diff options
Diffstat (limited to 'crates/parser')
| -rw-r--r-- | crates/parser/src/conversion.rs | 142 | ||||
| -rw-r--r-- | crates/parser/src/lib.rs | 1 | ||||
| -rw-r--r-- | crates/parser/src/macros.rs | 32 | ||||
| -rw-r--r-- | crates/parser/src/module.rs | 43 | ||||
| -rw-r--r-- | crates/parser/src/optimize.rs | 1 | ||||
| -rw-r--r-- | crates/parser/src/visit.rs | 184 |
6 files changed, 352 insertions, 51 deletions
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 600976a..8bc7df1 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -2,9 +2,9 @@ use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResour #[cfg(feature = "validate")] use crate::visit::process_operators_and_validate; use crate::{Result, module::FunctionCode, visit::process_operators}; -use alloc::{boxed::Box, format, string::ToString, vec::Vec}; +use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; -use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations}; +use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result<tinywasm_types::Element> { let kind = match element.kind { @@ -208,25 +208,77 @@ pub(crate) fn convert_module_code( )) } -pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<FuncType> { - let mut types = ty.types(); - // TODO(wasm3): Preserve recursive groups and non-function composite types instead of flattening singleton funcs. - if types.len() != 1 { - return Err(crate::ParseError::UnsupportedOperator( - "Expected exactly one type in the type section".to_string(), - )); +pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec<SubType>) -> Result<u32> { + let group_len = u32::try_from(ty.types().len()) + .map_err(|_| crate::ParseError::Other("recursive type group is too large".into()))?; + types.reserve(group_len as usize); + for ty in ty.into_types() { + let composite = &ty.composite_type; + if composite.shared { + return Err(crate::ParseError::UnsupportedOperator("shared composite types are unsupported".into())); + } + if composite.descriptor_idx.is_some() || composite.describes_idx.is_some() { + return Err(crate::ParseError::UnsupportedOperator("descriptor types are unsupported".into())); + } + + let supertype = + ty.supertype_idx.map(|idx| convert_type_index(idx.unpack(), group_start, group_len)).transpose()?; + let composite = match &composite.inner { + CompositeInnerType::Func(ty) => { + let params = ty + .params() + .iter() + .map(|ty| convert_valtype_in_group(ty, group_start, group_len)) + .collect::<Result<Vec<_>>>()?; + let results = ty + .results() + .iter() + .map(|ty| convert_valtype_in_group(ty, group_start, group_len)) + .collect::<Result<Vec<_>>>()?; + CompositeType::Func(FuncType::new(¶ms, &results)) + } + CompositeInnerType::Struct(ty) => CompositeType::Struct(StructType { + fields: ty + .fields + .iter() + .map(|field| convert_field_type(field, group_start, group_len)) + .collect::<Result<_>>()?, + }), + CompositeInnerType::Array(ty) => { + CompositeType::Array(ArrayType { field: convert_field_type(&ty.0, group_start, group_len)? }) + } + CompositeInnerType::Cont(_) => { + return Err(crate::ParseError::UnsupportedOperator("continuation types are unsupported".into())); + } + }; + types.push(SubType { is_final: ty.is_final, supertype, composite }); + } + Ok(group_len) +} + +fn convert_type_index(index: UnpackedIndex, group_start: u32, group_len: u32) -> Result<TypeAddr> { + match index { + UnpackedIndex::Module(index) => Ok(index), + UnpackedIndex::RecGroup(index) if index < group_len => { + group_start.checked_add(index).ok_or_else(|| crate::ParseError::Other("type index is too large".into())) + } + UnpackedIndex::RecGroup(index) => { + Err(crate::ParseError::Other(format!("recursive group type index out of bounds: {index}"))) + } + #[cfg(feature = "validate")] + UnpackedIndex::Id(_) => { + Err(crate::ParseError::UnsupportedOperator(format!("unsupported canonical type index: {index}"))) + } } +} - let ty = types.next().unwrap(); - let CompositeInnerType::Func(ty) = &ty.composite_type.inner else { - return Err(crate::ParseError::UnsupportedOperator(format!( - "Unsupported non-function type in type section: {}", - ty.composite_type - ))); +fn convert_field_type(field: &wasmparser::FieldType, group_start: u32, group_len: u32) -> Result<FieldType> { + let storage = match &field.element_type { + wasmparser::StorageType::I8 => StorageType::I8, + wasmparser::StorageType::I16 => StorageType::I16, + wasmparser::StorageType::Val(ty) => StorageType::Value(convert_valtype_in_group(ty, group_start, group_len)?), }; - let params = ty.params().iter().map(convert_valtype).collect::<Result<Vec<_>>>()?; - let results = ty.results().iter().map(convert_valtype).collect::<Result<Vec<_>>>()?; - Ok(FuncType::new(¶ms, &results)) + Ok(FieldType { storage, mutable: field.mutable }) } pub(crate) fn convert_ref_type(ty: wasmparser::RefType) -> Result<RefType> { @@ -234,13 +286,23 @@ pub(crate) fn convert_ref_type(ty: wasmparser::RefType) -> Result<RefType> { } pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> Result<WasmType> { + convert_valtype_with_group(valtype, None) +} + +fn convert_valtype_in_group(valtype: &wasmparser::ValType, group_start: u32, group_len: u32) -> Result<WasmType> { + convert_valtype_with_group(valtype, Some((group_start, group_len))) +} + +fn convert_valtype_with_group(valtype: &wasmparser::ValType, group: Option<(u32, u32)>) -> Result<WasmType> { match valtype { wasmparser::ValType::I32 => Ok(WasmType::I32), wasmparser::ValType::I64 => Ok(WasmType::I64), wasmparser::ValType::F32 => Ok(WasmType::F32), wasmparser::ValType::F64 => Ok(WasmType::F64), wasmparser::ValType::V128 => Ok(WasmType::V128), - wasmparser::ValType::Ref(r) => Ok(WasmType::Ref(convert_ref_type(*r)?)), + wasmparser::ValType::Ref(r) => { + Ok(WasmType::Ref(convert_heap_type_with_group(r.heap_type(), r.is_nullable(), group)?)) + } } } @@ -265,6 +327,20 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C wasmparser::Operator::RefFunc { function_index } => { ConstInstruction::Ref(RefValue::Func(FuncRef::new(function_index))) } + wasmparser::Operator::RefI31 => ConstInstruction::RefI31, + wasmparser::Operator::AnyConvertExtern => ConstInstruction::AnyConvertExtern, + wasmparser::Operator::ExternConvertAny => ConstInstruction::ExternConvertAny, + wasmparser::Operator::StructNew { struct_type_index } => ConstInstruction::StructNew(struct_type_index), + wasmparser::Operator::StructNewDefault { struct_type_index } => { + ConstInstruction::StructNewDefault(struct_type_index) + } + wasmparser::Operator::ArrayNew { array_type_index } => ConstInstruction::ArrayNew(array_type_index), + wasmparser::Operator::ArrayNewDefault { array_type_index } => { + ConstInstruction::ArrayNewDefault(array_type_index) + } + wasmparser::Operator::ArrayNewFixed { array_type_index, array_size } => { + ConstInstruction::ArrayNewFixed(array_type_index, array_size) + } wasmparser::Operator::I32Const { value } => ConstInstruction::I32Const(value), wasmparser::Operator::I64Const { value } => ConstInstruction::I64Const(value), wasmparser::Operator::F32Const { value } => ConstInstruction::F32Const(f32::from_bits(value.bits())), @@ -294,6 +370,14 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C } pub(crate) fn convert_heap_type(heap: wasmparser::HeapType, nullable: bool) -> Result<RefType> { + convert_heap_type_with_group(heap, nullable, None) +} + +fn convert_heap_type_with_group( + heap: wasmparser::HeapType, + nullable: bool, + group: Option<(u32, u32)>, +) -> Result<RefType> { match heap { wasmparser::HeapType::Abstract { shared: false, ty } => Ok(RefType::new_abstract( nullable, @@ -316,9 +400,23 @@ pub(crate) fn convert_heap_type(heap: wasmparser::HeapType, nullable: bool) -> R }, )), wasmparser::HeapType::Concrete(index) => { - let index = index.as_module_index().ok_or_else(|| { - crate::ParseError::UnsupportedOperator(format!("Unsupported non-module heap type index: {index:?}")) - })?; + let index = match index { + UnpackedIndex::Module(index) => index, + index @ UnpackedIndex::RecGroup(_) => { + let (group_start, group_len) = group.ok_or_else(|| { + crate::ParseError::UnsupportedOperator(format!( + "recursive-group heap type outside a type group: {index}" + )) + })?; + convert_type_index(index, group_start, group_len)? + } + #[cfg(feature = "validate")] + index @ UnpackedIndex::Id(_) => { + return Err(crate::ParseError::UnsupportedOperator(format!( + "unsupported canonical heap type index: {index}" + ))); + } + }; RefType::new_concrete(nullable, index) .ok_or_else(|| crate::ParseError::Other(format!("heap type index is too large: {index}"))) } diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 6efc112..5439558 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -174,6 +174,7 @@ impl Parser { | WasmFeatures::BULK_MEMORY_OPT | WasmFeatures::RELAXED_SIMD | WasmFeatures::GC_TYPES + | WasmFeatures::GC | WasmFeatures::REFERENCE_TYPES | WasmFeatures::MUTABLE_GLOBAL | WasmFeatures::MULTI_VALUE diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 4ce23bb..553f439 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -37,6 +37,27 @@ pub(crate) mod visit { $(lowering_ops!(@effect $inputs => $outputs $visit);)* lowering_ops!($($rest)*); }; + (unsupported $args:tt { $($visit:ident),* $(,)? } $($rest:tt)*) => { + $(lowering_ops!(@unsupported $args $visit);)* + lowering_ops!($($rest)*); + }; + (heap $nullable:literal $inputs:tt => $outputs:tt { + $($visit:ident => $instr:ident),* $(,)? + } $($rest:tt)*) => { + $( + fn $visit(&mut self, heap_type: wasmparser::HeapType) -> Self::Output { + let ty = convert_heap_type(heap_type, $nullable)?; + lowering_ops!(@emit self fixed $inputs => $outputs Instruction::$instr(ty)) + } + )* + lowering_ops!($($rest)*); + }; + + (@unsupported [$($argty:ty),*] $visit:ident) => { + fn $visit(&mut self $(, _: $argty)*) -> Self::Output { + Err(crate::ParseError::UnsupportedOperator(stringify!($visit).to_string())) + } + }; (@fixed [$($input:ident),*] => [$($output:ident),*] $visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident @@ -64,6 +85,15 @@ pub(crate) mod visit { (@table $inputs:tt => $outputs:tt $($operator:tt)*) => { lowering_ops!(@resolved table_size $inputs => $outputs $($operator)*); }; + (@array_field [$($input:ident),*] => [$($output:ident),*] + $visit:ident($type_index:ident: $type_ty:ty $(, $arg:ident: $arg_ty:ty)*) => $instr:ident + ) => { + fn $visit(&mut self, $type_index: $type_ty $(, $arg: $arg_ty)*) -> Self::Output { + let size = ModuleMetadata::storage_size(self.metadata.array_field($type_index)?.storage); + lowering_ops!(@emit self address(size) [$($input),*] => [$($output),*] + Instruction::$instr($type_index $(, $arg)*).into()) + } + }; (@resolved $resolver:ident [$($input:ident),*] => [$($output:ident),*] $visit:ident($index:ident: $ty:ty) => $instr:ident ) => { @@ -110,6 +140,7 @@ pub(crate) mod visit { }; (@size Addr, $address:ident) => { $address }; + (@size Field, $address:ident) => { $address }; (@size $size:ident $(, $address:ident)?) => { OperandSize::$size }; } @@ -128,6 +159,7 @@ pub(crate) mod visit { (@@relaxed_simd $($rest:tt)* ) => {}; (@@tail_call $($rest:tt)* ) => {}; (@@function_references $($rest:tt)* ) => {}; + (@@gc $($rest:tt)* ) => {}; (@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => { fn $visit(&mut self $($(,_: $argty)*)?) -> Self::Output { diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index a269141..237478c 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -44,11 +44,12 @@ pub(crate) struct ModuleReader<'a> { translation_metadata: Option<Arc<crate::visit::ModuleMetadata>>, has_code_section: bool, + has_type_section: bool, marker: PhantomData<&'a [u8]>, pub(crate) version: Option<u16>, pub(crate) start_func: Option<u32>, - pub(crate) func_types: Box<[FuncType]>, + pub(crate) types: TypeSection, pub(crate) code_type_addrs: Box<[u32]>, code_results: Box<[ValueCounts]>, pub(crate) exports: Arc<[Export]>, @@ -71,7 +72,7 @@ impl<'a> ModuleReader<'a> { fn translation_metadata(&mut self) -> &crate::visit::ModuleMetadata { if self.translation_metadata.is_none() { self.translation_metadata = Some(Arc::new(crate::visit::ModuleMetadata::new( - &self.func_types, + &self.types, &self.code_type_addrs, &self.imports, &self.globals, @@ -119,12 +120,25 @@ impl<'a> ModuleReader<'a> { self.start_func = Some(func); } Payload::TypeSection(reader) => { - check_section("type", !self.func_types.is_empty())?; + check_section("type", self.has_type_section)?; + self.has_type_section = true; #[cfg(feature = "validate")] if let Some(validator) = validator.as_mut() { validator.type_section(&reader)?; } - self.func_types = reader.into_iter().map(|t| convert_module_type(t?)).collect::<Result<_>>()?; + let mut types = Vec::with_capacity(reader.count() as usize); + let mut rec_group_lengths = Vec::with_capacity(reader.count() as usize); + for group in reader { + let group = group?; + let group_start = u32::try_from(types.len()) + .map_err(|_| ParseError::Other("type section is too large".into()))?; + let group_len = convert_rec_group(group, group_start, &mut types)?; + rec_group_lengths.push(group_len); + } + self.types = TypeSection { + types: types.into_boxed_slice(), + rec_group_lengths: rec_group_lengths.into_boxed_slice(), + }; } Payload::GlobalSection(reader) => { check_section("global", !self.globals.is_empty())?; @@ -207,10 +221,9 @@ impl<'a> ModuleReader<'a> { let mut results = Vec::with_capacity(reader.count() as usize); for ty_idx in reader { let ty_idx = ty_idx?; - let ty = self - .func_types - .get(ty_idx as usize) - .ok_or_else(|| ParseError::Other(format!("function type index out of bounds: {ty_idx}")))?; + let ty = self.types.get(ty_idx).and_then(SubType::as_func).ok_or_else(|| { + ParseError::Other(format!("function type index does not reference a function: {ty_idx}")) + })?; type_addrs.push(ty_idx); results.push(ValueCounts::from_iter(ty.results())); } @@ -227,7 +240,14 @@ impl<'a> ModuleReader<'a> { for import in reader.into_imports() { let import = convert_module_import(import?)?; match import.kind { - ImportKind::Function(_) => self.imported_func_count += 1, + ImportKind::Function(type_idx) => { + if self.types.get(type_idx).and_then(SubType::as_func).is_none() { + return Err(ParseError::Other(format!( + "function import type index does not reference a function: {type_idx}" + ))); + } + self.imported_func_count += 1; + } ImportKind::Memory(_) => self.imported_memory_count += 1, _ => {} } @@ -504,7 +524,8 @@ impl<'a> ModuleReader<'a> { .zip(self.code_type_addrs) .zip(self.code_results) .map(|((code, ty_idx), results)| { - let ty = self.func_types.get(ty_idx as usize).expect("function type was checked while parsing").clone(); + let ty = + self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing"); let params = ValueCounts::from_iter(ty.params()); if code.uses_local_memory { local_memory_allocation = LocalMemoryAllocation::Eager; @@ -522,7 +543,7 @@ impl<'a> ModuleReader<'a> { Ok(ModuleInner { funcs, - func_types: self.func_types, + types: self.types, func_type_idxs, globals: self.globals, tables: self.tables, diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index dcb7568..5c2d7d5 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -858,6 +858,7 @@ fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> { | Instruction::JumpIfNonZero64(ip) | Instruction::JumpIfRefNull(ip) | Instruction::JumpIfRefNonNull(ip) + | Instruction::BrOnCast(ip, _, _) | Instruction::JumpCmpStackConst32 { target_ip: ip, .. } | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 67651f9..4437242 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -2,8 +2,8 @@ use crate::{Result, conversion::convert_heap_type, macros::visit::*}; use alloc::string::ToString; use alloc::vec::Vec; use tinywasm_types::{ - FuncType, Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, TableDefinition, ValueCounts, - WasmFunctionData, WasmType, + Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, + TypeSection, ValueCounts, WasmFunctionData, WasmType, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -85,11 +85,12 @@ pub(crate) struct Signature { } pub(crate) struct ModuleMetadata { - signatures: Vec<Signature>, + signatures: Vec<Option<Signature>>, functions: Vec<u32>, globals: Vec<OperandSize>, memories: Vec<OperandSize>, tables: Vec<OperandSize>, + types: Vec<SubType>, } #[derive(Default)] @@ -140,6 +141,16 @@ impl<'a> FunctionBuilder<'a> { lane_counts: ValueCounts::default(), } } + + fn visit_struct_get_impl( + &mut self, + type_index: u32, + field_index: u32, + instruction: fn(u32, u32) -> Instruction, + ) -> Result<()> { + let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); + self.emit(&[OperandSize::S32], &[size], instruction(type_index, field_index)) + } } #[cfg(feature = "validate")] @@ -151,7 +162,7 @@ struct ValidateThenVisit<'a, 'm> { impl ModuleMetadata { pub(crate) fn new( - types: &[FuncType], + types: &TypeSection, code_type_addrs: &[u32], imports: &[Import], globals: &[Global], @@ -178,19 +189,30 @@ impl ModuleMetadata { table_sizes.extend(tables.iter().map(|table| OperandSize::from(table.ty.arch()))); let signatures = types + .types .iter() - .map(|ty| Signature { - params: ty.params().iter().map(OperandSize::from).collect(), - results: ty.results().iter().map(OperandSize::from).collect(), + .map(|ty| { + ty.as_func().map(|ty| Signature { + params: ty.params().iter().map(OperandSize::from).collect(), + results: ty.results().iter().map(OperandSize::from).collect(), + }) }) .collect(); - Self { signatures, functions, globals: global_sizes, memories: memory_sizes, tables: table_sizes } + Self { + signatures, + functions, + globals: global_sizes, + memories: memory_sizes, + tables: table_sizes, + types: types.types.to_vec(), + } } pub(crate) fn signature(&self, idx: u32) -> Result<&Signature> { self.signatures .get(idx as usize) - .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index out of bounds: {idx}"))) + .and_then(Option::as_ref) + .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not a function type: {idx}"))) } fn function_signature(&self, idx: u32) -> Result<&Signature> { @@ -219,6 +241,36 @@ impl ModuleMetadata { .copied() .ok_or_else(|| crate::ParseError::Other(alloc::format!("{entity} index out of bounds: {idx}"))) } + + fn storage_size(storage: StorageType) -> OperandSize { + match storage { + StorageType::I8 | StorageType::I16 => OperandSize::S32, + StorageType::Value(ref ty) => OperandSize::from(ty), + } + } + + fn struct_fields(&self, idx: u32) -> Result<&[tinywasm_types::FieldType]> { + self.types + .get(idx as usize) + .and_then(SubType::as_struct) + .map(|ty| ty.fields.as_ref()) + .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not a struct type: {idx}"))) + } + + fn struct_field(&self, type_index: u32, field_index: u32) -> Result<tinywasm_types::FieldType> { + self.struct_fields(type_index)? + .get(field_index as usize) + .copied() + .ok_or_else(|| crate::ParseError::Other("struct field index out of bounds".into())) + } + + fn array_field(&self, idx: u32) -> Result<tinywasm_types::FieldType> { + self.types + .get(idx as usize) + .and_then(SubType::as_array) + .map(|ty| ty.field) + .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not an array type: {idx}"))) + } } #[cfg(feature = "validate")] @@ -339,8 +391,17 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fixed [] => [] { visit_data_drop(segment: u32) => DataDrop, visit_elem_drop(segment: u32) => ElemDrop } fixed [] => [S32] { visit_i32_const(value: i32) => Const32, visit_ref_func(function: u32) => RefFunc } fixed [] => [S64] { visit_i64_const(value: i64) => Const64 } + heap false [] => [S32] { visit_ref_null => RefNull } + heap false [S32] => [S32] { + visit_ref_test_non_null => RefTest, visit_ref_cast_non_null => RefCast, + } + heap true [S32] => [S32] { + visit_ref_test_nullable => RefTest, visit_ref_cast_nullable => RefCast, + } fixed [S32] => [S32] { - visit_i32_eqz => I32Eqz, visit_ref_is_null => RefIsNull, visit_i32_clz => I32Clz, + visit_ref_is_null => RefIsNull, visit_ref_as_non_null => RefAsNonNull, visit_ref_i31 => RefI31, + visit_i31_get_s => I31GetS, visit_i31_get_u => I31GetU, + visit_i32_eqz => I32Eqz, visit_i32_clz => I32Clz, visit_i32_ctz => I32Ctz, visit_i32_popcnt => I32Popcnt, visit_i32_extend8_s => I32Extend8S, visit_i32_extend16_s => I32Extend16S, visit_i32_trunc_f32_s => I32TruncF32S, visit_i32_trunc_f32_u => I32TruncF32U, visit_f32_convert_i32_s => F32ConvertI32S, @@ -349,6 +410,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { visit_f32_ceil => F32Ceil, visit_f32_floor => F32Floor, visit_f32_trunc => F32Trunc, visit_f32_nearest => F32Nearest, visit_f32_sqrt => F32Sqrt, } + effect [S32] => [S32] { visit_any_convert_extern, visit_extern_convert_any } fixed [S64] => [S64] { visit_i64_clz => I64Clz, visit_i64_ctz => I64Ctz, visit_i64_popcnt => I64Popcnt, visit_i64_extend8_s => I64Extend8S, visit_i64_extend16_s => I64Extend16S, @@ -373,7 +435,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { visit_i64_trunc_sat_f32_u => I64TruncSatF32U, } fixed [S32, S32] => [S32] { - visit_i32_eq => I32Eq, visit_i32_ne => I32Ne, visit_i32_lt_s => I32LtS, visit_i32_lt_u => I32LtU, + visit_ref_eq => RefEq, visit_i32_eq => I32Eq, visit_i32_ne => I32Ne, + visit_i32_lt_s => I32LtS, visit_i32_lt_u => I32LtU, visit_i32_gt_s => I32GtS, visit_i32_gt_u => I32GtU, visit_i32_le_s => I32LeS, visit_i32_le_u => I32LeU, visit_i32_ge_s => I32GeS, visit_i32_ge_u => I32GeU, visit_f32_eq => F32Eq, visit_f32_ne => F32Ne, visit_f32_lt => F32Lt, visit_f32_gt => F32Gt, @@ -420,6 +483,65 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { table [S32, Addr] => [Addr] { visit_table_grow(table: u32) => TableGrow } table [Addr, S32, Addr] => [] { visit_table_fill(table: u32) => TableFill } table [Addr, S32, S32] => [] { visit_table_init(elem_index: u32, table: u32) => TableInit } + fixed [] => [S32] { visit_struct_new_default(type_index: u32) => StructNewDefault } + fixed [S32] => [S32] { + visit_array_new_default(type_index: u32) => ArrayNewDefault, visit_array_len => ArrayLen, + } + fixed [S32, S32] => [S32] { + visit_array_new_data(type_index: u32, data_index: u32) => ArrayNewData, + visit_array_new_elem(type_index: u32, elem_index: u32) => ArrayNewElem, + } + fixed [S32, S32, S32, S32] => [] { + visit_array_init_data(type_index: u32, data_index: u32) => ArrayInitData, + visit_array_init_elem(type_index: u32, elem_index: u32) => ArrayInitElem, + } + fixed [S32, S32, S32, S32, S32] => [] { + visit_array_copy(type_index_dst: u32, type_index_src: u32) => ArrayCopy, + } + array_field [Field, S32] => [S32] { visit_array_new(type_index: u32) => ArrayNew } + array_field [S32, S32] => [Field] { + visit_array_get(type_index: u32) => ArrayGet, visit_array_get_s(type_index: u32) => ArrayGetS, + visit_array_get_u(type_index: u32) => ArrayGetU, + } + array_field [S32, S32, Field] => [] { visit_array_set(type_index: u32) => ArraySet } + array_field [S32, S32, Field, S32] => [] { visit_array_fill(type_index: u32) => ArrayFill } + } + + fn visit_struct_new(&mut self, type_index: u32) -> Self::Output { + let inputs = self + .metadata + .struct_fields(type_index)? + .iter() + .map(|field| ModuleMetadata::storage_size(field.storage)) + .collect::<Vec<_>>(); + self.emit(&inputs, &[OperandSize::S32], Instruction::StructNew(type_index)) + } + + fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output { + self.visit_struct_get_impl(type_index, field_index, Instruction::StructGet) + } + + fn visit_struct_get_s(&mut self, type_index: u32, field_index: u32) -> Self::Output { + self.visit_struct_get_impl(type_index, field_index, Instruction::StructGetS) + } + + fn visit_struct_get_u(&mut self, type_index: u32, field_index: u32) -> Self::Output { + self.visit_struct_get_impl(type_index, field_index, Instruction::StructGetU) + } + + fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { + let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); + self.emit(&[OperandSize::S32, size], &[], Instruction::StructSet(type_index, field_index)) + } + + fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { + let size = ModuleMetadata::storage_size(self.metadata.array_field(type_index)?.storage); + for _ in 0..array_size { + self.pop_expect(size)?; + } + self.push_sizes(&[OperandSize::S32])?; + self.instructions.push(Instruction::ArrayNewFixed(type_index, array_size)); + Ok(()) } fn visit_call(&mut self, function_index: u32) -> Self::Output { @@ -718,14 +840,22 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem }) } - // Reference Types - fn visit_ref_null(&mut self, ty: wasmparser::HeapType) -> Self::Output { - let instruction = Instruction::RefNull(convert_heap_type(ty, false)?); - self.emit(&[], &[OperandSize::S32], instruction) + fn visit_br_on_cast( + &mut self, + relative_depth: u32, + _from_ref_type: wasmparser::RefType, + to_ref_type: wasmparser::RefType, + ) -> Self::Output { + self.emit_cast_branch(relative_depth, to_ref_type, false) } - fn visit_ref_as_non_null(&mut self) -> Self::Output { - self.emit(&[OperandSize::S32], &[OperandSize::S32], Instruction::RefAsNonNull) + fn visit_br_on_cast_fail( + &mut self, + relative_depth: u32, + _from_ref_type: wasmparser::RefType, + to_ref_type: wasmparser::RefType, + ) -> Self::Output { + self.emit_cast_branch(relative_depth, to_ref_type, true) } fn visit_br_on_null(&mut self, relative_depth: u32) -> Self::Output { @@ -971,6 +1101,23 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } impl FunctionBuilder<'_> { + fn emit_cast_branch( + &mut self, + relative_depth: u32, + target: wasmparser::RefType, + branch_on_fail: bool, + ) -> Result<()> { + self.pop_expect(OperandSize::S32)?; + let target = convert_heap_type(target.heap_type(), target.is_nullable())?; + let conditional_ip = self.instructions.len(); + self.instructions.push(Instruction::BrOnCast(0, target, branch_on_fail)); + self.push_sizes(&[OperandSize::S32])?; + self.emit_dropkeep_to_label(relative_depth)?; + self.emit_branch_jump_or_return(relative_depth)?; + self.patch_jump(conditional_ip, self.instructions.len()); + Ok(()) + } + fn is_unreachable(&self) -> bool { self.control_stack.last().is_none_or(|frame| frame.unreachable) } @@ -1108,7 +1255,8 @@ impl FunctionBuilder<'_> { | Instruction::JumpIfZero32(ip) | Instruction::JumpIfNonZero32(ip) | Instruction::JumpIfRefNull(ip) - | Instruction::JumpIfRefNonNull(ip) => { + | Instruction::JumpIfRefNonNull(ip) + | Instruction::BrOnCast(ip, _, _) => { *ip = target as u32; } _ => {} |
