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