142418abaSMehdi Amini //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===// 242418abaSMehdi Amini // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 642418abaSMehdi Amini // 742418abaSMehdi Amini //===----------------------------------------------------------------------===// 842418abaSMehdi Amini // 942418abaSMehdi Amini // This file implements Function import based on summaries. 1042418abaSMehdi Amini // 1142418abaSMehdi Amini //===----------------------------------------------------------------------===// 1242418abaSMehdi Amini 1342418abaSMehdi Amini #include "llvm/Transforms/IPO/FunctionImport.h" 14e9ea08a0SEugene Zelenko #include "llvm/ADT/ArrayRef.h" 15e9ea08a0SEugene Zelenko #include "llvm/ADT/STLExtras.h" 16e9ea08a0SEugene Zelenko #include "llvm/ADT/SetVector.h" 1701e32130SMehdi Amini #include "llvm/ADT/SmallVector.h" 18d29478f7STeresa Johnson #include "llvm/ADT/Statistic.h" 19e9ea08a0SEugene Zelenko #include "llvm/ADT/StringMap.h" 200efed325SSimon Pilgrim #include "llvm/ADT/StringRef.h" 21b040fcc6SCharles Saternos #include "llvm/ADT/StringSet.h" 22c15d60b7SPeter Collingbourne #include "llvm/Bitcode/BitcodeReader.h" 2342418abaSMehdi Amini #include "llvm/IR/AutoUpgrade.h" 2481bbf742STeresa Johnson #include "llvm/IR/Constants.h" 25e9ea08a0SEugene Zelenko #include "llvm/IR/Function.h" 26e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalAlias.h" 27e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalObject.h" 28e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalValue.h" 29e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalVariable.h" 30e9ea08a0SEugene Zelenko #include "llvm/IR/Metadata.h" 3142418abaSMehdi Amini #include "llvm/IR/Module.h" 32e9ea08a0SEugene Zelenko #include "llvm/IR/ModuleSummaryIndex.h" 3342418abaSMehdi Amini #include "llvm/IRReader/IRReader.h" 34e9ea08a0SEugene Zelenko #include "llvm/Linker/IRMover.h" 35e9ea08a0SEugene Zelenko #include "llvm/Object/ModuleSymbolTable.h" 36e9ea08a0SEugene Zelenko #include "llvm/Object/SymbolicFile.h" 37e9ea08a0SEugene Zelenko #include "llvm/Pass.h" 38e9ea08a0SEugene Zelenko #include "llvm/Support/Casting.h" 3942418abaSMehdi Amini #include "llvm/Support/CommandLine.h" 4042418abaSMehdi Amini #include "llvm/Support/Debug.h" 41e9ea08a0SEugene Zelenko #include "llvm/Support/Error.h" 42e9ea08a0SEugene Zelenko #include "llvm/Support/ErrorHandling.h" 43e9ea08a0SEugene Zelenko #include "llvm/Support/FileSystem.h" 4442418abaSMehdi Amini #include "llvm/Support/SourceMgr.h" 45e9ea08a0SEugene Zelenko #include "llvm/Support/raw_ostream.h" 4604c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h" 4781bbf742STeresa Johnson #include "llvm/Transforms/Utils/Cloning.h" 48488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h" 4981bbf742STeresa Johnson #include "llvm/Transforms/Utils/ValueMapper.h" 50e9ea08a0SEugene Zelenko #include <cassert> 51e9ea08a0SEugene Zelenko #include <memory> 52e9ea08a0SEugene Zelenko #include <set> 53e9ea08a0SEugene Zelenko #include <string> 54e9ea08a0SEugene Zelenko #include <system_error> 55e9ea08a0SEugene Zelenko #include <tuple> 56e9ea08a0SEugene Zelenko #include <utility> 577e88d0daSMehdi Amini 5842418abaSMehdi Amini using namespace llvm; 5942418abaSMehdi Amini 60e9ea08a0SEugene Zelenko #define DEBUG_TYPE "function-import" 61e9ea08a0SEugene Zelenko 62d2c234a4STeresa Johnson STATISTIC(NumImportedFunctionsThinLink, 63d2c234a4STeresa Johnson "Number of functions thin link decided to import"); 64d2c234a4STeresa Johnson STATISTIC(NumImportedHotFunctionsThinLink, 65d2c234a4STeresa Johnson "Number of hot functions thin link decided to import"); 66d2c234a4STeresa Johnson STATISTIC(NumImportedCriticalFunctionsThinLink, 67d2c234a4STeresa Johnson "Number of critical functions thin link decided to import"); 68d2c234a4STeresa Johnson STATISTIC(NumImportedGlobalVarsThinLink, 69d2c234a4STeresa Johnson "Number of global variables thin link decided to import"); 70d2c234a4STeresa Johnson STATISTIC(NumImportedFunctions, "Number of functions imported in backend"); 71d2c234a4STeresa Johnson STATISTIC(NumImportedGlobalVars, 72d2c234a4STeresa Johnson "Number of global variables imported in backend"); 736c475a75STeresa Johnson STATISTIC(NumImportedModules, "Number of modules imported from"); 746c475a75STeresa Johnson STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index"); 756c475a75STeresa Johnson STATISTIC(NumLiveSymbols, "Number of live symbols in index"); 76d29478f7STeresa Johnson 7739303619STeresa Johnson /// Limit on instruction count of imported functions. 7839303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit( 7939303619STeresa Johnson "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), 8039303619STeresa Johnson cl::desc("Only import functions with less than N instructions")); 8139303619STeresa Johnson 82974706ebSTeresa Johnson static cl::opt<int> ImportCutoff( 83974706ebSTeresa Johnson "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"), 84974706ebSTeresa Johnson cl::desc("Only import first N functions if N>=0 (default -1)")); 85974706ebSTeresa Johnson 8640641748SMehdi Amini static cl::opt<float> 8740641748SMehdi Amini ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), 8840641748SMehdi Amini cl::Hidden, cl::value_desc("x"), 8940641748SMehdi Amini cl::desc("As we import functions, multiply the " 9040641748SMehdi Amini "`import-instr-limit` threshold by this factor " 9140641748SMehdi Amini "before processing newly imported functions")); 92ba72b95fSPiotr Padlewski 93d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor( 94d2869473SPiotr Padlewski "import-hot-evolution-factor", cl::init(1.0), cl::Hidden, 95d2869473SPiotr Padlewski cl::value_desc("x"), 96d2869473SPiotr Padlewski cl::desc("As we import functions called from hot callsite, multiply the " 97d2869473SPiotr Padlewski "`import-instr-limit` threshold by this factor " 98d2869473SPiotr Padlewski "before processing newly imported functions")); 99d2869473SPiotr Padlewski 100d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier( 1018260d665SDehao Chen "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), 102ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for hot callsites")); 103ba72b95fSPiotr Padlewski 10464c46574SDehao Chen static cl::opt<float> ImportCriticalMultiplier( 10564c46574SDehao Chen "import-critical-multiplier", cl::init(100.0), cl::Hidden, 10664c46574SDehao Chen cl::value_desc("x"), 10764c46574SDehao Chen cl::desc( 10864c46574SDehao Chen "Multiply the `import-instr-limit` threshold for critical callsites")); 10964c46574SDehao Chen 110ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up. 111ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier( 112ba72b95fSPiotr Padlewski "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), 113ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for cold callsites")); 11440641748SMehdi Amini 115d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden, 116d29478f7STeresa Johnson cl::desc("Print imported functions")); 117d29478f7STeresa Johnson 118cb9a82fcSTeresa Johnson static cl::opt<bool> PrintImportFailures( 119cb9a82fcSTeresa Johnson "print-import-failures", cl::init(false), cl::Hidden, 120cb9a82fcSTeresa Johnson cl::desc("Print information for functions rejected for importing")); 121cb9a82fcSTeresa Johnson 1226c475a75STeresa Johnson static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden, 1236c475a75STeresa Johnson cl::desc("Compute dead symbols")); 1246c475a75STeresa Johnson 1253b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata( 1263b776128SPiotr Padlewski "enable-import-metadata", cl::init( 1273b776128SPiotr Padlewski #if !defined(NDEBUG) 1283b776128SPiotr Padlewski true /*Enabled with asserts.*/ 1293b776128SPiotr Padlewski #else 1303b776128SPiotr Padlewski false 1313b776128SPiotr Padlewski #endif 1323b776128SPiotr Padlewski ), 1333b776128SPiotr Padlewski cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'")); 1343b776128SPiotr Padlewski 135e9ea08a0SEugene Zelenko /// Summary file to use for function importing when using -function-import from 136e9ea08a0SEugene Zelenko /// the command line. 137e9ea08a0SEugene Zelenko static cl::opt<std::string> 138e9ea08a0SEugene Zelenko SummaryFile("summary-file", 139e9ea08a0SEugene Zelenko cl::desc("The summary file to use for function importing.")); 140e9ea08a0SEugene Zelenko 14181bbf742STeresa Johnson /// Used when testing importing from distributed indexes via opt 14281bbf742STeresa Johnson // -function-import. 14381bbf742STeresa Johnson static cl::opt<bool> 14481bbf742STeresa Johnson ImportAllIndex("import-all-index", 14581bbf742STeresa Johnson cl::desc("Import all external functions in index.")); 14681bbf742STeresa Johnson 14742418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context. 14842418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName, 14942418abaSMehdi Amini LLVMContext &Context) { 15042418abaSMehdi Amini SMDiagnostic Err; 151d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n"); 1526cba37ceSTeresa Johnson // Metadata isn't loaded until functions are imported, to minimize 1536cba37ceSTeresa Johnson // the memory overhead. 154a1080ee6STeresa Johnson std::unique_ptr<Module> Result = 155a1080ee6STeresa Johnson getLazyIRFileModule(FileName, Err, Context, 156a1080ee6STeresa Johnson /* ShouldLazyLoadMetadata = */ true); 15742418abaSMehdi Amini if (!Result) { 15842418abaSMehdi Amini Err.print("function-import", errs()); 159d7ad221cSMehdi Amini report_fatal_error("Abort"); 16042418abaSMehdi Amini } 16142418abaSMehdi Amini 16242418abaSMehdi Amini return Result; 16342418abaSMehdi Amini } 16442418abaSMehdi Amini 16501e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one 16601e32130SMehdi Amini /// that fits the \p Threshold. 16701e32130SMehdi Amini /// 16801e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"? 16901e32130SMehdi Amini /// - The smallest: more likely to be inlined. 17001e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized). 17101e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the 17201e32130SMehdi Amini /// number of source modules parsed/linked. 17301e32130SMehdi Amini /// - One that has PGO data attached. 17401e32130SMehdi Amini /// - [insert you fancy metric here] 1752d28f7aaSMehdi Amini static const GlobalValueSummary * 176b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index, 1779667b91bSPeter Collingbourne ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList, 178cb9a82fcSTeresa Johnson unsigned Threshold, StringRef CallerModulePath, 179cb9a82fcSTeresa Johnson FunctionImporter::ImportFailureReason &Reason, 180cb9a82fcSTeresa Johnson GlobalValue::GUID GUID) { 181cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::None; 18201e32130SMehdi Amini auto It = llvm::find_if( 18328e457bcSTeresa Johnson CalleeSummaryList, 18428e457bcSTeresa Johnson [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) { 18528e457bcSTeresa Johnson auto *GVSummary = SummaryPtr.get(); 186cb9a82fcSTeresa Johnson if (!Index.isGlobalValueLive(GVSummary)) { 187cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::NotLive; 188eaf5172cSGeorge Rimar return false; 189cb9a82fcSTeresa Johnson } 190eaf5172cSGeorge Rimar 19173305f82STeresa Johnson // For SamplePGO, in computeImportForFunction the OriginalId 19273305f82STeresa Johnson // may have been used to locate the callee summary list (See 19373305f82STeresa Johnson // comment there). 19473305f82STeresa Johnson // The mapping from OriginalId to GUID may return a GUID 19573305f82STeresa Johnson // that corresponds to a static variable. Filter it out here. 19673305f82STeresa Johnson // This can happen when 19773305f82STeresa Johnson // 1) There is a call to a library function which is not defined 19873305f82STeresa Johnson // in the index. 19973305f82STeresa Johnson // 2) There is a static variable with the OriginalGUID identical 20073305f82STeresa Johnson // to the GUID of the library function in 1); 20173305f82STeresa Johnson // When this happens, the logic for SamplePGO kicks in and 20273305f82STeresa Johnson // the static variable in 2) will be found, which needs to be 20373305f82STeresa Johnson // filtered out. 204cb9a82fcSTeresa Johnson if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) { 205cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::GlobalVar; 20673305f82STeresa Johnson return false; 207cb9a82fcSTeresa Johnson } 208cb9a82fcSTeresa Johnson if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) { 209cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::InterposableLinkage; 2105b85d8d6SMehdi Amini // There is no point in importing these, we can't inline them 21101e32130SMehdi Amini return false; 212cb9a82fcSTeresa Johnson } 2132c719cc1SMehdi Amini 21481bbf742STeresa Johnson auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject()); 2157e88d0daSMehdi Amini 21683aaf358STeresa Johnson // If this is a local function, make sure we import the copy 21783aaf358STeresa Johnson // in the caller's module. The only time a local function can 21883aaf358STeresa Johnson // share an entry in the index is if there is a local with the same name 21983aaf358STeresa Johnson // in another module that had the same source file name (in a different 22083aaf358STeresa Johnson // directory), where each was compiled in their own directory so there 22183aaf358STeresa Johnson // was not distinguishing path. 22283aaf358STeresa Johnson // However, do the import from another module if there is only one 22383aaf358STeresa Johnson // entry in the list - in that case this must be a reference due 22483aaf358STeresa Johnson // to indirect call profile data, since a function pointer can point to 22583aaf358STeresa Johnson // a local in another module. 22683aaf358STeresa Johnson if (GlobalValue::isLocalLinkage(Summary->linkage()) && 22783aaf358STeresa Johnson CalleeSummaryList.size() > 1 && 228cb9a82fcSTeresa Johnson Summary->modulePath() != CallerModulePath) { 229cb9a82fcSTeresa Johnson Reason = 230cb9a82fcSTeresa Johnson FunctionImporter::ImportFailureReason::LocalLinkageNotInModule; 23183aaf358STeresa Johnson return false; 232cb9a82fcSTeresa Johnson } 23383aaf358STeresa Johnson 234cb9a82fcSTeresa Johnson if (Summary->instCount() > Threshold) { 235cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::TooLarge; 236f9dc3deaSTeresa Johnson return false; 237cb9a82fcSTeresa Johnson } 238f9dc3deaSTeresa Johnson 239cb397461STeresa Johnson // Skip if it isn't legal to import (e.g. may reference unpromotable 240cb397461STeresa Johnson // locals). 241cb9a82fcSTeresa Johnson if (Summary->notEligibleToImport()) { 242cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::NotEligible; 243b4e1e829SMehdi Amini return false; 244cb9a82fcSTeresa Johnson } 245b4e1e829SMehdi Amini 246cb397461STeresa Johnson // Don't bother importing if we can't inline it anyway. 247cb397461STeresa Johnson if (Summary->fflags().NoInline) { 248cb397461STeresa Johnson Reason = FunctionImporter::ImportFailureReason::NoInline; 249cb397461STeresa Johnson return false; 250cb397461STeresa Johnson } 251cb397461STeresa Johnson 25201e32130SMehdi Amini return true; 25301e32130SMehdi Amini }); 25428e457bcSTeresa Johnson if (It == CalleeSummaryList.end()) 25501e32130SMehdi Amini return nullptr; 2567e88d0daSMehdi Amini 257f9dc3deaSTeresa Johnson return cast<GlobalValueSummary>(It->get()); 258434e9561SRafael Espindola } 2597e88d0daSMehdi Amini 260e9ea08a0SEugene Zelenko namespace { 261e9ea08a0SEugene Zelenko 262475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */, 263475b51a7STeresa Johnson GlobalValue::GUID>; 26401e32130SMehdi Amini 265e9ea08a0SEugene Zelenko } // anonymous namespace 266e9ea08a0SEugene Zelenko 2671958083dSTeresa Johnson static ValueInfo 2681958083dSTeresa Johnson updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) { 2691958083dSTeresa Johnson if (!VI.getSummaryList().empty()) 2701958083dSTeresa Johnson return VI; 2711958083dSTeresa Johnson // For SamplePGO, the indirect call targets for local functions will 2721958083dSTeresa Johnson // have its original name annotated in profile. We try to find the 2731958083dSTeresa Johnson // corresponding PGOFuncName as the GUID. 2741958083dSTeresa Johnson // FIXME: Consider updating the edges in the graph after building 2751958083dSTeresa Johnson // it, rather than needing to perform this mapping on each walk. 2761958083dSTeresa Johnson auto GUID = Index.getGUIDFromOriginalID(VI.getGUID()); 2771958083dSTeresa Johnson if (GUID == 0) 27828d8a49fSEugene Leviant return ValueInfo(); 2791958083dSTeresa Johnson return Index.getValueInfo(GUID); 2801958083dSTeresa Johnson } 2811958083dSTeresa Johnson 28219e23874SEugene Leviant static void computeImportForReferencedGlobals( 28319e23874SEugene Leviant const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries, 28419e23874SEugene Leviant FunctionImporter::ImportMapTy &ImportList, 28519e23874SEugene Leviant StringMap<FunctionImporter::ExportSetTy> *ExportLists) { 28619e23874SEugene Leviant for (auto &VI : Summary.refs()) { 28719e23874SEugene Leviant if (DefinedGVSummaries.count(VI.getGUID())) { 288d34e60caSNicola Zaghen LLVM_DEBUG( 289d34e60caSNicola Zaghen dbgs() << "Ref ignored! Target already in destination module.\n"); 29019e23874SEugene Leviant continue; 29119e23874SEugene Leviant } 29219e23874SEugene Leviant 2937e7b13d0STeresa Johnson LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n"); 29419e23874SEugene Leviant 29593f99962STeresa Johnson // If this is a local variable, make sure we import the copy 29693f99962STeresa Johnson // in the caller's module. The only time a local variable can 29793f99962STeresa Johnson // share an entry in the index is if there is a local with the same name 29893f99962STeresa Johnson // in another module that had the same source file name (in a different 29993f99962STeresa Johnson // directory), where each was compiled in their own directory so there 30093f99962STeresa Johnson // was not distinguishing path. 30193f99962STeresa Johnson auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool { 30293f99962STeresa Johnson return GlobalValue::isLocalLinkage(RefSummary->linkage()) && 30393f99962STeresa Johnson RefSummary->modulePath() != Summary.modulePath(); 30493f99962STeresa Johnson }; 30593f99962STeresa Johnson 30619e23874SEugene Leviant for (auto &RefSummary : VI.getSummaryList()) 307bf46e741SEugene Leviant if (isa<GlobalVarSummary>(RefSummary.get()) && 30893f99962STeresa Johnson canImportGlobalVar(RefSummary.get()) && 30993f99962STeresa Johnson !LocalNotInModule(RefSummary.get())) { 310d2c234a4STeresa Johnson auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID()); 311d2c234a4STeresa Johnson // Only update stat if we haven't already imported this variable. 312d2c234a4STeresa Johnson if (ILI.second) 313d2c234a4STeresa Johnson NumImportedGlobalVarsThinLink++; 31419e23874SEugene Leviant if (ExportLists) 31519e23874SEugene Leviant (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID()); 31619e23874SEugene Leviant break; 31719e23874SEugene Leviant } 31819e23874SEugene Leviant } 31919e23874SEugene Leviant } 32019e23874SEugene Leviant 321cb9a82fcSTeresa Johnson static const char * 322cb9a82fcSTeresa Johnson getFailureName(FunctionImporter::ImportFailureReason Reason) { 323cb9a82fcSTeresa Johnson switch (Reason) { 324cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::None: 325cb9a82fcSTeresa Johnson return "None"; 326cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::GlobalVar: 327cb9a82fcSTeresa Johnson return "GlobalVar"; 328cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::NotLive: 329cb9a82fcSTeresa Johnson return "NotLive"; 330cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::TooLarge: 331cb9a82fcSTeresa Johnson return "TooLarge"; 332cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::InterposableLinkage: 333cb9a82fcSTeresa Johnson return "InterposableLinkage"; 334cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule: 335cb9a82fcSTeresa Johnson return "LocalLinkageNotInModule"; 336cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::NotEligible: 337cb9a82fcSTeresa Johnson return "NotEligible"; 338cb397461STeresa Johnson case FunctionImporter::ImportFailureReason::NoInline: 339cb397461STeresa Johnson return "NoInline"; 340cb9a82fcSTeresa Johnson } 341cb9a82fcSTeresa Johnson llvm_unreachable("invalid reason"); 342cb9a82fcSTeresa Johnson } 343cb9a82fcSTeresa Johnson 34401e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these 34501e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as 34601e32130SMehdi Amini /// exported from their source module. 34701e32130SMehdi Amini static void computeImportForFunction( 3483255eec1STeresa Johnson const FunctionSummary &Summary, const ModuleSummaryIndex &Index, 349d9830eb7SPiotr Padlewski const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries, 35001e32130SMehdi Amini SmallVectorImpl<EdgeInfo> &Worklist, 3519b490f10SMehdi Amini FunctionImporter::ImportMapTy &ImportList, 352d68935c5STeresa Johnson StringMap<FunctionImporter::ExportSetTy> *ExportLists, 353d68935c5STeresa Johnson FunctionImporter::ImportThresholdsTy &ImportThresholds) { 35419e23874SEugene Leviant computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList, 35519e23874SEugene Leviant ExportLists); 356974706ebSTeresa Johnson static int ImportCount = 0; 35701e32130SMehdi Amini for (auto &Edge : Summary.calls()) { 3589667b91bSPeter Collingbourne ValueInfo VI = Edge.first; 3597e7b13d0STeresa Johnson LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold 3607e7b13d0STeresa Johnson << "\n"); 36101e32130SMehdi Amini 362974706ebSTeresa Johnson if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) { 363d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff 364974706ebSTeresa Johnson << " reached.\n"); 365974706ebSTeresa Johnson continue; 366974706ebSTeresa Johnson } 367974706ebSTeresa Johnson 3681958083dSTeresa Johnson VI = updateValueInfoForIndirectCalls(Index, VI); 3699667b91bSPeter Collingbourne if (!VI) 3709667b91bSPeter Collingbourne continue; 3714a435e08SDehao Chen 3729667b91bSPeter Collingbourne if (DefinedGVSummaries.count(VI.getGUID())) { 373d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n"); 3747e88d0daSMehdi Amini continue; 375d450da32STeresa Johnson } 37640641748SMehdi Amini 377ba72b95fSPiotr Padlewski auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float { 378ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Hot) 379ba72b95fSPiotr Padlewski return ImportHotMultiplier; 380ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Cold) 381ba72b95fSPiotr Padlewski return ImportColdMultiplier; 38264c46574SDehao Chen if (Hotness == CalleeInfo::HotnessType::Critical) 38364c46574SDehao Chen return ImportCriticalMultiplier; 384ba72b95fSPiotr Padlewski return 1.0; 385ba72b95fSPiotr Padlewski }; 386ba72b95fSPiotr Padlewski 387d9830eb7SPiotr Padlewski const auto NewThreshold = 388c73cec84SEaswaran Raman Threshold * GetBonusMultiplier(Edge.second.getHotness()); 389d2869473SPiotr Padlewski 390cb9a82fcSTeresa Johnson auto IT = ImportThresholds.insert(std::make_pair( 391cb9a82fcSTeresa Johnson VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr))); 392d68935c5STeresa Johnson bool PreviouslyVisited = !IT.second; 393cb9a82fcSTeresa Johnson auto &ProcessedThreshold = std::get<0>(IT.first->second); 394cb9a82fcSTeresa Johnson auto &CalleeSummary = std::get<1>(IT.first->second); 395cb9a82fcSTeresa Johnson auto &FailureInfo = std::get<2>(IT.first->second); 396d68935c5STeresa Johnson 397d2c234a4STeresa Johnson bool IsHotCallsite = 398d2c234a4STeresa Johnson Edge.second.getHotness() == CalleeInfo::HotnessType::Hot; 399d2c234a4STeresa Johnson bool IsCriticalCallsite = 400d2c234a4STeresa Johnson Edge.second.getHotness() == CalleeInfo::HotnessType::Critical; 401d2c234a4STeresa Johnson 402d68935c5STeresa Johnson const FunctionSummary *ResolvedCalleeSummary = nullptr; 403d68935c5STeresa Johnson if (CalleeSummary) { 404d68935c5STeresa Johnson assert(PreviouslyVisited); 405d68935c5STeresa Johnson // Since the traversal of the call graph is DFS, we can revisit a function 406d68935c5STeresa Johnson // a second time with a higher threshold. In this case, it is added back 407d68935c5STeresa Johnson // to the worklist with the new threshold (so that its own callee chains 408d68935c5STeresa Johnson // can be considered with the higher threshold). 409d68935c5STeresa Johnson if (NewThreshold <= ProcessedThreshold) { 410d68935c5STeresa Johnson LLVM_DEBUG( 411d68935c5STeresa Johnson dbgs() << "ignored! Target was already imported with Threshold " 412d68935c5STeresa Johnson << ProcessedThreshold << "\n"); 413d68935c5STeresa Johnson continue; 414d68935c5STeresa Johnson } 415d68935c5STeresa Johnson // Update with new larger threshold. 416d68935c5STeresa Johnson ProcessedThreshold = NewThreshold; 417d68935c5STeresa Johnson ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary); 418d68935c5STeresa Johnson } else { 419d68935c5STeresa Johnson // If we already rejected importing a callee at the same or higher 420d68935c5STeresa Johnson // threshold, don't waste time calling selectCallee. 421d68935c5STeresa Johnson if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) { 422d68935c5STeresa Johnson LLVM_DEBUG( 423d68935c5STeresa Johnson dbgs() << "ignored! Target was already rejected with Threshold " 424d68935c5STeresa Johnson << ProcessedThreshold << "\n"); 425cb9a82fcSTeresa Johnson if (PrintImportFailures) { 426cb9a82fcSTeresa Johnson assert(FailureInfo && 427cb9a82fcSTeresa Johnson "Expected FailureInfo for previously rejected candidate"); 428cb9a82fcSTeresa Johnson FailureInfo->Attempts++; 429cb9a82fcSTeresa Johnson } 430d68935c5STeresa Johnson continue; 431d68935c5STeresa Johnson } 432d68935c5STeresa Johnson 433cb9a82fcSTeresa Johnson FunctionImporter::ImportFailureReason Reason; 434d68935c5STeresa Johnson CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold, 435cb9a82fcSTeresa Johnson Summary.modulePath(), Reason, VI.getGUID()); 43601e32130SMehdi Amini if (!CalleeSummary) { 437d68935c5STeresa Johnson // Update with new larger threshold if this was a retry (otherwise 438cb9a82fcSTeresa Johnson // we would have already inserted with NewThreshold above). Also 439cb9a82fcSTeresa Johnson // update failure info if requested. 440cb9a82fcSTeresa Johnson if (PreviouslyVisited) { 441d68935c5STeresa Johnson ProcessedThreshold = NewThreshold; 442cb9a82fcSTeresa Johnson if (PrintImportFailures) { 443cb9a82fcSTeresa Johnson assert(FailureInfo && 444cb9a82fcSTeresa Johnson "Expected FailureInfo for previously rejected candidate"); 445cb9a82fcSTeresa Johnson FailureInfo->Reason = Reason; 446cb9a82fcSTeresa Johnson FailureInfo->Attempts++; 447cb9a82fcSTeresa Johnson FailureInfo->MaxHotness = 448cb9a82fcSTeresa Johnson std::max(FailureInfo->MaxHotness, Edge.second.getHotness()); 449cb9a82fcSTeresa Johnson } 450cb9a82fcSTeresa Johnson } else if (PrintImportFailures) { 451cb9a82fcSTeresa Johnson assert(!FailureInfo && 452cb9a82fcSTeresa Johnson "Expected no FailureInfo for newly rejected candidate"); 453*0eaee545SJonas Devlieghere FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>( 454cb9a82fcSTeresa Johnson VI, Edge.second.getHotness(), Reason, 1); 455cb9a82fcSTeresa Johnson } 456d34e60caSNicola Zaghen LLVM_DEBUG( 457d34e60caSNicola Zaghen dbgs() << "ignored! No qualifying callee with summary found.\n"); 4587e88d0daSMehdi Amini continue; 4597e88d0daSMehdi Amini } 4602f0cc477SDavid Blaikie 4612f0cc477SDavid Blaikie // "Resolve" the summary 462d68935c5STeresa Johnson CalleeSummary = CalleeSummary->getBaseObject(); 463d68935c5STeresa Johnson ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary); 4642d28f7aaSMehdi Amini 465d9830eb7SPiotr Padlewski assert(ResolvedCalleeSummary->instCount() <= NewThreshold && 46601e32130SMehdi Amini "selectCallee() didn't honor the threshold"); 46701e32130SMehdi Amini 4681b859a23STeresa Johnson auto ExportModulePath = ResolvedCalleeSummary->modulePath(); 469d68935c5STeresa Johnson auto ILI = ImportList[ExportModulePath].insert(VI.getGUID()); 470d68935c5STeresa Johnson // We previously decided to import this GUID definition if it was already 471d68935c5STeresa Johnson // inserted in the set of imports from the exporting module. 472d68935c5STeresa Johnson bool PreviouslyImported = !ILI.second; 473d2c234a4STeresa Johnson if (!PreviouslyImported) { 474d2c234a4STeresa Johnson NumImportedFunctionsThinLink++; 475d2c234a4STeresa Johnson if (IsHotCallsite) 476d2c234a4STeresa Johnson NumImportedHotFunctionsThinLink++; 477d2c234a4STeresa Johnson if (IsCriticalCallsite) 478d2c234a4STeresa Johnson NumImportedCriticalFunctionsThinLink++; 479d2c234a4STeresa Johnson } 480974706ebSTeresa Johnson 4811b859a23STeresa Johnson // Make exports in the source module. 4821b859a23STeresa Johnson if (ExportLists) { 4831b859a23STeresa Johnson auto &ExportList = (*ExportLists)[ExportModulePath]; 4849667b91bSPeter Collingbourne ExportList.insert(VI.getGUID()); 48519f2aa78STeresa Johnson if (!PreviouslyImported) { 48619f2aa78STeresa Johnson // This is the first time this function was exported from its source 48719f2aa78STeresa Johnson // module, so mark all functions and globals it references as exported 4881b859a23STeresa Johnson // to the outside if they are defined in the same source module. 489edddca22STeresa Johnson // For efficiency, we unconditionally add all the referenced GUIDs 490edddca22STeresa Johnson // to the ExportList for this module, and will prune out any not 491edddca22STeresa Johnson // defined in the module later in a single pass. 4921b859a23STeresa Johnson for (auto &Edge : ResolvedCalleeSummary->calls()) { 4931b859a23STeresa Johnson auto CalleeGUID = Edge.first.getGUID(); 494edddca22STeresa Johnson ExportList.insert(CalleeGUID); 4951b859a23STeresa Johnson } 4961b859a23STeresa Johnson for (auto &Ref : ResolvedCalleeSummary->refs()) { 4971b859a23STeresa Johnson auto GUID = Ref.getGUID(); 498edddca22STeresa Johnson ExportList.insert(GUID); 4991b859a23STeresa Johnson } 5001b859a23STeresa Johnson } 50119f2aa78STeresa Johnson } 502d68935c5STeresa Johnson } 503d68935c5STeresa Johnson 504d68935c5STeresa Johnson auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) { 505d68935c5STeresa Johnson // Adjust the threshold for next level of imported functions. 506d68935c5STeresa Johnson // The threshold is different for hot callsites because we can then 507d68935c5STeresa Johnson // inline chains of hot calls. 508d68935c5STeresa Johnson if (IsHotCallsite) 509d68935c5STeresa Johnson return Threshold * ImportHotInstrFactor; 510d68935c5STeresa Johnson return Threshold * ImportInstrFactor; 511d68935c5STeresa Johnson }; 512d68935c5STeresa Johnson 513d68935c5STeresa Johnson const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite); 514d68935c5STeresa Johnson 515d68935c5STeresa Johnson ImportCount++; 516d2869473SPiotr Padlewski 51701e32130SMehdi Amini // Insert the newly imported function to the worklist. 5189667b91bSPeter Collingbourne Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID()); 519d450da32STeresa Johnson } 520d450da32STeresa Johnson } 521d450da32STeresa Johnson 52201e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports 52301e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from 52401e32130SMehdi Amini /// another module (that may require promotion). 52501e32130SMehdi Amini static void ComputeImportForModule( 526c851d216STeresa Johnson const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index, 527cb9a82fcSTeresa Johnson StringRef ModName, FunctionImporter::ImportMapTy &ImportList, 52856584bbfSEvgeniy Stepanov StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 52901e32130SMehdi Amini // Worklist contains the list of function imported in this module, for which 53001e32130SMehdi Amini // we will analyse the callees and may import further down the callgraph. 53101e32130SMehdi Amini SmallVector<EdgeInfo, 128> Worklist; 532d68935c5STeresa Johnson FunctionImporter::ImportThresholdsTy ImportThresholds; 53301e32130SMehdi Amini 53401e32130SMehdi Amini // Populate the worklist with the import for the functions in the current 53501e32130SMehdi Amini // module 53628e457bcSTeresa Johnson for (auto &GVSummary : DefinedGVSummaries) { 5377e7b13d0STeresa Johnson #ifndef NDEBUG 5387e7b13d0STeresa Johnson // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID 5397e7b13d0STeresa Johnson // so this map look up (and possibly others) can be avoided. 5407e7b13d0STeresa Johnson auto VI = Index.getValueInfo(GVSummary.first); 5417e7b13d0STeresa Johnson #endif 54256584bbfSEvgeniy Stepanov if (!Index.isGlobalValueLive(GVSummary.second)) { 5437e7b13d0STeresa Johnson LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n"); 5446c475a75STeresa Johnson continue; 5456c475a75STeresa Johnson } 546cfbd0892SPeter Collingbourne auto *FuncSummary = 547cfbd0892SPeter Collingbourne dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject()); 5481aafabf7SMehdi Amini if (!FuncSummary) 5491aafabf7SMehdi Amini // Skip import for global variables 5501aafabf7SMehdi Amini continue; 5517e7b13d0STeresa Johnson LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n"); 5522d28f7aaSMehdi Amini computeImportForFunction(*FuncSummary, Index, ImportInstrLimit, 5539b490f10SMehdi Amini DefinedGVSummaries, Worklist, ImportList, 554d68935c5STeresa Johnson ExportLists, ImportThresholds); 55501e32130SMehdi Amini } 55601e32130SMehdi Amini 557d2869473SPiotr Padlewski // Process the newly imported functions and add callees to the worklist. 55842418abaSMehdi Amini while (!Worklist.empty()) { 55901e32130SMehdi Amini auto FuncInfo = Worklist.pop_back_val(); 560475b51a7STeresa Johnson auto *Summary = std::get<0>(FuncInfo); 561475b51a7STeresa Johnson auto Threshold = std::get<1>(FuncInfo); 56242418abaSMehdi Amini 5631aafabf7SMehdi Amini computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries, 564d68935c5STeresa Johnson Worklist, ImportList, ExportLists, 565d68935c5STeresa Johnson ImportThresholds); 566c8c55170SMehdi Amini } 567cb9a82fcSTeresa Johnson 568cb9a82fcSTeresa Johnson // Print stats about functions considered but rejected for importing 569cb9a82fcSTeresa Johnson // when requested. 570cb9a82fcSTeresa Johnson if (PrintImportFailures) { 571cb9a82fcSTeresa Johnson dbgs() << "Missed imports into module " << ModName << "\n"; 572cb9a82fcSTeresa Johnson for (auto &I : ImportThresholds) { 573cb9a82fcSTeresa Johnson auto &ProcessedThreshold = std::get<0>(I.second); 574cb9a82fcSTeresa Johnson auto &CalleeSummary = std::get<1>(I.second); 575cb9a82fcSTeresa Johnson auto &FailureInfo = std::get<2>(I.second); 576cb9a82fcSTeresa Johnson if (CalleeSummary) 577cb9a82fcSTeresa Johnson continue; // We are going to import. 578cb9a82fcSTeresa Johnson assert(FailureInfo); 579cb9a82fcSTeresa Johnson FunctionSummary *FS = nullptr; 580cb9a82fcSTeresa Johnson if (!FailureInfo->VI.getSummaryList().empty()) 581cb9a82fcSTeresa Johnson FS = dyn_cast<FunctionSummary>( 582cb9a82fcSTeresa Johnson FailureInfo->VI.getSummaryList()[0]->getBaseObject()); 583cb9a82fcSTeresa Johnson dbgs() << FailureInfo->VI 584cb9a82fcSTeresa Johnson << ": Reason = " << getFailureName(FailureInfo->Reason) 585cb9a82fcSTeresa Johnson << ", Threshold = " << ProcessedThreshold 586cb9a82fcSTeresa Johnson << ", Size = " << (FS ? (int)FS->instCount() : -1) 587cb9a82fcSTeresa Johnson << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness) 588cb9a82fcSTeresa Johnson << ", Attempts = " << FailureInfo->Attempts << "\n"; 589cb9a82fcSTeresa Johnson } 590cb9a82fcSTeresa Johnson } 59142418abaSMehdi Amini } 592ffe2e4aaSMehdi Amini 59319e23874SEugene Leviant #ifndef NDEBUG 59419e23874SEugene Leviant static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, 59519e23874SEugene Leviant GlobalValue::GUID G) { 59619e23874SEugene Leviant if (const auto &VI = Index.getValueInfo(G)) { 59719e23874SEugene Leviant auto SL = VI.getSummaryList(); 59819e23874SEugene Leviant if (!SL.empty()) 59919e23874SEugene Leviant return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind; 60019e23874SEugene Leviant } 60119e23874SEugene Leviant return false; 60219e23874SEugene Leviant } 60319e23874SEugene Leviant 60419e23874SEugene Leviant static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; } 60519e23874SEugene Leviant 60619e23874SEugene Leviant template <class T> 6071fc0da48SBenjamin Kramer static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, 6081fc0da48SBenjamin Kramer T &Cont) { 60919e23874SEugene Leviant unsigned NumGVS = 0; 61019e23874SEugene Leviant for (auto &V : Cont) 61119e23874SEugene Leviant if (isGlobalVarSummary(Index, getGUID(V))) 61219e23874SEugene Leviant ++NumGVS; 61319e23874SEugene Leviant return NumGVS; 61419e23874SEugene Leviant } 61519e23874SEugene Leviant #endif 61619e23874SEugene Leviant 617c86af334STeresa Johnson /// Compute all the import and export for every module using the Index. 61801e32130SMehdi Amini void llvm::ComputeCrossModuleImport( 61901e32130SMehdi Amini const ModuleSummaryIndex &Index, 620c851d216STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 62101e32130SMehdi Amini StringMap<FunctionImporter::ImportMapTy> &ImportLists, 62256584bbfSEvgeniy Stepanov StringMap<FunctionImporter::ExportSetTy> &ExportLists) { 62301e32130SMehdi Amini // For each module that has function defined, compute the import/export lists. 6241aafabf7SMehdi Amini for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { 6259b490f10SMehdi Amini auto &ImportList = ImportLists[DefinedGVSummaries.first()]; 626d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Computing import for Module '" 6271aafabf7SMehdi Amini << DefinedGVSummaries.first() << "'\n"); 628cb9a82fcSTeresa Johnson ComputeImportForModule(DefinedGVSummaries.second, Index, 629cb9a82fcSTeresa Johnson DefinedGVSummaries.first(), ImportList, 63056584bbfSEvgeniy Stepanov &ExportLists); 63101e32130SMehdi Amini } 63201e32130SMehdi Amini 633edddca22STeresa Johnson // When computing imports we added all GUIDs referenced by anything 634edddca22STeresa Johnson // imported from the module to its ExportList. Now we prune each ExportList 635edddca22STeresa Johnson // of any not defined in that module. This is more efficient than checking 636edddca22STeresa Johnson // while computing imports because some of the summary lists may be long 637edddca22STeresa Johnson // due to linkonce (comdat) copies. 638edddca22STeresa Johnson for (auto &ELI : ExportLists) { 639edddca22STeresa Johnson const auto &DefinedGVSummaries = 640edddca22STeresa Johnson ModuleToDefinedGVSummaries.lookup(ELI.first()); 641edddca22STeresa Johnson for (auto EI = ELI.second.begin(); EI != ELI.second.end();) { 642edddca22STeresa Johnson if (!DefinedGVSummaries.count(*EI)) 643edddca22STeresa Johnson EI = ELI.second.erase(EI); 644edddca22STeresa Johnson else 645edddca22STeresa Johnson ++EI; 646edddca22STeresa Johnson } 647edddca22STeresa Johnson } 648edddca22STeresa Johnson 64901e32130SMehdi Amini #ifndef NDEBUG 650d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size() 65101e32130SMehdi Amini << " modules:\n"); 65201e32130SMehdi Amini for (auto &ModuleImports : ImportLists) { 65301e32130SMehdi Amini auto ModName = ModuleImports.first(); 65401e32130SMehdi Amini auto &Exports = ExportLists[ModName]; 65519e23874SEugene Leviant unsigned NumGVS = numGlobalVarSummaries(Index, Exports); 656d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports " 65719e23874SEugene Leviant << Exports.size() - NumGVS << " functions and " << NumGVS 658d34e60caSNicola Zaghen << " vars. Imports from " << ModuleImports.second.size() 659d34e60caSNicola Zaghen << " modules.\n"); 66001e32130SMehdi Amini for (auto &Src : ModuleImports.second) { 66101e32130SMehdi Amini auto SrcModName = Src.first(); 66219e23874SEugene Leviant unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 663d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 66419e23874SEugene Leviant << " functions imported from " << SrcModName << "\n"); 665d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod 666d34e60caSNicola Zaghen << " global vars imported from " << SrcModName << "\n"); 66701e32130SMehdi Amini } 66801e32130SMehdi Amini } 66901e32130SMehdi Amini #endif 67001e32130SMehdi Amini } 67101e32130SMehdi Amini 67281bbf742STeresa Johnson #ifndef NDEBUG 67319e23874SEugene Leviant static void dumpImportListForModule(const ModuleSummaryIndex &Index, 67419e23874SEugene Leviant StringRef ModulePath, 67581bbf742STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 676d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from " 67781bbf742STeresa Johnson << ImportList.size() << " modules.\n"); 67881bbf742STeresa Johnson for (auto &Src : ImportList) { 67981bbf742STeresa Johnson auto SrcModName = Src.first(); 68019e23874SEugene Leviant unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 681d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 68219e23874SEugene Leviant << " functions imported from " << SrcModName << "\n"); 683d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from " 68481bbf742STeresa Johnson << SrcModName << "\n"); 68581bbf742STeresa Johnson } 68681bbf742STeresa Johnson } 68769b2de84STeresa Johnson #endif 68881bbf742STeresa Johnson 689c86af334STeresa Johnson /// Compute all the imports for the given module in the Index. 690c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule( 691c86af334STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 692c86af334STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 693c86af334STeresa Johnson // Collect the list of functions this module defines. 694c86af334STeresa Johnson // GUID -> Summary 695c851d216STeresa Johnson GVSummaryMapTy FunctionSummaryMap; 69628e457bcSTeresa Johnson Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap); 697c86af334STeresa Johnson 698c86af334STeresa Johnson // Compute the import list for this module. 699d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n"); 700cb9a82fcSTeresa Johnson ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList); 701c86af334STeresa Johnson 702c86af334STeresa Johnson #ifndef NDEBUG 70319e23874SEugene Leviant dumpImportListForModule(Index, ModulePath, ImportList); 70481bbf742STeresa Johnson #endif 705c86af334STeresa Johnson } 70681bbf742STeresa Johnson 70781bbf742STeresa Johnson // Mark all external summaries in Index for import into the given module. 70881bbf742STeresa Johnson // Used for distributed builds using a distributed index. 70981bbf742STeresa Johnson void llvm::ComputeCrossModuleImportForModuleFromIndex( 71081bbf742STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 71181bbf742STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 71281bbf742STeresa Johnson for (auto &GlobalList : Index) { 71381bbf742STeresa Johnson // Ignore entries for undefined references. 71481bbf742STeresa Johnson if (GlobalList.second.SummaryList.empty()) 71581bbf742STeresa Johnson continue; 71681bbf742STeresa Johnson 71781bbf742STeresa Johnson auto GUID = GlobalList.first; 71881bbf742STeresa Johnson assert(GlobalList.second.SummaryList.size() == 1 && 71981bbf742STeresa Johnson "Expected individual combined index to have one summary per GUID"); 72081bbf742STeresa Johnson auto &Summary = GlobalList.second.SummaryList[0]; 72181bbf742STeresa Johnson // Skip the summaries for the importing module. These are included to 72281bbf742STeresa Johnson // e.g. record required linkage changes. 72381bbf742STeresa Johnson if (Summary->modulePath() == ModulePath) 72481bbf742STeresa Johnson continue; 725d68935c5STeresa Johnson // Add an entry to provoke importing by thinBackend. 726d68935c5STeresa Johnson ImportList[Summary->modulePath()].insert(GUID); 72781bbf742STeresa Johnson } 72881bbf742STeresa Johnson #ifndef NDEBUG 72919e23874SEugene Leviant dumpImportListForModule(Index, ModulePath, ImportList); 730c86af334STeresa Johnson #endif 731c86af334STeresa Johnson } 732c86af334STeresa Johnson 73356584bbfSEvgeniy Stepanov void llvm::computeDeadSymbols( 73456584bbfSEvgeniy Stepanov ModuleSummaryIndex &Index, 735eaf5172cSGeorge Rimar const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 736eaf5172cSGeorge Rimar function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) { 73756584bbfSEvgeniy Stepanov assert(!Index.withGlobalValueDeadStripping()); 7386c475a75STeresa Johnson if (!ComputeDead) 73956584bbfSEvgeniy Stepanov return; 7406c475a75STeresa Johnson if (GUIDPreservedSymbols.empty()) 7416c475a75STeresa Johnson // Don't do anything when nothing is live, this is friendly with tests. 74256584bbfSEvgeniy Stepanov return; 74356584bbfSEvgeniy Stepanov unsigned LiveSymbols = 0; 7449667b91bSPeter Collingbourne SmallVector<ValueInfo, 128> Worklist; 7459667b91bSPeter Collingbourne Worklist.reserve(GUIDPreservedSymbols.size() * 2); 7469667b91bSPeter Collingbourne for (auto GUID : GUIDPreservedSymbols) { 7479667b91bSPeter Collingbourne ValueInfo VI = Index.getValueInfo(GUID); 7489667b91bSPeter Collingbourne if (!VI) 7499667b91bSPeter Collingbourne continue; 75056584bbfSEvgeniy Stepanov for (auto &S : VI.getSummaryList()) 75156584bbfSEvgeniy Stepanov S->setLive(true); 7526c475a75STeresa Johnson } 75356584bbfSEvgeniy Stepanov 7546c475a75STeresa Johnson // Add values flagged in the index as live roots to the worklist. 7557e7b13d0STeresa Johnson for (const auto &Entry : Index) { 7567e7b13d0STeresa Johnson auto VI = Index.getValueInfo(Entry); 75756584bbfSEvgeniy Stepanov for (auto &S : Entry.second.SummaryList) 75856584bbfSEvgeniy Stepanov if (S->isLive()) { 7597e7b13d0STeresa Johnson LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n"); 7607e7b13d0STeresa Johnson Worklist.push_back(VI); 76156584bbfSEvgeniy Stepanov ++LiveSymbols; 76256584bbfSEvgeniy Stepanov break; 7636c475a75STeresa Johnson } 7647e7b13d0STeresa Johnson } 7656c475a75STeresa Johnson 76656584bbfSEvgeniy Stepanov // Make value live and add it to the worklist if it was not live before. 76756584bbfSEvgeniy Stepanov auto visit = [&](ValueInfo VI) { 7681958083dSTeresa Johnson // FIXME: If we knew which edges were created for indirect call profiles, 7691958083dSTeresa Johnson // we could skip them here. Any that are live should be reached via 7701958083dSTeresa Johnson // other edges, e.g. reference edges. Otherwise, using a profile collected 7711958083dSTeresa Johnson // on a slightly different binary might provoke preserving, importing 7721958083dSTeresa Johnson // and ultimately promoting calls to functions not linked into this 7731958083dSTeresa Johnson // binary, which increases the binary size unnecessarily. Note that 7741958083dSTeresa Johnson // if this code changes, the importer needs to change so that edges 7751958083dSTeresa Johnson // to functions marked dead are skipped. 7761958083dSTeresa Johnson VI = updateValueInfoForIndirectCalls(Index, VI); 7771958083dSTeresa Johnson if (!VI) 7781958083dSTeresa Johnson return; 77933e3b4b9SXin Tong 7805b2f6a1bSTeresa Johnson if (llvm::any_of(VI.getSummaryList(), 78133e3b4b9SXin Tong [](const std::unique_ptr<llvm::GlobalValueSummary> &S) { 78233e3b4b9SXin Tong return S->isLive(); 78333e3b4b9SXin Tong })) 784f625118eSTeresa Johnson return; 785eaf5172cSGeorge Rimar 786aab60006SVlad Tsyrklevich // We only keep live symbols that are known to be non-prevailing if any are 787bfdad33bSXin Tong // available_externally, linkonceodr, weakodr. Those symbols are discarded 788bfdad33bSXin Tong // later in the EliminateAvailableExternally pass and setting them to 789bfdad33bSXin Tong // not-live could break downstreams users of liveness information (PR36483) 790bfdad33bSXin Tong // or limit optimization opportunities. 791aab60006SVlad Tsyrklevich if (isPrevailing(VI.getGUID()) == PrevailingType::No) { 792bfdad33bSXin Tong bool KeepAliveLinkage = false; 793aab60006SVlad Tsyrklevich bool Interposable = false; 794aab60006SVlad Tsyrklevich for (auto &S : VI.getSummaryList()) { 795bfdad33bSXin Tong if (S->linkage() == GlobalValue::AvailableExternallyLinkage || 796bfdad33bSXin Tong S->linkage() == GlobalValue::WeakODRLinkage || 797bfdad33bSXin Tong S->linkage() == GlobalValue::LinkOnceODRLinkage) 798bfdad33bSXin Tong KeepAliveLinkage = true; 799aab60006SVlad Tsyrklevich else if (GlobalValue::isInterposableLinkage(S->linkage())) 800aab60006SVlad Tsyrklevich Interposable = true; 801aab60006SVlad Tsyrklevich } 802aab60006SVlad Tsyrklevich 803bfdad33bSXin Tong if (!KeepAliveLinkage) 804eaf5172cSGeorge Rimar return; 805eaf5172cSGeorge Rimar 806aab60006SVlad Tsyrklevich if (Interposable) 807bfdad33bSXin Tong report_fatal_error( 808bfdad33bSXin Tong "Interposable and available_externally/linkonce_odr/weak_odr symbol"); 809aab60006SVlad Tsyrklevich } 810aab60006SVlad Tsyrklevich 811f625118eSTeresa Johnson for (auto &S : VI.getSummaryList()) 81256584bbfSEvgeniy Stepanov S->setLive(true); 81356584bbfSEvgeniy Stepanov ++LiveSymbols; 81456584bbfSEvgeniy Stepanov Worklist.push_back(VI); 81556584bbfSEvgeniy Stepanov }; 81656584bbfSEvgeniy Stepanov 8176c475a75STeresa Johnson while (!Worklist.empty()) { 8189667b91bSPeter Collingbourne auto VI = Worklist.pop_back_val(); 8199667b91bSPeter Collingbourne for (auto &Summary : VI.getSummaryList()) { 8205b2f6a1bSTeresa Johnson if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) { 8215b2f6a1bSTeresa Johnson // If this is an alias, visit the aliasee VI to ensure that all copies 8225b2f6a1bSTeresa Johnson // are marked live and it is added to the worklist for further 8235b2f6a1bSTeresa Johnson // processing of its references. 82470ec64cbSTeresa Johnson visit(AS->getAliaseeVI()); 8255b2f6a1bSTeresa Johnson continue; 8265b2f6a1bSTeresa Johnson } 8275b2f6a1bSTeresa Johnson 8285b2f6a1bSTeresa Johnson Summary->setLive(true); 8295b2f6a1bSTeresa Johnson for (auto Ref : Summary->refs()) 83056584bbfSEvgeniy Stepanov visit(Ref); 8315b2f6a1bSTeresa Johnson if (auto *FS = dyn_cast<FunctionSummary>(Summary.get())) 83256584bbfSEvgeniy Stepanov for (auto Call : FS->calls()) 83356584bbfSEvgeniy Stepanov visit(Call.first); 8346c475a75STeresa Johnson } 8356c475a75STeresa Johnson } 83656584bbfSEvgeniy Stepanov Index.setWithGlobalValueDeadStripping(); 83756584bbfSEvgeniy Stepanov 83856584bbfSEvgeniy Stepanov unsigned DeadSymbols = Index.size() - LiveSymbols; 839d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols 84056584bbfSEvgeniy Stepanov << " symbols Dead \n"); 84156584bbfSEvgeniy Stepanov NumDeadSymbols += DeadSymbols; 84256584bbfSEvgeniy Stepanov NumLiveSymbols += LiveSymbols; 8436c475a75STeresa Johnson } 8446c475a75STeresa Johnson 845bf46e741SEugene Leviant // Compute dead symbols and propagate constants in combined index. 846bf46e741SEugene Leviant void llvm::computeDeadSymbolsWithConstProp( 847bf46e741SEugene Leviant ModuleSummaryIndex &Index, 848bf46e741SEugene Leviant const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 849bf46e741SEugene Leviant function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing, 850bf46e741SEugene Leviant bool ImportEnabled) { 851bf46e741SEugene Leviant computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing); 852bf46e741SEugene Leviant if (ImportEnabled) { 8533aef3528SEugene Leviant Index.propagateAttributes(GUIDPreservedSymbols); 854bf46e741SEugene Leviant } else { 8553aef3528SEugene Leviant // If import is disabled we should drop read/write-only attribute 856bf46e741SEugene Leviant // from all summaries to prevent internalization. 857bf46e741SEugene Leviant for (auto &P : Index) 858bf46e741SEugene Leviant for (auto &S : P.second.SummaryList) 8593aef3528SEugene Leviant if (auto *GVS = dyn_cast<GlobalVarSummary>(S.get())) { 860bf46e741SEugene Leviant GVS->setReadOnly(false); 8613aef3528SEugene Leviant GVS->setWriteOnly(false); 8623aef3528SEugene Leviant } 863bf46e741SEugene Leviant } 864bf46e741SEugene Leviant } 865bf46e741SEugene Leviant 86684174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of 86784174c37STeresa Johnson /// \p ModulePath. 86884174c37STeresa Johnson void llvm::gatherImportedSummariesForModule( 86984174c37STeresa Johnson StringRef ModulePath, 87084174c37STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 871cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ImportList, 87284174c37STeresa Johnson std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 87384174c37STeresa Johnson // Include all summaries from the importing module. 87484174c37STeresa Johnson ModuleToSummariesForIndex[ModulePath] = 87584174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ModulePath); 87684174c37STeresa Johnson // Include summaries for imports. 87788c491ddSMehdi Amini for (auto &ILI : ImportList) { 87884174c37STeresa Johnson auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()]; 87984174c37STeresa Johnson const auto &DefinedGVSummaries = 88084174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ILI.first()); 88184174c37STeresa Johnson for (auto &GI : ILI.second) { 882d68935c5STeresa Johnson const auto &DS = DefinedGVSummaries.find(GI); 88384174c37STeresa Johnson assert(DS != DefinedGVSummaries.end() && 88484174c37STeresa Johnson "Expected a defined summary for imported global value"); 885d68935c5STeresa Johnson SummariesForIndex[GI] = DS->second; 88684174c37STeresa Johnson } 88784174c37STeresa Johnson } 88884174c37STeresa Johnson } 88984174c37STeresa Johnson 8908570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename. 891c0320ef4STeresa Johnson std::error_code llvm::EmitImportsFiles( 892c0320ef4STeresa Johnson StringRef ModulePath, StringRef OutputFilename, 893c0320ef4STeresa Johnson const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 8948570fe47STeresa Johnson std::error_code EC; 895d9b948b6SFangrui Song raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None); 8968570fe47STeresa Johnson if (EC) 8978570fe47STeresa Johnson return EC; 898c0320ef4STeresa Johnson for (auto &ILI : ModuleToSummariesForIndex) 899c0320ef4STeresa Johnson // The ModuleToSummariesForIndex map includes an entry for the current 900c0320ef4STeresa Johnson // Module (needed for writing out the index files). We don't want to 901c0320ef4STeresa Johnson // include it in the imports file, however, so filter it out. 902c0320ef4STeresa Johnson if (ILI.first != ModulePath) 903c0320ef4STeresa Johnson ImportsOS << ILI.first << "\n"; 9048570fe47STeresa Johnson return std::error_code(); 9058570fe47STeresa Johnson } 9068570fe47STeresa Johnson 9075a95c477STeresa Johnson bool llvm::convertToDeclaration(GlobalValue &GV) { 908d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() 909d34e60caSNicola Zaghen << "\n"); 9104566c6dbSTeresa Johnson if (Function *F = dyn_cast<Function>(&GV)) { 9114566c6dbSTeresa Johnson F->deleteBody(); 9124566c6dbSTeresa Johnson F->clearMetadata(); 9137873669bSPeter Collingbourne F->setComdat(nullptr); 9144566c6dbSTeresa Johnson } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) { 9154566c6dbSTeresa Johnson V->setInitializer(nullptr); 9164566c6dbSTeresa Johnson V->setLinkage(GlobalValue::ExternalLinkage); 9174566c6dbSTeresa Johnson V->clearMetadata(); 9187873669bSPeter Collingbourne V->setComdat(nullptr); 9195a95c477STeresa Johnson } else { 9205a95c477STeresa Johnson GlobalValue *NewGV; 9215a95c477STeresa Johnson if (GV.getValueType()->isFunctionTy()) 9225a95c477STeresa Johnson NewGV = 9235a95c477STeresa Johnson Function::Create(cast<FunctionType>(GV.getValueType()), 924f920da00SDylan McKay GlobalValue::ExternalLinkage, GV.getAddressSpace(), 925f920da00SDylan McKay "", GV.getParent()); 9265a95c477STeresa Johnson else 9275a95c477STeresa Johnson NewGV = 9285a95c477STeresa Johnson new GlobalVariable(*GV.getParent(), GV.getValueType(), 9295a95c477STeresa Johnson /*isConstant*/ false, GlobalValue::ExternalLinkage, 9305a95c477STeresa Johnson /*init*/ nullptr, "", 9315a95c477STeresa Johnson /*insertbefore*/ nullptr, GV.getThreadLocalMode(), 9325a95c477STeresa Johnson GV.getType()->getAddressSpace()); 9335a95c477STeresa Johnson NewGV->takeName(&GV); 9345a95c477STeresa Johnson GV.replaceAllUsesWith(NewGV); 9355a95c477STeresa Johnson return false; 9365a95c477STeresa Johnson } 9375a95c477STeresa Johnson return true; 938eaf5172cSGeorge Rimar } 9394566c6dbSTeresa Johnson 940e61652a3SPirama Arumuga Nainar /// Fixup prevailing symbol linkages in \p TheModule based on summary analysis. 941e61652a3SPirama Arumuga Nainar void llvm::thinLTOResolvePrevailingInModule( 942eaf5172cSGeorge Rimar Module &TheModule, const GVSummaryMapTy &DefinedGlobals) { 94304c9a2d6STeresa Johnson auto updateLinkage = [&](GlobalValue &GV) { 94404c9a2d6STeresa Johnson // See if the global summary analysis computed a new resolved linkage. 94504c9a2d6STeresa Johnson const auto &GS = DefinedGlobals.find(GV.getGUID()); 94604c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) 94704c9a2d6STeresa Johnson return; 94804c9a2d6STeresa Johnson auto NewLinkage = GS->second->linkage(); 94904c9a2d6STeresa Johnson if (NewLinkage == GV.getLinkage()) 95004c9a2d6STeresa Johnson return; 9516a5fbe52SDavide Italiano 9526a5fbe52SDavide Italiano // Switch the linkage to weakany if asked for, e.g. we do this for 9536a5fbe52SDavide Italiano // linker redefined symbols (via --wrap or --defsym). 954f4891d29SDavide Italiano // We record that the visibility should be changed here in `addThinLTO` 955f4891d29SDavide Italiano // as we need access to the resolution vectors for each input file in 956f4891d29SDavide Italiano // order to find which symbols have been redefined. 957f4891d29SDavide Italiano // We may consider reorganizing this code and moving the linkage recording 958e61652a3SPirama Arumuga Nainar // somewhere else, e.g. in thinLTOResolvePrevailingInIndex. 9596a5fbe52SDavide Italiano if (NewLinkage == GlobalValue::WeakAnyLinkage) { 9606a5fbe52SDavide Italiano GV.setLinkage(NewLinkage); 9616a5fbe52SDavide Italiano return; 9626a5fbe52SDavide Italiano } 9636a5fbe52SDavide Italiano 964e61652a3SPirama Arumuga Nainar if (GlobalValue::isLocalLinkage(GV.getLinkage()) || 965e61652a3SPirama Arumuga Nainar // In case it was dead and already converted to declaration. 966e61652a3SPirama Arumuga Nainar GV.isDeclaration()) 9676a5fbe52SDavide Italiano return; 9684566c6dbSTeresa Johnson // Check for a non-prevailing def that has interposable linkage 9694566c6dbSTeresa Johnson // (e.g. non-odr weak or linkonce). In that case we can't simply 9704566c6dbSTeresa Johnson // convert to available_externally, since it would lose the 9714566c6dbSTeresa Johnson // interposable property and possibly get inlined. Simply drop 9724566c6dbSTeresa Johnson // the definition in that case. 9734566c6dbSTeresa Johnson if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) && 9745a95c477STeresa Johnson GlobalValue::isInterposableLinkage(GV.getLinkage())) { 9755a95c477STeresa Johnson if (!convertToDeclaration(GV)) 9765a95c477STeresa Johnson // FIXME: Change this to collect replaced GVs and later erase 977e61652a3SPirama Arumuga Nainar // them from the parent module once thinLTOResolvePrevailingGUID is 9785a95c477STeresa Johnson // changed to enable this for aliases. 9795a95c477STeresa Johnson llvm_unreachable("Expected GV to be converted"); 9805a95c477STeresa Johnson } else { 98137b80122STeresa Johnson // If all copies of the original symbol had global unnamed addr and 98237b80122STeresa Johnson // linkonce_odr linkage, it should be an auto hide symbol. In that case 98337b80122STeresa Johnson // the thin link would have marked it as CanAutoHide. Add hidden visibility 98437b80122STeresa Johnson // to the symbol to preserve the property. 98537b80122STeresa Johnson if (NewLinkage == GlobalValue::WeakODRLinkage && 98637b80122STeresa Johnson GS->second->canAutoHide()) { 98737b80122STeresa Johnson assert(GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr()); 98833ba93c2SSteven Wu GV.setVisibility(GlobalValue::HiddenVisibility); 98937b80122STeresa Johnson } 99033ba93c2SSteven Wu 991d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() 992d34e60caSNicola Zaghen << "` from " << GV.getLinkage() << " to " << NewLinkage 993d34e60caSNicola Zaghen << "\n"); 99404c9a2d6STeresa Johnson GV.setLinkage(NewLinkage); 9954566c6dbSTeresa Johnson } 9964566c6dbSTeresa Johnson // Remove declarations from comdats, including available_externally 9976107a419STeresa Johnson // as this is a declaration for the linker, and will be dropped eventually. 9986107a419STeresa Johnson // It is illegal for comdats to contain declarations. 9996107a419STeresa Johnson auto *GO = dyn_cast_or_null<GlobalObject>(&GV); 10004566c6dbSTeresa Johnson if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) 10016107a419STeresa Johnson GO->setComdat(nullptr); 100204c9a2d6STeresa Johnson }; 100304c9a2d6STeresa Johnson 100404c9a2d6STeresa Johnson // Process functions and global now 100504c9a2d6STeresa Johnson for (auto &GV : TheModule) 100604c9a2d6STeresa Johnson updateLinkage(GV); 100704c9a2d6STeresa Johnson for (auto &GV : TheModule.globals()) 100804c9a2d6STeresa Johnson updateLinkage(GV); 100904c9a2d6STeresa Johnson for (auto &GV : TheModule.aliases()) 101004c9a2d6STeresa Johnson updateLinkage(GV); 101104c9a2d6STeresa Johnson } 101204c9a2d6STeresa Johnson 101304c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis. 101404c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule, 101504c9a2d6STeresa Johnson const GVSummaryMapTy &DefinedGlobals) { 101604c9a2d6STeresa Johnson // Declare a callback for the internalize pass that will ask for every 101704c9a2d6STeresa Johnson // candidate GlobalValue if it can be internalized or not. 101804c9a2d6STeresa Johnson auto MustPreserveGV = [&](const GlobalValue &GV) -> bool { 101904c9a2d6STeresa Johnson // Lookup the linkage recorded in the summaries during global analysis. 1020c3d677f9SPeter Collingbourne auto GS = DefinedGlobals.find(GV.getGUID()); 102104c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) { 102204c9a2d6STeresa Johnson // Must have been promoted (possibly conservatively). Find original 102304c9a2d6STeresa Johnson // name so that we can access the correct summary and see if it can 102404c9a2d6STeresa Johnson // be internalized again. 102504c9a2d6STeresa Johnson // FIXME: Eventually we should control promotion instead of promoting 102604c9a2d6STeresa Johnson // and internalizing again. 102704c9a2d6STeresa Johnson StringRef OrigName = 102804c9a2d6STeresa Johnson ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName()); 102904c9a2d6STeresa Johnson std::string OrigId = GlobalValue::getGlobalIdentifier( 103004c9a2d6STeresa Johnson OrigName, GlobalValue::InternalLinkage, 103104c9a2d6STeresa Johnson TheModule.getSourceFileName()); 1032c3d677f9SPeter Collingbourne GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); 10337ab1f692STeresa Johnson if (GS == DefinedGlobals.end()) { 10347ab1f692STeresa Johnson // Also check the original non-promoted non-globalized name. In some 10357ab1f692STeresa Johnson // cases a preempted weak value is linked in as a local copy because 10367ab1f692STeresa Johnson // it is referenced by an alias (IRLinker::linkGlobalValueProto). 10377ab1f692STeresa Johnson // In that case, since it was originally not a local value, it was 10387ab1f692STeresa Johnson // recorded in the index using the original name. 10397ab1f692STeresa Johnson // FIXME: This may not be needed once PR27866 is fixed. 1040c3d677f9SPeter Collingbourne GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); 104104c9a2d6STeresa Johnson assert(GS != DefinedGlobals.end()); 10427ab1f692STeresa Johnson } 1043c3d677f9SPeter Collingbourne } 1044c3d677f9SPeter Collingbourne return !GlobalValue::isLocalLinkage(GS->second->linkage()); 104504c9a2d6STeresa Johnson }; 104604c9a2d6STeresa Johnson 104704c9a2d6STeresa Johnson // FIXME: See if we can just internalize directly here via linkage changes 104804c9a2d6STeresa Johnson // based on the index, rather than invoking internalizeModule. 1049e9ea08a0SEugene Zelenko internalizeModule(TheModule, MustPreserveGV); 105004c9a2d6STeresa Johnson } 105104c9a2d6STeresa Johnson 105281bbf742STeresa Johnson /// Make alias a clone of its aliasee. 105381bbf742STeresa Johnson static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) { 105481bbf742STeresa Johnson Function *Fn = cast<Function>(GA->getBaseObject()); 105581bbf742STeresa Johnson 105681bbf742STeresa Johnson ValueToValueMapTy VMap; 105781bbf742STeresa Johnson Function *NewFn = CloneFunction(Fn, VMap); 10585b2088d1STeresa Johnson // Clone should use the original alias's linkage, visibility and name, and we 10595b2088d1STeresa Johnson // ensure all uses of alias instead use the new clone (casted if necessary). 106081bbf742STeresa Johnson NewFn->setLinkage(GA->getLinkage()); 10615b2088d1STeresa Johnson NewFn->setVisibility(GA->getVisibility()); 106281bbf742STeresa Johnson GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType())); 106381bbf742STeresa Johnson NewFn->takeName(GA); 106481bbf742STeresa Johnson return NewFn; 106581bbf742STeresa Johnson } 106681bbf742STeresa Johnson 1067bf46e741SEugene Leviant // Internalize values that we marked with specific attribute 1068bf46e741SEugene Leviant // in processGlobalForThinLTO. 10693aef3528SEugene Leviant static void internalizeGVsAfterImport(Module &M) { 1070bf46e741SEugene Leviant for (auto &GV : M.globals()) 1071bf46e741SEugene Leviant // Skip GVs which have been converted to declarations 1072bf46e741SEugene Leviant // by dropDeadSymbols. 1073bf46e741SEugene Leviant if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) { 1074bf46e741SEugene Leviant GV.setLinkage(GlobalValue::InternalLinkage); 1075bf46e741SEugene Leviant GV.setVisibility(GlobalValue::DefaultVisibility); 1076bf46e741SEugene Leviant } 1077bf46e741SEugene Leviant } 1078bf46e741SEugene Leviant 1079c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries 1080c8c55170SMehdi Amini // index. 10817f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions( 108266043797SAdrian Prantl Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) { 1083d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Starting import for Module " 1084311fef6eSMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 108519e23874SEugene Leviant unsigned ImportedCount = 0, ImportedGVCount = 0; 1086c8c55170SMehdi Amini 10876d8f817fSPeter Collingbourne IRMover Mover(DestModule); 10887e88d0daSMehdi Amini // Do the actual import of functions now, one Module at a time 108901e32130SMehdi Amini std::set<StringRef> ModuleNameOrderedList; 109001e32130SMehdi Amini for (auto &FunctionsToImportPerModule : ImportList) { 109101e32130SMehdi Amini ModuleNameOrderedList.insert(FunctionsToImportPerModule.first()); 109201e32130SMehdi Amini } 109301e32130SMehdi Amini for (auto &Name : ModuleNameOrderedList) { 10947e88d0daSMehdi Amini // Get the module for the import 109501e32130SMehdi Amini const auto &FunctionsToImportPerModule = ImportList.find(Name); 109601e32130SMehdi Amini assert(FunctionsToImportPerModule != ImportList.end()); 1097d9445c49SPeter Collingbourne Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name); 1098d9445c49SPeter Collingbourne if (!SrcModuleOrErr) 1099d9445c49SPeter Collingbourne return SrcModuleOrErr.takeError(); 1100d9445c49SPeter Collingbourne std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr); 11017e88d0daSMehdi Amini assert(&DestModule.getContext() == &SrcModule->getContext() && 11027e88d0daSMehdi Amini "Context mismatch"); 11037e88d0daSMehdi Amini 11046cba37ceSTeresa Johnson // If modules were created with lazy metadata loading, materialize it 11056cba37ceSTeresa Johnson // now, before linking it (otherwise this will be a noop). 11067f00d0a1SPeter Collingbourne if (Error Err = SrcModule->materializeMetadata()) 11077f00d0a1SPeter Collingbourne return std::move(Err); 1108e5a61917STeresa Johnson 110901e32130SMehdi Amini auto &ImportGUIDs = FunctionsToImportPerModule->second; 111001e32130SMehdi Amini // Find the globals to import 11116d8f817fSPeter Collingbourne SetVector<GlobalValue *> GlobalsToImport; 11121f685e01SPiotr Padlewski for (Function &F : *SrcModule) { 11131f685e01SPiotr Padlewski if (!F.hasName()) 11140beb858eSTeresa Johnson continue; 11151f685e01SPiotr Padlewski auto GUID = F.getGUID(); 11160beb858eSTeresa Johnson auto Import = ImportGUIDs.count(GUID); 1117d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " 1118d34e60caSNicola Zaghen << GUID << " " << F.getName() << " from " 1119aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 11200beb858eSTeresa Johnson if (Import) { 11217f00d0a1SPeter Collingbourne if (Error Err = F.materialize()) 11227f00d0a1SPeter Collingbourne return std::move(Err); 11233b776128SPiotr Padlewski if (EnableImportMetadata) { 11246deaa6afSPiotr Padlewski // Add 'thinlto_src_module' metadata for statistics and debugging. 11253b776128SPiotr Padlewski F.setMetadata( 11263b776128SPiotr Padlewski "thinlto_src_module", 1127e9ea08a0SEugene Zelenko MDNode::get(DestModule.getContext(), 1128e9ea08a0SEugene Zelenko {MDString::get(DestModule.getContext(), 11296deaa6afSPiotr Padlewski SrcModule->getSourceFileName())})); 11303b776128SPiotr Padlewski } 11311f685e01SPiotr Padlewski GlobalsToImport.insert(&F); 113201e32130SMehdi Amini } 113301e32130SMehdi Amini } 11341f685e01SPiotr Padlewski for (GlobalVariable &GV : SrcModule->globals()) { 11352d28f7aaSMehdi Amini if (!GV.hasName()) 11362d28f7aaSMehdi Amini continue; 11372d28f7aaSMehdi Amini auto GUID = GV.getGUID(); 11382d28f7aaSMehdi Amini auto Import = ImportGUIDs.count(GUID); 1139d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " 1140d34e60caSNicola Zaghen << GUID << " " << GV.getName() << " from " 1141aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 11422d28f7aaSMehdi Amini if (Import) { 11437f00d0a1SPeter Collingbourne if (Error Err = GV.materialize()) 11447f00d0a1SPeter Collingbourne return std::move(Err); 114519e23874SEugene Leviant ImportedGVCount += GlobalsToImport.insert(&GV); 11462d28f7aaSMehdi Amini } 11472d28f7aaSMehdi Amini } 11481f685e01SPiotr Padlewski for (GlobalAlias &GA : SrcModule->aliases()) { 11491f685e01SPiotr Padlewski if (!GA.hasName()) 115001e32130SMehdi Amini continue; 11511f685e01SPiotr Padlewski auto GUID = GA.getGUID(); 115281bbf742STeresa Johnson auto Import = ImportGUIDs.count(GUID); 1153d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " 1154d34e60caSNicola Zaghen << GUID << " " << GA.getName() << " from " 1155aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 115681bbf742STeresa Johnson if (Import) { 115781bbf742STeresa Johnson if (Error Err = GA.materialize()) 115881bbf742STeresa Johnson return std::move(Err); 115981bbf742STeresa Johnson // Import alias as a copy of its aliasee. 116081bbf742STeresa Johnson GlobalObject *Base = GA.getBaseObject(); 116181bbf742STeresa Johnson if (Error Err = Base->materialize()) 116281bbf742STeresa Johnson return std::move(Err); 116381bbf742STeresa Johnson auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA); 1164d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID() 116581bbf742STeresa Johnson << " " << Base->getName() << " from " 116681bbf742STeresa Johnson << SrcModule->getSourceFileName() << "\n"); 116781bbf742STeresa Johnson if (EnableImportMetadata) { 116881bbf742STeresa Johnson // Add 'thinlto_src_module' metadata for statistics and debugging. 116981bbf742STeresa Johnson Fn->setMetadata( 117081bbf742STeresa Johnson "thinlto_src_module", 117181bbf742STeresa Johnson MDNode::get(DestModule.getContext(), 117281bbf742STeresa Johnson {MDString::get(DestModule.getContext(), 117381bbf742STeresa Johnson SrcModule->getSourceFileName())})); 117401e32130SMehdi Amini } 117581bbf742STeresa Johnson GlobalsToImport.insert(Fn); 117681bbf742STeresa Johnson } 117781bbf742STeresa Johnson } 117801e32130SMehdi Amini 117919ef4fadSMehdi Amini // Upgrade debug info after we're done materializing all the globals and we 118019ef4fadSMehdi Amini // have loaded all the required metadata! 118119ef4fadSMehdi Amini UpgradeDebugInfo(*SrcModule); 118219ef4fadSMehdi Amini 11837e88d0daSMehdi Amini // Link in the specified functions. 118401e32130SMehdi Amini if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport)) 11858d05185aSMehdi Amini return true; 11868d05185aSMehdi Amini 1187d29478f7STeresa Johnson if (PrintImports) { 1188d29478f7STeresa Johnson for (const auto *GV : GlobalsToImport) 1189d29478f7STeresa Johnson dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName() 1190d29478f7STeresa Johnson << " from " << SrcModule->getSourceFileName() << "\n"; 1191d29478f7STeresa Johnson } 1192d29478f7STeresa Johnson 11936d8f817fSPeter Collingbourne if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(), 11946d8f817fSPeter Collingbourne [](GlobalValue &, IRMover::ValueAdder) {}, 1195e6fd9ff9SPeter Collingbourne /*IsPerformingImport=*/true)) 11967e88d0daSMehdi Amini report_fatal_error("Function Import: link error"); 11977e88d0daSMehdi Amini 119801e32130SMehdi Amini ImportedCount += GlobalsToImport.size(); 11996c475a75STeresa Johnson NumImportedModules++; 12007e88d0daSMehdi Amini } 1201e5a61917STeresa Johnson 12023aef3528SEugene Leviant internalizeGVsAfterImport(DestModule); 1203bf46e741SEugene Leviant 120419e23874SEugene Leviant NumImportedFunctions += (ImportedCount - ImportedGVCount); 120519e23874SEugene Leviant NumImportedGlobalVars += ImportedGVCount; 1206d29478f7STeresa Johnson 1207d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount 1208d34e60caSNicola Zaghen << " functions for Module " 1209d34e60caSNicola Zaghen << DestModule.getModuleIdentifier() << "\n"); 1210d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount 121119e23874SEugene Leviant << " global variables for Module " 1212c8c55170SMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 1213c8c55170SMehdi Amini return ImportedCount; 121442418abaSMehdi Amini } 121542418abaSMehdi Amini 1216598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) { 1217598bd2a2SPeter Collingbourne if (SummaryFile.empty()) 1218598bd2a2SPeter Collingbourne report_fatal_error("error: -function-import requires -summary-file\n"); 12196de481a3SPeter Collingbourne Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr = 12206de481a3SPeter Collingbourne getModuleSummaryIndexForFile(SummaryFile); 12216de481a3SPeter Collingbourne if (!IndexPtrOrErr) { 12226de481a3SPeter Collingbourne logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(), 12236de481a3SPeter Collingbourne "Error loading file '" + SummaryFile + "': "); 122442418abaSMehdi Amini return false; 122542418abaSMehdi Amini } 1226598bd2a2SPeter Collingbourne std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr); 122742418abaSMehdi Amini 1228c86af334STeresa Johnson // First step is collecting the import list. 1229c86af334STeresa Johnson FunctionImporter::ImportMapTy ImportList; 123081bbf742STeresa Johnson // If requested, simply import all functions in the index. This is used 123181bbf742STeresa Johnson // when testing distributed backend handling via the opt tool, when 123281bbf742STeresa Johnson // we have distributed indexes containing exactly the summaries to import. 123381bbf742STeresa Johnson if (ImportAllIndex) 123481bbf742STeresa Johnson ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index, 123581bbf742STeresa Johnson ImportList); 123681bbf742STeresa Johnson else 1237c86af334STeresa Johnson ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index, 1238c86af334STeresa Johnson ImportList); 123901e32130SMehdi Amini 12404fef68cbSTeresa Johnson // Conservatively mark all internal values as promoted. This interface is 12414fef68cbSTeresa Johnson // only used when doing importing via the function importing pass. The pass 12424fef68cbSTeresa Johnson // is only enabled when testing importing via the 'opt' tool, which does 12434fef68cbSTeresa Johnson // not do the ThinLink that would normally determine what values to promote. 12444fef68cbSTeresa Johnson for (auto &I : *Index) { 12459667b91bSPeter Collingbourne for (auto &S : I.second.SummaryList) { 12464fef68cbSTeresa Johnson if (GlobalValue::isLocalLinkage(S->linkage())) 12474fef68cbSTeresa Johnson S->setLinkage(GlobalValue::ExternalLinkage); 12484fef68cbSTeresa Johnson } 12494fef68cbSTeresa Johnson } 12504fef68cbSTeresa Johnson 125101e32130SMehdi Amini // Next we need to promote to global scope and rename any local values that 12521b00f2d9STeresa Johnson // are potentially exported to other modules. 125301e32130SMehdi Amini if (renameModuleForThinLTO(M, *Index, nullptr)) { 12541b00f2d9STeresa Johnson errs() << "Error renaming module\n"; 12551b00f2d9STeresa Johnson return false; 12561b00f2d9STeresa Johnson } 12571b00f2d9STeresa Johnson 125842418abaSMehdi Amini // Perform the import now. 1259d16c8065SMehdi Amini auto ModuleLoader = [&M](StringRef Identifier) { 1260d16c8065SMehdi Amini return loadFile(Identifier, M.getContext()); 1261d16c8065SMehdi Amini }; 12629d2bfc48SRafael Espindola FunctionImporter Importer(*Index, ModuleLoader); 126337e24591SPeter Collingbourne Expected<bool> Result = Importer.importFunctions(M, ImportList); 12647f00d0a1SPeter Collingbourne 12657f00d0a1SPeter Collingbourne // FIXME: Probably need to propagate Errors through the pass manager. 12667f00d0a1SPeter Collingbourne if (!Result) { 12677f00d0a1SPeter Collingbourne logAllUnhandledErrors(Result.takeError(), errs(), 12687f00d0a1SPeter Collingbourne "Error importing module: "); 12697f00d0a1SPeter Collingbourne return false; 12707f00d0a1SPeter Collingbourne } 12717f00d0a1SPeter Collingbourne 12727f00d0a1SPeter Collingbourne return *Result; 127321241571STeresa Johnson } 127421241571STeresa Johnson 127521241571STeresa Johnson namespace { 1276e9ea08a0SEugene Zelenko 127721241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file. 127821241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass { 127921241571STeresa Johnson public: 128021241571STeresa Johnson /// Pass identification, replacement for typeid 128121241571STeresa Johnson static char ID; 128221241571STeresa Johnson 1283e9ea08a0SEugene Zelenko explicit FunctionImportLegacyPass() : ModulePass(ID) {} 1284e9ea08a0SEugene Zelenko 128521241571STeresa Johnson /// Specify pass name for debug output 1286117296c0SMehdi Amini StringRef getPassName() const override { return "Function Importing"; } 128721241571STeresa Johnson 128821241571STeresa Johnson bool runOnModule(Module &M) override { 128921241571STeresa Johnson if (skipModule(M)) 129021241571STeresa Johnson return false; 129121241571STeresa Johnson 1292598bd2a2SPeter Collingbourne return doImportingForModule(M); 129342418abaSMehdi Amini } 129442418abaSMehdi Amini }; 1295e9ea08a0SEugene Zelenko 1296e9ea08a0SEugene Zelenko } // end anonymous namespace 129742418abaSMehdi Amini 129821241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M, 1299fd03ac6aSSean Silva ModuleAnalysisManager &AM) { 1300598bd2a2SPeter Collingbourne if (!doImportingForModule(M)) 130121241571STeresa Johnson return PreservedAnalyses::all(); 130221241571STeresa Johnson 130321241571STeresa Johnson return PreservedAnalyses::none(); 130421241571STeresa Johnson } 130521241571STeresa Johnson 130621241571STeresa Johnson char FunctionImportLegacyPass::ID = 0; 130721241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import", 130842418abaSMehdi Amini "Summary Based Function Import", false, false) 130942418abaSMehdi Amini 131042418abaSMehdi Amini namespace llvm { 1311e9ea08a0SEugene Zelenko 1312598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() { 1313598bd2a2SPeter Collingbourne return new FunctionImportLegacyPass(); 13145fcbdb71STeresa Johnson } 1315e9ea08a0SEugene Zelenko 1316e9ea08a0SEugene Zelenko } // end namespace llvm 1317