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"
2042418abaSMehdi Amini #include "llvm/IR/AutoUpgrade.h"
2142418abaSMehdi Amini #include "llvm/IR/DiagnosticPrinter.h"
2242418abaSMehdi Amini #include "llvm/IR/IntrinsicInst.h"
2342418abaSMehdi Amini #include "llvm/IR/Module.h"
2442418abaSMehdi Amini #include "llvm/IRReader/IRReader.h"
2542418abaSMehdi Amini #include "llvm/Linker/Linker.h"
2604c9a2d6STeresa Johnson #include "llvm/Object/IRObjectFile.h"
2726ab5772STeresa Johnson #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
2842418abaSMehdi Amini #include "llvm/Support/CommandLine.h"
2942418abaSMehdi Amini #include "llvm/Support/Debug.h"
3042418abaSMehdi Amini #include "llvm/Support/SourceMgr.h"
3104c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h"
32488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h"
337e88d0daSMehdi Amini 
3401e32130SMehdi Amini #define DEBUG_TYPE "function-import"
357e88d0daSMehdi Amini 
3642418abaSMehdi Amini using namespace llvm;
3742418abaSMehdi Amini 
38d29478f7STeresa Johnson STATISTIC(NumImported, "Number of functions imported");
39d29478f7STeresa Johnson 
4039303619STeresa Johnson /// Limit on instruction count of imported functions.
4139303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit(
4239303619STeresa Johnson     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
4339303619STeresa Johnson     cl::desc("Only import functions with less than N instructions"));
4439303619STeresa Johnson 
4540641748SMehdi Amini static cl::opt<float>
4640641748SMehdi Amini     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
4740641748SMehdi Amini                       cl::Hidden, cl::value_desc("x"),
4840641748SMehdi Amini                       cl::desc("As we import functions, multiply the "
4940641748SMehdi Amini                                "`import-instr-limit` threshold by this factor "
5040641748SMehdi Amini                                "before processing newly imported functions"));
51ba72b95fSPiotr Padlewski 
52d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor(
53d2869473SPiotr Padlewski     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
54d2869473SPiotr Padlewski     cl::value_desc("x"),
55d2869473SPiotr Padlewski     cl::desc("As we import functions called from hot callsite, multiply the "
56d2869473SPiotr Padlewski              "`import-instr-limit` threshold by this factor "
57d2869473SPiotr Padlewski              "before processing newly imported functions"));
58d2869473SPiotr Padlewski 
59d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier(
60d9830eb7SPiotr Padlewski     "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
61ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
62ba72b95fSPiotr Padlewski 
63ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up.
64ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier(
65ba72b95fSPiotr Padlewski     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
66ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
6740641748SMehdi Amini 
68d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
69d29478f7STeresa Johnson                                   cl::desc("Print imported functions"));
70d29478f7STeresa Johnson 
71bda3c97cSMehdi Amini // Temporary allows the function import pass to disable always linking
72bda3c97cSMehdi Amini // referenced discardable symbols.
73bda3c97cSMehdi Amini static cl::opt<bool>
74bda3c97cSMehdi Amini     DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
75bda3c97cSMehdi Amini                                                 cl::init(false), cl::Hidden);
76bda3c97cSMehdi Amini 
773b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata(
783b776128SPiotr Padlewski     "enable-import-metadata", cl::init(
793b776128SPiotr Padlewski #if !defined(NDEBUG)
803b776128SPiotr Padlewski                                   true /*Enabled with asserts.*/
813b776128SPiotr Padlewski #else
823b776128SPiotr Padlewski                                   false
833b776128SPiotr Padlewski #endif
843b776128SPiotr Padlewski                                   ),
853b776128SPiotr Padlewski     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
863b776128SPiotr Padlewski 
8742418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context.
8842418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName,
8942418abaSMehdi Amini                                         LLVMContext &Context) {
9042418abaSMehdi Amini   SMDiagnostic Err;
9142418abaSMehdi Amini   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
926cba37ceSTeresa Johnson   // Metadata isn't loaded until functions are imported, to minimize
936cba37ceSTeresa Johnson   // the memory overhead.
94a1080ee6STeresa Johnson   std::unique_ptr<Module> Result =
95a1080ee6STeresa Johnson       getLazyIRFileModule(FileName, Err, Context,
96a1080ee6STeresa Johnson                           /* ShouldLazyLoadMetadata = */ true);
9742418abaSMehdi Amini   if (!Result) {
9842418abaSMehdi Amini     Err.print("function-import", errs());
99d7ad221cSMehdi Amini     report_fatal_error("Abort");
10042418abaSMehdi Amini   }
10142418abaSMehdi Amini 
10242418abaSMehdi Amini   return Result;
10342418abaSMehdi Amini }
10442418abaSMehdi Amini 
1057e88d0daSMehdi Amini namespace {
10640641748SMehdi Amini 
107b4e1e829SMehdi Amini // Return true if the Summary describes a GlobalValue that can be externally
108b4e1e829SMehdi Amini // referenced, i.e. it does not need renaming (linkage is not local) or renaming
109b4e1e829SMehdi Amini // is possible (does not have a section for instance).
110b4e1e829SMehdi Amini static bool canBeExternallyReferenced(const GlobalValueSummary &Summary) {
111b4e1e829SMehdi Amini   if (!Summary.needsRenaming())
112b4e1e829SMehdi Amini     return true;
113b4e1e829SMehdi Amini 
11458fbc916STeresa Johnson   if (Summary.noRename())
11558fbc916STeresa Johnson     // Can't externally reference a global that needs renaming if has a section
11658fbc916STeresa Johnson     // or is referenced from inline assembly, for example.
117b4e1e829SMehdi Amini     return false;
118b4e1e829SMehdi Amini 
119b4e1e829SMehdi Amini   return true;
120b4e1e829SMehdi Amini }
121b4e1e829SMehdi Amini 
122b4e1e829SMehdi Amini // Return true if \p GUID describes a GlobalValue that can be externally
123b4e1e829SMehdi Amini // referenced, i.e. it does not need renaming (linkage is not local) or
124b4e1e829SMehdi Amini // renaming is possible (does not have a section for instance).
125b4e1e829SMehdi Amini static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index,
126b4e1e829SMehdi Amini                                       GlobalValue::GUID GUID) {
127b4e1e829SMehdi Amini   auto Summaries = Index.findGlobalValueSummaryList(GUID);
128b4e1e829SMehdi Amini   if (Summaries == Index.end())
129b4e1e829SMehdi Amini     return true;
130b4e1e829SMehdi Amini   if (Summaries->second.size() != 1)
131b4e1e829SMehdi Amini     // If there are multiple globals with this GUID, then we know it is
132b4e1e829SMehdi Amini     // not a local symbol, and it is necessarily externally referenced.
133b4e1e829SMehdi Amini     return true;
134b4e1e829SMehdi Amini 
135b4e1e829SMehdi Amini   // We don't need to check for the module path, because if it can't be
136b4e1e829SMehdi Amini   // externally referenced and we call it, it is necessarilly in the same
137b4e1e829SMehdi Amini   // module
138b4e1e829SMehdi Amini   return canBeExternallyReferenced(**Summaries->second.begin());
139b4e1e829SMehdi Amini }
140b4e1e829SMehdi Amini 
141b4e1e829SMehdi Amini // Return true if the global described by \p Summary can be imported in another
142b4e1e829SMehdi Amini // module.
143b4e1e829SMehdi Amini static bool eligibleForImport(const ModuleSummaryIndex &Index,
144b4e1e829SMehdi Amini                               const GlobalValueSummary &Summary) {
145b4e1e829SMehdi Amini   if (!canBeExternallyReferenced(Summary))
146b4e1e829SMehdi Amini     // Can't import a global that needs renaming if has a section for instance.
147b4e1e829SMehdi Amini     // FIXME: we may be able to import it by copying it without promotion.
148b4e1e829SMehdi Amini     return false;
149b4e1e829SMehdi Amini 
150332b3b22SPiotr Padlewski   // Don't import functions that are not viable to inline.
151332b3b22SPiotr Padlewski   if (Summary.isNotViableToInline())
152332b3b22SPiotr Padlewski     return false;
153332b3b22SPiotr Padlewski 
154b4e1e829SMehdi Amini   // Check references (and potential calls) in the same module. If the current
155b4e1e829SMehdi Amini   // value references a global that can't be externally referenced it is not
156*d5033a45STeresa Johnson   // eligible for import. First check the flag set when we have possible
157*d5033a45STeresa Johnson   // opaque references (e.g. inline asm calls), then check the call and
158*d5033a45STeresa Johnson   // reference sets.
159*d5033a45STeresa Johnson   if (Summary.hasInlineAsmMaybeReferencingInternal())
160*d5033a45STeresa Johnson     return false;
161b4e1e829SMehdi Amini   bool AllRefsCanBeExternallyReferenced =
162b4e1e829SMehdi Amini       llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
163b4e1e829SMehdi Amini         return canBeExternallyReferenced(Index, VI.getGUID());
164b4e1e829SMehdi Amini       });
165b4e1e829SMehdi Amini   if (!AllRefsCanBeExternallyReferenced)
166b4e1e829SMehdi Amini     return false;
167b4e1e829SMehdi Amini 
168b4e1e829SMehdi Amini   if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
169b4e1e829SMehdi Amini     bool AllCallsCanBeExternallyReferenced = llvm::all_of(
170b4e1e829SMehdi Amini         FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
171b4e1e829SMehdi Amini           return canBeExternallyReferenced(Index, Edge.first.getGUID());
172b4e1e829SMehdi Amini         });
173b4e1e829SMehdi Amini     if (!AllCallsCanBeExternallyReferenced)
174b4e1e829SMehdi Amini       return false;
175b4e1e829SMehdi Amini   }
176b4e1e829SMehdi Amini   return true;
177b4e1e829SMehdi Amini }
178b4e1e829SMehdi Amini 
17901e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one
18001e32130SMehdi Amini /// that fits the \p Threshold.
18101e32130SMehdi Amini ///
18201e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"?
18301e32130SMehdi Amini /// - The smallest: more likely to be inlined.
18401e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized).
18501e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the
18601e32130SMehdi Amini ///   number of source modules parsed/linked.
18701e32130SMehdi Amini /// - One that has PGO data attached.
18801e32130SMehdi Amini /// - [insert you fancy metric here]
1892d28f7aaSMehdi Amini static const GlobalValueSummary *
190b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index,
191b4e1e829SMehdi Amini              const GlobalValueSummaryList &CalleeSummaryList,
19228e457bcSTeresa Johnson              unsigned Threshold) {
19301e32130SMehdi Amini   auto It = llvm::find_if(
19428e457bcSTeresa Johnson       CalleeSummaryList,
19528e457bcSTeresa Johnson       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
19628e457bcSTeresa Johnson         auto *GVSummary = SummaryPtr.get();
197f329be83SRafael Espindola         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
1985b85d8d6SMehdi Amini           // There is no point in importing these, we can't inline them
19901e32130SMehdi Amini           return false;
2002c719cc1SMehdi Amini         if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
2012c719cc1SMehdi Amini           GVSummary = &AS->getAliasee();
2022c719cc1SMehdi Amini           // Alias can't point to "available_externally". However when we import
2032c719cc1SMehdi Amini           // linkOnceODR the linkage does not change. So we import the alias
2042c719cc1SMehdi Amini           // and aliasee only in this case.
2052c719cc1SMehdi Amini           // FIXME: we should import alias as available_externally *function*,
2062c719cc1SMehdi Amini           // the destination module does need to know it is an alias.
2072c719cc1SMehdi Amini           if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
2082c719cc1SMehdi Amini             return false;
2092c719cc1SMehdi Amini         }
2102c719cc1SMehdi Amini 
2112c719cc1SMehdi Amini         auto *Summary = cast<FunctionSummary>(GVSummary);
2127e88d0daSMehdi Amini 
21301e32130SMehdi Amini         if (Summary->instCount() > Threshold)
21401e32130SMehdi Amini           return false;
2157e88d0daSMehdi Amini 
216b4e1e829SMehdi Amini         if (!eligibleForImport(Index, *Summary))
217b4e1e829SMehdi Amini           return false;
218b4e1e829SMehdi Amini 
21901e32130SMehdi Amini         return true;
22001e32130SMehdi Amini       });
22128e457bcSTeresa Johnson   if (It == CalleeSummaryList.end())
22201e32130SMehdi Amini     return nullptr;
2237e88d0daSMehdi Amini 
22428e457bcSTeresa Johnson   return cast<GlobalValueSummary>(It->get());
225434e9561SRafael Espindola }
2267e88d0daSMehdi Amini 
22701e32130SMehdi Amini /// Return the summary for the function \p GUID that fits the \p Threshold, or
22801e32130SMehdi Amini /// null if there's no match.
2292d28f7aaSMehdi Amini static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
230ad5741b0SMehdi Amini                                               unsigned Threshold,
23101e32130SMehdi Amini                                               const ModuleSummaryIndex &Index) {
23228e457bcSTeresa Johnson   auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
233b4e1e829SMehdi Amini   if (CalleeSummaryList == Index.end())
23401e32130SMehdi Amini     return nullptr; // This function does not have a summary
235b4e1e829SMehdi Amini   return selectCallee(Index, CalleeSummaryList->second, Threshold);
23601e32130SMehdi Amini }
2377e88d0daSMehdi Amini 
238cb87494fSMehdi Amini /// Mark the global \p GUID as export by module \p ExportModulePath if found in
239cb87494fSMehdi Amini /// this module. If it is a GlobalVariable, we also mark any referenced global
240cb87494fSMehdi Amini /// in the current module as exported.
241cb87494fSMehdi Amini static void exportGlobalInModule(const ModuleSummaryIndex &Index,
242ad5741b0SMehdi Amini                                  StringRef ExportModulePath,
243cb87494fSMehdi Amini                                  GlobalValue::GUID GUID,
244cb87494fSMehdi Amini                                  FunctionImporter::ExportSetTy &ExportList) {
24528e457bcSTeresa Johnson   auto FindGlobalSummaryInModule =
24628e457bcSTeresa Johnson       [&](GlobalValue::GUID GUID) -> GlobalValueSummary *{
24728e457bcSTeresa Johnson         auto SummaryList = Index.findGlobalValueSummaryList(GUID);
24828e457bcSTeresa Johnson         if (SummaryList == Index.end())
24901e32130SMehdi Amini           // This global does not have a summary, it is not part of the ThinLTO
25001e32130SMehdi Amini           // process
251cb87494fSMehdi Amini           return nullptr;
25228e457bcSTeresa Johnson         auto SummaryIter = llvm::find_if(
25328e457bcSTeresa Johnson             SummaryList->second,
25428e457bcSTeresa Johnson             [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
25501e32130SMehdi Amini               return Summary->modulePath() == ExportModulePath;
25601e32130SMehdi Amini             });
25728e457bcSTeresa Johnson         if (SummaryIter == SummaryList->second.end())
258cb87494fSMehdi Amini           return nullptr;
25928e457bcSTeresa Johnson         return SummaryIter->get();
260cb87494fSMehdi Amini       };
261cb87494fSMehdi Amini 
26228e457bcSTeresa Johnson   auto *Summary = FindGlobalSummaryInModule(GUID);
26328e457bcSTeresa Johnson   if (!Summary)
264cb87494fSMehdi Amini     return;
265cb87494fSMehdi Amini   // We found it in the current module, mark as exported
266cb87494fSMehdi Amini   ExportList.insert(GUID);
267cb87494fSMehdi Amini 
268cb87494fSMehdi Amini   auto GVS = dyn_cast<GlobalVarSummary>(Summary);
269cb87494fSMehdi Amini   if (!GVS)
270cb87494fSMehdi Amini     return;
271cb87494fSMehdi Amini   // FunctionImportGlobalProcessing::doPromoteLocalToGlobal() will always
272cb87494fSMehdi Amini   // trigger importing  the initializer for `constant unnamed addr` globals that
273cb87494fSMehdi Amini   // are referenced. We conservatively export all the referenced symbols for
274cb87494fSMehdi Amini   // every global to workaround this, so that the ExportList is accurate.
275cb87494fSMehdi Amini   // FIXME: with a "isConstant" flag in the summary we could be more targetted.
276cb87494fSMehdi Amini   for (auto &Ref : GVS->refs()) {
277cb87494fSMehdi Amini     auto GUID = Ref.getGUID();
27828e457bcSTeresa Johnson     auto *RefSummary = FindGlobalSummaryInModule(GUID);
27928e457bcSTeresa Johnson     if (RefSummary)
280cb87494fSMehdi Amini       // Found a ref in the current module, mark it as exported
281cb87494fSMehdi Amini       ExportList.insert(GUID);
282cb87494fSMehdi Amini   }
28301e32130SMehdi Amini }
2847e88d0daSMehdi Amini 
28501e32130SMehdi Amini using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
28601e32130SMehdi Amini 
28701e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these
28801e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as
28901e32130SMehdi Amini /// exported from their source module.
29001e32130SMehdi Amini static void computeImportForFunction(
2913255eec1STeresa Johnson     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
292d9830eb7SPiotr Padlewski     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
29301e32130SMehdi Amini     SmallVectorImpl<EdgeInfo> &Worklist,
2949b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
295c86af334STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
29601e32130SMehdi Amini   for (auto &Edge : Summary.calls()) {
2972d5487cfSTeresa Johnson     auto GUID = Edge.first.getGUID();
29801e32130SMehdi Amini     DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
29901e32130SMehdi Amini 
3001aafabf7SMehdi Amini     if (DefinedGVSummaries.count(GUID)) {
30101e32130SMehdi Amini       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
3027e88d0daSMehdi Amini       continue;
303d450da32STeresa Johnson     }
30440641748SMehdi Amini 
305ba72b95fSPiotr Padlewski     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
306ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Hot)
307ba72b95fSPiotr Padlewski         return ImportHotMultiplier;
308ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Cold)
309ba72b95fSPiotr Padlewski         return ImportColdMultiplier;
310ba72b95fSPiotr Padlewski       return 1.0;
311ba72b95fSPiotr Padlewski     };
312ba72b95fSPiotr Padlewski 
313d9830eb7SPiotr Padlewski     const auto NewThreshold =
314ba72b95fSPiotr Padlewski         Threshold * GetBonusMultiplier(Edge.second.Hotness);
315d2869473SPiotr Padlewski 
316d9830eb7SPiotr Padlewski     auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
31701e32130SMehdi Amini     if (!CalleeSummary) {
31801e32130SMehdi Amini       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
3197e88d0daSMehdi Amini       continue;
3207e88d0daSMehdi Amini     }
3212d28f7aaSMehdi Amini     // "Resolve" the summary, traversing alias,
3222d28f7aaSMehdi Amini     const FunctionSummary *ResolvedCalleeSummary;
3236968ef77SMehdi Amini     if (isa<AliasSummary>(CalleeSummary)) {
3242d28f7aaSMehdi Amini       ResolvedCalleeSummary = cast<FunctionSummary>(
3252d28f7aaSMehdi Amini           &cast<AliasSummary>(CalleeSummary)->getAliasee());
3262c719cc1SMehdi Amini       assert(
3272c719cc1SMehdi Amini           GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
3282c719cc1SMehdi Amini           "Unexpected alias to a non-linkonceODR in import list");
3296968ef77SMehdi Amini     } else
3302d28f7aaSMehdi Amini       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
3312d28f7aaSMehdi Amini 
332d9830eb7SPiotr Padlewski     assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
33301e32130SMehdi Amini            "selectCallee() didn't honor the threshold");
33401e32130SMehdi Amini 
3352d28f7aaSMehdi Amini     auto ExportModulePath = ResolvedCalleeSummary->modulePath();
3369b490f10SMehdi Amini     auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
33701e32130SMehdi Amini     /// Since the traversal of the call graph is DFS, we can revisit a function
33801e32130SMehdi Amini     /// a second time with a higher threshold. In this case, it is added back to
33901e32130SMehdi Amini     /// the worklist with the new threshold.
3402e03094dSTeresa Johnson     if (ProcessedThreshold && ProcessedThreshold >= Threshold) {
34101e32130SMehdi Amini       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
34201e32130SMehdi Amini                    << ProcessedThreshold << "\n");
34301e32130SMehdi Amini       continue;
34401e32130SMehdi Amini     }
34501e32130SMehdi Amini     // Mark this function as imported in this module, with the current Threshold
34601e32130SMehdi Amini     ProcessedThreshold = Threshold;
34701e32130SMehdi Amini 
34801e32130SMehdi Amini     // Make exports in the source module.
349c86af334STeresa Johnson     if (ExportLists) {
350ef7555fbSMehdi Amini       auto &ExportList = (*ExportLists)[ExportModulePath];
35101e32130SMehdi Amini       ExportList.insert(GUID);
352c86af334STeresa Johnson       // Mark all functions and globals referenced by this function as exported
353c86af334STeresa Johnson       // to the outside if they are defined in the same source module.
3542d28f7aaSMehdi Amini       for (auto &Edge : ResolvedCalleeSummary->calls()) {
3552d5487cfSTeresa Johnson         auto CalleeGUID = Edge.first.getGUID();
356cb87494fSMehdi Amini         exportGlobalInModule(Index, ExportModulePath, CalleeGUID, ExportList);
35701e32130SMehdi Amini       }
3582d28f7aaSMehdi Amini       for (auto &Ref : ResolvedCalleeSummary->refs()) {
3592d5487cfSTeresa Johnson         auto GUID = Ref.getGUID();
360cb87494fSMehdi Amini         exportGlobalInModule(Index, ExportModulePath, GUID, ExportList);
3617e88d0daSMehdi Amini       }
362c86af334STeresa Johnson     }
3637e88d0daSMehdi Amini 
364d2869473SPiotr Padlewski     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
365d2869473SPiotr Padlewski       // Adjust the threshold for next level of imported functions.
366d2869473SPiotr Padlewski       // The threshold is different for hot callsites because we can then
367d2869473SPiotr Padlewski       // inline chains of hot calls.
368d2869473SPiotr Padlewski       if (IsHotCallsite)
369d2869473SPiotr Padlewski         return Threshold * ImportHotInstrFactor;
370d2869473SPiotr Padlewski       return Threshold * ImportInstrFactor;
371d2869473SPiotr Padlewski     };
372d2869473SPiotr Padlewski 
373d2869473SPiotr Padlewski     bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
374d2869473SPiotr Padlewski 
37501e32130SMehdi Amini     // Insert the newly imported function to the worklist.
376d2869473SPiotr Padlewski     Worklist.emplace_back(ResolvedCalleeSummary,
377d2869473SPiotr Padlewski                           GetAdjustedThreshold(Threshold, IsHotCallsite));
378d450da32STeresa Johnson   }
379d450da32STeresa Johnson }
380d450da32STeresa Johnson 
38101e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports
38201e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from
38301e32130SMehdi Amini /// another module (that may require promotion).
38401e32130SMehdi Amini static void ComputeImportForModule(
385c851d216STeresa Johnson     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
3869b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
387c86af334STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
38801e32130SMehdi Amini   // Worklist contains the list of function imported in this module, for which
38901e32130SMehdi Amini   // we will analyse the callees and may import further down the callgraph.
39001e32130SMehdi Amini   SmallVector<EdgeInfo, 128> Worklist;
39101e32130SMehdi Amini 
39201e32130SMehdi Amini   // Populate the worklist with the import for the functions in the current
39301e32130SMehdi Amini   // module
39428e457bcSTeresa Johnson   for (auto &GVSummary : DefinedGVSummaries) {
39528e457bcSTeresa Johnson     auto *Summary = GVSummary.second;
3962d28f7aaSMehdi Amini     if (auto *AS = dyn_cast<AliasSummary>(Summary))
3972d28f7aaSMehdi Amini       Summary = &AS->getAliasee();
3981aafabf7SMehdi Amini     auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
3991aafabf7SMehdi Amini     if (!FuncSummary)
4001aafabf7SMehdi Amini       // Skip import for global variables
4011aafabf7SMehdi Amini       continue;
40228e457bcSTeresa Johnson     DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
4032d28f7aaSMehdi Amini     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
4049b490f10SMehdi Amini                              DefinedGVSummaries, Worklist, ImportList,
40501e32130SMehdi Amini                              ExportLists);
40601e32130SMehdi Amini   }
40701e32130SMehdi Amini 
408d2869473SPiotr Padlewski   // Process the newly imported functions and add callees to the worklist.
40942418abaSMehdi Amini   while (!Worklist.empty()) {
41001e32130SMehdi Amini     auto FuncInfo = Worklist.pop_back_val();
41101e32130SMehdi Amini     auto *Summary = FuncInfo.first;
41201e32130SMehdi Amini     auto Threshold = FuncInfo.second;
41342418abaSMehdi Amini 
4141aafabf7SMehdi Amini     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
4159b490f10SMehdi Amini                              Worklist, ImportList, ExportLists);
416c8c55170SMehdi Amini   }
41742418abaSMehdi Amini }
418ffe2e4aaSMehdi Amini 
41901e32130SMehdi Amini } // anonymous namespace
42001e32130SMehdi Amini 
421c86af334STeresa Johnson /// Compute all the import and export for every module using the Index.
42201e32130SMehdi Amini void llvm::ComputeCrossModuleImport(
42301e32130SMehdi Amini     const ModuleSummaryIndex &Index,
424c851d216STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
42501e32130SMehdi Amini     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
42601e32130SMehdi Amini     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
42701e32130SMehdi Amini   // For each module that has function defined, compute the import/export lists.
4281aafabf7SMehdi Amini   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
4299b490f10SMehdi Amini     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
4301aafabf7SMehdi Amini     DEBUG(dbgs() << "Computing import for Module '"
4311aafabf7SMehdi Amini                  << DefinedGVSummaries.first() << "'\n");
4329b490f10SMehdi Amini     ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
433c86af334STeresa Johnson                            &ExportLists);
43401e32130SMehdi Amini   }
43501e32130SMehdi Amini 
43601e32130SMehdi Amini #ifndef NDEBUG
43701e32130SMehdi Amini   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
43801e32130SMehdi Amini                << " modules:\n");
43901e32130SMehdi Amini   for (auto &ModuleImports : ImportLists) {
44001e32130SMehdi Amini     auto ModName = ModuleImports.first();
44101e32130SMehdi Amini     auto &Exports = ExportLists[ModName];
44201e32130SMehdi Amini     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
44301e32130SMehdi Amini                  << " functions. Imports from " << ModuleImports.second.size()
44401e32130SMehdi Amini                  << " modules.\n");
44501e32130SMehdi Amini     for (auto &Src : ModuleImports.second) {
44601e32130SMehdi Amini       auto SrcModName = Src.first();
44701e32130SMehdi Amini       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
44801e32130SMehdi Amini                    << SrcModName << "\n");
44901e32130SMehdi Amini     }
45001e32130SMehdi Amini   }
45101e32130SMehdi Amini #endif
45201e32130SMehdi Amini }
45301e32130SMehdi Amini 
454c86af334STeresa Johnson /// Compute all the imports for the given module in the Index.
455c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule(
456c86af334STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
457c86af334STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
458c86af334STeresa Johnson 
459c86af334STeresa Johnson   // Collect the list of functions this module defines.
460c86af334STeresa Johnson   // GUID -> Summary
461c851d216STeresa Johnson   GVSummaryMapTy FunctionSummaryMap;
46228e457bcSTeresa Johnson   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
463c86af334STeresa Johnson 
464c86af334STeresa Johnson   // Compute the import list for this module.
465c86af334STeresa Johnson   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
46628e457bcSTeresa Johnson   ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
467c86af334STeresa Johnson 
468c86af334STeresa Johnson #ifndef NDEBUG
469c86af334STeresa Johnson   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
470c86af334STeresa Johnson                << ImportList.size() << " modules.\n");
471c86af334STeresa Johnson   for (auto &Src : ImportList) {
472c86af334STeresa Johnson     auto SrcModName = Src.first();
473c86af334STeresa Johnson     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
474c86af334STeresa Johnson                  << SrcModName << "\n");
475c86af334STeresa Johnson   }
476c86af334STeresa Johnson #endif
477c86af334STeresa Johnson }
478c86af334STeresa Johnson 
47984174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of
48084174c37STeresa Johnson /// \p ModulePath.
48184174c37STeresa Johnson void llvm::gatherImportedSummariesForModule(
48284174c37STeresa Johnson     StringRef ModulePath,
48384174c37STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
484cdbcbf74SMehdi Amini     const FunctionImporter::ImportMapTy &ImportList,
48584174c37STeresa Johnson     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
48684174c37STeresa Johnson   // Include all summaries from the importing module.
48784174c37STeresa Johnson   ModuleToSummariesForIndex[ModulePath] =
48884174c37STeresa Johnson       ModuleToDefinedGVSummaries.lookup(ModulePath);
48984174c37STeresa Johnson   // Include summaries for imports.
49088c491ddSMehdi Amini   for (auto &ILI : ImportList) {
49184174c37STeresa Johnson     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
49284174c37STeresa Johnson     const auto &DefinedGVSummaries =
49384174c37STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ILI.first());
49484174c37STeresa Johnson     for (auto &GI : ILI.second) {
49584174c37STeresa Johnson       const auto &DS = DefinedGVSummaries.find(GI.first);
49684174c37STeresa Johnson       assert(DS != DefinedGVSummaries.end() &&
49784174c37STeresa Johnson              "Expected a defined summary for imported global value");
49884174c37STeresa Johnson       SummariesForIndex[GI.first] = DS->second;
49984174c37STeresa Johnson     }
50084174c37STeresa Johnson   }
50184174c37STeresa Johnson }
50284174c37STeresa Johnson 
5038570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename.
504cdbcbf74SMehdi Amini std::error_code
505cdbcbf74SMehdi Amini llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
506cdbcbf74SMehdi Amini                        const FunctionImporter::ImportMapTy &ModuleImports) {
5078570fe47STeresa Johnson   std::error_code EC;
5088570fe47STeresa Johnson   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
5098570fe47STeresa Johnson   if (EC)
5108570fe47STeresa Johnson     return EC;
511cdbcbf74SMehdi Amini   for (auto &ILI : ModuleImports)
5128570fe47STeresa Johnson     ImportsOS << ILI.first() << "\n";
5138570fe47STeresa Johnson   return std::error_code();
5148570fe47STeresa Johnson }
5158570fe47STeresa Johnson 
51604c9a2d6STeresa Johnson /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
51704c9a2d6STeresa Johnson void llvm::thinLTOResolveWeakForLinkerModule(
51804c9a2d6STeresa Johnson     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
51904c9a2d6STeresa Johnson   auto updateLinkage = [&](GlobalValue &GV) {
52004c9a2d6STeresa Johnson     if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
52104c9a2d6STeresa Johnson       return;
52204c9a2d6STeresa Johnson     // See if the global summary analysis computed a new resolved linkage.
52304c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
52404c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end())
52504c9a2d6STeresa Johnson       return;
52604c9a2d6STeresa Johnson     auto NewLinkage = GS->second->linkage();
52704c9a2d6STeresa Johnson     if (NewLinkage == GV.getLinkage())
52804c9a2d6STeresa Johnson       return;
52904c9a2d6STeresa Johnson     DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
53004c9a2d6STeresa Johnson                  << GV.getLinkage() << " to " << NewLinkage << "\n");
53104c9a2d6STeresa Johnson     GV.setLinkage(NewLinkage);
5326107a419STeresa Johnson     // Remove functions converted to available_externally from comdats,
5336107a419STeresa Johnson     // as this is a declaration for the linker, and will be dropped eventually.
5346107a419STeresa Johnson     // It is illegal for comdats to contain declarations.
5356107a419STeresa Johnson     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
5366107a419STeresa Johnson     if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
5376107a419STeresa Johnson       assert(GO->hasAvailableExternallyLinkage() &&
5386107a419STeresa Johnson              "Expected comdat on definition (possibly available external)");
5396107a419STeresa Johnson       GO->setComdat(nullptr);
5406107a419STeresa Johnson     }
54104c9a2d6STeresa Johnson   };
54204c9a2d6STeresa Johnson 
54304c9a2d6STeresa Johnson   // Process functions and global now
54404c9a2d6STeresa Johnson   for (auto &GV : TheModule)
54504c9a2d6STeresa Johnson     updateLinkage(GV);
54604c9a2d6STeresa Johnson   for (auto &GV : TheModule.globals())
54704c9a2d6STeresa Johnson     updateLinkage(GV);
54804c9a2d6STeresa Johnson   for (auto &GV : TheModule.aliases())
54904c9a2d6STeresa Johnson     updateLinkage(GV);
55004c9a2d6STeresa Johnson }
55104c9a2d6STeresa Johnson 
55204c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis.
55304c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule,
55404c9a2d6STeresa Johnson                                     const GVSummaryMapTy &DefinedGlobals) {
55504c9a2d6STeresa Johnson   // Parse inline ASM and collect the list of symbols that are not defined in
55604c9a2d6STeresa Johnson   // the current module.
55704c9a2d6STeresa Johnson   StringSet<> AsmUndefinedRefs;
55804c9a2d6STeresa Johnson   object::IRObjectFile::CollectAsmUndefinedRefs(
55904c9a2d6STeresa Johnson       Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
56004c9a2d6STeresa Johnson       [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
56104c9a2d6STeresa Johnson         if (Flags & object::BasicSymbolRef::SF_Undefined)
56204c9a2d6STeresa Johnson           AsmUndefinedRefs.insert(Name);
56304c9a2d6STeresa Johnson       });
56404c9a2d6STeresa Johnson 
56504c9a2d6STeresa Johnson   // Declare a callback for the internalize pass that will ask for every
56604c9a2d6STeresa Johnson   // candidate GlobalValue if it can be internalized or not.
56704c9a2d6STeresa Johnson   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
56804c9a2d6STeresa Johnson     // Can't be internalized if referenced in inline asm.
56904c9a2d6STeresa Johnson     if (AsmUndefinedRefs.count(GV.getName()))
57004c9a2d6STeresa Johnson       return true;
57104c9a2d6STeresa Johnson 
57204c9a2d6STeresa Johnson     // Lookup the linkage recorded in the summaries during global analysis.
57304c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
57404c9a2d6STeresa Johnson     GlobalValue::LinkageTypes Linkage;
57504c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end()) {
57604c9a2d6STeresa Johnson       // Must have been promoted (possibly conservatively). Find original
57704c9a2d6STeresa Johnson       // name so that we can access the correct summary and see if it can
57804c9a2d6STeresa Johnson       // be internalized again.
57904c9a2d6STeresa Johnson       // FIXME: Eventually we should control promotion instead of promoting
58004c9a2d6STeresa Johnson       // and internalizing again.
58104c9a2d6STeresa Johnson       StringRef OrigName =
58204c9a2d6STeresa Johnson           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
58304c9a2d6STeresa Johnson       std::string OrigId = GlobalValue::getGlobalIdentifier(
58404c9a2d6STeresa Johnson           OrigName, GlobalValue::InternalLinkage,
58504c9a2d6STeresa Johnson           TheModule.getSourceFileName());
58604c9a2d6STeresa Johnson       const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
5877ab1f692STeresa Johnson       if (GS == DefinedGlobals.end()) {
5887ab1f692STeresa Johnson         // Also check the original non-promoted non-globalized name. In some
5897ab1f692STeresa Johnson         // cases a preempted weak value is linked in as a local copy because
5907ab1f692STeresa Johnson         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
5917ab1f692STeresa Johnson         // In that case, since it was originally not a local value, it was
5927ab1f692STeresa Johnson         // recorded in the index using the original name.
5937ab1f692STeresa Johnson         // FIXME: This may not be needed once PR27866 is fixed.
5947ab1f692STeresa Johnson         const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
59504c9a2d6STeresa Johnson         assert(GS != DefinedGlobals.end());
59604c9a2d6STeresa Johnson         Linkage = GS->second->linkage();
5977ab1f692STeresa Johnson       } else {
5987ab1f692STeresa Johnson         Linkage = GS->second->linkage();
5997ab1f692STeresa Johnson       }
60004c9a2d6STeresa Johnson     } else
60104c9a2d6STeresa Johnson       Linkage = GS->second->linkage();
60204c9a2d6STeresa Johnson     return !GlobalValue::isLocalLinkage(Linkage);
60304c9a2d6STeresa Johnson   };
60404c9a2d6STeresa Johnson 
60504c9a2d6STeresa Johnson   // FIXME: See if we can just internalize directly here via linkage changes
60604c9a2d6STeresa Johnson   // based on the index, rather than invoking internalizeModule.
60704c9a2d6STeresa Johnson   llvm::internalizeModule(TheModule, MustPreserveGV);
60804c9a2d6STeresa Johnson }
60904c9a2d6STeresa Johnson 
610c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries
611c8c55170SMehdi Amini // index.
612c8c55170SMehdi Amini //
6137f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions(
614bda3c97cSMehdi Amini     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
615bda3c97cSMehdi Amini     bool ForceImportReferencedDiscardableSymbols) {
6165411d051SMehdi Amini   DEBUG(dbgs() << "Starting import for Module "
617311fef6eSMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
618c8c55170SMehdi Amini   unsigned ImportedCount = 0;
619c8c55170SMehdi Amini 
620c8c55170SMehdi Amini   // Linker that will be used for importing function
6219d2bfc48SRafael Espindola   Linker TheLinker(DestModule);
6227e88d0daSMehdi Amini   // Do the actual import of functions now, one Module at a time
62301e32130SMehdi Amini   std::set<StringRef> ModuleNameOrderedList;
62401e32130SMehdi Amini   for (auto &FunctionsToImportPerModule : ImportList) {
62501e32130SMehdi Amini     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
62601e32130SMehdi Amini   }
62701e32130SMehdi Amini   for (auto &Name : ModuleNameOrderedList) {
6287e88d0daSMehdi Amini     // Get the module for the import
62901e32130SMehdi Amini     const auto &FunctionsToImportPerModule = ImportList.find(Name);
63001e32130SMehdi Amini     assert(FunctionsToImportPerModule != ImportList.end());
631d9445c49SPeter Collingbourne     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
632d9445c49SPeter Collingbourne     if (!SrcModuleOrErr)
633d9445c49SPeter Collingbourne       return SrcModuleOrErr.takeError();
634d9445c49SPeter Collingbourne     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
6357e88d0daSMehdi Amini     assert(&DestModule.getContext() == &SrcModule->getContext() &&
6367e88d0daSMehdi Amini            "Context mismatch");
6377e88d0daSMehdi Amini 
6386cba37ceSTeresa Johnson     // If modules were created with lazy metadata loading, materialize it
6396cba37ceSTeresa Johnson     // now, before linking it (otherwise this will be a noop).
6407f00d0a1SPeter Collingbourne     if (Error Err = SrcModule->materializeMetadata())
6417f00d0a1SPeter Collingbourne       return std::move(Err);
6426cba37ceSTeresa Johnson     UpgradeDebugInfo(*SrcModule);
643e5a61917STeresa Johnson 
64401e32130SMehdi Amini     auto &ImportGUIDs = FunctionsToImportPerModule->second;
64501e32130SMehdi Amini     // Find the globals to import
64601e32130SMehdi Amini     DenseSet<const GlobalValue *> GlobalsToImport;
6471f685e01SPiotr Padlewski     for (Function &F : *SrcModule) {
6481f685e01SPiotr Padlewski       if (!F.hasName())
6490beb858eSTeresa Johnson         continue;
6501f685e01SPiotr Padlewski       auto GUID = F.getGUID();
6510beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
652aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
6531f685e01SPiotr Padlewski                    << " " << F.getName() << " from "
654aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6550beb858eSTeresa Johnson       if (Import) {
6567f00d0a1SPeter Collingbourne         if (Error Err = F.materialize())
6577f00d0a1SPeter Collingbourne           return std::move(Err);
6583b776128SPiotr Padlewski         if (EnableImportMetadata) {
6596deaa6afSPiotr Padlewski           // Add 'thinlto_src_module' metadata for statistics and debugging.
6603b776128SPiotr Padlewski           F.setMetadata(
6613b776128SPiotr Padlewski               "thinlto_src_module",
6623b776128SPiotr Padlewski               llvm::MDNode::get(
6636deaa6afSPiotr Padlewski                   DestModule.getContext(),
6643b776128SPiotr Padlewski                   {llvm::MDString::get(DestModule.getContext(),
6656deaa6afSPiotr Padlewski                                        SrcModule->getSourceFileName())}));
6663b776128SPiotr Padlewski         }
6671f685e01SPiotr Padlewski         GlobalsToImport.insert(&F);
66801e32130SMehdi Amini       }
66901e32130SMehdi Amini     }
6701f685e01SPiotr Padlewski     for (GlobalVariable &GV : SrcModule->globals()) {
6712d28f7aaSMehdi Amini       if (!GV.hasName())
6722d28f7aaSMehdi Amini         continue;
6732d28f7aaSMehdi Amini       auto GUID = GV.getGUID();
6742d28f7aaSMehdi Amini       auto Import = ImportGUIDs.count(GUID);
675aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
676aeb1e59bSMehdi Amini                    << " " << GV.getName() << " from "
677aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6782d28f7aaSMehdi Amini       if (Import) {
6797f00d0a1SPeter Collingbourne         if (Error Err = GV.materialize())
6807f00d0a1SPeter Collingbourne           return std::move(Err);
6812d28f7aaSMehdi Amini         GlobalsToImport.insert(&GV);
6822d28f7aaSMehdi Amini       }
6832d28f7aaSMehdi Amini     }
6841f685e01SPiotr Padlewski     for (GlobalAlias &GA : SrcModule->aliases()) {
6851f685e01SPiotr Padlewski       if (!GA.hasName())
68601e32130SMehdi Amini         continue;
6871f685e01SPiotr Padlewski       auto GUID = GA.getGUID();
6880beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
689aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
6901f685e01SPiotr Padlewski                    << " " << GA.getName() << " from "
691aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6920beb858eSTeresa Johnson       if (Import) {
69301e32130SMehdi Amini         // Alias can't point to "available_externally". However when we import
6949aae395fSTeresa Johnson         // linkOnceODR the linkage does not change. So we import the alias
6956968ef77SMehdi Amini         // and aliasee only in this case. This has been handled by
6966968ef77SMehdi Amini         // computeImportForFunction()
6971f685e01SPiotr Padlewski         GlobalObject *GO = GA.getBaseObject();
6986968ef77SMehdi Amini         assert(GO->hasLinkOnceODRLinkage() &&
6996968ef77SMehdi Amini                "Unexpected alias to a non-linkonceODR in import list");
7002d28f7aaSMehdi Amini #ifndef NDEBUG
7012d28f7aaSMehdi Amini         if (!GlobalsToImport.count(GO))
7022d28f7aaSMehdi Amini           DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
7032d28f7aaSMehdi Amini                        << " " << GO->getName() << " from "
7042d28f7aaSMehdi Amini                        << SrcModule->getSourceFileName() << "\n");
7052d28f7aaSMehdi Amini #endif
7067f00d0a1SPeter Collingbourne         if (Error Err = GO->materialize())
7077f00d0a1SPeter Collingbourne           return std::move(Err);
70801e32130SMehdi Amini         GlobalsToImport.insert(GO);
7097f00d0a1SPeter Collingbourne         if (Error Err = GA.materialize())
7107f00d0a1SPeter Collingbourne           return std::move(Err);
7111f685e01SPiotr Padlewski         GlobalsToImport.insert(&GA);
71201e32130SMehdi Amini       }
71301e32130SMehdi Amini     }
71401e32130SMehdi Amini 
7157e88d0daSMehdi Amini     // Link in the specified functions.
71601e32130SMehdi Amini     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
7178d05185aSMehdi Amini       return true;
7188d05185aSMehdi Amini 
719d29478f7STeresa Johnson     if (PrintImports) {
720d29478f7STeresa Johnson       for (const auto *GV : GlobalsToImport)
721d29478f7STeresa Johnson         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
722d29478f7STeresa Johnson                << " from " << SrcModule->getSourceFileName() << "\n";
723d29478f7STeresa Johnson     }
724d29478f7STeresa Johnson 
725bda3c97cSMehdi Amini     // Instruct the linker that the client will take care of linkonce resolution
726bda3c97cSMehdi Amini     unsigned Flags = Linker::Flags::None;
727bda3c97cSMehdi Amini     if (!ForceImportReferencedDiscardableSymbols)
728bda3c97cSMehdi Amini       Flags |= Linker::Flags::DontForceLinkLinkonceODR;
729bda3c97cSMehdi Amini 
730bda3c97cSMehdi Amini     if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
7317e88d0daSMehdi Amini       report_fatal_error("Function Import: link error");
7327e88d0daSMehdi Amini 
73301e32130SMehdi Amini     ImportedCount += GlobalsToImport.size();
7347e88d0daSMehdi Amini   }
735e5a61917STeresa Johnson 
736d29478f7STeresa Johnson   NumImported += ImportedCount;
737d29478f7STeresa Johnson 
7387e88d0daSMehdi Amini   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
739c8c55170SMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
740c8c55170SMehdi Amini   return ImportedCount;
74142418abaSMehdi Amini }
74242418abaSMehdi Amini 
74342418abaSMehdi Amini /// Summary file to use for function importing when using -function-import from
74442418abaSMehdi Amini /// the command line.
74542418abaSMehdi Amini static cl::opt<std::string>
74642418abaSMehdi Amini     SummaryFile("summary-file",
74742418abaSMehdi Amini                 cl::desc("The summary file to use for function importing."));
74842418abaSMehdi Amini 
74921241571STeresa Johnson static bool doImportingForModule(Module &M, const ModuleSummaryIndex *Index) {
7505fcbdb71STeresa Johnson   if (SummaryFile.empty() && !Index)
7515fcbdb71STeresa Johnson     report_fatal_error("error: -function-import requires -summary-file or "
7525fcbdb71STeresa Johnson                        "file from frontend\n");
75326ab5772STeresa Johnson   std::unique_ptr<ModuleSummaryIndex> IndexPtr;
7545fcbdb71STeresa Johnson   if (!SummaryFile.empty()) {
7555fcbdb71STeresa Johnson     if (Index)
7565fcbdb71STeresa Johnson       report_fatal_error("error: -summary-file and index from frontend\n");
7576de481a3SPeter Collingbourne     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
7586de481a3SPeter Collingbourne         getModuleSummaryIndexForFile(SummaryFile);
7596de481a3SPeter Collingbourne     if (!IndexPtrOrErr) {
7606de481a3SPeter Collingbourne       logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
7616de481a3SPeter Collingbourne                             "Error loading file '" + SummaryFile + "': ");
76242418abaSMehdi Amini       return false;
76342418abaSMehdi Amini     }
7646de481a3SPeter Collingbourne     IndexPtr = std::move(*IndexPtrOrErr);
7655fcbdb71STeresa Johnson     Index = IndexPtr.get();
7665fcbdb71STeresa Johnson   }
76742418abaSMehdi Amini 
768c86af334STeresa Johnson   // First step is collecting the import list.
769c86af334STeresa Johnson   FunctionImporter::ImportMapTy ImportList;
770c86af334STeresa Johnson   ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
771c86af334STeresa Johnson                                     ImportList);
77201e32130SMehdi Amini 
77301e32130SMehdi Amini   // Next we need to promote to global scope and rename any local values that
7741b00f2d9STeresa Johnson   // are potentially exported to other modules.
77501e32130SMehdi Amini   if (renameModuleForThinLTO(M, *Index, nullptr)) {
7761b00f2d9STeresa Johnson     errs() << "Error renaming module\n";
7771b00f2d9STeresa Johnson     return false;
7781b00f2d9STeresa Johnson   }
7791b00f2d9STeresa Johnson 
78042418abaSMehdi Amini   // Perform the import now.
781d16c8065SMehdi Amini   auto ModuleLoader = [&M](StringRef Identifier) {
782d16c8065SMehdi Amini     return loadFile(Identifier, M.getContext());
783d16c8065SMehdi Amini   };
7849d2bfc48SRafael Espindola   FunctionImporter Importer(*Index, ModuleLoader);
7857f00d0a1SPeter Collingbourne   Expected<bool> Result = Importer.importFunctions(
7867f00d0a1SPeter Collingbourne       M, ImportList, !DontForceImportReferencedDiscardableSymbols);
7877f00d0a1SPeter Collingbourne 
7887f00d0a1SPeter Collingbourne   // FIXME: Probably need to propagate Errors through the pass manager.
7897f00d0a1SPeter Collingbourne   if (!Result) {
7907f00d0a1SPeter Collingbourne     logAllUnhandledErrors(Result.takeError(), errs(),
7917f00d0a1SPeter Collingbourne                           "Error importing module: ");
7927f00d0a1SPeter Collingbourne     return false;
7937f00d0a1SPeter Collingbourne   }
7947f00d0a1SPeter Collingbourne 
7957f00d0a1SPeter Collingbourne   return *Result;
79621241571STeresa Johnson }
79721241571STeresa Johnson 
79821241571STeresa Johnson namespace {
79921241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file.
80021241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass {
80121241571STeresa Johnson   /// Optional module summary index to use for importing, otherwise
80221241571STeresa Johnson   /// the summary-file option must be specified.
80321241571STeresa Johnson   const ModuleSummaryIndex *Index;
80421241571STeresa Johnson 
80521241571STeresa Johnson public:
80621241571STeresa Johnson   /// Pass identification, replacement for typeid
80721241571STeresa Johnson   static char ID;
80821241571STeresa Johnson 
80921241571STeresa Johnson   /// Specify pass name for debug output
810117296c0SMehdi Amini   StringRef getPassName() const override { return "Function Importing"; }
81121241571STeresa Johnson 
81221241571STeresa Johnson   explicit FunctionImportLegacyPass(const ModuleSummaryIndex *Index = nullptr)
81321241571STeresa Johnson       : ModulePass(ID), Index(Index) {}
81421241571STeresa Johnson 
81521241571STeresa Johnson   bool runOnModule(Module &M) override {
81621241571STeresa Johnson     if (skipModule(M))
81721241571STeresa Johnson       return false;
81821241571STeresa Johnson 
81921241571STeresa Johnson     return doImportingForModule(M, Index);
82042418abaSMehdi Amini   }
82142418abaSMehdi Amini };
822fe2b5415SBenjamin Kramer } // anonymous namespace
82342418abaSMehdi Amini 
82421241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M,
825fd03ac6aSSean Silva                                           ModuleAnalysisManager &AM) {
82621241571STeresa Johnson   if (!doImportingForModule(M, Index))
82721241571STeresa Johnson     return PreservedAnalyses::all();
82821241571STeresa Johnson 
82921241571STeresa Johnson   return PreservedAnalyses::none();
83021241571STeresa Johnson }
83121241571STeresa Johnson 
83221241571STeresa Johnson char FunctionImportLegacyPass::ID = 0;
83321241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
83442418abaSMehdi Amini                 "Summary Based Function Import", false, false)
83542418abaSMehdi Amini 
83642418abaSMehdi Amini namespace llvm {
83726ab5772STeresa Johnson Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
83821241571STeresa Johnson   return new FunctionImportLegacyPass(Index);
8395fcbdb71STeresa Johnson }
84042418abaSMehdi Amini }
841