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