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