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/ADT/Triple.h"
20 #include "llvm/IR/AutoUpgrade.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IRReader/IRReader.h"
25 #include "llvm/Linker/Linker.h"
26 #include "llvm/Object/IRObjectFile.h"
27 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/SourceMgr.h"
31 #include "llvm/Transforms/IPO/Internalize.h"
32 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
33 
34 #define DEBUG_TYPE "function-import"
35 
36 using namespace llvm;
37 
38 STATISTIC(NumImported, "Number of functions imported");
39 
40 /// Limit on instruction count of imported functions.
41 static cl::opt<unsigned> ImportInstrLimit(
42     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
43     cl::desc("Only import functions with less than N instructions"));
44 
45 static cl::opt<float>
46     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
47                       cl::Hidden, cl::value_desc("x"),
48                       cl::desc("As we import functions, multiply the "
49                                "`import-instr-limit` threshold by this factor "
50                                "before processing newly imported functions"));
51 
52 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
53                                   cl::desc("Print imported functions"));
54 
55 // Temporary allows the function import pass to disable always linking
56 // referenced discardable symbols.
57 static cl::opt<bool>
58     DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
59                                                 cl::init(false), cl::Hidden);
60 
61 // Load lazily a module from \p FileName in \p Context.
62 static std::unique_ptr<Module> loadFile(const std::string &FileName,
63                                         LLVMContext &Context) {
64   SMDiagnostic Err;
65   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
66   // Metadata isn't loaded until functions are imported, to minimize
67   // the memory overhead.
68   std::unique_ptr<Module> Result =
69       getLazyIRFileModule(FileName, Err, Context,
70                           /* ShouldLazyLoadMetadata = */ true);
71   if (!Result) {
72     Err.print("function-import", errs());
73     report_fatal_error("Abort");
74   }
75 
76   return Result;
77 }
78 
79 namespace {
80 
81 // Return true if the Summary describes a GlobalValue that can be externally
82 // referenced, i.e. it does not need renaming (linkage is not local) or renaming
83 // is possible (does not have a section for instance).
84 static bool canBeExternallyReferenced(const GlobalValueSummary &Summary) {
85   if (!Summary.needsRenaming())
86     return true;
87 
88   if (Summary.hasSection())
89     // Can't rename a global that needs renaming if has a section.
90     return false;
91 
92   return true;
93 }
94 
95 // Return true if \p GUID describes a GlobalValue that can be externally
96 // referenced, i.e. it does not need renaming (linkage is not local) or
97 // renaming is possible (does not have a section for instance).
98 static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index,
99                                       GlobalValue::GUID GUID) {
100   auto Summaries = Index.findGlobalValueSummaryList(GUID);
101   if (Summaries == Index.end())
102     return true;
103   if (Summaries->second.size() != 1)
104     // If there are multiple globals with this GUID, then we know it is
105     // not a local symbol, and it is necessarily externally referenced.
106     return true;
107 
108   // We don't need to check for the module path, because if it can't be
109   // externally referenced and we call it, it is necessarilly in the same
110   // module
111   return canBeExternallyReferenced(**Summaries->second.begin());
112 }
113 
114 // Return true if the global described by \p Summary can be imported in another
115 // module.
116 static bool eligibleForImport(const ModuleSummaryIndex &Index,
117                               const GlobalValueSummary &Summary) {
118   if (!canBeExternallyReferenced(Summary))
119     // Can't import a global that needs renaming if has a section for instance.
120     // FIXME: we may be able to import it by copying it without promotion.
121     return false;
122 
123   // Check references (and potential calls) in the same module. If the current
124   // value references a global that can't be externally referenced it is not
125   // eligible for import.
126   bool AllRefsCanBeExternallyReferenced =
127       llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
128         return canBeExternallyReferenced(Index, VI.getGUID());
129       });
130   if (!AllRefsCanBeExternallyReferenced)
131     return false;
132 
133   if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
134     bool AllCallsCanBeExternallyReferenced = llvm::all_of(
135         FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
136           return canBeExternallyReferenced(Index, Edge.first.getGUID());
137         });
138     if (!AllCallsCanBeExternallyReferenced)
139       return false;
140   }
141   return true;
142 }
143 
144 /// Given a list of possible callee implementation for a call site, select one
145 /// that fits the \p Threshold.
146 ///
147 /// FIXME: select "best" instead of first that fits. But what is "best"?
148 /// - The smallest: more likely to be inlined.
149 /// - The one with the least outgoing edges (already well optimized).
150 /// - One from a module already being imported from in order to reduce the
151 ///   number of source modules parsed/linked.
152 /// - One that has PGO data attached.
153 /// - [insert you fancy metric here]
154 static const GlobalValueSummary *
155 selectCallee(const ModuleSummaryIndex &Index,
156              const GlobalValueSummaryList &CalleeSummaryList,
157              unsigned Threshold) {
158   auto It = llvm::find_if(
159       CalleeSummaryList,
160       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
161         auto *GVSummary = SummaryPtr.get();
162         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
163           // There is no point in importing these, we can't inline them
164           return false;
165         if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
166           GVSummary = &AS->getAliasee();
167           // Alias can't point to "available_externally". However when we import
168           // linkOnceODR the linkage does not change. So we import the alias
169           // and aliasee only in this case.
170           // FIXME: we should import alias as available_externally *function*,
171           // the destination module does need to know it is an alias.
172           if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
173             return false;
174         }
175 
176         auto *Summary = cast<FunctionSummary>(GVSummary);
177 
178         if (Summary->instCount() > Threshold)
179           return false;
180 
181         if (!eligibleForImport(Index, *Summary))
182           return false;
183 
184         return true;
185       });
186   if (It == CalleeSummaryList.end())
187     return nullptr;
188 
189   return cast<GlobalValueSummary>(It->get());
190 }
191 
192 /// Return the summary for the function \p GUID that fits the \p Threshold, or
193 /// null if there's no match.
194 static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
195                                               unsigned Threshold,
196                                               const ModuleSummaryIndex &Index) {
197   auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
198   if (CalleeSummaryList == Index.end())
199     return nullptr; // This function does not have a summary
200   return selectCallee(Index, CalleeSummaryList->second, Threshold);
201 }
202 
203 /// Mark the global \p GUID as export by module \p ExportModulePath if found in
204 /// this module. If it is a GlobalVariable, we also mark any referenced global
205 /// in the current module as exported.
206 static void exportGlobalInModule(const ModuleSummaryIndex &Index,
207                                  StringRef ExportModulePath,
208                                  GlobalValue::GUID GUID,
209                                  FunctionImporter::ExportSetTy &ExportList) {
210   auto FindGlobalSummaryInModule =
211       [&](GlobalValue::GUID GUID) -> GlobalValueSummary *{
212         auto SummaryList = Index.findGlobalValueSummaryList(GUID);
213         if (SummaryList == Index.end())
214           // This global does not have a summary, it is not part of the ThinLTO
215           // process
216           return nullptr;
217         auto SummaryIter = llvm::find_if(
218             SummaryList->second,
219             [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
220               return Summary->modulePath() == ExportModulePath;
221             });
222         if (SummaryIter == SummaryList->second.end())
223           return nullptr;
224         return SummaryIter->get();
225       };
226 
227   auto *Summary = FindGlobalSummaryInModule(GUID);
228   if (!Summary)
229     return;
230   // We found it in the current module, mark as exported
231   ExportList.insert(GUID);
232 
233   auto GVS = dyn_cast<GlobalVarSummary>(Summary);
234   if (!GVS)
235     return;
236   // FunctionImportGlobalProcessing::doPromoteLocalToGlobal() will always
237   // trigger importing  the initializer for `constant unnamed addr` globals that
238   // are referenced. We conservatively export all the referenced symbols for
239   // every global to workaround this, so that the ExportList is accurate.
240   // FIXME: with a "isConstant" flag in the summary we could be more targetted.
241   for (auto &Ref : GVS->refs()) {
242     auto GUID = Ref.getGUID();
243     auto *RefSummary = FindGlobalSummaryInModule(GUID);
244     if (RefSummary)
245       // Found a ref in the current module, mark it as exported
246       ExportList.insert(GUID);
247   }
248 }
249 
250 using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
251 
252 /// Compute the list of functions to import for a given caller. Mark these
253 /// imported functions and the symbols they reference in their source module as
254 /// exported from their source module.
255 static void computeImportForFunction(
256     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
257     unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
258     SmallVectorImpl<EdgeInfo> &Worklist,
259     FunctionImporter::ImportMapTy &ImportsForModule,
260     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
261   for (auto &Edge : Summary.calls()) {
262     auto GUID = Edge.first.getGUID();
263     DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
264 
265     if (DefinedGVSummaries.count(GUID)) {
266       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
267       continue;
268     }
269 
270     auto *CalleeSummary = selectCallee(GUID, Threshold, Index);
271     if (!CalleeSummary) {
272       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
273       continue;
274     }
275     // "Resolve" the summary, traversing alias,
276     const FunctionSummary *ResolvedCalleeSummary;
277     if (isa<AliasSummary>(CalleeSummary)) {
278       ResolvedCalleeSummary = cast<FunctionSummary>(
279           &cast<AliasSummary>(CalleeSummary)->getAliasee());
280       assert(
281           GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
282           "Unexpected alias to a non-linkonceODR in import list");
283     } else
284       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
285 
286     assert(ResolvedCalleeSummary->instCount() <= Threshold &&
287            "selectCallee() didn't honor the threshold");
288 
289     auto ExportModulePath = ResolvedCalleeSummary->modulePath();
290     auto &ProcessedThreshold = ImportsForModule[ExportModulePath][GUID];
291     /// Since the traversal of the call graph is DFS, we can revisit a function
292     /// a second time with a higher threshold. In this case, it is added back to
293     /// the worklist with the new threshold.
294     if (ProcessedThreshold && ProcessedThreshold >= Threshold) {
295       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
296                    << ProcessedThreshold << "\n");
297       continue;
298     }
299     // Mark this function as imported in this module, with the current Threshold
300     ProcessedThreshold = Threshold;
301 
302     // Make exports in the source module.
303     if (ExportLists) {
304       auto &ExportList = (*ExportLists)[ExportModulePath];
305       ExportList.insert(GUID);
306       // Mark all functions and globals referenced by this function as exported
307       // to the outside if they are defined in the same source module.
308       for (auto &Edge : ResolvedCalleeSummary->calls()) {
309         auto CalleeGUID = Edge.first.getGUID();
310         exportGlobalInModule(Index, ExportModulePath, CalleeGUID, ExportList);
311       }
312       for (auto &Ref : ResolvedCalleeSummary->refs()) {
313         auto GUID = Ref.getGUID();
314         exportGlobalInModule(Index, ExportModulePath, GUID, ExportList);
315       }
316     }
317 
318     // Insert the newly imported function to the worklist.
319     Worklist.push_back(std::make_pair(ResolvedCalleeSummary, Threshold));
320   }
321 }
322 
323 /// Given the list of globals defined in a module, compute the list of imports
324 /// as well as the list of "exports", i.e. the list of symbols referenced from
325 /// another module (that may require promotion).
326 static void ComputeImportForModule(
327     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
328     FunctionImporter::ImportMapTy &ImportsForModule,
329     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
330   // Worklist contains the list of function imported in this module, for which
331   // we will analyse the callees and may import further down the callgraph.
332   SmallVector<EdgeInfo, 128> Worklist;
333 
334   // Populate the worklist with the import for the functions in the current
335   // module
336   for (auto &GVSummary : DefinedGVSummaries) {
337     auto *Summary = GVSummary.second;
338     if (auto *AS = dyn_cast<AliasSummary>(Summary))
339       Summary = &AS->getAliasee();
340     auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
341     if (!FuncSummary)
342       // Skip import for global variables
343       continue;
344     DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
345     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
346                              DefinedGVSummaries, Worklist, ImportsForModule,
347                              ExportLists);
348   }
349 
350   while (!Worklist.empty()) {
351     auto FuncInfo = Worklist.pop_back_val();
352     auto *Summary = FuncInfo.first;
353     auto Threshold = FuncInfo.second;
354 
355     // Process the newly imported functions and add callees to the worklist.
356     // Adjust the threshold
357     Threshold = Threshold * ImportInstrFactor;
358 
359     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
360                              Worklist, ImportsForModule, ExportLists);
361   }
362 }
363 
364 } // anonymous namespace
365 
366 /// Compute all the import and export for every module using the Index.
367 void llvm::ComputeCrossModuleImport(
368     const ModuleSummaryIndex &Index,
369     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
370     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
371     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
372   // For each module that has function defined, compute the import/export lists.
373   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
374     auto &ImportsForModule = ImportLists[DefinedGVSummaries.first()];
375     DEBUG(dbgs() << "Computing import for Module '"
376                  << DefinedGVSummaries.first() << "'\n");
377     ComputeImportForModule(DefinedGVSummaries.second, Index, ImportsForModule,
378                            &ExportLists);
379   }
380 
381 #ifndef NDEBUG
382   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
383                << " modules:\n");
384   for (auto &ModuleImports : ImportLists) {
385     auto ModName = ModuleImports.first();
386     auto &Exports = ExportLists[ModName];
387     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
388                  << " functions. Imports from " << ModuleImports.second.size()
389                  << " modules.\n");
390     for (auto &Src : ModuleImports.second) {
391       auto SrcModName = Src.first();
392       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
393                    << SrcModName << "\n");
394     }
395   }
396 #endif
397 }
398 
399 /// Compute all the imports for the given module in the Index.
400 void llvm::ComputeCrossModuleImportForModule(
401     StringRef ModulePath, const ModuleSummaryIndex &Index,
402     FunctionImporter::ImportMapTy &ImportList) {
403 
404   // Collect the list of functions this module defines.
405   // GUID -> Summary
406   GVSummaryMapTy FunctionSummaryMap;
407   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
408 
409   // Compute the import list for this module.
410   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
411   ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
412 
413 #ifndef NDEBUG
414   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
415                << ImportList.size() << " modules.\n");
416   for (auto &Src : ImportList) {
417     auto SrcModName = Src.first();
418     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
419                  << SrcModName << "\n");
420   }
421 #endif
422 }
423 
424 /// Compute the set of summaries needed for a ThinLTO backend compilation of
425 /// \p ModulePath.
426 void llvm::gatherImportedSummariesForModule(
427     StringRef ModulePath,
428     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
429     const StringMap<FunctionImporter::ImportMapTy> &ImportLists,
430     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
431   // Include all summaries from the importing module.
432   ModuleToSummariesForIndex[ModulePath] =
433       ModuleToDefinedGVSummaries.lookup(ModulePath);
434   auto ModuleImports = ImportLists.find(ModulePath);
435   if (ModuleImports != ImportLists.end()) {
436     // Include summaries for imports.
437     for (auto &ILI : ModuleImports->second) {
438       auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
439       const auto &DefinedGVSummaries =
440           ModuleToDefinedGVSummaries.lookup(ILI.first());
441       for (auto &GI : ILI.second) {
442         const auto &DS = DefinedGVSummaries.find(GI.first);
443         assert(DS != DefinedGVSummaries.end() &&
444                "Expected a defined summary for imported global value");
445         SummariesForIndex[GI.first] = DS->second;
446       }
447     }
448   }
449 }
450 
451 /// Emit the files \p ModulePath will import from into \p OutputFilename.
452 std::error_code llvm::EmitImportsFiles(
453     StringRef ModulePath, StringRef OutputFilename,
454     const StringMap<FunctionImporter::ImportMapTy> &ImportLists) {
455   auto ModuleImports = ImportLists.find(ModulePath);
456   std::error_code EC;
457   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
458   if (EC)
459     return EC;
460   if (ModuleImports != ImportLists.end())
461     for (auto &ILI : ModuleImports->second)
462       ImportsOS << ILI.first() << "\n";
463   return std::error_code();
464 }
465 
466 /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
467 void llvm::thinLTOResolveWeakForLinkerModule(
468     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
469   auto updateLinkage = [&](GlobalValue &GV) {
470     if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
471       return;
472     // See if the global summary analysis computed a new resolved linkage.
473     const auto &GS = DefinedGlobals.find(GV.getGUID());
474     if (GS == DefinedGlobals.end())
475       return;
476     auto NewLinkage = GS->second->linkage();
477     if (NewLinkage == GV.getLinkage())
478       return;
479     DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
480                  << GV.getLinkage() << " to " << NewLinkage << "\n");
481     GV.setLinkage(NewLinkage);
482   };
483 
484   // Process functions and global now
485   for (auto &GV : TheModule)
486     updateLinkage(GV);
487   for (auto &GV : TheModule.globals())
488     updateLinkage(GV);
489   for (auto &GV : TheModule.aliases())
490     updateLinkage(GV);
491 }
492 
493 /// Run internalization on \p TheModule based on symmary analysis.
494 void llvm::thinLTOInternalizeModule(Module &TheModule,
495                                     const GVSummaryMapTy &DefinedGlobals) {
496   // Parse inline ASM and collect the list of symbols that are not defined in
497   // the current module.
498   StringSet<> AsmUndefinedRefs;
499   object::IRObjectFile::CollectAsmUndefinedRefs(
500       Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
501       [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
502         if (Flags & object::BasicSymbolRef::SF_Undefined)
503           AsmUndefinedRefs.insert(Name);
504       });
505 
506   // Declare a callback for the internalize pass that will ask for every
507   // candidate GlobalValue if it can be internalized or not.
508   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
509     // Can't be internalized if referenced in inline asm.
510     if (AsmUndefinedRefs.count(GV.getName()))
511       return true;
512 
513     // Lookup the linkage recorded in the summaries during global analysis.
514     const auto &GS = DefinedGlobals.find(GV.getGUID());
515     GlobalValue::LinkageTypes Linkage;
516     if (GS == DefinedGlobals.end()) {
517       // Must have been promoted (possibly conservatively). Find original
518       // name so that we can access the correct summary and see if it can
519       // be internalized again.
520       // FIXME: Eventually we should control promotion instead of promoting
521       // and internalizing again.
522       StringRef OrigName =
523           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
524       std::string OrigId = GlobalValue::getGlobalIdentifier(
525           OrigName, GlobalValue::InternalLinkage,
526           TheModule.getSourceFileName());
527       const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
528       assert(GS != DefinedGlobals.end());
529       Linkage = GS->second->linkage();
530     } else
531       Linkage = GS->second->linkage();
532     return !GlobalValue::isLocalLinkage(Linkage);
533   };
534 
535   // FIXME: See if we can just internalize directly here via linkage changes
536   // based on the index, rather than invoking internalizeModule.
537   llvm::internalizeModule(TheModule, MustPreserveGV);
538 }
539 
540 // Automatically import functions in Module \p DestModule based on the summaries
541 // index.
542 //
543 bool FunctionImporter::importFunctions(
544     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
545     bool ForceImportReferencedDiscardableSymbols) {
546   DEBUG(dbgs() << "Starting import for Module "
547                << DestModule.getModuleIdentifier() << "\n");
548   unsigned ImportedCount = 0;
549 
550   // Linker that will be used for importing function
551   Linker TheLinker(DestModule);
552   // Do the actual import of functions now, one Module at a time
553   std::set<StringRef> ModuleNameOrderedList;
554   for (auto &FunctionsToImportPerModule : ImportList) {
555     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
556   }
557   for (auto &Name : ModuleNameOrderedList) {
558     // Get the module for the import
559     const auto &FunctionsToImportPerModule = ImportList.find(Name);
560     assert(FunctionsToImportPerModule != ImportList.end());
561     std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
562     assert(&DestModule.getContext() == &SrcModule->getContext() &&
563            "Context mismatch");
564 
565     // If modules were created with lazy metadata loading, materialize it
566     // now, before linking it (otherwise this will be a noop).
567     SrcModule->materializeMetadata();
568     UpgradeDebugInfo(*SrcModule);
569 
570     auto &ImportGUIDs = FunctionsToImportPerModule->second;
571     // Find the globals to import
572     DenseSet<const GlobalValue *> GlobalsToImport;
573     for (auto &GV : *SrcModule) {
574       if (!GV.hasName())
575         continue;
576       auto GUID = GV.getGUID();
577       auto Import = ImportGUIDs.count(GUID);
578       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
579                    << " " << GV.getName() << " from "
580                    << SrcModule->getSourceFileName() << "\n");
581       if (Import) {
582         GV.materialize();
583         GlobalsToImport.insert(&GV);
584       }
585     }
586     for (auto &GV : SrcModule->globals()) {
587       if (!GV.hasName())
588         continue;
589       auto GUID = GV.getGUID();
590       auto Import = ImportGUIDs.count(GUID);
591       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
592                    << " " << GV.getName() << " from "
593                    << SrcModule->getSourceFileName() << "\n");
594       if (Import) {
595         GV.materialize();
596         GlobalsToImport.insert(&GV);
597       }
598     }
599     for (auto &GV : SrcModule->aliases()) {
600       if (!GV.hasName())
601         continue;
602       auto GUID = GV.getGUID();
603       auto Import = ImportGUIDs.count(GUID);
604       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
605                    << " " << GV.getName() << " from "
606                    << SrcModule->getSourceFileName() << "\n");
607       if (Import) {
608         // Alias can't point to "available_externally". However when we import
609         // linkOnceODR the linkage does not change. So we import the alias
610         // and aliasee only in this case. This has been handled by
611         // computeImportForFunction()
612         GlobalObject *GO = GV.getBaseObject();
613         assert(GO->hasLinkOnceODRLinkage() &&
614                "Unexpected alias to a non-linkonceODR in import list");
615 #ifndef NDEBUG
616         if (!GlobalsToImport.count(GO))
617           DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
618                        << " " << GO->getName() << " from "
619                        << SrcModule->getSourceFileName() << "\n");
620 #endif
621         GO->materialize();
622         GlobalsToImport.insert(GO);
623         GV.materialize();
624         GlobalsToImport.insert(&GV);
625       }
626     }
627 
628     // Link in the specified functions.
629     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
630       return true;
631 
632     if (PrintImports) {
633       for (const auto *GV : GlobalsToImport)
634         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
635                << " from " << SrcModule->getSourceFileName() << "\n";
636     }
637 
638     // Instruct the linker that the client will take care of linkonce resolution
639     unsigned Flags = Linker::Flags::None;
640     if (!ForceImportReferencedDiscardableSymbols)
641       Flags |= Linker::Flags::DontForceLinkLinkonceODR;
642 
643     if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
644       report_fatal_error("Function Import: link error");
645 
646     ImportedCount += GlobalsToImport.size();
647   }
648 
649   NumImported += ImportedCount;
650 
651   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
652                << DestModule.getModuleIdentifier() << "\n");
653   return ImportedCount;
654 }
655 
656 /// Summary file to use for function importing when using -function-import from
657 /// the command line.
658 static cl::opt<std::string>
659     SummaryFile("summary-file",
660                 cl::desc("The summary file to use for function importing."));
661 
662 static void diagnosticHandler(const DiagnosticInfo &DI) {
663   raw_ostream &OS = errs();
664   DiagnosticPrinterRawOStream DP(OS);
665   DI.print(DP);
666   OS << '\n';
667 }
668 
669 /// Parse the summary index out of an IR file and return the summary
670 /// index object if found, or nullptr if not.
671 static std::unique_ptr<ModuleSummaryIndex>
672 getModuleSummaryIndexForFile(StringRef Path, std::string &Error,
673                              DiagnosticHandlerFunction DiagnosticHandler) {
674   std::unique_ptr<MemoryBuffer> Buffer;
675   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
676       MemoryBuffer::getFile(Path);
677   if (std::error_code EC = BufferOrErr.getError()) {
678     Error = EC.message();
679     return nullptr;
680   }
681   Buffer = std::move(BufferOrErr.get());
682   ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
683       object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
684                                                    DiagnosticHandler);
685   if (std::error_code EC = ObjOrErr.getError()) {
686     Error = EC.message();
687     return nullptr;
688   }
689   return (*ObjOrErr)->takeIndex();
690 }
691 
692 namespace {
693 /// Pass that performs cross-module function import provided a summary file.
694 class FunctionImportPass : public ModulePass {
695   /// Optional module summary index to use for importing, otherwise
696   /// the summary-file option must be specified.
697   const ModuleSummaryIndex *Index;
698 
699 public:
700   /// Pass identification, replacement for typeid
701   static char ID;
702 
703   /// Specify pass name for debug output
704   const char *getPassName() const override { return "Function Importing"; }
705 
706   explicit FunctionImportPass(const ModuleSummaryIndex *Index = nullptr)
707       : ModulePass(ID), Index(Index) {}
708 
709   bool runOnModule(Module &M) override {
710     if (skipModule(M))
711       return false;
712 
713     if (SummaryFile.empty() && !Index)
714       report_fatal_error("error: -function-import requires -summary-file or "
715                          "file from frontend\n");
716     std::unique_ptr<ModuleSummaryIndex> IndexPtr;
717     if (!SummaryFile.empty()) {
718       if (Index)
719         report_fatal_error("error: -summary-file and index from frontend\n");
720       std::string Error;
721       IndexPtr =
722           getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
723       if (!IndexPtr) {
724         errs() << "Error loading file '" << SummaryFile << "': " << Error
725                << "\n";
726         return false;
727       }
728       Index = IndexPtr.get();
729     }
730 
731     // First step is collecting the import list.
732     FunctionImporter::ImportMapTy ImportList;
733     ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
734                                       ImportList);
735 
736     // Next we need to promote to global scope and rename any local values that
737     // are potentially exported to other modules.
738     if (renameModuleForThinLTO(M, *Index, nullptr)) {
739       errs() << "Error renaming module\n";
740       return false;
741     }
742 
743     // Perform the import now.
744     auto ModuleLoader = [&M](StringRef Identifier) {
745       return loadFile(Identifier, M.getContext());
746     };
747     FunctionImporter Importer(*Index, ModuleLoader);
748     return Importer.importFunctions(
749         M, ImportList, !DontForceImportReferencedDiscardableSymbols);
750   }
751 };
752 } // anonymous namespace
753 
754 char FunctionImportPass::ID = 0;
755 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
756                       "Summary Based Function Import", false, false)
757 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
758                     "Summary Based Function Import", false, false)
759 
760 namespace llvm {
761 Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
762   return new FunctionImportPass(Index);
763 }
764 }
765