LLVM 24.0.0git
LTOBackend.cpp
Go to the documentation of this file.
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"
27#include "llvm/IR/PassManager.h"
28#include "llvm/IR/Verifier.h"
29#include "llvm/LTO/LTO.h"
35#include "llvm/Support/Error.h"
38#include "llvm/Support/Path.h"
48#include <optional>
49
50using namespace llvm;
51using namespace lto;
52
53#define DEBUG_TYPE "lto-backend"
54
60
62 "lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed),
64 "Do not embed"),
66 "Embed after all optimization passes"),
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
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
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"),
82
83namespace llvm {
85}
86
87[[noreturn]] static void reportOpenError(StringRef Path, Twine Msg) {
88 errs() << "failed to open " << Path << ": " << Msg << '\n';
89 errs().flush();
90 exit(1);
91}
92
93Error Config::addSaveTemps(std::string OutputFileName, bool UseInputModulePath,
94 const DenseSet<StringRef> &SaveTempsArgs) {
96
97 std::error_code EC;
98 if (SaveTempsArgs.empty() || SaveTempsArgs.contains("resolution")) {
100 std::make_unique<raw_fd_ostream>(OutputFileName + "resolution.txt", EC,
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() &&
118 SaveModNames,
119 std::string(llvm::sys::path::filename(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(Task) + ".";
135 } else
136 PathPrefix = M.getModuleIdentifier() + ".";
137 std::string Path = PathPrefix + PathSuffix + ".bc";
138 std::error_code EC;
140 // Because -save-temps is a debugging feature, we report the error
141 // directly and exit.
142 if (EC)
143 reportOpenError(Path, EC.message());
144 WriteBitcodeToFile(M, 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;
155 // Because -save-temps is a debugging feature, we report the error
156 // directly and exit.
157 if (EC)
158 reportOpenError(Path, EC.message());
159 writeIndexToFile(Index, OS);
160
161 Path = OutputFileName + "index.dot";
163 if (EC)
164 reportOpenError(Path, EC.message());
165 Index.exportToDot(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("preopt"))
179 setHook("0.preopt", PreOptModuleHook);
180 if (SaveTempsArgs.contains("promote"))
181 setHook("1.promote", PostPromoteModuleHook);
182 if (SaveTempsArgs.contains("internalize"))
183 setHook("2.internalize", PostInternalizeModuleHook);
184 if (SaveTempsArgs.contains("import"))
185 setHook("3.import", PostImportModuleHook);
186 if (SaveTempsArgs.contains("opt"))
187 setHook("4.opt", PostOptModuleHook);
188 if (SaveTempsArgs.contains("precodegen"))
189 setHook("5.precodegen", PreCodeGenModuleHook);
190 if (SaveTempsArgs.contains("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(PluginFN);
211 if (!PassPlugin)
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(TheTriple);
226 for (const std::string &A : Conf.MAttrs)
227 Features.AddFeature(A);
228
229 std::optional<Reloc::Model> RelocModel;
230 if (Conf.RelocModel)
231 RelocModel = *Conf.RelocModel;
232 else if (M.getModuleFlag("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 TargetOptions TargetOpts = Conf.Options;
243 if (TargetOpts.MCOptions.ABIName.empty()) {
244 TargetOpts.MCOptions.ABIName = M.getTargetABIFromMD();
245 }
246
247 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
248 TheTriple, Conf.CPU, Features.getString(), TargetOpts, RelocModel,
249 CodeModel, Conf.CGOptLevel));
250
251 assert(TM && "Failed to create target machine");
252
253 if (std::optional<uint64_t> LargeDataThreshold = M.getLargeDataThreshold())
254 TM->setLargeDataThreshold(*LargeDataThreshold);
255
256 return TM;
257}
258
259static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
260 unsigned OptLevel, bool IsThinLTO,
261 ModuleSummaryIndex *ExportSummary,
262 const ModuleSummaryIndex *ImportSummary,
263 const DenseSet<StringRef> &BitcodeLibFuncs) {
264 std::optional<PGOOptions> PGOOpt;
265 if (!Conf.SampleProfile.empty())
266 PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
267 /*MemoryProfile=*/"", PGOOptions::SampleUse,
270 else if (Conf.RunCSIRInstr) {
271 PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
272 /*MemoryProfile=*/"", PGOOptions::IRUse,
274 Conf.AddFSDiscriminator);
275 } else if (!Conf.CSIRProfile.empty()) {
276 PGOOpt =
278 /*MemoryProfile=*/"", PGOOptions::IRUse, PGOOptions::CSIRUse,
281 } else if (Conf.AddFSDiscriminator) {
282 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction,
285 }
286 TM->setPGOOption(PGOOpt);
287
292
295 Conf.VerifyEach);
296 SI.registerCallbacks(PIC, &MAM);
297 PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
298
299 RegisterPassPlugins(Conf, PB);
300
301 std::unique_ptr<TargetLibraryInfoImpl> TLII(
303 if (Conf.Freestanding)
304 TLII->disableAllFunctions();
305
306 // Determine whether or not its safe to emit calls to each libfunc. Libfuncs
307 // that might have been present in the current LTO unit, but are not, have
308 // lost their only opportunity to be defined, and calls must not be emitted to
309 // them.
310 // FIXME: BitcodeLibFuncs isn't yet set for distributed ThinLTO.
311 TargetLibraryInfo TLI(*TLII);
312 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs); I != E;
313 ++I) {
314 LibFunc F = static_cast<LibFunc>(I);
315 if (BitcodeLibFuncs.contains(TLI.getName(F)))
316 TLII->setUnavailable(F);
317 }
318
319 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
320
321 // Parse a custom AA pipeline if asked to.
322 if (!Conf.AAPipeline.empty()) {
324 if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {
325 report_fatal_error(Twine("unable to parse AA pipeline description '") +
326 Conf.AAPipeline + "': " + toString(std::move(Err)));
327 }
328 // Register the AA manager first so that our version is the one used.
329 FAM.registerPass([&] { return std::move(AA); });
330 }
331
332 // Register all the basic analyses with the managers.
333 PB.registerModuleAnalyses(MAM);
334 PB.registerCGSCCAnalyses(CGAM);
335 PB.registerFunctionAnalyses(FAM);
336 PB.registerLoopAnalyses(LAM);
337 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
338
339 if (Conf.PassBuilderCallback)
341
343
344 if (!Conf.DisableVerify)
345 MPM.addPass(VerifierPass());
346
348
349 switch (OptLevel) {
350 default:
351 llvm_unreachable("Invalid optimization level");
352 case 0:
354 break;
355 case 1:
357 break;
358 case 2:
360 break;
361 case 3:
363 break;
364 }
365
366 // Parse a custom pipeline if asked to.
367 if (!Conf.OptPipeline.empty()) {
368 if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {
369 report_fatal_error(Twine("unable to parse pass pipeline description '") +
370 Conf.OptPipeline + "': " + toString(std::move(Err)));
371 }
372 } else if (IsThinLTO) {
373 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
374 } else {
375 MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
376 }
377
378 if (!Conf.DisableVerify)
379 MPM.addPass(VerifierPass());
380
382 std::string PipelineStr;
383 raw_string_ostream OS(PipelineStr);
384 MPM.printPipeline(OS, [&PIC](StringRef ClassName) {
385 auto PassName = PIC.getPassNameForClassName(ClassName);
386 return PassName.empty() ? ClassName : PassName;
387 });
388 outs() << "pipeline-passes: " << PipelineStr << '\n';
389 }
390
391 MPM.run(Mod, MAM);
392}
393
394static bool isEmptyModule(const Module &Mod) {
395 // Module is empty if it has no functions, no globals, no inline asm and no
396 // named metadata (aliases and ifuncs require functions or globals so we
397 // don't need to check those explicitly).
398 return Mod.empty() && Mod.global_empty() && Mod.named_metadata_empty() &&
399 Mod.getModuleInlineAsm().empty();
400}
401
402bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
403 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
404 const ModuleSummaryIndex *ImportSummary,
405 const std::vector<uint8_t> &CmdArgs,
406 ArrayRef<StringRef> BitcodeLibFuncs) {
407 llvm::TimeTraceScope timeScope("opt");
409 // FIXME: the motivation for capturing post-merge bitcode and command line
410 // is replicating the compilation environment from bitcode, without needing
411 // to understand the dependencies (the functions to be imported). This
412 // assumes a clang - based invocation, case in which we have the command
413 // line.
414 // It's not very clear how the above motivation would map in the
415 // linker-based case, so we currently don't plumb the command line args in
416 // that case.
417 if (CmdArgs.empty())
419 dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
420 "command line arguments are not available");
422 /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
423 /*Cmdline*/ CmdArgs);
424 }
425 // No need to run any opt passes if the module is empty.
426 // In theory these passes should take almost no time for an empty
427 // module, however, this guards against doing any unnecessary summary-based
428 // analysis in the case of a ThinLTO build where this might be an empty
429 // regular LTO combined module, with a large combined index from ThinLTO.
430 if (!isEmptyModule(Mod)) {
431 DenseSet<StringRef> BitcodeLibFuncsSet(BitcodeLibFuncs.begin(),
432 BitcodeLibFuncs.end());
433 // FIXME: Plumb the combined index into the new pass manager.
434 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
435 ImportSummary, BitcodeLibFuncsSet);
436 }
437 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
438}
439
440static void codegen(const Config &Conf, TargetMachine *TM,
441 AddStreamFn AddStream, unsigned Task, Module &Mod,
442 const ModuleSummaryIndex &CombinedIndex) {
443 llvm::TimeTraceScope timeScope("codegen");
444 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
445 return;
446
449 /*EmbedBitcode*/ true,
450 /*EmbedCmdline*/ false,
451 /*CmdArgs*/ std::vector<uint8_t>());
452
453 std::unique_ptr<ToolOutputFile> DwoOut;
455 if (!Conf.DwoDir.empty()) {
456 std::error_code EC;
457 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
458 report_fatal_error(Twine("Failed to create directory ") + Conf.DwoDir +
459 ": " + EC.message());
460
461 DwoFile = Conf.DwoDir;
462 sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
463 TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
464 } else
466
467 if (!DwoFile.empty()) {
468 std::error_code EC;
469 DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
470 if (EC)
471 report_fatal_error(Twine("Failed to open ") + DwoFile + ": " +
472 EC.message());
473 }
474
476 AddStream(Task, Mod.getModuleIdentifier());
477 if (Error Err = StreamOrErr.takeError())
478 report_fatal_error(std::move(Err));
479 std::unique_ptr<CachedFileStream> &Stream = *StreamOrErr;
480 TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
481
482 // Create the codegen pipeline in its own scope so it gets deleted before
483 // Stream->commit() is called. The commit function of CacheStream deletes
484 // the raw stream, which is too early as streamers (e.g. MCAsmStreamer)
485 // keep the pointer and may use it until their destruction. See #138194.
486 {
487 legacy::PassManager CodeGenPasses;
488 TargetLibraryInfoImpl TLII(Mod.getTargetTriple(), TM->Options.VecLib);
489 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
490 CodeGenPasses.add(new RuntimeLibraryInfoWrapper(
492
493 // No need to make index available if the module is empty.
494 // In theory these passes should not use the index for an empty
495 // module, however, this guards against doing any unnecessary summary-based
496 // analysis in the case of a ThinLTO build where this might be an empty
497 // regular LTO combined module, with a large combined index from ThinLTO.
498 if (!isEmptyModule(Mod))
499 CodeGenPasses.add(
501 if (Conf.PreCodeGenPassesHook)
502 Conf.PreCodeGenPassesHook(CodeGenPasses);
503 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
504 DwoOut ? &DwoOut->os() : nullptr,
505 Conf.CGFileType))
506 report_fatal_error("Failed to setup codegen");
507 CodeGenPasses.run(Mod);
508
509 if (DwoOut)
510 DwoOut->keep();
511 }
512
513 if (Error Err = Stream->commit())
514 report_fatal_error(std::move(Err));
515}
516
517static void splitCodeGen(const Config &C, TargetMachine *TM,
518 AddStreamFn AddStream,
519 unsigned ParallelCodeGenParallelismLevel, Module &Mod,
520 const ModuleSummaryIndex &CombinedIndex) {
521 DefaultThreadPool CodegenThreadPool(
522 heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
523 unsigned ThreadCount = 0;
524 const Target *T = &TM->getTarget();
525
526 const auto HandleModulePartition =
527 [&](std::unique_ptr<Module> MPart) {
528 // We want to clone the module in a new context to multi-thread the
529 // codegen. We do it by serializing partition modules to bitcode
530 // (while still on the main thread, in order to avoid data races) and
531 // spinning up new threads which deserialize the partitions into
532 // separate contexts.
533 // FIXME: Provide a more direct way to do this in LLVM.
535 raw_svector_ostream BCOS(BC);
536 WriteBitcodeToFile(*MPart, BCOS);
537
538 // Enqueue the task
539 CodegenThreadPool.async(
540 [&](const SmallString<0> &BC, unsigned ThreadId) {
541 LTOLLVMContext Ctx(C);
543 parseBitcodeFile(MemoryBufferRef(BC.str(), "ld-temp.o"), Ctx);
544 if (!MOrErr)
545 report_fatal_error("Failed to read bitcode");
546 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
547
548 std::unique_ptr<TargetMachine> TM =
549 createTargetMachine(C, T, *MPartInCtx);
550
551 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
552 CombinedIndex);
553 },
554 // Pass BC using std::move to ensure that it get moved rather than
555 // copied into the thread's context.
556 std::move(BC), ThreadCount++);
557 };
558
559 // Try target-specific module splitting first, then fallback to the default.
560 if (!TM->splitModule(Mod, ParallelCodeGenParallelismLevel,
561 HandleModulePartition)) {
562 SplitModule(Mod, ParallelCodeGenParallelismLevel, HandleModulePartition,
563 false);
564 }
565
566 // Because the inner lambda (which runs in a worker thread) captures our local
567 // variables, we need to wait for the worker threads to terminate before we
568 // can leave the function scope.
569 CodegenThreadPool.wait();
570}
571
573 Module &Mod) {
574 if (!C.OverrideTriple.empty())
575 Mod.setTargetTriple(Triple(C.OverrideTriple));
576 else if (Mod.getTargetTriple().empty())
577 Mod.setTargetTriple(Triple(C.DefaultTriple));
578
579 std::string Msg;
580 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
581 if (!T)
583 return T;
584}
585
587 // Make sure we flush the diagnostic remarks file in case the linker doesn't
588 // call the global destructors before exiting.
589 if (!DiagOutputFile)
590 return Error::success();
591 DiagOutputFile.finalize();
592 DiagOutputFile->keep();
593 DiagOutputFile->os().flush();
594 return Error::success();
595}
596
598 unsigned ParallelCodeGenParallelismLevel, Module &Mod,
599 ModuleSummaryIndex &CombinedIndex,
600 ArrayRef<StringRef> BitcodeLibFuncs) {
601 llvm::TimeTraceScope timeScope("LTO backend");
603 if (!TOrErr)
604 return TOrErr.takeError();
605
606 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, Mod);
607
608 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
609 if (!C.CodeGenOnly) {
610 if (!opt(C, TM.get(), 0, Mod, /*IsThinLTO=*/false,
611 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
612 /*CmdArgs*/ std::vector<uint8_t>(), BitcodeLibFuncs))
613 return Error::success();
614 }
615
616 if (ParallelCodeGenParallelismLevel == 1) {
617 codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);
618 } else {
619 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
620 CombinedIndex);
621 }
622 return Error::success();
623}
624
625static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
626 const ModuleSummaryIndex &Index) {
627 llvm::TimeTraceScope timeScope("Drop dead symbols");
628 std::vector<GlobalValue*> DeadGVs;
629
630 for (auto &GV : Mod.global_values()) {
631 auto GUID = GV.getGUIDIfAssigned();
632 if (!GUID)
633 continue;
634
635 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(*GUID))
636 if (!Index.isGlobalValueLive(GVS)) {
637 DeadGVs.push_back(&GV);
639 }
640 }
641
642 // Now that all dead bodies have been dropped, delete the actual objects
643 // themselves when possible.
644 for (GlobalValue *GV : DeadGVs) {
645 GV->removeDeadConstantUsers();
646 // Might reference something defined in native object (i.e. dropped a
647 // non-prevailing IR def, but we need to keep the declaration).
648 if (GV->use_empty())
649 GV->eraseFromParent();
650 }
651}
652
653Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
654 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
655 const FunctionImporter::ImportMapTy &ImportList,
656 const GVSummaryMapTy &DefinedGlobals,
658 bool CodeGenOnly, ArrayRef<StringRef> BitcodeLibFuncs,
659 AddStreamFn IRAddStream,
660 const std::vector<uint8_t> &CmdArgs) {
661 llvm::TimeTraceScope timeScope("Thin backend", Mod.getModuleIdentifier());
663 if (!TOrErr)
664 return TOrErr.takeError();
665
666 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
667
668 // Setup optimization remarks.
669 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
670 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
672 Task);
673 if (!DiagFileOrErr)
674 return DiagFileOrErr.takeError();
675 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
676
677 // Set the partial sample profile ratio in the profile summary module flag of
678 // the module, if applicable.
679 Mod.setPartialSampleProfileRatio(CombinedIndex);
680
681 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
682 if (CodeGenOnly) {
683 // If CodeGenOnly is set, we only perform code generation and skip
684 // optimization. This value may differ from Conf.CodeGenOnly.
685 codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
686 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
687 }
688
689 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
690 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
691
692 auto OptimizeAndCodegen =
693 [&](Module &Mod, TargetMachine *TM,
694 LLVMRemarkFileHandle DiagnosticOutputFile) {
695 // Perform optimization and code generation for ThinLTO.
696 if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
697 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
698 CmdArgs, BitcodeLibFuncs))
699 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
700
701 // Save the current module before the first codegen round.
702 // Note that the second codegen round runs only `codegen()` without
703 // running `opt()`. We're not reaching here as it's bailed out earlier
704 // with `CodeGenOnly` which has been set in `SecondRoundThinBackend`.
705 if (IRAddStream)
706 cgdata::saveModuleForTwoRounds(Mod, Task, IRAddStream);
707
708 codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
709 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
710 };
711
713 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
714
715 // When linking an ELF shared object, dso_local should be dropped. We
716 // conservatively do this for -fpic.
717 bool ClearDSOLocalOnDeclarations =
718 TM->getTargetTriple().isOSBinFormatELF() &&
719 TM->getRelocationModel() != Reloc::Static &&
720 Mod.getPIELevel() == PIELevel::Default;
721 renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
722
723 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
724
725 thinLTOFinalizeInModule(Mod, DefinedGlobals, /*PropagateAttrs=*/true);
726
727 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
728 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
729
730 if (!DefinedGlobals.empty())
731 thinLTOInternalizeModule(Mod, DefinedGlobals);
732
733 if (Conf.PostInternalizeModuleHook &&
734 !Conf.PostInternalizeModuleHook(Task, Mod))
735 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
736
737 auto ModuleLoader = [&](StringRef Identifier) {
738 llvm::TimeTraceScope moduleLoaderScope("Module loader", Identifier);
739 assert(Mod.getContext().isODRUniquingDebugTypes() &&
740 "ODR Type uniquing should be enabled on the context");
741 if (ModuleMap) {
742 auto I = ModuleMap->find(Identifier);
743 assert(I != ModuleMap->end());
744 return I->second.getLazyModule(Mod.getContext(),
745 /*ShouldLazyLoadMetadata=*/true,
746 /*IsImporting*/ true);
747 }
748
750 llvm::MemoryBuffer::getFile(Identifier);
751 if (!MBOrErr)
753 Twine("Error loading imported file ") + Identifier + " : ",
754 MBOrErr.getError()));
755
756 Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
757 if (!BMOrErr)
759 Twine("Error loading imported file ") + Identifier + " : " +
760 toString(BMOrErr.takeError()),
762
764 BMOrErr->getLazyModule(Mod.getContext(),
765 /*ShouldLazyLoadMetadata=*/true,
766 /*IsImporting*/ true);
767 if (MOrErr)
768 (*MOrErr)->setOwnedMemoryBuffer(std::move(*MBOrErr));
769 return MOrErr;
770 };
771
772 {
773 llvm::TimeTraceScope importScope("Import functions");
774 FunctionImporter Importer(CombinedIndex, ModuleLoader,
775 ClearDSOLocalOnDeclarations);
776 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
777 return Err;
778 }
779
780 // Do this after any importing so that imported code is updated.
782
783 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
784 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
785
786 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
787}
788
790 if (ThinLTOAssumeMerged && BMs.size() == 1)
791 return BMs.begin();
792
793 for (BitcodeModule &BM : BMs) {
794 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
795 if (LTOInfo && LTOInfo->IsThinLTO)
796 return &BM;
797 }
798 return nullptr;
799}
800
803 if (!BMsOrErr)
804 return BMsOrErr.takeError();
805
806 // The bitcode file may contain multiple modules, we want the one that is
807 // marked as being the ThinLTO module.
808 if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
809 return *Bm;
810
811 return make_error<StringError>("Could not find module summary",
813}
814
816 const ModuleSummaryIndex &CombinedIndex,
817 FunctionImporter::ImportMapTy &ImportList) {
819 return true;
820 // We can simply import the values mentioned in the combined index, since
821 // we should only invoke this using the individual indexes written out
822 // via a WriteIndexesThinBackend.
823 for (const auto &GlobalList : CombinedIndex) {
824 // Ignore entries for undefined references.
825 if (GlobalList.second.getSummaryList().empty())
826 continue;
827
828 auto GUID = GlobalList.first;
829 for (const auto &Summary : GlobalList.second.getSummaryList()) {
830 // Skip the summaries for the importing module. These are included to
831 // e.g. record required linkage changes.
832 if (Summary->modulePath() == M.getModuleIdentifier())
833 continue;
834 // Add an entry to provoke importing by thinBackend.
835 ImportList.addGUID(Summary->modulePath(), GUID, Summary->importType());
836 }
837 }
838 return true;
839}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This header provides classes for managing passes over SCCs of the call graph.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This header defines various interfaces for pass management in LLVM.
static cl::opt< bool > ThinLTOAssumeMerged("thinlto-assume-merged", cl::init(false), cl::desc("Assume the input has already undergone ThinLTO function " "importing and the other pre-optimization pipeline changes."))
static void reportOpenError(StringRef Path, Twine Msg)
static cl::list< std::string > SaveModulesList("filter-save-modules", cl::value_desc("module names"), cl::desc("Only save bitcode for module whose name without " "path matches this for -save-temps options"), cl::CommaSeparated, cl::Hidden)
LTOBitcodeEmbedding
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
static void RegisterPassPlugins(const Config &Conf, PassBuilder &PB)
static void splitCodeGen(const Config &C, TargetMachine *TM, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &Mod, const ModuleSummaryIndex &CombinedIndex)
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)
static Expected< const Target * > initAndLookupTarget(const Config &C, Module &Mod)
static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM, unsigned OptLevel, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary, const DenseSet< StringRef > &BitcodeLibFuncs)
static bool isEmptyModule(const Module &Mod)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
This is the interface to build a ModuleSummaryIndex for a module.
static std::unique_ptr< TargetMachine > createTargetMachine(Function *F, CodeGenOptLevel OptLevel)
Create the TargetMachine object to query the backend for optimization preferences.
CGSCCAnalysisManager CGAM
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
const char * Msg
This header defines a class that provides bookkeeping for all standard (i.e in-tree) pass instrumenta...
#define LLVM_DEBUG(...)
Definition Debug.h:119
static cl::opt< int > ThreadCount("threads", cl::init(0))
Defines the virtual file system interface vfs::FileSystem.
static const char PassName[]
A manager for alias analyses.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
Represents a module in a bitcode file.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:285
bool empty() const
Definition DenseMap.h:206
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
The map maintains the list of imports.
void addGUID(StringRef FromModule, GlobalValue::GUID GUID, GlobalValueSummary::ImportKind ImportKind)
The function importer is automatically importing function from other modules based on the provided su...
LLVM_ABI Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
Function and variable summary information to aid decisions and implementation of importing.
RAII handle that manages the lifetime of the ToolOutputFile used to output remarks.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
iterator begin() const
Definition ArrayRef.h:338
This class provides access to building LLVM's passes.
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
A loaded pass plugin.
Definition PassPlugin.h:71
static LLVM_ABI Expected< PassPlugin > Load(const std::string &Filename)
Attempts to load a pass plugin from a given file.
void registerPassBuilderCallbacks(PassBuilder &PB) const
Invoke the PassBuilder callback registration.
Definition PassPlugin.h:93
void wait() override
Blocking wait for all the tasks to execute first.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class provides an interface to register all the standard pass instrumentations and manages their...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Manages the enabling and disabling of subtarget specific features.
LLVM_ABI void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
LLVM_ABI std::string getString() const
Returns features as a string.
LLVM_ABI void AddFeature(StringRef String, bool Enable=true)
Adds Features.
Analysis pass providing the TargetLibraryInfo.
Implementation of the target library information.
Provides information about what library functions are available for the current target.
StringRef getName(LibFunc F) const
Primary interface to the complete machine description for the target machine.
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfoWrapperPass *MMIWP=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
const Triple & getTargetTriple() const
virtual bool splitModule(Module &M, unsigned NumParts, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback)
Entry point for module splitting.
TargetOptions Options
const Target & getTarget() const
void setPGOOption(std::optional< PGOOptions > PGOOpt)
MCTargetOptions MCOptions
Machine level options.
VectorLibrary VecLib
Vector math library to use.
std::string ObjectFilenameForDebug
Stores the filename/path of the final .o/.obj file, to be written in the debug information.
Target - Wrapper for Target specific information.
TargetMachine * createTargetMachine(const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
auto async(Function &&F, Args &&...ArgList)
Asynchronous submission of a task to the pool.
Definition ThreadPool.h:80
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
void keep()
Indicate that the tool's job wrt this output file has been successful and the file should not be dele...
raw_fd_ostream & os()
Return the contained raw_fd_ostream.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
Create a verifier pass.
Definition Verifier.h:133
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
PassManager manages ModulePassManagers.
void add(Pass *P) override
Add a pass to the queue of passes to run.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
A raw_ostream that writes to a file descriptor.
A raw_ostream that writes to an std::string.
A raw_ostream that writes to an SmallVector or SmallString.
Interfaces for registering analysis passes, producing common pass manager configurations,...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
LLVM_ABI void saveModuleForTwoRounds(const Module &TheModule, unsigned Task, AddStreamFn AddStream)
Save TheModule before the first codegen round.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
LLVM_ABI bool opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary, const std::vector< uint8_t > &CmdArgs, ArrayRef< StringRef > BitcodeLibFuncs)
Runs middle-end LTO optimizations on Mod.
LLVM_ABI Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > *ModuleMap, bool CodeGenOnly, ArrayRef< StringRef > BitcodeLibFuncs, AddStreamFn IRAddStream=nullptr, const std::vector< uint8_t > &CmdArgs=std::vector< uint8_t >())
Runs a ThinLTO backend.
LLVM_ABI BitcodeModule * findThinLTOModule(MutableArrayRef< BitcodeModule > BMs)
Returns the BitcodeModule that is ThinLTO.
LLVM_ABI Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &M, ModuleSummaryIndex &CombinedIndex, ArrayRef< StringRef > BitcodeLibFuncs)
Runs a regular LTO backend.
LLVM_ABI Error finalizeOptimizationRemarks(LLVMRemarkFileHandle DiagOutputFile)
LLVM_ABI Expected< LLVMRemarkFileHandle > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, std::optional< uint64_t > RemarksHotnessThreshold=0, int Count=-1)
Setup optimization remarks.
Definition LTO.cpp:2346
LLVM_ABI bool initImportList(const Module &M, const ModuleSummaryIndex &CombinedIndex, FunctionImporter::ImportMapTy &ImportList)
Distributed ThinLTO: collect the referenced modules based on module summary and initialize ImportList...
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition FileSystem.h:777
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:786
LLVM_ABI std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition Path.cpp:993
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
This is an optimization pass for GlobalISel generic memory operations.
ThreadPoolStrategy heavyweight_hardware_concurrency(unsigned ThreadCount=0)
Returns a thread strategy for tasks requiring significant memory or other resources.
Definition Threading.h:167
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
LLVM_ABI cl::opt< std::optional< PrintPipelinePassesFormat >, false, PrintPipelinePassesFormatParser > PrintPipelinePasses
Common option used by multiple tools to print pipeline passes.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
LLVM_ABI bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
std::string utostr(uint64_t X, bool isNeg=false)
@ O1
Optimize quickly without destroying debuggability.
@ O0
Disable as many optimizations as possible.
@ O3
Optimize for fast execution as much as possible.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
LLVM_ABI void renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations, SetVector< GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
LLVM_ABI void SplitModule(Module &M, unsigned N, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback, bool PreserveLocals=false, bool RoundRobin=false)
Splits the module M into N linkable partitions.
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
cl::opt< bool > NoPGOWarnMismatch
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
SingleThreadExecutor DefaultThreadPool
Definition ThreadPool.h:262
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI ImmutablePass * createImmutableModuleSummaryIndexWrapperPass(const ModuleSummaryIndex *Index)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition Caching.h:62
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)
Based on the information recorded in the summaries during global summary-based analysis:
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
A struct capturing PGO tunables.
Definition PGOOptions.h:22
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
LTO configuration.
Definition Config.h:43
std::function< bool(unsigned Task, const Module &)> ModuleHookFn
The following callbacks deal with tasks, which normally represent the entire optimization and code ge...
Definition Config.h:237
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition Config.h:184
bool AddFSDiscriminator
Add FSAFDO discriminators.
Definition Config.h:202
std::optional< uint64_t > RemarksHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
Definition Config.h:178
LLVM_ABI Error addSaveTemps(std::string OutputFileName, bool UseInputModulePath=false, const DenseSet< StringRef > &SaveTempsArgs={})
This is a convenience function that configures this Config object to write temporary files named afte...
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module,...
Definition Config.h:241
CombinedIndexHookFn CombinedIndexHook
Definition Config.h:273
std::optional< CodeModel::Model > CodeModel
Definition Config.h:64
std::string AAPipeline
Definition Config.h:123
std::function< void(legacy::PassManager &)> PreCodeGenPassesHook
For adding passes that run right before codegen.
Definition Config.h:61
bool DisableVerify
Definition Config.h:69
std::vector< std::string > MAttrs
Definition Config.h:52
std::function< void(PassBuilder &)> PassBuilderCallback
Definition Config.h:62
CodeGenOptLevel CGOptLevel
Definition Config.h:65
PipelineTuningOptions PTO
Tunable parameters for passes in the default pipelines.
Definition Config.h:211
std::vector< llvm::PassPlugin * > LoadedPassPlugins
Definition Config.h:58
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
Definition Config.h:208
std::string CPU
Definition Config.h:50
std::string DwoDir
The directory to store .dwo files.
Definition Config.h:143
std::string RemarksFilename
Optimization remarks file path.
Definition Config.h:157
std::vector< std::string > PassPluginFilenames
Definition Config.h:59
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
Definition Config.h:245
std::string ProfileRemapping
Name remapping file for profile data.
Definition Config.h:140
TargetOptions Options
Definition Config.h:51
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
Definition Config.h:149
std::string SplitDwarfOutput
The path to write a .dwo file to.
Definition Config.h:154
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Definition Config.h:254
std::string RemarksPasses
Optimization remarks pass filter.
Definition Config.h:160
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
Definition Config.h:118
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
Definition Config.h:79
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
Definition Config.h:248
unsigned OptLevel
Definition Config.h:67
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Definition Config.h:251
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition Config.h:163
std::string CSIRProfile
Context Sensitive PGO profile path.
Definition Config.h:134
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition Config.h:259
std::optional< Reloc::Model > RelocModel
Definition Config.h:63
bool ShouldDiscardValueNames
Definition Config.h:198
bool PGOWarnMismatch
Turn on/off the warning about a hash mismatch in the PGO profile data.
Definition Config.h:82
CodeGenFileType CGFileType
Definition Config.h:66
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition Config.h:73
std::string SampleProfile
Sample PGO profile path.
Definition Config.h:137
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition Config.h:181
A derived class of LLVMContext that initializes itself according to a given Config object.
Definition Config.h:330