xref: /llvm-project-15.0.7/llvm/lib/LTO/LTO.cpp (revision c1121908)
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 = createInProcessThinBackend();
481 }
482 
483 LTO::LTO(Config Conf, ThinBackend Backend,
484          unsigned ParallelCodeGenParallelismLevel)
485     : Conf(std::move(Conf)),
486       RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
487       ThinLTO(std::move(Backend)) {}
488 
489 // Requires a destructor for MapVector<BitcodeModule>.
490 LTO::~LTO() = default;
491 
492 // Add the symbols in the given module to the GlobalResolutions map, and resolve
493 // their partitions.
494 void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
495                                ArrayRef<SymbolResolution> Res,
496                                unsigned Partition, bool InSummary) {
497   auto *ResI = Res.begin();
498   auto *ResE = Res.end();
499   (void)ResE;
500   for (const InputFile::Symbol &Sym : Syms) {
501     assert(ResI != ResE);
502     SymbolResolution Res = *ResI++;
503 
504     StringRef Name = Sym.getName();
505     Triple TT(RegularLTO.CombinedModule->getTargetTriple());
506     // Strip the __imp_ prefix from COFF dllimport symbols (similar to the
507     // way they are handled by lld), otherwise we can end up with two
508     // global resolutions (one with and one for a copy of the symbol without).
509     if (TT.isOSBinFormatCOFF() && Name.startswith("__imp_"))
510       Name = Name.substr(strlen("__imp_"));
511     auto &GlobalRes = GlobalResolutions[Name];
512     GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
513     if (Res.Prevailing) {
514       assert(!GlobalRes.Prevailing &&
515              "Multiple prevailing defs are not allowed");
516       GlobalRes.Prevailing = true;
517       GlobalRes.IRName = std::string(Sym.getIRName());
518     } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
519       // Sometimes it can be two copies of symbol in a module and prevailing
520       // symbol can have no IR name. That might happen if symbol is defined in
521       // module level inline asm block. In case we have multiple modules with
522       // the same symbol we want to use IR name of the prevailing symbol.
523       // Otherwise, if we haven't seen a prevailing symbol, set the name so that
524       // we can later use it to check if there is any prevailing copy in IR.
525       GlobalRes.IRName = std::string(Sym.getIRName());
526     }
527 
528     // Set the partition to external if we know it is re-defined by the linker
529     // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
530     // regular object, is referenced from llvm.compiler_used, or was already
531     // recorded as being referenced from a different partition.
532     if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
533         (GlobalRes.Partition != GlobalResolution::Unknown &&
534          GlobalRes.Partition != Partition)) {
535       GlobalRes.Partition = GlobalResolution::External;
536     } else
537       // First recorded reference, save the current partition.
538       GlobalRes.Partition = Partition;
539 
540     // Flag as visible outside of summary if visible from a regular object or
541     // from a module that does not have a summary.
542     GlobalRes.VisibleOutsideSummary |=
543         (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
544   }
545 }
546 
547 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
548                                   ArrayRef<SymbolResolution> Res) {
549   StringRef Path = Input->getName();
550   OS << Path << '\n';
551   auto ResI = Res.begin();
552   for (const InputFile::Symbol &Sym : Input->symbols()) {
553     assert(ResI != Res.end());
554     SymbolResolution Res = *ResI++;
555 
556     OS << "-r=" << Path << ',' << Sym.getName() << ',';
557     if (Res.Prevailing)
558       OS << 'p';
559     if (Res.FinalDefinitionInLinkageUnit)
560       OS << 'l';
561     if (Res.VisibleToRegularObj)
562       OS << 'x';
563     if (Res.LinkerRedefined)
564       OS << 'r';
565     OS << '\n';
566   }
567   OS.flush();
568   assert(ResI == Res.end());
569 }
570 
571 Error LTO::add(std::unique_ptr<InputFile> Input,
572                ArrayRef<SymbolResolution> Res) {
573   assert(!CalledGetMaxTasks);
574 
575   if (Conf.ResolutionFile)
576     writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
577 
578   if (RegularLTO.CombinedModule->getTargetTriple().empty())
579     RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
580 
581   const SymbolResolution *ResI = Res.begin();
582   for (unsigned I = 0; I != Input->Mods.size(); ++I)
583     if (Error Err = addModule(*Input, I, ResI, Res.end()))
584       return Err;
585 
586   assert(ResI == Res.end());
587   return Error::success();
588 }
589 
590 Error LTO::addModule(InputFile &Input, unsigned ModI,
591                      const SymbolResolution *&ResI,
592                      const SymbolResolution *ResE) {
593   Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
594   if (!LTOInfo)
595     return LTOInfo.takeError();
596 
597   if (EnableSplitLTOUnit.hasValue()) {
598     // If only some modules were split, flag this in the index so that
599     // we can skip or error on optimizations that need consistently split
600     // modules (whole program devirt and lower type tests).
601     if (EnableSplitLTOUnit.getValue() != LTOInfo->EnableSplitLTOUnit)
602       ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
603   } else
604     EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
605 
606   BitcodeModule BM = Input.Mods[ModI];
607   auto ModSyms = Input.module_symbols(ModI);
608   addModuleToGlobalRes(ModSyms, {ResI, ResE},
609                        LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
610                        LTOInfo->HasSummary);
611 
612   if (LTOInfo->IsThinLTO)
613     return addThinLTO(BM, ModSyms, ResI, ResE);
614 
615   Expected<RegularLTOState::AddedModule> ModOrErr =
616       addRegularLTO(BM, ModSyms, ResI, ResE);
617   if (!ModOrErr)
618     return ModOrErr.takeError();
619 
620   if (!LTOInfo->HasSummary)
621     return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false);
622 
623   // Regular LTO module summaries are added to a dummy module that represents
624   // the combined regular LTO module.
625   if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, "", -1ull))
626     return Err;
627   RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
628   return Error::success();
629 }
630 
631 // Checks whether the given global value is in a non-prevailing comdat
632 // (comdat containing values the linker indicated were not prevailing,
633 // which we then dropped to available_externally), and if so, removes
634 // it from the comdat. This is called for all global values to ensure the
635 // comdat is empty rather than leaving an incomplete comdat. It is needed for
636 // regular LTO modules, in case we are in a mixed-LTO mode (both regular
637 // and thin LTO modules) compilation. Since the regular LTO module will be
638 // linked first in the final native link, we want to make sure the linker
639 // doesn't select any of these incomplete comdats that would be left
640 // in the regular LTO module without this cleanup.
641 static void
642 handleNonPrevailingComdat(GlobalValue &GV,
643                           std::set<const Comdat *> &NonPrevailingComdats) {
644   Comdat *C = GV.getComdat();
645   if (!C)
646     return;
647 
648   if (!NonPrevailingComdats.count(C))
649     return;
650 
651   // Additionally need to drop externally visible global values from the comdat
652   // to available_externally, so that there aren't multiply defined linker
653   // errors.
654   if (!GV.hasLocalLinkage())
655     GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
656 
657   if (auto GO = dyn_cast<GlobalObject>(&GV))
658     GO->setComdat(nullptr);
659 }
660 
661 // Add a regular LTO object to the link.
662 // The resulting module needs to be linked into the combined LTO module with
663 // linkRegularLTO.
664 Expected<LTO::RegularLTOState::AddedModule>
665 LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
666                    const SymbolResolution *&ResI,
667                    const SymbolResolution *ResE) {
668   RegularLTOState::AddedModule Mod;
669   Expected<std::unique_ptr<Module>> MOrErr =
670       BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
671                        /*IsImporting*/ false);
672   if (!MOrErr)
673     return MOrErr.takeError();
674   Module &M = **MOrErr;
675   Mod.M = std::move(*MOrErr);
676 
677   if (Error Err = M.materializeMetadata())
678     return std::move(Err);
679   UpgradeDebugInfo(M);
680 
681   ModuleSymbolTable SymTab;
682   SymTab.addModule(&M);
683 
684   for (GlobalVariable &GV : M.globals())
685     if (GV.hasAppendingLinkage())
686       Mod.Keep.push_back(&GV);
687 
688   DenseSet<GlobalObject *> AliasedGlobals;
689   for (auto &GA : M.aliases())
690     if (GlobalObject *GO = GA.getBaseObject())
691       AliasedGlobals.insert(GO);
692 
693   // In this function we need IR GlobalValues matching the symbols in Syms
694   // (which is not backed by a module), so we need to enumerate them in the same
695   // order. The symbol enumeration order of a ModuleSymbolTable intentionally
696   // matches the order of an irsymtab, but when we read the irsymtab in
697   // InputFile::create we omit some symbols that are irrelevant to LTO. The
698   // Skip() function skips the same symbols from the module as InputFile does
699   // from the symbol table.
700   auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
701   auto Skip = [&]() {
702     while (MsymI != MsymE) {
703       auto Flags = SymTab.getSymbolFlags(*MsymI);
704       if ((Flags & object::BasicSymbolRef::SF_Global) &&
705           !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
706         return;
707       ++MsymI;
708     }
709   };
710   Skip();
711 
712   std::set<const Comdat *> NonPrevailingComdats;
713   for (const InputFile::Symbol &Sym : Syms) {
714     assert(ResI != ResE);
715     SymbolResolution Res = *ResI++;
716 
717     assert(MsymI != MsymE);
718     ModuleSymbolTable::Symbol Msym = *MsymI++;
719     Skip();
720 
721     if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
722       if (Res.Prevailing) {
723         if (Sym.isUndefined())
724           continue;
725         Mod.Keep.push_back(GV);
726         // For symbols re-defined with linker -wrap and -defsym options,
727         // set the linkage to weak to inhibit IPO. The linkage will be
728         // restored by the linker.
729         if (Res.LinkerRedefined)
730           GV->setLinkage(GlobalValue::WeakAnyLinkage);
731 
732         GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
733         if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
734           GV->setLinkage(GlobalValue::getWeakLinkage(
735               GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
736       } else if (isa<GlobalObject>(GV) &&
737                  (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
738                   GV->hasAvailableExternallyLinkage()) &&
739                  !AliasedGlobals.count(cast<GlobalObject>(GV))) {
740         // Any of the above three types of linkage indicates that the
741         // chosen prevailing symbol will have the same semantics as this copy of
742         // the symbol, so we may be able to link it with available_externally
743         // linkage. We will decide later whether to do that when we link this
744         // module (in linkRegularLTO), based on whether it is undefined.
745         Mod.Keep.push_back(GV);
746         GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
747         if (GV->hasComdat())
748           NonPrevailingComdats.insert(GV->getComdat());
749         cast<GlobalObject>(GV)->setComdat(nullptr);
750       }
751 
752       // Set the 'local' flag based on the linker resolution for this symbol.
753       if (Res.FinalDefinitionInLinkageUnit) {
754         GV->setDSOLocal(true);
755         if (GV->hasDLLImportStorageClass())
756           GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
757                                  DefaultStorageClass);
758       }
759     }
760     // Common resolution: collect the maximum size/alignment over all commons.
761     // We also record if we see an instance of a common as prevailing, so that
762     // if none is prevailing we can ignore it later.
763     if (Sym.isCommon()) {
764       // FIXME: We should figure out what to do about commons defined by asm.
765       // For now they aren't reported correctly by ModuleSymbolTable.
766       auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
767       CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
768       CommonRes.Align =
769           std::max(CommonRes.Align, MaybeAlign(Sym.getCommonAlignment()));
770       CommonRes.Prevailing |= Res.Prevailing;
771     }
772 
773   }
774   if (!M.getComdatSymbolTable().empty())
775     for (GlobalValue &GV : M.global_values())
776       handleNonPrevailingComdat(GV, NonPrevailingComdats);
777   assert(MsymI == MsymE);
778   return std::move(Mod);
779 }
780 
781 Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
782                           bool LivenessFromIndex) {
783   std::vector<GlobalValue *> Keep;
784   for (GlobalValue *GV : Mod.Keep) {
785     if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
786       if (Function *F = dyn_cast<Function>(GV)) {
787         OptimizationRemarkEmitter ORE(F);
788         ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
789                  << ore::NV("Function", F)
790                  << " not added to the combined module ");
791       }
792       continue;
793     }
794 
795     if (!GV->hasAvailableExternallyLinkage()) {
796       Keep.push_back(GV);
797       continue;
798     }
799 
800     // Only link available_externally definitions if we don't already have a
801     // definition.
802     GlobalValue *CombinedGV =
803         RegularLTO.CombinedModule->getNamedValue(GV->getName());
804     if (CombinedGV && !CombinedGV->isDeclaration())
805       continue;
806 
807     Keep.push_back(GV);
808   }
809 
810   return RegularLTO.Mover->move(std::move(Mod.M), Keep,
811                                 [](GlobalValue &, IRMover::ValueAdder) {},
812                                 /* IsPerformingImport */ false);
813 }
814 
815 // Add a ThinLTO module to the link.
816 Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
817                       const SymbolResolution *&ResI,
818                       const SymbolResolution *ResE) {
819   if (Error Err =
820           BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
821                          ThinLTO.ModuleMap.size()))
822     return Err;
823 
824   for (const InputFile::Symbol &Sym : Syms) {
825     assert(ResI != ResE);
826     SymbolResolution Res = *ResI++;
827 
828     if (!Sym.getIRName().empty()) {
829       auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
830           Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
831       if (Res.Prevailing) {
832         ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
833 
834         // For linker redefined symbols (via --wrap or --defsym) we want to
835         // switch the linkage to `weak` to prevent IPOs from happening.
836         // Find the summary in the module for this very GV and record the new
837         // linkage so that we can switch it when we import the GV.
838         if (Res.LinkerRedefined)
839           if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
840                   GUID, BM.getModuleIdentifier()))
841             S->setLinkage(GlobalValue::WeakAnyLinkage);
842       }
843 
844       // If the linker resolved the symbol to a local definition then mark it
845       // as local in the summary for the module we are adding.
846       if (Res.FinalDefinitionInLinkageUnit) {
847         if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
848                 GUID, BM.getModuleIdentifier())) {
849           S->setDSOLocal(true);
850         }
851       }
852     }
853   }
854 
855   if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
856     return make_error<StringError>(
857         "Expected at most one ThinLTO module per bitcode file",
858         inconvertibleErrorCode());
859 
860   return Error::success();
861 }
862 
863 unsigned LTO::getMaxTasks() const {
864   CalledGetMaxTasks = true;
865   return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
866 }
867 
868 // If only some of the modules were split, we cannot correctly handle
869 // code that contains type tests or type checked loads.
870 Error LTO::checkPartiallySplit() {
871   if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
872     return Error::success();
873 
874   Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
875       Intrinsic::getName(Intrinsic::type_test));
876   Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
877       Intrinsic::getName(Intrinsic::type_checked_load));
878 
879   // First check if there are type tests / type checked loads in the
880   // merged regular LTO module IR.
881   if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
882       (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()))
883     return make_error<StringError>(
884         "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
885         inconvertibleErrorCode());
886 
887   // Otherwise check if there are any recorded in the combined summary from the
888   // ThinLTO modules.
889   for (auto &P : ThinLTO.CombinedIndex) {
890     for (auto &S : P.second.SummaryList) {
891       auto *FS = dyn_cast<FunctionSummary>(S.get());
892       if (!FS)
893         continue;
894       if (!FS->type_test_assume_vcalls().empty() ||
895           !FS->type_checked_load_vcalls().empty() ||
896           !FS->type_test_assume_const_vcalls().empty() ||
897           !FS->type_checked_load_const_vcalls().empty() ||
898           !FS->type_tests().empty())
899         return make_error<StringError>(
900             "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
901             inconvertibleErrorCode());
902     }
903   }
904   return Error::success();
905 }
906 
907 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
908   // Compute "dead" symbols, we don't want to import/export these!
909   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
910   DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
911   for (auto &Res : GlobalResolutions) {
912     // Normally resolution have IR name of symbol. We can do nothing here
913     // otherwise. See comments in GlobalResolution struct for more details.
914     if (Res.second.IRName.empty())
915       continue;
916 
917     GlobalValue::GUID GUID = GlobalValue::getGUID(
918         GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
919 
920     if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
921       GUIDPreservedSymbols.insert(GUID);
922 
923     GUIDPrevailingResolutions[GUID] =
924         Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
925   }
926 
927   auto isPrevailing = [&](GlobalValue::GUID G) {
928     auto It = GUIDPrevailingResolutions.find(G);
929     if (It == GUIDPrevailingResolutions.end())
930       return PrevailingType::Unknown;
931     return It->second;
932   };
933   computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
934                                   isPrevailing, Conf.OptLevel > 0);
935 
936   // Setup output file to emit statistics.
937   auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
938   if (!StatsFileOrErr)
939     return StatsFileOrErr.takeError();
940   std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
941 
942   Error Result = runRegularLTO(AddStream);
943   if (!Result)
944     Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
945 
946   if (StatsFile)
947     PrintStatisticsJSON(StatsFile->os());
948 
949   return Result;
950 }
951 
952 Error LTO::runRegularLTO(AddStreamFn AddStream) {
953   // Setup optimization remarks.
954   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
955       RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename,
956       Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness);
957   if (!DiagFileOrErr)
958     return DiagFileOrErr.takeError();
959 
960   // Finalize linking of regular LTO modules containing summaries now that
961   // we have computed liveness information.
962   for (auto &M : RegularLTO.ModsWithSummaries)
963     if (Error Err = linkRegularLTO(std::move(M),
964                                    /*LivenessFromIndex=*/true))
965       return Err;
966 
967   // Ensure we don't have inconsistently split LTO units with type tests.
968   // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
969   // this path both cases but eventually this should be split into two and
970   // do the ThinLTO checks in `runThinLTO`.
971   if (Error Err = checkPartiallySplit())
972     return Err;
973 
974   // Make sure commons have the right size/alignment: we kept the largest from
975   // all the prevailing when adding the inputs, and we apply it here.
976   const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
977   for (auto &I : RegularLTO.Commons) {
978     if (!I.second.Prevailing)
979       // Don't do anything if no instance of this common was prevailing.
980       continue;
981     GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
982     if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
983       // Don't create a new global if the type is already correct, just make
984       // sure the alignment is correct.
985       OldGV->setAlignment(I.second.Align);
986       continue;
987     }
988     ArrayType *Ty =
989         ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
990     auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
991                                   GlobalValue::CommonLinkage,
992                                   ConstantAggregateZero::get(Ty), "");
993     GV->setAlignment(I.second.Align);
994     if (OldGV) {
995       OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
996       GV->takeName(OldGV);
997       OldGV->eraseFromParent();
998     } else {
999       GV->setName(I.first);
1000     }
1001   }
1002 
1003   // If allowed, upgrade public vcall visibility metadata to linkage unit
1004   // visibility before whole program devirtualization in the optimizer.
1005   updateVCallVisibilityInModule(*RegularLTO.CombinedModule,
1006                                 Conf.HasWholeProgramVisibility);
1007 
1008   if (Conf.PreOptModuleHook &&
1009       !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1010     return Error::success();
1011 
1012   if (!Conf.CodeGenOnly) {
1013     for (const auto &R : GlobalResolutions) {
1014       if (!R.second.isPrevailingIRSymbol())
1015         continue;
1016       if (R.second.Partition != 0 &&
1017           R.second.Partition != GlobalResolution::External)
1018         continue;
1019 
1020       GlobalValue *GV =
1021           RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
1022       // Ignore symbols defined in other partitions.
1023       // Also skip declarations, which are not allowed to have internal linkage.
1024       if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1025         continue;
1026       GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1027                                               : GlobalValue::UnnamedAddr::None);
1028       if (EnableLTOInternalization && R.second.Partition == 0)
1029         GV->setLinkage(GlobalValue::InternalLinkage);
1030     }
1031 
1032     RegularLTO.CombinedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
1033 
1034     if (Conf.PostInternalizeModuleHook &&
1035         !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1036       return Error::success();
1037   }
1038   if (Error Err =
1039           backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1040                   std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex))
1041     return Err;
1042 
1043   return finalizeOptimizationRemarks(std::move(*DiagFileOrErr));
1044 }
1045 
1046 static const char *libcallRoutineNames[] = {
1047 #define HANDLE_LIBCALL(code, name) name,
1048 #include "llvm/IR/RuntimeLibcalls.def"
1049 #undef HANDLE_LIBCALL
1050 };
1051 
1052 ArrayRef<const char*> LTO::getRuntimeLibcallSymbols() {
1053   return makeArrayRef(libcallRoutineNames);
1054 }
1055 
1056 /// This class defines the interface to the ThinLTO backend.
1057 class lto::ThinBackendProc {
1058 protected:
1059   const Config &Conf;
1060   ModuleSummaryIndex &CombinedIndex;
1061   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
1062 
1063 public:
1064   ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1065                   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
1066       : Conf(Conf), CombinedIndex(CombinedIndex),
1067         ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
1068 
1069   virtual ~ThinBackendProc() {}
1070   virtual Error start(
1071       unsigned Task, BitcodeModule BM,
1072       const FunctionImporter::ImportMapTy &ImportList,
1073       const FunctionImporter::ExportSetTy &ExportList,
1074       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1075       MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
1076   virtual Error wait() = 0;
1077 };
1078 
1079 namespace {
1080 class InProcessThinBackend : public ThinBackendProc {
1081   ThreadPool BackendThreadPool;
1082   AddStreamFn AddStream;
1083   NativeObjectCache Cache;
1084   std::set<GlobalValue::GUID> CfiFunctionDefs;
1085   std::set<GlobalValue::GUID> CfiFunctionDecls;
1086 
1087   Optional<Error> Err;
1088   std::mutex ErrMu;
1089 
1090 public:
1091   InProcessThinBackend(
1092       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1093       unsigned ThinLTOParallelismLevel,
1094       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1095       AddStreamFn AddStream, NativeObjectCache Cache)
1096       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
1097         BackendThreadPool(
1098             heavyweight_hardware_concurrency(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