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