1 //===-LTO.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 functions and classes used to support LTO.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/LTO/LTO.h"
15 #include "llvm/Analysis/TargetLibraryInfo.h"
16 #include "llvm/Analysis/TargetTransformInfo.h"
17 #include "llvm/Bitcode/BitcodeReader.h"
18 #include "llvm/Bitcode/BitcodeWriter.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/IR/AutoUpgrade.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/LTO/LTOBackend.h"
26 #include "llvm/Linker/IRMover.h"
27 #include "llvm/Object/IRObjectFile.h"
28 #include "llvm/Support/Error.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/SHA1.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/ThreadPool.h"
36 #include "llvm/Support/Threading.h"
37 #include "llvm/Support/VCSRevision.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Transforms/IPO.h"
42 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
43 #include "llvm/Transforms/Utils/SplitModule.h"
49 using namespace object;
51 #define DEBUG_TYPE "lto"
53 // The values are (type identifier, summary) pairs.
56 TinyPtrVector<const std::pair<const std::string, TypeIdSummary> *>>
57 TypeIdSummariesByGuidTy;
59 // Returns a unique hash for the Module considering the current list of
60 // export/import and other global analysis results.
61 // The hash is produced in \p Key.
62 static void computeCacheKey(
63 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
64 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
65 const FunctionImporter::ExportSetTy &ExportList,
66 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
67 const GVSummaryMapTy &DefinedGlobals,
68 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
69 // Compute the unique hash for this entry.
70 // This is based on the current compiler version, the module itself, the
71 // export list, the hash for every single module in the import list, the
72 // list of ResolvedODR for the module, and the list of preserved symbols.
75 // Start with the compiler revision
76 Hasher.update(LLVM_VERSION_STRING);
78 Hasher.update(LLVM_REVISION);
81 // Include the parts of the LTO configuration that affect code generation.
82 auto AddString = [&](StringRef Str) {
84 Hasher.update(ArrayRef<uint8_t>{0});
86 auto AddUnsigned = [&](unsigned I) {
92 Hasher.update(ArrayRef<uint8_t>{Data, 4});
94 auto AddUint64 = [&](uint64_t I) {
104 Hasher.update(ArrayRef<uint8_t>{Data, 8});
107 // FIXME: Hash more of Options. For now all clients initialize Options from
108 // command-line flags (which is unsupported in production), but may set
109 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
110 // DataSections and DebuggerTuning via command line flags.
111 AddUnsigned(Conf.Options.RelaxELFRelocations);
112 AddUnsigned(Conf.Options.FunctionSections);
113 AddUnsigned(Conf.Options.DataSections);
114 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
115 for (auto &A : Conf.MAttrs)
118 AddUnsigned(*Conf.RelocModel);
121 AddUnsigned(Conf.CodeModel);
122 AddUnsigned(Conf.CGOptLevel);
123 AddUnsigned(Conf.CGFileType);
124 AddUnsigned(Conf.OptLevel);
125 AddUnsigned(Conf.UseNewPM);
126 AddString(Conf.OptPipeline);
127 AddString(Conf.AAPipeline);
128 AddString(Conf.OverrideTriple);
129 AddString(Conf.DefaultTriple);
131 // Include the hash for the current module
132 auto ModHash = Index.getModuleHash(ModuleID);
133 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
134 for (auto F : ExportList)
135 // The export list can impact the internalization, be conservative here
136 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
138 // Include the hash for every module we import functions from. The set of
139 // imported symbols for each module may affect code generation and is
140 // sensitive to link order, so include that as well.
141 for (auto &Entry : ImportList) {
142 auto ModHash = Index.getModuleHash(Entry.first());
143 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
145 AddUint64(Entry.second.size());
146 for (auto &Fn : Entry.second)
150 // Include the hash for the resolved ODR.
151 for (auto &Entry : ResolvedODR) {
152 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
153 sizeof(GlobalValue::GUID)));
154 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
155 sizeof(GlobalValue::LinkageTypes)));
158 std::set<GlobalValue::GUID> UsedTypeIds;
160 auto AddUsedTypeIds = [&](GlobalValueSummary *GS) {
161 auto *FS = dyn_cast_or_null<FunctionSummary>(GS);
164 for (auto &TT : FS->type_tests())
165 UsedTypeIds.insert(TT);
166 for (auto &TT : FS->type_test_assume_vcalls())
167 UsedTypeIds.insert(TT.GUID);
168 for (auto &TT : FS->type_checked_load_vcalls())
169 UsedTypeIds.insert(TT.GUID);
170 for (auto &TT : FS->type_test_assume_const_vcalls())
171 UsedTypeIds.insert(TT.VFunc.GUID);
172 for (auto &TT : FS->type_checked_load_const_vcalls())
173 UsedTypeIds.insert(TT.VFunc.GUID);
176 // Include the hash for the linkage type to reflect internalization and weak
177 // resolution, and collect any used type identifier resolutions.
178 for (auto &GS : DefinedGlobals) {
179 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
181 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
182 AddUsedTypeIds(GS.second);
185 // Imported functions may introduce new uses of type identifier resolutions,
186 // so we need to collect their used resolutions as well.
187 for (auto &ImpM : ImportList)
188 for (auto &ImpF : ImpM.second)
189 AddUsedTypeIds(Index.findSummaryInModule(ImpF.first, ImpM.first()));
191 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
194 AddUnsigned(S.TTRes.TheKind);
195 AddUnsigned(S.TTRes.SizeM1BitWidth);
197 AddUint64(S.WPDRes.size());
198 for (auto &WPD : S.WPDRes) {
199 AddUnsigned(WPD.first);
200 AddUnsigned(WPD.second.TheKind);
201 AddString(WPD.second.SingleImplName);
203 AddUint64(WPD.second.ResByArg.size());
204 for (auto &ByArg : WPD.second.ResByArg) {
205 AddUint64(ByArg.first.size());
206 for (uint64_t Arg : ByArg.first)
208 AddUnsigned(ByArg.second.TheKind);
209 AddUint64(ByArg.second.Info);
214 // Include the hash for all type identifiers used by this module.
215 for (GlobalValue::GUID TId : UsedTypeIds) {
216 auto SummariesI = TypeIdSummariesByGuid.find(TId);
217 if (SummariesI != TypeIdSummariesByGuid.end())
218 for (auto *Summary : SummariesI->second)
219 AddTypeIdSummary(Summary->first, Summary->second);
222 if (!Conf.SampleProfile.empty()) {
223 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
225 Hasher.update(FileOrErr.get()->getBuffer());
228 Key = toHex(Hasher.result());
231 static void thinLTOResolveWeakForLinkerGUID(
232 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
233 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
234 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
236 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
238 for (auto &S : GVSummaryList) {
239 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
240 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
242 // We need to emit only one of these. The prevailing module will keep it,
243 // but turned into a weak, while the others will drop it when possible.
244 // This is both a compile-time optimization and a correctness
245 // transformation. This is necessary for correctness when we have exported
246 // a reference - we need to convert the linkonce to weak to
247 // ensure a copy is kept to satisfy the exported reference.
248 // FIXME: We may want to split the compile time and correctness
249 // aspects into separate routines.
250 if (isPrevailing(GUID, S.get())) {
251 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
252 S->setLinkage(GlobalValue::getWeakLinkage(
253 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
255 // Alias and aliasee can't be turned into available_externally.
256 else if (!isa<AliasSummary>(S.get()) &&
257 !GlobalInvolvedWithAlias.count(S.get()))
258 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
259 if (S->linkage() != OriginalLinkage)
260 recordNewLinkage(S->modulePath(), GUID, S->linkage());
264 // Resolve Weak and LinkOnce values in the \p Index.
266 // We'd like to drop these functions if they are no longer referenced in the
267 // current module. However there is a chance that another module is still
268 // referencing them because of the import. We make sure we always emit at least
270 void llvm::thinLTOResolveWeakForLinkerInIndex(
271 ModuleSummaryIndex &Index,
272 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
274 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
276 // We won't optimize the globals that are referenced by an alias for now
277 // Ideally we should turn the alias into a global and duplicate the definition
279 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
280 for (auto &I : Index)
281 for (auto &S : I.second.SummaryList)
282 if (auto AS = dyn_cast<AliasSummary>(S.get()))
283 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
285 for (auto &I : Index)
286 thinLTOResolveWeakForLinkerGUID(I.second.SummaryList, I.first,
287 GlobalInvolvedWithAlias, isPrevailing,
291 static void thinLTOInternalizeAndPromoteGUID(
292 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
293 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
294 for (auto &S : GVSummaryList) {
295 if (isExported(S->modulePath(), GUID)) {
296 if (GlobalValue::isLocalLinkage(S->linkage()))
297 S->setLinkage(GlobalValue::ExternalLinkage);
298 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
299 S->setLinkage(GlobalValue::InternalLinkage);
303 // Update the linkages in the given \p Index to mark exported values
304 // as external and non-exported values as internal.
305 void llvm::thinLTOInternalizeAndPromoteInIndex(
306 ModuleSummaryIndex &Index,
307 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
308 for (auto &I : Index)
309 thinLTOInternalizeAndPromoteGUID(I.second.SummaryList, I.first, isExported);
312 // Requires a destructor for std::vector<InputModule>.
313 InputFile::~InputFile() = default;
315 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
316 std::unique_ptr<InputFile> File(new InputFile);
318 ErrorOr<MemoryBufferRef> BCOrErr =
319 IRObjectFile::findBitcodeInMemBuffer(Object);
321 return errorCodeToError(BCOrErr.getError());
323 Expected<std::vector<BitcodeModule>> BMsOrErr =
324 getBitcodeModuleList(*BCOrErr);
326 return BMsOrErr.takeError();
328 if (BMsOrErr->empty())
329 return make_error<StringError>("Bitcode file does not contain any modules",
330 inconvertibleErrorCode());
332 File->Mods = *BMsOrErr;
335 std::vector<Module *> Mods;
336 std::vector<std::unique_ptr<Module>> OwnedMods;
337 for (auto BM : *BMsOrErr) {
338 Expected<std::unique_ptr<Module>> MOrErr =
339 BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
340 /*IsImporting*/ false);
342 return MOrErr.takeError();
344 if ((*MOrErr)->getDataLayoutStr().empty())
345 return make_error<StringError>("input module has no datalayout",
346 inconvertibleErrorCode());
348 Mods.push_back(MOrErr->get());
349 OwnedMods.push_back(std::move(*MOrErr));
352 SmallVector<char, 0> Symtab;
353 if (Error E = irsymtab::build(Mods, Symtab, File->Strtab))
356 irsymtab::Reader R({Symtab.data(), Symtab.size()},
357 {File->Strtab.data(), File->Strtab.size()});
358 File->TargetTriple = R.getTargetTriple();
359 File->SourceFileName = R.getSourceFileName();
360 File->COFFLinkerOpts = R.getCOFFLinkerOpts();
361 File->ComdatTable = R.getComdatTable();
363 for (unsigned I = 0; I != Mods.size(); ++I) {
364 size_t Begin = File->Symbols.size();
365 for (const irsymtab::Reader::SymbolRef &Sym : R.module_symbols(I))
366 // Skip symbols that are irrelevant to LTO. Note that this condition needs
367 // to match the one in Skip() in LTO::addRegularLTO().
368 if (Sym.isGlobal() && !Sym.isFormatSpecific())
369 File->Symbols.push_back(Sym);
370 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
373 return std::move(File);
376 StringRef InputFile::getName() const {
377 return Mods[0].getModuleIdentifier();
380 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
382 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
385 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
388 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
391 LTO::LTO(Config Conf, ThinBackend Backend,
392 unsigned ParallelCodeGenParallelismLevel)
393 : Conf(std::move(Conf)),
394 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
395 ThinLTO(std::move(Backend)) {}
397 // Requires a destructor for MapVector<BitcodeModule>.
398 LTO::~LTO() = default;
400 // Add the given symbol to the GlobalResolutions map, and resolve its partition.
401 void LTO::addSymbolToGlobalRes(const InputFile::Symbol &Sym,
402 SymbolResolution Res, unsigned Partition) {
403 auto &GlobalRes = GlobalResolutions[Sym.getName()];
404 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
406 GlobalRes.IRName = Sym.getIRName();
408 // Set the partition to external if we know it is used elsewhere, e.g.
409 // it is visible to a regular object, is referenced from llvm.compiler_used,
410 // or was already recorded as being referenced from a different partition.
411 if (Res.VisibleToRegularObj || Sym.isUsed() ||
412 (GlobalRes.Partition != GlobalResolution::Unknown &&
413 GlobalRes.Partition != Partition)) {
414 GlobalRes.Partition = GlobalResolution::External;
416 // First recorded reference, save the current partition.
417 GlobalRes.Partition = Partition;
419 // Flag as visible outside of ThinLTO if visible from a regular object or
420 // if this is a reference in the regular LTO partition.
421 GlobalRes.VisibleOutsideThinLTO |=
422 (Res.VisibleToRegularObj || Sym.isUsed() ||
423 Partition == GlobalResolution::RegularLTO);
426 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
427 ArrayRef<SymbolResolution> Res) {
428 StringRef Path = Input->getName();
430 auto ResI = Res.begin();
431 for (const InputFile::Symbol &Sym : Input->symbols()) {
432 assert(ResI != Res.end());
433 SymbolResolution Res = *ResI++;
435 OS << "-r=" << Path << ',' << Sym.getName() << ',';
438 if (Res.FinalDefinitionInLinkageUnit)
440 if (Res.VisibleToRegularObj)
445 assert(ResI == Res.end());
448 Error LTO::add(std::unique_ptr<InputFile> Input,
449 ArrayRef<SymbolResolution> Res) {
450 assert(!CalledGetMaxTasks);
452 if (Conf.ResolutionFile)
453 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
455 const SymbolResolution *ResI = Res.begin();
456 for (unsigned I = 0; I != Input->Mods.size(); ++I)
457 if (Error Err = addModule(*Input, I, ResI, Res.end()))
460 assert(ResI == Res.end());
461 return Error::success();
464 Error LTO::addModule(InputFile &Input, unsigned ModI,
465 const SymbolResolution *&ResI,
466 const SymbolResolution *ResE) {
467 Expected<bool> HasThinLTOSummary = Input.Mods[ModI].hasSummary();
468 if (!HasThinLTOSummary)
469 return HasThinLTOSummary.takeError();
471 auto ModSyms = Input.module_symbols(ModI);
472 if (*HasThinLTOSummary)
473 return addThinLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
475 return addRegularLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
478 // Add a regular LTO object to the link.
479 Error LTO::addRegularLTO(BitcodeModule BM,
480 ArrayRef<InputFile::Symbol> Syms,
481 const SymbolResolution *&ResI,
482 const SymbolResolution *ResE) {
483 if (!RegularLTO.CombinedModule) {
484 RegularLTO.CombinedModule =
485 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
486 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
488 Expected<std::unique_ptr<Module>> MOrErr =
489 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
490 /*IsImporting*/ false);
492 return MOrErr.takeError();
494 Module &M = **MOrErr;
495 if (Error Err = M.materializeMetadata())
499 ModuleSymbolTable SymTab;
500 SymTab.addModule(&M);
502 std::vector<GlobalValue *> Keep;
504 for (GlobalVariable &GV : M.globals())
505 if (GV.hasAppendingLinkage())
508 DenseSet<GlobalObject *> AliasedGlobals;
509 for (auto &GA : M.aliases())
510 if (GlobalObject *GO = GA.getBaseObject())
511 AliasedGlobals.insert(GO);
513 // In this function we need IR GlobalValues matching the symbols in Syms
514 // (which is not backed by a module), so we need to enumerate them in the same
515 // order. The symbol enumeration order of a ModuleSymbolTable intentionally
516 // matches the order of an irsymtab, but when we read the irsymtab in
517 // InputFile::create we omit some symbols that are irrelevant to LTO. The
518 // Skip() function skips the same symbols from the module as InputFile does
519 // from the symbol table.
520 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
522 while (MsymI != MsymE) {
523 auto Flags = SymTab.getSymbolFlags(*MsymI);
524 if ((Flags & object::BasicSymbolRef::SF_Global) &&
525 !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
532 for (const InputFile::Symbol &Sym : Syms) {
533 assert(ResI != ResE);
534 SymbolResolution Res = *ResI++;
535 addSymbolToGlobalRes(Sym, Res, 0);
537 assert(MsymI != MsymE);
538 ModuleSymbolTable::Symbol Msym = *MsymI++;
541 if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
542 if (Res.Prevailing) {
543 if (Sym.isUndefined())
546 GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
547 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
548 GV->setLinkage(GlobalValue::getWeakLinkage(
549 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
550 } else if (isa<GlobalObject>(GV) &&
551 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
552 GV->hasAvailableExternallyLinkage()) &&
553 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
554 // Either of the above three types of linkage indicates that the
555 // chosen prevailing symbol will have the same semantics as this copy of
556 // the symbol, so we can link it with available_externally linkage. We
557 // only need to do this if the symbol is undefined.
558 GlobalValue *CombinedGV =
559 RegularLTO.CombinedModule->getNamedValue(GV->getName());
560 if (!CombinedGV || CombinedGV->isDeclaration()) {
562 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
563 cast<GlobalObject>(GV)->setComdat(nullptr);
567 // Common resolution: collect the maximum size/alignment over all commons.
568 // We also record if we see an instance of a common as prevailing, so that
569 // if none is prevailing we can ignore it later.
570 if (Sym.isCommon()) {
571 // FIXME: We should figure out what to do about commons defined by asm.
572 // For now they aren't reported correctly by ModuleSymbolTable.
573 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
574 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
575 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
576 CommonRes.Prevailing |= Res.Prevailing;
579 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
581 assert(MsymI == MsymE);
583 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
584 [](GlobalValue &, IRMover::ValueAdder) {},
585 /* IsPerformingImport */ false);
588 // Add a ThinLTO object to the link.
589 Error LTO::addThinLTO(BitcodeModule BM,
590 ArrayRef<InputFile::Symbol> Syms,
591 const SymbolResolution *&ResI,
592 const SymbolResolution *ResE) {
594 BM.readSummary(ThinLTO.CombinedIndex, ThinLTO.ModuleMap.size()))
597 for (const InputFile::Symbol &Sym : Syms) {
598 assert(ResI != ResE);
599 SymbolResolution Res = *ResI++;
600 addSymbolToGlobalRes(Sym, Res, ThinLTO.ModuleMap.size() + 1);
602 if (Res.Prevailing) {
603 if (!Sym.getIRName().empty()) {
604 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
605 Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
606 ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
611 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
612 return make_error<StringError>(
613 "Expected at most one ThinLTO module per bitcode file",
614 inconvertibleErrorCode());
616 return Error::success();
619 unsigned LTO::getMaxTasks() const {
620 CalledGetMaxTasks = true;
621 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
624 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
625 // Compute "dead" symbols, we don't want to import/export these!
626 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
627 for (auto &Res : GlobalResolutions) {
628 if (Res.second.VisibleOutsideThinLTO &&
629 // IRName will be defined if we have seen the prevailing copy of
630 // this value. If not, no need to preserve any ThinLTO copies.
631 !Res.second.IRName.empty())
632 GUIDPreservedSymbols.insert(GlobalValue::getGUID(
633 GlobalValue::dropLLVMManglingEscape(Res.second.IRName)));
636 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
638 // Save the status of having a regularLTO combined module, as
639 // this is needed for generating the ThinLTO Task ID, and
640 // the CombinedModule will be moved at the end of runRegularLTO.
641 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
642 // Invoke regular LTO if there was a regular LTO module to start with.
644 if (auto E = runRegularLTO(AddStream))
646 return runThinLTO(AddStream, Cache, HasRegularLTO);
649 Error LTO::runRegularLTO(AddStreamFn AddStream) {
650 // Make sure commons have the right size/alignment: we kept the largest from
651 // all the prevailing when adding the inputs, and we apply it here.
652 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
653 for (auto &I : RegularLTO.Commons) {
654 if (!I.second.Prevailing)
655 // Don't do anything if no instance of this common was prevailing.
657 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
658 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
659 // Don't create a new global if the type is already correct, just make
660 // sure the alignment is correct.
661 OldGV->setAlignment(I.second.Align);
665 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
666 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
667 GlobalValue::CommonLinkage,
668 ConstantAggregateZero::get(Ty), "");
669 GV->setAlignment(I.second.Align);
671 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
673 OldGV->eraseFromParent();
675 GV->setName(I.first);
679 if (Conf.PreOptModuleHook &&
680 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
681 return Error::success();
683 if (!Conf.CodeGenOnly) {
684 for (const auto &R : GlobalResolutions) {
685 if (R.second.IRName.empty())
687 if (R.second.Partition != 0 &&
688 R.second.Partition != GlobalResolution::External)
692 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
693 // Ignore symbols defined in other partitions.
694 if (!GV || GV->hasLocalLinkage())
696 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
697 : GlobalValue::UnnamedAddr::None);
698 if (R.second.Partition == 0)
699 GV->setLinkage(GlobalValue::InternalLinkage);
702 if (Conf.PostInternalizeModuleHook &&
703 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
704 return Error::success();
706 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
707 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
710 /// This class defines the interface to the ThinLTO backend.
711 class lto::ThinBackendProc {
714 ModuleSummaryIndex &CombinedIndex;
715 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
718 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
719 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
720 : Conf(Conf), CombinedIndex(CombinedIndex),
721 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
723 virtual ~ThinBackendProc() {}
725 unsigned Task, BitcodeModule BM,
726 const FunctionImporter::ImportMapTy &ImportList,
727 const FunctionImporter::ExportSetTy &ExportList,
728 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
729 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
730 virtual Error wait() = 0;
734 class InProcessThinBackend : public ThinBackendProc {
735 ThreadPool BackendThreadPool;
736 AddStreamFn AddStream;
737 NativeObjectCache Cache;
738 TypeIdSummariesByGuidTy TypeIdSummariesByGuid;
744 InProcessThinBackend(
745 Config &Conf, ModuleSummaryIndex &CombinedIndex,
746 unsigned ThinLTOParallelismLevel,
747 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
748 AddStreamFn AddStream, NativeObjectCache Cache)
749 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
750 BackendThreadPool(ThinLTOParallelismLevel),
751 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
752 // Create a mapping from type identifier GUIDs to type identifier summaries.
753 // This allows backends to use the type identifier GUIDs stored in the
754 // function summaries to determine which type identifier summaries affect
755 // each function without needing to compute GUIDs in each backend.
756 for (auto &TId : CombinedIndex.typeIds())
757 TypeIdSummariesByGuid[GlobalValue::getGUID(TId.first)].push_back(&TId);
760 Error runThinLTOBackendThread(
761 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
762 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
763 const FunctionImporter::ImportMapTy &ImportList,
764 const FunctionImporter::ExportSetTy &ExportList,
765 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
766 const GVSummaryMapTy &DefinedGlobals,
767 MapVector<StringRef, BitcodeModule> &ModuleMap,
768 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
769 auto RunThinBackend = [&](AddStreamFn AddStream) {
770 LTOLLVMContext BackendContext(Conf);
771 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
773 return MOrErr.takeError();
775 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
776 ImportList, DefinedGlobals, ModuleMap);
779 auto ModuleID = BM.getModuleIdentifier();
781 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
782 all_of(CombinedIndex.getModuleHash(ModuleID),
783 [](uint32_t V) { return V == 0; }))
784 // Cache disabled or no entry for this module in the combined index or
786 return RunThinBackend(AddStream);
789 // The module may be cached, this helps handling it.
790 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
791 ResolvedODR, DefinedGlobals, TypeIdSummariesByGuid);
792 if (AddStreamFn CacheAddStream = Cache(Task, Key))
793 return RunThinBackend(CacheAddStream);
795 return Error::success();
799 unsigned Task, BitcodeModule BM,
800 const FunctionImporter::ImportMapTy &ImportList,
801 const FunctionImporter::ExportSetTy &ExportList,
802 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
803 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
804 StringRef ModulePath = BM.getModuleIdentifier();
805 assert(ModuleToDefinedGVSummaries.count(ModulePath));
806 const GVSummaryMapTy &DefinedGlobals =
807 ModuleToDefinedGVSummaries.find(ModulePath)->second;
808 BackendThreadPool.async(
809 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
810 const FunctionImporter::ImportMapTy &ImportList,
811 const FunctionImporter::ExportSetTy &ExportList,
812 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
814 const GVSummaryMapTy &DefinedGlobals,
815 MapVector<StringRef, BitcodeModule> &ModuleMap,
816 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
817 Error E = runThinLTOBackendThread(
818 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
819 ResolvedODR, DefinedGlobals, ModuleMap, TypeIdSummariesByGuid);
821 std::unique_lock<std::mutex> L(ErrMu);
823 Err = joinErrors(std::move(*Err), std::move(E));
828 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
829 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap),
830 std::ref(TypeIdSummariesByGuid));
831 return Error::success();
834 Error wait() override {
835 BackendThreadPool.wait();
837 return std::move(*Err);
839 return Error::success();
842 } // end anonymous namespace
844 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
845 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
846 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
847 AddStreamFn AddStream, NativeObjectCache Cache) {
848 return llvm::make_unique<InProcessThinBackend>(
849 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
854 // Given the original \p Path to an output file, replace any path
855 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
856 // resulting directory if it does not yet exist.
857 std::string lto::getThinLTOOutputFile(const std::string &Path,
858 const std::string &OldPrefix,
859 const std::string &NewPrefix) {
860 if (OldPrefix.empty() && NewPrefix.empty())
862 SmallString<128> NewPath(Path);
863 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
864 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
865 if (!ParentPath.empty()) {
866 // Make sure the new directory exists, creating it if necessary.
867 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
868 llvm::errs() << "warning: could not create directory '" << ParentPath
869 << "': " << EC.message() << '\n';
871 return NewPath.str();
875 class WriteIndexesThinBackend : public ThinBackendProc {
876 std::string OldPrefix, NewPrefix;
877 bool ShouldEmitImportsFiles;
879 std::string LinkedObjectsFileName;
880 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
883 WriteIndexesThinBackend(
884 Config &Conf, ModuleSummaryIndex &CombinedIndex,
885 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
886 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
887 std::string LinkedObjectsFileName)
888 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
889 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
890 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
891 LinkedObjectsFileName(LinkedObjectsFileName) {}
894 unsigned Task, BitcodeModule BM,
895 const FunctionImporter::ImportMapTy &ImportList,
896 const FunctionImporter::ExportSetTy &ExportList,
897 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
898 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
899 StringRef ModulePath = BM.getModuleIdentifier();
900 std::string NewModulePath =
901 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
904 if (!LinkedObjectsFileName.empty()) {
905 if (!LinkedObjectsFile) {
906 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
907 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
909 return errorCodeToError(EC);
911 *LinkedObjectsFile << NewModulePath << '\n';
914 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
915 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
916 ImportList, ModuleToSummariesForIndex);
918 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
919 sys::fs::OpenFlags::F_None);
921 return errorCodeToError(EC);
922 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
924 if (ShouldEmitImportsFiles)
925 return errorCodeToError(
926 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
927 return Error::success();
930 Error wait() override { return Error::success(); }
932 } // end anonymous namespace
934 ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
935 std::string NewPrefix,
936 bool ShouldEmitImportsFiles,
937 std::string LinkedObjectsFile) {
938 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
939 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
940 AddStreamFn AddStream, NativeObjectCache Cache) {
941 return llvm::make_unique<WriteIndexesThinBackend>(
942 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
943 ShouldEmitImportsFiles, LinkedObjectsFile);
947 static bool IsLiveByGUID(const ModuleSummaryIndex &Index,
948 GlobalValue::GUID GUID) {
949 auto VI = Index.getValueInfo(GUID);
952 for (auto &I : VI.getSummaryList())
953 if (Index.isGlobalValueLive(I.get()))
958 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
959 bool HasRegularLTO) {
960 if (ThinLTO.ModuleMap.empty())
961 return Error::success();
963 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
964 return Error::success();
966 // Collect for each module the list of function it defines (GUID ->
968 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
969 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
970 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
971 ModuleToDefinedGVSummaries);
972 // Create entries for any modules that didn't have any GV summaries
973 // (either they didn't have any GVs to start with, or we suppressed
974 // generation of the summaries because they e.g. had inline assembly
975 // uses that couldn't be promoted/renamed on export). This is so
976 // InProcessThinBackend::start can still launch a backend thread, which
977 // is passed the map of summaries for the module, without any special
978 // handling for this case.
979 for (auto &Mod : ThinLTO.ModuleMap)
980 if (!ModuleToDefinedGVSummaries.count(Mod.first))
981 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
983 StringMap<FunctionImporter::ImportMapTy> ImportLists(
984 ThinLTO.ModuleMap.size());
985 StringMap<FunctionImporter::ExportSetTy> ExportLists(
986 ThinLTO.ModuleMap.size());
987 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
989 if (Conf.OptLevel > 0) {
990 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
991 ImportLists, ExportLists);
993 std::set<GlobalValue::GUID> ExportedGUIDs;
994 for (auto &Res : GlobalResolutions) {
995 // First check if the symbol was flagged as having external references.
996 if (Res.second.Partition != GlobalResolution::External)
998 // IRName will be defined if we have seen the prevailing copy of
999 // this value. If not, no need to mark as exported from a ThinLTO
1000 // partition (and we can't get the GUID).
1001 if (Res.second.IRName.empty())
1003 auto GUID = GlobalValue::getGUID(
1004 GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1005 // Mark exported unless index-based analysis determined it to be dead.
1006 if (IsLiveByGUID(ThinLTO.CombinedIndex, GUID))
1007 ExportedGUIDs.insert(GUID);
1010 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
1011 const auto &ExportList = ExportLists.find(ModuleIdentifier);
1012 return (ExportList != ExportLists.end() &&
1013 ExportList->second.count(GUID)) ||
1014 ExportedGUIDs.count(GUID);
1016 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
1019 auto isPrevailing = [&](GlobalValue::GUID GUID,
1020 const GlobalValueSummary *S) {
1021 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1023 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1024 GlobalValue::GUID GUID,
1025 GlobalValue::LinkageTypes NewLinkage) {
1026 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1028 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
1031 std::unique_ptr<ThinBackendProc> BackendProc =
1032 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1035 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
1036 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
1037 // are reserved for parallel code generation partitions.
1039 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
1040 for (auto &Mod : ThinLTO.ModuleMap) {
1041 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1042 ExportLists[Mod.first],
1043 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1048 return BackendProc->wait();
1051 Expected<std::unique_ptr<tool_output_file>>
1052 lto::setupOptimizationRemarks(LLVMContext &Context,
1053 StringRef LTORemarksFilename,
1054 bool LTOPassRemarksWithHotness, int Count) {
1055 if (LTORemarksFilename.empty())
1058 std::string Filename = LTORemarksFilename;
1060 Filename += ".thin." + llvm::utostr(Count) + ".yaml";
1063 auto DiagnosticFile =
1064 llvm::make_unique<tool_output_file>(Filename, EC, sys::fs::F_None);
1066 return errorCodeToError(EC);
1067 Context.setDiagnosticsOutputFile(
1068 llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1069 if (LTOPassRemarksWithHotness)
1070 Context.setDiagnosticHotnessRequested(true);
1071 DiagnosticFile->keep();
1072 return std::move(DiagnosticFile);