[clang] [lld] [llvm] [CodeGen] Declare most CommandFlags options in TableGen (PR #242159)
Fangrui Song via cfe-commits
cfe-commits at lists.llvm.org
Thu Nov 12 20:03:38 PST 2026
https://github.com/MaskRay created https://github.com/llvm/llvm-project/pull/242159
Move the 34 RegisterCodeGenFlags options that only
codegen::getTargetOptions and codegen::setFunctionAttributes read into a
private CodeGenToolOptions struct, which codegen::getToolOptions adds to
the tool options, and remove their getters from CommandFlags.h.
getNumOccurrences checks become optional fields.
Like other tool options, these are listed only by -help-hidden.
clang-linker-wrapper, which does not pass the tool options, now rejects
them in -mllvm and --offload-opt.
LLM-aided
>From 6b9d40afb5dc8e8ddb66cb25d765ce31fe7cab2d Mon Sep 17 00:00:00 2001
From: Fangrui Song <i at maskray.me>
Date: Thu, 12 Nov 2026 11:00:27 -0800
Subject: [PATCH] [CodeGen] Declare most CommandFlags options in TableGen
Move the 34 RegisterCodeGenFlags options that only
codegen::getTargetOptions and codegen::setFunctionAttributes read into a
private CodeGenToolOptions struct, which codegen::getToolOptions adds to
the tool options, and remove their getters from CommandFlags.h.
getNumOccurrences checks become optional fields.
Like other tool options, these are listed only by -help-hidden.
clang-linker-wrapper, which does not pass the tool options, now rejects
them in -mllvm and --offload-opt.
LLM-aided
---
.../clang-fuzzer/handle-llvm/handle_llvm.cpp | 22 +-
.../ClangNVLinkWrapper.cpp | 2 +-
lld/COFF/LTO.cpp | 4 +-
lld/Common/TargetOptionsCommandFlags.cpp | 20 +-
lld/ELF/LTO.cpp | 8 +-
lld/MachO/LTO.cpp | 6 +-
.../lld/Common/TargetOptionsCommandFlags.h | 11 +-
lld/wasm/LTO.cpp | 6 +-
llvm/include/llvm/CodeGen/CommandFlags.h | 136 ++---
llvm/lib/CodeGen/CMakeLists.txt | 4 +
llvm/lib/CodeGen/CodeGenToolOptions.td | 93 ++++
llvm/lib/CodeGen/CommandFlags.cpp | 474 ++++--------------
llvm/lib/LTO/LTOCodeGenerator.cpp | 2 +-
llvm/lib/LTO/ThinLTOCodeGenerator.cpp | 14 +-
llvm/tools/gold/gold-plugin.cpp | 8 +-
llvm/tools/llc/lib/NewPMDriver.cpp | 3 +-
llvm/tools/llc/lib/llcdriver.cpp | 59 ++-
llvm/tools/lli/lli.cpp | 26 +-
llvm/tools/llvm-lto/llvm-lto.cpp | 11 +-
llvm/tools/llvm-lto2/llvm-lto2.cpp | 10 +-
llvm/tools/lto/lto.cpp | 2 +-
llvm/tools/opt/optdriver.cpp | 30 +-
.../gn/secondary/llvm/lib/CodeGen/BUILD.gn | 6 +
.../llvm-project-overlay/llvm/BUILD.bazel | 10 +
24 files changed, 391 insertions(+), 576 deletions(-)
create mode 100644 llvm/lib/CodeGen/CodeGenToolOptions.td
diff --git a/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp b/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
index 10b973fa8308f..bf9dc2d04f641 100644
--- a/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
+++ b/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
@@ -124,20 +124,22 @@ static std::string OptLLVM(const std::string &IR, CodeGenOptLevel OLvl) {
const TargetOptions Options =
codegen::getTargetOptions(Context.getLibraryOptions(), ModuleTriple);
std::string E;
- const Target *TheTarget =
- TargetRegistry::lookupTarget(codegen::getMArch(), ModuleTriple, E);
+ const Target *TheTarget = TargetRegistry::lookupTarget(
+ codegen::getMArch(Context.getLibraryOptions()), ModuleTriple, E);
if (!TheTarget)
ErrorAndExit(E);
std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
- M->getTargetTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),
- Options, codegen::getExplicitRelocModel(),
- codegen::getExplicitCodeModel(), OLvl));
+ M->getTargetTriple(), codegen::getCPUStr(Context.getLibraryOptions()),
+ codegen::getFeaturesStr(Context.getLibraryOptions()), Options,
+ codegen::getExplicitRelocModel(Context.getLibraryOptions()),
+ codegen::getExplicitCodeModel(Context.getLibraryOptions()), OLvl));
if (!TM)
ErrorAndExit("Could not create target machine");
- codegen::setFunctionAttributes(*M, codegen::getCPUStr(),
- codegen::getFeaturesStr());
+ codegen::setFunctionAttributes(
+ *M, codegen::getCPUStr(Context.getLibraryOptions()),
+ codegen::getFeaturesStr(Context.getLibraryOptions()));
// Add a pass that writes the optimized IR to an output stream
std::string outString;
@@ -171,9 +173,9 @@ static void CreateAndRunJITFunc(const std::string &IR, CodeGenOptLevel OLvl) {
Triple ModuleTriple(M->getTargetTriple());
EngineBuilder builder(std::move(M));
- builder.setMArch(codegen::getMArch());
- builder.setMCPU(codegen::getCPUStr());
- builder.setMAttrs(codegen::getFeatureList());
+ builder.setMArch(codegen::getMArch(Context.getLibraryOptions()));
+ builder.setMCPU(codegen::getCPUStr(Context.getLibraryOptions()));
+ builder.setMAttrs(codegen::getFeatureList(Context.getLibraryOptions()));
builder.setErrorStr(&ErrorMsg);
builder.setEngineKind(EngineKind::JIT);
builder.setMCJITMemoryManager(std::make_unique<SectionMemoryManager>());
diff --git a/clang/tools/clang-nvlink-wrapper/ClangNVLinkWrapper.cpp b/clang/tools/clang-nvlink-wrapper/ClangNVLinkWrapper.cpp
index 9229783a3dd23..2451612e0ddb0 100644
--- a/clang/tools/clang-nvlink-wrapper/ClangNVLinkWrapper.cpp
+++ b/clang/tools/clang-nvlink-wrapper/ClangNVLinkWrapper.cpp
@@ -406,7 +406,7 @@ createLTO(const cl::LibraryOptionsContext &LibraryOptions,
Args.hasArg(OPT_opt_remarks_with_hotness) || RemarksWithHotness;
Conf.RemarksHotnessThreshold = RemarksHotnessThreshold;
- Conf.MAttrs = llvm::codegen::getMAttrs();
+ Conf.MAttrs = llvm::codegen::getMAttrs(LibraryOptions);
std::optional<CodeGenOptLevel> CGOptLevelOrNone =
CodeGenOpt::parseLevel(Args.getLastArgValue(OPT_O, "2")[0]);
assert(CGOptLevelOrNone && "Invalid optimization level");
diff --git a/lld/COFF/LTO.cpp b/lld/COFF/LTO.cpp
index 03180209111af..d2519a51efe63 100644
--- a/lld/COFF/LTO.cpp
+++ b/lld/COFF/LTO.cpp
@@ -84,8 +84,8 @@ lto::Config BitcodeCompiler::createConfig() {
c.DiagHandler = diagnosticHandler;
c.DwoDir = ctx.config.dwoDir.str();
c.OptLevel = ctx.config.ltoo;
- c.CPU = getCPUStr();
- c.MAttrs = getMAttrs();
+ c.CPU = getCPUStr(ctx.config.libraryOptions);
+ c.MAttrs = getMAttrs(ctx.config.libraryOptions);
std::optional<CodeGenOptLevel> optLevelOrNone = CodeGenOpt::getLevel(
ctx.config.ltoCgo.value_or(args::getCGOptLevel(ctx.config.ltoo)));
assert(optLevelOrNone && "Invalid optimization level!");
diff --git a/lld/Common/TargetOptionsCommandFlags.cpp b/lld/Common/TargetOptionsCommandFlags.cpp
index c9adaf115e2b7..8e8552301d2f0 100644
--- a/lld/Common/TargetOptionsCommandFlags.cpp
+++ b/lld/Common/TargetOptionsCommandFlags.cpp
@@ -21,14 +21,22 @@ llvm::ArrayRef<const llvm::cl::LibraryOptions *> lld::getToolOptions() {
return llvm::codegen::getToolOptions();
}
-std::optional<llvm::Reloc::Model> lld::getRelocModelFromCMModel() {
- return llvm::codegen::getExplicitRelocModel();
+std::optional<llvm::Reloc::Model> lld::getRelocModelFromCMModel(
+ const llvm::cl::LibraryOptionsContext &libraryOptions) {
+ return llvm::codegen::getExplicitRelocModel(libraryOptions);
}
-std::optional<llvm::CodeModel::Model> lld::getCodeModelFromCMModel() {
- return llvm::codegen::getExplicitCodeModel();
+std::optional<llvm::CodeModel::Model> lld::getCodeModelFromCMModel(
+ const llvm::cl::LibraryOptionsContext &libraryOptions) {
+ return llvm::codegen::getExplicitCodeModel(libraryOptions);
}
-std::string lld::getCPUStr() { return llvm::codegen::getCPUStr(); }
+std::string
+lld::getCPUStr(const llvm::cl::LibraryOptionsContext &libraryOptions) {
+ return llvm::codegen::getCPUStr(libraryOptions);
+}
-std::vector<std::string> lld::getMAttrs() { return llvm::codegen::getMAttrs(); }
+std::vector<std::string>
+lld::getMAttrs(const llvm::cl::LibraryOptionsContext &libraryOptions) {
+ return llvm::codegen::getMAttrs(libraryOptions);
+}
diff --git a/lld/ELF/LTO.cpp b/lld/ELF/LTO.cpp
index 84bae5325afeb..63a5c6130e8e0 100644
--- a/lld/ELF/LTO.cpp
+++ b/lld/ELF/LTO.cpp
@@ -100,7 +100,7 @@ static lto::Config createConfig(Ctx &ctx) {
c.Options.UniqueBasicBlockSectionNames =
ctx.arg.ltoUniqueBasicBlockSectionNames;
- if (auto relocModel = getRelocModelFromCMModel())
+ if (auto relocModel = getRelocModelFromCMModel(ctx.arg.libraryOptions))
c.RelocModel = *relocModel;
else if (ctx.arg.relocatable)
c.RelocModel = std::nullopt;
@@ -109,12 +109,12 @@ static lto::Config createConfig(Ctx &ctx) {
else
c.RelocModel = Reloc::Static;
- c.CodeModel = getCodeModelFromCMModel();
+ c.CodeModel = getCodeModelFromCMModel(ctx.arg.libraryOptions);
c.DisableVerify = ctx.arg.disableVerify;
c.DiagHandler = diagnosticHandler;
c.OptLevel = ctx.arg.ltoo;
- c.CPU = getCPUStr();
- c.MAttrs = getMAttrs();
+ c.CPU = getCPUStr(ctx.arg.libraryOptions);
+ c.MAttrs = getMAttrs(ctx.arg.libraryOptions);
c.CGOptLevel = ctx.arg.ltoCgo;
c.PTO.LoopVectorization = c.OptLevel > 1;
diff --git a/lld/MachO/LTO.cpp b/lld/MachO/LTO.cpp
index ccdd1a39ffb53..3bb10040f5dee 100644
--- a/lld/MachO/LTO.cpp
+++ b/lld/MachO/LTO.cpp
@@ -47,9 +47,9 @@ static lto::Config createConfig() {
for (StringRef pluginFn : config->passPlugins)
c.PassPluginFilenames.push_back(std::string(pluginFn));
c.OptPipeline = std::string(config->ltoNewPmPasses);
- c.CodeModel = getCodeModelFromCMModel();
- c.CPU = getCPUStr();
- c.MAttrs = getMAttrs();
+ c.CodeModel = getCodeModelFromCMModel(config->libraryOptions);
+ c.CPU = getCPUStr(config->libraryOptions);
+ c.MAttrs = getMAttrs(config->libraryOptions);
c.DiagHandler = diagnosticHandler;
c.AlwaysEmitRegularLTOObj = !config->ltoObjPath.empty();
diff --git a/lld/include/lld/Common/TargetOptionsCommandFlags.h b/lld/include/lld/Common/TargetOptionsCommandFlags.h
index fc1db20874c1f..2cf913661c0f4 100644
--- a/lld/include/lld/Common/TargetOptionsCommandFlags.h
+++ b/lld/include/lld/Common/TargetOptionsCommandFlags.h
@@ -26,10 +26,13 @@ namespace lld {
llvm::TargetOptions
getTargetOptions(const llvm::cl::LibraryOptionsContext &libraryOptions);
llvm::ArrayRef<const llvm::cl::LibraryOptions *> getToolOptions();
-std::optional<llvm::Reloc::Model> getRelocModelFromCMModel();
-std::optional<llvm::CodeModel::Model> getCodeModelFromCMModel();
-std::string getCPUStr();
-std::vector<std::string> getMAttrs();
+std::optional<llvm::Reloc::Model>
+getRelocModelFromCMModel(const llvm::cl::LibraryOptionsContext &libraryOptions);
+std::optional<llvm::CodeModel::Model>
+getCodeModelFromCMModel(const llvm::cl::LibraryOptionsContext &libraryOptions);
+std::string getCPUStr(const llvm::cl::LibraryOptionsContext &libraryOptions);
+std::vector<std::string>
+getMAttrs(const llvm::cl::LibraryOptionsContext &libraryOptions);
}
#endif
diff --git a/lld/wasm/LTO.cpp b/lld/wasm/LTO.cpp
index 1a88c175ac939..67e462b358b4f 100644
--- a/lld/wasm/LTO.cpp
+++ b/lld/wasm/LTO.cpp
@@ -52,8 +52,8 @@ static lto::Config createConfig() {
c.DisableVerify = ctx.arg.disableVerify;
c.DiagHandler = diagnosticHandler;
c.OptLevel = ctx.arg.ltoo;
- c.CPU = getCPUStr();
- c.MAttrs = getMAttrs();
+ c.CPU = getCPUStr(ctx.arg.libraryOptions);
+ c.MAttrs = getMAttrs(ctx.arg.libraryOptions);
// If shared memory is enabled, ensure the TargetMachine backend is
// instantiated with atomics and bulk-memory features so that empty
@@ -71,7 +71,7 @@ static lto::Config createConfig() {
c.DebugPassManager = ctx.arg.ltoDebugPassManager;
c.AlwaysEmitRegularLTOObj = !ctx.arg.ltoObjPath.empty();
- if (auto relocModel = getRelocModelFromCMModel())
+ if (auto relocModel = getRelocModelFromCMModel(ctx.arg.libraryOptions))
c.RelocModel = *relocModel;
else if (ctx.arg.relocatable)
c.RelocModel = std::nullopt;
diff --git a/llvm/include/llvm/CodeGen/CommandFlags.h b/llvm/include/llvm/CodeGen/CommandFlags.h
index 332905197b810..f2a3c05e87dd2 100644
--- a/llvm/include/llvm/CodeGen/CommandFlags.h
+++ b/llvm/include/llvm/CodeGen/CommandFlags.h
@@ -16,7 +16,6 @@
#define LLVM_CODEGEN_COMMANDFLAGS_H
#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/FloatingPointMode.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Target/TargetOptions.h"
@@ -38,107 +37,49 @@ class LibraryOptions;
namespace codegen {
-LLVM_ABI std::string getMArch();
+LLVM_ABI std::string getMArch(const cl::LibraryOptionsContext &C);
-LLVM_ABI std::string getMCPU();
+LLVM_ABI std::string getMCPU(const cl::LibraryOptionsContext &C);
-LLVM_ABI std::string getMTune();
+LLVM_ABI std::string getMTune(const cl::LibraryOptionsContext &C);
-LLVM_ABI std::vector<std::string> getMAttrs();
+LLVM_ABI std::vector<std::string> getMAttrs(const cl::LibraryOptionsContext &C);
-LLVM_ABI Reloc::Model getRelocModel();
-LLVM_ABI std::optional<Reloc::Model> getExplicitRelocModel();
+LLVM_ABI Reloc::Model getRelocModel(const cl::LibraryOptionsContext &C);
+LLVM_ABI std::optional<Reloc::Model>
+getExplicitRelocModel(const cl::LibraryOptionsContext &C);
-LLVM_ABI CodeModel::Model getCodeModel();
-LLVM_ABI std::optional<CodeModel::Model> getExplicitCodeModel();
+LLVM_ABI CodeModel::Model getCodeModel(const cl::LibraryOptionsContext &C);
+LLVM_ABI std::optional<CodeModel::Model>
+getExplicitCodeModel(const cl::LibraryOptionsContext &C);
-LLVM_ABI uint64_t getLargeDataThreshold();
-LLVM_ABI std::optional<uint64_t> getExplicitLargeDataThreshold();
+LLVM_ABI uint64_t getLargeDataThreshold(const cl::LibraryOptionsContext &C);
+LLVM_ABI std::optional<uint64_t>
+getExplicitLargeDataThreshold(const cl::LibraryOptionsContext &C);
-LLVM_ABI llvm::ExceptionHandling getExceptionModel();
+LLVM_ABI std::optional<CodeGenFileType>
+getExplicitFileType(const cl::LibraryOptionsContext &C);
-LLVM_ABI std::optional<CodeGenFileType> getExplicitFileType();
+LLVM_ABI CodeGenFileType getFileType(const cl::LibraryOptionsContext &C);
-LLVM_ABI CodeGenFileType getFileType();
+LLVM_ABI llvm::FloatABI::ABIType
+getFloatABIForCalls(const cl::LibraryOptionsContext &C);
-LLVM_ABI FramePointerKind getFramePointerUsage();
+LLVM_ABI bool getDataSections(const cl::LibraryOptionsContext &C);
+LLVM_ABI std::optional<bool>
+getExplicitDataSections(const cl::LibraryOptionsContext &C);
-LLVM_ABI DenormalMode::DenormalModeKind getDenormalFPMath();
-LLVM_ABI DenormalMode::DenormalModeKind getDenormalFP32Math();
+LLVM_ABI bool getFunctionSections(const cl::LibraryOptionsContext &C);
+LLVM_ABI std::optional<bool>
+getExplicitFunctionSections(const cl::LibraryOptionsContext &C);
-LLVM_ABI llvm::FloatABI::ABIType getFloatABIForCalls();
-
-LLVM_ABI SwiftAsyncFramePointerMode getSwiftAsyncFramePointer();
-
-LLVM_ABI bool getDontPlaceZerosInBSS();
-
-LLVM_ABI bool getEnableGuaranteedTailCallOpt();
-
-LLVM_ABI bool getDisableTailCalls();
-
-LLVM_ABI bool getStackSymbolOrdering();
-
-LLVM_ABI bool getStackRealign();
-
-LLVM_ABI std::string getTrapFuncName();
-
-LLVM_ABI bool getUseCtors();
-
-LLVM_ABI bool getDataSections();
-LLVM_ABI std::optional<bool> getExplicitDataSections();
-
-LLVM_ABI bool getFunctionSections();
-LLVM_ABI std::optional<bool> getExplicitFunctionSections();
-
-LLVM_ABI bool getIgnoreXCOFFVisibility();
-
-LLVM_ABI bool getXCOFFTracebackTable();
-
-LLVM_ABI std::string getBBSections();
-
-LLVM_ABI unsigned getTLSSize();
-
-LLVM_ABI bool getEmulatedTLS();
-LLVM_ABI std::optional<bool> getExplicitEmulatedTLS();
-
-LLVM_ABI bool getEnableTLSDESC();
-LLVM_ABI std::optional<bool> getExplicitEnableTLSDESC();
-
-LLVM_ABI bool getUniqueSectionNames();
-
-LLVM_ABI bool getUniqueBasicBlockSectionNames();
-
-LLVM_ABI bool getSeparateNamedSections();
-
-LLVM_ABI llvm::VectorLibrary getVectorLibrary();
-
-LLVM_ABI bool getEnableStackSizeSection();
-
-LLVM_ABI bool getEnableAddrsig();
-
-LLVM_ABI bool getEnableCallGraphSection();
-
-LLVM_ABI bool getEmitCallSiteInfo();
-
-LLVM_ABI bool getEnableStaticDataPartitioning();
-
-LLVM_ABI bool getEnableDebugEntryValues();
-
-LLVM_ABI bool getForceDwarfFrameSection();
-
-LLVM_ABI bool getXRayFunctionIndex();
-
-LLVM_ABI bool getDebugStrictDwarf();
-
-LLVM_ABI unsigned getAlignLoops();
-
-LLVM_ABI bool getJMCInstrument();
-
-LLVM_ABI bool getXCOFFReadOnlyPointers();
+LLVM_ABI bool getEmulatedTLS(const cl::LibraryOptionsContext &C);
+LLVM_ABI std::optional<bool>
+getExplicitEmulatedTLS(const cl::LibraryOptionsContext &C);
enum SaveStatsMode { None, Cwd, Obj };
-LLVM_ABI SaveStatsMode getSaveStats();
+LLVM_ABI SaveStatsMode getSaveStats(const cl::LibraryOptionsContext &C);
/// Create this object with static storage to register codegen-related command
/// line options.
@@ -162,11 +103,6 @@ struct RegisterSaveStatsFlag {
LLVM_ABI RegisterSaveStatsFlag();
};
-LLVM_ABI bool getEnableBBAddrMap();
-
-LLVM_ABI llvm::BasicBlockSection
-getBBSectionsMode(llvm::TargetOptions &Options);
-
/// Common utility function tightly tied to the options listed here. Initializes
/// a TargetOptions object with CodeGen options and returns it.
/// \p TheTriple is used to determine the default value for options if
@@ -177,13 +113,14 @@ LLVM_ABI TargetOptions
getTargetOptions(const cl::LibraryOptionsContext &LibraryOptions,
const llvm::Triple &TheTriple);
-LLVM_ABI std::string getCPUStr();
+LLVM_ABI std::string getCPUStr(const cl::LibraryOptionsContext &C);
-LLVM_ABI std::string getTuneCPUStr();
+LLVM_ABI std::string getTuneCPUStr(const cl::LibraryOptionsContext &C);
-LLVM_ABI std::string getFeaturesStr();
+LLVM_ABI std::string getFeaturesStr(const cl::LibraryOptionsContext &C);
-LLVM_ABI std::vector<std::string> getFeatureList();
+LLVM_ABI std::vector<std::string>
+getFeatureList(const cl::LibraryOptionsContext &C);
LLVM_ABI void renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val);
@@ -207,13 +144,14 @@ LLVM_ABI Expected<std::unique_ptr<TargetMachine>> createTargetMachineForTriple(
/// Conditionally enables the collection of LLVM statistics during the tool run,
/// based on the value of the flag. Must be called before the tool run to
/// actually collect data.
-LLVM_ABI void MaybeEnableStatistics();
+LLVM_ABI void maybeEnableStatistics(const cl::LibraryOptionsContext &C);
/// Conditionally saves the collected LLVM statistics to the received output
/// file, based on the value of the flag. Should be called after the tool run,
-/// and must follow a call to `MaybeEnableStatistics()` to actually have data to
+/// and must follow a call to `maybeEnableStatistics()` to actually have data to
/// write.
-LLVM_ABI int MaybeSaveStatistics(StringRef OutputFilename, StringRef ToolName);
+LLVM_ABI int maybeSaveStatistics(const cl::LibraryOptionsContext &C,
+ StringRef OutputFilename, StringRef ToolName);
} // namespace codegen
} // namespace llvm
diff --git a/llvm/lib/CodeGen/CMakeLists.txt b/llvm/lib/CodeGen/CMakeLists.txt
index f29fe857b7a71..e604d6c0521a5 100644
--- a/llvm/lib/CodeGen/CMakeLists.txt
+++ b/llvm/lib/CodeGen/CMakeLists.txt
@@ -38,6 +38,9 @@ set(LLVM_TABLEGEN_PROJECT LLVM_HEADERS)
set(LLVM_TARGET_DEFINITIONS CodeGenOptions.td)
llvm_tablegen(CodeGenOptions.inc -gen-opt-parser-defs)
add_public_tablegen_target(CodeGenOptionsTableGen)
+set(LLVM_TARGET_DEFINITIONS CodeGenToolOptions.td)
+llvm_tablegen(CodeGenToolOptions.inc -gen-opt-parser-defs)
+add_public_tablegen_target(CodeGenToolOptionsTableGen)
add_llvm_component_library(LLVMCodeGen
AggressiveAntiDepBreaker.cpp
@@ -290,6 +293,7 @@ add_llvm_component_library(LLVMCodeGen
DEPENDS
CodeGenOptionsTableGen
+ CodeGenToolOptionsTableGen
intrinsics_gen
vt_gen
${MLDeps}
diff --git a/llvm/lib/CodeGen/CodeGenToolOptions.td b/llvm/lib/CodeGen/CodeGenToolOptions.td
new file mode 100644
index 0000000000000..accc38d972231
--- /dev/null
+++ b/llvm/lib/CodeGen/CodeGenToolOptions.td
@@ -0,0 +1,93 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+include "llvm/Option/LibraryOptions.td"
+
+def CodeGenToolOptions : OptionsStruct;
+
+defm : BoolField<"addrsig", "false",
+ "Emit an address-significance table">;
+defm : ValueField<"align-loops", "unsigned", "0",
+ "Default alignment for loops">;
+defm : BoolField<"basic-block-address-map", "false",
+ "Emit the basic block address map section">;
+defm : ValueField<"basic-block-sections", "StringRef", "\"none\"",
+ "Emit basic blocks into separate sections">;
+defm : BoolField<"call-graph-section", "false",
+ "Emit a call graph section">;
+defm : BoolField<"debug-entry-values", "false",
+ "Enable debug info for the debug entry values">;
+// FIXME: Doesn't have way to specify separate input and output modes.
+defm : OptionalEnumField<"denormal-fp-math", "DenormalMode::DenormalModeKind",
+ "ieee,preserve-sign,positive-zero,dynamic",
+ ["DenormalMode::IEEE", "DenormalMode::PreserveSign", "DenormalMode::PositiveZero", "DenormalMode::Dynamic"],
+ "Select which denormal numbers the code is permitted to require">;
+defm : OptionalEnumField<"denormal-fp-math-f32", "DenormalMode::DenormalModeKind",
+ "ieee,preserve-sign,positive-zero,dynamic",
+ ["DenormalMode::IEEE", "DenormalMode::PreserveSign", "DenormalMode::PositiveZero", "DenormalMode::Dynamic"],
+ "Select which denormal numbers the code is permitted to require for float">;
+defm : OptionalBoolField<"disable-tail-calls",
+ "Never emit tail calls">;
+defm : BoolField<"emit-call-site-info", "false",
+ "Emit call site debug information, if debug information is enabled">;
+defm : BoolField<"enable-jmc-instrument", "false",
+ "Instrument functions with a call to __CheckForDebuggerJustMyCode">;
+defm : OptionalBoolField<"enable-tlsdesc",
+ "Enable the use of TLS Descriptors">;
+defm : EnumField<"exception-model", "ExceptionHandling", "ExceptionHandling::Default",
+ "default,none,dwarf,sjlj,arm,wineh,wasm,emscripten",
+ ["ExceptionHandling::Default", "ExceptionHandling::None", "ExceptionHandling::DwarfCFI", "ExceptionHandling::SjLj", "ExceptionHandling::ARM", "ExceptionHandling::WinEH", "ExceptionHandling::Wasm", "ExceptionHandling::Emscripten"],
+ "Exception model">;
+defm : BoolField<"force-dwarf-frame-section", "false",
+ "Always emit a debug frame section">;
+defm : OptionalEnumField<"frame-pointer", "FramePointerKind",
+ "all,non-leaf,non-leaf-no-reserve,reserved,none",
+ ["FramePointerKind::All", "FramePointerKind::NonLeaf", "FramePointerKind::NonLeafNoReserve", "FramePointerKind::Reserved", "FramePointerKind::None"],
+ "Specify frame pointer elimination optimization">;
+defm : BoolField<"ignore-xcoff-visibility", "false",
+ "Not emit the visibility attribute for asm in AIX OS or give all symbols 'unspecified' visibility in XCOFF object file">;
+defm : BoolField<"mxcoff-roptr", "false",
+ "When set to true, const objects with relocatable address values are put into the RO data section">;
+defm : BoolField<"nozero-initialized-in-bss", "false",
+ "Don't place zero-initialized symbols into bss section">;
+defm : BoolField<"partition-static-data-sections", "false",
+ "Partition data sections using profile information">;
+defm : BoolField<"separate-named-sections", "false",
+ "Use separate unique sections for named sections">;
+defm : BoolField<"stack-size-section", "false",
+ "Emit a section containing stack size metadata">;
+defm : BoolField<"stack-symbol-ordering", "true",
+ "Order local stack symbols">;
+defm : BoolField<"stackrealign", "false",
+ "Force align the stack to the minimum alignment">;
+defm : BoolField<"strict-dwarf", "false",
+ "Use strict DWARF">;
+defm : EnumField<"swift-async-fp", "SwiftAsyncFramePointerMode", "SwiftAsyncFramePointerMode::Always",
+ "auto,always,never",
+ ["SwiftAsyncFramePointerMode::DeploymentBased", "SwiftAsyncFramePointerMode::Always", "SwiftAsyncFramePointerMode::Never"],
+ "Determine when the Swift async frame pointer should be set">;
+defm : BoolField<"tailcallopt", "false",
+ "Turn fastcc calls into tail calls by (potentially) changing ABI">;
+defm : ValueField<"tls-size", "unsigned", "0",
+ "Bit size of immediate TLS offsets">;
+defm : OptionalValueField<"trap-func", "StringRef",
+ "Emit a call to trap function rather than a trap instruction">;
+defm : BoolField<"unique-basic-block-section-names", "false",
+ "Give unique names to every basic block section">;
+defm : BoolField<"unique-section-names", "true",
+ "Give unique names to every section">;
+defm : BoolField<"use-ctors", "false",
+ "Use .ctors instead of .init_array">;
+defm : EnumField<"vector-library", "VectorLibrary", "VectorLibrary::NoLibrary",
+ "none,Accelerate,Darwin_libsystem_m,LIBMVEC,MASSV,SVML,sleefgnuabi,ArmPL,AMDLIBM",
+ ["VectorLibrary::NoLibrary", "VectorLibrary::Accelerate", "VectorLibrary::DarwinLibSystemM", "VectorLibrary::LIBMVEC", "VectorLibrary::MASSV", "VectorLibrary::SVML", "VectorLibrary::SLEEFGNUABI", "VectorLibrary::ArmPL", "VectorLibrary::AMDLIBM"],
+ "Vector functions library">;
+defm : BoolField<"xcoff-traceback-table", "true",
+ "Emit the XCOFF traceback table">;
+defm : BoolField<"xray-function-index", "true",
+ "Emit xray_fn_idx section">;
diff --git a/llvm/lib/CodeGen/CommandFlags.cpp b/llvm/lib/CodeGen/CommandFlags.cpp
index d0a15bdd7a22a..bd1615e28c3c9 100644
--- a/llvm/lib/CodeGen/CommandFlags.cpp
+++ b/llvm/lib/CodeGen/CommandFlags.cpp
@@ -13,6 +13,7 @@
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/CommandFlags.h"
+#include "llvm/ADT/FloatingPointMode.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
@@ -22,6 +23,7 @@
#include "llvm/IR/Module.h"
#include "llvm/MC/MCTargetOptionsCommandFlags.h"
#include "llvm/MC/TargetRegistry.h"
+#include "llvm/Option/LibraryOptions.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
@@ -40,16 +42,26 @@
using namespace llvm;
+#define OPTIONS_STRUCT_DECL
+#include "CodeGenToolOptions.inc"
+
+#define OPTIONS_STRUCT_DEFS
+#include "CodeGenToolOptions.inc"
+
+static const CodeGenToolOptions &getCodeGenToolOptions(const LLVMContext &C) {
+ return C.getLibraryOptions().get<CodeGenToolOptions>();
+}
+
#define CGOPT(TY, NAME) \
static cl::opt<TY> *NAME##View; \
- TY codegen::get##NAME() { \
+ TY codegen::get##NAME(const cl::LibraryOptionsContext &) { \
assert(NAME##View && "Flag not registered."); \
return *NAME##View; \
}
#define CGLIST(TY, NAME) \
static cl::list<TY> *NAME##View; \
- std::vector<TY> codegen::get##NAME() { \
+ std::vector<TY> codegen::get##NAME(const cl::LibraryOptionsContext &) { \
assert(NAME##View && "Flag not registered."); \
return *NAME##View; \
}
@@ -57,7 +69,8 @@ using namespace llvm;
// Temporary macro for incremental transition to std::optional.
#define CGOPT_EXP(TY, NAME) \
CGOPT(TY, NAME) \
- std::optional<TY> codegen::getExplicit##NAME() { \
+ std::optional<TY> codegen::getExplicit##NAME( \
+ const cl::LibraryOptionsContext &) { \
if (NAME##View->getNumOccurrences()) { \
TY res = *NAME##View; \
return res; \
@@ -72,45 +85,11 @@ CGLIST(std::string, MAttrs)
CGOPT_EXP(Reloc::Model, RelocModel)
CGOPT_EXP(CodeModel::Model, CodeModel)
CGOPT_EXP(uint64_t, LargeDataThreshold)
-CGOPT(ExceptionHandling, ExceptionModel)
CGOPT_EXP(CodeGenFileType, FileType)
-CGOPT(FramePointerKind, FramePointerUsage)
-CGOPT(DenormalMode::DenormalModeKind, DenormalFPMath)
-CGOPT(DenormalMode::DenormalModeKind, DenormalFP32Math)
CGOPT(FloatABI::ABIType, FloatABIForCalls)
-CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
-CGOPT(bool, DontPlaceZerosInBSS)
-CGOPT(bool, EnableGuaranteedTailCallOpt)
-CGOPT(bool, DisableTailCalls)
-CGOPT(bool, StackSymbolOrdering)
-CGOPT(bool, StackRealign)
-CGOPT(std::string, TrapFuncName)
-CGOPT(bool, UseCtors)
CGOPT_EXP(bool, DataSections)
CGOPT_EXP(bool, FunctionSections)
-CGOPT(bool, IgnoreXCOFFVisibility)
-CGOPT(bool, XCOFFTracebackTable)
-CGOPT(bool, EnableBBAddrMap)
-CGOPT(std::string, BBSections)
-CGOPT(unsigned, TLSSize)
CGOPT_EXP(bool, EmulatedTLS)
-CGOPT_EXP(bool, EnableTLSDESC)
-CGOPT(bool, UniqueSectionNames)
-CGOPT(bool, UniqueBasicBlockSectionNames)
-CGOPT(bool, SeparateNamedSections)
-CGOPT(VectorLibrary, VectorLibrary)
-CGOPT(bool, EnableStackSizeSection)
-CGOPT(bool, EnableAddrsig)
-CGOPT(bool, EnableCallGraphSection)
-CGOPT(bool, EmitCallSiteInfo)
-CGOPT(bool, EnableStaticDataPartitioning)
-CGOPT(bool, EnableDebugEntryValues)
-CGOPT(bool, ForceDwarfFrameSection)
-CGOPT(bool, XRayFunctionIndex)
-CGOPT(bool, DebugStrictDwarf)
-CGOPT(unsigned, AlignLoops)
-CGOPT(bool, JMCInstrument)
-CGOPT(bool, XCOFFReadOnlyPointers)
CGOPT(codegen::SaveStatsMode, SaveStats)
#define CGBINDOPT(NAME) \
@@ -167,26 +146,6 @@ codegen::RegisterCodeGenFlags::RegisterCodeGenFlags() {
cl::init(0));
CGBINDOPT(LargeDataThreshold);
- static cl::opt<ExceptionHandling> ExceptionModel(
- "exception-model", cl::desc("exception model"),
- cl::init(ExceptionHandling::Default),
- cl::values(
- clEnumValN(ExceptionHandling::Default, "default",
- "default exception handling model"),
- clEnumValN(ExceptionHandling::None, "none", "no exception handling"),
- clEnumValN(ExceptionHandling::DwarfCFI, "dwarf",
- "DWARF-like CFI based exception handling"),
- clEnumValN(ExceptionHandling::SjLj, "sjlj",
- "SjLj exception handling"),
- clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
- clEnumValN(ExceptionHandling::WinEH, "wineh",
- "Windows exception model"),
- clEnumValN(ExceptionHandling::Wasm, "wasm",
- "WebAssembly exception handling"),
- clEnumValN(ExceptionHandling::Emscripten, "emscripten",
- "Emscripten JavaScript-based exception handling")));
- CGBINDOPT(ExceptionModel);
-
static cl::opt<CodeGenFileType> FileType(
"filetype", cl::init(CodeGenFileType::AssemblyFile),
cl::desc(
@@ -199,50 +158,6 @@ codegen::RegisterCodeGenFlags::RegisterCodeGenFlags() {
"Emit nothing, for performance testing")));
CGBINDOPT(FileType);
- static cl::opt<FramePointerKind> FramePointerUsage(
- "frame-pointer",
- cl::desc("Specify frame pointer elimination optimization"),
- cl::init(FramePointerKind::None),
- cl::values(
- clEnumValN(FramePointerKind::All, "all",
- "Disable frame pointer elimination"),
- clEnumValN(FramePointerKind::NonLeaf, "non-leaf",
- "Disable frame pointer elimination for non-leaf frame but "
- "reserve the register in leaf functions"),
- clEnumValN(FramePointerKind::NonLeafNoReserve, "non-leaf-no-reserve",
- "Disable frame pointer elimination for non-leaf frame"),
- clEnumValN(FramePointerKind::Reserved, "reserved",
- "Enable frame pointer elimination, but reserve the frame "
- "pointer register"),
- clEnumValN(FramePointerKind::None, "none",
- "Enable frame pointer elimination")));
- CGBINDOPT(FramePointerUsage);
-
- static const auto DenormFlagEnumOptions = cl::values(
- clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
- clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
- "the sign of a flushed-to-zero number is preserved "
- "in the sign of 0"),
- clEnumValN(DenormalMode::PositiveZero, "positive-zero",
- "denormals are flushed to positive zero"),
- clEnumValN(DenormalMode::Dynamic, "dynamic",
- "denormals have unknown treatment"));
-
- // FIXME: Doesn't have way to specify separate input and output modes.
- static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
- "denormal-fp-math",
- cl::desc("Select which denormal numbers the code is permitted to require"),
- cl::init(DenormalMode::IEEE),
- DenormFlagEnumOptions);
- CGBINDOPT(DenormalFPMath);
-
- static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
- "denormal-fp-math-f32",
- cl::desc("Select which denormal numbers the code is permitted to require for float"),
- cl::init(DenormalMode::Invalid),
- DenormFlagEnumOptions);
- CGBINDOPT(DenormalFP32Math);
-
static cl::opt<FloatABI::ABIType> FloatABIForCalls(
"float-abi", cl::desc("Choose float ABI type"),
cl::init(FloatABI::Default),
@@ -254,57 +169,6 @@ codegen::RegisterCodeGenFlags::RegisterCodeGenFlags() {
"Hard float ABI (uses FP registers)")));
CGBINDOPT(FloatABIForCalls);
- static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
- "swift-async-fp",
- cl::desc("Determine when the Swift async frame pointer should be set"),
- cl::init(SwiftAsyncFramePointerMode::Always),
- cl::values(clEnumValN(SwiftAsyncFramePointerMode::DeploymentBased, "auto",
- "Determine based on deployment target"),
- clEnumValN(SwiftAsyncFramePointerMode::Always, "always",
- "Always set the bit"),
- clEnumValN(SwiftAsyncFramePointerMode::Never, "never",
- "Never set the bit")));
- CGBINDOPT(SwiftAsyncFramePointer);
-
- static cl::opt<bool> DontPlaceZerosInBSS(
- "nozero-initialized-in-bss",
- cl::desc("Don't place zero-initialized symbols into bss section"),
- cl::init(false));
- CGBINDOPT(DontPlaceZerosInBSS);
-
- static cl::opt<bool> EnableGuaranteedTailCallOpt(
- "tailcallopt",
- cl::desc(
- "Turn fastcc calls into tail calls by (potentially) changing ABI."),
- cl::init(false));
- CGBINDOPT(EnableGuaranteedTailCallOpt);
-
- static cl::opt<bool> DisableTailCalls(
- "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
- CGBINDOPT(DisableTailCalls);
-
- static cl::opt<bool> StackSymbolOrdering(
- "stack-symbol-ordering", cl::desc("Order local stack symbols."),
- cl::init(true));
- CGBINDOPT(StackSymbolOrdering);
-
- static cl::opt<bool> StackRealign(
- "stackrealign",
- cl::desc("Force align the stack to the minimum alignment"),
- cl::init(false));
- CGBINDOPT(StackRealign);
-
- static cl::opt<std::string> TrapFuncName(
- "trap-func", cl::Hidden,
- cl::desc("Emit a call to trap function rather than a trap instruction"),
- cl::init(""));
- CGBINDOPT(TrapFuncName);
-
- static cl::opt<bool> UseCtors("use-ctors",
- cl::desc("Use .ctors instead of .init_array."),
- cl::init(false));
- CGBINDOPT(UseCtors);
-
static cl::opt<bool> DataSections(
"data-sections", cl::desc("Emit data into separate sections"),
cl::init(false));
@@ -315,151 +179,19 @@ codegen::RegisterCodeGenFlags::RegisterCodeGenFlags() {
cl::init(false));
CGBINDOPT(FunctionSections);
- static cl::opt<bool> IgnoreXCOFFVisibility(
- "ignore-xcoff-visibility",
- cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
- "all symbols 'unspecified' visibility in XCOFF object file"),
- cl::init(false));
- CGBINDOPT(IgnoreXCOFFVisibility);
-
- static cl::opt<bool> XCOFFTracebackTable(
- "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
- cl::init(true));
- CGBINDOPT(XCOFFTracebackTable);
-
- static cl::opt<bool> EnableBBAddrMap(
- "basic-block-address-map",
- cl::desc("Emit the basic block address map section"), cl::init(false));
- CGBINDOPT(EnableBBAddrMap);
-
- static cl::opt<std::string> BBSections(
- "basic-block-sections",
- cl::desc("Emit basic blocks into separate sections"),
- cl::value_desc("all | <function list (file)> | labels | none"),
- cl::init("none"));
- CGBINDOPT(BBSections);
-
- static cl::opt<unsigned> TLSSize(
- "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
- CGBINDOPT(TLSSize);
-
static cl::opt<bool> EmulatedTLS(
"emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
CGBINDOPT(EmulatedTLS);
- static cl::opt<bool> EnableTLSDESC(
- "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
- cl::init(false));
- CGBINDOPT(EnableTLSDESC);
-
- static cl::opt<bool> UniqueSectionNames(
- "unique-section-names", cl::desc("Give unique names to every section"),
- cl::init(true));
- CGBINDOPT(UniqueSectionNames);
-
- static cl::opt<bool> UniqueBasicBlockSectionNames(
- "unique-basic-block-section-names",
- cl::desc("Give unique names to every basic block section"),
- cl::init(false));
- CGBINDOPT(UniqueBasicBlockSectionNames);
-
- static cl::opt<bool> SeparateNamedSections(
- "separate-named-sections",
- cl::desc("Use separate unique sections for named sections"),
- cl::init(false));
- CGBINDOPT(SeparateNamedSections);
-
- static cl::opt<VectorLibrary> VectorLibrary(
- "vector-library", cl::Hidden, cl::desc("Vector functions library"),
- cl::init(VectorLibrary::NoLibrary),
- cl::values(
- clEnumValN(VectorLibrary::NoLibrary, "none",
- "No vector functions library"),
- clEnumValN(VectorLibrary::Accelerate, "Accelerate",
- "Accelerate framework"),
- clEnumValN(VectorLibrary::DarwinLibSystemM, "Darwin_libsystem_m",
- "Darwin libsystem_m"),
- clEnumValN(VectorLibrary::LIBMVEC, "LIBMVEC",
- "GLIBC Vector Math library"),
- clEnumValN(VectorLibrary::MASSV, "MASSV", "IBM MASS vector library"),
- clEnumValN(VectorLibrary::SVML, "SVML", "Intel SVML library"),
- clEnumValN(VectorLibrary::SLEEFGNUABI, "sleefgnuabi",
- "SIMD Library for Evaluating Elementary Functions"),
- clEnumValN(VectorLibrary::ArmPL, "ArmPL",
- "Arm Performance Libraries"),
- clEnumValN(VectorLibrary::AMDLIBM, "AMDLIBM",
- "AMD vector math library")));
- CGBINDOPT(VectorLibrary);
-
- static cl::opt<bool> EnableStackSizeSection(
- "stack-size-section",
- cl::desc("Emit a section containing stack size metadata"),
- cl::init(false));
- CGBINDOPT(EnableStackSizeSection);
-
- static cl::opt<bool> EnableAddrsig(
- "addrsig", cl::desc("Emit an address-significance table"),
- cl::init(false));
- CGBINDOPT(EnableAddrsig);
-
- static cl::opt<bool> EnableCallGraphSection(
- "call-graph-section", cl::desc("Emit a call graph section"),
- cl::init(false));
- CGBINDOPT(EnableCallGraphSection);
-
- static cl::opt<bool> EmitCallSiteInfo(
- "emit-call-site-info",
- cl::desc(
- "Emit call site debug information, if debug information is enabled."),
- cl::init(false));
- CGBINDOPT(EmitCallSiteInfo);
-
- static cl::opt<bool> EnableDebugEntryValues(
- "debug-entry-values",
- cl::desc("Enable debug info for the debug entry values."),
- cl::init(false));
- CGBINDOPT(EnableDebugEntryValues);
-
- static cl::opt<bool> EnableStaticDataPartitioning(
- "partition-static-data-sections",
- cl::desc("Partition data sections using profile information."),
- cl::init(false));
- CGBINDOPT(EnableStaticDataPartitioning);
-
- static cl::opt<bool> ForceDwarfFrameSection(
- "force-dwarf-frame-section",
- cl::desc("Always emit a debug frame section."), cl::init(false));
- CGBINDOPT(ForceDwarfFrameSection);
-
- static cl::opt<bool> XRayFunctionIndex("xray-function-index",
- cl::desc("Emit xray_fn_idx section"),
- cl::init(true));
- CGBINDOPT(XRayFunctionIndex);
-
- static cl::opt<bool> DebugStrictDwarf(
- "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
- CGBINDOPT(DebugStrictDwarf);
-
- static cl::opt<unsigned> AlignLoops("align-loops",
- cl::desc("Default alignment for loops"));
- CGBINDOPT(AlignLoops);
-
- static cl::opt<bool> JMCInstrument(
- "enable-jmc-instrument",
- cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
- cl::init(false));
- CGBINDOPT(JMCInstrument);
-
- static cl::opt<bool> XCOFFReadOnlyPointers(
- "mxcoff-roptr",
- cl::desc("When set to true, const objects with relocatable address "
- "values are put into the RO data section."),
- cl::init(false));
- CGBINDOPT(XCOFFReadOnlyPointers);
}
ArrayRef<const cl::LibraryOptions *> codegen::getToolOptions() {
- return mc::getToolOptions();
+ static constexpr opt::LibraryOptionsParser Parser(
+ std::in_place_type<CodeGenToolOptions>);
+ assert(mc::getToolOptions().size() == 1);
+ static const cl::LibraryOptions *const Libraries[] = {mc::getToolOptions()[0],
+ &Parser};
+ return Libraries;
}
codegen::RegisterMTuneFlag::RegisterMTuneFlag() {
@@ -487,15 +219,15 @@ codegen::RegisterSaveStatsFlag::RegisterSaveStatsFlag() {
CGBINDOPT(SaveStats);
}
-llvm::BasicBlockSection
-codegen::getBBSectionsMode(llvm::TargetOptions &Options) {
- if (getBBSections() == "all")
+static BasicBlockSection getBBSectionsMode(const CodeGenToolOptions &Opts,
+ TargetOptions &Options) {
+ if (Opts.basic_block_sections == "all")
return BasicBlockSection::All;
- else if (getBBSections() == "none")
+ else if (Opts.basic_block_sections == "none")
return BasicBlockSection::None;
else {
ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
- MemoryBuffer::getFile(getBBSections());
+ MemoryBuffer::getFile(Opts.basic_block_sections);
if (!MBOrErr) {
errs() << "Error loading basic block sections function list file: "
<< MBOrErr.getError().message() << "\n";
@@ -511,48 +243,49 @@ codegen::getBBSectionsMode(llvm::TargetOptions &Options) {
TargetOptions
codegen::getTargetOptions(const cl::LibraryOptionsContext &LibraryOptions,
const Triple &TheTriple) {
+ const CodeGenToolOptions &Opts = LibraryOptions.get<CodeGenToolOptions>();
TargetOptions Options;
- Options.NoZerosInBSS = getDontPlaceZerosInBSS();
- Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
- Options.StackSymbolOrdering = getStackSymbolOrdering();
- Options.UseInitArray = !getUseCtors();
- Options.DataSections =
- getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
- Options.FunctionSections = getFunctionSections();
- Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
- Options.XCOFFTracebackTable = getXCOFFTracebackTable();
- Options.BBAddrMap = getEnableBBAddrMap();
- Options.BBSections = getBBSectionsMode(Options);
- Options.UniqueSectionNames = getUniqueSectionNames();
- Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
- Options.SeparateNamedSections = getSeparateNamedSections();
- Options.TLSSize = getTLSSize();
- Options.EmulatedTLS =
- getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
+ Options.NoZerosInBSS = Opts.nozero_initialized_in_bss;
+ Options.GuaranteedTailCallOpt = Opts.tailcallopt;
+ Options.StackSymbolOrdering = Opts.stack_symbol_ordering;
+ Options.UseInitArray = !Opts.use_ctors;
+ Options.DataSections = getExplicitDataSections(LibraryOptions)
+ .value_or(TheTriple.hasDefaultDataSections());
+ Options.FunctionSections = getFunctionSections(LibraryOptions);
+ Options.IgnoreXCOFFVisibility = Opts.ignore_xcoff_visibility;
+ Options.XCOFFTracebackTable = Opts.xcoff_traceback_table;
+ Options.BBAddrMap = Opts.basic_block_address_map;
+ Options.BBSections = getBBSectionsMode(Opts, Options);
+ Options.UniqueSectionNames = Opts.unique_section_names;
+ Options.UniqueBasicBlockSectionNames = Opts.unique_basic_block_section_names;
+ Options.SeparateNamedSections = Opts.separate_named_sections;
+ Options.TLSSize = Opts.tls_size;
+ Options.EmulatedTLS = getExplicitEmulatedTLS(LibraryOptions)
+ .value_or(TheTriple.hasDefaultEmulatedTLS());
Options.EnableTLSDESC =
- getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());
- Options.VecLib = getVectorLibrary();
- Options.EmitStackSizeSection = getEnableStackSizeSection();
- Options.EnableStaticDataPartitioning = getEnableStaticDataPartitioning();
- Options.EmitAddrsig = getEnableAddrsig();
- Options.EmitCallGraphSection = getEnableCallGraphSection();
- Options.EmitCallSiteInfo = getEmitCallSiteInfo();
- Options.EnableDebugEntryValues = getEnableDebugEntryValues();
- Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
- Options.XRayFunctionIndex = getXRayFunctionIndex();
- Options.DebugStrictDwarf = getDebugStrictDwarf();
- Options.LoopAlignment = getAlignLoops();
- Options.JMCInstrument = getJMCInstrument();
- Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
+ valueOr(Opts.enable_tlsdesc, TheTriple.hasDefaultTLSDESC());
+ Options.VecLib = Opts.vector_library;
+ Options.EmitStackSizeSection = Opts.stack_size_section;
+ Options.EnableStaticDataPartitioning = Opts.partition_static_data_sections;
+ Options.EmitAddrsig = Opts.addrsig;
+ Options.EmitCallGraphSection = Opts.call_graph_section;
+ Options.EmitCallSiteInfo = Opts.emit_call_site_info;
+ Options.EnableDebugEntryValues = Opts.debug_entry_values;
+ Options.ForceDwarfFrameSection = Opts.force_dwarf_frame_section;
+ Options.XRayFunctionIndex = Opts.xray_function_index;
+ Options.DebugStrictDwarf = Opts.strict_dwarf;
+ Options.LoopAlignment = Opts.align_loops;
+ Options.JMCInstrument = Opts.enable_jmc_instrument;
+ Options.XCOFFReadOnlyPointers = Opts.mxcoff_roptr;
Options.MCOptions = mc::getMCTargetOptions(LibraryOptions);
- Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
+ Options.SwiftAsyncFramePointer = Opts.swift_async_fp;
return Options;
}
-std::string codegen::getCPUStr() {
- std::string MCPU = getMCPU();
+std::string codegen::getCPUStr(const cl::LibraryOptionsContext &C) {
+ std::string MCPU = getMCPU(C);
// If user asked for the 'native' CPU, autodetect here. If auto-detection
// fails, this will set the CPU to an empty string which tells the target to
@@ -563,8 +296,8 @@ std::string codegen::getCPUStr() {
return MCPU;
}
-std::string codegen::getTuneCPUStr() {
- std::string TuneCPU = getMTune();
+std::string codegen::getTuneCPUStr(const cl::LibraryOptionsContext &C) {
+ std::string TuneCPU = getMTune(C);
// If user asked for the 'native' tune CPU, autodetect here. If auto-detection
// fails, this will set the tune CPU to an empty string which tells the target
@@ -575,35 +308,36 @@ std::string codegen::getTuneCPUStr() {
return TuneCPU;
}
-std::string codegen::getFeaturesStr() {
+std::string codegen::getFeaturesStr(const cl::LibraryOptionsContext &C) {
SubtargetFeatures Features;
// If user asked for the 'native' CPU, we need to autodetect features.
// This is necessary for x86 where the CPU might not support all the
// features the autodetected CPU name lists in the target. For example,
// not all Sandybridge processors support AVX.
- if (getMCPU() == "native")
+ if (getMCPU(C) == "native")
for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
Features.AddFeature(Feature, IsEnabled);
- for (auto const &MAttr : getMAttrs())
+ for (auto const &MAttr : getMAttrs(C))
Features.AddFeature(MAttr);
return Features.getString();
}
-std::vector<std::string> codegen::getFeatureList() {
+std::vector<std::string>
+codegen::getFeatureList(const cl::LibraryOptionsContext &C) {
SubtargetFeatures Features;
// If user asked for the 'native' CPU, we need to autodetect features.
// This is necessary for x86 where the CPU might not support all the
// features the autodetected CPU name lists in the target. For example,
// not all Sandybridge processors support AVX.
- if (getMCPU() == "native")
+ if (getMCPU(C) == "native")
for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
Features.AddFeature(Feature, IsEnabled);
- for (auto const &MAttr : getMAttrs())
+ for (auto const &MAttr : getMAttrs(C))
Features.AddFeature(MAttr);
return Features.getFeatures();
@@ -613,15 +347,10 @@ void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
B.addAttribute(Name, Val ? "true" : "false");
}
-#define HANDLE_BOOL_ATTR(CL, AttrName) \
- do { \
- if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
- renderBoolStringAttr(NewAttrs, AttrName, *CL); \
- } while (0)
-
void codegen::setFunctionAttributes(Function &F, StringRef CPU,
StringRef Features, StringRef TuneCPU) {
auto &Ctx = F.getContext();
+ const CodeGenToolOptions &Opts = getCodeGenToolOptions(Ctx);
AttributeList Attrs = F.getAttributes();
AttrBuilder NewAttrs(Ctx);
@@ -642,30 +371,30 @@ void codegen::setFunctionAttributes(Function &F, StringRef CPU,
NewAttrs.addAttribute("target-features", Appended);
}
}
- if (FramePointerUsageView->getNumOccurrences() > 0 &&
- !F.hasFnAttribute("frame-pointer")) {
- if (getFramePointerUsage() == FramePointerKind::All)
+ if (Opts.frame_pointer && !F.hasFnAttribute("frame-pointer")) {
+ if (*Opts.frame_pointer == FramePointerKind::All)
NewAttrs.addAttribute("frame-pointer", "all");
- else if (getFramePointerUsage() == FramePointerKind::NonLeaf)
+ else if (*Opts.frame_pointer == FramePointerKind::NonLeaf)
NewAttrs.addAttribute("frame-pointer", "non-leaf");
- else if (getFramePointerUsage() == FramePointerKind::NonLeafNoReserve)
+ else if (*Opts.frame_pointer == FramePointerKind::NonLeafNoReserve)
NewAttrs.addAttribute("frame-pointer", "non-leaf-no-reserve");
- else if (getFramePointerUsage() == FramePointerKind::Reserved)
+ else if (*Opts.frame_pointer == FramePointerKind::Reserved)
NewAttrs.addAttribute("frame-pointer", "reserved");
- else if (getFramePointerUsage() == FramePointerKind::None)
+ else if (*Opts.frame_pointer == FramePointerKind::None)
NewAttrs.addAttribute("frame-pointer", "none");
}
- if (DisableTailCallsView->getNumOccurrences() > 0)
+ if (Opts.disable_tail_calls != BoolOrDefault::Default)
NewAttrs.addAttribute("disable-tail-calls",
- toStringRef(getDisableTailCalls()));
- if (getStackRealign())
+ toStringRef(valueOr(Opts.disable_tail_calls, false)));
+ if (Opts.stackrealign)
NewAttrs.addAttribute("stackrealign");
- if ((DenormalFPMathView->getNumOccurrences() > 0 ||
- DenormalFP32MathView->getNumOccurrences() > 0) &&
+ if ((Opts.denormal_fp_math || Opts.denormal_fp_math_f32) &&
!F.hasFnAttribute(Attribute::DenormalFPEnv)) {
- DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();
- DenormalMode::DenormalModeKind DenormKindF32 = getDenormalFP32Math();
+ DenormalMode::DenormalModeKind DenormKind =
+ Opts.denormal_fp_math.value_or(DenormalMode::IEEE);
+ DenormalMode::DenormalModeKind DenormKindF32 =
+ Opts.denormal_fp_math_f32.value_or(DenormalMode::Invalid);
DenormalFPEnv FPEnv(DenormalMode{DenormKind, DenormKind},
DenormalMode{DenormKindF32, DenormKindF32});
@@ -673,7 +402,7 @@ void codegen::setFunctionAttributes(Function &F, StringRef CPU,
NewAttrs.addDenormalFPEnvAttr(FPEnv);
}
- if (TrapFuncNameView->getNumOccurrences() > 0)
+ if (Opts.trap_func)
for (auto &B : F)
for (auto &I : B)
if (auto *Call = dyn_cast<CallInst>(&I))
@@ -681,7 +410,7 @@ void codegen::setFunctionAttributes(Function &F, StringRef CPU,
if (F->getIntrinsicID() == Intrinsic::debugtrap ||
F->getIntrinsicID() == Intrinsic::trap)
Call->addFnAttr(
- Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
+ Attribute::get(Ctx, "trap-func-name", *Opts.trap_func));
// Let NewAttrs override Attrs.
F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
@@ -689,8 +418,9 @@ void codegen::setFunctionAttributes(Function &F, StringRef CPU,
void codegen::setFunctionAttributes(Module &M, StringRef CPU,
StringRef Features, StringRef TuneCPU) {
+ const cl::LibraryOptionsContext &C = M.getContext().getLibraryOptions();
// Synthesize the "float-abi" module flag from the -float-abi option.
- FloatABI::ABIType ABI = getFloatABIForCalls();
+ FloatABI::ABIType ABI = getFloatABIForCalls(C);
if (ABI != FloatABI::Default) {
if (auto *Existing =
dyn_cast_or_null<MDString>(M.getModuleFlag("float-abi"))) {
@@ -710,7 +440,7 @@ void codegen::setFunctionAttributes(Module &M, StringRef CPU,
// Synthesize the "exception-model" module flag from the -exception-model
// option.
- ExceptionHandling EH = getExceptionModel();
+ ExceptionHandling EH = getCodeGenToolOptions(M.getContext()).exception_model;
if (EH != ExceptionHandling::Default) {
if (auto *Existing =
dyn_cast_or_null<MDString>(M.getModuleFlag("exception-model"))) {
@@ -732,7 +462,7 @@ void codegen::setFunctionAttributes(Module &M, StringRef CPU,
//
// FIXME: verifyOptionsConsistency validates consistency for target-abi. We
// should consistently handle all ABI module flags either here or there.
- StringRef ABIName = mc::getABIName(M.getContext().getLibraryOptions());
+ StringRef ABIName = mc::getABIName(C);
if (!ABIName.empty() && !M.getModuleFlag("target-abi")) {
M.addModuleFlag(Module::Error, "target-abi",
MDString::get(M.getContext(), ABIName));
@@ -748,16 +478,17 @@ Expected<std::unique_ptr<TargetMachine>> codegen::createTargetMachineForTriple(
// lookupTarget may mutate the triple, so we need a copy.
Triple TheTriple(TargetTriple);
std::string Error;
- const auto *TheTarget =
- TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
+ const auto *TheTarget = TargetRegistry::lookupTarget(
+ codegen::getMArch(LibraryOptions), TheTriple, Error);
if (!TheTarget)
return createStringError(inconvertibleErrorCode(), Error);
TargetOptions Options = codegen::getTargetOptions(LibraryOptions, TheTriple);
Options.MCOptions.LibraryOptions = &LibraryOptions;
auto *Target = TheTarget->createTargetMachine(
- TheTriple, codegen::getCPUStr(), codegen::getFeaturesStr(), Options,
- codegen::getExplicitRelocModel(), codegen::getExplicitCodeModel(),
- OptLevel);
+ TheTriple, codegen::getCPUStr(LibraryOptions),
+ codegen::getFeaturesStr(LibraryOptions), Options,
+ codegen::getExplicitRelocModel(LibraryOptions),
+ codegen::getExplicitCodeModel(LibraryOptions), OptLevel);
if (!Target)
return createStringError(inconvertibleErrorCode(),
Twine("could not allocate target machine for ") +
@@ -765,15 +496,16 @@ Expected<std::unique_ptr<TargetMachine>> codegen::createTargetMachineForTriple(
return std::unique_ptr<TargetMachine>(Target);
}
-void codegen::MaybeEnableStatistics() {
- if (getSaveStats() == SaveStatsMode::None)
+void codegen::maybeEnableStatistics(const cl::LibraryOptionsContext &C) {
+ if (getSaveStats(C) == SaveStatsMode::None)
return;
llvm::EnableStatistics(false);
}
-int codegen::MaybeSaveStatistics(StringRef OutputFilename, StringRef ToolName) {
- auto SaveStatsValue = getSaveStats();
+int codegen::maybeSaveStatistics(const cl::LibraryOptionsContext &C,
+ StringRef OutputFilename, StringRef ToolName) {
+ auto SaveStatsValue = getSaveStats(C);
if (SaveStatsValue == codegen::SaveStatsMode::None)
return 0;
diff --git a/llvm/lib/LTO/LTOCodeGenerator.cpp b/llvm/lib/LTO/LTOCodeGenerator.cpp
index f15ed0321fa58..a01780f38b4af 100644
--- a/llvm/lib/LTO/LTOCodeGenerator.cpp
+++ b/llvm/lib/LTO/LTOCodeGenerator.cpp
@@ -397,7 +397,7 @@ bool LTOCodeGenerator::determineTarget() {
// If data-sections is not explicitly set or unset, set data-sections by
// default to match the behaviour of lld and gold plugin.
- if (!codegen::getExplicitDataSections())
+ if (!codegen::getExplicitDataSections(Context.getLibraryOptions()))
Config.Options.DataSections = true;
TargetMach = createTargetMachine();
diff --git a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
index bda1a0dedc828..e1543153b75e3 100644
--- a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
+++ b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
@@ -555,14 +555,15 @@ static void resolvePrevailingInIndex(
}
// Initialize the TargetMachine builder for a given Triple
-static void initTMBuilder(TargetMachineBuilder &TMBuilder,
+static void initTMBuilder(const cl::LibraryOptionsContext &LibraryOptions,
+ TargetMachineBuilder &TMBuilder,
const Triple &TheTriple) {
if (TMBuilder.MCpu.empty())
TMBuilder.MCpu = lto::getThinLTODefaultCPU(TheTriple);
TMBuilder.TheTriple = std::move(TheTriple);
// If data-sections is not explicitly set or unset, set data-sections by
// default to match the behaviour of lld and gold plugin.
- if (!codegen::getExplicitDataSections())
+ if (!codegen::getExplicitDataSections(LibraryOptions))
TMBuilder.Options.DataSections = true;
}
@@ -578,12 +579,13 @@ void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Triple TheTriple(TripleStr);
if (Modules.empty())
- initTMBuilder(TMBuilder, Triple(TheTriple));
+ initTMBuilder(LibraryOptions, TMBuilder, Triple(TheTriple));
else if (TMBuilder.TheTriple != TheTriple) {
if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
report_fatal_error("ThinLTO modules with incompatible triples not "
"supported");
- initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
+ initTMBuilder(LibraryOptions, TMBuilder,
+ Triple(TMBuilder.TheTriple.merge(TheTriple)));
}
Modules.emplace_back(std::move(*InputOrError));
@@ -873,7 +875,7 @@ void ThinLTOCodeGenerator::emitImports(Module &TheModule, StringRef OutputName,
void ThinLTOCodeGenerator::internalize(Module &TheModule,
ModuleSummaryIndex &Index,
const lto::InputFile &File) {
- initTMBuilder(TMBuilder, TheModule.getTargetTriple());
+ initTMBuilder(LibraryOptions, TMBuilder, TheModule.getTargetTriple());
auto ModuleCount = Index.modulePaths().size();
auto ModuleIdentifier = TheModule.getModuleIdentifier();
@@ -934,7 +936,7 @@ void ThinLTOCodeGenerator::internalize(Module &TheModule,
* Perform post-importing ThinLTO optimizations.
*/
void ThinLTOCodeGenerator::optimize(Module &TheModule) {
- initTMBuilder(TMBuilder, TheModule.getTargetTriple());
+ initTMBuilder(LibraryOptions, TMBuilder, TheModule.getTargetTriple());
// Optimize now
optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
diff --git a/llvm/tools/gold/gold-plugin.cpp b/llvm/tools/gold/gold-plugin.cpp
index 4e5300be67eb3..1b606e5d199e7 100644
--- a/llvm/tools/gold/gold-plugin.cpp
+++ b/llvm/tools/gold/gold-plugin.cpp
@@ -888,14 +888,14 @@ createLTO(const cl::LibraryOptionsContext &LibraryOptions,
Conf.Options.MCOptions.X86RelaxRelocations = false;
// Toggle function/data sections.
- if (!codegen::getExplicitFunctionSections())
+ if (!codegen::getExplicitFunctionSections(LibraryOptions))
Conf.Options.FunctionSections = SplitSections;
- if (!codegen::getExplicitDataSections())
+ if (!codegen::getExplicitDataSections(LibraryOptions))
Conf.Options.DataSections = SplitSections;
- Conf.MAttrs = codegen::getMAttrs();
+ Conf.MAttrs = codegen::getMAttrs(LibraryOptions);
Conf.RelocModel = RelocationModel;
- Conf.CodeModel = codegen::getExplicitCodeModel();
+ Conf.CodeModel = codegen::getExplicitCodeModel(LibraryOptions);
std::optional<CodeGenOptLevel> CGOptLevelOrNone =
CodeGenOpt::getLevel(options::OptLevel);
assert(CGOptLevelOrNone && "Invalid optimization level");
diff --git a/llvm/tools/llc/lib/NewPMDriver.cpp b/llvm/tools/llc/lib/NewPMDriver.cpp
index 34c26b13139a6..32aa51e7981e4 100644
--- a/llvm/tools/llc/lib/NewPMDriver.cpp
+++ b/llvm/tools/llc/lib/NewPMDriver.cpp
@@ -96,7 +96,8 @@ int llvm::compileModuleWithNewPM(
raw_pwrite_stream *OS = &Out->os();
std::unique_ptr<buffer_ostream> BOS;
- if (codegen::getFileType() != CodeGenFileType::AssemblyFile &&
+ if (codegen::getFileType(Context.getLibraryOptions()) !=
+ CodeGenFileType::AssemblyFile &&
!Out->os().supportsSeeking()) {
BOS = std::make_unique<buffer_ostream>(Out->os());
OS = BOS.get();
diff --git a/llvm/tools/llc/lib/llcdriver.cpp b/llvm/tools/llc/lib/llcdriver.cpp
index e809319a9f0e4..8b758c13c9815 100644
--- a/llvm/tools/llc/lib/llcdriver.cpp
+++ b/llvm/tools/llc/lib/llcdriver.cpp
@@ -312,7 +312,9 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &,
llvm_unreachable("reportError() should not return");
}
-static std::unique_ptr<ToolOutputFile> GetOutputStream(Triple::OSType OS) {
+static std::unique_ptr<ToolOutputFile>
+GetOutputStream(const cl::LibraryOptionsContext &LibraryOptions,
+ Triple::OSType OS) {
// If we don't yet have an output filename, make one.
if (OutputFilename.empty()) {
if (InputFilename == "-")
@@ -327,7 +329,7 @@ static std::unique_ptr<ToolOutputFile> GetOutputStream(Triple::OSType OS) {
else
OutputFilename = std::string(IFN);
- switch (codegen::getFileType()) {
+ switch (codegen::getFileType(LibraryOptions)) {
case CodeGenFileType::AssemblyFile:
OutputFilename += ".s";
break;
@@ -346,7 +348,7 @@ static std::unique_ptr<ToolOutputFile> GetOutputStream(Triple::OSType OS) {
// Decide if we need "binary" output.
bool Binary = false;
- switch (codegen::getFileType()) {
+ switch (codegen::getFileType(LibraryOptions)) {
case CodeGenFileType::AssemblyFile:
break;
case CodeGenFileType::ObjectFile:
@@ -448,7 +450,7 @@ extern "C" int llcMain(int argc, char **argv) {
reportError(std::move(E), RemarksFilename);
LLVMRemarkFileHandle RemarksFile = std::move(*RemarksFileOrErr);
- codegen::MaybeEnableStatistics();
+ codegen::maybeEnableStatistics(Context.getLibraryOptions());
std::string OutputFilename;
if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
@@ -463,7 +465,8 @@ extern "C" int llcMain(int argc, char **argv) {
if (RemarksFile)
RemarksFile->keep();
- return codegen::MaybeSaveStatistics(OutputFilename, "llc");
+ return codegen::maybeSaveStatistics(Context.getLibraryOptions(),
+ OutputFilename, "llc");
}
static bool addPass(PassManagerBase &PM, const char *argv0, StringRef PassName,
@@ -502,9 +505,10 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
std::unique_ptr<Module> M;
std::unique_ptr<MIRParser> MIR;
Triple TheTriple;
- std::string CPUStr = codegen::getCPUStr();
- std::string TuneCPUStr = codegen::getTuneCPUStr();
- std::string FeaturesStr = codegen::getFeaturesStr();
+ std::string CPUStr = codegen::getCPUStr(Context.getLibraryOptions());
+ std::string TuneCPUStr = codegen::getTuneCPUStr(Context.getLibraryOptions());
+ std::string FeaturesStr =
+ codegen::getFeaturesStr(Context.getLibraryOptions());
// Set attributes on functions as loaded from MIR from command line arguments.
auto setMIRFunctionAttributes = [&CPUStr, &TuneCPUStr,
@@ -580,14 +584,16 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
}
};
- std::optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
- std::optional<CodeModel::Model> CM = codegen::getExplicitCodeModel();
+ std::optional<Reloc::Model> RM =
+ codegen::getExplicitRelocModel(Context.getLibraryOptions());
+ std::optional<CodeModel::Model> CM =
+ codegen::getExplicitCodeModel(Context.getLibraryOptions());
const Target *TheTarget = nullptr;
std::unique_ptr<TargetMachine> Target;
// If user just wants to list available options, skip module loading
- auto MAttrs = codegen::getMAttrs();
+ auto MAttrs = codegen::getMAttrs(Context.getLibraryOptions());
bool SkipModule =
CPUStr == "help" || TuneCPUStr == "help" || is_contained(MAttrs, "help");
if (SkipModule) {
@@ -598,8 +604,8 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
// Get the target specific parser.
std::string Error;
- TheTarget =
- TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
+ TheTarget = TargetRegistry::lookupTarget(
+ codegen::getMArch(Context.getLibraryOptions()), TheTriple, Error);
if (!TheTarget) {
WithColor::error(errs(), argv[0]) << Error << "\n";
return 1;
@@ -635,8 +641,8 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
TheTriple.setTriple(sys::getDefaultTargetTriple());
std::string Error;
- TheTarget =
- TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
+ TheTarget = TargetRegistry::lookupTarget(
+ codegen::getMArch(Context.getLibraryOptions()), TheTriple, Error);
if (!TheTarget) {
WithColor::error(errs(), argv[0]) << Error << "\n";
exit(1);
@@ -676,11 +682,13 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
std::optional<CodeModel::Model> CM_IR = M->getCodeModel();
if (!CM && CM_IR)
Target->setCodeModel(*CM_IR);
- if (std::optional<uint64_t> LDT = codegen::getExplicitLargeDataThreshold())
+ if (std::optional<uint64_t> LDT =
+ codegen::getExplicitLargeDataThreshold(Context.getLibraryOptions()))
Target->setLargeDataThreshold(*LDT);
// Figure out where we are going to send the output.
- std::unique_ptr<ToolOutputFile> Out = GetOutputStream(TheTriple.getOS());
+ std::unique_ptr<ToolOutputFile> Out =
+ GetOutputStream(Context.getLibraryOptions(), TheTriple.getOS());
if (!Out)
return 1;
@@ -716,7 +724,7 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
codegen::setFunctionAttributes(*M, CPUStr, FeaturesStr, TuneCPUStr);
for (auto &Plugin : PluginList) {
- CodeGenFileType CGFT = codegen::getFileType();
+ CodeGenFileType CGFT = codegen::getFileType(Context.getLibraryOptions());
if (Plugin.invokePreCodeGenCallback(*M, *Target, CGFT, Out->os())) {
// TODO: Deduplicate code with below and the NewPMDriver.
if (Context.getDiagHandlerPtr()->HasErrors)
@@ -727,7 +735,8 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
}
if (Options.MCOptions.MCRelaxAll &&
- codegen::getFileType() != CodeGenFileType::ObjectFile)
+ codegen::getFileType(Context.getLibraryOptions()) !=
+ CodeGenFileType::ObjectFile)
WithColor::warning(errs(), argv[0])
<< ": warning: ignoring -mc-relax-all because filetype != obj";
@@ -749,7 +758,7 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
return compileModuleWithNewPM(
argv[0], std::move(M), std::move(MIR), std::move(Target),
std::move(Out), std::move(DwoOut), Context, TLII, VK, PassPipeline,
- PluginList, codegen::getFileType());
+ PluginList, codegen::getFileType(Context.getLibraryOptions()));
}
// Build up all of the passes that we want to do to the module.
@@ -765,7 +774,8 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
// so we can memcmp the contents in CompileTwice mode
SmallVector<char, 0> Buffer;
std::unique_ptr<raw_svector_ostream> BOS;
- if ((codegen::getFileType() != CodeGenFileType::AssemblyFile &&
+ if ((codegen::getFileType(Context.getLibraryOptions()) !=
+ CodeGenFileType::AssemblyFile &&
!Out->os().supportsSeeking()) ||
CompileTwice) {
BOS = std::make_unique<raw_svector_ostream>(Buffer);
@@ -832,9 +842,10 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
PM.add(createFreeMachineFunctionPass());
} else {
- if (Target->addPassesToEmitFile(PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
- codegen::getFileType(), NoVerify,
- MMIWP)) {
+ if (Target->addPassesToEmitFile(
+ PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
+ codegen::getFileType(Context.getLibraryOptions()), NoVerify,
+ MMIWP)) {
if (!HasMCErrors)
reportError("target does not support generation of this file type");
}
diff --git a/llvm/tools/lli/lli.cpp b/llvm/tools/lli/lli.cpp
index 263946d1df249..615fdc1bb21a5 100644
--- a/llvm/tools/lli/lli.cpp
+++ b/llvm/tools/lli/lli.cpp
@@ -488,12 +488,12 @@ int main(int argc, char **argv, char * const *envp) {
std::string ErrorMsg;
EngineBuilder builder(std::move(Owner));
- builder.setMArch(codegen::getMArch());
- builder.setMCPU(codegen::getCPUStr());
- builder.setMAttrs(codegen::getFeatureList());
- if (auto RM = codegen::getExplicitRelocModel())
+ builder.setMArch(codegen::getMArch(LibraryOptions));
+ builder.setMCPU(codegen::getCPUStr(LibraryOptions));
+ builder.setMAttrs(codegen::getFeatureList(LibraryOptions));
+ if (auto RM = codegen::getExplicitRelocModel(LibraryOptions))
builder.setRelocationModel(*RM);
- if (auto CM = codegen::getExplicitCodeModel())
+ if (auto CM = codegen::getExplicitCodeModel(LibraryOptions))
builder.setCodeModel(*CM);
builder.setErrorStr(&ErrorMsg);
builder.setEngineKind(ForceInterpreter
@@ -527,7 +527,7 @@ int main(int argc, char **argv, char * const *envp) {
TargetOptions Options =
codegen::getTargetOptions(LibraryOptions, Triple(TargetTriple));
- if (FloatABI::ABIType ABI = codegen::getFloatABIForCalls();
+ if (FloatABI::ABIType ABI = codegen::getFloatABIForCalls(LibraryOptions);
ABI != FloatABI::Default && !Mod->getModuleFlag("float-abi")) {
Mod->addModuleFlag(Module::Error, "float-abi",
MDString::get(Context, FloatABI::getABITypeName(ABI)));
@@ -969,17 +969,17 @@ static int runOrcJIT(const cl::LibraryOptionsContext &LibraryOptions,
if (DL)
Builder.setDataLayout(DL);
- if (!codegen::getMArch().empty())
+ if (!codegen::getMArch(LibraryOptions).empty())
Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(
- codegen::getMArch());
+ codegen::getMArch(LibraryOptions));
Builder.getJITTargetMachineBuilder()
- ->setCPU(codegen::getCPUStr())
- .addFeatures(codegen::getFeatureList())
- .setRelocationModel(codegen::getExplicitRelocModel())
- .setCodeModel(codegen::getExplicitCodeModel());
+ ->setCPU(codegen::getCPUStr(LibraryOptions))
+ .addFeatures(codegen::getFeatureList(LibraryOptions))
+ .setRelocationModel(codegen::getExplicitRelocModel(LibraryOptions))
+ .setCodeModel(codegen::getExplicitCodeModel(LibraryOptions));
- if (auto EmulatedTLS = codegen::getExplicitEmulatedTLS())
+ if (auto EmulatedTLS = codegen::getExplicitEmulatedTLS(LibraryOptions))
Builder.getJITTargetMachineBuilder()->getOptions().EmulatedTLS =
*EmulatedTLS;
diff --git a/llvm/tools/llvm-lto/llvm-lto.cpp b/llvm/tools/llvm-lto/llvm-lto.cpp
index 05f2cebd70588..57ab15ce4928d 100644
--- a/llvm/tools/llvm-lto/llvm-lto.cpp
+++ b/llvm/tools/llvm-lto/llvm-lto.cpp
@@ -662,7 +662,8 @@ class ThinLTOProcessing {
ThinLTOProcessing(const cl::LibraryOptionsContext &LibraryOptions,
const TargetOptions &Options)
: LibraryOptions(LibraryOptions), ThinGenerator(LibraryOptions) {
- ThinGenerator.setCodePICModel(codegen::getExplicitRelocModel());
+ ThinGenerator.setCodePICModel(
+ codegen::getExplicitRelocModel(LibraryOptions));
ThinGenerator.setTargetOptions(Options);
ThinGenerator.setCacheDir(ThinLTOCacheDir);
ThinGenerator.setCachePruningInterval(ThinLTOCachePruningInterval);
@@ -1079,7 +1080,7 @@ int main(int argc, char **argv) {
if (UseDiagnosticHandler)
CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
- CodeGen.setCodePICModel(codegen::getExplicitRelocModel());
+ CodeGen.setCodePICModel(codegen::getExplicitRelocModel(LibraryOptions));
CodeGen.setFreestanding(EnableFreestanding);
CodeGen.setDebugPassManager(DebugPassManager);
@@ -1129,12 +1130,12 @@ int main(int argc, char **argv) {
CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
// Set cpu and attrs strings for the default target/subtarget.
- CodeGen.setCpu(codegen::getMCPU());
+ CodeGen.setCpu(codegen::getMCPU(LibraryOptions));
CodeGen.setOptLevel(OptLevel - '0');
- CodeGen.setAttrs(codegen::getMAttrs());
+ CodeGen.setAttrs(codegen::getMAttrs(LibraryOptions));
- if (auto FT = codegen::getExplicitFileType())
+ if (auto FT = codegen::getExplicitFileType(LibraryOptions))
CodeGen.setFileType(*FT);
if (!OutputFilename.empty()) {
diff --git a/llvm/tools/llvm-lto2/llvm-lto2.cpp b/llvm/tools/llvm-lto2/llvm-lto2.cpp
index c46ac3c3a5868..f124d3d59ade3 100644
--- a/llvm/tools/llvm-lto2/llvm-lto2.cpp
+++ b/llvm/tools/llvm-lto2/llvm-lto2.cpp
@@ -351,12 +351,12 @@ static int run(int argc, char **argv) {
Conf.TimeTraceEnabled = TimeTrace;
Conf.TimeTraceGranularity = TimeTraceGranularity;
}
- Conf.CPU = codegen::getMCPU();
+ Conf.CPU = codegen::getMCPU(LibraryOptions);
Conf.Options = codegen::getTargetOptions(LibraryOptions, Triple());
- Conf.MAttrs = codegen::getMAttrs();
- if (auto RM = codegen::getExplicitRelocModel())
+ Conf.MAttrs = codegen::getMAttrs(LibraryOptions);
+ if (auto RM = codegen::getExplicitRelocModel(LibraryOptions))
Conf.RelocModel = *RM;
- Conf.CodeModel = codegen::getExplicitCodeModel();
+ Conf.CodeModel = codegen::getExplicitCodeModel(LibraryOptions);
Conf.DebugPassManager = DebugPassManager;
@@ -402,7 +402,7 @@ static int run(int argc, char **argv) {
return 1;
}
- if (auto FT = codegen::getExplicitFileType())
+ if (auto FT = codegen::getExplicitFileType(LibraryOptions))
Conf.CGFileType = *FT;
Conf.OverrideTriple = OverrideTriple;
diff --git a/llvm/tools/lto/lto.cpp b/llvm/tools/lto/lto.cpp
index 2f7aaae7104a4..808e6b17ba21e 100644
--- a/llvm/tools/lto/lto.cpp
+++ b/llvm/tools/lto/lto.cpp
@@ -181,7 +181,7 @@ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t)
// Convert the subtarget features into a string to pass to LTOCodeGenerator.
static void lto_add_attrs(lto_code_gen_t cg) {
LTOCodeGenerator *CG = unwrap(cg);
- CG->setAttrs(codegen::getMAttrs());
+ CG->setAttrs(codegen::getMAttrs(LTOContext->getLibraryOptions()));
if (OptLevel < '0' || OptLevel > '3')
report_fatal_error("Optimization level must be between 0 and 3");
diff --git a/llvm/tools/opt/optdriver.cpp b/llvm/tools/opt/optdriver.cpp
index 51af0a9492579..b02d0c0bcb57d 100644
--- a/llvm/tools/opt/optdriver.cpp
+++ b/llvm/tools/opt/optdriver.cpp
@@ -515,9 +515,9 @@ optMain(int argc, char **argv,
}
// If user just wants to list available options, skip module loading.
- auto MAttrs = codegen::getMAttrs();
- std::string CPUStr = codegen::getCPUStr();
- std::string TuneCPUStr = codegen::getTuneCPUStr();
+ auto MAttrs = codegen::getMAttrs(Context.getLibraryOptions());
+ std::string CPUStr = codegen::getCPUStr(Context.getLibraryOptions());
+ std::string TuneCPUStr = codegen::getTuneCPUStr(Context.getLibraryOptions());
bool SkipModule =
CPUStr == "help" || TuneCPUStr == "help" || is_contained(MAttrs, "help");
if (SkipModule) {
@@ -528,8 +528,8 @@ optMain(int argc, char **argv,
TheTriple = Triple(sys::getDefaultTargetTriple());
std::string Error;
- const Target *TheTarget =
- TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
+ const Target *TheTarget = TargetRegistry::lookupTarget(
+ codegen::getMArch(Context.getLibraryOptions()), TheTriple, Error);
if (!TheTarget) {
errs() << argv[0] << ": " << Error << "\n";
return 1;
@@ -542,8 +542,10 @@ optMain(int argc, char **argv,
// Create the target machine just to print the help info. Use unique_ptr
// to avoid a memory leak.
std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
- TheTriple, SkipModuleCPU, codegen::getFeaturesStr(), Options,
- codegen::getExplicitRelocModel(), codegen::getExplicitCodeModel(),
+ TheTriple, SkipModuleCPU,
+ codegen::getFeaturesStr(Context.getLibraryOptions()), Options,
+ codegen::getExplicitRelocModel(Context.getLibraryOptions()),
+ codegen::getExplicitCodeModel(Context.getLibraryOptions()),
GetCodeGenOptLevel()));
if (!TM) {
errs() << argv[0] << ": could not allocate target machine\n";
@@ -574,7 +576,7 @@ optMain(int argc, char **argv,
}
LLVMRemarkFileHandle RemarksFile = std::move(*RemarksFileOrErr);
- codegen::MaybeEnableStatistics();
+ codegen::maybeEnableStatistics(Context.getLibraryOptions());
StringRef ABIName =
mc::getABIName(Context.getLibraryOptions()); // FIXME: Handle module flag.
@@ -709,9 +711,9 @@ optMain(int argc, char **argv,
std::string FeaturesStr;
std::unique_ptr<TargetMachine> TM;
if (ModuleTriple.getArch()) {
- CPUStr = codegen::getCPUStr();
- TuneCPUStr = codegen::getTuneCPUStr();
- FeaturesStr = codegen::getFeaturesStr();
+ CPUStr = codegen::getCPUStr(Context.getLibraryOptions());
+ TuneCPUStr = codegen::getTuneCPUStr(Context.getLibraryOptions());
+ FeaturesStr = codegen::getFeaturesStr(Context.getLibraryOptions());
Expected<std::unique_ptr<TargetMachine>> ExpectedTM =
codegen::createTargetMachineForTriple(
Context.getLibraryOptions(), ModuleTriple, GetCodeGenOptLevel());
@@ -835,7 +837,8 @@ optMain(int argc, char **argv,
EmitModuleHash, EnableDebugify, VerifyDebugInfoPreserve,
EnableProfileVerification, UnifiedLTO))
return 1;
- return codegen::MaybeSaveStatistics(OutputFilename, "opt");
+ return codegen::maybeSaveStatistics(Context.getLibraryOptions(),
+ OutputFilename, "opt");
}
if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
@@ -1021,5 +1024,6 @@ optMain(int argc, char **argv,
if (ThinLinkOut)
ThinLinkOut->keep();
- return codegen::MaybeSaveStatistics(OutputFilename, "opt");
+ return codegen::maybeSaveStatistics(Context.getLibraryOptions(),
+ OutputFilename, "opt");
}
diff --git a/llvm/utils/gn/secondary/llvm/lib/CodeGen/BUILD.gn b/llvm/utils/gn/secondary/llvm/lib/CodeGen/BUILD.gn
index 2f09248ccd5c6..8df2bd3f424f2 100644
--- a/llvm/utils/gn/secondary/llvm/lib/CodeGen/BUILD.gn
+++ b/llvm/utils/gn/secondary/llvm/lib/CodeGen/BUILD.gn
@@ -5,6 +5,11 @@ tablegen("CodeGenOptions") {
args = [ "-gen-opt-parser-defs" ]
}
+tablegen("CodeGenToolOptions") {
+ visibility = [ ":CodeGen" ]
+ args = [ "-gen-opt-parser-defs" ]
+}
+
static_library("CodeGen") {
output_name = "LLVMCodeGen"
public_deps = [
@@ -13,6 +18,7 @@ static_library("CodeGen") {
]
deps = [
":CodeGenOptions",
+ ":CodeGenToolOptions",
"//llvm/include/llvm/CodeGen:GenVT",
"//llvm/include/llvm/CodeGen:RegAllocEvictModels",
"//llvm/lib/Analysis",
diff --git a/utils/bazel/llvm-project-overlay/llvm/BUILD.bazel b/utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
index 5fc8793314c39..d1853e5d1cec8 100644
--- a/utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
@@ -2586,6 +2586,15 @@ gentbl_cc_library(
deps = [":OptParserTdFiles"],
)
+gentbl_cc_library(
+ name = "CodeGenToolOptionsTableGen",
+ strip_include_prefix = "lib/CodeGen",
+ tbl_outs = {"lib/CodeGen/CodeGenToolOptions.inc": ["-gen-opt-parser-defs"]},
+ tblgen = ":llvm-min-tblgen",
+ td_file = "lib/CodeGen/CodeGenToolOptions.td",
+ deps = [":OptParserTdFiles"],
+)
+
gentbl_cc_library(
name = "SelectionDAGOptionsTableGen",
strip_include_prefix = "lib/CodeGen/SelectionDAG",
@@ -2666,6 +2675,7 @@ cc_library(
":CFGuard",
":CGData",
":CodeGenOptionsTableGen",
+ ":CodeGenToolOptionsTableGen",
":CodeGenTypes",
":Core",
":DebugInfoCodeView",
More information about the cfe-commits
mailing list