Expand description
A host’s IR in and out: its instructions translated into expressions (Semantics,
Lowering), and results translated back into instructions (Raise), without text.
A compiler describes what each of its instructions computes once, as a Semantics
implementation, in Rust or as a Template in the expression syntax, read at run time. A
Lowering then turns a function (or a block) into expressions: it maps the host’s values
to expressions, and makes a symbol for each value defined elsewhere (a parameter, a load, a
call), with the known bits the host has of it if it has any. After simplifying,
Lowering::raise turns a result back into instructions: a node some host value already
computes is that value (equal expressions are equal values, so this is value numbering),
and only the nodes no value computes are emitted, operands first, through the host’s
Raise.
use bitwright::engine::{Engine, Strategy};
use bitwright::translate::{Lowering, Raise, Semantics, Template};
use bitwright::{Context, Error, Expr, View, Width};
// A toy IR: SSA values are indices.
enum Op { Add, Sub, And, Or }
struct Inst { op: Op, dst: u32, a: u32, b: u32 }
impl Semantics for Inst {
type Value = u32;
fn result(&self) -> Option<u32> { Some(self.dst) }
fn lower(&self, lw: &mut Lowering<'_, u32>) -> Result<Expr, Error> {
let (a, b) = (lw.value(self.a, Width::W32)?, lw.value(self.b, Width::W32)?);
let cx = lw.context();
match self.op {
Op::Add => cx.add(a, b),
Op::Sub => cx.sub(a, b),
Op::And => cx.and(a, b),
Op::Or => cx.or(a, b),
}
}
}
// Emitting back: new instructions get new value numbers.
struct Emit { next: u32, out: Vec<String> }
impl Raise for Emit {
type Value = u32;
fn emit(&mut self, cx: &Context, _: Expr, node: &View, ops: &[u32]) -> Result<u32, Error> {
let dst = self.next;
self.next += 1;
let text = match node {
View::Bin(op, ..) => format!("%{dst} = {op:?} %{}, %{}", ops[0], ops[1]),
other => return Err(Error::Unsupported(format!("{other:?}"))),
};
self.out.push(text);
Ok(dst)
}
}
let engine = Engine::builder().builtin().strategy(Strategy::compile()).build()?;
let mut cx = Context::new();
let mut lw = Lowering::new(&mut cx);
// %2 = and %0, %1; %3 = or %0, %1; %4 = add %2, %3; %5 = sub %4, %1
let body = [
Inst { op: Op::And, dst: 2, a: 0, b: 1 },
Inst { op: Op::Or, dst: 3, a: 0, b: 1 },
Inst { op: Op::Add, dst: 4, a: 2, b: 3 },
Inst { op: Op::Sub, dst: 5, a: 4, b: 1 },
];
lw.lower_all(&body)?;
let v5 = lw.get(5).unwrap();
let out = engine.simplify(lw.context(), v5)?;
// (x & y) + (x | y) - y is x: the parameter %0 itself, nothing to emit.
let mut emit = Emit { next: 6, out: Vec::new() };
assert_eq!(lw.raise(out.expr, &mut emit)?, 0);
assert!(emit.out.is_empty());
// Semantics as text, read at run time: an absolute difference this IR has as one
// instruction.
let absdiff = Template::new("select(a <u b, b - a, a - b)", &["a", "b"])?;
let (a, b) = (lw.value(0, Width::W32)?, lw.value(1, Width::W32)?);
let d = absdiff.instantiate(lw.context(), &[a, b])?;
assert_eq!(lw.context().width(d)?, Width::W32);Structs§
- Lowered
- A
Lowering’s values detached from its context: what a host keeps between the calls that lower a function, when the context is used on its own in between (a language binding, which cannot keep a borrow of it).attachit to the same context to go on; with another, its expressions are foreign handles, rejected wherever they are used. - Lowering
- A function (or block) of the host’s IR being translated into expressions of a context: the expression of every host value it has seen, and a symbol for every value defined outside.
- Template
- An instruction’s semantics as an expression over named parameters, in the expression
syntax, read at run time:
select(a <s b, a, b),(a >>u k) | (a << (0 - k)). The parameters take the widths of the operands it is instantiated with, and a literal whose width the expression does not fix takes the widest operand’s. It is compiled once per combination of widths and then instantiated by copying, with no parsing. It can be shared between threads.
Traits§
- Raise
- Turns expression nodes back into the host’s instructions (see
Lowering::raise). - Semantics
- What an instruction of the host’s IR computes, as an expression.