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