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