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/CodeGen/TargetLoweringObjectFileImpl.h"
21 #include "llvm/IR/AutoUpgrade.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/LegacyPassManager.h"
24 #include "llvm/IR/Mangler.h"
25 #include "llvm/IR/Metadata.h"
26 #include "llvm/LTO/LTOBackend.h"
27 #include "llvm/Linker/IRMover.h"
28 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/SHA1.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/ThreadPool.h"
37 #include "llvm/Support/Threading.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 // Returns a unique hash for the Module considering the current list of
54 // export/import and other global analysis results.
55 // The hash is produced in \p Key.
56 static void computeCacheKey(
57 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
58 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
59 const FunctionImporter::ExportSetTy &ExportList,
60 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
61 const GVSummaryMapTy &DefinedGlobals) {
62 // Compute the unique hash for this entry.
63 // This is based on the current compiler version, the module itself, the
64 // export list, the hash for every single module in the import list, the
65 // list of ResolvedODR for the module, and the list of preserved symbols.
68 // Start with the compiler revision
69 Hasher.update(LLVM_VERSION_STRING);
70 #ifdef HAVE_LLVM_REVISION
71 Hasher.update(LLVM_REVISION);
74 // Include the parts of the LTO configuration that affect code generation.
75 auto AddString = [&](StringRef Str) {
77 Hasher.update(ArrayRef<uint8_t>{0});
79 auto AddUnsigned = [&](unsigned I) {
85 Hasher.update(ArrayRef<uint8_t>{Data, 4});
88 // FIXME: Hash more of Options. For now all clients initialize Options from
89 // command-line flags (which is unsupported in production), but may set
90 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
91 // DataSections and DebuggerTuning via command line flags.
92 AddUnsigned(Conf.Options.RelaxELFRelocations);
93 AddUnsigned(Conf.Options.FunctionSections);
94 AddUnsigned(Conf.Options.DataSections);
95 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
96 for (auto &A : Conf.MAttrs)
98 AddUnsigned(Conf.RelocModel);
99 AddUnsigned(Conf.CodeModel);
100 AddUnsigned(Conf.CGOptLevel);
101 AddUnsigned(Conf.OptLevel);
102 AddString(Conf.OptPipeline);
103 AddString(Conf.AAPipeline);
104 AddString(Conf.OverrideTriple);
105 AddString(Conf.DefaultTriple);
107 // Include the hash for the current module
108 auto ModHash = Index.getModuleHash(ModuleID);
109 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
110 for (auto F : ExportList)
111 // The export list can impact the internalization, be conservative here
112 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
114 // Include the hash for every module we import functions from
115 for (auto &Entry : ImportList) {
116 auto ModHash = Index.getModuleHash(Entry.first());
117 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
120 // Include the hash for the resolved ODR.
121 for (auto &Entry : ResolvedODR) {
122 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
123 sizeof(GlobalValue::GUID)));
124 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
125 sizeof(GlobalValue::LinkageTypes)));
128 // Include the hash for the linkage type to reflect internalization and weak
130 for (auto &GS : DefinedGlobals) {
131 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
133 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
136 if (!Conf.SampleProfile.empty()) {
137 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
139 Hasher.update(FileOrErr.get()->getBuffer());
142 Key = toHex(Hasher.result());
145 static void thinLTOResolveWeakForLinkerGUID(
146 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
147 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
148 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
150 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
152 for (auto &S : GVSummaryList) {
153 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
154 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
156 // We need to emit only one of these. The prevailing module will keep it,
157 // but turned into a weak, while the others will drop it when possible.
158 // This is both a compile-time optimization and a correctness
159 // transformation. This is necessary for correctness when we have exported
160 // a reference - we need to convert the linkonce to weak to
161 // ensure a copy is kept to satisfy the exported reference.
162 // FIXME: We may want to split the compile time and correctness
163 // aspects into separate routines.
164 if (isPrevailing(GUID, S.get())) {
165 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
166 S->setLinkage(GlobalValue::getWeakLinkage(
167 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
169 // Alias and aliasee can't be turned into available_externally.
170 else if (!isa<AliasSummary>(S.get()) &&
171 !GlobalInvolvedWithAlias.count(S.get()))
172 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
173 if (S->linkage() != OriginalLinkage)
174 recordNewLinkage(S->modulePath(), GUID, S->linkage());
178 // Resolve Weak and LinkOnce values in the \p Index.
180 // We'd like to drop these functions if they are no longer referenced in the
181 // current module. However there is a chance that another module is still
182 // referencing them because of the import. We make sure we always emit at least
184 void llvm::thinLTOResolveWeakForLinkerInIndex(
185 ModuleSummaryIndex &Index,
186 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
188 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
190 // We won't optimize the globals that are referenced by an alias for now
191 // Ideally we should turn the alias into a global and duplicate the definition
193 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
194 for (auto &I : Index)
195 for (auto &S : I.second)
196 if (auto AS = dyn_cast<AliasSummary>(S.get()))
197 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
199 for (auto &I : Index)
200 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
201 isPrevailing, recordNewLinkage);
204 static void thinLTOInternalizeAndPromoteGUID(
205 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
206 function_ref<SummaryResolution(StringRef, GlobalValue::GUID)> isExported) {
207 for (auto &S : GVSummaryList) {
208 auto ExportResolution = isExported(S->modulePath(), GUID);
209 if (ExportResolution != Internal) {
210 if (GlobalValue::isLocalLinkage(S->linkage()))
211 S->setLinkage(GlobalValue::ExternalLinkage);
212 if (ExportResolution == Hidden)
214 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
215 S->setLinkage(GlobalValue::InternalLinkage);
219 // Update the linkages in the given \p Index to mark exported values
220 // as external and non-exported values as internal.
221 void llvm::thinLTOInternalizeAndPromoteInIndex(
222 ModuleSummaryIndex &Index,
223 function_ref<SummaryResolution(StringRef, GlobalValue::GUID)> isExported) {
224 for (auto &I : Index)
225 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
228 struct InputFile::InputModule {
230 std::unique_ptr<Module> Mod;
232 // The range of ModuleSymbolTable entries for this input module.
233 size_t SymBegin, SymEnd;
236 // Requires a destructor for std::vector<InputModule>.
237 InputFile::~InputFile() = default;
239 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
240 std::unique_ptr<InputFile> File(new InputFile);
242 ErrorOr<MemoryBufferRef> BCOrErr =
243 IRObjectFile::findBitcodeInMemBuffer(Object);
245 return errorCodeToError(BCOrErr.getError());
247 Expected<std::vector<BitcodeModule>> BMsOrErr =
248 getBitcodeModuleList(*BCOrErr);
250 return BMsOrErr.takeError();
252 if (BMsOrErr->empty())
253 return make_error<StringError>("Bitcode file does not contain any modules",
254 inconvertibleErrorCode());
256 // Create an InputModule for each module in the InputFile, and add it to the
257 // ModuleSymbolTable.
258 for (auto BM : *BMsOrErr) {
259 Expected<std::unique_ptr<Module>> MOrErr =
260 BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true,
261 /*IsImporting*/ false);
263 return MOrErr.takeError();
265 size_t SymBegin = File->SymTab.symbols().size();
266 File->SymTab.addModule(MOrErr->get());
267 size_t SymEnd = File->SymTab.symbols().size();
269 for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
270 auto P = File->ComdatMap.insert(
271 std::make_pair(&C.second, File->Comdats.size()));
274 File->Comdats.push_back(C.first());
277 File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
280 return std::move(File);
283 Expected<int> InputFile::Symbol::getComdatIndex() const {
286 const GlobalObject *GO = getGV()->getBaseObject();
288 return make_error<StringError>("Unable to determine comdat of alias!",
289 inconvertibleErrorCode());
290 if (const Comdat *C = GO->getComdat()) {
291 auto I = File->ComdatMap.find(C);
292 assert(I != File->ComdatMap.end());
298 Expected<std::string> InputFile::getLinkerOpts() {
299 std::string LinkerOpts;
300 raw_string_ostream LOS(LinkerOpts);
301 // Extract linker options from module metadata.
302 for (InputModule &Mod : Mods) {
303 std::unique_ptr<Module> &M = Mod.Mod;
304 if (auto E = M->materializeMetadata())
306 if (Metadata *Val = M->getModuleFlag("Linker Options")) {
307 MDNode *LinkerOptions = cast<MDNode>(Val);
308 for (const MDOperand &MDOptions : LinkerOptions->operands())
309 for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
310 LOS << " " << cast<MDString>(MDOption)->getString();
314 // Synthesize export flags for symbols with dllexport storage.
315 const Triple TT(Mods[0].Mod->getTargetTriple());
317 for (const ModuleSymbolTable::Symbol &Sym : SymTab.symbols())
318 if (auto *GV = Sym.dyn_cast<GlobalValue*>())
319 emitLinkerFlagsForGlobalCOFF(LOS, GV, TT, M);
324 StringRef InputFile::getName() const {
325 return Mods[0].BM.getModuleIdentifier();
328 StringRef InputFile::getSourceFileName() const {
329 return Mods[0].Mod->getSourceFileName();
332 iterator_range<InputFile::symbol_iterator>
333 InputFile::module_symbols(InputModule &IM) {
334 return llvm::make_range(
335 symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
336 symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
339 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
341 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
344 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
347 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
350 LTO::LTO(Config Conf, ThinBackend Backend,
351 unsigned ParallelCodeGenParallelismLevel)
352 : Conf(std::move(Conf)),
353 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
354 ThinLTO(std::move(Backend)) {}
356 // Requires a destructor for MapVector<BitcodeModule>.
357 LTO::~LTO() = default;
359 // Add the given symbol to the GlobalResolutions map, and resolve its partition.
360 void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
361 const InputFile::Symbol &Sym,
362 SymbolResolution Res, unsigned Partition) {
363 GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
365 auto &GlobalRes = GlobalResolutions[Sym.getName()];
367 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
369 GlobalRes.IRName = GV->getName();
371 // Set the partition to external if we know it is used elsewhere, e.g.
372 // it is visible to a regular object, is referenced from llvm.compiler_used,
373 // or was already recorded as being referenced from a different partition.
374 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
375 (GlobalRes.Partition != GlobalResolution::Unknown &&
376 GlobalRes.Partition != Partition)) {
377 GlobalRes.Partition = GlobalResolution::External;
379 // First recorded reference, save the current partition.
380 GlobalRes.Partition = Partition;
382 // Flag as visible outside of ThinLTO if visible from a regular object or
383 // if this is a reference in the regular LTO partition.
384 GlobalRes.VisibleOutsideThinLTO |=
385 (Res.VisibleToRegularObj || (Partition == GlobalResolution::RegularLTO));
388 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
389 ArrayRef<SymbolResolution> Res) {
390 StringRef Path = Input->getName();
392 auto ResI = Res.begin();
393 for (const InputFile::Symbol &Sym : Input->symbols()) {
394 assert(ResI != Res.end());
395 SymbolResolution Res = *ResI++;
397 OS << "-r=" << Path << ',' << Sym.getName() << ',';
400 if (Res.FinalDefinitionInLinkageUnit)
402 if (Res.VisibleToRegularObj)
407 assert(ResI == Res.end());
410 Error LTO::add(std::unique_ptr<InputFile> Input,
411 ArrayRef<SymbolResolution> Res) {
412 assert(!CalledGetMaxTasks);
414 if (Conf.ResolutionFile)
415 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
417 const SymbolResolution *ResI = Res.begin();
418 for (InputFile::InputModule &IM : Input->Mods)
419 if (Error Err = addModule(*Input, IM, ResI, Res.end()))
422 assert(ResI == Res.end());
423 return Error::success();
426 Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
427 const SymbolResolution *&ResI,
428 const SymbolResolution *ResE) {
429 // FIXME: move to backend
432 if (M.getDataLayoutStr().empty())
433 return make_error<StringError>("input module has no datalayout",
434 inconvertibleErrorCode());
436 if (!Conf.OverrideTriple.empty())
437 M.setTargetTriple(Conf.OverrideTriple);
438 else if (M.getTargetTriple().empty())
439 M.setTargetTriple(Conf.DefaultTriple);
441 Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
442 if (!HasThinLTOSummary)
443 return HasThinLTOSummary.takeError();
445 if (*HasThinLTOSummary)
446 return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
448 return addRegularLTO(IM.BM, ResI, ResE);
451 // Add a regular LTO object to the link.
452 Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
453 const SymbolResolution *ResE) {
454 if (!RegularLTO.CombinedModule) {
455 RegularLTO.CombinedModule =
456 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
457 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
459 Expected<std::unique_ptr<Module>> MOrErr =
460 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
461 /*IsImporting*/ false);
463 return MOrErr.takeError();
465 Module &M = **MOrErr;
466 if (Error Err = M.materializeMetadata())
470 ModuleSymbolTable SymTab;
471 SymTab.addModule(&M);
473 SmallPtrSet<GlobalValue *, 8> Used;
474 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
476 std::vector<GlobalValue *> Keep;
478 for (GlobalVariable &GV : M.globals())
479 if (GV.hasAppendingLinkage())
482 DenseSet<GlobalObject *> AliasedGlobals;
483 for (auto &GA : M.aliases())
484 if (GlobalObject *GO = GA.getBaseObject())
485 AliasedGlobals.insert(GO);
487 for (const InputFile::Symbol &Sym :
488 make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
490 InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
492 assert(ResI != ResE);
493 SymbolResolution Res = *ResI++;
494 addSymbolToGlobalRes(Used, Sym, Res, 0);
497 GlobalValue *GV = Sym.getGV();
498 if (Res.Prevailing) {
499 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
502 switch (GV->getLinkage()) {
505 case GlobalValue::LinkOnceAnyLinkage:
506 GV->setLinkage(GlobalValue::WeakAnyLinkage);
508 case GlobalValue::LinkOnceODRLinkage:
509 GV->setLinkage(GlobalValue::WeakODRLinkage);
512 } else if (isa<GlobalObject>(GV) &&
513 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
514 GV->hasAvailableExternallyLinkage()) &&
515 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
516 // Either of the above three types of linkage indicates that the
517 // chosen prevailing symbol will have the same semantics as this copy of
518 // the symbol, so we can link it with available_externally linkage. We
519 // only need to do this if the symbol is undefined.
520 GlobalValue *CombinedGV =
521 RegularLTO.CombinedModule->getNamedValue(GV->getName());
522 if (!CombinedGV || CombinedGV->isDeclaration()) {
524 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
525 cast<GlobalObject>(GV)->setComdat(nullptr);
529 // Common resolution: collect the maximum size/alignment over all commons.
530 // We also record if we see an instance of a common as prevailing, so that
531 // if none is prevailing we can ignore it later.
532 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
533 // FIXME: We should figure out what to do about commons defined by asm.
534 // For now they aren't reported correctly by ModuleSymbolTable.
535 auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
536 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
537 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
538 CommonRes.Prevailing |= Res.Prevailing;
541 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
544 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
545 [](GlobalValue &, IRMover::ValueAdder) {},
546 /* LinkModuleInlineAsm */ true,
547 /* IsPerformingImport */ false);
550 // Add a ThinLTO object to the link.
551 // FIXME: This function should not need to take as many parameters once we have
552 // a bitcode symbol table.
553 Error LTO::addThinLTO(BitcodeModule BM, Module &M,
554 iterator_range<InputFile::symbol_iterator> Syms,
555 const SymbolResolution *&ResI,
556 const SymbolResolution *ResE) {
557 SmallPtrSet<GlobalValue *, 8> Used;
558 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
560 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
562 return SummaryOrErr.takeError();
563 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
564 ThinLTO.ModuleMap.size());
566 for (const InputFile::Symbol &Sym : Syms) {
567 assert(ResI != ResE);
568 SymbolResolution Res = *ResI++;
569 addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
571 if (Res.Prevailing && Sym.isGV())
572 ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
573 BM.getModuleIdentifier();
576 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
577 return make_error<StringError>(
578 "Expected at most one ThinLTO module per bitcode file",
579 inconvertibleErrorCode());
581 return Error::success();
584 unsigned LTO::getMaxTasks() const {
585 CalledGetMaxTasks = true;
586 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
589 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
590 // Save the status of having a regularLTO combined module, as
591 // this is needed for generating the ThinLTO Task ID, and
592 // the CombinedModule will be moved at the end of runRegularLTO.
593 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
594 // Invoke regular LTO if there was a regular LTO module to start with.
596 if (auto E = runRegularLTO(AddStream))
598 return runThinLTO(AddStream, Cache, HasRegularLTO);
601 Error LTO::runRegularLTO(AddStreamFn AddStream) {
602 // Make sure commons have the right size/alignment: we kept the largest from
603 // all the prevailing when adding the inputs, and we apply it here.
604 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
605 for (auto &I : RegularLTO.Commons) {
606 if (!I.second.Prevailing)
607 // Don't do anything if no instance of this common was prevailing.
609 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
610 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
611 // Don't create a new global if the type is already correct, just make
612 // sure the alignment is correct.
613 OldGV->setAlignment(I.second.Align);
617 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
618 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
619 GlobalValue::CommonLinkage,
620 ConstantAggregateZero::get(Ty), "");
621 GV->setAlignment(I.second.Align);
623 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
625 OldGV->eraseFromParent();
627 GV->setName(I.first);
631 if (Conf.PreOptModuleHook &&
632 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
633 return Error::success();
635 if (!Conf.CodeGenOnly) {
636 for (const auto &R : GlobalResolutions) {
637 if (R.second.IRName.empty())
639 if (R.second.Partition != 0 &&
640 R.second.Partition != GlobalResolution::External)
644 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
645 // Ignore symbols defined in other partitions.
646 if (!GV || GV->hasLocalLinkage())
648 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
649 : GlobalValue::UnnamedAddr::None);
650 if (R.second.Partition == 0)
651 GV->setLinkage(GlobalValue::InternalLinkage);
654 if (Conf.PostInternalizeModuleHook &&
655 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
656 return Error::success();
658 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
659 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
662 /// This class defines the interface to the ThinLTO backend.
663 class lto::ThinBackendProc {
666 ModuleSummaryIndex &CombinedIndex;
667 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
670 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
671 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
672 : Conf(Conf), CombinedIndex(CombinedIndex),
673 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
675 virtual ~ThinBackendProc() {}
677 unsigned Task, BitcodeModule BM,
678 const FunctionImporter::ImportMapTy &ImportList,
679 const FunctionImporter::ExportSetTy &ExportList,
680 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
681 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
682 virtual Error wait() = 0;
686 class InProcessThinBackend : public ThinBackendProc {
687 ThreadPool BackendThreadPool;
688 AddStreamFn AddStream;
689 NativeObjectCache Cache;
695 InProcessThinBackend(
696 Config &Conf, ModuleSummaryIndex &CombinedIndex,
697 unsigned ThinLTOParallelismLevel,
698 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
699 AddStreamFn AddStream, NativeObjectCache Cache)
700 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
701 BackendThreadPool(ThinLTOParallelismLevel),
702 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
704 Error runThinLTOBackendThread(
705 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
706 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
707 const FunctionImporter::ImportMapTy &ImportList,
708 const FunctionImporter::ExportSetTy &ExportList,
709 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
710 const GVSummaryMapTy &DefinedGlobals,
711 MapVector<StringRef, BitcodeModule> &ModuleMap) {
712 auto RunThinBackend = [&](AddStreamFn AddStream) {
713 LTOLLVMContext BackendContext(Conf);
714 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
716 return MOrErr.takeError();
718 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
719 ImportList, DefinedGlobals, ModuleMap);
722 auto ModuleID = BM.getModuleIdentifier();
724 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
725 all_of(CombinedIndex.getModuleHash(ModuleID),
726 [](uint32_t V) { return V == 0; }))
727 // Cache disabled or no entry for this module in the combined index or
729 return RunThinBackend(AddStream);
732 // The module may be cached, this helps handling it.
733 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
734 ResolvedODR, DefinedGlobals);
735 if (AddStreamFn CacheAddStream = Cache(Task, Key))
736 return RunThinBackend(CacheAddStream);
738 return Error::success();
742 unsigned Task, BitcodeModule BM,
743 const FunctionImporter::ImportMapTy &ImportList,
744 const FunctionImporter::ExportSetTy &ExportList,
745 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
746 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
747 StringRef ModulePath = BM.getModuleIdentifier();
748 assert(ModuleToDefinedGVSummaries.count(ModulePath));
749 const GVSummaryMapTy &DefinedGlobals =
750 ModuleToDefinedGVSummaries.find(ModulePath)->second;
751 BackendThreadPool.async(
752 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
753 const FunctionImporter::ImportMapTy &ImportList,
754 const FunctionImporter::ExportSetTy &ExportList,
755 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
757 const GVSummaryMapTy &DefinedGlobals,
758 MapVector<StringRef, BitcodeModule> &ModuleMap) {
759 Error E = runThinLTOBackendThread(
760 AddStream, Cache, Task, BM, CombinedIndex, ImportList,
761 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
763 std::unique_lock<std::mutex> L(ErrMu);
765 Err = joinErrors(std::move(*Err), std::move(E));
770 BM, std::ref(CombinedIndex), std::ref(ImportList),
771 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
772 std::ref(ModuleMap));
773 return Error::success();
776 Error wait() override {
777 BackendThreadPool.wait();
779 return std::move(*Err);
781 return Error::success();
784 } // end anonymous namespace
786 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
787 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
788 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
789 AddStreamFn AddStream, NativeObjectCache Cache) {
790 return llvm::make_unique<InProcessThinBackend>(
791 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
796 // Given the original \p Path to an output file, replace any path
797 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
798 // resulting directory if it does not yet exist.
799 std::string lto::getThinLTOOutputFile(const std::string &Path,
800 const std::string &OldPrefix,
801 const std::string &NewPrefix) {
802 if (OldPrefix.empty() && NewPrefix.empty())
804 SmallString<128> NewPath(Path);
805 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
806 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
807 if (!ParentPath.empty()) {
808 // Make sure the new directory exists, creating it if necessary.
809 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
810 llvm::errs() << "warning: could not create directory '" << ParentPath
811 << "': " << EC.message() << '\n';
813 return NewPath.str();
817 class WriteIndexesThinBackend : public ThinBackendProc {
818 std::string OldPrefix, NewPrefix;
819 bool ShouldEmitImportsFiles;
821 std::string LinkedObjectsFileName;
822 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
825 WriteIndexesThinBackend(
826 Config &Conf, ModuleSummaryIndex &CombinedIndex,
827 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
828 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
829 std::string LinkedObjectsFileName)
830 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
831 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
832 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
833 LinkedObjectsFileName(LinkedObjectsFileName) {}
836 unsigned Task, BitcodeModule BM,
837 const FunctionImporter::ImportMapTy &ImportList,
838 const FunctionImporter::ExportSetTy &ExportList,
839 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
840 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
841 StringRef ModulePath = BM.getModuleIdentifier();
842 std::string NewModulePath =
843 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
846 if (!LinkedObjectsFileName.empty()) {
847 if (!LinkedObjectsFile) {
848 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
849 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
851 return errorCodeToError(EC);
853 *LinkedObjectsFile << NewModulePath << '\n';
856 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
857 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
858 ImportList, ModuleToSummariesForIndex);
860 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
861 sys::fs::OpenFlags::F_None);
863 return errorCodeToError(EC);
864 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
866 if (ShouldEmitImportsFiles)
867 return errorCodeToError(
868 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
869 return Error::success();
872 Error wait() override { return Error::success(); }
874 } // end anonymous namespace
876 ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
877 std::string NewPrefix,
878 bool ShouldEmitImportsFiles,
879 std::string LinkedObjectsFile) {
880 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
881 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
882 AddStreamFn AddStream, NativeObjectCache Cache) {
883 return llvm::make_unique<WriteIndexesThinBackend>(
884 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
885 ShouldEmitImportsFiles, LinkedObjectsFile);
889 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
890 bool HasRegularLTO) {
891 if (ThinLTO.ModuleMap.empty())
892 return Error::success();
894 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
895 return Error::success();
897 // Collect for each module the list of function it defines (GUID ->
899 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
900 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
901 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
902 ModuleToDefinedGVSummaries);
903 // Create entries for any modules that didn't have any GV summaries
904 // (either they didn't have any GVs to start with, or we suppressed
905 // generation of the summaries because they e.g. had inline assembly
906 // uses that couldn't be promoted/renamed on export). This is so
907 // InProcessThinBackend::start can still launch a backend thread, which
908 // is passed the map of summaries for the module, without any special
909 // handling for this case.
910 for (auto &Mod : ThinLTO.ModuleMap)
911 if (!ModuleToDefinedGVSummaries.count(Mod.first))
912 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
914 StringMap<FunctionImporter::ImportMapTy> ImportLists(
915 ThinLTO.ModuleMap.size());
916 StringMap<FunctionImporter::ExportSetTy> ExportLists(
917 ThinLTO.ModuleMap.size());
918 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
920 if (Conf.OptLevel > 0) {
921 // Compute "dead" symbols, we don't want to import/export these!
922 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
923 for (auto &Res : GlobalResolutions) {
924 if (Res.second.VisibleOutsideThinLTO &&
925 // IRName will be defined if we have seen the prevailing copy of
926 // this value. If not, no need to preserve any ThinLTO copies.
927 !Res.second.IRName.empty())
928 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Res.second.IRName));
932 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
934 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
935 ImportLists, ExportLists, &DeadSymbols);
937 std::set<GlobalValue::GUID> ExportedGUIDs;
938 for (auto &Res : GlobalResolutions) {
939 // First check if the symbol was flagged as having external references.
940 if (Res.second.Partition != GlobalResolution::External)
942 // IRName will be defined if we have seen the prevailing copy of
943 // this value. If not, no need to mark as exported from a ThinLTO
944 // partition (and we can't get the GUID).
945 if (Res.second.IRName.empty())
947 auto GUID = GlobalValue::getGUID(Res.second.IRName);
948 // Mark exported unless index-based analysis determined it to be dead.
949 if (!DeadSymbols.count(GUID))
950 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
953 auto isPrevailing = [&](GlobalValue::GUID GUID,
954 const GlobalValueSummary *S) {
955 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
957 auto isExported = [&](StringRef ModuleIdentifier,
958 GlobalValue::GUID GUID) -> SummaryResolution {
959 const auto &ExportList = ExportLists.find(ModuleIdentifier);
960 if ((ExportList != ExportLists.end() && ExportList->second.count(GUID)) ||
961 ExportedGUIDs.count(GUID)) {
962 // We could do better by hiding when a symbol is in
963 // GUIDPreservedSymbols because it is only referenced from regular LTO
964 // or from native files and not outside the final binary, but that's
965 // something the native linker could do as gwell.
966 if (GUIDPreservedSymbols.count(GUID))
972 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
974 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
975 GlobalValue::GUID GUID,
976 GlobalValue::LinkageTypes NewLinkage) {
977 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
980 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
984 std::unique_ptr<ThinBackendProc> BackendProc =
985 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
988 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
989 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
990 // are reserved for parallel code generation partitions.
992 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
993 for (auto &Mod : ThinLTO.ModuleMap) {
994 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
995 ExportLists[Mod.first],
996 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1001 return BackendProc->wait();