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. We don't promote
322         // objects referenced by writeonly variable initializer, because
323         // we convert such variables initializers to "zeroinitializer".
324         // See processGlobalForThinLTO.
325         if (!Index.isWriteOnly(cast<GlobalVarSummary>(RefSummary.get())))
326           for (const auto &VI : RefSummary->refs())
327             for (const auto &RefFn : VI.getSummaryList())
328               MarkExported(VI, RefFn.get());
329         break;
330       }
331   }
332 }
333 
334 static const char *
335 getFailureName(FunctionImporter::ImportFailureReason Reason) {
336   switch (Reason) {
337   case FunctionImporter::ImportFailureReason::None:
338     return "None";
339   case FunctionImporter::ImportFailureReason::GlobalVar:
340     return "GlobalVar";
341   case FunctionImporter::ImportFailureReason::NotLive:
342     return "NotLive";
343   case FunctionImporter::ImportFailureReason::TooLarge:
344     return "TooLarge";
345   case FunctionImporter::ImportFailureReason::InterposableLinkage:
346     return "InterposableLinkage";
347   case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
348     return "LocalLinkageNotInModule";
349   case FunctionImporter::ImportFailureReason::NotEligible:
350     return "NotEligible";
351   case FunctionImporter::ImportFailureReason::NoInline:
352     return "NoInline";
353   }
354   llvm_unreachable("invalid reason");
355 }
356 
357 /// Compute the list of functions to import for a given caller. Mark these
358 /// imported functions and the symbols they reference in their source module as
359 /// exported from their source module.
360 static void computeImportForFunction(
361     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
362     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
363     SmallVectorImpl<EdgeInfo> &Worklist,
364     FunctionImporter::ImportMapTy &ImportList,
365     StringMap<FunctionImporter::ExportSetTy> *ExportLists,
366     FunctionImporter::ImportThresholdsTy &ImportThresholds) {
367   computeImportForReferencedGlobals(Summary, Index, DefinedGVSummaries,
368                                     ImportList, ExportLists);
369   static int ImportCount = 0;
370   for (auto &Edge : Summary.calls()) {
371     ValueInfo VI = Edge.first;
372     LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
373                       << "\n");
374 
375     if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
376       LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
377                         << " reached.\n");
378       continue;
379     }
380 
381     VI = updateValueInfoForIndirectCalls(Index, VI);
382     if (!VI)
383       continue;
384 
385     if (DefinedGVSummaries.count(VI.getGUID())) {
386       LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
387       continue;
388     }
389 
390     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
391       if (Hotness == CalleeInfo::HotnessType::Hot)
392         return ImportHotMultiplier;
393       if (Hotness == CalleeInfo::HotnessType::Cold)
394         return ImportColdMultiplier;
395       if (Hotness == CalleeInfo::HotnessType::Critical)
396         return ImportCriticalMultiplier;
397       return 1.0;
398     };
399 
400     const auto NewThreshold =
401         Threshold * GetBonusMultiplier(Edge.second.getHotness());
402 
403     auto IT = ImportThresholds.insert(std::make_pair(
404         VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
405     bool PreviouslyVisited = !IT.second;
406     auto &ProcessedThreshold = std::get<0>(IT.first->second);
407     auto &CalleeSummary = std::get<1>(IT.first->second);
408     auto &FailureInfo = std::get<2>(IT.first->second);
409 
410     bool IsHotCallsite =
411         Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
412     bool IsCriticalCallsite =
413         Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
414 
415     const FunctionSummary *ResolvedCalleeSummary = nullptr;
416     if (CalleeSummary) {
417       assert(PreviouslyVisited);
418       // Since the traversal of the call graph is DFS, we can revisit a function
419       // a second time with a higher threshold. In this case, it is added back
420       // to the worklist with the new threshold (so that its own callee chains
421       // can be considered with the higher threshold).
422       if (NewThreshold <= ProcessedThreshold) {
423         LLVM_DEBUG(
424             dbgs() << "ignored! Target was already imported with Threshold "
425                    << ProcessedThreshold << "\n");
426         continue;
427       }
428       // Update with new larger threshold.
429       ProcessedThreshold = NewThreshold;
430       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
431     } else {
432       // If we already rejected importing a callee at the same or higher
433       // threshold, don't waste time calling selectCallee.
434       if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
435         LLVM_DEBUG(
436             dbgs() << "ignored! Target was already rejected with Threshold "
437             << ProcessedThreshold << "\n");
438         if (PrintImportFailures) {
439           assert(FailureInfo &&
440                  "Expected FailureInfo for previously rejected candidate");
441           FailureInfo->Attempts++;
442         }
443         continue;
444       }
445 
446       FunctionImporter::ImportFailureReason Reason;
447       CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
448                                    Summary.modulePath(), Reason, VI.getGUID());
449       if (!CalleeSummary) {
450         // Update with new larger threshold if this was a retry (otherwise
451         // we would have already inserted with NewThreshold above). Also
452         // update failure info if requested.
453         if (PreviouslyVisited) {
454           ProcessedThreshold = NewThreshold;
455           if (PrintImportFailures) {
456             assert(FailureInfo &&
457                    "Expected FailureInfo for previously rejected candidate");
458             FailureInfo->Reason = Reason;
459             FailureInfo->Attempts++;
460             FailureInfo->MaxHotness =
461                 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
462           }
463         } else if (PrintImportFailures) {
464           assert(!FailureInfo &&
465                  "Expected no FailureInfo for newly rejected candidate");
466           FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
467               VI, Edge.second.getHotness(), Reason, 1);
468         }
469         LLVM_DEBUG(
470             dbgs() << "ignored! No qualifying callee with summary found.\n");
471         continue;
472       }
473 
474       // "Resolve" the summary
475       CalleeSummary = CalleeSummary->getBaseObject();
476       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
477 
478       assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
479              "selectCallee() didn't honor the threshold");
480 
481       auto ExportModulePath = ResolvedCalleeSummary->modulePath();
482       auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
483       // We previously decided to import this GUID definition if it was already
484       // inserted in the set of imports from the exporting module.
485       bool PreviouslyImported = !ILI.second;
486       if (!PreviouslyImported) {
487         NumImportedFunctionsThinLink++;
488         if (IsHotCallsite)
489           NumImportedHotFunctionsThinLink++;
490         if (IsCriticalCallsite)
491           NumImportedCriticalFunctionsThinLink++;
492       }
493 
494       // Make exports in the source module.
495       if (ExportLists) {
496         auto &ExportList = (*ExportLists)[ExportModulePath];
497         ExportList.insert(VI.getGUID());
498         if (!PreviouslyImported) {
499           // This is the first time this function was exported from its source
500           // module, so mark all functions and globals it references as exported
501           // to the outside if they are defined in the same source module.
502           // For efficiency, we unconditionally add all the referenced GUIDs
503           // to the ExportList for this module, and will prune out any not
504           // defined in the module later in a single pass.
505           for (auto &Edge : ResolvedCalleeSummary->calls()) {
506             auto CalleeGUID = Edge.first.getGUID();
507             ExportList.insert(CalleeGUID);
508           }
509           for (auto &Ref : ResolvedCalleeSummary->refs()) {
510             auto GUID = Ref.getGUID();
511             ExportList.insert(GUID);
512           }
513         }
514       }
515     }
516 
517     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
518       // Adjust the threshold for next level of imported functions.
519       // The threshold is different for hot callsites because we can then
520       // inline chains of hot calls.
521       if (IsHotCallsite)
522         return Threshold * ImportHotInstrFactor;
523       return Threshold * ImportInstrFactor;
524     };
525 
526     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
527 
528     ImportCount++;
529 
530     // Insert the newly imported function to the worklist.
531     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
532   }
533 }
534 
535 /// Given the list of globals defined in a module, compute the list of imports
536 /// as well as the list of "exports", i.e. the list of symbols referenced from
537 /// another module (that may require promotion).
538 static void ComputeImportForModule(
539     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
540     StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
541     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
542   // Worklist contains the list of function imported in this module, for which
543   // we will analyse the callees and may import further down the callgraph.
544   SmallVector<EdgeInfo, 128> Worklist;
545   FunctionImporter::ImportThresholdsTy ImportThresholds;
546 
547   // Populate the worklist with the import for the functions in the current
548   // module
549   for (auto &GVSummary : DefinedGVSummaries) {
550 #ifndef NDEBUG
551     // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
552     // so this map look up (and possibly others) can be avoided.
553     auto VI = Index.getValueInfo(GVSummary.first);
554 #endif
555     if (!Index.isGlobalValueLive(GVSummary.second)) {
556       LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
557       continue;
558     }
559     auto *FuncSummary =
560         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
561     if (!FuncSummary)
562       // Skip import for global variables
563       continue;
564     LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
565     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
566                              DefinedGVSummaries, Worklist, ImportList,
567                              ExportLists, ImportThresholds);
568   }
569 
570   // Process the newly imported functions and add callees to the worklist.
571   while (!Worklist.empty()) {
572     auto FuncInfo = Worklist.pop_back_val();
573     auto *Summary = std::get<0>(FuncInfo);
574     auto Threshold = std::get<1>(FuncInfo);
575 
576     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
577                              Worklist, ImportList, ExportLists,
578                              ImportThresholds);
579   }
580 
581   // Print stats about functions considered but rejected for importing
582   // when requested.
583   if (PrintImportFailures) {
584     dbgs() << "Missed imports into module " << ModName << "\n";
585     for (auto &I : ImportThresholds) {
586       auto &ProcessedThreshold = std::get<0>(I.second);
587       auto &CalleeSummary = std::get<1>(I.second);
588       auto &FailureInfo = std::get<2>(I.second);
589       if (CalleeSummary)
590         continue; // We are going to import.
591       assert(FailureInfo);
592       FunctionSummary *FS = nullptr;
593       if (!FailureInfo->VI.getSummaryList().empty())
594         FS = dyn_cast<FunctionSummary>(
595             FailureInfo->VI.getSummaryList()[0]->getBaseObject());
596       dbgs() << FailureInfo->VI
597              << ": Reason = " << getFailureName(FailureInfo->Reason)
598              << ", Threshold = " << ProcessedThreshold
599              << ", Size = " << (FS ? (int)FS->instCount() : -1)
600              << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
601              << ", Attempts = " << FailureInfo->Attempts << "\n";
602     }
603   }
604 }
605 
606 #ifndef NDEBUG
607 static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
608                                GlobalValue::GUID G) {
609   if (const auto &VI = Index.getValueInfo(G)) {
610     auto SL = VI.getSummaryList();
611     if (!SL.empty())
612       return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
613   }
614   return false;
615 }
616 
617 static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
618 
619 template <class T>
620 static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
621                                       T &Cont) {
622   unsigned NumGVS = 0;
623   for (auto &V : Cont)
624     if (isGlobalVarSummary(Index, getGUID(V)))
625       ++NumGVS;
626   return NumGVS;
627 }
628 #endif
629 
630 /// Compute all the import and export for every module using the Index.
631 void llvm::ComputeCrossModuleImport(
632     const ModuleSummaryIndex &Index,
633     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
634     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
635     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
636   // For each module that has function defined, compute the import/export lists.
637   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
638     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
639     LLVM_DEBUG(dbgs() << "Computing import for Module '"
640                       << DefinedGVSummaries.first() << "'\n");
641     ComputeImportForModule(DefinedGVSummaries.second, Index,
642                            DefinedGVSummaries.first(), ImportList,
643                            &ExportLists);
644   }
645 
646   // When computing imports we added all GUIDs referenced by anything
647   // imported from the module to its ExportList. Now we prune each ExportList
648   // of any not defined in that module. This is more efficient than checking
649   // while computing imports because some of the summary lists may be long
650   // due to linkonce (comdat) copies.
651   for (auto &ELI : ExportLists) {
652     const auto &DefinedGVSummaries =
653         ModuleToDefinedGVSummaries.lookup(ELI.first());
654     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
655       if (!DefinedGVSummaries.count(*EI))
656         EI = ELI.second.erase(EI);
657       else
658         ++EI;
659     }
660   }
661 
662 #ifndef NDEBUG
663   LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
664                     << " modules:\n");
665   for (auto &ModuleImports : ImportLists) {
666     auto ModName = ModuleImports.first();
667     auto &Exports = ExportLists[ModName];
668     unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
669     LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
670                       << Exports.size() - NumGVS << " functions and " << NumGVS
671                       << " vars. Imports from " << ModuleImports.second.size()
672                       << " modules.\n");
673     for (auto &Src : ModuleImports.second) {
674       auto SrcModName = Src.first();
675       unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
676       LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
677                         << " functions imported from " << SrcModName << "\n");
678       LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
679                         << " global vars imported from " << SrcModName << "\n");
680     }
681   }
682 #endif
683 }
684 
685 #ifndef NDEBUG
686 static void dumpImportListForModule(const ModuleSummaryIndex &Index,
687                                     StringRef ModulePath,
688                                     FunctionImporter::ImportMapTy &ImportList) {
689   LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
690                     << ImportList.size() << " modules.\n");
691   for (auto &Src : ImportList) {
692     auto SrcModName = Src.first();
693     unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
694     LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
695                       << " functions imported from " << SrcModName << "\n");
696     LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
697                       << SrcModName << "\n");
698   }
699 }
700 #endif
701 
702 /// Compute all the imports for the given module in the Index.
703 void llvm::ComputeCrossModuleImportForModule(
704     StringRef ModulePath, const ModuleSummaryIndex &Index,
705     FunctionImporter::ImportMapTy &ImportList) {
706   // Collect the list of functions this module defines.
707   // GUID -> Summary
708   GVSummaryMapTy FunctionSummaryMap;
709   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
710 
711   // Compute the import list for this module.
712   LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
713   ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
714 
715 #ifndef NDEBUG
716   dumpImportListForModule(Index, ModulePath, ImportList);
717 #endif
718 }
719 
720 // Mark all external summaries in Index for import into the given module.
721 // Used for distributed builds using a distributed index.
722 void llvm::ComputeCrossModuleImportForModuleFromIndex(
723     StringRef ModulePath, const ModuleSummaryIndex &Index,
724     FunctionImporter::ImportMapTy &ImportList) {
725   for (auto &GlobalList : Index) {
726     // Ignore entries for undefined references.
727     if (GlobalList.second.SummaryList.empty())
728       continue;
729 
730     auto GUID = GlobalList.first;
731     assert(GlobalList.second.SummaryList.size() == 1 &&
732            "Expected individual combined index to have one summary per GUID");
733     auto &Summary = GlobalList.second.SummaryList[0];
734     // Skip the summaries for the importing module. These are included to
735     // e.g. record required linkage changes.
736     if (Summary->modulePath() == ModulePath)
737       continue;
738     // Add an entry to provoke importing by thinBackend.
739     ImportList[Summary->modulePath()].insert(GUID);
740   }
741 #ifndef NDEBUG
742   dumpImportListForModule(Index, ModulePath, ImportList);
743 #endif
744 }
745 
746 void llvm::computeDeadSymbols(
747     ModuleSummaryIndex &Index,
748     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
749     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
750   assert(!Index.withGlobalValueDeadStripping());
751   if (!ComputeDead)
752     return;
753   if (GUIDPreservedSymbols.empty())
754     // Don't do anything when nothing is live, this is friendly with tests.
755     return;
756   unsigned LiveSymbols = 0;
757   SmallVector<ValueInfo, 128> Worklist;
758   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
759   for (auto GUID : GUIDPreservedSymbols) {
760     ValueInfo VI = Index.getValueInfo(GUID);
761     if (!VI)
762       continue;
763     for (auto &S : VI.getSummaryList())
764       S->setLive(true);
765   }
766 
767   // Add values flagged in the index as live roots to the worklist.
768   for (const auto &Entry : Index) {
769     auto VI = Index.getValueInfo(Entry);
770     for (auto &S : Entry.second.SummaryList)
771       if (S->isLive()) {
772         LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
773         Worklist.push_back(VI);
774         ++LiveSymbols;
775         break;
776       }
777   }
778 
779   // Make value live and add it to the worklist if it was not live before.
780   auto visit = [&](ValueInfo VI, bool IsAliasee) {
781     // FIXME: If we knew which edges were created for indirect call profiles,
782     // we could skip them here. Any that are live should be reached via
783     // other edges, e.g. reference edges. Otherwise, using a profile collected
784     // on a slightly different binary might provoke preserving, importing
785     // and ultimately promoting calls to functions not linked into this
786     // binary, which increases the binary size unnecessarily. Note that
787     // if this code changes, the importer needs to change so that edges
788     // to functions marked dead are skipped.
789     VI = updateValueInfoForIndirectCalls(Index, VI);
790     if (!VI)
791       return;
792 
793     if (llvm::any_of(VI.getSummaryList(),
794                      [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
795                        return S->isLive();
796                      }))
797       return;
798 
799     // We only keep live symbols that are known to be non-prevailing if any are
800     // available_externally, linkonceodr, weakodr. Those symbols are discarded
801     // later in the EliminateAvailableExternally pass and setting them to
802     // not-live could break downstreams users of liveness information (PR36483)
803     // or limit optimization opportunities.
804     if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
805       bool KeepAliveLinkage = false;
806       bool Interposable = false;
807       for (auto &S : VI.getSummaryList()) {
808         if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
809             S->linkage() == GlobalValue::WeakODRLinkage ||
810             S->linkage() == GlobalValue::LinkOnceODRLinkage)
811           KeepAliveLinkage = true;
812         else if (GlobalValue::isInterposableLinkage(S->linkage()))
813           Interposable = true;
814       }
815 
816       if (!IsAliasee) {
817         if (!KeepAliveLinkage)
818           return;
819 
820         if (Interposable)
821           report_fatal_error(
822               "Interposable and available_externally/linkonce_odr/weak_odr "
823               "symbol");
824       }
825     }
826 
827     for (auto &S : VI.getSummaryList())
828       S->setLive(true);
829     ++LiveSymbols;
830     Worklist.push_back(VI);
831   };
832 
833   while (!Worklist.empty()) {
834     auto VI = Worklist.pop_back_val();
835     for (auto &Summary : VI.getSummaryList()) {
836       if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
837         // If this is an alias, visit the aliasee VI to ensure that all copies
838         // are marked live and it is added to the worklist for further
839         // processing of its references.
840         visit(AS->getAliaseeVI(), true);
841         continue;
842       }
843 
844       Summary->setLive(true);
845       for (auto Ref : Summary->refs())
846         visit(Ref, false);
847       if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
848         for (auto Call : FS->calls())
849           visit(Call.first, false);
850     }
851   }
852   Index.setWithGlobalValueDeadStripping();
853 
854   unsigned DeadSymbols = Index.size() - LiveSymbols;
855   LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
856                     << " symbols Dead \n");
857   NumDeadSymbols += DeadSymbols;
858   NumLiveSymbols += LiveSymbols;
859 }
860 
861 // Compute dead symbols and propagate constants in combined index.
862 void llvm::computeDeadSymbolsWithConstProp(
863     ModuleSummaryIndex &Index,
864     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
865     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
866     bool ImportEnabled) {
867   computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
868   if (ImportEnabled) {
869     Index.propagateAttributes(GUIDPreservedSymbols);
870   } else {
871     // If import is disabled we should drop read/write-only attribute
872     // from all summaries to prevent internalization.
873     for (auto &P : Index)
874       for (auto &S : P.second.SummaryList)
875         if (auto *GVS = dyn_cast<GlobalVarSummary>(S.get())) {
876           GVS->setReadOnly(false);
877           GVS->setWriteOnly(false);
878         }
879   }
880   Index.setWithAttributePropagation();
881 }
882 
883 /// Compute the set of summaries needed for a ThinLTO backend compilation of
884 /// \p ModulePath.
885 void llvm::gatherImportedSummariesForModule(
886     StringRef ModulePath,
887     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
888     const FunctionImporter::ImportMapTy &ImportList,
889     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
890   // Include all summaries from the importing module.
891   ModuleToSummariesForIndex[ModulePath] =
892       ModuleToDefinedGVSummaries.lookup(ModulePath);
893   // Include summaries for imports.
894   for (auto &ILI : ImportList) {
895     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
896     const auto &DefinedGVSummaries =
897         ModuleToDefinedGVSummaries.lookup(ILI.first());
898     for (auto &GI : ILI.second) {
899       const auto &DS = DefinedGVSummaries.find(GI);
900       assert(DS != DefinedGVSummaries.end() &&
901              "Expected a defined summary for imported global value");
902       SummariesForIndex[GI] = DS->second;
903     }
904   }
905 }
906 
907 /// Emit the files \p ModulePath will import from into \p OutputFilename.
908 std::error_code llvm::EmitImportsFiles(
909     StringRef ModulePath, StringRef OutputFilename,
910     const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
911   std::error_code EC;
912   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
913   if (EC)
914     return EC;
915   for (auto &ILI : ModuleToSummariesForIndex)
916     // The ModuleToSummariesForIndex map includes an entry for the current
917     // Module (needed for writing out the index files). We don't want to
918     // include it in the imports file, however, so filter it out.
919     if (ILI.first != ModulePath)
920       ImportsOS << ILI.first << "\n";
921   return std::error_code();
922 }
923 
924 bool llvm::convertToDeclaration(GlobalValue &GV) {
925   LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
926                     << "\n");
927   if (Function *F = dyn_cast<Function>(&GV)) {
928     F->deleteBody();
929     F->clearMetadata();
930     F->setComdat(nullptr);
931   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
932     V->setInitializer(nullptr);
933     V->setLinkage(GlobalValue::ExternalLinkage);
934     V->clearMetadata();
935     V->setComdat(nullptr);
936   } else {
937     GlobalValue *NewGV;
938     if (GV.getValueType()->isFunctionTy())
939       NewGV =
940           Function::Create(cast<FunctionType>(GV.getValueType()),
941                            GlobalValue::ExternalLinkage, GV.getAddressSpace(),
942                            "", GV.getParent());
943     else
944       NewGV =
945           new GlobalVariable(*GV.getParent(), GV.getValueType(),
946                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
947                              /*init*/ nullptr, "",
948                              /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
949                              GV.getType()->getAddressSpace());
950     NewGV->takeName(&GV);
951     GV.replaceAllUsesWith(NewGV);
952     return false;
953   }
954   return true;
955 }
956 
957 /// Fixup prevailing symbol linkages in \p TheModule based on summary analysis.
958 void llvm::thinLTOResolvePrevailingInModule(
959     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
960   auto updateLinkage = [&](GlobalValue &GV) {
961     // See if the global summary analysis computed a new resolved linkage.
962     const auto &GS = DefinedGlobals.find(GV.getGUID());
963     if (GS == DefinedGlobals.end())
964       return;
965     auto NewLinkage = GS->second->linkage();
966     if (NewLinkage == GV.getLinkage())
967       return;
968     if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
969         // Don't internalize anything here, because the code below
970         // lacks necessary correctness checks. Leave this job to
971         // LLVM 'internalize' pass.
972         GlobalValue::isLocalLinkage(NewLinkage) ||
973         // In case it was dead and already converted to declaration.
974         GV.isDeclaration())
975       return;
976 
977     // Check for a non-prevailing def that has interposable linkage
978     // (e.g. non-odr weak or linkonce). In that case we can't simply
979     // convert to available_externally, since it would lose the
980     // interposable property and possibly get inlined. Simply drop
981     // the definition in that case.
982     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
983         GlobalValue::isInterposableLinkage(GV.getLinkage())) {
984       if (!convertToDeclaration(GV))
985         // FIXME: Change this to collect replaced GVs and later erase
986         // them from the parent module once thinLTOResolvePrevailingGUID is
987         // changed to enable this for aliases.
988         llvm_unreachable("Expected GV to be converted");
989     } else {
990       // If all copies of the original symbol had global unnamed addr and
991       // linkonce_odr linkage, it should be an auto hide symbol. In that case
992       // the thin link would have marked it as CanAutoHide. Add hidden visibility
993       // to the symbol to preserve the property.
994       if (NewLinkage == GlobalValue::WeakODRLinkage &&
995           GS->second->canAutoHide()) {
996         assert(GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr());
997         GV.setVisibility(GlobalValue::HiddenVisibility);
998       }
999 
1000       LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
1001                         << "` from " << GV.getLinkage() << " to " << NewLinkage
1002                         << "\n");
1003       GV.setLinkage(NewLinkage);
1004     }
1005     // Remove declarations from comdats, including available_externally
1006     // as this is a declaration for the linker, and will be dropped eventually.
1007     // It is illegal for comdats to contain declarations.
1008     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
1009     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
1010       GO->setComdat(nullptr);
1011   };
1012 
1013   // Process functions and global now
1014   for (auto &GV : TheModule)
1015     updateLinkage(GV);
1016   for (auto &GV : TheModule.globals())
1017     updateLinkage(GV);
1018   for (auto &GV : TheModule.aliases())
1019     updateLinkage(GV);
1020 }
1021 
1022 /// Run internalization on \p TheModule based on symmary analysis.
1023 void llvm::thinLTOInternalizeModule(Module &TheModule,
1024                                     const GVSummaryMapTy &DefinedGlobals) {
1025   // Declare a callback for the internalize pass that will ask for every
1026   // candidate GlobalValue if it can be internalized or not.
1027   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
1028     // Lookup the linkage recorded in the summaries during global analysis.
1029     auto GS = DefinedGlobals.find(GV.getGUID());
1030     if (GS == DefinedGlobals.end()) {
1031       // Must have been promoted (possibly conservatively). Find original
1032       // name so that we can access the correct summary and see if it can
1033       // be internalized again.
1034       // FIXME: Eventually we should control promotion instead of promoting
1035       // and internalizing again.
1036       StringRef OrigName =
1037           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
1038       std::string OrigId = GlobalValue::getGlobalIdentifier(
1039           OrigName, GlobalValue::InternalLinkage,
1040           TheModule.getSourceFileName());
1041       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
1042       if (GS == DefinedGlobals.end()) {
1043         // Also check the original non-promoted non-globalized name. In some
1044         // cases a preempted weak value is linked in as a local copy because
1045         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
1046         // In that case, since it was originally not a local value, it was
1047         // recorded in the index using the original name.
1048         // FIXME: This may not be needed once PR27866 is fixed.
1049         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
1050         assert(GS != DefinedGlobals.end());
1051       }
1052     }
1053     return !GlobalValue::isLocalLinkage(GS->second->linkage());
1054   };
1055 
1056   // FIXME: See if we can just internalize directly here via linkage changes
1057   // based on the index, rather than invoking internalizeModule.
1058   internalizeModule(TheModule, MustPreserveGV);
1059 }
1060 
1061 /// Make alias a clone of its aliasee.
1062 static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
1063   Function *Fn = cast<Function>(GA->getBaseObject());
1064 
1065   ValueToValueMapTy VMap;
1066   Function *NewFn = CloneFunction(Fn, VMap);
1067   // Clone should use the original alias's linkage, visibility and name, and we
1068   // ensure all uses of alias instead use the new clone (casted if necessary).
1069   NewFn->setLinkage(GA->getLinkage());
1070   NewFn->setVisibility(GA->getVisibility());
1071   GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
1072   NewFn->takeName(GA);
1073   return NewFn;
1074 }
1075 
1076 // Internalize values that we marked with specific attribute
1077 // in processGlobalForThinLTO.
1078 static void internalizeGVsAfterImport(Module &M) {
1079   for (auto &GV : M.globals())
1080     // Skip GVs which have been converted to declarations
1081     // by dropDeadSymbols.
1082     if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
1083       GV.setLinkage(GlobalValue::InternalLinkage);
1084       GV.setVisibility(GlobalValue::DefaultVisibility);
1085     }
1086 }
1087 
1088 // Automatically import functions in Module \p DestModule based on the summaries
1089 // index.
1090 Expected<bool> FunctionImporter::importFunctions(
1091     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
1092   LLVM_DEBUG(dbgs() << "Starting import for Module "
1093                     << DestModule.getModuleIdentifier() << "\n");
1094   unsigned ImportedCount = 0, ImportedGVCount = 0;
1095 
1096   IRMover Mover(DestModule);
1097   // Do the actual import of functions now, one Module at a time
1098   std::set<StringRef> ModuleNameOrderedList;
1099   for (auto &FunctionsToImportPerModule : ImportList) {
1100     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
1101   }
1102   for (auto &Name : ModuleNameOrderedList) {
1103     // Get the module for the import
1104     const auto &FunctionsToImportPerModule = ImportList.find(Name);
1105     assert(FunctionsToImportPerModule != ImportList.end());
1106     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
1107     if (!SrcModuleOrErr)
1108       return SrcModuleOrErr.takeError();
1109     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
1110     assert(&DestModule.getContext() == &SrcModule->getContext() &&
1111            "Context mismatch");
1112 
1113     // If modules were created with lazy metadata loading, materialize it
1114     // now, before linking it (otherwise this will be a noop).
1115     if (Error Err = SrcModule->materializeMetadata())
1116       return std::move(Err);
1117 
1118     auto &ImportGUIDs = FunctionsToImportPerModule->second;
1119     // Find the globals to import
1120     SetVector<GlobalValue *> GlobalsToImport;
1121     for (Function &F : *SrcModule) {
1122       if (!F.hasName())
1123         continue;
1124       auto GUID = F.getGUID();
1125       auto Import = ImportGUIDs.count(GUID);
1126       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
1127                         << GUID << " " << F.getName() << " from "
1128                         << SrcModule->getSourceFileName() << "\n");
1129       if (Import) {
1130         if (Error Err = F.materialize())
1131           return std::move(Err);
1132         if (EnableImportMetadata) {
1133           // Add 'thinlto_src_module' metadata for statistics and debugging.
1134           F.setMetadata(
1135               "thinlto_src_module",
1136               MDNode::get(DestModule.getContext(),
1137                           {MDString::get(DestModule.getContext(),
1138                                          SrcModule->getSourceFileName())}));
1139         }
1140         GlobalsToImport.insert(&F);
1141       }
1142     }
1143     for (GlobalVariable &GV : SrcModule->globals()) {
1144       if (!GV.hasName())
1145         continue;
1146       auto GUID = GV.getGUID();
1147       auto Import = ImportGUIDs.count(GUID);
1148       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
1149                         << GUID << " " << GV.getName() << " from "
1150                         << SrcModule->getSourceFileName() << "\n");
1151       if (Import) {
1152         if (Error Err = GV.materialize())
1153           return std::move(Err);
1154         ImportedGVCount += GlobalsToImport.insert(&GV);
1155       }
1156     }
1157     for (GlobalAlias &GA : SrcModule->aliases()) {
1158       if (!GA.hasName())
1159         continue;
1160       auto GUID = GA.getGUID();
1161       auto Import = ImportGUIDs.count(GUID);
1162       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
1163                         << GUID << " " << GA.getName() << " from "
1164                         << SrcModule->getSourceFileName() << "\n");
1165       if (Import) {
1166         if (Error Err = GA.materialize())
1167           return std::move(Err);
1168         // Import alias as a copy of its aliasee.
1169         GlobalObject *Base = GA.getBaseObject();
1170         if (Error Err = Base->materialize())
1171           return std::move(Err);
1172         auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
1173         LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
1174                           << " " << Base->getName() << " from "
1175                           << SrcModule->getSourceFileName() << "\n");
1176         if (EnableImportMetadata) {
1177           // Add 'thinlto_src_module' metadata for statistics and debugging.
1178           Fn->setMetadata(
1179               "thinlto_src_module",
1180               MDNode::get(DestModule.getContext(),
1181                           {MDString::get(DestModule.getContext(),
1182                                          SrcModule->getSourceFileName())}));
1183         }
1184         GlobalsToImport.insert(Fn);
1185       }
1186     }
1187 
1188     // Upgrade debug info after we're done materializing all the globals and we
1189     // have loaded all the required metadata!
1190     UpgradeDebugInfo(*SrcModule);
1191 
1192     // Link in the specified functions.
1193     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
1194       return true;
1195 
1196     if (PrintImports) {
1197       for (const auto *GV : GlobalsToImport)
1198         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
1199                << " from " << SrcModule->getSourceFileName() << "\n";
1200     }
1201 
1202     if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
1203                    [](GlobalValue &, IRMover::ValueAdder) {},
1204                    /*IsPerformingImport=*/true))
1205       report_fatal_error("Function Import: link error");
1206 
1207     ImportedCount += GlobalsToImport.size();
1208     NumImportedModules++;
1209   }
1210 
1211   internalizeGVsAfterImport(DestModule);
1212 
1213   NumImportedFunctions += (ImportedCount - ImportedGVCount);
1214   NumImportedGlobalVars += ImportedGVCount;
1215 
1216   LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
1217                     << " functions for Module "
1218                     << DestModule.getModuleIdentifier() << "\n");
1219   LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
1220                     << " global variables for Module "
1221                     << DestModule.getModuleIdentifier() << "\n");
1222   return ImportedCount;
1223 }
1224 
1225 static bool doImportingForModule(Module &M) {
1226   if (SummaryFile.empty())
1227     report_fatal_error("error: -function-import requires -summary-file\n");
1228   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
1229       getModuleSummaryIndexForFile(SummaryFile);
1230   if (!IndexPtrOrErr) {
1231     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
1232                           "Error loading file '" + SummaryFile + "': ");
1233     return false;
1234   }
1235   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
1236 
1237   // First step is collecting the import list.
1238   FunctionImporter::ImportMapTy ImportList;
1239   // If requested, simply import all functions in the index. This is used
1240   // when testing distributed backend handling via the opt tool, when
1241   // we have distributed indexes containing exactly the summaries to import.
1242   if (ImportAllIndex)
1243     ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
1244                                                ImportList);
1245   else
1246     ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
1247                                       ImportList);
1248 
1249   // Conservatively mark all internal values as promoted. This interface is
1250   // only used when doing importing via the function importing pass. The pass
1251   // is only enabled when testing importing via the 'opt' tool, which does
1252   // not do the ThinLink that would normally determine what values to promote.
1253   for (auto &I : *Index) {
1254     for (auto &S : I.second.SummaryList) {
1255       if (GlobalValue::isLocalLinkage(S->linkage()))
1256         S->setLinkage(GlobalValue::ExternalLinkage);
1257     }
1258   }
1259 
1260   // Next we need to promote to global scope and rename any local values that
1261   // are potentially exported to other modules.
1262   if (renameModuleForThinLTO(M, *Index, nullptr)) {
1263     errs() << "Error renaming module\n";
1264     return false;
1265   }
1266 
1267   // Perform the import now.
1268   auto ModuleLoader = [&M](StringRef Identifier) {
1269     return loadFile(Identifier, M.getContext());
1270   };
1271   FunctionImporter Importer(*Index, ModuleLoader);
1272   Expected<bool> Result = Importer.importFunctions(M, ImportList);
1273 
1274   // FIXME: Probably need to propagate Errors through the pass manager.
1275   if (!Result) {
1276     logAllUnhandledErrors(Result.takeError(), errs(),
1277                           "Error importing module: ");
1278     return false;
1279   }
1280 
1281   return *Result;
1282 }
1283 
1284 namespace {
1285 
1286 /// Pass that performs cross-module function import provided a summary file.
1287 class FunctionImportLegacyPass : public ModulePass {
1288 public:
1289   /// Pass identification, replacement for typeid
1290   static char ID;
1291 
1292   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
1293 
1294   /// Specify pass name for debug output
1295   StringRef getPassName() const override { return "Function Importing"; }
1296 
1297   bool runOnModule(Module &M) override {
1298     if (skipModule(M))
1299       return false;
1300 
1301     return doImportingForModule(M);
1302   }
1303 };
1304 
1305 } // end anonymous namespace
1306 
1307 PreservedAnalyses FunctionImportPass::run(Module &M,
1308                                           ModuleAnalysisManager &AM) {
1309   if (!doImportingForModule(M))
1310     return PreservedAnalyses::all();
1311 
1312   return PreservedAnalyses::none();
1313 }
1314 
1315 char FunctionImportLegacyPass::ID = 0;
1316 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
1317                 "Summary Based Function Import", false, false)
1318 
1319 namespace llvm {
1320 
1321 Pass *createFunctionImportPass() {
1322   return new FunctionImportLegacyPass();
1323 }
1324 
1325 } // end namespace llvm
1326