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