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