LLVM 18.0.0git
FunctionImport.h
Go to the documentation of this file.
1//===- llvm/Transforms/IPO/FunctionImport.h - ThinLTO importing -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_TRANSFORMS_IPO_FUNCTIONIMPORT_H
10#define LLVM_TRANSFORMS_IPO_FUNCTIONIMPORT_H
11
12#include "llvm/ADT/DenseSet.h"
13#include "llvm/ADT/StringMap.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/IR/GlobalValue.h"
17#include "llvm/IR/PassManager.h"
18#include "llvm/Support/Error.h"
19#include <functional>
20#include <map>
21#include <memory>
22#include <string>
23#include <system_error>
24#include <unordered_set>
25#include <utility>
26
27namespace llvm {
28
29class Module;
30
31/// The function importer is automatically importing function from other modules
32/// based on the provided summary informations.
34public:
35 /// Set of functions to import from a source module. Each entry is a set
36 /// containing all the GUIDs of all functions to import for a source module.
37 using FunctionsToImportTy = std::unordered_set<GlobalValue::GUID>;
38
39 /// The different reasons selectCallee will chose not to import a
40 /// candidate.
43 // We can encounter a global variable instead of a function in rare
44 // situations with SamplePGO. See comments where this failure type is
45 // set for more details.
47 // Found to be globally dead, so we don't bother importing.
49 // Instruction count over the current threshold.
51 // Don't import something with interposable linkage as we can't inline it
52 // anyway.
54 // Generally we won't end up failing due to this reason, as we expect
55 // to find at least one summary for the GUID that is global or a local
56 // in the referenced module for direct calls.
58 // This corresponds to the NotEligibleToImport being set on the summary,
59 // which can happen in a few different cases (e.g. local that can't be
60 // renamed or promoted because it is referenced on a llvm*.used variable).
62 // This corresponds to NoInline being set on the function summary,
63 // which will happen if it is known that the inliner will not be able
64 // to inline the function (e.g. it is marked with a NoInline attribute).
66 };
67
68 /// Information optionally tracked for candidates the importer decided
69 /// not to import. Used for optional stat printing.
71 // The ValueInfo corresponding to the candidate. We save an index hash
72 // table lookup for each GUID by stashing this here.
74 // The maximum call edge hotness for all failed imports of this candidate.
76 // most recent reason for failing to import (doesn't necessarily correspond
77 // to the attempt with the maximum hotness).
79 // The number of times we tried to import candidate but failed.
80 unsigned Attempts;
84 };
85
86 /// Map of callee GUID considered for import into a given module to a pair
87 /// consisting of the largest threshold applied when deciding whether to
88 /// import it and, if we decided to import, a pointer to the summary instance
89 /// imported. If we decided not to import, the summary will be nullptr.
92 std::tuple<unsigned, const GlobalValueSummary *,
93 std::unique_ptr<ImportFailureInfo>>>;
94
95 /// The map contains an entry for every module to import from, the key being
96 /// the module identifier to pass to the ModuleLoader. The value is the set of
97 /// functions to import. The module identifier strings must be owned
98 /// elsewhere, typically by the in-memory ModuleSummaryIndex the importing
99 /// decisions are made from (the module path for each summary is owned by the
100 /// index's module path string table).
102
103 /// The set contains an entry for every global value the module exports.
105
106 /// A function of this type is used to load modules referenced by the index.
108 std::function<Expected<std::unique_ptr<Module>>(StringRef Identifier)>;
109
110 /// Create a Function Importer.
112 bool ClearDSOLocalOnDeclarations)
113 : Index(Index), ModuleLoader(std::move(ModuleLoader)),
114 ClearDSOLocalOnDeclarations(ClearDSOLocalOnDeclarations) {}
115
116 /// Import functions in Module \p M based on the supplied import list.
117 Expected<bool> importFunctions(Module &M, const ImportMapTy &ImportList);
118
119private:
120 /// The summaries index used to trigger importing.
122
123 /// Factory function to load a Module for a given identifier
124 ModuleLoaderTy ModuleLoader;
125
126 /// See the comment of ClearDSOLocalOnDeclarations in
127 /// Utils/FunctionImportUtils.h.
128 bool ClearDSOLocalOnDeclarations;
129};
130
131/// The function importing pass
132class FunctionImportPass : public PassInfoMixin<FunctionImportPass> {
133public:
135};
136
137/// Compute all the imports and exports for every module in the Index.
138///
139/// \p ModuleToDefinedGVSummaries contains for each Module a map
140/// (GUID -> Summary) for every global defined in the module.
141///
142/// \p isPrevailing is a callback that will be called with a global value's GUID
143/// and summary and should return whether the module corresponding to the
144/// summary contains the linker-prevailing copy of that value.
145///
146/// \p ImportLists will be populated with an entry for every Module we are
147/// importing into. This entry is itself a map that can be passed to
148/// FunctionImporter::importFunctions() above (see description there).
149///
150/// \p ExportLists contains for each Module the set of globals (GUID) that will
151/// be imported by another module, or referenced by such a function. I.e. this
152/// is the set of globals that need to be promoted/renamed appropriately.
153///
154/// The module identifier strings that are the keys of the above two maps
155/// are owned by the in-memory ModuleSummaryIndex the importing decisions
156/// are made from (the module path for each summary is owned by the index's
157/// module path string table).
160 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
162 isPrevailing,
165
166/// PrevailingType enum used as a return type of callback passed
167/// to computeDeadSymbolsAndUpdateIndirectCalls. Yes and No values used when
168/// status explicitly set by symbols resolution, otherwise status is Unknown.
169enum class PrevailingType { Yes, No, Unknown };
170
171/// Update call edges for indirect calls to local functions added from
172/// SamplePGO when needed. Normally this is done during
173/// computeDeadSymbolsAndUpdateIndirectCalls, but can be called standalone
174/// when that is not called (e.g. during testing).
175void updateIndirectCalls(ModuleSummaryIndex &Index);
176
177/// Compute all the symbols that are "dead": i.e these that can't be reached
178/// in the graph from any of the given symbols listed in
179/// \p GUIDPreservedSymbols. Non-prevailing symbols are symbols without a
180/// prevailing copy anywhere in IR and are normally dead, \p isPrevailing
181/// predicate returns status of symbol.
182/// Also update call edges for indirect calls to local functions added from
183/// SamplePGO when needed.
185 ModuleSummaryIndex &Index,
186 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
187 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing);
188
189/// Compute dead symbols and run constant propagation in combined index
190/// after that.
192 ModuleSummaryIndex &Index,
193 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
194 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
195 bool ImportEnabled);
196
197/// Converts value \p GV to declaration, or replaces with a declaration if
198/// it is an alias. Returns true if converted, false if replaced.
199bool convertToDeclaration(GlobalValue &GV);
200
201/// Compute the set of summaries needed for a ThinLTO backend compilation of
202/// \p ModulePath.
203//
204/// This includes summaries from that module (in case any global summary based
205/// optimizations were recorded) and from any definitions in other modules that
206/// should be imported.
207//
208/// \p ModuleToSummariesForIndex will be populated with the needed summaries
209/// from each required module path. Use a std::map instead of StringMap to get
210/// stable order for bitcode emission.
212 StringRef ModulePath,
213 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
214 const FunctionImporter::ImportMapTy &ImportList,
215 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex);
216
217/// Emit into \p OutputFilename the files module \p ModulePath will import from.
218std::error_code EmitImportsFiles(
219 StringRef ModulePath, StringRef OutputFilename,
220 const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex);
221
222/// Based on the information recorded in the summaries during global
223/// summary-based analysis:
224/// 1. Resolve prevailing symbol linkages and constrain visibility (CanAutoHide
225/// and consider visibility from other definitions for ELF) in \p TheModule
226/// 2. (optional) Apply propagated function attributes to \p TheModule if
227/// PropagateAttrs is true
228void thinLTOFinalizeInModule(Module &TheModule,
229 const GVSummaryMapTy &DefinedGlobals,
230 bool PropagateAttrs);
231
232/// Internalize \p TheModule based on the information recorded in the summaries
233/// during global summary-based analysis.
234void thinLTOInternalizeModule(Module &TheModule,
235 const GVSummaryMapTy &DefinedGlobals);
236
237} // end namespace llvm
238
239#endif // LLVM_TRANSFORMS_IPO_FUNCTIONIMPORT_H
This file defines the StringMap class.
This file defines the DenseSet and SmallDenseSet classes.
Machine Check Debug Module
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
static cl::opt< bool > PropagateAttrs("propagate-attrs", cl::init(true), cl::Hidden, cl::desc("Propagate attributes in index"))
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
This header defines various interfaces for pass management in LLVM.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
Tagged union holding either a T or a Error.
Definition: Error.h:474
The function importing pass.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
The function importer is automatically importing function from other modules based on the provided su...
Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
DenseMap< StringRef, FunctionsToImportTy > ImportMapTy
The map contains an entry for every module to import from, the key being the module identifier to pas...
std::unordered_set< GlobalValue::GUID > FunctionsToImportTy
Set of functions to import from a source module.
FunctionImporter(const ModuleSummaryIndex &Index, ModuleLoaderTy ModuleLoader, bool ClearDSOLocalOnDeclarations)
Create a Function Importer.
ImportFailureReason
The different reasons selectCallee will chose not to import a candidate.
std::function< Expected< std::unique_ptr< Module > >(StringRef Identifier)> ModuleLoaderTy
A function of this type is used to load modules referenced by the index.
Function and variable summary information to aid decisions and implementation of importing.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:583
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
An efficient, type-erasing, non-owning reference to a callable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, DenseMap< StringRef, FunctionImporter::ImportMapTy > &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
std::error_code EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
void computeDeadSymbolsAndUpdateIndirectCalls(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing)
Compute all the symbols that are "dead": i.e these that can't be reached in the graph from any of the...
void gatherImportedSummariesForModule(StringRef ModulePath, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
void updateIndirectCalls(ModuleSummaryIndex &Index)
Update call edges for indirect calls to local functions added from SamplePGO when needed.
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1854
PrevailingType
PrevailingType enum used as a return type of callback passed to computeDeadSymbolsAndUpdateIndirectCa...
void computeDeadSymbolsWithConstProp(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing, bool ImportEnabled)
Compute dead symbols and run constant propagation in combined index after that.
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)
Based on the information recorded in the summaries during global summary-based analysis:
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Information optionally tracked for candidates the importer decided not to import.
ImportFailureInfo(ValueInfo VI, CalleeInfo::HotnessType MaxHotness, ImportFailureReason Reason, unsigned Attempts)
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:371
Struct that holds a reference to a particular GUID in a global value summary.