From d0c74255f9d6c57a243cf34037af0e8f371504b3 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Sat, 8 Aug 2026 15:43:26 +0200 Subject: feat: initial support for the webassembly gc proposal (#50) Signed-off-by: Henry --- crates/parser/src/optimize.rs | 1 + 1 file changed, 1 insertion(+) (limited to 'crates/parser/src/optimize.rs') diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index dcb7568..5c2d7d5 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -858,6 +858,7 @@ fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> { | Instruction::JumpIfNonZero64(ip) | Instruction::JumpIfRefNull(ip) | Instruction::JumpIfRefNonNull(ip) + | Instruction::BrOnCast(ip, _, _) | Instruction::JumpCmpStackConst32 { target_ip: ip, .. } | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } -- cgit v1.3.1 From 676be92cde66d7c20bfe11d64bfc3f5762c4c46e Mon Sep 17 00:00:00 2001 From: Henry Date: Sat, 8 Aug 2026 18:30:29 +0200 Subject: chore: store globals in different lanes based on size Signed-off-by: Henry --- CHANGELOG.md | 5 +- crates/parser/src/conversion.rs | 22 +- crates/parser/src/macros.rs | 2 +- crates/parser/src/optimize.rs | 8 +- crates/parser/src/visit.rs | 248 +++++++++------------ crates/tinywasm/src/imports.rs | 23 +- crates/tinywasm/src/interpreter/executor.rs | 50 ++--- .../tinywasm/src/interpreter/stack/value_stack.rs | 4 + crates/tinywasm/src/interpreter/values.rs | 40 +++- crates/tinywasm/src/reference.rs | 34 +-- crates/tinywasm/src/store/global.rs | 165 +++++++++++++- crates/tinywasm/src/store/mod.rs | 18 +- crates/tinywasm/src/store/state.rs | 64 ++++-- crates/tinywasm/tests/store_ownership.rs | 18 +- crates/tinywasm/tests/typed_globals.rs | 93 ++++++++ crates/types/src/instructions.rs | 7 +- crates/types/src/lib.rs | 41 +++- 17 files changed, 564 insertions(+), 278 deletions(-) create mode 100644 crates/tinywasm/tests/typed_globals.rs (limited to 'crates/parser/src/optimize.rs') diff --git a/CHANGELOG.md b/CHANGELOG.md index 38d4dd8..7ef6fb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,16 +10,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added support for the WebAssembly function-references proposal -- Added support for the WebAssembly garbage-collection proposal +- Added basic support for the WebAssembly garbage-collection proposal - Added `WasmValue::ty` and `WasmValue::matches_type` +- Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. ### Changed - Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`. +- Globals are stored in separate 32-bit, 64-bit, and 128-bit value lanes, avoiding tagged value conversion during guest execution. ### Fixed +- Directly defined imports now reject handles from a different `Store`. - Tail calls to host functions now return directly to the caller frame. ### Breaking Changes diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 8bc7df1..4073a8e 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -6,6 +6,14 @@ use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; +pub(crate) fn value_lane(ty: wasmparser::ValType) -> ValueLane { + match ty { + wasmparser::ValType::I32 | wasmparser::ValType::F32 | wasmparser::ValType::Ref(_) => ValueLane::S32, + wasmparser::ValType::I64 | wasmparser::ValType::F64 => ValueLane::S64, + wasmparser::ValType::V128 => ValueLane::S128, + } +} + pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result { let kind = match element.kind { wasmparser::ElementKind::Active { table_index, offset_expr } => tinywasm_types::ElementKind::Active { @@ -116,12 +124,8 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result, - count: u32, - ty: wasmparser::ValType, -) -> Result<()> { - let size = crate::visit::OperandSize::from(ty); +fn extend_local_types(local_types: &mut Vec, count: u32, ty: wasmparser::ValType) -> Result<()> { + let size = value_lane(ty); let count = usize::try_from(count).map_err(|_| crate::ParseError::Other("local declaration count is too large".into()))?; local_types.reserve(count); @@ -166,9 +170,9 @@ pub(crate) fn convert_module_code( for ty in &local_types { let (count, error) = match ty { - crate::visit::OperandSize::S32 => (&mut local_counts.c32, "too many 32-bit locals"), - crate::visit::OperandSize::S64 => (&mut local_counts.c64, "too many 64-bit locals"), - crate::visit::OperandSize::S128 => (&mut local_counts.c128, "too many 128-bit locals"), + ValueLane::S32 => (&mut local_counts.c32, "too many 32-bit locals"), + ValueLane::S64 => (&mut local_counts.c64, "too many 64-bit locals"), + ValueLane::S128 => (&mut local_counts.c128, "too many 128-bit locals"), }; local_addr_map.push(*count); *count = count.checked_add(1).ok_or_else(|| crate::ParseError::Other(error.into()))?; diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 553f439..db1402d 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -141,7 +141,7 @@ pub(crate) mod visit { (@size Addr, $address:ident) => { $address }; (@size Field, $address:ident) => { $address }; - (@size $size:ident $(, $address:ident)?) => { OperandSize::$size }; + (@size $size:ident $(, $address:ident)?) => { ValueLane::$size }; } macro_rules! impl_visit_operator { diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 5c2d7d5..74a9fc0 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -93,7 +93,7 @@ fn rewrite( rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal32(op, global)); + rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); rewrite!(instrs, i, [I32Add] => I32Add3); @@ -103,7 +103,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal32(op, global)); + rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]); rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 16), Const32(16)] => [LocalGet32(local), I32Extend16S]); @@ -114,7 +114,7 @@ fn rewrite( rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal64(op, global)); + rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const64(c)] => AddConst64(c)); rewrite!(instrs, i, [I64Add] => I64Add3); @@ -124,7 +124,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal64(op, global)); + rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 8), Const64(8)] => [LocalGet64(local), I64Extend8S]); rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 16), Const64(16)] => [LocalGet64(local), I64Extend16S]); diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 4437242..46d1f9f 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -1,9 +1,13 @@ -use crate::{Result, conversion::convert_heap_type, macros::visit::*}; +use crate::{ + Result, + conversion::{convert_heap_type, value_lane}, + macros::visit::*, +}; use alloc::string::ToString; use alloc::vec::Vec; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, - TypeSection, ValueCounts, WasmFunctionData, WasmType, + Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TypeSection, + ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -18,52 +22,6 @@ enum BlockKind { If, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum OperandSize { - S32, - S64, - S128, -} - -impl OperandSize { - fn choose(self, s32: T, s64: T, s128: T) -> T { - match self { - Self::S32 => s32, - Self::S64 => s64, - Self::S128 => s128, - } - } -} - -impl From for OperandSize { - fn from(ty: wasmparser::ValType) -> Self { - match ty { - wasmparser::ValType::I32 | wasmparser::ValType::F32 | wasmparser::ValType::Ref(_) => Self::S32, - wasmparser::ValType::I64 | wasmparser::ValType::F64 => Self::S64, - wasmparser::ValType::V128 => Self::S128, - } - } -} - -impl From<&WasmType> for OperandSize { - fn from(ty: &WasmType) -> Self { - match ty { - WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => Self::S32, - WasmType::I64 | WasmType::F64 => Self::S64, - WasmType::V128 => Self::S128, - } - } -} - -impl From for OperandSize { - fn from(arch: MemoryArch) -> Self { - match arch { - MemoryArch::I32 => Self::S32, - MemoryArch::I64 => Self::S64, - } - } -} - struct ControlFrame { kind: BlockKind, has_else: bool, @@ -71,8 +29,8 @@ struct ControlFrame { branch_jumps: Vec, height: usize, base: ValueCounts, - params: Vec, - results: Vec, + params: Vec, + results: Vec, unreachable: bool, entry_unreachable: bool, end_reachable: bool, @@ -80,16 +38,16 @@ struct ControlFrame { #[derive(Clone)] pub(crate) struct Signature { - pub params: Vec, - results: Vec, + pub params: Vec, + results: Vec, } pub(crate) struct ModuleMetadata { signatures: Vec>, functions: Vec, - globals: Vec, - memories: Vec, - tables: Vec, + globals: Vec, + memories: Vec, + tables: Vec, types: Vec, } @@ -103,10 +61,10 @@ pub(crate) struct FunctionBuilder<'a> { instructions: Vec, data: FunctionDataBuilder, control_stack: Vec, - operand_stack: Vec, + operand_stack: Vec, lane_counts: ValueCounts, metadata: &'a ModuleMetadata, - local_types: Vec, + local_types: Vec, local_addr_map: Vec, } @@ -114,7 +72,7 @@ impl<'a> FunctionBuilder<'a> { pub(crate) fn new( metadata: &'a ModuleMetadata, signature: Signature, - local_types: Vec, + local_types: Vec, local_addr_map: Vec, body_size: usize, ) -> Self { @@ -149,7 +107,7 @@ impl<'a> FunctionBuilder<'a> { instruction: fn(u32, u32) -> Instruction, ) -> Result<()> { let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); - self.emit(&[OperandSize::S32], &[size], instruction(type_index, field_index)) + self.emit(&[ValueLane::S32], &[size], instruction(type_index, field_index)) } } @@ -161,6 +119,13 @@ struct ValidateThenVisit<'a, 'm> { } impl ModuleMetadata { + fn address_lane(arch: tinywasm_types::MemoryArch) -> ValueLane { + match arch { + tinywasm_types::MemoryArch::I32 => ValueLane::S32, + tinywasm_types::MemoryArch::I64 => ValueLane::S64, + } + } + pub(crate) fn new( types: &TypeSection, code_type_addrs: &[u32], @@ -177,24 +142,24 @@ impl ModuleMetadata { for import in imports { match &import.kind { ImportKind::Function(ty) => functions.push(*ty), - ImportKind::Global(ty) => global_sizes.push(OperandSize::from(&ty.ty)), - ImportKind::Memory(ty) => memory_sizes.push(OperandSize::from(ty.arch())), - ImportKind::Table(ty) => table_sizes.push(OperandSize::from(ty.arch())), + ImportKind::Global(ty) => global_sizes.push(ValueLane::from(&ty.ty)), + ImportKind::Memory(ty) => memory_sizes.push(Self::address_lane(ty.arch())), + ImportKind::Table(ty) => table_sizes.push(Self::address_lane(ty.arch())), } } functions.extend_from_slice(code_type_addrs); - global_sizes.extend(globals.iter().map(|global| OperandSize::from(&global.ty.ty))); - memory_sizes.extend(memories.iter().map(|ty| OperandSize::from(ty.arch()))); - table_sizes.extend(tables.iter().map(|table| OperandSize::from(table.ty.arch()))); + global_sizes.extend(globals.iter().map(|global| ValueLane::from(&global.ty.ty))); + memory_sizes.extend(memories.iter().map(|ty| Self::address_lane(ty.arch()))); + table_sizes.extend(tables.iter().map(|table| Self::address_lane(table.ty.arch()))); let signatures = types .types .iter() .map(|ty| { ty.as_func().map(|ty| Signature { - params: ty.params().iter().map(OperandSize::from).collect(), - results: ty.results().iter().map(OperandSize::from).collect(), + params: ty.params().iter().map(ValueLane::from).collect(), + results: ty.results().iter().map(ValueLane::from).collect(), }) }) .collect(); @@ -223,29 +188,29 @@ impl ModuleMetadata { self.signature(ty) } - fn global_size(&self, idx: u32) -> Result { + fn global_size(&self, idx: u32) -> Result { Self::indexed_size(&self.globals, "global", idx) } - fn memory_size(&self, idx: u32) -> Result { + fn memory_size(&self, idx: u32) -> Result { Self::indexed_size(&self.memories, "memory", idx) } - fn table_size(&self, idx: u32) -> Result { + fn table_size(&self, idx: u32) -> Result { Self::indexed_size(&self.tables, "table", idx) } - fn indexed_size(sizes: &[OperandSize], entity: &str, idx: u32) -> Result { + fn indexed_size(sizes: &[ValueLane], entity: &str, idx: u32) -> Result { sizes .get(idx as usize) .copied() .ok_or_else(|| crate::ParseError::Other(alloc::format!("{entity} index out of bounds: {idx}"))) } - fn storage_size(storage: StorageType) -> OperandSize { + fn storage_size(storage: StorageType) -> ValueLane { match storage { - StorageType::I8 | StorageType::I16 => OperandSize::S32, - StorageType::Value(ref ty) => OperandSize::from(ty), + StorageType::I8 | StorageType::I16 => ValueLane::S32, + StorageType::Value(ref ty) => ValueLane::from(ty), } } @@ -291,7 +256,7 @@ impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> { pub(crate) fn process_operators( body: FunctionBody<'_>, - local_types: Vec, + local_types: Vec, local_addr_map: Vec, metadata: &ModuleMetadata, ty_idx: u32, @@ -327,7 +292,7 @@ pub(crate) fn process_operators( pub(crate) fn process_operators_and_validate( mut validator: FuncValidator, body: FunctionBody<'_>, - local_types: Vec, + local_types: Vec, local_addr_map: Vec, metadata: &ModuleMetadata, ty_idx: u32, @@ -470,7 +435,6 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { effect [S32] => [S32] { visit_f32_reinterpret_i32, visit_i32_reinterpret_f32 } effect [S64] => [S64] { visit_f64_reinterpret_i64, visit_i64_reinterpret_f64 } terminating [] => [] { visit_unreachable => Unreachable, visit_return => Return } - global [] => [Addr] { visit_global_get(global_index: u32) => GlobalGet } memory_index [] => [Addr] { visit_memory_size(memory: u32) => MemorySize } memory_index [Addr] => [Addr] { visit_memory_grow(memory: u32) => MemoryGrow } memory_index [Addr, S32, Addr] => [] { @@ -514,7 +478,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { .iter() .map(|field| ModuleMetadata::storage_size(field.storage)) .collect::>(); - self.emit(&inputs, &[OperandSize::S32], Instruction::StructNew(type_index)) + self.emit(&inputs, &[ValueLane::S32], Instruction::StructNew(type_index)) } fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output { @@ -531,7 +495,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); - self.emit(&[OperandSize::S32, size], &[], Instruction::StructSet(type_index, field_index)) + self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(type_index, field_index)) } fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { @@ -539,7 +503,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { for _ in 0..array_size { self.pop_expect(size)?; } - self.push_sizes(&[OperandSize::S32])?; + self.push_sizes(&[ValueLane::S32])?; self.instructions.push(Instruction::ArrayNewFixed(type_index, array_size)); Ok(()) } @@ -559,7 +523,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { let signature = self.metadata.signature(type_index)?.clone(); let mut inputs = signature.params; - inputs.push(OperandSize::S32); + inputs.push(ValueLane::S32); self.emit(&inputs, &signature.results, Instruction::CallRef(type_index)) } @@ -584,7 +548,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_return_call_ref(&mut self, type_index: u32) -> Self::Output { let signature = self.metadata.signature(type_index)?.clone(); let mut inputs = signature.params; - inputs.push(OperandSize::S32); + inputs.push(ValueLane::S32); self.apply_effect(&inputs, &[])?; self.mark_unreachable(); self.instructions.push(Instruction::ReturnCallRef(type_index)); @@ -593,7 +557,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_global_set(&mut self, global_index: u32) -> Self::Output { let size = self.metadata.global_size(global_index)?; - let instruction = size.choose( + let instruction = size.select( Instruction::GlobalSet32(global_index), Instruction::GlobalSet64(global_index), Instruction::GlobalSet128(global_index), @@ -601,21 +565,31 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.emit(&[size], &[], instruction) } + fn visit_global_get(&mut self, global_index: u32) -> Self::Output { + let size = self.metadata.global_size(global_index)?; + let instruction = size.select( + Instruction::GlobalGet32(global_index), + Instruction::GlobalGet64(global_index), + Instruction::GlobalGet128(global_index), + ); + self.emit(&[], &[size], instruction) + } + fn visit_drop(&mut self) -> Self::Output { - let size = self.operand_stack.last().copied().unwrap_or(OperandSize::S32); - let instruction = size.choose(Instruction::Drop32, Instruction::Drop64, Instruction::Drop128); + let size = self.operand_stack.last().copied().unwrap_or(ValueLane::S32); + let instruction = size.select(Instruction::Drop32, Instruction::Drop64, Instruction::Drop128); self.emit(&[size], &[], instruction) } fn visit_select(&mut self) -> Self::Output { - let size = self.operand_stack.iter().rev().nth(1).copied().unwrap_or(OperandSize::S32); - let instruction = size.choose(Instruction::Select32, Instruction::Select64, Instruction::Select128); - self.emit(&[size, size, OperandSize::S32], &[size], instruction) + let size = self.operand_stack.iter().rev().nth(1).copied().unwrap_or(ValueLane::S32); + let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128); + self.emit(&[size, size, ValueLane::S32], &[size], instruction) } fn visit_local_get(&mut self, idx: u32) -> Self::Output { let (size, local_idx) = self.local(idx)?; - let instruction = size.choose( + let instruction = size.select( Instruction::LocalGet32(local_idx), Instruction::LocalGet64(local_idx), Instruction::LocalGet128(local_idx), @@ -625,7 +599,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_local_set(&mut self, idx: u32) -> Self::Output { let (size, local_idx) = self.local(idx)?; - let instruction = size.choose( + let instruction = size.select( Instruction::LocalSet32(local_idx), Instruction::LocalSet64(local_idx), Instruction::LocalSet128(local_idx), @@ -637,21 +611,21 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let (size, local_idx) = self.local(idx)?; self.apply_effect(&[size], &[size])?; let src = match (size, self.instructions.last()) { - (OperandSize::S32, Some(Instruction::LocalGet32(src))) => Some(*src), - (OperandSize::S64, Some(Instruction::LocalGet64(src))) => Some(*src), - (OperandSize::S128, Some(Instruction::LocalGet128(src))) => Some(*src), + (ValueLane::S32, Some(Instruction::LocalGet32(src))) => Some(*src), + (ValueLane::S64, Some(Instruction::LocalGet64(src))) => Some(*src), + (ValueLane::S128, Some(Instruction::LocalGet128(src))) => Some(*src), _ => None, }; if let Some(src) = src { self.instructions.pop(); let instructions = match size { - OperandSize::S32 => [Instruction::LocalCopy32(src, local_idx), Instruction::LocalGet32(local_idx)], - OperandSize::S64 => [Instruction::LocalCopy64(src, local_idx), Instruction::LocalGet64(local_idx)], - OperandSize::S128 => [Instruction::LocalCopy128(src, local_idx), Instruction::LocalGet128(local_idx)], + ValueLane::S32 => [Instruction::LocalCopy32(src, local_idx), Instruction::LocalGet32(local_idx)], + ValueLane::S64 => [Instruction::LocalCopy64(src, local_idx), Instruction::LocalGet64(local_idx)], + ValueLane::S128 => [Instruction::LocalCopy128(src, local_idx), Instruction::LocalGet128(local_idx)], }; self.instructions.extend(instructions); } else { - self.instructions.push(size.choose( + self.instructions.push(size.select( Instruction::LocalTee32(local_idx), Instruction::LocalTee64(local_idx), Instruction::LocalTee128(local_idx), @@ -669,7 +643,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_if(&mut self, ty: wasmparser::BlockType) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; self.instructions.push(Instruction::JumpIfZero32(0)); self.push_control(BlockKind::If, ty, Some(self.instructions.len() - 1)) } @@ -721,7 +695,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_br_if(&mut self, depth: u32) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let cond_jump_ip = self.instructions.len(); self.instructions.push(Instruction::JumpIfZero32(0)); @@ -745,7 +719,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_br_table(&mut self, targets: wasmparser::BrTable<'_>) -> Self::Output { let ts = targets.targets().collect::, wasmparser::Error>>()?; - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let default_depth = targets.default(); let len = ts.len() as u32; @@ -819,24 +793,24 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_f32_const(&mut self, val: wasmparser::Ieee32) -> Self::Output { - self.emit(&[], &[OperandSize::S32], Instruction::Const32(val.bits() as i32)) + self.emit(&[], &[ValueLane::S32], Instruction::Const32(val.bits() as i32)) } fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - self.emit(&[], &[OperandSize::S64], Instruction::Const64(val.bits() as i64)) + self.emit(&[], &[ValueLane::S64], Instruction::Const64(val.bits() as i64)) } fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; - let len = if dst == OperandSize::S32 || src == OperandSize::S32 { OperandSize::S32 } else { OperandSize::S64 }; + let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; self.emit(&[dst, src, len], &[], Instruction::TableCopy { dst_table, src_table }) } fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; - let len = if dst == OperandSize::S32 || src == OperandSize::S32 { OperandSize::S32 } else { OperandSize::S64 }; + let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem }) } @@ -859,41 +833,41 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_br_on_null(&mut self, relative_depth: u32) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let fallthrough_jump = self.instructions.len(); self.instructions.push(Instruction::JumpIfRefNonNull(0)); self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; self.patch_jump(fallthrough_jump, self.instructions.len()); - self.push_sizes(&[OperandSize::S32]) + self.push_sizes(&[ValueLane::S32]) } fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let fallthrough_jump = self.instructions.len(); self.instructions.push(Instruction::JumpIfRefNull(0)); - self.push_sizes(&[OperandSize::S32])?; + self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; self.emit_branch_jump_or_return(relative_depth)?; self.patch_jump(fallthrough_jump, self.instructions.len()); Ok(()) } fn visit_typed_select_multi(&mut self, tys: Vec) -> Self::Output { - let sizes: Vec<_> = tys.into_iter().map(OperandSize::from).collect(); + let sizes: Vec<_> = tys.into_iter().map(value_lane).collect(); let counts = Self::value_counts(&sizes); self.emit( - &[sizes.as_slice(), sizes.as_slice(), &[OperandSize::S32]].concat(), + &[sizes.as_slice(), sizes.as_slice(), &[ValueLane::S32]].concat(), &sizes, Instruction::SelectMulti(counts), ) } fn visit_typed_select(&mut self, ty: wasmparser::ValType) -> Self::Output { - let size = OperandSize::from(ty); - let instruction = size.choose(Instruction::Select32, Instruction::Select64, Instruction::Select128); - self.emit(&[size, size, OperandSize::S32], &[size], instruction) + let size = value_lane(ty); + let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128); + self.emit(&[size, size, ValueLane::S32], &[size], instruction) } } @@ -1085,8 +1059,8 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { self.emit( - &[OperandSize::S128, OperandSize::S128], - &[OperandSize::S128], + &[ValueLane::S128, ValueLane::S128], + &[ValueLane::S128], Instruction::I8x16Shuffle(self.data.v128_constants.len() as u32), )?; self.data.v128_constants.push(lanes); @@ -1094,7 +1068,7 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output { - self.emit(&[], &[OperandSize::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?; + self.emit(&[], &[ValueLane::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?; self.data.v128_constants.push(*value.bytes()); Ok(()) } @@ -1107,11 +1081,11 @@ impl FunctionBuilder<'_> { target: wasmparser::RefType, branch_on_fail: bool, ) -> Result<()> { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; let conditional_ip = self.instructions.len(); self.instructions.push(Instruction::BrOnCast(0, target, branch_on_fail)); - self.push_sizes(&[OperandSize::S32])?; + self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; self.patch_jump(conditional_ip, self.instructions.len()); @@ -1129,7 +1103,7 @@ impl FunctionBuilder<'_> { .ok_or_else(|| crate::ParseError::Other(alloc::format!("branch depth out of bounds: {depth}"))) } - fn local(&self, idx: u32) -> Result<(OperandSize, u16)> { + fn local(&self, idx: u32) -> Result<(ValueLane, u16)> { let size = *self .local_types .get(idx as usize) @@ -1142,12 +1116,12 @@ impl FunctionBuilder<'_> { } /// Pushes logical operands while maintaining the lane counts used by `DropKeep`. - fn push_sizes(&mut self, sizes: &[OperandSize]) -> Result<()> { + fn push_sizes(&mut self, sizes: &[ValueLane]) -> Result<()> { for &size in sizes { let count = match size { - OperandSize::S32 => &mut self.lane_counts.c32, - OperandSize::S64 => &mut self.lane_counts.c64, - OperandSize::S128 => &mut self.lane_counts.c128, + ValueLane::S32 => &mut self.lane_counts.c32, + ValueLane::S64 => &mut self.lane_counts.c64, + ValueLane::S128 => &mut self.lane_counts.c128, }; *count = count .checked_add(1) @@ -1158,7 +1132,7 @@ impl FunctionBuilder<'_> { } /// Pops an operand, allowing a polymorphic value at an unreachable frame base. - fn pop_expect(&mut self, expected: OperandSize) -> Result<()> { + fn pop_expect(&mut self, expected: ValueLane) -> Result<()> { let frame_height = self.control_stack.last().map_or(0, |frame| frame.height); if self.operand_stack.len() == frame_height && self.is_unreachable() { return Ok(()); @@ -1171,22 +1145,22 @@ impl FunctionBuilder<'_> { return Err(crate::ParseError::Other("logical operand width mismatch".into())); } match actual { - OperandSize::S32 => self.lane_counts.c32 -= 1, - OperandSize::S64 => self.lane_counts.c64 -= 1, - OperandSize::S128 => self.lane_counts.c128 -= 1, + ValueLane::S32 => self.lane_counts.c32 -= 1, + ValueLane::S64 => self.lane_counts.c64 -= 1, + ValueLane::S128 => self.lane_counts.c128 -= 1, } Ok(()) } /// Applies a declared logical stack effect in WebAssembly operand order. - fn apply_effect(&mut self, inputs: &[OperandSize], outputs: &[OperandSize]) -> Result<()> { + fn apply_effect(&mut self, inputs: &[ValueLane], outputs: &[ValueLane]) -> Result<()> { inputs.iter().rev().try_for_each(|&size| self.pop_expect(size))?; self.push_sizes(outputs)?; Ok(()) } /// Applies an instruction's stack effect before adding it to the bytecode. - fn emit(&mut self, inputs: &[OperandSize], outputs: &[OperandSize], instruction: Instruction) -> Result<()> { + fn emit(&mut self, inputs: &[ValueLane], outputs: &[ValueLane], instruction: Instruction) -> Result<()> { self.apply_effect(inputs, outputs)?; self.instructions.push(instruction); Ok(()) @@ -1212,9 +1186,7 @@ impl FunctionBuilder<'_> { fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, initial_jump: Option) -> Result<()> { let signature = match ty { wasmparser::BlockType::Empty => Signature { params: Vec::new(), results: Vec::new() }, - wasmparser::BlockType::Type(ty) => { - Signature { params: Vec::new(), results: alloc::vec![OperandSize::from(ty)] } - } + wasmparser::BlockType::Type(ty) => Signature { params: Vec::new(), results: alloc::vec![value_lane(ty)] }, wasmparser::BlockType::FuncType(idx) => self.metadata.signature(idx)?.clone(), }; for &size in signature.params.iter().rev() { @@ -1263,13 +1235,13 @@ impl FunctionBuilder<'_> { } } - fn value_counts(sizes: &[OperandSize]) -> ValueCounts { + fn value_counts(sizes: &[ValueLane]) -> ValueCounts { let mut counts = ValueCounts::default(); for size in sizes { match size { - OperandSize::S32 => counts.c32 += 1, - OperandSize::S64 => counts.c64 += 1, - OperandSize::S128 => counts.c128 += 1, + ValueLane::S32 => counts.c32 += 1, + ValueLane::S64 => counts.c64 += 1, + ValueLane::S128 => counts.c128 += 1, } } counts diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index 3a7c06d..6a399ee 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -224,9 +224,18 @@ impl Imports { for import in &*module.imports { let (val, func_handle) = if let Some(defined) = self.take_defined(import) { match defined { - Extern::Global(global) => (ExternVal::Global(global.0.addr), None), - Extern::Table(table) => (ExternVal::Table(table.0.addr), None), - Extern::Memory(memory) => (ExternVal::Memory(memory.0.addr), None), + Extern::Global(global) => { + global.0.validate_store(store)?; + (ExternVal::Global(global.0.addr), None) + } + Extern::Table(table) => { + table.0.validate_store(store)?; + (ExternVal::Table(table.0.addr), None) + } + Extern::Memory(memory) => { + memory.0.validate_store(store)?; + (ExternVal::Memory(memory.0.addr), None) + } Extern::Function(func) => (ExternVal::Func(func.addr()), Some(func)), } } else { @@ -246,11 +255,11 @@ impl Imports { match (val, &import.kind) { (ExternVal::Global(global_addr), ImportKind::Global(ty)) => { - let global = store.state.get_global(global_addr); + let global_ty = store.state.globals.ty(global_addr); let expected = ty.with_ty(crate::store::canonicalize_value_type(ty.ty, type_addrs)); - let compatible = global.ty.mutable == ty.mutable - && store.state.value_type_is_subtype(global.ty.ty, expected.ty) - && (!ty.mutable || store.state.value_type_is_subtype(expected.ty, global.ty.ty)); + let compatible = global_ty.mutable == ty.mutable + && store.state.value_type_is_subtype(global_ty.ty, expected.ty) + && (!ty.mutable || store.state.value_type_is_subtype(expected.ty, global_ty.ty)); if !compatible { cold_path(); return Err(LinkingError::incompatible_import_type(import).into()); diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index fb8fdec..f864972 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -123,6 +123,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let val = <$ty>::stack_peek(&self.store.value_stack); <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val); }}; + (global_get $ty:ty, $global_index:expr) => {{ + let addr = self.module.resolve_global_addr(*$global_index); + let value = <$ty>::global_get(&self.store.state.globals, addr); + <$ty>::stack_push(&mut self.store.value_stack, value)?; + }}; + (global_set $ty:ty, $global_index:expr) => {{ + let addr = self.module.resolve_global_addr(*$global_index); + let value = <$ty>::stack_pop(&mut self.store.value_stack); + <$ty>::global_set(&mut self.store.state.globals, addr, value); + }}; } macro_rules! exec_binop { @@ -200,12 +210,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); self.store.value_stack.push(value)?; }}; - (stack_global $vt:ident, $width:tt, $op:ident, $global:ident) => {{ - let TinyWasmValue::$vt(global_val) = - self.store.state.get_global_val(self.module.resolve_global_addr(*$global)) - else { - unreachable!("expected global to be Value32") - }; + (stack_global $vt:ty, $width:tt, $op:ident, $global:ident) => {{ + let global_val = + <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); let stack_val = <$vt>::stack_pop(&mut self.store.value_stack); self.store.value_stack.push(exec_binop!($width, *$op, stack_val, global_val))?; }}; @@ -339,10 +346,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LocalTee32(local_index) => stack_op!(local_tee Value32, local_index), LocalTee64(local_index) => stack_op!(local_tee Value64, local_index), LocalTee128(local_index) => stack_op!(local_tee Value128, local_index), - GlobalGet(global_index) => self.exec_global_get(*global_index)?, - GlobalSet32(global_index) => self.exec_global_set_32(*global_index), - GlobalSet64(global_index) => self.exec_global_set::(*global_index), - GlobalSet128(global_index) => self.exec_global_set::(*global_index), + GlobalGet32(global_index) => stack_op!(global_get Value32, global_index), + GlobalGet64(global_index) => stack_op!(global_get Value64, global_index), + GlobalGet128(global_index) => stack_op!(global_get Value128, global_index), + GlobalSet32(global_index) => stack_op!(global_set Value32, global_index), + GlobalSet64(global_index) => stack_op!(global_set Value64, global_index), + GlobalSet128(global_index) => stack_op!(global_set Value128, global_index), Const32(val) => self.exec_const(*val)?, Const64(val) => self.exec_const(*val)?, I64Eqz => stack_op!(unary i64 => i32, |v| i32::from(v == 0)), @@ -1336,27 +1345,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_global_get(&mut self, global_index: u32) -> Result<(), Trap> { - self.store.value_stack.push_dyn(self.store.state.get_global_val(self.module.resolve_global_addr(global_index))) - } - - fn exec_global_set(&mut self, global_index: u32) { - let global_addr = self.module.resolve_global_addr(global_index); - let value = ::stack_pop(&mut self.store.value_stack).into(); - self.store.state.set_global_val(global_addr, value); - } - - fn exec_global_set_32(&mut self, global_index: u32) { - let global_addr = self.module.resolve_global_addr(global_index); - let raw = ::stack_pop(&mut self.store.value_stack); - let value = match self.store.state.get_global(global_addr).ty.ty { - WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(raw), - WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::from_raw(raw)), - WasmType::I64 | WasmType::F64 | WasmType::V128 => unreachable!("invalid global.set.32 target type"), - }; - self.store.state.set_global_val(global_addr, value); - } - fn exec_const(&mut self, val: T) -> Result<(), Trap> { self.store.value_stack.push(val) } diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 378dc7f..3b5dfe2 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -8,6 +8,10 @@ use crate::interpreter::*; use crate::{Result, Trap}; #[cfg_attr(feature = "debug", derive(Debug))] +/// Physical value lanes used by the interpreter. +/// +/// Guest values should normally be accessed through +/// [`InternalValue`] so their stack and global representation stays consistent. pub(crate) struct ValueStack { pub(crate) stack_32: Stack, pub(crate) stack_64: Stack, diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index f034906..fae7876 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -1,6 +1,7 @@ use super::stack::{CallFrame, ValueStack}; +use crate::store::Globals; use crate::{Result, interpreter::simd::Value128}; -use tinywasm_types::{AnyRef, ExnRef, ExternRef, FuncRef, LocalAddr, RefValue, WasmType, WasmValue}; +use tinywasm_types::{AnyRef, ExnRef, ExternRef, FuncRef, GlobalAddr, LocalAddr, RefValue, WasmType, WasmValue}; pub(crate) type Value32 = u32; pub(crate) type Value64 = u64; @@ -179,7 +180,8 @@ mod sealed { pub trait Sealed {} } -pub(crate) trait InternalValue: sealed::Sealed + Into + Copy + Default { +/// Typed access to values in their physical [`ValueStack`] and [`Globals`] lanes. +pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap>; fn stack_pop(stack: &mut ValueStack) -> Self; fn stack_peek(stack: &ValueStack) -> Self; @@ -188,12 +190,16 @@ pub(crate) trait InternalValue: sealed::Sealed + Into + Copy + De fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self); fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self); fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr); + /// Gets a value from its physical global lane. + fn global_get(globals: &Globals, addr: GlobalAddr) -> Self; + /// Sets a value in its physical global lane. + fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self); } macro_rules! impl_internalvalue { ( $( - $variant:ident, $stack:ident, $stack_base:ident, $outer:ty, + $variant:ident, $stack:ident, $stack_base:ident, $global_get:ident, $global_set:ident, $outer:ty, |$to_value_v:ident| $to_value:expr, |$to_stack_v:ident| $to_stack:expr, |$from_stack_v:ident| $from_stack:expr @@ -248,6 +254,18 @@ macro_rules! impl_internalvalue { stack.$stack.copy(base + from as usize, base + to as usize); } + #[inline(always)] + fn global_get(globals: &Globals, addr: GlobalAddr) -> Self { + let $from_stack_v = globals.$global_get(addr); + $from_stack + } + + #[inline(always)] + fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self) { + let $to_stack_v = value; + globals.$global_set(addr, $to_stack); + } + #[inline(always)] fn stack_pop(stack: &mut ValueStack) -> Self { let $from_stack_v = stack.$stack.pop(); @@ -278,12 +296,12 @@ macro_rules! impl_internalvalue { } impl_internalvalue! { - Value32, stack_32, s32, u32, |v| v, |v| v, |v| v - Value64, stack_64, s64, u64, |v| v, |v| v, |v| v - Value32, stack_32, s32, i32, |v| v as u32, |v| v as u32, |v| v as i32 - Value64, stack_64, s64, i64, |v| v as u64, |v| v as u64, |v| v as i64 - Value32, stack_32, s32, f32, |v| f32::to_bits(v), |v| f32::to_bits(v), |v| f32::from_bits(v) - Value64, stack_64, s64, f64, |v| f64::to_bits(v), |v| f64::to_bits(v), |v| f64::from_bits(v) - ValueRef, stack_32, s32, ValueRef, |v| v, |v| v.raw(), |v| ValueRef(v) - Value128, stack_128, s128, Value128, |v| v, |v| v, |v| v + Value32, stack_32, s32, get_32, set_32, u32, |v| v, |v| v, |v| v + Value64, stack_64, s64, get_64, set_64, u64, |v| v, |v| v, |v| v + Value32, stack_32, s32, get_32, set_32, i32, |v| v as u32, |v| v as u32, |v| v as i32 + Value64, stack_64, s64, get_64, set_64, i64, |v| v as u64, |v| v as u64, |v| v as i64 + Value32, stack_32, s32, get_32, set_32, f32, |v| f32::to_bits(v), |v| f32::to_bits(v), |v| f32::from_bits(v) + Value64, stack_64, s64, get_64, set_64, f64, |v| f64::to_bits(v), |v| f64::to_bits(v), |v| f64::from_bits(v) + ValueRef, stack_32, s32, get_32, set_32, ValueRef, |v| v, |v| v.raw(), |v| ValueRef(v) + Value128, stack_128, s128, get_128, set_128, Value128, |v| v, |v| v, |v| v } diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index d8f9669..ad9cfd9 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -6,9 +6,9 @@ use alloc::string::{String, ToString}; use alloc::vec::Vec; use crate::interpreter::TinyWasmValue; -use crate::store::{GlobalInstance, TableInstance}; +use crate::store::TableInstance; use crate::{Error, MemoryInstance, Result, Store, Trap}; -use tinywasm_types::{Addr, GlobalAddr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue}; +use tinywasm_types::{Addr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "debug", derive(Debug))] @@ -460,28 +460,20 @@ impl Global { cold_path(); return Err(Error::Other("invalid global value type".to_string())); } - let addr = store.state.globals.len() as GlobalAddr; - store.state.globals.push(GlobalInstance::new(ty, value.into())); + let addr = store.state.globals.push(ty, value.into()); Ok(Self(StoreItem::new(store.id(), addr))) } - #[inline] - fn instance<'a>(&self, store: &'a Store) -> Result<&'a GlobalInstance> { - self.0.validate_store(store)?; - Ok(store.state.get_global(self.0.addr)) - } - /// Get the type of the global. pub fn ty(&self, store: &Store) -> Result { - Ok(self.instance(store)?.ty) + self.0.validate_store(store)?; + Ok(store.state.globals.ty(self.0.addr)) } /// Get the current value of the global. pub fn get(&self, store: &Store) -> Result { - let global = self.instance(store)?; - let value = store.state.attach_value(global.value, global.ty.ty); - let value = - value.unwrap_or_else(|| unreachable!("Global value type does not match global type, this is a bug")); + self.0.validate_store(store)?; + let value = store.state.global_wasm_value(self.0.addr); if let WasmValue::Ref(value) = value { store.state.pin_host_ref(value); } @@ -491,16 +483,6 @@ impl Global { /// Set the current value of the global. pub fn set(&self, store: &mut Store, value: WasmValue) -> Result<()> { self.0.validate_store(store)?; - let global = store.state.get_global(self.0.addr); - if !global.ty.mutable { - cold_path(); - return Err(Error::Other("global is immutable".to_string())); - } - if !store.state.value_matches_type(value, global.ty.ty) { - cold_path(); - return Err(Error::Other("invalid global value type".to_string())); - } - store.state.get_global_mut(self.0.addr).value = value.into(); - Ok(()) + store.state.set_global_wasm_value(self.0.addr, value) } } diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index 9280494..c685d89 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -1,17 +1,162 @@ -use crate::interpreter::TinyWasmValue; +use alloc::vec::Vec; use tinywasm_types::*; -/// A WebAssembly Global Instance +use crate::interpreter::{TinyWasmValue, Value32, Value64, Value128, ValueRef}; + +struct GlobalLane { + values: Vec, + types: Vec, +} + +impl Default for GlobalLane { + fn default() -> Self { + Self { values: Vec::new(), types: Vec::new() } + } +} + +impl GlobalLane { + fn push(&mut self, ty: GlobalType, value: T) -> usize { + debug_assert_eq!(self.values.len(), self.types.len()); + let index = self.values.len(); + self.values.push(value); + self.types.push(ty); + index + } + + #[inline(always)] + fn get(&self, index: usize, addr: GlobalAddr) -> T { + *self.values.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + } + + #[inline(always)] + fn set(&mut self, index: usize, addr: GlobalAddr, value: T) { + *self.values.get_mut(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) = value; + } + + fn ty(&self, index: usize, addr: GlobalAddr) -> GlobalType { + *self.types.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + } +} + +/// Global instances split into their physical value lanes. /// -/// See -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct GlobalInstance { - pub(crate) value: TinyWasmValue, - pub(crate) ty: GlobalType, +/// Guest values should normally be accessed through +/// [`InternalValue`](crate::interpreter::InternalValue). Dynamic access is +/// reserved for initialization and host boundaries. +#[derive(Default)] +pub(crate) struct Globals { + globals_32: GlobalLane, + globals_64: GlobalLane, + globals_128: GlobalLane, } -impl GlobalInstance { - pub(crate) fn new(ty: GlobalType, value: TinyWasmValue) -> Self { - Self { ty, value } +impl Globals { + const LANE_SHIFT: u32 = 30; + const INDEX_MASK: u32 = (1 << Self::LANE_SHIFT) - 1; + const LANE_32: u32 = 0; + const LANE_64: u32 = 1 << Self::LANE_SHIFT; + const LANE_128: u32 = 2 << Self::LANE_SHIFT; + + fn addr(lane: u32, index: usize) -> GlobalAddr { + assert!(index <= Self::INDEX_MASK as usize, "too many globals in one value lane"); + lane | index as u32 + } + + #[inline(always)] + fn index(addr: GlobalAddr, lane: u32) -> usize { + debug_assert_eq!(addr & !Self::INDEX_MASK, lane, "global address has the wrong value lane"); + (addr & Self::INDEX_MASK) as usize + } + + /// Returns a global's logical type and mutability. + pub(crate) fn ty(&self, addr: GlobalAddr) -> GlobalType { + match addr & !Self::INDEX_MASK { + Self::LANE_32 => self.globals_32.ty(Self::index(addr, Self::LANE_32), addr), + Self::LANE_64 => self.globals_64.ty(Self::index(addr, Self::LANE_64), addr), + Self::LANE_128 => self.globals_128.ty(Self::index(addr, Self::LANE_128), addr), + _ => unreachable!("invalid global address: {addr}"), + } + } + + /// Adds a global and returns its packed store address. + pub(crate) fn push(&mut self, ty: GlobalType, value: TinyWasmValue) -> GlobalAddr { + match (ty.ty, value) { + (WasmType::I32 | WasmType::F32, TinyWasmValue::Value32(value)) => { + Self::addr(Self::LANE_32, self.globals_32.push(ty, value)) + } + (WasmType::Ref(_), TinyWasmValue::ValueRef(value)) => { + Self::addr(Self::LANE_32, self.globals_32.push(ty, value.raw())) + } + (WasmType::I64 | WasmType::F64, TinyWasmValue::Value64(value)) => { + Self::addr(Self::LANE_64, self.globals_64.push(ty, value)) + } + (WasmType::V128, TinyWasmValue::Value128(value)) => { + Self::addr(Self::LANE_128, self.globals_128.push(ty, value)) + } + _ => unreachable!("global value does not match its declared type"), + } + } + + /// Returns a dynamically represented global value. + pub(crate) fn get(&self, addr: GlobalAddr) -> TinyWasmValue { + let ty = self.ty(addr); + match ty.ty { + WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(self.get_32(addr)), + WasmType::I64 | WasmType::F64 => TinyWasmValue::Value64(self.get_64(addr)), + WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::from_raw(self.get_32(addr))), + WasmType::V128 => TinyWasmValue::Value128(self.get_128(addr)), + } + } + + /// Sets a global from a dynamically represented value. + pub(crate) fn set(&mut self, addr: GlobalAddr, value: TinyWasmValue) { + match (self.ty(addr).ty, value) { + (WasmType::I32 | WasmType::F32, TinyWasmValue::Value32(value)) => self.set_32(addr, value), + (WasmType::Ref(_), TinyWasmValue::ValueRef(value)) => self.set_32(addr, value.raw()), + (WasmType::I64 | WasmType::F64, TinyWasmValue::Value64(value)) => self.set_64(addr, value), + (WasmType::V128, TinyWasmValue::Value128(value)) => self.set_128(addr, value), + _ => unreachable!("global value does not match its declared type"), + } + } + + /// Returns a raw value from the 32-bit lane. + #[inline(always)] + pub(crate) fn get_32(&self, addr: GlobalAddr) -> Value32 { + self.globals_32.get(Self::index(addr, Self::LANE_32), addr) + } + + /// Returns a raw value from the 64-bit lane. + #[inline(always)] + pub(crate) fn get_64(&self, addr: GlobalAddr) -> Value64 { + self.globals_64.get(Self::index(addr, Self::LANE_64), addr) + } + + /// Returns a raw value from the 128-bit lane. + #[inline(always)] + pub(crate) fn get_128(&self, addr: GlobalAddr) -> Value128 { + self.globals_128.get(Self::index(addr, Self::LANE_128), addr) + } + + /// Sets a raw value in the 32-bit lane. + #[inline(always)] + pub(crate) fn set_32(&mut self, addr: GlobalAddr, value: Value32) { + self.globals_32.set(Self::index(addr, Self::LANE_32), addr, value); + } + + /// Sets a raw value in the 64-bit lane. + #[inline(always)] + pub(crate) fn set_64(&mut self, addr: GlobalAddr, value: Value64) { + self.globals_64.set(Self::index(addr, Self::LANE_64), addr, value); + } + + /// Sets a raw value in the 128-bit lane. + #[inline(always)] + pub(crate) fn set_128(&mut self, addr: GlobalAddr, value: Value128) { + self.globals_128.set(Self::index(addr, Self::LANE_128), addr, value); + } + + /// Iterates over globals in the 32-bit lane for root tracing. + pub(crate) fn globals_32(&self) -> impl Iterator + '_ { + self.globals_32.values.iter().copied().zip(self.globals_32.types.iter().copied()) } } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 84c4033..3c80e91 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -72,7 +72,8 @@ impl Store { /// Create a new store pub fn new(engine: Engine) -> Self { let id = STORE_ID.fetch_add(1, Ordering::Relaxed); - let state = State { gc: gc::GcHeap::new(engine.config().gc_collection_threshold), ..State::default() }; + let state = + State { gc: Box::new(gc::GcHeap::new(engine.config().gc_collection_threshold)), ..State::default() }; Self { id, module_instances: Vec::new(), @@ -138,16 +139,16 @@ impl Store { self.module_instances.push(instance); } - /// Get the global at the actual index in the store + /// Gets a global by its opaque store address. #[doc(hidden)] pub fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue { - self.state.get_global_val(addr) + self.state.globals.get(addr) } - /// Set the global at the actual index in the store + /// Sets a global by its opaque store address. #[doc(hidden)] pub fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) { - self.state.set_global_val(addr, value); + self.state.globals.set(addr, value); } /// Returns whether a public value has the requested runtime type. @@ -232,9 +233,6 @@ impl Store { func_addrs: &[FuncAddr], type_addrs: &[TypeAddr], ) -> Result<()> { - let start = self.state.globals.len() as Addr; - out.extend(start..start + globals.len() as Addr); - for global in globals { let value = match self.eval_const(&global.init, out, func_addrs, type_addrs) { Ok(val) => val, @@ -244,7 +242,7 @@ impl Store { } }; let ty = global.ty.with_ty(canonicalize_value_type(global.ty.ty, type_addrs)); - self.state.globals.push(GlobalInstance::new(ty, value)); + out.push(self.state.globals.push(ty, value)); } Ok(()) @@ -439,7 +437,7 @@ impl Store { let addr = *module_global_addrs .get(index as usize) .ok_or_else(|| Error::Other(format!("global {index} not found")))?; - Ok(state.globals.get(addr as usize).ok_or_else(|| Error::Other(format!("global {addr} not found")))?.value) + Ok(state.globals.get(addr)) }; let func_ref = |index: u32| -> Result { let addr = *module_func_addrs diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 125cc30..392035f 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -14,10 +14,10 @@ pub(crate) struct State { pub(crate) funcs: Vec, pub(crate) tables: Vec, pub(crate) memories: Vec, - pub(crate) globals: Vec, + pub(crate) globals: Globals, pub(crate) elements: Vec, pub(crate) data: Vec, - pub(crate) gc: gc::GcHeap, + pub(crate) gc: Box, } impl State { @@ -73,9 +73,9 @@ impl State { .map(ValueRef::from_raw) .chain( self.globals - .iter() - .filter(|global| Self::type_may_contain_gc_in(canonical_types, global.ty.ty)) - .filter_map(|global| global.value.as_ref()), + .globals_32() + .filter(|(_, ty)| Self::type_may_contain_gc_in(canonical_types, ty.ty)) + .map(|(value, _)| ValueRef::from_raw(value)), ) .chain( self.tables @@ -363,23 +363,45 @@ impl State { Self::get_mut(&mut self.elements, addr, "element") } - /// Get the global at the actual index in the store - pub(crate) fn get_global(&self, addr: GlobalAddr) -> &GlobalInstance { - Self::get(&self.globals, addr, "global") - } - - /// Get the global at the actual index in the store - pub(crate) fn get_global_mut(&mut self, addr: GlobalAddr) -> &mut GlobalInstance { - Self::get_mut(&mut self.globals, addr, "global") - } - - /// Get the global at the actual index in the store - pub(crate) fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue { - self.get_global(addr).value + /// Converts a global directly to its public value representation. + pub(crate) fn global_wasm_value(&self, addr: GlobalAddr) -> WasmValue { + let ty = self.globals.ty(addr).ty; + match ty { + WasmType::I32 => WasmValue::I32(self.globals.get_32(addr) as i32), + WasmType::I64 => WasmValue::I64(self.globals.get_64(addr) as i64), + WasmType::F32 => WasmValue::F32(f32::from_bits(self.globals.get_32(addr))), + WasmType::F64 => WasmValue::F64(f64::from_bits(self.globals.get_64(addr))), + WasmType::Ref(_) => self + .attach_value(TinyWasmValue::ValueRef(ValueRef::from_raw(self.globals.get_32(addr))), ty) + .unwrap_or_else(|| unreachable!("global value does not match its type")), + WasmType::V128 => WasmValue::V128(self.globals.get_128(addr).to_le_bytes()), + } } - /// Set the global at the actual index in the store - pub(crate) fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) { - self.get_global_mut(addr).value = value; + /// Validates and sets a global from its public value representation. + pub(crate) fn set_global_wasm_value(&mut self, addr: GlobalAddr, value: WasmValue) -> Result<()> { + let ty = self.globals.ty(addr); + if !ty.mutable { + cold_path(); + return Err(Error::other("global is immutable")); + } + if !self.value_matches_type(value, ty.ty) { + cold_path(); + return Err(Error::other("invalid global value type")); + } + match value { + WasmValue::I32(value) => self.globals.set_32(addr, value as u32), + WasmValue::I64(value) => self.globals.set_64(addr, value as u64), + WasmValue::F32(value) => self.globals.set_32(addr, value.to_bits()), + WasmValue::F64(value) => self.globals.set_64(addr, value.to_bits()), + WasmValue::Ref(value) => { + let TinyWasmValue::ValueRef(value) = TinyWasmValue::from(WasmValue::Ref(value)) else { + unreachable!("reference value did not convert to an internal reference") + }; + self.globals.set_32(addr, value.raw()); + } + WasmValue::V128(value) => self.globals.set_128(addr, value.into()), + } + Ok(()) } } diff --git a/crates/tinywasm/tests/store_ownership.rs b/crates/tinywasm/tests/store_ownership.rs index 8577d73..6cae984 100644 --- a/crates/tinywasm/tests/store_ownership.rs +++ b/crates/tinywasm/tests/store_ownership.rs @@ -1,5 +1,6 @@ use eyre::Result; -use tinywasm::{ModuleInstance, Store}; +use tinywasm::types::{GlobalType, WasmType}; +use tinywasm::{Global, Imports, ModuleInstance, Store}; const MODULE_WAT: &str = r#" (module @@ -86,3 +87,18 @@ fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<()> { Ok(()) } + +#[test] +fn global_import_rejects_wrong_store() -> Result<()> { + let wasm = wat::parse_str(r#"(module (import "env" "g" (global i32)))"#)?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut owner_store = Store::default(); + let global = Global::new(&mut owner_store, GlobalType::new(WasmType::I32, false), 1.into())?; + let mut imports = Imports::default(); + imports.define("env", "g", global); + + let mut other_store = Store::default(); + let err = ModuleInstance::instantiate(&mut other_store, &module, Some(imports)).unwrap_err(); + assert_eq!(err, tinywasm::Error::Trap(tinywasm::Trap::InvalidStore)); + Ok(()) +} diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs new file mode 100644 index 0000000..80494e0 --- /dev/null +++ b/crates/tinywasm/tests/typed_globals.rs @@ -0,0 +1,93 @@ +use eyre::Result; +use tinywasm::types::{GlobalType, Instruction, RefValue, WasmType, WasmValue}; +use tinywasm::{Global, Imports, ModuleInstance, Store}; + +#[test] +fn globals_use_typed_instructions_and_roundtrip_values() -> Result<()> { + let wasm = wat::parse_str( + r#" + (module + (global (mut i32) (i32.const 1)) + (global (mut f32) (f32.const 2)) + (global (mut i64) (i64.const 3)) + (global (mut f64) (f64.const 4)) + (global (mut v128) (v128.const i32x4 1 2 3 4)) + (global (mut funcref) (ref.null func)) + + (func (export "i32") (param i32) (result i32) + local.get 0 global.set 0 global.get 0) + (func (export "f32") (param f32) (result f32) + local.get 0 global.set 1 global.get 1) + (func (export "i64") (param i64) (result i64) + local.get 0 global.set 2 global.get 2) + (func (export "f64") (param f64) (result f64) + local.get 0 global.set 3 global.get 3) + (func (export "v128") (param v128) (result v128) + local.get 0 global.set 4 global.get 4) + (func (export "ref") (param funcref) (result funcref) + local.get 0 global.set 5 global.get 5) + (func (export "add-i32") (param i32) (result i32) + local.get 0 global.get 0 i32.add) + (func (export "add-i64") (param i64) (result i64) + local.get 0 global.get 2 i64.add) + ) + "#, + )?; + + let module = tinywasm::parse_bytes(&wasm)?; + let instructions = module.funcs.iter().flat_map(|func| func.instructions.iter()); + let (mut get32, mut get64, mut get128, mut fused32, mut fused64) = (0, 0, 0, 0, 0); + for instruction in instructions { + match instruction { + Instruction::GlobalGet32(_) => get32 += 1, + Instruction::GlobalGet64(_) => get64 += 1, + Instruction::GlobalGet128(_) => get128 += 1, + Instruction::BinOpStackGlobal32(..) => fused32 += 1, + Instruction::BinOpStackGlobal64(..) => fused64 += 1, + _ => {} + } + } + assert_eq!((get32, get64, get128), (3, 2, 1)); + assert_eq!((fused32, fused64), (1, 1)); + + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let cases = [ + ("i32", WasmValue::I32(11)), + ("f32", WasmValue::F32(12.5)), + ("i64", WasmValue::I64(13)), + ("f64", WasmValue::F64(14.5)), + ("v128", WasmValue::V128([15; 16])), + ("ref", WasmValue::Ref(RefValue::Null)), + ]; + for (name, value) in cases { + assert_eq!(instance.func_untyped(&store, name)?.call(&mut store, &[value])?, vec![value]); + } + assert_eq!(instance.func::(&store, "add-i32")?.call(&mut store, 2)?, 13); + assert_eq!(instance.func::(&store, "add-i64")?.call(&mut store, 2)?, 15); + + Ok(()) +} + +#[test] +fn imported_global_keeps_its_typed_store_address() -> Result<()> { + let wasm = wat::parse_str( + r#" + (module + (import "env" "g" (global (mut i64))) + (func (export "roundtrip") (param i64) (result i64) + local.get 0 global.set 0 global.get 0) + ) + "#, + )?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let global = Global::new(&mut store, GlobalType::new(WasmType::I64, true), WasmValue::I64(1))?; + let mut imports = Imports::default(); + imports.define("env", "g", global); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + + assert_eq!(instance.func::(&store, "roundtrip")?.call(&mut store, 42)?, 42); + assert_eq!(global.get(&store)?, WasmValue::I64(42)); + Ok(()) +} diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 1160fa5..b920ac7 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -239,10 +239,9 @@ pub enum Instruction { // > Variable Instructions // See - GlobalGet(GlobalAddr), - LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), GlobalSet32(GlobalAddr), - LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), GlobalSet64(GlobalAddr), - LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), GlobalSet128(GlobalAddr), + GlobalGet32(GlobalAddr), LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), GlobalSet32(GlobalAddr), + GlobalGet64(GlobalAddr), LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), GlobalSet64(GlobalAddr), + GlobalGet128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), GlobalSet128(GlobalAddr), // > Memory Instructions I32Load(MemoryArg), diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index c461296..0fd4e81 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -362,6 +362,39 @@ impl ExternVal { } } +/// The physical storage lane used by a [`WasmType`]. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum ValueLane { + /// A 32-bit value or reference. + S32, + /// A 64-bit value. + S64, + /// A 128-bit SIMD value. + S128, +} + +impl ValueLane { + /// Selects one of three values based on this lane. + pub fn select(self, s32: T, s64: T, s128: T) -> T { + match self { + Self::S32 => s32, + Self::S64 => s64, + Self::S128 => s128, + } + } +} + +impl From<&WasmType> for ValueLane { + fn from(ty: &WasmType) -> Self { + match ty { + WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => Self::S32, + WasmType::I64 | WasmType::F64 => Self::S64, + WasmType::V128 => Self::S128, + } + } +} + #[derive(Default, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -384,10 +417,10 @@ impl<'a> FromIterator<&'a WasmType> for ValueCounts { let mut counts = Self::default(); for ty in iter { - match ty { - WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => counts.c32 += 1, - WasmType::I64 | WasmType::F64 => counts.c64 += 1, - WasmType::V128 => counts.c128 += 1, + match ValueLane::from(ty) { + ValueLane::S32 => counts.c32 += 1, + ValueLane::S64 => counts.c64 += 1, + ValueLane::S128 => counts.c128 += 1, } } counts -- cgit v1.3.1 From e005e5afd144f5659e2ed19afa8ee94ff924be55 Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 9 Aug 2026 18:07:51 +0200 Subject: feat: initial exception support Signed-off-by: Henry --- CHANGELOG.md | 1 + README.md | 2 +- crates/cli/src/output.rs | 2 + crates/cli/src/wast_runner.rs | 179 ++++++++++++++++++------ crates/parser/src/conversion.rs | 11 +- crates/parser/src/lib.rs | 1 + crates/parser/src/macros.rs | 1 + crates/parser/src/module.rs | 36 +++++ crates/parser/src/optimize.rs | 42 ++++++ crates/parser/src/visit.rs | 127 ++++++++++++++++- crates/tinywasm/Cargo.toml | 2 - crates/tinywasm/src/error.rs | 7 +- crates/tinywasm/src/func/resume.rs | 20 ++- crates/tinywasm/src/imports.rs | 36 +++-- crates/tinywasm/src/instance.rs | 32 ++++- crates/tinywasm/src/interpreter/executor.rs | 158 ++++++++++++++++++--- crates/tinywasm/src/interpreter/mod.rs | 8 +- crates/tinywasm/src/interpreter/num_helpers.rs | 4 +- crates/tinywasm/src/reference.rs | 28 +++- crates/tinywasm/src/store/exception.rs | 10 ++ crates/tinywasm/src/store/mod.rs | 16 ++- crates/tinywasm/src/store/state.rs | 19 +++ crates/tinywasm/src/store/tag.rs | 7 + crates/tinywasm/tests/generated/wasm-3.csv | 2 +- crates/tinywasm/tests/generated/wasm-latest.csv | 2 +- crates/types/src/instructions.rs | 46 +++++- crates/types/src/lib.rs | 48 +++++++ 27 files changed, 744 insertions(+), 103 deletions(-) create mode 100644 crates/tinywasm/src/store/exception.rs create mode 100644 crates/tinywasm/src/store/tag.rs (limited to 'crates/parser/src/optimize.rs') diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ae416e..64366f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added support for the WebAssembly function-references proposal - Added basic support for the WebAssembly garbage-collection proposal +- Added support for the WebAssembly exception-handling proposal, including tags, `try_table`, `throw`, and `throw_ref` - Added `WasmValue::ty` and `WasmValue::matches_type` - Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. diff --git a/README.md b/README.md index 484dbaf..305f61e 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ TinyWasm targets non-JavaScript core proposals through [phase 3](https://github. | [**Custom Page Sizes**](https://github.com/WebAssembly/custom-page-sizes) | 🟢 | 0.9.0 | | [**Typed Function References**](https://github.com/WebAssembly/function-references) | 🟢 | `next` | | [**Garbage Collection**](https://github.com/WebAssembly/gc) | 🟢 | `next` | -| [**Exception Handling**](https://github.com/WebAssembly/exception-handling) | 🌑 | - | +| [**Exception Handling**](https://github.com/WebAssembly/exception-handling) | 🟢 | `next` | | [**Stack Switching**](https://github.com/WebAssembly/stack-switching) | 🌑 | - | | [**Compact Import Section**](https://github.com/WebAssembly/compact-import-section) | 🌑 | - | | [**Threads**](https://github.com/WebAssembly/threads) | 🌑 | - | diff --git a/crates/cli/src/output.rs b/crates/cli/src/output.rs index 40a271e..a2bd287 100644 --- a/crates/cli/src/output.rs +++ b/crates/cli/src/output.rs @@ -77,6 +77,7 @@ pub fn format_export_type(ty: ExportType<'_>) -> String { ExportType::Memory(ty) => format_memory_type(ty), ExportType::Table(ty) => format_table_type(ty), ExportType::Global(ty) => format_global_type(ty), + ExportType::Tag(ty) => format!("tag {}", format_func_type(ty)), } } @@ -86,5 +87,6 @@ pub fn format_import_type(ty: ImportType<'_>) -> String { ImportType::Memory(ty) => format_memory_type(ty), ImportType::Table(ty) => format_table_type(ty), ImportType::Global(ty) => format_global_type(ty), + ImportType::Tag(ty) => format!("tag {}", format_func_type(ty)), } } diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 2ca622d..24483b6 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -19,53 +19,63 @@ const TEST_MAX_SUSPENSIONS: u32 = 1000; #[derive(Default)] struct ModuleRegistry { - modules: HashMap, - named_modules: HashMap, - last_module: Option, + definitions: HashMap, + instances: HashMap, + registered: HashMap, + last_definition: Option, + last_instance: Option, } impl ModuleRegistry { - fn modules(&self) -> &HashMap { - &self.modules + fn registered(&self) -> &HashMap { + &self.registered } - fn update_last_module(&mut self, module: ModuleInstance, name: Option) { - self.last_module = Some(module.clone()); + fn define(&mut self, module: Module, name: Option) { + self.last_definition = Some(module.clone()); if let Some(name) = name { - self.named_modules.insert(name, module); + self.definitions.insert(name, module); } } - fn register(&mut self, name: String, module: ModuleInstance) { + fn definition(&self, id: Option>) -> Option { + match id { + Some(id) => self.definitions.get(id.name()).cloned(), + None => self.last_definition.clone(), + } + } + + fn update_last_instance(&mut self, instance: ModuleInstance, name: Option) { + self.last_instance = Some(instance.clone()); + if let Some(name) = name { + self.instances.insert(name, instance); + } + } + + fn register(&mut self, name: String, id: Option>) -> bool { + let Some(instance) = self.get(id) else { return false }; debug!("registering module: {name}"); - self.modules.insert(name.clone(), module.clone()); - self.last_module = Some(module.clone()); - self.named_modules.insert(name, module); + self.registered.insert(name, instance); + true } fn get_idx(&self, module_id: Option>) -> Option { match module_id { - Some(module) => self - .modules - .get(module.name()) - .or_else(|| self.named_modules.get(module.name())) - .map(ModuleInstance::id), - None => self.last_module.as_ref().map(ModuleInstance::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), } } fn get(&self, module_id: Option>) -> Option { match module_id { Some(module_id) => { - self.modules.get(module_id.name()).or_else(|| self.named_modules.get(module_id.name())).cloned() + self.registered.get(module_id.name()).or_else(|| self.instances.get(module_id.name())).cloned() } - None => self.last_module.clone(), + None => self.last_instance.clone(), } } - - fn last(&self) -> Option { - self.last_module.clone() - } } #[derive(Default)] @@ -200,6 +210,11 @@ impl WastRunner { Ok(imports) } + fn instantiate_module(store: &mut Store, registry: &ModuleRegistry, module: &Module) -> Result { + let imports = Self::imports(store, registry.registered())?; + Ok(ModuleInstance::instantiate(store, module, Some(&imports))?) + } + pub fn run_file(&mut self, file: TestFile<'_>) -> Result<()> { let test_group = self.test_group(file.name(), file.parent()); let wast_raw = file.raw(); @@ -213,51 +228,72 @@ impl WastRunner { for (i, directive) in directives.into_iter().enumerate() { let span = directive.span(); use wast::WastDirective::{ - AssertExhaustion, AssertInvalid, AssertMalformed, AssertReturn, AssertTrap, AssertUnlinkable, Invoke, - Module as Wat, ModuleDefinition, Register, + AssertException, AssertExhaustion, AssertInvalid, AssertMalformed, AssertReturn, AssertTrap, + AssertUnlinkable, Invoke, Module as Wat, ModuleDefinition, ModuleInstance as Instance, Register, }; match directive { - Register { span, name, .. } => { - let Some(last) = module_registry.last() else { + Register { span, name, module } => { + if !module_registry.register(name.to_string(), module) { test_group.add_result( &format!("Register({i})"), span.linecol_in(wast_raw), - Err(eyre!("no module to register")), + Err(eyre!("module instance to register was not found")), ); continue; - }; - module_registry.register(name.to_string(), last); + } test_group.add_result(&format!("Register({i})"), span.linecol_in(wast_raw), Ok(())); } Wat(module) => { let result = catch_unwind_silent(|| { - let (name, bytes) = encode_quote_wat(module); - let module = parse_module_bytes(&bytes).expect("failed to parse module bytes"); - let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); - let module_instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)) + let (name, module) = parse_quote_module(module).expect("failed to parse module bytes"); + let instance = Self::instantiate_module(&mut store, &module_registry, &module) .expect("failed to instantiate module"); - (name, module_instance) + (name, instance) }) .map_err(|e| eyre!("failed to parse wat module: {}", try_downcast_panic(e))); match &result { Err(err) => debug!("failed to parse module: {err:?}"), - Ok((name, module)) => module_registry.update_last_module(module.clone(), name.clone()), + Ok((name, instance)) => module_registry.update_last_instance(instance.clone(), name.clone()), }; test_group.add_result(&format!("Wat({i})"), span.linecol_in(wast_raw), result.map(|_| ())); } ModuleDefinition(module) => { + let result = + catch_unwind_silent(|| parse_quote_module(module).expect("failed to parse module definition")) + .map_err(|err| eyre!("failed to parse module definition: {}", try_downcast_panic(err))); + + if let Ok((name, module)) = &result { + module_registry.define(module.clone(), name.clone()); + } + + test_group.add_result( + &format!("ModuleDefinition({i})"), + span.linecol_in(wast_raw), + result.map(|_| ()), + ); + } + Instance { span, instance, module } => { + let name = instance.map(|id| id.name().to_string()); let result = catch_unwind_silent(|| { - let (_, bytes) = encode_quote_wat(module); - parse_module_bytes(&bytes) + let module = module_registry + .definition(module) + .ok_or_else(|| eyre!("module definition was not found"))?; + Self::instantiate_module(&mut store, &module_registry, &module) }) - .map_err(|err| eyre!("failed to parse module definition: {}", try_downcast_panic(err))) - .and_then(|result| result) - .map(|_| ()); + .map_err(|err| eyre!("failed to instantiate module definition: {}", try_downcast_panic(err))) + .and_then(|result| result); - test_group.add_result(&format!("ModuleDefinition({i})"), span.linecol_in(wast_raw), result); + if let Ok(instance) = &result { + module_registry.update_last_instance(instance.clone(), name); + } + test_group.add_result( + &format!("ModuleInstance({i})"), + span.linecol_in(wast_raw), + result.map(|_| ()), + ); } AssertMalformed { span, mut module, message } => { let Ok(encoded) = module.encode() else { @@ -330,7 +366,7 @@ impl WastRunner { wast::WastExecute::Wat(mut wat) => { let module = parse_module_bytes(&wat.encode().expect("failed to encode module")) .expect("failed to parse module"); - let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); + let imports = Self::imports(&mut store, module_registry.registered()).unwrap(); ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; return Ok(()); } @@ -371,11 +407,37 @@ impl WastRunner { ), } } + AssertException { exec, span } => { + let res: Result, _> = catch_unwind_silent(|| { + let invoke = match exec { + wast::WastExecute::Wat(mut wat) => { + let module = parse_module_bytes(&wat.encode().expect("failed to encode module")) + .expect("failed to parse module"); + let imports = Self::imports(&mut store, module_registry.registered()).unwrap(); + ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + return Ok(()); + } + wast::WastExecute::Get { .. } => panic!("get not supported"), + wast::WastExecute::Invoke(invoke) => invoke, + }; + let module = module_registry.get_idx(invoke.module); + let args = + convert_wastargs(invoke.args).map_err(|err| tinywasm::Error::Other(err.to_string()))?; + exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ()) + }); + let result = match res { + Err(err) => Err(eyre!("test panicked: {}", try_downcast_panic(err))), + Ok(Err(tinywasm::Error::Exception(_))) => Ok(()), + Ok(Err(err)) => Err(eyre!("expected exception, got: {err:?}")), + Ok(Ok(())) => Err(eyre!("expected exception, got Ok")), + }; + test_group.add_result(&format!("AssertException({i})"), span.linecol_in(wast_raw), result); + } AssertUnlinkable { mut module, span, message } => { let res = catch_unwind_silent(|| { let module = parse_module_bytes(&module.encode().expect("failed to encode module")) .expect("failed to parse module"); - let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); + let imports = Self::imports(&mut store, module_registry.registered()).unwrap(); ModuleInstance::instantiate(&mut store, &module, Some(&imports)) }); match res { @@ -729,6 +791,11 @@ fn parse_module_bytes(bytes: &[u8]) -> Result { Ok(tinywasm::parse_bytes(bytes)?) } +fn parse_quote_module(module: QuoteWat) -> Result<(Option, Module)> { + let (name, bytes) = encode_quote_wat(module); + Ok((name, parse_module_bytes(&bytes)?)) +} + fn convert_wastargs(args: Vec) -> Result> { args.into_iter().map(wastarg2tinywasmvalue).collect() } @@ -947,4 +1014,26 @@ mod tests { let mut runner = WastRunner::new(); runner.run_paths(&[path]).unwrap(); } + + #[test] + fn runs_module_definition_and_instance_directives() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("instance.wast"); + std::fs::write( + &path, + r#" + (module definition $M (global (export "g") i32 (i32.const 42))) + (module instance $I $M) + (register "I" $I) + (module + (import "I" "g" (global $g i32)) + (func (export "get") (result i32) global.get $g)) + (assert_return (invoke "get") (i32.const 42)) + "#, + ) + .unwrap(); + + let mut runner = WastRunner::new(); + runner.run_paths(&[path]).unwrap(); + } } diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 4073a8e..7b52363 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -76,9 +76,7 @@ pub(crate) fn convert_module_import(import: wasmparser::Import<'_>) -> Result { ImportKind::Global(GlobalType::new(convert_valtype(&ty.content_type)?, ty.mutable)) } - wasmparser::TypeRef::Tag(ty) => { - return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {ty:?}"))); - } + wasmparser::TypeRef::Tag(ty) => ImportKind::Tag(convert_tag_type(ty)), _ => { return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {:?}", import.ty))); } @@ -116,7 +114,8 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result ExternalKind::Table, wasmparser::ExternalKind::Memory => ExternalKind::Memory, wasmparser::ExternalKind::Global => ExternalKind::Global, - wasmparser::ExternalKind::Tag | wasmparser::ExternalKind::FuncExact => { + wasmparser::ExternalKind::Tag => ExternalKind::Tag, + wasmparser::ExternalKind::FuncExact => { return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported export kind: {:?}", export.kind))); } }; @@ -124,6 +123,10 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result TagType { + TagType::new(ty.func_type_idx) +} + fn extend_local_types(local_types: &mut Vec, count: u32, ty: wasmparser::ValType) -> Result<()> { let size = value_lane(ty); let count = diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index fe968d8..8b6cb39 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -189,6 +189,7 @@ impl Parser { | WasmFeatures::SIMD | WasmFeatures::MEMORY64 | WasmFeatures::CUSTOM_PAGE_SIZES + | WasmFeatures::EXCEPTIONS | WasmFeatures::WIDE_ARITHMETIC; self.options.validation().then(|| Validator::new_with_features(features)) } diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index db1402d..98312ab 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -160,6 +160,7 @@ pub(crate) mod visit { (@@tail_call $($rest:tt)* ) => {}; (@@function_references $($rest:tt)* ) => {}; (@@gc $($rest:tt)* ) => {}; + (@@exceptions $($rest:tt)* ) => {}; (@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => { fn $visit(&mut self $($(,_: $argty)*)?) -> Self::Output { diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 237478c..bbe2cf8 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -57,6 +57,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) globals: Box<[Global]>, pub(crate) tables: Box<[TableDefinition]>, pub(crate) memory_types: Box<[MemoryType]>, + pub(crate) tags: Box<[TagType]>, pub(crate) imports: Box<[Import]>, pub(crate) data: Box<[Data]>, pub(crate) elements: Box<[Element]>, @@ -78,6 +79,7 @@ impl<'a> ModuleReader<'a> { &self.globals, &self.memory_types, &self.tables, + &self.tags, ))); } self.translation_metadata.as_deref().unwrap() @@ -182,6 +184,25 @@ impl<'a> ModuleReader<'a> { self.memory_types = reader.into_iter().map(|memory| Ok(convert_module_memory(memory?))).collect::>()?; } + Payload::TagSection(reader) => { + check_section("tag", !self.tags.is_empty())?; + #[cfg(feature = "validate")] + if let Some(validator) = validator.as_mut() { + validator.tag_section(&reader)?; + } + let mut tags = Vec::with_capacity(reader.count() as usize); + for tag in reader { + let tag = convert_tag_type(tag?); + let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| { + ParseError::Other(format!("tag type index does not reference a function: {}", tag.type_idx)) + })?; + if !ty.results().is_empty() { + return Err(ParseError::Other(format!("tag type must not have results: {}", tag.type_idx))); + } + tags.push(tag); + } + self.tags = tags.into_boxed_slice(); + } Payload::ElementSection(reader) => { debug!("Found element section"); #[cfg(feature = "validate")] @@ -249,6 +270,20 @@ impl<'a> ModuleReader<'a> { self.imported_func_count += 1; } ImportKind::Memory(_) => self.imported_memory_count += 1, + ImportKind::Tag(tag) => { + let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| { + ParseError::Other(format!( + "tag import type index does not reference a function: {}", + tag.type_idx + )) + })?; + if !ty.results().is_empty() { + return Err(ParseError::Other(format!( + "tag import type must not have results: {}", + tag.type_idx + ))); + } + } _ => {} } imports.push(import); @@ -553,6 +588,7 @@ impl<'a> ModuleReader<'a> { exports: self.exports, elements: self.elements, memory_types: self.memory_types, + tags: self.tags, local_memory_allocation, } .into()) diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 74a9fc0..be37e5e 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -910,11 +910,28 @@ fn is_unconditional_terminator(instr: Instruction) -> bool { | Instruction::ReturnCallSelf | Instruction::ReturnCallIndirect(..) | Instruction::ReturnCallRef(_) + | Instruction::Throw(_) + | Instruction::ThrowRef ) } fn target_boundaries(instructions: &[Instruction], function_data: &WasmFunctionData) -> Result> { let mut boundaries = alloc::vec![false; instructions.len() + 1]; + for handler in &function_data.exception_handlers { + for target in [handler.start_ip, handler.end_ip] { + let boundary = boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) + })?; + *boundary = true; + } + for catch in &handler.catches { + let target = catch.landing_pad(); + let boundary = boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))?; + *boundary = true; + } + } for instr in instructions { if let Some(target) = instruction_target(instr) { let boundary = boundaries @@ -948,6 +965,31 @@ fn finalize( imported_memory_count: u32, ) -> Result { let len = instructions.len() as u32; + for handler in &mut function_data.exception_handlers { + if let Some(old_to_new) = old_to_new { + handler.start_ip = *old_to_new.get(handler.start_ip as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.start_ip)) + })?; + handler.end_ip = *old_to_new.get(handler.end_ip as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.end_ip)) + })?; + for catch in &mut handler.catches { + let landing_pad = match catch { + tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } + | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, + }; + *landing_pad = *old_to_new.get(*landing_pad as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception landing pad out of bounds: {landing_pad}")) + })?; + } + } + if handler.start_ip > handler.end_ip || handler.end_ip > len { + return Err(ParseError::Other("exception handler range out of bounds".into())); + } + if handler.catches.iter().any(|catch| catch.landing_pad() >= len) { + return Err(ParseError::Other("exception landing pad out of bounds".into())); + } + } for target in &mut function_data.branch_table_targets { if let Some(old_to_new) = old_to_new { *target = *old_to_new diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 46d1f9f..c462d05 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -6,8 +6,8 @@ use crate::{ use alloc::string::ToString; use alloc::vec::Vec; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TypeSection, - ValueCounts, ValueLane, WasmFunctionData, + Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TagType, + TypeSection, ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -20,6 +20,7 @@ enum BlockKind { Block, Loop, If, + TryTable(usize), } struct ControlFrame { @@ -48,6 +49,7 @@ pub(crate) struct ModuleMetadata { globals: Vec, memories: Vec, tables: Vec, + tags: Vec, types: Vec, } @@ -55,6 +57,7 @@ pub(crate) struct ModuleMetadata { struct FunctionDataBuilder { v128_constants: Vec<[u8; 16]>, branch_table_targets: Vec, + exception_handlers: Vec, } pub(crate) struct FunctionBuilder<'a> { @@ -133,11 +136,13 @@ impl ModuleMetadata { globals: &[Global], memories: &[MemoryType], tables: &[TableDefinition], + tags: &[TagType], ) -> Self { let mut functions = Vec::with_capacity(imports.len() + code_type_addrs.len()); let mut global_sizes = Vec::with_capacity(imports.len() + globals.len()); let mut memory_sizes = Vec::with_capacity(imports.len() + memories.len()); let mut table_sizes = Vec::with_capacity(imports.len() + tables.len()); + let mut tag_types = Vec::with_capacity(imports.len() + tags.len()); for import in imports { match &import.kind { @@ -145,6 +150,7 @@ impl ModuleMetadata { ImportKind::Global(ty) => global_sizes.push(ValueLane::from(&ty.ty)), ImportKind::Memory(ty) => memory_sizes.push(Self::address_lane(ty.arch())), ImportKind::Table(ty) => table_sizes.push(Self::address_lane(ty.arch())), + ImportKind::Tag(ty) => tag_types.push(ty.type_idx), } } @@ -152,6 +158,7 @@ impl ModuleMetadata { global_sizes.extend(globals.iter().map(|global| ValueLane::from(&global.ty.ty))); memory_sizes.extend(memories.iter().map(|ty| Self::address_lane(ty.arch()))); table_sizes.extend(tables.iter().map(|table| Self::address_lane(table.ty.arch()))); + tag_types.extend(tags.iter().map(|tag| tag.type_idx)); let signatures = types .types @@ -169,6 +176,7 @@ impl ModuleMetadata { globals: global_sizes, memories: memory_sizes, tables: table_sizes, + tags: tag_types, types: types.types.to_vec(), } } @@ -188,6 +196,14 @@ impl ModuleMetadata { self.signature(ty) } + fn tag_signature(&self, idx: u32) -> Result<&Signature> { + let ty = *self + .tags + .get(idx as usize) + .ok_or_else(|| crate::ParseError::Other(alloc::format!("tag index out of bounds: {idx}")))?; + self.signature(ty) + } + fn global_size(&self, idx: u32) -> Result { Self::indexed_size(&self.globals, "global", idx) } @@ -284,6 +300,7 @@ pub(crate) fn process_operators( let data = WasmFunctionData { v128_constants: builder.data.v128_constants.into_boxed_slice(), branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), + exception_handlers: builder.data.exception_handlers.into_boxed_slice(), }; Ok((builder.instructions, data, reader.into_allocations())) } @@ -320,6 +337,7 @@ pub(crate) fn process_operators_and_validate( let data = WasmFunctionData { v128_constants: builder.data.v128_constants.into_boxed_slice(), branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), + exception_handlers: builder.data.exception_handlers.into_boxed_slice(), }; Ok((builder.instructions, data, validator.into_allocations(), reader.into_allocations())) } @@ -648,6 +666,89 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.push_control(BlockKind::If, ty, Some(self.instructions.len() - 1)) } + fn visit_try_table(&mut self, try_table: wasmparser::TryTable) -> Self::Output { + let signature = self.block_signature(try_table.ty)?; + for &size in signature.params.iter().rev() { + self.pop_expect(size)?; + } + let height = self.operand_stack.len(); + let base = self.lane_counts; + let entry_unreachable = self.is_unreachable(); + + let body_jump = self.instructions.len(); + self.instructions.push(Instruction::Jump(0)); + let mut catches = Vec::with_capacity(try_table.catches.len()); + for catch in try_table.catches { + let (tag, depth, with_ref) = match catch { + wasmparser::Catch::One { tag, label } => (Some(tag), label, false), + wasmparser::Catch::OneRef { tag, label } => (Some(tag), label, true), + wasmparser::Catch::All { label } => (None, label, false), + wasmparser::Catch::AllRef { label } => (None, label, true), + }; + if let Some(tag) = tag { + self.metadata.tag_signature(tag)?; + } + let target_idx = self.get_ctx_idx(depth)?; + let target_base = self.control_stack[target_idx].base; + let landing_pad = u32::try_from(self.instructions.len()) + .map_err(|_| crate::ParseError::Other("function body is too large".into()))?; + match self.control_stack[target_idx].kind { + BlockKind::Function => self.instructions.push(Instruction::Return), + BlockKind::Loop => { + self.instructions.push(Instruction::Jump(self.control_stack[target_idx].start_ip as u32)); + } + BlockKind::Block | BlockKind::If | BlockKind::TryTable(_) => { + self.control_stack[target_idx].branch_jumps.push(self.instructions.len()); + self.control_stack[target_idx].end_reachable = true; + self.instructions.push(Instruction::Jump(0)); + } + } + catches.push(match tag { + Some(tag) => tinywasm_types::ExceptionCatch::Tag { tag, landing_pad, base: target_base, with_ref }, + None => tinywasm_types::ExceptionCatch::All { landing_pad, base: target_base, with_ref }, + }); + } + + let body_start = self.instructions.len(); + self.patch_jump(body_jump, body_start); + let handler_idx = self.data.exception_handlers.len(); + self.data.exception_handlers.push(tinywasm_types::ExceptionHandler { + start_ip: body_start as u32, + end_ip: 0, + catches: catches.into_boxed_slice(), + }); + self.push_sizes(&signature.params)?; + self.control_stack.push(ControlFrame { + kind: BlockKind::TryTable(handler_idx), + has_else: false, + start_ip: body_start, + branch_jumps: Vec::new(), + height, + base, + params: signature.params, + results: signature.results, + unreachable: entry_unreachable, + entry_unreachable, + end_reachable: false, + }); + Ok(()) + } + + fn visit_throw(&mut self, tag_index: u32) -> Self::Output { + let signature = self.metadata.tag_signature(tag_index)?.clone(); + self.apply_effect(&signature.params, &[])?; + self.instructions.push(Instruction::Throw(tag_index)); + self.mark_unreachable(); + Ok(()) + } + + fn visit_throw_ref(&mut self) -> Self::Output { + self.apply_effect(&[ValueLane::S32], &[])?; + self.instructions.push(Instruction::ThrowRef); + self.mark_unreachable(); + Ok(()) + } + fn visit_else(&mut self) -> Self::Output { let (cond_jump_ip, height, base, params, entry_unreachable) = { let ctx = self @@ -672,6 +773,9 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_end(&mut self) -> Self::Output { let ctx = self.control_stack.pop().ok_or_else(|| crate::ParseError::Other("end without control frame".into()))?; + if let BlockKind::TryTable(handler_idx) = ctx.kind { + self.data.exception_handlers[handler_idx].end_ip = self.instructions.len() as u32; + } if matches!(ctx.kind, BlockKind::Function) { self.instructions.push(Instruction::Return); } else { @@ -1184,11 +1288,24 @@ impl FunctionBuilder<'_> { /// Enters a control frame with its parameters restored above the saved base. fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, initial_jump: Option) -> Result<()> { - let signature = match ty { + let signature = self.block_signature(ty)?; + self.push_control_signature(kind, signature, initial_jump) + } + + fn block_signature(&self, ty: wasmparser::BlockType) -> Result { + Ok(match ty { wasmparser::BlockType::Empty => Signature { params: Vec::new(), results: Vec::new() }, wasmparser::BlockType::Type(ty) => Signature { params: Vec::new(), results: alloc::vec![value_lane(ty)] }, wasmparser::BlockType::FuncType(idx) => self.metadata.signature(idx)?.clone(), - }; + }) + } + + fn push_control_signature( + &mut self, + kind: BlockKind, + signature: Signature, + initial_jump: Option, + ) -> Result<()> { for &size in signature.params.iter().rev() { self.pop_expect(size)?; } @@ -1264,7 +1381,7 @@ impl FunctionBuilder<'_> { match self.control_stack[ctx_idx].kind { BlockKind::Function => self.instructions.push(Instruction::Return), BlockKind::Loop => self.instructions.push(Instruction::Jump(self.control_stack[ctx_idx].start_ip as u32)), - BlockKind::Block | BlockKind::If => { + BlockKind::Block | BlockKind::If | BlockKind::TryTable(_) => { self.control_stack[ctx_idx].branch_jumps.push(self.instructions.len()); self.control_stack[ctx_idx].end_reachable = true; self.instructions.push(Instruction::Jump(0)); diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 6cf9b17..67d0742 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -34,7 +34,6 @@ name = "test-wasm-1" [[test]] harness = false name = "test-wasm-3" -test = false [[test]] harness = false @@ -43,7 +42,6 @@ name = "test-wasm-2" [[test]] harness = false name = "test-wasm-latest" -test = false [[test]] harness = false diff --git a/crates/tinywasm/src/error.rs b/crates/tinywasm/src/error.rs index ebd0470..0597847 100644 --- a/crates/tinywasm/src/error.rs +++ b/crates/tinywasm/src/error.rs @@ -2,8 +2,8 @@ use alloc::boxed::Box; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::fmt::{Debug, Display}; -use tinywasm_types::FuncType; use tinywasm_types::archive::TwasmError; +use tinywasm_types::{ExnRef, FuncType}; #[cfg(feature = "parser")] pub use tinywasm_parser::ParseError; @@ -14,6 +14,9 @@ pub enum Error { /// A WebAssembly trap occurred Trap(Trap), + /// An uncaught WebAssembly exception occurred. + Exception(ExnRef), + /// A linking error occurred Linker(LinkingError), @@ -50,6 +53,7 @@ impl PartialEq for Error { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Trap(a), Self::Trap(b)) => a == b, + (Self::Exception(a), Self::Exception(b)) => a == b, (Self::Linker(a), Self::Linker(b)) => a == b, (Self::UnsupportedFeature(a), Self::UnsupportedFeature(b)) => a == b, (Self::Other(a), Self::Other(b)) => a == b, @@ -274,6 +278,7 @@ impl Display for Error { Self::Twasm(err) => write!(f, "serialization error: {err}"), Self::Trap(trap) => write!(f, "trap: {trap}"), + Self::Exception(_) => write!(f, "uncaught WebAssembly exception"), Self::Linker(err) => write!(f, "linking error: {err}"), Self::InvalidLabelType => write!(f, "invalid label type"), Self::Other(message) => write!(f, "unknown error: {message}"), diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs index a71be32..892aa05 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -3,7 +3,7 @@ use tinywasm_types::{FuncAddr, TypeAddr, WasmValue}; use super::{FromWasmValues, Function, FunctionTyped, IntoWasmValues}; use crate::interpreter::stack::{CallFrame, StackBase}; -use crate::{Error, InterpreterRuntime, Result, Store, Trap}; +use crate::{Error, InterpreterRuntime, Result, Store}; #[derive(Clone, PartialEq, Eq)] /// Progress for fuel-limited function execution. @@ -93,7 +93,7 @@ impl Function { impl<'store> FuncExecution<'store> { fn resume_raw( &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result, + run: impl FnOnce(&mut Store, CallFrame) -> Result, ) -> Result> { let (callframe, root_func_addr) = match &mut self.state { FuncExecutionState::Running { callframe, root_func_addr } => (*callframe, *root_func_addr), @@ -109,7 +109,17 @@ impl<'store> FuncExecution<'store> { let result = run(self.store, callframe); self.store.exit_execution(); - match result? { + let result = match result { + Ok(result) => result, + Err(error) => { + self.store.call_stack.clear(); + self.store.value_stack.clear(); + self.state = FuncExecutionState::Completed(None); + return Err(error); + } + }; + + match result { crate::interpreter::ExecState::Completed => { let func = self.store.state.get_func(root_func_addr); let result_ty = func.type_addr; @@ -129,7 +139,7 @@ impl<'store> FuncExecution<'store> { fn resume( &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result, + run: impl FnOnce(&mut Store, CallFrame) -> Result, ) -> Result>> { match self.resume_raw(run)? { ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => { @@ -231,7 +241,7 @@ impl FunctionTyped { impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> { fn resume( &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result, + run: impl FnOnce(&mut Store, CallFrame) -> Result, ) -> Result> { match self.execution.resume_raw(run)? { ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => Ok(ExecProgress::Completed( diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index a35cf2c..8232a90 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -3,7 +3,7 @@ use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::hint::cold_path; -use crate::{Function, Global, HostFunction, LinkingError, Memory, Result, Table}; +use crate::{Function, Global, HostFunction, LinkingError, Memory, Result, Table, Tag}; use tinywasm_types::*; #[derive(Clone)] @@ -21,6 +21,8 @@ pub enum Extern { Function(Function), /// A reusable host function definition. HostFunction(HostFunction), + /// A tag instance. + Tag(Tag), } macro_rules! impl_conv { @@ -41,6 +43,7 @@ impl_conv! { Memory => Memory, Function => Function, HostFunction => HostFunction, + Tag => Tag, } /// Imports for a module instance @@ -100,6 +103,7 @@ pub(crate) struct ResolvedImports { pub(crate) tables: Vec, pub(crate) memories: Vec, pub(crate) funcs: Vec, + pub(crate) tags: Vec, } impl Imports { @@ -127,7 +131,7 @@ impl Imports { /// Define an import value. /// - /// A [`Function`], [`Global`], [`Table`], or [`Memory`] handle belongs to + /// A [`Function`], [`Global`], [`Table`], [`Memory`], or [`Tag`] handle belongs to /// one store and can only be imported into that store. A [`HostFunction`] /// is a reusable definition and can be imported into multiple stores. /// @@ -225,12 +229,13 @@ impl Imports { module: &Module, type_addrs: &[TypeAddr], ) -> Result { - let (global_count, table_count, mem_count, func_count) = - module.imports.iter().fold((0, 0, 0, 0), |(g, t, m, f), import| match import.kind { - ImportKind::Global(_) => (g + 1, t, m, f), - ImportKind::Table(_) => (g, t + 1, m, f), - ImportKind::Memory(_) => (g, t, m + 1, f), - ImportKind::Function(_) => (g, t, m, f + 1), + let (global_count, table_count, mem_count, func_count, tag_count) = + module.imports.iter().fold((0, 0, 0, 0, 0), |(g, t, m, f, e), import| match import.kind { + ImportKind::Global(_) => (g + 1, t, m, f, e), + ImportKind::Table(_) => (g, t + 1, m, f, e), + ImportKind::Memory(_) => (g, t, m + 1, f, e), + ImportKind::Function(_) => (g, t, m, f + 1, e), + ImportKind::Tag(_) => (g, t, m, f, e + 1), }); let mut imports = ResolvedImports { @@ -238,6 +243,7 @@ impl Imports { tables: Vec::with_capacity(table_count + module.tables.len()), memories: Vec::with_capacity(mem_count + module.memory_types.len()), funcs: Vec::with_capacity(func_count + module.funcs.len()), + tags: Vec::with_capacity(tag_count + module.tags.len()), }; for import in &*module.imports { @@ -259,6 +265,10 @@ impl Imports { Extern::HostFunction(func) => { (ExternVal::Func(func.instantiate_for_import(store, type_addrs)?.addr()), None) } + Extern::Tag(tag) => { + tag.0.validate_store(store)?; + (ExternVal::Tag(tag.0.addr), None) + } } } else { let Some(instance) = self.modules.get(import.module.as_ref()) else { @@ -317,6 +327,16 @@ impl Imports { } imports.funcs.push(func_addr); } + (ExternVal::Tag(tag_addr), ImportKind::Tag(ty)) => { + let expected_type_addr = type_addrs + .get(ty.type_idx as usize) + .ok_or_else(|| LinkingError::incompatible_import_type(import))?; + if store.state.get_tag(tag_addr).type_addr != *expected_type_addr { + cold_path(); + return Err(LinkingError::incompatible_import_type(import).into()); + } + imports.tags.push(tag_addr); + } _ => unreachable!("import kind checked above"), } } diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 52bb948..23bb298 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -4,7 +4,7 @@ use tinywasm_types::*; use crate::func::{FromWasmValues, IntoWasmValues, ToWasmTypes}; use crate::store::MemoryInstance; -use crate::{Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Trap}; +use crate::{Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Tag, Trap}; /// A typed view over an exported extern value. pub enum ExternItem { @@ -16,6 +16,8 @@ pub enum ExternItem { Table(Table), /// Exported global reference. Global(Global), + /// Exported tag reference. + Tag(Tag), } /// An instantiated WebAssembly module @@ -52,6 +54,7 @@ struct ModuleInstanceInner { table_addrs: Box<[TableAddr]>, mem_addrs: Box<[MemAddr]>, global_addrs: Box<[GlobalAddr]>, + tag_addrs: Box<[TagAddr]>, elem_addrs: Box<[ElemAddr]>, data_addrs: Box<[DataAddr]>, func_start: Option, @@ -100,6 +103,11 @@ impl ModuleInstance { *self.0.global_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) } + #[inline] + pub(crate) fn resolve_tag_addr(&self, addr: TagAddr) -> TagAddr { + *self.0.tag_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid tag address: {addr}")) + } + #[inline] pub(crate) fn validate_store(&self, store: &Store) -> Result<()> { if self.0.store_id != store.id() { @@ -157,6 +165,7 @@ impl ModuleInstance { let mut addrs = imports.unwrap_or(&default_imports).link(store, module, &type_addrs)?; let imported_funcs = addrs.funcs.len(); addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs)); + addrs.tags.extend(store.init_tags(&module.tags, &type_addrs)); match module.local_memory_allocation { LocalMemoryAllocation::Skip => { #[cfg(feature = "guest-debug")] @@ -185,6 +194,7 @@ impl ModuleInstance { table_addrs: addrs.tables.into_boxed_slice(), mem_addrs: addrs.memories.into_boxed_slice(), global_addrs: addrs.globals.into_boxed_slice(), + tag_addrs: addrs.tags.into_boxed_slice(), elem_addrs, data_addrs, func_start: module.start_func, @@ -209,6 +219,7 @@ impl ModuleInstance { ExternalKind::Table => self.0.table_addrs.get(export.index as usize)?, ExternalKind::Memory => self.0.mem_addrs.get(export.index as usize)?, ExternalKind::Global => self.0.global_addrs.get(export.index as usize)?, + ExternalKind::Tag => self.0.tag_addrs.get(export.index as usize)?, }; Some(ExternVal::new(export.kind, *addr)) } @@ -257,6 +268,9 @@ impl ModuleInstance { ExternalKind::Global => { ExternItem::Global(Global(StoreItem::new(self.0.store_id, self.resolve_global_addr(export.index)))) } + ExternalKind::Tag => { + ExternItem::Tag(Tag(StoreItem::new(self.0.store_id, self.resolve_tag_addr(export.index)))) + } }; (export.name.as_ref(), item) @@ -309,6 +323,7 @@ impl ModuleInstance { ExternVal::Memory(addr) => Ok(ExternItem::Memory(Memory(StoreItem::new(self.0.store_id, addr)))), ExternVal::Table(addr) => Ok(ExternItem::Table(Table(StoreItem::new(self.0.store_id, addr)))), ExternVal::Global(addr) => Ok(ExternItem::Global(Global(StoreItem::new(self.0.store_id, addr)))), + ExternVal::Tag(addr) => Ok(ExternItem::Tag(Tag(StoreItem::new(self.0.store_id, addr)))), } } @@ -487,6 +502,21 @@ impl ModuleInstance { Ok(Table(StoreItem::new(self.0.store_id, Self::index_addr(&self.0.table_addrs, table_index, "table")?))) } + /// Get a tag export by name. + pub fn tag(&self, name: &str) -> Result { + match self.require_export(name)? { + ExternVal::Tag(tag_addr) => Ok(Tag(StoreItem::new(self.0.store_id, tag_addr))), + _ => Err(Error::Other(format!("Export is not a tag: {name}"))), + } + } + + /// Get a tag by its module-local index. + #[cfg_attr(docsrs, doc(cfg(feature = "guest-debug")))] + #[cfg(feature = "guest-debug")] + pub fn tag_by_index(&self, tag_index: TagAddr) -> Result { + Ok(Tag(StoreItem::new(self.0.store_id, Self::index_addr(&self.0.tag_addrs, tag_index, "tag")?))) + } + /// Get the value of a global export by name. pub fn global_get(&self, store: &Store, name: &str) -> Result { self.global(name)?.get(store) diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index f5c9351..22c8441 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -65,7 +65,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } #[inline(always)] - fn exec(&mut self) -> Result, Trap> { + fn exec(&mut self) -> Result> { macro_rules! stack_op { (unary $ty:ty, |$v:ident| $expr:expr) => { stack_op!(unary $ty => $ty, |$v| $expr) @@ -223,7 +223,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { use tinywasm_types::Instruction::*; #[rustfmt::skip] match &self.func.instructions[self.cf.instr_ptr] { - Unreachable => { cold_path(); return Err(Trap::Unreachable) }, + Unreachable => { cold_path(); return 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)}, @@ -239,6 +239,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ReturnCallSelf => { self.exec_return_call_self()?; return Ok(None); } ReturnCallIndirect(ty, table) => { if self.exec_call_indirect::(*ty, *table)? { return Ok(Some(())); } return Ok(None); } ReturnCallRef(ty) => { if self.exec_call_ref::(*ty)? { return Ok(Some(())); } return Ok(None); } + Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } + ThrowRef => { self.exec_throw_ref()?; return Ok(None); } Jump(ip) => { self.cf.instr_ptr = *ip as usize; return Ok(None); } JumpIfZero32(ip) => if self.exec_jump_zero_32(*ip) { return Ok(None) }, JumpIfNonZero32(ip) => if self.exec_jump_non_zero_32(*ip) { return Ok(None) }, @@ -472,7 +474,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { RefCast(ty) => { if !self.exec_ref_matches(*ty) { cold_path(); - return Err(Trap::CastFailure); + return Err(Trap::CastFailure.into()); } } // GC objects @@ -992,6 +994,135 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.value_stack.truncate_keep_counts(base, drop_keep.keep); } + fn create_exception(&mut self, tag_index: TagAddr) -> Result { + let tag_addr = self.module.resolve_tag_addr(tag_index); + let type_addr = self.store.state.get_tag(tag_addr).type_addr; + let addr = u32::try_from(self.store.state.exceptions.len()).map_err(|_| Trap::OutOfMemory)?; + self.store.state.exceptions.try_reserve(1).map_err(|_| Trap::OutOfMemory)?; + let params = self.store.state.get_canonical_func_type(type_addr).params(); + let mut payload = Vec::new(); + payload.try_reserve_exact(params.len()).map_err(|_| Trap::OutOfMemory)?; + for &ty in params.iter().rev() { + payload.push(match ty { + WasmType::I32 | WasmType::F32 => { + TinyWasmValue::Value32(Value32::stack_pop(&mut self.store.value_stack)) + } + WasmType::I64 | WasmType::F64 => { + TinyWasmValue::Value64(Value64::stack_pop(&mut self.store.value_stack)) + } + WasmType::V128 => TinyWasmValue::Value128(Value128::stack_pop(&mut self.store.value_stack)), + WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(&mut self.store.value_stack)), + }); + } + payload.reverse(); + self.store + .state + .exceptions + .push(crate::store::ExceptionInstance { tag_addr, payload: payload.into_boxed_slice() }); + Ok(addr) + } + + fn exec_throw(&mut self, tag_index: TagAddr) -> Result<()> { + let exception = self.create_exception(tag_index)?; + let outcome = match self.dispatch_exception(exception) { + Ok(outcome) => outcome, + Err(trap) => { + _ = self.store.state.exceptions.pop(); + return Err(trap.into()); + } + }; + match outcome { + Some(catch) if !catch.with_ref() => { + debug_assert_eq!(self.store.state.exceptions.len() - 1, exception as usize); + _ = self.store.state.exceptions.pop(); + Ok(()) + } + Some(_) => Ok(()), + None => Err(Error::Exception(ExnRef::new(exception))), + } + } + + fn exec_throw_ref(&mut self) -> Result<()> { + let exception = ValueRef::stack_pop(&mut self.store.value_stack); + let exception = exception + .addr() + .filter(|addr| self.store.state.exceptions.get(*addr as usize).is_some()) + .ok_or(Trap::NullReference)?; + match self.dispatch_exception(exception)? { + Some(_) => Ok(()), + None => Err(Error::Exception(ExnRef::new(exception))), + } + } + + fn matching_catch(&self, protected_ip: usize, tag_addr: TagAddr) -> Option { + let handlers = &self.func.data.exception_handlers; + let end = handlers.partition_point(|handler| handler.start_ip as usize <= protected_ip); + handlers[..end] + .iter() + .rev() + .filter(|handler| protected_ip < handler.end_ip as usize) + .flat_map(|handler| handler.catches.iter().copied()) + .find(|catch| match catch { + ExceptionCatch::Tag { tag, .. } => self.module.resolve_tag_addr(*tag) == tag_addr, + ExceptionCatch::All { .. } => true, + }) + } + + 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.get_wasm_func(self.cf.func_addr); + self.func = wasm_func.func.clone(); + if wasm_func.owner != self.module.id() { + self.module = self + .store + .get_module_instance(wasm_func.owner) + .unwrap_or_else(|| unreachable!("invalid module instance")) + .clone(); + } + } + + fn dispatch_exception(&mut self, exception_addr: ExnAddr) -> Result, Trap> { + let tag_addr = self.store.state.exceptions[exception_addr as usize].tag_addr; + let mut protected_ip = self.cf.instr_ptr; + 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; + for value in state.exceptions[exception_addr as usize].payload.iter().copied() { + value_stack.push_dyn(value)?; + } + } + if with_ref { + self.store.value_stack.push(ValueRef::from_category_addr(exception_addr))?; + } + self.cf.instr_ptr = landing_pad as usize; + return Ok(Some(catch)); + } + + 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).unwrap_or_else(|| unreachable!("invalid caller IP")); + } + } + fn exec_call(&mut self, wasm_func: WasmFunctionInstance, func_addr: FuncAddr) -> Result<(), Trap> { if !Arc::ptr_eq(&self.func, &wasm_func.func) { self.func = wasm_func.func.clone(); @@ -1207,20 +1338,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { return true; }; - if caller.func_addr == self.cf.func_addr { - self.cf = caller; - return false; - } - let wasm_func = self.store.state.get_wasm_func(caller.func_addr); - self.func = wasm_func.func.clone(); - if wasm_func.owner != self.module.id() { - self.module = self - .store - .get_module_instance(wasm_func.owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); - } - self.cf = caller; + self.switch_to_frame(caller); false } @@ -1922,7 +2040,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { impl<'store> Executor<'store, false> { #[inline(always)] - pub(crate) fn run_to_completion(&mut self) -> Result<(), Trap> { + pub(crate) fn run_to_completion(&mut self) -> Result<()> { // ideally we use `loop_match` / `become` once thats stabilized loop { if self.exec()?.is_some() { @@ -1933,7 +2051,7 @@ impl<'store> Executor<'store, false> { #[cfg(feature = "std")] #[inline(always)] - pub(crate) fn run_with_time_budget(&mut self, time_budget: core::time::Duration) -> Result { + pub(crate) fn run_with_time_budget(&mut self, time_budget: core::time::Duration) -> Result { use crate::std::time::Instant; let start = Instant::now(); if time_budget.is_zero() { @@ -1956,7 +2074,7 @@ impl<'store> Executor<'store, false> { impl<'store> Executor<'store, true> { #[inline(always)] - pub(crate) fn run_with_fuel(&mut self, fuel: u32) -> Result { + pub(crate) fn run_with_fuel(&mut self, fuel: u32) -> Result { self.store.execution_fuel = fuel; if self.store.execution_fuel == 0 { return Ok(ExecState::Suspended(self.cf)); diff --git a/crates/tinywasm/src/interpreter/mod.rs b/crates/tinywasm/src/interpreter/mod.rs index cece36a..6e6912c 100644 --- a/crates/tinywasm/src/interpreter/mod.rs +++ b/crates/tinywasm/src/interpreter/mod.rs @@ -7,7 +7,7 @@ pub(crate) mod values; #[cfg(not(feature = "std"))] mod no_std_floats; -use crate::{Result, Store, Trap, interpreter::stack::CallFrame}; +use crate::{Result, Store, interpreter::stack::CallFrame}; pub(crate) use simd::*; pub(crate) use values::*; @@ -26,11 +26,11 @@ pub(crate) enum ExecState { pub(crate) struct InterpreterRuntime; impl InterpreterRuntime { - pub(crate) fn exec(store: &mut Store, cf: CallFrame, call_stack_base: u32) -> Result<(), Trap> { + pub(crate) fn exec(store: &mut Store, cf: CallFrame, call_stack_base: u32) -> Result<()> { executor::Executor::::new(store, cf, call_stack_base).run_to_completion() } - pub(crate) fn exec_with_fuel(store: &mut Store, cf: CallFrame, fuel: u32) -> Result { + pub(crate) fn exec_with_fuel(store: &mut Store, cf: CallFrame, fuel: u32) -> Result { executor::Executor::::new(store, cf, 0).run_with_fuel(fuel) } @@ -39,7 +39,7 @@ impl InterpreterRuntime { store: &mut Store, cf: CallFrame, time_budget: core::time::Duration, - ) -> Result { + ) -> Result { executor::Executor::::new(store, cf, 0).run_with_time_budget(time_budget) } } diff --git a/crates/tinywasm/src/interpreter/num_helpers.rs b/crates/tinywasm/src/interpreter/num_helpers.rs index 7b3807e..783b10b 100644 --- a/crates/tinywasm/src/interpreter/num_helpers.rs +++ b/crates/tinywasm/src/interpreter/num_helpers.rs @@ -32,11 +32,11 @@ macro_rules! checked_conv_float { let (min, max) = float_min_max!($from, $intermediate); if v.is_nan() { core::hint::cold_path(); - return Err(crate::Trap::InvalidConversionToInt); + return Err(crate::Trap::InvalidConversionToInt.into()); } if v <= min || v >= max { core::hint::cold_path(); - return Err(crate::Trap::IntegerOverflow); + return Err(crate::Trap::IntegerOverflow.into()); } $self.store.value_stack.push::<$to>((v as $intermediate as $to).into())?; }}; diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index 6e904af..55f9e3b 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -8,7 +8,9 @@ use alloc::vec::Vec; use crate::interpreter::ValueRef; use crate::store::TableInstance; use crate::{Error, MemoryInstance, Result, Store, Trap}; -use tinywasm_types::{Addr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue}; +use tinywasm_types::{ + Addr, FuncType, GlobalType, MemAddr, MemoryType, TableAddr, TableType, TagAddr, WasmType, WasmValue, +}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "debug", derive(Debug))] @@ -66,6 +68,11 @@ pub struct Table(pub(crate) StoreItem); #[cfg_attr(feature = "debug", derive(Debug))] pub struct Global(pub(crate) StoreItem); +/// A tag instance in a store. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Tag(pub(crate) StoreItem); + /// A cursor over a [`Memory`] instance. /// /// Available with the `std` feature enabled. @@ -471,3 +478,22 @@ impl Global { store.state.set_global_wasmvalue(self.0.addr, value) } } + +impl Tag { + /// Create a new exception tag in the given store. + pub fn new(store: &mut Store, ty: FuncType) -> Result { + if !ty.results().is_empty() { + return Err(Error::other("tag types must not have results")); + } + let type_addr = store.register_host_type(&ty); + let addr = store.state.tags.len() as TagAddr; + store.state.tags.push(crate::store::TagInstance { type_addr }); + Ok(Self(StoreItem::new(store.id(), addr))) + } + + /// Get the payload type of the tag. + pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> { + self.0.validate_store(store)?; + Ok(store.state.get_canonical_func_type(store.state.get_tag(self.0.addr).type_addr)) + } +} diff --git a/crates/tinywasm/src/store/exception.rs b/crates/tinywasm/src/store/exception.rs new file mode 100644 index 0000000..0725cda --- /dev/null +++ b/crates/tinywasm/src/store/exception.rs @@ -0,0 +1,10 @@ +use alloc::boxed::Box; +use tinywasm_types::TagAddr; + +use crate::interpreter::TinyWasmValue; + +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) struct ExceptionInstance { + pub(crate) tag_addr: TagAddr, + pub(crate) payload: Box<[TinyWasmValue]>, +} diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 0cd5e5b..84a52b5 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -11,12 +11,14 @@ use crate::{Engine, Error, ModuleInstance, Result, Trap}; mod const_expr; mod data; mod element; +mod exception; mod function; mod gc; mod global; mod memory; mod state; mod table; +mod tag; mod types; use const_expr::eval_const; @@ -25,7 +27,7 @@ pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, Vec pub(crate) use memory::{MemValue, MemoryInstance}; pub(crate) use state::State; pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; -pub(crate) use {data::*, element::*, function::*, global::*, table::*}; +pub(crate) use {data::*, element::*, exception::*, function::*, global::*, table::*, tag::*}; // global store id counter static STORE_ID: AtomicU32 = AtomicU32::new(0); @@ -227,6 +229,18 @@ impl Store { start..start + funcs.len() as FuncAddr } + /// Add tags to the store, returning their addresses in the store. + pub(crate) fn init_tags( + &mut self, + tags: &[TagType], + type_addrs: &[TypeAddr], + ) -> impl ExactSizeIterator { + let start = self.state.tags.len() as TagAddr; + self.state.tags.reserve_exact(tags.len()); + self.state.tags.extend(tags.iter().map(|tag| TagInstance { type_addr: type_addrs[tag.type_idx as usize] })); + start..start + tags.len() as TagAddr + } + /// Add tables to the store, returning their addresses in the store pub(crate) fn init_tables( &mut self, diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 3371d4c..e6a213f 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -14,6 +14,8 @@ pub(crate) struct State { pub(crate) tables: Vec, pub(crate) memories: Vec, pub(crate) globals: Globals, + pub(crate) tags: Vec, + pub(crate) exceptions: Vec, pub(crate) elements: Vec, pub(crate) data: Vec, pub(crate) gc: Box, @@ -28,6 +30,8 @@ impl State { tables: Vec::new(), memories: Vec::new(), globals: Globals::default(), + tags: Vec::new(), + exceptions: Vec::new(), elements: Vec::new(), data: Vec::new(), gc: Box::new(gc::GcHeap::new(gc_collection_threshold)), @@ -104,6 +108,11 @@ impl State { .filter(|element| Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(element.ty))) .flat_map(|element| element.items.iter().flatten().copied()), ) + .chain( + self.exceptions + .iter() + .flat_map(|exception| exception.payload.iter().filter_map(|value| value.as_ref())), + ) .chain(values.iter().filter_map(|value| value.as_ref())); self.gc.collect(roots).map_err(|_| Trap::OutOfMemory)?; } @@ -261,6 +270,9 @@ impl State { let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); return self.ref_type_is_subtype(actual, expected); } + if expected.is_exn() { + return value.addr().is_some_and(|addr| self.exceptions.get(addr as usize).is_some()); + } if value.is_i31() { let actual = RefType::new_abstract(false, AbstractHeapType::I31); return self.ref_type_is_subtype(actual, expected); @@ -304,6 +316,9 @@ impl State { { false } + (WasmValue::Ref(RefValue::Exn(value)), WasmType::Ref(expected)) if expected.is_exn() => { + self.exceptions.get(value.addr() as usize).is_some() + } (WasmValue::Ref(RefValue::Any(value)), WasmType::Ref(expected)) => { self.value_ref_matches(ValueRef::from_raw(value.raw()), expected) } @@ -332,6 +347,10 @@ impl State { Self::get(&self.funcs, addr, "function") } + pub(crate) fn get_tag(&self, addr: TagAddr) -> &TagInstance { + Self::get(&self.tags, addr, "tag") + } + /// Get a wasm function at the actual index in the store, panicking if it's a host function (which should be guaranteed by the validator) pub(crate) fn get_wasm_func(&self, addr: FuncAddr) -> &WasmFunctionInstance { match self.funcs.get(addr as usize).map(|func| &func.kind) { diff --git a/crates/tinywasm/src/store/tag.rs b/crates/tinywasm/src/store/tag.rs new file mode 100644 index 0000000..49c16d8 --- /dev/null +++ b/crates/tinywasm/src/store/tag.rs @@ -0,0 +1,7 @@ +use tinywasm_types::TypeAddr; + +#[derive(Clone, Copy)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) struct TagInstance { + pub(crate) type_addr: TypeAddr, +} diff --git a/crates/tinywasm/tests/generated/wasm-3.csv b/crates/tinywasm/tests/generated/wasm-3.csv index 7d3961c..fdc0e86 100644 --- a/crates/tinywasm/tests/generated/wasm-3.csv +++ b/crates/tinywasm/tests/generated/wasm-3.csv @@ -1,3 +1,3 @@ 0.9.0,20776,452,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":89,"failed":1},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":37,"failed":9},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] 0.10.0,20778,450,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":38,"failed":8},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] -0.11.0-pre.0,21151,77,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] +0.11.0-pre.0,21228,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":218,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":23,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":34,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-latest.csv b/crates/tinywasm/tests/generated/wasm-latest.csv index 94a8b58..b25ec13 100644 --- a/crates/tinywasm/tests/generated/wasm-latest.csv +++ b/crates/tinywasm/tests/generated/wasm-latest.csv @@ -1,3 +1,3 @@ 0.9.0,20777,452,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":89,"failed":1},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":37,"failed":9},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] 0.10.0,20697,536,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":14,"failed":35},{"name":"return_call_indirect.wast","passed":30,"failed":51},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":38,"failed":8},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] -0.11.0-pre.0,21156,77,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":49,"failed":0},{"name":"return_call_indirect.wast","passed":81,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] +0.11.0-pre.0,21233,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":218,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":23,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":34,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":49,"failed":0},{"name":"return_call_indirect.wast","passed":81,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index b920ac7..aff9e24 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,4 +1,6 @@ -use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TypeAddr, ValueCounts}; +use alloc::boxed::Box; + +use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; use crate::{ConstIdx, DataAddr, ElemAddr, MemAddr, RefType, RefValue}; /// Represents a memory immediate in a WebAssembly memory instruction. @@ -20,6 +22,46 @@ pub struct DropKeep { pub keep: ValueCounts, } +/// A catch clause attached to a lowered `try_table` instruction. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub enum ExceptionCatch { + /// Catch exceptions carrying the specified module-local tag. + Tag { tag: TagAddr, landing_pad: u32, base: ValueCounts, with_ref: bool }, + /// Catch any exception. + All { landing_pad: u32, base: ValueCounts, with_ref: bool }, +} + +impl ExceptionCatch { + /// Returns the catch landing pad instruction pointer. + pub const fn landing_pad(self) -> u32 { + match self { + Self::Tag { landing_pad, .. } | Self::All { landing_pad, .. } => landing_pad, + } + } + + /// Returns whether this clause exposes the caught exception reference. + pub const fn with_ref(self) -> bool { + match self { + Self::Tag { with_ref, .. } | Self::All { with_ref, .. } => with_ref, + } + } +} + +/// A statically lowered exception handler range. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct ExceptionHandler { + /// First protected instruction, inclusive. + pub start_ip: u32, + /// End of the protected instruction range, exclusive. + pub end_ip: u32, + /// Catch clauses in source order. + pub catches: Box<[ExceptionCatch]>, +} + impl From<(ValueCounts, ValueCounts)> for DropKeep { fn from((base, keep): (ValueCounts, ValueCounts)) -> Self { Self { base, keep } @@ -229,6 +271,8 @@ pub enum Instruction { ReturnCallSelf, ReturnCallIndirect(TypeAddr, TableAddr), ReturnCallRef(TypeAddr), + Throw(TagAddr), + ThrowRef, // > Parametric Instructions // See diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 0fd4e81..78a8d0d 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -111,6 +111,11 @@ pub struct ModuleInner { /// Corresponds to the `memory` section of the original WebAssembly module. pub memory_types: Box<[MemoryType]>, + /// Tag components of the WebAssembly module. + /// + /// Corresponds to the `tag` section of the original WebAssembly module. + pub tags: Box<[TagType]>, + /// Imports of the WebAssembly module. /// /// Corresponds to the `import` section of the original WebAssembly module. @@ -141,6 +146,7 @@ impl Module { ImportKind::Table(table_ty) => Some(ImportType::Table(table_ty)), ImportKind::Memory(memory_ty) => Some(ImportType::Memory(memory_ty)), ImportKind::Global(global_ty) => Some(ImportType::Global(global_ty)), + ImportKind::Tag(tag_ty) => Some(ImportType::Tag(self.0.types.get(tag_ty.type_idx)?.as_func()?)), }?; Some(ModuleImport { module: import.module.as_ref(), name: import.name.as_ref(), ty }) @@ -162,6 +168,7 @@ impl Module { | (ExternalKind::Table, ImportKind::Table(_)) | (ExternalKind::Memory, ImportKind::Memory(_)) | (ExternalKind::Global, ImportKind::Global(_)) + | (ExternalKind::Tag, ImportKind::Tag(_)) ) }) .count() @@ -175,6 +182,7 @@ impl Module { | (ExternalKind::Table, ImportKind::Table(_)) | (ExternalKind::Memory, ImportKind::Memory(_)) | (ExternalKind::Global, ImportKind::Global(_)) + | (ExternalKind::Tag, ImportKind::Tag(_)) ) }); let import = imports.nth(index)?; @@ -184,6 +192,7 @@ impl Module { ImportKind::Table(table_ty) => Some(ExportType::Table(table_ty)), ImportKind::Memory(memory_ty) => Some(ExportType::Memory(memory_ty)), ImportKind::Global(global_ty) => Some(ExportType::Global(global_ty)), + ImportKind::Tag(tag_ty) => Some(ExportType::Tag(module.types.get(tag_ty.type_idx)?.as_func()?)), } } @@ -223,6 +232,15 @@ impl Module { ExportType::Global(&self.0.globals.get(idx - imported_globals)?.ty) } } + ExternalKind::Tag => { + let imported_tags = imported_count(&self.0, ExternalKind::Tag); + if idx < imported_tags { + imported_type(&self.0, ExternalKind::Tag, idx)? + } else { + let tag_ty = self.0.tags.get(idx - imported_tags)?; + ExportType::Tag(self.0.types.get(tag_ty.type_idx)?.as_func()?) + } + } }; Some(ModuleExport { name: export.name.as_ref(), ty }) @@ -258,6 +276,8 @@ pub enum ImportType<'a> { Memory(&'a MemoryType), /// Imported global type. Global(&'a GlobalType), + /// Imported tag type. + Tag(&'a FuncType), } /// Exported entity type. @@ -270,6 +290,8 @@ pub enum ExportType<'a> { Memory(&'a MemoryType), /// Exported global type. Global(&'a GlobalType), + /// Exported tag type. + Tag(&'a FuncType), } /// How instantiation should prepare local memories declared by the module. @@ -301,6 +323,8 @@ pub enum ExternalKind { Memory, /// A WebAssembly Global. Global, + /// A WebAssembly Tag. + Tag, } /// A WebAssembly Address. @@ -315,6 +339,8 @@ pub type FuncAddr = Addr; pub type TableAddr = Addr; pub type MemAddr = Addr; pub type GlobalAddr = Addr; +pub type TagAddr = Addr; +pub type ExnAddr = Addr; pub type ElemAddr = Addr; pub type DataAddr = Addr; pub type ExternAddr = Addr; @@ -338,6 +364,7 @@ pub enum ExternVal { Table(TableAddr), Memory(MemAddr), Global(GlobalAddr), + Tag(TagAddr), } impl ExternVal { @@ -348,6 +375,7 @@ impl ExternVal { Self::Table(_) => ExternalKind::Table, Self::Memory(_) => ExternalKind::Memory, Self::Global(_) => ExternalKind::Global, + Self::Tag(_) => ExternalKind::Tag, } } @@ -358,6 +386,7 @@ impl ExternVal { ExternalKind::Table => Self::Table(addr), ExternalKind::Memory => Self::Memory(addr), ExternalKind::Global => Self::Global(addr), + ExternalKind::Tag => Self::Tag(addr), } } } @@ -444,6 +473,7 @@ pub struct WasmFunction { pub struct WasmFunctionData { pub v128_constants: Box<[[u8; 16]]>, pub branch_table_targets: Box<[u32]>, + pub exception_handlers: Box<[ExceptionHandler]>, } impl WasmFunctionData { @@ -638,6 +668,22 @@ pub enum MemoryArch { I64, } +/// A WebAssembly tag type. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct TagType { + /// The module-local function type index used by this tag. + pub type_idx: TypeAddr, +} + +impl TagType { + /// Creates a tag type from a module-local function type index. + pub const fn new(type_idx: TypeAddr) -> Self { + Self { type_idx } + } +} + #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -655,6 +701,7 @@ pub enum ImportKind { Table(TableType), Memory(MemoryType), Global(GlobalType), + Tag(TagType), } impl From<&ImportKind> for ExternalKind { @@ -664,6 +711,7 @@ impl From<&ImportKind> for ExternalKind { ImportKind::Table(_) => Self::Table, ImportKind::Memory(_) => Self::Memory, ImportKind::Global(_) => Self::Global, + ImportKind::Tag(_) => Self::Tag, } } } -- cgit v1.3.1 From be3c350746e3dc6284b40349a8ac4a170d807c58 Mon Sep 17 00:00:00 2001 From: Henry Date: Tue, 11 Aug 2026 00:09:26 +0200 Subject: chore: improve interpreter loop performance, add more super instructions Signed-off-by: Henry --- crates/parser/src/optimize.rs | 62 ++++++++++++ crates/tinywasm/src/interpreter/executor.rs | 148 ++++++++++++++++++---------- crates/tinywasm/src/interpreter/values.rs | 10 +- crates/types/src/instructions.rs | 19 ++-- 4 files changed, 172 insertions(+), 67 deletions(-) (limited to 'crates/parser/src/optimize.rs') diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index be37e5e..2b5e331 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -131,6 +131,14 @@ fn rewrite( rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 32), Const64(32)] => [LocalGet64(local), I64Extend32S]); } } + instr @ (I32Eq | I32Ne | I32LtS | I32LtU | I32GtS | I32GtU | I32LeS | I32LeU | I32GeS | I32GeU) => { + let Some(op) = cmp_op(instr) else { unreachable!() }; + rewrite!(instrs, i, [LocalGet32(left), LocalGet32(right)] => CmpLocalLocal32(op, left, right)); + } + instr @ (I64Eq | I64Ne | I64LtS | I64LtU | I64GtS | I64GtU | I64LeS | I64LeU | I64GeS | I64GeU) => { + let Some(op) = cmp_op(instr) else { unreachable!() }; + rewrite!(instrs, i, [LocalGet64(left), LocalGet64(right)] => CmpLocalLocal64(op, left, right)); + } instr @ (F32Add | F32Mul | F32Min | F32Max) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); @@ -543,6 +551,31 @@ fn rewrite( replace!(instrs, i, 1 => JumpIfNonZero64(target)); continue; }); + rewrite!(instrs, i, + [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst)] if (local == dst) => + IncLocalJump32 { target_ip: target, local, delta, on_zero: true } + ); + rewrite!(instrs, i, + [CmpLocalLocal32(op, left, right)] => + JumpCmpLocalLocal32 { target_ip: target, left, right, op: inverse_cmp_op(op) } + ); + rewrite!(instrs, i, + [CmpLocalLocal64(op, left, right)] => + JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } + ); + rewrite!(instrs, i, + [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst), LocalGet32(right), cmp] if + (local == dst && let Some(op) = cmp_op(cmp)) => + IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(op) } + ); + rewrite!(instrs, i, + [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => + JumpCmpStackLocal32 { target_ip: target, local, op: inverse_cmp_op(op) } + ); + rewrite!(instrs, i, + [LocalGet64(local), cmp] if (let Some(op) = cmp_op(cmp)) => + JumpCmpStackLocal64 { target_ip: target, local, op: inverse_cmp_op(op) } + ); rewrite!(instrs, i, [LocalGet32(local), Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, inverse_cmp_op(op)) { @@ -599,6 +632,31 @@ fn rewrite( replace!(instrs, i, 1 => JumpIfZero64(target)); continue; }); + rewrite!(instrs, i, + [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst)] if (local == dst) => + IncLocalJump32 { target_ip: target, local, delta, on_zero: false } + ); + rewrite!(instrs, i, + [CmpLocalLocal32(op, left, right)] => + JumpCmpLocalLocal32 { target_ip: target, left, right, op } + ); + rewrite!(instrs, i, + [CmpLocalLocal64(op, left, right)] => + JumpCmpLocalLocal64 { target_ip: target, left, right, op } + ); + rewrite!(instrs, i, + [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst), LocalGet32(right), cmp] if + (local == dst && let Some(op) = cmp_op(cmp)) => + IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op } + ); + rewrite!(instrs, i, + [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => + JumpCmpStackLocal32 { target_ip: target, local, op } + ); + rewrite!(instrs, i, + [LocalGet64(local), cmp] if (let Some(op) = cmp_op(cmp)) => + JumpCmpStackLocal64 { target_ip: target, local, op } + ); rewrite!(instrs, i, [LocalGet32(local), Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, op) { @@ -861,6 +919,10 @@ fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> { | Instruction::BrOnCast(ip, _, _) | Instruction::JumpCmpStackConst32 { target_ip: ip, .. } | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } + | Instruction::JumpCmpStackLocal32 { target_ip: ip, .. } + | Instruction::JumpCmpStackLocal64 { target_ip: ip, .. } + | Instruction::IncLocalJump32 { target_ip: ip, .. } + | Instruction::IncLocalJumpCmpLocal32 { target_ip: ip, .. } | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } | Instruction::JumpIfLocalNonZero32 { target_ip: ip, .. } | Instruction::JumpIfLocalZero64 { target_ip: ip, .. } diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index d9d00eb..2d2a745 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -65,7 +65,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } #[inline(always)] - fn exec(&mut self) -> Result> { + fn exec(&mut self, instr_ptr: usize) -> Result> { macro_rules! stack_op { (unary $ty:ty, |$v:ident| $expr:expr) => { stack_op!(unary $ty => $ty, |$v| $expr) @@ -197,6 +197,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); self.store.value_stack.push(value)?; }}; + (local_local_cmp $vt:ty, $cmp:ident, $op:ident, $a:ident, $b:ident) => {{ + let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); + let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); + self.store.value_stack.push(i32::from($cmp(lhs, rhs, *$op)))?; + }}; (local_const $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); self.store.value_stack.push(exec_binop!($width, *$op, lhs, $rhs))?; @@ -222,14 +227,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { use tinywasm_types::Instruction::*; #[rustfmt::skip] - match &self.func.instructions[self.cf.instr_ptr] { + match &self.func.instructions[instr_ptr] { Unreachable => { cold_path(); return 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)?, + 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), SelectMulti(counts) => self.store.value_stack.select_multi(*counts), Call(v) => { self.exec_call_direct(*v)?; return Ok(None); } CallSelf => { self.exec_call_self()?; return Ok(None); } @@ -255,6 +260,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { JumpIfLocalNonZero64 { target_ip, local } => if self.exec_jump_local_non_zero_64(*target_ip, *local) { return Ok(None) }, JumpCmpStackConst32 { target_ip, imm, op } => if self.exec_jump_cmp_stack_const_32(*target_ip, *imm, *op) { return Ok(None) }, JumpCmpStackConst64 { target_ip, imm, op } => if self.exec_jump_cmp_stack_const_64(*target_ip, *imm, *op) { return Ok(None) }, + JumpCmpStackLocal32 { target_ip, local, op } => if self.exec_jump_cmp_stack_local_32(*target_ip, *local, *op) { return Ok(None) }, + JumpCmpStackLocal64 { target_ip, local, op } => if self.exec_jump_cmp_stack_local_64(*target_ip, *local, *op) { return Ok(None) }, + IncLocalJump32 { target_ip, local, delta, on_zero } => if self.exec_inc_local_jump_32(*target_ip, *local, *delta, *on_zero) { return Ok(None) }, + IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => if self.exec_inc_local_jump_cmp_local_32(*target_ip, *local, *delta, *right, *op) { return Ok(None) }, JumpCmpLocalConst32 { target_ip, local, imm, op } => if self.exec_jump_cmp_local_const_32(*target_ip, *local, *imm, *op) { return Ok(None) }, JumpCmpLocalConst64 { target_ip, local, imm, op } => if self.exec_jump_cmp_local_const_64(*target_ip, *local, *imm, *op) { return Ok(None) }, JumpCmpLocalLocal32 { target_ip, left, right, op } => if self.exec_jump_cmp_local_local_32(*target_ip, *left, *right, *op) { return Ok(None) }, @@ -288,6 +297,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { BinOpLocalLocal32(op, a, b) => binop!(local_local Value32, 32, op, a, b), BinOpLocalLocal64(op, a, b) => binop!(local_local Value64, 64, op, a, b), BinOpLocalLocal128(op, a, b) => binop!(local_local Value128, 128, op, a, b), + CmpLocalLocal32(op, a, b) => binop!(local_local_cmp i32, cmp_i32, op, a, b), + CmpLocalLocal64(op, a, b) => binop!(local_local_cmp i64, cmp_i64, op, a, b), BinOpLocalLocalSet32(op, a, b, dst) => binop!(local_local_set Value32, 32, op, a, b, dst), BinOpLocalLocalSet64(op, a, b, dst) => binop!(local_local_set Value64, 64, op, a, b, dst), BinOpLocalLocalSet128(op, a, b, dst) => binop!(local_local_set Value128, 128, op, a, b, dst), @@ -313,24 +324,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { StoreLocalLocal32(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, StoreLocalLocal64(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, StoreLocalLocal128(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - LoadLocal32(m, addr_local) => self.store.value_stack.push(self.exec_load_local_value::(*m, *addr_local)?)?, - LoadLocal64(m, addr_local) => self.store.value_stack.push(self.exec_load_local_value::(*m, *addr_local)?)?, - LoadLocal8S32(m, addr_local) => { - let value = self.exec_load_local_value::(*m, *addr_local)?; - self.store.value_stack.push(i32::from(value))?; - } - LoadLocal8U32(m, addr_local) => { - let value = self.exec_load_local_value::(*m, *addr_local)?; - self.store.value_stack.push(i32::from(value))?; - } - LoadLocal16S32(m, addr_local) => { - let value = self.exec_load_local_value::(*m, *addr_local)?; - self.store.value_stack.push(i32::from(value))?; - } - LoadLocal16U32(m, addr_local) => { - let value = self.exec_load_local_value::(*m, *addr_local)?; - self.store.value_stack.push(i32::from(value))?; - } + LoadLocal32(m, addr_local) => self.exec_load_local::(*m, *addr_local, |v| v)?, + LoadLocal64(m, addr_local) => self.exec_load_local::(*m, *addr_local, |v| v)?, + LoadLocal8S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, + LoadLocal8U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, + LoadLocal16S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, + LoadLocal16U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, LoadLocalTee32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, |v| v)?, LoadLocalSet32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, |v| v)?, LoadLocalTee8S32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, i32::from)?, @@ -466,17 +465,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I31GetS => self.exec_i31_get(true)?, I31GetU => self.exec_i31_get(false)?, RefEq => stack_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), - RefTest(ty) => { - let value = ValueRef::stack_pop(&mut self.store.value_stack); - let ty = self.canonical_ref_type(*ty); - self.store.value_stack.push(i32::from(self.store.state.value_ref_matches(value, ty)))?; - } - RefCast(ty) => { - if !self.exec_ref_matches(*ty) { - cold_path(); - return Err(Trap::CastFailure.into()); - } - } + 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)?, @@ -864,7 +854,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I32x4RelaxedTruncF64x2UZero => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()), }; - self.cf.instr_ptr += 1; + self.cf.instr_ptr = instr_ptr + 1; Ok(None) } @@ -951,6 +941,42 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.jump_if(condition, target_ip) } + #[inline(always)] + fn exec_jump_cmp_stack_local_32(&mut self, target_ip: u32, local: LocalAddr, op: CmpOp) -> bool { + let lhs = ::stack_pop(&mut self.store.value_stack); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, local); + self.jump_if(cmp_i32(lhs, rhs, op), target_ip) + } + + #[inline(always)] + fn exec_jump_cmp_stack_local_64(&mut self, target_ip: u32, local: LocalAddr, op: CmpOp) -> bool { + let lhs = ::stack_pop(&mut self.store.value_stack); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, local); + self.jump_if(cmp_i64(lhs, rhs, op), target_ip) + } + + #[inline(always)] + fn exec_inc_local_jump_32(&mut self, target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool) -> bool { + let value = i32::local_get(&self.store.value_stack, &self.cf, local).wrapping_add(delta); + i32::local_set(&mut self.store.value_stack, &self.cf, local, value); + self.jump_if((value == 0) == on_zero, target_ip) + } + + #[inline(always)] + fn exec_inc_local_jump_cmp_local_32( + &mut self, + target_ip: u32, + local: LocalAddr, + delta: i32, + right: LocalAddr, + op: CmpOp, + ) -> bool { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, local).wrapping_add(delta); + i32::local_set(&mut self.store.value_stack, &self.cf, local, lhs); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, right); + self.jump_if(cmp_i32(lhs, rhs, op), target_ip) + } + #[inline(always)] fn exec_jump_cmp_local_const_32(&mut self, target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp) -> bool { self.jump_if(cmp_i32(i32::local_get(&self.store.value_stack, &self.cf, local), imm, op), target_ip) @@ -1372,6 +1398,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.finish_return() } + #[inline(always)] fn exec_store_local_local, const N: usize>( &mut self, memarg: MemoryArg, @@ -1382,8 +1409,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local)); let mem = self.store.state.get_mem_mut(self.module.resolve_mem_addr(memarg.mem_addr())); let addr = mem.effective_addr_32::(base, memarg.offset())?; - value.store_at(&mut *mem.inner, addr)?; - Ok(()) + value.store_at(&mut *mem.inner, addr) } #[inline(always)] @@ -1439,6 +1465,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { T::local_update(&mut self.store.value_stack, &self.cf, acc, |v| add(mul(lhs, rhs), v)); } + #[inline(always)] fn exec_load_local_value, const N: usize>( &self, memarg: MemoryArg, @@ -1452,15 +1479,21 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); mem.effective_addr_32::(base, memarg.offset())? }; - match T::load_at(&*mem.inner, addr) { - Ok(res) => Ok(res), - Err(err) => { - cold_path(); - Err(err) - } - } + T::load_at(&*mem.inner, addr) + } + + #[inline(always)] + fn exec_load_local, const N: usize, TARGET: InternalValue>( + &mut self, + memarg: MemoryArg, + addr_local: u8, + cast: impl Fn(LOAD) -> TARGET, + ) -> Result<(), Trap> { + let value = cast(self.exec_load_local_value::(memarg, addr_local)?); + TARGET::stack_push(&mut self.store.value_stack, value) } + #[inline(always)] fn exec_load_local_tee, const N: usize, TARGET: InternalValue>( &mut self, memarg: MemoryArg, @@ -1474,6 +1507,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } + #[inline(always)] fn exec_load_local_set, const N: usize, TARGET: InternalValue>( &mut self, memarg: MemoryArg, @@ -1514,6 +1548,20 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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)); + self.store.value_stack.push(i32::from(matches)) + } + + fn exec_ref_cast(&self, ty: RefType) -> Result<(), Trap> { + if !self.exec_ref_matches(ty) { + cold_path(); + return 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() { @@ -2037,10 +2085,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { impl<'store> Executor<'store, false> { #[inline(always)] - pub(crate) fn run_to_completion(&mut self) -> Result<()> { + pub(crate) fn run_to_completion(mut self) -> Result<()> { // ideally we use `loop_match` / `become` once thats stabilized loop { - if self.exec()?.is_some() { + if self.exec(self.cf.instr_ptr)?.is_some() { return Ok(()); } } @@ -2048,7 +2096,7 @@ impl<'store> Executor<'store, false> { #[cfg(feature = "std")] #[inline(always)] - pub(crate) fn run_with_time_budget(&mut self, time_budget: core::time::Duration) -> Result { + pub(crate) fn run_with_time_budget(mut self, time_budget: core::time::Duration) -> Result { use crate::std::time::Instant; let start = Instant::now(); if time_budget.is_zero() { @@ -2057,7 +2105,7 @@ impl<'store> Executor<'store, false> { loop { for _ in 0..128 { - if self.exec()?.is_some() { + if self.exec(self.cf.instr_ptr)?.is_some() { return Ok(ExecState::Completed); } } @@ -2071,7 +2119,7 @@ impl<'store> Executor<'store, false> { impl<'store> Executor<'store, true> { #[inline(always)] - pub(crate) fn run_with_fuel(&mut self, fuel: u32) -> Result { + pub(crate) fn run_with_fuel(mut self, fuel: u32) -> Result { self.store.execution_fuel = fuel; if self.store.execution_fuel == 0 { return Ok(ExecState::Suspended(self.cf)); @@ -2079,7 +2127,7 @@ impl<'store> Executor<'store, true> { loop { for _ in 0..128 { - if self.exec()?.is_some() { + if self.exec(self.cf.instr_ptr)?.is_some() { return Ok(ExecState::Completed); } } diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index b3382e8..cc91a55 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -135,7 +135,7 @@ pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap>; fn stack_pop(stack: &mut ValueStack) -> Self; fn stack_peek(stack: &ValueStack) -> Self; - fn stack_select(stack: &mut ValueStack) -> Result<(), crate::Trap>; + fn stack_select(stack: &mut ValueStack); fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self; fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self); fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self); @@ -227,16 +227,14 @@ macro_rules! impl_internalvalue { } #[inline(always)] - fn stack_select(stack: &mut ValueStack) -> Result<(), crate::Trap> { + fn stack_select(stack: &mut ValueStack) { let cond = stack.stack_32.pop() as i32; let val2 = stack.$stack.pop(); if cond == 0 { - Self::stack_pop(stack); - stack.$stack.push(val2)?; + let val1 = stack.$stack.len() - 1; + stack.$stack.set(val1, val2); } - - Ok(()) } } )* diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 5eb5491..4e14d75 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -186,6 +186,7 @@ pub enum Instruction { // The 32/64 suffix describes the operand width. Future compare-style ops may still yield i32 results. BinOpLocalLocal32(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal64(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal128(BinOp128, LocalAddr, LocalAddr), + CmpLocalLocal32(CmpOp, LocalAddr, LocalAddr), CmpLocalLocal64(CmpOp, LocalAddr, LocalAddr), BinOpLocalLocalSet32(BinOp, LocalAddr, LocalAddr, LocalAddr), BinOpLocalLocalSet64(BinOp, LocalAddr, LocalAddr, LocalAddr), BinOpLocalLocalSet128(BinOp128, LocalAddr, LocalAddr, LocalAddr), @@ -255,6 +256,10 @@ pub enum Instruction { JumpIfLocalNonZero64 { target_ip: u32, local: LocalAddr }, JumpCmpStackConst32 { target_ip: u32, imm: i32, op: CmpOp }, JumpCmpStackConst64 { target_ip: u32, imm: i64, op: CmpOp }, + JumpCmpStackLocal32 { target_ip: u32, local: LocalAddr, op: CmpOp }, + JumpCmpStackLocal64 { target_ip: u32, local: LocalAddr, op: CmpOp }, + IncLocalJump32 { target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool }, + IncLocalJumpCmpLocal32 { target_ip: u32, local: LocalAddr, delta: i32, right: LocalAddr, op: CmpOp }, JumpCmpLocalConst32 { target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp }, JumpCmpLocalConst64 { target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp }, JumpCmpLocalLocal32 { target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp }, @@ -477,9 +482,11 @@ pub enum Instruction { F64x2RelaxedMin, F64x2RelaxedMax, I16x8RelaxedQ15mulrS, I16x8RelaxedDotI8x16I7x16S, - I32x4RelaxedDotI8x16I7x16AddS + I32x4RelaxedDotI8x16I7x16AddS, } +const _: () = assert!(core::mem::size_of::() <= 16); + impl Instruction { #[inline] pub const fn memory_addr(&self) -> Option { @@ -564,13 +571,3 @@ impl Instruction { } } } - -#[cfg(test)] -mod tests { - use super::Instruction; - - #[test] - fn instruction_layout_size_is_stable() { - assert_eq!(core::mem::size_of::(), 16); - } -} -- cgit v1.3.1 From 64cf33ced2db2135dd355a1c6e049bf51c93d956 Mon Sep 17 00:00:00 2001 From: Henry Date: Tue, 11 Aug 2026 17:25:32 +0200 Subject: chore: more superinstructions, cleanup Signed-off-by: Henry --- crates/parser/src/conversion.rs | 3 +- crates/parser/src/optimize.rs | 108 +- crates/tinywasm/src/func/host.rs | 5 +- crates/tinywasm/src/interpreter/executor.rs | 1304 ++++++++++---------- crates/tinywasm/src/store/state.rs | 21 +- crates/tinywasm/src/store/types.rs | 12 +- crates/tinywasm/tests/host_func_signature_check.rs | 2 +- crates/types/src/instructions.rs | 14 +- crates/types/src/reference.rs | 13 +- crates/types/src/value.rs | 2 +- examples/rust/Cargo.toml | 7 +- examples/rust/build.sh | 7 +- examples/rust/src/print.twasm | Bin 0 -> 154 bytes examples/rust/src/tinywasm_no_std.rs | 6 +- examples/rust/src/tinywasm_precompiled.rs | 30 + examples/wasm-rust.rs | 25 + 16 files changed, 827 insertions(+), 732 deletions(-) create mode 100644 examples/rust/src/print.twasm create mode 100644 examples/rust/src/tinywasm_precompiled.rs (limited to 'crates/parser/src/optimize.rs') diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 694c639..480a8d0 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -440,8 +440,7 @@ fn convert_heap_type_with_group( ))); } }; - RefType::new_concrete(nullable, index) - .ok_or_else(|| crate::ParseError::Other(format!("heap type index is too large: {index}"))) + Ok(RefType::new_concrete(nullable, index)) } wasmparser::HeapType::Abstract { shared: true, .. } | wasmparser::HeapType::Exact(_) => { Err(crate::ParseError::UnsupportedOperator(format!("Unsupported heap type: {heap:?}"))) diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 2b5e331..7081187 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -92,7 +92,9 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); @@ -103,6 +105,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]); @@ -113,7 +116,9 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const64(c)] => AddConst64(c)); @@ -124,6 +129,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 8), Const64(8)] => [LocalGet64(local), I64Extend8S]); @@ -143,33 +149,42 @@ fn rewrite( let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); } instr @ (F32Sub | F32Div | F32Copysign) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); } instr @ (F64Add | F64Mul | F64Min | F64Max) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); } instr @ (F64Sub | F64Div | F64Copysign) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); } instr @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul) => { let Some(op) = bin_op_128(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(op, a, b)); rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(op, local, c)); + rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(op, global, c)); rewrite!(instrs, i, [Const128(c), LocalGet128(local)] => BinOpLocalConst128(op, local, c)); + rewrite!(instrs, i, [Const128(c), GlobalGet128(global)] => BinOpGlobalConst128(op, global, c)); } V128AndNot => { rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(BinOp128::AndNot, a, b)); rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(BinOp128::AndNot, local, c)); + rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(BinOp128::AndNot, global, c)); } I32Store(memarg) | F32Store(memarg) => { rewrite!(instrs, i, @@ -277,6 +292,9 @@ fn rewrite( MemoryFill(mem) => { rewrite!(instrs, i, [Const32(val), Const32(size)] => MemoryFillImm(mem, val as u8, size)) } + GlobalGet32(dst) => rewrite!(instrs, i, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), + GlobalGet64(dst) => rewrite!(instrs, i, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), + GlobalGet128(dst) => rewrite!(instrs, i, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), LocalGet32(dst) => rewrite!(instrs, i, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), LocalGet64(dst) => rewrite!(instrs, i, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), LocalGet128(dst) => rewrite!(instrs, i, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), @@ -542,7 +560,6 @@ fn rewrite( replace!(instrs, i, 1 => JumpIfNonZero32(target)); continue; }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local }); rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { replace!(instrs, i, 2 => JumpIfLocalNonZero64 { target_ip: target, local }); continue; @@ -552,8 +569,30 @@ fn rewrite( continue; }); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst)] if (local == dst) => - IncLocalJump32 { target_ip: target, local, delta, on_zero: true } + [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => + match inc_delta(op, imm) { + Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: true }, + None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: true }, + } + ); + rewrite!(instrs, i, + [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: true } + ); + rewrite!(instrs, i, + [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: true } + ); + rewrite!(instrs, i, + [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: true } + ); + rewrite!(instrs, i, + [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => + match inc_delta(op, imm) { + Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: true }, + None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: true }, + } ); rewrite!(instrs, i, [CmpLocalLocal32(op, left, right)] => @@ -564,9 +603,12 @@ fn rewrite( JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } ); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst), LocalGet32(right), cmp] if - (local == dst && let Some(op) = cmp_op(cmp)) => - IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(op) } + [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if + (local == dst && let Some(cmp) = cmp_op(cmp)) => + match inc_delta(binop, imm) { + Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(cmp) }, + None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp: inverse_cmp_op(cmp) }, + } ); rewrite!(instrs, i, [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => @@ -611,6 +653,8 @@ fn rewrite( (0, CmpOp::Ne) => JumpIfNonZero64(target), (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, }); + rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local }); + rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local }); canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); } JumpIfNonZero32(ip) => { @@ -623,7 +667,6 @@ fn rewrite( replace!(instrs, i, 1 => JumpIfZero32(target)); continue; }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local }); rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { replace!(instrs, i, 2 => JumpIfLocalZero64 { target_ip: target, local }); continue; @@ -633,8 +676,30 @@ fn rewrite( continue; }); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst)] if (local == dst) => - IncLocalJump32 { target_ip: target, local, delta, on_zero: false } + [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => + match inc_delta(op, imm) { + Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: false }, + None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: false }, + } + ); + rewrite!(instrs, i, + [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: false } + ); + rewrite!(instrs, i, + [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: false } + ); + rewrite!(instrs, i, + [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: false } + ); + rewrite!(instrs, i, + [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => + match inc_delta(op, imm) { + Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: false }, + None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: false }, + } ); rewrite!(instrs, i, [CmpLocalLocal32(op, left, right)] => @@ -645,9 +710,12 @@ fn rewrite( JumpCmpLocalLocal64 { target_ip: target, left, right, op } ); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst), LocalGet32(right), cmp] if - (local == dst && let Some(op) = cmp_op(cmp)) => - IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op } + [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if + (local == dst && let Some(cmp) = cmp_op(cmp)) => + match inc_delta(binop, imm) { + Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: cmp }, + None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp }, + } ); rewrite!(instrs, i, [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => @@ -692,6 +760,8 @@ fn rewrite( (0, CmpOp::Ne) => JumpIfNonZero64(target), (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, }); + rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local }); + rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local }); canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); } JumpIfZero64(ip) => { @@ -774,6 +844,14 @@ fn cmp_op(instr: Instruction) -> Option { }) } +fn inc_delta(op: BinOp, imm: i32) -> Option { + match op { + BinOp::IAdd => Some(imm), + BinOp::ISub => Some(imm.wrapping_neg()), + _ => None, + } +} + fn int_bin_op(instr: Instruction) -> Option { Some(match instr { Instruction::I32Add | Instruction::I64Add => BinOp::IAdd, @@ -921,7 +999,13 @@ fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> { | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } | Instruction::JumpCmpStackLocal32 { target_ip: ip, .. } | Instruction::JumpCmpStackLocal64 { target_ip: ip, .. } + | Instruction::BinOpLocalConstJump32 { target_ip: ip, .. } + | Instruction::BinOpLocalConstJumpCmpLocal32 { target_ip: ip, .. } + | Instruction::BinOpStackConstTeeLocalJump32 { target_ip: ip, .. } + | Instruction::BinOpGlobalConstJump32 { target_ip: ip, .. } | Instruction::IncLocalJump32 { target_ip: ip, .. } + | Instruction::IncStackTeeLocalJump32 { target_ip: ip, .. } + | Instruction::IncGlobalJump32 { target_ip: ip, .. } | Instruction::IncLocalJumpCmpLocal32 { target_ip: ip, .. } | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } | Instruction::JumpIfLocalNonZero32 { target_ip: ip, .. } diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 5335444..27c5573 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -31,10 +31,7 @@ impl HostFunction { let canonical = *type_addrs .get(module_addr as usize) .ok_or_else(|| crate::Error::other("host function signature contains an invalid concrete type"))?; - Ok(WasmType::Ref( - tinywasm_types::RefType::new_concrete(ref_ty.is_nullable(), canonical) - .expect("canonical type addresses fit in references"), - )) + Ok(WasmType::Ref(tinywasm_types::RefType::new_concrete(ref_ty.is_nullable(), canonical))) }; let params = self.0.ty.params().iter().copied().map(resolve).collect::>>()?; let results = self.0.ty.results().iter().copied().map(resolve).collect::>>()?; diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 2d2a745..051b12f 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -66,14 +66,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec(&mut self, instr_ptr: usize) -> Result> { - macro_rules! stack_op { - (unary $ty:ty, |$v:ident| $expr:expr) => { - stack_op!(unary $ty => $ty, |$v| $expr) - }; - (binary $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => { - stack_op!(binary $ty => $ty, |$lhs, $rhs| $expr) - }; - (binary try $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + macro_rules! exec_op { + (branch $target:expr, $condition:expr) => {{ + if $condition { + self.cf.instr_ptr = *$target as usize; + return Ok(None); + } + }}; + (binary_fallible $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ let $rhs = <$ty>::stack_pop(&mut self.store.value_stack); let $lhs = <$ty>::stack_pop(&mut self.store.value_stack); <$ty>::stack_push(&mut self.store.value_stack, $expr?)?; @@ -87,28 +87,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let $lhs = <$from>::stack_pop(&mut self.store.value_stack); <$to>::stack_push(&mut self.store.value_stack, $expr)?; }}; - (binary_into2 $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + (binary_two_results $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ let $rhs = <$from>::stack_pop(&mut self.store.value_stack); let $lhs = <$from>::stack_pop(&mut self.store.value_stack); let out = $expr; <$to>::stack_push(&mut self.store.value_stack, out.0)?; <$to>::stack_push(&mut self.store.value_stack, out.1)?; }}; - (binary $lhs_ty:ty, $rhs_ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => { - stack_op!(binary $lhs_ty, $rhs_ty => $rhs_ty, |$lhs, $rhs| $expr) - }; - (binary $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + (binary_mixed $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ let $rhs = <$rhs_ty>::stack_pop(&mut self.store.value_stack); let $lhs = <$lhs_ty>::stack_pop(&mut self.store.value_stack); <$res>::stack_push(&mut self.store.value_stack, $expr)?; }}; - (ternary $ty:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{ - let $c = <$ty>::stack_pop(&mut self.store.value_stack); - let $b = <$ty>::stack_pop(&mut self.store.value_stack); - let $a = <$ty>::stack_pop(&mut self.store.value_stack); - <$ty>::stack_push(&mut self.store.value_stack, $expr)?; + (ternary $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{ + let $c = <$from>::stack_pop(&mut self.store.value_stack); + let $b = <$from>::stack_pop(&mut self.store.value_stack); + let $a = <$from>::stack_pop(&mut self.store.value_stack); + <$to>::stack_push(&mut self.store.value_stack, $expr)?; }}; - (quaternary_into2 $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident, $d:ident| $expr:expr) => {{ + (quaternary_two_results $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident, $d:ident| $expr:expr) => {{ let $d = <$from>::stack_pop(&mut self.store.value_stack); let $c = <$from>::stack_pop(&mut self.store.value_stack); let $b = <$from>::stack_pop(&mut self.store.value_stack); @@ -135,93 +132,64 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let value = <$ty>::stack_pop(&mut self.store.value_stack); <$ty>::global_set(&mut self.store.state.globals, addr, value); }}; - } - - macro_rules! exec_binop { - (32, $op:expr, $lhs:expr, $rhs:expr) => { - exec_binop!(@scalar i32, u32, f32, $op, $lhs, $rhs) - }; - (64, $op:expr, $lhs:expr, $rhs:expr) => { - exec_binop!(@scalar i64, u64, f64, $op, $lhs, $rhs) - }; - (@scalar $signed:ty, $unsigned:ty, $float:ty, $op:expr, $lhs:expr, $rhs:expr) => {{ - match $op { - BinOp::IAdd => $lhs.wrapping_add($rhs), - BinOp::ISub => $lhs.wrapping_sub($rhs), - BinOp::IMul => $lhs.wrapping_mul($rhs), - BinOp::IAnd => $lhs & $rhs, - BinOp::IOr => $lhs | $rhs, - BinOp::IXor => $lhs ^ $rhs, - BinOp::IShl => (($lhs as $signed).wrapping_shl($rhs as u32)) as $unsigned, - BinOp::IShrS => (($lhs as $signed).wrapping_shr($rhs as u32)) as $unsigned, - BinOp::IShrU => $lhs.wrapping_shr($rhs as u32), - BinOp::IRotl => (($lhs as $signed).rotate_left($rhs as u32)) as $unsigned, - BinOp::IRotr => (($lhs as $signed).rotate_right($rhs as u32)) as $unsigned, - BinOp::FAdd => (<$float>::from_bits($lhs) + <$float>::from_bits($rhs)).to_bits(), - BinOp::FSub => (<$float>::from_bits($lhs) - <$float>::from_bits($rhs)).to_bits(), - BinOp::FMul => (<$float>::from_bits($lhs) * <$float>::from_bits($rhs)).to_bits(), - BinOp::FDiv => (<$float>::from_bits($lhs) / <$float>::from_bits($rhs)).to_bits(), - BinOp::FMin => <$float>::from_bits($lhs).tw_minimum(<$float>::from_bits($rhs)).to_bits(), - BinOp::FMax => <$float>::from_bits($lhs).tw_maximum(<$float>::from_bits($rhs)).to_bits(), - BinOp::FCopysign => <$float>::from_bits($lhs).copysign(<$float>::from_bits($rhs)).to_bits(), - } - }}; - (128, $op:expr, $lhs:expr, $rhs:expr) => {{ - match $op { - BinOp128::And => $lhs.v128_and($rhs), - BinOp128::AndNot => $lhs.v128_andnot($rhs), - BinOp128::Or => $lhs.v128_or($rhs), - BinOp128::Xor => $lhs.v128_xor($rhs), - BinOp128::I64x2Add => $lhs.i64x2_add($rhs), - BinOp128::I64x2Mul => $lhs.i64x2_mul($rhs), - } + (global_tee $ty:ty, $global_index:expr) => {{ + let addr = self.module.resolve_global_addr(*$global_index); + let value = <$ty>::stack_peek(&self.store.value_stack); + <$ty>::global_set(&mut self.store.state.globals, addr, value); }}; - } - - macro_rules! binop { - (local_local $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident) => {{ + (binop_local_local $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - self.store.value_stack.push(exec_binop!($width, *$op, lhs, rhs))?; + <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?; }}; - (local_local_set $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ + (binop_local_local_set $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - let value = exec_binop!($width, *$op, lhs, rhs); + let value = $exec(*$op, lhs, rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); }}; - (local_local_tee $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ + (binop_local_local_tee $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - let value = exec_binop!($width, *$op, lhs, rhs); + let value = $exec(*$op, lhs, rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - self.store.value_stack.push(value)?; + <$vt>::stack_push(&mut self.store.value_stack, value)?; }}; - (local_local_cmp $vt:ty, $cmp:ident, $op:ident, $a:ident, $b:ident) => {{ + (cmp_local_local $vt:ty, $cmp:ident, $op:ident, $a:ident, $b:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); self.store.value_stack.push(i32::from($cmp(lhs, rhs, *$op)))?; }}; - (local_const $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr) => {{ + (binop_local_const $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - self.store.value_stack.push(exec_binop!($width, *$op, lhs, $rhs))?; + <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, $rhs))?; }}; - (local_const_set $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ + (binop_local_const_set $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let value = exec_binop!($width, *$op, lhs, $rhs); + let value = $exec(*$op, lhs, $rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); }}; - (local_const_tee $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ + (binop_local_const_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let value = exec_binop!($width, *$op, lhs, $rhs); + let value = $exec(*$op, lhs, $rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - self.store.value_stack.push(value)?; + <$vt>::stack_push(&mut self.store.value_stack, value)?; }}; - (stack_global $vt:ty, $width:tt, $op:ident, $global:ident) => {{ + (binop_global_const $vt:ty, $exec:ident, $op:ident, $global:ident, $rhs:expr) => {{ + let lhs = <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); + self.store.value_stack.push($exec(*$op, lhs, $rhs))?; + }}; + (binop_stack_global $vt:ty, $exec:ident, $op:ident, $global:ident) => {{ let global_val = <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); let stack_val = <$vt>::stack_pop(&mut self.store.value_stack); - self.store.value_stack.push(exec_binop!($width, *$op, stack_val, global_val))?; + self.store.value_stack.push($exec(*$op, stack_val, global_val))?; + }}; + (binop_acc_local $ty:ty, $acc:ident, $mul:expr, $add:expr) => {{ + let rhs = <$ty>::stack_pop(&mut self.store.value_stack); + let lhs = <$ty>::stack_pop(&mut self.store.value_stack); + let value = ($mul)(lhs, rhs); + <$ty>::local_update(&mut self.store.value_stack, &self.cf, *$acc, |acc| ($add)(value, acc)); }}; } @@ -247,27 +215,115 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } ThrowRef => { self.exec_throw_ref()?; return Ok(None); } Jump(ip) => { self.cf.instr_ptr = *ip as usize; return Ok(None); } - JumpIfZero32(ip) => if self.exec_jump_zero_32(*ip) { return Ok(None) }, - JumpIfNonZero32(ip) => if self.exec_jump_non_zero_32(*ip) { return Ok(None) }, - JumpIfZero64(ip) => if self.exec_jump_zero_64(*ip) { return Ok(None) }, - JumpIfNonZero64(ip) => if self.exec_jump_non_zero_64(*ip) { return Ok(None) }, - JumpIfRefNull(ip) => if self.exec_jump_ref_null(*ip) { return Ok(None) }, - JumpIfRefNonNull(ip) => if self.exec_jump_ref_non_null(*ip) { return Ok(None) }, + JumpIfZero32(ip) => exec_op!(branch ip, i32::stack_pop(&mut self.store.value_stack) == 0), + JumpIfNonZero32(ip) => exec_op!(branch ip, i32::stack_pop(&mut self.store.value_stack) != 0), + JumpIfZero64(ip) => exec_op!(branch ip, i64::stack_pop(&mut self.store.value_stack) == 0), + JumpIfNonZero64(ip) => exec_op!(branch ip, i64::stack_pop(&mut self.store.value_stack) != 0), + JumpIfRefNull(ip) => { + let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); + if is_null { + ValueRef::stack_pop(&mut self.store.value_stack); + } + exec_op!(branch ip, is_null); + }, + JumpIfRefNonNull(ip) => { + let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null(); + if !is_non_null { + ValueRef::stack_pop(&mut self.store.value_stack); + } + exec_op!(branch ip, is_non_null); + }, BrOnCast(ip, ty, on_fail) => if self.exec_ref_matches(*ty) == *on_fail { self.cf.instr_ptr = *ip as usize; return Ok(None); }, - JumpIfLocalZero32 { target_ip, local } => if self.exec_jump_local_zero_32(*target_ip, *local) { return Ok(None) }, - JumpIfLocalNonZero32 { target_ip, local } => if self.exec_jump_local_non_zero_32(*target_ip, *local) { return Ok(None) }, - JumpIfLocalZero64 { target_ip, local } => if self.exec_jump_local_zero_64(*target_ip, *local) { return Ok(None) }, - JumpIfLocalNonZero64 { target_ip, local } => if self.exec_jump_local_non_zero_64(*target_ip, *local) { return Ok(None) }, - JumpCmpStackConst32 { target_ip, imm, op } => if self.exec_jump_cmp_stack_const_32(*target_ip, *imm, *op) { return Ok(None) }, - JumpCmpStackConst64 { target_ip, imm, op } => if self.exec_jump_cmp_stack_const_64(*target_ip, *imm, *op) { return Ok(None) }, - JumpCmpStackLocal32 { target_ip, local, op } => if self.exec_jump_cmp_stack_local_32(*target_ip, *local, *op) { return Ok(None) }, - JumpCmpStackLocal64 { target_ip, local, op } => if self.exec_jump_cmp_stack_local_64(*target_ip, *local, *op) { return Ok(None) }, - IncLocalJump32 { target_ip, local, delta, on_zero } => if self.exec_inc_local_jump_32(*target_ip, *local, *delta, *on_zero) { return Ok(None) }, - IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => if self.exec_inc_local_jump_cmp_local_32(*target_ip, *local, *delta, *right, *op) { return Ok(None) }, - JumpCmpLocalConst32 { target_ip, local, imm, op } => if self.exec_jump_cmp_local_const_32(*target_ip, *local, *imm, *op) { return Ok(None) }, - JumpCmpLocalConst64 { target_ip, local, imm, op } => if self.exec_jump_cmp_local_const_64(*target_ip, *local, *imm, *op) { return Ok(None) }, - JumpCmpLocalLocal32 { target_ip, left, right, op } => if self.exec_jump_cmp_local_local_32(*target_ip, *left, *right, *op) { return Ok(None) }, - JumpCmpLocalLocal64 { target_ip, left, right, op } => if self.exec_jump_cmp_local_local_64(*target_ip, *left, *right, *op) { return Ok(None) }, + JumpIfLocalZero32 { target_ip, local } => exec_op!(branch target_ip, Value32::local_get(&self.store.value_stack, &self.cf, *local) == 0), + JumpIfLocalNonZero32 { target_ip, local } => exec_op!(branch target_ip, Value32::local_get(&self.store.value_stack, &self.cf, *local) != 0), + JumpIfLocalZero64 { target_ip, local } => exec_op!(branch target_ip, Value64::local_get(&self.store.value_stack, &self.cf, *local) == 0), + JumpIfLocalNonZero64 { target_ip, local } => exec_op!(branch target_ip, Value64::local_get(&self.store.value_stack, &self.cf, *local) != 0), + JumpCmpStackConst32 { target_ip, imm, op } => { + let lhs = i32::stack_pop(&mut self.store.value_stack); + exec_op!(branch target_ip, cmp_i32(lhs, *imm, *op)); + }, + JumpCmpStackConst64 { target_ip, imm, op } => { + let lhs = i64::stack_pop(&mut self.store.value_stack); + exec_op!(branch target_ip, cmp_i64(lhs, *imm, *op)); + }, + JumpCmpStackLocal32 { target_ip, local, op } => { + let lhs = i32::stack_pop(&mut self.store.value_stack); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); + }, + JumpCmpStackLocal64 { target_ip, local, op } => { + let lhs = i64::stack_pop(&mut self.store.value_stack); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i64(lhs, rhs, *op)); + }, + BinOpLocalConstJump32 { target_ip, local, imm, op, on_zero } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + BinOpLocalConstJumpCmpLocal32 { target_ip, local, imm, binop, right, cmp } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + let lhs = exec_binop_32(*binop, lhs as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, *local, lhs); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *cmp)); + }, + BinOpStackConstTeeLocalJump32 { target_ip, local, imm, op, on_zero } => { + let lhs = i32::stack_pop(&mut self.store.value_stack); + let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + i32::stack_push(&mut self.store.value_stack, value)?; + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + BinOpGlobalConstJump32 { target_ip, global, imm, op, on_zero } => { + let global = self.module.resolve_global_addr(*global); + let lhs = i32::global_get(&self.store.state.globals, global); + let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + i32::global_set(&mut self.store.state.globals, global, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncLocalJump32 { target_ip, local, delta, on_zero } => { + let value = i32::local_get(&self.store.value_stack, &self.cf, *local).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncStackTeeLocalJump32 { target_ip, local, delta, on_zero } => { + let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + i32::stack_push(&mut self.store.value_stack, value)?; + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncGlobalJump32 { target_ip, global, delta, on_zero } => { + let global = self.module.resolve_global_addr(*global); + let value = i32::global_get(&self.store.state.globals, global).wrapping_add(*delta); + i32::global_set(&mut self.store.state.globals, global, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, &self.cf, *local, lhs); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); + }, + JumpCmpLocalConst32 { target_ip, local, imm, op } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i32(lhs, *imm, *op)); + }, + JumpCmpLocalConst64 { target_ip, local, imm, op } => { + let lhs = i64::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i64(lhs, i64::from(*imm), *op)); + }, + JumpCmpLocalLocal32 { target_ip, left, right, op } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *left); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); + }, + JumpCmpLocalLocal64 { target_ip, left, right, op } => { + let lhs = i64::local_get(&self.store.value_stack, &self.cf, *left); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i64(lhs, rhs, *op)); + }, DropKeep(drop_keep) => self.exec_drop_keep(*drop_keep), BranchTable(default_ip, start, len) => { self.exec_branch_table(*default_ip, *start, *len); return Ok(None); } Return => { if self.exec_return() { return Ok(Some(())); } return Ok(None); } @@ -278,44 +334,47 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LocalGet32(local_index) => self.store.value_stack.push(Value32::local_get(&self.store.value_stack, &self.cf, *local_index))?, LocalGet64(local_index) => self.store.value_stack.push(Value64::local_get(&self.store.value_stack, &self.cf, *local_index))?, LocalGet128(local_index) => self.store.value_stack.push(Value128::local_get(&self.store.value_stack, &self.cf, *local_index))?, - LocalSet32(local_index) => stack_op!(local_set_pop Value32, local_index), - LocalSet64(local_index) => stack_op!(local_set_pop Value64, local_index), - LocalSet128(local_index) => stack_op!(local_set_pop Value128, local_index), + LocalSet32(local_index) => exec_op!(local_set_pop Value32, local_index), + LocalSet64(local_index) => exec_op!(local_set_pop Value64, local_index), + LocalSet128(local_index) => exec_op!(local_set_pop Value128, local_index), LocalCopy32(from, to) => Value32::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), - AddConst32(c) => stack_op!(unary i32, |v| v.wrapping_add(*c)), - AddConst64(c) => stack_op!(unary i64, |v| v.wrapping_add(*c)), + AddConst32(c) => exec_op!(unary i32 => i32, |v| v.wrapping_add(*c)), + AddConst64(c) => exec_op!(unary i64 => i64, |v| v.wrapping_add(*c)), IncLocal32(local_index, delta) => i32::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta)), IncLocal64(local_index, delta) => i64::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta )), - I32Add3 => stack_op!(ternary i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), - I64Add3 => stack_op!(ternary i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), - MulAccLocal32(acc) => self.exec_binop_acc_local::(*acc, |a, b| a.wrapping_mul(b), |a, b| a.wrapping_add(b)), - MulAccLocal64(acc) => self.exec_binop_acc_local::(*acc, |a, b| a.wrapping_mul(b), |a, b| a.wrapping_add(b)), - FMulAccLocal32(acc) => self.exec_binop_acc_local::(*acc, |a, b| a * b, |a, b| a + b), - FMulAccLocal64(acc) => self.exec_binop_acc_local::(*acc, |a, b| a * b, |a, b| a + b), - BinOpLocalLocal32(op, a, b) => binop!(local_local Value32, 32, op, a, b), - BinOpLocalLocal64(op, a, b) => binop!(local_local Value64, 64, op, a, b), - BinOpLocalLocal128(op, a, b) => binop!(local_local Value128, 128, op, a, b), - CmpLocalLocal32(op, a, b) => binop!(local_local_cmp i32, cmp_i32, op, a, b), - CmpLocalLocal64(op, a, b) => binop!(local_local_cmp i64, cmp_i64, op, a, b), - BinOpLocalLocalSet32(op, a, b, dst) => binop!(local_local_set Value32, 32, op, a, b, dst), - BinOpLocalLocalSet64(op, a, b, dst) => binop!(local_local_set Value64, 64, op, a, b, dst), - BinOpLocalLocalSet128(op, a, b, dst) => binop!(local_local_set Value128, 128, op, a, b, dst), - BinOpLocalLocalTee32(op, a, b, dst) => binop!(local_local_tee Value32, 32, op, a, b, dst), - BinOpLocalLocalTee64(op, a, b, dst) => binop!(local_local_tee Value64, 64, op, a, b, dst), - BinOpLocalLocalTee128(op, a, b, dst) => binop!(local_local_tee Value128, 128, op, a, b, dst), - BinOpLocalConst32(op, local_index, c) => binop!(local_const Value32, 32, op, local_index, *c as u32), - BinOpLocalConst64(op, local_index, c) => binop!(local_const Value64, 64, op, local_index, *c as u64), - BinOpLocalConst128(op, local_index, c) => binop!(local_const Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c))), - BinOpLocalConstSet32(op, local_index, c, dst) => binop!(local_const_set Value32, 32, op, local_index, *c as u32, dst), - BinOpLocalConstSet64(op, local_index, c, dst) => binop!(local_const_set Value64, 64, op, local_index, *c as u64, dst), - BinOpLocalConstSet128(op, local_index, c, dst) => binop!(local_const_set Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), - BinOpLocalConstTee32(op, local_index, c, dst) => binop!(local_const_tee Value32, 32, op, local_index, *c as u32, dst), - BinOpLocalConstTee64(op, local_index, c, dst) => binop!(local_const_tee Value64, 64, op, local_index, *c as u64, dst), - BinOpLocalConstTee128(op, local_index, c, dst) => binop!(local_const_tee Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), - BinOpStackGlobal32(op, global_index) => binop!(stack_global Value32, 32, op, global_index), - BinOpStackGlobal64(op, global_index) => binop!(stack_global Value64, 64, op, global_index), + I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), + I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), + MulAccLocal32(acc) => exec_op!(binop_acc_local i32, acc, |a: i32, b| a.wrapping_mul(b), |a: i32, b| a.wrapping_add(b)), + MulAccLocal64(acc) => exec_op!(binop_acc_local i64, acc, |a: i64, b| a.wrapping_mul(b), |a: i64, b| a.wrapping_add(b)), + FMulAccLocal32(acc) => exec_op!(binop_acc_local f32, acc, |a: f32, b| a * b, |a: f32, b| a + b), + FMulAccLocal64(acc) => exec_op!(binop_acc_local f64, acc, |a: f64, b| a * b, |a: f64, b| a + b), + BinOpLocalLocal32(op, a, b) => exec_op!(binop_local_local Value32, exec_binop_32, op, a, b), + BinOpLocalLocal64(op, a, b) => exec_op!(binop_local_local Value64, exec_binop_64, op, a, b), + BinOpLocalLocal128(op, a, b) => exec_op!(binop_local_local Value128, exec_binop_128, op, a, b), + CmpLocalLocal32(op, a, b) => exec_op!(cmp_local_local i32, cmp_i32, op, a, b), + CmpLocalLocal64(op, a, b) => exec_op!(cmp_local_local i64, cmp_i64, op, a, b), + BinOpLocalLocalSet32(op, a, b, dst) => exec_op!(binop_local_local_set Value32, exec_binop_32, op, a, b, dst), + BinOpLocalLocalSet64(op, a, b, dst) => exec_op!(binop_local_local_set Value64, exec_binop_64, op, a, b, dst), + BinOpLocalLocalSet128(op, a, b, dst) => exec_op!(binop_local_local_set Value128, exec_binop_128, op, a, b, dst), + BinOpLocalLocalTee32(op, a, b, dst) => exec_op!(binop_local_local_tee Value32, exec_binop_32, op, a, b, dst), + BinOpLocalLocalTee64(op, a, b, dst) => exec_op!(binop_local_local_tee Value64, exec_binop_64, op, a, b, dst), + BinOpLocalLocalTee128(op, a, b, dst) => exec_op!(binop_local_local_tee Value128, exec_binop_128, op, a, b, dst), + BinOpLocalConst32(op, local_index, c) => exec_op!(binop_local_const Value32, exec_binop_32, op, local_index, *c as u32), + BinOpLocalConst64(op, local_index, c) => exec_op!(binop_local_const Value64, exec_binop_64, op, local_index, *c as u64), + BinOpLocalConst128(op, local_index, c) => exec_op!(binop_local_const Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c))), + BinOpGlobalConst32(op, global_index, c) => exec_op!(binop_global_const Value32, exec_binop_32, op, global_index, *c as u32), + BinOpGlobalConst64(op, global_index, c) => exec_op!(binop_global_const Value64, exec_binop_64, op, global_index, *c as u64), + BinOpGlobalConst128(op, global_index, c) => exec_op!(binop_global_const Value128, exec_binop_128, op, global_index, Value128(self.func.data.v128_const(*c))), + BinOpLocalConstSet32(op, local_index, c, dst) => exec_op!(binop_local_const_set Value32, exec_binop_32, op, local_index, *c as u32, dst), + BinOpLocalConstSet64(op, local_index, c, dst) => exec_op!(binop_local_const_set Value64, exec_binop_64, op, local_index, *c as u64, dst), + BinOpLocalConstSet128(op, local_index, c, dst) => exec_op!(binop_local_const_set Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), + BinOpLocalConstTee32(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value32, exec_binop_32, op, local_index, *c as u32, dst), + BinOpLocalConstTee64(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value64, exec_binop_64, op, local_index, *c as u64, dst), + BinOpLocalConstTee128(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), + BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index), + BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index), SetLocalConst32(local_index, c) => i32::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), SetLocalConst64(local_index, c) => i64::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), SetLocalConst128(local_index, c) => Value128::local_set(&mut self.store.value_stack, &self.cf, *local_index, Value128(self.func.data.v128_const(*c))), @@ -342,129 +401,132 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, |v| v)?, LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, |v| v)?, - AndConstTee32(c, local_index) => { stack_op!(unary i32, |v| v & *c); stack_op!(local_tee i32, local_index); } - SubConstTee32(c, local_index) => { stack_op!(unary i32, |v| v.wrapping_sub(*c)); stack_op!(local_tee i32, local_index); } - AndConstTee64(c, local_index) => { stack_op!(unary i64, |v| v & *c); stack_op!(local_tee i64, local_index); } - SubConstTee64(c, local_index) => { stack_op!(unary i64, |v| v.wrapping_sub(*c)); stack_op!(local_tee i64, local_index); } - LocalTee32(local_index) => stack_op!(local_tee Value32, local_index), - LocalTee64(local_index) => stack_op!(local_tee Value64, local_index), - LocalTee128(local_index) => stack_op!(local_tee Value128, local_index), - GlobalGet32(global_index) => stack_op!(global_get Value32, global_index), - GlobalGet64(global_index) => stack_op!(global_get Value64, global_index), - GlobalGet128(global_index) => stack_op!(global_get Value128, global_index), - GlobalSet32(global_index) => stack_op!(global_set Value32, global_index), - GlobalSet64(global_index) => stack_op!(global_set Value64, global_index), - GlobalSet128(global_index) => stack_op!(global_set Value128, global_index), - Const32(val) => self.exec_const(*val)?, - Const64(val) => self.exec_const(*val)?, - I64Eqz => stack_op!(unary i64 => i32, |v| i32::from(v == 0)), - I32Eqz => stack_op!(unary i32, |v| i32::from(v == 0)), - I32Eq => stack_op!(binary i32, |a, b| i32::from(a == b)), - I64Eq => stack_op!(binary i64 => i32, |a, b| i32::from(a == b)), - F32Eq => stack_op!(binary f32 => i32, |a, b| i32::from(a == b)), - F64Eq => stack_op!(binary f64 => i32, |a, b| i32::from(a == b)), - I32Ne => stack_op!(binary i32, |a, b| i32::from(a != b)), - I64Ne => stack_op!(binary i64 => i32, |a, b| i32::from(a != b)), - F32Ne => stack_op!(binary f32 => i32, |a, b| i32::from(a != b)), - F64Ne => stack_op!(binary f64 => i32, |a, b| i32::from(a != b)), - I32LtS => stack_op!(binary i32, |a, b| i32::from(a < b)), - I64LtS => stack_op!(binary i64 => i32, |a, b| i32::from(a < b)), - I32LtU => stack_op!(binary u32 => i32, |a, b| i32::from(a < b)), - I64LtU => stack_op!(binary u64 => i32, |a, b| i32::from(a < b)), - F32Lt => stack_op!(binary f32 => i32, |a, b| i32::from(a < b)), - F64Lt => stack_op!(binary f64 => i32, |a, b| i32::from(a < b)), - I32LeS => stack_op!(binary i32, |a, b| i32::from(a <= b)), - I64LeS => stack_op!(binary i64 => i32, |a, b| i32::from(a <= b)), - I32LeU => stack_op!(binary u32 => i32, |a, b| i32::from(a <= b)), - I64LeU => stack_op!(binary u64 => i32, |a, b| i32::from(a <= b)), - F32Le => stack_op!(binary f32 => i32, |a, b| i32::from(a <= b)), - F64Le => stack_op!(binary f64 => i32, |a, b| i32::from(a <= b)), - I32GeS => stack_op!(binary i32, |a, b| i32::from(a >= b)), - I64GeS => stack_op!(binary i64 => i32, |a, b| i32::from(a >= b)), - I32GeU => stack_op!(binary u32 => i32, |a, b| i32::from(a >= b)), - I64GeU => stack_op!(binary u64 => i32, |a, b| i32::from(a >= b)), - F32Ge => stack_op!(binary f32 => i32, |a, b| i32::from(a >= b)), - F64Ge => stack_op!(binary f64 => i32, |a, b| i32::from(a >= b)), - I32GtS => stack_op!(binary i32, |a, b| i32::from(a > b)), - I64GtS => stack_op!(binary i64 => i32, |a, b| i32::from(a > b)), - I32GtU => stack_op!(binary u32 => i32, |a, b| i32::from(a > b)), - I64GtU => stack_op!(binary u64 => i32, |a, b| i32::from(a > b)), - F32Gt => stack_op!(binary f32 => i32, |a, b| i32::from(a > b)), - F64Gt => stack_op!(binary f64 => i32, |a, b| i32::from(a > b)), - I32Add => stack_op!(binary i32, |a, b| a.wrapping_add(b)), - I64Add => stack_op!(binary i64, |a, b| a.wrapping_add(b)), - F32Add => stack_op!(binary f32, |a, b| a + b), - F64Add => stack_op!(binary f64, |a, b| a + b), - I32Sub => stack_op!(binary i32, |a, b| a.wrapping_sub(b)), - I64Sub => stack_op!(binary i64, |a, b| a.wrapping_sub(b)), - F32Sub => stack_op!(binary f32, |a, b| a - b), - F64Sub => stack_op!(binary f64, |a, b| a - b), - F32Div => stack_op!(binary f32, |a, b| a / b), - F64Div => stack_op!(binary f64, |a, b| a / b), - I32Mul => stack_op!(binary i32, |a, b| a.wrapping_mul(b)), - I64Mul => stack_op!(binary i64, |a, b| a.wrapping_mul(b)), - F32Mul => stack_op!(binary f32, |a, b| a * b), - F64Mul => stack_op!(binary f64, |a, b| a * b), - I32DivS => stack_op!(binary try i32, |a, b| a.tw_checked_div(b)), - I64DivS => stack_op!(binary try i64, |a, b| a.tw_checked_div(b)), - I32DivU => stack_op!(binary try u32, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), - I64DivU => stack_op!(binary try u64, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), - I32RemS => stack_op!(binary try i32, |a, b| a.tw_checked_wrapping_rem(b)), - I64RemS => stack_op!(binary try i64, |a, b| a.tw_checked_wrapping_rem(b)), - I32RemU => stack_op!(binary try u32, |a, b| a.tw_checked_wrapping_rem(b)), - I64RemU => stack_op!(binary try u64, |a, b| a.tw_checked_wrapping_rem(b)), - I32And => stack_op!(binary i32, |a, b| a & b), - I64And => stack_op!(binary i64, |a, b| a & b), - I32Or => stack_op!(binary i32, |a, b| a | b), - I64Or => stack_op!(binary i64, |a, b| a | b), - I32Xor => stack_op!(binary i32, |a, b| a ^ b), - I64Xor => stack_op!(binary i64, |a, b| a ^ b), - I32Shl => stack_op!(binary i32, |a, b| a.wrapping_shl(b as u32)), - I64Shl => stack_op!(binary i64, |a, b| a.wrapping_shl(b as u32)), - I32ShrS => stack_op!(binary i32, |a, b| a.wrapping_shr(b as u32)), - I64ShrS => stack_op!(binary i64, |a, b| a.wrapping_shr(b as u32)), - I32ShrU => stack_op!(binary u32, |a, b| a.wrapping_shr(b)), - I64ShrU => stack_op!(binary u64, |a, b| a.wrapping_shr(b as u32)), - I32Rotl => stack_op!(binary i32, |a, b| a.rotate_left(b as u32)), - I64Rotl => stack_op!(binary i64, |a, b| a.rotate_left(b as u32)), - I32Rotr => stack_op!(binary i32, |a, b| a.rotate_right(b as u32)), - I64Rotr => stack_op!(binary i64, |a, b| a.rotate_right(b as u32)), - I64Add128 => stack_op!(quaternary_into2 i64 => i64, |a_lo, a_hi, b_lo, b_hi| { + AndConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v & *c); exec_op!(local_tee i32, local_index); } + SubConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(*c)); exec_op!(local_tee i32, local_index); } + AndConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v & *c); exec_op!(local_tee i64, local_index); } + SubConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v.wrapping_sub(*c)); exec_op!(local_tee i64, local_index); } + LocalTee32(local_index) => exec_op!(local_tee Value32, local_index), + LocalTee64(local_index) => exec_op!(local_tee Value64, local_index), + LocalTee128(local_index) => exec_op!(local_tee Value128, local_index), + GlobalGet32(global_index) => exec_op!(global_get Value32, global_index), + GlobalGet64(global_index) => exec_op!(global_get Value64, global_index), + GlobalGet128(global_index) => exec_op!(global_get Value128, global_index), + GlobalSet32(global_index) => exec_op!(global_set Value32, global_index), + GlobalSet64(global_index) => exec_op!(global_set Value64, global_index), + GlobalSet128(global_index) => exec_op!(global_set Value128, global_index), + GlobalTee32(global_index) => exec_op!(global_tee Value32, global_index), + GlobalTee64(global_index) => exec_op!(global_tee Value64, global_index), + GlobalTee128(global_index) => exec_op!(global_tee Value128, global_index), + Const32(val) => i32::stack_push(&mut self.store.value_stack, *val)?, + Const64(val) => i64::stack_push(&mut self.store.value_stack, *val)?, + I64Eqz => exec_op!(unary i64 => i32, |v| i32::from(v == 0)), + I32Eqz => exec_op!(unary i32 => i32, |v| i32::from(v == 0)), + I32Eq => exec_op!(binary i32 => i32, |a, b| i32::from(a == b)), + I64Eq => exec_op!(binary i64 => i32, |a, b| i32::from(a == b)), + F32Eq => exec_op!(binary f32 => i32, |a, b| i32::from(a == b)), + F64Eq => exec_op!(binary f64 => i32, |a, b| i32::from(a == b)), + I32Ne => exec_op!(binary i32 => i32, |a, b| i32::from(a != b)), + I64Ne => exec_op!(binary i64 => i32, |a, b| i32::from(a != b)), + F32Ne => exec_op!(binary f32 => i32, |a, b| i32::from(a != b)), + F64Ne => exec_op!(binary f64 => i32, |a, b| i32::from(a != b)), + I32LtS => exec_op!(binary i32 => i32, |a, b| i32::from(a < b)), + I64LtS => exec_op!(binary i64 => i32, |a, b| i32::from(a < b)), + I32LtU => exec_op!(binary u32 => i32, |a, b| i32::from(a < b)), + I64LtU => exec_op!(binary u64 => i32, |a, b| i32::from(a < b)), + F32Lt => exec_op!(binary f32 => i32, |a, b| i32::from(a < b)), + F64Lt => exec_op!(binary f64 => i32, |a, b| i32::from(a < b)), + I32LeS => exec_op!(binary i32 => i32, |a, b| i32::from(a <= b)), + I64LeS => exec_op!(binary i64 => i32, |a, b| i32::from(a <= b)), + I32LeU => exec_op!(binary u32 => i32, |a, b| i32::from(a <= b)), + I64LeU => exec_op!(binary u64 => i32, |a, b| i32::from(a <= b)), + F32Le => exec_op!(binary f32 => i32, |a, b| i32::from(a <= b)), + F64Le => exec_op!(binary f64 => i32, |a, b| i32::from(a <= b)), + I32GeS => exec_op!(binary i32 => i32, |a, b| i32::from(a >= b)), + I64GeS => exec_op!(binary i64 => i32, |a, b| i32::from(a >= b)), + I32GeU => exec_op!(binary u32 => i32, |a, b| i32::from(a >= b)), + I64GeU => exec_op!(binary u64 => i32, |a, b| i32::from(a >= b)), + F32Ge => exec_op!(binary f32 => i32, |a, b| i32::from(a >= b)), + F64Ge => exec_op!(binary f64 => i32, |a, b| i32::from(a >= b)), + I32GtS => exec_op!(binary i32 => i32, |a, b| i32::from(a > b)), + I64GtS => exec_op!(binary i64 => i32, |a, b| i32::from(a > b)), + I32GtU => exec_op!(binary u32 => i32, |a, b| i32::from(a > b)), + I64GtU => exec_op!(binary u64 => i32, |a, b| i32::from(a > b)), + F32Gt => exec_op!(binary f32 => i32, |a, b| i32::from(a > b)), + F64Gt => exec_op!(binary f64 => i32, |a, b| i32::from(a > b)), + I32Add => exec_op!(binary i32 => i32, |a, b| a.wrapping_add(b)), + I64Add => exec_op!(binary i64 => i64, |a, b| a.wrapping_add(b)), + F32Add => exec_op!(binary f32 => f32, |a, b| a + b), + F64Add => exec_op!(binary f64 => f64, |a, b| a + b), + I32Sub => exec_op!(binary i32 => i32, |a, b| a.wrapping_sub(b)), + I64Sub => exec_op!(binary i64 => i64, |a, b| a.wrapping_sub(b)), + F32Sub => exec_op!(binary f32 => f32, |a, b| a - b), + F64Sub => exec_op!(binary f64 => f64, |a, b| a - b), + F32Div => exec_op!(binary f32 => f32, |a, b| a / b), + F64Div => exec_op!(binary f64 => f64, |a, b| a / b), + I32Mul => exec_op!(binary i32 => i32, |a, b| a.wrapping_mul(b)), + I64Mul => exec_op!(binary i64 => i64, |a, b| a.wrapping_mul(b)), + F32Mul => exec_op!(binary f32 => f32, |a, b| a * b), + F64Mul => exec_op!(binary f64 => f64, |a, b| a * b), + I32DivS => exec_op!(binary_fallible i32, |a, b| a.tw_checked_div(b)), + I64DivS => exec_op!(binary_fallible i64, |a, b| a.tw_checked_div(b)), + I32DivU => exec_op!(binary_fallible u32, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), + I64DivU => exec_op!(binary_fallible u64, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), + I32RemS => exec_op!(binary_fallible i32, |a, b| a.tw_checked_wrapping_rem(b)), + I64RemS => exec_op!(binary_fallible i64, |a, b| a.tw_checked_wrapping_rem(b)), + I32RemU => exec_op!(binary_fallible u32, |a, b| a.tw_checked_wrapping_rem(b)), + I64RemU => exec_op!(binary_fallible u64, |a, b| a.tw_checked_wrapping_rem(b)), + I32And => exec_op!(binary i32 => i32, |a, b| a & b), + I64And => exec_op!(binary i64 => i64, |a, b| a & b), + I32Or => exec_op!(binary i32 => i32, |a, b| a | b), + I64Or => exec_op!(binary i64 => i64, |a, b| a | b), + I32Xor => exec_op!(binary i32 => i32, |a, b| a ^ b), + I64Xor => exec_op!(binary i64 => i64, |a, b| a ^ b), + I32Shl => exec_op!(binary i32 => i32, |a, b| a.wrapping_shl(b as u32)), + I64Shl => exec_op!(binary i64 => i64, |a, b| a.wrapping_shl(b as u32)), + I32ShrS => exec_op!(binary i32 => i32, |a, b| a.wrapping_shr(b as u32)), + I64ShrS => exec_op!(binary i64 => i64, |a, b| a.wrapping_shr(b as u32)), + I32ShrU => exec_op!(binary u32 => u32, |a, b| a.wrapping_shr(b)), + I64ShrU => exec_op!(binary u64 => u64, |a, b| a.wrapping_shr(b as u32)), + I32Rotl => exec_op!(binary i32 => i32, |a, b| a.rotate_left(b as u32)), + I64Rotl => exec_op!(binary i64 => i64, |a, b| a.rotate_left(b as u32)), + I32Rotr => exec_op!(binary i32 => i32, |a, b| a.rotate_right(b as u32)), + I64Rotr => exec_op!(binary i64 => i64, |a, b| a.rotate_right(b as u32)), + I64Add128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| { let lo = a_lo.wrapping_add(b_lo); let carry = u64::from((lo as u64) < (a_lo as u64)); let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64); (lo, hi) }), - I64Sub128 => stack_op!(quaternary_into2 i64 => i64, |a_lo, a_hi, b_lo, b_hi| { + I64Sub128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| { let lo = a_lo.wrapping_sub(b_lo); let borrow = u64::from((a_lo as u64) < (b_lo as u64)); let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64); (lo, hi) }), - I64MulWideS => stack_op!(binary_into2 i64 => i64, |a, b| { + I64MulWideS => exec_op!(binary_two_results i64 => i64, |a, b| { let product = (a as i128).wrapping_mul(b as i128); (product as i64, (product >> 64) as i64) }), - I64MulWideU => stack_op!(binary_into2 i64 => i64, |a, b| { + I64MulWideU => exec_op!(binary_two_results i64 => i64, |a, b| { let product = (a as u64 as u128).wrapping_mul(b as u64 as u128); (product as u64 as i64, (product >> 64) as u64 as i64) }), - I32Clz => stack_op!(unary i32, |v| v.leading_zeros() as i32), - I64Clz => stack_op!(unary i64, |v| i64::from(v.leading_zeros())), - I32Ctz => stack_op!(unary i32, |v| v.trailing_zeros() as i32), - I64Ctz => stack_op!(unary i64, |v| i64::from(v.trailing_zeros())), - I32Popcnt => stack_op!(unary i32, |v| v.count_ones() as i32), - I64Popcnt => stack_op!(unary i64, |v| i64::from(v.count_ones())), + I32Clz => exec_op!(unary i32 => i32, |v| v.leading_zeros() as i32), + I64Clz => exec_op!(unary i64 => i64, |v| i64::from(v.leading_zeros())), + I32Ctz => exec_op!(unary i32 => i32, |v| v.trailing_zeros() as i32), + I64Ctz => exec_op!(unary i64 => i64, |v| i64::from(v.trailing_zeros())), + I32Popcnt => exec_op!(unary i32 => i32, |v| v.count_ones() as i32), + I64Popcnt => exec_op!(unary i64 => i64, |v| i64::from(v.count_ones())), // Reference types - RefFunc(func_idx) => self.exec_const(ValueRef::from_category_addr(self.module.resolve_func_addr(*func_idx)))?, - RefNull(_) => self.exec_const(ValueRef::NULL)?, + RefFunc(func_idx) => ValueRef::stack_push(&mut self.store.value_stack, ValueRef::from_category_addr(self.module.resolve_func_addr(*func_idx)))?, + RefNull(_) => ValueRef::stack_push(&mut self.store.value_stack, ValueRef::NULL)?, RefIsNull => self.exec_ref_is_null()?, RefAsNonNull => self.exec_ref_as_non_null()?, - RefI31 => stack_op!(unary i32 => ValueRef, |v| ValueRef::from_i31(v)), + RefI31 => exec_op!(unary i32 => ValueRef, |v| ValueRef::from_i31(v)), I31GetS => self.exec_i31_get(true)?, I31GetU => self.exec_i31_get(false)?, - RefEq => stack_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), + RefEq => exec_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), RefTest(ty) => self.exec_ref_test(*ty)?, RefCast(ty) => self.exec_ref_cast(*ty)?, // GC objects @@ -536,46 +598,46 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64Load32U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, // Numeric conversion operations - F32ConvertI32S => stack_op!(unary i32 => f32, |v| v as f32), - F32ConvertI64S => stack_op!(unary i64 => f32, |v| v as f32), - F64ConvertI32S => stack_op!(unary i32 => f64, |v| f64::from(v)), - F64ConvertI64S => stack_op!(unary i64 => f64, |v| v as f64), - F32ConvertI32U => stack_op!(unary u32 => f32, |v| v as f32), - F32ConvertI64U => stack_op!(unary u64 => f32, |v| v as f32), - F64ConvertI32U => stack_op!(unary u32 => f64, |v| f64::from(v)), - F64ConvertI64U => stack_op!(unary u64 => f64, |v| v as f64), + F32ConvertI32S => exec_op!(unary i32 => f32, |v| v as f32), + F32ConvertI64S => exec_op!(unary i64 => f32, |v| v as f32), + F64ConvertI32S => exec_op!(unary i32 => f64, |v| f64::from(v)), + F64ConvertI64S => exec_op!(unary i64 => f64, |v| v as f64), + F32ConvertI32U => exec_op!(unary u32 => f32, |v| v as f32), + F32ConvertI64U => exec_op!(unary u64 => f32, |v| v as f32), + F64ConvertI32U => exec_op!(unary u32 => f64, |v| f64::from(v)), + F64ConvertI64U => exec_op!(unary u64 => f64, |v| v as f64), // Sign-extension operations - I32Extend8S => stack_op!(unary i32, |v| i32::from(v as i8)), - I32Extend16S => stack_op!(unary i32, |v| i32::from(v as i16)), - I64Extend8S => stack_op!(unary i64, |v| i64::from(v as i8)), - I64Extend16S => stack_op!(unary i64, |v| i64::from(v as i16)), - I64Extend32S => stack_op!(unary i64, |v| i64::from(v as i32)), - I64ExtendI32U => stack_op!(unary u32 => i64, |v| i64::from(v)), - I64ExtendI32S => stack_op!(unary i32 => i64, |v| i64::from(v)), - I32WrapI64 => stack_op!(unary i64 => i32, |v| v as i32), - F32DemoteF64 => stack_op!(unary f64 => f32, |v| v as f32), - F64PromoteF32 => stack_op!(unary f32 => f64, |v| f64::from(v)), - F32Abs => stack_op!(unary f32, |v| v.abs()), - F64Abs => stack_op!(unary f64, |v| v.abs()), - F32Neg => stack_op!(unary f32, |v| -v), - F64Neg => stack_op!(unary f64, |v| -v), - F32Ceil => stack_op!(unary f32, |v| v.ceil()), - F64Ceil => stack_op!(unary f64, |v| v.ceil()), - F32Floor => stack_op!(unary f32, |v| v.floor()), - F64Floor => stack_op!(unary f64, |v| v.floor()), - F32Trunc => stack_op!(unary f32, |v| v.trunc()), - F64Trunc => stack_op!(unary f64, |v| v.trunc()), - F32Nearest => stack_op!(unary f32, |v| v.tw_nearest()), - F64Nearest => stack_op!(unary f64, |v| v.tw_nearest()), - F32Sqrt => stack_op!(unary f32, |v| v.sqrt()), - F64Sqrt => stack_op!(unary f64, |v| v.sqrt()), - F32Min => stack_op!(binary f32, |a, b| a.tw_minimum(b)), - F64Min => stack_op!(binary f64, |a, b| a.tw_minimum(b)), - F32Max => stack_op!(binary f32, |a, b| a.tw_maximum(b)), - F64Max => stack_op!(binary f64, |a, b| a.tw_maximum(b)), - F32Copysign => stack_op!(binary f32, |a, b| a.copysign(b)), - F64Copysign => stack_op!(binary f64, |a, b| a.copysign(b)), + I32Extend8S => exec_op!(unary i32 => i32, |v| i32::from(v as i8)), + I32Extend16S => exec_op!(unary i32 => i32, |v| i32::from(v as i16)), + I64Extend8S => exec_op!(unary i64 => i64, |v| i64::from(v as i8)), + I64Extend16S => exec_op!(unary i64 => i64, |v| i64::from(v as i16)), + I64Extend32S => exec_op!(unary i64 => i64, |v| i64::from(v as i32)), + I64ExtendI32U => exec_op!(unary u32 => i64, |v| i64::from(v)), + I64ExtendI32S => exec_op!(unary i32 => i64, |v| i64::from(v)), + I32WrapI64 => exec_op!(unary i64 => i32, |v| v as i32), + F32DemoteF64 => exec_op!(unary f64 => f32, |v| v as f32), + F64PromoteF32 => exec_op!(unary f32 => f64, |v| f64::from(v)), + F32Abs => exec_op!(unary f32 => f32, |v| v.abs()), + F64Abs => exec_op!(unary f64 => f64, |v| v.abs()), + F32Neg => exec_op!(unary f32 => f32, |v| -v), + F64Neg => exec_op!(unary f64 => f64, |v| -v), + F32Ceil => exec_op!(unary f32 => f32, |v| v.ceil()), + F64Ceil => exec_op!(unary f64 => f64, |v| v.ceil()), + F32Floor => exec_op!(unary f32 => f32, |v| v.floor()), + F64Floor => exec_op!(unary f64 => f64, |v| v.floor()), + F32Trunc => exec_op!(unary f32 => f32, |v| v.trunc()), + F64Trunc => exec_op!(unary f64 => f64, |v| v.trunc()), + F32Nearest => exec_op!(unary f32 => f32, |v| v.tw_nearest()), + F64Nearest => exec_op!(unary f64 => f64, |v| v.tw_nearest()), + F32Sqrt => exec_op!(unary f32 => f32, |v| v.sqrt()), + F64Sqrt => exec_op!(unary f64 => f64, |v| v.sqrt()), + F32Min => exec_op!(binary f32 => f32, |a, b| a.tw_minimum(b)), + F64Min => exec_op!(binary f64 => f64, |a, b| a.tw_minimum(b)), + F32Max => exec_op!(binary f32 => f32, |a, b| a.tw_maximum(b)), + F64Max => exec_op!(binary f64 => f64, |a, b| a.tw_maximum(b)), + F32Copysign => exec_op!(binary f32 => f32, |a, b| a.copysign(b)), + F64Copysign => exec_op!(binary f64 => f64, |a, b| a.copysign(b)), I32TruncF32S => checked_conv_float!(f32, i32, self), I32TruncF64S => checked_conv_float!(f64, i32, self), I32TruncF32U => checked_conv_float!(f32, u32, i32, self), @@ -586,25 +648,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64TruncF64U => checked_conv_float!(f64, u64, i64, self), // Non-trapping float-to-int conversions - I32TruncSatF32S => stack_op!(unary f32 => i32, |v| v.trunc() as i32), - I32TruncSatF32U => stack_op!(unary f32 => u32, |v| v.trunc() as u32), - I32TruncSatF64S => stack_op!(unary f64 => i32, |v| v.trunc() as i32), - I32TruncSatF64U => stack_op!(unary f64 => u32, |v| v.trunc() as u32), - I64TruncSatF32S => stack_op!(unary f32 => i64, |v| v.trunc() as i64), - I64TruncSatF32U => stack_op!(unary f32 => u64, |v| v.trunc() as u64), - I64TruncSatF64S => stack_op!(unary f64 => i64, |v| v.trunc() as i64), - I64TruncSatF64U => stack_op!(unary f64 => u64, |v| v.trunc() as u64), + I32TruncSatF32S => exec_op!(unary f32 => i32, |v| v.trunc() as i32), + I32TruncSatF32U => exec_op!(unary f32 => u32, |v| v.trunc() as u32), + I32TruncSatF64S => exec_op!(unary f64 => i32, |v| v.trunc() as i32), + I32TruncSatF64U => exec_op!(unary f64 => u32, |v| v.trunc() as u32), + I64TruncSatF32S => exec_op!(unary f32 => i64, |v| v.trunc() as i64), + I64TruncSatF32U => exec_op!(unary f32 => u64, |v| v.trunc() as u64), + I64TruncSatF64S => exec_op!(unary f64 => i64, |v| v.trunc() as i64), + I64TruncSatF64U => exec_op!(unary f64 => u64, |v| v.trunc() as u64), // SIMD extension - V128Not => stack_op!(unary Value128, |v| v.v128_not()), - V128And => stack_op!(binary Value128, |a, b| a.v128_and(b)), - V128AndNot => stack_op!(binary Value128, |a, b| a.v128_andnot(b)), - V128Or => stack_op!(binary Value128, |a, b| a.v128_or(b)), - V128Xor => stack_op!(binary Value128, |a, b| a.v128_xor(b)), - V128Bitselect => stack_op!(ternary Value128, |a, b, c| Value128::v128_bitselect(a, b, c)), - V128AnyTrue => stack_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), - I8x16Swizzle => stack_op!(binary Value128, |a, s| a.i8x16_swizzle(s)), - I8x16RelaxedSwizzle => stack_op!(binary Value128, |a, s| a.i8x16_relaxed_swizzle(s)), + V128Not => exec_op!(unary Value128 => Value128, |v| v.v128_not()), + V128And => exec_op!(binary Value128 => Value128, |a, b| a.v128_and(b)), + V128AndNot => exec_op!(binary Value128 => Value128, |a, b| a.v128_andnot(b)), + V128Or => exec_op!(binary Value128 => Value128, |a, b| a.v128_or(b)), + V128Xor => exec_op!(binary Value128 => Value128, |a, b| a.v128_xor(b)), + V128Bitselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::v128_bitselect(a, b, c)), + V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), + I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), + I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), V128Load(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| v)?, V128Load8x8S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, V128Load8x8U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, @@ -623,235 +685,235 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128Store64Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load32Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i32x4([v, 0, 0, 0]))?, V128Load64Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i64x2([v, 0]))?, - Const128(arg) => self.exec_const(Value128(self.func.data.v128_const(*arg)))?, - I8x16ExtractLaneS(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), - I8x16ExtractLaneU(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), - I16x8ExtractLaneS(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), - I16x8ExtractLaneU(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_u16(*lane) as i32), - I32x4ExtractLane(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i32(*lane)), - I64x2ExtractLane(lane) => stack_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), - F32x4ExtractLane(lane) => stack_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), - F64x2ExtractLane(lane) => stack_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), + Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(self.func.data.v128_const(*arg)))?, + I8x16ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), + I8x16ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), + I16x8ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), + I16x8ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u16(*lane) as i32), + I32x4ExtractLane(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i32(*lane)), + I64x2ExtractLane(lane) => exec_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), + F32x4ExtractLane(lane) => exec_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), + F64x2ExtractLane(lane) => exec_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), V128Load8Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load16Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load32Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load64Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - I8x16ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), - I16x8ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), - I32x4ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), - I64x2ReplaceLane(lane) => stack_op!(binary i64, Value128, |value, vec| vec.i64x2_replace_lane(*lane, value)), - F32x4ReplaceLane(lane) => stack_op!(binary f32, Value128, |value, vec| vec.f32x4_replace_lane(*lane, value)), - F64x2ReplaceLane(lane) => stack_op!(binary f64, Value128, |value, vec| vec.f64x2_replace_lane(*lane, value)), - I8x16Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)), - I16x8Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)), - I32x4Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i32(v)), - I64x2Splat => stack_op!(unary i64 => Value128, |v| Value128::splat_i64(v)), - F32x4Splat => stack_op!(unary f32 => Value128, |v| Value128::splat_f32(v)), - F64x2Splat => stack_op!(unary f64 => Value128, |v| Value128::splat_f64(v)), - I8x16Eq => stack_op!(binary Value128, |a, b| a.i8x16_eq(b)), - I16x8Eq => stack_op!(binary Value128, |a, b| a.i16x8_eq(b)), - I32x4Eq => stack_op!(binary Value128, |a, b| a.i32x4_eq(b)), - I64x2Eq => stack_op!(binary Value128, |a, b| a.i64x2_eq(b)), - F32x4Eq => stack_op!(binary Value128, |a, b| a.f32x4_eq(b)), - F64x2Eq => stack_op!(binary Value128, |a, b| a.f64x2_eq(b)), - I8x16Ne => stack_op!(binary Value128, |a, b| a.i8x16_ne(b)), - I16x8Ne => stack_op!(binary Value128, |a, b| a.i16x8_ne(b)), - I32x4Ne => stack_op!(binary Value128, |a, b| a.i32x4_ne(b)), - I64x2Ne => stack_op!(binary Value128, |a, b| a.i64x2_ne(b)), - F32x4Ne => stack_op!(binary Value128, |a, b| a.f32x4_ne(b)), - F64x2Ne => stack_op!(binary Value128, |a, b| a.f64x2_ne(b)), - I8x16LtS => stack_op!(binary Value128, |a, b| a.i8x16_lt_s(b)), - I16x8LtS => stack_op!(binary Value128, |a, b| a.i16x8_lt_s(b)), - I32x4LtS => stack_op!(binary Value128, |a, b| a.i32x4_lt_s(b)), - I64x2LtS => stack_op!(binary Value128, |a, b| a.i64x2_lt_s(b)), - I8x16LtU => stack_op!(binary Value128, |a, b| a.i8x16_lt_u(b)), - I16x8LtU => stack_op!(binary Value128, |a, b| a.i16x8_lt_u(b)), - I32x4LtU => stack_op!(binary Value128, |a, b| a.i32x4_lt_u(b)), - F32x4Lt => stack_op!(binary Value128, |a, b| a.f32x4_lt(b)), - F64x2Lt => stack_op!(binary Value128, |a, b| a.f64x2_lt(b)), - F32x4Gt => stack_op!(binary Value128, |a, b| a.f32x4_gt(b)), - F64x2Gt => stack_op!(binary Value128, |a, b| a.f64x2_gt(b)), - I8x16GtS => stack_op!(binary Value128, |a, b| a.i8x16_gt_s(b)), - I16x8GtS => stack_op!(binary Value128, |a, b| a.i16x8_gt_s(b)), - I32x4GtS => stack_op!(binary Value128, |a, b| a.i32x4_gt_s(b)), - I64x2GtS => stack_op!(binary Value128, |a, b| a.i64x2_gt_s(b)), - I64x2LeS => stack_op!(binary Value128, |a, b| a.i64x2_le_s(b)), - F32x4Le => stack_op!(binary Value128, |a, b| a.f32x4_le(b)), - F64x2Le => stack_op!(binary Value128, |a, b| a.f64x2_le(b)), - I8x16GtU => stack_op!(binary Value128, |a, b| a.i8x16_gt_u(b)), - I16x8GtU => stack_op!(binary Value128, |a, b| a.i16x8_gt_u(b)), - I32x4GtU => stack_op!(binary Value128, |a, b| a.i32x4_gt_u(b)), - F32x4Ge => stack_op!(binary Value128, |a, b| a.f32x4_ge(b)), - F64x2Ge => stack_op!(binary Value128, |a, b| a.f64x2_ge(b)), - I8x16LeS => stack_op!(binary Value128, |a, b| a.i8x16_le_s(b)), - I16x8LeS => stack_op!(binary Value128, |a, b| a.i16x8_le_s(b)), - I32x4LeS => stack_op!(binary Value128, |a, b| a.i32x4_le_s(b)), - I8x16LeU => stack_op!(binary Value128, |a, b| a.i8x16_le_u(b)), - I16x8LeU => stack_op!(binary Value128, |a, b| a.i16x8_le_u(b)), - I32x4LeU => stack_op!(binary Value128, |a, b| a.i32x4_le_u(b)), - I8x16GeS => stack_op!(binary Value128, |a, b| a.i8x16_ge_s(b)), - I16x8GeS => stack_op!(binary Value128, |a, b| a.i16x8_ge_s(b)), - I32x4GeS => stack_op!(binary Value128, |a, b| a.i32x4_ge_s(b)), - I64x2GeS => stack_op!(binary Value128, |a, b| a.i64x2_ge_s(b)), - I8x16GeU => stack_op!(binary Value128, |a, b| a.i8x16_ge_u(b)), - I16x8GeU => stack_op!(binary Value128, |a, b| a.i16x8_ge_u(b)), - I32x4GeU => stack_op!(binary Value128, |a, b| a.i32x4_ge_u(b)), - I8x16Abs => stack_op!(unary Value128, |a| a.i8x16_abs()), - I16x8Abs => stack_op!(unary Value128, |a| a.i16x8_abs()), - I32x4Abs => stack_op!(unary Value128, |a| a.i32x4_abs()), - I64x2Abs => stack_op!(unary Value128, |a| a.i64x2_abs()), - I8x16Neg => stack_op!(unary Value128, |a| a.i8x16_neg()), - I16x8Neg => stack_op!(unary Value128, |a| a.i16x8_neg()), - I32x4Neg => stack_op!(unary Value128, |a| a.i32x4_neg()), - I64x2Neg => stack_op!(unary Value128, |a| a.i64x2_neg()), - I8x16AllTrue => stack_op!(unary Value128 => i32, |v| v.i8x16_all_true() as i32), - I16x8AllTrue => stack_op!(unary Value128 => i32, |v| v.i16x8_all_true() as i32), - I32x4AllTrue => stack_op!(unary Value128 => i32, |v| v.i32x4_all_true() as i32), - I64x2AllTrue => stack_op!(unary Value128 => i32, |v| v.i64x2_all_true() as i32), - I8x16Bitmask => stack_op!(unary Value128 => i32, |v| v.i8x16_bitmask() as i32), - I16x8Bitmask => stack_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32), - I32x4Bitmask => stack_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32), - I64x2Bitmask => stack_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32), - I8x16Shl => stack_op!(binary i32, Value128, |a, b| b.i8x16_shl(a as u32)), - I16x8Shl => stack_op!(binary i32, Value128, |a, b| b.i16x8_shl(a as u32)), - I32x4Shl => stack_op!(binary i32, Value128, |a, b| b.i32x4_shl(a as u32)), - I64x2Shl => stack_op!(binary i32, Value128, |a, b| b.i64x2_shl(a as u32)), - I8x16ShrS => stack_op!(binary i32, Value128, |a, b| b.i8x16_shr_s(a as u32)), - I16x8ShrS => stack_op!(binary i32, Value128, |a, b| b.i16x8_shr_s(a as u32)), - I32x4ShrS => stack_op!(binary i32, Value128, |a, b| b.i32x4_shr_s(a as u32)), - I64x2ShrS => stack_op!(binary i32, Value128, |a, b| b.i64x2_shr_s(a as u32)), - I8x16ShrU => stack_op!(binary i32, Value128, |a, b| b.i8x16_shr_u(a as u32)), - I16x8ShrU => stack_op!(binary i32, Value128, |a, b| b.i16x8_shr_u(a as u32)), - I32x4ShrU => stack_op!(binary i32, Value128, |a, b| b.i32x4_shr_u(a as u32)), - I64x2ShrU => stack_op!(binary i32, Value128, |a, b| b.i64x2_shr_u(a as u32)), - I8x16Add => stack_op!(binary Value128, |a, b| a.i8x16_add(b)), - I16x8Add => stack_op!(binary Value128, |a, b| a.i16x8_add(b)), - I32x4Add => stack_op!(binary Value128, |a, b| a.i32x4_add(b)), - I64x2Add => stack_op!(binary Value128, |a, b| a.i64x2_add(b)), - I8x16Sub => stack_op!(binary Value128, |a, b| a.i8x16_sub(b)), - I16x8Sub => stack_op!(binary Value128, |a, b| a.i16x8_sub(b)), - I32x4Sub => stack_op!(binary Value128, |a, b| a.i32x4_sub(b)), - I64x2Sub => stack_op!(binary Value128, |a, b| a.i64x2_sub(b)), - I8x16MinS => stack_op!(binary Value128, |a, b| a.i8x16_min_s(b)), - I16x8MinS => stack_op!(binary Value128, |a, b| a.i16x8_min_s(b)), - I32x4MinS => stack_op!(binary Value128, |a, b| a.i32x4_min_s(b)), - I8x16MinU => stack_op!(binary Value128, |a, b| a.i8x16_min_u(b)), - I16x8MinU => stack_op!(binary Value128, |a, b| a.i16x8_min_u(b)), - I32x4MinU => stack_op!(binary Value128, |a, b| a.i32x4_min_u(b)), - I8x16MaxS => stack_op!(binary Value128, |a, b| a.i8x16_max_s(b)), - I16x8MaxS => stack_op!(binary Value128, |a, b| a.i16x8_max_s(b)), - I32x4MaxS => stack_op!(binary Value128, |a, b| a.i32x4_max_s(b)), - I8x16MaxU => stack_op!(binary Value128, |a, b| a.i8x16_max_u(b)), - I16x8MaxU => stack_op!(binary Value128, |a, b| a.i16x8_max_u(b)), - I32x4MaxU => stack_op!(binary Value128, |a, b| a.i32x4_max_u(b)), - I64x2Mul => stack_op!(binary Value128, |a, b| a.i64x2_mul(b)), - I16x8Mul => stack_op!(binary Value128, |a, b| a.i16x8_mul(b)), - I32x4Mul => stack_op!(binary Value128, |a, b| a.i32x4_mul(b)), - I8x16NarrowI16x8S => stack_op!(binary Value128, |a, b| Value128::i8x16_narrow_i16x8_s(a, b)), - I8x16NarrowI16x8U => stack_op!(binary Value128, |a, b| Value128::i8x16_narrow_i16x8_u(a, b)), - I16x8NarrowI32x4S => stack_op!(binary Value128, |a, b| Value128::i16x8_narrow_i32x4_s(a, b)), - I16x8NarrowI32x4U => stack_op!(binary Value128, |a, b| Value128::i16x8_narrow_i32x4_u(a, b)), - I8x16AddSatS => stack_op!(binary Value128, |a, b| a.i8x16_add_sat_s(b)), - I16x8AddSatS => stack_op!(binary Value128, |a, b| a.i16x8_add_sat_s(b)), - I8x16AddSatU => stack_op!(binary Value128, |a, b| a.i8x16_add_sat_u(b)), - I16x8AddSatU => stack_op!(binary Value128, |a, b| a.i16x8_add_sat_u(b)), - I8x16SubSatS => stack_op!(binary Value128, |a, b| a.i8x16_sub_sat_s(b)), - I16x8SubSatS => stack_op!(binary Value128, |a, b| a.i16x8_sub_sat_s(b)), - I8x16SubSatU => stack_op!(binary Value128, |a, b| a.i8x16_sub_sat_u(b)), - I16x8SubSatU => stack_op!(binary Value128, |a, b| a.i16x8_sub_sat_u(b)), - I8x16AvgrU => stack_op!(binary Value128, |a, b| a.i8x16_avgr_u(b)), - I16x8AvgrU => stack_op!(binary Value128, |a, b| a.i16x8_avgr_u(b)), - I16x8ExtAddPairwiseI8x16S => stack_op!(unary Value128, |a| a.i16x8_extadd_pairwise_i8x16_s()), - I16x8ExtAddPairwiseI8x16U => stack_op!(unary Value128, |a| a.i16x8_extadd_pairwise_i8x16_u()), - I32x4ExtAddPairwiseI16x8S => stack_op!(unary Value128, |a| a.i32x4_extadd_pairwise_i16x8_s()), - I32x4ExtAddPairwiseI16x8U => stack_op!(unary Value128, |a| a.i32x4_extadd_pairwise_i16x8_u()), - I16x8ExtMulLowI8x16S => stack_op!(binary Value128, |a, b| a.i16x8_extmul_low_i8x16_s(b)), - I16x8ExtMulLowI8x16U => stack_op!(binary Value128, |a, b| a.i16x8_extmul_low_i8x16_u(b)), - I16x8ExtMulHighI8x16S => stack_op!(binary Value128, |a, b| a.i16x8_extmul_high_i8x16_s(b)), - I16x8ExtMulHighI8x16U => stack_op!(binary Value128, |a, b| a.i16x8_extmul_high_i8x16_u(b)), - I32x4ExtMulLowI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_extmul_low_i16x8_s(b)), - I32x4ExtMulLowI16x8U => stack_op!(binary Value128, |a, b| a.i32x4_extmul_low_i16x8_u(b)), - I32x4ExtMulHighI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_extmul_high_i16x8_s(b)), - I32x4ExtMulHighI16x8U => stack_op!(binary Value128, |a, b| a.i32x4_extmul_high_i16x8_u(b)), - I64x2ExtMulLowI32x4S => stack_op!(binary Value128, |a, b| a.i64x2_extmul_low_i32x4_s(b)), - I64x2ExtMulLowI32x4U => stack_op!(binary Value128, |a, b| a.i64x2_extmul_low_i32x4_u(b)), - I64x2ExtMulHighI32x4S => stack_op!(binary Value128, |a, b| a.i64x2_extmul_high_i32x4_s(b)), - I64x2ExtMulHighI32x4U => stack_op!(binary Value128, |a, b| a.i64x2_extmul_high_i32x4_u(b)), - I16x8ExtendLowI8x16S => stack_op!(unary Value128, |a| a.i16x8_extend_low_i8x16_s()), - I16x8ExtendLowI8x16U => stack_op!(unary Value128, |a| a.i16x8_extend_low_i8x16_u()), - I16x8ExtendHighI8x16S => stack_op!(unary Value128, |a| a.i16x8_extend_high_i8x16_s()), - I16x8ExtendHighI8x16U => stack_op!(unary Value128, |a| a.i16x8_extend_high_i8x16_u()), - I32x4ExtendLowI16x8S => stack_op!(unary Value128, |a| a.i32x4_extend_low_i16x8_s()), - I32x4ExtendLowI16x8U => stack_op!(unary Value128, |a| a.i32x4_extend_low_i16x8_u()), - I32x4ExtendHighI16x8S => stack_op!(unary Value128, |a| a.i32x4_extend_high_i16x8_s()), - I32x4ExtendHighI16x8U => stack_op!(unary Value128, |a| a.i32x4_extend_high_i16x8_u()), - I64x2ExtendLowI32x4S => stack_op!(unary Value128, |a| a.i64x2_extend_low_i32x4_s()), - I64x2ExtendLowI32x4U => stack_op!(unary Value128, |a| a.i64x2_extend_low_i32x4_u()), - I64x2ExtendHighI32x4S => stack_op!(unary Value128, |a| a.i64x2_extend_high_i32x4_s()), - I64x2ExtendHighI32x4U => stack_op!(unary Value128, |a| a.i64x2_extend_high_i32x4_u()), - I8x16Popcnt => stack_op!(unary Value128, |v| v.i8x16_popcnt()), - I8x16Shuffle(idx) => stack_op!(binary Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(self.func.data.v128_const(*idx)))), - I16x8Q15MulrSatS => stack_op!(binary Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), - I32x4DotI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_dot_i16x8_s(b)), - I8x16RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), - I16x8RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i16x8_relaxed_laneselect(a, b, c)), - I32x4RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i32x4_relaxed_laneselect(a, b, c)), - I64x2RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i64x2_relaxed_laneselect(a, b, c)), - I16x8RelaxedQ15mulrS => stack_op!(binary Value128, |a, b| a.i16x8_relaxed_q15mulr_s(b)), - I16x8RelaxedDotI8x16I7x16S => stack_op!(binary Value128, |a, b| a.i16x8_relaxed_dot_i8x16_i7x16_s(b)), - I32x4RelaxedDotI8x16I7x16AddS => stack_op!(ternary Value128, |a, b, c| a.i32x4_relaxed_dot_i8x16_i7x16_add_s(b, c)), - F32x4Ceil => stack_op!(unary Value128, |v| v.f32x4_ceil()), - F64x2Ceil => stack_op!(unary Value128, |v| v.f64x2_ceil()), - F32x4Floor => stack_op!(unary Value128, |v| v.f32x4_floor()), - F64x2Floor => stack_op!(unary Value128, |v| v.f64x2_floor()), - F32x4Trunc => stack_op!(unary Value128, |v| v.f32x4_trunc()), - F64x2Trunc => stack_op!(unary Value128, |v| v.f64x2_trunc()), - F32x4Nearest => stack_op!(unary Value128, |v| v.f32x4_nearest()), - F64x2Nearest => stack_op!(unary Value128, |v| v.f64x2_nearest()), - F32x4Abs => stack_op!(unary Value128, |v| v.f32x4_abs()), - F64x2Abs => stack_op!(unary Value128, |v| v.f64x2_abs()), - F32x4Neg => stack_op!(unary Value128, |v| v.f32x4_neg()), - F64x2Neg => stack_op!(unary Value128, |v| v.f64x2_neg()), - F32x4Sqrt => stack_op!(unary Value128, |v| v.f32x4_sqrt()), - F64x2Sqrt => stack_op!(unary Value128, |v| v.f64x2_sqrt()), - F32x4Add => stack_op!(binary Value128, |a, b| a.f32x4_add(b)), - F64x2Add => stack_op!(binary Value128, |a, b| a.f64x2_add(b)), - F32x4Sub => stack_op!(binary Value128, |a, b| a.f32x4_sub(b)), - F64x2Sub => stack_op!(binary Value128, |a, b| a.f64x2_sub(b)), - F32x4Mul => stack_op!(binary Value128, |a, b| a.f32x4_mul(b)), - F64x2Mul => stack_op!(binary Value128, |a, b| a.f64x2_mul(b)), - F32x4Div => stack_op!(binary Value128, |a, b| a.f32x4_div(b)), - F64x2Div => stack_op!(binary Value128, |a, b| a.f64x2_div(b)), - F32x4Min => stack_op!(binary Value128, |a, b| a.f32x4_min(b)), - F64x2Min => stack_op!(binary Value128, |a, b| a.f64x2_min(b)), - F32x4Max => stack_op!(binary Value128, |a, b| a.f32x4_max(b)), - F64x2Max => stack_op!(binary Value128, |a, b| a.f64x2_max(b)), - F32x4PMin => stack_op!(binary Value128, |a, b| a.f32x4_pmin(b)), - F32x4PMax => stack_op!(binary Value128, |a, b| a.f32x4_pmax(b)), - F64x2PMin => stack_op!(binary Value128, |a, b| a.f64x2_pmin(b)), - F64x2PMax => stack_op!(binary Value128, |a, b| a.f64x2_pmax(b)), - F32x4RelaxedMadd => stack_op!(ternary Value128, |a, b, c| a.f32x4_relaxed_madd(b, c)), - F32x4RelaxedNmadd => stack_op!(ternary Value128, |a, b, c| a.f32x4_relaxed_nmadd(b, c)), - F64x2RelaxedMadd => stack_op!(ternary Value128, |a, b, c| a.f64x2_relaxed_madd(b, c)), - F64x2RelaxedNmadd => stack_op!(ternary Value128, |a, b, c| a.f64x2_relaxed_nmadd(b, c)), - F32x4RelaxedMin => stack_op!(binary Value128, |a, b| a.f32x4_relaxed_min(b)), - F32x4RelaxedMax => stack_op!(binary Value128, |a, b| a.f32x4_relaxed_max(b)), - F64x2RelaxedMin => stack_op!(binary Value128, |a, b| a.f64x2_relaxed_min(b)), - F64x2RelaxedMax => stack_op!(binary Value128, |a, b| a.f64x2_relaxed_max(b)), - I32x4TruncSatF32x4S => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f32x4_s()), - I32x4TruncSatF32x4U => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f32x4_u()), - F32x4ConvertI32x4S => stack_op!(unary Value128, |v| v.f32x4_convert_i32x4_s()), - F32x4ConvertI32x4U => stack_op!(unary Value128, |v| v.f32x4_convert_i32x4_u()), - F64x2ConvertLowI32x4S => stack_op!(unary Value128, |v| v.f64x2_convert_low_i32x4_s()), - F64x2ConvertLowI32x4U => stack_op!(unary Value128, |v| v.f64x2_convert_low_i32x4_u()), - F32x4DemoteF64x2Zero => stack_op!(unary Value128, |v| v.f32x4_demote_f64x2_zero()), - F64x2PromoteLowF32x4 => stack_op!(unary Value128, |v| v.f64x2_promote_low_f32x4()), - I32x4TruncSatF64x2SZero => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f64x2_s_zero()), - I32x4TruncSatF64x2UZero => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f64x2_u_zero()), - I32x4RelaxedTruncF32x4S => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f32x4_s()), - I32x4RelaxedTruncF32x4U => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f32x4_u()), - I32x4RelaxedTruncF64x2SZero => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f64x2_s_zero()), - I32x4RelaxedTruncF64x2UZero => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()), + I8x16ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), + I16x8ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), + I32x4ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), + I64x2ReplaceLane(lane) => exec_op!(binary_mixed i64, Value128 => Value128, |value, vec| vec.i64x2_replace_lane(*lane, value)), + F32x4ReplaceLane(lane) => exec_op!(binary_mixed f32, Value128 => Value128, |value, vec| vec.f32x4_replace_lane(*lane, value)), + F64x2ReplaceLane(lane) => exec_op!(binary_mixed f64, Value128 => Value128, |value, vec| vec.f64x2_replace_lane(*lane, value)), + I8x16Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)), + I16x8Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)), + I32x4Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i32(v)), + I64x2Splat => exec_op!(unary i64 => Value128, |v| Value128::splat_i64(v)), + F32x4Splat => exec_op!(unary f32 => Value128, |v| Value128::splat_f32(v)), + F64x2Splat => exec_op!(unary f64 => Value128, |v| Value128::splat_f64(v)), + I8x16Eq => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_eq(b)), + I16x8Eq => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_eq(b)), + I32x4Eq => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_eq(b)), + I64x2Eq => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_eq(b)), + F32x4Eq => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_eq(b)), + F64x2Eq => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_eq(b)), + I8x16Ne => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ne(b)), + I16x8Ne => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ne(b)), + I32x4Ne => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ne(b)), + I64x2Ne => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_ne(b)), + F32x4Ne => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_ne(b)), + F64x2Ne => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_ne(b)), + I8x16LtS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_lt_s(b)), + I16x8LtS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_lt_s(b)), + I32x4LtS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_lt_s(b)), + I64x2LtS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_lt_s(b)), + I8x16LtU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_lt_u(b)), + I16x8LtU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_lt_u(b)), + I32x4LtU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_lt_u(b)), + F32x4Lt => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_lt(b)), + F64x2Lt => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_lt(b)), + F32x4Gt => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_gt(b)), + F64x2Gt => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_gt(b)), + I8x16GtS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_gt_s(b)), + I16x8GtS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_gt_s(b)), + I32x4GtS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_gt_s(b)), + I64x2GtS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_gt_s(b)), + I64x2LeS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_le_s(b)), + F32x4Le => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_le(b)), + F64x2Le => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_le(b)), + I8x16GtU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_gt_u(b)), + I16x8GtU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_gt_u(b)), + I32x4GtU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_gt_u(b)), + F32x4Ge => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_ge(b)), + F64x2Ge => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_ge(b)), + I8x16LeS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_le_s(b)), + I16x8LeS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_le_s(b)), + I32x4LeS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_le_s(b)), + I8x16LeU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_le_u(b)), + I16x8LeU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_le_u(b)), + I32x4LeU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_le_u(b)), + I8x16GeS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ge_s(b)), + I16x8GeS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ge_s(b)), + I32x4GeS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ge_s(b)), + I64x2GeS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_ge_s(b)), + I8x16GeU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ge_u(b)), + I16x8GeU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ge_u(b)), + I32x4GeU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ge_u(b)), + I8x16Abs => exec_op!(unary Value128 => Value128, |a| a.i8x16_abs()), + I16x8Abs => exec_op!(unary Value128 => Value128, |a| a.i16x8_abs()), + I32x4Abs => exec_op!(unary Value128 => Value128, |a| a.i32x4_abs()), + I64x2Abs => exec_op!(unary Value128 => Value128, |a| a.i64x2_abs()), + I8x16Neg => exec_op!(unary Value128 => Value128, |a| a.i8x16_neg()), + I16x8Neg => exec_op!(unary Value128 => Value128, |a| a.i16x8_neg()), + I32x4Neg => exec_op!(unary Value128 => Value128, |a| a.i32x4_neg()), + I64x2Neg => exec_op!(unary Value128 => Value128, |a| a.i64x2_neg()), + I8x16AllTrue => exec_op!(unary Value128 => i32, |v| v.i8x16_all_true() as i32), + I16x8AllTrue => exec_op!(unary Value128 => i32, |v| v.i16x8_all_true() as i32), + I32x4AllTrue => exec_op!(unary Value128 => i32, |v| v.i32x4_all_true() as i32), + I64x2AllTrue => exec_op!(unary Value128 => i32, |v| v.i64x2_all_true() as i32), + I8x16Bitmask => exec_op!(unary Value128 => i32, |v| v.i8x16_bitmask() as i32), + I16x8Bitmask => exec_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32), + I32x4Bitmask => exec_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32), + I64x2Bitmask => exec_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32), + I8x16Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)), + I16x8Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)), + I32x4Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)), + I64x2Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)), + I8x16ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)), + I16x8ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)), + I32x4ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)), + I64x2ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)), + I8x16ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)), + I16x8ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)), + I32x4ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)), + I64x2ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)), + I8x16Add => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add(b)), + I16x8Add => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add(b)), + I32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_add(b)), + I64x2Add => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_add(b)), + I8x16Sub => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub(b)), + I16x8Sub => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub(b)), + I32x4Sub => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_sub(b)), + I64x2Sub => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_sub(b)), + I8x16MinS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_min_s(b)), + I16x8MinS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_min_s(b)), + I32x4MinS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_min_s(b)), + I8x16MinU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_min_u(b)), + I16x8MinU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_min_u(b)), + I32x4MinU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_min_u(b)), + I8x16MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_max_s(b)), + I16x8MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_max_s(b)), + I32x4MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_max_s(b)), + I8x16MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_max_u(b)), + I16x8MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_max_u(b)), + I32x4MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_max_u(b)), + I64x2Mul => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_mul(b)), + I16x8Mul => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_mul(b)), + I32x4Mul => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_mul(b)), + I8x16NarrowI16x8S => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_s(a, b)), + I8x16NarrowI16x8U => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_u(a, b)), + I16x8NarrowI32x4S => exec_op!(binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_s(a, b)), + I16x8NarrowI32x4U => exec_op!(binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_u(a, b)), + I8x16AddSatS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add_sat_s(b)), + I16x8AddSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add_sat_s(b)), + I8x16AddSatU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add_sat_u(b)), + I16x8AddSatU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add_sat_u(b)), + I8x16SubSatS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub_sat_s(b)), + I16x8SubSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub_sat_s(b)), + I8x16SubSatU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub_sat_u(b)), + I16x8SubSatU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub_sat_u(b)), + I8x16AvgrU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_avgr_u(b)), + I16x8AvgrU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_avgr_u(b)), + I16x8ExtAddPairwiseI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_s()), + I16x8ExtAddPairwiseI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_u()), + I32x4ExtAddPairwiseI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_s()), + I32x4ExtAddPairwiseI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_u()), + I16x8ExtMulLowI8x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_s(b)), + I16x8ExtMulLowI8x16U => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_u(b)), + I16x8ExtMulHighI8x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_s(b)), + I16x8ExtMulHighI8x16U => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_u(b)), + I32x4ExtMulLowI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_s(b)), + I32x4ExtMulLowI16x8U => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_u(b)), + I32x4ExtMulHighI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_s(b)), + I32x4ExtMulHighI16x8U => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_u(b)), + I64x2ExtMulLowI32x4S => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_s(b)), + I64x2ExtMulLowI32x4U => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_u(b)), + I64x2ExtMulHighI32x4S => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_s(b)), + I64x2ExtMulHighI32x4U => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_u(b)), + I16x8ExtendLowI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_s()), + I16x8ExtendLowI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_u()), + I16x8ExtendHighI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_s()), + I16x8ExtendHighI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_u()), + I32x4ExtendLowI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_s()), + I32x4ExtendLowI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_u()), + I32x4ExtendHighI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_s()), + I32x4ExtendHighI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_u()), + I64x2ExtendLowI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_s()), + I64x2ExtendLowI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_u()), + I64x2ExtendHighI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()), + I64x2ExtendHighI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()), + I8x16Popcnt => exec_op!(unary Value128 => Value128, |v| v.i8x16_popcnt()), + I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(self.func.data.v128_const(*idx)))), + I16x8Q15MulrSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), + I32x4DotI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)), + I8x16RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), + I16x8RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i16x8_relaxed_laneselect(a, b, c)), + I32x4RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i32x4_relaxed_laneselect(a, b, c)), + I64x2RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i64x2_relaxed_laneselect(a, b, c)), + I16x8RelaxedQ15mulrS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_relaxed_q15mulr_s(b)), + I16x8RelaxedDotI8x16I7x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_relaxed_dot_i8x16_i7x16_s(b)), + I32x4RelaxedDotI8x16I7x16AddS => exec_op!(ternary Value128 => Value128, |a, b, c| a.i32x4_relaxed_dot_i8x16_i7x16_add_s(b, c)), + F32x4Ceil => exec_op!(unary Value128 => Value128, |v| v.f32x4_ceil()), + F64x2Ceil => exec_op!(unary Value128 => Value128, |v| v.f64x2_ceil()), + F32x4Floor => exec_op!(unary Value128 => Value128, |v| v.f32x4_floor()), + F64x2Floor => exec_op!(unary Value128 => Value128, |v| v.f64x2_floor()), + F32x4Trunc => exec_op!(unary Value128 => Value128, |v| v.f32x4_trunc()), + F64x2Trunc => exec_op!(unary Value128 => Value128, |v| v.f64x2_trunc()), + F32x4Nearest => exec_op!(unary Value128 => Value128, |v| v.f32x4_nearest()), + F64x2Nearest => exec_op!(unary Value128 => Value128, |v| v.f64x2_nearest()), + F32x4Abs => exec_op!(unary Value128 => Value128, |v| v.f32x4_abs()), + F64x2Abs => exec_op!(unary Value128 => Value128, |v| v.f64x2_abs()), + F32x4Neg => exec_op!(unary Value128 => Value128, |v| v.f32x4_neg()), + F64x2Neg => exec_op!(unary Value128 => Value128, |v| v.f64x2_neg()), + F32x4Sqrt => exec_op!(unary Value128 => Value128, |v| v.f32x4_sqrt()), + F64x2Sqrt => exec_op!(unary Value128 => Value128, |v| v.f64x2_sqrt()), + F32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_add(b)), + F64x2Add => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_add(b)), + F32x4Sub => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_sub(b)), + F64x2Sub => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_sub(b)), + F32x4Mul => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_mul(b)), + F64x2Mul => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_mul(b)), + F32x4Div => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_div(b)), + F64x2Div => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_div(b)), + F32x4Min => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_min(b)), + F64x2Min => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_min(b)), + F32x4Max => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_max(b)), + F64x2Max => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_max(b)), + F32x4PMin => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_pmin(b)), + F32x4PMax => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_pmax(b)), + F64x2PMin => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_pmin(b)), + F64x2PMax => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_pmax(b)), + F32x4RelaxedMadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_madd(b, c)), + F32x4RelaxedNmadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_nmadd(b, c)), + F64x2RelaxedMadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_madd(b, c)), + F64x2RelaxedNmadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_nmadd(b, c)), + F32x4RelaxedMin => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_relaxed_min(b)), + F32x4RelaxedMax => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_relaxed_max(b)), + F64x2RelaxedMin => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_relaxed_min(b)), + F64x2RelaxedMax => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_relaxed_max(b)), + I32x4TruncSatF32x4S => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_s()), + I32x4TruncSatF32x4U => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_u()), + F32x4ConvertI32x4S => exec_op!(unary Value128 => Value128, |v| v.f32x4_convert_i32x4_s()), + F32x4ConvertI32x4U => exec_op!(unary Value128 => Value128, |v| v.f32x4_convert_i32x4_u()), + F64x2ConvertLowI32x4S => exec_op!(unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_s()), + F64x2ConvertLowI32x4U => exec_op!(unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_u()), + F32x4DemoteF64x2Zero => exec_op!(unary Value128 => Value128, |v| v.f32x4_demote_f64x2_zero()), + F64x2PromoteLowF32x4 => exec_op!(unary Value128 => Value128, |v| v.f64x2_promote_low_f32x4()), + I32x4TruncSatF64x2SZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_s_zero()), + I32x4TruncSatF64x2UZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_u_zero()), + I32x4RelaxedTruncF32x4S => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_s()), + I32x4RelaxedTruncF32x4U => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_u()), + I32x4RelaxedTruncF64x2SZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_s_zero()), + I32x4RelaxedTruncF64x2UZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()), }; self.cf.instr_ptr = instr_ptr + 1; @@ -859,148 +921,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(None) } - #[inline(always)] - fn jump_if(&mut self, condition: bool, ip: u32) -> bool { - if condition { - self.cf.instr_ptr = ip as usize; - } - condition - } - - #[inline(always)] - fn exec_jump_zero_32(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) == 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_non_zero_32(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) != 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_zero_64(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) == 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_non_zero_64(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) != 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_ref_null(&mut self, target_ip: u32) -> bool { - let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); - if is_null { - ValueRef::stack_pop(&mut self.store.value_stack); - } - self.jump_if(is_null, target_ip) - } - - #[inline(always)] - fn exec_jump_ref_non_null(&mut self, target_ip: u32) -> bool { - let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null(); - if !is_non_null { - ValueRef::stack_pop(&mut self.store.value_stack); - } - self.jump_if(is_non_null, target_ip) - } - - #[inline(always)] - fn exec_jump_local_zero_32(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value32::local_get(&self.store.value_stack, &self.cf, local) == 0, target_ip) - } - - #[inline(always)] - fn exec_jump_local_non_zero_32(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value32::local_get(&self.store.value_stack, &self.cf, local) != 0, target_ip) - } - - #[inline(always)] - fn exec_jump_local_zero_64(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value64::local_get(&self.store.value_stack, &self.cf, local) == 0, target_ip) - } - - #[inline(always)] - fn exec_jump_local_non_zero_64(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value64::local_get(&self.store.value_stack, &self.cf, local) != 0, target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_const_32(&mut self, target_ip: u32, imm: i32, op: CmpOp) -> bool { - let condition = cmp_i32(::stack_pop(&mut self.store.value_stack), imm, op); - self.jump_if(condition, target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_const_64(&mut self, target_ip: u32, imm: i64, op: CmpOp) -> bool { - let condition = cmp_i64(::stack_pop(&mut self.store.value_stack), imm, op); - self.jump_if(condition, target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_local_32(&mut self, target_ip: u32, local: LocalAddr, op: CmpOp) -> bool { - let lhs = ::stack_pop(&mut self.store.value_stack); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, local); - self.jump_if(cmp_i32(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_local_64(&mut self, target_ip: u32, local: LocalAddr, op: CmpOp) -> bool { - let lhs = ::stack_pop(&mut self.store.value_stack); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, local); - self.jump_if(cmp_i64(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_inc_local_jump_32(&mut self, target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool) -> bool { - let value = i32::local_get(&self.store.value_stack, &self.cf, local).wrapping_add(delta); - i32::local_set(&mut self.store.value_stack, &self.cf, local, value); - self.jump_if((value == 0) == on_zero, target_ip) - } - - #[inline(always)] - fn exec_inc_local_jump_cmp_local_32( - &mut self, - target_ip: u32, - local: LocalAddr, - delta: i32, - right: LocalAddr, - op: CmpOp, - ) -> bool { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, local).wrapping_add(delta); - i32::local_set(&mut self.store.value_stack, &self.cf, local, lhs); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, right); - self.jump_if(cmp_i32(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_const_32(&mut self, target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp) -> bool { - self.jump_if(cmp_i32(i32::local_get(&self.store.value_stack, &self.cf, local), imm, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_const_64(&mut self, target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp) -> bool { - self.jump_if(cmp_i64(i64::local_get(&self.store.value_stack, &self.cf, local), i64::from(imm), op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_local_32(&mut self, target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp) -> bool { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, left); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, right); - self.jump_if(cmp_i32(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_local_64(&mut self, target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp) -> bool { - let lhs = i64::local_get(&self.store.value_stack, &self.cf, left); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, right); - self.jump_if(cmp_i64(lhs, rhs, op), target_ip) - } - fn exec_branch_table(&mut self, default_ip: u32, start: u32, len: u32) { let idx = ::stack_pop(&mut self.store.value_stack); let target_ip = if idx >= 0 && (idx as u32) < len { @@ -1453,18 +1373,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - #[inline(always)] - fn exec_binop_acc_local(&mut self, acc: LocalAddr, mul: M, add: A) - where - T: InternalValue, - M: Fn(T, T) -> T, - A: Fn(T, T) -> T, - { - let rhs = T::stack_pop(&mut self.store.value_stack); - let lhs = T::stack_pop(&mut self.store.value_stack); - T::local_update(&mut self.store.value_stack, &self.cf, acc, |v| add(mul(lhs, rhs), v)); - } - #[inline(always)] fn exec_load_local_value, const N: usize>( &self, @@ -1520,10 +1428,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_const(&mut self, val: T) -> Result<(), Trap> { - self.store.value_stack.push(val) - } - fn exec_ref_is_null(&mut self) -> Result<(), Trap> { let is_null = i32::from(::stack_pop(&mut self.store.value_stack).is_null()); self.store.value_stack.push::(is_null) @@ -1540,7 +1444,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn canonical_ref_type(&self, ty: RefType) -> RefType { let Some(type_index) = ty.type_index() else { return ty }; RefType::new_concrete(ty.is_nullable(), self.module.resolve_type_addr(type_index)) - .expect("canonical type address fits in a reference") } fn exec_ref_matches(&self, ty: RefType) -> bool { @@ -2171,3 +2074,60 @@ fn cmp_i64(lhs: i64, rhs: i64, op: CmpOp) -> bool { CmpOp::GeU => (lhs as u64) >= (rhs as u64), } } + +fn exec_binop_32(op: BinOp, lhs: u32, rhs: u32) -> u32 { + match op { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32, + BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32, + BinOp::IShrU => lhs.wrapping_shr(rhs), + BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32, + BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32, + BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(), + BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(), + BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(), + BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(), + BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(), + } +} + +fn exec_binop_64(op: BinOp, lhs: u64, rhs: u64) -> u64 { + match op { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64, + BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64, + BinOp::IShrU => lhs.wrapping_shr(rhs as u32), + BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64, + BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64, + BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(), + BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(), + BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(), + BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(), + BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(), + } +} + +fn exec_binop_128(op: BinOp128, lhs: Value128, rhs: Value128) -> Value128 { + match op { + BinOp128::And => lhs.v128_and(rhs), + BinOp128::AndNot => lhs.v128_andnot(rhs), + BinOp128::Or => lhs.v128_or(rhs), + BinOp128::Xor => lhs.v128_xor(rhs), + BinOp128::I64x2Add => lhs.i64x2_add(rhs), + BinOp128::I64x2Mul => lhs.i64x2_mul(rhs), + } +} diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index e12ef1a..6d13579 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -271,23 +271,20 @@ impl State { if expected_func { let Some(func_addr) = value.addr() else { return false }; let Some(func) = self.funcs.get(func_addr as usize) else { return false }; - let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); - return self.ref_type_is_subtype(actual, expected); + return self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected); } if expected.abstract_heap_type() == Some(AbstractHeapType::Exn) { return value.addr().is_some_and(|addr| self.exceptions.get(addr as usize).is_some()); } if value.is_i31() { - let actual = RefType::new_abstract(false, AbstractHeapType::I31); - return self.ref_type_is_subtype(actual, expected); + return self.ref_type_is_subtype(RefType::new_abstract(false, AbstractHeapType::I31), expected); } if value.is_host_any() { - let actual = RefType::new_abstract(false, AbstractHeapType::Any); - return self.ref_type_is_subtype(actual, expected); + return self.ref_type_is_subtype(RefType::new_abstract(false, AbstractHeapType::Any), expected); } let Some(object) = self.gc.get(value) else { return false }; - let actual = RefType::new_concrete(false, object.type_addr).expect("canonical type fits"); + let actual = RefType::new_concrete(false, object.type_addr); self.ref_type_is_subtype(actual, expected) } @@ -309,12 +306,10 @@ impl State { pub(crate) fn value_matches_type(&self, value: WasmValue, expected: WasmType) -> bool { match (value, expected) { (WasmValue::Ref(RefValue::Null), WasmType::Ref(expected)) => expected.is_nullable(), - (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => { - self.funcs.get(func.addr() as usize).is_some_and(|func| { - let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); - self.ref_type_is_subtype(actual, expected) - }) - } + (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => self + .funcs + .get(func.addr() as usize) + .is_some_and(|func| self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected)), (WasmValue::Ref(RefValue::Any(_)), WasmType::Ref(expected)) if expected.is_func() || expected.is_extern() || expected.is_exn() => { diff --git a/crates/tinywasm/src/store/types.rs b/crates/tinywasm/src/store/types.rs index 4954bba..e9fa6d1 100644 --- a/crates/tinywasm/src/store/types.rs +++ b/crates/tinywasm/src/store/types.rs @@ -6,7 +6,7 @@ use super::Store; pub(crate) fn canonicalize_ref_type(ty: RefType, type_addrs: &[TypeAddr]) -> RefType { let Some(type_addr) = ty.type_index() else { return ty }; let canonical = *type_addrs.get(type_addr as usize).expect("validated type address should exist"); - RefType::new_concrete(ty.is_nullable(), canonical).expect("canonical type addresses fit in references") + RefType::new_concrete(ty.is_nullable(), canonical) } pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) -> WasmType { @@ -18,12 +18,10 @@ pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) -> fn map_value_type(ty: WasmType, resolve: &mut impl FnMut(TypeAddr) -> TypeAddr) -> WasmType { match ty { - WasmType::Ref(ty) if ty.is_concrete() => { - let addr = resolve(ty.type_index().expect("concrete reference has a type index")); - WasmType::Ref( - RefType::new_concrete(ty.is_nullable(), addr).expect("canonical type addresses fit in references"), - ) - } + WasmType::Ref(ty) if ty.is_concrete() => WasmType::Ref(RefType::new_concrete( + ty.is_nullable(), + resolve(ty.type_index().expect("concrete reference has a type index")), + )), ty => ty, } } diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index 128f1ed..38a85ef 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -155,7 +155,7 @@ fn imported_host_functions_resolve_concrete_types() -> Result<(), Box Variable Instructions // See - GlobalGet32(GlobalAddr), LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), GlobalSet32(GlobalAddr), - GlobalGet64(GlobalAddr), LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), GlobalSet64(GlobalAddr), - GlobalGet128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), GlobalSet128(GlobalAddr), + GlobalGet32(GlobalAddr), GlobalSet32(GlobalAddr), GlobalTee32(GlobalAddr), LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), + GlobalGet64(GlobalAddr), GlobalSet64(GlobalAddr), GlobalTee64(GlobalAddr), LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), + GlobalGet128(GlobalAddr), GlobalSet128(GlobalAddr), GlobalTee128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), // > Memory Instructions I32Load(MemoryArg), diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index 884d330..9ed5df1 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -73,12 +73,9 @@ impl RefType { } #[inline] - pub const fn new_concrete(nullable: bool, type_index: u32) -> Option { - if type_index <= Self::PAYLOAD_MASK { - Some(Self(((nullable as u32) << 31) | Self::CONCRETE | type_index)) - } else { - None - } + pub const fn new_concrete(nullable: bool, type_index: u32) -> Self { + assert!(type_index <= Self::PAYLOAD_MASK, "type index is too large for a reference type"); + Self(((nullable as u32) << 31) | Self::CONCRETE | type_index) } #[inline] @@ -193,7 +190,7 @@ impl ExternRef { #[inline] pub const fn try_new(addr: u32) -> Option { match encode_host_ref(addr) { - Some(raw) => Some(Self(raw)), + Some(encoded) => Some(Self(encoded)), None => None, } } @@ -251,7 +248,7 @@ impl AnyRef { #[inline] pub const fn from_host(addr: u32) -> Option { match encode_host_ref(addr) { - Some(raw) => Some(Self(raw)), + Some(encoded) => Some(Self(encoded)), None => None, } } diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs index f0a576b..5049ba2 100644 --- a/crates/types/src/value.rs +++ b/crates/types/src/value.rs @@ -81,7 +81,7 @@ mod tests { #[test] fn concrete_references_require_store_type_information() { - let concrete = WasmType::Ref(RefType::new_concrete(false, 0).unwrap()); + let concrete = WasmType::Ref(RefType::new_concrete(false, 0)); assert!(!WasmValue::from(FuncRef::new(0)).matches_type(concrete)); assert!(!WasmValue::from(AnyRef::from_host(0).unwrap()).matches_type(concrete)); diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index 0ae646c..b338bd2 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -22,6 +22,10 @@ path = "src/print.rs" name = "tinywasm" path = "src/tinywasm.rs" +[[bin]] +name = "tinywasm_precompiled" +path = "src/tinywasm_precompiled.rs" + [[bin]] name = "tinywasm_no_std" path = "src/tinywasm_no_std.rs" @@ -39,8 +43,7 @@ argon2 = { version = "0.5" } dlmalloc = { version = "0.2", features = ["global"] } tinywasm = { path = "../../crates/tinywasm", default-features = false, features = [ "archive", - "parser", - "validate" + "parser" ] } [features] diff --git a/examples/rust/build.sh b/examples/rust/build.sh index db4cb43..b2a6149 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash cd "$(dirname "$0")" || exit -bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "argon2id") -exclude_wat=("tinywasm") +bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "tinywasm_precompiled" "argon2id") +exclude_wat=("tinywasm" "tinywasm_precompiled") out_dir="./target/wasm32-unknown-unknown/wasm" dest_dir="out" @@ -13,8 +13,9 @@ wasmopt_features="--enable-simd --enable-relaxed-simd --enable-tail-call --enabl mkdir -p "$dest_dir" # build no_std -cargo build --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features +RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features cp "$out_dir/tinywasm_no_std.wasm" "$dest_dir/" +wasm-opt "$dest_dir/tinywasm_no_std.wasm" -o "$dest_dir/tinywasm_no_std.opt.wasm" -O3 $wasmopt_features for bin in "${bins[@]}"; do RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=std,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin "$bin" diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm new file mode 100644 index 0000000..f0fa9a8 Binary files /dev/null and b/examples/rust/src/print.twasm differ diff --git a/examples/rust/src/tinywasm_no_std.rs b/examples/rust/src/tinywasm_no_std.rs index cbf10f4..a70abb9 100644 --- a/examples/rust/src/tinywasm_no_std.rs +++ b/examples/rust/src/tinywasm_no_std.rs @@ -1,7 +1,7 @@ #![no_main] #![no_std] use dlmalloc::GlobalDlmalloc; -use tinywasm::{FuncContext, HostFunction, ModuleInstance}; +use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance}; extern crate alloc; @@ -28,9 +28,7 @@ fn run() -> tinywasm::Result<()> { let mut store = tinywasm::Store::default(); let mut imports = tinywasm::Imports::new(); - let res = tinywasm::parser::Parser::default().parse_module_bytes(include_bytes!("./print.wasm"))?; - let twasm = res.serialize_twasm()?; - let module = tinywasm::parse_bytes(&twasm)?; + let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?; let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { unsafe { printi32(v) } diff --git a/examples/rust/src/tinywasm_precompiled.rs b/examples/rust/src/tinywasm_precompiled.rs new file mode 100644 index 0000000..bc0e0c1 --- /dev/null +++ b/examples/rust/src/tinywasm_precompiled.rs @@ -0,0 +1,30 @@ +#![no_main] +use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance}; + +#[link(wasm_import_module = "env")] +unsafe extern "C" { + fn printi32(x: i32); +} + +#[unsafe(no_mangle)] +pub extern "C" fn hello() { + let _ = run(); +} + +fn run() -> tinywasm::Result<()> { + let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?; + let mut store = tinywasm::Store::default(); + + let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { + unsafe { printi32(v) } + Ok(()) + }); + + let mut imports = tinywasm::Imports::new(); + imports.define("env", "printi32", printi32); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?; + add_and_print.call(&mut store, (1, 2))?; + Ok(()) +} diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs index 672b290..b3398f8 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -35,6 +35,8 @@ fn main() -> Result<()> { println!(" host_fn"); println!(" fibonacci - calculate fibonacci(30)"); println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); + println!(" tinywasm_precompiled - run a precompiled module inside of tinywasm"); + println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); println!(" argon2id - run argon2id(1000, 2, 1)"); return Ok(()); } @@ -44,6 +46,7 @@ fn main() -> Result<()> { "printi32" => printi32()?, "fibonacci" => fibonacci()?, "tinywasm" => tinywasm()?, + "tinywasm_precompiled" => tinywasm_precompiled()?, "tinywasm_no_std" => tinywasm_no_std()?, "argon2id" => argon2id()?, "host_fn" => host_fn()?, @@ -57,6 +60,8 @@ fn main() -> Result<()> { fibonacci()?; println!("\ntinywasm.wasm:"); tinywasm()?; + println!("\ntinywasm_precompiled.wasm:"); + tinywasm_precompiled()?; println!("\ntinywasm_no_std.wasm:"); tinywasm_no_std()?; println!("argon2id.wasm:"); @@ -100,6 +105,21 @@ fn tinywasm_no_std() -> Result<()> { Ok(()) } +fn tinywasm_precompiled() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/tinywasm_precompiled.opt.wasm")?; + let mut store = Store::default(); + + let mut imports = Imports::new(); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; + + let hello = instance.func::<(), ()>(&store, "hello")?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + Ok(()) +} + fn hello() -> Result<()> { let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?; let mut store = Store::default(); @@ -211,6 +231,11 @@ mod tests { tinywasm().unwrap(); } + #[test] + fn test_tinywasm_precompiled() { + tinywasm_precompiled().unwrap(); + } + #[test] fn test_tinywasm_no_std() { tinywasm_no_std().unwrap(); -- cgit v1.3.1 From e862a9ef83957b2e1e92e211922ce4e131c6e2b3 Mon Sep 17 00:00:00 2001 From: Henry Date: Wed, 12 Aug 2026 18:00:11 +0200 Subject: chore: improve interpreter performance, add cold path macros Signed-off-by: Henry --- Cargo.lock | 20 +- Cargo.toml | 6 +- crates/parser/src/optimize.rs | 48 +- crates/tinywasm/src/error.rs | 4 + crates/tinywasm/src/imports.rs | 31 +- crates/tinywasm/src/instance.rs | 15 +- crates/tinywasm/src/interpreter/executor.rs | 492 ++++++++------------- .../tinywasm/src/interpreter/stack/call_stack.rs | 7 +- .../tinywasm/src/interpreter/stack/value_stack.rs | 3 +- crates/tinywasm/src/interpreter/values.rs | 5 +- crates/tinywasm/src/lib.rs | 2 + crates/tinywasm/src/macros.rs | 18 + crates/tinywasm/src/store/const_expr.rs | 22 +- crates/tinywasm/src/store/element.rs | 11 +- crates/tinywasm/src/store/gc/mod.rs | 2 +- crates/tinywasm/src/store/memory/instance.rs | 12 +- crates/tinywasm/src/store/memory/lazy.rs | 4 +- crates/tinywasm/src/store/memory/mod.rs | 34 +- crates/tinywasm/src/store/memory/paged.rs | 17 +- crates/tinywasm/src/store/memory/vec.rs | 21 +- crates/tinywasm/src/store/mod.rs | 18 +- crates/tinywasm/src/store/state.rs | 4 +- crates/tinywasm/src/store/table.rs | 6 +- crates/tinywasm/tests/typed_globals.rs | 10 +- crates/types/src/instructions.rs | 3 + 25 files changed, 343 insertions(+), 472 deletions(-) create mode 100644 crates/tinywasm/src/macros.rs (limited to 'crates/parser/src/optimize.rs') diff --git a/Cargo.lock b/Cargo.lock index c4dbba7..b06f70f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -111,9 +111,9 @@ checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" [[package]] name = "bstr" -version = "1.13.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" dependencies = [ "memchr", "regex-automata", @@ -962,9 +962,9 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.255.0" +version = "0.256.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b524283fb5df62eec102ed0574838961bdd7ba5ac9c50d38e2756c51c971a42" +checksum = "ec1492381bfd5ea51c2a99a919b676662559925cb8d7490547ec2e14c1ad3eb1" dependencies = [ "leb128fmt", "wasmparser", @@ -982,9 +982,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.255.0" +version = "0.256.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8e329ef4b5d46e73b91d3ac6924417cad55a8cbbf869c199283383427c3320b" +checksum = "60bd825ffedc6cba8a642924ba7ae424afbc47811cffbcb7b92031ec24e59b4c" dependencies = [ "bitflags", "indexmap", @@ -993,9 +993,9 @@ dependencies = [ [[package]] name = "wast" -version = "255.0.0" +version = "256.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55ffec530f199bd3d553ac442c13dd108353cad533cad8514bc41e1f1f0fe686" +checksum = "a3ad42723fc9222da007f05812a3249c9a4ee7af79d497fc2a2079579ad7efe6" dependencies = [ "bumpalo", "leb128fmt", @@ -1006,9 +1006,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.255.0" +version = "1.256.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dda82c82e1486c7eed42a0465e544d80fff37abc3b39482e0d34dbaabe2fe5b1" +checksum = "37cc86c54d8011b3202e265bfebada440733ea3a788ffaf46d395f7d2fdeacfb" dependencies = [ "wast", ] diff --git a/Cargo.toml b/Cargo.toml index 5a4e83f..3af064c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,9 +31,9 @@ pretty_env_logger = "0.5" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } wasm-testsuite = { version = "0.7" } -wasmparser = { version = "0.255", default-features = false } -wast = "255" -wat = "1.255" +wasmparser = { version = "0.256", default-features = false } +wast = "256" +wat = "1.256" criterion = { version = "0.8", default-features = false, features = [ "cargo_bench_support", diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 7081187..969d686 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -96,9 +96,14 @@ fn rewrite( rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); rewrite!(instrs, i, [I32Add] => I32Add3); + rewrite!(instrs, i, + [BinOpStackLocal32(BinOp::IAdd, local)] => + [LocalGet32(local), I32Add3] + ); } } instr @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { @@ -107,6 +112,7 @@ fn rewrite( rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]); rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 16), Const32(16)] => [LocalGet32(local), I32Extend16S]); @@ -152,12 +158,14 @@ fn rewrite( rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); + rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); } instr @ (F32Sub | F32Div | F32Copysign) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); + rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); } instr @ (F64Add | F64Mul | F64Min | F64Max) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; @@ -198,6 +206,10 @@ fn rewrite( IncMemoryLocal32(memarg, load_addr) ); rewrite!(instrs, i, [F32Mul, F32Add] => FMaStoreF32(memarg)); + rewrite!(instrs, i, + [BinOpStackLocal32(BinOp::FMul, local), F32Add] => + [LocalGet32(local), FMaStoreF32(memarg)] + ); rewrite!(instrs, i, [LocalGet32(addr_local), LocalGet32(value_local)] if (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) => @@ -313,6 +325,15 @@ fn rewrite( ); rewrite!(instrs, i, [I32Mul, LocalGet32(acc), I32Add] if (acc == dst) => MulAccLocal32(dst)); rewrite!(instrs, i, [F32Mul, LocalGet32(acc), F32Add] if (acc == dst) => FMulAccLocal32(dst)); + rewrite!(instrs, i, + [I32Mul, BinOpStackLocal32(BinOp::IAdd, acc)] if (acc == dst) => + MulAccLocal32(dst) + ); + rewrite!(instrs, i, + [F32Mul, BinOpStackLocal32(BinOp::FAdd, acc)] if (acc == dst) => + FMulAccLocal32(dst) + ); + rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalSet32(op, local, dst)); rewrite_local_set_direct!( instrs, i, @@ -403,6 +424,7 @@ fn rewrite( ); } LocalTee32(dst) => { + rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalTee32(op, local, dst)); fold_local_binop!( instrs, i, dst, source = resolve_local_source_32, @@ -501,16 +523,22 @@ fn rewrite( LoadLocalTee128(memarg, addr, dst) ); } - Drop32 => rewrite_drop_tee_direct!( - instrs, - i, - tee = LocalTee32, - set = LocalSet32, - binop_local_local_tee = BinOpLocalLocalTee32, - binop_local_local_set = BinOpLocalLocalSet32, - binop_local_const_tee = BinOpLocalConstTee32, - binop_local_const_set = BinOpLocalConstSet32 - ), + Drop32 => { + rewrite!(instrs, i, + [BinOpStackLocalTee32(op, local, dst)] => + BinOpStackLocalSet32(op, local, dst) + ); + rewrite_drop_tee_direct!( + instrs, + i, + tee = LocalTee32, + set = LocalSet32, + binop_local_local_tee = BinOpLocalLocalTee32, + binop_local_local_set = BinOpLocalLocalSet32, + binop_local_const_tee = BinOpLocalConstTee32, + binop_local_const_set = BinOpLocalConstSet32 + ); + } Drop64 => rewrite_drop_tee_direct!( instrs, i, diff --git a/crates/tinywasm/src/error.rs b/crates/tinywasm/src/error.rs index 0597847..05e36aa 100644 --- a/crates/tinywasm/src/error.rs +++ b/crates/tinywasm/src/error.rs @@ -250,18 +250,21 @@ impl LinkingError { } impl From for Error { + #[cold] fn from(value: LinkingError) -> Self { Self::Linker(value) } } impl From for Error { + #[cold] fn from(value: TwasmError) -> Self { Self::Twasm(value) } } impl From for Error { + #[cold] fn from(value: Trap) -> Self { Self::Trap(value) } @@ -364,6 +367,7 @@ impl From for crate::std::io::Error { #[cfg(feature = "parser")] impl From for Error { + #[cold] fn from(value: tinywasm_parser::ParseError) -> Self { Self::Parser(value) } diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index b8de4e0..eb2351b 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -1,7 +1,6 @@ use alloc::collections::BTreeMap; use alloc::string::{String, ToString}; use alloc::vec::Vec; -use core::hint::cold_path; use crate::{Function, Global, HostFunction, LinkingError, Memory, Result, Table, Tag}; use tinywasm_types::*; @@ -175,8 +174,7 @@ impl Imports { fn compare_types(import: &Import, actual: &T, expected: &T) -> Result<()> { if expected != actual { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } Ok(()) } @@ -187,14 +185,12 @@ impl Imports { return Err(LinkingError::incompatible_import_type(import).into()); } if actual.size_initial < expected.size_initial { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } match expected.size_max { Some(expected_max) if actual.size_max.is_none_or(|actual_max| actual_max > expected_max) => { - cold_path(); - Err(LinkingError::incompatible_import_type(import).into()) + cold!(Err(LinkingError::incompatible_import_type(import).into())) } _ => Ok(()), } @@ -268,8 +264,7 @@ impl Imports { } Extern::HostFunction(func) => { let ImportKind::Function(type_idx) = import.kind else { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); }; let expected_type_addr = type_addrs .get(type_idx as usize) @@ -277,8 +272,7 @@ impl Imports { let actual_ty = func.resolve_import_type(type_addrs)?; let actual_type_addr = store.register_host_type(&actual_ty); if !store.state.type_addr_is_subtype(actual_type_addr, *expected_type_addr) { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } ExternVal::Func(func.instantiate_registered(store, actual_type_addr).addr()) } @@ -289,16 +283,14 @@ impl Imports { } } else { let Some(instance) = self.modules.get(import.module.as_ref()) else { - cold_path(); - return Err(LinkingError::unknown_import(import).into()); + return cold!(Err(LinkingError::unknown_import(import).into())); }; instance.validate_store(store)?; instance.export_addr(&import.name).ok_or_else(|| LinkingError::unknown_import(import))? }; if val.kind() != (&import.kind).into() { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } match (val, &import.kind) { @@ -309,8 +301,7 @@ impl Imports { && store.state.value_type_is_subtype(global_ty.ty, expected.ty) && (!ty.mutable || store.state.value_type_is_subtype(expected.ty, global_ty.ty)); if !compatible { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } imports.globals.push(global_addr); } @@ -336,8 +327,7 @@ impl Imports { type_addrs.get(*ty as usize).ok_or_else(|| LinkingError::incompatible_import_type(import))?; if !store.state.type_addr_is_subtype(store.state.get_func(func_addr).type_addr, *expected_type_addr) { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } imports.funcs.push(func_addr); } @@ -346,8 +336,7 @@ impl Imports { .get(ty.type_idx as usize) .ok_or_else(|| LinkingError::incompatible_import_type(import))?; if store.state.get_tag(tag_addr).type_addr != *expected_type_addr { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } imports.tags.push(tag_addr); } diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 23bb298..f45b718 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -111,8 +111,7 @@ impl ModuleInstance { #[inline] pub(crate) fn validate_store(&self, store: &Store) -> Result<()> { if self.0.store_id != store.id() { - cold_path(); - return Err(Trap::InvalidStore.into()); + return cold!(Err(Trap::InvalidStore.into())); } Ok(()) } @@ -205,8 +204,7 @@ impl ModuleInstance { store.add_instance(instance.clone()); if let Some(trap) = elem_trapped.or(data_trapped) { - cold_path(); - return Err(trap.into()); + return cold!(Err(trap.into())); } Ok(instance) } @@ -356,8 +354,7 @@ impl ModuleInstance { self.validate_store(store)?; let ExternVal::Func(func_addr) = self.require_export(name)? else { - cold_path(); - return Err(Error::Other(format!("Export is not a function: {name}"))); + return cold!(Err(Error::Other(format!("Export is not a function: {name}")))); }; Ok(Function { item: StoreItem::new(self.0.store_id, func_addr), module_id: self.id() }) @@ -410,8 +407,7 @@ impl ModuleInstance { self.validate_store(store)?; let ExternVal::Func(func_addr) = self.require_export(name)? else { - cold_path(); - return Err(Error::Other(format!("Export is not a function: {name}"))); + return cold!(Err(Error::Other(format!("Export is not a function: {name}")))); }; let func = Function { item: StoreItem::new(self.0.store_id, func_addr), module_id: self.id() }; @@ -464,8 +460,7 @@ impl ModuleInstance { match self.require_export(name)? { ExternVal::Memory(mem_addr) => Ok(Memory(StoreItem::new(self.0.store_id, mem_addr))), _ => { - cold_path(); - Err(Error::Other(format!("Export is not a memory: {name}"))) + cold!(Err(Error::Other(format!("Export is not a memory: {name}")))) } } } diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 051b12f..585819e 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -67,12 +67,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec(&mut self, instr_ptr: usize) -> Result> { macro_rules! exec_op { - (branch $target:expr, $condition:expr) => {{ - if $condition { - self.cf.instr_ptr = *$target as usize; - return Ok(None); - } - }}; (binary_fallible $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ let $rhs = <$ty>::stack_pop(&mut self.store.value_stack); let $lhs = <$ty>::stack_pop(&mut self.store.value_stack); @@ -185,6 +179,24 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let stack_val = <$vt>::stack_pop(&mut self.store.value_stack); self.store.value_stack.push($exec(*$op, stack_val, global_val))?; }}; + (binop_stack_local $vt:ty, $exec:ident, $op:ident, $local:ident) => {{ + let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); + let lhs = <$vt>::stack_pop(&mut self.store.value_stack); + <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?; + }}; + (binop_stack_local_set $vt:ty, $exec:ident, $op:ident, $local:ident, $dst:ident) => {{ + let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); + let lhs = <$vt>::stack_pop(&mut self.store.value_stack); + let value = $exec(*$op, lhs, rhs); + <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); + }}; + (binop_stack_local_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $dst:ident) => {{ + let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); + let lhs = <$vt>::stack_pop(&mut self.store.value_stack); + let value = $exec(*$op, lhs, rhs); + <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); + <$vt>::stack_push(&mut self.store.value_stack, value)?; + }}; (binop_acc_local $ty:ty, $acc:ident, $mul:expr, $add:expr) => {{ let rhs = <$ty>::stack_pop(&mut self.store.value_stack); let lhs = <$ty>::stack_pop(&mut self.store.value_stack); @@ -215,115 +227,83 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } ThrowRef => { self.exec_throw_ref()?; return Ok(None); } Jump(ip) => { self.cf.instr_ptr = *ip as usize; return Ok(None); } - JumpIfZero32(ip) => exec_op!(branch ip, i32::stack_pop(&mut self.store.value_stack) == 0), - JumpIfNonZero32(ip) => exec_op!(branch ip, i32::stack_pop(&mut self.store.value_stack) != 0), - JumpIfZero64(ip) => exec_op!(branch ip, i64::stack_pop(&mut self.store.value_stack) == 0), - JumpIfNonZero64(ip) => exec_op!(branch ip, i64::stack_pop(&mut self.store.value_stack) != 0), - JumpIfRefNull(ip) => { + JumpIfZero32(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| i32::stack_pop(&mut self.store.value_stack) == 0) { return Ok(None) }, + JumpIfNonZero32(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| i32::stack_pop(&mut self.store.value_stack) != 0) { return Ok(None) }, + JumpIfZero64(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| i64::stack_pop(&mut self.store.value_stack) == 0) { return Ok(None) }, + JumpIfNonZero64(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| i64::stack_pop(&mut self.store.value_stack) != 0) { return Ok(None) }, + JumpIfRefNull(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| { let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); - if is_null { - ValueRef::stack_pop(&mut self.store.value_stack); - } - exec_op!(branch ip, is_null); - }, - JumpIfRefNonNull(ip) => { + if is_null { ValueRef::stack_pop(&mut self.store.value_stack); } + is_null + }) { return Ok(None) }, + JumpIfRefNonNull(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| { let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null(); - if !is_non_null { - ValueRef::stack_pop(&mut self.store.value_stack); - } - exec_op!(branch ip, is_non_null); - }, + if !is_non_null { ValueRef::stack_pop(&mut self.store.value_stack); } + is_non_null + }) { return Ok(None) }, BrOnCast(ip, ty, on_fail) => if self.exec_ref_matches(*ty) == *on_fail { self.cf.instr_ptr = *ip as usize; return Ok(None); }, - JumpIfLocalZero32 { target_ip, local } => exec_op!(branch target_ip, Value32::local_get(&self.store.value_stack, &self.cf, *local) == 0), - JumpIfLocalNonZero32 { target_ip, local } => exec_op!(branch target_ip, Value32::local_get(&self.store.value_stack, &self.cf, *local) != 0), - JumpIfLocalZero64 { target_ip, local } => exec_op!(branch target_ip, Value64::local_get(&self.store.value_stack, &self.cf, *local) == 0), - JumpIfLocalNonZero64 { target_ip, local } => exec_op!(branch target_ip, Value64::local_get(&self.store.value_stack, &self.cf, *local) != 0), - JumpCmpStackConst32 { target_ip, imm, op } => { - let lhs = i32::stack_pop(&mut self.store.value_stack); - exec_op!(branch target_ip, cmp_i32(lhs, *imm, *op)); - }, - JumpCmpStackConst64 { target_ip, imm, op } => { - let lhs = i64::stack_pop(&mut self.store.value_stack); - exec_op!(branch target_ip, cmp_i64(lhs, *imm, *op)); - }, - JumpCmpStackLocal32 { target_ip, local, op } => { + JumpIfLocalZero32 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, *local) == 0) { return Ok(None) }, + JumpIfLocalNonZero32 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, *local) != 0) { return Ok(None) }, + JumpIfLocalZero64 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, *local) == 0) { return Ok(None) }, + JumpIfLocalNonZero64 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, *local) != 0) { return Ok(None) }, + JumpCmpStackConst32 { target_ip, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), *imm, *op)) { return Ok(None) }, + JumpCmpStackConst64 { target_ip, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), *imm, *op)) { return Ok(None) }, + JumpCmpStackLocal32 { target_ip, local, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { let lhs = i32::stack_pop(&mut self.store.value_stack); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, *local); - exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); - }, - JumpCmpStackLocal64 { target_ip, local, op } => { + cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *local), *op) + }) { return Ok(None) }, + JumpCmpStackLocal64 { target_ip, local, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { let lhs = i64::stack_pop(&mut self.store.value_stack); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, *local); - exec_op!(branch target_ip, cmp_i64(lhs, rhs, *op)); - }, - BinOpLocalConstJump32 { target_ip, local, imm, op, on_zero } => { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); - let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); - exec_op!(branch target_ip, (value == 0) == *on_zero); - }, - BinOpLocalConstJumpCmpLocal32 { target_ip, local, imm, binop, right, cmp } => { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); - let lhs = exec_binop_32(*binop, lhs as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, &self.cf, *local, lhs); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); - exec_op!(branch target_ip, cmp_i32(lhs, rhs, *cmp)); - }, + cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, *local), *op) + }) { return Ok(None) }, + BinOpLocalConstJump32 { target_ip, local, imm, op, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + let value = exec_binop_32(*op, i32::local_get(&self.store.value_stack, cf, *local) as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, cf, *local, value); + (value == 0) == *on_zero + }) { return Ok(None) }, + BinOpLocalConstJumpCmpLocal32 { target_ip, local, imm, binop, right, cmp } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + let lhs = exec_binop_32(*binop, i32::local_get(&self.store.value_stack, cf, *local) as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, cf, *local, lhs); + cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *right), *cmp) + }) { return Ok(None) }, BinOpStackConstTeeLocalJump32 { target_ip, local, imm, op, on_zero } => { - let lhs = i32::stack_pop(&mut self.store.value_stack); - let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + let value = exec_binop_32(*op, i32::stack_pop(&mut self.store.value_stack) as u32, *imm as u32) as i32; i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); i32::stack_push(&mut self.store.value_stack, value)?; - exec_op!(branch target_ip, (value == 0) == *on_zero); + if Self::exec_jump_if(&mut self.cf, *target_ip, |_| (value == 0) == *on_zero) { return Ok(None) } }, - BinOpGlobalConstJump32 { target_ip, global, imm, op, on_zero } => { + BinOpGlobalConstJump32 { target_ip, global, imm, op, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| { let global = self.module.resolve_global_addr(*global); - let lhs = i32::global_get(&self.store.state.globals, global); - let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + let value = exec_binop_32(*op, i32::global_get(&self.store.state.globals, global) as u32, *imm as u32) as i32; i32::global_set(&mut self.store.state.globals, global, value); - exec_op!(branch target_ip, (value == 0) == *on_zero); - }, - IncLocalJump32 { target_ip, local, delta, on_zero } => { - let value = i32::local_get(&self.store.value_stack, &self.cf, *local).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); - exec_op!(branch target_ip, (value == 0) == *on_zero); - }, + (value == 0) == *on_zero + }) { return Ok(None) }, + IncLocalJump32 { target_ip, local, delta, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + let value = i32::local_get(&self.store.value_stack, cf, *local).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, cf, *local, value); + (value == 0) == *on_zero + }) { return Ok(None) }, IncStackTeeLocalJump32 { target_ip, local, delta, on_zero } => { let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(*delta); i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); i32::stack_push(&mut self.store.value_stack, value)?; - exec_op!(branch target_ip, (value == 0) == *on_zero); + if Self::exec_jump_if(&mut self.cf, *target_ip, |_| (value == 0) == *on_zero) { return Ok(None) } }, - IncGlobalJump32 { target_ip, global, delta, on_zero } => { + IncGlobalJump32 { target_ip, global, delta, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| { let global = self.module.resolve_global_addr(*global); let value = i32::global_get(&self.store.state.globals, global).wrapping_add(*delta); i32::global_set(&mut self.store.state.globals, global, value); - exec_op!(branch target_ip, (value == 0) == *on_zero); - }, - IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, &self.cf, *local, lhs); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); - exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); - }, - JumpCmpLocalConst32 { target_ip, local, imm, op } => { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); - exec_op!(branch target_ip, cmp_i32(lhs, *imm, *op)); - }, - JumpCmpLocalConst64 { target_ip, local, imm, op } => { - let lhs = i64::local_get(&self.store.value_stack, &self.cf, *local); - exec_op!(branch target_ip, cmp_i64(lhs, i64::from(*imm), *op)); - }, - JumpCmpLocalLocal32 { target_ip, left, right, op } => { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, *left); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); - exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); - }, - JumpCmpLocalLocal64 { target_ip, left, right, op } => { - let lhs = i64::local_get(&self.store.value_stack, &self.cf, *left); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, *right); - exec_op!(branch target_ip, cmp_i64(lhs, rhs, *op)); - }, + (value == 0) == *on_zero + }) { return Ok(None) }, + IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + let lhs = i32::local_get(&self.store.value_stack, cf, *local).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, cf, *local, lhs); + cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *right), *op) + }) { return Ok(None) }, + JumpCmpLocalConst32 { target_ip, local, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, *local), *imm, *op)) { return Ok(None) }, + JumpCmpLocalConst64 { target_ip, local, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, *local), i64::from(*imm), *op)) { return Ok(None) }, + JumpCmpLocalLocal32 { target_ip, left, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, *left), i32::local_get(&self.store.value_stack, cf, *right), *op)) { return Ok(None) }, + JumpCmpLocalLocal64 { target_ip, left, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, *left), i64::local_get(&self.store.value_stack, cf, *right), *op)) { return Ok(None) }, DropKeep(drop_keep) => self.exec_drop_keep(*drop_keep), BranchTable(default_ip, start, len) => { self.exec_branch_table(*default_ip, *start, *len); return Ok(None); } Return => { if self.exec_return() { return Ok(Some(())); } return Ok(None); } @@ -375,6 +355,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { BinOpLocalConstTee128(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index), BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index), + BinOpStackLocal32(op, local) => exec_op!(binop_stack_local Value32, exec_binop_32, op, local), + BinOpStackLocalSet32(op, local, dst) => exec_op!(binop_stack_local_set Value32, exec_binop_32, op, local, dst), + BinOpStackLocalTee32(op, local, dst) => exec_op!(binop_stack_local_tee Value32, exec_binop_32, op, local, dst), SetLocalConst32(local_index, c) => i32::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), SetLocalConst64(local_index, c) => i64::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), SetLocalConst128(local_index, c) => Value128::local_set(&mut self.store.value_stack, &self.cf, *local_index, Value128(self.func.data.v128_const(*c))), @@ -383,24 +366,24 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { StoreLocalLocal32(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, StoreLocalLocal64(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, StoreLocalLocal128(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - LoadLocal32(m, addr_local) => self.exec_load_local::(*m, *addr_local, |v| v)?, - LoadLocal64(m, addr_local) => self.exec_load_local::(*m, *addr_local, |v| v)?, - LoadLocal8S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, - LoadLocal8U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, - LoadLocal16S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, - LoadLocal16U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, - LoadLocalTee32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalSet32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalTee8S32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee8U32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee16S32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee16U32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet8S32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet8U32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet16S32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, |v| v)?, + LoadLocal32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, |v| v)?, + LoadLocal64(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, |v| v)?, + LoadLocal8S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, + LoadLocal8U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, + LoadLocal16S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, + LoadLocal16U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, + LoadLocalTee32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, + LoadLocalSet32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, + LoadLocalTee8S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalTee8U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalTee16S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalTee16U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalSet8S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalSet8U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalSet16S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, + LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, AndConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v & *c); exec_op!(local_tee i32, local_index); } SubConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(*c)); exec_op!(local_tee i32, local_index); } AndConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v & *c); exec_op!(local_tee i64, local_index); } @@ -921,6 +904,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(None) } + #[inline(always)] + fn exec_jump_if(cf: &mut CallFrame, target_ip: u32, condition: impl FnOnce(&CallFrame) -> bool) -> bool { + let condition = condition(cf); + if condition { + cf.instr_ptr = target_ip as usize; + } + condition + } + fn exec_branch_table(&mut self, default_ip: u32, start: u32, len: u32) { let idx = ::stack_pop(&mut self.store.value_stack); let target_ip = if idx >= 0 && (idx as u32) < len { @@ -943,28 +935,23 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn create_exception(&mut self, tag_index: TagAddr) -> Result { let tag_addr = self.module.resolve_tag_addr(tag_index); let type_addr = self.store.state.get_tag(tag_addr).type_addr; - let addr = u32::try_from(self.store.state.exceptions.len()).map_err(|_| Trap::OutOfMemory)?; - self.store.state.exceptions.try_reserve(1).map_err(|_| Trap::OutOfMemory)?; + let addr = cold_err!(u32::try_from(self.store.state.exceptions.len())).map_err(|_| Trap::OutOfMemory)?; + cold_err!(self.store.state.exceptions.try_reserve(1)).map_err(|_| Trap::OutOfMemory)?; let params = self.store.state.get_canonical_func_type(type_addr).params(); let mut payload = Vec::new(); - payload.try_reserve_exact(params.len()).map_err(|_| Trap::OutOfMemory)?; + cold_err!(payload.try_reserve_exact(params.len())).map_err(|_| Trap::OutOfMemory)?; + let value_stack = &mut self.store.value_stack; for &ty in params.iter().rev() { payload.push(match ty { - WasmType::I32 | WasmType::F32 => { - TinyWasmValue::Value32(Value32::stack_pop(&mut self.store.value_stack)) - } - WasmType::I64 | WasmType::F64 => { - TinyWasmValue::Value64(Value64::stack_pop(&mut self.store.value_stack)) - } - WasmType::V128 => TinyWasmValue::Value128(Value128::stack_pop(&mut self.store.value_stack)), - WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(&mut self.store.value_stack)), + WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(Value32::stack_pop(value_stack)), + WasmType::I64 | WasmType::F64 => TinyWasmValue::Value64(Value64::stack_pop(value_stack)), + WasmType::V128 => TinyWasmValue::Value128(Value128::stack_pop(value_stack)), + WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(value_stack)), }); } payload.reverse(); - self.store - .state - .exceptions - .push(crate::store::ExceptionInstance { tag_addr, payload: payload.into_boxed_slice() }); + let exception = crate::store::ExceptionInstance { tag_addr, payload: payload.into_boxed_slice() }; + self.store.state.exceptions.push(exception); Ok(addr) } @@ -1076,8 +1063,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals) else { - cold_path(); - return Err(Trap::CallStackOverflow); + return cold!(Err(Trap::CallStackOverflow)); }; self.store.call_stack.push(self.cf)?; @@ -1101,8 +1087,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.value_stack.truncate_keep_counts(self.cf.locals_base, wasm_func.func.params); let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals) else { - cold_path(); - return Err(Trap::CallStackOverflow); + return cold!(Err(Trap::CallStackOverflow)); }; self.cf = CallFrame::new(func_addr, locals_base, wasm_func.func.locals); if wasm_func.owner != self.module.id() { @@ -1123,10 +1108,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { params_may_gc: bool, ) -> Result { if let Some(host_func) = host_func.typed_callback() { - if let Err(error) = host_func.call_stack(self.store, self.module.id(), type_addr) { - cold_path(); - return Err(Trap::HostFunction(Box::new(error))); - } + 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()); } @@ -1135,8 +1118,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } let param_types = self.store.state.get_canonical_func_type(type_addr).params(); - let mut params = Vec::new(); - params.try_reserve_exact(param_types.len()).map_err(|_| Trap::OutOfMemory)?; + let mut params = core::mem::take(&mut self.store.host_params); + debug_assert!(params.is_empty()); + cold_err!(params.try_reserve_exact(param_types.len())).map_err(|_| Trap::OutOfMemory)?; for &ty in param_types.iter().rev() { params.push(self.store.value_stack.pop_wasmvalue(&self.store.state, ty)); } @@ -1144,13 +1128,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if params_may_gc { self.store.state.pin_host_values(¶ms); } - let res = match host_func.call_values(self.store, self.module.id(), type_addr, ¶ms) { - Ok(res) => res, - Err(err) => { - cold_path(); - return Err(Trap::HostFunction(Box::new(err))); - } - }; + let result = host_func.call_values(self.store, self.module.id(), type_addr, ¶ms); + params.clear(); + self.store.host_params = params; + let res = cold_err!(result).map_err(|error| Trap::HostFunction(Box::new(error)))?; self.store.value_stack.extend_from_wasmvalues(&res)?; if TAIL { @@ -1192,8 +1173,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_call_self(&mut self) -> Result<(), Trap> { 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 { - cold_path(); - return Err(Trap::CallStackOverflow); + return cold!(Err(Trap::CallStackOverflow)); }; 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))?; @@ -1206,8 +1186,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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 { - cold_path(); - return Err(Trap::CallStackOverflow); + return cold!(Err(Trap::CallStackOverflow)); }; self.cf = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); Ok(()) @@ -1226,13 +1205,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table = self.store.state.get_table(table_addr); let Ok(table) = table.get(table_idx) else { - cold_path(); - return Err(Trap::UndefinedElement { index: table_idx }); + return cold!(Err(Trap::UndefinedElement { index: table_idx })); }; let Some(func_ref) = table.addr() else { - cold_path(); - return Err(Trap::UninitializedElement { index: table_idx }); + return cold!(Err(Trap::UninitializedElement { index: table_idx })); }; self.exec_typed_call::(func_ref, self.module.resolve_type_addr(type_addr)) @@ -1245,11 +1222,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ) -> Result { let func = self.store.state.get_func(func_addr).clone(); if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) { - cold_path(); - return Err(Trap::IndirectCallTypeMismatch { + return cold!(Err(Trap::IndirectCallTypeMismatch { actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()), expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), - }); + })); } match func.kind { crate::store::FunctionKind::Wasm(wasm_func) => match IS_RETURN_CALL { @@ -1267,8 +1243,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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 { - cold_path(); - return Err(Trap::NullFunctionReference); + return cold!(Err(Trap::NullFunctionReference)); }; self.exec_typed_call::(func_addr, self.module.resolve_type_addr(type_addr)) @@ -1284,7 +1259,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { return true; }; - self.switch_to_frame(caller); + if caller.func_addr == self.cf.func_addr { + self.cf = caller; + } else { + self.switch_to_frame(caller); + } false } @@ -1391,32 +1370,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } #[inline(always)] - fn exec_load_local, const N: usize, TARGET: InternalValue>( - &mut self, - memarg: MemoryArg, - addr_local: u8, - cast: impl Fn(LOAD) -> TARGET, - ) -> Result<(), Trap> { - let value = cast(self.exec_load_local_value::(memarg, addr_local)?); - TARGET::stack_push(&mut self.store.value_stack, value) - } - - #[inline(always)] - fn exec_load_local_tee, const N: usize, TARGET: InternalValue>( - &mut self, - memarg: MemoryArg, - addr_local: u8, - dst_local: u8, - cast: impl Fn(LOAD) -> TARGET, - ) -> Result<(), Trap> { - let value = cast(self.exec_load_local_value::(memarg, addr_local)?); - TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value); - self.store.value_stack.push(value)?; - Ok(()) - } - - #[inline(always)] - fn exec_load_local_set, const N: usize, TARGET: InternalValue>( + fn exec_load_local< + LOAD: MemValue, + const N: usize, + TARGET: InternalValue, + const SET_LOCAL: bool, + const TEE: bool, + >( &mut self, memarg: MemoryArg, addr_local: u8, @@ -1424,7 +1384,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { let value = cast(self.exec_load_local_value::(memarg, addr_local)?); - TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value); + 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(()) } @@ -1435,8 +1400,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_ref_as_non_null(&mut self) -> Result<(), Trap> { if ValueRef::stack_peek(&self.store.value_stack).is_null() { - cold_path(); - return Err(Trap::NullReference); + return cold!(Err(Trap::NullReference)); } Ok(()) } @@ -1459,8 +1423,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_ref_cast(&self, ty: RefType) -> Result<(), Trap> { if !self.exec_ref_matches(ty) { - cold_path(); - return Err(Trap::CastFailure); + return cold!(Err(Trap::CastFailure)); } Ok(()) } @@ -1468,8 +1431,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_i31_get(&mut self, signed: bool) -> Result<(), Trap> { let value = ValueRef::stack_pop(&mut self.store.value_stack); if value.is_null() { - cold_path(); - return Err(Trap::NullI31Reference); + return cold!(Err(Trap::NullI31Reference)); } let value = if signed { value.i31_s().expect("validated i31.get operand") @@ -1479,11 +1441,17 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.value_stack.push(value) } + fn push_gc_object(&mut self, type_addr: TypeAddr, values: Vec) -> Result<(), Trap> { + let roots = (&self.store.value_stack.stack_32).into_iter().copied(); + let reference = self.store.state.alloc_gc_object(type_addr, values, roots)?; + self.store.value_stack.push(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 fields = &self.store.state.get_type(type_addr).as_struct().expect("validated struct.new type").fields; let mut values = Vec::new(); - values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(fields.len())).map_err(|_| Trap::OutOfMemory)?; if default { values.extend(fields.iter().map(|field| default_value(field.storage))); } else { @@ -1492,12 +1460,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } values.reverse(); } - let value = self.store.state.alloc_gc_object( - type_addr, - values, - (&self.store.value_stack.stack_32).into_iter().copied(), - )?; - self.store.value_stack.push(value) + self.push_gc_object(type_addr, values) } fn exec_struct_get(&mut self, type_index: TypeAddr, field_index: u32, signed: Option) -> Result<(), Trap> { @@ -1529,14 +1492,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let len = u32::stack_pop(&mut self.store.value_stack) as usize; let value = if default { default_value(storage) } else { pop_value(&mut self.store.value_stack, storage) }; let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; values.resize(len, value); - let reference = self.store.state.alloc_gc_object( - type_addr, - values, - (&self.store.value_stack.stack_32).into_iter().copied(), - )?; - self.store.value_stack.push(reference) + self.push_gc_object(type_addr, values) } fn exec_array_new_fixed(&mut self, type_index: TypeAddr, len: u32) -> Result<(), Trap> { @@ -1545,17 +1503,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; let len = len as usize; let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + 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(); - let reference = self.store.state.alloc_gc_object( - type_addr, - values, - (&self.store.value_stack.stack_32).into_iter().copied(), - )?; - self.store.value_stack.push(reference) + self.push_gc_object(type_addr, values) } fn exec_array_get(&mut self, type_index: TypeAddr, signed: Option) -> Result<(), Trap> { @@ -1574,12 +1527,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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)?; - if index >= object.values.len() { - return Err(Trap::ArrayOutOfBounds); - } - self.store.state.gc.set(reference, index, value).expect("live array element"); - Ok(()) + self.store.state.gc_object(reference, type_addr)?; + self.store.state.gc.set(reference, index, value).ok_or(Trap::ArrayOutOfBounds) } fn exec_array_len(&mut self) -> Result<(), Trap> { @@ -1636,34 +1585,19 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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(&[]); let values = decode_data(storage, data, src, len)?; - let reference = self.store.state.alloc_gc_object( - type_addr, - values, - (&self.store.value_stack.stack_32).into_iter().copied(), - )?; - self.store.value_stack.push(reference) + self.push_gc_object(type_addr, values) } fn exec_array_new_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> { 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 elem_addr = self.module.resolve_elem_addr(elem_index); - let items = self.store.state.elements[elem_addr as usize].items.as_deref().unwrap_or(&[]); - let end = src.checked_add(len).filter(|end| *end <= items.len()).ok_or_else(|| Trap::TableOutOfBounds { - offset: src, - len, - max: items.len(), - })?; + let items = self.store.state.elements[elem_addr as usize].items_range(src, len)?; let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; - values.extend(items[src..end].iter().copied().map(TinyWasmValue::ValueRef)); + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; + values.extend(items.iter().copied().map(TinyWasmValue::ValueRef)); let type_addr = self.module.resolve_type_addr(type_index); - let reference = self.store.state.alloc_gc_object( - type_addr, - values, - (&self.store.value_stack.stack_32).into_iter().copied(), - )?; - self.store.value_stack.push(reference) + self.push_gc_object(type_addr, values) } fn exec_array_init_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> { @@ -1690,18 +1624,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let type_addr = self.module.resolve_type_addr(type_index); let object_len = self.store.state.gc_object(reference, type_addr)?.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 - .as_deref() - .unwrap_or(&[]); - let end = src.checked_add(len).filter(|end| *end <= items.len()).ok_or_else(|| Trap::TableOutOfBounds { - offset: src, - len, - max: items.len(), - })?; + let items = + self.store.state.elements[self.module.resolve_elem_addr(elem_index) as usize].items_range(src, len)?; let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; - values.extend(items[src..end].iter().copied().map(TinyWasmValue::ValueRef)); + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; + values.extend(items.iter().copied().map(TinyWasmValue::ValueRef)); self.store.state.gc.set_slice(reference, dst, &values).expect("live array range"); Ok(()) } @@ -1764,13 +1691,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_memory_fill_impl(&mut self, addr: u32, dst: i32, val: u8, size: i32) -> Result<(), Trap> { let mem = self.store.state.get_mem_mut(self.module.resolve_mem_addr(addr)); + let max = mem.inner.len(); if mem.inner.fill(dst as usize, size as usize, val).is_none() { - cold_path(); - return Err(Trap::MemoryOutOfBounds { - offset: dst as usize, - len: size as usize, - max: self.store.state.get_mem(self.module.resolve_mem_addr(addr)).inner.len(), - }); + return cold!(Err(Trap::MemoryOutOfBounds { offset: dst as usize, len: size as usize, max })); } Ok(()) } @@ -1783,9 +1706,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let data = &self.store.state.data[self.module.resolve_data_addr(data_index) as usize]; let mem = &mut self.store.state.memories[self.module.resolve_mem_addr(mem_index) as usize]; let data_len = data.data.as_ref().map_or(0, |d| d.len()); - if ((size + offset) as usize > data_len) || ((dst + size) as usize > mem.inner.len()) { - cold_path(); - return Err(Trap::MemoryOutOfBounds { offset: offset as usize, len: size as usize, max: data_len }); + let mem_len = mem.inner.len(); + if ((size + offset) as usize > data_len) || ((dst + size) as usize > mem_len) { + return cold!(Err(Trap::MemoryOutOfBounds { offset: offset as usize, len: size as usize, max: data_len })); } if size == 0 { @@ -1793,13 +1716,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } let Some(data) = &data.data else { - cold_path(); - return Err(Trap::MemoryOutOfBounds { offset: 0, len: 0, max: 0 }); + return cold!(Err(Trap::MemoryOutOfBounds { offset: 0, len: 0, max: 0 })); }; if mem.inner.write_all(dst as usize, &data[offset as usize..((offset + size) as usize)]).is_none() { - cold_path(); - return Err(Trap::MemoryOutOfBounds { offset: dst as usize, len: size as usize, max: mem.inner.len() }); + return cold!(Err(Trap::MemoryOutOfBounds { offset: dst as usize, len: size as usize, max: mem_len })); } Ok(()) } @@ -1850,17 +1771,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ) -> Result<(), Trap> { let mem = self.store.state.get_mem(self.module.resolve_mem_addr(mem_addr)); let addr = Self::pop_memory_addr::(&mut self.store.value_stack, mem, offset)?; - - match LOAD::load_at(&*mem.inner, addr) { - Ok(val) => { - self.store.value_stack.push(cast(val))?; - Ok(()) - } - Err(e) => { - cold_path(); - Err(e) - } - } + let value = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + self.store.value_stack.push(cast(value)) } fn exec_mem_store_lane + Copy, const N: usize>( @@ -1877,13 +1789,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let mem_addr = self.module.resolve_mem_addr(mem_addr); let mem = self.store.state.get_mem_mut(mem_addr); let addr = Self::pop_memory_addr::(&mut self.store.value_stack, mem, offset)?; - match val.store_at(&mut *mem.inner, addr) { - Ok(()) => Ok(()), - Err(e) => { - cold_path(); - Err(e) - } - } + cold_err!(val.store_at(&mut *mem.inner, addr))?; + Ok(()) } fn exec_mem_store, const N: usize>( @@ -1898,13 +1805,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let mem_addr = self.module.resolve_mem_addr(mem_addr); let mem = self.store.state.get_mem_mut(mem_addr); let addr = Self::pop_memory_addr::(&mut self.store.value_stack, mem, offset)?; - match val.store_at(&mut *mem.inner, addr) { - Ok(()) => Ok(()), - Err(e) => { - cold_path(); - Err(e) - } - } + cold_err!(val.store_at(&mut *mem.inner, addr))?; + Ok(()) } fn exec_table_get(&mut self, table_index: u32) -> Result<(), Trap> { @@ -1937,19 +1839,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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.as_deref().unwrap_or(&[]); - let Some(end) = offset.checked_add(size) else { - cold_path(); - return Err(Trap::TableOutOfBounds { offset, len: size, max: items.len() }); - }; - if end > items.len() { - cold_path(); - return Err(Trap::TableOutOfBounds { offset, len: size, max: items.len() }); - } + 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[offset..end]) + table.init(dst, items) } fn exec_table_grow(&mut self, table_index: u32) -> Result<(), Trap> { diff --git a/crates/tinywasm/src/interpreter/stack/call_stack.rs b/crates/tinywasm/src/interpreter/stack/call_stack.rs index 62f1f8e..f4e2595 100644 --- a/crates/tinywasm/src/interpreter/stack/call_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/call_stack.rs @@ -1,5 +1,4 @@ use crate::{Result, Trap}; -use core::hint::cold_path; use alloc::vec::Vec; use tinywasm_types::{FuncAddr, ValueCounts}; @@ -51,14 +50,12 @@ impl CallStack { } if required_len > self.max_size || !self.dynamic { - cold_path(); - return Err(Trap::CallStackOverflow); + return cold!(Err(Trap::CallStackOverflow)); } let target_capacity = required_len.max(self.stack.capacity().max(1).saturating_mul(2)).min(self.max_size); let Ok(()) = self.stack.try_reserve(target_capacity.saturating_sub(self.stack.len())) else { - cold_path(); - return Err(Trap::CallStackOverflow); + return cold!(Err(Trap::CallStackOverflow)); }; Ok(()) } diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index ceea9eb..0b37f51 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -102,8 +102,7 @@ impl Stack { #[inline(always)] pub(crate) fn push(&mut self, value: T) -> Result<(), Trap> { if !self.ensure_capacity_for(self.data.len() + 1) { - cold_path(); - return Err(Trap::ValueStackOverflow); + return cold!(Err(Trap::ValueStackOverflow)); } self.data.push(value); diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index cc91a55..e2cbef0 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -168,10 +168,7 @@ macro_rules! impl_internalvalue { #[inline(always)] fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap> { let $to_stack_v = value; - if let Err(e) = stack.$stack.push($to_stack) { - core::hint::cold_path(); - return Err(e); - } + cold_err!(stack.$stack.push($to_stack))?; Ok(()) } diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index e6c9ab8..e941430 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -83,6 +83,8 @@ //! //! See the [`Imports`] documentation for more information. +#[macro_use] +mod macros; mod std; extern crate alloc; diff --git a/crates/tinywasm/src/macros.rs b/crates/tinywasm/src/macros.rs new file mode 100644 index 0000000..351ae88 --- /dev/null +++ b/crates/tinywasm/src/macros.rs @@ -0,0 +1,18 @@ +macro_rules! cold { + ($value:expr) => {{ + core::hint::cold_path(); + $value + }}; +} + +// Mark the caller's error path cold. This makes a significant difference in interpreter benchmarks, +// while doing it inside map_err or inspect_err is unreliable: +// https://internals.rust-lang.org/t/err-automatic-hint-cold-path/24404 +macro_rules! cold_err { + ($result:expr) => { + match $result { + Ok(value) => Ok(value), + Err(error) => cold!(Err(error)), + } + }; +} diff --git a/crates/tinywasm/src/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs index c371763..2c847a7 100644 --- a/crates/tinywasm/src/store/const_expr.rs +++ b/crates/tinywasm/src/store/const_expr.rs @@ -1,5 +1,4 @@ use alloc::{format, vec::Vec}; -use core::hint::cold_path; use tinywasm_types::*; use super::{State, default_value}; @@ -108,8 +107,7 @@ pub(super) fn eval_const( stack.push(TinyWasmValue::ValueRef(ValueRef::from_category_addr(addr))); } Ref(_) => { - cold_path(); - return Err(Error::other("unsupported reference constant")); + return cold!(Err(Error::other("unsupported reference constant"))); } RefI31 => { let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; @@ -135,7 +133,7 @@ pub(super) fn eval_const( .as_ref(); let default = matches!(instruction, StructNewDefault(_)); let mut values = Vec::new(); - values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(fields.len())).map_err(|_| Trap::OutOfMemory)?; if default { values.extend(fields.iter().map(|field| default_value(field.storage))); } else { @@ -163,7 +161,7 @@ pub(super) fn eval_const( pop_value(&mut stack, storage)? }; let mut values = Vec::new(); - values.try_reserve_exact(len as usize).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(len as usize)).map_err(|_| Trap::OutOfMemory)?; values.resize(len as usize, value); alloc_object(state, &mut stack, type_addr, values)?; } @@ -176,7 +174,7 @@ pub(super) fn eval_const( .field .storage; let mut values = Vec::new(); - values.try_reserve_exact(*len as usize).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(*len as usize)).map_err(|_| Trap::OutOfMemory)?; for _ in 0..*len { values.push(pop_value(&mut stack, storage)?); } @@ -187,8 +185,7 @@ pub(super) fn eval_const( let rhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; let lhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; let (TinyWasmValue::Value32(lhs), TinyWasmValue::Value32(rhs)) = (lhs, rhs) else { - cold_path(); - return Err(Error::other("type mismatch in const i32 op")); + return cold!(Err(Error::other("type mismatch in const i32 op"))); }; let out = match instruction { I32Add => (lhs as i32).wrapping_add(rhs as i32), @@ -202,8 +199,7 @@ pub(super) fn eval_const( let rhs = stack.pop(); let lhs = stack.pop(); let (Some(TinyWasmValue::Value64(lhs)), Some(TinyWasmValue::Value64(rhs))) = (lhs, rhs) else { - cold_path(); - return Err(Error::other("type mismatch in const i64 op")); + return cold!(Err(Error::other("type mismatch in const i64 op"))); }; let out = match instruction { I64Add => (lhs as i64).wrapping_add(rhs as i64), @@ -217,12 +213,10 @@ pub(super) fn eval_const( } let Some(value) = stack.pop() else { - cold_path(); - return Err(Error::other("empty const expression")); + return cold!(Err(Error::other("empty const expression"))); }; if !stack.is_empty() { - cold_path(); - return Err(Error::other("const expression did not reduce to single value")); + return cold!(Err(Error::other("const expression did not reduce to single value"))); } Ok(value) } diff --git a/crates/tinywasm/src/store/element.rs b/crates/tinywasm/src/store/element.rs index 4437bd4..8119fe8 100644 --- a/crates/tinywasm/src/store/element.rs +++ b/crates/tinywasm/src/store/element.rs @@ -1,4 +1,4 @@ -use crate::interpreter::ValueRef; +use crate::{Trap, interpreter::ValueRef}; use alloc::vec::Vec; use tinywasm_types::RefType; @@ -15,4 +15,13 @@ impl ElementInstance { pub(crate) fn drop(&mut self) { self.items.take(); } + + pub(crate) fn items_range(&self, offset: usize, len: usize) -> Result<&[ValueRef], Trap> { + let items = self.items.as_deref().unwrap_or(&[]); + let end = offset.checked_add(len).filter(|end| *end <= items.len()).ok_or_else(|| { + core::hint::cold_path(); + Trap::TableOutOfBounds { offset, len, max: items.len() } + })?; + Ok(&items[offset..end]) + } } diff --git a/crates/tinywasm/src/store/gc/mod.rs b/crates/tinywasm/src/store/gc/mod.rs index 2a87a5f..6431037 100644 --- a/crates/tinywasm/src/store/gc/mod.rs +++ b/crates/tinywasm/src/store/gc/mod.rs @@ -79,7 +79,7 @@ pub(crate) fn decode_data( return Err(Trap::MemoryOutOfBounds { offset: src, len: len.saturating_mul(width), max: data.len() }); }; let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; values.extend(data[src..end].chunks_exact(width).map(|bytes| match width { 1 => TinyWasmValue::Value32(u32::from(bytes[0])), 2 => TinyWasmValue::Value32(u32::from(u16::from_le_bytes(bytes.try_into().unwrap()))), diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs index be0f3b4..d9c7990 100644 --- a/crates/tinywasm/src/store/memory/instance.rs +++ b/crates/tinywasm/src/store/memory/instance.rs @@ -38,8 +38,7 @@ impl MemoryInstance { match usize::try_from(u64::from(base) + offset) { Ok(addr) => Ok(addr), Err(_) => { - cold_path(); - Err(memory_oob(base as usize, N, self.inner.len())) + cold!(Err(memory_oob(base as usize, N, self.inner.len()))) } } } @@ -50,8 +49,7 @@ impl MemoryInstance { match base.checked_add(offset).and_then(|addr| usize::try_from(addr).ok()) { Some(addr) => Ok(addr), None => { - cold_path(); - Err(memory_oob(base as usize, N, self.inner.len())) + cold!(Err(memory_oob(base as usize, N, self.inner.len()))) } } } @@ -108,13 +106,11 @@ impl MemoryInstance { ) -> Result<(), Trap> { fn check_range(mem: &MemoryStorage, addr: usize, len: usize) -> Result<(), crate::Trap> { let Some(end) = addr.checked_add(len) else { - cold_path(); - return Err(memory_oob(addr, len, mem.len())); + return cold!(Err(memory_oob(addr, len, mem.len()))); }; if end > mem.len() || end < addr { - cold_path(); - return Err(memory_oob(addr, len, mem.len())); + return cold!(Err(memory_oob(addr, len, mem.len()))); } Ok(()) } diff --git a/crates/tinywasm/src/store/memory/lazy.rs b/crates/tinywasm/src/store/memory/lazy.rs index ef6dace..40451bb 100644 --- a/crates/tinywasm/src/store/memory/lazy.rs +++ b/crates/tinywasm/src/store/memory/lazy.rs @@ -1,5 +1,4 @@ use alloc::boxed::Box; -use core::hint::cold_path; use tinywasm_types::MemoryType; @@ -43,8 +42,7 @@ impl LazyLinearMemory { let storage = match self.backend.create(self.ty, self.initial_len) { Ok(storage) => storage, Err(Error::Trap(trap)) => { - cold_path(); - return Err(trap); + return cold!(Err(trap)); } Err(err) => panic!("lazy memory materialization failed: {err}"), }; diff --git a/crates/tinywasm/src/store/memory/mod.rs b/crates/tinywasm/src/store/memory/mod.rs index f25d4ae..739a6a4 100644 --- a/crates/tinywasm/src/store/memory/mod.rs +++ b/crates/tinywasm/src/store/memory/mod.rs @@ -54,21 +54,18 @@ pub trait LinearMemory { /// Writes all bytes in `src` starting at `addr`, or returns `None` if any byte could not be written. fn write_all(&mut self, addr: usize, src: &[u8]) -> Option<()> { let Some(end) = addr.checked_add(src.len()) else { - cold_path(); - return None; + return cold!(None); }; if end > self.len() { - cold_path(); - return None; + return cold!(None); } let mut offset = 0; while offset < src.len() { let written = self.write(addr + offset, &src[offset..]); if written == 0 { - cold_path(); - return None; + return cold!(None); } offset += written; } @@ -134,21 +131,18 @@ pub trait LinearMemory { /// Reads exactly `dst.len()` bytes starting at `addr`. fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> { let Some(end) = addr.checked_add(dst.len()) else { - cold_path(); - return None; + return cold!(None); }; if end > self.len() { - cold_path(); - return None; + return cold!(None); } let mut offset = 0; while offset < dst.len() { let read = self.read(addr + offset, &mut dst[offset..]); if read == 0 { - cold_path(); - return None; + return cold!(None); } offset += read; } @@ -377,13 +371,7 @@ macro_rules! impl_mem_traits { #[inline(always)] fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result { - match mem.$read(addr) { - Ok(bytes) => Ok(Self::from_le_bytes(bytes)), - Err(trap) => { - cold_path(); - Err(trap) - } - } + Ok(Self::from_le_bytes(cold_err!(mem.$read(addr))?)) } #[inline(always)] @@ -418,13 +406,7 @@ impl MemValue<16> for Value128 { #[inline(always)] fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result { - match mem.read_128(addr) { - Ok(bytes) => Ok(Self(bytes)), - Err(trap) => { - cold_path(); - Err(trap) - } - } + Ok(Self(cold_err!(mem.read_128(addr))?)) } #[inline(always)] diff --git a/crates/tinywasm/src/store/memory/paged.rs b/crates/tinywasm/src/store/memory/paged.rs index fc5947c..206014e 100644 --- a/crates/tinywasm/src/store/memory/paged.rs +++ b/crates/tinywasm/src/store/memory/paged.rs @@ -45,13 +45,7 @@ impl PagedMemory { #[inline(always)] fn allocate_chunk(&self) -> Result, crate::Trap> { let mut chunk = Vec::new(); - match chunk.try_reserve_exact(self.chunk_size) { - Ok(()) => {} - Err(_) => { - cold_path(); - return Err(crate::Trap::OutOfMemory); - } - } + cold_err!(chunk.try_reserve_exact(self.chunk_size)).map_err(|_| crate::Trap::OutOfMemory)?; chunk.resize(self.chunk_size, 0); Ok(chunk.into_boxed_slice()) } @@ -135,13 +129,8 @@ impl LinearMemory for PagedMemory { let new_chunk_count = if new_len == 0 { 0 } else { new_len.div_ceil(self.chunk_size) }; if new_chunk_count > self.chunks.len() { - match self.chunks.try_reserve_exact(new_chunk_count - self.chunks.len()) { - Ok(()) => {} - Err(_) => { - cold_path(); - return Err(crate::Trap::OutOfMemory); - } - } + cold_err!(self.chunks.try_reserve_exact(new_chunk_count - self.chunks.len())) + .map_err(|_| crate::Trap::OutOfMemory)?; self.chunks.resize_with(new_chunk_count, || None); } else { self.chunks.truncate(new_chunk_count); diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs index aa468ec..17b1f83 100644 --- a/crates/tinywasm/src/store/memory/vec.rs +++ b/crates/tinywasm/src/store/memory/vec.rs @@ -1,5 +1,4 @@ use alloc::vec::Vec; -use core::hint::cold_path; use super::{LinearMemory, memory_oob}; @@ -21,13 +20,7 @@ impl VecMemory { /// Prefer this backend when contiguous access is more important than grow performance. pub fn try_new(len: usize) -> Result { let mut data = Vec::new(); - match data.try_reserve_exact(len) { - Ok(()) => {} - Err(_) => { - cold_path(); - return Err(crate::Trap::OutOfMemory); - } - } + cold_err!(data.try_reserve_exact(len)).map_err(|_| crate::Trap::OutOfMemory)?; data.resize(len, 0); Ok(Self { data }) } @@ -43,8 +36,7 @@ impl VecMemory { #[inline(always)] fn check_fixed_addr(&self, addr: usize) -> Result<(), crate::Trap> { if N > self.data.len() || addr > self.data.len() - N { - cold_path(); - return Err(memory_oob(addr, N, self.data.len())); + return cold!(Err(memory_oob(addr, N, self.data.len()))); } Ok(()) } @@ -61,13 +53,8 @@ impl LinearMemory for VecMemory { if new_len < self.data.len() { return Err(crate::Trap::MemoryOutOfBounds { offset: new_len, len: 0, max: self.data.len() }); } - match self.data.try_reserve_exact(new_len.saturating_sub(self.data.len())) { - Ok(()) => {} - Err(_) => { - cold_path(); - return Err(crate::Trap::OutOfMemory); - } - } + cold_err!(self.data.try_reserve_exact(new_len.saturating_sub(self.data.len()))) + .map_err(|_| crate::Trap::OutOfMemory)?; self.data.resize(new_len, 0); Ok(()) } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 1aabfb3..46bb727 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -60,6 +60,7 @@ pub struct Store { pub(crate) state: State, pub(crate) call_stack: CallStack, pub(crate) value_stack: ValueStack, + pub(crate) host_params: Vec, } #[cfg(feature = "debug")] @@ -97,6 +98,7 @@ impl Store { state, call_stack: CallStack::new(engine.config()), value_stack: ValueStack::new(engine.config()), + host_params: Vec::new(), engine, execution_fuel: 0, execution_active: false, @@ -266,13 +268,7 @@ impl Store { let start = self.state.memories.len() as MemAddr; self.state.memories.reserve_exact(memories.len()); for mem in memories { - self.state.memories.push(match init(*mem, &self.engine.config().memory_backend) { - Ok(mem) => mem, - Err(e) => { - cold_path(); - return Err(e); - } - }); + self.state.memories.push(cold_err!(init(*mem, &self.engine.config().memory_backend))?); } Ok(start..start + memories.len() as MemAddr) } @@ -287,13 +283,7 @@ impl Store { ) -> Result<()> { self.state.globals.reserve(globals); for global in globals { - let value = match eval_const(&mut self.state, &global.init, out, func_addrs, type_addrs) { - Ok(val) => val, - Err(e) => { - cold_path(); - return Err(e); - } - }; + let value = cold_err!(eval_const(&mut self.state, &global.init, out, func_addrs, type_addrs))?; let ty = global.ty.with_ty(canonicalize_value_type(global.ty.ty, type_addrs)); out.push(self.state.globals.push(ty, value)); } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 6d13579..601bb6a 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -118,9 +118,9 @@ impl State { TinyWasmValue::ValueRef(value) => Some(*value), _ => None, })); - self.gc.collect(roots).map_err(|_| Trap::OutOfMemory)?; + cold_err!(self.gc.collect(roots)).map_err(|_| Trap::OutOfMemory)?; } - self.gc.alloc(type_addr, values, trace_references).map_err(|_| Trap::OutOfMemory) + cold_err!(self.gc.alloc(type_addr, values, trace_references)).map_err(|_| Trap::OutOfMemory) } /// Pins a host-visible reference when it resolves to a managed GC object. diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index 5cbce74..8e6c055 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -17,12 +17,12 @@ pub(crate) struct TableInstance { impl TableInstance { /// Creates a table filled with the given initial reference. pub(crate) fn new(kind: TableType, init: ValueRef) -> Result { - let size = usize::try_from(kind.size_initial).map_err(|_| Trap::OutOfMemory)?; + let size = cold_err!(usize::try_from(kind.size_initial)).map_err(|_| Trap::OutOfMemory)?; if size > MAX_TABLE_SIZE { return Err(Trap::OutOfMemory.into()); } let mut elements = Vec::new(); - elements.try_reserve_exact(size).map_err(|_| Trap::OutOfMemory)?; + cold_err!(elements.try_reserve_exact(size)).map_err(|_| Trap::OutOfMemory)?; elements.resize(size, init); Ok(Self { elements, kind }) } @@ -82,7 +82,7 @@ impl TableInstance { return Err(crate::Trap::TableOutOfBounds { offset: len, len: 1, max: self.elements.len() }); } - self.elements.try_reserve_exact(n).map_err(|_| Trap::OutOfMemory)?; + cold_err!(self.elements.try_reserve_exact(n)).map_err(|_| Trap::OutOfMemory)?; self.elements.resize(len, init); Ok(()) } diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs index ac79f6a..e57309f 100644 --- a/crates/tinywasm/tests/typed_globals.rs +++ b/crates/tinywasm/tests/typed_globals.rs @@ -35,18 +35,18 @@ fn globals_use_typed_instructions_and_roundtrip_values() -> Result<(), Box get32 += 1, - Instruction::GlobalGet64(_) => get64 += 1, - Instruction::GlobalGet128(_) => get128 += 1, + Instruction::GlobalTee32(_) => tee32 += 1, + Instruction::GlobalTee64(_) => tee64 += 1, + Instruction::GlobalTee128(_) => tee128 += 1, Instruction::BinOpStackGlobal32(..) => fused32 += 1, Instruction::BinOpStackGlobal64(..) => fused64 += 1, _ => {} } } - assert_eq!((get32, get64, get128), (3, 2, 1)); + assert_eq!((tee32, tee64, tee128), (3, 2, 1)); assert_eq!((fused32, fused64), (1, 1)); let mut store = Store::default(); diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index a505aed..a43c82c 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -203,6 +203,9 @@ pub enum Instruction { BinOpLocalConstTee32(BinOp, LocalAddr, i32, LocalAddr), BinOpLocalConstTee64(BinOp, LocalAddr, i64, LocalAddr), BinOpLocalConstTee128(BinOp128, LocalAddr, ConstIdx, LocalAddr), + BinOpStackLocal32(BinOp, LocalAddr), + BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr), + BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr), BinOpStackGlobal32(BinOp, u32), BinOpStackGlobal64(BinOp, u32), SetLocalConst32(LocalAddr, i32), SetLocalConst64(LocalAddr, i64), SetLocalConst128(LocalAddr, ConstIdx), -- cgit v1.3.1 From 358a183e5c12c32b8836acf9c71799f56e00b036 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Mon, 17 Aug 2026 20:07:51 +0200 Subject: chore: reduce instruction enum size (#52) this is a fairly big commit since I've been just playing around with this for a while now. the main goal is to reduce instruction size by moving some operands into two separate vecs. memory operations still seem like the biggest issue right now, so as a follow op I'll probably remove the public linear memory trait again but let's see how this goes first. performance wise this is about the same as before, but serialization/deserialization is about 20% faster now. Signed-off-by: Henry --------- Signed-off-by: Henry --- CHANGELOG.md | 1 + Cargo.lock | 8 +- crates/parser/src/conversion.rs | 33 +- crates/parser/src/lib.rs | 16 + crates/parser/src/macros.rs | 155 +-- crates/parser/src/module.rs | 42 +- crates/parser/src/optimize.rs | 1201 ----------------- crates/parser/src/optimize/mod.rs | 4 + crates/parser/src/optimize/rewrite.rs | 1397 ++++++++++++++++++++ crates/parser/src/optimize/targets.rs | 290 ++++ crates/parser/src/parallel.rs | 12 +- crates/parser/src/visit.rs | 281 +++- crates/tinywasm/src/interpreter/executor.rs | 543 ++++---- .../tinywasm/src/interpreter/stack/value_stack.rs | 11 + crates/tinywasm/src/interpreter/values.rs | 6 + .../tests/wasm-custom/conditional-rewrite.wast | 35 + .../tests/wasm-custom/sign-extension-rewrite.wast | 59 + .../tests/wasm-custom/simd-stack-local.wast | 53 + crates/types/src/archive.rs | 26 + crates/types/src/instructions.rs | 795 ++++++++--- crates/types/src/lib.rs | 13 +- crates/types/src/operands.rs | 177 +++ crates/types/src/reference.rs | 12 + 23 files changed, 3221 insertions(+), 1949 deletions(-) delete mode 100644 crates/parser/src/optimize.rs create mode 100644 crates/parser/src/optimize/mod.rs create mode 100644 crates/parser/src/optimize/rewrite.rs create mode 100644 crates/parser/src/optimize/targets.rs create mode 100644 crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast create mode 100644 crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast create mode 100644 crates/tinywasm/tests/wasm-custom/simd-stack-local.wast create mode 100644 crates/types/src/operands.rs (limited to 'crates/parser/src/optimize.rs') diff --git a/CHANGELOG.md b/CHANGELOG.md index 3427a80..701fc84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added `WasmValue::ty` and `WasmValue::matches_type` - Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. +- Added optional parse-time operand deduplication to reduce precompiled module and `.twasm` archive size. ### Changed diff --git a/Cargo.lock b/Cargo.lock index b06f70f..3c13501 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,9 +134,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.4.2" +version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" +checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" dependencies = [ "find-msvc-tools", "shlex", @@ -365,9 +365,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.10" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" [[package]] name = "float-cmp" diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 480a8d0..b94ebe6 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -1,7 +1,7 @@ use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResources}; #[cfg(feature = "validate")] use crate::visit::process_operators_and_validate; -use crate::{Result, module::FunctionCode, visit::process_operators}; +use crate::{ParserOptions, Result, module::FunctionCode, visit::process_operators}; use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; @@ -149,6 +149,7 @@ pub(crate) fn convert_module_code( reader_allocs: OperatorsReaderAllocations, metadata: &crate::visit::ModuleMetadata, ty_idx: u32, + options: &ParserOptions, ) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { let locals_reader = func.get_locals_reader()?; #[cfg(feature = "validate")] @@ -194,32 +195,40 @@ pub(crate) fn convert_module_code( let (body, data, validator_allocs, reader_allocs) = process_operators_and_validate( validator, func, - local_types, - local_addr_map, + (local_types, local_addr_map), metadata, ty_idx, reader_allocs, + options.deduplicate_operands(), )?; (body, data, Some(validator_allocs), reader_allocs) } None => { - let (body, data, reader_allocs) = - process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + let (body, data, reader_allocs) = process_operators( + func, + (local_types, local_addr_map), + metadata, + ty_idx, + reader_allocs, + options.deduplicate_operands(), + )?; (body, data, None, reader_allocs) } }; #[cfg(not(feature = "validate"))] let (body, data, validator_allocs, reader_allocs) = { let _ = validator; - let (body, data, reader_allocs) = - process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + let (body, data, reader_allocs) = process_operators( + func, + (local_types, local_addr_map), + metadata, + ty_idx, + reader_allocs, + options.deduplicate_operands(), + )?; (body, data, None, reader_allocs) }; - Ok(( - FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory: false }, - validator_allocs, - reader_allocs, - )) + Ok((FunctionCode { instructions: body, data, locals: local_counts }, validator_allocs, reader_allocs)) } pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec) -> Result { diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 8db7920..90e239b 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -65,6 +65,10 @@ pub struct ParserOptions { pub optimize_local_memory_allocation: bool, /// Whether to run the peephole rewrite optimizer. pub optimize_rewrite: bool, + /// Whether to deduplicate immutable function operands while parsing. + /// + /// This uses more parse CPU to reduce precompiled module and archive size. + pub deduplicate_operands: bool, #[cfg(parallel_parser)] /// Number of threads to use for parallel parsing. @@ -83,6 +87,7 @@ impl Default for ParserOptions { validation: cfg!(feature = "validate"), optimize_local_memory_allocation: true, optimize_rewrite: true, + deduplicate_operands: false, #[cfg(parallel_parser)] parser_threads: None, } @@ -134,6 +139,17 @@ impl ParserOptions { self.optimize_rewrite } + /// Enable or disable parse-time deduplication of immutable function operands. + pub const fn with_operand_deduplication(mut self, enabled: bool) -> Self { + self.deduplicate_operands = enabled; + self + } + + /// Returns whether immutable function operands are deduplicated while parsing. + pub const fn deduplicate_operands(&self) -> bool { + self.deduplicate_operands + } + #[cfg(parallel_parser)] /// Set the number of threads for parallel parsing. /// diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 9fa7a01..5e675e6 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -72,10 +72,17 @@ pub(crate) mod visit { ) => { fn $visit(&mut self, memarg: wasmparser::MemArg $(, $lane: $ty)?) -> Self::Output { let address = self.metadata.memory_size(memarg.memory)?; + let memory_arg_idx = self.push_operand(MemoryArg::new(memarg.offset, memarg.memory))?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - Instruction::$instr(MemoryArg::new(memarg.offset, memarg.memory) $(, $lane)?).into()) + lowering_ops!(@memory_instruction $instr memory_arg_idx $(, $lane)?)) } }; + (@memory_instruction $instr:ident $memory_arg_idx:ident) => { + Instruction::$instr($memory_arg_idx) + }; + (@memory_instruction $instr:ident $memory_arg_idx:ident, $lane:ident) => { + Instruction::$instr(tinywasm_types::MemoryLaneArg { memory_arg_idx: $memory_arg_idx, lane: $lane }) + }; (@global $inputs:tt => $outputs:tt $($operator:tt)*) => { lowering_ops!(@resolved global_size $inputs => $outputs $($operator)*); }; @@ -191,6 +198,20 @@ pub(crate) mod optimize { ($instructions:ident, $read:ident, $consumed:expr => $out:expr) => { replace!($instructions, $read, $consumed => [$out]); }; + ($instructions:ident, *$read:ident, $consumed:expr => [$($out:expr),+ $(,)?]) => {{ + const { + assert!($consumed >= 1 && $consumed <= 3); + assert!([$(stringify!($out)),+].len() <= $consumed + 1); + } + let replacements = [$($out),+]; + let start = *$read - $consumed; + $instructions[start..start + replacements.len()].copy_from_slice(&replacements); + $instructions.truncate(start + replacements.len()); + *$read = $instructions.len() - 1; + }}; + ($instructions:ident, *$read:ident, $consumed:expr => $out:expr) => { + replace!($instructions, *$read, $consumed => [$out]) + }; } macro_rules! rewrite { @@ -201,16 +222,13 @@ pub(crate) mod optimize { }; ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => $body:block $(,)?) => {{ const CONSUMED: usize = [$(stringify!($pattern)),+].len(); - if !$instructions.tail_rewritten - && $read < $instructions.len() - && $read >= $instructions.block_start + CONSUMED - { + if $read >= $instructions.block_start + CONSUMED { let previous: [Instruction; CONSUMED] = $instructions[$read - CONSUMED..$read].try_into().unwrap(); if let [$($pattern),+] = previous $( && $($guard)+ )? { - $instructions.tail_rewritten = true; $body + continue; } } }}; @@ -221,128 +239,5 @@ pub(crate) mod optimize { }; } - macro_rules! define_local_source_resolver { - ( - $name:ident, - get = $get:ident, - tee = $tee:ident, - set = $set:ident, - binop_local_local_tee = $lltee:ident, - binop_local_local_set = $llset:ident, - binop_local_const_tee = $lctee:ident, - binop_local_const_set = $lcset:ident - $(, load_local_tee = $loadtee:ident, load_local_set = $loadset:ident)? - ) => { - fn $name(instr: Instruction) -> Option<(Option, u16)> { - Some(match instr { - Instruction::$get(local) => (None, local), - Instruction::$tee(local) => (Some(Instruction::$set(local)), local), - Instruction::$lltee(op, a, b, local) => (Some(Instruction::$llset(op, a, b, local)), local), - Instruction::$lctee(op, src, c, local) => (Some(Instruction::$lcset(op, src, c, local)), local), - $(Instruction::$loadtee(memarg, addr, local) => (Some(Instruction::$loadset(memarg, addr, local)), local.into()),)? - _ => return None, - }) - } - }; - } - - macro_rules! fold_local_binop { - ( - $instrs:ident, $read:expr, $dst:expr, - source = $source:ident, - op = $op:ident, - const = $const:ident, - local_local = $local_local:ident, - local_const = $local_const:expr - ) => {{ - if !$instrs.tail_rewritten - && $read < $instrs.len() - && $read >= $instrs.block_start + 3 - && let [lhs_src, rhs_src, raw_op] = [$instrs[$read - 3], $instrs[$read - 2], $instrs[$read - 1]] - && let Some((lhs_instr, lhs)) = $source(lhs_src) - && let Some(op) = $op(raw_op) - { - if let Some((rhs_instr, rhs)) = $source(rhs_src) { - if rhs_instr.is_none() || rhs != lhs { - $instrs.tail_rewritten = true; - $instrs.truncate($read - 3); - $instrs.extend(lhs_instr); - $instrs.extend(rhs_instr); - $instrs.push(Instruction::$local_local(op, lhs, rhs, $dst)); - $read = $instrs.len() - 1; - } - } else if let Some(imm) = $const(rhs_src, raw_op) { - $instrs.tail_rewritten = true; - $instrs.truncate($read - 3); - $instrs.extend(lhs_instr); - $instrs.push($local_const($dst, lhs, op, imm)); - $read = $instrs.len() - 1; - } - } - }}; - } - - macro_rules! rewrite_local_set_direct { - ( - $instrs:ident, $read:ident, $dst:expr, - get = $get:ident, - copy = $copy:ident, - binop_local_local = $ll:ident, - binop_local_local_set = $llset:ident, - binop_local_const = $lc:ident, - binop_local_const_set = $lcset:expr - $(, const_instr = $const_instr:ident, set_local_const = $set_local_const:ident)? - ) => {{ - rewrite!($instrs, $read, [$get(src)] if (src != $dst) => Instruction::$copy(src, $dst)); - if !$instrs.tail_rewritten - && $read < $instrs.len() - && $read > $instrs.block_start - && let Instruction::$get(src) = $instrs[$read - 1] - && src == $dst - { - $instrs.tail_rewritten = true; - $instrs.truncate($read - 1); - $read = $instrs.len(); - } - $(rewrite!($instrs, $read, [$const_instr(c)] => Instruction::$set_local_const($dst, c));)? - rewrite!($instrs, $read, [$ll(op, a, b)] => Instruction::$llset(op, a, b, $dst)); - rewrite!($instrs, $read, [$lc(op, src, c)] => { replace!($instrs, $read, 1 => $lcset($dst, src, op, c)); }); - }}; - } - - macro_rules! rewrite_local_tee_direct { - ( - $instrs:ident, $read:ident, $dst:expr, - get = $get:ident, - binop_local_local = $ll:ident, - binop_local_local_tee = $lltee:ident, - binop_local_const = $lc:ident, - binop_local_const_tee = $lctee:ident - ) => {{ - rewrite!($instrs, $read, [$get(src)] if (src == $dst) => Instruction::$get(src)); - rewrite!($instrs, $read, [$ll(op, a, b)] => Instruction::$lltee(op, a, b, $dst)); - rewrite!($instrs, $read, [$lc(op, src, c)] => Instruction::$lctee(op, src, c, $dst)); - }}; - } - - macro_rules! rewrite_drop_tee_direct { - ( - $instrs:ident, $read:ident, - tee = $tee:ident, - set = $set:ident, - binop_local_local_tee = $lltee:ident, - binop_local_local_set = $llset:ident, - binop_local_const_tee = $lctee:ident, - binop_local_const_set = $lcset:ident - ) => {{ - rewrite!($instrs, $read, [$tee(local)] => Instruction::$set(local)); - rewrite!($instrs, $read, [$lltee(op, a, b, dst)] => Instruction::$llset(op, a, b, dst)); - rewrite!($instrs, $read, [$lctee(op, src, c, dst)] => Instruction::$lcset(op, src, c, dst)); - }}; - } - - pub(crate) use { - define_local_source_resolver, fold_local_binop, replace, rewrite, rewrite_drop_tee_direct, - rewrite_local_set_direct, rewrite_local_tee_direct, - }; + pub(crate) use {replace, rewrite}; } diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 3d38ad6..8138666 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -10,6 +10,12 @@ use tinywasm_types::*; use wasmparser::{OperatorsReaderAllocations, Payload}; pub(crate) struct FunctionCode { + pub instructions: Vec, + pub data: crate::visit::FunctionDataBuilder, + pub locals: ValueCounts, +} + +pub(crate) struct OptimizedFunctionCode { pub instructions: Vec, pub data: WasmFunctionData, pub locals: ValueCounts, @@ -22,19 +28,15 @@ pub(crate) fn optimize_function_code( function_results: ValueCounts, self_func_addr: u32, imported_memory_count: u32, -) -> Result { - let optimized = optimize::optimize_instructions( - code.instructions, - &mut code.data, - options, - function_results, - self_func_addr, - imported_memory_count, - )?; - - code.instructions = optimized.instructions; - code.uses_local_memory = optimized.uses_local_memory; - Ok(code) +) -> Result { + let optimized = + optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; + let data = code.data.finish(); + let uses_local_memory = optimized + .instructions + .iter() + .any(|instruction| instruction.memory_addr(&data).is_some_and(|memory| memory >= imported_memory_count)); + Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals, uses_local_memory }) } #[derive(Default)] @@ -53,7 +55,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) code_type_addrs: Box<[u32]>, code_results: Box<[ValueCounts]>, pub(crate) exports: Arc<[Export]>, - pub(crate) code: Vec, + pub(crate) code: Vec, pub(crate) globals: Box<[Global]>, pub(crate) tables: Box<[TableDefinition]>, pub(crate) memory_types: Box<[MemoryType]>, @@ -402,7 +404,7 @@ impl<'a> ModuleReader<'a> { let metadata = self.translation_metadata(); let (code, func_validator_allocs, operators_reader_allocs) = - convert_module_code(function, func_validator, operators_reader_allocs, metadata, ty_idx)?; + convert_module_code(function, func_validator, operators_reader_allocs, metadata, ty_idx, options)?; self.code.push(optimize_function_code( code, @@ -565,7 +567,7 @@ impl<'a> ModuleReader<'a> { .into_iter() .zip(self.code_type_addrs) .zip(self.code_results) - .map(|((code, ty_idx), results)| { + .map(|((code, ty_idx), results)| -> Result<_> { let ty = self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing"); let params = ValueCounts::from_iter(ty.params()); @@ -573,15 +575,15 @@ impl<'a> ModuleReader<'a> { local_memory_allocation = LocalMemoryAllocation::Eager; } - Arc::new(WasmFunction { - instructions: code.instructions.into(), + Ok(Arc::new(WasmFunction { + instructions: code.instructions.into_boxed_slice(), data: code.data, locals: code.locals, params, results, - }) + })) }) - .collect(); + .collect::>()?; Ok(ModuleInner { funcs, diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs deleted file mode 100644 index 969d686..0000000 --- a/crates/parser/src/optimize.rs +++ /dev/null @@ -1,1201 +0,0 @@ -use crate::macros::optimize::*; -use crate::{ParseError, ParserOptions, Result}; -use alloc::vec::Vec; -use core::ops::{Deref, DerefMut}; -use tinywasm_types::{BinOp, BinOp128, CmpOp, ConstIdx, Instruction, ValueCounts, WasmFunctionData}; - -pub(crate) struct OptimizeResult { - pub(crate) instructions: Vec, - pub(crate) uses_local_memory: bool, -} - -struct CompactOutput { - instructions: Vec, - block_start: usize, - tail_rewritten: bool, -} - -impl Deref for CompactOutput { - type Target = Vec; - - fn deref(&self) -> &Self::Target { - &self.instructions - } -} - -impl DerefMut for CompactOutput { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.instructions - } -} - -pub(crate) fn optimize_instructions( - instructions: Vec, - function_data: &mut WasmFunctionData, - options: &ParserOptions, - function_results: ValueCounts, - self_func_addr: u32, - imported_memory_count: u32, -) -> Result { - let (mut instructions, old_to_new) = if options.optimize_rewrite() { - let boundaries = target_boundaries(&instructions, function_data)?; - let (instructions, old_to_new) = rewrite(instructions, &boundaries, function_results, self_func_addr); - (instructions, Some(old_to_new)) - } else { - (instructions, None) - }; - let uses_local_memory = finalize(&mut instructions, function_data, old_to_new.as_deref(), imported_memory_count)?; - Ok(OptimizeResult { instructions, uses_local_memory }) -} - -fn rewrite( - source: Vec, - boundaries: &[bool], - function_results: ValueCounts, - self_func_addr: u32, -) -> (Vec, Vec) { - use Instruction::*; - let mut instrs = - CompactOutput { instructions: Vec::with_capacity(source.len()), block_start: 0, tail_rewritten: false }; - let mut old_to_new = alloc::vec![0; source.len() + 1]; - let mut after_terminator = false; - let return_instr = match function_results { - ValueCounts { c32: 0, c64: 0, c128: 0 } => Some(ReturnVoid), - ValueCounts { c32: 1, c64: 0, c128: 0 } => Some(Return32), - ValueCounts { c32: 0, c64: 1, c128: 0 } => Some(Return64), - ValueCounts { c32: 0, c64: 0, c128: 1 } => Some(Return128), - _ => None, - }; - - for (old_idx, instr) in source.iter().copied().enumerate() { - if boundaries[old_idx] || after_terminator { - instrs.block_start = instrs.len(); - } - old_to_new[old_idx] = instrs.len() as u32; - instrs.tail_rewritten = false; - instrs.push(instr); - let mut i = instrs.len() - 1; - match instrs[i] { - LocalCopy32(a, b) if a == b => { - instrs.pop(); - } - LocalCopy64(a, b) if a == b => { - instrs.pop(); - } - LocalCopy128(a, b) if a == b => { - instrs.pop(); - } - Call(addr) if addr == self_func_addr => instrs[i] = CallSelf, - ReturnCall(addr) if addr == self_func_addr => instrs[i] = ReturnCallSelf, - Return if let Some(return_instr) = return_instr => instrs[i] = return_instr, - instr @ (I32Add | I32Mul | I32And | I32Or | I32Xor) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if matches!(op, BinOp::IAdd) { - rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); - rewrite!(instrs, i, [I32Add] => I32Add3); - rewrite!(instrs, i, - [BinOpStackLocal32(BinOp::IAdd, local)] => - [LocalGet32(local), I32Add3] - ); - } - } - instr @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if matches!(op, BinOp::IShrS) { - rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]); - rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 16), Const32(16)] => [LocalGet32(local), I32Extend16S]); - } - } - instr @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); - if matches!(op, BinOp::IAdd) { - rewrite!(instrs, i, [Const64(c)] => AddConst64(c)); - rewrite!(instrs, i, [I64Add] => I64Add3); - } - } - instr @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); - if matches!(op, BinOp::IShrS) { - rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 8), Const64(8)] => [LocalGet64(local), I64Extend8S]); - rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 16), Const64(16)] => [LocalGet64(local), I64Extend16S]); - rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 32), Const64(32)] => [LocalGet64(local), I64Extend32S]); - } - } - instr @ (I32Eq | I32Ne | I32LtS | I32LtU | I32GtS | I32GtU | I32LeS | I32LeU | I32GeS | I32GeU) => { - let Some(op) = cmp_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(left), LocalGet32(right)] => CmpLocalLocal32(op, left, right)); - } - instr @ (I64Eq | I64Ne | I64LtS | I64LtU | I64GtS | I64GtU | I64LeS | I64LeU | I64GeS | I64GeU) => { - let Some(op) = cmp_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(left), LocalGet64(right)] => CmpLocalLocal64(op, left, right)); - } - instr @ (F32Add | F32Mul | F32Min | F32Max) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - } - instr @ (F32Sub | F32Div | F32Copysign) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - } - instr @ (F64Add | F64Mul | F64Min | F64Max) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); - } - instr @ (F64Sub | F64Div | F64Copysign) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - } - instr @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul) => { - let Some(op) = bin_op_128(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(op, a, b)); - rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(op, local, c)); - rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(op, global, c)); - rewrite!(instrs, i, [Const128(c), LocalGet128(local)] => BinOpLocalConst128(op, local, c)); - rewrite!(instrs, i, [Const128(c), GlobalGet128(global)] => BinOpGlobalConst128(op, global, c)); - } - V128AndNot => { - rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(BinOp128::AndNot, a, b)); - rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(BinOp128::AndNot, local, c)); - rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(BinOp128::AndNot, global, c)); - } - I32Store(memarg) | F32Store(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr), LoadLocal32(load_memarg, load_addr), AddConst32(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal32(memarg, load_addr) - ); - rewrite!(instrs, i, - [LocalGet64(addr), LoadLocal32(load_memarg, load_addr), AddConst32(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal32(memarg, load_addr) - ); - rewrite!(instrs, i, [F32Mul, F32Add] => FMaStoreF32(memarg)); - rewrite!(instrs, i, - [BinOpStackLocal32(BinOp::FMul, local), F32Add] => - [LocalGet32(local), FMaStoreF32(memarg)] - ); - rewrite!(instrs, i, - [LocalGet32(addr_local), LocalGet32(value_local)] if - (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) => - StoreLocalLocal32(memarg, addr_local, value_local) - ); - } - I64Store(memarg) | F64Store(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr), LoadLocal64(load_memarg, load_addr), AddConst64(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal64(memarg, load_addr) - ); - rewrite!(instrs, i, - [LocalGet64(addr), LoadLocal64(load_memarg, load_addr), AddConst64(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal64(memarg, load_addr) - ); - rewrite!(instrs, i, [F64Mul, F64Add] => FMaStoreF64(memarg)); - rewrite!(instrs, i, - [LocalGet32(addr_local), LocalGet64(value_local)] if - (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) => - StoreLocalLocal64(memarg, addr_local, value_local) - ); - } - V128Store(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local), LocalGet128(value_local)] if - (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) => - StoreLocalLocal128(memarg, addr_local, value_local) - ); - } - I32Load(memarg) | F32Load(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal32(memarg, addr_local) - ); - } - I64Load(memarg) | F64Load(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal64(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal64(memarg, addr_local) - ); - } - I32Load8S(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8S32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8S32(memarg, addr_local) - ); - } - I32Load8U(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8U32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8U32(memarg, addr_local) - ); - } - I32Load16S(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16S32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16S32(memarg, addr_local) - ); - } - I32Load16U(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16U32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16U32(memarg, addr_local) - ); - } - MemoryFill(mem) => { - rewrite!(instrs, i, [Const32(val), Const32(size)] => MemoryFillImm(mem, val as u8, size)) - } - GlobalGet32(dst) => rewrite!(instrs, i, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), - GlobalGet64(dst) => rewrite!(instrs, i, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), - GlobalGet128(dst) => rewrite!(instrs, i, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), - LocalGet32(dst) => rewrite!(instrs, i, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), - LocalGet64(dst) => rewrite!(instrs, i, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), - LocalGet128(dst) => rewrite!(instrs, i, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), - LocalSet32(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_32, - op = scalar_bin_op, - const = scalar_const_32, - local_local = BinOpLocalLocalSet32, - local_const = |dst, lhs, op, imm| match (dst == lhs, op) { - (true, BinOp::IAdd) => Instruction::IncLocal32(dst, imm), - (true, BinOp::ISub) => Instruction::IncLocal32(dst, imm.wrapping_neg()), - _ => Instruction::BinOpLocalConstSet32(op, lhs, imm, dst), - } - ); - rewrite!(instrs, i, [I32Mul, LocalGet32(acc), I32Add] if (acc == dst) => MulAccLocal32(dst)); - rewrite!(instrs, i, [F32Mul, LocalGet32(acc), F32Add] if (acc == dst) => FMulAccLocal32(dst)); - rewrite!(instrs, i, - [I32Mul, BinOpStackLocal32(BinOp::IAdd, acc)] if (acc == dst) => - MulAccLocal32(dst) - ); - rewrite!(instrs, i, - [F32Mul, BinOpStackLocal32(BinOp::FAdd, acc)] if (acc == dst) => - FMulAccLocal32(dst) - ); - rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalSet32(op, local, dst)); - rewrite_local_set_direct!( - instrs, - i, - dst, - get = LocalGet32, - copy = LocalCopy32, - binop_local_local = BinOpLocalLocal32, - binop_local_local_set = BinOpLocalLocalSet32, - binop_local_const = BinOpLocalConst32, - binop_local_const_set = |dst, src, op, c| match (dst == src, op) { - (true, BinOp::IAdd) => IncLocal32(dst, c), - (true, BinOp::ISub) => IncLocal32(dst, c.wrapping_neg()), - _ => BinOpLocalConstSet32(op, src, c, dst), - }, - const_instr = Const32, - set_local_const = SetLocalConst32 - ); - rewrite!(instrs, i, [LoadLocal32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal8S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet8S32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal8U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet8U32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal16S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet16S32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal16U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet16U32(memarg, addr, dst)); - rewrite!(instrs, i, - [LocalGet32(addr), I32Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalSet32(memarg, addr, dst) - ); - } - LocalSet64(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_64, - op = scalar_bin_op, - const = scalar_const_64, - local_local = BinOpLocalLocalSet64, - local_const = |dst, lhs, op, imm| match (dst == lhs, op) { - (true, BinOp::IAdd) => Instruction::IncLocal64(dst, imm), - (true, BinOp::ISub) => Instruction::IncLocal64(dst, imm.wrapping_neg()), - _ => Instruction::BinOpLocalConstSet64(op, lhs, imm, dst), - } - ); - rewrite!(instrs, i, [I64Mul, LocalGet64(acc), I64Add] if (acc == dst) => MulAccLocal64(dst)); - rewrite!(instrs, i, [F64Mul, LocalGet64(acc), F64Add] if (acc == dst) => FMulAccLocal64(dst)); - rewrite_local_set_direct!( - instrs, - i, - dst, - get = LocalGet64, - copy = LocalCopy64, - binop_local_local = BinOpLocalLocal64, - binop_local_local_set = BinOpLocalLocalSet64, - binop_local_const = BinOpLocalConst64, - binop_local_const_set = |dst, src, op, c| match (dst == src, op) { - (true, BinOp::IAdd) => IncLocal64(dst, c), - (true, BinOp::ISub) => IncLocal64(dst, c.wrapping_neg()), - _ => BinOpLocalConstSet64(op, src, c, dst), - }, - const_instr = Const64, - set_local_const = SetLocalConst64 - ); - } - LocalSet128(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_128, - op = bin_op_128, - const = const_128, - local_local = BinOpLocalLocalSet128, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstSet128(op, lhs, imm, dst) - ); - rewrite_local_set_direct!( - instrs, - i, - dst, - get = LocalGet128, - copy = LocalCopy128, - binop_local_local = BinOpLocalLocal128, - binop_local_local_set = BinOpLocalLocalSet128, - binop_local_const = BinOpLocalConst128, - binop_local_const_set = |dst, src, op, c| BinOpLocalConstSet128(op, src, c, dst), - const_instr = Const128, - set_local_const = SetLocalConst128 - ); - rewrite!(instrs, i, - [LocalGet32(addr), V128Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalSet128(memarg, addr, dst) - ); - } - LocalTee32(dst) => { - rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalTee32(op, local, dst)); - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_32, - op = scalar_bin_op, - const = scalar_const_32, - local_local = BinOpLocalLocalTee32, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee32(op, lhs, imm, dst) - ); - rewrite_local_tee_direct!( - instrs, - i, - dst, - get = LocalGet32, - binop_local_local = BinOpLocalLocal32, - binop_local_local_tee = BinOpLocalLocalTee32, - binop_local_const = BinOpLocalConst32, - binop_local_const_tee = BinOpLocalConstTee32 - ); - rewrite!(instrs, i, [Const32(c), I32And] => AndConstTee32(c, dst)); - rewrite!(instrs, i, [Const32(c), I32Sub] => SubConstTee32(c, dst)); - rewrite!(instrs, i, - [LocalGet32(addr), I32Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalTee32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LocalGet32(addr), F32Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalTee32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal8S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee8S32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal8U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee8U32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal16S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee16S32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal16U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee16U32(memarg, addr, dst) - ); - } - LocalTee64(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_64, - op = scalar_bin_op, - const = scalar_const_64, - local_local = BinOpLocalLocalTee64, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee64(op, lhs, imm, dst) - ); - rewrite_local_tee_direct!( - instrs, - i, - dst, - get = LocalGet64, - binop_local_local = BinOpLocalLocal64, - binop_local_local_tee = BinOpLocalLocalTee64, - binop_local_const = BinOpLocalConst64, - binop_local_const_tee = BinOpLocalConstTee64 - ); - rewrite!(instrs, i, [Const64(c), I64And] => AndConstTee64(c, dst)); - rewrite!(instrs, i, [Const64(c), I64Sub] => SubConstTee64(c, dst)); - } - LocalTee128(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_128, - op = bin_op_128, - const = const_128, - local_local = BinOpLocalLocalTee128, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee128(op, lhs, imm, dst) - ); - rewrite_local_tee_direct!( - instrs, - i, - dst, - get = LocalGet128, - binop_local_local = BinOpLocalLocal128, - binop_local_local_tee = BinOpLocalLocalTee128, - binop_local_const = BinOpLocalConst128, - binop_local_const_tee = BinOpLocalConstTee128 - ); - rewrite!(instrs, i, - [LocalGet32(addr), V128Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalTee128(memarg, addr, dst) - ); - } - Drop32 => { - rewrite!(instrs, i, - [BinOpStackLocalTee32(op, local, dst)] => - BinOpStackLocalSet32(op, local, dst) - ); - rewrite_drop_tee_direct!( - instrs, - i, - tee = LocalTee32, - set = LocalSet32, - binop_local_local_tee = BinOpLocalLocalTee32, - binop_local_local_set = BinOpLocalLocalSet32, - binop_local_const_tee = BinOpLocalConstTee32, - binop_local_const_set = BinOpLocalConstSet32 - ); - } - Drop64 => rewrite_drop_tee_direct!( - instrs, - i, - tee = LocalTee64, - set = LocalSet64, - binop_local_local_tee = BinOpLocalLocalTee64, - binop_local_local_set = BinOpLocalLocalSet64, - binop_local_const_tee = BinOpLocalConstTee64, - binop_local_const_set = BinOpLocalConstSet64 - ), - Drop128 => rewrite_drop_tee_direct!( - instrs, - i, - tee = LocalTee128, - set = LocalSet128, - binop_local_local_tee = BinOpLocalLocalTee128, - binop_local_local_set = BinOpLocalLocalSet128, - binop_local_const_tee = BinOpLocalConstTee128, - binop_local_const_set = BinOpLocalConstSet128 - ), - Jump(ip) => { - let target = resolve_jump_target(&source, ip); - let exit = old_idx as u32 + 1; - let body = target + 1; - - match source.get(target as usize).copied() { - Some(JumpCmpLocalLocal32 { target_ip, left, right, op }) - if resolve_jump_target(&source, target_ip) == exit && body > target => - { - instrs[i] = JumpCmpLocalLocal32 { target_ip: body, left, right, op: inverse_cmp_op(op) }; - } - Some(JumpCmpLocalLocal64 { target_ip, left, right, op }) - if resolve_jump_target(&source, target_ip) == exit && body > target => - { - instrs[i] = JumpCmpLocalLocal64 { target_ip: body, left, right, op: inverse_cmp_op(op) }; - } - _ => canonicalize_jump_like_with_target(&mut instrs, i, target, exit), - } - } - JumpIfZero32(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet32(local), I32Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalNonZero32 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I32Eqz] => { - replace!(instrs, i, 1 => JumpIfNonZero32(target)); - continue; - }); - rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalNonZero64 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I64Eqz] => { - replace!(instrs, i, 1 => JumpIfNonZero64(target)); - continue; - }); - rewrite!(instrs, i, - [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => - match inc_delta(op, imm) { - Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: true }, - None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: true }, - } - ); - rewrite!(instrs, i, - [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: true } - ); - rewrite!(instrs, i, - [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: true } - ); - rewrite!(instrs, i, - [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: true } - ); - rewrite!(instrs, i, - [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => - match inc_delta(op, imm) { - Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: true }, - None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: true }, - } - ); - rewrite!(instrs, i, - [CmpLocalLocal32(op, left, right)] => - JumpCmpLocalLocal32 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [CmpLocalLocal64(op, left, right)] => - JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if - (local == dst && let Some(cmp) = cmp_op(cmp)) => - match inc_delta(binop, imm) { - Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(cmp) }, - None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp: inverse_cmp_op(cmp) }, - } - ); - rewrite!(instrs, i, - [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal32 { target_ip: target, local, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [LocalGet64(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal64 { target_ip: target, local, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [LocalGet32(local), Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => - match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfLocalZero32 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero32 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst32 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet64(local), Const64(imm), cmp] if - (let Some(op) = cmp_op(cmp) && let Ok(imm) = i32::try_from(imm)) => - match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfLocalZero64 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero64 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst64 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet32(left), LocalGet32(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal32 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [LocalGet64(left), LocalGet64(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, [Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfZero32(target), - (0, CmpOp::Ne) => JumpIfNonZero32(target), - (imm, op) => JumpCmpStackConst32 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [Const64(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfZero64(target), - (0, CmpOp::Ne) => JumpIfNonZero64(target), - (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local }); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpIfNonZero32(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet32(local), I32Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalZero32 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I32Eqz] => { - replace!(instrs, i, 1 => JumpIfZero32(target)); - continue; - }); - rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalZero64 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I64Eqz] => { - replace!(instrs, i, 1 => JumpIfZero64(target)); - continue; - }); - rewrite!(instrs, i, - [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => - match inc_delta(op, imm) { - Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: false }, - None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: false }, - } - ); - rewrite!(instrs, i, - [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: false } - ); - rewrite!(instrs, i, - [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: false } - ); - rewrite!(instrs, i, - [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: false } - ); - rewrite!(instrs, i, - [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => - match inc_delta(op, imm) { - Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: false }, - None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: false }, - } - ); - rewrite!(instrs, i, - [CmpLocalLocal32(op, left, right)] => - JumpCmpLocalLocal32 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [CmpLocalLocal64(op, left, right)] => - JumpCmpLocalLocal64 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if - (local == dst && let Some(cmp) = cmp_op(cmp)) => - match inc_delta(binop, imm) { - Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: cmp }, - None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp }, - } - ); - rewrite!(instrs, i, - [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal32 { target_ip: target, local, op } - ); - rewrite!(instrs, i, - [LocalGet64(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal64 { target_ip: target, local, op } - ); - rewrite!(instrs, i, - [LocalGet32(local), Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => - match (imm, op) { - (0, CmpOp::Eq) => JumpIfLocalZero32 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero32 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst32 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet64(local), Const64(imm), cmp] if - (let Some(op) = cmp_op(cmp) && let Ok(imm) = i32::try_from(imm)) => - match (imm, op) { - (0, CmpOp::Eq) => JumpIfLocalZero64 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero64 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst64 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet32(left), LocalGet32(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal32 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [LocalGet64(left), LocalGet64(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal64 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, [Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, op) { - (0, CmpOp::Eq) => JumpIfZero32(target), - (0, CmpOp::Ne) => JumpIfNonZero32(target), - (imm, op) => JumpCmpStackConst32 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [Const64(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, op) { - (0, CmpOp::Eq) => JumpIfZero64(target), - (0, CmpOp::Ne) => JumpIfNonZero64(target), - (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local }); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpIfZero64(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpIfNonZero64(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpCmpStackConst32 { target_ip, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfZero32(target_ip), - CmpOp::Ne => instrs[i] = JumpIfNonZero32(target_ip), - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpStackConst64 { target_ip, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfZero64(target_ip), - CmpOp::Ne => instrs[i] = JumpIfNonZero64(target_ip), - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpLocalConst32 { target_ip, local, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfLocalZero32 { target_ip, local }, - CmpOp::Ne => instrs[i] = JumpIfLocalNonZero32 { target_ip, local }, - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpLocalConst64 { target_ip, local, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfLocalZero64 { target_ip, local }, - CmpOp::Ne => instrs[i] = JumpIfLocalNonZero64 { target_ip, local }, - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpStackConst32 { .. } - | JumpCmpStackConst64 { .. } - | JumpCmpLocalConst32 { .. } - | JumpCmpLocalConst64 { .. } - | JumpCmpLocalLocal32 { .. } - | JumpCmpLocalLocal64 { .. } - | JumpIfLocalZero32 { .. } - | JumpIfLocalNonZero32 { .. } - | JumpIfLocalZero64 { .. } - | JumpIfLocalNonZero64 { .. } => { - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - _ => {} - } - - after_terminator = is_unconditional_terminator(instr); - } - - old_to_new[source.len()] = instrs.len() as u32; - (instrs.instructions, old_to_new) -} - -fn cmp_op(instr: Instruction) -> Option { - Some(match instr { - Instruction::I32Eq | Instruction::I64Eq => CmpOp::Eq, - Instruction::I32Ne | Instruction::I64Ne => CmpOp::Ne, - Instruction::I32LtS | Instruction::I64LtS => CmpOp::LtS, - Instruction::I32LtU | Instruction::I64LtU => CmpOp::LtU, - Instruction::I32GtS | Instruction::I64GtS => CmpOp::GtS, - Instruction::I32GtU | Instruction::I64GtU => CmpOp::GtU, - Instruction::I32LeS | Instruction::I64LeS => CmpOp::LeS, - Instruction::I32LeU | Instruction::I64LeU => CmpOp::LeU, - Instruction::I32GeS | Instruction::I64GeS => CmpOp::GeS, - Instruction::I32GeU | Instruction::I64GeU => CmpOp::GeU, - _ => return None, - }) -} - -fn inc_delta(op: BinOp, imm: i32) -> Option { - match op { - BinOp::IAdd => Some(imm), - BinOp::ISub => Some(imm.wrapping_neg()), - _ => None, - } -} - -fn int_bin_op(instr: Instruction) -> Option { - Some(match instr { - Instruction::I32Add | Instruction::I64Add => BinOp::IAdd, - Instruction::I32Sub | Instruction::I64Sub => BinOp::ISub, - Instruction::I32Mul | Instruction::I64Mul => BinOp::IMul, - Instruction::I32And | Instruction::I64And => BinOp::IAnd, - Instruction::I32Or | Instruction::I64Or => BinOp::IOr, - Instruction::I32Xor | Instruction::I64Xor => BinOp::IXor, - Instruction::I32Shl | Instruction::I64Shl => BinOp::IShl, - Instruction::I32ShrS | Instruction::I64ShrS => BinOp::IShrS, - Instruction::I32ShrU | Instruction::I64ShrU => BinOp::IShrU, - Instruction::I32Rotl | Instruction::I64Rotl => BinOp::IRotl, - Instruction::I32Rotr | Instruction::I64Rotr => BinOp::IRotr, - _ => return None, - }) -} - -fn float_bin_op(instr: Instruction) -> Option { - Some(match instr { - Instruction::F32Add | Instruction::F64Add => BinOp::FAdd, - Instruction::F32Sub | Instruction::F64Sub => BinOp::FSub, - Instruction::F32Mul | Instruction::F64Mul => BinOp::FMul, - Instruction::F32Div | Instruction::F64Div => BinOp::FDiv, - Instruction::F32Min | Instruction::F64Min => BinOp::FMin, - Instruction::F32Max | Instruction::F64Max => BinOp::FMax, - Instruction::F32Copysign | Instruction::F64Copysign => BinOp::FCopysign, - _ => return None, - }) -} - -fn scalar_bin_op(instr: Instruction) -> Option { - int_bin_op(instr).or_else(|| float_bin_op(instr)) -} - -fn scalar_const_32(instr: Instruction, op_instr: Instruction) -> Option { - match instr { - Instruction::Const32(c) if scalar_bin_op(op_instr).is_some() => Some(c), - _ => None, - } -} - -fn scalar_const_64(instr: Instruction, op_instr: Instruction) -> Option { - match instr { - Instruction::Const64(c) if scalar_bin_op(op_instr).is_some() => Some(c), - _ => None, - } -} - -fn const_128(instr: Instruction, op_instr: Instruction) -> Option { - match instr { - Instruction::Const128(c) if bin_op_128(op_instr).is_some() => Some(c), - _ => None, - } -} - -define_local_source_resolver!( - resolve_local_source_32, - get = LocalGet32, - tee = LocalTee32, - set = LocalSet32, - binop_local_local_tee = BinOpLocalLocalTee32, - binop_local_local_set = BinOpLocalLocalSet32, - binop_local_const_tee = BinOpLocalConstTee32, - binop_local_const_set = BinOpLocalConstSet32, - load_local_tee = LoadLocalTee32, - load_local_set = LoadLocalSet32 -); - -define_local_source_resolver!( - resolve_local_source_64, - get = LocalGet64, - tee = LocalTee64, - set = LocalSet64, - binop_local_local_tee = BinOpLocalLocalTee64, - binop_local_local_set = BinOpLocalLocalSet64, - binop_local_const_tee = BinOpLocalConstTee64, - binop_local_const_set = BinOpLocalConstSet64 -); - -define_local_source_resolver!( - resolve_local_source_128, - get = LocalGet128, - tee = LocalTee128, - set = LocalSet128, - binop_local_local_tee = BinOpLocalLocalTee128, - binop_local_local_set = BinOpLocalLocalSet128, - binop_local_const_tee = BinOpLocalConstTee128, - binop_local_const_set = BinOpLocalConstSet128, - load_local_tee = LoadLocalTee128, - load_local_set = LoadLocalSet128 -); - -fn bin_op_128(instr: Instruction) -> Option { - Some(match instr { - Instruction::V128And => BinOp128::And, - Instruction::V128AndNot => BinOp128::AndNot, - Instruction::V128Or => BinOp128::Or, - Instruction::V128Xor => BinOp128::Xor, - Instruction::I64x2Add => BinOp128::I64x2Add, - Instruction::I64x2Mul => BinOp128::I64x2Mul, - _ => return None, - }) -} - -fn inverse_cmp_op(op: CmpOp) -> CmpOp { - match op { - CmpOp::Eq => CmpOp::Ne, - CmpOp::Ne => CmpOp::Eq, - CmpOp::LtS => CmpOp::GeS, - CmpOp::LtU => CmpOp::GeU, - CmpOp::GtS => CmpOp::LeS, - CmpOp::GtU => CmpOp::LeU, - CmpOp::LeS => CmpOp::GtS, - CmpOp::LeU => CmpOp::GtU, - CmpOp::GeS => CmpOp::LtS, - CmpOp::GeU => CmpOp::LtU, - } -} - -fn resolve_jump_target(instrs: &[Instruction], target: u32) -> u32 { - let mut idx = target as usize; - let mut steps = 0usize; - - while let Some(Instruction::Jump(next)) = instrs.get(idx) - && steps < instrs.len() - { - idx = *next as usize; - steps += 1; - } - - idx as u32 -} - -fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> { - Some(match instr { - Instruction::Jump(ip) - | Instruction::JumpIfZero32(ip) - | Instruction::JumpIfNonZero32(ip) - | Instruction::JumpIfZero64(ip) - | Instruction::JumpIfNonZero64(ip) - | Instruction::JumpIfRefNull(ip) - | Instruction::JumpIfRefNonNull(ip) - | Instruction::BrOnCast(ip, _, _) - | Instruction::JumpCmpStackConst32 { target_ip: ip, .. } - | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } - | Instruction::JumpCmpStackLocal32 { target_ip: ip, .. } - | Instruction::JumpCmpStackLocal64 { target_ip: ip, .. } - | Instruction::BinOpLocalConstJump32 { target_ip: ip, .. } - | Instruction::BinOpLocalConstJumpCmpLocal32 { target_ip: ip, .. } - | Instruction::BinOpStackConstTeeLocalJump32 { target_ip: ip, .. } - | Instruction::BinOpGlobalConstJump32 { target_ip: ip, .. } - | Instruction::IncLocalJump32 { target_ip: ip, .. } - | Instruction::IncStackTeeLocalJump32 { target_ip: ip, .. } - | Instruction::IncGlobalJump32 { target_ip: ip, .. } - | Instruction::IncLocalJumpCmpLocal32 { target_ip: ip, .. } - | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } - | Instruction::JumpIfLocalNonZero32 { target_ip: ip, .. } - | Instruction::JumpIfLocalZero64 { target_ip: ip, .. } - | Instruction::JumpIfLocalNonZero64 { target_ip: ip, .. } - | Instruction::JumpCmpLocalConst32 { target_ip: ip, .. } - | Instruction::JumpCmpLocalConst64 { target_ip: ip, .. } - | Instruction::JumpCmpLocalLocal32 { target_ip: ip, .. } - | Instruction::JumpCmpLocalLocal64 { target_ip: ip, .. } => ip, - Instruction::BranchTable(ip, _, _) => ip, - _ => return None, - }) -} - -fn instruction_target(instr: &Instruction) -> Option { - let mut instr = *instr; - instruction_target_mut(&mut instr).copied() -} - -fn canonicalize_jump_like(source: &[Instruction], instrs: &mut Vec, idx: usize, fallthrough: u32) { - let Some(target) = instruction_target(&instrs[idx]) else { - return; - }; - - canonicalize_jump_like_with_target(instrs, idx, resolve_jump_target(source, target), fallthrough); -} - -fn canonicalize_jump_like_with_target(instrs: &mut Vec, idx: usize, target: u32, fallthrough: u32) { - if matches!(instrs[idx], Instruction::Jump(_)) && target == fallthrough { - instrs.truncate(idx); - } else if let Some(ip) = instruction_target_mut(&mut instrs[idx]) { - *ip = target; - } -} - -fn is_unconditional_terminator(instr: Instruction) -> bool { - matches!( - instr, - Instruction::Unreachable - | Instruction::Jump(_) - | Instruction::BranchTable(..) - | Instruction::Return - | Instruction::ReturnVoid - | Instruction::Return32 - | Instruction::Return64 - | Instruction::Return128 - | Instruction::ReturnCall(_) - | Instruction::ReturnCallSelf - | Instruction::ReturnCallIndirect(..) - | Instruction::ReturnCallRef(_) - | Instruction::Throw(_) - | Instruction::ThrowRef - ) -} - -fn target_boundaries(instructions: &[Instruction], function_data: &WasmFunctionData) -> Result> { - let mut boundaries = alloc::vec![false; instructions.len() + 1]; - for handler in &function_data.exception_handlers { - for target in [handler.start_ip, handler.end_ip] { - let boundary = boundaries.get_mut(target as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) - })?; - *boundary = true; - } - for catch in &handler.catches { - let target = catch.landing_pad(); - let boundary = boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))?; - *boundary = true; - } - } - for instr in instructions { - if let Some(target) = instruction_target(instr) { - let boundary = boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?; - *boundary = true; - } - if let Instruction::BranchTable(_, start, count) = *instr { - let end = - start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; - let targets = function_data - .branch_table_targets - .get(start as usize..end as usize) - .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; - for &target in targets { - let boundary = boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("branch table target out of bounds: {target}")))?; - *boundary = true; - } - } - } - Ok(boundaries) -} - -/// Remaps rewritten targets, then validates targets and ranges while detecting local memory use. -fn finalize( - instructions: &mut [Instruction], - function_data: &mut WasmFunctionData, - old_to_new: Option<&[u32]>, - imported_memory_count: u32, -) -> Result { - let len = instructions.len() as u32; - for handler in &mut function_data.exception_handlers { - if let Some(old_to_new) = old_to_new { - handler.start_ip = *old_to_new.get(handler.start_ip as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.start_ip)) - })?; - handler.end_ip = *old_to_new.get(handler.end_ip as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.end_ip)) - })?; - for catch in &mut handler.catches { - let landing_pad = match catch { - tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } - | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, - }; - *landing_pad = *old_to_new.get(*landing_pad as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception landing pad out of bounds: {landing_pad}")) - })?; - } - } - if handler.start_ip > handler.end_ip || handler.end_ip > len { - return Err(ParseError::Other("exception handler range out of bounds".into())); - } - if handler.catches.iter().any(|catch| catch.landing_pad() >= len) { - return Err(ParseError::Other("exception landing pad out of bounds".into())); - } - } - for target in &mut function_data.branch_table_targets { - if let Some(old_to_new) = old_to_new { - *target = *old_to_new - .get(*target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?; - } - if *target >= len { - return Err(ParseError::Other(alloc::format!("branch table target out of bounds: {target}"))); - } - } - - let mut uses_local_memory = false; - for instr in instructions { - if let Some(target) = instruction_target_mut(instr) { - if let Some(old_to_new) = old_to_new { - *target = *old_to_new - .get(*target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?; - } - if *target >= len { - return Err(ParseError::Other(alloc::format!("instruction target out of bounds: {target}"))); - } - } - if let Instruction::BranchTable(_, start, count) = *instr { - let end = - start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; - function_data - .branch_table_targets - .get(start as usize..end as usize) - .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; - } - uses_local_memory |= instr.memory_addr().is_some_and(|mem| mem >= imported_memory_count); - } - Ok(uses_local_memory) -} diff --git a/crates/parser/src/optimize/mod.rs b/crates/parser/src/optimize/mod.rs new file mode 100644 index 0000000..09501f9 --- /dev/null +++ b/crates/parser/src/optimize/mod.rs @@ -0,0 +1,4 @@ +mod rewrite; +mod targets; + +pub(crate) use rewrite::optimize_instructions; diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs new file mode 100644 index 0000000..1146da7 --- /dev/null +++ b/crates/parser/src/optimize/rewrite.rs @@ -0,0 +1,1397 @@ +use super::targets::{finalize, resolve_jump_target, set_rewrite_target, target_boundaries}; +use crate::macros::optimize::{replace, rewrite}; +use crate::visit::FunctionDataBuilder as WasmFunctionData; +use crate::{ParserOptions, Result}; +use alloc::vec::Vec; +use core::ops::{Deref, DerefMut}; +use tinywasm_types::{ + BinOp, BinOp128, CmpOp, CompactMemoryArg, GlobalConst32, GlobalConst64, GlobalUpdate, GlobalV128, I32LocalArg, + I64Operand, Instruction, LocalConst64, LocalConstCmp, LocalConstSet32, LocalConstSet64, LocalConstSetV128, + LocalLocalCmp, LocalTripleArg, LocalU32, LocalUpdate, LocalUpdateCmp, LocalV128, MemoryArg, MemoryFillConstOp, + MemoryLocalArg, OperandIdx, PackedOp, StackConst32, StackConst64, TargetLocal, TargetLocalArg, V128Operand, + ValueCounts, +}; + +pub(crate) struct OptimizeResult { + pub(crate) instructions: Vec, +} + +struct CompactOutput { + instructions: Vec, + block_start: usize, +} + +macro_rules! operand { + ($data:expr, $value:expr) => { + $data.push_operand($value) + }; +} + +macro_rules! target_operand { + ($data:expr, $value:expr) => { + $data.push_target_operand($value) + }; +} + +impl Deref for CompactOutput { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.instructions + } +} + +impl DerefMut for CompactOutput { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.instructions + } +} + +pub(crate) fn optimize_instructions( + mut instructions: Vec, + function_data: &mut WasmFunctionData, + options: &ParserOptions, + function_results: ValueCounts, + self_func_addr: u32, +) -> Result { + let boundaries = target_boundaries(&instructions, function_data)?; + let (rewritten, old_to_new) = if options.optimize_rewrite() { + let (instructions, map) = rewrite(instructions, function_data, &boundaries, function_results, self_func_addr)?; + (instructions, Some(map)) + } else { + (instructions, None) + }; + instructions = rewritten; + finalize(&mut instructions, function_data, old_to_new.as_deref())?; + Ok(OptimizeResult { instructions }) +} + +fn rewrite( + source: Vec, + data: &mut WasmFunctionData, + boundaries: &[bool], + function_results: ValueCounts, + self_func_addr: u32, +) -> Result<(Vec, Vec)> { + #![allow(unused_assignments)] + use Instruction::*; + + let return_instruction = match function_results { + ValueCounts { c32: 0, c64: 0, c128: 0 } => Some(ReturnVoid), + ValueCounts { c32: 1, c64: 0, c128: 0 } => Some(Return32), + ValueCounts { c32: 0, c64: 1, c128: 0 } => Some(Return64), + ValueCounts { c32: 0, c64: 0, c128: 1 } => Some(Return128), + _ => None, + }; + let mut output = CompactOutput { instructions: Vec::with_capacity(source.len()), block_start: 0 }; + let mut old_to_new = alloc::vec![0; source.len() + 1]; + let mut after_terminator = false; + + for (old_index, instruction) in source.iter().copied().enumerate() { + if boundaries[old_index] || after_terminator { + output.block_start = output.len(); + } + after_terminator = is_unconditional_terminator(instruction); + old_to_new[old_index] = output.len() as u32; + output.push(instruction); + let mut read = output.len() - 1; + + match output[read] { + LocalCopy32(a, b) | LocalCopy64(a, b) | LocalCopy128(a, b) if a == b => { + output.pop(); + } + Call(address) if address == self_func_addr => output[read] = CallSelf, + ReturnCall(address) if address == self_func_addr => output[read] = ReturnCallSelf, + Return if let Some(specialized) = return_instruction => output[read] = specialized, + raw @ (I32Add | I32Mul | I32And | I32Or | I32Xor) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + if rewrite_scalar_const32(&mut output, &mut read, data, op, true)? { + continue; + } + if op == BinOp::IAdd { + rewrite!(output, read, [Const32(value)] => AddConst32(value)); + rewrite!(output, read, [I32Add] => I32Add3); + if read > output.block_start + && let BinOpStackLocal32(BinOp::IAdd, local) = output[read - 1] + { + output.truncate(read - 1); + output.extend([LocalGet32(local), I32Add3]); + read = output.len() - 1; + } + } + } + raw @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + if rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { + continue; + } + rewrite_sign_extend32(&mut output, &mut read, data, op); + } + raw @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); + if rewrite_scalar_const64(&mut output, &mut read, data, op, true)? { + continue; + } + if op == BinOp::IAdd { + rewrite!(output, read, [Const64(index)] => AddConst64(index)); + rewrite!(output, read, [I64Add] => I64Add3); + } + } + raw @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); + if rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { + continue; + } + rewrite_sign_extend64(&mut output, &mut read, data, op); + } + raw if cmp_op(raw).is_some() => { + let op = cmp_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => CmpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => CmpLocalLocal64(op, a, b)); + } + raw @ (F32Add | F32Mul | F32Min | F32Max) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + rewrite_scalar_const32(&mut output, &mut read, data, op, true)?; + } + raw @ (F32Sub | F32Div | F32Copysign) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + rewrite_scalar_const32(&mut output, &mut read, data, op, false)?; + } + raw @ (F64Add | F64Mul | F64Min | F64Max) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite_scalar_const64(&mut output, &mut read, data, op, true)?; + } + raw @ (F64Sub | F64Div | F64Copysign) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite_scalar_const64(&mut output, &mut read, data, op, false)?; + } + raw @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul | V128AndNot) => { + let op = bin_op_128(raw).unwrap(); + rewrite!(output, read, [LocalGet128(local)] => + BinOpStackLocal128(op, local) + ); + rewrite_vector_binop(&mut output, &mut read, data, op, raw != V128AndNot)?; + } + I32Store(index) | F32Store(index) => rewrite_store32(&mut output, &mut read, data, index)?, + I64Store(index) | F64Store(index) => rewrite_store64(&mut output, &mut read, data, index)?, + V128Store(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, + [LocalGet32(addr), LocalGet128(value)] if + (let (Ok(addr), Ok(value)) = (u8::try_from(addr), u8::try_from(value))) => + StoreLocalLocal128(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value }) + ); + } + } + I32Load(index) | F32Load(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => + LoadLocal32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) + ); + } + } + I64Load(index) | F64Load(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => + LoadLocal64(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) + ); + } + } + raw @ (I32Load8S(index) | I32Load8U(index) | I32Load16S(index) | I32Load16U(index)) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => match raw { + I32Load8S(_) => LoadLocal8S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load8U(_) => LoadLocal8U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load16S(_) => LoadLocal16S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load16U(_) => LoadLocal16U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + _ => unreachable!(), + } + ); + } + } + MemoryFill(memory) => rewrite!(output, read, [Const32(value), Const32(size)] => { + let index = operand!(data, MemoryFillConstOp { memory, byte: value as u8, value: size })?; + replace!(output, read, 2 => MemoryFillConst(index)); + }), + GlobalGet32(dst) => rewrite!(output, read, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), + GlobalGet64(dst) => rewrite!(output, read, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), + GlobalGet128(dst) => rewrite!(output, read, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), + LocalGet32(dst) => rewrite!(output, read, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), + LocalGet64(dst) => rewrite!(output, read, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), + LocalGet128(dst) => rewrite!(output, read, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), + LocalSet32(dst) => rewrite_local_set32(&mut output, &mut read, data, dst)?, + LocalSet64(dst) => rewrite_local_set64(&mut output, &mut read, data, dst)?, + LocalSet128(dst) => rewrite_local_set128(&mut output, &mut read, data, dst)?, + LocalTee32(dst) => rewrite_local_tee32(&mut output, &mut read, data, dst)?, + LocalTee64(dst) => rewrite_local_tee64(&mut output, &mut read, data, dst)?, + LocalTee128(dst) => rewrite_local_tee128(&mut output, &mut read, data, dst)?, + Drop32 => { + rewrite!(output, read, [LocalTee32(local)] => LocalSet32(local)); + rewrite!(output, read, [BinOpStackLocalTee32(op, local, dst)] => BinOpStackLocalSet32(op, local, dst)); + rewrite!(output, read, [AddLocalLocalTee32(arg)] => AddLocalLocalSet32(arg)); + rewrite!(output, read, [BinOpLocalLocalTee32(packed)] => BinOpLocalLocalSet32(packed)); + rewrite!(output, read, [BinOpLocalConstTee32(packed)] => BinOpLocalConstSet32(packed)); + } + Drop64 => { + rewrite!(output, read, [LocalTee64(local)] => LocalSet64(local)); + rewrite!(output, read, [BinOpLocalLocalTee64(packed)] => BinOpLocalLocalSet64(packed)); + rewrite!(output, read, [BinOpLocalConstTee64(packed)] => BinOpLocalConstSet64(packed)); + } + Drop128 => { + rewrite!(output, read, [LocalTee128(local)] => LocalSet128(local)); + rewrite!(output, read, [BinOpLocalLocalTee128(packed)] => BinOpLocalLocalSet128(packed)); + rewrite!(output, read, [BinOpLocalConstTee128(packed)] => BinOpLocalConstSet128(packed)); + } + Jump(target) => rewrite_jump(&source, &mut output, read, data, old_index as u32, target)?, + JumpIfZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, true)?, + JumpIfNonZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, false)?, + JumpIfZero64(target) => { + rewrite!(output, read, [LocalGet64(local)] => + JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + ); + } + JumpIfNonZero64(target) => { + rewrite!(output, read, [LocalGet64(local)] => + JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + ); + } + JumpCmpStackConst32(_) + | JumpCmpStackConst64(_) + | JumpCmpLocalConst32(_) + | JumpCmpLocalConst64(_) + | JumpCmpLocalLocal32(_) + | JumpCmpLocalLocal64(_) + | JumpIfLocalZero32(_) + | JumpIfLocalNonZero32(_) + | JumpIfLocalZero64(_) + | JumpIfLocalNonZero64(_) => {} + _ => {} + } + } + for instruction in &mut output.instructions { + match *instruction { + Instruction::Const64(index) => { + let value = data.operand(index).value; + if value == i64::from(value as i32) { + *instruction = Instruction::Const64Imm(value as i32); + } + } + Instruction::Const128(index) => { + let value = u128::from_le_bytes(data.operand(index).value); + if let Ok(value) = u32::try_from(value) { + *instruction = Instruction::Const128Imm(value); + } + } + _ => {} + } + } + let end = old_to_new.len() - 1; + old_to_new[end] = output.len() as u32; + Ok((output.instructions, old_to_new)) +} + +fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i32)> { + match instruction { + Instruction::AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)), + Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), + Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), + Instruction::BinOpLocalConst32(packed) => { + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value as i32)) + } + _ => None, + } +} + +fn local_const64(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i64)> { + let Instruction::BinOpLocalConst64(packed) = instruction else { return None }; + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value as i64)) +} + +fn local_const128( + data: &WasmFunctionData, + instruction: Instruction, +) -> Option<(BinOp128, u16, OperandIdx)> { + let Instruction::BinOpLocalConst128(packed) = instruction else { return None }; + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value)) +} + +fn compact_memory_arg( + data: &mut WasmFunctionData, + index: OperandIdx, +) -> Result>> { + let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) else { return Ok(None) }; + Ok(Some(operand!(data, arg)?)) +} + +fn rewrite_scalar_const32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp, + commutative: bool, +) -> Result { + if *read < output.block_start + 2 { + return Ok(false); + } + let previous = &output[*read - 2..*read]; + let replacement = match previous { + [Instruction::LocalGet32(local), Instruction::Const32(value)] => { + let arg = I32LocalArg { value: *value, local: *local }; + match op { + BinOp::IAdd => Instruction::AddLocalConst32(arg), + BinOp::ISub => Instruction::SubLocalConst32(arg), + BinOp::IMul => Instruction::MulLocalConst32(arg), + _ => Instruction::BinOpLocalConst32(PackedOp::new( + op, + operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + )), + } + } + [Instruction::GlobalGet32(global), Instruction::Const32(value)] => Instruction::BinOpGlobalConst32( + PackedOp::new(op, operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?), + ), + [Instruction::Const32(value), Instruction::LocalGet32(local)] if commutative => { + let arg = I32LocalArg { value: *value, local: *local }; + match op { + BinOp::IAdd => Instruction::AddLocalConst32(arg), + BinOp::IMul => Instruction::MulLocalConst32(arg), + _ => Instruction::BinOpLocalConst32(PackedOp::new( + op, + operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + )), + } + } + [Instruction::Const32(value), Instruction::GlobalGet32(global)] if commutative => { + Instruction::BinOpGlobalConst32(PackedOp::new( + op, + operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?, + )) + } + _ => return Ok(false), + }; + replace!(output, *read, 2 => replacement); + Ok(true) +} + +fn rewrite_scalar_const64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp, + commutative: bool, +) -> Result { + if *read < output.block_start + 2 { + return Ok(false); + } + let previous = [output[*read - 2], output[*read - 1]]; + let replacement = match previous { + [Instruction::LocalGet64(local), Instruction::Const64(index)] => Instruction::BinOpLocalConst64(PackedOp::new( + op, + operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?, + )), + [Instruction::GlobalGet64(global), Instruction::Const64(index)] => Instruction::BinOpGlobalConst64( + PackedOp::new(op, operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?), + ), + [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => Instruction::BinOpLocalConst64( + PackedOp::new(op, operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?), + ), + [Instruction::Const64(index), Instruction::GlobalGet64(global)] if commutative => { + Instruction::BinOpGlobalConst64(PackedOp::new( + op, + operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?, + )) + } + _ => return Ok(false), + }; + replace!(output, *read, 2 => replacement); + Ok(true) +} + +fn rewrite_sign_extend32(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { + if op != BinOp::IShrS || *read < output.block_start + 2 { + return false; + } + if let Some((BinOp::IShl, local, shift)) = local_const32(data, output[*read - 2]) + && let Instruction::Const32(right) = output[*read - 1] + && shift == right + && matches!(shift, 16 | 24) + { + output.truncate(*read - 2); + output.extend([ + Instruction::LocalGet32(local), + if shift == 24 { Instruction::I32Extend8S } else { Instruction::I32Extend16S }, + ]); + *read = output.len() - 1; + return true; + } + false +} + +fn rewrite_sign_extend64(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { + if op != BinOp::IShrS || *read < output.block_start + 2 { + return false; + } + if let Some((BinOp::IShl, local, shift)) = local_const64(data, output[*read - 2]) + && let Instruction::Const64(index) = output[*read - 1] + && shift == data.operand(index).value + { + let instruction = match shift { + 56 => Instruction::I64Extend8S, + 48 => Instruction::I64Extend16S, + 32 => Instruction::I64Extend32S, + _ => return false, + }; + output.truncate(*read - 2); + output.extend([Instruction::LocalGet64(local), instruction]); + *read = output.len() - 1; + return true; + } + false +} + +fn rewrite_vector_binop( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp128, + commutative: bool, +) -> Result<()> { + if *read >= output.block_start + 2 { + let previous = [output[*read - 2], output[*read - 1]]; + let replacement = match previous { + [Instruction::LocalGet128(a), Instruction::LocalGet128(b)] => Instruction::BinOpLocalLocal128(op, a, b), + [Instruction::LocalGet128(local), Instruction::Const128(value)] => { + Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) + } + [Instruction::GlobalGet128(global), Instruction::Const128(value)] => { + Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + } + [Instruction::Const128(value), Instruction::LocalGet128(local)] if commutative => { + Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) + } + [Instruction::Const128(value), Instruction::GlobalGet128(global)] if commutative => { + Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + } + _ => return Ok(()), + }; + replace!(output, *read, 2 => replacement); + } + Ok(()) +} + +fn rewrite_store32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + index: OperandIdx, +) -> Result<()> { + let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + if *read >= output.block_start + 3 { + let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; + if let [ + Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), + Instruction::LoadLocal32(arg), + Instruction::AddConst32(1), + ] = previous + && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && addr == u16::from(arg.local1) + { + replace!(output, *read, 3 => Instruction::IncMemoryLocal32(arg)); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + let previous = [output[*read - 2], output[*read - 1]]; + match previous { + [Instruction::F32Mul, Instruction::F32Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => Instruction::FMaStoreF32(arg)); + } + [Instruction::BinOpStackLocal32(BinOp::FMul, local), Instruction::F32Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => [Instruction::LocalGet32(local), Instruction::FMaStoreF32(arg)]); + } + [Instruction::LocalGet32(addr), Instruction::LocalGet32(value)] + if let (Ok(addr), Ok(value), Some(memory_arg)) = + (u8::try_from(addr), u8::try_from(value), compact_arg) => + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::StoreLocalLocal32(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_store64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + index: OperandIdx, +) -> Result<()> { + let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + if *read >= output.block_start + 3 { + let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; + if let [ + Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), + Instruction::LoadLocal64(arg), + Instruction::Const64(one), + ] = previous + && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && addr == u16::from(arg.local1) + && data.operand(one).value == 1 + { + replace!(output, *read, 3 => Instruction::IncMemoryLocal64(arg)); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::F64Mul, Instruction::F64Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => Instruction::FMaStoreF64(arg)); + } + [Instruction::LocalGet32(addr), Instruction::LocalGet64(value)] + if let (Ok(addr), Ok(value), Some(memory_arg)) = + (u8::try_from(addr), u8::try_from(value), compact_arg) => + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::StoreLocalLocal64(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); + } + _ => {} + } + } + Ok(()) +} + +macro_rules! local_const_set { + ($data:expr, 32, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSet32 { local: $src, dst: $dst, value: $value as u32 })?; + if $tee { + Instruction::BinOpLocalConstTee32(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet32(PackedOp::new($op, index)) + } + }}; + ($data:expr, 64, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSet64 { local: $src, dst: $dst, value: $value as u64 })?; + if $tee { + Instruction::BinOpLocalConstTee64(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet64(PackedOp::new($op, index)) + } + }}; + ($data:expr, 128, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSetV128 { local: $src, dst: $dst, value: $value })?; + if $tee { + Instruction::BinOpLocalConstTee128(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet128(PackedOp::new($op, index)) + } + }}; +} + +fn rewrite_local_set32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::I32Mul, Instruction::BinOpStackLocal32(BinOp::IAdd, acc)] if acc == dst => { + replace!(output, *read, 2 => Instruction::MulAccLocal32(dst)); + return Ok(()); + } + [Instruction::F32Mul, Instruction::BinOpStackLocal32(BinOp::FAdd, acc)] if acc == dst => { + replace!(output, *read, 2 => Instruction::FMulAccLocal32(dst)); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet32(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet32(src) => replace!(output, *read, 1 => Instruction::LocalCopy32(src, dst)), + Instruction::Const32(value) => { + replace!(output, *read, 1 => Instruction::SetLocalConst32(I32LocalArg { value, local: dst })) + } + Instruction::BinOpLocalLocal32(op, left, right) => { + let replacement = if op == BinOp::IAdd { + Instruction::AddLocalLocalSet32(LocalTripleArg { left, right, dst }) + } else { + Instruction::BinOpLocalLocalSet32(PackedOp::new( + op, + operand!(data, LocalTripleArg { left, right, dst })?, + )) + }; + replace!(output, *read, 1 => replacement); + } + instruction if let Some((op, src, value)) = local_const32(data, instruction) => { + if src == dst + && let Some(delta) = op.inc_delta(value) + { + replace!(output, *read, 1 => Instruction::IncLocal32(I32LocalArg { value: delta, local: dst })); + } else { + let replacement = local_const_set!(data, 32, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + } + Instruction::BinOpStackLocal32(op, local) => { + replace!(output, *read, 1 => Instruction::BinOpStackLocalSet32(op, local, dst)); + } + Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet32(arg)); + } + Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet8S32(arg)); + } + Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet8U32(arg)); + } + Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet16S32(arg)); + } + Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet16U32(arg)); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_set64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 3 { + match [output[*read - 3], output[*read - 2], output[*read - 1]] { + [Instruction::I64Mul, Instruction::LocalGet64(acc), Instruction::I64Add] if acc == dst => { + replace!(output, *read, 3 => Instruction::MulAccLocal64(dst)); + return Ok(()); + } + [Instruction::F64Mul, Instruction::LocalGet64(acc), Instruction::F64Add] if acc == dst => { + replace!(output, *read, 3 => Instruction::FMulAccLocal64(dst)); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet64(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet64(src) => replace!(output, *read, 1 => Instruction::LocalCopy64(src, dst)), + Instruction::Const64(index) => { + replace!(output, *read, 1 => Instruction::SetLocalConst64(PackedOp::new(dst, index))); + } + Instruction::BinOpLocalLocal64(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet64(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const64(data, instruction) => { + if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) { + let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() }; + let index = operand!(data, I64Operand { value: delta })?; + replace!(output, *read, 1 => Instruction::IncLocal64(PackedOp::new(dst, index))); + } else { + let replacement = local_const_set!(data, 64, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_set128( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 + && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] + && let (Ok(local), Ok(dst), Ok(memory_arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::LoadLocalSet128(MemoryLocalArg { + memory_arg_idx, + local1: local, + local2: dst, + })); + return Ok(()); + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet128(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet128(src) => replace!(output, *read, 1 => Instruction::LocalCopy128(src, dst)), + Instruction::Const128(value) => { + replace!(output, *read, 1 => Instruction::SetLocalConst128(PackedOp::new(dst, value))) + } + Instruction::BinOpLocalLocal128(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet128(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const128(data, instruction) => { + let replacement = local_const_set!(data, 128, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::Const32(value), Instruction::I32And] => { + replace!(output, *read, 2 => Instruction::AndConstTee32(I32LocalArg { value, local: dst })); + return Ok(()); + } + [Instruction::Const32(value), Instruction::I32Sub] => { + replace!(output, *read, 2 => Instruction::SubConstTee32(I32LocalArg { value, local: dst })); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet32(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet32(src)), + Instruction::BinOpLocalLocal32(op, left, right) => { + let replacement = if op == BinOp::IAdd { + Instruction::AddLocalLocalTee32(LocalTripleArg { left, right, dst }) + } else { + Instruction::BinOpLocalLocalTee32(PackedOp::new( + op, + operand!(data, LocalTripleArg { left, right, dst })?, + )) + }; + replace!(output, *read, 1 => replacement); + } + instruction if let Some((op, src, value)) = local_const32(data, instruction) => { + let replacement = local_const_set!(data, 32, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + Instruction::BinOpStackLocal32(op, local) => { + replace!(output, *read, 1 => Instruction::BinOpStackLocalTee32(op, local, dst)); + } + Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee32(arg)); + } + Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee8S32(arg)); + } + Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee8U32(arg)); + } + Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee16S32(arg)); + } + Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee16U32(arg)); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::Const64(value), Instruction::I64And] => { + replace!(output, *read, 2 => Instruction::AndConstTee64(PackedOp::new(dst, value))); + return Ok(()); + } + [Instruction::Const64(value), Instruction::I64Sub] => { + replace!(output, *read, 2 => Instruction::SubConstTee64(PackedOp::new(dst, value))); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)), + Instruction::BinOpLocalLocal64(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee64(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const64(data, instruction) => { + let replacement = local_const_set!(data, 64, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee128( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 + && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] + && let (Ok(local), Ok(dst), Ok(memory_arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::LoadLocalTee128(MemoryLocalArg { + memory_arg_idx, + local1: local, + local2: dst, + })); + return Ok(()); + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet128(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet128(src)), + Instruction::BinOpLocalLocal128(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee128(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const128(data, instruction) => { + let replacement = local_const_set!(data, 128, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn int_bin_op(instruction: Instruction) -> Option { + Some(match instruction { + Instruction::I32Add | Instruction::I64Add => BinOp::IAdd, + Instruction::I32Sub | Instruction::I64Sub => BinOp::ISub, + Instruction::I32Mul | Instruction::I64Mul => BinOp::IMul, + Instruction::I32And | Instruction::I64And => BinOp::IAnd, + Instruction::I32Or | Instruction::I64Or => BinOp::IOr, + Instruction::I32Xor | Instruction::I64Xor => BinOp::IXor, + Instruction::I32Shl | Instruction::I64Shl => BinOp::IShl, + Instruction::I32ShrS | Instruction::I64ShrS => BinOp::IShrS, + Instruction::I32ShrU | Instruction::I64ShrU => BinOp::IShrU, + Instruction::I32Rotl | Instruction::I64Rotl => BinOp::IRotl, + Instruction::I32Rotr | Instruction::I64Rotr => BinOp::IRotr, + _ => return None, + }) +} + +fn float_bin_op(instruction: Instruction) -> Option { + Some(match instruction { + Instruction::F32Add | Instruction::F64Add => BinOp::FAdd, + Instruction::F32Sub | Instruction::F64Sub => BinOp::FSub, + Instruction::F32Mul | Instruction::F64Mul => BinOp::FMul, + Instruction::F32Div | Instruction::F64Div => BinOp::FDiv, + Instruction::F32Min | Instruction::F64Min => BinOp::FMin, + Instruction::F32Max | Instruction::F64Max => BinOp::FMax, + Instruction::F32Copysign | Instruction::F64Copysign => BinOp::FCopysign, + _ => return None, + }) +} + +fn cmp_op(instruction: Instruction) -> Option { + Some(match instruction { + Instruction::I32Eq | Instruction::I64Eq => CmpOp::Eq, + Instruction::I32Ne | Instruction::I64Ne => CmpOp::Ne, + Instruction::I32LtS | Instruction::I64LtS => CmpOp::LtS, + Instruction::I32LtU | Instruction::I64LtU => CmpOp::LtU, + Instruction::I32GtS | Instruction::I64GtS => CmpOp::GtS, + Instruction::I32GtU | Instruction::I64GtU => CmpOp::GtU, + Instruction::I32LeS | Instruction::I64LeS => CmpOp::LeS, + Instruction::I32LeU | Instruction::I64LeU => CmpOp::LeU, + Instruction::I32GeS | Instruction::I64GeS => CmpOp::GeS, + Instruction::I32GeU | Instruction::I64GeU => CmpOp::GeU, + _ => return None, + }) +} + +fn bin_op_128(instruction: Instruction) -> Option { + Some(match instruction { + Instruction::V128And => BinOp128::And, + Instruction::V128AndNot => BinOp128::AndNot, + Instruction::V128Or => BinOp128::Or, + Instruction::V128Xor => BinOp128::Xor, + Instruction::I64x2Add => BinOp128::I64x2Add, + Instruction::I64x2Mul => BinOp128::I64x2Mul, + _ => return None, + }) +} + +fn jump_cmp_local_local( + data: &mut WasmFunctionData, + target: u32, + left: u16, + right: u16, + op: CmpOp, + width64: bool, +) -> Result { + let index = target_operand!(data, LocalLocalCmp { target, left, right })?; + Ok(if width64 { + Instruction::JumpCmpLocalLocal64(PackedOp::new(op, index)) + } else { + Instruction::JumpCmpLocalLocal32(PackedOp::new(op, index)) + }) +} + +fn rewrite_jump( + source: &[Instruction], + output: &mut CompactOutput, + index: usize, + data: &mut WasmFunctionData, + old_index: u32, + target: u32, +) -> Result<()> { + let target = resolve_jump_target(source, data, target); + let exit = old_index + 1; + let body = target + 1; + if let Some(instruction) = source.get(target as usize).copied() { + match instruction { + Instruction::JumpCmpLocalLocal32(side) + if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + { + let value = data.operand(side.index); + output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), false)?; + return Ok(()); + } + Instruction::JumpCmpLocalLocal64(side) + if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + { + let value = data.operand(side.index); + output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), true)?; + return Ok(()); + } + _ => {} + } + } + if matches!(output[index], Instruction::Jump(_)) && target == exit { + output.truncate(index); + } else { + set_rewrite_target(&mut output[index], data, target)?; + } + Ok(()) +} + +fn jump_cmp_stack_local( + data: &mut WasmFunctionData, + target: u32, + local: u16, + op: CmpOp, + width64: bool, +) -> Result { + let index = target_operand!(data, TargetLocal { target, local })?; + Ok(if width64 { + Instruction::JumpCmpStackLocal64(PackedOp::new(op, index)) + } else { + Instruction::JumpCmpStackLocal32(PackedOp::new(op, index)) + }) +} + +fn jump_cmp_local_const32( + data: &mut WasmFunctionData, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result { + if value == 0 { + return Ok(match op { + CmpOp::Eq => Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }), + CmpOp::Ne => Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }), + _ => Instruction::JumpCmpLocalConst32(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + )), + }); + } + Ok(Instruction::JumpCmpLocalConst32(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + ))) +} + +fn jump_cmp_local_const64( + data: &mut WasmFunctionData, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local })), + CmpOp::Ne => return Ok(Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local })), + _ => {} + } + } + Ok(Instruction::JumpCmpLocalConst64(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + ))) +} + +fn jump_cmp_stack_const32(data: &mut WasmFunctionData, target: u32, value: i32, op: CmpOp) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfZero32(target)), + CmpOp::Ne => return Ok(Instruction::JumpIfNonZero32(target)), + _ => {} + } + } + Ok(Instruction::JumpCmpStackConst32(PackedOp::new(op, target_operand!(data, StackConst32 { target, value })?))) +} + +fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, op: CmpOp) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfZero64(target)), + CmpOp::Ne => return Ok(Instruction::JumpIfNonZero64(target)), + _ => {} + } + } + Ok(Instruction::JumpCmpStackConst64(PackedOp::new(op, target_operand!(data, StackConst64 { target, value })?))) +} + +fn update_jump( + data: &mut WasmFunctionData, + target: u32, + immediate: i32, + address: u32, + op: BinOp, + on_zero: bool, + global: bool, +) -> Result { + if let Some(delta) = op.inc_delta(immediate) { + Ok(if global { + Instruction::IncGlobalJump32(target_operand!( + data, + GlobalUpdate { target, value: delta, global: address, on_zero: u8::from(on_zero) } + )?) + } else { + Instruction::IncLocalJump32(target_operand!( + data, + LocalUpdate { target, value: delta, local: address as u16, on_zero: u8::from(on_zero) } + )?) + }) + } else { + Ok(if global { + Instruction::BinOpGlobalConstJump32(PackedOp::new( + op, + target_operand!( + data, + GlobalUpdate { target, value: immediate, global: address, on_zero: u8::from(on_zero) } + )?, + )) + } else { + Instruction::BinOpLocalConstJump32(PackedOp::new( + op, + target_operand!( + data, + LocalUpdate { target, value: immediate, local: address as u16, on_zero: u8::from(on_zero) } + )?, + )) + }) + } +} + +fn rewrite_conditional( + source: &[Instruction], + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + target: u32, + on_zero: bool, +) -> Result<()> { + let target = resolve_jump_target(source, data, target); + if *read > output.block_start + && let Instruction::BinOpLocalConstTee32(packed) = output[*read - 1] + { + let value = data.operand(packed.index); + if value.local == value.dst { + let replacement = + update_jump(data, target, value.value as i32, u32::from(value.local), packed.op, on_zero, false)?; + replace!(output, *read, 1 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 2 + && let [Instruction::BinOpGlobalConst32(packed), Instruction::GlobalTee32(dst)] = + [output[*read - 2], output[*read - 1]] + { + let value = data.operand(packed.index); + if value.global == dst { + let replacement = update_jump(data, target, value.value as i32, dst, packed.op, on_zero, true)?; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 + && let [Instruction::AddConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] = + [output[*read - 3], output[*read - 2], output[*read - 1]] + && local == cond + { + let replacement = Instruction::IncStackTeeLocalJump32(target_operand!( + data, + LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } + )?); + replace!(output, *read, 3 => replacement); + return Ok(()); + } + if *read >= output.block_start + 2 { + let update = match [output[*read - 2], output[*read - 1]] { + [Instruction::AndConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { + Some((arg.local, arg.value, Some(BinOp::IAnd))) + } + [Instruction::SubConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { + Some((arg.local, arg.value.wrapping_neg(), None)) + } + _ => None, + }; + if let Some((local, value, op)) = update { + let replacement = if let Some(op) = op { + Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( + op, + target_operand!(data, LocalUpdate { target, value, local, on_zero: u8::from(on_zero) })?, + )) + } else { + Instruction::IncStackTeeLocalJump32(target_operand!( + data, + LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } + )?) + }; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 + && let [Instruction::BinOpLocalConstTee32(packed), Instruction::LocalGet32(right), raw_cmp] = + [output[*read - 3], output[*read - 2], output[*read - 1]] + && let Some(mut cmp) = cmp_op(raw_cmp) + { + let value = data.operand(packed.index); + if value.local == value.dst { + if on_zero { + cmp = cmp.inverse(); + } + let replacement = if let Some(delta) = packed.op.inc_delta(value.value as i32) { + Instruction::IncLocalJumpCmpLocal32(PackedOp::new( + cmp, + target_operand!(data, LocalUpdateCmp { target, value: delta, local: value.local, right })?, + )) + } else { + Instruction::BinOpLocalConstJumpCmpLocal32(PackedOp::new( + (packed.op, cmp), + target_operand!( + data, + LocalUpdateCmp { target, value: value.value as i32, local: value.local, right } + )?, + )) + }; + replace!(output, *read, 3 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::LocalGet32(local), Instruction::I32Eqz] => { + replace!(output, *read, 2 => + if on_zero { + Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) + } + ); + return Ok(()); + } + [Instruction::LocalGet64(local), Instruction::I64Eqz] => { + replace!(output, *read, 2 => + if on_zero { + Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + } + ); + return Ok(()); + } + [Instruction::CmpLocalLocal32(op, left, right), Instruction::I32Eqz] => { + let op = if on_zero { op } else { op.inverse() }; + let replacement = jump_cmp_local_local(data, target, left, right, op, false)?; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + let previous = output[*read - 1]; + let replacement = match previous { + Instruction::I32Eqz => { + Some(if on_zero { Instruction::JumpIfNonZero32(target) } else { Instruction::JumpIfZero32(target) }) + } + Instruction::I64Eqz => { + Some(if on_zero { Instruction::JumpIfNonZero64(target) } else { Instruction::JumpIfZero64(target) }) + } + Instruction::CmpLocalLocal32(op, left, right) => { + Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, false)?) + } + Instruction::CmpLocalLocal64(op, left, right) => { + Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, true)?) + } + Instruction::LocalGet32(local) => Some(if on_zero { + Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) + }), + Instruction::LocalGet64(local) => Some(if on_zero { + Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + }), + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 1 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 { + let raw_cmp = output[*read - 1]; + if let Some(mut op) = cmp_op(raw_cmp) { + if on_zero { + op = op.inverse(); + } + let replacement = match [output[*read - 3], output[*read - 2]] { + [Instruction::LocalGet32(local), Instruction::Const32(value)] => { + Some(jump_cmp_local_const32(data, target, local, value, op)?) + } + [Instruction::LocalGet64(local), Instruction::Const64(index)] + if let Ok(value) = i32::try_from(data.operand(index).value) => + { + Some(jump_cmp_local_const64(data, target, local, value, op)?) + } + [Instruction::LocalGet32(left), Instruction::LocalGet32(right)] => { + Some(jump_cmp_local_local(data, target, left, right, op, false)?) + } + [Instruction::LocalGet64(left), Instruction::LocalGet64(right)] => { + Some(jump_cmp_local_local(data, target, left, right, op, true)?) + } + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 3 => replacement); + return Ok(()); + } + } + } + if *read >= output.block_start + 2 { + let raw_cmp = output[*read - 1]; + if let Some(mut op) = cmp_op(raw_cmp) { + if on_zero { + op = op.inverse(); + } + let replacement = match output[*read - 2] { + Instruction::LocalGet32(local) => Some(jump_cmp_stack_local(data, target, local, op, false)?), + Instruction::LocalGet64(local) => Some(jump_cmp_stack_local(data, target, local, op, true)?), + Instruction::Const32(value) => Some(jump_cmp_stack_const32(data, target, value, op)?), + Instruction::Const64(index) => { + Some(jump_cmp_stack_const64(data, target, data.operand(index).value, op)?) + } + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + } + Ok(()) +} + +fn is_unconditional_terminator(instruction: Instruction) -> bool { + matches!( + instruction, + Instruction::Unreachable + | Instruction::Jump(_) + | Instruction::BranchTable(_) + | Instruction::Return + | Instruction::ReturnVoid + | Instruction::Return32 + | Instruction::Return64 + | Instruction::Return128 + | Instruction::ReturnCall(_) + | Instruction::ReturnCallSelf + | Instruction::ReturnCallIndirect(_) + | Instruction::ReturnCallRef(_) + | Instruction::Throw(_) + | Instruction::ThrowRef + ) +} diff --git a/crates/parser/src/optimize/targets.rs b/crates/parser/src/optimize/targets.rs new file mode 100644 index 0000000..36bdf2f --- /dev/null +++ b/crates/parser/src/optimize/targets.rs @@ -0,0 +1,290 @@ +use crate::visit::{BuilderRawOperand, FunctionDataBuilder}; +use crate::{ParseError, Result}; +use alloc::vec::Vec; +use tinywasm_types::{ + BranchTableArg, CastBranch, GlobalUpdate, Instruction, LocalConstCmp, LocalLocalCmp, LocalUpdate, LocalUpdateCmp, + OperandIdx, OperandType, PackedOp, StackConst32, StackConst64, TargetLocal, +}; + +pub(super) trait TargetOperand: OperandType { + fn set_target(&mut self, target: u32); +} + +macro_rules! target_operands { + ($($name:ty),+ $(,)?) => {$( + impl TargetOperand for $name { + fn set_target(&mut self, target: u32) { self.target = target; } + } + )+}; +} + +target_operands!( + TargetLocal, + CastBranch, + StackConst32, + StackConst64, + LocalUpdate, + GlobalUpdate, + LocalUpdateCmp, + LocalConstCmp, + LocalLocalCmp, + BranchTableArg, +); + +pub(super) fn resolve_jump_target(instructions: &[Instruction], data: &FunctionDataBuilder, target: u32) -> u32 { + let mut index = target as usize; + let mut steps = 0; + while let Some(instruction) = instructions.get(index) + && let Some(next) = instruction_target(data, *instruction) + && matches!(instruction, Instruction::Jump(_)) + && steps < instructions.len() + { + index = next as usize; + steps += 1; + } + index as u32 +} + +pub(super) fn set_rewrite_target( + instruction: &mut Instruction, + data: &mut FunctionDataBuilder, + target: u32, +) -> Result<()> { + use Instruction::*; + match instruction { + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BrOnCast(index) | BrOnCastFail(index) => *index = push_target_copy(data, *index, target)?, + JumpCmpStackConst32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + JumpCmpStackConst64(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BinOpLocalConstJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + BinOpGlobalConstJump32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => *index = push_target_copy(data, *index, target)?, + IncGlobalJump32(index) => *index = push_target_copy(data, *index, target)?, + IncLocalJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BranchTable(index) => *index = push_target_copy(data, *index, target)?, + _ => set_target(instruction, data, target), + } + Ok(()) +} + +fn push_target_copy( + data: &mut FunctionDataBuilder, + index: OperandIdx, + target: u32, +) -> Result> +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(index); + value.set_target(target); + data.push_target_operand(value) +} + +fn push_packed_target_copy( + data: &mut FunctionDataBuilder, + packed: PackedOp, + target: u32, +) -> Result> +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(packed.index); + value.set_target(target); + Ok(PackedOp::new(packed.op, data.push_target_operand(value)?)) +} + +fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> Option { + use Instruction::*; + Some(match instruction { + Jump(target) + | JumpIfZero32(target) + | JumpIfNonZero32(target) + | JumpIfZero64(target) + | JumpIfNonZero64(target) + | JumpIfRefNull(target) + | JumpIfRefNonNull(target) => target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { + arg.target_ip + } + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand(packed.index).target, + BrOnCast(index) | BrOnCastFail(index) => data.operand(index).target, + JumpCmpStackConst32(packed) => data.operand(packed.index).target, + JumpCmpStackConst64(packed) => data.operand(packed.index).target, + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand(packed.index).target, + BinOpLocalConstJumpCmpLocal32(packed) => data.operand(packed.index).target, + BinOpGlobalConstJump32(packed) => data.operand(packed.index).target, + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand(index).target, + IncGlobalJump32(index) => data.operand(index).target, + IncLocalJumpCmpLocal32(packed) => data.operand(packed.index).target, + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand(packed.index).target, + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand(packed.index).target, + BranchTable(index) => data.operand(index).target, + _ => return None, + }) +} + +fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) { + use Instruction::*; + match instruction { + Jump(value) + | JumpIfZero32(value) + | JumpIfNonZero32(value) + | JumpIfZero64(value) + | JumpIfNonZero64(value) + | JumpIfRefNull(value) + | JumpIfRefNonNull(value) => *value = target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { + arg.target_ip = target + } + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_packed_operand_target(data, *packed, target), + BrOnCast(index) | BrOnCastFail(index) => set_operand_target(data, *index, target), + JumpCmpStackConst32(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpStackConst64(packed) => set_packed_operand_target(data, *packed, target), + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { + set_packed_operand_target(data, *packed, target) + } + BinOpLocalConstJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), + BinOpGlobalConstJump32(packed) => set_packed_operand_target(data, *packed, target), + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_operand_target(data, *index, target), + IncGlobalJump32(index) => set_operand_target(data, *index, target), + IncLocalJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_packed_operand_target(data, *packed, target), + BranchTable(index) => set_operand_target(data, *index, target), + _ => {} + } +} + +fn set_operand_target(data: &mut FunctionDataBuilder, index: OperandIdx, target: u32) +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(index); + value.set_target(target); + data.set_operand(index, value); +} + +fn set_packed_operand_target( + data: &mut FunctionDataBuilder, + packed: PackedOp, + target: u32, +) where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(packed.index); + value.set_target(target); + data.set_operand(packed.index, value); +} + +fn branch_table_range(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(u32, u32)> { + let Instruction::BranchTable(index) = instruction else { return None }; + let operand = data.operand(index); + Some((operand.start, operand.len)) +} + +pub(super) fn target_boundaries(instructions: &[Instruction], data: &FunctionDataBuilder) -> Result> { + let mut boundaries = alloc::vec![false; instructions.len() + 1]; + for handler in &data.exception_handlers { + for target in [handler.start_ip, handler.end_ip] { + *boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) + })? = true; + } + for catch in &handler.catches { + let target = catch.landing_pad(); + *boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))? = + true; + } + } + for &instruction in instructions { + if let Some(target) = instruction_target(data, instruction) { + *boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? = true; + } + if let Some((start, count)) = branch_table_range(data, instruction) { + let end = + start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; + let targets = data + .branch_table_targets + .get(start as usize..end as usize) + .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; + for &target in targets { + *boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("branch table target out of bounds: {target}")) + })? = true; + } + } + } + Ok(boundaries) +} + +fn remap_target(target: u32, old_to_new: Option<&[u32]>, len: u32) -> Result { + let target = if let Some(map) = old_to_new { + *map.get(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? + } else { + target + }; + if target >= len { + return Err(ParseError::Other(alloc::format!("instruction target out of bounds: {target}"))); + } + Ok(target) +} + +pub(super) fn finalize( + instructions: &mut [Instruction], + data: &mut FunctionDataBuilder, + old_to_new: Option<&[u32]>, +) -> Result<()> { + let len = instructions.len() as u32; + for handler in &mut data.exception_handlers { + if let Some(map) = old_to_new { + handler.start_ip = *map + .get(handler.start_ip as usize) + .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; + handler.end_ip = *map + .get(handler.end_ip as usize) + .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; + for catch in &mut handler.catches { + let landing_pad = match catch { + tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } + | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, + }; + *landing_pad = remap_target(*landing_pad, Some(map), len)?; + } + } + if handler.start_ip > handler.end_ip || handler.end_ip > len { + return Err(ParseError::Other("exception handler range out of bounds".into())); + } + } + for target in &mut data.branch_table_targets { + *target = remap_target(*target, old_to_new, len)?; + } + for instruction in instructions { + if let Some(target) = instruction_target(data, *instruction) { + set_target(instruction, data, remap_target(target, old_to_new, len)?); + } + if let Some((start, count)) = branch_table_range(data, *instruction) { + let end = + start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; + data.branch_table_targets + .get(start as usize..end as usize) + .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; + } + } + Ok(()) +} diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs index e0e3858..e29b38f 100644 --- a/crates/parser/src/parallel.rs +++ b/crates/parser/src/parallel.rs @@ -1,4 +1,4 @@ -use crate::module::{FunctionCode, optimize_function_code}; +use crate::module::{OptimizedFunctionCode, optimize_function_code}; use crate::validation::{FuncToValidate, FuncValidatorAllocations, ValidatorResources}; use crate::{ParseError, ParserOptions, Result, conversion}; use alloc::sync::Arc; @@ -64,7 +64,7 @@ fn process_function_job( imported_memory_count: u32, validator_allocs: Option, reader_allocs: OperatorsReaderAllocations, -) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { +) -> Result<(OptimizedFunctionCode, Option, OperatorsReaderAllocations)> { #[cfg(feature = "validate")] let validator = job.func_to_validate.map(|func| func.into_validator(validator_allocs.unwrap_or_default())); #[cfg(not(feature = "validate"))] @@ -74,12 +74,12 @@ fn process_function_job( }; let (code, validator_allocs, reader_allocs) = match job.body { FunctionBodyInput::Borrowed(func) => { - conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx)? + conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx, options)? } FunctionBodyInput::Owned(body) => { let reader = wasmparser::BinaryReader::new(&body.section_bytes[body.body_range], body.body_offset); let func = wasmparser::FunctionBody::new(reader); - conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx)? + conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx, options)? } }; @@ -100,7 +100,7 @@ fn process_chunk<'a>( options: &ParserOptions, imported_func_count: usize, imported_memory_count: u32, -) -> Result> { +) -> Result> { let mut validator_allocs = None; let mut reader_allocs = OperatorsReaderAllocations::default(); let jobs = jobs.into_iter(); @@ -130,7 +130,7 @@ pub(crate) fn process_pending( options: &ParserOptions, imported_func_count: usize, imported_memory_count: u32, -) -> Result> { +) -> Result> { let num_workers = worker_count(options, pending.len()); if num_workers == 1 { return process_chunk(pending, metadata, options, imported_func_count, imported_memory_count); diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index cecbb8c..8315fb5 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -3,10 +3,11 @@ use crate::{ conversion::{convert_heap_type, value_lane}, macros::visit::*, }; -use alloc::{boxed::Box, string::ToString, vec::Vec}; +use alloc::{boxed::Box, collections::BTreeMap, string::ToString, vec::Vec}; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, TableDefinition, TagType, TypeSection, - ValueCounts, ValueLane, WasmFunctionData, + BranchTableArg, CastBranch, ExceptionHandler, Global, I64Operand, Import, ImportKind, Instruction, MemoryArg, + MemoryType, Operand64, Operand128, OperandIdx, OperandType, StorageType, TableDefinition, TagType, TwoU32, + TypeSection, V128Operand, ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -52,19 +53,107 @@ pub(crate) struct ModuleMetadata { aggregate_fields: Vec, } +pub(crate) struct FunctionDataBuilder { + pub(crate) operands64: Vec, + pub(crate) operands128: Vec, + pub(crate) branch_table_targets: Vec, + pub(crate) exception_handlers: Vec, + deduplicate64: Option>, + deduplicate128: Option>, +} + +pub(crate) trait BuilderRawOperand: tinywasm_types::RawOperand + Ord { + fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result; + fn get(builder: &FunctionDataBuilder, index: u32) -> Self; + fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self); +} + +macro_rules! builder_raw_operand { + ($raw:ty, $lane:ident, $map:ident) => { + impl BuilderRawOperand for $raw { + fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result { + if deduplicate && let Some(index) = builder.$map.as_ref().and_then(|map| map.get(&raw)) { + return Ok(*index); + } + let index = u32::try_from(builder.$lane.len()) + .map_err(|_| crate::ParseError::Other("instruction operand index overflow".into()))?; + builder.$lane.push(raw); + if deduplicate && let Some(map) = &mut builder.$map { + map.insert(raw, index); + } + Ok(index) + } + + fn get(builder: &FunctionDataBuilder, index: u32) -> Self { + *builder.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) + } + + fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self) { + *builder.$lane.get_mut(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) = raw; + } + } + }; +} + +builder_raw_operand!(Operand64, operands64, deduplicate64); +builder_raw_operand!(Operand128, operands128, deduplicate128); + +impl FunctionDataBuilder { + pub(crate) fn new(deduplicate_operands: bool) -> Self { + Self { + operands64: Vec::new(), + operands128: Vec::new(), + branch_table_targets: Vec::new(), + exception_handlers: Vec::new(), + deduplicate64: deduplicate_operands.then(BTreeMap::new), + deduplicate128: deduplicate_operands.then(BTreeMap::new), + } + } + + pub(crate) fn push_operand(&mut self, operand: T) -> Result> + where + T::Raw: BuilderRawOperand, + { + ::push(self, operand.encode(), true).map(OperandIdx::new) + } + + pub(crate) fn push_target_operand(&mut self, operand: T) -> Result> + where + T::Raw: BuilderRawOperand, + { + ::push(self, operand.encode(), false).map(OperandIdx::new) + } + + pub(crate) fn operand(&self, index: OperandIdx) -> T + where + T::Raw: BuilderRawOperand, + { + T::decode(::get(self, index.index())) + } + + pub(crate) fn set_operand(&mut self, index: OperandIdx, operand: T) + where + T::Raw: BuilderRawOperand, + { + ::set(self, index.index(), operand.encode()) + } + + pub(crate) fn finish(self) -> WasmFunctionData { + WasmFunctionData { + operands64: self.operands64.into_boxed_slice(), + operands128: self.operands128.into_boxed_slice(), + branch_table_targets: self.branch_table_targets.into_boxed_slice(), + exception_handlers: self.exception_handlers.into_boxed_slice(), + } + } +} + enum AggregateFields { Other, Struct(Box<[ValueLane]>), Array(ValueLane), } -#[derive(Default)] -struct FunctionDataBuilder { - v128_constants: Vec<[u8; 16]>, - branch_table_targets: Vec, - exception_handlers: Vec, -} - pub(crate) struct FunctionBuilder<'a> { instructions: Vec, data: FunctionDataBuilder, @@ -83,13 +172,14 @@ impl<'a> FunctionBuilder<'a> { local_types: Vec, local_addr_map: Vec, body_size: usize, + deduplicate_operands: bool, ) -> Self { Self { local_types, local_addr_map, metadata, instructions: Vec::with_capacity(body_size.min(1024)), - data: FunctionDataBuilder::default(), + data: FunctionDataBuilder::new(deduplicate_operands), control_stack: alloc::vec![ControlFrame { kind: BlockKind::Function, has_else: false, @@ -112,10 +202,18 @@ impl<'a> FunctionBuilder<'a> { &mut self, type_index: u32, field_index: u32, - instruction: fn(u32, u32) -> Instruction, + instruction: fn(OperandIdx) -> Instruction, ) -> Result<()> { let size = self.metadata.struct_field(type_index, field_index)?; - self.emit(&[ValueLane::S32], &[size], instruction(type_index, field_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + self.emit(&[ValueLane::S32], &[size], instruction(operand)) + } + + fn push_operand(&mut self, operand: T) -> Result> + where + T::Raw: BuilderRawOperand, + { + self.data.push_operand(operand) } } @@ -294,17 +392,19 @@ impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> { pub(crate) fn process_operators( body: FunctionBody<'_>, - local_types: Vec, - local_addr_map: Vec, + locals: (Vec, Vec), metadata: &ModuleMetadata, ty_idx: u32, allocs: OperatorsReaderAllocations, -) -> Result<(Vec, WasmFunctionData, OperatorsReaderAllocations)> { + deduplicate_operands: bool, +) -> Result<(Vec, FunctionDataBuilder, OperatorsReaderAllocations)> { + let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); let signature = metadata.signature(ty_idx)?.clone(); - let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size); + let mut builder = + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); while !reader.eof() { let position = reader.original_position(); @@ -319,29 +419,26 @@ pub(crate) fn process_operators( } reader.finish()?; - let data = WasmFunctionData { - v128_constants: builder.data.v128_constants.into_boxed_slice(), - branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), - exception_handlers: builder.data.exception_handlers.into_boxed_slice(), - }; - Ok((builder.instructions, data, reader.into_allocations())) + Ok((builder.instructions, builder.data, reader.into_allocations())) } #[cfg(feature = "validate")] pub(crate) fn process_operators_and_validate( mut validator: FuncValidator, body: FunctionBody<'_>, - local_types: Vec, - local_addr_map: Vec, + locals: (Vec, Vec), metadata: &ModuleMetadata, ty_idx: u32, allocs: OperatorsReaderAllocations, -) -> Result<(Vec, WasmFunctionData, FuncValidatorAllocations, OperatorsReaderAllocations)> { + deduplicate_operands: bool, +) -> Result<(Vec, FunctionDataBuilder, FuncValidatorAllocations, OperatorsReaderAllocations)> { + let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); let signature = metadata.signature(ty_idx)?.clone(); - let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size); + let mut builder = + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); while !reader.eof() { let position = reader.original_position(); @@ -356,12 +453,7 @@ pub(crate) fn process_operators_and_validate( } reader.finish()?; - let data = WasmFunctionData { - v128_constants: builder.data.v128_constants.into_boxed_slice(), - branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), - exception_handlers: builder.data.exception_handlers.into_boxed_slice(), - }; - Ok((builder.instructions, data, validator.into_allocations(), reader.into_allocations())) + Ok((builder.instructions, builder.data, validator.into_allocations(), reader.into_allocations())) } impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { @@ -395,7 +487,6 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fixed [] => [] { visit_data_drop(segment: u32) => DataDrop, visit_elem_drop(segment: u32) => ElemDrop } fixed [] => [S32] { visit_i32_const(value: i32) => Const32, visit_ref_func(function: u32) => RefFunc } - fixed [] => [S64] { visit_i64_const(value: i64) => Const64 } heap false [] => [S32] { visit_ref_null => RefNull } heap false [S32] => [S32] { visit_ref_test_non_null => RefTest, visit_ref_cast_non_null => RefCast, @@ -483,22 +574,10 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { table [] => [Addr] { visit_table_size(table: u32) => TableSize } table [S32, Addr] => [Addr] { visit_table_grow(table: u32) => TableGrow } table [Addr, S32, Addr] => [] { visit_table_fill(table: u32) => TableFill } - table [Addr, S32, S32] => [] { visit_table_init(elem_index: u32, table: u32) => TableInit } fixed [] => [S32] { visit_struct_new_default(type_index: u32) => StructNewDefault } fixed [S32] => [S32] { visit_array_new_default(type_index: u32) => ArrayNewDefault, visit_array_len => ArrayLen, } - fixed [S32, S32] => [S32] { - visit_array_new_data(type_index: u32, data_index: u32) => ArrayNewData, - visit_array_new_elem(type_index: u32, elem_index: u32) => ArrayNewElem, - } - fixed [S32, S32, S32, S32] => [] { - visit_array_init_data(type_index: u32, data_index: u32) => ArrayInitData, - visit_array_init_elem(type_index: u32, elem_index: u32) => ArrayInitElem, - } - fixed [S32, S32, S32, S32, S32] => [] { - visit_array_copy(type_index_dst: u32, type_index_src: u32) => ArrayCopy, - } array_field [Field, S32] => [S32] { visit_array_new(type_index: u32) => ArrayNew } array_field [S32, S32] => [Field] { visit_array_get(type_index: u32) => ArrayGet, visit_array_get_s(type_index: u32) => ArrayGetS, @@ -533,7 +612,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { let size = self.metadata.struct_field(type_index, field_index)?; - self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(type_index, field_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(operand)) } fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { @@ -542,7 +622,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.pop_expect(size)?; } self.push_sizes(&[ValueLane::S32])?; - self.instructions.push(Instruction::ArrayNewFixed(type_index, array_size)); + let operand = self.push_operand(TwoU32 { first: type_index, second: array_size })?; + self.instructions.push(Instruction::ArrayNewFixed(operand)); Ok(()) } @@ -555,7 +636,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let signature = self.metadata.signature(type_index)?.clone(); let mut inputs = signature.params; inputs.push(self.metadata.table_size(table_index)?); - self.emit(&inputs, &signature.results, Instruction::CallIndirect(type_index, table_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + self.emit(&inputs, &signature.results, Instruction::CallIndirect(operand)) } fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { @@ -579,7 +661,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { inputs.push(self.metadata.table_size(table_index)?); self.apply_effect(&inputs, &[])?; self.mark_unreachable(); - self.instructions.push(Instruction::ReturnCallIndirect(type_index, table_index)); + let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + self.instructions.push(Instruction::ReturnCallIndirect(operand)); Ok(()) } @@ -851,7 +934,9 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let header_ip = self.instructions.len(); let branch_table_start = self.data.branch_table_targets.len() as u32; - self.instructions.push(Instruction::BranchTable(0, branch_table_start, len)); + let branch_operand = + self.data.push_target_operand(BranchTableArg { target: 0, start: branch_table_start, len })?; + self.instructions.push(Instruction::BranchTable(branch_operand)); struct PadInfo { depth: u32, @@ -894,8 +979,10 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { .iter() .find(|pad| pad.depth == default_depth) .ok_or_else(|| crate::ParseError::Other("missing default branch table target".into()))?; - if let Instruction::BranchTable(default_ip, _, _) = &mut self.instructions[header_ip] { - *default_ip = default_pad.pad_start as u32; + if let Instruction::BranchTable(index) = self.instructions[header_ip] { + let mut operand = self.data.operand(index); + operand.target = default_pad.pad_start as u32; + self.data.set_operand(index, operand); } for pad in &pads { @@ -921,26 +1008,66 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - self.emit(&[], &[ValueLane::S64], Instruction::Const64(val.bits() as i64)) + let operand = self.push_operand(I64Operand { value: val.bits() as i64 })?; + self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) + } + + fn visit_i64_const(&mut self, value: i64) -> Self::Output { + let operand = self.push_operand(I64Operand { value })?; + self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) } fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - self.emit(&[dst, src, len], &[], Instruction::TableCopy { dst_table, src_table }) + let operand = self.push_operand(TwoU32 { first: dst_table, second: src_table })?; + self.emit(&[dst, src, len], &[], Instruction::TableCopy(operand)) } fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem }) + let operand = self.push_operand(TwoU32 { first: dst_mem, second: src_mem })?; + self.emit(&[dst, src, len], &[], Instruction::MemoryCopy(operand)) } fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Self::Output { let dst = self.metadata.memory_size(memory)?; - self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(data_index, memory)) + let operand = self.push_operand(TwoU32 { first: data_index, second: memory })?; + self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(operand)) + } + + fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Self::Output { + let address = self.metadata.table_size(table)?; + let operand = self.push_operand(TwoU32 { first: elem_index, second: table })?; + self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand)) + } + + fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewData(operand)) + } + + fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewElem(operand)) + } + + fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitData(operand)) + } + + fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitElem(operand)) + } + + fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index_dst, second: type_index_src })?; + self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand)) } fn visit_br_on_cast( @@ -1187,19 +1314,13 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { - self.emit( - &[ValueLane::S128, ValueLane::S128], - &[ValueLane::S128], - Instruction::I8x16Shuffle(self.data.v128_constants.len() as u32), - )?; - self.data.v128_constants.push(lanes); - Ok(()) + let index = self.push_operand(V128Operand { value: lanes })?; + self.emit(&[ValueLane::S128, ValueLane::S128], &[ValueLane::S128], Instruction::I8x16Shuffle(index)) } fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output { - self.emit(&[], &[ValueLane::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?; - self.data.v128_constants.push(*value.bytes()); - Ok(()) + let index = self.push_operand(V128Operand { value: *value.bytes() })?; + self.emit(&[], &[ValueLane::S128], Instruction::Const128(index)) } } @@ -1213,7 +1334,12 @@ impl FunctionBuilder<'_> { self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; let conditional_ip = self.instructions.len(); - self.instructions.push(Instruction::BrOnCast(0, target, branch_on_fail)); + let operand = self.data.push_target_operand(CastBranch { target: 0, ref_type_bits: target.to_bits() })?; + self.instructions.push(if branch_on_fail { + Instruction::BrOnCastFail(operand) + } else { + Instruction::BrOnCast(operand) + }); self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; @@ -1357,10 +1483,15 @@ impl FunctionBuilder<'_> { /// Emits the stack-shaping instruction required by a branch. fn emit_dropkeep(&mut self, base: ValueCounts, keep: ValueCounts) { let target = ValueCounts { c32: base.c32 + keep.c32, c64: base.c64 + keep.c64, c128: base.c128 + keep.c128 }; - if self.lane_counts == target { - return; + if self.lane_counts.c32 != target.c32 { + self.instructions.push(Instruction::DropKeep32 { base: base.c32, keep: keep.c32 }); + } + if self.lane_counts.c64 != target.c64 { + self.instructions.push(Instruction::DropKeep64 { base: base.c64, keep: keep.c64 }); + } + if self.lane_counts.c128 != target.c128 { + self.instructions.push(Instruction::DropKeep128 { base: base.c128, keep: keep.c128 }); } - self.instructions.push(Instruction::DropKeep((base, keep).into())); } fn patch_jump(&mut self, jump_ip: usize, target: usize) { @@ -1369,10 +1500,14 @@ impl FunctionBuilder<'_> { | Instruction::JumpIfZero32(ip) | Instruction::JumpIfNonZero32(ip) | Instruction::JumpIfRefNull(ip) - | Instruction::JumpIfRefNonNull(ip) - | Instruction::BrOnCast(ip, _, _) => { + | Instruction::JumpIfRefNonNull(ip) => { *ip = target as u32; } + Instruction::BrOnCast(index) | Instruction::BrOnCastFail(index) => { + let mut operand = self.data.operand(*index); + operand.target = target as u32; + self.data.set_operand(*index, operand); + } _ => {} } } diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 0bdb474..9da4a7a 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -205,11 +205,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { SelectMulti(counts) => self.store.value_stack.select_multi(*counts), Call(v) => { self.exec_call_direct(*v)?; return Ok(None); } CallSelf => { self.exec_call_self()?; return Ok(None); } - CallIndirect(ty, table) => { self.exec_call_indirect::(*ty, *table)?; return Ok(None); } + CallIndirect(idx) => { self.exec_call_indirect::(*idx)?; return Ok(None); } CallRef(ty) => { self.exec_call_ref::(*ty)?; return Ok(None); } ReturnCall(v) => { if self.exec_return_call_direct(*v)? { return Ok(Some(())); } return Ok(None); } ReturnCallSelf => { self.exec_return_call_self()?; return Ok(None); } - ReturnCallIndirect(ty, table) => { if self.exec_call_indirect::(*ty, *table)? { return Ok(Some(())); } return Ok(None); } + ReturnCallIndirect(idx) => { if self.exec_call_indirect::(*idx)? { return Ok(Some(())); } return Ok(None); } ReturnCallRef(ty) => { if self.exec_call_ref::(*ty)? { return Ok(Some(())); } return Ok(None); } Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } ThrowRef => { self.exec_throw_ref()?; return Ok(None); } @@ -228,79 +228,56 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if !is_non_null { ValueRef::stack_pop(&mut self.store.value_stack); } is_non_null }) { return Ok(None) }, - BrOnCast(ip, ty, on_fail) => if self.exec_ref_matches(*ty) == *on_fail { self.cf.instr_ptr = *ip as usize; return Ok(None); }, - JumpIfLocalZero32 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, *local) == 0) { return Ok(None) }, - JumpIfLocalNonZero32 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, *local) != 0) { return Ok(None) }, - JumpIfLocalZero64 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, *local) == 0) { return Ok(None) }, - JumpIfLocalNonZero64 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, *local) != 0) { return Ok(None) }, - JumpCmpStackConst32 { target_ip, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), *imm, *op)) { return Ok(None) }, - JumpCmpStackConst64 { target_ip, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), *imm, *op)) { return Ok(None) }, - JumpCmpStackLocal32 { target_ip, local, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + BrOnCast(idx) => { let v = idx.get(&self.func.data); if !self.exec_ref_matches(v.ref_type()) { self.cf.instr_ptr = v.target as usize; return Ok(None); } }, + BrOnCastFail(idx) => { let v = idx.get(&self.func.data); if self.exec_ref_matches(v.ref_type()) { self.cf.instr_ptr = v.target as usize; return Ok(None); } }, + JumpIfLocalZero32(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(None) }, + JumpIfLocalNonZero32(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(None) }, + JumpIfLocalZero64(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(None) }, + JumpIfLocalNonZero64(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(None) }, + JumpCmpStackConst32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(None) } }, + JumpCmpStackConst64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(None) } }, + JumpCmpStackLocal32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = i32::stack_pop(&mut self.store.value_stack); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *local), *op) - }) { return Ok(None) }, - JumpCmpStackLocal64 { target_ip, local, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.local), packed.op) + }) { return Ok(None) } }, + JumpCmpStackLocal64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = i64::stack_pop(&mut self.store.value_stack); - cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, *local), *op) - }) { return Ok(None) }, - BinOpLocalConstJump32 { target_ip, local, imm, op, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let value = exec_binop_32(*op, i32::local_get(&self.store.value_stack, cf, *local) as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, cf, *local, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - BinOpLocalConstJumpCmpLocal32 { target_ip, local, imm, binop, right, cmp } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let lhs = exec_binop_32(*binop, i32::local_get(&self.store.value_stack, cf, *local) as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, cf, *local, lhs); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *right), *cmp) - }) { return Ok(None) }, - BinOpStackConstTeeLocalJump32 { target_ip, local, imm, op, on_zero } => { - let value = exec_binop_32(*op, i32::stack_pop(&mut self.store.value_stack) as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); - i32::stack_push(&mut self.store.value_stack, value)?; - if Self::exec_jump_if(&mut self.cf, *target_ip, |_| (value == 0) == *on_zero) { return Ok(None) } - }, - BinOpGlobalConstJump32 { target_ip, global, imm, op, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| { - let global = self.module.resolve_global_addr(*global); - let value = exec_binop_32(*op, i32::global_get(&self.store.state.globals, global) as u32, *imm as u32) as i32; + cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, v.local), packed.op) + }) { return Ok(None) } }, + BinOpLocalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let value = exec_binop_32(op, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(None) } }, + BinOpLocalConstJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let (binop, cmp) = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = exec_binop_32(binop, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), cmp) }) { return Ok(None) } }, + BinOpStackConstTeeLocalJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; let value = exec_binop_32(op, i32::stack_pop(&mut self.store.value_stack) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&mut self.cf, v.target, |_| (value == 0) == (v.on_zero != 0)) { return Ok(None) } }, + BinOpGlobalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |_| { + let global = self.module.resolve_global_addr(v.global); + let value = exec_binop_32(op, i32::global_get(&self.store.state.globals, global) as u32, v.value as u32) as i32; i32::global_set(&mut self.store.state.globals, global, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - IncLocalJump32 { target_ip, local, delta, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let value = i32::local_get(&self.store.value_stack, cf, *local).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, cf, *local, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - IncStackTeeLocalJump32 { target_ip, local, delta, on_zero } => { - let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); - i32::stack_push(&mut self.store.value_stack, value)?; - if Self::exec_jump_if(&mut self.cf, *target_ip, |_| (value == 0) == *on_zero) { return Ok(None) } - }, - IncGlobalJump32 { target_ip, global, delta, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| { - let global = self.module.resolve_global_addr(*global); - let value = i32::global_get(&self.store.state.globals, global).wrapping_add(*delta); + (value == 0) == (v.on_zero != 0) + }) { return Ok(None) } }, + IncLocalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let value = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(None) } }, + IncStackTeeLocalJump32(idx) => { let v = idx.get(&self.func.data); let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&mut self.cf, v.target, |_| (value == 0) == (v.on_zero != 0)) { return Ok(None) } }, + IncGlobalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |_| { + let global = self.module.resolve_global_addr(v.global); + let value = i32::global_get(&self.store.state.globals, global).wrapping_add(v.value); i32::global_set(&mut self.store.state.globals, global, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let lhs = i32::local_get(&self.store.value_stack, cf, *local).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, cf, *local, lhs); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *right), *op) - }) { return Ok(None) }, - JumpCmpLocalConst32 { target_ip, local, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, *local), *imm, *op)) { return Ok(None) }, - JumpCmpLocalConst64 { target_ip, local, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, *local), i64::from(*imm), *op)) { return Ok(None) }, - JumpCmpLocalLocal32 { target_ip, left, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, *left), i32::local_get(&self.store.value_stack, cf, *right), *op)) { return Ok(None) }, - JumpCmpLocalLocal64 { target_ip, left, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, *left), i64::local_get(&self.store.value_stack, cf, *right), *op)) { return Ok(None) }, - DropKeep(drop_keep) => self.exec_drop_keep(*drop_keep), - BranchTable(default_ip, start, len) => { self.exec_branch_table(*default_ip, *start, *len); return Ok(None); } + (value == 0) == (v.on_zero != 0) + }) { return Ok(None) } }, + IncLocalJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), op) }) { return Ok(None) } }, + JumpCmpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.local), v.value, op)) { return Ok(None) } }, + JumpCmpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.local), i64::from(v.value), op)) { return Ok(None) } }, + JumpCmpLocalLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.left), i32::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(None) } }, + JumpCmpLocalLocal64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.left), i64::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(None) } }, + 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) => { self.exec_branch_table(*idx); return Ok(None); } Return => { if self.exec_return() { return Ok(Some(())); } return Ok(None); } ReturnVoid => { if self.exec_return_void() { return Ok(Some(())); } return Ok(None); } Return32 => { if self.exec_return_32() { return Ok(Some(())); } return Ok(None); } Return64 => { if self.exec_return_64() { return Ok(Some(())); } return Ok(None); } Return128 => { if self.exec_return_128() { return Ok(Some(())); } return Ok(None); } - LocalGet32(local_index) => self.store.value_stack.push(Value32::local_get(&self.store.value_stack, &self.cf, *local_index))?, - LocalGet64(local_index) => self.store.value_stack.push(Value64::local_get(&self.store.value_stack, &self.cf, *local_index))?, - LocalGet128(local_index) => self.store.value_stack.push(Value128::local_get(&self.store.value_stack, &self.cf, *local_index))?, + LocalGet32(local_index) => Value32::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, + LocalGet64(local_index) => Value64::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, + LocalGet128(local_index) => Value128::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, LocalSet32(local_index) => exec_op!(local_set_pop Value32, local_index), LocalSet64(local_index) => exec_op!(local_set_pop Value64, local_index), LocalSet128(local_index) => exec_op!(local_set_pop Value128, local_index), @@ -308,9 +285,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), AddConst32(c) => exec_op!(unary i32 => i32, |v| v.wrapping_add(*c)), - AddConst64(c) => exec_op!(unary i64 => i64, |v| v.wrapping_add(*c)), - IncLocal32(local_index, delta) => i32::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta)), - IncLocal64(local_index, delta) => i64::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta )), + AddConst64(idx) => { let c = idx.get(&self.func.data).value; exec_op!(unary i64 => i64, |v| v.wrapping_add(c)); }, + IncLocal32(arg) => i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)), + IncLocal64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); }, I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), MulAccLocal32(acc) => exec_op!(binop_acc_local i32, acc, |a: i32, b| a.wrapping_mul(b), |a: i32, b| a.wrapping_add(b)), @@ -322,59 +299,65 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { BinOpLocalLocal128(op, a, b) => exec_op!(binop_local_local Value128, exec_binop_128, op, a, b), CmpLocalLocal32(op, a, b) => exec_op!(cmp_local_local i32, cmp_i32, op, a, b), CmpLocalLocal64(op, a, b) => exec_op!(cmp_local_local i64, cmp_i64, op, a, b), - BinOpLocalLocalSet32(op, a, b, dst) => exec_op!(binop_local_local_set Value32, exec_binop_32, op, a, b, dst), - BinOpLocalLocalSet64(op, a, b, dst) => exec_op!(binop_local_local_set Value64, exec_binop_64, op, a, b, dst), - BinOpLocalLocalSet128(op, a, b, dst) => exec_op!(binop_local_local_set Value128, exec_binop_128, op, a, b, dst), - BinOpLocalLocalTee32(op, a, b, dst) => exec_op!(binop_local_local_tee Value32, exec_binop_32, op, a, b, dst), - BinOpLocalLocalTee64(op, a, b, dst) => exec_op!(binop_local_local_tee Value64, exec_binop_64, op, a, b, dst), - BinOpLocalLocalTee128(op, a, b, dst) => exec_op!(binop_local_local_tee Value128, exec_binop_128, op, a, b, dst), - BinOpLocalConst32(op, local_index, c) => exec_op!(binop_local_const Value32, exec_binop_32, op, local_index, *c as u32), - BinOpLocalConst64(op, local_index, c) => exec_op!(binop_local_const Value64, exec_binop_64, op, local_index, *c as u64), - BinOpLocalConst128(op, local_index, c) => exec_op!(binop_local_const Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c))), - BinOpGlobalConst32(op, global_index, c) => exec_op!(binop_global_const Value32, exec_binop_32, op, global_index, *c as u32), - BinOpGlobalConst64(op, global_index, c) => exec_op!(binop_global_const Value64, exec_binop_64, op, global_index, *c as u64), - BinOpGlobalConst128(op, global_index, c) => exec_op!(binop_global_const Value128, exec_binop_128, op, global_index, Value128(self.func.data.v128_const(*c))), - BinOpLocalConstSet32(op, local_index, c, dst) => exec_op!(binop_local_const_set Value32, exec_binop_32, op, local_index, *c as u32, dst), - BinOpLocalConstSet64(op, local_index, c, dst) => exec_op!(binop_local_const_set Value64, exec_binop_64, op, local_index, *c as u64, dst), - BinOpLocalConstSet128(op, local_index, c, dst) => exec_op!(binop_local_const_set Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), - BinOpLocalConstTee32(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value32, exec_binop_32, op, local_index, *c as u32, dst), - BinOpLocalConstTee64(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value64, exec_binop_64, op, local_index, *c as u64, dst), - BinOpLocalConstTee128(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), + AddLocalLocalSet32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); }, + AddLocalLocalTee32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); i32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalLocalSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalLocalSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalLocalSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalLocalTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalLocalTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalLocalTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; }, + AddLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_add(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, + SubLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_sub(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, + MulLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_mul(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value32::local_get(&self.store.value_stack, &self.cf, v.local); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, lhs, v.value))?; }, + BinOpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value64::local_get(&self.store.value_stack, &self.cf, v.local); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, lhs, v.value))?; }, + BinOpLocalConst128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::stack_push(&mut self.store.value_stack, value)?; }, + BinOpGlobalConst32(packed) => { let v = packed.index.get(&self.func.data); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, Value32::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; }, + BinOpGlobalConst64(packed) => { let v = packed.index.get(&self.func.data); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, Value64::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; }, + BinOpGlobalConst128(packed) => { let v = packed.index.get(&self.func.data); Value128::stack_push(&mut self.store.value_stack, exec_binop_128(packed.op, Value128::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), Value128(v.value.get(&self.func.data).value)))?; }, + BinOpLocalConstSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalConstTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalConstSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalConstTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalConstSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalConstTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; }, BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index), BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index), BinOpStackLocal32(op, local) => exec_op!(binop_stack_local Value32, exec_binop_32, op, local), BinOpStackLocalSet32(op, local, dst) => exec_op!(binop_stack_local_set Value32, exec_binop_32, op, local, dst), BinOpStackLocalTee32(op, local, dst) => exec_op!(binop_stack_local_tee Value32, exec_binop_32, op, local, dst), - SetLocalConst32(local_index, c) => i32::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), - SetLocalConst64(local_index, c) => i64::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), - SetLocalConst128(local_index, c) => Value128::local_set(&mut self.store.value_stack, &self.cf, *local_index, Value128(self.func.data.v128_const(*c))), - IncMemoryLocal32(m, addr_local) => self.exec_inc_memory_local::(*m, *addr_local, |v| v.wrapping_add(1))?, - IncMemoryLocal64(m, addr_local) => self.exec_inc_memory_local::(*m, *addr_local, |v| v.wrapping_add(1))?, - StoreLocalLocal32(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - StoreLocalLocal64(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - StoreLocalLocal128(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - LoadLocal32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, |v| v)?, - LoadLocal64(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, |v| v)?, - LoadLocal8S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocal8U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocal16S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocal16U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocalTee32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalSet32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalTee8S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee8U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee16S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee16U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet8S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet8U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet16S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - AndConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v & *c); exec_op!(local_tee i32, local_index); } - SubConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(*c)); exec_op!(local_tee i32, local_index); } - AndConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v & *c); exec_op!(local_tee i64, local_index); } - SubConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v.wrapping_sub(*c)); exec_op!(local_tee i64, local_index); } + BinOpStackLocal128(op, local) => exec_op!(binop_stack_local Value128, exec_binop_128, op, local), + SetLocalConst32(arg) => i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, arg.value), + SetLocalConst64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); }, + SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.get(&self.func.data).value)), + IncMemoryLocal32(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?, + IncMemoryLocal64(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?, + StoreLocalLocal32(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, + StoreLocalLocal64(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, + StoreLocalLocal128(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, + LoadLocal32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?, + LoadLocal64(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?, + LoadLocal8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocal8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocal16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocal16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocalTee32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + LoadLocalSet32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + LoadLocalTee8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee128(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + LoadLocalSet128(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + AndConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v & arg.value); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); }, + SubConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(arg.value)); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); }, + AndConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n & v); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); }, + SubConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n.wrapping_sub(v)); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); }, LocalTee32(local_index) => exec_op!(local_tee Value32, local_index), LocalTee64(local_index) => exec_op!(local_tee Value64, local_index), LocalTee128(local_index) => exec_op!(local_tee Value128, local_index), @@ -388,7 +371,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { GlobalTee64(global_index) => exec_op!(global_tee Value64, global_index), GlobalTee128(global_index) => exec_op!(global_tee Value128, global_index), Const32(val) => i32::stack_push(&mut self.store.value_stack, *val)?, - Const64(val) => i64::stack_push(&mut self.store.value_stack, *val)?, + Const64Imm(val) => i64::stack_push(&mut self.store.value_stack, i64::from(*val))?, + Const64(idx) => i64::stack_push(&mut self.store.value_stack, idx.get(&self.func.data).value)?, + 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)), @@ -502,32 +487,32 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { // GC objects StructNew(ty) => self.exec_struct_new(*ty, false)?, StructNewDefault(ty) => self.exec_struct_new(*ty, true)?, - StructGet(ty, field) => self.exec_struct_get(*ty, *field, None)?, - StructGetS(ty, field) => self.exec_struct_get(*ty, *field, Some(true))?, - StructGetU(ty, field) => self.exec_struct_get(*ty, *field, Some(false))?, - StructSet(ty, field) => self.exec_struct_set(*ty, *field)?, + 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(ty, len) => self.exec_array_new_fixed(*ty, *len)?, - ArrayNewData(ty, data) => self.exec_array_new_data(*ty, *data)?, - ArrayNewElem(ty, elem) => self.exec_array_new_elem(*ty, *elem)?, + 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(dst, src) => self.exec_array_copy(*dst, *src)?, - ArrayInitData(ty, data) => self.exec_array_init_data(*ty, *data)?, - ArrayInitElem(ty, elem) => self.exec_array_init_elem(*ty, *elem)?, + 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 { dst_mem, src_mem } => self.exec_memory_copy(*dst_mem, *src_mem)?, + MemoryCopy(idx) => self.exec_memory_copy(*idx)?, MemoryFill(addr) => self.exec_memory_fill(*addr)?, - MemoryFillImm(addr, val, size) => self.exec_memory_fill_imm(*addr, *val, *size)?, - MemoryInit(data_idx, mem_idx) => self.exec_memory_init(*data_idx, *mem_idx)?, + 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(), @@ -535,37 +520,37 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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(elem_idx, table_idx) => self.exec_table_init(*elem_idx, *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 { dst_table, src_table } => self.exec_table_copy(*dst_table, *src_table)?, + TableCopy(idx) => self.exec_table_copy(*idx)?, // Core memory load/store operations - I32Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, - I64Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, - F32Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, - F64Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, + I32Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + I64Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + F32Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + F64Store(idx) => self.exec_mem_store::(*idx, |v| v)?, FMaStoreF32(m) => self.exec_fma_store::(*m)?, FMaStoreF64(m) => self.exec_fma_store::(*m)?, - I32Store8(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i8)?, - I32Store16(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i16)?, - I64Store8(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i8)?, - I64Store16(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i16)?, - I64Store32(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i32)?, - I32Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - I64Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - F32Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - F64Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - I32Load8S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I32Load8U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I32Load16S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I32Load16U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I64Load8S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load8U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load16S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load16U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load32S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load32U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, + I32Store8(idx) => self.exec_mem_store::(*idx, |v| v as i8)?, + I32Store16(idx) => self.exec_mem_store::(*idx, |v| v as i16)?, + I64Store8(idx) => self.exec_mem_store::(*idx, |v| v as i8)?, + I64Store16(idx) => self.exec_mem_store::(*idx, |v| v as i16)?, + I64Store32(idx) => self.exec_mem_store::(*idx, |v| v as i32)?, + I32Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + I64Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + F32Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + F64Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + I32Load8S(idx) => self.exec_mem_load::(*idx, i32::from)?, + I32Load8U(idx) => self.exec_mem_load::(*idx, i32::from)?, + I32Load16S(idx) => self.exec_mem_load::(*idx, i32::from)?, + I32Load16U(idx) => self.exec_mem_load::(*idx, i32::from)?, + I64Load8S(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load8U(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load16S(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load16U(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load32S(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load32U(idx) => self.exec_mem_load::(*idx, i64::from)?, // Numeric conversion operations F32ConvertI32S => exec_op!(unary i32 => f32, |v| v as f32), @@ -637,25 +622,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), - V128Load(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| v)?, - V128Load8x8S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, - V128Load8x8U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, - V128Load16x4S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, - V128Load16x4U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, - V128Load32x2S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, - V128Load32x2U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, - V128Load8Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i8)?, - V128Load16Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i16)?, - V128Load32Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i32)?, - V128Load64Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i64)?, - V128Store(arg) => self.exec_mem_store::(arg.mem_addr(), arg.offset(), |v| v)?, - V128Store8Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Store16Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Store32Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Store64Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load32Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i32x4([v, 0, 0, 0]))?, - V128Load64Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i64x2([v, 0]))?, - Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(self.func.data.v128_const(*arg)))?, + V128Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + V128Load8x8S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, + V128Load8x8U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, + V128Load16x4S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, + V128Load16x4U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, + V128Load32x2S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, + V128Load32x2U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, + V128Load8Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i8)?, + V128Load16Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i16)?, + V128Load32Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i32)?, + V128Load64Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i64)?, + V128Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + V128Store8Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Store16Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Store32Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Store64Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Load32Zero(idx) => self.exec_mem_load::(*idx, |v| Value128::from_i32x4([v, 0, 0, 0]))?, + V128Load64Zero(idx) => self.exec_mem_load::(*idx, |v| Value128::from_i64x2([v, 0]))?, + Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(arg.get(&self.func.data).value))?, I8x16ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), I8x16ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), I16x8ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), @@ -664,10 +649,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64x2ExtractLane(lane) => exec_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), F32x4ExtractLane(lane) => exec_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), F64x2ExtractLane(lane) => exec_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), - V128Load8Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load16Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load32Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load64Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, + V128Load8Lane(arg) => self.exec_mem_load_lane::(*arg)?, + V128Load16Lane(arg) => self.exec_mem_load_lane::(*arg)?, + V128Load32Lane(arg) => self.exec_mem_load_lane::(*arg)?, + V128Load64Lane(arg) => self.exec_mem_load_lane::(*arg)?, I8x16ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), I16x8ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), I32x4ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), @@ -822,7 +807,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64x2ExtendHighI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()), I64x2ExtendHighI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()), I8x16Popcnt => exec_op!(unary Value128 => Value128, |v| v.i8x16_popcnt()), - I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(self.func.data.v128_const(*idx)))), + I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(idx.get(&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)), @@ -900,25 +885,18 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { condition } - fn exec_branch_table(&mut self, default_ip: u32, start: u32, len: u32) { + fn exec_branch_table(&mut self, index: OperandIdx) { + let v = index.get(&self.func.data); let idx = ::stack_pop(&mut self.store.value_stack); - let target_ip = if idx >= 0 && (idx as u32) < len { - self.func.data.branch_table_targets.get((start + idx as u32) as usize).copied().unwrap_or(default_ip) + let target_ip = if idx >= 0 && (idx as u32) < v.len { + self.func.data.branch_table_targets.get((v.start + idx as u32) as usize).copied().unwrap_or(v.target) } else { - default_ip + v.target }; self.cf.instr_ptr = target_ip as usize; } - fn exec_drop_keep(&mut self, drop_keep: DropKeep) { - let mut base = self.cf.stack_base(); - base.s32 += drop_keep.base.c32 as u32; - base.s64 += drop_keep.base.c64 as u32; - base.s128 += drop_keep.base.c128 as u32; - self.store.value_stack.truncate_keep_counts(base, drop_keep.keep); - } - fn create_exception(&mut self, tag_index: TagAddr) -> Result { let tag_addr = self.module.resolve_tag_addr(tag_index); let type_addr = self.store.state.get_tag(tag_addr).type_addr; @@ -1043,22 +1021,26 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_call(&mut self, wasm_func: WasmFunctionInstance, func_addr: FuncAddr) -> Result<(), Trap> { - if !Arc::ptr_eq(&self.func, &wasm_func.func) { - self.func = wasm_func.func.clone(); - } - - let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals) - else { + fn exec_call( + &mut self, + wasm_func: Arc, + owner: ModuleInstanceId, + func_addr: FuncAddr, + ) -> Result<(), Trap> { + let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { return cold!(Err(Trap::CallStackOverflow)); }; self.store.call_stack.push(self.cf)?; - self.cf = CallFrame::new(func_addr, locals_base, wasm_func.func.locals); - if wasm_func.owner != self.module.id() { + let locals = wasm_func.locals; + if !Arc::ptr_eq(&self.func, &wasm_func) { + self.func = wasm_func; + } + self.cf = CallFrame::new(func_addr, locals_base, locals); + if owner != self.module.id() { self.module = self .store - .get_module_instance(wasm_func.owner) + .get_module_instance(owner) .unwrap_or_else(|| unreachable!("invalid module instance")) .clone(); } @@ -1066,21 +1048,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_return_call(&mut self, wasm_func: WasmFunctionInstance, func_addr: FuncAddr) -> Result<(), Trap> { - if !Arc::ptr_eq(&self.func, &wasm_func.func) { - self.func = wasm_func.func.clone(); - } - - self.store.value_stack.truncate_keep_counts(self.cf.locals_base, wasm_func.func.params); - let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals) - else { + fn exec_return_call( + &mut self, + wasm_func: Arc, + owner: ModuleInstanceId, + func_addr: FuncAddr, + ) -> Result<(), Trap> { + self.store.value_stack.truncate_keep_counts(self.cf.locals_base, wasm_func.params); + let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { return cold!(Err(Trap::CallStackOverflow)); }; - self.cf = CallFrame::new(func_addr, locals_base, wasm_func.func.locals); - if wasm_func.owner != self.module.id() { + let locals = wasm_func.locals; + if !Arc::ptr_eq(&self.func, &wasm_func) { + self.func = wasm_func; + } + self.cf = CallFrame::new(func_addr, locals_base, locals); + if owner != self.module.id() { self.module = self .store - .get_module_instance(wasm_func.owner) + .get_module_instance(owner) .unwrap_or_else(|| unreachable!("invalid module instance")) .clone(); } @@ -1132,11 +1118,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_call_direct(&mut self, v: u32) -> Result<(), Trap> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); - let func = self.store.state.get_func(addr).clone(); - match func.kind { - crate::store::FunctionKind::Wasm(wasm_func) => self.exec_call(wasm_func, addr), + let func = self.store.state.get_func(addr); + match &func.kind { + crate::store::FunctionKind::Wasm(wasm_func) => { + self.exec_call(wasm_func.func.clone(), wasm_func.owner, addr) + } crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func, func.type_addr, func.gc.params)?; + self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params)?; Ok(()) } } @@ -1145,14 +1133,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_return_call_direct(&mut self, v: u32) -> Result { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); - let func = self.store.state.get_func(addr).clone(); - match func.kind { + let func = self.store.state.get_func(addr); + match &func.kind { crate::store::FunctionKind::Wasm(wasm_func) => { - self.exec_return_call(wasm_func, addr)?; + self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, addr)?; Ok(false) } crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func, func.type_addr, func.gc.params) + self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params) } } } @@ -1179,11 +1167,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_call_indirect( - &mut self, - type_addr: u32, - table_addr: u32, - ) -> Result { + fn exec_call_indirect(&mut self, index: OperandIdx) -> Result { + let TwoU32 { first: type_addr, second: table_addr } = index.get(&self.func.data); 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 @@ -1207,20 +1192,20 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { func_addr: FuncAddr, expected_type_addr: TypeAddr, ) -> Result { - let func = self.store.state.get_func(func_addr).clone(); + let func = self.store.state.get_func(func_addr); if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) { return cold!(Err(Trap::IndirectCallTypeMismatch { actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()), expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), })); } - match func.kind { + match &func.kind { crate::store::FunctionKind::Wasm(wasm_func) => match IS_RETURN_CALL { - true => self.exec_return_call(wasm_func, func_addr), - false => self.exec_call(wasm_func, func_addr), + true => self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, func_addr), + false => self.exec_call(wasm_func.func.clone(), wasm_func.owner, func_addr), }, crate::store::FunctionKind::Host(host_func) => { - return self.exec_call_host::(host_func, func.type_addr, func.gc.params); + return self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params); } }?; Ok(false) @@ -1287,7 +1272,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_store_local_local, const N: usize>( &mut self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, value_local: u8, ) -> Result<(), Trap> { @@ -1313,7 +1298,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_inc_memory_local, const N: usize>( &mut self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, increment: impl FnOnce(T) -> T, ) -> Result<(), Trap> { @@ -1333,7 +1318,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }; let mem = self.store.state.get_mem_mut(mem_addr); - let value = T::load_at(&*mem.inner, addr)?; + let value = cold_err!(T::load_at(&*mem.inner, addr))?; increment(value).store_at(&mut *mem.inner, addr) } @@ -1343,7 +1328,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { const N: usize, >( &mut self, - m: MemoryArg, + m: CompactMemoryArg, ) -> Result<(), Trap> { let rhs = T::stack_pop(&mut self.store.value_stack); let lhs = T::stack_pop(&mut self.store.value_stack); @@ -1361,7 +1346,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_load_local_value, const N: usize>( &self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, ) -> Result { let mem = self.store.state.get_mem(self.module.resolve_mem_addr(memarg.mem_addr())); @@ -1377,7 +1362,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); mem.effective_addr::(base as usize, memarg.offset())? }; - T::load_at(&*mem.inner, addr) + cold_err!(T::load_at(&*mem.inner, addr)) } #[inline(always)] @@ -1389,7 +1374,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { const TEE: bool, >( &mut self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, dst_local: u8, cast: impl Fn(LOAD) -> TARGET, @@ -1474,7 +1459,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_struct_get(&mut self, type_index: TypeAddr, field_index: u32, signed: Option) -> Result<(), Trap> { + fn exec_struct_get(&mut self, index: OperandIdx, signed: Option) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data); 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 @@ -1485,7 +1471,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { push_value(&mut self.store.value_stack, value, storage, signed) } - fn exec_struct_set(&mut self, type_index: TypeAddr, field_index: u32) -> Result<(), Trap> { + fn exec_struct_set(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data); 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] @@ -1508,7 +1495,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_new_fixed(&mut self, type_index: TypeAddr, len: u32) -> Result<(), Trap> { + fn exec_array_new_fixed(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: len } = index.get(&self.func.data); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; @@ -1567,7 +1555,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_copy(&mut self, dst_type: TypeAddr, src_type: TypeAddr) -> Result<(), Trap> { + fn exec_array_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: dst_type, second: src_type } = index.get(&self.func.data); 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); @@ -1588,7 +1577,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_new_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> { + fn exec_array_new_data(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data); 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); @@ -1599,7 +1589,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_new_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> { + fn exec_array_new_elem(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); 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 elem_addr = self.module.resolve_elem_addr(elem_index); @@ -1611,7 +1602,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_init_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> { + fn exec_array_init_data(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data); 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; @@ -1627,7 +1619,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_init_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> { + fn exec_array_init_elem(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); 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; @@ -1669,7 +1662,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Result<(), Trap> { + fn exec_memory_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: dst_mem, second: src_mem } = index.get(&self.func.data); let dst_mem_addr = self.module.resolve_mem_addr(dst_mem); let src_mem_addr = self.module.resolve_mem_addr(src_mem); let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch(); @@ -1701,7 +1695,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.exec_memory_fill_impl(mem_addr, dst, val as u8, size) } - fn exec_memory_fill_imm(&mut self, addr: u32, val: u8, size: i32) -> Result<(), Trap> { + fn exec_memory_fill_const(&mut self, index: OperandIdx) -> Result<(), Trap> { + let MemoryFillConstOp { memory: addr, byte: val, value: size } = index.get(&self.func.data); let mem_addr = self.module.resolve_mem_addr(addr); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let dst = self.store.value_stack.pop_memory_operand(arch)?; @@ -1717,7 +1712,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_memory_init(&mut self, data_index: u32, mem_index: u32) -> Result<(), Trap> { + fn exec_memory_init(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: data_index, second: mem_index } = index.get(&self.func.data); let size = u32::stack_pop(&mut self.store.value_stack) as usize; let offset = u32::stack_pop(&mut self.store.value_stack) as usize; let mem_addr = self.module.resolve_mem_addr(mem_index); @@ -1749,7 +1745,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_table_copy(&mut self, dst_table: u32, src_table: u32) -> Result<(), Trap> { + fn exec_table_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: dst_table, second: src_table } = index.get(&self.func.data); 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(); @@ -1772,15 +1769,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_mem_load_lane, const LOAD_SIZE: usize>( &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, - lane: u8, + arg: MemoryLaneArg, ) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(mem_addr)); + let m = arg.memory_arg_idx.get(&self.func.data); + let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; - let val = LOAD::load_at(&*mem.inner, addr)?; - let offset = lane as usize * LOAD_SIZE; + let addr = mem.effective_addr::(base, m.offset())?; + let val = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + let offset = arg.lane as usize * LOAD_SIZE; let mut imm = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); imm[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); self.store.value_stack.push(Value128(imm))?; @@ -1790,32 +1786,28 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_mem_load, const LOAD_SIZE: usize, TARGET: InternalValue>( &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, + index: OperandIdx, cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(mem_addr)); + let m = index.get(&self.func.data); + let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; + let addr = mem.effective_addr::(base, m.offset())?; let value = cold_err!(LOAD::load_at(&*mem.inner, addr))?; self.store.value_stack.push(cast(value)) } - fn exec_mem_store_lane + Copy, const N: usize>( - &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, - lane: u8, - ) -> Result<(), Trap> { + fn exec_mem_store_lane + Copy, const N: usize>(&mut self, arg: MemoryLaneArg) -> Result<(), Trap> { let bytes = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); - let lane_offset = lane as usize * N; + 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 mem_addr = self.module.resolve_mem_addr(mem_addr); + let m = arg.memory_arg_idx.get(&self.func.data); + let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; + let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); cold_err!(val.store_at(&mut *mem.inner, addr))?; Ok(()) @@ -1823,17 +1815,17 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_mem_store, const N: usize>( &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, + index: OperandIdx, cast: impl Fn(T) -> U, ) -> Result<(), Trap> { let val = ::stack_pop(&mut self.store.value_stack); let val = cast(val); - let mem_addr = self.module.resolve_mem_addr(mem_addr); + let m = index.get(&self.func.data); + let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; + let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); cold_err!(val.store_at(&mut *mem.inner, addr))?; Ok(()) @@ -1862,7 +1854,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_table_init(&mut self, elem_index: u32, table_index: u32) -> Result<(), Trap> { + fn exec_table_init(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: elem_index, second: table_index } = index.get(&self.func.data); 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); diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 43c214a..f2c0c28 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -109,6 +109,17 @@ impl Stack { Ok(()) } + #[inline(always)] + pub(crate) fn push_copy(&mut self, index: usize) -> Result<(), Trap> { + if !self.ensure_capacity_for(self.data.len() + 1) { + return cold!(Err(Trap::ValueStackOverflow)); + } + + let value = self.data[index]; + self.data.push(value); + Ok(()) + } + #[inline(always)] pub(crate) fn pop(&mut self) -> T { self.data.pop().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug")) diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index e2cbef0..4fb81c9 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -137,6 +137,7 @@ pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { fn stack_peek(stack: &ValueStack) -> Self; fn stack_select(stack: &mut ValueStack); fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self; + fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap>; fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self); fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self); fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr); @@ -178,6 +179,11 @@ macro_rules! impl_internalvalue { $from_stack } + #[inline(always)] + fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap> { + stack.$stack.push_copy(frame.locals_base.$stack_base as usize + index as usize) + } + #[inline(always)] fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self) { let $to_stack_v = value; diff --git a/crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast b/crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast new file mode 100644 index 0000000..bc92b30 --- /dev/null +++ b/crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast @@ -0,0 +1,35 @@ +(module + (func (export "retained-value-before-update-branch") (param i32 i32) (result i32) + (block (result i32) + local.get 0 + i32.eqz + local.get 1 + i32.const 1 + i32.add + local.tee 1 + br_if 0 + ) + drop + local.get 1 + ) + + (func (export "compare-eqz-br-if") (param i32 i32) (result i32) + block + i32.const 1 + local.get 0 + local.get 1 + i32.lt_u + i32.eqz + br_if 0 + drop + i32.const 2 + return + end + i32.const 3 + ) +) + +(assert_return (invoke "retained-value-before-update-branch" (i32.const 0) (i32.const 0)) (i32.const 1)) +(assert_return (invoke "retained-value-before-update-branch" (i32.const 1) (i32.const -1)) (i32.const 0)) +(assert_return (invoke "compare-eqz-br-if" (i32.const 1) (i32.const 2)) (i32.const 2)) +(assert_return (invoke "compare-eqz-br-if" (i32.const 2) (i32.const 1)) (i32.const 3)) diff --git a/crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast b/crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast new file mode 100644 index 0000000..147858a --- /dev/null +++ b/crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast @@ -0,0 +1,59 @@ +(module + (func (export "i32-shift-8") (param i32) (result i32) + local.get 0 + i32.const 8 + i32.shl + i32.const 8 + i32.shr_s + ) + (func (export "i32-extend-8") (param i32) (result i32) + local.get 0 + i32.const 24 + i32.shl + i32.const 24 + i32.shr_s + ) + (func (export "i32-extend-16") (param i32) (result i32) + local.get 0 + i32.const 16 + i32.shl + i32.const 16 + i32.shr_s + ) + (func (export "i64-shift-16") (param i64) (result i64) + local.get 0 + i64.const 16 + i64.shl + i64.const 16 + i64.shr_s + ) + (func (export "i64-extend-8") (param i64) (result i64) + local.get 0 + i64.const 56 + i64.shl + i64.const 56 + i64.shr_s + ) + (func (export "i64-extend-16") (param i64) (result i64) + local.get 0 + i64.const 48 + i64.shl + i64.const 48 + i64.shr_s + ) + (func (export "i64-extend-32") (param i64) (result i64) + local.get 0 + i64.const 32 + i64.shl + i64.const 32 + i64.shr_s + ) +) + +(assert_return (invoke "i32-shift-8" (i32.const 0x80)) (i32.const 0x80)) +(assert_return (invoke "i32-extend-8" (i32.const 0x80)) (i32.const -128)) +(assert_return (invoke "i32-extend-16" (i32.const 0x8000)) (i32.const -32768)) +(assert_return (invoke "i64-shift-16" (i64.const 0x80)) (i64.const 0x80)) +(assert_return (invoke "i64-extend-8" (i64.const 0x80)) (i64.const -128)) +(assert_return (invoke "i64-extend-16" (i64.const 0x8000)) (i64.const -32768)) +(assert_return (invoke "i64-extend-32" (i64.const 0x80000000)) (i64.const -2147483648)) diff --git a/crates/tinywasm/tests/wasm-custom/simd-stack-local.wast b/crates/tinywasm/tests/wasm-custom/simd-stack-local.wast new file mode 100644 index 0000000..0dabf4e --- /dev/null +++ b/crates/tinywasm/tests/wasm-custom/simd-stack-local.wast @@ -0,0 +1,53 @@ +(module + (func (export "and") (param v128 v128) (result v128) + local.get 0 + local.get 1 + v128.and + ) + (func (export "or") (param v128 v128) (result v128) + local.get 0 + local.get 1 + v128.or + ) + (func (export "add") (param v128 v128) (result v128) + local.get 0 + local.get 1 + i64x2.add + ) + (func (export "mul") (param v128 v128) (result v128) + local.get 0 + local.get 1 + i64x2.mul + ) + (func (export "deep-xor") (param v128 v128 v128) (result v128 v128) + local.get 0 + local.get 1 + local.get 2 + v128.xor + ) +) + +(assert_return + (invoke "and" (v128.const i32x4 -1 0 -1 0) (v128.const i32x4 1 2 3 4)) + (v128.const i32x4 1 0 3 0) +) +(assert_return + (invoke "or" (v128.const i32x4 1 0 3 0) (v128.const i32x4 0 2 0 4)) + (v128.const i32x4 1 2 3 4) +) +(assert_return + (invoke "add" (v128.const i64x2 1 2) (v128.const i64x2 3 4)) + (v128.const i64x2 4 6) +) +(assert_return + (invoke "mul" (v128.const i64x2 2 3) (v128.const i64x2 4 5)) + (v128.const i64x2 8 15) +) +(assert_return + (invoke "deep-xor" + (v128.const i32x4 1 2 3 4) + (v128.const i32x4 8 4 2 1) + (v128.const i32x4 1 1 1 1)) + (v128.const i32x4 1 2 3 4) + (v128.const i32x4 9 5 3 0) +) diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index 9904a7d..db40263 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -64,6 +64,9 @@ impl Module { #[cfg(test)] mod tests { use super::*; + use crate::{Instruction, ModuleInner, V128Operand, WasmFunction}; + use crate::{OperandIdx, OperandType}; + use alloc::{boxed::Box, sync::Arc, vec}; #[test] fn test_invalid_magic() { @@ -80,4 +83,27 @@ mod tests { twasm[4] = 0; assert!(matches!(Module::try_from_twasm(&twasm), Err(TwasmError::InvalidVersion))); } + + #[test] + fn v128_operands_round_trip_archive() { + let bytes = [0x00, 0x01, 0x02, 0x03, 0x7f, 0x80, 0xfe, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x90]; + let mut function = WasmFunction::default(); + let constant = OperandIdx::new(0); + function.data.operands128 = vec![V128Operand { value: bytes }.encode()].into_boxed_slice(); + function.instructions = vec![Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)].into(); + let module = Module::from(ModuleInner { funcs: Box::new([Arc::new(function)]), ..ModuleInner::default() }); + + let archive = module.serialize_twasm().expect("serialize archive"); + assert_eq!(&archive[..6], b"TWAS05"); + let decoded = Module::try_from_twasm(&archive).expect("deserialize archive"); + let function = &decoded.funcs[0]; + + for instruction in function.instructions.iter() { + let index = match instruction { + Instruction::Const128(index) | Instruction::I8x16Shuffle(index) => *index, + _ => panic!("unexpected instruction"), + }; + assert_eq!(index.get(&function.data).value, bytes); + } + } } diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 10ab028..797f703 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,7 +1,8 @@ use alloc::boxed::Box; use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; -use crate::{ConstIdx, DataAddr, ElemAddr, MemAddr, RefType, RefValue}; +use crate::operands::sealed; +use crate::{DataAddr, ElemAddr, MemAddr, Operand64, Operand128, OperandIdx, OperandType, RefType, RefValue}; /// Represents a memory immediate in a WebAssembly memory instruction. #[derive(Copy, Clone, PartialEq, Eq)] @@ -13,13 +14,275 @@ pub struct MemoryArg { mem_addr: MemAddr, } -/// Stack lanes discarded and retained when branching to a control frame. -#[derive(Clone, Copy, PartialEq, Eq)] +/// A compact memory immediate used by optimized instructions. +/// +/// Optimized instructions use this representation when the offset and +/// module-local memory index fit its narrower fields. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[repr(Rust, packed)] +pub struct CompactMemoryArg { + offset: u32, + mem_addr: u16, +} + +/// An indexed memory argument and up to two local operands. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[repr(Rust, packed)] +pub struct MemoryLocalArg { + pub memory_arg_idx: OperandIdx, + pub local1: u8, + pub local2: u8, +} + +/// An indexed memory argument and SIMD lane. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[repr(Rust, packed)] +pub struct MemoryLaneArg { + pub memory_arg_idx: OperandIdx, + pub lane: u8, +} + +/// A 32-bit immediate and local operand that fit in an instruction payload. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[repr(Rust, packed)] +pub struct I32LocalArg { + pub value: i32, + pub local: LocalAddr, +} + +/// Three local operands that fit in an instruction payload. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct LocalTripleArg { + pub left: LocalAddr, + pub right: LocalAddr, + pub dst: LocalAddr, +} + +impl sealed::Sealed for LocalTripleArg {} + +impl OperandType for LocalTripleArg { + type Raw = Operand64; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self { left: raw.u16::<0>(), right: raw.u16::<2>(), dst: raw.u16::<4>() } + } + + #[inline] + fn encode(self) -> Self::Raw { + Operand64::default().with_u16::<0>(self.left).with_u16::<2>(self.right).with_u16::<4>(self.dst) + } +} + +/// A branch target and local operand that fit in an instruction payload. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[repr(Rust, packed)] +pub struct TargetLocalArg { + pub target_ip: u32, + pub local: LocalAddr, +} + +macro_rules! operand_view { + ($name:ident, $lane:ident, $raw:ty, { $($field:ident : $ty:ty = $read:ident / $write:ident ($offset:expr)),+ $(,)? }) => { + #[derive(Copy, Clone, PartialEq, Eq)] + #[cfg_attr(feature = "debug", derive(Debug))] + pub struct $name { + $(pub $field: $ty),+ + } + + impl sealed::Sealed for $name {} + + impl OperandType for $name { + type Raw = $raw; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self { $($field: raw.$read::<$offset>() as $ty),+ } + } + + #[inline] + fn encode(self) -> Self::Raw { + <$raw>::default()$(.$write::<$offset>(self.$field as _))+ + } + } + }; +} + +operand_view!(I64Operand, operands64, Operand64, { value: i64 = u64 / with_u64(0) }); +operand_view!(TwoU32, operands64, Operand64, { + first: u32 = u32 / with_u32(0), second: u32 = u32 / with_u32(4) +}); +operand_view!(LocalU32, operands64, Operand64, { + local: u16 = u16 / with_u16(0), value: u32 = u32 / with_u32(2) +}); +operand_view!(TargetLocal, operands64, Operand64, { + target: u32 = u32 / with_u32(0), local: u16 = u16 / with_u16(4) +}); + +operand_view!(LocalConst64, operands128, Operand128, { + local: u16 = u16 / with_u16(0), value: u64 = u64 / with_u64(2) +}); +operand_view!(GlobalConst32, operands64, Operand64, { + global: u32 = u32 / with_u32(0), value: u32 = u32 / with_u32(4) +}); +operand_view!(GlobalConst64, operands128, Operand128, { + global: u32 = u32 / with_u32(0), value: u64 = u64 / with_u64(4) +}); +operand_view!(LocalConstSet32, operands64, Operand64, { + local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u32 = u32 / with_u32(4) +}); +operand_view!(LocalConstSet64, operands128, Operand128, { + local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u64 = u64 / with_u64(4) +}); +operand_view!(MemoryFillConstOp, operands128, Operand128, { + memory: u32 = u32 / with_u32(0), byte: u8 = u8 / with_u8(4), value: i32 = u32 / with_u32(5) +}); +operand_view!(CastBranch, operands64, Operand64, { + target: u32 = u32 / with_u32(0), ref_type_bits: u32 = u32 / with_u32(4) +}); +operand_view!(BranchTableArg, operands128, Operand128, { + target: u32 = u32 / with_u32(0), start: u32 = u32 / with_u32(4), len: u32 = u32 / with_u32(8) +}); +operand_view!(StackConst32, operands64, Operand64, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4) +}); +operand_view!(StackConst64, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i64 = u64 / with_u64(4) +}); +operand_view!(LocalConstCmp, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8) +}); +operand_view!(LocalLocalCmp, operands64, Operand64, { + target: u32 = u32 / with_u32(0), left: u16 = u16 / with_u16(4), right: u16 = u16 / with_u16(6) +}); +operand_view!(LocalUpdate, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), on_zero: u8 = u8 / with_u8(10) +}); +operand_view!(GlobalUpdate, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), global: u32 = u32 / with_u32(8), on_zero: u8 = u8 / with_u8(12) +}); +operand_view!(LocalUpdateCmp, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), right: u16 = u16 / with_u16(10) +}); + +/// An operation packed inline with an indexed operand. +#[derive(Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct DropKeep { - pub base: ValueCounts, - pub keep: ValueCounts, +#[cfg_attr( + feature = "archive", + serde(bound(serialize = "Op: Copy + serde::Serialize", deserialize = "Op: Copy + serde::de::DeserializeOwned",)) +)] +#[repr(Rust, packed)] +pub struct PackedOp { + pub op: Op, + pub index: OperandIdx, +} + +impl PackedOp { + /// Creates a packed operation from an operator and operand index. + #[inline] + pub const fn new(op: Op, index: OperandIdx) -> Self { + Self { op, index } + } +} + +/// A SIMD value stored in the 128-bit operand lane. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct V128Operand { + pub value: [u8; 16], +} + +/// A local SIMD operation with an indexed constant. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct LocalV128 { + pub local: u16, + pub value: OperandIdx, +} + +/// A global SIMD operation with an indexed constant. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct GlobalV128 { + pub global: u32, + pub value: OperandIdx, +} + +/// A local SIMD operation, indexed constant, and destination local. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct LocalConstSetV128 { + pub local: u16, + pub dst: u16, + pub value: OperandIdx, +} + +macro_rules! operand_raw_view { + ($name:ident, $raw:ty, $decode:expr, $encode:expr) => { + impl sealed::Sealed for $name {} + + impl OperandType for $name { + type Raw = $raw; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + $decode(raw) + } + + #[inline] + fn encode(self) -> Self::Raw { + $encode(self) + } + } + }; +} + +operand_raw_view!(V128Operand, Operand128, |raw: Operand128| Self { value: raw.to_le_bytes() }, |value: Self| { + Operand128::from_le_bytes(value.value) +}); +operand_raw_view!( + LocalV128, + Operand64, + |raw: Operand64| Self { local: raw.u16::<0>(), value: OperandIdx::new(raw.u32::<2>()) }, + |value: Self| { Operand64::default().with_u16::<0>(value.local).with_u32::<2>(value.value.index()) } +); +operand_raw_view!( + GlobalV128, + Operand64, + |raw: Operand64| Self { global: raw.u32::<0>(), value: OperandIdx::new(raw.u32::<4>()) }, + |value: Self| { Operand64::default().with_u32::<0>(value.global).with_u32::<4>(value.value.index()) } +); +operand_raw_view!( + LocalConstSetV128, + Operand64, + |raw: Operand64| Self { local: raw.u16::<0>(), dst: raw.u16::<2>(), value: OperandIdx::new(raw.u32::<4>()) }, + |value: Self| { + Operand64::default().with_u16::<0>(value.local).with_u16::<2>(value.dst).with_u32::<4>(value.value.index()) + } +); + +impl CastBranch { + #[inline] + pub const fn ref_type(self) -> RefType { + match RefType::from_bits(self.ref_type_bits) { + Some(value) => value, + None => unreachable!(), + } + } } /// A catch clause attached to a lowered `try_table` instruction. @@ -62,12 +325,6 @@ pub struct ExceptionHandler { pub catches: Box<[ExceptionCatch]>, } -impl From<(ValueCounts, ValueCounts)> for DropKeep { - fn from((base, keep): (ValueCounts, ValueCounts)) -> Self { - Self { base, keep } - } -} - impl MemoryArg { #[inline] pub const fn new(offset: u64, mem_addr: MemAddr) -> Self { @@ -85,6 +342,80 @@ impl MemoryArg { } } +impl sealed::Sealed for MemoryArg {} + +impl OperandType for MemoryArg { + type Raw = Operand128; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self::new(raw.u64::<0>(), raw.u32::<8>()) + } + + #[inline] + fn encode(self) -> Self::Raw { + Operand128::default().with_u64::<0>(self.offset).with_u32::<8>(self.mem_addr) + } +} + +impl CompactMemoryArg { + /// Returns the static byte offset. + #[inline] + pub const fn offset(self) -> u64 { + self.offset as u64 + } + + /// Returns the module-local memory index. + #[inline] + pub const fn mem_addr(self) -> MemAddr { + self.mem_addr as MemAddr + } +} + +impl sealed::Sealed for CompactMemoryArg {} + +impl OperandType for CompactMemoryArg { + type Raw = Operand64; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self { offset: raw.u32::<0>(), mem_addr: raw.u16::<4>() } + } + + #[inline] + fn encode(self) -> Self::Raw { + Operand64::default().with_u32::<0>(self.offset).with_u16::<4>(self.mem_addr) + } +} + +impl TryFrom for CompactMemoryArg { + type Error = (); + + #[inline] + fn try_from(arg: MemoryArg) -> Result { + Ok(Self { + offset: u32::try_from(arg.offset()).map_err(|_| ())?, + mem_addr: u16::try_from(arg.mem_addr()).map_err(|_| ())?, + }) + } +} + +impl From for MemoryArg { + #[inline] + fn from(arg: CompactMemoryArg) -> Self { + Self::new(arg.offset(), arg.mem_addr()) + } +} + +const _: () = { + assert!(core::mem::size_of::>() == 4); + assert!(core::mem::size_of::() == 8); + assert!(core::mem::size_of::() == 16); + assert!(core::mem::size_of::() == 6); + assert!(core::mem::size_of::() == 6); + assert!(core::mem::size_of::() == 6); +}; + #[derive(Clone, Copy, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -132,6 +463,25 @@ pub enum CmpOp { GeU, } +impl CmpOp { + /// Returns the comparison that is true exactly when `self` is false. + #[inline] + pub const fn inverse(self) -> Self { + match self { + Self::Eq => Self::Ne, + Self::Ne => Self::Eq, + Self::LtS => Self::GeS, + Self::LtU => Self::GeU, + Self::GtS => Self::LeS, + Self::GtU => Self::LeU, + Self::LeS => Self::GtS, + Self::LeU => Self::GtU, + Self::GeS => Self::LtS, + Self::GeU => Self::LtU, + } + } +} + #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -156,6 +506,18 @@ pub enum BinOp { FCopysign, } +impl BinOp { + /// Returns the update delta for `local OP immediate`, when it is a simple increment. + #[inline] + pub const fn inc_delta(self, immediate: i32) -> Option { + match self { + Self::IAdd => Some(immediate), + Self::ISub => Some(immediate.wrapping_neg()), + _ => None, + } + } +} + #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -181,69 +543,47 @@ pub enum BinOp128 { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub enum Instruction { LocalCopy32(LocalAddr, LocalAddr), LocalCopy64(LocalAddr, LocalAddr), LocalCopy128(LocalAddr, LocalAddr), - AddConst32(i32), AddConst64(i64), - IncLocal32(LocalAddr, i32), IncLocal64(LocalAddr, i64), + AddConst32(i32), AddConst64(OperandIdx), + IncLocal32(I32LocalArg), IncLocal64(PackedOp), // The 32/64 suffix describes the operand width. Future compare-style ops may still yield i32 results. BinOpLocalLocal32(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal64(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal128(BinOp128, LocalAddr, LocalAddr), CmpLocalLocal32(CmpOp, LocalAddr, LocalAddr), CmpLocalLocal64(CmpOp, LocalAddr, LocalAddr), - BinOpLocalLocalSet32(BinOp, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalLocalSet64(BinOp, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalLocalSet128(BinOp128, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalLocalTee32(BinOp, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalLocalTee64(BinOp, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalLocalTee128(BinOp128, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalConst32(BinOp, LocalAddr, i32), BinOpLocalConst64(BinOp, LocalAddr, i64), - BinOpGlobalConst32(BinOp, GlobalAddr, i32), BinOpGlobalConst64(BinOp, GlobalAddr, i64), - BinOpGlobalConst128(BinOp128, GlobalAddr, ConstIdx), - BinOpLocalConst128(BinOp128, LocalAddr, ConstIdx), - BinOpLocalConstSet32(BinOp, LocalAddr, i32, LocalAddr), - BinOpLocalConstSet64(BinOp, LocalAddr, i64, LocalAddr), - BinOpLocalConstSet128(BinOp128, LocalAddr, ConstIdx, LocalAddr), - BinOpLocalConstTee32(BinOp, LocalAddr, i32, LocalAddr), - BinOpLocalConstTee64(BinOp, LocalAddr, i64, LocalAddr), - BinOpLocalConstTee128(BinOp128, LocalAddr, ConstIdx, LocalAddr), + AddLocalLocalSet32(LocalTripleArg), AddLocalLocalTee32(LocalTripleArg), + BinOpLocalLocalSet32(PackedOp), BinOpLocalLocalSet64(PackedOp), BinOpLocalLocalSet128(PackedOp), + BinOpLocalLocalTee32(PackedOp), BinOpLocalLocalTee64(PackedOp), BinOpLocalLocalTee128(PackedOp), + AddLocalConst32(I32LocalArg), SubLocalConst32(I32LocalArg), MulLocalConst32(I32LocalArg), + BinOpLocalConst32(PackedOp), BinOpLocalConst64(PackedOp), + BinOpGlobalConst32(PackedOp), BinOpGlobalConst64(PackedOp), + BinOpGlobalConst128(PackedOp), BinOpLocalConst128(PackedOp), + BinOpLocalConstSet32(PackedOp), BinOpLocalConstSet64(PackedOp), BinOpLocalConstSet128(PackedOp), + BinOpLocalConstTee32(PackedOp), BinOpLocalConstTee64(PackedOp), BinOpLocalConstTee128(PackedOp), BinOpStackLocal32(BinOp, LocalAddr), BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr), BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr), + BinOpStackLocal128(BinOp128, LocalAddr), BinOpStackGlobal32(BinOp, u32), BinOpStackGlobal64(BinOp, u32), - SetLocalConst32(LocalAddr, i32), SetLocalConst64(LocalAddr, i64), SetLocalConst128(LocalAddr, ConstIdx), - IncMemoryLocal32(MemoryArg, u8), - IncMemoryLocal64(MemoryArg, u8), - StoreLocalLocal32(MemoryArg, u8, u8), - StoreLocalLocal64(MemoryArg, u8, u8), - StoreLocalLocal128(MemoryArg, u8, u8), - LoadLocal32(MemoryArg, u8), - LoadLocal64(MemoryArg, u8), - LoadLocal8S32(MemoryArg, u8), - LoadLocal8U32(MemoryArg, u8), - LoadLocal16S32(MemoryArg, u8), - LoadLocal16U32(MemoryArg, u8), - LoadLocalTee32(MemoryArg, u8, u8), - LoadLocalSet32(MemoryArg, u8, u8), - LoadLocalTee8S32(MemoryArg, u8, u8), - LoadLocalTee8U32(MemoryArg, u8, u8), - LoadLocalTee16S32(MemoryArg, u8, u8), - LoadLocalTee16U32(MemoryArg, u8, u8), - LoadLocalSet8S32(MemoryArg, u8, u8), - LoadLocalSet8U32(MemoryArg, u8, u8), - LoadLocalSet16S32(MemoryArg, u8, u8), - LoadLocalSet16U32(MemoryArg, u8, u8), - LoadLocalTee128(MemoryArg, u8, u8), - LoadLocalSet128(MemoryArg, u8, u8), - AndConstTee32(i32, LocalAddr), - SubConstTee32(i32, LocalAddr), - AndConstTee64(i64, LocalAddr), - SubConstTee64(i64, LocalAddr), - MulAccLocal32(LocalAddr), - MulAccLocal64(LocalAddr), - FMulAccLocal32(LocalAddr), - FMulAccLocal64(LocalAddr), + SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp), SetLocalConst128(PackedOp), + IncMemoryLocal32(MemoryLocalArg), IncMemoryLocal64(MemoryLocalArg), + StoreLocalLocal32(MemoryLocalArg), StoreLocalLocal64(MemoryLocalArg), StoreLocalLocal128(MemoryLocalArg), + LoadLocal32(MemoryLocalArg), LoadLocal64(MemoryLocalArg), + LoadLocal8S32(MemoryLocalArg), LoadLocal8U32(MemoryLocalArg), + LoadLocal16S32(MemoryLocalArg), LoadLocal16U32(MemoryLocalArg), + LoadLocalTee32(MemoryLocalArg), LoadLocalSet32(MemoryLocalArg), + LoadLocalTee8S32(MemoryLocalArg), LoadLocalTee8U32(MemoryLocalArg), + LoadLocalTee16S32(MemoryLocalArg), LoadLocalTee16U32(MemoryLocalArg), + LoadLocalSet8S32(MemoryLocalArg), LoadLocalSet8U32(MemoryLocalArg), + LoadLocalSet16S32(MemoryLocalArg), LoadLocalSet16U32(MemoryLocalArg), + LoadLocalTee128(MemoryLocalArg), LoadLocalSet128(MemoryLocalArg), + AndConstTee32(I32LocalArg), SubConstTee32(I32LocalArg), + AndConstTee64(PackedOp), SubConstTee64(PackedOp), + MulAccLocal32(LocalAddr), MulAccLocal64(LocalAddr), + FMulAccLocal32(LocalAddr), FMulAccLocal64(LocalAddr), I32Add3, I64Add3, - FMaStoreF32(MemoryArg), - FMaStoreF64(MemoryArg), + FMaStoreF32(CompactMemoryArg), + FMaStoreF64(CompactMemoryArg), // > Control Instructions (jump-oriented, lowered from structured control during parsing) // See @@ -255,28 +595,16 @@ pub enum Instruction { JumpIfNonZero64(u32), JumpIfRefNull(u32), JumpIfRefNonNull(u32), - JumpIfLocalZero32 { target_ip: u32, local: LocalAddr }, - JumpIfLocalNonZero32 { target_ip: u32, local: LocalAddr }, - JumpIfLocalZero64 { target_ip: u32, local: LocalAddr }, - JumpIfLocalNonZero64 { target_ip: u32, local: LocalAddr }, - JumpCmpStackConst32 { target_ip: u32, imm: i32, op: CmpOp }, - JumpCmpStackConst64 { target_ip: u32, imm: i64, op: CmpOp }, - JumpCmpStackLocal32 { target_ip: u32, local: LocalAddr, op: CmpOp }, - JumpCmpStackLocal64 { target_ip: u32, local: LocalAddr, op: CmpOp }, - BinOpLocalConstJump32 { target_ip: u32, local: LocalAddr, imm: i32, op: BinOp, on_zero: bool }, - BinOpLocalConstJumpCmpLocal32 { target_ip: u32, local: LocalAddr, imm: i32, binop: BinOp, right: LocalAddr, cmp: CmpOp }, - BinOpStackConstTeeLocalJump32 { target_ip: u32, local: LocalAddr, imm: i32, op: BinOp, on_zero: bool }, - BinOpGlobalConstJump32 { target_ip: u32, global: GlobalAddr, imm: i32, op: BinOp, on_zero: bool }, - IncLocalJump32 { target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool }, - IncStackTeeLocalJump32 { target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool }, - IncGlobalJump32 { target_ip: u32, global: GlobalAddr, delta: i32, on_zero: bool }, - IncLocalJumpCmpLocal32 { target_ip: u32, local: LocalAddr, delta: i32, right: LocalAddr, op: CmpOp }, - JumpCmpLocalConst32 { target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp }, - JumpCmpLocalConst64 { target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp }, - JumpCmpLocalLocal32 { target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp }, - JumpCmpLocalLocal64 { target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp }, - DropKeep(DropKeep), - BranchTable(u32, u32, u32), // (default_landing_pad_ip, branch_table_start, target_count) + JumpIfLocalZero32(TargetLocalArg), JumpIfLocalNonZero32(TargetLocalArg), + JumpIfLocalZero64(TargetLocalArg), JumpIfLocalNonZero64(TargetLocalArg), + JumpCmpStackConst32(PackedOp), JumpCmpStackConst64(PackedOp), + JumpCmpStackLocal32(PackedOp), JumpCmpStackLocal64(PackedOp), + BinOpLocalConstJump32(PackedOp), BinOpLocalConstJumpCmpLocal32(PackedOp<(BinOp, CmpOp), LocalUpdateCmp>), + BinOpStackConstTeeLocalJump32(PackedOp), BinOpGlobalConstJump32(PackedOp), + IncLocalJump32(OperandIdx), IncStackTeeLocalJump32(OperandIdx), IncGlobalJump32(OperandIdx), + IncLocalJumpCmpLocal32(PackedOp), JumpCmpLocalConst32(PackedOp), JumpCmpLocalConst64(PackedOp), + JumpCmpLocalLocal32(PackedOp), JumpCmpLocalLocal64(PackedOp), + DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(OperandIdx), Return, ReturnVoid, Return32, @@ -284,11 +612,11 @@ pub enum Instruction { Return128, Call(FuncAddr), CallSelf, - CallIndirect(TypeAddr, TableAddr), + CallIndirect(OperandIdx), CallRef(TypeAddr), ReturnCall(FuncAddr), ReturnCallSelf, - ReturnCallIndirect(TypeAddr, TableAddr), + ReturnCallIndirect(OperandIdx), ReturnCallRef(TypeAddr), Throw(TagAddr), ThrowRef, @@ -307,35 +635,18 @@ pub enum Instruction { GlobalGet128(GlobalAddr), GlobalSet128(GlobalAddr), GlobalTee128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), // > Memory Instructions - I32Load(MemoryArg), - I64Load(MemoryArg), - F32Load(MemoryArg), - F64Load(MemoryArg), - I32Load8S(MemoryArg), - I32Load8U(MemoryArg), - I32Load16S(MemoryArg), - I32Load16U(MemoryArg), - I64Load8S(MemoryArg), - I64Load8U(MemoryArg), - I64Load16S(MemoryArg), - I64Load16U(MemoryArg), - I64Load32S(MemoryArg), - I64Load32U(MemoryArg), - I32Store(MemoryArg), - I64Store(MemoryArg), - F32Store(MemoryArg), - F64Store(MemoryArg), - I32Store8(MemoryArg), - I32Store16(MemoryArg), - I64Store8(MemoryArg), - I64Store16(MemoryArg), - I64Store32(MemoryArg), + I32Load(OperandIdx), I64Load(OperandIdx), F32Load(OperandIdx), F64Load(OperandIdx), + I32Load8S(OperandIdx), I32Load8U(OperandIdx), I32Load16S(OperandIdx), I32Load16U(OperandIdx), + I64Load8S(OperandIdx), I64Load8U(OperandIdx), I64Load16S(OperandIdx), I64Load16U(OperandIdx), I64Load32S(OperandIdx), I64Load32U(OperandIdx), + I32Store(OperandIdx), I64Store(OperandIdx), F32Store(OperandIdx), F64Store(OperandIdx), + I32Store8(OperandIdx), I32Store16(OperandIdx), I64Store8(OperandIdx), I64Store16(OperandIdx), I64Store32(OperandIdx), MemorySize(MemAddr), MemoryGrow(MemAddr), // > Constants Const32(i32), - Const64(i64), + Const64Imm(i32), + Const64(OperandIdx), // > Reference Types RefNull(RefType), @@ -348,29 +659,24 @@ pub enum Instruction { RefEq, RefTest(RefType), RefCast(RefType), - BrOnCast(u32, RefType, bool), + BrOnCast(OperandIdx), + BrOnCastFail(OperandIdx), // > GC Objects StructNew(TypeAddr), StructNewDefault(TypeAddr), - StructGet(TypeAddr, u32), - StructGetS(TypeAddr, u32), - StructGetU(TypeAddr, u32), - StructSet(TypeAddr, u32), + StructGet(OperandIdx), StructGetS(OperandIdx), StructGetU(OperandIdx), StructSet(OperandIdx), ArrayNew(TypeAddr), ArrayNewDefault(TypeAddr), - ArrayNewFixed(TypeAddr, u32), - ArrayNewData(TypeAddr, DataAddr), - ArrayNewElem(TypeAddr, ElemAddr), + ArrayNewFixed(OperandIdx), + ArrayNewData(OperandIdx), ArrayNewElem(OperandIdx), ArrayGet(TypeAddr), ArrayGetS(TypeAddr), ArrayGetU(TypeAddr), ArraySet(TypeAddr), ArrayLen, ArrayFill(TypeAddr), - ArrayCopy(TypeAddr, TypeAddr), - ArrayInitData(TypeAddr, DataAddr), - ArrayInitElem(TypeAddr, ElemAddr), + ArrayCopy(OperandIdx), ArrayInitData(OperandIdx), ArrayInitElem(OperandIdx), // > Numeric Instructions // See @@ -400,19 +706,18 @@ pub enum Instruction { I64TruncSatF32S, I64TruncSatF32U, I64TruncSatF64S, I64TruncSatF64U, // > Table Instructions - TableInit(ElemAddr, TableAddr), + TableInit(OperandIdx), TableGet(TableAddr), TableSet(TableAddr), - TableCopy { dst_table: TableAddr, src_table: TableAddr }, + TableCopy(OperandIdx), TableGrow(TableAddr), TableSize(TableAddr), TableFill(TableAddr), // > Bulk Memory Instructions - MemoryInit(DataAddr, MemAddr), - MemoryCopy { dst_mem: MemAddr, src_mem: MemAddr }, + MemoryInit(OperandIdx), MemoryCopy(OperandIdx), MemoryFill(MemAddr), - MemoryFillImm(MemAddr, u8, i32), + MemoryFillConst(OperandIdx), DataDrop(DataAddr), ElemDrop(ElemAddr), @@ -420,20 +725,18 @@ pub enum Instruction { I64Add128, I64Sub128, I64MulWideS, I64MulWideU, // > SIMD - V128Load(MemoryArg), - V128Load8x8S(MemoryArg), V128Load8x8U(MemoryArg), - V128Load16x4S(MemoryArg), V128Load16x4U(MemoryArg), - V128Load32x2S(MemoryArg), V128Load32x2U(MemoryArg), + V128Load(OperandIdx), V128Load8x8S(OperandIdx), V128Load8x8U(OperandIdx), + V128Load16x4S(OperandIdx), V128Load16x4U(OperandIdx), V128Load32x2S(OperandIdx), V128Load32x2U(OperandIdx), - V128Load8Splat(MemoryArg), V128Load16Splat(MemoryArg), V128Load32Splat(MemoryArg), V128Load64Splat(MemoryArg), - V128Load8Lane(MemoryArg, u8), V128Load16Lane(MemoryArg, u8), V128Load32Lane(MemoryArg, u8), V128Load64Lane(MemoryArg, u8), + V128Load8Splat(OperandIdx), V128Load16Splat(OperandIdx), V128Load32Splat(OperandIdx), V128Load64Splat(OperandIdx), + V128Load8Lane(MemoryLaneArg), V128Load16Lane(MemoryLaneArg), V128Load32Lane(MemoryLaneArg), V128Load64Lane(MemoryLaneArg), - V128Load32Zero(MemoryArg), V128Load64Zero(MemoryArg), + V128Load32Zero(OperandIdx), V128Load64Zero(OperandIdx), - V128Store(MemoryArg), V128Store8Lane(MemoryArg, u8), V128Store16Lane(MemoryArg, u8), V128Store32Lane(MemoryArg, u8), V128Store64Lane(MemoryArg, u8), + V128Store(OperandIdx), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg), - I8x16Shuffle(ConstIdx), - Const128(ConstIdx), + I8x16Shuffle(OperandIdx), + Const128Imm(u32), Const128(OperandIdx), I8x16ExtractLaneS(u8), I8x16ExtractLaneU(u8), I8x16ReplaceLane(u8), I16x8ExtractLaneS(u8), I16x8ExtractLaneU(u8), I16x8ReplaceLane(u8), @@ -485,10 +788,8 @@ pub enum Instruction { I32x4RelaxedTruncF64x2SZero, I32x4RelaxedTruncF64x2UZero, F32x4RelaxedMadd, F32x4RelaxedNmadd, F64x2RelaxedMadd, F64x2RelaxedNmadd, - I8x16RelaxedLaneselect, - I16x8RelaxedLaneselect, - I32x4RelaxedLaneselect, - I64x2RelaxedLaneselect, + I8x16RelaxedLaneselect, I16x8RelaxedLaneselect, + I32x4RelaxedLaneselect, I64x2RelaxedLaneselect, F32x4RelaxedMin, F32x4RelaxedMax, F64x2RelaxedMin, F64x2RelaxedMax, I16x8RelaxedQ15mulrS, @@ -496,88 +797,144 @@ pub enum Instruction { I32x4RelaxedDotI8x16I7x16AddS, } -const _: () = assert!(core::mem::size_of::() <= 16); +const _: () = assert!(core::mem::size_of::() == 8); impl Instruction { + /// Returns the largest module-local memory index used by this instruction. #[inline] - pub const fn memory_addr(&self) -> Option { - match self { - Self::IncMemoryLocal32(arg, ..) - | Self::IncMemoryLocal64(arg, ..) - | Self::StoreLocalLocal32(arg, ..) - | Self::StoreLocalLocal64(arg, ..) - | Self::StoreLocalLocal128(arg, ..) - | Self::LoadLocal32(arg, ..) - | Self::LoadLocal64(arg, ..) - | Self::LoadLocal8S32(arg, ..) - | Self::LoadLocal8U32(arg, ..) - | Self::LoadLocal16S32(arg, ..) - | Self::LoadLocal16U32(arg, ..) - | Self::LoadLocalTee32(arg, ..) - | Self::LoadLocalSet32(arg, ..) - | Self::LoadLocalTee8S32(arg, ..) - | Self::LoadLocalTee8U32(arg, ..) - | Self::LoadLocalTee16S32(arg, ..) - | Self::LoadLocalTee16U32(arg, ..) - | Self::LoadLocalSet8S32(arg, ..) - | Self::LoadLocalSet8U32(arg, ..) - | Self::LoadLocalSet16S32(arg, ..) - | Self::LoadLocalSet16U32(arg, ..) - | Self::LoadLocalTee128(arg, ..) - | Self::LoadLocalSet128(arg, ..) - | Self::I32Load(arg) - | Self::I64Load(arg) - | Self::F32Load(arg) - | Self::F64Load(arg) - | Self::I32Load8S(arg) - | Self::I32Load8U(arg) - | Self::I32Load16S(arg) - | Self::I32Load16U(arg) - | Self::I64Load8S(arg) - | Self::I64Load8U(arg) - | Self::I64Load16S(arg) - | Self::I64Load16U(arg) - | Self::I64Load32S(arg) - | Self::I64Load32U(arg) - | Self::I32Store(arg) - | Self::I64Store(arg) - | Self::F32Store(arg) - | Self::F64Store(arg) - | Self::FMaStoreF32(arg) - | Self::FMaStoreF64(arg) - | Self::I32Store8(arg) - | Self::I32Store16(arg) - | Self::I64Store8(arg) - | Self::I64Store16(arg) - | Self::I64Store32(arg) - | Self::V128Load(arg) - | Self::V128Load8x8S(arg) - | Self::V128Load8x8U(arg) - | Self::V128Load16x4S(arg) - | Self::V128Load16x4U(arg) - | Self::V128Load32x2S(arg) - | Self::V128Load32x2U(arg) - | Self::V128Load8Splat(arg) - | Self::V128Load16Splat(arg) - | Self::V128Load32Splat(arg) - | Self::V128Load64Splat(arg) - | Self::V128Load8Lane(arg, ..) - | Self::V128Load16Lane(arg, ..) - | Self::V128Load32Lane(arg, ..) - | Self::V128Load64Lane(arg, ..) - | Self::V128Load32Zero(arg) - | Self::V128Load64Zero(arg) - | Self::V128Store(arg) - | Self::V128Store8Lane(arg, ..) - | Self::V128Store16Lane(arg, ..) - | Self::V128Store32Lane(arg, ..) - | Self::V128Store64Lane(arg, ..) => Some(arg.mem_addr()), - Self::MemorySize(mem) | Self::MemoryGrow(mem) | Self::MemoryFill(mem) | Self::MemoryFillImm(mem, ..) => { - Some(*mem) + pub fn memory_addr(&self, data: &super::WasmFunctionData) -> Option { + use Instruction::*; + match *self { + IncMemoryLocal32(arg) + | IncMemoryLocal64(arg) + | StoreLocalLocal32(arg) + | StoreLocalLocal64(arg) + | StoreLocalLocal128(arg) + | LoadLocal32(arg) + | LoadLocal64(arg) + | LoadLocal8S32(arg) + | LoadLocal8U32(arg) + | LoadLocal16S32(arg) + | LoadLocal16U32(arg) + | LoadLocalTee32(arg) + | LoadLocalSet32(arg) + | LoadLocalTee8S32(arg) + | LoadLocalTee8U32(arg) + | LoadLocalTee16S32(arg) + | LoadLocalTee16U32(arg) + | LoadLocalSet8S32(arg) + | LoadLocalSet8U32(arg) + | LoadLocalSet16S32(arg) + | LoadLocalSet16U32(arg) + | LoadLocalTee128(arg) + | LoadLocalSet128(arg) => Some(arg.memory_arg_idx.get(data).mem_addr()), + I32Load(index) + | I64Load(index) + | F32Load(index) + | F64Load(index) + | I32Load8S(index) + | I32Load8U(index) + | I32Load16S(index) + | I32Load16U(index) + | I64Load8S(index) + | I64Load8U(index) + | I64Load16S(index) + | I64Load16U(index) + | I64Load32S(index) + | I64Load32U(index) + | I32Store(index) + | I64Store(index) + | F32Store(index) + | F64Store(index) + | I32Store8(index) + | I32Store16(index) + | I64Store8(index) + | I64Store16(index) + | I64Store32(index) + | V128Load(index) + | V128Load8x8S(index) + | V128Load8x8U(index) + | V128Load16x4S(index) + | V128Load16x4U(index) + | V128Load32x2S(index) + | V128Load32x2U(index) + | V128Load8Splat(index) + | V128Load16Splat(index) + | V128Load32Splat(index) + | V128Load64Splat(index) + | V128Load32Zero(index) + | V128Load64Zero(index) + | V128Store(index) => Some(index.get(data).mem_addr()), + V128Load8Lane(arg) | V128Load16Lane(arg) | V128Load32Lane(arg) | V128Load64Lane(arg) + | V128Store8Lane(arg) | V128Store16Lane(arg) | V128Store32Lane(arg) | V128Store64Lane(arg) => { + Some(arg.memory_arg_idx.get(data).mem_addr()) + } + FMaStoreF32(arg) | FMaStoreF64(arg) => Some(arg.mem_addr()), + MemorySize(memory) | MemoryGrow(memory) | MemoryFill(memory) => Some(memory), + MemoryFillConst(index) => Some(index.get(data).memory), + MemoryInit(index) => Some(index.get(data).second), + MemoryCopy(index) => { + let value = index.get(data); + Some(value.first.max(value.second)) } - Self::MemoryInit(_, mem) => Some(*mem), - Self::MemoryCopy { dst_mem, src_mem } => Some(if *dst_mem >= *src_mem { *dst_mem } else { *src_mem }), _ => None, } } } + +#[cfg(test)] +mod tests { + use alloc::vec; + + use super::*; + + #[test] + fn compact_instruction_layout_is_exact() { + assert_eq!(core::mem::size_of::(), 8); + assert_eq!(core::mem::size_of::(), 6); + assert_eq!(core::mem::size_of::(), 6); + assert_eq!(core::mem::size_of::(), 6); + } + + #[test] + fn operand_lanes_round_trip_max_values() { + let memory = MemoryArg::new(u64::MAX, u32::MAX); + assert_eq!(MemoryArg::decode(memory.encode()), memory); + + let value = Operand128::default() + .with_u8::<0>(u8::MAX) + .with_u16::<1>(u16::MAX) + .with_u32::<3>(u32::MAX) + .with_u64::<7>(u64::MAX); + assert_eq!( + (value.u8::<0>(), value.u16::<1>(), value.u32::<3>(), value.u64::<7>()), + (u8::MAX, u16::MAX, u32::MAX, u64::MAX) + ); + + let bytes = [u8::MAX; 16]; + assert_eq!(Operand128::from_le_bytes(bytes).to_le_bytes(), bytes); + } + + #[test] + fn v128_operand_views_round_trip_max_bytes() { + let value = OperandIdx::::new(0); + let local = OperandIdx::::new(0); + let global = OperandIdx::::new(1); + let set = OperandIdx::::new(2); + let data = super::super::WasmFunctionData { + operands128: vec![V128Operand { value: [u8::MAX; 16] }.encode()].into_boxed_slice(), + operands64: vec![ + LocalV128 { local: u16::MAX, value }.encode(), + GlobalV128 { global: u32::MAX, value }.encode(), + LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }.encode(), + ] + .into_boxed_slice(), + ..Default::default() + }; + + assert_eq!(value.get(&data).value, [u8::MAX; 16]); + assert_eq!(local.get(&data), LocalV128 { local: u16::MAX, value }); + assert_eq!(global.get(&data), GlobalV128 { global: u32::MAX, value }); + assert_eq!(set.get(&data), LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }); + } +} diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 9a7071c..bd92753 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -22,10 +22,12 @@ const fn max_page_count(arch: MemoryArch, page_size: u64) -> u64 { } mod instructions; +mod operands; mod reference; mod types; mod value; pub use instructions::*; +pub use operands::*; pub use reference::*; pub use types::*; pub use value::*; @@ -472,19 +474,12 @@ pub struct WasmFunction { #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct WasmFunctionData { - pub v128_constants: Box<[[u8; 16]]>, + pub operands64: Box<[Operand64]>, + pub operands128: Box<[Operand128]>, pub branch_table_targets: Box<[u32]>, pub exception_handlers: Box<[ExceptionHandler]>, } -impl WasmFunctionData { - /// Panics if `idx` is out of bounds. - #[inline(always)] - pub fn v128_const(&self, idx: ConstIdx) -> [u8; 16] { - *self.v128_constants.get(idx as usize).unwrap_or_else(|| unreachable!("invalid v128 constant index: {idx}")) - } -} - /// A WebAssembly Module Export #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs new file mode 100644 index 0000000..3cc311c --- /dev/null +++ b/crates/types/src/operands.rs @@ -0,0 +1,177 @@ +use core::marker::PhantomData; + +use crate::WasmFunctionData; + +/// An index into the operand lane used by `T`. +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "archive", serde(transparent))] +#[repr(transparent)] +pub struct OperandIdx { + index: u32, + #[cfg_attr(feature = "archive", serde(skip))] + marker: PhantomData, +} + +impl OperandIdx { + #[inline] + #[doc(hidden)] + pub const fn new(index: u32) -> Self { + Self { index, marker: PhantomData } + } + + /// Returns the underlying lane index. + #[inline] + pub const fn index(self) -> u32 { + self.index + } +} + +impl OperandIdx { + /// Returns the typed operand at this index. + /// + /// Panics if the index is outside its statically selected operand lane. + #[inline(always)] + pub fn get(self, data: &WasmFunctionData) -> T { + T::decode(T::Raw::get(data, self.index)) + } +} + +impl Copy for OperandIdx {} + +impl Clone for OperandIdx { + fn clone(&self) -> Self { + *self + } +} + +impl PartialEq for OperandIdx { + fn eq(&self, other: &Self) -> bool { + self.index == other.index + } +} + +impl Eq for OperandIdx {} + +#[cfg(feature = "debug")] +impl core::fmt::Debug for OperandIdx { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.index.fmt(formatter) + } +} + +pub(crate) mod sealed { + pub trait Sealed {} +} + +/// A typed view stored in one of the per-function operand lanes. +pub trait OperandType: sealed::Sealed + Copy { + #[doc(hidden)] + type Raw: RawOperand; + + #[doc(hidden)] + fn decode(raw: Self::Raw) -> Self; + #[doc(hidden)] + fn encode(self) -> Self::Raw; +} + +#[doc(hidden)] +pub trait RawOperand: sealed::Sealed + Copy { + fn get(data: &WasmFunctionData, index: u32) -> Self; +} + +macro_rules! define_operand { + ($name:ident, $len:literal, $lane:ident) => { + #[doc = concat!("Raw fields stored in a per-function ", $len, "-byte operand lane.")] + #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)] + #[cfg_attr(feature = "debug", derive(Debug))] + #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] + #[repr(transparent)] + pub struct $name([u8; $len]); + + impl sealed::Sealed for $name {} + + impl RawOperand for $name { + #[inline(always)] + fn get(data: &WasmFunctionData, index: u32) -> Self { + *data.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) + } + } + + impl $name { + /// Returns the byte at `OFFSET`. + #[inline] + pub fn u8(self) -> u8 { + const { assert!(OFFSET < $len) }; + self.0[OFFSET] + } + + /// Returns the little-endian `u16` at `OFFSET`. + #[inline] + pub fn u16(self) -> u16 { + const { assert!(OFFSET + 2 <= $len) }; + u16::from_le_bytes(self.0[OFFSET..OFFSET + 2].try_into().unwrap_or_else(|_| unreachable!())) + } + + /// Returns the little-endian `u32` at `OFFSET`. + #[inline] + pub fn u32(self) -> u32 { + const { assert!(OFFSET + 4 <= $len) }; + u32::from_le_bytes(self.0[OFFSET..OFFSET + 4].try_into().unwrap_or_else(|_| unreachable!())) + } + + /// Returns the little-endian `u64` at `OFFSET`. + #[inline] + pub fn u64(self) -> u64 { + const { assert!(OFFSET + 8 <= $len) }; + u64::from_le_bytes(self.0[OFFSET..OFFSET + 8].try_into().unwrap_or_else(|_| unreachable!())) + } + + /// Builds an operand from its raw little-endian bytes. + #[inline] + pub fn from_le_bytes(value: [u8; $len]) -> Self { + Self(value) + } + + /// Returns the raw little-endian bytes. + #[inline] + pub fn to_le_bytes(self) -> [u8; $len] { + self.0 + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u8(mut self, value: u8) -> Self { + const { assert!(OFFSET < $len) }; + self.0[OFFSET] = value; + self + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u16(mut self, value: u16) -> Self { + const { assert!(OFFSET + 2 <= $len) }; + self.0[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes()); + self + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u32(mut self, value: u32) -> Self { + const { assert!(OFFSET + 4 <= $len) }; + self.0[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes()); + self + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u64(mut self, value: u64) -> Self { + const { assert!(OFFSET + 8 <= $len) }; + self.0[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes()); + self + } + } + }; +} + +define_operand!(Operand64, 8, operands64); +define_operand!(Operand128, 16, operands128); diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index 9ed5df1..ed59ae5 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -67,6 +67,18 @@ impl RefType { pub const EXTERNREF: Self = Self::new_abstract(true, AbstractHeapType::Extern); pub const EXNREF: Self = Self::new_abstract(true, AbstractHeapType::Exn); + #[inline] + #[doc(hidden)] + pub const fn to_bits(self) -> u32 { + self.0 + } + + #[inline] + pub(crate) const fn from_bits(bits: u32) -> Option { + let ty = Self(bits); + if ty.is_concrete() || ty.abstract_heap_type().is_some() { Some(ty) } else { None } + } + #[inline] pub const fn new_abstract(nullable: bool, heap_type: AbstractHeapType) -> Self { Self((nullable as u32) << 31 | heap_type as u32) -- cgit v1.3.1