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