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