xref: /llvm-project-15.0.7/llvm/lib/LTO/LTO.cpp (revision 4deabc97)
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   // Compute the unique hash for this entry.
70   // This is based on the current compiler version, the module itself, the
71   // export list, the hash for every single module in the import list, the
72   // list of ResolvedODR for the module, and the list of preserved symbols.
73   SHA1 Hasher;
74 
75   // Start with the compiler revision
76   Hasher.update(LLVM_VERSION_STRING);
77 #ifdef LLVM_REVISION
78   Hasher.update(LLVM_REVISION);
79 #endif
80 
81   // Include the parts of the LTO configuration that affect code generation.
82   auto AddString = [&](StringRef Str) {
83     Hasher.update(Str);
84     Hasher.update(ArrayRef<uint8_t>{0});
85   };
86   auto AddUnsigned = [&](unsigned I) {
87     uint8_t Data[4];
88     Data[0] = I;
89     Data[1] = I >> 8;
90     Data[2] = I >> 16;
91     Data[3] = I >> 24;
92     Hasher.update(ArrayRef<uint8_t>{Data, 4});
93   };
94   auto AddUint64 = [&](uint64_t I) {
95     uint8_t Data[8];
96     Data[0] = I;
97     Data[1] = I >> 8;
98     Data[2] = I >> 16;
99     Data[3] = I >> 24;
100     Data[4] = I >> 32;
101     Data[5] = I >> 40;
102     Data[6] = I >> 48;
103     Data[7] = I >> 56;
104     Hasher.update(ArrayRef<uint8_t>{Data, 8});
105   };
106   AddString(Conf.CPU);
107   // FIXME: Hash more of Options. For now all clients initialize Options from
108   // command-line flags (which is unsupported in production), but may set
109   // RelaxELFRelocations. The clang driver can also pass FunctionSections,
110   // DataSections and DebuggerTuning via command line flags.
111   AddUnsigned(Conf.Options.RelaxELFRelocations);
112   AddUnsigned(Conf.Options.FunctionSections);
113   AddUnsigned(Conf.Options.DataSections);
114   AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
115   for (auto &A : Conf.MAttrs)
116     AddString(A);
117   if (Conf.RelocModel)
118     AddUnsigned(*Conf.RelocModel);
119   else
120     AddUnsigned(-1);
121   AddUnsigned(Conf.CodeModel);
122   AddUnsigned(Conf.CGOptLevel);
123   AddUnsigned(Conf.CGFileType);
124   AddUnsigned(Conf.OptLevel);
125   AddString(Conf.OptPipeline);
126   AddString(Conf.AAPipeline);
127   AddString(Conf.OverrideTriple);
128   AddString(Conf.DefaultTriple);
129 
130   // Include the hash for the current module
131   auto ModHash = Index.getModuleHash(ModuleID);
132   Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
133   for (auto F : ExportList)
134     // The export list can impact the internalization, be conservative here
135     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
136 
137   // Include the hash for every module we import functions from. The set of
138   // imported symbols for each module may affect code generation and is
139   // sensitive to link order, so include that as well.
140   for (auto &Entry : ImportList) {
141     auto ModHash = Index.getModuleHash(Entry.first());
142     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
143 
144     AddUint64(Entry.second.size());
145     for (auto &Fn : Entry.second)
146       AddUint64(Fn.first);
147   }
148 
149   // Include the hash for the resolved ODR.
150   for (auto &Entry : ResolvedODR) {
151     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
152                                     sizeof(GlobalValue::GUID)));
153     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
154                                     sizeof(GlobalValue::LinkageTypes)));
155   }
156 
157   std::set<GlobalValue::GUID> UsedTypeIds;
158 
159   auto AddUsedTypeIds = [&](GlobalValueSummary *GS) {
160     auto *FS = dyn_cast_or_null<FunctionSummary>(GS);
161     if (!FS)
162       return;
163     for (auto &TT : FS->type_tests())
164       UsedTypeIds.insert(TT);
165     for (auto &TT : FS->type_test_assume_vcalls())
166       UsedTypeIds.insert(TT.GUID);
167     for (auto &TT : FS->type_checked_load_vcalls())
168       UsedTypeIds.insert(TT.GUID);
169     for (auto &TT : FS->type_test_assume_const_vcalls())
170       UsedTypeIds.insert(TT.VFunc.GUID);
171     for (auto &TT : FS->type_checked_load_const_vcalls())
172       UsedTypeIds.insert(TT.VFunc.GUID);
173   };
174 
175   // Include the hash for the linkage type to reflect internalization and weak
176   // resolution, and collect any used type identifier resolutions.
177   for (auto &GS : DefinedGlobals) {
178     GlobalValue::LinkageTypes Linkage = GS.second->linkage();
179     Hasher.update(
180         ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
181     AddUsedTypeIds(GS.second);
182   }
183 
184   // Imported functions may introduce new uses of type identifier resolutions,
185   // so we need to collect their used resolutions as well.
186   for (auto &ImpM : ImportList)
187     for (auto &ImpF : ImpM.second)
188       AddUsedTypeIds(Index.findSummaryInModule(ImpF.first, ImpM.first()));
189 
190   auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
191     AddString(TId);
192 
193     AddUnsigned(S.TTRes.TheKind);
194     AddUnsigned(S.TTRes.SizeM1BitWidth);
195 
196     AddUint64(S.WPDRes.size());
197     for (auto &WPD : S.WPDRes) {
198       AddUnsigned(WPD.first);
199       AddUnsigned(WPD.second.TheKind);
200       AddString(WPD.second.SingleImplName);
201 
202       AddUint64(WPD.second.ResByArg.size());
203       for (auto &ByArg : WPD.second.ResByArg) {
204         AddUint64(ByArg.first.size());
205         for (uint64_t Arg : ByArg.first)
206           AddUint64(Arg);
207         AddUnsigned(ByArg.second.TheKind);
208         AddUint64(ByArg.second.Info);
209       }
210     }
211   };
212 
213   // Include the hash for all type identifiers used by this module.
214   for (GlobalValue::GUID TId : UsedTypeIds) {
215     auto SummariesI = TypeIdSummariesByGuid.find(TId);
216     if (SummariesI != TypeIdSummariesByGuid.end())
217       for (auto *Summary : SummariesI->second)
218         AddTypeIdSummary(Summary->first, Summary->second);
219   }
220 
221   if (!Conf.SampleProfile.empty()) {
222     auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
223     if (FileOrErr)
224       Hasher.update(FileOrErr.get()->getBuffer());
225   }
226 
227   Key = toHex(Hasher.result());
228 }
229 
230 static void thinLTOResolveWeakForLinkerGUID(
231     GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
232     DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
233     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
234         isPrevailing,
235     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
236         recordNewLinkage) {
237   for (auto &S : GVSummaryList) {
238     GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
239     if (!GlobalValue::isWeakForLinker(OriginalLinkage))
240       continue;
241     // We need to emit only one of these. The prevailing module will keep it,
242     // but turned into a weak, while the others will drop it when possible.
243     // This is both a compile-time optimization and a correctness
244     // transformation. This is necessary for correctness when we have exported
245     // a reference - we need to convert the linkonce to weak to
246     // ensure a copy is kept to satisfy the exported reference.
247     // FIXME: We may want to split the compile time and correctness
248     // aspects into separate routines.
249     if (isPrevailing(GUID, S.get())) {
250       if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
251         S->setLinkage(GlobalValue::getWeakLinkage(
252             GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
253     }
254     // Alias and aliasee can't be turned into available_externally.
255     else if (!isa<AliasSummary>(S.get()) &&
256              !GlobalInvolvedWithAlias.count(S.get()))
257       S->setLinkage(GlobalValue::AvailableExternallyLinkage);
258     if (S->linkage() != OriginalLinkage)
259       recordNewLinkage(S->modulePath(), GUID, S->linkage());
260   }
261 }
262 
263 // Resolve Weak and LinkOnce values in the \p Index.
264 //
265 // We'd like to drop these functions if they are no longer referenced in the
266 // current module. However there is a chance that another module is still
267 // referencing them because of the import. We make sure we always emit at least
268 // one copy.
269 void llvm::thinLTOResolveWeakForLinkerInIndex(
270     ModuleSummaryIndex &Index,
271     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
272         isPrevailing,
273     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
274         recordNewLinkage) {
275   // We won't optimize the globals that are referenced by an alias for now
276   // Ideally we should turn the alias into a global and duplicate the definition
277   // when needed.
278   DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
279   for (auto &I : Index)
280     for (auto &S : I.second.SummaryList)
281       if (auto AS = dyn_cast<AliasSummary>(S.get()))
282         GlobalInvolvedWithAlias.insert(&AS->getAliasee());
283 
284   for (auto &I : Index)
285     thinLTOResolveWeakForLinkerGUID(I.second.SummaryList, I.first,
286                                     GlobalInvolvedWithAlias, isPrevailing,
287                                     recordNewLinkage);
288 }
289 
290 static void thinLTOInternalizeAndPromoteGUID(
291     GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
292     function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
293   for (auto &S : GVSummaryList) {
294     if (isExported(S->modulePath(), GUID)) {
295       if (GlobalValue::isLocalLinkage(S->linkage()))
296         S->setLinkage(GlobalValue::ExternalLinkage);
297     } else if (!GlobalValue::isLocalLinkage(S->linkage()))
298       S->setLinkage(GlobalValue::InternalLinkage);
299   }
300 }
301 
302 // Update the linkages in the given \p Index to mark exported values
303 // as external and non-exported values as internal.
304 void llvm::thinLTOInternalizeAndPromoteInIndex(
305     ModuleSummaryIndex &Index,
306     function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
307   for (auto &I : Index)
308     thinLTOInternalizeAndPromoteGUID(I.second.SummaryList, I.first, isExported);
309 }
310 
311 // Requires a destructor for std::vector<InputModule>.
312 InputFile::~InputFile() = default;
313 
314 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
315   std::unique_ptr<InputFile> File(new InputFile);
316 
317   ErrorOr<MemoryBufferRef> BCOrErr =
318       IRObjectFile::findBitcodeInMemBuffer(Object);
319   if (!BCOrErr)
320     return errorCodeToError(BCOrErr.getError());
321 
322   Expected<std::vector<BitcodeModule>> BMsOrErr =
323       getBitcodeModuleList(*BCOrErr);
324   if (!BMsOrErr)
325     return BMsOrErr.takeError();
326 
327   if (BMsOrErr->empty())
328     return make_error<StringError>("Bitcode file does not contain any modules",
329                                    inconvertibleErrorCode());
330 
331   File->Mods = *BMsOrErr;
332 
333   LLVMContext Ctx;
334   std::vector<Module *> Mods;
335   std::vector<std::unique_ptr<Module>> OwnedMods;
336   for (auto BM : *BMsOrErr) {
337     Expected<std::unique_ptr<Module>> MOrErr =
338         BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
339                          /*IsImporting*/ false);
340     if (!MOrErr)
341       return MOrErr.takeError();
342 
343     if ((*MOrErr)->getDataLayoutStr().empty())
344       return make_error<StringError>("input module has no datalayout",
345                                      inconvertibleErrorCode());
346 
347     Mods.push_back(MOrErr->get());
348     OwnedMods.push_back(std::move(*MOrErr));
349   }
350 
351   SmallVector<char, 0> Symtab;
352   if (Error E = irsymtab::build(Mods, Symtab, File->Strtab))
353     return std::move(E);
354 
355   irsymtab::Reader R({Symtab.data(), Symtab.size()},
356                      {File->Strtab.data(), File->Strtab.size()});
357   File->TargetTriple = R.getTargetTriple();
358   File->SourceFileName = R.getSourceFileName();
359   File->COFFLinkerOpts = R.getCOFFLinkerOpts();
360   File->ComdatTable = R.getComdatTable();
361 
362   for (unsigned I = 0; I != Mods.size(); ++I) {
363     size_t Begin = File->Symbols.size();
364     for (const irsymtab::Reader::SymbolRef &Sym : R.module_symbols(I))
365       // Skip symbols that are irrelevant to LTO. Note that this condition needs
366       // to match the one in Skip() in LTO::addRegularLTO().
367       if (Sym.isGlobal() && !Sym.isFormatSpecific())
368         File->Symbols.push_back(Sym);
369     File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
370   }
371 
372   return std::move(File);
373 }
374 
375 StringRef InputFile::getName() const {
376   return Mods[0].getModuleIdentifier();
377 }
378 
379 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
380                                       Config &Conf)
381     : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
382       Ctx(Conf) {}
383 
384 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
385   if (!Backend)
386     this->Backend =
387         createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
388 }
389 
390 LTO::LTO(Config Conf, ThinBackend Backend,
391          unsigned ParallelCodeGenParallelismLevel)
392     : Conf(std::move(Conf)),
393       RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
394       ThinLTO(std::move(Backend)) {}
395 
396 // Requires a destructor for MapVector<BitcodeModule>.
397 LTO::~LTO() = default;
398 
399 // Add the given symbol to the GlobalResolutions map, and resolve its partition.
400 void LTO::addSymbolToGlobalRes(const InputFile::Symbol &Sym,
401                                SymbolResolution Res, unsigned Partition) {
402   auto &GlobalRes = GlobalResolutions[Sym.getName()];
403   GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
404   if (Res.Prevailing)
405     GlobalRes.IRName = Sym.getIRName();
406 
407   // Set the partition to external if we know it is used elsewhere, e.g.
408   // it is visible to a regular object, is referenced from llvm.compiler_used,
409   // or was already recorded as being referenced from a different partition.
410   if (Res.VisibleToRegularObj || Sym.isUsed() ||
411       (GlobalRes.Partition != GlobalResolution::Unknown &&
412        GlobalRes.Partition != Partition)) {
413     GlobalRes.Partition = GlobalResolution::External;
414   } else
415     // First recorded reference, save the current partition.
416     GlobalRes.Partition = Partition;
417 
418   // Flag as visible outside of ThinLTO if visible from a regular object or
419   // if this is a reference in the regular LTO partition.
420   GlobalRes.VisibleOutsideThinLTO |=
421       (Res.VisibleToRegularObj || Sym.isUsed() ||
422        Partition == GlobalResolution::RegularLTO);
423 }
424 
425 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
426                                   ArrayRef<SymbolResolution> Res) {
427   StringRef Path = Input->getName();
428   OS << Path << '\n';
429   auto ResI = Res.begin();
430   for (const InputFile::Symbol &Sym : Input->symbols()) {
431     assert(ResI != Res.end());
432     SymbolResolution Res = *ResI++;
433 
434     OS << "-r=" << Path << ',' << Sym.getName() << ',';
435     if (Res.Prevailing)
436       OS << 'p';
437     if (Res.FinalDefinitionInLinkageUnit)
438       OS << 'l';
439     if (Res.VisibleToRegularObj)
440       OS << 'x';
441     OS << '\n';
442   }
443   OS.flush();
444   assert(ResI == Res.end());
445 }
446 
447 Error LTO::add(std::unique_ptr<InputFile> Input,
448                ArrayRef<SymbolResolution> Res) {
449   assert(!CalledGetMaxTasks);
450 
451   if (Conf.ResolutionFile)
452     writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
453 
454   const SymbolResolution *ResI = Res.begin();
455   for (unsigned I = 0; I != Input->Mods.size(); ++I)
456     if (Error Err = addModule(*Input, I, ResI, Res.end()))
457       return Err;
458 
459   assert(ResI == Res.end());
460   return Error::success();
461 }
462 
463 Error LTO::addModule(InputFile &Input, unsigned ModI,
464                      const SymbolResolution *&ResI,
465                      const SymbolResolution *ResE) {
466   Expected<bool> HasThinLTOSummary = Input.Mods[ModI].hasSummary();
467   if (!HasThinLTOSummary)
468     return HasThinLTOSummary.takeError();
469 
470   auto ModSyms = Input.module_symbols(ModI);
471   if (*HasThinLTOSummary)
472     return addThinLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
473   else
474     return addRegularLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
475 }
476 
477 // Add a regular LTO object to the link.
478 Error LTO::addRegularLTO(BitcodeModule BM,
479                          ArrayRef<InputFile::Symbol> Syms,
480                          const SymbolResolution *&ResI,
481                          const SymbolResolution *ResE) {
482   if (!RegularLTO.CombinedModule) {
483     RegularLTO.CombinedModule =
484         llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
485     RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
486   }
487   Expected<std::unique_ptr<Module>> MOrErr =
488       BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
489                        /*IsImporting*/ false);
490   if (!MOrErr)
491     return MOrErr.takeError();
492 
493   Module &M = **MOrErr;
494   if (Error Err = M.materializeMetadata())
495     return Err;
496   UpgradeDebugInfo(M);
497 
498   ModuleSymbolTable SymTab;
499   SymTab.addModule(&M);
500 
501   std::vector<GlobalValue *> Keep;
502 
503   for (GlobalVariable &GV : M.globals())
504     if (GV.hasAppendingLinkage())
505       Keep.push_back(&GV);
506 
507   DenseSet<GlobalObject *> AliasedGlobals;
508   for (auto &GA : M.aliases())
509     if (GlobalObject *GO = GA.getBaseObject())
510       AliasedGlobals.insert(GO);
511 
512   // In this function we need IR GlobalValues matching the symbols in Syms
513   // (which is not backed by a module), so we need to enumerate them in the same
514   // order. The symbol enumeration order of a ModuleSymbolTable intentionally
515   // matches the order of an irsymtab, but when we read the irsymtab in
516   // InputFile::create we omit some symbols that are irrelevant to LTO. The
517   // Skip() function skips the same symbols from the module as InputFile does
518   // from the symbol table.
519   auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
520   auto Skip = [&]() {
521     while (MsymI != MsymE) {
522       auto Flags = SymTab.getSymbolFlags(*MsymI);
523       if ((Flags & object::BasicSymbolRef::SF_Global) &&
524           !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
525         return;
526       ++MsymI;
527     }
528   };
529   Skip();
530 
531   for (const InputFile::Symbol &Sym : Syms) {
532     assert(ResI != ResE);
533     SymbolResolution Res = *ResI++;
534     addSymbolToGlobalRes(Sym, Res, 0);
535 
536     assert(MsymI != MsymE);
537     ModuleSymbolTable::Symbol Msym = *MsymI++;
538     Skip();
539 
540     if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
541       if (Res.Prevailing) {
542         if (Sym.isUndefined())
543           continue;
544         Keep.push_back(GV);
545         switch (GV->getLinkage()) {
546         default:
547           break;
548         case GlobalValue::LinkOnceAnyLinkage:
549           GV->setLinkage(GlobalValue::WeakAnyLinkage);
550           break;
551         case GlobalValue::LinkOnceODRLinkage:
552           GV->setLinkage(GlobalValue::WeakODRLinkage);
553           break;
554         }
555       } else if (isa<GlobalObject>(GV) &&
556                  (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
557                   GV->hasAvailableExternallyLinkage()) &&
558                  !AliasedGlobals.count(cast<GlobalObject>(GV))) {
559         // Either of the above three types of linkage indicates that the
560         // chosen prevailing symbol will have the same semantics as this copy of
561         // the symbol, so we can link it with available_externally linkage. We
562         // only need to do this if the symbol is undefined.
563         GlobalValue *CombinedGV =
564             RegularLTO.CombinedModule->getNamedValue(GV->getName());
565         if (!CombinedGV || CombinedGV->isDeclaration()) {
566           Keep.push_back(GV);
567           GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
568           cast<GlobalObject>(GV)->setComdat(nullptr);
569         }
570       }
571     }
572     // Common resolution: collect the maximum size/alignment over all commons.
573     // We also record if we see an instance of a common as prevailing, so that
574     // if none is prevailing we can ignore it later.
575     if (Sym.isCommon()) {
576       // FIXME: We should figure out what to do about commons defined by asm.
577       // For now they aren't reported correctly by ModuleSymbolTable.
578       auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
579       CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
580       CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
581       CommonRes.Prevailing |= Res.Prevailing;
582     }
583 
584     // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
585   }
586   assert(MsymI == MsymE);
587 
588   return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
589                                 [](GlobalValue &, IRMover::ValueAdder) {},
590                                 /* IsPerformingImport */ false);
591 }
592 
593 // Add a ThinLTO object to the link.
594 Error LTO::addThinLTO(BitcodeModule BM,
595                       ArrayRef<InputFile::Symbol> Syms,
596                       const SymbolResolution *&ResI,
597                       const SymbolResolution *ResE) {
598   if (Error Err =
599           BM.readSummary(ThinLTO.CombinedIndex, ThinLTO.ModuleMap.size()))
600     return Err;
601 
602   for (const InputFile::Symbol &Sym : Syms) {
603     assert(ResI != ResE);
604     SymbolResolution Res = *ResI++;
605     addSymbolToGlobalRes(Sym, Res, ThinLTO.ModuleMap.size() + 1);
606 
607     if (Res.Prevailing) {
608       if (!Sym.getIRName().empty()) {
609         auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
610             Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
611         ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
612       }
613     }
614   }
615 
616   if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
617     return make_error<StringError>(
618         "Expected at most one ThinLTO module per bitcode file",
619         inconvertibleErrorCode());
620 
621   return Error::success();
622 }
623 
624 unsigned LTO::getMaxTasks() const {
625   CalledGetMaxTasks = true;
626   return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
627 }
628 
629 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
630   // Save the status of having a regularLTO combined module, as
631   // this is needed for generating the ThinLTO Task ID, and
632   // the CombinedModule will be moved at the end of runRegularLTO.
633   bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
634   // Invoke regular LTO if there was a regular LTO module to start with.
635   if (HasRegularLTO)
636     if (auto E = runRegularLTO(AddStream))
637       return E;
638   return runThinLTO(AddStream, Cache, HasRegularLTO);
639 }
640 
641 Error LTO::runRegularLTO(AddStreamFn AddStream) {
642   // Make sure commons have the right size/alignment: we kept the largest from
643   // all the prevailing when adding the inputs, and we apply it here.
644   const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
645   for (auto &I : RegularLTO.Commons) {
646     if (!I.second.Prevailing)
647       // Don't do anything if no instance of this common was prevailing.
648       continue;
649     GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
650     if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
651       // Don't create a new global if the type is already correct, just make
652       // sure the alignment is correct.
653       OldGV->setAlignment(I.second.Align);
654       continue;
655     }
656     ArrayType *Ty =
657         ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
658     auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
659                                   GlobalValue::CommonLinkage,
660                                   ConstantAggregateZero::get(Ty), "");
661     GV->setAlignment(I.second.Align);
662     if (OldGV) {
663       OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
664       GV->takeName(OldGV);
665       OldGV->eraseFromParent();
666     } else {
667       GV->setName(I.first);
668     }
669   }
670 
671   if (Conf.PreOptModuleHook &&
672       !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
673     return Error::success();
674 
675   if (!Conf.CodeGenOnly) {
676     for (const auto &R : GlobalResolutions) {
677       if (R.second.IRName.empty())
678         continue;
679       if (R.second.Partition != 0 &&
680           R.second.Partition != GlobalResolution::External)
681         continue;
682 
683       GlobalValue *GV =
684           RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
685       // Ignore symbols defined in other partitions.
686       if (!GV || GV->hasLocalLinkage())
687         continue;
688       GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
689                                               : GlobalValue::UnnamedAddr::None);
690       if (R.second.Partition == 0)
691         GV->setLinkage(GlobalValue::InternalLinkage);
692     }
693 
694     if (Conf.PostInternalizeModuleHook &&
695         !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
696       return Error::success();
697   }
698   return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
699                  std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
700 }
701 
702 /// This class defines the interface to the ThinLTO backend.
703 class lto::ThinBackendProc {
704 protected:
705   Config &Conf;
706   ModuleSummaryIndex &CombinedIndex;
707   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
708 
709 public:
710   ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
711                   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
712       : Conf(Conf), CombinedIndex(CombinedIndex),
713         ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
714 
715   virtual ~ThinBackendProc() {}
716   virtual Error start(
717       unsigned Task, BitcodeModule BM,
718       const FunctionImporter::ImportMapTy &ImportList,
719       const FunctionImporter::ExportSetTy &ExportList,
720       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
721       MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
722   virtual Error wait() = 0;
723 };
724 
725 namespace {
726 class InProcessThinBackend : public ThinBackendProc {
727   ThreadPool BackendThreadPool;
728   AddStreamFn AddStream;
729   NativeObjectCache Cache;
730   TypeIdSummariesByGuidTy TypeIdSummariesByGuid;
731 
732   Optional<Error> Err;
733   std::mutex ErrMu;
734 
735 public:
736   InProcessThinBackend(
737       Config &Conf, ModuleSummaryIndex &CombinedIndex,
738       unsigned ThinLTOParallelismLevel,
739       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
740       AddStreamFn AddStream, NativeObjectCache Cache)
741       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
742         BackendThreadPool(ThinLTOParallelismLevel),
743         AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
744     // Create a mapping from type identifier GUIDs to type identifier summaries.
745     // This allows backends to use the type identifier GUIDs stored in the
746     // function summaries to determine which type identifier summaries affect
747     // each function without needing to compute GUIDs in each backend.
748     for (auto &TId : CombinedIndex.typeIds())
749       TypeIdSummariesByGuid[GlobalValue::getGUID(TId.first)].push_back(&TId);
750   }
751 
752   Error runThinLTOBackendThread(
753       AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
754       BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
755       const FunctionImporter::ImportMapTy &ImportList,
756       const FunctionImporter::ExportSetTy &ExportList,
757       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
758       const GVSummaryMapTy &DefinedGlobals,
759       MapVector<StringRef, BitcodeModule> &ModuleMap,
760       const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
761     auto RunThinBackend = [&](AddStreamFn AddStream) {
762       LTOLLVMContext BackendContext(Conf);
763       Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
764       if (!MOrErr)
765         return MOrErr.takeError();
766 
767       return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
768                          ImportList, DefinedGlobals, ModuleMap);
769     };
770 
771     auto ModuleID = BM.getModuleIdentifier();
772 
773     if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
774         all_of(CombinedIndex.getModuleHash(ModuleID),
775                [](uint32_t V) { return V == 0; }))
776       // Cache disabled or no entry for this module in the combined index or
777       // no module hash.
778       return RunThinBackend(AddStream);
779 
780     SmallString<40> Key;
781     // The module may be cached, this helps handling it.
782     computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
783                     ResolvedODR, DefinedGlobals, TypeIdSummariesByGuid);
784     if (AddStreamFn CacheAddStream = Cache(Task, Key))
785       return RunThinBackend(CacheAddStream);
786 
787     return Error::success();
788   }
789 
790   Error start(
791       unsigned Task, BitcodeModule BM,
792       const FunctionImporter::ImportMapTy &ImportList,
793       const FunctionImporter::ExportSetTy &ExportList,
794       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
795       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
796     StringRef ModulePath = BM.getModuleIdentifier();
797     assert(ModuleToDefinedGVSummaries.count(ModulePath));
798     const GVSummaryMapTy &DefinedGlobals =
799         ModuleToDefinedGVSummaries.find(ModulePath)->second;
800     BackendThreadPool.async(
801         [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
802             const FunctionImporter::ImportMapTy &ImportList,
803             const FunctionImporter::ExportSetTy &ExportList,
804             const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
805                 &ResolvedODR,
806             const GVSummaryMapTy &DefinedGlobals,
807             MapVector<StringRef, BitcodeModule> &ModuleMap,
808             const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
809           Error E = runThinLTOBackendThread(
810               AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
811               ResolvedODR, DefinedGlobals, ModuleMap, TypeIdSummariesByGuid);
812           if (E) {
813             std::unique_lock<std::mutex> L(ErrMu);
814             if (Err)
815               Err = joinErrors(std::move(*Err), std::move(E));
816             else
817               Err = std::move(E);
818           }
819         },
820         BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
821         std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap),
822         std::ref(TypeIdSummariesByGuid));
823     return Error::success();
824   }
825 
826   Error wait() override {
827     BackendThreadPool.wait();
828     if (Err)
829       return std::move(*Err);
830     else
831       return Error::success();
832   }
833 };
834 } // end anonymous namespace
835 
836 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
837   return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
838              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
839              AddStreamFn AddStream, NativeObjectCache Cache) {
840     return llvm::make_unique<InProcessThinBackend>(
841         Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
842         AddStream, Cache);
843   };
844 }
845 
846 // Given the original \p Path to an output file, replace any path
847 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
848 // resulting directory if it does not yet exist.
849 std::string lto::getThinLTOOutputFile(const std::string &Path,
850                                       const std::string &OldPrefix,
851                                       const std::string &NewPrefix) {
852   if (OldPrefix.empty() && NewPrefix.empty())
853     return Path;
854   SmallString<128> NewPath(Path);
855   llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
856   StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
857   if (!ParentPath.empty()) {
858     // Make sure the new directory exists, creating it if necessary.
859     if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
860       llvm::errs() << "warning: could not create directory '" << ParentPath
861                    << "': " << EC.message() << '\n';
862   }
863   return NewPath.str();
864 }
865 
866 namespace {
867 class WriteIndexesThinBackend : public ThinBackendProc {
868   std::string OldPrefix, NewPrefix;
869   bool ShouldEmitImportsFiles;
870 
871   std::string LinkedObjectsFileName;
872   std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
873 
874 public:
875   WriteIndexesThinBackend(
876       Config &Conf, ModuleSummaryIndex &CombinedIndex,
877       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
878       std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
879       std::string LinkedObjectsFileName)
880       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
881         OldPrefix(OldPrefix), NewPrefix(NewPrefix),
882         ShouldEmitImportsFiles(ShouldEmitImportsFiles),
883         LinkedObjectsFileName(LinkedObjectsFileName) {}
884 
885   Error start(
886       unsigned Task, BitcodeModule BM,
887       const FunctionImporter::ImportMapTy &ImportList,
888       const FunctionImporter::ExportSetTy &ExportList,
889       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
890       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
891     StringRef ModulePath = BM.getModuleIdentifier();
892     std::string NewModulePath =
893         getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
894 
895     std::error_code EC;
896     if (!LinkedObjectsFileName.empty()) {
897       if (!LinkedObjectsFile) {
898         LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
899             LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
900         if (EC)
901           return errorCodeToError(EC);
902       }
903       *LinkedObjectsFile << NewModulePath << '\n';
904     }
905 
906     std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
907     gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
908                                      ImportList, ModuleToSummariesForIndex);
909 
910     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
911                       sys::fs::OpenFlags::F_None);
912     if (EC)
913       return errorCodeToError(EC);
914     WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
915 
916     if (ShouldEmitImportsFiles)
917       return errorCodeToError(
918           EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
919     return Error::success();
920   }
921 
922   Error wait() override { return Error::success(); }
923 };
924 } // end anonymous namespace
925 
926 ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
927                                                std::string NewPrefix,
928                                                bool ShouldEmitImportsFiles,
929                                                std::string LinkedObjectsFile) {
930   return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
931              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
932              AddStreamFn AddStream, NativeObjectCache Cache) {
933     return llvm::make_unique<WriteIndexesThinBackend>(
934         Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
935         ShouldEmitImportsFiles, LinkedObjectsFile);
936   };
937 }
938 
939 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
940                       bool HasRegularLTO) {
941   if (ThinLTO.ModuleMap.empty())
942     return Error::success();
943 
944   if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
945     return Error::success();
946 
947   // Collect for each module the list of function it defines (GUID ->
948   // Summary).
949   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
950       ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
951   ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
952       ModuleToDefinedGVSummaries);
953   // Create entries for any modules that didn't have any GV summaries
954   // (either they didn't have any GVs to start with, or we suppressed
955   // generation of the summaries because they e.g. had inline assembly
956   // uses that couldn't be promoted/renamed on export). This is so
957   // InProcessThinBackend::start can still launch a backend thread, which
958   // is passed the map of summaries for the module, without any special
959   // handling for this case.
960   for (auto &Mod : ThinLTO.ModuleMap)
961     if (!ModuleToDefinedGVSummaries.count(Mod.first))
962       ModuleToDefinedGVSummaries.try_emplace(Mod.first);
963 
964   StringMap<FunctionImporter::ImportMapTy> ImportLists(
965       ThinLTO.ModuleMap.size());
966   StringMap<FunctionImporter::ExportSetTy> ExportLists(
967       ThinLTO.ModuleMap.size());
968   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
969 
970   if (Conf.OptLevel > 0) {
971     // Compute "dead" symbols, we don't want to import/export these!
972     DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
973     for (auto &Res : GlobalResolutions) {
974       if (Res.second.VisibleOutsideThinLTO &&
975           // IRName will be defined if we have seen the prevailing copy of
976           // this value. If not, no need to preserve any ThinLTO copies.
977           !Res.second.IRName.empty())
978         GUIDPreservedSymbols.insert(GlobalValue::getGUID(
979             GlobalValue::dropLLVMManglingEscape(Res.second.IRName)));
980     }
981 
982     auto DeadSymbols =
983         computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
984 
985     ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
986                              ImportLists, ExportLists, &DeadSymbols);
987 
988     std::set<GlobalValue::GUID> ExportedGUIDs;
989     for (auto &Res : GlobalResolutions) {
990       // First check if the symbol was flagged as having external references.
991       if (Res.second.Partition != GlobalResolution::External)
992         continue;
993       // IRName will be defined if we have seen the prevailing copy of
994       // this value. If not, no need to mark as exported from a ThinLTO
995       // partition (and we can't get the GUID).
996       if (Res.second.IRName.empty())
997         continue;
998       auto GUID = GlobalValue::getGUID(
999           GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1000       // Mark exported unless index-based analysis determined it to be dead.
1001       if (!DeadSymbols.count(GUID))
1002         ExportedGUIDs.insert(GUID);
1003     }
1004 
1005     auto isPrevailing = [&](GlobalValue::GUID GUID,
1006                             const GlobalValueSummary *S) {
1007       return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1008     };
1009     auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
1010       const auto &ExportList = ExportLists.find(ModuleIdentifier);
1011       return (ExportList != ExportLists.end() &&
1012               ExportList->second.count(GUID)) ||
1013              ExportedGUIDs.count(GUID);
1014     };
1015     thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
1016 
1017     auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1018                                 GlobalValue::GUID GUID,
1019                                 GlobalValue::LinkageTypes NewLinkage) {
1020       ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1021     };
1022 
1023     thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
1024                                        recordNewLinkage);
1025   }
1026 
1027   std::unique_ptr<ThinBackendProc> BackendProc =
1028       ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1029                       AddStream, Cache);
1030 
1031   // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
1032   // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
1033   // are reserved for parallel code generation partitions.
1034   unsigned Task =
1035       HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
1036   for (auto &Mod : ThinLTO.ModuleMap) {
1037     if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1038                                      ExportLists[Mod.first],
1039                                      ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1040       return E;
1041     ++Task;
1042   }
1043 
1044   return BackendProc->wait();
1045 }
1046 
1047 Expected<std::unique_ptr<tool_output_file>>
1048 lto::setupOptimizationRemarks(LLVMContext &Context,
1049                               StringRef LTORemarksFilename,
1050                               bool LTOPassRemarksWithHotness, int Count) {
1051   if (LTORemarksFilename.empty())
1052     return nullptr;
1053 
1054   std::string Filename = LTORemarksFilename;
1055   if (Count != -1)
1056     Filename += ".thin." + llvm::utostr(Count) + ".yaml";
1057 
1058   std::error_code EC;
1059   auto DiagnosticFile =
1060       llvm::make_unique<tool_output_file>(Filename, EC, sys::fs::F_None);
1061   if (EC)
1062     return errorCodeToError(EC);
1063   Context.setDiagnosticsOutputFile(
1064       llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1065   if (LTOPassRemarksWithHotness)
1066     Context.setDiagnosticHotnessRequested(true);
1067   DiagnosticFile->keep();
1068   return std::move(DiagnosticFile);
1069 }
1070