xref: /llvm-project/llvm/lib/Transforms/IPO/FunctionImport.cpp (revision ca48b015a1719ba7be2d357056f348473d495d3d)
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/StringRef.h"
20 #include "llvm/Bitcode/BitcodeReader.h"
21 #include "llvm/IR/AutoUpgrade.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GlobalAlias.h"
24 #include "llvm/IR/GlobalObject.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Metadata.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ModuleSummaryIndex.h"
30 #include "llvm/IRReader/IRReader.h"
31 #include "llvm/Linker/IRMover.h"
32 #include "llvm/ProfileData/PGOCtxProfReader.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Errc.h"
37 #include "llvm/Support/Error.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/JSON.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Transforms/IPO/Internalize.h"
44 #include "llvm/Transforms/Utils/Cloning.h"
45 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
46 #include "llvm/Transforms/Utils/ValueMapper.h"
47 #include <cassert>
48 #include <memory>
49 #include <set>
50 #include <string>
51 #include <system_error>
52 #include <tuple>
53 #include <utility>
54 
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "function-import"
58 
59 STATISTIC(NumImportedFunctionsThinLink,
60           "Number of functions thin link decided to import");
61 STATISTIC(NumImportedHotFunctionsThinLink,
62           "Number of hot functions thin link decided to import");
63 STATISTIC(NumImportedCriticalFunctionsThinLink,
64           "Number of critical functions thin link decided to import");
65 STATISTIC(NumImportedGlobalVarsThinLink,
66           "Number of global variables thin link decided to import");
67 STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
68 STATISTIC(NumImportedGlobalVars,
69           "Number of global variables imported in backend");
70 STATISTIC(NumImportedModules, "Number of modules imported from");
71 STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
72 STATISTIC(NumLiveSymbols, "Number of live symbols in index");
73 
74 /// Limit on instruction count of imported functions.
75 static cl::opt<unsigned> ImportInstrLimit(
76     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
77     cl::desc("Only import functions with less than N instructions"));
78 
79 static cl::opt<int> ImportCutoff(
80     "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
81     cl::desc("Only import first N functions if N>=0 (default -1)"));
82 
83 static cl::opt<bool>
84     ForceImportAll("force-import-all", cl::init(false), cl::Hidden,
85                    cl::desc("Import functions with noinline attribute"));
86 
87 static cl::opt<float>
88     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
89                       cl::Hidden, cl::value_desc("x"),
90                       cl::desc("As we import functions, multiply the "
91                                "`import-instr-limit` threshold by this factor "
92                                "before processing newly imported functions"));
93 
94 static cl::opt<float> ImportHotInstrFactor(
95     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
96     cl::value_desc("x"),
97     cl::desc("As we import functions called from hot callsite, multiply the "
98              "`import-instr-limit` threshold by this factor "
99              "before processing newly imported functions"));
100 
101 static cl::opt<float> ImportHotMultiplier(
102     "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
103     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
104 
105 static cl::opt<float> ImportCriticalMultiplier(
106     "import-critical-multiplier", cl::init(100.0), cl::Hidden,
107     cl::value_desc("x"),
108     cl::desc(
109         "Multiply the `import-instr-limit` threshold for critical callsites"));
110 
111 // FIXME: This multiplier was not really tuned up.
112 static cl::opt<float> ImportColdMultiplier(
113     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
114     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
115 
116 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
117                                   cl::desc("Print imported functions"));
118 
119 static cl::opt<bool> PrintImportFailures(
120     "print-import-failures", cl::init(false), cl::Hidden,
121     cl::desc("Print information for functions rejected for importing"));
122 
123 static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
124                                  cl::desc("Compute dead symbols"));
125 
126 static cl::opt<bool> EnableImportMetadata(
127     "enable-import-metadata", cl::init(false), cl::Hidden,
128     cl::desc("Enable import metadata like 'thinlto_src_module' and "
129              "'thinlto_src_file'"));
130 
131 /// Summary file to use for function importing when using -function-import from
132 /// the command line.
133 static cl::opt<std::string>
134     SummaryFile("summary-file",
135                 cl::desc("The summary file to use for function importing."));
136 
137 /// Used when testing importing from distributed indexes via opt
138 // -function-import.
139 static cl::opt<bool>
140     ImportAllIndex("import-all-index",
141                    cl::desc("Import all external functions in index."));
142 
143 /// This is a test-only option.
144 /// If this option is enabled, the ThinLTO indexing step will import each
145 /// function declaration as a fallback. In a real build this may increase ram
146 /// usage of the indexing step unnecessarily.
147 /// TODO: Implement selective import (based on combined summary analysis) to
148 /// ensure the imported function has a use case in the postlink pipeline.
149 static cl::opt<bool> ImportDeclaration(
150     "import-declaration", cl::init(false), cl::Hidden,
151     cl::desc("If true, import function declaration as fallback if the function "
152              "definition is not imported."));
153 
154 /// Pass a workload description file - an example of workload would be the
155 /// functions executed to satisfy a RPC request. A workload is defined by a root
156 /// function and the list of functions that are (frequently) needed to satisfy
157 /// it. The module that defines the root will have all those functions imported.
158 /// The file contains a JSON dictionary. The keys are root functions, the values
159 /// are lists of functions to import in the module defining the root. It is
160 /// assumed -funique-internal-linkage-names was used, thus ensuring function
161 /// names are unique even for local linkage ones.
162 static cl::opt<std::string> WorkloadDefinitions(
163     "thinlto-workload-def",
164     cl::desc("Pass a workload definition. This is a file containing a JSON "
165              "dictionary. The keys are root functions, the values are lists of "
166              "functions to import in the module defining the root. It is "
167              "assumed -funique-internal-linkage-names was used, to ensure "
168              "local linkage functions have unique names. For example: \n"
169              "{\n"
170              "  \"rootFunction_1\": [\"function_to_import_1\", "
171              "\"function_to_import_2\"], \n"
172              "  \"rootFunction_2\": [\"function_to_import_3\", "
173              "\"function_to_import_4\"] \n"
174              "}"),
175     cl::Hidden);
176 
177 extern cl::opt<std::string> UseCtxProfile;
178 
179 namespace llvm {
180 extern cl::opt<bool> EnableMemProfContextDisambiguation;
181 }
182 
183 // Load lazily a module from \p FileName in \p Context.
184 static std::unique_ptr<Module> loadFile(const std::string &FileName,
185                                         LLVMContext &Context) {
186   SMDiagnostic Err;
187   LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
188   // Metadata isn't loaded until functions are imported, to minimize
189   // the memory overhead.
190   std::unique_ptr<Module> Result =
191       getLazyIRFileModule(FileName, Err, Context,
192                           /* ShouldLazyLoadMetadata = */ true);
193   if (!Result) {
194     Err.print("function-import", errs());
195     report_fatal_error("Abort");
196   }
197 
198   return Result;
199 }
200 
201 static bool shouldSkipLocalInAnotherModule(const GlobalValueSummary *RefSummary,
202                                            size_t NumDefs,
203                                            StringRef ImporterModule) {
204   // We can import a local when there is one definition.
205   if (NumDefs == 1)
206     return false;
207   // In other cases, make sure we import the copy in the caller's module if the
208   // referenced value has local linkage. The only time a local variable can
209   // share an entry in the index is if there is a local with the same name in
210   // another module that had the same source file name (in a different
211   // directory), where each was compiled in their own directory so there was not
212   // distinguishing path.
213   return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
214          RefSummary->modulePath() != ImporterModule;
215 }
216 
217 /// Given a list of possible callee implementation for a call site, qualify the
218 /// legality of importing each. The return is a range of pairs. Each pair
219 /// corresponds to a candidate. The first value is the ImportFailureReason for
220 /// that candidate, the second is the candidate.
221 static auto qualifyCalleeCandidates(
222     const ModuleSummaryIndex &Index,
223     ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
224     StringRef CallerModulePath) {
225   return llvm::map_range(
226       CalleeSummaryList,
227       [&Index, CalleeSummaryList,
228        CallerModulePath](const std::unique_ptr<GlobalValueSummary> &SummaryPtr)
229           -> std::pair<FunctionImporter::ImportFailureReason,
230                        const GlobalValueSummary *> {
231         auto *GVSummary = SummaryPtr.get();
232         if (!Index.isGlobalValueLive(GVSummary))
233           return {FunctionImporter::ImportFailureReason::NotLive, GVSummary};
234 
235         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
236           return {FunctionImporter::ImportFailureReason::InterposableLinkage,
237                   GVSummary};
238 
239         auto *Summary = dyn_cast<FunctionSummary>(GVSummary->getBaseObject());
240 
241         // Ignore any callees that aren't actually functions. This could happen
242         // in the case of GUID hash collisions. It could also happen in theory
243         // for SamplePGO profiles collected on old versions of the code after
244         // renaming, since we synthesize edges to any inlined callees appearing
245         // in the profile.
246         if (!Summary)
247           return {FunctionImporter::ImportFailureReason::GlobalVar, GVSummary};
248 
249         // If this is a local function, make sure we import the copy in the
250         // caller's module. The only time a local function can share an entry in
251         // the index is if there is a local with the same name in another module
252         // that had the same source file name (in a different directory), where
253         // each was compiled in their own directory so there was not
254         // distinguishing path.
255         // If the local function is from another module, it must be a reference
256         // due to indirect call profile data since a function pointer can point
257         // to a local in another module. Do the import from another module if
258         // there is only one entry in the list or when all files in the program
259         // are compiled with full path - in both cases the local function has
260         // unique PGO name and GUID.
261         if (shouldSkipLocalInAnotherModule(Summary, CalleeSummaryList.size(),
262                                            CallerModulePath))
263           return {
264               FunctionImporter::ImportFailureReason::LocalLinkageNotInModule,
265               GVSummary};
266 
267         // Skip if it isn't legal to import (e.g. may reference unpromotable
268         // locals).
269         if (Summary->notEligibleToImport())
270           return {FunctionImporter::ImportFailureReason::NotEligible,
271                   GVSummary};
272 
273         return {FunctionImporter::ImportFailureReason::None, GVSummary};
274       });
275 }
276 
277 /// Given a list of possible callee implementation for a call site, select one
278 /// that fits the \p Threshold for function definition import. If none are
279 /// found, the Reason will give the last reason for the failure (last, in the
280 /// order of CalleeSummaryList entries). While looking for a callee definition,
281 /// sets \p TooLargeOrNoInlineSummary to the last seen too-large or noinline
282 /// candidate; other modules may want to know the function summary or
283 /// declaration even if a definition is not needed.
284 ///
285 /// FIXME: select "best" instead of first that fits. But what is "best"?
286 /// - The smallest: more likely to be inlined.
287 /// - The one with the least outgoing edges (already well optimized).
288 /// - One from a module already being imported from in order to reduce the
289 ///   number of source modules parsed/linked.
290 /// - One that has PGO data attached.
291 /// - [insert you fancy metric here]
292 static const GlobalValueSummary *
293 selectCallee(const ModuleSummaryIndex &Index,
294              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
295              unsigned Threshold, StringRef CallerModulePath,
296              const GlobalValueSummary *&TooLargeOrNoInlineSummary,
297              FunctionImporter::ImportFailureReason &Reason) {
298   // Records the last summary with reason noinline or too-large.
299   TooLargeOrNoInlineSummary = nullptr;
300   auto QualifiedCandidates =
301       qualifyCalleeCandidates(Index, CalleeSummaryList, CallerModulePath);
302   for (auto QualifiedValue : QualifiedCandidates) {
303     Reason = QualifiedValue.first;
304     // Skip a summary if its import is not (proved to be) legal.
305     if (Reason != FunctionImporter::ImportFailureReason::None)
306       continue;
307     auto *Summary =
308         cast<FunctionSummary>(QualifiedValue.second->getBaseObject());
309 
310     // Don't bother importing the definition if the chance of inlining it is
311     // not high enough (except under `--force-import-all`).
312     if ((Summary->instCount() > Threshold) && !Summary->fflags().AlwaysInline &&
313         !ForceImportAll) {
314       TooLargeOrNoInlineSummary = Summary;
315       Reason = FunctionImporter::ImportFailureReason::TooLarge;
316       continue;
317     }
318 
319     // Don't bother importing the definition if we can't inline it anyway.
320     if (Summary->fflags().NoInline && !ForceImportAll) {
321       TooLargeOrNoInlineSummary = Summary;
322       Reason = FunctionImporter::ImportFailureReason::NoInline;
323       continue;
324     }
325 
326     return Summary;
327   }
328   return nullptr;
329 }
330 
331 namespace {
332 
333 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */>;
334 
335 } // anonymous namespace
336 
337 FunctionImporter::AddDefinitionStatus
338 FunctionImporter::addDefinition(ImportMapTy &ImportList, StringRef FromModule,
339                                 GlobalValue::GUID GUID) {
340   auto [It, Inserted] =
341       ImportList[FromModule].try_emplace(GUID, GlobalValueSummary::Definition);
342   if (Inserted)
343     return AddDefinitionStatus::Inserted;
344   if (It->second == GlobalValueSummary::Definition)
345     return AddDefinitionStatus::NoChange;
346   It->second = GlobalValueSummary::Definition;
347   return AddDefinitionStatus::ChangedToDefinition;
348 }
349 
350 void FunctionImporter::maybeAddDeclaration(ImportMapTy &ImportList,
351                                            StringRef FromModule,
352                                            GlobalValue::GUID GUID) {
353   ImportList[FromModule].try_emplace(GUID, GlobalValueSummary::Declaration);
354 }
355 
356 /// Import globals referenced by a function or other globals that are being
357 /// imported, if importing such global is possible.
358 class GlobalsImporter final {
359   const ModuleSummaryIndex &Index;
360   const GVSummaryMapTy &DefinedGVSummaries;
361   function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
362       IsPrevailing;
363   FunctionImporter::ImportMapTy &ImportList;
364   DenseMap<StringRef, FunctionImporter::ExportSetTy> *const ExportLists;
365 
366   bool shouldImportGlobal(const ValueInfo &VI) {
367     const auto &GVS = DefinedGVSummaries.find(VI.getGUID());
368     if (GVS == DefinedGVSummaries.end())
369       return true;
370     // We should not skip import if the module contains a non-prevailing
371     // definition with interposable linkage type. This is required for
372     // correctness in the situation where there is a prevailing def available
373     // for import and marked read-only. In this case, the non-prevailing def
374     // will be converted to a declaration, while the prevailing one becomes
375     // internal, thus no definitions will be available for linking. In order to
376     // prevent undefined symbol link error, the prevailing definition must be
377     // imported.
378     // FIXME: Consider adding a check that the suitable prevailing definition
379     // exists and marked read-only.
380     if (VI.getSummaryList().size() > 1 &&
381         GlobalValue::isInterposableLinkage(GVS->second->linkage()) &&
382         !IsPrevailing(VI.getGUID(), GVS->second))
383       return true;
384 
385     return false;
386   }
387 
388   void
389   onImportingSummaryImpl(const GlobalValueSummary &Summary,
390                          SmallVectorImpl<const GlobalVarSummary *> &Worklist) {
391     for (const auto &VI : Summary.refs()) {
392       if (!shouldImportGlobal(VI)) {
393         LLVM_DEBUG(
394             dbgs() << "Ref ignored! Target already in destination module.\n");
395         continue;
396       }
397 
398       LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
399 
400       for (const auto &RefSummary : VI.getSummaryList()) {
401         const auto *GVS = dyn_cast<GlobalVarSummary>(RefSummary.get());
402         // Functions could be referenced by global vars - e.g. a vtable; but we
403         // don't currently imagine a reason those would be imported here, rather
404         // than as part of the logic deciding which functions to import (i.e.
405         // based on profile information). Should we decide to handle them here,
406         // we can refactor accordingly at that time.
407         if (!GVS || !Index.canImportGlobalVar(GVS, /* AnalyzeRefs */ true) ||
408             shouldSkipLocalInAnotherModule(GVS, VI.getSummaryList().size(),
409                                            Summary.modulePath()))
410           continue;
411 
412         // If there isn't an entry for GUID, insert <GUID, Definition> pair.
413         // Otherwise, definition should take precedence over declaration.
414         if (FunctionImporter::addDefinition(
415                 ImportList, RefSummary->modulePath(), VI.getGUID()) !=
416             FunctionImporter::AddDefinitionStatus::Inserted)
417           break;
418 
419         // Only update stat and exports if we haven't already imported this
420         // variable.
421         NumImportedGlobalVarsThinLink++;
422         // Any references made by this variable will be marked exported
423         // later, in ComputeCrossModuleImport, after import decisions are
424         // complete, which is more efficient than adding them here.
425         if (ExportLists)
426           (*ExportLists)[RefSummary->modulePath()].insert(VI);
427 
428         // If variable is not writeonly we attempt to recursively analyze
429         // its references in order to import referenced constants.
430         if (!Index.isWriteOnly(GVS))
431           Worklist.emplace_back(GVS);
432         break;
433       }
434     }
435   }
436 
437 public:
438   GlobalsImporter(
439       const ModuleSummaryIndex &Index, const GVSummaryMapTy &DefinedGVSummaries,
440       function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
441           IsPrevailing,
442       FunctionImporter::ImportMapTy &ImportList,
443       DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists)
444       : Index(Index), DefinedGVSummaries(DefinedGVSummaries),
445         IsPrevailing(IsPrevailing), ImportList(ImportList),
446         ExportLists(ExportLists) {}
447 
448   void onImportingSummary(const GlobalValueSummary &Summary) {
449     SmallVector<const GlobalVarSummary *, 128> Worklist;
450     onImportingSummaryImpl(Summary, Worklist);
451     while (!Worklist.empty())
452       onImportingSummaryImpl(*Worklist.pop_back_val(), Worklist);
453   }
454 };
455 
456 static const char *getFailureName(FunctionImporter::ImportFailureReason Reason);
457 
458 /// Determine the list of imports and exports for each module.
459 class ModuleImportsManager {
460 protected:
461   function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
462       IsPrevailing;
463   const ModuleSummaryIndex &Index;
464   DenseMap<StringRef, FunctionImporter::ExportSetTy> *const ExportLists;
465 
466   ModuleImportsManager(
467       function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
468           IsPrevailing,
469       const ModuleSummaryIndex &Index,
470       DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists = nullptr)
471       : IsPrevailing(IsPrevailing), Index(Index), ExportLists(ExportLists) {}
472 
473 public:
474   virtual ~ModuleImportsManager() = default;
475 
476   /// Given the list of globals defined in a module, compute the list of imports
477   /// as well as the list of "exports", i.e. the list of symbols referenced from
478   /// another module (that may require promotion).
479   virtual void
480   computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries,
481                          StringRef ModName,
482                          FunctionImporter::ImportMapTy &ImportList);
483 
484   static std::unique_ptr<ModuleImportsManager>
485   create(function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
486              IsPrevailing,
487          const ModuleSummaryIndex &Index,
488          DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists =
489              nullptr);
490 };
491 
492 /// A ModuleImportsManager that operates based on a workload definition (see
493 /// -thinlto-workload-def). For modules that do not define workload roots, it
494 /// applies the base ModuleImportsManager import policy.
495 class WorkloadImportsManager : public ModuleImportsManager {
496   // Keep a module name -> value infos to import association. We use it to
497   // determine if a module's import list should be done by the base
498   // ModuleImportsManager or by us.
499   StringMap<DenseSet<ValueInfo>> Workloads;
500 
501   void
502   computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries,
503                          StringRef ModName,
504                          FunctionImporter::ImportMapTy &ImportList) override {
505     auto SetIter = Workloads.find(ModName);
506     if (SetIter == Workloads.end()) {
507       LLVM_DEBUG(dbgs() << "[Workload] " << ModName
508                         << " does not contain the root of any context.\n");
509       return ModuleImportsManager::computeImportForModule(DefinedGVSummaries,
510                                                           ModName, ImportList);
511     }
512     LLVM_DEBUG(dbgs() << "[Workload] " << ModName
513                       << " contains the root(s) of context(s).\n");
514 
515     GlobalsImporter GVI(Index, DefinedGVSummaries, IsPrevailing, ImportList,
516                         ExportLists);
517     auto &ValueInfos = SetIter->second;
518     SmallVector<EdgeInfo, 128> GlobWorklist;
519     for (auto &VI : llvm::make_early_inc_range(ValueInfos)) {
520       auto It = DefinedGVSummaries.find(VI.getGUID());
521       if (It != DefinedGVSummaries.end() &&
522           IsPrevailing(VI.getGUID(), It->second)) {
523         LLVM_DEBUG(
524             dbgs() << "[Workload] " << VI.name()
525                    << " has the prevailing variant already in the module "
526                    << ModName << ". No need to import\n");
527         continue;
528       }
529       auto Candidates =
530           qualifyCalleeCandidates(Index, VI.getSummaryList(), ModName);
531 
532       const GlobalValueSummary *GVS = nullptr;
533       auto PotentialCandidates = llvm::map_range(
534           llvm::make_filter_range(
535               Candidates,
536               [&](const auto &Candidate) {
537                 LLVM_DEBUG(dbgs() << "[Workflow] Candidate for " << VI.name()
538                                   << " from " << Candidate.second->modulePath()
539                                   << " ImportFailureReason: "
540                                   << getFailureName(Candidate.first) << "\n");
541                 return Candidate.first ==
542                         FunctionImporter::ImportFailureReason::None;
543               }),
544           [](const auto &Candidate) { return Candidate.second; });
545       if (PotentialCandidates.empty()) {
546         LLVM_DEBUG(dbgs() << "[Workload] Not importing " << VI.name()
547                           << " because can't find eligible Callee. Guid is: "
548                           << Function::getGUID(VI.name()) << "\n");
549         continue;
550       }
551       /// We will prefer importing the prevailing candidate, if not, we'll
552       /// still pick the first available candidate. The reason we want to make
553       /// sure we do import the prevailing candidate is because the goal of
554       /// workload-awareness is to enable optimizations specializing the call
555       /// graph of that workload. Suppose a function is already defined in the
556       /// module, but it's not the prevailing variant. Suppose also we do not
557       /// inline it (in fact, if it were interposable, we can't inline it),
558       /// but we could specialize it to the workload in other ways. However,
559       /// the linker would drop it in the favor of the prevailing copy.
560       /// Instead, by importing the prevailing variant (assuming also the use
561       /// of `-avail-extern-to-local`), we keep the specialization. We could
562       /// alteranatively make the non-prevailing variant local, but the
563       /// prevailing one is also the one for which we would have previously
564       /// collected profiles, making it preferrable.
565       auto PrevailingCandidates = llvm::make_filter_range(
566           PotentialCandidates, [&](const auto *Candidate) {
567             return IsPrevailing(VI.getGUID(), Candidate);
568           });
569       if (PrevailingCandidates.empty()) {
570         GVS = *PotentialCandidates.begin();
571         if (!llvm::hasSingleElement(PotentialCandidates) &&
572             GlobalValue::isLocalLinkage(GVS->linkage()))
573           LLVM_DEBUG(
574               dbgs()
575               << "[Workload] Found multiple non-prevailing candidates for "
576               << VI.name()
577               << ". This is unexpected. Are module paths passed to the "
578                  "compiler unique for the modules passed to the linker?");
579         // We could in theory have multiple (interposable) copies of a symbol
580         // when there is no prevailing candidate, if say the prevailing copy was
581         // in a native object being linked in. However, we should in theory be
582         // marking all of these non-prevailing IR copies dead in that case, in
583         // which case they won't be candidates.
584         assert(GVS->isLive());
585       } else {
586         assert(llvm::hasSingleElement(PrevailingCandidates));
587         GVS = *PrevailingCandidates.begin();
588       }
589 
590       auto ExportingModule = GVS->modulePath();
591       // We checked that for the prevailing case, but if we happen to have for
592       // example an internal that's defined in this module, it'd have no
593       // PrevailingCandidates.
594       if (ExportingModule == ModName) {
595         LLVM_DEBUG(dbgs() << "[Workload] Not importing " << VI.name()
596                           << " because its defining module is the same as the "
597                              "current module\n");
598         continue;
599       }
600       LLVM_DEBUG(dbgs() << "[Workload][Including]" << VI.name() << " from "
601                         << ExportingModule << " : "
602                         << Function::getGUID(VI.name()) << "\n");
603       FunctionImporter::addDefinition(ImportList, ExportingModule,
604                                       VI.getGUID());
605       GVI.onImportingSummary(*GVS);
606       if (ExportLists)
607         (*ExportLists)[ExportingModule].insert(VI);
608     }
609     LLVM_DEBUG(dbgs() << "[Workload] Done\n");
610   }
611 
612   void loadFromJson() {
613     // Since the workload def uses names, we need a quick lookup
614     // name->ValueInfo.
615     StringMap<ValueInfo> NameToValueInfo;
616     StringSet<> AmbiguousNames;
617     for (auto &I : Index) {
618       ValueInfo VI = Index.getValueInfo(I);
619       if (!NameToValueInfo.insert(std::make_pair(VI.name(), VI)).second)
620         LLVM_DEBUG(AmbiguousNames.insert(VI.name()));
621     }
622     auto DbgReportIfAmbiguous = [&](StringRef Name) {
623       LLVM_DEBUG(if (AmbiguousNames.count(Name) > 0) {
624         dbgs() << "[Workload] Function name " << Name
625                << " present in the workload definition is ambiguous. Consider "
626                   "compiling with -funique-internal-linkage-names.";
627       });
628     };
629     std::error_code EC;
630     auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(WorkloadDefinitions);
631     if (std::error_code EC = BufferOrErr.getError()) {
632       report_fatal_error("Failed to open context file");
633       return;
634     }
635     auto Buffer = std::move(BufferOrErr.get());
636     std::map<std::string, std::vector<std::string>> WorkloadDefs;
637     json::Path::Root NullRoot;
638     // The JSON is supposed to contain a dictionary matching the type of
639     // WorkloadDefs. For example:
640     // {
641     //   "rootFunction_1": ["function_to_import_1", "function_to_import_2"],
642     //   "rootFunction_2": ["function_to_import_3", "function_to_import_4"]
643     // }
644     auto Parsed = json::parse(Buffer->getBuffer());
645     if (!Parsed)
646       report_fatal_error(Parsed.takeError());
647     if (!json::fromJSON(*Parsed, WorkloadDefs, NullRoot))
648       report_fatal_error("Invalid thinlto contextual profile format.");
649     for (const auto &Workload : WorkloadDefs) {
650       const auto &Root = Workload.first;
651       DbgReportIfAmbiguous(Root);
652       LLVM_DEBUG(dbgs() << "[Workload] Root: " << Root << "\n");
653       const auto &AllCallees = Workload.second;
654       auto RootIt = NameToValueInfo.find(Root);
655       if (RootIt == NameToValueInfo.end()) {
656         LLVM_DEBUG(dbgs() << "[Workload] Root " << Root
657                           << " not found in this linkage unit.\n");
658         continue;
659       }
660       auto RootVI = RootIt->second;
661       if (RootVI.getSummaryList().size() != 1) {
662         LLVM_DEBUG(dbgs() << "[Workload] Root " << Root
663                           << " should have exactly one summary, but has "
664                           << RootVI.getSummaryList().size() << ". Skipping.\n");
665         continue;
666       }
667       StringRef RootDefiningModule =
668           RootVI.getSummaryList().front()->modulePath();
669       LLVM_DEBUG(dbgs() << "[Workload] Root defining module for " << Root
670                         << " is : " << RootDefiningModule << "\n");
671       auto &Set = Workloads[RootDefiningModule];
672       for (const auto &Callee : AllCallees) {
673         LLVM_DEBUG(dbgs() << "[Workload] " << Callee << "\n");
674         DbgReportIfAmbiguous(Callee);
675         auto ElemIt = NameToValueInfo.find(Callee);
676         if (ElemIt == NameToValueInfo.end()) {
677           LLVM_DEBUG(dbgs() << "[Workload] " << Callee << " not found\n");
678           continue;
679         }
680         Set.insert(ElemIt->second);
681       }
682     }
683   }
684 
685   void loadFromCtxProf() {
686     std::error_code EC;
687     auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(UseCtxProfile);
688     if (std::error_code EC = BufferOrErr.getError()) {
689       report_fatal_error("Failed to open contextual profile file");
690       return;
691     }
692     auto Buffer = std::move(BufferOrErr.get());
693 
694     PGOCtxProfileReader Reader(Buffer->getBuffer());
695     auto Ctx = Reader.loadContexts();
696     if (!Ctx) {
697       report_fatal_error("Failed to parse contextual profiles");
698       return;
699     }
700     const auto &CtxMap = *Ctx;
701     DenseSet<GlobalValue::GUID> ContainedGUIDs;
702     for (const auto &[RootGuid, Root] : CtxMap) {
703       // Avoid ContainedGUIDs to get in/out of scope. Reuse its memory for
704       // subsequent roots, but clear its contents.
705       ContainedGUIDs.clear();
706 
707       auto RootVI = Index.getValueInfo(RootGuid);
708       if (!RootVI) {
709         LLVM_DEBUG(dbgs() << "[Workload] Root " << RootGuid
710                           << " not found in this linkage unit.\n");
711         continue;
712       }
713       if (RootVI.getSummaryList().size() != 1) {
714         LLVM_DEBUG(dbgs() << "[Workload] Root " << RootGuid
715                           << " should have exactly one summary, but has "
716                           << RootVI.getSummaryList().size() << ". Skipping.\n");
717         continue;
718       }
719       StringRef RootDefiningModule =
720           RootVI.getSummaryList().front()->modulePath();
721       LLVM_DEBUG(dbgs() << "[Workload] Root defining module for " << RootGuid
722                         << " is : " << RootDefiningModule << "\n");
723       auto &Set = Workloads[RootDefiningModule];
724       Root.getContainedGuids(ContainedGUIDs);
725       for (auto Guid : ContainedGUIDs)
726         if (auto VI = Index.getValueInfo(Guid))
727           Set.insert(VI);
728     }
729   }
730 
731 public:
732   WorkloadImportsManager(
733       function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
734           IsPrevailing,
735       const ModuleSummaryIndex &Index,
736       DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists)
737       : ModuleImportsManager(IsPrevailing, Index, ExportLists) {
738     if (UseCtxProfile.empty() == WorkloadDefinitions.empty()) {
739       report_fatal_error(
740           "Pass only one of: -thinlto-pgo-ctx-prof or -thinlto-workload-def");
741       return;
742     }
743     if (!UseCtxProfile.empty())
744       loadFromCtxProf();
745     else
746       loadFromJson();
747     LLVM_DEBUG({
748       for (const auto &[Root, Set] : Workloads) {
749         dbgs() << "[Workload] Root: " << Root << " we have " << Set.size()
750                << " distinct callees.\n";
751         for (const auto &VI : Set) {
752           dbgs() << "[Workload] Root: " << Root
753                  << " Would include: " << VI.getGUID() << "\n";
754         }
755       }
756     });
757   }
758 };
759 
760 std::unique_ptr<ModuleImportsManager> ModuleImportsManager::create(
761     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
762         IsPrevailing,
763     const ModuleSummaryIndex &Index,
764     DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists) {
765   if (WorkloadDefinitions.empty() && UseCtxProfile.empty()) {
766     LLVM_DEBUG(dbgs() << "[Workload] Using the regular imports manager.\n");
767     return std::unique_ptr<ModuleImportsManager>(
768         new ModuleImportsManager(IsPrevailing, Index, ExportLists));
769   }
770   LLVM_DEBUG(dbgs() << "[Workload] Using the contextual imports manager.\n");
771   return std::make_unique<WorkloadImportsManager>(IsPrevailing, Index,
772                                                   ExportLists);
773 }
774 
775 static const char *
776 getFailureName(FunctionImporter::ImportFailureReason Reason) {
777   switch (Reason) {
778   case FunctionImporter::ImportFailureReason::None:
779     return "None";
780   case FunctionImporter::ImportFailureReason::GlobalVar:
781     return "GlobalVar";
782   case FunctionImporter::ImportFailureReason::NotLive:
783     return "NotLive";
784   case FunctionImporter::ImportFailureReason::TooLarge:
785     return "TooLarge";
786   case FunctionImporter::ImportFailureReason::InterposableLinkage:
787     return "InterposableLinkage";
788   case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
789     return "LocalLinkageNotInModule";
790   case FunctionImporter::ImportFailureReason::NotEligible:
791     return "NotEligible";
792   case FunctionImporter::ImportFailureReason::NoInline:
793     return "NoInline";
794   }
795   llvm_unreachable("invalid reason");
796 }
797 
798 /// Compute the list of functions to import for a given caller. Mark these
799 /// imported functions and the symbols they reference in their source module as
800 /// exported from their source module.
801 static void computeImportForFunction(
802     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
803     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
804     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
805         isPrevailing,
806     SmallVectorImpl<EdgeInfo> &Worklist, GlobalsImporter &GVImporter,
807     FunctionImporter::ImportMapTy &ImportList,
808     DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists,
809     FunctionImporter::ImportThresholdsTy &ImportThresholds) {
810   GVImporter.onImportingSummary(Summary);
811   static int ImportCount = 0;
812   for (const auto &Edge : Summary.calls()) {
813     ValueInfo VI = Edge.first;
814     LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
815                       << "\n");
816 
817     if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
818       LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
819                         << " reached.\n");
820       continue;
821     }
822 
823     if (DefinedGVSummaries.count(VI.getGUID())) {
824       // FIXME: Consider not skipping import if the module contains
825       // a non-prevailing def with interposable linkage. The prevailing copy
826       // can safely be imported (see shouldImportGlobal()).
827       LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
828       continue;
829     }
830 
831     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
832       if (Hotness == CalleeInfo::HotnessType::Hot)
833         return ImportHotMultiplier;
834       if (Hotness == CalleeInfo::HotnessType::Cold)
835         return ImportColdMultiplier;
836       if (Hotness == CalleeInfo::HotnessType::Critical)
837         return ImportCriticalMultiplier;
838       return 1.0;
839     };
840 
841     const auto NewThreshold =
842         Threshold * GetBonusMultiplier(Edge.second.getHotness());
843 
844     auto IT = ImportThresholds.insert(std::make_pair(
845         VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
846     bool PreviouslyVisited = !IT.second;
847     auto &ProcessedThreshold = std::get<0>(IT.first->second);
848     auto &CalleeSummary = std::get<1>(IT.first->second);
849     auto &FailureInfo = std::get<2>(IT.first->second);
850 
851     bool IsHotCallsite =
852         Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
853     bool IsCriticalCallsite =
854         Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
855 
856     const FunctionSummary *ResolvedCalleeSummary = nullptr;
857     if (CalleeSummary) {
858       assert(PreviouslyVisited);
859       // Since the traversal of the call graph is DFS, we can revisit a function
860       // a second time with a higher threshold. In this case, it is added back
861       // to the worklist with the new threshold (so that its own callee chains
862       // can be considered with the higher threshold).
863       if (NewThreshold <= ProcessedThreshold) {
864         LLVM_DEBUG(
865             dbgs() << "ignored! Target was already imported with Threshold "
866                    << ProcessedThreshold << "\n");
867         continue;
868       }
869       // Update with new larger threshold.
870       ProcessedThreshold = NewThreshold;
871       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
872     } else {
873       // If we already rejected importing a callee at the same or higher
874       // threshold, don't waste time calling selectCallee.
875       if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
876         LLVM_DEBUG(
877             dbgs() << "ignored! Target was already rejected with Threshold "
878             << ProcessedThreshold << "\n");
879         if (PrintImportFailures) {
880           assert(FailureInfo &&
881                  "Expected FailureInfo for previously rejected candidate");
882           FailureInfo->Attempts++;
883         }
884         continue;
885       }
886 
887       FunctionImporter::ImportFailureReason Reason{};
888 
889       // `SummaryForDeclImport` is an summary eligible for declaration import.
890       const GlobalValueSummary *SummaryForDeclImport = nullptr;
891       CalleeSummary =
892           selectCallee(Index, VI.getSummaryList(), NewThreshold,
893                        Summary.modulePath(), SummaryForDeclImport, Reason);
894       if (!CalleeSummary) {
895         // There isn't a callee for definition import but one for declaration
896         // import.
897         if (ImportDeclaration && SummaryForDeclImport) {
898           StringRef DeclSourceModule = SummaryForDeclImport->modulePath();
899 
900           // Note `ExportLists` only keeps track of exports due to imported
901           // definitions.
902           FunctionImporter::maybeAddDeclaration(ImportList, DeclSourceModule,
903                                                 VI.getGUID());
904         }
905         // Update with new larger threshold if this was a retry (otherwise
906         // we would have already inserted with NewThreshold above). Also
907         // update failure info if requested.
908         if (PreviouslyVisited) {
909           ProcessedThreshold = NewThreshold;
910           if (PrintImportFailures) {
911             assert(FailureInfo &&
912                    "Expected FailureInfo for previously rejected candidate");
913             FailureInfo->Reason = Reason;
914             FailureInfo->Attempts++;
915             FailureInfo->MaxHotness =
916                 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
917           }
918         } else if (PrintImportFailures) {
919           assert(!FailureInfo &&
920                  "Expected no FailureInfo for newly rejected candidate");
921           FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
922               VI, Edge.second.getHotness(), Reason, 1);
923         }
924         if (ForceImportAll) {
925           std::string Msg = std::string("Failed to import function ") +
926                             VI.name().str() + " due to " +
927                             getFailureName(Reason);
928           auto Error = make_error<StringError>(
929               Msg, make_error_code(errc::not_supported));
930           logAllUnhandledErrors(std::move(Error), errs(),
931                                 "Error importing module: ");
932           break;
933         } else {
934           LLVM_DEBUG(dbgs()
935                      << "ignored! No qualifying callee with summary found.\n");
936           continue;
937         }
938       }
939 
940       // "Resolve" the summary
941       CalleeSummary = CalleeSummary->getBaseObject();
942       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
943 
944       assert((ResolvedCalleeSummary->fflags().AlwaysInline || ForceImportAll ||
945               (ResolvedCalleeSummary->instCount() <= NewThreshold)) &&
946              "selectCallee() didn't honor the threshold");
947 
948       auto ExportModulePath = ResolvedCalleeSummary->modulePath();
949 
950       // Try emplace the definition entry, and update stats based on insertion
951       // status.
952       if (FunctionImporter::addDefinition(ImportList, ExportModulePath,
953                                           VI.getGUID()) !=
954           FunctionImporter::AddDefinitionStatus::NoChange) {
955         NumImportedFunctionsThinLink++;
956         if (IsHotCallsite)
957           NumImportedHotFunctionsThinLink++;
958         if (IsCriticalCallsite)
959           NumImportedCriticalFunctionsThinLink++;
960       }
961 
962       // Any calls/references made by this function will be marked exported
963       // later, in ComputeCrossModuleImport, after import decisions are
964       // complete, which is more efficient than adding them here.
965       if (ExportLists)
966         (*ExportLists)[ExportModulePath].insert(VI);
967     }
968 
969     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
970       // Adjust the threshold for next level of imported functions.
971       // The threshold is different for hot callsites because we can then
972       // inline chains of hot calls.
973       if (IsHotCallsite)
974         return Threshold * ImportHotInstrFactor;
975       return Threshold * ImportInstrFactor;
976     };
977 
978     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
979 
980     ImportCount++;
981 
982     // Insert the newly imported function to the worklist.
983     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold);
984   }
985 }
986 
987 void ModuleImportsManager::computeImportForModule(
988     const GVSummaryMapTy &DefinedGVSummaries, StringRef ModName,
989     FunctionImporter::ImportMapTy &ImportList) {
990   // Worklist contains the list of function imported in this module, for which
991   // we will analyse the callees and may import further down the callgraph.
992   SmallVector<EdgeInfo, 128> Worklist;
993   GlobalsImporter GVI(Index, DefinedGVSummaries, IsPrevailing, ImportList,
994                       ExportLists);
995   FunctionImporter::ImportThresholdsTy ImportThresholds;
996 
997   // Populate the worklist with the import for the functions in the current
998   // module
999   for (const auto &GVSummary : DefinedGVSummaries) {
1000 #ifndef NDEBUG
1001     // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
1002     // so this map look up (and possibly others) can be avoided.
1003     auto VI = Index.getValueInfo(GVSummary.first);
1004 #endif
1005     if (!Index.isGlobalValueLive(GVSummary.second)) {
1006       LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
1007       continue;
1008     }
1009     auto *FuncSummary =
1010         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
1011     if (!FuncSummary)
1012       // Skip import for global variables
1013       continue;
1014     LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
1015     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
1016                              DefinedGVSummaries, IsPrevailing, Worklist, GVI,
1017                              ImportList, ExportLists, ImportThresholds);
1018   }
1019 
1020   // Process the newly imported functions and add callees to the worklist.
1021   while (!Worklist.empty()) {
1022     auto GVInfo = Worklist.pop_back_val();
1023     auto *Summary = std::get<0>(GVInfo);
1024     auto Threshold = std::get<1>(GVInfo);
1025 
1026     if (auto *FS = dyn_cast<FunctionSummary>(Summary))
1027       computeImportForFunction(*FS, Index, Threshold, DefinedGVSummaries,
1028                                IsPrevailing, Worklist, GVI, ImportList,
1029                                ExportLists, ImportThresholds);
1030   }
1031 
1032   // Print stats about functions considered but rejected for importing
1033   // when requested.
1034   if (PrintImportFailures) {
1035     dbgs() << "Missed imports into module " << ModName << "\n";
1036     for (auto &I : ImportThresholds) {
1037       auto &ProcessedThreshold = std::get<0>(I.second);
1038       auto &CalleeSummary = std::get<1>(I.second);
1039       auto &FailureInfo = std::get<2>(I.second);
1040       if (CalleeSummary)
1041         continue; // We are going to import.
1042       assert(FailureInfo);
1043       FunctionSummary *FS = nullptr;
1044       if (!FailureInfo->VI.getSummaryList().empty())
1045         FS = dyn_cast<FunctionSummary>(
1046             FailureInfo->VI.getSummaryList()[0]->getBaseObject());
1047       dbgs() << FailureInfo->VI
1048              << ": Reason = " << getFailureName(FailureInfo->Reason)
1049              << ", Threshold = " << ProcessedThreshold
1050              << ", Size = " << (FS ? (int)FS->instCount() : -1)
1051              << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
1052              << ", Attempts = " << FailureInfo->Attempts << "\n";
1053     }
1054   }
1055 }
1056 
1057 #ifndef NDEBUG
1058 static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI) {
1059   auto SL = VI.getSummaryList();
1060   return SL.empty()
1061              ? false
1062              : SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
1063 }
1064 
1065 static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
1066                                GlobalValue::GUID G) {
1067   if (const auto &VI = Index.getValueInfo(G))
1068     return isGlobalVarSummary(Index, VI);
1069   return false;
1070 }
1071 
1072 // Return the number of global variable summaries in ExportSet.
1073 static unsigned
1074 numGlobalVarSummaries(const ModuleSummaryIndex &Index,
1075                       FunctionImporter::ExportSetTy &ExportSet) {
1076   unsigned NumGVS = 0;
1077   for (auto &VI : ExportSet)
1078     if (isGlobalVarSummary(Index, VI.getGUID()))
1079       ++NumGVS;
1080   return NumGVS;
1081 }
1082 
1083 // Given ImportMap, return the number of global variable summaries and record
1084 // the number of defined function summaries as output parameter.
1085 static unsigned
1086 numGlobalVarSummaries(const ModuleSummaryIndex &Index,
1087                       FunctionImporter::FunctionsToImportTy &ImportMap,
1088                       unsigned &DefinedFS) {
1089   unsigned NumGVS = 0;
1090   DefinedFS = 0;
1091   for (auto &[GUID, Type] : ImportMap) {
1092     if (isGlobalVarSummary(Index, GUID))
1093       ++NumGVS;
1094     else if (Type == GlobalValueSummary::Definition)
1095       ++DefinedFS;
1096   }
1097   return NumGVS;
1098 }
1099 #endif
1100 
1101 #ifndef NDEBUG
1102 static bool checkVariableImport(
1103     const ModuleSummaryIndex &Index,
1104     DenseMap<StringRef, FunctionImporter::ImportMapTy> &ImportLists,
1105     DenseMap<StringRef, FunctionImporter::ExportSetTy> &ExportLists) {
1106   DenseSet<GlobalValue::GUID> FlattenedImports;
1107 
1108   for (auto &ImportPerModule : ImportLists)
1109     for (auto &ExportPerModule : ImportPerModule.second)
1110       for (auto &[GUID, Type] : ExportPerModule.second)
1111         FlattenedImports.insert(GUID);
1112 
1113   // Checks that all GUIDs of read/writeonly vars we see in export lists
1114   // are also in the import lists. Otherwise we my face linker undefs,
1115   // because readonly and writeonly vars are internalized in their
1116   // source modules. The exception would be if it has a linkage type indicating
1117   // that there may have been a copy existing in the importing module (e.g.
1118   // linkonce_odr). In that case we cannot accurately do this checking.
1119   auto IsReadOrWriteOnlyVarNeedingImporting = [&](StringRef ModulePath,
1120                                                   const ValueInfo &VI) {
1121     auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
1122         Index.findSummaryInModule(VI, ModulePath));
1123     return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS)) &&
1124            !(GVS->linkage() == GlobalValue::AvailableExternallyLinkage ||
1125              GVS->linkage() == GlobalValue::WeakODRLinkage ||
1126              GVS->linkage() == GlobalValue::LinkOnceODRLinkage);
1127   };
1128 
1129   for (auto &ExportPerModule : ExportLists)
1130     for (auto &VI : ExportPerModule.second)
1131       if (!FlattenedImports.count(VI.getGUID()) &&
1132           IsReadOrWriteOnlyVarNeedingImporting(ExportPerModule.first, VI))
1133         return false;
1134 
1135   return true;
1136 }
1137 #endif
1138 
1139 /// Compute all the import and export for every module using the Index.
1140 void llvm::ComputeCrossModuleImport(
1141     const ModuleSummaryIndex &Index,
1142     const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1143     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
1144         isPrevailing,
1145     DenseMap<StringRef, FunctionImporter::ImportMapTy> &ImportLists,
1146     DenseMap<StringRef, FunctionImporter::ExportSetTy> &ExportLists) {
1147   auto MIS = ModuleImportsManager::create(isPrevailing, Index, &ExportLists);
1148   // For each module that has function defined, compute the import/export lists.
1149   for (const auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
1150     auto &ImportList = ImportLists[DefinedGVSummaries.first];
1151     LLVM_DEBUG(dbgs() << "Computing import for Module '"
1152                       << DefinedGVSummaries.first << "'\n");
1153     MIS->computeImportForModule(DefinedGVSummaries.second,
1154                                 DefinedGVSummaries.first, ImportList);
1155   }
1156 
1157   // When computing imports we only added the variables and functions being
1158   // imported to the export list. We also need to mark any references and calls
1159   // they make as exported as well. We do this here, as it is more efficient
1160   // since we may import the same values multiple times into different modules
1161   // during the import computation.
1162   for (auto &ELI : ExportLists) {
1163     // `NewExports` tracks the VI that gets exported because the full definition
1164     // of its user/referencer gets exported.
1165     FunctionImporter::ExportSetTy NewExports;
1166     const auto &DefinedGVSummaries =
1167         ModuleToDefinedGVSummaries.lookup(ELI.first);
1168     for (auto &EI : ELI.second) {
1169       // Find the copy defined in the exporting module so that we can mark the
1170       // values it references in that specific definition as exported.
1171       // Below we will add all references and called values, without regard to
1172       // whether they are also defined in this module. We subsequently prune the
1173       // list to only include those defined in the exporting module, see comment
1174       // there as to why.
1175       auto DS = DefinedGVSummaries.find(EI.getGUID());
1176       // Anything marked exported during the import computation must have been
1177       // defined in the exporting module.
1178       assert(DS != DefinedGVSummaries.end());
1179       auto *S = DS->getSecond();
1180       S = S->getBaseObject();
1181       if (auto *GVS = dyn_cast<GlobalVarSummary>(S)) {
1182         // Export referenced functions and variables. We don't export/promote
1183         // objects referenced by writeonly variable initializer, because
1184         // we convert such variables initializers to "zeroinitializer".
1185         // See processGlobalForThinLTO.
1186         if (!Index.isWriteOnly(GVS))
1187           for (const auto &VI : GVS->refs())
1188             NewExports.insert(VI);
1189       } else {
1190         auto *FS = cast<FunctionSummary>(S);
1191         for (const auto &Edge : FS->calls())
1192           NewExports.insert(Edge.first);
1193         for (const auto &Ref : FS->refs())
1194           NewExports.insert(Ref);
1195       }
1196     }
1197     // Prune list computed above to only include values defined in the
1198     // exporting module. We do this after the above insertion since we may hit
1199     // the same ref/call target multiple times in above loop, and it is more
1200     // efficient to avoid a set lookup each time.
1201     for (auto EI = NewExports.begin(); EI != NewExports.end();) {
1202       if (!DefinedGVSummaries.count(EI->getGUID()))
1203         NewExports.erase(EI++);
1204       else
1205         ++EI;
1206     }
1207     ELI.second.insert(NewExports.begin(), NewExports.end());
1208   }
1209 
1210   assert(checkVariableImport(Index, ImportLists, ExportLists));
1211 #ifndef NDEBUG
1212   LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
1213                     << " modules:\n");
1214   for (auto &ModuleImports : ImportLists) {
1215     auto ModName = ModuleImports.first;
1216     auto &Exports = ExportLists[ModName];
1217     unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
1218     LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
1219                       << Exports.size() - NumGVS << " functions and " << NumGVS
1220                       << " vars. Imports from " << ModuleImports.second.size()
1221                       << " modules.\n");
1222     for (auto &Src : ModuleImports.second) {
1223       auto SrcModName = Src.first;
1224       unsigned DefinedFS = 0;
1225       unsigned NumGVSPerMod =
1226           numGlobalVarSummaries(Index, Src.second, DefinedFS);
1227       LLVM_DEBUG(dbgs() << " - " << DefinedFS << " function definitions and "
1228                         << Src.second.size() - NumGVSPerMod - DefinedFS
1229                         << " function declarations imported from " << SrcModName
1230                         << "\n");
1231       LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
1232                         << " global vars imported from " << SrcModName << "\n");
1233     }
1234   }
1235 #endif
1236 }
1237 
1238 #ifndef NDEBUG
1239 static void dumpImportListForModule(const ModuleSummaryIndex &Index,
1240                                     StringRef ModulePath,
1241                                     FunctionImporter::ImportMapTy &ImportList) {
1242   LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
1243                     << ImportList.size() << " modules.\n");
1244   for (auto &Src : ImportList) {
1245     auto SrcModName = Src.first;
1246     unsigned DefinedFS = 0;
1247     unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second, DefinedFS);
1248     LLVM_DEBUG(dbgs() << " - " << DefinedFS << " function definitions and "
1249                       << Src.second.size() - DefinedFS - NumGVSPerMod
1250                       << " function declarations imported from " << SrcModName
1251                       << "\n");
1252     LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
1253                       << SrcModName << "\n");
1254   }
1255 }
1256 #endif
1257 
1258 /// Compute all the imports for the given module using the Index.
1259 ///
1260 /// \p isPrevailing is a callback that will be called with a global value's GUID
1261 /// and summary and should return whether the module corresponding to the
1262 /// summary contains the linker-prevailing copy of that value.
1263 ///
1264 /// \p ImportList will be populated with a map that can be passed to
1265 /// FunctionImporter::importFunctions() above (see description there).
1266 static void ComputeCrossModuleImportForModuleForTest(
1267     StringRef ModulePath,
1268     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
1269         isPrevailing,
1270     const ModuleSummaryIndex &Index,
1271     FunctionImporter::ImportMapTy &ImportList) {
1272   // Collect the list of functions this module defines.
1273   // GUID -> Summary
1274   GVSummaryMapTy FunctionSummaryMap;
1275   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
1276 
1277   // Compute the import list for this module.
1278   LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
1279   auto MIS = ModuleImportsManager::create(isPrevailing, Index);
1280   MIS->computeImportForModule(FunctionSummaryMap, ModulePath, ImportList);
1281 
1282 #ifndef NDEBUG
1283   dumpImportListForModule(Index, ModulePath, ImportList);
1284 #endif
1285 }
1286 
1287 /// Mark all external summaries in \p Index for import into the given module.
1288 /// Used for testing the case of distributed builds using a distributed index.
1289 ///
1290 /// \p ImportList will be populated with a map that can be passed to
1291 /// FunctionImporter::importFunctions() above (see description there).
1292 static void ComputeCrossModuleImportForModuleFromIndexForTest(
1293     StringRef ModulePath, const ModuleSummaryIndex &Index,
1294     FunctionImporter::ImportMapTy &ImportList) {
1295   for (const auto &GlobalList : Index) {
1296     // Ignore entries for undefined references.
1297     if (GlobalList.second.SummaryList.empty())
1298       continue;
1299 
1300     auto GUID = GlobalList.first;
1301     assert(GlobalList.second.SummaryList.size() == 1 &&
1302            "Expected individual combined index to have one summary per GUID");
1303     auto &Summary = GlobalList.second.SummaryList[0];
1304     // Skip the summaries for the importing module. These are included to
1305     // e.g. record required linkage changes.
1306     if (Summary->modulePath() == ModulePath)
1307       continue;
1308     // Add an entry to provoke importing by thinBackend.
1309     FunctionImporter::addGUID(ImportList, Summary->modulePath(), GUID,
1310                               Summary->importType());
1311   }
1312 #ifndef NDEBUG
1313   dumpImportListForModule(Index, ModulePath, ImportList);
1314 #endif
1315 }
1316 
1317 // For SamplePGO, the indirect call targets for local functions will
1318 // have its original name annotated in profile. We try to find the
1319 // corresponding PGOFuncName as the GUID, and fix up the edges
1320 // accordingly.
1321 void updateValueInfoForIndirectCalls(ModuleSummaryIndex &Index,
1322                                      FunctionSummary *FS) {
1323   for (auto &EI : FS->mutableCalls()) {
1324     if (!EI.first.getSummaryList().empty())
1325       continue;
1326     auto GUID = Index.getGUIDFromOriginalID(EI.first.getGUID());
1327     if (GUID == 0)
1328       continue;
1329     // Update the edge to point directly to the correct GUID.
1330     auto VI = Index.getValueInfo(GUID);
1331     if (llvm::any_of(
1332             VI.getSummaryList(),
1333             [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
1334               // The mapping from OriginalId to GUID may return a GUID
1335               // that corresponds to a static variable. Filter it out here.
1336               // This can happen when
1337               // 1) There is a call to a library function which is not defined
1338               // in the index.
1339               // 2) There is a static variable with the  OriginalGUID identical
1340               // to the GUID of the library function in 1);
1341               // When this happens the static variable in 2) will be found,
1342               // which needs to be filtered out.
1343               return SummaryPtr->getSummaryKind() ==
1344                      GlobalValueSummary::GlobalVarKind;
1345             }))
1346       continue;
1347     EI.first = VI;
1348   }
1349 }
1350 
1351 void llvm::updateIndirectCalls(ModuleSummaryIndex &Index) {
1352   for (const auto &Entry : Index) {
1353     for (const auto &S : Entry.second.SummaryList) {
1354       if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
1355         updateValueInfoForIndirectCalls(Index, FS);
1356     }
1357   }
1358 }
1359 
1360 void llvm::computeDeadSymbolsAndUpdateIndirectCalls(
1361     ModuleSummaryIndex &Index,
1362     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
1363     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
1364   assert(!Index.withGlobalValueDeadStripping());
1365   if (!ComputeDead ||
1366       // Don't do anything when nothing is live, this is friendly with tests.
1367       GUIDPreservedSymbols.empty()) {
1368     // Still need to update indirect calls.
1369     updateIndirectCalls(Index);
1370     return;
1371   }
1372   unsigned LiveSymbols = 0;
1373   SmallVector<ValueInfo, 128> Worklist;
1374   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
1375   for (auto GUID : GUIDPreservedSymbols) {
1376     ValueInfo VI = Index.getValueInfo(GUID);
1377     if (!VI)
1378       continue;
1379     for (const auto &S : VI.getSummaryList())
1380       S->setLive(true);
1381   }
1382 
1383   // Add values flagged in the index as live roots to the worklist.
1384   for (const auto &Entry : Index) {
1385     auto VI = Index.getValueInfo(Entry);
1386     for (const auto &S : Entry.second.SummaryList) {
1387       if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
1388         updateValueInfoForIndirectCalls(Index, FS);
1389       if (S->isLive()) {
1390         LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
1391         Worklist.push_back(VI);
1392         ++LiveSymbols;
1393         break;
1394       }
1395     }
1396   }
1397 
1398   // Make value live and add it to the worklist if it was not live before.
1399   auto visit = [&](ValueInfo VI, bool IsAliasee) {
1400     // FIXME: If we knew which edges were created for indirect call profiles,
1401     // we could skip them here. Any that are live should be reached via
1402     // other edges, e.g. reference edges. Otherwise, using a profile collected
1403     // on a slightly different binary might provoke preserving, importing
1404     // and ultimately promoting calls to functions not linked into this
1405     // binary, which increases the binary size unnecessarily. Note that
1406     // if this code changes, the importer needs to change so that edges
1407     // to functions marked dead are skipped.
1408 
1409     if (llvm::any_of(VI.getSummaryList(),
1410                      [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
1411                        return S->isLive();
1412                      }))
1413       return;
1414 
1415     // We only keep live symbols that are known to be non-prevailing if any are
1416     // available_externally, linkonceodr, weakodr. Those symbols are discarded
1417     // later in the EliminateAvailableExternally pass and setting them to
1418     // not-live could break downstreams users of liveness information (PR36483)
1419     // or limit optimization opportunities.
1420     if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
1421       bool KeepAliveLinkage = false;
1422       bool Interposable = false;
1423       for (const auto &S : VI.getSummaryList()) {
1424         if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
1425             S->linkage() == GlobalValue::WeakODRLinkage ||
1426             S->linkage() == GlobalValue::LinkOnceODRLinkage)
1427           KeepAliveLinkage = true;
1428         else if (GlobalValue::isInterposableLinkage(S->linkage()))
1429           Interposable = true;
1430       }
1431 
1432       if (!IsAliasee) {
1433         if (!KeepAliveLinkage)
1434           return;
1435 
1436         if (Interposable)
1437           report_fatal_error(
1438               "Interposable and available_externally/linkonce_odr/weak_odr "
1439               "symbol");
1440       }
1441     }
1442 
1443     for (const auto &S : VI.getSummaryList())
1444       S->setLive(true);
1445     ++LiveSymbols;
1446     Worklist.push_back(VI);
1447   };
1448 
1449   while (!Worklist.empty()) {
1450     auto VI = Worklist.pop_back_val();
1451     for (const auto &Summary : VI.getSummaryList()) {
1452       if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
1453         // If this is an alias, visit the aliasee VI to ensure that all copies
1454         // are marked live and it is added to the worklist for further
1455         // processing of its references.
1456         visit(AS->getAliaseeVI(), true);
1457         continue;
1458       }
1459       for (auto Ref : Summary->refs())
1460         visit(Ref, false);
1461       if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
1462         for (auto Call : FS->calls())
1463           visit(Call.first, false);
1464     }
1465   }
1466   Index.setWithGlobalValueDeadStripping();
1467 
1468   unsigned DeadSymbols = Index.size() - LiveSymbols;
1469   LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
1470                     << " symbols Dead \n");
1471   NumDeadSymbols += DeadSymbols;
1472   NumLiveSymbols += LiveSymbols;
1473 }
1474 
1475 // Compute dead symbols and propagate constants in combined index.
1476 void llvm::computeDeadSymbolsWithConstProp(
1477     ModuleSummaryIndex &Index,
1478     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
1479     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
1480     bool ImportEnabled) {
1481   computeDeadSymbolsAndUpdateIndirectCalls(Index, GUIDPreservedSymbols,
1482                                            isPrevailing);
1483   if (ImportEnabled)
1484     Index.propagateAttributes(GUIDPreservedSymbols);
1485 }
1486 
1487 /// Compute the set of summaries needed for a ThinLTO backend compilation of
1488 /// \p ModulePath.
1489 void llvm::gatherImportedSummariesForModule(
1490     StringRef ModulePath,
1491     const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1492     const FunctionImporter::ImportMapTy &ImportList,
1493     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex,
1494     GVSummaryPtrSet &DecSummaries) {
1495   // Include all summaries from the importing module.
1496   ModuleToSummariesForIndex[std::string(ModulePath)] =
1497       ModuleToDefinedGVSummaries.lookup(ModulePath);
1498   // Include summaries for imports.
1499   for (const auto &ILI : ImportList) {
1500     auto &SummariesForIndex = ModuleToSummariesForIndex[std::string(ILI.first)];
1501 
1502     const auto &DefinedGVSummaries =
1503         ModuleToDefinedGVSummaries.lookup(ILI.first);
1504     for (const auto &[GUID, Type] : ILI.second) {
1505       const auto &DS = DefinedGVSummaries.find(GUID);
1506       assert(DS != DefinedGVSummaries.end() &&
1507              "Expected a defined summary for imported global value");
1508       if (Type == GlobalValueSummary::Declaration)
1509         DecSummaries.insert(DS->second);
1510 
1511       SummariesForIndex[GUID] = DS->second;
1512     }
1513   }
1514 }
1515 
1516 /// Emit the files \p ModulePath will import from into \p OutputFilename.
1517 std::error_code llvm::EmitImportsFiles(
1518     StringRef ModulePath, StringRef OutputFilename,
1519     const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
1520   std::error_code EC;
1521   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_Text);
1522   if (EC)
1523     return EC;
1524   for (const auto &ILI : ModuleToSummariesForIndex)
1525     // The ModuleToSummariesForIndex map includes an entry for the current
1526     // Module (needed for writing out the index files). We don't want to
1527     // include it in the imports file, however, so filter it out.
1528     if (ILI.first != ModulePath)
1529       ImportsOS << ILI.first << "\n";
1530   return std::error_code();
1531 }
1532 
1533 bool llvm::convertToDeclaration(GlobalValue &GV) {
1534   LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
1535                     << "\n");
1536   if (Function *F = dyn_cast<Function>(&GV)) {
1537     F->deleteBody();
1538     F->clearMetadata();
1539     F->setComdat(nullptr);
1540   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
1541     V->setInitializer(nullptr);
1542     V->setLinkage(GlobalValue::ExternalLinkage);
1543     V->clearMetadata();
1544     V->setComdat(nullptr);
1545   } else {
1546     GlobalValue *NewGV;
1547     if (GV.getValueType()->isFunctionTy())
1548       NewGV =
1549           Function::Create(cast<FunctionType>(GV.getValueType()),
1550                            GlobalValue::ExternalLinkage, GV.getAddressSpace(),
1551                            "", GV.getParent());
1552     else
1553       NewGV =
1554           new GlobalVariable(*GV.getParent(), GV.getValueType(),
1555                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
1556                              /*init*/ nullptr, "",
1557                              /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
1558                              GV.getType()->getAddressSpace());
1559     NewGV->takeName(&GV);
1560     GV.replaceAllUsesWith(NewGV);
1561     return false;
1562   }
1563   if (!GV.isImplicitDSOLocal())
1564     GV.setDSOLocal(false);
1565   return true;
1566 }
1567 
1568 void llvm::thinLTOFinalizeInModule(Module &TheModule,
1569                                    const GVSummaryMapTy &DefinedGlobals,
1570                                    bool PropagateAttrs) {
1571   DenseSet<Comdat *> NonPrevailingComdats;
1572   auto FinalizeInModule = [&](GlobalValue &GV, bool Propagate = false) {
1573     // See if the global summary analysis computed a new resolved linkage.
1574     const auto &GS = DefinedGlobals.find(GV.getGUID());
1575     if (GS == DefinedGlobals.end())
1576       return;
1577 
1578     if (Propagate)
1579       if (FunctionSummary *FS = dyn_cast<FunctionSummary>(GS->second)) {
1580         if (Function *F = dyn_cast<Function>(&GV)) {
1581           // TODO: propagate ReadNone and ReadOnly.
1582           if (FS->fflags().ReadNone && !F->doesNotAccessMemory())
1583             F->setDoesNotAccessMemory();
1584 
1585           if (FS->fflags().ReadOnly && !F->onlyReadsMemory())
1586             F->setOnlyReadsMemory();
1587 
1588           if (FS->fflags().NoRecurse && !F->doesNotRecurse())
1589             F->setDoesNotRecurse();
1590 
1591           if (FS->fflags().NoUnwind && !F->doesNotThrow())
1592             F->setDoesNotThrow();
1593         }
1594       }
1595 
1596     auto NewLinkage = GS->second->linkage();
1597     if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
1598         // Don't internalize anything here, because the code below
1599         // lacks necessary correctness checks. Leave this job to
1600         // LLVM 'internalize' pass.
1601         GlobalValue::isLocalLinkage(NewLinkage) ||
1602         // In case it was dead and already converted to declaration.
1603         GV.isDeclaration())
1604       return;
1605 
1606     // Set the potentially more constraining visibility computed from summaries.
1607     // The DefaultVisibility condition is because older GlobalValueSummary does
1608     // not record DefaultVisibility and we don't want to change protected/hidden
1609     // to default.
1610     if (GS->second->getVisibility() != GlobalValue::DefaultVisibility)
1611       GV.setVisibility(GS->second->getVisibility());
1612 
1613     if (NewLinkage == GV.getLinkage())
1614       return;
1615 
1616     // Check for a non-prevailing def that has interposable linkage
1617     // (e.g. non-odr weak or linkonce). In that case we can't simply
1618     // convert to available_externally, since it would lose the
1619     // interposable property and possibly get inlined. Simply drop
1620     // the definition in that case.
1621     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
1622         GlobalValue::isInterposableLinkage(GV.getLinkage())) {
1623       if (!convertToDeclaration(GV))
1624         // FIXME: Change this to collect replaced GVs and later erase
1625         // them from the parent module once thinLTOResolvePrevailingGUID is
1626         // changed to enable this for aliases.
1627         llvm_unreachable("Expected GV to be converted");
1628     } else {
1629       // If all copies of the original symbol had global unnamed addr and
1630       // linkonce_odr linkage, or if all of them had local unnamed addr linkage
1631       // and are constants, then it should be an auto hide symbol. In that case
1632       // the thin link would have marked it as CanAutoHide. Add hidden
1633       // visibility to the symbol to preserve the property.
1634       if (NewLinkage == GlobalValue::WeakODRLinkage &&
1635           GS->second->canAutoHide()) {
1636         assert(GV.canBeOmittedFromSymbolTable());
1637         GV.setVisibility(GlobalValue::HiddenVisibility);
1638       }
1639 
1640       LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
1641                         << "` from " << GV.getLinkage() << " to " << NewLinkage
1642                         << "\n");
1643       GV.setLinkage(NewLinkage);
1644     }
1645     // Remove declarations from comdats, including available_externally
1646     // as this is a declaration for the linker, and will be dropped eventually.
1647     // It is illegal for comdats to contain declarations.
1648     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
1649     if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
1650       if (GO->getComdat()->getName() == GO->getName())
1651         NonPrevailingComdats.insert(GO->getComdat());
1652       GO->setComdat(nullptr);
1653     }
1654   };
1655 
1656   // Process functions and global now
1657   for (auto &GV : TheModule)
1658     FinalizeInModule(GV, PropagateAttrs);
1659   for (auto &GV : TheModule.globals())
1660     FinalizeInModule(GV);
1661   for (auto &GV : TheModule.aliases())
1662     FinalizeInModule(GV);
1663 
1664   // For a non-prevailing comdat, all its members must be available_externally.
1665   // FinalizeInModule has handled non-local-linkage GlobalValues. Here we handle
1666   // local linkage GlobalValues.
1667   if (NonPrevailingComdats.empty())
1668     return;
1669   for (auto &GO : TheModule.global_objects()) {
1670     if (auto *C = GO.getComdat(); C && NonPrevailingComdats.count(C)) {
1671       GO.setComdat(nullptr);
1672       GO.setLinkage(GlobalValue::AvailableExternallyLinkage);
1673     }
1674   }
1675   bool Changed;
1676   do {
1677     Changed = false;
1678     // If an alias references a GlobalValue in a non-prevailing comdat, change
1679     // it to available_externally. For simplicity we only handle GlobalValue and
1680     // ConstantExpr with a base object. ConstantExpr without a base object is
1681     // unlikely used in a COMDAT.
1682     for (auto &GA : TheModule.aliases()) {
1683       if (GA.hasAvailableExternallyLinkage())
1684         continue;
1685       GlobalObject *Obj = GA.getAliaseeObject();
1686       assert(Obj && "aliasee without an base object is unimplemented");
1687       if (Obj->hasAvailableExternallyLinkage()) {
1688         GA.setLinkage(GlobalValue::AvailableExternallyLinkage);
1689         Changed = true;
1690       }
1691     }
1692   } while (Changed);
1693 }
1694 
1695 /// Run internalization on \p TheModule based on symmary analysis.
1696 void llvm::thinLTOInternalizeModule(Module &TheModule,
1697                                     const GVSummaryMapTy &DefinedGlobals) {
1698   // Declare a callback for the internalize pass that will ask for every
1699   // candidate GlobalValue if it can be internalized or not.
1700   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
1701     // It may be the case that GV is on a chain of an ifunc, its alias and
1702     // subsequent aliases. In this case, the summary for the value is not
1703     // available.
1704     if (isa<GlobalIFunc>(&GV) ||
1705         (isa<GlobalAlias>(&GV) &&
1706          isa<GlobalIFunc>(cast<GlobalAlias>(&GV)->getAliaseeObject())))
1707       return true;
1708 
1709     // Lookup the linkage recorded in the summaries during global analysis.
1710     auto GS = DefinedGlobals.find(GV.getGUID());
1711     if (GS == DefinedGlobals.end()) {
1712       // Must have been promoted (possibly conservatively). Find original
1713       // name so that we can access the correct summary and see if it can
1714       // be internalized again.
1715       // FIXME: Eventually we should control promotion instead of promoting
1716       // and internalizing again.
1717       StringRef OrigName =
1718           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
1719       std::string OrigId = GlobalValue::getGlobalIdentifier(
1720           OrigName, GlobalValue::InternalLinkage,
1721           TheModule.getSourceFileName());
1722       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
1723       if (GS == DefinedGlobals.end()) {
1724         // Also check the original non-promoted non-globalized name. In some
1725         // cases a preempted weak value is linked in as a local copy because
1726         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
1727         // In that case, since it was originally not a local value, it was
1728         // recorded in the index using the original name.
1729         // FIXME: This may not be needed once PR27866 is fixed.
1730         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
1731         assert(GS != DefinedGlobals.end());
1732       }
1733     }
1734     return !GlobalValue::isLocalLinkage(GS->second->linkage());
1735   };
1736 
1737   // FIXME: See if we can just internalize directly here via linkage changes
1738   // based on the index, rather than invoking internalizeModule.
1739   internalizeModule(TheModule, MustPreserveGV);
1740 }
1741 
1742 /// Make alias a clone of its aliasee.
1743 static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
1744   Function *Fn = cast<Function>(GA->getAliaseeObject());
1745 
1746   ValueToValueMapTy VMap;
1747   Function *NewFn = CloneFunction(Fn, VMap);
1748   // Clone should use the original alias's linkage, visibility and name, and we
1749   // ensure all uses of alias instead use the new clone (casted if necessary).
1750   NewFn->setLinkage(GA->getLinkage());
1751   NewFn->setVisibility(GA->getVisibility());
1752   GA->replaceAllUsesWith(NewFn);
1753   NewFn->takeName(GA);
1754   return NewFn;
1755 }
1756 
1757 // Internalize values that we marked with specific attribute
1758 // in processGlobalForThinLTO.
1759 static void internalizeGVsAfterImport(Module &M) {
1760   for (auto &GV : M.globals())
1761     // Skip GVs which have been converted to declarations
1762     // by dropDeadSymbols.
1763     if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
1764       GV.setLinkage(GlobalValue::InternalLinkage);
1765       GV.setVisibility(GlobalValue::DefaultVisibility);
1766     }
1767 }
1768 
1769 // Automatically import functions in Module \p DestModule based on the summaries
1770 // index.
1771 Expected<bool> FunctionImporter::importFunctions(
1772     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
1773   LLVM_DEBUG(dbgs() << "Starting import for Module "
1774                     << DestModule.getModuleIdentifier() << "\n");
1775   unsigned ImportedCount = 0, ImportedGVCount = 0;
1776 
1777   IRMover Mover(DestModule);
1778   // Do the actual import of functions now, one Module at a time
1779   std::set<StringRef> ModuleNameOrderedList;
1780   for (const auto &FunctionsToImportPerModule : ImportList) {
1781     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first);
1782   }
1783 
1784   auto getImportType = [&](const FunctionsToImportTy &GUIDToImportType,
1785                            GlobalValue::GUID GUID)
1786       -> std::optional<GlobalValueSummary::ImportKind> {
1787     auto Iter = GUIDToImportType.find(GUID);
1788     if (Iter == GUIDToImportType.end())
1789       return std::nullopt;
1790     return Iter->second;
1791   };
1792 
1793   for (const auto &Name : ModuleNameOrderedList) {
1794     // Get the module for the import
1795     const auto &FunctionsToImportPerModule = ImportList.find(Name);
1796     assert(FunctionsToImportPerModule != ImportList.end());
1797     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
1798     if (!SrcModuleOrErr)
1799       return SrcModuleOrErr.takeError();
1800     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
1801     assert(&DestModule.getContext() == &SrcModule->getContext() &&
1802            "Context mismatch");
1803 
1804     // If modules were created with lazy metadata loading, materialize it
1805     // now, before linking it (otherwise this will be a noop).
1806     if (Error Err = SrcModule->materializeMetadata())
1807       return std::move(Err);
1808 
1809     auto &ImportGUIDs = FunctionsToImportPerModule->second;
1810 
1811     // Find the globals to import
1812     SetVector<GlobalValue *> GlobalsToImport;
1813     for (Function &F : *SrcModule) {
1814       if (!F.hasName())
1815         continue;
1816       auto GUID = F.getGUID();
1817       auto MaybeImportType = getImportType(ImportGUIDs, GUID);
1818       bool ImportDefinition = MaybeImportType == GlobalValueSummary::Definition;
1819 
1820       LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
1821                         << " importing function"
1822                         << (ImportDefinition
1823                                 ? " definition "
1824                                 : (MaybeImportType ? " declaration " : " "))
1825                         << GUID << " " << F.getName() << " from "
1826                         << SrcModule->getSourceFileName() << "\n");
1827       if (ImportDefinition) {
1828         if (Error Err = F.materialize())
1829           return std::move(Err);
1830         // MemProf should match function's definition and summary,
1831         // 'thinlto_src_module' is needed.
1832         if (EnableImportMetadata || EnableMemProfContextDisambiguation) {
1833           // Add 'thinlto_src_module' and 'thinlto_src_file' metadata for
1834           // statistics and debugging.
1835           F.setMetadata(
1836               "thinlto_src_module",
1837               MDNode::get(DestModule.getContext(),
1838                           {MDString::get(DestModule.getContext(),
1839                                          SrcModule->getModuleIdentifier())}));
1840           F.setMetadata(
1841               "thinlto_src_file",
1842               MDNode::get(DestModule.getContext(),
1843                           {MDString::get(DestModule.getContext(),
1844                                          SrcModule->getSourceFileName())}));
1845         }
1846         GlobalsToImport.insert(&F);
1847       }
1848     }
1849     for (GlobalVariable &GV : SrcModule->globals()) {
1850       if (!GV.hasName())
1851         continue;
1852       auto GUID = GV.getGUID();
1853       auto MaybeImportType = getImportType(ImportGUIDs, GUID);
1854       bool ImportDefinition = MaybeImportType == GlobalValueSummary::Definition;
1855 
1856       LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
1857                         << " importing global"
1858                         << (ImportDefinition
1859                                 ? " definition "
1860                                 : (MaybeImportType ? " declaration " : " "))
1861                         << GUID << " " << GV.getName() << " from "
1862                         << SrcModule->getSourceFileName() << "\n");
1863       if (ImportDefinition) {
1864         if (Error Err = GV.materialize())
1865           return std::move(Err);
1866         ImportedGVCount += GlobalsToImport.insert(&GV);
1867       }
1868     }
1869     for (GlobalAlias &GA : SrcModule->aliases()) {
1870       if (!GA.hasName() || isa<GlobalIFunc>(GA.getAliaseeObject()))
1871         continue;
1872       auto GUID = GA.getGUID();
1873       auto MaybeImportType = getImportType(ImportGUIDs, GUID);
1874       bool ImportDefinition = MaybeImportType == GlobalValueSummary::Definition;
1875 
1876       LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
1877                         << " importing alias"
1878                         << (ImportDefinition
1879                                 ? " definition "
1880                                 : (MaybeImportType ? " declaration " : " "))
1881                         << GUID << " " << GA.getName() << " from "
1882                         << SrcModule->getSourceFileName() << "\n");
1883       if (ImportDefinition) {
1884         if (Error Err = GA.materialize())
1885           return std::move(Err);
1886         // Import alias as a copy of its aliasee.
1887         GlobalObject *GO = GA.getAliaseeObject();
1888         if (Error Err = GO->materialize())
1889           return std::move(Err);
1890         auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
1891         LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << GO->getGUID() << " "
1892                           << GO->getName() << " from "
1893                           << SrcModule->getSourceFileName() << "\n");
1894         if (EnableImportMetadata || EnableMemProfContextDisambiguation) {
1895           // Add 'thinlto_src_module' and 'thinlto_src_file' metadata for
1896           // statistics and debugging.
1897           Fn->setMetadata(
1898               "thinlto_src_module",
1899               MDNode::get(DestModule.getContext(),
1900                           {MDString::get(DestModule.getContext(),
1901                                          SrcModule->getModuleIdentifier())}));
1902           Fn->setMetadata(
1903               "thinlto_src_file",
1904               MDNode::get(DestModule.getContext(),
1905                           {MDString::get(DestModule.getContext(),
1906                                          SrcModule->getSourceFileName())}));
1907         }
1908         GlobalsToImport.insert(Fn);
1909       }
1910     }
1911 
1912     // Upgrade debug info after we're done materializing all the globals and we
1913     // have loaded all the required metadata!
1914     UpgradeDebugInfo(*SrcModule);
1915 
1916     // Set the partial sample profile ratio in the profile summary module flag
1917     // of the imported source module, if applicable, so that the profile summary
1918     // module flag will match with that of the destination module when it's
1919     // imported.
1920     SrcModule->setPartialSampleProfileRatio(Index);
1921 
1922     // Link in the specified functions.
1923     if (renameModuleForThinLTO(*SrcModule, Index, ClearDSOLocalOnDeclarations,
1924                                &GlobalsToImport))
1925       return true;
1926 
1927     if (PrintImports) {
1928       for (const auto *GV : GlobalsToImport)
1929         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
1930                << " from " << SrcModule->getSourceFileName() << "\n";
1931     }
1932 
1933     if (Error Err = Mover.move(std::move(SrcModule),
1934                                GlobalsToImport.getArrayRef(), nullptr,
1935                                /*IsPerformingImport=*/true))
1936       return createStringError(errc::invalid_argument,
1937                                Twine("Function Import: link error: ") +
1938                                    toString(std::move(Err)));
1939 
1940     ImportedCount += GlobalsToImport.size();
1941     NumImportedModules++;
1942   }
1943 
1944   internalizeGVsAfterImport(DestModule);
1945 
1946   NumImportedFunctions += (ImportedCount - ImportedGVCount);
1947   NumImportedGlobalVars += ImportedGVCount;
1948 
1949   // TODO: Print counters for definitions and declarations in the debugging log.
1950   LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
1951                     << " functions for Module "
1952                     << DestModule.getModuleIdentifier() << "\n");
1953   LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
1954                     << " global variables for Module "
1955                     << DestModule.getModuleIdentifier() << "\n");
1956   return ImportedCount;
1957 }
1958 
1959 static bool doImportingForModuleForTest(
1960     Module &M, function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
1961                    isPrevailing) {
1962   if (SummaryFile.empty())
1963     report_fatal_error("error: -function-import requires -summary-file\n");
1964   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
1965       getModuleSummaryIndexForFile(SummaryFile);
1966   if (!IndexPtrOrErr) {
1967     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
1968                           "Error loading file '" + SummaryFile + "': ");
1969     return false;
1970   }
1971   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
1972 
1973   // First step is collecting the import list.
1974   FunctionImporter::ImportMapTy ImportList;
1975   // If requested, simply import all functions in the index. This is used
1976   // when testing distributed backend handling via the opt tool, when
1977   // we have distributed indexes containing exactly the summaries to import.
1978   if (ImportAllIndex)
1979     ComputeCrossModuleImportForModuleFromIndexForTest(M.getModuleIdentifier(),
1980                                                       *Index, ImportList);
1981   else
1982     ComputeCrossModuleImportForModuleForTest(M.getModuleIdentifier(),
1983                                              isPrevailing, *Index, ImportList);
1984 
1985   // Conservatively mark all internal values as promoted. This interface is
1986   // only used when doing importing via the function importing pass. The pass
1987   // is only enabled when testing importing via the 'opt' tool, which does
1988   // not do the ThinLink that would normally determine what values to promote.
1989   for (auto &I : *Index) {
1990     for (auto &S : I.second.SummaryList) {
1991       if (GlobalValue::isLocalLinkage(S->linkage()))
1992         S->setLinkage(GlobalValue::ExternalLinkage);
1993     }
1994   }
1995 
1996   // Next we need to promote to global scope and rename any local values that
1997   // are potentially exported to other modules.
1998   if (renameModuleForThinLTO(M, *Index, /*ClearDSOLocalOnDeclarations=*/false,
1999                              /*GlobalsToImport=*/nullptr)) {
2000     errs() << "Error renaming module\n";
2001     return true;
2002   }
2003 
2004   // Perform the import now.
2005   auto ModuleLoader = [&M](StringRef Identifier) {
2006     return loadFile(std::string(Identifier), M.getContext());
2007   };
2008   FunctionImporter Importer(*Index, ModuleLoader,
2009                             /*ClearDSOLocalOnDeclarations=*/false);
2010   Expected<bool> Result = Importer.importFunctions(M, ImportList);
2011 
2012   // FIXME: Probably need to propagate Errors through the pass manager.
2013   if (!Result) {
2014     logAllUnhandledErrors(Result.takeError(), errs(),
2015                           "Error importing module: ");
2016     return true;
2017   }
2018 
2019   return true;
2020 }
2021 
2022 PreservedAnalyses FunctionImportPass::run(Module &M,
2023                                           ModuleAnalysisManager &AM) {
2024   // This is only used for testing the function import pass via opt, where we
2025   // don't have prevailing information from the LTO context available, so just
2026   // conservatively assume everything is prevailing (which is fine for the very
2027   // limited use of prevailing checking in this pass).
2028   auto isPrevailing = [](GlobalValue::GUID, const GlobalValueSummary *) {
2029     return true;
2030   };
2031   if (!doImportingForModuleForTest(M, isPrevailing))
2032     return PreservedAnalyses::all();
2033 
2034   return PreservedAnalyses::none();
2035 }
2036