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     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
142     unsigned Threshold,
143     const std::map<GlobalValue::GUID, FunctionSummary *> &DefinedFunctions,
144     SmallVectorImpl<EdgeInfo> &Worklist,
145     FunctionImporter::ImportMapTy &ImportsForModule,
146     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
147   for (auto &Edge : Summary.calls()) {
148     auto GUID = Edge.first.getGUID();
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     if (ExportLists) {
180       auto &ExportList = (*ExportLists)[ExportModulePath];
181       ExportList.insert(GUID);
182       // Mark all functions and globals referenced by this function as exported
183       // to the outside if they are defined in the same source module.
184       for (auto &Edge : CalleeSummary->calls()) {
185         auto CalleeGUID = Edge.first.getGUID();
186         if (isGlobalExported(Index, ExportModulePath, CalleeGUID))
187           ExportList.insert(CalleeGUID);
188       }
189       for (auto &Ref : CalleeSummary->refs()) {
190         auto GUID = Ref.getGUID();
191         if (isGlobalExported(Index, ExportModulePath, GUID))
192           ExportList.insert(GUID);
193       }
194     }
195 
196     // Insert the newly imported function to the worklist.
197     Worklist.push_back(std::make_pair(CalleeSummary, Threshold));
198   }
199 }
200 
201 /// Given the list of globals defined in a module, compute the list of imports
202 /// as well as the list of "exports", i.e. the list of symbols referenced from
203 /// another module (that may require promotion).
204 static void ComputeImportForModule(
205     const std::map<GlobalValue::GUID, FunctionSummary *> &DefinedFunctions,
206     const ModuleSummaryIndex &Index,
207     FunctionImporter::ImportMapTy &ImportsForModule,
208     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
209   // Worklist contains the list of function imported in this module, for which
210   // we will analyse the callees and may import further down the callgraph.
211   SmallVector<EdgeInfo, 128> Worklist;
212 
213   // Populate the worklist with the import for the functions in the current
214   // module
215   for (auto &FuncInfo : DefinedFunctions) {
216     auto *Summary = FuncInfo.second;
217     DEBUG(dbgs() << "Initalize import for " << FuncInfo.first << "\n");
218     computeImportForFunction(*Summary, Index, ImportInstrLimit,
219                              DefinedFunctions, Worklist, ImportsForModule,
220                              ExportLists);
221   }
222 
223   while (!Worklist.empty()) {
224     auto FuncInfo = Worklist.pop_back_val();
225     auto *Summary = FuncInfo.first;
226     auto Threshold = FuncInfo.second;
227 
228     // Process the newly imported functions and add callees to the worklist.
229     // Adjust the threshold
230     Threshold = Threshold * ImportInstrFactor;
231 
232     computeImportForFunction(*Summary, Index, Threshold, DefinedFunctions,
233                              Worklist, ImportsForModule, ExportLists);
234   }
235 }
236 
237 } // anonymous namespace
238 
239 /// Compute all the import and export for every module using the Index.
240 void llvm::ComputeCrossModuleImport(
241     const ModuleSummaryIndex &Index,
242     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
243     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
244   auto ModuleCount = Index.modulePaths().size();
245 
246   // Collect for each module the list of function it defines.
247   // GUID -> Summary
248   StringMap<std::map<GlobalValue::GUID, FunctionSummary *>>
249       Module2FunctionInfoMap(ModuleCount);
250 
251   for (auto &GlobalList : Index) {
252     auto GUID = GlobalList.first;
253     for (auto &GlobInfo : GlobalList.second) {
254       auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobInfo->summary());
255       if (!Summary)
256         /// Ignore global variable, focus on functions
257         continue;
258       DEBUG(dbgs() << "Adding definition: Module '" << Summary->modulePath()
259                    << "' defines '" << GUID << "'\n");
260       Module2FunctionInfoMap[Summary->modulePath()][GUID] = Summary;
261     }
262   }
263 
264   // For each module that has function defined, compute the import/export lists.
265   for (auto &DefinedFunctions : Module2FunctionInfoMap) {
266     auto &ImportsForModule = ImportLists[DefinedFunctions.first()];
267     DEBUG(dbgs() << "Computing import for Module '" << DefinedFunctions.first()
268                  << "'\n");
269     ComputeImportForModule(DefinedFunctions.second, Index, ImportsForModule,
270                            &ExportLists);
271   }
272 
273 #ifndef NDEBUG
274   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
275                << " modules:\n");
276   for (auto &ModuleImports : ImportLists) {
277     auto ModName = ModuleImports.first();
278     auto &Exports = ExportLists[ModName];
279     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
280                  << " functions. Imports from " << ModuleImports.second.size()
281                  << " modules.\n");
282     for (auto &Src : ModuleImports.second) {
283       auto SrcModName = Src.first();
284       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
285                    << SrcModName << "\n");
286     }
287   }
288 #endif
289 }
290 
291 /// Compute all the imports for the given module in the Index.
292 void llvm::ComputeCrossModuleImportForModule(
293     StringRef ModulePath, const ModuleSummaryIndex &Index,
294     FunctionImporter::ImportMapTy &ImportList) {
295 
296   // Collect the list of functions this module defines.
297   // GUID -> Summary
298   std::map<GlobalValue::GUID, FunctionSummary *> FunctionInfoMap;
299   Index.collectDefinedFunctionsForModule(ModulePath, FunctionInfoMap);
300 
301   // Compute the import list for this module.
302   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
303   ComputeImportForModule(FunctionInfoMap, Index, ImportList);
304 
305 #ifndef NDEBUG
306   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
307                << ImportList.size() << " modules.\n");
308   for (auto &Src : ImportList) {
309     auto SrcModName = Src.first();
310     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
311                  << SrcModName << "\n");
312   }
313 #endif
314 }
315 
316 // Automatically import functions in Module \p DestModule based on the summaries
317 // index.
318 //
319 bool FunctionImporter::importFunctions(
320     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
321   DEBUG(dbgs() << "Starting import for Module "
322                << DestModule.getModuleIdentifier() << "\n");
323   unsigned ImportedCount = 0;
324 
325   // Linker that will be used for importing function
326   Linker TheLinker(DestModule);
327   // Do the actual import of functions now, one Module at a time
328   std::set<StringRef> ModuleNameOrderedList;
329   for (auto &FunctionsToImportPerModule : ImportList) {
330     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
331   }
332   for (auto &Name : ModuleNameOrderedList) {
333     // Get the module for the import
334     const auto &FunctionsToImportPerModule = ImportList.find(Name);
335     assert(FunctionsToImportPerModule != ImportList.end());
336     std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
337     assert(&DestModule.getContext() == &SrcModule->getContext() &&
338            "Context mismatch");
339 
340     // If modules were created with lazy metadata loading, materialize it
341     // now, before linking it (otherwise this will be a noop).
342     SrcModule->materializeMetadata();
343     UpgradeDebugInfo(*SrcModule);
344 
345     auto &ImportGUIDs = FunctionsToImportPerModule->second;
346     // Find the globals to import
347     DenseSet<const GlobalValue *> GlobalsToImport;
348     for (auto &GV : *SrcModule) {
349       if (!GV.hasName())
350         continue;
351       auto GUID = GV.getGUID();
352       auto Import = ImportGUIDs.count(GUID);
353       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
354                    << GV.getName() << " from " << SrcModule->getSourceFileName()
355                    << "\n");
356       if (Import) {
357         GV.materialize();
358         GlobalsToImport.insert(&GV);
359       }
360     }
361     for (auto &GV : SrcModule->aliases()) {
362       if (!GV.hasName())
363         continue;
364       auto GUID = GV.getGUID();
365       auto Import = ImportGUIDs.count(GUID);
366       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
367                    << GV.getName() << " from " << SrcModule->getSourceFileName()
368                    << "\n");
369       if (Import) {
370         // Alias can't point to "available_externally". However when we import
371         // linkOnceODR the linkage does not change. So we import the alias
372         // and aliasee only in this case.
373         const GlobalObject *GO = GV.getBaseObject();
374         if (!GO->hasLinkOnceODRLinkage())
375           continue;
376         GV.materialize();
377         GlobalsToImport.insert(&GV);
378         GlobalsToImport.insert(GO);
379       }
380     }
381     for (auto &GV : SrcModule->globals()) {
382       if (!GV.hasName())
383         continue;
384       auto GUID = GV.getGUID();
385       auto Import = ImportGUIDs.count(GUID);
386       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
387                    << GV.getName() << " from " << SrcModule->getSourceFileName()
388                    << "\n");
389       if (Import) {
390         GV.materialize();
391         GlobalsToImport.insert(&GV);
392       }
393     }
394 
395     // Link in the specified functions.
396     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
397       return true;
398 
399     if (PrintImports) {
400       for (const auto *GV : GlobalsToImport)
401         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
402                << " from " << SrcModule->getSourceFileName() << "\n";
403     }
404 
405     if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
406                                &GlobalsToImport))
407       report_fatal_error("Function Import: link error");
408 
409     ImportedCount += GlobalsToImport.size();
410   }
411 
412   NumImported += ImportedCount;
413 
414   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
415                << DestModule.getModuleIdentifier() << "\n");
416   return ImportedCount;
417 }
418 
419 /// Summary file to use for function importing when using -function-import from
420 /// the command line.
421 static cl::opt<std::string>
422     SummaryFile("summary-file",
423                 cl::desc("The summary file to use for function importing."));
424 
425 static void diagnosticHandler(const DiagnosticInfo &DI) {
426   raw_ostream &OS = errs();
427   DiagnosticPrinterRawOStream DP(OS);
428   DI.print(DP);
429   OS << '\n';
430 }
431 
432 /// Parse the summary index out of an IR file and return the summary
433 /// index object if found, or nullptr if not.
434 static std::unique_ptr<ModuleSummaryIndex>
435 getModuleSummaryIndexForFile(StringRef Path, std::string &Error,
436                              DiagnosticHandlerFunction DiagnosticHandler) {
437   std::unique_ptr<MemoryBuffer> Buffer;
438   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
439       MemoryBuffer::getFile(Path);
440   if (std::error_code EC = BufferOrErr.getError()) {
441     Error = EC.message();
442     return nullptr;
443   }
444   Buffer = std::move(BufferOrErr.get());
445   ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
446       object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
447                                                    DiagnosticHandler);
448   if (std::error_code EC = ObjOrErr.getError()) {
449     Error = EC.message();
450     return nullptr;
451   }
452   return (*ObjOrErr)->takeIndex();
453 }
454 
455 namespace {
456 /// Pass that performs cross-module function import provided a summary file.
457 class FunctionImportPass : public ModulePass {
458   /// Optional module summary index to use for importing, otherwise
459   /// the summary-file option must be specified.
460   const ModuleSummaryIndex *Index;
461 
462 public:
463   /// Pass identification, replacement for typeid
464   static char ID;
465 
466   /// Specify pass name for debug output
467   const char *getPassName() const override {
468     return "Function Importing";
469   }
470 
471   explicit FunctionImportPass(const ModuleSummaryIndex *Index = nullptr)
472       : ModulePass(ID), Index(Index) {}
473 
474   bool runOnModule(Module &M) override {
475     if (SummaryFile.empty() && !Index)
476       report_fatal_error("error: -function-import requires -summary-file or "
477                          "file from frontend\n");
478     std::unique_ptr<ModuleSummaryIndex> IndexPtr;
479     if (!SummaryFile.empty()) {
480       if (Index)
481         report_fatal_error("error: -summary-file and index from frontend\n");
482       std::string Error;
483       IndexPtr =
484           getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
485       if (!IndexPtr) {
486         errs() << "Error loading file '" << SummaryFile << "': " << Error
487                << "\n";
488         return false;
489       }
490       Index = IndexPtr.get();
491     }
492 
493     // First step is collecting the import list.
494     FunctionImporter::ImportMapTy ImportList;
495     ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
496                                       ImportList);
497 
498     // Next we need to promote to global scope and rename any local values that
499     // are potentially exported to other modules.
500     if (renameModuleForThinLTO(M, *Index, nullptr)) {
501       errs() << "Error renaming module\n";
502       return false;
503     }
504 
505     // Perform the import now.
506     auto ModuleLoader = [&M](StringRef Identifier) {
507       return loadFile(Identifier, M.getContext());
508     };
509     FunctionImporter Importer(*Index, ModuleLoader);
510     return Importer.importFunctions(M, ImportList);
511   }
512 };
513 } // anonymous namespace
514 
515 char FunctionImportPass::ID = 0;
516 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
517                       "Summary Based Function Import", false, false)
518 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
519                     "Summary Based Function Import", false, false)
520 
521 namespace llvm {
522 Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
523   return new FunctionImportPass(Index);
524 }
525 }
526