xref: /llvm-project/llvm/lib/LTO/LTOBackend.cpp (revision 799955eb176042999b4d12a901b1c33b42035014)
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/Bitcode/BitcodeReader.h"
22 #include "llvm/Bitcode/BitcodeWriter.h"
23 #include "llvm/CGData/CodeGenData.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/TargetRegistry.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/ThreadPool.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/VirtualFileSystem.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/TargetParser/SubtargetFeature.h"
45 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
46 #include "llvm/Transforms/Scalar/LoopPassManager.h"
47 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
48 #include "llvm/Transforms/Utils/SplitModule.h"
49 #include <optional>
50 
51 using namespace llvm;
52 using namespace lto;
53 
54 #define DEBUG_TYPE "lto-backend"
55 
56 enum class LTOBitcodeEmbedding {
57   DoNotEmbed = 0,
58   EmbedOptimized = 1,
59   EmbedPostMergePreOptimized = 2
60 };
61 
62 static cl::opt<LTOBitcodeEmbedding> EmbedBitcode(
63     "lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed),
64     cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none",
65                           "Do not embed"),
66                clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized",
67                           "Embed after all optimization passes"),
68                clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized,
69                           "post-merge-pre-opt",
70                           "Embed post merge, but before optimizations")),
71     cl::desc("Embed LLVM bitcode in object files produced by LTO"));
72 
73 static cl::opt<bool> ThinLTOAssumeMerged(
74     "thinlto-assume-merged", cl::init(false),
75     cl::desc("Assume the input has already undergone ThinLTO function "
76              "importing and the other pre-optimization pipeline changes."));
77 
78 namespace llvm {
79 extern cl::opt<bool> NoPGOWarnMismatch;
80 }
81 
82 [[noreturn]] static void reportOpenError(StringRef Path, Twine Msg) {
83   errs() << "failed to open " << Path << ": " << Msg << '\n';
84   errs().flush();
85   exit(1);
86 }
87 
88 Error Config::addSaveTemps(std::string OutputFileName, bool UseInputModulePath,
89                            const DenseSet<StringRef> &SaveTempsArgs) {
90   ShouldDiscardValueNames = false;
91 
92   std::error_code EC;
93   if (SaveTempsArgs.empty() || SaveTempsArgs.contains("resolution")) {
94     ResolutionFile =
95         std::make_unique<raw_fd_ostream>(OutputFileName + "resolution.txt", EC,
96                                          sys::fs::OpenFlags::OF_TextWithCRLF);
97     if (EC) {
98       ResolutionFile.reset();
99       return errorCodeToError(EC);
100     }
101   }
102 
103   auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
104     // Keep track of the hook provided by the linker, which also needs to run.
105     ModuleHookFn LinkerHook = Hook;
106     Hook = [=](unsigned Task, const Module &M) {
107       // If the linker's hook returned false, we need to pass that result
108       // through.
109       if (LinkerHook && !LinkerHook(Task, M))
110         return false;
111 
112       std::string PathPrefix;
113       // If this is the combined module (not a ThinLTO backend compile) or the
114       // user hasn't requested using the input module's path, emit to a file
115       // named from the provided OutputFileName with the Task ID appended.
116       if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
117         PathPrefix = OutputFileName;
118         if (Task != (unsigned)-1)
119           PathPrefix += utostr(Task) + ".";
120       } else
121         PathPrefix = M.getModuleIdentifier() + ".";
122       std::string Path = PathPrefix + PathSuffix + ".bc";
123       std::error_code EC;
124       raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
125       // Because -save-temps is a debugging feature, we report the error
126       // directly and exit.
127       if (EC)
128         reportOpenError(Path, EC.message());
129       WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
130       return true;
131     };
132   };
133 
134   auto SaveCombinedIndex =
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_Text);
148         if (EC)
149           reportOpenError(Path, EC.message());
150         Index.exportToDot(OSDot, GUIDPreservedSymbols);
151         return true;
152       };
153 
154   if (SaveTempsArgs.empty()) {
155     setHook("0.preopt", PreOptModuleHook);
156     setHook("1.promote", PostPromoteModuleHook);
157     setHook("2.internalize", PostInternalizeModuleHook);
158     setHook("3.import", PostImportModuleHook);
159     setHook("4.opt", PostOptModuleHook);
160     setHook("5.precodegen", PreCodeGenModuleHook);
161     CombinedIndexHook = SaveCombinedIndex;
162   } else {
163     if (SaveTempsArgs.contains("preopt"))
164       setHook("0.preopt", PreOptModuleHook);
165     if (SaveTempsArgs.contains("promote"))
166       setHook("1.promote", PostPromoteModuleHook);
167     if (SaveTempsArgs.contains("internalize"))
168       setHook("2.internalize", PostInternalizeModuleHook);
169     if (SaveTempsArgs.contains("import"))
170       setHook("3.import", PostImportModuleHook);
171     if (SaveTempsArgs.contains("opt"))
172       setHook("4.opt", PostOptModuleHook);
173     if (SaveTempsArgs.contains("precodegen"))
174       setHook("5.precodegen", PreCodeGenModuleHook);
175     if (SaveTempsArgs.contains("combinedindex"))
176       CombinedIndexHook = SaveCombinedIndex;
177   }
178 
179   return Error::success();
180 }
181 
182 #define HANDLE_EXTENSION(Ext)                                                  \
183   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
184 #include "llvm/Support/Extension.def"
185 #undef HANDLE_EXTENSION
186 
187 static void RegisterPassPlugins(ArrayRef<std::string> PassPlugins,
188                                 PassBuilder &PB) {
189 #define HANDLE_EXTENSION(Ext)                                                  \
190   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
191 #include "llvm/Support/Extension.def"
192 #undef HANDLE_EXTENSION
193 
194   // Load requested pass plugins and let them register pass builder callbacks
195   for (auto &PluginFN : PassPlugins) {
196     auto PassPlugin = PassPlugin::Load(PluginFN);
197     if (!PassPlugin)
198       report_fatal_error(PassPlugin.takeError(), /*gen_crash_diag=*/false);
199     PassPlugin->registerPassBuilderCallbacks(PB);
200   }
201 }
202 
203 static std::unique_ptr<TargetMachine>
204 createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
205   StringRef TheTriple = M.getTargetTriple();
206   SubtargetFeatures Features;
207   Features.getDefaultSubtargetFeatures(Triple(TheTriple));
208   for (const std::string &A : Conf.MAttrs)
209     Features.AddFeature(A);
210 
211   std::optional<Reloc::Model> RelocModel;
212   if (Conf.RelocModel)
213     RelocModel = *Conf.RelocModel;
214   else if (M.getModuleFlag("PIC Level"))
215     RelocModel =
216         M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
217 
218   std::optional<CodeModel::Model> CodeModel;
219   if (Conf.CodeModel)
220     CodeModel = *Conf.CodeModel;
221   else
222     CodeModel = M.getCodeModel();
223 
224   std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
225       TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
226       CodeModel, Conf.CGOptLevel));
227 
228   assert(TM && "Failed to create target machine");
229 
230   if (std::optional<uint64_t> LargeDataThreshold = M.getLargeDataThreshold())
231     TM->setLargeDataThreshold(*LargeDataThreshold);
232 
233   return TM;
234 }
235 
236 static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
237                            unsigned OptLevel, bool IsThinLTO,
238                            ModuleSummaryIndex *ExportSummary,
239                            const ModuleSummaryIndex *ImportSummary) {
240   auto FS = vfs::getRealFileSystem();
241   std::optional<PGOOptions> PGOOpt;
242   if (!Conf.SampleProfile.empty())
243     PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
244                         /*MemoryProfile=*/"", FS, PGOOptions::SampleUse,
245                         PGOOptions::NoCSAction,
246                         PGOOptions::ColdFuncOpt::Default, true);
247   else if (Conf.RunCSIRInstr) {
248     PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
249                         /*MemoryProfile=*/"", FS, PGOOptions::IRUse,
250                         PGOOptions::CSIRInstr, PGOOptions::ColdFuncOpt::Default,
251                         Conf.AddFSDiscriminator);
252   } else if (!Conf.CSIRProfile.empty()) {
253     PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
254                         /*MemoryProfile=*/"", FS, PGOOptions::IRUse,
255                         PGOOptions::CSIRUse, PGOOptions::ColdFuncOpt::Default,
256                         Conf.AddFSDiscriminator);
257     NoPGOWarnMismatch = !Conf.PGOWarnMismatch;
258   } else if (Conf.AddFSDiscriminator) {
259     PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
260                         PGOOptions::NoAction, PGOOptions::NoCSAction,
261                         PGOOptions::ColdFuncOpt::Default, true);
262   }
263   TM->setPGOOption(PGOOpt);
264 
265   LoopAnalysisManager LAM;
266   FunctionAnalysisManager FAM;
267   CGSCCAnalysisManager CGAM;
268   ModuleAnalysisManager MAM;
269 
270   PassInstrumentationCallbacks PIC;
271   StandardInstrumentations SI(Mod.getContext(), Conf.DebugPassManager,
272                               Conf.VerifyEach);
273   SI.registerCallbacks(PIC, &MAM);
274   PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
275 
276   RegisterPassPlugins(Conf.PassPlugins, PB);
277 
278   std::unique_ptr<TargetLibraryInfoImpl> TLII(
279       new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
280   if (Conf.Freestanding)
281     TLII->disableAllFunctions();
282   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
283 
284   // Parse a custom AA pipeline if asked to.
285   if (!Conf.AAPipeline.empty()) {
286     AAManager AA;
287     if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {
288       report_fatal_error(Twine("unable to parse AA pipeline description '") +
289                          Conf.AAPipeline + "': " + toString(std::move(Err)));
290     }
291     // Register the AA manager first so that our version is the one used.
292     FAM.registerPass([&] { return std::move(AA); });
293   }
294 
295   // Register all the basic analyses with the managers.
296   PB.registerModuleAnalyses(MAM);
297   PB.registerCGSCCAnalyses(CGAM);
298   PB.registerFunctionAnalyses(FAM);
299   PB.registerLoopAnalyses(LAM);
300   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
301 
302   ModulePassManager MPM;
303 
304   if (!Conf.DisableVerify)
305     MPM.addPass(VerifierPass());
306 
307   OptimizationLevel OL;
308 
309   switch (OptLevel) {
310   default:
311     llvm_unreachable("Invalid optimization level");
312   case 0:
313     OL = OptimizationLevel::O0;
314     break;
315   case 1:
316     OL = OptimizationLevel::O1;
317     break;
318   case 2:
319     OL = OptimizationLevel::O2;
320     break;
321   case 3:
322     OL = OptimizationLevel::O3;
323     break;
324   }
325 
326   // Parse a custom pipeline if asked to.
327   if (!Conf.OptPipeline.empty()) {
328     if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {
329       report_fatal_error(Twine("unable to parse pass pipeline description '") +
330                          Conf.OptPipeline + "': " + toString(std::move(Err)));
331     }
332   } else if (IsThinLTO) {
333     MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
334   } else {
335     MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
336   }
337 
338   if (!Conf.DisableVerify)
339     MPM.addPass(VerifierPass());
340 
341   if (PrintPipelinePasses) {
342     std::string PipelineStr;
343     raw_string_ostream OS(PipelineStr);
344     MPM.printPipeline(OS, [&PIC](StringRef ClassName) {
345       auto PassName = PIC.getPassNameForClassName(ClassName);
346       return PassName.empty() ? ClassName : PassName;
347     });
348     outs() << "pipeline-passes: " << PipelineStr << '\n';
349   }
350 
351   MPM.run(Mod, MAM);
352 }
353 
354 static bool isEmptyModule(const Module &Mod) {
355   // Module is empty if it has no functions, no globals, no inline asm and no
356   // named metadata (aliases and ifuncs require functions or globals so we
357   // don't need to check those explicitly).
358   return Mod.empty() && Mod.global_empty() && Mod.named_metadata_empty() &&
359          Mod.getModuleInlineAsm().empty();
360 }
361 
362 bool lto::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   // No need to run any opt passes if the module is empty.
384   // In theory these passes should take almost no time for an empty
385   // module, however, this guards against doing any unnecessary summary-based
386   // analysis in the case of a ThinLTO build where this might be an empty
387   // regular LTO combined module, with a large combined index from ThinLTO.
388   if (!isEmptyModule(Mod)) {
389     // FIXME: Plumb the combined index into the new pass manager.
390     runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
391                    ImportSummary);
392   }
393   return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
394 }
395 
396 static void codegen(const Config &Conf, TargetMachine *TM,
397                     AddStreamFn AddStream, 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(Twine("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(Twine("Failed to open ") + DwoFile + ": " +
427                          EC.message());
428   }
429 
430   Expected<std::unique_ptr<CachedFileStream>> StreamOrErr =
431       AddStream(Task, Mod.getModuleIdentifier());
432   if (Error Err = StreamOrErr.takeError())
433     report_fatal_error(std::move(Err));
434   std::unique_ptr<CachedFileStream> &Stream = *StreamOrErr;
435   TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
436 
437   legacy::PassManager CodeGenPasses;
438   TargetLibraryInfoImpl TLII(Triple(Mod.getTargetTriple()));
439   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
440   // No need to make index available if the module is empty.
441   // In theory these passes should not use the index for an empty
442   // module, however, this guards against doing any unnecessary summary-based
443   // analysis in the case of a ThinLTO build where this might be an empty
444   // regular LTO combined module, with a large combined index from ThinLTO.
445   if (!isEmptyModule(Mod))
446     CodeGenPasses.add(
447         createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex));
448   if (Conf.PreCodeGenPassesHook)
449     Conf.PreCodeGenPassesHook(CodeGenPasses);
450   if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
451                               DwoOut ? &DwoOut->os() : nullptr,
452                               Conf.CGFileType))
453     report_fatal_error("Failed to setup codegen");
454   CodeGenPasses.run(Mod);
455 
456   if (DwoOut)
457     DwoOut->keep();
458 }
459 
460 static void splitCodeGen(const Config &C, TargetMachine *TM,
461                          AddStreamFn AddStream,
462                          unsigned ParallelCodeGenParallelismLevel, Module &Mod,
463                          const ModuleSummaryIndex &CombinedIndex) {
464   DefaultThreadPool CodegenThreadPool(
465       heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
466   unsigned ThreadCount = 0;
467   const Target *T = &TM->getTarget();
468 
469   const auto HandleModulePartition =
470       [&](std::unique_ptr<Module> MPart) {
471         // We want to clone the module in a new context to multi-thread the
472         // codegen. We do it by serializing partition modules to bitcode
473         // (while still on the main thread, in order to avoid data races) and
474         // spinning up new threads which deserialize the partitions into
475         // separate contexts.
476         // FIXME: Provide a more direct way to do this in LLVM.
477         SmallString<0> BC;
478         raw_svector_ostream BCOS(BC);
479         WriteBitcodeToFile(*MPart, BCOS);
480 
481         // Enqueue the task
482         CodegenThreadPool.async(
483             [&](const SmallString<0> &BC, unsigned ThreadId) {
484               LTOLLVMContext Ctx(C);
485               Expected<std::unique_ptr<Module>> MOrErr =
486                   parseBitcodeFile(MemoryBufferRef(BC.str(), "ld-temp.o"), Ctx);
487               if (!MOrErr)
488                 report_fatal_error("Failed to read bitcode");
489               std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
490 
491               std::unique_ptr<TargetMachine> TM =
492                   createTargetMachine(C, T, *MPartInCtx);
493 
494               codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
495                       CombinedIndex);
496             },
497             // Pass BC using std::move to ensure that it get moved rather than
498             // copied into the thread's context.
499             std::move(BC), ThreadCount++);
500       };
501 
502   // Try target-specific module splitting first, then fallback to the default.
503   if (!TM->splitModule(Mod, ParallelCodeGenParallelismLevel,
504                        HandleModulePartition)) {
505     SplitModule(Mod, ParallelCodeGenParallelismLevel, HandleModulePartition,
506                 false);
507   }
508 
509   // Because the inner lambda (which runs in a worker thread) captures our local
510   // variables, we need to wait for the worker threads to terminate before we
511   // can leave the function scope.
512   CodegenThreadPool.wait();
513 }
514 
515 static Expected<const Target *> initAndLookupTarget(const Config &C,
516                                                     Module &Mod) {
517   if (!C.OverrideTriple.empty())
518     Mod.setTargetTriple(C.OverrideTriple);
519   else if (Mod.getTargetTriple().empty())
520     Mod.setTargetTriple(C.DefaultTriple);
521 
522   std::string Msg;
523   const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
524   if (!T)
525     return make_error<StringError>(Msg, inconvertibleErrorCode());
526   return T;
527 }
528 
529 Error lto::finalizeOptimizationRemarks(
530     std::unique_ptr<ToolOutputFile> DiagOutputFile) {
531   // Make sure we flush the diagnostic remarks file in case the linker doesn't
532   // call the global destructors before exiting.
533   if (!DiagOutputFile)
534     return Error::success();
535   DiagOutputFile->keep();
536   DiagOutputFile->os().flush();
537   return Error::success();
538 }
539 
540 Error lto::backend(const Config &C, AddStreamFn AddStream,
541                    unsigned ParallelCodeGenParallelismLevel, Module &Mod,
542                    ModuleSummaryIndex &CombinedIndex) {
543   Expected<const Target *> TOrErr = initAndLookupTarget(C, Mod);
544   if (!TOrErr)
545     return TOrErr.takeError();
546 
547   std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, Mod);
548 
549   LLVM_DEBUG(dbgs() << "Running regular LTO\n");
550   if (!C.CodeGenOnly) {
551     if (!opt(C, TM.get(), 0, Mod, /*IsThinLTO=*/false,
552              /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
553              /*CmdArgs*/ std::vector<uint8_t>()))
554       return Error::success();
555   }
556 
557   if (ParallelCodeGenParallelismLevel == 1) {
558     codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);
559   } else {
560     splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
561                  CombinedIndex);
562   }
563   return Error::success();
564 }
565 
566 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
567                             const ModuleSummaryIndex &Index) {
568   std::vector<GlobalValue*> DeadGVs;
569   for (auto &GV : Mod.global_values())
570     if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
571       if (!Index.isGlobalValueLive(GVS)) {
572         DeadGVs.push_back(&GV);
573         convertToDeclaration(GV);
574       }
575 
576   // Now that all dead bodies have been dropped, delete the actual objects
577   // themselves when possible.
578   for (GlobalValue *GV : DeadGVs) {
579     GV->removeDeadConstantUsers();
580     // Might reference something defined in native object (i.e. dropped a
581     // non-prevailing IR def, but we need to keep the declaration).
582     if (GV->use_empty())
583       GV->eraseFromParent();
584   }
585 }
586 
587 Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
588                        Module &Mod, const ModuleSummaryIndex &CombinedIndex,
589                        const FunctionImporter::ImportMapTy &ImportList,
590                        const GVSummaryMapTy &DefinedGlobals,
591                        MapVector<StringRef, BitcodeModule> *ModuleMap,
592                        bool CodeGenOnly, AddStreamFn IRAddStream,
593                        const std::vector<uint8_t> &CmdArgs) {
594   Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
595   if (!TOrErr)
596     return TOrErr.takeError();
597 
598   std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
599 
600   // Setup optimization remarks.
601   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
602       Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
603       Conf.RemarksFormat, Conf.RemarksWithHotness, Conf.RemarksHotnessThreshold,
604       Task);
605   if (!DiagFileOrErr)
606     return DiagFileOrErr.takeError();
607   auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
608 
609   // Set the partial sample profile ratio in the profile summary module flag of
610   // the module, if applicable.
611   Mod.setPartialSampleProfileRatio(CombinedIndex);
612 
613   LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
614   if (CodeGenOnly) {
615     // If CodeGenOnly is set, we only perform code generation and skip
616     // optimization. This value may differ from Conf.CodeGenOnly.
617     codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
618     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
619   }
620 
621   if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
622     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
623 
624   auto OptimizeAndCodegen =
625       [&](Module &Mod, TargetMachine *TM,
626           std::unique_ptr<ToolOutputFile> DiagnosticOutputFile) {
627         // Perform optimization and code generation for ThinLTO.
628         if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
629                  /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
630                  CmdArgs))
631           return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
632 
633         // Save the current module before the first codegen round.
634         // Note that the second codegen round runs only `codegen()` without
635         // running `opt()`. We're not reaching here as it's bailed out earlier
636         // with `CodeGenOnly` which has been set in `SecondRoundThinBackend`.
637         if (IRAddStream)
638           cgdata::saveModuleForTwoRounds(Mod, Task, IRAddStream);
639 
640         codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
641         return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
642       };
643 
644   if (ThinLTOAssumeMerged)
645     return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
646 
647   // When linking an ELF shared object, dso_local should be dropped. We
648   // conservatively do this for -fpic.
649   bool ClearDSOLocalOnDeclarations =
650       TM->getTargetTriple().isOSBinFormatELF() &&
651       TM->getRelocationModel() != Reloc::Static &&
652       Mod.getPIELevel() == PIELevel::Default;
653   renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
654 
655   dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
656 
657   thinLTOFinalizeInModule(Mod, DefinedGlobals, /*PropagateAttrs=*/true);
658 
659   if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
660     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
661 
662   if (!DefinedGlobals.empty())
663     thinLTOInternalizeModule(Mod, DefinedGlobals);
664 
665   if (Conf.PostInternalizeModuleHook &&
666       !Conf.PostInternalizeModuleHook(Task, Mod))
667     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
668 
669   auto ModuleLoader = [&](StringRef Identifier) {
670     assert(Mod.getContext().isODRUniquingDebugTypes() &&
671            "ODR Type uniquing should be enabled on the context");
672     if (ModuleMap) {
673       auto I = ModuleMap->find(Identifier);
674       assert(I != ModuleMap->end());
675       return I->second.getLazyModule(Mod.getContext(),
676                                      /*ShouldLazyLoadMetadata=*/true,
677                                      /*IsImporting*/ true);
678     }
679 
680     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
681         llvm::MemoryBuffer::getFile(Identifier);
682     if (!MBOrErr)
683       return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
684           Twine("Error loading imported file ") + Identifier + " : ",
685           MBOrErr.getError()));
686 
687     Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
688     if (!BMOrErr)
689       return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
690           Twine("Error loading imported file ") + Identifier + " : " +
691               toString(BMOrErr.takeError()),
692           inconvertibleErrorCode()));
693 
694     Expected<std::unique_ptr<Module>> MOrErr =
695         BMOrErr->getLazyModule(Mod.getContext(),
696                                /*ShouldLazyLoadMetadata=*/true,
697                                /*IsImporting*/ true);
698     if (MOrErr)
699       (*MOrErr)->setOwnedMemoryBuffer(std::move(*MBOrErr));
700     return MOrErr;
701   };
702 
703   FunctionImporter Importer(CombinedIndex, ModuleLoader,
704                             ClearDSOLocalOnDeclarations);
705   if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
706     return Err;
707 
708   // Do this after any importing so that imported code is updated.
709   updateMemProfAttributes(Mod, CombinedIndex);
710   updatePublicTypeTestCalls(Mod, CombinedIndex.withWholeProgramVisibility());
711 
712   if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
713     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
714 
715   return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
716 }
717 
718 BitcodeModule *lto::findThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
719   if (ThinLTOAssumeMerged && BMs.size() == 1)
720     return BMs.begin();
721 
722   for (BitcodeModule &BM : BMs) {
723     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
724     if (LTOInfo && LTOInfo->IsThinLTO)
725       return &BM;
726   }
727   return nullptr;
728 }
729 
730 Expected<BitcodeModule> lto::findThinLTOModule(MemoryBufferRef MBRef) {
731   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
732   if (!BMsOrErr)
733     return BMsOrErr.takeError();
734 
735   // The bitcode file may contain multiple modules, we want the one that is
736   // marked as being the ThinLTO module.
737   if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
738     return *Bm;
739 
740   return make_error<StringError>("Could not find module summary",
741                                  inconvertibleErrorCode());
742 }
743 
744 bool lto::initImportList(const Module &M,
745                          const ModuleSummaryIndex &CombinedIndex,
746                          FunctionImporter::ImportMapTy &ImportList) {
747   if (ThinLTOAssumeMerged)
748     return true;
749   // We can simply import the values mentioned in the combined index, since
750   // we should only invoke this using the individual indexes written out
751   // via a WriteIndexesThinBackend.
752   for (const auto &GlobalList : CombinedIndex) {
753     // Ignore entries for undefined references.
754     if (GlobalList.second.SummaryList.empty())
755       continue;
756 
757     auto GUID = GlobalList.first;
758     for (const auto &Summary : GlobalList.second.SummaryList) {
759       // Skip the summaries for the importing module. These are included to
760       // e.g. record required linkage changes.
761       if (Summary->modulePath() == M.getModuleIdentifier())
762         continue;
763       // Add an entry to provoke importing by thinBackend.
764       ImportList.addGUID(Summary->modulePath(), GUID, Summary->importType());
765     }
766   }
767   return true;
768 }
769