1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Thin Link Time Optimization library. This library is 10 // intended to be used by linker to optimize code at link time. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h" 15 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 19 #include "llvm/Analysis/ProfileSummaryInfo.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/Bitcode/BitcodeReader.h" 23 #include "llvm/Bitcode/BitcodeWriter.h" 24 #include "llvm/Bitcode/BitcodeWriterPass.h" 25 #include "llvm/Config/llvm-config.h" 26 #include "llvm/IR/DebugInfo.h" 27 #include "llvm/IR/DiagnosticPrinter.h" 28 #include "llvm/IR/LLVMContext.h" 29 #include "llvm/IR/LegacyPassManager.h" 30 #include "llvm/IR/Mangler.h" 31 #include "llvm/IR/PassTimingInfo.h" 32 #include "llvm/IR/RemarkStreamer.h" 33 #include "llvm/IR/Verifier.h" 34 #include "llvm/IRReader/IRReader.h" 35 #include "llvm/LTO/LTO.h" 36 #include "llvm/LTO/SummaryBasedOptimizations.h" 37 #include "llvm/MC/SubtargetFeature.h" 38 #include "llvm/Object/IRObjectFile.h" 39 #include "llvm/Support/CachePruning.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/Error.h" 42 #include "llvm/Support/Path.h" 43 #include "llvm/Support/SHA1.h" 44 #include "llvm/Support/SmallVectorMemoryBuffer.h" 45 #include "llvm/Support/TargetRegistry.h" 46 #include "llvm/Support/ThreadPool.h" 47 #include "llvm/Support/Threading.h" 48 #include "llvm/Support/ToolOutputFile.h" 49 #include "llvm/Support/VCSRevision.h" 50 #include "llvm/Target/TargetMachine.h" 51 #include "llvm/Transforms/IPO.h" 52 #include "llvm/Transforms/IPO/FunctionImport.h" 53 #include "llvm/Transforms/IPO/Internalize.h" 54 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 55 #include "llvm/Transforms/ObjCARC.h" 56 #include "llvm/Transforms/Utils/FunctionImportUtils.h" 57 58 #include <numeric> 59 60 #if !defined(_MSC_VER) && !defined(__MINGW32__) 61 #include <unistd.h> 62 #else 63 #include <io.h> 64 #endif 65 66 using namespace llvm; 67 68 #define DEBUG_TYPE "thinlto" 69 70 namespace llvm { 71 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp 72 extern cl::opt<bool> LTODiscardValueNames; 73 extern cl::opt<std::string> RemarksFilename; 74 extern cl::opt<std::string> RemarksPasses; 75 extern cl::opt<bool> RemarksWithHotness; 76 extern cl::opt<std::string> RemarksFormat; 77 } 78 79 namespace { 80 81 static cl::opt<int> 82 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency())); 83 84 // Simple helper to save temporary files for debug. 85 static void saveTempBitcode(const Module &TheModule, StringRef TempDir, 86 unsigned count, StringRef Suffix) { 87 if (TempDir.empty()) 88 return; 89 // User asked to save temps, let dump the bitcode file after import. 90 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str(); 91 std::error_code EC; 92 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None); 93 if (EC) 94 report_fatal_error(Twine("Failed to open ") + SaveTempPath + 95 " to save optimized bitcode\n"); 96 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true); 97 } 98 99 static const GlobalValueSummary * 100 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) { 101 // If there is any strong definition anywhere, get it. 102 auto StrongDefForLinker = llvm::find_if( 103 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) { 104 auto Linkage = Summary->linkage(); 105 return !GlobalValue::isAvailableExternallyLinkage(Linkage) && 106 !GlobalValue::isWeakForLinker(Linkage); 107 }); 108 if (StrongDefForLinker != GVSummaryList.end()) 109 return StrongDefForLinker->get(); 110 // Get the first *linker visible* definition for this global in the summary 111 // list. 112 auto FirstDefForLinker = llvm::find_if( 113 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) { 114 auto Linkage = Summary->linkage(); 115 return !GlobalValue::isAvailableExternallyLinkage(Linkage); 116 }); 117 // Extern templates can be emitted as available_externally. 118 if (FirstDefForLinker == GVSummaryList.end()) 119 return nullptr; 120 return FirstDefForLinker->get(); 121 } 122 123 // Populate map of GUID to the prevailing copy for any multiply defined 124 // symbols. Currently assume first copy is prevailing, or any strong 125 // definition. Can be refined with Linker information in the future. 126 static void computePrevailingCopies( 127 const ModuleSummaryIndex &Index, 128 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) { 129 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) { 130 return GVSummaryList.size() > 1; 131 }; 132 133 for (auto &I : Index) { 134 if (HasMultipleCopies(I.second.SummaryList)) 135 PrevailingCopy[I.first] = 136 getFirstDefinitionForLinker(I.second.SummaryList); 137 } 138 } 139 140 static StringMap<lto::InputFile *> 141 generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) { 142 StringMap<lto::InputFile *> ModuleMap; 143 for (auto &M : Modules) { 144 assert(ModuleMap.find(M->getName()) == ModuleMap.end() && 145 "Expect unique Buffer Identifier"); 146 ModuleMap[M->getName()] = M.get(); 147 } 148 return ModuleMap; 149 } 150 151 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) { 152 if (renameModuleForThinLTO(TheModule, Index)) 153 report_fatal_error("renameModuleForThinLTO failed"); 154 } 155 156 namespace { 157 class ThinLTODiagnosticInfo : public DiagnosticInfo { 158 const Twine &Msg; 159 public: 160 ThinLTODiagnosticInfo(const Twine &DiagMsg, 161 DiagnosticSeverity Severity = DS_Error) 162 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {} 163 void print(DiagnosticPrinter &DP) const override { DP << Msg; } 164 }; 165 } 166 167 /// Verify the module and strip broken debug info. 168 static void verifyLoadedModule(Module &TheModule) { 169 bool BrokenDebugInfo = false; 170 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo)) 171 report_fatal_error("Broken module found, compilation aborted!"); 172 if (BrokenDebugInfo) { 173 TheModule.getContext().diagnose(ThinLTODiagnosticInfo( 174 "Invalid debug info found, debug info will be stripped", DS_Warning)); 175 StripDebugInfo(TheModule); 176 } 177 } 178 179 static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile *Input, 180 LLVMContext &Context, 181 bool Lazy, 182 bool IsImporting) { 183 auto &Mod = Input->getSingleBitcodeModule(); 184 SMDiagnostic Err; 185 Expected<std::unique_ptr<Module>> ModuleOrErr = 186 Lazy ? Mod.getLazyModule(Context, 187 /* ShouldLazyLoadMetadata */ true, IsImporting) 188 : Mod.parseModule(Context); 189 if (!ModuleOrErr) { 190 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) { 191 SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(), 192 SourceMgr::DK_Error, EIB.message()); 193 Err.print("ThinLTO", errs()); 194 }); 195 report_fatal_error("Can't load module, abort."); 196 } 197 if (!Lazy) 198 verifyLoadedModule(*ModuleOrErr.get()); 199 return std::move(*ModuleOrErr); 200 } 201 202 static void 203 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index, 204 StringMap<lto::InputFile*> &ModuleMap, 205 const FunctionImporter::ImportMapTy &ImportList) { 206 auto Loader = [&](StringRef Identifier) { 207 auto &Input = ModuleMap[Identifier]; 208 return loadModuleFromInput(Input, TheModule.getContext(), 209 /*Lazy=*/true, /*IsImporting*/ true); 210 }; 211 212 FunctionImporter Importer(Index, Loader); 213 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList); 214 if (!Result) { 215 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) { 216 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(), 217 SourceMgr::DK_Error, EIB.message()); 218 Err.print("ThinLTO", errs()); 219 }); 220 report_fatal_error("importFunctions failed"); 221 } 222 // Verify again after cross-importing. 223 verifyLoadedModule(TheModule); 224 } 225 226 static void optimizeModule(Module &TheModule, TargetMachine &TM, 227 unsigned OptLevel, bool Freestanding) { 228 // Populate the PassManager 229 PassManagerBuilder PMB; 230 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple()); 231 if (Freestanding) 232 PMB.LibraryInfo->disableAllFunctions(); 233 PMB.Inliner = createFunctionInliningPass(); 234 // FIXME: should get it from the bitcode? 235 PMB.OptLevel = OptLevel; 236 PMB.LoopVectorize = true; 237 PMB.SLPVectorize = true; 238 // Already did this in verifyLoadedModule(). 239 PMB.VerifyInput = false; 240 PMB.VerifyOutput = false; 241 242 legacy::PassManager PM; 243 244 // Add the TTI (required to inform the vectorizer about register size for 245 // instance) 246 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis())); 247 248 // Add optimizations 249 PMB.populateThinLTOPassManager(PM); 250 251 PM.run(TheModule); 252 } 253 254 static void 255 addUsedSymbolToPreservedGUID(const lto::InputFile &File, 256 DenseSet<GlobalValue::GUID> &PreservedGUID) { 257 for (const auto &Sym : File.symbols()) { 258 if (Sym.isUsed()) 259 PreservedGUID.insert(GlobalValue::getGUID(Sym.getIRName())); 260 } 261 } 262 263 // Convert the PreservedSymbols map from "Name" based to "GUID" based. 264 static DenseSet<GlobalValue::GUID> 265 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols, 266 const Triple &TheTriple) { 267 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size()); 268 for (auto &Entry : PreservedSymbols) { 269 StringRef Name = Entry.first(); 270 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_') 271 Name = Name.drop_front(); 272 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name)); 273 } 274 return GUIDPreservedSymbols; 275 } 276 277 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule, 278 TargetMachine &TM) { 279 SmallVector<char, 128> OutputBuffer; 280 281 // CodeGen 282 { 283 raw_svector_ostream OS(OutputBuffer); 284 legacy::PassManager PM; 285 286 // If the bitcode files contain ARC code and were compiled with optimization, 287 // the ObjCARCContractPass must be run, so do it unconditionally here. 288 PM.add(createObjCARCContractPass()); 289 290 // Setup the codegen now. 291 if (TM.addPassesToEmitFile(PM, OS, nullptr, TargetMachine::CGFT_ObjectFile, 292 /* DisableVerify */ true)) 293 report_fatal_error("Failed to setup codegen"); 294 295 // Run codegen now. resulting binary is in OutputBuffer. 296 PM.run(TheModule); 297 } 298 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer)); 299 } 300 301 /// Manage caching for a single Module. 302 class ModuleCacheEntry { 303 SmallString<128> EntryPath; 304 305 public: 306 // Create a cache entry. This compute a unique hash for the Module considering 307 // the current list of export/import, and offer an interface to query to 308 // access the content in the cache. 309 ModuleCacheEntry( 310 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID, 311 const FunctionImporter::ImportMapTy &ImportList, 312 const FunctionImporter::ExportSetTy &ExportList, 313 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, 314 const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel, 315 bool Freestanding, const TargetMachineBuilder &TMBuilder) { 316 if (CachePath.empty()) 317 return; 318 319 if (!Index.modulePaths().count(ModuleID)) 320 // The module does not have an entry, it can't have a hash at all 321 return; 322 323 if (all_of(Index.getModuleHash(ModuleID), 324 [](uint32_t V) { return V == 0; })) 325 // No hash entry, no caching! 326 return; 327 328 llvm::lto::Config Conf; 329 Conf.OptLevel = OptLevel; 330 Conf.Options = TMBuilder.Options; 331 Conf.CPU = TMBuilder.MCpu; 332 Conf.MAttrs.push_back(TMBuilder.MAttr); 333 Conf.RelocModel = TMBuilder.RelocModel; 334 Conf.CGOptLevel = TMBuilder.CGOptLevel; 335 Conf.Freestanding = Freestanding; 336 SmallString<40> Key; 337 computeLTOCacheKey(Key, Conf, Index, ModuleID, ImportList, ExportList, 338 ResolvedODR, DefinedGVSummaries); 339 340 // This choice of file name allows the cache to be pruned (see pruneCache() 341 // in include/llvm/Support/CachePruning.h). 342 sys::path::append(EntryPath, CachePath, "llvmcache-" + Key); 343 } 344 345 // Access the path to this entry in the cache. 346 StringRef getEntryPath() { return EntryPath; } 347 348 // Try loading the buffer for this cache entry. 349 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() { 350 if (EntryPath.empty()) 351 return std::error_code(); 352 int FD; 353 SmallString<64> ResultPath; 354 std::error_code EC = sys::fs::openFileForRead( 355 Twine(EntryPath), FD, sys::fs::OF_UpdateAtime, &ResultPath); 356 if (EC) 357 return EC; 358 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getOpenFile( 359 sys::fs::convertFDToNativeFile(FD), EntryPath, 360 /*FileSize=*/-1, /*RequiresNullTerminator=*/false); 361 close(FD); 362 return MBOrErr; 363 } 364 365 // Cache the Produced object file 366 void write(const MemoryBuffer &OutputBuffer) { 367 if (EntryPath.empty()) 368 return; 369 370 // Write to a temporary to avoid race condition 371 SmallString<128> TempFilename; 372 SmallString<128> CachePath(EntryPath); 373 int TempFD; 374 llvm::sys::path::remove_filename(CachePath); 375 sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o"); 376 std::error_code EC = 377 sys::fs::createUniqueFile(TempFilename, TempFD, TempFilename); 378 if (EC) { 379 errs() << "Error: " << EC.message() << "\n"; 380 report_fatal_error("ThinLTO: Can't get a temporary file"); 381 } 382 { 383 raw_fd_ostream OS(TempFD, /* ShouldClose */ true); 384 OS << OutputBuffer.getBuffer(); 385 } 386 // Rename temp file to final destination; rename is atomic 387 EC = sys::fs::rename(TempFilename, EntryPath); 388 if (EC) 389 sys::fs::remove(TempFilename); 390 } 391 }; 392 393 static std::unique_ptr<MemoryBuffer> 394 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index, 395 StringMap<lto::InputFile *> &ModuleMap, TargetMachine &TM, 396 const FunctionImporter::ImportMapTy &ImportList, 397 const FunctionImporter::ExportSetTy &ExportList, 398 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 399 const GVSummaryMapTy &DefinedGlobals, 400 const ThinLTOCodeGenerator::CachingOptions &CacheOptions, 401 bool DisableCodeGen, StringRef SaveTempsDir, 402 bool Freestanding, unsigned OptLevel, unsigned count) { 403 404 // "Benchmark"-like optimization: single-source case 405 bool SingleModule = (ModuleMap.size() == 1); 406 407 if (!SingleModule) { 408 promoteModule(TheModule, Index); 409 410 // Apply summary-based prevailing-symbol resolution decisions. 411 thinLTOResolvePrevailingInModule(TheModule, DefinedGlobals); 412 413 // Save temps: after promotion. 414 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc"); 415 } 416 417 // Be friendly and don't nuke totally the module when the client didn't 418 // supply anything to preserve. 419 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) { 420 // Apply summary-based internalization decisions. 421 thinLTOInternalizeModule(TheModule, DefinedGlobals); 422 } 423 424 // Save internalized bitcode 425 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc"); 426 427 if (!SingleModule) { 428 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList); 429 430 // Save temps: after cross-module import. 431 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc"); 432 } 433 434 optimizeModule(TheModule, TM, OptLevel, Freestanding); 435 436 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc"); 437 438 if (DisableCodeGen) { 439 // Configured to stop before CodeGen, serialize the bitcode and return. 440 SmallVector<char, 128> OutputBuffer; 441 { 442 raw_svector_ostream OS(OutputBuffer); 443 ProfileSummaryInfo PSI(TheModule); 444 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI); 445 WriteBitcodeToFile(TheModule, OS, true, &Index); 446 } 447 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer)); 448 } 449 450 return codegenModule(TheModule, TM); 451 } 452 453 /// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map 454 /// for caching, and in the \p Index for application during the ThinLTO 455 /// backends. This is needed for correctness for exported symbols (ensure 456 /// at least one copy kept) and a compile-time optimization (to drop duplicate 457 /// copies when possible). 458 static void resolvePrevailingInIndex( 459 ModuleSummaryIndex &Index, 460 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> 461 &ResolvedODR, 462 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) { 463 464 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy; 465 computePrevailingCopies(Index, PrevailingCopy); 466 467 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) { 468 const auto &Prevailing = PrevailingCopy.find(GUID); 469 // Not in map means that there was only one copy, which must be prevailing. 470 if (Prevailing == PrevailingCopy.end()) 471 return true; 472 return Prevailing->second == S; 473 }; 474 475 auto recordNewLinkage = [&](StringRef ModuleIdentifier, 476 GlobalValue::GUID GUID, 477 GlobalValue::LinkageTypes NewLinkage) { 478 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage; 479 }; 480 481 thinLTOResolvePrevailingInIndex(Index, isPrevailing, recordNewLinkage, 482 GUIDPreservedSymbols); 483 } 484 485 // Initialize the TargetMachine builder for a given Triple 486 static void initTMBuilder(TargetMachineBuilder &TMBuilder, 487 const Triple &TheTriple) { 488 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator). 489 // FIXME this looks pretty terrible... 490 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) { 491 if (TheTriple.getArch() == llvm::Triple::x86_64) 492 TMBuilder.MCpu = "core2"; 493 else if (TheTriple.getArch() == llvm::Triple::x86) 494 TMBuilder.MCpu = "yonah"; 495 else if (TheTriple.getArch() == llvm::Triple::aarch64) 496 TMBuilder.MCpu = "cyclone"; 497 } 498 TMBuilder.TheTriple = std::move(TheTriple); 499 } 500 501 } // end anonymous namespace 502 503 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) { 504 MemoryBufferRef Buffer(Data, Identifier); 505 506 auto InputOrError = lto::InputFile::create(Buffer); 507 if (!InputOrError) 508 report_fatal_error("ThinLTO cannot create input file: " + 509 toString(InputOrError.takeError())); 510 511 auto TripleStr = (*InputOrError)->getTargetTriple(); 512 Triple TheTriple(TripleStr); 513 514 if (Modules.empty()) 515 initTMBuilder(TMBuilder, Triple(TheTriple)); 516 else if (TMBuilder.TheTriple != TheTriple) { 517 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple)) 518 report_fatal_error("ThinLTO modules with incompatible triples not " 519 "supported"); 520 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple))); 521 } 522 523 Modules.emplace_back(std::move(*InputOrError)); 524 } 525 526 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) { 527 PreservedSymbols.insert(Name); 528 } 529 530 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) { 531 // FIXME: At the moment, we don't take advantage of this extra information, 532 // we're conservatively considering cross-references as preserved. 533 // CrossReferencedSymbols.insert(Name); 534 PreservedSymbols.insert(Name); 535 } 536 537 // TargetMachine factory 538 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const { 539 std::string ErrMsg; 540 const Target *TheTarget = 541 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg); 542 if (!TheTarget) { 543 report_fatal_error("Can't load target for this Triple: " + ErrMsg); 544 } 545 546 // Use MAttr as the default set of features. 547 SubtargetFeatures Features(MAttr); 548 Features.getDefaultSubtargetFeatures(TheTriple); 549 std::string FeatureStr = Features.getString(); 550 551 return std::unique_ptr<TargetMachine>( 552 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options, 553 RelocModel, None, CGOptLevel)); 554 } 555 556 /** 557 * Produce the combined summary index from all the bitcode files: 558 * "thin-link". 559 */ 560 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() { 561 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = 562 llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 563 uint64_t NextModuleId = 0; 564 for (auto &Mod : Modules) { 565 auto &M = Mod->getSingleBitcodeModule(); 566 if (Error Err = 567 M.readSummary(*CombinedIndex, Mod->getName(), NextModuleId++)) { 568 // FIXME diagnose 569 logAllUnhandledErrors( 570 std::move(Err), errs(), 571 "error: can't create module summary index for buffer: "); 572 return nullptr; 573 } 574 } 575 return CombinedIndex; 576 } 577 578 static void internalizeAndPromoteInIndex( 579 const StringMap<FunctionImporter::ExportSetTy> &ExportLists, 580 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 581 ModuleSummaryIndex &Index) { 582 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) { 583 const auto &ExportList = ExportLists.find(ModuleIdentifier); 584 return (ExportList != ExportLists.end() && 585 ExportList->second.count(GUID)) || 586 GUIDPreservedSymbols.count(GUID); 587 }; 588 589 thinLTOInternalizeAndPromoteInIndex(Index, isExported); 590 } 591 592 static void computeDeadSymbolsInIndex( 593 ModuleSummaryIndex &Index, 594 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) { 595 // We have no symbols resolution available. And can't do any better now in the 596 // case where the prevailing symbol is in a native object. It can be refined 597 // with linker information in the future. 598 auto isPrevailing = [&](GlobalValue::GUID G) { 599 return PrevailingType::Unknown; 600 }; 601 computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing, 602 /* ImportEnabled = */ true); 603 } 604 605 /** 606 * Perform promotion and renaming of exported internal functions. 607 * Index is updated to reflect linkage changes from weak resolution. 608 */ 609 void ThinLTOCodeGenerator::promote(Module &TheModule, ModuleSummaryIndex &Index, 610 const lto::InputFile &File) { 611 auto ModuleCount = Index.modulePaths().size(); 612 auto ModuleIdentifier = TheModule.getModuleIdentifier(); 613 614 // Collect for each module the list of function it defines (GUID -> Summary). 615 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries; 616 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 617 618 // Convert the preserved symbols set from string to GUID 619 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( 620 PreservedSymbols, Triple(TheModule.getTargetTriple())); 621 622 // Add used symbol to the preserved symbols. 623 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols); 624 625 // Compute "dead" symbols, we don't want to import/export these! 626 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); 627 628 // Generate import/export list 629 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 630 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 631 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 632 ExportLists); 633 634 // Resolve prevailing symbols 635 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; 636 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols); 637 638 thinLTOResolvePrevailingInModule( 639 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]); 640 641 // Promote the exported values in the index, so that they are promoted 642 // in the module. 643 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index); 644 645 promoteModule(TheModule, Index); 646 } 647 648 /** 649 * Perform cross-module importing for the module identified by ModuleIdentifier. 650 */ 651 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule, 652 ModuleSummaryIndex &Index, 653 const lto::InputFile &File) { 654 auto ModuleMap = generateModuleMap(Modules); 655 auto ModuleCount = Index.modulePaths().size(); 656 657 // Collect for each module the list of function it defines (GUID -> Summary). 658 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 659 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 660 661 // Convert the preserved symbols set from string to GUID 662 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( 663 PreservedSymbols, Triple(TheModule.getTargetTriple())); 664 665 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols); 666 667 // Compute "dead" symbols, we don't want to import/export these! 668 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); 669 670 // Generate import/export list 671 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 672 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 673 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 674 ExportLists); 675 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()]; 676 677 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList); 678 } 679 680 /** 681 * Compute the list of summaries needed for importing into module. 682 */ 683 void ThinLTOCodeGenerator::gatherImportedSummariesForModule( 684 Module &TheModule, ModuleSummaryIndex &Index, 685 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex, 686 const lto::InputFile &File) { 687 auto ModuleCount = Index.modulePaths().size(); 688 auto ModuleIdentifier = TheModule.getModuleIdentifier(); 689 690 // Collect for each module the list of function it defines (GUID -> Summary). 691 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 692 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 693 694 // Convert the preserved symbols set from string to GUID 695 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( 696 PreservedSymbols, Triple(TheModule.getTargetTriple())); 697 698 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols); 699 700 // Compute "dead" symbols, we don't want to import/export these! 701 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); 702 703 // Generate import/export list 704 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 705 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 706 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 707 ExportLists); 708 709 llvm::gatherImportedSummariesForModule( 710 ModuleIdentifier, ModuleToDefinedGVSummaries, 711 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex); 712 } 713 714 /** 715 * Emit the list of files needed for importing into module. 716 */ 717 void ThinLTOCodeGenerator::emitImports(Module &TheModule, StringRef OutputName, 718 ModuleSummaryIndex &Index, 719 const lto::InputFile &File) { 720 auto ModuleCount = Index.modulePaths().size(); 721 auto ModuleIdentifier = TheModule.getModuleIdentifier(); 722 723 // Collect for each module the list of function it defines (GUID -> Summary). 724 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 725 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 726 727 // Convert the preserved symbols set from string to GUID 728 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( 729 PreservedSymbols, Triple(TheModule.getTargetTriple())); 730 731 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols); 732 733 // Compute "dead" symbols, we don't want to import/export these! 734 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); 735 736 // Generate import/export list 737 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 738 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 739 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 740 ExportLists); 741 742 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex; 743 llvm::gatherImportedSummariesForModule( 744 ModuleIdentifier, ModuleToDefinedGVSummaries, 745 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex); 746 747 std::error_code EC; 748 if ((EC = EmitImportsFiles(ModuleIdentifier, OutputName, 749 ModuleToSummariesForIndex))) 750 report_fatal_error(Twine("Failed to open ") + OutputName + 751 " to save imports lists\n"); 752 } 753 754 /** 755 * Perform internalization. Runs promote and internalization together. 756 * Index is updated to reflect linkage changes. 757 */ 758 void ThinLTOCodeGenerator::internalize(Module &TheModule, 759 ModuleSummaryIndex &Index, 760 const lto::InputFile &File) { 761 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); 762 auto ModuleCount = Index.modulePaths().size(); 763 auto ModuleIdentifier = TheModule.getModuleIdentifier(); 764 765 // Convert the preserved symbols set from string to GUID 766 auto GUIDPreservedSymbols = 767 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple); 768 769 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols); 770 771 // Collect for each module the list of function it defines (GUID -> Summary). 772 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 773 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 774 775 // Compute "dead" symbols, we don't want to import/export these! 776 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); 777 778 // Generate import/export list 779 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 780 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 781 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 782 ExportLists); 783 auto &ExportList = ExportLists[ModuleIdentifier]; 784 785 // Be friendly and don't nuke totally the module when the client didn't 786 // supply anything to preserve. 787 if (ExportList.empty() && GUIDPreservedSymbols.empty()) 788 return; 789 790 // Resolve prevailing symbols 791 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; 792 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols); 793 794 // Promote the exported values in the index, so that they are promoted 795 // in the module. 796 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index); 797 798 promoteModule(TheModule, Index); 799 800 // Internalization 801 thinLTOResolvePrevailingInModule( 802 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]); 803 804 thinLTOInternalizeModule(TheModule, 805 ModuleToDefinedGVSummaries[ModuleIdentifier]); 806 } 807 808 /** 809 * Perform post-importing ThinLTO optimizations. 810 */ 811 void ThinLTOCodeGenerator::optimize(Module &TheModule) { 812 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); 813 814 // Optimize now 815 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding); 816 } 817 818 /// Write out the generated object file, either from CacheEntryPath or from 819 /// OutputBuffer, preferring hard-link when possible. 820 /// Returns the path to the generated file in SavedObjectsDirectoryPath. 821 std::string 822 ThinLTOCodeGenerator::writeGeneratedObject(int count, StringRef CacheEntryPath, 823 const MemoryBuffer &OutputBuffer) { 824 auto ArchName = TMBuilder.TheTriple.getArchName(); 825 SmallString<128> OutputPath(SavedObjectsDirectoryPath); 826 llvm::sys::path::append(OutputPath, 827 Twine(count) + "." + ArchName + ".thinlto.o"); 828 OutputPath.c_str(); // Ensure the string is null terminated. 829 if (sys::fs::exists(OutputPath)) 830 sys::fs::remove(OutputPath); 831 832 // We don't return a memory buffer to the linker, just a list of files. 833 if (!CacheEntryPath.empty()) { 834 // Cache is enabled, hard-link the entry (or copy if hard-link fails). 835 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath); 836 if (!Err) 837 return OutputPath.str(); 838 // Hard linking failed, try to copy. 839 Err = sys::fs::copy_file(CacheEntryPath, OutputPath); 840 if (!Err) 841 return OutputPath.str(); 842 // Copy failed (could be because the CacheEntry was removed from the cache 843 // in the meantime by another process), fall back and try to write down the 844 // buffer to the output. 845 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath 846 << "' to '" << OutputPath << "'\n"; 847 } 848 // No cache entry, just write out the buffer. 849 std::error_code Err; 850 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None); 851 if (Err) 852 report_fatal_error("Can't open output '" + OutputPath + "'\n"); 853 OS << OutputBuffer.getBuffer(); 854 return OutputPath.str(); 855 } 856 857 // Main entry point for the ThinLTO processing 858 void ThinLTOCodeGenerator::run() { 859 // Prepare the resulting object vector 860 assert(ProducedBinaries.empty() && "The generator should not be reused"); 861 if (SavedObjectsDirectoryPath.empty()) 862 ProducedBinaries.resize(Modules.size()); 863 else { 864 sys::fs::create_directories(SavedObjectsDirectoryPath); 865 bool IsDir; 866 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir); 867 if (!IsDir) 868 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'"); 869 ProducedBinaryFiles.resize(Modules.size()); 870 } 871 872 if (CodeGenOnly) { 873 // Perform only parallel codegen and return. 874 ThreadPool Pool; 875 int count = 0; 876 for (auto &Mod : Modules) { 877 Pool.async([&](int count) { 878 LLVMContext Context; 879 Context.setDiscardValueNames(LTODiscardValueNames); 880 881 // Parse module now 882 auto TheModule = loadModuleFromInput(Mod.get(), Context, false, 883 /*IsImporting*/ false); 884 885 // CodeGen 886 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create()); 887 if (SavedObjectsDirectoryPath.empty()) 888 ProducedBinaries[count] = std::move(OutputBuffer); 889 else 890 ProducedBinaryFiles[count] = 891 writeGeneratedObject(count, "", *OutputBuffer); 892 }, count++); 893 } 894 895 return; 896 } 897 898 // Sequential linking phase 899 auto Index = linkCombinedIndex(); 900 901 // Save temps: index. 902 if (!SaveTempsDir.empty()) { 903 auto SaveTempPath = SaveTempsDir + "index.bc"; 904 std::error_code EC; 905 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None); 906 if (EC) 907 report_fatal_error(Twine("Failed to open ") + SaveTempPath + 908 " to save optimized bitcode\n"); 909 WriteIndexToFile(*Index, OS); 910 } 911 912 913 // Prepare the module map. 914 auto ModuleMap = generateModuleMap(Modules); 915 auto ModuleCount = Modules.size(); 916 917 // Collect for each module the list of function it defines (GUID -> Summary). 918 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 919 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 920 921 // Convert the preserved symbols set from string to GUID, this is needed for 922 // computing the caching hash and the internalization. 923 auto GUIDPreservedSymbols = 924 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple); 925 926 // Add used symbol from inputs to the preserved symbols. 927 for (const auto &M : Modules) 928 addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols); 929 930 // Compute "dead" symbols, we don't want to import/export these! 931 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols); 932 933 // Synthesize entry counts for functions in the combined index. 934 computeSyntheticCounts(*Index); 935 936 // Collect the import/export lists for all modules from the call-graph in the 937 // combined index. 938 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 939 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 940 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists, 941 ExportLists); 942 943 // We use a std::map here to be able to have a defined ordering when 944 // producing a hash for the cache entry. 945 // FIXME: we should be able to compute the caching hash for the entry based 946 // on the index, and nuke this map. 947 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; 948 949 // Resolve prevailing symbols, this has to be computed early because it 950 // impacts the caching. 951 resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols); 952 953 // Use global summary-based analysis to identify symbols that can be 954 // internalized (because they aren't exported or preserved as per callback). 955 // Changes are made in the index, consumed in the ThinLTO backends. 956 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index); 957 958 // Make sure that every module has an entry in the ExportLists, ImportList, 959 // GVSummary and ResolvedODR maps to enable threaded access to these maps 960 // below. 961 for (auto &Module : Modules) { 962 auto ModuleIdentifier = Module->getName(); 963 ExportLists[ModuleIdentifier]; 964 ImportLists[ModuleIdentifier]; 965 ResolvedODR[ModuleIdentifier]; 966 ModuleToDefinedGVSummaries[ModuleIdentifier]; 967 } 968 969 // Compute the ordering we will process the inputs: the rough heuristic here 970 // is to sort them per size so that the largest module get schedule as soon as 971 // possible. This is purely a compile-time optimization. 972 std::vector<int> ModulesOrdering; 973 ModulesOrdering.resize(Modules.size()); 974 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0); 975 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) { 976 auto LSize = 977 Modules[LeftIndex]->getSingleBitcodeModule().getBuffer().size(); 978 auto RSize = 979 Modules[RightIndex]->getSingleBitcodeModule().getBuffer().size(); 980 return LSize > RSize; 981 }); 982 983 // Parallel optimizer + codegen 984 { 985 ThreadPool Pool(ThreadCount); 986 for (auto IndexCount : ModulesOrdering) { 987 auto &Mod = Modules[IndexCount]; 988 Pool.async([&](int count) { 989 auto ModuleIdentifier = Mod->getName(); 990 auto &ExportList = ExportLists[ModuleIdentifier]; 991 992 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier]; 993 994 // The module may be cached, this helps handling it. 995 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier, 996 ImportLists[ModuleIdentifier], ExportList, 997 ResolvedODR[ModuleIdentifier], 998 DefinedGVSummaries, OptLevel, Freestanding, 999 TMBuilder); 1000 auto CacheEntryPath = CacheEntry.getEntryPath(); 1001 1002 { 1003 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer(); 1004 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") 1005 << " '" << CacheEntryPath << "' for buffer " 1006 << count << " " << ModuleIdentifier << "\n"); 1007 1008 if (ErrOrBuffer) { 1009 // Cache Hit! 1010 if (SavedObjectsDirectoryPath.empty()) 1011 ProducedBinaries[count] = std::move(ErrOrBuffer.get()); 1012 else 1013 ProducedBinaryFiles[count] = writeGeneratedObject( 1014 count, CacheEntryPath, *ErrOrBuffer.get()); 1015 return; 1016 } 1017 } 1018 1019 LLVMContext Context; 1020 Context.setDiscardValueNames(LTODiscardValueNames); 1021 Context.enableDebugTypeODRUniquing(); 1022 auto DiagFileOrErr = lto::setupOptimizationRemarks( 1023 Context, RemarksFilename, RemarksPasses, RemarksFormat, 1024 RemarksWithHotness, count); 1025 if (!DiagFileOrErr) { 1026 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n"; 1027 report_fatal_error("ThinLTO: Can't get an output file for the " 1028 "remarks"); 1029 } 1030 1031 // Parse module now 1032 auto TheModule = loadModuleFromInput(Mod.get(), Context, false, 1033 /*IsImporting*/ false); 1034 1035 // Save temps: original file. 1036 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc"); 1037 1038 auto &ImportList = ImportLists[ModuleIdentifier]; 1039 // Run the main process now, and generates a binary 1040 auto OutputBuffer = ProcessThinLTOModule( 1041 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList, 1042 ExportList, GUIDPreservedSymbols, 1043 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions, 1044 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count); 1045 1046 // Commit to the cache (if enabled) 1047 CacheEntry.write(*OutputBuffer); 1048 1049 if (SavedObjectsDirectoryPath.empty()) { 1050 // We need to generated a memory buffer for the linker. 1051 if (!CacheEntryPath.empty()) { 1052 // When cache is enabled, reload from the cache if possible. 1053 // Releasing the buffer from the heap and reloading it from the 1054 // cache file with mmap helps us to lower memory pressure. 1055 // The freed memory can be used for the next input file. 1056 // The final binary link will read from the VFS cache (hopefully!) 1057 // or from disk (if the memory pressure was too high). 1058 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer(); 1059 if (auto EC = ReloadedBufferOrErr.getError()) { 1060 // On error, keep the preexisting buffer and print a diagnostic. 1061 errs() << "error: can't reload cached file '" << CacheEntryPath 1062 << "': " << EC.message() << "\n"; 1063 } else { 1064 OutputBuffer = std::move(*ReloadedBufferOrErr); 1065 } 1066 } 1067 ProducedBinaries[count] = std::move(OutputBuffer); 1068 return; 1069 } 1070 ProducedBinaryFiles[count] = writeGeneratedObject( 1071 count, CacheEntryPath, *OutputBuffer); 1072 }, IndexCount); 1073 } 1074 } 1075 1076 pruneCache(CacheOptions.Path, CacheOptions.Policy); 1077 1078 // If statistics were requested, print them out now. 1079 if (llvm::AreStatisticsEnabled()) 1080 llvm::PrintStatistics(); 1081 reportAndResetTimings(); 1082 } 1083