1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements Function import based on summaries. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/IPO/FunctionImport.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SetVector.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/ADT/StringMap.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/StringSet.h" 23 #include "llvm/Bitcode/BitcodeReader.h" 24 #include "llvm/IR/AutoUpgrade.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/GlobalAlias.h" 28 #include "llvm/IR/GlobalObject.h" 29 #include "llvm/IR/GlobalValue.h" 30 #include "llvm/IR/GlobalVariable.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/ModuleSummaryIndex.h" 34 #include "llvm/IRReader/IRReader.h" 35 #include "llvm/Linker/IRMover.h" 36 #include "llvm/Object/ModuleSymbolTable.h" 37 #include "llvm/Object/SymbolicFile.h" 38 #include "llvm/Pass.h" 39 #include "llvm/Support/Casting.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/Error.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/FileSystem.h" 45 #include "llvm/Support/SourceMgr.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Transforms/IPO/Internalize.h" 48 #include "llvm/Transforms/Utils/Cloning.h" 49 #include "llvm/Transforms/Utils/FunctionImportUtils.h" 50 #include "llvm/Transforms/Utils/ValueMapper.h" 51 #include <cassert> 52 #include <memory> 53 #include <set> 54 #include <string> 55 #include <system_error> 56 #include <tuple> 57 #include <utility> 58 59 using namespace llvm; 60 61 #define DEBUG_TYPE "function-import" 62 63 STATISTIC(NumImportedFunctions, "Number of functions imported"); 64 STATISTIC(NumImportedGlobalVars, "Number of global variables imported"); 65 STATISTIC(NumImportedModules, "Number of modules imported from"); 66 STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index"); 67 STATISTIC(NumLiveSymbols, "Number of live symbols in index"); 68 69 /// Limit on instruction count of imported functions. 70 static cl::opt<unsigned> ImportInstrLimit( 71 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), 72 cl::desc("Only import functions with less than N instructions")); 73 74 static cl::opt<int> ImportCutoff( 75 "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"), 76 cl::desc("Only import first N functions if N>=0 (default -1)")); 77 78 static cl::opt<float> 79 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), 80 cl::Hidden, cl::value_desc("x"), 81 cl::desc("As we import functions, multiply the " 82 "`import-instr-limit` threshold by this factor " 83 "before processing newly imported functions")); 84 85 static cl::opt<float> ImportHotInstrFactor( 86 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden, 87 cl::value_desc("x"), 88 cl::desc("As we import functions called from hot callsite, multiply the " 89 "`import-instr-limit` threshold by this factor " 90 "before processing newly imported functions")); 91 92 static cl::opt<float> ImportHotMultiplier( 93 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), 94 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites")); 95 96 static cl::opt<float> ImportCriticalMultiplier( 97 "import-critical-multiplier", cl::init(100.0), cl::Hidden, 98 cl::value_desc("x"), 99 cl::desc( 100 "Multiply the `import-instr-limit` threshold for critical callsites")); 101 102 // FIXME: This multiplier was not really tuned up. 103 static cl::opt<float> ImportColdMultiplier( 104 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), 105 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites")); 106 107 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden, 108 cl::desc("Print imported functions")); 109 110 static cl::opt<bool> PrintImportFailures( 111 "print-import-failures", cl::init(false), cl::Hidden, 112 cl::desc("Print information for functions rejected for importing")); 113 114 static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden, 115 cl::desc("Compute dead symbols")); 116 117 static cl::opt<bool> EnableImportMetadata( 118 "enable-import-metadata", cl::init( 119 #if !defined(NDEBUG) 120 true /*Enabled with asserts.*/ 121 #else 122 false 123 #endif 124 ), 125 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'")); 126 127 /// Summary file to use for function importing when using -function-import from 128 /// the command line. 129 static cl::opt<std::string> 130 SummaryFile("summary-file", 131 cl::desc("The summary file to use for function importing.")); 132 133 /// Used when testing importing from distributed indexes via opt 134 // -function-import. 135 static cl::opt<bool> 136 ImportAllIndex("import-all-index", 137 cl::desc("Import all external functions in index.")); 138 139 // Load lazily a module from \p FileName in \p Context. 140 static std::unique_ptr<Module> loadFile(const std::string &FileName, 141 LLVMContext &Context) { 142 SMDiagnostic Err; 143 LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n"); 144 // Metadata isn't loaded until functions are imported, to minimize 145 // the memory overhead. 146 std::unique_ptr<Module> Result = 147 getLazyIRFileModule(FileName, Err, Context, 148 /* ShouldLazyLoadMetadata = */ true); 149 if (!Result) { 150 Err.print("function-import", errs()); 151 report_fatal_error("Abort"); 152 } 153 154 return Result; 155 } 156 157 /// Given a list of possible callee implementation for a call site, select one 158 /// that fits the \p Threshold. 159 /// 160 /// FIXME: select "best" instead of first that fits. But what is "best"? 161 /// - The smallest: more likely to be inlined. 162 /// - The one with the least outgoing edges (already well optimized). 163 /// - One from a module already being imported from in order to reduce the 164 /// number of source modules parsed/linked. 165 /// - One that has PGO data attached. 166 /// - [insert you fancy metric here] 167 static const GlobalValueSummary * 168 selectCallee(const ModuleSummaryIndex &Index, 169 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList, 170 unsigned Threshold, StringRef CallerModulePath, 171 FunctionImporter::ImportFailureReason &Reason, 172 GlobalValue::GUID GUID) { 173 Reason = FunctionImporter::ImportFailureReason::None; 174 auto It = llvm::find_if( 175 CalleeSummaryList, 176 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) { 177 auto *GVSummary = SummaryPtr.get(); 178 if (!Index.isGlobalValueLive(GVSummary)) { 179 Reason = FunctionImporter::ImportFailureReason::NotLive; 180 return false; 181 } 182 183 // For SamplePGO, in computeImportForFunction the OriginalId 184 // may have been used to locate the callee summary list (See 185 // comment there). 186 // The mapping from OriginalId to GUID may return a GUID 187 // that corresponds to a static variable. Filter it out here. 188 // This can happen when 189 // 1) There is a call to a library function which is not defined 190 // in the index. 191 // 2) There is a static variable with the OriginalGUID identical 192 // to the GUID of the library function in 1); 193 // When this happens, the logic for SamplePGO kicks in and 194 // the static variable in 2) will be found, which needs to be 195 // filtered out. 196 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) { 197 Reason = FunctionImporter::ImportFailureReason::GlobalVar; 198 return false; 199 } 200 if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) { 201 Reason = FunctionImporter::ImportFailureReason::InterposableLinkage; 202 // There is no point in importing these, we can't inline them 203 return false; 204 } 205 206 auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject()); 207 208 // If this is a local function, make sure we import the copy 209 // in the caller's module. The only time a local function can 210 // share an entry in the index is if there is a local with the same name 211 // in another module that had the same source file name (in a different 212 // directory), where each was compiled in their own directory so there 213 // was not distinguishing path. 214 // However, do the import from another module if there is only one 215 // entry in the list - in that case this must be a reference due 216 // to indirect call profile data, since a function pointer can point to 217 // a local in another module. 218 if (GlobalValue::isLocalLinkage(Summary->linkage()) && 219 CalleeSummaryList.size() > 1 && 220 Summary->modulePath() != CallerModulePath) { 221 Reason = 222 FunctionImporter::ImportFailureReason::LocalLinkageNotInModule; 223 return false; 224 } 225 226 if (Summary->instCount() > Threshold) { 227 Reason = FunctionImporter::ImportFailureReason::TooLarge; 228 return false; 229 } 230 231 if (Summary->notEligibleToImport()) { 232 Reason = FunctionImporter::ImportFailureReason::NotEligible; 233 return false; 234 } 235 236 return true; 237 }); 238 if (It == CalleeSummaryList.end()) 239 return nullptr; 240 241 return cast<GlobalValueSummary>(It->get()); 242 } 243 244 namespace { 245 246 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */, 247 GlobalValue::GUID>; 248 249 } // anonymous namespace 250 251 static ValueInfo 252 updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) { 253 if (!VI.getSummaryList().empty()) 254 return VI; 255 // For SamplePGO, the indirect call targets for local functions will 256 // have its original name annotated in profile. We try to find the 257 // corresponding PGOFuncName as the GUID. 258 // FIXME: Consider updating the edges in the graph after building 259 // it, rather than needing to perform this mapping on each walk. 260 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID()); 261 if (GUID == 0) 262 return ValueInfo(); 263 return Index.getValueInfo(GUID); 264 } 265 266 static void computeImportForReferencedGlobals( 267 const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries, 268 FunctionImporter::ImportMapTy &ImportList, 269 StringMap<FunctionImporter::ExportSetTy> *ExportLists) { 270 for (auto &VI : Summary.refs()) { 271 if (DefinedGVSummaries.count(VI.getGUID())) { 272 LLVM_DEBUG( 273 dbgs() << "Ref ignored! Target already in destination module.\n"); 274 continue; 275 } 276 277 LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n"); 278 279 for (auto &RefSummary : VI.getSummaryList()) 280 if (RefSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind && 281 // Don't try to import regular LTO summaries added to dummy module. 282 !RefSummary->modulePath().empty() && 283 !GlobalValue::isInterposableLinkage(RefSummary->linkage()) && 284 RefSummary->refs().empty()) { 285 ImportList[RefSummary->modulePath()].insert(VI.getGUID()); 286 if (ExportLists) 287 (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID()); 288 break; 289 } 290 } 291 } 292 293 static const char * 294 getFailureName(FunctionImporter::ImportFailureReason Reason) { 295 switch (Reason) { 296 case FunctionImporter::ImportFailureReason::None: 297 return "None"; 298 case FunctionImporter::ImportFailureReason::GlobalVar: 299 return "GlobalVar"; 300 case FunctionImporter::ImportFailureReason::NotLive: 301 return "NotLive"; 302 case FunctionImporter::ImportFailureReason::TooLarge: 303 return "TooLarge"; 304 case FunctionImporter::ImportFailureReason::InterposableLinkage: 305 return "InterposableLinkage"; 306 case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule: 307 return "LocalLinkageNotInModule"; 308 case FunctionImporter::ImportFailureReason::NotEligible: 309 return "NotEligible"; 310 } 311 llvm_unreachable("invalid reason"); 312 } 313 314 /// Compute the list of functions to import for a given caller. Mark these 315 /// imported functions and the symbols they reference in their source module as 316 /// exported from their source module. 317 static void computeImportForFunction( 318 const FunctionSummary &Summary, const ModuleSummaryIndex &Index, 319 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries, 320 SmallVectorImpl<EdgeInfo> &Worklist, 321 FunctionImporter::ImportMapTy &ImportList, 322 StringMap<FunctionImporter::ExportSetTy> *ExportLists, 323 FunctionImporter::ImportThresholdsTy &ImportThresholds) { 324 computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList, 325 ExportLists); 326 static int ImportCount = 0; 327 for (auto &Edge : Summary.calls()) { 328 ValueInfo VI = Edge.first; 329 LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold 330 << "\n"); 331 332 if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) { 333 LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff 334 << " reached.\n"); 335 continue; 336 } 337 338 VI = updateValueInfoForIndirectCalls(Index, VI); 339 if (!VI) 340 continue; 341 342 if (DefinedGVSummaries.count(VI.getGUID())) { 343 LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n"); 344 continue; 345 } 346 347 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float { 348 if (Hotness == CalleeInfo::HotnessType::Hot) 349 return ImportHotMultiplier; 350 if (Hotness == CalleeInfo::HotnessType::Cold) 351 return ImportColdMultiplier; 352 if (Hotness == CalleeInfo::HotnessType::Critical) 353 return ImportCriticalMultiplier; 354 return 1.0; 355 }; 356 357 const auto NewThreshold = 358 Threshold * GetBonusMultiplier(Edge.second.getHotness()); 359 360 auto IT = ImportThresholds.insert(std::make_pair( 361 VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr))); 362 bool PreviouslyVisited = !IT.second; 363 auto &ProcessedThreshold = std::get<0>(IT.first->second); 364 auto &CalleeSummary = std::get<1>(IT.first->second); 365 auto &FailureInfo = std::get<2>(IT.first->second); 366 367 const FunctionSummary *ResolvedCalleeSummary = nullptr; 368 if (CalleeSummary) { 369 assert(PreviouslyVisited); 370 // Since the traversal of the call graph is DFS, we can revisit a function 371 // a second time with a higher threshold. In this case, it is added back 372 // to the worklist with the new threshold (so that its own callee chains 373 // can be considered with the higher threshold). 374 if (NewThreshold <= ProcessedThreshold) { 375 LLVM_DEBUG( 376 dbgs() << "ignored! Target was already imported with Threshold " 377 << ProcessedThreshold << "\n"); 378 continue; 379 } 380 // Update with new larger threshold. 381 ProcessedThreshold = NewThreshold; 382 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary); 383 } else { 384 // If we already rejected importing a callee at the same or higher 385 // threshold, don't waste time calling selectCallee. 386 if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) { 387 LLVM_DEBUG( 388 dbgs() << "ignored! Target was already rejected with Threshold " 389 << ProcessedThreshold << "\n"); 390 if (PrintImportFailures) { 391 assert(FailureInfo && 392 "Expected FailureInfo for previously rejected candidate"); 393 FailureInfo->Attempts++; 394 } 395 continue; 396 } 397 398 FunctionImporter::ImportFailureReason Reason; 399 CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold, 400 Summary.modulePath(), Reason, VI.getGUID()); 401 if (!CalleeSummary) { 402 // Update with new larger threshold if this was a retry (otherwise 403 // we would have already inserted with NewThreshold above). Also 404 // update failure info if requested. 405 if (PreviouslyVisited) { 406 ProcessedThreshold = NewThreshold; 407 if (PrintImportFailures) { 408 assert(FailureInfo && 409 "Expected FailureInfo for previously rejected candidate"); 410 FailureInfo->Reason = Reason; 411 FailureInfo->Attempts++; 412 FailureInfo->MaxHotness = 413 std::max(FailureInfo->MaxHotness, Edge.second.getHotness()); 414 } 415 } else if (PrintImportFailures) { 416 assert(!FailureInfo && 417 "Expected no FailureInfo for newly rejected candidate"); 418 FailureInfo = llvm::make_unique<FunctionImporter::ImportFailureInfo>( 419 VI, Edge.second.getHotness(), Reason, 1); 420 } 421 LLVM_DEBUG( 422 dbgs() << "ignored! No qualifying callee with summary found.\n"); 423 continue; 424 } 425 426 // "Resolve" the summary 427 CalleeSummary = CalleeSummary->getBaseObject(); 428 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary); 429 430 assert(ResolvedCalleeSummary->instCount() <= NewThreshold && 431 "selectCallee() didn't honor the threshold"); 432 433 auto ExportModulePath = ResolvedCalleeSummary->modulePath(); 434 auto ILI = ImportList[ExportModulePath].insert(VI.getGUID()); 435 // We previously decided to import this GUID definition if it was already 436 // inserted in the set of imports from the exporting module. 437 bool PreviouslyImported = !ILI.second; 438 439 // Make exports in the source module. 440 if (ExportLists) { 441 auto &ExportList = (*ExportLists)[ExportModulePath]; 442 ExportList.insert(VI.getGUID()); 443 if (!PreviouslyImported) { 444 // This is the first time this function was exported from its source 445 // module, so mark all functions and globals it references as exported 446 // to the outside if they are defined in the same source module. 447 // For efficiency, we unconditionally add all the referenced GUIDs 448 // to the ExportList for this module, and will prune out any not 449 // defined in the module later in a single pass. 450 for (auto &Edge : ResolvedCalleeSummary->calls()) { 451 auto CalleeGUID = Edge.first.getGUID(); 452 ExportList.insert(CalleeGUID); 453 } 454 for (auto &Ref : ResolvedCalleeSummary->refs()) { 455 auto GUID = Ref.getGUID(); 456 ExportList.insert(GUID); 457 } 458 } 459 } 460 } 461 462 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) { 463 // Adjust the threshold for next level of imported functions. 464 // The threshold is different for hot callsites because we can then 465 // inline chains of hot calls. 466 if (IsHotCallsite) 467 return Threshold * ImportHotInstrFactor; 468 return Threshold * ImportInstrFactor; 469 }; 470 471 bool IsHotCallsite = 472 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot; 473 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite); 474 475 ImportCount++; 476 477 // Insert the newly imported function to the worklist. 478 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID()); 479 } 480 } 481 482 /// Given the list of globals defined in a module, compute the list of imports 483 /// as well as the list of "exports", i.e. the list of symbols referenced from 484 /// another module (that may require promotion). 485 static void ComputeImportForModule( 486 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index, 487 StringRef ModName, FunctionImporter::ImportMapTy &ImportList, 488 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 489 // Worklist contains the list of function imported in this module, for which 490 // we will analyse the callees and may import further down the callgraph. 491 SmallVector<EdgeInfo, 128> Worklist; 492 FunctionImporter::ImportThresholdsTy ImportThresholds; 493 494 // Populate the worklist with the import for the functions in the current 495 // module 496 for (auto &GVSummary : DefinedGVSummaries) { 497 #ifndef NDEBUG 498 // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID 499 // so this map look up (and possibly others) can be avoided. 500 auto VI = Index.getValueInfo(GVSummary.first); 501 #endif 502 if (!Index.isGlobalValueLive(GVSummary.second)) { 503 LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n"); 504 continue; 505 } 506 auto *FuncSummary = 507 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject()); 508 if (!FuncSummary) 509 // Skip import for global variables 510 continue; 511 LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n"); 512 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit, 513 DefinedGVSummaries, Worklist, ImportList, 514 ExportLists, ImportThresholds); 515 } 516 517 // Process the newly imported functions and add callees to the worklist. 518 while (!Worklist.empty()) { 519 auto FuncInfo = Worklist.pop_back_val(); 520 auto *Summary = std::get<0>(FuncInfo); 521 auto Threshold = std::get<1>(FuncInfo); 522 523 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries, 524 Worklist, ImportList, ExportLists, 525 ImportThresholds); 526 } 527 528 // Print stats about functions considered but rejected for importing 529 // when requested. 530 if (PrintImportFailures) { 531 dbgs() << "Missed imports into module " << ModName << "\n"; 532 for (auto &I : ImportThresholds) { 533 auto &ProcessedThreshold = std::get<0>(I.second); 534 auto &CalleeSummary = std::get<1>(I.second); 535 auto &FailureInfo = std::get<2>(I.second); 536 if (CalleeSummary) 537 continue; // We are going to import. 538 assert(FailureInfo); 539 FunctionSummary *FS = nullptr; 540 if (!FailureInfo->VI.getSummaryList().empty()) 541 FS = dyn_cast<FunctionSummary>( 542 FailureInfo->VI.getSummaryList()[0]->getBaseObject()); 543 dbgs() << FailureInfo->VI 544 << ": Reason = " << getFailureName(FailureInfo->Reason) 545 << ", Threshold = " << ProcessedThreshold 546 << ", Size = " << (FS ? (int)FS->instCount() : -1) 547 << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness) 548 << ", Attempts = " << FailureInfo->Attempts << "\n"; 549 } 550 } 551 } 552 553 #ifndef NDEBUG 554 static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, 555 GlobalValue::GUID G) { 556 if (const auto &VI = Index.getValueInfo(G)) { 557 auto SL = VI.getSummaryList(); 558 if (!SL.empty()) 559 return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind; 560 } 561 return false; 562 } 563 564 static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; } 565 566 template <class T> 567 static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, 568 T &Cont) { 569 unsigned NumGVS = 0; 570 for (auto &V : Cont) 571 if (isGlobalVarSummary(Index, getGUID(V))) 572 ++NumGVS; 573 return NumGVS; 574 } 575 #endif 576 577 /// Compute all the import and export for every module using the Index. 578 void llvm::ComputeCrossModuleImport( 579 const ModuleSummaryIndex &Index, 580 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 581 StringMap<FunctionImporter::ImportMapTy> &ImportLists, 582 StringMap<FunctionImporter::ExportSetTy> &ExportLists) { 583 // For each module that has function defined, compute the import/export lists. 584 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { 585 auto &ImportList = ImportLists[DefinedGVSummaries.first()]; 586 LLVM_DEBUG(dbgs() << "Computing import for Module '" 587 << DefinedGVSummaries.first() << "'\n"); 588 ComputeImportForModule(DefinedGVSummaries.second, Index, 589 DefinedGVSummaries.first(), ImportList, 590 &ExportLists); 591 } 592 593 // When computing imports we added all GUIDs referenced by anything 594 // imported from the module to its ExportList. Now we prune each ExportList 595 // of any not defined in that module. This is more efficient than checking 596 // while computing imports because some of the summary lists may be long 597 // due to linkonce (comdat) copies. 598 for (auto &ELI : ExportLists) { 599 const auto &DefinedGVSummaries = 600 ModuleToDefinedGVSummaries.lookup(ELI.first()); 601 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) { 602 if (!DefinedGVSummaries.count(*EI)) 603 EI = ELI.second.erase(EI); 604 else 605 ++EI; 606 } 607 } 608 609 #ifndef NDEBUG 610 LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size() 611 << " modules:\n"); 612 for (auto &ModuleImports : ImportLists) { 613 auto ModName = ModuleImports.first(); 614 auto &Exports = ExportLists[ModName]; 615 unsigned NumGVS = numGlobalVarSummaries(Index, Exports); 616 LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports " 617 << Exports.size() - NumGVS << " functions and " << NumGVS 618 << " vars. Imports from " << ModuleImports.second.size() 619 << " modules.\n"); 620 for (auto &Src : ModuleImports.second) { 621 auto SrcModName = Src.first(); 622 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 623 LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 624 << " functions imported from " << SrcModName << "\n"); 625 LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod 626 << " global vars imported from " << SrcModName << "\n"); 627 } 628 } 629 #endif 630 } 631 632 #ifndef NDEBUG 633 static void dumpImportListForModule(const ModuleSummaryIndex &Index, 634 StringRef ModulePath, 635 FunctionImporter::ImportMapTy &ImportList) { 636 LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from " 637 << ImportList.size() << " modules.\n"); 638 for (auto &Src : ImportList) { 639 auto SrcModName = Src.first(); 640 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 641 LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 642 << " functions imported from " << SrcModName << "\n"); 643 LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from " 644 << SrcModName << "\n"); 645 } 646 } 647 #endif 648 649 /// Compute all the imports for the given module in the Index. 650 void llvm::ComputeCrossModuleImportForModule( 651 StringRef ModulePath, const ModuleSummaryIndex &Index, 652 FunctionImporter::ImportMapTy &ImportList) { 653 // Collect the list of functions this module defines. 654 // GUID -> Summary 655 GVSummaryMapTy FunctionSummaryMap; 656 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap); 657 658 // Compute the import list for this module. 659 LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n"); 660 ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList); 661 662 #ifndef NDEBUG 663 dumpImportListForModule(Index, ModulePath, ImportList); 664 #endif 665 } 666 667 // Mark all external summaries in Index for import into the given module. 668 // Used for distributed builds using a distributed index. 669 void llvm::ComputeCrossModuleImportForModuleFromIndex( 670 StringRef ModulePath, const ModuleSummaryIndex &Index, 671 FunctionImporter::ImportMapTy &ImportList) { 672 for (auto &GlobalList : Index) { 673 // Ignore entries for undefined references. 674 if (GlobalList.second.SummaryList.empty()) 675 continue; 676 677 auto GUID = GlobalList.first; 678 assert(GlobalList.second.SummaryList.size() == 1 && 679 "Expected individual combined index to have one summary per GUID"); 680 auto &Summary = GlobalList.second.SummaryList[0]; 681 // Skip the summaries for the importing module. These are included to 682 // e.g. record required linkage changes. 683 if (Summary->modulePath() == ModulePath) 684 continue; 685 // Add an entry to provoke importing by thinBackend. 686 ImportList[Summary->modulePath()].insert(GUID); 687 } 688 #ifndef NDEBUG 689 dumpImportListForModule(Index, ModulePath, ImportList); 690 #endif 691 } 692 693 void llvm::computeDeadSymbols( 694 ModuleSummaryIndex &Index, 695 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 696 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) { 697 assert(!Index.withGlobalValueDeadStripping()); 698 if (!ComputeDead) 699 return; 700 if (GUIDPreservedSymbols.empty()) 701 // Don't do anything when nothing is live, this is friendly with tests. 702 return; 703 unsigned LiveSymbols = 0; 704 SmallVector<ValueInfo, 128> Worklist; 705 Worklist.reserve(GUIDPreservedSymbols.size() * 2); 706 for (auto GUID : GUIDPreservedSymbols) { 707 ValueInfo VI = Index.getValueInfo(GUID); 708 if (!VI) 709 continue; 710 for (auto &S : VI.getSummaryList()) 711 S->setLive(true); 712 } 713 714 // Add values flagged in the index as live roots to the worklist. 715 for (const auto &Entry : Index) { 716 auto VI = Index.getValueInfo(Entry); 717 for (auto &S : Entry.second.SummaryList) 718 if (S->isLive()) { 719 LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n"); 720 Worklist.push_back(VI); 721 ++LiveSymbols; 722 break; 723 } 724 } 725 726 // Make value live and add it to the worklist if it was not live before. 727 auto visit = [&](ValueInfo VI) { 728 // FIXME: If we knew which edges were created for indirect call profiles, 729 // we could skip them here. Any that are live should be reached via 730 // other edges, e.g. reference edges. Otherwise, using a profile collected 731 // on a slightly different binary might provoke preserving, importing 732 // and ultimately promoting calls to functions not linked into this 733 // binary, which increases the binary size unnecessarily. Note that 734 // if this code changes, the importer needs to change so that edges 735 // to functions marked dead are skipped. 736 VI = updateValueInfoForIndirectCalls(Index, VI); 737 if (!VI) 738 return; 739 for (auto &S : VI.getSummaryList()) 740 if (S->isLive()) 741 return; 742 743 // We only keep live symbols that are known to be non-prevailing if any are 744 // available_externally. Those symbols are discarded later in the 745 // EliminateAvailableExternally pass and setting them to not-live breaks 746 // downstreams users of liveness information (PR36483). 747 if (isPrevailing(VI.getGUID()) == PrevailingType::No) { 748 bool AvailableExternally = false; 749 bool Interposable = false; 750 for (auto &S : VI.getSummaryList()) { 751 if (S->linkage() == GlobalValue::AvailableExternallyLinkage) 752 AvailableExternally = true; 753 else if (GlobalValue::isInterposableLinkage(S->linkage())) 754 Interposable = true; 755 } 756 757 if (!AvailableExternally) 758 return; 759 760 if (Interposable) 761 report_fatal_error("Interposable and available_externally symbol"); 762 } 763 764 for (auto &S : VI.getSummaryList()) 765 S->setLive(true); 766 ++LiveSymbols; 767 Worklist.push_back(VI); 768 }; 769 770 while (!Worklist.empty()) { 771 auto VI = Worklist.pop_back_val(); 772 for (auto &Summary : VI.getSummaryList()) { 773 GlobalValueSummary *Base = Summary->getBaseObject(); 774 // Set base value live in case it is an alias. 775 Base->setLive(true); 776 for (auto Ref : Base->refs()) 777 visit(Ref); 778 if (auto *FS = dyn_cast<FunctionSummary>(Base)) 779 for (auto Call : FS->calls()) 780 visit(Call.first); 781 } 782 } 783 Index.setWithGlobalValueDeadStripping(); 784 785 unsigned DeadSymbols = Index.size() - LiveSymbols; 786 LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols 787 << " symbols Dead \n"); 788 NumDeadSymbols += DeadSymbols; 789 NumLiveSymbols += LiveSymbols; 790 } 791 792 /// Compute the set of summaries needed for a ThinLTO backend compilation of 793 /// \p ModulePath. 794 void llvm::gatherImportedSummariesForModule( 795 StringRef ModulePath, 796 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 797 const FunctionImporter::ImportMapTy &ImportList, 798 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 799 // Include all summaries from the importing module. 800 ModuleToSummariesForIndex[ModulePath] = 801 ModuleToDefinedGVSummaries.lookup(ModulePath); 802 // Include summaries for imports. 803 for (auto &ILI : ImportList) { 804 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()]; 805 const auto &DefinedGVSummaries = 806 ModuleToDefinedGVSummaries.lookup(ILI.first()); 807 for (auto &GI : ILI.second) { 808 const auto &DS = DefinedGVSummaries.find(GI); 809 assert(DS != DefinedGVSummaries.end() && 810 "Expected a defined summary for imported global value"); 811 SummariesForIndex[GI] = DS->second; 812 } 813 } 814 } 815 816 /// Emit the files \p ModulePath will import from into \p OutputFilename. 817 std::error_code llvm::EmitImportsFiles( 818 StringRef ModulePath, StringRef OutputFilename, 819 const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 820 std::error_code EC; 821 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None); 822 if (EC) 823 return EC; 824 for (auto &ILI : ModuleToSummariesForIndex) 825 // The ModuleToSummariesForIndex map includes an entry for the current 826 // Module (needed for writing out the index files). We don't want to 827 // include it in the imports file, however, so filter it out. 828 if (ILI.first != ModulePath) 829 ImportsOS << ILI.first << "\n"; 830 return std::error_code(); 831 } 832 833 bool llvm::convertToDeclaration(GlobalValue &GV) { 834 LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() 835 << "\n"); 836 if (Function *F = dyn_cast<Function>(&GV)) { 837 F->deleteBody(); 838 F->clearMetadata(); 839 F->setComdat(nullptr); 840 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) { 841 V->setInitializer(nullptr); 842 V->setLinkage(GlobalValue::ExternalLinkage); 843 V->clearMetadata(); 844 V->setComdat(nullptr); 845 } else { 846 GlobalValue *NewGV; 847 if (GV.getValueType()->isFunctionTy()) 848 NewGV = 849 Function::Create(cast<FunctionType>(GV.getValueType()), 850 GlobalValue::ExternalLinkage, "", GV.getParent()); 851 else 852 NewGV = 853 new GlobalVariable(*GV.getParent(), GV.getValueType(), 854 /*isConstant*/ false, GlobalValue::ExternalLinkage, 855 /*init*/ nullptr, "", 856 /*insertbefore*/ nullptr, GV.getThreadLocalMode(), 857 GV.getType()->getAddressSpace()); 858 NewGV->takeName(&GV); 859 GV.replaceAllUsesWith(NewGV); 860 return false; 861 } 862 return true; 863 } 864 865 /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis. 866 void llvm::thinLTOResolveWeakForLinkerModule( 867 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) { 868 auto updateLinkage = [&](GlobalValue &GV) { 869 // See if the global summary analysis computed a new resolved linkage. 870 const auto &GS = DefinedGlobals.find(GV.getGUID()); 871 if (GS == DefinedGlobals.end()) 872 return; 873 auto NewLinkage = GS->second->linkage(); 874 if (NewLinkage == GV.getLinkage()) 875 return; 876 877 // Switch the linkage to weakany if asked for, e.g. we do this for 878 // linker redefined symbols (via --wrap or --defsym). 879 // We record that the visibility should be changed here in `addThinLTO` 880 // as we need access to the resolution vectors for each input file in 881 // order to find which symbols have been redefined. 882 // We may consider reorganizing this code and moving the linkage recording 883 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex. 884 if (NewLinkage == GlobalValue::WeakAnyLinkage) { 885 GV.setLinkage(NewLinkage); 886 return; 887 } 888 889 if (!GlobalValue::isWeakForLinker(GV.getLinkage())) 890 return; 891 // Check for a non-prevailing def that has interposable linkage 892 // (e.g. non-odr weak or linkonce). In that case we can't simply 893 // convert to available_externally, since it would lose the 894 // interposable property and possibly get inlined. Simply drop 895 // the definition in that case. 896 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) && 897 GlobalValue::isInterposableLinkage(GV.getLinkage())) { 898 if (!convertToDeclaration(GV)) 899 // FIXME: Change this to collect replaced GVs and later erase 900 // them from the parent module once thinLTOResolveWeakForLinkerGUID is 901 // changed to enable this for aliases. 902 llvm_unreachable("Expected GV to be converted"); 903 } else { 904 // If the original symbols has global unnamed addr and linkonce_odr linkage, 905 // it should be an auto hide symbol. Add hidden visibility to the symbol to 906 // preserve the property. 907 if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() && 908 NewLinkage == GlobalValue::WeakODRLinkage) 909 GV.setVisibility(GlobalValue::HiddenVisibility); 910 911 LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() 912 << "` from " << GV.getLinkage() << " to " << NewLinkage 913 << "\n"); 914 GV.setLinkage(NewLinkage); 915 } 916 // Remove declarations from comdats, including available_externally 917 // as this is a declaration for the linker, and will be dropped eventually. 918 // It is illegal for comdats to contain declarations. 919 auto *GO = dyn_cast_or_null<GlobalObject>(&GV); 920 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) 921 GO->setComdat(nullptr); 922 }; 923 924 // Process functions and global now 925 for (auto &GV : TheModule) 926 updateLinkage(GV); 927 for (auto &GV : TheModule.globals()) 928 updateLinkage(GV); 929 for (auto &GV : TheModule.aliases()) 930 updateLinkage(GV); 931 } 932 933 /// Run internalization on \p TheModule based on symmary analysis. 934 void llvm::thinLTOInternalizeModule(Module &TheModule, 935 const GVSummaryMapTy &DefinedGlobals) { 936 // Declare a callback for the internalize pass that will ask for every 937 // candidate GlobalValue if it can be internalized or not. 938 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool { 939 // Lookup the linkage recorded in the summaries during global analysis. 940 auto GS = DefinedGlobals.find(GV.getGUID()); 941 if (GS == DefinedGlobals.end()) { 942 // Must have been promoted (possibly conservatively). Find original 943 // name so that we can access the correct summary and see if it can 944 // be internalized again. 945 // FIXME: Eventually we should control promotion instead of promoting 946 // and internalizing again. 947 StringRef OrigName = 948 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName()); 949 std::string OrigId = GlobalValue::getGlobalIdentifier( 950 OrigName, GlobalValue::InternalLinkage, 951 TheModule.getSourceFileName()); 952 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); 953 if (GS == DefinedGlobals.end()) { 954 // Also check the original non-promoted non-globalized name. In some 955 // cases a preempted weak value is linked in as a local copy because 956 // it is referenced by an alias (IRLinker::linkGlobalValueProto). 957 // In that case, since it was originally not a local value, it was 958 // recorded in the index using the original name. 959 // FIXME: This may not be needed once PR27866 is fixed. 960 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); 961 assert(GS != DefinedGlobals.end()); 962 } 963 } 964 return !GlobalValue::isLocalLinkage(GS->second->linkage()); 965 }; 966 967 // FIXME: See if we can just internalize directly here via linkage changes 968 // based on the index, rather than invoking internalizeModule. 969 internalizeModule(TheModule, MustPreserveGV); 970 } 971 972 /// Make alias a clone of its aliasee. 973 static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) { 974 Function *Fn = cast<Function>(GA->getBaseObject()); 975 976 ValueToValueMapTy VMap; 977 Function *NewFn = CloneFunction(Fn, VMap); 978 // Clone should use the original alias's linkage and name, and we ensure 979 // all uses of alias instead use the new clone (casted if necessary). 980 NewFn->setLinkage(GA->getLinkage()); 981 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType())); 982 NewFn->takeName(GA); 983 return NewFn; 984 } 985 986 // Automatically import functions in Module \p DestModule based on the summaries 987 // index. 988 Expected<bool> FunctionImporter::importFunctions( 989 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) { 990 LLVM_DEBUG(dbgs() << "Starting import for Module " 991 << DestModule.getModuleIdentifier() << "\n"); 992 unsigned ImportedCount = 0, ImportedGVCount = 0; 993 994 IRMover Mover(DestModule); 995 // Do the actual import of functions now, one Module at a time 996 std::set<StringRef> ModuleNameOrderedList; 997 for (auto &FunctionsToImportPerModule : ImportList) { 998 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first()); 999 } 1000 for (auto &Name : ModuleNameOrderedList) { 1001 // Get the module for the import 1002 const auto &FunctionsToImportPerModule = ImportList.find(Name); 1003 assert(FunctionsToImportPerModule != ImportList.end()); 1004 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name); 1005 if (!SrcModuleOrErr) 1006 return SrcModuleOrErr.takeError(); 1007 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr); 1008 assert(&DestModule.getContext() == &SrcModule->getContext() && 1009 "Context mismatch"); 1010 1011 // If modules were created with lazy metadata loading, materialize it 1012 // now, before linking it (otherwise this will be a noop). 1013 if (Error Err = SrcModule->materializeMetadata()) 1014 return std::move(Err); 1015 1016 auto &ImportGUIDs = FunctionsToImportPerModule->second; 1017 // Find the globals to import 1018 SetVector<GlobalValue *> GlobalsToImport; 1019 for (Function &F : *SrcModule) { 1020 if (!F.hasName()) 1021 continue; 1022 auto GUID = F.getGUID(); 1023 auto Import = ImportGUIDs.count(GUID); 1024 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " 1025 << GUID << " " << F.getName() << " from " 1026 << SrcModule->getSourceFileName() << "\n"); 1027 if (Import) { 1028 if (Error Err = F.materialize()) 1029 return std::move(Err); 1030 if (EnableImportMetadata) { 1031 // Add 'thinlto_src_module' metadata for statistics and debugging. 1032 F.setMetadata( 1033 "thinlto_src_module", 1034 MDNode::get(DestModule.getContext(), 1035 {MDString::get(DestModule.getContext(), 1036 SrcModule->getSourceFileName())})); 1037 } 1038 GlobalsToImport.insert(&F); 1039 } 1040 } 1041 for (GlobalVariable &GV : SrcModule->globals()) { 1042 if (!GV.hasName()) 1043 continue; 1044 auto GUID = GV.getGUID(); 1045 auto Import = ImportGUIDs.count(GUID); 1046 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " 1047 << GUID << " " << GV.getName() << " from " 1048 << SrcModule->getSourceFileName() << "\n"); 1049 if (Import) { 1050 if (Error Err = GV.materialize()) 1051 return std::move(Err); 1052 ImportedGVCount += GlobalsToImport.insert(&GV); 1053 } 1054 } 1055 for (GlobalAlias &GA : SrcModule->aliases()) { 1056 if (!GA.hasName()) 1057 continue; 1058 auto GUID = GA.getGUID(); 1059 auto Import = ImportGUIDs.count(GUID); 1060 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " 1061 << GUID << " " << GA.getName() << " from " 1062 << SrcModule->getSourceFileName() << "\n"); 1063 if (Import) { 1064 if (Error Err = GA.materialize()) 1065 return std::move(Err); 1066 // Import alias as a copy of its aliasee. 1067 GlobalObject *Base = GA.getBaseObject(); 1068 if (Error Err = Base->materialize()) 1069 return std::move(Err); 1070 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA); 1071 LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID() 1072 << " " << Base->getName() << " from " 1073 << SrcModule->getSourceFileName() << "\n"); 1074 if (EnableImportMetadata) { 1075 // Add 'thinlto_src_module' metadata for statistics and debugging. 1076 Fn->setMetadata( 1077 "thinlto_src_module", 1078 MDNode::get(DestModule.getContext(), 1079 {MDString::get(DestModule.getContext(), 1080 SrcModule->getSourceFileName())})); 1081 } 1082 GlobalsToImport.insert(Fn); 1083 } 1084 } 1085 1086 // Upgrade debug info after we're done materializing all the globals and we 1087 // have loaded all the required metadata! 1088 UpgradeDebugInfo(*SrcModule); 1089 1090 // Link in the specified functions. 1091 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport)) 1092 return true; 1093 1094 if (PrintImports) { 1095 for (const auto *GV : GlobalsToImport) 1096 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName() 1097 << " from " << SrcModule->getSourceFileName() << "\n"; 1098 } 1099 1100 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(), 1101 [](GlobalValue &, IRMover::ValueAdder) {}, 1102 /*IsPerformingImport=*/true)) 1103 report_fatal_error("Function Import: link error"); 1104 1105 ImportedCount += GlobalsToImport.size(); 1106 NumImportedModules++; 1107 } 1108 1109 NumImportedFunctions += (ImportedCount - ImportedGVCount); 1110 NumImportedGlobalVars += ImportedGVCount; 1111 1112 LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount 1113 << " functions for Module " 1114 << DestModule.getModuleIdentifier() << "\n"); 1115 LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount 1116 << " global variables for Module " 1117 << DestModule.getModuleIdentifier() << "\n"); 1118 return ImportedCount; 1119 } 1120 1121 static bool doImportingForModule(Module &M) { 1122 if (SummaryFile.empty()) 1123 report_fatal_error("error: -function-import requires -summary-file\n"); 1124 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr = 1125 getModuleSummaryIndexForFile(SummaryFile); 1126 if (!IndexPtrOrErr) { 1127 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(), 1128 "Error loading file '" + SummaryFile + "': "); 1129 return false; 1130 } 1131 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr); 1132 1133 // First step is collecting the import list. 1134 FunctionImporter::ImportMapTy ImportList; 1135 // If requested, simply import all functions in the index. This is used 1136 // when testing distributed backend handling via the opt tool, when 1137 // we have distributed indexes containing exactly the summaries to import. 1138 if (ImportAllIndex) 1139 ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index, 1140 ImportList); 1141 else 1142 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index, 1143 ImportList); 1144 1145 // Conservatively mark all internal values as promoted. This interface is 1146 // only used when doing importing via the function importing pass. The pass 1147 // is only enabled when testing importing via the 'opt' tool, which does 1148 // not do the ThinLink that would normally determine what values to promote. 1149 for (auto &I : *Index) { 1150 for (auto &S : I.second.SummaryList) { 1151 if (GlobalValue::isLocalLinkage(S->linkage())) 1152 S->setLinkage(GlobalValue::ExternalLinkage); 1153 } 1154 } 1155 1156 // Next we need to promote to global scope and rename any local values that 1157 // are potentially exported to other modules. 1158 if (renameModuleForThinLTO(M, *Index, nullptr)) { 1159 errs() << "Error renaming module\n"; 1160 return false; 1161 } 1162 1163 // Perform the import now. 1164 auto ModuleLoader = [&M](StringRef Identifier) { 1165 return loadFile(Identifier, M.getContext()); 1166 }; 1167 FunctionImporter Importer(*Index, ModuleLoader); 1168 Expected<bool> Result = Importer.importFunctions(M, ImportList); 1169 1170 // FIXME: Probably need to propagate Errors through the pass manager. 1171 if (!Result) { 1172 logAllUnhandledErrors(Result.takeError(), errs(), 1173 "Error importing module: "); 1174 return false; 1175 } 1176 1177 return *Result; 1178 } 1179 1180 namespace { 1181 1182 /// Pass that performs cross-module function import provided a summary file. 1183 class FunctionImportLegacyPass : public ModulePass { 1184 public: 1185 /// Pass identification, replacement for typeid 1186 static char ID; 1187 1188 explicit FunctionImportLegacyPass() : ModulePass(ID) {} 1189 1190 /// Specify pass name for debug output 1191 StringRef getPassName() const override { return "Function Importing"; } 1192 1193 bool runOnModule(Module &M) override { 1194 if (skipModule(M)) 1195 return false; 1196 1197 return doImportingForModule(M); 1198 } 1199 }; 1200 1201 } // end anonymous namespace 1202 1203 PreservedAnalyses FunctionImportPass::run(Module &M, 1204 ModuleAnalysisManager &AM) { 1205 if (!doImportingForModule(M)) 1206 return PreservedAnalyses::all(); 1207 1208 return PreservedAnalyses::none(); 1209 } 1210 1211 char FunctionImportLegacyPass::ID = 0; 1212 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import", 1213 "Summary Based Function Import", false, false) 1214 1215 namespace llvm { 1216 1217 Pass *createFunctionImportPass() { 1218 return new FunctionImportLegacyPass(); 1219 } 1220 1221 } // end namespace llvm 1222