1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Function import based on summaries.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/IPO/FunctionImport.h"
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IRReader/IRReader.h"
22 #include "llvm/Linker/Linker.h"
23 #include "llvm/Object/FunctionIndexObjectFile.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/SourceMgr.h"
32 #define DEBUG_TYPE "function-import"
34 /// Limit on instruction count of imported functions.
35 static cl::opt<unsigned> ImportInstrLimit(
36 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
37 cl::desc("Only import functions with less than N instructions"));
39 // Load lazily a module from \p FileName in \p Context.
40 static std::unique_ptr<Module> loadFile(const std::string &FileName,
41 LLVMContext &Context) {
43 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
44 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
46 Err.print("function-import", errs());
50 Result->materializeMetadata();
51 UpgradeDebugInfo(*Result);
57 /// Helper to load on demand a Module from file and cache it for subsequent
58 /// queries. It can be used with the FunctionImporter.
59 class ModuleLazyLoaderCache {
60 /// Cache of lazily loaded module for import.
61 StringMap<std::unique_ptr<Module>> ModuleMap;
63 /// Retrieve a Module from the cache or lazily load it on demand.
64 std::function<std::unique_ptr<Module>(StringRef FileName)> createLazyModule;
67 /// Create the loader, Module will be initialized in \p Context.
68 ModuleLazyLoaderCache(std::function<
69 std::unique_ptr<Module>(StringRef FileName)> createLazyModule)
70 : createLazyModule(createLazyModule) {}
72 /// Retrieve a Module from the cache or lazily load it on demand.
73 Module &operator()(StringRef FileName);
75 std::unique_ptr<Module> takeModule(StringRef FileName) {
76 auto I = ModuleMap.find(FileName);
77 assert(I != ModuleMap.end());
78 std::unique_ptr<Module> Ret = std::move(I->second);
84 // Get a Module for \p FileName from the cache, or load it lazily.
85 Module &ModuleLazyLoaderCache::operator()(StringRef Identifier) {
86 auto &Module = ModuleMap[Identifier];
88 Module = createLazyModule(Identifier);
91 } // anonymous namespace
93 /// Walk through the instructions in \p F looking for external
94 /// calls not already in the \p CalledFunctions set. If any are
95 /// found they are added to the \p Worklist for importing.
96 static void findExternalCalls(const Module &DestModule, Function &F,
97 const FunctionInfoIndex &Index,
98 StringSet<> &CalledFunctions,
99 SmallVector<StringRef, 64> &Worklist) {
100 // We need to suffix internal function calls imported from other modules,
101 // prepare the suffix ahead of time.
103 if (F.getParent() != &DestModule)
106 Twine(Index.getModuleId(F.getParent()->getModuleIdentifier()))).str();
110 if (isa<CallInst>(I)) {
111 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
112 // Insert any new external calls that have not already been
113 // added to set/worklist.
114 if (!CalledFunction || !CalledFunction->hasName())
116 // Ignore intrinsics early
117 if (CalledFunction->isIntrinsic()) {
118 assert(CalledFunction->getIntrinsicID() != 0);
121 auto ImportedName = CalledFunction->getName();
122 auto Renamed = (ImportedName + Suffix).str();
123 // Rename internal functions
124 if (CalledFunction->hasInternalLinkage()) {
125 ImportedName = Renamed;
127 auto It = CalledFunctions.insert(ImportedName);
129 // This is a call to a function we already considered, skip.
132 // Ignore functions already present in the destination module
133 auto *SrcGV = DestModule.getNamedValue(ImportedName);
135 assert(isa<Function>(SrcGV) && "Name collision during import");
136 if (!cast<Function>(SrcGV)->isDeclaration()) {
137 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Ignoring "
138 << ImportedName << " already in DestinationModule\n");
143 Worklist.push_back(It.first->getKey());
144 DEBUG(dbgs() << DestModule.getModuleIdentifier()
145 << ": Adding callee for : " << ImportedName << " : "
146 << F.getName() << "\n");
152 // Helper function: given a worklist and an index, will process all the worklist
153 // and decide what to import based on the summary information.
155 // Nothing is actually imported, functions are materialized in their source
156 // module and analyzed there.
158 // \p ModuleToFunctionsToImportMap is filled with the set of Function to import
160 static void GetImportList(Module &DestModule,
161 SmallVector<StringRef, 64> &Worklist,
162 StringSet<> &CalledFunctions,
163 std::map<StringRef, DenseSet<const GlobalValue *>>
164 &ModuleToFunctionsToImportMap,
165 const FunctionInfoIndex &Index,
166 ModuleLazyLoaderCache &ModuleLoaderCache) {
167 while (!Worklist.empty()) {
168 auto CalledFunctionName = Worklist.pop_back_val();
169 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Process import for "
170 << CalledFunctionName << "\n");
172 // Try to get a summary for this function call.
173 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
174 if (InfoList == Index.end()) {
175 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": No summary for "
176 << CalledFunctionName << " Ignoring.\n");
179 assert(!InfoList->second.empty() && "No summary, error at import?");
181 // Comdat can have multiple entries, FIXME: what do we do with them?
182 auto &Info = InfoList->second[0];
183 assert(Info && "Nullptr in list, error importing summaries?\n");
185 auto *Summary = Info->functionSummary();
187 // FIXME: in case we are lazyloading summaries, we can do it now.
188 DEBUG(dbgs() << DestModule.getModuleIdentifier()
189 << ": Missing summary for " << CalledFunctionName
190 << ", error at import?\n");
191 llvm_unreachable("Missing summary");
194 if (Summary->instCount() > ImportInstrLimit) {
195 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Skip import of "
196 << CalledFunctionName << " with " << Summary->instCount()
197 << " instructions (limit " << ImportInstrLimit << ")\n");
201 // Get the module path from the summary.
202 auto ModuleIdentifier = Summary->modulePath();
203 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Importing "
204 << CalledFunctionName << " from " << ModuleIdentifier << "\n");
206 auto &SrcModule = ModuleLoaderCache(ModuleIdentifier);
208 // The function that we will import!
209 GlobalValue *SGV = SrcModule.getNamedValue(CalledFunctionName);
212 // The destination module is referencing function using their renamed name
213 // when importing a function that was originally local in the source
214 // module. The source module we have might not have been renamed so we try
215 // to remove the suffix added during the renaming to recover the original
216 // name in the source module.
217 std::pair<StringRef, StringRef> Split =
218 CalledFunctionName.split(".llvm.");
219 SGV = SrcModule.getNamedValue(Split.first);
220 assert(SGV && "Can't find function to import in source module");
223 report_fatal_error(Twine("Can't load function '") + CalledFunctionName +
224 "' in Module '" + SrcModule.getModuleIdentifier() +
225 "', error in the summary?\n");
228 Function *F = dyn_cast<Function>(SGV);
229 if (!F && isa<GlobalAlias>(SGV)) {
230 auto *SGA = dyn_cast<GlobalAlias>(SGV);
231 F = dyn_cast<Function>(SGA->getBaseObject());
232 CalledFunctionName = F->getName();
234 assert(F && "Imported Function is ... not a Function");
236 // We cannot import weak_any functions/aliases without possibly affecting
237 // the order they are seen and selected by the linker, changing program
239 if (SGV->hasWeakAnyLinkage()) {
240 DEBUG(dbgs() << DestModule.getModuleIdentifier()
241 << ": Ignoring import request for weak-any "
242 << (isa<Function>(SGV) ? "function " : "alias ")
243 << CalledFunctionName << " from "
244 << SrcModule.getModuleIdentifier() << "\n");
248 // Add the function to the import list
249 auto &Entry = ModuleToFunctionsToImportMap[SrcModule.getModuleIdentifier()];
252 // Process the newly imported functions and add callees to the worklist.
254 findExternalCalls(DestModule, *F, Index, CalledFunctions, Worklist);
258 // Automatically import functions in Module \p DestModule based on the summaries
261 // The current implementation imports every called functions that exists in the
263 bool FunctionImporter::importFunctions(Module &DestModule) {
264 DEBUG(dbgs() << "Starting import for Module "
265 << DestModule.getModuleIdentifier() << "\n");
266 unsigned ImportedCount = 0;
268 /// First step is collecting the called external functions.
269 StringSet<> CalledFunctions;
270 SmallVector<StringRef, 64> Worklist;
271 for (auto &F : DestModule) {
272 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
274 findExternalCalls(DestModule, F, Index, CalledFunctions, Worklist);
276 if (Worklist.empty())
279 /// Second step: for every call to an external function, try to import it.
281 // Linker that will be used for importing function
282 Linker TheLinker(DestModule);
284 // Map of Module -> List of Function to import from the Module
285 std::map<StringRef, DenseSet<const GlobalValue *>>
286 ModuleToFunctionsToImportMap;
288 // Analyze the summaries and get the list of functions to import by
289 // populating ModuleToFunctionsToImportMap
290 ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
291 GetImportList(DestModule, Worklist, CalledFunctions,
292 ModuleToFunctionsToImportMap, Index, ModuleLoaderCache);
293 assert(Worklist.empty() && "Worklist hasn't been flushed in GetImportList");
295 StringMap<std::unique_ptr<DenseMap<unsigned, MDNode *>>>
296 ModuleToTempMDValsMap;
298 // Do the actual import of functions now, one Module at a time
299 for (auto &FunctionsToImportPerModule : ModuleToFunctionsToImportMap) {
300 // Get the module for the import
301 auto &FunctionsToImport = FunctionsToImportPerModule.second;
302 std::unique_ptr<Module> SrcModule =
303 ModuleLoaderCache.takeModule(FunctionsToImportPerModule.first);
304 assert(&DestModule.getContext() == &SrcModule->getContext() &&
307 // Save the mapping of value ids to temporary metadata created when
308 // importing this function. If we have already imported from this module,
309 // add new temporary metadata to the existing mapping.
310 auto &TempMDVals = ModuleToTempMDValsMap[SrcModule->getModuleIdentifier()];
312 TempMDVals = llvm::make_unique<DenseMap<unsigned, MDNode *>>();
314 // Link in the specified functions.
315 if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
316 &Index, &FunctionsToImport, TempMDVals.get()))
317 report_fatal_error("Function Import: link error");
319 ImportedCount += FunctionsToImport.size();
322 // Now link in metadata for all modules from which we imported functions.
323 for (StringMapEntry<std::unique_ptr<DenseMap<unsigned, MDNode *>>> &SME :
324 ModuleToTempMDValsMap) {
325 // Load the specified source module.
326 auto &SrcModule = ModuleLoaderCache(SME.getKey());
328 // Link in all necessary metadata from this module.
329 if (TheLinker.linkInMetadata(SrcModule, SME.getValue().get()))
333 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
334 << DestModule.getModuleIdentifier() << "\n");
335 return ImportedCount;
338 /// Summary file to use for function importing when using -function-import from
339 /// the command line.
340 static cl::opt<std::string>
341 SummaryFile("summary-file",
342 cl::desc("The summary file to use for function importing."));
344 static void diagnosticHandler(const DiagnosticInfo &DI) {
345 raw_ostream &OS = errs();
346 DiagnosticPrinterRawOStream DP(OS);
351 /// Parse the function index out of an IR file and return the function
352 /// index object if found, or nullptr if not.
353 static std::unique_ptr<FunctionInfoIndex>
354 getFunctionIndexForFile(StringRef Path, std::string &Error,
355 DiagnosticHandlerFunction DiagnosticHandler) {
356 std::unique_ptr<MemoryBuffer> Buffer;
357 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
358 MemoryBuffer::getFile(Path);
359 if (std::error_code EC = BufferOrErr.getError()) {
360 Error = EC.message();
363 Buffer = std::move(BufferOrErr.get());
364 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
365 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
367 if (std::error_code EC = ObjOrErr.getError()) {
368 Error = EC.message();
371 return (*ObjOrErr)->takeIndex();
374 /// Pass that performs cross-module function import provided a summary file.
375 class FunctionImportPass : public ModulePass {
376 /// Optional function summary index to use for importing, otherwise
377 /// the summary-file option must be specified.
378 const FunctionInfoIndex *Index;
381 /// Pass identification, replacement for typeid
384 /// Specify pass name for debug output
385 const char *getPassName() const override {
386 return "Function Importing";
389 explicit FunctionImportPass(const FunctionInfoIndex *Index = nullptr)
390 : ModulePass(ID), Index(Index) {}
392 bool runOnModule(Module &M) override {
393 if (SummaryFile.empty() && !Index)
394 report_fatal_error("error: -function-import requires -summary-file or "
395 "file from frontend\n");
396 std::unique_ptr<FunctionInfoIndex> IndexPtr;
397 if (!SummaryFile.empty()) {
399 report_fatal_error("error: -summary-file and index from frontend\n");
401 IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
403 errs() << "Error loading file '" << SummaryFile << "': " << Error
407 Index = IndexPtr.get();
410 // Perform the import now.
411 auto ModuleLoader = [&M](StringRef Identifier) {
412 return loadFile(Identifier, M.getContext());
414 FunctionImporter Importer(*Index, ModuleLoader);
415 return Importer.importFunctions(M);
421 char FunctionImportPass::ID = 0;
422 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
423 "Summary Based Function Import", false, false)
424 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
425 "Summary Based Function Import", false, false)
428 Pass *createFunctionImportPass(const FunctionInfoIndex *Index = nullptr) {
429 return new FunctionImportPass(Index);