xref: /llvm-project-15.0.7/llvm/lib/LTO/LTO.cpp (revision bf02bcff)
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       CommonRes.Align =
761           std::max(CommonRes.Align, MaybeAlign(Sym.getCommonAlignment()));
762       CommonRes.Prevailing |= Res.Prevailing;
763     }
764 
765   }
766   if (!M.getComdatSymbolTable().empty())
767     for (GlobalValue &GV : M.global_values())
768       handleNonPrevailingComdat(GV, NonPrevailingComdats);
769   assert(MsymI == MsymE);
770   return std::move(Mod);
771 }
772 
773 Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
774                           bool LivenessFromIndex) {
775   std::vector<GlobalValue *> Keep;
776   for (GlobalValue *GV : Mod.Keep) {
777     if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
778       if (Function *F = dyn_cast<Function>(GV)) {
779         OptimizationRemarkEmitter ORE(F);
780         ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
781                  << ore::NV("Function", F)
782                  << " not added to the combined module ");
783       }
784       continue;
785     }
786 
787     if (!GV->hasAvailableExternallyLinkage()) {
788       Keep.push_back(GV);
789       continue;
790     }
791 
792     // Only link available_externally definitions if we don't already have a
793     // definition.
794     GlobalValue *CombinedGV =
795         RegularLTO.CombinedModule->getNamedValue(GV->getName());
796     if (CombinedGV && !CombinedGV->isDeclaration())
797       continue;
798 
799     Keep.push_back(GV);
800   }
801 
802   return RegularLTO.Mover->move(std::move(Mod.M), Keep,
803                                 [](GlobalValue &, IRMover::ValueAdder) {},
804                                 /* IsPerformingImport */ false);
805 }
806 
807 // Add a ThinLTO module to the link.
808 Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
809                       const SymbolResolution *&ResI,
810                       const SymbolResolution *ResE) {
811   if (Error Err =
812           BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
813                          ThinLTO.ModuleMap.size()))
814     return Err;
815 
816   for (const InputFile::Symbol &Sym : Syms) {
817     assert(ResI != ResE);
818     SymbolResolution Res = *ResI++;
819 
820     if (!Sym.getIRName().empty()) {
821       auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
822           Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
823       if (Res.Prevailing) {
824         ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
825 
826         // For linker redefined symbols (via --wrap or --defsym) we want to
827         // switch the linkage to `weak` to prevent IPOs from happening.
828         // Find the summary in the module for this very GV and record the new
829         // linkage so that we can switch it when we import the GV.
830         if (Res.LinkerRedefined)
831           if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
832                   GUID, BM.getModuleIdentifier()))
833             S->setLinkage(GlobalValue::WeakAnyLinkage);
834       }
835 
836       // If the linker resolved the symbol to a local definition then mark it
837       // as local in the summary for the module we are adding.
838       if (Res.FinalDefinitionInLinkageUnit) {
839         if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
840                 GUID, BM.getModuleIdentifier())) {
841           S->setDSOLocal(true);
842         }
843       }
844     }
845   }
846 
847   if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
848     return make_error<StringError>(
849         "Expected at most one ThinLTO module per bitcode file",
850         inconvertibleErrorCode());
851 
852   return Error::success();
853 }
854 
855 unsigned LTO::getMaxTasks() const {
856   CalledGetMaxTasks = true;
857   return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
858 }
859 
860 // If only some of the modules were split, we cannot correctly handle
861 // code that contains type tests or type checked loads.
862 Error LTO::checkPartiallySplit() {
863   if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
864     return Error::success();
865 
866   Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
867       Intrinsic::getName(Intrinsic::type_test));
868   Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
869       Intrinsic::getName(Intrinsic::type_checked_load));
870 
871   // First check if there are type tests / type checked loads in the
872   // merged regular LTO module IR.
873   if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
874       (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()))
875     return make_error<StringError>(
876         "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
877         inconvertibleErrorCode());
878 
879   // Otherwise check if there are any recorded in the combined summary from the
880   // ThinLTO modules.
881   for (auto &P : ThinLTO.CombinedIndex) {
882     for (auto &S : P.second.SummaryList) {
883       auto *FS = dyn_cast<FunctionSummary>(S.get());
884       if (!FS)
885         continue;
886       if (!FS->type_test_assume_vcalls().empty() ||
887           !FS->type_checked_load_vcalls().empty() ||
888           !FS->type_test_assume_const_vcalls().empty() ||
889           !FS->type_checked_load_const_vcalls().empty() ||
890           !FS->type_tests().empty())
891         return make_error<StringError>(
892             "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
893             inconvertibleErrorCode());
894     }
895   }
896   return Error::success();
897 }
898 
899 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
900   // Compute "dead" symbols, we don't want to import/export these!
901   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
902   DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
903   for (auto &Res : GlobalResolutions) {
904     // Normally resolution have IR name of symbol. We can do nothing here
905     // otherwise. See comments in GlobalResolution struct for more details.
906     if (Res.second.IRName.empty())
907       continue;
908 
909     GlobalValue::GUID GUID = GlobalValue::getGUID(
910         GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
911 
912     if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
913       GUIDPreservedSymbols.insert(GUID);
914 
915     GUIDPrevailingResolutions[GUID] =
916         Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
917   }
918 
919   auto isPrevailing = [&](GlobalValue::GUID G) {
920     auto It = GUIDPrevailingResolutions.find(G);
921     if (It == GUIDPrevailingResolutions.end())
922       return PrevailingType::Unknown;
923     return It->second;
924   };
925   computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
926                                   isPrevailing, Conf.OptLevel > 0);
927 
928   // Setup output file to emit statistics.
929   auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
930   if (!StatsFileOrErr)
931     return StatsFileOrErr.takeError();
932   std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
933 
934   Error Result = runRegularLTO(AddStream);
935   if (!Result)
936     Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
937 
938   if (StatsFile)
939     PrintStatisticsJSON(StatsFile->os());
940 
941   return Result;
942 }
943 
944 Error LTO::runRegularLTO(AddStreamFn AddStream) {
945   // Setup optimization remarks.
946   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
947       RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename,
948       Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness);
949   if (!DiagFileOrErr)
950     return DiagFileOrErr.takeError();
951 
952   // Finalize linking of regular LTO modules containing summaries now that
953   // we have computed liveness information.
954   for (auto &M : RegularLTO.ModsWithSummaries)
955     if (Error Err = linkRegularLTO(std::move(M),
956                                    /*LivenessFromIndex=*/true))
957       return Err;
958 
959   // Ensure we don't have inconsistently split LTO units with type tests.
960   // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
961   // this path both cases but eventually this should be split into two and
962   // do the ThinLTO checks in `runThinLTO`.
963   if (Error Err = checkPartiallySplit())
964     return Err;
965 
966   // Make sure commons have the right size/alignment: we kept the largest from
967   // all the prevailing when adding the inputs, and we apply it here.
968   const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
969   for (auto &I : RegularLTO.Commons) {
970     if (!I.second.Prevailing)
971       // Don't do anything if no instance of this common was prevailing.
972       continue;
973     GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
974     if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
975       // Don't create a new global if the type is already correct, just make
976       // sure the alignment is correct.
977       OldGV->setAlignment(I.second.Align);
978       continue;
979     }
980     ArrayType *Ty =
981         ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
982     auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
983                                   GlobalValue::CommonLinkage,
984                                   ConstantAggregateZero::get(Ty), "");
985     GV->setAlignment(I.second.Align);
986     if (OldGV) {
987       OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
988       GV->takeName(OldGV);
989       OldGV->eraseFromParent();
990     } else {
991       GV->setName(I.first);
992     }
993   }
994 
995   // If allowed, upgrade public vcall visibility metadata to linkage unit
996   // visibility before whole program devirtualization in the optimizer.
997   updateVCallVisibilityInModule(*RegularLTO.CombinedModule,
998                                 Conf.HasWholeProgramVisibility);
999 
1000   if (Conf.PreOptModuleHook &&
1001       !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1002     return Error::success();
1003 
1004   if (!Conf.CodeGenOnly) {
1005     for (const auto &R : GlobalResolutions) {
1006       if (!R.second.isPrevailingIRSymbol())
1007         continue;
1008       if (R.second.Partition != 0 &&
1009           R.second.Partition != GlobalResolution::External)
1010         continue;
1011 
1012       GlobalValue *GV =
1013           RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
1014       // Ignore symbols defined in other partitions.
1015       // Also skip declarations, which are not allowed to have internal linkage.
1016       if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1017         continue;
1018       GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1019                                               : GlobalValue::UnnamedAddr::None);
1020       if (EnableLTOInternalization && R.second.Partition == 0)
1021         GV->setLinkage(GlobalValue::InternalLinkage);
1022     }
1023 
1024     RegularLTO.CombinedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
1025 
1026     if (Conf.PostInternalizeModuleHook &&
1027         !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1028       return Error::success();
1029   }
1030 
1031   if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1032     if (Error Err = backend(
1033             Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1034             std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex))
1035       return Err;
1036   }
1037 
1038   return finalizeOptimizationRemarks(std::move(*DiagFileOrErr));
1039 }
1040 
1041 static const char *libcallRoutineNames[] = {
1042 #define HANDLE_LIBCALL(code, name) name,
1043 #include "llvm/IR/RuntimeLibcalls.def"
1044 #undef HANDLE_LIBCALL
1045 };
1046 
1047 ArrayRef<const char*> LTO::getRuntimeLibcallSymbols() {
1048   return makeArrayRef(libcallRoutineNames);
1049 }
1050 
1051 /// This class defines the interface to the ThinLTO backend.
1052 class lto::ThinBackendProc {
1053 protected:
1054   const Config &Conf;
1055   ModuleSummaryIndex &CombinedIndex;
1056   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
1057 
1058 public:
1059   ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1060                   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
1061       : Conf(Conf), CombinedIndex(CombinedIndex),
1062         ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
1063 
1064   virtual ~ThinBackendProc() {}
1065   virtual Error start(
1066       unsigned Task, BitcodeModule BM,
1067       const FunctionImporter::ImportMapTy &ImportList,
1068       const FunctionImporter::ExportSetTy &ExportList,
1069       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1070       MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
1071   virtual Error wait() = 0;
1072 };
1073 
1074 namespace {
1075 class InProcessThinBackend : public ThinBackendProc {
1076   ThreadPool BackendThreadPool;
1077   AddStreamFn AddStream;
1078   NativeObjectCache Cache;
1079   std::set<GlobalValue::GUID> CfiFunctionDefs;
1080   std::set<GlobalValue::GUID> CfiFunctionDecls;
1081 
1082   Optional<Error> Err;
1083   std::mutex ErrMu;
1084 
1085 public:
1086   InProcessThinBackend(
1087       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1088       ThreadPoolStrategy ThinLTOParallelism,
1089       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1090       AddStreamFn AddStream, NativeObjectCache Cache)
1091       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
1092         BackendThreadPool(ThinLTOParallelism), AddStream(std::move(AddStream)),
1093         Cache(std::move(Cache)) {
1094     for (auto &Name : CombinedIndex.cfiFunctionDefs())
1095       CfiFunctionDefs.insert(
1096           GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1097     for (auto &Name : CombinedIndex.cfiFunctionDecls())
1098       CfiFunctionDecls.insert(
1099           GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1100   }
1101 
1102   Error runThinLTOBackendThread(
1103       AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
1104       BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1105       const FunctionImporter::ImportMapTy &ImportList,
1106       const FunctionImporter::ExportSetTy &ExportList,
1107       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1108       const GVSummaryMapTy &DefinedGlobals,
1109       MapVector<StringRef, BitcodeModule> &ModuleMap) {
1110     auto RunThinBackend = [&](AddStreamFn AddStream) {
1111       LTOLLVMContext BackendContext(Conf);
1112       Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1113       if (!MOrErr)
1114         return MOrErr.takeError();
1115 
1116       return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1117                          ImportList, DefinedGlobals, ModuleMap);
1118     };
1119 
1120     auto ModuleID = BM.getModuleIdentifier();
1121 
1122     if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
1123         all_of(CombinedIndex.getModuleHash(ModuleID),
1124                [](uint32_t V) { return V == 0; }))
1125       // Cache disabled or no entry for this module in the combined index or
1126       // no module hash.
1127       return RunThinBackend(AddStream);
1128 
1129     SmallString<40> Key;
1130     // The module may be cached, this helps handling it.
1131     computeLTOCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList,
1132                        ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
1133                        CfiFunctionDecls);
1134     if (AddStreamFn CacheAddStream = Cache(Task, Key))
1135       return RunThinBackend(CacheAddStream);
1136 
1137     return Error::success();
1138   }
1139 
1140   Error start(
1141       unsigned Task, BitcodeModule BM,
1142       const FunctionImporter::ImportMapTy &ImportList,
1143       const FunctionImporter::ExportSetTy &ExportList,
1144       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1145       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1146     StringRef ModulePath = BM.getModuleIdentifier();
1147     assert(ModuleToDefinedGVSummaries.count(ModulePath));
1148     const GVSummaryMapTy &DefinedGlobals =
1149         ModuleToDefinedGVSummaries.find(ModulePath)->second;
1150     BackendThreadPool.async(
1151         [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1152             const FunctionImporter::ImportMapTy &ImportList,
1153             const FunctionImporter::ExportSetTy &ExportList,
1154             const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1155                 &ResolvedODR,
1156             const GVSummaryMapTy &DefinedGlobals,
1157             MapVector<StringRef, BitcodeModule> &ModuleMap) {
1158           if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1159             timeTraceProfilerInitialize(Conf.TimeTraceGranularity,
1160                                         "thin backend");
1161           Error E = runThinLTOBackendThread(
1162               AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1163               ResolvedODR, DefinedGlobals, ModuleMap);
1164           if (E) {
1165             std::unique_lock<std::mutex> L(ErrMu);
1166             if (Err)
1167               Err = joinErrors(std::move(*Err), std::move(E));
1168             else
1169               Err = std::move(E);
1170           }
1171           if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1172             timeTraceProfilerFinishThread();
1173         },
1174         BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1175         std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1176     return Error::success();
1177   }
1178 
1179   Error wait() override {
1180     BackendThreadPool.wait();
1181     if (Err)
1182       return std::move(*Err);
1183     else
1184       return Error::success();
1185   }
1186 };
1187 } // end anonymous namespace
1188 
1189 ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism) {
1190   return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1191              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1192              AddStreamFn AddStream, NativeObjectCache Cache) {
1193     return std::make_unique<InProcessThinBackend>(
1194         Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries, AddStream,
1195         Cache);
1196   };
1197 }
1198 
1199 // Given the original \p Path to an output file, replace any path
1200 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1201 // resulting directory if it does not yet exist.
1202 std::string lto::getThinLTOOutputFile(const std::string &Path,
1203                                       const std::string &OldPrefix,
1204                                       const std::string &NewPrefix) {
1205   if (OldPrefix.empty() && NewPrefix.empty())
1206     return Path;
1207   SmallString<128> NewPath(Path);
1208   llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
1209   StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
1210   if (!ParentPath.empty()) {
1211     // Make sure the new directory exists, creating it if necessary.
1212     if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
1213       llvm::errs() << "warning: could not create directory '" << ParentPath
1214                    << "': " << EC.message() << '\n';
1215   }
1216   return std::string(NewPath.str());
1217 }
1218 
1219 namespace {
1220 class WriteIndexesThinBackend : public ThinBackendProc {
1221   std::string OldPrefix, NewPrefix;
1222   bool ShouldEmitImportsFiles;
1223   raw_fd_ostream *LinkedObjectsFile;
1224   lto::IndexWriteCallback OnWrite;
1225 
1226 public:
1227   WriteIndexesThinBackend(
1228       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1229       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1230       std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
1231       raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
1232       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
1233         OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1234         ShouldEmitImportsFiles(ShouldEmitImportsFiles),
1235         LinkedObjectsFile(LinkedObjectsFile), OnWrite(OnWrite) {}
1236 
1237   Error start(
1238       unsigned Task, BitcodeModule BM,
1239       const FunctionImporter::ImportMapTy &ImportList,
1240       const FunctionImporter::ExportSetTy &ExportList,
1241       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1242       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1243     StringRef ModulePath = BM.getModuleIdentifier();
1244     std::string NewModulePath =
1245         getThinLTOOutputFile(std::string(ModulePath), OldPrefix, NewPrefix);
1246 
1247     if (LinkedObjectsFile)
1248       *LinkedObjectsFile << NewModulePath << '\n';
1249 
1250     std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
1251     gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
1252                                      ImportList, ModuleToSummariesForIndex);
1253 
1254     std::error_code EC;
1255     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
1256                       sys::fs::OpenFlags::OF_None);
1257     if (EC)
1258       return errorCodeToError(EC);
1259     WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
1260 
1261     if (ShouldEmitImportsFiles) {
1262       EC = EmitImportsFiles(ModulePath, NewModulePath + ".imports",
1263                             ModuleToSummariesForIndex);
1264       if (EC)
1265         return errorCodeToError(EC);
1266     }
1267 
1268     if (OnWrite)
1269       OnWrite(std::string(ModulePath));
1270     return Error::success();
1271   }
1272 
1273   Error wait() override { return Error::success(); }
1274 };
1275 } // end anonymous namespace
1276 
1277 ThinBackend lto::createWriteIndexesThinBackend(
1278     std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
1279     raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite) {
1280   return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1281              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1282              AddStreamFn AddStream, NativeObjectCache Cache) {
1283     return std::make_unique<WriteIndexesThinBackend>(
1284         Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
1285         ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
1286   };
1287 }
1288 
1289 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
1290                       const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
1291   if (ThinLTO.ModuleMap.empty())
1292     return Error::success();
1293 
1294   if (Conf.CombinedIndexHook &&
1295       !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
1296     return Error::success();
1297 
1298   // Collect for each module the list of function it defines (GUID ->
1299   // Summary).
1300   StringMap<GVSummaryMapTy>
1301       ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
1302   ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1303       ModuleToDefinedGVSummaries);
1304   // Create entries for any modules that didn't have any GV summaries
1305   // (either they didn't have any GVs to start with, or we suppressed
1306   // generation of the summaries because they e.g. had inline assembly
1307   // uses that couldn't be promoted/renamed on export). This is so
1308   // InProcessThinBackend::start can still launch a backend thread, which
1309   // is passed the map of summaries for the module, without any special
1310   // handling for this case.
1311   for (auto &Mod : ThinLTO.ModuleMap)
1312     if (!ModuleToDefinedGVSummaries.count(Mod.first))
1313       ModuleToDefinedGVSummaries.try_emplace(Mod.first);
1314 
1315   // Synthesize entry counts for functions in the CombinedIndex.
1316   computeSyntheticCounts(ThinLTO.CombinedIndex);
1317 
1318   StringMap<FunctionImporter::ImportMapTy> ImportLists(
1319       ThinLTO.ModuleMap.size());
1320   StringMap<FunctionImporter::ExportSetTy> ExportLists(
1321       ThinLTO.ModuleMap.size());
1322   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1323 
1324   if (DumpThinCGSCCs)
1325     ThinLTO.CombinedIndex.dumpSCCs(outs());
1326 
1327   std::set<GlobalValue::GUID> ExportedGUIDs;
1328 
1329   // If allowed, upgrade public vcall visibility to linkage unit visibility in
1330   // the summaries before whole program devirtualization below.
1331   updateVCallVisibilityInIndex(ThinLTO.CombinedIndex,
1332                                Conf.HasWholeProgramVisibility);
1333 
1334   // Perform index-based WPD. This will return immediately if there are
1335   // no index entries in the typeIdMetadata map (e.g. if we are instead
1336   // performing IR-based WPD in hybrid regular/thin LTO mode).
1337   std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1338   runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
1339                                LocalWPDTargetsMap);
1340 
1341   if (Conf.OptLevel > 0)
1342     ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1343                              ImportLists, ExportLists);
1344 
1345   // Figure out which symbols need to be internalized. This also needs to happen
1346   // at -O0 because summary-based DCE is implemented using internalization, and
1347   // we must apply DCE consistently with the full LTO module in order to avoid
1348   // undefined references during the final link.
1349   for (auto &Res : GlobalResolutions) {
1350     // If the symbol does not have external references or it is not prevailing,
1351     // then not need to mark it as exported from a ThinLTO partition.
1352     if (Res.second.Partition != GlobalResolution::External ||
1353         !Res.second.isPrevailingIRSymbol())
1354       continue;
1355     auto GUID = GlobalValue::getGUID(
1356         GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1357     // Mark exported unless index-based analysis determined it to be dead.
1358     if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1359       ExportedGUIDs.insert(GUID);
1360   }
1361 
1362   // Any functions referenced by the jump table in the regular LTO object must
1363   // be exported.
1364   for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1365     ExportedGUIDs.insert(
1366         GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Def)));
1367 
1368   auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
1369     const auto &ExportList = ExportLists.find(ModuleIdentifier);
1370     return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
1371            ExportedGUIDs.count(VI.getGUID());
1372   };
1373 
1374   // Update local devirtualized targets that were exported by cross-module
1375   // importing or by other devirtualizations marked in the ExportedGUIDs set.
1376   updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
1377                            LocalWPDTargetsMap);
1378 
1379   auto isPrevailing = [&](GlobalValue::GUID GUID,
1380                           const GlobalValueSummary *S) {
1381     return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1382   };
1383   thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
1384                                       isPrevailing);
1385 
1386   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1387                               GlobalValue::GUID GUID,
1388                               GlobalValue::LinkageTypes NewLinkage) {
1389     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1390   };
1391   thinLTOResolvePrevailingInIndex(ThinLTO.CombinedIndex, isPrevailing,
1392                                   recordNewLinkage, GUIDPreservedSymbols);
1393 
1394   std::unique_ptr<ThinBackendProc> BackendProc =
1395       ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1396                       AddStream, Cache);
1397 
1398   // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for combined
1399   // module and parallel code generation partitions.
1400   unsigned Task = RegularLTO.ParallelCodeGenParallelismLevel;
1401   for (auto &Mod : ThinLTO.ModuleMap) {
1402     if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1403                                      ExportLists[Mod.first],
1404                                      ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1405       return E;
1406     ++Task;
1407   }
1408 
1409   return BackendProc->wait();
1410 }
1411 
1412 Expected<std::unique_ptr<ToolOutputFile>> lto::setupLLVMOptimizationRemarks(
1413     LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
1414     StringRef RemarksFormat, bool RemarksWithHotness, int Count) {
1415   std::string Filename = std::string(RemarksFilename);
1416   // For ThinLTO, file.opt.<format> becomes
1417   // file.opt.<format>.thin.<num>.<format>.
1418   if (!Filename.empty() && Count != -1)
1419     Filename =
1420         (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
1421             .str();
1422 
1423   auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
1424       Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness);
1425   if (Error E = ResultOrErr.takeError())
1426     return std::move(E);
1427 
1428   if (*ResultOrErr)
1429     (*ResultOrErr)->keep();
1430 
1431   return ResultOrErr;
1432 }
1433 
1434 Expected<std::unique_ptr<ToolOutputFile>>
1435 lto::setupStatsFile(StringRef StatsFilename) {
1436   // Setup output file to emit statistics.
1437   if (StatsFilename.empty())
1438     return nullptr;
1439 
1440   llvm::EnableStatistics(false);
1441   std::error_code EC;
1442   auto StatsFile =
1443       std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
1444   if (EC)
1445     return errorCodeToError(EC);
1446 
1447   StatsFile->keep();
1448   return std::move(StatsFile);
1449 }
1450