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