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