diff options
Diffstat (limited to 'crates/parser')
| -rw-r--r-- | crates/parser/src/conversion.rs | 41 | ||||
| -rw-r--r-- | crates/parser/src/emitter.rs | 355 | ||||
| -rw-r--r-- | crates/parser/src/lib.rs | 35 | ||||
| -rw-r--r-- | crates/parser/src/macros.rs | 133 | ||||
| -rw-r--r-- | crates/parser/src/module.rs | 47 | ||||
| -rw-r--r-- | crates/parser/src/optimize/mod.rs | 4 | ||||
| -rw-r--r-- | crates/parser/src/optimize/rewrite.rs | 1500 | ||||
| -rw-r--r-- | crates/parser/src/optimize/targets.rs | 227 | ||||
| -rw-r--r-- | crates/parser/src/parallel.rs | 28 | ||||
| -rw-r--r-- | crates/parser/src/selection.rs | 314 | ||||
| -rw-r--r-- | crates/parser/src/selection/encoding.rs | 293 | ||||
| -rw-r--r-- | crates/parser/src/visit.rs | 916 |
12 files changed, 1565 insertions, 2328 deletions
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 4cf0d02..36455ee 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -6,6 +6,17 @@ use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; +/// Function identity and result layout shared by lowering and finalization. +#[derive(Clone, Copy)] +pub(crate) struct FunctionLoweringContext { + /// Module type index of the function signature. + pub(crate) ty_idx: u32, + /// Module function index, including imported functions. + pub(crate) self_func_addr: u32, + /// Result counts in each physical value lane. + pub(crate) function_results: ValueCounts, +} + pub(crate) fn value_lane(ty: wasmparser::ValType) -> ValueLane { match ty { wasmparser::ValType::I32 | wasmparser::ValType::F32 | wasmparser::ValType::Ref(_) => ValueLane::S32, @@ -148,11 +159,11 @@ pub(crate) fn convert_module_code( validator: Option<FuncValidator<ValidatorResources>>, reader_allocs: OperatorsReaderAllocations, metadata: &crate::visit::ModuleMetadata, - ty_idx: u32, + context: FunctionLoweringContext, options: &ParserOptions, ) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> { let mut locals_reader = func.get_locals_reader()?; - let mut local_types = metadata.signature(ty_idx)?.params.clone(); + let mut local_types = metadata.signature(context.ty_idx)?.params.clone(); #[cfg(feature = "validate")] let mut validator = validator; @@ -193,39 +204,27 @@ pub(crate) fn convert_module_code( func, (local_types, local_addr_map), metadata, - ty_idx, + context, reader_allocs, - options.deduplicate_operands(), + options, )?; (body, data, uses_local_memory, Some(validator_allocs), reader_allocs) } None => { - let (body, data, uses_local_memory, reader_allocs) = process_operators( - func, - (local_types, local_addr_map), - metadata, - ty_idx, - reader_allocs, - options.deduplicate_operands(), - )?; + let (body, data, uses_local_memory, reader_allocs) = + process_operators(func, (local_types, local_addr_map), metadata, context, reader_allocs, options)?; (body, data, uses_local_memory, None, reader_allocs) } }; #[cfg(not(feature = "validate"))] let (body, data, uses_local_memory, validator_allocs, reader_allocs) = { let _ = validator; - let (body, data, uses_local_memory, reader_allocs) = process_operators( - func, - (local_types, local_addr_map), - metadata, - ty_idx, - reader_allocs, - options.deduplicate_operands(), - )?; + let (body, data, uses_local_memory, reader_allocs) = + process_operators(func, (local_types, local_addr_map), metadata, context, reader_allocs, options)?; (body, data, uses_local_memory, None, reader_allocs) }; Ok(( - FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory }, + FunctionCode { instructions: body, data: data.finish(), locals: local_counts, uses_local_memory }, validator_allocs, reader_allocs, )) diff --git a/crates/parser/src/emitter.rs b/crates/parser/src/emitter.rs new file mode 100644 index 0000000..d36444a --- /dev/null +++ b/crates/parser/src/emitter.rs @@ -0,0 +1,355 @@ +//! Streaming instruction selection with stable labels and target-only relocation. + +use crate::{ + ParseError, ParserOptions, Result, conversion::FunctionLoweringContext, selection, visit::FunctionDataBuilder, +}; +use alloc::vec::Vec; +use tinywasm_types::{BranchTableOperand, ExceptionCatch, ExceptionHandler, Instruction, Operand128, ValueCounts}; + +const LOOKBEHIND: usize = 3; + +/// Restricted vector view, with no readable or mutable access to the committed prefix. +pub(crate) struct PendingTail<'a> { + instructions: &'a mut Vec<Instruction>, + start: usize, +} + +impl<'a> PendingTail<'a> { + fn new(instructions: &'a mut Vec<Instruction>, start: usize) -> Self { + assert!(start < instructions.len() && instructions.len() - start <= LOOKBEHIND + 1); + Self { instructions, start } + } + + /// Copies at most four pending instructions, including the incoming instruction. + pub(crate) fn suffix<const N: usize>(&self) -> Option<[Instruction; N]> { + const { assert!(N > 0 && N <= LOOKBEHIND + 1) }; + let pending = &self.instructions[self.start..]; + let start = pending.len().checked_sub(N)?; + Some(pending[start..].try_into().unwrap()) + } + + /// Splices a non-growing suffix and truncates immediately, leaving no holes. + pub(crate) fn replace<const N: usize, const M: usize>(&mut self, replacements: [Instruction; M]) { + const { + assert!(N > 0 && N <= LOOKBEHIND + 1); + assert!(M <= N); + } + let pending = &mut self.instructions[self.start..]; + let start = pending.len().checked_sub(N).expect("replacement exceeds pending tail"); + pending[start..start + M].copy_from_slice(&replacements); + self.instructions.truncate(self.start + start + M); + } +} + +/// Identity of a stable instruction boundary. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct LabelId(usize); + +enum PatchSite { + Instruction(usize), + TableEntry(usize), + ExceptionStart(usize), + ExceptionEnd(usize), + Catch(usize, usize), +} + +/// Owns one instruction vector with an immutable prefix and at most three pending instructions. +pub(crate) struct Emitter { + instructions: Vec<Instruction>, + committed: usize, + select: bool, + self_func_addr: u32, + return_instruction: Instruction, + pending_jump: Option<LabelId>, + labels: Vec<Option<u32>>, + uses: Vec<(PatchSite, LabelId)>, +} + +impl Emitter { + /// Creates an emitter with a bounded initial allocation. + pub(crate) fn new(body_size: usize, context: FunctionLoweringContext, options: &ParserOptions) -> Self { + use Instruction::*; + let return_instruction = match (options.optimize(), context.function_results) { + (true, ValueCounts { c32: 0, c64: 0, c128: 0 }) => ReturnVoid, + (true, ValueCounts { c32: 1, c64: 0, c128: 0 }) => Return32, + (true, ValueCounts { c32: 0, c64: 1, c128: 0 }) => Return64, + (true, ValueCounts { c32: 0, c64: 0, c128: 1 }) => Return128, + _ => Return, + }; + Self { + instructions: Vec::with_capacity(body_size.min(1024)), + committed: 0, + select: options.optimize(), + self_func_addr: context.self_func_addr, + return_instruction, + pending_jump: None, + labels: Vec::new(), + uses: Vec::new(), + } + } + + /// Whether lowering may select optimized instruction and target forms. + pub(crate) fn optimizations_enabled(&self) -> bool { + self.select + } + + /// Allocates an unbound structural or executable label. + pub(crate) fn new_label(&mut self) -> LabelId { + let label = LabelId(self.labels.len()); + self.labels.push(None); + label + } + + /// Flushes the pending tail and records a stable boundary. + pub(crate) fn bind(&mut self, label: LabelId) -> Result<()> { + // Only the uncommitted jump can disappear. Any other binding seals it, + // so removing it cannot move a previously bound boundary. + if self.pending_jump == Some(label) { + debug_assert_eq!(self.instructions.len(), self.committed + 1); + debug_assert!(matches!(self.instructions.last(), Some(Instruction::Jump(_)))); + self.pending_jump = None; + self.instructions.pop(); + } + self.seal_jump(); + self.commit(self.instructions.len()); + let offset = u32::try_from(self.instructions.len()) + .map_err(|_| ParseError::Other("function body is too large".into()))?; + let binding = self.labels.get_mut(label.0).ok_or_else(|| ParseError::Other("unknown label".into()))?; + if binding.is_some() { + return Err(ParseError::Other("label bound more than once".into())); + } + *binding = Some(offset); + Ok(()) + } + + /// Appends an instruction without applying logical stack effects. + #[inline] + pub(crate) fn emit(&mut self, instruction: Instruction) -> Result<()> { + self.push(instruction)?; + self.commit(self.instructions.len().saturating_sub(LOOKBEHIND).max(self.committed)); + Ok(()) + } + + /// Emits a call or terminator and seals the tail against subsequent fusion. + pub(crate) fn emit_boundary(&mut self, instruction: Instruction) -> Result<()> { + use Instruction::*; + let instruction = match instruction { + Call(address) if self.select && address == self.self_func_addr => CallSelf, + ReturnCall(address) if self.select && address == self.self_func_addr => ReturnCallSelf, + Return => self.return_instruction, + _ => instruction, + }; + self.push(instruction)?; + self.commit(self.instructions.len()); + Ok(()) + } + + fn push(&mut self, instruction: Instruction) -> Result<()> { + self.seal_jump(); + if self.instructions.len() >= u32::MAX as usize { + return Err(ParseError::Other("function body is too large".into())); + } + self.instructions.push(instruction); + Ok(()) + } + + fn seal_jump(&mut self) { + if let Some(label) = self.pending_jump.take() { + self.uses.push((PatchSite::Instruction(self.instructions.len() - 1), label)); + self.committed = self.instructions.len(); + } + } + + /// Appends and applies one statically selected family, without redispatching replacements. + #[inline] + pub(crate) fn emit_with( + &mut self, + data: &mut FunctionDataBuilder, + instruction: Instruction, + rules: impl FnOnce(&mut PendingTail<'_>, &mut FunctionDataBuilder) -> Result<()>, + ) -> Result<()> { + self.push(instruction)?; + if self.select { + rules(&mut PendingTail::new(&mut self.instructions, self.committed), data)?; + } + self.commit(self.instructions.len().saturating_sub(LOOKBEHIND).max(self.committed)); + Ok(()) + } + + /// Selects a conditional branch before sealing and recording its final patch site. + pub(crate) fn branch_if(&mut self, data: &mut FunctionDataBuilder, on_zero: bool, label: LabelId) -> Result<()> { + let instruction = if on_zero { Instruction::JumpIfZero32(0) } else { Instruction::JumpIfNonZero32(0) }; + self.emit_with(data, instruction, |tail, data| selection::conditional(tail, data, on_zero, 0))?; + // Conditional rules always retain a final target-bearing instruction. + assert!(self.instructions.len() > self.committed, "conditional rule removed its branch"); + let site = self.instructions.len() - 1; + self.uses.push((PatchSite::Instruction(site), label)); + self.commit(self.instructions.len()); + Ok(()) + } + + /// Emits a target-bearing instruction and records its symbolic destination. + /// Side operands must come from the non-deduplicating target operand allocators + /// and belong exclusively to this instruction. + pub(crate) fn branch(&mut self, instruction: Instruction, label: LabelId) -> Result<()> { + if self.select && matches!(instruction, Instruction::Jump(_)) { + self.commit(self.instructions.len()); + self.push(instruction)?; + self.pending_jump = Some(label); + return Ok(()); + } + self.emit(instruction)?; + let site = self.instructions.len() - 1; + self.uses.push((PatchSite::Instruction(site), label)); + self.commit(self.instructions.len()); + Ok(()) + } + + /// Commits table storage and records case and default destinations. + pub(crate) fn branch_table( + &mut self, + data: &mut FunctionDataBuilder, + targets: &[LabelId], + default: LabelId, + ) -> Result<()> { + let start = u32::try_from(data.branch_table_targets.len()) + .map_err(|_| ParseError::Other("branch table pool is too large".into()))?; + let count = u32::try_from(targets.len()).map_err(|_| ParseError::Other("branch table is too large".into()))?; + start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; + let operand = data.push_target128(Operand128::<BranchTableOperand>::new(0, start, count))?; + self.branch(Instruction::BranchTable(operand), default)?; + for &label in targets { + self.uses.push((PatchSite::TableEntry(data.branch_table_targets.len()), label)); + data.branch_table_targets.push(0); + } + Ok(()) + } + + /// Records exception boundaries and landing pads alongside their metadata. + pub(crate) fn exception_handler( + &mut self, + data: &mut FunctionDataBuilder, + start: LabelId, + end: LabelId, + catches: Vec<(ExceptionCatch, LabelId)>, + ) { + let index = data.exception_handlers.len(); + self.uses.push((PatchSite::ExceptionStart(index), start)); + self.uses.push((PatchSite::ExceptionEnd(index), end)); + let catches = catches + .into_iter() + .enumerate() + .map(|(catch_index, (catch, label))| { + self.uses.push((PatchSite::Catch(index, catch_index), label)); + catch + }) + .collect(); + data.exception_handlers.push(ExceptionHandler { start_ip: 0, end_ip: 0, catches }); + } + + fn commit(&mut self, end: usize) { + debug_assert!(self.committed <= end && end <= self.instructions.len()); + self.committed = end; + } + + /// Flushes the tail and resolves recorded targets without moving instructions. + pub(crate) fn finish(mut self, data: &mut FunctionDataBuilder) -> Result<Vec<Instruction>> { + self.seal_jump(); + self.commit(self.instructions.len()); + let invalid_site = || ParseError::Other("invalid label patch site".into()); + for (site, label) in self.uses { + let target = self + .labels + .get(label.0) + .copied() + .flatten() + .ok_or_else(|| ParseError::Other("referenced label is not bound".into()))?; + let boundary = matches!(site, PatchSite::ExceptionEnd(_)); + if target as usize > self.instructions.len() || (!boundary && target as usize == self.instructions.len()) { + return Err(ParseError::Other("label target out of bounds".into())); + } + match site { + PatchSite::Instruction(index) => { + let instruction = self.instructions.get_mut(index).ok_or_else(invalid_site)?; + Self::patch_target(instruction, data, target)?; + if let Instruction::BranchTable(index) = instruction { + let operand = data.operand128(*index); + let end = operand.start().checked_add(operand.size()).ok_or_else(invalid_site)?; + data.branch_table_targets + .get(operand.start() as usize..end as usize) + .ok_or_else(invalid_site)?; + } + } + PatchSite::TableEntry(index) => { + *data.branch_table_targets.get_mut(index).ok_or_else(invalid_site)? = target + } + PatchSite::ExceptionStart(index) => { + data.exception_handlers.get_mut(index).ok_or_else(invalid_site)?.start_ip = target + } + PatchSite::ExceptionEnd(index) => { + data.exception_handlers.get_mut(index).ok_or_else(invalid_site)?.end_ip = target + } + PatchSite::Catch(handler, catch) => { + let catch = data + .exception_handlers + .get_mut(handler) + .and_then(|handler| handler.catches.get_mut(catch)) + .ok_or_else(invalid_site)?; + match catch { + ExceptionCatch::Tag { landing_pad, .. } | ExceptionCatch::All { landing_pad, .. } => { + *landing_pad = target + } + } + } + } + } + for handler in &data.exception_handlers { + if handler.start_ip > handler.end_ip || handler.end_ip as usize > self.instructions.len() { + return Err(ParseError::Other("exception handler range out of bounds".into())); + } + } + Ok(self.instructions) + } + + fn patch_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) -> Result<()> { + // Target operands are allocated separately from deduplicated immutable + // operands. Relocation changes only their target field, not pool layout. + macro_rules! patch { + ($index:expr, $pool:ident) => {{ + let operand = data + .$pool + .get_mut($index.index()) + .ok_or_else(|| ParseError::Other("target operand out of bounds".into()))?; + *operand = operand.with_target(target); + }}; + } + use Instruction::*; + match instruction { + Jump(value) + | JumpIfZero32(value) + | JumpIfNonZero32(value) + | JumpIfZero64(value) + | JumpIfNonZero64(value) + | JumpIfRefNull(value) + | JumpIfRefNonNull(value) => *value = target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { + arg.target_ip = target + } + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => patch!(packed.index, operands64), + BrOnCast(index) | BrOnCastFail(index) => patch!(*index, operands64), + JumpCmpStackConst32(packed) => patch!(packed.index, operands64), + JumpCmpStackConst64(packed) => patch!(packed.index, operands128), + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => patch!(packed.index, operands128), + BinOpLocalConstJumpCmpLocal32(packed) => patch!(packed.index, operands128), + BinOpGlobalConstJump32(packed) => patch!(packed.index, operands128), + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => patch!(*index, operands128), + IncGlobalJump32(index) => patch!(*index, operands128), + IncLocalJumpCmpLocal32(packed) => patch!(packed.index, operands128), + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => patch!(packed.index, operands128), + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => patch!(packed.index, operands64), + BranchTable(index) => patch!(*index, operands128), + _ => return Err(ParseError::Other("unsupported instruction label patch".into())), + } + Ok(()) + } +} diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 4954056..2752d8b 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -30,10 +30,11 @@ pub(crate) mod log { } mod conversion; +mod emitter; mod error; mod macros; mod module; -mod optimize; +mod selection; mod validation; mod visit; @@ -62,8 +63,8 @@ pub struct ParserOptions { /// a module that violates runtime assumptions. pub validation: bool, - /// Whether to run the peephole rewrite optimizer. - pub optimize_rewrite: bool, + /// Whether to enable some of the optimizations during lowering, such as bounded instruction selection. + pub optimize: bool, /// Whether to deduplicate immutable function operands while parsing. pub deduplicate_operands: bool, @@ -76,17 +77,17 @@ pub struct ParserOptions { /// - `None`: auto-detect based on available parallelism /// - `Some(1)`: force single-threaded /// - `Some(n)`: use up to `n` workers - pub parser_threads: Option<usize>, + pub threads: Option<usize>, } impl Default for ParserOptions { fn default() -> Self { Self { validation: cfg!(feature = "validate"), - optimize_rewrite: true, - deduplicate_operands: false, + optimize: true, + deduplicate_operands: true, #[cfg(parallel_parser)] - parser_threads: None, + threads: None, } } } @@ -114,15 +115,15 @@ impl ParserOptions { self.validation } - /// Enable or disable the peephole rewrite optimizer. - pub const fn with_rewrite_optimization(mut self, enabled: bool) -> Self { - self.optimize_rewrite = enabled; + /// Enable or disable some of the optimizations during lowering, such as bounded instruction selection. + pub const fn with_optimize(mut self, enabled: bool) -> Self { + self.optimize = enabled; self } - /// Returns whether the peephole rewrite optimizer is enabled. - pub const fn optimize_rewrite(&self) -> bool { - self.optimize_rewrite + /// Returns whether some of the optimizations during lowering, such as bounded instruction selection, are enabled. + pub const fn optimize(&self) -> bool { + self.optimize } /// Enable or disable parse-time deduplication of immutable function operands. @@ -140,15 +141,15 @@ impl ParserOptions { /// Set the number of threads for parallel parsing. /// /// Requires the `parallel` feature to have any effect. - pub const fn with_parser_threads(mut self, threads: usize) -> Self { - self.parser_threads = Some(threads); + pub const fn with_threads(mut self, threads: usize) -> Self { + self.threads = Some(threads); self } #[cfg(parallel_parser)] /// Returns the configured parser thread count, or `None` for auto-detect. - pub const fn parser_threads(&self) -> Option<usize> { - self.parser_threads + pub const fn threads(&self) -> Option<usize> { + self.threads } } diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index f807c0f..fe1364b 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -1,4 +1,20 @@ pub(crate) mod visit { + // Rule families are chosen at the call site, not by matching the emitted opcode. + // Unary instruction operands are evaluated once and passed after family arguments. + macro_rules! emit_selected { + ($builder:ident, $inputs:expr, $outputs:expr, $op:ident($value:expr) [$family:ident($($arg:expr),* $(,)?)]) => {{ + let operand = $value; + $builder.emit_with($inputs, $outputs, tinywasm_types::Instruction::$op(operand), + |tail, data| crate::selection::$family(tail, data $(, $arg)*, operand)) + }}; + ($builder:ident, $inputs:expr, $outputs:expr, $op:ident [$family:ident($($arg:expr),* $(,)?)]) => { + $builder.emit_with($inputs, $outputs, tinywasm_types::Instruction::$op, + |tail, data| crate::selection::$family(tail, data $(, $arg)*)) + }; + ($builder:ident, $inputs:expr, $outputs:expr, $op:ident $(($($value:expr),*))?) => { + $builder.emit($inputs, $outputs, tinywasm_types::Instruction::$op $(($($value),*))?) + }; + } #[cfg(feature = "validate")] macro_rules! validate_then_visit { ($( @$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => {$( @@ -25,12 +41,14 @@ pub(crate) mod visit { )*}; } + // Optional `[family(args)]` selects rules alongside the visitor's stack effect + // and fallback opcode. Instructions without a family use plain emission. macro_rules! lowering_ops { () => {}; ($kind:ident $inputs:tt => $outputs:tt { - $($visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident),* $(,)? + $($visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident $([$family:ident($($rule_arg:expr),*)])?),* $(,)? } $($rest:tt)*) => { - $(lowering_ops!(@$kind $inputs => $outputs $visit $(($($arg: $ty),+))? => $instr);)* + $(lowering_ops!(@$kind $inputs => $outputs $visit $(($($arg: $ty),+))? => $instr $([$family($($rule_arg),*)])?);)* lowering_ops!($($rest)*); }; (effect $inputs:tt => $outputs:tt { $($visit:ident),* $(,)? } $($rest:tt)*) => { @@ -47,7 +65,7 @@ pub(crate) mod visit { $( 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!(@emit self fixed $inputs => $outputs $instr(ty)) } )* lowering_ops!($($rest)*); @@ -60,31 +78,31 @@ pub(crate) mod visit { }; (@fixed [$($input:ident),*] => [$($output:ident),*] - $visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident + $visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident $([$family:ident($($rule_arg:expr),*)])? ) => { fn $visit(&mut self $(, $($arg: $ty),+)?) -> Self::Output { lowering_ops!(@emit self fixed [$($input),*] => [$($output),*] - Instruction::$instr $(($($arg),+))?.into()) + $instr $(($($arg),+))? $([$family($($rule_arg),*)])?) } }; (@memory [$($input:ident),*] => [$($output:ident),*] - $visit:ident $(($lane:ident: $ty:ty))? => $instr:ident + $visit:ident $(($lane:ident: $ty:ty))? => $instr:ident $([$family:ident($($rule_arg:expr),*)])? ) => { fn $visit(&mut self, memarg: wasmparser::MemArg $(, $lane: $ty)?) -> Self::Output { let address = self.metadata.memory_size(memarg.memory)?; self.mark_memory(memarg.memory); - let memory_arg_idx = self.push_operand128(tinywasm_types::Operand128::< + let memory_arg_idx = self.push128(tinywasm_types::Operand128::< tinywasm_types::MemoryOperand, >::new(memarg.offset, memarg.memory))?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - lowering_ops!(@memory_instruction $instr memory_arg_idx $(, $lane)?)) + $instr(lowering_ops!(@memory_arg memory_arg_idx $(, $lane)?)) $([$family($($rule_arg),*)])?) } }; - (@memory_instruction $instr:ident $memory_arg_idx:ident) => { - Instruction::$instr($memory_arg_idx) + (@memory_arg $memory_arg_idx:ident) => { + $memory_arg_idx }; - (@memory_instruction $instr:ident $memory_arg_idx:ident, $lane:ident) => { - Instruction::$instr(tinywasm_types::MemoryLaneArg { memory_arg_idx: $memory_arg_idx, lane: $lane }) + (@memory_arg $memory_arg_idx:ident, $lane:ident) => { + tinywasm_types::MemoryLaneArg { memory_arg_idx: $memory_arg_idx, lane: $lane } }; (@global $inputs:tt => $outputs:tt $($operator:tt)*) => { lowering_ops!(@resolved global_size $inputs => $outputs $($operator)*); @@ -93,13 +111,13 @@ pub(crate) mod visit { lowering_ops!(@memory_index_impl $inputs => $outputs $($operator)*); }; (@memory_index_impl [$($input:ident),*] => [$($output:ident),*] - $visit:ident($index:ident: $ty:ty) => $instr:ident + $visit:ident($index:ident: $ty:ty) => $instr:ident $([$family:ident($($rule_arg:expr),*)])? ) => { fn $visit(&mut self, $index: $ty) -> Self::Output { let address = self.metadata.memory_size($index)?; self.mark_memory($index); lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - Instruction::$instr($index).into()) + $instr($index) $([$family($($rule_arg),*)])?) } }; (@table $inputs:tt => $outputs:tt $($operator:tt)*) => { @@ -111,7 +129,7 @@ pub(crate) mod visit { fn $visit(&mut self, $type_index: $type_ty $(, $arg: $arg_ty)*) -> Self::Output { let size = self.metadata.array_field($type_index)?; lowering_ops!(@emit self address(size) [$($input),*] => [$($output),*] - Instruction::$instr($type_index $(, $arg)*).into()) + $instr($type_index $(, $arg)*)) } }; (@resolved $resolver:ident [$($input:ident),*] => [$($output:ident),*] @@ -120,7 +138,7 @@ pub(crate) mod visit { fn $visit(&mut self, $index: $ty) -> Self::Output { let address = self.metadata.$resolver($index)?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - Instruction::$instr($index).into()) + $instr($index)) } }; (@resolved $resolver:ident [$($input:ident),*] => [$($output:ident),*] @@ -129,7 +147,7 @@ pub(crate) mod visit { fn $visit(&mut self, $arg: $arg_ty, $index: $index_ty) -> Self::Output { let address = self.metadata.$resolver($index)?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - Instruction::$instr($arg, $index).into()) + $instr($arg, $index)) } }; (@effect [$($input:ident),*] => [$($output:ident),*] $visit:ident) => { @@ -140,22 +158,26 @@ pub(crate) mod visit { (@terminating [$($input:ident),*] => [$($output:ident),*] $visit:ident => $instr:ident) => { fn $visit(&mut self) -> Self::Output { self.mark_unreachable(); - lowering_ops!(@emit self fixed [$($input),*] => [$($output),*] Instruction::$instr) + self.emit_boundary( + &[$(lowering_ops!(@size $input)),*], + &[$(lowering_ops!(@size $output)),*], + Instruction::$instr, + ) } }; - (@emit $self:ident fixed [$($input:ident),*] => [$($output:ident),*] $instruction:expr) => { - $self.emit( + (@emit $self:ident fixed [$($input:ident),*] => [$($output:ident),*] $($instruction:tt)+) => { + emit_selected!($self, &[$(lowering_ops!(@size $input)),*], &[$(lowering_ops!(@size $output)),*], - $instruction, + $($instruction)+ ) }; - (@emit $self:ident address($address:ident) [$($input:ident),*] => [$($output:ident),*] $instruction:expr) => { - $self.emit( + (@emit $self:ident address($address:ident) [$($input:ident),*] => [$($output:ident),*] $($instruction:tt)+) => { + emit_selected!($self, &[$(lowering_ops!(@size $input, $address)),*], &[$(lowering_ops!(@size $output, $address)),*], - $instruction, + $($instruction)+ ) }; @@ -189,68 +211,7 @@ pub(crate) mod visit { }; } - pub(crate) use {impl_visit_operator, lowering_ops}; + pub(crate) use {emit_selected, impl_visit_operator, lowering_ops}; #[cfg(feature = "validate")] pub(crate) use {validate_then_visit, validate_then_visit_simd}; } - -pub(crate) mod optimize { - macro_rules! replace { - ($instructions:ident, $read:ident, $consumed:expr => [$($out:expr),+ $(,)?]) => {{ - const { - assert!($consumed >= 1 && $consumed <= 3); - assert!([$(stringify!($out)),+].len() <= $consumed + 1); - } - let replacements = [$($out),+]; - let start = $read - $consumed; - $instructions[start..start + replacements.len()].copy_from_slice(&replacements); - $instructions.truncate(start + replacements.len()); - #[allow(unused_assignments)] - { $read = $instructions.len() - 1; } - }}; - ($instructions:ident, $read:ident, $consumed:expr => $out:expr) => { - replace!($instructions, $read, $consumed => [$out]); - }; - ($instructions:ident, *$read:ident, $consumed:expr => [$($out:expr),+ $(,)?]) => {{ - const { - assert!($consumed >= 1 && $consumed <= 3); - assert!([$(stringify!($out)),+].len() <= $consumed + 1); - } - let replacements = [$($out),+]; - let start = *$read - $consumed; - $instructions[start..start + replacements.len()].copy_from_slice(&replacements); - $instructions.truncate(start + replacements.len()); - *$read = $instructions.len() - 1; - }}; - ($instructions:ident, *$read:ident, $consumed:expr => $out:expr) => { - replace!($instructions, *$read, $consumed => [$out]) - }; - } - - macro_rules! rewrite { - ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => [$($out:expr),+ $(,)?]) => { - rewrite!($instructions, $read, [$($pattern),+] $(if ($($guard)+))? => { - replace!($instructions, $read, [$(stringify!($pattern)),+].len() => [$($out),+]); - }) - }; - ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => $body:block $(,)?) => {{ - const CONSUMED: usize = [$(stringify!($pattern)),+].len(); - if $read >= $instructions.block_start + CONSUMED { - let previous: [Instruction; CONSUMED] = $instructions[$read - CONSUMED..$read].try_into().unwrap(); - if let [$($pattern),+] = previous $( - && $($guard)+ - )? { - $body - continue; - } - } - }}; - ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => $out:expr $(,)?) => { - rewrite!($instructions, $read, [$($pattern),+] $(if ($($guard)+))? => { - replace!($instructions, $read, [$(stringify!($pattern)),+].len() => $out); - }) - }; - } - - pub(crate) use {replace, rewrite}; -} diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 4cd4406..03c725c 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -2,44 +2,21 @@ use crate::log::debug; #[cfg(parallel_parser)] use crate::validation::{FuncToValidate, ValidatorResources}; use crate::validation::{FuncValidatorAllocations, Validator}; -use crate::{ParseError, ParserOptions, Result, conversion::*, optimize}; +use crate::{ParseError, ParserOptions, Result, conversion::*}; use alloc::{boxed::Box, format, string::ToString, vec::Vec}; use core::marker::PhantomData; use core::ops::Range; use tinywasm_types::*; use wasmparser::{OperatorsReaderAllocations, Payload}; +/// Final bytecode and metadata produced by streaming function lowering. pub(crate) struct FunctionCode { pub instructions: Vec<Instruction>, - pub data: crate::visit::FunctionDataBuilder, - pub locals: ValueCounts, - pub uses_local_memory: bool, -} - -pub(crate) struct OptimizedFunctionCode { - pub instructions: Vec<Instruction>, pub data: WasmFunctionData, pub locals: ValueCounts, pub uses_local_memory: bool, } -pub(crate) fn optimize_function_code( - mut code: FunctionCode, - options: &ParserOptions, - function_results: ValueCounts, - self_func_addr: u32, -) -> Result<OptimizedFunctionCode> { - let optimized = - optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; - let data = code.data.finish(); - Ok(OptimizedFunctionCode { - instructions: optimized.instructions, - data, - locals: code.locals, - uses_local_memory: code.uses_local_memory, - }) -} - #[derive(Default)] pub(crate) struct ModuleReader<'a> { func_validator_allocations: Option<FuncValidatorAllocations>, @@ -56,7 +33,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) code_type_addrs: Box<[u32]>, code_results: Box<[ValueCounts]>, pub(crate) exports: Shared<[Export]>, - pub(crate) code: Vec<OptimizedFunctionCode>, + pub(crate) code: Vec<FunctionCode>, pub(crate) globals: Box<[Global]>, pub(crate) tables: Box<[TableDefinition]>, pub(crate) memory_types: Box<[MemoryType]>, @@ -400,17 +377,21 @@ impl<'a> ModuleReader<'a> { .code_type_addrs .get(ordinal) .ok_or_else(|| ParseError::Other("code entry has no function signature".into()))?; + let context = FunctionLoweringContext { + ty_idx, + self_func_addr: self + .imported_func_count + .checked_add(ordinal) + .and_then(|idx| u32::try_from(idx).ok()) + .ok_or_else(|| ParseError::Other("function index is too large".into()))?, + function_results: self.code_results[ordinal], + }; let metadata = self.translation_metadata(); let (code, func_validator_allocs, operators_reader_allocs) = - convert_module_code(function, func_validator, operators_reader_allocs, metadata, ty_idx, options)?; + convert_module_code(function, func_validator, operators_reader_allocs, metadata, context, options)?; - self.code.push(optimize_function_code( - code, - options, - self.code_results[self.code.len()], - (self.imported_func_count + self.code.len()) as u32, - )?); + self.code.push(code); self.func_validator_allocations = func_validator_allocs; self.operators_reader_allocations = Some(operators_reader_allocs); diff --git a/crates/parser/src/optimize/mod.rs b/crates/parser/src/optimize/mod.rs deleted file mode 100644 index 09501f9..0000000 --- a/crates/parser/src/optimize/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -mod rewrite; -mod targets; - -pub(crate) use rewrite::optimize_instructions; diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs deleted file mode 100644 index 366a094..0000000 --- a/crates/parser/src/optimize/rewrite.rs +++ /dev/null @@ -1,1500 +0,0 @@ -use super::targets::{finalize, resolve_jump_target, set_rewrite_target, target_boundaries}; -use crate::macros::optimize::{replace, rewrite}; -use crate::visit::FunctionDataBuilder as WasmFunctionData; -use crate::{ParserOptions, Result}; -use alloc::vec::Vec; -use core::ops::{Deref, DerefMut}; -use tinywasm_types::{ - BinOp, BinOp128, CmpOp, CompactMemoryArg, CompactMemoryOperand, GlobalUpdateOperand, I32LocalArg, Instruction, - LocalTripleArg, LocalUpdateCmpOperand, LocalUpdateOperand, MemoryFillOperand, MemoryLocalArg, MemoryOperand, - Operand64, Operand64Idx, Operand128, Operand128Idx, PackedOp, TargetLocalArg, ValueCounts, -}; - -pub(crate) struct OptimizeResult { - pub(crate) instructions: Vec<Instruction>, -} - -struct CompactOutput { - instructions: Vec<Instruction>, - block_start: usize, -} - -impl Deref for CompactOutput { - type Target = Vec<Instruction>; - - fn deref(&self) -> &Self::Target { - &self.instructions - } -} - -impl DerefMut for CompactOutput { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.instructions - } -} - -pub(crate) fn optimize_instructions( - mut instructions: Vec<Instruction>, - function_data: &mut WasmFunctionData, - options: &ParserOptions, - function_results: ValueCounts, - self_func_addr: u32, -) -> Result<OptimizeResult> { - let boundaries = target_boundaries(&instructions, function_data)?; - let (rewritten, old_to_new) = if options.optimize_rewrite() { - let (instructions, map) = rewrite(instructions, function_data, &boundaries, function_results, self_func_addr)?; - (instructions, Some(map)) - } else { - (instructions, None) - }; - instructions = rewritten; - finalize(&mut instructions, function_data, old_to_new.as_deref())?; - Ok(OptimizeResult { instructions }) -} - -fn rewrite( - source: Vec<Instruction>, - data: &mut WasmFunctionData, - boundaries: &[bool], - function_results: ValueCounts, - self_func_addr: u32, -) -> Result<(Vec<Instruction>, Vec<u32>)> { - #![allow(unused_assignments)] - use Instruction::*; - - let return_instruction = match function_results { - ValueCounts { c32: 0, c64: 0, c128: 0 } => Some(ReturnVoid), - ValueCounts { c32: 1, c64: 0, c128: 0 } => Some(Return32), - ValueCounts { c32: 0, c64: 1, c128: 0 } => Some(Return64), - ValueCounts { c32: 0, c64: 0, c128: 1 } => Some(Return128), - _ => None, - }; - let mut output = CompactOutput { instructions: Vec::with_capacity(source.len()), block_start: 0 }; - let mut old_to_new = alloc::vec![0; source.len() + 1]; - let mut after_terminator = false; - - for (old_index, instruction) in source.iter().copied().enumerate() { - if boundaries[old_index] || after_terminator { - output.block_start = output.len(); - } - after_terminator = is_unconditional_terminator(instruction); - old_to_new[old_index] = output.len() as u32; - output.push(instruction); - let mut read = output.len() - 1; - - match output[read] { - LocalCopy32(a, b) | LocalCopy64(a, b) | LocalCopy128(a, b) if a == b => { - output.pop(); - } - Call(address) if address == self_func_addr => output[read] = CallSelf, - ReturnCall(address) if address == self_func_addr => output[read] = ReturnCallSelf, - Return if let Some(specialized) = return_instruction => output[read] = specialized, - raw @ (I32Add | I32Mul | I32And | I32Or | I32Xor) => { - let op = int_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if rewrite_scalar_const32(&mut output, &mut read, data, op, true)? { - continue; - } - if op == BinOp::IAdd { - rewrite!(output, read, [Const32(value)] => AddConst32(value)); - rewrite!(output, read, [I32Add] => I32Add3); - if read > output.block_start - && let BinOpStackLocal32(BinOp::IAdd, local) = output[read - 1] - { - output.truncate(read - 1); - output.extend([LocalGet32(local), I32Add3]); - read = output.len() - 1; - } - } else { - rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); - } - } - raw @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { - let op = int_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { - continue; - } - if rewrite_sign_extend32(&mut output, &mut read, data, op) { - continue; - } - rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); - } - raw @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { - let op = int_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); - if rewrite_scalar_const64(&mut output, &mut read, data, op, true)? { - continue; - } - if op == BinOp::IAdd { - rewrite!(output, read, [Const64(index)] => AddConst64(index)); - rewrite!(output, read, [I64Add] => I64Add3); - } else { - rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); - } - } - raw @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { - let op = int_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); - if rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { - continue; - } - if rewrite_sign_extend64(&mut output, &mut read, data, op) { - continue; - } - rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); - } - raw if cmp_op(raw).is_some() => { - let op = cmp_op(raw).unwrap(); - rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => CmpLocalLocal32(op, a, b)); - rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => CmpLocalLocal64(op, a, b)); - } - raw @ (F32Add | F32Mul | F32Min | F32Max) => { - let op = float_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if !rewrite_scalar_const32(&mut output, &mut read, data, op, true)? { - rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); - } - } - raw @ (F32Sub | F32Div | F32Copysign) => { - let op = float_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if !rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { - rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); - } - } - raw @ (F64Add | F64Mul | F64Min | F64Max) => { - let op = float_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - if !rewrite_scalar_const64(&mut output, &mut read, data, op, true)? { - rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); - } - } - raw @ (F64Sub | F64Div | F64Copysign) => { - let op = float_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - if !rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { - rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); - } - } - raw @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul | V128AndNot) => { - let op = bin_op_128(raw).unwrap(); - rewrite!(output, read, [LocalGet128(local)] => - BinOpStackLocal128(op, local) - ); - rewrite_vector_binop(&mut output, &mut read, data, op, raw != V128AndNot)?; - } - I32Store(index) | F32Store(index) => rewrite_store32(&mut output, &mut read, data, index)?, - I64Store(index) | F64Store(index) => rewrite_store64(&mut output, &mut read, data, index)?, - V128Store(index) => { - if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { - rewrite!(output, read, - [LocalGet32(addr), LocalGet128(value)] if - (let (Ok(addr), Ok(value)) = (u8::try_from(addr), u8::try_from(value))) => - StoreLocalLocal128(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value }) - ); - } - } - I32Load(index) | F32Load(index) => { - if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { - rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if - (let Ok(local) = u8::try_from(local)) => - LoadLocal32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) - ); - } - } - I64Load(index) | F64Load(index) => { - if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { - rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if - (let Ok(local) = u8::try_from(local)) => - LoadLocal64(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) - ); - } - } - raw @ (I32Load8S(index) | I32Load8U(index) | I32Load16S(index) | I32Load16U(index)) => { - if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { - rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if - (let Ok(local) = u8::try_from(local)) => match raw { - I32Load8S(_) => LoadLocal8S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), - I32Load8U(_) => LoadLocal8U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), - I32Load16S(_) => LoadLocal16S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), - I32Load16U(_) => LoadLocal16U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), - _ => unreachable!(), - } - ); - } - } - MemoryFill(memory) => rewrite!(output, read, [Const32(value), Const32(size)] => { - let index = data.push_operand128(Operand128::<MemoryFillOperand>::new(memory, value as u8, size))?; - replace!(output, read, 2 => MemoryFillConst(index)); - }), - GlobalGet32(dst) => rewrite!(output, read, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), - GlobalGet64(dst) => rewrite!(output, read, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), - GlobalGet128(dst) => rewrite!(output, read, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), - LocalGet32(dst) => rewrite!(output, read, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), - LocalGet64(dst) => rewrite!(output, read, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), - LocalGet128(dst) => rewrite!(output, read, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), - LocalSet32(dst) => rewrite_local_set32(&mut output, &mut read, data, dst)?, - LocalSet64(dst) => rewrite_local_set64(&mut output, &mut read, data, dst)?, - LocalSet128(dst) => rewrite_local_set128(&mut output, &mut read, data, dst)?, - LocalTee32(dst) => rewrite_local_tee32(&mut output, &mut read, data, dst)?, - LocalTee64(dst) => rewrite_local_tee64(&mut output, &mut read, data, dst)?, - LocalTee128(dst) => rewrite_local_tee128(&mut output, &mut read, data, dst)?, - Drop32 => { - rewrite!(output, read, [LocalTee32(local)] => LocalSet32(local)); - rewrite!(output, read, [BinOpStackLocalTee32(op, local, dst)] => BinOpStackLocalSet32(op, local, dst)); - rewrite!(output, read, [AddLocalLocalTee32(arg)] => AddLocalLocalSet32(arg)); - rewrite!(output, read, [BinOpLocalLocalTee32(packed)] => BinOpLocalLocalSet32(packed)); - rewrite!(output, read, [BinOpLocalConstTee32(packed)] => BinOpLocalConstSet32(packed)); - } - Drop64 => { - rewrite!(output, read, [LocalTee64(local)] => LocalSet64(local)); - rewrite!(output, read, [BinOpLocalLocalTee64(packed)] => BinOpLocalLocalSet64(packed)); - rewrite!(output, read, [BinOpLocalConstTee64(packed)] => BinOpLocalConstSet64(packed)); - } - Drop128 => { - rewrite!(output, read, [LocalTee128(local)] => LocalSet128(local)); - rewrite!(output, read, [BinOpLocalLocalTee128(packed)] => BinOpLocalLocalSet128(packed)); - rewrite!(output, read, [BinOpLocalConstTee128(packed)] => BinOpLocalConstSet128(packed)); - } - Jump(target) => rewrite_jump(&source, &mut output, read, data, old_index as u32, target)?, - JumpIfZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, true)?, - JumpIfNonZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, false)?, - JumpIfZero64(target) => { - rewrite!(output, read, [LocalGet64(local)] => - JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) - ); - } - JumpIfNonZero64(target) => { - rewrite!(output, read, [LocalGet64(local)] => - JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) - ); - } - JumpCmpStackConst32(_) - | JumpCmpStackConst64(_) - | JumpCmpLocalConst32(_) - | JumpCmpLocalConst64(_) - | JumpCmpLocalLocal32(_) - | JumpCmpLocalLocal64(_) - | JumpIfLocalZero32(_) - | JumpIfLocalNonZero32(_) - | JumpIfLocalZero64(_) - | JumpIfLocalNonZero64(_) => {} - _ => {} - } - } - for instruction in &mut output.instructions { - match *instruction { - Instruction::Const64(index) => { - let value = data.operand64(index).value(); - if value == i64::from(value as i32) { - *instruction = Instruction::Const64Imm(value as i32); - } - } - Instruction::Const128(index) => { - if let Ok(value) = u32::try_from(u128::from_le_bytes(data.operand128(index).value())) { - *instruction = Instruction::Const128Imm(value); - } - } - _ => {} - } - } - let end = old_to_new.len() - 1; - old_to_new[end] = output.len() as u32; - Ok((output.instructions, old_to_new)) -} - -fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i32)> { - match instruction { - Instruction::AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)), - Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), - Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), - Instruction::AndLocalConst32(arg) => Some((BinOp::IAnd, arg.local, arg.value)), - Instruction::ShrULocalConst32(arg) => Some((BinOp::IShrU, arg.local, arg.value)), - Instruction::BinOpLocalConst32(packed) => { - let value = data.operand64(packed.index); - Some((packed.op, value.a(), value.b() as i32)) - } - _ => None, - } -} - -fn local_const64(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i64)> { - let Instruction::BinOpLocalConst64(packed) = instruction else { return None }; - let value = data.operand128(packed.index); - Some((packed.op, value.a(), value.b() as i64)) -} - -fn local_const128( - data: &WasmFunctionData, - instruction: Instruction, -) -> Option<(BinOp128, u16, Operand128Idx<[u8; 16]>)> { - let Instruction::BinOpLocalConst128(packed) = instruction else { return None }; - let value = data.operand64(packed.index); - Some((packed.op, value.a(), value.b())) -} - -fn compact_memory_arg( - data: &mut WasmFunctionData, - index: Operand128Idx<MemoryOperand>, -) -> Result<Option<Operand64Idx<CompactMemoryOperand>>> { - let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) else { return Ok(None) }; - Ok(Some(data.push_operand64(Operand64::from(arg))?)) -} - -fn rewrite_scalar_const32( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - op: BinOp, - commutative: bool, -) -> Result<bool> { - if *read < output.block_start + 2 { - return Ok(false); - } - let previous = &output[*read - 2..*read]; - let replacement = match previous { - [Instruction::LocalGet32(local), Instruction::Const32(value)] => { - let arg = I32LocalArg { value: *value, local: *local }; - match op { - BinOp::IAdd => Instruction::AddLocalConst32(arg), - BinOp::ISub => Instruction::SubLocalConst32(arg), - BinOp::IMul => Instruction::MulLocalConst32(arg), - BinOp::IAnd => Instruction::AndLocalConst32(arg), - BinOp::IShrU => Instruction::ShrULocalConst32(arg), - _ => Instruction::BinOpLocalConst32(PackedOp::new( - op, - data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, - )), - } - } - [Instruction::GlobalGet32(global), Instruction::Const32(value)] => Instruction::BinOpGlobalConst32( - PackedOp::new(op, data.push_operand64(Operand64::<(u32, u32)>::new(*global, *value as u32))?), - ), - [Instruction::Const32(value), Instruction::LocalGet32(local)] if commutative => { - let arg = I32LocalArg { value: *value, local: *local }; - match op { - BinOp::IAdd => Instruction::AddLocalConst32(arg), - BinOp::IMul => Instruction::MulLocalConst32(arg), - BinOp::IAnd => Instruction::AndLocalConst32(arg), - _ => Instruction::BinOpLocalConst32(PackedOp::new( - op, - data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, - )), - } - } - [Instruction::Const32(value), Instruction::GlobalGet32(global)] if commutative => { - Instruction::BinOpGlobalConst32(PackedOp::new( - op, - data.push_operand64(Operand64::<(u32, u32)>::new(*global, *value as u32))?, - )) - } - _ => return Ok(false), - }; - replace!(output, *read, 2 => replacement); - Ok(true) -} - -fn stack_const32(op: BinOp, value: i32) -> Instruction { - match op { - BinOp::IAnd => Instruction::AndConst32(value), - BinOp::IXor => Instruction::XorConst32(value), - BinOp::IShrU => Instruction::ShrUConst32(value), - _ => Instruction::BinOpStackConst32(op, value), - } -} - -fn rewrite_scalar_const64( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - op: BinOp, - commutative: bool, -) -> Result<bool> { - if *read < output.block_start + 2 { - return Ok(false); - } - let previous = [output[*read - 2], output[*read - 1]]; - let replacement = match previous { - [Instruction::LocalGet64(local), Instruction::Const64(index)] => Instruction::BinOpLocalConst64(PackedOp::new( - op, - data.push_operand128(Operand128::<(u16, u64)>::new(local, data.operand64(index).value() as u64))?, - )), - [Instruction::GlobalGet64(global), Instruction::Const64(index)] => { - Instruction::BinOpGlobalConst64(PackedOp::new( - op, - data.push_operand128(Operand128::<(u32, u64)>::new(global, data.operand64(index).value() as u64))?, - )) - } - [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => { - Instruction::BinOpLocalConst64(PackedOp::new( - op, - data.push_operand128(Operand128::<(u16, u64)>::new(local, data.operand64(index).value() as u64))?, - )) - } - [Instruction::Const64(index), Instruction::GlobalGet64(global)] if commutative => { - Instruction::BinOpGlobalConst64(PackedOp::new( - op, - data.push_operand128(Operand128::<(u32, u64)>::new(global, data.operand64(index).value() as u64))?, - )) - } - _ => return Ok(false), - }; - replace!(output, *read, 2 => replacement); - Ok(true) -} - -fn rewrite_sign_extend32(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { - if op != BinOp::IShrS || *read < output.block_start + 2 { - return false; - } - if let Some((BinOp::IShl, local, shift)) = local_const32(data, output[*read - 2]) - && let Instruction::Const32(right) = output[*read - 1] - && shift == right - && matches!(shift, 16 | 24) - { - output.truncate(*read - 2); - output.extend([ - Instruction::LocalGet32(local), - if shift == 24 { Instruction::I32Extend8S } else { Instruction::I32Extend16S }, - ]); - *read = output.len() - 1; - return true; - } - false -} - -fn rewrite_sign_extend64(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { - if op != BinOp::IShrS || *read < output.block_start + 2 { - return false; - } - if let Some((BinOp::IShl, local, shift)) = local_const64(data, output[*read - 2]) - && let Instruction::Const64(index) = output[*read - 1] - && shift == data.operand64(index).value() - { - let instruction = match shift { - 56 => Instruction::I64Extend8S, - 48 => Instruction::I64Extend16S, - 32 => Instruction::I64Extend32S, - _ => return false, - }; - output.truncate(*read - 2); - output.extend([Instruction::LocalGet64(local), instruction]); - *read = output.len() - 1; - return true; - } - false -} - -fn rewrite_vector_binop( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - op: BinOp128, - commutative: bool, -) -> Result<()> { - if *read >= output.block_start + 2 { - let previous = [output[*read - 2], output[*read - 1]]; - let replacement = match previous { - [Instruction::LocalGet128(a), Instruction::LocalGet128(b)] => Instruction::BinOpLocalLocal128(op, a, b), - [Instruction::LocalGet128(local), Instruction::Const128(value)] => Instruction::BinOpLocalConst128( - PackedOp::new(op, data.push_operand64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?), - ), - [Instruction::GlobalGet128(global), Instruction::Const128(value)] => { - Instruction::BinOpGlobalConst128(PackedOp::new( - op, - data.push_operand64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?, - )) - } - [Instruction::Const128(value), Instruction::LocalGet128(local)] if commutative => { - Instruction::BinOpLocalConst128(PackedOp::new( - op, - data.push_operand64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?, - )) - } - [Instruction::Const128(value), Instruction::GlobalGet128(global)] if commutative => { - Instruction::BinOpGlobalConst128(PackedOp::new( - op, - data.push_operand64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?, - )) - } - _ => return Ok(()), - }; - replace!(output, *read, 2 => replacement); - } - Ok(()) -} - -fn rewrite_store32( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - index: Operand128Idx<MemoryOperand>, -) -> Result<()> { - let compact_arg = CompactMemoryArg::try_from(data.operand128(index)).ok(); - if *read > output.block_start && output[*read - 1] == Instruction::Select32 { - replace!(output, *read, 1 => Instruction::SelectStore32(index)); - return Ok(()); - } - if *read >= output.block_start + 3 { - let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; - if let [ - Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), - Instruction::LoadLocal32(arg), - Instruction::AddConst32(1), - ] = previous - && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) } - && addr == u16::from(arg.local1) - { - replace!(output, *read, 3 => Instruction::IncMemoryLocal32(arg)); - return Ok(()); - } - } - if *read >= output.block_start + 2 { - let previous = [output[*read - 2], output[*read - 1]]; - match previous { - [Instruction::F32Mul, Instruction::F32Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => - { - replace!(output, *read, 2 => Instruction::FMaStoreF32(arg)); - } - [Instruction::BinOpStackLocal32(BinOp::FMul, local), Instruction::F32Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => - { - replace!(output, *read, 2 => [Instruction::LocalGet32(local), Instruction::FMaStoreF32(arg)]); - } - [Instruction::LocalGet32(addr), Instruction::LocalGet32(value)] - if let (Ok(addr), Ok(value), Some(memory_arg)) = - (u8::try_from(addr), u8::try_from(value), compact_arg) => - { - let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; - replace!(output, *read, 2 => Instruction::StoreLocalLocal32(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_store64( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - index: Operand128Idx<MemoryOperand>, -) -> Result<()> { - let compact_arg = CompactMemoryArg::try_from(data.operand128(index)).ok(); - if *read > output.block_start && output[*read - 1] == Instruction::Select64 { - replace!(output, *read, 1 => Instruction::SelectStore64(index)); - return Ok(()); - } - if *read >= output.block_start + 3 { - let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; - if let [ - Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), - Instruction::LoadLocal64(arg), - Instruction::AddConst64(one), - ] = previous - && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) } - && addr == u16::from(arg.local1) - && data.operand64(one).value() == 1 - { - replace!(output, *read, 3 => Instruction::IncMemoryLocal64(arg)); - return Ok(()); - } - } - if *read >= output.block_start + 2 { - match [output[*read - 2], output[*read - 1]] { - [Instruction::F64Mul, Instruction::F64Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => - { - replace!(output, *read, 2 => Instruction::FMaStoreF64(arg)); - } - [Instruction::LocalGet32(addr), Instruction::LocalGet64(value)] - if let (Ok(addr), Ok(value), Some(memory_arg)) = - (u8::try_from(addr), u8::try_from(value), compact_arg) => - { - let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; - replace!(output, *read, 2 => Instruction::StoreLocalLocal64(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); - } - _ => {} - } - } - Ok(()) -} - -macro_rules! local_const_set { - ($data:expr, 32, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = $data.push_operand64(Operand64::<(u16, u16, u32)>::new($src, $dst, $value as u32))?; - if $tee { - Instruction::BinOpLocalConstTee32(PackedOp::new($op, index)) - } else { - Instruction::BinOpLocalConstSet32(PackedOp::new($op, index)) - } - }}; - ($data:expr, 64, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = $data.push_operand128(Operand128::<(u16, u16, u64)>::new($src, $dst, $value as u64))?; - if $tee { - Instruction::BinOpLocalConstTee64(PackedOp::new($op, index)) - } else { - Instruction::BinOpLocalConstSet64(PackedOp::new($op, index)) - } - }}; - ($data:expr, 128, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = $data.push_operand64(Operand64::<(u16, u16, Operand128Idx<[u8; 16]>)>::new($src, $dst, $value))?; - if $tee { - Instruction::BinOpLocalConstTee128(PackedOp::new($op, index)) - } else { - Instruction::BinOpLocalConstSet128(PackedOp::new($op, index)) - } - }}; -} - -fn rewrite_local_set32( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 2 { - match [output[*read - 2], output[*read - 1]] { - [Instruction::I32Mul, Instruction::BinOpStackLocal32(BinOp::IAdd, acc)] if acc == dst => { - replace!(output, *read, 2 => Instruction::MulAccLocal32(dst)); - return Ok(()); - } - [Instruction::F32Mul, Instruction::BinOpStackLocal32(BinOp::FAdd, acc)] if acc == dst => { - replace!(output, *read, 2 => Instruction::FMulAccLocal32(dst)); - return Ok(()); - } - _ => {} - } - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::LocalGet32(src) if src == dst => { - output.truncate(*read - 1); - *read = output.len(); - return Ok(()); - } - Instruction::LocalGet32(src) => replace!(output, *read, 1 => Instruction::LocalCopy32(src, dst)), - Instruction::Const32(value) => { - replace!(output, *read, 1 => Instruction::SetLocalConst32(I32LocalArg { value, local: dst })) - } - Instruction::BinOpLocalLocal32(op, left, right) => { - let replacement = if op == BinOp::IAdd { - Instruction::AddLocalLocalSet32(LocalTripleArg { left, right, dst }) - } else { - Instruction::BinOpLocalLocalSet32(PackedOp::new( - op, - data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?, - )) - }; - replace!(output, *read, 1 => replacement); - } - instruction if let Some((op, src, value)) = local_const32(data, instruction) => { - if src == dst - && let Some(delta) = op.inc_delta(value) - { - replace!(output, *read, 1 => Instruction::IncLocal32(I32LocalArg { value: delta, local: dst })); - } else { - let replacement = local_const_set!(data, 32, op, src, dst, value, false); - replace!(output, *read, 1 => replacement); - } - } - Instruction::BinOpStackLocal32(op, local) => { - replace!(output, *read, 1 => Instruction::BinOpStackLocalSet32(op, local, dst)); - } - Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalSet32(arg)); - } - Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalSet8S32(arg)); - } - Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalSet8U32(arg)); - } - Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalSet16S32(arg)); - } - Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalSet16U32(arg)); - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_local_set64( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 3 { - match [output[*read - 3], output[*read - 2], output[*read - 1]] { - [Instruction::I64Mul, Instruction::LocalGet64(acc), Instruction::I64Add] if acc == dst => { - replace!(output, *read, 3 => Instruction::MulAccLocal64(dst)); - return Ok(()); - } - [Instruction::F64Mul, Instruction::LocalGet64(acc), Instruction::F64Add] if acc == dst => { - replace!(output, *read, 3 => Instruction::FMulAccLocal64(dst)); - return Ok(()); - } - _ => {} - } - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::LocalGet64(src) if src == dst => { - output.truncate(*read - 1); - *read = output.len(); - return Ok(()); - } - Instruction::LocalGet64(src) => replace!(output, *read, 1 => Instruction::LocalCopy64(src, dst)), - Instruction::Const64(index) => { - replace!(output, *read, 1 => Instruction::SetLocalConst64(PackedOp::new(dst, index))); - } - Instruction::BinOpLocalLocal64(op, left, right) => { - let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; - replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet64(PackedOp::new(op, index))); - } - instruction if let Some((op, src, value)) = local_const64(data, instruction) => { - if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) { - let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() }; - let index = data.push_operand64(Operand64::<i64>::new(delta))?; - replace!(output, *read, 1 => Instruction::IncLocal64(PackedOp::new(dst, index))); - } else { - let replacement = local_const_set!(data, 64, op, src, dst, value, false); - replace!(output, *read, 1 => replacement); - } - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_local_set128( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 2 - && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] - && let (Ok(local), Ok(dst), Ok(memory_arg)) = - (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index))) - { - let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; - replace!(output, *read, 2 => Instruction::LoadLocalSet128(MemoryLocalArg { - memory_arg_idx, - local1: local, - local2: dst, - })); - return Ok(()); - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::LocalGet128(src) if src == dst => { - output.truncate(*read - 1); - *read = output.len(); - return Ok(()); - } - Instruction::LocalGet128(src) => replace!(output, *read, 1 => Instruction::LocalCopy128(src, dst)), - Instruction::Const128(value) => { - replace!(output, *read, 1 => Instruction::SetLocalConst128(PackedOp::new(dst, value))) - } - Instruction::BinOpLocalLocal128(op, left, right) => { - let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; - replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet128(PackedOp::new(op, index))); - } - instruction if let Some((op, src, value)) = local_const128(data, instruction) => { - let replacement = local_const_set!(data, 128, op, src, dst, value, false); - replace!(output, *read, 1 => replacement); - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_local_tee32( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 2 { - match [output[*read - 2], output[*read - 1]] { - [Instruction::Const32(value), Instruction::I32And] => { - replace!(output, *read, 2 => Instruction::AndConstTee32(I32LocalArg { value, local: dst })); - return Ok(()); - } - [Instruction::Const32(value), Instruction::I32Sub] => { - replace!(output, *read, 2 => Instruction::SubConstTee32(I32LocalArg { value, local: dst })); - return Ok(()); - } - _ => {} - } - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::AndConst32(value) => { - replace!(output, *read, 1 => Instruction::AndConstTee32(I32LocalArg { value, local: dst })); - } - Instruction::BinOpStackConst32(BinOp::ISub, value) => { - replace!(output, *read, 1 => Instruction::SubConstTee32(I32LocalArg { value, local: dst })); - } - Instruction::LocalGet32(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet32(src)), - Instruction::LocalGet32(src) => { - replace!(output, *read, 1 => [Instruction::LocalCopy32(src, dst), Instruction::LocalGet32(dst)]); - } - Instruction::BinOpLocalLocal32(op, left, right) => { - let replacement = if op == BinOp::IAdd { - Instruction::AddLocalLocalTee32(LocalTripleArg { left, right, dst }) - } else { - Instruction::BinOpLocalLocalTee32(PackedOp::new( - op, - data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?, - )) - }; - replace!(output, *read, 1 => replacement); - } - instruction if let Some((op, src, value)) = local_const32(data, instruction) => { - let replacement = local_const_set!(data, 32, op, src, dst, value, true); - replace!(output, *read, 1 => replacement); - } - Instruction::BinOpStackLocal32(op, local) => { - replace!(output, *read, 1 => Instruction::BinOpStackLocalTee32(op, local, dst)); - } - Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalTee32(arg)); - } - Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalTee8S32(arg)); - } - Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalTee8U32(arg)); - } - Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalTee16S32(arg)); - } - Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalTee16U32(arg)); - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_local_tee64( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 2 { - match [output[*read - 2], output[*read - 1]] { - [Instruction::Const64(value), Instruction::I64And] => { - replace!(output, *read, 2 => Instruction::AndConstTee64(PackedOp::new(dst, value))); - return Ok(()); - } - [Instruction::Const64(value), Instruction::I64Sub] => { - replace!(output, *read, 2 => Instruction::SubConstTee64(PackedOp::new(dst, value))); - return Ok(()); - } - _ => {} - } - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::BinOpStackConst64(packed) if packed.op == BinOp::IAnd => { - replace!(output, *read, 1 => Instruction::AndConstTee64(PackedOp::new(dst, packed.index))); - } - Instruction::BinOpStackConst64(packed) if packed.op == BinOp::ISub => { - replace!(output, *read, 1 => Instruction::SubConstTee64(PackedOp::new(dst, packed.index))); - } - Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)), - Instruction::LocalGet64(src) => { - replace!(output, *read, 1 => [Instruction::LocalCopy64(src, dst), Instruction::LocalGet64(dst)]); - } - Instruction::BinOpLocalLocal64(op, left, right) => { - let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; - replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee64(PackedOp::new(op, index))); - } - instruction if let Some((op, src, value)) = local_const64(data, instruction) => { - let replacement = local_const_set!(data, 64, op, src, dst, value, true); - replace!(output, *read, 1 => replacement); - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_local_tee128( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 2 - && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] - && let (Ok(local), Ok(dst), Ok(memory_arg)) = - (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index))) - { - let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; - replace!(output, *read, 2 => Instruction::LoadLocalTee128(MemoryLocalArg { - memory_arg_idx, - local1: local, - local2: dst, - })); - return Ok(()); - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::LocalGet128(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet128(src)), - Instruction::LocalGet128(src) => { - replace!(output, *read, 1 => [Instruction::LocalCopy128(src, dst), Instruction::LocalGet128(dst)]); - } - Instruction::BinOpLocalLocal128(op, left, right) => { - let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; - replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee128(PackedOp::new(op, index))); - } - instruction if let Some((op, src, value)) = local_const128(data, instruction) => { - let replacement = local_const_set!(data, 128, op, src, dst, value, true); - replace!(output, *read, 1 => replacement); - } - _ => {} - } - } - Ok(()) -} - -fn int_bin_op(instruction: Instruction) -> Option<BinOp> { - Some(match instruction { - Instruction::I32Add | Instruction::I64Add => BinOp::IAdd, - Instruction::I32Sub | Instruction::I64Sub => BinOp::ISub, - Instruction::I32Mul | Instruction::I64Mul => BinOp::IMul, - Instruction::I32And | Instruction::I64And => BinOp::IAnd, - Instruction::I32Or | Instruction::I64Or => BinOp::IOr, - Instruction::I32Xor | Instruction::I64Xor => BinOp::IXor, - Instruction::I32Shl | Instruction::I64Shl => BinOp::IShl, - Instruction::I32ShrS | Instruction::I64ShrS => BinOp::IShrS, - Instruction::I32ShrU | Instruction::I64ShrU => BinOp::IShrU, - Instruction::I32Rotl | Instruction::I64Rotl => BinOp::IRotl, - Instruction::I32Rotr | Instruction::I64Rotr => BinOp::IRotr, - _ => return None, - }) -} - -fn float_bin_op(instruction: Instruction) -> Option<BinOp> { - Some(match instruction { - Instruction::F32Add | Instruction::F64Add => BinOp::FAdd, - Instruction::F32Sub | Instruction::F64Sub => BinOp::FSub, - Instruction::F32Mul | Instruction::F64Mul => BinOp::FMul, - Instruction::F32Div | Instruction::F64Div => BinOp::FDiv, - Instruction::F32Min | Instruction::F64Min => BinOp::FMin, - Instruction::F32Max | Instruction::F64Max => BinOp::FMax, - Instruction::F32Copysign | Instruction::F64Copysign => BinOp::FCopysign, - _ => return None, - }) -} - -fn cmp_op(instruction: Instruction) -> Option<CmpOp> { - Some(match instruction { - Instruction::I32Eq | Instruction::I64Eq => CmpOp::Eq, - Instruction::I32Ne | Instruction::I64Ne => CmpOp::Ne, - Instruction::I32LtS | Instruction::I64LtS => CmpOp::LtS, - Instruction::I32LtU | Instruction::I64LtU => CmpOp::LtU, - Instruction::I32GtS | Instruction::I64GtS => CmpOp::GtS, - Instruction::I32GtU | Instruction::I64GtU => CmpOp::GtU, - Instruction::I32LeS | Instruction::I64LeS => CmpOp::LeS, - Instruction::I32LeU | Instruction::I64LeU => CmpOp::LeU, - Instruction::I32GeS | Instruction::I64GeS => CmpOp::GeS, - Instruction::I32GeU | Instruction::I64GeU => CmpOp::GeU, - _ => return None, - }) -} - -fn bin_op_128(instruction: Instruction) -> Option<BinOp128> { - Some(match instruction { - Instruction::V128And => BinOp128::And, - Instruction::V128AndNot => BinOp128::AndNot, - Instruction::V128Or => BinOp128::Or, - Instruction::V128Xor => BinOp128::Xor, - Instruction::I64x2Add => BinOp128::I64x2Add, - Instruction::I64x2Mul => BinOp128::I64x2Mul, - _ => return None, - }) -} - -fn jump_cmp_local_local( - data: &mut WasmFunctionData, - target: u32, - left: u16, - right: u16, - op: CmpOp, - width64: bool, -) -> Result<Instruction> { - let index = data.push_target_operand64(Operand64::<(u32, u16, u16)>::new(target, left, right))?; - Ok(if width64 { - Instruction::JumpCmpLocalLocal64(PackedOp::new(op, index)) - } else { - Instruction::JumpCmpLocalLocal32(PackedOp::new(op, index)) - }) -} - -fn rewrite_jump( - source: &[Instruction], - output: &mut CompactOutput, - index: usize, - data: &mut WasmFunctionData, - old_index: u32, - target: u32, -) -> Result<()> { - let target = resolve_jump_target(source, data, target); - let exit = old_index + 1; - let body = target + 1; - if let Some(instruction) = source.get(target as usize).copied() { - match instruction { - Instruction::JumpCmpLocalLocal32(side) - if resolve_jump_target(source, data, data.operand64(side.index).a()) == exit && body > target => - { - let value = data.operand64(side.index); - output[index] = jump_cmp_local_local(data, body, value.b(), value.c(), side.op.inverse(), false)?; - return Ok(()); - } - Instruction::JumpCmpLocalLocal64(side) - if resolve_jump_target(source, data, data.operand64(side.index).a()) == exit && body > target => - { - let value = data.operand64(side.index); - output[index] = jump_cmp_local_local(data, body, value.b(), value.c(), side.op.inverse(), true)?; - return Ok(()); - } - _ => {} - } - } - if matches!(output[index], Instruction::Jump(_)) && target == exit { - output.truncate(index); - } else { - set_rewrite_target(&mut output[index], data, target)?; - } - Ok(()) -} - -fn jump_cmp_stack_local( - data: &mut WasmFunctionData, - target: u32, - local: u16, - op: CmpOp, - width64: bool, -) -> Result<Instruction> { - let index = data.push_target_operand64(Operand64::<(u32, u16)>::new(target, local))?; - Ok(if width64 { - Instruction::JumpCmpStackLocal64(PackedOp::new(op, index)) - } else { - Instruction::JumpCmpStackLocal32(PackedOp::new(op, index)) - }) -} - -fn jump_cmp_local_const32( - data: &mut WasmFunctionData, - target: u32, - local: u16, - value: i32, - op: CmpOp, -) -> Result<Instruction> { - if value == 0 { - return Ok(match op { - CmpOp::Eq => Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }), - CmpOp::Ne => Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }), - _ => Instruction::JumpCmpLocalConst32(PackedOp::new( - op, - data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, - )), - }); - } - Ok(Instruction::JumpCmpLocalConst32(PackedOp::new( - op, - data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, - ))) -} - -fn jump_cmp_local_const64( - data: &mut WasmFunctionData, - target: u32, - local: u16, - value: i32, - op: CmpOp, -) -> Result<Instruction> { - if value == 0 { - match op { - CmpOp::Eq => return Ok(Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local })), - CmpOp::Ne => return Ok(Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local })), - _ => {} - } - } - Ok(Instruction::JumpCmpLocalConst64(PackedOp::new( - op, - data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, - ))) -} - -fn jump_cmp_stack_const32(data: &mut WasmFunctionData, target: u32, value: i32, op: CmpOp) -> Result<Instruction> { - if value == 0 { - match op { - CmpOp::Eq => return Ok(Instruction::JumpIfZero32(target)), - CmpOp::Ne => return Ok(Instruction::JumpIfNonZero32(target)), - _ => {} - } - } - Ok(Instruction::JumpCmpStackConst32(PackedOp::new( - op, - data.push_target_operand64(Operand64::<(u32, i32)>::new(target, value))?, - ))) -} - -fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, op: CmpOp) -> Result<Instruction> { - if value == 0 { - match op { - CmpOp::Eq => return Ok(Instruction::JumpIfZero64(target)), - CmpOp::Ne => return Ok(Instruction::JumpIfNonZero64(target)), - _ => {} - } - } - Ok(Instruction::JumpCmpStackConst64(PackedOp::new( - op, - data.push_target_operand128(Operand128::<(u32, i64)>::new(target, value))?, - ))) -} - -fn update_jump( - data: &mut WasmFunctionData, - target: u32, - immediate: i32, - address: u32, - op: BinOp, - on_zero: bool, - global: bool, -) -> Result<Instruction> { - if let Some(delta) = op.inc_delta(immediate) { - Ok(if global { - Instruction::IncGlobalJump32( - data.push_target_operand128(Operand128::<GlobalUpdateOperand>::new(target, delta, address, on_zero))?, - ) - } else { - Instruction::IncLocalJump32(data.push_target_operand128(Operand128::<LocalUpdateOperand>::new( - target, - delta, - address as u16, - on_zero, - ))?) - }) - } else { - Ok(if global { - Instruction::BinOpGlobalConstJump32(PackedOp::new( - op, - data.push_target_operand128(Operand128::<GlobalUpdateOperand>::new( - target, immediate, address, on_zero, - ))?, - )) - } else { - Instruction::BinOpLocalConstJump32(PackedOp::new( - op, - data.push_target_operand128(Operand128::<LocalUpdateOperand>::new( - target, - immediate, - address as u16, - on_zero, - ))?, - )) - }) - } -} - -fn rewrite_conditional( - source: &[Instruction], - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - target: u32, - on_zero: bool, -) -> Result<()> { - let target = resolve_jump_target(source, data, target); - if *read > output.block_start - && let Instruction::BinOpLocalConstTee32(packed) = output[*read - 1] - { - let value = data.operand64(packed.index); - if value.a() == value.b() { - let replacement = - update_jump(data, target, value.c() as i32, u32::from(value.a()), packed.op, on_zero, false)?; - replace!(output, *read, 1 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 2 - && let [Instruction::BinOpGlobalConst32(packed), Instruction::GlobalTee32(dst)] = - [output[*read - 2], output[*read - 1]] - { - let value = data.operand64(packed.index); - if value.a() == dst { - let replacement = update_jump(data, target, value.b() as i32, dst, packed.op, on_zero, true)?; - replace!(output, *read, 2 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 3 - && let [Instruction::AddConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] = - [output[*read - 3], output[*read - 2], output[*read - 1]] - && local == cond - { - let replacement = - Instruction::IncStackTeeLocalJump32( - data.push_target_operand128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?, - ); - replace!(output, *read, 3 => replacement); - return Ok(()); - } - if *read >= output.block_start + 3 { - let update = match [output[*read - 3], output[*read - 2], output[*read - 1]] { - [Instruction::XorConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] - if local == cond => - { - Some((BinOp::IXor, value, local)) - } - [Instruction::ShrUConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] - if local == cond => - { - Some((BinOp::IShrU, value, local)) - } - [ - Instruction::BinOpStackConst32(op, value), - Instruction::LocalTee32(local), - Instruction::LocalGet32(cond), - ] if local == cond => Some((op, value, local)), - _ => None, - }; - if let Some((op, value, local)) = update { - let replacement = Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( - op, - data.push_target_operand128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?, - )); - replace!(output, *read, 3 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 2 { - let update = match [output[*read - 2], output[*read - 1]] { - [Instruction::AndConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { - Some((arg.local, arg.value, Some(BinOp::IAnd))) - } - [Instruction::SubConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { - Some((arg.local, arg.value.wrapping_neg(), None)) - } - _ => None, - }; - if let Some((local, value, op)) = update { - let replacement = if let Some(op) = op { - Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( - op, - data.push_target_operand128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?, - )) - } else { - Instruction::IncStackTeeLocalJump32( - data.push_target_operand128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?, - ) - }; - replace!(output, *read, 2 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 3 - && let [Instruction::BinOpLocalConstTee32(packed), Instruction::LocalGet32(right), raw_cmp] = - [output[*read - 3], output[*read - 2], output[*read - 1]] - && let Some(mut cmp) = cmp_op(raw_cmp) - { - let value = data.operand64(packed.index); - if value.a() == value.b() { - if on_zero { - cmp = cmp.inverse(); - } - let replacement = if let Some(delta) = packed.op.inc_delta(value.c() as i32) { - Instruction::IncLocalJumpCmpLocal32(PackedOp::new( - cmp, - data.push_target_operand128(Operand128::<LocalUpdateCmpOperand>::new( - target, - delta, - value.a(), - right, - ))?, - )) - } else { - Instruction::BinOpLocalConstJumpCmpLocal32(PackedOp::new( - (packed.op, cmp), - data.push_target_operand128(Operand128::<LocalUpdateCmpOperand>::new( - target, - value.c() as i32, - value.a(), - right, - ))?, - )) - }; - replace!(output, *read, 3 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 2 { - match [output[*read - 2], output[*read - 1]] { - [Instruction::LocalGet32(local), Instruction::I32Eqz] => { - replace!(output, *read, 2 => - if on_zero { - Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) - } else { - Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) - } - ); - return Ok(()); - } - [Instruction::LocalGet64(local), Instruction::I64Eqz] => { - replace!(output, *read, 2 => - if on_zero { - Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) - } else { - Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) - } - ); - return Ok(()); - } - [Instruction::CmpLocalLocal32(op, left, right), Instruction::I32Eqz] => { - let op = if on_zero { op } else { op.inverse() }; - let replacement = jump_cmp_local_local(data, target, left, right, op, false)?; - replace!(output, *read, 2 => replacement); - return Ok(()); - } - _ => {} - } - } - if *read > output.block_start { - let previous = output[*read - 1]; - let replacement = match previous { - Instruction::I32Eqz => { - Some(if on_zero { Instruction::JumpIfNonZero32(target) } else { Instruction::JumpIfZero32(target) }) - } - Instruction::I64Eqz => { - Some(if on_zero { Instruction::JumpIfNonZero64(target) } else { Instruction::JumpIfZero64(target) }) - } - Instruction::CmpLocalLocal32(op, left, right) => { - Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, false)?) - } - Instruction::CmpLocalLocal64(op, left, right) => { - Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, true)?) - } - Instruction::LocalGet32(local) => Some(if on_zero { - Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) - } else { - Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) - }), - Instruction::LocalGet64(local) => Some(if on_zero { - Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) - } else { - Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) - }), - _ => None, - }; - if let Some(replacement) = replacement { - replace!(output, *read, 1 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 3 { - let raw_cmp = output[*read - 1]; - if let Some(mut op) = cmp_op(raw_cmp) { - if on_zero { - op = op.inverse(); - } - let replacement = match [output[*read - 3], output[*read - 2]] { - [Instruction::LocalGet32(local), Instruction::Const32(value)] => { - Some(jump_cmp_local_const32(data, target, local, value, op)?) - } - [Instruction::LocalGet64(local), Instruction::Const64(index)] - if let Ok(value) = i32::try_from(data.operand64(index).value()) => - { - Some(jump_cmp_local_const64(data, target, local, value, op)?) - } - [Instruction::LocalGet32(left), Instruction::LocalGet32(right)] => { - Some(jump_cmp_local_local(data, target, left, right, op, false)?) - } - [Instruction::LocalGet64(left), Instruction::LocalGet64(right)] => { - Some(jump_cmp_local_local(data, target, left, right, op, true)?) - } - _ => None, - }; - if let Some(replacement) = replacement { - replace!(output, *read, 3 => replacement); - return Ok(()); - } - } - } - if *read >= output.block_start + 2 { - let raw_cmp = output[*read - 1]; - if let Some(mut op) = cmp_op(raw_cmp) { - if on_zero { - op = op.inverse(); - } - let replacement = match output[*read - 2] { - Instruction::LocalGet32(local) => Some(jump_cmp_stack_local(data, target, local, op, false)?), - Instruction::LocalGet64(local) => Some(jump_cmp_stack_local(data, target, local, op, true)?), - Instruction::Const32(value) => Some(jump_cmp_stack_const32(data, target, value, op)?), - Instruction::Const64(index) => { - Some(jump_cmp_stack_const64(data, target, data.operand64(index).value(), op)?) - } - _ => None, - }; - if let Some(replacement) = replacement { - replace!(output, *read, 2 => replacement); - return Ok(()); - } - } - } - Ok(()) -} - -fn is_unconditional_terminator(instruction: Instruction) -> bool { - matches!( - instruction, - Instruction::Unreachable - | Instruction::Jump(_) - | Instruction::BranchTable(_) - | Instruction::Return - | Instruction::ReturnVoid - | Instruction::Return32 - | Instruction::Return64 - | Instruction::Return128 - | Instruction::ReturnCall(_) - | Instruction::ReturnCallSelf - | Instruction::ReturnCallIndirect(_) - | Instruction::ReturnCallRef(_) - | Instruction::Throw(_) - | Instruction::ThrowRef - ) -} diff --git a/crates/parser/src/optimize/targets.rs b/crates/parser/src/optimize/targets.rs deleted file mode 100644 index c6b2252..0000000 --- a/crates/parser/src/optimize/targets.rs +++ /dev/null @@ -1,227 +0,0 @@ -use crate::visit::FunctionDataBuilder; -use crate::{ParseError, Result}; -use alloc::vec::Vec; -use tinywasm_types::{Instruction, PackedOp}; - -pub(super) fn resolve_jump_target(instructions: &[Instruction], data: &FunctionDataBuilder, target: u32) -> u32 { - let mut index = target as usize; - let mut steps = 0; - while let Some(instruction) = instructions.get(index) - && let Some(next) = instruction_target(data, *instruction) - && matches!(instruction, Instruction::Jump(_)) - && steps < instructions.len() - { - index = next as usize; - steps += 1; - } - index as u32 -} - -pub(super) fn set_rewrite_target( - instruction: &mut Instruction, - data: &mut FunctionDataBuilder, - target: u32, -) -> Result<()> { - macro_rules! rewrite_target { - ($slot:ident, operand64) => {{ data.push_target_operand64(data.operand64(*$slot).with_target(target))? }}; - ($slot:ident, operand128) => {{ data.push_target_operand128(data.operand128(*$slot).with_target(target))? }}; - ($slot:ident, packed64) => {{ PackedOp::new($slot.op, data.push_target_operand64(data.operand64($slot.index).with_target(target))?) }}; - ($slot:ident, packed128) => {{ PackedOp::new($slot.op, data.push_target_operand128(data.operand128($slot.index).with_target(target))?) }}; - } - - use Instruction::*; - match instruction { - JumpCmpStackLocal32(packed) => *packed = rewrite_target!(packed, packed64), - JumpCmpStackLocal64(packed) => *packed = rewrite_target!(packed, packed64), - BrOnCast(index) | BrOnCastFail(index) => *index = rewrite_target!(index, operand64), - JumpCmpStackConst32(packed) => *packed = rewrite_target!(packed, packed64), - JumpCmpStackConst64(packed) => *packed = rewrite_target!(packed, packed128), - BinOpStackConstTeeLocalJump32(packed) => *packed = rewrite_target!(packed, packed128), - BinOpLocalConstJump32(packed) => *packed = rewrite_target!(packed, packed128), - BinOpLocalConstJumpCmpLocal32(packed) => *packed = rewrite_target!(packed, packed128), - BinOpGlobalConstJump32(packed) => *packed = rewrite_target!(packed, packed128), - IncLocalJump32(index) => *index = rewrite_target!(index, operand128), - IncStackTeeLocalJump32(index) => *index = rewrite_target!(index, operand128), - IncGlobalJump32(index) => *index = rewrite_target!(index, operand128), - IncLocalJumpCmpLocal32(packed) => *packed = rewrite_target!(packed, packed128), - JumpCmpLocalConst32(packed) => *packed = rewrite_target!(packed, packed128), - JumpCmpLocalConst64(packed) => *packed = rewrite_target!(packed, packed128), - JumpCmpLocalLocal32(packed) => *packed = rewrite_target!(packed, packed64), - JumpCmpLocalLocal64(packed) => *packed = rewrite_target!(packed, packed64), - BranchTable(index) => *index = rewrite_target!(index, operand128), - _ => set_target(instruction, data, target), - } - - Ok(()) -} - -fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> Option<u32> { - use Instruction::*; - Some(match instruction { - Jump(target) - | JumpIfZero32(target) - | JumpIfNonZero32(target) - | JumpIfZero64(target) - | JumpIfNonZero64(target) - | JumpIfRefNull(target) - | JumpIfRefNonNull(target) => target, - JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { - arg.target_ip - } - JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand64(packed.index).target(), - BrOnCast(index) | BrOnCastFail(index) => data.operand64(index).target(), - JumpCmpStackConst32(packed) => data.operand64(packed.index).target(), - JumpCmpStackConst64(packed) => data.operand128(packed.index).target(), - BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand128(packed.index).target(), - BinOpLocalConstJumpCmpLocal32(packed) => data.operand128(packed.index).target(), - BinOpGlobalConstJump32(packed) => data.operand128(packed.index).target(), - IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand128(index).target(), - IncGlobalJump32(index) => data.operand128(index).target(), - IncLocalJumpCmpLocal32(packed) => data.operand128(packed.index).target(), - JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand128(packed.index).target(), - JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand64(packed.index).target(), - BranchTable(index) => data.operand128(index).target(), - _ => return None, - }) -} - -fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) { - macro_rules! set_target { - ($index:expr, operand64) => {{ data.set_operand64($index, data.operand64($index).with_target(target)) }}; - ($index:expr, operand128) => {{ data.set_operand128($index, data.operand128($index).with_target(target)) }}; - ($packed:expr, packed64) => {{ data.set_operand64($packed.index, data.operand64($packed.index).with_target(target)) }}; - ($packed:expr, packed128) => {{ data.set_operand128($packed.index, data.operand128($packed.index).with_target(target)) }}; - } - - use Instruction::*; - match instruction { - Jump(value) - | JumpIfZero32(value) - | JumpIfNonZero32(value) - | JumpIfZero64(value) - | JumpIfNonZero64(value) - | JumpIfRefNull(value) - | JumpIfRefNonNull(value) => *value = target, - - JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { - arg.target_ip = target - } - JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_target!(*packed, packed64), - BrOnCast(index) | BrOnCastFail(index) => set_target!(*index, operand64), - JumpCmpStackConst32(packed) => set_target!(*packed, packed64), - JumpCmpStackConst64(packed) => set_target!(*packed, packed128), - BinOpLocalConstJump32(packed) => set_target!(*packed, packed128), - BinOpStackConstTeeLocalJump32(packed) => set_target!(*packed, packed128), - BinOpLocalConstJumpCmpLocal32(packed) => set_target!(*packed, packed128), - BinOpGlobalConstJump32(packed) => set_target!(*packed, packed128), - IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_target!(*index, operand128), - IncGlobalJump32(index) => set_target!(*index, operand128), - IncLocalJumpCmpLocal32(packed) => set_target!(*packed, packed128), - JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_target!(*packed, packed128), - JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_target!(*packed, packed64), - BranchTable(index) => set_target!(*index, operand128), - _ => {} - } -} - -fn branch_table_range(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(u32, u32)> { - let Instruction::BranchTable(index) = instruction else { return None }; - let operand = data.operand128(index); - Some((operand.start(), operand.size())) -} - -pub(super) fn target_boundaries(instructions: &[Instruction], data: &FunctionDataBuilder) -> Result<Vec<bool>> { - let mut boundaries = alloc::vec![false; instructions.len() + 1]; - for handler in &data.exception_handlers { - for target in [handler.start_ip, handler.end_ip] { - *boundaries.get_mut(target as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) - })? = true; - } - for catch in &handler.catches { - let target = catch.landing_pad(); - *boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))? = - true; - } - } - for &instruction in instructions { - if let Some(target) = instruction_target(data, instruction) { - *boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? = true; - } - if let Some((start, count)) = branch_table_range(data, instruction) { - let end = - start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; - let targets = data - .branch_table_targets - .get(start as usize..end as usize) - .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; - for &target in targets { - *boundaries.get_mut(target as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("branch table target out of bounds: {target}")) - })? = true; - } - } - } - Ok(boundaries) -} - -fn remap_target(target: u32, old_to_new: Option<&[u32]>, len: u32) -> Result<u32> { - let target = if let Some(map) = old_to_new { - *map.get(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? - } else { - target - }; - if target >= len { - return Err(ParseError::Other(alloc::format!("instruction target out of bounds: {target}"))); - } - Ok(target) -} - -pub(super) fn finalize( - instructions: &mut [Instruction], - data: &mut FunctionDataBuilder, - old_to_new: Option<&[u32]>, -) -> Result<()> { - let len = instructions.len() as u32; - for handler in &mut data.exception_handlers { - if let Some(map) = old_to_new { - handler.start_ip = *map - .get(handler.start_ip as usize) - .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; - handler.end_ip = *map - .get(handler.end_ip as usize) - .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; - for catch in &mut handler.catches { - let landing_pad = match catch { - tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } - | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, - }; - *landing_pad = remap_target(*landing_pad, Some(map), len)?; - } - } - if handler.start_ip > handler.end_ip || handler.end_ip > len { - return Err(ParseError::Other("exception handler range out of bounds".into())); - } - } - for target in &mut data.branch_table_targets { - *target = remap_target(*target, old_to_new, len)?; - } - for instruction in instructions { - if let Some(target) = instruction_target(data, *instruction) { - set_target(instruction, data, remap_target(target, old_to_new, len)?); - } - if let Some((start, count)) = branch_table_range(data, *instruction) { - let end = - start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; - data.branch_table_targets - .get(start as usize..end as usize) - .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; - } - } - Ok(()) -} diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs index 4ad16cf..69dbac9 100644 --- a/crates/parser/src/parallel.rs +++ b/crates/parser/src/parallel.rs @@ -1,4 +1,4 @@ -use crate::module::{OptimizedFunctionCode, optimize_function_code}; +use crate::module::FunctionCode; use crate::validation::{FuncToValidate, FuncValidatorAllocations, ValidatorResources}; use crate::{ParseError, ParserOptions, Result, conversion}; use alloc::vec::Vec; @@ -48,10 +48,8 @@ pub(crate) fn should_use_parallel(options: &ParserOptions, num_functions: usize, } fn worker_count(options: &ParserOptions, num_functions: usize) -> usize { - let requested = options - .parser_threads() - .unwrap_or_else(|| std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1)) - .max(1); + let requested = + options.threads().unwrap_or_else(|| std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1)).max(1); requested.min(MAX_WORKERS).min(num_functions.div_ceil(MIN_FUNCTIONS_PER_WORKER)).max(1) } @@ -62,7 +60,15 @@ fn process_function_job( imported_func_count: usize, validator_allocs: Option<FuncValidatorAllocations>, reader_allocs: OperatorsReaderAllocations, -) -> Result<(OptimizedFunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> { +) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> { + let context = conversion::FunctionLoweringContext { + ty_idx: job.ty_idx, + self_func_addr: imported_func_count + .checked_add(job.ordinal) + .and_then(|idx| u32::try_from(idx).ok()) + .ok_or_else(|| ParseError::Other("function index is too large".into()))?, + function_results: job.results, + }; #[cfg(feature = "validate")] let validator = job.func_to_validate.map(|func| func.into_validator(validator_allocs.unwrap_or_default())); #[cfg(not(feature = "validate"))] @@ -72,17 +78,15 @@ fn process_function_job( }; let (code, validator_allocs, reader_allocs) = match job.body { FunctionBodyInput::Borrowed(func) => { - conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx, options)? + conversion::convert_module_code(func, validator, reader_allocs, metadata, context, options)? } FunctionBodyInput::Owned(body) => { let reader = wasmparser::BinaryReader::new(&body.section_bytes[body.body_range], body.body_offset); let func = wasmparser::FunctionBody::new(reader); - conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx, options)? + conversion::convert_module_code(func, validator, reader_allocs, metadata, context, options)? } }; - let code = optimize_function_code(code, options, job.results, (imported_func_count + job.ordinal) as u32)?; - Ok((code, validator_allocs, reader_allocs)) } @@ -91,7 +95,7 @@ fn process_chunk<'a>( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, -) -> Result<Vec<OptimizedFunctionCode>> { +) -> Result<Vec<FunctionCode>> { let mut validator_allocs = None; let mut reader_allocs = OperatorsReaderAllocations::default(); let jobs = jobs.into_iter(); @@ -113,7 +117,7 @@ pub(crate) fn process_pending( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, -) -> Result<Vec<OptimizedFunctionCode>> { +) -> Result<Vec<FunctionCode>> { let num_workers = worker_count(options, pending.len()); if num_workers == 1 { return process_chunk(pending, metadata, options, imported_func_count); diff --git a/crates/parser/src/selection.rs b/crates/parser/src/selection.rs new file mode 100644 index 0000000..2d96b66 --- /dev/null +++ b/crates/parser/src/selection.rs @@ -0,0 +1,314 @@ +//! Ordered rule families selected by lowering, not by the incoming opcode. +//! Replacements are contiguous, non-growing suffixes and are not dispatched again. +//! Small literals stay inline until a selected encoding needs a pooled operand. + +mod encoding; +use crate::{Result, emitter::PendingTail, visit::FunctionDataBuilder}; +use encoding::*; +use tinywasm_types::{Instruction, Instruction::*, *}; + +// Patterns include the incoming instruction. First match wins, including identity +// replacements. Parenthesized guards support expressions and let chains. +macro_rules! families { + ($($name:ident($tail:ident, $data:ident $(, $arg:ident: $ty:ty)*) { + $([$($pattern:pat),+ $(,)?] $(if ($($guard:tt)+))? => $replacement:expr),+ $(,)? + })*) => {$( + #[doc = concat!("Applies the ordered `", stringify!($name), "` rules to the pending suffix.")] + #[inline] + pub(crate) fn $name($tail: &mut PendingTail<'_>, $data: &mut FunctionDataBuilder $(, $arg: $ty)*) -> Result<()> { + let _ = &$data; + $( + if let Some([$($pattern),+]) = $tail.suffix::<{ [$(stringify!($pattern)),+].len() }>() + $( && $($guard)+ )? + { + $tail.replace::<{ [$(stringify!($pattern)),+].len() }, _>($replacement); + return Ok(()); + } + )+ + Ok(()) + } + )*}; +} + +#[rustfmt::skip] +families! { + integer32(tail, data, op: BinOp, commutative: bool) { + [LocalGet32(a), LocalGet32(b), _] => [BinOpLocalLocal32(op, a, b)], + [GlobalGet32(global), _] => [BinOpStackGlobal32(op, global)], + [LocalGet32(local), _] => [BinOpStackLocal32(op, local)], + // Both producers only read locals, and the outer integer operation commutes. + [LocalGet32(local), producer, _] if (commutative && local_const32(data, producer).is_some()) => [producer, BinOpStackLocal32(op, local)], + [LocalGet32(local), Const32(value), _] => [encode_local_const32(data, op, local, value)?], + [GlobalGet32(global), Const32(value), _] => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))], + [Const32(value), LocalGet32(local), _] if (commutative) => [encode_local_const32(data, op, local, value)?], + [Const32(value), GlobalGet32(global), _] if (commutative) => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))], + [Const32(value), I32Add] => [AddConst32(value)], + [I32Add, I32Add] => [I32Add3], + [BinOpStackLocal32(BinOp::IAdd, local), I32Add] => [LocalGet32(local), I32Add3], + [left, Const32(right), _] if (op == BinOp::IShrS + && let Some((BinOp::IShl, local, shift)) = local_const32(data, left) + && shift == right && matches!(shift, 16 | 24)) => + [LocalGet32(local), if shift == 24 { I32Extend8S } else { I32Extend16S }], + [Const32(value), _] if (op != BinOp::IAdd) => [stack_const32(op, value)], + } + integer64(tail, data, op: BinOp, commutative: bool) { + [LocalGet64(a), LocalGet64(b), _] => [BinOpLocalLocal64(op, a, b)], + [GlobalGet64(global), _] => [BinOpStackGlobal64(op, global)], + [LocalGet64(local), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))], + [GlobalGet64(global), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))], + [constant, LocalGet64(local), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))], + [constant, GlobalGet64(global), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))], + [constant @ (Const64(_) | Const64Imm(_)), I64Add] => [AddConst64(pool64(data, constant)?)], + [I64Add, I64Add] => [I64Add3], + [left, constant, _] if (op == BinOp::IShrS + && let Some((BinOp::IShl, local, shift)) = local_const64(data, left) + && Some(shift) == const64(data, constant) && matches!(shift, 56 | 48 | 32)) => + [LocalGet64(local), match shift { 56 => I64Extend8S, 48 => I64Extend16S, _ => I64Extend32S }], + [constant @ (Const64(_) | Const64Imm(_)), _] if (op != BinOp::IAdd) => [BinOpStackConst64(PackedOp::new(op, pool64(data, constant)?))], + } + compare(tail, data, op: CmpOp) { + [LocalGet32(a), LocalGet32(b), _] => [CmpLocalLocal32(op, a, b)], + [LocalGet64(a), LocalGet64(b), _] => [CmpLocalLocal64(op, a, b)], + } + extend_i32(tail, data, signed: bool) { + [Const32(value), _] => [{ + let value = if signed { i64::from(value) } else { i64::from(value as u32) }; + match i32::try_from(value) { + Ok(value) => Const64Imm(value), + Err(_) => Const64(data.push64(Operand64::<i64>::new(value))?), + } + }], + } + float32(tail, data, op: BinOp, commutative: bool) { + [LocalGet32(a), LocalGet32(b), _] => [BinOpLocalLocal32(op, a, b)], + [LocalGet32(local), _] => [BinOpStackLocal32(op, local)], + [LocalGet32(local), Const32(value), _] => [encode_local_const32(data, op, local, value)?], + [GlobalGet32(global), Const32(value), _] => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))], + [Const32(value), LocalGet32(local), _] if (commutative) => [encode_local_const32(data, op, local, value)?], + [Const32(value), GlobalGet32(global), _] if (commutative) => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))], + [Const32(value), _] => [stack_const32(op, value)], + } + float64(tail, data, op: BinOp, commutative: bool) { + [LocalGet64(a), LocalGet64(b), _] => [BinOpLocalLocal64(op, a, b)], + [LocalGet64(local), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))], + [GlobalGet64(global), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))], + [constant, LocalGet64(local), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))], + [constant, GlobalGet64(global), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))], + [constant @ (Const64(_) | Const64Imm(_)), _] => [BinOpStackConst64(PackedOp::new(op, pool64(data, constant)?))], + } + vector(tail, data, op: BinOp128, commutative: bool) { + // Stack/local deliberately shadows local/local and reversed local constants. + [LocalGet128(local), _] => [BinOpStackLocal128(op, local)], + [LocalGet128(a), LocalGet128(b), _] => [BinOpLocalLocal128(op, a, b)], + [LocalGet128(local), constant @ (Const128(_) | Const128Imm(_)), _] => [{ + let value = pool128(data, constant)?; + BinOpLocalConst128(PackedOp::new(op, data.push64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?)) + }], + [GlobalGet128(global), constant @ (Const128(_) | Const128Imm(_)), _] => [{ + let value = pool128(data, constant)?; + BinOpGlobalConst128(PackedOp::new(op, data.push64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?)) + }], + [constant @ (Const128(_) | Const128Imm(_)), LocalGet128(local), _] if (commutative) => [{ + let value = pool128(data, constant)?; + BinOpLocalConst128(PackedOp::new(op, data.push64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?)) + }], + [constant @ (Const128(_) | Const128Imm(_)), GlobalGet128(global), _] if (commutative) => [{ + let value = pool128(data, constant)?; + BinOpGlobalConst128(PackedOp::new(op, data.push64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?)) + }], + } + store32(tail, data, index: Operand128Idx<MemoryOperand>) { + [Select32, _] => [SelectStore32(index)], + [LocalGet32(addr) | LocalGet64(addr), LoadLocal32(arg), AddConst32(1), _] + if (CompactMemoryArg::try_from(data.operand128(index)).ok().map(Operand64::from) + == Some(data.operand64(arg.memory_arg_idx)) && addr == u16::from(arg.local1)) => [IncMemoryLocal32(arg)], + [F32Mul, F32Add, _] if (let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => [FMaStoreF32(arg)], + [BinOpStackLocal32(BinOp::FMul, local), F32Add, _] + if (let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => [LocalGet32(local), FMaStoreF32(arg)], + [LocalGet32(addr), LocalGet32(value), _] + if (let (Ok(addr), Ok(value), Ok(arg)) = (u8::try_from(addr), u8::try_from(value), + CompactMemoryArg::try_from(data.operand128(index)))) => [StoreLocalLocal32(MemoryLocalArg { + memory_arg_idx: data.push64(Operand64::from(arg))?, local1: addr, local2: value })], + } + store64(tail, data, index: Operand128Idx<MemoryOperand>) { + [Select64, _] => [SelectStore64(index)], + [LocalGet32(addr) | LocalGet64(addr), LoadLocal64(arg), AddConst64(one), _] + if (CompactMemoryArg::try_from(data.operand128(index)).ok().map(Operand64::from) + == Some(data.operand64(arg.memory_arg_idx)) && addr == u16::from(arg.local1) + && data.operand64(one).value() == 1) => [IncMemoryLocal64(arg)], + [F64Mul, F64Add, _] if (let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => [FMaStoreF64(arg)], + [LocalGet32(addr), LocalGet64(value), _] + if (let (Ok(addr), Ok(value), Ok(arg)) = (u8::try_from(addr), u8::try_from(value), + CompactMemoryArg::try_from(data.operand128(index)))) => [StoreLocalLocal64(MemoryLocalArg { + memory_arg_idx: data.push64(Operand64::from(arg))?, local1: addr, local2: value })], + } + memory_fill(tail, data, memory: u32) { + [Const32(value), Const32(size), _] => [MemoryFillConst(data.push128(Operand128::<MemoryFillOperand>::new(memory, value as u8, size))?)], + } + global_get32(tail, data, dst: u32) { [GlobalSet32(src), _] if (src == dst) => [GlobalTee32(src)] } + global_get64(tail, data, dst: u32) { [GlobalSet64(src), _] if (src == dst) => [GlobalTee64(src)] } + global_get128(tail, data, dst: u32) { [GlobalSet128(src), _] if (src == dst) => [GlobalTee128(src)] } + local_get32(tail, data, dst: u16) { [LocalSet32(src), _] if (src == dst) => [LocalTee32(src)] } + local_get64(tail, data, dst: u16) { [LocalSet64(src), _] if (src == dst) => [LocalTee64(src)] } + local_get128(tail, data, dst: u16) { [LocalSet128(src), _] if (src == dst) => [LocalTee128(src)] } + local_set32(tail, data, dst: u16) { + [I32Mul, BinOpStackLocal32(BinOp::IAdd, acc), _] if (acc == dst) => [MulAccLocal32(dst)], + [F32Mul, BinOpStackLocal32(BinOp::FAdd, acc), _] if (acc == dst) => [FMulAccLocal32(dst)], + [LocalGet32(src), _] if (src == dst) => [], + [LocalGet32(src), _] => [LocalCopy32(src, dst)], + [Const32(value), _] => [SetLocalConst32(I32LocalArg { value, local: dst })], + [BinOpLocalLocal32(BinOp::IAdd, left, right), _] => [AddLocalLocalSet32(LocalTripleArg { left, right, dst })], + [BinOpLocalLocal32(op, left, right), _] => [BinOpLocalLocalSet32(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const32(data, instruction)) => [{ + if src == dst && let Some(delta) = op.inc_delta(value) { + IncLocal32(I32LocalArg { value: delta, local: dst }) + } else { local_const_set32(data, op, src, dst, value, false)? } + }], + [BinOpStackLocal32(op, local), _] => [BinOpStackLocalSet32(op, local, dst)], + [LoadLocal32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal8S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet8S32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal8U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet8U32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal16S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet16S32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal16U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet16U32(MemoryLocalArg { local2: dst, ..arg })], + } + local_set64(tail, data, dst: u16) { + [I64Mul, LocalGet64(acc), I64Add, _] if (acc == dst) => [MulAccLocal64(dst)], + [F64Mul, LocalGet64(acc), F64Add, _] if (acc == dst) => [FMulAccLocal64(dst)], + [LocalGet64(src), _] if (src == dst) => [], + [LocalGet64(src), _] => [LocalCopy64(src, dst)], + [constant @ (Const64(_) | Const64Imm(_)), _] => [SetLocalConst64(PackedOp::new(dst, pool64(data, constant)?))], + [BinOpLocalLocal64(op, left, right), _] => [BinOpLocalLocalSet64(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const64(data, instruction)) => [{ + if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) { + let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() }; + IncLocal64(PackedOp::new(dst, data.push64(Operand64::<i64>::new(delta))?)) + } else { local_const_set64(data, op, src, dst, value, false)? } + }], + } + local_set128(tail, data, dst: u16) { + [LocalGet32(local), V128Load(index), _] if (let (Ok(local), Ok(dst), Ok(arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index)))) => + [LoadLocalSet128(MemoryLocalArg { memory_arg_idx: data.push64(Operand64::from(arg))?, local1: local, local2: dst })], + [LocalGet128(src), _] if (src == dst) => [], + [LocalGet128(src), _] => [LocalCopy128(src, dst)], + [constant @ (Const128(_) | Const128Imm(_)), _] => [SetLocalConst128(PackedOp::new(dst, pool128(data, constant)?))], + [BinOpLocalLocal128(op, left, right), _] => [BinOpLocalLocalSet128(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const128(data, instruction)) => + [local_const_set128(data, op, src, dst, value, false)?], + } + local_tee32(tail, data, dst: u16) { + [Const32(value), I32And, _] => [AndConstTee32(I32LocalArg { value, local: dst })], + [Const32(value), I32Sub, _] => [SubConstTee32(I32LocalArg { value, local: dst })], + [AndConst32(value), _] => [AndConstTee32(I32LocalArg { value, local: dst })], + [BinOpStackConst32(BinOp::ISub, value), _] => [SubConstTee32(I32LocalArg { value, local: dst })], + [LocalGet32(src), _] if (src == dst) => [LocalGet32(src)], + [LocalGet32(src), _] => [LocalCopy32(src, dst), LocalGet32(dst)], + [BinOpLocalLocal32(BinOp::IAdd, left, right), _] => [AddLocalLocalTee32(LocalTripleArg { left, right, dst })], + [BinOpLocalLocal32(op, left, right), _] => [BinOpLocalLocalTee32(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const32(data, instruction)) => + [local_const_set32(data, op, src, dst, value, true)?], + [BinOpStackLocal32(op, local), _] => [BinOpStackLocalTee32(op, local, dst)], + [LoadLocal32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal8S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee8S32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal8U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee8U32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal16S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee16S32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal16U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee16U32(MemoryLocalArg { local2: dst, ..arg })], + } + local_tee64(tail, data, dst: u16) { + [constant @ (Const64(_) | Const64Imm(_)), I64And, _] => [AndConstTee64(PackedOp::new(dst, pool64(data, constant)?))], + [constant @ (Const64(_) | Const64Imm(_)), I64Sub, _] => [SubConstTee64(PackedOp::new(dst, pool64(data, constant)?))], + [BinOpStackConst64(packed), _] if (packed.op == BinOp::IAnd) => [AndConstTee64(PackedOp::new(dst, packed.index))], + [BinOpStackConst64(packed), _] if (packed.op == BinOp::ISub) => [SubConstTee64(PackedOp::new(dst, packed.index))], + [LocalGet64(src), _] if (src == dst) => [LocalGet64(src)], + [LocalGet64(src), _] => [LocalCopy64(src, dst), LocalGet64(dst)], + [BinOpLocalLocal64(op, left, right), _] => [BinOpLocalLocalTee64(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const64(data, instruction)) => [local_const_set64(data, op, src, dst, value, true)?], + } + local_tee128(tail, data, dst: u16) { + [LocalGet32(local), V128Load(index), _] if (let (Ok(local), Ok(dst), Ok(arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index)))) => + [LoadLocalTee128(MemoryLocalArg { memory_arg_idx: data.push64(Operand64::from(arg))?, local1: local, local2: dst })], + [LocalGet128(src), _] if (src == dst) => [LocalGet128(src)], + [LocalGet128(src), _] => [LocalCopy128(src, dst), LocalGet128(dst)], + [BinOpLocalLocal128(op, left, right), _] => [BinOpLocalLocalTee128(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const128(data, instruction)) => [local_const_set128(data, op, src, dst, value, true)?], + } + drop32(tail, data) { + [LocalTee32(local), _] => [LocalSet32(local)], + [BinOpStackLocalTee32(op, local, dst), _] => [BinOpStackLocalSet32(op, local, dst)], + [AddLocalLocalTee32(arg), _] => [AddLocalLocalSet32(arg)], + [BinOpLocalLocalTee32(packed), _] => [BinOpLocalLocalSet32(packed)], + [BinOpLocalConstTee32(packed), _] => [BinOpLocalConstSet32(packed)], + } + drop64(tail, data) { + [LocalTee64(local), _] => [LocalSet64(local)], + [BinOpLocalLocalTee64(packed), _] => [BinOpLocalLocalSet64(packed)], + [BinOpLocalConstTee64(packed), _] => [BinOpLocalConstSet64(packed)], + } + drop128(tail, data) { + [LocalTee128(local), _] => [LocalSet128(local)], + [BinOpLocalLocalTee128(packed), _] => [BinOpLocalLocalSet128(packed)], + [BinOpLocalConstTee128(packed), _] => [BinOpLocalConstSet128(packed)], + } + load(tail, data, instruction: impl FnOnce(MemoryLocalArg) -> Instruction, index: Operand128Idx<MemoryOperand>) { + [LocalGet32(local) | LocalGet64(local), _] + if (let Ok(local) = u8::try_from(local) + && let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => + [instruction(MemoryLocalArg { + memory_arg_idx: data.push64(Operand64::from(arg))?, local1: local, local2: 0 })], + } + store128(tail, data, index: Operand128Idx<MemoryOperand>) { + [LocalGet32(addr), LocalGet128(value), _] + if (let (Ok(addr), Ok(value)) = (u8::try_from(addr), u8::try_from(value)) + && let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => + [StoreLocalLocal128(MemoryLocalArg { + memory_arg_idx: data.push64(Operand64::from(arg))?, local1: addr, local2: value })], + } + conditional(tail, data, on_zero: bool, target: u32) { + [BinOpLocalConstTee32(packed), _] if (data.operand64(packed.index).a() == data.operand64(packed.index).b()) => [{ + let value = data.operand64(packed.index); + update_jump(data, target, value.c() as i32, u32::from(value.a()), packed.op, on_zero, false)? + }], + [BinOpGlobalConst32(packed), GlobalTee32(dst), _] if (data.operand64(packed.index).a() == dst) => [update_jump(data, target, data.operand64(packed.index).b() as i32, dst, packed.op, on_zero, true)?], + [AddConst32(value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [IncStackTeeLocalJump32(data.push_target128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?)], + [XorConst32(value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [stack_update_jump(data, target, value, local, BinOp::IXor, on_zero)?], + [ShrUConst32(value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [stack_update_jump(data, target, value, local, BinOp::IShrU, on_zero)?], + [BinOpStackConst32(op, value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [stack_update_jump(data, target, value, local, op, on_zero)?], + [AndConstTee32(arg), LocalGet32(cond), _] if (arg.local == cond) => [stack_update_jump(data, target, arg.value, arg.local, BinOp::IAnd, on_zero)?], + [SubConstTee32(arg), LocalGet32(cond), _] if (arg.local == cond) => + [IncStackTeeLocalJump32(data.push_target128(Operand128::<LocalUpdateOperand>::new( + target, arg.value.wrapping_neg(), arg.local, on_zero))?)], + [BinOpLocalConstTee32(packed), LocalGet32(right), raw_cmp, _] + if (let Some(cmp) = cmp_op(raw_cmp) + && data.operand64(packed.index).a() == data.operand64(packed.index).b()) => [{ + let value = data.operand64(packed.index); + let cmp = if on_zero { cmp.inverse() } else { cmp }; + if let Some(delta) = packed.op.inc_delta(value.c() as i32) { + IncLocalJumpCmpLocal32(PackedOp::new(cmp, data.push_target128( + Operand128::<LocalUpdateCmpOperand>::new(target, delta, value.a(), right))?)) + } else { + BinOpLocalConstJumpCmpLocal32(PackedOp::new((packed.op, cmp), data.push_target128( + Operand128::<LocalUpdateCmpOperand>::new(target, value.c() as i32, value.a(), right))?)) + } + }], + [LocalGet32(local), I32Eqz, _] => [local_jump(target, local, !on_zero, false)], + [LocalGet64(local), I64Eqz, _] => [local_jump(target, local, !on_zero, true)], + [CmpLocalLocal32(op, left, right), I32Eqz, _] => [jump_cmp_local_local(data, target, left, right, if on_zero { op } else { op.inverse() }, false)?], + [I32Eqz, _] => [if on_zero { JumpIfNonZero32(target) } else { JumpIfZero32(target) }], + [I64Eqz, _] => [if on_zero { JumpIfNonZero64(target) } else { JumpIfZero64(target) }], + [CmpLocalLocal32(op, left, right), _] => [jump_cmp_local_local(data, target, left, right, if on_zero { op.inverse() } else { op }, false)?], + [CmpLocalLocal64(op, left, right), _] => [jump_cmp_local_local(data, target, left, right, if on_zero { op.inverse() } else { op }, true)?], + [LocalGet32(local), _] => [local_jump(target, local, on_zero, false)], + [LocalGet64(local), _] => [local_jump(target, local, on_zero, true)], + [LocalGet32(local), Const32(value), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_local_const32(data, target, local, value, op)?], + [LocalGet64(local), constant, raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero) + && let Some(value) = const64(data, constant) && let Ok(value) = i32::try_from(value)) => + [jump_cmp_local_const64(data, target, local, value, op)?], + [LocalGet32(left), LocalGet32(right), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_local_local(data, target, left, right, op, false)?], + [LocalGet64(left), LocalGet64(right), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_local_local(data, target, left, right, op, true)?], + [LocalGet32(local), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_stack_local(data, target, local, op, false)?], + [LocalGet64(local), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_stack_local(data, target, local, op, true)?], + [Const32(value), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_stack_const32(data, target, value, op)?], + [constant, raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero) && let Some(value) = const64(data, constant)) => [jump_cmp_stack_const64(data, target, value, op)?], + } +} diff --git a/crates/parser/src/selection/encoding.rs b/crates/parser/src/selection/encoding.rs new file mode 100644 index 0000000..0b407e5 --- /dev/null +++ b/crates/parser/src/selection/encoding.rs @@ -0,0 +1,293 @@ +//! Operand decoding and encoding, without access to the instruction tail. +use crate::{Result, visit::FunctionDataBuilder}; +use tinywasm_types::{Instruction, Instruction::*, *}; + +/// Reads a 64-bit literal without requiring a pool entry for immediate values. +pub(super) fn const64(data: &FunctionDataBuilder, instruction: Instruction) -> Option<i64> { + match instruction { + Const64(index) => Some(data.operand64(index).value()), + Const64Imm(value) => Some(i64::from(value)), + _ => None, + } +} + +/// Materializes a literal only when the selected encoding requires an operand index. +pub(super) fn pool64(data: &mut FunctionDataBuilder, instruction: Instruction) -> Result<Operand64Idx<i64>> { + match instruction { + Const64(index) => Ok(index), + Const64Imm(value) => data.push64(Operand64::<i64>::new(i64::from(value))), + _ => unreachable!("expected a 64-bit constant"), + } +} + +/// Materializes a vector literal only when the selected encoding requires an operand index. +pub(super) fn pool128(data: &mut FunctionDataBuilder, instruction: Instruction) -> Result<Operand128Idx<[u8; 16]>> { + match instruction { + Const128(index) => Ok(index), + Const128Imm(value) => data.push128(Operand128::<[u8; 16]>::new(u128::from(value).to_le_bytes())), + _ => unreachable!("expected a vector constant"), + } +} + +/// Decodes specialized and pooled local constants uniformly. +pub(super) fn local_const32(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(BinOp, u16, i32)> { + match instruction { + AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)), + SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), + MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), + AndLocalConst32(arg) => Some((BinOp::IAnd, arg.local, arg.value)), + ShrULocalConst32(arg) => Some((BinOp::IShrU, arg.local, arg.value)), + BinOpLocalConst32(packed) => { + let value = data.operand64(packed.index); + Some((packed.op, value.a(), value.b() as i32)) + } + _ => None, + } +} + +/// Decodes a pooled 64-bit local constant. +pub(super) fn local_const64(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(BinOp, u16, i64)> { + let BinOpLocalConst64(packed) = instruction else { return None }; + let value = data.operand128(packed.index); + Some((packed.op, value.a(), value.b() as i64)) +} + +/// Decodes a pooled vector local constant. +pub(super) fn local_const128( + data: &FunctionDataBuilder, + instruction: Instruction, +) -> Option<(BinOp128, u16, Operand128Idx<[u8; 16]>)> { + let BinOpLocalConst128(packed) = instruction else { return None }; + let value = data.operand64(packed.index); + Some((packed.op, value.a(), value.b())) +} + +/// Encodes the dedicated 32-bit local operations before falling back to a pooled operand. +pub(super) fn encode_local_const32( + data: &mut FunctionDataBuilder, + op: BinOp, + local: u16, + value: i32, +) -> Result<Instruction> { + let arg = I32LocalArg { value, local }; + Ok(match op { + BinOp::IAdd => AddLocalConst32(arg), + BinOp::ISub => SubLocalConst32(arg), + BinOp::IMul => MulLocalConst32(arg), + BinOp::IAnd => AndLocalConst32(arg), + BinOp::IShrU => ShrULocalConst32(arg), + _ => BinOpLocalConst32(PackedOp::new(op, data.push64(Operand64::<(u16, u32)>::new(local, value as u32))?)), + }) +} + +/// Encodes dedicated stack-immediate operations. +pub(super) fn stack_const32(op: BinOp, value: i32) -> Instruction { + match op { + BinOp::IAnd => AndConst32(value), + BinOp::IXor => XorConst32(value), + BinOp::IShrU => ShrUConst32(value), + _ => BinOpStackConst32(op, value), + } +} + +macro_rules! local_const_set { + ($($name:ident, $op:ty, $value:ty, [$($cast:tt)*], $pool:ident, $operand:ty, $set:ident, $tee:ident;)*) => {$( + /// Encodes a local constant operation with a destination local. + pub(super) fn $name(data: &mut FunctionDataBuilder, op: $op, src: u16, dst: u16, value: $value, tee: bool) -> Result<Instruction> { + let index = data.$pool(<$operand>::new(src, dst, value $($cast)*))?; + Ok(if tee { $tee(PackedOp::new(op, index)) } else { $set(PackedOp::new(op, index)) }) + } + )*}; +} +local_const_set! { + local_const_set32, BinOp, i32, [as u32], push64, Operand64<(u16, u16, u32)>, BinOpLocalConstSet32, BinOpLocalConstTee32; + local_const_set64, BinOp, i64, [as u64], push128, Operand128<(u16, u16, u64)>, BinOpLocalConstSet64, BinOpLocalConstTee64; + local_const_set128, BinOp128, Operand128Idx<[u8; 16]>, [], push64, Operand64<(u16, u16, Operand128Idx<[u8; 16]>)>, BinOpLocalConstSet128, BinOpLocalConstTee128; +} + +/// Decodes a preceding integer comparison, not the incoming instruction. +pub(super) fn cmp_op(instruction: Instruction) -> Option<CmpOp> { + Some(match instruction { + I32Eq | I64Eq => CmpOp::Eq, + I32Ne | I64Ne => CmpOp::Ne, + I32LtS | I64LtS => CmpOp::LtS, + I32LtU | I64LtU => CmpOp::LtU, + I32GtS | I64GtS => CmpOp::GtS, + I32GtU | I64GtU => CmpOp::GtU, + I32LeS | I64LeS => CmpOp::LeS, + I32LeU | I64LeU => CmpOp::LeU, + I32GeS | I64GeS => CmpOp::GeS, + I32GeU | I64GeU => CmpOp::GeU, + _ => return None, + }) +} + +/// Applies branch polarity to a preceding integer comparison. +pub(super) fn branch_cmp(instruction: Instruction, on_zero: bool) -> Option<CmpOp> { + cmp_op(instruction).map(|op| if on_zero { op.inverse() } else { op }) +} + +/// Encodes a local zero test of the requested width and polarity. +pub(super) fn local_jump(target: u32, local: u16, on_zero: bool, width64: bool) -> Instruction { + let arg = TargetLocalArg { target_ip: target, local }; + match (on_zero, width64) { + (true, false) => JumpIfLocalZero32(arg), + (false, false) => JumpIfLocalNonZero32(arg), + (true, true) => JumpIfLocalZero64(arg), + (false, true) => JumpIfLocalNonZero64(arg), + } +} + +/// Allocates a private target operand for a local/local comparison. +pub(super) fn jump_cmp_local_local( + data: &mut FunctionDataBuilder, + target: u32, + left: u16, + right: u16, + op: CmpOp, + width64: bool, +) -> Result<Instruction> { + let index = data.push_target64(Operand64::<(u32, u16, u16)>::new(target, left, right))?; + Ok(if width64 { + JumpCmpLocalLocal64(PackedOp::new(op, index)) + } else { + JumpCmpLocalLocal32(PackedOp::new(op, index)) + }) +} + +/// Allocates a private target operand for a stack/local comparison. +pub(super) fn jump_cmp_stack_local( + data: &mut FunctionDataBuilder, + target: u32, + local: u16, + op: CmpOp, + width64: bool, +) -> Result<Instruction> { + let index = data.push_target64(Operand64::<(u32, u16)>::new(target, local))?; + Ok(if width64 { + JumpCmpStackLocal64(PackedOp::new(op, index)) + } else { + JumpCmpStackLocal32(PackedOp::new(op, index)) + }) +} + +/// Encodes a local/immediate comparison, specializing zero equality tests. +pub(super) fn jump_cmp_local_const32( + data: &mut FunctionDataBuilder, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result<Instruction> { + if value == 0 && matches!(op, CmpOp::Eq | CmpOp::Ne) { + return Ok(local_jump(target, local, op == CmpOp::Eq, false)); + } + Ok(JumpCmpLocalConst32(PackedOp::new( + op, + data.push_target128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, + ))) +} + +/// Encodes a 64-bit local comparison with a representable 32-bit immediate. +pub(super) fn jump_cmp_local_const64( + data: &mut FunctionDataBuilder, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result<Instruction> { + if value == 0 && matches!(op, CmpOp::Eq | CmpOp::Ne) { + return Ok(local_jump(target, local, op == CmpOp::Eq, true)); + } + Ok(JumpCmpLocalConst64(PackedOp::new( + op, + data.push_target128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, + ))) +} + +/// Encodes a 32-bit stack/immediate comparison. +pub(super) fn jump_cmp_stack_const32( + data: &mut FunctionDataBuilder, + target: u32, + value: i32, + op: CmpOp, +) -> Result<Instruction> { + if value == 0 { + match op { + CmpOp::Eq => return Ok(JumpIfZero32(target)), + CmpOp::Ne => return Ok(JumpIfNonZero32(target)), + _ => {} + } + } + Ok(JumpCmpStackConst32(PackedOp::new(op, data.push_target64(Operand64::<(u32, i32)>::new(target, value))?))) +} + +/// Encodes a 64-bit stack/immediate comparison. +pub(super) fn jump_cmp_stack_const64( + data: &mut FunctionDataBuilder, + target: u32, + value: i64, + op: CmpOp, +) -> Result<Instruction> { + if value == 0 { + match op { + CmpOp::Eq => return Ok(JumpIfZero64(target)), + CmpOp::Ne => return Ok(JumpIfNonZero64(target)), + _ => {} + } + } + Ok(JumpCmpStackConst64(PackedOp::new(op, data.push_target128(Operand128::<(u32, i64)>::new(target, value))?))) +} + +/// Encodes a stack update, tee, and branch using a private target operand. +pub(super) fn stack_update_jump( + data: &mut FunctionDataBuilder, + target: u32, + value: i32, + local: u16, + op: BinOp, + on_zero: bool, +) -> Result<Instruction> { + Ok(BinOpStackConstTeeLocalJump32(PackedOp::new( + op, + data.push_target128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?, + ))) +} + +/// Encodes local/global updates, specializing increments when possible. +pub(super) fn update_jump( + data: &mut FunctionDataBuilder, + target: u32, + immediate: i32, + address: u32, + op: BinOp, + on_zero: bool, + global: bool, +) -> Result<Instruction> { + if let Some(delta) = op.inc_delta(immediate) { + Ok(if global { + IncGlobalJump32( + data.push_target128(Operand128::<GlobalUpdateOperand>::new(target, delta, address, on_zero))?, + ) + } else { + IncLocalJump32(data.push_target128(Operand128::<LocalUpdateOperand>::new( + target, + delta, + address as u16, + on_zero, + ))?) + }) + } else { + Ok(if global { + BinOpGlobalConstJump32(PackedOp::new( + op, + data.push_target128(Operand128::<GlobalUpdateOperand>::new(target, immediate, address, on_zero))?, + )) + } else { + BinOpLocalConstJump32(PackedOp::new( + op, + data.push_target128(Operand128::<LocalUpdateOperand>::new(target, immediate, address as u16, on_zero))?, + )) + }) + } +} diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 7daef52..a362f84 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -1,13 +1,19 @@ use crate::{ - Result, - conversion::{convert_heap_type, value_lane}, + ParserOptions, Result, + conversion::{FunctionLoweringContext, convert_heap_type, value_lane}, + emitter::{Emitter, LabelId}, macros::visit::*, }; -use alloc::{boxed::Box, collections::BTreeMap, string::ToString, vec::Vec}; +use alloc::{ + boxed::Box, + collections::{BTreeMap, btree_map::Entry}, + string::ToString, + vec::Vec, +}; use tinywasm_types::{ - BranchTableOperand, ExceptionHandler, Global, Import, ImportKind, Instruction, MemoryType, Operand64, Operand64Idx, - Operand128, Operand128Idx, StorageType, TableDefinition, TagType, TypeSection, ValueCounts, ValueLane, - WasmFunctionData, + BinOp, BinOp128, CmpOp, ExceptionHandler, Global, Import, ImportKind, Instruction, MemoryType, Operand64, + Operand64Idx, Operand128, Operand128Idx, StorageType, TableDefinition, TagType, TypeSection, ValueCounts, + ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -20,29 +26,53 @@ enum BlockKind { Block, Loop, If, - TryTable(usize), + TryTable, } -struct ControlFrame { +struct ControlFrame<'a> { kind: BlockKind, has_else: bool, - start_ip: usize, - branch_jumps: Vec<usize>, + loop_start: Option<LabelId>, + end: Option<LabelId>, + else_entry: Option<LabelId>, height: usize, base: ValueCounts, - params: Vec<ValueLane>, - results: Vec<ValueLane>, + signature: BlockSignature<'a>, unreachable: bool, entry_unreachable: bool, end_reachable: bool, } -#[derive(Clone)] +/// Module-owned physical lane signature, borrowed by control frames. pub(crate) struct Signature { pub params: Vec<ValueLane>, results: Vec<ValueLane>, } +#[derive(Clone, Copy)] +enum BlockSignature<'a> { + Empty, + Result(ValueLane), + Function(&'a Signature), +} + +impl BlockSignature<'_> { + fn params(&self) -> &[ValueLane] { + match self { + Self::Function(signature) => &signature.params, + _ => &[], + } + } + + fn results(&self) -> &[ValueLane] { + match self { + Self::Empty => &[], + Self::Result(lane) => core::slice::from_ref(lane), + Self::Function(signature) => &signature.results, + } + } +} + pub(crate) struct ModuleMetadata { signatures: Vec<Option<Signature>>, functions: Vec<u32>, @@ -75,40 +105,54 @@ impl FunctionDataBuilder { } } - pub(crate) fn push_operand64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> { + /// Allocates an immutable 64-bit operand, reusing it when deduplication is enabled. + pub(crate) fn push64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> { let operand = operand.cast(); - if let Some(index) = self.deduplicate64.as_ref().and_then(|map| map.get(&operand)) { - return Ok(Operand64Idx::new(*index)); - } - let index = self.operands64.len() as u32; + let entry = match self.deduplicate64.as_mut().map(|map| map.entry(operand)) { + Some(Entry::Occupied(entry)) => return Ok(Operand64Idx::new(*entry.get())), + Some(Entry::Vacant(entry)) => Some(entry), + None => None, + }; + let index = u32::try_from(self.operands64.len()) + .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?; self.operands64.push(operand); - if let Some(map) = &mut self.deduplicate64 { - map.insert(operand, index); + if let Some(entry) = entry { + entry.insert(index); } Ok(Operand64Idx::new(index)) } - pub(crate) fn push_operand128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> { + /// Allocates an immutable 128-bit operand, reusing it when deduplication is enabled. + pub(crate) fn push128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> { let operand = operand.cast(); - if let Some(index) = self.deduplicate128.as_ref().and_then(|map| map.get(&operand)) { - return Ok(Operand128Idx::new(*index)); - } - let index = self.operands128.len() as u32; + let entry = match self.deduplicate128.as_mut().map(|map| map.entry(operand)) { + Some(Entry::Occupied(entry)) => return Ok(Operand128Idx::new(*entry.get())), + Some(Entry::Vacant(entry)) => Some(entry), + None => None, + }; + let index = u32::try_from(self.operands128.len()) + .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?; self.operands128.push(operand); - if let Some(map) = &mut self.deduplicate128 { - map.insert(operand, index); + if let Some(entry) = entry { + entry.insert(index); } Ok(Operand128Idx::new(index)) } - pub(crate) fn push_target_operand64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> { + /// Allocates a private mutable target operand outside immutable deduplication. + pub(crate) fn push_target64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> { + let index = u32::try_from(self.operands64.len()) + .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?; self.operands64.push(operand.cast()); - Ok(Operand64Idx::new(self.operands64.len() as u32 - 1)) + Ok(Operand64Idx::new(index)) } - pub(crate) fn push_target_operand128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> { + /// Allocates a private mutable target operand outside immutable deduplication. + pub(crate) fn push_target128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> { + let index = u32::try_from(self.operands128.len()) + .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?; self.operands128.push(operand.cast()); - Ok(Operand128Idx::new(self.operands128.len() as u32 - 1)) + Ok(Operand128Idx::new(index)) } pub(crate) fn operand64<T>(&self, index: Operand64Idx<T>) -> Operand64<T> { @@ -119,14 +163,6 @@ impl FunctionDataBuilder { self.operands128[index.index()].cast() } - pub(crate) fn set_operand64<T>(&mut self, index: Operand64Idx<T>, operand: Operand64<T>) { - self.operands64[index.index()] = operand.cast(); - } - - pub(crate) fn set_operand128<T>(&mut self, index: Operand128Idx<T>, operand: Operand128<T>) { - self.operands128[index.index()] = operand.cast(); - } - pub(crate) fn finish(self) -> WasmFunctionData { WasmFunctionData { operands64: self.operands64.into_boxed_slice(), @@ -144,9 +180,9 @@ enum AggregateFields { } pub(crate) struct FunctionBuilder<'a> { - instructions: Vec<Instruction>, + emitter: Emitter, data: FunctionDataBuilder, - control_stack: Vec<ControlFrame>, + control_stack: Vec<ControlFrame<'a>>, operand_stack: Vec<ValueLane>, lane_counts: ValueCounts, metadata: &'a ModuleMetadata, @@ -156,29 +192,31 @@ pub(crate) struct FunctionBuilder<'a> { } impl<'a> FunctionBuilder<'a> { + /// Creates lowering state with a borrowed function signature. pub(crate) fn new( metadata: &'a ModuleMetadata, - signature: &Signature, + signature: &'a Signature, local_types: Vec<ValueLane>, local_addr_map: Vec<u16>, body_size: usize, - deduplicate_operands: bool, + context: FunctionLoweringContext, + options: &ParserOptions, ) -> Self { Self { local_types, local_addr_map, metadata, - instructions: Vec::with_capacity(body_size.min(1024)), - data: FunctionDataBuilder::new(deduplicate_operands), + emitter: Emitter::new(body_size, context, options), + data: FunctionDataBuilder::new(options.deduplicate_operands()), control_stack: alloc::vec![ControlFrame { kind: BlockKind::Function, has_else: false, - start_ip: 0, - branch_jumps: Vec::new(), + loop_start: None, + end: None, + else_entry: None, height: 0, base: ValueCounts::default(), - params: Vec::new(), - results: signature.results.clone(), + signature: BlockSignature::Function(signature), unreachable: false, entry_unreachable: false, end_reachable: false, @@ -200,16 +238,16 @@ impl<'a> FunctionBuilder<'a> { instruction: fn(Operand64Idx<(u32, u32)>) -> Instruction, ) -> Result<()> { let size = self.metadata.struct_field(type_index, field_index)?; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, field_index))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, field_index))?; self.emit(&[ValueLane::S32], &[size], instruction(operand)) } - fn push_operand64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> { - self.data.push_operand64(operand) + fn push64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> { + self.data.push64(operand) } - fn push_operand128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> { - self.data.push_operand128(operand) + fn push128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> { + self.data.push128(operand) } } @@ -380,7 +418,7 @@ impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> { #[cfg(not(rust_analyzer))] // rust analyzer gets confused and throws a bunch of errors when this macro is expanded wasmparser::for_each_visit_operator!(validate_then_visit); - fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> { + fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Result<()>>> { Some(self) } } @@ -395,17 +433,17 @@ pub(crate) fn process_operators( body: FunctionBody<'_>, locals: (Vec<ValueLane>, Vec<u16>), metadata: &ModuleMetadata, - ty_idx: u32, + context: FunctionLoweringContext, allocs: OperatorsReaderAllocations, - deduplicate_operands: bool, + options: &ParserOptions, ) -> Result<(Vec<Instruction>, FunctionDataBuilder, bool, OperatorsReaderAllocations)> { let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); - let signature = metadata.signature(ty_idx)?; + let signature = metadata.signature(context.ty_idx)?; let mut builder = - FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, context, options); while !reader.eof() { let position = reader.original_position(); @@ -420,7 +458,8 @@ pub(crate) fn process_operators( } reader.finish()?; - Ok((builder.instructions, builder.data, builder.uses_local_memory, reader.into_allocations())) + let instructions = builder.emitter.finish(&mut builder.data)?; + Ok((instructions, builder.data, builder.uses_local_memory, reader.into_allocations())) } #[cfg(feature = "validate")] @@ -429,17 +468,17 @@ pub(crate) fn process_operators_and_validate( body: FunctionBody<'_>, locals: (Vec<ValueLane>, Vec<u16>), metadata: &ModuleMetadata, - ty_idx: u32, + context: FunctionLoweringContext, allocs: OperatorsReaderAllocations, - deduplicate_operands: bool, + options: &ParserOptions, ) -> Result<(Vec<Instruction>, FunctionDataBuilder, bool, FuncValidatorAllocations, OperatorsReaderAllocations)> { let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); - let signature = metadata.signature(ty_idx)?; + let signature = metadata.signature(context.ty_idx)?; let mut builder = - FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, context, options); while !reader.eof() { let position = reader.original_position(); @@ -454,19 +493,14 @@ pub(crate) fn process_operators_and_validate( } reader.finish()?; - Ok(( - builder.instructions, - builder.data, - builder.uses_local_memory, - validator.into_allocations(), - reader.into_allocations(), - )) + let instructions = builder.emitter.finish(&mut builder.data)?; + Ok((instructions, builder.data, builder.uses_local_memory, validator.into_allocations(), reader.into_allocations())) } impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { type Output = Result<()>; - fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> { + fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Result<()>>> { Some(self) } @@ -474,23 +508,27 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { lowering_ops! { memory [Addr] => [S32] { - visit_i32_load => I32Load, visit_f32_load => F32Load, visit_i32_load8_s => I32Load8S, - visit_i32_load8_u => I32Load8U, visit_i32_load16_s => I32Load16S, - visit_i32_load16_u => I32Load16U, + visit_i32_load => I32Load [load(Instruction::LoadLocal32)], + visit_f32_load => F32Load [load(Instruction::LoadLocal32)], + visit_i32_load8_s => I32Load8S [load(Instruction::LoadLocal8S32)], + visit_i32_load8_u => I32Load8U [load(Instruction::LoadLocal8U32)], + visit_i32_load16_s => I32Load16S [load(Instruction::LoadLocal16S32)], + visit_i32_load16_u => I32Load16U [load(Instruction::LoadLocal16U32)], } memory [Addr] => [S64] { - visit_i64_load => I64Load, visit_f64_load => F64Load, visit_i64_load8_s => I64Load8S, + visit_i64_load => I64Load [load(Instruction::LoadLocal64)], + visit_f64_load => F64Load [load(Instruction::LoadLocal64)], visit_i64_load8_s => I64Load8S, visit_i64_load8_u => I64Load8U, visit_i64_load16_s => I64Load16S, visit_i64_load16_u => I64Load16U, visit_i64_load32_s => I64Load32S, visit_i64_load32_u => I64Load32U, } memory [Addr, S32] => [] { - visit_f32_store => F32Store, visit_i32_store8 => I32Store8, - visit_i32_store16 => I32Store16, visit_i32_store => I32Store, + visit_f32_store => F32Store [store32()], visit_i32_store8 => I32Store8, + visit_i32_store16 => I32Store16, visit_i32_store => I32Store [store32()], } memory [Addr, S64] => [] { - visit_f64_store => F64Store, visit_i64_store8 => I64Store8, - visit_i64_store16 => I64Store16, visit_i64_store32 => I64Store32, visit_i64_store => I64Store, + visit_f64_store => F64Store [store64()], visit_i64_store8 => I64Store8, + visit_i64_store16 => I64Store16, visit_i64_store32 => I64Store32, visit_i64_store => I64Store [store64()], } 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 } @@ -531,41 +569,83 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { visit_i32_trunc_sat_f64_s => I32TruncSatF64S, visit_i32_trunc_sat_f64_u => I32TruncSatF64U, } fixed [S32] => [S64] { - visit_i64_extend_i32_s => I64ExtendI32S, visit_i64_extend_i32_u => I64ExtendI32U, + visit_i64_extend_i32_s => I64ExtendI32S [extend_i32(true)], + visit_i64_extend_i32_u => I64ExtendI32U [extend_i32(false)], visit_i64_trunc_f32_s => I64TruncF32S, visit_i64_trunc_f32_u => I64TruncF32U, visit_f64_convert_i32_s => F64ConvertI32S, visit_f64_convert_i32_u => F64ConvertI32U, visit_f64_promote_f32 => F64PromoteF32, visit_i64_trunc_sat_f32_s => I64TruncSatF32S, visit_i64_trunc_sat_f32_u => I64TruncSatF32U, } fixed [S32, S32] => [S32] { - 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_ref_eq => RefEq, + visit_i32_eq => I32Eq [compare(CmpOp::Eq)], + visit_i32_ne => I32Ne [compare(CmpOp::Ne)], + visit_i32_lt_s => I32LtS [compare(CmpOp::LtS)], + visit_i32_lt_u => I32LtU [compare(CmpOp::LtU)], + visit_i32_gt_s => I32GtS [compare(CmpOp::GtS)], + visit_i32_gt_u => I32GtU [compare(CmpOp::GtU)], + visit_i32_le_s => I32LeS [compare(CmpOp::LeS)], + visit_i32_le_u => I32LeU [compare(CmpOp::LeU)], + visit_i32_ge_s => I32GeS [compare(CmpOp::GeS)], + visit_i32_ge_u => I32GeU [compare(CmpOp::GeU)], visit_f32_eq => F32Eq, visit_f32_ne => F32Ne, visit_f32_lt => F32Lt, visit_f32_gt => F32Gt, - visit_f32_le => F32Le, visit_f32_ge => F32Ge, visit_i32_add => I32Add, visit_i32_sub => I32Sub, - visit_i32_mul => I32Mul, visit_i32_div_s => I32DivS, visit_i32_div_u => I32DivU, - visit_i32_rem_s => I32RemS, visit_i32_rem_u => I32RemU, visit_i32_and => I32And, - visit_i32_or => I32Or, visit_i32_xor => I32Xor, visit_i32_shl => I32Shl, visit_i32_shr_s => I32ShrS, - visit_i32_shr_u => I32ShrU, visit_i32_rotl => I32Rotl, visit_i32_rotr => I32Rotr, - visit_f32_add => F32Add, visit_f32_sub => F32Sub, visit_f32_mul => F32Mul, visit_f32_div => F32Div, - visit_f32_min => F32Min, visit_f32_max => F32Max, visit_f32_copysign => F32Copysign, + visit_f32_le => F32Le, visit_f32_ge => F32Ge, + visit_i32_add => I32Add [integer32(BinOp::IAdd, true)], + visit_i32_sub => I32Sub [integer32(BinOp::ISub, false)], + visit_i32_mul => I32Mul [integer32(BinOp::IMul, true)], + visit_i32_div_s => I32DivS, visit_i32_div_u => I32DivU, + visit_i32_rem_s => I32RemS, visit_i32_rem_u => I32RemU, + visit_i32_and => I32And [integer32(BinOp::IAnd, true)], + visit_i32_or => I32Or [integer32(BinOp::IOr, true)], + visit_i32_xor => I32Xor [integer32(BinOp::IXor, true)], + visit_i32_shl => I32Shl [integer32(BinOp::IShl, false)], + visit_i32_shr_s => I32ShrS [integer32(BinOp::IShrS, false)], + visit_i32_shr_u => I32ShrU [integer32(BinOp::IShrU, false)], + visit_i32_rotl => I32Rotl [integer32(BinOp::IRotl, false)], + visit_i32_rotr => I32Rotr [integer32(BinOp::IRotr, false)], + visit_f32_add => F32Add [float32(BinOp::FAdd, true)], + visit_f32_sub => F32Sub [float32(BinOp::FSub, false)], + visit_f32_mul => F32Mul [float32(BinOp::FMul, true)], + visit_f32_div => F32Div [float32(BinOp::FDiv, false)], + visit_f32_min => F32Min [float32(BinOp::FMin, true)], + visit_f32_max => F32Max [float32(BinOp::FMax, true)], + visit_f32_copysign => F32Copysign [float32(BinOp::FCopysign, false)], } fixed [S64, S64] => [S32] { - visit_i64_eq => I64Eq, visit_i64_ne => I64Ne, visit_i64_lt_s => I64LtS, visit_i64_lt_u => I64LtU, - visit_i64_gt_s => I64GtS, visit_i64_gt_u => I64GtU, visit_i64_le_s => I64LeS, - visit_i64_le_u => I64LeU, visit_i64_ge_s => I64GeS, visit_i64_ge_u => I64GeU, + visit_i64_eq => I64Eq [compare(CmpOp::Eq)], + visit_i64_ne => I64Ne [compare(CmpOp::Ne)], + visit_i64_lt_s => I64LtS [compare(CmpOp::LtS)], + visit_i64_lt_u => I64LtU [compare(CmpOp::LtU)], + visit_i64_gt_s => I64GtS [compare(CmpOp::GtS)], + visit_i64_gt_u => I64GtU [compare(CmpOp::GtU)], + visit_i64_le_s => I64LeS [compare(CmpOp::LeS)], + visit_i64_le_u => I64LeU [compare(CmpOp::LeU)], + visit_i64_ge_s => I64GeS [compare(CmpOp::GeS)], + visit_i64_ge_u => I64GeU [compare(CmpOp::GeU)], visit_f64_eq => F64Eq, visit_f64_ne => F64Ne, visit_f64_lt => F64Lt, visit_f64_gt => F64Gt, visit_f64_le => F64Le, visit_f64_ge => F64Ge, } fixed [S64, S64] => [S64] { - visit_i64_add => I64Add, visit_i64_sub => I64Sub, visit_i64_mul => I64Mul, + visit_i64_add => I64Add [integer64(BinOp::IAdd, true)], + visit_i64_sub => I64Sub [integer64(BinOp::ISub, false)], + visit_i64_mul => I64Mul [integer64(BinOp::IMul, true)], visit_i64_div_s => I64DivS, visit_i64_div_u => I64DivU, visit_i64_rem_s => I64RemS, - visit_i64_rem_u => I64RemU, visit_i64_and => I64And, visit_i64_or => I64Or, visit_i64_xor => I64Xor, - visit_i64_shl => I64Shl, visit_i64_shr_s => I64ShrS, visit_i64_shr_u => I64ShrU, - visit_i64_rotl => I64Rotl, visit_i64_rotr => I64Rotr, visit_f64_add => F64Add, - visit_f64_sub => F64Sub, visit_f64_mul => F64Mul, visit_f64_div => F64Div, - visit_f64_min => F64Min, visit_f64_max => F64Max, visit_f64_copysign => F64Copysign, + visit_i64_rem_u => I64RemU, + visit_i64_and => I64And [integer64(BinOp::IAnd, true)], + visit_i64_or => I64Or [integer64(BinOp::IOr, true)], + visit_i64_xor => I64Xor [integer64(BinOp::IXor, true)], + visit_i64_shl => I64Shl [integer64(BinOp::IShl, false)], + visit_i64_shr_s => I64ShrS [integer64(BinOp::IShrS, false)], + visit_i64_shr_u => I64ShrU [integer64(BinOp::IShrU, false)], + visit_i64_rotl => I64Rotl [integer64(BinOp::IRotl, false)], + visit_i64_rotr => I64Rotr [integer64(BinOp::IRotr, false)], + visit_f64_add => F64Add [float64(BinOp::FAdd, true)], + visit_f64_sub => F64Sub [float64(BinOp::FSub, false)], + visit_f64_mul => F64Mul [float64(BinOp::FMul, true)], + visit_f64_div => F64Div [float64(BinOp::FDiv, false)], + visit_f64_min => F64Min [float64(BinOp::FMin, true)], + visit_f64_max => F64Max [float64(BinOp::FMax, true)], + visit_f64_copysign => F64Copysign [float64(BinOp::FCopysign, false)], } fixed [S64, S64, S64, S64] => [S64, S64] { visit_i64_add128 => I64Add128, visit_i64_sub128 => I64Sub128 } fixed [S64, S64] => [S64, S64] { visit_i64_mul_wide_s => I64MulWideS, visit_i64_mul_wide_u => I64MulWideU } @@ -575,7 +655,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { terminating [] => [] { visit_unreachable => Unreachable, visit_return => Return } memory_index [] => [Addr] { visit_memory_size(memory: u32) => MemorySize } memory_index [Addr] => [Addr] { visit_memory_grow(memory: u32) => MemoryGrow } - memory_index [Addr, S32, Addr] => [] { visit_memory_fill(memory: u32) => MemoryFill } + memory_index [Addr, S32, Addr] => [] { visit_memory_fill(memory: u32) => MemoryFill [memory_fill()] } table [Addr] => [S32] { visit_table_get(table: u32) => TableGet } table [Addr, S32] => [] { visit_table_set(table: u32) => TableSet } table [] => [Addr] { visit_table_size(table: u32) => TableSize } @@ -594,94 +674,94 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { array_field [S32, S32, Field, S32] => [] { visit_array_fill(type_index: u32) => ArrayFill } } - fn visit_struct_new(&mut self, type_index: u32) -> Self::Output { + fn visit_struct_new(&mut self, type_index: u32) -> Result<()> { let field_count = self.metadata.struct_fields(type_index)?.len(); for field_index in (0..field_count).rev() { let size = self.metadata.struct_field(type_index, field_index as u32)?; self.pop_expect(size)?; } self.push_sizes(&[ValueLane::S32])?; - self.instructions.push(Instruction::StructNew(type_index)); + self.emitter.emit(Instruction::StructNew(type_index))?; Ok(()) } - fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output { + fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Result<()> { 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 { + fn visit_struct_get_s(&mut self, type_index: u32, field_index: u32) -> Result<()> { 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 { + fn visit_struct_get_u(&mut self, type_index: u32, field_index: u32) -> Result<()> { 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 { + fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Result<()> { let size = self.metadata.struct_field(type_index, field_index)?; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, field_index))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, field_index))?; self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(operand)) } - fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { + fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Result<()> { let size = self.metadata.array_field(type_index)?; for _ in 0..array_size { self.pop_expect(size)?; } self.push_sizes(&[ValueLane::S32])?; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, array_size))?; - self.instructions.push(Instruction::ArrayNewFixed(operand)); + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, array_size))?; + self.emitter.emit(Instruction::ArrayNewFixed(operand))?; Ok(()) } - fn visit_call(&mut self, function_index: u32) -> Self::Output { + fn visit_call(&mut self, function_index: u32) -> Result<()> { let signature = self.metadata.function_signature(function_index)?; - self.emit(&signature.params, &signature.results, Instruction::Call(function_index)) + self.emit_boundary(&signature.params, &signature.results, Instruction::Call(function_index)) } - fn visit_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output { + fn visit_call_indirect(&mut self, type_index: u32, table_index: u32) -> Result<()> { let table_size = self.metadata.table_size(table_index)?; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, table_index))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, table_index))?; let signature = self.metadata.signature(type_index)?; self.pop_expect(table_size)?; - self.emit(&signature.params, &signature.results, Instruction::CallIndirect(operand)) + self.emit_boundary(&signature.params, &signature.results, Instruction::CallIndirect(operand)) } - fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { + fn visit_call_ref(&mut self, type_index: u32) -> Result<()> { let signature = self.metadata.signature(type_index)?; self.pop_expect(ValueLane::S32)?; - self.emit(&signature.params, &signature.results, Instruction::CallRef(type_index)) + self.emit_boundary(&signature.params, &signature.results, Instruction::CallRef(type_index)) } - fn visit_return_call(&mut self, function_index: u32) -> Self::Output { + fn visit_return_call(&mut self, function_index: u32) -> Result<()> { let signature = self.metadata.function_signature(function_index)?; self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); - self.instructions.push(Instruction::ReturnCall(function_index)); + self.emitter.emit_boundary(Instruction::ReturnCall(function_index))?; Ok(()) } - fn visit_return_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output { + fn visit_return_call_indirect(&mut self, type_index: u32, table_index: u32) -> Result<()> { let table_size = self.metadata.table_size(table_index)?; let signature = self.metadata.signature(type_index)?; self.pop_expect(table_size)?; self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, table_index))?; - self.instructions.push(Instruction::ReturnCallIndirect(operand)); + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, table_index))?; + self.emitter.emit_boundary(Instruction::ReturnCallIndirect(operand))?; Ok(()) } - fn visit_return_call_ref(&mut self, type_index: u32) -> Self::Output { + fn visit_return_call_ref(&mut self, type_index: u32) -> Result<()> { let signature = self.metadata.signature(type_index)?; self.pop_expect(ValueLane::S32)?; self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); - self.instructions.push(Instruction::ReturnCallRef(type_index)); + self.emitter.emit_boundary(Instruction::ReturnCallRef(type_index))?; Ok(()) } - fn visit_global_set(&mut self, global_index: u32) -> Self::Output { + fn visit_global_set(&mut self, global_index: u32) -> Result<()> { let size = self.metadata.global_size(global_index)?; let instruction = size.select( Instruction::GlobalSet32(global_index), @@ -691,87 +771,86 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.emit(&[size], &[], instruction) } - fn visit_global_get(&mut self, global_index: u32) -> Self::Output { + fn visit_global_get(&mut self, global_index: u32) -> Result<()> { let size = self.metadata.global_size(global_index)?; - let instruction = size.select( - Instruction::GlobalGet32(global_index), - Instruction::GlobalGet64(global_index), - Instruction::GlobalGet128(global_index), - ); - self.emit(&[], &[size], instruction) + match size { + ValueLane::S32 => emit_selected!(self, &[], &[size], GlobalGet32(global_index)[global_get32()]), + ValueLane::S64 => emit_selected!(self, &[], &[size], GlobalGet64(global_index)[global_get64()]), + ValueLane::S128 => emit_selected!(self, &[], &[size], GlobalGet128(global_index)[global_get128()]), + } } - fn visit_drop(&mut self) -> Self::Output { + fn visit_drop(&mut self) -> Result<()> { let size = self.operand_stack.last().copied().unwrap_or(ValueLane::S32); - let instruction = size.select(Instruction::Drop32, Instruction::Drop64, Instruction::Drop128); - self.emit(&[size], &[], instruction) + match size { + ValueLane::S32 => emit_selected!(self, &[size], &[], Drop32[drop32()]), + ValueLane::S64 => emit_selected!(self, &[size], &[], Drop64[drop64()]), + ValueLane::S128 => emit_selected!(self, &[size], &[], Drop128[drop128()]), + } } - fn visit_select(&mut self) -> Self::Output { + fn visit_select(&mut self) -> Result<()> { let size = self.operand_stack.iter().rev().nth(1).copied().unwrap_or(ValueLane::S32); let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128); self.emit(&[size, size, ValueLane::S32], &[size], instruction) } - fn visit_local_get(&mut self, idx: u32) -> Self::Output { + fn visit_local_get(&mut self, idx: u32) -> Result<()> { let (size, local_idx) = self.local(idx)?; - let instruction = size.select( - Instruction::LocalGet32(local_idx), - Instruction::LocalGet64(local_idx), - Instruction::LocalGet128(local_idx), - ); - self.emit(&[], &[size], instruction) + match size { + ValueLane::S32 => emit_selected!(self, &[], &[size], LocalGet32(local_idx)[local_get32()]), + ValueLane::S64 => emit_selected!(self, &[], &[size], LocalGet64(local_idx)[local_get64()]), + ValueLane::S128 => emit_selected!(self, &[], &[size], LocalGet128(local_idx)[local_get128()]), + } } - fn visit_local_set(&mut self, idx: u32) -> Self::Output { + fn visit_local_set(&mut self, idx: u32) -> Result<()> { let (size, local_idx) = self.local(idx)?; - let instruction = size.select( - Instruction::LocalSet32(local_idx), - Instruction::LocalSet64(local_idx), - Instruction::LocalSet128(local_idx), - ); - self.emit(&[size], &[], instruction) + match size { + ValueLane::S32 => emit_selected!(self, &[size], &[], LocalSet32(local_idx)[local_set32()]), + ValueLane::S64 => emit_selected!(self, &[size], &[], LocalSet64(local_idx)[local_set64()]), + ValueLane::S128 => emit_selected!(self, &[size], &[], LocalSet128(local_idx)[local_set128()]), + } } - fn visit_local_tee(&mut self, idx: u32) -> Self::Output { + fn visit_local_tee(&mut self, idx: u32) -> Result<()> { let (size, local_idx) = self.local(idx)?; - // No peephole here: this position may be a branch target (block end, - // loop start, if/else join), and fusing with the preceding `local.get` - // would move the label past the tee. The rewriter fuses the same pair - // within a basic block, where no branch can land between them. - let instruction = size.select( - Instruction::LocalTee32(local_idx), - Instruction::LocalTee64(local_idx), - Instruction::LocalTee128(local_idx), - ); - self.emit(&[size], &[size], instruction) + // Bound labels seal the tail, so these rules cannot fuse across a loop + // entry or another branch destination. + match size { + ValueLane::S32 => emit_selected!(self, &[size], &[size], LocalTee32(local_idx)[local_tee32()]), + ValueLane::S64 => emit_selected!(self, &[size], &[size], LocalTee64(local_idx)[local_tee64()]), + ValueLane::S128 => emit_selected!(self, &[size], &[size], LocalTee128(local_idx)[local_tee128()]), + } } - fn visit_block(&mut self, blockty: wasmparser::BlockType) -> Self::Output { + fn visit_block(&mut self, blockty: wasmparser::BlockType) -> Result<()> { self.push_control(BlockKind::Block, blockty, None) } - fn visit_loop(&mut self, ty: wasmparser::BlockType) -> Self::Output { + fn visit_loop(&mut self, ty: wasmparser::BlockType) -> Result<()> { self.push_control(BlockKind::Loop, ty, None) } - fn visit_if(&mut self, ty: wasmparser::BlockType) -> Self::Output { + fn visit_if(&mut self, ty: wasmparser::BlockType) -> Result<()> { self.pop_expect(ValueLane::S32)?; - self.instructions.push(Instruction::JumpIfZero32(0)); - self.push_control(BlockKind::If, ty, Some(self.instructions.len() - 1)) + let else_entry = self.emitter.new_label(); + self.emitter.branch_if(&mut self.data, true, else_entry)?; + self.push_control(BlockKind::If, ty, Some(else_entry)) } - fn visit_try_table(&mut self, try_table: wasmparser::TryTable) -> Self::Output { + fn visit_try_table(&mut self, try_table: wasmparser::TryTable) -> Result<()> { let signature = self.block_signature(try_table.ty)?; - for &size in signature.params.iter().rev() { + for &size in signature.params().iter().rev() { self.pop_expect(size)?; } let height = self.operand_stack.len(); let base = self.lane_counts; let entry_unreachable = self.is_unreachable(); - let body_jump = self.instructions.len(); - self.instructions.push(Instruction::Jump(0)); + let body_start = self.emitter.new_label(); + let body_end = self.emitter.new_label(); + self.emitter.branch(Instruction::Jump(0), body_start)?; let mut catches = Vec::with_capacity(try_table.catches.len()); for catch in try_table.catches { let (tag, depth, with_ref) = match catch { @@ -785,43 +864,31 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } let target_idx = self.get_ctx_idx(depth)?; let target_base = self.control_stack[target_idx].base; - let landing_pad = u32::try_from(self.instructions.len()) - .map_err(|_| crate::ParseError::Other("function body is too large".into()))?; - match self.control_stack[target_idx].kind { - BlockKind::Function => self.instructions.push(Instruction::Return), - BlockKind::Loop => { - self.instructions.push(Instruction::Jump(self.control_stack[target_idx].start_ip as u32)); - } - BlockKind::Block | BlockKind::If | BlockKind::TryTable(_) => { - self.control_stack[target_idx].branch_jumps.push(self.instructions.len()); - self.control_stack[target_idx].end_reachable = true; - self.instructions.push(Instruction::Jump(0)); - } - } - catches.push(match tag { - Some(tag) => tinywasm_types::ExceptionCatch::Tag { tag, landing_pad, base: target_base, with_ref }, - None => tinywasm_types::ExceptionCatch::All { landing_pad, base: target_base, with_ref }, - }); + let landing_label = self.emitter.new_label(); + self.emitter.bind(landing_label)?; + self.emit_branch_jump_or_return(depth)?; + let landing_pad = 0; + catches.push(( + match tag { + Some(tag) => tinywasm_types::ExceptionCatch::Tag { tag, landing_pad, base: target_base, with_ref }, + None => tinywasm_types::ExceptionCatch::All { landing_pad, base: target_base, with_ref }, + }, + landing_label, + )); } - let body_start = self.instructions.len(); - self.patch_jump(body_jump, body_start); - let handler_idx = self.data.exception_handlers.len(); - self.data.exception_handlers.push(tinywasm_types::ExceptionHandler { - start_ip: body_start as u32, - end_ip: 0, - catches: catches.into_boxed_slice(), - }); - self.push_sizes(&signature.params)?; + self.emitter.bind(body_start)?; + self.emitter.exception_handler(&mut self.data, body_start, body_end, catches); + self.push_sizes(signature.params())?; self.control_stack.push(ControlFrame { - kind: BlockKind::TryTable(handler_idx), + kind: BlockKind::TryTable, has_else: false, - start_ip: body_start, - branch_jumps: Vec::new(), + loop_start: None, + end: Some(body_end), + else_entry: None, height, base, - params: signature.params, - results: signature.results, + signature, unreachable: entry_unreachable, entry_unreachable, end_reachable: false, @@ -829,238 +896,229 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { Ok(()) } - fn visit_throw(&mut self, tag_index: u32) -> Self::Output { + fn visit_throw(&mut self, tag_index: u32) -> Result<()> { let signature = self.metadata.tag_signature(tag_index)?; self.apply_effect(&signature.params, &[])?; - self.instructions.push(Instruction::Throw(tag_index)); + self.emitter.emit_boundary(Instruction::Throw(tag_index))?; self.mark_unreachable(); Ok(()) } - fn visit_throw_ref(&mut self) -> Self::Output { + fn visit_throw_ref(&mut self) -> Result<()> { self.apply_effect(&[ValueLane::S32], &[])?; - self.instructions.push(Instruction::ThrowRef); + self.emitter.emit_boundary(Instruction::ThrowRef)?; self.mark_unreachable(); Ok(()) } - fn visit_else(&mut self) -> Self::Output { - let (cond_jump_ip, height, base, params, entry_unreachable) = { + fn visit_else(&mut self) -> Result<()> { + let (else_entry, end, height, base, signature, entry_unreachable) = { let ctx = self .control_stack .last_mut() - .filter(|ctx| matches!(ctx.kind, BlockKind::If)) + .filter(|ctx| matches!(ctx.kind, BlockKind::If) && !ctx.has_else) .ok_or_else(|| crate::ParseError::Other("else without matching if".into()))?; ctx.end_reachable |= !ctx.unreachable; ctx.has_else = true; - (ctx.branch_jumps[0], ctx.height, ctx.base, ctx.params.clone(), ctx.entry_unreachable) + let end = *ctx.end.get_or_insert_with(|| self.emitter.new_label()); + (ctx.else_entry.unwrap(), end, ctx.height, ctx.base, ctx.signature, ctx.entry_unreachable) }; - let jump_ip = self.instructions.len(); - self.instructions.push(Instruction::Jump(0)); - self.control_stack.last_mut().unwrap().branch_jumps.push(jump_ip); - self.patch_jump(cond_jump_ip, self.instructions.len()); + self.emitter.branch(Instruction::Jump(0), end)?; + self.emitter.bind(else_entry)?; self.reset_stack(height, base); - self.push_sizes(¶ms)?; + self.push_sizes(signature.params())?; self.control_stack.last_mut().unwrap().unreachable = entry_unreachable; Ok(()) } - fn visit_end(&mut self) -> Self::Output { + fn visit_end(&mut self) -> Result<()> { let ctx = self.control_stack.pop().ok_or_else(|| crate::ParseError::Other("end without control frame".into()))?; - if let BlockKind::TryTable(handler_idx) = ctx.kind { - self.data.exception_handlers[handler_idx].end_ip = self.instructions.len() as u32; + if let Some(end) = ctx.end { + self.emitter.bind(end)?; + } + if !ctx.has_else + && let Some(else_entry) = ctx.else_entry + { + self.emitter.bind(else_entry)?; } if matches!(ctx.kind, BlockKind::Function) { - self.instructions.push(Instruction::Return); + self.emitter.emit_boundary(Instruction::Return)?; } else { let reachable = !ctx.entry_unreachable && (!ctx.unreachable || ctx.end_reachable || matches!(ctx.kind, BlockKind::If) && !ctx.has_else); self.reset_stack(ctx.height, ctx.base); - self.push_sizes(&ctx.results)?; + self.push_sizes(ctx.signature.results())?; if let Some(parent) = self.control_stack.last_mut() { parent.unreachable = !reachable; } - self.patch_end_jumps(ctx, self.instructions.len()); } Ok(()) } - fn visit_br(&mut self, depth: u32) -> Self::Output { + fn visit_br(&mut self, depth: u32) -> Result<()> { self.emit_dropkeep_to_label(depth)?; self.emit_branch_jump_or_return(depth)?; self.mark_unreachable(); Ok(()) } - fn visit_br_if(&mut self, depth: u32) -> Self::Output { + fn visit_br_if(&mut self, depth: u32) -> Result<()> { self.pop_expect(ValueLane::S32)?; - let cond_jump_ip = self.instructions.len(); - self.instructions.push(Instruction::JumpIfZero32(0)); - - let branch_side_start = self.instructions.len(); - self.emit_dropkeep_to_label(depth)?; - - if self.instructions.len() == branch_side_start - && let Ok(ctx_idx) = self.get_ctx_idx(depth) - && !matches!(self.control_stack[ctx_idx].kind, BlockKind::Function) - { - self.instructions[cond_jump_ip] = Instruction::JumpIfNonZero32(0); - self.control_stack[ctx_idx].branch_jumps.push(cond_jump_ip); + let ctx_idx = self.get_ctx_idx(depth)?; + let frame = &self.control_stack[ctx_idx]; + let types = + if matches!(frame.kind, BlockKind::Loop) { frame.signature.params() } else { frame.signature.results() }; + let keep = Self::value_counts(types); + let needs_shaping = !self.is_unreachable() && self.needs_dropkeep(frame.base, keep); + if !needs_shaping && !matches!(frame.kind, BlockKind::Function) { + let target = if let Some(start) = frame.loop_start { + start + } else { + *self.control_stack[ctx_idx].end.get_or_insert_with(|| self.emitter.new_label()) + }; + self.emitter.branch_if(&mut self.data, false, target)?; self.control_stack[ctx_idx].end_reachable = true; return Ok(()); } - + let fallthrough = self.emitter.new_label(); + self.emitter.branch_if(&mut self.data, true, fallthrough)?; + self.emit_dropkeep_to_label(depth)?; self.emit_branch_jump_or_return(depth)?; - self.patch_jump(cond_jump_ip, self.instructions.len()); + self.emitter.bind(fallthrough)?; Ok(()) } - fn visit_br_table(&mut self, targets: wasmparser::BrTable<'_>) -> Self::Output { + fn visit_br_table(&mut self, targets: wasmparser::BrTable<'_>) -> Result<()> { let ts = targets.targets().collect::<Result<Vec<_>, wasmparser::Error>>()?; self.pop_expect(ValueLane::S32)?; let default_depth = targets.default(); - let len = ts.len() as u32; let target_depths: Vec<u32> = ts; - - let header_ip = self.instructions.len(); - let branch_table_start = self.data.branch_table_targets.len() as u32; - let branch_operand = - self.data.push_target_operand128(Operand128::<BranchTableOperand>::new(0, branch_table_start, len))?; - self.instructions.push(Instruction::BranchTable(branch_operand)); - - struct PadInfo { - depth: u32, - pad_start: usize, - jump_or_ret_ip: usize, - is_return: bool, - } - let mut pads: Vec<PadInfo> = Vec::new(); - + let mut pads: Vec<(u32, LabelId)> = Vec::new(); + let label_count = target_depths + .len() + .checked_add(1) + .ok_or_else(|| crate::ParseError::Other("branch table is too large".into()))?; + let mut labels = Vec::with_capacity(label_count); for &depth in target_depths.iter().chain(core::iter::once(&default_depth)) { - if pads.iter().any(|pad| pad.depth == depth) { - continue; + if self.emitter.optimizations_enabled() && !self.is_unreachable() { + let ctx_idx = self.get_ctx_idx(depth)?; + let frame = &self.control_stack[ctx_idx]; + let is_loop = matches!(frame.kind, BlockKind::Loop); + let types = if is_loop { frame.signature.params() } else { frame.signature.results() }; + if !matches!(frame.kind, BlockKind::Function) + && !self.needs_dropkeep(frame.base, Self::value_counts(types)) + { + let target = if let Some(start) = frame.loop_start { + start + } else { + *self.control_stack[ctx_idx].end.get_or_insert_with(|| self.emitter.new_label()) + }; + labels.push(target); + if !is_loop { + self.control_stack[ctx_idx].end_reachable = true; + } + continue; + } } - - let pad_start = self.instructions.len(); - let (jump_or_ret_ip, is_return) = if self.is_unreachable() { - self.instructions.push(Instruction::Return); - (pad_start, true) + let label = if let Some((_, label)) = pads.iter().find(|(pad_depth, _)| *pad_depth == depth) { + *label } else { - let frame = &self.control_stack[self.get_ctx_idx(depth)?]; - let base = frame.base; - let label_types = if matches!(frame.kind, BlockKind::Loop) { &frame.params } else { &frame.results }; - self.emit_dropkeep(base, Self::value_counts(label_types)); - let jump_ip = self.instructions.len(); - self.instructions.push(Instruction::Jump(0)); - (jump_ip, false) + let label = self.emitter.new_label(); + pads.push((depth, label)); + label }; - pads.push(PadInfo { depth, pad_start, jump_or_ret_ip, is_return }); - } - - for &depth in &target_depths { - let pad = pads - .iter() - .find(|pad| pad.depth == depth) - .ok_or_else(|| crate::ParseError::Other("missing branch table target".into()))?; - self.data.branch_table_targets.push(pad.pad_start as u32); - } - - let default_pad = pads - .iter() - .find(|pad| pad.depth == default_depth) - .ok_or_else(|| crate::ParseError::Other("missing default branch table target".into()))?; - if let Instruction::BranchTable(index) = self.instructions[header_ip] { - let operand = self.data.operand128(index); - self.data.set_operand128(index, operand.with_target(default_pad.pad_start as u32)); + labels.push(label); } - - for pad in &pads { - if pad.is_return { - continue; - } - let ctx_idx = self.get_ctx_idx(pad.depth)?; - if matches!(self.control_stack[ctx_idx].kind, BlockKind::Function) { - self.instructions[pad.jump_or_ret_ip] = Instruction::Return; - } else if matches!(self.control_stack[ctx_idx].kind, BlockKind::Loop) { - self.patch_jump(pad.jump_or_ret_ip, self.control_stack[ctx_idx].start_ip); + let default = labels.pop().unwrap(); + self.emitter.branch_table(&mut self.data, &labels, default)?; + for (depth, label) in pads { + self.emitter.bind(label)?; + if self.is_unreachable() { + self.emitter.emit_boundary(Instruction::Return)?; } else { - self.control_stack[ctx_idx].branch_jumps.push(pad.jump_or_ret_ip); - self.control_stack[ctx_idx].end_reachable = true; + self.emit_dropkeep_to_label(depth)?; + self.emit_branch_jump_or_return(depth)?; } } self.mark_unreachable(); Ok(()) } - fn visit_f32_const(&mut self, val: wasmparser::Ieee32) -> Self::Output { + fn visit_f32_const(&mut self, val: wasmparser::Ieee32) -> Result<()> { self.emit(&[], &[ValueLane::S32], Instruction::Const32(val.bits() as i32)) } - fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - let operand = self.push_operand64(Operand64::<i64>::new(val.bits() as i64))?; - self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) + #[cfg(not(rust_analyzer))] // rust-analyzer thinks the return type is wrong + fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Result<()> { + self.visit_i64_const(val.bits() as i64) } - fn visit_i64_const(&mut self, value: i64) -> Self::Output { - let operand = self.push_operand64(Operand64::<i64>::new(value))?; - self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) + fn visit_i64_const(&mut self, value: i64) -> Result<()> { + let instruction = if self.emitter.optimizations_enabled() + && let Ok(value) = i32::try_from(value) + { + Instruction::Const64Imm(value) + } else { + Instruction::Const64(self.push64(Operand64::<i64>::new(value))?) + }; + self.emit(&[], &[ValueLane::S64], instruction) } - fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output { + fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Result<()> { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(dst_table, src_table))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(dst_table, src_table))?; self.emit(&[dst, src, len], &[], Instruction::TableCopy(operand)) } - fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { + fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Result<()> { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; self.mark_memory(dst_mem); self.mark_memory(src_mem); let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(dst_mem, src_mem))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(dst_mem, src_mem))?; self.emit(&[dst, src, len], &[], Instruction::MemoryCopy(operand)) } - fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Self::Output { + fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Result<()> { let dst = self.metadata.memory_size(memory)?; self.mark_memory(memory); - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(data_index, memory))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(data_index, memory))?; self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(operand)) } - fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Self::Output { + fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Result<()> { let address = self.metadata.table_size(table)?; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(elem_index, table))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(elem_index, table))?; self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand)) } - fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, data_index))?; + fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Result<()> { + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, data_index))?; self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewData(operand)) } - fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; + fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Result<()> { + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewElem(operand)) } - fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, data_index))?; + fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Result<()> { + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, data_index))?; self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitData(operand)) } - fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; + fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Result<()> { + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitElem(operand)) } - fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Self::Output { - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index_dst, type_index_src))?; + fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Result<()> { + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index_dst, type_index_src))?; self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand)) } @@ -1069,7 +1127,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { relative_depth: u32, _from_ref_type: wasmparser::RefType, to_ref_type: wasmparser::RefType, - ) -> Self::Output { + ) -> Result<()> { self.emit_cast_branch(relative_depth, to_ref_type, false) } @@ -1078,33 +1136,33 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { relative_depth: u32, _from_ref_type: wasmparser::RefType, to_ref_type: wasmparser::RefType, - ) -> Self::Output { + ) -> Result<()> { self.emit_cast_branch(relative_depth, to_ref_type, true) } - fn visit_br_on_null(&mut self, relative_depth: u32) -> Self::Output { + fn visit_br_on_null(&mut self, relative_depth: u32) -> Result<()> { self.pop_expect(ValueLane::S32)?; - let fallthrough_jump = self.instructions.len(); - self.instructions.push(Instruction::JumpIfRefNonNull(0)); + let fallthrough = self.emitter.new_label(); + self.emitter.branch(Instruction::JumpIfRefNonNull(0), fallthrough)?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; - self.patch_jump(fallthrough_jump, self.instructions.len()); + self.emitter.bind(fallthrough)?; self.push_sizes(&[ValueLane::S32]) } - fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Self::Output { + fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Result<()> { self.pop_expect(ValueLane::S32)?; - let fallthrough_jump = self.instructions.len(); - self.instructions.push(Instruction::JumpIfRefNull(0)); + let fallthrough = self.emitter.new_label(); + self.emitter.branch(Instruction::JumpIfRefNull(0), fallthrough)?; self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.pop_expect(ValueLane::S32)?; self.emit_branch_jump_or_return(relative_depth)?; - self.patch_jump(fallthrough_jump, self.instructions.len()); + self.emitter.bind(fallthrough)?; Ok(()) } - fn visit_typed_select_multi(&mut self, tys: Vec<wasmparser::ValType>) -> Self::Output { + fn visit_typed_select_multi(&mut self, tys: Vec<wasmparser::ValType>) -> Result<()> { let sizes: Vec<_> = tys.into_iter().map(value_lane).collect(); let counts = Self::value_counts(&sizes); self.emit( @@ -1114,7 +1172,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { ) } - fn visit_typed_select(&mut self, ty: wasmparser::ValType) -> Self::Output { + fn visit_typed_select(&mut self, ty: wasmparser::ValType) -> Result<()> { let size = value_lane(ty); let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128); self.emit(&[size, size, ValueLane::S32], &[size], instruction) @@ -1129,7 +1187,7 @@ macro_rules! impl_visit_simd_operator { (@@simd $($rest:tt)* ) => {}; (@@relaxed_simd $($rest:tt)* ) => {}; (@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => { - fn $visit(&mut self $($(,$arg: $argty)*)?) -> Self::Output { + fn $visit(&mut self $($(,$arg: $argty)*)?) -> Result<()> { Err(crate::ParseError::UnsupportedOperator(stringify!($visit).to_string())) } }; @@ -1148,7 +1206,7 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { visit_v128_load64_splat => V128Load64Splat, visit_v128_load32_zero => V128Load32Zero, visit_v128_load64_zero => V128Load64Zero, } - memory [Addr, S128] => [] { visit_v128_store => V128Store } + memory [Addr, S128] => [] { visit_v128_store => V128Store [store128()] } memory [Addr, S128] => [S128] { visit_v128_load8_lane(lane: u8) => V128Load8Lane, visit_v128_load16_lane(lane: u8) => V128Load16Lane, @@ -1237,8 +1295,11 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { visit_i32x4_relaxed_trunc_f64x2_u_zero => I32x4RelaxedTruncF64x2UZero, } fixed [S128, S128] => [S128] { - visit_v128_and => V128And, visit_v128_andnot => V128AndNot, visit_v128_or => V128Or, - visit_v128_xor => V128Xor, visit_i8x16_swizzle => I8x16Swizzle, visit_i8x16_eq => I8x16Eq, + visit_v128_and => V128And [vector(BinOp128::And, true)], + visit_v128_andnot => V128AndNot [vector(BinOp128::AndNot, false)], + visit_v128_or => V128Or [vector(BinOp128::Or, true)], + visit_v128_xor => V128Xor [vector(BinOp128::Xor, true)], + visit_i8x16_swizzle => I8x16Swizzle, visit_i8x16_eq => I8x16Eq, visit_i8x16_ne => I8x16Ne, visit_i8x16_lt_s => I8x16LtS, visit_i8x16_lt_u => I8x16LtU, visit_i8x16_gt_s => I8x16GtS, visit_i8x16_gt_u => I8x16GtU, visit_i8x16_le_s => I8x16LeS, visit_i8x16_le_u => I8x16LeU, visit_i8x16_ge_s => I8x16GeS, visit_i8x16_ge_u => I8x16GeU, @@ -1269,8 +1330,10 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { visit_i16x8_sub_sat_u => I16x8SubSatU, visit_i16x8_avgr_u => I16x8AvgrU, visit_i16x8_mul => I16x8Mul, visit_i32x4_add => I32x4Add, visit_i32x4_sub => I32x4Sub, visit_i32x4_min_s => I32x4MinS, visit_i32x4_min_u => I32x4MinU, visit_i32x4_max_s => I32x4MaxS, - visit_i32x4_max_u => I32x4MaxU, visit_i32x4_mul => I32x4Mul, visit_i64x2_add => I64x2Add, - visit_i64x2_sub => I64x2Sub, visit_i64x2_mul => I64x2Mul, + visit_i32x4_max_u => I32x4MaxU, visit_i32x4_mul => I32x4Mul, + visit_i64x2_add => I64x2Add [vector(BinOp128::I64x2Add, true)], + visit_i64x2_sub => I64x2Sub, + visit_i64x2_mul => I64x2Mul [vector(BinOp128::I64x2Mul, true)], visit_i16x8_extmul_low_i8x16_s => I16x8ExtMulLowI8x16S, visit_i16x8_extmul_low_i8x16_u => I16x8ExtMulLowI8x16U, visit_i16x8_extmul_high_i8x16_s => I16x8ExtMulHighI8x16S, @@ -1307,18 +1370,24 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } } - fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { - let index = self.push_operand128(Operand128::<[u8; 16]>::new(lanes))?; + fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Result<()> { + let index = self.push128(Operand128::<[u8; 16]>::new(lanes))?; self.emit(&[ValueLane::S128, ValueLane::S128], &[ValueLane::S128], Instruction::I8x16Shuffle(index)) } - fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output { - let index = self.push_operand128(Operand128::<[u8; 16]>::new(*value.bytes()))?; - self.emit(&[], &[ValueLane::S128], Instruction::Const128(index)) + fn visit_v128_const(&mut self, value: wasmparser::V128) -> Result<()> { + let instruction = if self.emitter.optimizations_enabled() + && let Ok(value) = u32::try_from(u128::from_le_bytes(*value.bytes())) + { + Instruction::Const128Imm(value) + } else { + Instruction::Const128(self.push128(Operand128::<[u8; 16]>::new(*value.bytes()))?) + }; + self.emit(&[], &[ValueLane::S128], instruction) } } -impl FunctionBuilder<'_> { +impl<'a> FunctionBuilder<'a> { fn emit_cast_branch( &mut self, relative_depth: u32, @@ -1327,17 +1396,16 @@ impl FunctionBuilder<'_> { ) -> Result<()> { self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; - let conditional_ip = self.instructions.len(); - let operand = self.data.push_target_operand64(Operand64::<(u32, u32)>::new(0, target.to_bits()))?; - self.instructions.push(if branch_on_fail { - Instruction::BrOnCastFail(operand) - } else { - Instruction::BrOnCast(operand) - }); + let fallthrough = self.emitter.new_label(); + let operand = self.data.push_target64(Operand64::<(u32, u32)>::new(0, target.to_bits()))?; + self.emitter.branch( + if branch_on_fail { Instruction::BrOnCastFail(operand) } else { Instruction::BrOnCast(operand) }, + fallthrough, + )?; self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; - self.patch_jump(conditional_ip, self.instructions.len()); + self.emitter.bind(fallthrough)?; Ok(()) } @@ -1411,8 +1479,26 @@ impl FunctionBuilder<'_> { /// Applies an instruction's stack effect before adding it to the bytecode. fn emit(&mut self, inputs: &[ValueLane], outputs: &[ValueLane], instruction: Instruction) -> Result<()> { self.apply_effect(inputs, outputs)?; - self.instructions.push(instruction); - Ok(()) + self.emitter.emit(instruction) + } + + /// Applies stack effects and seals a call or terminator's instruction boundary. + fn emit_boundary(&mut self, inputs: &[ValueLane], outputs: &[ValueLane], instruction: Instruction) -> Result<()> { + self.apply_effect(inputs, outputs)?; + self.emitter.emit_boundary(instruction) + } + + /// Applies logical stack effects before invoking a statically selected rule family. + #[inline] + fn emit_with( + &mut self, + inputs: &[ValueLane], + outputs: &[ValueLane], + instruction: Instruction, + rules: impl FnOnce(&mut crate::emitter::PendingTail<'_>, &mut FunctionDataBuilder) -> Result<()>, + ) -> Result<()> { + self.apply_effect(inputs, outputs)?; + self.emitter.emit_with(&mut self.data, instruction, rules) } /// Restores both logical operand order and lane counts to a control-frame base. @@ -1431,42 +1517,42 @@ impl FunctionBuilder<'_> { } } - /// Enters a control frame with its parameters restored above the saved base. - fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, initial_jump: Option<usize>) -> Result<()> { - let signature = self.block_signature(ty)?; - self.push_control_signature(kind, signature, initial_jump) - } - - fn block_signature(&self, ty: wasmparser::BlockType) -> Result<Signature> { + fn block_signature(&self, ty: wasmparser::BlockType) -> Result<BlockSignature<'a>> { Ok(match ty { - wasmparser::BlockType::Empty => Signature { params: Vec::new(), results: Vec::new() }, - wasmparser::BlockType::Type(ty) => Signature { params: Vec::new(), results: alloc::vec![value_lane(ty)] }, - wasmparser::BlockType::FuncType(idx) => self.metadata.signature(idx)?.clone(), + wasmparser::BlockType::Empty => BlockSignature::Empty, + wasmparser::BlockType::Type(ty) => BlockSignature::Result(value_lane(ty)), + wasmparser::BlockType::FuncType(idx) => BlockSignature::Function(self.metadata.signature(idx)?), }) } - fn push_control_signature( - &mut self, - kind: BlockKind, - signature: Signature, - initial_jump: Option<usize>, - ) -> Result<()> { - for &size in signature.params.iter().rev() { + /// Enters a control frame with its parameters restored above the saved base. + fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, else_entry: Option<LabelId>) -> Result<()> { + let signature = self.block_signature(ty)?; + for &size in signature.params().iter().rev() { self.pop_expect(size)?; } let height = self.operand_stack.len(); let base = self.lane_counts; - self.push_sizes(&signature.params)?; + self.push_sizes(signature.params())?; let entry_unreachable = self.is_unreachable(); + // Backedges are not known yet, so loop headers always seal the tail. + // Other constructs have no entry target and allocate exits on first use. + let loop_start = if matches!(kind, BlockKind::Loop) { + let start = self.emitter.new_label(); + self.emitter.bind(start)?; + Some(start) + } else { + None + }; self.control_stack.push(ControlFrame { kind, has_else: false, - start_ip: self.instructions.len(), - branch_jumps: initial_jump.into_iter().collect(), + loop_start, + end: None, + else_entry, height, base, - params: signature.params, - results: signature.results, + signature, unreachable: entry_unreachable, entry_unreachable, end_reachable: false, @@ -1475,34 +1561,23 @@ impl FunctionBuilder<'_> { } /// Emits the stack-shaping instruction required by a branch. - fn emit_dropkeep(&mut self, base: ValueCounts, keep: ValueCounts) { - let target = ValueCounts { c32: base.c32 + keep.c32, c64: base.c64 + keep.c64, c128: base.c128 + keep.c128 }; - if self.lane_counts.c32 != target.c32 { - self.instructions.push(Instruction::DropKeep32 { base: base.c32, keep: keep.c32 }); + fn emit_dropkeep(&mut self, base: ValueCounts, keep: ValueCounts) -> Result<()> { + if Some(self.lane_counts.c32) != base.c32.checked_add(keep.c32) { + self.emitter.emit(Instruction::DropKeep32 { base: base.c32, keep: keep.c32 })?; } - if self.lane_counts.c64 != target.c64 { - self.instructions.push(Instruction::DropKeep64 { base: base.c64, keep: keep.c64 }); + if Some(self.lane_counts.c64) != base.c64.checked_add(keep.c64) { + self.emitter.emit(Instruction::DropKeep64 { base: base.c64, keep: keep.c64 })?; } - if self.lane_counts.c128 != target.c128 { - self.instructions.push(Instruction::DropKeep128 { base: base.c128, keep: keep.c128 }); + if Some(self.lane_counts.c128) != base.c128.checked_add(keep.c128) { + self.emitter.emit(Instruction::DropKeep128 { base: base.c128, keep: keep.c128 })?; } + Ok(()) } - fn patch_jump(&mut self, jump_ip: usize, target: usize) { - match &mut self.instructions[jump_ip] { - Instruction::Jump(ip) - | Instruction::JumpIfZero32(ip) - | Instruction::JumpIfNonZero32(ip) - | Instruction::JumpIfRefNull(ip) - | Instruction::JumpIfRefNonNull(ip) => { - *ip = target as u32; - } - Instruction::BrOnCast(index) | Instruction::BrOnCastFail(index) => { - let operand = self.data.operand64(*index); - self.data.set_operand64(*index, operand.with_target(target as u32)); - } - _ => {} - } + fn needs_dropkeep(&self, base: ValueCounts, keep: ValueCounts) -> bool { + Some(self.lane_counts.c32) != base.c32.checked_add(keep.c32) + || Some(self.lane_counts.c64) != base.c64.checked_add(keep.c64) + || Some(self.lane_counts.c128) != base.c128.checked_add(keep.c128) } fn value_counts(sizes: &[ValueLane]) -> ValueCounts { @@ -1524,39 +1599,24 @@ impl FunctionBuilder<'_> { } let frame = &self.control_stack[self.get_ctx_idx(label_depth)?]; let base = frame.base; - let label_types = if matches!(frame.kind, BlockKind::Loop) { &frame.params } else { &frame.results }; - self.emit_dropkeep(base, Self::value_counts(label_types)); - Ok(()) + let label_types = + if matches!(frame.kind, BlockKind::Loop) { frame.signature.params() } else { frame.signature.results() }; + self.emit_dropkeep(base, Self::value_counts(label_types)) } fn emit_branch_jump_or_return(&mut self, depth: u32) -> Result<()> { let ctx_idx = self.get_ctx_idx(depth)?; match self.control_stack[ctx_idx].kind { - BlockKind::Function => self.instructions.push(Instruction::Return), - BlockKind::Loop => self.instructions.push(Instruction::Jump(self.control_stack[ctx_idx].start_ip as u32)), - BlockKind::Block | BlockKind::If | BlockKind::TryTable(_) => { - self.control_stack[ctx_idx].branch_jumps.push(self.instructions.len()); + BlockKind::Function => self.emitter.emit_boundary(Instruction::Return)?, + BlockKind::Loop => { + self.emitter.branch(Instruction::Jump(0), self.control_stack[ctx_idx].loop_start.unwrap())? + } + BlockKind::Block | BlockKind::If | BlockKind::TryTable => { self.control_stack[ctx_idx].end_reachable = true; - self.instructions.push(Instruction::Jump(0)); + let end = *self.control_stack[ctx_idx].end.get_or_insert_with(|| self.emitter.new_label()); + self.emitter.branch(Instruction::Jump(0), end)?; } } Ok(()) } - - /// Resolves all jumps owned by a completed control frame. - fn patch_end_jumps(&mut self, ctx: ControlFrame, end_ip: usize) { - let target = if matches!(ctx.kind, BlockKind::Loop) { ctx.start_ip } else { end_ip }; - let mut jumps = ctx.branch_jumps.as_slice(); - if matches!(ctx.kind, BlockKind::If) - && let Some((cond_jump, branch_jumps)) = jumps.split_first() - { - if !ctx.has_else { - self.patch_jump(*cond_jump, end_ip); - } - jumps = branch_jumps; - } - for &jump in jumps { - self.patch_jump(jump, target); - } - } } |
