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