8000 Add an independent LLVM codegen optimization level by romart · Pull Request #5573 · google/xls · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions xls/jit/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,24 @@ cc_library(
],
)

cc_test(
name = "llvm_compiler_test",
srcs = ["llvm_compiler_test.cc"],
deps = [
":aot_compiler",
":jit_evaluator_options",
":llvm_compiler",
":orc_jit",
"//xls/common:xls_gunit_main",
"//xls/common/status:matchers",
"@abseil-cpp//absl/status",
"@abseil-cpp//absl/status:status_matchers",
"@googletest//:gtest",
"@llvm-project//llvm:Support",
"@llvm-project//llvm:Target",
],
)

cc_library(
name = "jit_emulated_tls",
srcs = ["jit_emulated_tls.cc"],
Expand Down
7 changes: 7 additions & 0 deletions xls/jit/aot_compiler.cc
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ namespace xls {
// static
absl::StatusOr<std::unique_ptr<AotCompiler>> AotCompiler::Create(
const JitEvaluatorOptions& jit_options) {
if (jit_options.codegen_opt_level() < 0 ||
jit_options.codegen_opt_level() > 3) {
return absl::InvalidArgumentError(
"LLVM codegen optimization level must be between 0 and 3");
}
LlvmCompiler::InitializeLlvm();
auto compiler = std::unique_ptr<AotCompiler>(new AotCompiler(jit_options));
XLS_RETURN_IF_ERROR(compiler->Init());
Expand Down Expand Up @@ -96,6 +101,8 @@ AotCompiler::CreateTargetMachine() {
};

error_or_target_builder->setRelocationModel(llvm::Reloc::Model::PIC_);
error_or_target_builder->setCodeGenOptLevel(
static_cast<llvm::CodeGenOptLevel>(jit_options_.codegen_opt_level()));
error_or_target_builder->setCodeModel(
error_or_target_builder->getTargetTriple().isAArch64()
? llvm::CodeModel::Large
Expand Down
16 changes: 9 additions & 7 deletions xls/jit/block_jit.cc
Original file line number Diff line number Diff line change
Expand Up @@ -337,21 +337,23 @@ BlockJit::InterfaceMetadata::CreateFromAotEntrypoint(
}

absl::StatusOr<std::unique_ptr<BlockJit>> BlockJit::Create(
Block* block, bool support_observer_callbacks, int64_t opt_level) {
Block* block, bool support_observer_callbacks, int64_t opt_level,
int64_t codegen_opt_level) {
XLS_ASSIGN_OR_RETURN(BlockElaboration elab,
BlockElaboration::Elaborate(block));
return BlockJit::Create(elab, support_observer_callbacks, opt_level);
return BlockJit::Create(elab, support_observer_callbacks, opt_level,
codegen_opt_level);
}

absl::StatusOr<std::unique_ptr<BlockJit>> BlockJit::Create(
const BlockElaboration& elab, bool support_observer_callbacks,
int64_t opt_level) {
int64_t opt_level, int64_t codegen_opt_level) {
Block* block;
XLS_ASSIGN_OR_RETURN(
std::unique_ptr<OrcJit> orc_jit,
OrcJit::Create(
opt_level,
/*include_observer_callbacks=*/support_observer_callbacks));
OrcJit::Create(opt_level,
/*include_observer_callbacks=*/support_observer_callbacks,
/*jit_observer=*/nullptr, codegen_opt_level));
XLS_ASSIGN_OR_RETURN(auto data_layout, orc_jit->CreateDataLayout());
auto jit_runtime =
std::make_unique<JitRuntime>(data_layout, *orc_jit->GetContext());
Expand Down Expand Up @@ -886,7 +888,7 @@ JitBlockEvaluator::MakeNewContinuation(
auto jit,
BlockJit::Create(elaboration,
/*support_observer_callbacks=*/supports_observer_,
opt_level_));
opt_level_, codegen_opt_level_));
auto jit_cont = jit->NewContinuation(sample_time);
XLS_RETURN_IF_ERROR(jit_cont->SetRegisters(initial_registers));
return std::make_unique<BlockContinuationJitWrapper>(std::move(jit_cont),
Expand Down
13 changes: 9 additions & 4 deletions xls/jit/block_jit.h
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,12 @@ class BlockJit {

static absl::StatusOr<std::unique_ptr<BlockJit>> Create(
Block* block, bool support_observer_callbacks = false,
int64_t opt_level = LlvmCompiler::kDefaultOptLevel);
int64_t opt_level = LlvmCompiler::kDefaultOptLevel,
int64_t codegen_opt_level = LlvmCompiler::kDefaultCodegenOptLevel);
static absl::StatusOr<std::unique_ptr<BlockJit>> Create(
const BlockElaboration& elab, bool support_observer_callbacks = false,
int64_t opt_level = LlvmCompiler::kDefaultOptLevel);
int64_t opt_level = LlvmCompiler::kDefaultOptLevel,
int64_t codegen_opt_level = LlvmCompiler::kDefaultCodegenOptLevel);

static absl::StatusOr<std::unique_ptr<BlockJit>> CreateFromAot(
const AotEntrypointProto& entrypoint,
Expand Down Expand Up @@ -305,10 +307,12 @@ class JitBlockEvaluator : public BlockEvaluator {
public:
explicit constexpr JitBlockEvaluator(
bool supports_observer = false,
int64_t opt_level = LlvmCompiler::kDefaultOptLevel)
int64_t opt_level = LlvmCompiler::kDefaultOptLevel,
int64_t codegen_opt_level = LlvmCompiler::kDefaultCodegenOptLevel)
: BlockEvaluator(supports_observer ? "ObservableJit" : "Jit"),
supports_observer_(supports_observer),
opt_level_(opt_level) {}
opt_level_(opt_level),
codegen_opt_level_(codegen_opt_level) {}
absl::StatusOr<JitRuntime*> GetRuntime(BlockContinuation* cont) const;

protected:
Expand All @@ -320,6 +324,7 @@ class JitBlockEvaluator : public BlockEvaluator {
private:
bool supports_observer_;
int64_t opt_level_;
int64_t codegen_opt_level_;
};

inline constexpr JitBlockEvaluator kJitBlockEvaluator(false);
Expand Down
3 changes: 2 additions & 1 deletion xls/jit/function_jit.cc
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@ absl::StatusOr<std::unique_ptr<FunctionJit>> FunctionJit::CreateInternal(
XLS_ASSIGN_OR_RETURN(auto orc_jit,
OrcJit::Create(jit_options.opt_level(),
jit_options.include_observer_callbacks(),
jit_options.jit_observer()));
jit_options.jit_observer(),
jit_options.codegen_opt_level()));
XLS_ASSIGN_OR_RETURN(llvm::DataLayout data_layout,
orc_jit->CreateDataLayout());
auto jit_runtime =
Expand Down
28 changes: 28 additions & 0 deletions xls/jit/function_jit_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,34 @@ absl::StatusOr<Value> RunJitNoEvents(FunctionJit* jit,
return InterpreterResultToStatusOrValue(result);
}

TEST(FunctionJitTest, WideAddWithIndependentCodegenOptimizationLevel) {
Package p("wide_add");
FunctionBuilder b("wide_add", &p);
BValue x = b.Param("x", p.GetBitsType(129));
BValue y = b.Param("y", p.GetBitsType(129));
XLS_ASSERT_OK_AND_ASSIGN(Function * function,
b.BuildWithReturnValue(b.Add(x, y)));
for (int64_t ir_level : {0, 3}) {
for (int64_t codegen_level : {0, 1, 2, 3}) {
SCOPED_TRACE(ir_level);
SCOPED_TRACE(codegen_level);
XLS_ASSERT_OK_AND_ASSIGN(
auto jit,
FunctionJit::Create(function, EvaluatorOptions(),
JitEvaluatorOptions()
.set_opt_level(ir_level)
.set_codegen_opt_level(codegen_level)));
for (const Bits& x_value :
{UBits(0, 129), UBits(42, 129), bits_ops::Not(UBits(0, 129))}) {
XLS_ASSERT_OK_AND_ASSIGN(
Value result,
RunJitNoEvents(jit.get(), {Value(x_value), Value(UBits(1, 129))}));
EXPECT_EQ(result, Value(bits_ops::Add(x_value, UBits(1, 129))));
}
}
}
}

TEST(FunctionJitTest, MsanCatchesUninitializedInputs) {
#ifndef ABSL_HAVE_MEMORY_SANITIZER
GTEST_SKIP() << "Msan is not linked";
Expand Down
11 changes: 10 additions & 1 deletion xls/jit/jit_evaluator_options.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,21 @@ class JitEvaluatorOptions {
public:
JitEvaluatorOptions() = default;

// The LLVM optimization level.
// The LLVM IR optimization level (0 through 3).
JitEvaluatorOptions& set_opt_level(int64_t value) {
opt_level_ = value;
return *this;
}
int64_t opt_level() const { return opt_level_; }

// The LLVM machine code optimization level, independent of opt_level():
// 0=None, 1=Less, 2=Default, 3=Aggressive.
JitEvaluatorOptions& set_codegen_opt_level(int64_t value) {
codegen_opt_level_ = value;
return *this;
}
int64_t codegen_opt_level() const { return codegen_opt_level_; }

// Additional text to append to symbol names to ensure no collisions
JitEvaluatorOptions& set_symbol_salt(std::string value) {
symbol_salt_ = std::move(value);
Expand Down Expand Up @@ -91,6 +99,7 @@ class JitEvaluatorOptions {

private:
int64_t opt_level_ = LlvmCompiler::kDefaultOptLevel;
int64_t codegen_opt_level_ = LlvmCompiler::kDefaultCodegenOptLevel;
std::string symbol_salt_;
bool include_observer_callbacks_ = false;
bool include_msan_ = false;
Expand Down
7 changes: 4 additions & 3 deletions xls/jit/jit_proc_runtime.cc
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,10 @@ absl::StatusOr<std::unique_ptr<SerialProcRuntime>> CreateRuntime(
// We use the compiler to know the data layout.
XLS_ASSIGN_OR_RETURN(
std::unique_ptr<OrcJit> comp,
OrcJit::Create(
jit_options.opt_level(),
/*include_observer_callbacks=*/options.support_observers()));
OrcJit::Create(jit_options.opt_level(),
/*include_observer_callbacks=*/options.support_observers(),
/*jit_observer=*/nullptr,
jit_options.codegen_opt_level()));
XLS_ASSIGN_OR_RETURN(llvm::DataLayout layout, comp->CreateDataLayout());
// Create a queue manager for the queues. This factory verifies that there an
// receive only queue for every receive only channel.
Expand Down
2 changes: 2 additions & 0 deletions xls/jit/llvm_compiler.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ class OrcJit;
class LlvmCompiler {
public:
static constexpr int64_t kDefaultOptLevel = 3;
// LLVM's backend default is independent of the IR optimization level.
static constexpr int64_t kDefaultCodegenOptLevel = 2;
static void InitializeLlvm();

virtual ~LlvmCompiler() = default;
Expand Down
78 changes: 78 additions & 0 deletions xls/jit/llvm_compiler_test.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright 2026 The XLS Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "xls/jit/llvm_compiler.h"

#include <cstdint>
#include <initializer_list>
#include <limits>

#include "absl/status/status.h"
#include "absl/status/status_matchers.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "llvm/include/llvm/Support/CodeGen.h"
#include "llvm/include/llvm/Target/TargetMachine.h"
#include "xls/common/status/matchers.h"
#include "xls/jit/aot_compiler.h"
#include "xls/jit/jit_evaluator_options.h"
#include "xls/jit/orc_jit.h"

namespace xls {
namespace {

TEST(LlvmCompilerTest, IndependentCodegenOptimizationLevel) {
for (int64_t ir_level : {0, 3}) {
for (int64_t codegen_level : {0, 1, 2, 3}) {
SCOPED_TRACE(ir_level);
SCOPED_TRACE(codegen_level);
XLS_ASSERT_OK_AND_ASSIGN(
auto jit, OrcJit::Create(ir_level, false, nullptr, codegen_level));
XLS_ASSERT_OK_AND_ASSIGN(auto jit_target, jit->CreateTargetMachine());
EXPECT_EQ(jit_target->getOptLevel(),
static_cast<llvm::CodeGenOptLevel>(codegen_level));
EXPECT_EQ(jit->opt_level(), ir_level);

XLS_ASSERT_OK_AND_ASSIGN(
auto aot,
AotCompiler::Create(JitEvaluatorOptions()
.set_opt_level(ir_level)
.set_codegen_opt_level(codegen_level)));
XLS_ASSERT_OK_AND_ASSIGN(auto aot_target, aot->CreateTargetMachine());
EXPECT_EQ(aot_target->getOptLevel(),
static_cast<llvm::CodeGenOptLevel>(codegen_level));
EXPECT_EQ(aot->opt_level(), ir_level);
}
}
}

TEST(LlvmCompilerTest, RejectInvalidCodegenOptimizationLevel) {
const int64_t invalid_levels[] = {-1, 4, std::numeric_limits<int64_t>::max()};
for (int64_t level : invalid_levels) {
EXPECT_THAT(OrcJit::Create(3, false, nullptr, level),
absl_testing::StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(
AotCompiler::Create(JitEvaluatorOptions().set_codegen_opt_level(level)),
absl_testing::StatusIs(absl::StatusCode::kInvalidArgument));
}
}

TEST(LlvmCompilerTest, PreserveDefaultCodegenOptimizationLevel) {
XLS_ASSERT_OK_AND_ASSIGN(auto jit, OrcJit::Create());
XLS_ASSERT_OK_AND_ASSIGN(auto target, jit->CreateTargetMachine());
EXPECT_EQ(target->getOptLevel(), llvm::CodeGenOptLevel::Default);
}

} // namespace
} // namespace xls
18 changes: 13 additions & 5 deletions xls/jit/orc_jit.cc
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ class UnsupportedExecutorProcessControl
} // namespace

OrcJit::OrcJit(int64_t opt_level, bool include_msan,
bool include_observer_callbacks)
bool include_observer_callbacks, int64_t codegen_opt_level)
: LlvmCompiler(opt_level, include_msan, include_observer_callbacks,
/*include_llvm_coverage=*/false),
context_(std::make_unique<llvm::LLVMContext>()),
Expand All @@ -127,7 +127,8 @@ OrcJit::OrcJit(int64_t opt_level, bool include_msan,
return std::make_unique<llvm::SectionMemoryManager>(
/*UnownedMM=*/nullptr, /*ReserveAlloc=*/true);
}),
dylib_(execution_session_.createBareJITDylib("main")) {}
dylib_(execution_session_.createBareJITDylib("main")),
codegen_opt_level_(codegen_opt_level) {}

OrcJit::~OrcJit() {
if (auto err = execution_session_.endSession()) {
Expand Down Expand Up @@ -188,15 +189,20 @@ llvm::Expected<llvm::orc::ThreadSafeModule> OrcJit::Optimizer(
}

absl::StatusOr<std::unique_ptr<OrcJit>> OrcJit::Create(
int64_t opt_level, bool include_observer_callbacks, JitObserver* observer) {
int64_t opt_level, bool include_observer_callbacks, JitObserver* observer,
int64_t codegen_opt_level) {
if (codegen_opt_level < 0 || codegen_opt_level > 3) {
return absl::InvalidArgumentError(
"LLVM codegen optimization level must be between 0 and 3");
}
LlvmCompiler::InitializeLlvm();
#ifdef ABSL_HAVE_MEMORY_SANITIZER
constexpr bool kHasMsan = true;
#else
constexpr bool kHasMsan = false;
#endif
std::unique_ptr<OrcJit> jit = absl::WrapUnique(
new OrcJit(opt_level, kHasMsan, include_observer_callbacks));
std::unique_ptr<OrcJit> jit = absl::WrapUnique(new OrcJit(
opt_level, kHasMsan, include_observer_callbacks, codegen_opt_level));
jit->SetJitObserver(observer);
XLS_RETURN_IF_ERROR(jit->Init());
return std::move(jit);
Expand All @@ -213,6 +219,8 @@ OrcJit::CreateTargetMachine() {
}

error_or_target_builder->setRelocationModel(llvm::Reloc::Model::PIC_);
error_or_target_builder->setCodeGenOptLevel(
static_cast<llvm::CodeGenOptLevel>(codegen_opt_level_));
auto error_or_target_machine = error_or_target_builder->createTargetMachine();
if (!error_or_target_machine) {
return absl::InternalError(
Expand Down
16 changes: 9 additions & 7 deletions xls/jit/orc_jit.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@ class OrcJit : public LlvmCompiler {

absl::StatusOr<OrcJit*> AsOrcJit() override { return this; }

// Create an LLVM orc jit. This can be used by the AOT generator to manually
// control whether asan calls should be included. Users other than the AOT
// compiler should use the 3-argument version above. Passing nullopt to
// emit_msan directs the jit to use MSAN if the running binary is MSAN and
// vice-versa.
// Create an LLVM orc jit. opt_level controls IR optimization;
// codegen_opt_level independently controls machine code optimization
// (0=None, 1=Less, 2=Default, 3=Aggressive). Both accept values from 0 to 3.
// MSAN instrumentation matches the running binary.
static absl::StatusOr<std::unique_ptr<OrcJit>> Create(
int64_t opt_level = kDefaultOptLevel,
bool include_observer_callbacks = false,
JitObserver* jit_observer = nullptr);
JitObserver* jit_observer = nullptr,
int64_t codegen_opt_level = LlvmCompiler::kDefaultCodegenOptLevel);

void SetJitObserver(JitObserver* o) { jit_observer_ = o; }

Expand All @@ -79,7 +79,8 @@ class OrcJit : public LlvmCompiler {
absl::Status InitInternal() override;

private:
OrcJit(int64_t opt_level, bool include_msan, bool include_observer_callbacks);
OrcJit(int64_t opt_level, bool include_msan, bool include_observer_callbacks,
int64_t codegen_opt_level);

// Method which optimizes the given module. Used within the JIT to form an IR
// transform layer.
Expand All @@ -96,6 +97,7 @@ class OrcJit : public LlvmCompiler {
std::unique_ptr<llvm::orc::IRTransformLayer> transform_layer_;

JitObserver* jit_observer_ = nullptr;
int64_t codegen_opt_level_;
};

} // namespace xls
Expand Down
Loading
0