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