19#include "llvm/ADT/ScopeExit.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/StringSwitch.h"
22#include "llvm/Analysis/GlobalsModRef.h"
23#include "llvm/Analysis/TargetLibraryInfo.h"
24#include "llvm/Analysis/TargetTransformInfo.h"
25#include "llvm/Bitcode/BitcodeReader.h"
26#include "llvm/Bitcode/BitcodeWriter.h"
27#include "llvm/Bitcode/BitcodeWriterPass.h"
28#include "llvm/CodeGen/TargetSubtargetInfo.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/MemoryBuffer.h"
48#include "llvm/Support/PrettyStackTrace.h"
49#include "llvm/Support/Program.h"
50#include "llvm/Support/TimeProfiler.h"
51#include "llvm/Support/Timer.h"
52#include "llvm/Support/ToolOutputFile.h"
53#include "llvm/Support/VirtualFileSystem.h"
54#include "llvm/Support/raw_ostream.h"
55#include "llvm/Target/TargetMachine.h"
56#include "llvm/Target/TargetOptions.h"
57#include "llvm/TargetParser/SubtargetFeature.h"
58#include "llvm/TargetParser/Triple.h"
59#include "llvm/Transforms/HipStdPar/HipStdPar.h"
60#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
61#include "llvm/Transforms/IPO/LowerTypeTests.h"
62#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
63#include "llvm/Transforms/InstCombine/InstCombine.h"
64#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
65#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
66#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
67#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
68#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
69#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
70#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
71#include "llvm/Transforms/Instrumentation/KCFI.h"
72#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
73#include "llvm/Transforms/Instrumentation/MemProfiler.h"
74#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
75#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
76#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
77#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
78#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
79#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
80#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
81#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
82#include "llvm/Transforms/ObjCARC.h"
83#include "llvm/Transforms/Scalar/EarlyCSE.h"
84#include "llvm/Transforms/Scalar/GVN.h"
85#include "llvm/Transforms/Scalar/JumpThreading.h"
86#include "llvm/Transforms/Utils/Debugify.h"
87#include "llvm/Transforms/Utils/ModuleUtils.h"
94#define HANDLE_EXTENSION(Ext) \
95 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
96#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.")));
130std::string getDefaultProfileGenName() {
132 ?
"default_%m.proflite"
133 :
"default_%m.profraw";
136class EmitAssemblyHelper {
142 llvm::Module *TheModule;
145 std::unique_ptr<raw_pwrite_stream> OS;
149 TargetIRAnalysis getTargetIRAnalysis()
const {
151 return TM->getTargetIRAnalysis();
153 return TargetIRAnalysis();
164 void CreateTargetMachine(
bool MustCreateTM);
169 bool AddEmitPasses(legacy::PassManager &CodeGenPasses,
BackendAction Action,
170 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
172 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef
Path) {
174 auto F = std::make_unique<llvm::ToolOutputFile>(
Path, EC,
175 llvm::sys::fs::OF_None);
177 Diags.
Report(diag::err_fe_unable_to_open_output) <<
Path << EC.message();
183 void RunOptimizationPipeline(
184 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
185 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS,
BackendConsumer *BC);
187 std::unique_ptr<raw_pwrite_stream> &OS,
188 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
195 bool shouldEmitRegularLTOSummary()
const {
196 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
197 TargetTriple.getVendor() != llvm::Triple::Apple;
203 bool shouldEmitUnifiedLTOModueFlag()
const {
204 return CodeGenOpts.UnifiedLTO &&
205 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
211 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
212 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
214 TargetTriple(TheModule->getTargetTriple()) {}
216 ~EmitAssemblyHelper() {
217 if (CodeGenOpts.DisableFree)
218 BuryPointer(std::move(TM));
221 std::unique_ptr<TargetMachine> TM;
224 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
229static SanitizerCoverageOptions
231 SanitizerCoverageOptions Opts;
233 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
234 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
235 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
236 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
237 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
238 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
239 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
240 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
241 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
242 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
243 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
244 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
245 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
246 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
247 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
248 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
249 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
253static SanitizerBinaryMetadataOptions
255 SanitizerBinaryMetadataOptions Opts;
256 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
257 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
258 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
267 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
269 switch (
T.getObjectFormat()) {
274 return !CGOpts.DisableIntegratedAS;
276 llvm::report_fatal_error(
"ASan not implemented for GOFF");
278 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
280 case Triple::DXContainer:
282 case Triple::UnknownObjectFormat:
288static std::optional<llvm::CodeModel::Model>
290 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
291 .Case(
"tiny", llvm::CodeModel::Tiny)
292 .Case(
"small", llvm::CodeModel::Small)
293 .Case(
"kernel", llvm::CodeModel::Kernel)
294 .Case(
"medium", llvm::CodeModel::Medium)
295 .Case(
"large", llvm::CodeModel::Large)
296 .Case(
"default", ~1u)
298 assert(CodeModel != ~0u &&
"invalid code model!");
299 if (CodeModel == ~1u)
301 return static_cast<llvm::CodeModel::Model
>(CodeModel);
306 return CodeGenFileType::ObjectFile;
308 return CodeGenFileType::Null;
311 return CodeGenFileType::AssemblyFile;
321 StringRef MainFilename) {
323 return std::string{};
325 std::string FlatCmdLine;
326 raw_string_ostream OS(FlatCmdLine);
327 bool PrintedOneArg =
false;
328 if (!StringRef(Args[0]).
contains(
"-cc1")) {
329 llvm::sys::printArg(OS,
"-cc1",
true);
330 PrintedOneArg =
true;
332 for (
unsigned i = 0; i < Args.size(); i++) {
333 StringRef Arg = Args[i];
336 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
340 if (Arg.starts_with(
"-object-file-name") || Arg == MainFilename)
343 if (Arg.starts_with(
"-fmessage-length"))
347 llvm::sys::printArg(OS, Arg,
true);
348 PrintedOneArg =
true;
355 llvm::TargetOptions &Options) {
360 switch (LangOpts.getThreadModel()) {
361 case LangOptions::ThreadModelKind::POSIX:
362 Options.ThreadModel = llvm::ThreadModel::POSIX;
364 case LangOptions::ThreadModelKind::Single:
365 Options.ThreadModel = llvm::ThreadModel::Single;
370 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
372 "Invalid Floating Point ABI!");
373 Options.FloatABIType =
374 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
375 .Case(
"soft", llvm::FloatABI::Soft)
376 .Case(
"softfp", llvm::FloatABI::Soft)
377 .Case(
"hard", llvm::FloatABI::Hard)
378 .Default(llvm::FloatABI::Default);
381 switch (LangOpts.getDefaultFPContractMode()) {
382 case LangOptions::FPM_Off:
385 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
387 case LangOptions::FPM_On:
388 case LangOptions::FPM_FastHonorPragmas:
389 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
391 case LangOptions::FPM_Fast:
392 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
396 Options.BinutilsVersion =
397 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
398 Options.UseInitArray = CodeGenOpts.UseInitArray;
399 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
405 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
407 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
409 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
411 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
413 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
414 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
415 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
416 Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
417 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
418 (LangOpts.getDefaultFPContractMode() ==
419 LangOptions::FPModeKind::FPM_Fast ||
420 LangOpts.getDefaultFPContractMode() ==
421 LangOptions::FPModeKind::FPM_FastHonorPragmas);
422 Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
424 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
426 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
427 .Case(
"all", llvm::BasicBlockSection::All)
428 .StartsWith(
"list=", llvm::BasicBlockSection::List)
429 .Case(
"none", llvm::BasicBlockSection::None)
430 .Default(llvm::BasicBlockSection::None);
432 if (Options.BBSections == llvm::BasicBlockSection::List) {
433 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
434 MemoryBuffer::getFile(CodeGenOpts.
BBSections.substr(5));
436 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
437 << MBOrErr.getError().message();
440 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
443 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
444 Options.FunctionSections = CodeGenOpts.FunctionSections;
445 Options.DataSections = CodeGenOpts.DataSections;
446 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
447 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
448 Options.UniqueBasicBlockSectionNames =
449 CodeGenOpts.UniqueBasicBlockSectionNames;
450 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
451 Options.TLSSize = CodeGenOpts.TLSSize;
452 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
453 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
454 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
455 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
457 Options.EmitAddrsig = CodeGenOpts.Addrsig;
458 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
459 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
460 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
461 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
462 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
463 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
465 Options.Hotpatch = CodeGenOpts.HotPatch;
466 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
467 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
469 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
470 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
471 Options.SwiftAsyncFramePointer =
472 SwiftAsyncFramePointerMode::DeploymentBased;
475 case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
476 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
479 case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
480 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
485 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
486 Options.MCOptions.EmitCompactUnwindNonCanonical =
487 CodeGenOpts.EmitCompactUnwindNonCanonical;
488 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
489 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
490 Options.MCOptions.MCUseDwarfDirectory =
491 CodeGenOpts.NoDwarfDirectoryAsm
492 ? llvm::MCTargetOptions::DisableDwarfDirectory
493 : llvm::MCTargetOptions::EnableDwarfDirectory;
494 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
495 Options.MCOptions.MCIncrementalLinkerCompatible =
496 CodeGenOpts.IncrementalLinkerCompatible;
497 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
498 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
499 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
500 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
501 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
502 Options.MCOptions.Crel = CodeGenOpts.Crel;
503 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
504 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
505 Options.MCOptions.CompressDebugSections =
506 CodeGenOpts.getCompressDebugSections();
507 if (CodeGenOpts.OutputAsmVariant != 3)
508 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
509 Options.MCOptions.ABIName = TargetOpts.
ABI;
510 for (
const auto &Entry : HSOpts.UserEntries)
511 if (!Entry.IsFramework &&
512 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
513 Entry.Group == frontend::IncludeDirGroup::Angled ||
514 Entry.Group == frontend::IncludeDirGroup::System))
515 Options.MCOptions.IASSearchPaths.push_back(
516 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
517 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
521 Options.MCOptions.PPCUseFullRegisterNames =
522 CodeGenOpts.PPCUseFullRegisterNames;
523 Options.MisExpect = CodeGenOpts.MisExpect;
528static std::optional<GCOVOptions>
539 Options.NoRedZone = CodeGenOpts.DisableRedZone;
542 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
546static std::optional<InstrProfOptions>
551 InstrProfOptions Options;
552 Options.NoRedZone = CodeGenOpts.DisableRedZone;
554 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
560 BackendArgs.push_back(
"clang");
562 BackendArgs.push_back(
"-debug-pass");
563 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
566 BackendArgs.push_back(
"-limit-float-precision");
572 if (BackendArgs.size() == 1)
574 BackendArgs.push_back(
nullptr);
578 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
582void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
585 std::string Triple = TheModule->getTargetTriple();
586 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
589 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
593 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
594 std::string FeaturesStr =
597 std::optional<CodeGenOptLevel> OptLevelOrNone =
598 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
599 assert(OptLevelOrNone &&
"Invalid optimization level!");
600 CodeGenOptLevel OptLevel = *OptLevelOrNone;
602 llvm::TargetOptions Options;
605 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
606 Options, RM, CM, OptLevel));
610bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
612 raw_pwrite_stream &OS,
613 raw_pwrite_stream *DwoOS) {
615 std::unique_ptr<TargetLibraryInfoImpl> TLII(
616 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
617 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
623 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
624 !CodeGenOpts.VerifyModule)) {
625 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
633 switch (Opts.OptimizationLevel) {
635 llvm_unreachable(
"Invalid optimization level!");
638 return OptimizationLevel::O0;
641 return OptimizationLevel::O1;
644 switch (Opts.OptimizeSize) {
646 llvm_unreachable(
"Invalid optimization level for size!");
649 return OptimizationLevel::O2;
652 return OptimizationLevel::Os;
655 return OptimizationLevel::Oz;
659 return OptimizationLevel::O3;
666 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
667 TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
671 PB.registerOptimizerLastEPCallback(
672 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
673 if (Level == OptimizationLevel::O0 &&
675 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
680 PB.registerPeepholeEPCallback(
681 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
682 if (Level != OptimizationLevel::O0 &&
684 FPM.addPass(KCFIPass());
691 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
692 ThinOrFullLTOPhase) {
695 MPM.addPass(SanitizerCoveragePass(
701 MPM.addPass(SanitizerBinaryMetadataPass(
706 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
708 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
711 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
712 CodeGenOpts.SanitizeMemoryParamRetval);
713 MPM.addPass(MemorySanitizerPass(options));
714 if (Level != OptimizationLevel::O0) {
719 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
720 FunctionPassManager FPM;
721 FPM.addPass(EarlyCSEPass(
true ));
722 FPM.addPass(InstCombinePass());
723 FPM.addPass(JumpThreadingPass());
724 FPM.addPass(GVNPass());
725 FPM.addPass(InstCombinePass());
726 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
730 MSanPass(SanitizerKind::Memory,
false);
731 MSanPass(SanitizerKind::KernelMemory,
true);
733 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
734 MPM.addPass(ModuleThreadSanitizerPass());
735 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
739 MPM.addPass(TypeSanitizerPass());
741 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
742 MPM.addPass(NumericalStabilitySanitizerPass());
744 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
745 MPM.addPass(RealtimeSanitizerPass());
747 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
750 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
751 llvm::AsanDtorKind DestructorKind =
752 CodeGenOpts.getSanitizeAddressDtor();
753 AddressSanitizerOptions Opts;
754 Opts.CompileKernel = CompileKernel;
756 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
757 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
758 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
762 ASanPass(SanitizerKind::Address,
false);
763 ASanPass(SanitizerKind::KernelAddress,
true);
765 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
768 MPM.addPass(HWAddressSanitizerPass(
769 {CompileKernel, Recover,
770 CodeGenOpts.OptimizationLevel == 0}));
773 HWASanPass(SanitizerKind::HWAddress,
false);
774 HWASanPass(SanitizerKind::KernelHWAddress,
true);
776 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
781 PB.registerOptimizerEarlyEPCallback(
782 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
783 ThinOrFullLTOPhase Phase) {
784 ModulePassManager NewMPM;
785 SanitizersCallback(NewMPM, Level, Phase);
786 if (!NewMPM.isEmpty()) {
788 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
789 MPM.addPass(std::move(NewMPM));
794 PB.registerOptimizerLastEPCallback(SanitizersCallback);
797 if (LowerAllowCheckPass::IsRequested()) {
799 PB.registerOptimizerEarlyEPCallback([&](ModulePassManager &MPM,
800 OptimizationLevel Level,
801 ThinOrFullLTOPhase Phase) {
802 LowerAllowCheckPass::Options Opts;
803 MPM.addPass(createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
808void EmitAssemblyHelper::RunOptimizationPipeline(
809 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
810 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS,
BackendConsumer *BC) {
811 std::optional<PGOOptions> PGOOpt;
820 CodeGenOpts.DebugInfoForProfiling,
821 false, CodeGenOpts.AtomicProfileUpdate);
825 : PGOOptions::NoCSAction;
830 CodeGenOpts.DebugInfoForProfiling);
837 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
841 PGOOptions::NoAction, PGOOptions::NoCSAction,
843 else if (CodeGenOpts.PseudoProbeForProfiling)
846 PGOOptions(
"",
"",
"",
"",
nullptr,
847 PGOOptions::NoAction, PGOOptions::NoCSAction,
849 else if (CodeGenOpts.DebugInfoForProfiling)
851 PGOOpt = PGOOptions(
"",
"",
"",
"",
nullptr,
852 PGOOptions::NoAction, PGOOptions::NoCSAction,
858 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
861 assert(PGOOpt->Action != PGOOptions::IRInstr &&
862 PGOOpt->Action != PGOOptions::SampleUse &&
863 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
866 ? getDefaultProfileGenName()
867 : CodeGenOpts.InstrProfileOutput;
868 PGOOpt->CSAction = PGOOptions::CSIRInstr;
870 PGOOpt = PGOOptions(
"",
872 ? getDefaultProfileGenName()
875 PGOOptions::NoAction, PGOOptions::CSIRInstr,
879 TM->setPGOOption(PGOOpt);
881 PipelineTuningOptions PTO;
882 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
885 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
886 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
887 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
888 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
891 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
892 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
894 LoopAnalysisManager LAM;
895 FunctionAnalysisManager FAM;
896 CGSCCAnalysisManager CGAM;
897 ModuleAnalysisManager MAM;
899 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
900 PassInstrumentationCallbacks PIC;
901 PrintPassOptions PrintPassOpts;
902 PrintPassOpts.Indent = DebugPassStructure;
903 PrintPassOpts.SkipAnalyses = DebugPassStructure;
904 StandardInstrumentations SI(
905 TheModule->getContext(),
906 (CodeGenOpts.DebugPassManager || DebugPassStructure),
907 CodeGenOpts.VerifyEach, PrintPassOpts);
908 SI.registerCallbacks(PIC, &MAM);
909 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
912 switch (CodeGenOpts.getAssignmentTrackingMode()) {
913 case CodeGenOptions::AssignmentTrackingOpts::Forced:
914 PB.registerPipelineStartEPCallback(
915 [&](ModulePassManager &MPM, OptimizationLevel Level) {
916 MPM.addPass(AssignmentTrackingPass());
919 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
922 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
923 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
924 PB.registerPipelineStartEPCallback(
925 [&](ModulePassManager &MPM, OptimizationLevel Level) {
927 if (Level != OptimizationLevel::O0)
928 MPM.addPass(AssignmentTrackingPass());
932 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
937 DebugifyEachInstrumentation Debugify;
938 DebugInfoPerPass DebugInfoBeforePass;
939 if (CodeGenOpts.EnableDIPreservationVerify) {
940 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
941 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
944 Debugify.setOrigDIVerifyBugsReportFilePath(
946 Debugify.registerCallbacks(PIC, MAM);
950 auto PassPlugin = PassPlugin::Load(PluginFN);
952 PassPlugin->registerPassBuilderCallbacks(PB);
954 Diags.
Report(diag::err_fe_unable_to_load_plugin)
955 << PluginFN <<
toString(PassPlugin.takeError());
960#define HANDLE_EXTENSION(Ext) \
961 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
962#include "llvm/Support/Extension.def"
966 std::unique_ptr<TargetLibraryInfoImpl> TLII(
967 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
968 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
971 PB.registerModuleAnalyses(MAM);
972 PB.registerCGSCCAnalyses(CGAM);
973 PB.registerFunctionAnalyses(FAM);
974 PB.registerLoopAnalyses(LAM);
975 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
977 ModulePassManager MPM;
979 if (CodeGenOpts.VerifyModule)
980 MPM.addPass(VerifierPass());
982 if (!CodeGenOpts.DisableLLVMPasses) {
987 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
988 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
990 if (LangOpts.ObjCAutoRefCount) {
991 PB.registerPipelineStartEPCallback(
992 [](ModulePassManager &MPM, OptimizationLevel Level) {
993 if (Level != OptimizationLevel::O0)
995 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
997 PB.registerPipelineEarlySimplificationEPCallback(
998 [](ModulePassManager &MPM, OptimizationLevel Level,
999 ThinOrFullLTOPhase) {
1000 if (Level != OptimizationLevel::O0)
1001 MPM.addPass(ObjCARCAPElimPass());
1003 PB.registerScalarOptimizerLateEPCallback(
1004 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1005 if (Level != OptimizationLevel::O0)
1006 FPM.addPass(ObjCARCOptPass());
1016 if (IsThinLTOPostLink)
1017 PB.registerPipelineStartEPCallback(
1018 [](ModulePassManager &MPM, OptimizationLevel Level) {
1019 MPM.addPass(LowerTypeTestsPass(
1022 lowertypetests::DropTestKind::Assume));
1027 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1028 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1029 OptimizationLevel Level) {
1030 BoundsCheckingPass::Options Options;
1033 static_assert(SanitizerKind::SO_LocalBounds <=
1034 std::numeric_limits<
1035 decltype(Options.GuardKind)::value_type>::max(),
1036 "Update type of llvm.allow.ubsan.check to represent "
1037 "SanitizerKind::SO_LocalBounds.");
1038 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1045 CodeGenOpts.SanitizeMinimalRuntime),
1047 CodeGenOpts.SanitizeRecover.has(SanitizerKind::LocalBounds),
1050 FPM.addPass(BoundsCheckingPass(Options));
1055 if (!IsThinLTOPostLink) {
1060 if (std::optional<GCOVOptions> Options =
1062 PB.registerPipelineStartEPCallback(
1063 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1064 MPM.addPass(GCOVProfilerPass(*Options));
1066 if (std::optional<InstrProfOptions> Options =
1068 PB.registerPipelineStartEPCallback(
1069 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1070 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1076 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1077 OptimizationLevel Level,
1078 ThinOrFullLTOPhase) {
1079 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1080 MPM.addPass(ModuleMemProfilerPass());
1084 if (CodeGenOpts.FatLTO) {
1085 MPM.addPass(PB.buildFatLTODefaultPipeline(
1086 Level, PrepareForThinLTO,
1087 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1088 }
else if (PrepareForThinLTO) {
1089 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1090 }
else if (PrepareForLTO) {
1091 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1093 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1098 if (CodeGenOpts.LinkBitcodePostopt)
1107 MPM.addPass(VerifierPass());
1110 CodeGenOpts.FatLTO) {
1111 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1112 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1113 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1114 CodeGenOpts.EnableSplitLTOUnit);
1121 MPM.addPass(ThinLTOBitcodeWriterPass(
1122 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1124 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1130 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1131 if (EmitLTOSummary) {
1132 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1133 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1134 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1135 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1139 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1142 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1147 if (shouldEmitUnifiedLTOModueFlag())
1148 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1156 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1157 auto PassName = PIC.getPassNameForClassName(ClassName);
1158 return PassName.empty() ? ClassName : PassName;
1164 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1165 LangOpts.HIPStdParInterposeAlloc)
1166 MPM.addPass(HipStdParAllocationInterpositionPass());
1170 PrettyStackTraceString CrashInfo(
"Optimizer");
1171 llvm::TimeTraceScope TimeScope(
"Optimizer");
1177 MPM.run(*TheModule, MAM);
1183void EmitAssemblyHelper::RunCodegenPipeline(
1184 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1185 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1189 legacy::PassManager CodeGenPasses;
1197 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1203 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1204 DwoOS ? &DwoOS->os() :
nullptr))
1220 PrettyStackTraceString CrashInfo(
"Code generation");
1221 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1224 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1227 CodeGenPasses.run(*TheModule);
1234 std::unique_ptr<raw_pwrite_stream> OS,
1239 CreateTargetMachine(RequiresCodeGen);
1241 if (RequiresCodeGen && !TM)
1244 TheModule->setDataLayout(TM->createDataLayout());
1247 cl::PrintOptionValues();
1249 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1250 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1251 RunCodegenPipeline(Action, OS, DwoOS);
1261 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1262 std::string SampleProfile, std::string ProfileRemapping,
1267 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1268 ModuleToDefinedGVSummaries;
1269 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1276 FunctionImporter::ImportIDTable ImportIDs;
1277 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1278 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1281 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1282 return std::make_unique<CachedFileStream>(std::move(OS),
1283 CGOpts.ObjectFilenameForDebug);
1286 if (CGOpts.SaveTempsFilePrefix !=
"") {
1287 if (Error
E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1289 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1290 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1295 Conf.CPU = TOpts.CPU;
1297 Conf.MAttrs = TOpts.Features;
1298 Conf.RelocModel = CGOpts.RelocationModel;
1299 std::optional<CodeGenOptLevel> OptLevelOrNone =
1300 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1301 assert(OptLevelOrNone &&
"Invalid optimization level!");
1302 Conf.CGOptLevel = *OptLevelOrNone;
1303 Conf.OptLevel = CGOpts.OptimizationLevel;
1305 Conf.SampleProfile = std::move(SampleProfile);
1306 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1309 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1310 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1311 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1314 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1317 if (CGOpts.hasProfileCSIRInstr()) {
1318 Conf.RunCSIRInstr =
true;
1319 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1320 }
else if (CGOpts.hasProfileCSIRUse()) {
1321 Conf.RunCSIRInstr =
false;
1322 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1325 Conf.ProfileRemapping = std::move(ProfileRemapping);
1326 Conf.DebugPassManager = CGOpts.DebugPassManager;
1327 Conf.VerifyEach = CGOpts.VerifyEach;
1328 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1329 Conf.RemarksFilename = CGOpts.OptRecordFile;
1330 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1331 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1332 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1333 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1336 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1341 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1342 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1347 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1348 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1357 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1358 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1359 nullptr, Conf.CodeGenOnly,
1360 nullptr, CGOpts.CmdArgs)) {
1361 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1362 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1370 std::unique_ptr<raw_pwrite_stream> OS,
1372 llvm::TimeTraceScope TimeScope(
"Backend");
1376 std::unique_ptr<llvm::Module> EmptyModule;
1377 if (!CGOpts.ThinLTOIndexFile.empty()) {
1381 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1382 if (Error
E = llvm::getModuleSummaryIndexForFile(
1383 CGOpts.ThinLTOIndexFile,
1385 .moveInto(CombinedIndex)) {
1386 logAllUnhandledErrors(std::move(
E), errs(),
1387 "Error loading index file '" +
1388 CGOpts.ThinLTOIndexFile +
"': ");
1395 if (CombinedIndex) {
1396 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1398 CGOpts.SampleProfileFile, CGOpts.ProfileRemappingFile,
1408 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1409 EmptyModule->setTargetTriple(M->getTargetTriple());
1410 M = EmptyModule.get();
1414 EmitAssemblyHelper AsmHelper(CI, M, VFS);
1415 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1420 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1421 if (DLDesc != TDesc) {
1424 "expected target description '%1'");
1425 Diags.
Report(DiagID) << DLDesc << TDesc;
1433 llvm::MemoryBufferRef Buf) {
1436 llvm::embedBitcodeInModule(
1448 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1449 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1450 if (ObjectOrErr.getError()) {
1452 "could not open '%0' for embedding");
1453 Diags.
Report(DiagID) << OffloadObject;
1457 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1458 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 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 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.
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::vector< std::string > CommandLineArgs
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...
bool hasWasmExceptions() const
bool hasSjLjExceptions() const
SanitizerSet Sanitize
Set of enabled sanitizers.
bool hasDWARFExceptions() const
bool hasSEHExceptions() const
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
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)
void emitBackendOutput(CompilerInstance &CI, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
llvm::cl::opt< bool > ClSanitizeGuardChecks
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.
cl::opt< bool > PrintPipelinePasses
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.