1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Function import based on summaries.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/IPO/FunctionImport.h"
15 
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringSet.h"
19 #include "llvm/IR/AutoUpgrade.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IRReader/IRReader.h"
24 #include "llvm/Linker/Linker.h"
25 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
30 
31 #define DEBUG_TYPE "function-import"
32 
33 using namespace llvm;
34 
35 STATISTIC(NumImported, "Number of functions imported");
36 
37 /// Limit on instruction count of imported functions.
38 static cl::opt<unsigned> ImportInstrLimit(
39     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
40     cl::desc("Only import functions with less than N instructions"));
41 
42 static cl::opt<float>
43     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
44                       cl::Hidden, cl::value_desc("x"),
45                       cl::desc("As we import functions, multiply the "
46                                "`import-instr-limit` threshold by this factor "
47                                "before processing newly imported functions"));
48 
49 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
50                                   cl::desc("Print imported functions"));
51 
52 // Load lazily a module from \p FileName in \p Context.
53 static std::unique_ptr<Module> loadFile(const std::string &FileName,
54                                         LLVMContext &Context) {
55   SMDiagnostic Err;
56   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
57   // Metadata isn't loaded until functions are imported, to minimize
58   // the memory overhead.
59   std::unique_ptr<Module> Result =
60       getLazyIRFileModule(FileName, Err, Context,
61                           /* ShouldLazyLoadMetadata = */ true);
62   if (!Result) {
63     Err.print("function-import", errs());
64     report_fatal_error("Abort");
65   }
66 
67   return Result;
68 }
69 
70 namespace {
71 
72 /// Given a list of possible callee implementation for a call site, select one
73 /// that fits the \p Threshold.
74 ///
75 /// FIXME: select "best" instead of first that fits. But what is "best"?
76 /// - The smallest: more likely to be inlined.
77 /// - The one with the least outgoing edges (already well optimized).
78 /// - One from a module already being imported from in order to reduce the
79 ///   number of source modules parsed/linked.
80 /// - One that has PGO data attached.
81 /// - [insert you fancy metric here]
82 static const FunctionSummary *
83 selectCallee(const GlobalValueInfoList &CalleeInfoList, unsigned Threshold) {
84   auto It = llvm::find_if(
85       CalleeInfoList, [&](const std::unique_ptr<GlobalValueInfo> &GlobInfo) {
86         assert(GlobInfo->summary() &&
87                "We should not have a Global Info without summary");
88         auto *Summary = cast<FunctionSummary>(GlobInfo->summary());
89 
90         if (GlobalValue::isWeakAnyLinkage(Summary->linkage()))
91           return false;
92 
93         if (Summary->instCount() > Threshold)
94           return false;
95 
96         return true;
97       });
98   if (It == CalleeInfoList.end())
99     return nullptr;
100 
101   return cast<FunctionSummary>((*It)->summary());
102 }
103 
104 /// Return the summary for the function \p GUID that fits the \p Threshold, or
105 /// null if there's no match.
106 static const FunctionSummary *selectCallee(GlobalValue::GUID GUID,
107                                            unsigned Threshold,
108                                            const ModuleSummaryIndex &Index) {
109   auto CalleeInfoList = Index.findGlobalValueInfoList(GUID);
110   if (CalleeInfoList == Index.end()) {
111     return nullptr; // This function does not have a summary
112   }
113   return selectCallee(CalleeInfoList->second, Threshold);
114 }
115 
116 /// Return true if the global \p GUID is exported by module \p ExportModulePath.
117 static bool isGlobalExported(const ModuleSummaryIndex &Index,
118                              StringRef ExportModulePath,
119                              GlobalValue::GUID GUID) {
120   auto CalleeInfoList = Index.findGlobalValueInfoList(GUID);
121   if (CalleeInfoList == Index.end())
122     // This global does not have a summary, it is not part of the ThinLTO
123     // process
124     return false;
125   auto DefinedInCalleeModule = llvm::find_if(
126       CalleeInfoList->second,
127       [&](const std::unique_ptr<GlobalValueInfo> &GlobInfo) {
128         auto *Summary = GlobInfo->summary();
129         assert(Summary && "Unexpected GlobalValueInfo without summary");
130         return Summary->modulePath() == ExportModulePath;
131       });
132   return (DefinedInCalleeModule != CalleeInfoList->second.end());
133 }
134 
135 using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
136 
137 /// Compute the list of functions to import for a given caller. Mark these
138 /// imported functions and the symbols they reference in their source module as
139 /// exported from their source module.
140 static void computeImportForFunction(
141     StringRef ModulePath, const FunctionSummary &Summary,
142     const ModuleSummaryIndex &Index, unsigned Threshold,
143     const std::map<GlobalValue::GUID, FunctionSummary *> &DefinedFunctions,
144     SmallVectorImpl<EdgeInfo> &Worklist,
145     FunctionImporter::ImportMapTy &ImportsForModule,
146     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
147   for (auto &Edge : Summary.calls()) {
148     auto GUID = Edge.first;
149     DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
150 
151     if (DefinedFunctions.count(GUID)) {
152       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
153       continue;
154     }
155 
156     auto *CalleeSummary = selectCallee(GUID, Threshold, Index);
157     if (!CalleeSummary) {
158       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
159       continue;
160     }
161     assert(CalleeSummary->instCount() <= Threshold &&
162            "selectCallee() didn't honor the threshold");
163 
164     auto &ProcessedThreshold =
165         ImportsForModule[CalleeSummary->modulePath()][GUID];
166     /// Since the traversal of the call graph is DFS, we can revisit a function
167     /// a second time with a higher threshold. In this case, it is added back to
168     /// the worklist with the new threshold.
169     if (ProcessedThreshold && ProcessedThreshold > Threshold) {
170       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
171                    << ProcessedThreshold << "\n");
172       continue;
173     }
174     // Mark this function as imported in this module, with the current Threshold
175     ProcessedThreshold = Threshold;
176 
177     // Make exports in the source module.
178     auto ExportModulePath = CalleeSummary->modulePath();
179     auto ExportList = ExportLists[ExportModulePath];
180     ExportList.insert(GUID);
181     // Mark all functions and globals referenced by this function as exported to
182     // the outside if they are defined in the same source module.
183     for (auto &Edge : CalleeSummary->calls()) {
184       auto CalleeGUID = Edge.first;
185       if (isGlobalExported(Index, ExportModulePath, CalleeGUID))
186         ExportList.insert(CalleeGUID);
187     }
188     for (auto &GUID : CalleeSummary->refs()) {
189       if (isGlobalExported(Index, ExportModulePath, GUID))
190         ExportList.insert(GUID);
191     }
192 
193     // Insert the newly imported function to the worklist.
194     Worklist.push_back(std::make_pair(CalleeSummary, Threshold));
195   }
196 }
197 
198 /// Given the list of globals defined in a module, compute the list of imports
199 /// as well as the list of "exports", i.e. the list of symbols referenced from
200 /// another module (that may require promotion).
201 static void ComputeImportForModule(
202     StringRef ModulePath,
203     const std::map<GlobalValue::GUID, FunctionSummary *> &DefinedFunctions,
204     const ModuleSummaryIndex &Index,
205     FunctionImporter::ImportMapTy &ImportsForModule,
206     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
207   // Worklist contains the list of function imported in this module, for which
208   // we will analyse the callees and may import further down the callgraph.
209   SmallVector<EdgeInfo, 128> Worklist;
210 
211   // Populate the worklist with the import for the functions in the current
212   // module
213   for (auto &FuncInfo : DefinedFunctions) {
214     auto *Summary = FuncInfo.second;
215     DEBUG(dbgs() << "Initalize import for " << FuncInfo.first << "\n");
216     computeImportForFunction(ModulePath, *Summary, Index, ImportInstrLimit,
217                              DefinedFunctions, Worklist, ImportsForModule,
218                              ExportLists);
219   }
220 
221   while (!Worklist.empty()) {
222     auto FuncInfo = Worklist.pop_back_val();
223     auto *Summary = FuncInfo.first;
224     auto Threshold = FuncInfo.second;
225 
226     // Process the newly imported functions and add callees to the worklist.
227     // Adjust the threshold
228     Threshold = Threshold * ImportInstrFactor;
229 
230     computeImportForFunction(ModulePath, *Summary, Index, Threshold,
231                              DefinedFunctions, Worklist, ImportsForModule,
232                              ExportLists);
233   }
234 }
235 
236 } // anonymous namespace
237 
238 /// Compute all the import and export for every module in the Index.
239 void llvm::ComputeCrossModuleImport(
240     const ModuleSummaryIndex &Index,
241     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
242     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
243   auto ModuleCount = Index.modulePaths().size();
244 
245   // Collect for each module the list of function it defines.
246   // GUID -> Summary
247   StringMap<std::map<GlobalValue::GUID, FunctionSummary *>>
248       Module2FunctionInfoMap(ModuleCount);
249 
250   for (auto &GlobalList : Index) {
251     auto GUID = GlobalList.first;
252     for (auto &GlobInfo : GlobalList.second) {
253       auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobInfo->summary());
254       if (!Summary)
255         /// Ignore global variable, focus on functions
256         continue;
257       DEBUG(dbgs() << "Adding definition: Module '" << Summary->modulePath()
258                    << "' defines '" << GUID << "'\n");
259       Module2FunctionInfoMap[Summary->modulePath()][GUID] = Summary;
260     }
261   }
262 
263   // For each module that has function defined, compute the import/export lists.
264   for (auto &DefinedFunctions : Module2FunctionInfoMap) {
265     auto &ImportsForModule = ImportLists[DefinedFunctions.first()];
266     DEBUG(dbgs() << "Computing import for Module '" << DefinedFunctions.first()
267                  << "'\n");
268     ComputeImportForModule(DefinedFunctions.first(), DefinedFunctions.second,
269                            Index, ImportsForModule, ExportLists);
270   }
271 
272 #ifndef NDEBUG
273   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
274                << " modules:\n");
275   for (auto &ModuleImports : ImportLists) {
276     auto ModName = ModuleImports.first();
277     auto &Exports = ExportLists[ModName];
278     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
279                  << " functions. Imports from " << ModuleImports.second.size()
280                  << " modules.\n");
281     for (auto &Src : ModuleImports.second) {
282       auto SrcModName = Src.first();
283       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
284                    << SrcModName << "\n");
285     }
286   }
287 #endif
288 }
289 
290 // Automatically import functions in Module \p DestModule based on the summaries
291 // index.
292 //
293 bool FunctionImporter::importFunctions(
294     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
295   DEBUG(dbgs() << "Starting import for Module "
296                << DestModule.getModuleIdentifier() << "\n");
297   unsigned ImportedCount = 0;
298 
299   // Linker that will be used for importing function
300   Linker TheLinker(DestModule);
301   // Do the actual import of functions now, one Module at a time
302   std::set<StringRef> ModuleNameOrderedList;
303   for (auto &FunctionsToImportPerModule : ImportList) {
304     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
305   }
306   for (auto &Name : ModuleNameOrderedList) {
307     // Get the module for the import
308     const auto &FunctionsToImportPerModule = ImportList.find(Name);
309     assert(FunctionsToImportPerModule != ImportList.end());
310     std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
311     assert(&DestModule.getContext() == &SrcModule->getContext() &&
312            "Context mismatch");
313 
314     // If modules were created with lazy metadata loading, materialize it
315     // now, before linking it (otherwise this will be a noop).
316     SrcModule->materializeMetadata();
317     UpgradeDebugInfo(*SrcModule);
318 
319     auto &ImportGUIDs = FunctionsToImportPerModule->second;
320     // Find the globals to import
321     DenseSet<const GlobalValue *> GlobalsToImport;
322     for (auto &GV : *SrcModule) {
323       if (!GV.hasName())
324         continue;
325       auto GUID = GV.getGUID();
326       auto Import = ImportGUIDs.count(GUID);
327       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
328                    << GV.getName() << " from " << SrcModule->getSourceFileName()
329                    << "\n");
330       if (Import) {
331         GV.materialize();
332         GlobalsToImport.insert(&GV);
333       }
334     }
335     for (auto &GV : SrcModule->aliases()) {
336       if (!GV.hasName())
337         continue;
338       auto GUID = GV.getGUID();
339       auto Import = ImportGUIDs.count(GUID);
340       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
341                    << GV.getName() << " from " << SrcModule->getSourceFileName()
342                    << "\n");
343       if (Import) {
344         // Alias can't point to "available_externally". However when we import
345         // linkOnceODR the linkage does not change. So we import the alias
346         // and aliasee only in this case.
347         const GlobalObject *GO = GV.getBaseObject();
348         if (!GO->hasLinkOnceODRLinkage())
349           continue;
350         GV.materialize();
351         GlobalsToImport.insert(&GV);
352         GlobalsToImport.insert(GO);
353       }
354     }
355     for (auto &GV : SrcModule->globals()) {
356       if (!GV.hasName())
357         continue;
358       auto GUID = GV.getGUID();
359       auto Import = ImportGUIDs.count(GUID);
360       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
361                    << GV.getName() << " from " << SrcModule->getSourceFileName()
362                    << "\n");
363       if (Import) {
364         GV.materialize();
365         GlobalsToImport.insert(&GV);
366       }
367     }
368 
369     // Link in the specified functions.
370     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
371       return true;
372 
373     if (PrintImports) {
374       for (const auto *GV : GlobalsToImport)
375         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
376                << " from " << SrcModule->getSourceFileName() << "\n";
377     }
378 
379     if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
380                                &GlobalsToImport))
381       report_fatal_error("Function Import: link error");
382 
383     ImportedCount += GlobalsToImport.size();
384   }
385 
386   NumImported += ImportedCount;
387 
388   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
389                << DestModule.getModuleIdentifier() << "\n");
390   return ImportedCount;
391 }
392 
393 /// Summary file to use for function importing when using -function-import from
394 /// the command line.
395 static cl::opt<std::string>
396     SummaryFile("summary-file",
397                 cl::desc("The summary file to use for function importing."));
398 
399 static void diagnosticHandler(const DiagnosticInfo &DI) {
400   raw_ostream &OS = errs();
401   DiagnosticPrinterRawOStream DP(OS);
402   DI.print(DP);
403   OS << '\n';
404 }
405 
406 /// Parse the summary index out of an IR file and return the summary
407 /// index object if found, or nullptr if not.
408 static std::unique_ptr<ModuleSummaryIndex>
409 getModuleSummaryIndexForFile(StringRef Path, std::string &Error,
410                              DiagnosticHandlerFunction DiagnosticHandler) {
411   std::unique_ptr<MemoryBuffer> Buffer;
412   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
413       MemoryBuffer::getFile(Path);
414   if (std::error_code EC = BufferOrErr.getError()) {
415     Error = EC.message();
416     return nullptr;
417   }
418   Buffer = std::move(BufferOrErr.get());
419   ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
420       object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
421                                                    DiagnosticHandler);
422   if (std::error_code EC = ObjOrErr.getError()) {
423     Error = EC.message();
424     return nullptr;
425   }
426   return (*ObjOrErr)->takeIndex();
427 }
428 
429 namespace {
430 /// Pass that performs cross-module function import provided a summary file.
431 class FunctionImportPass : public ModulePass {
432   /// Optional module summary index to use for importing, otherwise
433   /// the summary-file option must be specified.
434   const ModuleSummaryIndex *Index;
435 
436 public:
437   /// Pass identification, replacement for typeid
438   static char ID;
439 
440   /// Specify pass name for debug output
441   const char *getPassName() const override {
442     return "Function Importing";
443   }
444 
445   explicit FunctionImportPass(const ModuleSummaryIndex *Index = nullptr)
446       : ModulePass(ID), Index(Index) {}
447 
448   bool runOnModule(Module &M) override {
449     if (SummaryFile.empty() && !Index)
450       report_fatal_error("error: -function-import requires -summary-file or "
451                          "file from frontend\n");
452     std::unique_ptr<ModuleSummaryIndex> IndexPtr;
453     if (!SummaryFile.empty()) {
454       if (Index)
455         report_fatal_error("error: -summary-file and index from frontend\n");
456       std::string Error;
457       IndexPtr =
458           getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
459       if (!IndexPtr) {
460         errs() << "Error loading file '" << SummaryFile << "': " << Error
461                << "\n";
462         return false;
463       }
464       Index = IndexPtr.get();
465     }
466 
467     // First step is collecting the import/export lists
468     // The export list is not used yet, but could limit the amount of renaming
469     // performed in renameModuleForThinLTO()
470     StringMap<FunctionImporter::ImportMapTy> ImportLists;
471     StringMap<FunctionImporter::ExportSetTy> ExportLists;
472     ComputeCrossModuleImport(*Index, ImportLists, ExportLists);
473     auto &ImportList = ImportLists[M.getModuleIdentifier()];
474 
475     // Next we need to promote to global scope and rename any local values that
476     // are potentially exported to other modules.
477     if (renameModuleForThinLTO(M, *Index, nullptr)) {
478       errs() << "Error renaming module\n";
479       return false;
480     }
481 
482     // Perform the import now.
483     auto ModuleLoader = [&M](StringRef Identifier) {
484       return loadFile(Identifier, M.getContext());
485     };
486     FunctionImporter Importer(*Index, ModuleLoader);
487     return Importer.importFunctions(M, ImportList);
488   }
489 };
490 } // anonymous namespace
491 
492 char FunctionImportPass::ID = 0;
493 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
494                       "Summary Based Function Import", false, false)
495 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
496                     "Summary Based Function Import", false, false)
497 
498 namespace llvm {
499 Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
500   return new FunctionImportPass(Index);
501 }
502 }
503