summaryrefslogtreecommitdiff
path: root/crates/types/src
diff options
context:
space:
mode:
authorHenry Gressmann <mail@henrygressmann.de>2026-08-17 20:07:51 +0200
committerGitHub <noreply@github.com>2026-08-17 20:07:51 +0200
commit358a183e5c12c32b8836acf9c71799f56e00b036 (patch)
treeffe63de847cebf5935951454eb8d76d9c76c222a /crates/types/src
parenta42cb3434bd79accb6a49298f498e016e9c93b9e (diff)
chore: reduce instruction enum size (#52)
this is a fairly big commit since I've been just playing around with this for a while now. the main goal is to reduce instruction size by moving some operands into two separate vecs. memory operations still seem like the biggest issue right now, so as a follow op I'll probably remove the public linear memory trait again but let's see how this goes first. performance wise this is about the same as before, but serialization/deserialization is about 20% faster now. Signed-off-by: Henry <mail@henrygressmann.de> --------- Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates/types/src')
-rw-r--r--crates/types/src/archive.rs26
-rw-r--r--crates/types/src/instructions.rs795
-rw-r--r--crates/types/src/lib.rs13
-rw-r--r--crates/types/src/operands.rs177
-rw-r--r--crates/types/src/reference.rs12
5 files changed, 795 insertions, 228 deletions
diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs
index 9904a7d..db40263 100644
--- a/crates/types/src/archive.rs
+++ b/crates/types/src/archive.rs
@@ -64,6 +64,9 @@ impl Module {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::{Instruction, ModuleInner, V128Operand, WasmFunction};
+ use crate::{OperandIdx, OperandType};
+ use alloc::{boxed::Box, sync::Arc, vec};
#[test]
fn test_invalid_magic() {
@@ -80,4 +83,27 @@ mod tests {
twasm[4] = 0;
assert!(matches!(Module::try_from_twasm(&twasm), Err(TwasmError::InvalidVersion)));
}
+
+ #[test]
+ fn v128_operands_round_trip_archive() {
+ let bytes = [0x00, 0x01, 0x02, 0x03, 0x7f, 0x80, 0xfe, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x90];
+ let mut function = WasmFunction::default();
+ let constant = OperandIdx::new(0);
+ function.data.operands128 = vec![V128Operand { value: bytes }.encode()].into_boxed_slice();
+ function.instructions = vec![Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)].into();
+ let module = Module::from(ModuleInner { funcs: Box::new([Arc::new(function)]), ..ModuleInner::default() });
+
+ let archive = module.serialize_twasm().expect("serialize archive");
+ assert_eq!(&archive[..6], b"TWAS05");
+ let decoded = Module::try_from_twasm(&archive).expect("deserialize archive");
+ let function = &decoded.funcs[0];
+
+ for instruction in function.instructions.iter() {
+ let index = match instruction {
+ Instruction::Const128(index) | Instruction::I8x16Shuffle(index) => *index,
+ _ => panic!("unexpected instruction"),
+ };
+ assert_eq!(index.get(&function.data).value, bytes);
+ }
+ }
}
diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs
index 10ab028..797f703 100644
--- a/crates/types/src/instructions.rs
+++ b/crates/types/src/instructions.rs
@@ -1,7 +1,8 @@
use alloc::boxed::Box;
use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts};
-use crate::{ConstIdx, DataAddr, ElemAddr, MemAddr, RefType, RefValue};
+use crate::operands::sealed;
+use crate::{DataAddr, ElemAddr, MemAddr, Operand64, Operand128, OperandIdx, OperandType, RefType, RefValue};
/// Represents a memory immediate in a WebAssembly memory instruction.
#[derive(Copy, Clone, PartialEq, Eq)]
@@ -13,13 +14,275 @@ pub struct MemoryArg {
mem_addr: MemAddr,
}
-/// Stack lanes discarded and retained when branching to a control frame.
-#[derive(Clone, Copy, PartialEq, Eq)]
+/// A compact memory immediate used by optimized instructions.
+///
+/// Optimized instructions use this representation when the offset and
+/// module-local memory index fit its narrower fields.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[repr(Rust, packed)]
+pub struct CompactMemoryArg {
+ offset: u32,
+ mem_addr: u16,
+}
+
+/// An indexed memory argument and up to two local operands.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[repr(Rust, packed)]
+pub struct MemoryLocalArg {
+ pub memory_arg_idx: OperandIdx<CompactMemoryArg>,
+ pub local1: u8,
+ pub local2: u8,
+}
+
+/// An indexed memory argument and SIMD lane.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[repr(Rust, packed)]
+pub struct MemoryLaneArg {
+ pub memory_arg_idx: OperandIdx<MemoryArg>,
+ pub lane: u8,
+}
+
+/// A 32-bit immediate and local operand that fit in an instruction payload.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[repr(Rust, packed)]
+pub struct I32LocalArg {
+ pub value: i32,
+ pub local: LocalAddr,
+}
+
+/// Three local operands that fit in an instruction payload.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub struct LocalTripleArg {
+ pub left: LocalAddr,
+ pub right: LocalAddr,
+ pub dst: LocalAddr,
+}
+
+impl sealed::Sealed for LocalTripleArg {}
+
+impl OperandType for LocalTripleArg {
+ type Raw = Operand64;
+
+ #[inline(always)]
+ fn decode(raw: Self::Raw) -> Self {
+ Self { left: raw.u16::<0>(), right: raw.u16::<2>(), dst: raw.u16::<4>() }
+ }
+
+ #[inline]
+ fn encode(self) -> Self::Raw {
+ Operand64::default().with_u16::<0>(self.left).with_u16::<2>(self.right).with_u16::<4>(self.dst)
+ }
+}
+
+/// A branch target and local operand that fit in an instruction payload.
+#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub struct DropKeep {
- pub base: ValueCounts,
- pub keep: ValueCounts,
+#[repr(Rust, packed)]
+pub struct TargetLocalArg {
+ pub target_ip: u32,
+ pub local: LocalAddr,
+}
+
+macro_rules! operand_view {
+ ($name:ident, $lane:ident, $raw:ty, { $($field:ident : $ty:ty = $read:ident / $write:ident ($offset:expr)),+ $(,)? }) => {
+ #[derive(Copy, Clone, PartialEq, Eq)]
+ #[cfg_attr(feature = "debug", derive(Debug))]
+ pub struct $name {
+ $(pub $field: $ty),+
+ }
+
+ impl sealed::Sealed for $name {}
+
+ impl OperandType for $name {
+ type Raw = $raw;
+
+ #[inline(always)]
+ fn decode(raw: Self::Raw) -> Self {
+ Self { $($field: raw.$read::<$offset>() as $ty),+ }
+ }
+
+ #[inline]
+ fn encode(self) -> Self::Raw {
+ <$raw>::default()$(.$write::<$offset>(self.$field as _))+
+ }
+ }
+ };
+}
+
+operand_view!(I64Operand, operands64, Operand64, { value: i64 = u64 / with_u64(0) });
+operand_view!(TwoU32, operands64, Operand64, {
+ first: u32 = u32 / with_u32(0), second: u32 = u32 / with_u32(4)
+});
+operand_view!(LocalU32, operands64, Operand64, {
+ local: u16 = u16 / with_u16(0), value: u32 = u32 / with_u32(2)
+});
+operand_view!(TargetLocal, operands64, Operand64, {
+ target: u32 = u32 / with_u32(0), local: u16 = u16 / with_u16(4)
+});
+
+operand_view!(LocalConst64, operands128, Operand128, {
+ local: u16 = u16 / with_u16(0), value: u64 = u64 / with_u64(2)
+});
+operand_view!(GlobalConst32, operands64, Operand64, {
+ global: u32 = u32 / with_u32(0), value: u32 = u32 / with_u32(4)
+});
+operand_view!(GlobalConst64, operands128, Operand128, {
+ global: u32 = u32 / with_u32(0), value: u64 = u64 / with_u64(4)
+});
+operand_view!(LocalConstSet32, operands64, Operand64, {
+ local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u32 = u32 / with_u32(4)
+});
+operand_view!(LocalConstSet64, operands128, Operand128, {
+ local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u64 = u64 / with_u64(4)
+});
+operand_view!(MemoryFillConstOp, operands128, Operand128, {
+ memory: u32 = u32 / with_u32(0), byte: u8 = u8 / with_u8(4), value: i32 = u32 / with_u32(5)
+});
+operand_view!(CastBranch, operands64, Operand64, {
+ target: u32 = u32 / with_u32(0), ref_type_bits: u32 = u32 / with_u32(4)
+});
+operand_view!(BranchTableArg, operands128, Operand128, {
+ target: u32 = u32 / with_u32(0), start: u32 = u32 / with_u32(4), len: u32 = u32 / with_u32(8)
+});
+operand_view!(StackConst32, operands64, Operand64, {
+ target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4)
+});
+operand_view!(StackConst64, operands128, Operand128, {
+ target: u32 = u32 / with_u32(0), value: i64 = u64 / with_u64(4)
+});
+operand_view!(LocalConstCmp, operands128, Operand128, {
+ target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8)
+});
+operand_view!(LocalLocalCmp, operands64, Operand64, {
+ target: u32 = u32 / with_u32(0), left: u16 = u16 / with_u16(4), right: u16 = u16 / with_u16(6)
+});
+operand_view!(LocalUpdate, operands128, Operand128, {
+ target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), on_zero: u8 = u8 / with_u8(10)
+});
+operand_view!(GlobalUpdate, operands128, Operand128, {
+ target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), global: u32 = u32 / with_u32(8), on_zero: u8 = u8 / with_u8(12)
+});
+operand_view!(LocalUpdateCmp, operands128, Operand128, {
+ target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), right: u16 = u16 / with_u16(10)
+});
+
+/// An operation packed inline with an indexed operand.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[cfg_attr(
+ feature = "archive",
+ serde(bound(serialize = "Op: Copy + serde::Serialize", deserialize = "Op: Copy + serde::de::DeserializeOwned",))
+)]
+#[repr(Rust, packed)]
+pub struct PackedOp<Op, T> {
+ pub op: Op,
+ pub index: OperandIdx<T>,
+}
+
+impl<Op, T> PackedOp<Op, T> {
+ /// Creates a packed operation from an operator and operand index.
+ #[inline]
+ pub const fn new(op: Op, index: OperandIdx<T>) -> Self {
+ Self { op, index }
+ }
+}
+
+/// A SIMD value stored in the 128-bit operand lane.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct V128Operand {
+ pub value: [u8; 16],
+}
+
+/// A local SIMD operation with an indexed constant.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct LocalV128 {
+ pub local: u16,
+ pub value: OperandIdx<V128Operand>,
+}
+
+/// A global SIMD operation with an indexed constant.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct GlobalV128 {
+ pub global: u32,
+ pub value: OperandIdx<V128Operand>,
+}
+
+/// A local SIMD operation, indexed constant, and destination local.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct LocalConstSetV128 {
+ pub local: u16,
+ pub dst: u16,
+ pub value: OperandIdx<V128Operand>,
+}
+
+macro_rules! operand_raw_view {
+ ($name:ident, $raw:ty, $decode:expr, $encode:expr) => {
+ impl sealed::Sealed for $name {}
+
+ impl OperandType for $name {
+ type Raw = $raw;
+
+ #[inline(always)]
+ fn decode(raw: Self::Raw) -> Self {
+ $decode(raw)
+ }
+
+ #[inline]
+ fn encode(self) -> Self::Raw {
+ $encode(self)
+ }
+ }
+ };
+}
+
+operand_raw_view!(V128Operand, Operand128, |raw: Operand128| Self { value: raw.to_le_bytes() }, |value: Self| {
+ Operand128::from_le_bytes(value.value)
+});
+operand_raw_view!(
+ LocalV128,
+ Operand64,
+ |raw: Operand64| Self { local: raw.u16::<0>(), value: OperandIdx::new(raw.u32::<2>()) },
+ |value: Self| { Operand64::default().with_u16::<0>(value.local).with_u32::<2>(value.value.index()) }
+);
+operand_raw_view!(
+ GlobalV128,
+ Operand64,
+ |raw: Operand64| Self { global: raw.u32::<0>(), value: OperandIdx::new(raw.u32::<4>()) },
+ |value: Self| { Operand64::default().with_u32::<0>(value.global).with_u32::<4>(value.value.index()) }
+);
+operand_raw_view!(
+ LocalConstSetV128,
+ Operand64,
+ |raw: Operand64| Self { local: raw.u16::<0>(), dst: raw.u16::<2>(), value: OperandIdx::new(raw.u32::<4>()) },
+ |value: Self| {
+ Operand64::default().with_u16::<0>(value.local).with_u16::<2>(value.dst).with_u32::<4>(value.value.index())
+ }
+);
+
+impl CastBranch {
+ #[inline]
+ pub const fn ref_type(self) -> RefType {
+ match RefType::from_bits(self.ref_type_bits) {
+ Some(value) => value,
+ None => unreachable!(),
+ }
+ }
}
/// A catch clause attached to a lowered `try_table` instruction.
@@ -62,12 +325,6 @@ pub struct ExceptionHandler {
pub catches: Box<[ExceptionCatch]>,
}
-impl From<(ValueCounts, ValueCounts)> for DropKeep {
- fn from((base, keep): (ValueCounts, ValueCounts)) -> Self {
- Self { base, keep }
- }
-}
-
impl MemoryArg {
#[inline]
pub const fn new(offset: u64, mem_addr: MemAddr) -> Self {
@@ -85,6 +342,80 @@ impl MemoryArg {
}
}
+impl sealed::Sealed for MemoryArg {}
+
+impl OperandType for MemoryArg {
+ type Raw = Operand128;
+
+ #[inline(always)]
+ fn decode(raw: Self::Raw) -> Self {
+ Self::new(raw.u64::<0>(), raw.u32::<8>())
+ }
+
+ #[inline]
+ fn encode(self) -> Self::Raw {
+ Operand128::default().with_u64::<0>(self.offset).with_u32::<8>(self.mem_addr)
+ }
+}
+
+impl CompactMemoryArg {
+ /// Returns the static byte offset.
+ #[inline]
+ pub const fn offset(self) -> u64 {
+ self.offset as u64
+ }
+
+ /// Returns the module-local memory index.
+ #[inline]
+ pub const fn mem_addr(self) -> MemAddr {
+ self.mem_addr as MemAddr
+ }
+}
+
+impl sealed::Sealed for CompactMemoryArg {}
+
+impl OperandType for CompactMemoryArg {
+ type Raw = Operand64;
+
+ #[inline(always)]
+ fn decode(raw: Self::Raw) -> Self {
+ Self { offset: raw.u32::<0>(), mem_addr: raw.u16::<4>() }
+ }
+
+ #[inline]
+ fn encode(self) -> Self::Raw {
+ Operand64::default().with_u32::<0>(self.offset).with_u16::<4>(self.mem_addr)
+ }
+}
+
+impl TryFrom<MemoryArg> for CompactMemoryArg {
+ type Error = ();
+
+ #[inline]
+ fn try_from(arg: MemoryArg) -> Result<Self, Self::Error> {
+ Ok(Self {
+ offset: u32::try_from(arg.offset()).map_err(|_| ())?,
+ mem_addr: u16::try_from(arg.mem_addr()).map_err(|_| ())?,
+ })
+ }
+}
+
+impl From<CompactMemoryArg> for MemoryArg {
+ #[inline]
+ fn from(arg: CompactMemoryArg) -> Self {
+ Self::new(arg.offset(), arg.mem_addr())
+ }
+}
+
+const _: () = {
+ assert!(core::mem::size_of::<OperandIdx<I64Operand>>() == 4);
+ assert!(core::mem::size_of::<Operand64>() == 8);
+ assert!(core::mem::size_of::<Operand128>() == 16);
+ assert!(core::mem::size_of::<CompactMemoryArg>() == 6);
+ assert!(core::mem::size_of::<MemoryLocalArg>() == 6);
+ assert!(core::mem::size_of::<LocalTripleArg>() == 6);
+};
+
#[derive(Clone, Copy, PartialEq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -132,6 +463,25 @@ pub enum CmpOp {
GeU,
}
+impl CmpOp {
+ /// Returns the comparison that is true exactly when `self` is false.
+ #[inline]
+ pub const fn inverse(self) -> Self {
+ match self {
+ Self::Eq => Self::Ne,
+ Self::Ne => Self::Eq,
+ Self::LtS => Self::GeS,
+ Self::LtU => Self::GeU,
+ Self::GtS => Self::LeS,
+ Self::GtU => Self::LeU,
+ Self::LeS => Self::GtS,
+ Self::LeU => Self::GtU,
+ Self::GeS => Self::LtS,
+ Self::GeU => Self::LtU,
+ }
+ }
+}
+
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -156,6 +506,18 @@ pub enum BinOp {
FCopysign,
}
+impl BinOp {
+ /// Returns the update delta for `local OP immediate`, when it is a simple increment.
+ #[inline]
+ pub const fn inc_delta(self, immediate: i32) -> Option<i32> {
+ match self {
+ Self::IAdd => Some(immediate),
+ Self::ISub => Some(immediate.wrapping_neg()),
+ _ => None,
+ }
+ }
+}
+
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -181,69 +543,47 @@ pub enum BinOp128 {
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
pub enum Instruction {
LocalCopy32(LocalAddr, LocalAddr), LocalCopy64(LocalAddr, LocalAddr), LocalCopy128(LocalAddr, LocalAddr),
- AddConst32(i32), AddConst64(i64),
- IncLocal32(LocalAddr, i32), IncLocal64(LocalAddr, i64),
+ AddConst32(i32), AddConst64(OperandIdx<I64Operand>),
+ IncLocal32(I32LocalArg), IncLocal64(PackedOp<LocalAddr, I64Operand>),
// The 32/64 suffix describes the operand width. Future compare-style ops may still yield i32 results.
BinOpLocalLocal32(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal64(BinOp, LocalAddr, LocalAddr),
BinOpLocalLocal128(BinOp128, LocalAddr, LocalAddr),
CmpLocalLocal32(CmpOp, LocalAddr, LocalAddr), CmpLocalLocal64(CmpOp, LocalAddr, LocalAddr),
- BinOpLocalLocalSet32(BinOp, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalLocalSet64(BinOp, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalLocalSet128(BinOp128, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalLocalTee32(BinOp, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalLocalTee64(BinOp, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalLocalTee128(BinOp128, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalConst32(BinOp, LocalAddr, i32), BinOpLocalConst64(BinOp, LocalAddr, i64),
- BinOpGlobalConst32(BinOp, GlobalAddr, i32), BinOpGlobalConst64(BinOp, GlobalAddr, i64),
- BinOpGlobalConst128(BinOp128, GlobalAddr, ConstIdx),
- BinOpLocalConst128(BinOp128, LocalAddr, ConstIdx),
- BinOpLocalConstSet32(BinOp, LocalAddr, i32, LocalAddr),
- BinOpLocalConstSet64(BinOp, LocalAddr, i64, LocalAddr),
- BinOpLocalConstSet128(BinOp128, LocalAddr, ConstIdx, LocalAddr),
- BinOpLocalConstTee32(BinOp, LocalAddr, i32, LocalAddr),
- BinOpLocalConstTee64(BinOp, LocalAddr, i64, LocalAddr),
- BinOpLocalConstTee128(BinOp128, LocalAddr, ConstIdx, LocalAddr),
+ AddLocalLocalSet32(LocalTripleArg), AddLocalLocalTee32(LocalTripleArg),
+ BinOpLocalLocalSet32(PackedOp<BinOp, LocalTripleArg>), BinOpLocalLocalSet64(PackedOp<BinOp, LocalTripleArg>), BinOpLocalLocalSet128(PackedOp<BinOp128, LocalTripleArg>),
+ BinOpLocalLocalTee32(PackedOp<BinOp, LocalTripleArg>), BinOpLocalLocalTee64(PackedOp<BinOp, LocalTripleArg>), BinOpLocalLocalTee128(PackedOp<BinOp128, LocalTripleArg>),
+ AddLocalConst32(I32LocalArg), SubLocalConst32(I32LocalArg), MulLocalConst32(I32LocalArg),
+ BinOpLocalConst32(PackedOp<BinOp, LocalU32>), BinOpLocalConst64(PackedOp<BinOp, LocalConst64>),
+ BinOpGlobalConst32(PackedOp<BinOp, GlobalConst32>), BinOpGlobalConst64(PackedOp<BinOp, GlobalConst64>),
+ BinOpGlobalConst128(PackedOp<BinOp128, GlobalV128>), BinOpLocalConst128(PackedOp<BinOp128, LocalV128>),
+ BinOpLocalConstSet32(PackedOp<BinOp, LocalConstSet32>), BinOpLocalConstSet64(PackedOp<BinOp, LocalConstSet64>), BinOpLocalConstSet128(PackedOp<BinOp128, LocalConstSetV128>),
+ BinOpLocalConstTee32(PackedOp<BinOp, LocalConstSet32>), BinOpLocalConstTee64(PackedOp<BinOp, LocalConstSet64>), BinOpLocalConstTee128(PackedOp<BinOp128, LocalConstSetV128>),
BinOpStackLocal32(BinOp, LocalAddr),
BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr),
BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr),
+ BinOpStackLocal128(BinOp128, LocalAddr),
BinOpStackGlobal32(BinOp, u32),
BinOpStackGlobal64(BinOp, u32),
- SetLocalConst32(LocalAddr, i32), SetLocalConst64(LocalAddr, i64), SetLocalConst128(LocalAddr, ConstIdx),
- IncMemoryLocal32(MemoryArg, u8),
- IncMemoryLocal64(MemoryArg, u8),
- StoreLocalLocal32(MemoryArg, u8, u8),
- StoreLocalLocal64(MemoryArg, u8, u8),
- StoreLocalLocal128(MemoryArg, u8, u8),
- LoadLocal32(MemoryArg, u8),
- LoadLocal64(MemoryArg, u8),
- LoadLocal8S32(MemoryArg, u8),
- LoadLocal8U32(MemoryArg, u8),
- LoadLocal16S32(MemoryArg, u8),
- LoadLocal16U32(MemoryArg, u8),
- LoadLocalTee32(MemoryArg, u8, u8),
- LoadLocalSet32(MemoryArg, u8, u8),
- LoadLocalTee8S32(MemoryArg, u8, u8),
- LoadLocalTee8U32(MemoryArg, u8, u8),
- LoadLocalTee16S32(MemoryArg, u8, u8),
- LoadLocalTee16U32(MemoryArg, u8, u8),
- LoadLocalSet8S32(MemoryArg, u8, u8),
- LoadLocalSet8U32(MemoryArg, u8, u8),
- LoadLocalSet16S32(MemoryArg, u8, u8),
- LoadLocalSet16U32(MemoryArg, u8, u8),
- LoadLocalTee128(MemoryArg, u8, u8),
- LoadLocalSet128(MemoryArg, u8, u8),
- AndConstTee32(i32, LocalAddr),
- SubConstTee32(i32, LocalAddr),
- AndConstTee64(i64, LocalAddr),
- SubConstTee64(i64, LocalAddr),
- MulAccLocal32(LocalAddr),
- MulAccLocal64(LocalAddr),
- FMulAccLocal32(LocalAddr),
- FMulAccLocal64(LocalAddr),
+ SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp<LocalAddr, I64Operand>), SetLocalConst128(PackedOp<LocalAddr, V128Operand>),
+ IncMemoryLocal32(MemoryLocalArg), IncMemoryLocal64(MemoryLocalArg),
+ StoreLocalLocal32(MemoryLocalArg), StoreLocalLocal64(MemoryLocalArg), StoreLocalLocal128(MemoryLocalArg),
+ LoadLocal32(MemoryLocalArg), LoadLocal64(MemoryLocalArg),
+ LoadLocal8S32(MemoryLocalArg), LoadLocal8U32(MemoryLocalArg),
+ LoadLocal16S32(MemoryLocalArg), LoadLocal16U32(MemoryLocalArg),
+ LoadLocalTee32(MemoryLocalArg), LoadLocalSet32(MemoryLocalArg),
+ LoadLocalTee8S32(MemoryLocalArg), LoadLocalTee8U32(MemoryLocalArg),
+ LoadLocalTee16S32(MemoryLocalArg), LoadLocalTee16U32(MemoryLocalArg),
+ LoadLocalSet8S32(MemoryLocalArg), LoadLocalSet8U32(MemoryLocalArg),
+ LoadLocalSet16S32(MemoryLocalArg), LoadLocalSet16U32(MemoryLocalArg),
+ LoadLocalTee128(MemoryLocalArg), LoadLocalSet128(MemoryLocalArg),
+ AndConstTee32(I32LocalArg), SubConstTee32(I32LocalArg),
+ AndConstTee64(PackedOp<LocalAddr, I64Operand>), SubConstTee64(PackedOp<LocalAddr, I64Operand>),
+ MulAccLocal32(LocalAddr), MulAccLocal64(LocalAddr),
+ FMulAccLocal32(LocalAddr), FMulAccLocal64(LocalAddr),
I32Add3,
I64Add3,
- FMaStoreF32(MemoryArg),
- FMaStoreF64(MemoryArg),
+ FMaStoreF32(CompactMemoryArg),
+ FMaStoreF64(CompactMemoryArg),
// > Control Instructions (jump-oriented, lowered from structured control during parsing)
// See <https://webassembly.github.io/spec/core/binary/instructions.html#control-instructions>
@@ -255,28 +595,16 @@ pub enum Instruction {
JumpIfNonZero64(u32),
JumpIfRefNull(u32),
JumpIfRefNonNull(u32),
- JumpIfLocalZero32 { target_ip: u32, local: LocalAddr },
- JumpIfLocalNonZero32 { target_ip: u32, local: LocalAddr },
- JumpIfLocalZero64 { target_ip: u32, local: LocalAddr },
- JumpIfLocalNonZero64 { target_ip: u32, local: LocalAddr },
- JumpCmpStackConst32 { target_ip: u32, imm: i32, op: CmpOp },
- JumpCmpStackConst64 { target_ip: u32, imm: i64, op: CmpOp },
- JumpCmpStackLocal32 { target_ip: u32, local: LocalAddr, op: CmpOp },
- JumpCmpStackLocal64 { target_ip: u32, local: LocalAddr, op: CmpOp },
- BinOpLocalConstJump32 { target_ip: u32, local: LocalAddr, imm: i32, op: BinOp, on_zero: bool },
- BinOpLocalConstJumpCmpLocal32 { target_ip: u32, local: LocalAddr, imm: i32, binop: BinOp, right: LocalAddr, cmp: CmpOp },
- BinOpStackConstTeeLocalJump32 { target_ip: u32, local: LocalAddr, imm: i32, op: BinOp, on_zero: bool },
- BinOpGlobalConstJump32 { target_ip: u32, global: GlobalAddr, imm: i32, op: BinOp, on_zero: bool },
- IncLocalJump32 { target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool },
- IncStackTeeLocalJump32 { target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool },
- IncGlobalJump32 { target_ip: u32, global: GlobalAddr, delta: i32, on_zero: bool },
- IncLocalJumpCmpLocal32 { target_ip: u32, local: LocalAddr, delta: i32, right: LocalAddr, op: CmpOp },
- JumpCmpLocalConst32 { target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp },
- JumpCmpLocalConst64 { target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp },
- JumpCmpLocalLocal32 { target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp },
- JumpCmpLocalLocal64 { target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp },
- DropKeep(DropKeep),
- BranchTable(u32, u32, u32), // (default_landing_pad_ip, branch_table_start, target_count)
+ JumpIfLocalZero32(TargetLocalArg), JumpIfLocalNonZero32(TargetLocalArg),
+ JumpIfLocalZero64(TargetLocalArg), JumpIfLocalNonZero64(TargetLocalArg),
+ JumpCmpStackConst32(PackedOp<CmpOp, StackConst32>), JumpCmpStackConst64(PackedOp<CmpOp, StackConst64>),
+ JumpCmpStackLocal32(PackedOp<CmpOp, TargetLocal>), JumpCmpStackLocal64(PackedOp<CmpOp, TargetLocal>),
+ BinOpLocalConstJump32(PackedOp<BinOp, LocalUpdate>), BinOpLocalConstJumpCmpLocal32(PackedOp<(BinOp, CmpOp), LocalUpdateCmp>),
+ BinOpStackConstTeeLocalJump32(PackedOp<BinOp, LocalUpdate>), BinOpGlobalConstJump32(PackedOp<BinOp, GlobalUpdate>),
+ IncLocalJump32(OperandIdx<LocalUpdate>), IncStackTeeLocalJump32(OperandIdx<LocalUpdate>), IncGlobalJump32(OperandIdx<GlobalUpdate>),
+ IncLocalJumpCmpLocal32(PackedOp<CmpOp, LocalUpdateCmp>), JumpCmpLocalConst32(PackedOp<CmpOp, LocalConstCmp>), JumpCmpLocalConst64(PackedOp<CmpOp, LocalConstCmp>),
+ JumpCmpLocalLocal32(PackedOp<CmpOp, LocalLocalCmp>), JumpCmpLocalLocal64(PackedOp<CmpOp, LocalLocalCmp>),
+ DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(OperandIdx<BranchTableArg>),
Return,
ReturnVoid,
Return32,
@@ -284,11 +612,11 @@ pub enum Instruction {
Return128,
Call(FuncAddr),
CallSelf,
- CallIndirect(TypeAddr, TableAddr),
+ CallIndirect(OperandIdx<TwoU32>),
CallRef(TypeAddr),
ReturnCall(FuncAddr),
ReturnCallSelf,
- ReturnCallIndirect(TypeAddr, TableAddr),
+ ReturnCallIndirect(OperandIdx<TwoU32>),
ReturnCallRef(TypeAddr),
Throw(TagAddr),
ThrowRef,
@@ -307,35 +635,18 @@ pub enum Instruction {
GlobalGet128(GlobalAddr), GlobalSet128(GlobalAddr), GlobalTee128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr),
// > Memory Instructions
- I32Load(MemoryArg),
- I64Load(MemoryArg),
- F32Load(MemoryArg),
- F64Load(MemoryArg),
- I32Load8S(MemoryArg),
- I32Load8U(MemoryArg),
- I32Load16S(MemoryArg),
- I32Load16U(MemoryArg),
- I64Load8S(MemoryArg),
- I64Load8U(MemoryArg),
- I64Load16S(MemoryArg),
- I64Load16U(MemoryArg),
- I64Load32S(MemoryArg),
- I64Load32U(MemoryArg),
- I32Store(MemoryArg),
- I64Store(MemoryArg),
- F32Store(MemoryArg),
- F64Store(MemoryArg),
- I32Store8(MemoryArg),
- I32Store16(MemoryArg),
- I64Store8(MemoryArg),
- I64Store16(MemoryArg),
- I64Store32(MemoryArg),
+ I32Load(OperandIdx<MemoryArg>), I64Load(OperandIdx<MemoryArg>), F32Load(OperandIdx<MemoryArg>), F64Load(OperandIdx<MemoryArg>),
+ I32Load8S(OperandIdx<MemoryArg>), I32Load8U(OperandIdx<MemoryArg>), I32Load16S(OperandIdx<MemoryArg>), I32Load16U(OperandIdx<MemoryArg>),
+ I64Load8S(OperandIdx<MemoryArg>), I64Load8U(OperandIdx<MemoryArg>), I64Load16S(OperandIdx<MemoryArg>), I64Load16U(OperandIdx<MemoryArg>), I64Load32S(OperandIdx<MemoryArg>), I64Load32U(OperandIdx<MemoryArg>),
+ I32Store(OperandIdx<MemoryArg>), I64Store(OperandIdx<MemoryArg>), F32Store(OperandIdx<MemoryArg>), F64Store(OperandIdx<MemoryArg>),
+ I32Store8(OperandIdx<MemoryArg>), I32Store16(OperandIdx<MemoryArg>), I64Store8(OperandIdx<MemoryArg>), I64Store16(OperandIdx<MemoryArg>), I64Store32(OperandIdx<MemoryArg>),
MemorySize(MemAddr),
MemoryGrow(MemAddr),
// > Constants
Const32(i32),
- Const64(i64),
+ Const64Imm(i32),
+ Const64(OperandIdx<I64Operand>),
// > Reference Types
RefNull(RefType),
@@ -348,29 +659,24 @@ pub enum Instruction {
RefEq,
RefTest(RefType),
RefCast(RefType),
- BrOnCast(u32, RefType, bool),
+ BrOnCast(OperandIdx<CastBranch>),
+ BrOnCastFail(OperandIdx<CastBranch>),
// > GC Objects
StructNew(TypeAddr),
StructNewDefault(TypeAddr),
- StructGet(TypeAddr, u32),
- StructGetS(TypeAddr, u32),
- StructGetU(TypeAddr, u32),
- StructSet(TypeAddr, u32),
+ StructGet(OperandIdx<TwoU32>), StructGetS(OperandIdx<TwoU32>), StructGetU(OperandIdx<TwoU32>), StructSet(OperandIdx<TwoU32>),
ArrayNew(TypeAddr),
ArrayNewDefault(TypeAddr),
- ArrayNewFixed(TypeAddr, u32),
- ArrayNewData(TypeAddr, DataAddr),
- ArrayNewElem(TypeAddr, ElemAddr),
+ ArrayNewFixed(OperandIdx<TwoU32>),
+ ArrayNewData(OperandIdx<TwoU32>), ArrayNewElem(OperandIdx<TwoU32>),
ArrayGet(TypeAddr),
ArrayGetS(TypeAddr),
ArrayGetU(TypeAddr),
ArraySet(TypeAddr),
ArrayLen,
ArrayFill(TypeAddr),
- ArrayCopy(TypeAddr, TypeAddr),
- ArrayInitData(TypeAddr, DataAddr),
- ArrayInitElem(TypeAddr, ElemAddr),
+ ArrayCopy(OperandIdx<TwoU32>), ArrayInitData(OperandIdx<TwoU32>), ArrayInitElem(OperandIdx<TwoU32>),
// > Numeric Instructions
// See <https://webassembly.github.io/spec/core/binary/instructions.html#numeric-instructions>
@@ -400,19 +706,18 @@ pub enum Instruction {
I64TruncSatF32S, I64TruncSatF32U, I64TruncSatF64S, I64TruncSatF64U,
// > Table Instructions
- TableInit(ElemAddr, TableAddr),
+ TableInit(OperandIdx<TwoU32>),
TableGet(TableAddr),
TableSet(TableAddr),
- TableCopy { dst_table: TableAddr, src_table: TableAddr },
+ TableCopy(OperandIdx<TwoU32>),
TableGrow(TableAddr),
TableSize(TableAddr),
TableFill(TableAddr),
// > Bulk Memory Instructions
- MemoryInit(DataAddr, MemAddr),
- MemoryCopy { dst_mem: MemAddr, src_mem: MemAddr },
+ MemoryInit(OperandIdx<TwoU32>), MemoryCopy(OperandIdx<TwoU32>),
MemoryFill(MemAddr),
- MemoryFillImm(MemAddr, u8, i32),
+ MemoryFillConst(OperandIdx<MemoryFillConstOp>),
DataDrop(DataAddr),
ElemDrop(ElemAddr),
@@ -420,20 +725,18 @@ pub enum Instruction {
I64Add128, I64Sub128, I64MulWideS, I64MulWideU,
// > SIMD
- V128Load(MemoryArg),
- V128Load8x8S(MemoryArg), V128Load8x8U(MemoryArg),
- V128Load16x4S(MemoryArg), V128Load16x4U(MemoryArg),
- V128Load32x2S(MemoryArg), V128Load32x2U(MemoryArg),
+ V128Load(OperandIdx<MemoryArg>), V128Load8x8S(OperandIdx<MemoryArg>), V128Load8x8U(OperandIdx<MemoryArg>),
+ V128Load16x4S(OperandIdx<MemoryArg>), V128Load16x4U(OperandIdx<MemoryArg>), V128Load32x2S(OperandIdx<MemoryArg>), V128Load32x2U(OperandIdx<MemoryArg>),
- V128Load8Splat(MemoryArg), V128Load16Splat(MemoryArg), V128Load32Splat(MemoryArg), V128Load64Splat(MemoryArg),
- V128Load8Lane(MemoryArg, u8), V128Load16Lane(MemoryArg, u8), V128Load32Lane(MemoryArg, u8), V128Load64Lane(MemoryArg, u8),
+ V128Load8Splat(OperandIdx<MemoryArg>), V128Load16Splat(OperandIdx<MemoryArg>), V128Load32Splat(OperandIdx<MemoryArg>), V128Load64Splat(OperandIdx<MemoryArg>),
+ V128Load8Lane(MemoryLaneArg), V128Load16Lane(MemoryLaneArg), V128Load32Lane(MemoryLaneArg), V128Load64Lane(MemoryLaneArg),
- V128Load32Zero(MemoryArg), V128Load64Zero(MemoryArg),
+ V128Load32Zero(OperandIdx<MemoryArg>), V128Load64Zero(OperandIdx<MemoryArg>),
- V128Store(MemoryArg), V128Store8Lane(MemoryArg, u8), V128Store16Lane(MemoryArg, u8), V128Store32Lane(MemoryArg, u8), V128Store64Lane(MemoryArg, u8),
+ V128Store(OperandIdx<MemoryArg>), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg),
- I8x16Shuffle(ConstIdx),
- Const128(ConstIdx),
+ I8x16Shuffle(OperandIdx<V128Operand>),
+ Const128Imm(u32), Const128(OperandIdx<V128Operand>),
I8x16ExtractLaneS(u8), I8x16ExtractLaneU(u8), I8x16ReplaceLane(u8),
I16x8ExtractLaneS(u8), I16x8ExtractLaneU(u8), I16x8ReplaceLane(u8),
@@ -485,10 +788,8 @@ pub enum Instruction {
I32x4RelaxedTruncF64x2SZero, I32x4RelaxedTruncF64x2UZero,
F32x4RelaxedMadd, F32x4RelaxedNmadd,
F64x2RelaxedMadd, F64x2RelaxedNmadd,
- I8x16RelaxedLaneselect,
- I16x8RelaxedLaneselect,
- I32x4RelaxedLaneselect,
- I64x2RelaxedLaneselect,
+ I8x16RelaxedLaneselect, I16x8RelaxedLaneselect,
+ I32x4RelaxedLaneselect, I64x2RelaxedLaneselect,
F32x4RelaxedMin, F32x4RelaxedMax,
F64x2RelaxedMin, F64x2RelaxedMax,
I16x8RelaxedQ15mulrS,
@@ -496,88 +797,144 @@ pub enum Instruction {
I32x4RelaxedDotI8x16I7x16AddS,
}
-const _: () = assert!(core::mem::size_of::<Instruction>() <= 16);
+const _: () = assert!(core::mem::size_of::<Instruction>() == 8);
impl Instruction {
+ /// Returns the largest module-local memory index used by this instruction.
#[inline]
- pub const fn memory_addr(&self) -> Option<MemAddr> {
- match self {
- Self::IncMemoryLocal32(arg, ..)
- | Self::IncMemoryLocal64(arg, ..)
- | Self::StoreLocalLocal32(arg, ..)
- | Self::StoreLocalLocal64(arg, ..)
- | Self::StoreLocalLocal128(arg, ..)
- | Self::LoadLocal32(arg, ..)
- | Self::LoadLocal64(arg, ..)
- | Self::LoadLocal8S32(arg, ..)
- | Self::LoadLocal8U32(arg, ..)
- | Self::LoadLocal16S32(arg, ..)
- | Self::LoadLocal16U32(arg, ..)
- | Self::LoadLocalTee32(arg, ..)
- | Self::LoadLocalSet32(arg, ..)
- | Self::LoadLocalTee8S32(arg, ..)
- | Self::LoadLocalTee8U32(arg, ..)
- | Self::LoadLocalTee16S32(arg, ..)
- | Self::LoadLocalTee16U32(arg, ..)
- | Self::LoadLocalSet8S32(arg, ..)
- | Self::LoadLocalSet8U32(arg, ..)
- | Self::LoadLocalSet16S32(arg, ..)
- | Self::LoadLocalSet16U32(arg, ..)
- | Self::LoadLocalTee128(arg, ..)
- | Self::LoadLocalSet128(arg, ..)
- | Self::I32Load(arg)
- | Self::I64Load(arg)
- | Self::F32Load(arg)
- | Self::F64Load(arg)
- | Self::I32Load8S(arg)
- | Self::I32Load8U(arg)
- | Self::I32Load16S(arg)
- | Self::I32Load16U(arg)
- | Self::I64Load8S(arg)
- | Self::I64Load8U(arg)
- | Self::I64Load16S(arg)
- | Self::I64Load16U(arg)
- | Self::I64Load32S(arg)
- | Self::I64Load32U(arg)
- | Self::I32Store(arg)
- | Self::I64Store(arg)
- | Self::F32Store(arg)
- | Self::F64Store(arg)
- | Self::FMaStoreF32(arg)
- | Self::FMaStoreF64(arg)
- | Self::I32Store8(arg)
- | Self::I32Store16(arg)
- | Self::I64Store8(arg)
- | Self::I64Store16(arg)
- | Self::I64Store32(arg)
- | Self::V128Load(arg)
- | Self::V128Load8x8S(arg)
- | Self::V128Load8x8U(arg)
- | Self::V128Load16x4S(arg)
- | Self::V128Load16x4U(arg)
- | Self::V128Load32x2S(arg)
- | Self::V128Load32x2U(arg)
- | Self::V128Load8Splat(arg)
- | Self::V128Load16Splat(arg)
- | Self::V128Load32Splat(arg)
- | Self::V128Load64Splat(arg)
- | Self::V128Load8Lane(arg, ..)
- | Self::V128Load16Lane(arg, ..)
- | Self::V128Load32Lane(arg, ..)
- | Self::V128Load64Lane(arg, ..)
- | Self::V128Load32Zero(arg)
- | Self::V128Load64Zero(arg)
- | Self::V128Store(arg)
- | Self::V128Store8Lane(arg, ..)
- | Self::V128Store16Lane(arg, ..)
- | Self::V128Store32Lane(arg, ..)
- | Self::V128Store64Lane(arg, ..) => Some(arg.mem_addr()),
- Self::MemorySize(mem) | Self::MemoryGrow(mem) | Self::MemoryFill(mem) | Self::MemoryFillImm(mem, ..) => {
- Some(*mem)
+ pub fn memory_addr(&self, data: &super::WasmFunctionData) -> Option<MemAddr> {
+ use Instruction::*;
+ match *self {
+ IncMemoryLocal32(arg)
+ | IncMemoryLocal64(arg)
+ | StoreLocalLocal32(arg)
+ | StoreLocalLocal64(arg)
+ | StoreLocalLocal128(arg)
+ | LoadLocal32(arg)
+ | LoadLocal64(arg)
+ | LoadLocal8S32(arg)
+ | LoadLocal8U32(arg)
+ | LoadLocal16S32(arg)
+ | LoadLocal16U32(arg)
+ | LoadLocalTee32(arg)
+ | LoadLocalSet32(arg)
+ | LoadLocalTee8S32(arg)
+ | LoadLocalTee8U32(arg)
+ | LoadLocalTee16S32(arg)
+ | LoadLocalTee16U32(arg)
+ | LoadLocalSet8S32(arg)
+ | LoadLocalSet8U32(arg)
+ | LoadLocalSet16S32(arg)
+ | LoadLocalSet16U32(arg)
+ | LoadLocalTee128(arg)
+ | LoadLocalSet128(arg) => Some(arg.memory_arg_idx.get(data).mem_addr()),
+ I32Load(index)
+ | I64Load(index)
+ | F32Load(index)
+ | F64Load(index)
+ | I32Load8S(index)
+ | I32Load8U(index)
+ | I32Load16S(index)
+ | I32Load16U(index)
+ | I64Load8S(index)
+ | I64Load8U(index)
+ | I64Load16S(index)
+ | I64Load16U(index)
+ | I64Load32S(index)
+ | I64Load32U(index)
+ | I32Store(index)
+ | I64Store(index)
+ | F32Store(index)
+ | F64Store(index)
+ | I32Store8(index)
+ | I32Store16(index)
+ | I64Store8(index)
+ | I64Store16(index)
+ | I64Store32(index)
+ | V128Load(index)
+ | V128Load8x8S(index)
+ | V128Load8x8U(index)
+ | V128Load16x4S(index)
+ | V128Load16x4U(index)
+ | V128Load32x2S(index)
+ | V128Load32x2U(index)
+ | V128Load8Splat(index)
+ | V128Load16Splat(index)
+ | V128Load32Splat(index)
+ | V128Load64Splat(index)
+ | V128Load32Zero(index)
+ | V128Load64Zero(index)
+ | V128Store(index) => Some(index.get(data).mem_addr()),
+ V128Load8Lane(arg) | V128Load16Lane(arg) | V128Load32Lane(arg) | V128Load64Lane(arg)
+ | V128Store8Lane(arg) | V128Store16Lane(arg) | V128Store32Lane(arg) | V128Store64Lane(arg) => {
+ Some(arg.memory_arg_idx.get(data).mem_addr())
+ }
+ FMaStoreF32(arg) | FMaStoreF64(arg) => Some(arg.mem_addr()),
+ MemorySize(memory) | MemoryGrow(memory) | MemoryFill(memory) => Some(memory),
+ MemoryFillConst(index) => Some(index.get(data).memory),
+ MemoryInit(index) => Some(index.get(data).second),
+ MemoryCopy(index) => {
+ let value = index.get(data);
+ Some(value.first.max(value.second))
}
- Self::MemoryInit(_, mem) => Some(*mem),
- Self::MemoryCopy { dst_mem, src_mem } => Some(if *dst_mem >= *src_mem { *dst_mem } else { *src_mem }),
_ => None,
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use alloc::vec;
+
+ use super::*;
+
+ #[test]
+ fn compact_instruction_layout_is_exact() {
+ assert_eq!(core::mem::size_of::<Instruction>(), 8);
+ assert_eq!(core::mem::size_of::<CompactMemoryArg>(), 6);
+ assert_eq!(core::mem::size_of::<MemoryLocalArg>(), 6);
+ assert_eq!(core::mem::size_of::<LocalTripleArg>(), 6);
+ }
+
+ #[test]
+ fn operand_lanes_round_trip_max_values() {
+ let memory = MemoryArg::new(u64::MAX, u32::MAX);
+ assert_eq!(MemoryArg::decode(memory.encode()), memory);
+
+ let value = Operand128::default()
+ .with_u8::<0>(u8::MAX)
+ .with_u16::<1>(u16::MAX)
+ .with_u32::<3>(u32::MAX)
+ .with_u64::<7>(u64::MAX);
+ assert_eq!(
+ (value.u8::<0>(), value.u16::<1>(), value.u32::<3>(), value.u64::<7>()),
+ (u8::MAX, u16::MAX, u32::MAX, u64::MAX)
+ );
+
+ let bytes = [u8::MAX; 16];
+ assert_eq!(Operand128::from_le_bytes(bytes).to_le_bytes(), bytes);
+ }
+
+ #[test]
+ fn v128_operand_views_round_trip_max_bytes() {
+ let value = OperandIdx::<V128Operand>::new(0);
+ let local = OperandIdx::<LocalV128>::new(0);
+ let global = OperandIdx::<GlobalV128>::new(1);
+ let set = OperandIdx::<LocalConstSetV128>::new(2);
+ let data = super::super::WasmFunctionData {
+ operands128: vec![V128Operand { value: [u8::MAX; 16] }.encode()].into_boxed_slice(),
+ operands64: vec![
+ LocalV128 { local: u16::MAX, value }.encode(),
+ GlobalV128 { global: u32::MAX, value }.encode(),
+ LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }.encode(),
+ ]
+ .into_boxed_slice(),
+ ..Default::default()
+ };
+
+ assert_eq!(value.get(&data).value, [u8::MAX; 16]);
+ assert_eq!(local.get(&data), LocalV128 { local: u16::MAX, value });
+ assert_eq!(global.get(&data), GlobalV128 { global: u32::MAX, value });
+ assert_eq!(set.get(&data), LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value });
+ }
+}
diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs
index 9a7071c..bd92753 100644
--- a/crates/types/src/lib.rs
+++ b/crates/types/src/lib.rs
@@ -22,10 +22,12 @@ const fn max_page_count(arch: MemoryArch, page_size: u64) -> u64 {
}
mod instructions;
+mod operands;
mod reference;
mod types;
mod value;
pub use instructions::*;
+pub use operands::*;
pub use reference::*;
pub use types::*;
pub use value::*;
@@ -472,19 +474,12 @@ pub struct WasmFunction {
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
pub struct WasmFunctionData {
- pub v128_constants: Box<[[u8; 16]]>,
+ pub operands64: Box<[Operand64]>,
+ pub operands128: Box<[Operand128]>,
pub branch_table_targets: Box<[u32]>,
pub exception_handlers: Box<[ExceptionHandler]>,
}
-impl WasmFunctionData {
- /// Panics if `idx` is out of bounds.
- #[inline(always)]
- pub fn v128_const(&self, idx: ConstIdx) -> [u8; 16] {
- *self.v128_constants.get(idx as usize).unwrap_or_else(|| unreachable!("invalid v128 constant index: {idx}"))
- }
-}
-
/// A WebAssembly Module Export
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs
new file mode 100644
index 0000000..3cc311c
--- /dev/null
+++ b/crates/types/src/operands.rs
@@ -0,0 +1,177 @@
+use core::marker::PhantomData;
+
+use crate::WasmFunctionData;
+
+/// An index into the operand lane used by `T`.
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[cfg_attr(feature = "archive", serde(transparent))]
+#[repr(transparent)]
+pub struct OperandIdx<T> {
+ index: u32,
+ #[cfg_attr(feature = "archive", serde(skip))]
+ marker: PhantomData<T>,
+}
+
+impl<T> OperandIdx<T> {
+ #[inline]
+ #[doc(hidden)]
+ pub const fn new(index: u32) -> Self {
+ Self { index, marker: PhantomData }
+ }
+
+ /// Returns the underlying lane index.
+ #[inline]
+ pub const fn index(self) -> u32 {
+ self.index
+ }
+}
+
+impl<T: OperandType> OperandIdx<T> {
+ /// Returns the typed operand at this index.
+ ///
+ /// Panics if the index is outside its statically selected operand lane.
+ #[inline(always)]
+ pub fn get(self, data: &WasmFunctionData) -> T {
+ T::decode(T::Raw::get(data, self.index))
+ }
+}
+
+impl<T> Copy for OperandIdx<T> {}
+
+impl<T> Clone for OperandIdx<T> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<T> PartialEq for OperandIdx<T> {
+ fn eq(&self, other: &Self) -> bool {
+ self.index == other.index
+ }
+}
+
+impl<T> Eq for OperandIdx<T> {}
+
+#[cfg(feature = "debug")]
+impl<T> core::fmt::Debug for OperandIdx<T> {
+ fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ self.index.fmt(formatter)
+ }
+}
+
+pub(crate) mod sealed {
+ pub trait Sealed {}
+}
+
+/// A typed view stored in one of the per-function operand lanes.
+pub trait OperandType: sealed::Sealed + Copy {
+ #[doc(hidden)]
+ type Raw: RawOperand;
+
+ #[doc(hidden)]
+ fn decode(raw: Self::Raw) -> Self;
+ #[doc(hidden)]
+ fn encode(self) -> Self::Raw;
+}
+
+#[doc(hidden)]
+pub trait RawOperand: sealed::Sealed + Copy {
+ fn get(data: &WasmFunctionData, index: u32) -> Self;
+}
+
+macro_rules! define_operand {
+ ($name:ident, $len:literal, $lane:ident) => {
+ #[doc = concat!("Raw fields stored in a per-function ", $len, "-byte operand lane.")]
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
+ #[cfg_attr(feature = "debug", derive(Debug))]
+ #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+ #[repr(transparent)]
+ pub struct $name([u8; $len]);
+
+ impl sealed::Sealed for $name {}
+
+ impl RawOperand for $name {
+ #[inline(always)]
+ fn get(data: &WasmFunctionData, index: u32) -> Self {
+ *data.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index"))
+ }
+ }
+
+ impl $name {
+ /// Returns the byte at `OFFSET`.
+ #[inline]
+ pub fn u8<const OFFSET: usize>(self) -> u8 {
+ const { assert!(OFFSET < $len) };
+ self.0[OFFSET]
+ }
+
+ /// Returns the little-endian `u16` at `OFFSET`.
+ #[inline]
+ pub fn u16<const OFFSET: usize>(self) -> u16 {
+ const { assert!(OFFSET + 2 <= $len) };
+ u16::from_le_bytes(self.0[OFFSET..OFFSET + 2].try_into().unwrap_or_else(|_| unreachable!()))
+ }
+
+ /// Returns the little-endian `u32` at `OFFSET`.
+ #[inline]
+ pub fn u32<const OFFSET: usize>(self) -> u32 {
+ const { assert!(OFFSET + 4 <= $len) };
+ u32::from_le_bytes(self.0[OFFSET..OFFSET + 4].try_into().unwrap_or_else(|_| unreachable!()))
+ }
+
+ /// Returns the little-endian `u64` at `OFFSET`.
+ #[inline]
+ pub fn u64<const OFFSET: usize>(self) -> u64 {
+ const { assert!(OFFSET + 8 <= $len) };
+ u64::from_le_bytes(self.0[OFFSET..OFFSET + 8].try_into().unwrap_or_else(|_| unreachable!()))
+ }
+
+ /// Builds an operand from its raw little-endian bytes.
+ #[inline]
+ pub fn from_le_bytes(value: [u8; $len]) -> Self {
+ Self(value)
+ }
+
+ /// Returns the raw little-endian bytes.
+ #[inline]
+ pub fn to_le_bytes(self) -> [u8; $len] {
+ self.0
+ }
+
+ /// Writes `value` at `OFFSET` and returns the updated operand.
+ #[inline]
+ pub fn with_u8<const OFFSET: usize>(mut self, value: u8) -> Self {
+ const { assert!(OFFSET < $len) };
+ self.0[OFFSET] = value;
+ self
+ }
+
+ /// Writes `value` at `OFFSET` and returns the updated operand.
+ #[inline]
+ pub fn with_u16<const OFFSET: usize>(mut self, value: u16) -> Self {
+ const { assert!(OFFSET + 2 <= $len) };
+ self.0[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes());
+ self
+ }
+
+ /// Writes `value` at `OFFSET` and returns the updated operand.
+ #[inline]
+ pub fn with_u32<const OFFSET: usize>(mut self, value: u32) -> Self {
+ const { assert!(OFFSET + 4 <= $len) };
+ self.0[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes());
+ self
+ }
+
+ /// Writes `value` at `OFFSET` and returns the updated operand.
+ #[inline]
+ pub fn with_u64<const OFFSET: usize>(mut self, value: u64) -> Self {
+ const { assert!(OFFSET + 8 <= $len) };
+ self.0[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes());
+ self
+ }
+ }
+ };
+}
+
+define_operand!(Operand64, 8, operands64);
+define_operand!(Operand128, 16, operands128);
diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs
index 9ed5df1..ed59ae5 100644
--- a/crates/types/src/reference.rs
+++ b/crates/types/src/reference.rs
@@ -68,6 +68,18 @@ impl RefType {
pub const EXNREF: Self = Self::new_abstract(true, AbstractHeapType::Exn);
#[inline]
+ #[doc(hidden)]
+ pub const fn to_bits(self) -> u32 {
+ self.0
+ }
+
+ #[inline]
+ pub(crate) const fn from_bits(bits: u32) -> Option<Self> {
+ let ty = Self(bits);
+ if ty.is_concrete() || ty.abstract_heap_type().is_some() { Some(ty) } else { None }
+ }
+
+ #[inline]
pub const fn new_abstract(nullable: bool, heap_type: AbstractHeapType) -> Self {
Self((nullable as u32) << 31 | heap_type as u32)
}