142418abaSMehdi Amini //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
242418abaSMehdi Amini //
342418abaSMehdi Amini //                     The LLVM Compiler Infrastructure
442418abaSMehdi Amini //
542418abaSMehdi Amini // This file is distributed under the University of Illinois Open Source
642418abaSMehdi Amini // License. See LICENSE.TXT for details.
742418abaSMehdi Amini //
842418abaSMehdi Amini //===----------------------------------------------------------------------===//
942418abaSMehdi Amini //
1042418abaSMehdi Amini // This file implements Function import based on summaries.
1142418abaSMehdi Amini //
1242418abaSMehdi Amini //===----------------------------------------------------------------------===//
1342418abaSMehdi Amini 
1442418abaSMehdi Amini #include "llvm/Transforms/IPO/FunctionImport.h"
1542418abaSMehdi Amini 
1601e32130SMehdi Amini #include "llvm/ADT/SmallVector.h"
17d29478f7STeresa Johnson #include "llvm/ADT/Statistic.h"
1842418abaSMehdi Amini #include "llvm/ADT/StringSet.h"
1904c9a2d6STeresa Johnson #include "llvm/ADT/Triple.h"
20c15d60b7SPeter Collingbourne #include "llvm/Bitcode/BitcodeReader.h"
2142418abaSMehdi Amini #include "llvm/IR/AutoUpgrade.h"
2242418abaSMehdi Amini #include "llvm/IR/DiagnosticPrinter.h"
2342418abaSMehdi Amini #include "llvm/IR/IntrinsicInst.h"
2442418abaSMehdi Amini #include "llvm/IR/Module.h"
25fc06b83eSMehdi Amini #include "llvm/IR/Verifier.h"
2642418abaSMehdi Amini #include "llvm/IRReader/IRReader.h"
2742418abaSMehdi Amini #include "llvm/Linker/Linker.h"
2804c9a2d6STeresa Johnson #include "llvm/Object/IRObjectFile.h"
2942418abaSMehdi Amini #include "llvm/Support/CommandLine.h"
3042418abaSMehdi Amini #include "llvm/Support/Debug.h"
3142418abaSMehdi Amini #include "llvm/Support/SourceMgr.h"
3204c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h"
33488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h"
347e88d0daSMehdi Amini 
3501e32130SMehdi Amini #define DEBUG_TYPE "function-import"
367e88d0daSMehdi Amini 
3742418abaSMehdi Amini using namespace llvm;
3842418abaSMehdi Amini 
396c475a75STeresa Johnson STATISTIC(NumImportedFunctions, "Number of functions imported");
406c475a75STeresa Johnson STATISTIC(NumImportedModules, "Number of modules imported from");
416c475a75STeresa Johnson STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
426c475a75STeresa Johnson STATISTIC(NumLiveSymbols, "Number of live symbols in index");
43d29478f7STeresa Johnson 
4439303619STeresa Johnson /// Limit on instruction count of imported functions.
4539303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit(
4639303619STeresa Johnson     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
4739303619STeresa Johnson     cl::desc("Only import functions with less than N instructions"));
4839303619STeresa Johnson 
4940641748SMehdi Amini static cl::opt<float>
5040641748SMehdi Amini     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
5140641748SMehdi Amini                       cl::Hidden, cl::value_desc("x"),
5240641748SMehdi Amini                       cl::desc("As we import functions, multiply the "
5340641748SMehdi Amini                                "`import-instr-limit` threshold by this factor "
5440641748SMehdi Amini                                "before processing newly imported functions"));
55ba72b95fSPiotr Padlewski 
56d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor(
57d2869473SPiotr Padlewski     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
58d2869473SPiotr Padlewski     cl::value_desc("x"),
59d2869473SPiotr Padlewski     cl::desc("As we import functions called from hot callsite, multiply the "
60d2869473SPiotr Padlewski              "`import-instr-limit` threshold by this factor "
61d2869473SPiotr Padlewski              "before processing newly imported functions"));
62d2869473SPiotr Padlewski 
63d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier(
64d9830eb7SPiotr Padlewski     "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
65ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
66ba72b95fSPiotr Padlewski 
67ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up.
68ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier(
69ba72b95fSPiotr Padlewski     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
70ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
7140641748SMehdi Amini 
72d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
73d29478f7STeresa Johnson                                   cl::desc("Print imported functions"));
74d29478f7STeresa Johnson 
756c475a75STeresa Johnson static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
766c475a75STeresa Johnson                                  cl::desc("Compute dead symbols"));
776c475a75STeresa Johnson 
783b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata(
793b776128SPiotr Padlewski     "enable-import-metadata", cl::init(
803b776128SPiotr Padlewski #if !defined(NDEBUG)
813b776128SPiotr Padlewski                                   true /*Enabled with asserts.*/
823b776128SPiotr Padlewski #else
833b776128SPiotr Padlewski                                   false
843b776128SPiotr Padlewski #endif
853b776128SPiotr Padlewski                                   ),
863b776128SPiotr Padlewski     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
873b776128SPiotr Padlewski 
8842418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context.
8942418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName,
9042418abaSMehdi Amini                                         LLVMContext &Context) {
9142418abaSMehdi Amini   SMDiagnostic Err;
9242418abaSMehdi Amini   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
936cba37ceSTeresa Johnson   // Metadata isn't loaded until functions are imported, to minimize
946cba37ceSTeresa Johnson   // the memory overhead.
95a1080ee6STeresa Johnson   std::unique_ptr<Module> Result =
96a1080ee6STeresa Johnson       getLazyIRFileModule(FileName, Err, Context,
97a1080ee6STeresa Johnson                           /* ShouldLazyLoadMetadata = */ true);
9842418abaSMehdi Amini   if (!Result) {
9942418abaSMehdi Amini     Err.print("function-import", errs());
100d7ad221cSMehdi Amini     report_fatal_error("Abort");
10142418abaSMehdi Amini   }
10242418abaSMehdi Amini 
10342418abaSMehdi Amini   return Result;
10442418abaSMehdi Amini }
10542418abaSMehdi Amini 
1067e88d0daSMehdi Amini namespace {
10740641748SMehdi Amini 
10801e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one
10901e32130SMehdi Amini /// that fits the \p Threshold.
11001e32130SMehdi Amini ///
11101e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"?
11201e32130SMehdi Amini /// - The smallest: more likely to be inlined.
11301e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized).
11401e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the
11501e32130SMehdi Amini ///   number of source modules parsed/linked.
11601e32130SMehdi Amini /// - One that has PGO data attached.
11701e32130SMehdi Amini /// - [insert you fancy metric here]
1182d28f7aaSMehdi Amini static const GlobalValueSummary *
119b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index,
1209667b91bSPeter Collingbourne              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
12183aaf358STeresa Johnson              unsigned Threshold, StringRef CallerModulePath) {
12201e32130SMehdi Amini   auto It = llvm::find_if(
12328e457bcSTeresa Johnson       CalleeSummaryList,
12428e457bcSTeresa Johnson       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
12528e457bcSTeresa Johnson         auto *GVSummary = SummaryPtr.get();
126f329be83SRafael Espindola         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
1275b85d8d6SMehdi Amini           // There is no point in importing these, we can't inline them
12801e32130SMehdi Amini           return false;
1292c719cc1SMehdi Amini         if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
1302c719cc1SMehdi Amini           GVSummary = &AS->getAliasee();
1312c719cc1SMehdi Amini           // Alias can't point to "available_externally". However when we import
1322c719cc1SMehdi Amini           // linkOnceODR the linkage does not change. So we import the alias
1332c719cc1SMehdi Amini           // and aliasee only in this case.
1342c719cc1SMehdi Amini           // FIXME: we should import alias as available_externally *function*,
1352c719cc1SMehdi Amini           // the destination module does need to know it is an alias.
1362c719cc1SMehdi Amini           if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
1372c719cc1SMehdi Amini             return false;
1382c719cc1SMehdi Amini         }
1392c719cc1SMehdi Amini 
1402c719cc1SMehdi Amini         auto *Summary = cast<FunctionSummary>(GVSummary);
1417e88d0daSMehdi Amini 
14283aaf358STeresa Johnson         // If this is a local function, make sure we import the copy
14383aaf358STeresa Johnson         // in the caller's module. The only time a local function can
14483aaf358STeresa Johnson         // share an entry in the index is if there is a local with the same name
14583aaf358STeresa Johnson         // in another module that had the same source file name (in a different
14683aaf358STeresa Johnson         // directory), where each was compiled in their own directory so there
14783aaf358STeresa Johnson         // was not distinguishing path.
14883aaf358STeresa Johnson         // However, do the import from another module if there is only one
14983aaf358STeresa Johnson         // entry in the list - in that case this must be a reference due
15083aaf358STeresa Johnson         // to indirect call profile data, since a function pointer can point to
15183aaf358STeresa Johnson         // a local in another module.
15283aaf358STeresa Johnson         if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
15383aaf358STeresa Johnson             CalleeSummaryList.size() > 1 &&
15483aaf358STeresa Johnson             Summary->modulePath() != CallerModulePath)
15583aaf358STeresa Johnson           return false;
15683aaf358STeresa Johnson 
15701e32130SMehdi Amini         if (Summary->instCount() > Threshold)
15801e32130SMehdi Amini           return false;
1597e88d0daSMehdi Amini 
160519465b9STeresa Johnson         if (Summary->notEligibleToImport())
161b4e1e829SMehdi Amini           return false;
162b4e1e829SMehdi Amini 
16301e32130SMehdi Amini         return true;
16401e32130SMehdi Amini       });
16528e457bcSTeresa Johnson   if (It == CalleeSummaryList.end())
16601e32130SMehdi Amini     return nullptr;
1677e88d0daSMehdi Amini 
16828e457bcSTeresa Johnson   return cast<GlobalValueSummary>(It->get());
169434e9561SRafael Espindola }
1707e88d0daSMehdi Amini 
171475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
172475b51a7STeresa Johnson                             GlobalValue::GUID>;
17301e32130SMehdi Amini 
17401e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these
17501e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as
17601e32130SMehdi Amini /// exported from their source module.
17701e32130SMehdi Amini static void computeImportForFunction(
1783255eec1STeresa Johnson     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
179d9830eb7SPiotr Padlewski     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
18001e32130SMehdi Amini     SmallVectorImpl<EdgeInfo> &Worklist,
1819b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
182c86af334STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
18301e32130SMehdi Amini   for (auto &Edge : Summary.calls()) {
1849667b91bSPeter Collingbourne     ValueInfo VI = Edge.first;
1859667b91bSPeter Collingbourne     DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
1869667b91bSPeter Collingbourne                  << "\n");
18701e32130SMehdi Amini 
1889667b91bSPeter Collingbourne     if (VI.getSummaryList().empty()) {
1894a435e08SDehao Chen       // For SamplePGO, the indirect call targets for local functions will
1904a435e08SDehao Chen       // have its original name annotated in profile. We try to find the
1914a435e08SDehao Chen       // corresponding PGOFuncName as the GUID.
1929667b91bSPeter Collingbourne       auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
1934a435e08SDehao Chen       if (GUID == 0)
1944a435e08SDehao Chen         continue;
1959667b91bSPeter Collingbourne       VI = Index.getValueInfo(GUID);
1969667b91bSPeter Collingbourne       if (!VI)
1979667b91bSPeter Collingbourne         continue;
1984a435e08SDehao Chen     }
1994a435e08SDehao Chen 
2009667b91bSPeter Collingbourne     if (DefinedGVSummaries.count(VI.getGUID())) {
20101e32130SMehdi Amini       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
2027e88d0daSMehdi Amini       continue;
203d450da32STeresa Johnson     }
20440641748SMehdi Amini 
205ba72b95fSPiotr Padlewski     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
206ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Hot)
207ba72b95fSPiotr Padlewski         return ImportHotMultiplier;
208ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Cold)
209ba72b95fSPiotr Padlewski         return ImportColdMultiplier;
210ba72b95fSPiotr Padlewski       return 1.0;
211ba72b95fSPiotr Padlewski     };
212ba72b95fSPiotr Padlewski 
213d9830eb7SPiotr Padlewski     const auto NewThreshold =
214ba72b95fSPiotr Padlewski         Threshold * GetBonusMultiplier(Edge.second.Hotness);
215d2869473SPiotr Padlewski 
2169667b91bSPeter Collingbourne     auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
2179667b91bSPeter Collingbourne                                        Summary.modulePath());
21801e32130SMehdi Amini     if (!CalleeSummary) {
21901e32130SMehdi Amini       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
2207e88d0daSMehdi Amini       continue;
2217e88d0daSMehdi Amini     }
2222d28f7aaSMehdi Amini     // "Resolve" the summary, traversing alias,
2232d28f7aaSMehdi Amini     const FunctionSummary *ResolvedCalleeSummary;
2246968ef77SMehdi Amini     if (isa<AliasSummary>(CalleeSummary)) {
2252d28f7aaSMehdi Amini       ResolvedCalleeSummary = cast<FunctionSummary>(
2262d28f7aaSMehdi Amini           &cast<AliasSummary>(CalleeSummary)->getAliasee());
2272c719cc1SMehdi Amini       assert(
2282c719cc1SMehdi Amini           GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
2292c719cc1SMehdi Amini           "Unexpected alias to a non-linkonceODR in import list");
2306968ef77SMehdi Amini     } else
2312d28f7aaSMehdi Amini       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
2322d28f7aaSMehdi Amini 
233d9830eb7SPiotr Padlewski     assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
23401e32130SMehdi Amini            "selectCallee() didn't honor the threshold");
23501e32130SMehdi Amini 
236d2869473SPiotr Padlewski     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
237d2869473SPiotr Padlewski       // Adjust the threshold for next level of imported functions.
238d2869473SPiotr Padlewski       // The threshold is different for hot callsites because we can then
239d2869473SPiotr Padlewski       // inline chains of hot calls.
240d2869473SPiotr Padlewski       if (IsHotCallsite)
241d2869473SPiotr Padlewski         return Threshold * ImportHotInstrFactor;
242d2869473SPiotr Padlewski       return Threshold * ImportInstrFactor;
243d2869473SPiotr Padlewski     };
244d2869473SPiotr Padlewski 
245d2869473SPiotr Padlewski     bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
2461b859a23STeresa Johnson     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
2471b859a23STeresa Johnson 
2481b859a23STeresa Johnson     auto ExportModulePath = ResolvedCalleeSummary->modulePath();
2499667b91bSPeter Collingbourne     auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
2501b859a23STeresa Johnson     /// Since the traversal of the call graph is DFS, we can revisit a function
2511b859a23STeresa Johnson     /// a second time with a higher threshold. In this case, it is added back to
2521b859a23STeresa Johnson     /// the worklist with the new threshold.
2531b859a23STeresa Johnson     if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
2541b859a23STeresa Johnson       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
2551b859a23STeresa Johnson                    << ProcessedThreshold << "\n");
2561b859a23STeresa Johnson       continue;
2571b859a23STeresa Johnson     }
25819f2aa78STeresa Johnson     bool PreviouslyImported = ProcessedThreshold != 0;
2591b859a23STeresa Johnson     // Mark this function as imported in this module, with the current Threshold
2601b859a23STeresa Johnson     ProcessedThreshold = AdjThreshold;
2611b859a23STeresa Johnson 
2621b859a23STeresa Johnson     // Make exports in the source module.
2631b859a23STeresa Johnson     if (ExportLists) {
2641b859a23STeresa Johnson       auto &ExportList = (*ExportLists)[ExportModulePath];
2659667b91bSPeter Collingbourne       ExportList.insert(VI.getGUID());
26619f2aa78STeresa Johnson       if (!PreviouslyImported) {
26719f2aa78STeresa Johnson         // This is the first time this function was exported from its source
26819f2aa78STeresa Johnson         // module, so mark all functions and globals it references as exported
2691b859a23STeresa Johnson         // to the outside if they are defined in the same source module.
270edddca22STeresa Johnson         // For efficiency, we unconditionally add all the referenced GUIDs
271edddca22STeresa Johnson         // to the ExportList for this module, and will prune out any not
272edddca22STeresa Johnson         // defined in the module later in a single pass.
2731b859a23STeresa Johnson         for (auto &Edge : ResolvedCalleeSummary->calls()) {
2741b859a23STeresa Johnson           auto CalleeGUID = Edge.first.getGUID();
275edddca22STeresa Johnson           ExportList.insert(CalleeGUID);
2761b859a23STeresa Johnson         }
2771b859a23STeresa Johnson         for (auto &Ref : ResolvedCalleeSummary->refs()) {
2781b859a23STeresa Johnson           auto GUID = Ref.getGUID();
279edddca22STeresa Johnson           ExportList.insert(GUID);
2801b859a23STeresa Johnson         }
2811b859a23STeresa Johnson       }
28219f2aa78STeresa Johnson     }
283d2869473SPiotr Padlewski 
28401e32130SMehdi Amini     // Insert the newly imported function to the worklist.
2859667b91bSPeter Collingbourne     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
286d450da32STeresa Johnson   }
287d450da32STeresa Johnson }
288d450da32STeresa Johnson 
28901e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports
29001e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from
29101e32130SMehdi Amini /// another module (that may require promotion).
29201e32130SMehdi Amini static void ComputeImportForModule(
293c851d216STeresa Johnson     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
2949b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
295*56584bbfSEvgeniy Stepanov     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
29601e32130SMehdi Amini   // Worklist contains the list of function imported in this module, for which
29701e32130SMehdi Amini   // we will analyse the callees and may import further down the callgraph.
29801e32130SMehdi Amini   SmallVector<EdgeInfo, 128> Worklist;
29901e32130SMehdi Amini 
30001e32130SMehdi Amini   // Populate the worklist with the import for the functions in the current
30101e32130SMehdi Amini   // module
30228e457bcSTeresa Johnson   for (auto &GVSummary : DefinedGVSummaries) {
303*56584bbfSEvgeniy Stepanov     if (!Index.isGlobalValueLive(GVSummary.second)) {
3046c475a75STeresa Johnson       DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
3056c475a75STeresa Johnson       continue;
3066c475a75STeresa Johnson     }
30728e457bcSTeresa Johnson     auto *Summary = GVSummary.second;
3082d28f7aaSMehdi Amini     if (auto *AS = dyn_cast<AliasSummary>(Summary))
3092d28f7aaSMehdi Amini       Summary = &AS->getAliasee();
3101aafabf7SMehdi Amini     auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
3111aafabf7SMehdi Amini     if (!FuncSummary)
3121aafabf7SMehdi Amini       // Skip import for global variables
3131aafabf7SMehdi Amini       continue;
31428e457bcSTeresa Johnson     DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
3152d28f7aaSMehdi Amini     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
3169b490f10SMehdi Amini                              DefinedGVSummaries, Worklist, ImportList,
31701e32130SMehdi Amini                              ExportLists);
31801e32130SMehdi Amini   }
31901e32130SMehdi Amini 
320d2869473SPiotr Padlewski   // Process the newly imported functions and add callees to the worklist.
32142418abaSMehdi Amini   while (!Worklist.empty()) {
32201e32130SMehdi Amini     auto FuncInfo = Worklist.pop_back_val();
323475b51a7STeresa Johnson     auto *Summary = std::get<0>(FuncInfo);
324475b51a7STeresa Johnson     auto Threshold = std::get<1>(FuncInfo);
325475b51a7STeresa Johnson     auto GUID = std::get<2>(FuncInfo);
326475b51a7STeresa Johnson 
327475b51a7STeresa Johnson     // Check if we later added this summary with a higher threshold.
328475b51a7STeresa Johnson     // If so, skip this entry.
329475b51a7STeresa Johnson     auto ExportModulePath = Summary->modulePath();
330475b51a7STeresa Johnson     auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
331475b51a7STeresa Johnson     if (LatestProcessedThreshold > Threshold)
332475b51a7STeresa Johnson       continue;
33342418abaSMehdi Amini 
3341aafabf7SMehdi Amini     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
3359b490f10SMehdi Amini                              Worklist, ImportList, ExportLists);
336c8c55170SMehdi Amini   }
33742418abaSMehdi Amini }
338ffe2e4aaSMehdi Amini 
33901e32130SMehdi Amini } // anonymous namespace
34001e32130SMehdi Amini 
341c86af334STeresa Johnson /// Compute all the import and export for every module using the Index.
34201e32130SMehdi Amini void llvm::ComputeCrossModuleImport(
34301e32130SMehdi Amini     const ModuleSummaryIndex &Index,
344c851d216STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
34501e32130SMehdi Amini     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
346*56584bbfSEvgeniy Stepanov     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
34701e32130SMehdi Amini   // For each module that has function defined, compute the import/export lists.
3481aafabf7SMehdi Amini   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
3499b490f10SMehdi Amini     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
3501aafabf7SMehdi Amini     DEBUG(dbgs() << "Computing import for Module '"
3511aafabf7SMehdi Amini                  << DefinedGVSummaries.first() << "'\n");
3529b490f10SMehdi Amini     ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
353*56584bbfSEvgeniy Stepanov                            &ExportLists);
35401e32130SMehdi Amini   }
35501e32130SMehdi Amini 
356edddca22STeresa Johnson   // When computing imports we added all GUIDs referenced by anything
357edddca22STeresa Johnson   // imported from the module to its ExportList. Now we prune each ExportList
358edddca22STeresa Johnson   // of any not defined in that module. This is more efficient than checking
359edddca22STeresa Johnson   // while computing imports because some of the summary lists may be long
360edddca22STeresa Johnson   // due to linkonce (comdat) copies.
361edddca22STeresa Johnson   for (auto &ELI : ExportLists) {
362edddca22STeresa Johnson     const auto &DefinedGVSummaries =
363edddca22STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ELI.first());
364edddca22STeresa Johnson     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
365edddca22STeresa Johnson       if (!DefinedGVSummaries.count(*EI))
366edddca22STeresa Johnson         EI = ELI.second.erase(EI);
367edddca22STeresa Johnson       else
368edddca22STeresa Johnson         ++EI;
369edddca22STeresa Johnson     }
370edddca22STeresa Johnson   }
371edddca22STeresa Johnson 
37201e32130SMehdi Amini #ifndef NDEBUG
37301e32130SMehdi Amini   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
37401e32130SMehdi Amini                << " modules:\n");
37501e32130SMehdi Amini   for (auto &ModuleImports : ImportLists) {
37601e32130SMehdi Amini     auto ModName = ModuleImports.first();
37701e32130SMehdi Amini     auto &Exports = ExportLists[ModName];
37801e32130SMehdi Amini     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
37901e32130SMehdi Amini                  << " functions. Imports from " << ModuleImports.second.size()
38001e32130SMehdi Amini                  << " modules.\n");
38101e32130SMehdi Amini     for (auto &Src : ModuleImports.second) {
38201e32130SMehdi Amini       auto SrcModName = Src.first();
38301e32130SMehdi Amini       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
38401e32130SMehdi Amini                    << SrcModName << "\n");
38501e32130SMehdi Amini     }
38601e32130SMehdi Amini   }
38701e32130SMehdi Amini #endif
38801e32130SMehdi Amini }
38901e32130SMehdi Amini 
390c86af334STeresa Johnson /// Compute all the imports for the given module in the Index.
391c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule(
392c86af334STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
393c86af334STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
394c86af334STeresa Johnson 
395c86af334STeresa Johnson   // Collect the list of functions this module defines.
396c86af334STeresa Johnson   // GUID -> Summary
397c851d216STeresa Johnson   GVSummaryMapTy FunctionSummaryMap;
39828e457bcSTeresa Johnson   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
399c86af334STeresa Johnson 
400c86af334STeresa Johnson   // Compute the import list for this module.
401c86af334STeresa Johnson   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
40228e457bcSTeresa Johnson   ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
403c86af334STeresa Johnson 
404c86af334STeresa Johnson #ifndef NDEBUG
405c86af334STeresa Johnson   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
406c86af334STeresa Johnson                << ImportList.size() << " modules.\n");
407c86af334STeresa Johnson   for (auto &Src : ImportList) {
408c86af334STeresa Johnson     auto SrcModName = Src.first();
409c86af334STeresa Johnson     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
410c86af334STeresa Johnson                  << SrcModName << "\n");
411c86af334STeresa Johnson   }
412c86af334STeresa Johnson #endif
413c86af334STeresa Johnson }
414c86af334STeresa Johnson 
415*56584bbfSEvgeniy Stepanov void llvm::computeDeadSymbols(
416*56584bbfSEvgeniy Stepanov     ModuleSummaryIndex &Index,
4176c475a75STeresa Johnson     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
418*56584bbfSEvgeniy Stepanov   assert(!Index.withGlobalValueDeadStripping());
4196c475a75STeresa Johnson   if (!ComputeDead)
420*56584bbfSEvgeniy Stepanov     return;
4216c475a75STeresa Johnson   if (GUIDPreservedSymbols.empty())
4226c475a75STeresa Johnson     // Don't do anything when nothing is live, this is friendly with tests.
423*56584bbfSEvgeniy Stepanov     return;
424*56584bbfSEvgeniy Stepanov   unsigned LiveSymbols = 0;
4259667b91bSPeter Collingbourne   SmallVector<ValueInfo, 128> Worklist;
4269667b91bSPeter Collingbourne   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
4279667b91bSPeter Collingbourne   for (auto GUID : GUIDPreservedSymbols) {
4289667b91bSPeter Collingbourne     ValueInfo VI = Index.getValueInfo(GUID);
4299667b91bSPeter Collingbourne     if (!VI)
4309667b91bSPeter Collingbourne       continue;
431*56584bbfSEvgeniy Stepanov     for (auto &S : VI.getSummaryList())
432*56584bbfSEvgeniy Stepanov       S->setLive(true);
4336c475a75STeresa Johnson   }
434*56584bbfSEvgeniy Stepanov 
4356c475a75STeresa Johnson   // Add values flagged in the index as live roots to the worklist.
436*56584bbfSEvgeniy Stepanov   for (const auto &Entry : Index)
437*56584bbfSEvgeniy Stepanov     for (auto &S : Entry.second.SummaryList)
438*56584bbfSEvgeniy Stepanov       if (S->isLive()) {
439*56584bbfSEvgeniy Stepanov         DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
4409667b91bSPeter Collingbourne         Worklist.push_back(ValueInfo(&Entry));
441*56584bbfSEvgeniy Stepanov         ++LiveSymbols;
442*56584bbfSEvgeniy Stepanov         break;
4436c475a75STeresa Johnson       }
4446c475a75STeresa Johnson 
445*56584bbfSEvgeniy Stepanov   // Make value live and add it to the worklist if it was not live before.
446*56584bbfSEvgeniy Stepanov   // FIXME: we should only make the prevailing copy live here
447*56584bbfSEvgeniy Stepanov   auto visit = [&](ValueInfo VI) {
448*56584bbfSEvgeniy Stepanov     for (auto &S : VI.getSummaryList())
449*56584bbfSEvgeniy Stepanov       if (S->isLive())
450*56584bbfSEvgeniy Stepanov         return;
451*56584bbfSEvgeniy Stepanov     for (auto &S : VI.getSummaryList())
452*56584bbfSEvgeniy Stepanov       S->setLive(true);
453*56584bbfSEvgeniy Stepanov     ++LiveSymbols;
454*56584bbfSEvgeniy Stepanov     Worklist.push_back(VI);
455*56584bbfSEvgeniy Stepanov   };
456*56584bbfSEvgeniy Stepanov 
4576c475a75STeresa Johnson   while (!Worklist.empty()) {
4589667b91bSPeter Collingbourne     auto VI = Worklist.pop_back_val();
4599667b91bSPeter Collingbourne     for (auto &Summary : VI.getSummaryList()) {
460*56584bbfSEvgeniy Stepanov       for (auto Ref : Summary->refs())
461*56584bbfSEvgeniy Stepanov         visit(Ref);
462*56584bbfSEvgeniy Stepanov       if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
463*56584bbfSEvgeniy Stepanov         for (auto Call : FS->calls())
464*56584bbfSEvgeniy Stepanov           visit(Call.first);
4656c475a75STeresa Johnson       if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
4666c475a75STeresa Johnson         auto AliaseeGUID = AS->getAliasee().getOriginalName();
4679667b91bSPeter Collingbourne         ValueInfo AliaseeVI = Index.getValueInfo(AliaseeGUID);
468*56584bbfSEvgeniy Stepanov         if (AliaseeVI)
469*56584bbfSEvgeniy Stepanov           visit(AliaseeVI);
4706c475a75STeresa Johnson       }
4716c475a75STeresa Johnson     }
4726c475a75STeresa Johnson   }
473*56584bbfSEvgeniy Stepanov   Index.setWithGlobalValueDeadStripping();
474*56584bbfSEvgeniy Stepanov 
475*56584bbfSEvgeniy Stepanov   unsigned DeadSymbols = Index.size() - LiveSymbols;
476*56584bbfSEvgeniy Stepanov   DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
477*56584bbfSEvgeniy Stepanov                << " symbols Dead \n");
478*56584bbfSEvgeniy Stepanov   NumDeadSymbols += DeadSymbols;
479*56584bbfSEvgeniy Stepanov   NumLiveSymbols += LiveSymbols;
4806c475a75STeresa Johnson }
4816c475a75STeresa Johnson 
48284174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of
48384174c37STeresa Johnson /// \p ModulePath.
48484174c37STeresa Johnson void llvm::gatherImportedSummariesForModule(
48584174c37STeresa Johnson     StringRef ModulePath,
48684174c37STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
487cdbcbf74SMehdi Amini     const FunctionImporter::ImportMapTy &ImportList,
48884174c37STeresa Johnson     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
48984174c37STeresa Johnson   // Include all summaries from the importing module.
49084174c37STeresa Johnson   ModuleToSummariesForIndex[ModulePath] =
49184174c37STeresa Johnson       ModuleToDefinedGVSummaries.lookup(ModulePath);
49284174c37STeresa Johnson   // Include summaries for imports.
49388c491ddSMehdi Amini   for (auto &ILI : ImportList) {
49484174c37STeresa Johnson     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
49584174c37STeresa Johnson     const auto &DefinedGVSummaries =
49684174c37STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ILI.first());
49784174c37STeresa Johnson     for (auto &GI : ILI.second) {
49884174c37STeresa Johnson       const auto &DS = DefinedGVSummaries.find(GI.first);
49984174c37STeresa Johnson       assert(DS != DefinedGVSummaries.end() &&
50084174c37STeresa Johnson              "Expected a defined summary for imported global value");
50184174c37STeresa Johnson       SummariesForIndex[GI.first] = DS->second;
50284174c37STeresa Johnson     }
50384174c37STeresa Johnson   }
50484174c37STeresa Johnson }
50584174c37STeresa Johnson 
5068570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename.
507cdbcbf74SMehdi Amini std::error_code
508cdbcbf74SMehdi Amini llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
509cdbcbf74SMehdi Amini                        const FunctionImporter::ImportMapTy &ModuleImports) {
5108570fe47STeresa Johnson   std::error_code EC;
5118570fe47STeresa Johnson   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
5128570fe47STeresa Johnson   if (EC)
5138570fe47STeresa Johnson     return EC;
514cdbcbf74SMehdi Amini   for (auto &ILI : ModuleImports)
5158570fe47STeresa Johnson     ImportsOS << ILI.first() << "\n";
5168570fe47STeresa Johnson   return std::error_code();
5178570fe47STeresa Johnson }
5188570fe47STeresa Johnson 
51904c9a2d6STeresa Johnson /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
52004c9a2d6STeresa Johnson void llvm::thinLTOResolveWeakForLinkerModule(
52104c9a2d6STeresa Johnson     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
5224566c6dbSTeresa Johnson   auto ConvertToDeclaration = [](GlobalValue &GV) {
5234566c6dbSTeresa Johnson     DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
5244566c6dbSTeresa Johnson     if (Function *F = dyn_cast<Function>(&GV)) {
5254566c6dbSTeresa Johnson       F->deleteBody();
5264566c6dbSTeresa Johnson       F->clearMetadata();
5274566c6dbSTeresa Johnson     } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
5284566c6dbSTeresa Johnson       V->setInitializer(nullptr);
5294566c6dbSTeresa Johnson       V->setLinkage(GlobalValue::ExternalLinkage);
5304566c6dbSTeresa Johnson       V->clearMetadata();
5314566c6dbSTeresa Johnson     } else
5324566c6dbSTeresa Johnson       // For now we don't resolve or drop aliases. Once we do we'll
5334566c6dbSTeresa Johnson       // need to add support here for creating either a function or
5344566c6dbSTeresa Johnson       // variable declaration, and return the new GlobalValue* for
5354566c6dbSTeresa Johnson       // the caller to use.
53691239088SDavide Italiano       llvm_unreachable("Expected function or variable");
5374566c6dbSTeresa Johnson   };
5384566c6dbSTeresa Johnson 
53904c9a2d6STeresa Johnson   auto updateLinkage = [&](GlobalValue &GV) {
54004c9a2d6STeresa Johnson     if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
54104c9a2d6STeresa Johnson       return;
54204c9a2d6STeresa Johnson     // See if the global summary analysis computed a new resolved linkage.
54304c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
54404c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end())
54504c9a2d6STeresa Johnson       return;
54604c9a2d6STeresa Johnson     auto NewLinkage = GS->second->linkage();
54704c9a2d6STeresa Johnson     if (NewLinkage == GV.getLinkage())
54804c9a2d6STeresa Johnson       return;
5494566c6dbSTeresa Johnson     // Check for a non-prevailing def that has interposable linkage
5504566c6dbSTeresa Johnson     // (e.g. non-odr weak or linkonce). In that case we can't simply
5514566c6dbSTeresa Johnson     // convert to available_externally, since it would lose the
5524566c6dbSTeresa Johnson     // interposable property and possibly get inlined. Simply drop
5534566c6dbSTeresa Johnson     // the definition in that case.
5544566c6dbSTeresa Johnson     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
5554566c6dbSTeresa Johnson         GlobalValue::isInterposableLinkage(GV.getLinkage()))
5564566c6dbSTeresa Johnson       ConvertToDeclaration(GV);
5574566c6dbSTeresa Johnson     else {
55804c9a2d6STeresa Johnson       DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
55904c9a2d6STeresa Johnson                    << GV.getLinkage() << " to " << NewLinkage << "\n");
56004c9a2d6STeresa Johnson       GV.setLinkage(NewLinkage);
5614566c6dbSTeresa Johnson     }
5624566c6dbSTeresa Johnson     // Remove declarations from comdats, including available_externally
5636107a419STeresa Johnson     // as this is a declaration for the linker, and will be dropped eventually.
5646107a419STeresa Johnson     // It is illegal for comdats to contain declarations.
5656107a419STeresa Johnson     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
5664566c6dbSTeresa Johnson     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
5676107a419STeresa Johnson       GO->setComdat(nullptr);
56804c9a2d6STeresa Johnson   };
56904c9a2d6STeresa Johnson 
57004c9a2d6STeresa Johnson   // Process functions and global now
57104c9a2d6STeresa Johnson   for (auto &GV : TheModule)
57204c9a2d6STeresa Johnson     updateLinkage(GV);
57304c9a2d6STeresa Johnson   for (auto &GV : TheModule.globals())
57404c9a2d6STeresa Johnson     updateLinkage(GV);
57504c9a2d6STeresa Johnson   for (auto &GV : TheModule.aliases())
57604c9a2d6STeresa Johnson     updateLinkage(GV);
57704c9a2d6STeresa Johnson }
57804c9a2d6STeresa Johnson 
57904c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis.
58004c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule,
58104c9a2d6STeresa Johnson                                     const GVSummaryMapTy &DefinedGlobals) {
58204c9a2d6STeresa Johnson   // Parse inline ASM and collect the list of symbols that are not defined in
58304c9a2d6STeresa Johnson   // the current module.
58404c9a2d6STeresa Johnson   StringSet<> AsmUndefinedRefs;
585863cbfbeSPeter Collingbourne   ModuleSymbolTable::CollectAsmSymbols(
586d8204472STeresa Johnson       TheModule,
58704c9a2d6STeresa Johnson       [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
58804c9a2d6STeresa Johnson         if (Flags & object::BasicSymbolRef::SF_Undefined)
58904c9a2d6STeresa Johnson           AsmUndefinedRefs.insert(Name);
59004c9a2d6STeresa Johnson       });
59104c9a2d6STeresa Johnson 
59204c9a2d6STeresa Johnson   // Declare a callback for the internalize pass that will ask for every
59304c9a2d6STeresa Johnson   // candidate GlobalValue if it can be internalized or not.
59404c9a2d6STeresa Johnson   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
59504c9a2d6STeresa Johnson     // Can't be internalized if referenced in inline asm.
59604c9a2d6STeresa Johnson     if (AsmUndefinedRefs.count(GV.getName()))
59704c9a2d6STeresa Johnson       return true;
59804c9a2d6STeresa Johnson 
59904c9a2d6STeresa Johnson     // Lookup the linkage recorded in the summaries during global analysis.
600c3d677f9SPeter Collingbourne     auto GS = DefinedGlobals.find(GV.getGUID());
60104c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end()) {
60204c9a2d6STeresa Johnson       // Must have been promoted (possibly conservatively). Find original
60304c9a2d6STeresa Johnson       // name so that we can access the correct summary and see if it can
60404c9a2d6STeresa Johnson       // be internalized again.
60504c9a2d6STeresa Johnson       // FIXME: Eventually we should control promotion instead of promoting
60604c9a2d6STeresa Johnson       // and internalizing again.
60704c9a2d6STeresa Johnson       StringRef OrigName =
60804c9a2d6STeresa Johnson           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
60904c9a2d6STeresa Johnson       std::string OrigId = GlobalValue::getGlobalIdentifier(
61004c9a2d6STeresa Johnson           OrigName, GlobalValue::InternalLinkage,
61104c9a2d6STeresa Johnson           TheModule.getSourceFileName());
612c3d677f9SPeter Collingbourne       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
6137ab1f692STeresa Johnson       if (GS == DefinedGlobals.end()) {
6147ab1f692STeresa Johnson         // Also check the original non-promoted non-globalized name. In some
6157ab1f692STeresa Johnson         // cases a preempted weak value is linked in as a local copy because
6167ab1f692STeresa Johnson         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
6177ab1f692STeresa Johnson         // In that case, since it was originally not a local value, it was
6187ab1f692STeresa Johnson         // recorded in the index using the original name.
6197ab1f692STeresa Johnson         // FIXME: This may not be needed once PR27866 is fixed.
620c3d677f9SPeter Collingbourne         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
62104c9a2d6STeresa Johnson         assert(GS != DefinedGlobals.end());
6227ab1f692STeresa Johnson       }
623c3d677f9SPeter Collingbourne     }
624c3d677f9SPeter Collingbourne     return !GlobalValue::isLocalLinkage(GS->second->linkage());
62504c9a2d6STeresa Johnson   };
62604c9a2d6STeresa Johnson 
62704c9a2d6STeresa Johnson   // FIXME: See if we can just internalize directly here via linkage changes
62804c9a2d6STeresa Johnson   // based on the index, rather than invoking internalizeModule.
62904c9a2d6STeresa Johnson   llvm::internalizeModule(TheModule, MustPreserveGV);
63004c9a2d6STeresa Johnson }
63104c9a2d6STeresa Johnson 
632c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries
633c8c55170SMehdi Amini // index.
634c8c55170SMehdi Amini //
6357f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions(
63666043797SAdrian Prantl     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
6375411d051SMehdi Amini   DEBUG(dbgs() << "Starting import for Module "
638311fef6eSMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
639c8c55170SMehdi Amini   unsigned ImportedCount = 0;
640c8c55170SMehdi Amini 
6416d8f817fSPeter Collingbourne   IRMover Mover(DestModule);
6427e88d0daSMehdi Amini   // Do the actual import of functions now, one Module at a time
64301e32130SMehdi Amini   std::set<StringRef> ModuleNameOrderedList;
64401e32130SMehdi Amini   for (auto &FunctionsToImportPerModule : ImportList) {
64501e32130SMehdi Amini     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
64601e32130SMehdi Amini   }
64701e32130SMehdi Amini   for (auto &Name : ModuleNameOrderedList) {
6487e88d0daSMehdi Amini     // Get the module for the import
64901e32130SMehdi Amini     const auto &FunctionsToImportPerModule = ImportList.find(Name);
65001e32130SMehdi Amini     assert(FunctionsToImportPerModule != ImportList.end());
651d9445c49SPeter Collingbourne     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
652d9445c49SPeter Collingbourne     if (!SrcModuleOrErr)
653d9445c49SPeter Collingbourne       return SrcModuleOrErr.takeError();
654d9445c49SPeter Collingbourne     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
6557e88d0daSMehdi Amini     assert(&DestModule.getContext() == &SrcModule->getContext() &&
6567e88d0daSMehdi Amini            "Context mismatch");
6577e88d0daSMehdi Amini 
6586cba37ceSTeresa Johnson     // If modules were created with lazy metadata loading, materialize it
6596cba37ceSTeresa Johnson     // now, before linking it (otherwise this will be a noop).
6607f00d0a1SPeter Collingbourne     if (Error Err = SrcModule->materializeMetadata())
6617f00d0a1SPeter Collingbourne       return std::move(Err);
662e5a61917STeresa Johnson 
66301e32130SMehdi Amini     auto &ImportGUIDs = FunctionsToImportPerModule->second;
66401e32130SMehdi Amini     // Find the globals to import
6656d8f817fSPeter Collingbourne     SetVector<GlobalValue *> GlobalsToImport;
6661f685e01SPiotr Padlewski     for (Function &F : *SrcModule) {
6671f685e01SPiotr Padlewski       if (!F.hasName())
6680beb858eSTeresa Johnson         continue;
6691f685e01SPiotr Padlewski       auto GUID = F.getGUID();
6700beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
671aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
6721f685e01SPiotr Padlewski                    << " " << F.getName() << " from "
673aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6740beb858eSTeresa Johnson       if (Import) {
6757f00d0a1SPeter Collingbourne         if (Error Err = F.materialize())
6767f00d0a1SPeter Collingbourne           return std::move(Err);
6773b776128SPiotr Padlewski         if (EnableImportMetadata) {
6786deaa6afSPiotr Padlewski           // Add 'thinlto_src_module' metadata for statistics and debugging.
6793b776128SPiotr Padlewski           F.setMetadata(
6803b776128SPiotr Padlewski               "thinlto_src_module",
6813b776128SPiotr Padlewski               llvm::MDNode::get(
6826deaa6afSPiotr Padlewski                   DestModule.getContext(),
6833b776128SPiotr Padlewski                   {llvm::MDString::get(DestModule.getContext(),
6846deaa6afSPiotr Padlewski                                        SrcModule->getSourceFileName())}));
6853b776128SPiotr Padlewski         }
6861f685e01SPiotr Padlewski         GlobalsToImport.insert(&F);
68701e32130SMehdi Amini       }
68801e32130SMehdi Amini     }
6891f685e01SPiotr Padlewski     for (GlobalVariable &GV : SrcModule->globals()) {
6902d28f7aaSMehdi Amini       if (!GV.hasName())
6912d28f7aaSMehdi Amini         continue;
6922d28f7aaSMehdi Amini       auto GUID = GV.getGUID();
6932d28f7aaSMehdi Amini       auto Import = ImportGUIDs.count(GUID);
694aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
695aeb1e59bSMehdi Amini                    << " " << GV.getName() << " from "
696aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6972d28f7aaSMehdi Amini       if (Import) {
6987f00d0a1SPeter Collingbourne         if (Error Err = GV.materialize())
6997f00d0a1SPeter Collingbourne           return std::move(Err);
7002d28f7aaSMehdi Amini         GlobalsToImport.insert(&GV);
7012d28f7aaSMehdi Amini       }
7022d28f7aaSMehdi Amini     }
7031f685e01SPiotr Padlewski     for (GlobalAlias &GA : SrcModule->aliases()) {
7046d8f817fSPeter Collingbourne       // FIXME: This should eventually be controlled entirely by the summary.
7056d8f817fSPeter Collingbourne       if (FunctionImportGlobalProcessing::doImportAsDefinition(
7066d8f817fSPeter Collingbourne               &GA, &GlobalsToImport)) {
7076d8f817fSPeter Collingbourne         GlobalsToImport.insert(&GA);
7086d8f817fSPeter Collingbourne         continue;
7096d8f817fSPeter Collingbourne       }
7106d8f817fSPeter Collingbourne 
7111f685e01SPiotr Padlewski       if (!GA.hasName())
71201e32130SMehdi Amini         continue;
7131f685e01SPiotr Padlewski       auto GUID = GA.getGUID();
7140beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
715aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
7161f685e01SPiotr Padlewski                    << " " << GA.getName() << " from "
717aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
7180beb858eSTeresa Johnson       if (Import) {
71901e32130SMehdi Amini         // Alias can't point to "available_externally". However when we import
7209aae395fSTeresa Johnson         // linkOnceODR the linkage does not change. So we import the alias
7216968ef77SMehdi Amini         // and aliasee only in this case. This has been handled by
7226968ef77SMehdi Amini         // computeImportForFunction()
7231f685e01SPiotr Padlewski         GlobalObject *GO = GA.getBaseObject();
7246968ef77SMehdi Amini         assert(GO->hasLinkOnceODRLinkage() &&
7256968ef77SMehdi Amini                "Unexpected alias to a non-linkonceODR in import list");
7262d28f7aaSMehdi Amini #ifndef NDEBUG
7272d28f7aaSMehdi Amini         if (!GlobalsToImport.count(GO))
7282d28f7aaSMehdi Amini           DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
7292d28f7aaSMehdi Amini                        << " " << GO->getName() << " from "
7302d28f7aaSMehdi Amini                        << SrcModule->getSourceFileName() << "\n");
7312d28f7aaSMehdi Amini #endif
7327f00d0a1SPeter Collingbourne         if (Error Err = GO->materialize())
7337f00d0a1SPeter Collingbourne           return std::move(Err);
73401e32130SMehdi Amini         GlobalsToImport.insert(GO);
7357f00d0a1SPeter Collingbourne         if (Error Err = GA.materialize())
7367f00d0a1SPeter Collingbourne           return std::move(Err);
7371f685e01SPiotr Padlewski         GlobalsToImport.insert(&GA);
73801e32130SMehdi Amini       }
73901e32130SMehdi Amini     }
74001e32130SMehdi Amini 
74119ef4fadSMehdi Amini     // Upgrade debug info after we're done materializing all the globals and we
74219ef4fadSMehdi Amini     // have loaded all the required metadata!
74319ef4fadSMehdi Amini     UpgradeDebugInfo(*SrcModule);
74419ef4fadSMehdi Amini 
7457e88d0daSMehdi Amini     // Link in the specified functions.
74601e32130SMehdi Amini     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
7478d05185aSMehdi Amini       return true;
7488d05185aSMehdi Amini 
749d29478f7STeresa Johnson     if (PrintImports) {
750d29478f7STeresa Johnson       for (const auto *GV : GlobalsToImport)
751d29478f7STeresa Johnson         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
752d29478f7STeresa Johnson                << " from " << SrcModule->getSourceFileName() << "\n";
753d29478f7STeresa Johnson     }
754d29478f7STeresa Johnson 
7556d8f817fSPeter Collingbourne     if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
7566d8f817fSPeter Collingbourne                    [](GlobalValue &, IRMover::ValueAdder) {},
757e6fd9ff9SPeter Collingbourne                    /*IsPerformingImport=*/true))
7587e88d0daSMehdi Amini       report_fatal_error("Function Import: link error");
7597e88d0daSMehdi Amini 
76001e32130SMehdi Amini     ImportedCount += GlobalsToImport.size();
7616c475a75STeresa Johnson     NumImportedModules++;
7627e88d0daSMehdi Amini   }
763e5a61917STeresa Johnson 
7646c475a75STeresa Johnson   NumImportedFunctions += ImportedCount;
765d29478f7STeresa Johnson 
7667e88d0daSMehdi Amini   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
767c8c55170SMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
768c8c55170SMehdi Amini   return ImportedCount;
76942418abaSMehdi Amini }
77042418abaSMehdi Amini 
77142418abaSMehdi Amini /// Summary file to use for function importing when using -function-import from
77242418abaSMehdi Amini /// the command line.
77342418abaSMehdi Amini static cl::opt<std::string>
77442418abaSMehdi Amini     SummaryFile("summary-file",
77542418abaSMehdi Amini                 cl::desc("The summary file to use for function importing."));
77642418abaSMehdi Amini 
777598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) {
778598bd2a2SPeter Collingbourne   if (SummaryFile.empty())
779598bd2a2SPeter Collingbourne     report_fatal_error("error: -function-import requires -summary-file\n");
7806de481a3SPeter Collingbourne   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
7816de481a3SPeter Collingbourne       getModuleSummaryIndexForFile(SummaryFile);
7826de481a3SPeter Collingbourne   if (!IndexPtrOrErr) {
7836de481a3SPeter Collingbourne     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
7846de481a3SPeter Collingbourne                           "Error loading file '" + SummaryFile + "': ");
78542418abaSMehdi Amini     return false;
78642418abaSMehdi Amini   }
787598bd2a2SPeter Collingbourne   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
78842418abaSMehdi Amini 
789c86af334STeresa Johnson   // First step is collecting the import list.
790c86af334STeresa Johnson   FunctionImporter::ImportMapTy ImportList;
791c86af334STeresa Johnson   ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
792c86af334STeresa Johnson                                     ImportList);
79301e32130SMehdi Amini 
7944fef68cbSTeresa Johnson   // Conservatively mark all internal values as promoted. This interface is
7954fef68cbSTeresa Johnson   // only used when doing importing via the function importing pass. The pass
7964fef68cbSTeresa Johnson   // is only enabled when testing importing via the 'opt' tool, which does
7974fef68cbSTeresa Johnson   // not do the ThinLink that would normally determine what values to promote.
7984fef68cbSTeresa Johnson   for (auto &I : *Index) {
7999667b91bSPeter Collingbourne     for (auto &S : I.second.SummaryList) {
8004fef68cbSTeresa Johnson       if (GlobalValue::isLocalLinkage(S->linkage()))
8014fef68cbSTeresa Johnson         S->setLinkage(GlobalValue::ExternalLinkage);
8024fef68cbSTeresa Johnson     }
8034fef68cbSTeresa Johnson   }
8044fef68cbSTeresa Johnson 
80501e32130SMehdi Amini   // Next we need to promote to global scope and rename any local values that
8061b00f2d9STeresa Johnson   // are potentially exported to other modules.
80701e32130SMehdi Amini   if (renameModuleForThinLTO(M, *Index, nullptr)) {
8081b00f2d9STeresa Johnson     errs() << "Error renaming module\n";
8091b00f2d9STeresa Johnson     return false;
8101b00f2d9STeresa Johnson   }
8111b00f2d9STeresa Johnson 
81242418abaSMehdi Amini   // Perform the import now.
813d16c8065SMehdi Amini   auto ModuleLoader = [&M](StringRef Identifier) {
814d16c8065SMehdi Amini     return loadFile(Identifier, M.getContext());
815d16c8065SMehdi Amini   };
8169d2bfc48SRafael Espindola   FunctionImporter Importer(*Index, ModuleLoader);
81737e24591SPeter Collingbourne   Expected<bool> Result = Importer.importFunctions(M, ImportList);
8187f00d0a1SPeter Collingbourne 
8197f00d0a1SPeter Collingbourne   // FIXME: Probably need to propagate Errors through the pass manager.
8207f00d0a1SPeter Collingbourne   if (!Result) {
8217f00d0a1SPeter Collingbourne     logAllUnhandledErrors(Result.takeError(), errs(),
8227f00d0a1SPeter Collingbourne                           "Error importing module: ");
8237f00d0a1SPeter Collingbourne     return false;
8247f00d0a1SPeter Collingbourne   }
8257f00d0a1SPeter Collingbourne 
8267f00d0a1SPeter Collingbourne   return *Result;
82721241571STeresa Johnson }
82821241571STeresa Johnson 
82921241571STeresa Johnson namespace {
83021241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file.
83121241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass {
83221241571STeresa Johnson public:
83321241571STeresa Johnson   /// Pass identification, replacement for typeid
83421241571STeresa Johnson   static char ID;
83521241571STeresa Johnson 
83621241571STeresa Johnson   /// Specify pass name for debug output
837117296c0SMehdi Amini   StringRef getPassName() const override { return "Function Importing"; }
83821241571STeresa Johnson 
839598bd2a2SPeter Collingbourne   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
84021241571STeresa Johnson 
84121241571STeresa Johnson   bool runOnModule(Module &M) override {
84221241571STeresa Johnson     if (skipModule(M))
84321241571STeresa Johnson       return false;
84421241571STeresa Johnson 
845598bd2a2SPeter Collingbourne     return doImportingForModule(M);
84642418abaSMehdi Amini   }
84742418abaSMehdi Amini };
848fe2b5415SBenjamin Kramer } // anonymous namespace
84942418abaSMehdi Amini 
85021241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M,
851fd03ac6aSSean Silva                                           ModuleAnalysisManager &AM) {
852598bd2a2SPeter Collingbourne   if (!doImportingForModule(M))
85321241571STeresa Johnson     return PreservedAnalyses::all();
85421241571STeresa Johnson 
85521241571STeresa Johnson   return PreservedAnalyses::none();
85621241571STeresa Johnson }
85721241571STeresa Johnson 
85821241571STeresa Johnson char FunctionImportLegacyPass::ID = 0;
85921241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
86042418abaSMehdi Amini                 "Summary Based Function Import", false, false)
86142418abaSMehdi Amini 
86242418abaSMehdi Amini namespace llvm {
863598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() {
864598bd2a2SPeter Collingbourne   return new FunctionImportLegacyPass();
8655fcbdb71STeresa Johnson }
86642418abaSMehdi Amini }
867