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/Bitcode/BitcodeReader.h"
26#include "llvm/Bitcode/BitcodeWriter.h"
27#include "llvm/Bitcode/BitcodeWriterPass.h"
28#include "llvm/CodeGen/MachineModuleInfo.h"
29#include "llvm/CodeGen/TargetSubtargetInfo.h"
30#include "llvm/Config/llvm-config.h"
31#include "llvm/Frontend/Driver/CodeGenOptions.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DebugInfo.h"
34#include "llvm/IR/LLVMRemarkStreamer.h"
35#include "llvm/IR/LegacyPassManager.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/ModuleSummaryIndex.h"
38#include "llvm/IR/PassManager.h"
39#include "llvm/IR/Verifier.h"
40#include "llvm/IRPrinter/IRPrintingPasses.h"
41#include "llvm/LTO/LTOBackend.h"
42#include "llvm/MC/TargetRegistry.h"
43#include "llvm/Object/OffloadBinary.h"
44#include "llvm/Passes/PassBuilder.h"
45#include "llvm/Passes/StandardInstrumentations.h"
46#include "llvm/Plugins/PassPlugin.h"
47#include "llvm/ProfileData/InstrProfCorrelator.h"
48#include "llvm/Support/BuryPointer.h"
49#include "llvm/Support/CodeGen.h"
50#include "llvm/Support/CommandLine.h"
51#include "llvm/Support/Compiler.h"
52#include "llvm/Support/IOSandbox.h"
53#include "llvm/Support/MemoryBuffer.h"
54#include "llvm/Support/PrettyStackTrace.h"
55#include "llvm/Support/Program.h"
56#include "llvm/Support/TimeProfiler.h"
57#include "llvm/Support/Timer.h"
58#include "llvm/Support/ToolOutputFile.h"
59#include "llvm/Support/VirtualFileSystem.h"
60#include "llvm/Support/raw_ostream.h"
61#include "llvm/Target/TargetMachine.h"
62#include "llvm/Target/TargetOptions.h"
63#include "llvm/TargetParser/SubtargetFeature.h"
64#include "llvm/TargetParser/Triple.h"
65#include "llvm/Transforms/HipStdPar/HipStdPar.h"
66#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
67#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
68#include "llvm/Transforms/IPO/LowerTypeTests.h"
69#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
70#include "llvm/Transforms/InstCombine/InstCombine.h"
71#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
72#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
73#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
74#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
75#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
76#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
77#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
78#include "llvm/Transforms/Instrumentation/KCFI.h"
79#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
80#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
81#include "llvm/Transforms/Instrumentation/MemProfUse.h"
82#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
83#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
84#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
85#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
86#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
87#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
88#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
89#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
90#include "llvm/Transforms/ObjCARC.h"
91#include "llvm/Transforms/Scalar/EarlyCSE.h"
92#include "llvm/Transforms/Scalar/GVN.h"
93#include "llvm/Transforms/Scalar/JumpThreading.h"
94#include "llvm/Transforms/Utils/AssignGUID.h"
95#include "llvm/Transforms/Utils/Debugify.h"
96#include "llvm/Transforms/Utils/ModuleUtils.h"
100using namespace clang;
103#define HANDLE_EXTENSION(Ext) \
104 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
105#include "llvm/Support/Extension.def"
110 "sanitizer-early-opt-ep", cl::Optional,
111 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
116 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
118 "Function attribute to apply to cold functions as determined by PGO"),
119 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
120 "Default (no attribute)"),
121 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
122 "Mark cold functions with optsize."),
123 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
124 "Mark cold functions with minsize."),
125 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
126 "Mark cold functions with optnone.")));
128LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
138 ? llvm::driver::getDefaultProfileGenName()
140 if (CodeGenOpts.ContinuousProfileSync)
147class EmitAssemblyHelper {
148 CompilerInstance &CI;
149 DiagnosticsEngine &Diags;
150 const CodeGenOptions &CodeGenOpts;
151 const clang::TargetOptions &TargetOpts;
152 const LangOptions &LangOpts;
153 llvm::Module *TheModule;
154 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
156 std::unique_ptr<raw_pwrite_stream> OS;
160 TargetIRAnalysis getTargetIRAnalysis()
const {
162 return TM->getTargetIRAnalysis();
164 return TargetIRAnalysis();
175 void CreateTargetMachine(
bool MustCreateTM);
177 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
179 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
180 llvm::sys::fs::OF_None);
182 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
188 void RunOptimizationPipeline(
189 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
190 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
192 std::unique_ptr<raw_pwrite_stream> &OS,
193 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
195 std::unique_ptr<raw_pwrite_stream> &OS,
196 std::unique_ptr<llvm::ToolOutputFile> &DwoOS,
197 CodeGenFileType CGFT);
199 std::unique_ptr<raw_pwrite_stream> &OS,
200 std::unique_ptr<llvm::ToolOutputFile> &DwoOS,
201 CodeGenFileType CGFT);
202 void TimeCodegenPasses(llvm::function_ref<
void()> RunPasses);
209 bool shouldEmitRegularLTOSummary()
const {
210 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
211 TargetTriple.getVendor() != llvm::Triple::Apple;
217 bool shouldEmitUnifiedLTOModueFlag()
const {
218 return CodeGenOpts.UnifiedLTO &&
219 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
223 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
225 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
226 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
227 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
228 TheModule(M), VFS(std::move(VFS)),
229 TargetTriple(TheModule->getTargetTriple()) {}
231 ~EmitAssemblyHelper() {
232 if (CodeGenOpts.DisableFree)
233 BuryPointer(std::move(TM));
236 std::unique_ptr<TargetMachine> TM;
239 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
240 BackendConsumer *BC);
244static SanitizerCoverageOptions
246 SanitizerCoverageOptions Opts;
248 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
249 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
250 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
251 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
252 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
253 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
254 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
255 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
256 Opts.TracePCEntryExit = CGOpts.SanitizeCoverageTracePCEntryExit;
257 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
258 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
259 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
260 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
261 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
262 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
263 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
264 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
265 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
266 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
270static SanitizerBinaryMetadataOptions
272 SanitizerBinaryMetadataOptions Opts;
273 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
274 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
275 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
284 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
286 switch (
T.getObjectFormat()) {
291 return !CGOpts.DisableIntegratedAS;
293 llvm::report_fatal_error(
"ASan not implemented for GOFF");
295 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
297 case Triple::DXContainer:
299 case Triple::UnknownObjectFormat:
305static std::optional<llvm::CodeModel::Model>
307 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
308 .Case(
"tiny", llvm::CodeModel::Tiny)
309 .Case(
"small", llvm::CodeModel::Small)
310 .Case(
"kernel", llvm::CodeModel::Kernel)
311 .Case(
"medium", llvm::CodeModel::Medium)
312 .Case(
"large", llvm::CodeModel::Large)
313 .Cases({
"default",
""}, ~1u)
315 assert(CodeModel != ~0u &&
"invalid code model!");
316 if (CodeModel == ~1u)
318 return static_cast<llvm::CodeModel::Model
>(CodeModel);
323 return CodeGenFileType::ObjectFile;
325 return CodeGenFileType::Null;
328 return CodeGenFileType::AssemblyFile;
338 StringRef MainFilename,
341 return std::string{};
343 std::string FlatCmdLine;
344 raw_string_ostream OS(FlatCmdLine);
345 bool PrintedOneArg =
false;
346 if (!StringRef(Args[0]).
contains(
"-cc1")) {
347 llvm::sys::printArg(OS,
"-cc1",
true);
348 PrintedOneArg =
true;
350 for (
unsigned i = 0; i < Args.size(); i++) {
351 StringRef Arg = Args[i];
354 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
358 if (Arg.starts_with(
"-object-file-name"))
366 if (Arg == MainFilename || llvm::is_contained(InputFiles, Arg))
369 if (Arg.starts_with(
"-fmessage-length"))
373 llvm::sys::printArg(OS, Arg,
true);
374 PrintedOneArg =
true;
381 llvm::TargetOptions &Options) {
386 switch (LangOpts.getThreadModel()) {
388 Options.ThreadModel = llvm::ThreadModel::POSIX;
391 Options.ThreadModel = llvm::ThreadModel::Single;
396 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
398 "Invalid Floating Point ABI!");
399 Options.FloatABIType =
400 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
401 .Case(
"soft", llvm::FloatABI::Soft)
402 .Case(
"softfp", llvm::FloatABI::Soft)
403 .Case(
"hard", llvm::FloatABI::Hard)
404 .Default(llvm::FloatABI::Default);
407 switch (LangOpts.getDefaultFPContractMode()) {
411 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
415 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
418 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
422 Options.BinutilsVersion =
423 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
424 Options.UseInitArray = CodeGenOpts.UseInitArray;
425 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
431 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
433 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
435 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
437 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
439 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
441 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
443 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
444 .Case(
"all", llvm::BasicBlockSection::All)
445 .StartsWith(
"list=", llvm::BasicBlockSection::List)
446 .Case(
"none", llvm::BasicBlockSection::None)
447 .Default(llvm::BasicBlockSection::None);
449 if (Options.BBSections == llvm::BasicBlockSection::List) {
450 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
454 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
455 << MBOrErr.getError().message();
458 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
461 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
462 Options.EnableStaticDataPartitioning =
463 CodeGenOpts.PartitionStaticDataSections;
464 Options.FunctionSections = CodeGenOpts.FunctionSections;
465 Options.DataSections = CodeGenOpts.DataSections;
466 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
467 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
468 Options.UniqueBasicBlockSectionNames =
469 CodeGenOpts.UniqueBasicBlockSectionNames;
470 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
471 Options.TLSSize = CodeGenOpts.TLSSize;
472 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
473 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
474 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
475 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
477 Options.EmitAddrsig = CodeGenOpts.Addrsig;
478 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
479 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
480 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
481 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
482 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
483 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
484 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
486 Options.Hotpatch = CodeGenOpts.HotPatch;
487 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
488 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
490 convertDriverVectorLibraryToVectorLibrary(CodeGenOpts.getVecLib());
492 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
494 Options.SwiftAsyncFramePointer =
495 SwiftAsyncFramePointerMode::DeploymentBased;
499 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
503 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
508 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
509 Options.MCOptions.EmitCompactUnwindNonCanonical =
510 CodeGenOpts.EmitCompactUnwindNonCanonical;
511 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
512 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
513 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
514 Options.MCOptions.MCUseDwarfDirectory =
515 CodeGenOpts.NoDwarfDirectoryAsm
516 ? llvm::MCTargetOptions::DisableDwarfDirectory
517 : llvm::MCTargetOptions::EnableDwarfDirectory;
518 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
519 Options.MCOptions.MCIncrementalLinkerCompatible =
520 CodeGenOpts.IncrementalLinkerCompatible;
521 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
522 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
523 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
524 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
525 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
526 Options.MCOptions.Crel = CodeGenOpts.Crel;
527 Options.MCOptions.RelocSectionSym = CodeGenOpts.getRelocSectionSym();
528 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
529 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
530 Options.MCOptions.CompressDebugSections =
531 CodeGenOpts.getCompressDebugSections();
532 if (CodeGenOpts.OutputAsmVariant != 3)
533 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
534 Options.MCOptions.ABIName = TargetOpts.
ABI;
535 for (
const auto &Entry : HSOpts.UserEntries)
536 if (!Entry.IsFramework &&
540 Options.MCOptions.IASSearchPaths.push_back(
541 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
542 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
549 InputFiles.push_back(Input.getFile());
553 Options.MCOptions.PPCUseFullRegisterNames =
554 CodeGenOpts.PPCUseFullRegisterNames;
555 Options.MisExpect = CodeGenOpts.MisExpect;
560static std::optional<GCOVOptions>
571 Options.NoRedZone = CodeGenOpts.DisableRedZone;
574 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
578static std::optional<InstrProfOptions>
583 InstrProfOptions Options;
584 Options.NoRedZone = CodeGenOpts.DisableRedZone;
588 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
593 vfs::FileSystem &VFS) {
595 BackendArgs.push_back(
"clang");
597 BackendArgs.push_back(
"-debug-pass");
598 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
601 BackendArgs.push_back(
"-limit-float-precision");
608 if (BackendArgs.size() == 1)
610 BackendArgs.push_back(
nullptr);
614 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
619void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
622 const llvm::Triple &Triple = TheModule->getTargetTriple();
623 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
626 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
630 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
631 std::string FeaturesStr =
634 std::optional<CodeGenOptLevel> OptLevelOrNone =
635 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
636 assert(OptLevelOrNone &&
"Invalid optimization level!");
637 CodeGenOptLevel OptLevel = *OptLevelOrNone;
639 llvm::TargetOptions Options;
642 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
643 Options, RM, CM, OptLevel));
649 switch (Opts.OptimizationLevel) {
651 llvm_unreachable(
"Invalid optimization level!");
654 return OptimizationLevel::O0;
657 return OptimizationLevel::O1;
660 return OptimizationLevel::O2;
663 return OptimizationLevel::O3;
670 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
671 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
672 TargetTriple.isARM() || TargetTriple.isThumb())
676 PB.registerOptimizerLastEPCallback(
677 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
678 if (Level == OptimizationLevel::O0 &&
680 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
685 PB.registerPeepholeEPCallback(
686 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
687 if (Level != OptimizationLevel::O0 &&
689 FPM.addPass(KCFIPass());
696 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
697 ThinOrFullLTOPhase) {
701 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
707 MPM.addPass(SanitizerBinaryMetadataPass(
709 PB.getVirtualFileSystemPtr(),
713 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
715 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
718 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
719 CodeGenOpts.SanitizeMemoryParamRetval);
720 MPM.addPass(MemorySanitizerPass(
options));
721 if (Level != OptimizationLevel::O0) {
726 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
727 FunctionPassManager FPM;
728 FPM.addPass(EarlyCSEPass(
true ));
729 FPM.addPass(InstCombinePass());
730 FPM.addPass(JumpThreadingPass());
731 FPM.addPass(GVNPass());
732 FPM.addPass(InstCombinePass());
733 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
737 MSanPass(SanitizerKind::Memory,
false);
738 MSanPass(SanitizerKind::KernelMemory,
true);
740 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
741 MPM.addPass(ModuleThreadSanitizerPass());
742 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
746 MPM.addPass(TypeSanitizerPass());
748 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
749 MPM.addPass(NumericalStabilitySanitizerPass());
751 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
752 MPM.addPass(RealtimeSanitizerPass());
754 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
757 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
758 llvm::AsanDtorKind DestructorKind =
759 CodeGenOpts.getSanitizeAddressDtor();
760 AddressSanitizerOptions Opts;
761 Opts.CompileKernel = CompileKernel;
763 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
764 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
765 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
769 ASanPass(SanitizerKind::Address,
false);
770 ASanPass(SanitizerKind::KernelAddress,
true);
772 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
775 MPM.addPass(HWAddressSanitizerPass(
776 {CompileKernel, Recover,
777 CodeGenOpts.OptimizationLevel == 0}));
780 HWASanPass(SanitizerKind::HWAddress,
false);
781 HWASanPass(SanitizerKind::KernelHWAddress,
true);
783 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
785 PB.getVirtualFileSystemPtr()));
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);
811 uint64_t AllowRuntimeCheckSkipHotCutoff =
816 SanitizerKind::Address | SanitizerKind::KernelAddress |
817 SanitizerKind::Thread | SanitizerKind::Memory |
818 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
819 SanitizerKind::KernelHWAddress);
822 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
824 LowerAllowSanitize) {
826 PB.registerOptimizerEarlyEPCallback(
827 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
828 ModulePassManager &MPM, OptimizationLevel Level,
829 ThinOrFullLTOPhase Phase) {
830 LowerAllowCheckPass::Options Opts;
832 if (ScaledCutoffs.has_value())
833 Opts.cutoffs = ScaledCutoffs.value();
834 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
836 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
841void EmitAssemblyHelper::RunOptimizationPipeline(
842 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
843 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
844 std::optional<PGOOptions> PGOOpt;
851 CodeGenOpts.DebugInfoForProfiling,
853 CodeGenOpts.AtomicProfileUpdate);
857 : PGOOptions::NoCSAction;
862 CodeGenOpts.DebugInfoForProfiling);
869 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
873 PGOOptions::NoAction, PGOOptions::NoCSAction,
875 else if (CodeGenOpts.PseudoProbeForProfiling)
877 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
879 CodeGenOpts.DebugInfoForProfiling,
true);
880 else if (CodeGenOpts.DebugInfoForProfiling)
882 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
888 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
891 assert(PGOOpt->Action != PGOOptions::IRInstr &&
892 PGOOpt->Action != PGOOptions::SampleUse &&
893 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
896 PGOOpt->CSAction = PGOOptions::CSIRInstr;
899 "", PGOOptions::NoAction,
901 CodeGenOpts.DebugInfoForProfiling);
904 TM->setPGOOption(PGOOpt);
906 PipelineTuningOptions PTO;
907 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
908 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
909 PTO.LoopFusion = CodeGenOpts.FuseLoops;
912 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
913 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
914 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
915 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
918 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
919 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
920 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
922 LoopAnalysisManager LAM;
923 FunctionAnalysisManager FAM;
924 CGSCCAnalysisManager CGAM;
925 ModuleAnalysisManager MAM;
927 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
928 PassInstrumentationCallbacks PIC;
929 PrintPassOptions PrintPassOpts;
930 PrintPassOpts.Indent = DebugPassStructure;
931 PrintPassOpts.SkipAnalyses = DebugPassStructure;
932 StandardInstrumentations SI(
933 TheModule->getContext(),
934 (CodeGenOpts.DebugPassManager || DebugPassStructure),
935 CodeGenOpts.VerifyEach, PrintPassOpts);
936 SI.registerCallbacks(PIC, &MAM);
940 switch (CodeGenOpts.getAssignmentTrackingMode()) {
941 case CodeGenOptions::AssignmentTrackingOpts::Forced:
942 PB.registerPipelineStartEPCallback(
943 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
944 MPM.addPass(AssignmentTrackingPass());
947 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
950 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
951 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
952 PB.registerPipelineStartEPCallback(
953 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
955 if (
Level != OptimizationLevel::O0)
956 MPM.addPass(AssignmentTrackingPass());
960 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
965 DebugifyEachInstrumentation Debugify;
966 DebugInfoPerPass DebugInfoBeforePass;
967 if (CodeGenOpts.EnableDIPreservationVerify) {
968 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
969 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
972 Debugify.setOrigDIVerifyBugsReportFilePath(
974 Debugify.registerCallbacks(PIC, MAM);
976#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
983 if (!F.getSubprogram())
985 for (BasicBlock &BB : F)
986 for (Instruction &I : BB)
987 if (!I.getDebugLoc())
988 I.setDebugLoc(DebugLoc::getCompilerGenerated());
993 for (
const std::unique_ptr<PassPlugin> &Plugin : CI.
getPassPlugins())
994 Plugin->registerPassBuilderCallbacks(PB);
997#define HANDLE_EXTENSION(Ext) \
998 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
999#include "llvm/Support/Extension.def"
1003 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1004 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1005 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1008 PB.registerModuleAnalyses(MAM);
1009 PB.registerCGSCCAnalyses(CGAM);
1010 PB.registerFunctionAnalyses(FAM);
1011 PB.registerLoopAnalyses(LAM);
1012 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1014 ModulePassManager MPM;
1016 if (CodeGenOpts.VerifyModule)
1017 MPM.addPass(VerifierPass());
1019 if (!CodeGenOpts.DisableLLVMPasses) {
1024 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1025 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1027 if (LangOpts.ObjCAutoRefCount) {
1028 PB.registerPipelineStartEPCallback(
1029 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1030 if (
Level != OptimizationLevel::O0)
1032 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1034 PB.registerScalarOptimizerLateEPCallback(
1035 [](FunctionPassManager &FPM, OptimizationLevel
Level) {
1036 if (
Level != OptimizationLevel::O0)
1037 FPM.addPass(ObjCARCOptPass());
1047 if (IsThinLTOPostLink)
1048 PB.registerPipelineStartEPCallback(
1049 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1050 MPM.addPass(DropTypeTestsPass());
1055 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1056 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1057 OptimizationLevel
Level) {
1058 BoundsCheckingPass::Options Options;
1061 static_assert(SanitizerKind::SO_LocalBounds <=
1062 std::numeric_limits<
1063 decltype(Options.GuardKind)::value_type>
::max(),
1064 "Update type of llvm.allow.ubsan.check to represent "
1065 "SanitizerKind::SO_LocalBounds.");
1066 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1073 CodeGenOpts.SanitizeMinimalRuntime),
1077 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1080 FPM.addPass(BoundsCheckingPass(Options));
1083 if (!IsThinLTOPostLink) {
1089 PB.registerPipelineStartEPCallback(
1090 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
1091 if (
Level == OptimizationLevel::O0 &&
1092 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
1098 MPM.addPass(InferFunctionAttrsPass());
1103 if (std::optional<GCOVOptions> Options =
1105 PB.registerPipelineStartEPCallback(
1106 [
this, Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1110 if (std::optional<InstrProfOptions> Options =
1112 PB.registerPipelineStartEPCallback(
1113 [Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1114 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1120 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1121 OptimizationLevel
Level,
1122 ThinOrFullLTOPhase) {
1123 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1124 MPM.addPass(ModuleMemProfilerPass());
1128 if (CodeGenOpts.FatLTO) {
1129 MPM.addPass(PB.buildFatLTODefaultPipeline(
1130 Level, PrepareForThinLTO,
1131 PrepareForThinLTO || shouldEmitRegularLTOSummary(),
1132 CodeGenOpts.VerifyModule));
1133 }
else if (PrepareForThinLTO) {
1134 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(
Level));
1135 }
else if (PrepareForLTO) {
1136 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(
Level));
1138 MPM.addPass(PB.buildPerModuleDefaultPipeline(
Level));
1143 if (CodeGenOpts.LinkBitcodePostopt) {
1144 MPM.addPass(LinkInModulesPass(BC));
1145 MPM.addPass(AssignGUIDPass());
1148 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1149 LangOpts.HIPStdParInterposeAlloc)
1150 MPM.addPass(HipStdParAllocationInterpositionPass());
1158 MPM.addPass(VerifierPass());
1161 CodeGenOpts.FatLTO) {
1162 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1163 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1164 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1165 CodeGenOpts.EnableSplitLTOUnit);
1172 MPM.addPass(ThinLTOBitcodeWriterPass(
1173 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1175 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1181 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1182 if (EmitLTOSummary) {
1183 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1184 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1185 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1186 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1190 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1193 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1198 if (shouldEmitUnifiedLTOModueFlag() &&
1199 !TheModule->getModuleFlag(
"UnifiedLTO"))
1200 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1207 if (PrintPipelinePasses) {
1208 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1209 auto PassName = PIC.getPassNameForClassName(ClassName);
1210 return PassName.empty() ? ClassName : PassName;
1218 PrettyStackTraceString CrashInfo(
"Optimizer");
1219 llvm::TimeTraceScope TimeScope(
"Optimizer");
1225 MPM.run(*TheModule, MAM);
1231void EmitAssemblyHelper::RunCodegenPipeline(
1232 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1233 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1243 for (
const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.
getPassPlugins()) {
1244 if (Plugin->invokePreCodeGenCallback(*TheModule, *TM, CGFT, *OS))
1254 if (CodeGenOpts.EnableNewPMCodeGen) {
1255 RunCodegenPipelineNewPM(Action, OS, DwoOS, CGFT);
1257 RunCodegenPipelineLegacy(Action, OS, DwoOS, CGFT);
1261void EmitAssemblyHelper::RunCodegenPipelineLegacy(
1262 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1263 std::unique_ptr<llvm::ToolOutputFile> &DwoOS, CodeGenFileType CGFT) {
1267 legacy::PassManager CodeGenPasses;
1270 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1272 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1273 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1274 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
1276 const llvm::TargetOptions &Options = TM->Options;
1277 CodeGenPasses.add(
new RuntimeLibraryInfoWrapper(
1278 TargetTriple, Options.ExceptionModel, Options.FloatABIType,
1279 Options.EABIVersion, Options.MCOptions.ABIName, Options.VecLib));
1281 if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
1282 DwoOS ? &DwoOS->os() :
nullptr, CGFT,
1283 !CodeGenOpts.VerifyModule)) {
1284 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1291 if (PrintPipelinePasses) {
1295 TimeCodegenPasses([&] { CodeGenPasses.run(*TheModule); });
1298void EmitAssemblyHelper::RunCodegenPipelineNewPM(
1299 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1300 std::unique_ptr<llvm::ToolOutputFile> &DwoOS, CodeGenFileType CGFT) {
1301 ModulePassManager MPM;
1302 MachineFunctionAnalysisManager MFAM;
1303 LoopAnalysisManager LAM;
1304 FunctionAnalysisManager FAM;
1305 CGSCCAnalysisManager CGAM;
1306 ModuleAnalysisManager MAM;
1307 CGPassBuilderOption Opt = getCGPassBuilderOption();
1308 Opt.DisableVerify = !CodeGenOpts.VerifyModule;
1309 MachineModuleInfo MMI(TM.get());
1310 PassInstrumentationCallbacks PIC;
1311 PipelineTuningOptions PTOptions;
1312 TargetMachine *TMPointer = TM.get();
1313 PassBuilder PB(TMPointer, PTOptions, std::nullopt, &PIC,
1315 PB.registerModuleAnalyses(MAM);
1316 PB.registerCGSCCAnalyses(CGAM);
1317 PB.registerFunctionAnalyses(FAM);
1318 PB.registerLoopAnalyses(LAM);
1319 PB.registerMachineFunctionAnalyses(MFAM);
1320 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM, &MFAM);
1322 MAM.registerPass([&] {
return MachineModuleAnalysis(MMI); });
1324 Error BuildPipelineError =
1325 TM->buildCodeGenPipeline(MPM, MAM, *OS, DwoOS ? &DwoOS->os() :
nullptr,
1326 CGFT, Opt, MMI.getContext(), &PIC);
1327 if (BuildPipelineError) {
1328 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1332 TimeCodegenPasses([&] { MPM.run(*TheModule, MAM); });
1335void EmitAssemblyHelper::TimeCodegenPasses(
1336 llvm::function_ref<
void()> RunPasses) {
1337 PrettyStackTraceString CrashInfo(
"Code generation");
1338 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1341 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1350 std::unique_ptr<raw_pwrite_stream> OS,
1351 BackendConsumer *BC) {
1355 CreateTargetMachine(RequiresCodeGen);
1357 if (RequiresCodeGen && !TM)
1360 TheModule->setDataLayout(TM->createDataLayout());
1363 cl::PrintOptionValues();
1365 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1366 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1367 RunCodegenPipeline(Action, OS, DwoOS);
1377 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1378 std::string SampleProfile, std::string ProfileRemapping,
1383 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1384 ModuleToDefinedGVSummaries;
1385 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1392 FunctionImporter::ImportIDTable ImportIDs;
1393 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1394 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1397 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1398 return std::make_unique<CachedFileStream>(std::move(OS),
1399 CGOpts.ObjectFilenameForDebug);
1402 if (CGOpts.SaveTempsFilePrefix !=
"") {
1403 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1405 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1406 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1411 Conf.CPU = TOpts.CPU;
1413 Conf.MAttrs = TOpts.Features;
1414 Conf.RelocModel = CGOpts.RelocationModel;
1415 std::optional<CodeGenOptLevel> OptLevelOrNone =
1416 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1417 assert(OptLevelOrNone &&
"Invalid optimization level!");
1418 Conf.CGOptLevel = *OptLevelOrNone;
1419 Conf.OptLevel = CGOpts.OptimizationLevel;
1421 Conf.SampleProfile = std::move(SampleProfile);
1422 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1423 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1424 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1427 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1428 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1429 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1432 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1435 if (CGOpts.hasProfileCSIRInstr()) {
1436 Conf.RunCSIRInstr =
true;
1438 }
else if (CGOpts.hasProfileCSIRUse()) {
1439 Conf.RunCSIRInstr =
false;
1440 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1443 Conf.ProfileRemapping = std::move(ProfileRemapping);
1444 Conf.DebugPassManager = CGOpts.DebugPassManager;
1445 Conf.VerifyEach = CGOpts.VerifyEach;
1446 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1447 Conf.RemarksFilename = CGOpts.OptRecordFile;
1448 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1449 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1450 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1451 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1453 Conf.LoadedPassPlugins.push_back(Plugin.get());
1456 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1461 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1462 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1467 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1468 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1481 finalizeLLVMOptimizationRemarks(M->getContext());
1482 if (
Error E = thinBackend(
1483 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1484 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1485 nullptr, Conf.CodeGenOnly, {},
1486 nullptr, CGOpts.CmdArgs)) {
1487 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1488 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1494 StringRef TDesc, llvm::Module *M,
1497 std::unique_ptr<raw_pwrite_stream> OS,
1499 llvm::TimeTraceScope TimeScope(
"Backend");
1502 std::unique_ptr<llvm::Module> EmptyModule;
1505 auto BypassSandbox = sys::sandbox::scopedDisable();
1509 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1510 if (
Error E = llvm::getModuleSummaryIndexForFile(
1513 .moveInto(CombinedIndex)) {
1514 logAllUnhandledErrors(std::move(E), errs(),
1515 "Error loading index file '" +
1523 if (CombinedIndex) {
1524 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1536 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1537 EmptyModule->setTargetTriple(M->getTargetTriple());
1538 M = EmptyModule.get();
1542 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1543 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1548 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1549 if (DLDesc != TDesc) {
1550 Diags.
Report(diag::err_data_layout_mismatch) << DLDesc << TDesc;
1558 llvm::MemoryBufferRef Buf) {
1561 llvm::embedBitcodeInModule(
1573 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1574 VFS.getBufferForFile(OffloadObject);
1575 if (ObjectOrErr.getError()) {
1576 Diags.
Report(diag::err_failed_to_open_for_embedding) << OffloadObject;
1580 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1581 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 setCommandLineOpts(const CodeGenOptions &CodeGenOpts, vfs::FileSystem &VFS)
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::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)
void addLowerAllowCheckPass(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
static CodeGenFileType getCodeGenFileType(BackendAction Action)
Defines the Diagnostic-related interfaces.
Defines the clang::LangOptions interface.
This file provides a pass to link in Modules from a provided BackendConsumer.
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 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.
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.
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
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.
@ Single
Single Threaded Environment.
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.
llvm::EABI EABIVersion
The EABI version to use.
@ Angled
Paths for '#include <>' added by '-I'.
@ System
Like Angled, but marks system directories.
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
The JSON file list parser is used to communicate input to InstallAPI.
@ Default
Set to the current date and time.
const FunctionProtoType * T
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 EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
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)
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."))
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_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.