1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the "backend" phase of LTO, i.e. it performs
10 // optimization and code generation on a loaded module. It is generally used
11 // internally by the LTO class but can also be used independently, for example
12 // to implement a standalone ThinLTO backend.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/LTO/LTOBackend.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/CGSCCPassManager.h"
19 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Bitcode/BitcodeReader.h"
22 #include "llvm/Bitcode/BitcodeWriter.h"
23 #include "llvm/IR/LLVMRemarkStreamer.h"
24 #include "llvm/IR/LegacyPassManager.h"
25 #include "llvm/IR/PassManager.h"
26 #include "llvm/IR/Verifier.h"
27 #include "llvm/LTO/LTO.h"
28 #include "llvm/MC/SubtargetFeature.h"
29 #include "llvm/MC/TargetRegistry.h"
30 #include "llvm/Object/ModuleSymbolTable.h"
31 #include "llvm/Passes/PassBuilder.h"
32 #include "llvm/Passes/PassPlugin.h"
33 #include "llvm/Passes/StandardInstrumentations.h"
34 #include "llvm/Support/Error.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Program.h"
39 #include "llvm/Support/ThreadPool.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
44 #include "llvm/Transforms/Scalar/LoopPassManager.h"
45 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
46 #include "llvm/Transforms/Utils/SplitModule.h"
47 
48 using namespace llvm;
49 using namespace lto;
50 
51 #define DEBUG_TYPE "lto-backend"
52 
53 enum class LTOBitcodeEmbedding {
54   DoNotEmbed = 0,
55   EmbedOptimized = 1,
56   EmbedPostMergePreOptimized = 2
57 };
58 
59 static cl::opt<LTOBitcodeEmbedding> EmbedBitcode(
60     "lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed),
61     cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none",
62                           "Do not embed"),
63                clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized",
64                           "Embed after all optimization passes"),
65                clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized,
66                           "post-merge-pre-opt",
67                           "Embed post merge, but before optimizations")),
68     cl::desc("Embed LLVM bitcode in object files produced by LTO"));
69 
70 static cl::opt<bool> ThinLTOAssumeMerged(
71     "thinlto-assume-merged", cl::init(false),
72     cl::desc("Assume the input has already undergone ThinLTO function "
73              "importing and the other pre-optimization pipeline changes."));
74 
75 namespace llvm {
76 extern cl::opt<bool> NoPGOWarnMismatch;
77 }
78 
79 [[noreturn]] static void reportOpenError(StringRef Path, Twine Msg) {
80   errs() << "failed to open " << Path << ": " << Msg << '\n';
81   errs().flush();
82   exit(1);
83 }
84 
85 Error Config::addSaveTemps(std::string OutputFileName, bool UseInputModulePath,
86                            const DenseSet<StringRef> &SaveTempsArgs) {
87   ShouldDiscardValueNames = false;
88 
89   std::error_code EC;
90   if (SaveTempsArgs.empty() || SaveTempsArgs.contains("resolution")) {
91     ResolutionFile =
92         std::make_unique<raw_fd_ostream>(OutputFileName + "resolution.txt", EC,
93                                          sys::fs::OpenFlags::OF_TextWithCRLF);
94     if (EC) {
95       ResolutionFile.reset();
96       return errorCodeToError(EC);
97     }
98   }
99 
100   auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
101     // Keep track of the hook provided by the linker, which also needs to run.
102     ModuleHookFn LinkerHook = Hook;
103     Hook = [=](unsigned Task, const Module &M) {
104       // If the linker's hook returned false, we need to pass that result
105       // through.
106       if (LinkerHook && !LinkerHook(Task, M))
107         return false;
108 
109       std::string PathPrefix;
110       // If this is the combined module (not a ThinLTO backend compile) or the
111       // user hasn't requested using the input module's path, emit to a file
112       // named from the provided OutputFileName with the Task ID appended.
113       if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
114         PathPrefix = OutputFileName;
115         if (Task != (unsigned)-1)
116           PathPrefix += utostr(Task) + ".";
117       } else
118         PathPrefix = M.getModuleIdentifier() + ".";
119       std::string Path = PathPrefix + PathSuffix + ".bc";
120       std::error_code EC;
121       raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
122       // Because -save-temps is a debugging feature, we report the error
123       // directly and exit.
124       if (EC)
125         reportOpenError(Path, EC.message());
126       WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
127       return true;
128     };
129   };
130 
131   auto SaveCombinedIndex =
132       [=](const ModuleSummaryIndex &Index,
133           const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
134         std::string Path = OutputFileName + "index.bc";
135         std::error_code EC;
136         raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
137         // Because -save-temps is a debugging feature, we report the error
138         // directly and exit.
139         if (EC)
140           reportOpenError(Path, EC.message());
141         writeIndexToFile(Index, OS);
142 
143         Path = OutputFileName + "index.dot";
144         raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::OF_None);
145         if (EC)
146           reportOpenError(Path, EC.message());
147         Index.exportToDot(OSDot, GUIDPreservedSymbols);
148         return true;
149       };
150 
151   if (SaveTempsArgs.empty()) {
152     setHook("0.preopt", PreOptModuleHook);
153     setHook("1.promote", PostPromoteModuleHook);
154     setHook("2.internalize", PostInternalizeModuleHook);
155     setHook("3.import", PostImportModuleHook);
156     setHook("4.opt", PostOptModuleHook);
157     setHook("5.precodegen", PreCodeGenModuleHook);
158     CombinedIndexHook = SaveCombinedIndex;
159   } else {
160     if (SaveTempsArgs.contains("preopt"))
161       setHook("0.preopt", PreOptModuleHook);
162     if (SaveTempsArgs.contains("promote"))
163       setHook("1.promote", PostPromoteModuleHook);
164     if (SaveTempsArgs.contains("internalize"))
165       setHook("2.internalize", PostInternalizeModuleHook);
166     if (SaveTempsArgs.contains("import"))
167       setHook("3.import", PostImportModuleHook);
168     if (SaveTempsArgs.contains("opt"))
169       setHook("4.opt", PostOptModuleHook);
170     if (SaveTempsArgs.contains("precodegen"))
171       setHook("5.precodegen", PreCodeGenModuleHook);
172     if (SaveTempsArgs.contains("combinedindex"))
173       CombinedIndexHook = SaveCombinedIndex;
174   }
175 
176   return Error::success();
177 }
178 
179 #define HANDLE_EXTENSION(Ext)                                                  \
180   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
181 #include "llvm/Support/Extension.def"
182 
183 static void RegisterPassPlugins(ArrayRef<std::string> PassPlugins,
184                                 PassBuilder &PB) {
185 #define HANDLE_EXTENSION(Ext)                                                  \
186   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
187 #include "llvm/Support/Extension.def"
188 
189   // Load requested pass plugins and let them register pass builder callbacks
190   for (auto &PluginFN : PassPlugins) {
191     auto PassPlugin = PassPlugin::Load(PluginFN);
192     if (!PassPlugin) {
193       errs() << "Failed to load passes from '" << PluginFN
194              << "'. Request ignored.\n";
195       continue;
196     }
197 
198     PassPlugin->registerPassBuilderCallbacks(PB);
199   }
200 }
201 
202 static std::unique_ptr<TargetMachine>
203 createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
204   StringRef TheTriple = M.getTargetTriple();
205   SubtargetFeatures Features;
206   Features.getDefaultSubtargetFeatures(Triple(TheTriple));
207   for (const std::string &A : Conf.MAttrs)
208     Features.AddFeature(A);
209 
210   Optional<Reloc::Model> RelocModel = None;
211   if (Conf.RelocModel)
212     RelocModel = *Conf.RelocModel;
213   else if (M.getModuleFlag("PIC Level"))
214     RelocModel =
215         M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
216 
217   Optional<CodeModel::Model> CodeModel;
218   if (Conf.CodeModel)
219     CodeModel = *Conf.CodeModel;
220   else
221     CodeModel = M.getCodeModel();
222 
223   std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
224       TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
225       CodeModel, Conf.CGOptLevel));
226   assert(TM && "Failed to create target machine");
227   return TM;
228 }
229 
230 static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
231                            unsigned OptLevel, bool IsThinLTO,
232                            ModuleSummaryIndex *ExportSummary,
233                            const ModuleSummaryIndex *ImportSummary) {
234   Optional<PGOOptions> PGOOpt;
235   if (!Conf.SampleProfile.empty())
236     PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
237                         PGOOptions::SampleUse, PGOOptions::NoCSAction, true);
238   else if (Conf.RunCSIRInstr) {
239     PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
240                         PGOOptions::IRUse, PGOOptions::CSIRInstr,
241                         Conf.AddFSDiscriminator);
242   } else if (!Conf.CSIRProfile.empty()) {
243     PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
244                         PGOOptions::IRUse, PGOOptions::CSIRUse,
245                         Conf.AddFSDiscriminator);
246     NoPGOWarnMismatch = !Conf.PGOWarnMismatch;
247   } else if (Conf.AddFSDiscriminator) {
248     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
249                         PGOOptions::NoCSAction, true);
250   }
251   TM->setPGOOption(PGOOpt);
252 
253   LoopAnalysisManager LAM;
254   FunctionAnalysisManager FAM;
255   CGSCCAnalysisManager CGAM;
256   ModuleAnalysisManager MAM;
257 
258   PassInstrumentationCallbacks PIC;
259   StandardInstrumentations SI(Conf.DebugPassManager);
260   SI.registerCallbacks(PIC, &FAM);
261   PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
262 
263   RegisterPassPlugins(Conf.PassPlugins, PB);
264 
265   std::unique_ptr<TargetLibraryInfoImpl> TLII(
266       new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
267   if (Conf.Freestanding)
268     TLII->disableAllFunctions();
269   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
270 
271   // Parse a custom AA pipeline if asked to.
272   if (!Conf.AAPipeline.empty()) {
273     AAManager AA;
274     if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {
275       report_fatal_error(Twine("unable to parse AA pipeline description '") +
276                          Conf.AAPipeline + "': " + toString(std::move(Err)));
277     }
278     // Register the AA manager first so that our version is the one used.
279     FAM.registerPass([&] { return std::move(AA); });
280   }
281 
282   // Register all the basic analyses with the managers.
283   PB.registerModuleAnalyses(MAM);
284   PB.registerCGSCCAnalyses(CGAM);
285   PB.registerFunctionAnalyses(FAM);
286   PB.registerLoopAnalyses(LAM);
287   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
288 
289   ModulePassManager MPM;
290 
291   if (!Conf.DisableVerify)
292     MPM.addPass(VerifierPass());
293 
294   OptimizationLevel OL;
295 
296   switch (OptLevel) {
297   default:
298     llvm_unreachable("Invalid optimization level");
299   case 0:
300     OL = OptimizationLevel::O0;
301     break;
302   case 1:
303     OL = OptimizationLevel::O1;
304     break;
305   case 2:
306     OL = OptimizationLevel::O2;
307     break;
308   case 3:
309     OL = OptimizationLevel::O3;
310     break;
311   }
312 
313   // Parse a custom pipeline if asked to.
314   if (!Conf.OptPipeline.empty()) {
315     if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {
316       report_fatal_error(Twine("unable to parse pass pipeline description '") +
317                          Conf.OptPipeline + "': " + toString(std::move(Err)));
318     }
319   } else if (Conf.UseDefaultPipeline) {
320     MPM.addPass(PB.buildPerModuleDefaultPipeline(OL));
321   } else if (IsThinLTO) {
322     MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
323   } else {
324     MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
325   }
326 
327   if (!Conf.DisableVerify)
328     MPM.addPass(VerifierPass());
329 
330   MPM.run(Mod, MAM);
331 }
332 
333 bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
334               bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
335               const ModuleSummaryIndex *ImportSummary,
336               const std::vector<uint8_t> &CmdArgs) {
337   if (EmbedBitcode == LTOBitcodeEmbedding::EmbedPostMergePreOptimized) {
338     // FIXME: the motivation for capturing post-merge bitcode and command line
339     // is replicating the compilation environment from bitcode, without needing
340     // to understand the dependencies (the functions to be imported). This
341     // assumes a clang - based invocation, case in which we have the command
342     // line.
343     // It's not very clear how the above motivation would map in the
344     // linker-based case, so we currently don't plumb the command line args in
345     // that case.
346     if (CmdArgs.empty())
347       LLVM_DEBUG(
348           dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
349                     "command line arguments are not available");
350     llvm::embedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
351                                /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
352                                /*Cmdline*/ CmdArgs);
353   }
354   // FIXME: Plumb the combined index into the new pass manager.
355   runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
356                  ImportSummary);
357   return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
358 }
359 
360 static void codegen(const Config &Conf, TargetMachine *TM,
361                     AddStreamFn AddStream, unsigned Task, Module &Mod,
362                     const ModuleSummaryIndex &CombinedIndex) {
363   if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
364     return;
365 
366   if (EmbedBitcode == LTOBitcodeEmbedding::EmbedOptimized)
367     llvm::embedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
368                                /*EmbedBitcode*/ true,
369                                /*EmbedCmdline*/ false,
370                                /*CmdArgs*/ std::vector<uint8_t>());
371 
372   std::unique_ptr<ToolOutputFile> DwoOut;
373   SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
374   if (!Conf.DwoDir.empty()) {
375     std::error_code EC;
376     if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
377       report_fatal_error(Twine("Failed to create directory ") + Conf.DwoDir +
378                          ": " + EC.message());
379 
380     DwoFile = Conf.DwoDir;
381     sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
382     TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
383   } else
384     TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
385 
386   if (!DwoFile.empty()) {
387     std::error_code EC;
388     DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
389     if (EC)
390       report_fatal_error(Twine("Failed to open ") + DwoFile + ": " +
391                          EC.message());
392   }
393 
394   Expected<std::unique_ptr<CachedFileStream>> StreamOrErr = AddStream(Task);
395   if (Error Err = StreamOrErr.takeError())
396     report_fatal_error(std::move(Err));
397   std::unique_ptr<CachedFileStream> &Stream = *StreamOrErr;
398   TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
399 
400   legacy::PassManager CodeGenPasses;
401   TargetLibraryInfoImpl TLII(Triple(Mod.getTargetTriple()));
402   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
403   CodeGenPasses.add(
404       createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex));
405   if (Conf.PreCodeGenPassesHook)
406     Conf.PreCodeGenPassesHook(CodeGenPasses);
407   if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
408                               DwoOut ? &DwoOut->os() : nullptr,
409                               Conf.CGFileType))
410     report_fatal_error("Failed to setup codegen");
411   CodeGenPasses.run(Mod);
412 
413   if (DwoOut)
414     DwoOut->keep();
415 }
416 
417 static void splitCodeGen(const Config &C, TargetMachine *TM,
418                          AddStreamFn AddStream,
419                          unsigned ParallelCodeGenParallelismLevel, Module &Mod,
420                          const ModuleSummaryIndex &CombinedIndex) {
421   ThreadPool CodegenThreadPool(
422       heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
423   unsigned ThreadCount = 0;
424   const Target *T = &TM->getTarget();
425 
426   SplitModule(
427       Mod, ParallelCodeGenParallelismLevel,
428       [&](std::unique_ptr<Module> MPart) {
429         // We want to clone the module in a new context to multi-thread the
430         // codegen. We do it by serializing partition modules to bitcode
431         // (while still on the main thread, in order to avoid data races) and
432         // spinning up new threads which deserialize the partitions into
433         // separate contexts.
434         // FIXME: Provide a more direct way to do this in LLVM.
435         SmallString<0> BC;
436         raw_svector_ostream BCOS(BC);
437         WriteBitcodeToFile(*MPart, BCOS);
438 
439         // Enqueue the task
440         CodegenThreadPool.async(
441             [&](const SmallString<0> &BC, unsigned ThreadId) {
442               LTOLLVMContext Ctx(C);
443               Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
444                   MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
445                   Ctx);
446               if (!MOrErr)
447                 report_fatal_error("Failed to read bitcode");
448               std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
449 
450               std::unique_ptr<TargetMachine> TM =
451                   createTargetMachine(C, T, *MPartInCtx);
452 
453               codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
454                       CombinedIndex);
455             },
456             // Pass BC using std::move to ensure that it get moved rather than
457             // copied into the thread's context.
458             std::move(BC), ThreadCount++);
459       },
460       false);
461 
462   // Because the inner lambda (which runs in a worker thread) captures our local
463   // variables, we need to wait for the worker threads to terminate before we
464   // can leave the function scope.
465   CodegenThreadPool.wait();
466 }
467 
468 static Expected<const Target *> initAndLookupTarget(const Config &C,
469                                                     Module &Mod) {
470   if (!C.OverrideTriple.empty())
471     Mod.setTargetTriple(C.OverrideTriple);
472   else if (Mod.getTargetTriple().empty())
473     Mod.setTargetTriple(C.DefaultTriple);
474 
475   std::string Msg;
476   const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
477   if (!T)
478     return make_error<StringError>(Msg, inconvertibleErrorCode());
479   return T;
480 }
481 
482 Error lto::finalizeOptimizationRemarks(
483     std::unique_ptr<ToolOutputFile> DiagOutputFile) {
484   // Make sure we flush the diagnostic remarks file in case the linker doesn't
485   // call the global destructors before exiting.
486   if (!DiagOutputFile)
487     return Error::success();
488   DiagOutputFile->keep();
489   DiagOutputFile->os().flush();
490   return Error::success();
491 }
492 
493 Error lto::backend(const Config &C, AddStreamFn AddStream,
494                    unsigned ParallelCodeGenParallelismLevel, Module &Mod,
495                    ModuleSummaryIndex &CombinedIndex) {
496   Expected<const Target *> TOrErr = initAndLookupTarget(C, Mod);
497   if (!TOrErr)
498     return TOrErr.takeError();
499 
500   std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, Mod);
501 
502   if (!C.CodeGenOnly) {
503     if (!opt(C, TM.get(), 0, Mod, /*IsThinLTO=*/false,
504              /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
505              /*CmdArgs*/ std::vector<uint8_t>()))
506       return Error::success();
507   }
508 
509   if (ParallelCodeGenParallelismLevel == 1) {
510     codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);
511   } else {
512     splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
513                  CombinedIndex);
514   }
515   return Error::success();
516 }
517 
518 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
519                             const ModuleSummaryIndex &Index) {
520   std::vector<GlobalValue*> DeadGVs;
521   for (auto &GV : Mod.global_values())
522     if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
523       if (!Index.isGlobalValueLive(GVS)) {
524         DeadGVs.push_back(&GV);
525         convertToDeclaration(GV);
526       }
527 
528   // Now that all dead bodies have been dropped, delete the actual objects
529   // themselves when possible.
530   for (GlobalValue *GV : DeadGVs) {
531     GV->removeDeadConstantUsers();
532     // Might reference something defined in native object (i.e. dropped a
533     // non-prevailing IR def, but we need to keep the declaration).
534     if (GV->use_empty())
535       GV->eraseFromParent();
536   }
537 }
538 
539 Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
540                        Module &Mod, const ModuleSummaryIndex &CombinedIndex,
541                        const FunctionImporter::ImportMapTy &ImportList,
542                        const GVSummaryMapTy &DefinedGlobals,
543                        MapVector<StringRef, BitcodeModule> *ModuleMap,
544                        const std::vector<uint8_t> &CmdArgs) {
545   Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
546   if (!TOrErr)
547     return TOrErr.takeError();
548 
549   std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
550 
551   // Setup optimization remarks.
552   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
553       Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
554       Conf.RemarksFormat, Conf.RemarksWithHotness, Conf.RemarksHotnessThreshold,
555       Task);
556   if (!DiagFileOrErr)
557     return DiagFileOrErr.takeError();
558   auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
559 
560   // Set the partial sample profile ratio in the profile summary module flag of
561   // the module, if applicable.
562   Mod.setPartialSampleProfileRatio(CombinedIndex);
563 
564   updatePublicTypeTestCalls(Mod, CombinedIndex.withWholeProgramVisibility());
565 
566   if (Conf.CodeGenOnly) {
567     codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
568     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
569   }
570 
571   if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
572     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
573 
574   auto OptimizeAndCodegen =
575       [&](Module &Mod, TargetMachine *TM,
576           std::unique_ptr<ToolOutputFile> DiagnosticOutputFile) {
577         if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
578                  /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
579                  CmdArgs))
580           return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
581 
582         codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
583         return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
584       };
585 
586   if (ThinLTOAssumeMerged)
587     return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
588 
589   // When linking an ELF shared object, dso_local should be dropped. We
590   // conservatively do this for -fpic.
591   bool ClearDSOLocalOnDeclarations =
592       TM->getTargetTriple().isOSBinFormatELF() &&
593       TM->getRelocationModel() != Reloc::Static &&
594       Mod.getPIELevel() == PIELevel::Default;
595   renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
596 
597   dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
598 
599   thinLTOFinalizeInModule(Mod, DefinedGlobals, /*PropagateAttrs=*/true);
600 
601   if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
602     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
603 
604   if (!DefinedGlobals.empty())
605     thinLTOInternalizeModule(Mod, DefinedGlobals);
606 
607   if (Conf.PostInternalizeModuleHook &&
608       !Conf.PostInternalizeModuleHook(Task, Mod))
609     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
610 
611   auto ModuleLoader = [&](StringRef Identifier) {
612     assert(Mod.getContext().isODRUniquingDebugTypes() &&
613            "ODR Type uniquing should be enabled on the context");
614     if (ModuleMap) {
615       auto I = ModuleMap->find(Identifier);
616       assert(I != ModuleMap->end());
617       return I->second.getLazyModule(Mod.getContext(),
618                                      /*ShouldLazyLoadMetadata=*/true,
619                                      /*IsImporting*/ true);
620     }
621 
622     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
623         llvm::MemoryBuffer::getFile(Identifier);
624     if (!MBOrErr)
625       return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
626           Twine("Error loading imported file ") + Identifier + " : ",
627           MBOrErr.getError()));
628 
629     Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
630     if (!BMOrErr)
631       return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
632           Twine("Error loading imported file ") + Identifier + " : " +
633               toString(BMOrErr.takeError()),
634           inconvertibleErrorCode()));
635 
636     Expected<std::unique_ptr<Module>> MOrErr =
637         BMOrErr->getLazyModule(Mod.getContext(),
638                                /*ShouldLazyLoadMetadata=*/true,
639                                /*IsImporting*/ true);
640     if (MOrErr)
641       (*MOrErr)->setOwnedMemoryBuffer(std::move(*MBOrErr));
642     return MOrErr;
643   };
644 
645   FunctionImporter Importer(CombinedIndex, ModuleLoader,
646                             ClearDSOLocalOnDeclarations);
647   if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
648     return Err;
649 
650   if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
651     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
652 
653   return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
654 }
655 
656 BitcodeModule *lto::findThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
657   if (ThinLTOAssumeMerged && BMs.size() == 1)
658     return BMs.begin();
659 
660   for (BitcodeModule &BM : BMs) {
661     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
662     if (LTOInfo && LTOInfo->IsThinLTO)
663       return &BM;
664   }
665   return nullptr;
666 }
667 
668 Expected<BitcodeModule> lto::findThinLTOModule(MemoryBufferRef MBRef) {
669   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
670   if (!BMsOrErr)
671     return BMsOrErr.takeError();
672 
673   // The bitcode file may contain multiple modules, we want the one that is
674   // marked as being the ThinLTO module.
675   if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
676     return *Bm;
677 
678   return make_error<StringError>("Could not find module summary",
679                                  inconvertibleErrorCode());
680 }
681 
682 bool lto::initImportList(const Module &M,
683                          const ModuleSummaryIndex &CombinedIndex,
684                          FunctionImporter::ImportMapTy &ImportList) {
685   if (ThinLTOAssumeMerged)
686     return true;
687   // We can simply import the values mentioned in the combined index, since
688   // we should only invoke this using the individual indexes written out
689   // via a WriteIndexesThinBackend.
690   for (const auto &GlobalList : CombinedIndex) {
691     // Ignore entries for undefined references.
692     if (GlobalList.second.SummaryList.empty())
693       continue;
694 
695     auto GUID = GlobalList.first;
696     for (const auto &Summary : GlobalList.second.SummaryList) {
697       // Skip the summaries for the importing module. These are included to
698       // e.g. record required linkage changes.
699       if (Summary->modulePath() == M.getModuleIdentifier())
700         continue;
701       // Add an entry to provoke importing by thinBackend.
702       ImportList[Summary->modulePath()].insert(GUID);
703     }
704   }
705   return true;
706 }
707