From 9893a51d2712f82a2ee57316a66bc26500eb3fdd Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 9 Aug 2026 16:11:57 +0200 Subject: feat: add reusable host imports and simplify function calls - make host definitions reusable across stores with gc-aware import linking - reorganize function calls, resumable execution, and typed value handling - expand typed tuples to arity 20 and update parser and store APIs Signed-off-by: Henry --- examples/rust/src/tinywasm.rs | 4 ++-- examples/rust/src/tinywasm_no_std.rs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'examples/rust/src') diff --git a/examples/rust/src/tinywasm.rs b/examples/rust/src/tinywasm.rs index 70de73e..b0a2e47 100644 --- a/examples/rust/src/tinywasm.rs +++ b/examples/rust/src/tinywasm.rs @@ -15,7 +15,7 @@ fn run() -> tinywasm::Result<()> { let module = tinywasm::parse_stream(&include_bytes!("./print.wasm")[..])?; let mut store = tinywasm::Store::default(); - let printi32 = HostFunction::from(&mut store, |_: FuncContext<'_>, v: i32| { + let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { unsafe { printi32(v) } Ok(()) }); @@ -23,7 +23,7 @@ fn run() -> tinywasm::Result<()> { let mut imports = tinywasm::Imports::new(); imports.define("env", "printi32", printi32); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?; add_and_print.call(&mut store, (1, 2))?; Ok(()) diff --git a/examples/rust/src/tinywasm_no_std.rs b/examples/rust/src/tinywasm_no_std.rs index c1dd910..cbf10f4 100644 --- a/examples/rust/src/tinywasm_no_std.rs +++ b/examples/rust/src/tinywasm_no_std.rs @@ -28,17 +28,17 @@ fn run() -> tinywasm::Result<()> { let mut store = tinywasm::Store::default(); let mut imports = tinywasm::Imports::new(); - let res = tinywasm::parser::Parser::new().parse_module_bytes(include_bytes!("./print.wasm"))?; + let res = tinywasm::parser::Parser::default().parse_module_bytes(include_bytes!("./print.wasm"))?; let twasm = res.serialize_twasm()?; let module = tinywasm::parse_bytes(&twasm)?; - let printi32 = HostFunction::from(&mut store, |_: FuncContext<'_>, v: i32| { + let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { unsafe { printi32(v) } Ok(()) }); imports.define("env", "printi32", printi32); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?; add_and_print.call(&mut store, (1, 2))?; Ok(()) -- cgit v1.3.1 From 64cf33ced2db2135dd355a1c6e049bf51c93d956 Mon Sep 17 00:00:00 2001 From: Henry Date: Tue, 11 Aug 2026 17:25:32 +0200 Subject: chore: more superinstructions, cleanup Signed-off-by: Henry --- crates/parser/src/conversion.rs | 3 +- crates/parser/src/optimize.rs | 108 +- crates/tinywasm/src/func/host.rs | 5 +- crates/tinywasm/src/interpreter/executor.rs | 1304 ++++++++++---------- crates/tinywasm/src/store/state.rs | 21 +- crates/tinywasm/src/store/types.rs | 12 +- crates/tinywasm/tests/host_func_signature_check.rs | 2 +- crates/types/src/instructions.rs | 14 +- crates/types/src/reference.rs | 13 +- crates/types/src/value.rs | 2 +- examples/rust/Cargo.toml | 7 +- examples/rust/build.sh | 7 +- examples/rust/src/print.twasm | Bin 0 -> 154 bytes examples/rust/src/tinywasm_no_std.rs | 6 +- examples/rust/src/tinywasm_precompiled.rs | 30 + examples/wasm-rust.rs | 25 + 16 files changed, 827 insertions(+), 732 deletions(-) create mode 100644 examples/rust/src/print.twasm create mode 100644 examples/rust/src/tinywasm_precompiled.rs (limited to 'examples/rust/src') diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 694c639..480a8d0 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -440,8 +440,7 @@ fn convert_heap_type_with_group( ))); } }; - RefType::new_concrete(nullable, index) - .ok_or_else(|| crate::ParseError::Other(format!("heap type index is too large: {index}"))) + Ok(RefType::new_concrete(nullable, index)) } wasmparser::HeapType::Abstract { shared: true, .. } | wasmparser::HeapType::Exact(_) => { Err(crate::ParseError::UnsupportedOperator(format!("Unsupported heap type: {heap:?}"))) diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 2b5e331..7081187 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -92,7 +92,9 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); @@ -103,6 +105,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]); @@ -113,7 +116,9 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const64(c)] => AddConst64(c)); @@ -124,6 +129,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 8), Const64(8)] => [LocalGet64(local), I64Extend8S]); @@ -143,33 +149,42 @@ fn rewrite( let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); } instr @ (F32Sub | F32Div | F32Copysign) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); } instr @ (F64Add | F64Mul | F64Min | F64Max) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); } instr @ (F64Sub | F64Div | F64Copysign) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); } instr @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul) => { let Some(op) = bin_op_128(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(op, a, b)); rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(op, local, c)); + rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(op, global, c)); rewrite!(instrs, i, [Const128(c), LocalGet128(local)] => BinOpLocalConst128(op, local, c)); + rewrite!(instrs, i, [Const128(c), GlobalGet128(global)] => BinOpGlobalConst128(op, global, c)); } V128AndNot => { rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(BinOp128::AndNot, a, b)); rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(BinOp128::AndNot, local, c)); + rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(BinOp128::AndNot, global, c)); } I32Store(memarg) | F32Store(memarg) => { rewrite!(instrs, i, @@ -277,6 +292,9 @@ fn rewrite( MemoryFill(mem) => { rewrite!(instrs, i, [Const32(val), Const32(size)] => MemoryFillImm(mem, val as u8, size)) } + GlobalGet32(dst) => rewrite!(instrs, i, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), + GlobalGet64(dst) => rewrite!(instrs, i, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), + GlobalGet128(dst) => rewrite!(instrs, i, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), LocalGet32(dst) => rewrite!(instrs, i, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), LocalGet64(dst) => rewrite!(instrs, i, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), LocalGet128(dst) => rewrite!(instrs, i, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), @@ -542,7 +560,6 @@ fn rewrite( replace!(instrs, i, 1 => JumpIfNonZero32(target)); continue; }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local }); rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { replace!(instrs, i, 2 => JumpIfLocalNonZero64 { target_ip: target, local }); continue; @@ -552,8 +569,30 @@ fn rewrite( continue; }); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst)] if (local == dst) => - IncLocalJump32 { target_ip: target, local, delta, on_zero: true } + [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => + match inc_delta(op, imm) { + Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: true }, + None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: true }, + } + ); + rewrite!(instrs, i, + [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: true } + ); + rewrite!(instrs, i, + [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: true } + ); + rewrite!(instrs, i, + [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: true } + ); + rewrite!(instrs, i, + [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => + match inc_delta(op, imm) { + Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: true }, + None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: true }, + } ); rewrite!(instrs, i, [CmpLocalLocal32(op, left, right)] => @@ -564,9 +603,12 @@ fn rewrite( JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } ); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst), LocalGet32(right), cmp] if - (local == dst && let Some(op) = cmp_op(cmp)) => - IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(op) } + [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if + (local == dst && let Some(cmp) = cmp_op(cmp)) => + match inc_delta(binop, imm) { + Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(cmp) }, + None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp: inverse_cmp_op(cmp) }, + } ); rewrite!(instrs, i, [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => @@ -611,6 +653,8 @@ fn rewrite( (0, CmpOp::Ne) => JumpIfNonZero64(target), (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, }); + rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local }); + rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local }); canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); } JumpIfNonZero32(ip) => { @@ -623,7 +667,6 @@ fn rewrite( replace!(instrs, i, 1 => JumpIfZero32(target)); continue; }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local }); rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { replace!(instrs, i, 2 => JumpIfLocalZero64 { target_ip: target, local }); continue; @@ -633,8 +676,30 @@ fn rewrite( continue; }); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst)] if (local == dst) => - IncLocalJump32 { target_ip: target, local, delta, on_zero: false } + [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => + match inc_delta(op, imm) { + Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: false }, + None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: false }, + } + ); + rewrite!(instrs, i, + [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: false } + ); + rewrite!(instrs, i, + [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: false } + ); + rewrite!(instrs, i, + [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: false } + ); + rewrite!(instrs, i, + [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => + match inc_delta(op, imm) { + Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: false }, + None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: false }, + } ); rewrite!(instrs, i, [CmpLocalLocal32(op, left, right)] => @@ -645,9 +710,12 @@ fn rewrite( JumpCmpLocalLocal64 { target_ip: target, left, right, op } ); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst), LocalGet32(right), cmp] if - (local == dst && let Some(op) = cmp_op(cmp)) => - IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op } + [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if + (local == dst && let Some(cmp) = cmp_op(cmp)) => + match inc_delta(binop, imm) { + Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: cmp }, + None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp }, + } ); rewrite!(instrs, i, [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => @@ -692,6 +760,8 @@ fn rewrite( (0, CmpOp::Ne) => JumpIfNonZero64(target), (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, }); + rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local }); + rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local }); canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); } JumpIfZero64(ip) => { @@ -774,6 +844,14 @@ fn cmp_op(instr: Instruction) -> Option { }) } +fn inc_delta(op: BinOp, imm: i32) -> Option { + match op { + BinOp::IAdd => Some(imm), + BinOp::ISub => Some(imm.wrapping_neg()), + _ => None, + } +} + fn int_bin_op(instr: Instruction) -> Option { Some(match instr { Instruction::I32Add | Instruction::I64Add => BinOp::IAdd, @@ -921,7 +999,13 @@ fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> { | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } | Instruction::JumpCmpStackLocal32 { target_ip: ip, .. } | Instruction::JumpCmpStackLocal64 { target_ip: ip, .. } + | Instruction::BinOpLocalConstJump32 { target_ip: ip, .. } + | Instruction::BinOpLocalConstJumpCmpLocal32 { target_ip: ip, .. } + | Instruction::BinOpStackConstTeeLocalJump32 { target_ip: ip, .. } + | Instruction::BinOpGlobalConstJump32 { target_ip: ip, .. } | Instruction::IncLocalJump32 { target_ip: ip, .. } + | Instruction::IncStackTeeLocalJump32 { target_ip: ip, .. } + | Instruction::IncGlobalJump32 { target_ip: ip, .. } | Instruction::IncLocalJumpCmpLocal32 { target_ip: ip, .. } | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } | Instruction::JumpIfLocalNonZero32 { target_ip: ip, .. } diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 5335444..27c5573 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -31,10 +31,7 @@ impl HostFunction { let canonical = *type_addrs .get(module_addr as usize) .ok_or_else(|| crate::Error::other("host function signature contains an invalid concrete type"))?; - Ok(WasmType::Ref( - tinywasm_types::RefType::new_concrete(ref_ty.is_nullable(), canonical) - .expect("canonical type addresses fit in references"), - )) + Ok(WasmType::Ref(tinywasm_types::RefType::new_concrete(ref_ty.is_nullable(), canonical))) }; let params = self.0.ty.params().iter().copied().map(resolve).collect::>>()?; let results = self.0.ty.results().iter().copied().map(resolve).collect::>>()?; diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 2d2a745..051b12f 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -66,14 +66,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec(&mut self, instr_ptr: usize) -> Result> { - macro_rules! stack_op { - (unary $ty:ty, |$v:ident| $expr:expr) => { - stack_op!(unary $ty => $ty, |$v| $expr) - }; - (binary $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => { - stack_op!(binary $ty => $ty, |$lhs, $rhs| $expr) - }; - (binary try $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + macro_rules! exec_op { + (branch $target:expr, $condition:expr) => {{ + if $condition { + self.cf.instr_ptr = *$target as usize; + return Ok(None); + } + }}; + (binary_fallible $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ let $rhs = <$ty>::stack_pop(&mut self.store.value_stack); let $lhs = <$ty>::stack_pop(&mut self.store.value_stack); <$ty>::stack_push(&mut self.store.value_stack, $expr?)?; @@ -87,28 +87,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let $lhs = <$from>::stack_pop(&mut self.store.value_stack); <$to>::stack_push(&mut self.store.value_stack, $expr)?; }}; - (binary_into2 $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + (binary_two_results $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ let $rhs = <$from>::stack_pop(&mut self.store.value_stack); let $lhs = <$from>::stack_pop(&mut self.store.value_stack); let out = $expr; <$to>::stack_push(&mut self.store.value_stack, out.0)?; <$to>::stack_push(&mut self.store.value_stack, out.1)?; }}; - (binary $lhs_ty:ty, $rhs_ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => { - stack_op!(binary $lhs_ty, $rhs_ty => $rhs_ty, |$lhs, $rhs| $expr) - }; - (binary $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + (binary_mixed $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ let $rhs = <$rhs_ty>::stack_pop(&mut self.store.value_stack); let $lhs = <$lhs_ty>::stack_pop(&mut self.store.value_stack); <$res>::stack_push(&mut self.store.value_stack, $expr)?; }}; - (ternary $ty:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{ - let $c = <$ty>::stack_pop(&mut self.store.value_stack); - let $b = <$ty>::stack_pop(&mut self.store.value_stack); - let $a = <$ty>::stack_pop(&mut self.store.value_stack); - <$ty>::stack_push(&mut self.store.value_stack, $expr)?; + (ternary $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{ + let $c = <$from>::stack_pop(&mut self.store.value_stack); + let $b = <$from>::stack_pop(&mut self.store.value_stack); + let $a = <$from>::stack_pop(&mut self.store.value_stack); + <$to>::stack_push(&mut self.store.value_stack, $expr)?; }}; - (quaternary_into2 $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident, $d:ident| $expr:expr) => {{ + (quaternary_two_results $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident, $d:ident| $expr:expr) => {{ let $d = <$from>::stack_pop(&mut self.store.value_stack); let $c = <$from>::stack_pop(&mut self.store.value_stack); let $b = <$from>::stack_pop(&mut self.store.value_stack); @@ -135,93 +132,64 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let value = <$ty>::stack_pop(&mut self.store.value_stack); <$ty>::global_set(&mut self.store.state.globals, addr, value); }}; - } - - macro_rules! exec_binop { - (32, $op:expr, $lhs:expr, $rhs:expr) => { - exec_binop!(@scalar i32, u32, f32, $op, $lhs, $rhs) - }; - (64, $op:expr, $lhs:expr, $rhs:expr) => { - exec_binop!(@scalar i64, u64, f64, $op, $lhs, $rhs) - }; - (@scalar $signed:ty, $unsigned:ty, $float:ty, $op:expr, $lhs:expr, $rhs:expr) => {{ - match $op { - BinOp::IAdd => $lhs.wrapping_add($rhs), - BinOp::ISub => $lhs.wrapping_sub($rhs), - BinOp::IMul => $lhs.wrapping_mul($rhs), - BinOp::IAnd => $lhs & $rhs, - BinOp::IOr => $lhs | $rhs, - BinOp::IXor => $lhs ^ $rhs, - BinOp::IShl => (($lhs as $signed).wrapping_shl($rhs as u32)) as $unsigned, - BinOp::IShrS => (($lhs as $signed).wrapping_shr($rhs as u32)) as $unsigned, - BinOp::IShrU => $lhs.wrapping_shr($rhs as u32), - BinOp::IRotl => (($lhs as $signed).rotate_left($rhs as u32)) as $unsigned, - BinOp::IRotr => (($lhs as $signed).rotate_right($rhs as u32)) as $unsigned, - BinOp::FAdd => (<$float>::from_bits($lhs) + <$float>::from_bits($rhs)).to_bits(), - BinOp::FSub => (<$float>::from_bits($lhs) - <$float>::from_bits($rhs)).to_bits(), - BinOp::FMul => (<$float>::from_bits($lhs) * <$float>::from_bits($rhs)).to_bits(), - BinOp::FDiv => (<$float>::from_bits($lhs) / <$float>::from_bits($rhs)).to_bits(), - BinOp::FMin => <$float>::from_bits($lhs).tw_minimum(<$float>::from_bits($rhs)).to_bits(), - BinOp::FMax => <$float>::from_bits($lhs).tw_maximum(<$float>::from_bits($rhs)).to_bits(), - BinOp::FCopysign => <$float>::from_bits($lhs).copysign(<$float>::from_bits($rhs)).to_bits(), - } - }}; - (128, $op:expr, $lhs:expr, $rhs:expr) => {{ - match $op { - BinOp128::And => $lhs.v128_and($rhs), - BinOp128::AndNot => $lhs.v128_andnot($rhs), - BinOp128::Or => $lhs.v128_or($rhs), - BinOp128::Xor => $lhs.v128_xor($rhs), - BinOp128::I64x2Add => $lhs.i64x2_add($rhs), - BinOp128::I64x2Mul => $lhs.i64x2_mul($rhs), - } + (global_tee $ty:ty, $global_index:expr) => {{ + let addr = self.module.resolve_global_addr(*$global_index); + let value = <$ty>::stack_peek(&self.store.value_stack); + <$ty>::global_set(&mut self.store.state.globals, addr, value); }}; - } - - macro_rules! binop { - (local_local $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident) => {{ + (binop_local_local $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - self.store.value_stack.push(exec_binop!($width, *$op, lhs, rhs))?; + <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?; }}; - (local_local_set $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ + (binop_local_local_set $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - let value = exec_binop!($width, *$op, lhs, rhs); + let value = $exec(*$op, lhs, rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); }}; - (local_local_tee $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ + (binop_local_local_tee $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - let value = exec_binop!($width, *$op, lhs, rhs); + let value = $exec(*$op, lhs, rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - self.store.value_stack.push(value)?; + <$vt>::stack_push(&mut self.store.value_stack, value)?; }}; - (local_local_cmp $vt:ty, $cmp:ident, $op:ident, $a:ident, $b:ident) => {{ + (cmp_local_local $vt:ty, $cmp:ident, $op:ident, $a:ident, $b:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); self.store.value_stack.push(i32::from($cmp(lhs, rhs, *$op)))?; }}; - (local_const $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr) => {{ + (binop_local_const $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - self.store.value_stack.push(exec_binop!($width, *$op, lhs, $rhs))?; + <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, $rhs))?; }}; - (local_const_set $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ + (binop_local_const_set $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let value = exec_binop!($width, *$op, lhs, $rhs); + let value = $exec(*$op, lhs, $rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); }}; - (local_const_tee $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ + (binop_local_const_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let value = exec_binop!($width, *$op, lhs, $rhs); + let value = $exec(*$op, lhs, $rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - self.store.value_stack.push(value)?; + <$vt>::stack_push(&mut self.store.value_stack, value)?; }}; - (stack_global $vt:ty, $width:tt, $op:ident, $global:ident) => {{ + (binop_global_const $vt:ty, $exec:ident, $op:ident, $global:ident, $rhs:expr) => {{ + let lhs = <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); + self.store.value_stack.push($exec(*$op, lhs, $rhs))?; + }}; + (binop_stack_global $vt:ty, $exec:ident, $op:ident, $global:ident) => {{ let global_val = <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); let stack_val = <$vt>::stack_pop(&mut self.store.value_stack); - self.store.value_stack.push(exec_binop!($width, *$op, stack_val, global_val))?; + self.store.value_stack.push($exec(*$op, stack_val, global_val))?; + }}; + (binop_acc_local $ty:ty, $acc:ident, $mul:expr, $add:expr) => {{ + let rhs = <$ty>::stack_pop(&mut self.store.value_stack); + let lhs = <$ty>::stack_pop(&mut self.store.value_stack); + let value = ($mul)(lhs, rhs); + <$ty>::local_update(&mut self.store.value_stack, &self.cf, *$acc, |acc| ($add)(value, acc)); }}; } @@ -247,27 +215,115 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } ThrowRef => { self.exec_throw_ref()?; return Ok(None); } Jump(ip) => { self.cf.instr_ptr = *ip as usize; return Ok(None); } - JumpIfZero32(ip) => if self.exec_jump_zero_32(*ip) { return Ok(None) }, - JumpIfNonZero32(ip) => if self.exec_jump_non_zero_32(*ip) { return Ok(None) }, - JumpIfZero64(ip) => if self.exec_jump_zero_64(*ip) { return Ok(None) }, - JumpIfNonZero64(ip) => if self.exec_jump_non_zero_64(*ip) { return Ok(None) }, - JumpIfRefNull(ip) => if self.exec_jump_ref_null(*ip) { return Ok(None) }, - JumpIfRefNonNull(ip) => if self.exec_jump_ref_non_null(*ip) { return Ok(None) }, + JumpIfZero32(ip) => exec_op!(branch ip, i32::stack_pop(&mut self.store.value_stack) == 0), + JumpIfNonZero32(ip) => exec_op!(branch ip, i32::stack_pop(&mut self.store.value_stack) != 0), + JumpIfZero64(ip) => exec_op!(branch ip, i64::stack_pop(&mut self.store.value_stack) == 0), + JumpIfNonZero64(ip) => exec_op!(branch ip, i64::stack_pop(&mut self.store.value_stack) != 0), + JumpIfRefNull(ip) => { + let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); + if is_null { + ValueRef::stack_pop(&mut self.store.value_stack); + } + exec_op!(branch ip, is_null); + }, + JumpIfRefNonNull(ip) => { + let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null(); + if !is_non_null { + ValueRef::stack_pop(&mut self.store.value_stack); + } + exec_op!(branch ip, is_non_null); + }, BrOnCast(ip, ty, on_fail) => if self.exec_ref_matches(*ty) == *on_fail { self.cf.instr_ptr = *ip as usize; return Ok(None); }, - JumpIfLocalZero32 { target_ip, local } => if self.exec_jump_local_zero_32(*target_ip, *local) { return Ok(None) }, - JumpIfLocalNonZero32 { target_ip, local } => if self.exec_jump_local_non_zero_32(*target_ip, *local) { return Ok(None) }, - JumpIfLocalZero64 { target_ip, local } => if self.exec_jump_local_zero_64(*target_ip, *local) { return Ok(None) }, - JumpIfLocalNonZero64 { target_ip, local } => if self.exec_jump_local_non_zero_64(*target_ip, *local) { return Ok(None) }, - JumpCmpStackConst32 { target_ip, imm, op } => if self.exec_jump_cmp_stack_const_32(*target_ip, *imm, *op) { return Ok(None) }, - JumpCmpStackConst64 { target_ip, imm, op } => if self.exec_jump_cmp_stack_const_64(*target_ip, *imm, *op) { return Ok(None) }, - JumpCmpStackLocal32 { target_ip, local, op } => if self.exec_jump_cmp_stack_local_32(*target_ip, *local, *op) { return Ok(None) }, - JumpCmpStackLocal64 { target_ip, local, op } => if self.exec_jump_cmp_stack_local_64(*target_ip, *local, *op) { return Ok(None) }, - IncLocalJump32 { target_ip, local, delta, on_zero } => if self.exec_inc_local_jump_32(*target_ip, *local, *delta, *on_zero) { return Ok(None) }, - IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => if self.exec_inc_local_jump_cmp_local_32(*target_ip, *local, *delta, *right, *op) { return Ok(None) }, - JumpCmpLocalConst32 { target_ip, local, imm, op } => if self.exec_jump_cmp_local_const_32(*target_ip, *local, *imm, *op) { return Ok(None) }, - JumpCmpLocalConst64 { target_ip, local, imm, op } => if self.exec_jump_cmp_local_const_64(*target_ip, *local, *imm, *op) { return Ok(None) }, - JumpCmpLocalLocal32 { target_ip, left, right, op } => if self.exec_jump_cmp_local_local_32(*target_ip, *left, *right, *op) { return Ok(None) }, - JumpCmpLocalLocal64 { target_ip, left, right, op } => if self.exec_jump_cmp_local_local_64(*target_ip, *left, *right, *op) { return Ok(None) }, + JumpIfLocalZero32 { target_ip, local } => exec_op!(branch target_ip, Value32::local_get(&self.store.value_stack, &self.cf, *local) == 0), + JumpIfLocalNonZero32 { target_ip, local } => exec_op!(branch target_ip, Value32::local_get(&self.store.value_stack, &self.cf, *local) != 0), + JumpIfLocalZero64 { target_ip, local } => exec_op!(branch target_ip, Value64::local_get(&self.store.value_stack, &self.cf, *local) == 0), + JumpIfLocalNonZero64 { target_ip, local } => exec_op!(branch target_ip, Value64::local_get(&self.store.value_stack, &self.cf, *local) != 0), + JumpCmpStackConst32 { target_ip, imm, op } => { + let lhs = i32::stack_pop(&mut self.store.value_stack); + exec_op!(branch target_ip, cmp_i32(lhs, *imm, *op)); + }, + JumpCmpStackConst64 { target_ip, imm, op } => { + let lhs = i64::stack_pop(&mut self.store.value_stack); + exec_op!(branch target_ip, cmp_i64(lhs, *imm, *op)); + }, + JumpCmpStackLocal32 { target_ip, local, op } => { + let lhs = i32::stack_pop(&mut self.store.value_stack); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); + }, + JumpCmpStackLocal64 { target_ip, local, op } => { + let lhs = i64::stack_pop(&mut self.store.value_stack); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i64(lhs, rhs, *op)); + }, + BinOpLocalConstJump32 { target_ip, local, imm, op, on_zero } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + BinOpLocalConstJumpCmpLocal32 { target_ip, local, imm, binop, right, cmp } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + let lhs = exec_binop_32(*binop, lhs as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, *local, lhs); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *cmp)); + }, + BinOpStackConstTeeLocalJump32 { target_ip, local, imm, op, on_zero } => { + let lhs = i32::stack_pop(&mut self.store.value_stack); + let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + i32::stack_push(&mut self.store.value_stack, value)?; + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + BinOpGlobalConstJump32 { target_ip, global, imm, op, on_zero } => { + let global = self.module.resolve_global_addr(*global); + let lhs = i32::global_get(&self.store.state.globals, global); + let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + i32::global_set(&mut self.store.state.globals, global, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncLocalJump32 { target_ip, local, delta, on_zero } => { + let value = i32::local_get(&self.store.value_stack, &self.cf, *local).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncStackTeeLocalJump32 { target_ip, local, delta, on_zero } => { + let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + i32::stack_push(&mut self.store.value_stack, value)?; + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncGlobalJump32 { target_ip, global, delta, on_zero } => { + let global = self.module.resolve_global_addr(*global); + let value = i32::global_get(&self.store.state.globals, global).wrapping_add(*delta); + i32::global_set(&mut self.store.state.globals, global, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, &self.cf, *local, lhs); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); + }, + JumpCmpLocalConst32 { target_ip, local, imm, op } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i32(lhs, *imm, *op)); + }, + JumpCmpLocalConst64 { target_ip, local, imm, op } => { + let lhs = i64::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i64(lhs, i64::from(*imm), *op)); + }, + JumpCmpLocalLocal32 { target_ip, left, right, op } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *left); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); + }, + JumpCmpLocalLocal64 { target_ip, left, right, op } => { + let lhs = i64::local_get(&self.store.value_stack, &self.cf, *left); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i64(lhs, rhs, *op)); + }, DropKeep(drop_keep) => self.exec_drop_keep(*drop_keep), BranchTable(default_ip, start, len) => { self.exec_branch_table(*default_ip, *start, *len); return Ok(None); } Return => { if self.exec_return() { return Ok(Some(())); } return Ok(None); } @@ -278,44 +334,47 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LocalGet32(local_index) => self.store.value_stack.push(Value32::local_get(&self.store.value_stack, &self.cf, *local_index))?, LocalGet64(local_index) => self.store.value_stack.push(Value64::local_get(&self.store.value_stack, &self.cf, *local_index))?, LocalGet128(local_index) => self.store.value_stack.push(Value128::local_get(&self.store.value_stack, &self.cf, *local_index))?, - LocalSet32(local_index) => stack_op!(local_set_pop Value32, local_index), - LocalSet64(local_index) => stack_op!(local_set_pop Value64, local_index), - LocalSet128(local_index) => stack_op!(local_set_pop Value128, local_index), + LocalSet32(local_index) => exec_op!(local_set_pop Value32, local_index), + LocalSet64(local_index) => exec_op!(local_set_pop Value64, local_index), + LocalSet128(local_index) => exec_op!(local_set_pop Value128, local_index), LocalCopy32(from, to) => Value32::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), - AddConst32(c) => stack_op!(unary i32, |v| v.wrapping_add(*c)), - AddConst64(c) => stack_op!(unary i64, |v| v.wrapping_add(*c)), + AddConst32(c) => exec_op!(unary i32 => i32, |v| v.wrapping_add(*c)), + AddConst64(c) => exec_op!(unary i64 => i64, |v| v.wrapping_add(*c)), IncLocal32(local_index, delta) => i32::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta)), IncLocal64(local_index, delta) => i64::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta )), - I32Add3 => stack_op!(ternary i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), - I64Add3 => stack_op!(ternary i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), - MulAccLocal32(acc) => self.exec_binop_acc_local::(*acc, |a, b| a.wrapping_mul(b), |a, b| a.wrapping_add(b)), - MulAccLocal64(acc) => self.exec_binop_acc_local::(*acc, |a, b| a.wrapping_mul(b), |a, b| a.wrapping_add(b)), - FMulAccLocal32(acc) => self.exec_binop_acc_local::(*acc, |a, b| a * b, |a, b| a + b), - FMulAccLocal64(acc) => self.exec_binop_acc_local::(*acc, |a, b| a * b, |a, b| a + b), - BinOpLocalLocal32(op, a, b) => binop!(local_local Value32, 32, op, a, b), - BinOpLocalLocal64(op, a, b) => binop!(local_local Value64, 64, op, a, b), - BinOpLocalLocal128(op, a, b) => binop!(local_local Value128, 128, op, a, b), - CmpLocalLocal32(op, a, b) => binop!(local_local_cmp i32, cmp_i32, op, a, b), - CmpLocalLocal64(op, a, b) => binop!(local_local_cmp i64, cmp_i64, op, a, b), - BinOpLocalLocalSet32(op, a, b, dst) => binop!(local_local_set Value32, 32, op, a, b, dst), - BinOpLocalLocalSet64(op, a, b, dst) => binop!(local_local_set Value64, 64, op, a, b, dst), - BinOpLocalLocalSet128(op, a, b, dst) => binop!(local_local_set Value128, 128, op, a, b, dst), - BinOpLocalLocalTee32(op, a, b, dst) => binop!(local_local_tee Value32, 32, op, a, b, dst), - BinOpLocalLocalTee64(op, a, b, dst) => binop!(local_local_tee Value64, 64, op, a, b, dst), - BinOpLocalLocalTee128(op, a, b, dst) => binop!(local_local_tee Value128, 128, op, a, b, dst), - BinOpLocalConst32(op, local_index, c) => binop!(local_const Value32, 32, op, local_index, *c as u32), - BinOpLocalConst64(op, local_index, c) => binop!(local_const Value64, 64, op, local_index, *c as u64), - BinOpLocalConst128(op, local_index, c) => binop!(local_const Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c))), - BinOpLocalConstSet32(op, local_index, c, dst) => binop!(local_const_set Value32, 32, op, local_index, *c as u32, dst), - BinOpLocalConstSet64(op, local_index, c, dst) => binop!(local_const_set Value64, 64, op, local_index, *c as u64, dst), - BinOpLocalConstSet128(op, local_index, c, dst) => binop!(local_const_set Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), - BinOpLocalConstTee32(op, local_index, c, dst) => binop!(local_const_tee Value32, 32, op, local_index, *c as u32, dst), - BinOpLocalConstTee64(op, local_index, c, dst) => binop!(local_const_tee Value64, 64, op, local_index, *c as u64, dst), - BinOpLocalConstTee128(op, local_index, c, dst) => binop!(local_const_tee Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), - BinOpStackGlobal32(op, global_index) => binop!(stack_global Value32, 32, op, global_index), - BinOpStackGlobal64(op, global_index) => binop!(stack_global Value64, 64, op, global_index), + I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), + I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), + MulAccLocal32(acc) => exec_op!(binop_acc_local i32, acc, |a: i32, b| a.wrapping_mul(b), |a: i32, b| a.wrapping_add(b)), + MulAccLocal64(acc) => exec_op!(binop_acc_local i64, acc, |a: i64, b| a.wrapping_mul(b), |a: i64, b| a.wrapping_add(b)), + FMulAccLocal32(acc) => exec_op!(binop_acc_local f32, acc, |a: f32, b| a * b, |a: f32, b| a + b), + FMulAccLocal64(acc) => exec_op!(binop_acc_local f64, acc, |a: f64, b| a * b, |a: f64, b| a + b), + BinOpLocalLocal32(op, a, b) => exec_op!(binop_local_local Value32, exec_binop_32, op, a, b), + BinOpLocalLocal64(op, a, b) => exec_op!(binop_local_local Value64, exec_binop_64, op, a, b), + BinOpLocalLocal128(op, a, b) => exec_op!(binop_local_local Value128, exec_binop_128, op, a, b), + CmpLocalLocal32(op, a, b) => exec_op!(cmp_local_local i32, cmp_i32, op, a, b), + CmpLocalLocal64(op, a, b) => exec_op!(cmp_local_local i64, cmp_i64, op, a, b), + BinOpLocalLocalSet32(op, a, b, dst) => exec_op!(binop_local_local_set Value32, exec_binop_32, op, a, b, dst), + BinOpLocalLocalSet64(op, a, b, dst) => exec_op!(binop_local_local_set Value64, exec_binop_64, op, a, b, dst), + BinOpLocalLocalSet128(op, a, b, dst) => exec_op!(binop_local_local_set Value128, exec_binop_128, op, a, b, dst), + BinOpLocalLocalTee32(op, a, b, dst) => exec_op!(binop_local_local_tee Value32, exec_binop_32, op, a, b, dst), + BinOpLocalLocalTee64(op, a, b, dst) => exec_op!(binop_local_local_tee Value64, exec_binop_64, op, a, b, dst), + BinOpLocalLocalTee128(op, a, b, dst) => exec_op!(binop_local_local_tee Value128, exec_binop_128, op, a, b, dst), + BinOpLocalConst32(op, local_index, c) => exec_op!(binop_local_const Value32, exec_binop_32, op, local_index, *c as u32), + BinOpLocalConst64(op, local_index, c) => exec_op!(binop_local_const Value64, exec_binop_64, op, local_index, *c as u64), + BinOpLocalConst128(op, local_index, c) => exec_op!(binop_local_const Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c))), + BinOpGlobalConst32(op, global_index, c) => exec_op!(binop_global_const Value32, exec_binop_32, op, global_index, *c as u32), + BinOpGlobalConst64(op, global_index, c) => exec_op!(binop_global_const Value64, exec_binop_64, op, global_index, *c as u64), + BinOpGlobalConst128(op, global_index, c) => exec_op!(binop_global_const Value128, exec_binop_128, op, global_index, Value128(self.func.data.v128_const(*c))), + BinOpLocalConstSet32(op, local_index, c, dst) => exec_op!(binop_local_const_set Value32, exec_binop_32, op, local_index, *c as u32, dst), + BinOpLocalConstSet64(op, local_index, c, dst) => exec_op!(binop_local_const_set Value64, exec_binop_64, op, local_index, *c as u64, dst), + BinOpLocalConstSet128(op, local_index, c, dst) => exec_op!(binop_local_const_set Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), + BinOpLocalConstTee32(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value32, exec_binop_32, op, local_index, *c as u32, dst), + BinOpLocalConstTee64(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value64, exec_binop_64, op, local_index, *c as u64, dst), + BinOpLocalConstTee128(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), + BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index), + BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index), SetLocalConst32(local_index, c) => i32::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), SetLocalConst64(local_index, c) => i64::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), SetLocalConst128(local_index, c) => Value128::local_set(&mut self.store.value_stack, &self.cf, *local_index, Value128(self.func.data.v128_const(*c))), @@ -342,129 +401,132 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, |v| v)?, LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, |v| v)?, - AndConstTee32(c, local_index) => { stack_op!(unary i32, |v| v & *c); stack_op!(local_tee i32, local_index); } - SubConstTee32(c, local_index) => { stack_op!(unary i32, |v| v.wrapping_sub(*c)); stack_op!(local_tee i32, local_index); } - AndConstTee64(c, local_index) => { stack_op!(unary i64, |v| v & *c); stack_op!(local_tee i64, local_index); } - SubConstTee64(c, local_index) => { stack_op!(unary i64, |v| v.wrapping_sub(*c)); stack_op!(local_tee i64, local_index); } - LocalTee32(local_index) => stack_op!(local_tee Value32, local_index), - LocalTee64(local_index) => stack_op!(local_tee Value64, local_index), - LocalTee128(local_index) => stack_op!(local_tee Value128, local_index), - GlobalGet32(global_index) => stack_op!(global_get Value32, global_index), - GlobalGet64(global_index) => stack_op!(global_get Value64, global_index), - GlobalGet128(global_index) => stack_op!(global_get Value128, global_index), - GlobalSet32(global_index) => stack_op!(global_set Value32, global_index), - GlobalSet64(global_index) => stack_op!(global_set Value64, global_index), - GlobalSet128(global_index) => stack_op!(global_set Value128, global_index), - Const32(val) => self.exec_const(*val)?, - Const64(val) => self.exec_const(*val)?, - I64Eqz => stack_op!(unary i64 => i32, |v| i32::from(v == 0)), - I32Eqz => stack_op!(unary i32, |v| i32::from(v == 0)), - I32Eq => stack_op!(binary i32, |a, b| i32::from(a == b)), - I64Eq => stack_op!(binary i64 => i32, |a, b| i32::from(a == b)), - F32Eq => stack_op!(binary f32 => i32, |a, b| i32::from(a == b)), - F64Eq => stack_op!(binary f64 => i32, |a, b| i32::from(a == b)), - I32Ne => stack_op!(binary i32, |a, b| i32::from(a != b)), - I64Ne => stack_op!(binary i64 => i32, |a, b| i32::from(a != b)), - F32Ne => stack_op!(binary f32 => i32, |a, b| i32::from(a != b)), - F64Ne => stack_op!(binary f64 => i32, |a, b| i32::from(a != b)), - I32LtS => stack_op!(binary i32, |a, b| i32::from(a < b)), - I64LtS => stack_op!(binary i64 => i32, |a, b| i32::from(a < b)), - I32LtU => stack_op!(binary u32 => i32, |a, b| i32::from(a < b)), - I64LtU => stack_op!(binary u64 => i32, |a, b| i32::from(a < b)), - F32Lt => stack_op!(binary f32 => i32, |a, b| i32::from(a < b)), - F64Lt => stack_op!(binary f64 => i32, |a, b| i32::from(a < b)), - I32LeS => stack_op!(binary i32, |a, b| i32::from(a <= b)), - I64LeS => stack_op!(binary i64 => i32, |a, b| i32::from(a <= b)), - I32LeU => stack_op!(binary u32 => i32, |a, b| i32::from(a <= b)), - I64LeU => stack_op!(binary u64 => i32, |a, b| i32::from(a <= b)), - F32Le => stack_op!(binary f32 => i32, |a, b| i32::from(a <= b)), - F64Le => stack_op!(binary f64 => i32, |a, b| i32::from(a <= b)), - I32GeS => stack_op!(binary i32, |a, b| i32::from(a >= b)), - I64GeS => stack_op!(binary i64 => i32, |a, b| i32::from(a >= b)), - I32GeU => stack_op!(binary u32 => i32, |a, b| i32::from(a >= b)), - I64GeU => stack_op!(binary u64 => i32, |a, b| i32::from(a >= b)), - F32Ge => stack_op!(binary f32 => i32, |a, b| i32::from(a >= b)), - F64Ge => stack_op!(binary f64 => i32, |a, b| i32::from(a >= b)), - I32GtS => stack_op!(binary i32, |a, b| i32::from(a > b)), - I64GtS => stack_op!(binary i64 => i32, |a, b| i32::from(a > b)), - I32GtU => stack_op!(binary u32 => i32, |a, b| i32::from(a > b)), - I64GtU => stack_op!(binary u64 => i32, |a, b| i32::from(a > b)), - F32Gt => stack_op!(binary f32 => i32, |a, b| i32::from(a > b)), - F64Gt => stack_op!(binary f64 => i32, |a, b| i32::from(a > b)), - I32Add => stack_op!(binary i32, |a, b| a.wrapping_add(b)), - I64Add => stack_op!(binary i64, |a, b| a.wrapping_add(b)), - F32Add => stack_op!(binary f32, |a, b| a + b), - F64Add => stack_op!(binary f64, |a, b| a + b), - I32Sub => stack_op!(binary i32, |a, b| a.wrapping_sub(b)), - I64Sub => stack_op!(binary i64, |a, b| a.wrapping_sub(b)), - F32Sub => stack_op!(binary f32, |a, b| a - b), - F64Sub => stack_op!(binary f64, |a, b| a - b), - F32Div => stack_op!(binary f32, |a, b| a / b), - F64Div => stack_op!(binary f64, |a, b| a / b), - I32Mul => stack_op!(binary i32, |a, b| a.wrapping_mul(b)), - I64Mul => stack_op!(binary i64, |a, b| a.wrapping_mul(b)), - F32Mul => stack_op!(binary f32, |a, b| a * b), - F64Mul => stack_op!(binary f64, |a, b| a * b), - I32DivS => stack_op!(binary try i32, |a, b| a.tw_checked_div(b)), - I64DivS => stack_op!(binary try i64, |a, b| a.tw_checked_div(b)), - I32DivU => stack_op!(binary try u32, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), - I64DivU => stack_op!(binary try u64, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), - I32RemS => stack_op!(binary try i32, |a, b| a.tw_checked_wrapping_rem(b)), - I64RemS => stack_op!(binary try i64, |a, b| a.tw_checked_wrapping_rem(b)), - I32RemU => stack_op!(binary try u32, |a, b| a.tw_checked_wrapping_rem(b)), - I64RemU => stack_op!(binary try u64, |a, b| a.tw_checked_wrapping_rem(b)), - I32And => stack_op!(binary i32, |a, b| a & b), - I64And => stack_op!(binary i64, |a, b| a & b), - I32Or => stack_op!(binary i32, |a, b| a | b), - I64Or => stack_op!(binary i64, |a, b| a | b), - I32Xor => stack_op!(binary i32, |a, b| a ^ b), - I64Xor => stack_op!(binary i64, |a, b| a ^ b), - I32Shl => stack_op!(binary i32, |a, b| a.wrapping_shl(b as u32)), - I64Shl => stack_op!(binary i64, |a, b| a.wrapping_shl(b as u32)), - I32ShrS => stack_op!(binary i32, |a, b| a.wrapping_shr(b as u32)), - I64ShrS => stack_op!(binary i64, |a, b| a.wrapping_shr(b as u32)), - I32ShrU => stack_op!(binary u32, |a, b| a.wrapping_shr(b)), - I64ShrU => stack_op!(binary u64, |a, b| a.wrapping_shr(b as u32)), - I32Rotl => stack_op!(binary i32, |a, b| a.rotate_left(b as u32)), - I64Rotl => stack_op!(binary i64, |a, b| a.rotate_left(b as u32)), - I32Rotr => stack_op!(binary i32, |a, b| a.rotate_right(b as u32)), - I64Rotr => stack_op!(binary i64, |a, b| a.rotate_right(b as u32)), - I64Add128 => stack_op!(quaternary_into2 i64 => i64, |a_lo, a_hi, b_lo, b_hi| { + AndConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v & *c); exec_op!(local_tee i32, local_index); } + SubConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(*c)); exec_op!(local_tee i32, local_index); } + AndConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v & *c); exec_op!(local_tee i64, local_index); } + SubConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v.wrapping_sub(*c)); exec_op!(local_tee i64, local_index); } + LocalTee32(local_index) => exec_op!(local_tee Value32, local_index), + LocalTee64(local_index) => exec_op!(local_tee Value64, local_index), + LocalTee128(local_index) => exec_op!(local_tee Value128, local_index), + GlobalGet32(global_index) => exec_op!(global_get Value32, global_index), + GlobalGet64(global_index) => exec_op!(global_get Value64, global_index), + GlobalGet128(global_index) => exec_op!(global_get Value128, global_index), + GlobalSet32(global_index) => exec_op!(global_set Value32, global_index), + GlobalSet64(global_index) => exec_op!(global_set Value64, global_index), + GlobalSet128(global_index) => exec_op!(global_set Value128, global_index), + GlobalTee32(global_index) => exec_op!(global_tee Value32, global_index), + GlobalTee64(global_index) => exec_op!(global_tee Value64, global_index), + GlobalTee128(global_index) => exec_op!(global_tee Value128, global_index), + Const32(val) => i32::stack_push(&mut self.store.value_stack, *val)?, + Const64(val) => i64::stack_push(&mut self.store.value_stack, *val)?, + I64Eqz => exec_op!(unary i64 => i32, |v| i32::from(v == 0)), + I32Eqz => exec_op!(unary i32 => i32, |v| i32::from(v == 0)), + I32Eq => exec_op!(binary i32 => i32, |a, b| i32::from(a == b)), + I64Eq => exec_op!(binary i64 => i32, |a, b| i32::from(a == b)), + F32Eq => exec_op!(binary f32 => i32, |a, b| i32::from(a == b)), + F64Eq => exec_op!(binary f64 => i32, |a, b| i32::from(a == b)), + I32Ne => exec_op!(binary i32 => i32, |a, b| i32::from(a != b)), + I64Ne => exec_op!(binary i64 => i32, |a, b| i32::from(a != b)), + F32Ne => exec_op!(binary f32 => i32, |a, b| i32::from(a != b)), + F64Ne => exec_op!(binary f64 => i32, |a, b| i32::from(a != b)), + I32LtS => exec_op!(binary i32 => i32, |a, b| i32::from(a < b)), + I64LtS => exec_op!(binary i64 => i32, |a, b| i32::from(a < b)), + I32LtU => exec_op!(binary u32 => i32, |a, b| i32::from(a < b)), + I64LtU => exec_op!(binary u64 => i32, |a, b| i32::from(a < b)), + F32Lt => exec_op!(binary f32 => i32, |a, b| i32::from(a < b)), + F64Lt => exec_op!(binary f64 => i32, |a, b| i32::from(a < b)), + I32LeS => exec_op!(binary i32 => i32, |a, b| i32::from(a <= b)), + I64LeS => exec_op!(binary i64 => i32, |a, b| i32::from(a <= b)), + I32LeU => exec_op!(binary u32 => i32, |a, b| i32::from(a <= b)), + I64LeU => exec_op!(binary u64 => i32, |a, b| i32::from(a <= b)), + F32Le => exec_op!(binary f32 => i32, |a, b| i32::from(a <= b)), + F64Le => exec_op!(binary f64 => i32, |a, b| i32::from(a <= b)), + I32GeS => exec_op!(binary i32 => i32, |a, b| i32::from(a >= b)), + I64GeS => exec_op!(binary i64 => i32, |a, b| i32::from(a >= b)), + I32GeU => exec_op!(binary u32 => i32, |a, b| i32::from(a >= b)), + I64GeU => exec_op!(binary u64 => i32, |a, b| i32::from(a >= b)), + F32Ge => exec_op!(binary f32 => i32, |a, b| i32::from(a >= b)), + F64Ge => exec_op!(binary f64 => i32, |a, b| i32::from(a >= b)), + I32GtS => exec_op!(binary i32 => i32, |a, b| i32::from(a > b)), + I64GtS => exec_op!(binary i64 => i32, |a, b| i32::from(a > b)), + I32GtU => exec_op!(binary u32 => i32, |a, b| i32::from(a > b)), + I64GtU => exec_op!(binary u64 => i32, |a, b| i32::from(a > b)), + F32Gt => exec_op!(binary f32 => i32, |a, b| i32::from(a > b)), + F64Gt => exec_op!(binary f64 => i32, |a, b| i32::from(a > b)), + I32Add => exec_op!(binary i32 => i32, |a, b| a.wrapping_add(b)), + I64Add => exec_op!(binary i64 => i64, |a, b| a.wrapping_add(b)), + F32Add => exec_op!(binary f32 => f32, |a, b| a + b), + F64Add => exec_op!(binary f64 => f64, |a, b| a + b), + I32Sub => exec_op!(binary i32 => i32, |a, b| a.wrapping_sub(b)), + I64Sub => exec_op!(binary i64 => i64, |a, b| a.wrapping_sub(b)), + F32Sub => exec_op!(binary f32 => f32, |a, b| a - b), + F64Sub => exec_op!(binary f64 => f64, |a, b| a - b), + F32Div => exec_op!(binary f32 => f32, |a, b| a / b), + F64Div => exec_op!(binary f64 => f64, |a, b| a / b), + I32Mul => exec_op!(binary i32 => i32, |a, b| a.wrapping_mul(b)), + I64Mul => exec_op!(binary i64 => i64, |a, b| a.wrapping_mul(b)), + F32Mul => exec_op!(binary f32 => f32, |a, b| a * b), + F64Mul => exec_op!(binary f64 => f64, |a, b| a * b), + I32DivS => exec_op!(binary_fallible i32, |a, b| a.tw_checked_div(b)), + I64DivS => exec_op!(binary_fallible i64, |a, b| a.tw_checked_div(b)), + I32DivU => exec_op!(binary_fallible u32, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), + I64DivU => exec_op!(binary_fallible u64, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), + I32RemS => exec_op!(binary_fallible i32, |a, b| a.tw_checked_wrapping_rem(b)), + I64RemS => exec_op!(binary_fallible i64, |a, b| a.tw_checked_wrapping_rem(b)), + I32RemU => exec_op!(binary_fallible u32, |a, b| a.tw_checked_wrapping_rem(b)), + I64RemU => exec_op!(binary_fallible u64, |a, b| a.tw_checked_wrapping_rem(b)), + I32And => exec_op!(binary i32 => i32, |a, b| a & b), + I64And => exec_op!(binary i64 => i64, |a, b| a & b), + I32Or => exec_op!(binary i32 => i32, |a, b| a | b), + I64Or => exec_op!(binary i64 => i64, |a, b| a | b), + I32Xor => exec_op!(binary i32 => i32, |a, b| a ^ b), + I64Xor => exec_op!(binary i64 => i64, |a, b| a ^ b), + I32Shl => exec_op!(binary i32 => i32, |a, b| a.wrapping_shl(b as u32)), + I64Shl => exec_op!(binary i64 => i64, |a, b| a.wrapping_shl(b as u32)), + I32ShrS => exec_op!(binary i32 => i32, |a, b| a.wrapping_shr(b as u32)), + I64ShrS => exec_op!(binary i64 => i64, |a, b| a.wrapping_shr(b as u32)), + I32ShrU => exec_op!(binary u32 => u32, |a, b| a.wrapping_shr(b)), + I64ShrU => exec_op!(binary u64 => u64, |a, b| a.wrapping_shr(b as u32)), + I32Rotl => exec_op!(binary i32 => i32, |a, b| a.rotate_left(b as u32)), + I64Rotl => exec_op!(binary i64 => i64, |a, b| a.rotate_left(b as u32)), + I32Rotr => exec_op!(binary i32 => i32, |a, b| a.rotate_right(b as u32)), + I64Rotr => exec_op!(binary i64 => i64, |a, b| a.rotate_right(b as u32)), + I64Add128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| { let lo = a_lo.wrapping_add(b_lo); let carry = u64::from((lo as u64) < (a_lo as u64)); let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64); (lo, hi) }), - I64Sub128 => stack_op!(quaternary_into2 i64 => i64, |a_lo, a_hi, b_lo, b_hi| { + I64Sub128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| { let lo = a_lo.wrapping_sub(b_lo); let borrow = u64::from((a_lo as u64) < (b_lo as u64)); let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64); (lo, hi) }), - I64MulWideS => stack_op!(binary_into2 i64 => i64, |a, b| { + I64MulWideS => exec_op!(binary_two_results i64 => i64, |a, b| { let product = (a as i128).wrapping_mul(b as i128); (product as i64, (product >> 64) as i64) }), - I64MulWideU => stack_op!(binary_into2 i64 => i64, |a, b| { + I64MulWideU => exec_op!(binary_two_results i64 => i64, |a, b| { let product = (a as u64 as u128).wrapping_mul(b as u64 as u128); (product as u64 as i64, (product >> 64) as u64 as i64) }), - I32Clz => stack_op!(unary i32, |v| v.leading_zeros() as i32), - I64Clz => stack_op!(unary i64, |v| i64::from(v.leading_zeros())), - I32Ctz => stack_op!(unary i32, |v| v.trailing_zeros() as i32), - I64Ctz => stack_op!(unary i64, |v| i64::from(v.trailing_zeros())), - I32Popcnt => stack_op!(unary i32, |v| v.count_ones() as i32), - I64Popcnt => stack_op!(unary i64, |v| i64::from(v.count_ones())), + I32Clz => exec_op!(unary i32 => i32, |v| v.leading_zeros() as i32), + I64Clz => exec_op!(unary i64 => i64, |v| i64::from(v.leading_zeros())), + I32Ctz => exec_op!(unary i32 => i32, |v| v.trailing_zeros() as i32), + I64Ctz => exec_op!(unary i64 => i64, |v| i64::from(v.trailing_zeros())), + I32Popcnt => exec_op!(unary i32 => i32, |v| v.count_ones() as i32), + I64Popcnt => exec_op!(unary i64 => i64, |v| i64::from(v.count_ones())), // Reference types - RefFunc(func_idx) => self.exec_const(ValueRef::from_category_addr(self.module.resolve_func_addr(*func_idx)))?, - RefNull(_) => self.exec_const(ValueRef::NULL)?, + RefFunc(func_idx) => ValueRef::stack_push(&mut self.store.value_stack, ValueRef::from_category_addr(self.module.resolve_func_addr(*func_idx)))?, + RefNull(_) => ValueRef::stack_push(&mut self.store.value_stack, ValueRef::NULL)?, RefIsNull => self.exec_ref_is_null()?, RefAsNonNull => self.exec_ref_as_non_null()?, - RefI31 => stack_op!(unary i32 => ValueRef, |v| ValueRef::from_i31(v)), + RefI31 => exec_op!(unary i32 => ValueRef, |v| ValueRef::from_i31(v)), I31GetS => self.exec_i31_get(true)?, I31GetU => self.exec_i31_get(false)?, - RefEq => stack_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), + RefEq => exec_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), RefTest(ty) => self.exec_ref_test(*ty)?, RefCast(ty) => self.exec_ref_cast(*ty)?, // GC objects @@ -536,46 +598,46 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64Load32U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, // Numeric conversion operations - F32ConvertI32S => stack_op!(unary i32 => f32, |v| v as f32), - F32ConvertI64S => stack_op!(unary i64 => f32, |v| v as f32), - F64ConvertI32S => stack_op!(unary i32 => f64, |v| f64::from(v)), - F64ConvertI64S => stack_op!(unary i64 => f64, |v| v as f64), - F32ConvertI32U => stack_op!(unary u32 => f32, |v| v as f32), - F32ConvertI64U => stack_op!(unary u64 => f32, |v| v as f32), - F64ConvertI32U => stack_op!(unary u32 => f64, |v| f64::from(v)), - F64ConvertI64U => stack_op!(unary u64 => f64, |v| v as f64), + F32ConvertI32S => exec_op!(unary i32 => f32, |v| v as f32), + F32ConvertI64S => exec_op!(unary i64 => f32, |v| v as f32), + F64ConvertI32S => exec_op!(unary i32 => f64, |v| f64::from(v)), + F64ConvertI64S => exec_op!(unary i64 => f64, |v| v as f64), + F32ConvertI32U => exec_op!(unary u32 => f32, |v| v as f32), + F32ConvertI64U => exec_op!(unary u64 => f32, |v| v as f32), + F64ConvertI32U => exec_op!(unary u32 => f64, |v| f64::from(v)), + F64ConvertI64U => exec_op!(unary u64 => f64, |v| v as f64), // Sign-extension operations - I32Extend8S => stack_op!(unary i32, |v| i32::from(v as i8)), - I32Extend16S => stack_op!(unary i32, |v| i32::from(v as i16)), - I64Extend8S => stack_op!(unary i64, |v| i64::from(v as i8)), - I64Extend16S => stack_op!(unary i64, |v| i64::from(v as i16)), - I64Extend32S => stack_op!(unary i64, |v| i64::from(v as i32)), - I64ExtendI32U => stack_op!(unary u32 => i64, |v| i64::from(v)), - I64ExtendI32S => stack_op!(unary i32 => i64, |v| i64::from(v)), - I32WrapI64 => stack_op!(unary i64 => i32, |v| v as i32), - F32DemoteF64 => stack_op!(unary f64 => f32, |v| v as f32), - F64PromoteF32 => stack_op!(unary f32 => f64, |v| f64::from(v)), - F32Abs => stack_op!(unary f32, |v| v.abs()), - F64Abs => stack_op!(unary f64, |v| v.abs()), - F32Neg => stack_op!(unary f32, |v| -v), - F64Neg => stack_op!(unary f64, |v| -v), - F32Ceil => stack_op!(unary f32, |v| v.ceil()), - F64Ceil => stack_op!(unary f64, |v| v.ceil()), - F32Floor => stack_op!(unary f32, |v| v.floor()), - F64Floor => stack_op!(unary f64, |v| v.floor()), - F32Trunc => stack_op!(unary f32, |v| v.trunc()), - F64Trunc => stack_op!(unary f64, |v| v.trunc()), - F32Nearest => stack_op!(unary f32, |v| v.tw_nearest()), - F64Nearest => stack_op!(unary f64, |v| v.tw_nearest()), - F32Sqrt => stack_op!(unary f32, |v| v.sqrt()), - F64Sqrt => stack_op!(unary f64, |v| v.sqrt()), - F32Min => stack_op!(binary f32, |a, b| a.tw_minimum(b)), - F64Min => stack_op!(binary f64, |a, b| a.tw_minimum(b)), - F32Max => stack_op!(binary f32, |a, b| a.tw_maximum(b)), - F64Max => stack_op!(binary f64, |a, b| a.tw_maximum(b)), - F32Copysign => stack_op!(binary f32, |a, b| a.copysign(b)), - F64Copysign => stack_op!(binary f64, |a, b| a.copysign(b)), + I32Extend8S => exec_op!(unary i32 => i32, |v| i32::from(v as i8)), + I32Extend16S => exec_op!(unary i32 => i32, |v| i32::from(v as i16)), + I64Extend8S => exec_op!(unary i64 => i64, |v| i64::from(v as i8)), + I64Extend16S => exec_op!(unary i64 => i64, |v| i64::from(v as i16)), + I64Extend32S => exec_op!(unary i64 => i64, |v| i64::from(v as i32)), + I64ExtendI32U => exec_op!(unary u32 => i64, |v| i64::from(v)), + I64ExtendI32S => exec_op!(unary i32 => i64, |v| i64::from(v)), + I32WrapI64 => exec_op!(unary i64 => i32, |v| v as i32), + F32DemoteF64 => exec_op!(unary f64 => f32, |v| v as f32), + F64PromoteF32 => exec_op!(unary f32 => f64, |v| f64::from(v)), + F32Abs => exec_op!(unary f32 => f32, |v| v.abs()), + F64Abs => exec_op!(unary f64 => f64, |v| v.abs()), + F32Neg => exec_op!(unary f32 => f32, |v| -v), + F64Neg => exec_op!(unary f64 => f64, |v| -v), + F32Ceil => exec_op!(unary f32 => f32, |v| v.ceil()), + F64Ceil => exec_op!(unary f64 => f64, |v| v.ceil()), + F32Floor => exec_op!(unary f32 => f32, |v| v.floor()), + F64Floor => exec_op!(unary f64 => f64, |v| v.floor()), + F32Trunc => exec_op!(unary f32 => f32, |v| v.trunc()), + F64Trunc => exec_op!(unary f64 => f64, |v| v.trunc()), + F32Nearest => exec_op!(unary f32 => f32, |v| v.tw_nearest()), + F64Nearest => exec_op!(unary f64 => f64, |v| v.tw_nearest()), + F32Sqrt => exec_op!(unary f32 => f32, |v| v.sqrt()), + F64Sqrt => exec_op!(unary f64 => f64, |v| v.sqrt()), + F32Min => exec_op!(binary f32 => f32, |a, b| a.tw_minimum(b)), + F64Min => exec_op!(binary f64 => f64, |a, b| a.tw_minimum(b)), + F32Max => exec_op!(binary f32 => f32, |a, b| a.tw_maximum(b)), + F64Max => exec_op!(binary f64 => f64, |a, b| a.tw_maximum(b)), + F32Copysign => exec_op!(binary f32 => f32, |a, b| a.copysign(b)), + F64Copysign => exec_op!(binary f64 => f64, |a, b| a.copysign(b)), I32TruncF32S => checked_conv_float!(f32, i32, self), I32TruncF64S => checked_conv_float!(f64, i32, self), I32TruncF32U => checked_conv_float!(f32, u32, i32, self), @@ -586,25 +648,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64TruncF64U => checked_conv_float!(f64, u64, i64, self), // Non-trapping float-to-int conversions - I32TruncSatF32S => stack_op!(unary f32 => i32, |v| v.trunc() as i32), - I32TruncSatF32U => stack_op!(unary f32 => u32, |v| v.trunc() as u32), - I32TruncSatF64S => stack_op!(unary f64 => i32, |v| v.trunc() as i32), - I32TruncSatF64U => stack_op!(unary f64 => u32, |v| v.trunc() as u32), - I64TruncSatF32S => stack_op!(unary f32 => i64, |v| v.trunc() as i64), - I64TruncSatF32U => stack_op!(unary f32 => u64, |v| v.trunc() as u64), - I64TruncSatF64S => stack_op!(unary f64 => i64, |v| v.trunc() as i64), - I64TruncSatF64U => stack_op!(unary f64 => u64, |v| v.trunc() as u64), + I32TruncSatF32S => exec_op!(unary f32 => i32, |v| v.trunc() as i32), + I32TruncSatF32U => exec_op!(unary f32 => u32, |v| v.trunc() as u32), + I32TruncSatF64S => exec_op!(unary f64 => i32, |v| v.trunc() as i32), + I32TruncSatF64U => exec_op!(unary f64 => u32, |v| v.trunc() as u32), + I64TruncSatF32S => exec_op!(unary f32 => i64, |v| v.trunc() as i64), + I64TruncSatF32U => exec_op!(unary f32 => u64, |v| v.trunc() as u64), + I64TruncSatF64S => exec_op!(unary f64 => i64, |v| v.trunc() as i64), + I64TruncSatF64U => exec_op!(unary f64 => u64, |v| v.trunc() as u64), // SIMD extension - V128Not => stack_op!(unary Value128, |v| v.v128_not()), - V128And => stack_op!(binary Value128, |a, b| a.v128_and(b)), - V128AndNot => stack_op!(binary Value128, |a, b| a.v128_andnot(b)), - V128Or => stack_op!(binary Value128, |a, b| a.v128_or(b)), - V128Xor => stack_op!(binary Value128, |a, b| a.v128_xor(b)), - V128Bitselect => stack_op!(ternary Value128, |a, b, c| Value128::v128_bitselect(a, b, c)), - V128AnyTrue => stack_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), - I8x16Swizzle => stack_op!(binary Value128, |a, s| a.i8x16_swizzle(s)), - I8x16RelaxedSwizzle => stack_op!(binary Value128, |a, s| a.i8x16_relaxed_swizzle(s)), + V128Not => exec_op!(unary Value128 => Value128, |v| v.v128_not()), + V128And => exec_op!(binary Value128 => Value128, |a, b| a.v128_and(b)), + V128AndNot => exec_op!(binary Value128 => Value128, |a, b| a.v128_andnot(b)), + V128Or => exec_op!(binary Value128 => Value128, |a, b| a.v128_or(b)), + V128Xor => exec_op!(binary Value128 => Value128, |a, b| a.v128_xor(b)), + V128Bitselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::v128_bitselect(a, b, c)), + V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), + I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), + I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), V128Load(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| v)?, V128Load8x8S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, V128Load8x8U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, @@ -623,235 +685,235 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128Store64Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load32Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i32x4([v, 0, 0, 0]))?, V128Load64Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i64x2([v, 0]))?, - Const128(arg) => self.exec_const(Value128(self.func.data.v128_const(*arg)))?, - I8x16ExtractLaneS(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), - I8x16ExtractLaneU(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), - I16x8ExtractLaneS(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), - I16x8ExtractLaneU(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_u16(*lane) as i32), - I32x4ExtractLane(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i32(*lane)), - I64x2ExtractLane(lane) => stack_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), - F32x4ExtractLane(lane) => stack_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), - F64x2ExtractLane(lane) => stack_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), + Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(self.func.data.v128_const(*arg)))?, + I8x16ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), + I8x16ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), + I16x8ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), + I16x8ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u16(*lane) as i32), + I32x4ExtractLane(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i32(*lane)), + I64x2ExtractLane(lane) => exec_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), + F32x4ExtractLane(lane) => exec_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), + F64x2ExtractLane(lane) => exec_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), V128Load8Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load16Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load32Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load64Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - I8x16ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), - I16x8ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), - I32x4ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), - I64x2ReplaceLane(lane) => stack_op!(binary i64, Value128, |value, vec| vec.i64x2_replace_lane(*lane, value)), - F32x4ReplaceLane(lane) => stack_op!(binary f32, Value128, |value, vec| vec.f32x4_replace_lane(*lane, value)), - F64x2ReplaceLane(lane) => stack_op!(binary f64, Value128, |value, vec| vec.f64x2_replace_lane(*lane, value)), - I8x16Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)), - I16x8Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)), - I32x4Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i32(v)), - I64x2Splat => stack_op!(unary i64 => Value128, |v| Value128::splat_i64(v)), - F32x4Splat => stack_op!(unary f32 => Value128, |v| Value128::splat_f32(v)), - F64x2Splat => stack_op!(unary f64 => Value128, |v| Value128::splat_f64(v)), - I8x16Eq => stack_op!(binary Value128, |a, b| a.i8x16_eq(b)), - I16x8Eq => stack_op!(binary Value128, |a, b| a.i16x8_eq(b)), - I32x4Eq => stack_op!(binary Value128, |a, b| a.i32x4_eq(b)), - I64x2Eq => stack_op!(binary Value128, |a, b| a.i64x2_eq(b)), - F32x4Eq => stack_op!(binary Value128, |a, b| a.f32x4_eq(b)), - F64x2Eq => stack_op!(binary Value128, |a, b| a.f64x2_eq(b)), - I8x16Ne => stack_op!(binary Value128, |a, b| a.i8x16_ne(b)), - I16x8Ne => stack_op!(binary Value128, |a, b| a.i16x8_ne(b)), - I32x4Ne => stack_op!(binary Value128, |a, b| a.i32x4_ne(b)), - I64x2Ne => stack_op!(binary Value128, |a, b| a.i64x2_ne(b)), - F32x4Ne => stack_op!(binary Value128, |a, b| a.f32x4_ne(b)), - F64x2Ne => stack_op!(binary Value128, |a, b| a.f64x2_ne(b)), - I8x16LtS => stack_op!(binary Value128, |a, b| a.i8x16_lt_s(b)), - I16x8LtS => stack_op!(binary Value128, |a, b| a.i16x8_lt_s(b)), - I32x4LtS => stack_op!(binary Value128, |a, b| a.i32x4_lt_s(b)), - I64x2LtS => stack_op!(binary Value128, |a, b| a.i64x2_lt_s(b)), - I8x16LtU => stack_op!(binary Value128, |a, b| a.i8x16_lt_u(b)), - I16x8LtU => stack_op!(binary Value128, |a, b| a.i16x8_lt_u(b)), - I32x4LtU => stack_op!(binary Value128, |a, b| a.i32x4_lt_u(b)), - F32x4Lt => stack_op!(binary Value128, |a, b| a.f32x4_lt(b)), - F64x2Lt => stack_op!(binary Value128, |a, b| a.f64x2_lt(b)), - F32x4Gt => stack_op!(binary Value128, |a, b| a.f32x4_gt(b)), - F64x2Gt => stack_op!(binary Value128, |a, b| a.f64x2_gt(b)), - I8x16GtS => stack_op!(binary Value128, |a, b| a.i8x16_gt_s(b)), - I16x8GtS => stack_op!(binary Value128, |a, b| a.i16x8_gt_s(b)), - I32x4GtS => stack_op!(binary Value128, |a, b| a.i32x4_gt_s(b)), - I64x2GtS => stack_op!(binary Value128, |a, b| a.i64x2_gt_s(b)), - I64x2LeS => stack_op!(binary Value128, |a, b| a.i64x2_le_s(b)), - F32x4Le => stack_op!(binary Value128, |a, b| a.f32x4_le(b)), - F64x2Le => stack_op!(binary Value128, |a, b| a.f64x2_le(b)), - I8x16GtU => stack_op!(binary Value128, |a, b| a.i8x16_gt_u(b)), - I16x8GtU => stack_op!(binary Value128, |a, b| a.i16x8_gt_u(b)), - I32x4GtU => stack_op!(binary Value128, |a, b| a.i32x4_gt_u(b)), - F32x4Ge => stack_op!(binary Value128, |a, b| a.f32x4_ge(b)), - F64x2Ge => stack_op!(binary Value128, |a, b| a.f64x2_ge(b)), - I8x16LeS => stack_op!(binary Value128, |a, b| a.i8x16_le_s(b)), - I16x8LeS => stack_op!(binary Value128, |a, b| a.i16x8_le_s(b)), - I32x4LeS => stack_op!(binary Value128, |a, b| a.i32x4_le_s(b)), - I8x16LeU => stack_op!(binary Value128, |a, b| a.i8x16_le_u(b)), - I16x8LeU => stack_op!(binary Value128, |a, b| a.i16x8_le_u(b)), - I32x4LeU => stack_op!(binary Value128, |a, b| a.i32x4_le_u(b)), - I8x16GeS => stack_op!(binary Value128, |a, b| a.i8x16_ge_s(b)), - I16x8GeS => stack_op!(binary Value128, |a, b| a.i16x8_ge_s(b)), - I32x4GeS => stack_op!(binary Value128, |a, b| a.i32x4_ge_s(b)), - I64x2GeS => stack_op!(binary Value128, |a, b| a.i64x2_ge_s(b)), - I8x16GeU => stack_op!(binary Value128, |a, b| a.i8x16_ge_u(b)), - I16x8GeU => stack_op!(binary Value128, |a, b| a.i16x8_ge_u(b)), - I32x4GeU => stack_op!(binary Value128, |a, b| a.i32x4_ge_u(b)), - I8x16Abs => stack_op!(unary Value128, |a| a.i8x16_abs()), - I16x8Abs => stack_op!(unary Value128, |a| a.i16x8_abs()), - I32x4Abs => stack_op!(unary Value128, |a| a.i32x4_abs()), - I64x2Abs => stack_op!(unary Value128, |a| a.i64x2_abs()), - I8x16Neg => stack_op!(unary Value128, |a| a.i8x16_neg()), - I16x8Neg => stack_op!(unary Value128, |a| a.i16x8_neg()), - I32x4Neg => stack_op!(unary Value128, |a| a.i32x4_neg()), - I64x2Neg => stack_op!(unary Value128, |a| a.i64x2_neg()), - I8x16AllTrue => stack_op!(unary Value128 => i32, |v| v.i8x16_all_true() as i32), - I16x8AllTrue => stack_op!(unary Value128 => i32, |v| v.i16x8_all_true() as i32), - I32x4AllTrue => stack_op!(unary Value128 => i32, |v| v.i32x4_all_true() as i32), - I64x2AllTrue => stack_op!(unary Value128 => i32, |v| v.i64x2_all_true() as i32), - I8x16Bitmask => stack_op!(unary Value128 => i32, |v| v.i8x16_bitmask() as i32), - I16x8Bitmask => stack_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32), - I32x4Bitmask => stack_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32), - I64x2Bitmask => stack_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32), - I8x16Shl => stack_op!(binary i32, Value128, |a, b| b.i8x16_shl(a as u32)), - I16x8Shl => stack_op!(binary i32, Value128, |a, b| b.i16x8_shl(a as u32)), - I32x4Shl => stack_op!(binary i32, Value128, |a, b| b.i32x4_shl(a as u32)), - I64x2Shl => stack_op!(binary i32, Value128, |a, b| b.i64x2_shl(a as u32)), - I8x16ShrS => stack_op!(binary i32, Value128, |a, b| b.i8x16_shr_s(a as u32)), - I16x8ShrS => stack_op!(binary i32, Value128, |a, b| b.i16x8_shr_s(a as u32)), - I32x4ShrS => stack_op!(binary i32, Value128, |a, b| b.i32x4_shr_s(a as u32)), - I64x2ShrS => stack_op!(binary i32, Value128, |a, b| b.i64x2_shr_s(a as u32)), - I8x16ShrU => stack_op!(binary i32, Value128, |a, b| b.i8x16_shr_u(a as u32)), - I16x8ShrU => stack_op!(binary i32, Value128, |a, b| b.i16x8_shr_u(a as u32)), - I32x4ShrU => stack_op!(binary i32, Value128, |a, b| b.i32x4_shr_u(a as u32)), - I64x2ShrU => stack_op!(binary i32, Value128, |a, b| b.i64x2_shr_u(a as u32)), - I8x16Add => stack_op!(binary Value128, |a, b| a.i8x16_add(b)), - I16x8Add => stack_op!(binary Value128, |a, b| a.i16x8_add(b)), - I32x4Add => stack_op!(binary Value128, |a, b| a.i32x4_add(b)), - I64x2Add => stack_op!(binary Value128, |a, b| a.i64x2_add(b)), - I8x16Sub => stack_op!(binary Value128, |a, b| a.i8x16_sub(b)), - I16x8Sub => stack_op!(binary Value128, |a, b| a.i16x8_sub(b)), - I32x4Sub => stack_op!(binary Value128, |a, b| a.i32x4_sub(b)), - I64x2Sub => stack_op!(binary Value128, |a, b| a.i64x2_sub(b)), - I8x16MinS => stack_op!(binary Value128, |a, b| a.i8x16_min_s(b)), - I16x8MinS => stack_op!(binary Value128, |a, b| a.i16x8_min_s(b)), - I32x4MinS => stack_op!(binary Value128, |a, b| a.i32x4_min_s(b)), - I8x16MinU => stack_op!(binary Value128, |a, b| a.i8x16_min_u(b)), - I16x8MinU => stack_op!(binary Value128, |a, b| a.i16x8_min_u(b)), - I32x4MinU => stack_op!(binary Value128, |a, b| a.i32x4_min_u(b)), - I8x16MaxS => stack_op!(binary Value128, |a, b| a.i8x16_max_s(b)), - I16x8MaxS => stack_op!(binary Value128, |a, b| a.i16x8_max_s(b)), - I32x4MaxS => stack_op!(binary Value128, |a, b| a.i32x4_max_s(b)), - I8x16MaxU => stack_op!(binary Value128, |a, b| a.i8x16_max_u(b)), - I16x8MaxU => stack_op!(binary Value128, |a, b| a.i16x8_max_u(b)), - I32x4MaxU => stack_op!(binary Value128, |a, b| a.i32x4_max_u(b)), - I64x2Mul => stack_op!(binary Value128, |a, b| a.i64x2_mul(b)), - I16x8Mul => stack_op!(binary Value128, |a, b| a.i16x8_mul(b)), - I32x4Mul => stack_op!(binary Value128, |a, b| a.i32x4_mul(b)), - I8x16NarrowI16x8S => stack_op!(binary Value128, |a, b| Value128::i8x16_narrow_i16x8_s(a, b)), - I8x16NarrowI16x8U => stack_op!(binary Value128, |a, b| Value128::i8x16_narrow_i16x8_u(a, b)), - I16x8NarrowI32x4S => stack_op!(binary Value128, |a, b| Value128::i16x8_narrow_i32x4_s(a, b)), - I16x8NarrowI32x4U => stack_op!(binary Value128, |a, b| Value128::i16x8_narrow_i32x4_u(a, b)), - I8x16AddSatS => stack_op!(binary Value128, |a, b| a.i8x16_add_sat_s(b)), - I16x8AddSatS => stack_op!(binary Value128, |a, b| a.i16x8_add_sat_s(b)), - I8x16AddSatU => stack_op!(binary Value128, |a, b| a.i8x16_add_sat_u(b)), - I16x8AddSatU => stack_op!(binary Value128, |a, b| a.i16x8_add_sat_u(b)), - I8x16SubSatS => stack_op!(binary Value128, |a, b| a.i8x16_sub_sat_s(b)), - I16x8SubSatS => stack_op!(binary Value128, |a, b| a.i16x8_sub_sat_s(b)), - I8x16SubSatU => stack_op!(binary Value128, |a, b| a.i8x16_sub_sat_u(b)), - I16x8SubSatU => stack_op!(binary Value128, |a, b| a.i16x8_sub_sat_u(b)), - I8x16AvgrU => stack_op!(binary Value128, |a, b| a.i8x16_avgr_u(b)), - I16x8AvgrU => stack_op!(binary Value128, |a, b| a.i16x8_avgr_u(b)), - I16x8ExtAddPairwiseI8x16S => stack_op!(unary Value128, |a| a.i16x8_extadd_pairwise_i8x16_s()), - I16x8ExtAddPairwiseI8x16U => stack_op!(unary Value128, |a| a.i16x8_extadd_pairwise_i8x16_u()), - I32x4ExtAddPairwiseI16x8S => stack_op!(unary Value128, |a| a.i32x4_extadd_pairwise_i16x8_s()), - I32x4ExtAddPairwiseI16x8U => stack_op!(unary Value128, |a| a.i32x4_extadd_pairwise_i16x8_u()), - I16x8ExtMulLowI8x16S => stack_op!(binary Value128, |a, b| a.i16x8_extmul_low_i8x16_s(b)), - I16x8ExtMulLowI8x16U => stack_op!(binary Value128, |a, b| a.i16x8_extmul_low_i8x16_u(b)), - I16x8ExtMulHighI8x16S => stack_op!(binary Value128, |a, b| a.i16x8_extmul_high_i8x16_s(b)), - I16x8ExtMulHighI8x16U => stack_op!(binary Value128, |a, b| a.i16x8_extmul_high_i8x16_u(b)), - I32x4ExtMulLowI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_extmul_low_i16x8_s(b)), - I32x4ExtMulLowI16x8U => stack_op!(binary Value128, |a, b| a.i32x4_extmul_low_i16x8_u(b)), - I32x4ExtMulHighI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_extmul_high_i16x8_s(b)), - I32x4ExtMulHighI16x8U => stack_op!(binary Value128, |a, b| a.i32x4_extmul_high_i16x8_u(b)), - I64x2ExtMulLowI32x4S => stack_op!(binary Value128, |a, b| a.i64x2_extmul_low_i32x4_s(b)), - I64x2ExtMulLowI32x4U => stack_op!(binary Value128, |a, b| a.i64x2_extmul_low_i32x4_u(b)), - I64x2ExtMulHighI32x4S => stack_op!(binary Value128, |a, b| a.i64x2_extmul_high_i32x4_s(b)), - I64x2ExtMulHighI32x4U => stack_op!(binary Value128, |a, b| a.i64x2_extmul_high_i32x4_u(b)), - I16x8ExtendLowI8x16S => stack_op!(unary Value128, |a| a.i16x8_extend_low_i8x16_s()), - I16x8ExtendLowI8x16U => stack_op!(unary Value128, |a| a.i16x8_extend_low_i8x16_u()), - I16x8ExtendHighI8x16S => stack_op!(unary Value128, |a| a.i16x8_extend_high_i8x16_s()), - I16x8ExtendHighI8x16U => stack_op!(unary Value128, |a| a.i16x8_extend_high_i8x16_u()), - I32x4ExtendLowI16x8S => stack_op!(unary Value128, |a| a.i32x4_extend_low_i16x8_s()), - I32x4ExtendLowI16x8U => stack_op!(unary Value128, |a| a.i32x4_extend_low_i16x8_u()), - I32x4ExtendHighI16x8S => stack_op!(unary Value128, |a| a.i32x4_extend_high_i16x8_s()), - I32x4ExtendHighI16x8U => stack_op!(unary Value128, |a| a.i32x4_extend_high_i16x8_u()), - I64x2ExtendLowI32x4S => stack_op!(unary Value128, |a| a.i64x2_extend_low_i32x4_s()), - I64x2ExtendLowI32x4U => stack_op!(unary Value128, |a| a.i64x2_extend_low_i32x4_u()), - I64x2ExtendHighI32x4S => stack_op!(unary Value128, |a| a.i64x2_extend_high_i32x4_s()), - I64x2ExtendHighI32x4U => stack_op!(unary Value128, |a| a.i64x2_extend_high_i32x4_u()), - I8x16Popcnt => stack_op!(unary Value128, |v| v.i8x16_popcnt()), - I8x16Shuffle(idx) => stack_op!(binary Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(self.func.data.v128_const(*idx)))), - I16x8Q15MulrSatS => stack_op!(binary Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), - I32x4DotI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_dot_i16x8_s(b)), - I8x16RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), - I16x8RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i16x8_relaxed_laneselect(a, b, c)), - I32x4RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i32x4_relaxed_laneselect(a, b, c)), - I64x2RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i64x2_relaxed_laneselect(a, b, c)), - I16x8RelaxedQ15mulrS => stack_op!(binary Value128, |a, b| a.i16x8_relaxed_q15mulr_s(b)), - I16x8RelaxedDotI8x16I7x16S => stack_op!(binary Value128, |a, b| a.i16x8_relaxed_dot_i8x16_i7x16_s(b)), - I32x4RelaxedDotI8x16I7x16AddS => stack_op!(ternary Value128, |a, b, c| a.i32x4_relaxed_dot_i8x16_i7x16_add_s(b, c)), - F32x4Ceil => stack_op!(unary Value128, |v| v.f32x4_ceil()), - F64x2Ceil => stack_op!(unary Value128, |v| v.f64x2_ceil()), - F32x4Floor => stack_op!(unary Value128, |v| v.f32x4_floor()), - F64x2Floor => stack_op!(unary Value128, |v| v.f64x2_floor()), - F32x4Trunc => stack_op!(unary Value128, |v| v.f32x4_trunc()), - F64x2Trunc => stack_op!(unary Value128, |v| v.f64x2_trunc()), - F32x4Nearest => stack_op!(unary Value128, |v| v.f32x4_nearest()), - F64x2Nearest => stack_op!(unary Value128, |v| v.f64x2_nearest()), - F32x4Abs => stack_op!(unary Value128, |v| v.f32x4_abs()), - F64x2Abs => stack_op!(unary Value128, |v| v.f64x2_abs()), - F32x4Neg => stack_op!(unary Value128, |v| v.f32x4_neg()), - F64x2Neg => stack_op!(unary Value128, |v| v.f64x2_neg()), - F32x4Sqrt => stack_op!(unary Value128, |v| v.f32x4_sqrt()), - F64x2Sqrt => stack_op!(unary Value128, |v| v.f64x2_sqrt()), - F32x4Add => stack_op!(binary Value128, |a, b| a.f32x4_add(b)), - F64x2Add => stack_op!(binary Value128, |a, b| a.f64x2_add(b)), - F32x4Sub => stack_op!(binary Value128, |a, b| a.f32x4_sub(b)), - F64x2Sub => stack_op!(binary Value128, |a, b| a.f64x2_sub(b)), - F32x4Mul => stack_op!(binary Value128, |a, b| a.f32x4_mul(b)), - F64x2Mul => stack_op!(binary Value128, |a, b| a.f64x2_mul(b)), - F32x4Div => stack_op!(binary Value128, |a, b| a.f32x4_div(b)), - F64x2Div => stack_op!(binary Value128, |a, b| a.f64x2_div(b)), - F32x4Min => stack_op!(binary Value128, |a, b| a.f32x4_min(b)), - F64x2Min => stack_op!(binary Value128, |a, b| a.f64x2_min(b)), - F32x4Max => stack_op!(binary Value128, |a, b| a.f32x4_max(b)), - F64x2Max => stack_op!(binary Value128, |a, b| a.f64x2_max(b)), - F32x4PMin => stack_op!(binary Value128, |a, b| a.f32x4_pmin(b)), - F32x4PMax => stack_op!(binary Value128, |a, b| a.f32x4_pmax(b)), - F64x2PMin => stack_op!(binary Value128, |a, b| a.f64x2_pmin(b)), - F64x2PMax => stack_op!(binary Value128, |a, b| a.f64x2_pmax(b)), - F32x4RelaxedMadd => stack_op!(ternary Value128, |a, b, c| a.f32x4_relaxed_madd(b, c)), - F32x4RelaxedNmadd => stack_op!(ternary Value128, |a, b, c| a.f32x4_relaxed_nmadd(b, c)), - F64x2RelaxedMadd => stack_op!(ternary Value128, |a, b, c| a.f64x2_relaxed_madd(b, c)), - F64x2RelaxedNmadd => stack_op!(ternary Value128, |a, b, c| a.f64x2_relaxed_nmadd(b, c)), - F32x4RelaxedMin => stack_op!(binary Value128, |a, b| a.f32x4_relaxed_min(b)), - F32x4RelaxedMax => stack_op!(binary Value128, |a, b| a.f32x4_relaxed_max(b)), - F64x2RelaxedMin => stack_op!(binary Value128, |a, b| a.f64x2_relaxed_min(b)), - F64x2RelaxedMax => stack_op!(binary Value128, |a, b| a.f64x2_relaxed_max(b)), - I32x4TruncSatF32x4S => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f32x4_s()), - I32x4TruncSatF32x4U => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f32x4_u()), - F32x4ConvertI32x4S => stack_op!(unary Value128, |v| v.f32x4_convert_i32x4_s()), - F32x4ConvertI32x4U => stack_op!(unary Value128, |v| v.f32x4_convert_i32x4_u()), - F64x2ConvertLowI32x4S => stack_op!(unary Value128, |v| v.f64x2_convert_low_i32x4_s()), - F64x2ConvertLowI32x4U => stack_op!(unary Value128, |v| v.f64x2_convert_low_i32x4_u()), - F32x4DemoteF64x2Zero => stack_op!(unary Value128, |v| v.f32x4_demote_f64x2_zero()), - F64x2PromoteLowF32x4 => stack_op!(unary Value128, |v| v.f64x2_promote_low_f32x4()), - I32x4TruncSatF64x2SZero => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f64x2_s_zero()), - I32x4TruncSatF64x2UZero => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f64x2_u_zero()), - I32x4RelaxedTruncF32x4S => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f32x4_s()), - I32x4RelaxedTruncF32x4U => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f32x4_u()), - I32x4RelaxedTruncF64x2SZero => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f64x2_s_zero()), - I32x4RelaxedTruncF64x2UZero => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()), + I8x16ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), + I16x8ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), + I32x4ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), + I64x2ReplaceLane(lane) => exec_op!(binary_mixed i64, Value128 => Value128, |value, vec| vec.i64x2_replace_lane(*lane, value)), + F32x4ReplaceLane(lane) => exec_op!(binary_mixed f32, Value128 => Value128, |value, vec| vec.f32x4_replace_lane(*lane, value)), + F64x2ReplaceLane(lane) => exec_op!(binary_mixed f64, Value128 => Value128, |value, vec| vec.f64x2_replace_lane(*lane, value)), + I8x16Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)), + I16x8Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)), + I32x4Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i32(v)), + I64x2Splat => exec_op!(unary i64 => Value128, |v| Value128::splat_i64(v)), + F32x4Splat => exec_op!(unary f32 => Value128, |v| Value128::splat_f32(v)), + F64x2Splat => exec_op!(unary f64 => Value128, |v| Value128::splat_f64(v)), + I8x16Eq => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_eq(b)), + I16x8Eq => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_eq(b)), + I32x4Eq => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_eq(b)), + I64x2Eq => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_eq(b)), + F32x4Eq => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_eq(b)), + F64x2Eq => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_eq(b)), + I8x16Ne => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ne(b)), + I16x8Ne => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ne(b)), + I32x4Ne => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ne(b)), + I64x2Ne => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_ne(b)), + F32x4Ne => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_ne(b)), + F64x2Ne => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_ne(b)), + I8x16LtS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_lt_s(b)), + I16x8LtS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_lt_s(b)), + I32x4LtS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_lt_s(b)), + I64x2LtS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_lt_s(b)), + I8x16LtU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_lt_u(b)), + I16x8LtU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_lt_u(b)), + I32x4LtU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_lt_u(b)), + F32x4Lt => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_lt(b)), + F64x2Lt => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_lt(b)), + F32x4Gt => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_gt(b)), + F64x2Gt => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_gt(b)), + I8x16GtS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_gt_s(b)), + I16x8GtS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_gt_s(b)), + I32x4GtS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_gt_s(b)), + I64x2GtS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_gt_s(b)), + I64x2LeS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_le_s(b)), + F32x4Le => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_le(b)), + F64x2Le => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_le(b)), + I8x16GtU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_gt_u(b)), + I16x8GtU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_gt_u(b)), + I32x4GtU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_gt_u(b)), + F32x4Ge => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_ge(b)), + F64x2Ge => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_ge(b)), + I8x16LeS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_le_s(b)), + I16x8LeS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_le_s(b)), + I32x4LeS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_le_s(b)), + I8x16LeU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_le_u(b)), + I16x8LeU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_le_u(b)), + I32x4LeU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_le_u(b)), + I8x16GeS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ge_s(b)), + I16x8GeS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ge_s(b)), + I32x4GeS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ge_s(b)), + I64x2GeS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_ge_s(b)), + I8x16GeU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ge_u(b)), + I16x8GeU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ge_u(b)), + I32x4GeU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ge_u(b)), + I8x16Abs => exec_op!(unary Value128 => Value128, |a| a.i8x16_abs()), + I16x8Abs => exec_op!(unary Value128 => Value128, |a| a.i16x8_abs()), + I32x4Abs => exec_op!(unary Value128 => Value128, |a| a.i32x4_abs()), + I64x2Abs => exec_op!(unary Value128 => Value128, |a| a.i64x2_abs()), + I8x16Neg => exec_op!(unary Value128 => Value128, |a| a.i8x16_neg()), + I16x8Neg => exec_op!(unary Value128 => Value128, |a| a.i16x8_neg()), + I32x4Neg => exec_op!(unary Value128 => Value128, |a| a.i32x4_neg()), + I64x2Neg => exec_op!(unary Value128 => Value128, |a| a.i64x2_neg()), + I8x16AllTrue => exec_op!(unary Value128 => i32, |v| v.i8x16_all_true() as i32), + I16x8AllTrue => exec_op!(unary Value128 => i32, |v| v.i16x8_all_true() as i32), + I32x4AllTrue => exec_op!(unary Value128 => i32, |v| v.i32x4_all_true() as i32), + I64x2AllTrue => exec_op!(unary Value128 => i32, |v| v.i64x2_all_true() as i32), + I8x16Bitmask => exec_op!(unary Value128 => i32, |v| v.i8x16_bitmask() as i32), + I16x8Bitmask => exec_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32), + I32x4Bitmask => exec_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32), + I64x2Bitmask => exec_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32), + I8x16Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)), + I16x8Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)), + I32x4Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)), + I64x2Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)), + I8x16ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)), + I16x8ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)), + I32x4ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)), + I64x2ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)), + I8x16ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)), + I16x8ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)), + I32x4ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)), + I64x2ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)), + I8x16Add => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add(b)), + I16x8Add => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add(b)), + I32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_add(b)), + I64x2Add => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_add(b)), + I8x16Sub => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub(b)), + I16x8Sub => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub(b)), + I32x4Sub => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_sub(b)), + I64x2Sub => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_sub(b)), + I8x16MinS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_min_s(b)), + I16x8MinS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_min_s(b)), + I32x4MinS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_min_s(b)), + I8x16MinU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_min_u(b)), + I16x8MinU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_min_u(b)), + I32x4MinU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_min_u(b)), + I8x16MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_max_s(b)), + I16x8MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_max_s(b)), + I32x4MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_max_s(b)), + I8x16MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_max_u(b)), + I16x8MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_max_u(b)), + I32x4MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_max_u(b)), + I64x2Mul => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_mul(b)), + I16x8Mul => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_mul(b)), + I32x4Mul => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_mul(b)), + I8x16NarrowI16x8S => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_s(a, b)), + I8x16NarrowI16x8U => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_u(a, b)), + I16x8NarrowI32x4S => exec_op!(binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_s(a, b)), + I16x8NarrowI32x4U => exec_op!(binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_u(a, b)), + I8x16AddSatS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add_sat_s(b)), + I16x8AddSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add_sat_s(b)), + I8x16AddSatU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add_sat_u(b)), + I16x8AddSatU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add_sat_u(b)), + I8x16SubSatS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub_sat_s(b)), + I16x8SubSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub_sat_s(b)), + I8x16SubSatU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub_sat_u(b)), + I16x8SubSatU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub_sat_u(b)), + I8x16AvgrU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_avgr_u(b)), + I16x8AvgrU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_avgr_u(b)), + I16x8ExtAddPairwiseI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_s()), + I16x8ExtAddPairwiseI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_u()), + I32x4ExtAddPairwiseI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_s()), + I32x4ExtAddPairwiseI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_u()), + I16x8ExtMulLowI8x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_s(b)), + I16x8ExtMulLowI8x16U => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_u(b)), + I16x8ExtMulHighI8x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_s(b)), + I16x8ExtMulHighI8x16U => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_u(b)), + I32x4ExtMulLowI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_s(b)), + I32x4ExtMulLowI16x8U => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_u(b)), + I32x4ExtMulHighI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_s(b)), + I32x4ExtMulHighI16x8U => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_u(b)), + I64x2ExtMulLowI32x4S => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_s(b)), + I64x2ExtMulLowI32x4U => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_u(b)), + I64x2ExtMulHighI32x4S => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_s(b)), + I64x2ExtMulHighI32x4U => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_u(b)), + I16x8ExtendLowI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_s()), + I16x8ExtendLowI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_u()), + I16x8ExtendHighI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_s()), + I16x8ExtendHighI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_u()), + I32x4ExtendLowI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_s()), + I32x4ExtendLowI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_u()), + I32x4ExtendHighI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_s()), + I32x4ExtendHighI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_u()), + I64x2ExtendLowI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_s()), + I64x2ExtendLowI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_u()), + I64x2ExtendHighI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()), + I64x2ExtendHighI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()), + I8x16Popcnt => exec_op!(unary Value128 => Value128, |v| v.i8x16_popcnt()), + I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(self.func.data.v128_const(*idx)))), + I16x8Q15MulrSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), + I32x4DotI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)), + I8x16RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), + I16x8RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i16x8_relaxed_laneselect(a, b, c)), + I32x4RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i32x4_relaxed_laneselect(a, b, c)), + I64x2RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i64x2_relaxed_laneselect(a, b, c)), + I16x8RelaxedQ15mulrS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_relaxed_q15mulr_s(b)), + I16x8RelaxedDotI8x16I7x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_relaxed_dot_i8x16_i7x16_s(b)), + I32x4RelaxedDotI8x16I7x16AddS => exec_op!(ternary Value128 => Value128, |a, b, c| a.i32x4_relaxed_dot_i8x16_i7x16_add_s(b, c)), + F32x4Ceil => exec_op!(unary Value128 => Value128, |v| v.f32x4_ceil()), + F64x2Ceil => exec_op!(unary Value128 => Value128, |v| v.f64x2_ceil()), + F32x4Floor => exec_op!(unary Value128 => Value128, |v| v.f32x4_floor()), + F64x2Floor => exec_op!(unary Value128 => Value128, |v| v.f64x2_floor()), + F32x4Trunc => exec_op!(unary Value128 => Value128, |v| v.f32x4_trunc()), + F64x2Trunc => exec_op!(unary Value128 => Value128, |v| v.f64x2_trunc()), + F32x4Nearest => exec_op!(unary Value128 => Value128, |v| v.f32x4_nearest()), + F64x2Nearest => exec_op!(unary Value128 => Value128, |v| v.f64x2_nearest()), + F32x4Abs => exec_op!(unary Value128 => Value128, |v| v.f32x4_abs()), + F64x2Abs => exec_op!(unary Value128 => Value128, |v| v.f64x2_abs()), + F32x4Neg => exec_op!(unary Value128 => Value128, |v| v.f32x4_neg()), + F64x2Neg => exec_op!(unary Value128 => Value128, |v| v.f64x2_neg()), + F32x4Sqrt => exec_op!(unary Value128 => Value128, |v| v.f32x4_sqrt()), + F64x2Sqrt => exec_op!(unary Value128 => Value128, |v| v.f64x2_sqrt()), + F32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_add(b)), + F64x2Add => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_add(b)), + F32x4Sub => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_sub(b)), + F64x2Sub => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_sub(b)), + F32x4Mul => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_mul(b)), + F64x2Mul => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_mul(b)), + F32x4Div => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_div(b)), + F64x2Div => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_div(b)), + F32x4Min => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_min(b)), + F64x2Min => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_min(b)), + F32x4Max => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_max(b)), + F64x2Max => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_max(b)), + F32x4PMin => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_pmin(b)), + F32x4PMax => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_pmax(b)), + F64x2PMin => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_pmin(b)), + F64x2PMax => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_pmax(b)), + F32x4RelaxedMadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_madd(b, c)), + F32x4RelaxedNmadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_nmadd(b, c)), + F64x2RelaxedMadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_madd(b, c)), + F64x2RelaxedNmadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_nmadd(b, c)), + F32x4RelaxedMin => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_relaxed_min(b)), + F32x4RelaxedMax => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_relaxed_max(b)), + F64x2RelaxedMin => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_relaxed_min(b)), + F64x2RelaxedMax => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_relaxed_max(b)), + I32x4TruncSatF32x4S => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_s()), + I32x4TruncSatF32x4U => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_u()), + F32x4ConvertI32x4S => exec_op!(unary Value128 => Value128, |v| v.f32x4_convert_i32x4_s()), + F32x4ConvertI32x4U => exec_op!(unary Value128 => Value128, |v| v.f32x4_convert_i32x4_u()), + F64x2ConvertLowI32x4S => exec_op!(unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_s()), + F64x2ConvertLowI32x4U => exec_op!(unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_u()), + F32x4DemoteF64x2Zero => exec_op!(unary Value128 => Value128, |v| v.f32x4_demote_f64x2_zero()), + F64x2PromoteLowF32x4 => exec_op!(unary Value128 => Value128, |v| v.f64x2_promote_low_f32x4()), + I32x4TruncSatF64x2SZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_s_zero()), + I32x4TruncSatF64x2UZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_u_zero()), + I32x4RelaxedTruncF32x4S => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_s()), + I32x4RelaxedTruncF32x4U => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_u()), + I32x4RelaxedTruncF64x2SZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_s_zero()), + I32x4RelaxedTruncF64x2UZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()), }; self.cf.instr_ptr = instr_ptr + 1; @@ -859,148 +921,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(None) } - #[inline(always)] - fn jump_if(&mut self, condition: bool, ip: u32) -> bool { - if condition { - self.cf.instr_ptr = ip as usize; - } - condition - } - - #[inline(always)] - fn exec_jump_zero_32(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) == 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_non_zero_32(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) != 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_zero_64(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) == 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_non_zero_64(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) != 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_ref_null(&mut self, target_ip: u32) -> bool { - let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); - if is_null { - ValueRef::stack_pop(&mut self.store.value_stack); - } - self.jump_if(is_null, target_ip) - } - - #[inline(always)] - fn exec_jump_ref_non_null(&mut self, target_ip: u32) -> bool { - let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null(); - if !is_non_null { - ValueRef::stack_pop(&mut self.store.value_stack); - } - self.jump_if(is_non_null, target_ip) - } - - #[inline(always)] - fn exec_jump_local_zero_32(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value32::local_get(&self.store.value_stack, &self.cf, local) == 0, target_ip) - } - - #[inline(always)] - fn exec_jump_local_non_zero_32(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value32::local_get(&self.store.value_stack, &self.cf, local) != 0, target_ip) - } - - #[inline(always)] - fn exec_jump_local_zero_64(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value64::local_get(&self.store.value_stack, &self.cf, local) == 0, target_ip) - } - - #[inline(always)] - fn exec_jump_local_non_zero_64(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value64::local_get(&self.store.value_stack, &self.cf, local) != 0, target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_const_32(&mut self, target_ip: u32, imm: i32, op: CmpOp) -> bool { - let condition = cmp_i32(::stack_pop(&mut self.store.value_stack), imm, op); - self.jump_if(condition, target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_const_64(&mut self, target_ip: u32, imm: i64, op: CmpOp) -> bool { - let condition = cmp_i64(::stack_pop(&mut self.store.value_stack), imm, op); - self.jump_if(condition, target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_local_32(&mut self, target_ip: u32, local: LocalAddr, op: CmpOp) -> bool { - let lhs = ::stack_pop(&mut self.store.value_stack); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, local); - self.jump_if(cmp_i32(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_local_64(&mut self, target_ip: u32, local: LocalAddr, op: CmpOp) -> bool { - let lhs = ::stack_pop(&mut self.store.value_stack); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, local); - self.jump_if(cmp_i64(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_inc_local_jump_32(&mut self, target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool) -> bool { - let value = i32::local_get(&self.store.value_stack, &self.cf, local).wrapping_add(delta); - i32::local_set(&mut self.store.value_stack, &self.cf, local, value); - self.jump_if((value == 0) == on_zero, target_ip) - } - - #[inline(always)] - fn exec_inc_local_jump_cmp_local_32( - &mut self, - target_ip: u32, - local: LocalAddr, - delta: i32, - right: LocalAddr, - op: CmpOp, - ) -> bool { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, local).wrapping_add(delta); - i32::local_set(&mut self.store.value_stack, &self.cf, local, lhs); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, right); - self.jump_if(cmp_i32(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_const_32(&mut self, target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp) -> bool { - self.jump_if(cmp_i32(i32::local_get(&self.store.value_stack, &self.cf, local), imm, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_const_64(&mut self, target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp) -> bool { - self.jump_if(cmp_i64(i64::local_get(&self.store.value_stack, &self.cf, local), i64::from(imm), op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_local_32(&mut self, target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp) -> bool { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, left); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, right); - self.jump_if(cmp_i32(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_local_64(&mut self, target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp) -> bool { - let lhs = i64::local_get(&self.store.value_stack, &self.cf, left); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, right); - self.jump_if(cmp_i64(lhs, rhs, op), target_ip) - } - fn exec_branch_table(&mut self, default_ip: u32, start: u32, len: u32) { let idx = ::stack_pop(&mut self.store.value_stack); let target_ip = if idx >= 0 && (idx as u32) < len { @@ -1453,18 +1373,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - #[inline(always)] - fn exec_binop_acc_local(&mut self, acc: LocalAddr, mul: M, add: A) - where - T: InternalValue, - M: Fn(T, T) -> T, - A: Fn(T, T) -> T, - { - let rhs = T::stack_pop(&mut self.store.value_stack); - let lhs = T::stack_pop(&mut self.store.value_stack); - T::local_update(&mut self.store.value_stack, &self.cf, acc, |v| add(mul(lhs, rhs), v)); - } - #[inline(always)] fn exec_load_local_value, const N: usize>( &self, @@ -1520,10 +1428,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_const(&mut self, val: T) -> Result<(), Trap> { - self.store.value_stack.push(val) - } - fn exec_ref_is_null(&mut self) -> Result<(), Trap> { let is_null = i32::from(::stack_pop(&mut self.store.value_stack).is_null()); self.store.value_stack.push::(is_null) @@ -1540,7 +1444,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn canonical_ref_type(&self, ty: RefType) -> RefType { let Some(type_index) = ty.type_index() else { return ty }; RefType::new_concrete(ty.is_nullable(), self.module.resolve_type_addr(type_index)) - .expect("canonical type address fits in a reference") } fn exec_ref_matches(&self, ty: RefType) -> bool { @@ -2171,3 +2074,60 @@ fn cmp_i64(lhs: i64, rhs: i64, op: CmpOp) -> bool { CmpOp::GeU => (lhs as u64) >= (rhs as u64), } } + +fn exec_binop_32(op: BinOp, lhs: u32, rhs: u32) -> u32 { + match op { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32, + BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32, + BinOp::IShrU => lhs.wrapping_shr(rhs), + BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32, + BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32, + BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(), + BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(), + BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(), + BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(), + BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(), + } +} + +fn exec_binop_64(op: BinOp, lhs: u64, rhs: u64) -> u64 { + match op { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64, + BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64, + BinOp::IShrU => lhs.wrapping_shr(rhs as u32), + BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64, + BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64, + BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(), + BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(), + BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(), + BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(), + BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(), + } +} + +fn exec_binop_128(op: BinOp128, lhs: Value128, rhs: Value128) -> Value128 { + match op { + BinOp128::And => lhs.v128_and(rhs), + BinOp128::AndNot => lhs.v128_andnot(rhs), + BinOp128::Or => lhs.v128_or(rhs), + BinOp128::Xor => lhs.v128_xor(rhs), + BinOp128::I64x2Add => lhs.i64x2_add(rhs), + BinOp128::I64x2Mul => lhs.i64x2_mul(rhs), + } +} diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index e12ef1a..6d13579 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -271,23 +271,20 @@ impl State { if expected_func { let Some(func_addr) = value.addr() else { return false }; let Some(func) = self.funcs.get(func_addr as usize) else { return false }; - let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); - return self.ref_type_is_subtype(actual, expected); + return self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected); } if expected.abstract_heap_type() == Some(AbstractHeapType::Exn) { return value.addr().is_some_and(|addr| self.exceptions.get(addr as usize).is_some()); } if value.is_i31() { - let actual = RefType::new_abstract(false, AbstractHeapType::I31); - return self.ref_type_is_subtype(actual, expected); + return self.ref_type_is_subtype(RefType::new_abstract(false, AbstractHeapType::I31), expected); } if value.is_host_any() { - let actual = RefType::new_abstract(false, AbstractHeapType::Any); - return self.ref_type_is_subtype(actual, expected); + return self.ref_type_is_subtype(RefType::new_abstract(false, AbstractHeapType::Any), expected); } let Some(object) = self.gc.get(value) else { return false }; - let actual = RefType::new_concrete(false, object.type_addr).expect("canonical type fits"); + let actual = RefType::new_concrete(false, object.type_addr); self.ref_type_is_subtype(actual, expected) } @@ -309,12 +306,10 @@ impl State { pub(crate) fn value_matches_type(&self, value: WasmValue, expected: WasmType) -> bool { match (value, expected) { (WasmValue::Ref(RefValue::Null), WasmType::Ref(expected)) => expected.is_nullable(), - (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => { - self.funcs.get(func.addr() as usize).is_some_and(|func| { - let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); - self.ref_type_is_subtype(actual, expected) - }) - } + (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => self + .funcs + .get(func.addr() as usize) + .is_some_and(|func| self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected)), (WasmValue::Ref(RefValue::Any(_)), WasmType::Ref(expected)) if expected.is_func() || expected.is_extern() || expected.is_exn() => { diff --git a/crates/tinywasm/src/store/types.rs b/crates/tinywasm/src/store/types.rs index 4954bba..e9fa6d1 100644 --- a/crates/tinywasm/src/store/types.rs +++ b/crates/tinywasm/src/store/types.rs @@ -6,7 +6,7 @@ use super::Store; pub(crate) fn canonicalize_ref_type(ty: RefType, type_addrs: &[TypeAddr]) -> RefType { let Some(type_addr) = ty.type_index() else { return ty }; let canonical = *type_addrs.get(type_addr as usize).expect("validated type address should exist"); - RefType::new_concrete(ty.is_nullable(), canonical).expect("canonical type addresses fit in references") + RefType::new_concrete(ty.is_nullable(), canonical) } pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) -> WasmType { @@ -18,12 +18,10 @@ pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) -> fn map_value_type(ty: WasmType, resolve: &mut impl FnMut(TypeAddr) -> TypeAddr) -> WasmType { match ty { - WasmType::Ref(ty) if ty.is_concrete() => { - let addr = resolve(ty.type_index().expect("concrete reference has a type index")); - WasmType::Ref( - RefType::new_concrete(ty.is_nullable(), addr).expect("canonical type addresses fit in references"), - ) - } + WasmType::Ref(ty) if ty.is_concrete() => WasmType::Ref(RefType::new_concrete( + ty.is_nullable(), + resolve(ty.type_index().expect("concrete reference has a type index")), + )), ty => ty, } } diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index 128f1ed..38a85ef 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -155,7 +155,7 @@ fn imported_host_functions_resolve_concrete_types() -> Result<(), Box Variable Instructions // See - GlobalGet32(GlobalAddr), LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), GlobalSet32(GlobalAddr), - GlobalGet64(GlobalAddr), LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), GlobalSet64(GlobalAddr), - GlobalGet128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), GlobalSet128(GlobalAddr), + GlobalGet32(GlobalAddr), GlobalSet32(GlobalAddr), GlobalTee32(GlobalAddr), LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), + GlobalGet64(GlobalAddr), GlobalSet64(GlobalAddr), GlobalTee64(GlobalAddr), LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), + GlobalGet128(GlobalAddr), GlobalSet128(GlobalAddr), GlobalTee128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), // > Memory Instructions I32Load(MemoryArg), diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index 884d330..9ed5df1 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -73,12 +73,9 @@ impl RefType { } #[inline] - pub const fn new_concrete(nullable: bool, type_index: u32) -> Option { - if type_index <= Self::PAYLOAD_MASK { - Some(Self(((nullable as u32) << 31) | Self::CONCRETE | type_index)) - } else { - None - } + pub const fn new_concrete(nullable: bool, type_index: u32) -> Self { + assert!(type_index <= Self::PAYLOAD_MASK, "type index is too large for a reference type"); + Self(((nullable as u32) << 31) | Self::CONCRETE | type_index) } #[inline] @@ -193,7 +190,7 @@ impl ExternRef { #[inline] pub const fn try_new(addr: u32) -> Option { match encode_host_ref(addr) { - Some(raw) => Some(Self(raw)), + Some(encoded) => Some(Self(encoded)), None => None, } } @@ -251,7 +248,7 @@ impl AnyRef { #[inline] pub const fn from_host(addr: u32) -> Option { match encode_host_ref(addr) { - Some(raw) => Some(Self(raw)), + Some(encoded) => Some(Self(encoded)), None => None, } } diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs index f0a576b..5049ba2 100644 --- a/crates/types/src/value.rs +++ b/crates/types/src/value.rs @@ -81,7 +81,7 @@ mod tests { #[test] fn concrete_references_require_store_type_information() { - let concrete = WasmType::Ref(RefType::new_concrete(false, 0).unwrap()); + let concrete = WasmType::Ref(RefType::new_concrete(false, 0)); assert!(!WasmValue::from(FuncRef::new(0)).matches_type(concrete)); assert!(!WasmValue::from(AnyRef::from_host(0).unwrap()).matches_type(concrete)); diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index 0ae646c..b338bd2 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -22,6 +22,10 @@ path = "src/print.rs" name = "tinywasm" path = "src/tinywasm.rs" +[[bin]] +name = "tinywasm_precompiled" +path = "src/tinywasm_precompiled.rs" + [[bin]] name = "tinywasm_no_std" path = "src/tinywasm_no_std.rs" @@ -39,8 +43,7 @@ argon2 = { version = "0.5" } dlmalloc = { version = "0.2", features = ["global"] } tinywasm = { path = "../../crates/tinywasm", default-features = false, features = [ "archive", - "parser", - "validate" + "parser" ] } [features] diff --git a/examples/rust/build.sh b/examples/rust/build.sh index db4cb43..b2a6149 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash cd "$(dirname "$0")" || exit -bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "argon2id") -exclude_wat=("tinywasm") +bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "tinywasm_precompiled" "argon2id") +exclude_wat=("tinywasm" "tinywasm_precompiled") out_dir="./target/wasm32-unknown-unknown/wasm" dest_dir="out" @@ -13,8 +13,9 @@ wasmopt_features="--enable-simd --enable-relaxed-simd --enable-tail-call --enabl mkdir -p "$dest_dir" # build no_std -cargo build --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features +RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features cp "$out_dir/tinywasm_no_std.wasm" "$dest_dir/" +wasm-opt "$dest_dir/tinywasm_no_std.wasm" -o "$dest_dir/tinywasm_no_std.opt.wasm" -O3 $wasmopt_features for bin in "${bins[@]}"; do RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=std,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin "$bin" diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm new file mode 100644 index 0000000..f0fa9a8 Binary files /dev/null and b/examples/rust/src/print.twasm differ diff --git a/examples/rust/src/tinywasm_no_std.rs b/examples/rust/src/tinywasm_no_std.rs index cbf10f4..a70abb9 100644 --- a/examples/rust/src/tinywasm_no_std.rs +++ b/examples/rust/src/tinywasm_no_std.rs @@ -1,7 +1,7 @@ #![no_main] #![no_std] use dlmalloc::GlobalDlmalloc; -use tinywasm::{FuncContext, HostFunction, ModuleInstance}; +use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance}; extern crate alloc; @@ -28,9 +28,7 @@ fn run() -> tinywasm::Result<()> { let mut store = tinywasm::Store::default(); let mut imports = tinywasm::Imports::new(); - let res = tinywasm::parser::Parser::default().parse_module_bytes(include_bytes!("./print.wasm"))?; - let twasm = res.serialize_twasm()?; - let module = tinywasm::parse_bytes(&twasm)?; + let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?; let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { unsafe { printi32(v) } diff --git a/examples/rust/src/tinywasm_precompiled.rs b/examples/rust/src/tinywasm_precompiled.rs new file mode 100644 index 0000000..bc0e0c1 --- /dev/null +++ b/examples/rust/src/tinywasm_precompiled.rs @@ -0,0 +1,30 @@ +#![no_main] +use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance}; + +#[link(wasm_import_module = "env")] +unsafe extern "C" { + fn printi32(x: i32); +} + +#[unsafe(no_mangle)] +pub extern "C" fn hello() { + let _ = run(); +} + +fn run() -> tinywasm::Result<()> { + let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?; + let mut store = tinywasm::Store::default(); + + let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { + unsafe { printi32(v) } + Ok(()) + }); + + let mut imports = tinywasm::Imports::new(); + imports.define("env", "printi32", printi32); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?; + add_and_print.call(&mut store, (1, 2))?; + Ok(()) +} diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs index 672b290..b3398f8 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -35,6 +35,8 @@ fn main() -> Result<()> { println!(" host_fn"); println!(" fibonacci - calculate fibonacci(30)"); println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); + println!(" tinywasm_precompiled - run a precompiled module inside of tinywasm"); + println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); println!(" argon2id - run argon2id(1000, 2, 1)"); return Ok(()); } @@ -44,6 +46,7 @@ fn main() -> Result<()> { "printi32" => printi32()?, "fibonacci" => fibonacci()?, "tinywasm" => tinywasm()?, + "tinywasm_precompiled" => tinywasm_precompiled()?, "tinywasm_no_std" => tinywasm_no_std()?, "argon2id" => argon2id()?, "host_fn" => host_fn()?, @@ -57,6 +60,8 @@ fn main() -> Result<()> { fibonacci()?; println!("\ntinywasm.wasm:"); tinywasm()?; + println!("\ntinywasm_precompiled.wasm:"); + tinywasm_precompiled()?; println!("\ntinywasm_no_std.wasm:"); tinywasm_no_std()?; println!("argon2id.wasm:"); @@ -100,6 +105,21 @@ fn tinywasm_no_std() -> Result<()> { Ok(()) } +fn tinywasm_precompiled() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/tinywasm_precompiled.opt.wasm")?; + let mut store = Store::default(); + + let mut imports = Imports::new(); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; + + let hello = instance.func::<(), ()>(&store, "hello")?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + Ok(()) +} + fn hello() -> Result<()> { let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?; let mut store = Store::default(); @@ -211,6 +231,11 @@ mod tests { tinywasm().unwrap(); } + #[test] + fn test_tinywasm_precompiled() { + tinywasm_precompiled().unwrap(); + } + #[test] fn test_tinywasm_no_std() { tinywasm_no_std().unwrap(); -- cgit v1.3.1 From 951c8070169e8bd970940029156f305e741aecdb Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Sun, 23 Aug 2026 13:40:38 +0200 Subject: chore: remove LinearMemory trait (#53) Signed-off-by: Henry --- ARCHITECTURE.md | 23 +- CHANGELOG.md | 10 +- Cargo.lock | 28 +- Cargo.toml | 12 +- README.md | 2 +- benches/memory_backends.rs | 151 ----------- crates/cli/src/engine_flags.rs | 36 +-- crates/parser/src/conversion.rs | 19 +- crates/parser/src/error.rs | 2 +- crates/parser/src/lib.rs | 39 +-- crates/parser/src/module.rs | 47 +--- crates/parser/src/parallel.rs | 31 +-- crates/parser/src/visit.rs | 2 +- crates/tinywasm/src/engine.rs | 58 ++-- crates/tinywasm/src/instance.rs | 27 +- crates/tinywasm/src/interpreter/executor.rs | 107 ++++---- crates/tinywasm/src/lib.rs | 7 +- crates/tinywasm/src/reference.rs | 50 ++-- crates/tinywasm/src/store/memory/instance.rs | 138 +++------- crates/tinywasm/src/store/memory/lazy.rs | 114 -------- crates/tinywasm/src/store/memory/mod.rs | 390 ++------------------------- crates/tinywasm/src/store/memory/paged.rs | 368 ------------------------- crates/tinywasm/src/store/memory/vec.rs | 185 +++++-------- crates/tinywasm/src/store/mod.rs | 80 +++++- crates/tinywasm/src/store/table.rs | 41 ++- crates/tinywasm/tests/internal_refs.rs | 2 +- crates/tinywasm/tests/memory.rs | 198 ++++++++++++++ crates/tinywasm/tests/memory_backends.rs | 307 --------------------- crates/types/src/instructions.rs | 83 ------ crates/types/src/lib.rs | 27 +- examples/rust/Cargo.toml | 14 +- examples/rust/build.sh | 4 +- examples/rust/src/hello.rs | 12 +- examples/rust/src/print.rs | 4 +- examples/rust/src/print.twasm | Bin 154 -> 154 bytes examples/rust/src/tinywasm_precompiled.rs | 30 --- examples/wasm-rust.rs | 24 -- 37 files changed, 663 insertions(+), 2009 deletions(-) delete mode 100644 benches/memory_backends.rs delete mode 100644 crates/tinywasm/src/store/memory/lazy.rs delete mode 100644 crates/tinywasm/src/store/memory/paged.rs create mode 100644 crates/tinywasm/tests/memory.rs delete mode 100644 crates/tinywasm/tests/memory_backends.rs delete mode 100644 examples/rust/src/tinywasm_precompiled.rs (limited to 'examples/rust/src') diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 9405d38..62fa503 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,6 +1,6 @@ # TinyWasm Architecture -TinyWasm follows the general runtime model described in the [WebAssembly specification](https://webassembly.github.io/spec/core/exec/runtime.html). It is a stack-based interpreter with a compact internal bytecode, width-specific value stacks, and configurable linear-memory backends. +TinyWasm follows the general runtime model described in the [WebAssembly specification](https://webassembly.github.io/spec/core/exec/runtime.html). It is a stack-based interpreter with a compact internal bytecode, width-specific value stacks, and a contiguous `Vec`-backed linear memory. ## Execution Pipeline @@ -40,29 +40,20 @@ The default runtime remains safe Rust throughout rather than relying on unchecke SIMD instructions have a portable safe-Rust implementation built from fixed-size arrays and lane operations, relying on the compiler to auto-vectorize where possible. Generated code is inspected with `cargo asm`, and benchmarks determine where architecture-specific alternatives are worthwhile. WebAssembly targets use native SIMD intrinsics where available, while the optional `simd-x86` feature provides selected x86 implementations for operations where the generic code produces worse results. -## Memory Backends +## Linear Memory -Linear memory is implemented through the `LinearMemory` trait. The backend is selected with `engine::Config::with_memory_backend()`. +Linear memory is a contiguous `Vec` allocation owned by a `MemoryInstance`. The interpreter accesses it through the internal `MemoryStorage` type, a small concrete boundary that keeps the `Vec` representation out of the executor so an mmap-backed storage can be substituted later without touching load and store paths. -`LinearMemory` exposes separate fixed-width read and write methods for 8-, 16-, 32-, 64-, and 128-bit accesses. A const-generic method would not be callable through a `dyn LinearMemory` trait object, so each width is an explicit vtable entry that backends can optimize independently. +Fixed-width loads and stores use a single const-generic `read_fixed::` / `write_fixed::` pair rather than per-width vtable methods. Scalar operations reduce to an effective-address computation, a bounds check, a slice access, and a `from_le_bytes` / `to_le_bytes` conversion, with out-of-bounds construction kept on cold paths. Bulk operations such as `fill` and `copy_within` map directly to native slice methods. -This flexibility has a measurable cost: guest loads and stores cross the `dyn LinearMemory` boundary, adding an indirect call and generally preventing the backend operation from being inlined into the interpreter. The fixed-width methods keep the work behind that boundary as small and specialized as possible. +Memory growth keeps the Wasm page count and limits on `MemoryInstance`. Before memory or table backing storage is allocated or resized, the configured `ResourceLimiter` is consulted so a host can bound guest resource consumption. The limiter is shared across the stores created from one `Engine` and lives behind an `Arc`. -Available backends: - -- `VecMemory` - contiguous `Vec` backing and the default backend. -- `PagedMemory` - sparse chunk-based allocation, with untouched chunks left unallocated and growth avoiding relocation of one contiguous buffer. -- `LazyLinearMemory` - serves zero-filled reads without allocation and creates the configured backend on the first mutation or growth. -- Custom backends through `MemoryBackend::custom()`. - -`VecMemory` growth may reallocate, though operating-system allocators can often grow page-backed allocations without copying the full buffer. Applications on conventional operating systems should generally keep it unless sparse allocation or non-relocating growth is specifically needed. Bounded dynamic stacks and sparse paged memory trade some runtime overhead for a smaller initial footprint on embedded and other resource-constrained systems. +For conventional operating systems, a future mmap-backed storage could reserve virtual address space and use guard pages to move more bounds enforcement to the operating system, reducing explicit checks in linear-memory hot paths. This is the same broad approach described in [Wasmtime's linear-memory architecture](https://docs.wasmtime.dev/contributing-architecture.html#linear-memory), where virtual-memory reservations and guard regions eliminate or deduplicate explicit bounds checks. ## Future Experiments Future work may explore additional dispatch and code-generation strategies, including Rust's experimental `loop_match` state-machine work, a tail-call-based interpreter once Rust's explicit tail-call support matures, more aggressive superinstruction fusion, top-of-stack register allocation, or optional JIT compilation. -For conventional operating systems, a future `mmap`-based memory backend could reserve virtual address space and use guard pages to move more bounds enforcement to the operating system, reducing explicit checks in linear-memory hot paths. This is the same broad approach described in [Wasmtime's linear-memory architecture](https://docs.wasmtime.dev/contributing-architecture.html#linear-memory), where virtual-memory reservations and guard regions eliminate or deduplicate explicit bounds checks. - ## Important Modules - [visit.rs](./crates/parser/src/visit.rs) - function-body operator lowering @@ -71,4 +62,4 @@ For conventional operating systems, a future `mmap`-based memory backend could r - [instructions.rs](./crates/types/src/instructions.rs) - internal instruction set - [value_stack.rs](./crates/tinywasm/src/interpreter/stack/value_stack.rs) - width-specific stacks - [call_stack.rs](./crates/tinywasm/src/interpreter/stack/call_stack.rs) - call frame stack -- [memory/mod.rs](./crates/tinywasm/src/store/memory/mod.rs) - memory backend trait and implementations +- [memory/mod.rs](./crates/tinywasm/src/store/memory/mod.rs) - linear memory storage diff --git a/CHANGELOG.md b/CHANGELOG.md index 701fc84..c6c8ff7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. - Added optional parse-time operand deduplication to reduce precompiled module and `.twasm` archive size. +- Added a `ResourceLimiter` trait, configurable through `engine::Config::with_resource_limiter`, to bound guest memory and table allocation and growth. ### Changed @@ -25,14 +26,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Typed function tuples now support up to 20 parameters or results. `WasmTupleChain` is deprecated. Use untyped functions for larger signatures. - Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`. - Globals are stored in separate 32-bit, 64-bit, and 128-bit value lanes, avoiding tagged value conversion during guest execution. -- `LinearMemory` mutation methods and custom memory-backend factories now return `Trap` errors so lazy backend failures can be propagated. +- Linear memory now uses a single contiguous `Vec`-backed storage with const-generic fixed-width loads and stores. +- Increased the minimum supported Rust version from 1.95 to 1.98. ### Fixed - Directly defined imports now reject handles from a different `Store`. - Tail calls to host functions now return directly to the caller frame. - Fixed Memory64 bulk-memory operations and optimized stores using the wrong value-stack lane. -- Fixed `memory.init` bounds checks, operand lowering, and local-memory allocation analysis. +- Fixed `memory.init` bounds checks and operand lowering. - Fixed Memory64 default limits and host-size handling, including 32-bit targets. ### Breaking Changes @@ -44,6 +46,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Renamed `ModuleInstanceAddr` to `ModuleInstanceId`. - Removed `HostFunction::ty` and `WasmFunction::ty`. Use `Function::ty(&Store)` for runtime function types. - Changed `TableType::element_type` and `Element::ty` from `WasmType` to `RefType`, and replaced module `table_types` with `TableDefinition { ty, init }`. +- Removed the pluggable memory backend system (`LinearMemory`, `MemoryBackend`, `VecMemory`, `PagedMemory`, `LazyLinearMemory`, and `Config::with_memory_backend`). Linear memory is always `Vec`-backed. To limit initial memory allocation and growth, configure a `ResourceLimiter` with `Config::with_resource_limiter`. +- Removed the local-memory allocation analysis (`LocalMemoryAllocation` and `ParserOptions::optimize_local_memory_allocation`). Local memories are always allocated eagerly. +- Removed `Config::with_trap_on_oom`. A `ResourceLimiter` can return a trap when rejecting a memory or table allocation or growth request. +- `Table::grow` now returns `Result>`, matching `Memory::grow`. Growth limits and allocation failures return `None`, while limiter-provided traps return an error. ## [0.10.0] - 2026-07-24 diff --git a/Cargo.lock b/Cargo.lock index 3c13501..ac0895a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,9 +134,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.4.3" +version = "1.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" +checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" dependencies = [ "find-msvc-tools", "shlex", @@ -312,9 +312,9 @@ checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" [[package]] name = "either" -version = "1.17.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" [[package]] name = "embedded-io" @@ -511,9 +511,9 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "log" -version = "0.4.33" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "memchr" @@ -962,9 +962,9 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.256.0" +version = "0.257.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec1492381bfd5ea51c2a99a919b676662559925cb8d7490547ec2e14c1ad3eb1" +checksum = "7d8ad9f0a39050867bda22e6486c316e2e52d20a42154d5bc433934bf738d085" dependencies = [ "leb128fmt", "wasmparser", @@ -982,9 +982,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.256.0" +version = "0.257.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60bd825ffedc6cba8a642924ba7ae424afbc47811cffbcb7b92031ec24e59b4c" +checksum = "d92fc335fb6d48f46bda1d8b26b69e28320c15ac3272208333833d6e217e2b4a" dependencies = [ "bitflags", "indexmap", @@ -993,9 +993,9 @@ dependencies = [ [[package]] name = "wast" -version = "256.0.0" +version = "257.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3ad42723fc9222da007f05812a3249c9a4ee7af79d497fc2a2079579ad7efe6" +checksum = "3c416ee8044cf88c5280e3d87c322b009525eb25142cf7428f0a90ea88febc3b" dependencies = [ "bumpalo", "leb128fmt", @@ -1006,9 +1006,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.256.0" +version = "1.257.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37cc86c54d8011b3202e265bfebada440733ea3a788ffaf46d395f7d2fdeacfb" +checksum = "672e5495f00c5fc6c6b502205bae4708aa4dd13d969754438743afe0a8af0f1d" dependencies = [ "wast", ] diff --git a/Cargo.toml b/Cargo.toml index 7ea5181..764ae53 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ default-members = [".", "crates/parser", "crates/tinywasm", "crates/types"] [workspace.package] version = "0.11.0-pre.0" edition = "2024" -rust-version = "1.95" +rust-version = "1.98" repository = "https://github.com/explodingcamera/tinywasm" license = "MIT OR Apache-2.0" keywords = ["interpreter", "no-std", "tinywasm", "wasm", "webassembly"] @@ -31,9 +31,9 @@ pretty_env_logger = "0.5" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } wasm-testsuite = { version = "0.7" } -wasmparser = { version = "0.256", default-features = false } -wast = "256" -wat = "1.256" +wasmparser = { version = "0.257", default-features = false } +wast = "257" +wat = "1.257" criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support", "rayon"] } @@ -57,10 +57,6 @@ name = "tinywasm" harness = false name = "tinywasm_modes" -[[bench]] -harness = false -name = "memory_backends" - [dev-dependencies] anyhow.workspace = true criterion.workspace = true diff --git a/README.md b/README.md index 3d3bc4c..7f27ea4 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ TinyWasm modules can be compiled to the internal `twasm` bytecode format, which With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`[^libm], making it usable in `no_std + alloc` environments. -Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, memory backend selection, the GC collection threshold, or trap-on-OOM behavior. +Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, or the GC collection threshold. A `ResourceLimiter` attached to the engine's config bounds guest memory and table allocation and growth and can trap rejected requests. [^libm]: [rust-lang/rust#137578](https://github.com/rust-lang/rust/issues/137578) — tracking issue for floating-point math support in `no_std`. diff --git a/benches/memory_backends.rs b/benches/memory_backends.rs deleted file mode 100644 index d7b8703..0000000 --- a/benches/memory_backends.rs +++ /dev/null @@ -1,151 +0,0 @@ -use criterion::measurement::WallTime; -use criterion::{BatchSize, BenchmarkGroup, BenchmarkId, Criterion, criterion_group, criterion_main}; -use std::hint::black_box; -use tinywasm::{LinearMemory, PagedMemory, VecMemory}; - -const PAGE_SIZE: usize = 64 * 1024; -const CHUNK_SIZE: usize = 4 * 1024; -const GROW_STEPS: usize = 32; -const BENCH_MEASUREMENT_TIME: std::time::Duration = std::time::Duration::from_secs(10); - -const MEMORY_LEN: usize = PAGE_SIZE * 4; -const CONTIGUOUS_OFFSET: usize = 1024; -const CONTIGUOUS_LEN: usize = 2048; -const CROSS_CHUNK_OFFSET: usize = CHUNK_SIZE - 512; -const CROSS_CHUNK_LEN: usize = CHUNK_SIZE * 2; - -fn bench_grow(group: &mut BenchmarkGroup<'_, WallTime>, backend: &str, make_memory: F) -where - M: LinearMemory, - F: Fn() -> M + Copy, -{ - group.bench_function(BenchmarkId::new("grow", backend), |b| { - b.iter_batched( - make_memory, - |mut memory| { - for page_count in 2..=GROW_STEPS + 1 { - memory.grow_to(page_count * PAGE_SIZE).unwrap(); - } - black_box(memory.len()) - }, - BatchSize::SmallInput, - ) - }); -} - -fn bench_write_all( - group: &mut BenchmarkGroup<'_, WallTime>, - backend: &str, - workload: &str, - mut memory: M, - offset: usize, - len: usize, -) { - let src = vec![0xA5; len]; - group.bench_function(BenchmarkId::new(format!("write_all/{workload}"), backend), |b| { - b.iter(|| { - memory.write_all(offset, black_box(&src)).unwrap(); - black_box(memory.len()) - }) - }); -} - -fn bench_read_exact( - group: &mut BenchmarkGroup<'_, WallTime>, - backend: &str, - workload: &str, - mut memory: M, - offset: usize, - len: usize, -) { - let src = vec![0x5A; len]; - memory.write_all(offset, &src).unwrap(); - - let mut dst = vec![0; len]; - group.bench_function(BenchmarkId::new(format!("read_exact/{workload}"), backend), |b| { - b.iter(|| { - memory.read_exact(offset, black_box(&mut dst)).unwrap(); - black_box(&dst); - }) - }); -} - -fn criterion_benchmark(c: &mut Criterion) { - let mut group = c.benchmark_group("memory_backends"); - group.measurement_time(BENCH_MEASUREMENT_TIME); - - bench_grow(&mut group, "vec", || VecMemory::try_new(PAGE_SIZE).expect("bench memory should be constructible")); - bench_grow(&mut group, "paged", || { - PagedMemory::try_new(PAGE_SIZE, CHUNK_SIZE).expect("bench memory should be constructible") - }); - bench_write_all( - &mut group, - "vec", - "contiguous", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - bench_write_all( - &mut group, - "paged", - "contiguous", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - bench_read_exact( - &mut group, - "vec", - "contiguous", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - bench_read_exact( - &mut group, - "paged", - "contiguous", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - - bench_write_all( - &mut group, - "vec", - "cross_chunk", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - bench_write_all( - &mut group, - "paged", - "cross_chunk", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - bench_read_exact( - &mut group, - "vec", - "cross_chunk", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - bench_read_exact( - &mut group, - "paged", - "cross_chunk", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - - group.finish(); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/crates/cli/src/engine_flags.rs b/crates/cli/src/engine_flags.rs index 3d90847..edc56aa 100644 --- a/crates/cli/src/engine_flags.rs +++ b/crates/cli/src/engine_flags.rs @@ -1,4 +1,4 @@ -use anyhow::{Result, bail}; +use anyhow::Result; use clap::{Args, ValueEnum}; use tinywasm::{Engine, StackConfig, engine::FuelPolicy}; @@ -8,18 +8,6 @@ pub struct EngineFlags { #[arg(long, value_enum)] pub fuel_policy: Option, - /// Trap immediately on memory or stack allocation failure - #[arg(long)] - pub trap_on_oom: bool, - - /// Memory backend to use for instantiated memories - #[arg(long, value_enum)] - pub memory_backend: Option, - - /// Chunk size in bytes for the paged memory backend - #[arg(long, default_value_t = 64 * 1024)] - pub memory_page_chunk_size: usize, - /// Fixed value stack size for all value lanes #[arg(long, conflicts_with = "value_stack_dynamic")] pub value_stack_size: Option, @@ -43,12 +31,6 @@ pub enum FuelPolicyArg { Weighted, } -#[derive(Clone, Copy, ValueEnum)] -pub enum MemoryBackendArg { - Vec, - Paged, -} - #[derive(Clone)] pub struct StackSpec { initial: usize, @@ -86,18 +68,6 @@ impl EngineFlags { }); } - if let Some(memory_backend) = self.memory_backend { - config = config.with_memory_backend(match memory_backend { - MemoryBackendArg::Vec => tinywasm::MemoryBackend::vec(), - MemoryBackendArg::Paged => { - if self.memory_page_chunk_size == 0 { - bail!("--memory-page-chunk-size must be greater than zero"); - } - tinywasm::MemoryBackend::paged(self.memory_page_chunk_size) - } - }); - } - if let Some(value_stack_size) = self.value_stack_size { config = config.with_value_stack(StackConfig::fixed(value_stack_size)); } @@ -114,10 +84,6 @@ impl EngineFlags { config = config.with_call_stack(call_stack_dynamic.into_stack_config()); } - if self.trap_on_oom { - config = config.with_trap_on_oom(true); - } - Ok(Engine::new(config)) } } diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index b94ebe6..364bae8 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -151,29 +151,26 @@ pub(crate) fn convert_module_code( ty_idx: u32, options: &ParserOptions, ) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { - let locals_reader = func.get_locals_reader()?; - #[cfg(feature = "validate")] - let locals_position = locals_reader.original_position(); + let mut locals_reader = func.get_locals_reader()?; let signature = metadata.signature(ty_idx)?.clone(); let mut local_types = signature.params.clone(); #[cfg(feature = "validate")] let mut validator = validator; - #[cfg(feature = "validate")] - for (local_index, local) in locals_reader.into_iter().enumerate() { - let local = local?; + for _ in 0..locals_reader.get_count() { + #[cfg(feature = "validate")] + let position = locals_reader.original_position(); + let local = locals_reader.read()?; + #[cfg(feature = "validate")] if let Some(validator) = validator.as_mut() { - validator.define_locals(locals_position + local_index, local.0, local.1)?; + validator.define_locals(position, local.0, local.1)?; } extend_local_types(&mut local_types, local.0, local.1)?; } #[cfg(not(feature = "validate"))] - for local in locals_reader { - let local = local?; - extend_local_types(&mut local_types, local.0, local.1)?; - } + let _ = validator; // maps a local's address to the index in the type's locals array let mut local_addr_map = Vec::with_capacity(local_types.len()); diff --git a/crates/parser/src/error.rs b/crates/parser/src/error.rs index e4d8abd..892e27b 100644 --- a/crates/parser/src/error.rs +++ b/crates/parser/src/error.rs @@ -20,7 +20,7 @@ pub enum ParseError { /// The error message message: String, /// The offset in the module where the error occurred - offset: usize, + offset: u64, }, /// An invalid encoding was encountered InvalidEncoding(Encoding), diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 90e239b..262cc07 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -61,8 +61,6 @@ pub struct ParserOptions { /// Disable this only for trusted input. Parsing without validation may produce /// a module that violates runtime assumptions. pub validation: bool, - /// Whether to optimize local memory allocation by skipping allocation of unused local memories. - pub optimize_local_memory_allocation: bool, /// Whether to run the peephole rewrite optimizer. pub optimize_rewrite: bool, /// Whether to deduplicate immutable function operands while parsing. @@ -85,7 +83,6 @@ impl Default for ParserOptions { fn default() -> Self { Self { validation: cfg!(feature = "validate"), - optimize_local_memory_allocation: true, optimize_rewrite: true, deduplicate_operands: false, #[cfg(parallel_parser)] @@ -117,17 +114,6 @@ impl ParserOptions { self.validation } - /// Enable or disable the optimization that skips allocating unused local memories. - pub const fn with_local_memory_allocation_optimization(mut self, enabled: bool) -> Self { - self.optimize_local_memory_allocation = enabled; - self - } - - /// Returns whether unused local memory allocation optimization is enabled. - pub const fn optimize_local_memory_allocation(&self) -> bool { - self.optimize_local_memory_allocation - } - /// Enable or disable the peephole rewrite optimizer. pub const fn with_rewrite_optimization(mut self, enabled: bool) -> Self { self.optimize_rewrite = enabled; @@ -234,7 +220,7 @@ impl Parser { } reader.process_pending_functions(&self.options)?; - reader.into_module(&self.options) + reader.into_module() } #[cfg(feature = "std")] @@ -263,7 +249,7 @@ impl Parser { buffer.truncate(buffer.len() - buffer_offset); buffer_offset = 0; } - let read_bytes = Self::read_more(&mut stream, &mut buffer, hint as usize)?; + let read_bytes = Self::read_more(&mut stream, &mut buffer, hint)?; eof = read_bytes == 0; } wasmparser::Chunk::Parsed { consumed, payload } => { @@ -272,17 +258,12 @@ impl Parser { match payload { wasmparser::Payload::CodeSectionStart { count, range, size } => { - let defer = reader.begin_code_section( - count, - range.clone(), - size, - validator.as_mut(), - &self.options, - )?; + let defer = + reader.begin_code_section(count, range, size, validator.as_mut(), &self.options)?; #[cfg(parallel_parser)] if defer { - deferred_code_section = Some((count, range.end - size as usize, size as usize)); + deferred_code_section = Some((count, size as usize)); } #[cfg(not(parallel_parser))] @@ -298,21 +279,21 @@ impl Parser { buffer_offset += consumed; #[cfg(parallel_parser)] - if let Some((count, body_offset, section_size)) = deferred_code_section { + if let Some((count, section_size)) = deferred_code_section { while buffer.len() - buffer_offset < section_size { let remaining = section_size - (buffer.len() - buffer_offset); let read_bytes = Self::read_more(&mut stream, &mut buffer, remaining)?; if read_bytes == 0 { return Err(ParseError::ParseError { message: "unexpected end-of-file".into(), - offset: body_offset + buffer.len() - buffer_offset, + offset: parser.offset() + (buffer.len() - buffer_offset) as u64, }); } } let section_end = buffer_offset + section_size; let section_bytes = alloc::sync::Arc::<[u8]>::from(buffer[buffer_offset..section_end].to_vec()); - reader.queue_owned_code_section(count, body_offset, section_bytes, validator.as_mut())?; + reader.queue_owned_code_section(count, parser.offset(), section_bytes, validator.as_mut())?; parser.skip_section(); buffer_offset = section_end; continue; @@ -335,7 +316,7 @@ impl Parser { if reader.end_reached || eof { reader.process_pending_functions(&self.options)?; - return reader.into_module(&self.options); + return reader.into_module(); } } }; @@ -347,7 +328,7 @@ impl TryFrom> for Module { type Error = ParseError; fn try_from(reader: ModuleReader<'_>) -> Result { - reader.into_module(&ParserOptions::default()) + reader.into_module() } } diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 8138666..c076035 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -19,7 +19,6 @@ pub(crate) struct OptimizedFunctionCode { pub instructions: Vec, pub data: WasmFunctionData, pub locals: ValueCounts, - pub uses_local_memory: bool, } pub(crate) fn optimize_function_code( @@ -27,16 +26,11 @@ pub(crate) fn optimize_function_code( options: &ParserOptions, function_results: ValueCounts, self_func_addr: u32, - imported_memory_count: u32, ) -> Result { let optimized = optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; let data = code.data.finish(); - let uses_local_memory = optimized - .instructions - .iter() - .any(|instruction| instruction.memory_addr(&data).is_some_and(|memory| memory >= imported_memory_count)); - Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals, uses_local_memory }) + Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals }) } #[derive(Default)] @@ -65,7 +59,6 @@ pub(crate) struct ModuleReader<'a> { pub(crate) elements: Box<[Element]>, pub(crate) end_reached: bool, imported_func_count: usize, - imported_memory_count: u32, global_types: Vec, #[cfg(parallel_parser)] @@ -277,7 +270,6 @@ impl<'a> ModuleReader<'a> { } self.imported_func_count += 1; } - ImportKind::Memory(_) => self.imported_memory_count += 1, ImportKind::Global(ty) => self.global_types.push(ty.ty), ImportKind::Tag(tag) => { let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| { @@ -338,7 +330,7 @@ impl<'a> ModuleReader<'a> { pub(crate) fn begin_code_section( &mut self, count: u32, - range: Range, + range: Range, size: u32, validator: Option<&mut Validator>, options: &ParserOptions, @@ -411,7 +403,6 @@ impl<'a> ModuleReader<'a> { options, self.code_results[self.code.len()], (self.imported_func_count + self.code.len()) as u32, - self.imported_memory_count, )?); self.func_validator_allocations = func_validator_allocs; @@ -443,7 +434,7 @@ impl<'a> ModuleReader<'a> { pub(crate) fn queue_owned_code_section( &mut self, count: u32, - body_offset: usize, + body_offset: u64, section_bytes: Arc<[u8]>, validator: Option<&mut Validator>, ) -> Result<()> { @@ -455,6 +446,8 @@ impl<'a> ModuleReader<'a> { for _ in 0..count { let body_reader = reader.read_reader()?; let body_range = body_reader.range(); + let body_start = (body_range.start - body_offset) as usize; + let body_end = (body_range.end - body_offset) as usize; #[cfg(feature = "validate")] let func_to_validate = { let function = wasmparser::FunctionBody::new(body_reader); @@ -465,7 +458,7 @@ impl<'a> ModuleReader<'a> { self.queue_function( crate::parallel::FunctionBodyInput::Owned(crate::parallel::OwnedFunctionBody { section_bytes: section_bytes.clone(), - body_range: (body_range.start - body_offset)..(body_range.end - body_offset), + body_range: body_start..body_end, body_offset: body_range.start, }), func_to_validate, @@ -512,10 +505,8 @@ impl<'a> ModuleReader<'a> { }; let imported_func_count = self.imported_func_count; - let imported_memory_count = self.imported_memory_count; let metadata = self.translation_metadata(); - let code = - crate::parallel::process_pending(pending, metadata, options, imported_func_count, imported_memory_count)?; + let code = crate::parallel::process_pending(pending, metadata, options, imported_func_count)?; self.code.extend(code); Ok(()) } @@ -525,7 +516,7 @@ impl<'a> ModuleReader<'a> { Ok(()) } - pub(crate) fn into_module(self, options: &ParserOptions) -> Result { + pub(crate) fn into_module(self) -> Result { if !self.end_reached { return Err(ParseError::EndNotReached); } @@ -534,24 +525,6 @@ impl<'a> ModuleReader<'a> { return Err(ParseError::Other("Code and code type address count mismatch".to_string())); } - let import_mem_count = self.imported_memory_count; - let has_local_mem_export = - self.exports.iter().any(|export| export.kind == ExternalKind::Memory && export.index >= import_mem_count); - let has_active_data_segment_on_local_memory = self.data.iter().any(|data| match &data.kind { - DataKind::Active { mem, .. } => *mem >= import_mem_count, - DataKind::Passive => false, - }); - let optimize_local_memory_allocation = options.optimize_local_memory_allocation(); - let mut local_memory_allocation = if self.memory_types.is_empty() { - LocalMemoryAllocation::Skip - } else if !optimize_local_memory_allocation || has_active_data_segment_on_local_memory { - LocalMemoryAllocation::Eager - } else if has_local_mem_export { - LocalMemoryAllocation::Lazy - } else { - LocalMemoryAllocation::Skip - }; - let func_type_idxs = self .imports .iter() @@ -571,9 +544,6 @@ impl<'a> ModuleReader<'a> { let ty = self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing"); let params = ValueCounts::from_iter(ty.params()); - if code.uses_local_memory { - local_memory_allocation = LocalMemoryAllocation::Eager; - } Ok(Arc::new(WasmFunction { instructions: code.instructions.into_boxed_slice(), @@ -598,7 +568,6 @@ impl<'a> ModuleReader<'a> { elements: self.elements, memory_types: self.memory_types, tags: self.tags, - local_memory_allocation, } .into()) } diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs index e29b38f..9b96c7a 100644 --- a/crates/parser/src/parallel.rs +++ b/crates/parser/src/parallel.rs @@ -17,7 +17,7 @@ pub(crate) struct OwnedFunctionBody { // function jobs from that section. pub section_bytes: Arc<[u8]>, pub body_range: Range, - pub body_offset: usize, + pub body_offset: u64, } pub(crate) struct PendingFunction<'a> { @@ -61,7 +61,6 @@ fn process_function_job( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, - imported_memory_count: u32, validator_allocs: Option, reader_allocs: OperatorsReaderAllocations, ) -> Result<(OptimizedFunctionCode, Option, OperatorsReaderAllocations)> { @@ -83,13 +82,7 @@ fn process_function_job( } }; - let code = optimize_function_code( - code, - options, - job.results, - (imported_func_count + job.ordinal) as u32, - imported_memory_count, - )?; + let code = optimize_function_code(code, options, job.results, (imported_func_count + job.ordinal) as u32)?; Ok((code, validator_allocs, reader_allocs)) } @@ -99,7 +92,6 @@ fn process_chunk<'a>( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, - imported_memory_count: u32, ) -> Result> { let mut validator_allocs = None; let mut reader_allocs = OperatorsReaderAllocations::default(); @@ -107,15 +99,8 @@ fn process_chunk<'a>( let mut codes = Vec::with_capacity(jobs.size_hint().0); for job in jobs { - let (code, next_validator_allocs, next_reader_allocs) = process_function_job( - job, - metadata, - options, - imported_func_count, - imported_memory_count, - validator_allocs, - reader_allocs, - )?; + let (code, next_validator_allocs, next_reader_allocs) = + process_function_job(job, metadata, options, imported_func_count, validator_allocs, reader_allocs)?; codes.push(code); validator_allocs = next_validator_allocs; reader_allocs = next_reader_allocs; @@ -129,11 +114,10 @@ pub(crate) fn process_pending( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, - imported_memory_count: u32, ) -> Result> { let num_workers = worker_count(options, pending.len()); if num_workers == 1 { - return process_chunk(pending, metadata, options, imported_func_count, imported_memory_count); + return process_chunk(pending, metadata, options, imported_func_count); } let code_count = pending.len(); let chunk_size = pending.len().div_ceil(num_workers); @@ -151,10 +135,7 @@ pub(crate) fn process_pending( bytes += body_len(&job.body); chunk.push(job); } - handles - .push(scope.spawn(move || { - process_chunk(chunk, metadata, options, imported_func_count, imported_memory_count) - })); + handles.push(scope.spawn(move || process_chunk(chunk, metadata, options, imported_func_count))); } let mut codes = Vec::with_capacity(code_count); diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 8315fb5..f48e1cf 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -221,7 +221,7 @@ impl<'a> FunctionBuilder<'a> { struct ValidateThenVisit<'a, 'm> { validator: &'a mut FuncValidator, builder: &'a mut FunctionBuilder<'m>, - position: usize, + position: u64, } impl ModuleMetadata { diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs index 64ef6be..f1feae6 100644 --- a/crates/tinywasm/src/engine.rs +++ b/crates/tinywasm/src/engine.rs @@ -1,5 +1,6 @@ -/// Memory backend types and traits. -pub use crate::store::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory}; +use alloc::sync::Arc; + +use crate::ResourceLimiter; /// Global configuration for the WebAssembly interpreter /// @@ -88,21 +89,18 @@ impl StackConfig { /// /// ## Example /// ```rust -/// use tinywasm::engine::{Config, FuelPolicy, MemoryBackend, StackConfig}; +/// use tinywasm::engine::{Config, FuelPolicy, StackConfig}; /// /// let config = Config::new() /// .with_fuel_policy(FuelPolicy::Weighted) /// .with_value_stack_32(StackConfig::dynamic(1024, 36 * 1024)) /// .with_value_stack_64(StackConfig::dynamic(1024, 32 * 1024)) /// .with_value_stack_128(StackConfig::dynamic(256, 4 * 1024)) -/// .with_call_stack(StackConfig::dynamic(64, 1024)) -/// .with_memory_backend(MemoryBackend::paged(64 * 1024)) -/// .with_trap_on_oom(true); +/// .with_call_stack(StackConfig::dynamic(64, 1024)); /// /// assert!(matches!(config.fuel_policy(), FuelPolicy::Weighted)); /// ``` #[derive(Clone)] -#[cfg_attr(feature = "debug", derive(Debug))] #[non_exhaustive] pub struct Config { /// Configuration for the 32-bit value stack (i32, f32, ref values). @@ -118,11 +116,8 @@ pub struct Config { pub call_stack: StackConfig, /// Fuel accounting policy used by budgeted execution. Defaults to [`FuelPolicy::PerInstruction`]. pub fuel_policy: FuelPolicy, - /// Backend used for runtime memories. Defaults to [`MemoryBackend::vec`]. - pub memory_backend: MemoryBackend, - /// Whether memory and stack allocation failures should trap instead of degrading into normal operation failure modes. - /// Defaults to `false`. - pub trap_on_oom: bool, + /// Resource limiter shared across all stores created from this engine. Defaults to `None`. + pub resource_limiter: Option>, /// Initial number of GC heap bytes that triggers collection. /// Defaults to 1 MiB. pub gc_collection_threshold: usize, @@ -140,12 +135,6 @@ impl Config { self } - /// Set the backend used for runtime memories. - pub fn with_memory_backend(mut self, memory_backend: MemoryBackend) -> Self { - self.memory_backend = memory_backend; - self - } - /// Set the configuration used for the 32-bit value stack. pub fn with_value_stack_32(mut self, stack: StackConfig) -> Self { self.value_stack_32 = stack; @@ -178,9 +167,9 @@ impl Config { self } - /// Configure whether memory and stack allocation failures trap immediately. - pub fn with_trap_on_oom(mut self, trap_on_oom: bool) -> Self { - self.trap_on_oom = trap_on_oom; + /// Set the resource limiter shared across all stores created from this engine. + pub fn with_resource_limiter(mut self, limiter: Arc) -> Self { + self.resource_limiter = Some(limiter); self } @@ -194,15 +183,6 @@ impl Config { pub fn fuel_policy(&self) -> FuelPolicy { self.fuel_policy } - - /// Get the current memory backend - pub fn memory_backend(&self) -> &MemoryBackend { - &self.memory_backend - } - - pub(crate) const fn trap_on_oom(&self) -> bool { - self.trap_on_oom - } } impl Default for Config { @@ -213,9 +193,23 @@ impl Default for Config { value_stack_128: StackConfig::fixed(DEFAULT_VALUE_STACK_128_SIZE), call_stack: StackConfig::fixed(DEFAULT_MAX_CALL_STACK_SIZE), fuel_policy: FuelPolicy::default(), - memory_backend: MemoryBackend::default(), - trap_on_oom: false, + resource_limiter: None, gc_collection_threshold: 1024 * 1024, } } } + +#[cfg(feature = "debug")] +impl core::fmt::Debug for Config { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Config") + .field("value_stack_32", &self.value_stack_32) + .field("value_stack_64", &self.value_stack_64) + .field("value_stack_128", &self.value_stack_128) + .field("call_stack", &self.call_stack) + .field("fuel_policy", &self.fuel_policy) + .field("resource_limiter", &self.resource_limiter.is_some()) + .field("gc_collection_threshold", &self.gc_collection_threshold) + .finish() + } +} diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index f45b718..6700d53 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -85,6 +85,17 @@ impl ModuleInstance { *self.0.mem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid memory address: {addr}")) } + /// The resolved store address of the module's first memory, or `MemAddr::MAX` when the module + /// has none. + /// + /// The sentinel is never used in practice: validation guarantees a memory instruction can only + /// reference index 0 when the module declares a memory, so any read of the sentinel would trip + /// an out-of-bounds panic in the store lookup and surface a bug. + #[inline] + pub(crate) fn mem0_addr(&self) -> MemAddr { + self.0.mem_addrs.first().copied().unwrap_or(MemAddr::MAX) + } + /// resolve a data address to the global store address #[inline] pub(crate) fn resolve_data_addr(&self, addr: DataAddr) -> DataAddr { @@ -165,18 +176,10 @@ impl ModuleInstance { let imported_funcs = addrs.funcs.len(); addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs)); addrs.tags.extend(store.init_tags(&module.tags, &type_addrs)); - match module.local_memory_allocation { - LocalMemoryAllocation::Skip => { - #[cfg(feature = "guest-debug")] - addrs.memories.extend(store.init_memories(&module.memory_types, MemoryInstance::new_lazy)?); - } - LocalMemoryAllocation::Lazy => { - addrs.memories.extend(store.init_memories(&module.memory_types, MemoryInstance::new_lazy)?) - } - LocalMemoryAllocation::Eager => { - addrs.memories.extend(store.init_memories(&module.memory_types, MemoryInstance::new)?) - } - } + let limiter = store.engine.config().resource_limiter.clone(); + addrs + .memories + .extend(store.init_memories(&module.memory_types, |ty| MemoryInstance::new(ty, limiter.as_deref()))?); store.init_globals(&mut addrs.globals, &module.globals, &addrs.funcs, &type_addrs)?; addrs.tables.extend(store.init_tables(&module.tables, &addrs.globals, &addrs.funcs, &type_addrs)?); diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 9da4a7a..b203980 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -27,6 +27,7 @@ pub(crate) struct Executor<'store, const BUDGETED: bool> { module: ModuleInstance, store: &'store mut Store, call_stack_base: u32, + mem0: MemAddr, } impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { @@ -36,7 +37,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { .get_module_instance(wasm_func.owner) .unwrap_or_else(|| unreachable!("invalid module instance")) .clone(); - Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base } + let mem0 = module.mem0_addr(); + Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base, mem0 } + } + + /// Resolves a module-local memory index to its store address, caching the common memory-0 case. + #[inline(always)] + fn mem_addr(&self, idx: MemAddr) -> MemAddr { + if idx == 0 { self.mem0 } else { self.module.resolve_mem_addr(idx) } + } + + /// Switches the executor to another module, keeping the cached memory-0 address in sync. + #[inline] + fn set_module(&mut self, owner: ModuleInstanceId) { + self.module = + self.store.get_module_instance(owner).unwrap_or_else(|| unreachable!("invalid module instance")).clone(); + self.mem0 = self.module.mem0_addr(); } #[inline(always)] @@ -975,11 +991,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let wasm_func = self.store.state.get_wasm_func(self.cf.func_addr); self.func = wasm_func.func.clone(); if wasm_func.owner != self.module.id() { - self.module = self - .store - .get_module_instance(wasm_func.owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + self.set_module(wasm_func.owner); } } @@ -1038,11 +1050,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } self.cf = CallFrame::new(func_addr, locals_base, locals); if owner != self.module.id() { - self.module = self - .store - .get_module_instance(owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + self.set_module(owner); } Ok(()) @@ -1064,11 +1072,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } self.cf = CallFrame::new(func_addr, locals_base, locals); if owner != self.module.id() { - self.module = self - .store - .get_module_instance(owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + self.set_module(owner); } Ok(()) @@ -1277,7 +1281,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { value_local: u8, ) -> Result<(), Trap> { let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local)); - let mem_addr = self.module.resolve_mem_addr(memarg.mem_addr()); + let mem_addr = self.mem_addr(memarg.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let addr = if mem.is_64bit() { let base = u64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); @@ -1292,7 +1296,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { mem.effective_addr::(base as usize, memarg.offset())? }; let mem = self.store.state.get_mem_mut(mem_addr); - value.store_at(&mut *mem.inner, addr) + value.store_at(&mut mem.inner, addr) } #[inline(always)] @@ -1302,7 +1306,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { addr_local: u8, increment: impl FnOnce(T) -> T, ) -> Result<(), Trap> { - let mem_addr = self.module.resolve_mem_addr(memarg.mem_addr()); + let mem_addr = self.mem_addr(memarg.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let addr = if mem.is_64bit() { let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; @@ -1318,8 +1322,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }; let mem = self.store.state.get_mem_mut(mem_addr); - let value = cold_err!(T::load_at(&*mem.inner, addr))?; - increment(value).store_at(&mut *mem.inner, addr) + let value = cold_err!(T::load_at(&mem.inner, addr))?; + increment(value).store_at(&mut mem.inner, addr) } #[inline(always)] @@ -1334,12 +1338,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let lhs = T::stack_pop(&mut self.store.value_stack); let acc = T::stack_pop(&mut self.store.value_stack); let fma = acc + lhs * rhs; - let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); + let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); - fma.store_at(&mut *mem.inner, addr)?; + fma.store_at(&mut mem.inner, addr)?; Ok(()) } @@ -1349,7 +1353,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { memarg: CompactMemoryArg, addr_local: u8, ) -> Result { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(memarg.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(memarg.mem_addr())); let addr = if mem.is_64bit() { let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds { @@ -1362,7 +1366,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); mem.effective_addr::(base as usize, memarg.offset())? }; - cold_err!(T::load_at(&*mem.inner, addr)) + cold_err!(T::load_at(&mem.inner, addr)) } #[inline(always)] @@ -1638,7 +1642,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_memory_size(&mut self, addr: u32) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(addr)); + let mem = self.store.state.get_mem(self.mem_addr(addr)); match mem.is_64bit() { true => self.store.value_stack.push::(mem.page_count as i64), false => self.store.value_stack.push::(mem.page_count as i32), @@ -1646,14 +1650,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_memory_grow(&mut self, addr: u32) -> Result<(), Trap> { - let mem = self.store.state.get_mem_mut(self.module.resolve_mem_addr(addr)); - let is_64bit = mem.is_64bit(); + let mem_addr = self.mem_addr(addr); + let is_64bit = self.store.state.get_mem(mem_addr).is_64bit(); let pages_delta = match is_64bit { true => ::stack_pop(&mut self.store.value_stack), false => i64::from(::stack_pop(&mut self.store.value_stack)), }; + let limiter = self.store.engine.config().resource_limiter.as_deref(); - let size = mem.grow(pages_delta, self.store.engine.config().trap_on_oom())?.unwrap_or(-1); + let mem = self.store.state.get_mem_mut(mem_addr); + let size = mem.grow(pages_delta, limiter)?.unwrap_or(-1); match is_64bit { true => self.store.value_stack.push::(size)?, false => self.store.value_stack.push::(size as i32)?, @@ -1664,8 +1670,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_memory_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { let TwoU32 { first: dst_mem, second: src_mem } = index.get(&self.func.data); - let dst_mem_addr = self.module.resolve_mem_addr(dst_mem); - let src_mem_addr = self.module.resolve_mem_addr(src_mem); + let dst_mem_addr = self.mem_addr(dst_mem); + let src_mem_addr = self.mem_addr(src_mem); let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch(); let src_arch = self.store.state.get_mem(src_mem_addr).kind.arch(); let len_arch = @@ -1687,7 +1693,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_memory_fill(&mut self, addr: u32) -> Result<(), Trap> { - let mem_addr = self.module.resolve_mem_addr(addr); + let mem_addr = self.mem_addr(addr); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let size = self.store.value_stack.pop_memory_operand(arch)?; let val = i32::stack_pop(&mut self.store.value_stack); @@ -1697,7 +1703,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_memory_fill_const(&mut self, index: OperandIdx) -> Result<(), Trap> { let MemoryFillConstOp { memory: addr, byte: val, value: size } = index.get(&self.func.data); - let mem_addr = self.module.resolve_mem_addr(addr); + let mem_addr = self.mem_addr(addr); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let dst = self.store.value_stack.pop_memory_operand(arch)?; self.exec_memory_fill_impl(mem_addr, dst, val, size as u32 as usize) @@ -1706,7 +1712,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_memory_fill_impl(&mut self, mem_addr: MemAddr, dst: usize, val: u8, size: usize) -> Result<(), Trap> { let mem = self.store.state.get_mem_mut(mem_addr); let max = mem.inner.len(); - if mem.inner.fill(dst, size, val)?.is_none() { + if mem.inner.fill(dst, size, val).is_none() { return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max })); } Ok(()) @@ -1716,7 +1722,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let TwoU32 { first: data_index, second: mem_index } = index.get(&self.func.data); let size = u32::stack_pop(&mut self.store.value_stack) as usize; let offset = u32::stack_pop(&mut self.store.value_stack) as usize; - let mem_addr = self.module.resolve_mem_addr(mem_index); + let mem_addr = self.mem_addr(mem_index); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let dst = self.store.value_stack.pop_memory_operand(arch)?; @@ -1739,7 +1745,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return cold!(Err(Trap::MemoryOutOfBounds { offset: 0, len: 0, max: 0 })); }; - if mem.inner.write_all(dst, &data[offset..offset + size])?.is_none() { + if mem.inner.write_all(dst, &data[offset..offset + size]).is_none() { return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max: mem_len })); } Ok(()) @@ -1772,10 +1778,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { arg: MemoryLaneArg, ) -> Result<(), Trap> { let m = arg.memory_arg_idx.get(&self.func.data); - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; - let val = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + let val = cold_err!(LOAD::load_at(&mem.inner, addr))?; let offset = arg.lane as usize * LOAD_SIZE; let mut imm = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); imm[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); @@ -1790,10 +1796,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { let m = index.get(&self.func.data); - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; - let value = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + let value = cold_err!(LOAD::load_at(&mem.inner, addr))?; self.store.value_stack.push(cast(value)) } @@ -1804,12 +1810,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { val_bytes.copy_from_slice(&bytes[lane_offset..lane_offset + N]); let val = U::from_mem_bytes(val_bytes); let m = arg.memory_arg_idx.get(&self.func.data); - let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); + let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); - cold_err!(val.store_at(&mut *mem.inner, addr))?; + cold_err!(val.store_at(&mut mem.inner, addr))?; Ok(()) } @@ -1822,12 +1828,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let val = cast(val); let m = index.get(&self.func.data); - let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); + let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); - cold_err!(val.store_at(&mut *mem.inner, addr))?; + cold_err!(val.store_at(&mut mem.inner, addr))?; Ok(()) } @@ -1874,14 +1880,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let arch = self.store.state.get_table(table_addr).kind.arch(); let n = self.pop_table_operand(arch)?; let val = ::stack_pop(&mut self.store.value_stack); + let limiter = self.store.engine.config().resource_limiter.as_deref(); let table = self.store.state.get_table_mut(table_addr); let sz = table.size(); - let result = table.grow(n, val); - match (arch, result) { - (MemoryArch::I32, Ok(())) => self.store.value_stack.push(sz as i32), - (MemoryArch::I32, Err(_)) => self.store.value_stack.push(-1_i32), - (MemoryArch::I64, Ok(())) => self.store.value_stack.push(sz as i64), - (MemoryArch::I64, Err(_)) => self.store.value_stack.push(-1_i64), + let grew = table.grow(n, val, limiter)?; + match (arch, grew) { + (MemoryArch::I32, true) => self.store.value_stack.push(sz as i32), + (MemoryArch::I32, false) => self.store.value_stack.push(-1_i32), + (MemoryArch::I64, true) => self.store.value_stack.push(sz as i64), + (MemoryArch::I64, false) => self.store.value_stack.push(-1_i64), } } diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index e941430..bd80ef1 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -54,8 +54,9 @@ //! ``` //! //! For non-default runtime behavior, construct a [`Store`] with a custom [`Engine`] -//! and [`engine::Config`] to control stack sizing, fuel accounting, memory backends, -//! and trap-on-OOM behavior. +//! and [`engine::Config`] to control stack sizing and fuel accounting. A [`ResourceLimiter`] can be +//! attached to the engine configuration to bound memory and table allocation and growth for stores +//! created from that engine and to trap rejected requests. //! //! For more examples, see the [`examples`](https://github.com/explodingcamera/tinywasm/tree/main/examples) directory. //! @@ -129,7 +130,7 @@ use interpreter::InterpreterRuntime; /// Global configuration for the WebAssembly interpreter pub mod engine; -pub use engine::{Engine, LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, StackConfig, VecMemory}; +pub use engine::{Engine, StackConfig}; #[cfg(feature = "parser")] /// Re-export of [`tinywasm_parser`]. Requires `parser` feature. diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index f5d9c23..271e71c 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -122,7 +122,7 @@ impl crate::std::io::Read for MemoryCursor<'_> { impl crate::std::io::Write for MemoryCursor<'_> { fn write(&mut self, buf: &[u8]) -> crate::std::io::Result { let offset = self.offset()?; - let written = self.memory.inner.write(offset, buf).map_err(Error::from)?; + let written = self.memory.inner.write(offset, buf); self.advance(written)?; Ok(written) } @@ -163,7 +163,8 @@ impl Memory { /// Create a new memory in the given store. pub fn new(store: &mut Store, ty: MemoryType) -> Result { let addr = store.state.memories.len() as MemAddr; - store.state.memories.push(MemoryInstance::new(ty, &store.engine.config().memory_backend)?); + let limiter = store.engine.config().resource_limiter.clone(); + store.state.memories.push(MemoryInstance::new(ty, limiter.as_deref())?); Ok(Self(StoreItem::new(store.id(), addr))) } @@ -230,19 +231,18 @@ impl Memory { /// Reads up to `dst.len()` bytes from memory and returns the number of bytes read. /// - /// Depending on the configured backend, this may return fewer bytes than requested even when - /// more data is available. Use [`Self::read_exact`] or [`Self::read_vec`] when you need a full - /// range. + /// This returns fewer bytes than requested when the range extends past the end of memory. Use + /// [`Self::read_exact`] or [`Self::read_vec`] when you need a full range. pub fn read(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result { Ok(self.instance(store)?.inner.read(offset, dst)) } /// Writes up to `src.len()` bytes into memory and returns the number of bytes written. /// - /// Depending on the configured backend, this may return fewer bytes than requested even when - /// more space is available. Use [`Self::copy_from_slice`] when you need the full slice written. + /// This returns fewer bytes than requested when the range extends past the end of memory. Use + /// [`Self::copy_from_slice`] when you need the full slice written. pub fn write(&self, store: &mut Store, offset: usize, src: &[u8]) -> Result { - Ok(self.instance_mut(store)?.inner.write(offset, src)?) + Ok(self.instance_mut(store)?.inner.write(offset, src)) } /// Reads exactly `dst.len()` bytes from memory. @@ -263,9 +263,14 @@ impl Memory { }) } - /// Grow the memory by the given number of pages. + /// Grows the memory by the given number of pages. + /// + /// Returns the previous size, or `None` if growth fails or is rejected by the resource limiter. + /// A limiter-provided trap is returned as an error. pub fn grow(&self, store: &mut Store, delta_pages: i64) -> Result> { - self.instance_mut(store)?.grow(delta_pages, true).map_err(Into::into) + let limiter = store.engine.config().resource_limiter.clone(); + let mem = self.instance_mut(store)?; + mem.grow(delta_pages, limiter.as_deref()).map_err(Into::into) } /// Get the current size of the memory in pages. @@ -281,14 +286,14 @@ impl Memory { /// Fill a slice of memory with a value. pub fn fill(&self, store: &mut Store, offset: usize, len: usize, val: u8) -> Result<()> { - self.instance_mut(store)?.inner.fill(offset, len, val)?.ok_or_else(|| { + self.instance_mut(store)?.inner.fill(offset, len, val).ok_or_else(|| { Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() }) }) } /// Copies a full slice into memory. pub fn copy_from_slice(&self, store: &mut Store, offset: usize, data: &[u8]) -> Result<()> { - self.instance_mut(store)?.inner.write_all(offset, data)?.ok_or_else(|| { + self.instance_mut(store)?.inner.write_all(offset, data).ok_or_else(|| { Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len: data.len(), @@ -368,8 +373,9 @@ impl Table { return Err(Error::other("host tables cannot use module-relative concrete reference types")); } let init = table_value_to_element(&store.state, ty.element_type, init).map_err(Error::from)?; + let limiter = store.engine.config().resource_limiter.clone(); let addr = store.state.tables.len() as TableAddr; - store.state.tables.push(TableInstance::new(ty, init)?); + store.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); Ok(Self(StoreItem::new(store.id(), addr))) } @@ -430,15 +436,23 @@ impl Table { store.state.get_table_mut(self.0.addr).copy_within(dst, src, len) } - /// Grow the table and return the previous size. - pub fn grow(&self, store: &mut Store, delta: i32, init: WasmValue) -> Result { + /// Grows the table and returns the previous size. + /// + /// Returns `None` if growth fails or is rejected by the resource limiter. A limiter-provided + /// trap is returned as an error. + pub fn grow(&self, store: &mut Store, delta: i32, init: WasmValue) -> Result> { self.0.validate_store(store)?; let table = store.state.get_table(self.0.addr); let old_size = table.size(); let init = table_value_to_element(&store.state, table.kind.element_type, init)?; - let delta = usize::try_from(delta).map_err(|_| Trap::TableOutOfBounds { offset: 0, len: 1, max: old_size })?; - store.state.get_table_mut(self.0.addr).grow(delta, init)?; - Ok(old_size) + let Ok(delta) = usize::try_from(delta) else { + return Ok(None); + }; + let limiter = store.engine.config().resource_limiter.clone(); + match store.state.get_table_mut(self.0.addr).grow(delta, init, limiter.as_deref())? { + true => Ok(Some(old_size)), + false => Ok(None), + } } } diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs index 68a075b..a075d25 100644 --- a/crates/tinywasm/src/store/memory/instance.rs +++ b/crates/tinywasm/src/store/memory/instance.rs @@ -1,10 +1,8 @@ -use alloc::format; use tinywasm_types::{MemoryArch, MemoryType}; -use crate::{Error, MemoryBackend, Result, Trap}; +use crate::{Error, ResourceLimiter, Result, Trap}; use super::{MemoryStorage, memory_oob}; -use core::hint::cold_path; /// A WebAssembly Memory Instance /// @@ -23,25 +21,17 @@ impl core::fmt::Debug for MemoryInstance { } impl MemoryInstance { - const COPY_CHUNK_SIZE: usize = 4 * 1024; - + #[inline] fn host_size(kind: MemoryType, pages: u64) -> Result { - #[cfg(target_pointer_width = "64")] - { - pages - .checked_mul(kind.page_size()) - .map(|size| size as usize) - .ok_or(Error::UnsupportedFeature("memory size exceeds the host address space")) - } + let size = pages + .checked_mul(kind.page_size()) + .ok_or(Error::UnsupportedFeature("memory size exceeds the host address space"))?; + usize::try_from(size).map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space")) + } - #[cfg(not(target_pointer_width = "64"))] - { - let page_size = usize::try_from(kind.page_size()) - .map_err(|_| Error::UnsupportedFeature("memory page size exceeds the host address space"))?; - let pages = usize::try_from(pages) - .map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space"))?; - pages.checked_mul(page_size).ok_or(Error::UnsupportedFeature("memory size exceeds the host address space")) - } + #[inline] + fn maximum_size(kind: MemoryType) -> Option { + kind.page_count_max_declared().map(|pages| Self::host_size(kind, pages).unwrap_or(usize::MAX)) } #[inline(always)] @@ -67,7 +57,7 @@ impl MemoryInstance { } } - pub(crate) fn new(kind: MemoryType, backend: &MemoryBackend) -> Result { + pub(crate) fn new(kind: MemoryType, limiter: Option<&dyn ResourceLimiter>) -> Result { let initial_len = Self::host_size(kind, kind.page_count_initial())?; crate::log::debug!( @@ -76,27 +66,14 @@ impl MemoryInstance { kind.page_size() ); - let storage = backend.create(kind, initial_len)?; - if storage.len() != initial_len { - return Err(Error::Other(format!( - "memory backend returned {} bytes for a memory that requires {initial_len}", - storage.len() - ))); + if initial_len != 0 + && let Some(limiter) = limiter + && !limiter.memory_growing(0, initial_len, Self::maximum_size(kind))? + { + return cold!(Err(Trap::OutOfMemory.into())); } - Ok(Self { kind, inner: storage, page_count: kind.page_count_initial() as usize }) - } - - pub(crate) fn new_lazy(kind: MemoryType, backend: &MemoryBackend) -> Result { - let initial_len = Self::host_size(kind, kind.page_count_initial())?; - - crate::log::debug!( - "initializing lazy memory with {} pages of {} bytes", - kind.page_count_initial(), - kind.page_size() - ); - - let storage = backend.create_lazy(kind, initial_len)?; + let storage = MemoryStorage::try_new(initial_len)?; Ok(Self { kind, inner: storage, page_count: kind.page_count_initial() as usize }) } @@ -111,82 +88,49 @@ impl MemoryInstance { src: usize, len: usize, ) -> Result<(), Trap> { - fn check_range(mem: &MemoryStorage, addr: usize, len: usize) -> Result<(), crate::Trap> { - let Some(end) = addr.checked_add(len) else { - return cold!(Err(memory_oob(addr, len, mem.len()))); - }; - - if end > mem.len() || end < addr { - return cold!(Err(memory_oob(addr, len, mem.len()))); - } - Ok(()) - } - - check_range(&src_memory.inner, src, len)?; - check_range(&self.inner, dst, len)?; - - if len == 0 { - return Ok(()); - } - - let mut buf = [0u8; Self::COPY_CHUNK_SIZE]; - let mut copied = 0; - while copied < len { - let chunk_len = buf.len().min(len - copied); - src_memory.inner.read_exact(src + copied, &mut buf[..chunk_len]).ok_or_else(|| { - cold_path(); - memory_oob(src + copied, chunk_len, src_memory.inner.len()) - })?; - self.inner.write_all(dst + copied, &buf[..chunk_len])?.ok_or_else(|| { - cold_path(); - memory_oob(dst + copied, chunk_len, self.inner.len()) - })?; - copied += chunk_len; - } - + src_memory.inner.checked_range(src, len).ok_or_else(|| cold!(memory_oob(src, len, src_memory.inner.len())))?; + self.inner.checked_range(dst, len).ok_or_else(|| cold!(memory_oob(dst, len, self.inner.len())))?; + self.inner.copy_from(dst, &src_memory.inner, src, len); Ok(()) } pub(crate) fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result<(), Trap> { - self.inner.copy_within(dst, src, len)?.ok_or_else(|| { - cold_path(); - memory_oob(dst, len, self.inner.len()) - }) + self.inner.copy_within(dst, src, len).ok_or_else(|| cold!(memory_oob(dst, len, self.inner.len()))) } - pub(crate) fn grow(&mut self, pages_delta: i64, trap_on_oom: bool) -> Result, Trap> { - if pages_delta < 0 { - cold_path(); - crate::log::debug!("memory.grow failed: negative delta {}", pages_delta); - return Ok(None); - } - + pub(crate) fn grow( + &mut self, + pages_delta: i64, + limiter: Option<&dyn ResourceLimiter>, + ) -> Result, Trap> { let current_pages = self.page_count; - let Some(pages_delta) = usize::try_from(pages_delta).ok() else { - return Ok(None); - }; - let Some(new_pages) = current_pages.checked_add(pages_delta) else { - return Ok(None); + let Some(new_pages) = usize::try_from(pages_delta).ok().and_then(|delta| current_pages.checked_add(delta)) + else { + return cold!(Ok(None)); }; let max_pages = self.kind.page_count_max().try_into().unwrap_or(usize::MAX); if new_pages > max_pages { - cold_path(); - crate::log::debug!("memory.grow failed: new_pages={}, max_pages={}", new_pages, max_pages); - return Ok(None); + return cold!({ + crate::log::debug!("memory.grow failed: new_pages={}, max_pages={}", new_pages, max_pages); + Ok(None) + }); } let Ok(new_size) = Self::host_size(self.kind, new_pages as u64) else { - return Ok(None); + return cold!(Ok(None)); }; if new_size == self.inner.len() { return Ok(i64::try_from(current_pages).ok()); } - if let Err(err) = self.inner.grow_to(new_size) { - if trap_on_oom { - return Err(err); - } + if let Some(limiter) = limiter + && !limiter.memory_growing(self.inner.len(), new_size, Self::maximum_size(self.kind))? + { + return cold!(Ok(None)); + } + + if cold_err!(self.inner.grow_to(new_size)).is_err() { return Ok(None); } self.page_count = new_pages; diff --git a/crates/tinywasm/src/store/memory/lazy.rs b/crates/tinywasm/src/store/memory/lazy.rs deleted file mode 100644 index 780d5b5..0000000 --- a/crates/tinywasm/src/store/memory/lazy.rs +++ /dev/null @@ -1,114 +0,0 @@ -use alloc::boxed::Box; - -use tinywasm_types::MemoryType; - -use crate::{Error, MemoryBackend, Result}; - -use super::LinearMemory; - -/// A linear memory wrapper that allocates its backend on the first mutation. -/// -/// Before materialization, the memory is represented by its logical length and -/// reads return the zeroes required by WebAssembly semantics. -pub struct LazyLinearMemory { - ty: MemoryType, - initial_len: usize, - backend: MemoryBackend, - inner: Option>, -} - -impl LazyLinearMemory { - /// Creates a lazy memory for `ty` using `backend` for eventual storage. - pub fn try_new(ty: MemoryType, backend: MemoryBackend) -> Result { - let page_size = usize::try_from(ty.page_size()) - .map_err(|_| Error::UnsupportedFeature("memory page size exceeds the host address space"))?; - let pages = usize::try_from(ty.page_count_initial()) - .map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space"))?; - let initial_len = pages - .checked_mul(page_size) - .ok_or(Error::UnsupportedFeature("memory size exceeds the host address space"))?; - Ok(Self::new_with_initial_len(ty, initial_len, backend)) - } - - pub(crate) fn new_with_initial_len(ty: MemoryType, initial_len: usize, backend: MemoryBackend) -> Self { - Self { ty, initial_len, backend, inner: None } - } - - fn materialize(&mut self) -> core::result::Result<&mut dyn LinearMemory, crate::Trap> { - if self.inner.is_none() { - let storage = cold_err!(self.backend.create(self.ty, self.initial_len))?; - self.inner = Some(storage); - } - Ok(self.inner.as_deref_mut().expect("lazy memory should be materialized")) - } -} - -impl LinearMemory for LazyLinearMemory { - fn len(&self) -> usize { - self.inner.as_deref().map_or(self.initial_len, LinearMemory::len) - } - - fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> { - self.materialize()?.grow_to(new_len) - } - - fn read(&self, addr: usize, dst: &mut [u8]) -> usize { - if let Some(inner) = self.inner.as_deref() { - return inner.read(addr, dst); - } - if addr >= self.initial_len { - return 0; - } - let read_len = dst.len().min(self.initial_len - addr); - dst[..read_len].fill(0); - read_len - } - - fn write(&mut self, addr: usize, src: &[u8]) -> core::result::Result { - if src.is_empty() || addr >= self.len() { - return Ok(0); - } - self.materialize()?.write(addr, src) - } - - fn write_all(&mut self, addr: usize, src: &[u8]) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(src.len()) else { return Ok(None) }; - if end > self.len() { - return Ok(None); - } - if src.is_empty() { - return Ok(Some(())); - } - self.materialize()?.write_all(addr, src) - } - - fn fill(&mut self, addr: usize, len: usize, val: u8) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(len) else { return Ok(None) }; - if end > self.len() { - return Ok(None); - } - if len == 0 || val == 0 && self.inner.is_none() { - return Ok(Some(())); - } - self.materialize()?.fill(addr, len, val) - } - - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> core::result::Result, crate::Trap> { - let Some(src_end) = src.checked_add(len) else { return Ok(None) }; - let Some(dst_end) = dst.checked_add(len) else { return Ok(None) }; - if src_end > self.len() || dst_end > self.len() { - return Ok(None); - } - if self.inner.is_none() || len == 0 || dst == src { - return Ok(Some(())); - } - self.materialize()?.copy_within(dst, src, len) - } -} - -#[cfg(feature = "debug")] -impl core::fmt::Debug for LazyLinearMemory { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("LazyLinearMemory").field("ty", &self.ty).field("materialized", &self.inner.is_some()).finish() - } -} diff --git a/crates/tinywasm/src/store/memory/mod.rs b/crates/tinywasm/src/store/memory/mod.rs index 70ffb20..24f295b 100644 --- a/crates/tinywasm/src/store/memory/mod.rs +++ b/crates/tinywasm/src/store/memory/mod.rs @@ -1,372 +1,32 @@ -use alloc::{boxed::Box, sync::Arc}; -use alloc::{vec, vec::Vec}; -use core::cmp::min; -use core::hint::cold_path; - -use tinywasm_types::MemoryType; - -use crate::Result; use crate::interpreter::Value128; mod instance; -mod lazy; - -mod paged; -#[path = "vec.rs"] -mod vec_memory; +mod vec; pub(crate) use instance::MemoryInstance; -pub use {lazy::LazyLinearMemory, paged::PagedMemory, vec_memory::VecMemory}; +pub(crate) use vec::VecMemory; -/// Backend storage for a linear memory +/// Internal storage for a linear memory. /// -/// This is a low-level trait that abstracts over the actual storage mechanism for linear memory. -/// This will probably change in the future to allow more efficient implementations. -/// See [`MemoryBackend`] for a higher-level interface to configuring memory storage. -/// The runtime passes slices of the exact indicated width to the fixed-width `write_*` methods. -pub trait LinearMemory { - /// Returns the current memory length in bytes. - fn len(&self) -> usize; - - /// Returns true if the memory is empty. - fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Grows the memory to `new_len` bytes. - /// - /// The runtime only calls this with lengths that are exact multiples of the Wasm page size for - /// the owning memory. - fn grow_to(&mut self, new_len: usize) -> core::result::Result<(), crate::Trap>; - - /// Reads up to `dst.len()` bytes starting at `addr` and returns the number of bytes read. - /// - /// Backends may return fewer bytes than requested even when more data is available. This lets - /// non-contiguous backends stop at a natural boundary such as the end of a chunk. - fn read(&self, addr: usize, dst: &mut [u8]) -> usize; - - /// Writes up to `src.len()` bytes starting at `addr` and returns the number of bytes written. - /// - /// Backends may return fewer bytes than requested even when more space is available. This lets - /// non-contiguous backends stop at a natural boundary such as the end of a chunk. Backend - /// failures are returned as traps. - fn write(&mut self, addr: usize, src: &[u8]) -> core::result::Result; - - /// Writes all bytes in `src`, returns `Ok(None)` for an invalid range, or returns a backend trap. - fn write_all(&mut self, addr: usize, src: &[u8]) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(src.len()) else { - return cold!(Ok(None)); - }; - - if end > self.len() { - return cold!(Ok(None)); - } - - let mut offset = 0; - while offset < src.len() { - let written = self.write(addr + offset, &src[offset..])?; - if written == 0 { - return cold!(Ok(None)); - } - offset += written; - } - - Ok(Some(())) - } - - /// Fills the range `[addr, addr + len)` with `val`. - fn fill(&mut self, addr: usize, len: usize, val: u8) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(len) else { return Ok(None) }; - if end > self.len() { - return Ok(None); - } - - let chunk = [val; 1024]; - let mut offset = 0; - while offset < len { - let chunk_len = min(len - offset, 1024); - if self.write_all(addr + offset, &chunk[..chunk_len])?.is_none() { - return Ok(None); - } - offset += chunk_len; - } - - Ok(Some(())) - } - - /// Copies `len` bytes from `src` to `dst` within the same memory. - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> core::result::Result, crate::Trap> { - let Some(src_end) = src.checked_add(len) else { return Ok(None) }; - let Some(dst_end) = dst.checked_add(len) else { return Ok(None) }; - if src_end > self.len() || dst_end > self.len() { - return Ok(None); - } - - if len == 0 || dst == src { - return Ok(Some(())); - } - - let mut chunk = [0; 1024]; - - // If the source and destination ranges are disjoint, we can copy forward without a temporary buffer. - if dst < src || dst >= src_end { - let mut offset = 0; - while offset < len { - let chunk_len = min(len - offset, 1024); - if self.read_exact(src + offset, &mut chunk[..chunk_len]).is_none() - || self.write_all(dst + offset, &chunk[..chunk_len])?.is_none() - { - return Ok(None); - } - offset += chunk_len; - } - } else { - // Otherwise, we need to copy backward to avoid overwriting the source data before it's read. - let mut offset = len; - while offset > 0 { - let chunk_len = min(offset, 1024); - offset -= chunk_len; - if self.read_exact(src + offset, &mut chunk[..chunk_len]).is_none() - || self.write_all(dst + offset, &chunk[..chunk_len])?.is_none() - { - return Ok(None); - } - } - } - - Ok(Some(())) - } - - /// Reads exactly `dst.len()` bytes starting at `addr`. - fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> { - let Some(end) = addr.checked_add(dst.len()) else { - return cold!(None); - }; - - if end > self.len() { - return cold!(None); - } - - let mut offset = 0; - while offset < dst.len() { - let read = self.read(addr + offset, &mut dst[offset..]); - if read == 0 { - return cold!(None); - } - offset += read; - } - - Some(()) - } - - /// Reads `len` bytes starting at `addr` into a newly allocated buffer. - fn read_vec(&self, addr: usize, len: usize) -> Option> { - let end = addr.checked_add(len)?; - if end > self.len() { - return None; - } - - let mut data = vec![0; len]; - self.read_exact(addr, &mut data)?; - Some(data) - } - - /// Reads exactly 1 byte at `addr`. - fn read_8(&self, addr: usize) -> core::result::Result<[u8; 1], crate::Trap> { - let mut bytes = [0; 1]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 1, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 2 bytes at `addr`. - fn read_16(&self, addr: usize) -> core::result::Result<[u8; 2], crate::Trap> { - let mut bytes = [0; 2]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 2, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 4 bytes at `addr`. - fn read_32(&self, addr: usize) -> core::result::Result<[u8; 4], crate::Trap> { - let mut bytes = [0; 4]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 4, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 8 bytes at `addr`. - fn read_64(&self, addr: usize) -> core::result::Result<[u8; 8], crate::Trap> { - let mut bytes = [0; 8]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 8, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 16 bytes at `addr`. - fn read_128(&self, addr: usize) -> core::result::Result<[u8; 16], crate::Trap> { - let mut bytes = [0; 16]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 16, self.len()) - })?; - Ok(bytes) - } - - /// Writes exactly 1 byte at `addr`. - fn write_8(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 1, self.len()) - }) - } - - /// Writes exactly 2 bytes at `addr`. - fn write_16(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 2, self.len()) - }) - } - - /// Writes exactly 4 bytes at `addr`. - fn write_32(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 4, self.len()) - }) - } - - /// Writes exactly 8 bytes at `addr`. - fn write_64(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 8, self.len()) - }) - } - - /// Writes exactly 16 bytes at `addr`. - fn write_128(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 16, self.len()) - }) - } -} - -type MemoryFactory = dyn Fn(MemoryType) -> core::result::Result, crate::Trap> + Send + Sync; - -/// Configures how runtime memory instances are created. -#[derive(Clone, Default)] -pub struct MemoryBackend(MemoryBackendInner); - -#[derive(Clone, Default)] -enum MemoryBackendInner { - #[default] - Vec, - Paged { - chunk_size: usize, - }, - Custom(Arc), -} - -impl MemoryBackend { - /// Uses a contiguous [`VecMemory`] for each memory instance. - /// - /// This is usually the fastest option for reads and writes, but large grows can be expensive - /// because they may reallocate and copy the entire buffer. - pub const fn vec() -> Self { - Self(MemoryBackendInner::Vec) - } - - /// Uses sparse chunked storage for each memory instance. - /// - /// `chunk_size` is the backend chunk size in bytes. It must be a non-zero power - /// of two and is independent from the Wasm page size. - /// - /// This generally makes growth cheaper than [`Self::vec`], but read and write operations do a - /// little more work and may be slightly slower. - pub fn paged(chunk_size: usize) -> Self { - assert!(chunk_size.is_power_of_two(), "chunk_size must be a non-zero power of two"); - Self(MemoryBackendInner::Paged { chunk_size }) - } - - /// Uses a custom factory to create memory instances. - /// - /// Factory traps are returned during eager creation or when a lazy memory first materializes. - pub fn custom(factory: F) -> Self - where - F: Fn(MemoryType) -> core::result::Result + Send + Sync + 'static, - M: LinearMemory + 'static, - { - Self(MemoryBackendInner::Custom(Arc::new(move |ty| { - let memory = factory(ty)?; - Ok(Box::new(memory) as Box) - }))) - } - - pub(crate) fn create( - &self, - ty: MemoryType, - initial_len: usize, - ) -> core::result::Result { - let storage = match &self.0 { - MemoryBackendInner::Vec => Box::new(VecMemory::try_new(initial_len)?) as Box, - MemoryBackendInner::Paged { chunk_size } => { - Box::new(PagedMemory::try_new(initial_len, *chunk_size)?) as Box - } - MemoryBackendInner::Custom(factory) => factory(ty)?, - }; - - if storage.len() < initial_len { - return Err(crate::Trap::Other("memory backend returned less storage than required")); - } - - Ok(storage) - } - - pub(crate) fn create_lazy(&self, ty: MemoryType, initial_len: usize) -> Result { - Ok(Box::new(LazyLinearMemory::new_with_initial_len(ty, initial_len, self.clone()))) - } -} - -#[cfg(feature = "debug")] -impl core::fmt::Debug for MemoryBackend { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match &self.0 { - MemoryBackendInner::Vec => f.debug_tuple("MemoryBackend::Vec").finish(), - MemoryBackendInner::Paged { chunk_size } => { - f.debug_struct("MemoryBackend::Paged").field("chunk_size", chunk_size).finish() - } - MemoryBackendInner::Custom(_) => f.debug_tuple("MemoryBackend::Custom").finish(), - } - } -} - -pub(crate) type MemoryStorage = Box; +/// This is the boundary between the interpreter and the backing representation. Keeping it a +/// concrete type selected at compile time means the executor's load and store paths stay the same +/// whether the memory is `Vec`-backed or, later, mmap-backed. +pub(crate) type MemoryStorage = VecMemory; -/// A trait for types that can be converted to and from static byte arrays +/// A trait for types that can be converted to and from static byte arrays. pub(crate) trait MemValue: Copy + Default { - /// Store a value in memory + /// Store a value in memory. fn to_mem_bytes(self) -> [u8; N]; fn from_mem_bytes(bytes: [u8; N]) -> Self; - fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result; + fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result; - fn store_at(self, mem: &mut dyn LinearMemory, addr: usize) -> core::result::Result<(), crate::Trap>; + fn store_at(self, mem: &mut MemoryStorage, addr: usize) -> core::result::Result<(), crate::Trap>; } macro_rules! impl_mem_traits { - ($($ty:ty, $size:expr, $read:ident, $write:ident),* $(,)?) => { + ($($ty:ty, $size:expr),* $(,)?) => { $( impl MemValue<$size> for $ty { #[inline(always)] @@ -380,28 +40,20 @@ macro_rules! impl_mem_traits { } #[inline(always)] - fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result { - Ok(Self::from_le_bytes(cold_err!(mem.$read(addr))?)) + fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result { + Ok(Self::from_le_bytes(cold_err!(mem.read_fixed::<$size>(addr))?)) } #[inline(always)] - fn store_at( - self, - mem: &mut dyn LinearMemory, - addr: usize, - ) -> core::result::Result<(), crate::Trap> { - mem.$write(addr, &self.to_mem_bytes()) + fn store_at(self, mem: &mut MemoryStorage, addr: usize) -> core::result::Result<(), crate::Trap> { + mem.write_fixed::<$size>(addr, &self.to_mem_bytes()) } } )* }; } -impl_mem_traits!( - u8, 1, read_8, write_8, i8, 1, read_8, write_8, u16, 2, read_16, write_16, i16, 2, read_16, write_16, u32, 4, - read_32, write_32, i32, 4, read_32, write_32, f32, 4, read_32, write_32, u64, 8, read_64, write_64, i64, 8, - read_64, write_64, f64, 8, read_64, write_64 -); +impl_mem_traits!(u8, 1, i8, 1, u16, 2, i16, 2, u32, 4, i32, 4, f32, 4, u64, 8, i64, 8, f64, 8); impl MemValue<16> for Value128 { #[inline(always)] @@ -415,13 +67,13 @@ impl MemValue<16> for Value128 { } #[inline(always)] - fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result { - Ok(Self(cold_err!(mem.read_128(addr))?)) + fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result { + Ok(Self(cold_err!(mem.read_fixed::<16>(addr))?)) } #[inline(always)] - fn store_at(self, mem: &mut dyn LinearMemory, addr: usize) -> core::result::Result<(), crate::Trap> { - mem.write_128(addr, &self.0) + fn store_at(self, mem: &mut MemoryStorage, addr: usize) -> core::result::Result<(), crate::Trap> { + mem.write_fixed::<16>(addr, &self.0) } } diff --git a/crates/tinywasm/src/store/memory/paged.rs b/crates/tinywasm/src/store/memory/paged.rs deleted file mode 100644 index 3e6e5ea..0000000 --- a/crates/tinywasm/src/store/memory/paged.rs +++ /dev/null @@ -1,368 +0,0 @@ -use alloc::boxed::Box; -use alloc::vec::Vec; -use core::cmp::min; -use core::hint::cold_path; - -use super::{LinearMemory, memory_oob}; - -/// A sparse chunked linear memory. -/// -/// This backend stores memory in fixed-size chunks, which makes growth cheaper because it avoids -/// resizing and copying one large contiguous buffer. -/// -/// The tradeoff is that reads and writes do a bit more bookkeeping and may need to cross chunk -/// boundaries, so they are usually slightly slower than [`super::VecMemory`]. -/// -/// In particular, [`LinearMemory::read`] and [`LinearMemory::write`] return at most the bytes up to -/// the end of the current chunk. Higher-level exact helpers loop over these short operations when -/// they need a full range. -pub struct PagedMemory { - len: usize, - chunk_size: usize, - chunk_shift: u32, - chunk_mask: usize, - chunks: Vec>>, -} - -impl PagedMemory { - /// Tries to create a new sparse memory with `len` addressable bytes and the given `chunk_size`. - /// - /// Prefer this backend when grow behavior matters more than absolute read and write speed. - pub fn try_new(len: usize, chunk_size: usize) -> Result { - assert!(chunk_size.is_power_of_two(), "chunk_size must be a power of two"); - - let mut memory = Self { - len: 0, - chunk_size, - chunk_shift: chunk_size.trailing_zeros(), - chunk_mask: chunk_size - 1, - chunks: Vec::new(), - }; - memory.grow_to(len)?; - Ok(memory) - } - - #[inline(always)] - fn allocate_chunk(&self) -> Result, crate::Trap> { - let mut chunk = Vec::new(); - cold_err!(chunk.try_reserve_exact(self.chunk_size)).map_err(|_| crate::Trap::OutOfMemory)?; - chunk.resize(self.chunk_size, 0); - Ok(chunk.into_boxed_slice()) - } - - #[inline(always)] - fn chunk_mut(&mut self, chunk_idx: usize) -> Result<&mut [u8], crate::Trap> { - if self.chunks[chunk_idx].is_none() { - self.chunks[chunk_idx] = Some(self.allocate_chunk()?); - } - - Ok(self.chunks[chunk_idx].as_deref_mut().unwrap_or_else(|| unreachable!())) - } - - #[inline(always)] - fn chunk_slice(&self, chunk_idx: usize) -> Option<&[u8]> { - self.chunks[chunk_idx].as_deref() - } - - #[inline(always)] - fn read_fixed(&self, addr: usize) -> Result<[u8; N], crate::Trap> { - let Some(end) = addr.checked_add(N).filter(|end| *end <= self.len) else { - return cold!(Err(memory_oob(addr, N, self.len))); - }; - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - if end <= ((chunk_idx + 1) << self.chunk_shift) { - let mut bytes = [0; N]; - if let Some(chunk) = self.chunk_slice(chunk_idx) { - bytes.copy_from_slice(&chunk[chunk_offset..chunk_offset + N]); - } - return Ok(bytes); - } - cold_path(); - let mut bytes = [0; N]; - self.read_exact(addr, &mut bytes).ok_or_else(|| memory_oob(addr, N, self.len))?; - Ok(bytes) - } - - #[inline(always)] - fn write_fixed(&mut self, addr: usize, bytes: &[u8]) -> Result<(), crate::Trap> { - let Some(end) = addr.checked_add(N).filter(|end| *end <= self.len) else { - return cold!(Err(memory_oob(addr, N, self.len))); - }; - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - if end <= ((chunk_idx + 1) << self.chunk_shift) { - self.chunk_mut(chunk_idx)?[chunk_offset..chunk_offset + N].copy_from_slice(bytes); - return Ok(()); - } - cold_path(); - self.write_all(addr, bytes)?.ok_or_else(|| memory_oob(addr, N, self.len)) - } - - #[inline(always)] - fn checked_end(&self, addr: usize, len: usize) -> Option { - let end = addr.checked_add(len)?; - if end > self.len { - return None; - } - Some(end) - } - - #[inline(always)] - fn copy_within_single_chunk(&mut self, dst: usize, src: usize, len: usize) -> bool { - if len == 0 { - return true; - } - - if self.checked_end(src, len).is_none() || self.checked_end(dst, len).is_none() { - return false; - } - - let src_chunk_idx = src >> self.chunk_shift; - let dst_chunk_idx = dst >> self.chunk_shift; - if src_chunk_idx != dst_chunk_idx { - return false; - } - - let src_offset = src & self.chunk_mask; - let dst_offset = dst & self.chunk_mask; - if src_offset + len > self.chunk_size || dst_offset + len > self.chunk_size { - return false; - } - - if let Some(Some(chunk)) = self.chunks.get_mut(src_chunk_idx) { - chunk.copy_within(src_offset..src_offset + len, dst_offset); - } - - true - } -} - -#[cfg(feature = "debug")] -impl core::fmt::Debug for PagedMemory { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let allocated_chunks = self.chunks.iter().filter(|chunk| chunk.is_some()).count(); - f.debug_struct("PagedMemory") - .field("len", &self.len) - .field("chunk_size", &self.chunk_size) - .field("allocated_chunks", &allocated_chunks) - .finish() - } -} - -impl LinearMemory for PagedMemory { - #[inline(always)] - fn len(&self) -> usize { - self.len - } - - #[inline(always)] - fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> { - if new_len < self.len { - return Err(crate::Trap::MemoryOutOfBounds { offset: new_len, len: 0, max: self.len }); - } - - let new_chunk_count = if new_len == 0 { 0 } else { new_len.div_ceil(self.chunk_size) }; - if new_chunk_count > self.chunks.len() { - cold_err!(self.chunks.try_reserve_exact(new_chunk_count - self.chunks.len())) - .map_err(|_| crate::Trap::OutOfMemory)?; - self.chunks.resize_with(new_chunk_count, || None); - } else { - self.chunks.truncate(new_chunk_count); - } - - self.len = new_len; - Ok(()) - } - - #[inline(always)] - fn read(&self, addr: usize, dst: &mut [u8]) -> usize { - if addr >= self.len || dst.is_empty() { - return 0; - } - - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - let chunk_end = min((chunk_idx + 1) << self.chunk_shift, self.len); - let read_len = min(chunk_end - addr, dst.len()); - if let Some(chunk) = self.chunk_slice(chunk_idx) { - dst[..read_len].copy_from_slice(&chunk[chunk_offset..chunk_offset + read_len]); - } else { - dst[..read_len].fill(0); - } - - read_len - } - - #[inline(always)] - fn write(&mut self, addr: usize, src: &[u8]) -> Result { - if addr >= self.len || src.is_empty() { - return Ok(0); - } - - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - let write_len = min(min(self.chunk_size - chunk_offset, self.len - addr), src.len()); - - let chunk = self.chunk_mut(chunk_idx)?; - chunk[chunk_offset..chunk_offset + write_len].copy_from_slice(&src[..write_len]); - Ok(write_len) - } - - #[inline(always)] - fn write_all(&mut self, addr: usize, src: &[u8]) -> Result, crate::Trap> { - let Some(end) = self.checked_end(addr, src.len()) else { return Ok(None) }; - let mut pos = addr; - let mut src_offset = 0; - - while pos < end { - let chunk_idx = pos >> self.chunk_shift; - let chunk_offset = pos & self.chunk_mask; - let copy_len = min(self.chunk_size - chunk_offset, end - pos); - - let chunk = self.chunk_mut(chunk_idx)?; - chunk[chunk_offset..chunk_offset + copy_len].copy_from_slice(&src[src_offset..src_offset + copy_len]); - - pos += copy_len; - src_offset += copy_len; - } - - Ok(Some(())) - } - - #[inline(always)] - fn fill(&mut self, addr: usize, len: usize, val: u8) -> Result, crate::Trap> { - let Some(end) = self.checked_end(addr, len) else { return Ok(None) }; - let mut pos = addr; - - while pos < end { - let chunk_idx = pos >> self.chunk_shift; - let chunk_offset = pos & self.chunk_mask; - let chunk_start = chunk_idx << self.chunk_shift; - let chunk_full_len = min(self.chunk_size, self.len - chunk_start); - let chunk_end = min(chunk_start + self.chunk_size, end); - let fill_len = chunk_end - pos; - - if val == 0 { - if chunk_offset == 0 && fill_len == chunk_full_len { - self.chunks[chunk_idx] = None; - } else if let Some(Some(chunk)) = self.chunks.get_mut(chunk_idx) { - chunk[chunk_offset..chunk_offset + fill_len].fill(0); - } - } else { - self.chunk_mut(chunk_idx)?[chunk_offset..chunk_offset + fill_len].fill(val); - } - - pos = chunk_end; - } - - Ok(Some(())) - } - - #[inline(always)] - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result, crate::Trap> { - if self.checked_end(src, len).is_none() || self.checked_end(dst, len).is_none() { - return Ok(None); - } - - if len == 0 || dst == src { - return Ok(Some(())); - } - - if self.copy_within_single_chunk(dst, src, len) { - return Ok(Some(())); - } - - let mut buf = [0u8; 256]; - - if dst < src || dst >= src + len { - let mut copied = 0; - while copied < len { - let chunk_len = min(buf.len(), len - copied); - if self.read_exact(src + copied, &mut buf[..chunk_len]).is_none() - || self.write_all(dst + copied, &buf[..chunk_len])?.is_none() - { - return Ok(None); - } - copied += chunk_len; - } - } else { - let mut remaining = len; - while remaining > 0 { - let chunk_len = min(buf.len(), remaining); - let chunk_start = remaining - chunk_len; - if self.read_exact(src + chunk_start, &mut buf[..chunk_len]).is_none() - || self.write_all(dst + chunk_start, &buf[..chunk_len])?.is_none() - { - return Ok(None); - } - remaining = chunk_start; - } - } - - Ok(Some(())) - } - - #[inline(always)] - fn read_8(&self, addr: usize) -> core::result::Result<[u8; 1], crate::Trap> { - if addr >= self.len { - cold_path(); - return Err(memory_oob(addr, 1, self.len)); - } - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - Ok([self.chunk_slice(chunk_idx).map_or(0, |chunk| chunk[chunk_offset])]) - } - - #[inline(always)] - fn read_16(&self, addr: usize) -> core::result::Result<[u8; 2], crate::Trap> { - self.read_fixed::<2>(addr) - } - - #[inline(always)] - fn read_32(&self, addr: usize) -> core::result::Result<[u8; 4], crate::Trap> { - self.read_fixed::<4>(addr) - } - - #[inline(always)] - fn read_64(&self, addr: usize) -> core::result::Result<[u8; 8], crate::Trap> { - self.read_fixed::<8>(addr) - } - - #[inline(always)] - fn read_128(&self, addr: usize) -> core::result::Result<[u8; 16], crate::Trap> { - self.read_fixed::<16>(addr) - } - - #[inline(always)] - fn write_8(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - if addr >= self.len { - cold_path(); - return Err(memory_oob(addr, 1, self.len)); - } - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - self.chunk_mut(chunk_idx)?[chunk_offset] = bytes[0]; - Ok(()) - } - - #[inline(always)] - fn write_16(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<2>(addr, bytes) - } - - #[inline(always)] - fn write_32(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<4>(addr, bytes) - } - - #[inline(always)] - fn write_64(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<8>(addr, bytes) - } - - #[inline(always)] - fn write_128(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<16>(addr, bytes) - } -} diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs index be85e9b..98c24d6 100644 --- a/crates/tinywasm/src/store/memory/vec.rs +++ b/crates/tinywasm/src/store/memory/vec.rs @@ -1,24 +1,20 @@ use alloc::vec::Vec; +use core::ops::Range; -use super::{LinearMemory, memory_oob}; +use super::memory_oob; -/// A contiguous `Vec`-backed linear memory. +/// A contiguous `Vec`-backed linear memory storage. /// -/// This is the simplest backend and typically gives the best read and write throughput because -/// the whole memory lives in one contiguous allocation. -/// -/// The tradeoff is growth cost: large grows may need to reallocate and copy the full buffer, -/// which can get expensive for large memories. -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct VecMemory { +/// This is the internal storage boundary for [`super::MemoryInstance`]. Keeping it a concrete type +/// rather than a `Vec` directly means the backing representation can later be swapped for an +/// mmap-backed implementation without touching the interpreter's load and store paths. +pub(crate) struct VecMemory { data: Vec, } impl VecMemory { /// Tries to create a new memory with `len` zero-initialized bytes. - /// - /// Prefer this backend when contiguous access is more important than grow performance. - pub fn try_new(len: usize) -> Result { + pub(crate) fn try_new(len: usize) -> Result { let mut data = Vec::new(); cold_err!(data.try_reserve_exact(len)).map_err(|_| crate::Trap::OutOfMemory)?; data.resize(len, 0); @@ -26,11 +22,24 @@ impl VecMemory { } #[inline(always)] - fn read_fixed(&self, addr: usize) -> Result<[u8; N], crate::Trap> { - self.check_fixed_addr::(addr)?; - let mut bytes = [0u8; N]; - bytes.copy_from_slice(&self.data[addr..addr + N]); - Ok(bytes) + pub(crate) fn len(&self) -> usize { + self.data.len() + } + + #[inline(always)] + pub(super) fn checked_range(&self, addr: usize, len: usize) -> Option> { + let end = addr.checked_add(len)?; + (end <= self.data.len()).then_some(addr..end) + } + + /// Grows the backing allocation to `new_len`. Only called after the Wasm limits and any user + /// limiter have accepted the grow. + #[inline(always)] + pub(crate) fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> { + debug_assert!(new_len >= self.data.len(), "memory only grows"); + cold_err!(self.data.try_reserve_exact(new_len - self.data.len())).map_err(|_| crate::Trap::OutOfMemory)?; + self.data.resize(new_len, 0); + Ok(()) } #[inline(always)] @@ -40,27 +49,27 @@ impl VecMemory { } Ok(()) } -} -impl LinearMemory for VecMemory { + /// Reads exactly `N` bytes at `addr` into a fixed-size array. #[inline(always)] - fn len(&self) -> usize { - self.data.len() + pub(crate) fn read_fixed(&self, addr: usize) -> Result<[u8; N], crate::Trap> { + self.check_fixed_addr::(addr)?; + let mut bytes = [0u8; N]; + bytes.copy_from_slice(&self.data[addr..addr + N]); + Ok(bytes) } + /// Writes exactly `N` bytes from `bytes` at `addr`. #[inline(always)] - fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> { - if new_len < self.data.len() { - return Err(crate::Trap::MemoryOutOfBounds { offset: new_len, len: 0, max: self.data.len() }); - } - cold_err!(self.data.try_reserve_exact(new_len.saturating_sub(self.data.len()))) - .map_err(|_| crate::Trap::OutOfMemory)?; - self.data.resize(new_len, 0); + pub(crate) fn write_fixed(&mut self, addr: usize, bytes: &[u8; N]) -> Result<(), crate::Trap> { + self.check_fixed_addr::(addr)?; + self.data[addr..addr + N].copy_from_slice(bytes); Ok(()) } + /// Reads up to `dst.len()` bytes starting at `addr` and returns the number of bytes read. #[inline(always)] - fn read(&self, addr: usize, dst: &mut [u8]) -> usize { + pub(crate) fn read(&self, addr: usize, dst: &mut [u8]) -> usize { if addr >= self.data.len() { return 0; } @@ -69,114 +78,60 @@ impl LinearMemory for VecMemory { read_len } + /// Writes up to `src.len()` bytes starting at `addr` and returns the number of bytes written. #[inline(always)] - fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> { - dst.copy_from_slice(self.data.get(addr..addr.checked_add(dst.len())?)?); - Some(()) - } - - #[inline(always)] - fn read_vec(&self, addr: usize, len: usize) -> Option> { - Some(self.data.get(addr..addr.checked_add(len)?)?.to_vec()) - } - - #[inline(always)] - fn write(&mut self, addr: usize, src: &[u8]) -> Result { + pub(crate) fn write(&mut self, addr: usize, src: &[u8]) -> usize { if addr >= self.data.len() { - return Ok(0); + return 0; } - let write_len = src.len().min(self.data.len() - addr); self.data[addr..addr + write_len].copy_from_slice(&src[..write_len]); - Ok(write_len) + write_len } + /// Reads exactly `dst.len()` bytes starting at `addr`, returning `None` for an invalid range. #[inline(always)] - fn write_all(&mut self, addr: usize, src: &[u8]) -> Result, crate::Trap> { - let Some(end) = addr.checked_add(src.len()) else { return Ok(None) }; - let Some(dst) = self.data.get_mut(addr..end) else { return Ok(None) }; - dst.copy_from_slice(src); - Ok(Some(())) - } - - #[inline(always)] - fn fill(&mut self, addr: usize, len: usize, val: u8) -> Result, crate::Trap> { - let Some(end) = addr.checked_add(len) else { return Ok(None) }; - let Some(dst) = self.data.get_mut(addr..end) else { return Ok(None) }; - dst.fill(val); - Ok(Some(())) - } - - #[inline(always)] - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result, crate::Trap> { - let Some(src_end) = src.checked_add(len) else { return Ok(None) }; - let Some(dst_end) = dst.checked_add(len) else { return Ok(None) }; - if src_end > self.data.len() || dst_end > self.data.len() { - return Ok(None); - } - - self.data.copy_within(src..src_end, dst); - Ok(Some(())) - } - - #[inline(always)] - fn read_8(&self, addr: usize) -> core::result::Result<[u8; 1], crate::Trap> { - self.check_fixed_addr::<1>(addr)?; - Ok([self.data[addr]]) - } - - #[inline(always)] - fn read_16(&self, addr: usize) -> core::result::Result<[u8; 2], crate::Trap> { - self.read_fixed::<2>(addr) - } - - #[inline(always)] - fn read_32(&self, addr: usize) -> core::result::Result<[u8; 4], crate::Trap> { - self.read_fixed::<4>(addr) - } - - #[inline(always)] - fn read_64(&self, addr: usize) -> core::result::Result<[u8; 8], crate::Trap> { - self.read_fixed::<8>(addr) - } - - #[inline(always)] - fn read_128(&self, addr: usize) -> core::result::Result<[u8; 16], crate::Trap> { - self.read_fixed::<16>(addr) + pub(crate) fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> { + dst.copy_from_slice(&self.data[self.checked_range(addr, dst.len())?]); + Some(()) } + /// Reads `len` bytes starting at `addr` into a newly allocated buffer, returning `None` for an + /// invalid range. #[inline(always)] - fn write_8(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.check_fixed_addr::<1>(addr)?; - self.data[addr] = bytes[0]; - Ok(()) + pub(crate) fn read_vec(&self, addr: usize, len: usize) -> Option> { + Some(self.data[self.checked_range(addr, len)?].to_vec()) } + /// Writes all of `src` at `addr`, returning `None` for an invalid range. #[inline(always)] - fn write_16(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.check_fixed_addr::<2>(addr)?; - self.data[addr..addr + 2].copy_from_slice(bytes); - Ok(()) + pub(crate) fn write_all(&mut self, addr: usize, src: &[u8]) -> Option<()> { + let range = self.checked_range(addr, src.len())?; + self.data[range].copy_from_slice(src); + Some(()) } + /// Fills the range `[addr, addr + len)` with `val`, returning `None` for an invalid range. #[inline(always)] - fn write_32(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.check_fixed_addr::<4>(addr)?; - self.data[addr..addr + 4].copy_from_slice(bytes); - Ok(()) + pub(crate) fn fill(&mut self, addr: usize, len: usize, val: u8) -> Option<()> { + let range = self.checked_range(addr, len)?; + self.data[range].fill(val); + Some(()) } + /// Copies `len` bytes from `src` to `dst` within the memory, returning `None` for an invalid + /// range. #[inline(always)] - fn write_64(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.check_fixed_addr::<8>(addr)?; - self.data[addr..addr + 8].copy_from_slice(bytes); - Ok(()) + pub(crate) fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Option<()> { + let src = self.checked_range(src, len)?; + self.checked_range(dst, len)?; + self.data.copy_within(src, dst); + Some(()) } + /// Copies a previously checked range from another memory. #[inline(always)] - fn write_128(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.check_fixed_addr::<16>(addr)?; - self.data[addr..addr + 16].copy_from_slice(bytes); - Ok(()) + pub(super) fn copy_from(&mut self, dst: usize, src_memory: &Self, src: usize, len: usize) { + self.data[dst..dst + len].copy_from_slice(&src_memory.data[src..src + len]); } } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 33a549c..f0e426f 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -23,7 +23,6 @@ mod types; use const_expr::eval_const; pub(crate) use gc::{decode_data, default_value, pop_value, push_value}; -pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory}; pub(crate) use memory::{MemValue, MemoryInstance}; pub(crate) use state::State; pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; @@ -32,12 +31,72 @@ pub(crate) use {data::*, element::*, exception::*, function::*, global::*, table // global store id counter static STORE_ID: AtomicU32 = AtomicU32::new(0); -/// Global state that can be manipulated by WebAssembly programs +/// Controls resource usage by WebAssembly instances. /// -/// Managed WebAssembly GC objects are collected automatically. Other Store -/// instances, such as modules, functions, memories, and tables, live until the -/// Store is dropped. GC references exposed through the copyable host value API -/// are retained for the Store's lifetime. +/// Configure a limiter with +/// [`Config::with_resource_limiter`](crate::engine::Config::with_resource_limiter). It currently +/// controls guest linear-memory and table allocation and growth. It does not account for stacks, +/// GC storage, runtime metadata, or other host allocations. +/// +/// # Example +/// ```rust +/// use std::sync::Arc; +/// use tinywasm::engine::Config; +/// use tinywasm::types::{MemoryArch, MemoryType}; +/// use tinywasm::{Engine, Memory, ResourceLimiter, Store}; +/// +/// struct MemoryLimit(usize); +/// +/// impl ResourceLimiter for MemoryLimit { +/// fn memory_growing( +/// &self, +/// _current: usize, +/// desired: usize, +/// _maximum: Option, +/// ) -> Result { +/// Ok(desired <= self.0) +/// } +/// } +/// +/// let config = Config::new().with_resource_limiter(Arc::new(MemoryLimit(64 * 1024))); +/// let mut store = Store::new(Engine::new(config)); +/// let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; +/// assert_eq!(memory.grow(&mut store, 1)?, None); +/// # Ok::<(), tinywasm::Error>(()) +/// ``` +pub trait ResourceLimiter: Send + Sync { + /// Returns whether a memory allocation or growth is allowed. + /// + /// Sizes are in bytes. `current` is zero for initial allocation, and `maximum` is `None` for an + /// unbounded memory. `Ok(false)` rejects the request, while `Err` traps. Rejected initial + /// allocations return [`Trap::OutOfMemory`], since they have no normal failure result. The + /// default implementation allows the request. + fn memory_growing( + &self, + _current: usize, + _desired: usize, + _maximum: Option, + ) -> core::result::Result { + Ok(true) + } + + /// Returns whether a table allocation or growth is allowed. + /// + /// Sizes are in elements. `current` is zero for initial allocation, and `maximum` is `None` for + /// an unbounded table. `Ok(false)` rejects the request, while `Err` traps. Rejected initial + /// allocations return [`Trap::OutOfMemory`], since they have no normal failure result. The + /// default implementation allows the request. + fn table_growing( + &self, + _current: usize, + _desired: usize, + _maximum: Option, + ) -> core::result::Result { + Ok(true) + } +} + +/// Runtime state used by WebAssembly instances and host functions. /// /// ## Example /// ```rust @@ -240,6 +299,7 @@ impl Store { type_addrs: &[TypeAddr], ) -> Result> { let start = self.state.tables.len() as TableAddr; + let limiter = self.engine.config().resource_limiter.clone(); self.state.tables.reserve_exact(tables.len()); for table in tables { let init = match &table.init { @@ -254,7 +314,7 @@ impl Store { MemoryArch::I32 => TableType::new(element_type, table.ty.size_initial, table.ty.size_max), MemoryArch::I64 => TableType::new64(element_type, table.ty.size_initial, table.ty.size_max), }; - self.state.tables.push(TableInstance::new(ty, init)?); + self.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); } Ok(start..start + tables.len() as TableAddr) } @@ -263,12 +323,12 @@ impl Store { pub(crate) fn init_memories( &mut self, memories: &[MemoryType], - init: impl Fn(MemoryType, &MemoryBackend) -> Result, + init: impl Fn(MemoryType) -> Result, ) -> Result> { let start = self.state.memories.len() as MemAddr; self.state.memories.reserve_exact(memories.len()); for mem in memories { - self.state.memories.push(cold_err!(init(*mem, &self.engine.config().memory_backend))?); + self.state.memories.push(cold_err!(init(*mem))?); } Ok(start..start + memories.len() as MemAddr) } @@ -428,7 +488,7 @@ impl Store { }; let offset = usize::try_from(offset).unwrap_or(usize::MAX); - match mem.inner.write_all(offset, &data.data)? { + match mem.inner.write_all(offset, &data.data) { Some(()) => None, None => { return Ok(( diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index 8e6c055..da52660 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -1,4 +1,4 @@ -use crate::{Result, Trap, interpreter::ValueRef}; +use crate::{ResourceLimiter, Result, Trap, interpreter::ValueRef}; use alloc::vec::Vec; use core::ops::Range; use tinywasm_types::*; @@ -16,11 +16,17 @@ pub(crate) struct TableInstance { impl TableInstance { /// Creates a table filled with the given initial reference. - pub(crate) fn new(kind: TableType, init: ValueRef) -> Result { + pub(crate) fn new(kind: TableType, init: ValueRef, limiter: Option<&dyn ResourceLimiter>) -> Result { let size = cold_err!(usize::try_from(kind.size_initial)).map_err(|_| Trap::OutOfMemory)?; if size > MAX_TABLE_SIZE { return Err(Trap::OutOfMemory.into()); } + if size != 0 + && let Some(limiter) = limiter + && !limiter.table_growing(0, size, Self::maximum_size(kind))? + { + return Err(Trap::OutOfMemory.into()); + } let mut elements = Vec::new(); cold_err!(elements.try_reserve_exact(size)).map_err(|_| Trap::OutOfMemory)?; elements.resize(size, init); @@ -74,17 +80,38 @@ impl TableInstance { Ok(()) } - pub(crate) fn grow(&mut self, n: usize, init: ValueRef) -> Result<(), Trap> { - let len = n.checked_add(self.elements.len()).ok_or(Trap::OutOfMemory)?; + pub(crate) fn grow( + &mut self, + n: usize, + init: ValueRef, + limiter: Option<&dyn ResourceLimiter>, + ) -> Result { + let Some(len) = n.checked_add(self.elements.len()) else { + return Ok(false); + }; let declared_max = self.kind.size_max.and_then(|max| usize::try_from(max).ok()).unwrap_or(usize::MAX); let max = declared_max.min(MAX_TABLE_SIZE); if len > max { - return Err(crate::Trap::TableOutOfBounds { offset: len, len: 1, max: self.elements.len() }); + return Ok(false); + } + if len == self.elements.len() { + return Ok(true); + } + if let Some(limiter) = limiter + && !limiter.table_growing(self.elements.len(), len, Self::maximum_size(self.kind))? + { + return Ok(false); } - cold_err!(self.elements.try_reserve_exact(n)).map_err(|_| Trap::OutOfMemory)?; + if cold_err!(self.elements.try_reserve_exact(n)).is_err() { + return Ok(false); + } self.elements.resize(len, init); - Ok(()) + Ok(true) + } + + fn maximum_size(kind: TableType) -> Option { + kind.size_max.and_then(|maximum| usize::try_from(maximum).ok()) } pub(crate) fn size(&self) -> usize { diff --git a/crates/tinywasm/tests/internal_refs.rs b/crates/tinywasm/tests/internal_refs.rs index 07cbde2..1793e05 100644 --- a/crates/tinywasm/tests/internal_refs.rs +++ b/crates/tinywasm/tests/internal_refs.rs @@ -65,7 +65,7 @@ fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<(), Box = Result>; + +fn store_with_limiter(limiter: Arc) -> Store { + let engine = Engine::new(Config::new().with_resource_limiter(limiter)); + Store::new(engine) +} + +#[test] +fn memory_read_write_roundtrip() -> TestResult { + let mut store = Store::default(); + let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; + + memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4, 5])?; + assert_eq!(memory.read_vec(&store, 0, 5)?, &[1, 2, 3, 4, 5]); + memory.fill(&mut store, 2, 2, 0)?; + assert_eq!(memory.read_vec(&store, 0, 5)?, &[1, 2, 0, 0, 5]); + Ok(()) +} + +#[test] +fn read_returns_short_count_at_end_of_memory() -> TestResult { + let mut store = Store::default(); + let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)))?; + memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4])?; + + let mut dst = [9; 8]; + assert_eq!(memory.read(&store, 2, &mut dst)?, 2); + assert_eq!(&dst[..2], &[3, 4]); + assert_eq!(&dst[2..], &[9; 6]); + + Ok(()) +} + +#[test] +fn memory64_default_limit_is_not_memory32_limit() { + let ty = MemoryType::new(MemoryArch::I64, 65_537, None, None); + assert!(ty.page_count_max() > 65_536); +} + +struct DenyAll; + +impl ResourceLimiter for DenyAll { + fn memory_growing(&self, _current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(false) + } + + fn table_growing(&self, _current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(false) + } +} + +struct DenyGrowth; + +impl ResourceLimiter for DenyGrowth { + fn memory_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(current == 0) + } + + fn table_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(current == 0) + } +} + +struct TrapGrowth; + +impl ResourceLimiter for TrapGrowth { + fn memory_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + if current == 0 { Ok(true) } else { Err(Trap::Unreachable) } + } + + fn table_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + if current == 0 { Ok(true) } else { Err(Trap::Unreachable) } + } +} + +#[test] +fn resource_limiter_can_reject_growth() -> TestResult { + let mut store = store_with_limiter(Arc::new(DenyGrowth)); + let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; + + assert_eq!(memory.grow(&mut store, 1)?, None); + assert_eq!(memory.page_count(&store)?, 1); + Ok(()) +} + +#[test] +fn resource_limiter_rejects_guest_memory_grow() -> TestResult { + let wasm = wat::parse_str( + r#" + (module + (memory 1) + (func (export "grow") (result i32) + i32.const 1 + memory.grow)) + "#, + )?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = store_with_limiter(Arc::new(DenyGrowth)); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + + let grow = instance.func::<(), i32>(&store, "grow")?; + assert_eq!(grow.call(&mut store, ())?, -1); + Ok(()) +} + +#[test] +fn resource_limiter_can_trap_guest_memory_grow() -> TestResult { + let wasm = wat::parse_str( + r#" + (module + (memory 1) + (func (export "grow") (result i32) + i32.const 1 + memory.grow)) + "#, + )?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = store_with_limiter(Arc::new(TrapGrowth)); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + + let grow = instance.func::<(), i32>(&store, "grow")?; + assert!(matches!(grow.call(&mut store, ()), Err(tinywasm::Error::Trap(Trap::Unreachable)))); + Ok(()) +} + +#[test] +fn resource_limiter_rejects_host_memory_initial_size() { + let mut store = store_with_limiter(Arc::new(DenyAll)); + let result = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None)); + + assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); +} + +#[test] +fn resource_limiter_rejects_module_memory_initial_size() -> TestResult { + let wasm = wat::parse_str("(module (memory 1))")?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = store_with_limiter(Arc::new(DenyAll)); + let result = ModuleInstance::instantiate(&mut store, &module, None); + + assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); + Ok(()) +} + +#[test] +fn resource_limiter_rejects_table_initial_size() { + let mut store = store_with_limiter(Arc::new(DenyAll)); + let result = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into()); + + assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); +} + +#[test] +fn resource_limiter_can_reject_table_growth() -> TestResult { + let mut store = store_with_limiter(Arc::new(DenyGrowth)); + let table = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; + + assert_eq!(table.grow(&mut store, 1, RefValue::Null.into())?, None); + assert_eq!(table.size(&store)?, 1); + Ok(()) +} + +#[test] +fn resource_limiter_can_trap_table_growth() -> TestResult { + let mut store = store_with_limiter(Arc::new(TrapGrowth)); + let table = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; + + assert!(matches!(table.grow(&mut store, 1, RefValue::Null.into()), Err(tinywasm::Error::Trap(Trap::Unreachable)))); + Ok(()) +} + +#[test] +fn resource_limiter_allows_guest_memory_grow_by_default() -> TestResult { + let wasm = wat::parse_str( + r#" + (module + (memory 1) + (func (export "grow") (result i32) + i32.const 1 + memory.grow)) + "#, + )?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + + let grow = instance.func::<(), i32>(&store, "grow")?; + assert_eq!(grow.call(&mut store, ())?, 1); + Ok(()) +} diff --git a/crates/tinywasm/tests/memory_backends.rs b/crates/tinywasm/tests/memory_backends.rs deleted file mode 100644 index 73657df..0000000 --- a/crates/tinywasm/tests/memory_backends.rs +++ /dev/null @@ -1,307 +0,0 @@ -extern crate alloc; - -use alloc::sync::Arc; -use core::sync::atomic::{AtomicUsize, Ordering}; - -#[cfg(feature = "std")] -use std::io::{Read, Seek, SeekFrom, Write}; - -use tinywasm::engine::Config; -use tinywasm::types::{MemoryArch, MemoryType}; -use tinywasm::{Engine, Memory, MemoryBackend, Module, ModuleInstance, PagedMemory, Store}; -use tinywasm_parser::{Parser, ParserOptions}; - -type TestResult = Result>; - -fn initial_memory_size(ty: MemoryType) -> usize { - usize::try_from(ty.page_count_initial()) - .ok() - .and_then(|pages| pages.checked_mul(usize::try_from(ty.page_size()).ok()?)) - .expect("test memory size should fit usize") -} - -fn instantiate_module_with_counting_backend(module: Module) -> TestResult { - let created = Arc::new(AtomicUsize::new(0)); - let factory_calls = created.clone(); - let backend = MemoryBackend::custom(move |ty| { - factory_calls.fetch_add(1, Ordering::Relaxed); - PagedMemory::try_new(initial_memory_size(ty), 16) - }); - let engine = Engine::new(Config::new().with_memory_backend(backend)); - let mut store = Store::new(engine); - - let _ = ModuleInstance::instantiate(&mut store, &module, None)?; - - Ok(created.load(Ordering::Relaxed)) -} - -fn instantiate_with_counting_backend(wat: &str) -> TestResult { - let wasm = wat::parse_str(wat)?; - let module = tinywasm::parse_bytes(&wasm)?; - instantiate_module_with_counting_backend(module) -} - -fn instantiate_exported_memory_with_counting_backend( - wat: &str, -) -> TestResult<(Store, tinywasm::ModuleInstance, Arc)> { - let wasm = wat::parse_str(wat)?; - let module = tinywasm::parse_bytes(&wasm)?; - let created = Arc::new(AtomicUsize::new(0)); - let factory_calls = created.clone(); - let backend = MemoryBackend::custom(move |ty| { - factory_calls.fetch_add(1, Ordering::Relaxed); - PagedMemory::try_new(initial_memory_size(ty), 16) - }); - let engine = Engine::new(Config::new().with_memory_backend(backend)); - let mut store = Store::new(engine); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - Ok((store, instance, created)) -} - -#[test] -fn paged_backend_works_for_module_memories() -> TestResult { - let wasm = wat::parse_str( - r#" - (module - (memory (export "memory") 1) - ) - "#, - )?; - - let module = tinywasm::parse_bytes(&wasm)?; - let config = Config::new().with_memory_backend(MemoryBackend::paged(8)); - let mut store = Store::new(Engine::new(config)); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let memory = instance.memory("memory")?; - - memory.copy_from_slice(&mut store, 6, &[1, 2, 3, 4, 5, 6, 7, 8])?; - assert_eq!(memory.read_vec(&store, 6, 8)?, &[1, 2, 3, 4, 5, 6, 7, 8]); - - Ok(()) -} - -#[test] -fn custom_backend_factory_is_used_for_host_memories() -> TestResult { - let created = Arc::new(AtomicUsize::new(0)); - let seen_page_size = Arc::new(AtomicUsize::new(0)); - let factory_calls = created.clone(); - let page_size_seen = seen_page_size.clone(); - - let backend = MemoryBackend::custom(move |ty| { - factory_calls.fetch_add(1, Ordering::Relaxed); - page_size_seen.store(ty.page_size() as usize, Ordering::Relaxed); - PagedMemory::try_new(initial_memory_size(ty), 16) - }); - - let engine = Engine::new(Config::new().with_memory_backend(backend)); - let mut store = Store::new(engine); - - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(2), Some(32)))?; - assert_eq!(memory.ty(&store)?.page_size(), 32); - memory.copy_from_slice(&mut store, 12, &[9, 8, 7, 6, 5])?; - - assert_eq!(memory.read_vec(&store, 12, 5)?, &[9, 8, 7, 6, 5]); - assert_eq!(created.load(Ordering::Relaxed), 1); - assert_eq!(seen_page_size.load(Ordering::Relaxed), 32); - - Ok(()) -} - -#[test] -fn local_memory_without_observable_use_is_not_allocated() -> TestResult { - let created = instantiate_with_counting_backend( - r#" - (module - (memory 1) - (func (export "run")) - ) - "#, - )?; - - assert_eq!(created, 0); - Ok(()) -} - -#[test] -fn exported_local_memory_is_not_eagerly_allocated() -> TestResult { - let created = instantiate_with_counting_backend( - r#" - (module - (memory (export "memory") 1) - ) - "#, - )?; - - assert_eq!(created, 0); - Ok(()) -} - -#[test] -fn exported_local_memory_reads_zeroes_without_materializing() -> TestResult { - let (mut store, instance, created) = instantiate_exported_memory_with_counting_backend( - r#" - (module - (memory (export "memory") 1) - ) - "#, - )?; - - let memory = instance.memory("memory")?; - assert_eq!(created.load(Ordering::Relaxed), 0); - assert_eq!(memory.len(&store)?, 65536); - assert_eq!(memory.read_vec(&store, 65534, 2)?, &[0, 0]); - assert_eq!(created.load(Ordering::Relaxed), 0); - - memory.copy_from_slice(&mut store, 65534, &[1, 2])?; - assert_eq!(created.load(Ordering::Relaxed), 1); - assert_eq!(memory.read_vec(&store, 65534, 2)?, &[1, 2]); - Ok(()) -} - -#[test] -fn active_data_segment_on_local_memory_is_allocated() -> TestResult { - let created = instantiate_with_counting_backend( - r#" - (module - (memory 1) - (data (i32.const 0) "hi") - ) - "#, - )?; - - assert_eq!(created, 1); - Ok(()) -} - -#[test] -fn local_memory_instruction_is_allocated() -> TestResult { - let created = instantiate_with_counting_backend( - r#" - (module - (memory 1) - (func (export "run") (drop (memory.size))) - ) - "#, - )?; - - assert_eq!(created, 1); - Ok(()) -} - -#[test] -fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> TestResult { - let wasm = wat::parse_str( - r#" - (module - (memory 1) - (func (export "run")) - ) - "#, - )?; - let parser = Parser::new(ParserOptions::default().with_local_memory_allocation_optimization(false)); - let module = parser.parse_module_bytes(&wasm)?; - - let created = instantiate_module_with_counting_backend(module)?; - - assert_eq!(created, 1); - Ok(()) -} - -#[test] -fn read_returns_short_count_at_end_of_memory() -> TestResult { - let mut store = Store::default(); - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)))?; - memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4])?; - - let mut dst = [9; 8]; - assert_eq!(memory.read(&store, 2, &mut dst)?, 2); - assert_eq!(&dst[..2], &[3, 4]); - assert_eq!(&dst[2..], &[9; 6]); - - Ok(()) -} - -#[test] -fn paged_read_and_write_stop_at_chunk_boundaries() -> TestResult { - let engine = Engine::new(Config::new().with_memory_backend(MemoryBackend::paged(4))); - let mut store = Store::new(engine); - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(16)))?; - - memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4, 5, 6, 7, 8])?; - - let mut read_buf = [9; 6]; - assert_eq!(memory.read(&store, 2, &mut read_buf)?, 2); - assert_eq!(&read_buf[..2], &[3, 4]); - assert_eq!(&read_buf[2..], &[9; 4]); - - let mut exact_buf = [0; 6]; - memory.read_exact(&store, 2, &mut exact_buf)?; - assert_eq!(exact_buf, [3, 4, 5, 6, 7, 8]); - - assert_eq!(memory.write(&mut store, 6, &[10, 11, 12, 13])?, 2); - assert_eq!(memory.read_vec(&store, 6, 4)?, &[10, 11, 0, 0]); - - memory.copy_from_slice(&mut store, 6, &[20, 21, 22, 23])?; - assert_eq!(memory.read_vec(&store, 6, 4)?, &[20, 21, 22, 23]); - - Ok(()) -} - -#[test] -fn paged_fixed_width_accesses_cross_chunk_boundaries() -> TestResult { - use tinywasm::LinearMemory; - - let mut memory = PagedMemory::try_new(32, 4).map_err(tinywasm::Error::from)?; - memory.write_32(2, &0x1234_5678u32.to_le_bytes()).map_err(tinywasm::Error::from)?; - memory.write_64(6, &0x0123_4567_89ab_cdefu64.to_le_bytes()).map_err(tinywasm::Error::from)?; - memory.write_128(14, &u128::MAX.to_le_bytes()).map_err(tinywasm::Error::from)?; - - assert_eq!(u32::from_le_bytes(memory.read_32(2).map_err(tinywasm::Error::from)?), 0x1234_5678); - assert_eq!(u64::from_le_bytes(memory.read_64(6).map_err(tinywasm::Error::from)?), 0x0123_4567_89ab_cdef); - assert_eq!(u128::from_le_bytes(memory.read_128(14).map_err(tinywasm::Error::from)?), u128::MAX); - Ok(()) -} - -#[test] -fn lazy_custom_backend_creation_trap_is_propagated() -> TestResult { - let wasm = wat::parse_str(r#"(module (memory (export "memory") 1))"#)?; - let module = tinywasm::parse_bytes(&wasm)?; - let backend = MemoryBackend::custom(|_| Err::(tinywasm::Trap::Other("backend unavailable"))); - let mut store = Store::new(Engine::new(Config::new().with_memory_backend(backend))); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let memory = instance.memory("memory")?; - - assert_eq!( - memory.copy_from_slice(&mut store, 0, &[1]).unwrap_err(), - tinywasm::Error::from(tinywasm::Trap::Other("backend unavailable")) - ); - Ok(()) -} - -#[test] -fn memory64_default_limit_is_not_memory32_limit() { - let ty = MemoryType::new(MemoryArch::I64, 65_537, None, None); - assert!(ty.page_count_max() > 65_536); -} - -#[cfg(feature = "std")] -#[test] -fn memory_cursor_supports_read_write_and_seek() -> TestResult { - let mut store = Store::default(); - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(8)))?; - - let mut cursor = memory.cursor(&mut store)?; - cursor.seek(SeekFrom::Start(2))?; - cursor.write_all(b"abc")?; - cursor.seek(SeekFrom::Start(0))?; - - let mut buf = [0; 5]; - cursor.read_exact(&mut buf)?; - assert_eq!(buf, [0, 0, b'a', b'b', b'c']); - - cursor.seek(SeekFrom::End(-1))?; - cursor.write_all(b"z")?; - - assert_eq!(memory.read_vec(&store, 0, 8)?, &[0, 0, b'a', b'b', b'c', 0, 0, b'z']); - Ok(()) -} diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 797f703..c9786d3 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -799,89 +799,6 @@ pub enum Instruction { const _: () = assert!(core::mem::size_of::() == 8); -impl Instruction { - /// Returns the largest module-local memory index used by this instruction. - #[inline] - pub fn memory_addr(&self, data: &super::WasmFunctionData) -> Option { - use Instruction::*; - match *self { - IncMemoryLocal32(arg) - | IncMemoryLocal64(arg) - | StoreLocalLocal32(arg) - | StoreLocalLocal64(arg) - | StoreLocalLocal128(arg) - | LoadLocal32(arg) - | LoadLocal64(arg) - | LoadLocal8S32(arg) - | LoadLocal8U32(arg) - | LoadLocal16S32(arg) - | LoadLocal16U32(arg) - | LoadLocalTee32(arg) - | LoadLocalSet32(arg) - | LoadLocalTee8S32(arg) - | LoadLocalTee8U32(arg) - | LoadLocalTee16S32(arg) - | LoadLocalTee16U32(arg) - | LoadLocalSet8S32(arg) - | LoadLocalSet8U32(arg) - | LoadLocalSet16S32(arg) - | LoadLocalSet16U32(arg) - | LoadLocalTee128(arg) - | LoadLocalSet128(arg) => Some(arg.memory_arg_idx.get(data).mem_addr()), - I32Load(index) - | I64Load(index) - | F32Load(index) - | F64Load(index) - | I32Load8S(index) - | I32Load8U(index) - | I32Load16S(index) - | I32Load16U(index) - | I64Load8S(index) - | I64Load8U(index) - | I64Load16S(index) - | I64Load16U(index) - | I64Load32S(index) - | I64Load32U(index) - | I32Store(index) - | I64Store(index) - | F32Store(index) - | F64Store(index) - | I32Store8(index) - | I32Store16(index) - | I64Store8(index) - | I64Store16(index) - | I64Store32(index) - | V128Load(index) - | V128Load8x8S(index) - | V128Load8x8U(index) - | V128Load16x4S(index) - | V128Load16x4U(index) - | V128Load32x2S(index) - | V128Load32x2U(index) - | V128Load8Splat(index) - | V128Load16Splat(index) - | V128Load32Splat(index) - | V128Load64Splat(index) - | V128Load32Zero(index) - | V128Load64Zero(index) - | V128Store(index) => Some(index.get(data).mem_addr()), - V128Load8Lane(arg) | V128Load16Lane(arg) | V128Load32Lane(arg) | V128Load64Lane(arg) - | V128Store8Lane(arg) | V128Store16Lane(arg) | V128Store32Lane(arg) | V128Store64Lane(arg) => { - Some(arg.memory_arg_idx.get(data).mem_addr()) - } - FMaStoreF32(arg) | FMaStoreF64(arg) => Some(arg.mem_addr()), - MemorySize(memory) | MemoryGrow(memory) | MemoryFill(memory) => Some(memory), - MemoryFillConst(index) => Some(index.get(data).memory), - MemoryInit(index) => Some(index.get(data).second), - MemoryCopy(index) => { - let value = index.get(data); - Some(value.first.max(value.second)) - } - _ => None, - } - } -} - #[cfg(test)] mod tests { use alloc::vec; diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index bd92753..d1f7453 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -133,9 +133,6 @@ pub struct ModuleInner { /// /// Corresponds to the `elem` section of the original WebAssembly module. pub elements: Box<[Element]>, - - /// How instantiation should prepare the module's local memories. - pub local_memory_allocation: LocalMemoryAllocation, } impl Module { @@ -297,20 +294,6 @@ pub enum ExportType<'a> { Tag(&'a FuncType), } -/// How instantiation should prepare local memories declared by the module. -#[derive(Clone, Copy, PartialEq, Eq, Default)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub enum LocalMemoryAllocation { - /// The module's local memories are unobservable and can be skipped entirely. - #[default] - Skip, - /// The module's local memories may be observed through exports, but can be delayed until first use. - Lazy, - /// The module's local memories must be allocated during instantiation. - Eager, -} - /// A WebAssembly External Kind. /// /// See @@ -614,6 +597,12 @@ impl MemoryType { } } + /// The declared maximum page count, or `None` when the memory is unbounded. + #[inline] + pub const fn page_count_max_declared(&self) -> Option { + self.page_count_max + } + #[inline] pub const fn page_size(&self) -> u64 { if let Some(page_size) = self.page_size { page_size } else { MEM_PAGE_SIZE } @@ -711,7 +700,7 @@ impl From<&ImportKind> for ExternalKind { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct Data { pub data: Box<[u8]>, - pub range: Range, + pub range: Range, pub kind: DataKind, } @@ -729,7 +718,7 @@ pub enum DataKind { pub struct Element { pub kind: ElementKind, pub items: Box<[ElementItem]>, - pub range: Range, + pub range: Range, pub ty: RefType, } diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index b338bd2..6701074 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-wasm-examples" -edition = "2021" +edition = "2024" publish = false # treat this as an independent package @@ -22,10 +22,6 @@ path = "src/print.rs" name = "tinywasm" path = "src/tinywasm.rs" -[[bin]] -name = "tinywasm_precompiled" -path = "src/tinywasm_precompiled.rs" - [[bin]] name = "tinywasm_no_std" path = "src/tinywasm_no_std.rs" @@ -41,10 +37,10 @@ path = "src/argon2id.rs" [dependencies] argon2 = { version = "0.5" } dlmalloc = { version = "0.2", features = ["global"] } -tinywasm = { path = "../../crates/tinywasm", default-features = false, features = [ - "archive", - "parser" -] } +tinywasm = { path = "../../crates/tinywasm", default-features = false, features = ["archive", "parser"] } + +[lints.clippy] +missing_safety_doc = "allow" [features] default = ["std"] diff --git a/examples/rust/build.sh b/examples/rust/build.sh index b2a6149..cbd3b27 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash cd "$(dirname "$0")" || exit -bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "tinywasm_precompiled" "argon2id") -exclude_wat=("tinywasm" "tinywasm_precompiled") +bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "argon2id") +exclude_wat=("tinywasm") out_dir="./target/wasm32-unknown-unknown/wasm" dest_dir="out" diff --git a/examples/rust/src/hello.rs b/examples/rust/src/hello.rs index 3d9f400..06ef5c9 100644 --- a/examples/rust/src/hello.rs +++ b/examples/rust/src/hello.rs @@ -19,10 +19,12 @@ pub unsafe extern "C" fn arg_size() -> i32 { #[unsafe(no_mangle)] pub unsafe extern "C" fn hello(len: i32) { - let arg = core::str::from_utf8(&ARG[0..len as usize]).unwrap(); - let res = format!("Hello, {}!", arg).as_bytes().to_vec(); + unsafe { + let arg = core::str::from_utf8(&ARG[0..len as usize]).unwrap(); + let res = format!("Hello, {}!", arg).as_bytes().to_vec(); - let len = res.len() as i32; - let ptr = res.leak().as_ptr() as i64; - print_utf8(ptr, len); + let len = res.len() as i32; + let ptr = res.leak().as_ptr() as i64; + print_utf8(ptr, len); + } } diff --git a/examples/rust/src/print.rs b/examples/rust/src/print.rs index d2934f0..991ea4a 100644 --- a/examples/rust/src/print.rs +++ b/examples/rust/src/print.rs @@ -7,5 +7,7 @@ unsafe extern "C" { #[unsafe(no_mangle)] pub unsafe extern "C" fn add_and_print(lh: i32, rh: i32) { - printi32(lh + rh); + unsafe { + printi32(lh + rh); + } } diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm index f0fa9a8..7841329 100644 Binary files a/examples/rust/src/print.twasm and b/examples/rust/src/print.twasm differ diff --git a/examples/rust/src/tinywasm_precompiled.rs b/examples/rust/src/tinywasm_precompiled.rs deleted file mode 100644 index bc0e0c1..0000000 --- a/examples/rust/src/tinywasm_precompiled.rs +++ /dev/null @@ -1,30 +0,0 @@ -#![no_main] -use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance}; - -#[link(wasm_import_module = "env")] -unsafe extern "C" { - fn printi32(x: i32); -} - -#[unsafe(no_mangle)] -pub extern "C" fn hello() { - let _ = run(); -} - -fn run() -> tinywasm::Result<()> { - let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?; - let mut store = tinywasm::Store::default(); - - let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { - unsafe { printi32(v) } - Ok(()) - }); - - let mut imports = tinywasm::Imports::new(); - imports.define("env", "printi32", printi32); - - let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; - let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?; - add_and_print.call(&mut store, (1, 2))?; - Ok(()) -} diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs index b3398f8..0cfb0ce 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -35,7 +35,6 @@ fn main() -> Result<()> { println!(" host_fn"); println!(" fibonacci - calculate fibonacci(30)"); println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); - println!(" tinywasm_precompiled - run a precompiled module inside of tinywasm"); println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); println!(" argon2id - run argon2id(1000, 2, 1)"); return Ok(()); @@ -46,7 +45,6 @@ fn main() -> Result<()> { "printi32" => printi32()?, "fibonacci" => fibonacci()?, "tinywasm" => tinywasm()?, - "tinywasm_precompiled" => tinywasm_precompiled()?, "tinywasm_no_std" => tinywasm_no_std()?, "argon2id" => argon2id()?, "host_fn" => host_fn()?, @@ -60,8 +58,6 @@ fn main() -> Result<()> { fibonacci()?; println!("\ntinywasm.wasm:"); tinywasm()?; - println!("\ntinywasm_precompiled.wasm:"); - tinywasm_precompiled()?; println!("\ntinywasm_no_std.wasm:"); tinywasm_no_std()?; println!("argon2id.wasm:"); @@ -105,21 +101,6 @@ fn tinywasm_no_std() -> Result<()> { Ok(()) } -fn tinywasm_precompiled() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/tinywasm_precompiled.opt.wasm")?; - let mut store = Store::default(); - - let mut imports = Imports::new(); - imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; - - let hello = instance.func::<(), ()>(&store, "hello")?; - hello.call(&mut store, black_box(()))?; - hello.call(&mut store, black_box(()))?; - hello.call(&mut store, black_box(()))?; - Ok(()) -} - fn hello() -> Result<()> { let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?; let mut store = Store::default(); @@ -231,11 +212,6 @@ mod tests { tinywasm().unwrap(); } - #[test] - fn test_tinywasm_precompiled() { - tinywasm_precompiled().unwrap(); - } - #[test] fn test_tinywasm_no_std() { tinywasm_no_std().unwrap(); -- cgit v1.3.1 From 843e0ff5601479239791f452bec9865df779839b Mon Sep 17 00:00:00 2001 From: Henry Date: Thu, 27 Aug 2026 16:06:57 +0200 Subject: chore: simplify operands, extract more exec_ methods Signed-off-by: Henry --- benches/fibonacci.rs | 2 +- crates/parser/src/conversion.rs | 22 +- crates/parser/src/lib.rs | 4 +- crates/parser/src/macros.rs | 17 +- crates/parser/src/module.rs | 24 +- crates/parser/src/optimize/rewrite.rs | 284 ++-- crates/parser/src/optimize/targets.rs | 193 +-- crates/parser/src/visit.rs | 198 +-- crates/tinywasm/src/func/context.rs | 10 +- crates/tinywasm/src/func/host.rs | 10 +- crates/tinywasm/src/instance.rs | 24 +- crates/tinywasm/src/interpreter/executor.rs | 1385 ++++++++++++-------- crates/tinywasm/src/interpreter/num_helpers.rs | 23 +- crates/tinywasm/src/interpreter/simd/macros.rs | 21 +- .../tinywasm/src/interpreter/stack/value_stack.rs | 8 +- crates/tinywasm/src/interpreter/values.rs | 134 +- crates/tinywasm/src/macros.rs | 18 + crates/tinywasm/src/store/global.rs | 6 +- crates/tinywasm/src/store/mod.rs | 7 +- crates/tinywasm/src/store/state.rs | 4 +- crates/types/src/archive.rs | 12 +- crates/types/src/instructions.rs | 576 ++++---- crates/types/src/lib.rs | 3 + crates/types/src/operands.rs | 386 ++++-- crates/types/src/reference.rs | 3 +- examples/rust/build.sh | 4 + examples/rust/src/print.twasm | Bin 154 -> 155 bytes 27 files changed, 1942 insertions(+), 1436 deletions(-) (limited to 'examples/rust/src') diff --git a/benches/fibonacci.rs b/benches/fibonacci.rs index 51fd2d3..699dc79 100644 --- a/benches/fibonacci.rs +++ b/benches/fibonacci.rs @@ -44,7 +44,7 @@ fn criterion_benchmark(c: &mut Criterion) { group.bench_function("fibonacci_from_twasm", |b| b.iter(|| fibonacci_from_twasm(&twasm))); group.measurement_time(std::time::Duration::from_secs(10)); - group.bench_function("fibonacci_iterative_60", |b| b.iter(|| fibonacci_run(module.clone(), false, 60))); + group.bench_function("fibonacci_iterative_100", |b| b.iter(|| fibonacci_run(module.clone(), false, 100))); group.bench_function("fibonacci_recursive_26", |b| b.iter(|| fibonacci_run(module.clone(), true, 26))); } diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 225b6ae..4cf0d02 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -186,9 +186,9 @@ pub(crate) fn convert_module_code( } #[cfg(feature = "validate")] - let (body, data, validator_allocs, reader_allocs) = match validator { + let (body, data, uses_local_memory, validator_allocs, reader_allocs) = match validator { Some(validator) => { - let (body, data, validator_allocs, reader_allocs) = process_operators_and_validate( + let (body, data, uses_local_memory, validator_allocs, reader_allocs) = process_operators_and_validate( validator, func, (local_types, local_addr_map), @@ -197,10 +197,10 @@ pub(crate) fn convert_module_code( reader_allocs, options.deduplicate_operands(), )?; - (body, data, Some(validator_allocs), reader_allocs) + (body, data, uses_local_memory, Some(validator_allocs), reader_allocs) } None => { - let (body, data, reader_allocs) = process_operators( + let (body, data, uses_local_memory, reader_allocs) = process_operators( func, (local_types, local_addr_map), metadata, @@ -208,13 +208,13 @@ pub(crate) fn convert_module_code( reader_allocs, options.deduplicate_operands(), )?; - (body, data, None, reader_allocs) + (body, data, uses_local_memory, None, reader_allocs) } }; #[cfg(not(feature = "validate"))] - let (body, data, validator_allocs, reader_allocs) = { + let (body, data, uses_local_memory, validator_allocs, reader_allocs) = { let _ = validator; - let (body, data, reader_allocs) = process_operators( + let (body, data, uses_local_memory, reader_allocs) = process_operators( func, (local_types, local_addr_map), metadata, @@ -222,9 +222,13 @@ pub(crate) fn convert_module_code( reader_allocs, options.deduplicate_operands(), )?; - (body, data, None, reader_allocs) + (body, data, uses_local_memory, None, reader_allocs) }; - Ok((FunctionCode { instructions: body, data, locals: local_counts }, validator_allocs, reader_allocs)) + Ok(( + FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory }, + validator_allocs, + reader_allocs, + )) } pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec) -> Result { diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 3369f7b..4954056 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -61,11 +61,11 @@ pub struct ParserOptions { /// Disable this only for trusted input. Parsing without validation may produce /// a module that violates runtime assumptions. pub validation: bool, + /// Whether to run the peephole rewrite optimizer. pub optimize_rewrite: bool, + /// Whether to deduplicate immutable function operands while parsing. - /// - /// This uses more parse CPU to reduce precompiled module and archive size. pub deduplicate_operands: bool, #[cfg(parallel_parser)] diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 5e675e6..f807c0f 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -72,7 +72,10 @@ pub(crate) mod visit { ) => { fn $visit(&mut self, memarg: wasmparser::MemArg $(, $lane: $ty)?) -> Self::Output { let address = self.metadata.memory_size(memarg.memory)?; - let memory_arg_idx = self.push_operand(MemoryArg::new(memarg.offset, memarg.memory))?; + self.mark_memory(memarg.memory); + let memory_arg_idx = self.push_operand128(tinywasm_types::Operand128::< + tinywasm_types::MemoryOperand, + >::new(memarg.offset, memarg.memory))?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] lowering_ops!(@memory_instruction $instr memory_arg_idx $(, $lane)?)) } @@ -87,7 +90,17 @@ pub(crate) mod visit { lowering_ops!(@resolved global_size $inputs => $outputs $($operator)*); }; (@memory_index $inputs:tt => $outputs:tt $($operator:tt)*) => { - lowering_ops!(@resolved memory_size $inputs => $outputs $($operator)*); + lowering_ops!(@memory_index_impl $inputs => $outputs $($operator)*); + }; + (@memory_index_impl [$($input:ident),*] => [$($output:ident),*] + $visit:ident($index:ident: $ty:ty) => $instr:ident + ) => { + fn $visit(&mut self, $index: $ty) -> Self::Output { + let address = self.metadata.memory_size($index)?; + self.mark_memory($index); + lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] + Instruction::$instr($index).into()) + } }; (@table $inputs:tt => $outputs:tt $($operator:tt)*) => { lowering_ops!(@resolved table_size $inputs => $outputs $($operator)*); diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index bfb28ce..4cd4406 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -13,12 +13,14 @@ pub(crate) struct FunctionCode { pub instructions: Vec, pub data: crate::visit::FunctionDataBuilder, pub locals: ValueCounts, + pub uses_local_memory: bool, } pub(crate) struct OptimizedFunctionCode { pub instructions: Vec, pub data: WasmFunctionData, pub locals: ValueCounts, + pub uses_local_memory: bool, } pub(crate) fn optimize_function_code( @@ -30,7 +32,12 @@ pub(crate) fn optimize_function_code( let optimized = optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; let data = code.data.finish(); - Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals }) + Ok(OptimizedFunctionCode { + instructions: optimized.instructions, + data, + locals: code.locals, + uses_local_memory: code.uses_local_memory, + }) } #[derive(Default)] @@ -535,6 +542,20 @@ impl<'a> ModuleReader<'a> { .chain(self.code_type_addrs.iter().copied()) .collect(); + let imported_memory_count = + self.imports.iter().filter(|import| matches!(import.kind, ImportKind::Memory(_))).count(); + let uses_local_memory = self.code.iter().any(|code| code.uses_local_memory); + let exports_local_memory = self + .exports + .iter() + .any(|export| export.kind == ExternalKind::Memory && export.index as usize >= imported_memory_count); + let initializes_local_memory = self + .data + .iter() + .any(|data| matches!(data.kind, DataKind::Active { mem, .. } if mem as usize >= imported_memory_count)); + let skip_local_memory_allocation = + !self.memory_types.is_empty() && !uses_local_memory && !exports_local_memory && !initializes_local_memory; + let funcs = self .code .into_iter() @@ -567,6 +588,7 @@ impl<'a> ModuleReader<'a> { exports: self.exports, elements: self.elements, memory_types: self.memory_types, + skip_local_memory_allocation, tags: self.tags, } .into()) diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs index 1146da7..d0dfb66 100644 --- a/crates/parser/src/optimize/rewrite.rs +++ b/crates/parser/src/optimize/rewrite.rs @@ -5,11 +5,9 @@ use crate::{ParserOptions, Result}; use alloc::vec::Vec; use core::ops::{Deref, DerefMut}; use tinywasm_types::{ - BinOp, BinOp128, CmpOp, CompactMemoryArg, GlobalConst32, GlobalConst64, GlobalUpdate, GlobalV128, I32LocalArg, - I64Operand, Instruction, LocalConst64, LocalConstCmp, LocalConstSet32, LocalConstSet64, LocalConstSetV128, - LocalLocalCmp, LocalTripleArg, LocalU32, LocalUpdate, LocalUpdateCmp, LocalV128, MemoryArg, MemoryFillConstOp, - MemoryLocalArg, OperandIdx, PackedOp, StackConst32, StackConst64, TargetLocal, TargetLocalArg, V128Operand, - ValueCounts, + BinOp, BinOp128, CmpOp, CompactMemoryArg, CompactMemoryOperand, GlobalUpdateOperand, I32LocalArg, Instruction, + LocalTripleArg, LocalUpdateCmpOperand, LocalUpdateOperand, MemoryFillOperand, MemoryLocalArg, MemoryOperand, + Operand64, Operand64Idx, Operand128, Operand128Idx, PackedOp, TargetLocalArg, ValueCounts, }; pub(crate) struct OptimizeResult { @@ -21,18 +19,6 @@ struct CompactOutput { block_start: usize, } -macro_rules! operand { - ($data:expr, $value:expr) => { - $data.push_operand($value) - }; -} - -macro_rules! target_operand { - ($data:expr, $value:expr) => { - $data.push_target_operand($value) - }; -} - impl Deref for CompactOutput { type Target = Vec; @@ -229,7 +215,7 @@ fn rewrite( } } MemoryFill(memory) => rewrite!(output, read, [Const32(value), Const32(size)] => { - let index = operand!(data, MemoryFillConstOp { memory, byte: value as u8, value: size })?; + let index = data.push_operand128(Operand128::::new(memory, value as u8, size))?; replace!(output, read, 2 => MemoryFillConst(index)); }), GlobalGet32(dst) => rewrite!(output, read, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), @@ -290,14 +276,13 @@ fn rewrite( for instruction in &mut output.instructions { match *instruction { Instruction::Const64(index) => { - let value = data.operand(index).value; + let value = data.operand64(index).value(); if value == i64::from(value as i32) { *instruction = Instruction::Const64Imm(value as i32); } } Instruction::Const128(index) => { - let value = u128::from_le_bytes(data.operand(index).value); - if let Ok(value) = u32::try_from(value) { + if let Ok(value) = u32::try_from(u128::from_le_bytes(data.operand128(index).value())) { *instruction = Instruction::Const128Imm(value); } } @@ -315,8 +300,8 @@ fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(B Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), Instruction::BinOpLocalConst32(packed) => { - let value = data.operand(packed.index); - Some((packed.op, value.local, value.value as i32)) + let value = data.operand64(packed.index); + Some((packed.op, value.a(), value.b() as i32)) } _ => None, } @@ -324,25 +309,25 @@ fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(B fn local_const64(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i64)> { let Instruction::BinOpLocalConst64(packed) = instruction else { return None }; - let value = data.operand(packed.index); - Some((packed.op, value.local, value.value as i64)) + let value = data.operand128(packed.index); + Some((packed.op, value.a(), value.b() as i64)) } fn local_const128( data: &WasmFunctionData, instruction: Instruction, -) -> Option<(BinOp128, u16, OperandIdx)> { +) -> Option<(BinOp128, u16, Operand128Idx<[u8; 16]>)> { let Instruction::BinOpLocalConst128(packed) = instruction else { return None }; - let value = data.operand(packed.index); - Some((packed.op, value.local, value.value)) + let value = data.operand64(packed.index); + Some((packed.op, value.a(), value.b())) } fn compact_memory_arg( data: &mut WasmFunctionData, - index: OperandIdx, -) -> Result>> { - let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) else { return Ok(None) }; - Ok(Some(operand!(data, arg)?)) + index: Operand128Idx, +) -> Result>> { + let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) else { return Ok(None) }; + Ok(Some(data.push_operand64(Operand64::from(arg))?)) } fn rewrite_scalar_const32( @@ -365,12 +350,12 @@ fn rewrite_scalar_const32( BinOp::IMul => Instruction::MulLocalConst32(arg), _ => Instruction::BinOpLocalConst32(PackedOp::new( op, - operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, )), } } [Instruction::GlobalGet32(global), Instruction::Const32(value)] => Instruction::BinOpGlobalConst32( - PackedOp::new(op, operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?), + PackedOp::new(op, data.push_operand64(Operand64::<(u32, u32)>::new(*global, *value as u32))?), ), [Instruction::Const32(value), Instruction::LocalGet32(local)] if commutative => { let arg = I32LocalArg { value: *value, local: *local }; @@ -379,14 +364,14 @@ fn rewrite_scalar_const32( BinOp::IMul => Instruction::MulLocalConst32(arg), _ => Instruction::BinOpLocalConst32(PackedOp::new( op, - operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, )), } } [Instruction::Const32(value), Instruction::GlobalGet32(global)] if commutative => { Instruction::BinOpGlobalConst32(PackedOp::new( op, - operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?, + data.push_operand64(Operand64::<(u32, u32)>::new(*global, *value as u32))?, )) } _ => return Ok(false), @@ -409,18 +394,24 @@ fn rewrite_scalar_const64( let replacement = match previous { [Instruction::LocalGet64(local), Instruction::Const64(index)] => Instruction::BinOpLocalConst64(PackedOp::new( op, - operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?, + data.push_operand128(Operand128::<(u16, u64)>::new(local, data.operand64(index).value() as u64))?, )), - [Instruction::GlobalGet64(global), Instruction::Const64(index)] => Instruction::BinOpGlobalConst64( - PackedOp::new(op, operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?), - ), - [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => Instruction::BinOpLocalConst64( - PackedOp::new(op, operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?), - ), + [Instruction::GlobalGet64(global), Instruction::Const64(index)] => { + Instruction::BinOpGlobalConst64(PackedOp::new( + op, + data.push_operand128(Operand128::<(u32, u64)>::new(global, data.operand64(index).value() as u64))?, + )) + } + [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => { + Instruction::BinOpLocalConst64(PackedOp::new( + op, + data.push_operand128(Operand128::<(u16, u64)>::new(local, data.operand64(index).value() as u64))?, + )) + } [Instruction::Const64(index), Instruction::GlobalGet64(global)] if commutative => { Instruction::BinOpGlobalConst64(PackedOp::new( op, - operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?, + data.push_operand128(Operand128::<(u32, u64)>::new(global, data.operand64(index).value() as u64))?, )) } _ => return Ok(false), @@ -455,7 +446,7 @@ fn rewrite_sign_extend64(output: &mut CompactOutput, read: &mut usize, data: &Wa } if let Some((BinOp::IShl, local, shift)) = local_const64(data, output[*read - 2]) && let Instruction::Const64(index) = output[*read - 1] - && shift == data.operand(index).value + && shift == data.operand64(index).value() { let instruction = match shift { 56 => Instruction::I64Extend8S, @@ -482,17 +473,26 @@ fn rewrite_vector_binop( let previous = [output[*read - 2], output[*read - 1]]; let replacement = match previous { [Instruction::LocalGet128(a), Instruction::LocalGet128(b)] => Instruction::BinOpLocalLocal128(op, a, b), - [Instruction::LocalGet128(local), Instruction::Const128(value)] => { - Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) - } + [Instruction::LocalGet128(local), Instruction::Const128(value)] => Instruction::BinOpLocalConst128( + PackedOp::new(op, data.push_operand64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?), + ), [Instruction::GlobalGet128(global), Instruction::Const128(value)] => { - Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + Instruction::BinOpGlobalConst128(PackedOp::new( + op, + data.push_operand64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?, + )) } [Instruction::Const128(value), Instruction::LocalGet128(local)] if commutative => { - Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) + Instruction::BinOpLocalConst128(PackedOp::new( + op, + data.push_operand64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?, + )) } [Instruction::Const128(value), Instruction::GlobalGet128(global)] if commutative => { - Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + Instruction::BinOpGlobalConst128(PackedOp::new( + op, + data.push_operand64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?, + )) } _ => return Ok(()), }; @@ -505,9 +505,13 @@ fn rewrite_store32( output: &mut CompactOutput, read: &mut usize, data: &mut WasmFunctionData, - index: OperandIdx, + index: Operand128Idx, ) -> Result<()> { - let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + let compact_arg = CompactMemoryArg::try_from(data.operand128(index)).ok(); + if *read > output.block_start && output[*read - 1] == Instruction::Select32 { + replace!(output, *read, 1 => Instruction::SelectStore32(index)); + return Ok(()); + } if *read >= output.block_start + 3 { let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; if let [ @@ -515,7 +519,7 @@ fn rewrite_store32( Instruction::LoadLocal32(arg), Instruction::AddConst32(1), ] = previous - && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) } && addr == u16::from(arg.local1) { replace!(output, *read, 3 => Instruction::IncMemoryLocal32(arg)); @@ -526,12 +530,12 @@ fn rewrite_store32( let previous = [output[*read - 2], output[*read - 1]]; match previous { [Instruction::F32Mul, Instruction::F32Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => { replace!(output, *read, 2 => Instruction::FMaStoreF32(arg)); } [Instruction::BinOpStackLocal32(BinOp::FMul, local), Instruction::F32Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => { replace!(output, *read, 2 => [Instruction::LocalGet32(local), Instruction::FMaStoreF32(arg)]); } @@ -539,7 +543,7 @@ fn rewrite_store32( if let (Ok(addr), Ok(value), Some(memory_arg)) = (u8::try_from(addr), u8::try_from(value), compact_arg) => { - let memory_arg_idx = operand!(data, memory_arg)?; + let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; replace!(output, *read, 2 => Instruction::StoreLocalLocal32(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); } _ => {} @@ -552,9 +556,13 @@ fn rewrite_store64( output: &mut CompactOutput, read: &mut usize, data: &mut WasmFunctionData, - index: OperandIdx, + index: Operand128Idx, ) -> Result<()> { - let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + let compact_arg = CompactMemoryArg::try_from(data.operand128(index)).ok(); + if *read > output.block_start && output[*read - 1] == Instruction::Select64 { + replace!(output, *read, 1 => Instruction::SelectStore64(index)); + return Ok(()); + } if *read >= output.block_start + 3 { let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; if let [ @@ -562,9 +570,9 @@ fn rewrite_store64( Instruction::LoadLocal64(arg), Instruction::Const64(one), ] = previous - && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) } && addr == u16::from(arg.local1) - && data.operand(one).value == 1 + && data.operand64(one).value() == 1 { replace!(output, *read, 3 => Instruction::IncMemoryLocal64(arg)); return Ok(()); @@ -573,7 +581,7 @@ fn rewrite_store64( if *read >= output.block_start + 2 { match [output[*read - 2], output[*read - 1]] { [Instruction::F64Mul, Instruction::F64Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => { replace!(output, *read, 2 => Instruction::FMaStoreF64(arg)); } @@ -581,7 +589,7 @@ fn rewrite_store64( if let (Ok(addr), Ok(value), Some(memory_arg)) = (u8::try_from(addr), u8::try_from(value), compact_arg) => { - let memory_arg_idx = operand!(data, memory_arg)?; + let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; replace!(output, *read, 2 => Instruction::StoreLocalLocal64(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); } _ => {} @@ -592,7 +600,7 @@ fn rewrite_store64( macro_rules! local_const_set { ($data:expr, 32, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = operand!($data, LocalConstSet32 { local: $src, dst: $dst, value: $value as u32 })?; + let index = $data.push_operand64(Operand64::<(u16, u16, u32)>::new($src, $dst, $value as u32))?; if $tee { Instruction::BinOpLocalConstTee32(PackedOp::new($op, index)) } else { @@ -600,7 +608,7 @@ macro_rules! local_const_set { } }}; ($data:expr, 64, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = operand!($data, LocalConstSet64 { local: $src, dst: $dst, value: $value as u64 })?; + let index = $data.push_operand128(Operand128::<(u16, u16, u64)>::new($src, $dst, $value as u64))?; if $tee { Instruction::BinOpLocalConstTee64(PackedOp::new($op, index)) } else { @@ -608,7 +616,7 @@ macro_rules! local_const_set { } }}; ($data:expr, 128, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = operand!($data, LocalConstSetV128 { local: $src, dst: $dst, value: $value })?; + let index = $data.push_operand64(Operand64::<(u16, u16, Operand128Idx<[u8; 16]>)>::new($src, $dst, $value))?; if $tee { Instruction::BinOpLocalConstTee128(PackedOp::new($op, index)) } else { @@ -653,7 +661,7 @@ fn rewrite_local_set32( } else { Instruction::BinOpLocalLocalSet32(PackedOp::new( op, - operand!(data, LocalTripleArg { left, right, dst })?, + data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?, )) }; replace!(output, *read, 1 => replacement); @@ -728,13 +736,13 @@ fn rewrite_local_set64( replace!(output, *read, 1 => Instruction::SetLocalConst64(PackedOp::new(dst, index))); } Instruction::BinOpLocalLocal64(op, left, right) => { - let index = operand!(data, LocalTripleArg { left, right, dst })?; + let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet64(PackedOp::new(op, index))); } instruction if let Some((op, src, value)) = local_const64(data, instruction) => { if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) { let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() }; - let index = operand!(data, I64Operand { value: delta })?; + let index = data.push_operand64(Operand64::::new(delta))?; replace!(output, *read, 1 => Instruction::IncLocal64(PackedOp::new(dst, index))); } else { let replacement = local_const_set!(data, 64, op, src, dst, value, false); @@ -756,9 +764,9 @@ fn rewrite_local_set128( if *read >= output.block_start + 2 && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] && let (Ok(local), Ok(dst), Ok(memory_arg)) = - (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index))) { - let memory_arg_idx = operand!(data, memory_arg)?; + let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; replace!(output, *read, 2 => Instruction::LoadLocalSet128(MemoryLocalArg { memory_arg_idx, local1: local, @@ -778,7 +786,7 @@ fn rewrite_local_set128( replace!(output, *read, 1 => Instruction::SetLocalConst128(PackedOp::new(dst, value))) } Instruction::BinOpLocalLocal128(op, left, right) => { - let index = operand!(data, LocalTripleArg { left, right, dst })?; + let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet128(PackedOp::new(op, index))); } instruction if let Some((op, src, value)) = local_const128(data, instruction) => { @@ -819,7 +827,7 @@ fn rewrite_local_tee32( } else { Instruction::BinOpLocalLocalTee32(PackedOp::new( op, - operand!(data, LocalTripleArg { left, right, dst })?, + data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?, )) }; replace!(output, *read, 1 => replacement); @@ -880,7 +888,7 @@ fn rewrite_local_tee64( match output[*read - 1] { Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)), Instruction::BinOpLocalLocal64(op, left, right) => { - let index = operand!(data, LocalTripleArg { left, right, dst })?; + let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee64(PackedOp::new(op, index))); } instruction if let Some((op, src, value)) = local_const64(data, instruction) => { @@ -902,9 +910,9 @@ fn rewrite_local_tee128( if *read >= output.block_start + 2 && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] && let (Ok(local), Ok(dst), Ok(memory_arg)) = - (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index))) { - let memory_arg_idx = operand!(data, memory_arg)?; + let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; replace!(output, *read, 2 => Instruction::LoadLocalTee128(MemoryLocalArg { memory_arg_idx, local1: local, @@ -916,7 +924,7 @@ fn rewrite_local_tee128( match output[*read - 1] { Instruction::LocalGet128(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet128(src)), Instruction::BinOpLocalLocal128(op, left, right) => { - let index = operand!(data, LocalTripleArg { left, right, dst })?; + let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee128(PackedOp::new(op, index))); } instruction if let Some((op, src, value)) = local_const128(data, instruction) => { @@ -995,7 +1003,7 @@ fn jump_cmp_local_local( op: CmpOp, width64: bool, ) -> Result { - let index = target_operand!(data, LocalLocalCmp { target, left, right })?; + let index = data.push_target_operand64(Operand64::<(u32, u16, u16)>::new(target, left, right))?; Ok(if width64 { Instruction::JumpCmpLocalLocal64(PackedOp::new(op, index)) } else { @@ -1017,17 +1025,17 @@ fn rewrite_jump( if let Some(instruction) = source.get(target as usize).copied() { match instruction { Instruction::JumpCmpLocalLocal32(side) - if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + if resolve_jump_target(source, data, data.operand64(side.index).a()) == exit && body > target => { - let value = data.operand(side.index); - output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), false)?; + let value = data.operand64(side.index); + output[index] = jump_cmp_local_local(data, body, value.b(), value.c(), side.op.inverse(), false)?; return Ok(()); } Instruction::JumpCmpLocalLocal64(side) - if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + if resolve_jump_target(source, data, data.operand64(side.index).a()) == exit && body > target => { - let value = data.operand(side.index); - output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), true)?; + let value = data.operand64(side.index); + output[index] = jump_cmp_local_local(data, body, value.b(), value.c(), side.op.inverse(), true)?; return Ok(()); } _ => {} @@ -1048,7 +1056,7 @@ fn jump_cmp_stack_local( op: CmpOp, width64: bool, ) -> Result { - let index = target_operand!(data, TargetLocal { target, local })?; + let index = data.push_target_operand64(Operand64::<(u32, u16)>::new(target, local))?; Ok(if width64 { Instruction::JumpCmpStackLocal64(PackedOp::new(op, index)) } else { @@ -1069,13 +1077,13 @@ fn jump_cmp_local_const32( CmpOp::Ne => Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }), _ => Instruction::JumpCmpLocalConst32(PackedOp::new( op, - target_operand!(data, LocalConstCmp { target, value, local })?, + data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, )), }); } Ok(Instruction::JumpCmpLocalConst32(PackedOp::new( op, - target_operand!(data, LocalConstCmp { target, value, local })?, + data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, ))) } @@ -1095,7 +1103,7 @@ fn jump_cmp_local_const64( } Ok(Instruction::JumpCmpLocalConst64(PackedOp::new( op, - target_operand!(data, LocalConstCmp { target, value, local })?, + data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, ))) } @@ -1107,7 +1115,10 @@ fn jump_cmp_stack_const32(data: &mut WasmFunctionData, target: u32, value: i32, _ => {} } } - Ok(Instruction::JumpCmpStackConst32(PackedOp::new(op, target_operand!(data, StackConst32 { target, value })?))) + Ok(Instruction::JumpCmpStackConst32(PackedOp::new( + op, + data.push_target_operand64(Operand64::<(u32, i32)>::new(target, value))?, + ))) } fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, op: CmpOp) -> Result { @@ -1118,7 +1129,10 @@ fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, _ => {} } } - Ok(Instruction::JumpCmpStackConst64(PackedOp::new(op, target_operand!(data, StackConst64 { target, value })?))) + Ok(Instruction::JumpCmpStackConst64(PackedOp::new( + op, + data.push_target_operand128(Operand128::<(u32, i64)>::new(target, value))?, + ))) } fn update_jump( @@ -1132,32 +1146,34 @@ fn update_jump( ) -> Result { if let Some(delta) = op.inc_delta(immediate) { Ok(if global { - Instruction::IncGlobalJump32(target_operand!( - data, - GlobalUpdate { target, value: delta, global: address, on_zero: u8::from(on_zero) } - )?) + Instruction::IncGlobalJump32( + data.push_target_operand128(Operand128::::new(target, delta, address, on_zero))?, + ) } else { - Instruction::IncLocalJump32(target_operand!( - data, - LocalUpdate { target, value: delta, local: address as u16, on_zero: u8::from(on_zero) } - )?) + Instruction::IncLocalJump32(data.push_target_operand128(Operand128::::new( + target, + delta, + address as u16, + on_zero, + ))?) }) } else { Ok(if global { Instruction::BinOpGlobalConstJump32(PackedOp::new( op, - target_operand!( - data, - GlobalUpdate { target, value: immediate, global: address, on_zero: u8::from(on_zero) } - )?, + data.push_target_operand128(Operand128::::new( + target, immediate, address, on_zero, + ))?, )) } else { Instruction::BinOpLocalConstJump32(PackedOp::new( op, - target_operand!( - data, - LocalUpdate { target, value: immediate, local: address as u16, on_zero: u8::from(on_zero) } - )?, + data.push_target_operand128(Operand128::::new( + target, + immediate, + address as u16, + on_zero, + ))?, )) }) } @@ -1175,10 +1191,10 @@ fn rewrite_conditional( if *read > output.block_start && let Instruction::BinOpLocalConstTee32(packed) = output[*read - 1] { - let value = data.operand(packed.index); - if value.local == value.dst { + let value = data.operand64(packed.index); + if value.a() == value.b() { let replacement = - update_jump(data, target, value.value as i32, u32::from(value.local), packed.op, on_zero, false)?; + update_jump(data, target, value.c() as i32, u32::from(value.a()), packed.op, on_zero, false)?; replace!(output, *read, 1 => replacement); return Ok(()); } @@ -1187,9 +1203,9 @@ fn rewrite_conditional( && let [Instruction::BinOpGlobalConst32(packed), Instruction::GlobalTee32(dst)] = [output[*read - 2], output[*read - 1]] { - let value = data.operand(packed.index); - if value.global == dst { - let replacement = update_jump(data, target, value.value as i32, dst, packed.op, on_zero, true)?; + let value = data.operand64(packed.index); + if value.a() == dst { + let replacement = update_jump(data, target, value.b() as i32, dst, packed.op, on_zero, true)?; replace!(output, *read, 2 => replacement); return Ok(()); } @@ -1199,10 +1215,10 @@ fn rewrite_conditional( [output[*read - 3], output[*read - 2], output[*read - 1]] && local == cond { - let replacement = Instruction::IncStackTeeLocalJump32(target_operand!( - data, - LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } - )?); + let replacement = + Instruction::IncStackTeeLocalJump32( + data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, + ); replace!(output, *read, 3 => replacement); return Ok(()); } @@ -1220,13 +1236,12 @@ fn rewrite_conditional( let replacement = if let Some(op) = op { Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( op, - target_operand!(data, LocalUpdate { target, value, local, on_zero: u8::from(on_zero) })?, + data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, )) } else { - Instruction::IncStackTeeLocalJump32(target_operand!( - data, - LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } - )?) + Instruction::IncStackTeeLocalJump32( + data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, + ) }; replace!(output, *read, 2 => replacement); return Ok(()); @@ -1237,23 +1252,30 @@ fn rewrite_conditional( [output[*read - 3], output[*read - 2], output[*read - 1]] && let Some(mut cmp) = cmp_op(raw_cmp) { - let value = data.operand(packed.index); - if value.local == value.dst { + let value = data.operand64(packed.index); + if value.a() == value.b() { if on_zero { cmp = cmp.inverse(); } - let replacement = if let Some(delta) = packed.op.inc_delta(value.value as i32) { + let replacement = if let Some(delta) = packed.op.inc_delta(value.c() as i32) { Instruction::IncLocalJumpCmpLocal32(PackedOp::new( cmp, - target_operand!(data, LocalUpdateCmp { target, value: delta, local: value.local, right })?, + data.push_target_operand128(Operand128::::new( + target, + delta, + value.a(), + right, + ))?, )) } else { Instruction::BinOpLocalConstJumpCmpLocal32(PackedOp::new( (packed.op, cmp), - target_operand!( - data, - LocalUpdateCmp { target, value: value.value as i32, local: value.local, right } - )?, + data.push_target_operand128(Operand128::::new( + target, + value.c() as i32, + value.a(), + right, + ))?, )) }; replace!(output, *read, 3 => replacement); @@ -1334,7 +1356,7 @@ fn rewrite_conditional( Some(jump_cmp_local_const32(data, target, local, value, op)?) } [Instruction::LocalGet64(local), Instruction::Const64(index)] - if let Ok(value) = i32::try_from(data.operand(index).value) => + if let Ok(value) = i32::try_from(data.operand64(index).value()) => { Some(jump_cmp_local_const64(data, target, local, value, op)?) } @@ -1363,7 +1385,7 @@ fn rewrite_conditional( Instruction::LocalGet64(local) => Some(jump_cmp_stack_local(data, target, local, op, true)?), Instruction::Const32(value) => Some(jump_cmp_stack_const32(data, target, value, op)?), Instruction::Const64(index) => { - Some(jump_cmp_stack_const64(data, target, data.operand(index).value, op)?) + Some(jump_cmp_stack_const64(data, target, data.operand64(index).value(), op)?) } _ => None, }; diff --git a/crates/parser/src/optimize/targets.rs b/crates/parser/src/optimize/targets.rs index 36bdf2f..c6b2252 100644 --- a/crates/parser/src/optimize/targets.rs +++ b/crates/parser/src/optimize/targets.rs @@ -1,35 +1,7 @@ -use crate::visit::{BuilderRawOperand, FunctionDataBuilder}; +use crate::visit::FunctionDataBuilder; use crate::{ParseError, Result}; use alloc::vec::Vec; -use tinywasm_types::{ - BranchTableArg, CastBranch, GlobalUpdate, Instruction, LocalConstCmp, LocalLocalCmp, LocalUpdate, LocalUpdateCmp, - OperandIdx, OperandType, PackedOp, StackConst32, StackConst64, TargetLocal, -}; - -pub(super) trait TargetOperand: OperandType { - fn set_target(&mut self, target: u32); -} - -macro_rules! target_operands { - ($($name:ty),+ $(,)?) => {$( - impl TargetOperand for $name { - fn set_target(&mut self, target: u32) { self.target = target; } - } - )+}; -} - -target_operands!( - TargetLocal, - CastBranch, - StackConst32, - StackConst64, - LocalUpdate, - GlobalUpdate, - LocalUpdateCmp, - LocalConstCmp, - LocalLocalCmp, - BranchTableArg, -); +use tinywasm_types::{Instruction, PackedOp}; pub(super) fn resolve_jump_target(instructions: &[Instruction], data: &FunctionDataBuilder, target: u32) -> u32 { let mut index = target as usize; @@ -50,58 +22,37 @@ pub(super) fn set_rewrite_target( data: &mut FunctionDataBuilder, target: u32, ) -> Result<()> { + macro_rules! rewrite_target { + ($slot:ident, operand64) => {{ data.push_target_operand64(data.operand64(*$slot).with_target(target))? }}; + ($slot:ident, operand128) => {{ data.push_target_operand128(data.operand128(*$slot).with_target(target))? }}; + ($slot:ident, packed64) => {{ PackedOp::new($slot.op, data.push_target_operand64(data.operand64($slot.index).with_target(target))?) }}; + ($slot:ident, packed128) => {{ PackedOp::new($slot.op, data.push_target_operand128(data.operand128($slot.index).with_target(target))?) }}; + } + use Instruction::*; match instruction { - JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => { - *packed = push_packed_target_copy(data, *packed, target)? - } - BrOnCast(index) | BrOnCastFail(index) => *index = push_target_copy(data, *index, target)?, - JumpCmpStackConst32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, - JumpCmpStackConst64(packed) => *packed = push_packed_target_copy(data, *packed, target)?, - BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { - *packed = push_packed_target_copy(data, *packed, target)? - } - BinOpLocalConstJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, - BinOpGlobalConstJump32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, - IncLocalJump32(index) | IncStackTeeLocalJump32(index) => *index = push_target_copy(data, *index, target)?, - IncGlobalJump32(index) => *index = push_target_copy(data, *index, target)?, - IncLocalJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, - JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => { - *packed = push_packed_target_copy(data, *packed, target)? - } - JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => { - *packed = push_packed_target_copy(data, *packed, target)? - } - BranchTable(index) => *index = push_target_copy(data, *index, target)?, + JumpCmpStackLocal32(packed) => *packed = rewrite_target!(packed, packed64), + JumpCmpStackLocal64(packed) => *packed = rewrite_target!(packed, packed64), + BrOnCast(index) | BrOnCastFail(index) => *index = rewrite_target!(index, operand64), + JumpCmpStackConst32(packed) => *packed = rewrite_target!(packed, packed64), + JumpCmpStackConst64(packed) => *packed = rewrite_target!(packed, packed128), + BinOpStackConstTeeLocalJump32(packed) => *packed = rewrite_target!(packed, packed128), + BinOpLocalConstJump32(packed) => *packed = rewrite_target!(packed, packed128), + BinOpLocalConstJumpCmpLocal32(packed) => *packed = rewrite_target!(packed, packed128), + BinOpGlobalConstJump32(packed) => *packed = rewrite_target!(packed, packed128), + IncLocalJump32(index) => *index = rewrite_target!(index, operand128), + IncStackTeeLocalJump32(index) => *index = rewrite_target!(index, operand128), + IncGlobalJump32(index) => *index = rewrite_target!(index, operand128), + IncLocalJumpCmpLocal32(packed) => *packed = rewrite_target!(packed, packed128), + JumpCmpLocalConst32(packed) => *packed = rewrite_target!(packed, packed128), + JumpCmpLocalConst64(packed) => *packed = rewrite_target!(packed, packed128), + JumpCmpLocalLocal32(packed) => *packed = rewrite_target!(packed, packed64), + JumpCmpLocalLocal64(packed) => *packed = rewrite_target!(packed, packed64), + BranchTable(index) => *index = rewrite_target!(index, operand128), _ => set_target(instruction, data, target), } - Ok(()) -} -fn push_target_copy( - data: &mut FunctionDataBuilder, - index: OperandIdx, - target: u32, -) -> Result> -where - T::Raw: BuilderRawOperand, -{ - let mut value = data.operand(index); - value.set_target(target); - data.push_target_operand(value) -} - -fn push_packed_target_copy( - data: &mut FunctionDataBuilder, - packed: PackedOp, - target: u32, -) -> Result> -where - T::Raw: BuilderRawOperand, -{ - let mut value = data.operand(packed.index); - value.set_target(target); - Ok(PackedOp::new(packed.op, data.push_target_operand(value)?)) + Ok(()) } fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> Option { @@ -117,24 +68,31 @@ fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> O JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { arg.target_ip } - JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand(packed.index).target, - BrOnCast(index) | BrOnCastFail(index) => data.operand(index).target, - JumpCmpStackConst32(packed) => data.operand(packed.index).target, - JumpCmpStackConst64(packed) => data.operand(packed.index).target, - BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand(packed.index).target, - BinOpLocalConstJumpCmpLocal32(packed) => data.operand(packed.index).target, - BinOpGlobalConstJump32(packed) => data.operand(packed.index).target, - IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand(index).target, - IncGlobalJump32(index) => data.operand(index).target, - IncLocalJumpCmpLocal32(packed) => data.operand(packed.index).target, - JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand(packed.index).target, - JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand(packed.index).target, - BranchTable(index) => data.operand(index).target, + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand64(packed.index).target(), + BrOnCast(index) | BrOnCastFail(index) => data.operand64(index).target(), + JumpCmpStackConst32(packed) => data.operand64(packed.index).target(), + JumpCmpStackConst64(packed) => data.operand128(packed.index).target(), + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand128(packed.index).target(), + BinOpLocalConstJumpCmpLocal32(packed) => data.operand128(packed.index).target(), + BinOpGlobalConstJump32(packed) => data.operand128(packed.index).target(), + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand128(index).target(), + IncGlobalJump32(index) => data.operand128(index).target(), + IncLocalJumpCmpLocal32(packed) => data.operand128(packed.index).target(), + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand128(packed.index).target(), + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand64(packed.index).target(), + BranchTable(index) => data.operand128(index).target(), _ => return None, }) } fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) { + macro_rules! set_target { + ($index:expr, operand64) => {{ data.set_operand64($index, data.operand64($index).with_target(target)) }}; + ($index:expr, operand128) => {{ data.set_operand128($index, data.operand128($index).with_target(target)) }}; + ($packed:expr, packed64) => {{ data.set_operand64($packed.index, data.operand64($packed.index).with_target(target)) }}; + ($packed:expr, packed128) => {{ data.set_operand128($packed.index, data.operand128($packed.index).with_target(target)) }}; + } + use Instruction::*; match instruction { Jump(value) @@ -144,53 +102,32 @@ fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, tar | JumpIfNonZero64(value) | JumpIfRefNull(value) | JumpIfRefNonNull(value) => *value = target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { arg.target_ip = target } - JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_packed_operand_target(data, *packed, target), - BrOnCast(index) | BrOnCastFail(index) => set_operand_target(data, *index, target), - JumpCmpStackConst32(packed) => set_packed_operand_target(data, *packed, target), - JumpCmpStackConst64(packed) => set_packed_operand_target(data, *packed, target), - BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { - set_packed_operand_target(data, *packed, target) - } - BinOpLocalConstJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), - BinOpGlobalConstJump32(packed) => set_packed_operand_target(data, *packed, target), - IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_operand_target(data, *index, target), - IncGlobalJump32(index) => set_operand_target(data, *index, target), - IncLocalJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), - JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_packed_operand_target(data, *packed, target), - JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_packed_operand_target(data, *packed, target), - BranchTable(index) => set_operand_target(data, *index, target), + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_target!(*packed, packed64), + BrOnCast(index) | BrOnCastFail(index) => set_target!(*index, operand64), + JumpCmpStackConst32(packed) => set_target!(*packed, packed64), + JumpCmpStackConst64(packed) => set_target!(*packed, packed128), + BinOpLocalConstJump32(packed) => set_target!(*packed, packed128), + BinOpStackConstTeeLocalJump32(packed) => set_target!(*packed, packed128), + BinOpLocalConstJumpCmpLocal32(packed) => set_target!(*packed, packed128), + BinOpGlobalConstJump32(packed) => set_target!(*packed, packed128), + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_target!(*index, operand128), + IncGlobalJump32(index) => set_target!(*index, operand128), + IncLocalJumpCmpLocal32(packed) => set_target!(*packed, packed128), + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_target!(*packed, packed128), + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_target!(*packed, packed64), + BranchTable(index) => set_target!(*index, operand128), _ => {} } } -fn set_operand_target(data: &mut FunctionDataBuilder, index: OperandIdx, target: u32) -where - T::Raw: BuilderRawOperand, -{ - let mut value = data.operand(index); - value.set_target(target); - data.set_operand(index, value); -} - -fn set_packed_operand_target( - data: &mut FunctionDataBuilder, - packed: PackedOp, - target: u32, -) where - T::Raw: BuilderRawOperand, -{ - let mut value = data.operand(packed.index); - value.set_target(target); - data.set_operand(packed.index, value); -} - fn branch_table_range(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(u32, u32)> { let Instruction::BranchTable(index) = instruction else { return None }; - let operand = data.operand(index); - Some((operand.start, operand.len)) + let operand = data.operand128(index); + Some((operand.start(), operand.size())) } pub(super) fn target_boundaries(instructions: &[Instruction], data: &FunctionDataBuilder) -> Result> { diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index b65f77c..724c1bf 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -5,9 +5,9 @@ use crate::{ }; use alloc::{boxed::Box, collections::BTreeMap, string::ToString, vec::Vec}; use tinywasm_types::{ - BranchTableArg, CastBranch, ExceptionHandler, Global, I64Operand, Import, ImportKind, Instruction, MemoryArg, - MemoryType, Operand64, Operand128, OperandIdx, OperandType, StorageType, TableDefinition, TagType, TwoU32, - TypeSection, V128Operand, ValueCounts, ValueLane, WasmFunctionData, + BranchTableOperand, ExceptionHandler, Global, Import, ImportKind, Instruction, MemoryType, Operand64, Operand64Idx, + Operand128, Operand128Idx, StorageType, TableDefinition, TagType, TypeSection, ValueCounts, ValueLane, + WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -51,6 +51,7 @@ pub(crate) struct ModuleMetadata { tables: Vec, tags: Vec, aggregate_fields: Vec, + imported_memories: u32, } pub(crate) struct FunctionDataBuilder { @@ -62,42 +63,6 @@ pub(crate) struct FunctionDataBuilder { deduplicate128: Option>, } -pub(crate) trait BuilderRawOperand: tinywasm_types::RawOperand + Ord { - fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result; - fn get(builder: &FunctionDataBuilder, index: u32) -> Self; - fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self); -} - -macro_rules! builder_raw_operand { - ($raw:ty, $lane:ident, $map:ident) => { - impl BuilderRawOperand for $raw { - fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result { - if deduplicate && let Some(index) = builder.$map.as_ref().and_then(|map| map.get(&raw)) { - return Ok(*index); - } - let index = u32::try_from(builder.$lane.len()) - .map_err(|_| crate::ParseError::Other("instruction operand index overflow".into()))?; - builder.$lane.push(raw); - if deduplicate && let Some(map) = &mut builder.$map { - map.insert(raw, index); - } - Ok(index) - } - - fn get(builder: &FunctionDataBuilder, index: u32) -> Self { - *builder.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) - } - - fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self) { - *builder.$lane.get_mut(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) = raw; - } - } - }; -} - -builder_raw_operand!(Operand64, operands64, deduplicate64); -builder_raw_operand!(Operand128, operands128, deduplicate128); - impl FunctionDataBuilder { pub(crate) fn new(deduplicate_operands: bool) -> Self { Self { @@ -110,32 +75,56 @@ impl FunctionDataBuilder { } } - pub(crate) fn push_operand(&mut self, operand: T) -> Result> - where - T::Raw: BuilderRawOperand, - { - ::push(self, operand.encode(), true).map(OperandIdx::new) + pub(crate) fn push_operand64(&mut self, operand: Operand64) -> Result> { + let operand = operand.cast(); + if let Some(index) = self.deduplicate64.as_ref().and_then(|map| map.get(&operand)) { + return Ok(Operand64Idx::new(*index)); + } + let index = self.operands64.len() as u32; + self.operands64.push(operand); + if let Some(map) = &mut self.deduplicate64 { + map.insert(operand, index); + } + Ok(Operand64Idx::new(index)) + } + + pub(crate) fn push_operand128(&mut self, operand: Operand128) -> Result> { + let operand = operand.cast(); + if let Some(index) = self.deduplicate128.as_ref().and_then(|map| map.get(&operand)) { + return Ok(Operand128Idx::new(*index)); + } + let index = self.operands128.len() as u32; + self.operands128.push(operand); + if let Some(map) = &mut self.deduplicate128 { + map.insert(operand, index); + } + Ok(Operand128Idx::new(index)) + } + + pub(crate) fn push_target_operand64(&mut self, operand: Operand64) -> Result> { + self.operands64.push(operand.cast()); + Ok(Operand64Idx::new(self.operands64.len() as u32 - 1)) } - pub(crate) fn push_target_operand(&mut self, operand: T) -> Result> - where - T::Raw: BuilderRawOperand, - { - ::push(self, operand.encode(), false).map(OperandIdx::new) + pub(crate) fn push_target_operand128(&mut self, operand: Operand128) -> Result> { + self.operands128.push(operand.cast()); + Ok(Operand128Idx::new(self.operands128.len() as u32 - 1)) } - pub(crate) fn operand(&self, index: OperandIdx) -> T - where - T::Raw: BuilderRawOperand, - { - T::decode(::get(self, index.index())) + pub(crate) fn operand64(&self, index: Operand64Idx) -> Operand64 { + self.operands64[index.index()].cast() } - pub(crate) fn set_operand(&mut self, index: OperandIdx, operand: T) - where - T::Raw: BuilderRawOperand, - { - ::set(self, index.index(), operand.encode()) + pub(crate) fn operand128(&self, index: Operand128Idx) -> Operand128 { + self.operands128[index.index()].cast() + } + + pub(crate) fn set_operand64(&mut self, index: Operand64Idx, operand: Operand64) { + self.operands64[index.index()] = operand.cast(); + } + + pub(crate) fn set_operand128(&mut self, index: Operand128Idx, operand: Operand128) { + self.operands128[index.index()] = operand.cast(); } pub(crate) fn finish(self) -> WasmFunctionData { @@ -163,6 +152,7 @@ pub(crate) struct FunctionBuilder<'a> { metadata: &'a ModuleMetadata, local_types: Vec, local_addr_map: Vec, + uses_local_memory: bool, } impl<'a> FunctionBuilder<'a> { @@ -195,25 +185,31 @@ impl<'a> FunctionBuilder<'a> { }], operand_stack: Vec::new(), lane_counts: ValueCounts::default(), + uses_local_memory: false, } } + fn mark_memory(&mut self, memory: u32) { + self.uses_local_memory |= memory >= self.metadata.imported_memories; + } + fn visit_struct_get_impl( &mut self, type_index: u32, field_index: u32, - instruction: fn(OperandIdx) -> Instruction, + instruction: fn(Operand64Idx<(u32, u32)>) -> Instruction, ) -> Result<()> { let size = self.metadata.struct_field(type_index, field_index)?; - let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, field_index))?; self.emit(&[ValueLane::S32], &[size], instruction(operand)) } - fn push_operand(&mut self, operand: T) -> Result> - where - T::Raw: BuilderRawOperand, - { - self.data.push_operand(operand) + fn push_operand64(&mut self, operand: Operand64) -> Result> { + self.data.push_operand64(operand) + } + + fn push_operand128(&mut self, operand: Operand128) -> Result> { + self.data.push_operand128(operand) } } @@ -246,6 +242,8 @@ impl ModuleMetadata { let mut memory_sizes = Vec::with_capacity(imports.len() + memories.len()); let mut table_sizes = Vec::with_capacity(imports.len() + tables.len()); let mut tag_types = Vec::with_capacity(imports.len() + tags.len()); + let imported_memories = + imports.iter().filter(|import| matches!(import.kind, ImportKind::Memory(_))).count() as u32; for import in imports { match &import.kind { @@ -294,6 +292,7 @@ impl ModuleMetadata { tables: table_sizes, tags: tag_types, aggregate_fields, + imported_memories, } } @@ -378,6 +377,7 @@ impl ModuleMetadata { impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> { type Output = Result<()>; + #[cfg(not(rust_analyzer))] // rust analyzer gets confused and throws a bunch of errors when this macro is expanded wasmparser::for_each_visit_operator!(validate_then_visit); fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> { @@ -387,6 +387,7 @@ impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> { #[cfg(feature = "validate")] impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> { + #[cfg(not(rust_analyzer))] // rust analyzer gets confused and throws a bunch of errors when this macro is expanded wasmparser::for_each_visit_simd_operator!(validate_then_visit_simd); } @@ -397,7 +398,7 @@ pub(crate) fn process_operators( ty_idx: u32, allocs: OperatorsReaderAllocations, deduplicate_operands: bool, -) -> Result<(Vec, FunctionDataBuilder, OperatorsReaderAllocations)> { +) -> Result<(Vec, FunctionDataBuilder, bool, OperatorsReaderAllocations)> { let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; @@ -419,7 +420,7 @@ pub(crate) fn process_operators( } reader.finish()?; - Ok((builder.instructions, builder.data, reader.into_allocations())) + Ok((builder.instructions, builder.data, builder.uses_local_memory, reader.into_allocations())) } #[cfg(feature = "validate")] @@ -431,7 +432,7 @@ pub(crate) fn process_operators_and_validate( ty_idx: u32, allocs: OperatorsReaderAllocations, deduplicate_operands: bool, -) -> Result<(Vec, FunctionDataBuilder, FuncValidatorAllocations, OperatorsReaderAllocations)> { +) -> Result<(Vec, FunctionDataBuilder, bool, FuncValidatorAllocations, OperatorsReaderAllocations)> { let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; @@ -453,7 +454,13 @@ pub(crate) fn process_operators_and_validate( } reader.finish()?; - Ok((builder.instructions, builder.data, validator.into_allocations(), reader.into_allocations())) + Ok(( + builder.instructions, + builder.data, + builder.uses_local_memory, + validator.into_allocations(), + reader.into_allocations(), + )) } impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { @@ -612,7 +619,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { let size = self.metadata.struct_field(type_index, field_index)?; - let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, field_index))?; self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(operand)) } @@ -622,7 +629,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.pop_expect(size)?; } self.push_sizes(&[ValueLane::S32])?; - let operand = self.push_operand(TwoU32 { first: type_index, second: array_size })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, array_size))?; self.instructions.push(Instruction::ArrayNewFixed(operand)); Ok(()) } @@ -634,7 +641,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output { let table_size = self.metadata.table_size(table_index)?; - let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, table_index))?; let signature = self.metadata.signature(type_index)?; self.pop_expect(table_size)?; self.emit(&signature.params, &signature.results, Instruction::CallIndirect(operand)) @@ -660,7 +667,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.pop_expect(table_size)?; self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); - let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, table_index))?; self.instructions.push(Instruction::ReturnCallIndirect(operand)); Ok(()) } @@ -933,7 +940,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let header_ip = self.instructions.len(); let branch_table_start = self.data.branch_table_targets.len() as u32; let branch_operand = - self.data.push_target_operand(BranchTableArg { target: 0, start: branch_table_start, len })?; + self.data.push_target_operand128(Operand128::::new(0, branch_table_start, len))?; self.instructions.push(Instruction::BranchTable(branch_operand)); struct PadInfo { @@ -978,9 +985,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { .find(|pad| pad.depth == default_depth) .ok_or_else(|| crate::ParseError::Other("missing default branch table target".into()))?; if let Instruction::BranchTable(index) = self.instructions[header_ip] { - let mut operand = self.data.operand(index); - operand.target = default_pad.pad_start as u32; - self.data.set_operand(index, operand); + let operand = self.data.operand128(index); + self.data.set_operand128(index, operand.with_target(default_pad.pad_start as u32)); } for pad in &pads { @@ -1006,12 +1012,12 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - let operand = self.push_operand(I64Operand { value: val.bits() as i64 })?; + let operand = self.push_operand64(Operand64::::new(val.bits() as i64))?; self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) } fn visit_i64_const(&mut self, value: i64) -> Self::Output { - let operand = self.push_operand(I64Operand { value })?; + let operand = self.push_operand64(Operand64::::new(value))?; self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) } @@ -1019,52 +1025,55 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - let operand = self.push_operand(TwoU32 { first: dst_table, second: src_table })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(dst_table, src_table))?; self.emit(&[dst, src, len], &[], Instruction::TableCopy(operand)) } fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; + self.mark_memory(dst_mem); + self.mark_memory(src_mem); let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - let operand = self.push_operand(TwoU32 { first: dst_mem, second: src_mem })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(dst_mem, src_mem))?; self.emit(&[dst, src, len], &[], Instruction::MemoryCopy(operand)) } fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Self::Output { let dst = self.metadata.memory_size(memory)?; - let operand = self.push_operand(TwoU32 { first: data_index, second: memory })?; + self.mark_memory(memory); + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(data_index, memory))?; self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(operand)) } fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Self::Output { let address = self.metadata.table_size(table)?; - let operand = self.push_operand(TwoU32 { first: elem_index, second: table })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(elem_index, table))?; self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand)) } fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { - let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, data_index))?; self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewData(operand)) } fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { - let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewElem(operand)) } fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { - let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, data_index))?; self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitData(operand)) } fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { - let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitElem(operand)) } fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Self::Output { - let operand = self.push_operand(TwoU32 { first: type_index_dst, second: type_index_src })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index_dst, type_index_src))?; self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand)) } @@ -1312,12 +1321,12 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { - let index = self.push_operand(V128Operand { value: lanes })?; + let index = self.push_operand128(Operand128::<[u8; 16]>::new(lanes))?; self.emit(&[ValueLane::S128, ValueLane::S128], &[ValueLane::S128], Instruction::I8x16Shuffle(index)) } fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output { - let index = self.push_operand(V128Operand { value: *value.bytes() })?; + let index = self.push_operand128(Operand128::<[u8; 16]>::new(*value.bytes()))?; self.emit(&[], &[ValueLane::S128], Instruction::Const128(index)) } } @@ -1332,7 +1341,7 @@ impl FunctionBuilder<'_> { self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; let conditional_ip = self.instructions.len(); - let operand = self.data.push_target_operand(CastBranch { target: 0, ref_type_bits: target.to_bits() })?; + let operand = self.data.push_target_operand64(Operand64::<(u32, u32)>::new(0, target.to_bits()))?; self.instructions.push(if branch_on_fail { Instruction::BrOnCastFail(operand) } else { @@ -1502,9 +1511,8 @@ impl FunctionBuilder<'_> { *ip = target as u32; } Instruction::BrOnCast(index) | Instruction::BrOnCastFail(index) => { - let mut operand = self.data.operand(*index); - operand.target = target as u32; - self.data.set_operand(*index, operand); + let operand = self.data.operand64(*index); + self.data.set_operand64(*index, operand.with_target(target as u32)); } _ => {} } diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs index 0b9e1f9..9f637f0 100644 --- a/crates/tinywasm/src/func/context.rs +++ b/crates/tinywasm/src/func/context.rs @@ -22,10 +22,12 @@ impl FuncContext<'_> { /// Get the module instance. pub fn module(&self) -> crate::ModuleInstance { - self.store - .get_module_instance(self.module_id) - .unwrap_or_else(|| unreachable!("invalid module instance id in host function context: {}", self.module_id)) - .clone() + unwrap_or_unreachable!( + self.store.get_module_instance(self.module_id), + "invalid module instance id in host function context: {}", + self.module_id + ) + .clone() } /// Get a memory export. diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 1dcf3c1..064f6c7 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -261,13 +261,13 @@ where { fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { let mut values = args.iter().cloned(); - let params = P::from_wasm_values_exact(&mut values)?; + let params = cold_err!(P::from_wasm_values_exact(&mut values))?; let mut values = (self.func)(ctx, params)?.into_wasm_values(); for result in results { - *result = values.next().ok_or_else(|| crate::Error::other("not enough typed function results"))?; + *result = cold_err!(values.next().ok_or_else(|| crate::Error::other("not enough typed function results")))?; } if values.next().is_some() { - return Err(crate::Error::other("too many typed function results")); + return cold!(Err(crate::Error::other("too many typed function results"))); } Ok(()) } @@ -279,10 +279,10 @@ where }; let params = { let mut values = store.stack_value_iter(type_addr, FuncValueTypes::Params, base)?; - P::from_wasm_values_exact(&mut values) + cold_err!(P::from_wasm_values_exact(&mut values)) }; store.value_stack.truncate_to_base(base); - let result = (self.func)(FuncContext { store, module_id }, params?)?; + let result = cold_err!((self.func)(FuncContext { store, module_id }, params?))?; store.push_typed_values::(type_addr, result.into_wasm_values(), base) } } diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index bd78a57..ea97961 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -68,25 +68,25 @@ struct ModuleInstanceInner { impl ModuleInstance { #[inline] pub(crate) fn resolve_type_addr(&self, type_addr: TypeAddr) -> TypeAddr { - *self.0.type_addrs.get(type_addr as usize).unwrap_or_else(|| unreachable!("invalid type address: {type_addr}")) + *unwrap_or_unreachable!(self.0.type_addrs.get(type_addr as usize), "invalid type address: {type_addr}") } /// resolve a function address to the global store address #[inline] pub(crate) fn resolve_func_addr(&self, addr: FuncAddr) -> FuncAddr { - *self.0.func_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid function address: {addr}")) + *unwrap_or_unreachable!(self.0.func_addrs.get(addr as usize), "invalid function address: {addr}") } /// resolve a table address to the global store address #[inline] pub(crate) fn resolve_table_addr(&self, addr: TableAddr) -> TableAddr { - *self.0.table_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid table address: {addr}")) + *unwrap_or_unreachable!(self.0.table_addrs.get(addr as usize), "invalid table address: {addr}") } /// resolve a memory address to the global store address #[inline] pub(crate) fn resolve_mem_addr(&self, addr: MemAddr) -> MemAddr { - *self.0.mem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid memory address: {addr}")) + *unwrap_or_unreachable!(self.0.mem_addrs.get(addr as usize), "invalid memory address: {addr}") } /// The resolved store address of the module's first memory, or `MemAddr::MAX` when the module @@ -103,24 +103,24 @@ impl ModuleInstance { /// resolve a data address to the global store address #[inline] pub(crate) fn resolve_data_addr(&self, addr: DataAddr) -> DataAddr { - *self.0.data_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid data address: {addr}")) + *unwrap_or_unreachable!(self.0.data_addrs.get(addr as usize), "invalid data address: {addr}") } /// resolve an element address to the global store address #[inline] pub(crate) fn resolve_elem_addr(&self, addr: ElemAddr) -> ElemAddr { - *self.0.elem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid element address: {addr}")) + *unwrap_or_unreachable!(self.0.elem_addrs.get(addr as usize), "invalid element address: {addr}") } /// resolve a global address to the global store address #[inline] pub(crate) fn resolve_global_addr(&self, addr: GlobalAddr) -> GlobalAddr { - *self.0.global_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + *unwrap_or_unreachable!(self.0.global_addrs.get(addr as usize), "invalid global address: {addr}") } #[inline] pub(crate) fn resolve_tag_addr(&self, addr: TagAddr) -> TagAddr { - *self.0.tag_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid tag address: {addr}")) + *unwrap_or_unreachable!(self.0.tag_addrs.get(addr as usize), "invalid tag address: {addr}") } #[inline] @@ -181,9 +181,11 @@ impl ModuleInstance { addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs)); addrs.tags.extend(store.init_tags(&module.tags, &type_addrs)); let limiter = store.engine.config().resource_limiter.clone(); - addrs - .memories - .extend(store.init_memories(&module.memory_types, |ty| MemoryInstance::new(ty, limiter.as_deref()))?); + if !module.skip_local_memory_allocation { + addrs + .memories + .extend(store.init_memories(&module.memory_types, |ty| MemoryInstance::new(ty, limiter.as_deref()))?); + } store.init_globals(&mut addrs.globals, &module.globals, &addrs.funcs, &type_addrs)?; addrs.tables.extend(store.init_tables(&module.tables, &addrs.globals, &addrs.funcs, &type_addrs)?); diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 4824b63..4011e96 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -1,4 +1,3 @@ -use core::hint::cold_path; use core::ops::ControlFlow; #[cfg(not(feature = "std"))] @@ -8,7 +7,7 @@ use super::no_std_floats::NoStdFloatExt; use alloc::boxed::Box; use alloc::vec::Vec; -use interpreter::stack::CallFrame; +use interpreter::stack::{CallFrame, ValueStack}; use tinywasm_types::*; use super::ExecState; @@ -33,10 +32,8 @@ pub(crate) struct Executor<'store, const BUDGETED: bool> { impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { pub(crate) fn new(store: &'store mut Store, cf: CallFrame, call_stack_base: u32) -> Self { let wasm_func = store.state.get_wasm_func(cf.func_addr); - let module = store - .get_module_instance(wasm_func.owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + let module = + unwrap_or_unreachable!(store.get_module_instance(wasm_func.owner), "invalid module instance").clone(); let mem0 = module.mem0_addr(); Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base, mem0 } } @@ -50,8 +47,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { /// Switches the executor to another module, keeping the cached memory-0 address in sync. #[inline] fn set_module(&mut self, owner: ModuleInstanceId) { - self.module = - self.store.get_module_instance(owner).unwrap_or_else(|| unreachable!("invalid module instance")).clone(); + self.module = unwrap_or_unreachable!(self.store.get_module_instance(owner), "invalid module instance").clone(); self.mem0 = self.module.mem0_addr(); } @@ -71,324 +67,206 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec(&mut self, instr_ptr: usize) -> Result> { macro_rules! exec_op { (binary_fallible $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - let $rhs = <$ty>::stack_pop(&mut self.store.value_stack); - let $lhs = <$ty>::stack_pop(&mut self.store.value_stack); - <$ty>::stack_push(&mut self.store.value_stack, $expr?)?; + fn exec_binary_fallible(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $rhs = <$ty>::stack_pop(value_stack); + let $lhs = <$ty>::stack_pop(value_stack); + <$ty>::stack_push(value_stack, $expr?) + } + exec_binary_fallible(&mut self.store.value_stack)?; }}; (unary $from:ty => $to:ty, |$v:ident| $expr:expr) => {{ - let $v = <$from>::stack_pop(&mut self.store.value_stack); - <$to>::stack_push(&mut self.store.value_stack, $expr)?; + fn exec_unary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $v = <$from>::stack_pop(value_stack); + <$to>::stack_push(value_stack, $expr) + } + exec_unary(&mut self.store.value_stack)?; }}; (binary $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - let $rhs = <$from>::stack_pop(&mut self.store.value_stack); - let $lhs = <$from>::stack_pop(&mut self.store.value_stack); - <$to>::stack_push(&mut self.store.value_stack, $expr)?; - }}; - (binary_two_results $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - let $rhs = <$from>::stack_pop(&mut self.store.value_stack); - let $lhs = <$from>::stack_pop(&mut self.store.value_stack); - let out = $expr; - <$to>::stack_push(&mut self.store.value_stack, out.0)?; - <$to>::stack_push(&mut self.store.value_stack, out.1)?; + fn exec_binary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $rhs = <$from>::stack_pop(value_stack); + let $lhs = <$from>::stack_pop(value_stack); + <$to>::stack_push(value_stack, $expr) + } + exec_binary(&mut self.store.value_stack)?; }}; - (binary_mixed $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - let $rhs = <$rhs_ty>::stack_pop(&mut self.store.value_stack); - let $lhs = <$lhs_ty>::stack_pop(&mut self.store.value_stack); - <$res>::stack_push(&mut self.store.value_stack, $expr)?; + (binary $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + fn exec_binary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $rhs = <$rhs_ty>::stack_pop(value_stack); + let $lhs = <$lhs_ty>::stack_pop(value_stack); + <$res>::stack_push(value_stack, $expr) + } + exec_binary(&mut self.store.value_stack)?; }}; (ternary $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{ - let $c = <$from>::stack_pop(&mut self.store.value_stack); - let $b = <$from>::stack_pop(&mut self.store.value_stack); - let $a = <$from>::stack_pop(&mut self.store.value_stack); - <$to>::stack_push(&mut self.store.value_stack, $expr)?; - }}; - (quaternary_two_results $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident, $d:ident| $expr:expr) => {{ - let $d = <$from>::stack_pop(&mut self.store.value_stack); - let $c = <$from>::stack_pop(&mut self.store.value_stack); - let $b = <$from>::stack_pop(&mut self.store.value_stack); - let $a = <$from>::stack_pop(&mut self.store.value_stack); - let out = $expr; - <$to>::stack_push(&mut self.store.value_stack, out.0)?; - <$to>::stack_push(&mut self.store.value_stack, out.1)?; - }}; - (local_set_pop $ty:ty, $local_index:expr) => {{ - let val = <$ty>::stack_pop(&mut self.store.value_stack); - <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val); - }}; - (local_tee $ty:ty, $local_index:expr) => {{ - let val = <$ty>::stack_peek(&self.store.value_stack); - <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val); - }}; - (global_get $ty:ty, $global_index:expr) => {{ - let addr = self.module.resolve_global_addr(*$global_index); - let value = <$ty>::global_get(&self.store.state.globals, addr); - <$ty>::stack_push(&mut self.store.value_stack, value)?; - }}; - (global_set $ty:ty, $global_index:expr) => {{ - let addr = self.module.resolve_global_addr(*$global_index); - let value = <$ty>::stack_pop(&mut self.store.value_stack); - <$ty>::global_set(&mut self.store.state.globals, addr, value); - }}; - (global_tee $ty:ty, $global_index:expr) => {{ - let addr = self.module.resolve_global_addr(*$global_index); - let value = <$ty>::stack_peek(&self.store.value_stack); - <$ty>::global_set(&mut self.store.state.globals, addr, value); - }}; - (binop_local_local $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?; - }}; - (binop_local_local_set $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - let value = $exec(*$op, lhs, rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - }}; - (binop_local_local_tee $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - let value = $exec(*$op, lhs, rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - <$vt>::stack_push(&mut self.store.value_stack, value)?; - }}; - (cmp_local_local $vt:ty, $cmp:ident, $op:ident, $a:ident, $b:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - self.store.value_stack.push(i32::from($cmp(lhs, rhs, *$op)))?; - }}; - (binop_local_const $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, $rhs))?; - }}; - (binop_local_const_set $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let value = $exec(*$op, lhs, $rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - }}; - (binop_local_const_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let value = $exec(*$op, lhs, $rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - <$vt>::stack_push(&mut self.store.value_stack, value)?; - }}; - (binop_global_const $vt:ty, $exec:ident, $op:ident, $global:ident, $rhs:expr) => {{ - let lhs = <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); - self.store.value_stack.push($exec(*$op, lhs, $rhs))?; - }}; - (binop_stack_global $vt:ty, $exec:ident, $op:ident, $global:ident) => {{ - let global_val = - <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); - let stack_val = <$vt>::stack_pop(&mut self.store.value_stack); - self.store.value_stack.push($exec(*$op, stack_val, global_val))?; - }}; - (binop_stack_local $vt:ty, $exec:ident, $op:ident, $local:ident) => {{ - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let lhs = <$vt>::stack_pop(&mut self.store.value_stack); - <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?; - }}; - (binop_stack_local_set $vt:ty, $exec:ident, $op:ident, $local:ident, $dst:ident) => {{ - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let lhs = <$vt>::stack_pop(&mut self.store.value_stack); - let value = $exec(*$op, lhs, rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - }}; - (binop_stack_local_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $dst:ident) => {{ - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let lhs = <$vt>::stack_pop(&mut self.store.value_stack); - let value = $exec(*$op, lhs, rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - <$vt>::stack_push(&mut self.store.value_stack, value)?; - }}; - (binop_acc_local $ty:ty, $acc:ident, $mul:expr, $add:expr) => {{ - let rhs = <$ty>::stack_pop(&mut self.store.value_stack); - let lhs = <$ty>::stack_pop(&mut self.store.value_stack); - let value = ($mul)(lhs, rhs); - <$ty>::local_update(&mut self.store.value_stack, &self.cf, *$acc, |acc| ($add)(value, acc)); + fn exec_ternary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $c = <$from>::stack_pop(value_stack); + let $b = <$from>::stack_pop(value_stack); + let $a = <$from>::stack_pop(value_stack); + <$to>::stack_push(value_stack, $expr) + } + exec_ternary(&mut self.store.value_stack)?; }}; } use tinywasm_types::Instruction::*; #[rustfmt::skip] match &self.func.instructions[instr_ptr] { - Unreachable => { cold_path(); return Err(Trap::Unreachable.into()) }, + Unreachable => return cold!(Err(Trap::Unreachable.into())), Drop32 => { _ = Value32::stack_pop(&mut self.store.value_stack)}, Drop64 => { _ = Value64::stack_pop(&mut self.store.value_stack)}, Drop128 => { _ = Value128::stack_pop(&mut self.store.value_stack)}, Select32 => Value32::stack_select(&mut self.store.value_stack), Select64 => Value64::stack_select(&mut self.store.value_stack), Select128 => Value128::stack_select(&mut self.store.value_stack), + SelectStore32(idx) => self.exec_select_store::(idx.resolve(&self.func.data))?, + SelectStore64(idx) => self.exec_select_store::(idx.resolve(&self.func.data))?, SelectMulti(counts) => self.store.value_stack.select_multi(*counts), - Call(v) => { return Ok(self.exec_call_direct(*v, instr_ptr + 1)?); } - CallSelf => { self.exec_call_self(instr_ptr + 1)?; return Ok(ControlFlow::Continue(0)); } - CallIndirect(idx) => { return Ok(self.exec_call_indirect::(*idx, instr_ptr + 1)?); } - CallRef(ty) => { return Ok(self.exec_call_ref::(*ty, instr_ptr + 1)?); } - ReturnCall(v) => { return Ok(self.exec_return_call_direct(*v)?); } - ReturnCallSelf => { self.exec_return_call_self()?; return Ok(ControlFlow::Continue(0)); } - ReturnCallIndirect(idx) => { return Ok(self.exec_call_indirect::(*idx, instr_ptr + 1)?); } - ReturnCallRef(ty) => { return Ok(self.exec_call_ref::(*ty, instr_ptr + 1)?); } - Throw(tag) => { return Ok(ControlFlow::Continue(self.exec_throw(*tag, instr_ptr)?)); } - ThrowRef => { return Ok(ControlFlow::Continue(self.exec_throw_ref(instr_ptr)?)); } - Jump(ip) => { return Ok(ControlFlow::Continue(*ip as usize)); } - JumpIfZero32(ip) => if Self::exec_jump_if(&self.cf, |_| i32::stack_pop(&mut self.store.value_stack) == 0) { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfNonZero32(ip) => if Self::exec_jump_if(&self.cf, |_| i32::stack_pop(&mut self.store.value_stack) != 0) { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfZero64(ip) => if Self::exec_jump_if(&self.cf, |_| i64::stack_pop(&mut self.store.value_stack) == 0) { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfNonZero64(ip) => if Self::exec_jump_if(&self.cf, |_| i64::stack_pop(&mut self.store.value_stack) != 0) { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfRefNull(ip) => if Self::exec_jump_if(&self.cf, |_| { - let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); - if is_null { ValueRef::stack_pop(&mut self.store.value_stack); } - is_null - }) { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfRefNonNull(ip) => if Self::exec_jump_if(&self.cf, |_| { - let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null(); - if !is_non_null { ValueRef::stack_pop(&mut self.store.value_stack); } - is_non_null - }) { return Ok(ControlFlow::Continue(*ip as usize)) }, - BrOnCast(idx) => { let v = idx.get(&self.func.data); if !self.exec_ref_matches(v.ref_type()) { return Ok(ControlFlow::Continue(v.target as usize)); } }, - BrOnCastFail(idx) => { let v = idx.get(&self.func.data); if self.exec_ref_matches(v.ref_type()) { return Ok(ControlFlow::Continue(v.target as usize)); } }, - JumpIfLocalZero32(arg) => if Self::exec_jump_if(&self.cf, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalNonZero32(arg) => if Self::exec_jump_if(&self.cf, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalZero64(arg) => if Self::exec_jump_if(&self.cf, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalNonZero64(arg) => if Self::exec_jump_if(&self.cf, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpCmpStackConst32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpStackConst64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpStackLocal32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |cf| { - let lhs = i32::stack_pop(&mut self.store.value_stack); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.local), packed.op) - }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpStackLocal64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |cf| { - let lhs = i64::stack_pop(&mut self.store.value_stack); - cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, v.local), packed.op) - }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - BinOpLocalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| { let value = exec_binop_32(op, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - BinOpLocalConstJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let (binop, cmp) = packed.op; if Self::exec_jump_if(&self.cf, |cf| { let lhs = exec_binop_32(binop, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), cmp) }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - BinOpStackConstTeeLocalJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; let value = exec_binop_32(op, i32::stack_pop(&mut self.store.value_stack) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&self.cf, |_| (value == 0) == (v.on_zero != 0)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - BinOpGlobalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |_| { - let global = self.module.resolve_global_addr(v.global); - let value = exec_binop_32(op, i32::global_get(&self.store.state.globals, global) as u32, v.value as u32) as i32; - i32::global_set(&mut self.store.state.globals, global, value); - (value == 0) == (v.on_zero != 0) - }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - IncLocalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&self.cf, |cf| { let value = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - IncStackTeeLocalJump32(idx) => { let v = idx.get(&self.func.data); let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&self.cf, |_| (value == 0) == (v.on_zero != 0)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - IncGlobalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&self.cf, |_| { - let global = self.module.resolve_global_addr(v.global); - let value = i32::global_get(&self.store.state.globals, global).wrapping_add(v.value); - i32::global_set(&mut self.store.state.globals, global, value); - (value == 0) == (v.on_zero != 0) - }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - IncLocalJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| { let lhs = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), op) }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.local), v.value, op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.local), i64::from(v.value), op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpLocalLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.left), i32::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpLocalLocal64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.left), i64::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, + Call(v) => return self.exec_call_direct(*v, instr_ptr + 1), + CallSelf => return self.exec_call_self(instr_ptr + 1), + CallIndirect(idx) => return self.exec_call_indirect::(*idx, instr_ptr + 1), + CallRef(ty) => return self.exec_call_ref::(*ty, instr_ptr + 1), + ReturnCall(v) => return self.exec_return_call_direct(*v), + ReturnCallSelf => return self.exec_return_call_self(), + ReturnCallIndirect(idx) => return self.exec_call_indirect::(*idx, instr_ptr + 1), + ReturnCallRef(ty) => return self.exec_call_ref::(*ty, instr_ptr + 1), + Throw(tag) => return self.exec_throw(*tag, instr_ptr), + ThrowRef => return self.exec_throw_ref(instr_ptr), + Jump(ip) => return Ok(ControlFlow::Continue(*ip as usize)), + JumpIfZero32(ip) => if i32::stack_pop(&mut self.store.value_stack) == 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, + JumpIfNonZero32(ip) => if i32::stack_pop(&mut self.store.value_stack) != 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, + JumpIfZero64(ip) => if i64::stack_pop(&mut self.store.value_stack) == 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, + JumpIfNonZero64(ip) => if i64::stack_pop(&mut self.store.value_stack) != 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, + JumpIfRefNull(ip) => { let ip = *ip; if self.exec_jump_if_ref::() { return Ok(ControlFlow::Continue(ip as usize)) } }, + JumpIfRefNonNull(ip) => { let ip = *ip; if self.exec_jump_if_ref::() { return Ok(ControlFlow::Continue(ip as usize)) } }, + BrOnCast(idx) => if let Some(ip) = self.exec_br_on_cast::(*idx) { return Ok(ControlFlow::Continue(ip)) }, + BrOnCastFail(idx) => if let Some(ip) = self.exec_br_on_cast::(*idx) { return Ok(ControlFlow::Continue(ip)) }, + JumpIfLocalZero32(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, + JumpIfLocalNonZero32(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, + JumpIfLocalZero64(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, + JumpIfLocalNonZero64(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, + JumpCmpStackConst32(packed) => if let Some(ip) = self.exec_jump_cmp_stack_const32(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpStackConst64(packed) => if let Some(ip) = self.exec_jump_cmp_stack_const64(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpStackLocal32(packed) => if let Some(ip) = self.exec_jump_cmp_stack_local32(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpStackLocal64(packed) => if let Some(ip) = self.exec_jump_cmp_stack_local64(*packed) { return Ok(ControlFlow::Continue(ip)) }, + BinOpLocalConstJump32(packed) => if let Some(ip) = self.exec_binop_local_const_jump(*packed) { return Ok(ControlFlow::Continue(ip)) }, + BinOpLocalConstJumpCmpLocal32(packed) => if let Some(ip) = self.exec_binop_local_const_jump_cmp_local(*packed) { return Ok(ControlFlow::Continue(ip)) }, + BinOpStackConstTeeLocalJump32(packed) => if let Some(ip) = self.exec_binop_stack_const_tee_local_jump(*packed)? { return Ok(ControlFlow::Continue(ip)) }, + BinOpGlobalConstJump32(packed) => if let Some(ip) = self.exec_binop_global_const_jump(*packed) { return Ok(ControlFlow::Continue(ip)) }, + IncLocalJump32(idx) => if let Some(ip) = self.exec_inc_local_jump(*idx) { return Ok(ControlFlow::Continue(ip)) }, + IncStackTeeLocalJump32(idx) => if let Some(ip) = self.exec_inc_stack_tee_local_jump(*idx)? { return Ok(ControlFlow::Continue(ip)) }, + IncGlobalJump32(idx) => if let Some(ip) = self.exec_inc_global_jump(*idx) { return Ok(ControlFlow::Continue(ip)) }, + IncLocalJumpCmpLocal32(packed) => if let Some(ip) = self.exec_inc_local_jump_cmp_local(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpLocalConst32(packed) => if let Some(ip) = self.exec_jump_cmp_local_const32(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpLocalConst64(packed) => if let Some(ip) = self.exec_jump_cmp_local_const64(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpLocalLocal32(packed) => if let Some(ip) = self.exec_jump_cmp_local_local32(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpLocalLocal64(packed) => if let Some(ip) = self.exec_jump_cmp_local_local64(*packed) { return Ok(ControlFlow::Continue(ip)) }, DropKeep32 { base, keep } => self.store.value_stack.stack_32.truncate_keep((self.cf.stack_base().s32 + u32::from(*base)) as usize, *keep as usize), DropKeep64 { base, keep } => self.store.value_stack.stack_64.truncate_keep((self.cf.stack_base().s64 + u32::from(*base)) as usize, *keep as usize), DropKeep128 { base, keep } => self.store.value_stack.stack_128.truncate_keep((self.cf.stack_base().s128 + u32::from(*base)) as usize, *keep as usize), - BranchTable(idx) => { return Ok(ControlFlow::Continue(self.exec_branch_table(*idx))); } - Return => { return Ok(self.exec_return()); } - ReturnVoid => { return Ok(self.exec_return_void()); } - Return32 => { return Ok(self.exec_return_32()); } - Return64 => { return Ok(self.exec_return_64()); } - Return128 => { return Ok(self.exec_return_128()); } + BranchTable(idx) => return Ok(ControlFlow::Continue(self.exec_branch_table(*idx))), + Return => return Ok(self.exec_return()), + ReturnVoid => return Ok(self.exec_return_void()), + Return32 => return Ok(self.exec_return_32()), + Return64 => return Ok(self.exec_return_64()), + Return128 => return Ok(self.exec_return_128()), LocalGet32(local_index) => Value32::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, LocalGet64(local_index) => Value64::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, LocalGet128(local_index) => Value128::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, - LocalSet32(local_index) => exec_op!(local_set_pop Value32, local_index), - LocalSet64(local_index) => exec_op!(local_set_pop Value64, local_index), - LocalSet128(local_index) => exec_op!(local_set_pop Value128, local_index), + LocalSet32(local_index) => self.exec_local_set_pop::(*local_index), + LocalSet64(local_index) => self.exec_local_set_pop::(*local_index), + LocalSet128(local_index) => self.exec_local_set_pop::(*local_index), LocalCopy32(from, to) => Value32::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), - AddConst32(c) => exec_op!(unary i32 => i32, |v| v.wrapping_add(*c)), - AddConst64(idx) => { let c = idx.get(&self.func.data).value; exec_op!(unary i64 => i64, |v| v.wrapping_add(c)); }, - IncLocal32(arg) => i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)), - IncLocal64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); }, + AddConst32(c) => { i32::stack_update(&mut self.store.value_stack, #[inline(always)] |value| value.wrapping_add(*c))?; }, + AddConst64(idx) => { let constant = idx.resolve(&self.func.data).value(); i64::stack_update(&mut self.store.value_stack, #[inline(always)] |value| value.wrapping_add(constant))?; }, + IncLocal32(arg) => { i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)); }, + IncLocal64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); }, I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), - MulAccLocal32(acc) => exec_op!(binop_acc_local i32, acc, |a: i32, b| a.wrapping_mul(b), |a: i32, b| a.wrapping_add(b)), - MulAccLocal64(acc) => exec_op!(binop_acc_local i64, acc, |a: i64, b| a.wrapping_mul(b), |a: i64, b| a.wrapping_add(b)), - FMulAccLocal32(acc) => exec_op!(binop_acc_local f32, acc, |a: f32, b| a * b, |a: f32, b| a + b), - FMulAccLocal64(acc) => exec_op!(binop_acc_local f64, acc, |a: f64, b| a * b, |a: f64, b| a + b), - BinOpLocalLocal32(op, a, b) => exec_op!(binop_local_local Value32, exec_binop_32, op, a, b), - BinOpLocalLocal64(op, a, b) => exec_op!(binop_local_local Value64, exec_binop_64, op, a, b), - BinOpLocalLocal128(op, a, b) => exec_op!(binop_local_local Value128, exec_binop_128, op, a, b), - CmpLocalLocal32(op, a, b) => exec_op!(cmp_local_local i32, cmp_i32, op, a, b), - CmpLocalLocal64(op, a, b) => exec_op!(cmp_local_local i64, cmp_i64, op, a, b), - AddLocalLocalSet32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); }, - AddLocalLocalTee32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); i32::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalLocalSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalLocalSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalLocalSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalLocalTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalLocalTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalLocalTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; }, - AddLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_add(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, - SubLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_sub(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, - MulLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_mul(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value32::local_get(&self.store.value_stack, &self.cf, v.local); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, lhs, v.value))?; }, - BinOpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value64::local_get(&self.store.value_stack, &self.cf, v.local); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, lhs, v.value))?; }, - BinOpLocalConst128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::stack_push(&mut self.store.value_stack, value)?; }, - BinOpGlobalConst32(packed) => { let v = packed.index.get(&self.func.data); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, Value32::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; }, - BinOpGlobalConst64(packed) => { let v = packed.index.get(&self.func.data); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, Value64::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; }, - BinOpGlobalConst128(packed) => { let v = packed.index.get(&self.func.data); Value128::stack_push(&mut self.store.value_stack, exec_binop_128(packed.op, Value128::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), Value128(v.value.get(&self.func.data).value)))?; }, - BinOpLocalConstSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalConstTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalConstSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalConstTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalConstSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalConstTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; }, - BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index), - BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index), - BinOpStackLocal32(op, local) => exec_op!(binop_stack_local Value32, exec_binop_32, op, local), - BinOpStackLocalSet32(op, local, dst) => exec_op!(binop_stack_local_set Value32, exec_binop_32, op, local, dst), - BinOpStackLocalTee32(op, local, dst) => exec_op!(binop_stack_local_tee Value32, exec_binop_32, op, local, dst), - BinOpStackLocal128(op, local) => exec_op!(binop_stack_local Value128, exec_binop_128, op, local), + MulAccLocal32(acc) => self.exec_mul_acc_local::(*acc, i32::wrapping_mul, i32::wrapping_add), + MulAccLocal64(acc) => self.exec_mul_acc_local::(*acc, i64::wrapping_mul, i64::wrapping_add), + FMulAccLocal32(acc) => self.exec_mul_acc_local::(*acc, |a, b| a * b, |a, b| a + b), + FMulAccLocal64(acc) => self.exec_mul_acc_local::(*acc, |a, b| a * b, |a, b| a + b), + BinOpLocalLocal32(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, + BinOpLocalLocal64(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, + BinOpLocalLocal128(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, + CmpLocalLocal32(op, a, b) => self.exec_cmp_local_local::(*a, *b, *op)?, + CmpLocalLocal64(op, a, b) => self.exec_cmp_local_local::(*a, *b, *op)?, + AddLocalLocalSet32(arg) => self.exec_binop_local_local::(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, + AddLocalLocalTee32(arg) => self.exec_binop_local_local::(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, + BinOpLocalLocalSet32(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalSet64(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalSet128(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalTee32(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalTee64(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalTee128(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + AddLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IAdd)?, + SubLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::ISub)?, + MulLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IMul)?, + BinOpLocalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.b(), None, packed.op)?; }, + BinOpLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.b(), None, packed.op)?; }, + BinOpLocalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, None, packed.op)?; }, + BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_global_const::(v.a(), rhs, packed.op)?; }, + BinOpLocalConstSet32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstTee32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstSet64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstTee64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstSet128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, Some(v.b()), packed.op)?; }, + BinOpLocalConstTee128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, Some(v.b()), packed.op)?; }, + BinOpStackGlobal32(op, global_index) => self.exec_binop_stack_global::(*global_index, *op)?, + BinOpStackGlobal64(op, global_index) => self.exec_binop_stack_global::(*global_index, *op)?, + BinOpStackLocal32(op, local) => self.exec_binop_stack_local::(*local, None, *op)?, + BinOpStackLocalSet32(op, local, dst) => self.exec_binop_stack_local::(*local, Some(*dst), *op)?, + BinOpStackLocalTee32(op, local, dst) => self.exec_binop_stack_local::(*local, Some(*dst), *op)?, + BinOpStackLocal128(op, local) => self.exec_binop_stack_local::(*local, None, *op)?, SetLocalConst32(arg) => i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, arg.value), - SetLocalConst64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); }, - SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.get(&self.func.data).value)), - IncMemoryLocal32(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?, - IncMemoryLocal64(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?, - StoreLocalLocal32(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, - StoreLocalLocal64(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, - StoreLocalLocal128(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, - LoadLocal32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?, - LoadLocal64(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?, - LoadLocal8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, - LoadLocal8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, - LoadLocal16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, - LoadLocal16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, - LoadLocalTee32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, - LoadLocalSet32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, - LoadLocalTee8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalTee8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalTee16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalTee16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalSet8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalSet8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalSet16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalSet16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalTee128(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, - LoadLocalSet128(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, - AndConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v & arg.value); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); }, - SubConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(arg.value)); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); }, - AndConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n & v); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); }, - SubConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n.wrapping_sub(v)); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); }, - LocalTee32(local_index) => exec_op!(local_tee Value32, local_index), - LocalTee64(local_index) => exec_op!(local_tee Value64, local_index), - LocalTee128(local_index) => exec_op!(local_tee Value128, local_index), - GlobalGet32(global_index) => exec_op!(global_get Value32, global_index), - GlobalGet64(global_index) => exec_op!(global_get Value64, global_index), - GlobalGet128(global_index) => exec_op!(global_get Value128, global_index), - GlobalSet32(global_index) => exec_op!(global_set Value32, global_index), - GlobalSet64(global_index) => exec_op!(global_set Value64, global_index), - GlobalSet128(global_index) => exec_op!(global_set Value128, global_index), - GlobalTee32(global_index) => exec_op!(global_tee Value32, global_index), - GlobalTee64(global_index) => exec_op!(global_tee Value64, global_index), - GlobalTee128(global_index) => exec_op!(global_tee Value128, global_index), + SetLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); }, + SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.resolve(&self.func.data).value())), + IncMemoryLocal32(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, + IncMemoryLocal64(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, + StoreLocalLocal32(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, + StoreLocalLocal64(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, + StoreLocalLocal128(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, + LoadLocal32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, #[inline(always)] |v| v)?, + LoadLocal64(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, #[inline(always)] |v| v)?, + LoadLocal8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocalTee32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + LoadLocalSet32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + LoadLocalTee8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee128(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + LoadLocalSet128(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + AndConstTee32(arg) => self.exec_binop_const_tee::(arg.value as u32, arg.local, BinOp::IAnd)?, + SubConstTee32(arg) => self.exec_binop_const_tee::(arg.value as u32, arg.local, BinOp::ISub)?, + AndConstTee64(packed) => self.exec_binop_const_tee::(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::IAnd)?, + SubConstTee64(packed) => self.exec_binop_const_tee::(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::ISub)?, + LocalTee32(local_index) => self.exec_local_tee::(*local_index), + LocalTee64(local_index) => self.exec_local_tee::(*local_index), + LocalTee128(local_index) => self.exec_local_tee::(*local_index), + GlobalGet32(global_index) => self.exec_global_get::(*global_index)?, + GlobalGet64(global_index) => self.exec_global_get::(*global_index)?, + GlobalGet128(global_index) => self.exec_global_get::(*global_index)?, + GlobalSet32(global_index) => self.exec_global_set::(*global_index), + GlobalSet64(global_index) => self.exec_global_set::(*global_index), + GlobalSet128(global_index) => self.exec_global_set::(*global_index), + GlobalTee32(global_index) => self.exec_global_tee::(*global_index), + GlobalTee64(global_index) => self.exec_global_tee::(*global_index), + GlobalTee128(global_index) => self.exec_global_tee::(*global_index), Const32(val) => i32::stack_push(&mut self.store.value_stack, *val)?, Const64Imm(val) => i64::stack_push(&mut self.store.value_stack, i64::from(*val))?, - Const64(idx) => i64::stack_push(&mut self.store.value_stack, idx.get(&self.func.data).value)?, + Const64(idx) => i64::stack_push(&mut self.store.value_stack, idx.resolve(&self.func.data).value())?, Const128Imm(val) => Value128::stack_push(&mut self.store.value_stack, Value128(u128::from(*val).to_le_bytes()))?, I64Eqz => exec_op!(unary i64 => i32, |v| i32::from(v == 0)), I32Eqz => exec_op!(unary i32 => i32, |v| i32::from(v == 0)), @@ -462,26 +340,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64Rotl => exec_op!(binary i64 => i64, |a, b| a.rotate_left(b as u32)), I32Rotr => exec_op!(binary i32 => i32, |a, b| a.rotate_right(b as u32)), I64Rotr => exec_op!(binary i64 => i64, |a, b| a.rotate_right(b as u32)), - I64Add128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| { - let lo = a_lo.wrapping_add(b_lo); - let carry = u64::from((lo as u64) < (a_lo as u64)); - let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64); - (lo, hi) - }), - I64Sub128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| { - let lo = a_lo.wrapping_sub(b_lo); - let borrow = u64::from((a_lo as u64) < (b_lo as u64)); - let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64); - (lo, hi) - }), - I64MulWideS => exec_op!(binary_two_results i64 => i64, |a, b| { - let product = (a as i128).wrapping_mul(b as i128); - (product as i64, (product >> 64) as i64) - }), - I64MulWideU => exec_op!(binary_two_results i64 => i64, |a, b| { - let product = (a as u64 as u128).wrapping_mul(b as u64 as u128); - (product as u64 as i64, (product >> 64) as u64 as i64) - }), + I64Add128 => self.exec_i64_add128()?, + I64Sub128 => self.exec_i64_sub128()?, + I64MulWideS => self.exec_i64_mul_wide_s()?, + I64MulWideU => self.exec_i64_mul_wide_u()?, I32Clz => exec_op!(unary i32 => i32, |v| v.leading_zeros() as i32), I64Clz => exec_op!(unary i64 => i64, |v| i64::from(v.leading_zeros())), I32Ctz => exec_op!(unary i32 => i32, |v| v.trailing_zeros() as i32), @@ -500,6 +362,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { RefEq => exec_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), RefTest(ty) => self.exec_ref_test(*ty)?, RefCast(ty) => self.exec_ref_cast(*ty)?, + // GC objects StructNew(ty) => self.exec_struct_new(*ty, false)?, StructNewDefault(ty) => self.exec_struct_new(*ty, true)?, @@ -542,31 +405,31 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { TableCopy(idx) => self.exec_table_copy(*idx)?, // Core memory load/store operations - I32Store(idx) => self.exec_mem_store::(*idx, |v| v)?, - I64Store(idx) => self.exec_mem_store::(*idx, |v| v)?, - F32Store(idx) => self.exec_mem_store::(*idx, |v| v)?, - F64Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + I32Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + I64Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + F32Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + F64Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, FMaStoreF32(m) => self.exec_fma_store::(*m)?, FMaStoreF64(m) => self.exec_fma_store::(*m)?, - I32Store8(idx) => self.exec_mem_store::(*idx, |v| v as i8)?, - I32Store16(idx) => self.exec_mem_store::(*idx, |v| v as i16)?, - I64Store8(idx) => self.exec_mem_store::(*idx, |v| v as i8)?, - I64Store16(idx) => self.exec_mem_store::(*idx, |v| v as i16)?, - I64Store32(idx) => self.exec_mem_store::(*idx, |v| v as i32)?, - I32Load(idx) => self.exec_mem_load::(*idx, |v| v)?, - I64Load(idx) => self.exec_mem_load::(*idx, |v| v)?, - F32Load(idx) => self.exec_mem_load::(*idx, |v| v)?, - F64Load(idx) => self.exec_mem_load::(*idx, |v| v)?, - I32Load8S(idx) => self.exec_mem_load::(*idx, i32::from)?, - I32Load8U(idx) => self.exec_mem_load::(*idx, i32::from)?, - I32Load16S(idx) => self.exec_mem_load::(*idx, i32::from)?, - I32Load16U(idx) => self.exec_mem_load::(*idx, i32::from)?, - I64Load8S(idx) => self.exec_mem_load::(*idx, i64::from)?, - I64Load8U(idx) => self.exec_mem_load::(*idx, i64::from)?, - I64Load16S(idx) => self.exec_mem_load::(*idx, i64::from)?, - I64Load16U(idx) => self.exec_mem_load::(*idx, i64::from)?, - I64Load32S(idx) => self.exec_mem_load::(*idx, i64::from)?, - I64Load32U(idx) => self.exec_mem_load::(*idx, i64::from)?, + I32Store8(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, + I32Store16(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?, + I64Store8(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, + I64Store16(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?, + I64Store32(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i32)?, + I32Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + I64Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + F32Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + F64Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + I32Load8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, + I32Load8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, + I32Load16S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, + I32Load16U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, + I64Load8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, + I64Load8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, + I64Load16S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, + I64Load16U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, + I64Load32S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, + I64Load32U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, // Numeric conversion operations F32ConvertI32S => exec_op!(unary i32 => f32, |v| v as f32), @@ -638,43 +501,43 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), - V128Load(idx) => self.exec_mem_load::(*idx, |v| v)?, - V128Load8x8S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, - V128Load8x8U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, - V128Load16x4S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, - V128Load16x4U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, - V128Load32x2S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, - V128Load32x2U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, - V128Load8Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i8)?, - V128Load16Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i16)?, - V128Load32Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i32)?, - V128Load64Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i64)?, - V128Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + V128Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| v)?, + V128Load8x8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, + V128Load8x8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, + V128Load16x4S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, + V128Load16x4U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, + V128Load32x2S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, + V128Load32x2U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, + V128Load8Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i8)?, + V128Load16Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i16)?, + V128Load32Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i32)?, + V128Load64Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i64)?, + V128Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), |v| v)?, V128Store8Lane(arg) => self.exec_mem_store_lane::(*arg)?, V128Store16Lane(arg) => self.exec_mem_store_lane::(*arg)?, V128Store32Lane(arg) => self.exec_mem_store_lane::(*arg)?, V128Store64Lane(arg) => self.exec_mem_store_lane::(*arg)?, - V128Load32Zero(idx) => self.exec_mem_load::(*idx, |v| Value128::from_i32x4([v, 0, 0, 0]))?, - V128Load64Zero(idx) => self.exec_mem_load::(*idx, |v| Value128::from_i64x2([v, 0]))?, - Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(arg.get(&self.func.data).value))?, - I8x16ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), - I8x16ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), - I16x8ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), - I16x8ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u16(*lane) as i32), - I32x4ExtractLane(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i32(*lane)), - I64x2ExtractLane(lane) => exec_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), - F32x4ExtractLane(lane) => exec_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), - F64x2ExtractLane(lane) => exec_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), + V128Load32Zero(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::from_i32x4([v, 0, 0, 0]))?, + V128Load64Zero(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::from_i64x2([v, 0]))?, + Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(arg.resolve(&self.func.data).value()))?, + I8x16ExtractLaneS(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_i8(lane) as i32)?, + I8x16ExtractLaneU(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_u8(lane) as i32)?, + I16x8ExtractLaneS(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_i16(lane) as i32)?, + I16x8ExtractLaneU(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_u16(lane) as i32)?, + I32x4ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_i32)?, + I64x2ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_i64)?, + F32x4ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_f32)?, + F64x2ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_f64)?, V128Load8Lane(arg) => self.exec_mem_load_lane::(*arg)?, V128Load16Lane(arg) => self.exec_mem_load_lane::(*arg)?, V128Load32Lane(arg) => self.exec_mem_load_lane::(*arg)?, V128Load64Lane(arg) => self.exec_mem_load_lane::(*arg)?, - I8x16ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), - I16x8ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), - I32x4ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), - I64x2ReplaceLane(lane) => exec_op!(binary_mixed i64, Value128 => Value128, |value, vec| vec.i64x2_replace_lane(*lane, value)), - F32x4ReplaceLane(lane) => exec_op!(binary_mixed f32, Value128 => Value128, |value, vec| vec.f32x4_replace_lane(*lane, value)), - F64x2ReplaceLane(lane) => exec_op!(binary_mixed f64, Value128 => Value128, |value, vec| vec.f64x2_replace_lane(*lane, value)), + I8x16ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i8x16_replace_lane(lane, value as i8))?, + I16x8ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i16x8_replace_lane(lane, value as i16))?, + I32x4ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i32x4_replace_lane(lane, value))?, + I64x2ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i64x2_replace_lane(lane, value))?, + F32x4ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.f32x4_replace_lane(lane, value))?, + F64x2ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.f64x2_replace_lane(lane, value))?, I8x16Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)), I16x8Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)), I32x4Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i32(v)), @@ -745,18 +608,18 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I16x8Bitmask => exec_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32), I32x4Bitmask => exec_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32), I64x2Bitmask => exec_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32), - I8x16Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)), - I16x8Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)), - I32x4Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)), - I64x2Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)), - I8x16ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)), - I16x8ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)), - I32x4ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)), - I64x2ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)), - I8x16ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)), - I16x8ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)), - I32x4ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)), - I64x2ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)), + I8x16Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)), + I16x8Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)), + I32x4Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)), + I64x2Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)), + I8x16ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)), + I16x8ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)), + I32x4ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)), + I64x2ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)), + I8x16ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)), + I16x8ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)), + I32x4ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)), + I64x2ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)), I8x16Add => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add(b)), I16x8Add => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add(b)), I32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_add(b)), @@ -823,7 +686,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64x2ExtendHighI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()), I64x2ExtendHighI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()), I8x16Popcnt => exec_op!(unary Value128 => Value128, |v| v.i8x16_popcnt()), - I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(idx.get(&self.func.data).value))), + I8x16Shuffle(idx) => self.exec_simd_shuffle(Value128(idx.resolve(&self.func.data).value()))?, I16x8Q15MulrSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), I32x4DotI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)), I8x16RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), @@ -891,17 +754,424 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } #[inline(always)] - fn exec_jump_if(cf: &CallFrame, condition: impl FnOnce(&CallFrame) -> bool) -> bool { - condition(cf) + fn exec_jump_if_ref(&mut self) -> bool { + let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); + if is_null { + ValueRef::stack_pop(&mut self.store.value_stack); + } + is_null == ON_NULL + } + + #[inline(always)] + fn exec_br_on_cast(&self, index: Operand64Idx<(u32, u32)>) -> Option { + let operand = index.resolve(&self.func.data); + let ty = unwrap_or_unreachable!(RefType::from_bits(operand.b())); + (self.exec_ref_matches(ty) == ON_MATCH).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_if_local( + &self, + local: LocalAddr, + ) -> bool { + (T::local_get(&self.store.value_stack, &self.cf, local) == T::default()) == ON_ZERO + } + + #[inline(always)] + fn exec_jump_cmp_stack_const32(&mut self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + packed.op.cmp(i32::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_stack_const64(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + packed.op.cmp(i64::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_stack_local32(&mut self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::stack_pop(&mut self.store.value_stack); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_stack_local64(&mut self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i64::stack_pop(&mut self.store.value_stack); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_binop_local_const_jump(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let value = i32::local_update( + &mut self.store.value_stack, + &self.cf, + operand.local(), + #[inline(always)] + |value| packed.op.exec(value as u32, operand.value() as u32) as i32, + ); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_binop_local_const_jump_cmp_local( + &mut self, + packed: PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>, + ) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_update( + &mut self.store.value_stack, + &self.cf, + operand.local(), + #[inline(always)] + |value| packed.op.0.exec(value as u32, operand.value() as u32) as i32, + ); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); + packed.op.1.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_binop_stack_const_tee_local_jump( + &mut self, + packed: PackedOp128, + ) -> Result, Trap> { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::stack_pop(&mut self.store.value_stack); + let value = packed.op.exec(lhs as u32, operand.value() as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value); + i32::stack_push(&mut self.store.value_stack, value)?; + Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) + } + + #[inline(always)] + fn exec_binop_global_const_jump(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let global = self.module.resolve_global_addr(operand.global()); + let value = i32::global_update( + &mut self.store.state.globals, + global, + #[inline(always)] + |value| packed.op.exec(value as u32, operand.value() as u32) as i32, + ); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_inc_local_jump(&mut self, index: Operand128Idx) -> Option { + let operand = index.resolve(&self.func.data); + let value = i32::local_update( + &mut self.store.value_stack, + &self.cf, + operand.local(), + #[inline(always)] + |value| value.wrapping_add(operand.value()), + ); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_inc_stack_tee_local_jump( + &mut self, + index: Operand128Idx, + ) -> Result, Trap> { + let operand = index.resolve(&self.func.data); + let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(operand.value()); + i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value); + i32::stack_push(&mut self.store.value_stack, value)?; + Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) + } + + #[inline(always)] + fn exec_inc_global_jump(&mut self, index: Operand128Idx) -> Option { + let operand = index.resolve(&self.func.data); + let global = self.module.resolve_global_addr(operand.global()); + let value = i32::global_update( + &mut self.store.state.globals, + global, + #[inline(always)] + |value| value.wrapping_add(operand.value()), + ); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_inc_local_jump_cmp_local(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_update( + &mut self.store.value_stack, + &self.cf, + operand.local(), + #[inline(always)] + |value| value.wrapping_add(operand.value()), + ); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_const32(&self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, operand.b()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_const64(&self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, i64::from(operand.b())).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_local32(&self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b()); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_local64(&self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b()); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + fn exec_i64_add128(&mut self) -> Result<(), Trap> { + let b_hi = i64::stack_pop(&mut self.store.value_stack); + let b_lo = i64::stack_pop(&mut self.store.value_stack); + let a_hi = i64::stack_pop(&mut self.store.value_stack); + let a_lo = i64::stack_pop(&mut self.store.value_stack); + let lo = a_lo.wrapping_add(b_lo); + let carry = u64::from((lo as u64) < (a_lo as u64)); + let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64); + i64::stack_push(&mut self.store.value_stack, lo)?; + i64::stack_push(&mut self.store.value_stack, hi) + } + + fn exec_i64_sub128(&mut self) -> Result<(), Trap> { + let b_hi = i64::stack_pop(&mut self.store.value_stack); + let b_lo = i64::stack_pop(&mut self.store.value_stack); + let a_hi = i64::stack_pop(&mut self.store.value_stack); + let a_lo = i64::stack_pop(&mut self.store.value_stack); + let lo = a_lo.wrapping_sub(b_lo); + let borrow = u64::from((a_lo as u64) < (b_lo as u64)); + let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64); + i64::stack_push(&mut self.store.value_stack, lo)?; + i64::stack_push(&mut self.store.value_stack, hi) + } + + fn exec_i64_mul_wide_s(&mut self) -> Result<(), Trap> { + let rhs = i64::stack_pop(&mut self.store.value_stack); + let lhs = i64::stack_pop(&mut self.store.value_stack); + let product = (lhs as i128).wrapping_mul(rhs as i128); + i64::stack_push(&mut self.store.value_stack, product as i64)?; + i64::stack_push(&mut self.store.value_stack, (product >> 64) as i64) + } + + fn exec_i64_mul_wide_u(&mut self) -> Result<(), Trap> { + let rhs = i64::stack_pop(&mut self.store.value_stack); + let lhs = i64::stack_pop(&mut self.store.value_stack); + let product = (lhs as u64 as u128).wrapping_mul(rhs as u64 as u128); + i64::stack_push(&mut self.store.value_stack, product as u64 as i64)?; + i64::stack_push(&mut self.store.value_stack, (product >> 64) as u64 as i64) + } + + fn exec_simd_extract_lane( + &mut self, + lane: u8, + operation: impl FnOnce(Value128, u8) -> TO, + ) -> Result<(), Trap> { + let vector = Value128::stack_pop(&mut self.store.value_stack); + TO::stack_push(&mut self.store.value_stack, operation(vector, lane)) + } + + fn exec_simd_replace_lane( + &mut self, + lane: u8, + operation: impl FnOnce(VALUE, Value128, u8) -> Value128, + ) -> Result<(), Trap> { + let vector = Value128::stack_pop(&mut self.store.value_stack); + let value = VALUE::stack_pop(&mut self.store.value_stack); + Value128::stack_push(&mut self.store.value_stack, operation(value, vector, lane)) + } + + fn exec_simd_shuffle(&mut self, lanes: Value128) -> Result<(), Trap> { + let rhs = Value128::stack_pop(&mut self.store.value_stack); + let lhs = Value128::stack_pop(&mut self.store.value_stack); + Value128::stack_push(&mut self.store.value_stack, Value128::i8x16_shuffle(lhs, rhs, lanes)) + } + + #[inline(always)] + fn exec_local_set_pop(&mut self, local: LocalAddr) { + let value = T::stack_pop(&mut self.store.value_stack); + T::local_set(&mut self.store.value_stack, &self.cf, local, value); + } + + #[inline(always)] + fn exec_local_tee(&mut self, local: LocalAddr) { + let value = T::stack_peek(&self.store.value_stack); + T::local_set(&mut self.store.value_stack, &self.cf, local, value); + } + + #[inline(always)] + fn exec_global_get(&mut self, global: GlobalAddr) -> Result<(), Trap> { + let addr = self.module.resolve_global_addr(global); + let value = T::global_get(&self.store.state.globals, addr); + T::stack_push(&mut self.store.value_stack, value) + } + + #[inline(always)] + fn exec_global_set(&mut self, global: GlobalAddr) { + let addr = self.module.resolve_global_addr(global); + let value = T::stack_pop(&mut self.store.value_stack); + T::global_set(&mut self.store.state.globals, addr, value); } - fn exec_branch_table(&mut self, index: OperandIdx) -> usize { - let v = index.get(&self.func.data); + #[inline(always)] + fn exec_global_tee(&mut self, global: GlobalAddr) { + let addr = self.module.resolve_global_addr(global); + let value = T::stack_peek(&self.store.value_stack); + T::global_set(&mut self.store.state.globals, addr, value); + } + + #[inline(always)] + fn exec_binop_result( + &mut self, + dst: Option, + val: T, + ) -> Result<(), Trap> { + if let Some(dst) = dst { + T::local_set(&mut self.store.value_stack, &self.cf, dst, val); + } + if PUSH { T::stack_push(&mut self.store.value_stack, val) } else { Ok(()) } + } + + #[inline(always)] + fn exec_binop_local_local( + &mut self, + lhs: LocalAddr, + rhs: LocalAddr, + destination: Option, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); + let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs); + self.exec_binop_result::(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_local_local_indexed( + &mut self, + index: Operand64Idx<(u16, u16, u16)>, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let operands = index.resolve(&self.func.data); + self.exec_binop_local_local::(operands.a(), operands.b(), Some(operands.c()), op) + } + + #[inline(always)] + fn exec_binop_local_const( + &mut self, + lhs: LocalAddr, + rhs: T, + destination: Option, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); + self.exec_binop_result::(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_global_const( + &mut self, + lhs: GlobalAddr, + rhs: T, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let lhs = T::global_get(&self.store.state.globals, self.module.resolve_global_addr(lhs)); + T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_cmp_local_local(&mut self, lhs: LocalAddr, rhs: LocalAddr, op: CmpOp) -> Result<(), Trap> + where + T: InternalValue, + CmpOp: CmpOpExt, + { + let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); + let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs); + i32::stack_push(&mut self.store.value_stack, i32::from(op.cmp(lhs, rhs))) + } + + #[inline(always)] + fn exec_binop_stack_global( + &mut self, + global: GlobalAddr, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let addr = self.module.resolve_global_addr(global); + let rhs = T::global_get(&self.store.state.globals, addr); + let lhs = T::stack_pop(&mut self.store.value_stack); + T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_stack_local( + &mut self, + local: LocalAddr, + destination: Option, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let rhs = T::local_get(&self.store.value_stack, &self.cf, local); + let lhs = T::stack_pop(&mut self.store.value_stack); + self.exec_binop_result::(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_const_tee( + &mut self, + rhs: T, + destination: LocalAddr, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let value = T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs))?; + T::local_set(&mut self.store.value_stack, &self.cf, destination, value); + Ok(()) + } + + #[inline(always)] + fn exec_mul_acc_local( + &mut self, + accumulator: LocalAddr, + multiply: fn(T, T) -> T, + add: fn(T, T) -> T, + ) { + let rhs = T::stack_pop(&mut self.store.value_stack); + let lhs = T::stack_pop(&mut self.store.value_stack); + let product = multiply(lhs, rhs); + T::local_update( + &mut self.store.value_stack, + &self.cf, + accumulator, + #[inline(always)] + |value| add(product, value), + ); + } + + fn exec_branch_table(&mut self, index: Operand128Idx) -> usize { + let v = index.resolve(&self.func.data); let idx = ::stack_pop(&mut self.store.value_stack); - let target_ip = if idx >= 0 && (idx as u32) < v.len { - self.func.data.branch_table_targets.get((v.start + idx as u32) as usize).copied().unwrap_or(v.target) + let target_ip = if idx >= 0 && (idx as u32) < v.size() { + self.func.data.branch_table_targets.get((v.start() + idx as u32) as usize).copied().unwrap_or(v.target()) } else { - v.target + v.target() }; target_ip as usize @@ -929,12 +1199,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.state.alloc_exception(tag_addr, payload, roots) } - fn exec_throw(&mut self, tag_index: TagAddr, instr_ptr: usize) -> Result { + fn exec_throw(&mut self, tag_index: TagAddr, instr_ptr: usize) -> Result> { let exception = self.create_exception(tag_index)?; self.throw_exception(exception, instr_ptr) } - fn exec_throw_ref(&mut self, instr_ptr: usize) -> Result { + fn exec_throw_ref(&mut self, instr_ptr: usize) -> Result> { let exception = ValueRef::stack_pop(&mut self.store.value_stack); if exception.is_null() { return Err(Trap::NullReference.into()); @@ -942,11 +1212,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.throw_exception(exception, instr_ptr) } - fn throw_exception(&mut self, exception: ValueRef, protected_ip: usize) -> Result { - match self.dispatch_exception(exception, protected_ip) { - Ok(Some(landing_pad)) => Ok(landing_pad), - Ok(None) => self.store.root_exception(exception).and_then(|exception| Err(Error::Exception(exception))), - Err(trap) => Err(trap.into()), + fn throw_exception(&mut self, exception: ValueRef, protected_ip: usize) -> Result> { + match self.dispatch_exception(exception, protected_ip)? { + Some(landing_pad) => Ok(ControlFlow::Continue(landing_pad)), + None => self.store.root_exception(exception).and_then(|exception| Err(Error::Exception(exception))), } } @@ -964,6 +1233,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }) } + #[inline(always)] fn switch_to_frame(&mut self, frame: CallFrame) { let previous = core::mem::replace(&mut self.cf, frame); if previous.func_addr == self.cf.func_addr { @@ -1013,7 +1283,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return Ok(None); }; self.switch_to_frame(caller); - protected_ip = self.cf.instr_ptr.checked_sub(1).unwrap_or_else(|| unreachable!("invalid caller IP")); + protected_ip = unwrap_or_unreachable!(self.cf.instr_ptr.checked_sub(1), "invalid caller IP"); } } @@ -1066,7 +1336,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { host_func: HostFunction, type_addr: TypeAddr, return_instr_ptr: usize, - ) -> Result, Trap> { + ) -> Result> { if let Some(host_func) = host_func.typed_callback() { cold_err!(host_func.call_stack(self.store, self.module.id(), type_addr)) .map_err(|error| Trap::HostFunction(Box::new(error)))?; @@ -1101,7 +1371,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if TAIL { Ok(self.exec_return()) } else { Ok(ControlFlow::Continue(return_instr_ptr)) } } - fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> Result, Trap> { + fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); let func = self.store.state.get_func(addr); @@ -1116,7 +1386,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_return_call_direct(&mut self, v: u32) -> Result, Trap> { + fn exec_return_call_direct(&mut self, v: u32) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); let func = self.store.state.get_func(addr); @@ -1131,34 +1401,36 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_call_self(&mut self, return_instr_ptr: usize) -> Result<(), Trap> { + fn exec_call_self(&mut self, return_instr_ptr: usize) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else { - return cold!(Err(Trap::CallStackOverflow)); + return cold!(Err(Trap::CallStackOverflow.into())); }; let new = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); self.store.call_stack.push(core::mem::replace(&mut self.cf, new), return_instr_ptr)?; - Ok(()) + Ok(ControlFlow::Continue(0)) } - fn exec_return_call_self(&mut self) -> Result<(), Trap> { + fn exec_return_call_self(&mut self) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.params); let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else { - return cold!(Err(Trap::CallStackOverflow)); + return cold!(Err(Trap::CallStackOverflow.into())); }; self.cf = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); - Ok(()) + Ok(ControlFlow::Continue(0)) } fn exec_call_indirect( &mut self, - index: OperandIdx, + index: Operand64Idx<(u32, u32)>, return_instr_ptr: usize, - ) -> Result, Trap> { - let TwoU32 { first: type_addr, second: table_addr } = index.get(&self.func.data); + ) -> Result> { + let operand = index.resolve(&self.func.data); + let type_addr = operand.a(); + let table_addr = operand.b(); self.charge_call_fuel(FUEL_COST_CALL_TOTAL); // verify that the table is of the right type, this should be validated by the parser already let table_addr = self.module.resolve_table_addr(table_addr); @@ -1166,11 +1438,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table = self.store.state.get_table(table_addr); let Ok(table) = table.get(table_idx) else { - return cold!(Err(Trap::UndefinedElement { index: table_idx })); + return cold!(Err(Trap::UndefinedElement { index: table_idx }.into())); }; let Some(func_ref) = table.addr() else { - return cold!(Err(Trap::UninitializedElement { index: table_idx })); + return cold!(Err(Trap::UninitializedElement { index: table_idx }.into())); }; self.exec_typed_call::(func_ref, self.module.resolve_type_addr(type_addr), return_instr_ptr) @@ -1181,13 +1453,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { func_addr: FuncAddr, expected_type_addr: TypeAddr, return_instr_ptr: usize, - ) -> Result, Trap> { + ) -> Result> { let func = self.store.state.get_func(func_addr); if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) { return cold!(Err(Trap::IndirectCallTypeMismatch { actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()), expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), - })); + } + .into())); } match &func.inner { crate::store::FunctionInstanceInner::Wasm(wasm_func) => match IS_RETURN_CALL { @@ -1205,11 +1478,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { &mut self, type_addr: u32, return_instr_ptr: usize, - ) -> Result, Trap> { + ) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let func_ref = ValueRef::stack_pop(&mut self.store.value_stack); let Some(func_addr) = func_ref.addr() else { - return cold!(Err(Trap::NullFunctionReference)); + return cold!(Err(Trap::NullFunctionReference.into())); }; self.exec_typed_call::(func_addr, self.module.resolve_type_addr(type_addr), return_instr_ptr) @@ -1234,13 +1507,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ControlFlow::Continue(instr_ptr) } - #[inline(always)] fn exec_return_void(&mut self) -> ControlFlow<(), usize> { self.store.value_stack.truncate_to_base(self.cf.locals_base); self.finish_return() } - #[inline(always)] fn exec_return_32(&mut self) -> ControlFlow<(), usize> { self.store.value_stack.stack_32.truncate_to_one_tail(self.cf.locals_base.s32 as usize); self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize); @@ -1248,7 +1519,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.finish_return() } - #[inline(always)] fn exec_return_64(&mut self) -> ControlFlow<(), usize> { self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize); self.store.value_stack.stack_64.truncate_to_one_tail(self.cf.locals_base.s64 as usize); @@ -1256,7 +1526,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.finish_return() } - #[inline(always)] fn exec_return_128(&mut self) -> ControlFlow<(), usize> { self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize); self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize); @@ -1264,15 +1533,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.finish_return() } - #[inline(always)] fn exec_store_local_local, const N: usize>( &mut self, - memarg: CompactMemoryArg, + index: Operand64Idx, addr_local: u8, value_local: u8, ) -> Result<(), Trap> { + let memarg = index.resolve(&self.func.data); let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local)); - let mem_addr = self.mem_addr(memarg.mem_addr()); + let mem_addr = self.mem_addr(MemAddr::from(memarg.memory())); let mem = self.store.state.get_mem_mut(mem_addr); let addr = if mem.is_64bit() { let base = u64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); @@ -1281,22 +1550,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { len: N, max: mem.inner.len(), }))?; - mem.effective_addr::(base, memarg.offset())? + cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))? } else { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); - mem.effective_addr::(base as usize, memarg.offset())? + cold_err!(mem.effective_addr::(base as usize, u64::from(memarg.offset())))? }; value.store_at(&mut mem.inner, addr) } - #[inline(always)] fn exec_inc_memory_local, const N: usize>( &mut self, - memarg: CompactMemoryArg, + index: Operand64Idx, addr_local: u8, increment: impl FnOnce(T) -> T, ) -> Result<(), Trap> { - let mem_addr = self.mem_addr(memarg.mem_addr()); + let memarg = index.resolve(&self.func.data); + let mem_addr = self.mem_addr(MemAddr::from(memarg.memory())); let mem = self.store.state.get_mem_mut(mem_addr); let addr = if mem.is_64bit() { let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; @@ -1305,17 +1574,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { len: N, max: mem.inner.len(), }))?; - mem.effective_addr::(base, memarg.offset())? + cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))? } else { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); - mem.effective_addr::(base as usize, memarg.offset())? + cold_err!(mem.effective_addr::(base as usize, u64::from(memarg.offset())))? }; let value = cold_err!(T::load_at(&mem.inner, addr))?; increment(value).store_at(&mut mem.inner, addr) } - #[inline(always)] fn exec_fma_store< T: InternalValue + MemValue + core::ops::Add + core::ops::Mul, const N: usize, @@ -1330,18 +1598,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem_mut(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, m.offset())?; - fma.store_at(&mut mem.inner, addr)?; - Ok(()) + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; + cold_err!(fma.store_at(&mut mem.inner, addr)) } - #[inline(always)] fn exec_load_local_value, const N: usize>( &self, - memarg: CompactMemoryArg, + memarg: Operand64, addr_local: u8, ) -> Result { - let mem = self.store.state.get_mem(self.mem_addr(memarg.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(MemAddr::from(memarg.memory()))); let addr = if mem.is_64bit() { let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds { @@ -1349,15 +1615,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { len: N, max: mem.inner.len(), }))?; - mem.effective_addr::(base, memarg.offset())? + cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))? } else { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); - mem.effective_addr::(base as usize, memarg.offset())? + cold_err!(mem.effective_addr::(base as usize, u64::from(memarg.offset())))? }; cold_err!(T::load_at(&mem.inner, addr)) } - #[inline(always)] fn exec_load_local< LOAD: MemValue, const N: usize, @@ -1366,11 +1631,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { const TEE: bool, >( &mut self, - memarg: CompactMemoryArg, + index: Operand64Idx, addr_local: u8, dst_local: u8, cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { + let memarg = index.resolve(&self.func.data); let value = cast(self.exec_load_local_value::(memarg, addr_local)?); if SET_LOCAL { TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value); @@ -1382,7 +1648,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_ref_is_null(&mut self) -> Result<(), Trap> { - let is_null = i32::from(::stack_pop(&mut self.store.value_stack).is_null()); + let is_null = i32::from(ValueRef::stack_pop(&mut self.store.value_stack).is_null()); self.store.value_stack.push::(is_null) } @@ -1463,8 +1729,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_struct_get(&mut self, index: OperandIdx, signed: Option) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data); + fn exec_struct_get(&mut self, index: Operand64Idx<(u32, u32)>, signed: Option) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let field_index = operand.b(); let reference = ValueRef::stack_pop(&mut self.store.value_stack); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.get type").fields @@ -1476,8 +1744,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { push_value(&mut self.store.value_stack, value, storage, signed) } - fn exec_struct_set(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data); + fn exec_struct_set(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let field_index = operand.b(); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.set type").fields [field_index as usize] @@ -1501,8 +1771,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_new_fixed(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: len } = index.get(&self.func.data); + fn exec_array_new_fixed(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let len = operand.b(); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; @@ -1567,8 +1839,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: dst_type, second: src_type } = index.get(&self.func.data); + fn exec_array_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let dst_type = operand.a(); + let src_type = operand.b(); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src_index = u32::stack_pop(&mut self.store.value_stack) as usize; let src = ValueRef::stack_pop(&mut self.store.value_stack); @@ -1595,8 +1869,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_new_data(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data); + fn exec_array_new_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let data_index = operand.b(); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let type_addr = self.module.resolve_type_addr(type_index); @@ -1609,8 +1885,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_new_elem(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); + fn exec_array_new_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let elem_index = operand.b(); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let type_addr = self.module.resolve_type_addr(type_index); @@ -1623,8 +1901,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_init_data(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data); + fn exec_array_init_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let data_index = operand.b(); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let dst = u32::stack_pop(&mut self.store.value_stack) as usize; @@ -1641,8 +1921,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_init_elem(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); + fn exec_array_init_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let elem_index = operand.b(); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let dst = u32::stack_pop(&mut self.store.value_stack) as usize; @@ -1674,21 +1956,23 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let mem = self.store.state.get_mem_mut(mem_addr); let is_64bit = mem.is_64bit(); let pages_delta = match is_64bit { - true => ::stack_pop(&mut self.store.value_stack), - false => i64::from(::stack_pop(&mut self.store.value_stack)), + true => i64::stack_pop(&mut self.store.value_stack), + false => i64::from(i32::stack_pop(&mut self.store.value_stack)), }; let size = mem.grow(pages_delta, limiter)?.unwrap_or(-1); match is_64bit { - true => self.store.value_stack.push::(size)?, - false => self.store.value_stack.push::(size as i32)?, + true => i64::stack_push(&mut self.store.value_stack, size)?, + false => i32::stack_push(&mut self.store.value_stack, size as i32)?, }; Ok(()) } - fn exec_memory_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: dst_mem, second: src_mem } = index.get(&self.func.data); + fn exec_memory_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let dst_mem = operand.a(); + let src_mem = operand.b(); let dst_mem_addr = self.mem_addr(dst_mem); let src_mem_addr = self.mem_addr(src_mem); let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch(); @@ -1720,12 +2004,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.exec_memory_fill_impl(mem_addr, dst, val as u8, size) } - fn exec_memory_fill_const(&mut self, index: OperandIdx) -> Result<(), Trap> { - let MemoryFillConstOp { memory: addr, byte: val, value: size } = index.get(&self.func.data); - let mem_addr = self.mem_addr(addr); + fn exec_memory_fill_const(&mut self, index: Operand128Idx) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let mem_addr = self.mem_addr(operand.memory()); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let dst = self.store.value_stack.pop_memory_operand(arch)?; - self.exec_memory_fill_impl(mem_addr, dst, val, size as u32 as usize) + self.exec_memory_fill_impl(mem_addr, dst, operand.byte(), operand.value() as u32 as usize) } fn exec_memory_fill_impl(&mut self, mem_addr: MemAddr, dst: usize, val: u8, size: usize) -> Result<(), Trap> { @@ -1737,8 +2021,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_memory_init(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: data_index, second: mem_index } = index.get(&self.func.data); + fn exec_memory_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let data_index = operand.a(); + let mem_index = operand.b(); let size = u32::stack_pop(&mut self.store.value_stack) as usize; let offset = u32::stack_pop(&mut self.store.value_stack) as usize; let mem_addr = self.mem_addr(mem_index); @@ -1770,8 +2056,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_table_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: dst_table, second: src_table } = index.get(&self.func.data); + fn exec_table_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let dst_table = operand.a(); + let src_table = operand.b(); let dst_table_addr = self.module.resolve_table_addr(dst_table); let src_table_addr = self.module.resolve_table_addr(src_table); let dst_arch = self.store.state.get_table(dst_table_addr).kind.arch(); @@ -1796,13 +2084,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { &mut self, arg: MemoryLaneArg, ) -> Result<(), Trap> { - let m = arg.memory_arg_idx.get(&self.func.data); - let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr())); + let m = arg.memory_arg_idx.resolve(&self.func.data); + let mem = self.store.state.get_mem(self.mem_addr(m.memory())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, m.offset())?; + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; let val = cold_err!(LOAD::load_at(&mem.inner, addr))?; let offset = arg.lane as usize * LOAD_SIZE; - let mut imm = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); + let mut imm = Value128::stack_pop(&mut self.store.value_stack).to_mem_bytes(); imm[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); self.store.value_stack.push(Value128(imm))?; Ok(()) @@ -1811,47 +2099,65 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_mem_load, const LOAD_SIZE: usize, TARGET: InternalValue>( &mut self, - index: OperandIdx, + m: Operand128, cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { - let m = index.get(&self.func.data); - let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(m.memory())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, m.offset())?; + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; let value = cold_err!(LOAD::load_at(&mem.inner, addr))?; self.store.value_stack.push(cast(value)) } + #[inline(always)] fn exec_mem_store_lane + Copy, const N: usize>(&mut self, arg: MemoryLaneArg) -> Result<(), Trap> { - let bytes = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); + let bytes = Value128::stack_pop(&mut self.store.value_stack).to_mem_bytes(); let lane_offset = arg.lane as usize * N; let mut val_bytes = [0u8; N]; val_bytes.copy_from_slice(&bytes[lane_offset..lane_offset + N]); let val = U::from_mem_bytes(val_bytes); - let m = arg.memory_arg_idx.get(&self.func.data); - let mem_addr = self.mem_addr(m.mem_addr()); + let m = arg.memory_arg_idx.resolve(&self.func.data); + let mem_addr = self.mem_addr(m.memory()); let mem = self.store.state.get_mem_mut(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, m.offset())?; + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; cold_err!(val.store_at(&mut mem.inner, addr))?; Ok(()) } + #[inline(always)] fn exec_mem_store, const N: usize>( &mut self, - index: OperandIdx, + memory: Operand128, cast: impl Fn(T) -> U, ) -> Result<(), Trap> { - let val = ::stack_pop(&mut self.store.value_stack); - let val = cast(val); + let val = cast(::stack_pop(&mut self.store.value_stack)); + self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), val) + } - let m = index.get(&self.func.data); - let mem_addr = self.mem_addr(m.mem_addr()); - let mem = self.store.state.get_mem_mut(mem_addr); + #[inline(always)] + fn exec_select_store, const N: usize>( + &mut self, + memory: Operand128, + ) -> Result<(), Trap> { + let condition = Value32::stack_pop(&mut self.store.value_stack); + let false_value = T::stack_pop(&mut self.store.value_stack); + let true_value = T::stack_pop(&mut self.store.value_stack); + let value = if condition == 0 { false_value } else { true_value }; + self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), value) + } + + #[inline(always)] + fn exec_mem_store_value, const N: usize>( + &mut self, + memory_addr: MemAddr, + offset: u64, + val: U, + ) -> Result<(), Trap> { + let mem = self.store.state.get_mem_mut(memory_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, m.offset())?; - cold_err!(val.store_at(&mut mem.inner, addr))?; - Ok(()) + let addr = cold_err!(mem.effective_addr::(base, offset))?; + cold_err!(val.store_at(&mut mem.inner, addr)) } fn exec_table_get(&mut self, table_index: u32) -> Result<(), Trap> { @@ -1862,7 +2168,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> { - let val = ::stack_pop(&mut self.store.value_stack); + let val = ValueRef::stack_pop(&mut self.store.value_stack); let table_addr = self.module.resolve_table_addr(table_index); let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; let table = self.store.state.get_table_mut(table_addr); @@ -1877,8 +2183,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_table_init(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: elem_index, second: table_index } = index.get(&self.func.data); + fn exec_table_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let elem_index = operand.a(); + let table_index = operand.b(); let size = self.pop_table_operand(MemoryArch::I32)?; // n let offset = self.pop_table_operand(MemoryArch::I32)?; // s let table_addr = self.module.resolve_table_addr(table_index); @@ -1896,7 +2204,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table_addr = self.module.resolve_table_addr(table_index); let arch = self.store.state.get_table(table_addr).kind.arch(); let n = self.pop_table_operand(arch)?; - let val = ::stack_pop(&mut self.store.value_stack); + let val = ValueRef::stack_pop(&mut self.store.value_stack); let limiter = self.store.engine.config().resource_limiter.as_deref(); let table = self.store.state.get_table_mut(table_addr); let sz = table.size(); @@ -1913,15 +2221,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table_addr = self.module.resolve_table_addr(table_index); let arch = self.store.state.get_table(table_addr).kind.arch(); let n = self.pop_table_operand(arch)?; - let val = ::stack_pop(&mut self.store.value_stack); + let val = ValueRef::stack_pop(&mut self.store.value_stack); let i = self.pop_table_operand(arch)?; self.store.state.get_table_mut(table_addr).fill(i, n, val) } fn pop_table_operand(&mut self, arch: MemoryArch) -> Result { let value = match arch { - MemoryArch::I32 => ::stack_pop(&mut self.store.value_stack) as u32 as u64, - MemoryArch::I64 => ::stack_pop(&mut self.store.value_stack) as u64, + MemoryArch::I32 => i32::stack_pop(&mut self.store.value_stack) as u32 as u64, + MemoryArch::I64 => i64::stack_pop(&mut self.store.value_stack) as u64, }; cold_err!(usize::try_from(value).map_err(|_| Trap::TableOutOfBounds { offset: usize::MAX, @@ -1994,92 +2302,3 @@ impl<'store> Executor<'store, true> { } } } - -#[inline(always)] -fn cmp_i32(lhs: i32, rhs: i32, op: CmpOp) -> bool { - match op { - CmpOp::Eq => lhs == rhs, - CmpOp::Ne => lhs != rhs, - CmpOp::LtS => lhs < rhs, - CmpOp::LtU => (lhs as u32) < (rhs as u32), - CmpOp::GtS => lhs > rhs, - CmpOp::GtU => (lhs as u32) > (rhs as u32), - CmpOp::LeS => lhs <= rhs, - CmpOp::LeU => (lhs as u32) <= (rhs as u32), - CmpOp::GeS => lhs >= rhs, - CmpOp::GeU => (lhs as u32) >= (rhs as u32), - } -} - -#[inline(always)] -fn cmp_i64(lhs: i64, rhs: i64, op: CmpOp) -> bool { - match op { - CmpOp::Eq => lhs == rhs, - CmpOp::Ne => lhs != rhs, - CmpOp::LtS => lhs < rhs, - CmpOp::LtU => (lhs as u64) < (rhs as u64), - CmpOp::GtS => lhs > rhs, - CmpOp::GtU => (lhs as u64) > (rhs as u64), - CmpOp::LeS => lhs <= rhs, - CmpOp::LeU => (lhs as u64) <= (rhs as u64), - CmpOp::GeS => lhs >= rhs, - CmpOp::GeU => (lhs as u64) >= (rhs as u64), - } -} - -fn exec_binop_32(op: BinOp, lhs: u32, rhs: u32) -> u32 { - match op { - BinOp::IAdd => lhs.wrapping_add(rhs), - BinOp::ISub => lhs.wrapping_sub(rhs), - BinOp::IMul => lhs.wrapping_mul(rhs), - BinOp::IAnd => lhs & rhs, - BinOp::IOr => lhs | rhs, - BinOp::IXor => lhs ^ rhs, - BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32, - BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32, - BinOp::IShrU => lhs.wrapping_shr(rhs), - BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32, - BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32, - BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(), - BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(), - BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(), - BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(), - BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(), - BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(), - BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(), - } -} - -fn exec_binop_64(op: BinOp, lhs: u64, rhs: u64) -> u64 { - match op { - BinOp::IAdd => lhs.wrapping_add(rhs), - BinOp::ISub => lhs.wrapping_sub(rhs), - BinOp::IMul => lhs.wrapping_mul(rhs), - BinOp::IAnd => lhs & rhs, - BinOp::IOr => lhs | rhs, - BinOp::IXor => lhs ^ rhs, - BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64, - BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64, - BinOp::IShrU => lhs.wrapping_shr(rhs as u32), - BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64, - BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64, - BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(), - BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(), - BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(), - BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(), - BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(), - BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(), - BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(), - } -} - -fn exec_binop_128(op: BinOp128, lhs: Value128, rhs: Value128) -> Value128 { - match op { - BinOp128::And => lhs.v128_and(rhs), - BinOp128::AndNot => lhs.v128_andnot(rhs), - BinOp128::Or => lhs.v128_or(rhs), - BinOp128::Xor => lhs.v128_xor(rhs), - BinOp128::I64x2Add => lhs.i64x2_add(rhs), - BinOp128::I64x2Mul => lhs.i64x2_mul(rhs), - } -} diff --git a/crates/tinywasm/src/interpreter/num_helpers.rs b/crates/tinywasm/src/interpreter/num_helpers.rs index 783b10b..d35b217 100644 --- a/crates/tinywasm/src/interpreter/num_helpers.rs +++ b/crates/tinywasm/src/interpreter/num_helpers.rs @@ -7,25 +7,22 @@ pub(crate) trait TinywasmIntExt: Sized { /// we need to check for overflow. This macro generates the min/max values /// for a specific conversion, which are then used in the actual conversion. /// Rust sadly doesn't have wrapping casts for floats yet. -#[rustfmt::skip] macro_rules! float_min_max { - (f32, i32) => {(i32::MIN as f32 - (1 << 8) as f32, i32::MAX as f32 + 1.0)}; // 2^8: f32 precision margin - (f64, i32) => {(i32::MIN as f64 - 1.0, i32::MAX as f64 + 1.0)}; - (f32, u32) => {(-1.0_f32, u32::MAX as f32 + 1.0)}; - (f64, u32) => {(-1.0_f64, u32::MAX as f64 + 1.0)}; - (f32, i64) => {(i64::MIN as f32 - (1i64 << 40) as f32, i64::MAX as f32 + 1.0)}; // 2^40: f32 has 23 mantissa bits - (f64, i64) => {(i64::MIN as f64 - (1i64 << 11) as f64, i64::MAX as f64 + 1.0)}; // 2^11: f64 precision margin - (f32, u64) => {(-1.0_f32, u64::MAX as f32 + 1.0)}; - (f64, u64) => {(-1.0_f64, u64::MAX as f64 + 1.0)}; - ($from:ty, $to:ty) => {compile_error!("invalid float conversion")}; + (f32, i32) => {{ (i32::MIN as f32 - (1 << 8) as f32, i32::MAX as f32 + 1.0) }}; // 2^8: f32 precision margin + (f64, i32) => {{ (i32::MIN as f64 - 1.0, i32::MAX as f64 + 1.0) }}; + (f32, u32) => {{ (-1.0_f32, u32::MAX as f32 + 1.0) }}; + (f64, u32) => {{ (-1.0_f64, u32::MAX as f64 + 1.0) }}; + (f32, i64) => {{ (i64::MIN as f32 - (1i64 << 40) as f32, i64::MAX as f32 + 1.0) }}; // 2^40: f32 has 23 mantissa bits + (f64, i64) => {{ (i64::MIN as f64 - (1i64 << 11) as f64, i64::MAX as f64 + 1.0) }}; // 2^11: f64 precision margin + (f32, u64) => {{ (-1.0_f32, u64::MAX as f32 + 1.0) }}; + (f64, u64) => {{ (-1.0_f64, u64::MAX as f64 + 1.0) }}; + ($from:ty, $to:ty) => {{ compile_error!("invalid float conversion") }}; } /// Convert a value on the stack with error checking macro_rules! checked_conv_float { // Direct conversion with error checking (two types) - ($from:tt, $to:tt, $self:expr) => { - checked_conv_float!($from, $to, $to, $self) - }; + ($from:tt, $to:tt, $self:expr) => {{ checked_conv_float!($from, $to, $to, $self) }}; // Conversion with an intermediate unsigned type and error checking (three types) ($from:tt, $intermediate:tt, $to:tt, $self:expr) => {{ let v = <$from>::stack_pop(&mut $self.store.value_stack); diff --git a/crates/tinywasm/src/interpreter/simd/macros.rs b/crates/tinywasm/src/interpreter/simd/macros.rs index bc7b805..9306d8f 100644 --- a/crates/tinywasm/src/interpreter/simd/macros.rs +++ b/crates/tinywasm/src/interpreter/simd/macros.rs @@ -183,18 +183,17 @@ macro_rules! lane_read { (f64, $bytes:expr, $offset:expr) => { f64::from_bits(u64::from_le_bytes([$bytes[$offset], $bytes[$offset + 1], $bytes[$offset + 2], $bytes[$offset + 3], $bytes[$offset + 4], $bytes[$offset + 5], $bytes[$offset + 6], $bytes[$offset + 7]])) }; } -#[rustfmt::skip] macro_rules! lane_write { - (i8, $value:expr) => { [$value as u8] }; - (u8, $value:expr) => { [$value] }; - (i16, $value:expr) => { $value.to_le_bytes() }; - (u16, $value:expr) => { $value.to_le_bytes() }; - (i32, $value:expr) => { $value.to_le_bytes() }; - (u32, $value:expr) => { $value.to_le_bytes() }; - (i64, $value:expr) => { $value.to_le_bytes() }; - (u64, $value:expr) => { $value.to_le_bytes() }; - (f32, $value:expr) => { $value.to_bits().to_le_bytes() }; - (f64, $value:expr) => { $value.to_bits().to_le_bytes() }; + (i8, $value:expr) => {{ [$value as u8] }}; + (u8, $value:expr) => {{ [$value] }}; + (i16, $value:expr) => {{ $value.to_le_bytes() }}; + (u16, $value:expr) => {{ $value.to_le_bytes() }}; + (i32, $value:expr) => {{ $value.to_le_bytes() }}; + (u32, $value:expr) => {{ $value.to_le_bytes() }}; + (i64, $value:expr) => {{ $value.to_le_bytes() }}; + (u64, $value:expr) => {{ $value.to_le_bytes() }}; + (f32, $value:expr) => {{ $value.to_bits().to_le_bytes() }}; + (f64, $value:expr) => {{ $value.to_bits().to_le_bytes() }}; } macro_rules! impl_lane_accessors { diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index e123a41..3748ef9 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -62,12 +62,12 @@ impl Stack { #[inline(always)] pub(crate) fn pop(&mut self) -> T { - self.data.pop().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug")) + unwrap_or_unreachable!(self.data.pop(), "ValueStack underflow, this is a bug") } #[inline(always)] pub(crate) fn last(&self) -> &T { - self.data.last().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug")) + unwrap_or_unreachable!(self.data.last(), "ValueStack underflow, this is a bug") } #[inline(always)] @@ -107,7 +107,7 @@ impl Stack { #[inline(always)] pub(crate) fn truncate_to_one_tail(&mut self, n: usize) { debug_assert!(n < self.data.len()); - let last = self.data.pop().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug")); + let last = unwrap_or_unreachable!(self.data.pop(), "ValueStack underflow, this is a bug"); self.data.truncate(n); self.data.push(last); } @@ -164,7 +164,7 @@ impl Stack { } let len = self.data.len(); - let needed = count.checked_mul(2).unwrap_or_else(|| unreachable!("Stack underflow, this is a bug")); + let needed = unwrap_or_unreachable!(count.checked_mul(2), "Stack underflow, this is a bug"); if len < needed { unreachable!("Stack underflow, this is a bug"); diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index 22f20b7..83b520b 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -1,7 +1,8 @@ +use super::num_helpers::TinywasmFloatExt; use super::stack::{CallFrame, ValueStack}; use crate::store::Globals; use crate::{Error, Result, Store, WasmValue, interpreter::simd::Value128}; -use tinywasm_types::{GlobalAddr, LocalAddr, WasmType}; +use tinywasm_types::{BinOp, BinOp128, CmpOp, GlobalAddr, LocalAddr, WasmType}; pub(crate) type Value32 = u32; pub(crate) type Value64 = u64; @@ -114,14 +115,24 @@ pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap>; fn stack_pop(stack: &mut ValueStack) -> Self; fn stack_peek(stack: &ValueStack) -> Self; + fn stack_update(stack: &mut ValueStack, f: impl FnOnce(Self) -> Self) -> Result { + let value = f(Self::stack_pop(stack)); + Self::stack_push(stack, value)?; + Ok(value) + } fn stack_select(stack: &mut ValueStack); fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self; fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap>; fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self); - fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self); + fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self) -> Self; fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr); fn global_get(globals: &Globals, addr: GlobalAddr) -> Self; fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self); + fn global_update(globals: &mut Globals, addr: GlobalAddr, f: impl FnOnce(Self) -> Self) -> Self { + let value = f(Self::global_get(globals, addr)); + Self::global_set(globals, addr, value); + value + } } macro_rules! impl_internalvalue { @@ -136,13 +147,6 @@ macro_rules! impl_internalvalue { impl sealed::Sealed for $outer {} impl InternalValue for $outer { - #[inline(always)] - fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap> { - let $to_stack_v = value; - cold_err!(stack.$stack.push($to_stack))?; - Ok(()) - } - #[inline(always)] fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self { let $from_stack_v = @@ -168,11 +172,13 @@ macro_rules! impl_internalvalue { frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self, - ) { + ) -> Self { let abs_index = frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize; let $from_stack_v = *stack.$stack.get(abs_index); - let $to_stack_v = f($from_stack); + let value = f($from_stack); + let $to_stack_v = value; stack.$stack.set(abs_index, $to_stack); + value } #[inline(always)] @@ -194,6 +200,13 @@ macro_rules! impl_internalvalue { globals.$global_set(addr, $to_stack); } + #[inline(always)] + fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap> { + let $to_stack_v = value; + cold_err!(stack.$stack.push($to_stack))?; + Ok(()) + } + #[inline(always)] fn stack_pop(stack: &mut ValueStack) -> Self { let $from_stack_v = stack.$stack.pop(); @@ -232,6 +245,105 @@ impl_internalvalue! { stack_128, s128, get_128, set_128, Value128, |v| v, |v| v } +pub(crate) trait BinOpExt: Copy { + fn exec(self, lhs: T, rhs: T) -> T; +} + +impl BinOpExt for BinOp { + #[inline(always)] + fn exec(self, lhs: Value32, rhs: Value32) -> Value32 { + match self { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32, + BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32, + BinOp::IShrU => lhs.wrapping_shr(rhs), + BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32, + BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32, + BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(), + BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(), + BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(), + BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(), + BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(), + } + } +} + +impl BinOpExt for BinOp { + #[inline(always)] + fn exec(self, lhs: Value64, rhs: Value64) -> Value64 { + match self { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64, + BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64, + BinOp::IShrU => lhs.wrapping_shr(rhs as u32), + BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64, + BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64, + BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(), + BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(), + BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(), + BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(), + BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(), + } + } +} + +impl BinOpExt for BinOp128 { + #[inline(always)] + fn exec(self, lhs: Value128, rhs: Value128) -> Value128 { + match self { + BinOp128::And => lhs.v128_and(rhs), + BinOp128::AndNot => lhs.v128_andnot(rhs), + BinOp128::Or => lhs.v128_or(rhs), + BinOp128::Xor => lhs.v128_xor(rhs), + BinOp128::I64x2Add => lhs.i64x2_add(rhs), + BinOp128::I64x2Mul => lhs.i64x2_mul(rhs), + } + } +} + +pub(crate) trait CmpOpExt: Copy { + fn cmp(self, lhs: T, rhs: T) -> bool; +} + +macro_rules! impl_cmp_value { + ($ty:ty, $unsigned:ty) => { + impl CmpOpExt<$ty> for CmpOp { + #[inline(always)] + fn cmp(self, lhs: $ty, rhs: $ty) -> bool { + match self { + CmpOp::Eq => lhs == rhs, + CmpOp::Ne => lhs != rhs, + CmpOp::LtS => lhs < rhs, + CmpOp::LtU => (lhs as $unsigned) < (rhs as $unsigned), + CmpOp::GtS => lhs > rhs, + CmpOp::GtU => (lhs as $unsigned) > (rhs as $unsigned), + CmpOp::LeS => lhs <= rhs, + CmpOp::LeU => (lhs as $unsigned) <= (rhs as $unsigned), + CmpOp::GeS => lhs >= rhs, + CmpOp::GeU => (lhs as $unsigned) >= (rhs as $unsigned), + } + } + } + }; +} + +impl_cmp_value!(i32, u32); +impl_cmp_value!(i64, u64); + #[cfg(test)] mod tests { use super::ValueRef; diff --git a/crates/tinywasm/src/macros.rs b/crates/tinywasm/src/macros.rs index 351ae88..b071259 100644 --- a/crates/tinywasm/src/macros.rs +++ b/crates/tinywasm/src/macros.rs @@ -16,3 +16,21 @@ macro_rules! cold_err { } }; } + +macro_rules! unwrap_or_unreachable { + ($value:expr) => {{ + unwrap_or_unreachable!($value, "entered unreachable code") + }}; + ($value:expr, $($message:tt)+) => {{ + match $value { + Some(value) => value, + None => $crate::macros::unwrap_unreachable(format_args!($($message)+)), + } + }}; +} + +#[cold] +#[inline(never)] +pub(crate) fn unwrap_unreachable(message: core::fmt::Arguments<'_>) -> ! { + unreachable!("{message}") +} diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index 4052eb8..42a2acf 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -30,16 +30,16 @@ impl GlobalLane { #[inline(always)] fn get(&self, index: usize, addr: GlobalAddr) -> T { - *self.values.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + *unwrap_or_unreachable!(self.values.get(index), "invalid global address: {addr}") } #[inline(always)] fn set(&mut self, index: usize, addr: GlobalAddr, value: T) { - *self.values.get_mut(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) = value; + *unwrap_or_unreachable!(self.values.get_mut(index), "invalid global address: {addr}") = value; } fn ty(&self, index: usize, addr: GlobalAddr) -> GlobalType { - *self.types.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + *unwrap_or_unreachable!(self.types.get(index), "invalid global address: {addr}") } } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 93e62a5..d4c8b15 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -489,15 +489,14 @@ impl Store { } /// Reads typed results from the value stack and restores its previous base. + #[inline] pub(crate) fn take_typed_results( &mut self, type_addr: TypeAddr, stack_base: StackBase, ) -> Result { - let result = { - let mut values = self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base)?; - R::from_wasm_values_exact(&mut values) - }; + let mut values = cold_err!(self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base))?; + let result = cold_err!(R::from_wasm_values_exact(&mut values)); self.value_stack.truncate_to_base(stack_base); result } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 769fc8b..49efcdc 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -284,11 +284,11 @@ impl State { } pub(super) fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T { - items.get(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}")) + unwrap_or_unreachable!(items.get(addr as usize), "invalid {kind} address: {addr}") } fn get_mut<'a, T>(items: &'a mut [T], addr: Addr, kind: &str) -> &'a mut T { - items.get_mut(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}")) + unwrap_or_unreachable!(items.get_mut(addr as usize), "invalid {kind} address: {addr}") } fn get_disjoint_mut<'a, T>(items: &'a mut [T], addr: Addr, addr2: Addr, kind: &str) -> (&'a mut T, &'a mut T) { diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index db13ab0..bdce379 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -64,11 +64,11 @@ impl Module { #[cfg(test)] mod tests { use super::*; + use crate::Operand128Idx; use crate::{ - AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, RefType, - Shared, V128Operand, WasmFunction, WasmType, + AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, Operand128, + RefType, Shared, WasmFunction, WasmType, }; - use crate::{OperandIdx, OperandType}; use alloc::boxed::Box; #[test] @@ -91,8 +91,8 @@ mod tests { fn v128_operands_round_trip_archive() { let bytes = [0x00, 0x01, 0x02, 0x03, 0x7f, 0x80, 0xfe, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x90]; let mut function = WasmFunction::default(); - let constant = OperandIdx::new(0); - function.data.operands128 = Box::new([V128Operand { value: bytes }.encode()]); + let constant = Operand128Idx::new(0); + function.data.operands128 = Box::new([Operand128::<[u8; 16]>::new(bytes).cast()]); function.instructions = Box::new([Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)]); let module = Module::from(ModuleInner { funcs: Box::new([Shared::new(function)]), ..ModuleInner::default() }); @@ -106,7 +106,7 @@ mod tests { Instruction::Const128(index) | Instruction::I8x16Shuffle(index) => *index, _ => panic!("unexpected instruction"), }; - assert_eq!(index.get(&function.data).value, bytes); + assert_eq!(index.resolve(&function.data).value(), bytes); } } diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 7e0cd28..9330af6 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,18 +1,31 @@ use alloc::boxed::Box; use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; -use crate::operands::sealed; -use crate::{DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand128, OperandIdx, OperandType, RefType}; +use crate::operands::read_field; +use crate::{ + DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand64Idx, Operand128, Operand128Idx, OperandIdx, RefType, +}; -/// Represents a memory immediate in a WebAssembly memory instruction. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -#[repr(Rust, packed)] -pub struct MemoryArg { - offset: u64, - mem_addr: MemAddr, -} +/// Identifies the packed full-width memory operand layout. +pub enum MemoryOperand {} + +/// Identifies the packed compact memory operand layout. +pub enum CompactMemoryOperand {} + +/// Identifies a packed branch-table operand. +pub enum BranchTableOperand {} + +/// Identifies a packed constant memory-fill operand. +pub enum MemoryFillOperand {} + +/// Identifies a packed local update and branch operand. +pub enum LocalUpdateOperand {} + +/// Identifies a packed global update and branch operand. +pub enum GlobalUpdateOperand {} + +/// Identifies a packed local update, comparison, and branch operand. +pub enum LocalUpdateCmpOperand {} /// A compact memory immediate used by optimized instructions. /// @@ -33,7 +46,7 @@ pub struct CompactMemoryArg { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] #[repr(Rust, packed)] pub struct MemoryLocalArg { - pub memory_arg_idx: OperandIdx, + pub memory_arg_idx: Operand64Idx, pub local1: u8, pub local2: u8, } @@ -44,7 +57,7 @@ pub struct MemoryLocalArg { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] #[repr(Rust, packed)] pub struct MemoryLaneArg { - pub memory_arg_idx: OperandIdx, + pub memory_arg_idx: Operand128Idx, pub lane: u8, } @@ -68,22 +81,6 @@ pub struct LocalTripleArg { pub dst: LocalAddr, } -impl sealed::Sealed for LocalTripleArg {} - -impl OperandType for LocalTripleArg { - type Raw = Operand64; - - #[inline(always)] - fn decode(raw: Self::Raw) -> Self { - Self { left: raw.u16::<0>(), right: raw.u16::<2>(), dst: raw.u16::<4>() } - } - - #[inline] - fn encode(self) -> Self::Raw { - Operand64::default().with_u16::<0>(self.left).with_u16::<2>(self.right).with_u16::<4>(self.dst) - } -} - /// A branch target and local operand that fit in an instruction payload. #[derive(Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] @@ -94,194 +91,55 @@ pub struct TargetLocalArg { pub local: LocalAddr, } -macro_rules! operand_view { - ($name:ident, $lane:ident, $raw:ty, { $($field:ident : $ty:ty = $read:ident / $write:ident ($offset:expr)),+ $(,)? }) => { - #[derive(Copy, Clone, PartialEq, Eq)] - #[cfg_attr(feature = "debug", derive(Debug))] - pub struct $name { - $(pub $field: $ty),+ - } - - impl sealed::Sealed for $name {} - - impl OperandType for $name { - type Raw = $raw; - - #[inline(always)] - fn decode(raw: Self::Raw) -> Self { - Self { $($field: raw.$read::<$offset>() as $ty),+ } - } - - #[inline] - fn encode(self) -> Self::Raw { - <$raw>::default()$(.$write::<$offset>(self.$field as _))+ - } - } - }; -} - -operand_view!(I64Operand, operands64, Operand64, { value: i64 = u64 / with_u64(0) }); -operand_view!(TwoU32, operands64, Operand64, { - first: u32 = u32 / with_u32(0), second: u32 = u32 / with_u32(4) -}); -operand_view!(LocalU32, operands64, Operand64, { - local: u16 = u16 / with_u16(0), value: u32 = u32 / with_u32(2) -}); -operand_view!(TargetLocal, operands64, Operand64, { - target: u32 = u32 / with_u32(0), local: u16 = u16 / with_u16(4) -}); - -operand_view!(LocalConst64, operands128, Operand128, { - local: u16 = u16 / with_u16(0), value: u64 = u64 / with_u64(2) -}); -operand_view!(GlobalConst32, operands64, Operand64, { - global: u32 = u32 / with_u32(0), value: u32 = u32 / with_u32(4) -}); -operand_view!(GlobalConst64, operands128, Operand128, { - global: u32 = u32 / with_u32(0), value: u64 = u64 / with_u64(4) -}); -operand_view!(LocalConstSet32, operands64, Operand64, { - local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u32 = u32 / with_u32(4) -}); -operand_view!(LocalConstSet64, operands128, Operand128, { - local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u64 = u64 / with_u64(4) -}); -operand_view!(MemoryFillConstOp, operands128, Operand128, { - memory: u32 = u32 / with_u32(0), byte: u8 = u8 / with_u8(4), value: i32 = u32 / with_u32(5) -}); -operand_view!(CastBranch, operands64, Operand64, { - target: u32 = u32 / with_u32(0), ref_type_bits: u32 = u32 / with_u32(4) -}); -operand_view!(BranchTableArg, operands128, Operand128, { - target: u32 = u32 / with_u32(0), start: u32 = u32 / with_u32(4), len: u32 = u32 / with_u32(8) -}); -operand_view!(StackConst32, operands64, Operand64, { - target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4) -}); -operand_view!(StackConst64, operands128, Operand128, { - target: u32 = u32 / with_u32(0), value: i64 = u64 / with_u64(4) -}); -operand_view!(LocalConstCmp, operands128, Operand128, { - target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8) -}); -operand_view!(LocalLocalCmp, operands64, Operand64, { - target: u32 = u32 / with_u32(0), left: u16 = u16 / with_u16(4), right: u16 = u16 / with_u16(6) -}); -operand_view!(LocalUpdate, operands128, Operand128, { - target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), on_zero: u8 = u8 / with_u8(10) -}); -operand_view!(GlobalUpdate, operands128, Operand128, { - target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), global: u32 = u32 / with_u32(8), on_zero: u8 = u8 / with_u8(12) -}); -operand_view!(LocalUpdateCmp, operands128, Operand128, { - target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), right: u16 = u16 / with_u16(10) -}); - /// An operation packed inline with an indexed operand. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( feature = "archive", serde(bound(serialize = "Op: Copy + serde::Serialize", deserialize = "Op: Copy + serde::de::DeserializeOwned",)) )] #[repr(Rust, packed)] -pub struct PackedOp { +pub struct PackedOp { pub op: Op, - pub index: OperandIdx, + pub index: OperandIdx, } -impl PackedOp { - /// Creates a packed operation from an operator and operand index. - #[inline] - pub const fn new(op: Op, index: OperandIdx) -> Self { - Self { op, index } - } -} +/// An operation packed with an index into the 64-bit operand lane. +pub type PackedOp64 = PackedOp; -/// A SIMD value stored in the 128-bit operand lane. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct V128Operand { - pub value: [u8; 16], -} +/// An operation packed with an index into the 128-bit operand lane. +pub type PackedOp128 = PackedOp; -/// A local SIMD operation with an indexed constant. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct LocalV128 { - pub local: u16, - pub value: OperandIdx, -} +impl Copy for PackedOp {} -/// A global SIMD operation with an indexed constant. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct GlobalV128 { - pub global: u32, - pub value: OperandIdx, +impl Clone for PackedOp { + fn clone(&self) -> Self { + *self + } } -/// A local SIMD operation, indexed constant, and destination local. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct LocalConstSetV128 { - pub local: u16, - pub dst: u16, - pub value: OperandIdx, +impl PartialEq for PackedOp { + fn eq(&self, other: &Self) -> bool { + let (op, index) = (self.op, self.index); + let (other_op, other_index) = (other.op, other.index); + op == other_op && index == other_index + } } -macro_rules! operand_raw_view { - ($name:ident, $raw:ty, $decode:expr, $encode:expr) => { - impl sealed::Sealed for $name {} +impl Eq for PackedOp {} - impl OperandType for $name { - type Raw = $raw; - - #[inline(always)] - fn decode(raw: Self::Raw) -> Self { - $decode(raw) - } +#[cfg(feature = "debug")] +impl core::fmt::Debug for PackedOp { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let (op, index) = (self.op, self.index); + formatter.debug_struct("PackedOp").field("op", &op).field("index", &index).finish() + } +} - #[inline] - fn encode(self) -> Self::Raw { - $encode(self) - } - } - }; -} - -operand_raw_view!(V128Operand, Operand128, |raw: Operand128| Self { value: raw.to_le_bytes() }, |value: Self| { - Operand128::from_le_bytes(value.value) -}); -operand_raw_view!( - LocalV128, - Operand64, - |raw: Operand64| Self { local: raw.u16::<0>(), value: OperandIdx::new(raw.u32::<2>()) }, - |value: Self| { Operand64::default().with_u16::<0>(value.local).with_u32::<2>(value.value.index()) } -); -operand_raw_view!( - GlobalV128, - Operand64, - |raw: Operand64| Self { global: raw.u32::<0>(), value: OperandIdx::new(raw.u32::<4>()) }, - |value: Self| { Operand64::default().with_u32::<0>(value.global).with_u32::<4>(value.value.index()) } -); -operand_raw_view!( - LocalConstSetV128, - Operand64, - |raw: Operand64| Self { local: raw.u16::<0>(), dst: raw.u16::<2>(), value: OperandIdx::new(raw.u32::<4>()) }, - |value: Self| { - Operand64::default().with_u16::<0>(value.local).with_u16::<2>(value.dst).with_u32::<4>(value.value.index()) - } -); - -impl CastBranch { +impl PackedOp { + /// Creates a packed operation from an operator and operand index. #[inline] - pub const fn ref_type(self) -> RefType { - match RefType::from_bits(self.ref_type_bits) { - Some(value) => value, - None => unreachable!(), - } + pub const fn new(op: Op, index: OperandIdx) -> Self { + Self { op, index } } } @@ -325,36 +183,163 @@ pub struct ExceptionHandler { pub catches: Box<[ExceptionCatch]>, } -impl MemoryArg { +impl Operand128 { + /// Creates a full-width memory operand. #[inline] - pub const fn new(offset: u64, mem_addr: MemAddr) -> Self { - Self { offset, mem_addr } + pub fn new(offset: u64, memory: MemAddr) -> Self { + let mut operand = Self::default(); + operand.write_u64::<0>(offset); + operand.write_u32::<8>(memory); + operand + } + + /// Returns the static byte offset. + #[inline(always)] + pub fn offset(&self) -> u64 { + read_field!(self, u64, 0) + } + + /// Returns the module-local memory index. + #[inline(always)] + pub fn memory(&self) -> MemAddr { + read_field!(self, u32, 8) } +} +impl Operand64 { + /// Creates a compact memory operand. #[inline] - pub const fn offset(self) -> u64 { - self.offset + pub fn new(offset: u32, memory: u16) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(offset); + operand.write_u16::<4>(memory); + operand + } + + /// Returns the static byte offset. + #[inline(always)] + pub fn offset(&self) -> u32 { + read_field!(self, u32, 0) + } + + /// Returns the module-local memory index. + #[inline(always)] + pub fn memory(&self) -> u16 { + read_field!(self, u16, 4) } +} +impl Operand128 { #[inline] - pub const fn mem_addr(self) -> MemAddr { - self.mem_addr + pub fn new(target: u32, start: u32, len: u32) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(target); + operand.write_u32::<4>(start); + operand.write_u32::<8>(len); + operand + } + #[inline(always)] + pub fn start(&self) -> u32 { + read_field!(self, u32, 4) + } + #[inline(always)] + pub fn size(&self) -> u32 { + read_field!(self, u32, 8) } } -impl sealed::Sealed for MemoryArg {} +impl Operand128 { + #[inline] + pub fn new(memory: MemAddr, byte: u8, value: i32) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(memory); + operand.write_u8::<4>(byte); + operand.write_u32::<5>(value as u32); + operand + } + #[inline(always)] + pub fn memory(&self) -> MemAddr { + read_field!(self, u32, 0) + } + #[inline(always)] + pub fn byte(&self) -> u8 { + read_field!(self, u8, 4) + } + #[inline(always)] + pub fn value(&self) -> i32 { + read_field!(self, i32, 5) + } +} -impl OperandType for MemoryArg { - type Raw = Operand128; +impl Operand128 { + #[inline] + pub fn new(target: u32, value: i32, local: LocalAddr, on_zero: bool) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(target); + operand.write_u32::<4>(value as u32); + operand.write_u16::<8>(local); + operand.write_u8::<10>(u8::from(on_zero)); + operand + } + #[inline(always)] + pub fn value(&self) -> i32 { + read_field!(self, i32, 4) + } + #[inline(always)] + pub fn local(&self) -> LocalAddr { + read_field!(self, u16, 8) + } + #[inline(always)] + pub fn on_zero(&self) -> bool { + read_field!(self, u8, 10) != 0 + } +} +impl Operand128 { + #[inline] + pub fn new(target: u32, value: i32, global: GlobalAddr, on_zero: bool) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(target); + operand.write_u32::<4>(value as u32); + operand.write_u32::<8>(global); + operand.write_u8::<12>(u8::from(on_zero)); + operand + } + #[inline(always)] + pub fn value(&self) -> i32 { + read_field!(self, i32, 4) + } + #[inline(always)] + pub fn global(&self) -> GlobalAddr { + read_field!(self, u32, 8) + } #[inline(always)] - fn decode(raw: Self::Raw) -> Self { - Self::new(raw.u64::<0>(), raw.u32::<8>()) + pub fn on_zero(&self) -> bool { + read_field!(self, u8, 12) != 0 } +} +impl Operand128 { #[inline] - fn encode(self) -> Self::Raw { - Operand128::default().with_u64::<0>(self.offset).with_u32::<8>(self.mem_addr) + pub fn new(target: u32, value: i32, local: LocalAddr, right: LocalAddr) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(target); + operand.write_u32::<4>(value as u32); + operand.write_u16::<8>(local); + operand.write_u16::<10>(right); + operand + } + #[inline(always)] + pub fn value(&self) -> i32 { + read_field!(self, i32, 4) + } + #[inline(always)] + pub fn local(&self) -> LocalAddr { + read_field!(self, u16, 8) + } + #[inline(always)] + pub fn right(&self) -> LocalAddr { + read_field!(self, u16, 10) } } @@ -372,43 +357,27 @@ impl CompactMemoryArg { } } -impl sealed::Sealed for CompactMemoryArg {} - -impl OperandType for CompactMemoryArg { - type Raw = Operand64; - - #[inline(always)] - fn decode(raw: Self::Raw) -> Self { - Self { offset: raw.u32::<0>(), mem_addr: raw.u16::<4>() } - } - - #[inline] - fn encode(self) -> Self::Raw { - Operand64::default().with_u32::<0>(self.offset).with_u16::<4>(self.mem_addr) - } -} - -impl TryFrom for CompactMemoryArg { +impl TryFrom> for CompactMemoryArg { type Error = (); #[inline] - fn try_from(arg: MemoryArg) -> Result { + fn try_from(arg: Operand128) -> Result { Ok(Self { offset: u32::try_from(arg.offset()).map_err(|_| ())?, - mem_addr: u16::try_from(arg.mem_addr()).map_err(|_| ())?, + mem_addr: u16::try_from(arg.memory()).map_err(|_| ())?, }) } } -impl From for MemoryArg { +impl From for Operand64 { #[inline] fn from(arg: CompactMemoryArg) -> Self { - Self::new(arg.offset(), arg.mem_addr()) + Self::new(arg.offset, arg.mem_addr) } } const _: () = { - assert!(core::mem::size_of::>() == 4); + assert!(core::mem::size_of::>() == 4); assert!(core::mem::size_of::() == 8); assert!(core::mem::size_of::() == 16); assert!(core::mem::size_of::() == 6); @@ -542,28 +511,28 @@ pub enum BinOp128 { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub enum Instruction { LocalCopy32(LocalAddr, LocalAddr), LocalCopy64(LocalAddr, LocalAddr), LocalCopy128(LocalAddr, LocalAddr), - AddConst32(i32), AddConst64(OperandIdx), - IncLocal32(I32LocalArg), IncLocal64(PackedOp), + AddConst32(i32), AddConst64(Operand64Idx), + IncLocal32(I32LocalArg), IncLocal64(PackedOp64), // The 32/64 suffix describes the operand width. Future compare-style ops may still yield i32 results. BinOpLocalLocal32(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal64(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal128(BinOp128, LocalAddr, LocalAddr), CmpLocalLocal32(CmpOp, LocalAddr, LocalAddr), CmpLocalLocal64(CmpOp, LocalAddr, LocalAddr), AddLocalLocalSet32(LocalTripleArg), AddLocalLocalTee32(LocalTripleArg), - BinOpLocalLocalSet32(PackedOp), BinOpLocalLocalSet64(PackedOp), BinOpLocalLocalSet128(PackedOp), - BinOpLocalLocalTee32(PackedOp), BinOpLocalLocalTee64(PackedOp), BinOpLocalLocalTee128(PackedOp), + BinOpLocalLocalSet32(PackedOp64), BinOpLocalLocalSet64(PackedOp64), BinOpLocalLocalSet128(PackedOp64), + BinOpLocalLocalTee32(PackedOp64), BinOpLocalLocalTee64(PackedOp64), BinOpLocalLocalTee128(PackedOp64), AddLocalConst32(I32LocalArg), SubLocalConst32(I32LocalArg), MulLocalConst32(I32LocalArg), - BinOpLocalConst32(PackedOp), BinOpLocalConst64(PackedOp), - BinOpGlobalConst32(PackedOp), BinOpGlobalConst64(PackedOp), - BinOpGlobalConst128(PackedOp), BinOpLocalConst128(PackedOp), - BinOpLocalConstSet32(PackedOp), BinOpLocalConstSet64(PackedOp), BinOpLocalConstSet128(PackedOp), - BinOpLocalConstTee32(PackedOp), BinOpLocalConstTee64(PackedOp), BinOpLocalConstTee128(PackedOp), + BinOpLocalConst32(PackedOp64), BinOpLocalConst64(PackedOp128), + BinOpGlobalConst32(PackedOp64), BinOpGlobalConst64(PackedOp128), + BinOpGlobalConst128(PackedOp64)>), BinOpLocalConst128(PackedOp64)>), + BinOpLocalConstSet32(PackedOp64), BinOpLocalConstSet64(PackedOp128), BinOpLocalConstSet128(PackedOp64)>), + BinOpLocalConstTee32(PackedOp64), BinOpLocalConstTee64(PackedOp128), BinOpLocalConstTee128(PackedOp64)>), BinOpStackLocal32(BinOp, LocalAddr), BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr), BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr), BinOpStackLocal128(BinOp128, LocalAddr), BinOpStackGlobal32(BinOp, u32), BinOpStackGlobal64(BinOp, u32), - SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp), SetLocalConst128(PackedOp), + SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp64), SetLocalConst128(PackedOp128), IncMemoryLocal32(MemoryLocalArg), IncMemoryLocal64(MemoryLocalArg), StoreLocalLocal32(MemoryLocalArg), StoreLocalLocal64(MemoryLocalArg), StoreLocalLocal128(MemoryLocalArg), LoadLocal32(MemoryLocalArg), LoadLocal64(MemoryLocalArg), @@ -576,7 +545,7 @@ pub enum Instruction { LoadLocalSet16S32(MemoryLocalArg), LoadLocalSet16U32(MemoryLocalArg), LoadLocalTee128(MemoryLocalArg), LoadLocalSet128(MemoryLocalArg), AndConstTee32(I32LocalArg), SubConstTee32(I32LocalArg), - AndConstTee64(PackedOp), SubConstTee64(PackedOp), + AndConstTee64(PackedOp64), SubConstTee64(PackedOp64), MulAccLocal32(LocalAddr), MulAccLocal64(LocalAddr), FMulAccLocal32(LocalAddr), FMulAccLocal64(LocalAddr), I32Add3, @@ -596,14 +565,14 @@ pub enum Instruction { JumpIfRefNonNull(u32), JumpIfLocalZero32(TargetLocalArg), JumpIfLocalNonZero32(TargetLocalArg), JumpIfLocalZero64(TargetLocalArg), JumpIfLocalNonZero64(TargetLocalArg), - JumpCmpStackConst32(PackedOp), JumpCmpStackConst64(PackedOp), - JumpCmpStackLocal32(PackedOp), JumpCmpStackLocal64(PackedOp), - BinOpLocalConstJump32(PackedOp), BinOpLocalConstJumpCmpLocal32(PackedOp<(BinOp, CmpOp), LocalUpdateCmp>), - BinOpStackConstTeeLocalJump32(PackedOp), BinOpGlobalConstJump32(PackedOp), - IncLocalJump32(OperandIdx), IncStackTeeLocalJump32(OperandIdx), IncGlobalJump32(OperandIdx), - IncLocalJumpCmpLocal32(PackedOp), JumpCmpLocalConst32(PackedOp), JumpCmpLocalConst64(PackedOp), - JumpCmpLocalLocal32(PackedOp), JumpCmpLocalLocal64(PackedOp), - DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(OperandIdx), + JumpCmpStackConst32(PackedOp64), JumpCmpStackConst64(PackedOp128), + JumpCmpStackLocal32(PackedOp64), JumpCmpStackLocal64(PackedOp64), + BinOpLocalConstJump32(PackedOp128), BinOpLocalConstJumpCmpLocal32(PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>), + BinOpStackConstTeeLocalJump32(PackedOp128), BinOpGlobalConstJump32(PackedOp128), + IncLocalJump32(Operand128Idx), IncStackTeeLocalJump32(Operand128Idx), IncGlobalJump32(Operand128Idx), + IncLocalJumpCmpLocal32(PackedOp128), JumpCmpLocalConst32(PackedOp128), JumpCmpLocalConst64(PackedOp128), + JumpCmpLocalLocal32(PackedOp64), JumpCmpLocalLocal64(PackedOp64), + DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(Operand128Idx), Return, ReturnVoid, Return32, @@ -611,11 +580,11 @@ pub enum Instruction { Return128, Call(FuncAddr), CallSelf, - CallIndirect(OperandIdx), + CallIndirect(Operand64Idx<(u32, u32)>), CallRef(TypeAddr), ReturnCall(FuncAddr), ReturnCallSelf, - ReturnCallIndirect(OperandIdx), + ReturnCallIndirect(Operand64Idx<(u32, u32)>), ReturnCallRef(TypeAddr), Throw(TagAddr), ThrowRef, @@ -634,18 +603,18 @@ pub enum Instruction { GlobalGet128(GlobalAddr), GlobalSet128(GlobalAddr), GlobalTee128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), // > Memory Instructions - I32Load(OperandIdx), I64Load(OperandIdx), F32Load(OperandIdx), F64Load(OperandIdx), - I32Load8S(OperandIdx), I32Load8U(OperandIdx), I32Load16S(OperandIdx), I32Load16U(OperandIdx), - I64Load8S(OperandIdx), I64Load8U(OperandIdx), I64Load16S(OperandIdx), I64Load16U(OperandIdx), I64Load32S(OperandIdx), I64Load32U(OperandIdx), - I32Store(OperandIdx), I64Store(OperandIdx), F32Store(OperandIdx), F64Store(OperandIdx), - I32Store8(OperandIdx), I32Store16(OperandIdx), I64Store8(OperandIdx), I64Store16(OperandIdx), I64Store32(OperandIdx), + I32Load(Operand128Idx), I64Load(Operand128Idx), F32Load(Operand128Idx), F64Load(Operand128Idx), + I32Load8S(Operand128Idx), I32Load8U(Operand128Idx), I32Load16S(Operand128Idx), I32Load16U(Operand128Idx), + I64Load8S(Operand128Idx), I64Load8U(Operand128Idx), I64Load16S(Operand128Idx), I64Load16U(Operand128Idx), I64Load32S(Operand128Idx), I64Load32U(Operand128Idx), + I32Store(Operand128Idx), I64Store(Operand128Idx), F32Store(Operand128Idx), F64Store(Operand128Idx), + I32Store8(Operand128Idx), I32Store16(Operand128Idx), I64Store8(Operand128Idx), I64Store16(Operand128Idx), I64Store32(Operand128Idx), MemorySize(MemAddr), MemoryGrow(MemAddr), // > Constants Const32(i32), Const64Imm(i32), - Const64(OperandIdx), + Const64(Operand64Idx), // > Reference Types RefNull(RefType), @@ -658,24 +627,24 @@ pub enum Instruction { RefEq, RefTest(RefType), RefCast(RefType), - BrOnCast(OperandIdx), - BrOnCastFail(OperandIdx), + BrOnCast(Operand64Idx<(u32, u32)>), + BrOnCastFail(Operand64Idx<(u32, u32)>), // > GC Objects StructNew(TypeAddr), StructNewDefault(TypeAddr), - StructGet(OperandIdx), StructGetS(OperandIdx), StructGetU(OperandIdx), StructSet(OperandIdx), + StructGet(Operand64Idx<(u32, u32)>), StructGetS(Operand64Idx<(u32, u32)>), StructGetU(Operand64Idx<(u32, u32)>), StructSet(Operand64Idx<(u32, u32)>), ArrayNew(TypeAddr), ArrayNewDefault(TypeAddr), - ArrayNewFixed(OperandIdx), - ArrayNewData(OperandIdx), ArrayNewElem(OperandIdx), + ArrayNewFixed(Operand64Idx<(u32, u32)>), + ArrayNewData(Operand64Idx<(u32, u32)>), ArrayNewElem(Operand64Idx<(u32, u32)>), ArrayGet(TypeAddr), ArrayGetS(TypeAddr), ArrayGetU(TypeAddr), ArraySet(TypeAddr), ArrayLen, ArrayFill(TypeAddr), - ArrayCopy(OperandIdx), ArrayInitData(OperandIdx), ArrayInitElem(OperandIdx), + ArrayCopy(Operand64Idx<(u32, u32)>), ArrayInitData(Operand64Idx<(u32, u32)>), ArrayInitElem(Operand64Idx<(u32, u32)>), // > Numeric Instructions // See @@ -705,18 +674,18 @@ pub enum Instruction { I64TruncSatF32S, I64TruncSatF32U, I64TruncSatF64S, I64TruncSatF64U, // > Table Instructions - TableInit(OperandIdx), + TableInit(Operand64Idx<(u32, u32)>), TableGet(TableAddr), TableSet(TableAddr), - TableCopy(OperandIdx), + TableCopy(Operand64Idx<(u32, u32)>), TableGrow(TableAddr), TableSize(TableAddr), TableFill(TableAddr), // > Bulk Memory Instructions - MemoryInit(OperandIdx), MemoryCopy(OperandIdx), + MemoryInit(Operand64Idx<(u32, u32)>), MemoryCopy(Operand64Idx<(u32, u32)>), MemoryFill(MemAddr), - MemoryFillConst(OperandIdx), + MemoryFillConst(Operand128Idx), DataDrop(DataAddr), ElemDrop(ElemAddr), @@ -724,18 +693,18 @@ pub enum Instruction { I64Add128, I64Sub128, I64MulWideS, I64MulWideU, // > SIMD - V128Load(OperandIdx), V128Load8x8S(OperandIdx), V128Load8x8U(OperandIdx), - V128Load16x4S(OperandIdx), V128Load16x4U(OperandIdx), V128Load32x2S(OperandIdx), V128Load32x2U(OperandIdx), + V128Load(Operand128Idx), V128Load8x8S(Operand128Idx), V128Load8x8U(Operand128Idx), + V128Load16x4S(Operand128Idx), V128Load16x4U(Operand128Idx), V128Load32x2S(Operand128Idx), V128Load32x2U(Operand128Idx), - V128Load8Splat(OperandIdx), V128Load16Splat(OperandIdx), V128Load32Splat(OperandIdx), V128Load64Splat(OperandIdx), + V128Load8Splat(Operand128Idx), V128Load16Splat(Operand128Idx), V128Load32Splat(Operand128Idx), V128Load64Splat(Operand128Idx), V128Load8Lane(MemoryLaneArg), V128Load16Lane(MemoryLaneArg), V128Load32Lane(MemoryLaneArg), V128Load64Lane(MemoryLaneArg), - V128Load32Zero(OperandIdx), V128Load64Zero(OperandIdx), + V128Load32Zero(Operand128Idx), V128Load64Zero(Operand128Idx), - V128Store(OperandIdx), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg), + V128Store(Operand128Idx), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg), - I8x16Shuffle(OperandIdx), - Const128Imm(u32), Const128(OperandIdx), + I8x16Shuffle(Operand128Idx<[u8; 16]>), + Const128Imm(u32), Const128(Operand128Idx<[u8; 16]>), I8x16ExtractLaneS(u8), I8x16ExtractLaneU(u8), I8x16ReplaceLane(u8), I16x8ExtractLaneS(u8), I16x8ExtractLaneU(u8), I16x8ReplaceLane(u8), @@ -794,6 +763,8 @@ pub enum Instruction { I16x8RelaxedQ15mulrS, I16x8RelaxedDotI8x16I7x16S, I32x4RelaxedDotI8x16I7x16AddS, + + SelectStore32(Operand128Idx), SelectStore64(Operand128Idx), } const _: () = assert!(core::mem::size_of::() == 8); @@ -814,43 +785,40 @@ mod tests { #[test] fn operand_lanes_round_trip_max_values() { - let memory = MemoryArg::new(u64::MAX, u32::MAX); - assert_eq!(MemoryArg::decode(memory.encode()), memory); - - let value = Operand128::default() - .with_u8::<0>(u8::MAX) - .with_u16::<1>(u16::MAX) - .with_u32::<3>(u32::MAX) - .with_u64::<7>(u64::MAX); - assert_eq!( - (value.u8::<0>(), value.u16::<1>(), value.u32::<3>(), value.u64::<7>()), - (u8::MAX, u16::MAX, u32::MAX, u64::MAX) - ); - - let bytes = [u8::MAX; 16]; - assert_eq!(Operand128::from_le_bytes(bytes).to_le_bytes(), bytes); + let memory = Operand128::::new(u64::MAX, u32::MAX); + assert_eq!(memory.offset(), u64::MAX); + assert_eq!(memory.memory(), u32::MAX); + + let value = Operand128::::new(u32::MAX, i32::MIN, u16::MAX, true); + assert_eq!(value.target(), u32::MAX); + assert_eq!(value.value(), i32::MIN); + assert_eq!(value.local(), u16::MAX); + assert!(value.on_zero()); } #[test] fn v128_operand_views_round_trip_max_bytes() { - let value = OperandIdx::::new(0); - let local = OperandIdx::::new(0); - let global = OperandIdx::::new(1); - let set = OperandIdx::::new(2); + let value = Operand128Idx::<[u8; 16]>::new(0); + let local = Operand64Idx::<(u16, Operand128Idx<[u8; 16]>)>::new(0); + let global = Operand64Idx::<(u32, Operand128Idx<[u8; 16]>)>::new(1); + let set = Operand64Idx::<(u16, u16, Operand128Idx<[u8; 16]>)>::new(2); let data = super::super::WasmFunctionData { - operands128: vec![V128Operand { value: [u8::MAX; 16] }.encode()].into_boxed_slice(), + operands128: vec![Operand128::<[u8; 16]>::new([u8::MAX; 16]).cast()].into_boxed_slice(), operands64: vec![ - LocalV128 { local: u16::MAX, value }.encode(), - GlobalV128 { global: u32::MAX, value }.encode(), - LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }.encode(), + Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(u16::MAX, value).cast(), + Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(u32::MAX, value).cast(), + Operand64::<(u16, u16, Operand128Idx<[u8; 16]>)>::new(u16::MAX, u16::MAX, value).cast(), ] .into_boxed_slice(), ..Default::default() }; - assert_eq!(value.get(&data).value, [u8::MAX; 16]); - assert_eq!(local.get(&data), LocalV128 { local: u16::MAX, value }); - assert_eq!(global.get(&data), GlobalV128 { global: u32::MAX, value }); - assert_eq!(set.get(&data), LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }); + assert_eq!(value.resolve(&data).value(), [u8::MAX; 16]); + assert_eq!((local.resolve(&data).a(), local.resolve(&data).b()), (u16::MAX, value)); + assert_eq!((global.resolve(&data).a(), global.resolve(&data).b()), (u32::MAX, value)); + assert_eq!( + (set.resolve(&data).a(), set.resolve(&data).b(), set.resolve(&data).c()), + (u16::MAX, u16::MAX, value) + ); } } diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index f9f85fa..a3f26f2 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -133,6 +133,9 @@ pub struct ModuleInner { /// Corresponds to the `memory` section of the original WebAssembly module. pub memory_types: Box<[MemoryType]>, + /// Whether instantiation should omit unexported local memories that guest code cannot access. + pub skip_local_memory_allocation: bool, + /// Tag components of the WebAssembly module. /// /// Corresponds to the `tag` section of the original WebAssembly module. diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs index 3cc311c..1bc4a28 100644 --- a/crates/types/src/operands.rs +++ b/crates/types/src/operands.rs @@ -1,18 +1,22 @@ use core::marker::PhantomData; -use crate::WasmFunctionData; - /// An index into the operand lane used by `T`. #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "archive", serde(transparent))] #[repr(transparent)] -pub struct OperandIdx { +pub struct OperandIdx { index: u32, #[cfg_attr(feature = "archive", serde(skip))] marker: PhantomData, } -impl OperandIdx { +/// An index into the 64-bit operand lane. +pub type Operand64Idx = OperandIdx; + +/// An index into the 128-bit operand lane. +pub type Operand128Idx = OperandIdx; + +impl OperandIdx { #[inline] #[doc(hidden)] pub const fn new(index: u32) -> Self { @@ -21,157 +25,329 @@ impl OperandIdx { /// Returns the underlying lane index. #[inline] - pub const fn index(self) -> u32 { - self.index - } -} - -impl OperandIdx { - /// Returns the typed operand at this index. - /// - /// Panics if the index is outside its statically selected operand lane. - #[inline(always)] - pub fn get(self, data: &WasmFunctionData) -> T { - T::decode(T::Raw::get(data, self.index)) + pub const fn index(self) -> usize { + self.index as usize } } -impl Copy for OperandIdx {} - -impl Clone for OperandIdx { +impl Copy for OperandIdx {} +impl Clone for OperandIdx { fn clone(&self) -> Self { *self } } - -impl PartialEq for OperandIdx { +impl PartialEq for OperandIdx { fn eq(&self, other: &Self) -> bool { self.index == other.index } } - -impl Eq for OperandIdx {} +impl Eq for OperandIdx {} #[cfg(feature = "debug")] -impl core::fmt::Debug for OperandIdx { +impl core::fmt::Debug for OperandIdx { fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.index.fmt(formatter) } } -pub(crate) mod sealed { - pub trait Sealed {} -} - -/// A typed view stored in one of the per-function operand lanes. -pub trait OperandType: sealed::Sealed + Copy { - #[doc(hidden)] - type Raw: RawOperand; - - #[doc(hidden)] - fn decode(raw: Self::Raw) -> Self; - #[doc(hidden)] - fn encode(self) -> Self::Raw; -} - -#[doc(hidden)] -pub trait RawOperand: sealed::Sealed + Copy { - fn get(data: &WasmFunctionData, index: u32) -> Self; -} - macro_rules! define_operand { - ($name:ident, $len:literal, $lane:ident) => { - #[doc = concat!("Raw fields stored in a per-function ", $len, "-byte operand lane.")] - #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)] - #[cfg_attr(feature = "debug", derive(Debug))] - #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] - #[repr(transparent)] - pub struct $name([u8; $len]); - - impl sealed::Sealed for $name {} - - impl RawOperand for $name { - #[inline(always)] - fn get(data: &WasmFunctionData, index: u32) -> Self { - *data.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) - } + ($name:ident, $len:literal) => { + #[doc = concat!("A typed packed ", $len, "-byte operand value.")] + #[repr(C)] + pub struct $name { + pub(crate) bytes: [u8; $len], + marker: PhantomData, } - impl $name { - /// Returns the byte at `OFFSET`. + #[allow(dead_code)] + impl $name { #[inline] - pub fn u8(self) -> u8 { + pub(crate) fn write_u8(&mut self, value: u8) { const { assert!(OFFSET < $len) }; - self.0[OFFSET] + self.bytes[OFFSET] = value; } - /// Returns the little-endian `u16` at `OFFSET`. #[inline] - pub fn u16(self) -> u16 { + pub(crate) fn write_u16(&mut self, value: u16) { const { assert!(OFFSET + 2 <= $len) }; - u16::from_le_bytes(self.0[OFFSET..OFFSET + 2].try_into().unwrap_or_else(|_| unreachable!())) + self.bytes[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes()); } - /// Returns the little-endian `u32` at `OFFSET`. #[inline] - pub fn u32(self) -> u32 { + pub(crate) fn write_u32(&mut self, value: u32) { const { assert!(OFFSET + 4 <= $len) }; - u32::from_le_bytes(self.0[OFFSET..OFFSET + 4].try_into().unwrap_or_else(|_| unreachable!())) + self.bytes[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes()); } - /// Returns the little-endian `u64` at `OFFSET`. #[inline] - pub fn u64(self) -> u64 { + pub(crate) fn write_u64(&mut self, value: u64) { const { assert!(OFFSET + 8 <= $len) }; - u64::from_le_bytes(self.0[OFFSET..OFFSET + 8].try_into().unwrap_or_else(|_| unreachable!())) + self.bytes[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes()); } - /// Builds an operand from its raw little-endian bytes. - #[inline] - pub fn from_le_bytes(value: [u8; $len]) -> Self { - Self(value) + #[inline(always)] + #[doc(hidden)] + pub fn cast(self) -> $name { + $name { bytes: self.bytes, marker: PhantomData } } + } - /// Returns the raw little-endian bytes. - #[inline] - pub fn to_le_bytes(self) -> [u8; $len] { - self.0 + impl Copy for $name {} + impl Clone for $name { + fn clone(&self) -> Self { + *self } + } + impl PartialEq for $name { + fn eq(&self, other: &Self) -> bool { + self.bytes == other.bytes + } + } + impl Eq for $name {} + impl PartialOrd for $name { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + impl Ord for $name { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { + self.bytes.cmp(&other.bytes) + } + } + impl Default for $name { + fn default() -> Self { + Self { bytes: [0; $len], marker: PhantomData } + } + } - /// Writes `value` at `OFFSET` and returns the updated operand. - #[inline] - pub fn with_u8(mut self, value: u8) -> Self { - const { assert!(OFFSET < $len) }; - self.0[OFFSET] = value; - self + #[cfg(feature = "debug")] + impl core::fmt::Debug for $name { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.bytes.fmt(formatter) } + } - /// Writes `value` at `OFFSET` and returns the updated operand. - #[inline] - pub fn with_u16(mut self, value: u16) -> Self { - const { assert!(OFFSET + 2 <= $len) }; - self.0[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes()); - self + #[cfg(feature = "archive")] + impl serde::Serialize for $name { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + self.bytes.serialize(serializer) } + } - /// Writes `value` at `OFFSET` and returns the updated operand. - #[inline] - pub fn with_u32(mut self, value: u32) -> Self { - const { assert!(OFFSET + 4 <= $len) }; - self.0[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes()); - self + #[cfg(feature = "archive")] + impl<'de, T> serde::Deserialize<'de> for $name { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + Ok(Self { bytes: <[u8; $len]>::deserialize(deserializer)?, marker: PhantomData }) } + } + }; +} + +define_operand!(Operand64, 8); +define_operand!(Operand128, 16); + +macro_rules! unwrap_or_unreachable { + ($value:expr) => {{ unwrap_or_unreachable!($value, "entered unreachable code") }}; + ($value:expr, $message:literal) => {{ + match $value { + Some(value) => value, + None => operand_unreachable($message), + } + }}; +} + +#[cold] +#[inline(never)] +pub(crate) fn operand_unreachable(message: &'static str) -> ! { + unreachable!("{message}") +} - /// Writes `value` at `OFFSET` and returns the updated operand. +impl Operand64Idx { + /// Resolves this index to a copied 64-bit packed operand. + #[inline(always)] + pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand64 { + (*unwrap_or_unreachable!(data.operands64.get(self.index()), "invalid 64-bit operand index")).cast() + } +} + +impl Operand128Idx { + /// Resolves this index to a copied 128-bit packed operand. + #[inline(always)] + pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand128 { + (*unwrap_or_unreachable!(data.operands128.get(self.index()), "invalid 128-bit operand index")).cast() + } +} + +macro_rules! field_ty { + (u8) => { u8 }; (u16) => { u16 }; (u32) => { u32 }; (u64) => { u64 }; + (i32) => { i32 }; (i64) => { i64 }; (idx128) => { Operand128Idx<[u8; 16]> }; +} +macro_rules! field_size { + (u8) => {{ 1 }}; + (u16) => {{ 2 }}; + (u32) => {{ 4 }}; + (u64) => {{ 8 }}; + (i32) => {{ 4 }}; + (i64) => {{ 8 }}; + (idx128) => {{ 4 }}; +} + +macro_rules! read_field { + ($self:ident, u8, $offset:expr) => {{ $self.bytes[$offset] }}; + ($self:ident, u16, $offset:expr) => {{ u16::from_le_bytes($crate::operands::read_bytes!($self, $offset, 2)) }}; + ($self:ident, u32, $offset:expr) => {{ u32::from_le_bytes($crate::operands::read_bytes!($self, $offset, 4)) }}; + ($self:ident, u64, $offset:expr) => {{ u64::from_le_bytes($crate::operands::read_bytes!($self, $offset, 8)) }}; + ($self:ident, i32, $offset:expr) => {{ read_field!($self, u32, $offset) as i32 }}; + ($self:ident, i64, $offset:expr) => {{ read_field!($self, u64, $offset) as i64 }}; + ($self:ident, idx128, $offset:expr) => {{ Operand128Idx::new(read_field!($self, u32, $offset)) }}; +} +pub(crate) use read_field; + +macro_rules! read_bytes { + ($self:ident, $offset:expr, $len:literal) => {{ + match <[u8; $len]>::try_from(&$self.bytes[$offset..$offset + $len]) { + Ok(bytes) => bytes, + Err(_) => $crate::operands::operand_unreachable("invalid operand field"), + } + }}; +} +pub(crate) use read_bytes; +macro_rules! write_field { + ($self:ident, u8, $offset:expr, $value:expr) => {{ $self.write_u8::<{ $offset }>($value) }}; + ($self:ident, u16, $offset:expr, $value:expr) => {{ $self.write_u16::<{ $offset }>($value) }}; + ($self:ident, u32, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value) }}; + ($self:ident, u64, $offset:expr, $value:expr) => {{ $self.write_u64::<{ $offset }>($value) }}; + ($self:ident, i32, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value as u32) }}; + ($self:ident, i64, $offset:expr, $value:expr) => {{ $self.write_u64::<{ $offset }>($value as u64) }}; + ($self:ident, idx128, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value.index) }}; +} + +impl Operand64 { + /// Returns the jump target stored at the start of a retargetable operand. + #[inline(always)] + pub fn target(&self) -> u32 { + read_field!(self, u32, 0) + } + + /// Replaces the jump target stored at the start of a retargetable operand. + #[inline] + pub fn with_target(mut self, target: u32) -> Self { + self.write_u32::<0>(target); + self + } +} + +impl Operand128 { + /// Returns the jump target stored at the start of a retargetable operand. + #[inline(always)] + pub fn target(&self) -> u32 { + read_field!(self, u32, 0) + } + + /// Replaces the jump target stored at the start of a retargetable operand. + #[inline] + pub fn with_target(mut self, target: u32) -> Self { + self.write_u32::<0>(target); + self + } +} + +macro_rules! packed_layout { + ($operand:ident, $lane:ident, $field:tt) => { + impl $operand { #[inline] - pub fn with_u64(mut self, value: u64) -> Self { - const { assert!(OFFSET + 8 <= $len) }; - self.0[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes()); - self + pub fn new(value: field_ty!($field)) -> Self { + let mut operand = Self::default(); + write_field!(operand, $field, 0, value); + operand + } + #[inline(always)] + pub fn value(&self) -> field_ty!($field) { + read_field!(self, $field, 0) + } + } + }; + ($operand:ident, $lane:ident, $a:tt, $b:tt) => { + impl $operand<(field_ty!($a), field_ty!($b))> { + #[inline] + pub fn new(a: field_ty!($a), b: field_ty!($b)) -> Self { + let mut operand = Self::default(); + write_field!(operand, $a, 0, a); + write_field!(operand, $b, field_size!($a), b); + operand + } + #[inline(always)] + pub fn a(&self) -> field_ty!($a) { + read_field!(self, $a, 0) + } + #[inline(always)] + pub fn b(&self) -> field_ty!($b) { + read_field!(self, $b, field_size!($a)) + } + } + }; + ($operand:ident, $lane:ident, $a:tt, $b:tt, $c:tt) => { + impl $operand<(field_ty!($a), field_ty!($b), field_ty!($c))> { + #[inline] + pub fn new(a: field_ty!($a), b: field_ty!($b), c: field_ty!($c)) -> Self { + let mut operand = Self::default(); + write_field!(operand, $a, 0, a); + write_field!(operand, $b, field_size!($a), b); + write_field!(operand, $c, field_size!($a) + field_size!($b), c); + operand + } + #[inline(always)] + pub fn a(&self) -> field_ty!($a) { + read_field!(self, $a, 0) + } + #[inline(always)] + pub fn b(&self) -> field_ty!($b) { + read_field!(self, $b, field_size!($a)) + } + #[inline(always)] + pub fn c(&self) -> field_ty!($c) { + read_field!(self, $c, field_size!($a) + field_size!($b)) } } }; } -define_operand!(Operand64, 8, operands64); -define_operand!(Operand128, 16, operands128); +packed_layout!(Operand64, operands64, i64); +packed_layout!(Operand64, operands64, u32, u32); +packed_layout!(Operand64, operands64, u16, u32); +packed_layout!(Operand64, operands64, u32, u16); +packed_layout!(Operand64, operands64, u16, u16, u16); +packed_layout!(Operand64, operands64, u16, u16, u32); +packed_layout!(Operand64, operands64, u32, i32); +packed_layout!(Operand64, operands64, u32, u16, u16); +packed_layout!(Operand64, operands64, u16, idx128); +packed_layout!(Operand64, operands64, u32, idx128); +packed_layout!(Operand64, operands64, u16, u16, idx128); + +packed_layout!(Operand128, operands128, u16, u64); +packed_layout!(Operand128, operands128, u32, u64); +packed_layout!(Operand128, operands128, u16, u16, u64); +packed_layout!(Operand128, operands128, u32, i64); +packed_layout!(Operand128, operands128, u32, i32, u16); + +impl Operand128<[u8; 16]> { + #[inline] + pub fn new(value: [u8; 16]) -> Self { + Self { bytes: value, marker: PhantomData } + } + #[inline(always)] + pub fn value(&self) -> [u8; 16] { + self.bytes + } +} +const _: () = { + assert!(core::mem::size_of::>() == 4); + assert!(core::mem::size_of::() == 8); + assert!(core::mem::size_of::() == 16); +}; diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index 2d725ca..d195a81 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -69,7 +69,8 @@ impl RefType { } #[inline] - pub(crate) const fn from_bits(bits: u32) -> Option { + #[doc(hidden)] + pub const fn from_bits(bits: u32) -> Option { let ty = Self(bits); if ty.is_concrete() || ty.abstract_heap_type().is_some() { Some(ty) } else { None } } diff --git a/examples/rust/build.sh b/examples/rust/build.sh index cbd3b27..873028f 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -12,6 +12,10 @@ wasmopt_features="--enable-simd --enable-relaxed-simd --enable-tail-call --enabl # ensure out dir exists mkdir -p "$dest_dir" +# Keep the embedded archive synchronized with the current archive version and instruction layout. +cargo run --quiet --manifest-path "../../Cargo.toml" --package tinywasm-cli -- \ + compile "src/print.wasm" --output "src/print.twasm" --force || exit + # build no_std RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features cp "$out_dir/tinywasm_no_std.wasm" "$dest_dir/" diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm index 7841329..0fb3f39 100644 Binary files a/examples/rust/src/print.twasm and b/examples/rust/src/print.twasm differ -- cgit v1.3.1 From c67ce64bfc88eada4d2b611e30b2dd307a7f7526 Mon Sep 17 00:00:00 2001 From: Henry Date: Sat, 29 Aug 2026 22:20:03 +0200 Subject: feat: add nightly tail-call interpreter dispatch Signed-off-by: Henry --- .github/workflows/test.yaml | 8 + CHANGELOG.md | 1 + README.md | 8 +- crates/cli/src/wast_runner.rs | 22 +- crates/parser/Cargo.toml | 3 + crates/tinywasm/Cargo.toml | 3 + crates/tinywasm/src/interpreter/executor.rs | 2289 -------------------- .../tinywasm/src/interpreter/executor/dispatch.rs | 90 + .../src/interpreter/executor/dispatch_become.rs | 189 ++ .../src/interpreter/executor/instructions.rs | 690 ++++++ crates/tinywasm/src/interpreter/executor/mod.rs | 1561 +++++++++++++ crates/tinywasm/src/interpreter/mod.rs | 6 +- .../tinywasm/src/interpreter/stack/value_stack.rs | 12 +- crates/tinywasm/src/lib.rs | 9 +- crates/tinywasm/tests/resume_execution.rs | 4 +- examples/rust/src/print.twasm | Bin 155 -> 155 bytes 16 files changed, 2577 insertions(+), 2318 deletions(-) delete mode 100644 crates/tinywasm/src/interpreter/executor.rs create mode 100644 crates/tinywasm/src/interpreter/executor/dispatch.rs create mode 100644 crates/tinywasm/src/interpreter/executor/dispatch_become.rs create mode 100644 crates/tinywasm/src/interpreter/executor/instructions.rs create mode 100644 crates/tinywasm/src/interpreter/executor/mod.rs (limited to 'examples/rust/src') diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index e950c47..e623fef 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -54,6 +54,10 @@ jobs: - os: ubuntu-latest rust: nightly name: "Linux x86 (nightly)" + - os: ubuntu-latest + rust: nightly + name: "Linux x86 (nightly tail calls)" + args: "--features tinywasm/nightly-tail-calls" - os: ubuntu-latest rust: stable name: "Linux x86 (stable, no default features)" @@ -62,6 +66,10 @@ jobs: rust: nightly name: "Linux x86 (nightly, no default features)" args: "--no-default-features" + - os: ubuntu-latest + rust: nightly + name: "Linux x86 (nightly tail calls, no default features)" + args: "--no-default-features --features tinywasm/nightly-tail-calls" - os: macos-14 rust: stable name: "macOS arm64 (Apple M1)" diff --git a/CHANGELOG.md b/CHANGELOG.md index a24ba43..d674c30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Optional parse-time operand deduplication to reduce `.twasm` archive size - Optional `send` support for moving stores and store-local handles across threads - Optional portable atomic shared pointers and counters for targets without native compare-and-swap +- Optional `nightly-tail-calls` backend using Rust's unstable explicit tail calls for interpreter dispatch ### Changed diff --git a/README.md b/README.md index 20c432a..383b007 100644 --- a/README.md +++ b/README.md @@ -50,15 +50,17 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin - **`full`:** Enables `archive`, `parallel-parser`, `parser`, and `validate`. Enabled by default. - **`std`:** Enables `std` and parsing from files and streams. Enabled by default. -- **`log`:** Enables integration with the `log` crate. Enabled by default. - **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default. - **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through [`ParserOptions`](https://docs.rs/tinywasm/latest/tinywasm/parser/struct.ParserOptions.html). +- **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default. - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default. +- **`log`:** Enables integration with the `log` crate. Enabled by default. +- **`send`:** Makes stores and store-local handles movable across threads. +- **`portable-atomic`:** Supports targets without native atomic compare-and-swap. - **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results. Enabled by default. - **`debug`:** Derives `Debug` for runtime types. Enabled by default. -- **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default. - **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`). -- **`send`:** Makes stores and store-local handles movable across threads +- **`nightly-tail-calls`:** Uses Rust's unstable explicit tail calls for interpreter dispatch. Requires nightly Rust (recommended for maximum performance). - **`simd-x86`:** Enables x86-specific SIMD intrinsics and uses `unsafe` internally. With default features disabled, `tinywasm` supports `no_std + alloc` and depends only on `libm`. diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 02add87..4ebdc6c 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -50,10 +50,8 @@ impl ModuleRegistry { } fn definition(&self, id: Option>) -> Option { - match id { - Some(id) => self.definitions.get(id.name()).cloned(), - None => self.last_definition.clone(), - } + let Some(id) = id else { return self.last_definition.clone() }; + self.definitions.get(id.name()).cloned() } fn update_last_instance(&mut self, instance: ModuleInstance, name: Option) { @@ -71,21 +69,13 @@ impl ModuleRegistry { } fn get_idx(&self, module_id: Option>) -> Option { - match module_id { - Some(module) => { - self.registered.get(module.name()).or_else(|| self.instances.get(module.name())).map(ModuleInstance::id) - } - None => self.last_instance.as_ref().map(ModuleInstance::id), - } + let Some(module_id) = module_id else { return self.last_instance.as_ref().map(ModuleInstance::id) }; + self.registered.get(module_id.name()).or_else(|| self.instances.get(module_id.name())).map(ModuleInstance::id) } fn get(&self, module_id: Option>) -> Option { - match module_id { - Some(module_id) => { - self.registered.get(module_id.name()).or_else(|| self.instances.get(module_id.name())).cloned() - } - None => self.last_instance.clone(), - } + let Some(module_id) = module_id else { return self.last_instance.clone() }; + self.registered.get(module_id.name()).or_else(|| self.instances.get(module_id.name())).cloned() } } diff --git a/crates/parser/Cargo.toml b/crates/parser/Cargo.toml index 042eeda..7d781a4 100644 --- a/crates/parser/Cargo.toml +++ b/crates/parser/Cargo.toml @@ -32,3 +32,6 @@ std = ["tinywasm-types/std", "wasmparser/std"] # validate WebAssembly while parsing validate = ["wasmparser/features", "wasmparser/validate"] + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(rust_analyzer)"] } diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index e20f6c6..3d78fca 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -122,6 +122,9 @@ debug = ["tinywasm-types/debug"] # expose module-internal by-index inspection APIs for non-exported entities (for testing and debugging) guest-debug = [] +# use explicit tail calls for interpreter dispatch (requires nightly Rust) +nightly-tail-calls = [] + # enable x86-specific SIMD intrinsics in Value128 (uses unsafe code) # note: for x86 backend selection, compile with x86-64-v3 target features # (for example: `RUSTFLAGS="-C target-cpu=x86-64-v3"`) diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs deleted file mode 100644 index 5266084..0000000 --- a/crates/tinywasm/src/interpreter/executor.rs +++ /dev/null @@ -1,2289 +0,0 @@ -use core::{convert::identity, ops::ControlFlow}; - -#[cfg(not(feature = "std"))] -#[allow(unused_imports)] -use super::no_std_floats::NoStdFloatExt; - -use alloc::boxed::Box; -use alloc::vec::Vec; - -use interpreter::stack::{CallFrame, ValueStack}; -use tinywasm_types::*; - -use super::ExecState; -use super::num_helpers::*; -use super::values::*; -use crate::engine::FuelPolicy; -use crate::func::HostFunction; -use crate::interpreter::Value128; -use crate::*; - -const FUEL_COST_CALL_TOTAL: u32 = 5; - -pub(crate) struct Executor<'store, const BUDGETED: bool> { - cf: CallFrame, - func: Shared, - module: ModuleInstance, - store: &'store mut Store, - call_stack_base: u32, - mem0: MemAddr, -} - -impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { - pub(crate) fn new(store: &'store mut Store, cf: CallFrame, call_stack_base: u32) -> Self { - let wasm_func = store.state.funcs.wasm(cf.func_addr); - let module = store.get_module_instance(wasm_func.owner).expect("invalid module instance").clone(); - let mem0 = module.mem0_addr(); - Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base, mem0 } - } - - #[inline(always)] - fn exec(&mut self, instr_ptr: usize) -> Result> { - macro_rules! exec_op { - (binary_fallible $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - fn exec_binary_fallible(value_stack: &mut ValueStack) -> Result<(), Trap> { - let $rhs = <$ty>::stack_pop(value_stack); - let $lhs = <$ty>::stack_pop(value_stack); - <$ty>::stack_push(value_stack, $expr?) - } - exec_binary_fallible(&mut self.store.value_stack)?; - }}; - (unary $from:ty => $to:ty, |$v:ident| $expr:expr) => {{ - fn exec_unary(value_stack: &mut ValueStack) -> Result<(), Trap> { - let $v = <$from>::stack_pop(value_stack); - <$to>::stack_push(value_stack, $expr) - } - exec_unary(&mut self.store.value_stack)?; - }}; - (binary $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - fn exec_binary(value_stack: &mut ValueStack) -> Result<(), Trap> { - let $rhs = <$from>::stack_pop(value_stack); - let $lhs = <$from>::stack_pop(value_stack); - <$to>::stack_push(value_stack, $expr) - } - exec_binary(&mut self.store.value_stack)?; - }}; - (binary $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - fn exec_binary(value_stack: &mut ValueStack) -> Result<(), Trap> { - let $rhs = <$rhs_ty>::stack_pop(value_stack); - let $lhs = <$lhs_ty>::stack_pop(value_stack); - <$res>::stack_push(value_stack, $expr) - } - exec_binary(&mut self.store.value_stack)?; - }}; - (ternary $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{ - fn exec_ternary(value_stack: &mut ValueStack) -> Result<(), Trap> { - let $c = <$from>::stack_pop(value_stack); - let $b = <$from>::stack_pop(value_stack); - let $a = <$from>::stack_pop(value_stack); - <$to>::stack_push(value_stack, $expr) - } - exec_ternary(&mut self.store.value_stack)?; - }}; - } - - use tinywasm_types::Instruction::*; - #[rustfmt::skip] - match &self.func.instructions[instr_ptr] { - Unreachable => return cold!(Err(Trap::Unreachable.into())), - Drop32 => { _ = Value32::stack_pop(&mut self.store.value_stack)}, - Drop64 => { _ = Value64::stack_pop(&mut self.store.value_stack)}, - Drop128 => { _ = Value128::stack_pop(&mut self.store.value_stack)}, - Select32 => Value32::stack_select(&mut self.store.value_stack), - Select64 => Value64::stack_select(&mut self.store.value_stack), - Select128 => Value128::stack_select(&mut self.store.value_stack), - SelectStore32(idx) => self.exec_select_store::(idx.resolve(&self.func.data))?, - SelectStore64(idx) => self.exec_select_store::(idx.resolve(&self.func.data))?, - SelectMulti(counts) => self.store.value_stack.select_multi(*counts), - Call(v) => return self.exec_call_direct(*v, instr_ptr + 1), - CallSelf => return self.exec_call_self(instr_ptr + 1), - CallIndirect(idx) => return self.exec_call_indirect::(*idx, instr_ptr + 1), - CallRef(ty) => return self.exec_call_ref::(*ty, instr_ptr + 1), - ReturnCall(v) => return self.exec_return_call_direct(*v), - ReturnCallSelf => return self.exec_return_call_self(), - ReturnCallIndirect(idx) => return self.exec_call_indirect::(*idx, instr_ptr + 1), - ReturnCallRef(ty) => return self.exec_call_ref::(*ty, instr_ptr + 1), - Throw(tag) => return self.exec_throw(*tag, instr_ptr), - ThrowRef => return self.exec_throw_ref(instr_ptr), - Jump(ip) => return Ok(ControlFlow::Continue(*ip as usize)), - JumpIfZero32(ip) => if i32::stack_pop(&mut self.store.value_stack) == 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfNonZero32(ip) => if i32::stack_pop(&mut self.store.value_stack) != 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfZero64(ip) => if i64::stack_pop(&mut self.store.value_stack) == 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfNonZero64(ip) => if i64::stack_pop(&mut self.store.value_stack) != 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfRefNull(ip) => { let ip = *ip; if self.exec_jump_if_ref::() { return Ok(ControlFlow::Continue(ip as usize)) } }, - JumpIfRefNonNull(ip) => { let ip = *ip; if self.exec_jump_if_ref::() { return Ok(ControlFlow::Continue(ip as usize)) } }, - BrOnCast(idx) => if let Some(ip) = self.exec_br_on_cast::(*idx) { return Ok(ControlFlow::Continue(ip)) }, - BrOnCastFail(idx) => if let Some(ip) = self.exec_br_on_cast::(*idx) { return Ok(ControlFlow::Continue(ip)) }, - JumpIfLocalZero32(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalNonZero32(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalZero64(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalNonZero64(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpCmpStackConst32(packed) => if let Some(ip) = self.exec_jump_cmp_stack_const32(*packed) { return Ok(ControlFlow::Continue(ip)) }, - JumpCmpStackConst64(packed) => if let Some(ip) = self.exec_jump_cmp_stack_const64(*packed) { return Ok(ControlFlow::Continue(ip)) }, - JumpCmpStackLocal32(packed) => if let Some(ip) = self.exec_jump_cmp_stack_local32(*packed) { return Ok(ControlFlow::Continue(ip)) }, - JumpCmpStackLocal64(packed) => if let Some(ip) = self.exec_jump_cmp_stack_local64(*packed) { return Ok(ControlFlow::Continue(ip)) }, - BinOpLocalConstJump32(packed) => if let Some(ip) = self.exec_binop_local_const_jump(*packed) { return Ok(ControlFlow::Continue(ip)) }, - BinOpLocalConstJumpCmpLocal32(packed) => if let Some(ip) = self.exec_binop_local_const_jump_cmp_local(*packed) { return Ok(ControlFlow::Continue(ip)) }, - BinOpStackConstTeeLocalJump32(packed) => if let Some(ip) = self.exec_binop_stack_const_tee_local_jump(*packed)? { return Ok(ControlFlow::Continue(ip)) }, - BinOpGlobalConstJump32(packed) => if let Some(ip) = self.exec_binop_global_const_jump(*packed) { return Ok(ControlFlow::Continue(ip)) }, - IncLocalJump32(idx) => if let Some(ip) = self.exec_inc_local_jump(*idx) { return Ok(ControlFlow::Continue(ip)) }, - IncStackTeeLocalJump32(idx) => if let Some(ip) = self.exec_inc_stack_tee_local_jump(*idx)? { return Ok(ControlFlow::Continue(ip)) }, - IncGlobalJump32(idx) => if let Some(ip) = self.exec_inc_global_jump(*idx) { return Ok(ControlFlow::Continue(ip)) }, - IncLocalJumpCmpLocal32(packed) => if let Some(ip) = self.exec_inc_local_jump_cmp_local(*packed) { return Ok(ControlFlow::Continue(ip)) }, - JumpCmpLocalConst32(packed) => if let Some(ip) = self.exec_jump_cmp_local_const32(*packed) { return Ok(ControlFlow::Continue(ip)) }, - JumpCmpLocalConst64(packed) => if let Some(ip) = self.exec_jump_cmp_local_const64(*packed) { return Ok(ControlFlow::Continue(ip)) }, - JumpCmpLocalLocal32(packed) => if let Some(ip) = self.exec_jump_cmp_local_local32(*packed) { return Ok(ControlFlow::Continue(ip)) }, - JumpCmpLocalLocal64(packed) => if let Some(ip) = self.exec_jump_cmp_local_local64(*packed) { return Ok(ControlFlow::Continue(ip)) }, - DropKeep32 { base, keep } => self.store.value_stack.stack_32.truncate_keep((self.cf.stack_base().s32 + u32::from(*base)) as usize, *keep as usize), - DropKeep64 { base, keep } => self.store.value_stack.stack_64.truncate_keep((self.cf.stack_base().s64 + u32::from(*base)) as usize, *keep as usize), - DropKeep128 { base, keep } => self.store.value_stack.stack_128.truncate_keep((self.cf.stack_base().s128 + u32::from(*base)) as usize, *keep as usize), - BranchTable(idx) => return Ok(ControlFlow::Continue(self.exec_branch_table(*idx))), - Return => return Ok(self.exec_return()), - ReturnVoid => return Ok(self.exec_return_void()), - Return32 => return Ok(self.exec_return_32()), - Return64 => return Ok(self.exec_return_64()), - Return128 => return Ok(self.exec_return_128()), - LocalGet32(local_index) => Value32::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, - LocalGet64(local_index) => Value64::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, - LocalGet128(local_index) => Value128::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, - LocalSet32(local_index) => self.exec_local_set_pop::(*local_index), - LocalSet64(local_index) => self.exec_local_set_pop::(*local_index), - LocalSet128(local_index) => self.exec_local_set_pop::(*local_index), - LocalCopy32(from, to) => Value32::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), - LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), - LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), - AddConst32(c) => { i32::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(*c)); }, - AndConst32(c) => { i32::stack_update(&mut self.store.value_stack, |value| value & *c); }, - XorConst32(c) => { i32::stack_update(&mut self.store.value_stack, |value| value ^ *c); }, - ShrUConst32(c) => { u32::stack_update(&mut self.store.value_stack, |value| value.wrapping_shr(*c as u32)); }, - AddConst64(idx) => { let rhs = idx.resolve(&self.func.data).value(); i64::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(rhs)); }, - BinOpStackConst32(op, rhs) => { u32::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, *rhs as u32)); }, - BinOpStackConst64(packed) => { let rhs = packed.index.resolve(&self.func.data).value() as u64; u64::stack_update(&mut self.store.value_stack, |lhs| packed.op.exec(lhs, rhs)); }, - IncLocal32(arg) => { i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |value| value.wrapping_add(arg.value)); }, - IncLocal64(packed) => { let rhs = packed.index.resolve(&self.func.data).value(); i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |value| value.wrapping_add(rhs)); }, - I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), - I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), - MulAccLocal32(acc) => self.exec_mul_acc_local::(*acc, i32::wrapping_mul, i32::wrapping_add), - MulAccLocal64(acc) => self.exec_mul_acc_local::(*acc, i64::wrapping_mul, i64::wrapping_add), - FMulAccLocal32(acc) => self.exec_mul_acc_local::(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), - FMulAccLocal64(acc) => self.exec_mul_acc_local::(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), - BinOpLocalLocal32(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, - BinOpLocalLocal64(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, - BinOpLocalLocal128(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, - CmpLocalLocal32(op, a, b) => self.exec_cmp_local_local::(*a, *b, *op)?, - CmpLocalLocal64(op, a, b) => self.exec_cmp_local_local::(*a, *b, *op)?, - AddLocalLocalSet32(arg) => self.exec_binop_local_local::(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, - AddLocalLocalTee32(arg) => self.exec_binop_local_local::(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, - BinOpLocalLocalSet32(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, - BinOpLocalLocalSet64(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, - BinOpLocalLocalSet128(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, - BinOpLocalLocalTee32(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, - BinOpLocalLocalTee64(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, - BinOpLocalLocalTee128(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, - AddLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IAdd)?, - SubLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::ISub)?, - MulLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IMul)?, - AndLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IAnd)?, - ShrULocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IShrU)?, - BinOpLocalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.b(), None, packed.op)?; }, - BinOpLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.b(), None, packed.op)?; }, - BinOpLocalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, None, packed.op)?; }, - BinOpLocalConstSet32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, - BinOpLocalConstTee32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, - BinOpLocalConstSet64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, - BinOpLocalConstTee64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, - BinOpLocalConstSet128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, Some(v.b()), packed.op)?; }, - BinOpLocalConstTee128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, Some(v.b()), packed.op)?; }, - BinOpStackLocal32(op, local) => self.exec_binop_stack_local::(*local, None, *op)?, - BinOpStackLocalSet32(op, local, dst) => self.exec_binop_stack_local::(*local, Some(*dst), *op)?, - BinOpStackLocalTee32(op, local, dst) => self.exec_binop_stack_local::(*local, Some(*dst), *op)?, - BinOpStackLocal128(op, local) => self.exec_binop_stack_local::(*local, None, *op)?, - BinOpStackGlobal32(op, global_index) => self.exec_binop_stack_global::(*global_index, *op)?, - BinOpStackGlobal64(op, global_index) => self.exec_binop_stack_global::(*global_index, *op)?, - BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, - BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, - BinOpGlobalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_global_const::(v.a(), rhs, packed.op)?; }, - SetLocalConst32(arg) => i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, arg.value), - SetLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); }, - SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.resolve(&self.func.data).value())), - IncMemoryLocal32(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, - IncMemoryLocal64(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, - StoreLocalLocal32(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, - StoreLocalLocal64(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, - StoreLocalLocal128(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, - LoadLocal32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, identity)?, - LoadLocal64(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, identity)?, - LoadLocal8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, - LoadLocal8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, - LoadLocal16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, - LoadLocal16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, - LoadLocalTee32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, - LoadLocalSet32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, - LoadLocalTee8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalTee8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalTee16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalTee16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalSet8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalSet8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalSet16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalSet16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalTee128(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, - LoadLocalSet128(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, - AndConstTee32(arg) => self.exec_binop_const_tee::(arg.value as u32, arg.local, BinOp::IAnd)?, - SubConstTee32(arg) => self.exec_binop_const_tee::(arg.value as u32, arg.local, BinOp::ISub)?, - AndConstTee64(packed) => self.exec_binop_const_tee::(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::IAnd)?, - SubConstTee64(packed) => self.exec_binop_const_tee::(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::ISub)?, - LocalTee32(local_index) => self.exec_local_tee::(*local_index), - LocalTee64(local_index) => self.exec_local_tee::(*local_index), - LocalTee128(local_index) => self.exec_local_tee::(*local_index), - GlobalGet32(global_index) => self.exec_global_get::(*global_index)?, - GlobalGet64(global_index) => self.exec_global_get::(*global_index)?, - GlobalGet128(global_index) => self.exec_global_get::(*global_index)?, - GlobalSet32(global_index) => self.exec_global_set::(*global_index), - GlobalSet64(global_index) => self.exec_global_set::(*global_index), - GlobalSet128(global_index) => self.exec_global_set::(*global_index), - GlobalTee32(global_index) => self.exec_global_tee::(*global_index), - GlobalTee64(global_index) => self.exec_global_tee::(*global_index), - GlobalTee128(global_index) => self.exec_global_tee::(*global_index), - Const32(val) => i32::stack_push(&mut self.store.value_stack, *val)?, - Const64Imm(val) => i64::stack_push(&mut self.store.value_stack, i64::from(*val))?, - Const64(idx) => i64::stack_push(&mut self.store.value_stack, idx.resolve(&self.func.data).value())?, - Const128Imm(val) => Value128::stack_push(&mut self.store.value_stack, Value128(u128::from(*val).to_le_bytes()))?, - I64Eqz => exec_op!(unary i64 => i32, |v| i32::from(v == 0)), - I32Eqz => exec_op!(unary i32 => i32, |v| i32::from(v == 0)), - I32Eq => exec_op!(binary i32 => i32, |a, b| i32::from(a == b)), - I64Eq => exec_op!(binary i64 => i32, |a, b| i32::from(a == b)), - F32Eq => exec_op!(binary f32 => i32, |a, b| i32::from(a == b)), - F64Eq => exec_op!(binary f64 => i32, |a, b| i32::from(a == b)), - I32Ne => exec_op!(binary i32 => i32, |a, b| i32::from(a != b)), - I64Ne => exec_op!(binary i64 => i32, |a, b| i32::from(a != b)), - F32Ne => exec_op!(binary f32 => i32, |a, b| i32::from(a != b)), - F64Ne => exec_op!(binary f64 => i32, |a, b| i32::from(a != b)), - I32LtS => exec_op!(binary i32 => i32, |a, b| i32::from(a < b)), - I64LtS => exec_op!(binary i64 => i32, |a, b| i32::from(a < b)), - I32LtU => exec_op!(binary u32 => i32, |a, b| i32::from(a < b)), - I64LtU => exec_op!(binary u64 => i32, |a, b| i32::from(a < b)), - F32Lt => exec_op!(binary f32 => i32, |a, b| i32::from(a < b)), - F64Lt => exec_op!(binary f64 => i32, |a, b| i32::from(a < b)), - I32LeS => exec_op!(binary i32 => i32, |a, b| i32::from(a <= b)), - I64LeS => exec_op!(binary i64 => i32, |a, b| i32::from(a <= b)), - I32LeU => exec_op!(binary u32 => i32, |a, b| i32::from(a <= b)), - I64LeU => exec_op!(binary u64 => i32, |a, b| i32::from(a <= b)), - F32Le => exec_op!(binary f32 => i32, |a, b| i32::from(a <= b)), - F64Le => exec_op!(binary f64 => i32, |a, b| i32::from(a <= b)), - I32GeS => exec_op!(binary i32 => i32, |a, b| i32::from(a >= b)), - I64GeS => exec_op!(binary i64 => i32, |a, b| i32::from(a >= b)), - I32GeU => exec_op!(binary u32 => i32, |a, b| i32::from(a >= b)), - I64GeU => exec_op!(binary u64 => i32, |a, b| i32::from(a >= b)), - F32Ge => exec_op!(binary f32 => i32, |a, b| i32::from(a >= b)), - F64Ge => exec_op!(binary f64 => i32, |a, b| i32::from(a >= b)), - I32GtS => exec_op!(binary i32 => i32, |a, b| i32::from(a > b)), - I64GtS => exec_op!(binary i64 => i32, |a, b| i32::from(a > b)), - I32GtU => exec_op!(binary u32 => i32, |a, b| i32::from(a > b)), - I64GtU => exec_op!(binary u64 => i32, |a, b| i32::from(a > b)), - F32Gt => exec_op!(binary f32 => i32, |a, b| i32::from(a > b)), - F64Gt => exec_op!(binary f64 => i32, |a, b| i32::from(a > b)), - I32Add => exec_op!(binary i32 => i32, |a, b| a.wrapping_add(b)), - I64Add => exec_op!(binary i64 => i64, |a, b| a.wrapping_add(b)), - F32Add => exec_op!(binary f32 => f32, |a, b| a + b), - F64Add => exec_op!(binary f64 => f64, |a, b| a + b), - I32Sub => exec_op!(binary i32 => i32, |a, b| a.wrapping_sub(b)), - I64Sub => exec_op!(binary i64 => i64, |a, b| a.wrapping_sub(b)), - F32Sub => exec_op!(binary f32 => f32, |a, b| a - b), - F64Sub => exec_op!(binary f64 => f64, |a, b| a - b), - F32Div => exec_op!(binary f32 => f32, |a, b| a / b), - F64Div => exec_op!(binary f64 => f64, |a, b| a / b), - I32Mul => exec_op!(binary i32 => i32, |a, b| a.wrapping_mul(b)), - I64Mul => exec_op!(binary i64 => i64, |a, b| a.wrapping_mul(b)), - F32Mul => exec_op!(binary f32 => f32, |a, b| a * b), - F64Mul => exec_op!(binary f64 => f64, |a, b| a * b), - I32DivS => exec_op!(binary_fallible i32, |a, b| a.tw_checked_div(b)), - I64DivS => exec_op!(binary_fallible i64, |a, b| a.tw_checked_div(b)), - I32DivU => exec_op!(binary_fallible u32, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), - I64DivU => exec_op!(binary_fallible u64, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), - I32RemS => exec_op!(binary_fallible i32, |a, b| a.tw_checked_wrapping_rem(b)), - I64RemS => exec_op!(binary_fallible i64, |a, b| a.tw_checked_wrapping_rem(b)), - I32RemU => exec_op!(binary_fallible u32, |a, b| a.tw_checked_wrapping_rem(b)), - I64RemU => exec_op!(binary_fallible u64, |a, b| a.tw_checked_wrapping_rem(b)), - I32And => exec_op!(binary i32 => i32, |a, b| a & b), - I64And => exec_op!(binary i64 => i64, |a, b| a & b), - I32Or => exec_op!(binary i32 => i32, |a, b| a | b), - I64Or => exec_op!(binary i64 => i64, |a, b| a | b), - I32Xor => exec_op!(binary i32 => i32, |a, b| a ^ b), - I64Xor => exec_op!(binary i64 => i64, |a, b| a ^ b), - I32Shl => exec_op!(binary i32 => i32, |a, b| a.wrapping_shl(b as u32)), - I64Shl => exec_op!(binary i64 => i64, |a, b| a.wrapping_shl(b as u32)), - I32ShrS => exec_op!(binary i32 => i32, |a, b| a.wrapping_shr(b as u32)), - I64ShrS => exec_op!(binary i64 => i64, |a, b| a.wrapping_shr(b as u32)), - I32ShrU => exec_op!(binary u32 => u32, |a, b| a.wrapping_shr(b)), - I64ShrU => exec_op!(binary u64 => u64, |a, b| a.wrapping_shr(b as u32)), - I32Rotl => exec_op!(binary i32 => i32, |a, b| a.rotate_left(b as u32)), - I64Rotl => exec_op!(binary i64 => i64, |a, b| a.rotate_left(b as u32)), - I32Rotr => exec_op!(binary i32 => i32, |a, b| a.rotate_right(b as u32)), - I64Rotr => exec_op!(binary i64 => i64, |a, b| a.rotate_right(b as u32)), - I64Add128 => self.exec_i64_add128()?, - I64Sub128 => self.exec_i64_sub128()?, - I64MulWideS => self.exec_i64_mul_wide_s()?, - I64MulWideU => self.exec_i64_mul_wide_u()?, - I32Clz => exec_op!(unary i32 => i32, |v| v.leading_zeros() as i32), - I64Clz => exec_op!(unary i64 => i64, |v| i64::from(v.leading_zeros())), - I32Ctz => exec_op!(unary i32 => i32, |v| v.trailing_zeros() as i32), - I64Ctz => exec_op!(unary i64 => i64, |v| i64::from(v.trailing_zeros())), - I32Popcnt => exec_op!(unary i32 => i32, |v| v.count_ones() as i32), - I64Popcnt => exec_op!(unary i64 => i64, |v| i64::from(v.count_ones())), - - // Reference types - RefFunc(func_idx) => ValueRef::stack_push(&mut self.store.value_stack, ValueRef::from_category_addr(self.module.resolve_func_addr(*func_idx)))?, - RefNull(_) => ValueRef::stack_push(&mut self.store.value_stack, ValueRef::NULL)?, - RefIsNull => self.exec_ref_is_null()?, - RefAsNonNull => self.exec_ref_as_non_null()?, - RefI31 => exec_op!(unary i32 => ValueRef, |v| ValueRef::from_i31(v)), - I31GetS => self.exec_i31_get(true)?, - I31GetU => self.exec_i31_get(false)?, - RefEq => exec_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), - RefTest(ty) => self.exec_ref_test(*ty)?, - RefCast(ty) => self.exec_ref_cast(*ty)?, - - // GC objects - StructNew(ty) => self.exec_struct_new(*ty, false)?, - StructNewDefault(ty) => self.exec_struct_new(*ty, true)?, - StructGet(idx) => self.exec_struct_get(*idx, None)?, - StructGetS(idx) => self.exec_struct_get(*idx, Some(true))?, - StructGetU(idx) => self.exec_struct_get(*idx, Some(false))?, - StructSet(idx) => self.exec_struct_set(*idx)?, - ArrayNew(ty) => self.exec_array_new(*ty, false)?, - ArrayNewDefault(ty) => self.exec_array_new(*ty, true)?, - ArrayNewFixed(idx) => self.exec_array_new_fixed(*idx)?, - ArrayNewData(idx) => self.exec_array_new_data(*idx)?, - ArrayNewElem(idx) => self.exec_array_new_elem(*idx)?, - ArrayGet(ty) => self.exec_array_get(*ty, None)?, - ArrayGetS(ty) => self.exec_array_get(*ty, Some(true))?, - ArrayGetU(ty) => self.exec_array_get(*ty, Some(false))?, - ArraySet(ty) => self.exec_array_set(*ty)?, - ArrayLen => self.exec_array_len()?, - ArrayFill(ty) => self.exec_array_fill(*ty)?, - ArrayCopy(idx) => self.exec_array_copy(*idx)?, - ArrayInitData(idx) => self.exec_array_init_data(*idx)?, - ArrayInitElem(idx) => self.exec_array_init_elem(*idx)?, - MemorySize(addr) => self.exec_memory_size(*addr)?, - MemoryGrow(addr) => self.exec_memory_grow(*addr)?, - - // Bulk memory operations - MemoryCopy(idx) => self.exec_memory_copy(*idx)?, - MemoryFill(addr) => self.exec_memory_fill(*addr)?, - MemoryFillConst(idx) => self.exec_memory_fill_const(*idx)?, - MemoryInit(idx) => self.exec_memory_init(*idx)?, - DataDrop(data_index) => self.store.state.get_data_mut(self.module.resolve_data_addr(*data_index)).drop(), - ElemDrop(elem_index) => self.store.state.get_elem_mut(self.module.resolve_elem_addr(*elem_index)).drop(), - - // Table instructions - TableGet(table_idx) => self.exec_table_get(*table_idx)?, - TableSet(table_idx) => self.exec_table_set(*table_idx)?, - TableSize(table_idx) => self.exec_table_size(*table_idx)?, - TableInit(idx) => self.exec_table_init(*idx)?, - TableGrow(table_idx) => self.exec_table_grow(*table_idx)?, - TableFill(table_idx) => self.exec_table_fill(*table_idx)?, - TableCopy(idx) => self.exec_table_copy(*idx)?, - - // Core memory load/store operations - I32Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), identity)?, - I64Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), identity)?, - F32Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), identity)?, - F64Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), identity)?, - FMaStoreF32(m) => self.exec_fma_store::(*m)?, - FMaStoreF64(m) => self.exec_fma_store::(*m)?, - I32Store8(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, - I32Store16(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?, - I64Store8(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, - I64Store16(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?, - I64Store32(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i32)?, - I32Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), identity)?, - I64Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), identity)?, - F32Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), identity)?, - F64Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), identity)?, - I32Load8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, - I32Load8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, - I32Load16S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, - I32Load16U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, - I64Load8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, - I64Load8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, - I64Load16S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, - I64Load16U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, - I64Load32S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, - I64Load32U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, - - // Numeric conversion operations - F32ConvertI32S => exec_op!(unary i32 => f32, |v| v as f32), - F32ConvertI64S => exec_op!(unary i64 => f32, |v| v as f32), - F64ConvertI32S => exec_op!(unary i32 => f64, |v| f64::from(v)), - F64ConvertI64S => exec_op!(unary i64 => f64, |v| v as f64), - F32ConvertI32U => exec_op!(unary u32 => f32, |v| v as f32), - F32ConvertI64U => exec_op!(unary u64 => f32, |v| v as f32), - F64ConvertI32U => exec_op!(unary u32 => f64, |v| f64::from(v)), - F64ConvertI64U => exec_op!(unary u64 => f64, |v| v as f64), - - // Sign-extension operations - I32Extend8S => exec_op!(unary i32 => i32, |v| i32::from(v as i8)), - I32Extend16S => exec_op!(unary i32 => i32, |v| i32::from(v as i16)), - I64Extend8S => exec_op!(unary i64 => i64, |v| i64::from(v as i8)), - I64Extend16S => exec_op!(unary i64 => i64, |v| i64::from(v as i16)), - I64Extend32S => exec_op!(unary i64 => i64, |v| i64::from(v as i32)), - I64ExtendI32U => exec_op!(unary u32 => i64, |v| i64::from(v)), - I64ExtendI32S => exec_op!(unary i32 => i64, |v| i64::from(v)), - I32WrapI64 => exec_op!(unary i64 => i32, |v| v as i32), - F32DemoteF64 => exec_op!(unary f64 => f32, |v| v as f32), - F64PromoteF32 => exec_op!(unary f32 => f64, |v| f64::from(v)), - F32Abs => exec_op!(unary f32 => f32, |v| v.abs()), - F64Abs => exec_op!(unary f64 => f64, |v| v.abs()), - F32Neg => exec_op!(unary f32 => f32, |v| -v), - F64Neg => exec_op!(unary f64 => f64, |v| -v), - F32Ceil => exec_op!(unary f32 => f32, |v| v.ceil()), - F64Ceil => exec_op!(unary f64 => f64, |v| v.ceil()), - F32Floor => exec_op!(unary f32 => f32, |v| v.floor()), - F64Floor => exec_op!(unary f64 => f64, |v| v.floor()), - F32Trunc => exec_op!(unary f32 => f32, |v| v.trunc()), - F64Trunc => exec_op!(unary f64 => f64, |v| v.trunc()), - F32Nearest => exec_op!(unary f32 => f32, |v| v.tw_nearest()), - F64Nearest => exec_op!(unary f64 => f64, |v| v.tw_nearest()), - F32Sqrt => exec_op!(unary f32 => f32, |v| v.sqrt()), - F64Sqrt => exec_op!(unary f64 => f64, |v| v.sqrt()), - F32Min => exec_op!(binary f32 => f32, |a, b| a.tw_minimum(b)), - F64Min => exec_op!(binary f64 => f64, |a, b| a.tw_minimum(b)), - F32Max => exec_op!(binary f32 => f32, |a, b| a.tw_maximum(b)), - F64Max => exec_op!(binary f64 => f64, |a, b| a.tw_maximum(b)), - F32Copysign => exec_op!(binary f32 => f32, |a, b| a.copysign(b)), - F64Copysign => exec_op!(binary f64 => f64, |a, b| a.copysign(b)), - I32TruncF32S => checked_conv_float!(f32, i32, self), - I32TruncF64S => checked_conv_float!(f64, i32, self), - I32TruncF32U => checked_conv_float!(f32, u32, i32, self), - I32TruncF64U => checked_conv_float!(f64, u32, i32, self), - I64TruncF32S => checked_conv_float!(f32, i64, self), - I64TruncF64S => checked_conv_float!(f64, i64, self), - I64TruncF32U => checked_conv_float!(f32, u64, i64, self), - I64TruncF64U => checked_conv_float!(f64, u64, i64, self), - - // Non-trapping float-to-int conversions - I32TruncSatF32S => exec_op!(unary f32 => i32, |v| v.trunc() as i32), - I32TruncSatF32U => exec_op!(unary f32 => u32, |v| v.trunc() as u32), - I32TruncSatF64S => exec_op!(unary f64 => i32, |v| v.trunc() as i32), - I32TruncSatF64U => exec_op!(unary f64 => u32, |v| v.trunc() as u32), - I64TruncSatF32S => exec_op!(unary f32 => i64, |v| v.trunc() as i64), - I64TruncSatF32U => exec_op!(unary f32 => u64, |v| v.trunc() as u64), - I64TruncSatF64S => exec_op!(unary f64 => i64, |v| v.trunc() as i64), - I64TruncSatF64U => exec_op!(unary f64 => u64, |v| v.trunc() as u64), - - // SIMD extension - V128Not => exec_op!(unary Value128 => Value128, |v| v.v128_not()), - V128And => exec_op!(binary Value128 => Value128, |a, b| a.v128_and(b)), - V128AndNot => exec_op!(binary Value128 => Value128, |a, b| a.v128_andnot(b)), - V128Or => exec_op!(binary Value128 => Value128, |a, b| a.v128_or(b)), - V128Xor => exec_op!(binary Value128 => Value128, |a, b| a.v128_xor(b)), - V128Bitselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::v128_bitselect(a, b, c)), - V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), - I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), - I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), - V128Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), identity)?, - V128Load8x8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, - V128Load8x8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, - V128Load16x4S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, - V128Load16x4U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, - V128Load32x2S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, - V128Load32x2U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, - V128Load8Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i8)?, - V128Load16Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i16)?, - V128Load32Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i32)?, - V128Load64Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i64)?, - V128Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), identity)?, - V128Store8Lane(arg) => self.exec_mem_store_lane::(*arg)?, - V128Store16Lane(arg) => self.exec_mem_store_lane::(*arg)?, - V128Store32Lane(arg) => self.exec_mem_store_lane::(*arg)?, - V128Store64Lane(arg) => self.exec_mem_store_lane::(*arg)?, - V128Load32Zero(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::from_i32x4([v, 0, 0, 0]))?, - V128Load64Zero(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::from_i64x2([v, 0]))?, - Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(arg.resolve(&self.func.data).value()))?, - I8x16ExtractLaneS(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_i8(lane) as i32)?, - I8x16ExtractLaneU(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_u8(lane) as i32)?, - I16x8ExtractLaneS(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_i16(lane) as i32)?, - I16x8ExtractLaneU(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_u16(lane) as i32)?, - I32x4ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_i32)?, - I64x2ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_i64)?, - F32x4ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_f32)?, - F64x2ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_f64)?, - V128Load8Lane(arg) => self.exec_mem_load_lane::(*arg)?, - V128Load16Lane(arg) => self.exec_mem_load_lane::(*arg)?, - V128Load32Lane(arg) => self.exec_mem_load_lane::(*arg)?, - V128Load64Lane(arg) => self.exec_mem_load_lane::(*arg)?, - I8x16ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i8x16_replace_lane(lane, value as i8))?, - I16x8ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i16x8_replace_lane(lane, value as i16))?, - I32x4ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i32x4_replace_lane(lane, value))?, - I64x2ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i64x2_replace_lane(lane, value))?, - F32x4ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.f32x4_replace_lane(lane, value))?, - F64x2ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.f64x2_replace_lane(lane, value))?, - I8x16Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)), - I16x8Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)), - I32x4Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i32(v)), - I64x2Splat => exec_op!(unary i64 => Value128, |v| Value128::splat_i64(v)), - F32x4Splat => exec_op!(unary f32 => Value128, |v| Value128::splat_f32(v)), - F64x2Splat => exec_op!(unary f64 => Value128, |v| Value128::splat_f64(v)), - I8x16Eq => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_eq(b)), - I16x8Eq => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_eq(b)), - I32x4Eq => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_eq(b)), - I64x2Eq => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_eq(b)), - F32x4Eq => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_eq(b)), - F64x2Eq => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_eq(b)), - I8x16Ne => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ne(b)), - I16x8Ne => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ne(b)), - I32x4Ne => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ne(b)), - I64x2Ne => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_ne(b)), - F32x4Ne => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_ne(b)), - F64x2Ne => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_ne(b)), - I8x16LtS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_lt_s(b)), - I16x8LtS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_lt_s(b)), - I32x4LtS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_lt_s(b)), - I64x2LtS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_lt_s(b)), - I8x16LtU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_lt_u(b)), - I16x8LtU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_lt_u(b)), - I32x4LtU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_lt_u(b)), - F32x4Lt => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_lt(b)), - F64x2Lt => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_lt(b)), - F32x4Gt => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_gt(b)), - F64x2Gt => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_gt(b)), - I8x16GtS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_gt_s(b)), - I16x8GtS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_gt_s(b)), - I32x4GtS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_gt_s(b)), - I64x2GtS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_gt_s(b)), - I64x2LeS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_le_s(b)), - F32x4Le => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_le(b)), - F64x2Le => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_le(b)), - I8x16GtU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_gt_u(b)), - I16x8GtU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_gt_u(b)), - I32x4GtU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_gt_u(b)), - F32x4Ge => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_ge(b)), - F64x2Ge => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_ge(b)), - I8x16LeS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_le_s(b)), - I16x8LeS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_le_s(b)), - I32x4LeS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_le_s(b)), - I8x16LeU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_le_u(b)), - I16x8LeU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_le_u(b)), - I32x4LeU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_le_u(b)), - I8x16GeS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ge_s(b)), - I16x8GeS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ge_s(b)), - I32x4GeS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ge_s(b)), - I64x2GeS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_ge_s(b)), - I8x16GeU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ge_u(b)), - I16x8GeU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ge_u(b)), - I32x4GeU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ge_u(b)), - I8x16Abs => exec_op!(unary Value128 => Value128, |a| a.i8x16_abs()), - I16x8Abs => exec_op!(unary Value128 => Value128, |a| a.i16x8_abs()), - I32x4Abs => exec_op!(unary Value128 => Value128, |a| a.i32x4_abs()), - I64x2Abs => exec_op!(unary Value128 => Value128, |a| a.i64x2_abs()), - I8x16Neg => exec_op!(unary Value128 => Value128, |a| a.i8x16_neg()), - I16x8Neg => exec_op!(unary Value128 => Value128, |a| a.i16x8_neg()), - I32x4Neg => exec_op!(unary Value128 => Value128, |a| a.i32x4_neg()), - I64x2Neg => exec_op!(unary Value128 => Value128, |a| a.i64x2_neg()), - I8x16AllTrue => exec_op!(unary Value128 => i32, |v| v.i8x16_all_true() as i32), - I16x8AllTrue => exec_op!(unary Value128 => i32, |v| v.i16x8_all_true() as i32), - I32x4AllTrue => exec_op!(unary Value128 => i32, |v| v.i32x4_all_true() as i32), - I64x2AllTrue => exec_op!(unary Value128 => i32, |v| v.i64x2_all_true() as i32), - I8x16Bitmask => exec_op!(unary Value128 => i32, |v| v.i8x16_bitmask() as i32), - I16x8Bitmask => exec_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32), - I32x4Bitmask => exec_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32), - I64x2Bitmask => exec_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32), - I8x16Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)), - I16x8Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)), - I32x4Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)), - I64x2Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)), - I8x16ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)), - I16x8ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)), - I32x4ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)), - I64x2ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)), - I8x16ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)), - I16x8ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)), - I32x4ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)), - I64x2ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)), - I8x16Add => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add(b)), - I16x8Add => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add(b)), - I32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_add(b)), - I64x2Add => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_add(b)), - I8x16Sub => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub(b)), - I16x8Sub => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub(b)), - I32x4Sub => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_sub(b)), - I64x2Sub => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_sub(b)), - I8x16MinS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_min_s(b)), - I16x8MinS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_min_s(b)), - I32x4MinS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_min_s(b)), - I8x16MinU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_min_u(b)), - I16x8MinU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_min_u(b)), - I32x4MinU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_min_u(b)), - I8x16MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_max_s(b)), - I16x8MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_max_s(b)), - I32x4MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_max_s(b)), - I8x16MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_max_u(b)), - I16x8MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_max_u(b)), - I32x4MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_max_u(b)), - I64x2Mul => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_mul(b)), - I16x8Mul => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_mul(b)), - I32x4Mul => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_mul(b)), - I8x16NarrowI16x8S => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_s(a, b)), - I8x16NarrowI16x8U => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_u(a, b)), - I16x8NarrowI32x4S => exec_op!(binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_s(a, b)), - I16x8NarrowI32x4U => exec_op!(binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_u(a, b)), - I8x16AddSatS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add_sat_s(b)), - I16x8AddSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add_sat_s(b)), - I8x16AddSatU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add_sat_u(b)), - I16x8AddSatU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add_sat_u(b)), - I8x16SubSatS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub_sat_s(b)), - I16x8SubSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub_sat_s(b)), - I8x16SubSatU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub_sat_u(b)), - I16x8SubSatU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub_sat_u(b)), - I8x16AvgrU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_avgr_u(b)), - I16x8AvgrU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_avgr_u(b)), - I16x8ExtAddPairwiseI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_s()), - I16x8ExtAddPairwiseI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_u()), - I32x4ExtAddPairwiseI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_s()), - I32x4ExtAddPairwiseI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_u()), - I16x8ExtMulLowI8x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_s(b)), - I16x8ExtMulLowI8x16U => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_u(b)), - I16x8ExtMulHighI8x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_s(b)), - I16x8ExtMulHighI8x16U => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_u(b)), - I32x4ExtMulLowI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_s(b)), - I32x4ExtMulLowI16x8U => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_u(b)), - I32x4ExtMulHighI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_s(b)), - I32x4ExtMulHighI16x8U => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_u(b)), - I64x2ExtMulLowI32x4S => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_s(b)), - I64x2ExtMulLowI32x4U => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_u(b)), - I64x2ExtMulHighI32x4S => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_s(b)), - I64x2ExtMulHighI32x4U => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_u(b)), - I16x8ExtendLowI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_s()), - I16x8ExtendLowI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_u()), - I16x8ExtendHighI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_s()), - I16x8ExtendHighI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_u()), - I32x4ExtendLowI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_s()), - I32x4ExtendLowI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_u()), - I32x4ExtendHighI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_s()), - I32x4ExtendHighI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_u()), - I64x2ExtendLowI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_s()), - I64x2ExtendLowI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_u()), - I64x2ExtendHighI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()), - I64x2ExtendHighI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()), - I8x16Popcnt => exec_op!(unary Value128 => Value128, |v| v.i8x16_popcnt()), - I8x16Shuffle(idx) => self.exec_simd_shuffle(Value128(idx.resolve(&self.func.data).value()))?, - I16x8Q15MulrSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), - I32x4DotI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)), - I8x16RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), - I16x8RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i16x8_relaxed_laneselect(a, b, c)), - I32x4RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i32x4_relaxed_laneselect(a, b, c)), - I64x2RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i64x2_relaxed_laneselect(a, b, c)), - I16x8RelaxedQ15mulrS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_relaxed_q15mulr_s(b)), - I16x8RelaxedDotI8x16I7x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_relaxed_dot_i8x16_i7x16_s(b)), - I32x4RelaxedDotI8x16I7x16AddS => exec_op!(ternary Value128 => Value128, |a, b, c| a.i32x4_relaxed_dot_i8x16_i7x16_add_s(b, c)), - F32x4Ceil => exec_op!(unary Value128 => Value128, |v| v.f32x4_ceil()), - F64x2Ceil => exec_op!(unary Value128 => Value128, |v| v.f64x2_ceil()), - F32x4Floor => exec_op!(unary Value128 => Value128, |v| v.f32x4_floor()), - F64x2Floor => exec_op!(unary Value128 => Value128, |v| v.f64x2_floor()), - F32x4Trunc => exec_op!(unary Value128 => Value128, |v| v.f32x4_trunc()), - F64x2Trunc => exec_op!(unary Value128 => Value128, |v| v.f64x2_trunc()), - F32x4Nearest => exec_op!(unary Value128 => Value128, |v| v.f32x4_nearest()), - F64x2Nearest => exec_op!(unary Value128 => Value128, |v| v.f64x2_nearest()), - F32x4Abs => exec_op!(unary Value128 => Value128, |v| v.f32x4_abs()), - F64x2Abs => exec_op!(unary Value128 => Value128, |v| v.f64x2_abs()), - F32x4Neg => exec_op!(unary Value128 => Value128, |v| v.f32x4_neg()), - F64x2Neg => exec_op!(unary Value128 => Value128, |v| v.f64x2_neg()), - F32x4Sqrt => exec_op!(unary Value128 => Value128, |v| v.f32x4_sqrt()), - F64x2Sqrt => exec_op!(unary Value128 => Value128, |v| v.f64x2_sqrt()), - F32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_add(b)), - F64x2Add => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_add(b)), - F32x4Sub => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_sub(b)), - F64x2Sub => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_sub(b)), - F32x4Mul => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_mul(b)), - F64x2Mul => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_mul(b)), - F32x4Div => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_div(b)), - F64x2Div => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_div(b)), - F32x4Min => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_min(b)), - F64x2Min => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_min(b)), - F32x4Max => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_max(b)), - F64x2Max => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_max(b)), - F32x4PMin => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_pmin(b)), - F32x4PMax => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_pmax(b)), - F64x2PMin => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_pmin(b)), - F64x2PMax => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_pmax(b)), - F32x4RelaxedMadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_madd(b, c)), - F32x4RelaxedNmadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_nmadd(b, c)), - F64x2RelaxedMadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_madd(b, c)), - F64x2RelaxedNmadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_nmadd(b, c)), - F32x4RelaxedMin => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_relaxed_min(b)), - F32x4RelaxedMax => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_relaxed_max(b)), - F64x2RelaxedMin => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_relaxed_min(b)), - F64x2RelaxedMax => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_relaxed_max(b)), - I32x4TruncSatF32x4S => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_s()), - I32x4TruncSatF32x4U => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_u()), - F32x4ConvertI32x4S => exec_op!(unary Value128 => Value128, |v| v.f32x4_convert_i32x4_s()), - F32x4ConvertI32x4U => exec_op!(unary Value128 => Value128, |v| v.f32x4_convert_i32x4_u()), - F64x2ConvertLowI32x4S => exec_op!(unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_s()), - F64x2ConvertLowI32x4U => exec_op!(unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_u()), - F32x4DemoteF64x2Zero => exec_op!(unary Value128 => Value128, |v| v.f32x4_demote_f64x2_zero()), - F64x2PromoteLowF32x4 => exec_op!(unary Value128 => Value128, |v| v.f64x2_promote_low_f32x4()), - I32x4TruncSatF64x2SZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_s_zero()), - I32x4TruncSatF64x2UZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_u_zero()), - I32x4RelaxedTruncF32x4S => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_s()), - I32x4RelaxedTruncF32x4U => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_u()), - I32x4RelaxedTruncF64x2SZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_s_zero()), - I32x4RelaxedTruncF64x2UZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()), - }; - - Ok(ControlFlow::Continue(instr_ptr + 1)) - } - - /// Resolves a module-local memory index to its store address, caching the common memory-0 case. - #[inline(always)] - fn mem_addr(&self, idx: MemAddr) -> MemAddr { - if idx == 0 { self.mem0 } else { self.module.resolve_mem_addr(idx) } - } - - /// Switches the executor to another module, keeping the cached memory-0 address in sync. - #[inline] - fn set_module(&mut self, owner: ModuleInstanceId) { - self.module = self.store.get_module_instance(owner).expect("invalid module instance").clone(); - self.mem0 = self.module.mem0_addr(); - } - - #[inline(always)] - fn charge_call_fuel(&mut self, total_fuel_cost: u32) { - if BUDGETED { - let extra = match self.store.engine.config().fuel_policy { - FuelPolicy::PerInstruction => 0, - FuelPolicy::Weighted => total_fuel_cost.saturating_sub(1), - }; - - self.store.execution_fuel = self.store.execution_fuel.saturating_sub(extra); - } - } - - #[inline(always)] - fn exec_jump_if_ref(&mut self) -> bool { - let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); - if is_null { - ValueRef::stack_pop(&mut self.store.value_stack); - } - is_null == ON_NULL - } - - #[inline(always)] - fn exec_br_on_cast(&self, index: Operand64Idx<(u32, u32)>) -> Option { - let operand = index.resolve(&self.func.data); - let ty = RefType::from_bits(operand.b()).expect("invalid ref type"); - (self.exec_ref_matches(ty) == ON_MATCH).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_jump_if_local( - &self, - local: LocalAddr, - ) -> bool { - (T::local_get(&self.store.value_stack, &self.cf, local) == T::default()) == ON_ZERO - } - - #[inline(always)] - fn exec_jump_cmp_stack_const32(&mut self, packed: PackedOp64) -> Option { - let operand = packed.index.resolve(&self.func.data); - packed.op.cmp(i32::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_jump_cmp_stack_const64(&mut self, packed: PackedOp128) -> Option { - let operand = packed.index.resolve(&self.func.data); - packed.op.cmp(i64::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_jump_cmp_stack_local32(&mut self, packed: PackedOp64) -> Option { - let operand = packed.index.resolve(&self.func.data); - let lhs = i32::stack_pop(&mut self.store.value_stack); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b()); - packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_jump_cmp_stack_local64(&mut self, packed: PackedOp64) -> Option { - let operand = packed.index.resolve(&self.func.data); - let lhs = i64::stack_pop(&mut self.store.value_stack); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b()); - packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_binop_local_const_jump(&mut self, packed: PackedOp128) -> Option { - let operand = packed.index.resolve(&self.func.data); - let value = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { - packed.op.exec(value as u32, operand.value() as u32) as i32 - }); - ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_binop_local_const_jump_cmp_local( - &mut self, - packed: PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>, - ) -> Option { - let operand = packed.index.resolve(&self.func.data); - let lhs = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { - packed.op.0.exec(value as u32, operand.value() as u32) as i32 - }); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); - packed.op.1.cmp(lhs, rhs).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_binop_stack_const_tee_local_jump( - &mut self, - packed: PackedOp128, - ) -> Result, Trap> { - let operand = packed.index.resolve(&self.func.data); - let value = i32::stack_update(&mut self.store.value_stack, |lhs| { - packed.op.exec(lhs as u32, operand.value() as u32) as i32 - }); - i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value); - Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) - } - - #[inline(always)] - fn exec_binop_global_const_jump(&mut self, packed: PackedOp128) -> Option { - let operand = packed.index.resolve(&self.func.data); - let global = self.module.resolve_global_addr(operand.global()); - let value = i32::global_update(&mut self.store.state.globals, global, |value| { - packed.op.exec(value as u32, operand.value() as u32) as i32 - }); - ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_inc_local_jump(&mut self, index: Operand128Idx) -> Option { - let operand = index.resolve(&self.func.data); - let value = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { - value.wrapping_add(operand.value()) - }); - ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_inc_stack_tee_local_jump( - &mut self, - index: Operand128Idx, - ) -> Result, Trap> { - let operand = index.resolve(&self.func.data); - let value = i32::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(operand.value())); - i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value); - Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) - } - - #[inline(always)] - fn exec_inc_global_jump(&mut self, index: Operand128Idx) -> Option { - let operand = index.resolve(&self.func.data); - let global = self.module.resolve_global_addr(operand.global()); - let value = - i32::global_update(&mut self.store.state.globals, global, |value| value.wrapping_add(operand.value())); - ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_inc_local_jump_cmp_local(&mut self, packed: PackedOp128) -> Option { - let operand = packed.index.resolve(&self.func.data); - let lhs = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { - value.wrapping_add(operand.value()) - }); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); - packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_jump_cmp_local_const32(&self, packed: PackedOp128) -> Option { - let operand = packed.index.resolve(&self.func.data); - let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c()); - packed.op.cmp(lhs, operand.b()).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_jump_cmp_local_const64(&self, packed: PackedOp128) -> Option { - let operand = packed.index.resolve(&self.func.data); - let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c()); - packed.op.cmp(lhs, i64::from(operand.b())).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_jump_cmp_local_local32(&self, packed: PackedOp64) -> Option { - let operand = packed.index.resolve(&self.func.data); - let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b()); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c()); - packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) - } - - #[inline(always)] - fn exec_jump_cmp_local_local64(&self, packed: PackedOp64) -> Option { - let operand = packed.index.resolve(&self.func.data); - let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b()); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c()); - packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) - } - - fn exec_i64_add128(&mut self) -> Result<(), Trap> { - let b_hi = i64::stack_pop(&mut self.store.value_stack); - let b_lo = i64::stack_pop(&mut self.store.value_stack); - let a_hi = i64::stack_pop(&mut self.store.value_stack); - let a_lo = i64::stack_pop(&mut self.store.value_stack); - let lo = a_lo.wrapping_add(b_lo); - let carry = u64::from((lo as u64) < (a_lo as u64)); - let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64); - i64::stack_push(&mut self.store.value_stack, lo)?; - i64::stack_push(&mut self.store.value_stack, hi) - } - - fn exec_i64_sub128(&mut self) -> Result<(), Trap> { - let b_hi = i64::stack_pop(&mut self.store.value_stack); - let b_lo = i64::stack_pop(&mut self.store.value_stack); - let a_hi = i64::stack_pop(&mut self.store.value_stack); - let a_lo = i64::stack_pop(&mut self.store.value_stack); - let lo = a_lo.wrapping_sub(b_lo); - let borrow = u64::from((a_lo as u64) < (b_lo as u64)); - let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64); - i64::stack_push(&mut self.store.value_stack, lo)?; - i64::stack_push(&mut self.store.value_stack, hi) - } - - fn exec_i64_mul_wide_s(&mut self) -> Result<(), Trap> { - let rhs = i64::stack_pop(&mut self.store.value_stack); - let lhs = i64::stack_pop(&mut self.store.value_stack); - let product = (lhs as i128).wrapping_mul(rhs as i128); - i64::stack_push(&mut self.store.value_stack, product as i64)?; - i64::stack_push(&mut self.store.value_stack, (product >> 64) as i64) - } - - fn exec_i64_mul_wide_u(&mut self) -> Result<(), Trap> { - let rhs = i64::stack_pop(&mut self.store.value_stack); - let lhs = i64::stack_pop(&mut self.store.value_stack); - let product = (lhs as u64 as u128).wrapping_mul(rhs as u64 as u128); - i64::stack_push(&mut self.store.value_stack, product as u64 as i64)?; - i64::stack_push(&mut self.store.value_stack, (product >> 64) as u64 as i64) - } - - #[inline(always)] - fn exec_simd_extract_lane( - &mut self, - lane: u8, - operation: impl FnOnce(Value128, u8) -> TO, - ) -> Result<(), Trap> { - let vector = Value128::stack_pop(&mut self.store.value_stack); - TO::stack_push(&mut self.store.value_stack, operation(vector, lane)) - } - - #[inline(always)] - fn exec_simd_replace_lane( - &mut self, - lane: u8, - operation: impl FnOnce(VALUE, Value128, u8) -> Value128, - ) -> Result<(), Trap> { - let vector = Value128::stack_pop(&mut self.store.value_stack); - let value = VALUE::stack_pop(&mut self.store.value_stack); - Value128::stack_push(&mut self.store.value_stack, operation(value, vector, lane)) - } - - fn exec_simd_shuffle(&mut self, lanes: Value128) -> Result<(), Trap> { - let rhs = Value128::stack_pop(&mut self.store.value_stack); - let lhs = Value128::stack_pop(&mut self.store.value_stack); - Value128::stack_push(&mut self.store.value_stack, Value128::i8x16_shuffle(lhs, rhs, lanes)) - } - - #[inline(always)] - fn exec_local_set_pop(&mut self, local: LocalAddr) { - let value = T::stack_pop(&mut self.store.value_stack); - T::local_set(&mut self.store.value_stack, &self.cf, local, value); - } - - #[inline(always)] - fn exec_local_tee(&mut self, local: LocalAddr) { - let value = T::stack_peek(&self.store.value_stack); - T::local_set(&mut self.store.value_stack, &self.cf, local, value); - } - - #[inline(always)] - fn exec_global_get(&mut self, global: GlobalAddr) -> Result<(), Trap> { - let addr = self.module.resolve_global_addr(global); - let value = T::global_get(&self.store.state.globals, addr); - T::stack_push(&mut self.store.value_stack, value) - } - - #[inline(always)] - fn exec_global_set(&mut self, global: GlobalAddr) { - let addr = self.module.resolve_global_addr(global); - let value = T::stack_pop(&mut self.store.value_stack); - T::global_set(&mut self.store.state.globals, addr, value); - } - - #[inline(always)] - fn exec_global_tee(&mut self, global: GlobalAddr) { - let addr = self.module.resolve_global_addr(global); - let value = T::stack_peek(&self.store.value_stack); - T::global_set(&mut self.store.state.globals, addr, value); - } - - #[inline(always)] - fn exec_binop_result( - &mut self, - dst: Option, - val: T, - ) -> Result<(), Trap> { - if let Some(dst) = dst { - T::local_set(&mut self.store.value_stack, &self.cf, dst, val); - } - if PUSH { T::stack_push(&mut self.store.value_stack, val) } else { Ok(()) } - } - - #[inline(always)] - fn exec_binop_local_local( - &mut self, - lhs: LocalAddr, - rhs: LocalAddr, - destination: Option, - op: impl BinOpExt, - ) -> Result<(), Trap> { - let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); - let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs); - self.exec_binop_result::(destination, op.exec(lhs, rhs)) - } - - #[inline(always)] - fn exec_binop_local_local_indexed( - &mut self, - index: Operand64Idx<(u16, u16, u16)>, - op: impl BinOpExt, - ) -> Result<(), Trap> { - let operands = index.resolve(&self.func.data); - self.exec_binop_local_local::(operands.a(), operands.b(), Some(operands.c()), op) - } - - #[inline(always)] - fn exec_binop_local_const( - &mut self, - lhs: LocalAddr, - rhs: T, - destination: Option, - op: impl BinOpExt, - ) -> Result<(), Trap> { - let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); - self.exec_binop_result::(destination, op.exec(lhs, rhs)) - } - - #[inline(always)] - fn exec_binop_global_const( - &mut self, - lhs: GlobalAddr, - rhs: T, - op: impl BinOpExt, - ) -> Result<(), Trap> { - let lhs = T::global_get(&self.store.state.globals, self.module.resolve_global_addr(lhs)); - T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs)) - } - - #[inline(always)] - fn exec_cmp_local_local(&mut self, lhs: LocalAddr, rhs: LocalAddr, op: CmpOp) -> Result<(), Trap> - where - T: InternalValue, - CmpOp: CmpOpExt, - { - let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); - let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs); - i32::stack_push(&mut self.store.value_stack, i32::from(op.cmp(lhs, rhs))) - } - - #[inline(always)] - fn exec_binop_stack_global( - &mut self, - global: GlobalAddr, - op: impl BinOpExt, - ) -> Result<(), Trap> { - let addr = self.module.resolve_global_addr(global); - let rhs = T::global_get(&self.store.state.globals, addr); - T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs)); - Ok(()) - } - - #[inline(always)] - fn exec_binop_stack_local( - &mut self, - local: LocalAddr, - destination: Option, - op: impl BinOpExt, - ) -> Result<(), Trap> { - let rhs = T::local_get(&self.store.value_stack, &self.cf, local); - let lhs = T::stack_pop(&mut self.store.value_stack); - self.exec_binop_result::(destination, op.exec(lhs, rhs)) - } - - #[inline(always)] - fn exec_binop_const_tee( - &mut self, - rhs: T, - destination: LocalAddr, - op: impl BinOpExt, - ) -> Result<(), Trap> { - let value = T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs)); - T::local_set(&mut self.store.value_stack, &self.cf, destination, value); - Ok(()) - } - - #[inline(always)] - fn exec_mul_acc_local( - &mut self, - accumulator: LocalAddr, - multiply: fn(T, T) -> T, - add: fn(T, T) -> T, - ) { - let rhs = T::stack_pop(&mut self.store.value_stack); - let lhs = T::stack_pop(&mut self.store.value_stack); - let product = multiply(lhs, rhs); - T::local_update(&mut self.store.value_stack, &self.cf, accumulator, |value| add(product, value)); - } - - fn exec_branch_table(&mut self, index: Operand128Idx) -> usize { - let v = index.resolve(&self.func.data); - let idx = ::stack_pop(&mut self.store.value_stack); - let target_ip = if idx >= 0 && (idx as u32) < v.size() { - self.func.data.branch_table_targets.get((v.start() + idx as u32) as usize).copied().unwrap_or(v.target()) - } else { - v.target() - }; - - target_ip as usize - } - - fn create_exception(&mut self, tag_index: TagAddr) -> Result { - let tag_addr = self.module.resolve_tag_addr(tag_index); - let type_addr = self.store.state.get_tag(tag_addr).type_addr; - let payload_len = self.store.state.get_canonical_func_type(type_addr).params().len(); - self.store.state.gc.check_allocation(payload_len, true)?; - let mut payload = Vec::new(); - cold_err!(payload.try_reserve_exact(payload_len)).map_err(|_| Trap::OutOfMemory)?; - let value_stack = &mut self.store.value_stack; - for index in (0..payload_len).rev() { - let ty = self.store.state.get_canonical_func_type(type_addr).params()[index]; - payload.push(match ty { - WasmType::I32 | WasmType::F32 => RuntimeValue::Value32(Value32::stack_pop(value_stack)), - WasmType::I64 | WasmType::F64 => RuntimeValue::Value64(Value64::stack_pop(value_stack)), - WasmType::V128 => RuntimeValue::Value128(Value128::stack_pop(value_stack)), - WasmType::Ref(_) => RuntimeValue::ValueRef(ValueRef::stack_pop(value_stack)), - }); - } - payload.reverse(); - let roots = (&self.store.value_stack.stack_32).into_iter().copied().map(ValueRef::from_raw); - self.store.state.alloc_exception(tag_addr, payload, roots) - } - - fn exec_throw(&mut self, tag_index: TagAddr, instr_ptr: usize) -> Result> { - let exception = self.create_exception(tag_index)?; - self.throw_exception(exception, instr_ptr) - } - - fn exec_throw_ref(&mut self, instr_ptr: usize) -> Result> { - let exception = ValueRef::stack_pop(&mut self.store.value_stack); - if exception.is_null() { - return Err(Trap::NullReference.into()); - } - self.throw_exception(exception, instr_ptr) - } - - fn throw_exception(&mut self, exception: ValueRef, protected_ip: usize) -> Result> { - match self.dispatch_exception(exception, protected_ip)? { - Some(landing_pad) => Ok(ControlFlow::Continue(landing_pad)), - None => self.store.root_exception(exception).and_then(|exception| Err(Error::Exception(exception))), - } - } - - fn matching_catch(&self, protected_ip: usize, tag_addr: TagAddr) -> Option { - let handlers = &self.func.data.exception_handlers; - let end = handlers.partition_point(|handler| handler.start_ip as usize <= protected_ip); - handlers[..end] - .iter() - .rev() - .filter(|handler| protected_ip < handler.end_ip as usize) - .flat_map(|handler| handler.catches.iter().copied()) - .find(|catch| match catch { - ExceptionCatch::Tag { tag, .. } => self.module.resolve_tag_addr(*tag) == tag_addr, - ExceptionCatch::All { .. } => true, - }) - } - - #[inline(always)] - fn switch_to_frame(&mut self, frame: CallFrame) { - let previous = core::mem::replace(&mut self.cf, frame); - if previous.func_addr == self.cf.func_addr { - return; - } - - let wasm_func = self.store.state.funcs.wasm(self.cf.func_addr); - if !Shared::ptr_eq(&self.func, &wasm_func.func) { - self.func = wasm_func.func.clone(); - } - if wasm_func.owner != self.module.id() { - self.set_module(wasm_func.owner); - } - } - - fn dispatch_exception(&mut self, exception: ValueRef, mut protected_ip: usize) -> Result, Trap> { - let object = self.store.state.gc.get(exception).ok_or(Trap::InvalidReference)?; - let crate::store::GcObjectKind::Exception(tag_addr) = object.kind else { - return Err(Trap::InvalidReference); - }; - loop { - if let Some(catch) = self.matching_catch(protected_ip, tag_addr) { - let (landing_pad, base, with_ref, include_payload) = match catch { - ExceptionCatch::Tag { landing_pad, base, with_ref, .. } => (landing_pad, base, with_ref, true), - ExceptionCatch::All { landing_pad, base, with_ref } => (landing_pad, base, with_ref, false), - }; - let stack_base = self.cf.stack_base(); - let target = interpreter::stack::StackBase { - s32: stack_base.s32 + base.c32 as u32, - s64: stack_base.s64 + base.c64 as u32, - s128: stack_base.s128 + base.c128 as u32, - }; - self.store.value_stack.truncate_to_base(target); - if include_payload { - let Store { state, value_stack, .. } = self.store; - let object = state.gc.get(exception).ok_or(Trap::InvalidReference)?; - for value in object.values.iter().copied() { - value_stack.push_dyn(value)?; - } - } - if with_ref { - ValueRef::stack_push(&mut self.store.value_stack, exception)?; - } - return Ok(Some(landing_pad as usize)); - } - - self.store.value_stack.truncate_to_base(self.cf.locals_base); - let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { - return Ok(None); - }; - self.switch_to_frame(caller); - protected_ip = self.cf.instr_ptr.checked_sub(1).expect("invalid caller IP"); - } - } - - fn exec_call_host( - &mut self, - host_func: HostFunction, - type_addr: TypeAddr, - return_instr_ptr: usize, - ) -> Result> { - if let Some(host_func) = host_func.typed_callback() { - cold_err!(host_func.call_stack(self.store, self.module.id(), type_addr)) - .map_err(|error| Trap::HostFunction(Box::new(error)))?; - if TAIL { - return Ok(self.exec_return()); - } - return Ok(ControlFlow::Continue(return_instr_ptr)); - } - - let (param_count, result_count, base) = { - let ty = self.store.state.get_canonical_func_type(type_addr); - (ty.params().len(), ty.results().len(), self.store.value_stack.base_before(ty.params().iter().collect())) - }; - let module_id = self.module.id(); - self.store - .with_scratch_values(param_count + result_count, |store, values| { - let host_values = store.stack_value_iter(type_addr, crate::store::FuncValueTypes::Params, base)?; - for (slot, value) in values[..param_count].iter_mut().zip(host_values) { - *slot = value; - } - store.value_stack.truncate_to_base(base); - let (params, results) = values.split_at_mut(param_count); - host_func - .call_values(store, module_id, type_addr, params, results) - .map_err(|error| Error::Trap(Trap::HostFunction(Box::new(error))))?; - store.push_wasm_values(results) - }) - .map_err(|error| match error { - Error::Trap(trap) => trap, - other => Trap::HostFunction(Box::new(other)), - })?; - if TAIL { Ok(self.exec_return()) } else { Ok(ControlFlow::Continue(return_instr_ptr)) } - } - - fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> Result> { - self.charge_call_fuel(FUEL_COST_CALL_TOTAL); - let addr = self.module.resolve_func_addr(v); - if self.store.state.funcs.is_host(addr) { - let host_func = self.store.state.funcs.host(addr); - let type_addr = host_func.type_addr; - let host_func = host_func.func.clone(); - self.exec_call_host::(host_func, type_addr, return_instr_ptr) - } else { - let wasm_func = self.store.state.funcs.wasm(addr); - let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals) - else { - return cold!(Err(Trap::CallStackOverflow.into())); - }; - - self.store.call_stack.push(self.cf, return_instr_ptr)?; - self.cf = CallFrame::new(addr, locals_base, wasm_func.func.locals); - if !Shared::ptr_eq(&self.func, &wasm_func.func) { - self.func = wasm_func.func.clone(); - } - if wasm_func.owner != self.module.id() { - self.set_module(wasm_func.owner); - } - Ok(ControlFlow::Continue(0)) - } - } - - fn exec_return_call_direct(&mut self, v: u32) -> Result> { - self.charge_call_fuel(FUEL_COST_CALL_TOTAL); - let addr = self.module.resolve_func_addr(v); - if self.store.state.funcs.is_host(addr) { - let host_func = self.store.state.funcs.host(addr); - let type_addr = host_func.type_addr; - let host_func = host_func.func.clone(); - self.exec_call_host::(host_func, type_addr, 0) - } else { - let wasm_func = self.store.state.funcs.wasm(addr); - let (params, locals, owner, next_func) = { - let next_func = (!Shared::ptr_eq(&self.func, &wasm_func.func)).then(|| wasm_func.func.clone()); - (wasm_func.func.params, wasm_func.func.locals, wasm_func.owner, next_func) - }; - self.store.value_stack.truncate_keep_counts(self.cf.locals_base, params); - let Ok(locals_base) = self.store.value_stack.enter_locals(¶ms, &locals) else { - return cold!(Err(Trap::CallStackOverflow.into())); - }; - self.cf = CallFrame::new(addr, locals_base, locals); - if let Some(next_func) = next_func { - self.func = next_func; - } - if owner != self.module.id() { - self.set_module(owner); - } - Ok(ControlFlow::Continue(0)) - } - } - - fn exec_call_self(&mut self, return_instr_ptr: usize) -> Result> { - self.charge_call_fuel(FUEL_COST_CALL_TOTAL); - let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else { - return cold!(Err(Trap::CallStackOverflow.into())); - }; - let new = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); - self.store.call_stack.push(core::mem::replace(&mut self.cf, new), return_instr_ptr)?; - Ok(ControlFlow::Continue(0)) - } - - fn exec_return_call_self(&mut self) -> Result> { - self.charge_call_fuel(FUEL_COST_CALL_TOTAL); - - self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.params); - let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else { - return cold!(Err(Trap::CallStackOverflow.into())); - }; - self.cf = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); - Ok(ControlFlow::Continue(0)) - } - - fn exec_call_indirect( - &mut self, - index: Operand64Idx<(u32, u32)>, - return_instr_ptr: usize, - ) -> Result> { - let operand = index.resolve(&self.func.data); - let type_addr = operand.a(); - let table_addr = operand.b(); - self.charge_call_fuel(FUEL_COST_CALL_TOTAL); - // verify that the table is of the right type, this should be validated by the parser already - let table_addr = self.module.resolve_table_addr(table_addr); - let table_idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; - let table = self.store.state.get_table(table_addr); - - let Ok(table) = table.get(table_idx) else { - return cold!(Err(Trap::UndefinedElement { index: table_idx }.into())); - }; - - let Some(func_ref) = table.addr() else { - return cold!(Err(Trap::UninitializedElement { index: table_idx }.into())); - }; - - self.exec_typed_call::(func_ref, self.module.resolve_type_addr(type_addr), return_instr_ptr) - } - - fn exec_typed_call( - &mut self, - func_addr: FuncAddr, - expected_type_addr: TypeAddr, - return_instr_ptr: usize, - ) -> Result> { - if self.store.state.funcs.is_host(func_addr) { - let host_func = self.store.state.funcs.host(func_addr); - let type_addr = host_func.type_addr; - if !self.store.state.type_addr_is_subtype(type_addr, expected_type_addr) { - return cold!(Err(Trap::IndirectCallTypeMismatch { - actual: Box::new(self.store.state.get_canonical_func_type(type_addr).clone()), - expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), - } - .into())); - } - let host_func = host_func.func.clone(); - return self.exec_call_host::(host_func, type_addr, return_instr_ptr); - } - - let wasm_func = self.store.state.funcs.wasm(func_addr); - let type_addr = wasm_func.type_addr; - if !self.store.state.type_addr_is_subtype(type_addr, expected_type_addr) { - return cold!(Err(Trap::IndirectCallTypeMismatch { - actual: Box::new(self.store.state.get_canonical_func_type(type_addr).clone()), - expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), - } - .into())); - } - let (params, locals, owner, next_func) = { - let next_func = (!Shared::ptr_eq(&self.func, &wasm_func.func)).then(|| wasm_func.func.clone()); - (wasm_func.func.params, wasm_func.func.locals, wasm_func.owner, next_func) - }; - let locals_base = if IS_RETURN_CALL { - self.store.value_stack.truncate_keep_counts(self.cf.locals_base, params); - self.store.value_stack.enter_locals(¶ms, &locals) - } else { - self.store.value_stack.enter_locals(¶ms, &locals) - }?; - if IS_RETURN_CALL { - self.cf = CallFrame::new(func_addr, locals_base, locals); - } else { - self.store.call_stack.push(self.cf, return_instr_ptr)?; - self.cf = CallFrame::new(func_addr, locals_base, locals); - } - if let Some(next_func) = next_func { - self.func = next_func; - } - if owner != self.module.id() { - self.set_module(owner); - } - Ok(ControlFlow::Continue(0)) - } - - fn exec_call_ref( - &mut self, - type_addr: u32, - return_instr_ptr: usize, - ) -> Result> { - self.charge_call_fuel(FUEL_COST_CALL_TOTAL); - let func_ref = ValueRef::stack_pop(&mut self.store.value_stack); - let Some(func_addr) = func_ref.addr() else { - return cold!(Err(Trap::NullFunctionReference.into())); - }; - - self.exec_typed_call::(func_addr, self.module.resolve_type_addr(type_addr), return_instr_ptr) - } - - fn exec_return(&mut self) -> ControlFlow<(), usize> { - self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.results); - self.finish_return() - } - - #[inline(always)] - fn finish_return(&mut self) -> ControlFlow<(), usize> { - let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { - return ControlFlow::Break(()); - }; - let instr_ptr = caller.instr_ptr; - if caller.func_addr == self.cf.func_addr { - self.cf = caller; - } else { - self.switch_to_frame(caller); - } - ControlFlow::Continue(instr_ptr) - } - - fn exec_return_void(&mut self) -> ControlFlow<(), usize> { - self.store.value_stack.truncate_to_base(self.cf.locals_base); - self.finish_return() - } - - fn exec_return_32(&mut self) -> ControlFlow<(), usize> { - self.store.value_stack.stack_32.truncate_to_one_tail(self.cf.locals_base.s32 as usize); - self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize); - self.store.value_stack.stack_128.truncate_to(self.cf.locals_base.s128 as usize); - self.finish_return() - } - - fn exec_return_64(&mut self) -> ControlFlow<(), usize> { - self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize); - self.store.value_stack.stack_64.truncate_to_one_tail(self.cf.locals_base.s64 as usize); - self.store.value_stack.stack_128.truncate_to(self.cf.locals_base.s128 as usize); - self.finish_return() - } - - fn exec_return_128(&mut self) -> ControlFlow<(), usize> { - self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize); - self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize); - self.store.value_stack.stack_128.truncate_to_one_tail(self.cf.locals_base.s128 as usize); - self.finish_return() - } - - fn exec_store_local_local, const N: usize>( - &mut self, - index: Operand64Idx, - addr_local: u8, - value_local: u8, - ) -> Result<(), Trap> { - let memarg = index.resolve(&self.func.data); - let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local)); - let mem_addr = self.mem_addr(MemAddr::from(memarg.memory())); - let mem = self.store.state.get_mem_mut(mem_addr); - let addr = if mem.is_64bit() { - let base = u64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); - let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds { - offset: usize::MAX, - len: N, - max: mem.inner.len(), - }))?; - cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))? - } else { - let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); - cold_err!(mem.effective_addr::(base as usize, u64::from(memarg.offset())))? - }; - value.store_at(&mut mem.inner, addr) - } - - fn exec_inc_memory_local, const N: usize>( - &mut self, - index: Operand64Idx, - addr_local: u8, - increment: impl FnOnce(T) -> T, - ) -> Result<(), Trap> { - let memarg = index.resolve(&self.func.data); - let mem_addr = self.mem_addr(MemAddr::from(memarg.memory())); - let mem = self.store.state.get_mem_mut(mem_addr); - let addr = if mem.is_64bit() { - let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; - let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds { - offset: usize::MAX, - len: N, - max: mem.inner.len(), - }))?; - cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))? - } else { - let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); - cold_err!(mem.effective_addr::(base as usize, u64::from(memarg.offset())))? - }; - - let value = cold_err!(T::load_at(&mem.inner, addr))?; - increment(value).store_at(&mut mem.inner, addr) - } - - fn exec_fma_store< - T: InternalValue + MemValue + core::ops::Add + core::ops::Mul, - const N: usize, - >( - &mut self, - m: CompactMemoryArg, - ) -> Result<(), Trap> { - let rhs = T::stack_pop(&mut self.store.value_stack); - let lhs = T::stack_pop(&mut self.store.value_stack); - let acc = T::stack_pop(&mut self.store.value_stack); - let fma = acc + lhs * rhs; - let mem_addr = self.mem_addr(m.mem_addr()); - let mem = self.store.state.get_mem_mut(mem_addr); - let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; - cold_err!(fma.store_at(&mut mem.inner, addr)) - } - - fn exec_load_local< - LOAD: MemValue, - const N: usize, - TARGET: InternalValue, - const SET_LOCAL: bool, - const TEE: bool, - >( - &mut self, - index: Operand64Idx, - addr_local: u8, - dst_local: u8, - cast: impl Fn(LOAD) -> TARGET, - ) -> Result<(), Trap> { - let memarg = index.resolve(&self.func.data); - - let mem = self.store.state.get_mem(self.mem_addr(MemAddr::from(memarg.memory()))); - let base = if mem.is_64bit() { - let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; - cold_err!(usize::try_from(base)).map_err(|_| Trap::MemoryOutOfBounds { - offset: usize::MAX, - len: N, - max: mem.inner.len(), - })? - } else { - u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as usize - }; - - let addr = cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))?; - let value = cast(cold_err!(LOAD::load_at(&mem.inner, addr))?); - - if SET_LOCAL { - TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value); - } - if !SET_LOCAL || TEE { - TARGET::stack_push(&mut self.store.value_stack, value)?; - } - Ok(()) - } - - fn exec_ref_is_null(&mut self) -> Result<(), Trap> { - let is_null = i32::from(ValueRef::stack_pop(&mut self.store.value_stack).is_null()); - i32::stack_push(&mut self.store.value_stack, is_null) - } - - fn exec_ref_as_non_null(&mut self) -> Result<(), Trap> { - if ValueRef::stack_peek(&self.store.value_stack).is_null() { - return cold!(Err(Trap::NullReference)); - } - Ok(()) - } - - fn canonical_ref_type(&self, ty: RefType) -> RefType { - let Some(type_index) = ty.type_index() else { return ty }; - RefType::new_concrete(ty.is_nullable(), self.module.resolve_type_addr(type_index)) - } - - fn exec_ref_matches(&self, ty: RefType) -> bool { - let value = ValueRef::stack_peek(&self.store.value_stack); - self.store.state.value_ref_matches(value, self.canonical_ref_type(ty)) - } - - fn exec_ref_test(&mut self, ty: RefType) -> Result<(), Trap> { - let value = ValueRef::stack_pop(&mut self.store.value_stack); - let matches = self.store.state.value_ref_matches(value, self.canonical_ref_type(ty)); - i32::stack_push(&mut self.store.value_stack, i32::from(matches)) - } - - fn exec_ref_cast(&self, ty: RefType) -> Result<(), Trap> { - if !self.exec_ref_matches(ty) { - return cold!(Err(Trap::CastFailure)); - } - Ok(()) - } - - fn exec_i31_get(&mut self, signed: bool) -> Result<(), Trap> { - let value = ValueRef::stack_pop(&mut self.store.value_stack); - if value.is_null() { - return cold!(Err(Trap::NullI31Reference)); - } - let value = if signed { - value.i31_s().expect("validated i31.get operand") - } else { - value.i31_u().expect("validated i31.get operand") as i32 - }; - i32::stack_push(&mut self.store.value_stack, value) - } - - fn push_gc_object(&mut self, type_addr: TypeAddr, values: Vec) -> Result<(), Trap> { - let roots = (&self.store.value_stack.stack_32).into_iter().copied().map(ValueRef::from_raw); - let reference = self.store.state.alloc_gc_object(type_addr, values, roots)?; - ValueRef::stack_push(&mut self.store.value_stack, reference) - } - - fn exec_struct_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> { - let type_addr = self.module.resolve_type_addr(type_index); - let field_count = - self.store.state.get_type(type_addr).as_struct().expect("validated struct.new type").fields.len(); - self.store.state.check_gc_allocation(type_addr, field_count)?; - let mut values = Vec::new(); - cold_err!(values.try_reserve_exact(field_count)).map_err(|_| Trap::OutOfMemory)?; - if default { - values.extend( - self.store - .state - .get_type(type_addr) - .as_struct() - .expect("validated struct.new type") - .fields - .iter() - .map(|field| default_value(field.storage)), - ); - } else { - for index in (0..field_count).rev() { - let storage = self.store.state.get_type(type_addr).as_struct().unwrap().fields[index].storage; - values.push(pop_value(&mut self.store.value_stack, storage)); - } - values.reverse(); - } - self.push_gc_object(type_addr, values) - } - - fn exec_struct_get(&mut self, index: Operand64Idx<(u32, u32)>, signed: Option) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let type_index = operand.a(); - let field_index = operand.b(); - let reference = ValueRef::stack_pop(&mut self.store.value_stack); - let type_addr = self.module.resolve_type_addr(type_index); - let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.get type").fields - [field_index as usize] - .storage; - let object = self.store.state.gc_object(reference, type_addr)?; - let object = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; - let value = *object.values.get(field_index as usize).expect("validated struct field index"); - push_value(&mut self.store.value_stack, value, storage, signed) - } - - fn exec_struct_set(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let type_index = operand.a(); - let field_index = operand.b(); - let type_addr = self.module.resolve_type_addr(type_index); - let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.set type").fields - [field_index as usize] - .storage; - let value = pop_value(&mut self.store.value_stack, storage); - let reference = ValueRef::stack_pop(&mut self.store.value_stack); - let object = self.store.state.gc_object(reference, type_addr)?; - self.store.state.gc.set(object, field_index as usize, value).expect("live struct field"); - Ok(()) - } - - fn exec_array_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> { - let type_addr = self.module.resolve_type_addr(type_index); - let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new type").field.storage; - let len = u32::stack_pop(&mut self.store.value_stack) as usize; - self.store.state.check_gc_allocation(type_addr, len)?; - let value = if default { default_value(storage) } else { pop_value(&mut self.store.value_stack, storage) }; - let mut values = Vec::new(); - cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; - values.resize(len, value); - self.push_gc_object(type_addr, values) - } - - fn exec_array_new_fixed(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let type_index = operand.a(); - let len = operand.b(); - let type_addr = self.module.resolve_type_addr(type_index); - let storage = - self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; - let len = len as usize; - self.store.state.check_gc_allocation(type_addr, len)?; - let mut values = Vec::new(); - cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; - for _ in 0..len { - values.push(pop_value(&mut self.store.value_stack, storage)); - } - values.reverse(); - self.push_gc_object(type_addr, values) - } - - fn exec_array_get(&mut self, type_index: TypeAddr, signed: Option) -> Result<(), Trap> { - let index = u32::stack_pop(&mut self.store.value_stack) as usize; - let reference = ValueRef::stack_pop(&mut self.store.value_stack); - let type_addr = self.module.resolve_type_addr(type_index); - let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.get type").field.storage; - let object = self.store.state.gc_object(reference, type_addr)?; - let object = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; - let value = *object.values.get(index).ok_or(Trap::ArrayOutOfBounds)?; - push_value(&mut self.store.value_stack, value, storage, signed) - } - - fn exec_array_set(&mut self, type_index: TypeAddr) -> Result<(), Trap> { - let type_addr = self.module.resolve_type_addr(type_index); - let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.set type").field.storage; - let value = pop_value(&mut self.store.value_stack, storage); - let index = u32::stack_pop(&mut self.store.value_stack) as usize; - let reference = ValueRef::stack_pop(&mut self.store.value_stack); - let object = self.store.state.gc_object(reference, type_addr)?; - self.store.state.gc.set(object, index, value).ok_or(Trap::ArrayOutOfBounds) - } - - fn exec_array_len(&mut self) -> Result<(), Trap> { - let reference = ValueRef::stack_pop(&mut self.store.value_stack); - if reference.is_null() { - return Err(Trap::NullArrayReference); - } - let object = self.store.state.gc.get(reference).ok_or(Trap::Other("invalid GC reference"))?; - let crate::store::GcObjectKind::Composite(type_addr) = object.kind else { - return Err(Trap::Other("GC reference is not an array")); - }; - if self.store.state.get_type(type_addr).as_array().is_none() { - return Err(Trap::Other("GC reference is not an array")); - } - i32::stack_push(&mut self.store.value_stack, object.values.len() as i32) - } - - fn exec_array_fill(&mut self, type_index: TypeAddr) -> Result<(), Trap> { - let type_addr = self.module.resolve_type_addr(type_index); - let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.fill type").field.storage; - let len = u32::stack_pop(&mut self.store.value_stack) as usize; - let value = pop_value(&mut self.store.value_stack, storage); - let index = u32::stack_pop(&mut self.store.value_stack) as usize; - let reference = ValueRef::stack_pop(&mut self.store.value_stack); - let object = self.store.state.gc_object(reference, type_addr)?; - let object_ref = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; - let end = index.checked_add(len).filter(|end| *end <= object_ref.values.len()).ok_or(Trap::ArrayOutOfBounds)?; - self.store.state.gc.fill(object, index..end, value).expect("live array range"); - Ok(()) - } - - fn exec_array_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let dst_type = operand.a(); - let src_type = operand.b(); - let len = u32::stack_pop(&mut self.store.value_stack) as usize; - let src_index = u32::stack_pop(&mut self.store.value_stack) as usize; - let src = ValueRef::stack_pop(&mut self.store.value_stack); - let dst_index = u32::stack_pop(&mut self.store.value_stack) as usize; - let dst = ValueRef::stack_pop(&mut self.store.value_stack); - let dst_type = self.module.resolve_type_addr(dst_type); - let src_type = self.module.resolve_type_addr(src_type); - let dst_handle = self.store.state.gc_object(dst, dst_type)?; - let dst_len = self.store.state.gc.get_handle(dst_handle).expect("validated array").values.len(); - let src_handle = self.store.state.gc_object(src, src_type)?; - let src_object = self.store.state.gc.get_handle(src_handle).expect("validated array"); - let src_end = - src_index.checked_add(len).filter(|end| *end <= src_object.values.len()).ok_or(Trap::ArrayOutOfBounds)?; - dst_index.checked_add(len).filter(|end| *end <= dst_len).ok_or(Trap::ArrayOutOfBounds)?; - if src_handle == dst_handle { - self.store.state.gc.copy_within(dst_handle, src_index..src_end, dst_index).expect("live array range"); - return Ok(()); - } - self.store - .state - .gc - .copy_between(src_handle, src_index..src_end, dst_handle, dst_index) - .expect("live array ranges"); - Ok(()) - } - - fn exec_array_new_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let type_index = operand.a(); - let data_index = operand.b(); - let len = u32::stack_pop(&mut self.store.value_stack) as usize; - let src = u32::stack_pop(&mut self.store.value_stack) as usize; - let type_addr = self.module.resolve_type_addr(type_index); - let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage; - let data_addr = self.module.resolve_data_addr(data_index); - let data = self.store.state.data[data_addr as usize].data.as_deref().unwrap_or(&[]); - data_range(storage, data, src, len)?; - self.store.state.check_gc_allocation(type_addr, len)?; - let values = decode_data(storage, data, src, len)?; - self.push_gc_object(type_addr, values) - } - - fn exec_array_new_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let type_index = operand.a(); - let elem_index = operand.b(); - let len = u32::stack_pop(&mut self.store.value_stack) as usize; - let src = u32::stack_pop(&mut self.store.value_stack) as usize; - let type_addr = self.module.resolve_type_addr(type_index); - let elem_addr = self.module.resolve_elem_addr(elem_index); - let items = self.store.state.elements[elem_addr as usize].items_range(src, len)?; - self.store.state.check_gc_allocation(type_addr, len)?; - let mut values = Vec::new(); - cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; - values.extend(items.iter().copied().map(RuntimeValue::ValueRef)); - self.push_gc_object(type_addr, values) - } - - fn exec_array_init_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let type_index = operand.a(); - let data_index = operand.b(); - let len = u32::stack_pop(&mut self.store.value_stack) as usize; - let src = u32::stack_pop(&mut self.store.value_stack) as usize; - let dst = u32::stack_pop(&mut self.store.value_stack) as usize; - let reference = ValueRef::stack_pop(&mut self.store.value_stack); - let type_addr = self.module.resolve_type_addr(type_index); - let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage; - let object = self.store.state.gc_object(reference, type_addr)?; - let object_len = self.store.state.gc.get_handle(object).expect("validated array").values.len(); - dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; - let data = - self.store.state.data[self.module.resolve_data_addr(data_index) as usize].data.as_deref().unwrap_or(&[]); - let values = decode_data(storage, data, src, len)?; - self.store.state.gc.set_slice(object, dst, &values).expect("live array range"); - Ok(()) - } - - fn exec_array_init_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let type_index = operand.a(); - let elem_index = operand.b(); - let len = u32::stack_pop(&mut self.store.value_stack) as usize; - let src = u32::stack_pop(&mut self.store.value_stack) as usize; - let dst = u32::stack_pop(&mut self.store.value_stack) as usize; - let reference = ValueRef::stack_pop(&mut self.store.value_stack); - let type_addr = self.module.resolve_type_addr(type_index); - let object = self.store.state.gc_object(reference, type_addr)?; - let object_len = self.store.state.gc.get_handle(object).expect("validated array").values.len(); - dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; - let items = - self.store.state.elements[self.module.resolve_elem_addr(elem_index) as usize].items_range(src, len)?; - let mut values = Vec::new(); - cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; - values.extend(items.iter().copied().map(RuntimeValue::ValueRef)); - self.store.state.gc.set_slice(object, dst, &values).expect("live array range"); - Ok(()) - } - - fn exec_memory_size(&mut self, addr: u32) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.mem_addr(addr)); - match mem.is_64bit() { - true => i64::stack_push(&mut self.store.value_stack, mem.page_count as i64), - false => i32::stack_push(&mut self.store.value_stack, mem.page_count as i32), - } - } - - fn exec_memory_grow(&mut self, addr: u32) -> Result<(), Trap> { - let mem_addr = self.mem_addr(addr); - let limiter = self.store.engine.config().resource_limiter.as_deref(); - let mem = self.store.state.get_mem_mut(mem_addr); - let is_64bit = mem.is_64bit(); - let pages_delta = match is_64bit { - true => i64::stack_pop(&mut self.store.value_stack), - false => i64::from(i32::stack_pop(&mut self.store.value_stack)), - }; - - let size = mem.grow(pages_delta, limiter)?.unwrap_or(-1); - match is_64bit { - true => i64::stack_push(&mut self.store.value_stack, size)?, - false => i32::stack_push(&mut self.store.value_stack, size as i32)?, - }; - - Ok(()) - } - - fn exec_memory_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let dst_mem = operand.a(); - let src_mem = operand.b(); - let dst_mem_addr = self.mem_addr(dst_mem); - let src_mem_addr = self.mem_addr(src_mem); - let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch(); - let src_arch = self.store.state.get_mem(src_mem_addr).kind.arch(); - let len_arch = - if dst_arch == MemoryArch::I32 || src_arch == MemoryArch::I32 { MemoryArch::I32 } else { MemoryArch::I64 }; - let size = self.store.value_stack.pop_memory_operand(len_arch)?; - let src = self.store.value_stack.pop_memory_operand(src_arch)?; - let dst = self.store.value_stack.pop_memory_operand(dst_arch)?; - - if dst_mem_addr == src_mem_addr { - // copy within the same memory - let mem = self.store.state.get_mem_mut(dst_mem_addr); - mem.copy_within(dst, src, size)?; - } else { - // copy between two memories - let (dst_memory, src_memory) = self.store.state.get_mems_mut(dst_mem_addr, src_mem_addr); - dst_memory.copy_from_memory(dst, src_memory, src, size)?; - } - Ok(()) - } - - fn exec_memory_fill(&mut self, addr: u32) -> Result<(), Trap> { - let mem_addr = self.mem_addr(addr); - let arch = self.store.state.get_mem(mem_addr).kind.arch(); - let size = self.store.value_stack.pop_memory_operand(arch)?; - let val = i32::stack_pop(&mut self.store.value_stack); - let dst = self.store.value_stack.pop_memory_operand(arch)?; - self.exec_memory_fill_impl(mem_addr, dst, val as u8, size) - } - - fn exec_memory_fill_const(&mut self, index: Operand128Idx) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let mem_addr = self.mem_addr(operand.memory()); - let arch = self.store.state.get_mem(mem_addr).kind.arch(); - let dst = self.store.value_stack.pop_memory_operand(arch)?; - self.exec_memory_fill_impl(mem_addr, dst, operand.byte(), operand.value() as u32 as usize) - } - - fn exec_memory_fill_impl(&mut self, mem_addr: MemAddr, dst: usize, val: u8, size: usize) -> Result<(), Trap> { - let mem = self.store.state.get_mem_mut(mem_addr); - let max = mem.inner.len(); - if mem.inner.fill(dst, size, val).is_none() { - return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max })); - } - Ok(()) - } - - fn exec_memory_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let data_index = operand.a(); - let mem_index = operand.b(); - let size = u32::stack_pop(&mut self.store.value_stack) as usize; - let offset = u32::stack_pop(&mut self.store.value_stack) as usize; - let mem_addr = self.mem_addr(mem_index); - let arch = self.store.state.get_mem(mem_addr).kind.arch(); - let dst = self.store.value_stack.pop_memory_operand(arch)?; - - let data = &self.store.state.data[self.module.resolve_data_addr(data_index) as usize]; - let mem = &mut self.store.state.memories[mem_addr as usize]; - let data_len = data.data.as_ref().map_or(0, |d| d.len()); - let mem_len = mem.inner.len(); - if offset.checked_add(size).is_none_or(|end| end > data_len) { - return cold!(Err(Trap::MemoryOutOfBounds { offset, len: size, max: data_len })); - } - if dst.checked_add(size).is_none_or(|end| end > mem_len) { - return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max: mem_len })); - } - - if size == 0 { - return Ok(()); - } - - let Some(data) = &data.data else { - return cold!(Err(Trap::MemoryOutOfBounds { offset: 0, len: 0, max: 0 })); - }; - - if mem.inner.write_all(dst, &data[offset..offset + size]).is_none() { - return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max: mem_len })); - } - Ok(()) - } - - fn exec_table_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let dst_table = operand.a(); - let src_table = operand.b(); - let dst_table_addr = self.module.resolve_table_addr(dst_table); - let src_table_addr = self.module.resolve_table_addr(src_table); - let dst_arch = self.store.state.get_table(dst_table_addr).kind.arch(); - let src_arch = self.store.state.get_table(src_table_addr).kind.arch(); - let len_arch = - if dst_arch == MemoryArch::I32 || src_arch == MemoryArch::I32 { MemoryArch::I32 } else { MemoryArch::I64 }; - let size = self.pop_table_operand(len_arch)?; - let src = self.pop_table_operand(src_arch)?; - let dst = self.pop_table_operand(dst_arch)?; - - if dst_table_addr == src_table_addr { - // copy within the same table - self.store.state.get_table_mut(dst_table_addr).copy_within(dst, src, size) - } else { - // copy between two tables - let (dst_table_ref, src_table_ref) = self.store.state.get_tables_mut(dst_table_addr, src_table_addr); - dst_table_ref.copy_from_slice(dst, src_table_ref.load(src, size)?) - } - } - - fn exec_mem_load_lane, const LOAD_SIZE: usize>( - &mut self, - arg: MemoryLaneArg, - ) -> Result<(), Trap> { - let m = arg.memory_arg_idx.resolve(&self.func.data); - let mem = self.store.state.get_mem(self.mem_addr(m.memory())); - let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; - let val = cold_err!(LOAD::load_at(&mem.inner, addr))?; - let offset = arg.lane as usize * LOAD_SIZE; - Value128::stack_update(&mut self.store.value_stack, |value| { - let mut bytes = value.to_mem_bytes(); - bytes[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); - Value128(bytes) - }); - Ok(()) - } - - #[inline(always)] - fn exec_mem_load, const LOAD_SIZE: usize, TARGET: InternalValue>( - &mut self, - m: Operand128, - cast: impl Fn(LOAD) -> TARGET, - ) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.mem_addr(m.memory())); - let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; - let value = cold_err!(LOAD::load_at(&mem.inner, addr))?; - TARGET::stack_push(&mut self.store.value_stack, cast(value)) - } - - #[inline(always)] - fn exec_mem_store_lane + Copy, const N: usize>(&mut self, arg: MemoryLaneArg) -> Result<(), Trap> { - let bytes = Value128::stack_pop(&mut self.store.value_stack).to_mem_bytes(); - let lane_offset = arg.lane as usize * N; - let mut val_bytes = [0u8; N]; - val_bytes.copy_from_slice(&bytes[lane_offset..lane_offset + N]); - let val = U::from_mem_bytes(val_bytes); - let m = arg.memory_arg_idx.resolve(&self.func.data); - let mem_addr = self.mem_addr(m.memory()); - let mem = self.store.state.get_mem_mut(mem_addr); - let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; - cold_err!(val.store_at(&mut mem.inner, addr))?; - Ok(()) - } - - #[inline(always)] - fn exec_mem_store, const N: usize>( - &mut self, - memory: Operand128, - cast: impl Fn(T) -> U, - ) -> Result<(), Trap> { - let val = cast(::stack_pop(&mut self.store.value_stack)); - self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), val) - } - - #[inline(always)] - fn exec_select_store, const N: usize>( - &mut self, - memory: Operand128, - ) -> Result<(), Trap> { - let condition = Value32::stack_pop(&mut self.store.value_stack); - let false_value = T::stack_pop(&mut self.store.value_stack); - let true_value = T::stack_pop(&mut self.store.value_stack); - let value = if condition == 0 { false_value } else { true_value }; - self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), value) - } - - #[inline(always)] - fn exec_mem_store_value, const N: usize>( - &mut self, - memory_addr: MemAddr, - offset: u64, - val: U, - ) -> Result<(), Trap> { - let mem = self.store.state.get_mem_mut(memory_addr); - let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = cold_err!(mem.effective_addr::(base, offset))?; - cold_err!(val.store_at(&mut mem.inner, addr)) - } - - fn exec_table_get(&mut self, table_index: u32) -> Result<(), Trap> { - let table_addr = self.module.resolve_table_addr(table_index); - let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; - let value = *self.store.state.get_table(table_addr).get(idx)?; - ValueRef::stack_push(&mut self.store.value_stack, value) - } - - fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> { - let val = ValueRef::stack_pop(&mut self.store.value_stack); - let table_addr = self.module.resolve_table_addr(table_index); - let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; - let table = self.store.state.get_table_mut(table_addr); - table.set(idx, val) - } - - fn exec_table_size(&mut self, table_index: u32) -> Result<(), Trap> { - let table = self.store.state.get_table(self.module.resolve_table_addr(table_index)); - match table.kind.arch() { - MemoryArch::I32 => i32::stack_push(&mut self.store.value_stack, table.size() as i32), - MemoryArch::I64 => i64::stack_push(&mut self.store.value_stack, table.size() as i64), - } - } - - fn exec_table_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { - let operand = index.resolve(&self.func.data); - let elem_index = operand.a(); - let table_index = operand.b(); - let size = self.pop_table_operand(MemoryArch::I32)?; // n - let offset = self.pop_table_operand(MemoryArch::I32)?; // s - let table_addr = self.module.resolve_table_addr(table_index); - let dst = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; // d - let elem_addr = self.module.resolve_elem_addr(elem_index) as usize; - let elem = self.store.state.elements.get(elem_addr).ok_or_else(|| Trap::Other("element not found"))?; - let items = elem.items_range(offset, size)?; - - let table = - self.store.state.tables.get_mut(table_addr as usize).ok_or_else(|| Trap::Other("table not found"))?; - table.init(dst, items) - } - - fn exec_table_grow(&mut self, table_index: u32) -> Result<(), Trap> { - let table_addr = self.module.resolve_table_addr(table_index); - let arch = self.store.state.get_table(table_addr).kind.arch(); - let n = self.pop_table_operand(arch)?; - let val = ValueRef::stack_pop(&mut self.store.value_stack); - let limiter = self.store.engine.config().resource_limiter.as_deref(); - let table = self.store.state.get_table_mut(table_addr); - let sz = table.size(); - let grew = table.grow(n, val, limiter)?; - match (arch, grew) { - (MemoryArch::I32, true) => i32::stack_push(&mut self.store.value_stack, sz as i32), - (MemoryArch::I32, false) => i32::stack_push(&mut self.store.value_stack, -1), - (MemoryArch::I64, true) => i64::stack_push(&mut self.store.value_stack, sz as i64), - (MemoryArch::I64, false) => i64::stack_push(&mut self.store.value_stack, -1), - } - } - - fn exec_table_fill(&mut self, table_index: u32) -> Result<(), Trap> { - let table_addr = self.module.resolve_table_addr(table_index); - let arch = self.store.state.get_table(table_addr).kind.arch(); - let n = self.pop_table_operand(arch)?; - let val = ValueRef::stack_pop(&mut self.store.value_stack); - let i = self.pop_table_operand(arch)?; - self.store.state.get_table_mut(table_addr).fill(i, n, val) - } - - fn pop_table_operand(&mut self, arch: MemoryArch) -> Result { - let value = match arch { - MemoryArch::I32 => i32::stack_pop(&mut self.store.value_stack) as u32 as u64, - MemoryArch::I64 => i64::stack_pop(&mut self.store.value_stack) as u64, - }; - cold_err!(usize::try_from(value).map_err(|_| Trap::TableOutOfBounds { - offset: usize::MAX, - len: 1, - max: usize::MAX, - })) - } -} - -impl<'store> Executor<'store, false> { - #[inline(always)] - pub(crate) fn run_to_completion(mut self) -> Result<()> { - let mut instr_ptr = self.cf.instr_ptr; - loop { - match self.exec(instr_ptr)? { - ControlFlow::Continue(next_instr_ptr) => instr_ptr = next_instr_ptr, - ControlFlow::Break(()) => return cold!(Ok(())), - } - } - } - - #[cfg(feature = "std")] - #[inline(always)] - pub(crate) fn run_with_time_budget(mut self, time_budget: core::time::Duration) -> Result { - use crate::std::time::Instant; - let start = Instant::now(); - if time_budget.is_zero() { - return Ok(ExecState::Suspended(self.cf)); - } - - let mut instr_ptr = self.cf.instr_ptr; - loop { - for _ in 0..128 { - match self.exec(instr_ptr)? { - ControlFlow::Continue(next_instr_ptr) => instr_ptr = next_instr_ptr, - ControlFlow::Break(()) => return Ok(ExecState::Completed), - } - } - - if start.elapsed() >= time_budget { - self.cf.instr_ptr = instr_ptr; - return Ok(ExecState::Suspended(self.cf)); - } - } - } -} - -impl<'store> Executor<'store, true> { - #[inline(always)] - pub(crate) fn run_with_fuel(mut self, fuel: u32) -> Result { - self.store.execution_fuel = fuel; - if self.store.execution_fuel == 0 { - return Ok(ExecState::Suspended(self.cf)); - } - - let mut instr_ptr = self.cf.instr_ptr; - loop { - for _ in 0..128 { - match self.exec(instr_ptr)? { - ControlFlow::Continue(next_instr_ptr) => instr_ptr = next_instr_ptr, - ControlFlow::Break(()) => return Ok(ExecState::Completed), - } - } - - self.store.execution_fuel = self.store.execution_fuel.saturating_sub(128); - if self.store.execution_fuel == 0 { - self.cf.instr_ptr = instr_ptr; - return Ok(ExecState::Suspended(self.cf)); - } - } - } -} diff --git a/crates/tinywasm/src/interpreter/executor/dispatch.rs b/crates/tinywasm/src/interpreter/executor/dispatch.rs new file mode 100644 index 0000000..57efc54 --- /dev/null +++ b/crates/tinywasm/src/interpreter/executor/dispatch.rs @@ -0,0 +1,90 @@ +use super::*; + +macro_rules! define_stable_dispatch { + ($executor:ident, $instr_ptr:ident, $dispatch_next:ident, $dispatch_flow:ident; + $($variant:ident $(($($arg:pat),*))? $({ $($field:ident),* })? => $body:expr),* $(,)?) => { + #[inline(always)] + fn exec_step($executor: &mut Self, $instr_ptr: usize) -> ExecResult { + macro_rules! $dispatch_next { + ($next_instr_ptr:expr) => {{ + return Ok(ExecFlow::next($next_instr_ptr)); + }}; + } + macro_rules! $dispatch_flow { + ($flow:expr) => {{ + return Ok($flow); + }}; + } + use tinywasm_types::Instruction::*; + match &$executor.func.instructions[$instr_ptr] { + $($variant $(($($arg),*))? $({ $($field),* })? => $body,)* + } + Ok(ExecFlow::next($instr_ptr + 1)) + } + }; +} + +impl Executor<'_> { + instruction_handlers!(define_stable_dispatch); + + #[inline(always)] + pub(crate) fn run_to_completion(mut self) -> Result<()> { + let mut instr_ptr = self.cf.instr_ptr; + loop { + match Self::exec_step(&mut self, instr_ptr)?.next_instr_ptr() { + Some(next_instr_ptr) => instr_ptr = next_instr_ptr, + None => return cold!(Ok(())), + } + } + } + + #[cfg(feature = "std")] + #[inline(always)] + pub(crate) fn run_with_time_budget(mut self, time_budget: core::time::Duration) -> Result { + use crate::std::time::Instant; + + if time_budget.is_zero() { + return Ok(ExecState::Suspended(self.cf)); + } + let start = Instant::now(); + let mut instr_ptr = self.cf.instr_ptr; + loop { + for _ in 0..CHECKPOINT_INTERVAL { + match Self::exec_step(&mut self, instr_ptr)?.next_instr_ptr() { + Some(next_instr_ptr) => instr_ptr = next_instr_ptr, + None => return Ok(ExecState::Completed), + } + } + + if start.elapsed() >= time_budget { + self.cf.instr_ptr = instr_ptr; + return Ok(ExecState::Suspended(self.cf)); + } + } + } + + #[inline(always)] + pub(crate) fn run_with_fuel(mut self, fuel: u32) -> Result { + self.fuel_metered = true; + self.store.execution_fuel = fuel; + if self.store.execution_fuel == 0 { + return Ok(ExecState::Suspended(self.cf)); + } + + let mut instr_ptr = self.cf.instr_ptr; + loop { + for _ in 0..CHECKPOINT_INTERVAL { + match Self::exec_step(&mut self, instr_ptr)?.next_instr_ptr() { + Some(next_instr_ptr) => instr_ptr = next_instr_ptr, + None => return Ok(ExecState::Completed), + } + } + + self.store.execution_fuel = self.store.execution_fuel.saturating_sub(CHECKPOINT_INTERVAL); + if self.store.execution_fuel == 0 { + self.cf.instr_ptr = instr_ptr; + return Ok(ExecState::Suspended(self.cf)); + } + } + } +} diff --git a/crates/tinywasm/src/interpreter/executor/dispatch_become.rs b/crates/tinywasm/src/interpreter/executor/dispatch_become.rs new file mode 100644 index 0000000..66cbb51 --- /dev/null +++ b/crates/tinywasm/src/interpreter/executor/dispatch_become.rs @@ -0,0 +1,189 @@ +use super::*; + +struct Unbudgeted; +struct Bounded; + +type UnbudgetedHandler = for<'store> fn(&mut Executor<'store>, usize, Instruction) -> ExecResult<()>; +type BoundedHandler = for<'store> fn(&mut Executor<'store>, usize, Instruction, u32) -> ExecResult<()>; + +#[cold] +#[inline(never)] +fn instruction_handler_mismatch() -> ! { + unreachable!("instruction handler mismatch") +} + +macro_rules! define_unbudgeted_tail_dispatch { + ($executor:ident, $instr_ptr:ident, $dispatch_next:ident, $dispatch_flow:ident; + $($variant:ident $(($($arg:pat),*))? $({ $($field:ident),* })? => $body:expr),* $(,)?) => { + #[inline(always)] + fn handler_for(instruction: &Instruction) -> UnbudgetedHandler { + use tinywasm_types::Instruction::*; + + match instruction { + $($variant { .. } => Self::$variant,)* + } + } + + $( + #[allow(non_snake_case, unreachable_code, unused_imports, unused_macros, unused_variables)] + fn $variant( + $executor: &mut Executor<'_>, + $instr_ptr: usize, + instruction: Instruction, + ) -> ExecResult<()> { + macro_rules! $dispatch_next { + ($next_instr_ptr:expr) => {{ + let next_instr_ptr = $next_instr_ptr; + let instruction = $executor.func.instructions[next_instr_ptr]; + let handler = Self::handler_for(&instruction); + become handler($executor, next_instr_ptr, instruction); + }}; + } + macro_rules! $dispatch_flow { + ($flow:expr) => {{ + match $flow.next_instr_ptr() { + Some(next_instr_ptr) => $dispatch_next!(next_instr_ptr), + None => return cold!(Ok(())), + } + }}; + } + use tinywasm_types::Instruction::*; + $(let $variant($($arg),*) = &instruction else { + cold!(instruction_handler_mismatch()) + };)? + $(let $variant { $($field),* } = &instruction else { + cold!(instruction_handler_mismatch()) + };)? + $body; + $dispatch_next!($instr_ptr + 1) + } + )* + }; +} + +macro_rules! define_bounded_tail_dispatch { + ($executor:ident, $instr_ptr:ident, $dispatch_next:ident, $dispatch_flow:ident; + $($variant:ident $(($($arg:pat),*))? $({ $($field:ident),* })? => $body:expr),* $(,)?) => { + #[inline(always)] + fn handler_for(instruction: &Instruction) -> BoundedHandler { + use tinywasm_types::Instruction::*; + + match instruction { + $($variant { .. } => Self::$variant,)* + } + } + + $( + #[allow(non_snake_case, unreachable_code, unused_imports, unused_macros, unused_variables)] + fn $variant( + $executor: &mut Executor<'_>, + $instr_ptr: usize, + instruction: Instruction, + instructions_until_checkpoint: u32, + ) -> ExecResult<()> { + macro_rules! $dispatch_next { + ($next_instr_ptr:expr) => {{ + let next_instr_ptr = $next_instr_ptr; + if instructions_until_checkpoint == 0 { + return cold!({ + $executor.cf.instr_ptr = next_instr_ptr; + Ok(()) + }); + } + + let instruction = $executor.func.instructions[next_instr_ptr]; + let handler = Self::handler_for(&instruction); + become handler($executor, next_instr_ptr, instruction, instructions_until_checkpoint - 1); + }}; + } + macro_rules! $dispatch_flow { + ($flow:expr) => {{ + match $flow.next_instr_ptr() { + Some(next_instr_ptr) => $dispatch_next!(next_instr_ptr), + None => return cold!({ + $executor.completed = true; + Ok(()) + }), + } + }}; + } + use tinywasm_types::Instruction::*; + $(let $variant($($arg),*) = &instruction else { + cold!(instruction_handler_mismatch()) + };)? + $(let $variant { $($field),* } = &instruction else { + cold!(instruction_handler_mismatch()) + };)? + $body; + $dispatch_next!($instr_ptr + 1) + } + )* + }; +} + +impl Unbudgeted { + instruction_handlers!(define_unbudgeted_tail_dispatch); +} + +impl Bounded { + instruction_handlers!(define_bounded_tail_dispatch); + + #[inline(always)] + fn run(executor: &mut Executor<'_>) -> ExecResult<()> { + let instr_ptr = executor.cf.instr_ptr; + let instruction = executor.func.instructions[instr_ptr]; + let handler = Self::handler_for(&instruction); + handler(executor, instr_ptr, instruction, CHECKPOINT_INTERVAL - 1) + } +} + +impl<'store> Executor<'store> { + #[inline(always)] + pub(crate) fn run_to_completion(mut self) -> Result<()> { + let instr_ptr = self.cf.instr_ptr; + let instruction = self.func.instructions[instr_ptr]; + let handler = Unbudgeted::handler_for(&instruction); + Ok(handler(&mut self, instr_ptr, instruction)?) + } + + #[cfg(feature = "std")] + #[inline(always)] + pub(crate) fn run_with_time_budget(mut self, time_budget: core::time::Duration) -> Result { + use crate::std::time::Instant; + + if time_budget.is_zero() { + return Ok(ExecState::Suspended(self.cf)); + } + let start = Instant::now(); + + loop { + Bounded::run(&mut self)?; + if self.completed { + return cold!(Ok(ExecState::Completed)); + } + if start.elapsed() >= time_budget { + return cold!(Ok(ExecState::Suspended(self.cf))); + } + } + } + + #[inline(always)] + pub(crate) fn run_with_fuel(mut self, fuel: u32) -> Result { + self.fuel_metered = true; + self.store.execution_fuel = fuel; + if self.store.execution_fuel == 0 { + return Ok(ExecState::Suspended(self.cf)); + } + + loop { + Bounded::run(&mut self)?; + if self.completed { + return cold!(Ok(ExecState::Completed)); + } + self.store.execution_fuel = self.store.execution_fuel.saturating_sub(CHECKPOINT_INTERVAL); + if self.store.execution_fuel == 0 { + return cold!(Ok(ExecState::Suspended(self.cf))); + } + } + } +} diff --git a/crates/tinywasm/src/interpreter/executor/instructions.rs b/crates/tinywasm/src/interpreter/executor/instructions.rs new file mode 100644 index 0000000..587d776 --- /dev/null +++ b/crates/tinywasm/src/interpreter/executor/instructions.rs @@ -0,0 +1,690 @@ +macro_rules! exec_op { + ($executor:ident; binary_fallible $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + fn exec_binary_fallible(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $rhs = <$ty>::stack_pop(value_stack); + let $lhs = <$ty>::stack_pop(value_stack); + <$ty>::stack_push(value_stack, $expr?) + } + exec_binary_fallible(&mut $executor.store.value_stack)?; + }}; + ($executor:ident; unary $from:ty => $to:ty, |$v:ident| $expr:expr) => {{ + fn exec_unary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $v = <$from>::stack_pop(value_stack); + <$to>::stack_push(value_stack, $expr) + } + exec_unary(&mut $executor.store.value_stack)?; + }}; + ($executor:ident; binary $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + exec_op!($executor; binary $from, $from => $to, |$lhs, $rhs| $expr) + }}; + ($executor:ident; binary $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + fn exec_binary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $rhs = <$rhs_ty>::stack_pop(value_stack); + let $lhs = <$lhs_ty>::stack_pop(value_stack); + <$res>::stack_push(value_stack, $expr) + } + exec_binary(&mut $executor.store.value_stack)?; + }}; + ($executor:ident; ternary $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{ + fn exec_ternary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $c = <$from>::stack_pop(value_stack); + let $b = <$from>::stack_pop(value_stack); + let $a = <$from>::stack_pop(value_stack); + <$to>::stack_push(value_stack, $expr) + } + exec_ternary(&mut $executor.store.value_stack)?; + }}; +} + +// This list is the single source for stable instruction stepping and nightly tail handlers. +#[rustfmt::skip] +macro_rules! instruction_handlers { + ($emit:ident) => { + $emit! { executor, instr_ptr, dispatch_next, dispatch_flow; + Unreachable => { return cold!(Err(Trap::Unreachable.into())); }, + Drop32 => { _ = Value32::stack_pop(&mut executor.store.value_stack)}, + Drop64 => { _ = Value64::stack_pop(&mut executor.store.value_stack)}, + Drop128 => { _ = Value128::stack_pop(&mut executor.store.value_stack)}, + Select32 => Value32::stack_select(&mut executor.store.value_stack), + Select64 => Value64::stack_select(&mut executor.store.value_stack), + Select128 => Value128::stack_select(&mut executor.store.value_stack), + SelectStore32(idx) => executor.exec_select_store::(idx.resolve(&executor.func.data))?, + SelectStore64(idx) => executor.exec_select_store::(idx.resolve(&executor.func.data))?, + SelectMulti(counts) => executor.store.value_stack.select_multi(*counts), + Call(v) => dispatch_flow!(executor.exec_call_direct(*v, instr_ptr + 1)?), + CallSelf => { executor.exec_call_self(instr_ptr + 1)?; dispatch_next!(0); }, + CallIndirect(idx) => dispatch_flow!(executor.exec_call_indirect::(*idx, instr_ptr + 1)?), + CallRef(ty) => dispatch_flow!(executor.exec_call_ref::(*ty, instr_ptr + 1)?), + ReturnCall(v) => dispatch_flow!(executor.exec_return_call_direct(*v)?), + ReturnCallSelf => { executor.exec_return_call_self()?; dispatch_next!(0); }, + ReturnCallIndirect(idx) => dispatch_flow!(executor.exec_call_indirect::(*idx, instr_ptr + 1)?), + ReturnCallRef(ty) => dispatch_flow!(executor.exec_call_ref::(*ty, instr_ptr + 1)?), + Throw(tag) => dispatch_flow!(executor.exec_throw(*tag, instr_ptr)?), + ThrowRef => dispatch_flow!(executor.exec_throw_ref(instr_ptr)?), + Jump(ip) => dispatch_next!(*ip as usize), + JumpIfZero32(ip) => if i32::stack_pop(&mut executor.store.value_stack) == 0 { dispatch_next!(*ip as usize) }, + JumpIfNonZero32(ip) => if i32::stack_pop(&mut executor.store.value_stack) != 0 { dispatch_next!(*ip as usize) }, + JumpIfZero64(ip) => if i64::stack_pop(&mut executor.store.value_stack) == 0 { dispatch_next!(*ip as usize) }, + JumpIfNonZero64(ip) => if i64::stack_pop(&mut executor.store.value_stack) != 0 { dispatch_next!(*ip as usize) }, + JumpIfRefNull(ip) => { let ip = *ip; if executor.exec_jump_if_ref::() { dispatch_next!(ip as usize) } }, + JumpIfRefNonNull(ip) => { let ip = *ip; if executor.exec_jump_if_ref::() { dispatch_next!(ip as usize) } }, + BrOnCast(idx) => if let Some(ip) = executor.exec_br_on_cast::(*idx) { dispatch_next!(ip) }, + BrOnCastFail(idx) => if let Some(ip) = executor.exec_br_on_cast::(*idx) { dispatch_next!(ip) }, + JumpIfLocalZero32(arg) => if executor.exec_jump_if_local::(arg.local) { dispatch_next!(arg.target_ip as usize) }, + JumpIfLocalNonZero32(arg) => if executor.exec_jump_if_local::(arg.local) { dispatch_next!(arg.target_ip as usize) }, + JumpIfLocalZero64(arg) => if executor.exec_jump_if_local::(arg.local) { dispatch_next!(arg.target_ip as usize) }, + JumpIfLocalNonZero64(arg) => if executor.exec_jump_if_local::(arg.local) { dispatch_next!(arg.target_ip as usize) }, + JumpCmpStackConst32(packed) => if let Some(ip) = executor.exec_jump_cmp_stack_const32(*packed) { dispatch_next!(ip) }, + JumpCmpStackConst64(packed) => if let Some(ip) = executor.exec_jump_cmp_stack_const64(*packed) { dispatch_next!(ip) }, + JumpCmpStackLocal32(packed) => if let Some(ip) = executor.exec_jump_cmp_stack_local32(*packed) { dispatch_next!(ip) }, + JumpCmpStackLocal64(packed) => if let Some(ip) = executor.exec_jump_cmp_stack_local64(*packed) { dispatch_next!(ip) }, + BinOpLocalConstJump32(packed) => if let Some(ip) = executor.exec_binop_local_const_jump(*packed) { dispatch_next!(ip) }, + BinOpLocalConstJumpCmpLocal32(packed) => if let Some(ip) = executor.exec_binop_local_const_jump_cmp_local(*packed) { dispatch_next!(ip) }, + BinOpStackConstTeeLocalJump32(packed) => if let Some(ip) = executor.exec_binop_stack_const_tee_local_jump(*packed)? { dispatch_next!(ip) }, + BinOpGlobalConstJump32(packed) => if let Some(ip) = executor.exec_binop_global_const_jump(*packed) { dispatch_next!(ip) }, + IncLocalJump32(idx) => if let Some(ip) = executor.exec_inc_local_jump(*idx) { dispatch_next!(ip) }, + IncStackTeeLocalJump32(idx) => if let Some(ip) = executor.exec_inc_stack_tee_local_jump(*idx)? { dispatch_next!(ip) }, + IncGlobalJump32(idx) => if let Some(ip) = executor.exec_inc_global_jump(*idx) { dispatch_next!(ip) }, + IncLocalJumpCmpLocal32(packed) => if let Some(ip) = executor.exec_inc_local_jump_cmp_local(*packed) { dispatch_next!(ip) }, + JumpCmpLocalConst32(packed) => if let Some(ip) = executor.exec_jump_cmp_local_const32(*packed) { dispatch_next!(ip) }, + JumpCmpLocalConst64(packed) => if let Some(ip) = executor.exec_jump_cmp_local_const64(*packed) { dispatch_next!(ip) }, + JumpCmpLocalLocal32(packed) => if let Some(ip) = executor.exec_jump_cmp_local_local32(*packed) { dispatch_next!(ip) }, + JumpCmpLocalLocal64(packed) => if let Some(ip) = executor.exec_jump_cmp_local_local64(*packed) { dispatch_next!(ip) }, + DropKeep32 { base, keep } => executor.store.value_stack.stack_32.truncate_keep((executor.cf.stack_base().s32 + u32::from(*base)) as usize, *keep as usize), + DropKeep64 { base, keep } => executor.store.value_stack.stack_64.truncate_keep((executor.cf.stack_base().s64 + u32::from(*base)) as usize, *keep as usize), + DropKeep128 { base, keep } => executor.store.value_stack.stack_128.truncate_keep((executor.cf.stack_base().s128 + u32::from(*base)) as usize, *keep as usize), + BranchTable(idx) => dispatch_next!(executor.exec_branch_table(*idx)), + Return => dispatch_flow!(executor.exec_return()), + ReturnVoid => dispatch_flow!(executor.exec_return_void()), + Return32 => dispatch_flow!(executor.exec_return_32()), + Return64 => dispatch_flow!(executor.exec_return_64()), + Return128 => dispatch_flow!(executor.exec_return_128()), + LocalGet32(local_index) => Value32::local_push(&mut executor.store.value_stack, &executor.cf, *local_index)?, + LocalGet64(local_index) => Value64::local_push(&mut executor.store.value_stack, &executor.cf, *local_index)?, + LocalGet128(local_index) => Value128::local_push(&mut executor.store.value_stack, &executor.cf, *local_index)?, + LocalSet32(local_index) => executor.exec_local_set_pop::(*local_index), + LocalSet64(local_index) => executor.exec_local_set_pop::(*local_index), + LocalSet128(local_index) => executor.exec_local_set_pop::(*local_index), + LocalCopy32(from, to) => Value32::local_copy(&mut executor.store.value_stack, &executor.cf, *from, *to), + LocalCopy64(from, to) => Value64::local_copy(&mut executor.store.value_stack, &executor.cf, *from, *to), + LocalCopy128(from, to) => Value128::local_copy(&mut executor.store.value_stack, &executor.cf, *from, *to), + AddConst32(c) => { i32::stack_update(&mut executor.store.value_stack, |value| value.wrapping_add(*c)); }, + AndConst32(c) => { i32::stack_update(&mut executor.store.value_stack, |value| value & *c); }, + XorConst32(c) => { i32::stack_update(&mut executor.store.value_stack, |value| value ^ *c); }, + ShrUConst32(c) => { u32::stack_update(&mut executor.store.value_stack, |value| value.wrapping_shr(*c as u32)); }, + AddConst64(idx) => { let rhs = idx.resolve(&executor.func.data).value(); i64::stack_update(&mut executor.store.value_stack, |value| value.wrapping_add(rhs)); }, + BinOpStackConst32(op, rhs) => { u32::stack_update(&mut executor.store.value_stack, |lhs| op.exec(lhs, *rhs as u32)); }, + BinOpStackConst64(packed) => { let rhs = packed.index.resolve(&executor.func.data).value() as u64; u64::stack_update(&mut executor.store.value_stack, |lhs| packed.op.exec(lhs, rhs)); }, + IncLocal32(arg) => { i32::local_update(&mut executor.store.value_stack, &executor.cf, arg.local, |value| value.wrapping_add(arg.value)); }, + IncLocal64(packed) => { let rhs = packed.index.resolve(&executor.func.data).value(); i64::local_update(&mut executor.store.value_stack, &executor.cf, packed.op, |value| value.wrapping_add(rhs)); }, + I32Add3 => exec_op!(executor; ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), + I64Add3 => exec_op!(executor; ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), + MulAccLocal32(acc) => executor.exec_mul_acc_local::(*acc, i32::wrapping_mul, i32::wrapping_add), + MulAccLocal64(acc) => executor.exec_mul_acc_local::(*acc, i64::wrapping_mul, i64::wrapping_add), + FMulAccLocal32(acc) => executor.exec_mul_acc_local::(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), + FMulAccLocal64(acc) => executor.exec_mul_acc_local::(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), + BinOpLocalLocal32(op, a, b) => executor.exec_binop_local_local::(*a, *b, None, *op)?, + BinOpLocalLocal64(op, a, b) => executor.exec_binop_local_local::(*a, *b, None, *op)?, + BinOpLocalLocal128(op, a, b) => executor.exec_binop_local_local::(*a, *b, None, *op)?, + CmpLocalLocal32(op, a, b) => executor.exec_cmp_local_local::(*a, *b, *op)?, + CmpLocalLocal64(op, a, b) => executor.exec_cmp_local_local::(*a, *b, *op)?, + AddLocalLocalSet32(arg) => executor.exec_binop_local_local::(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, + AddLocalLocalTee32(arg) => executor.exec_binop_local_local::(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, + BinOpLocalLocalSet32(packed) => executor.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalSet64(packed) => executor.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalSet128(packed) => executor.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalTee32(packed) => executor.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalTee64(packed) => executor.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalTee128(packed) => executor.exec_binop_local_local_indexed::(packed.index, packed.op)?, + AddLocalConst32(arg) => executor.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IAdd)?, + SubLocalConst32(arg) => executor.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::ISub)?, + MulLocalConst32(arg) => executor.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IMul)?, + AndLocalConst32(arg) => executor.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IAnd)?, + ShrULocalConst32(arg) => executor.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IShrU)?, + BinOpLocalConst32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::(v.a(), v.b(), None, packed.op)?; }, + BinOpLocalConst64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::(v.a(), v.b(), None, packed.op)?; }, + BinOpLocalConst128(packed) => { let v = packed.index.resolve(&executor.func.data); let rhs = Value128(v.b().resolve(&executor.func.data).value()); executor.exec_binop_local_const::(v.a(), rhs, None, packed.op)?; }, + BinOpLocalConstSet32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstTee32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstSet64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstTee64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstSet128(packed) => { let v = packed.index.resolve(&executor.func.data); let rhs = Value128(v.c().resolve(&executor.func.data).value()); executor.exec_binop_local_const::(v.a(), rhs, Some(v.b()), packed.op)?; }, + BinOpLocalConstTee128(packed) => { let v = packed.index.resolve(&executor.func.data); let rhs = Value128(v.c().resolve(&executor.func.data).value()); executor.exec_binop_local_const::(v.a(), rhs, Some(v.b()), packed.op)?; }, + BinOpStackLocal32(op, local) => executor.exec_binop_stack_local::(*local, None, *op)?, + BinOpStackLocalSet32(op, local, dst) => executor.exec_binop_stack_local::(*local, Some(*dst), *op)?, + BinOpStackLocalTee32(op, local, dst) => executor.exec_binop_stack_local::(*local, Some(*dst), *op)?, + BinOpStackLocal128(op, local) => executor.exec_binop_stack_local::(*local, None, *op)?, + BinOpStackGlobal32(op, global_index) => executor.exec_binop_stack_global::(*global_index, *op)?, + BinOpStackGlobal64(op, global_index) => executor.exec_binop_stack_global::(*global_index, *op)?, + BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst128(packed) => { let v = packed.index.resolve(&executor.func.data); let rhs = Value128(v.b().resolve(&executor.func.data).value()); executor.exec_binop_global_const::(v.a(), rhs, packed.op)?; }, + SetLocalConst32(arg) => i32::local_set(&mut executor.store.value_stack, &executor.cf, arg.local, arg.value), + SetLocalConst64(packed) => { let v = packed.index.resolve(&executor.func.data).value(); i64::local_set(&mut executor.store.value_stack, &executor.cf, packed.op, v); }, + SetLocalConst128(packed) => Value128::local_set(&mut executor.store.value_stack, &executor.cf, packed.op, Value128(packed.index.resolve(&executor.func.data).value())), + IncMemoryLocal32(arg) => executor.exec_inc_memory_local::(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, + IncMemoryLocal64(arg) => executor.exec_inc_memory_local::(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, + StoreLocalLocal32(arg) => executor.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, + StoreLocalLocal64(arg) => executor.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, + StoreLocalLocal128(arg) => executor.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, + LoadLocal32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, identity)?, + LoadLocal64(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, identity)?, + LoadLocal8S32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal8U32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal16S32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal16U32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocalTee32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + LoadLocalSet32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + LoadLocalTee8S32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee8U32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee16S32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee16U32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet8S32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet8U32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet16S32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet16U32(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee128(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + LoadLocalSet128(arg) => executor.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + AndConstTee32(arg) => executor.exec_binop_const_tee::(arg.value as u32, arg.local, BinOp::IAnd)?, + SubConstTee32(arg) => executor.exec_binop_const_tee::(arg.value as u32, arg.local, BinOp::ISub)?, + AndConstTee64(packed) => executor.exec_binop_const_tee::(packed.index.resolve(&executor.func.data).value() as u64, packed.op, BinOp::IAnd)?, + SubConstTee64(packed) => executor.exec_binop_const_tee::(packed.index.resolve(&executor.func.data).value() as u64, packed.op, BinOp::ISub)?, + LocalTee32(local_index) => executor.exec_local_tee::(*local_index), + LocalTee64(local_index) => executor.exec_local_tee::(*local_index), + LocalTee128(local_index) => executor.exec_local_tee::(*local_index), + GlobalGet32(global_index) => executor.exec_global_get::(*global_index)?, + GlobalGet64(global_index) => executor.exec_global_get::(*global_index)?, + GlobalGet128(global_index) => executor.exec_global_get::(*global_index)?, + GlobalSet32(global_index) => executor.exec_global_set::(*global_index), + GlobalSet64(global_index) => executor.exec_global_set::(*global_index), + GlobalSet128(global_index) => executor.exec_global_set::(*global_index), + GlobalTee32(global_index) => executor.exec_global_tee::(*global_index), + GlobalTee64(global_index) => executor.exec_global_tee::(*global_index), + GlobalTee128(global_index) => executor.exec_global_tee::(*global_index), + Const32(val) => i32::stack_push(&mut executor.store.value_stack, *val)?, + Const64Imm(val) => i64::stack_push(&mut executor.store.value_stack, i64::from(*val))?, + Const64(idx) => i64::stack_push(&mut executor.store.value_stack, idx.resolve(&executor.func.data).value())?, + Const128Imm(val) => Value128::stack_push(&mut executor.store.value_stack, Value128(u128::from(*val).to_le_bytes()))?, + I64Eqz => exec_op!(executor; unary i64 => i32, |v| i32::from(v == 0)), + I32Eqz => exec_op!(executor; unary i32 => i32, |v| i32::from(v == 0)), + I32Eq => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a == b)), + I64Eq => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a == b)), + F32Eq => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a == b)), + F64Eq => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a == b)), + I32Ne => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a != b)), + I64Ne => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a != b)), + F32Ne => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a != b)), + F64Ne => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a != b)), + I32LtS => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a < b)), + I64LtS => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a < b)), + I32LtU => exec_op!(executor; binary u32 => i32, |a, b| i32::from(a < b)), + I64LtU => exec_op!(executor; binary u64 => i32, |a, b| i32::from(a < b)), + F32Lt => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a < b)), + F64Lt => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a < b)), + I32LeS => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a <= b)), + I64LeS => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a <= b)), + I32LeU => exec_op!(executor; binary u32 => i32, |a, b| i32::from(a <= b)), + I64LeU => exec_op!(executor; binary u64 => i32, |a, b| i32::from(a <= b)), + F32Le => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a <= b)), + F64Le => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a <= b)), + I32GeS => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a >= b)), + I64GeS => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a >= b)), + I32GeU => exec_op!(executor; binary u32 => i32, |a, b| i32::from(a >= b)), + I64GeU => exec_op!(executor; binary u64 => i32, |a, b| i32::from(a >= b)), + F32Ge => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a >= b)), + F64Ge => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a >= b)), + I32GtS => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a > b)), + I64GtS => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a > b)), + I32GtU => exec_op!(executor; binary u32 => i32, |a, b| i32::from(a > b)), + I64GtU => exec_op!(executor; binary u64 => i32, |a, b| i32::from(a > b)), + F32Gt => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a > b)), + F64Gt => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a > b)), + I32Add => exec_op!(executor; binary i32 => i32, |a, b| a.wrapping_add(b)), + I64Add => exec_op!(executor; binary i64 => i64, |a, b| a.wrapping_add(b)), + F32Add => exec_op!(executor; binary f32 => f32, |a, b| a + b), + F64Add => exec_op!(executor; binary f64 => f64, |a, b| a + b), + I32Sub => exec_op!(executor; binary i32 => i32, |a, b| a.wrapping_sub(b)), + I64Sub => exec_op!(executor; binary i64 => i64, |a, b| a.wrapping_sub(b)), + F32Sub => exec_op!(executor; binary f32 => f32, |a, b| a - b), + F64Sub => exec_op!(executor; binary f64 => f64, |a, b| a - b), + F32Div => exec_op!(executor; binary f32 => f32, |a, b| a / b), + F64Div => exec_op!(executor; binary f64 => f64, |a, b| a / b), + I32Mul => exec_op!(executor; binary i32 => i32, |a, b| a.wrapping_mul(b)), + I64Mul => exec_op!(executor; binary i64 => i64, |a, b| a.wrapping_mul(b)), + F32Mul => exec_op!(executor; binary f32 => f32, |a, b| a * b), + F64Mul => exec_op!(executor; binary f64 => f64, |a, b| a * b), + I32DivS => exec_op!(executor; binary_fallible i32, |a, b| a.tw_checked_div(b)), + I64DivS => exec_op!(executor; binary_fallible i64, |a, b| a.tw_checked_div(b)), + I32DivU => exec_op!(executor; binary_fallible u32, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), + I64DivU => exec_op!(executor; binary_fallible u64, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), + I32RemS => exec_op!(executor; binary_fallible i32, |a, b| a.tw_checked_wrapping_rem(b)), + I64RemS => exec_op!(executor; binary_fallible i64, |a, b| a.tw_checked_wrapping_rem(b)), + I32RemU => exec_op!(executor; binary_fallible u32, |a, b| a.tw_checked_wrapping_rem(b)), + I64RemU => exec_op!(executor; binary_fallible u64, |a, b| a.tw_checked_wrapping_rem(b)), + I32And => exec_op!(executor; binary i32 => i32, |a, b| a & b), + I64And => exec_op!(executor; binary i64 => i64, |a, b| a & b), + I32Or => exec_op!(executor; binary i32 => i32, |a, b| a | b), + I64Or => exec_op!(executor; binary i64 => i64, |a, b| a | b), + I32Xor => exec_op!(executor; binary i32 => i32, |a, b| a ^ b), + I64Xor => exec_op!(executor; binary i64 => i64, |a, b| a ^ b), + I32Shl => exec_op!(executor; binary i32 => i32, |a, b| a.wrapping_shl(b as u32)), + I64Shl => exec_op!(executor; binary i64 => i64, |a, b| a.wrapping_shl(b as u32)), + I32ShrS => exec_op!(executor; binary i32 => i32, |a, b| a.wrapping_shr(b as u32)), + I64ShrS => exec_op!(executor; binary i64 => i64, |a, b| a.wrapping_shr(b as u32)), + I32ShrU => exec_op!(executor; binary u32 => u32, |a, b| a.wrapping_shr(b)), + I64ShrU => exec_op!(executor; binary u64 => u64, |a, b| a.wrapping_shr(b as u32)), + I32Rotl => exec_op!(executor; binary i32 => i32, |a, b| a.rotate_left(b as u32)), + I64Rotl => exec_op!(executor; binary i64 => i64, |a, b| a.rotate_left(b as u32)), + I32Rotr => exec_op!(executor; binary i32 => i32, |a, b| a.rotate_right(b as u32)), + I64Rotr => exec_op!(executor; binary i64 => i64, |a, b| a.rotate_right(b as u32)), + I64Add128 => executor.exec_i64_add128()?, + I64Sub128 => executor.exec_i64_sub128()?, + I64MulWideS => executor.exec_i64_mul_wide_s()?, + I64MulWideU => executor.exec_i64_mul_wide_u()?, + I32Clz => exec_op!(executor; unary i32 => i32, |v| v.leading_zeros() as i32), + I64Clz => exec_op!(executor; unary i64 => i64, |v| i64::from(v.leading_zeros())), + I32Ctz => exec_op!(executor; unary i32 => i32, |v| v.trailing_zeros() as i32), + I64Ctz => exec_op!(executor; unary i64 => i64, |v| i64::from(v.trailing_zeros())), + I32Popcnt => exec_op!(executor; unary i32 => i32, |v| v.count_ones() as i32), + I64Popcnt => exec_op!(executor; unary i64 => i64, |v| i64::from(v.count_ones())), + + // Reference types + RefFunc(func_idx) => ValueRef::stack_push(&mut executor.store.value_stack, ValueRef::from_category_addr(executor.module.resolve_func_addr(*func_idx)))?, + RefNull(_) => ValueRef::stack_push(&mut executor.store.value_stack, ValueRef::NULL)?, + RefIsNull => executor.exec_ref_is_null()?, + RefAsNonNull => executor.exec_ref_as_non_null()?, + RefI31 => exec_op!(executor; unary i32 => ValueRef, |v| ValueRef::from_i31(v)), + I31GetS => executor.exec_i31_get(true)?, + I31GetU => executor.exec_i31_get(false)?, + RefEq => exec_op!(executor; binary ValueRef => i32, |a, b| i32::from(a == b)), + RefTest(ty) => executor.exec_ref_test(*ty)?, + RefCast(ty) => executor.exec_ref_cast(*ty)?, + + // GC objects + StructNew(ty) => executor.exec_struct_new(*ty, false)?, + StructNewDefault(ty) => executor.exec_struct_new(*ty, true)?, + StructGet(idx) => executor.exec_struct_get(*idx, None)?, + StructGetS(idx) => executor.exec_struct_get(*idx, Some(true))?, + StructGetU(idx) => executor.exec_struct_get(*idx, Some(false))?, + StructSet(idx) => executor.exec_struct_set(*idx)?, + ArrayNew(ty) => executor.exec_array_new(*ty, false)?, + ArrayNewDefault(ty) => executor.exec_array_new(*ty, true)?, + ArrayNewFixed(idx) => executor.exec_array_new_fixed(*idx)?, + ArrayNewData(idx) => executor.exec_array_new_data(*idx)?, + ArrayNewElem(idx) => executor.exec_array_new_elem(*idx)?, + ArrayGet(ty) => executor.exec_array_get(*ty, None)?, + ArrayGetS(ty) => executor.exec_array_get(*ty, Some(true))?, + ArrayGetU(ty) => executor.exec_array_get(*ty, Some(false))?, + ArraySet(ty) => executor.exec_array_set(*ty)?, + ArrayLen => executor.exec_array_len()?, + ArrayFill(ty) => executor.exec_array_fill(*ty)?, + ArrayCopy(idx) => executor.exec_array_copy(*idx)?, + ArrayInitData(idx) => executor.exec_array_init_data(*idx)?, + ArrayInitElem(idx) => executor.exec_array_init_elem(*idx)?, + MemorySize(addr) => executor.exec_memory_size(*addr)?, + MemoryGrow(addr) => executor.exec_memory_grow(*addr)?, + + // Bulk memory operations + MemoryCopy(idx) => executor.exec_memory_copy(*idx)?, + MemoryFill(addr) => executor.exec_memory_fill(*addr)?, + MemoryFillConst(idx) => executor.exec_memory_fill_const(*idx)?, + MemoryInit(idx) => executor.exec_memory_init(*idx)?, + DataDrop(data_index) => executor.store.state.get_data_mut(executor.module.resolve_data_addr(*data_index)).drop(), + ElemDrop(elem_index) => executor.store.state.get_elem_mut(executor.module.resolve_elem_addr(*elem_index)).drop(), + + // Table instructions + TableGet(table_idx) => executor.exec_table_get(*table_idx)?, + TableSet(table_idx) => executor.exec_table_set(*table_idx)?, + TableSize(table_idx) => executor.exec_table_size(*table_idx)?, + TableInit(idx) => executor.exec_table_init(*idx)?, + TableGrow(table_idx) => executor.exec_table_grow(*table_idx)?, + TableFill(table_idx) => executor.exec_table_fill(*table_idx)?, + TableCopy(idx) => executor.exec_table_copy(*idx)?, + + // Core memory load/store operations + I32Store(idx) => executor.exec_mem_store::(idx.resolve(&executor.func.data), identity)?, + I64Store(idx) => executor.exec_mem_store::(idx.resolve(&executor.func.data), identity)?, + F32Store(idx) => executor.exec_mem_store::(idx.resolve(&executor.func.data), identity)?, + F64Store(idx) => executor.exec_mem_store::(idx.resolve(&executor.func.data), identity)?, + FMaStoreF32(m) => executor.exec_fma_store::(*m)?, + FMaStoreF64(m) => executor.exec_fma_store::(*m)?, + I32Store8(idx) => executor.exec_mem_store::(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i8)?, + I32Store16(idx) => executor.exec_mem_store::(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i16)?, + I64Store8(idx) => executor.exec_mem_store::(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i8)?, + I64Store16(idx) => executor.exec_mem_store::(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i16)?, + I64Store32(idx) => executor.exec_mem_store::(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i32)?, + I32Load(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), identity)?, + I64Load(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), identity)?, + F32Load(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), identity)?, + F64Load(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), identity)?, + I32Load8S(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), i32::from)?, + I32Load8U(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), i32::from)?, + I32Load16S(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), i32::from)?, + I32Load16U(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), i32::from)?, + I64Load8S(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), i64::from)?, + I64Load8U(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), i64::from)?, + I64Load16S(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), i64::from)?, + I64Load16U(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), i64::from)?, + I64Load32S(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), i64::from)?, + I64Load32U(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), i64::from)?, + + // Numeric conversion operations + F32ConvertI32S => exec_op!(executor; unary i32 => f32, |v| v as f32), + F32ConvertI64S => exec_op!(executor; unary i64 => f32, |v| v as f32), + F64ConvertI32S => exec_op!(executor; unary i32 => f64, |v| f64::from(v)), + F64ConvertI64S => exec_op!(executor; unary i64 => f64, |v| v as f64), + F32ConvertI32U => exec_op!(executor; unary u32 => f32, |v| v as f32), + F32ConvertI64U => exec_op!(executor; unary u64 => f32, |v| v as f32), + F64ConvertI32U => exec_op!(executor; unary u32 => f64, |v| f64::from(v)), + F64ConvertI64U => exec_op!(executor; unary u64 => f64, |v| v as f64), + + // Sign-extension operations + I32Extend8S => exec_op!(executor; unary i32 => i32, |v| i32::from(v as i8)), + I32Extend16S => exec_op!(executor; unary i32 => i32, |v| i32::from(v as i16)), + I64Extend8S => exec_op!(executor; unary i64 => i64, |v| i64::from(v as i8)), + I64Extend16S => exec_op!(executor; unary i64 => i64, |v| i64::from(v as i16)), + I64Extend32S => exec_op!(executor; unary i64 => i64, |v| i64::from(v as i32)), + I64ExtendI32U => exec_op!(executor; unary u32 => i64, |v| i64::from(v)), + I64ExtendI32S => exec_op!(executor; unary i32 => i64, |v| i64::from(v)), + I32WrapI64 => exec_op!(executor; unary i64 => i32, |v| v as i32), + F32DemoteF64 => exec_op!(executor; unary f64 => f32, |v| v as f32), + F64PromoteF32 => exec_op!(executor; unary f32 => f64, |v| f64::from(v)), + F32Abs => exec_op!(executor; unary f32 => f32, |v| v.abs()), + F64Abs => exec_op!(executor; unary f64 => f64, |v| v.abs()), + F32Neg => exec_op!(executor; unary f32 => f32, |v| -v), + F64Neg => exec_op!(executor; unary f64 => f64, |v| -v), + F32Ceil => exec_op!(executor; unary f32 => f32, |v| v.ceil()), + F64Ceil => exec_op!(executor; unary f64 => f64, |v| v.ceil()), + F32Floor => exec_op!(executor; unary f32 => f32, |v| v.floor()), + F64Floor => exec_op!(executor; unary f64 => f64, |v| v.floor()), + F32Trunc => exec_op!(executor; unary f32 => f32, |v| v.trunc()), + F64Trunc => exec_op!(executor; unary f64 => f64, |v| v.trunc()), + F32Nearest => exec_op!(executor; unary f32 => f32, |v| v.tw_nearest()), + F64Nearest => exec_op!(executor; unary f64 => f64, |v| v.tw_nearest()), + F32Sqrt => exec_op!(executor; unary f32 => f32, |v| v.sqrt()), + F64Sqrt => exec_op!(executor; unary f64 => f64, |v| v.sqrt()), + F32Min => exec_op!(executor; binary f32 => f32, |a, b| a.tw_minimum(b)), + F64Min => exec_op!(executor; binary f64 => f64, |a, b| a.tw_minimum(b)), + F32Max => exec_op!(executor; binary f32 => f32, |a, b| a.tw_maximum(b)), + F64Max => exec_op!(executor; binary f64 => f64, |a, b| a.tw_maximum(b)), + F32Copysign => exec_op!(executor; binary f32 => f32, |a, b| a.copysign(b)), + F64Copysign => exec_op!(executor; binary f64 => f64, |a, b| a.copysign(b)), + I32TruncF32S => checked_conv_float!(f32, i32, executor), + I32TruncF64S => checked_conv_float!(f64, i32, executor), + I32TruncF32U => checked_conv_float!(f32, u32, i32, executor), + I32TruncF64U => checked_conv_float!(f64, u32, i32, executor), + I64TruncF32S => checked_conv_float!(f32, i64, executor), + I64TruncF64S => checked_conv_float!(f64, i64, executor), + I64TruncF32U => checked_conv_float!(f32, u64, i64, executor), + I64TruncF64U => checked_conv_float!(f64, u64, i64, executor), + + // Non-trapping float-to-int conversions + I32TruncSatF32S => exec_op!(executor; unary f32 => i32, |v| v.trunc() as i32), + I32TruncSatF32U => exec_op!(executor; unary f32 => u32, |v| v.trunc() as u32), + I32TruncSatF64S => exec_op!(executor; unary f64 => i32, |v| v.trunc() as i32), + I32TruncSatF64U => exec_op!(executor; unary f64 => u32, |v| v.trunc() as u32), + I64TruncSatF32S => exec_op!(executor; unary f32 => i64, |v| v.trunc() as i64), + I64TruncSatF32U => exec_op!(executor; unary f32 => u64, |v| v.trunc() as u64), + I64TruncSatF64S => exec_op!(executor; unary f64 => i64, |v| v.trunc() as i64), + I64TruncSatF64U => exec_op!(executor; unary f64 => u64, |v| v.trunc() as u64), + + // SIMD extension + V128Not => exec_op!(executor; unary Value128 => Value128, |v| v.v128_not()), + V128And => exec_op!(executor; binary Value128 => Value128, |a, b| a.v128_and(b)), + V128AndNot => exec_op!(executor; binary Value128 => Value128, |a, b| a.v128_andnot(b)), + V128Or => exec_op!(executor; binary Value128 => Value128, |a, b| a.v128_or(b)), + V128Xor => exec_op!(executor; binary Value128 => Value128, |a, b| a.v128_xor(b)), + V128Bitselect => exec_op!(executor; ternary Value128 => Value128, |a, b, c| Value128::v128_bitselect(a, b, c)), + V128AnyTrue => exec_op!(executor; unary Value128 => i32, |v| v.v128_any_true() as i32), + I8x16Swizzle => exec_op!(executor; binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), + I8x16RelaxedSwizzle => exec_op!(executor; binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), + V128Load(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), identity)?, + V128Load8x8S(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, + V128Load8x8U(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, + V128Load16x4S(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, + V128Load16x4U(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, + V128Load32x2S(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, + V128Load32x2U(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, + V128Load8Splat(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), Value128::splat_i8)?, + V128Load16Splat(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), Value128::splat_i16)?, + V128Load32Splat(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), Value128::splat_i32)?, + V128Load64Splat(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), Value128::splat_i64)?, + V128Store(idx) => executor.exec_mem_store::(idx.resolve(&executor.func.data), identity)?, + V128Store8Lane(arg) => executor.exec_mem_store_lane::(*arg)?, + V128Store16Lane(arg) => executor.exec_mem_store_lane::(*arg)?, + V128Store32Lane(arg) => executor.exec_mem_store_lane::(*arg)?, + V128Store64Lane(arg) => executor.exec_mem_store_lane::(*arg)?, + V128Load32Zero(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), |v| Value128::from_i32x4([v, 0, 0, 0]))?, + V128Load64Zero(idx) => executor.exec_mem_load::(idx.resolve(&executor.func.data), |v| Value128::from_i64x2([v, 0]))?, + Const128(arg) => Value128::stack_push(&mut executor.store.value_stack, Value128(arg.resolve(&executor.func.data).value()))?, + I8x16ExtractLaneS(lane) => executor.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_i8(lane) as i32)?, + I8x16ExtractLaneU(lane) => executor.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_u8(lane) as i32)?, + I16x8ExtractLaneS(lane) => executor.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_i16(lane) as i32)?, + I16x8ExtractLaneU(lane) => executor.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_u16(lane) as i32)?, + I32x4ExtractLane(lane) => executor.exec_simd_extract_lane::(*lane, Value128::extract_lane_i32)?, + I64x2ExtractLane(lane) => executor.exec_simd_extract_lane::(*lane, Value128::extract_lane_i64)?, + F32x4ExtractLane(lane) => executor.exec_simd_extract_lane::(*lane, Value128::extract_lane_f32)?, + F64x2ExtractLane(lane) => executor.exec_simd_extract_lane::(*lane, Value128::extract_lane_f64)?, + V128Load8Lane(arg) => executor.exec_mem_load_lane::(*arg)?, + V128Load16Lane(arg) => executor.exec_mem_load_lane::(*arg)?, + V128Load32Lane(arg) => executor.exec_mem_load_lane::(*arg)?, + V128Load64Lane(arg) => executor.exec_mem_load_lane::(*arg)?, + I8x16ReplaceLane(lane) => executor.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i8x16_replace_lane(lane, value as i8))?, + I16x8ReplaceLane(lane) => executor.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i16x8_replace_lane(lane, value as i16))?, + I32x4ReplaceLane(lane) => executor.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i32x4_replace_lane(lane, value))?, + I64x2ReplaceLane(lane) => executor.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i64x2_replace_lane(lane, value))?, + F32x4ReplaceLane(lane) => executor.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.f32x4_replace_lane(lane, value))?, + F64x2ReplaceLane(lane) => executor.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.f64x2_replace_lane(lane, value))?, + I8x16Splat => exec_op!(executor; unary i32 => Value128, |v| Value128::splat_i8(v as i8)), + I16x8Splat => exec_op!(executor; unary i32 => Value128, |v| Value128::splat_i16(v as i16)), + I32x4Splat => exec_op!(executor; unary i32 => Value128, |v| Value128::splat_i32(v)), + I64x2Splat => exec_op!(executor; unary i64 => Value128, |v| Value128::splat_i64(v)), + F32x4Splat => exec_op!(executor; unary f32 => Value128, |v| Value128::splat_f32(v)), + F64x2Splat => exec_op!(executor; unary f64 => Value128, |v| Value128::splat_f64(v)), + I8x16Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_eq(b)), + I16x8Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_eq(b)), + I32x4Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_eq(b)), + I64x2Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_eq(b)), + F32x4Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_eq(b)), + F64x2Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_eq(b)), + I8x16Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_ne(b)), + I16x8Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_ne(b)), + I32x4Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_ne(b)), + I64x2Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_ne(b)), + F32x4Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_ne(b)), + F64x2Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_ne(b)), + I8x16LtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_lt_s(b)), + I16x8LtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_lt_s(b)), + I32x4LtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_lt_s(b)), + I64x2LtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_lt_s(b)), + I8x16LtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_lt_u(b)), + I16x8LtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_lt_u(b)), + I32x4LtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_lt_u(b)), + F32x4Lt => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_lt(b)), + F64x2Lt => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_lt(b)), + F32x4Gt => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_gt(b)), + F64x2Gt => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_gt(b)), + I8x16GtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_gt_s(b)), + I16x8GtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_gt_s(b)), + I32x4GtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_gt_s(b)), + I64x2GtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_gt_s(b)), + I64x2LeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_le_s(b)), + F32x4Le => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_le(b)), + F64x2Le => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_le(b)), + I8x16GtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_gt_u(b)), + I16x8GtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_gt_u(b)), + I32x4GtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_gt_u(b)), + F32x4Ge => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_ge(b)), + F64x2Ge => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_ge(b)), + I8x16LeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_le_s(b)), + I16x8LeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_le_s(b)), + I32x4LeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_le_s(b)), + I8x16LeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_le_u(b)), + I16x8LeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_le_u(b)), + I32x4LeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_le_u(b)), + I8x16GeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_ge_s(b)), + I16x8GeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_ge_s(b)), + I32x4GeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_ge_s(b)), + I64x2GeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_ge_s(b)), + I8x16GeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_ge_u(b)), + I16x8GeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_ge_u(b)), + I32x4GeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_ge_u(b)), + I8x16Abs => exec_op!(executor; unary Value128 => Value128, |a| a.i8x16_abs()), + I16x8Abs => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_abs()), + I32x4Abs => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_abs()), + I64x2Abs => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_abs()), + I8x16Neg => exec_op!(executor; unary Value128 => Value128, |a| a.i8x16_neg()), + I16x8Neg => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_neg()), + I32x4Neg => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_neg()), + I64x2Neg => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_neg()), + I8x16AllTrue => exec_op!(executor; unary Value128 => i32, |v| v.i8x16_all_true() as i32), + I16x8AllTrue => exec_op!(executor; unary Value128 => i32, |v| v.i16x8_all_true() as i32), + I32x4AllTrue => exec_op!(executor; unary Value128 => i32, |v| v.i32x4_all_true() as i32), + I64x2AllTrue => exec_op!(executor; unary Value128 => i32, |v| v.i64x2_all_true() as i32), + I8x16Bitmask => exec_op!(executor; unary Value128 => i32, |v| v.i8x16_bitmask() as i32), + I16x8Bitmask => exec_op!(executor; unary Value128 => i32, |v| v.i16x8_bitmask() as i32), + I32x4Bitmask => exec_op!(executor; unary Value128 => i32, |v| v.i32x4_bitmask() as i32), + I64x2Bitmask => exec_op!(executor; unary Value128 => i32, |v| v.i64x2_bitmask() as i32), + I8x16Shl => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)), + I16x8Shl => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)), + I32x4Shl => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)), + I64x2Shl => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)), + I8x16ShrS => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)), + I16x8ShrS => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)), + I32x4ShrS => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)), + I64x2ShrS => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)), + I8x16ShrU => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)), + I16x8ShrU => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)), + I32x4ShrU => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)), + I64x2ShrU => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)), + I8x16Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_add(b)), + I16x8Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_add(b)), + I32x4Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_add(b)), + I64x2Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_add(b)), + I8x16Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_sub(b)), + I16x8Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_sub(b)), + I32x4Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_sub(b)), + I64x2Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_sub(b)), + I8x16MinS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_min_s(b)), + I16x8MinS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_min_s(b)), + I32x4MinS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_min_s(b)), + I8x16MinU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_min_u(b)), + I16x8MinU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_min_u(b)), + I32x4MinU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_min_u(b)), + I8x16MaxS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_max_s(b)), + I16x8MaxS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_max_s(b)), + I32x4MaxS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_max_s(b)), + I8x16MaxU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_max_u(b)), + I16x8MaxU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_max_u(b)), + I32x4MaxU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_max_u(b)), + I64x2Mul => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_mul(b)), + I16x8Mul => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_mul(b)), + I32x4Mul => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_mul(b)), + I8x16NarrowI16x8S => exec_op!(executor; binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_s(a, b)), + I8x16NarrowI16x8U => exec_op!(executor; binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_u(a, b)), + I16x8NarrowI32x4S => exec_op!(executor; binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_s(a, b)), + I16x8NarrowI32x4U => exec_op!(executor; binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_u(a, b)), + I8x16AddSatS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_add_sat_s(b)), + I16x8AddSatS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_add_sat_s(b)), + I8x16AddSatU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_add_sat_u(b)), + I16x8AddSatU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_add_sat_u(b)), + I8x16SubSatS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_sub_sat_s(b)), + I16x8SubSatS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_sub_sat_s(b)), + I8x16SubSatU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_sub_sat_u(b)), + I16x8SubSatU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_sub_sat_u(b)), + I8x16AvgrU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_avgr_u(b)), + I16x8AvgrU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_avgr_u(b)), + I16x8ExtAddPairwiseI8x16S => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_s()), + I16x8ExtAddPairwiseI8x16U => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_u()), + I32x4ExtAddPairwiseI16x8S => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_s()), + I32x4ExtAddPairwiseI16x8U => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_u()), + I16x8ExtMulLowI8x16S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_s(b)), + I16x8ExtMulLowI8x16U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_u(b)), + I16x8ExtMulHighI8x16S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_s(b)), + I16x8ExtMulHighI8x16U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_u(b)), + I32x4ExtMulLowI16x8S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_s(b)), + I32x4ExtMulLowI16x8U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_u(b)), + I32x4ExtMulHighI16x8S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_s(b)), + I32x4ExtMulHighI16x8U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_u(b)), + I64x2ExtMulLowI32x4S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_s(b)), + I64x2ExtMulLowI32x4U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_u(b)), + I64x2ExtMulHighI32x4S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_s(b)), + I64x2ExtMulHighI32x4U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_u(b)), + I16x8ExtendLowI8x16S => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_s()), + I16x8ExtendLowI8x16U => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_u()), + I16x8ExtendHighI8x16S => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_s()), + I16x8ExtendHighI8x16U => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_u()), + I32x4ExtendLowI16x8S => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_s()), + I32x4ExtendLowI16x8U => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_u()), + I32x4ExtendHighI16x8S => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_s()), + I32x4ExtendHighI16x8U => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_u()), + I64x2ExtendLowI32x4S => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_s()), + I64x2ExtendLowI32x4U => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_u()), + I64x2ExtendHighI32x4S => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()), + I64x2ExtendHighI32x4U => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()), + I8x16Popcnt => exec_op!(executor; unary Value128 => Value128, |v| v.i8x16_popcnt()), + I8x16Shuffle(idx) => executor.exec_simd_shuffle(Value128(idx.resolve(&executor.func.data).value()))?, + I16x8Q15MulrSatS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), + I32x4DotI16x8S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)), + I8x16RelaxedLaneselect => exec_op!(executor; ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), + I16x8RelaxedLaneselect => exec_op!(executor; ternary Value128 => Value128, |a, b, c| Value128::i16x8_relaxed_laneselect(a, b, c)), + I32x4RelaxedLaneselect => exec_op!(executor; ternary Value128 => Value128, |a, b, c| Value128::i32x4_relaxed_laneselect(a, b, c)), + I64x2RelaxedLaneselect => exec_op!(executor; ternary Value128 => Value128, |a, b, c| Value128::i64x2_relaxed_laneselect(a, b, c)), + I16x8RelaxedQ15mulrS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_relaxed_q15mulr_s(b)), + I16x8RelaxedDotI8x16I7x16S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_relaxed_dot_i8x16_i7x16_s(b)), + I32x4RelaxedDotI8x16I7x16AddS => exec_op!(executor; ternary Value128 => Value128, |a, b, c| a.i32x4_relaxed_dot_i8x16_i7x16_add_s(b, c)), + F32x4Ceil => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_ceil()), + F64x2Ceil => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_ceil()), + F32x4Floor => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_floor()), + F64x2Floor => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_floor()), + F32x4Trunc => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_trunc()), + F64x2Trunc => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_trunc()), + F32x4Nearest => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_nearest()), + F64x2Nearest => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_nearest()), + F32x4Abs => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_abs()), + F64x2Abs => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_abs()), + F32x4Neg => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_neg()), + F64x2Neg => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_neg()), + F32x4Sqrt => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_sqrt()), + F64x2Sqrt => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_sqrt()), + F32x4Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_add(b)), + F64x2Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_add(b)), + F32x4Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_sub(b)), + F64x2Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_sub(b)), + F32x4Mul => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_mul(b)), + F64x2Mul => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_mul(b)), + F32x4Div => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_div(b)), + F64x2Div => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_div(b)), + F32x4Min => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_min(b)), + F64x2Min => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_min(b)), + F32x4Max => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_max(b)), + F64x2Max => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_max(b)), + F32x4PMin => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_pmin(b)), + F32x4PMax => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_pmax(b)), + F64x2PMin => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_pmin(b)), + F64x2PMax => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_pmax(b)), + F32x4RelaxedMadd => exec_op!(executor; ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_madd(b, c)), + F32x4RelaxedNmadd => exec_op!(executor; ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_nmadd(b, c)), + F64x2RelaxedMadd => exec_op!(executor; ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_madd(b, c)), + F64x2RelaxedNmadd => exec_op!(executor; ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_nmadd(b, c)), + F32x4RelaxedMin => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_relaxed_min(b)), + F32x4RelaxedMax => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_relaxed_max(b)), + F64x2RelaxedMin => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_relaxed_min(b)), + F64x2RelaxedMax => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_relaxed_max(b)), + I32x4TruncSatF32x4S => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_s()), + I32x4TruncSatF32x4U => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_u()), + F32x4ConvertI32x4S => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_convert_i32x4_s()), + F32x4ConvertI32x4U => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_convert_i32x4_u()), + F64x2ConvertLowI32x4S => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_s()), + F64x2ConvertLowI32x4U => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_u()), + F32x4DemoteF64x2Zero => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_demote_f64x2_zero()), + F64x2PromoteLowF32x4 => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_promote_low_f32x4()), + I32x4TruncSatF64x2SZero => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_s_zero()), + I32x4TruncSatF64x2UZero => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_u_zero()), + I32x4RelaxedTruncF32x4S => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_s()), + I32x4RelaxedTruncF32x4U => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_u()), + I32x4RelaxedTruncF64x2SZero => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_s_zero()), + I32x4RelaxedTruncF64x2UZero => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()), + } + }; +} diff --git a/crates/tinywasm/src/interpreter/executor/mod.rs b/crates/tinywasm/src/interpreter/executor/mod.rs new file mode 100644 index 0000000..48a99a6 --- /dev/null +++ b/crates/tinywasm/src/interpreter/executor/mod.rs @@ -0,0 +1,1561 @@ +use core::convert::identity; + +#[cfg(not(feature = "std"))] +#[allow(unused_imports)] +use super::no_std_floats::NoStdFloatExt; + +use alloc::boxed::Box; +use alloc::vec::Vec; + +use interpreter::stack::{CallFrame, ValueStack}; +use tinywasm_types::*; + +use super::ExecState; +use super::num_helpers::*; +use super::values::*; +use crate::engine::FuelPolicy; +use crate::func::HostFunction; +use crate::interpreter::Value128; +use crate::*; + +#[macro_use] +mod instructions; + +#[cfg(not(feature = "nightly-tail-calls"))] +mod dispatch; +#[cfg(feature = "nightly-tail-calls")] +mod dispatch_become; + +const CHECKPOINT_INTERVAL: u32 = 128; +const FUEL_COST_CALL_TOTAL: u32 = 5; + +struct ExecError(Box); + +type ExecResult = core::result::Result; + +impl From for ExecError { + #[cold] + fn from(trap: Trap) -> Self { + Self(Box::new(Error::Trap(trap))) + } +} + +impl From for ExecError { + #[cold] + fn from(error: Error) -> Self { + Self(Box::new(error)) + } +} + +impl From for Error { + #[cold] + fn from(error: ExecError) -> Self { + *error.0 + } +} + +#[derive(Clone, Copy)] +struct ExecFlow(usize); + +impl ExecFlow { + const COMPLETE: Self = Self(usize::MAX); + + #[inline(always)] + fn next(instr_ptr: usize) -> Self { + debug_assert_ne!(instr_ptr, Self::COMPLETE.0); + Self(instr_ptr) + } + + #[inline(always)] + fn next_instr_ptr(self) -> Option { + (self.0 != Self::COMPLETE.0).then_some(self.0) + } +} + +pub(crate) struct Executor<'store> { + cf: CallFrame, + func: Shared, + module: ModuleInstance, + store: &'store mut Store, + call_stack_base: u32, + mem0: MemAddr, + fuel_metered: bool, + #[cfg(feature = "nightly-tail-calls")] + completed: bool, +} + +impl<'store> Executor<'store> { + pub(crate) fn new(store: &'store mut Store, cf: CallFrame, call_stack_base: u32) -> Self { + let wasm_func = store.state.funcs.wasm(cf.func_addr); + let module = store.get_module_instance(wasm_func.owner).expect("invalid module instance").clone(); + let mem0 = module.mem0_addr(); + Self { + module, + cf, + func: wasm_func.func.clone(), + store, + call_stack_base, + mem0, + fuel_metered: false, + #[cfg(feature = "nightly-tail-calls")] + completed: false, + } + } + + /// Resolves a module-local memory index to its store address, caching the common memory-0 case. + #[inline(always)] + fn mem_addr(&self, idx: MemAddr) -> MemAddr { + if idx == 0 { self.mem0 } else { self.module.resolve_mem_addr(idx) } + } + + /// Switches the executor to another module, keeping the cached memory-0 address in sync. + #[inline] + fn set_module(&mut self, owner: ModuleInstanceId) { + self.module = self.store.get_module_instance(owner).expect("invalid module instance").clone(); + self.mem0 = self.module.mem0_addr(); + } + + #[inline(always)] + fn charge_call_fuel(&mut self, total_fuel_cost: u32) { + if self.fuel_metered { + let extra = match self.store.engine.config().fuel_policy { + FuelPolicy::PerInstruction => 0, + FuelPolicy::Weighted => total_fuel_cost.saturating_sub(1), + }; + + self.store.execution_fuel = self.store.execution_fuel.saturating_sub(extra); + } + } + + #[inline(always)] + fn exec_jump_if_ref(&mut self) -> bool { + let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); + if is_null { + ValueRef::stack_pop(&mut self.store.value_stack); + } + is_null == ON_NULL + } + + #[inline(always)] + fn exec_br_on_cast(&self, index: Operand64Idx<(u32, u32)>) -> Option { + let operand = index.resolve(&self.func.data); + let ty = RefType::from_bits(operand.b()).expect("invalid ref type"); + (self.exec_ref_matches(ty) == ON_MATCH).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_if_local( + &self, + local: LocalAddr, + ) -> bool { + (T::local_get(&self.store.value_stack, &self.cf, local) == T::default()) == ON_ZERO + } + + #[inline(always)] + fn exec_jump_cmp_stack_const32(&mut self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + packed.op.cmp(i32::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_stack_const64(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + packed.op.cmp(i64::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_stack_local32(&mut self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::stack_pop(&mut self.store.value_stack); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_stack_local64(&mut self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i64::stack_pop(&mut self.store.value_stack); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_binop_local_const_jump(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let value = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { + packed.op.exec(value as u32, operand.value() as u32) as i32 + }); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_binop_local_const_jump_cmp_local( + &mut self, + packed: PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>, + ) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { + packed.op.0.exec(value as u32, operand.value() as u32) as i32 + }); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); + packed.op.1.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_binop_stack_const_tee_local_jump( + &mut self, + packed: PackedOp128, + ) -> Result, Trap> { + let operand = packed.index.resolve(&self.func.data); + let value = i32::stack_update(&mut self.store.value_stack, |lhs| { + packed.op.exec(lhs as u32, operand.value() as u32) as i32 + }); + i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value); + Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) + } + + #[inline(always)] + fn exec_binop_global_const_jump(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let global = self.module.resolve_global_addr(operand.global()); + let value = i32::global_update(&mut self.store.state.globals, global, |value| { + packed.op.exec(value as u32, operand.value() as u32) as i32 + }); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_inc_local_jump(&mut self, index: Operand128Idx) -> Option { + let operand = index.resolve(&self.func.data); + let value = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { + value.wrapping_add(operand.value()) + }); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_inc_stack_tee_local_jump( + &mut self, + index: Operand128Idx, + ) -> Result, Trap> { + let operand = index.resolve(&self.func.data); + let value = i32::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(operand.value())); + i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value); + Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) + } + + #[inline(always)] + fn exec_inc_global_jump(&mut self, index: Operand128Idx) -> Option { + let operand = index.resolve(&self.func.data); + let global = self.module.resolve_global_addr(operand.global()); + let value = + i32::global_update(&mut self.store.state.globals, global, |value| value.wrapping_add(operand.value())); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_inc_local_jump_cmp_local(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { + value.wrapping_add(operand.value()) + }); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_const32(&self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, operand.b()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_const64(&self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, i64::from(operand.b())).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_local32(&self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b()); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_local64(&self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b()); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + fn exec_i64_add128(&mut self) -> Result<(), Trap> { + let b_hi = i64::stack_pop(&mut self.store.value_stack); + let b_lo = i64::stack_pop(&mut self.store.value_stack); + let a_hi = i64::stack_pop(&mut self.store.value_stack); + let a_lo = i64::stack_pop(&mut self.store.value_stack); + let lo = a_lo.wrapping_add(b_lo); + let carry = u64::from((lo as u64) < (a_lo as u64)); + let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64); + i64::stack_push(&mut self.store.value_stack, lo)?; + i64::stack_push(&mut self.store.value_stack, hi) + } + + fn exec_i64_sub128(&mut self) -> Result<(), Trap> { + let b_hi = i64::stack_pop(&mut self.store.value_stack); + let b_lo = i64::stack_pop(&mut self.store.value_stack); + let a_hi = i64::stack_pop(&mut self.store.value_stack); + let a_lo = i64::stack_pop(&mut self.store.value_stack); + let lo = a_lo.wrapping_sub(b_lo); + let borrow = u64::from((a_lo as u64) < (b_lo as u64)); + let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64); + i64::stack_push(&mut self.store.value_stack, lo)?; + i64::stack_push(&mut self.store.value_stack, hi) + } + + fn exec_i64_mul_wide_s(&mut self) -> Result<(), Trap> { + let rhs = i64::stack_pop(&mut self.store.value_stack); + let lhs = i64::stack_pop(&mut self.store.value_stack); + let product = (lhs as i128).wrapping_mul(rhs as i128); + i64::stack_push(&mut self.store.value_stack, product as i64)?; + i64::stack_push(&mut self.store.value_stack, (product >> 64) as i64) + } + + fn exec_i64_mul_wide_u(&mut self) -> Result<(), Trap> { + let rhs = i64::stack_pop(&mut self.store.value_stack); + let lhs = i64::stack_pop(&mut self.store.value_stack); + let product = (lhs as u64 as u128).wrapping_mul(rhs as u64 as u128); + i64::stack_push(&mut self.store.value_stack, product as u64 as i64)?; + i64::stack_push(&mut self.store.value_stack, (product >> 64) as u64 as i64) + } + + #[inline(always)] + fn exec_simd_extract_lane( + &mut self, + lane: u8, + operation: impl FnOnce(Value128, u8) -> TO, + ) -> Result<(), Trap> { + let vector = Value128::stack_pop(&mut self.store.value_stack); + TO::stack_push(&mut self.store.value_stack, operation(vector, lane)) + } + + #[inline(always)] + fn exec_simd_replace_lane( + &mut self, + lane: u8, + operation: impl FnOnce(VALUE, Value128, u8) -> Value128, + ) -> Result<(), Trap> { + let vector = Value128::stack_pop(&mut self.store.value_stack); + let value = VALUE::stack_pop(&mut self.store.value_stack); + Value128::stack_push(&mut self.store.value_stack, operation(value, vector, lane)) + } + + fn exec_simd_shuffle(&mut self, lanes: Value128) -> Result<(), Trap> { + let rhs = Value128::stack_pop(&mut self.store.value_stack); + let lhs = Value128::stack_pop(&mut self.store.value_stack); + Value128::stack_push(&mut self.store.value_stack, Value128::i8x16_shuffle(lhs, rhs, lanes)) + } + + #[inline(always)] + fn exec_local_set_pop(&mut self, local: LocalAddr) { + let value = T::stack_pop(&mut self.store.value_stack); + T::local_set(&mut self.store.value_stack, &self.cf, local, value); + } + + #[inline(always)] + fn exec_local_tee(&mut self, local: LocalAddr) { + let value = T::stack_peek(&self.store.value_stack); + T::local_set(&mut self.store.value_stack, &self.cf, local, value); + } + + #[inline(always)] + fn exec_global_get(&mut self, global: GlobalAddr) -> Result<(), Trap> { + let addr = self.module.resolve_global_addr(global); + let value = T::global_get(&self.store.state.globals, addr); + T::stack_push(&mut self.store.value_stack, value) + } + + #[inline(always)] + fn exec_global_set(&mut self, global: GlobalAddr) { + let addr = self.module.resolve_global_addr(global); + let value = T::stack_pop(&mut self.store.value_stack); + T::global_set(&mut self.store.state.globals, addr, value); + } + + #[inline(always)] + fn exec_global_tee(&mut self, global: GlobalAddr) { + let addr = self.module.resolve_global_addr(global); + let value = T::stack_peek(&self.store.value_stack); + T::global_set(&mut self.store.state.globals, addr, value); + } + + #[inline(always)] + fn exec_binop_result( + &mut self, + dst: Option, + val: T, + ) -> Result<(), Trap> { + if let Some(dst) = dst { + T::local_set(&mut self.store.value_stack, &self.cf, dst, val); + } + if PUSH { T::stack_push(&mut self.store.value_stack, val) } else { Ok(()) } + } + + #[inline(always)] + fn exec_binop_local_local( + &mut self, + lhs: LocalAddr, + rhs: LocalAddr, + destination: Option, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); + let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs); + self.exec_binop_result::(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_local_local_indexed( + &mut self, + index: Operand64Idx<(u16, u16, u16)>, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let operands = index.resolve(&self.func.data); + self.exec_binop_local_local::(operands.a(), operands.b(), Some(operands.c()), op) + } + + #[inline(always)] + fn exec_binop_local_const( + &mut self, + lhs: LocalAddr, + rhs: T, + destination: Option, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); + self.exec_binop_result::(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_global_const( + &mut self, + lhs: GlobalAddr, + rhs: T, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let lhs = T::global_get(&self.store.state.globals, self.module.resolve_global_addr(lhs)); + T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_cmp_local_local(&mut self, lhs: LocalAddr, rhs: LocalAddr, op: CmpOp) -> Result<(), Trap> + where + T: InternalValue, + CmpOp: CmpOpExt, + { + let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); + let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs); + i32::stack_push(&mut self.store.value_stack, i32::from(op.cmp(lhs, rhs))) + } + + #[inline(always)] + fn exec_binop_stack_global( + &mut self, + global: GlobalAddr, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let addr = self.module.resolve_global_addr(global); + let rhs = T::global_get(&self.store.state.globals, addr); + T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs)); + Ok(()) + } + + #[inline(always)] + fn exec_binop_stack_local( + &mut self, + local: LocalAddr, + destination: Option, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let rhs = T::local_get(&self.store.value_stack, &self.cf, local); + let lhs = T::stack_pop(&mut self.store.value_stack); + self.exec_binop_result::(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_const_tee( + &mut self, + rhs: T, + destination: LocalAddr, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let value = T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs)); + T::local_set(&mut self.store.value_stack, &self.cf, destination, value); + Ok(()) + } + + #[inline(always)] + fn exec_mul_acc_local( + &mut self, + accumulator: LocalAddr, + multiply: fn(T, T) -> T, + add: fn(T, T) -> T, + ) { + let rhs = T::stack_pop(&mut self.store.value_stack); + let lhs = T::stack_pop(&mut self.store.value_stack); + let product = multiply(lhs, rhs); + T::local_update(&mut self.store.value_stack, &self.cf, accumulator, |value| add(product, value)); + } + + fn exec_branch_table(&mut self, index: Operand128Idx) -> usize { + let v = index.resolve(&self.func.data); + let idx = ::stack_pop(&mut self.store.value_stack); + let target_ip = if idx >= 0 && (idx as u32) < v.size() { + self.func.data.branch_table_targets.get((v.start() + idx as u32) as usize).copied().unwrap_or(v.target()) + } else { + v.target() + }; + + target_ip as usize + } + + fn create_exception(&mut self, tag_index: TagAddr) -> Result { + let tag_addr = self.module.resolve_tag_addr(tag_index); + let type_addr = self.store.state.get_tag(tag_addr).type_addr; + let payload_len = self.store.state.get_canonical_func_type(type_addr).params().len(); + self.store.state.gc.check_allocation(payload_len, true)?; + let mut payload = Vec::new(); + cold_err!(payload.try_reserve_exact(payload_len)).map_err(|_| Trap::OutOfMemory)?; + let value_stack = &mut self.store.value_stack; + for index in (0..payload_len).rev() { + let ty = self.store.state.get_canonical_func_type(type_addr).params()[index]; + payload.push(match ty { + WasmType::I32 | WasmType::F32 => RuntimeValue::Value32(Value32::stack_pop(value_stack)), + WasmType::I64 | WasmType::F64 => RuntimeValue::Value64(Value64::stack_pop(value_stack)), + WasmType::V128 => RuntimeValue::Value128(Value128::stack_pop(value_stack)), + WasmType::Ref(_) => RuntimeValue::ValueRef(ValueRef::stack_pop(value_stack)), + }); + } + payload.reverse(); + let roots = (&self.store.value_stack.stack_32).into_iter().copied().map(ValueRef::from_raw); + self.store.state.alloc_exception(tag_addr, payload, roots) + } + + fn exec_throw(&mut self, tag_index: TagAddr, instr_ptr: usize) -> ExecResult { + let exception = self.create_exception(tag_index)?; + self.throw_exception(exception, instr_ptr) + } + + fn exec_throw_ref(&mut self, instr_ptr: usize) -> ExecResult { + let exception = ValueRef::stack_pop(&mut self.store.value_stack); + if exception.is_null() { + return Err(Trap::NullReference.into()); + } + self.throw_exception(exception, instr_ptr) + } + + fn throw_exception(&mut self, exception: ValueRef, protected_ip: usize) -> ExecResult { + match self.dispatch_exception(exception, protected_ip)? { + Some(landing_pad) => Ok(ExecFlow::next(landing_pad)), + None => match self.store.root_exception(exception) { + Ok(exception) => Err(Error::Exception(exception).into()), + Err(error) => Err(error.into()), + }, + } + } + + fn matching_catch(&self, protected_ip: usize, tag_addr: TagAddr) -> Option { + let handlers = &self.func.data.exception_handlers; + let end = handlers.partition_point(|handler| handler.start_ip as usize <= protected_ip); + handlers[..end] + .iter() + .rev() + .filter(|handler| protected_ip < handler.end_ip as usize) + .flat_map(|handler| handler.catches.iter().copied()) + .find(|catch| match catch { + ExceptionCatch::Tag { tag, .. } => self.module.resolve_tag_addr(*tag) == tag_addr, + ExceptionCatch::All { .. } => true, + }) + } + + #[inline(always)] + fn switch_to_frame(&mut self, frame: CallFrame) { + let previous = core::mem::replace(&mut self.cf, frame); + if previous.func_addr == self.cf.func_addr { + return; + } + + let wasm_func = self.store.state.funcs.wasm(self.cf.func_addr); + if !Shared::ptr_eq(&self.func, &wasm_func.func) { + self.func = wasm_func.func.clone(); + } + if wasm_func.owner != self.module.id() { + self.set_module(wasm_func.owner); + } + } + + fn dispatch_exception(&mut self, exception: ValueRef, mut protected_ip: usize) -> Result, Trap> { + let object = self.store.state.gc.get(exception).ok_or(Trap::InvalidReference)?; + let crate::store::GcObjectKind::Exception(tag_addr) = object.kind else { + return Err(Trap::InvalidReference); + }; + loop { + if let Some(catch) = self.matching_catch(protected_ip, tag_addr) { + let (landing_pad, base, with_ref, include_payload) = match catch { + ExceptionCatch::Tag { landing_pad, base, with_ref, .. } => (landing_pad, base, with_ref, true), + ExceptionCatch::All { landing_pad, base, with_ref } => (landing_pad, base, with_ref, false), + }; + let stack_base = self.cf.stack_base(); + let target = interpreter::stack::StackBase { + s32: stack_base.s32 + base.c32 as u32, + s64: stack_base.s64 + base.c64 as u32, + s128: stack_base.s128 + base.c128 as u32, + }; + self.store.value_stack.truncate_to_base(target); + if include_payload { + let Store { state, value_stack, .. } = self.store; + let object = state.gc.get(exception).ok_or(Trap::InvalidReference)?; + for value in object.values.iter().copied() { + value_stack.push_dyn(value)?; + } + } + if with_ref { + ValueRef::stack_push(&mut self.store.value_stack, exception)?; + } + return Ok(Some(landing_pad as usize)); + } + + self.store.value_stack.truncate_to_base(self.cf.locals_base); + let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { + return Ok(None); + }; + self.switch_to_frame(caller); + protected_ip = self.cf.instr_ptr.checked_sub(1).expect("invalid caller IP"); + } + } + + fn exec_call_host( + &mut self, + host_func: HostFunction, + type_addr: TypeAddr, + return_instr_ptr: usize, + ) -> ExecResult { + if let Some(host_func) = host_func.typed_callback() { + cold_err!(host_func.call_stack(self.store, self.module.id(), type_addr)) + .map_err(|error| Trap::HostFunction(Box::new(error)))?; + if TAIL { + return Ok(self.exec_return()); + } + return Ok(ExecFlow::next(return_instr_ptr)); + } + + let (param_count, result_count, base) = { + let ty = self.store.state.get_canonical_func_type(type_addr); + (ty.params().len(), ty.results().len(), self.store.value_stack.base_before(ty.params().iter().collect())) + }; + let module_id = self.module.id(); + self.store + .with_scratch_values(param_count + result_count, |store, values| { + let host_values = store.stack_value_iter(type_addr, crate::store::FuncValueTypes::Params, base)?; + for (slot, value) in values[..param_count].iter_mut().zip(host_values) { + *slot = value; + } + store.value_stack.truncate_to_base(base); + let (params, results) = values.split_at_mut(param_count); + host_func + .call_values(store, module_id, type_addr, params, results) + .map_err(|error| Error::Trap(Trap::HostFunction(Box::new(error))))?; + store.push_wasm_values(results) + }) + .map_err(|error| match error { + Error::Trap(trap) => trap, + other => Trap::HostFunction(Box::new(other)), + })?; + if TAIL { Ok(self.exec_return()) } else { Ok(ExecFlow::next(return_instr_ptr)) } + } + + fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> ExecResult { + self.charge_call_fuel(FUEL_COST_CALL_TOTAL); + let addr = self.module.resolve_func_addr(v); + if self.store.state.funcs.is_host(addr) { + let host_func = self.store.state.funcs.host(addr); + let type_addr = host_func.type_addr; + let host_func = host_func.func.clone(); + self.exec_call_host::(host_func, type_addr, return_instr_ptr) + } else { + self.exec_call_wasm::(addr, return_instr_ptr) + } + } + + fn exec_return_call_direct(&mut self, v: u32) -> ExecResult { + self.charge_call_fuel(FUEL_COST_CALL_TOTAL); + let addr = self.module.resolve_func_addr(v); + if self.store.state.funcs.is_host(addr) { + let host_func = self.store.state.funcs.host(addr); + let type_addr = host_func.type_addr; + let host_func = host_func.func.clone(); + self.exec_call_host::(host_func, type_addr, 0) + } else { + self.exec_call_wasm::(addr, 0) + } + } + + fn exec_call_self(&mut self, return_instr_ptr: usize) -> ExecResult<()> { + self.charge_call_fuel(FUEL_COST_CALL_TOTAL); + let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else { + return cold!(Err(Trap::CallStackOverflow.into())); + }; + let new = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); + self.store.call_stack.push(core::mem::replace(&mut self.cf, new), return_instr_ptr)?; + Ok(()) + } + + fn exec_return_call_self(&mut self) -> ExecResult<()> { + self.charge_call_fuel(FUEL_COST_CALL_TOTAL); + + self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.params); + let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else { + return cold!(Err(Trap::CallStackOverflow.into())); + }; + self.cf = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); + Ok(()) + } + + fn exec_call_indirect( + &mut self, + index: Operand64Idx<(u32, u32)>, + return_instr_ptr: usize, + ) -> ExecResult { + let operand = index.resolve(&self.func.data); + let type_addr = operand.a(); + let table_addr = operand.b(); + self.charge_call_fuel(FUEL_COST_CALL_TOTAL); + // verify that the table is of the right type, this should be validated by the parser already + let table_addr = self.module.resolve_table_addr(table_addr); + let table_idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; + let table = self.store.state.get_table(table_addr); + + let Ok(table) = table.get(table_idx) else { + return cold!(Err(Trap::UndefinedElement { index: table_idx }.into())); + }; + + let Some(func_ref) = table.addr() else { + return cold!(Err(Trap::UninitializedElement { index: table_idx }.into())); + }; + + self.exec_typed_call::(func_ref, self.module.resolve_type_addr(type_addr), return_instr_ptr) + } + + fn exec_typed_call( + &mut self, + func_addr: FuncAddr, + expected_type_addr: TypeAddr, + return_instr_ptr: usize, + ) -> ExecResult { + let type_addr = self.store.state.funcs.type_addr(func_addr); + if !self.store.state.type_addr_is_subtype(type_addr, expected_type_addr) { + return cold!(Err(Trap::IndirectCallTypeMismatch { + actual: Box::new(self.store.state.get_canonical_func_type(type_addr).clone()), + expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), + } + .into())); + } + if self.store.state.funcs.is_host(func_addr) { + let host_func = self.store.state.funcs.host(func_addr); + let host_func = host_func.func.clone(); + return self.exec_call_host::(host_func, type_addr, return_instr_ptr); + } + + self.exec_call_wasm::(func_addr, return_instr_ptr) + } + + #[inline(always)] + fn exec_call_wasm( + &mut self, + func_addr: FuncAddr, + return_instr_ptr: usize, + ) -> ExecResult { + let wasm_func = self.store.state.funcs.wasm(func_addr); + let (params, locals, owner, next_func) = { + let next_func = (!Shared::ptr_eq(&self.func, &wasm_func.func)).then(|| wasm_func.func.clone()); + (wasm_func.func.params, wasm_func.func.locals, wasm_func.owner, next_func) + }; + if TAIL { + self.store.value_stack.truncate_keep_counts(self.cf.locals_base, params); + } + let locals_base = self.store.value_stack.enter_locals(¶ms, &locals)?; + if TAIL { + self.cf = CallFrame::new(func_addr, locals_base, locals); + } else { + self.store.call_stack.push(self.cf, return_instr_ptr)?; + self.cf = CallFrame::new(func_addr, locals_base, locals); + } + if let Some(next_func) = next_func { + self.func = next_func; + } + if owner != self.module.id() { + self.set_module(owner); + } + Ok(ExecFlow::next(0)) + } + + fn exec_call_ref(&mut self, type_addr: u32, return_instr_ptr: usize) -> ExecResult { + self.charge_call_fuel(FUEL_COST_CALL_TOTAL); + let func_ref = ValueRef::stack_pop(&mut self.store.value_stack); + let Some(func_addr) = func_ref.addr() else { + return cold!(Err(Trap::NullFunctionReference.into())); + }; + + self.exec_typed_call::(func_addr, self.module.resolve_type_addr(type_addr), return_instr_ptr) + } + + fn exec_return(&mut self) -> ExecFlow { + self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.results); + self.finish_return() + } + + #[inline(always)] + fn finish_return(&mut self) -> ExecFlow { + let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { + return ExecFlow::COMPLETE; + }; + let instr_ptr = caller.instr_ptr; + if caller.func_addr == self.cf.func_addr { + self.cf = caller; + } else { + self.switch_to_frame(caller); + } + ExecFlow::next(instr_ptr) + } + + fn exec_return_void(&mut self) -> ExecFlow { + self.store.value_stack.truncate_to_base(self.cf.locals_base); + self.finish_return() + } + + fn exec_return_32(&mut self) -> ExecFlow { + self.store.value_stack.stack_32.truncate_to_one_tail(self.cf.locals_base.s32 as usize); + self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize); + self.store.value_stack.stack_128.truncate_to(self.cf.locals_base.s128 as usize); + self.finish_return() + } + + fn exec_return_64(&mut self) -> ExecFlow { + self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize); + self.store.value_stack.stack_64.truncate_to_one_tail(self.cf.locals_base.s64 as usize); + self.store.value_stack.stack_128.truncate_to(self.cf.locals_base.s128 as usize); + self.finish_return() + } + + fn exec_return_128(&mut self) -> ExecFlow { + self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize); + self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize); + self.store.value_stack.stack_128.truncate_to_one_tail(self.cf.locals_base.s128 as usize); + self.finish_return() + } + + fn exec_store_local_local, const N: usize>( + &mut self, + index: Operand64Idx, + addr_local: u8, + value_local: u8, + ) -> Result<(), Trap> { + let memarg = index.resolve(&self.func.data); + let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local)); + let mem_addr = self.mem_addr(MemAddr::from(memarg.memory())); + let mem = self.store.state.get_mem_mut(mem_addr); + let addr = if mem.is_64bit() { + let base = u64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); + let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds { + offset: usize::MAX, + len: N, + max: mem.inner.len(), + }))?; + cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))? + } else { + let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); + cold_err!(mem.effective_addr::(base as usize, u64::from(memarg.offset())))? + }; + value.store_at(&mut mem.inner, addr) + } + + fn exec_inc_memory_local, const N: usize>( + &mut self, + index: Operand64Idx, + addr_local: u8, + increment: impl FnOnce(T) -> T, + ) -> Result<(), Trap> { + let memarg = index.resolve(&self.func.data); + let mem_addr = self.mem_addr(MemAddr::from(memarg.memory())); + let mem = self.store.state.get_mem_mut(mem_addr); + let addr = if mem.is_64bit() { + let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; + let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds { + offset: usize::MAX, + len: N, + max: mem.inner.len(), + }))?; + cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))? + } else { + let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); + cold_err!(mem.effective_addr::(base as usize, u64::from(memarg.offset())))? + }; + + let value = cold_err!(T::load_at(&mem.inner, addr))?; + increment(value).store_at(&mut mem.inner, addr) + } + + fn exec_fma_store< + T: InternalValue + MemValue + core::ops::Add + core::ops::Mul, + const N: usize, + >( + &mut self, + m: CompactMemoryArg, + ) -> Result<(), Trap> { + let rhs = T::stack_pop(&mut self.store.value_stack); + let lhs = T::stack_pop(&mut self.store.value_stack); + let acc = T::stack_pop(&mut self.store.value_stack); + let fma = acc + lhs * rhs; + let mem_addr = self.mem_addr(m.mem_addr()); + let mem = self.store.state.get_mem_mut(mem_addr); + let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; + cold_err!(fma.store_at(&mut mem.inner, addr)) + } + + fn exec_load_local< + LOAD: MemValue, + const N: usize, + TARGET: InternalValue, + const SET_LOCAL: bool, + const TEE: bool, + >( + &mut self, + index: Operand64Idx, + addr_local: u8, + dst_local: u8, + cast: impl Fn(LOAD) -> TARGET, + ) -> Result<(), Trap> { + let memarg = index.resolve(&self.func.data); + + let mem = self.store.state.get_mem(self.mem_addr(MemAddr::from(memarg.memory()))); + let base = if mem.is_64bit() { + let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; + cold_err!(usize::try_from(base)).map_err(|_| Trap::MemoryOutOfBounds { + offset: usize::MAX, + len: N, + max: mem.inner.len(), + })? + } else { + u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as usize + }; + + let addr = cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))?; + let value = cast(cold_err!(LOAD::load_at(&mem.inner, addr))?); + + if SET_LOCAL { + TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value); + } + if !SET_LOCAL || TEE { + TARGET::stack_push(&mut self.store.value_stack, value)?; + } + Ok(()) + } + + fn exec_ref_is_null(&mut self) -> Result<(), Trap> { + let is_null = i32::from(ValueRef::stack_pop(&mut self.store.value_stack).is_null()); + i32::stack_push(&mut self.store.value_stack, is_null) + } + + fn exec_ref_as_non_null(&mut self) -> Result<(), Trap> { + if ValueRef::stack_peek(&self.store.value_stack).is_null() { + return cold!(Err(Trap::NullReference)); + } + Ok(()) + } + + fn canonical_ref_type(&self, ty: RefType) -> RefType { + let Some(type_index) = ty.type_index() else { return ty }; + RefType::new_concrete(ty.is_nullable(), self.module.resolve_type_addr(type_index)) + } + + fn exec_ref_matches(&self, ty: RefType) -> bool { + let value = ValueRef::stack_peek(&self.store.value_stack); + self.store.state.value_ref_matches(value, self.canonical_ref_type(ty)) + } + + fn exec_ref_test(&mut self, ty: RefType) -> Result<(), Trap> { + let value = ValueRef::stack_pop(&mut self.store.value_stack); + let matches = self.store.state.value_ref_matches(value, self.canonical_ref_type(ty)); + i32::stack_push(&mut self.store.value_stack, i32::from(matches)) + } + + fn exec_ref_cast(&self, ty: RefType) -> Result<(), Trap> { + if !self.exec_ref_matches(ty) { + return cold!(Err(Trap::CastFailure)); + } + Ok(()) + } + + fn exec_i31_get(&mut self, signed: bool) -> Result<(), Trap> { + let value = ValueRef::stack_pop(&mut self.store.value_stack); + if value.is_null() { + return cold!(Err(Trap::NullI31Reference)); + } + let value = if signed { + value.i31_s().expect("validated i31.get operand") + } else { + value.i31_u().expect("validated i31.get operand") as i32 + }; + i32::stack_push(&mut self.store.value_stack, value) + } + + fn push_gc_object(&mut self, type_addr: TypeAddr, values: Vec) -> Result<(), Trap> { + let roots = (&self.store.value_stack.stack_32).into_iter().copied().map(ValueRef::from_raw); + let reference = self.store.state.alloc_gc_object(type_addr, values, roots)?; + ValueRef::stack_push(&mut self.store.value_stack, reference) + } + + fn exec_struct_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> { + let type_addr = self.module.resolve_type_addr(type_index); + let field_count = + self.store.state.get_type(type_addr).as_struct().expect("validated struct.new type").fields.len(); + self.store.state.check_gc_allocation(type_addr, field_count)?; + let mut values = Vec::new(); + cold_err!(values.try_reserve_exact(field_count)).map_err(|_| Trap::OutOfMemory)?; + if default { + values.extend( + self.store + .state + .get_type(type_addr) + .as_struct() + .expect("validated struct.new type") + .fields + .iter() + .map(|field| default_value(field.storage)), + ); + } else { + for index in (0..field_count).rev() { + let storage = self.store.state.get_type(type_addr).as_struct().unwrap().fields[index].storage; + values.push(pop_value(&mut self.store.value_stack, storage)); + } + values.reverse(); + } + self.push_gc_object(type_addr, values) + } + + fn exec_struct_get(&mut self, index: Operand64Idx<(u32, u32)>, signed: Option) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let field_index = operand.b(); + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.get type").fields + [field_index as usize] + .storage; + let object = self.store.state.gc_object(reference, type_addr)?; + let object = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; + let value = *object.values.get(field_index as usize).expect("validated struct field index"); + push_value(&mut self.store.value_stack, value, storage, signed) + } + + fn exec_struct_set(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let field_index = operand.b(); + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.set type").fields + [field_index as usize] + .storage; + let value = pop_value(&mut self.store.value_stack, storage); + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let object = self.store.state.gc_object(reference, type_addr)?; + self.store.state.gc.set(object, field_index as usize, value).expect("live struct field"); + Ok(()) + } + + fn exec_array_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> { + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new type").field.storage; + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + self.store.state.check_gc_allocation(type_addr, len)?; + let value = if default { default_value(storage) } else { pop_value(&mut self.store.value_stack, storage) }; + let mut values = Vec::new(); + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; + values.resize(len, value); + self.push_gc_object(type_addr, values) + } + + fn exec_array_new_fixed(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let len = operand.b(); + let type_addr = self.module.resolve_type_addr(type_index); + let storage = + self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; + let len = len as usize; + self.store.state.check_gc_allocation(type_addr, len)?; + let mut values = Vec::new(); + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; + for _ in 0..len { + values.push(pop_value(&mut self.store.value_stack, storage)); + } + values.reverse(); + self.push_gc_object(type_addr, values) + } + + fn exec_array_get(&mut self, type_index: TypeAddr, signed: Option) -> Result<(), Trap> { + let index = u32::stack_pop(&mut self.store.value_stack) as usize; + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.get type").field.storage; + let object = self.store.state.gc_object(reference, type_addr)?; + let object = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; + let value = *object.values.get(index).ok_or(Trap::ArrayOutOfBounds)?; + push_value(&mut self.store.value_stack, value, storage, signed) + } + + fn exec_array_set(&mut self, type_index: TypeAddr) -> Result<(), Trap> { + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.set type").field.storage; + let value = pop_value(&mut self.store.value_stack, storage); + let index = u32::stack_pop(&mut self.store.value_stack) as usize; + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let object = self.store.state.gc_object(reference, type_addr)?; + self.store.state.gc.set(object, index, value).ok_or(Trap::ArrayOutOfBounds) + } + + fn exec_array_len(&mut self) -> Result<(), Trap> { + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + if reference.is_null() { + return Err(Trap::NullArrayReference); + } + let object = self.store.state.gc.get(reference).ok_or(Trap::Other("invalid GC reference"))?; + let crate::store::GcObjectKind::Composite(type_addr) = object.kind else { + return Err(Trap::Other("GC reference is not an array")); + }; + if self.store.state.get_type(type_addr).as_array().is_none() { + return Err(Trap::Other("GC reference is not an array")); + } + i32::stack_push(&mut self.store.value_stack, object.values.len() as i32) + } + + fn exec_array_fill(&mut self, type_index: TypeAddr) -> Result<(), Trap> { + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.fill type").field.storage; + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let value = pop_value(&mut self.store.value_stack, storage); + let index = u32::stack_pop(&mut self.store.value_stack) as usize; + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let object = self.store.state.gc_object(reference, type_addr)?; + let object_ref = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; + let end = index.checked_add(len).filter(|end| *end <= object_ref.values.len()).ok_or(Trap::ArrayOutOfBounds)?; + self.store.state.gc.fill(object, index..end, value).expect("live array range"); + Ok(()) + } + + fn exec_array_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let dst_type = operand.a(); + let src_type = operand.b(); + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let src_index = u32::stack_pop(&mut self.store.value_stack) as usize; + let src = ValueRef::stack_pop(&mut self.store.value_stack); + let dst_index = u32::stack_pop(&mut self.store.value_stack) as usize; + let dst = ValueRef::stack_pop(&mut self.store.value_stack); + let dst_type = self.module.resolve_type_addr(dst_type); + let src_type = self.module.resolve_type_addr(src_type); + let dst_handle = self.store.state.gc_object(dst, dst_type)?; + let dst_len = self.store.state.gc.get_handle(dst_handle).expect("validated array").values.len(); + let src_handle = self.store.state.gc_object(src, src_type)?; + let src_object = self.store.state.gc.get_handle(src_handle).expect("validated array"); + let src_end = + src_index.checked_add(len).filter(|end| *end <= src_object.values.len()).ok_or(Trap::ArrayOutOfBounds)?; + dst_index.checked_add(len).filter(|end| *end <= dst_len).ok_or(Trap::ArrayOutOfBounds)?; + if src_handle == dst_handle { + self.store.state.gc.copy_within(dst_handle, src_index..src_end, dst_index).expect("live array range"); + return Ok(()); + } + self.store + .state + .gc + .copy_between(src_handle, src_index..src_end, dst_handle, dst_index) + .expect("live array ranges"); + Ok(()) + } + + fn exec_array_new_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let data_index = operand.b(); + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let src = u32::stack_pop(&mut self.store.value_stack) as usize; + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage; + let data_addr = self.module.resolve_data_addr(data_index); + let data = self.store.state.data[data_addr as usize].data.as_deref().unwrap_or(&[]); + data_range(storage, data, src, len)?; + self.store.state.check_gc_allocation(type_addr, len)?; + let values = decode_data(storage, data, src, len)?; + self.push_gc_object(type_addr, values) + } + + fn exec_array_new_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let elem_index = operand.b(); + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let src = u32::stack_pop(&mut self.store.value_stack) as usize; + let type_addr = self.module.resolve_type_addr(type_index); + let elem_addr = self.module.resolve_elem_addr(elem_index); + let items = self.store.state.elements[elem_addr as usize].items_range(src, len)?; + self.store.state.check_gc_allocation(type_addr, len)?; + let mut values = Vec::new(); + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; + values.extend(items.iter().copied().map(RuntimeValue::ValueRef)); + self.push_gc_object(type_addr, values) + } + + fn exec_array_init_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let data_index = operand.b(); + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let src = u32::stack_pop(&mut self.store.value_stack) as usize; + let dst = u32::stack_pop(&mut self.store.value_stack) as usize; + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage; + let object = self.store.state.gc_object(reference, type_addr)?; + let object_len = self.store.state.gc.get_handle(object).expect("validated array").values.len(); + dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; + let data = + self.store.state.data[self.module.resolve_data_addr(data_index) as usize].data.as_deref().unwrap_or(&[]); + let values = decode_data(storage, data, src, len)?; + self.store.state.gc.set_slice(object, dst, &values).expect("live array range"); + Ok(()) + } + + fn exec_array_init_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let elem_index = operand.b(); + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let src = u32::stack_pop(&mut self.store.value_stack) as usize; + let dst = u32::stack_pop(&mut self.store.value_stack) as usize; + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let type_addr = self.module.resolve_type_addr(type_index); + let object = self.store.state.gc_object(reference, type_addr)?; + let object_len = self.store.state.gc.get_handle(object).expect("validated array").values.len(); + dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; + let items = + self.store.state.elements[self.module.resolve_elem_addr(elem_index) as usize].items_range(src, len)?; + let mut values = Vec::new(); + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; + values.extend(items.iter().copied().map(RuntimeValue::ValueRef)); + self.store.state.gc.set_slice(object, dst, &values).expect("live array range"); + Ok(()) + } + + fn exec_memory_size(&mut self, addr: u32) -> Result<(), Trap> { + let mem = self.store.state.get_mem(self.mem_addr(addr)); + match mem.is_64bit() { + true => i64::stack_push(&mut self.store.value_stack, mem.page_count as i64), + false => i32::stack_push(&mut self.store.value_stack, mem.page_count as i32), + } + } + + fn exec_memory_grow(&mut self, addr: u32) -> Result<(), Trap> { + let mem_addr = self.mem_addr(addr); + let limiter = self.store.engine.config().resource_limiter.as_deref(); + let mem = self.store.state.get_mem_mut(mem_addr); + let is_64bit = mem.is_64bit(); + let pages_delta = match is_64bit { + true => i64::stack_pop(&mut self.store.value_stack), + false => i64::from(i32::stack_pop(&mut self.store.value_stack)), + }; + + let size = mem.grow(pages_delta, limiter)?.unwrap_or(-1); + match is_64bit { + true => i64::stack_push(&mut self.store.value_stack, size)?, + false => i32::stack_push(&mut self.store.value_stack, size as i32)?, + }; + + Ok(()) + } + + fn exec_memory_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let dst_mem = operand.a(); + let src_mem = operand.b(); + let dst_mem_addr = self.mem_addr(dst_mem); + let src_mem_addr = self.mem_addr(src_mem); + let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch(); + let src_arch = self.store.state.get_mem(src_mem_addr).kind.arch(); + let len_arch = + if dst_arch == MemoryArch::I32 || src_arch == MemoryArch::I32 { MemoryArch::I32 } else { MemoryArch::I64 }; + let size = self.store.value_stack.pop_memory_operand(len_arch)?; + let src = self.store.value_stack.pop_memory_operand(src_arch)?; + let dst = self.store.value_stack.pop_memory_operand(dst_arch)?; + + if dst_mem_addr == src_mem_addr { + // copy within the same memory + let mem = self.store.state.get_mem_mut(dst_mem_addr); + mem.copy_within(dst, src, size)?; + } else { + // copy between two memories + let (dst_memory, src_memory) = self.store.state.get_mems_mut(dst_mem_addr, src_mem_addr); + dst_memory.copy_from_memory(dst, src_memory, src, size)?; + } + Ok(()) + } + + fn exec_memory_fill(&mut self, addr: u32) -> Result<(), Trap> { + let mem_addr = self.mem_addr(addr); + let arch = self.store.state.get_mem(mem_addr).kind.arch(); + let size = self.store.value_stack.pop_memory_operand(arch)?; + let val = i32::stack_pop(&mut self.store.value_stack); + let dst = self.store.value_stack.pop_memory_operand(arch)?; + self.exec_memory_fill_impl(mem_addr, dst, val as u8, size) + } + + fn exec_memory_fill_const(&mut self, index: Operand128Idx) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let mem_addr = self.mem_addr(operand.memory()); + let arch = self.store.state.get_mem(mem_addr).kind.arch(); + let dst = self.store.value_stack.pop_memory_operand(arch)?; + self.exec_memory_fill_impl(mem_addr, dst, operand.byte(), operand.value() as u32 as usize) + } + + fn exec_memory_fill_impl(&mut self, mem_addr: MemAddr, dst: usize, val: u8, size: usize) -> Result<(), Trap> { + let mem = self.store.state.get_mem_mut(mem_addr); + let max = mem.inner.len(); + if mem.inner.fill(dst, size, val).is_none() { + return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max })); + } + Ok(()) + } + + fn exec_memory_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let data_index = operand.a(); + let mem_index = operand.b(); + let size = u32::stack_pop(&mut self.store.value_stack) as usize; + let offset = u32::stack_pop(&mut self.store.value_stack) as usize; + let mem_addr = self.mem_addr(mem_index); + let arch = self.store.state.get_mem(mem_addr).kind.arch(); + let dst = self.store.value_stack.pop_memory_operand(arch)?; + + let data = &self.store.state.data[self.module.resolve_data_addr(data_index) as usize]; + let mem = &mut self.store.state.memories[mem_addr as usize]; + let data_len = data.data.as_ref().map_or(0, |d| d.len()); + let mem_len = mem.inner.len(); + if offset.checked_add(size).is_none_or(|end| end > data_len) { + return cold!(Err(Trap::MemoryOutOfBounds { offset, len: size, max: data_len })); + } + if dst.checked_add(size).is_none_or(|end| end > mem_len) { + return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max: mem_len })); + } + + if size == 0 { + return Ok(()); + } + + let Some(data) = &data.data else { + return cold!(Err(Trap::MemoryOutOfBounds { offset: 0, len: 0, max: 0 })); + }; + + if mem.inner.write_all(dst, &data[offset..offset + size]).is_none() { + return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max: mem_len })); + } + Ok(()) + } + + fn exec_table_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let dst_table = operand.a(); + let src_table = operand.b(); + let dst_table_addr = self.module.resolve_table_addr(dst_table); + let src_table_addr = self.module.resolve_table_addr(src_table); + let dst_arch = self.store.state.get_table(dst_table_addr).kind.arch(); + let src_arch = self.store.state.get_table(src_table_addr).kind.arch(); + let len_arch = + if dst_arch == MemoryArch::I32 || src_arch == MemoryArch::I32 { MemoryArch::I32 } else { MemoryArch::I64 }; + let size = self.pop_table_operand(len_arch)?; + let src = self.pop_table_operand(src_arch)?; + let dst = self.pop_table_operand(dst_arch)?; + + if dst_table_addr == src_table_addr { + // copy within the same table + self.store.state.get_table_mut(dst_table_addr).copy_within(dst, src, size) + } else { + // copy between two tables + let (dst_table_ref, src_table_ref) = self.store.state.get_tables_mut(dst_table_addr, src_table_addr); + dst_table_ref.copy_from_slice(dst, src_table_ref.load(src, size)?) + } + } + + fn exec_mem_load_lane, const LOAD_SIZE: usize>( + &mut self, + arg: MemoryLaneArg, + ) -> Result<(), Trap> { + let m = arg.memory_arg_idx.resolve(&self.func.data); + let mem = self.store.state.get_mem(self.mem_addr(m.memory())); + let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; + let val = cold_err!(LOAD::load_at(&mem.inner, addr))?; + let offset = arg.lane as usize * LOAD_SIZE; + Value128::stack_update(&mut self.store.value_stack, |value| { + let mut bytes = value.to_mem_bytes(); + bytes[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); + Value128(bytes) + }); + Ok(()) + } + + #[inline(always)] + fn exec_mem_load, const LOAD_SIZE: usize, TARGET: InternalValue>( + &mut self, + m: Operand128, + cast: impl Fn(LOAD) -> TARGET, + ) -> Result<(), Trap> { + let mem = self.store.state.get_mem(self.mem_addr(m.memory())); + let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; + let value = cold_err!(LOAD::load_at(&mem.inner, addr))?; + TARGET::stack_push(&mut self.store.value_stack, cast(value)) + } + + #[inline(always)] + fn exec_mem_store_lane + Copy, const N: usize>(&mut self, arg: MemoryLaneArg) -> Result<(), Trap> { + let bytes = Value128::stack_pop(&mut self.store.value_stack).to_mem_bytes(); + let lane_offset = arg.lane as usize * N; + let mut val_bytes = [0u8; N]; + val_bytes.copy_from_slice(&bytes[lane_offset..lane_offset + N]); + let val = U::from_mem_bytes(val_bytes); + let m = arg.memory_arg_idx.resolve(&self.func.data); + let mem_addr = self.mem_addr(m.memory()); + let mem = self.store.state.get_mem_mut(mem_addr); + let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; + cold_err!(val.store_at(&mut mem.inner, addr))?; + Ok(()) + } + + #[inline(always)] + fn exec_mem_store, const N: usize>( + &mut self, + memory: Operand128, + cast: impl Fn(T) -> U, + ) -> Result<(), Trap> { + let val = cast(::stack_pop(&mut self.store.value_stack)); + self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), val) + } + + #[inline(always)] + fn exec_select_store, const N: usize>( + &mut self, + memory: Operand128, + ) -> Result<(), Trap> { + let condition = Value32::stack_pop(&mut self.store.value_stack); + let false_value = T::stack_pop(&mut self.store.value_stack); + let true_value = T::stack_pop(&mut self.store.value_stack); + let value = if condition == 0 { false_value } else { true_value }; + self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), value) + } + + #[inline(always)] + fn exec_mem_store_value, const N: usize>( + &mut self, + memory_addr: MemAddr, + offset: u64, + val: U, + ) -> Result<(), Trap> { + let mem = self.store.state.get_mem_mut(memory_addr); + let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; + let addr = cold_err!(mem.effective_addr::(base, offset))?; + cold_err!(val.store_at(&mut mem.inner, addr)) + } + + fn exec_table_get(&mut self, table_index: u32) -> Result<(), Trap> { + let table_addr = self.module.resolve_table_addr(table_index); + let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; + let value = *self.store.state.get_table(table_addr).get(idx)?; + ValueRef::stack_push(&mut self.store.value_stack, value) + } + + fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> { + let val = ValueRef::stack_pop(&mut self.store.value_stack); + let table_addr = self.module.resolve_table_addr(table_index); + let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; + let table = self.store.state.get_table_mut(table_addr); + table.set(idx, val) + } + + fn exec_table_size(&mut self, table_index: u32) -> Result<(), Trap> { + let table = self.store.state.get_table(self.module.resolve_table_addr(table_index)); + match table.kind.arch() { + MemoryArch::I32 => i32::stack_push(&mut self.store.value_stack, table.size() as i32), + MemoryArch::I64 => i64::stack_push(&mut self.store.value_stack, table.size() as i64), + } + } + + fn exec_table_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let elem_index = operand.a(); + let table_index = operand.b(); + let size = self.pop_table_operand(MemoryArch::I32)?; // n + let offset = self.pop_table_operand(MemoryArch::I32)?; // s + let table_addr = self.module.resolve_table_addr(table_index); + let dst = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; // d + let elem_addr = self.module.resolve_elem_addr(elem_index) as usize; + let elem = self.store.state.elements.get(elem_addr).ok_or_else(|| Trap::Other("element not found"))?; + let items = elem.items_range(offset, size)?; + + let table = + self.store.state.tables.get_mut(table_addr as usize).ok_or_else(|| Trap::Other("table not found"))?; + table.init(dst, items) + } + + fn exec_table_grow(&mut self, table_index: u32) -> Result<(), Trap> { + let table_addr = self.module.resolve_table_addr(table_index); + let arch = self.store.state.get_table(table_addr).kind.arch(); + let n = self.pop_table_operand(arch)?; + let val = ValueRef::stack_pop(&mut self.store.value_stack); + let limiter = self.store.engine.config().resource_limiter.as_deref(); + let table = self.store.state.get_table_mut(table_addr); + let sz = table.size(); + let grew = table.grow(n, val, limiter)?; + match (arch, grew) { + (MemoryArch::I32, true) => i32::stack_push(&mut self.store.value_stack, sz as i32), + (MemoryArch::I32, false) => i32::stack_push(&mut self.store.value_stack, -1), + (MemoryArch::I64, true) => i64::stack_push(&mut self.store.value_stack, sz as i64), + (MemoryArch::I64, false) => i64::stack_push(&mut self.store.value_stack, -1), + } + } + + fn exec_table_fill(&mut self, table_index: u32) -> Result<(), Trap> { + let table_addr = self.module.resolve_table_addr(table_index); + let arch = self.store.state.get_table(table_addr).kind.arch(); + let n = self.pop_table_operand(arch)?; + let val = ValueRef::stack_pop(&mut self.store.value_stack); + let i = self.pop_table_operand(arch)?; + self.store.state.get_table_mut(table_addr).fill(i, n, val) + } + + fn pop_table_operand(&mut self, arch: MemoryArch) -> Result { + let value = match arch { + MemoryArch::I32 => i32::stack_pop(&mut self.store.value_stack) as u32 as u64, + MemoryArch::I64 => i64::stack_pop(&mut self.store.value_stack) as u64, + }; + cold_err!(usize::try_from(value).map_err(|_| Trap::TableOutOfBounds { + offset: usize::MAX, + len: 1, + max: usize::MAX, + })) + } +} diff --git a/crates/tinywasm/src/interpreter/mod.rs b/crates/tinywasm/src/interpreter/mod.rs index 6e6912c..0f7ae20 100644 --- a/crates/tinywasm/src/interpreter/mod.rs +++ b/crates/tinywasm/src/interpreter/mod.rs @@ -27,11 +27,11 @@ pub(crate) struct InterpreterRuntime; impl InterpreterRuntime { pub(crate) fn exec(store: &mut Store, cf: CallFrame, call_stack_base: u32) -> Result<()> { - executor::Executor::::new(store, cf, call_stack_base).run_to_completion() + executor::Executor::new(store, cf, call_stack_base).run_to_completion() } pub(crate) fn exec_with_fuel(store: &mut Store, cf: CallFrame, fuel: u32) -> Result { - executor::Executor::::new(store, cf, 0).run_with_fuel(fuel) + executor::Executor::new(store, cf, 0).run_with_fuel(fuel) } #[cfg(feature = "std")] @@ -40,6 +40,6 @@ impl InterpreterRuntime { cf: CallFrame, time_budget: core::time::Duration, ) -> Result { - executor::Executor::::new(store, cf, 0).run_with_time_budget(time_budget) + executor::Executor::new(store, cf, 0).run_with_time_budget(time_budget) } } diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index a9c86b7..2bed835 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -24,6 +24,12 @@ pub(crate) struct Stack { dynamic: bool, } +#[cold] +#[inline(never)] +fn stack_underflow() -> ! { + unreachable!("ValueStack underflow, this is a bug") +} + impl Stack { pub(crate) fn new(config: StackConfig) -> Self { Self { data: Vec::with_capacity(config.initial_size), max_size: config.max_size, dynamic: config.dynamic } @@ -61,7 +67,7 @@ impl Stack { pub(crate) fn pop(&mut self) -> T { match self.data.pop() { Some(value) => value, - None => cold!(unreachable!("ValueStack underflow, this is a bug")), + None => cold!(stack_underflow()), } } @@ -69,7 +75,7 @@ impl Stack { pub(crate) fn last(&self) -> &T { match self.data.last() { Some(value) => value, - None => cold!(unreachable!("ValueStack underflow, this is a bug")), + None => cold!(stack_underflow()), } } @@ -150,7 +156,7 @@ impl Stack { let needed = count.wrapping_mul(2); if len < needed { - unreachable!("Stack underflow, this is a bug"); + cold!(stack_underflow()); } if !condition { diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index fe74fcf..b2b7eae 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -1,4 +1,6 @@ #![no_std] +#![cfg_attr(feature = "nightly-tail-calls", allow(incomplete_features))] +#![cfg_attr(feature = "nightly-tail-calls", feature(explicit_tail_calls))] #![doc(test( no_crate_inject, attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_assignments, unused_variables)) @@ -65,14 +67,17 @@ //! //! - **`full`:** Enables `archive`, `parallel-parser`, `parser`, and `validate`. Enabled by default. //! - **`std`:** Enables `std` and parsing from files and streams. Enabled by default. -//! - **`log`:** Enables integration with the `log` crate. Enabled by default. //! - **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default. //! - **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through `ParserOptions`. +//! - **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default. //! - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default. +//! - **`log`:** Enables integration with the `log` crate. Enabled by default. +//! - **`send`:** Makes stores and store-local handles movable across threads. +//! - **`portable-atomic`:** Supports targets without native atomic compare-and-swap. //! - **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results. Enabled by default. //! - **`debug`:** Derives `Debug` for runtime types. Enabled by default. -//! - **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default. //! - **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`). +//! - **`nightly-tail-calls`:** Uses Rust's unstable explicit tail calls for interpreter dispatch. Requires nightly Rust (recommended for maximum performance). //! - **`simd-x86`:** Enables x86-specific SIMD intrinsics and uses `unsafe` internally. //! //! With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`, diff --git a/crates/tinywasm/tests/resume_execution.rs b/crates/tinywasm/tests/resume_execution.rs index f7dff4f..431a696 100644 --- a/crates/tinywasm/tests/resume_execution.rs +++ b/crates/tinywasm/tests/resume_execution.rs @@ -70,7 +70,7 @@ fn weighted_call_fuel_requires_more_rounds() -> Result<()> { let instance_weighted = ModuleInstance::instantiate(&mut weighted_store, &module, None)?; let func_weighted = instance_weighted.func::(&weighted_store, "fibonacci_recursive")?; - let fuel = 64; + let fuel = 512; let n = 20; let mut per_exec = func_per_instr.call_resumable(&mut per_instr_store, n)?; @@ -94,7 +94,7 @@ fn weighted_call_fuel_requires_more_rounds() -> Result<()> { }; assert_eq!(weighted_result, per_result); - assert!(weighted_rounds >= per_rounds, "weighted call fuel should not use fewer rounds than per-instruction"); + assert!(weighted_rounds > per_rounds, "weighted call fuel should require more rounds than per-instruction"); Ok(()) } diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm index 0fb3f39..967eda1 100644 Binary files a/examples/rust/src/print.twasm and b/examples/rust/src/print.twasm differ -- cgit v1.3.1 From 70b4ca7b8effb5b8f61c7a43ea15a77af0db0103 Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 14 Sep 2026 11:14:37 +0200 Subject: chore: update changelog, fix clippy issues Signed-off-by: Henry --- CHANGELOG.md | 64 +++++++++++++++++++++++++++--------------- crates/tinywasm/Cargo.toml | 2 +- crates/types/src/archive.rs | 4 +-- examples/rust.rs | 14 ++++----- examples/rust/Cargo.toml | 4 +-- examples/rust/build.sh | 4 +-- examples/rust/src/print.twasm | Bin 155 -> 155 bytes 7 files changed, 55 insertions(+), 37 deletions(-) (limited to 'examples/rust/src') diff --git a/CHANGELOG.md b/CHANGELOG.md index d674c30..a37655e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,23 +7,56 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +This release adds garbage collection and typed function reference support, single-pass parsing, and an optional tail-call dispatch backend. The internal instruction representation is now 8 bytes, down from 16, and pluggable memory backends were removed for performance reasons (however, `ResourceLimiter` was added to allow, reject, or trap memory allocation and growth requests). + +### Breaking Changes + +#### Functions and references + +- `Function::call` and `Function::call_resumable` now write to caller-provided result slices. Untyped host callbacks also receive a result slice and return `Result<()>`. +- Creating a `HostFunction` no longer requires a `Store`. Definitions require `Send + Sync` and can be reused across stores. +- Module instantiation now borrows `Imports`, allowing the same imports to be reused. +- `HostFunction::ty` and `WasmFunction::ty` were removed. Use `Function::ty(&Store)` for runtime types. +- Function and managed reference handles are tied to their originating `Store`. Managed references keep their referents live, so `WasmValue` is no longer `Copy`. +- Nullable typed references use `Option`, while bare typed references are non-null. +- `WasmTupleChain` was removed. Use direct tuples up to arity 20 or untyped functions for larger signatures. +- `ToWasmTypes` was renamed to `WasmTypes`, and `ToWasmType` was renamed to `WasmValueType`. +- Conversion traits now include `WasmTypes`, and `FromWasmValues::from_wasm_values` rejects unconsumed values directly. + +#### Memory, tables, and stores + +- Pluggable memory backends and `Config::with_trap_on_oom` were removed for performance reasons. Linear memory is always `Vec`-backed. Use `ResourceLimiter` to allow, reject, or trap memory allocation and growth requests. +- The `Memory`, `Table`, `Global`, and `Tag` constructors were renamed from `new` to `try_new`. +- Element types now use `RefType`, and module definitions use `TableDefinition { ty, init }`. +- `Table::grow` now returns `Result>`, matching `Memory::grow`. +- `Store::id` now returns `u32`, and `ModuleInstanceAddr` was renamed to `ModuleInstanceId`. + +#### Parser and archives + +- `Parser::new` now takes `ParserOptions`. Use `Parser::default()` for default settings. +- `Parser::with_options` was removed. +- `ParserOptions::optimize_rewrite` was renamed to `ParserOptions::optimize`. +- `ParserOptions::parser_threads` was renamed to `ParserOptions::threads`. +- The `.twasm` format changed. Regenerate archives created by earlier TinyWasm versions. + ### Added - Support for the typed function references, garbage collection, exception handling, and compact import section proposals. -- `ResourceLimiter` callbacks for memory and table allocation or growth -- A default `validate` Cargo feature & parser option to skip wasm validation -- Optional parse-time operand deduplication to reduce `.twasm` archive size -- Optional `send` support for moving stores and store-local handles across threads -- Optional portable atomic shared pointers and counters for targets without native compare-and-swap -- Optional `nightly-tail-calls` backend using Rust's unstable explicit tail calls for interpreter dispatch +- `ResourceLimiter` callbacks for memory and table allocation or growth. +- A default-enabled `validate` Cargo feature and a parser option to skip WebAssembly validation. +- Optional parse-time operand deduplication to reduce `.twasm` archive size. +- Optional `send` support for moving stores and store-local handles across threads. +- Optional portable atomic shared pointers and counters for targets without native compare-and-swap. +- Optional `nightly-tail-calls` backend using Rust's unstable explicit tail calls for interpreter dispatch. ### Changed +- Parsing now uses a single pass. - Typed functions now support tuples up to arity 20 and `[u8; 16]` values for `v128`. -- Module types now use one recursive type space. Runtime function types are available through `Function::ty(&Store)`. +- Module types now use one recursive type space. - Linear memory now uses contiguous `Vec`-backed storage. +- The internal instruction representation was reduced from 16 to 8 bytes. - The minimum supported Rust version increased from 1.95 to 1.98. -- The internal instruction represetaions size was reduced from 16 to 8 bytes. ### Fixed @@ -33,21 +66,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `memory.init` now performs correct bounds checks and operand lowering. - Memory64 now uses the correct default limits and host-size conversions, including on 32-bit targets. -### Breaking Changes - -- `Function::call` and `Function::call_resumable` now write to caller-provided result slices. Untyped host callbacks also receive a result slice and return `Result<()>`. -- Creating a `HostFunction` no longer requires a `Store`. Definitions require `Send + Sync` and can be reused across stores. Module instantiation now borrows `Imports` so the same imports can also be reused. -- `HostFunction::ty` and `WasmFunction::ty` were removed. Use `Function::ty(&Store)` for runtime types. -- Function and managed reference handles are tied to their originating `Store`. Managed references keep their referents live, so `WasmValue` is no longer `Copy`. Nullable typed references use `Option`, while bare typed references are non-null. -- The `Memory`, `Table`, `Global`, and `Tag` constructors were renamed from `new` to `try_new`. -- `Store::id` now returns `u32`, and `ModuleInstanceAddr` was renamed to `ModuleInstanceId`. -- Element types now use `RefType`, and module definitions use `TableDefinition { ty, init }`. `Table::grow` now returns `Result>`, matching `Memory::grow`. -- `Parser::new` now takes `ParserOptions`. Use `Parser::default()` for default settings. `Parser::with_options` was removed. -- Pluggable memory backends and `Config::with_trap_on_oom` were removed for performance reasons. Linear memory is always `Vec`-backed. Use `ResourceLimiter` to allow, reject, or trap memory allocation and growth requests. -- `WasmTupleChain` was removed. Use direct tuples up to arity 20 or untyped functions for larger signatures. -- `ToWasmTypes` was renamed to `WasmTypes`, and `ToWasmType` was renamed to `WasmValueType`. Conversion traits now include `WasmTypes`, and `FromWasmValues::from_wasm_values` rejects unconsumed values directly. -- The `.twasm` format changed. Regenerate archives created by earlier TinyWasm versions. - ## [0.10.0] - 2026-07-24 **All Commits**: https://github.com/explodingcamera/tinywasm/compare/v0.9.1...v0.10.0 diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 15744a3..d59d3dd 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -90,7 +90,7 @@ wat.workspace = true [features] default = ["full", "std"] -full = ["archive", "parallel-parser", "parser", "validate"] +full = ["archive", "debug", "parallel-parser", "parser", "validate"] log = ["dep:log", "tinywasm-parser?/log"] std = ["tinywasm-parser?/std", "tinywasm-types/std"] diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index bdce379..6a03605 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -7,7 +7,7 @@ use crate::Module; #[rustfmt::skip] const TWASM_MAGIC: [u8; 16] = [ TWASM_MAGIC_PREFIX[0], TWASM_MAGIC_PREFIX[1], TWASM_MAGIC_PREFIX[2], TWASM_MAGIC_PREFIX[3], TWASM_VERSION[0], TWASM_VERSION[1], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; const TWASM_MAGIC_PREFIX: &[u8; 4] = b"TWAS"; -const TWASM_VERSION: &[u8; 2] = b"06"; +const TWASM_VERSION: &[u8; 2] = b"05"; fn validate_magic(wasm: &[u8]) -> Result { if wasm.len() < TWASM_MAGIC.len() || &wasm[..TWASM_MAGIC_PREFIX.len()] != TWASM_MAGIC_PREFIX { @@ -97,7 +97,7 @@ mod tests { let module = Module::from(ModuleInner { funcs: Box::new([Shared::new(function)]), ..ModuleInner::default() }); let archive = module.serialize_twasm().expect("serialize archive"); - assert_eq!(&archive[..6], b"TWAS06"); + assert_eq!(&archive[..6], b"TWAS05"); let decoded = Module::try_from_twasm(&archive).expect("deserialize archive"); let function = &decoded.funcs[0]; diff --git a/examples/rust.rs b/examples/rust.rs index 24b3b73..77ba428 100644 --- a/examples/rust.rs +++ b/examples/rust.rs @@ -32,10 +32,10 @@ fn main() -> Result<()> { println!("Available examples:"); println!(" hello"); println!(" printi32"); - println!(" host_fn"); + println!(" host-fn"); println!(" fibonacci - calculate fibonacci(30)"); println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); - println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); + println!(" tinywasm-no-std - run a precompiled module inside of no_std tinywasm"); println!(" argon2id - run argon2id(1000, 2, 1)"); return Ok(()); } @@ -45,9 +45,9 @@ fn main() -> Result<()> { "printi32" => printi32()?, "fibonacci" => fibonacci()?, "tinywasm" => tinywasm()?, - "tinywasm_no_std" => tinywasm_no_std()?, + "tinywasm-no-std" => tinywasm_no_std()?, "argon2id" => argon2id()?, - "host_fn" => host_fn()?, + "host-fn" => host_fn()?, "all" => { println!("Running all examples"); println!("\nhello.wasm:"); @@ -58,11 +58,11 @@ fn main() -> Result<()> { fibonacci()?; println!("\ntinywasm.wasm:"); tinywasm()?; - println!("\ntinywasm_no_std.wasm:"); + println!("\ntinywasm-no-std.wasm:"); tinywasm_no_std()?; println!("argon2id.wasm:"); argon2id()?; - println!("\nhost_fn.wasm:"); + println!("\nhost-fn.wasm:"); host_fn()?; } _ => {} @@ -129,7 +129,7 @@ fn hello() -> Result<()> { } fn host_fn() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/host_fn.opt.wasm")?; + let module = tinywasm::parse_file("./examples/rust/out/host-fn.opt.wasm")?; let mut store = Store::default(); let bar = HostFunction::from(|_: FuncContext<'_>, (left, right): (i64, i32)| { diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index e0bdba6..74d38e7 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -11,7 +11,7 @@ name = "hello" path = "src/hello.rs" [[bin]] -name = "host_fn" +name = "host-fn" path = "src/host_fn.rs" [[bin]] @@ -23,7 +23,7 @@ name = "tinywasm" path = "src/tinywasm.rs" [[bin]] -name = "tinywasm_no_std" +name = "tinywasm-no-std" path = "src/tinywasm_no_std.rs" [[bin]] diff --git a/examples/rust/build.sh b/examples/rust/build.sh index 873028f..aa60d33 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash cd "$(dirname "$0")" || exit -bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "argon2id") +bins=("host-fn" "hello" "fibonacci" "print" "tinywasm" "argon2id") exclude_wat=("tinywasm") out_dir="./target/wasm32-unknown-unknown/wasm" dest_dir="out" @@ -17,7 +17,7 @@ cargo run --quiet --manifest-path "../../Cargo.toml" --package tinywasm-cli -- \ compile "src/print.wasm" --output "src/print.twasm" --force || exit # build no_std -RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features +RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm-no-std --no-default-features cp "$out_dir/tinywasm_no_std.wasm" "$dest_dir/" wasm-opt "$dest_dir/tinywasm_no_std.wasm" -o "$dest_dir/tinywasm_no_std.opt.wasm" -O3 $wasmopt_features diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm index 967eda1..8ad32e3 100644 Binary files a/examples/rust/src/print.twasm and b/examples/rust/src/print.twasm differ -- cgit v1.3.1