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