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