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