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