10 个版本
0.1.9 | 2023年10月26日 |
---|---|
0.1.8 | 2023年9月24日 |
0.1.4 | 2023年7月13日 |
0.1.1 | 2023年6月28日 |
#102 in 编程语言
1.5MB
39K SLoC
b3-rs
基于 WebKit 的 B3 空骨头后端的后端。我制作它是为了教育目的。
用法
查看示例和 src/tests.rs
。
以下是一个迭代阶乘生成器
// imports ARGUMENT_GPR0
use b3::macroassembler::jit::gpr_info::*;
fn main() {
let opts = b3::Options::default();
let mut proc = b3::Procedure::new(opts);
// Create entry block. The argument to `add_block` is block frequency.
// Blocks with different frequences are ordered differently. By default
// they are recalculated before lowering to Assembly IR.
// set `opts.estimate_static_execution_counts` to `false` to use user provided frequency.
let entry = proc.add_block(1.0);
let mut builder = b3::BasicBlockBuilder::new(&mut proc, entry);
// Argument management is offloaded to client code. Here we load argument from first GPR argument register,
// it is RDI on x86-64
let number = builder.argument(b3::Reg::new_gpr(ARGUMENT_GPR0), b3::Type::Int32);
// Declare variables. They are automatically converted to SSA form.
let i = builder.procedure.add_variable(b3::Type::Int32);
let factorial = builder.procedure.add_variable(b3::Type::Int32);
// Create blocks for `for` loop.
let for_header = builder.procedure.add_block(1.0);
let for_body = builder.procedure.add_block(1.0);
let for_exit = builder.procedure.add_block(1.0);
let one = builder.const32(1);
builder.var_set(factorial, one);
builder.var_set(i, one);
builder.jump(Some(for_header));
builder.block = for_header;
let i_value = builder.var_get(i);
let cmp = builder.binary(b3::Opcode::LessEqual, i_value, number);
// Conditional branch.
builder.branch(cmp, for_body, (for_exit, b3::Frequency::Normal));
builder.block = for_body;
let i_value = builder.var_get(i);
let factorial_value = builder.var_get(factorial);
let mul = builder.binary(b3::Opcode::Mul, i_value, factorial_value);
builder.var_set(factorial, mul);
let i_value = builder.var_get(i);
let one = builder.const32(1);
let add = builder.binary(b3::Opcode::Add, i_value, one);
builder.var_set(i, add);
builder.jump(Some(for_header));
builder.block = for_exit;
let factorial_value = builder.var_get(factorial);
builder.return_(Some(factorial_value));
// Compiles B3 IR down to machine code.
let compilation = b3::compile(proc);
// use `entrypoint(0)` to get first entrypoint of code.
// NOTE: Multiple entrypoints are not yet supported.
let func: extern "C" fn(i32) -> i32 = unsafe { std::mem::transmute(compilation.entrypoint(0)) };
assert_eq!(func(5), 120);
}
贡献者
- PROMETHIA - 帮助修复 UB 并将 B3 移植到稳定工具链。
许可
原始 B3 代码属于 WebKit,并使用 BSD-2 许可证。
依赖
~3–21MB
~341K SLoC