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/Debugify.h"
95#include "llvm/Transforms/Utils/ModuleUtils.h"
102#define HANDLE_EXTENSION(Ext) \
103 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
104#include "llvm/Support/Extension.def"
109 "sanitizer-early-opt-ep", cl::Optional,
110 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
115 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
117 "Function attribute to apply to cold functions as determined by PGO"),
118 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
119 "Default (no attribute)"),
120 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
121 "Mark cold functions with optsize."),
122 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
123 "Mark cold functions with minsize."),
124 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
125 "Mark cold functions with optnone.")));
127LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
137 ? llvm::driver::getDefaultProfileGenName()
139 if (CodeGenOpts.ContinuousProfileSync)
146class EmitAssemblyHelper {
147 CompilerInstance &CI;
148 DiagnosticsEngine &Diags;
149 const CodeGenOptions &CodeGenOpts;
150 const clang::TargetOptions &TargetOpts;
151 const LangOptions &LangOpts;
152 llvm::Module *TheModule;
153 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
155 std::unique_ptr<raw_pwrite_stream> OS;
159 TargetIRAnalysis getTargetIRAnalysis()
const {
161 return TM->getTargetIRAnalysis();
163 return TargetIRAnalysis();
174 void CreateTargetMachine(
bool MustCreateTM);
176 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
178 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
179 llvm::sys::fs::OF_None);
181 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
187 void RunOptimizationPipeline(
188 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
189 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
191 std::unique_ptr<raw_pwrite_stream> &OS,
192 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
194 std::unique_ptr<raw_pwrite_stream> &OS,
195 std::unique_ptr<llvm::ToolOutputFile> &DwoOS,
196 CodeGenFileType CGFT);
198 std::unique_ptr<raw_pwrite_stream> &OS,
199 std::unique_ptr<llvm::ToolOutputFile> &DwoOS,
200 CodeGenFileType CGFT);
201 void TimeCodegenPasses(llvm::function_ref<
void()> RunPasses);
208 bool shouldEmitRegularLTOSummary()
const {
209 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
210 TargetTriple.getVendor() != llvm::Triple::Apple;
216 bool shouldEmitUnifiedLTOModueFlag()
const {
217 return CodeGenOpts.UnifiedLTO &&
218 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
222 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
224 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
225 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
226 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
227 TheModule(M), VFS(std::move(VFS)),
228 TargetTriple(TheModule->getTargetTriple()) {}
230 ~EmitAssemblyHelper() {
231 if (CodeGenOpts.DisableFree)
232 BuryPointer(std::move(TM));
235 std::unique_ptr<TargetMachine> TM;
238 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
239 BackendConsumer *BC);
243static SanitizerCoverageOptions
245 SanitizerCoverageOptions Opts;
247 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
248 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
249 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
250 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
251 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
252 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
253 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
254 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
255 Opts.TracePCEntryExit = CGOpts.SanitizeCoverageTracePCEntryExit;
256 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
257 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
258 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
259 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
260 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
261 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
262 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
263 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
264 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
265 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
269static SanitizerBinaryMetadataOptions
271 SanitizerBinaryMetadataOptions Opts;
272 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
273 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
274 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
283 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
285 switch (T.getObjectFormat()) {
290 return !CGOpts.DisableIntegratedAS;
292 llvm::report_fatal_error(
"ASan not implemented for GOFF");
294 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
296 case Triple::DXContainer:
298 case Triple::UnknownObjectFormat:
304static std::optional<llvm::CodeModel::Model>
306 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
307 .Case(
"tiny", llvm::CodeModel::Tiny)
308 .Case(
"small", llvm::CodeModel::Small)
309 .Case(
"kernel", llvm::CodeModel::Kernel)
310 .Case(
"medium", llvm::CodeModel::Medium)
311 .Case(
"large", llvm::CodeModel::Large)
312 .Cases({
"default",
""}, ~1u)
314 assert(CodeModel != ~0u &&
"invalid code model!");
315 if (CodeModel == ~1u)
317 return static_cast<llvm::CodeModel::Model
>(CodeModel);
322 return CodeGenFileType::ObjectFile;
324 return CodeGenFileType::Null;
327 return CodeGenFileType::AssemblyFile;
337 StringRef MainFilename,
340 return std::string{};
342 std::string FlatCmdLine;
343 raw_string_ostream OS(FlatCmdLine);
344 bool PrintedOneArg =
false;
345 if (!StringRef(Args[0]).
contains(
"-cc1")) {
346 llvm::sys::printArg(OS,
"-cc1",
true);
347 PrintedOneArg =
true;
349 for (
unsigned i = 0; i < Args.size(); i++) {
350 StringRef Arg = Args[i];
353 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
357 if (Arg.starts_with(
"-object-file-name"))
365 if (Arg == MainFilename || llvm::is_contained(InputFiles, Arg))
368 if (Arg.starts_with(
"-fmessage-length"))
372 llvm::sys::printArg(OS, Arg,
true);
373 PrintedOneArg =
true;
380 llvm::TargetOptions &Options) {
385 switch (LangOpts.getThreadModel()) {
387 Options.ThreadModel = llvm::ThreadModel::POSIX;
390 Options.ThreadModel = llvm::ThreadModel::Single;
395 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
397 "Invalid Floating Point ABI!");
398 Options.FloatABIType =
399 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
400 .Case(
"soft", llvm::FloatABI::Soft)
401 .Case(
"softfp", llvm::FloatABI::Soft)
402 .Case(
"hard", llvm::FloatABI::Hard)
403 .Default(llvm::FloatABI::Default);
406 switch (LangOpts.getDefaultFPContractMode()) {
410 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
414 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
417 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
421 Options.BinutilsVersion =
422 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
423 Options.UseInitArray = CodeGenOpts.UseInitArray;
424 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
430 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
432 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
434 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
436 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
438 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
440 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
442 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
443 .Case(
"all", llvm::BasicBlockSection::All)
444 .StartsWith(
"list=", llvm::BasicBlockSection::List)
445 .Case(
"none", llvm::BasicBlockSection::None)
446 .Default(llvm::BasicBlockSection::None);
448 if (Options.BBSections == llvm::BasicBlockSection::List) {
449 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
453 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
454 << MBOrErr.getError().message();
457 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
460 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
461 Options.EnableStaticDataPartitioning =
462 CodeGenOpts.PartitionStaticDataSections;
463 Options.FunctionSections = CodeGenOpts.FunctionSections;
464 Options.DataSections = CodeGenOpts.DataSections;
465 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
466 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
467 Options.UniqueBasicBlockSectionNames =
468 CodeGenOpts.UniqueBasicBlockSectionNames;
469 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
470 Options.TLSSize = CodeGenOpts.TLSSize;
471 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
472 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
473 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
474 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
476 Options.EmitAddrsig = CodeGenOpts.Addrsig;
477 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
478 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
479 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
480 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
481 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
482 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
483 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
485 Options.Hotpatch = CodeGenOpts.HotPatch;
486 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
487 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
489 convertDriverVectorLibraryToVectorLibrary(CodeGenOpts.getVecLib());
491 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
493 Options.SwiftAsyncFramePointer =
494 SwiftAsyncFramePointerMode::DeploymentBased;
498 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
502 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
507 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
508 Options.MCOptions.EmitCompactUnwindNonCanonical =
509 CodeGenOpts.EmitCompactUnwindNonCanonical;
510 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
511 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
512 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
513 Options.MCOptions.MCUseDwarfDirectory =
514 CodeGenOpts.NoDwarfDirectoryAsm
515 ? llvm::MCTargetOptions::DisableDwarfDirectory
516 : llvm::MCTargetOptions::EnableDwarfDirectory;
517 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
518 Options.MCOptions.MCIncrementalLinkerCompatible =
519 CodeGenOpts.IncrementalLinkerCompatible;
520 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
521 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
522 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
523 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
524 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
525 Options.MCOptions.Crel = CodeGenOpts.Crel;
526 Options.MCOptions.RelocSectionSym = CodeGenOpts.getRelocSectionSym();
527 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
528 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
529 Options.MCOptions.CompressDebugSections =
530 CodeGenOpts.getCompressDebugSections();
531 if (CodeGenOpts.OutputAsmVariant != 3)
532 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
533 Options.MCOptions.ABIName = TargetOpts.
ABI;
534 for (
const auto &Entry : HSOpts.UserEntries)
535 if (!Entry.IsFramework &&
539 Options.MCOptions.IASSearchPaths.push_back(
540 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
541 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
548 InputFiles.push_back(Input.getFile());
552 Options.MCOptions.PPCUseFullRegisterNames =
553 CodeGenOpts.PPCUseFullRegisterNames;
554 Options.MisExpect = CodeGenOpts.MisExpect;
559static std::optional<GCOVOptions>
570 Options.NoRedZone = CodeGenOpts.DisableRedZone;
573 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
577static std::optional<InstrProfOptions>
582 InstrProfOptions Options;
583 Options.NoRedZone = CodeGenOpts.DisableRedZone;
587 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
592 vfs::FileSystem &VFS) {
594 BackendArgs.push_back(
"clang");
596 BackendArgs.push_back(
"-debug-pass");
597 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
600 BackendArgs.push_back(
"-limit-float-precision");
607 if (BackendArgs.size() == 1)
609 BackendArgs.push_back(
nullptr);
613 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
618void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
621 const llvm::Triple &Triple = TheModule->getTargetTriple();
622 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
625 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
629 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
630 std::string FeaturesStr =
633 std::optional<CodeGenOptLevel> OptLevelOrNone =
634 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
635 assert(OptLevelOrNone &&
"Invalid optimization level!");
636 CodeGenOptLevel OptLevel = *OptLevelOrNone;
638 llvm::TargetOptions Options;
641 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
642 Options, RM, CM, OptLevel));
648 switch (Opts.OptimizationLevel) {
650 llvm_unreachable(
"Invalid optimization level!");
653 return OptimizationLevel::O0;
656 return OptimizationLevel::O1;
659 return OptimizationLevel::O2;
662 return OptimizationLevel::O3;
669 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
670 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
671 TargetTriple.isARM() || TargetTriple.isThumb())
675 PB.registerOptimizerLastEPCallback(
676 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
677 if (Level == OptimizationLevel::O0 &&
679 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
684 PB.registerPeepholeEPCallback(
685 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
686 if (Level != OptimizationLevel::O0 &&
688 FPM.addPass(KCFIPass());
695 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
696 ThinOrFullLTOPhase) {
700 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
706 MPM.addPass(SanitizerBinaryMetadataPass(
708 PB.getVirtualFileSystemPtr(),
712 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
714 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
717 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
718 CodeGenOpts.SanitizeMemoryParamRetval);
719 MPM.addPass(MemorySanitizerPass(
options));
720 if (Level != OptimizationLevel::O0) {
725 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
726 FunctionPassManager FPM;
727 FPM.addPass(EarlyCSEPass(
true ));
728 FPM.addPass(InstCombinePass());
729 FPM.addPass(JumpThreadingPass());
730 FPM.addPass(GVNPass());
731 FPM.addPass(InstCombinePass());
732 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
736 MSanPass(SanitizerKind::Memory,
false);
737 MSanPass(SanitizerKind::KernelMemory,
true);
739 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
740 MPM.addPass(ModuleThreadSanitizerPass());
741 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
745 MPM.addPass(TypeSanitizerPass());
747 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
748 MPM.addPass(NumericalStabilitySanitizerPass());
750 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
751 MPM.addPass(RealtimeSanitizerPass());
753 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
756 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
757 llvm::AsanDtorKind DestructorKind =
758 CodeGenOpts.getSanitizeAddressDtor();
759 AddressSanitizerOptions Opts;
760 Opts.CompileKernel = CompileKernel;
762 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
763 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
764 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
768 ASanPass(SanitizerKind::Address,
false);
769 ASanPass(SanitizerKind::KernelAddress,
true);
771 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
774 MPM.addPass(HWAddressSanitizerPass(
775 {CompileKernel, Recover,
776 CodeGenOpts.OptimizationLevel == 0}));
779 HWASanPass(SanitizerKind::HWAddress,
false);
780 HWASanPass(SanitizerKind::KernelHWAddress,
true);
782 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
784 PB.getVirtualFileSystemPtr()));
788 PB.registerOptimizerEarlyEPCallback(
789 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
790 ThinOrFullLTOPhase Phase) {
791 ModulePassManager NewMPM;
792 SanitizersCallback(NewMPM, Level, Phase);
793 if (!NewMPM.isEmpty()) {
795 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
796 MPM.addPass(std::move(NewMPM));
801 PB.registerOptimizerLastEPCallback(SanitizersCallback);
810 uint64_t AllowRuntimeCheckSkipHotCutoff =
815 SanitizerKind::Address | SanitizerKind::KernelAddress |
816 SanitizerKind::Thread | SanitizerKind::Memory |
817 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
818 SanitizerKind::KernelHWAddress);
821 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
823 LowerAllowSanitize) {
825 PB.registerOptimizerEarlyEPCallback(
826 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
827 ModulePassManager &MPM, OptimizationLevel Level,
828 ThinOrFullLTOPhase Phase) {
829 LowerAllowCheckPass::Options Opts;
831 if (ScaledCutoffs.has_value())
832 Opts.cutoffs = ScaledCutoffs.value();
833 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
835 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
840void EmitAssemblyHelper::RunOptimizationPipeline(
841 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
842 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
843 std::optional<PGOOptions> PGOOpt;
850 CodeGenOpts.DebugInfoForProfiling,
852 CodeGenOpts.AtomicProfileUpdate);
856 : PGOOptions::NoCSAction;
861 CodeGenOpts.DebugInfoForProfiling);
868 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
872 PGOOptions::NoAction, PGOOptions::NoCSAction,
874 else if (CodeGenOpts.PseudoProbeForProfiling)
876 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
878 CodeGenOpts.DebugInfoForProfiling,
true);
879 else if (CodeGenOpts.DebugInfoForProfiling)
881 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
887 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
890 assert(PGOOpt->Action != PGOOptions::IRInstr &&
891 PGOOpt->Action != PGOOptions::SampleUse &&
892 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
895 PGOOpt->CSAction = PGOOptions::CSIRInstr;
898 "", PGOOptions::NoAction,
900 CodeGenOpts.DebugInfoForProfiling);
903 TM->setPGOOption(PGOOpt);
905 PipelineTuningOptions PTO;
906 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
907 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
908 PTO.LoopFusion = CodeGenOpts.FuseLoops;
911 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
912 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
913 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
914 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
917 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
918 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
919 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
921 LoopAnalysisManager LAM;
922 FunctionAnalysisManager FAM;
923 CGSCCAnalysisManager CGAM;
924 ModuleAnalysisManager MAM;
926 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
927 PassInstrumentationCallbacks PIC;
928 PrintPassOptions PrintPassOpts;
929 PrintPassOpts.Indent = DebugPassStructure;
930 PrintPassOpts.SkipAnalyses = DebugPassStructure;
931 StandardInstrumentations SI(
932 TheModule->getContext(),
933 (CodeGenOpts.DebugPassManager || DebugPassStructure),
934 CodeGenOpts.VerifyEach, PrintPassOpts);
935 SI.registerCallbacks(PIC, &MAM);
939 switch (CodeGenOpts.getAssignmentTrackingMode()) {
940 case CodeGenOptions::AssignmentTrackingOpts::Forced:
941 PB.registerPipelineStartEPCallback(
942 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
943 MPM.addPass(AssignmentTrackingPass());
946 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
949 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
950 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
951 PB.registerPipelineStartEPCallback(
952 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
954 if (
Level != OptimizationLevel::O0)
955 MPM.addPass(AssignmentTrackingPass());
959 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
964 DebugifyEachInstrumentation Debugify;
965 DebugInfoPerPass DebugInfoBeforePass;
966 if (CodeGenOpts.EnableDIPreservationVerify) {
967 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
968 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
971 Debugify.setOrigDIVerifyBugsReportFilePath(
973 Debugify.registerCallbacks(PIC, MAM);
975#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
982 if (!F.getSubprogram())
984 for (BasicBlock &BB : F)
985 for (Instruction &I : BB)
986 if (!I.getDebugLoc())
987 I.setDebugLoc(DebugLoc::getCompilerGenerated());
992 for (
const std::unique_ptr<PassPlugin> &Plugin : CI.
getPassPlugins())
993 Plugin->registerPassBuilderCallbacks(PB);
996#define HANDLE_EXTENSION(Ext) \
997 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
998#include "llvm/Support/Extension.def"
1002 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1003 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1004 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1007 PB.registerModuleAnalyses(MAM);
1008 PB.registerCGSCCAnalyses(CGAM);
1009 PB.registerFunctionAnalyses(FAM);
1010 PB.registerLoopAnalyses(LAM);
1011 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1013 ModulePassManager MPM;
1015 if (CodeGenOpts.VerifyModule)
1016 MPM.addPass(VerifierPass());
1018 if (!CodeGenOpts.DisableLLVMPasses) {
1023 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1024 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1026 if (LangOpts.ObjCAutoRefCount) {
1027 PB.registerPipelineStartEPCallback(
1028 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1029 if (
Level != OptimizationLevel::O0)
1031 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1033 PB.registerScalarOptimizerLateEPCallback(
1034 [](FunctionPassManager &FPM, OptimizationLevel
Level) {
1035 if (
Level != OptimizationLevel::O0)
1036 FPM.addPass(ObjCARCOptPass());
1046 if (IsThinLTOPostLink)
1047 PB.registerPipelineStartEPCallback(
1048 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1049 MPM.addPass(DropTypeTestsPass());
1054 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1055 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1056 OptimizationLevel
Level) {
1057 BoundsCheckingPass::Options Options;
1060 static_assert(SanitizerKind::SO_LocalBounds <=
1061 std::numeric_limits<
1062 decltype(Options.GuardKind)::value_type>
::max(),
1063 "Update type of llvm.allow.ubsan.check to represent "
1064 "SanitizerKind::SO_LocalBounds.");
1065 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1072 CodeGenOpts.SanitizeMinimalRuntime),
1076 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1079 FPM.addPass(BoundsCheckingPass(Options));
1082 if (!IsThinLTOPostLink) {
1088 PB.registerPipelineStartEPCallback(
1089 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
1090 if (
Level == OptimizationLevel::O0 &&
1091 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
1097 MPM.addPass(InferFunctionAttrsPass());
1102 if (std::optional<GCOVOptions> Options =
1104 PB.registerPipelineStartEPCallback(
1105 [
this, Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1109 if (std::optional<InstrProfOptions> Options =
1111 PB.registerPipelineStartEPCallback(
1112 [Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1113 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1119 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1120 OptimizationLevel
Level,
1121 ThinOrFullLTOPhase) {
1122 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1123 MPM.addPass(ModuleMemProfilerPass());
1127 if (CodeGenOpts.FatLTO) {
1128 MPM.addPass(PB.buildFatLTODefaultPipeline(
1129 Level, PrepareForThinLTO,
1130 PrepareForThinLTO || shouldEmitRegularLTOSummary(),
1131 CodeGenOpts.VerifyModule));
1132 }
else if (PrepareForThinLTO) {
1133 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(
Level));
1134 }
else if (PrepareForLTO) {
1135 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(
Level));
1137 MPM.addPass(PB.buildPerModuleDefaultPipeline(
Level));
1142 if (CodeGenOpts.LinkBitcodePostopt)
1143 MPM.addPass(LinkInModulesPass(BC));
1145 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1146 LangOpts.HIPStdParInterposeAlloc)
1147 MPM.addPass(HipStdParAllocationInterpositionPass());
1155 MPM.addPass(VerifierPass());
1158 CodeGenOpts.FatLTO) {
1159 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1160 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1161 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1162 CodeGenOpts.EnableSplitLTOUnit);
1169 MPM.addPass(ThinLTOBitcodeWriterPass(
1170 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1172 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1178 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1179 if (EmitLTOSummary) {
1180 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1181 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1182 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1183 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1187 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1190 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1195 if (shouldEmitUnifiedLTOModueFlag() &&
1196 !TheModule->getModuleFlag(
"UnifiedLTO"))
1197 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1204 if (PrintPipelinePasses) {
1205 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1206 auto PassName = PIC.getPassNameForClassName(ClassName);
1207 return PassName.empty() ? ClassName : PassName;
1215 PrettyStackTraceString CrashInfo(
"Optimizer");
1216 llvm::TimeTraceScope TimeScope(
"Optimizer");
1222 MPM.run(*TheModule, MAM);
1228void EmitAssemblyHelper::RunCodegenPipeline(
1229 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1230 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1240 for (
const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.
getPassPlugins()) {
1241 if (Plugin->invokePreCodeGenCallback(*TheModule, *TM, CGFT, *OS))
1251 if (CodeGenOpts.EnableNewPMCodeGen) {
1252 RunCodegenPipelineNewPM(Action, OS, DwoOS, CGFT);
1254 RunCodegenPipelineLegacy(Action, OS, DwoOS, CGFT);
1258void EmitAssemblyHelper::RunCodegenPipelineLegacy(
1259 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1260 std::unique_ptr<llvm::ToolOutputFile> &DwoOS, CodeGenFileType CGFT) {
1264 legacy::PassManager CodeGenPasses;
1267 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1269 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1270 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1271 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
1273 const llvm::TargetOptions &Options = TM->Options;
1274 CodeGenPasses.add(
new RuntimeLibraryInfoWrapper(
1275 TargetTriple, Options.ExceptionModel, Options.FloatABIType,
1276 Options.EABIVersion, Options.MCOptions.ABIName, Options.VecLib));
1278 if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
1279 DwoOS ? &DwoOS->os() :
nullptr, CGFT,
1280 !CodeGenOpts.VerifyModule)) {
1281 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1288 if (PrintPipelinePasses) {
1292 TimeCodegenPasses([&] { CodeGenPasses.run(*TheModule); });
1295void EmitAssemblyHelper::RunCodegenPipelineNewPM(
1296 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1297 std::unique_ptr<llvm::ToolOutputFile> &DwoOS, CodeGenFileType CGFT) {
1298 ModulePassManager MPM;
1299 MachineFunctionAnalysisManager MFAM;
1300 LoopAnalysisManager LAM;
1301 FunctionAnalysisManager FAM;
1302 CGSCCAnalysisManager CGAM;
1303 ModuleAnalysisManager MAM;
1304 CGPassBuilderOption Opt = getCGPassBuilderOption();
1305 Opt.DisableVerify = !CodeGenOpts.VerifyModule;
1306 MachineModuleInfo MMI(TM.get());
1307 PassInstrumentationCallbacks PIC;
1308 PipelineTuningOptions PTOptions;
1309 TargetMachine *TMPointer = TM.get();
1310 PassBuilder PB(TMPointer, PTOptions, std::nullopt, &PIC,
1312 PB.registerModuleAnalyses(MAM);
1313 PB.registerCGSCCAnalyses(CGAM);
1314 PB.registerFunctionAnalyses(FAM);
1315 PB.registerLoopAnalyses(LAM);
1316 PB.registerMachineFunctionAnalyses(MFAM);
1317 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM, &MFAM);
1319 MAM.registerPass([&] {
return MachineModuleAnalysis(MMI); });
1321 Error BuildPipelineError =
1322 TM->buildCodeGenPipeline(MPM, MAM, *OS, DwoOS ? &DwoOS->os() :
nullptr,
1323 CGFT, Opt, MMI.getContext(), &PIC);
1324 if (BuildPipelineError) {
1325 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1329 TimeCodegenPasses([&] { MPM.run(*TheModule, MAM); });
1332void EmitAssemblyHelper::TimeCodegenPasses(
1333 llvm::function_ref<
void()> RunPasses) {
1334 PrettyStackTraceString CrashInfo(
"Code generation");
1335 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1338 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1347 std::unique_ptr<raw_pwrite_stream> OS,
1348 BackendConsumer *BC) {
1352 CreateTargetMachine(RequiresCodeGen);
1354 if (RequiresCodeGen && !TM)
1357 TheModule->setDataLayout(TM->createDataLayout());
1360 cl::PrintOptionValues();
1362 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1363 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1364 RunCodegenPipeline(Action, OS, DwoOS);
1374 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1375 std::string SampleProfile, std::string ProfileRemapping,
1380 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1381 ModuleToDefinedGVSummaries;
1382 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1389 FunctionImporter::ImportIDTable ImportIDs;
1390 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1391 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1394 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1395 return std::make_unique<CachedFileStream>(std::move(OS),
1396 CGOpts.ObjectFilenameForDebug);
1399 if (CGOpts.SaveTempsFilePrefix !=
"") {
1400 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1402 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1403 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1408 Conf.CPU = TOpts.CPU;
1410 Conf.MAttrs = TOpts.Features;
1411 Conf.RelocModel = CGOpts.RelocationModel;
1412 std::optional<CodeGenOptLevel> OptLevelOrNone =
1413 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1414 assert(OptLevelOrNone &&
"Invalid optimization level!");
1415 Conf.CGOptLevel = *OptLevelOrNone;
1416 Conf.OptLevel = CGOpts.OptimizationLevel;
1418 Conf.SampleProfile = std::move(SampleProfile);
1419 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1420 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1421 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1424 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1425 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1426 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1429 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1432 if (CGOpts.hasProfileCSIRInstr()) {
1433 Conf.RunCSIRInstr =
true;
1435 }
else if (CGOpts.hasProfileCSIRUse()) {
1436 Conf.RunCSIRInstr =
false;
1437 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1440 Conf.ProfileRemapping = std::move(ProfileRemapping);
1441 Conf.DebugPassManager = CGOpts.DebugPassManager;
1442 Conf.VerifyEach = CGOpts.VerifyEach;
1443 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1444 Conf.RemarksFilename = CGOpts.OptRecordFile;
1445 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1446 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1447 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1448 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1450 Conf.LoadedPassPlugins.push_back(Plugin.get());
1453 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1458 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1459 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1464 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1465 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1478 finalizeLLVMOptimizationRemarks(M->getContext());
1479 if (
Error E = thinBackend(
1480 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1481 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1482 nullptr, Conf.CodeGenOnly, {},
1483 nullptr, CGOpts.CmdArgs)) {
1484 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1485 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1491 StringRef TDesc, llvm::Module *M,
1494 std::unique_ptr<raw_pwrite_stream> OS,
1496 llvm::TimeTraceScope TimeScope(
"Backend");
1499 std::unique_ptr<llvm::Module> EmptyModule;
1502 auto BypassSandbox = sys::sandbox::scopedDisable();
1506 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1507 if (
Error E = llvm::getModuleSummaryIndexForFile(
1510 .moveInto(CombinedIndex)) {
1511 logAllUnhandledErrors(std::move(E), errs(),
1512 "Error loading index file '" +
1520 if (CombinedIndex) {
1521 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1533 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1534 EmptyModule->setTargetTriple(M->getTargetTriple());
1535 M = EmptyModule.get();
1539 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1540 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1545 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1546 if (DLDesc != TDesc) {
1547 Diags.
Report(diag::err_data_layout_mismatch) << DLDesc << TDesc;
1555 llvm::MemoryBufferRef Buf) {
1558 llvm::embedBitcodeInModule(
1570 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1571 VFS.getBufferForFile(OffloadObject);
1572 if (ObjectOrErr.getError()) {
1573 Diags.
Report(diag::err_failed_to_open_for_embedding) << OffloadObject;
1577 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1578 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.
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.