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 
114*58fbc916STeresa Johnson   if (Summary.noRename())
115*58fbc916STeresa Johnson     // Can't externally reference a global that needs renaming if has a section
116*58fbc916STeresa 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
156b4e1e829SMehdi Amini   // eligible for import.
157b4e1e829SMehdi Amini   bool AllRefsCanBeExternallyReferenced =
158b4e1e829SMehdi Amini       llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
159b4e1e829SMehdi Amini         return canBeExternallyReferenced(Index, VI.getGUID());
160b4e1e829SMehdi Amini       });
161b4e1e829SMehdi Amini   if (!AllRefsCanBeExternallyReferenced)
162b4e1e829SMehdi Amini     return false;
163b4e1e829SMehdi Amini 
164b4e1e829SMehdi Amini   if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
165b4e1e829SMehdi Amini     bool AllCallsCanBeExternallyReferenced = llvm::all_of(
166b4e1e829SMehdi Amini         FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
167b4e1e829SMehdi Amini           return canBeExternallyReferenced(Index, Edge.first.getGUID());
168b4e1e829SMehdi Amini         });
169b4e1e829SMehdi Amini     if (!AllCallsCanBeExternallyReferenced)
170b4e1e829SMehdi Amini       return false;
171b4e1e829SMehdi Amini   }
172b4e1e829SMehdi Amini   return true;
173b4e1e829SMehdi Amini }
174b4e1e829SMehdi Amini 
17501e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one
17601e32130SMehdi Amini /// that fits the \p Threshold.
17701e32130SMehdi Amini ///
17801e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"?
17901e32130SMehdi Amini /// - The smallest: more likely to be inlined.
18001e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized).
18101e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the
18201e32130SMehdi Amini ///   number of source modules parsed/linked.
18301e32130SMehdi Amini /// - One that has PGO data attached.
18401e32130SMehdi Amini /// - [insert you fancy metric here]
1852d28f7aaSMehdi Amini static const GlobalValueSummary *
186b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index,
187b4e1e829SMehdi Amini              const GlobalValueSummaryList &CalleeSummaryList,
18828e457bcSTeresa Johnson              unsigned Threshold) {
18901e32130SMehdi Amini   auto It = llvm::find_if(
19028e457bcSTeresa Johnson       CalleeSummaryList,
19128e457bcSTeresa Johnson       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
19228e457bcSTeresa Johnson         auto *GVSummary = SummaryPtr.get();
193f329be83SRafael Espindola         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
1945b85d8d6SMehdi Amini           // There is no point in importing these, we can't inline them
19501e32130SMehdi Amini           return false;
1962c719cc1SMehdi Amini         if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
1972c719cc1SMehdi Amini           GVSummary = &AS->getAliasee();
1982c719cc1SMehdi Amini           // Alias can't point to "available_externally". However when we import
1992c719cc1SMehdi Amini           // linkOnceODR the linkage does not change. So we import the alias
2002c719cc1SMehdi Amini           // and aliasee only in this case.
2012c719cc1SMehdi Amini           // FIXME: we should import alias as available_externally *function*,
2022c719cc1SMehdi Amini           // the destination module does need to know it is an alias.
2032c719cc1SMehdi Amini           if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
2042c719cc1SMehdi Amini             return false;
2052c719cc1SMehdi Amini         }
2062c719cc1SMehdi Amini 
2072c719cc1SMehdi Amini         auto *Summary = cast<FunctionSummary>(GVSummary);
2087e88d0daSMehdi Amini 
20901e32130SMehdi Amini         if (Summary->instCount() > Threshold)
21001e32130SMehdi Amini           return false;
2117e88d0daSMehdi Amini 
212b4e1e829SMehdi Amini         if (!eligibleForImport(Index, *Summary))
213b4e1e829SMehdi Amini           return false;
214b4e1e829SMehdi Amini 
21501e32130SMehdi Amini         return true;
21601e32130SMehdi Amini       });
21728e457bcSTeresa Johnson   if (It == CalleeSummaryList.end())
21801e32130SMehdi Amini     return nullptr;
2197e88d0daSMehdi Amini 
22028e457bcSTeresa Johnson   return cast<GlobalValueSummary>(It->get());
221434e9561SRafael Espindola }
2227e88d0daSMehdi Amini 
22301e32130SMehdi Amini /// Return the summary for the function \p GUID that fits the \p Threshold, or
22401e32130SMehdi Amini /// null if there's no match.
2252d28f7aaSMehdi Amini static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
226ad5741b0SMehdi Amini                                               unsigned Threshold,
22701e32130SMehdi Amini                                               const ModuleSummaryIndex &Index) {
22828e457bcSTeresa Johnson   auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
229b4e1e829SMehdi Amini   if (CalleeSummaryList == Index.end())
23001e32130SMehdi Amini     return nullptr; // This function does not have a summary
231b4e1e829SMehdi Amini   return selectCallee(Index, CalleeSummaryList->second, Threshold);
23201e32130SMehdi Amini }
2337e88d0daSMehdi Amini 
234cb87494fSMehdi Amini /// Mark the global \p GUID as export by module \p ExportModulePath if found in
235cb87494fSMehdi Amini /// this module. If it is a GlobalVariable, we also mark any referenced global
236cb87494fSMehdi Amini /// in the current module as exported.
237cb87494fSMehdi Amini static void exportGlobalInModule(const ModuleSummaryIndex &Index,
238ad5741b0SMehdi Amini                                  StringRef ExportModulePath,
239cb87494fSMehdi Amini                                  GlobalValue::GUID GUID,
240cb87494fSMehdi Amini                                  FunctionImporter::ExportSetTy &ExportList) {
24128e457bcSTeresa Johnson   auto FindGlobalSummaryInModule =
24228e457bcSTeresa Johnson       [&](GlobalValue::GUID GUID) -> GlobalValueSummary *{
24328e457bcSTeresa Johnson         auto SummaryList = Index.findGlobalValueSummaryList(GUID);
24428e457bcSTeresa Johnson         if (SummaryList == Index.end())
24501e32130SMehdi Amini           // This global does not have a summary, it is not part of the ThinLTO
24601e32130SMehdi Amini           // process
247cb87494fSMehdi Amini           return nullptr;
24828e457bcSTeresa Johnson         auto SummaryIter = llvm::find_if(
24928e457bcSTeresa Johnson             SummaryList->second,
25028e457bcSTeresa Johnson             [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
25101e32130SMehdi Amini               return Summary->modulePath() == ExportModulePath;
25201e32130SMehdi Amini             });
25328e457bcSTeresa Johnson         if (SummaryIter == SummaryList->second.end())
254cb87494fSMehdi Amini           return nullptr;
25528e457bcSTeresa Johnson         return SummaryIter->get();
256cb87494fSMehdi Amini       };
257cb87494fSMehdi Amini 
25828e457bcSTeresa Johnson   auto *Summary = FindGlobalSummaryInModule(GUID);
25928e457bcSTeresa Johnson   if (!Summary)
260cb87494fSMehdi Amini     return;
261cb87494fSMehdi Amini   // We found it in the current module, mark as exported
262cb87494fSMehdi Amini   ExportList.insert(GUID);
263cb87494fSMehdi Amini 
264cb87494fSMehdi Amini   auto GVS = dyn_cast<GlobalVarSummary>(Summary);
265cb87494fSMehdi Amini   if (!GVS)
266cb87494fSMehdi Amini     return;
267cb87494fSMehdi Amini   // FunctionImportGlobalProcessing::doPromoteLocalToGlobal() will always
268cb87494fSMehdi Amini   // trigger importing  the initializer for `constant unnamed addr` globals that
269cb87494fSMehdi Amini   // are referenced. We conservatively export all the referenced symbols for
270cb87494fSMehdi Amini   // every global to workaround this, so that the ExportList is accurate.
271cb87494fSMehdi Amini   // FIXME: with a "isConstant" flag in the summary we could be more targetted.
272cb87494fSMehdi Amini   for (auto &Ref : GVS->refs()) {
273cb87494fSMehdi Amini     auto GUID = Ref.getGUID();
27428e457bcSTeresa Johnson     auto *RefSummary = FindGlobalSummaryInModule(GUID);
27528e457bcSTeresa Johnson     if (RefSummary)
276cb87494fSMehdi Amini       // Found a ref in the current module, mark it as exported
277cb87494fSMehdi Amini       ExportList.insert(GUID);
278cb87494fSMehdi Amini   }
27901e32130SMehdi Amini }
2807e88d0daSMehdi Amini 
28101e32130SMehdi Amini using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
28201e32130SMehdi Amini 
28301e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these
28401e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as
28501e32130SMehdi Amini /// exported from their source module.
28601e32130SMehdi Amini static void computeImportForFunction(
2873255eec1STeresa Johnson     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
288d9830eb7SPiotr Padlewski     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
28901e32130SMehdi Amini     SmallVectorImpl<EdgeInfo> &Worklist,
2909b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
291c86af334STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
29201e32130SMehdi Amini   for (auto &Edge : Summary.calls()) {
2932d5487cfSTeresa Johnson     auto GUID = Edge.first.getGUID();
29401e32130SMehdi Amini     DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
29501e32130SMehdi Amini 
2961aafabf7SMehdi Amini     if (DefinedGVSummaries.count(GUID)) {
29701e32130SMehdi Amini       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
2987e88d0daSMehdi Amini       continue;
299d450da32STeresa Johnson     }
30040641748SMehdi Amini 
301ba72b95fSPiotr Padlewski     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
302ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Hot)
303ba72b95fSPiotr Padlewski         return ImportHotMultiplier;
304ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Cold)
305ba72b95fSPiotr Padlewski         return ImportColdMultiplier;
306ba72b95fSPiotr Padlewski       return 1.0;
307ba72b95fSPiotr Padlewski     };
308ba72b95fSPiotr Padlewski 
309d9830eb7SPiotr Padlewski     const auto NewThreshold =
310ba72b95fSPiotr Padlewski         Threshold * GetBonusMultiplier(Edge.second.Hotness);
311d2869473SPiotr Padlewski 
312d9830eb7SPiotr Padlewski     auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
31301e32130SMehdi Amini     if (!CalleeSummary) {
31401e32130SMehdi Amini       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
3157e88d0daSMehdi Amini       continue;
3167e88d0daSMehdi Amini     }
3172d28f7aaSMehdi Amini     // "Resolve" the summary, traversing alias,
3182d28f7aaSMehdi Amini     const FunctionSummary *ResolvedCalleeSummary;
3196968ef77SMehdi Amini     if (isa<AliasSummary>(CalleeSummary)) {
3202d28f7aaSMehdi Amini       ResolvedCalleeSummary = cast<FunctionSummary>(
3212d28f7aaSMehdi Amini           &cast<AliasSummary>(CalleeSummary)->getAliasee());
3222c719cc1SMehdi Amini       assert(
3232c719cc1SMehdi Amini           GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
3242c719cc1SMehdi Amini           "Unexpected alias to a non-linkonceODR in import list");
3256968ef77SMehdi Amini     } else
3262d28f7aaSMehdi Amini       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
3272d28f7aaSMehdi Amini 
328d9830eb7SPiotr Padlewski     assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
32901e32130SMehdi Amini            "selectCallee() didn't honor the threshold");
33001e32130SMehdi Amini 
3312d28f7aaSMehdi Amini     auto ExportModulePath = ResolvedCalleeSummary->modulePath();
3329b490f10SMehdi Amini     auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
33301e32130SMehdi Amini     /// Since the traversal of the call graph is DFS, we can revisit a function
33401e32130SMehdi Amini     /// a second time with a higher threshold. In this case, it is added back to
33501e32130SMehdi Amini     /// the worklist with the new threshold.
3362e03094dSTeresa Johnson     if (ProcessedThreshold && ProcessedThreshold >= Threshold) {
33701e32130SMehdi Amini       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
33801e32130SMehdi Amini                    << ProcessedThreshold << "\n");
33901e32130SMehdi Amini       continue;
34001e32130SMehdi Amini     }
34101e32130SMehdi Amini     // Mark this function as imported in this module, with the current Threshold
34201e32130SMehdi Amini     ProcessedThreshold = Threshold;
34301e32130SMehdi Amini 
34401e32130SMehdi Amini     // Make exports in the source module.
345c86af334STeresa Johnson     if (ExportLists) {
346ef7555fbSMehdi Amini       auto &ExportList = (*ExportLists)[ExportModulePath];
34701e32130SMehdi Amini       ExportList.insert(GUID);
348c86af334STeresa Johnson       // Mark all functions and globals referenced by this function as exported
349c86af334STeresa Johnson       // to the outside if they are defined in the same source module.
3502d28f7aaSMehdi Amini       for (auto &Edge : ResolvedCalleeSummary->calls()) {
3512d5487cfSTeresa Johnson         auto CalleeGUID = Edge.first.getGUID();
352cb87494fSMehdi Amini         exportGlobalInModule(Index, ExportModulePath, CalleeGUID, ExportList);
35301e32130SMehdi Amini       }
3542d28f7aaSMehdi Amini       for (auto &Ref : ResolvedCalleeSummary->refs()) {
3552d5487cfSTeresa Johnson         auto GUID = Ref.getGUID();
356cb87494fSMehdi Amini         exportGlobalInModule(Index, ExportModulePath, GUID, ExportList);
3577e88d0daSMehdi Amini       }
358c86af334STeresa Johnson     }
3597e88d0daSMehdi Amini 
360d2869473SPiotr Padlewski     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
361d2869473SPiotr Padlewski       // Adjust the threshold for next level of imported functions.
362d2869473SPiotr Padlewski       // The threshold is different for hot callsites because we can then
363d2869473SPiotr Padlewski       // inline chains of hot calls.
364d2869473SPiotr Padlewski       if (IsHotCallsite)
365d2869473SPiotr Padlewski         return Threshold * ImportHotInstrFactor;
366d2869473SPiotr Padlewski       return Threshold * ImportInstrFactor;
367d2869473SPiotr Padlewski     };
368d2869473SPiotr Padlewski 
369d2869473SPiotr Padlewski     bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
370d2869473SPiotr Padlewski 
37101e32130SMehdi Amini     // Insert the newly imported function to the worklist.
372d2869473SPiotr Padlewski     Worklist.emplace_back(ResolvedCalleeSummary,
373d2869473SPiotr Padlewski                           GetAdjustedThreshold(Threshold, IsHotCallsite));
374d450da32STeresa Johnson   }
375d450da32STeresa Johnson }
376d450da32STeresa Johnson 
37701e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports
37801e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from
37901e32130SMehdi Amini /// another module (that may require promotion).
38001e32130SMehdi Amini static void ComputeImportForModule(
381c851d216STeresa Johnson     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
3829b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
383c86af334STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
38401e32130SMehdi Amini   // Worklist contains the list of function imported in this module, for which
38501e32130SMehdi Amini   // we will analyse the callees and may import further down the callgraph.
38601e32130SMehdi Amini   SmallVector<EdgeInfo, 128> Worklist;
38701e32130SMehdi Amini 
38801e32130SMehdi Amini   // Populate the worklist with the import for the functions in the current
38901e32130SMehdi Amini   // module
39028e457bcSTeresa Johnson   for (auto &GVSummary : DefinedGVSummaries) {
39128e457bcSTeresa Johnson     auto *Summary = GVSummary.second;
3922d28f7aaSMehdi Amini     if (auto *AS = dyn_cast<AliasSummary>(Summary))
3932d28f7aaSMehdi Amini       Summary = &AS->getAliasee();
3941aafabf7SMehdi Amini     auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
3951aafabf7SMehdi Amini     if (!FuncSummary)
3961aafabf7SMehdi Amini       // Skip import for global variables
3971aafabf7SMehdi Amini       continue;
39828e457bcSTeresa Johnson     DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
3992d28f7aaSMehdi Amini     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
4009b490f10SMehdi Amini                              DefinedGVSummaries, Worklist, ImportList,
40101e32130SMehdi Amini                              ExportLists);
40201e32130SMehdi Amini   }
40301e32130SMehdi Amini 
404d2869473SPiotr Padlewski   // Process the newly imported functions and add callees to the worklist.
40542418abaSMehdi Amini   while (!Worklist.empty()) {
40601e32130SMehdi Amini     auto FuncInfo = Worklist.pop_back_val();
40701e32130SMehdi Amini     auto *Summary = FuncInfo.first;
40801e32130SMehdi Amini     auto Threshold = FuncInfo.second;
40942418abaSMehdi Amini 
4101aafabf7SMehdi Amini     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
4119b490f10SMehdi Amini                              Worklist, ImportList, ExportLists);
412c8c55170SMehdi Amini   }
41342418abaSMehdi Amini }
414ffe2e4aaSMehdi Amini 
41501e32130SMehdi Amini } // anonymous namespace
41601e32130SMehdi Amini 
417c86af334STeresa Johnson /// Compute all the import and export for every module using the Index.
41801e32130SMehdi Amini void llvm::ComputeCrossModuleImport(
41901e32130SMehdi Amini     const ModuleSummaryIndex &Index,
420c851d216STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
42101e32130SMehdi Amini     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
42201e32130SMehdi Amini     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
42301e32130SMehdi Amini   // For each module that has function defined, compute the import/export lists.
4241aafabf7SMehdi Amini   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
4259b490f10SMehdi Amini     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
4261aafabf7SMehdi Amini     DEBUG(dbgs() << "Computing import for Module '"
4271aafabf7SMehdi Amini                  << DefinedGVSummaries.first() << "'\n");
4289b490f10SMehdi Amini     ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
429c86af334STeresa Johnson                            &ExportLists);
43001e32130SMehdi Amini   }
43101e32130SMehdi Amini 
43201e32130SMehdi Amini #ifndef NDEBUG
43301e32130SMehdi Amini   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
43401e32130SMehdi Amini                << " modules:\n");
43501e32130SMehdi Amini   for (auto &ModuleImports : ImportLists) {
43601e32130SMehdi Amini     auto ModName = ModuleImports.first();
43701e32130SMehdi Amini     auto &Exports = ExportLists[ModName];
43801e32130SMehdi Amini     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
43901e32130SMehdi Amini                  << " functions. Imports from " << ModuleImports.second.size()
44001e32130SMehdi Amini                  << " modules.\n");
44101e32130SMehdi Amini     for (auto &Src : ModuleImports.second) {
44201e32130SMehdi Amini       auto SrcModName = Src.first();
44301e32130SMehdi Amini       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
44401e32130SMehdi Amini                    << SrcModName << "\n");
44501e32130SMehdi Amini     }
44601e32130SMehdi Amini   }
44701e32130SMehdi Amini #endif
44801e32130SMehdi Amini }
44901e32130SMehdi Amini 
450c86af334STeresa Johnson /// Compute all the imports for the given module in the Index.
451c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule(
452c86af334STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
453c86af334STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
454c86af334STeresa Johnson 
455c86af334STeresa Johnson   // Collect the list of functions this module defines.
456c86af334STeresa Johnson   // GUID -> Summary
457c851d216STeresa Johnson   GVSummaryMapTy FunctionSummaryMap;
45828e457bcSTeresa Johnson   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
459c86af334STeresa Johnson 
460c86af334STeresa Johnson   // Compute the import list for this module.
461c86af334STeresa Johnson   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
46228e457bcSTeresa Johnson   ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
463c86af334STeresa Johnson 
464c86af334STeresa Johnson #ifndef NDEBUG
465c86af334STeresa Johnson   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
466c86af334STeresa Johnson                << ImportList.size() << " modules.\n");
467c86af334STeresa Johnson   for (auto &Src : ImportList) {
468c86af334STeresa Johnson     auto SrcModName = Src.first();
469c86af334STeresa Johnson     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
470c86af334STeresa Johnson                  << SrcModName << "\n");
471c86af334STeresa Johnson   }
472c86af334STeresa Johnson #endif
473c86af334STeresa Johnson }
474c86af334STeresa Johnson 
47584174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of
47684174c37STeresa Johnson /// \p ModulePath.
47784174c37STeresa Johnson void llvm::gatherImportedSummariesForModule(
47884174c37STeresa Johnson     StringRef ModulePath,
47984174c37STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
480cdbcbf74SMehdi Amini     const FunctionImporter::ImportMapTy &ImportList,
48184174c37STeresa Johnson     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
48284174c37STeresa Johnson   // Include all summaries from the importing module.
48384174c37STeresa Johnson   ModuleToSummariesForIndex[ModulePath] =
48484174c37STeresa Johnson       ModuleToDefinedGVSummaries.lookup(ModulePath);
48584174c37STeresa Johnson   // Include summaries for imports.
48688c491ddSMehdi Amini   for (auto &ILI : ImportList) {
48784174c37STeresa Johnson     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
48884174c37STeresa Johnson     const auto &DefinedGVSummaries =
48984174c37STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ILI.first());
49084174c37STeresa Johnson     for (auto &GI : ILI.second) {
49184174c37STeresa Johnson       const auto &DS = DefinedGVSummaries.find(GI.first);
49284174c37STeresa Johnson       assert(DS != DefinedGVSummaries.end() &&
49384174c37STeresa Johnson              "Expected a defined summary for imported global value");
49484174c37STeresa Johnson       SummariesForIndex[GI.first] = DS->second;
49584174c37STeresa Johnson     }
49684174c37STeresa Johnson   }
49784174c37STeresa Johnson }
49884174c37STeresa Johnson 
4998570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename.
500cdbcbf74SMehdi Amini std::error_code
501cdbcbf74SMehdi Amini llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
502cdbcbf74SMehdi Amini                        const FunctionImporter::ImportMapTy &ModuleImports) {
5038570fe47STeresa Johnson   std::error_code EC;
5048570fe47STeresa Johnson   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
5058570fe47STeresa Johnson   if (EC)
5068570fe47STeresa Johnson     return EC;
507cdbcbf74SMehdi Amini   for (auto &ILI : ModuleImports)
5088570fe47STeresa Johnson     ImportsOS << ILI.first() << "\n";
5098570fe47STeresa Johnson   return std::error_code();
5108570fe47STeresa Johnson }
5118570fe47STeresa Johnson 
51204c9a2d6STeresa Johnson /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
51304c9a2d6STeresa Johnson void llvm::thinLTOResolveWeakForLinkerModule(
51404c9a2d6STeresa Johnson     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
51504c9a2d6STeresa Johnson   auto updateLinkage = [&](GlobalValue &GV) {
51604c9a2d6STeresa Johnson     if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
51704c9a2d6STeresa Johnson       return;
51804c9a2d6STeresa Johnson     // See if the global summary analysis computed a new resolved linkage.
51904c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
52004c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end())
52104c9a2d6STeresa Johnson       return;
52204c9a2d6STeresa Johnson     auto NewLinkage = GS->second->linkage();
52304c9a2d6STeresa Johnson     if (NewLinkage == GV.getLinkage())
52404c9a2d6STeresa Johnson       return;
52504c9a2d6STeresa Johnson     DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
52604c9a2d6STeresa Johnson                  << GV.getLinkage() << " to " << NewLinkage << "\n");
52704c9a2d6STeresa Johnson     GV.setLinkage(NewLinkage);
5286107a419STeresa Johnson     // Remove functions converted to available_externally from comdats,
5296107a419STeresa Johnson     // as this is a declaration for the linker, and will be dropped eventually.
5306107a419STeresa Johnson     // It is illegal for comdats to contain declarations.
5316107a419STeresa Johnson     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
5326107a419STeresa Johnson     if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
5336107a419STeresa Johnson       assert(GO->hasAvailableExternallyLinkage() &&
5346107a419STeresa Johnson              "Expected comdat on definition (possibly available external)");
5356107a419STeresa Johnson       GO->setComdat(nullptr);
5366107a419STeresa Johnson     }
53704c9a2d6STeresa Johnson   };
53804c9a2d6STeresa Johnson 
53904c9a2d6STeresa Johnson   // Process functions and global now
54004c9a2d6STeresa Johnson   for (auto &GV : TheModule)
54104c9a2d6STeresa Johnson     updateLinkage(GV);
54204c9a2d6STeresa Johnson   for (auto &GV : TheModule.globals())
54304c9a2d6STeresa Johnson     updateLinkage(GV);
54404c9a2d6STeresa Johnson   for (auto &GV : TheModule.aliases())
54504c9a2d6STeresa Johnson     updateLinkage(GV);
54604c9a2d6STeresa Johnson }
54704c9a2d6STeresa Johnson 
54804c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis.
54904c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule,
55004c9a2d6STeresa Johnson                                     const GVSummaryMapTy &DefinedGlobals) {
55104c9a2d6STeresa Johnson   // Parse inline ASM and collect the list of symbols that are not defined in
55204c9a2d6STeresa Johnson   // the current module.
55304c9a2d6STeresa Johnson   StringSet<> AsmUndefinedRefs;
55404c9a2d6STeresa Johnson   object::IRObjectFile::CollectAsmUndefinedRefs(
55504c9a2d6STeresa Johnson       Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
55604c9a2d6STeresa Johnson       [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
55704c9a2d6STeresa Johnson         if (Flags & object::BasicSymbolRef::SF_Undefined)
55804c9a2d6STeresa Johnson           AsmUndefinedRefs.insert(Name);
55904c9a2d6STeresa Johnson       });
56004c9a2d6STeresa Johnson 
56104c9a2d6STeresa Johnson   // Declare a callback for the internalize pass that will ask for every
56204c9a2d6STeresa Johnson   // candidate GlobalValue if it can be internalized or not.
56304c9a2d6STeresa Johnson   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
56404c9a2d6STeresa Johnson     // Can't be internalized if referenced in inline asm.
56504c9a2d6STeresa Johnson     if (AsmUndefinedRefs.count(GV.getName()))
56604c9a2d6STeresa Johnson       return true;
56704c9a2d6STeresa Johnson 
56804c9a2d6STeresa Johnson     // Lookup the linkage recorded in the summaries during global analysis.
56904c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
57004c9a2d6STeresa Johnson     GlobalValue::LinkageTypes Linkage;
57104c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end()) {
57204c9a2d6STeresa Johnson       // Must have been promoted (possibly conservatively). Find original
57304c9a2d6STeresa Johnson       // name so that we can access the correct summary and see if it can
57404c9a2d6STeresa Johnson       // be internalized again.
57504c9a2d6STeresa Johnson       // FIXME: Eventually we should control promotion instead of promoting
57604c9a2d6STeresa Johnson       // and internalizing again.
57704c9a2d6STeresa Johnson       StringRef OrigName =
57804c9a2d6STeresa Johnson           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
57904c9a2d6STeresa Johnson       std::string OrigId = GlobalValue::getGlobalIdentifier(
58004c9a2d6STeresa Johnson           OrigName, GlobalValue::InternalLinkage,
58104c9a2d6STeresa Johnson           TheModule.getSourceFileName());
58204c9a2d6STeresa Johnson       const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
5837ab1f692STeresa Johnson       if (GS == DefinedGlobals.end()) {
5847ab1f692STeresa Johnson         // Also check the original non-promoted non-globalized name. In some
5857ab1f692STeresa Johnson         // cases a preempted weak value is linked in as a local copy because
5867ab1f692STeresa Johnson         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
5877ab1f692STeresa Johnson         // In that case, since it was originally not a local value, it was
5887ab1f692STeresa Johnson         // recorded in the index using the original name.
5897ab1f692STeresa Johnson         // FIXME: This may not be needed once PR27866 is fixed.
5907ab1f692STeresa Johnson         const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
59104c9a2d6STeresa Johnson         assert(GS != DefinedGlobals.end());
59204c9a2d6STeresa Johnson         Linkage = GS->second->linkage();
5937ab1f692STeresa Johnson       } else {
5947ab1f692STeresa Johnson         Linkage = GS->second->linkage();
5957ab1f692STeresa Johnson       }
59604c9a2d6STeresa Johnson     } else
59704c9a2d6STeresa Johnson       Linkage = GS->second->linkage();
59804c9a2d6STeresa Johnson     return !GlobalValue::isLocalLinkage(Linkage);
59904c9a2d6STeresa Johnson   };
60004c9a2d6STeresa Johnson 
60104c9a2d6STeresa Johnson   // FIXME: See if we can just internalize directly here via linkage changes
60204c9a2d6STeresa Johnson   // based on the index, rather than invoking internalizeModule.
60304c9a2d6STeresa Johnson   llvm::internalizeModule(TheModule, MustPreserveGV);
60404c9a2d6STeresa Johnson }
60504c9a2d6STeresa Johnson 
606c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries
607c8c55170SMehdi Amini // index.
608c8c55170SMehdi Amini //
60901e32130SMehdi Amini bool FunctionImporter::importFunctions(
610bda3c97cSMehdi Amini     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
611bda3c97cSMehdi Amini     bool ForceImportReferencedDiscardableSymbols) {
6125411d051SMehdi Amini   DEBUG(dbgs() << "Starting import for Module "
613311fef6eSMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
614c8c55170SMehdi Amini   unsigned ImportedCount = 0;
615c8c55170SMehdi Amini 
616c8c55170SMehdi Amini   // Linker that will be used for importing function
6179d2bfc48SRafael Espindola   Linker TheLinker(DestModule);
6187e88d0daSMehdi Amini   // Do the actual import of functions now, one Module at a time
61901e32130SMehdi Amini   std::set<StringRef> ModuleNameOrderedList;
62001e32130SMehdi Amini   for (auto &FunctionsToImportPerModule : ImportList) {
62101e32130SMehdi Amini     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
62201e32130SMehdi Amini   }
62301e32130SMehdi Amini   for (auto &Name : ModuleNameOrderedList) {
6247e88d0daSMehdi Amini     // Get the module for the import
62501e32130SMehdi Amini     const auto &FunctionsToImportPerModule = ImportList.find(Name);
62601e32130SMehdi Amini     assert(FunctionsToImportPerModule != ImportList.end());
62701e32130SMehdi Amini     std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
6287e88d0daSMehdi Amini     assert(&DestModule.getContext() == &SrcModule->getContext() &&
6297e88d0daSMehdi Amini            "Context mismatch");
6307e88d0daSMehdi Amini 
6316cba37ceSTeresa Johnson     // If modules were created with lazy metadata loading, materialize it
6326cba37ceSTeresa Johnson     // now, before linking it (otherwise this will be a noop).
6336cba37ceSTeresa Johnson     SrcModule->materializeMetadata();
6346cba37ceSTeresa Johnson     UpgradeDebugInfo(*SrcModule);
635e5a61917STeresa Johnson 
63601e32130SMehdi Amini     auto &ImportGUIDs = FunctionsToImportPerModule->second;
63701e32130SMehdi Amini     // Find the globals to import
63801e32130SMehdi Amini     DenseSet<const GlobalValue *> GlobalsToImport;
6391f685e01SPiotr Padlewski     for (Function &F : *SrcModule) {
6401f685e01SPiotr Padlewski       if (!F.hasName())
6410beb858eSTeresa Johnson         continue;
6421f685e01SPiotr Padlewski       auto GUID = F.getGUID();
6430beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
644aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
6451f685e01SPiotr Padlewski                    << " " << F.getName() << " from "
646aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6470beb858eSTeresa Johnson       if (Import) {
6481f685e01SPiotr Padlewski         F.materialize();
6493b776128SPiotr Padlewski         if (EnableImportMetadata) {
6506deaa6afSPiotr Padlewski           // Add 'thinlto_src_module' metadata for statistics and debugging.
6513b776128SPiotr Padlewski           F.setMetadata(
6523b776128SPiotr Padlewski               "thinlto_src_module",
6533b776128SPiotr Padlewski               llvm::MDNode::get(
6546deaa6afSPiotr Padlewski                   DestModule.getContext(),
6553b776128SPiotr Padlewski                   {llvm::MDString::get(DestModule.getContext(),
6566deaa6afSPiotr Padlewski                                        SrcModule->getSourceFileName())}));
6573b776128SPiotr Padlewski         }
6581f685e01SPiotr Padlewski         GlobalsToImport.insert(&F);
65901e32130SMehdi Amini       }
66001e32130SMehdi Amini     }
6611f685e01SPiotr Padlewski     for (GlobalVariable &GV : SrcModule->globals()) {
6622d28f7aaSMehdi Amini       if (!GV.hasName())
6632d28f7aaSMehdi Amini         continue;
6642d28f7aaSMehdi Amini       auto GUID = GV.getGUID();
6652d28f7aaSMehdi Amini       auto Import = ImportGUIDs.count(GUID);
666aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
667aeb1e59bSMehdi Amini                    << " " << GV.getName() << " from "
668aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6692d28f7aaSMehdi Amini       if (Import) {
6702d28f7aaSMehdi Amini         GV.materialize();
6712d28f7aaSMehdi Amini         GlobalsToImport.insert(&GV);
6722d28f7aaSMehdi Amini       }
6732d28f7aaSMehdi Amini     }
6741f685e01SPiotr Padlewski     for (GlobalAlias &GA : SrcModule->aliases()) {
6751f685e01SPiotr Padlewski       if (!GA.hasName())
67601e32130SMehdi Amini         continue;
6771f685e01SPiotr Padlewski       auto GUID = GA.getGUID();
6780beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
679aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
6801f685e01SPiotr Padlewski                    << " " << GA.getName() << " from "
681aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6820beb858eSTeresa Johnson       if (Import) {
68301e32130SMehdi Amini         // Alias can't point to "available_externally". However when we import
6849aae395fSTeresa Johnson         // linkOnceODR the linkage does not change. So we import the alias
6856968ef77SMehdi Amini         // and aliasee only in this case. This has been handled by
6866968ef77SMehdi Amini         // computeImportForFunction()
6871f685e01SPiotr Padlewski         GlobalObject *GO = GA.getBaseObject();
6886968ef77SMehdi Amini         assert(GO->hasLinkOnceODRLinkage() &&
6896968ef77SMehdi Amini                "Unexpected alias to a non-linkonceODR in import list");
6902d28f7aaSMehdi Amini #ifndef NDEBUG
6912d28f7aaSMehdi Amini         if (!GlobalsToImport.count(GO))
6922d28f7aaSMehdi Amini           DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
6932d28f7aaSMehdi Amini                        << " " << GO->getName() << " from "
6942d28f7aaSMehdi Amini                        << SrcModule->getSourceFileName() << "\n");
6952d28f7aaSMehdi Amini #endif
6962d28f7aaSMehdi Amini         GO->materialize();
69701e32130SMehdi Amini         GlobalsToImport.insert(GO);
6981f685e01SPiotr Padlewski         GA.materialize();
6991f685e01SPiotr Padlewski         GlobalsToImport.insert(&GA);
70001e32130SMehdi Amini       }
70101e32130SMehdi Amini     }
70201e32130SMehdi Amini 
7037e88d0daSMehdi Amini     // Link in the specified functions.
70401e32130SMehdi Amini     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
7058d05185aSMehdi Amini       return true;
7068d05185aSMehdi Amini 
707d29478f7STeresa Johnson     if (PrintImports) {
708d29478f7STeresa Johnson       for (const auto *GV : GlobalsToImport)
709d29478f7STeresa Johnson         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
710d29478f7STeresa Johnson                << " from " << SrcModule->getSourceFileName() << "\n";
711d29478f7STeresa Johnson     }
712d29478f7STeresa Johnson 
713bda3c97cSMehdi Amini     // Instruct the linker that the client will take care of linkonce resolution
714bda3c97cSMehdi Amini     unsigned Flags = Linker::Flags::None;
715bda3c97cSMehdi Amini     if (!ForceImportReferencedDiscardableSymbols)
716bda3c97cSMehdi Amini       Flags |= Linker::Flags::DontForceLinkLinkonceODR;
717bda3c97cSMehdi Amini 
718bda3c97cSMehdi Amini     if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
7197e88d0daSMehdi Amini       report_fatal_error("Function Import: link error");
7207e88d0daSMehdi Amini 
72101e32130SMehdi Amini     ImportedCount += GlobalsToImport.size();
7227e88d0daSMehdi Amini   }
723e5a61917STeresa Johnson 
724d29478f7STeresa Johnson   NumImported += ImportedCount;
725d29478f7STeresa Johnson 
7267e88d0daSMehdi Amini   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
727c8c55170SMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
728c8c55170SMehdi Amini   return ImportedCount;
72942418abaSMehdi Amini }
73042418abaSMehdi Amini 
73142418abaSMehdi Amini /// Summary file to use for function importing when using -function-import from
73242418abaSMehdi Amini /// the command line.
73342418abaSMehdi Amini static cl::opt<std::string>
73442418abaSMehdi Amini     SummaryFile("summary-file",
73542418abaSMehdi Amini                 cl::desc("The summary file to use for function importing."));
73642418abaSMehdi Amini 
73742418abaSMehdi Amini static void diagnosticHandler(const DiagnosticInfo &DI) {
73842418abaSMehdi Amini   raw_ostream &OS = errs();
73942418abaSMehdi Amini   DiagnosticPrinterRawOStream DP(OS);
74042418abaSMehdi Amini   DI.print(DP);
74142418abaSMehdi Amini   OS << '\n';
74242418abaSMehdi Amini }
74342418abaSMehdi Amini 
74426ab5772STeresa Johnson /// Parse the summary index out of an IR file and return the summary
74542418abaSMehdi Amini /// index object if found, or nullptr if not.
7461afc1de4SBenjamin Kramer static std::unique_ptr<ModuleSummaryIndex> getModuleSummaryIndexForFile(
7471afc1de4SBenjamin Kramer     StringRef Path, std::string &Error,
7481afc1de4SBenjamin Kramer     const DiagnosticHandlerFunction &DiagnosticHandler) {
74942418abaSMehdi Amini   std::unique_ptr<MemoryBuffer> Buffer;
75042418abaSMehdi Amini   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
75142418abaSMehdi Amini       MemoryBuffer::getFile(Path);
75242418abaSMehdi Amini   if (std::error_code EC = BufferOrErr.getError()) {
75342418abaSMehdi Amini     Error = EC.message();
75442418abaSMehdi Amini     return nullptr;
75542418abaSMehdi Amini   }
75642418abaSMehdi Amini   Buffer = std::move(BufferOrErr.get());
75726ab5772STeresa Johnson   ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
75826ab5772STeresa Johnson       object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
75942418abaSMehdi Amini                                                    DiagnosticHandler);
76042418abaSMehdi Amini   if (std::error_code EC = ObjOrErr.getError()) {
76142418abaSMehdi Amini     Error = EC.message();
76242418abaSMehdi Amini     return nullptr;
76342418abaSMehdi Amini   }
76442418abaSMehdi Amini   return (*ObjOrErr)->takeIndex();
76542418abaSMehdi Amini }
76642418abaSMehdi Amini 
76721241571STeresa Johnson static bool doImportingForModule(Module &M, const ModuleSummaryIndex *Index) {
7685fcbdb71STeresa Johnson   if (SummaryFile.empty() && !Index)
7695fcbdb71STeresa Johnson     report_fatal_error("error: -function-import requires -summary-file or "
7705fcbdb71STeresa Johnson                        "file from frontend\n");
77126ab5772STeresa Johnson   std::unique_ptr<ModuleSummaryIndex> IndexPtr;
7725fcbdb71STeresa Johnson   if (!SummaryFile.empty()) {
7735fcbdb71STeresa Johnson     if (Index)
7745fcbdb71STeresa Johnson       report_fatal_error("error: -summary-file and index from frontend\n");
77542418abaSMehdi Amini     std::string Error;
77626ab5772STeresa Johnson     IndexPtr =
77726ab5772STeresa Johnson         getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
7785fcbdb71STeresa Johnson     if (!IndexPtr) {
77921241571STeresa Johnson       errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
78042418abaSMehdi Amini       return false;
78142418abaSMehdi Amini     }
7825fcbdb71STeresa Johnson     Index = IndexPtr.get();
7835fcbdb71STeresa Johnson   }
78442418abaSMehdi Amini 
785c86af334STeresa Johnson   // First step is collecting the import list.
786c86af334STeresa Johnson   FunctionImporter::ImportMapTy ImportList;
787c86af334STeresa Johnson   ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
788c86af334STeresa Johnson                                     ImportList);
78901e32130SMehdi Amini 
79001e32130SMehdi Amini   // Next we need to promote to global scope and rename any local values that
7911b00f2d9STeresa Johnson   // are potentially exported to other modules.
79201e32130SMehdi Amini   if (renameModuleForThinLTO(M, *Index, nullptr)) {
7931b00f2d9STeresa Johnson     errs() << "Error renaming module\n";
7941b00f2d9STeresa Johnson     return false;
7951b00f2d9STeresa Johnson   }
7961b00f2d9STeresa Johnson 
79742418abaSMehdi Amini   // Perform the import now.
798d16c8065SMehdi Amini   auto ModuleLoader = [&M](StringRef Identifier) {
799d16c8065SMehdi Amini     return loadFile(Identifier, M.getContext());
800d16c8065SMehdi Amini   };
8019d2bfc48SRafael Espindola   FunctionImporter Importer(*Index, ModuleLoader);
80221241571STeresa Johnson   return Importer.importFunctions(M, ImportList,
80321241571STeresa Johnson                                   !DontForceImportReferencedDiscardableSymbols);
80421241571STeresa Johnson }
80521241571STeresa Johnson 
80621241571STeresa Johnson namespace {
80721241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file.
80821241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass {
80921241571STeresa Johnson   /// Optional module summary index to use for importing, otherwise
81021241571STeresa Johnson   /// the summary-file option must be specified.
81121241571STeresa Johnson   const ModuleSummaryIndex *Index;
81221241571STeresa Johnson 
81321241571STeresa Johnson public:
81421241571STeresa Johnson   /// Pass identification, replacement for typeid
81521241571STeresa Johnson   static char ID;
81621241571STeresa Johnson 
81721241571STeresa Johnson   /// Specify pass name for debug output
818117296c0SMehdi Amini   StringRef getPassName() const override { return "Function Importing"; }
81921241571STeresa Johnson 
82021241571STeresa Johnson   explicit FunctionImportLegacyPass(const ModuleSummaryIndex *Index = nullptr)
82121241571STeresa Johnson       : ModulePass(ID), Index(Index) {}
82221241571STeresa Johnson 
82321241571STeresa Johnson   bool runOnModule(Module &M) override {
82421241571STeresa Johnson     if (skipModule(M))
82521241571STeresa Johnson       return false;
82621241571STeresa Johnson 
82721241571STeresa Johnson     return doImportingForModule(M, Index);
82842418abaSMehdi Amini   }
82942418abaSMehdi Amini };
830fe2b5415SBenjamin Kramer } // anonymous namespace
83142418abaSMehdi Amini 
83221241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M,
833fd03ac6aSSean Silva                                           ModuleAnalysisManager &AM) {
83421241571STeresa Johnson   if (!doImportingForModule(M, Index))
83521241571STeresa Johnson     return PreservedAnalyses::all();
83621241571STeresa Johnson 
83721241571STeresa Johnson   return PreservedAnalyses::none();
83821241571STeresa Johnson }
83921241571STeresa Johnson 
84021241571STeresa Johnson char FunctionImportLegacyPass::ID = 0;
84121241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
84242418abaSMehdi Amini                 "Summary Based Function Import", false, false)
84342418abaSMehdi Amini 
84442418abaSMehdi Amini namespace llvm {
84526ab5772STeresa Johnson Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
84621241571STeresa Johnson   return new FunctionImportLegacyPass(Index);
8475fcbdb71STeresa Johnson }
84842418abaSMehdi Amini }
849