diff options
| -rw-r--r-- | .github/workflows/test.yaml | 8 | ||||
| -rw-r--r-- | CHANGELOG.md | 1 | ||||
| -rw-r--r-- | README.md | 8 | ||||
| -rw-r--r-- | crates/cli/src/wast_runner.rs | 22 | ||||
| -rw-r--r-- | crates/parser/Cargo.toml | 3 | ||||
| -rw-r--r-- | crates/tinywasm/Cargo.toml | 3 | ||||
| -rw-r--r-- | crates/tinywasm/src/interpreter/executor.rs | 2289 | ||||
| -rw-r--r-- | crates/tinywasm/src/interpreter/executor/dispatch.rs | 90 | ||||
| -rw-r--r-- | crates/tinywasm/src/interpreter/executor/dispatch_become.rs | 189 | ||||
| -rw-r--r-- | crates/tinywasm/src/interpreter/executor/instructions.rs | 690 | ||||
| -rw-r--r-- | crates/tinywasm/src/interpreter/executor/mod.rs | 1561 | ||||
| -rw-r--r-- | crates/tinywasm/src/interpreter/mod.rs | 6 | ||||
| -rw-r--r-- | crates/tinywasm/src/interpreter/stack/value_stack.rs | 12 | ||||
| -rw-r--r-- | crates/tinywasm/src/lib.rs | 9 | ||||
| -rw-r--r-- | crates/tinywasm/tests/resume_execution.rs | 4 | ||||
| -rw-r--r-- | examples/rust/src/print.twasm | bin | 155 -> 155 bytes |
16 files changed, 2577 insertions, 2318 deletions
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 @@ -55,6 +55,10 @@ jobs: 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)" args: "--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 @@ -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<wast::token::Id<'_>>) -> Option<Module> { - 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<String>) { @@ -71,21 +69,13 @@ impl ModuleRegistry { } fn get_idx(&self, module_id: Option<wast::token::Id<'_>>) -> Option<u32> { - 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<wast::token::Id<'_>>) -> Option<ModuleInstance> { - 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<WasmFunction>, - 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<ControlFlow<(), usize>> { - 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::<Value32, 4>(idx.resolve(&self.func.data))?, - SelectStore64(idx) => self.exec_select_store::<Value64, 8>(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::<false>(*idx, instr_ptr + 1), - CallRef(ty) => return self.exec_call_ref::<false>(*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::<true>(*idx, instr_ptr + 1), - ReturnCallRef(ty) => return self.exec_call_ref::<true>(*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::<true>() { return Ok(ControlFlow::Continue(ip as usize)) } }, - JumpIfRefNonNull(ip) => { let ip = *ip; if self.exec_jump_if_ref::<false>() { return Ok(ControlFlow::Continue(ip as usize)) } }, - BrOnCast(idx) => if let Some(ip) = self.exec_br_on_cast::<false>(*idx) { return Ok(ControlFlow::Continue(ip)) }, - BrOnCastFail(idx) => if let Some(ip) = self.exec_br_on_cast::<true>(*idx) { return Ok(ControlFlow::Continue(ip)) }, - JumpIfLocalZero32(arg) => if self.exec_jump_if_local::<Value32, true>(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalNonZero32(arg) => if self.exec_jump_if_local::<Value32, false>(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalZero64(arg) => if self.exec_jump_if_local::<Value64, true>(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalNonZero64(arg) => if self.exec_jump_if_local::<Value64, false>(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::<Value32>(*local_index), - LocalSet64(local_index) => self.exec_local_set_pop::<Value64>(*local_index), - LocalSet128(local_index) => self.exec_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) => { 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::<i32>(*acc, i32::wrapping_mul, i32::wrapping_add), - MulAccLocal64(acc) => self.exec_mul_acc_local::<i64>(*acc, i64::wrapping_mul, i64::wrapping_add), - FMulAccLocal32(acc) => self.exec_mul_acc_local::<f32>(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), - FMulAccLocal64(acc) => self.exec_mul_acc_local::<f64>(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), - BinOpLocalLocal32(op, a, b) => self.exec_binop_local_local::<Value32, true>(*a, *b, None, *op)?, - BinOpLocalLocal64(op, a, b) => self.exec_binop_local_local::<Value64, true>(*a, *b, None, *op)?, - BinOpLocalLocal128(op, a, b) => self.exec_binop_local_local::<Value128, true>(*a, *b, None, *op)?, - CmpLocalLocal32(op, a, b) => self.exec_cmp_local_local::<i32>(*a, *b, *op)?, - CmpLocalLocal64(op, a, b) => self.exec_cmp_local_local::<i64>(*a, *b, *op)?, - AddLocalLocalSet32(arg) => self.exec_binop_local_local::<Value32, false>(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, - AddLocalLocalTee32(arg) => self.exec_binop_local_local::<Value32, true>(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, - BinOpLocalLocalSet32(packed) => self.exec_binop_local_local_indexed::<Value32, false>(packed.index, packed.op)?, - BinOpLocalLocalSet64(packed) => self.exec_binop_local_local_indexed::<Value64, false>(packed.index, packed.op)?, - BinOpLocalLocalSet128(packed) => self.exec_binop_local_local_indexed::<Value128, false>(packed.index, packed.op)?, - BinOpLocalLocalTee32(packed) => self.exec_binop_local_local_indexed::<Value32, true>(packed.index, packed.op)?, - BinOpLocalLocalTee64(packed) => self.exec_binop_local_local_indexed::<Value64, true>(packed.index, packed.op)?, - BinOpLocalLocalTee128(packed) => self.exec_binop_local_local_indexed::<Value128, true>(packed.index, packed.op)?, - AddLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IAdd)?, - SubLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::ISub)?, - MulLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IMul)?, - AndLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IAnd)?, - ShrULocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IShrU)?, - BinOpLocalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value32, true>(v.a(), v.b(), None, packed.op)?; }, - BinOpLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value64, true>(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::<Value128, true>(v.a(), rhs, None, packed.op)?; }, - BinOpLocalConstSet32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value32, false>(v.a(), v.c(), Some(v.b()), packed.op)?; }, - BinOpLocalConstTee32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value32, true>(v.a(), v.c(), Some(v.b()), packed.op)?; }, - BinOpLocalConstSet64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value64, false>(v.a(), v.c(), Some(v.b()), packed.op)?; }, - BinOpLocalConstTee64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value64, true>(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::<Value128, false>(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::<Value128, true>(v.a(), rhs, Some(v.b()), packed.op)?; }, - BinOpStackLocal32(op, local) => self.exec_binop_stack_local::<Value32, true>(*local, None, *op)?, - BinOpStackLocalSet32(op, local, dst) => self.exec_binop_stack_local::<Value32, false>(*local, Some(*dst), *op)?, - BinOpStackLocalTee32(op, local, dst) => self.exec_binop_stack_local::<Value32, true>(*local, Some(*dst), *op)?, - BinOpStackLocal128(op, local) => self.exec_binop_stack_local::<Value128, true>(*local, None, *op)?, - BinOpStackGlobal32(op, global_index) => self.exec_binop_stack_global::<Value32>(*global_index, *op)?, - BinOpStackGlobal64(op, global_index) => self.exec_binop_stack_global::<Value64>(*global_index, *op)?, - BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::<Value32>(v.a(), v.b(), packed.op)?; }, - BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::<Value64>(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::<Value128>(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::<i32, 4>(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, - IncMemoryLocal64(arg) => self.exec_inc_memory_local::<i64, 8>(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, - StoreLocalLocal32(arg) => self.exec_store_local_local::<u32, 4>(arg.memory_arg_idx, arg.local1, arg.local2)?, - StoreLocalLocal64(arg) => self.exec_store_local_local::<i64, 8>(arg.memory_arg_idx, arg.local1, arg.local2)?, - StoreLocalLocal128(arg) => self.exec_store_local_local::<Value128, 16>(arg.memory_arg_idx, arg.local1, arg.local2)?, - LoadLocal32(arg) => self.exec_load_local::<i32, 4, _, false, false>(arg.memory_arg_idx, arg.local1, 0, identity)?, - LoadLocal64(arg) => self.exec_load_local::<i64, 8, _, false, false>(arg.memory_arg_idx, arg.local1, 0, identity)?, - LoadLocal8S32(arg) => self.exec_load_local::<i8, 1, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, - LoadLocal8U32(arg) => self.exec_load_local::<u8, 1, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, - LoadLocal16S32(arg) => self.exec_load_local::<i16, 2, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, - LoadLocal16U32(arg) => self.exec_load_local::<u16, 2, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, - LoadLocalTee32(arg) => self.exec_load_local::<i32, 4, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, - LoadLocalSet32(arg) => self.exec_load_local::<i32, 4, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, - LoadLocalTee8S32(arg) => self.exec_load_local::<i8, 1, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalTee8U32(arg) => self.exec_load_local::<u8, 1, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalTee16S32(arg) => self.exec_load_local::<i16, 2, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalTee16U32(arg) => self.exec_load_local::<u16, 2, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalSet8S32(arg) => self.exec_load_local::<i8, 1, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalSet8U32(arg) => self.exec_load_local::<u8, 1, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalSet16S32(arg) => self.exec_load_local::<i16, 2, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalSet16U32(arg) => self.exec_load_local::<u16, 2, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalTee128(arg) => self.exec_load_local::<Value128, 16, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, - LoadLocalSet128(arg) => self.exec_load_local::<Value128, 16, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, - AndConstTee32(arg) => self.exec_binop_const_tee::<Value32>(arg.value as u32, arg.local, BinOp::IAnd)?, - SubConstTee32(arg) => self.exec_binop_const_tee::<Value32>(arg.value as u32, arg.local, BinOp::ISub)?, - AndConstTee64(packed) => self.exec_binop_const_tee::<Value64>(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::IAnd)?, - SubConstTee64(packed) => self.exec_binop_const_tee::<Value64>(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::ISub)?, - LocalTee32(local_index) => self.exec_local_tee::<Value32>(*local_index), - LocalTee64(local_index) => self.exec_local_tee::<Value64>(*local_index), - LocalTee128(local_index) => self.exec_local_tee::<Value128>(*local_index), - GlobalGet32(global_index) => self.exec_global_get::<Value32>(*global_index)?, - GlobalGet64(global_index) => self.exec_global_get::<Value64>(*global_index)?, - GlobalGet128(global_index) => self.exec_global_get::<Value128>(*global_index)?, - GlobalSet32(global_index) => self.exec_global_set::<Value32>(*global_index), - GlobalSet64(global_index) => self.exec_global_set::<Value64>(*global_index), - GlobalSet128(global_index) => self.exec_global_set::<Value128>(*global_index), - GlobalTee32(global_index) => self.exec_global_tee::<Value32>(*global_index), - GlobalTee64(global_index) => self.exec_global_tee::<Value64>(*global_index), - GlobalTee128(global_index) => self.exec_global_tee::<Value128>(*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::<i32, i32, 4>(idx.resolve(&self.func.data), identity)?, - I64Store(idx) => self.exec_mem_store::<i64, i64, 8>(idx.resolve(&self.func.data), identity)?, - F32Store(idx) => self.exec_mem_store::<f32, f32, 4>(idx.resolve(&self.func.data), identity)?, - F64Store(idx) => self.exec_mem_store::<f64, f64, 8>(idx.resolve(&self.func.data), identity)?, - FMaStoreF32(m) => self.exec_fma_store::<f32, 4>(*m)?, - FMaStoreF64(m) => self.exec_fma_store::<f64, 8>(*m)?, - I32Store8(idx) => self.exec_mem_store::<i32, i8, 1>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, - I32Store16(idx) => self.exec_mem_store::<i32, i16, 2>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?, - I64Store8(idx) => self.exec_mem_store::<i64, i8, 1>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, - I64Store16(idx) => self.exec_mem_store::<i64, i16, 2>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?, - I64Store32(idx) => self.exec_mem_store::<i64, i32, 4>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i32)?, - I32Load(idx) => self.exec_mem_load::<i32, 4, _>(idx.resolve(&self.func.data), identity)?, - I64Load(idx) => self.exec_mem_load::<i64, 8, _>(idx.resolve(&self.func.data), identity)?, - F32Load(idx) => self.exec_mem_load::<f32, 4, _>(idx.resolve(&self.func.data), identity)?, - F64Load(idx) => self.exec_mem_load::<f64, 8, _>(idx.resolve(&self.func.data), identity)?, - I32Load8S(idx) => self.exec_mem_load::<i8, 1, _>(idx.resolve(&self.func.data), i32::from)?, - I32Load8U(idx) => self.exec_mem_load::<u8, 1, _>(idx.resolve(&self.func.data), i32::from)?, - I32Load16S(idx) => self.exec_mem_load::<i16, 2, _>(idx.resolve(&self.func.data), i32::from)?, - I32Load16U(idx) => self.exec_mem_load::<u16, 2, _>(idx.resolve(&self.func.data), i32::from)?, - I64Load8S(idx) => self.exec_mem_load::<i8, 1, _>(idx.resolve(&self.func.data), i64::from)?, - I64Load8U(idx) => self.exec_mem_load::<u8, 1, _>(idx.resolve(&self.func.data), i64::from)?, - I64Load16S(idx) => self.exec_mem_load::<i16, 2, _>(idx.resolve(&self.func.data), i64::from)?, - I64Load16U(idx) => self.exec_mem_load::<u16, 2, _>(idx.resolve(&self.func.data), i64::from)?, - I64Load32S(idx) => self.exec_mem_load::<i32, 4, _>(idx.resolve(&self.func.data), i64::from)?, - I64Load32U(idx) => self.exec_mem_load::<u32, 4, _>(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::<Value128, 16, _>(idx.resolve(&self.func.data), identity)?, - V128Load8x8S(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, - V128Load8x8U(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, - V128Load16x4S(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, - V128Load16x4U(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, - V128Load32x2S(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, - V128Load32x2U(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, - V128Load8Splat(idx) => self.exec_mem_load::<i8, 1, Value128>(idx.resolve(&self.func.data), Value128::splat_i8)?, - V128Load16Splat(idx) => self.exec_mem_load::<i16, 2, Value128>(idx.resolve(&self.func.data), Value128::splat_i16)?, - V128Load32Splat(idx) => self.exec_mem_load::<i32, 4, Value128>(idx.resolve(&self.func.data), Value128::splat_i32)?, - V128Load64Splat(idx) => self.exec_mem_load::<i64, 8, Value128>(idx.resolve(&self.func.data), Value128::splat_i64)?, - V128Store(idx) => self.exec_mem_store::<Value128, Value128, 16>(idx.resolve(&self.func.data), identity)?, - V128Store8Lane(arg) => self.exec_mem_store_lane::<i8, 1>(*arg)?, - V128Store16Lane(arg) => self.exec_mem_store_lane::<i16, 2>(*arg)?, - V128Store32Lane(arg) => self.exec_mem_store_lane::<i32, 4>(*arg)?, - V128Store64Lane(arg) => self.exec_mem_store_lane::<i64, 8>(*arg)?, - V128Load32Zero(idx) => self.exec_mem_load::<i32, 4, Value128>(idx.resolve(&self.func.data), |v| Value128::from_i32x4([v, 0, 0, 0]))?, - V128Load64Zero(idx) => self.exec_mem_load::<i64, 8, Value128>(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::<i32>(*lane, |v, lane| v.extract_lane_i8(lane) as i32)?, - I8x16ExtractLaneU(lane) => self.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_u8(lane) as i32)?, - I16x8ExtractLaneS(lane) => self.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_i16(lane) as i32)?, - I16x8ExtractLaneU(lane) => self.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_u16(lane) as i32)?, - I32x4ExtractLane(lane) => self.exec_simd_extract_lane::<i32>(*lane, Value128::extract_lane_i32)?, - I64x2ExtractLane(lane) => self.exec_simd_extract_lane::<i64>(*lane, Value128::extract_lane_i64)?, - F32x4ExtractLane(lane) => self.exec_simd_extract_lane::<f32>(*lane, Value128::extract_lane_f32)?, - F64x2ExtractLane(lane) => self.exec_simd_extract_lane::<f64>(*lane, Value128::extract_lane_f64)?, - V128Load8Lane(arg) => self.exec_mem_load_lane::<i8, 1>(*arg)?, - V128Load16Lane(arg) => self.exec_mem_load_lane::<i16, 2>(*arg)?, - V128Load32Lane(arg) => self.exec_mem_load_lane::<i32, 4>(*arg)?, - V128Load64Lane(arg) => self.exec_mem_load_lane::<i64, 8>(*arg)?, - I8x16ReplaceLane(lane) => self.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i8x16_replace_lane(lane, value as i8))?, - I16x8ReplaceLane(lane) => self.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i16x8_replace_lane(lane, value as i16))?, - I32x4ReplaceLane(lane) => self.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i32x4_replace_lane(lane, value))?, - I64x2ReplaceLane(lane) => self.exec_simd_replace_lane::<i64>(*lane, |value, vector, lane| vector.i64x2_replace_lane(lane, value))?, - F32x4ReplaceLane(lane) => self.exec_simd_replace_lane::<f32>(*lane, |value, vector, lane| vector.f32x4_replace_lane(lane, value))?, - F64x2ReplaceLane(lane) => self.exec_simd_replace_lane::<f64>(*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<const ON_NULL: bool>(&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<const ON_MATCH: bool>(&self, index: Operand64Idx<(u32, u32)>) -> Option<usize> { - 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<T: InternalValue + Default + PartialEq, const ON_ZERO: bool>( - &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<CmpOp, (u32, i32)>) -> Option<usize> { - 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<CmpOp, (u32, i64)>) -> Option<usize> { - 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<CmpOp, (u32, u16)>) -> Option<usize> { - 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<CmpOp, (u32, u16)>) -> Option<usize> { - 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<BinOp, LocalUpdateOperand>) -> Option<usize> { - 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<usize> { - 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<BinOp, LocalUpdateOperand>, - ) -> Result<Option<usize>, 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<BinOp, GlobalUpdateOperand>) -> Option<usize> { - 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<LocalUpdateOperand>) -> Option<usize> { - 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<LocalUpdateOperand>, - ) -> Result<Option<usize>, 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<GlobalUpdateOperand>) -> Option<usize> { - 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<CmpOp, LocalUpdateCmpOperand>) -> Option<usize> { - 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<CmpOp, (u32, i32, u16)>) -> Option<usize> { - 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<CmpOp, (u32, i32, u16)>) -> Option<usize> { - 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<CmpOp, (u32, u16, u16)>) -> Option<usize> { - 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<CmpOp, (u32, u16, u16)>) -> Option<usize> { - 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<TO: InternalValue>( - &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<VALUE: InternalValue>( - &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<T: InternalValue>(&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<T: InternalValue>(&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<T: InternalValue>(&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<T: InternalValue>(&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<T: InternalValue>(&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<T: InternalValue, const PUSH: bool>( - &mut self, - dst: Option<LocalAddr>, - 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<T: InternalValue, const PUSH: bool>( - &mut self, - lhs: LocalAddr, - rhs: LocalAddr, - destination: Option<LocalAddr>, - op: impl BinOpExt<T>, - ) -> 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::<T, PUSH>(destination, op.exec(lhs, rhs)) - } - - #[inline(always)] - fn exec_binop_local_local_indexed<T: InternalValue, const PUSH: bool>( - &mut self, - index: Operand64Idx<(u16, u16, u16)>, - op: impl BinOpExt<T>, - ) -> Result<(), Trap> { - let operands = index.resolve(&self.func.data); - self.exec_binop_local_local::<T, PUSH>(operands.a(), operands.b(), Some(operands.c()), op) - } - - #[inline(always)] - fn exec_binop_local_const<T: InternalValue, const PUSH: bool>( - &mut self, - lhs: LocalAddr, - rhs: T, - destination: Option<LocalAddr>, - op: impl BinOpExt<T>, - ) -> Result<(), Trap> { - let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); - self.exec_binop_result::<T, PUSH>(destination, op.exec(lhs, rhs)) - } - - #[inline(always)] - fn exec_binop_global_const<T: InternalValue>( - &mut self, - lhs: GlobalAddr, - rhs: T, - op: impl BinOpExt<T>, - ) -> 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<T>(&mut self, lhs: LocalAddr, rhs: LocalAddr, op: CmpOp) -> Result<(), Trap> - where - T: InternalValue, - CmpOp: CmpOpExt<T>, - { - 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<T: InternalValue>( - &mut self, - global: GlobalAddr, - op: impl BinOpExt<T>, - ) -> 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<T: InternalValue, const PUSH: bool>( - &mut self, - local: LocalAddr, - destination: Option<LocalAddr>, - op: impl BinOpExt<T>, - ) -> 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::<T, PUSH>(destination, op.exec(lhs, rhs)) - } - - #[inline(always)] - fn exec_binop_const_tee<T: InternalValue>( - &mut self, - rhs: T, - destination: LocalAddr, - op: impl BinOpExt<T>, - ) -> 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<T: InternalValue>( - &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<BranchTableOperand>) -> usize { - let v = index.resolve(&self.func.data); - let idx = <i32>::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<ValueRef, Trap> { - 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<ControlFlow<(), usize>> { - let exception = self.create_exception(tag_index)?; - self.throw_exception(exception, instr_ptr) - } - - fn exec_throw_ref(&mut self, instr_ptr: usize) -> Result<ControlFlow<(), usize>> { - 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<ControlFlow<(), usize>> { - 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<ExceptionCatch> { - 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<Option<usize>, 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<const TAIL: bool>( - &mut self, - host_func: HostFunction, - type_addr: TypeAddr, - return_instr_ptr: usize, - ) -> Result<ControlFlow<(), usize>> { - 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<ControlFlow<(), usize>> { - 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::<false>(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<ControlFlow<(), usize>> { - 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::<true>(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<ControlFlow<(), usize>> { - 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<ControlFlow<(), usize>> { - 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<const IS_RETURN_CALL: bool>( - &mut self, - index: Operand64Idx<(u32, u32)>, - return_instr_ptr: usize, - ) -> Result<ControlFlow<(), usize>> { - 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::<IS_RETURN_CALL>(func_ref, self.module.resolve_type_addr(type_addr), return_instr_ptr) - } - - fn exec_typed_call<const IS_RETURN_CALL: bool>( - &mut self, - func_addr: FuncAddr, - expected_type_addr: TypeAddr, - return_instr_ptr: usize, - ) -> Result<ControlFlow<(), usize>> { - 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::<IS_RETURN_CALL>(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<const IS_RETURN_CALL: bool>( - &mut self, - type_addr: u32, - return_instr_ptr: usize, - ) -> Result<ControlFlow<(), usize>> { - 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::<IS_RETURN_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<T: InternalValue + MemValue<N>, const N: usize>( - &mut self, - index: Operand64Idx<CompactMemoryOperand>, - 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::<N>(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::<N>(base as usize, u64::from(memarg.offset())))? - }; - value.store_at(&mut mem.inner, addr) - } - - fn exec_inc_memory_local<T: MemValue<N>, const N: usize>( - &mut self, - index: Operand64Idx<CompactMemoryOperand>, - 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::<N>(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::<N>(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<N> + core::ops::Add<Output = T> + core::ops::Mul<Output = T>, - 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::<N>(base, m.offset()))?; - cold_err!(fma.store_at(&mut mem.inner, addr)) - } - - fn exec_load_local< - LOAD: MemValue<N>, - const N: usize, - TARGET: InternalValue, - const SET_LOCAL: bool, - const TEE: bool, - >( - &mut self, - index: Operand64Idx<CompactMemoryOperand>, - 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::<N>(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<RuntimeValue>) -> 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<bool>) -> 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<bool>) -> 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<MemoryFillOperand>) -> 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<LOAD: MemValue<LOAD_SIZE>, 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::<LOAD_SIZE>(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<LOAD: MemValue<LOAD_SIZE>, const LOAD_SIZE: usize, TARGET: InternalValue>( - &mut self, - m: Operand128<MemoryOperand>, - 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::<LOAD_SIZE>(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<U: MemValue<N> + 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::<N>(base, m.offset()))?; - cold_err!(val.store_at(&mut mem.inner, addr))?; - Ok(()) - } - - #[inline(always)] - fn exec_mem_store<T: InternalValue, U: MemValue<N>, const N: usize>( - &mut self, - memory: Operand128<MemoryOperand>, - cast: impl Fn(T) -> U, - ) -> Result<(), Trap> { - let val = cast(<T>::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<T: InternalValue + MemValue<N>, const N: usize>( - &mut self, - memory: Operand128<MemoryOperand>, - ) -> 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<U: MemValue<N>, 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::<N>(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<usize, Trap> { - 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<ExecState> { - 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<ExecState> { - 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<ExecFlow> { + 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<ExecState> { + 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<ExecState> { + 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<ExecState> { + 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<ExecState> { + 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::<Value32, 4>(idx.resolve(&executor.func.data))?, + SelectStore64(idx) => executor.exec_select_store::<Value64, 8>(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::<false>(*idx, instr_ptr + 1)?), + CallRef(ty) => dispatch_flow!(executor.exec_call_ref::<false>(*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::<true>(*idx, instr_ptr + 1)?), + ReturnCallRef(ty) => dispatch_flow!(executor.exec_call_ref::<true>(*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::<true>() { dispatch_next!(ip as usize) } }, + JumpIfRefNonNull(ip) => { let ip = *ip; if executor.exec_jump_if_ref::<false>() { dispatch_next!(ip as usize) } }, + BrOnCast(idx) => if let Some(ip) = executor.exec_br_on_cast::<false>(*idx) { dispatch_next!(ip) }, + BrOnCastFail(idx) => if let Some(ip) = executor.exec_br_on_cast::<true>(*idx) { dispatch_next!(ip) }, + JumpIfLocalZero32(arg) => if executor.exec_jump_if_local::<Value32, true>(arg.local) { dispatch_next!(arg.target_ip as usize) }, + JumpIfLocalNonZero32(arg) => if executor.exec_jump_if_local::<Value32, false>(arg.local) { dispatch_next!(arg.target_ip as usize) }, + JumpIfLocalZero64(arg) => if executor.exec_jump_if_local::<Value64, true>(arg.local) { dispatch_next!(arg.target_ip as usize) }, + JumpIfLocalNonZero64(arg) => if executor.exec_jump_if_local::<Value64, false>(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::<Value32>(*local_index), + LocalSet64(local_index) => executor.exec_local_set_pop::<Value64>(*local_index), + LocalSet128(local_index) => executor.exec_local_set_pop::<Value128>(*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::<i32>(*acc, i32::wrapping_mul, i32::wrapping_add), + MulAccLocal64(acc) => executor.exec_mul_acc_local::<i64>(*acc, i64::wrapping_mul, i64::wrapping_add), + FMulAccLocal32(acc) => executor.exec_mul_acc_local::<f32>(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), + FMulAccLocal64(acc) => executor.exec_mul_acc_local::<f64>(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), + BinOpLocalLocal32(op, a, b) => executor.exec_binop_local_local::<Value32, true>(*a, *b, None, *op)?, + BinOpLocalLocal64(op, a, b) => executor.exec_binop_local_local::<Value64, true>(*a, *b, None, *op)?, + BinOpLocalLocal128(op, a, b) => executor.exec_binop_local_local::<Value128, true>(*a, *b, None, *op)?, + CmpLocalLocal32(op, a, b) => executor.exec_cmp_local_local::<i32>(*a, *b, *op)?, + CmpLocalLocal64(op, a, b) => executor.exec_cmp_local_local::<i64>(*a, *b, *op)?, + AddLocalLocalSet32(arg) => executor.exec_binop_local_local::<Value32, false>(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, + AddLocalLocalTee32(arg) => executor.exec_binop_local_local::<Value32, true>(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, + BinOpLocalLocalSet32(packed) => executor.exec_binop_local_local_indexed::<Value32, false>(packed.index, packed.op)?, + BinOpLocalLocalSet64(packed) => executor.exec_binop_local_local_indexed::<Value64, false>(packed.index, packed.op)?, + BinOpLocalLocalSet128(packed) => executor.exec_binop_local_local_indexed::<Value128, false>(packed.index, packed.op)?, + BinOpLocalLocalTee32(packed) => executor.exec_binop_local_local_indexed::<Value32, true>(packed.index, packed.op)?, + BinOpLocalLocalTee64(packed) => executor.exec_binop_local_local_indexed::<Value64, true>(packed.index, packed.op)?, + BinOpLocalLocalTee128(packed) => executor.exec_binop_local_local_indexed::<Value128, true>(packed.index, packed.op)?, + AddLocalConst32(arg) => executor.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IAdd)?, + SubLocalConst32(arg) => executor.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::ISub)?, + MulLocalConst32(arg) => executor.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IMul)?, + AndLocalConst32(arg) => executor.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IAnd)?, + ShrULocalConst32(arg) => executor.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IShrU)?, + BinOpLocalConst32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value32, true>(v.a(), v.b(), None, packed.op)?; }, + BinOpLocalConst64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value64, true>(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::<Value128, true>(v.a(), rhs, None, packed.op)?; }, + BinOpLocalConstSet32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value32, false>(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstTee32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value32, true>(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstSet64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value64, false>(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstTee64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value64, true>(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::<Value128, false>(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::<Value128, true>(v.a(), rhs, Some(v.b()), packed.op)?; }, + BinOpStackLocal32(op, local) => executor.exec_binop_stack_local::<Value32, true>(*local, None, *op)?, + BinOpStackLocalSet32(op, local, dst) => executor.exec_binop_stack_local::<Value32, false>(*local, Some(*dst), *op)?, + BinOpStackLocalTee32(op, local, dst) => executor.exec_binop_stack_local::<Value32, true>(*local, Some(*dst), *op)?, + BinOpStackLocal128(op, local) => executor.exec_binop_stack_local::<Value128, true>(*local, None, *op)?, + BinOpStackGlobal32(op, global_index) => executor.exec_binop_stack_global::<Value32>(*global_index, *op)?, + BinOpStackGlobal64(op, global_index) => executor.exec_binop_stack_global::<Value64>(*global_index, *op)?, + BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_global_const::<Value32>(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_global_const::<Value64>(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::<Value128>(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::<i32, 4>(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, + IncMemoryLocal64(arg) => executor.exec_inc_memory_local::<i64, 8>(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, + StoreLocalLocal32(arg) => executor.exec_store_local_local::<u32, 4>(arg.memory_arg_idx, arg.local1, arg.local2)?, + StoreLocalLocal64(arg) => executor.exec_store_local_local::<i64, 8>(arg.memory_arg_idx, arg.local1, arg.local2)?, + StoreLocalLocal128(arg) => executor.exec_store_local_local::<Value128, 16>(arg.memory_arg_idx, arg.local1, arg.local2)?, + LoadLocal32(arg) => executor.exec_load_local::<i32, 4, _, false, false>(arg.memory_arg_idx, arg.local1, 0, identity)?, + LoadLocal64(arg) => executor.exec_load_local::<i64, 8, _, false, false>(arg.memory_arg_idx, arg.local1, 0, identity)?, + LoadLocal8S32(arg) => executor.exec_load_local::<i8, 1, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal8U32(arg) => executor.exec_load_local::<u8, 1, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal16S32(arg) => executor.exec_load_local::<i16, 2, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal16U32(arg) => executor.exec_load_local::<u16, 2, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocalTee32(arg) => executor.exec_load_local::<i32, 4, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + LoadLocalSet32(arg) => executor.exec_load_local::<i32, 4, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + LoadLocalTee8S32(arg) => executor.exec_load_local::<i8, 1, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee8U32(arg) => executor.exec_load_local::<u8, 1, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee16S32(arg) => executor.exec_load_local::<i16, 2, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee16U32(arg) => executor.exec_load_local::<u16, 2, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet8S32(arg) => executor.exec_load_local::<i8, 1, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet8U32(arg) => executor.exec_load_local::<u8, 1, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet16S32(arg) => executor.exec_load_local::<i16, 2, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet16U32(arg) => executor.exec_load_local::<u16, 2, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee128(arg) => executor.exec_load_local::<Value128, 16, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + LoadLocalSet128(arg) => executor.exec_load_local::<Value128, 16, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + AndConstTee32(arg) => executor.exec_binop_const_tee::<Value32>(arg.value as u32, arg.local, BinOp::IAnd)?, + SubConstTee32(arg) => executor.exec_binop_const_tee::<Value32>(arg.value as u32, arg.local, BinOp::ISub)?, + AndConstTee64(packed) => executor.exec_binop_const_tee::<Value64>(packed.index.resolve(&executor.func.data).value() as u64, packed.op, BinOp::IAnd)?, + SubConstTee64(packed) => executor.exec_binop_const_tee::<Value64>(packed.index.resolve(&executor.func.data).value() as u64, packed.op, BinOp::ISub)?, + LocalTee32(local_index) => executor.exec_local_tee::<Value32>(*local_index), + LocalTee64(local_index) => executor.exec_local_tee::<Value64>(*local_index), + LocalTee128(local_index) => executor.exec_local_tee::<Value128>(*local_index), + GlobalGet32(global_index) => executor.exec_global_get::<Value32>(*global_index)?, + GlobalGet64(global_index) => executor.exec_global_get::<Value64>(*global_index)?, + GlobalGet128(global_index) => executor.exec_global_get::<Value128>(*global_index)?, + GlobalSet32(global_index) => executor.exec_global_set::<Value32>(*global_index), + GlobalSet64(global_index) => executor.exec_global_set::<Value64>(*global_index), + GlobalSet128(global_index) => executor.exec_global_set::<Value128>(*global_index), + GlobalTee32(global_index) => executor.exec_global_tee::<Value32>(*global_index), + GlobalTee64(global_index) => executor.exec_global_tee::<Value64>(*global_index), + GlobalTee128(global_index) => executor.exec_global_tee::<Value128>(*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::<i32, i32, 4>(idx.resolve(&executor.func.data), identity)?, + I64Store(idx) => executor.exec_mem_store::<i64, i64, 8>(idx.resolve(&executor.func.data), identity)?, + F32Store(idx) => executor.exec_mem_store::<f32, f32, 4>(idx.resolve(&executor.func.data), identity)?, + F64Store(idx) => executor.exec_mem_store::<f64, f64, 8>(idx.resolve(&executor.func.data), identity)?, + FMaStoreF32(m) => executor.exec_fma_store::<f32, 4>(*m)?, + FMaStoreF64(m) => executor.exec_fma_store::<f64, 8>(*m)?, + I32Store8(idx) => executor.exec_mem_store::<i32, i8, 1>(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i8)?, + I32Store16(idx) => executor.exec_mem_store::<i32, i16, 2>(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i16)?, + I64Store8(idx) => executor.exec_mem_store::<i64, i8, 1>(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i8)?, + I64Store16(idx) => executor.exec_mem_store::<i64, i16, 2>(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i16)?, + I64Store32(idx) => executor.exec_mem_store::<i64, i32, 4>(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i32)?, + I32Load(idx) => executor.exec_mem_load::<i32, 4, _>(idx.resolve(&executor.func.data), identity)?, + I64Load(idx) => executor.exec_mem_load::<i64, 8, _>(idx.resolve(&executor.func.data), identity)?, + F32Load(idx) => executor.exec_mem_load::<f32, 4, _>(idx.resolve(&executor.func.data), identity)?, + F64Load(idx) => executor.exec_mem_load::<f64, 8, _>(idx.resolve(&executor.func.data), identity)?, + I32Load8S(idx) => executor.exec_mem_load::<i8, 1, _>(idx.resolve(&executor.func.data), i32::from)?, + I32Load8U(idx) => executor.exec_mem_load::<u8, 1, _>(idx.resolve(&executor.func.data), i32::from)?, + I32Load16S(idx) => executor.exec_mem_load::<i16, 2, _>(idx.resolve(&executor.func.data), i32::from)?, + I32Load16U(idx) => executor.exec_mem_load::<u16, 2, _>(idx.resolve(&executor.func.data), i32::from)?, + I64Load8S(idx) => executor.exec_mem_load::<i8, 1, _>(idx.resolve(&executor.func.data), i64::from)?, + I64Load8U(idx) => executor.exec_mem_load::<u8, 1, _>(idx.resolve(&executor.func.data), i64::from)?, + I64Load16S(idx) => executor.exec_mem_load::<i16, 2, _>(idx.resolve(&executor.func.data), i64::from)?, + I64Load16U(idx) => executor.exec_mem_load::<u16, 2, _>(idx.resolve(&executor.func.data), i64::from)?, + I64Load32S(idx) => executor.exec_mem_load::<i32, 4, _>(idx.resolve(&executor.func.data), i64::from)?, + I64Load32U(idx) => executor.exec_mem_load::<u32, 4, _>(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::<Value128, 16, _>(idx.resolve(&executor.func.data), identity)?, + V128Load8x8S(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, + V128Load8x8U(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, + V128Load16x4S(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, + V128Load16x4U(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, + V128Load32x2S(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, + V128Load32x2U(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, + V128Load8Splat(idx) => executor.exec_mem_load::<i8, 1, Value128>(idx.resolve(&executor.func.data), Value128::splat_i8)?, + V128Load16Splat(idx) => executor.exec_mem_load::<i16, 2, Value128>(idx.resolve(&executor.func.data), Value128::splat_i16)?, + V128Load32Splat(idx) => executor.exec_mem_load::<i32, 4, Value128>(idx.resolve(&executor.func.data), Value128::splat_i32)?, + V128Load64Splat(idx) => executor.exec_mem_load::<i64, 8, Value128>(idx.resolve(&executor.func.data), Value128::splat_i64)?, + V128Store(idx) => executor.exec_mem_store::<Value128, Value128, 16>(idx.resolve(&executor.func.data), identity)?, + V128Store8Lane(arg) => executor.exec_mem_store_lane::<i8, 1>(*arg)?, + V128Store16Lane(arg) => executor.exec_mem_store_lane::<i16, 2>(*arg)?, + V128Store32Lane(arg) => executor.exec_mem_store_lane::<i32, 4>(*arg)?, + V128Store64Lane(arg) => executor.exec_mem_store_lane::<i64, 8>(*arg)?, + V128Load32Zero(idx) => executor.exec_mem_load::<i32, 4, Value128>(idx.resolve(&executor.func.data), |v| Value128::from_i32x4([v, 0, 0, 0]))?, + V128Load64Zero(idx) => executor.exec_mem_load::<i64, 8, Value128>(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::<i32>(*lane, |v, lane| v.extract_lane_i8(lane) as i32)?, + I8x16ExtractLaneU(lane) => executor.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_u8(lane) as i32)?, + I16x8ExtractLaneS(lane) => executor.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_i16(lane) as i32)?, + I16x8ExtractLaneU(lane) => executor.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_u16(lane) as i32)?, + I32x4ExtractLane(lane) => executor.exec_simd_extract_lane::<i32>(*lane, Value128::extract_lane_i32)?, + I64x2ExtractLane(lane) => executor.exec_simd_extract_lane::<i64>(*lane, Value128::extract_lane_i64)?, + F32x4ExtractLane(lane) => executor.exec_simd_extract_lane::<f32>(*lane, Value128::extract_lane_f32)?, + F64x2ExtractLane(lane) => executor.exec_simd_extract_lane::<f64>(*lane, Value128::extract_lane_f64)?, + V128Load8Lane(arg) => executor.exec_mem_load_lane::<i8, 1>(*arg)?, + V128Load16Lane(arg) => executor.exec_mem_load_lane::<i16, 2>(*arg)?, + V128Load32Lane(arg) => executor.exec_mem_load_lane::<i32, 4>(*arg)?, + V128Load64Lane(arg) => executor.exec_mem_load_lane::<i64, 8>(*arg)?, + I8x16ReplaceLane(lane) => executor.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i8x16_replace_lane(lane, value as i8))?, + I16x8ReplaceLane(lane) => executor.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i16x8_replace_lane(lane, value as i16))?, + I32x4ReplaceLane(lane) => executor.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i32x4_replace_lane(lane, value))?, + I64x2ReplaceLane(lane) => executor.exec_simd_replace_lane::<i64>(*lane, |value, vector, lane| vector.i64x2_replace_lane(lane, value))?, + F32x4ReplaceLane(lane) => executor.exec_simd_replace_lane::<f32>(*lane, |value, vector, lane| vector.f32x4_replace_lane(lane, value))?, + F64x2ReplaceLane(lane) => executor.exec_simd_replace_lane::<f64>(*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<Error>); + +type ExecResult<T> = core::result::Result<T, ExecError>; + +impl From<Trap> for ExecError { + #[cold] + fn from(trap: Trap) -> Self { + Self(Box::new(Error::Trap(trap))) + } +} + +impl From<Error> for ExecError { + #[cold] + fn from(error: Error) -> Self { + Self(Box::new(error)) + } +} + +impl From<ExecError> 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<usize> { + (self.0 != Self::COMPLETE.0).then_some(self.0) + } +} + +pub(crate) struct Executor<'store> { + cf: CallFrame, + func: Shared<WasmFunction>, + 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<const ON_NULL: bool>(&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<const ON_MATCH: bool>(&self, index: Operand64Idx<(u32, u32)>) -> Option<usize> { + 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<T: InternalValue + Default + PartialEq, const ON_ZERO: bool>( + &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<CmpOp, (u32, i32)>) -> Option<usize> { + 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<CmpOp, (u32, i64)>) -> Option<usize> { + 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<CmpOp, (u32, u16)>) -> Option<usize> { + 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<CmpOp, (u32, u16)>) -> Option<usize> { + 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<BinOp, LocalUpdateOperand>) -> Option<usize> { + 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<usize> { + 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<BinOp, LocalUpdateOperand>, + ) -> Result<Option<usize>, 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<BinOp, GlobalUpdateOperand>) -> Option<usize> { + 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<LocalUpdateOperand>) -> Option<usize> { + 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<LocalUpdateOperand>, + ) -> Result<Option<usize>, 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<GlobalUpdateOperand>) -> Option<usize> { + 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<CmpOp, LocalUpdateCmpOperand>) -> Option<usize> { + 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<CmpOp, (u32, i32, u16)>) -> Option<usize> { + 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<CmpOp, (u32, i32, u16)>) -> Option<usize> { + 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<CmpOp, (u32, u16, u16)>) -> Option<usize> { + 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<CmpOp, (u32, u16, u16)>) -> Option<usize> { + 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<TO: InternalValue>( + &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<VALUE: InternalValue>( + &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<T: InternalValue>(&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<T: InternalValue>(&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<T: InternalValue>(&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<T: InternalValue>(&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<T: InternalValue>(&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<T: InternalValue, const PUSH: bool>( + &mut self, + dst: Option<LocalAddr>, + 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<T: InternalValue, const PUSH: bool>( + &mut self, + lhs: LocalAddr, + rhs: LocalAddr, + destination: Option<LocalAddr>, + op: impl BinOpExt<T>, + ) -> 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::<T, PUSH>(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_local_local_indexed<T: InternalValue, const PUSH: bool>( + &mut self, + index: Operand64Idx<(u16, u16, u16)>, + op: impl BinOpExt<T>, + ) -> Result<(), Trap> { + let operands = index.resolve(&self.func.data); + self.exec_binop_local_local::<T, PUSH>(operands.a(), operands.b(), Some(operands.c()), op) + } + + #[inline(always)] + fn exec_binop_local_const<T: InternalValue, const PUSH: bool>( + &mut self, + lhs: LocalAddr, + rhs: T, + destination: Option<LocalAddr>, + op: impl BinOpExt<T>, + ) -> Result<(), Trap> { + let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); + self.exec_binop_result::<T, PUSH>(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_global_const<T: InternalValue>( + &mut self, + lhs: GlobalAddr, + rhs: T, + op: impl BinOpExt<T>, + ) -> 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<T>(&mut self, lhs: LocalAddr, rhs: LocalAddr, op: CmpOp) -> Result<(), Trap> + where + T: InternalValue, + CmpOp: CmpOpExt<T>, + { + 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<T: InternalValue>( + &mut self, + global: GlobalAddr, + op: impl BinOpExt<T>, + ) -> 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<T: InternalValue, const PUSH: bool>( + &mut self, + local: LocalAddr, + destination: Option<LocalAddr>, + op: impl BinOpExt<T>, + ) -> 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::<T, PUSH>(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_const_tee<T: InternalValue>( + &mut self, + rhs: T, + destination: LocalAddr, + op: impl BinOpExt<T>, + ) -> 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<T: InternalValue>( + &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<BranchTableOperand>) -> usize { + let v = index.resolve(&self.func.data); + let idx = <i32>::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<ValueRef, Trap> { + 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<ExecFlow> { + let exception = self.create_exception(tag_index)?; + self.throw_exception(exception, instr_ptr) + } + + fn exec_throw_ref(&mut self, instr_ptr: usize) -> ExecResult<ExecFlow> { + 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<ExecFlow> { + 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<ExceptionCatch> { + 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<Option<usize>, 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<const TAIL: bool>( + &mut self, + host_func: HostFunction, + type_addr: TypeAddr, + return_instr_ptr: usize, + ) -> ExecResult<ExecFlow> { + 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<ExecFlow> { + 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::<false>(host_func, type_addr, return_instr_ptr) + } else { + self.exec_call_wasm::<false>(addr, return_instr_ptr) + } + } + + fn exec_return_call_direct(&mut self, v: u32) -> ExecResult<ExecFlow> { + 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::<true>(host_func, type_addr, 0) + } else { + self.exec_call_wasm::<true>(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<const TAIL: bool>( + &mut self, + index: Operand64Idx<(u32, u32)>, + return_instr_ptr: usize, + ) -> ExecResult<ExecFlow> { + 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::<TAIL>(func_ref, self.module.resolve_type_addr(type_addr), return_instr_ptr) + } + + fn exec_typed_call<const TAIL: bool>( + &mut self, + func_addr: FuncAddr, + expected_type_addr: TypeAddr, + return_instr_ptr: usize, + ) -> ExecResult<ExecFlow> { + 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::<TAIL>(host_func, type_addr, return_instr_ptr); + } + + self.exec_call_wasm::<TAIL>(func_addr, return_instr_ptr) + } + + #[inline(always)] + fn exec_call_wasm<const TAIL: bool>( + &mut self, + func_addr: FuncAddr, + return_instr_ptr: usize, + ) -> ExecResult<ExecFlow> { + 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<const TAIL: bool>(&mut self, type_addr: u32, return_instr_ptr: usize) -> ExecResult<ExecFlow> { + 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::<TAIL>(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<T: InternalValue + MemValue<N>, const N: usize>( + &mut self, + index: Operand64Idx<CompactMemoryOperand>, + 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::<N>(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::<N>(base as usize, u64::from(memarg.offset())))? + }; + value.store_at(&mut mem.inner, addr) + } + + fn exec_inc_memory_local<T: MemValue<N>, const N: usize>( + &mut self, + index: Operand64Idx<CompactMemoryOperand>, + 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::<N>(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::<N>(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<N> + core::ops::Add<Output = T> + core::ops::Mul<Output = T>, + 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::<N>(base, m.offset()))?; + cold_err!(fma.store_at(&mut mem.inner, addr)) + } + + fn exec_load_local< + LOAD: MemValue<N>, + const N: usize, + TARGET: InternalValue, + const SET_LOCAL: bool, + const TEE: bool, + >( + &mut self, + index: Operand64Idx<CompactMemoryOperand>, + 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::<N>(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<RuntimeValue>) -> 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<bool>) -> 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<bool>) -> 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<MemoryFillOperand>) -> 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<LOAD: MemValue<LOAD_SIZE>, 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::<LOAD_SIZE>(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<LOAD: MemValue<LOAD_SIZE>, const LOAD_SIZE: usize, TARGET: InternalValue>( + &mut self, + m: Operand128<MemoryOperand>, + 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::<LOAD_SIZE>(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<U: MemValue<N> + 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::<N>(base, m.offset()))?; + cold_err!(val.store_at(&mut mem.inner, addr))?; + Ok(()) + } + + #[inline(always)] + fn exec_mem_store<T: InternalValue, U: MemValue<N>, const N: usize>( + &mut self, + memory: Operand128<MemoryOperand>, + cast: impl Fn(T) -> U, + ) -> Result<(), Trap> { + let val = cast(<T>::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<T: InternalValue + MemValue<N>, const N: usize>( + &mut self, + memory: Operand128<MemoryOperand>, + ) -> 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<U: MemValue<N>, 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::<N>(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<usize, Trap> { + 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::<false>::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<ExecState> { - executor::Executor::<true>::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<ExecState> { - executor::Executor::<false>::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<T: Copy + Default> { dynamic: bool, } +#[cold] +#[inline(never)] +fn stack_underflow() -> ! { + unreachable!("ValueStack underflow, this is a bug") +} + impl<T: Copy + Default> Stack<T> { 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<T: Copy + Default> Stack<T> { 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<T: Copy + Default> Stack<T> { 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<T: Copy + Default> Stack<T> { 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))] # 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::<i32, i32>(&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 Binary files differindex 0fb3f39..967eda1 100644 --- a/examples/rust/src/print.twasm +++ b/examples/rust/src/print.twasm |
