xref: /llvm-project-15.0.7/llvm/lib/LTO/LTO.cpp (revision 7ebe9cc4)
1 //===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements functions and classes used to support LTO.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/LTO/LTO.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
16 #include "llvm/Analysis/TargetLibraryInfo.h"
17 #include "llvm/Analysis/TargetTransformInfo.h"
18 #include "llvm/Bitcode/BitcodeReader.h"
19 #include "llvm/Bitcode/BitcodeWriter.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/Config/llvm-config.h"
22 #include "llvm/IR/AutoUpgrade.h"
23 #include "llvm/IR/DiagnosticPrinter.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/LLVMRemarkStreamer.h"
26 #include "llvm/IR/LegacyPassManager.h"
27 #include "llvm/IR/Mangler.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/LTO/LTOBackend.h"
30 #include "llvm/LTO/SummaryBasedOptimizations.h"
31 #include "llvm/Linker/IRMover.h"
32 #include "llvm/Object/IRObjectFile.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Error.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/SHA1.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/ThreadPool.h"
42 #include "llvm/Support/Threading.h"
43 #include "llvm/Support/TimeProfiler.h"
44 #include "llvm/Support/VCSRevision.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Transforms/IPO.h"
49 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
50 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
51 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
52 #include "llvm/Transforms/Utils/SplitModule.h"
53 
54 #include <set>
55 
56 using namespace llvm;
57 using namespace lto;
58 using namespace object;
59 
60 #define DEBUG_TYPE "lto"
61 
62 static cl::opt<bool>
63     DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden,
64                    cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
65 
66 /// Enable global value internalization in LTO.
67 cl::opt<bool> EnableLTOInternalization(
68     "enable-lto-internalization", cl::init(true), cl::Hidden,
69     cl::desc("Enable global value internalization in LTO"));
70 
71 // Computes a unique hash for the Module considering the current list of
72 // export/import and other global analysis results.
73 // The hash is produced in \p Key.
74 void llvm::computeLTOCacheKey(
75     SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
76     StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
77     const FunctionImporter::ExportSetTy &ExportList,
78     const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
79     const GVSummaryMapTy &DefinedGlobals,
80     const std::set<GlobalValue::GUID> &CfiFunctionDefs,
81     const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
82   // Compute the unique hash for this entry.
83   // This is based on the current compiler version, the module itself, the
84   // export list, the hash for every single module in the import list, the
85   // list of ResolvedODR for the module, and the list of preserved symbols.
86   SHA1 Hasher;
87 
88   // Start with the compiler revision
89   Hasher.update(LLVM_VERSION_STRING);
90 #ifdef LLVM_REVISION
91   Hasher.update(LLVM_REVISION);
92 #endif
93 
94   // Include the parts of the LTO configuration that affect code generation.
95   auto AddString = [&](StringRef Str) {
96     Hasher.update(Str);
97     Hasher.update(ArrayRef<uint8_t>{0});
98   };
99   auto AddUnsigned = [&](unsigned I) {
100     uint8_t Data[4];
101     Data[0] = I;
102     Data[1] = I >> 8;
103     Data[2] = I >> 16;
104     Data[3] = I >> 24;
105     Hasher.update(ArrayRef<uint8_t>{Data, 4});
106   };
107   auto AddUint64 = [&](uint64_t I) {
108     uint8_t Data[8];
109     Data[0] = I;
110     Data[1] = I >> 8;
111     Data[2] = I >> 16;
112     Data[3] = I >> 24;
113     Data[4] = I >> 32;
114     Data[5] = I >> 40;
115     Data[6] = I >> 48;
116     Data[7] = I >> 56;
117     Hasher.update(ArrayRef<uint8_t>{Data, 8});
118   };
119   AddString(Conf.CPU);
120   // FIXME: Hash more of Options. For now all clients initialize Options from
121   // command-line flags (which is unsupported in production), but may set
122   // RelaxELFRelocations. The clang driver can also pass FunctionSections,
123   // DataSections and DebuggerTuning via command line flags.
124   AddUnsigned(Conf.Options.RelaxELFRelocations);
125   AddUnsigned(Conf.Options.FunctionSections);
126   AddUnsigned(Conf.Options.DataSections);
127   AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
128   for (auto &A : Conf.MAttrs)
129     AddString(A);
130   if (Conf.RelocModel)
131     AddUnsigned(*Conf.RelocModel);
132   else
133     AddUnsigned(-1);
134   if (Conf.CodeModel)
135     AddUnsigned(*Conf.CodeModel);
136   else
137     AddUnsigned(-1);
138   AddUnsigned(Conf.CGOptLevel);
139   AddUnsigned(Conf.CGFileType);
140   AddUnsigned(Conf.OptLevel);
141   AddUnsigned(Conf.UseNewPM);
142   AddUnsigned(Conf.Freestanding);
143   AddString(Conf.OptPipeline);
144   AddString(Conf.AAPipeline);
145   AddString(Conf.OverrideTriple);
146   AddString(Conf.DefaultTriple);
147   AddString(Conf.DwoDir);
148 
149   // Include the hash for the current module
150   auto ModHash = Index.getModuleHash(ModuleID);
151   Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
152   for (const auto &VI : ExportList) {
153     auto GUID = VI.getGUID();
154     // The export list can impact the internalization, be conservative here
155     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
156   }
157 
158   // Include the hash for every module we import functions from. The set of
159   // imported symbols for each module may affect code generation and is
160   // sensitive to link order, so include that as well.
161   for (auto &Entry : ImportList) {
162     auto ModHash = Index.getModuleHash(Entry.first());
163     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
164 
165     AddUint64(Entry.second.size());
166     for (auto &Fn : Entry.second)
167       AddUint64(Fn);
168   }
169 
170   // Include the hash for the resolved ODR.
171   for (auto &Entry : ResolvedODR) {
172     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
173                                     sizeof(GlobalValue::GUID)));
174     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
175                                     sizeof(GlobalValue::LinkageTypes)));
176   }
177 
178   // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
179   // defined in this module.
180   std::set<GlobalValue::GUID> UsedCfiDefs;
181   std::set<GlobalValue::GUID> UsedCfiDecls;
182 
183   // Typeids used in this module.
184   std::set<GlobalValue::GUID> UsedTypeIds;
185 
186   auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
187     if (CfiFunctionDefs.count(ValueGUID))
188       UsedCfiDefs.insert(ValueGUID);
189     if (CfiFunctionDecls.count(ValueGUID))
190       UsedCfiDecls.insert(ValueGUID);
191   };
192 
193   auto AddUsedThings = [&](GlobalValueSummary *GS) {
194     if (!GS) return;
195     AddUnsigned(GS->isLive());
196     AddUnsigned(GS->canAutoHide());
197     for (const ValueInfo &VI : GS->refs()) {
198       AddUnsigned(VI.isDSOLocal());
199       AddUsedCfiGlobal(VI.getGUID());
200     }
201     if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) {
202       AddUnsigned(GVS->maybeReadOnly());
203       AddUnsigned(GVS->maybeWriteOnly());
204     }
205     if (auto *FS = dyn_cast<FunctionSummary>(GS)) {
206       for (auto &TT : FS->type_tests())
207         UsedTypeIds.insert(TT);
208       for (auto &TT : FS->type_test_assume_vcalls())
209         UsedTypeIds.insert(TT.GUID);
210       for (auto &TT : FS->type_checked_load_vcalls())
211         UsedTypeIds.insert(TT.GUID);
212       for (auto &TT : FS->type_test_assume_const_vcalls())
213         UsedTypeIds.insert(TT.VFunc.GUID);
214       for (auto &TT : FS->type_checked_load_const_vcalls())
215         UsedTypeIds.insert(TT.VFunc.GUID);
216       for (auto &ET : FS->calls()) {
217         AddUnsigned(ET.first.isDSOLocal());
218         AddUsedCfiGlobal(ET.first.getGUID());
219       }
220     }
221   };
222 
223   // Include the hash for the linkage type to reflect internalization and weak
224   // resolution, and collect any used type identifier resolutions.
225   for (auto &GS : DefinedGlobals) {
226     GlobalValue::LinkageTypes Linkage = GS.second->linkage();
227     Hasher.update(
228         ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
229     AddUsedCfiGlobal(GS.first);
230     AddUsedThings(GS.second);
231   }
232 
233   // Imported functions may introduce new uses of type identifier resolutions,
234   // so we need to collect their used resolutions as well.
235   for (auto &ImpM : ImportList)
236     for (auto &ImpF : ImpM.second) {
237       GlobalValueSummary *S = Index.findSummaryInModule(ImpF, ImpM.first());
238       AddUsedThings(S);
239       // If this is an alias, we also care about any types/etc. that the aliasee
240       // may reference.
241       if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
242         AddUsedThings(AS->getBaseObject());
243     }
244 
245   auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
246     AddString(TId);
247 
248     AddUnsigned(S.TTRes.TheKind);
249     AddUnsigned(S.TTRes.SizeM1BitWidth);
250 
251     AddUint64(S.TTRes.AlignLog2);
252     AddUint64(S.TTRes.SizeM1);
253     AddUint64(S.TTRes.BitMask);
254     AddUint64(S.TTRes.InlineBits);
255 
256     AddUint64(S.WPDRes.size());
257     for (auto &WPD : S.WPDRes) {
258       AddUnsigned(WPD.first);
259       AddUnsigned(WPD.second.TheKind);
260       AddString(WPD.second.SingleImplName);
261 
262       AddUint64(WPD.second.ResByArg.size());
263       for (auto &ByArg : WPD.second.ResByArg) {
264         AddUint64(ByArg.first.size());
265         for (uint64_t Arg : ByArg.first)
266           AddUint64(Arg);
267         AddUnsigned(ByArg.second.TheKind);
268         AddUint64(ByArg.second.Info);
269         AddUnsigned(ByArg.second.Byte);
270         AddUnsigned(ByArg.second.Bit);
271       }
272     }
273   };
274 
275   // Include the hash for all type identifiers used by this module.
276   for (GlobalValue::GUID TId : UsedTypeIds) {
277     auto TidIter = Index.typeIds().equal_range(TId);
278     for (auto It = TidIter.first; It != TidIter.second; ++It)
279       AddTypeIdSummary(It->second.first, It->second.second);
280   }
281 
282   AddUnsigned(UsedCfiDefs.size());
283   for (auto &V : UsedCfiDefs)
284     AddUint64(V);
285 
286   AddUnsigned(UsedCfiDecls.size());
287   for (auto &V : UsedCfiDecls)
288     AddUint64(V);
289 
290   if (!Conf.SampleProfile.empty()) {
291     auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
292     if (FileOrErr) {
293       Hasher.update(FileOrErr.get()->getBuffer());
294 
295       if (!Conf.ProfileRemapping.empty()) {
296         FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping);
297         if (FileOrErr)
298           Hasher.update(FileOrErr.get()->getBuffer());
299       }
300     }
301   }
302 
303   Key = toHex(Hasher.result());
304 }
305 
306 static void thinLTOResolvePrevailingGUID(
307     ValueInfo VI, DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
308     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
309         isPrevailing,
310     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
311         recordNewLinkage,
312     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
313   for (auto &S : VI.getSummaryList()) {
314     GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
315     // Ignore local and appending linkage values since the linker
316     // doesn't resolve them.
317     if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
318         GlobalValue::isAppendingLinkage(S->linkage()))
319       continue;
320     // We need to emit only one of these. The prevailing module will keep it,
321     // but turned into a weak, while the others will drop it when possible.
322     // This is both a compile-time optimization and a correctness
323     // transformation. This is necessary for correctness when we have exported
324     // a reference - we need to convert the linkonce to weak to
325     // ensure a copy is kept to satisfy the exported reference.
326     // FIXME: We may want to split the compile time and correctness
327     // aspects into separate routines.
328     if (isPrevailing(VI.getGUID(), S.get())) {
329       if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) {
330         S->setLinkage(GlobalValue::getWeakLinkage(
331             GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
332         // The kept copy is eligible for auto-hiding (hidden visibility) if all
333         // copies were (i.e. they were all linkonce_odr global unnamed addr).
334         // If any copy is not (e.g. it was originally weak_odr), then the symbol
335         // must remain externally available (e.g. a weak_odr from an explicitly
336         // instantiated template). Additionally, if it is in the
337         // GUIDPreservedSymbols set, that means that it is visibile outside
338         // the summary (e.g. in a native object or a bitcode file without
339         // summary), and in that case we cannot hide it as it isn't possible to
340         // check all copies.
341         S->setCanAutoHide(VI.canAutoHide() &&
342                           !GUIDPreservedSymbols.count(VI.getGUID()));
343       }
344     }
345     // Alias and aliasee can't be turned into available_externally.
346     else if (!isa<AliasSummary>(S.get()) &&
347              !GlobalInvolvedWithAlias.count(S.get()))
348       S->setLinkage(GlobalValue::AvailableExternallyLinkage);
349     if (S->linkage() != OriginalLinkage)
350       recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
351   }
352 }
353 
354 /// Resolve linkage for prevailing symbols in the \p Index.
355 //
356 // We'd like to drop these functions if they are no longer referenced in the
357 // current module. However there is a chance that another module is still
358 // referencing them because of the import. We make sure we always emit at least
359 // one copy.
360 void llvm::thinLTOResolvePrevailingInIndex(
361     ModuleSummaryIndex &Index,
362     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
363         isPrevailing,
364     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
365         recordNewLinkage,
366     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
367   // We won't optimize the globals that are referenced by an alias for now
368   // Ideally we should turn the alias into a global and duplicate the definition
369   // when needed.
370   DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
371   for (auto &I : Index)
372     for (auto &S : I.second.SummaryList)
373       if (auto AS = dyn_cast<AliasSummary>(S.get()))
374         GlobalInvolvedWithAlias.insert(&AS->getAliasee());
375 
376   for (auto &I : Index)
377     thinLTOResolvePrevailingGUID(Index.getValueInfo(I), GlobalInvolvedWithAlias,
378                                  isPrevailing, recordNewLinkage,
379                                  GUIDPreservedSymbols);
380 }
381 
382 static bool isWeakObjectWithRWAccess(GlobalValueSummary *GVS) {
383   if (auto *VarSummary = dyn_cast<GlobalVarSummary>(GVS->getBaseObject()))
384     return !VarSummary->maybeReadOnly() && !VarSummary->maybeWriteOnly() &&
385            (VarSummary->linkage() == GlobalValue::WeakODRLinkage ||
386             VarSummary->linkage() == GlobalValue::LinkOnceODRLinkage);
387   return false;
388 }
389 
390 static void thinLTOInternalizeAndPromoteGUID(
391     ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
392     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
393         isPrevailing) {
394   for (auto &S : VI.getSummaryList()) {
395     if (isExported(S->modulePath(), VI)) {
396       if (GlobalValue::isLocalLinkage(S->linkage()))
397         S->setLinkage(GlobalValue::ExternalLinkage);
398     } else if (EnableLTOInternalization &&
399                // Ignore local and appending linkage values since the linker
400                // doesn't resolve them.
401                !GlobalValue::isLocalLinkage(S->linkage()) &&
402                (!GlobalValue::isInterposableLinkage(S->linkage()) ||
403                 isPrevailing(VI.getGUID(), S.get())) &&
404                S->linkage() != GlobalValue::AppendingLinkage &&
405                // We can't internalize available_externally globals because this
406                // can break function pointer equality.
407                S->linkage() != GlobalValue::AvailableExternallyLinkage &&
408                // Functions and read-only variables with linkonce_odr and
409                // weak_odr linkage can be internalized. We can't internalize
410                // linkonce_odr and weak_odr variables which are both modified
411                // and read somewhere in the program because reads and writes
412                // will become inconsistent.
413                !isWeakObjectWithRWAccess(S.get()))
414       S->setLinkage(GlobalValue::InternalLinkage);
415   }
416 }
417 
418 // Update the linkages in the given \p Index to mark exported values
419 // as external and non-exported values as internal.
420 void llvm::thinLTOInternalizeAndPromoteInIndex(
421     ModuleSummaryIndex &Index,
422     function_ref<bool(StringRef, ValueInfo)> isExported,
423     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
424         isPrevailing) {
425   for (auto &I : Index)
426     thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported,
427                                      isPrevailing);
428 }
429 
430 // Requires a destructor for std::vector<InputModule>.
431 InputFile::~InputFile() = default;
432 
433 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
434   std::unique_ptr<InputFile> File(new InputFile);
435 
436   Expected<IRSymtabFile> FOrErr = readIRSymtab(Object);
437   if (!FOrErr)
438     return FOrErr.takeError();
439 
440   File->TargetTriple = FOrErr->TheReader.getTargetTriple();
441   File->SourceFileName = FOrErr->TheReader.getSourceFileName();
442   File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
443   File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
444   File->ComdatTable = FOrErr->TheReader.getComdatTable();
445 
446   for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
447     size_t Begin = File->Symbols.size();
448     for (const irsymtab::Reader::SymbolRef &Sym :
449          FOrErr->TheReader.module_symbols(I))
450       // Skip symbols that are irrelevant to LTO. Note that this condition needs
451       // to match the one in Skip() in LTO::addRegularLTO().
452       if (Sym.isGlobal() && !Sym.isFormatSpecific())
453         File->Symbols.push_back(Sym);
454     File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
455   }
456 
457   File->Mods = FOrErr->Mods;
458   File->Strtab = std::move(FOrErr->Strtab);
459   return std::move(File);
460 }
461 
462 StringRef InputFile::getName() const {
463   return Mods[0].getModuleIdentifier();
464 }
465 
466 BitcodeModule &InputFile::getSingleBitcodeModule() {
467   assert(Mods.size() == 1 && "Expect only one bitcode module");
468   return Mods[0];
469 }
470 
471 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
472                                       const Config &Conf)
473     : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
474       Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)),
475       Mover(std::make_unique<IRMover>(*CombinedModule)) {}
476 
477 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend)
478     : Backend(Backend), CombinedIndex(/*HaveGVs*/ false) {
479   if (!Backend)
480     this->Backend =
481         createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
482 }
483 
484 LTO::LTO(Config Conf, ThinBackend Backend,
485          unsigned ParallelCodeGenParallelismLevel)
486     : Conf(std::move(Conf)),
487       RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
488       ThinLTO(std::move(Backend)) {}
489 
490 // Requires a destructor for MapVector<BitcodeModule>.
491 LTO::~LTO() = default;
492 
493 // Add the symbols in the given module to the GlobalResolutions map, and resolve
494 // their partitions.
495 void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
496                                ArrayRef<SymbolResolution> Res,
497                                unsigned Partition, bool InSummary) {
498   auto *ResI = Res.begin();
499   auto *ResE = Res.end();
500   (void)ResE;
501   for (const InputFile::Symbol &Sym : Syms) {
502     assert(ResI != ResE);
503     SymbolResolution Res = *ResI++;
504 
505     StringRef Name = Sym.getName();
506     Triple TT(RegularLTO.CombinedModule->getTargetTriple());
507     // Strip the __imp_ prefix from COFF dllimport symbols (similar to the
508     // way they are handled by lld), otherwise we can end up with two
509     // global resolutions (one with and one for a copy of the symbol without).
510     if (TT.isOSBinFormatCOFF() && Name.startswith("__imp_"))
511       Name = Name.substr(strlen("__imp_"));
512     auto &GlobalRes = GlobalResolutions[Name];
513     GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
514     if (Res.Prevailing) {
515       assert(!GlobalRes.Prevailing &&
516              "Multiple prevailing defs are not allowed");
517       GlobalRes.Prevailing = true;
518       GlobalRes.IRName = std::string(Sym.getIRName());
519     } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
520       // Sometimes it can be two copies of symbol in a module and prevailing
521       // symbol can have no IR name. That might happen if symbol is defined in
522       // module level inline asm block. In case we have multiple modules with
523       // the same symbol we want to use IR name of the prevailing symbol.
524       // Otherwise, if we haven't seen a prevailing symbol, set the name so that
525       // we can later use it to check if there is any prevailing copy in IR.
526       GlobalRes.IRName = std::string(Sym.getIRName());
527     }
528 
529     // Set the partition to external if we know it is re-defined by the linker
530     // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
531     // regular object, is referenced from llvm.compiler_used, or was already
532     // recorded as being referenced from a different partition.
533     if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
534         (GlobalRes.Partition != GlobalResolution::Unknown &&
535          GlobalRes.Partition != Partition)) {
536       GlobalRes.Partition = GlobalResolution::External;
537     } else
538       // First recorded reference, save the current partition.
539       GlobalRes.Partition = Partition;
540 
541     // Flag as visible outside of summary if visible from a regular object or
542     // from a module that does not have a summary.
543     GlobalRes.VisibleOutsideSummary |=
544         (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
545   }
546 }
547 
548 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
549                                   ArrayRef<SymbolResolution> Res) {
550   StringRef Path = Input->getName();
551   OS << Path << '\n';
552   auto ResI = Res.begin();
553   for (const InputFile::Symbol &Sym : Input->symbols()) {
554     assert(ResI != Res.end());
555     SymbolResolution Res = *ResI++;
556 
557     OS << "-r=" << Path << ',' << Sym.getName() << ',';
558     if (Res.Prevailing)
559       OS << 'p';
560     if (Res.FinalDefinitionInLinkageUnit)
561       OS << 'l';
562     if (Res.VisibleToRegularObj)
563       OS << 'x';
564     if (Res.LinkerRedefined)
565       OS << 'r';
566     OS << '\n';
567   }
568   OS.flush();
569   assert(ResI == Res.end());
570 }
571 
572 Error LTO::add(std::unique_ptr<InputFile> Input,
573                ArrayRef<SymbolResolution> Res) {
574   assert(!CalledGetMaxTasks);
575 
576   if (Conf.ResolutionFile)
577     writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
578 
579   if (RegularLTO.CombinedModule->getTargetTriple().empty())
580     RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
581 
582   const SymbolResolution *ResI = Res.begin();
583   for (unsigned I = 0; I != Input->Mods.size(); ++I)
584     if (Error Err = addModule(*Input, I, ResI, Res.end()))
585       return Err;
586 
587   assert(ResI == Res.end());
588   return Error::success();
589 }
590 
591 Error LTO::addModule(InputFile &Input, unsigned ModI,
592                      const SymbolResolution *&ResI,
593                      const SymbolResolution *ResE) {
594   Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
595   if (!LTOInfo)
596     return LTOInfo.takeError();
597 
598   if (EnableSplitLTOUnit.hasValue()) {
599     // If only some modules were split, flag this in the index so that
600     // we can skip or error on optimizations that need consistently split
601     // modules (whole program devirt and lower type tests).
602     if (EnableSplitLTOUnit.getValue() != LTOInfo->EnableSplitLTOUnit)
603       ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
604   } else
605     EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
606 
607   BitcodeModule BM = Input.Mods[ModI];
608   auto ModSyms = Input.module_symbols(ModI);
609   addModuleToGlobalRes(ModSyms, {ResI, ResE},
610                        LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
611                        LTOInfo->HasSummary);
612 
613   if (LTOInfo->IsThinLTO)
614     return addThinLTO(BM, ModSyms, ResI, ResE);
615 
616   Expected<RegularLTOState::AddedModule> ModOrErr =
617       addRegularLTO(BM, ModSyms, ResI, ResE);
618   if (!ModOrErr)
619     return ModOrErr.takeError();
620 
621   if (!LTOInfo->HasSummary)
622     return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false);
623 
624   // Regular LTO module summaries are added to a dummy module that represents
625   // the combined regular LTO module.
626   if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, "", -1ull))
627     return Err;
628   RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
629   return Error::success();
630 }
631 
632 // Checks whether the given global value is in a non-prevailing comdat
633 // (comdat containing values the linker indicated were not prevailing,
634 // which we then dropped to available_externally), and if so, removes
635 // it from the comdat. This is called for all global values to ensure the
636 // comdat is empty rather than leaving an incomplete comdat. It is needed for
637 // regular LTO modules, in case we are in a mixed-LTO mode (both regular
638 // and thin LTO modules) compilation. Since the regular LTO module will be
639 // linked first in the final native link, we want to make sure the linker
640 // doesn't select any of these incomplete comdats that would be left
641 // in the regular LTO module without this cleanup.
642 static void
643 handleNonPrevailingComdat(GlobalValue &GV,
644                           std::set<const Comdat *> &NonPrevailingComdats) {
645   Comdat *C = GV.getComdat();
646   if (!C)
647     return;
648 
649   if (!NonPrevailingComdats.count(C))
650     return;
651 
652   // Additionally need to drop externally visible global values from the comdat
653   // to available_externally, so that there aren't multiply defined linker
654   // errors.
655   if (!GV.hasLocalLinkage())
656     GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
657 
658   if (auto GO = dyn_cast<GlobalObject>(&GV))
659     GO->setComdat(nullptr);
660 }
661 
662 // Add a regular LTO object to the link.
663 // The resulting module needs to be linked into the combined LTO module with
664 // linkRegularLTO.
665 Expected<LTO::RegularLTOState::AddedModule>
666 LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
667                    const SymbolResolution *&ResI,
668                    const SymbolResolution *ResE) {
669   RegularLTOState::AddedModule Mod;
670   Expected<std::unique_ptr<Module>> MOrErr =
671       BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
672                        /*IsImporting*/ false);
673   if (!MOrErr)
674     return MOrErr.takeError();
675   Module &M = **MOrErr;
676   Mod.M = std::move(*MOrErr);
677 
678   if (Error Err = M.materializeMetadata())
679     return std::move(Err);
680   UpgradeDebugInfo(M);
681 
682   ModuleSymbolTable SymTab;
683   SymTab.addModule(&M);
684 
685   for (GlobalVariable &GV : M.globals())
686     if (GV.hasAppendingLinkage())
687       Mod.Keep.push_back(&GV);
688 
689   DenseSet<GlobalObject *> AliasedGlobals;
690   for (auto &GA : M.aliases())
691     if (GlobalObject *GO = GA.getBaseObject())
692       AliasedGlobals.insert(GO);
693 
694   // In this function we need IR GlobalValues matching the symbols in Syms
695   // (which is not backed by a module), so we need to enumerate them in the same
696   // order. The symbol enumeration order of a ModuleSymbolTable intentionally
697   // matches the order of an irsymtab, but when we read the irsymtab in
698   // InputFile::create we omit some symbols that are irrelevant to LTO. The
699   // Skip() function skips the same symbols from the module as InputFile does
700   // from the symbol table.
701   auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
702   auto Skip = [&]() {
703     while (MsymI != MsymE) {
704       auto Flags = SymTab.getSymbolFlags(*MsymI);
705       if ((Flags & object::BasicSymbolRef::SF_Global) &&
706           !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
707         return;
708       ++MsymI;
709     }
710   };
711   Skip();
712 
713   std::set<const Comdat *> NonPrevailingComdats;
714   for (const InputFile::Symbol &Sym : Syms) {
715     assert(ResI != ResE);
716     SymbolResolution Res = *ResI++;
717 
718     assert(MsymI != MsymE);
719     ModuleSymbolTable::Symbol Msym = *MsymI++;
720     Skip();
721 
722     if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
723       if (Res.Prevailing) {
724         if (Sym.isUndefined())
725           continue;
726         Mod.Keep.push_back(GV);
727         // For symbols re-defined with linker -wrap and -defsym options,
728         // set the linkage to weak to inhibit IPO. The linkage will be
729         // restored by the linker.
730         if (Res.LinkerRedefined)
731           GV->setLinkage(GlobalValue::WeakAnyLinkage);
732 
733         GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
734         if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
735           GV->setLinkage(GlobalValue::getWeakLinkage(
736               GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
737       } else if (isa<GlobalObject>(GV) &&
738                  (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
739                   GV->hasAvailableExternallyLinkage()) &&
740                  !AliasedGlobals.count(cast<GlobalObject>(GV))) {
741         // Any of the above three types of linkage indicates that the
742         // chosen prevailing symbol will have the same semantics as this copy of
743         // the symbol, so we may be able to link it with available_externally
744         // linkage. We will decide later whether to do that when we link this
745         // module (in linkRegularLTO), based on whether it is undefined.
746         Mod.Keep.push_back(GV);
747         GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
748         if (GV->hasComdat())
749           NonPrevailingComdats.insert(GV->getComdat());
750         cast<GlobalObject>(GV)->setComdat(nullptr);
751       }
752 
753       // Set the 'local' flag based on the linker resolution for this symbol.
754       if (Res.FinalDefinitionInLinkageUnit) {
755         GV->setDSOLocal(true);
756         if (GV->hasDLLImportStorageClass())
757           GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
758                                  DefaultStorageClass);
759       }
760     }
761     // Common resolution: collect the maximum size/alignment over all commons.
762     // We also record if we see an instance of a common as prevailing, so that
763     // if none is prevailing we can ignore it later.
764     if (Sym.isCommon()) {
765       // FIXME: We should figure out what to do about commons defined by asm.
766       // For now they aren't reported correctly by ModuleSymbolTable.
767       auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
768       CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
769       CommonRes.Align =
770           std::max(CommonRes.Align, MaybeAlign(Sym.getCommonAlignment()));
771       CommonRes.Prevailing |= Res.Prevailing;
772     }
773 
774   }
775   if (!M.getComdatSymbolTable().empty())
776     for (GlobalValue &GV : M.global_values())
777       handleNonPrevailingComdat(GV, NonPrevailingComdats);
778   assert(MsymI == MsymE);
779   return std::move(Mod);
780 }
781 
782 Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
783                           bool LivenessFromIndex) {
784   std::vector<GlobalValue *> Keep;
785   for (GlobalValue *GV : Mod.Keep) {
786     if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
787       if (Function *F = dyn_cast<Function>(GV)) {
788         OptimizationRemarkEmitter ORE(F);
789         ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
790                  << ore::NV("Function", F)
791                  << " not added to the combined module ");
792       }
793       continue;
794     }
795 
796     if (!GV->hasAvailableExternallyLinkage()) {
797       Keep.push_back(GV);
798       continue;
799     }
800 
801     // Only link available_externally definitions if we don't already have a
802     // definition.
803     GlobalValue *CombinedGV =
804         RegularLTO.CombinedModule->getNamedValue(GV->getName());
805     if (CombinedGV && !CombinedGV->isDeclaration())
806       continue;
807 
808     Keep.push_back(GV);
809   }
810 
811   return RegularLTO.Mover->move(std::move(Mod.M), Keep,
812                                 [](GlobalValue &, IRMover::ValueAdder) {},
813                                 /* IsPerformingImport */ false);
814 }
815 
816 // Add a ThinLTO module to the link.
817 Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
818                       const SymbolResolution *&ResI,
819                       const SymbolResolution *ResE) {
820   if (Error Err =
821           BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
822                          ThinLTO.ModuleMap.size()))
823     return Err;
824 
825   for (const InputFile::Symbol &Sym : Syms) {
826     assert(ResI != ResE);
827     SymbolResolution Res = *ResI++;
828 
829     if (!Sym.getIRName().empty()) {
830       auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
831           Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
832       if (Res.Prevailing) {
833         ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
834 
835         // For linker redefined symbols (via --wrap or --defsym) we want to
836         // switch the linkage to `weak` to prevent IPOs from happening.
837         // Find the summary in the module for this very GV and record the new
838         // linkage so that we can switch it when we import the GV.
839         if (Res.LinkerRedefined)
840           if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
841                   GUID, BM.getModuleIdentifier()))
842             S->setLinkage(GlobalValue::WeakAnyLinkage);
843       }
844 
845       // If the linker resolved the symbol to a local definition then mark it
846       // as local in the summary for the module we are adding.
847       if (Res.FinalDefinitionInLinkageUnit) {
848         if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
849                 GUID, BM.getModuleIdentifier())) {
850           S->setDSOLocal(true);
851         }
852       }
853     }
854   }
855 
856   if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
857     return make_error<StringError>(
858         "Expected at most one ThinLTO module per bitcode file",
859         inconvertibleErrorCode());
860 
861   return Error::success();
862 }
863 
864 unsigned LTO::getMaxTasks() const {
865   CalledGetMaxTasks = true;
866   return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
867 }
868 
869 // If only some of the modules were split, we cannot correctly handle
870 // code that contains type tests or type checked loads.
871 Error LTO::checkPartiallySplit() {
872   if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
873     return Error::success();
874 
875   Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
876       Intrinsic::getName(Intrinsic::type_test));
877   Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
878       Intrinsic::getName(Intrinsic::type_checked_load));
879 
880   // First check if there are type tests / type checked loads in the
881   // merged regular LTO module IR.
882   if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
883       (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()))
884     return make_error<StringError>(
885         "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
886         inconvertibleErrorCode());
887 
888   // Otherwise check if there are any recorded in the combined summary from the
889   // ThinLTO modules.
890   for (auto &P : ThinLTO.CombinedIndex) {
891     for (auto &S : P.second.SummaryList) {
892       auto *FS = dyn_cast<FunctionSummary>(S.get());
893       if (!FS)
894         continue;
895       if (!FS->type_test_assume_vcalls().empty() ||
896           !FS->type_checked_load_vcalls().empty() ||
897           !FS->type_test_assume_const_vcalls().empty() ||
898           !FS->type_checked_load_const_vcalls().empty() ||
899           !FS->type_tests().empty())
900         return make_error<StringError>(
901             "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
902             inconvertibleErrorCode());
903     }
904   }
905   return Error::success();
906 }
907 
908 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
909   // Compute "dead" symbols, we don't want to import/export these!
910   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
911   DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
912   for (auto &Res : GlobalResolutions) {
913     // Normally resolution have IR name of symbol. We can do nothing here
914     // otherwise. See comments in GlobalResolution struct for more details.
915     if (Res.second.IRName.empty())
916       continue;
917 
918     GlobalValue::GUID GUID = GlobalValue::getGUID(
919         GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
920 
921     if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
922       GUIDPreservedSymbols.insert(GUID);
923 
924     GUIDPrevailingResolutions[GUID] =
925         Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
926   }
927 
928   auto isPrevailing = [&](GlobalValue::GUID G) {
929     auto It = GUIDPrevailingResolutions.find(G);
930     if (It == GUIDPrevailingResolutions.end())
931       return PrevailingType::Unknown;
932     return It->second;
933   };
934   computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
935                                   isPrevailing, Conf.OptLevel > 0);
936 
937   // Setup output file to emit statistics.
938   auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
939   if (!StatsFileOrErr)
940     return StatsFileOrErr.takeError();
941   std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
942 
943   Error Result = runRegularLTO(AddStream);
944   if (!Result)
945     Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
946 
947   if (StatsFile)
948     PrintStatisticsJSON(StatsFile->os());
949 
950   return Result;
951 }
952 
953 Error LTO::runRegularLTO(AddStreamFn AddStream) {
954   // Setup optimization remarks.
955   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
956       RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename,
957       Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness);
958   if (!DiagFileOrErr)
959     return DiagFileOrErr.takeError();
960 
961   // Finalize linking of regular LTO modules containing summaries now that
962   // we have computed liveness information.
963   for (auto &M : RegularLTO.ModsWithSummaries)
964     if (Error Err = linkRegularLTO(std::move(M),
965                                    /*LivenessFromIndex=*/true))
966       return Err;
967 
968   // Ensure we don't have inconsistently split LTO units with type tests.
969   // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
970   // this path both cases but eventually this should be split into two and
971   // do the ThinLTO checks in `runThinLTO`.
972   if (Error Err = checkPartiallySplit())
973     return Err;
974 
975   // Make sure commons have the right size/alignment: we kept the largest from
976   // all the prevailing when adding the inputs, and we apply it here.
977   const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
978   for (auto &I : RegularLTO.Commons) {
979     if (!I.second.Prevailing)
980       // Don't do anything if no instance of this common was prevailing.
981       continue;
982     GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
983     if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
984       // Don't create a new global if the type is already correct, just make
985       // sure the alignment is correct.
986       OldGV->setAlignment(I.second.Align);
987       continue;
988     }
989     ArrayType *Ty =
990         ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
991     auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
992                                   GlobalValue::CommonLinkage,
993                                   ConstantAggregateZero::get(Ty), "");
994     GV->setAlignment(I.second.Align);
995     if (OldGV) {
996       OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
997       GV->takeName(OldGV);
998       OldGV->eraseFromParent();
999     } else {
1000       GV->setName(I.first);
1001     }
1002   }
1003 
1004   // If allowed, upgrade public vcall visibility metadata to linkage unit
1005   // visibility before whole program devirtualization in the optimizer.
1006   updateVCallVisibilityInModule(*RegularLTO.CombinedModule,
1007                                 Conf.HasWholeProgramVisibility);
1008 
1009   if (Conf.PreOptModuleHook &&
1010       !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1011     return Error::success();
1012 
1013   if (!Conf.CodeGenOnly) {
1014     for (const auto &R : GlobalResolutions) {
1015       if (!R.second.isPrevailingIRSymbol())
1016         continue;
1017       if (R.second.Partition != 0 &&
1018           R.second.Partition != GlobalResolution::External)
1019         continue;
1020 
1021       GlobalValue *GV =
1022           RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
1023       // Ignore symbols defined in other partitions.
1024       // Also skip declarations, which are not allowed to have internal linkage.
1025       if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1026         continue;
1027       GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1028                                               : GlobalValue::UnnamedAddr::None);
1029       if (EnableLTOInternalization && R.second.Partition == 0)
1030         GV->setLinkage(GlobalValue::InternalLinkage);
1031     }
1032 
1033     RegularLTO.CombinedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
1034 
1035     if (Conf.PostInternalizeModuleHook &&
1036         !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1037       return Error::success();
1038   }
1039   if (Error Err =
1040           backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1041                   std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex))
1042     return Err;
1043 
1044   return finalizeOptimizationRemarks(std::move(*DiagFileOrErr));
1045 }
1046 
1047 static const char *libcallRoutineNames[] = {
1048 #define HANDLE_LIBCALL(code, name) name,
1049 #include "llvm/IR/RuntimeLibcalls.def"
1050 #undef HANDLE_LIBCALL
1051 };
1052 
1053 ArrayRef<const char*> LTO::getRuntimeLibcallSymbols() {
1054   return makeArrayRef(libcallRoutineNames);
1055 }
1056 
1057 /// This class defines the interface to the ThinLTO backend.
1058 class lto::ThinBackendProc {
1059 protected:
1060   const Config &Conf;
1061   ModuleSummaryIndex &CombinedIndex;
1062   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
1063 
1064 public:
1065   ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1066                   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
1067       : Conf(Conf), CombinedIndex(CombinedIndex),
1068         ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
1069 
1070   virtual ~ThinBackendProc() {}
1071   virtual Error start(
1072       unsigned Task, BitcodeModule BM,
1073       const FunctionImporter::ImportMapTy &ImportList,
1074       const FunctionImporter::ExportSetTy &ExportList,
1075       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1076       MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
1077   virtual Error wait() = 0;
1078 };
1079 
1080 namespace {
1081 class InProcessThinBackend : public ThinBackendProc {
1082   ThreadPool BackendThreadPool;
1083   AddStreamFn AddStream;
1084   NativeObjectCache Cache;
1085   std::set<GlobalValue::GUID> CfiFunctionDefs;
1086   std::set<GlobalValue::GUID> CfiFunctionDecls;
1087 
1088   Optional<Error> Err;
1089   std::mutex ErrMu;
1090 
1091 public:
1092   InProcessThinBackend(
1093       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1094       unsigned ThinLTOParallelismLevel,
1095       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1096       AddStreamFn AddStream, NativeObjectCache Cache)
1097       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
1098         BackendThreadPool(ThinLTOParallelismLevel),
1099         AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
1100     for (auto &Name : CombinedIndex.cfiFunctionDefs())
1101       CfiFunctionDefs.insert(
1102           GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1103     for (auto &Name : CombinedIndex.cfiFunctionDecls())
1104       CfiFunctionDecls.insert(
1105           GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1106   }
1107 
1108   Error runThinLTOBackendThread(
1109       AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
1110       BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1111       const FunctionImporter::ImportMapTy &ImportList,
1112       const FunctionImporter::ExportSetTy &ExportList,
1113       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1114       const GVSummaryMapTy &DefinedGlobals,
1115       MapVector<StringRef, BitcodeModule> &ModuleMap) {
1116     auto RunThinBackend = [&](AddStreamFn AddStream) {
1117       LTOLLVMContext BackendContext(Conf);
1118       Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1119       if (!MOrErr)
1120         return MOrErr.takeError();
1121 
1122       return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1123                          ImportList, DefinedGlobals, ModuleMap);
1124     };
1125 
1126     auto ModuleID = BM.getModuleIdentifier();
1127 
1128     if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
1129         all_of(CombinedIndex.getModuleHash(ModuleID),
1130                [](uint32_t V) { return V == 0; }))
1131       // Cache disabled or no entry for this module in the combined index or
1132       // no module hash.
1133       return RunThinBackend(AddStream);
1134 
1135     SmallString<40> Key;
1136     // The module may be cached, this helps handling it.
1137     computeLTOCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList,
1138                        ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
1139                        CfiFunctionDecls);
1140     if (AddStreamFn CacheAddStream = Cache(Task, Key))
1141       return RunThinBackend(CacheAddStream);
1142 
1143     return Error::success();
1144   }
1145 
1146   Error start(
1147       unsigned Task, BitcodeModule BM,
1148       const FunctionImporter::ImportMapTy &ImportList,
1149       const FunctionImporter::ExportSetTy &ExportList,
1150       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1151       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1152     StringRef ModulePath = BM.getModuleIdentifier();
1153     assert(ModuleToDefinedGVSummaries.count(ModulePath));
1154     const GVSummaryMapTy &DefinedGlobals =
1155         ModuleToDefinedGVSummaries.find(ModulePath)->second;
1156     BackendThreadPool.async(
1157         [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1158             const FunctionImporter::ImportMapTy &ImportList,
1159             const FunctionImporter::ExportSetTy &ExportList,
1160             const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1161                 &ResolvedODR,
1162             const GVSummaryMapTy &DefinedGlobals,
1163             MapVector<StringRef, BitcodeModule> &ModuleMap) {
1164           if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1165             timeTraceProfilerInitialize(Conf.TimeTraceGranularity,
1166                                         "thin backend");
1167           Error E = runThinLTOBackendThread(
1168               AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1169               ResolvedODR, DefinedGlobals, ModuleMap);
1170           if (E) {
1171             std::unique_lock<std::mutex> L(ErrMu);
1172             if (Err)
1173               Err = joinErrors(std::move(*Err), std::move(E));
1174             else
1175               Err = std::move(E);
1176           }
1177           if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1178             timeTraceProfilerFinishThread();
1179         },
1180         BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1181         std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1182     return Error::success();
1183   }
1184 
1185   Error wait() override {
1186     BackendThreadPool.wait();
1187     if (Err)
1188       return std::move(*Err);
1189     else
1190       return Error::success();
1191   }
1192 };
1193 } // end anonymous namespace
1194 
1195 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
1196   return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1197              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1198              AddStreamFn AddStream, NativeObjectCache Cache) {
1199     return std::make_unique<InProcessThinBackend>(
1200         Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
1201         AddStream, Cache);
1202   };
1203 }
1204 
1205 // Given the original \p Path to an output file, replace any path
1206 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1207 // resulting directory if it does not yet exist.
1208 std::string lto::getThinLTOOutputFile(const std::string &Path,
1209                                       const std::string &OldPrefix,
1210                                       const std::string &NewPrefix) {
1211   if (OldPrefix.empty() && NewPrefix.empty())
1212     return Path;
1213   SmallString<128> NewPath(Path);
1214   llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
1215   StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
1216   if (!ParentPath.empty()) {
1217     // Make sure the new directory exists, creating it if necessary.
1218     if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
1219       llvm::errs() << "warning: could not create directory '" << ParentPath
1220                    << "': " << EC.message() << '\n';
1221   }
1222   return std::string(NewPath.str());
1223 }
1224 
1225 namespace {
1226 class WriteIndexesThinBackend : public ThinBackendProc {
1227   std::string OldPrefix, NewPrefix;
1228   bool ShouldEmitImportsFiles;
1229   raw_fd_ostream *LinkedObjectsFile;
1230   lto::IndexWriteCallback OnWrite;
1231 
1232 public:
1233   WriteIndexesThinBackend(
1234       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1235       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1236       std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
1237       raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
1238       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
1239         OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1240         ShouldEmitImportsFiles(ShouldEmitImportsFiles),
1241         LinkedObjectsFile(LinkedObjectsFile), OnWrite(OnWrite) {}
1242 
1243   Error start(
1244       unsigned Task, BitcodeModule BM,
1245       const FunctionImporter::ImportMapTy &ImportList,
1246       const FunctionImporter::ExportSetTy &ExportList,
1247       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1248       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1249     StringRef ModulePath = BM.getModuleIdentifier();
1250     std::string NewModulePath =
1251         getThinLTOOutputFile(std::string(ModulePath), OldPrefix, NewPrefix);
1252 
1253     if (LinkedObjectsFile)
1254       *LinkedObjectsFile << NewModulePath << '\n';
1255 
1256     std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
1257     gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
1258                                      ImportList, ModuleToSummariesForIndex);
1259 
1260     std::error_code EC;
1261     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
1262                       sys::fs::OpenFlags::OF_None);
1263     if (EC)
1264       return errorCodeToError(EC);
1265     WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
1266 
1267     if (ShouldEmitImportsFiles) {
1268       EC = EmitImportsFiles(ModulePath, NewModulePath + ".imports",
1269                             ModuleToSummariesForIndex);
1270       if (EC)
1271         return errorCodeToError(EC);
1272     }
1273 
1274     if (OnWrite)
1275       OnWrite(std::string(ModulePath));
1276     return Error::success();
1277   }
1278 
1279   Error wait() override { return Error::success(); }
1280 };
1281 } // end anonymous namespace
1282 
1283 ThinBackend lto::createWriteIndexesThinBackend(
1284     std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
1285     raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite) {
1286   return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1287              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1288              AddStreamFn AddStream, NativeObjectCache Cache) {
1289     return std::make_unique<WriteIndexesThinBackend>(
1290         Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
1291         ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
1292   };
1293 }
1294 
1295 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
1296                       const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
1297   if (ThinLTO.ModuleMap.empty())
1298     return Error::success();
1299 
1300   if (Conf.CombinedIndexHook &&
1301       !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
1302     return Error::success();
1303 
1304   // Collect for each module the list of function it defines (GUID ->
1305   // Summary).
1306   StringMap<GVSummaryMapTy>
1307       ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
1308   ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1309       ModuleToDefinedGVSummaries);
1310   // Create entries for any modules that didn't have any GV summaries
1311   // (either they didn't have any GVs to start with, or we suppressed
1312   // generation of the summaries because they e.g. had inline assembly
1313   // uses that couldn't be promoted/renamed on export). This is so
1314   // InProcessThinBackend::start can still launch a backend thread, which
1315   // is passed the map of summaries for the module, without any special
1316   // handling for this case.
1317   for (auto &Mod : ThinLTO.ModuleMap)
1318     if (!ModuleToDefinedGVSummaries.count(Mod.first))
1319       ModuleToDefinedGVSummaries.try_emplace(Mod.first);
1320 
1321   // Synthesize entry counts for functions in the CombinedIndex.
1322   computeSyntheticCounts(ThinLTO.CombinedIndex);
1323 
1324   StringMap<FunctionImporter::ImportMapTy> ImportLists(
1325       ThinLTO.ModuleMap.size());
1326   StringMap<FunctionImporter::ExportSetTy> ExportLists(
1327       ThinLTO.ModuleMap.size());
1328   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1329 
1330   if (DumpThinCGSCCs)
1331     ThinLTO.CombinedIndex.dumpSCCs(outs());
1332 
1333   std::set<GlobalValue::GUID> ExportedGUIDs;
1334 
1335   // If allowed, upgrade public vcall visibility to linkage unit visibility in
1336   // the summaries before whole program devirtualization below.
1337   updateVCallVisibilityInIndex(ThinLTO.CombinedIndex,
1338                                Conf.HasWholeProgramVisibility);
1339 
1340   // Perform index-based WPD. This will return immediately if there are
1341   // no index entries in the typeIdMetadata map (e.g. if we are instead
1342   // performing IR-based WPD in hybrid regular/thin LTO mode).
1343   std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1344   runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
1345                                LocalWPDTargetsMap);
1346 
1347   if (Conf.OptLevel > 0)
1348     ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1349                              ImportLists, ExportLists);
1350 
1351   // Figure out which symbols need to be internalized. This also needs to happen
1352   // at -O0 because summary-based DCE is implemented using internalization, and
1353   // we must apply DCE consistently with the full LTO module in order to avoid
1354   // undefined references during the final link.
1355   for (auto &Res : GlobalResolutions) {
1356     // If the symbol does not have external references or it is not prevailing,
1357     // then not need to mark it as exported from a ThinLTO partition.
1358     if (Res.second.Partition != GlobalResolution::External ||
1359         !Res.second.isPrevailingIRSymbol())
1360       continue;
1361     auto GUID = GlobalValue::getGUID(
1362         GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1363     // Mark exported unless index-based analysis determined it to be dead.
1364     if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1365       ExportedGUIDs.insert(GUID);
1366   }
1367 
1368   // Any functions referenced by the jump table in the regular LTO object must
1369   // be exported.
1370   for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1371     ExportedGUIDs.insert(
1372         GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Def)));
1373 
1374   auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
1375     const auto &ExportList = ExportLists.find(ModuleIdentifier);
1376     return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
1377            ExportedGUIDs.count(VI.getGUID());
1378   };
1379 
1380   // Update local devirtualized targets that were exported by cross-module
1381   // importing or by other devirtualizations marked in the ExportedGUIDs set.
1382   updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
1383                            LocalWPDTargetsMap);
1384 
1385   auto isPrevailing = [&](GlobalValue::GUID GUID,
1386                           const GlobalValueSummary *S) {
1387     return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1388   };
1389   thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
1390                                       isPrevailing);
1391 
1392   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1393                               GlobalValue::GUID GUID,
1394                               GlobalValue::LinkageTypes NewLinkage) {
1395     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1396   };
1397   thinLTOResolvePrevailingInIndex(ThinLTO.CombinedIndex, isPrevailing,
1398                                   recordNewLinkage, GUIDPreservedSymbols);
1399 
1400   std::unique_ptr<ThinBackendProc> BackendProc =
1401       ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1402                       AddStream, Cache);
1403 
1404   // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for combined
1405   // module and parallel code generation partitions.
1406   unsigned Task = RegularLTO.ParallelCodeGenParallelismLevel;
1407   for (auto &Mod : ThinLTO.ModuleMap) {
1408     if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1409                                      ExportLists[Mod.first],
1410                                      ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1411       return E;
1412     ++Task;
1413   }
1414 
1415   return BackendProc->wait();
1416 }
1417 
1418 Expected<std::unique_ptr<ToolOutputFile>> lto::setupLLVMOptimizationRemarks(
1419     LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
1420     StringRef RemarksFormat, bool RemarksWithHotness, int Count) {
1421   std::string Filename = std::string(RemarksFilename);
1422   // For ThinLTO, file.opt.<format> becomes
1423   // file.opt.<format>.thin.<num>.<format>.
1424   if (!Filename.empty() && Count != -1)
1425     Filename =
1426         (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
1427             .str();
1428 
1429   auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
1430       Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness);
1431   if (Error E = ResultOrErr.takeError())
1432     return std::move(E);
1433 
1434   if (*ResultOrErr)
1435     (*ResultOrErr)->keep();
1436 
1437   return ResultOrErr;
1438 }
1439 
1440 Expected<std::unique_ptr<ToolOutputFile>>
1441 lto::setupStatsFile(StringRef StatsFilename) {
1442   // Setup output file to emit statistics.
1443   if (StatsFilename.empty())
1444     return nullptr;
1445 
1446   llvm::EnableStatistics(false);
1447   std::error_code EC;
1448   auto StatsFile =
1449       std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
1450   if (EC)
1451     return errorCodeToError(EC);
1452 
1453   StatsFile->keep();
1454   return std::move(StatsFile);
1455 }
1456