diff options
Diffstat (limited to 'crates')
29 files changed, 512 insertions, 686 deletions
diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 3f905d4..0cd5c34 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -9,7 +9,8 @@ use anyhow::{Context, Result, anyhow, bail}; use log::{debug, error}; use tinywasm::types::{MemoryType, RefType, RefValue, TableType, WasmType, WasmValue}; use tinywasm::{ExecProgress, Global, HostFunction, Imports, Memory, Module, ModuleInstance, Store, Table}; -use wast::{QuoteWat, core::AbstractHeapType}; +use wast::QuoteWat; +use wast::core::{AbstractHeapType, NanPattern}; const TEST_TIME_SLICE: Duration = Duration::from_millis(20); const TEST_MAX_SUSPENSIONS: u32 = 1000; @@ -18,6 +19,15 @@ const ACCEPTED_MALFORMED_MESSAGES: &[&str] = &["integer representation too long", "zero byte expected", "zero flag expected"]; const ACCEPTED_INVALID_MESSAGES: &[&str] = &["multiple memories"]; +macro_rules! float_value { + ($pattern:expr, $float:ty, $variant:ident) => { + match $pattern { + NanPattern::CanonicalNan | NanPattern::ArithmeticNan => WasmValue::$variant(<$float>::NAN), + NanPattern::Value(value) => WasmValue::$variant(<$float>::from_bits(value.bits)), + } + }; +} + #[derive(Default)] struct ModuleRegistry { definitions: HashMap<String, Module>, @@ -845,10 +855,10 @@ fn wastarg2tinywasmvalue(store: &mut Store, arg: wast::WastArg) -> Result<WasmVa fn wast_v128_to_bytes(i: wast::core::V128Pattern) -> [u8; 16] { let res: Vec<u8> = match i { wast::core::V128Pattern::F32x4(f) => { - f.iter().flat_map(|v| nanpattern2tinywasmvalue(*v).unwrap().as_f32().unwrap().to_le_bytes()).collect() + f.iter().flat_map(|v| float_value!(*v, f32, F32).as_f32().unwrap().to_le_bytes()).collect() } wast::core::V128Pattern::F64x2(f) => { - f.iter().flat_map(|v| nanpattern2tinywasmvalue(*v).unwrap().as_f64().unwrap().to_le_bytes()).collect() + f.iter().flat_map(|v| float_value!(*v, f64, F64).as_f64().unwrap().to_le_bytes()).collect() } wast::core::V128Pattern::I16x8(f) => f.iter().flat_map(|v| v.to_le_bytes()).collect(), wast::core::V128Pattern::I32x4(f) => f.iter().flat_map(|v| v.to_le_bytes()).collect(), @@ -920,8 +930,8 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result<ExpectedVal RefStruct, V128, }; Ok(match ret { - F32(f) => ExpectedValue::Exact(nanpattern2tinywasmvalue(f)?), - F64(f) => ExpectedValue::Exact(nanpattern2tinywasmvalue(f)?), + F32(f) => ExpectedValue::Exact(float_value!(f, f32, F32)), + F64(f) => ExpectedValue::Exact(float_value!(f, f64, F64)), I32(i) => ExpectedValue::Exact(WasmValue::I32(i)), I64(i) => ExpectedValue::Exact(WasmValue::I64(i)), V128(i) => ExpectedValue::Exact(WasmValue::V128(wast_v128_to_bytes(i))), @@ -945,63 +955,6 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result<ExpectedVal }) } -enum Bits { - U32(u32), - U64(u64), -} - -trait FloatToken { - fn bits(&self) -> Bits; - fn canonical_nan() -> WasmValue; - fn arithmetic_nan() -> WasmValue; - fn value(&self) -> WasmValue { - match self.bits() { - Bits::U32(v) => WasmValue::F32(f32::from_bits(v)), - Bits::U64(v) => WasmValue::F64(f64::from_bits(v)), - } - } -} - -impl FloatToken for wast::token::F32 { - fn bits(&self) -> Bits { - Bits::U32(self.bits) - } - - fn canonical_nan() -> WasmValue { - WasmValue::F32(f32::NAN) - } - - fn arithmetic_nan() -> WasmValue { - WasmValue::F32(f32::NAN) - } -} - -impl FloatToken for wast::token::F64 { - fn bits(&self) -> Bits { - Bits::U64(self.bits) - } - - fn canonical_nan() -> WasmValue { - WasmValue::F64(f64::NAN) - } - - fn arithmetic_nan() -> WasmValue { - WasmValue::F64(f64::NAN) - } -} - -fn nanpattern2tinywasmvalue<T>(arg: wast::core::NanPattern<T>) -> Result<WasmValue> -where - T: FloatToken, -{ - use wast::core::NanPattern::{ArithmeticNan, CanonicalNan, Value}; - Ok(match arg { - CanonicalNan => T::canonical_nan(), - ArithmeticNan => T::arithmetic_nan(), - Value(v) => v.value(), - }) -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs index 4fc74d5..b4ad0b8 100644 --- a/crates/tinywasm/src/engine.rs +++ b/crates/tinywasm/src/engine.rs @@ -51,16 +51,16 @@ pub enum FuelPolicy { } /// Default size for the 32-bit value stack (i32, f32, ref values). -pub const DEFAULT_VALUE_STACK_32_SIZE: usize = 36 * 1024; // 36k slots +const DEFAULT_VALUE_STACK_32_SIZE: usize = 36 * 1024; // 36k slots /// Default size for the 64-bit value stack (i64, f64 values). -pub const DEFAULT_VALUE_STACK_64_SIZE: usize = 32 * 1024; // 32k slots +const DEFAULT_VALUE_STACK_64_SIZE: usize = 32 * 1024; // 32k slots /// Default size for the 128-bit value stack (v128 values). -pub const DEFAULT_VALUE_STACK_128_SIZE: usize = 4 * 1024; // 4k slots +const DEFAULT_VALUE_STACK_128_SIZE: usize = 4 * 1024; // 4k slots /// Default maximum size for the call stack (function frames). -pub const DEFAULT_MAX_CALL_STACK_SIZE: usize = 1024; // 1024 frames +const DEFAULT_MAX_CALL_STACK_SIZE: usize = 1024; // 1024 frames /// Stack allocation policy. #[derive(Clone, Copy, PartialEq, Eq)] diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs index aa54e1d..bdc50a3 100644 --- a/crates/tinywasm/src/func/context.rs +++ b/crates/tinywasm/src/func/context.rs @@ -21,12 +21,11 @@ impl FuncContext<'_> { } /// Get the module instance. - pub fn module(&self) -> crate::ModuleInstance { + pub fn module(&self) -> &crate::ModuleInstance { unwrap_or_unreachable!( self.store.get_module_instance(self.module_id), "invalid module instance id in host function context" ) - .clone() } /// Get a memory export. @@ -46,7 +45,7 @@ impl FuncContext<'_> { /// Get the value of a global export. pub fn global_get(&mut self, name: &str) -> Result<WasmValue> { - self.module().global_get(self.store, name) + self.module().clone().global_get(self.store, name) } /// Get a global export. @@ -56,7 +55,7 @@ impl FuncContext<'_> { /// Set the value of a mutable global export. pub fn global_set(&mut self, name: &str, value: WasmValue) -> Result<()> { - self.module().global_set(self.store, name, value) + self.module().clone().global_set(self.store, name, value) } /// Charge additional fuel from the currently running resumable invocation. @@ -98,11 +97,11 @@ impl FuncContext<'_> { /// Calls a Store-aware function reference in the current module context. pub fn call_ref(&mut self, func: FuncRef, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { - let addr = func.addr(self.store.store_id()).ok_or(crate::Trap::InvalidStore)?; + let addr = func.addr(self.store.id()).ok_or(crate::Trap::InvalidStore)?; if self.store.state.funcs.get(addr as usize).is_none() { return Err(crate::Trap::InvalidReference.into()); } - let function = Function { item: crate::StoreItem::new(self.store.store_id(), addr), module_id: self.module_id }; + let function = Function { item: crate::StoreItem::new(self.store.id(), addr), module_id: self.module_id }; self.call_untyped(&function, args, results) } @@ -132,7 +131,7 @@ impl FuncContext<'_> { let value_stack_base = store.value_stack.base(); func.func.call_untyped(store, params, results, call_stack_base, value_stack_base)?; values.drain(..param_count); - R::from_wasm_values_exact(&mut values.drain(..)) + R::from_wasm_values(&mut values.drain(..)) }) } else { let call_stack_base = self.store.call_stack.len(); diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 064f6c7..5e3fefa 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -1,7 +1,7 @@ use alloc::{boxed::Box, vec::Vec}; use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType}; -use super::{FromWasmValues, FuncContext, IntoWasmValues, ToWasmTypes}; +use super::{FromWasmValues, FuncContext, IntoWasmValues}; use crate::shared::StoreShared; use crate::store::FuncValueTypes; use crate::{Function, FunctionInstance, Result, Store, WasmValue}; @@ -33,7 +33,7 @@ impl HostFunction { pub(crate) fn instantiate_registered(&self, store: &mut Store, type_addr: TypeAddr) -> Function { let addr = store .add_func(FunctionInstance { type_addr, inner: crate::store::FunctionInstanceInner::Host(self.clone()) }); - Function { item: crate::StoreItem::new(store.store_id(), addr), module_id: 0 } + Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } } /// Resolves the importing module's types without allocating a function instance. @@ -213,10 +213,10 @@ impl HostFunction { pub fn from<F, P, R>(func: F) -> Self where F: Fn(FuncContext<'_>, P) -> Result<R> + HostFunctionCallback + 'static, - P: FromWasmValues + ToWasmTypes + 'static, - R: IntoWasmValues + ToWasmTypes + 'static, + P: FromWasmValues + 'static, + R: IntoWasmValues + 'static, { - let ty = FuncType::new(&P::wasm_types(), &R::wasm_types()); + let ty = FuncType::new(P::WASM_TYPES, R::WASM_TYPES); let func = TypedHostCallbackImpl { func, marker: core::marker::PhantomData }; Self(StoreShared::new(HostFunctionInner { ty, callback: HostCallback::Typed(Box::new(func)) })) } @@ -261,7 +261,7 @@ where { fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { let mut values = args.iter().cloned(); - let params = cold_err!(P::from_wasm_values_exact(&mut values))?; + let params = cold_err!(P::from_wasm_values(&mut values))?; let mut values = (self.func)(ctx, params)?.into_wasm_values(); for result in results { *result = cold_err!(values.next().ok_or_else(|| crate::Error::other("not enough typed function results")))?; @@ -279,7 +279,7 @@ where }; let params = { let mut values = store.stack_value_iter(type_addr, FuncValueTypes::Params, base)?; - cold_err!(P::from_wasm_values_exact(&mut values)) + cold_err!(P::from_wasm_values(&mut values)) }; store.value_stack.truncate_to_base(base); let result = cold_err!((self.func)(FuncContext { store, module_id }, params?))?; diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs index 2fbc22f..3f5ef54 100644 --- a/crates/tinywasm/src/func/mod.rs +++ b/crates/tinywasm/src/func/mod.rs @@ -16,7 +16,7 @@ pub use host::HostFunction; #[doc(hidden)] pub use host::HostFunctionCallback; pub use resume::{ExecProgress, FuncExecution, FuncExecutionTyped}; -pub use values::{FromWasmValues, IntoWasmValues, ToWasmType, ToWasmTypes}; +pub use values::{FromWasmValues, IntoWasmValues, WasmTypes, WasmValueType}; fn write_typed_params(params: &mut [WasmValue], mut values: impl Iterator<Item = WasmValue>) -> Result<()> { for param in params { @@ -42,7 +42,7 @@ impl Function { /// Returns this function as a Store-aware WebAssembly function reference. pub fn as_func_ref(&self, store: &Store) -> Result<FuncRef> { self.item.validate_store(store)?; - Ok(FuncRef::new(store.store_id(), self.addr())) + Ok(FuncRef::new(store.id(), self.addr())) } #[inline] @@ -219,7 +219,7 @@ impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> { let (params, results) = values.split_at_mut(param_count); self.func.call(store, params, results)?; values.drain(..param_count); - R::from_wasm_values_exact(&mut values.drain(..)) + R::from_wasm_values(&mut values.drain(..)) }) } else { store.enter_execution()?; diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs index cc461a7..c0d7f23 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -16,18 +16,25 @@ pub enum ExecProgress<T> { /// Resumable execution for an untyped function call. #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] pub struct FuncExecution<'store> { - execution: ExecutionCore<'store>, + execution: ExecutionInner<'store>, results: &'store mut [WasmValue], } +/// Resumable execution for a typed function call. +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +pub struct FuncExecutionTyped<'store, R> { + execution: ExecutionInner<'store>, + result: Option<R>, +} + #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -struct ExecutionCore<'store> { +struct ExecutionInner<'store> { store: &'store mut Store, - state: FuncExecutionState, + state: ExecState, } #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -enum FuncExecutionState { +enum ExecState { Running { callframe: CallFrame, root_func_addr: FuncAddr }, Completed(Option<CallResult>), } @@ -38,13 +45,6 @@ enum CallResult { Written, } -/// Resumable execution for a typed function call. -#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -pub struct FuncExecutionTyped<'store, R> { - execution: ExecutionCore<'store>, - result: Option<R>, -} - impl Function { /// Call a function and return a resumable execution handle. /// @@ -60,12 +60,12 @@ impl Function { self.validate_call(store, params, results.len())?; store.enter_execution()?; - let result: Result<FuncExecutionState> = (|| { + let result: Result<ExecState> = (|| { let func_instance = store.state.get_func(self.addr()).clone(); match &func_instance.inner { crate::store::FunctionInstanceInner::Host(host_func) => { host_func.clone().call_values(store, self.module_id, func_instance.type_addr, params, results)?; - Ok(FuncExecutionState::Completed(Some(CallResult::Written))) + Ok(ExecState::Completed(Some(CallResult::Written))) } crate::store::FunctionInstanceInner::Wasm(wasm_func) => { store.call_stack.clear(); @@ -74,25 +74,25 @@ impl Function { let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)?; let callframe = CallFrame::new(self.addr(), locals_base, wasm_func.func.locals); - Ok(FuncExecutionState::Running { callframe, root_func_addr: self.addr() }) + Ok(ExecState::Running { callframe, root_func_addr: self.addr() }) } } })(); store.exit_execution(); let state = result?; - Ok(FuncExecution { execution: ExecutionCore { store, state }, results }) + Ok(FuncExecution { execution: ExecutionInner { store, state }, results }) } } -impl ExecutionCore<'_> { +impl ExecutionInner<'_> { fn resume_raw( &mut self, run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState>, ) -> Result<ExecProgress<CallResult>> { let (callframe, root_func_addr) = match &mut self.state { - FuncExecutionState::Running { callframe, root_func_addr } => (*callframe, *root_func_addr), - FuncExecutionState::Completed(result) => { + ExecState::Running { callframe, root_func_addr } => (*callframe, *root_func_addr), + ExecState::Completed(result) => { return result .take() .map(ExecProgress::Completed) @@ -109,7 +109,7 @@ impl ExecutionCore<'_> { Err(error) => { self.store.call_stack.clear(); self.store.value_stack.clear(); - self.state = FuncExecutionState::Completed(None); + self.state = ExecState::Completed(None); return Err(error); } }; @@ -118,11 +118,11 @@ impl ExecutionCore<'_> { crate::interpreter::ExecState::Completed => { let func = self.store.state.get_func(root_func_addr); let result_ty = func.type_addr; - self.state = FuncExecutionState::Completed(None); + self.state = ExecState::Completed(None); Ok(ExecProgress::Completed(CallResult::Stack { type_addr: result_ty })) } crate::interpreter::ExecState::Suspended(callframe) => { - let FuncExecutionState::Running { callframe: current, .. } = &mut self.state else { + let ExecState::Running { callframe: current, .. } = &mut self.state else { unreachable!("invalid function execution state") }; *current = callframe; @@ -206,21 +206,21 @@ impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> { let func = store.state.get_func(self.func.addr()).clone(); if matches!(&func.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) { let result = self.call(store, params)?; - let execution = ExecutionCore { store, state: FuncExecutionState::Completed(None) }; + let execution = ExecutionInner { store, state: ExecState::Completed(None) }; return Ok(FuncExecutionTyped { execution, result: Some(result) }); } store.enter_execution()?; - let result: Result<FuncExecutionState> = (|| { + let result: Result<ExecState> = (|| { store.call_stack.clear(); store.value_stack.clear(); match self.func.prepare_typed(store, &func, params.into_wasm_values(), StackBase::default())? { - Some(callframe) => Ok(FuncExecutionState::Running { callframe, root_func_addr: self.func.addr() }), - None => Ok(FuncExecutionState::Completed(Some(CallResult::Stack { type_addr: func.type_addr }))), + Some(callframe) => Ok(ExecState::Running { callframe, root_func_addr: self.func.addr() }), + None => Ok(ExecState::Completed(Some(CallResult::Stack { type_addr: func.type_addr }))), } })(); store.exit_execution(); - let execution = ExecutionCore { store, state: result? }; + let execution = ExecutionInner { store, state: result? }; Ok(FuncExecutionTyped { execution, result: None }) } } diff --git a/crates/tinywasm/src/func/values.rs b/crates/tinywasm/src/func/values.rs index 19d0673..11d3b17 100644 --- a/crates/tinywasm/src/func/values.rs +++ b/crates/tinywasm/src/func/values.rs @@ -1,70 +1,53 @@ use crate::{Error, Result}; -use alloc::borrow::Cow; use tinywasm_types::WasmType; use crate::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, StructRef, WasmValue}; +/// Describes the WebAssembly value types produced by a Rust value or tuple shape. +pub trait WasmTypes { + /// Flattened WebAssembly value types for this shape. + const WASM_TYPES: &'static [WasmType]; +} + +/// Describes the WebAssembly value types produced by a scalar Rust type. +pub trait WasmValueType { + /// The single WebAssembly value type for this scalar type. + const WASM_TYPE: WasmType; +} + /// Convert a Rust value or tuple into WebAssembly values. -pub trait IntoWasmValues { +pub trait IntoWasmValues: WasmTypes { /// Return the flattened WebAssembly values. fn into_wasm_values(self) -> impl Iterator<Item = WasmValue>; } /// Convert WebAssembly values into a Rust value or tuple. -pub trait FromWasmValues: Sized { - /// Read this value from a flattened WebAssembly value iterator. +pub trait FromWasmValues: WasmTypes + Sized { + /// Read this value and reject unconsumed WebAssembly values. fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self>; - - /// Read one value and reject unconsumed iterator items. - fn from_wasm_values_exact(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> { - let result = Self::from_wasm_values(values)?; - if values.next().is_some() { - return Err(Error::other("typed conversion did not consume all WebAssembly values")); - } - Ok(result) - } } -/// Describes the WebAssembly value types produced by a Rust value or tuple shape. -pub trait ToWasmTypes { - /// Static WebAssembly types for this shape. - /// - /// Implementations that require runtime construction may set this to `None`, - /// but must then override [`Self::wasm_types`]. - const WASM_TYPES: Option<&'static [WasmType]>; - - /// Return the flattened WebAssembly value types for this tuple shape. - fn wasm_types() -> Cow<'static, [WasmType]> { - Cow::Borrowed(Self::WASM_TYPES.expect("dynamic ToWasmTypes implementation must override wasm_types")) - } -} - -/// Describes the WebAssembly value types produced by a scalar Rust type. -pub trait ToWasmType { - /// The single WebAssembly value type for this scalar type. - const WASM_TYPE: WasmType; +fn next_value<T: TryFrom<WasmValue, Error = ()>>(values: &mut impl Iterator<Item = WasmValue>) -> Result<T> { + let value = cold_err!(values.next().ok_or_else(|| { Error::other("not enough WebAssembly values") }))?; + cold_err!(T::try_from(value).map_err(|_| { Error::other("WebAssembly value does not match the expected type") })) } -fn next_value<T: TryFrom<WasmValue, Error = ()>>(values: &mut impl Iterator<Item = WasmValue>) -> Result<T> { - let value = values.next().ok_or_else(|| { - core::hint::cold_path(); - Error::other("not enough WebAssembly values") - })?; - T::try_from(value).map_err(|_| { - core::hint::cold_path(); - Error::other("WebAssembly value does not match the expected type") - }) +fn finish_values<T>(result: T, values: &mut impl Iterator<Item = WasmValue>) -> Result<T> { + if values.next().is_some() { + return cold!(Err(Error::other("typed conversion did not consume all WebAssembly values"))); + } + Ok(result) } macro_rules! impl_scalar_wasm_traits { ($($T:ty => $val_ty:expr),+ $(,)?) => { $( - impl ToWasmType for $T { + impl WasmValueType for $T { const WASM_TYPE: WasmType = $val_ty; } - impl ToWasmTypes for $T { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$val_ty]); + impl WasmTypes for $T { + const WASM_TYPES: &'static [WasmType] = &[$val_ty]; } impl IntoWasmValues for $T { @@ -77,7 +60,8 @@ macro_rules! impl_scalar_wasm_traits { impl FromWasmValues for $T { #[inline] fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> { - next_value(values) + let result = next_value(values)?; + finish_values(result, values) } } )+ @@ -90,16 +74,16 @@ macro_rules! impl_tuple_traits { }; (@next $head:ident) => {}; ($($T:ident),+) => { - impl<$($T),+> ToWasmTypes for ($($T,)+) + impl<$($T),+> WasmTypes for ($($T,)+) where - $($T: ToWasmType,)+ + $($T: WasmValueType,)+ { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$($T::WASM_TYPE,)+]); + const WASM_TYPES: &'static [WasmType] = &[$($T::WASM_TYPE,)+]; } impl<$($T),+> IntoWasmValues for ($($T,)+) where - $($T: Into<WasmValue>,)+ + $($T: Into<WasmValue> + WasmValueType,)+ { #[allow(non_snake_case)] #[inline] @@ -111,11 +95,12 @@ macro_rules! impl_tuple_traits { impl<$($T),+> FromWasmValues for ($($T,)+) where - $($T: TryFrom<WasmValue, Error = ()>,)+ + $($T: TryFrom<WasmValue, Error = ()> + WasmValueType,)+ { #[inline] fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> { - Ok(($(next_value::<$T>(values)?,)+)) + let result = ($(next_value::<$T>(values)?,)+); + finish_values(result, values) } } @@ -151,8 +136,8 @@ impl_scalar_wasm_traits!( ); impl_tuple_traits!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20); -impl ToWasmTypes for () { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[]); +impl WasmTypes for () { + const WASM_TYPES: &'static [WasmType] = &[]; } impl IntoWasmValues for () { @@ -164,7 +149,7 @@ impl IntoWasmValues for () { impl FromWasmValues for () { #[inline] - fn from_wasm_values(_values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> { - Ok(()) + fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> { + finish_values((), values) } } diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index ea97961..08682e3 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -2,7 +2,7 @@ use alloc::{boxed::Box, format}; use core::hint::cold_path; use tinywasm_types::*; -use crate::func::{FromWasmValues, IntoWasmValues, ToWasmTypes}; +use crate::func::{FromWasmValues, IntoWasmValues, WasmTypes}; use crate::reference::StoreId; use crate::shared::StoreShared; use crate::store::MemoryInstance; @@ -125,7 +125,7 @@ impl ModuleInstance { #[inline] pub(crate) fn validate_store(&self, store: &Store) -> Result<()> { - if self.0.store_id != store.store_id() { + if self.0.store_id != store.id() { return cold!(Err(Trap::InvalidStore.into())); } Ok(()) @@ -195,7 +195,7 @@ impl ModuleInstance { store.init_data(&addrs.memories, &addrs.globals, &addrs.funcs, &module.data, &type_addrs)?; let instance = ModuleInstanceInner { - store_id: store.store_id(), + store_id: store.id(), id, type_addrs, func_addrs: addrs.funcs.into_boxed_slice(), @@ -362,7 +362,6 @@ impl ModuleInstance { /// For typed access, see [`Self::func`]. pub fn func_untyped(&self, store: &Store, name: &str) -> Result<Function> { self.validate_store(store)?; - let ExternVal::Func(func_addr) = self.require_export(name)? else { return cold!(Err(Error::Other(format!("Export is not a function: {name}")))); }; @@ -409,19 +408,13 @@ impl ModuleInstance { /// For untyped access, see [`Self::func_untyped`] and [`Self::extern_item`]. /// /// Tuples are supported up to arity 20. Use [`Self::func_untyped`] for larger signatures. - pub fn func<P: IntoWasmValues + ToWasmTypes, R: FromWasmValues + ToWasmTypes>( - &self, - store: &Store, - name: &str, - ) -> Result<FunctionTyped<P, R>> { + pub fn func<P: IntoWasmValues, R: FromWasmValues>(&self, store: &Store, name: &str) -> Result<FunctionTyped<P, R>> { self.validate_store(store)?; - let ExternVal::Func(func_addr) = self.require_export(name)? else { 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() }; - Self::validate_typed_func::<P, R>(store, &func, name)?; Ok(FunctionTyped { func, marker: core::marker::PhantomData }) } @@ -429,7 +422,7 @@ impl ModuleInstance { /// Get a typed function by its module-local index. #[cfg_attr(docsrs, doc(cfg(feature = "guest-debug")))] #[cfg(feature = "guest-debug")] - pub fn func_typed_by_index<P: IntoWasmValues + ToWasmTypes, R: FromWasmValues + ToWasmTypes>( + pub fn func_typed_by_index<P: IntoWasmValues, R: FromWasmValues>( &self, store: &Store, func_index: FuncAddr, @@ -440,21 +433,17 @@ impl ModuleInstance { } #[inline] - fn validate_typed_func<P: ToWasmTypes, R: ToWasmTypes>( - store: &Store, - func: &Function, - func_name: &str, - ) -> Result<()> { - let params = P::wasm_types(); - let results = R::wasm_types(); + fn validate_typed_func<P: WasmTypes, R: WasmTypes>(store: &Store, func: &Function, func_name: &str) -> Result<()> { + let params = P::WASM_TYPES; + let results = R::WASM_TYPES; let ty = store.state.get_func_type(func.addr()); - if ty.params() != params.as_ref() || ty.results() != results.as_ref() { + if ty.params() != params || ty.results() != results { cold_path(); #[cfg(feature = "debug")] return Err(Error::Other(format!( "function type mismatch for {func_name}: expected {:?}, actual {:?}", - FuncType::new(¶ms, &results), + FuncType::new(params, results), ty ))); @@ -469,9 +458,7 @@ impl ModuleInstance { pub fn memory(&self, name: &str) -> Result<Memory> { match self.require_export(name)? { ExternVal::Memory(mem_addr) => Ok(Memory(StoreItem::new(self.0.store_id, mem_addr))), - _ => { - cold!(Err(Error::Other(format!("Export is not a memory: {name}")))) - } + _ => cold!(Err(Error::Other(format!("Export is not a memory: {name}")))), } } @@ -491,7 +478,7 @@ impl ModuleInstance { pub fn table(&self, name: &str) -> Result<Table> { match self.require_export(name)? { ExternVal::Table(table_addr) => Ok(Table(StoreItem::new(self.0.store_id, table_addr))), - _ => Err(Error::Other(format!("Export is not a table: {name}"))), + _ => cold!(Err(Error::Other(format!("Export is not a table: {name}")))), } } @@ -511,7 +498,7 @@ impl ModuleInstance { pub fn tag(&self, name: &str) -> Result<Tag> { 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}"))), + _ => cold!(Err(Error::Other(format!("Export is not a tag: {name}")))), } } @@ -531,7 +518,7 @@ impl ModuleInstance { pub fn global(&self, name: &str) -> Result<Global> { match self.require_export(name)? { ExternVal::Global(global_addr) => Ok(Global(StoreItem::new(self.0.store_id, global_addr))), - _ => Err(Error::Other(format!("Export is not a global: {name}"))), + _ => cold!(Err(Error::Other(format!("Export is not a global: {name}")))), } } diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 4011e96..fa3f3f1 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -178,16 +178,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LocalCopy32(from, to) => Value32::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), - AddConst32(c) => { i32::stack_update(&mut self.store.value_stack, #[inline(always)] |value| value.wrapping_add(*c))?; }, - AddConst64(idx) => { let constant = idx.resolve(&self.func.data).value(); i64::stack_update(&mut self.store.value_stack, #[inline(always)] |value| value.wrapping_add(constant))?; }, - IncLocal32(arg) => { i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)); }, - IncLocal64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); }, + AddConst32(c) => { i32::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(*c)); }, + AddConst64(idx) => { let rhs = idx.resolve(&self.func.data).value(); i64::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(rhs)); }, + IncLocal32(arg) => { i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |value| value.wrapping_add(arg.value)); }, + IncLocal64(packed) => { let rhs = packed.index.resolve(&self.func.data).value(); i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |value| value.wrapping_add(rhs)); }, I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), MulAccLocal32(acc) => self.exec_mul_acc_local::<i32>(*acc, i32::wrapping_mul, i32::wrapping_add), MulAccLocal64(acc) => self.exec_mul_acc_local::<i64>(*acc, i64::wrapping_mul, i64::wrapping_add), - FMulAccLocal32(acc) => self.exec_mul_acc_local::<f32>(*acc, |a, b| a * b, |a, b| a + b), - FMulAccLocal64(acc) => self.exec_mul_acc_local::<f64>(*acc, |a, b| a * b, |a, b| a + b), + FMulAccLocal32(acc) => self.exec_mul_acc_local::<f32>(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), + FMulAccLocal64(acc) => self.exec_mul_acc_local::<f64>(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), BinOpLocalLocal32(op, a, b) => self.exec_binop_local_local::<Value32, true>(*a, *b, None, *op)?, BinOpLocalLocal64(op, a, b) => self.exec_binop_local_local::<Value64, true>(*a, *b, None, *op)?, BinOpLocalLocal128(op, a, b) => self.exec_binop_local_local::<Value128, true>(*a, *b, None, *op)?, @@ -808,13 +808,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_binop_local_const_jump(&mut self, packed: PackedOp128<BinOp, LocalUpdateOperand>) -> Option<usize> { let operand = packed.index.resolve(&self.func.data); - let value = i32::local_update( - &mut self.store.value_stack, - &self.cf, - operand.local(), - #[inline(always)] - |value| packed.op.exec(value as u32, operand.value() as u32) as i32, - ); + let value = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { + packed.op.exec(value as u32, operand.value() as u32) as i32 + }); ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) } @@ -824,13 +820,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { packed: PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>, ) -> Option<usize> { let operand = packed.index.resolve(&self.func.data); - let lhs = i32::local_update( - &mut self.store.value_stack, - &self.cf, - operand.local(), - #[inline(always)] - |value| packed.op.0.exec(value as u32, operand.value() as u32) as i32, - ); + let lhs = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { + value.wrapping_add(operand.value()) + }); let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); packed.op.1.cmp(lhs, rhs).then_some(operand.target() as usize) } @@ -841,10 +833,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { packed: PackedOp128<BinOp, LocalUpdateOperand>, ) -> Result<Option<usize>, Trap> { let operand = packed.index.resolve(&self.func.data); - let lhs = i32::stack_pop(&mut self.store.value_stack); - let value = packed.op.exec(lhs as u32, operand.value() as u32) as i32; + let value = i32::stack_update(&mut self.store.value_stack, |lhs| { + packed.op.exec(lhs as u32, operand.value() as u32) as i32 + }); i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value); - i32::stack_push(&mut self.store.value_stack, value)?; Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) } @@ -852,25 +844,18 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_binop_global_const_jump(&mut self, packed: PackedOp128<BinOp, GlobalUpdateOperand>) -> Option<usize> { let operand = packed.index.resolve(&self.func.data); let global = self.module.resolve_global_addr(operand.global()); - let value = i32::global_update( - &mut self.store.state.globals, - global, - #[inline(always)] - |value| packed.op.exec(value as u32, operand.value() as u32) as i32, - ); + let value = i32::global_update(&mut self.store.state.globals, global, |value| { + packed.op.exec(value as u32, operand.value() as u32) as i32 + }); ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) } #[inline(always)] fn exec_inc_local_jump(&mut self, index: Operand128Idx<LocalUpdateOperand>) -> Option<usize> { let operand = index.resolve(&self.func.data); - let value = i32::local_update( - &mut self.store.value_stack, - &self.cf, - operand.local(), - #[inline(always)] - |value| value.wrapping_add(operand.value()), - ); + let value = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { + value.wrapping_add(operand.value()) + }); ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) } @@ -880,9 +865,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { index: Operand128Idx<LocalUpdateOperand>, ) -> Result<Option<usize>, Trap> { let operand = index.resolve(&self.func.data); - let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(operand.value()); + let value = i32::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(operand.value())); i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value); - i32::stack_push(&mut self.store.value_stack, value)?; Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) } @@ -890,25 +874,17 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_inc_global_jump(&mut self, index: Operand128Idx<GlobalUpdateOperand>) -> Option<usize> { let operand = index.resolve(&self.func.data); let global = self.module.resolve_global_addr(operand.global()); - let value = i32::global_update( - &mut self.store.state.globals, - global, - #[inline(always)] - |value| value.wrapping_add(operand.value()), - ); + let value = + i32::global_update(&mut self.store.state.globals, global, |value| value.wrapping_add(operand.value())); ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) } #[inline(always)] fn exec_inc_local_jump_cmp_local(&mut self, packed: PackedOp128<CmpOp, LocalUpdateCmpOperand>) -> Option<usize> { let operand = packed.index.resolve(&self.func.data); - let lhs = i32::local_update( - &mut self.store.value_stack, - &self.cf, - operand.local(), - #[inline(always)] - |value| value.wrapping_add(operand.value()), - ); + let lhs = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { + value.wrapping_add(operand.value()) + }); let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) } @@ -1118,8 +1094,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ) -> Result<(), Trap> { let addr = self.module.resolve_global_addr(global); let rhs = T::global_get(&self.store.state.globals, addr); - let lhs = T::stack_pop(&mut self.store.value_stack); - T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs)) + T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs)); + Ok(()) } #[inline(always)] @@ -1141,7 +1117,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { destination: LocalAddr, op: impl BinOpExt<T>, ) -> Result<(), Trap> { - let value = T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs))?; + let value = T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs)); T::local_set(&mut self.store.value_stack, &self.cf, destination, value); Ok(()) } @@ -1156,13 +1132,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let rhs = T::stack_pop(&mut self.store.value_stack); let lhs = T::stack_pop(&mut self.store.value_stack); let product = multiply(lhs, rhs); - T::local_update( - &mut self.store.value_stack, - &self.cf, - accumulator, - #[inline(always)] - |value| add(product, value), - ); + T::local_update(&mut self.store.value_stack, &self.cf, accumulator, |value| add(product, value)); } fn exec_branch_table(&mut self, index: Operand128Idx<BranchTableOperand>) -> usize { @@ -1273,7 +1243,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } if with_ref { - self.store.value_stack.push(exception)?; + ValueRef::stack_push(&mut self.store.value_stack, exception)?; } return Ok(Some(landing_pad as usize)); } @@ -1649,7 +1619,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_ref_is_null(&mut self) -> Result<(), Trap> { let is_null = i32::from(ValueRef::stack_pop(&mut self.store.value_stack).is_null()); - self.store.value_stack.push::<i32>(is_null) + i32::stack_push(&mut self.store.value_stack, is_null) } fn exec_ref_as_non_null(&mut self) -> Result<(), Trap> { @@ -1672,7 +1642,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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)) + i32::stack_push(&mut self.store.value_stack, i32::from(matches)) } fn exec_ref_cast(&self, ty: RefType) -> Result<(), Trap> { @@ -1692,13 +1662,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } else { value.i31_u().expect("validated i31.get operand") as i32 }; - self.store.value_stack.push(value) + i32::stack_push(&mut self.store.value_stack, value) } fn push_gc_object(&mut self, type_addr: TypeAddr, values: Vec<RuntimeValue>) -> Result<(), Trap> { let roots = (&self.store.value_stack.stack_32).into_iter().copied().map(ValueRef::from_raw); let reference = self.store.state.alloc_gc_object(type_addr, values, roots)?; - self.store.value_stack.push(reference) + ValueRef::stack_push(&mut self.store.value_stack, reference) } fn exec_struct_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> { @@ -1822,7 +1792,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if self.store.state.get_type(type_addr).as_array().is_none() { return Err(Trap::Other("GC reference is not an array")); } - self.store.value_stack.push(object.values.len() as i32) + i32::stack_push(&mut self.store.value_stack, object.values.len() as i32) } fn exec_array_fill(&mut self, type_index: TypeAddr) -> Result<(), Trap> { @@ -1945,8 +1915,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_memory_size(&mut self, addr: u32) -> Result<(), Trap> { let mem = self.store.state.get_mem(self.mem_addr(addr)); match mem.is_64bit() { - true => self.store.value_stack.push::<i64>(mem.page_count as i64), - false => self.store.value_stack.push::<i32>(mem.page_count as i32), + true => i64::stack_push(&mut self.store.value_stack, mem.page_count as i64), + false => i32::stack_push(&mut self.store.value_stack, mem.page_count as i32), } } @@ -2090,9 +2060,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let addr = cold_err!(mem.effective_addr::<LOAD_SIZE>(base, m.offset()))?; let val = cold_err!(LOAD::load_at(&mem.inner, addr))?; let offset = arg.lane as usize * LOAD_SIZE; - let mut imm = Value128::stack_pop(&mut self.store.value_stack).to_mem_bytes(); - imm[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); - self.store.value_stack.push(Value128(imm))?; + Value128::stack_update(&mut self.store.value_stack, |value| { + let mut bytes = value.to_mem_bytes(); + bytes[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); + Value128(bytes) + }); Ok(()) } @@ -2106,7 +2078,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = cold_err!(mem.effective_addr::<LOAD_SIZE>(base, m.offset()))?; let value = cold_err!(LOAD::load_at(&mem.inner, addr))?; - self.store.value_stack.push(cast(value)) + TARGET::stack_push(&mut self.store.value_stack, cast(value)) } #[inline(always)] @@ -2164,7 +2136,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table_addr = self.module.resolve_table_addr(table_index); let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; let value = *self.store.state.get_table(table_addr).get(idx)?; - self.store.value_stack.push(value) + ValueRef::stack_push(&mut self.store.value_stack, value) } fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> { @@ -2178,8 +2150,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_table_size(&mut self, table_index: u32) -> Result<(), Trap> { let table = self.store.state.get_table(self.module.resolve_table_addr(table_index)); match table.kind.arch() { - MemoryArch::I32 => self.store.value_stack.push(table.size() as i32), - MemoryArch::I64 => self.store.value_stack.push(table.size() as i64), + MemoryArch::I32 => i32::stack_push(&mut self.store.value_stack, table.size() as i32), + MemoryArch::I64 => i64::stack_push(&mut self.store.value_stack, table.size() as i64), } } @@ -2210,10 +2182,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let sz = table.size(); let grew = table.grow(n, val, limiter)?; match (arch, grew) { - (MemoryArch::I32, true) => self.store.value_stack.push(sz as i32), - (MemoryArch::I32, false) => self.store.value_stack.push(-1_i32), - (MemoryArch::I64, true) => self.store.value_stack.push(sz as i64), - (MemoryArch::I64, false) => self.store.value_stack.push(-1_i64), + (MemoryArch::I32, true) => i32::stack_push(&mut self.store.value_stack, sz as i32), + (MemoryArch::I32, false) => i32::stack_push(&mut self.store.value_stack, -1), + (MemoryArch::I64, true) => i64::stack_push(&mut self.store.value_stack, sz as i64), + (MemoryArch::I64, false) => i64::stack_push(&mut self.store.value_stack, -1), } } diff --git a/crates/tinywasm/src/interpreter/num_helpers.rs b/crates/tinywasm/src/interpreter/num_helpers.rs index d35b217..591326f 100644 --- a/crates/tinywasm/src/interpreter/num_helpers.rs +++ b/crates/tinywasm/src/interpreter/num_helpers.rs @@ -35,7 +35,7 @@ macro_rules! checked_conv_float { core::hint::cold_path(); return Err(crate::Trap::IntegerOverflow.into()); } - $self.store.value_stack.push::<$to>((v as $intermediate as $to).into())?; + <$to>::stack_push(&mut $self.store.value_stack, (v as $intermediate as $to).into())?; }}; } @@ -120,18 +120,16 @@ macro_rules! impl_checked_wrapping_rem { impl TinywasmIntExt for $t { fn tw_checked_wrapping_rem(self, rhs: Self) -> Result<Self, crate::Trap> { if rhs == 0 { - Err(crate::Trap::DivisionByZero) - } else { - Ok(self.wrapping_rem(rhs)) + return Err(crate::Trap::DivisionByZero) } + Ok(self.wrapping_rem(rhs)) } fn tw_checked_div(self, rhs: Self) -> Result<Self, crate::Trap> { if rhs == 0 { - Err(crate::Trap::DivisionByZero) - } else { - self.checked_div(rhs).ok_or_else(|| crate::Trap::IntegerOverflow) + return Err(crate::Trap::DivisionByZero) } + self.checked_div(rhs).ok_or_else(|| crate::Trap::IntegerOverflow) } } )*) diff --git a/crates/tinywasm/src/interpreter/simd/instructions.rs b/crates/tinywasm/src/interpreter/simd/instructions.rs index c859caf..cd35d16 100644 --- a/crates/tinywasm/src/interpreter/simd/instructions.rs +++ b/crates/tinywasm/src/interpreter/simd/instructions.rs @@ -26,7 +26,7 @@ use core::arch::x86_64 as x86; impl Value128 { #[doc(alias = "v128.any_true")] - pub fn v128_any_true(self) -> bool { + pub(crate) fn v128_any_true(self) -> bool { simd_impl! { wasm => { wasm::v128_any_true(self.to_wasm_v128()) } generic => { self.0.iter().any(|&b| b != 0) } @@ -34,7 +34,7 @@ impl Value128 { } #[doc(alias = "v128.not")] - pub fn v128_not(self) -> Self { + pub(crate) fn v128_not(self) -> Self { simd_impl! { wasm => { Self::from_wasm_v128(wasm::v128_not(self.to_wasm_v128())) } generic => { Self(self.0.map(|b| !b)) } @@ -42,7 +42,7 @@ impl Value128 { } #[doc(alias = "v128.and")] - pub fn v128_and(self, rhs: Self) -> Self { + pub(crate) fn v128_and(self, rhs: Self) -> Self { simd_impl! { wasm => { Self::from_wasm_v128(wasm::v128_and(self.to_wasm_v128(), rhs.to_wasm_v128())) } generic => { (i128::from(self) & i128::from(rhs)).into() } @@ -50,7 +50,7 @@ impl Value128 { } #[doc(alias = "v128.andnot")] - pub fn v128_andnot(self, rhs: Self) -> Self { + pub(crate) fn v128_andnot(self, rhs: Self) -> Self { simd_impl! { wasm => { Self::from_wasm_v128(wasm::v128_andnot(self.to_wasm_v128(), rhs.to_wasm_v128())) } generic => { (i128::from(self) & !i128::from(rhs)).into() } @@ -58,7 +58,7 @@ impl Value128 { } #[doc(alias = "v128.or")] - pub fn v128_or(self, rhs: Self) -> Self { + pub(crate) fn v128_or(self, rhs: Self) -> Self { simd_impl! { wasm => { Self::from_wasm_v128(wasm::v128_or(self.to_wasm_v128(), rhs.to_wasm_v128())) } generic => { (i128::from(self) | i128::from(rhs)).into() } @@ -66,7 +66,7 @@ impl Value128 { } #[doc(alias = "v128.xor")] - pub fn v128_xor(self, rhs: Self) -> Self { + pub(crate) fn v128_xor(self, rhs: Self) -> Self { simd_impl! { wasm => { Self::from_wasm_v128(wasm::v128_xor(self.to_wasm_v128(), rhs.to_wasm_v128())) } generic => { (i128::from(self) ^ i128::from(rhs)).into() } @@ -74,7 +74,7 @@ impl Value128 { } #[doc(alias = "v128.bitselect")] - pub fn v128_bitselect(v1: Self, v2: Self, c: Self) -> Self { + pub(crate) fn v128_bitselect(v1: Self, v2: Self, c: Self) -> Self { simd_impl! { wasm => { Self::from_wasm_v128(wasm::v128_bitselect(v1.to_wasm_v128(), v2.to_wasm_v128(), c.to_wasm_v128())) } generic => { ((i128::from(v1) & i128::from(c)) | (i128::from(v2) & !i128::from(c))).into() } @@ -82,7 +82,7 @@ impl Value128 { } #[doc(alias = "v128.load8x8_s")] - pub const fn v128_load8x8_s(src: [u8; 8]) -> Self { + pub(crate) const fn v128_load8x8_s(src: [u8; 8]) -> Self { Self::from_i16x8([ src[0] as i8 as i16, src[1] as i8 as i16, @@ -96,7 +96,7 @@ impl Value128 { } #[doc(alias = "v128.load8x8_u")] - pub const fn v128_load8x8_u(src: [u8; 8]) -> Self { + pub(crate) const fn v128_load8x8_u(src: [u8; 8]) -> Self { Self::from_u16x8([ src[0] as u16, src[1] as u16, @@ -110,7 +110,7 @@ impl Value128 { } #[doc(alias = "v128.load16x4_s")] - pub const fn v128_load16x4_s(src: [u8; 8]) -> Self { + pub(crate) const fn v128_load16x4_s(src: [u8; 8]) -> Self { Self::from_i32x4([ i16::from_le_bytes([src[0], src[1]]) as i32, i16::from_le_bytes([src[2], src[3]]) as i32, @@ -120,7 +120,7 @@ impl Value128 { } #[doc(alias = "v128.load16x4_u")] - pub const fn v128_load16x4_u(src: [u8; 8]) -> Self { + pub(crate) const fn v128_load16x4_u(src: [u8; 8]) -> Self { Self::from_u32x4([ u16::from_le_bytes([src[0], src[1]]) as u32, u16::from_le_bytes([src[2], src[3]]) as u32, @@ -130,7 +130,7 @@ impl Value128 { } #[doc(alias = "v128.load32x2_s")] - pub const fn v128_load32x2_s(src: [u8; 8]) -> Self { + pub(crate) const fn v128_load32x2_s(src: [u8; 8]) -> Self { Self::from_i64x2([ i32::from_le_bytes([src[0], src[1], src[2], src[3]]) as i64, i32::from_le_bytes([src[4], src[5], src[6], src[7]]) as i64, @@ -138,7 +138,7 @@ impl Value128 { } #[doc(alias = "v128.load32x2_u")] - pub const fn v128_load32x2_u(src: [u8; 8]) -> Self { + pub(crate) const fn v128_load32x2_u(src: [u8; 8]) -> Self { Self::from_u64x2([ u32::from_le_bytes([src[0], src[1], src[2], src[3]]) as u64, u32::from_le_bytes([src[4], src[5], src[6], src[7]]) as u64, @@ -146,7 +146,7 @@ impl Value128 { } #[doc(alias = "i8x16.swizzle")] - pub fn i8x16_swizzle(self, s: Self) -> Self { + pub(crate) fn i8x16_swizzle(self, s: Self) -> Self { simd_impl! { wasm => { Self::from_wasm_v128(wasm::i8x16_swizzle(self.to_wasm_v128(), s.to_wasm_v128())) } x86 => { @@ -182,7 +182,7 @@ impl Value128 { } #[doc(alias = "i8x16.relaxed_swizzle")] - pub fn i8x16_relaxed_swizzle(self, s: Self) -> Self { + pub(crate) fn i8x16_relaxed_swizzle(self, s: Self) -> Self { simd_impl! { wasm => { Self::from_wasm_v128(wasm::i8x16_relaxed_swizzle(self.to_wasm_v128(), s.to_wasm_v128())) } generic => { self.i8x16_swizzle(s) } @@ -190,7 +190,7 @@ impl Value128 { } #[doc(alias = "i8x16.shuffle")] - pub fn i8x16_shuffle(a: Self, b: Self, idx: Self) -> Self { + pub(crate) fn i8x16_shuffle(a: Self, b: Self, idx: Self) -> Self { simd_impl! { x86 => { let idx = idx.0; @@ -235,62 +235,62 @@ impl Value128 { } #[doc(alias = "i8x16.splat")] - pub fn splat_i8(src: i8) -> Self { + pub(crate) fn splat_i8(src: i8) -> Self { Self([src as u8; 16]) } #[doc(alias = "i8x16.replace_lane")] - pub fn i8x16_replace_lane(self, lane: u8, value: i8) -> Self { + pub(crate) fn i8x16_replace_lane(self, lane: u8, value: i8) -> Self { self.replace_lane_bytes::<1, 16>(lane, [value as u8]) } #[doc(alias = "i16x8.replace_lane")] - pub fn i16x8_replace_lane(self, lane: u8, value: i16) -> Self { + pub(crate) fn i16x8_replace_lane(self, lane: u8, value: i16) -> Self { self.replace_lane_bytes::<2, 8>(lane, value.to_le_bytes()) } #[doc(alias = "i32x4.replace_lane")] - pub fn i32x4_replace_lane(self, lane: u8, value: i32) -> Self { + pub(crate) fn i32x4_replace_lane(self, lane: u8, value: i32) -> Self { self.replace_lane_bytes::<4, 4>(lane, value.to_le_bytes()) } #[doc(alias = "i64x2.replace_lane")] - pub fn i64x2_replace_lane(self, lane: u8, value: i64) -> Self { + pub(crate) fn i64x2_replace_lane(self, lane: u8, value: i64) -> Self { self.replace_lane_bytes::<8, 2>(lane, value.to_le_bytes()) } #[doc(alias = "f32x4.replace_lane")] - pub fn f32x4_replace_lane(self, lane: u8, value: f32) -> Self { + pub(crate) fn f32x4_replace_lane(self, lane: u8, value: f32) -> Self { self.replace_lane_bytes::<4, 4>(lane, value.to_bits().to_le_bytes()) } #[doc(alias = "f64x2.replace_lane")] - pub fn f64x2_replace_lane(self, lane: u8, value: f64) -> Self { + pub(crate) fn f64x2_replace_lane(self, lane: u8, value: f64) -> Self { self.replace_lane_bytes::<8, 2>(lane, value.to_bits().to_le_bytes()) } #[doc(alias = "i8x16.all_true")] - pub fn i8x16_all_true(self) -> bool { + pub(crate) fn i8x16_all_true(self) -> bool { self.0.iter().all(|&b| b != 0) } #[doc(alias = "i16x8.all_true")] - pub fn i16x8_all_true(self) -> bool { + pub(crate) fn i16x8_all_true(self) -> bool { self.as_i16x8().iter().all(|&x| x != 0) } #[doc(alias = "i32x4.all_true")] - pub fn i32x4_all_true(self) -> bool { + pub(crate) fn i32x4_all_true(self) -> bool { self.as_i32x4().iter().all(|&x| x != 0) } #[doc(alias = "i64x2.all_true")] - pub fn i64x2_all_true(self) -> bool { + pub(crate) fn i64x2_all_true(self) -> bool { self.as_i64x2().iter().all(|&x| x != 0) } #[doc(alias = "i8x16.bitmask")] - pub fn i8x16_bitmask(self) -> u32 { + pub(crate) fn i8x16_bitmask(self) -> u32 { let bytes = self.0; let mut mask = 0u32; for (i, byte) in bytes.into_iter().enumerate() { @@ -302,7 +302,7 @@ impl Value128 { } #[doc(alias = "i16x8.bitmask")] - pub fn i16x8_bitmask(self) -> u32 { + pub(crate) fn i16x8_bitmask(self) -> u32 { let bytes = self.0; let mut mask = 0u32; for (i, lane) in bytes.as_chunks::<2>().0.iter().enumerate() { @@ -314,7 +314,7 @@ impl Value128 { } #[doc(alias = "i32x4.bitmask")] - pub fn i32x4_bitmask(self) -> u32 { + pub(crate) fn i32x4_bitmask(self) -> u32 { let bytes = self.0; let mut mask = 0u32; for (i, lane) in bytes.as_chunks::<4>().0.iter().enumerate() { @@ -326,13 +326,13 @@ impl Value128 { } #[doc(alias = "i64x2.bitmask")] - pub fn i64x2_bitmask(self) -> u32 { + pub(crate) fn i64x2_bitmask(self) -> u32 { let x = u128::from_le_bytes(self.0); (((x >> 63) & 1) as u32) | ((((x >> 127) & 1) as u32) << 1) } #[doc(alias = "i8x16.popcnt")] - pub fn i8x16_popcnt(self) -> Self { + pub(crate) fn i8x16_popcnt(self) -> Self { Self(self.0.map(|lane| lane.count_ones() as u8)) } @@ -374,17 +374,17 @@ impl Value128 { } #[doc(alias = "i8x16.avgr_u")] - pub fn i8x16_avgr_u(self, rhs: Self) -> Self { + pub(crate) fn i8x16_avgr_u(self, rhs: Self) -> Self { simd_avgr_u!(self, rhs, u8x16_avgr, u8, u16, as_u8x16, from_u8x16) } #[doc(alias = "i16x8.avgr_u")] - pub fn i16x8_avgr_u(self, rhs: Self) -> Self { + pub(crate) fn i16x8_avgr_u(self, rhs: Self) -> Self { simd_avgr_u!(self, rhs, u16x8_avgr, u16, u32, as_u16x8, from_u16x8) } #[doc(alias = "i8x16.narrow_i16x8_s")] - pub fn i8x16_narrow_i16x8_s(a: Self, b: Self) -> Self { + pub(crate) fn i8x16_narrow_i16x8_s(a: Self, b: Self) -> Self { let av = a.as_i16x8(); let bv = b.as_i16x8(); let mut out = [0i8; 16]; @@ -397,7 +397,7 @@ impl Value128 { } #[doc(alias = "i8x16.narrow_i16x8_u")] - pub fn i8x16_narrow_i16x8_u(a: Self, b: Self) -> Self { + pub(crate) fn i8x16_narrow_i16x8_u(a: Self, b: Self) -> Self { let av = a.as_i16x8(); let bv = b.as_i16x8(); let mut out = [0u8; 16]; @@ -410,7 +410,7 @@ impl Value128 { } #[doc(alias = "i16x8.narrow_i32x4_s")] - pub fn i16x8_narrow_i32x4_s(a: Self, b: Self) -> Self { + pub(crate) fn i16x8_narrow_i32x4_s(a: Self, b: Self) -> Self { let av = a.as_i32x4(); let bv = b.as_i32x4(); let mut out = [0i16; 8]; @@ -423,7 +423,7 @@ impl Value128 { } #[doc(alias = "i16x8.narrow_i32x4_u")] - pub fn i16x8_narrow_i32x4_u(a: Self, b: Self) -> Self { + pub(crate) fn i16x8_narrow_i32x4_u(a: Self, b: Self) -> Self { let av = a.as_i32x4(); let bv = b.as_i32x4(); let mut out = [0u16; 8]; @@ -436,25 +436,25 @@ impl Value128 { } #[doc(alias = "i16x8.extadd_pairwise_i8x16_s")] - pub fn i16x8_extadd_pairwise_i8x16_s(self) -> Self { + pub(crate) fn i16x8_extadd_pairwise_i8x16_s(self) -> Self { let lanes = self.as_i8x16(); Self::from_i16x8(array::from_fn(|i| lanes[i * 2] as i16 + lanes[i * 2 + 1] as i16)) } #[doc(alias = "i16x8.extadd_pairwise_i8x16_u")] - pub fn i16x8_extadd_pairwise_i8x16_u(self) -> Self { + pub(crate) fn i16x8_extadd_pairwise_i8x16_u(self) -> Self { let lanes = self.as_u8x16(); Self::from_u16x8(array::from_fn(|i| lanes[i * 2] as u16 + lanes[i * 2 + 1] as u16)) } #[doc(alias = "i32x4.extadd_pairwise_i16x8_s")] - pub fn i32x4_extadd_pairwise_i16x8_s(self) -> Self { + pub(crate) fn i32x4_extadd_pairwise_i16x8_s(self) -> Self { let lanes = self.as_i16x8(); Self::from_i32x4(array::from_fn(|i| lanes[i * 2] as i32 + lanes[i * 2 + 1] as i32)) } #[doc(alias = "i32x4.extadd_pairwise_i16x8_u")] - pub fn i32x4_extadd_pairwise_i16x8_u(self) -> Self { + pub(crate) fn i32x4_extadd_pairwise_i16x8_u(self) -> Self { let lanes = self.as_u16x8(); Self::from_u32x4(array::from_fn(|i| lanes[i * 2] as u32 + lanes[i * 2 + 1] as u32)) } @@ -490,7 +490,7 @@ impl Value128 { } #[doc(alias = "i16x8.q15mulr_sat_s")] - pub fn i16x8_q15mulr_sat_s(self, rhs: Self) -> Self { + pub(crate) fn i16x8_q15mulr_sat_s(self, rhs: Self) -> Self { let a = self.as_i16x8(); let b = rhs.as_i16x8(); let mut out = [0i16; 8]; @@ -502,7 +502,7 @@ impl Value128 { } #[doc(alias = "i32x4.dot_i16x8_s")] - pub fn i32x4_dot_i16x8_s(self, rhs: Self) -> Self { + pub(crate) fn i32x4_dot_i16x8_s(self, rhs: Self) -> Self { let a = self.as_i16x8(); let b = rhs.as_i16x8(); Self::from_i32x4(array::from_fn(|i| { @@ -521,12 +521,12 @@ impl Value128 { } #[doc(alias = "i16x8.relaxed_q15mulr_s")] - pub fn i16x8_relaxed_q15mulr_s(self, rhs: Self) -> Self { + pub(crate) fn i16x8_relaxed_q15mulr_s(self, rhs: Self) -> Self { self.i16x8_q15mulr_sat_s(rhs) } #[doc(alias = "i16x8.relaxed_dot_i8x16_i7x16_s")] - pub fn i16x8_relaxed_dot_i8x16_i7x16_s(self, rhs: Self) -> Self { + pub(crate) fn i16x8_relaxed_dot_i8x16_i7x16_s(self, rhs: Self) -> Self { let a = self.as_i8x16(); let b = rhs.as_i8x16(); Self::from_i16x8(array::from_fn(|i| { @@ -538,7 +538,7 @@ impl Value128 { } #[doc(alias = "i32x4.relaxed_dot_i8x16_i7x16_add_s")] - pub fn i32x4_relaxed_dot_i8x16_i7x16_add_s(self, rhs: Self, acc: Self) -> Self { + pub(crate) fn i32x4_relaxed_dot_i8x16_i7x16_add_s(self, rhs: Self, acc: Self) -> Self { let a = self.as_i8x16(); let b = rhs.as_i8x16(); let c = acc.as_i32x4(); @@ -595,499 +595,499 @@ impl Value128 { } #[doc(alias = "i8x16.abs")] - pub fn i8x16_abs(self) -> Self { + pub(crate) fn i8x16_abs(self) -> Self { simd_abs_const!(self, as_i8x16, from_i8x16) } #[doc(alias = "i16x8.abs")] - pub fn i16x8_abs(self) -> Self { + pub(crate) fn i16x8_abs(self) -> Self { simd_abs_const!(self, as_i16x8, from_i16x8) } #[doc(alias = "i32x4.abs")] - pub fn i32x4_abs(self) -> Self { + pub(crate) fn i32x4_abs(self) -> Self { simd_abs_const!(self, as_i32x4, from_i32x4) } #[doc(alias = "i64x2.abs")] - pub fn i64x2_abs(self) -> Self { + pub(crate) fn i64x2_abs(self) -> Self { simd_abs_const!(self, as_i64x2, from_i64x2) } #[doc(alias = "i8x16.neg")] - pub fn i8x16_neg(self) -> Self { + pub(crate) fn i8x16_neg(self) -> Self { simd_neg!(self, i8x16_neg, as_i8x16, from_i8x16) } #[doc(alias = "i16x8.neg")] - pub fn i16x8_neg(self) -> Self { + pub(crate) fn i16x8_neg(self) -> Self { simd_neg!(self, i16x8_neg, as_i16x8, from_i16x8) } #[doc(alias = "i32x4.neg")] - pub fn i32x4_neg(self) -> Self { + pub(crate) fn i32x4_neg(self) -> Self { simd_neg!(self, i32x4_neg, as_i32x4, from_i32x4) } #[doc(alias = "i64x2.neg")] - pub fn i64x2_neg(self) -> Self { + pub(crate) fn i64x2_neg(self) -> Self { simd_neg!(self, i64x2_neg, as_i64x2, from_i64x2) } #[doc(alias = "i8x16.min_s")] - pub fn i8x16_min_s(self, rhs: Self) -> Self { + pub(crate) fn i8x16_min_s(self, rhs: Self) -> Self { simd_minmax!(self, rhs, i8x16_min, as_i8x16, from_i8x16, <) } #[doc(alias = "i16x8.min_s")] - pub fn i16x8_min_s(self, rhs: Self) -> Self { + pub(crate) fn i16x8_min_s(self, rhs: Self) -> Self { simd_minmax!(self, rhs, i16x8_min, as_i16x8, from_i16x8, <) } #[doc(alias = "i32x4.min_s")] - pub fn i32x4_min_s(self, rhs: Self) -> Self { + pub(crate) fn i32x4_min_s(self, rhs: Self) -> Self { simd_minmax!(self, rhs, i32x4_min, as_i32x4, from_i32x4, <) } #[doc(alias = "i8x16.min_u")] - pub fn i8x16_min_u(self, rhs: Self) -> Self { + pub(crate) fn i8x16_min_u(self, rhs: Self) -> Self { simd_minmax!(self, rhs, u8x16_min, as_u8x16, from_u8x16, <) } #[doc(alias = "i16x8.min_u")] - pub fn i16x8_min_u(self, rhs: Self) -> Self { + pub(crate) fn i16x8_min_u(self, rhs: Self) -> Self { simd_minmax!(self, rhs, u16x8_min, as_u16x8, from_u16x8, <) } #[doc(alias = "i32x4.min_u")] - pub fn i32x4_min_u(self, rhs: Self) -> Self { + pub(crate) fn i32x4_min_u(self, rhs: Self) -> Self { simd_minmax!(self, rhs, u32x4_min, as_u32x4, from_u32x4, <) } #[doc(alias = "i8x16.max_s")] - pub fn i8x16_max_s(self, rhs: Self) -> Self { + pub(crate) fn i8x16_max_s(self, rhs: Self) -> Self { simd_minmax!(self, rhs, i8x16_max, as_i8x16, from_i8x16, >) } #[doc(alias = "i16x8.max_s")] - pub fn i16x8_max_s(self, rhs: Self) -> Self { + pub(crate) fn i16x8_max_s(self, rhs: Self) -> Self { simd_minmax!(self, rhs, i16x8_max, as_i16x8, from_i16x8, >) } #[doc(alias = "i32x4.max_s")] - pub fn i32x4_max_s(self, rhs: Self) -> Self { + pub(crate) fn i32x4_max_s(self, rhs: Self) -> Self { simd_minmax!(self, rhs, i32x4_max, as_i32x4, from_i32x4, >) } #[doc(alias = "i8x16.max_u")] - pub fn i8x16_max_u(self, rhs: Self) -> Self { + pub(crate) fn i8x16_max_u(self, rhs: Self) -> Self { simd_minmax!(self, rhs, u8x16_max, as_u8x16, from_u8x16, >) } #[doc(alias = "i16x8.max_u")] - pub fn i16x8_max_u(self, rhs: Self) -> Self { + pub(crate) fn i16x8_max_u(self, rhs: Self) -> Self { simd_minmax!(self, rhs, u16x8_max, as_u16x8, from_u16x8, >) } #[doc(alias = "i32x4.max_u")] - pub fn i32x4_max_u(self, rhs: Self) -> Self { + pub(crate) fn i32x4_max_u(self, rhs: Self) -> Self { simd_minmax!(self, rhs, u32x4_max, as_u32x4, from_u32x4, >) } #[doc(alias = "f32x4.eq")] - pub fn f32x4_eq(self, rhs: Self) -> Self { + pub(crate) fn f32x4_eq(self, rhs: Self) -> Self { simd_cmp_mask!(generic self, rhs, as_f32x4, from_i32x4, ==) } #[doc(alias = "f64x2.eq")] - pub fn f64x2_eq(self, rhs: Self) -> Self { + pub(crate) fn f64x2_eq(self, rhs: Self) -> Self { simd_cmp_mask!(generic self, rhs, as_f64x2, from_i64x2, ==) } #[doc(alias = "f32x4.ne")] - pub fn f32x4_ne(self, rhs: Self) -> Self { + pub(crate) fn f32x4_ne(self, rhs: Self) -> Self { simd_cmp_mask!(generic self, rhs, as_f32x4, from_i32x4, !=) } #[doc(alias = "f64x2.ne")] - pub fn f64x2_ne(self, rhs: Self) -> Self { + pub(crate) fn f64x2_ne(self, rhs: Self) -> Self { simd_cmp_mask!(generic self, rhs, as_f64x2, from_i64x2, !=) } #[doc(alias = "f32x4.lt")] - pub fn f32x4_lt(self, rhs: Self) -> Self { + pub(crate) fn f32x4_lt(self, rhs: Self) -> Self { simd_cmp_mask!(generic self, rhs, as_f32x4, from_i32x4, <) } #[doc(alias = "f64x2.lt")] - pub fn f64x2_lt(self, rhs: Self) -> Self { + pub(crate) fn f64x2_lt(self, rhs: Self) -> Self { simd_cmp_mask!(generic self, rhs, as_f64x2, from_i64x2, <) } #[doc(alias = "f32x4.gt")] - pub fn f32x4_gt(self, rhs: Self) -> Self { + pub(crate) fn f32x4_gt(self, rhs: Self) -> Self { rhs.f32x4_lt(self) } #[doc(alias = "f64x2.gt")] - pub fn f64x2_gt(self, rhs: Self) -> Self { + pub(crate) fn f64x2_gt(self, rhs: Self) -> Self { rhs.f64x2_lt(self) } #[doc(alias = "f32x4.le")] - pub fn f32x4_le(self, rhs: Self) -> Self { + pub(crate) fn f32x4_le(self, rhs: Self) -> Self { simd_cmp_mask!(generic self, rhs, as_f32x4, from_i32x4, <=) } #[doc(alias = "f64x2.le")] - pub fn f64x2_le(self, rhs: Self) -> Self { + pub(crate) fn f64x2_le(self, rhs: Self) -> Self { simd_cmp_mask!(generic self, rhs, as_f64x2, from_i64x2, <=) } #[doc(alias = "f32x4.ge")] - pub fn f32x4_ge(self, rhs: Self) -> Self { + pub(crate) fn f32x4_ge(self, rhs: Self) -> Self { simd_cmp_mask!(generic self, rhs, as_f32x4, from_i32x4, >=) } #[doc(alias = "f64x2.ge")] - pub fn f64x2_ge(self, rhs: Self) -> Self { + pub(crate) fn f64x2_ge(self, rhs: Self) -> Self { simd_cmp_mask!(generic self, rhs, as_f64x2, from_i64x2, >=) } #[doc(alias = "f32x4.ceil")] - pub fn f32x4_ceil(self) -> Self { + pub(crate) fn f32x4_ceil(self) -> Self { self.map_f32x4(|x| canonicalize_simd_f32_nan(x.ceil())) } #[doc(alias = "f64x2.ceil")] - pub fn f64x2_ceil(self) -> Self { + pub(crate) fn f64x2_ceil(self) -> Self { self.map_f64x2(|x| canonicalize_simd_f64_nan(x.ceil())) } #[doc(alias = "f32x4.floor")] - pub fn f32x4_floor(self) -> Self { + pub(crate) fn f32x4_floor(self) -> Self { self.map_f32x4(|x| canonicalize_simd_f32_nan(x.floor())) } #[doc(alias = "f64x2.floor")] - pub fn f64x2_floor(self) -> Self { + pub(crate) fn f64x2_floor(self) -> Self { self.map_f64x2(|x| canonicalize_simd_f64_nan(x.floor())) } #[doc(alias = "f32x4.trunc")] - pub fn f32x4_trunc(self) -> Self { + pub(crate) fn f32x4_trunc(self) -> Self { self.map_f32x4(|x| canonicalize_simd_f32_nan(x.trunc())) } #[doc(alias = "f64x2.trunc")] - pub fn f64x2_trunc(self) -> Self { + pub(crate) fn f64x2_trunc(self) -> Self { self.map_f64x2(|x| canonicalize_simd_f64_nan(x.trunc())) } #[doc(alias = "f32x4.nearest")] - pub fn f32x4_nearest(self) -> Self { + pub(crate) fn f32x4_nearest(self) -> Self { self.map_f32x4(|x| canonicalize_simd_f32_nan(TinywasmFloatExt::tw_nearest(x))) } #[doc(alias = "f64x2.nearest")] - pub fn f64x2_nearest(self) -> Self { + pub(crate) fn f64x2_nearest(self) -> Self { self.map_f64x2(|x| canonicalize_simd_f64_nan(TinywasmFloatExt::tw_nearest(x))) } #[doc(alias = "f32x4.abs")] - pub fn f32x4_abs(self) -> Self { + pub(crate) fn f32x4_abs(self) -> Self { self.map_f32x4(f32::abs) } #[doc(alias = "f64x2.abs")] - pub fn f64x2_abs(self) -> Self { + pub(crate) fn f64x2_abs(self) -> Self { self.map_f64x2(f64::abs) } #[doc(alias = "f32x4.neg")] - pub fn f32x4_neg(self) -> Self { + pub(crate) fn f32x4_neg(self) -> Self { self.map_f32x4(|x| -x) } #[doc(alias = "f64x2.neg")] - pub fn f64x2_neg(self) -> Self { + pub(crate) fn f64x2_neg(self) -> Self { self.map_f64x2(|x| -x) } #[doc(alias = "f32x4.sqrt")] - pub fn f32x4_sqrt(self) -> Self { + pub(crate) fn f32x4_sqrt(self) -> Self { self.map_f32x4(|x| canonicalize_simd_f32_nan(x.sqrt())) } #[doc(alias = "f64x2.sqrt")] - pub fn f64x2_sqrt(self) -> Self { + pub(crate) fn f64x2_sqrt(self) -> Self { self.map_f64x2(|x| canonicalize_simd_f64_nan(x.sqrt())) } #[doc(alias = "f32x4.add")] - pub fn f32x4_add(self, rhs: Self) -> Self { + pub(crate) fn f32x4_add(self, rhs: Self) -> Self { self.zip_f32x4(rhs, |a, b| canonicalize_simd_f32_nan(a + b)) } #[doc(alias = "f64x2.add")] - pub fn f64x2_add(self, rhs: Self) -> Self { + pub(crate) fn f64x2_add(self, rhs: Self) -> Self { self.zip_f64x2(rhs, |a, b| canonicalize_simd_f64_nan(a + b)) } #[doc(alias = "f32x4.sub")] - pub fn f32x4_sub(self, rhs: Self) -> Self { + pub(crate) fn f32x4_sub(self, rhs: Self) -> Self { self.zip_f32x4(rhs, |a, b| canonicalize_simd_f32_nan(a - b)) } #[doc(alias = "f64x2.sub")] - pub fn f64x2_sub(self, rhs: Self) -> Self { + pub(crate) fn f64x2_sub(self, rhs: Self) -> Self { self.zip_f64x2(rhs, |a, b| canonicalize_simd_f64_nan(a - b)) } #[doc(alias = "f32x4.mul")] - pub fn f32x4_mul(self, rhs: Self) -> Self { + pub(crate) fn f32x4_mul(self, rhs: Self) -> Self { self.zip_f32x4(rhs, |a, b| canonicalize_simd_f32_nan(a * b)) } #[doc(alias = "f64x2.mul")] - pub fn f64x2_mul(self, rhs: Self) -> Self { + pub(crate) fn f64x2_mul(self, rhs: Self) -> Self { self.zip_f64x2(rhs, |a, b| canonicalize_simd_f64_nan(a * b)) } #[doc(alias = "f32x4.div")] - pub fn f32x4_div(self, rhs: Self) -> Self { + pub(crate) fn f32x4_div(self, rhs: Self) -> Self { self.zip_f32x4(rhs, |a, b| canonicalize_simd_f32_nan(a / b)) } #[doc(alias = "f64x2.div")] - pub fn f64x2_div(self, rhs: Self) -> Self { + pub(crate) fn f64x2_div(self, rhs: Self) -> Self { self.zip_f64x2(rhs, |a, b| canonicalize_simd_f64_nan(a / b)) } #[doc(alias = "f32x4.min")] - pub fn f32x4_min(self, rhs: Self) -> Self { + pub(crate) fn f32x4_min(self, rhs: Self) -> Self { self.zip_f32x4(rhs, TinywasmFloatExt::tw_minimum) } #[doc(alias = "f64x2.min")] - pub fn f64x2_min(self, rhs: Self) -> Self { + pub(crate) fn f64x2_min(self, rhs: Self) -> Self { self.zip_f64x2(rhs, TinywasmFloatExt::tw_minimum) } #[doc(alias = "f32x4.max")] - pub fn f32x4_max(self, rhs: Self) -> Self { + pub(crate) fn f32x4_max(self, rhs: Self) -> Self { self.zip_f32x4(rhs, TinywasmFloatExt::tw_maximum) } #[doc(alias = "f64x2.max")] - pub fn f64x2_max(self, rhs: Self) -> Self { + pub(crate) fn f64x2_max(self, rhs: Self) -> Self { self.zip_f64x2(rhs, TinywasmFloatExt::tw_maximum) } #[doc(alias = "f32x4.pmin")] - pub fn f32x4_pmin(self, rhs: Self) -> Self { + pub(crate) fn f32x4_pmin(self, rhs: Self) -> Self { self.zip_f32x4(rhs, |a, b| if b < a { b } else { a }) } #[doc(alias = "f64x2.pmin")] - pub fn f64x2_pmin(self, rhs: Self) -> Self { + pub(crate) fn f64x2_pmin(self, rhs: Self) -> Self { self.zip_f64x2(rhs, |a, b| if b < a { b } else { a }) } #[doc(alias = "f32x4.pmax")] - pub fn f32x4_pmax(self, rhs: Self) -> Self { + pub(crate) fn f32x4_pmax(self, rhs: Self) -> Self { self.zip_f32x4(rhs, |a, b| if b > a { b } else { a }) } #[doc(alias = "f64x2.pmax")] - pub fn f64x2_pmax(self, rhs: Self) -> Self { + pub(crate) fn f64x2_pmax(self, rhs: Self) -> Self { self.zip_f64x2(rhs, |a, b| if b > a { b } else { a }) } #[doc(alias = "f32x4.relaxed_madd")] - pub fn f32x4_relaxed_madd(self, b: Self, c: Self) -> Self { + pub(crate) fn f32x4_relaxed_madd(self, b: Self, c: Self) -> Self { self.zip_f32x4(b, |x, y| canonicalize_simd_f32_nan(x * y)) .zip_f32x4(c, |xy, z| canonicalize_simd_f32_nan(xy + z)) } #[doc(alias = "f32x4.relaxed_nmadd")] - pub fn f32x4_relaxed_nmadd(self, b: Self, c: Self) -> Self { + pub(crate) fn f32x4_relaxed_nmadd(self, b: Self, c: Self) -> Self { self.zip_f32x4(b, |x, y| canonicalize_simd_f32_nan(-(x * y))) .zip_f32x4(c, |neg_xy, z| canonicalize_simd_f32_nan(neg_xy + z)) } #[doc(alias = "f64x2.relaxed_madd")] - pub fn f64x2_relaxed_madd(self, b: Self, c: Self) -> Self { + pub(crate) fn f64x2_relaxed_madd(self, b: Self, c: Self) -> Self { self.zip_f64x2(b, |x, y| canonicalize_simd_f64_nan(x * y)) .zip_f64x2(c, |xy, z| canonicalize_simd_f64_nan(xy + z)) } #[doc(alias = "f64x2.relaxed_nmadd")] - pub fn f64x2_relaxed_nmadd(self, b: Self, c: Self) -> Self { + pub(crate) fn f64x2_relaxed_nmadd(self, b: Self, c: Self) -> Self { self.zip_f64x2(b, |x, y| canonicalize_simd_f64_nan(-(x * y))) .zip_f64x2(c, |neg_xy, z| canonicalize_simd_f64_nan(neg_xy + z)) } #[doc(alias = "f32x4.relaxed_min")] - pub fn f32x4_relaxed_min(self, rhs: Self) -> Self { + pub(crate) fn f32x4_relaxed_min(self, rhs: Self) -> Self { self.f32x4_min(rhs) } #[doc(alias = "f64x2.relaxed_min")] - pub fn f64x2_relaxed_min(self, rhs: Self) -> Self { + pub(crate) fn f64x2_relaxed_min(self, rhs: Self) -> Self { self.f64x2_min(rhs) } #[doc(alias = "f32x4.relaxed_max")] - pub fn f32x4_relaxed_max(self, rhs: Self) -> Self { + pub(crate) fn f32x4_relaxed_max(self, rhs: Self) -> Self { self.f32x4_max(rhs) } #[doc(alias = "f64x2.relaxed_max")] - pub fn f64x2_relaxed_max(self, rhs: Self) -> Self { + pub(crate) fn f64x2_relaxed_max(self, rhs: Self) -> Self { self.f64x2_max(rhs) } #[doc(alias = "i32x4.relaxed_trunc_f32x4_s")] - pub fn i32x4_relaxed_trunc_f32x4_s(self) -> Self { + pub(crate) fn i32x4_relaxed_trunc_f32x4_s(self) -> Self { self.i32x4_trunc_sat_f32x4_s() } #[doc(alias = "i32x4.relaxed_trunc_f32x4_u")] - pub fn i32x4_relaxed_trunc_f32x4_u(self) -> Self { + pub(crate) fn i32x4_relaxed_trunc_f32x4_u(self) -> Self { self.i32x4_trunc_sat_f32x4_u() } #[doc(alias = "i32x4.relaxed_trunc_f64x2_s_zero")] - pub fn i32x4_relaxed_trunc_f64x2_s_zero(self) -> Self { + pub(crate) fn i32x4_relaxed_trunc_f64x2_s_zero(self) -> Self { self.i32x4_trunc_sat_f64x2_s_zero() } #[doc(alias = "i32x4.relaxed_trunc_f64x2_u_zero")] - pub fn i32x4_relaxed_trunc_f64x2_u_zero(self) -> Self { + pub(crate) fn i32x4_relaxed_trunc_f64x2_u_zero(self) -> Self { self.i32x4_trunc_sat_f64x2_u_zero() } #[doc(alias = "i32x4.trunc_sat_f32x4_s")] - pub fn i32x4_trunc_sat_f32x4_s(self) -> Self { + pub(crate) fn i32x4_trunc_sat_f32x4_s(self) -> Self { Self::from_i32x4(self.as_f32x4().map(trunc_sat_f32_to_i32)) } #[doc(alias = "i32x4.trunc_sat_f32x4_u")] - pub fn i32x4_trunc_sat_f32x4_u(self) -> Self { + pub(crate) fn i32x4_trunc_sat_f32x4_u(self) -> Self { Self::from_u32x4(self.as_f32x4().map(trunc_sat_f32_to_u32)) } #[doc(alias = "i32x4.trunc_sat_f64x2_s_zero")] - pub fn i32x4_trunc_sat_f64x2_s_zero(self) -> Self { + pub(crate) fn i32x4_trunc_sat_f64x2_s_zero(self) -> Self { let v = self.as_f64x2(); Self::from_i32x4([trunc_sat_f64_to_i32(v[0]), trunc_sat_f64_to_i32(v[1]), 0, 0]) } #[doc(alias = "i32x4.trunc_sat_f64x2_u_zero")] - pub fn i32x4_trunc_sat_f64x2_u_zero(self) -> Self { + pub(crate) fn i32x4_trunc_sat_f64x2_u_zero(self) -> Self { let v = self.as_f64x2(); Self::from_u32x4([trunc_sat_f64_to_u32(v[0]), trunc_sat_f64_to_u32(v[1]), 0, 0]) } #[doc(alias = "f32x4.convert_i32x4_s")] - pub fn f32x4_convert_i32x4_s(self) -> Self { + pub(crate) fn f32x4_convert_i32x4_s(self) -> Self { Self::from_f32x4(self.as_i32x4().map(|x| x as f32)) } #[doc(alias = "f32x4.convert_i32x4_u")] - pub fn f32x4_convert_i32x4_u(self) -> Self { + pub(crate) fn f32x4_convert_i32x4_u(self) -> Self { Self::from_f32x4(self.as_u32x4().map(|x| x as f32)) } #[doc(alias = "f64x2.convert_low_i32x4_s")] - pub fn f64x2_convert_low_i32x4_s(self) -> Self { + pub(crate) fn f64x2_convert_low_i32x4_s(self) -> Self { let [a, b, ..] = self.as_i32x4(); Self::from_f64x2([a as f64, b as f64]) } #[doc(alias = "f64x2.convert_low_i32x4_u")] - pub fn f64x2_convert_low_i32x4_u(self) -> Self { + pub(crate) fn f64x2_convert_low_i32x4_u(self) -> Self { let [a, b, ..] = self.as_u32x4(); Self::from_f64x2([a as f64, b as f64]) } #[doc(alias = "f32x4.demote_f64x2_zero")] - pub fn f32x4_demote_f64x2_zero(self) -> Self { + pub(crate) fn f32x4_demote_f64x2_zero(self) -> Self { let [a, b] = self.as_f64x2(); Self::from_f32x4([a as f32, b as f32, 0.0, 0.0]) } #[doc(alias = "f64x2.promote_low_f32x4")] - pub fn f64x2_promote_low_f32x4(self) -> Self { + pub(crate) fn f64x2_promote_low_f32x4(self) -> Self { let [a, b, ..] = self.as_f32x4(); Self::from_f64x2([a as f64, b as f64]) } #[doc(alias = "i16x8.splat")] - pub fn splat_i16(src: i16) -> Self { + pub(crate) fn splat_i16(src: i16) -> Self { Self::from_i16x8([src; 8]) } #[doc(alias = "i32x4.splat")] - pub fn splat_i32(src: i32) -> Self { + pub(crate) fn splat_i32(src: i32) -> Self { Self::from_i32x4([src; 4]) } #[doc(alias = "i64x2.splat")] - pub fn splat_i64(src: i64) -> Self { + pub(crate) fn splat_i64(src: i64) -> Self { Self::from_i64x2([src; 2]) } #[doc(alias = "f32x4.splat")] - pub fn splat_f32(src: f32) -> Self { + pub(crate) fn splat_f32(src: f32) -> Self { Self::splat_i32(src.to_bits() as i32) } #[doc(alias = "f64x2.splat")] - pub fn splat_f64(src: f64) -> Self { + pub(crate) fn splat_f64(src: f64) -> Self { Self::splat_i64(src.to_bits() as i64) } #[doc(alias = "i8x16.extract_lane_s")] - pub fn extract_lane_i8(self, lane: u8) -> i8 { + pub(crate) fn extract_lane_i8(self, lane: u8) -> i8 { debug_assert!(lane < 16); self.0[lane as usize] as i8 } #[doc(alias = "i8x16.extract_lane_u")] - pub fn extract_lane_u8(self, lane: u8) -> u8 { + pub(crate) fn extract_lane_u8(self, lane: u8) -> u8 { debug_assert!(lane < 16); self.0[lane as usize] } #[doc(alias = "i16x8.extract_lane_s")] - pub fn extract_lane_i16(self, lane: u8) -> i16 { + pub(crate) fn extract_lane_i16(self, lane: u8) -> i16 { i16::from_le_bytes(self.extract_lane_bytes::<2, 8>(lane)) } #[doc(alias = "i16x8.extract_lane_u")] - pub fn extract_lane_u16(self, lane: u8) -> u16 { + pub(crate) fn extract_lane_u16(self, lane: u8) -> u16 { u16::from_le_bytes(self.extract_lane_bytes::<2, 8>(lane)) } #[doc(alias = "i32x4.extract_lane")] - pub fn extract_lane_i32(self, lane: u8) -> i32 { + pub(crate) fn extract_lane_i32(self, lane: u8) -> i32 { i32::from_le_bytes(self.extract_lane_bytes::<4, 4>(lane)) } #[doc(alias = "i64x2.extract_lane")] - pub fn extract_lane_i64(self, lane: u8) -> i64 { + pub(crate) fn extract_lane_i64(self, lane: u8) -> i64 { i64::from_le_bytes(self.extract_lane_bytes::<8, 2>(lane)) } #[doc(alias = "f32x4.extract_lane")] - pub fn extract_lane_f32(self, lane: u8) -> f32 { + pub(crate) fn extract_lane_f32(self, lane: u8) -> f32 { f32::from_bits(self.extract_lane_i32(lane) as u32) } #[doc(alias = "f64x2.extract_lane")] - pub fn extract_lane_f64(self, lane: u8) -> f64 { + pub(crate) fn extract_lane_f64(self, lane: u8) -> f64 { f64::from_bits(self.extract_lane_i64(lane) as u64) } } diff --git a/crates/tinywasm/src/interpreter/simd/macros.rs b/crates/tinywasm/src/interpreter/simd/macros.rs index 9306d8f..e79ed77 100644 --- a/crates/tinywasm/src/interpreter/simd/macros.rs +++ b/crates/tinywasm/src/interpreter/simd/macros.rs @@ -118,7 +118,7 @@ macro_rules! impl_simd_shifts { ($($alias:literal => $name:ident($as_lanes:ident, $from_lanes:ident, $mask:expr, $op:ident);)*) => { $( #[doc(alias = $alias)] - pub fn $name(self, shift: u32) -> Self { + pub(crate) fn $name(self, shift: u32) -> Self { simd_shift!(self, shift, $as_lanes, $from_lanes, $mask, $op) } )* @@ -129,7 +129,7 @@ macro_rules! impl_simd_binary_methods { ($helper:ident; $($alias:literal => $name:ident($($args:tt)*);)*) => { $( #[doc(alias = $alias)] - pub fn $name(self, rhs: Self) -> Self { + pub(crate) fn $name(self, rhs: Self) -> Self { $helper!(self, rhs, $($args)*) } )* @@ -140,7 +140,7 @@ macro_rules! impl_simd_extend { ($($alias:literal => $name:ident($src_as:ident, $dst_from:ident, $dst_ty:ty, $offset:expr);)*) => { $( #[doc(alias = $alias)] - pub fn $name(self) -> Self { + pub(crate) fn $name(self) -> Self { simd_extend_cast!(self, $src_as, $dst_from, $dst_ty, $offset) } )* @@ -151,7 +151,7 @@ macro_rules! impl_simd_relaxed_laneselect { ($($alias:literal => $name:ident;)*) => { $( #[doc(alias = $alias)] - pub fn $name(v1: Self, v2: Self, c: Self) -> Self { + pub(crate) fn $name(v1: Self, v2: Self, c: Self) -> Self { Self::v128_bitselect(v1, v2, c) } )* @@ -162,7 +162,7 @@ macro_rules! impl_simd_reverse_comparisons { ($($alias:literal => $name:ident($reverse:ident);)*) => { $( #[doc(alias = $alias)] - pub fn $name(self, rhs: Self) -> Self { + pub(crate) fn $name(self, rhs: Self) -> Self { rhs.$reverse(self) } )* @@ -197,10 +197,10 @@ macro_rules! lane_write { } macro_rules! impl_lane_accessors { - ($($as_vis:vis $as_name:ident => $from_vis:vis $from_name:ident: $lane_ty:tt, $lane_count:expr, $lane_bytes:expr;)*) => { + ($($as_name:ident => $from_name:ident: $lane_ty:tt, $lane_count:expr, $lane_bytes:expr;)*) => { $( #[inline] - $as_vis const fn $as_name(self) -> [$lane_ty; $lane_count] { + pub(crate) const fn $as_name(self) -> [$lane_ty; $lane_count] { const { assert!($lane_count * $lane_bytes == 16); }; let bytes = self.0; let mut out = [0 as $lane_ty; $lane_count]; @@ -213,7 +213,7 @@ macro_rules! impl_lane_accessors { } #[inline] - $from_vis const fn $from_name(lanes: [$lane_ty; $lane_count]) -> Self { + pub(crate) const fn $from_name(lanes: [$lane_ty; $lane_count]) -> Self { const { assert!($lane_count * $lane_bytes == 16); }; let mut bytes = [0u8; 16]; diff --git a/crates/tinywasm/src/interpreter/simd/mod.rs b/crates/tinywasm/src/interpreter/simd/mod.rs index 8a3ca84..62ea4ab 100644 --- a/crates/tinywasm/src/interpreter/simd/mod.rs +++ b/crates/tinywasm/src/interpreter/simd/mod.rs @@ -34,10 +34,10 @@ impl Value128 { as_u8x16 => from_u8x16: u8, 16, 1; as_i16x8 => from_i16x8: i16, 8, 2; as_u16x8 => from_u16x8: u16, 8, 2; - as_i32x4 => pub from_i32x4: i32, 4, 4; + as_i32x4 => from_i32x4: i32, 4, 4; as_u32x4 => from_u32x4: u32, 4, 4; as_f32x4 => from_f32x4: f32, 4, 4; - as_i64x2 => pub from_i64x2: i64, 2, 8; + as_i64x2 => from_i64x2: i64, 2, 8; as_u64x2 => from_u64x2: u64, 2, 8; as_f64x2 => from_f64x2: f64, 2, 8; } diff --git a/crates/tinywasm/src/interpreter/simd/utils.rs b/crates/tinywasm/src/interpreter/simd/utils.rs index ebba815..3d90744 100644 --- a/crates/tinywasm/src/interpreter/simd/utils.rs +++ b/crates/tinywasm/src/interpreter/simd/utils.rs @@ -9,7 +9,6 @@ impl Value128 { lane: u8, ) -> [u8; LANE_BYTES] { const { assert!(LANE_BYTES * LANE_COUNT == 16) }; - assert!((lane as usize) < LANE_COUNT); let start = lane as usize * LANE_BYTES; core::array::from_fn(|i| self.0[start + i]) } @@ -20,7 +19,6 @@ impl Value128 { value: [u8; LANE_BYTES], ) -> Self { const { assert!(LANE_BYTES * LANE_COUNT == 16) }; - assert!((lane as usize) < LANE_COUNT); let mut bytes = self.0; let start = lane as usize * LANE_BYTES; bytes[start..start + LANE_BYTES].copy_from_slice(&value); diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 3748ef9..92b4d93 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -222,16 +222,11 @@ impl ValueStack { } #[inline(always)] - pub(crate) fn push<T: InternalValue>(&mut self, value: T) -> Result<(), Trap> { - T::stack_push(self, value) - } - - #[inline(always)] pub(crate) fn pop_memory_operand(&mut self, arch: MemoryArch) -> Result<usize, Trap> { match arch { - MemoryArch::I32 => Ok(self.stack_32.pop() as usize), + MemoryArch::I32 => Ok(u32::stack_pop(self) as usize), MemoryArch::I64 => { - let value = self.stack_64.pop(); + let value = u64::stack_pop(self); #[cfg(target_pointer_width = "64")] return Ok(value as usize); #[cfg(not(target_pointer_width = "64"))] @@ -276,10 +271,10 @@ impl ValueStack { pub(crate) fn push_dyn(&mut self, value: RuntimeValue) -> Result<(), Trap> { match value { - RuntimeValue::Value32(v) => self.stack_32.push(v), - RuntimeValue::Value64(v) => self.stack_64.push(v), - RuntimeValue::Value128(v) => self.stack_128.push(v), - RuntimeValue::ValueRef(v) => self.stack_32.push(v.raw()), + RuntimeValue::Value32(value) => Value32::stack_push(self, value), + RuntimeValue::Value64(value) => Value64::stack_push(self, value), + RuntimeValue::Value128(value) => Value128::stack_push(self, value), + RuntimeValue::ValueRef(value) => ValueRef::stack_push(self, value), } } } diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index 83b520b..38b7a04 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -105,21 +105,12 @@ impl RuntimeValue { } } -mod sealed { - #[expect(unreachable_pub)] - pub trait Sealed {} -} - /// Typed access to values in their physical [`ValueStack`] and [`Globals`] lanes. -pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { +pub(crate) trait InternalValue: Copy + Default { fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap>; fn stack_pop(stack: &mut ValueStack) -> Self; fn stack_peek(stack: &ValueStack) -> Self; - fn stack_update(stack: &mut ValueStack, f: impl FnOnce(Self) -> Self) -> Result<Self, crate::Trap> { - let value = f(Self::stack_pop(stack)); - Self::stack_push(stack, value)?; - Ok(value) - } + fn stack_update(stack: &mut ValueStack, f: impl FnOnce(Self) -> Self) -> 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>; @@ -128,11 +119,7 @@ pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr); fn global_get(globals: &Globals, addr: GlobalAddr) -> Self; fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self); - fn global_update(globals: &mut Globals, addr: GlobalAddr, f: impl FnOnce(Self) -> Self) -> Self { - let value = f(Self::global_get(globals, addr)); - Self::global_set(globals, addr, value); - value - } + fn global_update(globals: &mut Globals, addr: GlobalAddr, f: impl FnOnce(Self) -> Self) -> Self; } macro_rules! impl_internalvalue { @@ -144,8 +131,6 @@ macro_rules! impl_internalvalue { )* ) => { $( - impl sealed::Sealed for $outer {} - impl InternalValue for $outer { #[inline(always)] fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self { @@ -201,6 +186,15 @@ macro_rules! impl_internalvalue { } #[inline(always)] + fn global_update(globals: &mut Globals, addr: GlobalAddr, f: impl FnOnce(Self) -> Self) -> Self { + let $from_stack_v = globals.$global_get(addr); + let value = f($from_stack); + let $to_stack_v = value; + globals.$global_set(addr, $to_stack); + value + } + + #[inline(always)] fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap> { let $to_stack_v = value; cold_err!(stack.$stack.push($to_stack))?; @@ -220,6 +214,16 @@ macro_rules! impl_internalvalue { } #[inline(always)] + fn stack_update(stack: &mut ValueStack, f: impl FnOnce(Self) -> Self) -> Self { + let index = stack.$stack.len() - 1; + let $from_stack_v = *stack.$stack.get(index); + let value = f($from_stack); + let $to_stack_v = value; + stack.$stack.set(index, $to_stack); + value + } + + #[inline(always)] fn stack_select(stack: &mut ValueStack) { let cond = stack.stack_32.pop() as i32; let val2 = stack.$stack.pop(); @@ -249,81 +253,41 @@ pub(crate) trait BinOpExt<T>: Copy { fn exec(self, lhs: T, rhs: T) -> T; } -impl BinOpExt<Value32> for BinOp { - #[inline(always)] - fn exec(self, lhs: Value32, rhs: Value32) -> Value32 { - match self { - BinOp::IAdd => lhs.wrapping_add(rhs), - BinOp::ISub => lhs.wrapping_sub(rhs), - BinOp::IMul => lhs.wrapping_mul(rhs), - BinOp::IAnd => lhs & rhs, - BinOp::IOr => lhs | rhs, - BinOp::IXor => lhs ^ rhs, - BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32, - BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32, - BinOp::IShrU => lhs.wrapping_shr(rhs), - BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32, - BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32, - BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(), - BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(), - BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(), - BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(), - BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(), - BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(), - BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(), - } - } -} - -impl BinOpExt<Value64> for BinOp { - #[inline(always)] - fn exec(self, lhs: Value64, rhs: Value64) -> Value64 { - match self { - BinOp::IAdd => lhs.wrapping_add(rhs), - BinOp::ISub => lhs.wrapping_sub(rhs), - BinOp::IMul => lhs.wrapping_mul(rhs), - BinOp::IAnd => lhs & rhs, - BinOp::IOr => lhs | rhs, - BinOp::IXor => lhs ^ rhs, - BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64, - BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64, - BinOp::IShrU => lhs.wrapping_shr(rhs as u32), - BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64, - BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64, - BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(), - BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(), - BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(), - BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(), - BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(), - BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(), - BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(), - } - } -} - -impl BinOpExt<Value128> for BinOp128 { - #[inline(always)] - fn exec(self, lhs: Value128, rhs: Value128) -> Value128 { - match self { - BinOp128::And => lhs.v128_and(rhs), - BinOp128::AndNot => lhs.v128_andnot(rhs), - BinOp128::Or => lhs.v128_or(rhs), - BinOp128::Xor => lhs.v128_xor(rhs), - BinOp128::I64x2Add => lhs.i64x2_add(rhs), - BinOp128::I64x2Mul => lhs.i64x2_mul(rhs), - } - } -} - pub(crate) trait CmpOpExt<T>: Copy { fn cmp(self, lhs: T, rhs: T) -> bool; } -macro_rules! impl_cmp_value { - ($ty:ty, $unsigned:ty) => { - impl CmpOpExt<$ty> for CmpOp { +macro_rules! impl_value_ops { + ($unsigned:ty, $signed:ty, $float:ty) => { + impl BinOpExt<$unsigned> for BinOp { + #[inline(always)] + fn exec(self, lhs: $unsigned, rhs: $unsigned) -> $unsigned { + match self { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as $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(), + } + } + } + + impl CmpOpExt<$signed> for CmpOp { #[inline(always)] - fn cmp(self, lhs: $ty, rhs: $ty) -> bool { + fn cmp(self, lhs: $signed, rhs: $signed) -> bool { match self { CmpOp::Eq => lhs == rhs, CmpOp::Ne => lhs != rhs, @@ -341,8 +305,22 @@ macro_rules! impl_cmp_value { }; } -impl_cmp_value!(i32, u32); -impl_cmp_value!(i64, u64); +impl_value_ops!(Value32, i32, f32); +impl_value_ops!(Value64, i64, f64); + +impl BinOpExt<Value128> for BinOp128 { + #[inline(always)] + fn exec(self, lhs: Value128, rhs: Value128) -> Value128 { + match self { + BinOp128::And => lhs.v128_and(rhs), + BinOp128::AndNot => lhs.v128_andnot(rhs), + BinOp128::Or => lhs.v128_or(rhs), + BinOp128::Xor => lhs.v128_xor(rhs), + BinOp128::I64x2Add => lhs.i64x2_add(rhs), + BinOp128::I64x2Mul => lhs.i64x2_mul(rhs), + } + } +} #[cfg(test)] mod tests { diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index d89bfa1..e2ee684 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -114,7 +114,7 @@ mod error; pub use error::*; pub use func::{ ExecProgress, FromWasmValues, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped, - HostFunction, HostFunctionCallback, IntoWasmValues, ToWasmType, ToWasmTypes, + HostFunction, HostFunctionCallback, IntoWasmValues, WasmTypes, WasmValueType, }; pub use imports::*; pub use instance::{ExternItem, ModuleInstance}; diff --git a/crates/tinywasm/src/reference/managed.rs b/crates/tinywasm/src/reference/managed.rs index 79bd0b9..05edf04 100644 --- a/crates/tinywasm/src/reference/managed.rs +++ b/crates/tinywasm/src/reference/managed.rs @@ -14,10 +14,6 @@ impl StoreId { assert_ne!(id, u32::MAX, "Store identity space exhausted"); StoreId(id) } - - pub(crate) const fn get(self) -> u32 { - self.0 - } } #[cfg(feature = "debug")] diff --git a/crates/tinywasm/src/reference/store.rs b/crates/tinywasm/src/reference/store.rs index d0eba6b..07d8eb2 100644 --- a/crates/tinywasm/src/reference/store.rs +++ b/crates/tinywasm/src/reference/store.rs @@ -30,7 +30,7 @@ impl StoreItem { #[inline] pub(crate) fn validate_store(&self, store: &Store) -> Result<(), Trap> { - if self.store_id != store.store_id() { + if self.store_id != store.id() { return Err(Trap::InvalidStore); } Ok(()) @@ -243,7 +243,7 @@ fn gc_field_type(store: &Store, field: FieldType) -> GcFieldType { WasmType::Ref(ty) => GcValueType::Ref(GcRefType { nullable: ty.is_nullable(), heap_type: match ty.type_index() { - Some(addr) => GcHeapType::Concrete(GcType(StoreItem::new(store.store_id(), addr))), + Some(addr) => GcHeapType::Concrete(GcType(StoreItem::new(store.id(), addr))), None => GcHeapType::Abstract(ty.abstract_heap_type().expect("abstract reference type")), }, }), @@ -356,7 +356,7 @@ impl Memory { let addr = store.state.memories.len() as MemAddr; let limiter = store.engine.config().resource_limiter.clone(); store.state.memories.push(MemoryInstance::new(ty, limiter.as_deref())?); - Ok(Self(StoreItem::new(store.store_id(), addr))) + Ok(Self(StoreItem::new(store.id(), addr))) } /// Creates a cursor positioned at the start of this memory. @@ -574,7 +574,7 @@ impl StructRef { /// Returns this struct's canonical type. pub fn ty(&self, store: &Store) -> Result<GcType> { let (_, type_addr) = rooted_object(store, self, ReferentKind::Struct)?; - Ok(GcType(StoreItem::new(store.store_id(), type_addr))) + Ok(GcType(StoreItem::new(store.id(), type_addr))) } /// Reads one field. @@ -633,7 +633,7 @@ impl ArrayRef { /// Returns this array's canonical type. pub fn ty(&self, store: &Store) -> Result<GcType> { let (_, type_addr) = rooted_object(store, self, ReferentKind::Array)?; - Ok(GcType(StoreItem::new(store.store_id(), type_addr))) + Ok(GcType(StoreItem::new(store.id(), type_addr))) } /// Returns the number of array elements. @@ -703,7 +703,7 @@ impl ExnRef { /// Returns the exception's tag. pub fn tag(&self, store: &Store) -> Result<Tag> { let (_, tag_addr) = exception_object(store, self)?; - Ok(Tag(StoreItem::new(store.store_id(), tag_addr))) + Ok(Tag(StoreItem::new(store.id(), tag_addr))) } /// Reads one exception payload field. @@ -769,7 +769,7 @@ impl Table { let limiter = store.engine.config().resource_limiter.clone(); let addr = store.state.tables.len() as TableAddr; store.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); - Ok(Self(StoreItem::new(store.store_id(), addr))) + Ok(Self(StoreItem::new(store.id(), addr))) } #[inline] @@ -861,7 +861,7 @@ impl Global { } let value = value.to_runtime(store)?; let addr = store.state.globals.push(ty, value); - Ok(Self(StoreItem::new(store.store_id(), addr))) + Ok(Self(StoreItem::new(store.id(), addr))) } /// Get the type of the global. @@ -904,7 +904,7 @@ impl Tag { 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.store_id(), addr))) + Ok(Self(StoreItem::new(store.id(), addr))) } /// Get the payload type of the tag. diff --git a/crates/tinywasm/src/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs index cd01648..d896457 100644 --- a/crates/tinywasm/src/store/const_expr.rs +++ b/crates/tinywasm/src/store/const_expr.rs @@ -2,7 +2,7 @@ use alloc::{format, vec::Vec}; use tinywasm_types::*; use super::{State, default_value}; -use crate::interpreter::{RuntimeValue, Value128, ValueRef}; +use crate::interpreter::{InternalValue, RuntimeValue, Value32, Value64, Value128, ValueRef}; use crate::{Error, Result, Trap}; fn resolve<T: Copy>(items: &[T], index: u32, kind: &str) -> Result<T> { @@ -59,17 +59,20 @@ pub(super) fn eval_const( F64Const(value) => return Ok(RuntimeValue::Value64(value.to_bits())), V128Const(value) => return Ok(RuntimeValue::Value128(Value128(*value))), GlobalGet32(index) => { - return Ok(RuntimeValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + return Ok(RuntimeValue::Value32(Value32::global_get(&state.globals, addr))); } GlobalGet64(index) => { - return Ok(RuntimeValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + return Ok(RuntimeValue::Value64(Value64::global_get(&state.globals, addr))); } GlobalGet128(index) => { - return Ok(RuntimeValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + return Ok(RuntimeValue::Value128(Value128::global_get(&state.globals, addr))); } GlobalGetRef(index) => { - let value = state.globals.get_32(resolve(global_addrs, *index, "global")?); - return Ok(RuntimeValue::ValueRef(ValueRef::from_raw(value))); + let addr = resolve(global_addrs, *index, "global")?; + return Ok(RuntimeValue::ValueRef(ValueRef::global_get(&state.globals, addr))); } RefNull(_) => return Ok(RuntimeValue::ValueRef(ValueRef::NULL)), RefFunc(func) => { @@ -89,17 +92,20 @@ pub(super) fn eval_const( F64Const(value) => stack.push(RuntimeValue::Value64(value.to_bits())), V128Const(value) => stack.push(RuntimeValue::Value128(Value128(*value))), GlobalGet32(index) => { - stack.push(RuntimeValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + stack.push(RuntimeValue::Value32(Value32::global_get(&state.globals, addr))); } GlobalGet64(index) => { - stack.push(RuntimeValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + stack.push(RuntimeValue::Value64(Value64::global_get(&state.globals, addr))); } GlobalGet128(index) => { - stack.push(RuntimeValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + stack.push(RuntimeValue::Value128(Value128::global_get(&state.globals, addr))); } GlobalGetRef(index) => { - let value = state.globals.get_32(resolve(global_addrs, *index, "global")?); - stack.push(RuntimeValue::ValueRef(ValueRef::from_raw(value))); + let addr = resolve(global_addrs, *index, "global")?; + stack.push(RuntimeValue::ValueRef(ValueRef::global_get(&state.globals, addr))); } RefNull(_) => stack.push(RuntimeValue::ValueRef(ValueRef::NULL)), RefFunc(func) => { diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs index d7edd15..3a478fb 100644 --- a/crates/tinywasm/src/store/memory/instance.rs +++ b/crates/tinywasm/src/store/memory/instance.rs @@ -31,26 +31,21 @@ impl MemoryInstance { kind.page_count_max_declared().map(|pages| Self::host_size(kind, pages).unwrap_or(usize::MAX)) } + #[cfg(target_pointer_width = "64")] #[inline(always)] pub(crate) fn effective_addr<const N: usize>(&self, base: usize, offset: u64) -> Result<usize, Trap> { - #[cfg(target_pointer_width = "64")] - { - if !self.is_64bit() { - debug_assert!(u32::try_from(offset).is_ok(), "validated memory32 offsets fit in u32"); - return Ok(base + offset as usize); - } - match base.checked_add(offset as usize) { - Some(addr) => Ok(addr), - None => cold!(Err(memory_oob(base, N, self.inner.len()))), - } + match base.checked_add(offset as usize) { + Some(addr) => Ok(addr), + None => cold!(Err(memory_oob(base, N, self.inner.len()))), } + } - #[cfg(not(target_pointer_width = "64"))] - { - match usize::try_from(offset).ok().and_then(|offset| base.checked_add(offset)) { - Some(addr) => Ok(addr), - None => cold!(Err(memory_oob(base, N, self.inner.len()))), - } + #[cfg(not(target_pointer_width = "64"))] + #[inline(always)] + pub(crate) fn effective_addr<const N: usize>(&self, base: usize, offset: u64) -> Result<usize, Trap> { + match usize::try_from(offset).ok().and_then(|offset| base.checked_add(offset)) { + Some(addr) => Ok(addr), + None => cold!(Err(memory_oob(base, N, self.inner.len()))), } } @@ -84,18 +79,18 @@ impl MemoryInstance { pub(crate) fn copy_from_memory( &mut self, dst: usize, - src_memory: &MemoryInstance, + src_mem: &MemoryInstance, src: usize, len: usize, ) -> Result<(), Trap> { - src_memory.inner.checked_range(src, len).ok_or_else(|| cold!(memory_oob(src, len, src_memory.inner.len())))?; - self.inner.checked_range(dst, len).ok_or_else(|| cold!(memory_oob(dst, len, self.inner.len())))?; - self.inner.copy_from(dst, &src_memory.inner, src, len); + cold_err!(src_mem.inner.checked_range(src, len).ok_or_else(|| memory_oob(src, len, src_mem.inner.len())))?; + cold_err!(self.inner.checked_range(dst, len).ok_or_else(|| memory_oob(dst, len, self.inner.len())))?; + self.inner.copy_from(dst, &src_mem.inner, src, len); Ok(()) } pub(crate) fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result<(), Trap> { - self.inner.copy_within(dst, src, len).ok_or_else(|| cold!(memory_oob(dst, len, self.inner.len()))) + cold_err!(self.inner.copy_within(dst, src, len).ok_or_else(|| memory_oob(dst, len, self.inner.len()))) } pub(crate) fn grow( diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs index 89bce83..ef2d4df 100644 --- a/crates/tinywasm/src/store/memory/vec.rs +++ b/crates/tinywasm/src/store/memory/vec.rs @@ -16,7 +16,7 @@ impl VecMemory { /// Tries to create a new memory with `len` zero-initialized bytes. pub(crate) fn try_new(len: usize) -> Result<Self, crate::Trap> { let mut data = Vec::new(); - cold_err!(data.try_reserve_exact(len)).map_err(|_| crate::Trap::OutOfMemory)?; + cold_err!(data.try_reserve(len)).map_err(|_| crate::Trap::OutOfMemory)?; data.resize(len, 0); Ok(Self { data }) } @@ -37,7 +37,7 @@ impl VecMemory { #[inline(always)] pub(crate) fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> { debug_assert!(new_len >= self.data.len(), "memory only grows"); - cold_err!(self.data.try_reserve_exact(new_len - self.data.len())).map_err(|_| crate::Trap::OutOfMemory)?; + cold_err!(self.data.try_reserve(new_len - 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 d4c8b15..862cb4f 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -126,7 +126,6 @@ pub trait ResourceLimiter: Send + Sync { pub struct Store { id: StoreId, pub(crate) module_instances: Vec<ModuleInstance>, - pub(crate) engine: Engine, pub(crate) execution_fuel: u32, pub(crate) execution_active: bool, @@ -242,12 +241,7 @@ impl Store { } } - /// Get the store's ID (unique per process) - pub fn id(&self) -> u32 { - self.id.get() - } - - pub(crate) const fn store_id(&self) -> StoreId { + pub(crate) const fn id(&self) -> StoreId { self.id } @@ -496,7 +490,7 @@ impl Store { stack_base: StackBase, ) -> Result<R> { let mut values = cold_err!(self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base))?; - let result = cold_err!(R::from_wasm_values_exact(&mut values)); + let result = cold_err!(R::from_wasm_values(&mut values)); self.value_stack.truncate_to_base(stack_base); result } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 49efcdc..cad0208 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -2,6 +2,7 @@ use alloc::vec::Vec; use super::*; use crate::engine::Config; +use crate::interpreter::{InternalValue, Value32, Value64, Value128}; /// Global state that can be manipulated by WebAssembly programs /// @@ -363,10 +364,10 @@ impl State { pub(crate) fn global_value(&self, addr: GlobalAddr) -> RuntimeValue { let ty = self.globals.ty(addr).ty; match ty { - WasmType::I32 | WasmType::F32 => RuntimeValue::Value32(self.globals.get_32(addr)), - WasmType::I64 | WasmType::F64 => RuntimeValue::Value64(self.globals.get_64(addr)), - WasmType::Ref(_) => RuntimeValue::ValueRef(ValueRef::from_raw(self.globals.get_32(addr))), - WasmType::V128 => RuntimeValue::Value128(self.globals.get_128(addr)), + WasmType::I32 | WasmType::F32 => RuntimeValue::Value32(Value32::global_get(&self.globals, addr)), + WasmType::I64 | WasmType::F64 => RuntimeValue::Value64(Value64::global_get(&self.globals, addr)), + WasmType::Ref(_) => RuntimeValue::ValueRef(ValueRef::global_get(&self.globals, addr)), + WasmType::V128 => RuntimeValue::Value128(Value128::global_get(&self.globals, addr)), } } @@ -378,10 +379,10 @@ impl State { return Err(Error::other("global is immutable")); } match value { - RuntimeValue::Value32(value) => self.globals.set_32(addr, value), - RuntimeValue::Value64(value) => self.globals.set_64(addr, value), - RuntimeValue::ValueRef(value) => self.globals.set_32(addr, value.raw()), - RuntimeValue::Value128(value) => self.globals.set_128(addr, value), + RuntimeValue::Value32(value) => Value32::global_set(&mut self.globals, addr, value), + RuntimeValue::Value64(value) => Value64::global_set(&mut self.globals, addr, value), + RuntimeValue::ValueRef(value) => ValueRef::global_set(&mut self.globals, addr, value), + RuntimeValue::Value128(value) => Value128::global_set(&mut self.globals, addr, value), } Ok(()) } diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index cb8ded0..71d0184 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -106,8 +106,8 @@ impl TableInstance { return Ok(false); } - if cold_err!(self.elements.try_reserve_exact(n)).is_err() { - return Ok(false); + if self.elements.try_reserve_exact(n).is_err() { + return cold!(Ok(false)); } self.elements.resize(len, init); Ok(true) diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index 484b3cc..5eee068 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -1,11 +1,11 @@ use std::fmt::Write; use tinywasm::types::{FuncType, RefType, RefValue, WasmType, WasmValue}; -use tinywasm::{FuncContext, HostFunction, Imports, IntoWasmValues, Module, ModuleInstance, Store, ToWasmTypes}; +use tinywasm::{FuncContext, HostFunction, Imports, IntoWasmValues, Module, ModuleInstance, Store, WasmTypes}; struct TooFewParams; -impl ToWasmTypes for TooFewParams { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[WasmType::I32, WasmType::I32]); +impl WasmTypes for TooFewParams { + const WASM_TYPES: &'static [WasmType] = &[WasmType::I32, WasmType::I32]; } impl IntoWasmValues for TooFewParams { @@ -16,8 +16,8 @@ impl IntoWasmValues for TooFewParams { struct TooManyParams; -impl ToWasmTypes for TooManyParams { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[WasmType::I32, WasmType::I32]); +impl WasmTypes for TooManyParams { + const WASM_TYPES: &'static [WasmType] = &[WasmType::I32, WasmType::I32]; } impl IntoWasmValues for TooManyParams { diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 9330af6..b92a0f4 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,7 +1,7 @@ use alloc::boxed::Box; use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; -use crate::operands::read_field; +use crate::operands::{read_field, write_field}; use crate::{ DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand64Idx, Operand128, Operand128Idx, OperandIdx, RefType, }; @@ -188,8 +188,8 @@ impl Operand128<MemoryOperand> { #[inline] pub fn new(offset: u64, memory: MemAddr) -> Self { let mut operand = Self::default(); - operand.write_u64::<0>(offset); - operand.write_u32::<8>(memory); + write_field!(operand, u64, 0, offset); + write_field!(operand, u32, 8, memory); operand } @@ -211,8 +211,8 @@ impl Operand64<CompactMemoryOperand> { #[inline] pub fn new(offset: u32, memory: u16) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(offset); - operand.write_u16::<4>(memory); + write_field!(operand, u32, 0, offset); + write_field!(operand, u16, 4, memory); operand } @@ -233,9 +233,9 @@ impl Operand128<BranchTableOperand> { #[inline] pub fn new(target: u32, start: u32, len: u32) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(target); - operand.write_u32::<4>(start); - operand.write_u32::<8>(len); + write_field!(operand, u32, 0, target); + write_field!(operand, u32, 4, start); + write_field!(operand, u32, 8, len); operand } #[inline(always)] @@ -252,9 +252,9 @@ impl Operand128<MemoryFillOperand> { #[inline] pub fn new(memory: MemAddr, byte: u8, value: i32) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(memory); - operand.write_u8::<4>(byte); - operand.write_u32::<5>(value as u32); + write_field!(operand, u32, 0, memory); + write_field!(operand, u8, 4, byte); + write_field!(operand, i32, 5, value); operand } #[inline(always)] @@ -275,10 +275,10 @@ impl Operand128<LocalUpdateOperand> { #[inline] pub fn new(target: u32, value: i32, local: LocalAddr, on_zero: bool) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(target); - operand.write_u32::<4>(value as u32); - operand.write_u16::<8>(local); - operand.write_u8::<10>(u8::from(on_zero)); + write_field!(operand, u32, 0, target); + write_field!(operand, i32, 4, value); + write_field!(operand, u16, 8, local); + write_field!(operand, u8, 10, u8::from(on_zero)); operand } #[inline(always)] @@ -299,10 +299,10 @@ impl Operand128<GlobalUpdateOperand> { #[inline] pub fn new(target: u32, value: i32, global: GlobalAddr, on_zero: bool) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(target); - operand.write_u32::<4>(value as u32); - operand.write_u32::<8>(global); - operand.write_u8::<12>(u8::from(on_zero)); + write_field!(operand, u32, 0, target); + write_field!(operand, i32, 4, value); + write_field!(operand, u32, 8, global); + write_field!(operand, u8, 12, u8::from(on_zero)); operand } #[inline(always)] @@ -323,10 +323,10 @@ impl Operand128<LocalUpdateCmpOperand> { #[inline] pub fn new(target: u32, value: i32, local: LocalAddr, right: LocalAddr) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(target); - operand.write_u32::<4>(value as u32); - operand.write_u16::<8>(local); - operand.write_u16::<10>(right); + write_field!(operand, u32, 0, target); + write_field!(operand, i32, 4, value); + write_field!(operand, u16, 8, local); + write_field!(operand, u16, 10, right); operand } #[inline(always)] @@ -771,8 +771,6 @@ const _: () = assert!(core::mem::size_of::<Instruction>() == 8); #[cfg(test)] mod tests { - use alloc::vec; - use super::*; #[test] @@ -795,30 +793,4 @@ mod tests { assert_eq!(value.local(), u16::MAX); assert!(value.on_zero()); } - - #[test] - fn v128_operand_views_round_trip_max_bytes() { - let value = Operand128Idx::<[u8; 16]>::new(0); - let local = Operand64Idx::<(u16, Operand128Idx<[u8; 16]>)>::new(0); - let global = Operand64Idx::<(u32, Operand128Idx<[u8; 16]>)>::new(1); - let set = Operand64Idx::<(u16, u16, Operand128Idx<[u8; 16]>)>::new(2); - let data = super::super::WasmFunctionData { - operands128: vec![Operand128::<[u8; 16]>::new([u8::MAX; 16]).cast()].into_boxed_slice(), - operands64: vec![ - Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(u16::MAX, value).cast(), - Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(u32::MAX, value).cast(), - Operand64::<(u16, u16, Operand128Idx<[u8; 16]>)>::new(u16::MAX, u16::MAX, value).cast(), - ] - .into_boxed_slice(), - ..Default::default() - }; - - assert_eq!(value.resolve(&data).value(), [u8::MAX; 16]); - assert_eq!((local.resolve(&data).a(), local.resolve(&data).b()), (u16::MAX, value)); - assert_eq!((global.resolve(&data).a(), global.resolve(&data).b()), (u32::MAX, value)); - assert_eq!( - (set.resolve(&data).a(), set.resolve(&data).b(), set.resolve(&data).c()), - (u16::MAX, u16::MAX, value) - ); - } } diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs index 1bc4a28..edbab26 100644 --- a/crates/types/src/operands.rs +++ b/crates/types/src/operands.rs @@ -129,20 +129,14 @@ macro_rules! define_operand { #[cfg(feature = "archive")] impl<T> serde::Serialize for $name<T> { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: serde::Serializer, - { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { self.bytes.serialize(serializer) } } #[cfg(feature = "archive")] impl<'de, T> serde::Deserialize<'de> for $name<T> { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: serde::Deserializer<'de>, - { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { Ok(Self { bytes: <[u8; $len]>::deserialize(deserializer)?, marker: PhantomData }) } } @@ -153,19 +147,18 @@ define_operand!(Operand64, 8); define_operand!(Operand128, 16); macro_rules! unwrap_or_unreachable { - ($value:expr) => {{ unwrap_or_unreachable!($value, "entered unreachable code") }}; - ($value:expr, $message:literal) => {{ + ($value:expr) => {{ match $value { Some(value) => value, - None => operand_unreachable($message), + None => { core::hint::cold_path(); unreachable!() }, + } + }}; + ($value:expr, $($arg:tt)+) => {{ + match $value { + Some(value) => value, + None => { core::hint::cold_path(); unreachable!($($arg)+) }, } }}; -} - -#[cold] -#[inline(never)] -pub(crate) fn operand_unreachable(message: &'static str) -> ! { - unreachable!("{message}") } impl<T> Operand64Idx<T> { @@ -207,17 +200,19 @@ macro_rules! read_field { ($self:ident, i64, $offset:expr) => {{ read_field!($self, u64, $offset) as i64 }}; ($self:ident, idx128, $offset:expr) => {{ Operand128Idx::new(read_field!($self, u32, $offset)) }}; } -pub(crate) use read_field; macro_rules! read_bytes { ($self:ident, $offset:expr, $len:literal) => {{ match <[u8; $len]>::try_from(&$self.bytes[$offset..$offset + $len]) { Ok(bytes) => bytes, - Err(_) => $crate::operands::operand_unreachable("invalid operand field"), + Err(_) => { + core::hint::cold_path(); + unreachable!("invalid operand field read") + } } }}; } -pub(crate) use read_bytes; + macro_rules! write_field { ($self:ident, u8, $offset:expr, $value:expr) => {{ $self.write_u8::<{ $offset }>($value) }}; ($self:ident, u16, $offset:expr, $value:expr) => {{ $self.write_u16::<{ $offset }>($value) }}; @@ -228,6 +223,8 @@ macro_rules! write_field { ($self:ident, idx128, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value.index) }}; } +pub(crate) use {read_bytes, read_field, write_field}; + impl<T> Operand64<T> { /// Returns the jump target stored at the start of a retargetable operand. #[inline(always)] @@ -238,7 +235,7 @@ impl<T> Operand64<T> { /// Replaces the jump target stored at the start of a retargetable operand. #[inline] pub fn with_target(mut self, target: u32) -> Self { - self.write_u32::<0>(target); + write_field!(self, u32, 0, target); self } } @@ -253,7 +250,7 @@ impl<T> Operand128<T> { /// Replaces the jump target stored at the start of a retargetable operand. #[inline] pub fn with_target(mut self, target: u32) -> Self { - self.write_u32::<0>(target); + write_field!(self, u32, 0, target); self } } @@ -267,6 +264,7 @@ macro_rules! packed_layout { write_field!(operand, $field, 0, value); operand } + #[inline(always)] pub fn value(&self) -> field_ty!($field) { read_field!(self, $field, 0) @@ -282,10 +280,12 @@ macro_rules! packed_layout { write_field!(operand, $b, field_size!($a), b); operand } + #[inline(always)] pub fn a(&self) -> field_ty!($a) { read_field!(self, $a, 0) } + #[inline(always)] pub fn b(&self) -> field_ty!($b) { read_field!(self, $b, field_size!($a)) @@ -302,14 +302,17 @@ macro_rules! packed_layout { write_field!(operand, $c, field_size!($a) + field_size!($b), c); operand } + #[inline(always)] pub fn a(&self) -> field_ty!($a) { read_field!(self, $a, 0) } + #[inline(always)] pub fn b(&self) -> field_ty!($b) { read_field!(self, $b, field_size!($a)) } + #[inline(always)] pub fn c(&self) -> field_ty!($c) { read_field!(self, $c, field_size!($a) + field_size!($b)) @@ -329,7 +332,6 @@ packed_layout!(Operand64, operands64, u32, u16, u16); packed_layout!(Operand64, operands64, u16, idx128); packed_layout!(Operand64, operands64, u32, idx128); packed_layout!(Operand64, operands64, u16, u16, idx128); - packed_layout!(Operand128, operands128, u16, u64); packed_layout!(Operand128, operands128, u32, u64); packed_layout!(Operand128, operands128, u16, u16, u64); @@ -341,11 +343,13 @@ impl Operand128<[u8; 16]> { pub fn new(value: [u8; 16]) -> Self { Self { bytes: value, marker: PhantomData } } + #[inline(always)] pub fn value(&self) -> [u8; 16] { self.bytes } } + const _: () = { assert!(core::mem::size_of::<Operand64Idx<i64>>() == 4); assert!(core::mem::size_of::<Operand64>() == 8); diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs index 847e5e1..3a396a2 100644 --- a/crates/types/src/value.rs +++ b/crates/types/src/value.rs @@ -21,13 +21,6 @@ pub enum WasmType { Ref(RefType), } -impl WasmType { - #[inline] - pub const fn is_simd(self) -> bool { - matches!(self, Self::V128) - } -} - impl From<StorageType> for WasmType { fn from(value: StorageType) -> Self { match value { |
