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