19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Analysis/GlobalsModRef.h"
22#include "llvm/Analysis/TargetLibraryInfo.h"
23#include "llvm/Analysis/TargetTransformInfo.h"
24#include "llvm/Bitcode/BitcodeReader.h"
25#include "llvm/Bitcode/BitcodeWriter.h"
26#include "llvm/Bitcode/BitcodeWriterPass.h"
27#include "llvm/CodeGen/TargetSubtargetInfo.h"
28#include "llvm/Config/llvm-config.h"
29#include "llvm/Frontend/Driver/CodeGenOptions.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DebugInfo.h"
32#include "llvm/IR/LegacyPassManager.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/ModuleSummaryIndex.h"
35#include "llvm/IR/PassManager.h"
36#include "llvm/IR/Verifier.h"
37#include "llvm/IRPrinter/IRPrintingPasses.h"
38#include "llvm/LTO/LTOBackend.h"
39#include "llvm/MC/TargetRegistry.h"
40#include "llvm/Object/OffloadBinary.h"
41#include "llvm/Passes/PassBuilder.h"
42#include "llvm/Passes/PassPlugin.h"
43#include "llvm/Passes/StandardInstrumentations.h"
44#include "llvm/ProfileData/InstrProfCorrelator.h"
45#include "llvm/Support/BuryPointer.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Compiler.h"
48#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/PrettyStackTrace.h"
50#include "llvm/Support/Program.h"
51#include "llvm/Support/TimeProfiler.h"
52#include "llvm/Support/Timer.h"
53#include "llvm/Support/ToolOutputFile.h"
54#include "llvm/Support/VirtualFileSystem.h"
55#include "llvm/Support/raw_ostream.h"
56#include "llvm/Target/TargetMachine.h"
57#include "llvm/Target/TargetOptions.h"
58#include "llvm/TargetParser/SubtargetFeature.h"
59#include "llvm/TargetParser/Triple.h"
60#include "llvm/Transforms/HipStdPar/HipStdPar.h"
61#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
62#include "llvm/Transforms/IPO/LowerTypeTests.h"
63#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
64#include "llvm/Transforms/InstCombine/InstCombine.h"
65#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
66#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
67#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
68#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
69#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
70#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
71#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
72#include "llvm/Transforms/Instrumentation/KCFI.h"
73#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
74#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
75#include "llvm/Transforms/Instrumentation/MemProfUse.h"
76#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
77#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
78#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
79#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
80#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
81#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
82#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
83#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
84#include "llvm/Transforms/ObjCARC.h"
85#include "llvm/Transforms/Scalar/EarlyCSE.h"
86#include "llvm/Transforms/Scalar/GVN.h"
87#include "llvm/Transforms/Scalar/JumpThreading.h"
88#include "llvm/Transforms/Utils/Debugify.h"
89#include "llvm/Transforms/Utils/ModuleUtils.h"
96#define HANDLE_EXTENSION(Ext) \
97 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
98#include "llvm/Support/Extension.def"
103 "sanitizer-early-opt-ep", cl::Optional,
104 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
109 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
111 "Function attribute to apply to cold functions as determined by PGO"),
112 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
113 "Default (no attribute)"),
114 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
115 "Mark cold functions with optsize."),
116 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
117 "Mark cold functions with minsize."),
118 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
119 "Mark cold functions with optnone.")));
121LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
131 ? llvm::driver::getDefaultProfileGenName()
133 if (CodeGenOpts.ContinuousProfileSync)
140class EmitAssemblyHelper {
146 llvm::Module *TheModule;
149 std::unique_ptr<raw_pwrite_stream> OS;
153 TargetIRAnalysis getTargetIRAnalysis()
const {
155 return TM->getTargetIRAnalysis();
157 return TargetIRAnalysis();
168 void CreateTargetMachine(
bool MustCreateTM);
173 bool AddEmitPasses(legacy::PassManager &CodeGenPasses,
BackendAction Action,
174 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
176 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef
Path) {
178 auto F = std::make_unique<llvm::ToolOutputFile>(
Path, EC,
179 llvm::sys::fs::OF_None);
181 Diags.
Report(diag::err_fe_unable_to_open_output) <<
Path << EC.message();
187 void RunOptimizationPipeline(
188 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
189 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS,
BackendConsumer *BC);
191 std::unique_ptr<raw_pwrite_stream> &OS,
192 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
199 bool shouldEmitRegularLTOSummary()
const {
200 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
201 TargetTriple.getVendor() != llvm::Triple::Apple;
207 bool shouldEmitUnifiedLTOModueFlag()
const {
208 return CodeGenOpts.UnifiedLTO &&
209 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
216 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
217 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
219 TargetTriple(TheModule->getTargetTriple()) {}
221 ~EmitAssemblyHelper() {
222 if (CodeGenOpts.DisableFree)
223 BuryPointer(std::move(TM));
226 std::unique_ptr<TargetMachine> TM;
229 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
234static SanitizerCoverageOptions
236 SanitizerCoverageOptions Opts;
238 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
239 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
240 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
241 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
242 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
243 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
244 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
245 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
246 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
247 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
248 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
249 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
250 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
251 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
252 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
253 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
254 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
255 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
259static SanitizerBinaryMetadataOptions
261 SanitizerBinaryMetadataOptions Opts;
262 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
263 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
264 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
273 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
275 switch (
T.getObjectFormat()) {
280 return !CGOpts.DisableIntegratedAS;
282 llvm::report_fatal_error(
"ASan not implemented for GOFF");
284 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
286 case Triple::DXContainer:
288 case Triple::UnknownObjectFormat:
294static std::optional<llvm::CodeModel::Model>
296 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
297 .Case(
"tiny", llvm::CodeModel::Tiny)
298 .Case(
"small", llvm::CodeModel::Small)
299 .Case(
"kernel", llvm::CodeModel::Kernel)
300 .Case(
"medium", llvm::CodeModel::Medium)
301 .Case(
"large", llvm::CodeModel::Large)
302 .Cases(
"default",
"", ~1u)
304 assert(CodeModel != ~0u &&
"invalid code model!");
305 if (CodeModel == ~1u)
307 return static_cast<llvm::CodeModel::Model
>(CodeModel);
312 return CodeGenFileType::ObjectFile;
314 return CodeGenFileType::Null;
317 return CodeGenFileType::AssemblyFile;
327 StringRef MainFilename) {
329 return std::string{};
331 std::string FlatCmdLine;
332 raw_string_ostream OS(FlatCmdLine);
333 bool PrintedOneArg =
false;
334 if (!StringRef(Args[0]).
contains(
"-cc1")) {
335 llvm::sys::printArg(OS,
"-cc1",
true);
336 PrintedOneArg =
true;
338 for (
unsigned i = 0; i < Args.size(); i++) {
339 StringRef Arg = Args[i];
342 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
346 if (Arg.starts_with(
"-object-file-name") || Arg == MainFilename)
349 if (Arg.starts_with(
"-fmessage-length"))
353 llvm::sys::printArg(OS, Arg,
true);
354 PrintedOneArg =
true;
361 llvm::TargetOptions &Options) {
366 switch (LangOpts.getThreadModel()) {
367 case LangOptions::ThreadModelKind::POSIX:
368 Options.ThreadModel = llvm::ThreadModel::POSIX;
370 case LangOptions::ThreadModelKind::Single:
371 Options.ThreadModel = llvm::ThreadModel::Single;
376 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
378 "Invalid Floating Point ABI!");
379 Options.FloatABIType =
380 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
381 .Case(
"soft", llvm::FloatABI::Soft)
382 .Case(
"softfp", llvm::FloatABI::Soft)
383 .Case(
"hard", llvm::FloatABI::Hard)
384 .Default(llvm::FloatABI::Default);
387 switch (LangOpts.getDefaultFPContractMode()) {
388 case LangOptions::FPM_Off:
391 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
393 case LangOptions::FPM_On:
394 case LangOptions::FPM_FastHonorPragmas:
395 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
397 case LangOptions::FPM_Fast:
398 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
402 Options.BinutilsVersion =
403 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
404 Options.UseInitArray = CodeGenOpts.UseInitArray;
405 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
411 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
413 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
415 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
417 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
419 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
420 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
421 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
422 Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
423 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
424 (LangOpts.getDefaultFPContractMode() ==
425 LangOptions::FPModeKind::FPM_Fast ||
426 LangOpts.getDefaultFPContractMode() ==
427 LangOptions::FPModeKind::FPM_FastHonorPragmas);
429 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
431 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
432 .Case(
"all", llvm::BasicBlockSection::All)
433 .StartsWith(
"list=", llvm::BasicBlockSection::List)
434 .Case(
"none", llvm::BasicBlockSection::None)
435 .Default(llvm::BasicBlockSection::None);
437 if (Options.BBSections == llvm::BasicBlockSection::List) {
438 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
439 MemoryBuffer::getFile(CodeGenOpts.
BBSections.substr(5));
441 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
442 << MBOrErr.getError().message();
445 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
448 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
449 Options.FunctionSections = CodeGenOpts.FunctionSections;
450 Options.DataSections = CodeGenOpts.DataSections;
451 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
452 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
453 Options.UniqueBasicBlockSectionNames =
454 CodeGenOpts.UniqueBasicBlockSectionNames;
455 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
456 Options.TLSSize = CodeGenOpts.TLSSize;
457 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
458 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
459 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
460 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
462 Options.EmitAddrsig = CodeGenOpts.Addrsig;
463 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
464 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
465 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
466 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
467 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
468 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
470 Options.Hotpatch = CodeGenOpts.HotPatch;
471 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
472 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
474 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
475 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
476 Options.SwiftAsyncFramePointer =
477 SwiftAsyncFramePointerMode::DeploymentBased;
480 case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
481 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
484 case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
485 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
490 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
491 Options.MCOptions.EmitCompactUnwindNonCanonical =
492 CodeGenOpts.EmitCompactUnwindNonCanonical;
493 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
494 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
495 Options.MCOptions.MCUseDwarfDirectory =
496 CodeGenOpts.NoDwarfDirectoryAsm
497 ? llvm::MCTargetOptions::DisableDwarfDirectory
498 : llvm::MCTargetOptions::EnableDwarfDirectory;
499 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
500 Options.MCOptions.MCIncrementalLinkerCompatible =
501 CodeGenOpts.IncrementalLinkerCompatible;
502 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
503 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
504 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
505 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
506 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
507 Options.MCOptions.Crel = CodeGenOpts.Crel;
508 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
509 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
510 Options.MCOptions.CompressDebugSections =
511 CodeGenOpts.getCompressDebugSections();
512 if (CodeGenOpts.OutputAsmVariant != 3)
513 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
514 Options.MCOptions.ABIName = TargetOpts.
ABI;
515 for (
const auto &Entry : HSOpts.UserEntries)
516 if (!Entry.IsFramework &&
517 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
518 Entry.Group == frontend::IncludeDirGroup::Angled ||
519 Entry.Group == frontend::IncludeDirGroup::System))
520 Options.MCOptions.IASSearchPaths.push_back(
521 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
522 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
526 Options.MCOptions.PPCUseFullRegisterNames =
527 CodeGenOpts.PPCUseFullRegisterNames;
528 Options.MisExpect = CodeGenOpts.MisExpect;
533static std::optional<GCOVOptions>
544 Options.NoRedZone = CodeGenOpts.DisableRedZone;
547 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
551static std::optional<InstrProfOptions>
556 InstrProfOptions Options;
557 Options.NoRedZone = CodeGenOpts.DisableRedZone;
558 Options.InstrProfileOutput = CodeGenOpts.ContinuousProfileSync
561 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
567 BackendArgs.push_back(
"clang");
569 BackendArgs.push_back(
"-debug-pass");
570 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
573 BackendArgs.push_back(
"-limit-float-precision");
579 if (BackendArgs.size() == 1)
581 BackendArgs.push_back(
nullptr);
585 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
589void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
592 const llvm::Triple &Triple = TheModule->getTargetTriple();
593 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
596 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
600 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
601 std::string FeaturesStr =
604 std::optional<CodeGenOptLevel> OptLevelOrNone =
605 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
606 assert(OptLevelOrNone &&
"Invalid optimization level!");
607 CodeGenOptLevel OptLevel = *OptLevelOrNone;
609 llvm::TargetOptions Options;
612 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
613 Options, RM, CM, OptLevel));
618bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
620 raw_pwrite_stream &OS,
621 raw_pwrite_stream *DwoOS) {
623 std::unique_ptr<TargetLibraryInfoImpl> TLII(
624 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
625 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
631 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
632 !CodeGenOpts.VerifyModule)) {
633 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
641 switch (Opts.OptimizationLevel) {
643 llvm_unreachable(
"Invalid optimization level!");
646 return OptimizationLevel::O0;
649 return OptimizationLevel::O1;
652 switch (Opts.OptimizeSize) {
654 llvm_unreachable(
"Invalid optimization level for size!");
657 return OptimizationLevel::O2;
660 return OptimizationLevel::Os;
663 return OptimizationLevel::Oz;
667 return OptimizationLevel::O3;
674 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
675 TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
679 PB.registerOptimizerLastEPCallback(
680 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
681 if (Level == OptimizationLevel::O0 &&
683 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
688 PB.registerPeepholeEPCallback(
689 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
690 if (Level != OptimizationLevel::O0 &&
692 FPM.addPass(KCFIPass());
699 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
700 ThinOrFullLTOPhase) {
703 MPM.addPass(SanitizerCoveragePass(
709 MPM.addPass(SanitizerBinaryMetadataPass(
714 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
716 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
719 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
720 CodeGenOpts.SanitizeMemoryParamRetval);
721 MPM.addPass(MemorySanitizerPass(options));
722 if (Level != OptimizationLevel::O0) {
727 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
728 FunctionPassManager FPM;
729 FPM.addPass(EarlyCSEPass(
true ));
730 FPM.addPass(InstCombinePass());
731 FPM.addPass(JumpThreadingPass());
732 FPM.addPass(GVNPass());
733 FPM.addPass(InstCombinePass());
734 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
738 MSanPass(SanitizerKind::Memory,
false);
739 MSanPass(SanitizerKind::KernelMemory,
true);
741 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
742 MPM.addPass(ModuleThreadSanitizerPass());
743 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
747 MPM.addPass(TypeSanitizerPass());
749 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
750 MPM.addPass(NumericalStabilitySanitizerPass());
752 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
753 MPM.addPass(RealtimeSanitizerPass());
755 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
758 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
759 llvm::AsanDtorKind DestructorKind =
760 CodeGenOpts.getSanitizeAddressDtor();
761 AddressSanitizerOptions Opts;
762 Opts.CompileKernel = CompileKernel;
764 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
765 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
766 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
770 ASanPass(SanitizerKind::Address,
false);
771 ASanPass(SanitizerKind::KernelAddress,
true);
773 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
776 MPM.addPass(HWAddressSanitizerPass(
777 {CompileKernel, Recover,
778 CodeGenOpts.OptimizationLevel == 0}));
781 HWASanPass(SanitizerKind::HWAddress,
false);
782 HWASanPass(SanitizerKind::KernelHWAddress,
true);
784 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
789 PB.registerOptimizerEarlyEPCallback(
790 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
791 ThinOrFullLTOPhase Phase) {
792 ModulePassManager NewMPM;
793 SanitizersCallback(NewMPM, Level, Phase);
794 if (!NewMPM.isEmpty()) {
796 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
797 MPM.addPass(std::move(NewMPM));
802 PB.registerOptimizerLastEPCallback(SanitizersCallback);
808 uint64_t AllowRuntimeCheckSkipHotCutoff =
811 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
814 PB.registerOptimizerEarlyEPCallback(
815 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
816 ModulePassManager &MPM, OptimizationLevel Level,
817 ThinOrFullLTOPhase Phase) {
818 LowerAllowCheckPass::Options Opts;
820 if (ScaledCutoffs.has_value())
821 Opts.cutoffs = ScaledCutoffs.value();
822 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
824 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
829void EmitAssemblyHelper::RunOptimizationPipeline(
830 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
831 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS,
BackendConsumer *BC) {
832 std::optional<PGOOptions> PGOOpt;
838 PGOOptions::IRInstr, PGOOptions::NoCSAction,
841 CodeGenOpts.AtomicProfileUpdate);
845 : PGOOptions::NoCSAction;
850 CodeGenOpts.DebugInfoForProfiling);
857 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
861 PGOOptions::NoAction, PGOOptions::NoCSAction,
863 else if (CodeGenOpts.PseudoProbeForProfiling)
866 PGOOptions(
"",
"",
"",
"",
nullptr,
867 PGOOptions::NoAction, PGOOptions::NoCSAction,
869 else if (CodeGenOpts.DebugInfoForProfiling)
871 PGOOpt = PGOOptions(
"",
"",
"",
"",
nullptr,
872 PGOOptions::NoAction, PGOOptions::NoCSAction,
878 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
881 assert(PGOOpt->Action != PGOOptions::IRInstr &&
882 PGOOpt->Action != PGOOptions::SampleUse &&
883 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
886 PGOOpt->CSAction = PGOOptions::CSIRInstr;
889 "",
nullptr, PGOOptions::NoAction,
891 CodeGenOpts.DebugInfoForProfiling);
894 TM->setPGOOption(PGOOpt);
896 PipelineTuningOptions PTO;
897 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
898 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
901 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
902 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
903 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
904 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
907 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
908 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
910 LoopAnalysisManager LAM;
911 FunctionAnalysisManager FAM;
912 CGSCCAnalysisManager CGAM;
913 ModuleAnalysisManager MAM;
915 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
916 PassInstrumentationCallbacks PIC;
917 PrintPassOptions PrintPassOpts;
918 PrintPassOpts.Indent = DebugPassStructure;
919 PrintPassOpts.SkipAnalyses = DebugPassStructure;
920 StandardInstrumentations SI(
921 TheModule->getContext(),
922 (CodeGenOpts.DebugPassManager || DebugPassStructure),
923 CodeGenOpts.VerifyEach, PrintPassOpts);
924 SI.registerCallbacks(PIC, &MAM);
925 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
928 switch (CodeGenOpts.getAssignmentTrackingMode()) {
929 case CodeGenOptions::AssignmentTrackingOpts::Forced:
930 PB.registerPipelineStartEPCallback(
931 [&](ModulePassManager &MPM, OptimizationLevel Level) {
932 MPM.addPass(AssignmentTrackingPass());
935 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
938 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
939 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
940 PB.registerPipelineStartEPCallback(
941 [&](ModulePassManager &MPM, OptimizationLevel Level) {
943 if (Level != OptimizationLevel::O0)
944 MPM.addPass(AssignmentTrackingPass());
948 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
953 DebugifyEachInstrumentation Debugify;
954 DebugInfoPerPass DebugInfoBeforePass;
955 if (CodeGenOpts.EnableDIPreservationVerify) {
956 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
957 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
960 Debugify.setOrigDIVerifyBugsReportFilePath(
962 Debugify.registerCallbacks(PIC, MAM);
964#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
970 for (Function &F : *TheModule) {
971 if (!F.getSubprogram())
973 for (BasicBlock &BB : F)
974 for (Instruction &I : BB)
975 if (!I.getDebugLoc())
976 I.setDebugLoc(DebugLoc::getCompilerGenerated());
982 auto PassPlugin = PassPlugin::Load(PluginFN);
984 PassPlugin->registerPassBuilderCallbacks(PB);
986 Diags.
Report(diag::err_fe_unable_to_load_plugin)
987 << PluginFN <<
toString(PassPlugin.takeError());
992#define HANDLE_EXTENSION(Ext) \
993 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
994#include "llvm/Support/Extension.def"
998 std::unique_ptr<TargetLibraryInfoImpl> TLII(
999 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1000 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1003 PB.registerModuleAnalyses(MAM);
1004 PB.registerCGSCCAnalyses(CGAM);
1005 PB.registerFunctionAnalyses(FAM);
1006 PB.registerLoopAnalyses(LAM);
1007 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1009 ModulePassManager MPM;
1011 if (CodeGenOpts.VerifyModule)
1012 MPM.addPass(VerifierPass());
1014 if (!CodeGenOpts.DisableLLVMPasses) {
1019 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1020 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1022 if (LangOpts.ObjCAutoRefCount) {
1023 PB.registerPipelineStartEPCallback(
1024 [](ModulePassManager &MPM, OptimizationLevel Level) {
1025 if (Level != OptimizationLevel::O0)
1027 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1029 PB.registerScalarOptimizerLateEPCallback(
1030 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1031 if (Level != OptimizationLevel::O0)
1032 FPM.addPass(ObjCARCOptPass());
1042 if (IsThinLTOPostLink)
1043 PB.registerPipelineStartEPCallback(
1044 [](ModulePassManager &MPM, OptimizationLevel Level) {
1045 MPM.addPass(LowerTypeTestsPass(
1048 lowertypetests::DropTestKind::Assume));
1053 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1054 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1055 OptimizationLevel Level) {
1056 BoundsCheckingPass::Options Options;
1059 static_assert(SanitizerKind::SO_LocalBounds <=
1060 std::numeric_limits<
1061 decltype(Options.GuardKind)::value_type>::max(),
1062 "Update type of llvm.allow.ubsan.check to represent "
1063 "SanitizerKind::SO_LocalBounds.");
1064 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1071 CodeGenOpts.SanitizeMinimalRuntime),
1073 CodeGenOpts.SanitizeRecover.has(SanitizerKind::LocalBounds),
1076 FPM.addPass(BoundsCheckingPass(Options));
1081 if (!IsThinLTOPostLink) {
1086 if (std::optional<GCOVOptions> Options =
1088 PB.registerPipelineStartEPCallback(
1089 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1090 MPM.addPass(GCOVProfilerPass(*Options));
1092 if (std::optional<InstrProfOptions> Options =
1094 PB.registerPipelineStartEPCallback(
1095 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1096 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1102 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1103 OptimizationLevel Level,
1104 ThinOrFullLTOPhase) {
1105 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1106 MPM.addPass(ModuleMemProfilerPass());
1110 if (CodeGenOpts.FatLTO) {
1111 MPM.addPass(PB.buildFatLTODefaultPipeline(
1112 Level, PrepareForThinLTO,
1113 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1114 }
else if (PrepareForThinLTO) {
1115 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1116 }
else if (PrepareForLTO) {
1117 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1119 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1124 if (CodeGenOpts.LinkBitcodePostopt)
1127 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1128 LangOpts.HIPStdParInterposeAlloc)
1129 MPM.addPass(HipStdParAllocationInterpositionPass());
1137 MPM.addPass(VerifierPass());
1140 CodeGenOpts.FatLTO) {
1141 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1142 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1143 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1144 CodeGenOpts.EnableSplitLTOUnit);
1151 MPM.addPass(ThinLTOBitcodeWriterPass(
1152 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1154 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1160 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1161 if (EmitLTOSummary) {
1162 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1163 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1164 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1165 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1169 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1172 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1177 if (shouldEmitUnifiedLTOModueFlag())
1178 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1185 if (PrintPipelinePasses) {
1186 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1187 auto PassName = PIC.getPassNameForClassName(ClassName);
1188 return PassName.empty() ? ClassName : PassName;
1196 PrettyStackTraceString CrashInfo(
"Optimizer");
1197 llvm::TimeTraceScope TimeScope(
"Optimizer");
1203 MPM.run(*TheModule, MAM);
1209void EmitAssemblyHelper::RunCodegenPipeline(
1210 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1211 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1215 legacy::PassManager CodeGenPasses;
1223 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1229 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1230 DwoOS ? &DwoOS->os() :
nullptr))
1241 if (PrintPipelinePasses) {
1246 PrettyStackTraceString CrashInfo(
"Code generation");
1247 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1250 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1253 CodeGenPasses.run(*TheModule);
1260 std::unique_ptr<raw_pwrite_stream> OS,
1265 CreateTargetMachine(RequiresCodeGen);
1267 if (RequiresCodeGen && !TM)
1270 TheModule->setDataLayout(TM->createDataLayout());
1273 cl::PrintOptionValues();
1275 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1276 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1277 RunCodegenPipeline(Action, OS, DwoOS);
1287 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1288 std::string SampleProfile, std::string ProfileRemapping,
1293 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1294 ModuleToDefinedGVSummaries;
1295 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1302 FunctionImporter::ImportIDTable ImportIDs;
1303 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1304 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1307 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1308 return std::make_unique<CachedFileStream>(std::move(OS),
1309 CGOpts.ObjectFilenameForDebug);
1312 if (CGOpts.SaveTempsFilePrefix !=
"") {
1313 if (Error
E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1315 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1316 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1321 Conf.CPU = TOpts.CPU;
1323 Conf.MAttrs = TOpts.Features;
1324 Conf.RelocModel = CGOpts.RelocationModel;
1325 std::optional<CodeGenOptLevel> OptLevelOrNone =
1326 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1327 assert(OptLevelOrNone &&
"Invalid optimization level!");
1328 Conf.CGOptLevel = *OptLevelOrNone;
1329 Conf.OptLevel = CGOpts.OptimizationLevel;
1331 Conf.SampleProfile = std::move(SampleProfile);
1332 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1333 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1336 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1337 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1338 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1341 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1344 if (CGOpts.hasProfileCSIRInstr()) {
1345 Conf.RunCSIRInstr =
true;
1347 }
else if (CGOpts.hasProfileCSIRUse()) {
1348 Conf.RunCSIRInstr =
false;
1349 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1352 Conf.ProfileRemapping = std::move(ProfileRemapping);
1353 Conf.DebugPassManager = CGOpts.DebugPassManager;
1354 Conf.VerifyEach = CGOpts.VerifyEach;
1355 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1356 Conf.RemarksFilename = CGOpts.OptRecordFile;
1357 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1358 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1359 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1360 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1363 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1368 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1369 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1374 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1375 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1384 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1385 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1386 nullptr, Conf.CodeGenOnly,
1387 nullptr, CGOpts.CmdArgs)) {
1388 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1389 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1395 StringRef TDesc, llvm::Module *M,
1398 std::unique_ptr<raw_pwrite_stream> OS,
1400 llvm::TimeTraceScope TimeScope(
"Backend");
1403 std::unique_ptr<llvm::Module> EmptyModule;
1408 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1409 if (Error
E = llvm::getModuleSummaryIndexForFile(
1412 .moveInto(CombinedIndex)) {
1413 logAllUnhandledErrors(std::move(
E), errs(),
1414 "Error loading index file '" +
1422 if (CombinedIndex) {
1423 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1435 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1436 EmptyModule->setTargetTriple(M->getTargetTriple());
1437 M = EmptyModule.get();
1441 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1442 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1447 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1448 if (DLDesc != TDesc) {
1451 "expected target description '%1'");
1452 Diags.
Report(DiagID) << DLDesc << TDesc;
1460 llvm::MemoryBufferRef Buf) {
1463 llvm::embedBitcodeInModule(
1475 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1476 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1477 if (ObjectOrErr.getError()) {
1479 "could not open '%0' for embedding");
1480 Diags.
Report(DiagID) << OffloadObject;
1484 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1485 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 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 std::string getProfileGenName(const CodeGenOptions &CodeGenOpts)
static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts, PassBuilder &PB)
static SanitizerCoverageOptions getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts)
static OptimizationLevel mapToLevel(const CodeGenOptions &Opts)
static std::optional< InstrProfOptions > getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts)
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts)
static CodeGenFileType getCodeGenFileType(BackendAction Action)
static std::string flattenClangCommandLine(ArrayRef< std::string > Args, StringRef MainFilename)
Defines the Diagnostic-related interfaces.
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.
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 InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate, -fprofile-generate,...
std::string BinutilsVersion
bool hasDWARFExceptions() const
bool hasProfileIRUse() const
Check if IR level profile use is on.
char CoverageVersion[4]
The version string to put into coverage files.
std::string FloatABI
The ABI to use for passing floating point arguments.
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.
std::vector< std::string > PassPlugins
List of dynamic shared object files to be loaded as pass plugins.
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
std::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
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.
bool hasWasmExceptions() const
bool hasSjLjExceptions() const
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
bool hasSEHExceptions() const
std::string MemoryProfileUsePath
Name of the profile file to use as input for -fmemory-profile-use.
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.
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
TargetOptions & getTargetOpts()
HeaderSearchOptions & getHeaderSearchOpts()
LangOptions & getLangOpts()
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.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
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
Options for controlling the target.
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.
llvm::EABI EABIVersion
The EABI version to use.
Create and return a pass that links in Moduels from a provided BackendConsumer to a given primary Mod...
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
llvm::cl::opt< bool > ClSanitizeGuardChecks
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, StringRef TDesc, 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)
const FunctionProtoType * T
Diagnostic wrappers for TextAPI types for error reporting.
LLVM_ABI cl::opt< InstrProfCorrelator::ProfCorrelatorKind > ProfileCorrelate
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::Optional, cl::desc("Insert sanitizers on OptimizerEarlyEP."))
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.