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 
228   RegisterPassPlugins(Conf.PassPlugins, PB);
229 
230   LoopAnalysisManager LAM(Conf.DebugPassManager);
231   FunctionAnalysisManager FAM(Conf.DebugPassManager);
232   CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
233   ModuleAnalysisManager MAM(Conf.DebugPassManager);
234 
235   std::unique_ptr<TargetLibraryInfoImpl> TLII(
236       new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
237   if (Conf.Freestanding)
238     TLII->disableAllFunctions();
239   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
240 
241   AAManager AA;
242   // Parse a custom AA pipeline if asked to.
243   if (!Conf.AAPipeline.empty()) {
244     if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {
245       report_fatal_error("unable to parse AA pipeline description '" +
246                          Conf.AAPipeline + "': " + toString(std::move(Err)));
247     }
248   } else {
249     AA = PB.buildDefaultAAPipeline();
250   }
251   // Register the AA manager first so that our version is the one used.
252   FAM.registerPass([&] { return std::move(AA); });
253 
254   // Register all the basic analyses with the managers.
255   PB.registerModuleAnalyses(MAM);
256   PB.registerCGSCCAnalyses(CGAM);
257   PB.registerFunctionAnalyses(FAM);
258   PB.registerLoopAnalyses(LAM);
259   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
260 
261   ModulePassManager MPM(Conf.DebugPassManager);
262 
263   if (!Conf.DisableVerify)
264     MPM.addPass(VerifierPass());
265 
266   PassBuilder::OptimizationLevel OL;
267 
268   switch (OptLevel) {
269   default:
270     llvm_unreachable("Invalid optimization level");
271   case 0:
272     OL = PassBuilder::OptimizationLevel::O0;
273     break;
274   case 1:
275     OL = PassBuilder::OptimizationLevel::O1;
276     break;
277   case 2:
278     OL = PassBuilder::OptimizationLevel::O2;
279     break;
280   case 3:
281     OL = PassBuilder::OptimizationLevel::O3;
282     break;
283   }
284 
285   // Parse a custom pipeline if asked to.
286   if (!Conf.OptPipeline.empty()) {
287     if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {
288       report_fatal_error("unable to parse pass pipeline description '" +
289                          Conf.OptPipeline + "': " + toString(std::move(Err)));
290     }
291   } else if (IsThinLTO) {
292     MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
293   } else {
294     MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
295   }
296 
297   if (!Conf.DisableVerify)
298     MPM.addPass(VerifierPass());
299 
300   MPM.run(Mod, MAM);
301 }
302 
303 static void runOldPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
304                            bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
305                            const ModuleSummaryIndex *ImportSummary) {
306   legacy::PassManager passes;
307   passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
308 
309   PassManagerBuilder PMB;
310   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
311   if (Conf.Freestanding)
312     PMB.LibraryInfo->disableAllFunctions();
313   PMB.Inliner = createFunctionInliningPass();
314   PMB.ExportSummary = ExportSummary;
315   PMB.ImportSummary = ImportSummary;
316   // Unconditionally verify input since it is not verified before this
317   // point and has unknown origin.
318   PMB.VerifyInput = true;
319   PMB.VerifyOutput = !Conf.DisableVerify;
320   PMB.LoopVectorize = true;
321   PMB.SLPVectorize = true;
322   PMB.OptLevel = Conf.OptLevel;
323   PMB.PGOSampleUse = Conf.SampleProfile;
324   PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
325   if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
326     PMB.EnablePGOCSInstrUse = true;
327     PMB.PGOInstrUse = Conf.CSIRProfile;
328   }
329   if (IsThinLTO)
330     PMB.populateThinLTOPassManager(passes);
331   else
332     PMB.populateLTOPassManager(passes);
333   passes.run(Mod);
334 }
335 
336 bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
337               bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
338               const ModuleSummaryIndex *ImportSummary,
339               const std::vector<uint8_t> &CmdArgs) {
340   if (EmbedBitcode == LTOBitcodeEmbedding::EmbedPostMergePreOptimized) {
341     // FIXME: the motivation for capturing post-merge bitcode and command line
342     // is replicating the compilation environment from bitcode, without needing
343     // to understand the dependencies (the functions to be imported). This
344     // assumes a clang - based invocation, case in which we have the command
345     // line.
346     // It's not very clear how the above motivation would map in the
347     // linker-based case, so we currently don't plumb the command line args in
348     // that case.
349     if (CmdArgs.empty())
350       LLVM_DEBUG(
351           dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
352                     "command line arguments are not available");
353     llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
354                                /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
355                                /*Cmdline*/ CmdArgs);
356   }
357   // FIXME: Plumb the combined index into the new pass manager.
358   if (Conf.UseNewPM || !Conf.OptPipeline.empty()) {
359     runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
360                    ImportSummary);
361   } else {
362     runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
363   }
364   return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
365 }
366 
367 static void codegen(const Config &Conf, TargetMachine *TM,
368                     AddStreamFn AddStream, unsigned Task, Module &Mod,
369                     const ModuleSummaryIndex &CombinedIndex) {
370   if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
371     return;
372 
373   if (EmbedBitcode == LTOBitcodeEmbedding::EmbedOptimized)
374     llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
375                                /*EmbedBitcode*/ true,
376                                /*EmbedCmdline*/ false,
377                                /*CmdArgs*/ std::vector<uint8_t>());
378 
379   std::unique_ptr<ToolOutputFile> DwoOut;
380   SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
381   if (!Conf.DwoDir.empty()) {
382     std::error_code EC;
383     if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
384       report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
385                          EC.message());
386 
387     DwoFile = Conf.DwoDir;
388     sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
389     TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
390   } else
391     TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
392 
393   if (!DwoFile.empty()) {
394     std::error_code EC;
395     DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
396     if (EC)
397       report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
398   }
399 
400   auto Stream = AddStream(Task);
401   legacy::PassManager CodeGenPasses;
402   CodeGenPasses.add(
403       createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex));
404   if (Conf.PreCodeGenPassesHook)
405     Conf.PreCodeGenPassesHook(CodeGenPasses);
406   if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
407                               DwoOut ? &DwoOut->os() : nullptr,
408                               Conf.CGFileType))
409     report_fatal_error("Failed to setup codegen");
410   CodeGenPasses.run(Mod);
411 
412   if (DwoOut)
413     DwoOut->keep();
414 }
415 
416 static void splitCodeGen(const Config &C, TargetMachine *TM,
417                          AddStreamFn AddStream,
418                          unsigned ParallelCodeGenParallelismLevel, Module &Mod,
419                          const ModuleSummaryIndex &CombinedIndex) {
420   ThreadPool CodegenThreadPool(
421       heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
422   unsigned ThreadCount = 0;
423   const Target *T = &TM->getTarget();
424 
425   SplitModule(
426       Mod, ParallelCodeGenParallelismLevel,
427       [&](std::unique_ptr<Module> MPart) {
428         // We want to clone the module in a new context to multi-thread the
429         // codegen. We do it by serializing partition modules to bitcode
430         // (while still on the main thread, in order to avoid data races) and
431         // spinning up new threads which deserialize the partitions into
432         // separate contexts.
433         // FIXME: Provide a more direct way to do this in LLVM.
434         SmallString<0> BC;
435         raw_svector_ostream BCOS(BC);
436         WriteBitcodeToFile(*MPart, BCOS);
437 
438         // Enqueue the task
439         CodegenThreadPool.async(
440             [&](const SmallString<0> &BC, unsigned ThreadId) {
441               LTOLLVMContext Ctx(C);
442               Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
443                   MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
444                   Ctx);
445               if (!MOrErr)
446                 report_fatal_error("Failed to read bitcode");
447               std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
448 
449               std::unique_ptr<TargetMachine> TM =
450                   createTargetMachine(C, T, *MPartInCtx);
451 
452               codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
453                       CombinedIndex);
454             },
455             // Pass BC using std::move to ensure that it get moved rather than
456             // copied into the thread's context.
457             std::move(BC), ThreadCount++);
458       },
459       false);
460 
461   // Because the inner lambda (which runs in a worker thread) captures our local
462   // variables, we need to wait for the worker threads to terminate before we
463   // can leave the function scope.
464   CodegenThreadPool.wait();
465 }
466 
467 static Expected<const Target *> initAndLookupTarget(const Config &C,
468                                                     Module &Mod) {
469   if (!C.OverrideTriple.empty())
470     Mod.setTargetTriple(C.OverrideTriple);
471   else if (Mod.getTargetTriple().empty())
472     Mod.setTargetTriple(C.DefaultTriple);
473 
474   std::string Msg;
475   const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
476   if (!T)
477     return make_error<StringError>(Msg, inconvertibleErrorCode());
478   return T;
479 }
480 
481 Error lto::finalizeOptimizationRemarks(
482     std::unique_ptr<ToolOutputFile> DiagOutputFile) {
483   // Make sure we flush the diagnostic remarks file in case the linker doesn't
484   // call the global destructors before exiting.
485   if (!DiagOutputFile)
486     return Error::success();
487   DiagOutputFile->keep();
488   DiagOutputFile->os().flush();
489   return Error::success();
490 }
491 
492 Error lto::backend(const Config &C, AddStreamFn AddStream,
493                    unsigned ParallelCodeGenParallelismLevel, Module &Mod,
494                    ModuleSummaryIndex &CombinedIndex) {
495   Expected<const Target *> TOrErr = initAndLookupTarget(C, Mod);
496   if (!TOrErr)
497     return TOrErr.takeError();
498 
499   std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, Mod);
500 
501   if (!C.CodeGenOnly) {
502     if (!opt(C, TM.get(), 0, Mod, /*IsThinLTO=*/false,
503              /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
504              /*CmdArgs*/ std::vector<uint8_t>()))
505       return Error::success();
506   }
507 
508   if (ParallelCodeGenParallelismLevel == 1) {
509     codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);
510   } else {
511     splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
512                  CombinedIndex);
513   }
514   return Error::success();
515 }
516 
517 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
518                             const ModuleSummaryIndex &Index) {
519   std::vector<GlobalValue*> DeadGVs;
520   for (auto &GV : Mod.global_values())
521     if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
522       if (!Index.isGlobalValueLive(GVS)) {
523         DeadGVs.push_back(&GV);
524         convertToDeclaration(GV);
525       }
526 
527   // Now that all dead bodies have been dropped, delete the actual objects
528   // themselves when possible.
529   for (GlobalValue *GV : DeadGVs) {
530     GV->removeDeadConstantUsers();
531     // Might reference something defined in native object (i.e. dropped a
532     // non-prevailing IR def, but we need to keep the declaration).
533     if (GV->use_empty())
534       GV->eraseFromParent();
535   }
536 }
537 
538 Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
539                        Module &Mod, const ModuleSummaryIndex &CombinedIndex,
540                        const FunctionImporter::ImportMapTy &ImportList,
541                        const GVSummaryMapTy &DefinedGlobals,
542                        MapVector<StringRef, BitcodeModule> &ModuleMap,
543                        const std::vector<uint8_t> &CmdArgs) {
544   Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
545   if (!TOrErr)
546     return TOrErr.takeError();
547 
548   std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
549 
550   // Setup optimization remarks.
551   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
552       Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
553       Conf.RemarksFormat, Conf.RemarksWithHotness, Conf.RemarksHotnessThreshold,
554       Task);
555   if (!DiagFileOrErr)
556     return DiagFileOrErr.takeError();
557   auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
558 
559   // Set the partial sample profile ratio in the profile summary module flag of
560   // the module, if applicable.
561   Mod.setPartialSampleProfileRatio(CombinedIndex);
562 
563   if (Conf.CodeGenOnly) {
564     codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
565     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
566   }
567 
568   if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
569     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
570 
571   auto OptimizeAndCodegen =
572       [&](Module &Mod, TargetMachine *TM,
573           std::unique_ptr<ToolOutputFile> DiagnosticOutputFile) {
574         if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
575                  /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
576                  CmdArgs))
577           return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
578 
579         codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
580         return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
581       };
582 
583   if (ThinLTOAssumeMerged)
584     return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
585 
586   // When linking an ELF shared object, dso_local should be dropped. We
587   // conservatively do this for -fpic.
588   bool ClearDSOLocalOnDeclarations =
589       TM->getTargetTriple().isOSBinFormatELF() &&
590       TM->getRelocationModel() != Reloc::Static &&
591       Mod.getPIELevel() == PIELevel::Default;
592   renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
593 
594   dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
595 
596   thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
597 
598   if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
599     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
600 
601   if (!DefinedGlobals.empty())
602     thinLTOInternalizeModule(Mod, DefinedGlobals);
603 
604   if (Conf.PostInternalizeModuleHook &&
605       !Conf.PostInternalizeModuleHook(Task, Mod))
606     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
607 
608   auto ModuleLoader = [&](StringRef Identifier) {
609     assert(Mod.getContext().isODRUniquingDebugTypes() &&
610            "ODR Type uniquing should be enabled on the context");
611     auto I = ModuleMap.find(Identifier);
612     assert(I != ModuleMap.end());
613     return I->second.getLazyModule(Mod.getContext(),
614                                    /*ShouldLazyLoadMetadata=*/true,
615                                    /*IsImporting*/ true);
616   };
617 
618   FunctionImporter Importer(CombinedIndex, ModuleLoader,
619                             ClearDSOLocalOnDeclarations);
620   if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
621     return Err;
622 
623   if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
624     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
625 
626   return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
627 }
628 
629 BitcodeModule *lto::findThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
630   if (ThinLTOAssumeMerged && BMs.size() == 1)
631     return BMs.begin();
632 
633   for (BitcodeModule &BM : BMs) {
634     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
635     if (LTOInfo && LTOInfo->IsThinLTO)
636       return &BM;
637   }
638   return nullptr;
639 }
640 
641 Expected<BitcodeModule> lto::findThinLTOModule(MemoryBufferRef MBRef) {
642   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
643   if (!BMsOrErr)
644     return BMsOrErr.takeError();
645 
646   // The bitcode file may contain multiple modules, we want the one that is
647   // marked as being the ThinLTO module.
648   if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
649     return *Bm;
650 
651   return make_error<StringError>("Could not find module summary",
652                                  inconvertibleErrorCode());
653 }
654 
655 bool lto::loadReferencedModules(
656     const Module &M, const ModuleSummaryIndex &CombinedIndex,
657     FunctionImporter::ImportMapTy &ImportList,
658     MapVector<llvm::StringRef, llvm::BitcodeModule> &ModuleMap,
659     std::vector<std::unique_ptr<llvm::MemoryBuffer>>
660         &OwnedImportsLifetimeManager) {
661   if (ThinLTOAssumeMerged)
662     return true;
663   // We can simply import the values mentioned in the combined index, since
664   // we should only invoke this using the individual indexes written out
665   // via a WriteIndexesThinBackend.
666   for (const auto &GlobalList : CombinedIndex) {
667     // Ignore entries for undefined references.
668     if (GlobalList.second.SummaryList.empty())
669       continue;
670 
671     auto GUID = GlobalList.first;
672     for (const auto &Summary : GlobalList.second.SummaryList) {
673       // Skip the summaries for the importing module. These are included to
674       // e.g. record required linkage changes.
675       if (Summary->modulePath() == M.getModuleIdentifier())
676         continue;
677       // Add an entry to provoke importing by thinBackend.
678       ImportList[Summary->modulePath()].insert(GUID);
679     }
680   }
681 
682   for (auto &I : ImportList) {
683     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
684         llvm::MemoryBuffer::getFile(I.first());
685     if (!MBOrErr) {
686       errs() << "Error loading imported file '" << I.first()
687              << "': " << MBOrErr.getError().message() << "\n";
688       return false;
689     }
690 
691     Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
692     if (!BMOrErr) {
693       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
694         errs() << "Error loading imported file '" << I.first()
695                << "': " << EIB.message() << '\n';
696       });
697       return false;
698     }
699     ModuleMap.insert({I.first(), *BMOrErr});
700     OwnedImportsLifetimeManager.push_back(std::move(*MBOrErr));
701   }
702   return true;
703 }
704