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