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"
24*fc06b83eSMehdi Amini #include "llvm/IR/Verifier.h"
2542418abaSMehdi Amini #include "llvm/IRReader/IRReader.h"
2642418abaSMehdi Amini #include "llvm/Linker/Linker.h"
2704c9a2d6STeresa Johnson #include "llvm/Object/IRObjectFile.h"
2826ab5772STeresa Johnson #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
2942418abaSMehdi Amini #include "llvm/Support/CommandLine.h"
3042418abaSMehdi Amini #include "llvm/Support/Debug.h"
3142418abaSMehdi Amini #include "llvm/Support/SourceMgr.h"
3204c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h"
33488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h"
347e88d0daSMehdi Amini 
3501e32130SMehdi Amini #define DEBUG_TYPE "function-import"
367e88d0daSMehdi Amini 
3742418abaSMehdi Amini using namespace llvm;
3842418abaSMehdi Amini 
39d29478f7STeresa Johnson STATISTIC(NumImported, "Number of functions imported");
40d29478f7STeresa Johnson 
4139303619STeresa Johnson /// Limit on instruction count of imported functions.
4239303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit(
4339303619STeresa Johnson     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
4439303619STeresa Johnson     cl::desc("Only import functions with less than N instructions"));
4539303619STeresa Johnson 
4640641748SMehdi Amini static cl::opt<float>
4740641748SMehdi Amini     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
4840641748SMehdi Amini                       cl::Hidden, cl::value_desc("x"),
4940641748SMehdi Amini                       cl::desc("As we import functions, multiply the "
5040641748SMehdi Amini                                "`import-instr-limit` threshold by this factor "
5140641748SMehdi Amini                                "before processing newly imported functions"));
52ba72b95fSPiotr Padlewski 
53d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor(
54d2869473SPiotr Padlewski     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
55d2869473SPiotr Padlewski     cl::value_desc("x"),
56d2869473SPiotr Padlewski     cl::desc("As we import functions called from hot callsite, multiply the "
57d2869473SPiotr Padlewski              "`import-instr-limit` threshold by this factor "
58d2869473SPiotr Padlewski              "before processing newly imported functions"));
59d2869473SPiotr Padlewski 
60d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier(
61d9830eb7SPiotr Padlewski     "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
62ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
63ba72b95fSPiotr Padlewski 
64ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up.
65ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier(
66ba72b95fSPiotr Padlewski     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
67ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
6840641748SMehdi Amini 
69d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
70d29478f7STeresa Johnson                                   cl::desc("Print imported functions"));
71d29478f7STeresa Johnson 
72bda3c97cSMehdi Amini // Temporary allows the function import pass to disable always linking
73bda3c97cSMehdi Amini // referenced discardable symbols.
74bda3c97cSMehdi Amini static cl::opt<bool>
75bda3c97cSMehdi Amini     DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
76bda3c97cSMehdi Amini                                                 cl::init(false), cl::Hidden);
77bda3c97cSMehdi Amini 
783b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata(
793b776128SPiotr Padlewski     "enable-import-metadata", cl::init(
803b776128SPiotr Padlewski #if !defined(NDEBUG)
813b776128SPiotr Padlewski                                   true /*Enabled with asserts.*/
823b776128SPiotr Padlewski #else
833b776128SPiotr Padlewski                                   false
843b776128SPiotr Padlewski #endif
853b776128SPiotr Padlewski                                   ),
863b776128SPiotr Padlewski     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
873b776128SPiotr Padlewski 
8842418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context.
8942418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName,
9042418abaSMehdi Amini                                         LLVMContext &Context) {
9142418abaSMehdi Amini   SMDiagnostic Err;
9242418abaSMehdi Amini   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
936cba37ceSTeresa Johnson   // Metadata isn't loaded until functions are imported, to minimize
946cba37ceSTeresa Johnson   // the memory overhead.
95a1080ee6STeresa Johnson   std::unique_ptr<Module> Result =
96a1080ee6STeresa Johnson       getLazyIRFileModule(FileName, Err, Context,
97a1080ee6STeresa Johnson                           /* ShouldLazyLoadMetadata = */ true);
9842418abaSMehdi Amini   if (!Result) {
9942418abaSMehdi Amini     Err.print("function-import", errs());
100d7ad221cSMehdi Amini     report_fatal_error("Abort");
10142418abaSMehdi Amini   }
10242418abaSMehdi Amini 
10342418abaSMehdi Amini   return Result;
10442418abaSMehdi Amini }
10542418abaSMehdi Amini 
1067e88d0daSMehdi Amini namespace {
10740641748SMehdi Amini 
108b4e1e829SMehdi Amini // Return true if the Summary describes a GlobalValue that can be externally
109b4e1e829SMehdi Amini // referenced, i.e. it does not need renaming (linkage is not local) or renaming
110b4e1e829SMehdi Amini // is possible (does not have a section for instance).
111b4e1e829SMehdi Amini static bool canBeExternallyReferenced(const GlobalValueSummary &Summary) {
112b4e1e829SMehdi Amini   if (!Summary.needsRenaming())
113b4e1e829SMehdi Amini     return true;
114b4e1e829SMehdi Amini 
11558fbc916STeresa Johnson   if (Summary.noRename())
11658fbc916STeresa Johnson     // Can't externally reference a global that needs renaming if has a section
11758fbc916STeresa Johnson     // or is referenced from inline assembly, for example.
118b4e1e829SMehdi Amini     return false;
119b4e1e829SMehdi Amini 
120b4e1e829SMehdi Amini   return true;
121b4e1e829SMehdi Amini }
122b4e1e829SMehdi Amini 
123b4e1e829SMehdi Amini // Return true if \p GUID describes a GlobalValue that can be externally
124b4e1e829SMehdi Amini // referenced, i.e. it does not need renaming (linkage is not local) or
125b4e1e829SMehdi Amini // renaming is possible (does not have a section for instance).
126b4e1e829SMehdi Amini static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index,
127b4e1e829SMehdi Amini                                       GlobalValue::GUID GUID) {
128b4e1e829SMehdi Amini   auto Summaries = Index.findGlobalValueSummaryList(GUID);
129b4e1e829SMehdi Amini   if (Summaries == Index.end())
130b4e1e829SMehdi Amini     return true;
131b4e1e829SMehdi Amini   if (Summaries->second.size() != 1)
132b4e1e829SMehdi Amini     // If there are multiple globals with this GUID, then we know it is
133b4e1e829SMehdi Amini     // not a local symbol, and it is necessarily externally referenced.
134b4e1e829SMehdi Amini     return true;
135b4e1e829SMehdi Amini 
136b4e1e829SMehdi Amini   // We don't need to check for the module path, because if it can't be
137b4e1e829SMehdi Amini   // externally referenced and we call it, it is necessarilly in the same
138b4e1e829SMehdi Amini   // module
139b4e1e829SMehdi Amini   return canBeExternallyReferenced(**Summaries->second.begin());
140b4e1e829SMehdi Amini }
141b4e1e829SMehdi Amini 
142b4e1e829SMehdi Amini // Return true if the global described by \p Summary can be imported in another
143b4e1e829SMehdi Amini // module.
144b4e1e829SMehdi Amini static bool eligibleForImport(const ModuleSummaryIndex &Index,
145b4e1e829SMehdi Amini                               const GlobalValueSummary &Summary) {
146b4e1e829SMehdi Amini   if (!canBeExternallyReferenced(Summary))
147b4e1e829SMehdi Amini     // Can't import a global that needs renaming if has a section for instance.
148b4e1e829SMehdi Amini     // FIXME: we may be able to import it by copying it without promotion.
149b4e1e829SMehdi Amini     return false;
150b4e1e829SMehdi Amini 
151332b3b22SPiotr Padlewski   // Don't import functions that are not viable to inline.
152332b3b22SPiotr Padlewski   if (Summary.isNotViableToInline())
153332b3b22SPiotr Padlewski     return false;
154332b3b22SPiotr Padlewski 
155b4e1e829SMehdi Amini   // Check references (and potential calls) in the same module. If the current
156b4e1e829SMehdi Amini   // value references a global that can't be externally referenced it is not
157d5033a45STeresa Johnson   // eligible for import. First check the flag set when we have possible
158d5033a45STeresa Johnson   // opaque references (e.g. inline asm calls), then check the call and
159d5033a45STeresa Johnson   // reference sets.
160d5033a45STeresa Johnson   if (Summary.hasInlineAsmMaybeReferencingInternal())
161d5033a45STeresa Johnson     return false;
162b4e1e829SMehdi Amini   bool AllRefsCanBeExternallyReferenced =
163b4e1e829SMehdi Amini       llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
164b4e1e829SMehdi Amini         return canBeExternallyReferenced(Index, VI.getGUID());
165b4e1e829SMehdi Amini       });
166b4e1e829SMehdi Amini   if (!AllRefsCanBeExternallyReferenced)
167b4e1e829SMehdi Amini     return false;
168b4e1e829SMehdi Amini 
169b4e1e829SMehdi Amini   if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
170b4e1e829SMehdi Amini     bool AllCallsCanBeExternallyReferenced = llvm::all_of(
171b4e1e829SMehdi Amini         FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
172b4e1e829SMehdi Amini           return canBeExternallyReferenced(Index, Edge.first.getGUID());
173b4e1e829SMehdi Amini         });
174b4e1e829SMehdi Amini     if (!AllCallsCanBeExternallyReferenced)
175b4e1e829SMehdi Amini       return false;
176b4e1e829SMehdi Amini   }
177b4e1e829SMehdi Amini   return true;
178b4e1e829SMehdi Amini }
179b4e1e829SMehdi Amini 
18001e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one
18101e32130SMehdi Amini /// that fits the \p Threshold.
18201e32130SMehdi Amini ///
18301e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"?
18401e32130SMehdi Amini /// - The smallest: more likely to be inlined.
18501e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized).
18601e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the
18701e32130SMehdi Amini ///   number of source modules parsed/linked.
18801e32130SMehdi Amini /// - One that has PGO data attached.
18901e32130SMehdi Amini /// - [insert you fancy metric here]
1902d28f7aaSMehdi Amini static const GlobalValueSummary *
191b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index,
192b4e1e829SMehdi Amini              const GlobalValueSummaryList &CalleeSummaryList,
19328e457bcSTeresa Johnson              unsigned Threshold) {
19401e32130SMehdi Amini   auto It = llvm::find_if(
19528e457bcSTeresa Johnson       CalleeSummaryList,
19628e457bcSTeresa Johnson       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
19728e457bcSTeresa Johnson         auto *GVSummary = SummaryPtr.get();
198f329be83SRafael Espindola         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
1995b85d8d6SMehdi Amini           // There is no point in importing these, we can't inline them
20001e32130SMehdi Amini           return false;
2012c719cc1SMehdi Amini         if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
2022c719cc1SMehdi Amini           GVSummary = &AS->getAliasee();
2032c719cc1SMehdi Amini           // Alias can't point to "available_externally". However when we import
2042c719cc1SMehdi Amini           // linkOnceODR the linkage does not change. So we import the alias
2052c719cc1SMehdi Amini           // and aliasee only in this case.
2062c719cc1SMehdi Amini           // FIXME: we should import alias as available_externally *function*,
2072c719cc1SMehdi Amini           // the destination module does need to know it is an alias.
2082c719cc1SMehdi Amini           if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
2092c719cc1SMehdi Amini             return false;
2102c719cc1SMehdi Amini         }
2112c719cc1SMehdi Amini 
2122c719cc1SMehdi Amini         auto *Summary = cast<FunctionSummary>(GVSummary);
2137e88d0daSMehdi Amini 
21401e32130SMehdi Amini         if (Summary->instCount() > Threshold)
21501e32130SMehdi Amini           return false;
2167e88d0daSMehdi Amini 
217b4e1e829SMehdi Amini         if (!eligibleForImport(Index, *Summary))
218b4e1e829SMehdi Amini           return false;
219b4e1e829SMehdi Amini 
22001e32130SMehdi Amini         return true;
22101e32130SMehdi Amini       });
22228e457bcSTeresa Johnson   if (It == CalleeSummaryList.end())
22301e32130SMehdi Amini     return nullptr;
2247e88d0daSMehdi Amini 
22528e457bcSTeresa Johnson   return cast<GlobalValueSummary>(It->get());
226434e9561SRafael Espindola }
2277e88d0daSMehdi Amini 
22801e32130SMehdi Amini /// Return the summary for the function \p GUID that fits the \p Threshold, or
22901e32130SMehdi Amini /// null if there's no match.
2302d28f7aaSMehdi Amini static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
231ad5741b0SMehdi Amini                                               unsigned Threshold,
23201e32130SMehdi Amini                                               const ModuleSummaryIndex &Index) {
23328e457bcSTeresa Johnson   auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
234b4e1e829SMehdi Amini   if (CalleeSummaryList == Index.end())
23501e32130SMehdi Amini     return nullptr; // This function does not have a summary
236b4e1e829SMehdi Amini   return selectCallee(Index, CalleeSummaryList->second, Threshold);
23701e32130SMehdi Amini }
2387e88d0daSMehdi Amini 
239475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
240475b51a7STeresa Johnson                             GlobalValue::GUID>;
24101e32130SMehdi Amini 
24201e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these
24301e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as
24401e32130SMehdi Amini /// exported from their source module.
24501e32130SMehdi Amini static void computeImportForFunction(
2463255eec1STeresa Johnson     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
247d9830eb7SPiotr Padlewski     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
24801e32130SMehdi Amini     SmallVectorImpl<EdgeInfo> &Worklist,
2499b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
250c86af334STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
25101e32130SMehdi Amini   for (auto &Edge : Summary.calls()) {
2522d5487cfSTeresa Johnson     auto GUID = Edge.first.getGUID();
25301e32130SMehdi Amini     DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
25401e32130SMehdi Amini 
2551aafabf7SMehdi Amini     if (DefinedGVSummaries.count(GUID)) {
25601e32130SMehdi Amini       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
2577e88d0daSMehdi Amini       continue;
258d450da32STeresa Johnson     }
25940641748SMehdi Amini 
260ba72b95fSPiotr Padlewski     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
261ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Hot)
262ba72b95fSPiotr Padlewski         return ImportHotMultiplier;
263ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Cold)
264ba72b95fSPiotr Padlewski         return ImportColdMultiplier;
265ba72b95fSPiotr Padlewski       return 1.0;
266ba72b95fSPiotr Padlewski     };
267ba72b95fSPiotr Padlewski 
268d9830eb7SPiotr Padlewski     const auto NewThreshold =
269ba72b95fSPiotr Padlewski         Threshold * GetBonusMultiplier(Edge.second.Hotness);
270d2869473SPiotr Padlewski 
271d9830eb7SPiotr Padlewski     auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
27201e32130SMehdi Amini     if (!CalleeSummary) {
27301e32130SMehdi Amini       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
2747e88d0daSMehdi Amini       continue;
2757e88d0daSMehdi Amini     }
2762d28f7aaSMehdi Amini     // "Resolve" the summary, traversing alias,
2772d28f7aaSMehdi Amini     const FunctionSummary *ResolvedCalleeSummary;
2786968ef77SMehdi Amini     if (isa<AliasSummary>(CalleeSummary)) {
2792d28f7aaSMehdi Amini       ResolvedCalleeSummary = cast<FunctionSummary>(
2802d28f7aaSMehdi Amini           &cast<AliasSummary>(CalleeSummary)->getAliasee());
2812c719cc1SMehdi Amini       assert(
2822c719cc1SMehdi Amini           GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
2832c719cc1SMehdi Amini           "Unexpected alias to a non-linkonceODR in import list");
2846968ef77SMehdi Amini     } else
2852d28f7aaSMehdi Amini       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
2862d28f7aaSMehdi Amini 
287d9830eb7SPiotr Padlewski     assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
28801e32130SMehdi Amini            "selectCallee() didn't honor the threshold");
28901e32130SMehdi Amini 
290d2869473SPiotr Padlewski     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
291d2869473SPiotr Padlewski       // Adjust the threshold for next level of imported functions.
292d2869473SPiotr Padlewski       // The threshold is different for hot callsites because we can then
293d2869473SPiotr Padlewski       // inline chains of hot calls.
294d2869473SPiotr Padlewski       if (IsHotCallsite)
295d2869473SPiotr Padlewski         return Threshold * ImportHotInstrFactor;
296d2869473SPiotr Padlewski       return Threshold * ImportInstrFactor;
297d2869473SPiotr Padlewski     };
298d2869473SPiotr Padlewski 
299d2869473SPiotr Padlewski     bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
3001b859a23STeresa Johnson     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
3011b859a23STeresa Johnson 
3021b859a23STeresa Johnson     auto ExportModulePath = ResolvedCalleeSummary->modulePath();
3031b859a23STeresa Johnson     auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
3041b859a23STeresa Johnson     /// Since the traversal of the call graph is DFS, we can revisit a function
3051b859a23STeresa Johnson     /// a second time with a higher threshold. In this case, it is added back to
3061b859a23STeresa Johnson     /// the worklist with the new threshold.
3071b859a23STeresa Johnson     if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
3081b859a23STeresa Johnson       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
3091b859a23STeresa Johnson                    << ProcessedThreshold << "\n");
3101b859a23STeresa Johnson       continue;
3111b859a23STeresa Johnson     }
31219f2aa78STeresa Johnson     bool PreviouslyImported = ProcessedThreshold != 0;
3131b859a23STeresa Johnson     // Mark this function as imported in this module, with the current Threshold
3141b859a23STeresa Johnson     ProcessedThreshold = AdjThreshold;
3151b859a23STeresa Johnson 
3161b859a23STeresa Johnson     // Make exports in the source module.
3171b859a23STeresa Johnson     if (ExportLists) {
3181b859a23STeresa Johnson       auto &ExportList = (*ExportLists)[ExportModulePath];
3191b859a23STeresa Johnson       ExportList.insert(GUID);
32019f2aa78STeresa Johnson       if (!PreviouslyImported) {
32119f2aa78STeresa Johnson         // This is the first time this function was exported from its source
32219f2aa78STeresa Johnson         // module, so mark all functions and globals it references as exported
3231b859a23STeresa Johnson         // to the outside if they are defined in the same source module.
324edddca22STeresa Johnson         // For efficiency, we unconditionally add all the referenced GUIDs
325edddca22STeresa Johnson         // to the ExportList for this module, and will prune out any not
326edddca22STeresa Johnson         // defined in the module later in a single pass.
3271b859a23STeresa Johnson         for (auto &Edge : ResolvedCalleeSummary->calls()) {
3281b859a23STeresa Johnson           auto CalleeGUID = Edge.first.getGUID();
329edddca22STeresa Johnson           ExportList.insert(CalleeGUID);
3301b859a23STeresa Johnson         }
3311b859a23STeresa Johnson         for (auto &Ref : ResolvedCalleeSummary->refs()) {
3321b859a23STeresa Johnson           auto GUID = Ref.getGUID();
333edddca22STeresa Johnson           ExportList.insert(GUID);
3341b859a23STeresa Johnson         }
3351b859a23STeresa Johnson       }
33619f2aa78STeresa Johnson     }
337d2869473SPiotr Padlewski 
33801e32130SMehdi Amini     // Insert the newly imported function to the worklist.
339475b51a7STeresa Johnson     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, GUID);
340d450da32STeresa Johnson   }
341d450da32STeresa Johnson }
342d450da32STeresa Johnson 
34301e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports
34401e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from
34501e32130SMehdi Amini /// another module (that may require promotion).
34601e32130SMehdi Amini static void ComputeImportForModule(
347c851d216STeresa Johnson     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
3489b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
349c86af334STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
35001e32130SMehdi Amini   // Worklist contains the list of function imported in this module, for which
35101e32130SMehdi Amini   // we will analyse the callees and may import further down the callgraph.
35201e32130SMehdi Amini   SmallVector<EdgeInfo, 128> Worklist;
35301e32130SMehdi Amini 
35401e32130SMehdi Amini   // Populate the worklist with the import for the functions in the current
35501e32130SMehdi Amini   // module
35628e457bcSTeresa Johnson   for (auto &GVSummary : DefinedGVSummaries) {
35728e457bcSTeresa Johnson     auto *Summary = GVSummary.second;
3582d28f7aaSMehdi Amini     if (auto *AS = dyn_cast<AliasSummary>(Summary))
3592d28f7aaSMehdi Amini       Summary = &AS->getAliasee();
3601aafabf7SMehdi Amini     auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
3611aafabf7SMehdi Amini     if (!FuncSummary)
3621aafabf7SMehdi Amini       // Skip import for global variables
3631aafabf7SMehdi Amini       continue;
36428e457bcSTeresa Johnson     DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
3652d28f7aaSMehdi Amini     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
3669b490f10SMehdi Amini                              DefinedGVSummaries, Worklist, ImportList,
36701e32130SMehdi Amini                              ExportLists);
36801e32130SMehdi Amini   }
36901e32130SMehdi Amini 
370d2869473SPiotr Padlewski   // Process the newly imported functions and add callees to the worklist.
37142418abaSMehdi Amini   while (!Worklist.empty()) {
37201e32130SMehdi Amini     auto FuncInfo = Worklist.pop_back_val();
373475b51a7STeresa Johnson     auto *Summary = std::get<0>(FuncInfo);
374475b51a7STeresa Johnson     auto Threshold = std::get<1>(FuncInfo);
375475b51a7STeresa Johnson     auto GUID = std::get<2>(FuncInfo);
376475b51a7STeresa Johnson 
377475b51a7STeresa Johnson     // Check if we later added this summary with a higher threshold.
378475b51a7STeresa Johnson     // If so, skip this entry.
379475b51a7STeresa Johnson     auto ExportModulePath = Summary->modulePath();
380475b51a7STeresa Johnson     auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
381475b51a7STeresa Johnson     if (LatestProcessedThreshold > Threshold)
382475b51a7STeresa Johnson       continue;
38342418abaSMehdi Amini 
3841aafabf7SMehdi Amini     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
3859b490f10SMehdi Amini                              Worklist, ImportList, ExportLists);
386c8c55170SMehdi Amini   }
38742418abaSMehdi Amini }
388ffe2e4aaSMehdi Amini 
38901e32130SMehdi Amini } // anonymous namespace
39001e32130SMehdi Amini 
391c86af334STeresa Johnson /// Compute all the import and export for every module using the Index.
39201e32130SMehdi Amini void llvm::ComputeCrossModuleImport(
39301e32130SMehdi Amini     const ModuleSummaryIndex &Index,
394c851d216STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
39501e32130SMehdi Amini     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
39601e32130SMehdi Amini     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
39701e32130SMehdi Amini   // For each module that has function defined, compute the import/export lists.
3981aafabf7SMehdi Amini   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
3999b490f10SMehdi Amini     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
4001aafabf7SMehdi Amini     DEBUG(dbgs() << "Computing import for Module '"
4011aafabf7SMehdi Amini                  << DefinedGVSummaries.first() << "'\n");
4029b490f10SMehdi Amini     ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
403c86af334STeresa Johnson                            &ExportLists);
40401e32130SMehdi Amini   }
40501e32130SMehdi Amini 
406edddca22STeresa Johnson   // When computing imports we added all GUIDs referenced by anything
407edddca22STeresa Johnson   // imported from the module to its ExportList. Now we prune each ExportList
408edddca22STeresa Johnson   // of any not defined in that module. This is more efficient than checking
409edddca22STeresa Johnson   // while computing imports because some of the summary lists may be long
410edddca22STeresa Johnson   // due to linkonce (comdat) copies.
411edddca22STeresa Johnson   for (auto &ELI : ExportLists) {
412edddca22STeresa Johnson     const auto &DefinedGVSummaries =
413edddca22STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ELI.first());
414edddca22STeresa Johnson     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
415edddca22STeresa Johnson       if (!DefinedGVSummaries.count(*EI))
416edddca22STeresa Johnson         EI = ELI.second.erase(EI);
417edddca22STeresa Johnson       else
418edddca22STeresa Johnson         ++EI;
419edddca22STeresa Johnson     }
420edddca22STeresa Johnson   }
421edddca22STeresa Johnson 
42201e32130SMehdi Amini #ifndef NDEBUG
42301e32130SMehdi Amini   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
42401e32130SMehdi Amini                << " modules:\n");
42501e32130SMehdi Amini   for (auto &ModuleImports : ImportLists) {
42601e32130SMehdi Amini     auto ModName = ModuleImports.first();
42701e32130SMehdi Amini     auto &Exports = ExportLists[ModName];
42801e32130SMehdi Amini     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
42901e32130SMehdi Amini                  << " functions. Imports from " << ModuleImports.second.size()
43001e32130SMehdi Amini                  << " modules.\n");
43101e32130SMehdi Amini     for (auto &Src : ModuleImports.second) {
43201e32130SMehdi Amini       auto SrcModName = Src.first();
43301e32130SMehdi Amini       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
43401e32130SMehdi Amini                    << SrcModName << "\n");
43501e32130SMehdi Amini     }
43601e32130SMehdi Amini   }
43701e32130SMehdi Amini #endif
43801e32130SMehdi Amini }
43901e32130SMehdi Amini 
440c86af334STeresa Johnson /// Compute all the imports for the given module in the Index.
441c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule(
442c86af334STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
443c86af334STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
444c86af334STeresa Johnson 
445c86af334STeresa Johnson   // Collect the list of functions this module defines.
446c86af334STeresa Johnson   // GUID -> Summary
447c851d216STeresa Johnson   GVSummaryMapTy FunctionSummaryMap;
44828e457bcSTeresa Johnson   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
449c86af334STeresa Johnson 
450c86af334STeresa Johnson   // Compute the import list for this module.
451c86af334STeresa Johnson   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
45228e457bcSTeresa Johnson   ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
453c86af334STeresa Johnson 
454c86af334STeresa Johnson #ifndef NDEBUG
455c86af334STeresa Johnson   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
456c86af334STeresa Johnson                << ImportList.size() << " modules.\n");
457c86af334STeresa Johnson   for (auto &Src : ImportList) {
458c86af334STeresa Johnson     auto SrcModName = Src.first();
459c86af334STeresa Johnson     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
460c86af334STeresa Johnson                  << SrcModName << "\n");
461c86af334STeresa Johnson   }
462c86af334STeresa Johnson #endif
463c86af334STeresa Johnson }
464c86af334STeresa Johnson 
46584174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of
46684174c37STeresa Johnson /// \p ModulePath.
46784174c37STeresa Johnson void llvm::gatherImportedSummariesForModule(
46884174c37STeresa Johnson     StringRef ModulePath,
46984174c37STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
470cdbcbf74SMehdi Amini     const FunctionImporter::ImportMapTy &ImportList,
47184174c37STeresa Johnson     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
47284174c37STeresa Johnson   // Include all summaries from the importing module.
47384174c37STeresa Johnson   ModuleToSummariesForIndex[ModulePath] =
47484174c37STeresa Johnson       ModuleToDefinedGVSummaries.lookup(ModulePath);
47584174c37STeresa Johnson   // Include summaries for imports.
47688c491ddSMehdi Amini   for (auto &ILI : ImportList) {
47784174c37STeresa Johnson     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
47884174c37STeresa Johnson     const auto &DefinedGVSummaries =
47984174c37STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ILI.first());
48084174c37STeresa Johnson     for (auto &GI : ILI.second) {
48184174c37STeresa Johnson       const auto &DS = DefinedGVSummaries.find(GI.first);
48284174c37STeresa Johnson       assert(DS != DefinedGVSummaries.end() &&
48384174c37STeresa Johnson              "Expected a defined summary for imported global value");
48484174c37STeresa Johnson       SummariesForIndex[GI.first] = DS->second;
48584174c37STeresa Johnson     }
48684174c37STeresa Johnson   }
48784174c37STeresa Johnson }
48884174c37STeresa Johnson 
4898570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename.
490cdbcbf74SMehdi Amini std::error_code
491cdbcbf74SMehdi Amini llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
492cdbcbf74SMehdi Amini                        const FunctionImporter::ImportMapTy &ModuleImports) {
4938570fe47STeresa Johnson   std::error_code EC;
4948570fe47STeresa Johnson   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
4958570fe47STeresa Johnson   if (EC)
4968570fe47STeresa Johnson     return EC;
497cdbcbf74SMehdi Amini   for (auto &ILI : ModuleImports)
4988570fe47STeresa Johnson     ImportsOS << ILI.first() << "\n";
4998570fe47STeresa Johnson   return std::error_code();
5008570fe47STeresa Johnson }
5018570fe47STeresa Johnson 
50204c9a2d6STeresa Johnson /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
50304c9a2d6STeresa Johnson void llvm::thinLTOResolveWeakForLinkerModule(
50404c9a2d6STeresa Johnson     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
50504c9a2d6STeresa Johnson   auto updateLinkage = [&](GlobalValue &GV) {
50604c9a2d6STeresa Johnson     if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
50704c9a2d6STeresa Johnson       return;
50804c9a2d6STeresa Johnson     // See if the global summary analysis computed a new resolved linkage.
50904c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
51004c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end())
51104c9a2d6STeresa Johnson       return;
51204c9a2d6STeresa Johnson     auto NewLinkage = GS->second->linkage();
51304c9a2d6STeresa Johnson     if (NewLinkage == GV.getLinkage())
51404c9a2d6STeresa Johnson       return;
51504c9a2d6STeresa Johnson     DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
51604c9a2d6STeresa Johnson                  << GV.getLinkage() << " to " << NewLinkage << "\n");
51704c9a2d6STeresa Johnson     GV.setLinkage(NewLinkage);
5186107a419STeresa Johnson     // Remove functions converted to available_externally from comdats,
5196107a419STeresa Johnson     // as this is a declaration for the linker, and will be dropped eventually.
5206107a419STeresa Johnson     // It is illegal for comdats to contain declarations.
5216107a419STeresa Johnson     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
5226107a419STeresa Johnson     if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
5236107a419STeresa Johnson       assert(GO->hasAvailableExternallyLinkage() &&
5246107a419STeresa Johnson              "Expected comdat on definition (possibly available external)");
5256107a419STeresa Johnson       GO->setComdat(nullptr);
5266107a419STeresa Johnson     }
52704c9a2d6STeresa Johnson   };
52804c9a2d6STeresa Johnson 
52904c9a2d6STeresa Johnson   // Process functions and global now
53004c9a2d6STeresa Johnson   for (auto &GV : TheModule)
53104c9a2d6STeresa Johnson     updateLinkage(GV);
53204c9a2d6STeresa Johnson   for (auto &GV : TheModule.globals())
53304c9a2d6STeresa Johnson     updateLinkage(GV);
53404c9a2d6STeresa Johnson   for (auto &GV : TheModule.aliases())
53504c9a2d6STeresa Johnson     updateLinkage(GV);
53604c9a2d6STeresa Johnson }
53704c9a2d6STeresa Johnson 
53804c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis.
53904c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule,
54004c9a2d6STeresa Johnson                                     const GVSummaryMapTy &DefinedGlobals) {
54104c9a2d6STeresa Johnson   // Parse inline ASM and collect the list of symbols that are not defined in
54204c9a2d6STeresa Johnson   // the current module.
54304c9a2d6STeresa Johnson   StringSet<> AsmUndefinedRefs;
544863cbfbeSPeter Collingbourne   ModuleSymbolTable::CollectAsmSymbols(
54504c9a2d6STeresa Johnson       Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
54604c9a2d6STeresa Johnson       [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
54704c9a2d6STeresa Johnson         if (Flags & object::BasicSymbolRef::SF_Undefined)
54804c9a2d6STeresa Johnson           AsmUndefinedRefs.insert(Name);
54904c9a2d6STeresa Johnson       });
55004c9a2d6STeresa Johnson 
55104c9a2d6STeresa Johnson   // Declare a callback for the internalize pass that will ask for every
55204c9a2d6STeresa Johnson   // candidate GlobalValue if it can be internalized or not.
55304c9a2d6STeresa Johnson   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
55404c9a2d6STeresa Johnson     // Can't be internalized if referenced in inline asm.
55504c9a2d6STeresa Johnson     if (AsmUndefinedRefs.count(GV.getName()))
55604c9a2d6STeresa Johnson       return true;
55704c9a2d6STeresa Johnson 
55804c9a2d6STeresa Johnson     // Lookup the linkage recorded in the summaries during global analysis.
55904c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
56004c9a2d6STeresa Johnson     GlobalValue::LinkageTypes Linkage;
56104c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end()) {
56204c9a2d6STeresa Johnson       // Must have been promoted (possibly conservatively). Find original
56304c9a2d6STeresa Johnson       // name so that we can access the correct summary and see if it can
56404c9a2d6STeresa Johnson       // be internalized again.
56504c9a2d6STeresa Johnson       // FIXME: Eventually we should control promotion instead of promoting
56604c9a2d6STeresa Johnson       // and internalizing again.
56704c9a2d6STeresa Johnson       StringRef OrigName =
56804c9a2d6STeresa Johnson           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
56904c9a2d6STeresa Johnson       std::string OrigId = GlobalValue::getGlobalIdentifier(
57004c9a2d6STeresa Johnson           OrigName, GlobalValue::InternalLinkage,
57104c9a2d6STeresa Johnson           TheModule.getSourceFileName());
57204c9a2d6STeresa Johnson       const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
5737ab1f692STeresa Johnson       if (GS == DefinedGlobals.end()) {
5747ab1f692STeresa Johnson         // Also check the original non-promoted non-globalized name. In some
5757ab1f692STeresa Johnson         // cases a preempted weak value is linked in as a local copy because
5767ab1f692STeresa Johnson         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
5777ab1f692STeresa Johnson         // In that case, since it was originally not a local value, it was
5787ab1f692STeresa Johnson         // recorded in the index using the original name.
5797ab1f692STeresa Johnson         // FIXME: This may not be needed once PR27866 is fixed.
5807ab1f692STeresa Johnson         const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
58104c9a2d6STeresa Johnson         assert(GS != DefinedGlobals.end());
58204c9a2d6STeresa Johnson         Linkage = GS->second->linkage();
5837ab1f692STeresa Johnson       } else {
5847ab1f692STeresa Johnson         Linkage = GS->second->linkage();
5857ab1f692STeresa Johnson       }
58604c9a2d6STeresa Johnson     } else
58704c9a2d6STeresa Johnson       Linkage = GS->second->linkage();
58804c9a2d6STeresa Johnson     return !GlobalValue::isLocalLinkage(Linkage);
58904c9a2d6STeresa Johnson   };
59004c9a2d6STeresa Johnson 
59104c9a2d6STeresa Johnson   // FIXME: See if we can just internalize directly here via linkage changes
59204c9a2d6STeresa Johnson   // based on the index, rather than invoking internalizeModule.
59304c9a2d6STeresa Johnson   llvm::internalizeModule(TheModule, MustPreserveGV);
59404c9a2d6STeresa Johnson }
59504c9a2d6STeresa Johnson 
596c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries
597c8c55170SMehdi Amini // index.
598c8c55170SMehdi Amini //
5997f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions(
600bda3c97cSMehdi Amini     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
601bda3c97cSMehdi Amini     bool ForceImportReferencedDiscardableSymbols) {
6025411d051SMehdi Amini   DEBUG(dbgs() << "Starting import for Module "
603311fef6eSMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
604c8c55170SMehdi Amini   unsigned ImportedCount = 0;
605c8c55170SMehdi Amini 
606c8c55170SMehdi Amini   // Linker that will be used for importing function
6079d2bfc48SRafael Espindola   Linker TheLinker(DestModule);
6087e88d0daSMehdi Amini   // Do the actual import of functions now, one Module at a time
60901e32130SMehdi Amini   std::set<StringRef> ModuleNameOrderedList;
61001e32130SMehdi Amini   for (auto &FunctionsToImportPerModule : ImportList) {
61101e32130SMehdi Amini     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
61201e32130SMehdi Amini   }
61301e32130SMehdi Amini   for (auto &Name : ModuleNameOrderedList) {
6147e88d0daSMehdi Amini     // Get the module for the import
61501e32130SMehdi Amini     const auto &FunctionsToImportPerModule = ImportList.find(Name);
61601e32130SMehdi Amini     assert(FunctionsToImportPerModule != ImportList.end());
617d9445c49SPeter Collingbourne     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
618d9445c49SPeter Collingbourne     if (!SrcModuleOrErr)
619d9445c49SPeter Collingbourne       return SrcModuleOrErr.takeError();
620d9445c49SPeter Collingbourne     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
6217e88d0daSMehdi Amini     assert(&DestModule.getContext() == &SrcModule->getContext() &&
6227e88d0daSMehdi Amini            "Context mismatch");
6237e88d0daSMehdi Amini 
6246cba37ceSTeresa Johnson     // If modules were created with lazy metadata loading, materialize it
6256cba37ceSTeresa Johnson     // now, before linking it (otherwise this will be a noop).
6267f00d0a1SPeter Collingbourne     if (Error Err = SrcModule->materializeMetadata())
6277f00d0a1SPeter Collingbourne       return std::move(Err);
6286cba37ceSTeresa Johnson     UpgradeDebugInfo(*SrcModule);
629e5a61917STeresa Johnson 
63001e32130SMehdi Amini     auto &ImportGUIDs = FunctionsToImportPerModule->second;
63101e32130SMehdi Amini     // Find the globals to import
63201e32130SMehdi Amini     DenseSet<const GlobalValue *> GlobalsToImport;
6331f685e01SPiotr Padlewski     for (Function &F : *SrcModule) {
6341f685e01SPiotr Padlewski       if (!F.hasName())
6350beb858eSTeresa Johnson         continue;
6361f685e01SPiotr Padlewski       auto GUID = F.getGUID();
6370beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
638aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
6391f685e01SPiotr Padlewski                    << " " << F.getName() << " from "
640aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6410beb858eSTeresa Johnson       if (Import) {
6427f00d0a1SPeter Collingbourne         if (Error Err = F.materialize())
6437f00d0a1SPeter Collingbourne           return std::move(Err);
6443b776128SPiotr Padlewski         if (EnableImportMetadata) {
6456deaa6afSPiotr Padlewski           // Add 'thinlto_src_module' metadata for statistics and debugging.
6463b776128SPiotr Padlewski           F.setMetadata(
6473b776128SPiotr Padlewski               "thinlto_src_module",
6483b776128SPiotr Padlewski               llvm::MDNode::get(
6496deaa6afSPiotr Padlewski                   DestModule.getContext(),
6503b776128SPiotr Padlewski                   {llvm::MDString::get(DestModule.getContext(),
6516deaa6afSPiotr Padlewski                                        SrcModule->getSourceFileName())}));
6523b776128SPiotr Padlewski         }
6531f685e01SPiotr Padlewski         GlobalsToImport.insert(&F);
65401e32130SMehdi Amini       }
65501e32130SMehdi Amini     }
6561f685e01SPiotr Padlewski     for (GlobalVariable &GV : SrcModule->globals()) {
6572d28f7aaSMehdi Amini       if (!GV.hasName())
6582d28f7aaSMehdi Amini         continue;
6592d28f7aaSMehdi Amini       auto GUID = GV.getGUID();
6602d28f7aaSMehdi Amini       auto Import = ImportGUIDs.count(GUID);
661aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
662aeb1e59bSMehdi Amini                    << " " << GV.getName() << " from "
663aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6642d28f7aaSMehdi Amini       if (Import) {
6657f00d0a1SPeter Collingbourne         if (Error Err = GV.materialize())
6667f00d0a1SPeter Collingbourne           return std::move(Err);
6672d28f7aaSMehdi Amini         GlobalsToImport.insert(&GV);
6682d28f7aaSMehdi Amini       }
6692d28f7aaSMehdi Amini     }
6701f685e01SPiotr Padlewski     for (GlobalAlias &GA : SrcModule->aliases()) {
6711f685e01SPiotr Padlewski       if (!GA.hasName())
67201e32130SMehdi Amini         continue;
6731f685e01SPiotr Padlewski       auto GUID = GA.getGUID();
6740beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
675aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
6761f685e01SPiotr Padlewski                    << " " << GA.getName() << " from "
677aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6780beb858eSTeresa Johnson       if (Import) {
67901e32130SMehdi Amini         // Alias can't point to "available_externally". However when we import
6809aae395fSTeresa Johnson         // linkOnceODR the linkage does not change. So we import the alias
6816968ef77SMehdi Amini         // and aliasee only in this case. This has been handled by
6826968ef77SMehdi Amini         // computeImportForFunction()
6831f685e01SPiotr Padlewski         GlobalObject *GO = GA.getBaseObject();
6846968ef77SMehdi Amini         assert(GO->hasLinkOnceODRLinkage() &&
6856968ef77SMehdi Amini                "Unexpected alias to a non-linkonceODR in import list");
6862d28f7aaSMehdi Amini #ifndef NDEBUG
6872d28f7aaSMehdi Amini         if (!GlobalsToImport.count(GO))
6882d28f7aaSMehdi Amini           DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
6892d28f7aaSMehdi Amini                        << " " << GO->getName() << " from "
6902d28f7aaSMehdi Amini                        << SrcModule->getSourceFileName() << "\n");
6912d28f7aaSMehdi Amini #endif
6927f00d0a1SPeter Collingbourne         if (Error Err = GO->materialize())
6937f00d0a1SPeter Collingbourne           return std::move(Err);
69401e32130SMehdi Amini         GlobalsToImport.insert(GO);
6957f00d0a1SPeter Collingbourne         if (Error Err = GA.materialize())
6967f00d0a1SPeter Collingbourne           return std::move(Err);
6971f685e01SPiotr Padlewski         GlobalsToImport.insert(&GA);
69801e32130SMehdi Amini       }
69901e32130SMehdi Amini     }
70001e32130SMehdi Amini 
7019a9077fdSMehdi Amini #ifndef NDEBUG
70296cdc493SMehdi Amini     // Note: this can't be done after `renameModuleForThinLTO` as it leaves the
70396cdc493SMehdi Amini     // module in a state that does not pass the verifier (for example aliases
70496cdc493SMehdi Amini     // pointing to available_externally functions).
70596cdc493SMehdi Amini     if (verifyModule(*SrcModule, &errs()))
70696cdc493SMehdi Amini       report_fatal_error("Invalid lazy-loaded source module for importing");
70796cdc493SMehdi Amini #endif
70896cdc493SMehdi Amini 
7097e88d0daSMehdi Amini     // Link in the specified functions.
71001e32130SMehdi Amini     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
7118d05185aSMehdi Amini       return true;
7128d05185aSMehdi Amini 
713d29478f7STeresa Johnson     if (PrintImports) {
714d29478f7STeresa Johnson       for (const auto *GV : GlobalsToImport)
715d29478f7STeresa Johnson         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
716d29478f7STeresa Johnson                << " from " << SrcModule->getSourceFileName() << "\n";
717d29478f7STeresa Johnson     }
718d29478f7STeresa Johnson 
719bda3c97cSMehdi Amini     // Instruct the linker that the client will take care of linkonce resolution
720bda3c97cSMehdi Amini     unsigned Flags = Linker::Flags::None;
721bda3c97cSMehdi Amini     if (!ForceImportReferencedDiscardableSymbols)
722bda3c97cSMehdi Amini       Flags |= Linker::Flags::DontForceLinkLinkonceODR;
723bda3c97cSMehdi Amini 
724bda3c97cSMehdi Amini     if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
7257e88d0daSMehdi Amini       report_fatal_error("Function Import: link error");
7267e88d0daSMehdi Amini 
72701e32130SMehdi Amini     ImportedCount += GlobalsToImport.size();
7287e88d0daSMehdi Amini   }
729e5a61917STeresa Johnson 
730d29478f7STeresa Johnson   NumImported += ImportedCount;
731d29478f7STeresa Johnson 
7327e88d0daSMehdi Amini   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
733c8c55170SMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
734c8c55170SMehdi Amini   return ImportedCount;
73542418abaSMehdi Amini }
73642418abaSMehdi Amini 
73742418abaSMehdi Amini /// Summary file to use for function importing when using -function-import from
73842418abaSMehdi Amini /// the command line.
73942418abaSMehdi Amini static cl::opt<std::string>
74042418abaSMehdi Amini     SummaryFile("summary-file",
74142418abaSMehdi Amini                 cl::desc("The summary file to use for function importing."));
74242418abaSMehdi Amini 
743598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) {
744598bd2a2SPeter Collingbourne   if (SummaryFile.empty())
745598bd2a2SPeter Collingbourne     report_fatal_error("error: -function-import requires -summary-file\n");
7466de481a3SPeter Collingbourne   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
7476de481a3SPeter Collingbourne       getModuleSummaryIndexForFile(SummaryFile);
7486de481a3SPeter Collingbourne   if (!IndexPtrOrErr) {
7496de481a3SPeter Collingbourne     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
7506de481a3SPeter Collingbourne                           "Error loading file '" + SummaryFile + "': ");
75142418abaSMehdi Amini     return false;
75242418abaSMehdi Amini   }
753598bd2a2SPeter Collingbourne   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
75442418abaSMehdi Amini 
755c86af334STeresa Johnson   // First step is collecting the import list.
756c86af334STeresa Johnson   FunctionImporter::ImportMapTy ImportList;
757c86af334STeresa Johnson   ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
758c86af334STeresa Johnson                                     ImportList);
75901e32130SMehdi Amini 
7604fef68cbSTeresa Johnson   // Conservatively mark all internal values as promoted. This interface is
7614fef68cbSTeresa Johnson   // only used when doing importing via the function importing pass. The pass
7624fef68cbSTeresa Johnson   // is only enabled when testing importing via the 'opt' tool, which does
7634fef68cbSTeresa Johnson   // not do the ThinLink that would normally determine what values to promote.
7644fef68cbSTeresa Johnson   for (auto &I : *Index) {
7654fef68cbSTeresa Johnson     for (auto &S : I.second) {
7664fef68cbSTeresa Johnson       if (GlobalValue::isLocalLinkage(S->linkage()))
7674fef68cbSTeresa Johnson         S->setLinkage(GlobalValue::ExternalLinkage);
7684fef68cbSTeresa Johnson     }
7694fef68cbSTeresa Johnson   }
7704fef68cbSTeresa Johnson 
77101e32130SMehdi Amini   // Next we need to promote to global scope and rename any local values that
7721b00f2d9STeresa Johnson   // are potentially exported to other modules.
77301e32130SMehdi Amini   if (renameModuleForThinLTO(M, *Index, nullptr)) {
7741b00f2d9STeresa Johnson     errs() << "Error renaming module\n";
7751b00f2d9STeresa Johnson     return false;
7761b00f2d9STeresa Johnson   }
7771b00f2d9STeresa Johnson 
77842418abaSMehdi Amini   // Perform the import now.
779d16c8065SMehdi Amini   auto ModuleLoader = [&M](StringRef Identifier) {
780d16c8065SMehdi Amini     return loadFile(Identifier, M.getContext());
781d16c8065SMehdi Amini   };
7829d2bfc48SRafael Espindola   FunctionImporter Importer(*Index, ModuleLoader);
7837f00d0a1SPeter Collingbourne   Expected<bool> Result = Importer.importFunctions(
7847f00d0a1SPeter Collingbourne       M, ImportList, !DontForceImportReferencedDiscardableSymbols);
7857f00d0a1SPeter Collingbourne 
7867f00d0a1SPeter Collingbourne   // FIXME: Probably need to propagate Errors through the pass manager.
7877f00d0a1SPeter Collingbourne   if (!Result) {
7887f00d0a1SPeter Collingbourne     logAllUnhandledErrors(Result.takeError(), errs(),
7897f00d0a1SPeter Collingbourne                           "Error importing module: ");
7907f00d0a1SPeter Collingbourne     return false;
7917f00d0a1SPeter Collingbourne   }
7927f00d0a1SPeter Collingbourne 
7937f00d0a1SPeter Collingbourne   return *Result;
79421241571STeresa Johnson }
79521241571STeresa Johnson 
79621241571STeresa Johnson namespace {
79721241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file.
79821241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass {
79921241571STeresa Johnson public:
80021241571STeresa Johnson   /// Pass identification, replacement for typeid
80121241571STeresa Johnson   static char ID;
80221241571STeresa Johnson 
80321241571STeresa Johnson   /// Specify pass name for debug output
804117296c0SMehdi Amini   StringRef getPassName() const override { return "Function Importing"; }
80521241571STeresa Johnson 
806598bd2a2SPeter Collingbourne   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
80721241571STeresa Johnson 
80821241571STeresa Johnson   bool runOnModule(Module &M) override {
80921241571STeresa Johnson     if (skipModule(M))
81021241571STeresa Johnson       return false;
81121241571STeresa Johnson 
812598bd2a2SPeter Collingbourne     return doImportingForModule(M);
81342418abaSMehdi Amini   }
81442418abaSMehdi Amini };
815fe2b5415SBenjamin Kramer } // anonymous namespace
81642418abaSMehdi Amini 
81721241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M,
818fd03ac6aSSean Silva                                           ModuleAnalysisManager &AM) {
819598bd2a2SPeter Collingbourne   if (!doImportingForModule(M))
82021241571STeresa Johnson     return PreservedAnalyses::all();
82121241571STeresa Johnson 
82221241571STeresa Johnson   return PreservedAnalyses::none();
82321241571STeresa Johnson }
82421241571STeresa Johnson 
82521241571STeresa Johnson char FunctionImportLegacyPass::ID = 0;
82621241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
82742418abaSMehdi Amini                 "Summary Based Function Import", false, false)
82842418abaSMehdi Amini 
82942418abaSMehdi Amini namespace llvm {
830598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() {
831598bd2a2SPeter Collingbourne   return new FunctionImportLegacyPass();
8325fcbdb71STeresa Johnson }
83342418abaSMehdi Amini }
834