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/RuntimeLibcallInfo.h"
21#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Bitcode/BitcodeReader.h"
23#include "llvm/Bitcode/BitcodeWriter.h"
24#include "llvm/CGData/CodeGenData.h"
25#include "llvm/IR/LLVMRemarkStreamer.h"
26#include "llvm/IR/LegacyPassManager.h"
27#include "llvm/IR/PassManager.h"
28#include "llvm/IR/Verifier.h"
29#include "llvm/LTO/LTO.h"
30#include "llvm/MC/TargetRegistry.h"
31#include "llvm/Object/ModuleSymbolTable.h"
32#include "llvm/Passes/PassBuilder.h"
33#include "llvm/Passes/StandardInstrumentations.h"
34#include "llvm/Plugins/PassPlugin.h"
35#include "llvm/Support/Error.h"
36#include "llvm/Support/FileSystem.h"
37#include "llvm/Support/MemoryBuffer.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/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/Utils/FunctionImportUtils.h"
47#include "llvm/Transforms/Utils/SplitModule.h"
48#include <optional>
49
50using namespace llvm;
51using namespace lto;
52
53#define DEBUG_TYPE "lto-backend"
54
55enum class LTOBitcodeEmbedding {
56 DoNotEmbed = 0,
57 EmbedOptimized = 1,
58 EmbedPostMergePreOptimized = 2
59};
60
61static cl::opt<LTOBitcodeEmbedding> EmbedBitcode(
62 "lto-embed-bitcode", cl::init(Val: 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
72static cl::opt<bool> ThinLTOAssumeMerged(
73 "thinlto-assume-merged", cl::init(Val: false),
74 cl::desc("Assume the input has already undergone ThinLTO function "
75 "importing and the other pre-optimization pipeline changes."));
76
77static cl::list<std::string>
78 SaveModulesList("filter-save-modules", cl::value_desc("module names"),
79 cl::desc("Only save bitcode for module whose name without "
80 "path matches this for -save-temps options"),
81 cl::CommaSeparated, cl::Hidden);
82
83namespace llvm {
84extern cl::opt<bool> NoPGOWarnMismatch;
85}
86
87[[noreturn]] static void reportOpenError(StringRef Path, Twine Msg) {
88 errs() << "failed to open " << Path << ": " << Msg << '\n';
89 errs().flush();
90 exit(status: 1);
91}
92
93Error Config::addSaveTemps(std::string OutputFileName, bool UseInputModulePath,
94 const DenseSet<StringRef> &SaveTempsArgs) {
95 ShouldDiscardValueNames = false;
96
97 std::error_code EC;
98 if (SaveTempsArgs.empty() || SaveTempsArgs.contains(V: "resolution")) {
99 ResolutionFile =
100 std::make_unique<raw_fd_ostream>(args: OutputFileName + "resolution.txt", args&: EC,
101 args: sys::fs::OpenFlags::OF_TextWithCRLF);
102 if (EC) {
103 ResolutionFile.reset();
104 return errorCodeToError(EC);
105 }
106 }
107
108 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
109 // Keep track of the hook provided by the linker, which also needs to run.
110 ModuleHookFn LinkerHook = Hook;
111 Hook = [=, SaveModNames = llvm::SmallVector<std::string, 1>(
112 SaveModulesList.begin(), SaveModulesList.end())](
113 unsigned Task, const Module &M) {
114 // If SaveModulesList is not empty, only do save-temps if the module's
115 // filename (without path) matches a name in the list.
116 if (!SaveModNames.empty() &&
117 !llvm::is_contained(
118 Range: SaveModNames,
119 Element: std::string(llvm::sys::path::filename(path: M.getName()))))
120 return false;
121
122 // If the linker's hook returned false, we need to pass that result
123 // through.
124 if (LinkerHook && !LinkerHook(Task, M))
125 return false;
126
127 std::string PathPrefix;
128 // If this is the combined module (not a ThinLTO backend compile) or the
129 // user hasn't requested using the input module's path, emit to a file
130 // named from the provided OutputFileName with the Task ID appended.
131 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
132 PathPrefix = OutputFileName;
133 if (Task != (unsigned)-1)
134 PathPrefix += utostr(X: Task) + ".";
135 } else
136 PathPrefix = M.getModuleIdentifier() + ".";
137 std::string Path = PathPrefix + PathSuffix + ".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, Msg: EC.message());
144 WriteBitcodeToFile(M, Out&: OS, /*ShouldPreserveUseListOrder=*/false);
145 return true;
146 };
147 };
148
149 auto SaveCombinedIndex =
150 [=](const ModuleSummaryIndex &Index,
151 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
152 std::string Path = OutputFileName + "index.bc";
153 std::error_code EC;
154 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
155 // Because -save-temps is a debugging feature, we report the error
156 // directly and exit.
157 if (EC)
158 reportOpenError(Path, Msg: EC.message());
159 writeIndexToFile(Index, Out&: OS);
160
161 Path = OutputFileName + "index.dot";
162 raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::OF_Text);
163 if (EC)
164 reportOpenError(Path, Msg: EC.message());
165 Index.exportToDot(OS&: OSDot, GUIDPreservedSymbols);
166 return true;
167 };
168
169 if (SaveTempsArgs.empty()) {
170 setHook("0.preopt", PreOptModuleHook);
171 setHook("1.promote", PostPromoteModuleHook);
172 setHook("2.internalize", PostInternalizeModuleHook);
173 setHook("3.import", PostImportModuleHook);
174 setHook("4.opt", PostOptModuleHook);
175 setHook("5.precodegen", PreCodeGenModuleHook);
176 CombinedIndexHook = SaveCombinedIndex;
177 } else {
178 if (SaveTempsArgs.contains(V: "preopt"))
179 setHook("0.preopt", PreOptModuleHook);
180 if (SaveTempsArgs.contains(V: "promote"))
181 setHook("1.promote", PostPromoteModuleHook);
182 if (SaveTempsArgs.contains(V: "internalize"))
183 setHook("2.internalize", PostInternalizeModuleHook);
184 if (SaveTempsArgs.contains(V: "import"))
185 setHook("3.import", PostImportModuleHook);
186 if (SaveTempsArgs.contains(V: "opt"))
187 setHook("4.opt", PostOptModuleHook);
188 if (SaveTempsArgs.contains(V: "precodegen"))
189 setHook("5.precodegen", PreCodeGenModuleHook);
190 if (SaveTempsArgs.contains(V: "combinedindex"))
191 CombinedIndexHook = SaveCombinedIndex;
192 }
193
194 return Error::success();
195}
196
197#define HANDLE_EXTENSION(Ext) \
198 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
199#include "llvm/Support/Extension.def"
200#undef HANDLE_EXTENSION
201
202static void RegisterPassPlugins(const Config &Conf, PassBuilder &PB) {
203#define HANDLE_EXTENSION(Ext) \
204 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
205#include "llvm/Support/Extension.def"
206#undef HANDLE_EXTENSION
207
208 // Load requested pass plugins and let them register pass builder callbacks
209 for (auto &PluginFN : Conf.PassPluginFilenames) {
210 auto PassPlugin = PassPlugin::load(Filename: PluginFN);
211 if (!PassPlugin)
212 reportFatalUsageError(Err: PassPlugin.takeError());
213 PassPlugin->registerPassBuilderCallbacks(PB);
214 }
215
216 // Register already loaded plugins
217 for (auto *LoadedPlugin : Conf.LoadedPassPlugins)
218 LoadedPlugin->registerPassBuilderCallbacks(PB);
219}
220
221static std::unique_ptr<TargetMachine>
222createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
223 const Triple &TheTriple = M.getTargetTriple();
224 SubtargetFeatures Features;
225 Features.getDefaultSubtargetFeatures(Triple: TheTriple);
226 for (const std::string &A : Conf.MAttrs)
227 Features.AddFeature(String: A);
228
229 std::optional<Reloc::Model> RelocModel;
230 if (Conf.RelocModel)
231 RelocModel = *Conf.RelocModel;
232 else if (M.getModuleFlag(Key: "PIC Level"))
233 RelocModel =
234 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
235
236 std::optional<CodeModel::Model> CodeModel;
237 if (Conf.CodeModel)
238 CodeModel = *Conf.CodeModel;
239 else
240 CodeModel = M.getCodeModel();
241
242 assert(!Conf.Options.MCOptions.LibraryOptions &&
243 "set Config::LibraryOptions instead");
244 TargetOptions TargetOpts = Conf.Options;
245 if (TargetOpts.MCOptions.ABIName.empty()) {
246 TargetOpts.MCOptions.ABIName = M.getTargetABIFromMD();
247 }
248 TargetOpts.MCOptions.LibraryOptions = &M.getContext().getLibraryOptions();
249
250 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
251 TT: TheTriple, CPU: Conf.CPU, Features: Features.getString(), Options: TargetOpts, RM: RelocModel,
252 CM: CodeModel, OL: Conf.CGOptLevel));
253
254 assert(TM && "Failed to create target machine");
255
256 if (std::optional<uint64_t> LargeDataThreshold = M.getLargeDataThreshold())
257 TM->setLargeDataThreshold(*LargeDataThreshold);
258
259 return TM;
260}
261
262static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
263 unsigned OptLevel, bool IsThinLTO,
264 ModuleSummaryIndex *ExportSummary,
265 const ModuleSummaryIndex *ImportSummary,
266 const DenseSet<StringRef> &BitcodeLibFuncs) {
267 std::optional<PGOOptions> PGOOpt;
268 if (!Conf.SampleProfile.empty())
269 PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
270 /*MemoryProfile=*/"", PGOOptions::SampleUse,
271 PGOOptions::NoCSAction,
272 PGOOptions::ColdFuncOpt::Default, true);
273 else if (Conf.RunCSIRInstr) {
274 PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
275 /*MemoryProfile=*/"", PGOOptions::IRUse,
276 PGOOptions::CSIRInstr, PGOOptions::ColdFuncOpt::Default,
277 Conf.AddFSDiscriminator);
278 } else if (!Conf.CSIRProfile.empty()) {
279 PGOOpt =
280 PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
281 /*MemoryProfile=*/"", PGOOptions::IRUse, PGOOptions::CSIRUse,
282 PGOOptions::ColdFuncOpt::Default, Conf.AddFSDiscriminator);
283 NoPGOWarnMismatch = !Conf.PGOWarnMismatch;
284 } else if (Conf.AddFSDiscriminator) {
285 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction,
286 PGOOptions::NoCSAction,
287 PGOOptions::ColdFuncOpt::Default, true);
288 }
289 TM->setPGOOption(PGOOpt);
290
291 LoopAnalysisManager LAM;
292 FunctionAnalysisManager FAM;
293 CGSCCAnalysisManager CGAM;
294 ModuleAnalysisManager MAM;
295
296 PassInstrumentationCallbacks PIC;
297 StandardInstrumentations SI(Mod.getContext(), Conf.DebugPassManager,
298 Conf.VerifyEach);
299 SI.registerCallbacks(PIC, MAM: &MAM);
300 PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
301
302 RegisterPassPlugins(Conf, PB);
303
304 std::unique_ptr<TargetLibraryInfoImpl> TLII(
305 new TargetLibraryInfoImpl(TM->getTargetTriple(), TM->Options.VecLib));
306 if (Conf.Freestanding)
307 TLII->disableAllFunctions();
308
309 // Determine whether or not its safe to emit calls to each libfunc. Libfuncs
310 // that might have been present in the current LTO unit, but are not, have
311 // lost their only opportunity to be defined, and calls must not be emitted to
312 // them.
313 // FIXME: BitcodeLibFuncs isn't yet set for distributed ThinLTO.
314 TargetLibraryInfo TLI(*TLII);
315 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs); I != E;
316 ++I) {
317 LibFunc F = static_cast<LibFunc>(I);
318 if (BitcodeLibFuncs.contains(V: TLI.getName(F)))
319 TLII->setUnavailable(F);
320 }
321
322 FAM.registerPass(PassBuilder: [&] { return TargetLibraryAnalysis(*TLII); });
323
324 // Parse a custom AA pipeline if asked to.
325 if (!Conf.AAPipeline.empty()) {
326 AAManager AA;
327 if (auto Err = PB.parseAAPipeline(AA, PipelineText: Conf.AAPipeline)) {
328 report_fatal_error(reason: Twine("unable to parse AA pipeline description '") +
329 Conf.AAPipeline + "': " + toString(E: std::move(Err)));
330 }
331 // Register the AA manager first so that our version is the one used.
332 FAM.registerPass(PassBuilder: [&] { return std::move(AA); });
333 }
334
335 // Register all the basic analyses with the managers.
336 PB.registerModuleAnalyses(MAM);
337 PB.registerCGSCCAnalyses(CGAM);
338 PB.registerFunctionAnalyses(FAM);
339 PB.registerLoopAnalyses(LAM);
340 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
341
342 if (Conf.PassBuilderCallback)
343 Conf.PassBuilderCallback(PB);
344
345 ModulePassManager MPM;
346
347 if (!Conf.DisableVerify)
348 MPM.addPass(Pass: VerifierPass());
349
350 OptimizationLevel OL;
351
352 switch (OptLevel) {
353 default:
354 llvm_unreachable("Invalid optimization level");
355 case 0:
356 OL = OptimizationLevel::O0;
357 break;
358 case 1:
359 OL = OptimizationLevel::O1;
360 break;
361 case 2:
362 OL = OptimizationLevel::O2;
363 break;
364 case 3:
365 OL = OptimizationLevel::O3;
366 break;
367 }
368
369 // Parse a custom pipeline if asked to.
370 if (!Conf.OptPipeline.empty()) {
371 if (auto Err = PB.parsePassPipeline(MPM, PipelineText: Conf.OptPipeline)) {
372 report_fatal_error(reason: Twine("unable to parse pass pipeline description '") +
373 Conf.OptPipeline + "': " + toString(E: std::move(Err)));
374 }
375 } else if (IsThinLTO) {
376 MPM.addPass(Pass: PB.buildThinLTODefaultPipeline(Level: OL, ImportSummary));
377 } else {
378 MPM.addPass(Pass: PB.buildLTODefaultPipeline(Level: OL, ExportSummary));
379 }
380
381 if (!Conf.DisableVerify)
382 MPM.addPass(Pass: VerifierPass());
383
384 if (PB.getPrintPipelinePasses()) {
385 std::string PipelineStr;
386 raw_string_ostream OS(PipelineStr);
387 MPM.printPipeline(OS, MapClassName2PassName: [&PIC](StringRef ClassName) {
388 auto PassName = PIC.getPassNameForClassName(ClassName);
389 return PassName.empty() ? ClassName : PassName;
390 });
391 outs() << "pipeline-passes: " << PipelineStr << '\n';
392 }
393
394 MPM.run(IR&: Mod, AM&: MAM);
395}
396
397static bool isEmptyModule(const Module &Mod) {
398 // Module is empty if it has no functions, no globals, no inline asm and no
399 // named metadata (aliases and ifuncs require functions or globals so we
400 // don't need to check those explicitly).
401 return Mod.empty() && Mod.global_empty() && Mod.named_metadata_empty() &&
402 Mod.getModuleInlineAsm().empty();
403}
404
405bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
406 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
407 const ModuleSummaryIndex *ImportSummary,
408 const std::vector<uint8_t> &CmdArgs,
409 ArrayRef<StringRef> BitcodeLibFuncs) {
410 llvm::TimeTraceScope timeScope("opt");
411 if (EmbedBitcode == LTOBitcodeEmbedding::EmbedPostMergePreOptimized) {
412 // FIXME: the motivation for capturing post-merge bitcode and command line
413 // is replicating the compilation environment from bitcode, without needing
414 // to understand the dependencies (the functions to be imported). This
415 // assumes a clang - based invocation, case in which we have the command
416 // line.
417 // It's not very clear how the above motivation would map in the
418 // linker-based case, so we currently don't plumb the command line args in
419 // that case.
420 if (CmdArgs.empty())
421 LLVM_DEBUG(
422 dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
423 "command line arguments are not available");
424 llvm::embedBitcodeInModule(M&: Mod, Buf: llvm::MemoryBufferRef(),
425 /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
426 /*Cmdline*/ CmdArgs);
427 }
428 // No need to run any opt passes if the module is empty.
429 // In theory these passes should take almost no time for an empty
430 // module, however, this guards against doing any unnecessary summary-based
431 // analysis in the case of a ThinLTO build where this might be an empty
432 // regular LTO combined module, with a large combined index from ThinLTO.
433 if (!isEmptyModule(Mod)) {
434 DenseSet<StringRef> BitcodeLibFuncsSet(BitcodeLibFuncs.begin(),
435 BitcodeLibFuncs.end());
436 // FIXME: Plumb the combined index into the new pass manager.
437 runNewPMPasses(Conf, Mod, TM, OptLevel: Conf.OptLevel, IsThinLTO, ExportSummary,
438 ImportSummary, BitcodeLibFuncs: BitcodeLibFuncsSet);
439 }
440 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
441}
442
443static void codegen(const Config &Conf, TargetMachine *TM,
444 AddStreamFn AddStream, unsigned Task, Module &Mod,
445 const ModuleSummaryIndex &CombinedIndex) {
446 llvm::TimeTraceScope timeScope("codegen");
447 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
448 return;
449
450 if (EmbedBitcode == LTOBitcodeEmbedding::EmbedOptimized)
451 llvm::embedBitcodeInModule(M&: Mod, Buf: llvm::MemoryBufferRef(),
452 /*EmbedBitcode*/ true,
453 /*EmbedCmdline*/ false,
454 /*CmdArgs*/ std::vector<uint8_t>());
455
456 std::unique_ptr<ToolOutputFile> DwoOut;
457 SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
458 if (!Conf.DwoDir.empty()) {
459 std::error_code EC;
460 if (auto EC = llvm::sys::fs::create_directories(path: Conf.DwoDir))
461 report_fatal_error(reason: Twine("Failed to create directory ") + Conf.DwoDir +
462 ": " + EC.message());
463
464 DwoFile = Conf.DwoDir;
465 sys::path::append(path&: DwoFile, a: std::to_string(val: Task) + ".dwo");
466 TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
467 } else
468 TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
469
470 if (!DwoFile.empty()) {
471 std::error_code EC;
472 DwoOut = std::make_unique<ToolOutputFile>(args&: DwoFile, args&: EC, args: sys::fs::OF_None);
473 if (EC)
474 report_fatal_error(reason: Twine("Failed to open ") + DwoFile + ": " +
475 EC.message());
476 }
477
478 Expected<std::unique_ptr<CachedFileStream>> StreamOrErr =
479 AddStream(Task, Mod.getModuleIdentifier());
480 if (Error Err = StreamOrErr.takeError())
481 report_fatal_error(Err: std::move(Err));
482 std::unique_ptr<CachedFileStream> &Stream = *StreamOrErr;
483 TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
484
485 // Create the codegen pipeline in its own scope so it gets deleted before
486 // Stream->commit() is called. The commit function of CacheStream deletes
487 // the raw stream, which is too early as streamers (e.g. MCAsmStreamer)
488 // keep the pointer and may use it until their destruction. See #138194.
489 {
490 legacy::PassManager CodeGenPasses;
491 TargetLibraryInfoImpl TLII(Mod.getTargetTriple(), TM->Options.VecLib);
492 CodeGenPasses.add(P: new TargetLibraryInfoWrapperPass(TLII));
493 CodeGenPasses.add(P: new RuntimeLibraryInfoWrapper(
494 TM->Options.MCOptions.ABIName, TM->Options.VecLib));
495
496 // No need to make index available if the module is empty.
497 // In theory these passes should not use the index for an empty
498 // module, however, this guards against doing any unnecessary summary-based
499 // analysis in the case of a ThinLTO build where this might be an empty
500 // regular LTO combined module, with a large combined index from ThinLTO.
501 if (!isEmptyModule(Mod))
502 CodeGenPasses.add(
503 P: createImmutableModuleSummaryIndexWrapperPass(Index: &CombinedIndex));
504 if (Conf.PreCodeGenPassesHook)
505 Conf.PreCodeGenPassesHook(CodeGenPasses);
506 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
507 DwoOut ? &DwoOut->os() : nullptr,
508 Conf.CGFileType))
509 report_fatal_error(reason: "Failed to setup codegen");
510 CodeGenPasses.run(M&: Mod);
511
512 if (DwoOut)
513 DwoOut->keep();
514 }
515
516 if (Error Err = Stream->commit())
517 report_fatal_error(Err: std::move(Err));
518}
519
520static void splitCodeGen(const Config &C, TargetMachine *TM,
521 AddStreamFn AddStream,
522 unsigned ParallelCodeGenParallelismLevel, Module &Mod,
523 const ModuleSummaryIndex &CombinedIndex) {
524 DefaultThreadPool CodegenThreadPool(
525 heavyweight_hardware_concurrency(ThreadCount: ParallelCodeGenParallelismLevel));
526 unsigned ThreadCount = 0;
527 const Target *T = &TM->getTarget();
528
529 const auto HandleModulePartition =
530 [&](std::unique_ptr<Module> MPart) {
531 // We want to clone the module in a new context to multi-thread the
532 // codegen. We do it by serializing partition modules to bitcode
533 // (while still on the main thread, in order to avoid data races) and
534 // spinning up new threads which deserialize the partitions into
535 // separate contexts.
536 // FIXME: Provide a more direct way to do this in LLVM.
537 SmallString<0> BC;
538 raw_svector_ostream BCOS(BC);
539 WriteBitcodeToFile(M: *MPart, Out&: BCOS);
540
541 // Enqueue the task
542 CodegenThreadPool.async(
543 F: [&](const SmallString<0> &BC, unsigned ThreadId) {
544 LTOLLVMContext Ctx(C);
545 Expected<std::unique_ptr<Module>> MOrErr =
546 parseBitcodeFile(Buffer: MemoryBufferRef(BC.str(), "ld-temp.o"), Context&: Ctx);
547 if (!MOrErr)
548 report_fatal_error(reason: "Failed to read bitcode");
549 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
550
551 std::unique_ptr<TargetMachine> TM =
552 createTargetMachine(Conf: C, TheTarget: T, M&: *MPartInCtx);
553
554 codegen(Conf: C, TM: TM.get(), AddStream, Task: ThreadId, Mod&: *MPartInCtx,
555 CombinedIndex);
556 },
557 // Pass BC using std::move to ensure that it get moved rather than
558 // copied into the thread's context.
559 ArgList: std::move(BC), ArgList: ThreadCount++);
560 };
561
562 // Try target-specific module splitting first, then fallback to the default.
563 if (!TM->splitModule(M&: Mod, NumParts: ParallelCodeGenParallelismLevel,
564 ModuleCallback: HandleModulePartition)) {
565 SplitModule(M&: Mod, N: ParallelCodeGenParallelismLevel, ModuleCallback: HandleModulePartition,
566 PreserveLocals: false);
567 }
568
569 // Because the inner lambda (which runs in a worker thread) captures our local
570 // variables, we need to wait for the worker threads to terminate before we
571 // can leave the function scope.
572 CodegenThreadPool.wait();
573}
574
575static Expected<const Target *> initAndLookupTarget(const Config &C,
576 Module &Mod) {
577 if (!C.OverrideTriple.empty())
578 Mod.setTargetTriple(Triple(C.OverrideTriple));
579 else if (Mod.getTargetTriple().empty())
580 Mod.setTargetTriple(Triple(C.DefaultTriple));
581
582 std::string Msg;
583 const Target *T = TargetRegistry::lookupTarget(TheTriple: Mod.getTargetTriple(), Error&: Msg);
584 if (!T)
585 return make_error<StringError>(Args&: Msg, Args: inconvertibleErrorCode());
586 return T;
587}
588
589Error lto::finalizeOptimizationRemarks(LLVMRemarkFileHandle DiagOutputFile) {
590 // Make sure we flush the diagnostic remarks file in case the linker doesn't
591 // call the global destructors before exiting.
592 if (!DiagOutputFile)
593 return Error::success();
594 DiagOutputFile.finalize();
595 DiagOutputFile->keep();
596 DiagOutputFile->os().flush();
597 return Error::success();
598}
599
600Error lto::backend(const Config &C, AddStreamFn AddStream,
601 unsigned ParallelCodeGenParallelismLevel, Module &Mod,
602 ModuleSummaryIndex &CombinedIndex,
603 ArrayRef<StringRef> BitcodeLibFuncs) {
604 llvm::TimeTraceScope timeScope("LTO backend");
605 Expected<const Target *> TOrErr = initAndLookupTarget(C, Mod);
606 if (!TOrErr)
607 return TOrErr.takeError();
608
609 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf: C, TheTarget: *TOrErr, M&: Mod);
610
611 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
612 if (!C.CodeGenOnly) {
613 if (!opt(Conf: C, TM: TM.get(), Task: 0, Mod, /*IsThinLTO=*/false,
614 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
615 /*CmdArgs*/ std::vector<uint8_t>(), BitcodeLibFuncs))
616 return Error::success();
617 }
618
619 if (ParallelCodeGenParallelismLevel == 1) {
620 codegen(Conf: C, TM: TM.get(), AddStream, Task: 0, Mod, CombinedIndex);
621 } else {
622 splitCodeGen(C, TM: TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
623 CombinedIndex);
624 }
625 return Error::success();
626}
627
628static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
629 const ModuleSummaryIndex &Index) {
630 llvm::TimeTraceScope timeScope("Drop dead symbols");
631 std::vector<GlobalValue*> DeadGVs;
632
633 for (auto &GV : Mod.global_values()) {
634 auto GUID = GV.getGUIDIfAssigned();
635 if (!GUID)
636 continue;
637
638 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(Val: *GUID))
639 if (!Index.isGlobalValueLive(GVS)) {
640 DeadGVs.push_back(x: &GV);
641 convertToDeclaration(GV);
642 }
643 }
644
645 // Now that all dead bodies have been dropped, delete the actual objects
646 // themselves when possible.
647 for (GlobalValue *GV : DeadGVs) {
648 GV->removeDeadConstantUsers();
649 // Might reference something defined in native object (i.e. dropped a
650 // non-prevailing IR def, but we need to keep the declaration).
651 if (GV->use_empty())
652 GV->eraseFromParent();
653 }
654}
655
656Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
657 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
658 const FunctionImporter::ImportMapTy &ImportList,
659 const GVSummaryMapTy &DefinedGlobals,
660 MapVector<StringRef, BitcodeModule> *ModuleMap,
661 bool CodeGenOnly, ArrayRef<StringRef> BitcodeLibFuncs,
662 AddStreamFn IRAddStream,
663 const std::vector<uint8_t> &CmdArgs) {
664 llvm::TimeTraceScope timeScope("Thin backend", Mod.getModuleIdentifier());
665 Expected<const Target *> TOrErr = initAndLookupTarget(C: Conf, Mod);
666 if (!TOrErr)
667 return TOrErr.takeError();
668
669 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, TheTarget: *TOrErr, M&: Mod);
670
671 // Setup optimization remarks.
672 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
673 Context&: Mod.getContext(), RemarksFilename: Conf.RemarksFilename, RemarksPasses: Conf.RemarksPasses,
674 RemarksFormat: Conf.RemarksFormat, RemarksWithHotness: Conf.RemarksWithHotness, RemarksHotnessThreshold: Conf.RemarksHotnessThreshold,
675 Count: Task);
676 if (!DiagFileOrErr)
677 return DiagFileOrErr.takeError();
678 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
679
680 // Set the partial sample profile ratio in the profile summary module flag of
681 // the module, if applicable.
682 Mod.setPartialSampleProfileRatio(CombinedIndex);
683
684 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
685 if (CodeGenOnly) {
686 // If CodeGenOnly is set, we only perform code generation and skip
687 // optimization. This value may differ from Conf.CodeGenOnly.
688 codegen(Conf, TM: TM.get(), AddStream, Task, Mod, CombinedIndex);
689 return finalizeOptimizationRemarks(DiagOutputFile: std::move(DiagnosticOutputFile));
690 }
691
692 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
693 return finalizeOptimizationRemarks(DiagOutputFile: std::move(DiagnosticOutputFile));
694
695 auto OptimizeAndCodegen =
696 [&](Module &Mod, TargetMachine *TM,
697 LLVMRemarkFileHandle DiagnosticOutputFile) {
698 // Perform optimization and code generation for ThinLTO.
699 if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
700 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
701 CmdArgs, BitcodeLibFuncs))
702 return finalizeOptimizationRemarks(DiagOutputFile: std::move(DiagnosticOutputFile));
703
704 // Save the current module before the first codegen round.
705 // Note that the second codegen round runs only `codegen()` without
706 // running `opt()`. We're not reaching here as it's bailed out earlier
707 // with `CodeGenOnly` which has been set in `SecondRoundThinBackend`.
708 if (IRAddStream)
709 cgdata::saveModuleForTwoRounds(TheModule: Mod, Task, AddStream: IRAddStream);
710
711 codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
712 return finalizeOptimizationRemarks(DiagOutputFile: std::move(DiagnosticOutputFile));
713 };
714
715 if (ThinLTOAssumeMerged)
716 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
717
718 // When linking an ELF shared object, dso_local should be dropped. We
719 // conservatively do this for -fpic.
720 bool ClearDSOLocalOnDeclarations =
721 Mod.getTargetTriple().isOSBinFormatELF() &&
722 TM->getRelocationModel() != Reloc::Static &&
723 Mod.getPIELevel() == PIELevel::Default;
724 renameModuleForThinLTO(M&: Mod, Index: CombinedIndex, ClearDSOLocalOnDeclarations);
725
726 dropDeadSymbols(Mod, DefinedGlobals, Index: CombinedIndex);
727
728 thinLTOFinalizeInModule(TheModule&: Mod, DefinedGlobals, /*PropagateAttrs=*/true);
729
730 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
731 return finalizeOptimizationRemarks(DiagOutputFile: std::move(DiagnosticOutputFile));
732
733 if (!DefinedGlobals.empty())
734 thinLTOInternalizeModule(TheModule&: Mod, DefinedGlobals);
735
736 if (Conf.PostInternalizeModuleHook &&
737 !Conf.PostInternalizeModuleHook(Task, Mod))
738 return finalizeOptimizationRemarks(DiagOutputFile: std::move(DiagnosticOutputFile));
739
740 auto ModuleLoader = [&](StringRef Identifier) {
741 llvm::TimeTraceScope moduleLoaderScope("Module loader", Identifier);
742 assert(Mod.getContext().isODRUniquingDebugTypes() &&
743 "ODR Type uniquing should be enabled on the context");
744 if (ModuleMap) {
745 auto I = ModuleMap->find(Key: Identifier);
746 assert(I != ModuleMap->end());
747 return I->second.getLazyModule(Context&: Mod.getContext(),
748 /*ShouldLazyLoadMetadata=*/true,
749 /*IsImporting*/ true);
750 }
751
752 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
753 llvm::MemoryBuffer::getFile(Filename: Identifier);
754 if (!MBOrErr)
755 return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
756 Args: Twine("Error loading imported file ") + Identifier + " : ",
757 Args: MBOrErr.getError()));
758
759 Expected<BitcodeModule> BMOrErr = findThinLTOModule(MBRef: **MBOrErr);
760 if (!BMOrErr)
761 return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
762 Args: Twine("Error loading imported file ") + Identifier + " : " +
763 toString(E: BMOrErr.takeError()),
764 Args: inconvertibleErrorCode()));
765
766 Expected<std::unique_ptr<Module>> MOrErr =
767 BMOrErr->getLazyModule(Context&: Mod.getContext(),
768 /*ShouldLazyLoadMetadata=*/true,
769 /*IsImporting*/ true);
770 if (MOrErr)
771 (*MOrErr)->setOwnedMemoryBuffer(std::move(*MBOrErr));
772 return MOrErr;
773 };
774
775 {
776 llvm::TimeTraceScope importScope("Import functions");
777 FunctionImporter Importer(CombinedIndex, ModuleLoader,
778 ClearDSOLocalOnDeclarations);
779 if (Error Err = Importer.importFunctions(M&: Mod, ImportList).takeError())
780 return Err;
781 }
782
783 // Do this after any importing so that imported code is updated.
784 updatePublicTypeTestCalls(M&: Mod, WholeProgramVisibilityEnabledInLTO: CombinedIndex.withWholeProgramVisibility());
785
786 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
787 return finalizeOptimizationRemarks(DiagOutputFile: std::move(DiagnosticOutputFile));
788
789 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
790}
791
792BitcodeModule *lto::findThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
793 if (ThinLTOAssumeMerged && BMs.size() == 1)
794 return BMs.begin();
795
796 for (BitcodeModule &BM : BMs) {
797 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
798 if (LTOInfo && LTOInfo->IsThinLTO)
799 return &BM;
800 }
801 return nullptr;
802}
803
804Expected<BitcodeModule> lto::findThinLTOModule(MemoryBufferRef MBRef) {
805 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef);
806 if (!BMsOrErr)
807 return BMsOrErr.takeError();
808
809 // The bitcode file may contain multiple modules, we want the one that is
810 // marked as being the ThinLTO module.
811 if (const BitcodeModule *Bm = lto::findThinLTOModule(BMs: *BMsOrErr))
812 return *Bm;
813
814 return make_error<StringError>(Args: "Could not find module summary",
815 Args: inconvertibleErrorCode());
816}
817
818bool lto::initImportList(const Module &M,
819 const ModuleSummaryIndex &CombinedIndex,
820 FunctionImporter::ImportMapTy &ImportList) {
821 if (ThinLTOAssumeMerged)
822 return true;
823 // We can simply import the values mentioned in the combined index, since
824 // we should only invoke this using the individual indexes written out
825 // via a WriteIndexesThinBackend.
826 for (const auto &GlobalList : CombinedIndex) {
827 // Ignore entries for undefined references.
828 if (GlobalList.second.getSummaryList().empty())
829 continue;
830
831 auto GUID = GlobalList.first;
832 for (const auto &Summary : GlobalList.second.getSummaryList()) {
833 // Skip the summaries for the importing module. These are included to
834 // e.g. record required linkage changes.
835 if (Summary->modulePath() == M.getModuleIdentifier())
836 continue;
837 // Add an entry to provoke importing by thinBackend.
838 ImportList.addGUID(FromModule: Summary->modulePath(), GUID, ImportKind: Summary->importType());
839 }
840 }
841 return true;
842}
843