142418abaSMehdi Amini //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===// 242418abaSMehdi Amini // 342418abaSMehdi Amini // The LLVM Compiler Infrastructure 442418abaSMehdi Amini // 542418abaSMehdi Amini // This file is distributed under the University of Illinois Open Source 642418abaSMehdi Amini // License. See LICENSE.TXT for details. 742418abaSMehdi Amini // 842418abaSMehdi Amini //===----------------------------------------------------------------------===// 942418abaSMehdi Amini // 1042418abaSMehdi Amini // This file implements Function import based on summaries. 1142418abaSMehdi Amini // 1242418abaSMehdi Amini //===----------------------------------------------------------------------===// 1342418abaSMehdi Amini 1442418abaSMehdi Amini #include "llvm/Transforms/IPO/FunctionImport.h" 1542418abaSMehdi Amini 1601e32130SMehdi Amini #include "llvm/ADT/SmallVector.h" 17d29478f7STeresa Johnson #include "llvm/ADT/Statistic.h" 1842418abaSMehdi Amini #include "llvm/ADT/StringSet.h" 1904c9a2d6STeresa Johnson #include "llvm/ADT/Triple.h" 2042418abaSMehdi Amini #include "llvm/IR/AutoUpgrade.h" 2142418abaSMehdi Amini #include "llvm/IR/DiagnosticPrinter.h" 2242418abaSMehdi Amini #include "llvm/IR/IntrinsicInst.h" 2342418abaSMehdi Amini #include "llvm/IR/Module.h" 2442418abaSMehdi Amini #include "llvm/IRReader/IRReader.h" 2542418abaSMehdi Amini #include "llvm/Linker/Linker.h" 2604c9a2d6STeresa Johnson #include "llvm/Object/IRObjectFile.h" 2726ab5772STeresa Johnson #include "llvm/Object/ModuleSummaryIndexObjectFile.h" 2842418abaSMehdi Amini #include "llvm/Support/CommandLine.h" 2942418abaSMehdi Amini #include "llvm/Support/Debug.h" 3042418abaSMehdi Amini #include "llvm/Support/SourceMgr.h" 3104c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h" 32488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h" 337e88d0daSMehdi Amini 3401e32130SMehdi Amini #define DEBUG_TYPE "function-import" 357e88d0daSMehdi Amini 3642418abaSMehdi Amini using namespace llvm; 3742418abaSMehdi Amini 38d29478f7STeresa Johnson STATISTIC(NumImported, "Number of functions imported"); 39d29478f7STeresa Johnson 4039303619STeresa Johnson /// Limit on instruction count of imported functions. 4139303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit( 4239303619STeresa Johnson "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), 4339303619STeresa Johnson cl::desc("Only import functions with less than N instructions")); 4439303619STeresa Johnson 4540641748SMehdi Amini static cl::opt<float> 4640641748SMehdi Amini ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), 4740641748SMehdi Amini cl::Hidden, cl::value_desc("x"), 4840641748SMehdi Amini cl::desc("As we import functions, multiply the " 4940641748SMehdi Amini "`import-instr-limit` threshold by this factor " 5040641748SMehdi Amini "before processing newly imported functions")); 51ba72b95fSPiotr Padlewski 52d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor( 53d2869473SPiotr Padlewski "import-hot-evolution-factor", cl::init(1.0), cl::Hidden, 54d2869473SPiotr Padlewski cl::value_desc("x"), 55d2869473SPiotr Padlewski cl::desc("As we import functions called from hot callsite, multiply the " 56d2869473SPiotr Padlewski "`import-instr-limit` threshold by this factor " 57d2869473SPiotr Padlewski "before processing newly imported functions")); 58d2869473SPiotr Padlewski 59d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier( 60d9830eb7SPiotr Padlewski "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"), 61ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for hot callsites")); 62ba72b95fSPiotr Padlewski 63ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up. 64ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier( 65ba72b95fSPiotr Padlewski "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), 66ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for cold callsites")); 6740641748SMehdi Amini 68d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden, 69d29478f7STeresa Johnson cl::desc("Print imported functions")); 70d29478f7STeresa Johnson 71bda3c97cSMehdi Amini // Temporary allows the function import pass to disable always linking 72bda3c97cSMehdi Amini // referenced discardable symbols. 73bda3c97cSMehdi Amini static cl::opt<bool> 74bda3c97cSMehdi Amini DontForceImportReferencedDiscardableSymbols("disable-force-link-odr", 75bda3c97cSMehdi Amini cl::init(false), cl::Hidden); 76bda3c97cSMehdi Amini 773b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata( 783b776128SPiotr Padlewski "enable-import-metadata", cl::init( 793b776128SPiotr Padlewski #if !defined(NDEBUG) 803b776128SPiotr Padlewski true /*Enabled with asserts.*/ 813b776128SPiotr Padlewski #else 823b776128SPiotr Padlewski false 833b776128SPiotr Padlewski #endif 843b776128SPiotr Padlewski ), 853b776128SPiotr Padlewski cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'")); 863b776128SPiotr Padlewski 8742418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context. 8842418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName, 8942418abaSMehdi Amini LLVMContext &Context) { 9042418abaSMehdi Amini SMDiagnostic Err; 9142418abaSMehdi Amini DEBUG(dbgs() << "Loading '" << FileName << "'\n"); 926cba37ceSTeresa Johnson // Metadata isn't loaded until functions are imported, to minimize 936cba37ceSTeresa Johnson // the memory overhead. 94a1080ee6STeresa Johnson std::unique_ptr<Module> Result = 95a1080ee6STeresa Johnson getLazyIRFileModule(FileName, Err, Context, 96a1080ee6STeresa Johnson /* ShouldLazyLoadMetadata = */ true); 9742418abaSMehdi Amini if (!Result) { 9842418abaSMehdi Amini Err.print("function-import", errs()); 99d7ad221cSMehdi Amini report_fatal_error("Abort"); 10042418abaSMehdi Amini } 10142418abaSMehdi Amini 10242418abaSMehdi Amini return Result; 10342418abaSMehdi Amini } 10442418abaSMehdi Amini 1057e88d0daSMehdi Amini namespace { 10640641748SMehdi Amini 107b4e1e829SMehdi Amini // Return true if the Summary describes a GlobalValue that can be externally 108b4e1e829SMehdi Amini // referenced, i.e. it does not need renaming (linkage is not local) or renaming 109b4e1e829SMehdi Amini // is possible (does not have a section for instance). 110b4e1e829SMehdi Amini static bool canBeExternallyReferenced(const GlobalValueSummary &Summary) { 111b4e1e829SMehdi Amini if (!Summary.needsRenaming()) 112b4e1e829SMehdi Amini return true; 113b4e1e829SMehdi Amini 11458fbc916STeresa Johnson if (Summary.noRename()) 11558fbc916STeresa Johnson // Can't externally reference a global that needs renaming if has a section 11658fbc916STeresa Johnson // or is referenced from inline assembly, for example. 117b4e1e829SMehdi Amini return false; 118b4e1e829SMehdi Amini 119b4e1e829SMehdi Amini return true; 120b4e1e829SMehdi Amini } 121b4e1e829SMehdi Amini 122b4e1e829SMehdi Amini // Return true if \p GUID describes a GlobalValue that can be externally 123b4e1e829SMehdi Amini // referenced, i.e. it does not need renaming (linkage is not local) or 124b4e1e829SMehdi Amini // renaming is possible (does not have a section for instance). 125b4e1e829SMehdi Amini static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index, 126b4e1e829SMehdi Amini GlobalValue::GUID GUID) { 127b4e1e829SMehdi Amini auto Summaries = Index.findGlobalValueSummaryList(GUID); 128b4e1e829SMehdi Amini if (Summaries == Index.end()) 129b4e1e829SMehdi Amini return true; 130b4e1e829SMehdi Amini if (Summaries->second.size() != 1) 131b4e1e829SMehdi Amini // If there are multiple globals with this GUID, then we know it is 132b4e1e829SMehdi Amini // not a local symbol, and it is necessarily externally referenced. 133b4e1e829SMehdi Amini return true; 134b4e1e829SMehdi Amini 135b4e1e829SMehdi Amini // We don't need to check for the module path, because if it can't be 136b4e1e829SMehdi Amini // externally referenced and we call it, it is necessarilly in the same 137b4e1e829SMehdi Amini // module 138b4e1e829SMehdi Amini return canBeExternallyReferenced(**Summaries->second.begin()); 139b4e1e829SMehdi Amini } 140b4e1e829SMehdi Amini 141b4e1e829SMehdi Amini // Return true if the global described by \p Summary can be imported in another 142b4e1e829SMehdi Amini // module. 143b4e1e829SMehdi Amini static bool eligibleForImport(const ModuleSummaryIndex &Index, 144b4e1e829SMehdi Amini const GlobalValueSummary &Summary) { 145b4e1e829SMehdi Amini if (!canBeExternallyReferenced(Summary)) 146b4e1e829SMehdi Amini // Can't import a global that needs renaming if has a section for instance. 147b4e1e829SMehdi Amini // FIXME: we may be able to import it by copying it without promotion. 148b4e1e829SMehdi Amini return false; 149b4e1e829SMehdi Amini 150332b3b22SPiotr Padlewski // Don't import functions that are not viable to inline. 151332b3b22SPiotr Padlewski if (Summary.isNotViableToInline()) 152332b3b22SPiotr Padlewski return false; 153332b3b22SPiotr Padlewski 154b4e1e829SMehdi Amini // Check references (and potential calls) in the same module. If the current 155b4e1e829SMehdi Amini // value references a global that can't be externally referenced it is not 156d5033a45STeresa Johnson // eligible for import. First check the flag set when we have possible 157d5033a45STeresa Johnson // opaque references (e.g. inline asm calls), then check the call and 158d5033a45STeresa Johnson // reference sets. 159d5033a45STeresa Johnson if (Summary.hasInlineAsmMaybeReferencingInternal()) 160d5033a45STeresa Johnson return false; 161b4e1e829SMehdi Amini bool AllRefsCanBeExternallyReferenced = 162b4e1e829SMehdi Amini llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) { 163b4e1e829SMehdi Amini return canBeExternallyReferenced(Index, VI.getGUID()); 164b4e1e829SMehdi Amini }); 165b4e1e829SMehdi Amini if (!AllRefsCanBeExternallyReferenced) 166b4e1e829SMehdi Amini return false; 167b4e1e829SMehdi Amini 168b4e1e829SMehdi Amini if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) { 169b4e1e829SMehdi Amini bool AllCallsCanBeExternallyReferenced = llvm::all_of( 170b4e1e829SMehdi Amini FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) { 171b4e1e829SMehdi Amini return canBeExternallyReferenced(Index, Edge.first.getGUID()); 172b4e1e829SMehdi Amini }); 173b4e1e829SMehdi Amini if (!AllCallsCanBeExternallyReferenced) 174b4e1e829SMehdi Amini return false; 175b4e1e829SMehdi Amini } 176b4e1e829SMehdi Amini return true; 177b4e1e829SMehdi Amini } 178b4e1e829SMehdi Amini 17901e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one 18001e32130SMehdi Amini /// that fits the \p Threshold. 18101e32130SMehdi Amini /// 18201e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"? 18301e32130SMehdi Amini /// - The smallest: more likely to be inlined. 18401e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized). 18501e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the 18601e32130SMehdi Amini /// number of source modules parsed/linked. 18701e32130SMehdi Amini /// - One that has PGO data attached. 18801e32130SMehdi Amini /// - [insert you fancy metric here] 1892d28f7aaSMehdi Amini static const GlobalValueSummary * 190b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index, 191b4e1e829SMehdi Amini const GlobalValueSummaryList &CalleeSummaryList, 19228e457bcSTeresa Johnson unsigned Threshold) { 19301e32130SMehdi Amini auto It = llvm::find_if( 19428e457bcSTeresa Johnson CalleeSummaryList, 19528e457bcSTeresa Johnson [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) { 19628e457bcSTeresa Johnson auto *GVSummary = SummaryPtr.get(); 197f329be83SRafael Espindola if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) 1985b85d8d6SMehdi Amini // There is no point in importing these, we can't inline them 19901e32130SMehdi Amini return false; 2002c719cc1SMehdi Amini if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) { 2012c719cc1SMehdi Amini GVSummary = &AS->getAliasee(); 2022c719cc1SMehdi Amini // Alias can't point to "available_externally". However when we import 2032c719cc1SMehdi Amini // linkOnceODR the linkage does not change. So we import the alias 2042c719cc1SMehdi Amini // and aliasee only in this case. 2052c719cc1SMehdi Amini // FIXME: we should import alias as available_externally *function*, 2062c719cc1SMehdi Amini // the destination module does need to know it is an alias. 2072c719cc1SMehdi Amini if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage())) 2082c719cc1SMehdi Amini return false; 2092c719cc1SMehdi Amini } 2102c719cc1SMehdi Amini 2112c719cc1SMehdi Amini auto *Summary = cast<FunctionSummary>(GVSummary); 2127e88d0daSMehdi Amini 21301e32130SMehdi Amini if (Summary->instCount() > Threshold) 21401e32130SMehdi Amini return false; 2157e88d0daSMehdi Amini 216b4e1e829SMehdi Amini if (!eligibleForImport(Index, *Summary)) 217b4e1e829SMehdi Amini return false; 218b4e1e829SMehdi Amini 21901e32130SMehdi Amini return true; 22001e32130SMehdi Amini }); 22128e457bcSTeresa Johnson if (It == CalleeSummaryList.end()) 22201e32130SMehdi Amini return nullptr; 2237e88d0daSMehdi Amini 22428e457bcSTeresa Johnson return cast<GlobalValueSummary>(It->get()); 225434e9561SRafael Espindola } 2267e88d0daSMehdi Amini 22701e32130SMehdi Amini /// Return the summary for the function \p GUID that fits the \p Threshold, or 22801e32130SMehdi Amini /// null if there's no match. 2292d28f7aaSMehdi Amini static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID, 230ad5741b0SMehdi Amini unsigned Threshold, 23101e32130SMehdi Amini const ModuleSummaryIndex &Index) { 23228e457bcSTeresa Johnson auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID); 233b4e1e829SMehdi Amini if (CalleeSummaryList == Index.end()) 23401e32130SMehdi Amini return nullptr; // This function does not have a summary 235b4e1e829SMehdi Amini return selectCallee(Index, CalleeSummaryList->second, Threshold); 23601e32130SMehdi Amini } 2377e88d0daSMehdi Amini 238475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */, 239475b51a7STeresa Johnson GlobalValue::GUID>; 24001e32130SMehdi Amini 24101e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these 24201e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as 24301e32130SMehdi Amini /// exported from their source module. 24401e32130SMehdi Amini static void computeImportForFunction( 2453255eec1STeresa Johnson const FunctionSummary &Summary, const ModuleSummaryIndex &Index, 246d9830eb7SPiotr Padlewski const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries, 24701e32130SMehdi Amini SmallVectorImpl<EdgeInfo> &Worklist, 2489b490f10SMehdi Amini FunctionImporter::ImportMapTy &ImportList, 249c86af334STeresa Johnson StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 25001e32130SMehdi Amini for (auto &Edge : Summary.calls()) { 2512d5487cfSTeresa Johnson auto GUID = Edge.first.getGUID(); 25201e32130SMehdi Amini DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n"); 25301e32130SMehdi Amini 2541aafabf7SMehdi Amini if (DefinedGVSummaries.count(GUID)) { 25501e32130SMehdi Amini DEBUG(dbgs() << "ignored! Target already in destination module.\n"); 2567e88d0daSMehdi Amini continue; 257d450da32STeresa Johnson } 25840641748SMehdi Amini 259ba72b95fSPiotr Padlewski auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float { 260ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Hot) 261ba72b95fSPiotr Padlewski return ImportHotMultiplier; 262ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Cold) 263ba72b95fSPiotr Padlewski return ImportColdMultiplier; 264ba72b95fSPiotr Padlewski return 1.0; 265ba72b95fSPiotr Padlewski }; 266ba72b95fSPiotr Padlewski 267d9830eb7SPiotr Padlewski const auto NewThreshold = 268ba72b95fSPiotr Padlewski Threshold * GetBonusMultiplier(Edge.second.Hotness); 269d2869473SPiotr Padlewski 270d9830eb7SPiotr Padlewski auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index); 27101e32130SMehdi Amini if (!CalleeSummary) { 27201e32130SMehdi Amini DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n"); 2737e88d0daSMehdi Amini continue; 2747e88d0daSMehdi Amini } 2752d28f7aaSMehdi Amini // "Resolve" the summary, traversing alias, 2762d28f7aaSMehdi Amini const FunctionSummary *ResolvedCalleeSummary; 2776968ef77SMehdi Amini if (isa<AliasSummary>(CalleeSummary)) { 2782d28f7aaSMehdi Amini ResolvedCalleeSummary = cast<FunctionSummary>( 2792d28f7aaSMehdi Amini &cast<AliasSummary>(CalleeSummary)->getAliasee()); 2802c719cc1SMehdi Amini assert( 2812c719cc1SMehdi Amini GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) && 2822c719cc1SMehdi Amini "Unexpected alias to a non-linkonceODR in import list"); 2836968ef77SMehdi Amini } else 2842d28f7aaSMehdi Amini ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary); 2852d28f7aaSMehdi Amini 286d9830eb7SPiotr Padlewski assert(ResolvedCalleeSummary->instCount() <= NewThreshold && 28701e32130SMehdi Amini "selectCallee() didn't honor the threshold"); 28801e32130SMehdi Amini 289d2869473SPiotr Padlewski auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) { 290d2869473SPiotr Padlewski // Adjust the threshold for next level of imported functions. 291d2869473SPiotr Padlewski // The threshold is different for hot callsites because we can then 292d2869473SPiotr Padlewski // inline chains of hot calls. 293d2869473SPiotr Padlewski if (IsHotCallsite) 294d2869473SPiotr Padlewski return Threshold * ImportHotInstrFactor; 295d2869473SPiotr Padlewski return Threshold * ImportInstrFactor; 296d2869473SPiotr Padlewski }; 297d2869473SPiotr Padlewski 298d2869473SPiotr Padlewski bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot; 2991b859a23STeresa Johnson const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite); 3001b859a23STeresa Johnson 3011b859a23STeresa Johnson auto ExportModulePath = ResolvedCalleeSummary->modulePath(); 3021b859a23STeresa Johnson auto &ProcessedThreshold = ImportList[ExportModulePath][GUID]; 3031b859a23STeresa Johnson /// Since the traversal of the call graph is DFS, we can revisit a function 3041b859a23STeresa Johnson /// a second time with a higher threshold. In this case, it is added back to 3051b859a23STeresa Johnson /// the worklist with the new threshold. 3061b859a23STeresa Johnson if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) { 3071b859a23STeresa Johnson DEBUG(dbgs() << "ignored! Target was already seen with Threshold " 3081b859a23STeresa Johnson << ProcessedThreshold << "\n"); 3091b859a23STeresa Johnson continue; 3101b859a23STeresa Johnson } 31119f2aa78STeresa Johnson bool PreviouslyImported = ProcessedThreshold != 0; 3121b859a23STeresa Johnson // Mark this function as imported in this module, with the current Threshold 3131b859a23STeresa Johnson ProcessedThreshold = AdjThreshold; 3141b859a23STeresa Johnson 3151b859a23STeresa Johnson // Make exports in the source module. 3161b859a23STeresa Johnson if (ExportLists) { 3171b859a23STeresa Johnson auto &ExportList = (*ExportLists)[ExportModulePath]; 3181b859a23STeresa Johnson ExportList.insert(GUID); 31919f2aa78STeresa Johnson if (!PreviouslyImported) { 32019f2aa78STeresa Johnson // This is the first time this function was exported from its source 32119f2aa78STeresa Johnson // module, so mark all functions and globals it references as exported 3221b859a23STeresa Johnson // to the outside if they are defined in the same source module. 323*edddca22STeresa Johnson // For efficiency, we unconditionally add all the referenced GUIDs 324*edddca22STeresa Johnson // to the ExportList for this module, and will prune out any not 325*edddca22STeresa Johnson // defined in the module later in a single pass. 3261b859a23STeresa Johnson for (auto &Edge : ResolvedCalleeSummary->calls()) { 3271b859a23STeresa Johnson auto CalleeGUID = Edge.first.getGUID(); 328*edddca22STeresa Johnson ExportList.insert(CalleeGUID); 3291b859a23STeresa Johnson } 3301b859a23STeresa Johnson for (auto &Ref : ResolvedCalleeSummary->refs()) { 3311b859a23STeresa Johnson auto GUID = Ref.getGUID(); 332*edddca22STeresa Johnson ExportList.insert(GUID); 3331b859a23STeresa Johnson } 3341b859a23STeresa Johnson } 33519f2aa78STeresa Johnson } 336d2869473SPiotr Padlewski 33701e32130SMehdi Amini // Insert the newly imported function to the worklist. 338475b51a7STeresa Johnson Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, GUID); 339d450da32STeresa Johnson } 340d450da32STeresa Johnson } 341d450da32STeresa Johnson 34201e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports 34301e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from 34401e32130SMehdi Amini /// another module (that may require promotion). 34501e32130SMehdi Amini static void ComputeImportForModule( 346c851d216STeresa Johnson const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index, 3479b490f10SMehdi Amini FunctionImporter::ImportMapTy &ImportList, 348c86af334STeresa Johnson StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 34901e32130SMehdi Amini // Worklist contains the list of function imported in this module, for which 35001e32130SMehdi Amini // we will analyse the callees and may import further down the callgraph. 35101e32130SMehdi Amini SmallVector<EdgeInfo, 128> Worklist; 35201e32130SMehdi Amini 35301e32130SMehdi Amini // Populate the worklist with the import for the functions in the current 35401e32130SMehdi Amini // module 35528e457bcSTeresa Johnson for (auto &GVSummary : DefinedGVSummaries) { 35628e457bcSTeresa Johnson auto *Summary = GVSummary.second; 3572d28f7aaSMehdi Amini if (auto *AS = dyn_cast<AliasSummary>(Summary)) 3582d28f7aaSMehdi Amini Summary = &AS->getAliasee(); 3591aafabf7SMehdi Amini auto *FuncSummary = dyn_cast<FunctionSummary>(Summary); 3601aafabf7SMehdi Amini if (!FuncSummary) 3611aafabf7SMehdi Amini // Skip import for global variables 3621aafabf7SMehdi Amini continue; 36328e457bcSTeresa Johnson DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n"); 3642d28f7aaSMehdi Amini computeImportForFunction(*FuncSummary, Index, ImportInstrLimit, 3659b490f10SMehdi Amini DefinedGVSummaries, Worklist, ImportList, 36601e32130SMehdi Amini ExportLists); 36701e32130SMehdi Amini } 36801e32130SMehdi Amini 369d2869473SPiotr Padlewski // Process the newly imported functions and add callees to the worklist. 37042418abaSMehdi Amini while (!Worklist.empty()) { 37101e32130SMehdi Amini auto FuncInfo = Worklist.pop_back_val(); 372475b51a7STeresa Johnson auto *Summary = std::get<0>(FuncInfo); 373475b51a7STeresa Johnson auto Threshold = std::get<1>(FuncInfo); 374475b51a7STeresa Johnson auto GUID = std::get<2>(FuncInfo); 375475b51a7STeresa Johnson 376475b51a7STeresa Johnson // Check if we later added this summary with a higher threshold. 377475b51a7STeresa Johnson // If so, skip this entry. 378475b51a7STeresa Johnson auto ExportModulePath = Summary->modulePath(); 379475b51a7STeresa Johnson auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID]; 380475b51a7STeresa Johnson if (LatestProcessedThreshold > Threshold) 381475b51a7STeresa Johnson continue; 38242418abaSMehdi Amini 3831aafabf7SMehdi Amini computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries, 3849b490f10SMehdi Amini Worklist, ImportList, ExportLists); 385c8c55170SMehdi Amini } 38642418abaSMehdi Amini } 387ffe2e4aaSMehdi Amini 38801e32130SMehdi Amini } // anonymous namespace 38901e32130SMehdi Amini 390c86af334STeresa Johnson /// Compute all the import and export for every module using the Index. 39101e32130SMehdi Amini void llvm::ComputeCrossModuleImport( 39201e32130SMehdi Amini const ModuleSummaryIndex &Index, 393c851d216STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 39401e32130SMehdi Amini StringMap<FunctionImporter::ImportMapTy> &ImportLists, 39501e32130SMehdi Amini StringMap<FunctionImporter::ExportSetTy> &ExportLists) { 39601e32130SMehdi Amini // For each module that has function defined, compute the import/export lists. 3971aafabf7SMehdi Amini for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { 3989b490f10SMehdi Amini auto &ImportList = ImportLists[DefinedGVSummaries.first()]; 3991aafabf7SMehdi Amini DEBUG(dbgs() << "Computing import for Module '" 4001aafabf7SMehdi Amini << DefinedGVSummaries.first() << "'\n"); 4019b490f10SMehdi Amini ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList, 402c86af334STeresa Johnson &ExportLists); 40301e32130SMehdi Amini } 40401e32130SMehdi Amini 405*edddca22STeresa Johnson // When computing imports we added all GUIDs referenced by anything 406*edddca22STeresa Johnson // imported from the module to its ExportList. Now we prune each ExportList 407*edddca22STeresa Johnson // of any not defined in that module. This is more efficient than checking 408*edddca22STeresa Johnson // while computing imports because some of the summary lists may be long 409*edddca22STeresa Johnson // due to linkonce (comdat) copies. 410*edddca22STeresa Johnson for (auto &ELI : ExportLists) { 411*edddca22STeresa Johnson const auto &DefinedGVSummaries = 412*edddca22STeresa Johnson ModuleToDefinedGVSummaries.lookup(ELI.first()); 413*edddca22STeresa Johnson for (auto EI = ELI.second.begin(); EI != ELI.second.end();) { 414*edddca22STeresa Johnson if (!DefinedGVSummaries.count(*EI)) 415*edddca22STeresa Johnson EI = ELI.second.erase(EI); 416*edddca22STeresa Johnson else 417*edddca22STeresa Johnson ++EI; 418*edddca22STeresa Johnson } 419*edddca22STeresa Johnson } 420*edddca22STeresa Johnson 42101e32130SMehdi Amini #ifndef NDEBUG 42201e32130SMehdi Amini DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size() 42301e32130SMehdi Amini << " modules:\n"); 42401e32130SMehdi Amini for (auto &ModuleImports : ImportLists) { 42501e32130SMehdi Amini auto ModName = ModuleImports.first(); 42601e32130SMehdi Amini auto &Exports = ExportLists[ModName]; 42701e32130SMehdi Amini DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size() 42801e32130SMehdi Amini << " functions. Imports from " << ModuleImports.second.size() 42901e32130SMehdi Amini << " modules.\n"); 43001e32130SMehdi Amini for (auto &Src : ModuleImports.second) { 43101e32130SMehdi Amini auto SrcModName = Src.first(); 43201e32130SMehdi Amini DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from " 43301e32130SMehdi Amini << SrcModName << "\n"); 43401e32130SMehdi Amini } 43501e32130SMehdi Amini } 43601e32130SMehdi Amini #endif 43701e32130SMehdi Amini } 43801e32130SMehdi Amini 439c86af334STeresa Johnson /// Compute all the imports for the given module in the Index. 440c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule( 441c86af334STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 442c86af334STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 443c86af334STeresa Johnson 444c86af334STeresa Johnson // Collect the list of functions this module defines. 445c86af334STeresa Johnson // GUID -> Summary 446c851d216STeresa Johnson GVSummaryMapTy FunctionSummaryMap; 44728e457bcSTeresa Johnson Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap); 448c86af334STeresa Johnson 449c86af334STeresa Johnson // Compute the import list for this module. 450c86af334STeresa Johnson DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n"); 45128e457bcSTeresa Johnson ComputeImportForModule(FunctionSummaryMap, Index, ImportList); 452c86af334STeresa Johnson 453c86af334STeresa Johnson #ifndef NDEBUG 454c86af334STeresa Johnson DEBUG(dbgs() << "* Module " << ModulePath << " imports from " 455c86af334STeresa Johnson << ImportList.size() << " modules.\n"); 456c86af334STeresa Johnson for (auto &Src : ImportList) { 457c86af334STeresa Johnson auto SrcModName = Src.first(); 458c86af334STeresa Johnson DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from " 459c86af334STeresa Johnson << SrcModName << "\n"); 460c86af334STeresa Johnson } 461c86af334STeresa Johnson #endif 462c86af334STeresa Johnson } 463c86af334STeresa Johnson 46484174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of 46584174c37STeresa Johnson /// \p ModulePath. 46684174c37STeresa Johnson void llvm::gatherImportedSummariesForModule( 46784174c37STeresa Johnson StringRef ModulePath, 46884174c37STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 469cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ImportList, 47084174c37STeresa Johnson std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 47184174c37STeresa Johnson // Include all summaries from the importing module. 47284174c37STeresa Johnson ModuleToSummariesForIndex[ModulePath] = 47384174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ModulePath); 47484174c37STeresa Johnson // Include summaries for imports. 47588c491ddSMehdi Amini for (auto &ILI : ImportList) { 47684174c37STeresa Johnson auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()]; 47784174c37STeresa Johnson const auto &DefinedGVSummaries = 47884174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ILI.first()); 47984174c37STeresa Johnson for (auto &GI : ILI.second) { 48084174c37STeresa Johnson const auto &DS = DefinedGVSummaries.find(GI.first); 48184174c37STeresa Johnson assert(DS != DefinedGVSummaries.end() && 48284174c37STeresa Johnson "Expected a defined summary for imported global value"); 48384174c37STeresa Johnson SummariesForIndex[GI.first] = DS->second; 48484174c37STeresa Johnson } 48584174c37STeresa Johnson } 48684174c37STeresa Johnson } 48784174c37STeresa Johnson 4888570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename. 489cdbcbf74SMehdi Amini std::error_code 490cdbcbf74SMehdi Amini llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, 491cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ModuleImports) { 4928570fe47STeresa Johnson std::error_code EC; 4938570fe47STeresa Johnson raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None); 4948570fe47STeresa Johnson if (EC) 4958570fe47STeresa Johnson return EC; 496cdbcbf74SMehdi Amini for (auto &ILI : ModuleImports) 4978570fe47STeresa Johnson ImportsOS << ILI.first() << "\n"; 4988570fe47STeresa Johnson return std::error_code(); 4998570fe47STeresa Johnson } 5008570fe47STeresa Johnson 50104c9a2d6STeresa Johnson /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis. 50204c9a2d6STeresa Johnson void llvm::thinLTOResolveWeakForLinkerModule( 50304c9a2d6STeresa Johnson Module &TheModule, const GVSummaryMapTy &DefinedGlobals) { 50404c9a2d6STeresa Johnson auto updateLinkage = [&](GlobalValue &GV) { 50504c9a2d6STeresa Johnson if (!GlobalValue::isWeakForLinker(GV.getLinkage())) 50604c9a2d6STeresa Johnson return; 50704c9a2d6STeresa Johnson // See if the global summary analysis computed a new resolved linkage. 50804c9a2d6STeresa Johnson const auto &GS = DefinedGlobals.find(GV.getGUID()); 50904c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) 51004c9a2d6STeresa Johnson return; 51104c9a2d6STeresa Johnson auto NewLinkage = GS->second->linkage(); 51204c9a2d6STeresa Johnson if (NewLinkage == GV.getLinkage()) 51304c9a2d6STeresa Johnson return; 51404c9a2d6STeresa Johnson DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from " 51504c9a2d6STeresa Johnson << GV.getLinkage() << " to " << NewLinkage << "\n"); 51604c9a2d6STeresa Johnson GV.setLinkage(NewLinkage); 5176107a419STeresa Johnson // Remove functions converted to available_externally from comdats, 5186107a419STeresa Johnson // as this is a declaration for the linker, and will be dropped eventually. 5196107a419STeresa Johnson // It is illegal for comdats to contain declarations. 5206107a419STeresa Johnson auto *GO = dyn_cast_or_null<GlobalObject>(&GV); 5216107a419STeresa Johnson if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) { 5226107a419STeresa Johnson assert(GO->hasAvailableExternallyLinkage() && 5236107a419STeresa Johnson "Expected comdat on definition (possibly available external)"); 5246107a419STeresa Johnson GO->setComdat(nullptr); 5256107a419STeresa Johnson } 52604c9a2d6STeresa Johnson }; 52704c9a2d6STeresa Johnson 52804c9a2d6STeresa Johnson // Process functions and global now 52904c9a2d6STeresa Johnson for (auto &GV : TheModule) 53004c9a2d6STeresa Johnson updateLinkage(GV); 53104c9a2d6STeresa Johnson for (auto &GV : TheModule.globals()) 53204c9a2d6STeresa Johnson updateLinkage(GV); 53304c9a2d6STeresa Johnson for (auto &GV : TheModule.aliases()) 53404c9a2d6STeresa Johnson updateLinkage(GV); 53504c9a2d6STeresa Johnson } 53604c9a2d6STeresa Johnson 53704c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis. 53804c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule, 53904c9a2d6STeresa Johnson const GVSummaryMapTy &DefinedGlobals) { 54004c9a2d6STeresa Johnson // Parse inline ASM and collect the list of symbols that are not defined in 54104c9a2d6STeresa Johnson // the current module. 54204c9a2d6STeresa Johnson StringSet<> AsmUndefinedRefs; 543863cbfbeSPeter Collingbourne ModuleSymbolTable::CollectAsmSymbols( 54404c9a2d6STeresa Johnson Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(), 54504c9a2d6STeresa Johnson [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) { 54604c9a2d6STeresa Johnson if (Flags & object::BasicSymbolRef::SF_Undefined) 54704c9a2d6STeresa Johnson AsmUndefinedRefs.insert(Name); 54804c9a2d6STeresa Johnson }); 54904c9a2d6STeresa Johnson 55004c9a2d6STeresa Johnson // Declare a callback for the internalize pass that will ask for every 55104c9a2d6STeresa Johnson // candidate GlobalValue if it can be internalized or not. 55204c9a2d6STeresa Johnson auto MustPreserveGV = [&](const GlobalValue &GV) -> bool { 55304c9a2d6STeresa Johnson // Can't be internalized if referenced in inline asm. 55404c9a2d6STeresa Johnson if (AsmUndefinedRefs.count(GV.getName())) 55504c9a2d6STeresa Johnson return true; 55604c9a2d6STeresa Johnson 55704c9a2d6STeresa Johnson // Lookup the linkage recorded in the summaries during global analysis. 55804c9a2d6STeresa Johnson const auto &GS = DefinedGlobals.find(GV.getGUID()); 55904c9a2d6STeresa Johnson GlobalValue::LinkageTypes Linkage; 56004c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) { 56104c9a2d6STeresa Johnson // Must have been promoted (possibly conservatively). Find original 56204c9a2d6STeresa Johnson // name so that we can access the correct summary and see if it can 56304c9a2d6STeresa Johnson // be internalized again. 56404c9a2d6STeresa Johnson // FIXME: Eventually we should control promotion instead of promoting 56504c9a2d6STeresa Johnson // and internalizing again. 56604c9a2d6STeresa Johnson StringRef OrigName = 56704c9a2d6STeresa Johnson ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName()); 56804c9a2d6STeresa Johnson std::string OrigId = GlobalValue::getGlobalIdentifier( 56904c9a2d6STeresa Johnson OrigName, GlobalValue::InternalLinkage, 57004c9a2d6STeresa Johnson TheModule.getSourceFileName()); 57104c9a2d6STeresa Johnson const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); 5727ab1f692STeresa Johnson if (GS == DefinedGlobals.end()) { 5737ab1f692STeresa Johnson // Also check the original non-promoted non-globalized name. In some 5747ab1f692STeresa Johnson // cases a preempted weak value is linked in as a local copy because 5757ab1f692STeresa Johnson // it is referenced by an alias (IRLinker::linkGlobalValueProto). 5767ab1f692STeresa Johnson // In that case, since it was originally not a local value, it was 5777ab1f692STeresa Johnson // recorded in the index using the original name. 5787ab1f692STeresa Johnson // FIXME: This may not be needed once PR27866 is fixed. 5797ab1f692STeresa Johnson const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); 58004c9a2d6STeresa Johnson assert(GS != DefinedGlobals.end()); 58104c9a2d6STeresa Johnson Linkage = GS->second->linkage(); 5827ab1f692STeresa Johnson } else { 5837ab1f692STeresa Johnson Linkage = GS->second->linkage(); 5847ab1f692STeresa Johnson } 58504c9a2d6STeresa Johnson } else 58604c9a2d6STeresa Johnson Linkage = GS->second->linkage(); 58704c9a2d6STeresa Johnson return !GlobalValue::isLocalLinkage(Linkage); 58804c9a2d6STeresa Johnson }; 58904c9a2d6STeresa Johnson 59004c9a2d6STeresa Johnson // FIXME: See if we can just internalize directly here via linkage changes 59104c9a2d6STeresa Johnson // based on the index, rather than invoking internalizeModule. 59204c9a2d6STeresa Johnson llvm::internalizeModule(TheModule, MustPreserveGV); 59304c9a2d6STeresa Johnson } 59404c9a2d6STeresa Johnson 595c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries 596c8c55170SMehdi Amini // index. 597c8c55170SMehdi Amini // 5987f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions( 599bda3c97cSMehdi Amini Module &DestModule, const FunctionImporter::ImportMapTy &ImportList, 600bda3c97cSMehdi Amini bool ForceImportReferencedDiscardableSymbols) { 6015411d051SMehdi Amini DEBUG(dbgs() << "Starting import for Module " 602311fef6eSMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 603c8c55170SMehdi Amini unsigned ImportedCount = 0; 604c8c55170SMehdi Amini 605c8c55170SMehdi Amini // Linker that will be used for importing function 6069d2bfc48SRafael Espindola Linker TheLinker(DestModule); 6077e88d0daSMehdi Amini // Do the actual import of functions now, one Module at a time 60801e32130SMehdi Amini std::set<StringRef> ModuleNameOrderedList; 60901e32130SMehdi Amini for (auto &FunctionsToImportPerModule : ImportList) { 61001e32130SMehdi Amini ModuleNameOrderedList.insert(FunctionsToImportPerModule.first()); 61101e32130SMehdi Amini } 61201e32130SMehdi Amini for (auto &Name : ModuleNameOrderedList) { 6137e88d0daSMehdi Amini // Get the module for the import 61401e32130SMehdi Amini const auto &FunctionsToImportPerModule = ImportList.find(Name); 61501e32130SMehdi Amini assert(FunctionsToImportPerModule != ImportList.end()); 616d9445c49SPeter Collingbourne Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name); 617d9445c49SPeter Collingbourne if (!SrcModuleOrErr) 618d9445c49SPeter Collingbourne return SrcModuleOrErr.takeError(); 619d9445c49SPeter Collingbourne std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr); 6207e88d0daSMehdi Amini assert(&DestModule.getContext() == &SrcModule->getContext() && 6217e88d0daSMehdi Amini "Context mismatch"); 6227e88d0daSMehdi Amini 6236cba37ceSTeresa Johnson // If modules were created with lazy metadata loading, materialize it 6246cba37ceSTeresa Johnson // now, before linking it (otherwise this will be a noop). 6257f00d0a1SPeter Collingbourne if (Error Err = SrcModule->materializeMetadata()) 6267f00d0a1SPeter Collingbourne return std::move(Err); 6276cba37ceSTeresa Johnson UpgradeDebugInfo(*SrcModule); 628e5a61917STeresa Johnson 62901e32130SMehdi Amini auto &ImportGUIDs = FunctionsToImportPerModule->second; 63001e32130SMehdi Amini // Find the globals to import 63101e32130SMehdi Amini DenseSet<const GlobalValue *> GlobalsToImport; 6321f685e01SPiotr Padlewski for (Function &F : *SrcModule) { 6331f685e01SPiotr Padlewski if (!F.hasName()) 6340beb858eSTeresa Johnson continue; 6351f685e01SPiotr Padlewski auto GUID = F.getGUID(); 6360beb858eSTeresa Johnson auto Import = ImportGUIDs.count(GUID); 637aeb1e59bSMehdi Amini DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID 6381f685e01SPiotr Padlewski << " " << F.getName() << " from " 639aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 6400beb858eSTeresa Johnson if (Import) { 6417f00d0a1SPeter Collingbourne if (Error Err = F.materialize()) 6427f00d0a1SPeter Collingbourne return std::move(Err); 6433b776128SPiotr Padlewski if (EnableImportMetadata) { 6446deaa6afSPiotr Padlewski // Add 'thinlto_src_module' metadata for statistics and debugging. 6453b776128SPiotr Padlewski F.setMetadata( 6463b776128SPiotr Padlewski "thinlto_src_module", 6473b776128SPiotr Padlewski llvm::MDNode::get( 6486deaa6afSPiotr Padlewski DestModule.getContext(), 6493b776128SPiotr Padlewski {llvm::MDString::get(DestModule.getContext(), 6506deaa6afSPiotr Padlewski SrcModule->getSourceFileName())})); 6513b776128SPiotr Padlewski } 6521f685e01SPiotr Padlewski GlobalsToImport.insert(&F); 65301e32130SMehdi Amini } 65401e32130SMehdi Amini } 6551f685e01SPiotr Padlewski for (GlobalVariable &GV : SrcModule->globals()) { 6562d28f7aaSMehdi Amini if (!GV.hasName()) 6572d28f7aaSMehdi Amini continue; 6582d28f7aaSMehdi Amini auto GUID = GV.getGUID(); 6592d28f7aaSMehdi Amini auto Import = ImportGUIDs.count(GUID); 660aeb1e59bSMehdi Amini DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID 661aeb1e59bSMehdi Amini << " " << GV.getName() << " from " 662aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 6632d28f7aaSMehdi Amini if (Import) { 6647f00d0a1SPeter Collingbourne if (Error Err = GV.materialize()) 6657f00d0a1SPeter Collingbourne return std::move(Err); 6662d28f7aaSMehdi Amini GlobalsToImport.insert(&GV); 6672d28f7aaSMehdi Amini } 6682d28f7aaSMehdi Amini } 6691f685e01SPiotr Padlewski for (GlobalAlias &GA : SrcModule->aliases()) { 6701f685e01SPiotr Padlewski if (!GA.hasName()) 67101e32130SMehdi Amini continue; 6721f685e01SPiotr Padlewski auto GUID = GA.getGUID(); 6730beb858eSTeresa Johnson auto Import = ImportGUIDs.count(GUID); 674aeb1e59bSMehdi Amini DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID 6751f685e01SPiotr Padlewski << " " << GA.getName() << " from " 676aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 6770beb858eSTeresa Johnson if (Import) { 67801e32130SMehdi Amini // Alias can't point to "available_externally". However when we import 6799aae395fSTeresa Johnson // linkOnceODR the linkage does not change. So we import the alias 6806968ef77SMehdi Amini // and aliasee only in this case. This has been handled by 6816968ef77SMehdi Amini // computeImportForFunction() 6821f685e01SPiotr Padlewski GlobalObject *GO = GA.getBaseObject(); 6836968ef77SMehdi Amini assert(GO->hasLinkOnceODRLinkage() && 6846968ef77SMehdi Amini "Unexpected alias to a non-linkonceODR in import list"); 6852d28f7aaSMehdi Amini #ifndef NDEBUG 6862d28f7aaSMehdi Amini if (!GlobalsToImport.count(GO)) 6872d28f7aaSMehdi Amini DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID() 6882d28f7aaSMehdi Amini << " " << GO->getName() << " from " 6892d28f7aaSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 6902d28f7aaSMehdi Amini #endif 6917f00d0a1SPeter Collingbourne if (Error Err = GO->materialize()) 6927f00d0a1SPeter Collingbourne return std::move(Err); 69301e32130SMehdi Amini GlobalsToImport.insert(GO); 6947f00d0a1SPeter Collingbourne if (Error Err = GA.materialize()) 6957f00d0a1SPeter Collingbourne return std::move(Err); 6961f685e01SPiotr Padlewski GlobalsToImport.insert(&GA); 69701e32130SMehdi Amini } 69801e32130SMehdi Amini } 69901e32130SMehdi Amini 7007e88d0daSMehdi Amini // Link in the specified functions. 70101e32130SMehdi Amini if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport)) 7028d05185aSMehdi Amini return true; 7038d05185aSMehdi Amini 704d29478f7STeresa Johnson if (PrintImports) { 705d29478f7STeresa Johnson for (const auto *GV : GlobalsToImport) 706d29478f7STeresa Johnson dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName() 707d29478f7STeresa Johnson << " from " << SrcModule->getSourceFileName() << "\n"; 708d29478f7STeresa Johnson } 709d29478f7STeresa Johnson 710bda3c97cSMehdi Amini // Instruct the linker that the client will take care of linkonce resolution 711bda3c97cSMehdi Amini unsigned Flags = Linker::Flags::None; 712bda3c97cSMehdi Amini if (!ForceImportReferencedDiscardableSymbols) 713bda3c97cSMehdi Amini Flags |= Linker::Flags::DontForceLinkLinkonceODR; 714bda3c97cSMehdi Amini 715bda3c97cSMehdi Amini if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport)) 7167e88d0daSMehdi Amini report_fatal_error("Function Import: link error"); 7177e88d0daSMehdi Amini 71801e32130SMehdi Amini ImportedCount += GlobalsToImport.size(); 7197e88d0daSMehdi Amini } 720e5a61917STeresa Johnson 721d29478f7STeresa Johnson NumImported += ImportedCount; 722d29478f7STeresa Johnson 7237e88d0daSMehdi Amini DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module " 724c8c55170SMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 725c8c55170SMehdi Amini return ImportedCount; 72642418abaSMehdi Amini } 72742418abaSMehdi Amini 72842418abaSMehdi Amini /// Summary file to use for function importing when using -function-import from 72942418abaSMehdi Amini /// the command line. 73042418abaSMehdi Amini static cl::opt<std::string> 73142418abaSMehdi Amini SummaryFile("summary-file", 73242418abaSMehdi Amini cl::desc("The summary file to use for function importing.")); 73342418abaSMehdi Amini 73421241571STeresa Johnson static bool doImportingForModule(Module &M, const ModuleSummaryIndex *Index) { 7355fcbdb71STeresa Johnson if (SummaryFile.empty() && !Index) 7365fcbdb71STeresa Johnson report_fatal_error("error: -function-import requires -summary-file or " 7375fcbdb71STeresa Johnson "file from frontend\n"); 73826ab5772STeresa Johnson std::unique_ptr<ModuleSummaryIndex> IndexPtr; 7395fcbdb71STeresa Johnson if (!SummaryFile.empty()) { 7405fcbdb71STeresa Johnson if (Index) 7415fcbdb71STeresa Johnson report_fatal_error("error: -summary-file and index from frontend\n"); 7426de481a3SPeter Collingbourne Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr = 7436de481a3SPeter Collingbourne getModuleSummaryIndexForFile(SummaryFile); 7446de481a3SPeter Collingbourne if (!IndexPtrOrErr) { 7456de481a3SPeter Collingbourne logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(), 7466de481a3SPeter Collingbourne "Error loading file '" + SummaryFile + "': "); 74742418abaSMehdi Amini return false; 74842418abaSMehdi Amini } 7496de481a3SPeter Collingbourne IndexPtr = std::move(*IndexPtrOrErr); 7505fcbdb71STeresa Johnson Index = IndexPtr.get(); 7515fcbdb71STeresa Johnson } 75242418abaSMehdi Amini 753c86af334STeresa Johnson // First step is collecting the import list. 754c86af334STeresa Johnson FunctionImporter::ImportMapTy ImportList; 755c86af334STeresa Johnson ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index, 756c86af334STeresa Johnson ImportList); 75701e32130SMehdi Amini 7584fef68cbSTeresa Johnson // Conservatively mark all internal values as promoted. This interface is 7594fef68cbSTeresa Johnson // only used when doing importing via the function importing pass. The pass 7604fef68cbSTeresa Johnson // is only enabled when testing importing via the 'opt' tool, which does 7614fef68cbSTeresa Johnson // not do the ThinLink that would normally determine what values to promote. 7624fef68cbSTeresa Johnson for (auto &I : *Index) { 7634fef68cbSTeresa Johnson for (auto &S : I.second) { 7644fef68cbSTeresa Johnson if (GlobalValue::isLocalLinkage(S->linkage())) 7654fef68cbSTeresa Johnson S->setLinkage(GlobalValue::ExternalLinkage); 7664fef68cbSTeresa Johnson } 7674fef68cbSTeresa Johnson } 7684fef68cbSTeresa Johnson 76901e32130SMehdi Amini // Next we need to promote to global scope and rename any local values that 7701b00f2d9STeresa Johnson // are potentially exported to other modules. 77101e32130SMehdi Amini if (renameModuleForThinLTO(M, *Index, nullptr)) { 7721b00f2d9STeresa Johnson errs() << "Error renaming module\n"; 7731b00f2d9STeresa Johnson return false; 7741b00f2d9STeresa Johnson } 7751b00f2d9STeresa Johnson 77642418abaSMehdi Amini // Perform the import now. 777d16c8065SMehdi Amini auto ModuleLoader = [&M](StringRef Identifier) { 778d16c8065SMehdi Amini return loadFile(Identifier, M.getContext()); 779d16c8065SMehdi Amini }; 7809d2bfc48SRafael Espindola FunctionImporter Importer(*Index, ModuleLoader); 7817f00d0a1SPeter Collingbourne Expected<bool> Result = Importer.importFunctions( 7827f00d0a1SPeter Collingbourne M, ImportList, !DontForceImportReferencedDiscardableSymbols); 7837f00d0a1SPeter Collingbourne 7847f00d0a1SPeter Collingbourne // FIXME: Probably need to propagate Errors through the pass manager. 7857f00d0a1SPeter Collingbourne if (!Result) { 7867f00d0a1SPeter Collingbourne logAllUnhandledErrors(Result.takeError(), errs(), 7877f00d0a1SPeter Collingbourne "Error importing module: "); 7887f00d0a1SPeter Collingbourne return false; 7897f00d0a1SPeter Collingbourne } 7907f00d0a1SPeter Collingbourne 7917f00d0a1SPeter Collingbourne return *Result; 79221241571STeresa Johnson } 79321241571STeresa Johnson 79421241571STeresa Johnson namespace { 79521241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file. 79621241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass { 79721241571STeresa Johnson /// Optional module summary index to use for importing, otherwise 79821241571STeresa Johnson /// the summary-file option must be specified. 79921241571STeresa Johnson const ModuleSummaryIndex *Index; 80021241571STeresa Johnson 80121241571STeresa Johnson public: 80221241571STeresa Johnson /// Pass identification, replacement for typeid 80321241571STeresa Johnson static char ID; 80421241571STeresa Johnson 80521241571STeresa Johnson /// Specify pass name for debug output 806117296c0SMehdi Amini StringRef getPassName() const override { return "Function Importing"; } 80721241571STeresa Johnson 80821241571STeresa Johnson explicit FunctionImportLegacyPass(const ModuleSummaryIndex *Index = nullptr) 80921241571STeresa Johnson : ModulePass(ID), Index(Index) {} 81021241571STeresa Johnson 81121241571STeresa Johnson bool runOnModule(Module &M) override { 81221241571STeresa Johnson if (skipModule(M)) 81321241571STeresa Johnson return false; 81421241571STeresa Johnson 81521241571STeresa Johnson return doImportingForModule(M, Index); 81642418abaSMehdi Amini } 81742418abaSMehdi Amini }; 818fe2b5415SBenjamin Kramer } // anonymous namespace 81942418abaSMehdi Amini 82021241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M, 821fd03ac6aSSean Silva ModuleAnalysisManager &AM) { 82221241571STeresa Johnson if (!doImportingForModule(M, Index)) 82321241571STeresa Johnson return PreservedAnalyses::all(); 82421241571STeresa Johnson 82521241571STeresa Johnson return PreservedAnalyses::none(); 82621241571STeresa Johnson } 82721241571STeresa Johnson 82821241571STeresa Johnson char FunctionImportLegacyPass::ID = 0; 82921241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import", 83042418abaSMehdi Amini "Summary Based Function Import", false, false) 83142418abaSMehdi Amini 83242418abaSMehdi Amini namespace llvm { 83326ab5772STeresa Johnson Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) { 83421241571STeresa Johnson return new FunctionImportLegacyPass(Index); 8355fcbdb71STeresa Johnson } 83642418abaSMehdi Amini } 837