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