1df6edc52STeresa Johnson //===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
2df6edc52STeresa Johnson //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6df6edc52STeresa Johnson //
7df6edc52STeresa Johnson //===----------------------------------------------------------------------===//
8df6edc52STeresa Johnson //
9df6edc52STeresa Johnson // This file implements functions and classes used to support LTO.
10df6edc52STeresa Johnson //
11df6edc52STeresa Johnson //===----------------------------------------------------------------------===//
12df6edc52STeresa Johnson
13df6edc52STeresa Johnson #include "llvm/LTO/LTO.h"
14f5b8a312Smodimo #include "llvm/ADT/ScopeExit.h"
15b4a8c0ebSYuanfang Chen #include "llvm/ADT/SmallSet.h"
16d4332eb3SFlorian Hahn #include "llvm/ADT/Statistic.h"
17b4a8c0ebSYuanfang Chen #include "llvm/ADT/StringExtras.h"
1831ae0165SGabor Horvath #include "llvm/Analysis/OptimizationRemarkEmitter.h"
19c1e47b47SVitaly Buka #include "llvm/Analysis/StackSafetyAnalysis.h"
209ba95f99STeresa Johnson #include "llvm/Analysis/TargetLibraryInfo.h"
219ba95f99STeresa Johnson #include "llvm/Analysis/TargetTransformInfo.h"
22ad17679aSTeresa Johnson #include "llvm/Bitcode/BitcodeReader.h"
23ad17679aSTeresa Johnson #include "llvm/Bitcode/BitcodeWriter.h"
249ba95f99STeresa Johnson #include "llvm/CodeGen/Analysis.h"
25432a3883SNico Weber #include "llvm/Config/llvm-config.h"
269ba95f99STeresa Johnson #include "llvm/IR/AutoUpgrade.h"
279ba95f99STeresa Johnson #include "llvm/IR/DiagnosticPrinter.h"
28d0b1f30bSTeresa Johnson #include "llvm/IR/Intrinsics.h"
297531a503SFrancis Visoiu Mistrih #include "llvm/IR/LLVMRemarkStreamer.h"
309ba95f99STeresa Johnson #include "llvm/IR/LegacyPassManager.h"
31dd4ebc1dSBob Haarman #include "llvm/IR/Mangler.h"
32dd4ebc1dSBob Haarman #include "llvm/IR/Metadata.h"
339ba95f99STeresa Johnson #include "llvm/LTO/LTOBackend.h"
345a7056faSEaswaran Raman #include "llvm/LTO/SummaryBasedOptimizations.h"
359ba95f99STeresa Johnson #include "llvm/Linker/IRMover.h"
3689b57061SReid Kleckner #include "llvm/MC/TargetRegistry.h"
37192d8520SPeter Collingbourne #include "llvm/Object/IRObjectFile.h"
384c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
39dd4ebc1dSBob Haarman #include "llvm/Support/Error.h"
40ba7a92c0SNico Weber #include "llvm/Support/FileSystem.h"
419ba95f99STeresa Johnson #include "llvm/Support/ManagedStatic.h"
42df6edc52STeresa Johnson #include "llvm/Support/MemoryBuffer.h"
439ba95f99STeresa Johnson #include "llvm/Support/Path.h"
44adc0e26bSMehdi Amini #include "llvm/Support/SHA1.h"
45df6edc52STeresa Johnson #include "llvm/Support/SourceMgr.h"
469ba95f99STeresa Johnson #include "llvm/Support/ThreadPool.h"
47ec544c55STeresa Johnson #include "llvm/Support/Threading.h"
48e7cb3744SRussell Gallop #include "llvm/Support/TimeProfiler.h"
49e188aae4Sserge-sans-paille #include "llvm/Support/ToolOutputFile.h"
50942fa56fSPeter Collingbourne #include "llvm/Support/VCSRevision.h"
51df6edc52STeresa Johnson #include "llvm/Support/raw_ostream.h"
529ba95f99STeresa Johnson #include "llvm/Target/TargetMachine.h"
539ba95f99STeresa Johnson #include "llvm/Target/TargetOptions.h"
549ba95f99STeresa Johnson #include "llvm/Transforms/IPO.h"
559ba95f99STeresa Johnson #include "llvm/Transforms/IPO/PassManagerBuilder.h"
56d2df54e6STeresa Johnson #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
575a7056faSEaswaran Raman #include "llvm/Transforms/Utils/FunctionImportUtils.h"
589ba95f99STeresa Johnson #include "llvm/Transforms/Utils/SplitModule.h"
59df6edc52STeresa Johnson
609ba95f99STeresa Johnson #include <set>
619ba95f99STeresa Johnson
629ba95f99STeresa Johnson using namespace llvm;
639ba95f99STeresa Johnson using namespace lto;
649ba95f99STeresa Johnson using namespace object;
65df6edc52STeresa Johnson
66adc0e26bSMehdi Amini #define DEBUG_TYPE "lto"
67adc0e26bSMehdi Amini
68b040fcc6SCharles Saternos static cl::opt<bool>
69b040fcc6SCharles Saternos DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden,
70b040fcc6SCharles Saternos cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
71b040fcc6SCharles Saternos
727ca74448SXin Tong /// Enable global value internalization in LTO.
737ca74448SXin Tong cl::opt<bool> EnableLTOInternalization(
747ca74448SXin Tong "enable-lto-internalization", cl::init(true), cl::Hidden,
757ca74448SXin Tong cl::desc("Enable global value internalization in LTO"));
767ca74448SXin Tong
775f312ad4STeresa Johnson // Computes a unique hash for the Module considering the current list of
78adc0e26bSMehdi Amini // export/import and other global analysis results.
79adc0e26bSMehdi Amini // The hash is produced in \p Key.
computeLTOCacheKey(SmallString<40> & Key,const Config & Conf,const ModuleSummaryIndex & Index,StringRef ModuleID,const FunctionImporter::ImportMapTy & ImportList,const FunctionImporter::ExportSetTy & ExportList,const std::map<GlobalValue::GUID,GlobalValue::LinkageTypes> & ResolvedODR,const GVSummaryMapTy & DefinedGlobals,const std::set<GlobalValue::GUID> & CfiFunctionDefs,const std::set<GlobalValue::GUID> & CfiFunctionDecls)805f312ad4STeresa Johnson void llvm::computeLTOCacheKey(
81f4257528SPeter Collingbourne SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
82f4257528SPeter Collingbourne StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
83adc0e26bSMehdi Amini const FunctionImporter::ExportSetTy &ExportList,
84adc0e26bSMehdi Amini const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
85780a4dd3SPeter Collingbourne const GVSummaryMapTy &DefinedGlobals,
863427d17cSEvgeniy Stepanov const std::set<GlobalValue::GUID> &CfiFunctionDefs,
873427d17cSEvgeniy Stepanov const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
88adc0e26bSMehdi Amini // Compute the unique hash for this entry.
89adc0e26bSMehdi Amini // This is based on the current compiler version, the module itself, the
90adc0e26bSMehdi Amini // export list, the hash for every single module in the import list, the
91adc0e26bSMehdi Amini // list of ResolvedODR for the module, and the list of preserved symbols.
92adc0e26bSMehdi Amini SHA1 Hasher;
93adc0e26bSMehdi Amini
94adc0e26bSMehdi Amini // Start with the compiler revision
95adc0e26bSMehdi Amini Hasher.update(LLVM_VERSION_STRING);
96942fa56fSPeter Collingbourne #ifdef LLVM_REVISION
97adc0e26bSMehdi Amini Hasher.update(LLVM_REVISION);
98adc0e26bSMehdi Amini #endif
99adc0e26bSMehdi Amini
100f4257528SPeter Collingbourne // Include the parts of the LTO configuration that affect code generation.
101f4257528SPeter Collingbourne auto AddString = [&](StringRef Str) {
102f4257528SPeter Collingbourne Hasher.update(Str);
103f4257528SPeter Collingbourne Hasher.update(ArrayRef<uint8_t>{0});
104f4257528SPeter Collingbourne };
105f4257528SPeter Collingbourne auto AddUnsigned = [&](unsigned I) {
106f4257528SPeter Collingbourne uint8_t Data[4];
107232eff55SBenjamin Kramer support::endian::write32le(Data, I);
108f4257528SPeter Collingbourne Hasher.update(ArrayRef<uint8_t>{Data, 4});
109f4257528SPeter Collingbourne };
11054a52b75SPeter Collingbourne auto AddUint64 = [&](uint64_t I) {
11154a52b75SPeter Collingbourne uint8_t Data[8];
112232eff55SBenjamin Kramer support::endian::write64le(Data, I);
11354a52b75SPeter Collingbourne Hasher.update(ArrayRef<uint8_t>{Data, 8});
11454a52b75SPeter Collingbourne };
115f4257528SPeter Collingbourne AddString(Conf.CPU);
116f4257528SPeter Collingbourne // FIXME: Hash more of Options. For now all clients initialize Options from
117f4257528SPeter Collingbourne // command-line flags (which is unsupported in production), but may set
118f4257528SPeter Collingbourne // RelaxELFRelocations. The clang driver can also pass FunctionSections,
119f4257528SPeter Collingbourne // DataSections and DebuggerTuning via command line flags.
120f4257528SPeter Collingbourne AddUnsigned(Conf.Options.RelaxELFRelocations);
121f4257528SPeter Collingbourne AddUnsigned(Conf.Options.FunctionSections);
122f4257528SPeter Collingbourne AddUnsigned(Conf.Options.DataSections);
123f4257528SPeter Collingbourne AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
124f4257528SPeter Collingbourne for (auto &A : Conf.MAttrs)
125f4257528SPeter Collingbourne AddString(A);
126b9f1b014SEvgeniy Stepanov if (Conf.RelocModel)
127b9f1b014SEvgeniy Stepanov AddUnsigned(*Conf.RelocModel);
128b9f1b014SEvgeniy Stepanov else
129b9f1b014SEvgeniy Stepanov AddUnsigned(-1);
13079e238afSRafael Espindola if (Conf.CodeModel)
13179e238afSRafael Espindola AddUnsigned(*Conf.CodeModel);
13279e238afSRafael Espindola else
13379e238afSRafael Espindola AddUnsigned(-1);
134f4257528SPeter Collingbourne AddUnsigned(Conf.CGOptLevel);
135f454b9eaSTobias Edler von Koch AddUnsigned(Conf.CGFileType);
136f4257528SPeter Collingbourne AddUnsigned(Conf.OptLevel);
1375f312ad4STeresa Johnson AddUnsigned(Conf.Freestanding);
138f4257528SPeter Collingbourne AddString(Conf.OptPipeline);
139f4257528SPeter Collingbourne AddString(Conf.AAPipeline);
140f4257528SPeter Collingbourne AddString(Conf.OverrideTriple);
141f4257528SPeter Collingbourne AddString(Conf.DefaultTriple);
142bd200b9fSYunlian Jiang AddString(Conf.DwoDir);
143f4257528SPeter Collingbourne
144adc0e26bSMehdi Amini // Include the hash for the current module
145adc0e26bSMehdi Amini auto ModHash = Index.getModuleHash(ModuleID);
146adc0e26bSMehdi Amini Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
147252892feSromanova-ekaterina
148252892feSromanova-ekaterina std::vector<uint64_t> ExportsGUID;
149252892feSromanova-ekaterina ExportsGUID.reserve(ExportList.size());
1503d708bf5Sevgeny for (const auto &VI : ExportList) {
1513d708bf5Sevgeny auto GUID = VI.getGUID();
152252892feSromanova-ekaterina ExportsGUID.push_back(GUID);
153252892feSromanova-ekaterina }
154252892feSromanova-ekaterina
155252892feSromanova-ekaterina // Sort the export list elements GUIDs.
156252892feSromanova-ekaterina llvm::sort(ExportsGUID);
157252892feSromanova-ekaterina for (uint64_t GUID : ExportsGUID) {
158adc0e26bSMehdi Amini // The export list can impact the internalization, be conservative here
1593d708bf5Sevgeny Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
1603d708bf5Sevgeny }
161adc0e26bSMehdi Amini
16254a52b75SPeter Collingbourne // Include the hash for every module we import functions from. The set of
16354a52b75SPeter Collingbourne // imported symbols for each module may affect code generation and is
16454a52b75SPeter Collingbourne // sensitive to link order, so include that as well.
165252892feSromanova-ekaterina using ImportMapIteratorTy = FunctionImporter::ImportMapTy::const_iterator;
166252892feSromanova-ekaterina std::vector<ImportMapIteratorTy> ImportModulesVector;
167252892feSromanova-ekaterina ImportModulesVector.reserve(ImportList.size());
168252892feSromanova-ekaterina
169252892feSromanova-ekaterina for (ImportMapIteratorTy It = ImportList.begin(); It != ImportList.end();
170252892feSromanova-ekaterina ++It) {
171252892feSromanova-ekaterina ImportModulesVector.push_back(It);
172252892feSromanova-ekaterina }
173252892feSromanova-ekaterina llvm::sort(ImportModulesVector,
174252892feSromanova-ekaterina [](const ImportMapIteratorTy &Lhs, const ImportMapIteratorTy &Rhs)
175252892feSromanova-ekaterina -> bool { return Lhs->getKey() < Rhs->getKey(); });
176252892feSromanova-ekaterina for (const ImportMapIteratorTy &EntryIt : ImportModulesVector) {
177252892feSromanova-ekaterina auto ModHash = Index.getModuleHash(EntryIt->first());
178adc0e26bSMehdi Amini Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
17954a52b75SPeter Collingbourne
180252892feSromanova-ekaterina AddUint64(EntryIt->second.size());
181252892feSromanova-ekaterina for (auto &Fn : EntryIt->second)
182d68935c5STeresa Johnson AddUint64(Fn);
183adc0e26bSMehdi Amini }
184adc0e26bSMehdi Amini
185adc0e26bSMehdi Amini // Include the hash for the resolved ODR.
186adc0e26bSMehdi Amini for (auto &Entry : ResolvedODR) {
187adc0e26bSMehdi Amini Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
188adc0e26bSMehdi Amini sizeof(GlobalValue::GUID)));
189adc0e26bSMehdi Amini Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
190adc0e26bSMehdi Amini sizeof(GlobalValue::LinkageTypes)));
191adc0e26bSMehdi Amini }
192adc0e26bSMehdi Amini
1933427d17cSEvgeniy Stepanov // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
1943427d17cSEvgeniy Stepanov // defined in this module.
1953427d17cSEvgeniy Stepanov std::set<GlobalValue::GUID> UsedCfiDefs;
1963427d17cSEvgeniy Stepanov std::set<GlobalValue::GUID> UsedCfiDecls;
1973427d17cSEvgeniy Stepanov
1983427d17cSEvgeniy Stepanov // Typeids used in this module.
199780a4dd3SPeter Collingbourne std::set<GlobalValue::GUID> UsedTypeIds;
200780a4dd3SPeter Collingbourne
2013427d17cSEvgeniy Stepanov auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
2023427d17cSEvgeniy Stepanov if (CfiFunctionDefs.count(ValueGUID))
2033427d17cSEvgeniy Stepanov UsedCfiDefs.insert(ValueGUID);
2043427d17cSEvgeniy Stepanov if (CfiFunctionDecls.count(ValueGUID))
2053427d17cSEvgeniy Stepanov UsedCfiDecls.insert(ValueGUID);
2063427d17cSEvgeniy Stepanov };
2073427d17cSEvgeniy Stepanov
2083427d17cSEvgeniy Stepanov auto AddUsedThings = [&](GlobalValueSummary *GS) {
2093427d17cSEvgeniy Stepanov if (!GS) return;
21054fb3ca9SFangrui Song AddUnsigned(GS->getVisibility());
2117f1a5ba1SPeter Collingbourne AddUnsigned(GS->isLive());
21237b80122STeresa Johnson AddUnsigned(GS->canAutoHide());
213b4edfb9aSPeter Collingbourne for (const ValueInfo &VI : GS->refs()) {
21480dc0661SWei Wang AddUnsigned(VI.isDSOLocal(Index.withDSOLocalPropagation()));
2153427d17cSEvgeniy Stepanov AddUsedCfiGlobal(VI.getGUID());
216b4edfb9aSPeter Collingbourne }
2173aef3528SEugene Leviant if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) {
2183aef3528SEugene Leviant AddUnsigned(GVS->maybeReadOnly());
2193aef3528SEugene Leviant AddUnsigned(GVS->maybeWriteOnly());
2203aef3528SEugene Leviant }
2213427d17cSEvgeniy Stepanov if (auto *FS = dyn_cast<FunctionSummary>(GS)) {
222780a4dd3SPeter Collingbourne for (auto &TT : FS->type_tests())
223780a4dd3SPeter Collingbourne UsedTypeIds.insert(TT);
224780a4dd3SPeter Collingbourne for (auto &TT : FS->type_test_assume_vcalls())
225780a4dd3SPeter Collingbourne UsedTypeIds.insert(TT.GUID);
226780a4dd3SPeter Collingbourne for (auto &TT : FS->type_checked_load_vcalls())
227780a4dd3SPeter Collingbourne UsedTypeIds.insert(TT.GUID);
228780a4dd3SPeter Collingbourne for (auto &TT : FS->type_test_assume_const_vcalls())
229780a4dd3SPeter Collingbourne UsedTypeIds.insert(TT.VFunc.GUID);
230780a4dd3SPeter Collingbourne for (auto &TT : FS->type_checked_load_const_vcalls())
231780a4dd3SPeter Collingbourne UsedTypeIds.insert(TT.VFunc.GUID);
2323fe815d1SPeter Collingbourne for (auto &ET : FS->calls()) {
23380dc0661SWei Wang AddUnsigned(ET.first.isDSOLocal(Index.withDSOLocalPropagation()));
2343427d17cSEvgeniy Stepanov AddUsedCfiGlobal(ET.first.getGUID());
2353427d17cSEvgeniy Stepanov }
2363fe815d1SPeter Collingbourne }
237780a4dd3SPeter Collingbourne };
238780a4dd3SPeter Collingbourne
239adc0e26bSMehdi Amini // Include the hash for the linkage type to reflect internalization and weak
240780a4dd3SPeter Collingbourne // resolution, and collect any used type identifier resolutions.
241adc0e26bSMehdi Amini for (auto &GS : DefinedGlobals) {
242adc0e26bSMehdi Amini GlobalValue::LinkageTypes Linkage = GS.second->linkage();
243adc0e26bSMehdi Amini Hasher.update(
244adc0e26bSMehdi Amini ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
2453427d17cSEvgeniy Stepanov AddUsedCfiGlobal(GS.first);
2463427d17cSEvgeniy Stepanov AddUsedThings(GS.second);
247780a4dd3SPeter Collingbourne }
248780a4dd3SPeter Collingbourne
249780a4dd3SPeter Collingbourne // Imported functions may introduce new uses of type identifier resolutions,
250780a4dd3SPeter Collingbourne // so we need to collect their used resolutions as well.
251780a4dd3SPeter Collingbourne for (auto &ImpM : ImportList)
252cf5ecb1aSGeorge Burgess IV for (auto &ImpF : ImpM.second) {
253cf5ecb1aSGeorge Burgess IV GlobalValueSummary *S = Index.findSummaryInModule(ImpF, ImpM.first());
254cf5ecb1aSGeorge Burgess IV AddUsedThings(S);
255cf5ecb1aSGeorge Burgess IV // If this is an alias, we also care about any types/etc. that the aliasee
256cf5ecb1aSGeorge Burgess IV // may reference.
257cf5ecb1aSGeorge Burgess IV if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
258cf5ecb1aSGeorge Burgess IV AddUsedThings(AS->getBaseObject());
259cf5ecb1aSGeorge Burgess IV }
260780a4dd3SPeter Collingbourne
261780a4dd3SPeter Collingbourne auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
262780a4dd3SPeter Collingbourne AddString(TId);
263780a4dd3SPeter Collingbourne
264780a4dd3SPeter Collingbourne AddUnsigned(S.TTRes.TheKind);
265780a4dd3SPeter Collingbourne AddUnsigned(S.TTRes.SizeM1BitWidth);
266711284b0SPeter Collingbourne
267b9b60253SPeter Collingbourne AddUint64(S.TTRes.AlignLog2);
268b9b60253SPeter Collingbourne AddUint64(S.TTRes.SizeM1);
269b9b60253SPeter Collingbourne AddUint64(S.TTRes.BitMask);
270b9b60253SPeter Collingbourne AddUint64(S.TTRes.InlineBits);
271b9b60253SPeter Collingbourne
272711284b0SPeter Collingbourne AddUint64(S.WPDRes.size());
273711284b0SPeter Collingbourne for (auto &WPD : S.WPDRes) {
274711284b0SPeter Collingbourne AddUnsigned(WPD.first);
275711284b0SPeter Collingbourne AddUnsigned(WPD.second.TheKind);
276711284b0SPeter Collingbourne AddString(WPD.second.SingleImplName);
277711284b0SPeter Collingbourne
278711284b0SPeter Collingbourne AddUint64(WPD.second.ResByArg.size());
279711284b0SPeter Collingbourne for (auto &ByArg : WPD.second.ResByArg) {
280711284b0SPeter Collingbourne AddUint64(ByArg.first.size());
281711284b0SPeter Collingbourne for (uint64_t Arg : ByArg.first)
282711284b0SPeter Collingbourne AddUint64(Arg);
283711284b0SPeter Collingbourne AddUnsigned(ByArg.second.TheKind);
284711284b0SPeter Collingbourne AddUint64(ByArg.second.Info);
285b15a35e6SPeter Collingbourne AddUnsigned(ByArg.second.Byte);
286b15a35e6SPeter Collingbourne AddUnsigned(ByArg.second.Bit);
287711284b0SPeter Collingbourne }
288711284b0SPeter Collingbourne }
289780a4dd3SPeter Collingbourne };
290780a4dd3SPeter Collingbourne
291780a4dd3SPeter Collingbourne // Include the hash for all type identifiers used by this module.
292780a4dd3SPeter Collingbourne for (GlobalValue::GUID TId : UsedTypeIds) {
2937fb39dfaSTeresa Johnson auto TidIter = Index.typeIds().equal_range(TId);
2947fb39dfaSTeresa Johnson for (auto It = TidIter.first; It != TidIter.second; ++It)
2957fb39dfaSTeresa Johnson AddTypeIdSummary(It->second.first, It->second.second);
296adc0e26bSMehdi Amini }
297adc0e26bSMehdi Amini
2983427d17cSEvgeniy Stepanov AddUnsigned(UsedCfiDefs.size());
2993427d17cSEvgeniy Stepanov for (auto &V : UsedCfiDefs)
3003427d17cSEvgeniy Stepanov AddUint64(V);
3013427d17cSEvgeniy Stepanov
3023427d17cSEvgeniy Stepanov AddUnsigned(UsedCfiDecls.size());
3033427d17cSEvgeniy Stepanov for (auto &V : UsedCfiDecls)
3043427d17cSEvgeniy Stepanov AddUint64(V);
3053427d17cSEvgeniy Stepanov
30627978005SDehao Chen if (!Conf.SampleProfile.empty()) {
30727978005SDehao Chen auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
3086c676628SRichard Smith if (FileOrErr) {
3096c676628SRichard Smith Hasher.update(FileOrErr.get()->getBuffer());
3106c676628SRichard Smith
3116c676628SRichard Smith if (!Conf.ProfileRemapping.empty()) {
3126c676628SRichard Smith FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping);
31327978005SDehao Chen if (FileOrErr)
31427978005SDehao Chen Hasher.update(FileOrErr.get()->getBuffer());
31527978005SDehao Chen }
3166c676628SRichard Smith }
3176c676628SRichard Smith }
31827978005SDehao Chen
319adc0e26bSMehdi Amini Key = toHex(Hasher.result());
320adc0e26bSMehdi Amini }
321adc0e26bSMehdi Amini
thinLTOResolvePrevailingGUID(const Config & C,ValueInfo VI,DenseSet<GlobalValueSummary * > & GlobalInvolvedWithAlias,function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> isPrevailing,function_ref<void (StringRef,GlobalValue::GUID,GlobalValue::LinkageTypes)> recordNewLinkage,const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols)322e61652a3SPirama Arumuga Nainar static void thinLTOResolvePrevailingGUID(
32354fb3ca9SFangrui Song const Config &C, ValueInfo VI,
32454fb3ca9SFangrui Song DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
325d3f4c05aSBenjamin Kramer function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
32604c9a2d6STeresa Johnson isPrevailing,
327d3f4c05aSBenjamin Kramer function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
32837b80122STeresa Johnson recordNewLinkage,
32937b80122STeresa Johnson const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
33054fb3ca9SFangrui Song GlobalValue::VisibilityTypes Visibility =
33154fb3ca9SFangrui Song C.VisibilityScheme == Config::ELF ? VI.getELFVisibility()
33254fb3ca9SFangrui Song : GlobalValue::DefaultVisibility;
33337b80122STeresa Johnson for (auto &S : VI.getSummaryList()) {
33404c9a2d6STeresa Johnson GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
335e61652a3SPirama Arumuga Nainar // Ignore local and appending linkage values since the linker
336e61652a3SPirama Arumuga Nainar // doesn't resolve them.
337e61652a3SPirama Arumuga Nainar if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
338e61652a3SPirama Arumuga Nainar GlobalValue::isAppendingLinkage(S->linkage()))
33904c9a2d6STeresa Johnson continue;
34073589f32SPeter Collingbourne // We need to emit only one of these. The prevailing module will keep it,
34104c9a2d6STeresa Johnson // but turned into a weak, while the others will drop it when possible.
3423bc8abdfSTeresa Johnson // This is both a compile-time optimization and a correctness
3433bc8abdfSTeresa Johnson // transformation. This is necessary for correctness when we have exported
3443bc8abdfSTeresa Johnson // a reference - we need to convert the linkonce to weak to
3453bc8abdfSTeresa Johnson // ensure a copy is kept to satisfy the exported reference.
3463bc8abdfSTeresa Johnson // FIXME: We may want to split the compile time and correctness
3473bc8abdfSTeresa Johnson // aspects into separate routines.
34837b80122STeresa Johnson if (isPrevailing(VI.getGUID(), S.get())) {
34937b80122STeresa Johnson if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) {
35028c03b56STeresa Johnson S->setLinkage(GlobalValue::getWeakLinkage(
35128c03b56STeresa Johnson GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
35237b80122STeresa Johnson // The kept copy is eligible for auto-hiding (hidden visibility) if all
35337b80122STeresa Johnson // copies were (i.e. they were all linkonce_odr global unnamed addr).
35437b80122STeresa Johnson // If any copy is not (e.g. it was originally weak_odr), then the symbol
35537b80122STeresa Johnson // must remain externally available (e.g. a weak_odr from an explicitly
35637b80122STeresa Johnson // instantiated template). Additionally, if it is in the
35737b80122STeresa Johnson // GUIDPreservedSymbols set, that means that it is visibile outside
35837b80122STeresa Johnson // the summary (e.g. in a native object or a bitcode file without
35937b80122STeresa Johnson // summary), and in that case we cannot hide it as it isn't possible to
36037b80122STeresa Johnson // check all copies.
36137b80122STeresa Johnson S->setCanAutoHide(VI.canAutoHide() &&
36237b80122STeresa Johnson !GUIDPreservedSymbols.count(VI.getGUID()));
36337b80122STeresa Johnson }
36454fb3ca9SFangrui Song if (C.VisibilityScheme == Config::FromPrevailing)
36554fb3ca9SFangrui Song Visibility = S->getVisibility();
36604c9a2d6STeresa Johnson }
3673bc8abdfSTeresa Johnson // Alias and aliasee can't be turned into available_externally.
36804c9a2d6STeresa Johnson else if (!isa<AliasSummary>(S.get()) &&
3694566c6dbSTeresa Johnson !GlobalInvolvedWithAlias.count(S.get()))
37004c9a2d6STeresa Johnson S->setLinkage(GlobalValue::AvailableExternallyLinkage);
37154fb3ca9SFangrui Song
37254fb3ca9SFangrui Song // For ELF, set visibility to the computed visibility from summaries. We
37354fb3ca9SFangrui Song // don't track visibility from declarations so this may be more relaxed than
37454fb3ca9SFangrui Song // the most constraining one.
37554fb3ca9SFangrui Song if (C.VisibilityScheme == Config::ELF)
37654fb3ca9SFangrui Song S->setVisibility(Visibility);
37754fb3ca9SFangrui Song
37804c9a2d6STeresa Johnson if (S->linkage() != OriginalLinkage)
37937b80122STeresa Johnson recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
38004c9a2d6STeresa Johnson }
38154fb3ca9SFangrui Song
38254fb3ca9SFangrui Song if (C.VisibilityScheme == Config::FromPrevailing) {
38354fb3ca9SFangrui Song for (auto &S : VI.getSummaryList()) {
38454fb3ca9SFangrui Song GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
38554fb3ca9SFangrui Song if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
38654fb3ca9SFangrui Song GlobalValue::isAppendingLinkage(S->linkage()))
38754fb3ca9SFangrui Song continue;
38854fb3ca9SFangrui Song S->setVisibility(Visibility);
38954fb3ca9SFangrui Song }
39054fb3ca9SFangrui Song }
39104c9a2d6STeresa Johnson }
39204c9a2d6STeresa Johnson
393e61652a3SPirama Arumuga Nainar /// Resolve linkage for prevailing symbols in the \p Index.
39404c9a2d6STeresa Johnson //
39504c9a2d6STeresa Johnson // We'd like to drop these functions if they are no longer referenced in the
39604c9a2d6STeresa Johnson // current module. However there is a chance that another module is still
39704c9a2d6STeresa Johnson // referencing them because of the import. We make sure we always emit at least
39804c9a2d6STeresa Johnson // one copy.
thinLTOResolvePrevailingInIndex(const Config & C,ModuleSummaryIndex & Index,function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> isPrevailing,function_ref<void (StringRef,GlobalValue::GUID,GlobalValue::LinkageTypes)> recordNewLinkage,const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols)399e61652a3SPirama Arumuga Nainar void llvm::thinLTOResolvePrevailingInIndex(
40054fb3ca9SFangrui Song const Config &C, ModuleSummaryIndex &Index,
401d3f4c05aSBenjamin Kramer function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
40204c9a2d6STeresa Johnson isPrevailing,
403d3f4c05aSBenjamin Kramer function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
40437b80122STeresa Johnson recordNewLinkage,
40537b80122STeresa Johnson const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
40604c9a2d6STeresa Johnson // We won't optimize the globals that are referenced by an alias for now
40704c9a2d6STeresa Johnson // Ideally we should turn the alias into a global and duplicate the definition
40804c9a2d6STeresa Johnson // when needed.
40904c9a2d6STeresa Johnson DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
41004c9a2d6STeresa Johnson for (auto &I : Index)
4119667b91bSPeter Collingbourne for (auto &S : I.second.SummaryList)
41204c9a2d6STeresa Johnson if (auto AS = dyn_cast<AliasSummary>(S.get()))
41304c9a2d6STeresa Johnson GlobalInvolvedWithAlias.insert(&AS->getAliasee());
41404c9a2d6STeresa Johnson
41504c9a2d6STeresa Johnson for (auto &I : Index)
41654fb3ca9SFangrui Song thinLTOResolvePrevailingGUID(C, Index.getValueInfo(I),
41754fb3ca9SFangrui Song GlobalInvolvedWithAlias, isPrevailing,
41854fb3ca9SFangrui Song recordNewLinkage, GUIDPreservedSymbols);
41904c9a2d6STeresa Johnson }
42004c9a2d6STeresa Johnson
isWeakObjectWithRWAccess(GlobalValueSummary * GVS)4213aef3528SEugene Leviant static bool isWeakObjectWithRWAccess(GlobalValueSummary *GVS) {
422053c6fc2SEugene Leviant if (auto *VarSummary = dyn_cast<GlobalVarSummary>(GVS->getBaseObject()))
4233aef3528SEugene Leviant return !VarSummary->maybeReadOnly() && !VarSummary->maybeWriteOnly() &&
424053c6fc2SEugene Leviant (VarSummary->linkage() == GlobalValue::WeakODRLinkage ||
425053c6fc2SEugene Leviant VarSummary->linkage() == GlobalValue::LinkOnceODRLinkage);
426053c6fc2SEugene Leviant return false;
427053c6fc2SEugene Leviant }
428053c6fc2SEugene Leviant
thinLTOInternalizeAndPromoteGUID(ValueInfo VI,function_ref<bool (StringRef,ValueInfo)> isExported,function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> isPrevailing)42904c9a2d6STeresa Johnson static void thinLTOInternalizeAndPromoteGUID(
430ef5e3b85Sevgeny ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
431ea314fd4STeresa Johnson function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
432ea314fd4STeresa Johnson isPrevailing) {
433ef5e3b85Sevgeny for (auto &S : VI.getSummaryList()) {
4343d708bf5Sevgeny if (isExported(S->modulePath(), VI)) {
43504c9a2d6STeresa Johnson if (GlobalValue::isLocalLinkage(S->linkage()))
43604c9a2d6STeresa Johnson S->setLinkage(GlobalValue::ExternalLinkage);
4377ca74448SXin Tong } else if (EnableLTOInternalization &&
438e61652a3SPirama Arumuga Nainar // Ignore local and appending linkage values since the linker
439e61652a3SPirama Arumuga Nainar // doesn't resolve them.
440e61652a3SPirama Arumuga Nainar !GlobalValue::isLocalLinkage(S->linkage()) &&
441ea314fd4STeresa Johnson (!GlobalValue::isInterposableLinkage(S->linkage()) ||
4423d708bf5Sevgeny isPrevailing(VI.getGUID(), S.get())) &&
443ff9aaa25SPeter Collingbourne S->linkage() != GlobalValue::AppendingLinkage &&
444ff9aaa25SPeter Collingbourne // We can't internalize available_externally globals because this
445ff9aaa25SPeter Collingbourne // can break function pointer equality.
446053c6fc2SEugene Leviant S->linkage() != GlobalValue::AvailableExternallyLinkage &&
4473aef3528SEugene Leviant // Functions and read-only variables with linkonce_odr and
4483aef3528SEugene Leviant // weak_odr linkage can be internalized. We can't internalize
4493aef3528SEugene Leviant // linkonce_odr and weak_odr variables which are both modified
4503aef3528SEugene Leviant // and read somewhere in the program because reads and writes
4513aef3528SEugene Leviant // will become inconsistent.
4523aef3528SEugene Leviant !isWeakObjectWithRWAccess(S.get()))
45304c9a2d6STeresa Johnson S->setLinkage(GlobalValue::InternalLinkage);
45404c9a2d6STeresa Johnson }
45504c9a2d6STeresa Johnson }
45604c9a2d6STeresa Johnson
45704c9a2d6STeresa Johnson // Update the linkages in the given \p Index to mark exported values
45804c9a2d6STeresa Johnson // as external and non-exported values as internal.
thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex & Index,function_ref<bool (StringRef,ValueInfo)> isExported,function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> isPrevailing)4599ba95f99STeresa Johnson void llvm::thinLTOInternalizeAndPromoteInIndex(
46004c9a2d6STeresa Johnson ModuleSummaryIndex &Index,
4613d708bf5Sevgeny function_ref<bool(StringRef, ValueInfo)> isExported,
462ea314fd4STeresa Johnson function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
463ea314fd4STeresa Johnson isPrevailing) {
46404c9a2d6STeresa Johnson for (auto &I : Index)
465ef5e3b85Sevgeny thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported,
466ef5e3b85Sevgeny isPrevailing);
46704c9a2d6STeresa Johnson }
4689ba95f99STeresa Johnson
4691a0720e8SPeter Collingbourne // Requires a destructor for std::vector<InputModule>.
4701a0720e8SPeter Collingbourne InputFile::~InputFile() = default;
4711a0720e8SPeter Collingbourne
create(MemoryBufferRef Object)4729ba95f99STeresa Johnson Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
4739ba95f99STeresa Johnson std::unique_ptr<InputFile> File(new InputFile);
4749ba95f99STeresa Johnson
475c00c2b24SPeter Collingbourne Expected<IRSymtabFile> FOrErr = readIRSymtab(Object);
476c00c2b24SPeter Collingbourne if (!FOrErr)
477c00c2b24SPeter Collingbourne return FOrErr.takeError();
4789ba95f99STeresa Johnson
479c00c2b24SPeter Collingbourne File->TargetTriple = FOrErr->TheReader.getTargetTriple();
480c00c2b24SPeter Collingbourne File->SourceFileName = FOrErr->TheReader.getSourceFileName();
481c00c2b24SPeter Collingbourne File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
4821d16515fSBen Dunbobbin File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
483c00c2b24SPeter Collingbourne File->ComdatTable = FOrErr->TheReader.getComdatTable();
4841a0720e8SPeter Collingbourne
485c00c2b24SPeter Collingbourne for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
4867b30f16cSPeter Collingbourne size_t Begin = File->Symbols.size();
487c00c2b24SPeter Collingbourne for (const irsymtab::Reader::SymbolRef &Sym :
488c00c2b24SPeter Collingbourne FOrErr->TheReader.module_symbols(I))
4897b30f16cSPeter Collingbourne // Skip symbols that are irrelevant to LTO. Note that this condition needs
4907b30f16cSPeter Collingbourne // to match the one in Skip() in LTO::addRegularLTO().
4917b30f16cSPeter Collingbourne if (Sym.isGlobal() && !Sym.isFormatSpecific())
4927b30f16cSPeter Collingbourne File->Symbols.push_back(Sym);
4937b30f16cSPeter Collingbourne File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
4941a0720e8SPeter Collingbourne }
4951a0720e8SPeter Collingbourne
496c00c2b24SPeter Collingbourne File->Mods = FOrErr->Mods;
497c00c2b24SPeter Collingbourne File->Strtab = std::move(FOrErr->Strtab);
498c55cf4afSBill Wendling return std::move(File);
4999ba95f99STeresa Johnson }
5009ba95f99STeresa Johnson
getName() const5011a0720e8SPeter Collingbourne StringRef InputFile::getName() const {
5027b30f16cSPeter Collingbourne return Mods[0].getModuleIdentifier();
5031a0720e8SPeter Collingbourne }
5041a0720e8SPeter Collingbourne
getSingleBitcodeModule()50505a358cdSSteven Wu BitcodeModule &InputFile::getSingleBitcodeModule() {
50605a358cdSSteven Wu assert(Mods.size() == 1 && "Expect only one bitcode module");
50705a358cdSSteven Wu return Mods[0];
50805a358cdSSteven Wu }
50905a358cdSSteven Wu
RegularLTOState(unsigned ParallelCodeGenParallelismLevel,const Config & Conf)5109ba95f99STeresa Johnson LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
511d0aad9f5STeresa Johnson const Config &Conf)
5129ba95f99STeresa Johnson : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
5130eaee545SJonas Devlieghere Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)),
5140eaee545SJonas Devlieghere Mover(std::make_unique<IRMover>(*CombinedModule)) {}
5159ba95f99STeresa Johnson
ThinLTOState(ThinBackend Backend)51628d8a49fSEugene Leviant LTO::ThinLTOState::ThinLTOState(ThinBackend Backend)
5174ffc3e78STeresa Johnson : Backend(Backend), CombinedIndex(/*HaveGVs*/ false) {
5189ba95f99STeresa Johnson if (!Backend)
51909158252SAlexandre Ganea this->Backend =
52009158252SAlexandre Ganea createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
5219ba95f99STeresa Johnson }
5229ba95f99STeresa Johnson
LTO(Config Conf,ThinBackend Backend,unsigned ParallelCodeGenParallelismLevel)5239ba95f99STeresa Johnson LTO::LTO(Config Conf, ThinBackend Backend,
5249ba95f99STeresa Johnson unsigned ParallelCodeGenParallelismLevel)
5259ba95f99STeresa Johnson : Conf(std::move(Conf)),
5269ba95f99STeresa Johnson RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
527026ddbb4SMehdi Amini ThinLTO(std::move(Backend)) {}
5289ba95f99STeresa Johnson
5291a0720e8SPeter Collingbourne // Requires a destructor for MapVector<BitcodeModule>.
5301a0720e8SPeter Collingbourne LTO::~LTO() = default;
5311a0720e8SPeter Collingbourne
532dbd2fed6SPeter Collingbourne // Add the symbols in the given module to the GlobalResolutions map, and resolve
533dbd2fed6SPeter Collingbourne // their partitions.
addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,ArrayRef<SymbolResolution> Res,unsigned Partition,bool InSummary)534dbd2fed6SPeter Collingbourne void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
535dbd2fed6SPeter Collingbourne ArrayRef<SymbolResolution> Res,
536dbd2fed6SPeter Collingbourne unsigned Partition, bool InSummary) {
537dbd2fed6SPeter Collingbourne auto *ResI = Res.begin();
538dbd2fed6SPeter Collingbourne auto *ResE = Res.end();
5397e85b265SPeter Collingbourne (void)ResE;
540595c418aSFangrui Song const Triple TT(RegularLTO.CombinedModule->getTargetTriple());
541dbd2fed6SPeter Collingbourne for (const InputFile::Symbol &Sym : Syms) {
542dbd2fed6SPeter Collingbourne assert(ResI != ResE);
543dbd2fed6SPeter Collingbourne SymbolResolution Res = *ResI++;
544dbd2fed6SPeter Collingbourne
545b963c0b6STeresa Johnson StringRef Name = Sym.getName();
546b963c0b6STeresa Johnson // Strip the __imp_ prefix from COFF dllimport symbols (similar to the
547b963c0b6STeresa Johnson // way they are handled by lld), otherwise we can end up with two
548b963c0b6STeresa Johnson // global resolutions (one with and one for a copy of the symbol without).
549b963c0b6STeresa Johnson if (TT.isOSBinFormatCOFF() && Name.startswith("__imp_"))
550b963c0b6STeresa Johnson Name = Name.substr(strlen("__imp_"));
551b963c0b6STeresa Johnson auto &GlobalRes = GlobalResolutions[Name];
5527b30f16cSPeter Collingbourne GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
553746f152dSEugene Leviant if (Res.Prevailing) {
554d328365bSGeorge Rimar assert(!GlobalRes.Prevailing &&
555cb122492SEugene Leviant "Multiple prevailing defs are not allowed");
556d328365bSGeorge Rimar GlobalRes.Prevailing = true;
557adcd0268SBenjamin Kramer GlobalRes.IRName = std::string(Sym.getIRName());
558eaf5172cSGeorge Rimar } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
559eaf5172cSGeorge Rimar // Sometimes it can be two copies of symbol in a module and prevailing
560eaf5172cSGeorge Rimar // symbol can have no IR name. That might happen if symbol is defined in
561eaf5172cSGeorge Rimar // module level inline asm block. In case we have multiple modules with
562eaf5172cSGeorge Rimar // the same symbol we want to use IR name of the prevailing symbol.
563eaf5172cSGeorge Rimar // Otherwise, if we haven't seen a prevailing symbol, set the name so that
564eaf5172cSGeorge Rimar // we can later use it to check if there is any prevailing copy in IR.
565adcd0268SBenjamin Kramer GlobalRes.IRName = std::string(Sym.getIRName());
566746f152dSEugene Leviant }
5677b30f16cSPeter Collingbourne
568db3b87b2SDmitry Mikulin // Set the partition to external if we know it is re-defined by the linker
569db3b87b2SDmitry Mikulin // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
570584cb67dSFangrui Song // regular object, is referenced from llvm.compiler.used/llvm.used, or was
571584cb67dSFangrui Song // already recorded as being referenced from a different partition.
572db3b87b2SDmitry Mikulin if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
5739ba95f99STeresa Johnson (GlobalRes.Partition != GlobalResolution::Unknown &&
5746c475a75STeresa Johnson GlobalRes.Partition != Partition)) {
5759ba95f99STeresa Johnson GlobalRes.Partition = GlobalResolution::External;
5766c475a75STeresa Johnson } else
5776c475a75STeresa Johnson // First recorded reference, save the current partition.
5789ba95f99STeresa Johnson GlobalRes.Partition = Partition;
5796c475a75STeresa Johnson
580dbd2fed6SPeter Collingbourne // Flag as visible outside of summary if visible from a regular object or
581dbd2fed6SPeter Collingbourne // from a module that does not have a summary.
582dbd2fed6SPeter Collingbourne GlobalRes.VisibleOutsideSummary |=
583dbd2fed6SPeter Collingbourne (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
5841487747eSTeresa Johnson
5851487747eSTeresa Johnson GlobalRes.ExportDynamic |= Res.ExportDynamic;
586dbd2fed6SPeter Collingbourne }
5879ba95f99STeresa Johnson }
5889ba95f99STeresa Johnson
writeToResolutionFile(raw_ostream & OS,InputFile * Input,ArrayRef<SymbolResolution> Res)5897775c331SRafael Espindola static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
5909ba95f99STeresa Johnson ArrayRef<SymbolResolution> Res) {
5911a0720e8SPeter Collingbourne StringRef Path = Input->getName();
5927775c331SRafael Espindola OS << Path << '\n';
5939ba95f99STeresa Johnson auto ResI = Res.begin();
5949ba95f99STeresa Johnson for (const InputFile::Symbol &Sym : Input->symbols()) {
5959ba95f99STeresa Johnson assert(ResI != Res.end());
5969ba95f99STeresa Johnson SymbolResolution Res = *ResI++;
5979ba95f99STeresa Johnson
5987775c331SRafael Espindola OS << "-r=" << Path << ',' << Sym.getName() << ',';
5999ba95f99STeresa Johnson if (Res.Prevailing)
6007775c331SRafael Espindola OS << 'p';
6019ba95f99STeresa Johnson if (Res.FinalDefinitionInLinkageUnit)
6027775c331SRafael Espindola OS << 'l';
6039ba95f99STeresa Johnson if (Res.VisibleToRegularObj)
6047775c331SRafael Espindola OS << 'x';
605db3b87b2SDmitry Mikulin if (Res.LinkerRedefined)
606db3b87b2SDmitry Mikulin OS << 'r';
6077775c331SRafael Espindola OS << '\n';
6089ba95f99STeresa Johnson }
60958ffcfbfSPeter Collingbourne OS.flush();
6109ba95f99STeresa Johnson assert(ResI == Res.end());
6119ba95f99STeresa Johnson }
6129ba95f99STeresa Johnson
add(std::unique_ptr<InputFile> Input,ArrayRef<SymbolResolution> Res)6139ba95f99STeresa Johnson Error LTO::add(std::unique_ptr<InputFile> Input,
6149ba95f99STeresa Johnson ArrayRef<SymbolResolution> Res) {
6159ba95f99STeresa Johnson assert(!CalledGetMaxTasks);
6169ba95f99STeresa Johnson
6179ba95f99STeresa Johnson if (Conf.ResolutionFile)
6187775c331SRafael Espindola writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
6199ba95f99STeresa Johnson
62054fb3ca9SFangrui Song if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
621a5376f39SVitaly Buka RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
62254fb3ca9SFangrui Song if (Triple(Input->getTargetTriple()).isOSBinFormatELF())
62354fb3ca9SFangrui Song Conf.VisibilityScheme = Config::ELF;
62454fb3ca9SFangrui Song }
625a5376f39SVitaly Buka
6261a0720e8SPeter Collingbourne const SymbolResolution *ResI = Res.begin();
6277b30f16cSPeter Collingbourne for (unsigned I = 0; I != Input->Mods.size(); ++I)
6287b30f16cSPeter Collingbourne if (Error Err = addModule(*Input, I, ResI, Res.end()))
6291a0720e8SPeter Collingbourne return Err;
6301a0720e8SPeter Collingbourne
6311a0720e8SPeter Collingbourne assert(ResI == Res.end());
6321a0720e8SPeter Collingbourne return Error::success();
6331a0720e8SPeter Collingbourne }
6341a0720e8SPeter Collingbourne
addModule(InputFile & Input,unsigned ModI,const SymbolResolution * & ResI,const SymbolResolution * ResE)6357b30f16cSPeter Collingbourne Error LTO::addModule(InputFile &Input, unsigned ModI,
6361a0720e8SPeter Collingbourne const SymbolResolution *&ResI,
6371a0720e8SPeter Collingbourne const SymbolResolution *ResE) {
638dbd2fed6SPeter Collingbourne Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
639dbd2fed6SPeter Collingbourne if (!LTOInfo)
640dbd2fed6SPeter Collingbourne return LTOInfo.takeError();
6419ba95f99STeresa Johnson
642e0e687a6SKazu Hirata if (EnableSplitLTOUnit) {
643290a8398STeresa Johnson // If only some modules were split, flag this in the index so that
644290a8398STeresa Johnson // we can skip or error on optimizations that need consistently split
645290a8398STeresa Johnson // modules (whole program devirt and lower type tests).
6467a47ee51SKazu Hirata if (*EnableSplitLTOUnit != LTOInfo->EnableSplitLTOUnit)
647290a8398STeresa Johnson ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
648290a8398STeresa Johnson } else
649290a8398STeresa Johnson EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
650290a8398STeresa Johnson
651dbd2fed6SPeter Collingbourne BitcodeModule BM = Input.Mods[ModI];
6527b30f16cSPeter Collingbourne auto ModSyms = Input.module_symbols(ModI);
653dbd2fed6SPeter Collingbourne addModuleToGlobalRes(ModSyms, {ResI, ResE},
654dbd2fed6SPeter Collingbourne LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
655dbd2fed6SPeter Collingbourne LTOInfo->HasSummary);
656dbd2fed6SPeter Collingbourne
657dbd2fed6SPeter Collingbourne if (LTOInfo->IsThinLTO)
658dbd2fed6SPeter Collingbourne return addThinLTO(BM, ModSyms, ResI, ResE);
659dbd2fed6SPeter Collingbourne
660ad5fad0aSZakk Chen RegularLTO.EmptyCombinedModule = false;
661dbd2fed6SPeter Collingbourne Expected<RegularLTOState::AddedModule> ModOrErr =
662dbd2fed6SPeter Collingbourne addRegularLTO(BM, ModSyms, ResI, ResE);
663dbd2fed6SPeter Collingbourne if (!ModOrErr)
664dbd2fed6SPeter Collingbourne return ModOrErr.takeError();
665dbd2fed6SPeter Collingbourne
666dbd2fed6SPeter Collingbourne if (!LTOInfo->HasSummary)
667dbd2fed6SPeter Collingbourne return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false);
668dbd2fed6SPeter Collingbourne
669dbd2fed6SPeter Collingbourne // Regular LTO module summaries are added to a dummy module that represents
670dbd2fed6SPeter Collingbourne // the combined regular LTO module.
671dbd2fed6SPeter Collingbourne if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, "", -1ull))
672dbd2fed6SPeter Collingbourne return Err;
673dbd2fed6SPeter Collingbourne RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
674dbd2fed6SPeter Collingbourne return Error::success();
6759ba95f99STeresa Johnson }
6769ba95f99STeresa Johnson
677b247ffbaSTeresa Johnson // Checks whether the given global value is in a non-prevailing comdat
678b247ffbaSTeresa Johnson // (comdat containing values the linker indicated were not prevailing,
679b247ffbaSTeresa Johnson // which we then dropped to available_externally), and if so, removes
680b247ffbaSTeresa Johnson // it from the comdat. This is called for all global values to ensure the
681b247ffbaSTeresa Johnson // comdat is empty rather than leaving an incomplete comdat. It is needed for
682b247ffbaSTeresa Johnson // regular LTO modules, in case we are in a mixed-LTO mode (both regular
683b247ffbaSTeresa Johnson // and thin LTO modules) compilation. Since the regular LTO module will be
684b247ffbaSTeresa Johnson // linked first in the final native link, we want to make sure the linker
685b247ffbaSTeresa Johnson // doesn't select any of these incomplete comdats that would be left
686b247ffbaSTeresa Johnson // in the regular LTO module without this cleanup.
687b247ffbaSTeresa Johnson static void
handleNonPrevailingComdat(GlobalValue & GV,std::set<const Comdat * > & NonPrevailingComdats)688b247ffbaSTeresa Johnson handleNonPrevailingComdat(GlobalValue &GV,
689b247ffbaSTeresa Johnson std::set<const Comdat *> &NonPrevailingComdats) {
690b247ffbaSTeresa Johnson Comdat *C = GV.getComdat();
691b247ffbaSTeresa Johnson if (!C)
692b247ffbaSTeresa Johnson return;
693b247ffbaSTeresa Johnson
694b247ffbaSTeresa Johnson if (!NonPrevailingComdats.count(C))
695b247ffbaSTeresa Johnson return;
696b247ffbaSTeresa Johnson
697b247ffbaSTeresa Johnson // Additionally need to drop externally visible global values from the comdat
698b247ffbaSTeresa Johnson // to available_externally, so that there aren't multiply defined linker
699b247ffbaSTeresa Johnson // errors.
700b247ffbaSTeresa Johnson if (!GV.hasLocalLinkage())
701b247ffbaSTeresa Johnson GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
702b247ffbaSTeresa Johnson
703b247ffbaSTeresa Johnson if (auto GO = dyn_cast<GlobalObject>(&GV))
704b247ffbaSTeresa Johnson GO->setComdat(nullptr);
705b247ffbaSTeresa Johnson }
706b247ffbaSTeresa Johnson
7079ba95f99STeresa Johnson // Add a regular LTO object to the link.
708dbd2fed6SPeter Collingbourne // The resulting module needs to be linked into the combined LTO module with
709dbd2fed6SPeter Collingbourne // linkRegularLTO.
710dbd2fed6SPeter Collingbourne Expected<LTO::RegularLTOState::AddedModule>
addRegularLTO(BitcodeModule BM,ArrayRef<InputFile::Symbol> Syms,const SymbolResolution * & ResI,const SymbolResolution * ResE)711dbd2fed6SPeter Collingbourne LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
7127b30f16cSPeter Collingbourne const SymbolResolution *&ResI,
7131a0720e8SPeter Collingbourne const SymbolResolution *ResE) {
714dbd2fed6SPeter Collingbourne RegularLTOState::AddedModule Mod;
715ad90369aSPeter Collingbourne Expected<std::unique_ptr<Module>> MOrErr =
716a61f5e37STeresa Johnson BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
717a61f5e37STeresa Johnson /*IsImporting*/ false);
718ad90369aSPeter Collingbourne if (!MOrErr)
719ad90369aSPeter Collingbourne return MOrErr.takeError();
720ad90369aSPeter Collingbourne Module &M = **MOrErr;
721dbd2fed6SPeter Collingbourne Mod.M = std::move(*MOrErr);
722dbd2fed6SPeter Collingbourne
7237f00d0a1SPeter Collingbourne if (Error Err = M.materializeMetadata())
724c55cf4afSBill Wendling return std::move(Err);
7259ba95f99STeresa Johnson UpgradeDebugInfo(M);
7269ba95f99STeresa Johnson
727ad90369aSPeter Collingbourne ModuleSymbolTable SymTab;
728ad90369aSPeter Collingbourne SymTab.addModule(&M);
729ad90369aSPeter Collingbourne
7309ba95f99STeresa Johnson for (GlobalVariable &GV : M.globals())
7319ba95f99STeresa Johnson if (GV.hasAppendingLinkage())
732dbd2fed6SPeter Collingbourne Mod.Keep.push_back(&GV);
7339ba95f99STeresa Johnson
7344613626dSPeter Collingbourne DenseSet<GlobalObject *> AliasedGlobals;
7354613626dSPeter Collingbourne for (auto &GA : M.aliases())
73640ec1c0fSItay Bookstein if (GlobalObject *GO = GA.getAliaseeObject())
7374613626dSPeter Collingbourne AliasedGlobals.insert(GO);
7384613626dSPeter Collingbourne
7397b30f16cSPeter Collingbourne // In this function we need IR GlobalValues matching the symbols in Syms
7407b30f16cSPeter Collingbourne // (which is not backed by a module), so we need to enumerate them in the same
7417b30f16cSPeter Collingbourne // order. The symbol enumeration order of a ModuleSymbolTable intentionally
7427b30f16cSPeter Collingbourne // matches the order of an irsymtab, but when we read the irsymtab in
7437b30f16cSPeter Collingbourne // InputFile::create we omit some symbols that are irrelevant to LTO. The
7447b30f16cSPeter Collingbourne // Skip() function skips the same symbols from the module as InputFile does
7457b30f16cSPeter Collingbourne // from the symbol table.
7467b30f16cSPeter Collingbourne auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
7477b30f16cSPeter Collingbourne auto Skip = [&]() {
7487b30f16cSPeter Collingbourne while (MsymI != MsymE) {
7497b30f16cSPeter Collingbourne auto Flags = SymTab.getSymbolFlags(*MsymI);
7507b30f16cSPeter Collingbourne if ((Flags & object::BasicSymbolRef::SF_Global) &&
7517b30f16cSPeter Collingbourne !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
7527b30f16cSPeter Collingbourne return;
7537b30f16cSPeter Collingbourne ++MsymI;
7547b30f16cSPeter Collingbourne }
7557b30f16cSPeter Collingbourne };
7567b30f16cSPeter Collingbourne Skip();
7577b30f16cSPeter Collingbourne
758b247ffbaSTeresa Johnson std::set<const Comdat *> NonPrevailingComdats;
759b4a8c0ebSYuanfang Chen SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
7607b30f16cSPeter Collingbourne for (const InputFile::Symbol &Sym : Syms) {
7611a0720e8SPeter Collingbourne assert(ResI != ResE);
7629ba95f99STeresa Johnson SymbolResolution Res = *ResI++;
7639ba95f99STeresa Johnson
7647b30f16cSPeter Collingbourne assert(MsymI != MsymE);
7657b30f16cSPeter Collingbourne ModuleSymbolTable::Symbol Msym = *MsymI++;
7667b30f16cSPeter Collingbourne Skip();
7677b30f16cSPeter Collingbourne
7687b30f16cSPeter Collingbourne if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
769c387e70cSPeter Collingbourne if (Res.Prevailing) {
7700d56b959SPeter Collingbourne if (Sym.isUndefined())
77139ccd241SDavide Italiano continue;
772dbd2fed6SPeter Collingbourne Mod.Keep.push_back(GV);
773db3b87b2SDmitry Mikulin // For symbols re-defined with linker -wrap and -defsym options,
774db3b87b2SDmitry Mikulin // set the linkage to weak to inhibit IPO. The linkage will be
775db3b87b2SDmitry Mikulin // restored by the linker.
776db3b87b2SDmitry Mikulin if (Res.LinkerRedefined)
777db3b87b2SDmitry Mikulin GV->setLinkage(GlobalValue::WeakAnyLinkage);
778db3b87b2SDmitry Mikulin
779d4db116aSDavide Italiano GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
780d4db116aSDavide Italiano if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
781d4db116aSDavide Italiano GV->setLinkage(GlobalValue::getWeakLinkage(
782d4db116aSDavide Italiano GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
7834613626dSPeter Collingbourne } else if (isa<GlobalObject>(GV) &&
7844613626dSPeter Collingbourne (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
7854613626dSPeter Collingbourne GV->hasAvailableExternallyLinkage()) &&
7864613626dSPeter Collingbourne !AliasedGlobals.count(cast<GlobalObject>(GV))) {
787dbd2fed6SPeter Collingbourne // Any of the above three types of linkage indicates that the
7884613626dSPeter Collingbourne // chosen prevailing symbol will have the same semantics as this copy of
789dbd2fed6SPeter Collingbourne // the symbol, so we may be able to link it with available_externally
790dbd2fed6SPeter Collingbourne // linkage. We will decide later whether to do that when we link this
791dbd2fed6SPeter Collingbourne // module (in linkRegularLTO), based on whether it is undefined.
792dbd2fed6SPeter Collingbourne Mod.Keep.push_back(GV);
7934613626dSPeter Collingbourne GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
794b247ffbaSTeresa Johnson if (GV->hasComdat())
795b247ffbaSTeresa Johnson NonPrevailingComdats.insert(GV->getComdat());
7964613626dSPeter Collingbourne cast<GlobalObject>(GV)->setComdat(nullptr);
7974613626dSPeter Collingbourne }
7984595a915SSean Fertile
7994595a915SSean Fertile // Set the 'local' flag based on the linker resolution for this symbol.
80062fcfc5aSMatthew Voss if (Res.FinalDefinitionInLinkageUnit) {
801349fe0aaSRafael Espindola GV->setDSOLocal(true);
80262fcfc5aSMatthew Voss if (GV->hasDLLImportStorageClass())
80362fcfc5aSMatthew Voss GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
80462fcfc5aSMatthew Voss DefaultStorageClass);
80562fcfc5aSMatthew Voss }
806b4a8c0ebSYuanfang Chen } else if (auto *AS = Msym.dyn_cast<ModuleSymbolTable::AsmSymbol *>()) {
807b4a8c0ebSYuanfang Chen // Collect non-prevailing symbols.
808b4a8c0ebSYuanfang Chen if (!Res.Prevailing)
809b4a8c0ebSYuanfang Chen NonPrevailingAsmSymbols.insert(AS->first);
810b4a8c0ebSYuanfang Chen } else {
811b4a8c0ebSYuanfang Chen llvm_unreachable("unknown symbol type");
812c387e70cSPeter Collingbourne }
813b4a8c0ebSYuanfang Chen
814b2f46d1dSMehdi Amini // Common resolution: collect the maximum size/alignment over all commons.
815b2f46d1dSMehdi Amini // We also record if we see an instance of a common as prevailing, so that
816b2f46d1dSMehdi Amini // if none is prevailing we can ignore it later.
8170d56b959SPeter Collingbourne if (Sym.isCommon()) {
818fb8c2a4aSPeter Collingbourne // FIXME: We should figure out what to do about commons defined by asm.
819fb8c2a4aSPeter Collingbourne // For now they aren't reported correctly by ModuleSymbolTable.
820adcd0268SBenjamin Kramer auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
821dc4c8cf9SMehdi Amini CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
822f1255186SGuillaume Chatelet if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
823f1255186SGuillaume Chatelet const Align SymAlign(SymAlignValue);
824f1255186SGuillaume Chatelet CommonRes.Align = std::max(SymAlign, CommonRes.Align.valueOrOne());
825f1255186SGuillaume Chatelet }
826b2f46d1dSMehdi Amini CommonRes.Prevailing |= Res.Prevailing;
827dc4c8cf9SMehdi Amini }
8289ba95f99STeresa Johnson }
829b4a8c0ebSYuanfang Chen
830b247ffbaSTeresa Johnson if (!M.getComdatSymbolTable().empty())
831b247ffbaSTeresa Johnson for (GlobalValue &GV : M.global_values())
832b247ffbaSTeresa Johnson handleNonPrevailingComdat(GV, NonPrevailingComdats);
833b4a8c0ebSYuanfang Chen
834b4a8c0ebSYuanfang Chen // Prepend ".lto_discard <sym>, <sym>*" directive to each module inline asm
835b4a8c0ebSYuanfang Chen // block.
836b4a8c0ebSYuanfang Chen if (!M.getModuleInlineAsm().empty()) {
837b4a8c0ebSYuanfang Chen std::string NewIA = ".lto_discard";
838b4a8c0ebSYuanfang Chen if (!NonPrevailingAsmSymbols.empty()) {
839b4a8c0ebSYuanfang Chen // Don't dicard a symbol if there is a live .symver for it.
840b4a8c0ebSYuanfang Chen ModuleSymbolTable::CollectAsmSymvers(
841b4a8c0ebSYuanfang Chen M, [&](StringRef Name, StringRef Alias) {
842b4a8c0ebSYuanfang Chen if (!NonPrevailingAsmSymbols.count(Alias))
843b4a8c0ebSYuanfang Chen NonPrevailingAsmSymbols.erase(Name);
844b4a8c0ebSYuanfang Chen });
845b4a8c0ebSYuanfang Chen NewIA += " " + llvm::join(NonPrevailingAsmSymbols, ", ");
846b4a8c0ebSYuanfang Chen }
847b4a8c0ebSYuanfang Chen NewIA += "\n";
848b4a8c0ebSYuanfang Chen M.setModuleInlineAsm(NewIA + M.getModuleInlineAsm());
849b4a8c0ebSYuanfang Chen }
850b4a8c0ebSYuanfang Chen
8517b30f16cSPeter Collingbourne assert(MsymI == MsymE);
852c55cf4afSBill Wendling return std::move(Mod);
853dbd2fed6SPeter Collingbourne }
8549ba95f99STeresa Johnson
linkRegularLTO(RegularLTOState::AddedModule Mod,bool LivenessFromIndex)855dbd2fed6SPeter Collingbourne Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
856dbd2fed6SPeter Collingbourne bool LivenessFromIndex) {
857dbd2fed6SPeter Collingbourne std::vector<GlobalValue *> Keep;
858dbd2fed6SPeter Collingbourne for (GlobalValue *GV : Mod.Keep) {
85931ae0165SGabor Horvath if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
86031ae0165SGabor Horvath if (Function *F = dyn_cast<Function>(GV)) {
86132ab4057SXu Mingjie if (DiagnosticOutputFile) {
86232ab4057SXu Mingjie if (Error Err = F->materialize())
86332ab4057SXu Mingjie return Err;
864ae90df8eSWei Wang OptimizationRemarkEmitter ORE(F, nullptr);
86531ae0165SGabor Horvath ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
86631ae0165SGabor Horvath << ore::NV("Function", F)
86731ae0165SGabor Horvath << " not added to the combined module ");
86831ae0165SGabor Horvath }
86932ab4057SXu Mingjie }
870dbd2fed6SPeter Collingbourne continue;
87131ae0165SGabor Horvath }
872dbd2fed6SPeter Collingbourne
873dbd2fed6SPeter Collingbourne if (!GV->hasAvailableExternallyLinkage()) {
874dbd2fed6SPeter Collingbourne Keep.push_back(GV);
875dbd2fed6SPeter Collingbourne continue;
876dbd2fed6SPeter Collingbourne }
877dbd2fed6SPeter Collingbourne
878dbd2fed6SPeter Collingbourne // Only link available_externally definitions if we don't already have a
879dbd2fed6SPeter Collingbourne // definition.
880dbd2fed6SPeter Collingbourne GlobalValue *CombinedGV =
881dbd2fed6SPeter Collingbourne RegularLTO.CombinedModule->getNamedValue(GV->getName());
882dbd2fed6SPeter Collingbourne if (CombinedGV && !CombinedGV->isDeclaration())
883dbd2fed6SPeter Collingbourne continue;
884dbd2fed6SPeter Collingbourne
885dbd2fed6SPeter Collingbourne Keep.push_back(GV);
886dbd2fed6SPeter Collingbourne }
887dbd2fed6SPeter Collingbourne
888236695e7SNick Desaulniers return RegularLTO.Mover->move(std::move(Mod.M), Keep, nullptr,
889040cc168STeresa Johnson /* IsPerformingImport */ false);
8909ba95f99STeresa Johnson }
8919ba95f99STeresa Johnson
892dbd2fed6SPeter Collingbourne // Add a ThinLTO module to the link.
addThinLTO(BitcodeModule BM,ArrayRef<InputFile::Symbol> Syms,const SymbolResolution * & ResI,const SymbolResolution * ResE)893dbd2fed6SPeter Collingbourne Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
8941a0720e8SPeter Collingbourne const SymbolResolution *&ResI,
8951a0720e8SPeter Collingbourne const SymbolResolution *ResE) {
89674d22dd7SPeter Collingbourne if (Error Err =
897dbd2fed6SPeter Collingbourne BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
898dbd2fed6SPeter Collingbourne ThinLTO.ModuleMap.size()))
89974d22dd7SPeter Collingbourne return Err;
9009ba95f99STeresa Johnson
9011a0720e8SPeter Collingbourne for (const InputFile::Symbol &Sym : Syms) {
9021a0720e8SPeter Collingbourne assert(ResI != ResE);
9039ba95f99STeresa Johnson SymbolResolution Res = *ResI++;
9049ba95f99STeresa Johnson
9057b30f16cSPeter Collingbourne if (!Sym.getIRName().empty()) {
9067b30f16cSPeter Collingbourne auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
9077b30f16cSPeter Collingbourne Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
9084595a915SSean Fertile if (Res.Prevailing) {
9097b30f16cSPeter Collingbourne ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
9106a5fbe52SDavide Italiano
9116a5fbe52SDavide Italiano // For linker redefined symbols (via --wrap or --defsym) we want to
9126a5fbe52SDavide Italiano // switch the linkage to `weak` to prevent IPOs from happening.
9136a5fbe52SDavide Italiano // Find the summary in the module for this very GV and record the new
9146a5fbe52SDavide Italiano // linkage so that we can switch it when we import the GV.
9156a5fbe52SDavide Italiano if (Res.LinkerRedefined)
9166a5fbe52SDavide Italiano if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
9176a5fbe52SDavide Italiano GUID, BM.getModuleIdentifier()))
9186a5fbe52SDavide Italiano S->setLinkage(GlobalValue::WeakAnyLinkage);
9197b30f16cSPeter Collingbourne }
9204595a915SSean Fertile
9214595a915SSean Fertile // If the linker resolved the symbol to a local definition then mark it
9224595a915SSean Fertile // as local in the summary for the module we are adding.
9234595a915SSean Fertile if (Res.FinalDefinitionInLinkageUnit) {
9244595a915SSean Fertile if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
9254595a915SSean Fertile GUID, BM.getModuleIdentifier())) {
9264595a915SSean Fertile S->setDSOLocal(true);
9274595a915SSean Fertile }
9284595a915SSean Fertile }
9297b30f16cSPeter Collingbourne }
9309ba95f99STeresa Johnson }
9319ba95f99STeresa Johnson
9321a0720e8SPeter Collingbourne if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
9331a0720e8SPeter Collingbourne return make_error<StringError>(
9341a0720e8SPeter Collingbourne "Expected at most one ThinLTO module per bitcode file",
9351a0720e8SPeter Collingbourne inconvertibleErrorCode());
9361a0720e8SPeter Collingbourne
9372638aafeSHongtao Yu if (!Conf.ThinLTOModulesToCompile.empty()) {
9382638aafeSHongtao Yu if (!ThinLTO.ModulesToCompile)
9392638aafeSHongtao Yu ThinLTO.ModulesToCompile = ModuleMapType();
9402638aafeSHongtao Yu // This is a fuzzy name matching where only modules with name containing the
9412638aafeSHongtao Yu // specified switch values are going to be compiled.
9422638aafeSHongtao Yu for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
9432638aafeSHongtao Yu if (BM.getModuleIdentifier().contains(Name)) {
9442638aafeSHongtao Yu ThinLTO.ModulesToCompile->insert({BM.getModuleIdentifier(), BM});
9452638aafeSHongtao Yu llvm::errs() << "[ThinLTO] Selecting " << BM.getModuleIdentifier()
9462638aafeSHongtao Yu << " to compile\n";
9472638aafeSHongtao Yu }
9482638aafeSHongtao Yu }
9492638aafeSHongtao Yu }
9502638aafeSHongtao Yu
95141af4309SMehdi Amini return Error::success();
9529ba95f99STeresa Johnson }
9539ba95f99STeresa Johnson
getMaxTasks() const954faa7506fSTeresa Johnson unsigned LTO::getMaxTasks() const {
9559ba95f99STeresa Johnson CalledGetMaxTasks = true;
9562638aafeSHongtao Yu auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
9572638aafeSHongtao Yu : ThinLTO.ModuleMap.size();
9582638aafeSHongtao Yu return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
9599ba95f99STeresa Johnson }
9609ba95f99STeresa Johnson
961d0b1f30bSTeresa Johnson // If only some of the modules were split, we cannot correctly handle
962d0b1f30bSTeresa Johnson // code that contains type tests or type checked loads.
checkPartiallySplit()963d0b1f30bSTeresa Johnson Error LTO::checkPartiallySplit() {
964d0b1f30bSTeresa Johnson if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
965d0b1f30bSTeresa Johnson return Error::success();
966d0b1f30bSTeresa Johnson
967d0b1f30bSTeresa Johnson Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
968d0b1f30bSTeresa Johnson Intrinsic::getName(Intrinsic::type_test));
969d0b1f30bSTeresa Johnson Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
970d0b1f30bSTeresa Johnson Intrinsic::getName(Intrinsic::type_checked_load));
971d0b1f30bSTeresa Johnson
972d0b1f30bSTeresa Johnson // First check if there are type tests / type checked loads in the
973d0b1f30bSTeresa Johnson // merged regular LTO module IR.
974d0b1f30bSTeresa Johnson if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
975d0b1f30bSTeresa Johnson (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()))
976d0b1f30bSTeresa Johnson return make_error<StringError>(
977d0b1f30bSTeresa Johnson "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
978d0b1f30bSTeresa Johnson inconvertibleErrorCode());
979d0b1f30bSTeresa Johnson
980d0b1f30bSTeresa Johnson // Otherwise check if there are any recorded in the combined summary from the
981d0b1f30bSTeresa Johnson // ThinLTO modules.
982d0b1f30bSTeresa Johnson for (auto &P : ThinLTO.CombinedIndex) {
983d0b1f30bSTeresa Johnson for (auto &S : P.second.SummaryList) {
984d0b1f30bSTeresa Johnson auto *FS = dyn_cast<FunctionSummary>(S.get());
985d0b1f30bSTeresa Johnson if (!FS)
986d0b1f30bSTeresa Johnson continue;
987d0b1f30bSTeresa Johnson if (!FS->type_test_assume_vcalls().empty() ||
988d0b1f30bSTeresa Johnson !FS->type_checked_load_vcalls().empty() ||
989d0b1f30bSTeresa Johnson !FS->type_test_assume_const_vcalls().empty() ||
990d0b1f30bSTeresa Johnson !FS->type_checked_load_const_vcalls().empty() ||
991d0b1f30bSTeresa Johnson !FS->type_tests().empty())
992d0b1f30bSTeresa Johnson return make_error<StringError>(
993d0b1f30bSTeresa Johnson "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
994d0b1f30bSTeresa Johnson inconvertibleErrorCode());
995d0b1f30bSTeresa Johnson }
996d0b1f30bSTeresa Johnson }
997d0b1f30bSTeresa Johnson return Error::success();
998d0b1f30bSTeresa Johnson }
999d0b1f30bSTeresa Johnson
run(AddStreamFn AddStream,FileCache Cache)1000d788c44fSNoah Shutty Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
1001659b3bc7SEvgeniy Stepanov // Compute "dead" symbols, we don't want to import/export these!
1002659b3bc7SEvgeniy Stepanov DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1003eaf5172cSGeorge Rimar DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
1004eaf5172cSGeorge Rimar for (auto &Res : GlobalResolutions) {
1005eaf5172cSGeorge Rimar // Normally resolution have IR name of symbol. We can do nothing here
1006eaf5172cSGeorge Rimar // otherwise. See comments in GlobalResolution struct for more details.
1007eaf5172cSGeorge Rimar if (Res.second.IRName.empty())
1008eaf5172cSGeorge Rimar continue;
1009eaf5172cSGeorge Rimar
1010eaf5172cSGeorge Rimar GlobalValue::GUID GUID = GlobalValue::getGUID(
1011eaf5172cSGeorge Rimar GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1012eaf5172cSGeorge Rimar
1013d328365bSGeorge Rimar if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
10146b9df910SFangrui Song GUIDPreservedSymbols.insert(GUID);
1015659b3bc7SEvgeniy Stepanov
10161487747eSTeresa Johnson if (Res.second.ExportDynamic)
10171487747eSTeresa Johnson DynamicExportSymbols.insert(GUID);
10181487747eSTeresa Johnson
1019eaf5172cSGeorge Rimar GUIDPrevailingResolutions[GUID] =
1020eaf5172cSGeorge Rimar Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
1021eaf5172cSGeorge Rimar }
1022eaf5172cSGeorge Rimar
1023eaf5172cSGeorge Rimar auto isPrevailing = [&](GlobalValue::GUID G) {
1024eaf5172cSGeorge Rimar auto It = GUIDPrevailingResolutions.find(G);
1025eaf5172cSGeorge Rimar if (It == GUIDPrevailingResolutions.end())
1026eaf5172cSGeorge Rimar return PrevailingType::Unknown;
1027eaf5172cSGeorge Rimar return It->second;
1028eaf5172cSGeorge Rimar };
1029bf46e741SEugene Leviant computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
1030bf46e741SEugene Leviant isPrevailing, Conf.OptLevel > 0);
1031659b3bc7SEvgeniy Stepanov
1032d4332eb3SFlorian Hahn // Setup output file to emit statistics.
1033b340497fSFlorian Hahn auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
1034b340497fSFlorian Hahn if (!StatsFileOrErr)
1035b340497fSFlorian Hahn return StatsFileOrErr.takeError();
1036b340497fSFlorian Hahn std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1037d4332eb3SFlorian Hahn
1038d4332eb3SFlorian Hahn Error Result = runRegularLTO(AddStream);
1039d4332eb3SFlorian Hahn if (!Result)
104037b80122STeresa Johnson Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1041d4332eb3SFlorian Hahn
1042d4332eb3SFlorian Hahn if (StatsFile)
1043d4332eb3SFlorian Hahn PrintStatisticsJSON(StatsFile->os());
1044d4332eb3SFlorian Hahn
1045d4332eb3SFlorian Hahn return Result;
10469ba95f99STeresa Johnson }
10479ba95f99STeresa Johnson
runRegularLTO(AddStreamFn AddStream)104880186a57SPeter Collingbourne Error LTO::runRegularLTO(AddStreamFn AddStream) {
104931ae0165SGabor Horvath // Setup optimization remarks.
10507531a503SFrancis Visoiu Mistrih auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
105131ae0165SGabor Horvath RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename,
10523acda917SWei Wang Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness,
10533acda917SWei Wang Conf.RemarksHotnessThreshold);
105431ae0165SGabor Horvath if (!DiagFileOrErr)
105531ae0165SGabor Horvath return DiagFileOrErr.takeError();
105632ab4057SXu Mingjie DiagnosticOutputFile = std::move(*DiagFileOrErr);
105731ae0165SGabor Horvath
105831ae0165SGabor Horvath // Finalize linking of regular LTO modules containing summaries now that
105931ae0165SGabor Horvath // we have computed liveness information.
106031ae0165SGabor Horvath for (auto &M : RegularLTO.ModsWithSummaries)
106131ae0165SGabor Horvath if (Error Err = linkRegularLTO(std::move(M),
106231ae0165SGabor Horvath /*LivenessFromIndex=*/true))
106331ae0165SGabor Horvath return Err;
106431ae0165SGabor Horvath
106531ae0165SGabor Horvath // Ensure we don't have inconsistently split LTO units with type tests.
106631ae0165SGabor Horvath // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
106731ae0165SGabor Horvath // this path both cases but eventually this should be split into two and
106831ae0165SGabor Horvath // do the ThinLTO checks in `runThinLTO`.
106931ae0165SGabor Horvath if (Error Err = checkPartiallySplit())
107031ae0165SGabor Horvath return Err;
107131ae0165SGabor Horvath
1072dc4c8cf9SMehdi Amini // Make sure commons have the right size/alignment: we kept the largest from
1073dc4c8cf9SMehdi Amini // all the prevailing when adding the inputs, and we apply it here.
1074e2e621a3STeresa Johnson const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
1075dc4c8cf9SMehdi Amini for (auto &I : RegularLTO.Commons) {
1076b2f46d1dSMehdi Amini if (!I.second.Prevailing)
1077b2f46d1dSMehdi Amini // Don't do anything if no instance of this common was prevailing.
1078b2f46d1dSMehdi Amini continue;
1079dc4c8cf9SMehdi Amini GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
1080e2e621a3STeresa Johnson if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
1081dc4c8cf9SMehdi Amini // Don't create a new global if the type is already correct, just make
1082dc4c8cf9SMehdi Amini // sure the alignment is correct.
1083dc4c8cf9SMehdi Amini OldGV->setAlignment(I.second.Align);
1084dc4c8cf9SMehdi Amini continue;
1085dc4c8cf9SMehdi Amini }
1086e2e621a3STeresa Johnson ArrayType *Ty =
1087e2e621a3STeresa Johnson ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
1088dc4c8cf9SMehdi Amini auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
1089dc4c8cf9SMehdi Amini GlobalValue::CommonLinkage,
1090dc4c8cf9SMehdi Amini ConstantAggregateZero::get(Ty), "");
1091dc4c8cf9SMehdi Amini GV->setAlignment(I.second.Align);
1092dc4c8cf9SMehdi Amini if (OldGV) {
1093dc4c8cf9SMehdi Amini OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
1094dc4c8cf9SMehdi Amini GV->takeName(OldGV);
1095dc4c8cf9SMehdi Amini OldGV->eraseFromParent();
1096dc4c8cf9SMehdi Amini } else {
1097dc4c8cf9SMehdi Amini GV->setName(I.first);
1098dc4c8cf9SMehdi Amini }
1099dc4c8cf9SMehdi Amini }
1100dc4c8cf9SMehdi Amini
11012f63d549STeresa Johnson // If allowed, upgrade public vcall visibility metadata to linkage unit
11022f63d549STeresa Johnson // visibility before whole program devirtualization in the optimizer.
11032f63d549STeresa Johnson updateVCallVisibilityInModule(*RegularLTO.CombinedModule,
11041487747eSTeresa Johnson Conf.HasWholeProgramVisibility,
11051487747eSTeresa Johnson DynamicExportSymbols);
1106*2eade1dbSArthur Eubanks updatePublicTypeTestCalls(*RegularLTO.CombinedModule,
1107*2eade1dbSArthur Eubanks Conf.HasWholeProgramVisibility);
11082f63d549STeresa Johnson
11099ba95f99STeresa Johnson if (Conf.PreOptModuleHook &&
11109ba95f99STeresa Johnson !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1111cb63ad8dSXu Mingjie return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
11129ba95f99STeresa Johnson
1113d310b47cSMehdi Amini if (!Conf.CodeGenOnly) {
11149ba95f99STeresa Johnson for (const auto &R : GlobalResolutions) {
1115eaf5172cSGeorge Rimar if (!R.second.isPrevailingIRSymbol())
11169ba95f99STeresa Johnson continue;
11179ba95f99STeresa Johnson if (R.second.Partition != 0 &&
11189ba95f99STeresa Johnson R.second.Partition != GlobalResolution::External)
11199ba95f99STeresa Johnson continue;
11209ba95f99STeresa Johnson
1121d310b47cSMehdi Amini GlobalValue *GV =
1122d310b47cSMehdi Amini RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
11239ba95f99STeresa Johnson // Ignore symbols defined in other partitions.
1124eae4742dSBob Haarman // Also skip declarations, which are not allowed to have internal linkage.
1125eae4742dSBob Haarman if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
11269ba95f99STeresa Johnson continue;
11279ba95f99STeresa Johnson GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
11289ba95f99STeresa Johnson : GlobalValue::UnnamedAddr::None);
11297ca74448SXin Tong if (EnableLTOInternalization && R.second.Partition == 0)
11309ba95f99STeresa Johnson GV->setLinkage(GlobalValue::InternalLinkage);
11319ba95f99STeresa Johnson }
11329ba95f99STeresa Johnson
11333b598b9cSOliver Stannard RegularLTO.CombinedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
11343b598b9cSOliver Stannard
11359ba95f99STeresa Johnson if (Conf.PostInternalizeModuleHook &&
11369ba95f99STeresa Johnson !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1137cb63ad8dSXu Mingjie return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1138d310b47cSMehdi Amini }
1139ad5fad0aSZakk Chen
1140ad5fad0aSZakk Chen if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1141f3a710caSFlorian Hahn if (Error Err =
1142f3a710caSFlorian Hahn backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1143f3a710caSFlorian Hahn *RegularLTO.CombinedModule, ThinLTO.CombinedIndex))
114431ae0165SGabor Horvath return Err;
1145ad5fad0aSZakk Chen }
114631ae0165SGabor Horvath
114732ab4057SXu Mingjie return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
11489ba95f99STeresa Johnson }
11499ba95f99STeresa Johnson
115034d80461SSteven Wu static const char *libcallRoutineNames[] = {
115134d80461SSteven Wu #define HANDLE_LIBCALL(code, name) name,
115234d80461SSteven Wu #include "llvm/IR/RuntimeLibcalls.def"
115334d80461SSteven Wu #undef HANDLE_LIBCALL
115434d80461SSteven Wu };
115534d80461SSteven Wu
getRuntimeLibcallSymbols()115634d80461SSteven Wu ArrayRef<const char*> LTO::getRuntimeLibcallSymbols() {
115734d80461SSteven Wu return makeArrayRef(libcallRoutineNames);
115834d80461SSteven Wu }
115934d80461SSteven Wu
11609ba95f99STeresa Johnson /// This class defines the interface to the ThinLTO backend.
11619ba95f99STeresa Johnson class lto::ThinBackendProc {
11629ba95f99STeresa Johnson protected:
1163d0aad9f5STeresa Johnson const Config &Conf;
11649ba95f99STeresa Johnson ModuleSummaryIndex &CombinedIndex;
1165767e1457SMehdi Amini const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
116622f12733SJin Xin Ng lto::IndexWriteCallback OnWrite;
116722f12733SJin Xin Ng bool ShouldEmitImportsFiles;
11689ba95f99STeresa Johnson
11699ba95f99STeresa Johnson public:
ThinBackendProc(const Config & Conf,ModuleSummaryIndex & CombinedIndex,const StringMap<GVSummaryMapTy> & ModuleToDefinedGVSummaries,lto::IndexWriteCallback OnWrite,bool ShouldEmitImportsFiles)1170d0aad9f5STeresa Johnson ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex,
117122f12733SJin Xin Ng const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
117222f12733SJin Xin Ng lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles)
117318b91112SMehdi Amini : Conf(Conf), CombinedIndex(CombinedIndex),
117422f12733SJin Xin Ng ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries),
117522f12733SJin Xin Ng OnWrite(OnWrite), ShouldEmitImportsFiles(ShouldEmitImportsFiles) {}
11769ba95f99STeresa Johnson
11773a3cb929SKazu Hirata virtual ~ThinBackendProc() = default;
1178adc0e26bSMehdi Amini virtual Error start(
11791a0720e8SPeter Collingbourne unsigned Task, BitcodeModule BM,
1180cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ImportList,
1181adc0e26bSMehdi Amini const FunctionImporter::ExportSetTy &ExportList,
1182adc0e26bSMehdi Amini const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
11831a0720e8SPeter Collingbourne MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
11849ba95f99STeresa Johnson virtual Error wait() = 0;
1185617d64f6SAlexandre Ganea virtual unsigned getThreadCount() = 0;
118622f12733SJin Xin Ng
118722f12733SJin Xin Ng // Write sharded indices and (optionally) imports to disk
emitFiles(const FunctionImporter::ImportMapTy & ImportList,llvm::StringRef ModulePath,const std::string & NewModulePath)118822f12733SJin Xin Ng Error emitFiles(const FunctionImporter::ImportMapTy &ImportList,
118922f12733SJin Xin Ng llvm::StringRef ModulePath,
119022f12733SJin Xin Ng const std::string &NewModulePath) {
119122f12733SJin Xin Ng std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
119222f12733SJin Xin Ng std::error_code EC;
119322f12733SJin Xin Ng gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
119422f12733SJin Xin Ng ImportList, ModuleToSummariesForIndex);
119522f12733SJin Xin Ng
119622f12733SJin Xin Ng raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
119722f12733SJin Xin Ng sys::fs::OpenFlags::OF_None);
119822f12733SJin Xin Ng if (EC)
119922f12733SJin Xin Ng return errorCodeToError(EC);
120022f12733SJin Xin Ng writeIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
120122f12733SJin Xin Ng
120222f12733SJin Xin Ng if (ShouldEmitImportsFiles) {
120322f12733SJin Xin Ng EC = EmitImportsFiles(ModulePath, NewModulePath + ".imports",
120422f12733SJin Xin Ng ModuleToSummariesForIndex);
120522f12733SJin Xin Ng if (EC)
120622f12733SJin Xin Ng return errorCodeToError(EC);
120722f12733SJin Xin Ng }
120822f12733SJin Xin Ng return Error::success();
120922f12733SJin Xin Ng }
12109ba95f99STeresa Johnson };
12119ba95f99STeresa Johnson
1212ffd3715dSBenjamin Kramer namespace {
12139ba95f99STeresa Johnson class InProcessThinBackend : public ThinBackendProc {
12149ba95f99STeresa Johnson ThreadPool BackendThreadPool;
121580186a57SPeter Collingbourne AddStreamFn AddStream;
1216d788c44fSNoah Shutty FileCache Cache;
12173427d17cSEvgeniy Stepanov std::set<GlobalValue::GUID> CfiFunctionDefs;
12183427d17cSEvgeniy Stepanov std::set<GlobalValue::GUID> CfiFunctionDecls;
12199ba95f99STeresa Johnson
12209ba95f99STeresa Johnson Optional<Error> Err;
12219ba95f99STeresa Johnson std::mutex ErrMu;
12229ba95f99STeresa Johnson
122322f12733SJin Xin Ng bool ShouldEmitIndexFiles;
122422f12733SJin Xin Ng
12259ba95f99STeresa Johnson public:
InProcessThinBackend(const Config & Conf,ModuleSummaryIndex & CombinedIndex,ThreadPoolStrategy ThinLTOParallelism,const StringMap<GVSummaryMapTy> & ModuleToDefinedGVSummaries,AddStreamFn AddStream,FileCache Cache,lto::IndexWriteCallback OnWrite,bool ShouldEmitIndexFiles,bool ShouldEmitImportsFiles)1226767e1457SMehdi Amini InProcessThinBackend(
1227d0aad9f5STeresa Johnson const Config &Conf, ModuleSummaryIndex &CombinedIndex,
122809158252SAlexandre Ganea ThreadPoolStrategy ThinLTOParallelism,
1229767e1457SMehdi Amini const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
123022f12733SJin Xin Ng AddStreamFn AddStream, FileCache Cache, lto::IndexWriteCallback OnWrite,
123122f12733SJin Xin Ng bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles)
123222f12733SJin Xin Ng : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
123322f12733SJin Xin Ng OnWrite, ShouldEmitImportsFiles),
123409158252SAlexandre Ganea BackendThreadPool(ThinLTOParallelism), AddStream(std::move(AddStream)),
123522f12733SJin Xin Ng Cache(std::move(Cache)), ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
12363427d17cSEvgeniy Stepanov for (auto &Name : CombinedIndex.cfiFunctionDefs())
12373427d17cSEvgeniy Stepanov CfiFunctionDefs.insert(
12383427d17cSEvgeniy Stepanov GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
12393427d17cSEvgeniy Stepanov for (auto &Name : CombinedIndex.cfiFunctionDecls())
12403427d17cSEvgeniy Stepanov CfiFunctionDecls.insert(
12413427d17cSEvgeniy Stepanov GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1242780a4dd3SPeter Collingbourne }
12439ba95f99STeresa Johnson
runThinLTOBackendThread(AddStreamFn AddStream,FileCache Cache,unsigned Task,BitcodeModule BM,ModuleSummaryIndex & CombinedIndex,const FunctionImporter::ImportMapTy & ImportList,const FunctionImporter::ExportSetTy & ExportList,const std::map<GlobalValue::GUID,GlobalValue::LinkageTypes> & ResolvedODR,const GVSummaryMapTy & DefinedGlobals,MapVector<StringRef,BitcodeModule> & ModuleMap)1244adc0e26bSMehdi Amini Error runThinLTOBackendThread(
1245d788c44fSNoah Shutty AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1246d788c44fSNoah Shutty ModuleSummaryIndex &CombinedIndex,
12479ba95f99STeresa Johnson const FunctionImporter::ImportMapTy &ImportList,
1248adc0e26bSMehdi Amini const FunctionImporter::ExportSetTy &ExportList,
1249adc0e26bSMehdi Amini const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
12509ba95f99STeresa Johnson const GVSummaryMapTy &DefinedGlobals,
12517fb39dfaSTeresa Johnson MapVector<StringRef, BitcodeModule> &ModuleMap) {
125280186a57SPeter Collingbourne auto RunThinBackend = [&](AddStreamFn AddStream) {
1253adc0e26bSMehdi Amini LTOLLVMContext BackendContext(Conf);
12541a0720e8SPeter Collingbourne Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1255d9445c49SPeter Collingbourne if (!MOrErr)
1256d9445c49SPeter Collingbourne return MOrErr.takeError();
12579ba95f99STeresa Johnson
125880186a57SPeter Collingbourne return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1259d535a05cSWei Mi ImportList, DefinedGlobals, &ModuleMap);
126080186a57SPeter Collingbourne };
126180186a57SPeter Collingbourne
12621a0720e8SPeter Collingbourne auto ModuleID = BM.getModuleIdentifier();
1263f82bda0aSMehdi Amini
126422f12733SJin Xin Ng if (ShouldEmitIndexFiles) {
126522f12733SJin Xin Ng if (auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
126622f12733SJin Xin Ng return E;
126722f12733SJin Xin Ng }
126822f12733SJin Xin Ng
1269f82bda0aSMehdi Amini if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
1270f82bda0aSMehdi Amini all_of(CombinedIndex.getModuleHash(ModuleID),
1271f82bda0aSMehdi Amini [](uint32_t V) { return V == 0; }))
1272f82bda0aSMehdi Amini // Cache disabled or no entry for this module in the combined index or
1273f82bda0aSMehdi Amini // no module hash.
127480186a57SPeter Collingbourne return RunThinBackend(AddStream);
127580186a57SPeter Collingbourne
127680186a57SPeter Collingbourne SmallString<40> Key;
127780186a57SPeter Collingbourne // The module may be cached, this helps handling it.
12785f312ad4STeresa Johnson computeLTOCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList,
12795f312ad4STeresa Johnson ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
12807fb39dfaSTeresa Johnson CfiFunctionDecls);
1281d788c44fSNoah Shutty Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key);
1282d788c44fSNoah Shutty if (Error Err = CacheAddStreamOrErr.takeError())
1283d788c44fSNoah Shutty return Err;
1284d788c44fSNoah Shutty AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1285d788c44fSNoah Shutty if (CacheAddStream)
128680186a57SPeter Collingbourne return RunThinBackend(CacheAddStream);
128780186a57SPeter Collingbourne
128841af4309SMehdi Amini return Error::success();
12899ba95f99STeresa Johnson }
12909ba95f99STeresa Johnson
start(unsigned Task,BitcodeModule BM,const FunctionImporter::ImportMapTy & ImportList,const FunctionImporter::ExportSetTy & ExportList,const std::map<GlobalValue::GUID,GlobalValue::LinkageTypes> & ResolvedODR,MapVector<StringRef,BitcodeModule> & ModuleMap)1291adc0e26bSMehdi Amini Error start(
12921a0720e8SPeter Collingbourne unsigned Task, BitcodeModule BM,
1293cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ImportList,
1294adc0e26bSMehdi Amini const FunctionImporter::ExportSetTy &ExportList,
1295adc0e26bSMehdi Amini const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
12961a0720e8SPeter Collingbourne MapVector<StringRef, BitcodeModule> &ModuleMap) override {
12971a0720e8SPeter Collingbourne StringRef ModulePath = BM.getModuleIdentifier();
1298767e1457SMehdi Amini assert(ModuleToDefinedGVSummaries.count(ModulePath));
1299767e1457SMehdi Amini const GVSummaryMapTy &DefinedGlobals =
1300767e1457SMehdi Amini ModuleToDefinedGVSummaries.find(ModulePath)->second;
13019ba95f99STeresa Johnson BackendThreadPool.async(
13021a0720e8SPeter Collingbourne [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
13039ba95f99STeresa Johnson const FunctionImporter::ImportMapTy &ImportList,
1304adc0e26bSMehdi Amini const FunctionImporter::ExportSetTy &ExportList,
1305adc0e26bSMehdi Amini const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1306adc0e26bSMehdi Amini &ResolvedODR,
1307767e1457SMehdi Amini const GVSummaryMapTy &DefinedGlobals,
13087fb39dfaSTeresa Johnson MapVector<StringRef, BitcodeModule> &ModuleMap) {
1309e7cb3744SRussell Gallop if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1310e7cb3744SRussell Gallop timeTraceProfilerInitialize(Conf.TimeTraceGranularity,
1311e7cb3744SRussell Gallop "thin backend");
1312adc0e26bSMehdi Amini Error E = runThinLTOBackendThread(
1313780a4dd3SPeter Collingbourne AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
13147fb39dfaSTeresa Johnson ResolvedODR, DefinedGlobals, ModuleMap);
13159ba95f99STeresa Johnson if (E) {
13169ba95f99STeresa Johnson std::unique_lock<std::mutex> L(ErrMu);
13179ba95f99STeresa Johnson if (Err)
13189ba95f99STeresa Johnson Err = joinErrors(std::move(*Err), std::move(E));
13199ba95f99STeresa Johnson else
13209ba95f99STeresa Johnson Err = std::move(E);
13219ba95f99STeresa Johnson }
1322e7cb3744SRussell Gallop if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1323e7cb3744SRussell Gallop timeTraceProfilerFinishThread();
13249ba95f99STeresa Johnson },
1325780a4dd3SPeter Collingbourne BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
13267fb39dfaSTeresa Johnson std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
132722f12733SJin Xin Ng
132822f12733SJin Xin Ng if (OnWrite)
132922f12733SJin Xin Ng OnWrite(std::string(ModulePath));
133041af4309SMehdi Amini return Error::success();
13319ba95f99STeresa Johnson }
13329ba95f99STeresa Johnson
wait()13339ba95f99STeresa Johnson Error wait() override {
13349ba95f99STeresa Johnson BackendThreadPool.wait();
13359ba95f99STeresa Johnson if (Err)
13369ba95f99STeresa Johnson return std::move(*Err);
13379ba95f99STeresa Johnson else
133841af4309SMehdi Amini return Error::success();
13399ba95f99STeresa Johnson }
1340617d64f6SAlexandre Ganea
getThreadCount()1341617d64f6SAlexandre Ganea unsigned getThreadCount() override {
1342617d64f6SAlexandre Ganea return BackendThreadPool.getThreadCount();
1343617d64f6SAlexandre Ganea }
13449ba95f99STeresa Johnson };
1345ffd3715dSBenjamin Kramer } // end anonymous namespace
13469ba95f99STeresa Johnson
createInProcessThinBackend(ThreadPoolStrategy Parallelism,lto::IndexWriteCallback OnWrite,bool ShouldEmitIndexFiles,bool ShouldEmitImportsFiles)134722f12733SJin Xin Ng ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism,
134822f12733SJin Xin Ng lto::IndexWriteCallback OnWrite,
134922f12733SJin Xin Ng bool ShouldEmitIndexFiles,
135022f12733SJin Xin Ng bool ShouldEmitImportsFiles) {
1351d0aad9f5STeresa Johnson return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1352767e1457SMehdi Amini const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1353d788c44fSNoah Shutty AddStreamFn AddStream, FileCache Cache) {
13540eaee545SJonas Devlieghere return std::make_unique<InProcessThinBackend>(
135509158252SAlexandre Ganea Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries, AddStream,
135622f12733SJin Xin Ng Cache, OnWrite, ShouldEmitIndexFiles, ShouldEmitImportsFiles);
13579ba95f99STeresa Johnson };
13589ba95f99STeresa Johnson }
13599ba95f99STeresa Johnson
13603f212b89STeresa Johnson // Given the original \p Path to an output file, replace any path
13613f212b89STeresa Johnson // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
13623f212b89STeresa Johnson // resulting directory if it does not yet exist.
getThinLTOOutputFile(const std::string & Path,const std::string & OldPrefix,const std::string & NewPrefix)13633f212b89STeresa Johnson std::string lto::getThinLTOOutputFile(const std::string &Path,
13643f212b89STeresa Johnson const std::string &OldPrefix,
13653f212b89STeresa Johnson const std::string &NewPrefix) {
13663f212b89STeresa Johnson if (OldPrefix.empty() && NewPrefix.empty())
13673f212b89STeresa Johnson return Path;
13683f212b89STeresa Johnson SmallString<128> NewPath(Path);
13693f212b89STeresa Johnson llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
13703f212b89STeresa Johnson StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
13713f212b89STeresa Johnson if (!ParentPath.empty()) {
13723f212b89STeresa Johnson // Make sure the new directory exists, creating it if necessary.
13733f212b89STeresa Johnson if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
13743f212b89STeresa Johnson llvm::errs() << "warning: could not create directory '" << ParentPath
13753f212b89STeresa Johnson << "': " << EC.message() << '\n';
13763f212b89STeresa Johnson }
1377adcd0268SBenjamin Kramer return std::string(NewPath.str());
13783f212b89STeresa Johnson }
13793f212b89STeresa Johnson
1380ffd3715dSBenjamin Kramer namespace {
13819ba95f99STeresa Johnson class WriteIndexesThinBackend : public ThinBackendProc {
13829ba95f99STeresa Johnson std::string OldPrefix, NewPrefix;
1383a139b69eSVitaly Buka raw_fd_ostream *LinkedObjectsFile;
138459baf73aSVitaly Buka
13859ba95f99STeresa Johnson public:
WriteIndexesThinBackend(const Config & Conf,ModuleSummaryIndex & CombinedIndex,const StringMap<GVSummaryMapTy> & ModuleToDefinedGVSummaries,std::string OldPrefix,std::string NewPrefix,bool ShouldEmitImportsFiles,raw_fd_ostream * LinkedObjectsFile,lto::IndexWriteCallback OnWrite)1386767e1457SMehdi Amini WriteIndexesThinBackend(
1387d0aad9f5STeresa Johnson const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1388767e1457SMehdi Amini const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1389767e1457SMehdi Amini std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
1390a139b69eSVitaly Buka raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
139122f12733SJin Xin Ng : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
139222f12733SJin Xin Ng OnWrite, ShouldEmitImportsFiles),
13939ba95f99STeresa Johnson OldPrefix(OldPrefix), NewPrefix(NewPrefix),
139422f12733SJin Xin Ng LinkedObjectsFile(LinkedObjectsFile) {}
13959ba95f99STeresa Johnson
start(unsigned Task,BitcodeModule BM,const FunctionImporter::ImportMapTy & ImportList,const FunctionImporter::ExportSetTy & ExportList,const std::map<GlobalValue::GUID,GlobalValue::LinkageTypes> & ResolvedODR,MapVector<StringRef,BitcodeModule> & ModuleMap)1396adc0e26bSMehdi Amini Error start(
13971a0720e8SPeter Collingbourne unsigned Task, BitcodeModule BM,
1398cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ImportList,
1399adc0e26bSMehdi Amini const FunctionImporter::ExportSetTy &ExportList,
1400adc0e26bSMehdi Amini const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
14011a0720e8SPeter Collingbourne MapVector<StringRef, BitcodeModule> &ModuleMap) override {
14021a0720e8SPeter Collingbourne StringRef ModulePath = BM.getModuleIdentifier();
14039ba95f99STeresa Johnson std::string NewModulePath =
1404adcd0268SBenjamin Kramer getThinLTOOutputFile(std::string(ModulePath), OldPrefix, NewPrefix);
14059ba95f99STeresa Johnson
1406a139b69eSVitaly Buka if (LinkedObjectsFile)
14079ba95f99STeresa Johnson *LinkedObjectsFile << NewModulePath << '\n';
14089ba95f99STeresa Johnson
140922f12733SJin Xin Ng if (auto E = emitFiles(ImportList, ModulePath, NewModulePath))
141022f12733SJin Xin Ng return E;
141159baf73aSVitaly Buka
141259baf73aSVitaly Buka if (OnWrite)
1413adcd0268SBenjamin Kramer OnWrite(std::string(ModulePath));
141441af4309SMehdi Amini return Error::success();
14159ba95f99STeresa Johnson }
14169ba95f99STeresa Johnson
wait()141741af4309SMehdi Amini Error wait() override { return Error::success(); }
1418617d64f6SAlexandre Ganea
1419617d64f6SAlexandre Ganea // WriteIndexesThinBackend should always return 1 to prevent module
1420617d64f6SAlexandre Ganea // re-ordering and avoid non-determinism in the final link.
getThreadCount()1421617d64f6SAlexandre Ganea unsigned getThreadCount() override { return 1; }
14229ba95f99STeresa Johnson };
1423ffd3715dSBenjamin Kramer } // end anonymous namespace
14249ba95f99STeresa Johnson
createWriteIndexesThinBackend(std::string OldPrefix,std::string NewPrefix,bool ShouldEmitImportsFiles,raw_fd_ostream * LinkedObjectsFile,IndexWriteCallback OnWrite)1425a139b69eSVitaly Buka ThinBackend lto::createWriteIndexesThinBackend(
1426a139b69eSVitaly Buka std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
1427a139b69eSVitaly Buka raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite) {
1428d0aad9f5STeresa Johnson return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1429767e1457SMehdi Amini const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1430d788c44fSNoah Shutty AddStreamFn AddStream, FileCache Cache) {
14310eaee545SJonas Devlieghere return std::make_unique<WriteIndexesThinBackend>(
143218b91112SMehdi Amini Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
143359baf73aSVitaly Buka ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
14349ba95f99STeresa Johnson };
14359ba95f99STeresa Johnson }
14369ba95f99STeresa Johnson
runThinLTO(AddStreamFn AddStream,FileCache Cache,const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols)1437d788c44fSNoah Shutty Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache,
143837b80122STeresa Johnson const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
1439f5b8a312Smodimo timeTraceProfilerBegin("ThinLink", StringRef(""));
1440f5b8a312Smodimo auto TimeTraceScopeExit = llvm::make_scope_exit([]() {
1441f5b8a312Smodimo if (llvm::timeTraceProfilerEnabled())
1442f5b8a312Smodimo llvm::timeTraceProfilerEnd();
1443f5b8a312Smodimo });
14449ba95f99STeresa Johnson if (ThinLTO.ModuleMap.empty())
144541af4309SMehdi Amini return Error::success();
14469ba95f99STeresa Johnson
14472638aafeSHongtao Yu if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
14482638aafeSHongtao Yu llvm::errs() << "warning: [ThinLTO] No module compiled\n";
14492638aafeSHongtao Yu return Error::success();
14502638aafeSHongtao Yu }
14512638aafeSHongtao Yu
1452ad364956Sevgeny if (Conf.CombinedIndexHook &&
1453ad364956Sevgeny !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
145441af4309SMehdi Amini return Error::success();
14559ba95f99STeresa Johnson
14569ba95f99STeresa Johnson // Collect for each module the list of function it defines (GUID ->
14579ba95f99STeresa Johnson // Summary).
14585d96ee4fSDehao Chen StringMap<GVSummaryMapTy>
14599ba95f99STeresa Johnson ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
14609ba95f99STeresa Johnson ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
14619ba95f99STeresa Johnson ModuleToDefinedGVSummaries);
1462620c140aSTeresa Johnson // Create entries for any modules that didn't have any GV summaries
1463620c140aSTeresa Johnson // (either they didn't have any GVs to start with, or we suppressed
1464620c140aSTeresa Johnson // generation of the summaries because they e.g. had inline assembly
1465620c140aSTeresa Johnson // uses that couldn't be promoted/renamed on export). This is so
1466620c140aSTeresa Johnson // InProcessThinBackend::start can still launch a backend thread, which
1467620c140aSTeresa Johnson // is passed the map of summaries for the module, without any special
1468620c140aSTeresa Johnson // handling for this case.
1469620c140aSTeresa Johnson for (auto &Mod : ThinLTO.ModuleMap)
1470620c140aSTeresa Johnson if (!ModuleToDefinedGVSummaries.count(Mod.first))
1471620c140aSTeresa Johnson ModuleToDefinedGVSummaries.try_emplace(Mod.first);
14729ba95f99STeresa Johnson
14735a7056faSEaswaran Raman // Synthesize entry counts for functions in the CombinedIndex.
14745a7056faSEaswaran Raman computeSyntheticCounts(ThinLTO.CombinedIndex);
14755a7056faSEaswaran Raman
1476f39ce994SMehdi Amini StringMap<FunctionImporter::ImportMapTy> ImportLists(
1477f39ce994SMehdi Amini ThinLTO.ModuleMap.size());
1478f39ce994SMehdi Amini StringMap<FunctionImporter::ExportSetTy> ExportLists(
1479f39ce994SMehdi Amini ThinLTO.ModuleMap.size());
1480f39ce994SMehdi Amini StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1481f39ce994SMehdi Amini
1482b040fcc6SCharles Saternos if (DumpThinCGSCCs)
1483b040fcc6SCharles Saternos ThinLTO.CombinedIndex.dumpSCCs(outs());
1484b040fcc6SCharles Saternos
1485d2df54e6STeresa Johnson std::set<GlobalValue::GUID> ExportedGUIDs;
1486d2df54e6STeresa Johnson
1487*2eade1dbSArthur Eubanks if (hasWholeProgramVisibility(Conf.HasWholeProgramVisibility))
1488*2eade1dbSArthur Eubanks ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
14892f63d549STeresa Johnson // If allowed, upgrade public vcall visibility to linkage unit visibility in
14902f63d549STeresa Johnson // the summaries before whole program devirtualization below.
14912f63d549STeresa Johnson updateVCallVisibilityInIndex(ThinLTO.CombinedIndex,
14921487747eSTeresa Johnson Conf.HasWholeProgramVisibility,
14931487747eSTeresa Johnson DynamicExportSymbols);
14942f63d549STeresa Johnson
1495d2df54e6STeresa Johnson // Perform index-based WPD. This will return immediately if there are
1496d2df54e6STeresa Johnson // no index entries in the typeIdMetadata map (e.g. if we are instead
1497d2df54e6STeresa Johnson // performing IR-based WPD in hybrid regular/thin LTO mode).
1498d2df54e6STeresa Johnson std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1499d2df54e6STeresa Johnson runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
1500d2df54e6STeresa Johnson LocalWPDTargetsMap);
1501d2df54e6STeresa Johnson
15029fb6e1a0SPeter Collingbourne if (Conf.OptLevel > 0)
15039ba95f99STeresa Johnson ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
150456584bbfSEvgeniy Stepanov ImportLists, ExportLists);
15059ba95f99STeresa Johnson
15069fb6e1a0SPeter Collingbourne // Figure out which symbols need to be internalized. This also needs to happen
15079fb6e1a0SPeter Collingbourne // at -O0 because summary-based DCE is implemented using internalization, and
15089fb6e1a0SPeter Collingbourne // we must apply DCE consistently with the full LTO module in order to avoid
15099fb6e1a0SPeter Collingbourne // undefined references during the final link.
15109ba95f99STeresa Johnson for (auto &Res : GlobalResolutions) {
1511d328365bSGeorge Rimar // If the symbol does not have external references or it is not prevailing,
1512d328365bSGeorge Rimar // then not need to mark it as exported from a ThinLTO partition.
1513d328365bSGeorge Rimar if (Res.second.Partition != GlobalResolution::External ||
1514eaf5172cSGeorge Rimar !Res.second.isPrevailingIRSymbol())
15156c475a75STeresa Johnson continue;
1516d6aea719SBob Haarman auto GUID = GlobalValue::getGUID(
15176f0ecca3SPeter Collingbourne GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
15186c475a75STeresa Johnson // Mark exported unless index-based analysis determined it to be dead.
1519dbd2fed6SPeter Collingbourne if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1520d6aea719SBob Haarman ExportedGUIDs.insert(GUID);
15219ba95f99STeresa Johnson }
15229ba95f99STeresa Johnson
1523e776dd9cSPeter Collingbourne // Any functions referenced by the jump table in the regular LTO object must
1524e776dd9cSPeter Collingbourne // be exported.
1525e776dd9cSPeter Collingbourne for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1526e776dd9cSPeter Collingbourne ExportedGUIDs.insert(
1527e776dd9cSPeter Collingbourne GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Def)));
15282f9ba6aaSSami Tolvanen for (auto &Decl : ThinLTO.CombinedIndex.cfiFunctionDecls())
15292f9ba6aaSSami Tolvanen ExportedGUIDs.insert(
15302f9ba6aaSSami Tolvanen GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Decl)));
1531e776dd9cSPeter Collingbourne
15323d708bf5Sevgeny auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
15339ba95f99STeresa Johnson const auto &ExportList = ExportLists.find(ModuleIdentifier);
15343d708bf5Sevgeny return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
15353d708bf5Sevgeny ExportedGUIDs.count(VI.getGUID());
15369ba95f99STeresa Johnson };
1537077cc3fcSTeresa Johnson
1538077cc3fcSTeresa Johnson // Update local devirtualized targets that were exported by cross-module
1539077cc3fcSTeresa Johnson // importing or by other devirtualizations marked in the ExportedGUIDs set.
1540077cc3fcSTeresa Johnson updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
1541077cc3fcSTeresa Johnson LocalWPDTargetsMap);
1542077cc3fcSTeresa Johnson
1543f87197adSPeter Collingbourne auto isPrevailing = [&](GlobalValue::GUID GUID,
1544f87197adSPeter Collingbourne const GlobalValueSummary *S) {
1545f87197adSPeter Collingbourne return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1546f87197adSPeter Collingbourne };
1547ea314fd4STeresa Johnson thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
1548ea314fd4STeresa Johnson isPrevailing);
1549ea314fd4STeresa Johnson
1550adc0e26bSMehdi Amini auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1551adc0e26bSMehdi Amini GlobalValue::GUID GUID,
1552adc0e26bSMehdi Amini GlobalValue::LinkageTypes NewLinkage) {
1553adc0e26bSMehdi Amini ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1554adc0e26bSMehdi Amini };
155554fb3ca9SFangrui Song thinLTOResolvePrevailingInIndex(Conf, ThinLTO.CombinedIndex, isPrevailing,
155637b80122STeresa Johnson recordNewLinkage, GUIDPreservedSymbols);
15579ba95f99STeresa Johnson
155820faf789Smodimo thinLTOPropagateFunctionAttrs(ThinLTO.CombinedIndex, isPrevailing);
155920faf789Smodimo
1560c1e47b47SVitaly Buka generateParamAccessSummary(ThinLTO.CombinedIndex);
1561c1e47b47SVitaly Buka
1562f5b8a312Smodimo if (llvm::timeTraceProfilerEnabled())
1563f5b8a312Smodimo llvm::timeTraceProfilerEnd();
1564f5b8a312Smodimo
1565f5b8a312Smodimo TimeTraceScopeExit.release();
1566f5b8a312Smodimo
156780186a57SPeter Collingbourne std::unique_ptr<ThinBackendProc> BackendProc =
156880186a57SPeter Collingbourne ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
156980186a57SPeter Collingbourne AddStream, Cache);
15709ba95f99STeresa Johnson
15712638aafeSHongtao Yu auto &ModuleMap =
15722638aafeSHongtao Yu ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
15732638aafeSHongtao Yu
1574617d64f6SAlexandre Ganea auto ProcessOneModule = [&](int I) -> Error {
1575617d64f6SAlexandre Ganea auto &Mod = *(ModuleMap.begin() + I);
1576617d64f6SAlexandre Ganea // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
1577617d64f6SAlexandre Ganea // combined module and parallel code generation partitions.
1578617d64f6SAlexandre Ganea return BackendProc->start(RegularLTO.ParallelCodeGenParallelismLevel + I,
1579617d64f6SAlexandre Ganea Mod.second, ImportLists[Mod.first],
1580617d64f6SAlexandre Ganea ExportLists[Mod.first], ResolvedODR[Mod.first],
1581617d64f6SAlexandre Ganea ThinLTO.ModuleMap);
1582617d64f6SAlexandre Ganea };
15839ba95f99STeresa Johnson
1584617d64f6SAlexandre Ganea if (BackendProc->getThreadCount() == 1) {
1585617d64f6SAlexandre Ganea // Process the modules in the order they were provided on the command-line.
1586617d64f6SAlexandre Ganea // It is important for this codepath to be used for WriteIndexesThinBackend,
1587617d64f6SAlexandre Ganea // to ensure the emitted LinkedObjectsFile lists ThinLTO objects in the same
1588617d64f6SAlexandre Ganea // order as the inputs, which otherwise would affect the final link order.
1589617d64f6SAlexandre Ganea for (int I = 0, E = ModuleMap.size(); I != E; ++I)
1590617d64f6SAlexandre Ganea if (Error E = ProcessOneModule(I))
1591617d64f6SAlexandre Ganea return E;
1592617d64f6SAlexandre Ganea } else {
1593617d64f6SAlexandre Ganea // When executing in parallel, process largest bitsize modules first to
1594617d64f6SAlexandre Ganea // improve parallelism, and avoid starving the thread pool near the end.
1595617d64f6SAlexandre Ganea // This saves about 15 sec on a 36-core machine while link `clang.exe` (out
1596617d64f6SAlexandre Ganea // of 100 sec).
1597617d64f6SAlexandre Ganea std::vector<BitcodeModule *> ModulesVec;
1598617d64f6SAlexandre Ganea ModulesVec.reserve(ModuleMap.size());
1599617d64f6SAlexandre Ganea for (auto &Mod : ModuleMap)
1600617d64f6SAlexandre Ganea ModulesVec.push_back(&Mod.second);
1601617d64f6SAlexandre Ganea for (int I : generateModulesOrdering(ModulesVec))
1602617d64f6SAlexandre Ganea if (Error E = ProcessOneModule(I))
1603617d64f6SAlexandre Ganea return E;
1604617d64f6SAlexandre Ganea }
16059ba95f99STeresa Johnson return BackendProc->wait();
1606df6edc52STeresa Johnson }
1607690ed9deSDavide Italiano
setupLLVMOptimizationRemarks(LLVMContext & Context,StringRef RemarksFilename,StringRef RemarksPasses,StringRef RemarksFormat,bool RemarksWithHotness,Optional<uint64_t> RemarksHotnessThreshold,int Count)16087531a503SFrancis Visoiu Mistrih Expected<std::unique_ptr<ToolOutputFile>> lto::setupLLVMOptimizationRemarks(
16097531a503SFrancis Visoiu Mistrih LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
16103acda917SWei Wang StringRef RemarksFormat, bool RemarksWithHotness,
16113acda917SWei Wang Optional<uint64_t> RemarksHotnessThreshold, int Count) {
1612adcd0268SBenjamin Kramer std::string Filename = std::string(RemarksFilename);
16137902d6ccSFrancis Visoiu Mistrih // For ThinLTO, file.opt.<format> becomes
16147902d6ccSFrancis Visoiu Mistrih // file.opt.<format>.thin.<num>.<format>.
16157a21113cSFrancis Visoiu Mistrih if (!Filename.empty() && Count != -1)
16167902d6ccSFrancis Visoiu Mistrih Filename =
16177902d6ccSFrancis Visoiu Mistrih (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
16187902d6ccSFrancis Visoiu Mistrih .str();
1619690ed9deSDavide Italiano
16207531a503SFrancis Visoiu Mistrih auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
16213acda917SWei Wang Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness,
16223acda917SWei Wang RemarksHotnessThreshold);
16237a21113cSFrancis Visoiu Mistrih if (Error E = ResultOrErr.takeError())
1624c55cf4afSBill Wendling return std::move(E);
1625dd42236cSFrancis Visoiu Mistrih
16267a21113cSFrancis Visoiu Mistrih if (*ResultOrErr)
16277a21113cSFrancis Visoiu Mistrih (*ResultOrErr)->keep();
16287a21113cSFrancis Visoiu Mistrih
16297a21113cSFrancis Visoiu Mistrih return ResultOrErr;
1630690ed9deSDavide Italiano }
1631b340497fSFlorian Hahn
1632b340497fSFlorian Hahn Expected<std::unique_ptr<ToolOutputFile>>
setupStatsFile(StringRef StatsFilename)1633b340497fSFlorian Hahn lto::setupStatsFile(StringRef StatsFilename) {
1634b340497fSFlorian Hahn // Setup output file to emit statistics.
1635b340497fSFlorian Hahn if (StatsFilename.empty())
1636b340497fSFlorian Hahn return nullptr;
1637b340497fSFlorian Hahn
1638b340497fSFlorian Hahn llvm::EnableStatistics(false);
1639b340497fSFlorian Hahn std::error_code EC;
1640b340497fSFlorian Hahn auto StatsFile =
16410eaee545SJonas Devlieghere std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
1642b340497fSFlorian Hahn if (EC)
1643b340497fSFlorian Hahn return errorCodeToError(EC);
1644b340497fSFlorian Hahn
1645b340497fSFlorian Hahn StatsFile->keep();
1646c55cf4afSBill Wendling return std::move(StatsFile);
1647b340497fSFlorian Hahn }
1648617d64f6SAlexandre Ganea
1649617d64f6SAlexandre Ganea // Compute the ordering we will process the inputs: the rough heuristic here
1650617d64f6SAlexandre Ganea // is to sort them per size so that the largest module get schedule as soon as
1651617d64f6SAlexandre Ganea // possible. This is purely a compile-time optimization.
generateModulesOrdering(ArrayRef<BitcodeModule * > R)1652617d64f6SAlexandre Ganea std::vector<int> lto::generateModulesOrdering(ArrayRef<BitcodeModule *> R) {
165385243124SBenjamin Kramer auto Seq = llvm::seq<int>(0, R.size());
165485243124SBenjamin Kramer std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
1655617d64f6SAlexandre Ganea llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
1656617d64f6SAlexandre Ganea auto LSize = R[LeftIndex]->getBuffer().size();
1657617d64f6SAlexandre Ganea auto RSize = R[RightIndex]->getBuffer().size();
1658617d64f6SAlexandre Ganea return LSize > RSize;
1659617d64f6SAlexandre Ganea });
1660617d64f6SAlexandre Ganea return ModulesOrdering;
1661617d64f6SAlexandre Ganea }
1662