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