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