19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Analysis/GlobalsModRef.h"
22#include "llvm/Analysis/RuntimeLibcallInfo.h"
23#include "llvm/Analysis/TargetLibraryInfo.h"
24#include "llvm/Analysis/TargetTransformInfo.h"
25#include "llvm/BinaryFormat/ELF.h"
26#include "llvm/Bitcode/BitcodeReader.h"
27#include "llvm/Bitcode/BitcodeWriter.h"
28#include "llvm/Bitcode/BitcodeWriterPass.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
30#include "llvm/CodeGen/TargetSubtargetInfo.h"
31#include "llvm/Config/llvm-config.h"
32#include "llvm/Frontend/Driver/CodeGenOptions.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DebugInfo.h"
35#include "llvm/IR/LLVMRemarkStreamer.h"
36#include "llvm/IR/LegacyPassManager.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/ModuleSummaryIndex.h"
39#include "llvm/IR/PassManager.h"
40#include "llvm/IR/Verifier.h"
41#include "llvm/IRPrinter/IRPrintingPasses.h"
42#include "llvm/LTO/LTOBackend.h"
43#include "llvm/MC/MCTargetOptions.h"
44#include "llvm/MC/TargetRegistry.h"
45#include "llvm/Object/OffloadBinary.h"
46#include "llvm/Passes/PassBuilder.h"
47#include "llvm/Passes/RunCodeGen.h"
48#include "llvm/Passes/StandardInstrumentations.h"
49#include "llvm/Plugins/PassPlugin.h"
50#include "llvm/ProfileData/InstrProfCorrelator.h"
51#include "llvm/Support/BuryPointer.h"
52#include "llvm/Support/CodeGen.h"
53#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/IOSandbox.h"
56#include "llvm/Support/MemoryBuffer.h"
57#include "llvm/Support/PrettyStackTrace.h"
58#include "llvm/Support/Program.h"
59#include "llvm/Support/TimeProfiler.h"
60#include "llvm/Support/Timer.h"
61#include "llvm/Support/ToolOutputFile.h"
62#include "llvm/Support/VirtualFileSystem.h"
63#include "llvm/Support/raw_ostream.h"
64#include "llvm/Target/TargetMachine.h"
65#include "llvm/Target/TargetOptions.h"
66#include "llvm/TargetParser/SubtargetFeature.h"
67#include "llvm/TargetParser/Triple.h"
68#include "llvm/Transforms/HipStdPar/HipStdPar.h"
69#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
70#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
71#include "llvm/Transforms/IPO/LowerTypeTests.h"
72#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
73#include "llvm/Transforms/InstCombine/InstCombine.h"
74#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
75#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
76#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
77#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
78#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
79#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
80#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
81#include "llvm/Transforms/Instrumentation/KCFI.h"
82#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
83#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
84#include "llvm/Transforms/Instrumentation/MemProfUse.h"
85#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
86#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
87#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
88#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
89#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
90#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
91#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
92#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
93#include "llvm/Transforms/ObjCARC.h"
94#include "llvm/Transforms/Scalar/EarlyCSE.h"
95#include "llvm/Transforms/Scalar/GVN.h"
96#include "llvm/Transforms/Scalar/JumpThreading.h"
97#include "llvm/Transforms/Utils/AssignGUID.h"
98#include "llvm/Transforms/Utils/Debugify.h"
99#include "llvm/Transforms/Utils/DynamicDebugging.h"
100#include "llvm/Transforms/Utils/ModuleUtils.h"
104using namespace clang;
107#define HANDLE_EXTENSION(Ext) \
108 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
109#include "llvm/Support/Extension.def"
114 "sanitizer-early-opt-ep",
115 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
120 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
122 "Function attribute to apply to cold functions as determined by PGO"),
123 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
124 "Default (no attribute)"),
125 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
126 "Mark cold functions with optsize."),
127 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
128 "Mark cold functions with minsize."),
129 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
130 "Mark cold functions with optnone.")));
132LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
142 ? llvm::driver::getDefaultProfileGenName()
144 if (CodeGenOpts.ContinuousProfileSync)
151class EmitAssemblyHelper {
152 CompilerInstance &CI;
153 DiagnosticsEngine &Diags;
154 const CodeGenOptions &CodeGenOpts;
155 const clang::TargetOptions &TargetOpts;
156 const LangOptions &LangOpts;
157 llvm::Module *TheModule;
158 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
160 std::unique_ptr<raw_pwrite_stream> OS;
164 TargetIRAnalysis getTargetIRAnalysis()
const {
166 return TM->getTargetIRAnalysis();
168 return TargetIRAnalysis();
179 void CreateTargetMachine(
bool MustCreateTM);
181 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
183 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
184 llvm::sys::fs::OF_None);
186 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
192 void RunOptimizationPipeline(
193 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
194 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
196 std::unique_ptr<raw_pwrite_stream> &OS,
197 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
198 void TimeCodegenPasses(llvm::function_ref<
void()> RunPasses);
205 bool shouldEmitRegularLTOSummary()
const {
206 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
207 TargetTriple.getVendor() != llvm::Triple::Apple;
213 bool shouldEmitUnifiedLTOModueFlag()
const {
214 return CodeGenOpts.UnifiedLTO &&
215 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
219 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
221 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
222 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
223 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
224 TheModule(M), VFS(std::move(VFS)),
225 TargetTriple(TheModule->getTargetTriple()) {}
227 ~EmitAssemblyHelper() {
228 if (CodeGenOpts.DisableFree)
229 BuryPointer(std::move(TM));
232 std::unique_ptr<TargetMachine> TM;
235 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
236 BackendConsumer *BC);
240static SanitizerCoverageOptions
242 SanitizerCoverageOptions Opts;
244 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
245 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
246 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
247 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
248 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
249 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
250 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
251 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
252 Opts.TracePCEntryExit = CGOpts.SanitizeCoverageTracePCEntryExit;
253 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
254 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
255 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
256 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
257 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
258 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
259 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
260 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
261 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
262 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
266static SanitizerBinaryMetadataOptions
268 SanitizerBinaryMetadataOptions Opts;
269 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
270 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
271 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
280 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
282 switch (
T.getObjectFormat()) {
287 return !CGOpts.DisableIntegratedAS;
289 llvm::report_fatal_error(
"ASan not implemented for GOFF");
291 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
293 case Triple::DXContainer:
295 case Triple::UnknownObjectFormat:
301static std::optional<llvm::CodeModel::Model>
303 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
304 .Case(
"tiny", llvm::CodeModel::Tiny)
305 .Case(
"small", llvm::CodeModel::Small)
306 .Case(
"kernel", llvm::CodeModel::Kernel)
307 .Case(
"medium", llvm::CodeModel::Medium)
308 .Case(
"large", llvm::CodeModel::Large)
309 .Cases({
"default",
""}, ~1u)
311 assert(CodeModel != ~0u &&
"invalid code model!");
312 if (CodeModel == ~1u)
314 return static_cast<llvm::CodeModel::Model
>(CodeModel);
319 return CodeGenFileType::ObjectFile;
321 return CodeGenFileType::Null;
324 return CodeGenFileType::AssemblyFile;
334 StringRef MainFilename,
337 return std::string{};
339 std::string FlatCmdLine;
340 raw_string_ostream OS(FlatCmdLine);
341 bool PrintedOneArg =
false;
342 if (!StringRef(Args[0]).
contains(
"-cc1")) {
343 llvm::sys::printArg(OS,
"-cc1",
true);
344 PrintedOneArg =
true;
346 for (
unsigned i = 0; i < Args.size(); i++) {
347 StringRef Arg = Args[i];
350 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
354 if (Arg.starts_with(
"-object-file-name"))
362 if (Arg == MainFilename || llvm::is_contained(InputFiles, Arg))
365 if (Arg.starts_with(
"-fmessage-length"))
369 llvm::sys::printArg(OS, Arg,
true);
370 PrintedOneArg =
true;
377 llvm::TargetOptions &Options) {
383 Options.MCOptions.BinutilsVersion =
384 llvm::MCTargetOptions::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
385 Options.UseInitArray = CodeGenOpts.UseInitArray;
386 Options.MCOptions.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
389 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
391 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
393 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
395 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
397 Options.ExceptionModel = llvm::ExceptionHandling::Emscripten;
399 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
401 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
403 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
404 .Case(
"all", llvm::BasicBlockSection::All)
405 .StartsWith(
"list=", llvm::BasicBlockSection::List)
406 .Case(
"none", llvm::BasicBlockSection::None)
407 .Default(llvm::BasicBlockSection::None);
409 if (Options.BBSections == llvm::BasicBlockSection::List) {
410 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
414 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
415 << MBOrErr.getError().message();
418 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
421 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
422 Options.EnableStaticDataPartitioning =
423 CodeGenOpts.PartitionStaticDataSections;
424 Options.FunctionSections = CodeGenOpts.FunctionSections;
425 Options.DataSections = CodeGenOpts.DataSections;
426 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
427 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
428 Options.UniqueBasicBlockSectionNames =
429 CodeGenOpts.UniqueBasicBlockSectionNames;
430 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
431 Options.TLSSize = CodeGenOpts.TLSSize;
432 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
433 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
434 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
435 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
437 Options.EmitAddrsig = CodeGenOpts.Addrsig;
438 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
439 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
440 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
441 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
442 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
443 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
446 Options.Hotpatch = CodeGenOpts.HotPatch;
447 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
448 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
450 convertDriverVectorLibraryToVectorLibrary(CodeGenOpts.getVecLib());
452 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
454 Options.SwiftAsyncFramePointer =
455 SwiftAsyncFramePointerMode::DeploymentBased;
459 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
463 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
468 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
469 Options.MCOptions.EmitCompactUnwindNonCanonical =
470 CodeGenOpts.EmitCompactUnwindNonCanonical;
471 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
472 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
473 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
474 Options.MCOptions.MCUseDwarfDirectory =
475 CodeGenOpts.NoDwarfDirectoryAsm
476 ? llvm::MCTargetOptions::DisableDwarfDirectory
477 : llvm::MCTargetOptions::EnableDwarfDirectory;
478 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
479 Options.MCOptions.MCIncrementalLinkerCompatible =
480 CodeGenOpts.IncrementalLinkerCompatible;
481 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
482 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
483 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
484 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
485 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
486 Options.MCOptions.Crel = CodeGenOpts.Crel;
487 Options.MCOptions.RelocSectionSym = CodeGenOpts.getRelocSectionSym();
488 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
489 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
490 Options.MCOptions.CompressDebugSections =
491 CodeGenOpts.getCompressDebugSections();
492 if (CodeGenOpts.OutputAsmVariant != 3)
493 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
494 Options.MCOptions.ABIName = TargetOpts.
ABI;
495 for (
const auto &Entry : HSOpts.UserEntries)
496 if (!Entry.IsFramework &&
500 Options.MCOptions.IASSearchPaths.push_back(
501 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
502 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
509 InputFiles.push_back(Input.getFile());
513 Options.MCOptions.PPCUseFullRegisterNames =
514 CodeGenOpts.PPCUseFullRegisterNames;
515 Options.MisExpect = CodeGenOpts.MisExpect;
520static std::optional<GCOVOptions>
531 Options.NoRedZone = CodeGenOpts.DisableRedZone;
534 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
538static std::optional<InstrProfOptions>
543 InstrProfOptions Options;
544 Options.NoRedZone = CodeGenOpts.DisableRedZone;
548 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
553 vfs::FileSystem &VFS) {
555 BackendArgs.push_back(
"clang");
557 BackendArgs.push_back(
"-debug-pass");
558 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
561 BackendArgs.push_back(
"-limit-float-precision");
568 if (BackendArgs.size() == 1)
570 BackendArgs.push_back(
nullptr);
574 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
579void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
582 const llvm::Triple &Triple = TheModule->getTargetTriple();
583 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
586 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
590 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
591 std::string FeaturesStr =
594 std::optional<CodeGenOptLevel> OptLevelOrNone =
595 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
596 assert(OptLevelOrNone &&
"Invalid optimization level!");
597 CodeGenOptLevel OptLevel = *OptLevelOrNone;
599 llvm::TargetOptions Options;
602 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
603 Options, RM, CM, OptLevel));
609 switch (Opts.OptimizationLevel) {
611 llvm_unreachable(
"Invalid optimization level!");
614 return OptimizationLevel::O0;
617 return OptimizationLevel::O1;
620 return OptimizationLevel::O2;
623 return OptimizationLevel::O3;
630 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
631 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
632 TargetTriple.isARM() || TargetTriple.isThumb() ||
633 TargetTriple.getArch() == llvm::Triple::hexagon)
637 PB.registerOptimizerLastEPCallback(
638 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
639 if (Level == OptimizationLevel::O0 &&
641 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
646 PB.registerPeepholeEPCallback(
647 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
648 if (Level != OptimizationLevel::O0 &&
650 FPM.addPass(KCFIPass());
657 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
658 ThinOrFullLTOPhase) {
662 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
668 MPM.addPass(SanitizerBinaryMetadataPass(
670 PB.getVirtualFileSystemPtr(),
674 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
676 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
679 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
680 CodeGenOpts.SanitizeMemoryParamRetval);
681 MPM.addPass(MemorySanitizerPass(
options));
682 if (Level != OptimizationLevel::O0) {
687 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
688 FunctionPassManager FPM;
689 FPM.addPass(EarlyCSEPass(
true ));
690 FPM.addPass(InstCombinePass());
691 FPM.addPass(JumpThreadingPass());
692 FPM.addPass(GVNPass());
693 FPM.addPass(InstCombinePass());
694 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
698 MSanPass(SanitizerKind::Memory,
false);
699 MSanPass(SanitizerKind::KernelMemory,
true);
701 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
702 MPM.addPass(ModuleThreadSanitizerPass());
703 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
707 MPM.addPass(TypeSanitizerPass());
709 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
710 MPM.addPass(NumericalStabilitySanitizerPass());
712 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
713 MPM.addPass(RealtimeSanitizerPass());
715 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
718 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
719 llvm::AsanDtorKind DestructorKind =
720 CodeGenOpts.getSanitizeAddressDtor();
721 AddressSanitizerOptions Opts;
722 Opts.CompileKernel = CompileKernel;
724 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
725 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
726 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
730 ASanPass(SanitizerKind::Address,
false);
731 ASanPass(SanitizerKind::KernelAddress,
true);
733 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
736 MPM.addPass(HWAddressSanitizerPass(
737 {CompileKernel, Recover,
738 CodeGenOpts.OptimizationLevel == 0}));
741 HWASanPass(SanitizerKind::HWAddress,
false);
742 HWASanPass(SanitizerKind::KernelHWAddress,
true);
744 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
746 PB.getVirtualFileSystemPtr()));
750 PB.registerOptimizerEarlyEPCallback(
751 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
752 ThinOrFullLTOPhase Phase) {
753 ModulePassManager NewMPM;
754 SanitizersCallback(NewMPM, Level, Phase);
755 if (!NewMPM.isEmpty()) {
757 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
758 MPM.addPass(std::move(NewMPM));
763 PB.registerOptimizerLastEPCallback(SanitizersCallback);
772 uint64_t AllowRuntimeCheckSkipHotCutoff =
777 SanitizerKind::Address | SanitizerKind::KernelAddress |
778 SanitizerKind::Thread | SanitizerKind::Memory |
779 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
780 SanitizerKind::KernelHWAddress);
783 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
785 LowerAllowSanitize) {
787 PB.registerOptimizerEarlyEPCallback(
788 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
789 ModulePassManager &MPM, OptimizationLevel Level,
790 ThinOrFullLTOPhase Phase) {
791 LowerAllowCheckPass::Options Opts;
793 if (ScaledCutoffs.has_value())
794 Opts.cutoffs = ScaledCutoffs.value();
795 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
797 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
802void EmitAssemblyHelper::RunOptimizationPipeline(
803 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
804 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
805 std::optional<PGOOptions> PGOOpt;
812 CodeGenOpts.DebugInfoForProfiling,
814 CodeGenOpts.AtomicProfileUpdate);
818 : PGOOptions::NoCSAction;
823 CodeGenOpts.DebugInfoForProfiling);
830 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
834 PGOOptions::NoAction, PGOOptions::NoCSAction,
836 else if (CodeGenOpts.PseudoProbeForProfiling)
838 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
840 CodeGenOpts.DebugInfoForProfiling,
true);
841 else if (CodeGenOpts.DebugInfoForProfiling)
843 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
849 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
852 assert(PGOOpt->Action != PGOOptions::IRInstr &&
853 PGOOpt->Action != PGOOptions::SampleUse &&
854 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
857 PGOOpt->CSAction = PGOOptions::CSIRInstr;
860 "", PGOOptions::NoAction,
862 CodeGenOpts.DebugInfoForProfiling);
865 TM->setPGOOption(PGOOpt);
867 PipelineTuningOptions PTO;
868 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
869 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
870 PTO.LoopFusion = CodeGenOpts.FuseLoops;
873 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
874 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
875 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
876 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
879 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
880 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
881 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
883 LoopAnalysisManager LAM;
884 FunctionAnalysisManager FAM;
885 CGSCCAnalysisManager CGAM;
886 ModuleAnalysisManager MAM;
888 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
889 PassInstrumentationCallbacks PIC;
890 PrintPassOptions PrintPassOpts;
891 PrintPassOpts.Indent = DebugPassStructure;
892 PrintPassOpts.SkipAnalyses = DebugPassStructure;
893 StandardInstrumentations SI(
894 TheModule->getContext(),
895 (CodeGenOpts.DebugPassManager || DebugPassStructure),
896 CodeGenOpts.VerifyEach, PrintPassOpts);
897 SI.registerCallbacks(PIC, &MAM);
901 switch (CodeGenOpts.getAssignmentTrackingMode()) {
902 case CodeGenOptions::AssignmentTrackingOpts::Forced:
903 PB.registerPipelineStartEPCallback(
904 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
905 MPM.addPass(AssignmentTrackingPass());
908 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
911 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
912 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
913 PB.registerPipelineStartEPCallback(
914 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
916 if (
Level != OptimizationLevel::O0)
917 MPM.addPass(AssignmentTrackingPass());
921 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
926 DebugifyEachInstrumentation Debugify;
927 DebugInfoPerPass DebugInfoBeforePass;
928 if (CodeGenOpts.EnableDIPreservationVerify) {
929 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
930 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
933 Debugify.setOrigDIVerifyBugsReportFilePath(
935 Debugify.registerCallbacks(PIC, MAM);
937#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
944 if (!F.getSubprogram())
946 for (BasicBlock &BB : F)
947 for (Instruction &I : BB)
948 if (!I.getDebugLoc())
949 I.setDebugLoc(DebugLoc::getCompilerGenerated());
954 for (
const std::unique_ptr<PassPlugin> &Plugin : CI.
getPassPlugins())
955 Plugin->registerPassBuilderCallbacks(PB);
958#define HANDLE_EXTENSION(Ext) \
959 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
960#include "llvm/Support/Extension.def"
964 std::unique_ptr<TargetLibraryInfoImpl> TLII(
965 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
966 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
969 PB.registerModuleAnalyses(MAM);
970 PB.registerCGSCCAnalyses(CGAM);
971 PB.registerFunctionAnalyses(FAM);
972 PB.registerLoopAnalyses(LAM);
973 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
975 ModulePassManager MPM;
977 if (CodeGenOpts.VerifyModule)
978 MPM.addPass(VerifierPass());
980 if (!CodeGenOpts.DisableLLVMPasses) {
985 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
986 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
988 if (LangOpts.ObjCAutoRefCount) {
989 PB.registerPipelineStartEPCallback(
990 [](ModulePassManager &MPM, OptimizationLevel
Level) {
991 if (
Level != OptimizationLevel::O0)
993 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
995 PB.registerScalarOptimizerLateEPCallback(
996 [](FunctionPassManager &FPM, OptimizationLevel
Level) {
997 if (
Level != OptimizationLevel::O0)
998 FPM.addPass(ObjCARCOptPass());
1008 if (IsThinLTOPostLink)
1009 PB.registerPipelineStartEPCallback(
1010 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1011 MPM.addPass(DropTypeTestsPass());
1016 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1017 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1018 OptimizationLevel
Level) {
1019 BoundsCheckingPass::Options Options;
1022 static_assert(SanitizerKind::SO_LocalBounds <=
1023 std::numeric_limits<
1024 decltype(Options.GuardKind)::value_type>
::max(),
1025 "Update type of llvm.allow.ubsan.check to represent "
1026 "SanitizerKind::SO_LocalBounds.");
1027 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1034 CodeGenOpts.SanitizeMinimalRuntime),
1038 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1041 FPM.addPass(BoundsCheckingPass(Options));
1044 if (!IsThinLTOPostLink) {
1050 PB.registerPipelineStartEPCallback(
1051 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
1052 if (
Level == OptimizationLevel::O0 &&
1053 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
1059 MPM.addPass(InferFunctionAttrsPass());
1064 if (std::optional<GCOVOptions> Options =
1066 PB.registerPipelineStartEPCallback(
1067 [
this, Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1071 if (std::optional<InstrProfOptions> Options =
1073 PB.registerPipelineStartEPCallback(
1074 [Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1075 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1081 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1082 OptimizationLevel
Level,
1083 ThinOrFullLTOPhase) {
1084 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1085 MPM.addPass(ModuleMemProfilerPass());
1089 if (CodeGenOpts.FatLTO) {
1090 MPM.addPass(PB.buildFatLTODefaultPipeline(
1091 Level, PrepareForThinLTO,
1092 PrepareForThinLTO || shouldEmitRegularLTOSummary(),
1093 CodeGenOpts.VerifyModule));
1094 }
else if (PrepareForThinLTO) {
1095 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(
Level));
1096 }
else if (PrepareForLTO) {
1097 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(
Level));
1099 MPM.addPass(PB.buildPerModuleDefaultPipeline(
Level));
1104 if (CodeGenOpts.LinkBitcodePostopt) {
1105 MPM.addPass(LinkInModulesPass(BC));
1106 MPM.addPass(AssignGUIDPass());
1109 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1110 LangOpts.HIPStdParInterposeAlloc)
1111 MPM.addPass(HipStdParAllocationInterpositionPass());
1119 MPM.addPass(VerifierPass());
1122 CodeGenOpts.FatLTO) {
1123 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1124 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1125 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1126 CodeGenOpts.EnableSplitLTOUnit);
1133 MPM.addPass(ThinLTOBitcodeWriterPass(
1134 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1136 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1143 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1144 if (EmitLTOSummary) {
1145 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1146 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1147 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1148 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1152 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1155 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1161 if (shouldEmitUnifiedLTOModueFlag() &&
1162 !TheModule->getModuleFlag(
"UnifiedLTO"))
1163 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1170 if (PrintPipelinePasses) {
1171 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1172 auto PassName = PIC.getPassNameForClassName(ClassName);
1173 return PassName.empty() ? ClassName : PassName;
1181 PrettyStackTraceString CrashInfo(
"Optimizer");
1182 llvm::TimeTraceScope TimeScope(
"Optimizer");
1188 MPM.run(*TheModule, MAM);
1194void EmitAssemblyHelper::RunCodegenPipeline(
1195 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1196 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1206 for (
const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.
getPassPlugins()) {
1207 if (Plugin->invokePreCodeGenCallback(*TheModule, *TM, CGFT, *OS))
1217 TimeCodegenPasses([&]() {
1218 Error CodeGenError = runCodeGenPipeline(
1219 *TM, *TheModule, *OS, DwoOS, CGFT, PrintPipelinePasses.has_value(),
1220 !CodeGenOpts.VerifyModule,
false,
1223 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1227void EmitAssemblyHelper::TimeCodegenPasses(
1228 llvm::function_ref<
void()> RunPasses) {
1229 PrettyStackTraceString CrashInfo(
"Code generation");
1230 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1233 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1242 std::unique_ptr<raw_pwrite_stream> OS,
1243 BackendConsumer *BC) {
1247 CreateTargetMachine(RequiresCodeGen);
1249 if (RequiresCodeGen && !TM)
1251 if (TM && TheModule->getDataLayout().isDefault())
1252 TheModule->setDataLayout(TheModule->getTargetTriple().computeDataLayout(
1253 TM->getTargetABIName(*TheModule)));
1256 cl::PrintOptionValues();
1258 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1259 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1260 RunCodegenPipeline(Action, OS, DwoOS);
1270 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1271 std::string SampleProfile, std::string ProfileRemapping,
1276 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1277 ModuleToDefinedGVSummaries;
1278 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1285 FunctionImporter::ImportIDTable ImportIDs;
1286 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1287 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1290 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1291 return std::make_unique<CachedFileStream>(std::move(OS),
1292 CGOpts.ObjectFilenameForDebug);
1295 if (CGOpts.SaveTempsFilePrefix !=
"") {
1296 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1298 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1299 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1304 Conf.CPU = TOpts.CPU;
1306 Conf.MAttrs = TOpts.Features;
1307 Conf.RelocModel = CGOpts.RelocationModel;
1308 std::optional<CodeGenOptLevel> OptLevelOrNone =
1309 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1310 assert(OptLevelOrNone &&
"Invalid optimization level!");
1311 Conf.CGOptLevel = *OptLevelOrNone;
1312 Conf.OptLevel = CGOpts.OptimizationLevel;
1314 Conf.SampleProfile = std::move(SampleProfile);
1315 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1316 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1317 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1320 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1321 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1322 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1325 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1328 if (CGOpts.hasProfileCSIRInstr()) {
1329 Conf.RunCSIRInstr =
true;
1331 }
else if (CGOpts.hasProfileCSIRUse()) {
1332 Conf.RunCSIRInstr =
false;
1333 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1336 Conf.ProfileRemapping = std::move(ProfileRemapping);
1337 Conf.DebugPassManager = CGOpts.DebugPassManager;
1338 Conf.VerifyEach = CGOpts.VerifyEach;
1339 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1340 Conf.RemarksFilename = CGOpts.OptRecordFile;
1341 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1342 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1343 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1344 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1346 Conf.LoadedPassPlugins.push_back(Plugin.get());
1349 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1354 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1355 M->renumberMetadataForAssembly();
1356 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1361 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1362 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1375 finalizeLLVMOptimizationRemarks(M->getContext());
1376 if (
Error E = thinBackend(
1377 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1378 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1379 nullptr, Conf.CodeGenOnly, {},
1380 nullptr, CGOpts.CmdArgs)) {
1381 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1382 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1391 auto SaveModule = [&](StringRef Name, llvm::Module &M) {
1397 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
1401 errs() <<
"failed to open " << Path <<
": " << EC.message() <<
'\n';
1405 M.print(OS,
nullptr);
1409 std::string PromotionSuffix;
1416 for (
auto *CU : M->debug_compile_units()) {
1417 if (CU->getDirectory().size() > 0)
1418 Hash.update(CU->getDirectory());
1420 Hash.update(CU->getFilename());
1425 PromotionSuffix =
".dyndbg." + utohexstr(
Result.low());
1428 SaveModule(
"dyndbg.0.input", *M);
1430 auto UnoptM = prepareForDynamicDebugging(M, PromotionSuffix);
1431 SaveModule(
"dyndbg.1.inner", *UnoptM);
1433 if (!CGOpts.DiscardDynamicDebuggingDebugModule) {
1435 UnoptOpts.OptimizationLevel = 0;
1436 UnoptOpts.OptimizeSize = 0;
1437 EmitAssemblyHelper AsmHelper(CI, UnoptOpts, UnoptM.get(), VFS);
1441 std::unique_ptr<llvm::raw_pwrite_stream> UnoptOS =
1442 std::make_unique<llvm::raw_svector_ostream>(UnoptBuf);
1449 assert(!UnoptBuf.empty() &&
"Expected emitAssembly to fill UnoptBuf");
1452 StringRef SR(UnoptBuf.data(), UnoptBuf.size());
1453 std::unique_ptr<MemoryBuffer> Buf =
1454 MemoryBuffer::getMemBuffer(SR,
"",
false);
1456 GlobalVariable *EmbeddedGV =
1457 llvm::embedBufferInModule(*M, *Buf,
".debug_llvm_dyndbg", Align(8),
1460 auto &
C = M->getContext();
1461 auto getU32Metadata = [&
C](
unsigned Val) {
1462 return ConstantAsMetadata::get(ConstantInt::get(
C, APInt(32, Val)));
1464 EmbeddedGV->addMetadata(
1465 LLVMContext::MD_elf_section_properties,
1466 *MDTuple::get(
C, { getU32Metadata(ELF::SHT_LLVM_DYNDBG_ELF),
1467 getU32Metadata(0)}));
1469 SaveModule(
"dyndbg.2.outer", *M);
1475 std::unique_ptr<raw_pwrite_stream> OS,
1477 llvm::TimeTraceScope TimeScope(
"Backend");
1480 std::unique_ptr<llvm::Module> EmptyModule;
1483 auto BypassSandbox = sys::sandbox::scopedDisable();
1487 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1488 if (
Error E = llvm::getModuleSummaryIndexForFile(
1491 .moveInto(CombinedIndex)) {
1492 logAllUnhandledErrors(std::move(E), errs(),
1493 "Error loading index file '" +
1501 if (CombinedIndex) {
1502 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1514 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1515 EmptyModule->setTargetTriple(M->getTargetTriple());
1516 M = EmptyModule.get();
1520 bool EnableDynamicDebugging = CGOpts.DynamicDebugging;
1521 if (EnableDynamicDebugging) {
1525 const llvm::Target *TheTarget =
1526 TargetRegistry::lookupTarget(M->getTargetTriple(),
Error);
1527 if (!TheTarget && !CGOpts.DiscardDynamicDebuggingDebugModule) {
1528 Diags.
Report(diag::warn_dyndbg_unable_to_create_target) <<
Error;
1529 EnableDynamicDebugging =
false;
1536 if (CGOpts.getProfileInstr() != driver::ProfileInstrKind::ProfileNone) {
1537 Diags.
Report(diag::err_dyndbg_no_instrumentation);
1538 EnableDynamicDebugging =
false;
1541 if (EnableDynamicDebugging)
1544 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1545 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1551 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1552 std::string TDesc = M->getTargetTriple().computeDataLayout(
1553 AsmHelper.TM->getTargetABIName(*M));
1554 if (DLDesc != TDesc)
1555 Diags.
Report(diag::err_data_layout_mismatch) << DLDesc << TDesc;
1562 llvm::MemoryBufferRef Buf) {
1565 llvm::embedBitcodeInModule(
1577 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1578 VFS.getBufferForFile(OffloadObject);
1579 if (ObjectOrErr.getError()) {
1580 Diags.
Report(diag::err_failed_to_open_for_embedding) << OffloadObject;
1584 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1585 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 void createAndEmbedModuleForDynamicDebugging(CompilerInstance &CI, CodeGenOptions &CGOpts, llvm::Module *M, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, BackendConsumer *BC)
static SanitizerBinaryMetadataOptions getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts)
static std::optional< GCOVOptions > getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool initTargetOptions(const CompilerInstance &CI, DiagnosticsEngine &Diags, llvm::TargetOptions &Options)
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts, vfs::FileSystem &VFS)
static 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.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
This file provides a pass to link in Modules from a provided BackendConsumer.
static 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 hasEmscriptenExceptions() const
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 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
std::string remapDebugPathPrefix(StringRef Path) const
Remap specified path prefix using provided DebugPrefixMap map.
SanitizerMaskCutoffs SanitizeSkipHotCutoffs
Set of thresholds in a range [0.0, 1.0]: the top hottest code responsible for the given fraction of P...
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
std::optional< double > AllowRuntimeCheckSkipHotCutoff
std::vector< std::string > CommandLineArgs
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.
std::string SaveDynDbgTempsFilePrefix
Prefix to use for -save-dynamic-debugging-temps output.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
llvm::TimerGroup & getTimerGroup() const
llvm::Timer & getFrontendTimer() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetOptions & getTargetOpts()
FrontendOptions & getFrontendOpts()
HeaderSearchOptions & getHeaderSearchOpts()
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
llvm::ArrayRef< std::unique_ptr< llvm::PassPlugin > > getPassPlugins() const
CodeGenOptions & getCodeGenOpts()
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
SanitizerSet Sanitize
Set of enabled sanitizers.
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
std::optional< std::vector< unsigned > > getAllScaled(unsigned ScalingFactor) const
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string ABI
If given, the name of the target ABI to use.
std::string CPU
If given, the name of the target CPU to generate code for.
@ Angled
Paths for '#include <>' added by '-I'.
@ System
Like Angled, but marks system directories.
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
Top level wrappers for InstallAPI frontend operations.
@ Default
Set to the current date and time.
const FunctionProtoType * T
llvm::cl::opt< bool > ClSanitizeGuardChecks
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
@ Backend_EmitAssembly
Emit native assembly files.
@ Backend_EmitLL
Emit human-readable LLVM assembly.
@ Backend_EmitBC
Emit LLVM bitcode files.
@ Backend_EmitObj
Emit native object files.
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
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::desc("Insert sanitizers on OptimizerEarlyEP."))
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t __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.