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