xref: /llvm-project-15.0.7/llvm/lib/LTO/LTO.cpp (revision 286adee5)
1 //===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements functions and classes used to support LTO.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/LTO/LTO.h"
15 #include "llvm/Analysis/TargetLibraryInfo.h"
16 #include "llvm/Analysis/TargetTransformInfo.h"
17 #include "llvm/Bitcode/BitcodeReader.h"
18 #include "llvm/Bitcode/BitcodeWriter.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/IR/AutoUpgrade.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/LTO/LTOBackend.h"
24 #include "llvm/Linker/IRMover.h"
25 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/SHA1.h"
30 #include "llvm/Support/SourceMgr.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Support/ThreadPool.h"
33 #include "llvm/Support/Threading.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Transforms/IPO.h"
38 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
39 #include "llvm/Transforms/Utils/SplitModule.h"
40 
41 #include <set>
42 
43 using namespace llvm;
44 using namespace lto;
45 using namespace object;
46 
47 #define DEBUG_TYPE "lto"
48 
49 // Returns a unique hash for the Module considering the current list of
50 // export/import and other global analysis results.
51 // The hash is produced in \p Key.
52 static void computeCacheKey(
53     SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
54     StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
55     const FunctionImporter::ExportSetTy &ExportList,
56     const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
57     const GVSummaryMapTy &DefinedGlobals) {
58   // Compute the unique hash for this entry.
59   // This is based on the current compiler version, the module itself, the
60   // export list, the hash for every single module in the import list, the
61   // list of ResolvedODR for the module, and the list of preserved symbols.
62   SHA1 Hasher;
63 
64   // Start with the compiler revision
65   Hasher.update(LLVM_VERSION_STRING);
66 #ifdef HAVE_LLVM_REVISION
67   Hasher.update(LLVM_REVISION);
68 #endif
69 
70   // Include the parts of the LTO configuration that affect code generation.
71   auto AddString = [&](StringRef Str) {
72     Hasher.update(Str);
73     Hasher.update(ArrayRef<uint8_t>{0});
74   };
75   auto AddUnsigned = [&](unsigned I) {
76     uint8_t Data[4];
77     Data[0] = I;
78     Data[1] = I >> 8;
79     Data[2] = I >> 16;
80     Data[3] = I >> 24;
81     Hasher.update(ArrayRef<uint8_t>{Data, 4});
82   };
83   AddString(Conf.CPU);
84   // FIXME: Hash more of Options. For now all clients initialize Options from
85   // command-line flags (which is unsupported in production), but may set
86   // RelaxELFRelocations. The clang driver can also pass FunctionSections,
87   // DataSections and DebuggerTuning via command line flags.
88   AddUnsigned(Conf.Options.RelaxELFRelocations);
89   AddUnsigned(Conf.Options.FunctionSections);
90   AddUnsigned(Conf.Options.DataSections);
91   AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
92   for (auto &A : Conf.MAttrs)
93     AddString(A);
94   AddUnsigned(Conf.RelocModel);
95   AddUnsigned(Conf.CodeModel);
96   AddUnsigned(Conf.CGOptLevel);
97   AddUnsigned(Conf.OptLevel);
98   AddString(Conf.OptPipeline);
99   AddString(Conf.AAPipeline);
100   AddString(Conf.OverrideTriple);
101   AddString(Conf.DefaultTriple);
102 
103   // Include the hash for the current module
104   auto ModHash = Index.getModuleHash(ModuleID);
105   Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
106   for (auto F : ExportList)
107     // The export list can impact the internalization, be conservative here
108     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
109 
110   // Include the hash for every module we import functions from
111   for (auto &Entry : ImportList) {
112     auto ModHash = Index.getModuleHash(Entry.first());
113     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
114   }
115 
116   // Include the hash for the resolved ODR.
117   for (auto &Entry : ResolvedODR) {
118     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
119                                     sizeof(GlobalValue::GUID)));
120     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
121                                     sizeof(GlobalValue::LinkageTypes)));
122   }
123 
124   // Include the hash for the linkage type to reflect internalization and weak
125   // resolution.
126   for (auto &GS : DefinedGlobals) {
127     GlobalValue::LinkageTypes Linkage = GS.second->linkage();
128     Hasher.update(
129         ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
130   }
131 
132   Key = toHex(Hasher.result());
133 }
134 
135 static void thinLTOResolveWeakForLinkerGUID(
136     GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
137     DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
138     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
139         isPrevailing,
140     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
141         recordNewLinkage) {
142   for (auto &S : GVSummaryList) {
143     GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
144     if (!GlobalValue::isWeakForLinker(OriginalLinkage))
145       continue;
146     // We need to emit only one of these. The prevailing module will keep it,
147     // but turned into a weak, while the others will drop it when possible.
148     // This is both a compile-time optimization and a correctness
149     // transformation. This is necessary for correctness when we have exported
150     // a reference - we need to convert the linkonce to weak to
151     // ensure a copy is kept to satisfy the exported reference.
152     // FIXME: We may want to split the compile time and correctness
153     // aspects into separate routines.
154     if (isPrevailing(GUID, S.get())) {
155       if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
156         S->setLinkage(GlobalValue::getWeakLinkage(
157             GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
158     }
159     // Alias and aliasee can't be turned into available_externally.
160     else if (!isa<AliasSummary>(S.get()) &&
161              !GlobalInvolvedWithAlias.count(S.get()) &&
162              (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
163               GlobalValue::isWeakODRLinkage(OriginalLinkage)))
164       S->setLinkage(GlobalValue::AvailableExternallyLinkage);
165     if (S->linkage() != OriginalLinkage)
166       recordNewLinkage(S->modulePath(), GUID, S->linkage());
167   }
168 }
169 
170 // Resolve Weak and LinkOnce values in the \p Index.
171 //
172 // We'd like to drop these functions if they are no longer referenced in the
173 // current module. However there is a chance that another module is still
174 // referencing them because of the import. We make sure we always emit at least
175 // one copy.
176 void llvm::thinLTOResolveWeakForLinkerInIndex(
177     ModuleSummaryIndex &Index,
178     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
179         isPrevailing,
180     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
181         recordNewLinkage) {
182   // We won't optimize the globals that are referenced by an alias for now
183   // Ideally we should turn the alias into a global and duplicate the definition
184   // when needed.
185   DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
186   for (auto &I : Index)
187     for (auto &S : I.second)
188       if (auto AS = dyn_cast<AliasSummary>(S.get()))
189         GlobalInvolvedWithAlias.insert(&AS->getAliasee());
190 
191   for (auto &I : Index)
192     thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
193                                     isPrevailing, recordNewLinkage);
194 }
195 
196 static void thinLTOInternalizeAndPromoteGUID(
197     GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
198     function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
199   for (auto &S : GVSummaryList) {
200     if (isExported(S->modulePath(), GUID)) {
201       if (GlobalValue::isLocalLinkage(S->linkage()))
202         S->setLinkage(GlobalValue::ExternalLinkage);
203     } else if (!GlobalValue::isLocalLinkage(S->linkage()))
204       S->setLinkage(GlobalValue::InternalLinkage);
205   }
206 }
207 
208 // Update the linkages in the given \p Index to mark exported values
209 // as external and non-exported values as internal.
210 void llvm::thinLTOInternalizeAndPromoteInIndex(
211     ModuleSummaryIndex &Index,
212     function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
213   for (auto &I : Index)
214     thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
215 }
216 
217 struct InputFile::InputModule {
218   BitcodeModule BM;
219   std::unique_ptr<Module> Mod;
220 
221   // The range of ModuleSymbolTable entries for this input module.
222   size_t SymBegin, SymEnd;
223 };
224 
225 // Requires a destructor for std::vector<InputModule>.
226 InputFile::~InputFile() = default;
227 
228 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
229   std::unique_ptr<InputFile> File(new InputFile);
230 
231   ErrorOr<MemoryBufferRef> BCOrErr =
232       IRObjectFile::findBitcodeInMemBuffer(Object);
233   if (!BCOrErr)
234     return errorCodeToError(BCOrErr.getError());
235 
236   Expected<std::vector<BitcodeModule>> BMsOrErr =
237       getBitcodeModuleList(*BCOrErr);
238   if (!BMsOrErr)
239     return BMsOrErr.takeError();
240 
241   if (BMsOrErr->empty())
242     return make_error<StringError>("Bitcode file does not contain any modules",
243                                    inconvertibleErrorCode());
244 
245   // Create an InputModule for each module in the InputFile, and add it to the
246   // ModuleSymbolTable.
247   for (auto BM : *BMsOrErr) {
248     Expected<std::unique_ptr<Module>> MOrErr =
249         BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true);
250     if (!MOrErr)
251       return MOrErr.takeError();
252 
253     size_t SymBegin = File->SymTab.symbols().size();
254     File->SymTab.addModule(MOrErr->get());
255     size_t SymEnd = File->SymTab.symbols().size();
256 
257     for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
258       auto P = File->ComdatMap.insert(
259           std::make_pair(&C.second, File->Comdats.size()));
260       assert(P.second);
261       (void)P;
262       File->Comdats.push_back(C.first());
263     }
264 
265     File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
266   }
267 
268   return std::move(File);
269 }
270 
271 Expected<int> InputFile::Symbol::getComdatIndex() const {
272   if (!isGV())
273     return -1;
274   const GlobalObject *GO = getGV()->getBaseObject();
275   if (!GO)
276     return make_error<StringError>("Unable to determine comdat of alias!",
277                                    inconvertibleErrorCode());
278   if (const Comdat *C = GO->getComdat()) {
279     auto I = File->ComdatMap.find(C);
280     assert(I != File->ComdatMap.end());
281     return I->second;
282   }
283   return -1;
284 }
285 
286 StringRef InputFile::getName() const {
287   return Mods[0].BM.getModuleIdentifier();
288 }
289 
290 StringRef InputFile::getSourceFileName() const {
291   return Mods[0].Mod->getSourceFileName();
292 }
293 
294 iterator_range<InputFile::symbol_iterator>
295 InputFile::module_symbols(InputModule &IM) {
296   return llvm::make_range(
297       symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
298       symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
299 }
300 
301 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
302                                       Config &Conf)
303     : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
304       Ctx(Conf) {}
305 
306 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
307   if (!Backend)
308     this->Backend =
309         createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
310 }
311 
312 LTO::LTO(Config Conf, ThinBackend Backend,
313          unsigned ParallelCodeGenParallelismLevel)
314     : Conf(std::move(Conf)),
315       RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
316       ThinLTO(std::move(Backend)) {}
317 
318 // Requires a destructor for MapVector<BitcodeModule>.
319 LTO::~LTO() = default;
320 
321 // Add the given symbol to the GlobalResolutions map, and resolve its partition.
322 void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
323                                const InputFile::Symbol &Sym,
324                                SymbolResolution Res, unsigned Partition) {
325   GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
326 
327   auto &GlobalRes = GlobalResolutions[Sym.getName()];
328   if (GV) {
329     GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
330     if (Res.Prevailing)
331       GlobalRes.IRName = GV->getName();
332   }
333   if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
334       (GlobalRes.Partition != GlobalResolution::Unknown &&
335        GlobalRes.Partition != Partition))
336     GlobalRes.Partition = GlobalResolution::External;
337   else
338     GlobalRes.Partition = Partition;
339 }
340 
341 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
342                                   ArrayRef<SymbolResolution> Res) {
343   StringRef Path = Input->getName();
344   OS << Path << '\n';
345   auto ResI = Res.begin();
346   for (const InputFile::Symbol &Sym : Input->symbols()) {
347     assert(ResI != Res.end());
348     SymbolResolution Res = *ResI++;
349 
350     OS << "-r=" << Path << ',' << Sym.getName() << ',';
351     if (Res.Prevailing)
352       OS << 'p';
353     if (Res.FinalDefinitionInLinkageUnit)
354       OS << 'l';
355     if (Res.VisibleToRegularObj)
356       OS << 'x';
357     OS << '\n';
358   }
359   assert(ResI == Res.end());
360 }
361 
362 Error LTO::add(std::unique_ptr<InputFile> Input,
363                ArrayRef<SymbolResolution> Res) {
364   assert(!CalledGetMaxTasks);
365 
366   if (Conf.ResolutionFile)
367     writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
368 
369   const SymbolResolution *ResI = Res.begin();
370   for (InputFile::InputModule &IM : Input->Mods)
371     if (Error Err = addModule(*Input, IM, ResI, Res.end()))
372       return Err;
373 
374   assert(ResI == Res.end());
375   return Error::success();
376 }
377 
378 Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
379                      const SymbolResolution *&ResI,
380                      const SymbolResolution *ResE) {
381   // FIXME: move to backend
382   Module &M = *IM.Mod;
383 
384   if (M.getDataLayoutStr().empty())
385     return make_error<StringError>("input module has no datalayout",
386                                     inconvertibleErrorCode());
387 
388   if (!Conf.OverrideTriple.empty())
389     M.setTargetTriple(Conf.OverrideTriple);
390   else if (M.getTargetTriple().empty())
391     M.setTargetTriple(Conf.DefaultTriple);
392 
393   Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
394   if (!HasThinLTOSummary)
395     return HasThinLTOSummary.takeError();
396 
397   if (*HasThinLTOSummary)
398     return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
399   else
400     return addRegularLTO(IM.BM, ResI, ResE);
401 }
402 
403 // Add a regular LTO object to the link.
404 Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
405                          const SymbolResolution *ResE) {
406   if (!RegularLTO.CombinedModule) {
407     RegularLTO.CombinedModule =
408         llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
409     RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
410   }
411   Expected<std::unique_ptr<Module>> MOrErr =
412       BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true);
413   if (!MOrErr)
414     return MOrErr.takeError();
415 
416   Module &M = **MOrErr;
417   if (Error Err = M.materializeMetadata())
418     return Err;
419   UpgradeDebugInfo(M);
420 
421   ModuleSymbolTable SymTab;
422   SymTab.addModule(&M);
423 
424   SmallPtrSet<GlobalValue *, 8> Used;
425   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
426 
427   std::vector<GlobalValue *> Keep;
428 
429   for (GlobalVariable &GV : M.globals())
430     if (GV.hasAppendingLinkage())
431       Keep.push_back(&GV);
432 
433   for (const InputFile::Symbol &Sym :
434        make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
435                                              nullptr),
436                   InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
437                                              nullptr))) {
438     assert(ResI != ResE);
439     SymbolResolution Res = *ResI++;
440     addSymbolToGlobalRes(Used, Sym, Res, 0);
441 
442     if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
443       continue;
444     if (Res.Prevailing && Sym.isGV()) {
445       GlobalValue *GV = Sym.getGV();
446       Keep.push_back(GV);
447       switch (GV->getLinkage()) {
448       default:
449         break;
450       case GlobalValue::LinkOnceAnyLinkage:
451         GV->setLinkage(GlobalValue::WeakAnyLinkage);
452         break;
453       case GlobalValue::LinkOnceODRLinkage:
454         GV->setLinkage(GlobalValue::WeakODRLinkage);
455         break;
456       }
457     }
458     // Common resolution: collect the maximum size/alignment over all commons.
459     // We also record if we see an instance of a common as prevailing, so that
460     // if none is prevailing we can ignore it later.
461     if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
462       // FIXME: We should figure out what to do about commons defined by asm.
463       // For now they aren't reported correctly by ModuleSymbolTable.
464       auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
465       CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
466       CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
467       CommonRes.Prevailing |= Res.Prevailing;
468     }
469 
470     // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
471   }
472 
473   return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
474                                 [](GlobalValue &, IRMover::ValueAdder) {},
475                                 /* LinkModuleInlineAsm */ true,
476                                 /* IsPerformingImport */ false);
477 }
478 
479 // Add a ThinLTO object to the link.
480 // FIXME: This function should not need to take as many parameters once we have
481 // a bitcode symbol table.
482 Error LTO::addThinLTO(BitcodeModule BM, Module &M,
483                       iterator_range<InputFile::symbol_iterator> Syms,
484                       const SymbolResolution *&ResI,
485                       const SymbolResolution *ResE) {
486   SmallPtrSet<GlobalValue *, 8> Used;
487   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
488 
489   Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
490   if (!SummaryOrErr)
491     return SummaryOrErr.takeError();
492   ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
493                                   ThinLTO.ModuleMap.size());
494 
495   for (const InputFile::Symbol &Sym : Syms) {
496     assert(ResI != ResE);
497     SymbolResolution Res = *ResI++;
498     addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
499 
500     if (Res.Prevailing && Sym.isGV())
501       ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
502           BM.getModuleIdentifier();
503   }
504 
505   if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
506     return make_error<StringError>(
507         "Expected at most one ThinLTO module per bitcode file",
508         inconvertibleErrorCode());
509 
510   return Error::success();
511 }
512 
513 unsigned LTO::getMaxTasks() const {
514   CalledGetMaxTasks = true;
515   return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
516 }
517 
518 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
519   // Save the status of having a regularLTO combined module, as
520   // this is needed for generating the ThinLTO Task ID, and
521   // the CombinedModule will be moved at the end of runRegularLTO.
522   bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
523   // Invoke regular LTO if there was a regular LTO module to start with.
524   if (HasRegularLTO)
525     if (auto E = runRegularLTO(AddStream))
526       return E;
527   return runThinLTO(AddStream, Cache, HasRegularLTO);
528 }
529 
530 Error LTO::runRegularLTO(AddStreamFn AddStream) {
531   // Make sure commons have the right size/alignment: we kept the largest from
532   // all the prevailing when adding the inputs, and we apply it here.
533   const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
534   for (auto &I : RegularLTO.Commons) {
535     if (!I.second.Prevailing)
536       // Don't do anything if no instance of this common was prevailing.
537       continue;
538     GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
539     if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
540       // Don't create a new global if the type is already correct, just make
541       // sure the alignment is correct.
542       OldGV->setAlignment(I.second.Align);
543       continue;
544     }
545     ArrayType *Ty =
546         ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
547     auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
548                                   GlobalValue::CommonLinkage,
549                                   ConstantAggregateZero::get(Ty), "");
550     GV->setAlignment(I.second.Align);
551     if (OldGV) {
552       OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
553       GV->takeName(OldGV);
554       OldGV->eraseFromParent();
555     } else {
556       GV->setName(I.first);
557     }
558   }
559 
560   if (Conf.PreOptModuleHook &&
561       !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
562     return Error::success();
563 
564   if (!Conf.CodeGenOnly) {
565     for (const auto &R : GlobalResolutions) {
566       if (R.second.IRName.empty())
567         continue;
568       if (R.second.Partition != 0 &&
569           R.second.Partition != GlobalResolution::External)
570         continue;
571 
572       GlobalValue *GV =
573           RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
574       // Ignore symbols defined in other partitions.
575       if (!GV || GV->hasLocalLinkage())
576         continue;
577       GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
578                                               : GlobalValue::UnnamedAddr::None);
579       if (R.second.Partition == 0)
580         GV->setLinkage(GlobalValue::InternalLinkage);
581     }
582 
583     if (Conf.PostInternalizeModuleHook &&
584         !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
585       return Error::success();
586   }
587   return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
588                  std::move(RegularLTO.CombinedModule));
589 }
590 
591 /// This class defines the interface to the ThinLTO backend.
592 class lto::ThinBackendProc {
593 protected:
594   Config &Conf;
595   ModuleSummaryIndex &CombinedIndex;
596   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
597 
598 public:
599   ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
600                   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
601       : Conf(Conf), CombinedIndex(CombinedIndex),
602         ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
603 
604   virtual ~ThinBackendProc() {}
605   virtual Error start(
606       unsigned Task, BitcodeModule BM,
607       const FunctionImporter::ImportMapTy &ImportList,
608       const FunctionImporter::ExportSetTy &ExportList,
609       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
610       MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
611   virtual Error wait() = 0;
612 };
613 
614 namespace {
615 class InProcessThinBackend : public ThinBackendProc {
616   ThreadPool BackendThreadPool;
617   AddStreamFn AddStream;
618   NativeObjectCache Cache;
619 
620   Optional<Error> Err;
621   std::mutex ErrMu;
622 
623 public:
624   InProcessThinBackend(
625       Config &Conf, ModuleSummaryIndex &CombinedIndex,
626       unsigned ThinLTOParallelismLevel,
627       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
628       AddStreamFn AddStream, NativeObjectCache Cache)
629       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
630         BackendThreadPool(ThinLTOParallelismLevel),
631         AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
632 
633   Error runThinLTOBackendThread(
634       AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
635       BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
636       const FunctionImporter::ImportMapTy &ImportList,
637       const FunctionImporter::ExportSetTy &ExportList,
638       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
639       const GVSummaryMapTy &DefinedGlobals,
640       MapVector<StringRef, BitcodeModule> &ModuleMap) {
641     auto RunThinBackend = [&](AddStreamFn AddStream) {
642       LTOLLVMContext BackendContext(Conf);
643       Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
644       if (!MOrErr)
645         return MOrErr.takeError();
646 
647       return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
648                          ImportList, DefinedGlobals, ModuleMap);
649     };
650 
651     auto ModuleID = BM.getModuleIdentifier();
652 
653     if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
654         all_of(CombinedIndex.getModuleHash(ModuleID),
655                [](uint32_t V) { return V == 0; }))
656       // Cache disabled or no entry for this module in the combined index or
657       // no module hash.
658       return RunThinBackend(AddStream);
659 
660     SmallString<40> Key;
661     // The module may be cached, this helps handling it.
662     computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
663                     ResolvedODR, DefinedGlobals);
664     if (AddStreamFn CacheAddStream = Cache(Task, Key))
665       return RunThinBackend(CacheAddStream);
666 
667     return Error::success();
668   }
669 
670   Error start(
671       unsigned Task, BitcodeModule BM,
672       const FunctionImporter::ImportMapTy &ImportList,
673       const FunctionImporter::ExportSetTy &ExportList,
674       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
675       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
676     StringRef ModulePath = BM.getModuleIdentifier();
677     assert(ModuleToDefinedGVSummaries.count(ModulePath));
678     const GVSummaryMapTy &DefinedGlobals =
679         ModuleToDefinedGVSummaries.find(ModulePath)->second;
680     BackendThreadPool.async(
681         [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
682             const FunctionImporter::ImportMapTy &ImportList,
683             const FunctionImporter::ExportSetTy &ExportList,
684             const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
685                 &ResolvedODR,
686             const GVSummaryMapTy &DefinedGlobals,
687             MapVector<StringRef, BitcodeModule> &ModuleMap) {
688           Error E = runThinLTOBackendThread(
689               AddStream, Cache, Task, BM, CombinedIndex, ImportList,
690               ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
691           if (E) {
692             std::unique_lock<std::mutex> L(ErrMu);
693             if (Err)
694               Err = joinErrors(std::move(*Err), std::move(E));
695             else
696               Err = std::move(E);
697           }
698         },
699         BM, std::ref(CombinedIndex), std::ref(ImportList),
700         std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
701         std::ref(ModuleMap));
702     return Error::success();
703   }
704 
705   Error wait() override {
706     BackendThreadPool.wait();
707     if (Err)
708       return std::move(*Err);
709     else
710       return Error::success();
711   }
712 };
713 } // end anonymous namespace
714 
715 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
716   return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
717              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
718              AddStreamFn AddStream, NativeObjectCache Cache) {
719     return llvm::make_unique<InProcessThinBackend>(
720         Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
721         AddStream, Cache);
722   };
723 }
724 
725 // Given the original \p Path to an output file, replace any path
726 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
727 // resulting directory if it does not yet exist.
728 std::string lto::getThinLTOOutputFile(const std::string &Path,
729                                       const std::string &OldPrefix,
730                                       const std::string &NewPrefix) {
731   if (OldPrefix.empty() && NewPrefix.empty())
732     return Path;
733   SmallString<128> NewPath(Path);
734   llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
735   StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
736   if (!ParentPath.empty()) {
737     // Make sure the new directory exists, creating it if necessary.
738     if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
739       llvm::errs() << "warning: could not create directory '" << ParentPath
740                    << "': " << EC.message() << '\n';
741   }
742   return NewPath.str();
743 }
744 
745 namespace {
746 class WriteIndexesThinBackend : public ThinBackendProc {
747   std::string OldPrefix, NewPrefix;
748   bool ShouldEmitImportsFiles;
749 
750   std::string LinkedObjectsFileName;
751   std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
752 
753 public:
754   WriteIndexesThinBackend(
755       Config &Conf, ModuleSummaryIndex &CombinedIndex,
756       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
757       std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
758       std::string LinkedObjectsFileName)
759       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
760         OldPrefix(OldPrefix), NewPrefix(NewPrefix),
761         ShouldEmitImportsFiles(ShouldEmitImportsFiles),
762         LinkedObjectsFileName(LinkedObjectsFileName) {}
763 
764   Error start(
765       unsigned Task, BitcodeModule BM,
766       const FunctionImporter::ImportMapTy &ImportList,
767       const FunctionImporter::ExportSetTy &ExportList,
768       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
769       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
770     StringRef ModulePath = BM.getModuleIdentifier();
771     std::string NewModulePath =
772         getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
773 
774     std::error_code EC;
775     if (!LinkedObjectsFileName.empty()) {
776       if (!LinkedObjectsFile) {
777         LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
778             LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
779         if (EC)
780           return errorCodeToError(EC);
781       }
782       *LinkedObjectsFile << NewModulePath << '\n';
783     }
784 
785     std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
786     gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
787                                      ImportList, ModuleToSummariesForIndex);
788 
789     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
790                       sys::fs::OpenFlags::F_None);
791     if (EC)
792       return errorCodeToError(EC);
793     WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
794 
795     if (ShouldEmitImportsFiles)
796       return errorCodeToError(
797           EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
798     return Error::success();
799   }
800 
801   Error wait() override { return Error::success(); }
802 };
803 } // end anonymous namespace
804 
805 ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
806                                                std::string NewPrefix,
807                                                bool ShouldEmitImportsFiles,
808                                                std::string LinkedObjectsFile) {
809   return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
810              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
811              AddStreamFn AddStream, NativeObjectCache Cache) {
812     return llvm::make_unique<WriteIndexesThinBackend>(
813         Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
814         ShouldEmitImportsFiles, LinkedObjectsFile);
815   };
816 }
817 
818 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
819                       bool HasRegularLTO) {
820   if (ThinLTO.ModuleMap.empty())
821     return Error::success();
822 
823   if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
824     return Error::success();
825 
826   // Collect for each module the list of function it defines (GUID ->
827   // Summary).
828   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
829       ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
830   ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
831       ModuleToDefinedGVSummaries);
832   // Create entries for any modules that didn't have any GV summaries
833   // (either they didn't have any GVs to start with, or we suppressed
834   // generation of the summaries because they e.g. had inline assembly
835   // uses that couldn't be promoted/renamed on export). This is so
836   // InProcessThinBackend::start can still launch a backend thread, which
837   // is passed the map of summaries for the module, without any special
838   // handling for this case.
839   for (auto &Mod : ThinLTO.ModuleMap)
840     if (!ModuleToDefinedGVSummaries.count(Mod.first))
841       ModuleToDefinedGVSummaries.try_emplace(Mod.first);
842 
843   StringMap<FunctionImporter::ImportMapTy> ImportLists(
844       ThinLTO.ModuleMap.size());
845   StringMap<FunctionImporter::ExportSetTy> ExportLists(
846       ThinLTO.ModuleMap.size());
847   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
848 
849   if (Conf.OptLevel > 0) {
850     ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
851                              ImportLists, ExportLists);
852 
853     std::set<GlobalValue::GUID> ExportedGUIDs;
854     for (auto &Res : GlobalResolutions) {
855       if (!Res.second.IRName.empty() &&
856           Res.second.Partition == GlobalResolution::External)
857         ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
858     }
859 
860     auto isPrevailing = [&](GlobalValue::GUID GUID,
861                             const GlobalValueSummary *S) {
862       return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
863     };
864     auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
865       const auto &ExportList = ExportLists.find(ModuleIdentifier);
866       return (ExportList != ExportLists.end() &&
867               ExportList->second.count(GUID)) ||
868              ExportedGUIDs.count(GUID);
869     };
870     thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
871 
872     auto recordNewLinkage = [&](StringRef ModuleIdentifier,
873                                 GlobalValue::GUID GUID,
874                                 GlobalValue::LinkageTypes NewLinkage) {
875       ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
876     };
877 
878     thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
879                                        recordNewLinkage);
880   }
881 
882   std::unique_ptr<ThinBackendProc> BackendProc =
883       ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
884                       AddStream, Cache);
885 
886   // Partition numbers for ThinLTO jobs start at 1 (see comments for
887   // GlobalResolution in LTO.h). Task numbers, however, start at
888   // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
889   // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
890   // generation partitions.
891   unsigned Task =
892       HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
893   unsigned Partition = 1;
894 
895   for (auto &Mod : ThinLTO.ModuleMap) {
896     if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
897                                      ExportLists[Mod.first],
898                                      ResolvedODR[Mod.first], ThinLTO.ModuleMap))
899       return E;
900 
901     ++Task;
902     ++Partition;
903   }
904 
905   return BackendProc->wait();
906 }
907