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/Bitcode/BitcodeReader.h"
21 #include "llvm/IR/AutoUpgrade.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Verifier.h"
26 #include "llvm/IRReader/IRReader.h"
27 #include "llvm/Linker/Linker.h"
28 #include "llvm/Object/IRObjectFile.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Transforms/IPO/Internalize.h"
33 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
34 
35 #define DEBUG_TYPE "function-import"
36 
37 using namespace llvm;
38 
39 STATISTIC(NumImportedFunctions, "Number of functions imported");
40 STATISTIC(NumImportedModules, "Number of modules imported from");
41 STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
42 STATISTIC(NumLiveSymbols, "Number of live symbols in index");
43 
44 /// Limit on instruction count of imported functions.
45 static cl::opt<unsigned> ImportInstrLimit(
46     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
47     cl::desc("Only import functions with less than N instructions"));
48 
49 static cl::opt<float>
50     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
51                       cl::Hidden, cl::value_desc("x"),
52                       cl::desc("As we import functions, multiply the "
53                                "`import-instr-limit` threshold by this factor "
54                                "before processing newly imported functions"));
55 
56 static cl::opt<float> ImportHotInstrFactor(
57     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
58     cl::value_desc("x"),
59     cl::desc("As we import functions called from hot callsite, multiply the "
60              "`import-instr-limit` threshold by this factor "
61              "before processing newly imported functions"));
62 
63 static cl::opt<float> ImportHotMultiplier(
64     "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
65     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
66 
67 static cl::opt<float> ImportCriticalMultiplier(
68     "import-critical-multiplier", cl::init(100.0), cl::Hidden,
69     cl::value_desc("x"),
70     cl::desc(
71         "Multiply the `import-instr-limit` threshold for critical callsites"));
72 
73 // FIXME: This multiplier was not really tuned up.
74 static cl::opt<float> ImportColdMultiplier(
75     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
76     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
77 
78 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
79                                   cl::desc("Print imported functions"));
80 
81 static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
82                                  cl::desc("Compute dead symbols"));
83 
84 static cl::opt<bool> EnableImportMetadata(
85     "enable-import-metadata", cl::init(
86 #if !defined(NDEBUG)
87                                   true /*Enabled with asserts.*/
88 #else
89                                   false
90 #endif
91                                   ),
92     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
93 
94 // Load lazily a module from \p FileName in \p Context.
95 static std::unique_ptr<Module> loadFile(const std::string &FileName,
96                                         LLVMContext &Context) {
97   SMDiagnostic Err;
98   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
99   // Metadata isn't loaded until functions are imported, to minimize
100   // the memory overhead.
101   std::unique_ptr<Module> Result =
102       getLazyIRFileModule(FileName, Err, Context,
103                           /* ShouldLazyLoadMetadata = */ true);
104   if (!Result) {
105     Err.print("function-import", errs());
106     report_fatal_error("Abort");
107   }
108 
109   return Result;
110 }
111 
112 namespace {
113 
114 /// Given a list of possible callee implementation for a call site, select one
115 /// that fits the \p Threshold.
116 ///
117 /// FIXME: select "best" instead of first that fits. But what is "best"?
118 /// - The smallest: more likely to be inlined.
119 /// - The one with the least outgoing edges (already well optimized).
120 /// - One from a module already being imported from in order to reduce the
121 ///   number of source modules parsed/linked.
122 /// - One that has PGO data attached.
123 /// - [insert you fancy metric here]
124 static const GlobalValueSummary *
125 selectCallee(const ModuleSummaryIndex &Index,
126              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
127              unsigned Threshold, StringRef CallerModulePath) {
128   auto It = llvm::find_if(
129       CalleeSummaryList,
130       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
131         auto *GVSummary = SummaryPtr.get();
132         // For SamplePGO, in computeImportForFunction the OriginalId
133         // may have been used to locate the callee summary list (See
134         // comment there).
135         // The mapping from OriginalId to GUID may return a GUID
136         // that corresponds to a static variable. Filter it out here.
137         // This can happen when
138         // 1) There is a call to a library function which is not defined
139         // in the index.
140         // 2) There is a static variable with the  OriginalGUID identical
141         // to the GUID of the library function in 1);
142         // When this happens, the logic for SamplePGO kicks in and
143         // the static variable in 2) will be found, which needs to be
144         // filtered out.
145         if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
146           return false;
147         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
148           // There is no point in importing these, we can't inline them
149           return false;
150         if (isa<AliasSummary>(GVSummary))
151           // Aliases can't point to "available_externally".
152           // FIXME: we should import alias as available_externally *function*,
153           // the destination module does not need to know it is an alias.
154           return false;
155 
156         auto *Summary = cast<FunctionSummary>(GVSummary);
157 
158         // If this is a local function, make sure we import the copy
159         // in the caller's module. The only time a local function can
160         // share an entry in the index is if there is a local with the same name
161         // in another module that had the same source file name (in a different
162         // directory), where each was compiled in their own directory so there
163         // was not distinguishing path.
164         // However, do the import from another module if there is only one
165         // entry in the list - in that case this must be a reference due
166         // to indirect call profile data, since a function pointer can point to
167         // a local in another module.
168         if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
169             CalleeSummaryList.size() > 1 &&
170             Summary->modulePath() != CallerModulePath)
171           return false;
172 
173         if (Summary->instCount() > Threshold)
174           return false;
175 
176         if (Summary->notEligibleToImport())
177           return false;
178 
179         return true;
180       });
181   if (It == CalleeSummaryList.end())
182     return nullptr;
183 
184   return cast<GlobalValueSummary>(It->get());
185 }
186 
187 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
188                             GlobalValue::GUID>;
189 
190 /// Compute the list of functions to import for a given caller. Mark these
191 /// imported functions and the symbols they reference in their source module as
192 /// exported from their source module.
193 static void computeImportForFunction(
194     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
195     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
196     SmallVectorImpl<EdgeInfo> &Worklist,
197     FunctionImporter::ImportMapTy &ImportList,
198     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
199   for (auto &Edge : Summary.calls()) {
200     ValueInfo VI = Edge.first;
201     DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
202                  << "\n");
203 
204     if (VI.getSummaryList().empty()) {
205       // For SamplePGO, the indirect call targets for local functions will
206       // have its original name annotated in profile. We try to find the
207       // corresponding PGOFuncName as the GUID.
208       auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
209       if (GUID == 0)
210         continue;
211       VI = Index.getValueInfo(GUID);
212       if (!VI)
213         continue;
214     }
215 
216     if (DefinedGVSummaries.count(VI.getGUID())) {
217       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
218       continue;
219     }
220 
221     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
222       if (Hotness == CalleeInfo::HotnessType::Hot)
223         return ImportHotMultiplier;
224       if (Hotness == CalleeInfo::HotnessType::Cold)
225         return ImportColdMultiplier;
226       if (Hotness == CalleeInfo::HotnessType::Critical)
227         return ImportCriticalMultiplier;
228       return 1.0;
229     };
230 
231     const auto NewThreshold =
232         Threshold * GetBonusMultiplier(Edge.second.Hotness);
233 
234     auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
235                                        Summary.modulePath());
236     if (!CalleeSummary) {
237       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
238       continue;
239     }
240 
241     // "Resolve" the summary
242     assert(!isa<AliasSummary>(CalleeSummary) &&
243            "Unexpected alias in import list");
244     const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
245 
246     assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
247            "selectCallee() didn't honor the threshold");
248 
249     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
250       // Adjust the threshold for next level of imported functions.
251       // The threshold is different for hot callsites because we can then
252       // inline chains of hot calls.
253       if (IsHotCallsite)
254         return Threshold * ImportHotInstrFactor;
255       return Threshold * ImportInstrFactor;
256     };
257 
258     bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
259     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
260 
261     auto ExportModulePath = ResolvedCalleeSummary->modulePath();
262     auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
263     /// Since the traversal of the call graph is DFS, we can revisit a function
264     /// a second time with a higher threshold. In this case, it is added back to
265     /// the worklist with the new threshold.
266     if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
267       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
268                    << ProcessedThreshold << "\n");
269       continue;
270     }
271     bool PreviouslyImported = ProcessedThreshold != 0;
272     // Mark this function as imported in this module, with the current Threshold
273     ProcessedThreshold = AdjThreshold;
274 
275     // Make exports in the source module.
276     if (ExportLists) {
277       auto &ExportList = (*ExportLists)[ExportModulePath];
278       ExportList.insert(VI.getGUID());
279       if (!PreviouslyImported) {
280         // This is the first time this function was exported from its source
281         // module, so mark all functions and globals it references as exported
282         // to the outside if they are defined in the same source module.
283         // For efficiency, we unconditionally add all the referenced GUIDs
284         // to the ExportList for this module, and will prune out any not
285         // defined in the module later in a single pass.
286         for (auto &Edge : ResolvedCalleeSummary->calls()) {
287           auto CalleeGUID = Edge.first.getGUID();
288           ExportList.insert(CalleeGUID);
289         }
290         for (auto &Ref : ResolvedCalleeSummary->refs()) {
291           auto GUID = Ref.getGUID();
292           ExportList.insert(GUID);
293         }
294       }
295     }
296 
297     // Insert the newly imported function to the worklist.
298     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
299   }
300 }
301 
302 /// Given the list of globals defined in a module, compute the list of imports
303 /// as well as the list of "exports", i.e. the list of symbols referenced from
304 /// another module (that may require promotion).
305 static void ComputeImportForModule(
306     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
307     FunctionImporter::ImportMapTy &ImportList,
308     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
309   // Worklist contains the list of function imported in this module, for which
310   // we will analyse the callees and may import further down the callgraph.
311   SmallVector<EdgeInfo, 128> Worklist;
312 
313   // Populate the worklist with the import for the functions in the current
314   // module
315   for (auto &GVSummary : DefinedGVSummaries) {
316     if (!Index.isGlobalValueLive(GVSummary.second)) {
317       DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
318       continue;
319     }
320     auto *Summary = GVSummary.second;
321     if (auto *AS = dyn_cast<AliasSummary>(Summary))
322       Summary = &AS->getAliasee();
323     auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
324     if (!FuncSummary)
325       // Skip import for global variables
326       continue;
327     DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n");
328     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
329                              DefinedGVSummaries, Worklist, ImportList,
330                              ExportLists);
331   }
332 
333   // Process the newly imported functions and add callees to the worklist.
334   while (!Worklist.empty()) {
335     auto FuncInfo = Worklist.pop_back_val();
336     auto *Summary = std::get<0>(FuncInfo);
337     auto Threshold = std::get<1>(FuncInfo);
338     auto GUID = std::get<2>(FuncInfo);
339 
340     // Check if we later added this summary with a higher threshold.
341     // If so, skip this entry.
342     auto ExportModulePath = Summary->modulePath();
343     auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
344     if (LatestProcessedThreshold > Threshold)
345       continue;
346 
347     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
348                              Worklist, ImportList, ExportLists);
349   }
350 }
351 
352 } // anonymous namespace
353 
354 /// Compute all the import and export for every module using the Index.
355 void llvm::ComputeCrossModuleImport(
356     const ModuleSummaryIndex &Index,
357     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
358     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
359     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
360   // For each module that has function defined, compute the import/export lists.
361   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
362     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
363     DEBUG(dbgs() << "Computing import for Module '"
364                  << DefinedGVSummaries.first() << "'\n");
365     ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
366                            &ExportLists);
367   }
368 
369   // When computing imports we added all GUIDs referenced by anything
370   // imported from the module to its ExportList. Now we prune each ExportList
371   // of any not defined in that module. This is more efficient than checking
372   // while computing imports because some of the summary lists may be long
373   // due to linkonce (comdat) copies.
374   for (auto &ELI : ExportLists) {
375     const auto &DefinedGVSummaries =
376         ModuleToDefinedGVSummaries.lookup(ELI.first());
377     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
378       if (!DefinedGVSummaries.count(*EI))
379         EI = ELI.second.erase(EI);
380       else
381         ++EI;
382     }
383   }
384 
385 #ifndef NDEBUG
386   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
387                << " modules:\n");
388   for (auto &ModuleImports : ImportLists) {
389     auto ModName = ModuleImports.first();
390     auto &Exports = ExportLists[ModName];
391     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
392                  << " functions. Imports from " << ModuleImports.second.size()
393                  << " modules.\n");
394     for (auto &Src : ModuleImports.second) {
395       auto SrcModName = Src.first();
396       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
397                    << SrcModName << "\n");
398     }
399   }
400 #endif
401 }
402 
403 /// Compute all the imports for the given module in the Index.
404 void llvm::ComputeCrossModuleImportForModule(
405     StringRef ModulePath, const ModuleSummaryIndex &Index,
406     FunctionImporter::ImportMapTy &ImportList) {
407 
408   // Collect the list of functions this module defines.
409   // GUID -> Summary
410   GVSummaryMapTy FunctionSummaryMap;
411   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
412 
413   // Compute the import list for this module.
414   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
415   ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
416 
417 #ifndef NDEBUG
418   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
419                << ImportList.size() << " modules.\n");
420   for (auto &Src : ImportList) {
421     auto SrcModName = Src.first();
422     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
423                  << SrcModName << "\n");
424   }
425 #endif
426 }
427 
428 void llvm::computeDeadSymbols(
429     ModuleSummaryIndex &Index,
430     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
431   assert(!Index.withGlobalValueDeadStripping());
432   if (!ComputeDead)
433     return;
434   if (GUIDPreservedSymbols.empty())
435     // Don't do anything when nothing is live, this is friendly with tests.
436     return;
437   unsigned LiveSymbols = 0;
438   SmallVector<ValueInfo, 128> Worklist;
439   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
440   for (auto GUID : GUIDPreservedSymbols) {
441     ValueInfo VI = Index.getValueInfo(GUID);
442     if (!VI)
443       continue;
444     for (auto &S : VI.getSummaryList())
445       S->setLive(true);
446   }
447 
448   // Add values flagged in the index as live roots to the worklist.
449   for (const auto &Entry : Index)
450     for (auto &S : Entry.second.SummaryList)
451       if (S->isLive()) {
452         DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
453         Worklist.push_back(ValueInfo(&Entry));
454         ++LiveSymbols;
455         break;
456       }
457 
458   // Make value live and add it to the worklist if it was not live before.
459   // FIXME: we should only make the prevailing copy live here
460   auto visit = [&](ValueInfo VI) {
461     for (auto &S : VI.getSummaryList())
462       if (S->isLive())
463         return;
464     for (auto &S : VI.getSummaryList())
465       S->setLive(true);
466     ++LiveSymbols;
467     Worklist.push_back(VI);
468   };
469 
470   while (!Worklist.empty()) {
471     auto VI = Worklist.pop_back_val();
472     for (auto &Summary : VI.getSummaryList()) {
473       for (auto Ref : Summary->refs())
474         visit(Ref);
475       if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
476         for (auto Call : FS->calls())
477           visit(Call.first);
478       if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
479         auto AliaseeGUID = AS->getAliasee().getOriginalName();
480         ValueInfo AliaseeVI = Index.getValueInfo(AliaseeGUID);
481         if (AliaseeVI)
482           visit(AliaseeVI);
483       }
484     }
485   }
486   Index.setWithGlobalValueDeadStripping();
487 
488   unsigned DeadSymbols = Index.size() - LiveSymbols;
489   DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
490                << " symbols Dead \n");
491   NumDeadSymbols += DeadSymbols;
492   NumLiveSymbols += LiveSymbols;
493 }
494 
495 /// Compute the set of summaries needed for a ThinLTO backend compilation of
496 /// \p ModulePath.
497 void llvm::gatherImportedSummariesForModule(
498     StringRef ModulePath,
499     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
500     const FunctionImporter::ImportMapTy &ImportList,
501     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
502   // Include all summaries from the importing module.
503   ModuleToSummariesForIndex[ModulePath] =
504       ModuleToDefinedGVSummaries.lookup(ModulePath);
505   // Include summaries for imports.
506   for (auto &ILI : ImportList) {
507     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
508     const auto &DefinedGVSummaries =
509         ModuleToDefinedGVSummaries.lookup(ILI.first());
510     for (auto &GI : ILI.second) {
511       const auto &DS = DefinedGVSummaries.find(GI.first);
512       assert(DS != DefinedGVSummaries.end() &&
513              "Expected a defined summary for imported global value");
514       SummariesForIndex[GI.first] = DS->second;
515     }
516   }
517 }
518 
519 /// Emit the files \p ModulePath will import from into \p OutputFilename.
520 std::error_code
521 llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
522                        const FunctionImporter::ImportMapTy &ModuleImports) {
523   std::error_code EC;
524   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
525   if (EC)
526     return EC;
527   for (auto &ILI : ModuleImports)
528     ImportsOS << ILI.first() << "\n";
529   return std::error_code();
530 }
531 
532 /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
533 void llvm::thinLTOResolveWeakForLinkerModule(
534     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
535   auto ConvertToDeclaration = [](GlobalValue &GV) {
536     DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
537     if (Function *F = dyn_cast<Function>(&GV)) {
538       F->deleteBody();
539       F->clearMetadata();
540     } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
541       V->setInitializer(nullptr);
542       V->setLinkage(GlobalValue::ExternalLinkage);
543       V->clearMetadata();
544     } else
545       // For now we don't resolve or drop aliases. Once we do we'll
546       // need to add support here for creating either a function or
547       // variable declaration, and return the new GlobalValue* for
548       // the caller to use.
549       llvm_unreachable("Expected function or variable");
550   };
551 
552   auto updateLinkage = [&](GlobalValue &GV) {
553     // See if the global summary analysis computed a new resolved linkage.
554     const auto &GS = DefinedGlobals.find(GV.getGUID());
555     if (GS == DefinedGlobals.end())
556       return;
557     auto NewLinkage = GS->second->linkage();
558     if (NewLinkage == GV.getLinkage())
559       return;
560 
561     // Switch the linkage to weakany if asked for, e.g. we do this for
562     // linker redefined symbols (via --wrap or --defsym).
563     // We record that the visibility should be changed here in `addThinLTO`
564     // as we need access to the resolution vectors for each input file in
565     // order to find which symbols have been redefined.
566     // We may consider reorganizing this code and moving the linkage recording
567     // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
568     if (NewLinkage == GlobalValue::WeakAnyLinkage) {
569       GV.setLinkage(NewLinkage);
570       return;
571     }
572 
573     if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
574       return;
575     // Check for a non-prevailing def that has interposable linkage
576     // (e.g. non-odr weak or linkonce). In that case we can't simply
577     // convert to available_externally, since it would lose the
578     // interposable property and possibly get inlined. Simply drop
579     // the definition in that case.
580     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
581         GlobalValue::isInterposableLinkage(GV.getLinkage()))
582       ConvertToDeclaration(GV);
583     else {
584       DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
585                    << GV.getLinkage() << " to " << NewLinkage << "\n");
586       GV.setLinkage(NewLinkage);
587     }
588     // Remove declarations from comdats, including available_externally
589     // as this is a declaration for the linker, and will be dropped eventually.
590     // It is illegal for comdats to contain declarations.
591     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
592     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
593       GO->setComdat(nullptr);
594   };
595 
596   // Process functions and global now
597   for (auto &GV : TheModule)
598     updateLinkage(GV);
599   for (auto &GV : TheModule.globals())
600     updateLinkage(GV);
601   for (auto &GV : TheModule.aliases())
602     updateLinkage(GV);
603 }
604 
605 /// Run internalization on \p TheModule based on symmary analysis.
606 void llvm::thinLTOInternalizeModule(Module &TheModule,
607                                     const GVSummaryMapTy &DefinedGlobals) {
608   // Parse inline ASM and collect the list of symbols that are not defined in
609   // the current module.
610   StringSet<> AsmUndefinedRefs;
611   ModuleSymbolTable::CollectAsmSymbols(
612       TheModule,
613       [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
614         if (Flags & object::BasicSymbolRef::SF_Undefined)
615           AsmUndefinedRefs.insert(Name);
616       });
617 
618   // Declare a callback for the internalize pass that will ask for every
619   // candidate GlobalValue if it can be internalized or not.
620   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
621     // Can't be internalized if referenced in inline asm.
622     if (AsmUndefinedRefs.count(GV.getName()))
623       return true;
624 
625     // Lookup the linkage recorded in the summaries during global analysis.
626     auto GS = DefinedGlobals.find(GV.getGUID());
627     if (GS == DefinedGlobals.end()) {
628       // Must have been promoted (possibly conservatively). Find original
629       // name so that we can access the correct summary and see if it can
630       // be internalized again.
631       // FIXME: Eventually we should control promotion instead of promoting
632       // and internalizing again.
633       StringRef OrigName =
634           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
635       std::string OrigId = GlobalValue::getGlobalIdentifier(
636           OrigName, GlobalValue::InternalLinkage,
637           TheModule.getSourceFileName());
638       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
639       if (GS == DefinedGlobals.end()) {
640         // Also check the original non-promoted non-globalized name. In some
641         // cases a preempted weak value is linked in as a local copy because
642         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
643         // In that case, since it was originally not a local value, it was
644         // recorded in the index using the original name.
645         // FIXME: This may not be needed once PR27866 is fixed.
646         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
647         assert(GS != DefinedGlobals.end());
648       }
649     }
650     return !GlobalValue::isLocalLinkage(GS->second->linkage());
651   };
652 
653   // FIXME: See if we can just internalize directly here via linkage changes
654   // based on the index, rather than invoking internalizeModule.
655   llvm::internalizeModule(TheModule, MustPreserveGV);
656 }
657 
658 // Automatically import functions in Module \p DestModule based on the summaries
659 // index.
660 //
661 Expected<bool> FunctionImporter::importFunctions(
662     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
663   DEBUG(dbgs() << "Starting import for Module "
664                << DestModule.getModuleIdentifier() << "\n");
665   unsigned ImportedCount = 0;
666 
667   IRMover Mover(DestModule);
668   // Do the actual import of functions now, one Module at a time
669   std::set<StringRef> ModuleNameOrderedList;
670   for (auto &FunctionsToImportPerModule : ImportList) {
671     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
672   }
673   for (auto &Name : ModuleNameOrderedList) {
674     // Get the module for the import
675     const auto &FunctionsToImportPerModule = ImportList.find(Name);
676     assert(FunctionsToImportPerModule != ImportList.end());
677     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
678     if (!SrcModuleOrErr)
679       return SrcModuleOrErr.takeError();
680     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
681     assert(&DestModule.getContext() == &SrcModule->getContext() &&
682            "Context mismatch");
683 
684     // If modules were created with lazy metadata loading, materialize it
685     // now, before linking it (otherwise this will be a noop).
686     if (Error Err = SrcModule->materializeMetadata())
687       return std::move(Err);
688 
689     auto &ImportGUIDs = FunctionsToImportPerModule->second;
690     // Find the globals to import
691     SetVector<GlobalValue *> GlobalsToImport;
692     for (Function &F : *SrcModule) {
693       if (!F.hasName())
694         continue;
695       auto GUID = F.getGUID();
696       auto Import = ImportGUIDs.count(GUID);
697       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
698                    << " " << F.getName() << " from "
699                    << SrcModule->getSourceFileName() << "\n");
700       if (Import) {
701         if (Error Err = F.materialize())
702           return std::move(Err);
703         if (EnableImportMetadata) {
704           // Add 'thinlto_src_module' metadata for statistics and debugging.
705           F.setMetadata(
706               "thinlto_src_module",
707               llvm::MDNode::get(
708                   DestModule.getContext(),
709                   {llvm::MDString::get(DestModule.getContext(),
710                                        SrcModule->getSourceFileName())}));
711         }
712         GlobalsToImport.insert(&F);
713       }
714     }
715     for (GlobalVariable &GV : SrcModule->globals()) {
716       if (!GV.hasName())
717         continue;
718       auto GUID = GV.getGUID();
719       auto Import = ImportGUIDs.count(GUID);
720       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
721                    << " " << GV.getName() << " from "
722                    << SrcModule->getSourceFileName() << "\n");
723       if (Import) {
724         if (Error Err = GV.materialize())
725           return std::move(Err);
726         GlobalsToImport.insert(&GV);
727       }
728     }
729 #ifndef NDEBUG
730     for (GlobalAlias &GA : SrcModule->aliases()) {
731       if (!GA.hasName())
732         continue;
733       auto GUID = GA.getGUID();
734       assert(!ImportGUIDs.count(GUID) && "Unexpected alias in import list");
735       DEBUG(dbgs() << "Not importing alias " << GUID
736                    << " " << GA.getName() << " from "
737                    << SrcModule->getSourceFileName() << "\n");
738     }
739 #endif
740 
741     // Upgrade debug info after we're done materializing all the globals and we
742     // have loaded all the required metadata!
743     UpgradeDebugInfo(*SrcModule);
744 
745     // Link in the specified functions.
746     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
747       return true;
748 
749     if (PrintImports) {
750       for (const auto *GV : GlobalsToImport)
751         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
752                << " from " << SrcModule->getSourceFileName() << "\n";
753     }
754 
755     if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
756                    [](GlobalValue &, IRMover::ValueAdder) {},
757                    /*IsPerformingImport=*/true))
758       report_fatal_error("Function Import: link error");
759 
760     ImportedCount += GlobalsToImport.size();
761     NumImportedModules++;
762   }
763 
764   NumImportedFunctions += ImportedCount;
765 
766   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
767                << DestModule.getModuleIdentifier() << "\n");
768   return ImportedCount;
769 }
770 
771 /// Summary file to use for function importing when using -function-import from
772 /// the command line.
773 static cl::opt<std::string>
774     SummaryFile("summary-file",
775                 cl::desc("The summary file to use for function importing."));
776 
777 static bool doImportingForModule(Module &M) {
778   if (SummaryFile.empty())
779     report_fatal_error("error: -function-import requires -summary-file\n");
780   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
781       getModuleSummaryIndexForFile(SummaryFile);
782   if (!IndexPtrOrErr) {
783     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
784                           "Error loading file '" + SummaryFile + "': ");
785     return false;
786   }
787   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
788 
789   // First step is collecting the import list.
790   FunctionImporter::ImportMapTy ImportList;
791   ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
792                                     ImportList);
793 
794   // Conservatively mark all internal values as promoted. This interface is
795   // only used when doing importing via the function importing pass. The pass
796   // is only enabled when testing importing via the 'opt' tool, which does
797   // not do the ThinLink that would normally determine what values to promote.
798   for (auto &I : *Index) {
799     for (auto &S : I.second.SummaryList) {
800       if (GlobalValue::isLocalLinkage(S->linkage()))
801         S->setLinkage(GlobalValue::ExternalLinkage);
802     }
803   }
804 
805   // Next we need to promote to global scope and rename any local values that
806   // are potentially exported to other modules.
807   if (renameModuleForThinLTO(M, *Index, nullptr)) {
808     errs() << "Error renaming module\n";
809     return false;
810   }
811 
812   // Perform the import now.
813   auto ModuleLoader = [&M](StringRef Identifier) {
814     return loadFile(Identifier, M.getContext());
815   };
816   FunctionImporter Importer(*Index, ModuleLoader);
817   Expected<bool> Result = Importer.importFunctions(M, ImportList);
818 
819   // FIXME: Probably need to propagate Errors through the pass manager.
820   if (!Result) {
821     logAllUnhandledErrors(Result.takeError(), errs(),
822                           "Error importing module: ");
823     return false;
824   }
825 
826   return *Result;
827 }
828 
829 namespace {
830 /// Pass that performs cross-module function import provided a summary file.
831 class FunctionImportLegacyPass : public ModulePass {
832 public:
833   /// Pass identification, replacement for typeid
834   static char ID;
835 
836   /// Specify pass name for debug output
837   StringRef getPassName() const override { return "Function Importing"; }
838 
839   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
840 
841   bool runOnModule(Module &M) override {
842     if (skipModule(M))
843       return false;
844 
845     return doImportingForModule(M);
846   }
847 };
848 } // anonymous namespace
849 
850 PreservedAnalyses FunctionImportPass::run(Module &M,
851                                           ModuleAnalysisManager &AM) {
852   if (!doImportingForModule(M))
853     return PreservedAnalyses::all();
854 
855   return PreservedAnalyses::none();
856 }
857 
858 char FunctionImportLegacyPass::ID = 0;
859 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
860                 "Summary Based Function Import", false, false)
861 
862 namespace llvm {
863 Pass *createFunctionImportPass() {
864   return new FunctionImportLegacyPass();
865 }
866 }
867