19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Analysis/GlobalsModRef.h"
22#include "llvm/Analysis/RuntimeLibcallInfo.h"
23#include "llvm/Analysis/TargetLibraryInfo.h"
24#include "llvm/Analysis/TargetTransformInfo.h"
25#include "llvm/BinaryFormat/ELF.h"
26#include "llvm/Bitcode/BitcodeReader.h"
27#include "llvm/Bitcode/BitcodeWriter.h"
28#include "llvm/Bitcode/BitcodeWriterPass.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
30#include "llvm/CodeGen/TargetSubtargetInfo.h"
31#include "llvm/Config/llvm-config.h"
32#include "llvm/Frontend/Driver/CodeGenOptions.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DebugInfo.h"
35#include "llvm/IR/LLVMRemarkStreamer.h"
36#include "llvm/IR/LegacyPassManager.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/ModuleSummaryIndex.h"
39#include "llvm/IR/PassManager.h"
40#include "llvm/IR/Verifier.h"
41#include "llvm/IRPrinter/IRPrintingPasses.h"
42#include "llvm/LTO/LTOBackend.h"
43#include "llvm/MC/MCTargetOptions.h"
44#include "llvm/MC/TargetRegistry.h"
45#include "llvm/Object/OffloadBinary.h"
46#include "llvm/Passes/PassBuilder.h"
47#include "llvm/Passes/RunCodeGen.h"
48#include "llvm/Passes/StandardInstrumentations.h"
49#include "llvm/Plugins/PassPlugin.h"
50#include "llvm/ProfileData/InstrProfCorrelator.h"
51#include "llvm/Support/BuryPointer.h"
52#include "llvm/Support/CodeGen.h"
53#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/IOSandbox.h"
56#include "llvm/Support/MemoryBuffer.h"
57#include "llvm/Support/PrettyStackTrace.h"
58#include "llvm/Support/Program.h"
59#include "llvm/Support/TimeProfiler.h"
60#include "llvm/Support/Timer.h"
61#include "llvm/Support/ToolOutputFile.h"
62#include "llvm/Support/VirtualFileSystem.h"
63#include "llvm/Support/raw_ostream.h"
64#include "llvm/Target/TargetMachine.h"
65#include "llvm/Target/TargetOptions.h"
66#include "llvm/TargetParser/SubtargetFeature.h"
67#include "llvm/TargetParser/Triple.h"
68#include "llvm/Transforms/HipStdPar/HipStdPar.h"
69#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
70#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
71#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
72#include "llvm/Transforms/IPO/FunctionAttrs.h"
73#include "llvm/Transforms/IPO/GlobalOpt.h"
74#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
75#include "llvm/Transforms/IPO/LowerTypeTests.h"
76#include "llvm/Transforms/IPO/SCCP.h"
77#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
78#include "llvm/Transforms/InstCombine/InstCombine.h"
79#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
80#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
81#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
82#include "llvm/Transforms/Instrumentation/ConcurrencySanitizer.h"
83#include "llvm/Transforms/Instrumentation/CopyProf.h"
84#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
85#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
86#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
87#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
88#include "llvm/Transforms/Instrumentation/KCFI.h"
89#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
90#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
91#include "llvm/Transforms/Instrumentation/MemProfUse.h"
92#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
93#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
94#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
95#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
96#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
97#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
98#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
99#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
100#include "llvm/Transforms/ObjCARC.h"
101#include "llvm/Transforms/Scalar/EarlyCSE.h"
102#include "llvm/Transforms/Scalar/GVN.h"
103#include "llvm/Transforms/Scalar/JumpThreading.h"
104#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
105#include "llvm/Transforms/Scalar/SROA.h"
106#include "llvm/Transforms/Scalar/SimplifyCFG.h"
107#include "llvm/Transforms/Utils/AssignGUID.h"
108#include "llvm/Transforms/Utils/Debugify.h"
109#include "llvm/Transforms/Utils/DynamicDebugging.h"
110#include "llvm/Transforms/Utils/Mem2Reg.h"
111#include "llvm/Transforms/Utils/ModuleUtils.h"
115using namespace clang;
118#define HANDLE_EXTENSION(Ext) \
119 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
120#include "llvm/Support/Extension.def"
125 "sanitizer-early-opt-ep",
126 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
131 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
133 "Function attribute to apply to cold functions as determined by PGO"),
134 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
135 "Default (no attribute)"),
136 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
137 "Mark cold functions with optsize."),
138 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
139 "Mark cold functions with minsize."),
140 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
141 "Mark cold functions with optnone.")));
153 ? llvm::driver::getDefaultProfileGenName(LibraryOptions)
155 if (CodeGenOpts.ContinuousProfileSync)
162class EmitAssemblyHelper {
163 CompilerInstance &CI;
164 DiagnosticsEngine &Diags;
165 const CodeGenOptions &CodeGenOpts;
166 const clang::TargetOptions &TargetOpts;
167 const LangOptions &LangOpts;
168 llvm::Module *TheModule;
169 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
171 std::unique_ptr<raw_pwrite_stream> OS;
175 TargetIRAnalysis getTargetIRAnalysis()
const {
177 return TM->getTargetIRAnalysis();
179 return TargetIRAnalysis();
190 void CreateTargetMachine(
bool MustCreateTM);
192 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
194 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
195 llvm::sys::fs::OF_None);
197 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
203 void RunOptimizationPipeline(
204 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
205 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
207 std::unique_ptr<raw_pwrite_stream> &OS,
208 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
209 void TimeCodegenPasses(llvm::function_ref<
void()> RunPasses);
216 bool shouldEmitRegularLTOSummary()
const {
217 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
218 TargetTriple.getVendor() != llvm::Triple::Apple;
224 bool shouldEmitUnifiedLTOModueFlag()
const {
225 return CodeGenOpts.UnifiedLTO &&
226 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
230 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
232 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
233 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
234 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
235 TheModule(M), VFS(std::move(VFS)),
236 TargetTriple(TheModule->getTargetTriple()) {}
238 ~EmitAssemblyHelper() {
239 if (CodeGenOpts.DisableFree)
240 BuryPointer(std::move(TM));
243 std::unique_ptr<TargetMachine> TM;
246 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
247 BackendConsumer *BC);
251static SanitizerCoverageOptions
253 SanitizerCoverageOptions Opts;
255 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
256 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
257 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
258 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
259 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
260 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
261 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
262 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
263 Opts.TracePCEntryExit = CGOpts.SanitizeCoverageTracePCEntryExit;
264 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
265 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
266 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
267 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
268 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
269 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
270 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
271 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
272 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
273 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
277static SanitizerBinaryMetadataOptions
279 SanitizerBinaryMetadataOptions Opts;
280 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
281 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
282 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
291 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
293 switch (
T.getObjectFormat()) {
298 return !CGOpts.DisableIntegratedAS;
300 llvm::report_fatal_error(
"ASan not implemented for GOFF");
302 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
304 case Triple::DXContainer:
306 case Triple::UnknownObjectFormat:
312static std::optional<llvm::CodeModel::Model>
314 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
315 .Case(
"tiny", llvm::CodeModel::Tiny)
316 .Case(
"small", llvm::CodeModel::Small)
317 .Case(
"kernel", llvm::CodeModel::Kernel)
318 .Case(
"medium", llvm::CodeModel::Medium)
319 .Case(
"large", llvm::CodeModel::Large)
320 .Cases({
"default",
""}, ~1u)
322 assert(CodeModel != ~0u &&
"invalid code model!");
323 if (CodeModel == ~1u)
325 return static_cast<llvm::CodeModel::Model
>(CodeModel);
330 return CodeGenFileType::ObjectFile;
332 return CodeGenFileType::Null;
335 return CodeGenFileType::AssemblyFile;
345 StringRef MainFilename,
348 return std::string{};
350 std::string FlatCmdLine;
351 raw_string_ostream OS(FlatCmdLine);
352 bool PrintedOneArg =
false;
353 if (!StringRef(Args[0]).
contains(
"-cc1")) {
354 llvm::sys::printArg(OS,
"-cc1",
true);
355 PrintedOneArg =
true;
357 for (
unsigned i = 0; i < Args.size(); i++) {
358 StringRef Arg = Args[i];
361 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
365 if (Arg.starts_with(
"-object-file-name"))
373 if (Arg == MainFilename || llvm::is_contained(InputFiles, Arg))
376 if (Arg.starts_with(
"-fmessage-length"))
380 llvm::sys::printArg(OS, Arg,
true);
381 PrintedOneArg =
true;
388 llvm::TargetOptions &Options) {
394 Options.MCOptions.BinutilsVersion =
395 llvm::MCTargetOptions::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
396 Options.UseInitArray = CodeGenOpts.UseInitArray;
397 Options.MCOptions.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
399 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
401 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
403 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
404 .Case(
"all", llvm::BasicBlockSection::All)
405 .StartsWith(
"list=", llvm::BasicBlockSection::List)
406 .Case(
"none", llvm::BasicBlockSection::None)
407 .Default(llvm::BasicBlockSection::None);
409 if (Options.BBSections == llvm::BasicBlockSection::List) {
410 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
414 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
415 << MBOrErr.getError().message();
418 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
421 if (CodeGenOpts.SplitMachineFunctions)
422 Options.FunctionSplitting = llvm::FunctionSplittingMode::All;
423 Options.EnableStaticDataPartitioning =
424 CodeGenOpts.PartitionStaticDataSections;
425 Options.FunctionSections = CodeGenOpts.FunctionSections;
426 Options.DataSections = CodeGenOpts.DataSections;
427 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
428 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
429 Options.UniqueBasicBlockSectionNames =
430 CodeGenOpts.UniqueBasicBlockSectionNames;
431 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
432 Options.TLSSize = CodeGenOpts.TLSSize;
433 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
434 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
435 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
437 Options.EmitAddrsig = CodeGenOpts.Addrsig;
438 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
439 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
440 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
441 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
442 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
443 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
446 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
447 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
449 convertDriverVectorLibraryToVectorLibrary(CodeGenOpts.getVecLib());
451 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
453 Options.SwiftAsyncFramePointer =
454 SwiftAsyncFramePointerMode::DeploymentBased;
458 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
462 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
467 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
468 Options.MCOptions.EmitCompactUnwindNonCanonical =
469 CodeGenOpts.EmitCompactUnwindNonCanonical;
470 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
471 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
472 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
473 Options.MCOptions.MCUseDwarfDirectory =
474 CodeGenOpts.NoDwarfDirectoryAsm
475 ? llvm::MCTargetOptions::DisableDwarfDirectory
476 : llvm::MCTargetOptions::EnableDwarfDirectory;
477 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
478 Options.MCOptions.MCIncrementalLinkerCompatible =
479 CodeGenOpts.IncrementalLinkerCompatible;
480 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
481 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
482 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
483 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
484 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
485 Options.MCOptions.Crel = CodeGenOpts.Crel;
486 Options.MCOptions.RelocSectionSym = CodeGenOpts.getRelocSectionSym();
487 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
488 Options.MCOptions.MachORelocatableDwarf = CodeGenOpts.MachORelocatableDwarf;
489 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
490 Options.MCOptions.CompressDebugSections =
491 CodeGenOpts.getCompressDebugSections();
492 if (CodeGenOpts.OutputAsmVariant != 3)
493 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
494 Options.MCOptions.ABIName = TargetOpts.
ABI;
495 for (
const auto &Entry : HSOpts.UserEntries)
496 if (!Entry.IsFramework &&
500 Options.MCOptions.IASSearchPaths.push_back(
501 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
502 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
509 InputFiles.push_back(Input.getFile());
513 Options.MCOptions.PPCUseFullRegisterNames =
514 CodeGenOpts.PPCUseFullRegisterNames;
515 Options.MisExpect = CodeGenOpts.MisExpect;
516 Options.VerifyArgABICompliance =
true;
521static std::optional<GCOVOptions>
533 Options.NoRedZone = CodeGenOpts.DisableRedZone;
536 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
540static std::optional<InstrProfOptions>
545 InstrProfOptions Options;
546 Options.NoRedZone = CodeGenOpts.DisableRedZone;
550 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
555 vfs::FileSystem &VFS) {
557 BackendArgs.push_back(
"clang");
559 BackendArgs.push_back(
"-debug-pass");
560 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
563 BackendArgs.push_back(
"-limit-float-precision");
570 if (BackendArgs.size() == 1)
572 BackendArgs.push_back(
nullptr);
576 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
581void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
584 const llvm::Triple &Triple = TheModule->getTargetTriple();
585 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
588 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
592 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
593 std::string FeaturesStr =
596 std::optional<CodeGenOptLevel> OptLevelOrNone =
597 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
598 assert(OptLevelOrNone &&
"Invalid optimization level!");
599 CodeGenOptLevel OptLevel = *OptLevelOrNone;
601 llvm::TargetOptions Options;
604 Options.MCOptions.LibraryOptions =
605 &TheModule->getContext().getLibraryOptions();
606 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
607 Options, RM, CM, OptLevel));
613 switch (Opts.OptimizationLevel) {
615 llvm_unreachable(
"Invalid optimization level!");
618 return OptimizationLevel::O0;
621 return OptimizationLevel::O1;
624 return OptimizationLevel::O2;
627 return OptimizationLevel::O3;
634 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
635 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
636 TargetTriple.isARM() || TargetTriple.isThumb() ||
637 TargetTriple.getArch() == llvm::Triple::hexagon)
641 PB.registerOptimizerLastEPCallback(
642 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
643 if (Level == OptimizationLevel::O0 &&
645 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
650 PB.registerPeepholeEPCallback(
651 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
652 if (Level != OptimizationLevel::O0 &&
654 FPM.addPass(KCFIPass());
661 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
662 ThinOrFullLTOPhase) {
666 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
672 MPM.addPass(SanitizerBinaryMetadataPass(
674 PB.getVirtualFileSystemPtr(),
678 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
680 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
683 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
684 CodeGenOpts.SanitizeMemoryParamRetval);
685 MPM.addPass(MemorySanitizerPass(
options));
686 if (Level != OptimizationLevel::O0) {
691 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
692 FunctionPassManager FPM;
693 FPM.addPass(EarlyCSEPass(
true ));
694 FPM.addPass(InstCombinePass());
695 FPM.addPass(JumpThreadingPass());
696 FPM.addPass(GVNPass());
697 FPM.addPass(InstCombinePass());
698 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
702 MSanPass(SanitizerKind::Memory,
false);
703 MSanPass(SanitizerKind::KernelMemory,
true);
705 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
706 MPM.addPass(ModuleThreadSanitizerPass());
707 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
710 if (LangOpts.
Sanitize.
has(SanitizerKind::Concurrency)) {
711 MPM.addPass(ModuleConcurrencySanitizerPass());
713 createModuleToFunctionPassAdaptor(ConcurrencySanitizerPass()));
717 MPM.addPass(TypeSanitizerPass());
719 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
720 MPM.addPass(NumericalStabilitySanitizerPass());
722 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
723 MPM.addPass(RealtimeSanitizerPass());
725 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
728 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
729 llvm::AsanDtorKind DestructorKind =
730 CodeGenOpts.getSanitizeAddressDtor();
731 AddressSanitizerOptions Opts;
732 Opts.CompileKernel = CompileKernel;
734 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
735 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
736 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
740 ASanPass(SanitizerKind::Address,
false);
741 ASanPass(SanitizerKind::KernelAddress,
true);
743 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
746 MPM.addPass(HWAddressSanitizerPass(
747 {CompileKernel, Recover,
748 CodeGenOpts.OptimizationLevel == 0}));
751 HWASanPass(SanitizerKind::HWAddress,
false);
752 HWASanPass(SanitizerKind::KernelHWAddress,
true);
754 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
756 PB.getVirtualFileSystemPtr()));
760 PB.registerOptimizerEarlyEPCallback(
761 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
762 ThinOrFullLTOPhase Phase) {
763 ModulePassManager NewMPM;
764 SanitizersCallback(NewMPM, Level, Phase);
765 if (!NewMPM.isEmpty()) {
767 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
768 MPM.addPass(std::move(NewMPM));
773 PB.registerOptimizerLastEPCallback(SanitizersCallback);
783 uint64_t AllowRuntimeCheckSkipHotCutoff =
788 SanitizerKind::Address | SanitizerKind::KernelAddress |
789 SanitizerKind::Thread | SanitizerKind::Memory |
790 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
791 SanitizerKind::KernelHWAddress);
794 if (LowerAllowCheckPass::isRequested(LibraryOptions) ||
795 ScaledCutoffs.has_value() ||
797 LowerAllowSanitize) {
799 PB.registerOptimizerEarlyEPCallback(
800 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
801 ModulePassManager &MPM, OptimizationLevel Level,
802 ThinOrFullLTOPhase Phase) {
803 LowerAllowCheckPass::Options Opts;
805 if (ScaledCutoffs.has_value())
806 Opts.cutoffs = ScaledCutoffs.value();
807 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
809 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
825 MPM.addPass(createModuleToFunctionPassAdaptor(LowerExpectIntrinsicPass()));
826 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
828 createModuleToFunctionPassAdaptor(SROAPass(SROAOptions::PreserveCFG)));
829 MPM.addPass(createModuleToFunctionPassAdaptor(EarlyCSEPass()));
834 MPM.addPass(ForceFunctionAttrsPass());
835 MPM.addPass(InferFunctionAttrsPass());
836 MPM.addPass(IPSCCPPass());
837 MPM.addPass(GlobalOptPass());
838 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
839 MPM.addPass(DeadArgumentEliminationPass());
840 MPM.addPass(createModuleToFunctionPassAdaptor(InstCombinePass()));
841 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
843 createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass()));
846void EmitAssemblyHelper::RunOptimizationPipeline(
847 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
848 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
849 const cl::LibraryOptionsContext &LibraryOptions =
850 TheModule->getContext().getLibraryOptions();
851 std::optional<PGOOptions> PGOOpt;
858 CodeGenOpts.DebugInfoForProfiling,
860 CodeGenOpts.AtomicProfileUpdate);
864 : PGOOptions::NoCSAction;
869 CodeGenOpts.DebugInfoForProfiling);
876 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
880 PGOOptions::NoAction, PGOOptions::NoCSAction,
882 else if (CodeGenOpts.PseudoProbeForProfiling)
884 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
886 CodeGenOpts.DebugInfoForProfiling,
true);
887 else if (CodeGenOpts.DebugInfoForProfiling)
889 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
895 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
898 assert(PGOOpt->Action != PGOOptions::IRInstr &&
899 PGOOpt->Action != PGOOptions::SampleUse &&
900 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
903 PGOOpt->CSAction = PGOOptions::CSIRInstr;
907 "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
911 TM->setPGOOption(PGOOpt);
913 PipelineTuningOptions PTO;
914 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
915 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
916 PTO.LoopFusion = CodeGenOpts.FuseLoops;
919 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
920 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
921 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
922 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
925 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
926 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
927 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
929 LoopAnalysisManager LAM;
930 FunctionAnalysisManager FAM;
931 CGSCCAnalysisManager CGAM;
932 ModuleAnalysisManager MAM;
934 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
935 PassInstrumentationCallbacks PIC;
936 PrintPassOptions PrintPassOpts;
937 PrintPassOpts.Indent = DebugPassStructure;
938 PrintPassOpts.SkipAnalyses = DebugPassStructure;
939 StandardInstrumentations SI(
940 TheModule->getContext(),
941 (CodeGenOpts.DebugPassManager || DebugPassStructure),
942 CodeGenOpts.VerifyEach, PrintPassOpts);
943 SI.registerCallbacks(PIC, &MAM);
944 PassBuilder PB(TheModule->getContext(), TM.get(), PTO, PGOOpt, &PIC,
948 switch (CodeGenOpts.getAssignmentTrackingMode()) {
949 case CodeGenOptions::AssignmentTrackingOpts::Forced:
950 PB.registerPipelineStartEPCallback(
951 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
952 MPM.addPass(AssignmentTrackingPass());
955 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
958 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
959 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
960 PB.registerPipelineStartEPCallback(
961 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
963 if (
Level != OptimizationLevel::O0)
964 MPM.addPass(AssignmentTrackingPass());
968 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
973 DebugifyEachInstrumentation Debugify;
974 DebugInfoPerPass DebugInfoBeforePass;
975 if (CodeGenOpts.EnableDIPreservationVerify) {
976 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
977 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
980 Debugify.setOrigDIVerifyBugsReportFilePath(
982 Debugify.registerCallbacks(PIC, MAM);
984#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
991 if (!F.getSubprogram())
993 for (BasicBlock &BB : F)
994 for (Instruction &I : BB)
995 if (!I.getDebugLoc())
996 I.setDebugLoc(DebugLoc::getCompilerGenerated());
1001 for (
const std::unique_ptr<PassPlugin> &Plugin : CI.
getPassPlugins())
1002 Plugin->registerPassBuilderCallbacks(PB);
1005#define HANDLE_EXTENSION(Ext) \
1006 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1007#include "llvm/Support/Extension.def"
1011 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1012 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1013 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1016 PB.registerModuleAnalyses(MAM);
1017 PB.registerCGSCCAnalyses(CGAM);
1018 PB.registerFunctionAnalyses(FAM);
1019 PB.registerLoopAnalyses(LAM);
1020 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1022 ModulePassManager MPM;
1024 if (CodeGenOpts.VerifyModule)
1025 MPM.addPass(VerifierPass());
1027 if (!CodeGenOpts.DisableLLVMPasses) {
1032 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1033 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1035 if (LangOpts.ObjCAutoRefCount) {
1036 PB.registerPipelineStartEPCallback(
1037 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1038 if (
Level != OptimizationLevel::O0)
1040 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1042 PB.registerScalarOptimizerLateEPCallback(
1043 [](FunctionPassManager &FPM, OptimizationLevel
Level) {
1044 if (
Level != OptimizationLevel::O0)
1045 FPM.addPass(ObjCARCOptPass());
1055 if (IsThinLTOPostLink)
1056 PB.registerPipelineStartEPCallback(
1057 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1058 MPM.addPass(DropTypeTestsPass());
1063 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1064 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1065 OptimizationLevel
Level) {
1066 BoundsCheckingPass::Options Options;
1069 static_assert(SanitizerKind::SO_LocalBounds <=
1070 std::numeric_limits<
1071 decltype(Options.GuardKind)::value_type>
::max(),
1072 "Update type of llvm.allow.ubsan.check to represent "
1073 "SanitizerKind::SO_LocalBounds.");
1074 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1081 CodeGenOpts.SanitizeMinimalRuntime),
1085 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1088 FPM.addPass(BoundsCheckingPass(Options));
1091 if (!IsThinLTOPostLink) {
1097 PB.registerPipelineStartEPCallback(
1098 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
1099 if (
Level == OptimizationLevel::O0 &&
1100 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
1106 MPM.addPass(InferFunctionAttrsPass());
1110 if (CodeGenOpts.CopyProf) {
1113 PB.registerPipelineEarlySimplificationEPCallback(
1114 [](ModulePassManager &MPM, OptimizationLevel, ThinOrFullLTOPhase) {
1115 MPM.addPass(createModuleToFunctionPassAdaptor(CopyProfPass()));
1116 MPM.addPass(ModuleCopyProfPass());
1120 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1122 ThinOrFullLTOPhase) {
1123 MPM.addPass(createModuleToFunctionPassAdaptor(CopyProfStoresPass()));
1128 if (std::optional<GCOVOptions> Options =
1130 PB.registerPipelineStartEPCallback(
1131 [
this, Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1135 if (std::optional<InstrProfOptions> Options =
1137 PB.registerPipelineStartEPCallback(
1138 [Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1139 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1145 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1146 OptimizationLevel
Level,
1147 ThinOrFullLTOPhase) {
1148 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1149 MPM.addPass(ModuleMemProfilerPass());
1153 if (CodeGenOpts.FatLTO) {
1154 MPM.addPass(PB.buildFatLTODefaultPipeline(
1155 Level, PrepareForThinLTO,
1156 PrepareForThinLTO || shouldEmitRegularLTOSummary(),
1157 CodeGenOpts.VerifyModule));
1158 }
else if (PrepareForThinLTO) {
1159 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(
Level));
1160 }
else if (PrepareForLTO) {
1161 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(
Level));
1163 MPM.addPass(PB.buildPerModuleDefaultPipeline(
Level));
1165 }
else if (
mapToLevel(CodeGenOpts) > OptimizationLevel::O0 &&
1166 CodeGenOpts.AMDGCNSPIRVSizeOptimization) {
1167 if (!TargetTriple.isSPIRV() ||
1168 (TargetTriple.getVendor() != llvm::Triple::VendorType::AMD)) {
1169 Diags.
Report(diag::err_opt_not_valid_on_target)
1170 <<
"fenable-spirv-size-optimization";
1177 if (CodeGenOpts.LinkBitcodePostopt) {
1178 MPM.addPass(LinkInModulesPass(BC));
1179 MPM.addPass(AssignGUIDPass());
1182 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1183 LangOpts.HIPStdParInterposeAlloc)
1184 MPM.addPass(HipStdParAllocationInterpositionPass());
1192 MPM.addPass(VerifierPass());
1195 CodeGenOpts.FatLTO) {
1196 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1197 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1198 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1199 CodeGenOpts.EnableSplitLTOUnit);
1206 MPM.addPass(ThinLTOBitcodeWriterPass(
1207 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1209 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1216 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1217 if (EmitLTOSummary) {
1218 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1219 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1220 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1221 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1225 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1228 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1234 if (shouldEmitUnifiedLTOModueFlag() &&
1235 !TheModule->getModuleFlag(
"UnifiedLTO"))
1236 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1243 if (PB.getPrintPipelinePasses()) {
1244 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1245 auto PassName = PIC.getPassNameForClassName(ClassName);
1246 return PassName.empty() ? ClassName : PassName;
1254 PrettyStackTraceString CrashInfo(
"Optimizer");
1255 llvm::TimeTraceScope TimeScope(
"Optimizer");
1261 MPM.run(*TheModule, MAM);
1267void EmitAssemblyHelper::RunCodegenPipeline(
1268 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1269 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1285 for (
const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.
getPassPlugins()) {
1286 if (Plugin->invokePreCodeGenCallback(
1287 *TM, *TheModule, *OS, DwoOS ? &DwoOS->os() :
nullptr, CGFT,
1288 !CodeGenOpts.VerifyModule,
false,
1293 TimeCodegenPasses([&]() {
1294 Error CodeGenError =
1295 runCodeGenPipeline(*TM, *TheModule, *OS, DwoOS ? &DwoOS->os() :
nullptr,
1296 CGFT, !CodeGenOpts.VerifyModule,
1300 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1304void EmitAssemblyHelper::TimeCodegenPasses(
1305 llvm::function_ref<
void()> RunPasses) {
1306 PrettyStackTraceString CrashInfo(
"Code generation");
1307 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1310 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1319 std::unique_ptr<raw_pwrite_stream> OS,
1320 BackendConsumer *BC) {
1324 CreateTargetMachine(RequiresCodeGen);
1326 if (RequiresCodeGen && !TM)
1328 if (TM && TheModule->getDataLayout().isDefault())
1329 TheModule->setDataLayout(TheModule->getTargetTriple().computeDataLayout(
1330 TM->getTargetABIName(*TheModule)));
1333 cl::PrintOptionValues();
1335 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1336 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1337 RunCodegenPipeline(Action, OS, DwoOS);
1347 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1348 std::string SampleProfile, std::string ProfileRemapping,
1353 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1354 ModuleToDefinedGVSummaries;
1355 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1362 FunctionImporter::ImportIDTable ImportIDs;
1363 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1364 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1367 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1368 return std::make_unique<CachedFileStream>(std::move(OS),
1369 CGOpts.ObjectFilenameForDebug);
1372 if (CGOpts.SaveTempsFilePrefix !=
"") {
1373 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1375 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1376 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1381 Conf.CPU = TOpts.CPU;
1383 Conf.MAttrs = TOpts.Features;
1384 Conf.RelocModel = CGOpts.RelocationModel;
1385 std::optional<CodeGenOptLevel> OptLevelOrNone =
1386 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1387 assert(OptLevelOrNone &&
"Invalid optimization level!");
1388 Conf.CGOptLevel = *OptLevelOrNone;
1389 Conf.OptLevel = CGOpts.OptimizationLevel;
1391 Conf.SampleProfile = std::move(SampleProfile);
1392 const cl::LibraryOptionsContext &LibraryOptions =
1393 M->getContext().getLibraryOptions();
1394 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1395 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1396 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1399 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1400 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1401 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1404 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1407 if (CGOpts.hasProfileCSIRInstr()) {
1408 Conf.RunCSIRInstr =
true;
1410 }
else if (CGOpts.hasProfileCSIRUse()) {
1411 Conf.RunCSIRInstr =
false;
1412 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1415 Conf.ProfileRemapping = std::move(ProfileRemapping);
1416 Conf.DebugPassManager = CGOpts.DebugPassManager;
1417 Conf.VerifyEach = CGOpts.VerifyEach;
1418 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1419 Conf.RemarksFilename = CGOpts.OptRecordFile;
1420 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1421 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1422 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1423 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1425 Conf.LoadedPassPlugins.push_back(Plugin.get());
1428 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1433 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1434 M->renumberMetadataForAssembly();
1435 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1440 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1441 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1454 finalizeLLVMOptimizationRemarks(M->getContext());
1455 if (
Error E = thinBackend(
1456 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1457 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1458 nullptr, Conf.CodeGenOnly, {},
1459 nullptr, CGOpts.CmdArgs)) {
1460 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1461 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1470 auto SaveModule = [&](StringRef Name, llvm::Module &M) {
1476 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
1480 errs() <<
"failed to open " << Path <<
": " << EC.message() <<
'\n';
1484 M.print(OS,
nullptr);
1488 std::string PromotionSuffix;
1495 for (
auto *CU : M->debug_compile_units()) {
1496 if (CU->getDirectory().size() > 0)
1497 Hash.update(CU->getDirectory());
1499 Hash.update(CU->getFilename());
1504 PromotionSuffix =
".dyndbg." + utohexstr(
Result.low());
1507 SaveModule(
"dyndbg.0.input", *M);
1509 auto UnoptM = prepareForDynamicDebugging(M, PromotionSuffix);
1510 SaveModule(
"dyndbg.1.inner", *UnoptM);
1512 if (!CGOpts.DiscardDynamicDebuggingDebugModule) {
1514 UnoptOpts.OptimizationLevel = 0;
1515 UnoptOpts.OptimizeSize = 0;
1516 EmitAssemblyHelper AsmHelper(CI, UnoptOpts, UnoptM.get(), VFS);
1520 std::unique_ptr<llvm::raw_pwrite_stream> UnoptOS =
1521 std::make_unique<llvm::raw_svector_ostream>(UnoptBuf);
1528 assert(!UnoptBuf.empty() &&
"Expected emitAssembly to fill UnoptBuf");
1531 StringRef SR(UnoptBuf.data(), UnoptBuf.size());
1532 std::unique_ptr<MemoryBuffer> Buf =
1533 MemoryBuffer::getMemBuffer(SR,
"",
false);
1535 GlobalVariable *EmbeddedGV =
1536 llvm::embedBufferInModule(*M, *Buf,
".debug_llvm_dyndbg", Align(8),
1539 auto &
C = M->getContext();
1540 auto getU32Metadata = [&
C](
unsigned Val) {
1541 return ConstantAsMetadata::get(ConstantInt::get(
C, APInt(32, Val)));
1543 EmbeddedGV->addMetadata(
1544 LLVMContext::MD_elf_section_properties,
1545 *MDTuple::get(
C, { getU32Metadata(ELF::SHT_LLVM_DYNDBG_ELF),
1546 getU32Metadata(0)}));
1548 SaveModule(
"dyndbg.2.outer", *M);
1556 for (
const std::unique_ptr<PassPlugin> &Plugin : CI.
getPassPlugins())
1557 Infos.push_back(Plugin->getInfo());
1558#define HANDLE_EXTENSION(Ext) Infos.push_back(get##Ext##PluginInfo());
1559#include "llvm/Support/Extension.def"
1560 if (
Error E = llvm::passPluginArguments(Infos, Args)) {
1571 std::unique_ptr<raw_pwrite_stream> OS,
1573 llvm::TimeTraceScope TimeScope(
"Backend");
1576 std::unique_ptr<llvm::Module> EmptyModule;
1579 auto BypassSandbox = sys::sandbox::scopedDisable();
1583 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1584 if (
Error E = llvm::getModuleSummaryIndexForFile(
1587 .moveInto(CombinedIndex)) {
1588 logAllUnhandledErrors(std::move(E), errs(),
1589 "Error loading index file '" +
1597 if (CombinedIndex) {
1598 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1610 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1611 EmptyModule->setTargetTriple(M->getTargetTriple());
1612 M = EmptyModule.get();
1616 bool EnableDynamicDebugging = CGOpts.DynamicDebugging;
1617 if (EnableDynamicDebugging) {
1621 const llvm::Target *TheTarget =
1622 TargetRegistry::lookupTarget(M->getTargetTriple(),
Error);
1623 if (!TheTarget && !CGOpts.DiscardDynamicDebuggingDebugModule) {
1624 Diags.
Report(diag::warn_dyndbg_unable_to_create_target) <<
Error;
1625 EnableDynamicDebugging =
false;
1632 if (CGOpts.getProfileInstr() != driver::ProfileInstrKind::ProfileNone) {
1633 Diags.
Report(diag::err_dyndbg_no_instrumentation);
1634 EnableDynamicDebugging =
false;
1637 if (EnableDynamicDebugging)
1640 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1641 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1647 std::string TDesc = M->getTargetTriple().computeDataLayout(
1648 AsmHelper.TM->getTargetABIName(*M));
1649 if (M->getDataLayout() != DataLayout(TDesc)) {
1650 Diags.
Report(diag::err_data_layout_mismatch)
1651 << M->getDataLayout().getStringRepresentation() << TDesc;
1659 llvm::MemoryBufferRef Buf) {
1662 llvm::embedBitcodeInModule(
1674 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1675 VFS.getBufferForFile(OffloadObject);
1676 if (ObjectOrErr.getError()) {
1677 Diags.
Report(diag::err_failed_to_open_for_embedding) << OffloadObject;
1681 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1682 Align(object::OffloadBinary::getAlignment()));
static bool actionRequiresCodeGen(BackendAction Action)
static void addSanitizers(const Triple &TargetTriple, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
static std::optional< llvm::CodeModel::Model > getCodeModel(const CodeGenOptions &CodeGenOpts)
static void runThinLTOBackend(CompilerInstance &CI, ModuleSummaryIndex *CombinedIndex, llvm::Module *M, std::unique_ptr< raw_pwrite_stream > OS, std::string SampleProfile, std::string ProfileRemapping, BackendAction Action)
static std::string getProfileGenName(const cl::LibraryOptionsContext &LibraryOptions, const CodeGenOptions &CodeGenOpts)
static void createAndEmbedModuleForDynamicDebugging(CompilerInstance &CI, CodeGenOptions &CGOpts, llvm::Module *M, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, BackendConsumer *BC)
static SanitizerBinaryMetadataOptions getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts)
static std::optional< GCOVOptions > getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool initTargetOptions(const CompilerInstance &CI, DiagnosticsEngine &Diags, llvm::TargetOptions &Options)
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts, vfs::FileSystem &VFS)
static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts, PassBuilder &PB)
static void addAMDGCNSPIRVSizeOptimizationPasses(ModulePassManager &MPM)
static SanitizerCoverageOptions getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts)
static OptimizationLevel mapToLevel(const CodeGenOptions &Opts)
void addLowerAllowCheckPass(const cl::LibraryOptionsContext &LibraryOptions, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
static std::string flattenClangCommandLine(ArrayRef< std::string > Args, StringRef MainFilename, ArrayRef< StringRef > InputFiles)
static std::optional< InstrProfOptions > getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts)
static CodeGenFileType getCodeGenFileType(BackendAction Action)
Defines the Diagnostic-related interfaces.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
This file provides a pass to link in Modules from a provided BackendConsumer.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static bool contains(const std::set< tok::TokenKind > &Terminators, const Token &Tok)
Defines the clang::TargetOptions class.
__DEVICE__ int max(int __a, int __b)
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
SanitizerSet SanitizeMergeHandlers
Set of sanitizer checks that can merge handlers (smaller code size at the expense of debuggability).
std::string StackUsageFile
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate, -fprofile-generate,...
std::string BinutilsVersion
bool hasProfileIRUse() const
Check if IR level profile use is on.
char CoverageVersion[4]
The version string to put into coverage files.
std::string ThinLinkBitcodeFile
Name of a file that can optionally be written with minimized bitcode to be used as input for the Thin...
bool hasProfileCSIRInstr() const
Check if CS IR level profile instrumentation is on.
std::string DebugPass
Enable additional debugging information.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
uint64_t LargeDataThreshold
The code model-specific large data threshold to use (-mlarge-data-threshold).
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
std::vector< std::function< void(llvm::PassBuilder &)> > PassBuilderCallbacks
List of pass builder callbacks.
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
std::string CodeModel
The code model to use (-mcmodel).
std::string CoverageDataFile
The filename with path we use for coverage data files.
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
std::vector< std::string > SanitizeCoverageAllowlistFiles
Path to allowlist file specifying which objects (files, functions) should exclusively be instrumented...
std::vector< std::string > SanitizeCoverageIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
bool hasSanitizeCoverage() const
std::string MainFileName
The user provided name for the "main file", if non-empty.
bool hasProfileIRInstr() const
Check if IR level profile instrumentation is on.
bool hasProfileCSIRUse() const
Check if CSIR profile use is on.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
std::vector< std::string > SanitizeMetadataIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
std::string ProfileExcludeFiles
Regexes separated by a semi-colon to filter the files to not instrument.
std::string AsSecureLogFile
The name of a file to use with .secure_log_unique directives.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
bool hasSanitizeBinaryMetadata() const
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
const char * Argv0
Executable and command-line used to create a given CompilerInvocation.
std::string remapDebugPathPrefix(StringRef Path) const
Remap specified path prefix using provided DebugPrefixMap map.
SanitizerMaskCutoffs SanitizeSkipHotCutoffs
Set of thresholds in a range [0.0, 1.0]: the top hottest code responsible for the given fraction of P...
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
std::optional< double > AllowRuntimeCheckSkipHotCutoff
std::vector< std::string > CommandLineArgs
std::string MemoryProfileUsePath
Name of the profile file to use as input for -fmemory-profile-use.
bool UseAbsolutePathsInNotesFile
Whether to force absolute paths in coverage notes files.
std::vector< std::string > PassPluginArgs
"<plugin>,<arg>" values of -fpass-plugin-arg=.
std::vector< std::string > OffloadObjects
List of filenames passed in using the -fembed-offload-object option.
std::string ProfileFilterFiles
Regexes separated by a semi-colon to filter the files to instrument.
std::string ObjectFilenameForDebug
Output filename used in the COFF debug information.
std::string SplitDwarfOutput
Output filename for the split debug info, not used in the skeleton CU.
std::string DIBugsReportFilePath
The file to use for dumping bug report by Debugify for original debug info.
std::string SaveDynDbgTempsFilePrefix
Prefix to use for -save-dynamic-debugging-temps output.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
llvm::TimerGroup & getTimerGroup() const
llvm::Timer & getFrontendTimer() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetOptions & getTargetOpts()
FrontendOptions & getFrontendOpts()
HeaderSearchOptions & getHeaderSearchOpts()
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
llvm::ArrayRef< std::unique_ptr< llvm::PassPlugin > > getPassPlugins() const
CodeGenOptions & getCodeGenOpts()
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
SanitizerSet Sanitize
Set of enabled sanitizers.
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
std::optional< std::vector< unsigned > > getAllScaled(unsigned ScalingFactor) const
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string ABI
If given, the name of the target ABI to use.
std::string CPU
If given, the name of the target CPU to generate code for.
@ Angled
Paths for '#include <>' added by '-I'.
@ System
Like Angled, but marks system directories.
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
Top level wrappers for InstallAPI frontend operations.
@ Default
Set to the current date and time.
const FunctionProtoType * T
llvm::cl::opt< bool > ClSanitizeGuardChecks
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
@ Backend_EmitAssembly
Emit native assembly files.
@ Backend_EmitLL
Emit human-readable LLVM assembly.
@ Backend_EmitBC
Emit LLVM bitcode files.
@ Backend_EmitObj
Emit native object files.
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
bool passPluginArguments(CompilerInstance &CI)
Passes the -fpass-plugin-arg= values to the loaded pass plugins and the statically linked extensions.
Diagnostic wrappers for TextAPI types for error reporting.
static cl::opt< PGOOptions::ColdFuncOpt > ClPGOColdFuncAttr("pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden, cl::desc("Function attribute to apply to cold functions as determined by PGO"), cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default", "Default (no attribute)"), clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize", "Mark cold functions with optsize."), clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize", "Mark cold functions with minsize."), clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone", "Mark cold functions with optnone.")))
static cl::opt< bool > ClSanitizeOnOptimizerEarlyEP("sanitizer-early-opt-ep", cl::desc("Insert sanitizers on OptimizerEarlyEP."))
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.