From ded5fd88a6fe318888023c553f47d08485e8ff47 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Tue, 17 Nov 2026 15:24:58 +0000 Subject: [PATCH 1/6] clazel-lir: LIR syntax and semantics (jit.md J.5) A new tier-0 crate with the abstract syntax (types, values, structured instructions, bounds_check, region loads and stores, exit) and a fuelled big-step semantics as a spec fn, transcribing the Wasm core 2.0 instructions it mirrors. Modelling choices are listed at the top of spec.rs. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 7 + crates/clazel-lir/Cargo.toml | 24 + crates/clazel-lir/src/lib.rs | 18 + crates/clazel-lir/src/spec.rs | 818 ++++++++++++++++++++++++++++++++ crates/clazel-lir/src/syntax.rs | 259 ++++++++++ xtask/src/status.rs | 2 + 6 files changed, 1128 insertions(+) create mode 100644 crates/clazel-lir/Cargo.toml create mode 100644 crates/clazel-lir/src/lib.rs create mode 100644 crates/clazel-lir/src/spec.rs create mode 100644 crates/clazel-lir/src/syntax.rs diff --git a/Cargo.lock b/Cargo.lock index 8d70e204a..23a878b68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -435,6 +435,13 @@ dependencies = [ "rustybuzz", ] +[[package]] +name = "clazel-lir" +version = "0.0.0" +dependencies = [ + "vstd", +] + [[package]] name = "clazel-mime" version = "0.0.0" diff --git a/crates/clazel-lir/Cargo.toml b/crates/clazel-lir/Cargo.toml new file mode 100644 index 000000000..c0b8c070a --- /dev/null +++ b/crates/clazel-lir/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "clazel-lir" +version = "0.0.0" +edition.workspace = true +license.workspace = true +publish.workspace = true +description = "LIR, the JIT's low-level IR shaped like WebAssembly (docs/phases/jit.md item J.5): syntax, typing and semantics. No back end and no front end exist yet." + +[dependencies] +vstd = "=0.0.0-2026-10-04-0306" + +# Verification tier (docs/VERIFICATION.md). `tier` is what is proven about the +# shipped code today: nothing, since this crate holds only the language's +# definition (syntax, semantics, typing) and proofs about it. `target-tier` is +# what jit.md's "Crates" table sets for the finished crate. +[package.metadata.clazel] +tier = 0 +target-tier = 2 + +[package.metadata.verus] +verify = true + +[lints] +workspace = true diff --git a/crates/clazel-lir/src/lib.rs b/crates/clazel-lir/src/lib.rs new file mode 100644 index 000000000..bcd59a0ce --- /dev/null +++ b/crates/clazel-lir/src/lib.rs @@ -0,0 +1,18 @@ +//! LIR, the JIT's low-level intermediate representation (docs/phases/jit.md +//! item J.5): syntax, semantics and typing, shaped like WebAssembly. +//! +//! - [`syntax`]: types, values and instructions; +//! - [`spec`]: the semantics, `spec fn eval`, with the modelling choices +//! listed at its top; +//! - [`typing`]: the typing judgment and the soundness theorem; +//! - [`examples`]: small programs with proven properties. +//! +//! There is no back end and no front end. The crate depends on no other +//! browser crate and has no JavaScript-specific type (jit.md, "The +//! instruction-set layer knows nothing of JS"). +//! +//! Tier: see `[package.metadata.clazel]` in `Cargo.toml` and +//! `docs/VERIFICATION.md`. + +pub mod spec; +pub mod syntax; diff --git a/crates/clazel-lir/src/spec.rs b/crates/clazel-lir/src/spec.rs new file mode 100644 index 000000000..7ff764c9e --- /dev/null +++ b/crates/clazel-lir/src/spec.rs @@ -0,0 +1,818 @@ +//! LIR's semantics (docs/phases/jit.md item J.5): a big-step, fuelled +//! interpreter written as a `spec fn`, [`eval`]. +//! +//! It transcribes the numeric, variable, parametric, memory and control +//! instructions of the WebAssembly core specification, release 2.0 +//! ("Execution", §4.3 numeric operators and §4.4 instructions). The Wasm +//! specification is **not vendored**, and the section numbers below are +//! from the 2.0 release as remembered by the author: they name the +//! instruction or operator exactly, and a reviewer should check the number +//! against the text. Wasm's own presentation is a small-step reduction +//! relation on configurations with administrative instructions (`label`, +//! `frame`); the first modelling choice below explains the change. +//! +//! # Modelling choices +//! +//! Everything here where the *form* differs from the standard, or where LIR +//! differs from Wasm in *meaning*: +//! +//! 1. **Big-step with fuel instead of small-step reduction.** Wasm §4.4.8 +//! reduces `label` administrative instructions; here a structured +//! instruction evaluates its body and then handles the outcome. A branch +//! is the outcome `Branch(l, state)`, and the enclosing `block`, `loop` or +//! `if` that is label `l` catches it (§4.4.8, `br l` with label `L`: "pop +//! the top `n` values, discard the rest of the label's stack, push them, +//! continue after the label, or at its start for a `loop`"). Divergence is +//! `OutOfFuel`: every recursive call spends one unit of fuel, so `eval` is +//! a total function, and "the program runs for ever" is "`OutOfFuel` at +//! every fuel". Results are deterministic by construction. +//! 2. **A block's body runs on a fresh stack holding only its parameters.** +//! Wasm's label records the stack height; here the outer values below the +//! parameters are set aside (`base`) and put back, below the results, +//! when the block ends or is branched to. The meaning is the same +//! because Wasm's validation forbids a body from reaching below its +//! parameters. +//! 3. **No function calls, no tables, no globals, no `memory.grow`.** There +//! is one function body, run by [`run`], whose label `0` (outermost) is +//! "return". Wasm's trap is the outcome `Exit` (jit.md: services and +//! traps are exits); an `exit` is also LIR's only way to stop other than +//! falling off the end or a return. +//! 4. **Memory is regions.** The layout (a `Seq`, each a base and a +//! bound) is a constant parameter of the semantics, not part of the +//! state: the blob is entered once with a fixed table (jit.md: "Regions +//! are passed afresh at each entry"). Memory is a map from addresses to +//! bytes, with absent bytes reading as 0, which is Wasm's initial memory +//! content; Wasm §4.3.1 stores integers and floats little-endian, as +//! here. A load or store whose region does not exist, or whose +//! `index + size` exceeds the bound, is `Stuck`: a semantics has no +//! meaning for it, and the typing proves it never happens. Wasm would +//! trap; LIR code is required to have checked (`bounds_check`) before. +//! 5. **`bounds_check` and the index mask are LIR's, not Wasm's.** After a +//! passing check, the address is `base + masked(bound, i)`, where +//! `masked(bound, i) = if i < bound { i } else { 0 }` (jit.md: "Indexes +//! are masked after the check"). Under a passing check with `size > 0` +//! the mask is the identity; it is in the semantics so that the back +//! end's masking is a refinement of it, not an addition to it. +//! 6. **`f64` arithmetic is uninterpreted.** `add`, `sub`, `mul`, `div`, +//! `sqrt` and the integer-to-float conversions are the uninterpreted +//! functions [`f64_add`] and so on, over bit patterns. IEEE 754 rounding +//! is not transcribed (the JS engine's `spec` does the same, and the +//! hardware semantics in `clazel-x64` and `clazel-a64` is what the back +//! ends are proven against). Wasm leaves the sign and payload of a NaN +//! result nondeterministic (§4.3.3, `nans`); one fixed function is a +//! refinement of that, and no more. Comparison, `neg` and `abs` are +//! exact (§4.3.3: `feq`, `flt`..., `fneg`, `fabs`), on the bits. +//! 7. **Integers are `u32` and `u64`**, signedness is in the operator, as +//! in Wasm (§4.3.1 "Integers", `signed_N`). Arithmetic is on `int` +//! followed by reduction modulo `2^N`, which is the definition of +//! `iadd`, `isub`, `imul` (§4.3.2). +//! 8. **`select` is the untyped form**, and `if` takes its condition from +//! the stack of the *enclosing* body, as Wasm does. + +/// The syntax, re-exported so that every module sees one namespace. +pub use crate::syntax::*; +#[allow(unused_imports)] +use vstd::prelude::*; + +verus! { + +/// `2^n`: vstd's `pow2`, under a short name. +pub open spec fn pow2(n: nat) -> nat { + vstd::arithmetic::power2::pow2(n) +} + +// --------------------------------------------------------------------- +// Layout and memory +// --------------------------------------------------------------------- + +/// A region: where it starts in the address space and how many bytes it has. +pub struct Region { + /// The address of the region's first byte. + pub base: nat, + /// The region's size in bytes. + pub bound: nat, +} + +/// The table of regions a blob is entered with (jit.md: "a fixed table of +/// (base, bound) pairs"). +pub type Layout = Seq; + +/// Every region lies below `2^64`, so every address the semantics forms is a +/// machine address. +pub open spec fn layout_wf(lay: Layout) -> bool { + forall|r: int| 0 <= r < lay.len() ==> (#[trigger] lay[r]).base + lay[r].bound <= 0x1_0000_0000_0000_0000 +} + +/// Byte-addressed memory. Absent addresses read as 0. +pub type Mem = Map; + +/// The byte at `a`. +pub open spec fn byte_at(m: Mem, a: nat) -> u8 { + if m.dom().contains(a) { + m[a] + } else { + 0 + } +} + +/// `n` bytes from `a`, little-endian, as a number (Wasm core §4.3.1 +/// "Bytes": `bytes_t`, little-endian, and its inverse). +pub open spec fn read_le(m: Mem, a: nat, n: nat) -> nat + decreases n, +{ + if n == 0 { + 0 + } else { + byte_at(m, a) as nat + 256 * read_le(m, a + 1, (n - 1) as nat) + } +} + +/// Store the low `n` bytes of `v` at `a`, little-endian. +pub open spec fn write_le(m: Mem, a: nat, v: nat, n: nat) -> Mem + decreases n, +{ + if n == 0 { + m + } else { + write_le(m.insert(a, (v % 256) as u8), a + 1, v / 256, (n - 1) as nat) + } +} + +/// The index after the mask (modelling choice 5). +pub open spec fn masked(bound: nat, i: nat) -> nat { + if i < bound { + i + } else { + 0 + } +} + +/// The size in bytes of a value of type `t` in memory (Wasm core §4.3.1, +/// `|t|/8`). 0 for `Idx`, which is not a storable type. +pub open spec fn ty_size(t: Ty) -> nat { + match t { + Ty::I32 => 4, + Ty::I64 => 8, + Ty::F64 => 8, + Ty::Idx(_, _) => 0, + } +} + +/// The bits of a value, as stored. +pub open spec fn val_bits(v: Val) -> nat { + match v { + Val::I32(x) => x as nat, + Val::I64(x) => x as nat, + Val::F64(x) => x as nat, + } +} + +/// The value of type `t` whose stored bits are `n`. +pub open spec fn val_of_bits(t: Ty, n: nat) -> Val { + match t { + Ty::I32 => Val::I32(n as u32), + Ty::I64 => Val::I64(n as u64), + Ty::F64 => Val::F64(n as u64), + Ty::Idx(_, _) => Val::I64(n as u64), + } +} + +/// The value has the base type `t` (`Idx` is not a base type: no value has +/// it by its shape alone, see `typing::conforms`). +pub open spec fn val_has_base_ty(v: Val, t: Ty) -> bool { + match (v, t) { + (Val::I32(_), Ty::I32) => true, + (Val::I64(_), Ty::I64) => true, + (Val::F64(_), Ty::F64) => true, + _ => false, + } +} + +// --------------------------------------------------------------------- +// Integer and floating-point operators (Wasm core §4.3) +// --------------------------------------------------------------------- + +/// `signed_N` (Wasm core §4.3.1 "Integers"): the two's-complement reading +/// of the `bits`-bit unsigned number `x`. +pub open spec fn signed_of(bits: nat, x: int) -> int { + if x < pow2(bits) / 2 { + x + } else { + x - pow2(bits) + } +} + +/// Reduction modulo `2^bits`. +pub open spec fn wrap(bits: nat, n: int) -> int { + n % (pow2(bits) as int) +} + +/// The arithmetic and shift integer operators on `bits`-bit unsigned numbers +/// `x`, `y` (Wasm core §4.3.2). The bitwise `and`, `or`, `xor` are +/// not here: they are on `u32` and `u64` directly, see [`ibin32`]. +/// A shift or rotate count is taken modulo `bits` (§4.3.2, `ishl`: "`k` is +/// `j2 mod N`"). +pub open spec fn iarith(op: IBin, bits: nat, x: int, y: int) -> int { + let k = (y % (bits as int)) as nat; + match op { + // iadd: "(i1 + i2) mod 2^N" + IBin::Add => wrap(bits, x + y), + // isub: "(i1 - i2 + 2^N) mod 2^N" + IBin::Sub => wrap(bits, x - y), + // imul: "(i1 * i2) mod 2^N" + IBin::Mul => wrap(bits, x * y), + // ishl: "ibits_N^-1 (ibits_N(i1) << k)" = i1 * 2^k mod 2^N + IBin::Shl => wrap(bits, x * pow2(k) as int), + // ishr_u: "(i1 >> k)" with zeros shifted in = floor(i1 / 2^k) + IBin::ShrU => x / (pow2(k) as int), + // ishr_s: the sign bit is shifted in = floor(signed(i1) / 2^k), mod 2^N + IBin::ShrS => wrap(bits, signed_of(bits, x) / (pow2(k) as int)), + // irotl: the bits shifted out of the left come back on the right + IBin::Rotl => wrap( + bits, + wrap(bits, x * pow2(k) as int) + x / (pow2((bits - k) as nat) as int), + ), + // irotr: the bits shifted out of the right come back on the left + IBin::Rotr => wrap( + bits, + x / (pow2(k) as int) + wrap(bits, x * pow2((bits - k) as nat) as int), + ), + // and, or, xor are handled by the caller on fixed-width values + _ => 0, + } +} + +/// An `i32` binary operator. +pub open spec fn ibin32(op: IBin, x: u32, y: u32) -> u32 { + match op { + IBin::And => x & y, + IBin::Or => x | y, + IBin::Xor => x ^ y, + _ => iarith(op, 32, x as int, y as int) as u32, + } +} + +/// An `i64` binary operator. +pub open spec fn ibin64(op: IBin, x: u64, y: u64) -> u64 { + match op { + IBin::And => x & y, + IBin::Or => x | y, + IBin::Xor => x ^ y, + _ => iarith(op, 64, x as int, y as int) as u64, + } +} + +/// An integer comparison on `bits`-bit unsigned numbers (Wasm core §4.3.2: +/// `ieq`, `ine`, `ilt_s`, `ilt_u`, ...). +pub open spec fn icmp(op: ICmp, bits: nat, x: int, y: int) -> bool { + match op { + ICmp::Eq => x == y, + ICmp::Ne => x != y, + ICmp::LtS => signed_of(bits, x) < signed_of(bits, y), + ICmp::LtU => x < y, + ICmp::GtS => signed_of(bits, x) > signed_of(bits, y), + ICmp::GtU => x > y, + ICmp::LeS => signed_of(bits, x) <= signed_of(bits, y), + ICmp::LeU => x <= y, + ICmp::GeS => signed_of(bits, x) >= signed_of(bits, y), + ICmp::GeU => x >= y, + } +} + +/// A comparison's result as an `i32` (Wasm core §4.4.1 `t.relop`: "push the +/// `i32` value `c`", 1 if true). +pub open spec fn bool_i32(b: bool) -> u32 { + if b { + 1 + } else { + 0 + } +} + +/// The `f64` bit pattern is a NaN (Wasm core §4.3.3 "Floating-Point +/// Operations", `nans`): exponent all ones, fraction non-zero. +pub open spec fn f64_is_nan(b: u64) -> bool { + (b >> 52) & 0x7FF == 0x7FF && b & 0xF_FFFF_FFFF_FFFF != 0 +} + +/// The order key of a non-NaN `f64`: the sign-magnitude reading of its bits. +/// `+0` and `-0` both have key 0, so they compare equal; the keys of the +/// others order as the numbers do. +pub open spec fn f64_key(b: u64) -> int { + let mag = (b & 0x7FFF_FFFF_FFFF_FFFF) as int; + if b >> 63 == 1 { + -mag + } else { + mag + } +} + +/// An `f64` comparison (Wasm core §4.3.3 `feq`, `fne`, `flt`, `fgt`, `fle`, +/// `fge`): false if either operand is a NaN, except `ne`, which is true. +pub open spec fn fcmp(op: FCmp, a: u64, b: u64) -> bool { + if f64_is_nan(a) || f64_is_nan(b) { + op == FCmp::Ne + } else { + match op { + FCmp::Eq => f64_key(a) == f64_key(b), + FCmp::Ne => f64_key(a) != f64_key(b), + FCmp::Lt => f64_key(a) < f64_key(b), + FCmp::Gt => f64_key(a) > f64_key(b), + FCmp::Le => f64_key(a) <= f64_key(b), + FCmp::Ge => f64_key(a) >= f64_key(b), + } + } +} + +/// `fadd` (Wasm core §4.3.3), the rounded sum, with the NaN choice of +/// modelling choice 6. Uninterpreted. +pub uninterp spec fn f64_add(a: u64, b: u64) -> u64; + +/// `fsub`. Uninterpreted. +pub uninterp spec fn f64_sub(a: u64, b: u64) -> u64; + +/// `fmul`. Uninterpreted. +pub uninterp spec fn f64_mul(a: u64, b: u64) -> u64; + +/// `fdiv`. Uninterpreted. +pub uninterp spec fn f64_div(a: u64, b: u64) -> u64; + +/// `fsqrt`. Uninterpreted. +pub uninterp spec fn f64_sqrt(a: u64) -> u64; + +/// `convert_{s,u}` (Wasm core §4.3.4 "Conversions", `convert_{N,M}^{sx}`): +/// the nearest `f64` to the integer `n`, ties to even. Uninterpreted. +pub uninterp spec fn f64_of_int(n: int) -> u64; + +/// An `f64` binary operator. +pub open spec fn fbin(op: FBin, a: u64, b: u64) -> u64 { + match op { + FBin::Add => f64_add(a, b), + FBin::Sub => f64_sub(a, b), + FBin::Mul => f64_mul(a, b), + FBin::Div => f64_div(a, b), + } +} + +/// A binary numeric instruction on two values; `None` if the operands are +/// not of the operator's type (the instruction is then stuck). +/// Wasm core §4.4.1 `t.binop` and `t.relop`. +pub open spec fn bin_eval(op: BinOp, a: Val, b: Val) -> Option { + match (op, a, b) { + // t.binop: "Let c be the result of binop_t(c1, c2). Push t.const c". + (BinOp::I32(o), Val::I32(x), Val::I32(y)) => Some(Val::I32(ibin32(o, x, y))), + (BinOp::I64(o), Val::I64(x), Val::I64(y)) => Some(Val::I64(ibin64(o, x, y))), + (BinOp::F64(o), Val::F64(x), Val::F64(y)) => Some(Val::F64(fbin(o, x, y))), + // t.relop: "Let c be the result of relop_t(c1, c2). Push i32.const c". + (BinOp::I32Cmp(o), Val::I32(x), Val::I32(y)) => Some( + Val::I32(bool_i32(icmp(o, 32, x as int, y as int))), + ), + (BinOp::I64Cmp(o), Val::I64(x), Val::I64(y)) => Some( + Val::I32(bool_i32(icmp(o, 64, x as int, y as int))), + ), + (BinOp::F64Cmp(o), Val::F64(x), Val::F64(y)) => Some(Val::I32(bool_i32(fcmp(o, x, y)))), + _ => None, + } +} + +/// A unary numeric instruction on a value; `None` if the operand is not of +/// the operator's type. Wasm core §4.4.1 `t.unop`, `t.testop`, `t2.cvtop`. +pub open spec fn un_eval(op: UnOp, a: Val) -> Option { + match (op, a) { + // t.testop, ieqz (§4.3.2): 1 if the operand is 0. + (UnOp::I32Eqz, Val::I32(x)) => Some(Val::I32(bool_i32(x == 0))), + (UnOp::I64Eqz, Val::I64(x)) => Some(Val::I32(bool_i32(x == 0))), + // fneg, fabs (§4.3.3): flip, or clear, the sign bit; NaNs included. + (UnOp::F64Neg, Val::F64(x)) => Some(Val::F64(x ^ 0x8000_0000_0000_0000)), + (UnOp::F64Abs, Val::F64(x)) => Some(Val::F64(x & 0x7FFF_FFFF_FFFF_FFFF)), + (UnOp::F64Sqrt, Val::F64(x)) => Some(Val::F64(f64_sqrt(x))), + // wrap_{M,N} (§4.3.4): "i mod 2^N". + (UnOp::I32WrapI64, Val::I64(x)) => Some(Val::I32((x & 0xFFFF_FFFF) as u32)), + // extend_{M,N}^{sx} (§4.3.4): sx = s keeps the signed value. + (UnOp::I64ExtendI32S, Val::I32(x)) => Some(Val::I64(wrap(64, signed_of(32, x as int)) as u64)), + (UnOp::I64ExtendI32U, Val::I32(x)) => Some(Val::I64(x as u64)), + // convert_{M,N}^{sx} (§4.3.4). + (UnOp::F64ConvertI32S, Val::I32(x)) => Some(Val::F64(f64_of_int(signed_of(32, x as int)))), + (UnOp::F64ConvertI32U, Val::I32(x)) => Some(Val::F64(f64_of_int(x as int))), + (UnOp::F64ConvertI64S, Val::I64(x)) => Some(Val::F64(f64_of_int(signed_of(64, x as int)))), + (UnOp::F64ConvertI64U, Val::I64(x)) => Some(Val::F64(f64_of_int(x as int))), + // reinterpret_{t1,t2} (§4.3.4): the same bits. + (UnOp::F64ReinterpretI64, Val::I64(x)) => Some(Val::F64(x)), + (UnOp::I64ReinterpretF64, Val::F64(x)) => Some(Val::I64(x)), + _ => None, + } +} + +// --------------------------------------------------------------------- +// The machine and the interpreter +// --------------------------------------------------------------------- + +/// The machine state: the operand stack (top is the last element), the +/// locals and memory. Wasm core §4.2 "Runtime Structure" (frames hold the +/// locals; the store holds memory). +pub struct St { + /// The operand stack, top last. + pub stack: Seq, + /// The locals. + pub locals: Seq, + /// Memory. + pub mem: Mem, +} + +/// What evaluating an instruction does (modelling choice 1). +pub enum Outcome { + /// Finished and fell through, with the new state. + Normal(St), + /// A `br` to the label `n` levels out (0 is the innermost). The stack of + /// the state is the stack of the code that branched. + Branch(nat, St), + /// An `exit` with its code and operand values, and the state after the + /// operands were popped. + Exit(nat, Seq, St), + /// No meaning: a type error, or an access outside its region. The typing + /// proves it unreachable. + Stuck, + /// The fuel ran out. + OutOfFuel, +} + +/// The top `k` elements of `s`. +pub open spec fn top(s: Seq, k: nat) -> Seq { + s.skip(s.len() - k) +} + +/// `s` without its top `k` elements. +pub open spec fn below(s: Seq, k: nat) -> Seq { + s.take(s.len() - k) +} + +impl St { + /// The state with another stack. + pub open spec fn with_stack(self, s: Seq) -> St { + St { stack: s, locals: self.locals, mem: self.mem } + } + + /// The state with another memory. + pub open spec fn with_mem(self, m: Mem) -> St { + St { stack: self.stack, locals: self.locals, mem: m } + } + + /// The state with another set of locals. + pub open spec fn with_locals(self, l: Seq) -> St { + St { stack: self.stack, locals: l, mem: self.mem } + } +} + +/// The result of a block-like instruction's body, for the instruction that +/// is label 0 (Wasm core §4.4.8 "Blocks" and `br`): `base` is what was set +/// aside under the block's parameters, `arity` the number of values a +/// branch to this label carries, and `again` is what to do on a branch to +/// the label (`Some(i)` for a `loop`, which restarts at its start) or `None` +/// (a `block` or `if`, which continue after their end). +pub open spec fn finish_label( + lay: Layout, + base: Seq, + arity: nat, + restart: Option, + o: Outcome, + fuel: nat, +) -> Outcome + decreases fuel, 0nat, +{ + match o { + // 'end' reached: all the body's stack is the results. + Outcome::Normal(s) => Outcome::Normal(s.with_stack(base + s.stack)), + Outcome::Branch(n, s) => { + if n > 0 { + // A branch to an outer label: pass it on. + Outcome::Branch((n - 1) as nat, s) + } else if s.stack.len() < arity { + Outcome::Stuck + } else { + let carried = base + top(s.stack, arity); + match restart { + // `loop`: branching to it restarts the loop. + Some(i) => { + if fuel == 0 { + Outcome::OutOfFuel + } else { + eval(lay, i, s.with_stack(carried), (fuel - 1) as nat) + } + }, + // `block`, `if`: continue after `end`. + None => Outcome::Normal(s.with_stack(carried)), + } + } + }, + other => other, + } +} + +/// Evaluate `i` in state `st` with at most `fuel` steps. Every call spends +/// one unit. +/// +/// Each arm cites Wasm core 2.0. `Stuck` is returned where Wasm validation +/// would have excluded the case (a missing operand, an operand of the wrong +/// type, a bad local index). +pub open spec fn eval(lay: Layout, i: Instr, st: St, fuel: nat) -> Outcome + decreases fuel, 1nat, +{ + if fuel == 0 { + Outcome::OutOfFuel + } else { + let f = (fuel - 1) as nat; + let n = st.stack.len(); + match i { + // Wasm core §4.4.8 `nop`: "Do nothing." + Instr::Nop => Outcome::Normal(st), + // Wasm core §4.4.8 instruction sequences: the first, then the + // rest, unless the first branched or exited. + Instr::Then(a, b) => { + match eval(lay, *a, st, f) { + Outcome::Normal(s1) => eval(lay, *b, s1, f), + other => other, + } + }, + // Wasm core §4.4.1 `t.const c`: "Push the value t.const c". + Instr::Const(v) => Outcome::Normal(st.with_stack(st.stack.push(v))), + // Wasm core §4.4.4 `local.get x`: "Push the value val to the stack". + Instr::LocalGet(x) => { + if x < st.locals.len() { + Outcome::Normal(st.with_stack(st.stack.push(st.locals[x as int]))) + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.4 `local.set x`: "Pop the value val from the + // stack. Replace the local". + Instr::LocalSet(x) => { + if n >= 1 && x < st.locals.len() { + Outcome::Normal( + St { + stack: st.stack.drop_last(), + locals: st.locals.update(x as int, st.stack.last()), + mem: st.mem, + }, + ) + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.4 `local.tee x`: "Assert: ... a value val on the + // top of the stack. Push val, then `local.set x`". + Instr::LocalTee(x) => { + if n >= 1 && x < st.locals.len() { + Outcome::Normal(st.with_locals(st.locals.update(x as int, st.stack.last()))) + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.3 `drop`: "Pop the value val from the stack." + Instr::Drop => { + if n >= 1 { + Outcome::Normal(st.with_stack(st.stack.drop_last())) + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.3 `select`: pop c (an i32), then val2, then + // val1; "If c is not 0, push val1, else push val2". + Instr::Select => { + if n >= 3 { + match st.stack[n - 1] { + Val::I32(c) => { + let v1 = st.stack[n - 3]; + let v2 = st.stack[n - 2]; + Outcome::Normal( + st.with_stack( + below(st.stack, 3).push(if c != 0 { + v1 + } else { + v2 + }), + ), + ) + }, + _ => Outcome::Stuck, + } + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.1 `t.binop`, `t.relop`: pop c2, then c1. + Instr::Bin(op) => { + if n >= 2 { + match bin_eval(op, st.stack[n - 2], st.stack[n - 1]) { + Some(v) => Outcome::Normal(st.with_stack(below(st.stack, 2).push(v))), + None => Outcome::Stuck, + } + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.1 `t.unop`, `t.testop`, `t2.cvtop`. + Instr::Un(op) => { + if n >= 1 { + match un_eval(op, st.stack[n - 1]) { + Some(v) => Outcome::Normal(st.with_stack(below(st.stack, 1).push(v))), + None => Outcome::Stuck, + } + } else { + Outcome::Stuck + } + }, + // LIR's `bounds_check` (modelling choice 5): pop the index; push + // it back if `i + size <= bound`, else exit with the code. + Instr::BoundsCheck { region, size, code } => { + if n >= 1 && region < lay.len() { + match st.stack[n - 1] { + Val::I64(ix) => { + if ix as nat + size <= lay[region as int].bound { + Outcome::Normal(st) + } else { + Outcome::Exit(code, seq![], st.with_stack(below(st.stack, 1))) + } + }, + _ => Outcome::Stuck, + } + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.6 `t.load`: pop the address i; "let ea be i + + // offset"; "If ea + N/8 is larger than the length of mem.data, + // trap"; else read the bytes and push the value. Here the + // address is `base + masked(bound, i)` and the out-of-region + // case is Stuck (modelling choice 4). + Instr::Load { region, ty } => { + if n >= 1 && region < lay.len() && ty_size(ty) > 0 { + match st.stack[n - 1] { + Val::I64(ix) => { + let r = lay[region as int]; + if ix as nat + ty_size(ty) <= r.bound { + let a = r.base + masked(r.bound, ix as nat); + Outcome::Normal( + st.with_stack( + below(st.stack, 1).push( + val_of_bits(ty, read_le(st.mem, a, ty_size(ty))), + ), + ), + ) + } else { + Outcome::Stuck + } + }, + _ => Outcome::Stuck, + } + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.6 `t.store`: pop the value c, then the address + // i; write `bytes_t(c)` at `ea`. + Instr::Store { region, ty } => { + if n >= 2 && region < lay.len() && ty_size(ty) > 0 && val_has_base_ty( + st.stack[n - 1], + ty, + ) { + match st.stack[n - 2] { + Val::I64(ix) => { + let r = lay[region as int]; + if ix as nat + ty_size(ty) <= r.bound { + let a = r.base + masked(r.bound, ix as nat); + Outcome::Normal( + st.with_stack(below(st.stack, 2)).with_mem( + write_le( + st.mem, + a, + val_bits(st.stack[n - 1]), + ty_size(ty), + ), + ), + ) + } else { + Outcome::Stuck + } + }, + _ => Outcome::Stuck, + } + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.8 `block bt instr* end`: "Let L be the label + // whose arity is m [the results] ... Enter the block with the + // values val^n [the parameters] on the stack". + Instr::Block(bt, body) => { + if n >= bt.params.len() { + let base = below(st.stack, bt.params.len()); + let o = eval(lay, *body, st.with_stack(top(st.stack, bt.params.len())), f); + finish_label(lay, base, bt.results.len(), None, o, f) + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.8 `loop bt instr* end`: the label's arity is the + // number of *parameters* (a branch restarts the loop). + Instr::Loop(bt, body) => { + if n >= bt.params.len() { + let base = below(st.stack, bt.params.len()); + let o = eval(lay, *body, st.with_stack(top(st.stack, bt.params.len())), f); + finish_label(lay, base, bt.params.len(), Some(Instr::Loop(bt, body)), o, f) + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.8 `if bt instr1* else instr2* end`: "Pop the + // value i32.const c from the stack. If c is non-zero, ... block + // bt instr1* end, else ... block bt instr2* end." + Instr::If(bt, t, e) => { + if n >= 1 { + match st.stack[n - 1] { + Val::I32(c) => eval( + lay, + Instr::Block(bt, if c != 0 { + t + } else { + e + }), + st.with_stack(below(st.stack, 1)), + f, + ), + _ => Outcome::Stuck, + } + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.8 `br l`: the branch itself; the label that is + // `l` levels out handles it (see `finish_label`). + Instr::Br(l) => Outcome::Branch(l, st), + // Wasm core §4.4.8 `br_if l`: "Pop the value i32.const c. If c is + // non-zero, then branch l; else do nothing." + Instr::BrIf(l) => { + if n >= 1 { + match st.stack[n - 1] { + Val::I32(c) => { + let s1 = st.with_stack(below(st.stack, 1)); + if c != 0 { + Outcome::Branch(l, s1) + } else { + Outcome::Normal(s1) + } + }, + _ => Outcome::Stuck, + } + } else { + Outcome::Stuck + } + }, + // Wasm core §4.4.8 `br_table l* l_N`: "If i is less than the + // length of l*, then branch l*[i]; else branch l_N." + Instr::BrTable(ls, d) => { + if n >= 1 { + match st.stack[n - 1] { + Val::I32(c) => Outcome::Branch( + if (c as nat) < ls.len() { + ls[c as int] + } else { + d + }, + st.with_stack(below(st.stack, 1)), + ), + _ => Outcome::Stuck, + } + } else { + Outcome::Stuck + } + }, + // LIR's `exit` (modelling choice 3): stop with the code and the + // top values. + Instr::Exit(code, tys) => { + if n >= tys.len() { + Outcome::Exit(code, top(st.stack, tys.len()), st.with_stack(below(st.stack, tys.len()))) + } else { + Outcome::Stuck + } + }, + } + } +} + +/// Run a function body: the body is `body`, with label 0 being the function's +/// own end, so a `br` to it is a return (Wasm core §4.4.9 "Function Calls": +/// the function body is a block whose label is the return). The state is the +/// entry state: the stack holds the arguments, the locals are the +/// parameters and the declared locals. +pub open spec fn run(lay: Layout, body: Instr, st: St, fuel: nat) -> Outcome { + match eval(lay, body, st, fuel) { + Outcome::Branch(n, s) => if n == 0 { + Outcome::Normal(s) + } else { + Outcome::Stuck + }, + other => other, + } +} + +} // verus! diff --git a/crates/clazel-lir/src/syntax.rs b/crates/clazel-lir/src/syntax.rs new file mode 100644 index 000000000..1d400fbcc --- /dev/null +++ b/crates/clazel-lir/src/syntax.rs @@ -0,0 +1,259 @@ +//! LIR's abstract syntax (docs/phases/jit.md item J.5): types, values and +//! instructions. Meaning is in [`crate::spec`], typing in [`crate::typing`]. +//! +//! The syntax mirrors WebAssembly's structured instruction set (Wasm core +//! specification 2.0, §2.4 "Instructions" and §2.3 "Types"), restricted to +//! what the JIT needs, with LIR's own additions: regions and `bounds_check` +//! (jit.md, "Regions are the only memory") and `exit` (jit.md, "Generated +//! code never calls anything"). + +#[allow(unused_imports)] +use vstd::prelude::*; + +verus! { + +/// A region number: an index into the layout (the table of (base, bound) +/// pairs the blob is entered with). +pub type RegionId = nat; + +/// A value type. Wasm core §2.3.1 "Number Types" has `i32`, `i64`, `f32`, +/// `f64`; LIR has no `f32` (see the crate docs). +pub enum Ty { + /// `i32`. + I32, + /// `i64`. + I64, + /// `f64`. + F64, + /// **LIR's addition, not in Wasm.** An `i64` that has been bounds-checked + /// for `size` bytes of `region`: its value `i` satisfies + /// `i + size <= bound(region)`. Only `bounds_check` makes one, and + /// `load` and `store` take only this type, so an access without a + /// check does not type. It is a subtype of `i64`, and of `Idx` of the + /// same region with a smaller size. + Idx(RegionId, nat), +} + +/// A runtime value. Wasm core §4.2.1 "Values" (`i32.const`, `i64.const`, +/// `f64.const`). An `f64` is its IEEE 754 bit pattern, so NaN payloads are +/// kept (§4.3.3.1). +pub enum Val { + /// An `i32`: 32 bits, no signedness. + I32(u32), + /// An `i64`. + I64(u64), + /// An `f64`, as bits. + F64(u64), +} + +/// A block type with parameters. Wasm core §2.4.8 "Control Instructions" +/// (`blocktype`), in its general form `[t1*] -> [t2*]` (the 2.0 spec allows a +/// type index; we write the function type inline). +pub struct BlockType { + /// The values the block consumes. + pub params: Seq, + /// The values the block leaves. + pub results: Seq, +} + +/// Integer binary operators, for `i32` and `i64` alike. Wasm core §2.4.1 +/// "Numeric Instructions", `ibinop`. LIR omits `div` and `rem`, which trap +/// in Wasm; the JIT does not need them yet. +pub enum IBin { + /// `add`. + Add, + /// `sub`. + Sub, + /// `mul`. + Mul, + /// `and`. + And, + /// `or`. + Or, + /// `xor`. + Xor, + /// `shl`. + Shl, + /// `shr_s`. + ShrS, + /// `shr_u`. + ShrU, + /// `rotl`. + Rotl, + /// `rotr`. + Rotr, +} + +/// Integer comparisons (`irelop`, giving an `i32`). +pub enum ICmp { + /// `eq`. + Eq, + /// `ne`. + Ne, + /// `lt_s`. + LtS, + /// `lt_u`. + LtU, + /// `gt_s`. + GtS, + /// `gt_u`. + GtU, + /// `le_s`. + LeS, + /// `le_u`. + LeU, + /// `ge_s`. + GeS, + /// `ge_u`. + GeU, +} + +/// `f64` binary operators (`fbinop`). LIR omits `min`, `max`, `copysign`. +pub enum FBin { + /// `add`. + Add, + /// `sub`. + Sub, + /// `mul`. + Mul, + /// `div`. + Div, +} + +/// `f64` comparisons (`frelop`, giving an `i32`). +pub enum FCmp { + /// `eq`. + Eq, + /// `ne`. + Ne, + /// `lt`. + Lt, + /// `gt`. + Gt, + /// `le`. + Le, + /// `ge`. + Ge, +} + +/// A binary numeric operator: two operands of one type, one result. +pub enum BinOp { + /// An `i32` operator. + I32(IBin), + /// An `i64` operator. + I64(IBin), + /// An `i32` comparison. + I32Cmp(ICmp), + /// An `i64` comparison. + I64Cmp(ICmp), + /// An `f64` operator. + F64(FBin), + /// An `f64` comparison. + F64Cmp(FCmp), +} + +/// A unary numeric operator: Wasm core §2.4.1 `testop` (`eqz`), `funop` +/// (`neg`, `abs`, `sqrt`) and `cvtop` (conversions). +pub enum UnOp { + /// `i32.eqz`. + I32Eqz, + /// `i64.eqz`. + I64Eqz, + /// `f64.neg`. + F64Neg, + /// `f64.abs`. + F64Abs, + /// `f64.sqrt`. + F64Sqrt, + /// `i32.wrap_i64`. + I32WrapI64, + /// `i64.extend_i32_s`. + I64ExtendI32S, + /// `i64.extend_i32_u`. + I64ExtendI32U, + /// `f64.convert_i32_s`. + F64ConvertI32S, + /// `f64.convert_i32_u`. + F64ConvertI32U, + /// `f64.convert_i64_s`. + F64ConvertI64S, + /// `f64.convert_i64_u`. + F64ConvertI64U, + /// `f64.reinterpret_i64`. + F64ReinterpretI64, + /// `i64.reinterpret_f64`. + I64ReinterpretF64, +} + +/// An instruction. Wasm core §2.4 "Instructions"; one recursive type, with +/// `Then` for sequencing (Wasm's `instr*`) and `Box`ed bodies for the +/// structured instructions. +/// +/// There are no calls and no indirect branches (jit.md): every branch names +/// an enclosing label. +pub enum Instr { + /// `nop`. + Nop, + /// Sequencing: `a`, then `b`. + Then(Box, Box), + /// `t.const`. + Const(Val), + /// `local.get x`. + LocalGet(nat), + /// `local.set x`. + LocalSet(nat), + /// `local.tee x`. + LocalTee(nat), + /// `drop`. + Drop, + /// `select` (the untyped form, restricted to operands of one type). + Select, + /// A numeric instruction with two operands. + Bin(BinOp), + /// A numeric instruction with one operand. + Un(UnOp), + /// **LIR's addition.** Pops an `i64` index `i`. If `i + size` is at most + /// the bound of `region`, pushes `i`, now of type `Idx(region, size)`. + /// Otherwise it is an exit with `code` and no operands: the bounds + /// failure is a runtime service, not a trap. + BoundsCheck { + /// The region checked against. + region: RegionId, + /// The number of bytes the checked index must leave room for. + size: nat, + /// The exit code if the check fails. + code: nat, + }, + /// `t.load` from `region` (Wasm core §2.4.7 "Memory Instructions"), with + /// no offset and no narrow forms. Takes an `Idx(region, size of ty)`. + Load { + /// The region read. + region: RegionId, + /// The type loaded. + ty: Ty, + }, + /// `t.store` to `region`. Takes an `Idx(region, size of ty)` and a value. + Store { + /// The region written. + region: RegionId, + /// The type stored. + ty: Ty, + }, + /// `block bt body end`. + Block(BlockType, Box), + /// `loop bt body end`. + Loop(BlockType, Box), + /// `if bt then else end`. + If(BlockType, Box, Box), + /// `br l`. + Br(nat), + /// `br_if l`. + BrIf(nat), + /// `br_table l* l_default`. + BrTable(Seq, nat), + /// **LIR's addition.** Stops the blob and returns to the enter stub with + /// `code` and the top `operands.len()` values, whose types are given. + Exit(nat, Seq), +} + +} // verus! diff --git a/xtask/src/status.rs b/xtask/src/status.rs index f051ec36c..0ecc9c1d0 100644 --- a/xtask/src/status.rs +++ b/xtask/src/status.rs @@ -91,6 +91,8 @@ const PLACES: &[(&str, Place)] = &[ // The JIT's instruction-set layer (docs/phases/jit.md item J.2 creates them empty). ("clazel-x64", Place::Primitive), ("clazel-a64", Place::Primitive), + // The JIT's low-level IR (item J.5). + ("clazel-lir", Place::Renderer), ("clazel-ipc", Place::Primitive), ("clazel-sandbox", Place::Os), ("clazel-sys", Place::Os), From 04870e34c557cd15ee05e7835fa3ca1c7ceedbcc Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Tue, 17 Nov 2026 15:26:57 +0000 Subject: [PATCH 2/6] clazel-lir: the typing judgment (jit.md J.5) tc checks an instruction against the stack types, with Idx types for bounds-checked indexes and no stack-polymorphic dead code. The soundness theorem follows in the next commit. Co-Authored-By: Claude Sonnet 5.5 --- crates/clazel-lir/src/lib.rs | 1 + crates/clazel-lir/src/typing.rs | 373 ++++++++++++++++++++++++++++++++ 2 files changed, 374 insertions(+) create mode 100644 crates/clazel-lir/src/typing.rs diff --git a/crates/clazel-lir/src/lib.rs b/crates/clazel-lir/src/lib.rs index bcd59a0ce..0dbf34ae8 100644 --- a/crates/clazel-lir/src/lib.rs +++ b/crates/clazel-lir/src/lib.rs @@ -16,3 +16,4 @@ pub mod spec; pub mod syntax; +pub mod typing; diff --git a/crates/clazel-lir/src/typing.rs b/crates/clazel-lir/src/typing.rs new file mode 100644 index 000000000..9564aec96 --- /dev/null +++ b/crates/clazel-lir/src/typing.rs @@ -0,0 +1,373 @@ +//! LIR's typing judgment and its soundness theorem (docs/phases/jit.md item +//! J.5). +//! +//! The judgment is [`tc`]: given the layout, a context (the types of the +//! locals and of the enclosing labels) and the types of the operand stack, +//! it says whether an instruction is well-typed and what it leaves on the +//! stack. It is Wasm core 2.0 §3.3 "Instructions" (validation), written as +//! a checking function in the style of the algorithm of Appendix A +//! "Validation Algorithm", with three differences: +//! +//! 1. **No stack-polymorphic dead code.** Wasm types the code after `br`, +//! `br_table`, `return` and `unreachable` at any stack (§3.3.8, +//! `[t1* t*] -> [t2*]`). LIR instead requires the instruction that never +//! falls through ([`Flow::Diverges`]: `br`, `br_table`, `exit`) to be the +//! last of its sequence, and rejects anything after it. A front end drops +//! the dead code; the typing is then monomorphic, which is what the +//! back ends' templates want. +//! 2. **`Idx` types** (see [`Ty`]): the only way to type a `load` or +//! `store`. This is what makes "every access is inside its region" a +//! type-level fact. +//! 3. **No function, table, global or reference instructions**; one body, +//! with label 0 as its return (see `spec`). +//! +//! The soundness theorem, `tc_sound`, is stated and proven in the commit +//! after this one: a well-typed instruction, started in a state that +//! conforms to its input types, is never [`Outcome::Stuck`] (so every load +//! and store is inside its region, every operand exists and has the right +//! type), and whatever it does conforms to what the typing said. + +#[allow(unused_imports)] +use super::spec::*; +#[allow(unused_imports)] +use vstd::prelude::*; + +verus! { + +// --------------------------------------------------------------------- +// Subtyping and conformance +// --------------------------------------------------------------------- + +/// `a` may be used where `b` is expected. `Idx(r, n)` is an `i64`, and it +/// is an `Idx(r, m)` for any smaller `m`; otherwise only equal types match. +pub open spec fn sub(a: Ty, b: Ty) -> bool { + match (a, b) { + (Ty::Idx(r, n), Ty::Idx(s, m)) => r == s && m <= n, + (Ty::Idx(_, _), Ty::I64) => true, + _ => a == b, + } +} + +/// `sub` pointwise, on sequences of equal length. +pub open spec fn stack_sub(a: Seq, b: Seq) -> bool { + a.len() == b.len() && forall|j: int| 0 <= j < a.len() ==> sub(#[trigger] a[j], b[j]) +} + +/// The top `tys.len()` types of `stk` are subtypes of `tys`. +pub open spec fn top_sub(stk: Seq, tys: Seq) -> bool { + stk.len() >= tys.len() && stack_sub(top(stk, tys.len()), tys) +} + +/// The value `v` has type `t` under the layout `lay`: its shape matches, and +/// for `Idx(r, n)` it is an index of `r` with room for `n` bytes. +pub open spec fn conforms(lay: Layout, v: Val, t: Ty) -> bool { + match (v, t) { + (Val::I32(_), Ty::I32) => true, + (Val::I64(_), Ty::I64) => true, + (Val::F64(_), Ty::F64) => true, + (Val::I64(i), Ty::Idx(r, n)) => r < lay.len() && i as nat + n <= lay[r as int].bound, + _ => false, + } +} + +/// The values conform to the types, pointwise. +pub open spec fn vals_conform(lay: Layout, vs: Seq, ts: Seq) -> bool { + vs.len() == ts.len() && forall|j: int| 0 <= j < vs.len() ==> conforms(lay, #[trigger] vs[j], ts[j]) +} + +/// The type of a constant. +pub open spec fn val_ty(v: Val) -> Ty { + match v { + Val::I32(_) => Ty::I32, + Val::I64(_) => Ty::I64, + Val::F64(_) => Ty::F64, + } +} + +// --------------------------------------------------------------------- +// Numeric operator signatures (Wasm core §3.3.1 "Numeric Instructions") +// --------------------------------------------------------------------- + +/// The type of both operands of a binary operator. +pub open spec fn bin_arg(op: BinOp) -> Ty { + match op { + BinOp::I32(_) | BinOp::I32Cmp(_) => Ty::I32, + BinOp::I64(_) | BinOp::I64Cmp(_) => Ty::I64, + BinOp::F64(_) | BinOp::F64Cmp(_) => Ty::F64, + } +} + +/// The result type of a binary operator (comparisons give `i32`). +pub open spec fn bin_res(op: BinOp) -> Ty { + match op { + BinOp::I32(_) => Ty::I32, + BinOp::I64(_) => Ty::I64, + BinOp::F64(_) => Ty::F64, + BinOp::I32Cmp(_) | BinOp::I64Cmp(_) | BinOp::F64Cmp(_) => Ty::I32, + } +} + +/// The operand type of a unary operator. +pub open spec fn un_arg(op: UnOp) -> Ty { + match op { + UnOp::I32Eqz | UnOp::I64ExtendI32S | UnOp::I64ExtendI32U | UnOp::F64ConvertI32S + | UnOp::F64ConvertI32U => Ty::I32, + UnOp::I64Eqz | UnOp::I32WrapI64 | UnOp::F64ConvertI64S | UnOp::F64ConvertI64U + | UnOp::F64ReinterpretI64 => Ty::I64, + UnOp::F64Neg | UnOp::F64Abs | UnOp::F64Sqrt | UnOp::I64ReinterpretF64 => Ty::F64, + } +} + +/// The result type of a unary operator. +pub open spec fn un_res(op: UnOp) -> Ty { + match op { + UnOp::I32Eqz | UnOp::I64Eqz | UnOp::I32WrapI64 => Ty::I32, + UnOp::I64ExtendI32S | UnOp::I64ExtendI32U | UnOp::I64ReinterpretF64 => Ty::I64, + UnOp::F64Neg | UnOp::F64Abs | UnOp::F64Sqrt | UnOp::F64ConvertI32S + | UnOp::F64ConvertI32U | UnOp::F64ConvertI64S | UnOp::F64ConvertI64U + | UnOp::F64ReinterpretI64 => Ty::F64, + } +} + +// --------------------------------------------------------------------- +// The typing judgment +// --------------------------------------------------------------------- + +/// What an instruction's typing context holds. +pub struct Ctx { + /// The types of the locals. + pub locals: Seq, + /// The types a branch to each enclosing label carries; index 0 is the + /// innermost label, and the last is the function's return. + pub labels: Seq>, +} + +/// What a well-typed instruction does to the stack. +pub enum Flow { + /// It can fall through, leaving a stack of these types. + Falls(Seq), + /// It never falls through (it branches or exits), so it must end its + /// sequence. + Diverges, +} + +/// The number of nodes of an instruction, the measure of [`tc`]. +pub open spec fn isize(i: Instr) -> nat + decreases i, +{ + match i { + Instr::Then(a, b) => 1 + isize(*a) + isize(*b), + Instr::Block(_, b) => 1 + isize(*b), + Instr::Loop(_, b) => 1 + isize(*b), + Instr::If(_, t, e) => 1 + isize(*t) + isize(*e), + _ => 1, + } +} + +/// Type-check `i` against the stack types `stk`, giving what it leaves. +/// `None` means the instruction is ill-typed. +pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option + decreases isize(i), 1nat, +{ + let n = stk.len(); + match i { + // Wasm core §3.3.8 `nop`: [] -> []. + Instr::Nop => Some(Flow::Falls(stk)), + // Wasm core §3.3.8 instruction sequences; a diverging instruction + // may not be followed by anything (difference 1). + Instr::Then(a, b) => { + match tc(lay, ctx, *a, stk) { + Some(Flow::Falls(s1)) => tc(lay, ctx, *b, s1), + _ => None, + } + }, + // Wasm core §3.3.1 `t.const c`: [] -> [t]. + Instr::Const(v) => Some(Flow::Falls(stk.push(val_ty(v)))), + // Wasm core §3.3.5 `local.get x`: [] -> [t]. + Instr::LocalGet(x) => { + if x < ctx.locals.len() { + Some(Flow::Falls(stk.push(ctx.locals[x as int]))) + } else { + None + } + }, + // Wasm core §3.3.5 `local.set x`: [t] -> []. + Instr::LocalSet(x) => { + if x < ctx.locals.len() && n >= 1 && sub(stk.last(), ctx.locals[x as int]) { + Some(Flow::Falls(stk.drop_last())) + } else { + None + } + }, + // Wasm core §3.3.5 `local.tee x`: [t] -> [t]. + Instr::LocalTee(x) => { + if x < ctx.locals.len() && n >= 1 && sub(stk.last(), ctx.locals[x as int]) { + Some(Flow::Falls(stk)) + } else { + None + } + }, + // Wasm core §3.3.4 `drop`: [t] -> []. + Instr::Drop => { + if n >= 1 { + Some(Flow::Falls(stk.drop_last())) + } else { + None + } + }, + // Wasm core §3.3.4 `select`: [t t i32] -> [t]. + Instr::Select => { + if n >= 3 && stk[n - 1] == Ty::I32 && stk[n - 3] == stk[n - 2] { + Some(Flow::Falls(below(stk, 3).push(stk[n - 3]))) + } else { + None + } + }, + // Wasm core §3.3.1 `t.binop`, `t.relop`: [t t] -> [t] or [i32]. + Instr::Bin(op) => { + if n >= 2 && sub(stk[n - 2], bin_arg(op)) && sub(stk[n - 1], bin_arg(op)) { + Some(Flow::Falls(below(stk, 2).push(bin_res(op)))) + } else { + None + } + }, + // Wasm core §3.3.1 `t.unop`, `t.testop`, `t2.cvtop`: [t1] -> [t2]. + Instr::Un(op) => { + if n >= 1 && sub(stk[n - 1], un_arg(op)) { + Some(Flow::Falls(below(stk, 1).push(un_res(op)))) + } else { + None + } + }, + // LIR's `bounds_check`: [i64] -> [Idx(region, size)]. + Instr::BoundsCheck { region, size, code } => { + if region < lay.len() && n >= 1 && sub(stk[n - 1], Ty::I64) { + Some(Flow::Falls(below(stk, 1).push(Ty::Idx(region, size)))) + } else { + None + } + }, + // Wasm core §3.3.6 `t.load`: [i32] -> [t], with the address an + // `Idx` of the region for the size of `t`. + Instr::Load { region, ty } => { + if ty_size(ty) > 0 && region < lay.len() && n >= 1 && sub( + stk[n - 1], + Ty::Idx(region, ty_size(ty)), + ) { + Some(Flow::Falls(below(stk, 1).push(ty))) + } else { + None + } + }, + // Wasm core §3.3.6 `t.store`: [i32 t] -> []. + Instr::Store { region, ty } => { + if ty_size(ty) > 0 && region < lay.len() && n >= 2 && sub( + stk[n - 2], + Ty::Idx(region, ty_size(ty)), + ) && sub(stk[n - 1], ty) { + Some(Flow::Falls(below(stk, 2))) + } else { + None + } + }, + // Wasm core §3.3.8 `block`, `loop`. + Instr::Block(bt, body) => tc_blk(lay, ctx, bt, *body, stk, false), + Instr::Loop(bt, body) => tc_blk(lay, ctx, bt, *body, stk, true), + // Wasm core §3.3.8 `if`: [t1* i32] -> [t2*], both arms typed as + // blocks. + Instr::If(bt, t, e) => { + if n >= 1 && sub(stk[n - 1], Ty::I32) { + match ( + tc_blk(lay, ctx, bt, *t, stk.drop_last(), false), + tc_blk(lay, ctx, bt, *e, stk.drop_last(), false), + ) { + (Some(f1), Some(_)) => Some(f1), + _ => None, + } + } else { + None + } + }, + // Wasm core §3.3.8 `br l`: [t1* t*] -> [t2*], with `t*` the label's + // types; here it ends its sequence. + Instr::Br(l) => { + if l < ctx.labels.len() && top_sub(stk, ctx.labels[l as int]) { + Some(Flow::Diverges) + } else { + None + } + }, + // Wasm core §3.3.8 `br_if l`: [t* i32] -> [t*]. + Instr::BrIf(l) => { + if n >= 1 && sub(stk[n - 1], Ty::I32) && l < ctx.labels.len() && top_sub( + stk.drop_last(), + ctx.labels[l as int], + ) { + Some(Flow::Falls(stk.drop_last())) + } else { + None + } + }, + // Wasm core §3.3.8 `br_table l* l_N`: every label must take the + // values on the stack. + Instr::BrTable(ls, d) => { + if n >= 1 && sub(stk[n - 1], Ty::I32) && d < ctx.labels.len() && top_sub( + stk.drop_last(), + ctx.labels[d as int], + ) && (forall|j: int| + 0 <= j < ls.len() ==> (#[trigger] ls[j]) < ctx.labels.len() && top_sub( + stk.drop_last(), + ctx.labels[ls[j] as int], + )) { + Some(Flow::Diverges) + } else { + None + } + }, + // LIR's `exit`: takes the operands, never falls through. + Instr::Exit(code, tys) => { + if top_sub(stk, tys) { + Some(Flow::Diverges) + } else { + None + } + }, + } +} + +/// The typing of `block` (`is_loop` false) and `loop` (`is_loop` true): the +/// body is checked on a stack of just the parameters, with a new innermost +/// label whose types are the results (a block) or the parameters (a loop). +pub open spec fn tc_blk( + lay: Layout, + ctx: Ctx, + bt: BlockType, + body: Instr, + stk: Seq, + is_loop: bool, +) -> Option + decreases isize(body) + 1, 0nat, +{ + if top_sub(stk, bt.params) { + let lbl = if is_loop { + bt.params + } else { + bt.results + }; + let ctx2 = Ctx { locals: ctx.locals, labels: seq![lbl] + ctx.labels }; + let out = Flow::Falls(below(stk, bt.params.len()) + bt.results); + match tc(lay, ctx2, body, bt.params) { + Some(Flow::Falls(s)) => if stack_sub(s, bt.results) { + Some(out) + } else { + None + }, + Some(Flow::Diverges) => Some(out), + None => None, + } + } else { + None + } +} + +} // verus! From 598e1dda98be2894e0c0f9418b5350bbd9959427 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Tue, 17 Nov 2026 15:36:55 +0000 Subject: [PATCH 3/6] clazel-lir: soundness of the typing, proven (jit.md J.5) tc_sound: a well-typed instruction in a conforming state is never stuck (so every load and store is inside its region), and its outcome conforms to its typing. run_sound is the corollary for a function body. Also the Wasm-coverage comparison and the gaps, as crate docs. Co-Authored-By: Claude Sonnet 5.5 --- crates/clazel-lir/src/lib.rs | 112 ++++- crates/clazel-lir/src/soundness.rs | 741 +++++++++++++++++++++++++++++ crates/clazel-lir/src/spec.rs | 6 +- crates/clazel-lir/src/typing.rs | 34 +- 4 files changed, 868 insertions(+), 25 deletions(-) create mode 100644 crates/clazel-lir/src/soundness.rs diff --git a/crates/clazel-lir/src/lib.rs b/crates/clazel-lir/src/lib.rs index 0dbf34ae8..88fccd014 100644 --- a/crates/clazel-lir/src/lib.rs +++ b/crates/clazel-lir/src/lib.rs @@ -3,17 +3,119 @@ //! //! - [`syntax`]: types, values and instructions; //! - [`spec`]: the semantics, `spec fn eval`, with the modelling choices -//! listed at its top; -//! - [`typing`]: the typing judgment and the soundness theorem; +//! listed at its top (read those first); +//! - [`typing`]: the typing judgment `tc`; +//! - [`soundness`]: the soundness theorem `tc_sound`, and `run_sound` for a +//! whole function body; //! - [`examples`]: small programs with proven properties. //! -//! There is no back end and no front end. The crate depends on no other -//! browser crate and has no JavaScript-specific type (jit.md, "The -//! instruction-set layer knows nothing of JS"). +//! There is no back end and no front end. The crate depends only on `vstd` +//! and has no JavaScript-specific type (jit.md, "The instruction-set layer +//! knows nothing of JS"). +//! +//! # What is proven +//! +//! - **Determinism and totality of the semantics.** `eval` is a total +//! `spec fn`; it takes fuel, and running out is the outcome `OutOfFuel`. +//! - **Soundness of the typing** (`soundness::tc_sound`, proven, no axiom +//! and no assumption): a well-typed instruction in a conforming state is +//! never `Stuck`. In particular every `load` and `store` is in a region +//! that exists and inside its bound, because only an `Idx` index types, +//! and only `bounds_check` makes one. +//! - Concrete programs: typed, rejected when they should be, and evaluated. +//! +//! # What is only stated, or not covered +//! +//! - Nothing is stated-but-unproven in this crate. +//! - **Not covered:** the Wasm specification is not vendored, and its +//! section numbers in the comments are from memory of release 2.0 (the +//! instruction and operator names are exact); there is no independent +//! transcription, no mutation file and no conformance suite, so the crate +//! stays at tier 0 (`target-tier` 2 is jit.md's goal). +//! `f64` arithmetic and conversions are uninterpreted functions of the bit +//! patterns, so no property of IEEE rounding is proven here. +//! - Refinement by the back ends (J.9) and the front end (J.10) is future +//! work; they will be stated against `eval`. +//! +//! # Coverage of the WebAssembly core instructions (jit.md J.5) +//! +//! A Wasm front end (a later phase) needs the instructions of Wasm core 2.0 +//! §2.4. Present in LIR, each with the same meaning as in Wasm unless a note +//! says otherwise: +//! +//! - **Numeric, `i32` and `i64`:** `const`; `add`, `sub`, `mul`, `and`, +//! `or`, `xor`, `shl`, `shr_s`, `shr_u`, `rotl`, `rotr`; `eqz`; `eq`, `ne`, +//! `lt_s`, `lt_u`, `gt_s`, `gt_u`, `le_s`, `le_u`, `ge_s`, `ge_u`; +//! `i32.wrap_i64`, `i64.extend_i32_s`, `i64.extend_i32_u`. +//! - **Numeric, `f64`:** `const`; `add`, `sub`, `mul`, `div`, `sqrt`, `neg`, +//! `abs`; `eq`, `ne`, `lt`, `gt`, `le`, `ge`; `convert_i32_s`, +//! `convert_i32_u`, `convert_i64_s`, `convert_i64_u`; +//! `f64.reinterpret_i64`, `i64.reinterpret_f64`. +//! - **Parametric:** `drop`, `select` (the untyped form; operands of one +//! type). +//! - **Variable:** `local.get`, `local.set`, `local.tee`. +//! - **Memory:** `i32.load`, `i64.load`, `f64.load`, `i32.store`, +//! `i64.store`, `f64.store`, from a region, with the bounds check explicit +//! (a Wasm trap becomes the `bounds_check` exit). +//! - **Control:** `nop`; `block`, `loop`, `if` with multi-value block types +//! (parameters and results); `br`, `br_if`, `br_table`; `return` (a `br` to +//! the outermost label); `unreachable` (an `exit`). +//! +//! **Gaps**, with what a Wasm front end would do about each: +//! +//! - **Integer bit counting and division:** `clz`, `ctz`, `popcnt`, `div_s`, +//! `div_u`, `rem_s`, `rem_u`. The division family traps in Wasm (on zero, +//! and on `INT_MIN / -1`); add them with an explicit exit on the trapping +//! operands, as `bounds_check` does. +//! - **Sign-extension operators** (Wasm 2.0 `extend8_s`, `extend16_s`, +//! `extend32_s`): expressible as `shl` then `shr_s`; add the instruction +//! when a back end has a cheaper form. +//! - **`f64` rounding and sign operators:** `ceil`, `floor`, `trunc`, +//! `nearest`, `min`, `max`, `copysign`. `min`, `max` and `copysign` are +//! definable from the comparison and the bit operations; the rounding ones +//! are uninterpreted functions of the bits, like `add`, when added. +//! - **Float-to-integer conversion:** `trunc_f64_{s,u}` (trapping) and +//! `trunc_sat_f64_{s,u}`. The JS engine's `ToInt32` and checked +//! double-to-int paths will need one of them. +//! - **`f32`**, with `demote`, `promote`, and `i32.reinterpret_f32`: LIR has +//! no `f32` type (jit.md: "later `f32`"). +//! - **Narrow memory access:** `load8_s`, `load8_u`, `load16_*`, `load32_*`, +//! `store8`, `store16`, `store32`, and the `offset` and `align` immediates +//! (a front end adds the offset to the index in `i64`, so the effective +//! address is not computed modulo 2^32 or 2^33 as in Wasm). The access +//! width becomes a field of `load` and `store`, and the type of `Idx` +//! already carries a size. +//! - **Memory growth and bulk memory:** `memory.size`, `memory.grow`, +//! `memory.fill`, `memory.copy`, `memory.init`, `data.drop`. The layout is +//! a constant of one entry (jit.md: regions are passed afresh at each +//! entry), so growth must be an `exit` and a re-entry with a new layout; +//! fill and copy are loops over `load` and `store`, or an exit. +//! - **Globals:** `global.get`, `global.set`. A global is a slot of a region +//! (a region of globals), reached with `load`/`store` at a constant index; +//! no new instruction is needed, but the front end's mapping is untested. +//! - **Calls:** `call`, `call_indirect`, `return_call`: jit.md forbids calls +//! from generated code. A Wasm front end inlines, or exits to the host +//! with the arguments, and `call_indirect` is an exit that does the table +//! lookup in Rust. This is the largest gap and fixes the design of a +//! multi-function Wasm blob; this crate has one function body. +//! - **Reference types and tables:** `ref.null`, `ref.is_null`, `ref.func`, +//! `table.*`, typed `select`. LIR has no reference types; tables are +//! regions of `i64` and references would be indexes (jit.md, "heap +//! references as arena indexes"). +//! - **SIMD** (`v128`): no type, no instructions. +//! - **Stack-polymorphic code** after `br`, `br_table`, `return`, +//! `unreachable`: Wasm accepts it (§3.3.8); LIR's typing rejects any +//! instruction after one that cannot fall through, so a Wasm front end +//! drops dead code before it lowers (which a one-pass lowering can do by +//! tracking validity as Wasm's own validation algorithm does). +//! - **Nondeterminism:** Wasm leaves the NaN payload of float results, and +//! the choice of `memory.grow` outcome, open. LIR fixes one choice +//! (uninterpreted but deterministic functions), which refines Wasm. //! //! Tier: see `[package.metadata.clazel]` in `Cargo.toml` and //! `docs/VERIFICATION.md`. +pub mod soundness; pub mod spec; pub mod syntax; pub mod typing; diff --git a/crates/clazel-lir/src/soundness.rs b/crates/clazel-lir/src/soundness.rs new file mode 100644 index 000000000..c8412a4c5 --- /dev/null +++ b/crates/clazel-lir/src/soundness.rs @@ -0,0 +1,741 @@ +//! The soundness of LIR's typing (docs/phases/jit.md item J.5): `tc_sound`. +//! +//! If `tc(lay, ctx, i, stk) == Some(fl)` and the state conforms to `stk` and +//! to the locals' types, then for every amount of fuel, `eval` of `i`: +//! +//! - is never [`Outcome::Stuck`]. So every operand exists and has the right +//! type, every local index is in range, and every `load` and `store` names +//! an existing region and an address inside it; +//! - if it falls through (`Normal`), `fl` was `Falls(rs)` and the new state +//! conforms to `rs` (a `Diverges` instruction never falls through); +//! - if it branches, the label exists and the values it carries conform to +//! the label's types, so the label's handler is never `Stuck` either; +//! - if it exits, the locals still conform (this is what lets a resume +//! point trust them). +//! +//! The proof is by induction on the fuel, the same measure `eval` recurses +//! on. `tc_sound` and `lemma_finish` (what happens when a block's body +//! has produced its outcome) call each other. +//! +//! Proof status: everything here is proven, with no assumption and no axiom. + +#[allow(unused_imports)] +use super::spec::*; +pub use super::typing::*; +#[allow(unused_imports)] +use vstd::prelude::*; + +verus! { + +/// The state conforms to the context's locals and to the stack types. +pub open spec fn state_ok(lay: Layout, ctx: Ctx, st: St, stk: Seq) -> bool { + vals_conform(lay, st.stack, stk) && vals_conform(lay, st.locals, ctx.locals) +} + +/// What the typing promises about an outcome, given the flow it computed. +pub open spec fn outcome_ok(lay: Layout, ctx: Ctx, fl: Flow, o: Outcome) -> bool { + match o { + Outcome::Stuck => false, + Outcome::OutOfFuel => true, + Outcome::Normal(s) => match fl { + Flow::Falls(rs) => state_ok(lay, ctx, s, rs), + Flow::Diverges => false, + }, + Outcome::Branch(n, s) => n < ctx.labels.len() && vals_conform(lay, s.locals, ctx.locals) + && s.stack.len() >= ctx.labels[n as int].len() && vals_conform( + lay, + top(s.stack, ctx.labels[n as int].len()), + ctx.labels[n as int], + ), + Outcome::Exit(_, _, s) => vals_conform(lay, s.locals, ctx.locals), + } +} + +// --------------------------------------------------------------------- +// Facts about sequences of values and types +// --------------------------------------------------------------------- + +proof fn lemma_sub_refl(t: Ty) + ensures + ty_sub(t, t), +{ +} + +proof fn lemma_stack_sub_refl(s: Seq) + ensures + stack_sub(s, s), +{ + assert forall|j: int| 0 <= j < s.len() implies ty_sub(#[trigger] s[j], s[j]) by { + lemma_sub_refl(s[j]); + } +} + +proof fn lemma_conf_sub(lay: Layout, v: Val, t: Ty, u: Ty) + requires + conforms(lay, v, t), + ty_sub(t, u), + ensures + conforms(lay, v, u), +{ +} + +proof fn lemma_vals_sub(lay: Layout, vs: Seq, ts: Seq, us: Seq) + requires + vals_conform(lay, vs, ts), + stack_sub(ts, us), + ensures + vals_conform(lay, vs, us), +{ + assert forall|j: int| 0 <= j < vs.len() implies conforms(lay, #[trigger] vs[j], us[j]) by { + lemma_conf_sub(lay, vs[j], ts[j], us[j]); + } +} + +proof fn lemma_vals_push(lay: Layout, vs: Seq, ts: Seq, v: Val, t: Ty) + requires + vals_conform(lay, vs, ts), + conforms(lay, v, t), + ensures + vals_conform(lay, vs.push(v), ts.push(t)), +{ + assert forall|j: int| 0 <= j < vs.push(v).len() implies conforms( + lay, + #[trigger] vs.push(v)[j], + ts.push(t)[j], + ) by { + if j < vs.len() { + assert(vs.push(v)[j] == vs[j]); + assert(ts.push(t)[j] == ts[j]); + } else { + assert(vs.push(v)[j] == v); + assert(ts.push(t)[j] == t); + } + } +} + +proof fn lemma_vals_below_top(lay: Layout, vs: Seq, ts: Seq, k: nat) + requires + vals_conform(lay, vs, ts), + k <= vs.len(), + ensures + vals_conform(lay, below(vs, k), below(ts, k)), + vals_conform(lay, top(vs, k), top(ts, k)), +{ + assert forall|j: int| 0 <= j < below(vs, k).len() implies conforms( + lay, + #[trigger] below(vs, k)[j], + below(ts, k)[j], + ) by { + assert(below(vs, k)[j] == vs[j]); + assert(below(ts, k)[j] == ts[j]); + } + assert forall|j: int| 0 <= j < top(vs, k).len() implies conforms( + lay, + #[trigger] top(vs, k)[j], + top(ts, k)[j], + ) by { + assert(top(vs, k)[j] == vs[vs.len() - k + j]); + assert(top(ts, k)[j] == ts[vs.len() - k + j]); + } +} + +proof fn lemma_vals_concat(lay: Layout, a: Seq, x: Seq, b: Seq, y: Seq) + requires + vals_conform(lay, a, x), + vals_conform(lay, b, y), + ensures + vals_conform(lay, a + b, x + y), +{ + assert forall|j: int| 0 <= j < (a + b).len() implies conforms( + lay, + #[trigger] (a + b)[j], + (x + y)[j], + ) by { + if j < a.len() { + assert((a + b)[j] == a[j]); + assert((x + y)[j] == x[j]); + } else { + assert((a + b)[j] == b[j - a.len()]); + assert((x + y)[j] == y[j - a.len()]); + } + } +} + +/// The top values of a conforming stack conform to the types the stack's +/// top types are subtypes of. +proof fn lemma_top_conform(lay: Layout, vs: Seq, stk: Seq, tys: Seq) + requires + vals_conform(lay, vs, stk), + top_sub(stk, tys), + ensures + vs.len() >= tys.len(), + vals_conform(lay, top(vs, tys.len()), tys), +{ + lemma_vals_below_top(lay, vs, stk, tys.len()); + lemma_vals_sub(lay, top(vs, tys.len()), top(stk, tys.len()), tys); +} + +/// Popping one element with `below` is `drop_last`. +proof fn lemma_below1(s: Seq) + requires + s.len() >= 1, + ensures + below(s, 1) == s.drop_last(), +{ + assert(below(s, 1) =~= s.drop_last()); +} + +/// A sequence is its `below(.., k)` followed by its `top(.., k)`. +proof fn lemma_split(s: Seq, k: nat) + requires + k <= s.len(), + ensures + below(s, k) + top(s, k) == s, +{ + assert(below(s, k) + top(s, k) =~= s); +} + +// --------------------------------------------------------------------- +// Numeric operators +// --------------------------------------------------------------------- + +proof fn lemma_bin_sound(lay: Layout, op: BinOp, a: Val, b: Val, ta: Ty, tb: Ty) + requires + conforms(lay, a, ta), + conforms(lay, b, tb), + ty_sub(ta, bin_arg(op)), + ty_sub(tb, bin_arg(op)), + ensures + bin_eval(op, a, b) is Some, + conforms(lay, bin_eval(op, a, b).unwrap(), bin_res(op)), +{ + lemma_conf_sub(lay, a, ta, bin_arg(op)); + lemma_conf_sub(lay, b, tb, bin_arg(op)); +} + +proof fn lemma_un_sound(lay: Layout, op: UnOp, a: Val, ta: Ty) + requires + conforms(lay, a, ta), + ty_sub(ta, un_arg(op)), + ensures + un_eval(op, a) is Some, + conforms(lay, un_eval(op, a).unwrap(), un_res(op)), +{ + lemma_conf_sub(lay, a, ta, un_arg(op)); +} + +// --------------------------------------------------------------------- +// Blocks +// --------------------------------------------------------------------- + +/// Whatever `tc_blk` accepts, it types as `below(stk, k) + results`. +proof fn lemma_blk_form( + lay: Layout, + ctx: Ctx, + bt: BlockType, + body: Instr, + stk: Seq, + is_loop: bool, + fl: Flow, +) + requires + tc_blk(lay, ctx, bt, body, stk, is_loop) == Some(fl), + ensures + fl == Flow::Falls(below(stk, bt.params.len()) + bt.results), + top_sub(stk, bt.params), +{ +} + +/// The label context inside a block's body. +pub open spec fn body_ctx(ctx: Ctx, bt: BlockType, is_loop: bool) -> Ctx { + Ctx { + locals: ctx.locals, + labels: seq![if is_loop { + bt.params + } else { + bt.results + }] + ctx.labels, + } +} + +/// The body's typing, if the block's is `Some`: there is a flow `fb` for it, +/// with a `Falls` having a stack that is a subtype of the results. +proof fn lemma_blk_body( + lay: Layout, + ctx: Ctx, + bt: BlockType, + body: Instr, + stk: Seq, + is_loop: bool, + fl: Flow, +) -> (fb: Flow) + requires + tc_blk(lay, ctx, bt, body, stk, is_loop) == Some(fl), + ensures + tc(lay, body_ctx(ctx, bt, is_loop), body, bt.params) == Some(fb), + match fb { + Flow::Falls(s) => stack_sub(s, bt.results), + Flow::Diverges => true, + }, +{ + let ctx2 = body_ctx(ctx, bt, is_loop); + match tc(lay, ctx2, body, bt.params) { + Some(fb) => fb, + None => { + assert(false); + Flow::Diverges + }, + } +} + +/// The block's body produced the outcome `o` (which conforms to the body's +/// typing); the block-like instruction then finishes. This is `finish_label` +/// of `eval`, for the `block` (`is_loop` false) and the `loop`. +proof fn lemma_finish( + lay: Layout, + ctx: Ctx, + bt: BlockType, + body: Instr, + is_loop: bool, + stk: Seq, + st: St, + fb: Flow, + o: Outcome, + fuel: nat, + fl: Flow, +) + requires + tc_blk(lay, ctx, bt, body, stk, is_loop) == Some(fl), + state_ok(lay, ctx, st, stk), + tc(lay, body_ctx(ctx, bt, is_loop), body, bt.params) == Some(fb), + match fb { + Flow::Falls(s) => stack_sub(s, bt.results), + Flow::Diverges => true, + }, + outcome_ok(lay, body_ctx(ctx, bt, is_loop), fb, o), + ensures + outcome_ok( + lay, + ctx, + fl, + finish_label( + lay, + below(st.stack, bt.params.len()), + if is_loop { + bt.params.len() + } else { + bt.results.len() + }, + if is_loop { + Some(Instr::Loop(bt, Box::new(body))) + } else { + None + }, + o, + fuel, + ), + ), + decreases fuel, 0nat, +{ + let k = bt.params.len(); + let ctx2 = body_ctx(ctx, bt, is_loop); + lemma_blk_form(lay, ctx, bt, body, stk, is_loop, fl); + lemma_vals_below_top(lay, st.stack, stk, k); + let lbl = if is_loop { + bt.params + } else { + bt.results + }; + assert(ctx2.labels[0] == lbl); + match o { + Outcome::Normal(s) => { + // The body fell through, so its flow was `Falls(s_ty)`. + match fb { + Flow::Falls(sty) => { + lemma_vals_sub(lay, s.stack, sty, bt.results); + lemma_vals_concat( + lay, + below(st.stack, k), + below(stk, k), + s.stack, + bt.results, + ); + }, + Flow::Diverges => {}, + } + }, + Outcome::Branch(n, s) => { + if n > 0 { + assert(ctx2.labels[n as int] == ctx.labels[n - 1]); + } else { + // The label is this block: it carries `lbl.len()` values. + assert(ctx2.labels[0].len() == lbl.len()); + lemma_vals_concat( + lay, + below(st.stack, k), + below(stk, k), + top(s.stack, lbl.len()), + lbl, + ); + if is_loop { + // Branching to a loop restarts it, in the stack + // `below(stk, k) + params`. + if fuel > 0 { + let stk2 = below(stk, k) + bt.params; + let carried = below(st.stack, k) + top(s.stack, k); + let st2 = s.with_stack(carried); + assert(below(stk2, k) =~= below(stk, k)); + assert(top(stk2, k) =~= bt.params); + lemma_stack_sub_refl(bt.params); + assert(top_sub(stk2, bt.params)); + assert(tc_blk(lay, ctx, bt, body, stk2, true) == tc_blk( + lay, + ctx, + bt, + body, + stk, + true, + )); + assert(state_ok(lay, ctx, st2, stk2)); + tc_sound( + lay, + ctx, + Instr::Loop(bt, Box::new(body)), + stk2, + st2, + (fuel - 1) as nat, + fl, + ); + } + } + } + }, + _ => {}, + } +} + +// --------------------------------------------------------------------- +// The theorem +// --------------------------------------------------------------------- + +/// **A whole function.** The body type-checks with the single label +/// `results` (the return), and either diverges or falls through to a stack +/// that is a subtype of `results`. Then `run` of it, from a conforming state, +/// is never stuck, and if it returns (falls through or branches to the +/// return) the top values conform to the results. +pub proof fn run_sound( + lay: Layout, + locals: Seq, + results: Seq, + body: Instr, + params: Seq, + st: St, + fuel: nat, + fl: Flow, +) + requires + tc(lay, Ctx { locals: locals, labels: seq![results] }, body, params) == Some(fl), + match fl { + Flow::Falls(rs) => stack_sub(rs, results), + Flow::Diverges => true, + }, + state_ok(lay, Ctx { locals: locals, labels: seq![results] }, st, params), + ensures + !(run(lay, body, st, fuel) is Stuck), + match run(lay, body, st, fuel) { + Outcome::Normal(s) => s.stack.len() >= results.len() && vals_conform( + lay, + top(s.stack, results.len()), + results, + ), + _ => true, + }, +{ + let ctx = Ctx { locals: locals, labels: seq![results] }; + tc_sound(lay, ctx, body, params, st, fuel, fl); + match eval(lay, body, st, fuel) { + Outcome::Normal(s) => { + match fl { + Flow::Falls(rs) => { + lemma_vals_sub(lay, s.stack, rs, results); + assert(top(s.stack, results.len()) =~= s.stack); + }, + Flow::Diverges => {}, + } + }, + _ => {}, + } +} + +/// **Soundness of the typing.**A well-typed instruction, started in a +/// conforming state, with any amount of fuel, is never stuck and does what +/// its typing says (see the module docs and [`outcome_ok`]). +pub proof fn tc_sound(lay: Layout, ctx: Ctx, i: Instr, stk: Seq, st: St, fuel: nat, fl: Flow) + requires + tc(lay, ctx, i, stk) == Some(fl), + state_ok(lay, ctx, st, stk), + ensures + outcome_ok(lay, ctx, fl, eval(lay, i, st, fuel)), + decreases fuel, 1nat, +{ + if fuel == 0 { + return ; + } + let f = (fuel - 1) as nat; + let n = st.stack.len(); + assert(n == stk.len()); + match i { + Instr::Nop => {}, + Instr::Then(a, b) => { + match tc(lay, ctx, *a, stk) { + Some(Flow::Falls(s1)) => { + tc_sound(lay, ctx, *a, stk, st, f, Flow::Falls(s1)); + match eval(lay, *a, st, f) { + Outcome::Normal(s2) => { + tc_sound(lay, ctx, *b, s1, s2, f, fl); + }, + _ => {}, + } + }, + _ => {}, + } + }, + Instr::Const(v) => { + lemma_vals_push(lay, st.stack, stk, v, val_ty(v)); + }, + Instr::LocalGet(x) => { + assert(conforms(lay, st.locals[x as int], ctx.locals[x as int])); + lemma_vals_push(lay, st.stack, stk, st.locals[x as int], ctx.locals[x as int]); + }, + Instr::LocalSet(x) => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + lemma_conf_sub(lay, st.stack[n - 1], stk[n - 1], ctx.locals[x as int]); + lemma_vals_below_top(lay, st.stack, stk, 1); + lemma_below1(st.stack); + lemma_below1(stk); + let nl = st.locals.update(x as int, st.stack.last()); + assert forall|j: int| 0 <= j < nl.len() implies conforms( + lay, + #[trigger] nl[j], + ctx.locals[j], + ) by { + if j == x as int { + } else { + assert(nl[j] == st.locals[j]); + } + } + }, + Instr::LocalTee(x) => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + lemma_conf_sub(lay, st.stack[n - 1], stk[n - 1], ctx.locals[x as int]); + let nl = st.locals.update(x as int, st.stack.last()); + assert forall|j: int| 0 <= j < nl.len() implies conforms( + lay, + #[trigger] nl[j], + ctx.locals[j], + ) by { + if j == x as int { + } else { + assert(nl[j] == st.locals[j]); + } + } + }, + Instr::Drop => { + lemma_vals_below_top(lay, st.stack, stk, 1); + lemma_below1(st.stack); + lemma_below1(stk); + }, + Instr::Select => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + assert(conforms(lay, st.stack[n - 2], stk[n - 2])); + assert(conforms(lay, st.stack[n - 3], stk[n - 3])); + lemma_vals_below_top(lay, st.stack, stk, 3); + match st.stack[n - 1] { + Val::I32(c) => { + let v = if c != 0 { + st.stack[n - 3] + } else { + st.stack[n - 2] + }; + assert(conforms(lay, v, stk[n - 3])); + lemma_vals_push(lay, below(st.stack, 3), below(stk, 3), v, stk[n - 3]); + }, + _ => {}, + } + }, + Instr::Bin(op) => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + assert(conforms(lay, st.stack[n - 2], stk[n - 2])); + lemma_bin_sound(lay, op, st.stack[n - 2], st.stack[n - 1], stk[n - 2], stk[n - 1]); + lemma_vals_below_top(lay, st.stack, stk, 2); + lemma_vals_push( + lay, + below(st.stack, 2), + below(stk, 2), + bin_eval(op, st.stack[n - 2], st.stack[n - 1]).unwrap(), + bin_res(op), + ); + }, + Instr::Un(op) => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + lemma_un_sound(lay, op, st.stack[n - 1], stk[n - 1]); + lemma_vals_below_top(lay, st.stack, stk, 1); + lemma_vals_push( + lay, + below(st.stack, 1), + below(stk, 1), + un_eval(op, st.stack[n - 1]).unwrap(), + un_res(op), + ); + }, + Instr::BoundsCheck { region, size, code } => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + lemma_conf_sub(lay, st.stack[n - 1], stk[n - 1], Ty::I64); + lemma_vals_below_top(lay, st.stack, stk, 1); + match st.stack[n - 1] { + Val::I64(ix) => { + if ix as nat + size <= lay[region as int].bound { + assert(st.stack =~= below(st.stack, 1).push(st.stack[n - 1])); + lemma_vals_push( + lay, + below(st.stack, 1), + below(stk, 1), + st.stack[n - 1], + Ty::Idx(region, size), + ); + } + }, + _ => {}, + } + }, + Instr::Load { region, ty } => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + lemma_conf_sub(lay, st.stack[n - 1], stk[n - 1], Ty::Idx(region, ty_size(ty))); + lemma_vals_below_top(lay, st.stack, stk, 1); + match st.stack[n - 1] { + Val::I64(ix) => { + let r = lay[region as int]; + assert(ix as nat + ty_size(ty) <= r.bound); + let v = val_of_bits(ty, read_le(st.mem, r.base + masked(r.bound, ix as nat), ty_size(ty))); + assert(conforms(lay, v, ty)); + lemma_vals_push(lay, below(st.stack, 1), below(stk, 1), v, ty); + }, + _ => {}, + } + }, + Instr::Store { region, ty } => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + assert(conforms(lay, st.stack[n - 2], stk[n - 2])); + lemma_conf_sub(lay, st.stack[n - 1], stk[n - 1], ty); + lemma_conf_sub(lay, st.stack[n - 2], stk[n - 2], Ty::Idx(region, ty_size(ty))); + lemma_vals_below_top(lay, st.stack, stk, 2); + match st.stack[n - 2] { + Val::I64(ix) => { + let r = lay[region as int]; + assert(ix as nat + ty_size(ty) <= r.bound); + }, + _ => {}, + } + }, + Instr::Block(bt, body) => { + let k = bt.params.len(); + let fb = lemma_blk_body(lay, ctx, bt, *body, stk, false, fl); + lemma_blk_form(lay, ctx, bt, *body, stk, false, fl); + lemma_top_conform(lay, st.stack, stk, bt.params); + let sb = st.with_stack(top(st.stack, k)); + tc_sound(lay, body_ctx(ctx, bt, false), *body, bt.params, sb, f, fb); + lemma_finish( + lay, + ctx, + bt, + *body, + false, + stk, + st, + fb, + eval(lay, *body, sb, f), + f, + fl, + ); + }, + Instr::Loop(bt, body) => { + let k = bt.params.len(); + let fb = lemma_blk_body(lay, ctx, bt, *body, stk, true, fl); + lemma_blk_form(lay, ctx, bt, *body, stk, true, fl); + lemma_top_conform(lay, st.stack, stk, bt.params); + let sb = st.with_stack(top(st.stack, k)); + tc_sound(lay, body_ctx(ctx, bt, true), *body, bt.params, sb, f, fb); + lemma_finish(lay, ctx, bt, *body, true, stk, st, fb, eval(lay, *body, sb, f), f, fl); + }, + Instr::If(bt, t, e) => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + lemma_conf_sub(lay, st.stack[n - 1], stk[n - 1], Ty::I32); + lemma_vals_below_top(lay, st.stack, stk, 1); + lemma_below1(st.stack); + lemma_below1(stk); + let stk1 = stk.drop_last(); + let st1 = st.with_stack(below(st.stack, 1)); + match st.stack[n - 1] { + Val::I32(c) => { + let chosen = if c != 0 { + t + } else { + e + }; + if let (Some(f1), Some(f2)) = ( + tc_blk(lay, ctx, bt, *t, stk1, false), + tc_blk(lay, ctx, bt, *e, stk1, false), + ) { + lemma_blk_form(lay, ctx, bt, *t, stk1, false, f1); + lemma_blk_form(lay, ctx, bt, *e, stk1, false, f2); + tc_sound(lay, ctx, Instr::Block(bt, chosen), stk1, st1, f, fl); + } + }, + _ => {}, + } + }, + Instr::Br(l) => { + lemma_top_conform(lay, st.stack, stk, ctx.labels[l as int]); + }, + Instr::BrIf(l) => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + lemma_conf_sub(lay, st.stack[n - 1], stk[n - 1], Ty::I32); + lemma_vals_below_top(lay, st.stack, stk, 1); + lemma_below1(st.stack); + lemma_below1(stk); + lemma_top_conform(lay, below(st.stack, 1), below(stk, 1), ctx.labels[l as int]); + }, + Instr::BrTable(ls, d) => { + assert(conforms(lay, st.stack[n - 1], stk[n - 1])); + lemma_conf_sub(lay, st.stack[n - 1], stk[n - 1], Ty::I32); + lemma_vals_below_top(lay, st.stack, stk, 1); + lemma_below1(st.stack); + lemma_below1(stk); + match st.stack[n - 1] { + Val::I32(c) => { + if (c as nat) < ls.len() { + lemma_top_conform( + lay, + below(st.stack, 1), + below(stk, 1), + ctx.labels[ls[c as int] as int], + ); + } else { + lemma_top_conform( + lay, + below(st.stack, 1), + below(stk, 1), + ctx.labels[d as int], + ); + } + }, + _ => {}, + } + }, + Instr::Exit(code, tys) => { + lemma_top_conform(lay, st.stack, stk, tys); + }, + } +} + +} // verus! diff --git a/crates/clazel-lir/src/spec.rs b/crates/clazel-lir/src/spec.rs index 7ff764c9e..8194baed2 100644 --- a/crates/clazel-lir/src/spec.rs +++ b/crates/clazel-lir/src/spec.rs @@ -1,5 +1,5 @@ //! LIR's semantics (docs/phases/jit.md item J.5): a big-step, fuelled -//! interpreter written as a `spec fn`, [`eval`]. +//! interpreter written as a `spec fn`, `eval`. //! //! It transcribes the numeric, variable, parametric, memory and control //! instructions of the WebAssembly core specification, release 2.0 @@ -33,7 +33,7 @@ //! because Wasm's validation forbids a body from reaching below its //! parameters. //! 3. **No function calls, no tables, no globals, no `memory.grow`.** There -//! is one function body, run by [`run`], whose label `0` (outermost) is +//! is one function body, run by `run`, whose label `0` (outermost) is //! "return". Wasm's trap is the outcome `Exit` (jit.md: services and //! traps are exits); an `exit` is also LIR's only way to stop other than //! falling off the end or a return. @@ -55,7 +55,7 @@ //! end's masking is a refinement of it, not an addition to it. //! 6. **`f64` arithmetic is uninterpreted.** `add`, `sub`, `mul`, `div`, //! `sqrt` and the integer-to-float conversions are the uninterpreted -//! functions [`f64_add`] and so on, over bit patterns. IEEE 754 rounding +//! functions `f64_add` and so on, over bit patterns. IEEE 754 rounding //! is not transcribed (the JS engine's `spec` does the same, and the //! hardware semantics in `clazel-x64` and `clazel-a64` is what the back //! ends are proven against). Wasm leaves the sign and payload of a NaN diff --git a/crates/clazel-lir/src/typing.rs b/crates/clazel-lir/src/typing.rs index 9564aec96..a5a594fab 100644 --- a/crates/clazel-lir/src/typing.rs +++ b/crates/clazel-lir/src/typing.rs @@ -1,7 +1,7 @@ //! LIR's typing judgment and its soundness theorem (docs/phases/jit.md item //! J.5). //! -//! The judgment is [`tc`]: given the layout, a context (the types of the +//! The judgment is `tc`: given the layout, a context (the types of the //! locals and of the enclosing labels) and the types of the operand stack, //! it says whether an instruction is well-typed and what it leaves on the //! stack. It is Wasm core 2.0 §3.3 "Instructions" (validation), written as @@ -21,8 +21,8 @@ //! 3. **No function, table, global or reference instructions**; one body, //! with label 0 as its return (see `spec`). //! -//! The soundness theorem, `tc_sound`, is stated and proven in the commit -//! after this one: a well-typed instruction, started in a state that +//! The soundness theorem, `soundness::tc_sound`, is proven in +//! [`crate::soundness`]: a well-typed instruction, started in a state that //! conforms to its input types, is never [`Outcome::Stuck`] (so every load //! and store is inside its region, every operand exists and has the right //! type), and whatever it does conforms to what the typing said. @@ -40,7 +40,7 @@ verus! { /// `a` may be used where `b` is expected. `Idx(r, n)` is an `i64`, and it /// is an `Idx(r, m)` for any smaller `m`; otherwise only equal types match. -pub open spec fn sub(a: Ty, b: Ty) -> bool { +pub open spec fn ty_sub(a: Ty, b: Ty) -> bool { match (a, b) { (Ty::Idx(r, n), Ty::Idx(s, m)) => r == s && m <= n, (Ty::Idx(_, _), Ty::I64) => true, @@ -50,7 +50,7 @@ pub open spec fn sub(a: Ty, b: Ty) -> bool { /// `sub` pointwise, on sequences of equal length. pub open spec fn stack_sub(a: Seq, b: Seq) -> bool { - a.len() == b.len() && forall|j: int| 0 <= j < a.len() ==> sub(#[trigger] a[j], b[j]) + a.len() == b.len() && forall|j: int| 0 <= j < a.len() ==> ty_sub(#[trigger] a[j], b[j]) } /// The top `tys.len()` types of `stk` are subtypes of `tys`. @@ -151,7 +151,7 @@ pub enum Flow { Diverges, } -/// The number of nodes of an instruction, the measure of [`tc`]. +/// The number of nodes of an instruction, the measure of `tc`. pub open spec fn isize(i: Instr) -> nat decreases i, { @@ -193,7 +193,7 @@ pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option []. Instr::LocalSet(x) => { - if x < ctx.locals.len() && n >= 1 && sub(stk.last(), ctx.locals[x as int]) { + if x < ctx.locals.len() && n >= 1 && ty_sub(stk.last(), ctx.locals[x as int]) { Some(Flow::Falls(stk.drop_last())) } else { None @@ -201,7 +201,7 @@ pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option [t]. Instr::LocalTee(x) => { - if x < ctx.locals.len() && n >= 1 && sub(stk.last(), ctx.locals[x as int]) { + if x < ctx.locals.len() && n >= 1 && ty_sub(stk.last(), ctx.locals[x as int]) { Some(Flow::Falls(stk)) } else { None @@ -225,7 +225,7 @@ pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option [t] or [i32]. Instr::Bin(op) => { - if n >= 2 && sub(stk[n - 2], bin_arg(op)) && sub(stk[n - 1], bin_arg(op)) { + if n >= 2 && ty_sub(stk[n - 2], bin_arg(op)) && ty_sub(stk[n - 1], bin_arg(op)) { Some(Flow::Falls(below(stk, 2).push(bin_res(op)))) } else { None @@ -233,7 +233,7 @@ pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option [t2]. Instr::Un(op) => { - if n >= 1 && sub(stk[n - 1], un_arg(op)) { + if n >= 1 && ty_sub(stk[n - 1], un_arg(op)) { Some(Flow::Falls(below(stk, 1).push(un_res(op)))) } else { None @@ -241,7 +241,7 @@ pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option [Idx(region, size)]. Instr::BoundsCheck { region, size, code } => { - if region < lay.len() && n >= 1 && sub(stk[n - 1], Ty::I64) { + if region < lay.len() && n >= 1 && ty_sub(stk[n - 1], Ty::I64) { Some(Flow::Falls(below(stk, 1).push(Ty::Idx(region, size)))) } else { None @@ -250,7 +250,7 @@ pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option [t], with the address an // `Idx` of the region for the size of `t`. Instr::Load { region, ty } => { - if ty_size(ty) > 0 && region < lay.len() && n >= 1 && sub( + if ty_size(ty) > 0 && region < lay.len() && n >= 1 && ty_sub( stk[n - 1], Ty::Idx(region, ty_size(ty)), ) { @@ -261,10 +261,10 @@ pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option []. Instr::Store { region, ty } => { - if ty_size(ty) > 0 && region < lay.len() && n >= 2 && sub( + if ty_size(ty) > 0 && region < lay.len() && n >= 2 && ty_sub( stk[n - 2], Ty::Idx(region, ty_size(ty)), - ) && sub(stk[n - 1], ty) { + ) && ty_sub(stk[n - 1], ty) { Some(Flow::Falls(below(stk, 2))) } else { None @@ -276,7 +276,7 @@ pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option [t2*], both arms typed as // blocks. Instr::If(bt, t, e) => { - if n >= 1 && sub(stk[n - 1], Ty::I32) { + if n >= 1 && ty_sub(stk[n - 1], Ty::I32) { match ( tc_blk(lay, ctx, bt, *t, stk.drop_last(), false), tc_blk(lay, ctx, bt, *e, stk.drop_last(), false), @@ -299,7 +299,7 @@ pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option [t*]. Instr::BrIf(l) => { - if n >= 1 && sub(stk[n - 1], Ty::I32) && l < ctx.labels.len() && top_sub( + if n >= 1 && ty_sub(stk[n - 1], Ty::I32) && l < ctx.labels.len() && top_sub( stk.drop_last(), ctx.labels[l as int], ) { @@ -311,7 +311,7 @@ pub open spec fn tc(lay: Layout, ctx: Ctx, i: Instr, stk: Seq) -> Option { - if n >= 1 && sub(stk[n - 1], Ty::I32) && d < ctx.labels.len() && top_sub( + if n >= 1 && ty_sub(stk[n - 1], Ty::I32) && d < ctx.labels.len() && top_sub( stk.drop_last(), ctx.labels[d as int], ) && (forall|j: int| From 863fe2ff2c86342935434af39bf521771d938e82 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Tue, 17 Nov 2026 15:37:02 +0000 Subject: [PATCH 4/6] clazel-lir: proven examples (jit.md J.5) A bounds-checked load, a countdown loop and a store-then-load, typed, rejected when they should be (no check, a short check, dead code), shown never stuck by tc_sound, and evaluated. Co-Authored-By: Claude Sonnet 5.5 --- crates/clazel-lir/src/examples.rs | 295 ++++++++++++++++++++++++++++++ crates/clazel-lir/src/lib.rs | 1 + 2 files changed, 296 insertions(+) create mode 100644 crates/clazel-lir/src/examples.rs diff --git a/crates/clazel-lir/src/examples.rs b/crates/clazel-lir/src/examples.rs new file mode 100644 index 000000000..cd462b2a9 --- /dev/null +++ b/crates/clazel-lir/src/examples.rs @@ -0,0 +1,295 @@ +//! Small LIR programs with proven properties: evidence that the typing +//! accepts what a front end would write, rejects what it must, and that the +//! soundness theorem applies to concrete code. +//! +//! - `load_at`: the bounds-checked load every JS property access lowers +//! to. It type-checks; the typing rejects the same code with the +//! `bounds_check` removed or with dead code after a branch; and by +//! `tc_sound` it is never stuck, whatever the index (the bounds failure +//! is an `exit`, `example_load_at_exits`). +//! - `countdown`: a loop with a `br_if` back edge, typed, and by +//! `tc_sound` never stuck for any fuel. +//! - `store_then_load`: memory through a region. + +#[allow(unused_imports)] +use super::spec::*; +pub use super::typing::*; +#[allow(unused_imports)] +use vstd::prelude::*; + +verus! { + +/// `a; b`. +pub open spec fn then(a: Instr, b: Instr) -> Instr { + Instr::Then(Box::new(a), Box::new(b)) +} + +/// One region of 64 bytes at `0x1000`. +pub open spec fn lay1() -> Layout { + seq![Region { base: 0x1000, bound: 64 }] +} + +/// Local 0 is an `i64` index. Check it against region 0 for 8 bytes (exit +/// with code 7 if it does not fit), then load the `i64` there. +pub open spec fn load_at() -> Instr { + then( + Instr::LocalGet(0), + then( + Instr::BoundsCheck { region: 0, size: 8, code: 7 }, + Instr::Load { region: 0, ty: Ty::I64 }, + ), + ) +} + +/// The context of `load_at`: one `i64` local, and the function's return +/// label taking an `i64`. +pub open spec fn ctx_load() -> Ctx { + Ctx { locals: seq![Ty::I64], labels: seq![seq![Ty::I64]] } +} + +/// `load_at` type-checks, leaving an `i64`. +pub proof fn example_load_at_types() + ensures + tc(lay1(), ctx_load(), load_at(), seq![]) == Some(Flow::Falls(seq![Ty::I64])), +{ + let l = lay1(); + let c = ctx_load(); + let bc = Instr::BoundsCheck { region: 0, size: 8, code: 7 }; + let ld = Instr::Load { region: 0, ty: Ty::I64 }; + assert(Seq::::empty().push(Ty::I64) =~= seq![Ty::I64]); + assert(below(seq![Ty::I64], 1).push(Ty::Idx(0, 8)) =~= seq![Ty::Idx(0, 8)]); + assert(below(seq![Ty::Idx(0, 8)], 1).push(Ty::I64) =~= seq![Ty::I64]); + assert(tc(l, c, Instr::LocalGet(0), seq![]) == Some(Flow::Falls(seq![Ty::I64]))); + assert(tc(l, c, bc, seq![Ty::I64]) == Some(Flow::Falls(seq![Ty::Idx(0, 8)]))); + assert(tc(l, c, ld, seq![Ty::Idx(0, 8)]) == Some(Flow::Falls(seq![Ty::I64]))); + assert(tc(l, c, then(bc, ld), seq![Ty::I64]) == Some(Flow::Falls(seq![Ty::I64]))); + assert(tc(l, c, load_at(), seq![]) == Some(Flow::Falls(seq![Ty::I64]))); +} + +/// The same code without the `bounds_check` does not type: the index is an +/// `i64`, not an `Idx`. +pub proof fn example_unchecked_load_rejected() + ensures + tc( + lay1(), + ctx_load(), + then(Instr::LocalGet(0), Instr::Load { region: 0, ty: Ty::I64 }), + seq![], + ) is None, +{ + reveal_with_fuel(tc, 12); + reveal_with_fuel(tc_blk, 3); + assert(tc( + lay1(), + ctx_load(), + then(Instr::LocalGet(0), Instr::Load { region: 0, ty: Ty::I64 }), + seq![], + ) is None); +} + +/// A check for 4 bytes does not license an 8-byte load. +pub proof fn example_short_check_rejected() + ensures + tc( + lay1(), + ctx_load(), + then( + Instr::LocalGet(0), + then( + Instr::BoundsCheck { region: 0, size: 4, code: 7 }, + Instr::Load { region: 0, ty: Ty::I64 }, + ), + ), + seq![], + ) is None, +{ + reveal_with_fuel(tc, 12); + reveal_with_fuel(tc_blk, 3); + assert(tc( + lay1(), + ctx_load(), + then( + Instr::LocalGet(0), + then( + Instr::BoundsCheck { region: 0, size: 4, code: 7 }, + Instr::Load { region: 0, ty: Ty::I64 }, + ), + ), + seq![], + ) is None); +} + +/// Dead code after `br` does not type (difference 1 of the typing). +pub proof fn example_dead_code_rejected() + ensures + tc(lay1(), ctx_load(), then(Instr::Br(0), Instr::Nop), seq![Ty::I64]) is None, +{ + reveal_with_fuel(tc, 12); + reveal_with_fuel(tc_blk, 3); + assert(tc(lay1(), ctx_load(), then(Instr::Br(0), Instr::Nop), seq![Ty::I64]) is None); +} + +/// For any state with an `i64` local and an empty stack, in any amount of +/// fuel, `load_at` is not stuck: it reads inside region 0, or exits. +pub proof fn example_load_at_never_stuck(st: St, fuel: nat) + requires + st.stack == Seq::::empty(), + st.locals.len() == 1, + st.locals[0] is I64, + ensures + !(eval(lay1(), load_at(), st, fuel) is Stuck), +{ + example_load_at_types(); + assert(vals_conform(lay1(), st.stack, seq![])); + assert(vals_conform(lay1(), st.locals, ctx_load().locals)); + crate::soundness::tc_sound(lay1(), ctx_load(), load_at(), seq![], st, fuel, Flow::Falls(seq![Ty::I64])); +} + +/// An index past the end of the region exits with the check's code. +pub proof fn example_load_at_exits() + ensures + ({ + let st = St { stack: seq![], locals: seq![Val::I64(60)], mem: Map::empty() }; + match eval(lay1(), load_at(), st, 10) { + Outcome::Exit(code, ops, _) => code == 7 && ops.len() == 0, + _ => false, + } + }), +{ + reveal_with_fuel(eval, 6); +} + +/// A countdown loop on local 0 (an `i32`): subtract 1, keep it, and branch +/// back to the start while it is non-zero. +pub open spec fn countdown() -> Instr { + Instr::Loop( + BlockType { params: seq![], results: seq![] }, + Box::new( + then( + Instr::LocalGet(0), + then( + Instr::Const(Val::I32(1)), + then( + Instr::Bin(BinOp::I32(IBin::Sub)), + then(Instr::LocalTee(0), Instr::BrIf(0)), + ), + ), + ), + ), + ) +} + +/// The context of `countdown`. +pub open spec fn ctx_count() -> Ctx { + Ctx { locals: seq![Ty::I32], labels: seq![seq![]] } +} + +/// `countdown` type-checks and leaves nothing. +pub proof fn example_countdown_types() + ensures + tc(lay1(), ctx_count(), countdown(), seq![]) == Some(Flow::Falls(seq![])), +{ + reveal_with_fuel(tc, 12); + reveal_with_fuel(tc_blk, 3); + assert(tc(lay1(), ctx_count(), countdown(), seq![]) == Some(Flow::Falls(seq![]))); +} + +/// For any state with an `i32` local and an empty stack, in any amount of +/// fuel, `countdown` is not stuck. (It does not run for ever when it has +/// enough fuel, but that is a fact about the semantics, not the typing.) +pub proof fn example_countdown_never_stuck(st: St, fuel: nat) + requires + st.stack == Seq::::empty(), + st.locals.len() == 1, + st.locals[0] is I32, + ensures + !(eval(lay1(), countdown(), st, fuel) is Stuck), +{ + example_countdown_types(); + assert(vals_conform(lay1(), st.stack, seq![])); + assert(vals_conform(lay1(), st.locals, ctx_count().locals)); + crate::soundness::tc_sound(lay1(), ctx_count(), countdown(), seq![], st, fuel, Flow::Falls(seq![])); +} + +/// Store the `i32` `0x11223344` at index 4 of region 0, then load it back. +pub open spec fn store_then_load() -> Instr { + then( + then( + Instr::Const(Val::I64(4)), + then( + Instr::BoundsCheck { region: 0, size: 4, code: 1 }, + then( + Instr::Const(Val::I32(0x1122_3344)), + Instr::Store { region: 0, ty: Ty::I32 }, + ), + ), + ), + then( + Instr::Const(Val::I64(4)), + then( + Instr::BoundsCheck { region: 0, size: 4, code: 1 }, + Instr::Load { region: 0, ty: Ty::I32 }, + ), + ), + ) +} + +/// It types, leaving an `i32`. +pub proof fn example_store_then_load_types() + ensures + tc( + lay1(), + Ctx { locals: seq![], labels: seq![] }, + store_then_load(), + seq![], + ) == Some(Flow::Falls(seq![Ty::I32])), +{ + let l = lay1(); + let c = Ctx { locals: seq![], labels: seq![] }; + let bc = Instr::BoundsCheck { region: 0, size: 4, code: 1 }; + let s0 = Seq::::empty(); + let s1 = seq![Ty::I64]; + let s2 = seq![Ty::Idx(0, 4)]; + let s3 = seq![Ty::Idx(0, 4), Ty::I32]; + let s4 = seq![Ty::I32]; + assert(s0.push(Ty::I64) =~= s1); + assert(below(s1, 1).push(Ty::Idx(0, 4)) =~= s2); + assert(s2.push(Ty::I32) =~= s3); + assert(below(s3, 2) =~= s0); + assert(below(s2, 1).push(Ty::I32) =~= s4); + let sto = Instr::Store { region: 0, ty: Ty::I32 }; + let ld = Instr::Load { region: 0, ty: Ty::I32 }; + let c4 = Instr::Const(Val::I32(0x1122_3344)); + let c64 = Instr::Const(Val::I64(4)); + assert(tc(l, c, c64, s0) == Some(Flow::Falls(s1))); + assert(tc(l, c, bc, s1) == Some(Flow::Falls(s2))); + assert(tc(l, c, c4, s2) == Some(Flow::Falls(s3))); + assert(tc(l, c, sto, s3) == Some(Flow::Falls(s0))); + assert(tc(l, c, ld, s2) == Some(Flow::Falls(s4))); + assert(tc(l, c, then(c4, sto), s2) == Some(Flow::Falls(s0))); + assert(tc(l, c, then(bc, then(c4, sto)), s1) == Some(Flow::Falls(s0))); + assert(tc(l, c, then(c64, then(bc, then(c4, sto))), s0) == Some(Flow::Falls(s0))); + assert(tc(l, c, then(bc, ld), s1) == Some(Flow::Falls(s4))); + assert(tc(l, c, then(c64, then(bc, ld)), s0) == Some(Flow::Falls(s4))); + assert(tc(l, c, store_then_load(), s0) == Some(Flow::Falls(s4))); +} + +/// Run from empty memory, `store_then_load` gives back the stored `i32`. +/// (Region 0 is at `0x1000` and the index is 4, so bytes `0x1004..0x1008` +/// are written, little-endian, and read.) +pub proof fn example_store_then_load_runs() + ensures + ({ + let st = St { stack: seq![], locals: seq![], mem: Map::empty() }; + match eval(lay1(), store_then_load(), st, 40) { + Outcome::Normal(s) => s.stack == seq![Val::I32(0x1122_3344)], + _ => false, + } + }), +{ + reveal_with_fuel(eval, 12); + reveal_with_fuel(read_le, 5); + reveal_with_fuel(write_le, 5); +} + +} // verus! diff --git a/crates/clazel-lir/src/lib.rs b/crates/clazel-lir/src/lib.rs index 88fccd014..57be7ea41 100644 --- a/crates/clazel-lir/src/lib.rs +++ b/crates/clazel-lir/src/lib.rs @@ -115,6 +115,7 @@ //! Tier: see `[package.metadata.clazel]` in `Cargo.toml` and //! `docs/VERIFICATION.md`. +pub mod examples; pub mod soundness; pub mod spec; pub mod syntax; From 6cf4e3352ca0059151512e3104051526402f3051 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Tue, 17 Nov 2026 20:21:25 +0000 Subject: [PATCH 5/6] Give the LIR spec its mutation tests (J.5) CI's proof job requires a mutations.json for every crate Verus checks. Three mutations of the typing (a load taking an unchecked index, Idx subtyping reversed, `br` falling through), each killed by an existing proven example. Co-Authored-By: Claude Opus 5.5 --- crates/clazel-lir/mutations.json | 43 ++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 crates/clazel-lir/mutations.json diff --git a/crates/clazel-lir/mutations.json b/crates/clazel-lir/mutations.json new file mode 100644 index 000000000..36ea115f6 --- /dev/null +++ b/crates/clazel-lir/mutations.json @@ -0,0 +1,43 @@ +{ + "mutations": [ + { + "id": "load-accepts-unchecked-index", + "file": "src/typing.rs", + "find": "stk[n - 1],\n Ty::Idx(region, ty_size(ty)),", + "replace": "stk[n - 1],\n Ty::I64,", + "expect": "killed", + "reason": "Lets a load take any i64, not an index a bounds_check has checked: a load with no check would type, so example_unchecked_load_rejected is false (and tc_sound no longer holds).", + "certificate": { + "file": "src/examples.rs", + "lemma": "example_unchecked_load_rejected()", + "witness": "tc(lay1(), ctx_load(), then(Instr::LocalGet(0), Instr::Load { region: 0, ty: Ty::I64 }), seq![]) is Some" + } + }, + { + "id": "idx-subtyping-reversed", + "file": "src/typing.rs", + "find": "(Ty::Idx(r, n), Ty::Idx(s, m)) => r == s && m <= n,", + "replace": "(Ty::Idx(r, n), Ty::Idx(s, m)) => r == s && n <= m,", + "expect": "killed", + "reason": "Reverses the size order of Idx subtyping, so a 4-byte bounds check would license an 8-byte load: example_short_check_rejected is false.", + "certificate": { + "file": "src/examples.rs", + "lemma": "example_short_check_rejected()", + "witness": "tc(lay1(), ctx_load(), then(Instr::LocalGet(0), then(Instr::BoundsCheck { region: 0, size: 4, code: 7 }, Instr::Load { region: 0, ty: Ty::I64 })), seq![]) is Some" + } + }, + { + "id": "branch-allows-dead-code", + "file": "src/typing.rs", + "find": "Some(Flow::Diverges)\n } else {\n None\n }\n },\n // Wasm core §3.3.8 `br_if l`", + "replace": "Some(Flow::Falls(stk))\n } else {\n None\n }\n },\n // Wasm core §3.3.8 `br_if l`", + "expect": "killed", + "reason": "Types `br l` as falling through with the stack unchanged, so code after a branch is accepted (difference 1 of the typing from Wasm): example_dead_code_rejected is false.", + "certificate": { + "file": "src/examples.rs", + "lemma": "example_dead_code_rejected()", + "witness": "tc(lay1(), ctx_load(), then(Instr::Br(0), Instr::Nop), seq![Ty::I64]) is Some" + } + } + ] +} From d337276dc70312d585f2cec06988b213a172deff Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Fri, 20 Nov 2026 19:40:19 +0000 Subject: [PATCH 6/6] clazel-lir: state stack_sub by recursion, so compute_only can type a br The branch-allows-dead-code kill certificate "did not build" in CI: typing `br` goes through top_sub and stack_sub, whose pointwise `forall` compute_only cannot evaluate. stack_sub is now defined by recursion on the last element (same meaning), and soundness::lemma_stack_sub_pointwise proves it equals the `forall` form, which the two lemmas that used that form now call. This is the pattern clazel-pkcs1 uses for `two_to` against vstd's pow2. Locally (Verus 0.2026.10.04): 36 verified, 0 errors; 3 mutations, 3 killed by a theorem with certificates. Co-Authored-By: Claude Opus 5.5 --- crates/clazel-lir/src/soundness.rs | 30 ++++++++++++++++++++++++++++++ crates/clazel-lir/src/typing.rs | 14 ++++++++++++-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/clazel-lir/src/soundness.rs b/crates/clazel-lir/src/soundness.rs index c8412a4c5..19c74fece 100644 --- a/crates/clazel-lir/src/soundness.rs +++ b/crates/clazel-lir/src/soundness.rs @@ -61,6 +61,34 @@ proof fn lemma_sub_refl(t: Ty) { } +/// `stack_sub` (stated by recursion so that it can be evaluated) is `ty_sub` +/// pointwise on sequences of equal length. +pub proof fn lemma_stack_sub_pointwise(a: Seq, b: Seq) + ensures + stack_sub(a, b) <==> (a.len() == b.len() && forall|j: int| + 0 <= j < a.len() ==> ty_sub(#[trigger] a[j], b[j])), + decreases a.len(), +{ + if a.len() == b.len() && a.len() > 0 { + let (a0, b0) = (a.drop_last(), b.drop_last()); + lemma_stack_sub_pointwise(a0, b0); + assert forall|j: int| 0 <= j < a0.len() implies a0[j] == a[j] && b0[j] == b[j] by {} + if stack_sub(a, b) { + assert forall|j: int| 0 <= j < a.len() implies ty_sub(#[trigger] a[j], b[j]) by { + if j < a0.len() { + assert(ty_sub(a0[j], b0[j])); + } + } + } + if forall|j: int| 0 <= j < a.len() ==> ty_sub(#[trigger] a[j], b[j]) { + assert(ty_sub(a[a.len() - 1], b[b.len() - 1])); + assert forall|j: int| 0 <= j < a0.len() implies ty_sub(#[trigger] a0[j], b0[j]) by { + assert(ty_sub(a[j], b[j])); + } + } + } +} + proof fn lemma_stack_sub_refl(s: Seq) ensures stack_sub(s, s), @@ -68,6 +96,7 @@ proof fn lemma_stack_sub_refl(s: Seq) assert forall|j: int| 0 <= j < s.len() implies ty_sub(#[trigger] s[j], s[j]) by { lemma_sub_refl(s[j]); } + lemma_stack_sub_pointwise(s, s); } proof fn lemma_conf_sub(lay: Layout, v: Val, t: Ty, u: Ty) @@ -86,6 +115,7 @@ proof fn lemma_vals_sub(lay: Layout, vs: Seq, ts: Seq, us: Seq) ensures vals_conform(lay, vs, us), { + lemma_stack_sub_pointwise(ts, us); assert forall|j: int| 0 <= j < vs.len() implies conforms(lay, #[trigger] vs[j], us[j]) by { lemma_conf_sub(lay, vs[j], ts[j], us[j]); } diff --git a/crates/clazel-lir/src/typing.rs b/crates/clazel-lir/src/typing.rs index a5a594fab..3b056a65d 100644 --- a/crates/clazel-lir/src/typing.rs +++ b/crates/clazel-lir/src/typing.rs @@ -49,8 +49,18 @@ pub open spec fn ty_sub(a: Ty, b: Ty) -> bool { } /// `sub` pointwise, on sequences of equal length. -pub open spec fn stack_sub(a: Seq, b: Seq) -> bool { - a.len() == b.len() && forall|j: int| 0 <= j < a.len() ==> ty_sub(#[trigger] a[j], b[j]) +/// +/// Stated by recursion on the last element rather than with `forall`, so that +/// `compute_only` can evaluate it (the kill certificates in `mutations.json` +/// type a `br` through it); `soundness::lemma_stack_sub_pointwise` proves it +/// is the pointwise `forall` form. +pub open spec fn stack_sub(a: Seq, b: Seq) -> bool + decreases a.len(), +{ + a.len() == b.len() && (a.len() == 0 || (ty_sub(a.last(), b.last()) && stack_sub( + a.drop_last(), + b.drop_last(), + ))) } /// The top `tys.len()` types of `stk` are subtypes of `tys`.