1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
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/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IRReader/IRReader.h"
32 #include "llvm/LTO/LTO.h"
33 #include "llvm/Linker/Linker.h"
34 #include "llvm/MC/SubtargetFeature.h"
35 #include "llvm/Object/IRObjectFile.h"
36 #include "llvm/Support/CachePruning.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Error.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/SHA1.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/ThreadPool.h"
43 #include "llvm/Support/Threading.h"
44 #include "llvm/Support/ToolOutputFile.h"
45 #include "llvm/Support/VCSRevision.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Transforms/IPO.h"
48 #include "llvm/Transforms/IPO/FunctionImport.h"
49 #include "llvm/Transforms/IPO/Internalize.h"
50 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
51 #include "llvm/Transforms/ObjCARC.h"
52 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
58 #define DEBUG_TYPE "thinlto"
61 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
62 extern cl::opt<bool> LTODiscardValueNames;
63 extern cl::opt<std::string> LTORemarksFilename;
64 extern cl::opt<bool> LTOPassRemarksWithHotness;
70 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
72 // Simple helper to save temporary files for debug.
73 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
74 unsigned count, StringRef Suffix) {
77 // User asked to save temps, let dump the bitcode file after import.
78 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
80 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
82 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
83 " to save optimized bitcode\n");
84 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
87 static const GlobalValueSummary *
88 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
89 // If there is any strong definition anywhere, get it.
90 auto StrongDefForLinker = llvm::find_if(
91 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
92 auto Linkage = Summary->linkage();
93 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
94 !GlobalValue::isWeakForLinker(Linkage);
96 if (StrongDefForLinker != GVSummaryList.end())
97 return StrongDefForLinker->get();
98 // Get the first *linker visible* definition for this global in the summary
100 auto FirstDefForLinker = llvm::find_if(
101 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
102 auto Linkage = Summary->linkage();
103 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
105 // Extern templates can be emitted as available_externally.
106 if (FirstDefForLinker == GVSummaryList.end())
108 return FirstDefForLinker->get();
111 // Populate map of GUID to the prevailing copy for any multiply defined
112 // symbols. Currently assume first copy is prevailing, or any strong
113 // definition. Can be refined with Linker information in the future.
114 static void computePrevailingCopies(
115 const ModuleSummaryIndex &Index,
116 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
117 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
118 return GVSummaryList.size() > 1;
121 for (auto &I : Index) {
122 if (HasMultipleCopies(I.second))
123 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
127 static StringMap<MemoryBufferRef>
128 generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
129 StringMap<MemoryBufferRef> ModuleMap;
130 for (auto &ModuleBuffer : Modules) {
131 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
133 "Expect unique Buffer Identifier");
134 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
139 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
140 if (renameModuleForThinLTO(TheModule, Index))
141 report_fatal_error("renameModuleForThinLTO failed");
144 static std::unique_ptr<Module>
145 loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
146 bool Lazy, bool IsImporting) {
148 Expected<std::unique_ptr<Module>> ModuleOrErr =
150 ? getLazyBitcodeModule(Buffer, Context,
151 /* ShouldLazyLoadMetadata */ true, IsImporting)
152 : parseBitcodeFile(Buffer, Context);
154 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
155 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
156 SourceMgr::DK_Error, EIB.message());
157 Err.print("ThinLTO", errs());
159 report_fatal_error("Can't load module, abort.");
161 return std::move(ModuleOrErr.get());
165 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
166 StringMap<MemoryBufferRef> &ModuleMap,
167 const FunctionImporter::ImportMapTy &ImportList) {
168 auto Loader = [&](StringRef Identifier) {
169 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
170 /*Lazy=*/true, /*IsImporting*/ true);
173 FunctionImporter Importer(Index, Loader);
174 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
176 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
177 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
178 SourceMgr::DK_Error, EIB.message());
179 Err.print("ThinLTO", errs());
181 report_fatal_error("importFunctions failed");
185 static void optimizeModule(Module &TheModule, TargetMachine &TM,
186 unsigned OptLevel, bool Freestanding) {
187 // Populate the PassManager
188 PassManagerBuilder PMB;
189 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
191 PMB.LibraryInfo->disableAllFunctions();
192 PMB.Inliner = createFunctionInliningPass();
193 // FIXME: should get it from the bitcode?
194 PMB.OptLevel = OptLevel;
195 PMB.LoopVectorize = true;
196 PMB.SLPVectorize = true;
197 PMB.VerifyInput = true;
198 PMB.VerifyOutput = false;
200 legacy::PassManager PM;
202 // Add the TTI (required to inform the vectorizer about register size for
204 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
207 PMB.populateThinLTOPassManager(PM);
212 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
213 static DenseSet<GlobalValue::GUID>
214 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
215 const Triple &TheTriple) {
216 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
217 for (auto &Entry : PreservedSymbols) {
218 StringRef Name = Entry.first();
219 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
220 Name = Name.drop_front();
221 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
223 return GUIDPreservedSymbols;
226 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
228 SmallVector<char, 128> OutputBuffer;
232 raw_svector_ostream OS(OutputBuffer);
233 legacy::PassManager PM;
235 // If the bitcode files contain ARC code and were compiled with optimization,
236 // the ObjCARCContractPass must be run, so do it unconditionally here.
237 PM.add(createObjCARCContractPass());
239 // Setup the codegen now.
240 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
241 /* DisableVerify */ true))
242 report_fatal_error("Failed to setup codegen");
244 // Run codegen now. resulting binary is in OutputBuffer.
247 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
250 /// Manage caching for a single Module.
251 class ModuleCacheEntry {
252 SmallString<128> EntryPath;
255 // Create a cache entry. This compute a unique hash for the Module considering
256 // the current list of export/import, and offer an interface to query to
257 // access the content in the cache.
259 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
260 const FunctionImporter::ImportMapTy &ImportList,
261 const FunctionImporter::ExportSetTy &ExportList,
262 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
263 const GVSummaryMapTy &DefinedFunctions,
264 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
265 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
266 if (CachePath.empty())
269 if (!Index.modulePaths().count(ModuleID))
270 // The module does not have an entry, it can't have a hash at all
273 // Compute the unique hash for this entry
274 // This is based on the current compiler version, the module itself, the
275 // export list, the hash for every single module in the import list, the
276 // list of ResolvedODR for the module, and the list of preserved symbols.
278 // Include the hash for the current module
279 auto ModHash = Index.getModuleHash(ModuleID);
281 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
282 // No hash entry, no caching!
287 // Include the parts of the LTO configuration that affect code generation.
288 auto AddString = [&](StringRef Str) {
290 Hasher.update(ArrayRef<uint8_t>{0});
292 auto AddUnsigned = [&](unsigned I) {
298 Hasher.update(ArrayRef<uint8_t>{Data, 4});
301 // Start with the compiler revision
302 Hasher.update(LLVM_VERSION_STRING);
304 Hasher.update(LLVM_REVISION);
307 // Hash the optimization level and the target machine settings.
308 AddString(TMBuilder.MCpu);
309 // FIXME: Hash more of Options. For now all clients initialize Options from
310 // command-line flags (which is unsupported in production), but may set
311 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
312 // DataSections and DebuggerTuning via command line flags.
313 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
314 AddUnsigned(TMBuilder.Options.FunctionSections);
315 AddUnsigned(TMBuilder.Options.DataSections);
316 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
317 AddString(TMBuilder.MAttr);
318 if (TMBuilder.RelocModel)
319 AddUnsigned(*TMBuilder.RelocModel);
320 AddUnsigned(TMBuilder.CGOptLevel);
321 AddUnsigned(OptLevel);
322 AddUnsigned(Freestanding);
324 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
325 for (auto F : ExportList)
326 // The export list can impact the internalization, be conservative here
327 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
329 // Include the hash for every module we import functions from
330 for (auto &Entry : ImportList) {
331 auto ModHash = Index.getModuleHash(Entry.first());
332 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
335 // Include the hash for the resolved ODR.
336 for (auto &Entry : ResolvedODR) {
337 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
338 sizeof(GlobalValue::GUID)));
339 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
340 sizeof(GlobalValue::LinkageTypes)));
343 // Include the hash for the preserved symbols.
344 for (auto &Entry : PreservedSymbols) {
345 if (DefinedFunctions.count(Entry))
347 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
350 // This choice of file name allows the cache to be pruned (see pruneCache()
351 // in include/llvm/Support/CachePruning.h).
352 sys::path::append(EntryPath, CachePath,
353 "llvmcache-" + toHex(Hasher.result()));
356 // Access the path to this entry in the cache.
357 StringRef getEntryPath() { return EntryPath; }
359 // Try loading the buffer for this cache entry.
360 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
361 if (EntryPath.empty())
362 return std::error_code();
363 return MemoryBuffer::getFile(EntryPath);
366 // Cache the Produced object file
367 void write(const MemoryBuffer &OutputBuffer) {
368 if (EntryPath.empty())
371 // Write to a temporary to avoid race condition
372 SmallString<128> TempFilename;
375 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
377 errs() << "Error: " << EC.message() << "\n";
378 report_fatal_error("ThinLTO: Can't get a temporary file");
381 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
382 OS << OutputBuffer.getBuffer();
384 // Rename to final destination (hopefully race condition won't matter here)
385 EC = sys::fs::rename(TempFilename, EntryPath);
387 sys::fs::remove(TempFilename);
388 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
390 report_fatal_error(Twine("Failed to open ") + EntryPath +
391 " to save cached entry\n");
392 OS << OutputBuffer.getBuffer();
397 static std::unique_ptr<MemoryBuffer>
398 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
399 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
400 const FunctionImporter::ImportMapTy &ImportList,
401 const FunctionImporter::ExportSetTy &ExportList,
402 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
403 const GVSummaryMapTy &DefinedGlobals,
404 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
405 bool DisableCodeGen, StringRef SaveTempsDir,
406 bool Freestanding, unsigned OptLevel, unsigned count) {
408 // "Benchmark"-like optimization: single-source case
409 bool SingleModule = (ModuleMap.size() == 1);
412 promoteModule(TheModule, Index);
414 // Apply summary-based LinkOnce/Weak resolution decisions.
415 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
417 // Save temps: after promotion.
418 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
421 // Be friendly and don't nuke totally the module when the client didn't
422 // supply anything to preserve.
423 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
424 // Apply summary-based internalization decisions.
425 thinLTOInternalizeModule(TheModule, DefinedGlobals);
428 // Save internalized bitcode
429 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
432 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
434 // Save temps: after cross-module import.
435 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
438 optimizeModule(TheModule, TM, OptLevel, Freestanding);
440 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
442 if (DisableCodeGen) {
443 // Configured to stop before CodeGen, serialize the bitcode and return.
444 SmallVector<char, 128> OutputBuffer;
446 raw_svector_ostream OS(OutputBuffer);
447 ProfileSummaryInfo PSI(TheModule);
448 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
449 WriteBitcodeToFile(&TheModule, OS, true, &Index);
451 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
454 return codegenModule(TheModule, TM);
457 /// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
458 /// for caching, and in the \p Index for application during the ThinLTO
459 /// backends. This is needed for correctness for exported symbols (ensure
460 /// at least one copy kept) and a compile-time optimization (to drop duplicate
461 /// copies when possible).
462 static void resolveWeakForLinkerInIndex(
463 ModuleSummaryIndex &Index,
464 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
467 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
468 computePrevailingCopies(Index, PrevailingCopy);
470 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
471 const auto &Prevailing = PrevailingCopy.find(GUID);
472 // Not in map means that there was only one copy, which must be prevailing.
473 if (Prevailing == PrevailingCopy.end())
475 return Prevailing->second == S;
478 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
479 GlobalValue::GUID GUID,
480 GlobalValue::LinkageTypes NewLinkage) {
481 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
484 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
487 // Initialize the TargetMachine builder for a given Triple
488 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
489 const Triple &TheTriple) {
490 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
491 // FIXME this looks pretty terrible...
492 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
493 if (TheTriple.getArch() == llvm::Triple::x86_64)
494 TMBuilder.MCpu = "core2";
495 else if (TheTriple.getArch() == llvm::Triple::x86)
496 TMBuilder.MCpu = "yonah";
497 else if (TheTriple.getArch() == llvm::Triple::aarch64)
498 TMBuilder.MCpu = "cyclone";
500 TMBuilder.TheTriple = std::move(TheTriple);
503 } // end anonymous namespace
505 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
506 ThinLTOBuffer Buffer(Data, Identifier);
507 if (Modules.empty()) {
508 // First module added, so initialize the triple and some options
511 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
512 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
514 TripleStr = *TripleOrErr;
515 Triple TheTriple(TripleStr);
516 initTMBuilder(TMBuilder, Triple(TheTriple));
522 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
523 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
525 TripleStr = *TripleOrErr;
526 assert(TMBuilder.TheTriple.str() == TripleStr &&
527 "ThinLTO modules with different triple not supported");
530 Modules.push_back(Buffer);
533 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
534 PreservedSymbols.insert(Name);
537 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
538 // FIXME: At the moment, we don't take advantage of this extra information,
539 // we're conservatively considering cross-references as preserved.
540 // CrossReferencedSymbols.insert(Name);
541 PreservedSymbols.insert(Name);
544 // TargetMachine factory
545 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
547 const Target *TheTarget =
548 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
550 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
553 // Use MAttr as the default set of features.
554 SubtargetFeatures Features(MAttr);
555 Features.getDefaultSubtargetFeatures(TheTriple);
556 std::string FeatureStr = Features.getString();
558 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
559 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
560 CodeModel::Default, CGOptLevel));
564 * Produce the combined summary index from all the bitcode files:
567 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
568 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
569 llvm::make_unique<ModuleSummaryIndex>();
570 uint64_t NextModuleId = 0;
571 for (auto &ModuleBuffer : Modules) {
572 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
573 *CombinedIndex, NextModuleId++)) {
575 logAllUnhandledErrors(
576 std::move(Err), errs(),
577 "error: can't create module summary index for buffer: ");
581 return CombinedIndex;
585 * Perform promotion and renaming of exported internal functions.
586 * Index is updated to reflect linkage changes from weak resolution.
588 void ThinLTOCodeGenerator::promote(Module &TheModule,
589 ModuleSummaryIndex &Index) {
590 auto ModuleCount = Index.modulePaths().size();
591 auto ModuleIdentifier = TheModule.getModuleIdentifier();
593 // Collect for each module the list of function it defines (GUID -> Summary).
594 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
595 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
597 // Convert the preserved symbols set from string to GUID
598 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
599 PreservedSymbols, Triple(TheModule.getTargetTriple()));
601 // Compute "dead" symbols, we don't want to import/export these!
602 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
604 // Generate import/export list
605 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
606 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
607 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
608 ExportLists, &DeadSymbols);
610 // Resolve LinkOnce/Weak symbols.
611 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
612 resolveWeakForLinkerInIndex(Index, ResolvedODR);
614 thinLTOResolveWeakForLinkerModule(
615 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
617 // Promote the exported values in the index, so that they are promoted
619 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
620 const auto &ExportList = ExportLists.find(ModuleIdentifier);
621 return (ExportList != ExportLists.end() &&
622 ExportList->second.count(GUID)) ||
623 GUIDPreservedSymbols.count(GUID);
625 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
627 promoteModule(TheModule, Index);
631 * Perform cross-module importing for the module identified by ModuleIdentifier.
633 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
634 ModuleSummaryIndex &Index) {
635 auto ModuleMap = generateModuleMap(Modules);
636 auto ModuleCount = Index.modulePaths().size();
638 // Collect for each module the list of function it defines (GUID -> Summary).
639 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
640 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
642 // Convert the preserved symbols set from string to GUID
643 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
644 PreservedSymbols, Triple(TheModule.getTargetTriple()));
646 // Compute "dead" symbols, we don't want to import/export these!
647 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
649 // Generate import/export list
650 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
651 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
652 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
653 ExportLists, &DeadSymbols);
654 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
656 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
660 * Compute the list of summaries needed for importing into module.
662 void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
663 StringRef ModulePath, ModuleSummaryIndex &Index,
664 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
665 auto ModuleCount = Index.modulePaths().size();
667 // Collect for each module the list of function it defines (GUID -> Summary).
668 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
669 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
671 // Generate import/export list
672 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
673 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
674 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
677 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
678 ImportLists[ModulePath],
679 ModuleToSummariesForIndex);
683 * Emit the list of files needed for importing into module.
685 void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
686 StringRef OutputName,
687 ModuleSummaryIndex &Index) {
688 auto ModuleCount = Index.modulePaths().size();
690 // Collect for each module the list of function it defines (GUID -> Summary).
691 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
692 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
694 // Generate import/export list
695 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
696 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
697 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
701 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
702 report_fatal_error(Twine("Failed to open ") + OutputName +
703 " to save imports lists\n");
707 * Perform internalization. Index is updated to reflect linkage changes.
709 void ThinLTOCodeGenerator::internalize(Module &TheModule,
710 ModuleSummaryIndex &Index) {
711 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
712 auto ModuleCount = Index.modulePaths().size();
713 auto ModuleIdentifier = TheModule.getModuleIdentifier();
715 // Convert the preserved symbols set from string to GUID
716 auto GUIDPreservedSymbols =
717 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
719 // Collect for each module the list of function it defines (GUID -> Summary).
720 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
721 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
723 // Compute "dead" symbols, we don't want to import/export these!
724 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
726 // Generate import/export list
727 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
728 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
729 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
730 ExportLists, &DeadSymbols);
731 auto &ExportList = ExportLists[ModuleIdentifier];
733 // Be friendly and don't nuke totally the module when the client didn't
734 // supply anything to preserve.
735 if (ExportList.empty() && GUIDPreservedSymbols.empty())
739 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
740 const auto &ExportList = ExportLists.find(ModuleIdentifier);
741 return (ExportList != ExportLists.end() &&
742 ExportList->second.count(GUID)) ||
743 GUIDPreservedSymbols.count(GUID);
745 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
746 thinLTOInternalizeModule(TheModule,
747 ModuleToDefinedGVSummaries[ModuleIdentifier]);
751 * Perform post-importing ThinLTO optimizations.
753 void ThinLTOCodeGenerator::optimize(Module &TheModule) {
754 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
757 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
761 * Perform ThinLTO CodeGen.
763 std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
764 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
765 return codegenModule(TheModule, *TMBuilder.create());
768 /// Write out the generated object file, either from CacheEntryPath or from
769 /// OutputBuffer, preferring hard-link when possible.
770 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
771 static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
772 StringRef SavedObjectsDirectoryPath,
773 const MemoryBuffer &OutputBuffer) {
774 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
775 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
776 OutputPath.c_str(); // Ensure the string is null terminated.
777 if (sys::fs::exists(OutputPath))
778 sys::fs::remove(OutputPath);
780 // We don't return a memory buffer to the linker, just a list of files.
781 if (!CacheEntryPath.empty()) {
782 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
783 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
785 return OutputPath.str();
786 // Hard linking failed, try to copy.
787 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
789 return OutputPath.str();
790 // Copy failed (could be because the CacheEntry was removed from the cache
791 // in the meantime by another process), fall back and try to write down the
792 // buffer to the output.
793 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
794 << "' to '" << OutputPath << "'\n";
796 // No cache entry, just write out the buffer.
798 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
800 report_fatal_error("Can't open output '" + OutputPath + "'\n");
801 OS << OutputBuffer.getBuffer();
802 return OutputPath.str();
805 // Main entry point for the ThinLTO processing
806 void ThinLTOCodeGenerator::run() {
807 // Prepare the resulting object vector
808 assert(ProducedBinaries.empty() && "The generator should not be reused");
809 if (SavedObjectsDirectoryPath.empty())
810 ProducedBinaries.resize(Modules.size());
812 sys::fs::create_directories(SavedObjectsDirectoryPath);
814 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
816 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
817 ProducedBinaryFiles.resize(Modules.size());
821 // Perform only parallel codegen and return.
824 for (auto &ModuleBuffer : Modules) {
825 Pool.async([&](int count) {
827 Context.setDiscardValueNames(LTODiscardValueNames);
831 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
832 /*IsImporting*/ false);
835 auto OutputBuffer = codegen(*TheModule);
836 if (SavedObjectsDirectoryPath.empty())
837 ProducedBinaries[count] = std::move(OutputBuffer);
839 ProducedBinaryFiles[count] = writeGeneratedObject(
840 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
847 // Sequential linking phase
848 auto Index = linkCombinedIndex();
850 // Save temps: index.
851 if (!SaveTempsDir.empty()) {
852 auto SaveTempPath = SaveTempsDir + "index.bc";
854 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
856 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
857 " to save optimized bitcode\n");
858 WriteIndexToFile(*Index, OS);
862 // Prepare the module map.
863 auto ModuleMap = generateModuleMap(Modules);
864 auto ModuleCount = Modules.size();
866 // Collect for each module the list of function it defines (GUID -> Summary).
867 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
868 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
870 // Convert the preserved symbols set from string to GUID, this is needed for
871 // computing the caching hash and the internalization.
872 auto GUIDPreservedSymbols =
873 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
875 // Compute "dead" symbols, we don't want to import/export these!
876 auto DeadSymbols = computeDeadSymbols(*Index, GUIDPreservedSymbols);
878 // Collect the import/export lists for all modules from the call-graph in the
880 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
881 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
882 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
883 ExportLists, &DeadSymbols);
885 // We use a std::map here to be able to have a defined ordering when
886 // producing a hash for the cache entry.
887 // FIXME: we should be able to compute the caching hash for the entry based
888 // on the index, and nuke this map.
889 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
891 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
892 // impacts the caching.
893 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
895 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
896 const auto &ExportList = ExportLists.find(ModuleIdentifier);
897 return (ExportList != ExportLists.end() &&
898 ExportList->second.count(GUID)) ||
899 GUIDPreservedSymbols.count(GUID);
902 // Use global summary-based analysis to identify symbols that can be
903 // internalized (because they aren't exported or preserved as per callback).
904 // Changes are made in the index, consumed in the ThinLTO backends.
905 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
907 // Make sure that every module has an entry in the ExportLists and
908 // ResolvedODR maps to enable threaded access to these maps below.
909 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
910 ExportLists[DefinedGVSummaries.first()];
911 ResolvedODR[DefinedGVSummaries.first()];
914 // Compute the ordering we will process the inputs: the rough heuristic here
915 // is to sort them per size so that the largest module get schedule as soon as
916 // possible. This is purely a compile-time optimization.
917 std::vector<int> ModulesOrdering;
918 ModulesOrdering.resize(Modules.size());
919 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
920 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
921 [&](int LeftIndex, int RightIndex) {
922 auto LSize = Modules[LeftIndex].getBuffer().size();
923 auto RSize = Modules[RightIndex].getBuffer().size();
924 return LSize > RSize;
927 // Parallel optimizer + codegen
929 ThreadPool Pool(ThreadCount);
930 for (auto IndexCount : ModulesOrdering) {
931 auto &ModuleBuffer = Modules[IndexCount];
932 Pool.async([&](int count) {
933 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
934 auto &ExportList = ExportLists[ModuleIdentifier];
936 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
938 // The module may be cached, this helps handling it.
939 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
940 ImportLists[ModuleIdentifier], ExportList,
941 ResolvedODR[ModuleIdentifier],
942 DefinedFunctions, GUIDPreservedSymbols,
943 OptLevel, Freestanding, TMBuilder);
944 auto CacheEntryPath = CacheEntry.getEntryPath();
947 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
948 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
949 << CacheEntryPath << "' for buffer " << count << " "
950 << ModuleIdentifier << "\n");
954 if (SavedObjectsDirectoryPath.empty())
955 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
957 ProducedBinaryFiles[count] = writeGeneratedObject(
958 count, CacheEntryPath, SavedObjectsDirectoryPath,
965 Context.setDiscardValueNames(LTODiscardValueNames);
966 Context.enableDebugTypeODRUniquing();
967 auto DiagFileOrErr = lto::setupOptimizationRemarks(
968 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
969 if (!DiagFileOrErr) {
970 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
971 report_fatal_error("ThinLTO: Can't get an output file for the "
977 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
978 /*IsImporting*/ false);
980 // Save temps: original file.
981 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
983 auto &ImportList = ImportLists[ModuleIdentifier];
984 // Run the main process now, and generates a binary
985 auto OutputBuffer = ProcessThinLTOModule(
986 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
987 ExportList, GUIDPreservedSymbols,
988 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
989 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
991 // Commit to the cache (if enabled)
992 CacheEntry.write(*OutputBuffer);
994 if (SavedObjectsDirectoryPath.empty()) {
995 // We need to generated a memory buffer for the linker.
996 if (!CacheEntryPath.empty()) {
997 // Cache is enabled, reload from the cache
998 // We do this to lower memory pressuree: the buffer is on the heap
999 // and releasing it frees memory that can be used for the next input
1000 // file. The final binary link will read from the VFS cache
1001 // (hopefully!) or from disk if the memory pressure wasn't too high.
1002 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1003 if (auto EC = ReloadedBufferOrErr.getError()) {
1004 // On error, keeping the preexisting buffer and printing a
1005 // diagnostic is more friendly than just crashing.
1006 errs() << "error: can't reload cached file '" << CacheEntryPath
1007 << "': " << EC.message() << "\n";
1009 OutputBuffer = std::move(*ReloadedBufferOrErr);
1012 ProducedBinaries[count] = std::move(OutputBuffer);
1015 ProducedBinaryFiles[count] = writeGeneratedObject(
1016 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
1021 pruneCache(CacheOptions.Path, CacheOptions.Policy);
1023 // If statistics were requested, print them out now.
1024 if (llvm::AreStatisticsEnabled())
1025 llvm::PrintStatistics();