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" 15e9ea08a0SEugene Zelenko #include "llvm/ADT/ArrayRef.h" 16e9ea08a0SEugene Zelenko #include "llvm/ADT/STLExtras.h" 17e9ea08a0SEugene Zelenko #include "llvm/ADT/SetVector.h" 1801e32130SMehdi Amini #include "llvm/ADT/SmallVector.h" 19d29478f7STeresa Johnson #include "llvm/ADT/Statistic.h" 20e9ea08a0SEugene Zelenko #include "llvm/ADT/StringMap.h" 210efed325SSimon Pilgrim #include "llvm/ADT/StringRef.h" 22b040fcc6SCharles Saternos #include "llvm/ADT/StringSet.h" 23c15d60b7SPeter Collingbourne #include "llvm/Bitcode/BitcodeReader.h" 2442418abaSMehdi Amini #include "llvm/IR/AutoUpgrade.h" 2581bbf742STeresa Johnson #include "llvm/IR/Constants.h" 26e9ea08a0SEugene Zelenko #include "llvm/IR/Function.h" 27e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalAlias.h" 28e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalObject.h" 29e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalValue.h" 30e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalVariable.h" 31e9ea08a0SEugene Zelenko #include "llvm/IR/Metadata.h" 3242418abaSMehdi Amini #include "llvm/IR/Module.h" 33e9ea08a0SEugene Zelenko #include "llvm/IR/ModuleSummaryIndex.h" 3442418abaSMehdi Amini #include "llvm/IRReader/IRReader.h" 35e9ea08a0SEugene Zelenko #include "llvm/Linker/IRMover.h" 36e9ea08a0SEugene Zelenko #include "llvm/Object/ModuleSymbolTable.h" 37e9ea08a0SEugene Zelenko #include "llvm/Object/SymbolicFile.h" 38e9ea08a0SEugene Zelenko #include "llvm/Pass.h" 39e9ea08a0SEugene Zelenko #include "llvm/Support/Casting.h" 4042418abaSMehdi Amini #include "llvm/Support/CommandLine.h" 4142418abaSMehdi Amini #include "llvm/Support/Debug.h" 42e9ea08a0SEugene Zelenko #include "llvm/Support/Error.h" 43e9ea08a0SEugene Zelenko #include "llvm/Support/ErrorHandling.h" 44e9ea08a0SEugene Zelenko #include "llvm/Support/FileSystem.h" 4542418abaSMehdi Amini #include "llvm/Support/SourceMgr.h" 46e9ea08a0SEugene Zelenko #include "llvm/Support/raw_ostream.h" 4704c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h" 4881bbf742STeresa Johnson #include "llvm/Transforms/Utils/Cloning.h" 49488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h" 5081bbf742STeresa Johnson #include "llvm/Transforms/Utils/ValueMapper.h" 51e9ea08a0SEugene Zelenko #include <cassert> 52e9ea08a0SEugene Zelenko #include <memory> 53e9ea08a0SEugene Zelenko #include <set> 54e9ea08a0SEugene Zelenko #include <string> 55e9ea08a0SEugene Zelenko #include <system_error> 56e9ea08a0SEugene Zelenko #include <tuple> 57e9ea08a0SEugene Zelenko #include <utility> 587e88d0daSMehdi Amini 5942418abaSMehdi Amini using namespace llvm; 6042418abaSMehdi Amini 61e9ea08a0SEugene Zelenko #define DEBUG_TYPE "function-import" 62e9ea08a0SEugene Zelenko 636c475a75STeresa Johnson STATISTIC(NumImportedFunctions, "Number of functions imported"); 6419e23874SEugene Leviant STATISTIC(NumImportedGlobalVars, "Number of global variables imported"); 656c475a75STeresa Johnson STATISTIC(NumImportedModules, "Number of modules imported from"); 666c475a75STeresa Johnson STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index"); 676c475a75STeresa Johnson STATISTIC(NumLiveSymbols, "Number of live symbols in index"); 68d29478f7STeresa Johnson 6939303619STeresa Johnson /// Limit on instruction count of imported functions. 7039303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit( 7139303619STeresa Johnson "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), 7239303619STeresa Johnson cl::desc("Only import functions with less than N instructions")); 7339303619STeresa Johnson 74974706ebSTeresa Johnson static cl::opt<int> ImportCutoff( 75974706ebSTeresa Johnson "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"), 76974706ebSTeresa Johnson cl::desc("Only import first N functions if N>=0 (default -1)")); 77974706ebSTeresa Johnson 7840641748SMehdi Amini static cl::opt<float> 7940641748SMehdi Amini ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), 8040641748SMehdi Amini cl::Hidden, cl::value_desc("x"), 8140641748SMehdi Amini cl::desc("As we import functions, multiply the " 8240641748SMehdi Amini "`import-instr-limit` threshold by this factor " 8340641748SMehdi Amini "before processing newly imported functions")); 84ba72b95fSPiotr Padlewski 85d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor( 86d2869473SPiotr Padlewski "import-hot-evolution-factor", cl::init(1.0), cl::Hidden, 87d2869473SPiotr Padlewski cl::value_desc("x"), 88d2869473SPiotr Padlewski cl::desc("As we import functions called from hot callsite, multiply the " 89d2869473SPiotr Padlewski "`import-instr-limit` threshold by this factor " 90d2869473SPiotr Padlewski "before processing newly imported functions")); 91d2869473SPiotr Padlewski 92d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier( 938260d665SDehao Chen "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), 94ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for hot callsites")); 95ba72b95fSPiotr Padlewski 9664c46574SDehao Chen static cl::opt<float> ImportCriticalMultiplier( 9764c46574SDehao Chen "import-critical-multiplier", cl::init(100.0), cl::Hidden, 9864c46574SDehao Chen cl::value_desc("x"), 9964c46574SDehao Chen cl::desc( 10064c46574SDehao Chen "Multiply the `import-instr-limit` threshold for critical callsites")); 10164c46574SDehao Chen 102ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up. 103ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier( 104ba72b95fSPiotr Padlewski "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), 105ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for cold callsites")); 10640641748SMehdi Amini 107d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden, 108d29478f7STeresa Johnson cl::desc("Print imported functions")); 109d29478f7STeresa Johnson 1106c475a75STeresa Johnson static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden, 1116c475a75STeresa Johnson cl::desc("Compute dead symbols")); 1126c475a75STeresa Johnson 1133b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata( 1143b776128SPiotr Padlewski "enable-import-metadata", cl::init( 1153b776128SPiotr Padlewski #if !defined(NDEBUG) 1163b776128SPiotr Padlewski true /*Enabled with asserts.*/ 1173b776128SPiotr Padlewski #else 1183b776128SPiotr Padlewski false 1193b776128SPiotr Padlewski #endif 1203b776128SPiotr Padlewski ), 1213b776128SPiotr Padlewski cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'")); 1223b776128SPiotr Padlewski 123e9ea08a0SEugene Zelenko /// Summary file to use for function importing when using -function-import from 124e9ea08a0SEugene Zelenko /// the command line. 125e9ea08a0SEugene Zelenko static cl::opt<std::string> 126e9ea08a0SEugene Zelenko SummaryFile("summary-file", 127e9ea08a0SEugene Zelenko cl::desc("The summary file to use for function importing.")); 128e9ea08a0SEugene Zelenko 12981bbf742STeresa Johnson /// Used when testing importing from distributed indexes via opt 13081bbf742STeresa Johnson // -function-import. 13181bbf742STeresa Johnson static cl::opt<bool> 13281bbf742STeresa Johnson ImportAllIndex("import-all-index", 13381bbf742STeresa Johnson cl::desc("Import all external functions in index.")); 13481bbf742STeresa Johnson 13542418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context. 13642418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName, 13742418abaSMehdi Amini LLVMContext &Context) { 13842418abaSMehdi Amini SMDiagnostic Err; 13942418abaSMehdi Amini DEBUG(dbgs() << "Loading '" << FileName << "'\n"); 1406cba37ceSTeresa Johnson // Metadata isn't loaded until functions are imported, to minimize 1416cba37ceSTeresa Johnson // the memory overhead. 142a1080ee6STeresa Johnson std::unique_ptr<Module> Result = 143a1080ee6STeresa Johnson getLazyIRFileModule(FileName, Err, Context, 144a1080ee6STeresa Johnson /* ShouldLazyLoadMetadata = */ true); 14542418abaSMehdi Amini if (!Result) { 14642418abaSMehdi Amini Err.print("function-import", errs()); 147d7ad221cSMehdi Amini report_fatal_error("Abort"); 14842418abaSMehdi Amini } 14942418abaSMehdi Amini 15042418abaSMehdi Amini return Result; 15142418abaSMehdi Amini } 15242418abaSMehdi Amini 15301e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one 15401e32130SMehdi Amini /// that fits the \p Threshold. 15501e32130SMehdi Amini /// 15601e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"? 15701e32130SMehdi Amini /// - The smallest: more likely to be inlined. 15801e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized). 15901e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the 16001e32130SMehdi Amini /// number of source modules parsed/linked. 16101e32130SMehdi Amini /// - One that has PGO data attached. 16201e32130SMehdi Amini /// - [insert you fancy metric here] 1632d28f7aaSMehdi Amini static const GlobalValueSummary * 164b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index, 1659667b91bSPeter Collingbourne ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList, 16683aaf358STeresa Johnson unsigned Threshold, StringRef CallerModulePath) { 16701e32130SMehdi Amini auto It = llvm::find_if( 16828e457bcSTeresa Johnson CalleeSummaryList, 16928e457bcSTeresa Johnson [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) { 17028e457bcSTeresa Johnson auto *GVSummary = SummaryPtr.get(); 171eaf5172cSGeorge Rimar if (!Index.isGlobalValueLive(GVSummary)) 172eaf5172cSGeorge Rimar return false; 173eaf5172cSGeorge Rimar 17473305f82STeresa Johnson // For SamplePGO, in computeImportForFunction the OriginalId 17573305f82STeresa Johnson // may have been used to locate the callee summary list (See 17673305f82STeresa Johnson // comment there). 17773305f82STeresa Johnson // The mapping from OriginalId to GUID may return a GUID 17873305f82STeresa Johnson // that corresponds to a static variable. Filter it out here. 17973305f82STeresa Johnson // This can happen when 18073305f82STeresa Johnson // 1) There is a call to a library function which is not defined 18173305f82STeresa Johnson // in the index. 18273305f82STeresa Johnson // 2) There is a static variable with the OriginalGUID identical 18373305f82STeresa Johnson // to the GUID of the library function in 1); 18473305f82STeresa Johnson // When this happens, the logic for SamplePGO kicks in and 18573305f82STeresa Johnson // the static variable in 2) will be found, which needs to be 18673305f82STeresa Johnson // filtered out. 18773305f82STeresa Johnson if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) 18873305f82STeresa Johnson return false; 189f329be83SRafael Espindola if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) 1905b85d8d6SMehdi Amini // There is no point in importing these, we can't inline them 19101e32130SMehdi Amini return false; 1922c719cc1SMehdi Amini 19381bbf742STeresa Johnson auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject()); 1947e88d0daSMehdi Amini 19583aaf358STeresa Johnson // If this is a local function, make sure we import the copy 19683aaf358STeresa Johnson // in the caller's module. The only time a local function can 19783aaf358STeresa Johnson // share an entry in the index is if there is a local with the same name 19883aaf358STeresa Johnson // in another module that had the same source file name (in a different 19983aaf358STeresa Johnson // directory), where each was compiled in their own directory so there 20083aaf358STeresa Johnson // was not distinguishing path. 20183aaf358STeresa Johnson // However, do the import from another module if there is only one 20283aaf358STeresa Johnson // entry in the list - in that case this must be a reference due 20383aaf358STeresa Johnson // to indirect call profile data, since a function pointer can point to 20483aaf358STeresa Johnson // a local in another module. 20583aaf358STeresa Johnson if (GlobalValue::isLocalLinkage(Summary->linkage()) && 20683aaf358STeresa Johnson CalleeSummaryList.size() > 1 && 20783aaf358STeresa Johnson Summary->modulePath() != CallerModulePath) 20883aaf358STeresa Johnson return false; 20983aaf358STeresa Johnson 210f9dc3deaSTeresa Johnson if (Summary->instCount() > Threshold) 211f9dc3deaSTeresa Johnson return false; 212f9dc3deaSTeresa Johnson 213519465b9STeresa Johnson if (Summary->notEligibleToImport()) 214b4e1e829SMehdi Amini return false; 215b4e1e829SMehdi Amini 21601e32130SMehdi Amini return true; 21701e32130SMehdi Amini }); 21828e457bcSTeresa Johnson if (It == CalleeSummaryList.end()) 21901e32130SMehdi Amini return nullptr; 2207e88d0daSMehdi Amini 221f9dc3deaSTeresa Johnson return cast<GlobalValueSummary>(It->get()); 222434e9561SRafael Espindola } 2237e88d0daSMehdi Amini 224e9ea08a0SEugene Zelenko namespace { 225e9ea08a0SEugene Zelenko 226475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */, 227475b51a7STeresa Johnson GlobalValue::GUID>; 22801e32130SMehdi Amini 229e9ea08a0SEugene Zelenko } // anonymous namespace 230e9ea08a0SEugene Zelenko 2311958083dSTeresa Johnson static ValueInfo 2321958083dSTeresa Johnson updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) { 2331958083dSTeresa Johnson if (!VI.getSummaryList().empty()) 2341958083dSTeresa Johnson return VI; 2351958083dSTeresa Johnson // For SamplePGO, the indirect call targets for local functions will 2361958083dSTeresa Johnson // have its original name annotated in profile. We try to find the 2371958083dSTeresa Johnson // corresponding PGOFuncName as the GUID. 2381958083dSTeresa Johnson // FIXME: Consider updating the edges in the graph after building 2391958083dSTeresa Johnson // it, rather than needing to perform this mapping on each walk. 2401958083dSTeresa Johnson auto GUID = Index.getGUIDFromOriginalID(VI.getGUID()); 2411958083dSTeresa Johnson if (GUID == 0) 24228d8a49fSEugene Leviant return ValueInfo(); 2431958083dSTeresa Johnson return Index.getValueInfo(GUID); 2441958083dSTeresa Johnson } 2451958083dSTeresa Johnson 24619e23874SEugene Leviant static void computeImportForReferencedGlobals( 24719e23874SEugene Leviant const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries, 24819e23874SEugene Leviant FunctionImporter::ImportMapTy &ImportList, 24919e23874SEugene Leviant StringMap<FunctionImporter::ExportSetTy> *ExportLists) { 25019e23874SEugene Leviant for (auto &VI : Summary.refs()) { 25119e23874SEugene Leviant if (DefinedGVSummaries.count(VI.getGUID())) { 25219e23874SEugene Leviant DEBUG(dbgs() << "Ref ignored! Target already in destination module.\n"); 25319e23874SEugene Leviant continue; 25419e23874SEugene Leviant } 25519e23874SEugene Leviant 25619e23874SEugene Leviant DEBUG(dbgs() << " ref -> " << VI.getGUID() << "\n"); 25719e23874SEugene Leviant 25819e23874SEugene Leviant for (auto &RefSummary : VI.getSummaryList()) 25919e23874SEugene Leviant if (RefSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind && 26019e23874SEugene Leviant // Don't try to import regular LTO summaries added to dummy module. 26119e23874SEugene Leviant !RefSummary->modulePath().empty() && 26219e23874SEugene Leviant !GlobalValue::isInterposableLinkage(RefSummary->linkage()) && 26319e23874SEugene Leviant RefSummary->refs().empty()) { 26419e23874SEugene Leviant ImportList[RefSummary->modulePath()][VI.getGUID()] = 1; 26519e23874SEugene Leviant if (ExportLists) 26619e23874SEugene Leviant (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID()); 26719e23874SEugene Leviant break; 26819e23874SEugene Leviant } 26919e23874SEugene Leviant } 27019e23874SEugene Leviant } 27119e23874SEugene Leviant 27201e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these 27301e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as 27401e32130SMehdi Amini /// exported from their source module. 27501e32130SMehdi Amini static void computeImportForFunction( 2763255eec1STeresa Johnson const FunctionSummary &Summary, const ModuleSummaryIndex &Index, 277d9830eb7SPiotr Padlewski const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries, 27801e32130SMehdi Amini SmallVectorImpl<EdgeInfo> &Worklist, 2799b490f10SMehdi Amini FunctionImporter::ImportMapTy &ImportList, 280c86af334STeresa Johnson StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 28119e23874SEugene Leviant computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList, 28219e23874SEugene Leviant ExportLists); 283974706ebSTeresa Johnson static int ImportCount = 0; 28401e32130SMehdi Amini for (auto &Edge : Summary.calls()) { 2859667b91bSPeter Collingbourne ValueInfo VI = Edge.first; 2869667b91bSPeter Collingbourne DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold 2879667b91bSPeter Collingbourne << "\n"); 28801e32130SMehdi Amini 289974706ebSTeresa Johnson if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) { 290974706ebSTeresa Johnson DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff 291974706ebSTeresa Johnson << " reached.\n"); 292974706ebSTeresa Johnson continue; 293974706ebSTeresa Johnson } 294974706ebSTeresa Johnson 2951958083dSTeresa Johnson VI = updateValueInfoForIndirectCalls(Index, VI); 2969667b91bSPeter Collingbourne if (!VI) 2979667b91bSPeter Collingbourne continue; 2984a435e08SDehao Chen 2999667b91bSPeter Collingbourne if (DefinedGVSummaries.count(VI.getGUID())) { 30001e32130SMehdi Amini DEBUG(dbgs() << "ignored! Target already in destination module.\n"); 3017e88d0daSMehdi Amini continue; 302d450da32STeresa Johnson } 30340641748SMehdi Amini 304ba72b95fSPiotr Padlewski auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float { 305ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Hot) 306ba72b95fSPiotr Padlewski return ImportHotMultiplier; 307ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Cold) 308ba72b95fSPiotr Padlewski return ImportColdMultiplier; 30964c46574SDehao Chen if (Hotness == CalleeInfo::HotnessType::Critical) 31064c46574SDehao Chen return ImportCriticalMultiplier; 311ba72b95fSPiotr Padlewski return 1.0; 312ba72b95fSPiotr Padlewski }; 313ba72b95fSPiotr Padlewski 314d9830eb7SPiotr Padlewski const auto NewThreshold = 315c73cec84SEaswaran Raman Threshold * GetBonusMultiplier(Edge.second.getHotness()); 316d2869473SPiotr Padlewski 3179667b91bSPeter Collingbourne auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold, 3189667b91bSPeter Collingbourne Summary.modulePath()); 31901e32130SMehdi Amini if (!CalleeSummary) { 32001e32130SMehdi Amini DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n"); 3217e88d0daSMehdi Amini continue; 3227e88d0daSMehdi Amini } 3232f0cc477SDavid Blaikie 3242f0cc477SDavid Blaikie // "Resolve" the summary 32581bbf742STeresa Johnson const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary->getBaseObject()); 3262d28f7aaSMehdi Amini 327d9830eb7SPiotr Padlewski assert(ResolvedCalleeSummary->instCount() <= NewThreshold && 32801e32130SMehdi Amini "selectCallee() didn't honor the threshold"); 32901e32130SMehdi Amini 330d2869473SPiotr Padlewski auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) { 331d2869473SPiotr Padlewski // Adjust the threshold for next level of imported functions. 332d2869473SPiotr Padlewski // The threshold is different for hot callsites because we can then 333d2869473SPiotr Padlewski // inline chains of hot calls. 334d2869473SPiotr Padlewski if (IsHotCallsite) 335d2869473SPiotr Padlewski return Threshold * ImportHotInstrFactor; 336d2869473SPiotr Padlewski return Threshold * ImportInstrFactor; 337d2869473SPiotr Padlewski }; 338d2869473SPiotr Padlewski 339c73cec84SEaswaran Raman bool IsHotCallsite = 340c73cec84SEaswaran Raman Edge.second.getHotness() == CalleeInfo::HotnessType::Hot; 3411b859a23STeresa Johnson const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite); 3421b859a23STeresa Johnson 3431b859a23STeresa Johnson auto ExportModulePath = ResolvedCalleeSummary->modulePath(); 3449667b91bSPeter Collingbourne auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()]; 3451b859a23STeresa Johnson /// Since the traversal of the call graph is DFS, we can revisit a function 3461b859a23STeresa Johnson /// a second time with a higher threshold. In this case, it is added back to 3471b859a23STeresa Johnson /// the worklist with the new threshold. 3481b859a23STeresa Johnson if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) { 3491b859a23STeresa Johnson DEBUG(dbgs() << "ignored! Target was already seen with Threshold " 3501b859a23STeresa Johnson << ProcessedThreshold << "\n"); 3511b859a23STeresa Johnson continue; 3521b859a23STeresa Johnson } 35319f2aa78STeresa Johnson bool PreviouslyImported = ProcessedThreshold != 0; 3541b859a23STeresa Johnson // Mark this function as imported in this module, with the current Threshold 3551b859a23STeresa Johnson ProcessedThreshold = AdjThreshold; 3561b859a23STeresa Johnson 357974706ebSTeresa Johnson ImportCount++; 358974706ebSTeresa Johnson 3591b859a23STeresa Johnson // Make exports in the source module. 3601b859a23STeresa Johnson if (ExportLists) { 3611b859a23STeresa Johnson auto &ExportList = (*ExportLists)[ExportModulePath]; 3629667b91bSPeter Collingbourne ExportList.insert(VI.getGUID()); 36319f2aa78STeresa Johnson if (!PreviouslyImported) { 36419f2aa78STeresa Johnson // This is the first time this function was exported from its source 36519f2aa78STeresa Johnson // module, so mark all functions and globals it references as exported 3661b859a23STeresa Johnson // to the outside if they are defined in the same source module. 367edddca22STeresa Johnson // For efficiency, we unconditionally add all the referenced GUIDs 368edddca22STeresa Johnson // to the ExportList for this module, and will prune out any not 369edddca22STeresa Johnson // defined in the module later in a single pass. 3701b859a23STeresa Johnson for (auto &Edge : ResolvedCalleeSummary->calls()) { 3711b859a23STeresa Johnson auto CalleeGUID = Edge.first.getGUID(); 372edddca22STeresa Johnson ExportList.insert(CalleeGUID); 3731b859a23STeresa Johnson } 3741b859a23STeresa Johnson for (auto &Ref : ResolvedCalleeSummary->refs()) { 3751b859a23STeresa Johnson auto GUID = Ref.getGUID(); 376edddca22STeresa Johnson ExportList.insert(GUID); 3771b859a23STeresa Johnson } 3781b859a23STeresa Johnson } 37919f2aa78STeresa Johnson } 380d2869473SPiotr Padlewski 38101e32130SMehdi Amini // Insert the newly imported function to the worklist. 3829667b91bSPeter Collingbourne Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID()); 383d450da32STeresa Johnson } 384d450da32STeresa Johnson } 385d450da32STeresa Johnson 38601e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports 38701e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from 38801e32130SMehdi Amini /// another module (that may require promotion). 38901e32130SMehdi Amini static void ComputeImportForModule( 390c851d216STeresa Johnson const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index, 3919b490f10SMehdi Amini FunctionImporter::ImportMapTy &ImportList, 39256584bbfSEvgeniy Stepanov StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 39301e32130SMehdi Amini // Worklist contains the list of function imported in this module, for which 39401e32130SMehdi Amini // we will analyse the callees and may import further down the callgraph. 39501e32130SMehdi Amini SmallVector<EdgeInfo, 128> Worklist; 39601e32130SMehdi Amini 39701e32130SMehdi Amini // Populate the worklist with the import for the functions in the current 39801e32130SMehdi Amini // module 39928e457bcSTeresa Johnson for (auto &GVSummary : DefinedGVSummaries) { 40056584bbfSEvgeniy Stepanov if (!Index.isGlobalValueLive(GVSummary.second)) { 4016c475a75STeresa Johnson DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n"); 4026c475a75STeresa Johnson continue; 4036c475a75STeresa Johnson } 404cfbd0892SPeter Collingbourne auto *FuncSummary = 405cfbd0892SPeter Collingbourne dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject()); 4061aafabf7SMehdi Amini if (!FuncSummary) 4071aafabf7SMehdi Amini // Skip import for global variables 4081aafabf7SMehdi Amini continue; 40924524f31SXinliang David Li DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n"); 4102d28f7aaSMehdi Amini computeImportForFunction(*FuncSummary, Index, ImportInstrLimit, 4119b490f10SMehdi Amini DefinedGVSummaries, Worklist, ImportList, 41201e32130SMehdi Amini ExportLists); 41301e32130SMehdi Amini } 41401e32130SMehdi Amini 415d2869473SPiotr Padlewski // Process the newly imported functions and add callees to the worklist. 41642418abaSMehdi Amini while (!Worklist.empty()) { 41701e32130SMehdi Amini auto FuncInfo = Worklist.pop_back_val(); 418475b51a7STeresa Johnson auto *Summary = std::get<0>(FuncInfo); 419475b51a7STeresa Johnson auto Threshold = std::get<1>(FuncInfo); 420475b51a7STeresa Johnson auto GUID = std::get<2>(FuncInfo); 421475b51a7STeresa Johnson 422475b51a7STeresa Johnson // Check if we later added this summary with a higher threshold. 423475b51a7STeresa Johnson // If so, skip this entry. 424475b51a7STeresa Johnson auto ExportModulePath = Summary->modulePath(); 425475b51a7STeresa Johnson auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID]; 426475b51a7STeresa Johnson if (LatestProcessedThreshold > Threshold) 427475b51a7STeresa Johnson continue; 42842418abaSMehdi Amini 4291aafabf7SMehdi Amini computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries, 4309b490f10SMehdi Amini Worklist, ImportList, ExportLists); 431c8c55170SMehdi Amini } 43242418abaSMehdi Amini } 433ffe2e4aaSMehdi Amini 43419e23874SEugene Leviant #ifndef NDEBUG 43519e23874SEugene Leviant static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, 43619e23874SEugene Leviant GlobalValue::GUID G) { 43719e23874SEugene Leviant if (const auto &VI = Index.getValueInfo(G)) { 43819e23874SEugene Leviant auto SL = VI.getSummaryList(); 43919e23874SEugene Leviant if (!SL.empty()) 44019e23874SEugene Leviant return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind; 44119e23874SEugene Leviant } 44219e23874SEugene Leviant return false; 44319e23874SEugene Leviant } 44419e23874SEugene Leviant 44519e23874SEugene Leviant static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; } 44619e23874SEugene Leviant 44719e23874SEugene Leviant static GlobalValue::GUID 44819e23874SEugene Leviant getGUID(const std::pair<const GlobalValue::GUID, unsigned> &P) { 44919e23874SEugene Leviant return P.first; 45019e23874SEugene Leviant } 45119e23874SEugene Leviant 45219e23874SEugene Leviant template <class T> 453*1fc0da48SBenjamin Kramer static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, 454*1fc0da48SBenjamin Kramer T &Cont) { 45519e23874SEugene Leviant unsigned NumGVS = 0; 45619e23874SEugene Leviant for (auto &V : Cont) 45719e23874SEugene Leviant if (isGlobalVarSummary(Index, getGUID(V))) 45819e23874SEugene Leviant ++NumGVS; 45919e23874SEugene Leviant return NumGVS; 46019e23874SEugene Leviant } 46119e23874SEugene Leviant #endif 46219e23874SEugene Leviant 463c86af334STeresa Johnson /// Compute all the import and export for every module using the Index. 46401e32130SMehdi Amini void llvm::ComputeCrossModuleImport( 46501e32130SMehdi Amini const ModuleSummaryIndex &Index, 466c851d216STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 46701e32130SMehdi Amini StringMap<FunctionImporter::ImportMapTy> &ImportLists, 46856584bbfSEvgeniy Stepanov StringMap<FunctionImporter::ExportSetTy> &ExportLists) { 46901e32130SMehdi Amini // For each module that has function defined, compute the import/export lists. 4701aafabf7SMehdi Amini for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { 4719b490f10SMehdi Amini auto &ImportList = ImportLists[DefinedGVSummaries.first()]; 4721aafabf7SMehdi Amini DEBUG(dbgs() << "Computing import for Module '" 4731aafabf7SMehdi Amini << DefinedGVSummaries.first() << "'\n"); 4749b490f10SMehdi Amini ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList, 47556584bbfSEvgeniy Stepanov &ExportLists); 47601e32130SMehdi Amini } 47701e32130SMehdi Amini 478edddca22STeresa Johnson // When computing imports we added all GUIDs referenced by anything 479edddca22STeresa Johnson // imported from the module to its ExportList. Now we prune each ExportList 480edddca22STeresa Johnson // of any not defined in that module. This is more efficient than checking 481edddca22STeresa Johnson // while computing imports because some of the summary lists may be long 482edddca22STeresa Johnson // due to linkonce (comdat) copies. 483edddca22STeresa Johnson for (auto &ELI : ExportLists) { 484edddca22STeresa Johnson const auto &DefinedGVSummaries = 485edddca22STeresa Johnson ModuleToDefinedGVSummaries.lookup(ELI.first()); 486edddca22STeresa Johnson for (auto EI = ELI.second.begin(); EI != ELI.second.end();) { 487edddca22STeresa Johnson if (!DefinedGVSummaries.count(*EI)) 488edddca22STeresa Johnson EI = ELI.second.erase(EI); 489edddca22STeresa Johnson else 490edddca22STeresa Johnson ++EI; 491edddca22STeresa Johnson } 492edddca22STeresa Johnson } 493edddca22STeresa Johnson 49401e32130SMehdi Amini #ifndef NDEBUG 49501e32130SMehdi Amini DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size() 49601e32130SMehdi Amini << " modules:\n"); 49701e32130SMehdi Amini for (auto &ModuleImports : ImportLists) { 49801e32130SMehdi Amini auto ModName = ModuleImports.first(); 49901e32130SMehdi Amini auto &Exports = ExportLists[ModName]; 50019e23874SEugene Leviant unsigned NumGVS = numGlobalVarSummaries(Index, Exports); 50119e23874SEugene Leviant DEBUG(dbgs() << "* Module " << ModName << " exports " 50219e23874SEugene Leviant << Exports.size() - NumGVS << " functions and " << NumGVS 50319e23874SEugene Leviant << " vars. Imports from " 50419e23874SEugene Leviant << ModuleImports.second.size() << " modules.\n"); 50501e32130SMehdi Amini for (auto &Src : ModuleImports.second) { 50601e32130SMehdi Amini auto SrcModName = Src.first(); 50719e23874SEugene Leviant unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 50819e23874SEugene Leviant DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 50919e23874SEugene Leviant << " functions imported from " << SrcModName << "\n"); 51019e23874SEugene Leviant DEBUG(dbgs() << " - " << NumGVSPerMod << " global vars imported from " 51101e32130SMehdi Amini << SrcModName << "\n"); 51201e32130SMehdi Amini } 51301e32130SMehdi Amini } 51401e32130SMehdi Amini #endif 51501e32130SMehdi Amini } 51601e32130SMehdi Amini 51781bbf742STeresa Johnson #ifndef NDEBUG 51819e23874SEugene Leviant static void dumpImportListForModule(const ModuleSummaryIndex &Index, 51919e23874SEugene Leviant StringRef ModulePath, 52081bbf742STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 52181bbf742STeresa Johnson DEBUG(dbgs() << "* Module " << ModulePath << " imports from " 52281bbf742STeresa Johnson << ImportList.size() << " modules.\n"); 52381bbf742STeresa Johnson for (auto &Src : ImportList) { 52481bbf742STeresa Johnson auto SrcModName = Src.first(); 52519e23874SEugene Leviant unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 52619e23874SEugene Leviant DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 52719e23874SEugene Leviant << " functions imported from " << SrcModName << "\n"); 52819e23874SEugene Leviant DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from " 52981bbf742STeresa Johnson << SrcModName << "\n"); 53081bbf742STeresa Johnson } 53181bbf742STeresa Johnson } 53269b2de84STeresa Johnson #endif 53381bbf742STeresa Johnson 534c86af334STeresa Johnson /// Compute all the imports for the given module in the Index. 535c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule( 536c86af334STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 537c86af334STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 538c86af334STeresa Johnson // Collect the list of functions this module defines. 539c86af334STeresa Johnson // GUID -> Summary 540c851d216STeresa Johnson GVSummaryMapTy FunctionSummaryMap; 54128e457bcSTeresa Johnson Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap); 542c86af334STeresa Johnson 543c86af334STeresa Johnson // Compute the import list for this module. 544c86af334STeresa Johnson DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n"); 54528e457bcSTeresa Johnson ComputeImportForModule(FunctionSummaryMap, Index, ImportList); 546c86af334STeresa Johnson 547c86af334STeresa Johnson #ifndef NDEBUG 54819e23874SEugene Leviant dumpImportListForModule(Index, ModulePath, ImportList); 54981bbf742STeresa Johnson #endif 550c86af334STeresa Johnson } 55181bbf742STeresa Johnson 55281bbf742STeresa Johnson // Mark all external summaries in Index for import into the given module. 55381bbf742STeresa Johnson // Used for distributed builds using a distributed index. 55481bbf742STeresa Johnson void llvm::ComputeCrossModuleImportForModuleFromIndex( 55581bbf742STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 55681bbf742STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 55781bbf742STeresa Johnson for (auto &GlobalList : Index) { 55881bbf742STeresa Johnson // Ignore entries for undefined references. 55981bbf742STeresa Johnson if (GlobalList.second.SummaryList.empty()) 56081bbf742STeresa Johnson continue; 56181bbf742STeresa Johnson 56281bbf742STeresa Johnson auto GUID = GlobalList.first; 56381bbf742STeresa Johnson assert(GlobalList.second.SummaryList.size() == 1 && 56481bbf742STeresa Johnson "Expected individual combined index to have one summary per GUID"); 56581bbf742STeresa Johnson auto &Summary = GlobalList.second.SummaryList[0]; 56681bbf742STeresa Johnson // Skip the summaries for the importing module. These are included to 56781bbf742STeresa Johnson // e.g. record required linkage changes. 56881bbf742STeresa Johnson if (Summary->modulePath() == ModulePath) 56981bbf742STeresa Johnson continue; 57081bbf742STeresa Johnson // Doesn't matter what value we plug in to the map, just needs an entry 57181bbf742STeresa Johnson // to provoke importing by thinBackend. 57281bbf742STeresa Johnson ImportList[Summary->modulePath()][GUID] = 1; 57381bbf742STeresa Johnson } 57481bbf742STeresa Johnson #ifndef NDEBUG 57519e23874SEugene Leviant dumpImportListForModule(Index, ModulePath, ImportList); 576c86af334STeresa Johnson #endif 577c86af334STeresa Johnson } 578c86af334STeresa Johnson 57956584bbfSEvgeniy Stepanov void llvm::computeDeadSymbols( 58056584bbfSEvgeniy Stepanov ModuleSummaryIndex &Index, 581eaf5172cSGeorge Rimar const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 582eaf5172cSGeorge Rimar function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) { 58356584bbfSEvgeniy Stepanov assert(!Index.withGlobalValueDeadStripping()); 5846c475a75STeresa Johnson if (!ComputeDead) 58556584bbfSEvgeniy Stepanov return; 5866c475a75STeresa Johnson if (GUIDPreservedSymbols.empty()) 5876c475a75STeresa Johnson // Don't do anything when nothing is live, this is friendly with tests. 58856584bbfSEvgeniy Stepanov return; 58956584bbfSEvgeniy Stepanov unsigned LiveSymbols = 0; 5909667b91bSPeter Collingbourne SmallVector<ValueInfo, 128> Worklist; 5919667b91bSPeter Collingbourne Worklist.reserve(GUIDPreservedSymbols.size() * 2); 5929667b91bSPeter Collingbourne for (auto GUID : GUIDPreservedSymbols) { 5939667b91bSPeter Collingbourne ValueInfo VI = Index.getValueInfo(GUID); 5949667b91bSPeter Collingbourne if (!VI) 5959667b91bSPeter Collingbourne continue; 59656584bbfSEvgeniy Stepanov for (auto &S : VI.getSummaryList()) 59756584bbfSEvgeniy Stepanov S->setLive(true); 5986c475a75STeresa Johnson } 59956584bbfSEvgeniy Stepanov 6006c475a75STeresa Johnson // Add values flagged in the index as live roots to the worklist. 60156584bbfSEvgeniy Stepanov for (const auto &Entry : Index) 60256584bbfSEvgeniy Stepanov for (auto &S : Entry.second.SummaryList) 60356584bbfSEvgeniy Stepanov if (S->isLive()) { 60456584bbfSEvgeniy Stepanov DEBUG(dbgs() << "Live root: " << Entry.first << "\n"); 60528d8a49fSEugene Leviant Worklist.push_back(ValueInfo(/*IsAnalysis=*/false, &Entry)); 60656584bbfSEvgeniy Stepanov ++LiveSymbols; 60756584bbfSEvgeniy Stepanov break; 6086c475a75STeresa Johnson } 6096c475a75STeresa Johnson 61056584bbfSEvgeniy Stepanov // Make value live and add it to the worklist if it was not live before. 61156584bbfSEvgeniy Stepanov auto visit = [&](ValueInfo VI) { 6121958083dSTeresa Johnson // FIXME: If we knew which edges were created for indirect call profiles, 6131958083dSTeresa Johnson // we could skip them here. Any that are live should be reached via 6141958083dSTeresa Johnson // other edges, e.g. reference edges. Otherwise, using a profile collected 6151958083dSTeresa Johnson // on a slightly different binary might provoke preserving, importing 6161958083dSTeresa Johnson // and ultimately promoting calls to functions not linked into this 6171958083dSTeresa Johnson // binary, which increases the binary size unnecessarily. Note that 6181958083dSTeresa Johnson // if this code changes, the importer needs to change so that edges 6191958083dSTeresa Johnson // to functions marked dead are skipped. 6201958083dSTeresa Johnson VI = updateValueInfoForIndirectCalls(Index, VI); 6211958083dSTeresa Johnson if (!VI) 6221958083dSTeresa Johnson return; 62356584bbfSEvgeniy Stepanov for (auto &S : VI.getSummaryList()) 624f625118eSTeresa Johnson if (S->isLive()) 625f625118eSTeresa Johnson return; 626eaf5172cSGeorge Rimar 627aab60006SVlad Tsyrklevich // We only keep live symbols that are known to be non-prevailing if any are 628aab60006SVlad Tsyrklevich // available_externally. Those symbols are discarded later in the 629aab60006SVlad Tsyrklevich // EliminateAvailableExternally pass and setting them to not-live breaks 630aab60006SVlad Tsyrklevich // downstreams users of liveness information (PR36483). 631aab60006SVlad Tsyrklevich if (isPrevailing(VI.getGUID()) == PrevailingType::No) { 632aab60006SVlad Tsyrklevich bool AvailableExternally = false; 633aab60006SVlad Tsyrklevich bool Interposable = false; 634aab60006SVlad Tsyrklevich for (auto &S : VI.getSummaryList()) { 635aab60006SVlad Tsyrklevich if (S->linkage() == GlobalValue::AvailableExternallyLinkage) 636aab60006SVlad Tsyrklevich AvailableExternally = true; 637aab60006SVlad Tsyrklevich else if (GlobalValue::isInterposableLinkage(S->linkage())) 638aab60006SVlad Tsyrklevich Interposable = true; 639aab60006SVlad Tsyrklevich } 640aab60006SVlad Tsyrklevich 641aab60006SVlad Tsyrklevich if (!AvailableExternally) 642eaf5172cSGeorge Rimar return; 643eaf5172cSGeorge Rimar 644aab60006SVlad Tsyrklevich if (Interposable) 645aab60006SVlad Tsyrklevich report_fatal_error("Interposable and available_externally symbol"); 646aab60006SVlad Tsyrklevich } 647aab60006SVlad Tsyrklevich 648f625118eSTeresa Johnson for (auto &S : VI.getSummaryList()) 64956584bbfSEvgeniy Stepanov S->setLive(true); 65056584bbfSEvgeniy Stepanov ++LiveSymbols; 65156584bbfSEvgeniy Stepanov Worklist.push_back(VI); 65256584bbfSEvgeniy Stepanov }; 65356584bbfSEvgeniy Stepanov 6546c475a75STeresa Johnson while (!Worklist.empty()) { 6559667b91bSPeter Collingbourne auto VI = Worklist.pop_back_val(); 6569667b91bSPeter Collingbourne for (auto &Summary : VI.getSummaryList()) { 657cfbd0892SPeter Collingbourne GlobalValueSummary *Base = Summary->getBaseObject(); 658eaf5172cSGeorge Rimar // Set base value live in case it is an alias. 659eaf5172cSGeorge Rimar Base->setLive(true); 660cfbd0892SPeter Collingbourne for (auto Ref : Base->refs()) 66156584bbfSEvgeniy Stepanov visit(Ref); 662cfbd0892SPeter Collingbourne if (auto *FS = dyn_cast<FunctionSummary>(Base)) 66356584bbfSEvgeniy Stepanov for (auto Call : FS->calls()) 66456584bbfSEvgeniy Stepanov visit(Call.first); 6656c475a75STeresa Johnson } 6666c475a75STeresa Johnson } 66756584bbfSEvgeniy Stepanov Index.setWithGlobalValueDeadStripping(); 66856584bbfSEvgeniy Stepanov 66956584bbfSEvgeniy Stepanov unsigned DeadSymbols = Index.size() - LiveSymbols; 67056584bbfSEvgeniy Stepanov DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols 67156584bbfSEvgeniy Stepanov << " symbols Dead \n"); 67256584bbfSEvgeniy Stepanov NumDeadSymbols += DeadSymbols; 67356584bbfSEvgeniy Stepanov NumLiveSymbols += LiveSymbols; 6746c475a75STeresa Johnson } 6756c475a75STeresa Johnson 67684174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of 67784174c37STeresa Johnson /// \p ModulePath. 67884174c37STeresa Johnson void llvm::gatherImportedSummariesForModule( 67984174c37STeresa Johnson StringRef ModulePath, 68084174c37STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 681cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ImportList, 68284174c37STeresa Johnson std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 68384174c37STeresa Johnson // Include all summaries from the importing module. 68484174c37STeresa Johnson ModuleToSummariesForIndex[ModulePath] = 68584174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ModulePath); 68684174c37STeresa Johnson // Include summaries for imports. 68788c491ddSMehdi Amini for (auto &ILI : ImportList) { 68884174c37STeresa Johnson auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()]; 68984174c37STeresa Johnson const auto &DefinedGVSummaries = 69084174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ILI.first()); 69184174c37STeresa Johnson for (auto &GI : ILI.second) { 69284174c37STeresa Johnson const auto &DS = DefinedGVSummaries.find(GI.first); 69384174c37STeresa Johnson assert(DS != DefinedGVSummaries.end() && 69484174c37STeresa Johnson "Expected a defined summary for imported global value"); 69584174c37STeresa Johnson SummariesForIndex[GI.first] = DS->second; 69684174c37STeresa Johnson } 69784174c37STeresa Johnson } 69884174c37STeresa Johnson } 69984174c37STeresa Johnson 7008570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename. 701cdbcbf74SMehdi Amini std::error_code 702cdbcbf74SMehdi Amini llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, 703cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ModuleImports) { 7048570fe47STeresa Johnson std::error_code EC; 7058570fe47STeresa Johnson raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None); 7068570fe47STeresa Johnson if (EC) 7078570fe47STeresa Johnson return EC; 708cdbcbf74SMehdi Amini for (auto &ILI : ModuleImports) 7098570fe47STeresa Johnson ImportsOS << ILI.first() << "\n"; 7108570fe47STeresa Johnson return std::error_code(); 7118570fe47STeresa Johnson } 7128570fe47STeresa Johnson 7135a95c477STeresa Johnson bool llvm::convertToDeclaration(GlobalValue &GV) { 7144566c6dbSTeresa Johnson DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n"); 7154566c6dbSTeresa Johnson if (Function *F = dyn_cast<Function>(&GV)) { 7164566c6dbSTeresa Johnson F->deleteBody(); 7174566c6dbSTeresa Johnson F->clearMetadata(); 7187873669bSPeter Collingbourne F->setComdat(nullptr); 7194566c6dbSTeresa Johnson } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) { 7204566c6dbSTeresa Johnson V->setInitializer(nullptr); 7214566c6dbSTeresa Johnson V->setLinkage(GlobalValue::ExternalLinkage); 7224566c6dbSTeresa Johnson V->clearMetadata(); 7237873669bSPeter Collingbourne V->setComdat(nullptr); 7245a95c477STeresa Johnson } else { 7255a95c477STeresa Johnson GlobalValue *NewGV; 7265a95c477STeresa Johnson if (GV.getValueType()->isFunctionTy()) 7275a95c477STeresa Johnson NewGV = 7285a95c477STeresa Johnson Function::Create(cast<FunctionType>(GV.getValueType()), 7295a95c477STeresa Johnson GlobalValue::ExternalLinkage, "", GV.getParent()); 7305a95c477STeresa Johnson else 7315a95c477STeresa Johnson NewGV = 7325a95c477STeresa Johnson new GlobalVariable(*GV.getParent(), GV.getValueType(), 7335a95c477STeresa Johnson /*isConstant*/ false, GlobalValue::ExternalLinkage, 7345a95c477STeresa Johnson /*init*/ nullptr, "", 7355a95c477STeresa Johnson /*insertbefore*/ nullptr, GV.getThreadLocalMode(), 7365a95c477STeresa Johnson GV.getType()->getAddressSpace()); 7375a95c477STeresa Johnson NewGV->takeName(&GV); 7385a95c477STeresa Johnson GV.replaceAllUsesWith(NewGV); 7395a95c477STeresa Johnson return false; 7405a95c477STeresa Johnson } 7415a95c477STeresa Johnson return true; 742eaf5172cSGeorge Rimar } 7434566c6dbSTeresa Johnson 744eaf5172cSGeorge Rimar /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis. 745eaf5172cSGeorge Rimar void llvm::thinLTOResolveWeakForLinkerModule( 746eaf5172cSGeorge Rimar Module &TheModule, const GVSummaryMapTy &DefinedGlobals) { 74704c9a2d6STeresa Johnson auto updateLinkage = [&](GlobalValue &GV) { 74804c9a2d6STeresa Johnson // See if the global summary analysis computed a new resolved linkage. 74904c9a2d6STeresa Johnson const auto &GS = DefinedGlobals.find(GV.getGUID()); 75004c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) 75104c9a2d6STeresa Johnson return; 75204c9a2d6STeresa Johnson auto NewLinkage = GS->second->linkage(); 75304c9a2d6STeresa Johnson if (NewLinkage == GV.getLinkage()) 75404c9a2d6STeresa Johnson return; 7556a5fbe52SDavide Italiano 7566a5fbe52SDavide Italiano // Switch the linkage to weakany if asked for, e.g. we do this for 7576a5fbe52SDavide Italiano // linker redefined symbols (via --wrap or --defsym). 758f4891d29SDavide Italiano // We record that the visibility should be changed here in `addThinLTO` 759f4891d29SDavide Italiano // as we need access to the resolution vectors for each input file in 760f4891d29SDavide Italiano // order to find which symbols have been redefined. 761f4891d29SDavide Italiano // We may consider reorganizing this code and moving the linkage recording 762f4891d29SDavide Italiano // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex. 7636a5fbe52SDavide Italiano if (NewLinkage == GlobalValue::WeakAnyLinkage) { 7646a5fbe52SDavide Italiano GV.setLinkage(NewLinkage); 7656a5fbe52SDavide Italiano return; 7666a5fbe52SDavide Italiano } 7676a5fbe52SDavide Italiano 7686a5fbe52SDavide Italiano if (!GlobalValue::isWeakForLinker(GV.getLinkage())) 7696a5fbe52SDavide Italiano return; 7704566c6dbSTeresa Johnson // Check for a non-prevailing def that has interposable linkage 7714566c6dbSTeresa Johnson // (e.g. non-odr weak or linkonce). In that case we can't simply 7724566c6dbSTeresa Johnson // convert to available_externally, since it would lose the 7734566c6dbSTeresa Johnson // interposable property and possibly get inlined. Simply drop 7744566c6dbSTeresa Johnson // the definition in that case. 7754566c6dbSTeresa Johnson if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) && 7765a95c477STeresa Johnson GlobalValue::isInterposableLinkage(GV.getLinkage())) { 7775a95c477STeresa Johnson if (!convertToDeclaration(GV)) 7785a95c477STeresa Johnson // FIXME: Change this to collect replaced GVs and later erase 7795a95c477STeresa Johnson // them from the parent module once thinLTOResolveWeakForLinkerGUID is 7805a95c477STeresa Johnson // changed to enable this for aliases. 7815a95c477STeresa Johnson llvm_unreachable("Expected GV to be converted"); 7825a95c477STeresa Johnson } else { 78333ba93c2SSteven Wu // If the original symbols has global unnamed addr and linkonce_odr linkage, 78433ba93c2SSteven Wu // it should be an auto hide symbol. Add hidden visibility to the symbol to 78533ba93c2SSteven Wu // preserve the property. 78633ba93c2SSteven Wu if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() && 78733ba93c2SSteven Wu NewLinkage == GlobalValue::WeakODRLinkage) 78833ba93c2SSteven Wu GV.setVisibility(GlobalValue::HiddenVisibility); 78933ba93c2SSteven Wu 79004c9a2d6STeresa Johnson DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from " 79104c9a2d6STeresa Johnson << GV.getLinkage() << " to " << NewLinkage << "\n"); 79204c9a2d6STeresa Johnson GV.setLinkage(NewLinkage); 7934566c6dbSTeresa Johnson } 7944566c6dbSTeresa Johnson // Remove declarations from comdats, including available_externally 7956107a419STeresa Johnson // as this is a declaration for the linker, and will be dropped eventually. 7966107a419STeresa Johnson // It is illegal for comdats to contain declarations. 7976107a419STeresa Johnson auto *GO = dyn_cast_or_null<GlobalObject>(&GV); 7984566c6dbSTeresa Johnson if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) 7996107a419STeresa Johnson GO->setComdat(nullptr); 80004c9a2d6STeresa Johnson }; 80104c9a2d6STeresa Johnson 80204c9a2d6STeresa Johnson // Process functions and global now 80304c9a2d6STeresa Johnson for (auto &GV : TheModule) 80404c9a2d6STeresa Johnson updateLinkage(GV); 80504c9a2d6STeresa Johnson for (auto &GV : TheModule.globals()) 80604c9a2d6STeresa Johnson updateLinkage(GV); 80704c9a2d6STeresa Johnson for (auto &GV : TheModule.aliases()) 80804c9a2d6STeresa Johnson updateLinkage(GV); 80904c9a2d6STeresa Johnson } 81004c9a2d6STeresa Johnson 81104c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis. 81204c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule, 81304c9a2d6STeresa Johnson const GVSummaryMapTy &DefinedGlobals) { 81404c9a2d6STeresa Johnson // Declare a callback for the internalize pass that will ask for every 81504c9a2d6STeresa Johnson // candidate GlobalValue if it can be internalized or not. 81604c9a2d6STeresa Johnson auto MustPreserveGV = [&](const GlobalValue &GV) -> bool { 81704c9a2d6STeresa Johnson // Lookup the linkage recorded in the summaries during global analysis. 818c3d677f9SPeter Collingbourne auto GS = DefinedGlobals.find(GV.getGUID()); 81904c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) { 82004c9a2d6STeresa Johnson // Must have been promoted (possibly conservatively). Find original 82104c9a2d6STeresa Johnson // name so that we can access the correct summary and see if it can 82204c9a2d6STeresa Johnson // be internalized again. 82304c9a2d6STeresa Johnson // FIXME: Eventually we should control promotion instead of promoting 82404c9a2d6STeresa Johnson // and internalizing again. 82504c9a2d6STeresa Johnson StringRef OrigName = 82604c9a2d6STeresa Johnson ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName()); 82704c9a2d6STeresa Johnson std::string OrigId = GlobalValue::getGlobalIdentifier( 82804c9a2d6STeresa Johnson OrigName, GlobalValue::InternalLinkage, 82904c9a2d6STeresa Johnson TheModule.getSourceFileName()); 830c3d677f9SPeter Collingbourne GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); 8317ab1f692STeresa Johnson if (GS == DefinedGlobals.end()) { 8327ab1f692STeresa Johnson // Also check the original non-promoted non-globalized name. In some 8337ab1f692STeresa Johnson // cases a preempted weak value is linked in as a local copy because 8347ab1f692STeresa Johnson // it is referenced by an alias (IRLinker::linkGlobalValueProto). 8357ab1f692STeresa Johnson // In that case, since it was originally not a local value, it was 8367ab1f692STeresa Johnson // recorded in the index using the original name. 8377ab1f692STeresa Johnson // FIXME: This may not be needed once PR27866 is fixed. 838c3d677f9SPeter Collingbourne GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); 83904c9a2d6STeresa Johnson assert(GS != DefinedGlobals.end()); 8407ab1f692STeresa Johnson } 841c3d677f9SPeter Collingbourne } 842c3d677f9SPeter Collingbourne return !GlobalValue::isLocalLinkage(GS->second->linkage()); 84304c9a2d6STeresa Johnson }; 84404c9a2d6STeresa Johnson 84504c9a2d6STeresa Johnson // FIXME: See if we can just internalize directly here via linkage changes 84604c9a2d6STeresa Johnson // based on the index, rather than invoking internalizeModule. 847e9ea08a0SEugene Zelenko internalizeModule(TheModule, MustPreserveGV); 84804c9a2d6STeresa Johnson } 84904c9a2d6STeresa Johnson 85081bbf742STeresa Johnson /// Make alias a clone of its aliasee. 85181bbf742STeresa Johnson static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) { 85281bbf742STeresa Johnson Function *Fn = cast<Function>(GA->getBaseObject()); 85381bbf742STeresa Johnson 85481bbf742STeresa Johnson ValueToValueMapTy VMap; 85581bbf742STeresa Johnson Function *NewFn = CloneFunction(Fn, VMap); 85681bbf742STeresa Johnson // Clone should use the original alias's linkage and name, and we ensure 85781bbf742STeresa Johnson // all uses of alias instead use the new clone (casted if necessary). 85881bbf742STeresa Johnson NewFn->setLinkage(GA->getLinkage()); 85981bbf742STeresa Johnson GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType())); 86081bbf742STeresa Johnson NewFn->takeName(GA); 86181bbf742STeresa Johnson return NewFn; 86281bbf742STeresa Johnson } 86381bbf742STeresa Johnson 864c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries 865c8c55170SMehdi Amini // index. 8667f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions( 86766043797SAdrian Prantl Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) { 8685411d051SMehdi Amini DEBUG(dbgs() << "Starting import for Module " 869311fef6eSMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 87019e23874SEugene Leviant unsigned ImportedCount = 0, ImportedGVCount = 0; 871c8c55170SMehdi Amini 8726d8f817fSPeter Collingbourne IRMover Mover(DestModule); 8737e88d0daSMehdi Amini // Do the actual import of functions now, one Module at a time 87401e32130SMehdi Amini std::set<StringRef> ModuleNameOrderedList; 87501e32130SMehdi Amini for (auto &FunctionsToImportPerModule : ImportList) { 87601e32130SMehdi Amini ModuleNameOrderedList.insert(FunctionsToImportPerModule.first()); 87701e32130SMehdi Amini } 87801e32130SMehdi Amini for (auto &Name : ModuleNameOrderedList) { 8797e88d0daSMehdi Amini // Get the module for the import 88001e32130SMehdi Amini const auto &FunctionsToImportPerModule = ImportList.find(Name); 88101e32130SMehdi Amini assert(FunctionsToImportPerModule != ImportList.end()); 882d9445c49SPeter Collingbourne Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name); 883d9445c49SPeter Collingbourne if (!SrcModuleOrErr) 884d9445c49SPeter Collingbourne return SrcModuleOrErr.takeError(); 885d9445c49SPeter Collingbourne std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr); 8867e88d0daSMehdi Amini assert(&DestModule.getContext() == &SrcModule->getContext() && 8877e88d0daSMehdi Amini "Context mismatch"); 8887e88d0daSMehdi Amini 8896cba37ceSTeresa Johnson // If modules were created with lazy metadata loading, materialize it 8906cba37ceSTeresa Johnson // now, before linking it (otherwise this will be a noop). 8917f00d0a1SPeter Collingbourne if (Error Err = SrcModule->materializeMetadata()) 8927f00d0a1SPeter Collingbourne return std::move(Err); 893e5a61917STeresa Johnson 89401e32130SMehdi Amini auto &ImportGUIDs = FunctionsToImportPerModule->second; 89501e32130SMehdi Amini // Find the globals to import 8966d8f817fSPeter Collingbourne SetVector<GlobalValue *> GlobalsToImport; 8971f685e01SPiotr Padlewski for (Function &F : *SrcModule) { 8981f685e01SPiotr Padlewski if (!F.hasName()) 8990beb858eSTeresa Johnson continue; 9001f685e01SPiotr Padlewski auto GUID = F.getGUID(); 9010beb858eSTeresa Johnson auto Import = ImportGUIDs.count(GUID); 902aeb1e59bSMehdi Amini DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID 9031f685e01SPiotr Padlewski << " " << F.getName() << " from " 904aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 9050beb858eSTeresa Johnson if (Import) { 9067f00d0a1SPeter Collingbourne if (Error Err = F.materialize()) 9077f00d0a1SPeter Collingbourne return std::move(Err); 9083b776128SPiotr Padlewski if (EnableImportMetadata) { 9096deaa6afSPiotr Padlewski // Add 'thinlto_src_module' metadata for statistics and debugging. 9103b776128SPiotr Padlewski F.setMetadata( 9113b776128SPiotr Padlewski "thinlto_src_module", 912e9ea08a0SEugene Zelenko MDNode::get(DestModule.getContext(), 913e9ea08a0SEugene Zelenko {MDString::get(DestModule.getContext(), 9146deaa6afSPiotr Padlewski SrcModule->getSourceFileName())})); 9153b776128SPiotr Padlewski } 9161f685e01SPiotr Padlewski GlobalsToImport.insert(&F); 91701e32130SMehdi Amini } 91801e32130SMehdi Amini } 9191f685e01SPiotr Padlewski for (GlobalVariable &GV : SrcModule->globals()) { 9202d28f7aaSMehdi Amini if (!GV.hasName()) 9212d28f7aaSMehdi Amini continue; 9222d28f7aaSMehdi Amini auto GUID = GV.getGUID(); 9232d28f7aaSMehdi Amini auto Import = ImportGUIDs.count(GUID); 924aeb1e59bSMehdi Amini DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID 925aeb1e59bSMehdi Amini << " " << GV.getName() << " from " 926aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 9272d28f7aaSMehdi Amini if (Import) { 9287f00d0a1SPeter Collingbourne if (Error Err = GV.materialize()) 9297f00d0a1SPeter Collingbourne return std::move(Err); 93019e23874SEugene Leviant ImportedGVCount += GlobalsToImport.insert(&GV); 9312d28f7aaSMehdi Amini } 9322d28f7aaSMehdi Amini } 9331f685e01SPiotr Padlewski for (GlobalAlias &GA : SrcModule->aliases()) { 9341f685e01SPiotr Padlewski if (!GA.hasName()) 93501e32130SMehdi Amini continue; 9361f685e01SPiotr Padlewski auto GUID = GA.getGUID(); 93781bbf742STeresa Johnson auto Import = ImportGUIDs.count(GUID); 93881bbf742STeresa Johnson DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID 9391f685e01SPiotr Padlewski << " " << GA.getName() << " from " 940aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 94181bbf742STeresa Johnson if (Import) { 94281bbf742STeresa Johnson if (Error Err = GA.materialize()) 94381bbf742STeresa Johnson return std::move(Err); 94481bbf742STeresa Johnson // Import alias as a copy of its aliasee. 94581bbf742STeresa Johnson GlobalObject *Base = GA.getBaseObject(); 94681bbf742STeresa Johnson if (Error Err = Base->materialize()) 94781bbf742STeresa Johnson return std::move(Err); 94881bbf742STeresa Johnson auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA); 94981bbf742STeresa Johnson DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID() 95081bbf742STeresa Johnson << " " << Base->getName() << " from " 95181bbf742STeresa Johnson << SrcModule->getSourceFileName() << "\n"); 95281bbf742STeresa Johnson if (EnableImportMetadata) { 95381bbf742STeresa Johnson // Add 'thinlto_src_module' metadata for statistics and debugging. 95481bbf742STeresa Johnson Fn->setMetadata( 95581bbf742STeresa Johnson "thinlto_src_module", 95681bbf742STeresa Johnson MDNode::get(DestModule.getContext(), 95781bbf742STeresa Johnson {MDString::get(DestModule.getContext(), 95881bbf742STeresa Johnson SrcModule->getSourceFileName())})); 95901e32130SMehdi Amini } 96081bbf742STeresa Johnson GlobalsToImport.insert(Fn); 96181bbf742STeresa Johnson } 96281bbf742STeresa Johnson } 96301e32130SMehdi Amini 96419ef4fadSMehdi Amini // Upgrade debug info after we're done materializing all the globals and we 96519ef4fadSMehdi Amini // have loaded all the required metadata! 96619ef4fadSMehdi Amini UpgradeDebugInfo(*SrcModule); 96719ef4fadSMehdi Amini 9687e88d0daSMehdi Amini // Link in the specified functions. 96901e32130SMehdi Amini if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport)) 9708d05185aSMehdi Amini return true; 9718d05185aSMehdi Amini 972d29478f7STeresa Johnson if (PrintImports) { 973d29478f7STeresa Johnson for (const auto *GV : GlobalsToImport) 974d29478f7STeresa Johnson dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName() 975d29478f7STeresa Johnson << " from " << SrcModule->getSourceFileName() << "\n"; 976d29478f7STeresa Johnson } 977d29478f7STeresa Johnson 9786d8f817fSPeter Collingbourne if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(), 9796d8f817fSPeter Collingbourne [](GlobalValue &, IRMover::ValueAdder) {}, 980e6fd9ff9SPeter Collingbourne /*IsPerformingImport=*/true)) 9817e88d0daSMehdi Amini report_fatal_error("Function Import: link error"); 9827e88d0daSMehdi Amini 98301e32130SMehdi Amini ImportedCount += GlobalsToImport.size(); 9846c475a75STeresa Johnson NumImportedModules++; 9857e88d0daSMehdi Amini } 986e5a61917STeresa Johnson 98719e23874SEugene Leviant NumImportedFunctions += (ImportedCount - ImportedGVCount); 98819e23874SEugene Leviant NumImportedGlobalVars += ImportedGVCount; 989d29478f7STeresa Johnson 99019e23874SEugene Leviant DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount 99119e23874SEugene Leviant << " functions for Module " << DestModule.getModuleIdentifier() 99219e23874SEugene Leviant << "\n"); 99319e23874SEugene Leviant DEBUG(dbgs() << "Imported " << ImportedGVCount 99419e23874SEugene Leviant << " global variables for Module " 995c8c55170SMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 996c8c55170SMehdi Amini return ImportedCount; 99742418abaSMehdi Amini } 99842418abaSMehdi Amini 999598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) { 1000598bd2a2SPeter Collingbourne if (SummaryFile.empty()) 1001598bd2a2SPeter Collingbourne report_fatal_error("error: -function-import requires -summary-file\n"); 10026de481a3SPeter Collingbourne Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr = 10036de481a3SPeter Collingbourne getModuleSummaryIndexForFile(SummaryFile); 10046de481a3SPeter Collingbourne if (!IndexPtrOrErr) { 10056de481a3SPeter Collingbourne logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(), 10066de481a3SPeter Collingbourne "Error loading file '" + SummaryFile + "': "); 100742418abaSMehdi Amini return false; 100842418abaSMehdi Amini } 1009598bd2a2SPeter Collingbourne std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr); 101042418abaSMehdi Amini 1011c86af334STeresa Johnson // First step is collecting the import list. 1012c86af334STeresa Johnson FunctionImporter::ImportMapTy ImportList; 101381bbf742STeresa Johnson // If requested, simply import all functions in the index. This is used 101481bbf742STeresa Johnson // when testing distributed backend handling via the opt tool, when 101581bbf742STeresa Johnson // we have distributed indexes containing exactly the summaries to import. 101681bbf742STeresa Johnson if (ImportAllIndex) 101781bbf742STeresa Johnson ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index, 101881bbf742STeresa Johnson ImportList); 101981bbf742STeresa Johnson else 1020c86af334STeresa Johnson ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index, 1021c86af334STeresa Johnson ImportList); 102201e32130SMehdi Amini 10234fef68cbSTeresa Johnson // Conservatively mark all internal values as promoted. This interface is 10244fef68cbSTeresa Johnson // only used when doing importing via the function importing pass. The pass 10254fef68cbSTeresa Johnson // is only enabled when testing importing via the 'opt' tool, which does 10264fef68cbSTeresa Johnson // not do the ThinLink that would normally determine what values to promote. 10274fef68cbSTeresa Johnson for (auto &I : *Index) { 10289667b91bSPeter Collingbourne for (auto &S : I.second.SummaryList) { 10294fef68cbSTeresa Johnson if (GlobalValue::isLocalLinkage(S->linkage())) 10304fef68cbSTeresa Johnson S->setLinkage(GlobalValue::ExternalLinkage); 10314fef68cbSTeresa Johnson } 10324fef68cbSTeresa Johnson } 10334fef68cbSTeresa Johnson 103401e32130SMehdi Amini // Next we need to promote to global scope and rename any local values that 10351b00f2d9STeresa Johnson // are potentially exported to other modules. 103601e32130SMehdi Amini if (renameModuleForThinLTO(M, *Index, nullptr)) { 10371b00f2d9STeresa Johnson errs() << "Error renaming module\n"; 10381b00f2d9STeresa Johnson return false; 10391b00f2d9STeresa Johnson } 10401b00f2d9STeresa Johnson 104142418abaSMehdi Amini // Perform the import now. 1042d16c8065SMehdi Amini auto ModuleLoader = [&M](StringRef Identifier) { 1043d16c8065SMehdi Amini return loadFile(Identifier, M.getContext()); 1044d16c8065SMehdi Amini }; 10459d2bfc48SRafael Espindola FunctionImporter Importer(*Index, ModuleLoader); 104637e24591SPeter Collingbourne Expected<bool> Result = Importer.importFunctions(M, ImportList); 10477f00d0a1SPeter Collingbourne 10487f00d0a1SPeter Collingbourne // FIXME: Probably need to propagate Errors through the pass manager. 10497f00d0a1SPeter Collingbourne if (!Result) { 10507f00d0a1SPeter Collingbourne logAllUnhandledErrors(Result.takeError(), errs(), 10517f00d0a1SPeter Collingbourne "Error importing module: "); 10527f00d0a1SPeter Collingbourne return false; 10537f00d0a1SPeter Collingbourne } 10547f00d0a1SPeter Collingbourne 10557f00d0a1SPeter Collingbourne return *Result; 105621241571STeresa Johnson } 105721241571STeresa Johnson 105821241571STeresa Johnson namespace { 1059e9ea08a0SEugene Zelenko 106021241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file. 106121241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass { 106221241571STeresa Johnson public: 106321241571STeresa Johnson /// Pass identification, replacement for typeid 106421241571STeresa Johnson static char ID; 106521241571STeresa Johnson 1066e9ea08a0SEugene Zelenko explicit FunctionImportLegacyPass() : ModulePass(ID) {} 1067e9ea08a0SEugene Zelenko 106821241571STeresa Johnson /// Specify pass name for debug output 1069117296c0SMehdi Amini StringRef getPassName() const override { return "Function Importing"; } 107021241571STeresa Johnson 107121241571STeresa Johnson bool runOnModule(Module &M) override { 107221241571STeresa Johnson if (skipModule(M)) 107321241571STeresa Johnson return false; 107421241571STeresa Johnson 1075598bd2a2SPeter Collingbourne return doImportingForModule(M); 107642418abaSMehdi Amini } 107742418abaSMehdi Amini }; 1078e9ea08a0SEugene Zelenko 1079e9ea08a0SEugene Zelenko } // end anonymous namespace 108042418abaSMehdi Amini 108121241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M, 1082fd03ac6aSSean Silva ModuleAnalysisManager &AM) { 1083598bd2a2SPeter Collingbourne if (!doImportingForModule(M)) 108421241571STeresa Johnson return PreservedAnalyses::all(); 108521241571STeresa Johnson 108621241571STeresa Johnson return PreservedAnalyses::none(); 108721241571STeresa Johnson } 108821241571STeresa Johnson 108921241571STeresa Johnson char FunctionImportLegacyPass::ID = 0; 109021241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import", 109142418abaSMehdi Amini "Summary Based Function Import", false, false) 109242418abaSMehdi Amini 109342418abaSMehdi Amini namespace llvm { 1094e9ea08a0SEugene Zelenko 1095598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() { 1096598bd2a2SPeter Collingbourne return new FunctionImportLegacyPass(); 10975fcbdb71STeresa Johnson } 1098e9ea08a0SEugene Zelenko 1099e9ea08a0SEugene Zelenko } // end namespace llvm 1100