Truly independent web browser
LibWasm: Add an AArch64 backend to the JIT
Andreas Kling9e6129ee0c6b
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rs b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rsnew file mode 100644index 00000000000..d14ffb316e7--- /dev/null+++ b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rs@@ -0,0 +1,575 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Encoders beyond what libjs_jit's code generation uses, for the WebAssembly JIT: scalar floating point of both+//! precisions, conversions, bit counting, LSE atomics, and Advanced SIMD (NEON).++use super::{Assembler, Cond, Fpr, Gpr, Width, rd, rm, rn, sf, vd, vm, vn};++/// The precision of a scalar floating point instruction (its `ftype` field).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FloatSize {+ Single,+ Double,+}++const fn ftype(size: FloatSize) -> u32 {+ match size {+ FloatSize::Single => 0,+ FloatSize::Double => 1 << 22,+ }+}++/// The scalar floating point instructions of two sources.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FloatBinary {+ Mul = 0b0000,+ Div = 0b0001,+ Add = 0b0010,+ Sub = 0b0011,+ Max = 0b0100,+ Min = 0b0101,+}++/// The scalar floating point instructions of one source.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FloatUnary {+ Mov = 0b000000,+ Abs = 0b000001,+ Neg = 0b000010,+ Sqrt = 0b000011,+ /// To nearest, ties to even.+ RoundNearest = 0b001000,+ /// Toward plus infinity.+ RoundUp = 0b001001,+ /// Toward minus infinity.+ RoundDown = 0b001010,+ /// Toward zero.+ RoundTowardZero = 0b001011,+}++/// The access size of an atomic instruction (its `size` field).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AtomicSize {+ Byte = 0,+ Half = 1,+ Word = 2,+ Double = 3,+}++impl AtomicSize {+ pub const fn from_log2(log2: u32) -> Self {+ match log2 {+ 0 => AtomicSize::Byte,+ 1 => AtomicSize::Half,+ 2 => AtomicSize::Word,+ _ => AtomicSize::Double,+ }+ }+}++/// The LSE read-modify-write instructions, in their sequentially consistent (acquire and release) forms.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AtomicRmw {+ /// `ldaddal`+ Add = 0b0000,+ /// `ldclral`: clears the bits set in the operand.+ Clear = 0b0001,+ /// `ldeoral`+ Xor = 0b0010,+ /// `ldsetal`+ Set = 0b0011,+ /// `swpal`+ Swap = 0b1000,+}++/// The arrangement of an Advanced SIMD register: the lane size and whether all 128 bits are used.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum VectorArrangement {+ B8,+ B16,+ H4,+ H8,+ S2,+ S4,+ D2,+}++impl VectorArrangement {+ /// The Q bit, at bit 30.+ pub const fn q(self) -> u32 {+ match self {+ VectorArrangement::B8 | VectorArrangement::H4 | VectorArrangement::S2 => 0,+ _ => 1 << 30,+ }+ }++ /// log2 of the lane size in bytes.+ pub const fn size(self) -> u32 {+ match self {+ VectorArrangement::B8 | VectorArrangement::B16 => 0,+ VectorArrangement::H4 | VectorArrangement::H8 => 1,+ VectorArrangement::S2 | VectorArrangement::S4 => 2,+ VectorArrangement::D2 => 3,+ }+ }+}++impl Assembler {+ /// Makes sure that the next `size` bytes of code go in one piece, without a veneer pool between them.+ pub fn reserve_room(&mut self, size: usize) {+ self.reserve(size);+ }++ // Integers.++ /// `clz rd, rn`.+ pub fn clz(&mut self, width: Width, rd_: Gpr, rn_: Gpr) {+ self.emit(0x5ac0_1000 | sf(width) | rn(rn_) | rd(rd_));+ }++ /// `rbit rd, rn`.+ pub fn rbit(&mut self, width: Width, rd_: Gpr, rn_: Gpr) {+ self.emit(0x5ac0_0000 | sf(width) | rn(rn_) | rd(rd_));+ }++ /// `ror rd, rn, #amount` (`extr rd, rn, rn, #amount`).+ pub fn ror_imm(&mut self, width: Width, rd_: Gpr, rn_: Gpr, amount: u8) {+ assert!(u32::from(amount) < width.bits(), "rotate amount out of range");+ let n = if width == Width::W64 { 1 << 22 } else { 0 };+ self.emit(0x1380_0000 | sf(width) | n | rm(rn_) | (u32::from(amount) << 10) | rn(rn_) | rd(rd_));+ }++ /// `add rd, rn, #imm`, for any 64-bit `imm`, through `scratch` where it does not fit an immediate. rd and rn+ /// may be SP.+ pub fn add_any(&mut self, rd_: Gpr, rn_: Gpr, imm: i64, scratch: Gpr) {+ let magnitude = imm.unsigned_abs();+ let negative = imm < 0;+ if magnitude < 4096 {+ if negative {+ self.sub_imm(Width::W64, rd_, rn_, magnitude as u32, false);+ } else {+ self.add_imm(Width::W64, rd_, rn_, magnitude as u32, false);+ }+ } else if magnitude & 0xfff == 0 && magnitude < (1 << 24) {+ if negative {+ self.sub_imm(Width::W64, rd_, rn_, (magnitude >> 12) as u32, true);+ } else {+ self.add_imm(Width::W64, rd_, rn_, (magnitude >> 12) as u32, true);+ }+ } else if magnitude < (1 << 24) {+ let (high, low) = ((magnitude >> 12) as u32, (magnitude & 0xfff) as u32);+ if negative {+ self.sub_imm(Width::W64, rd_, rn_, high, true);+ self.sub_imm(Width::W64, rd_, rd_, low, false);+ } else {+ self.add_imm(Width::W64, rd_, rn_, high, true);+ self.add_imm(Width::W64, rd_, rd_, low, false);+ }+ } else {+ self.mov_imm(Width::W64, scratch, imm as u64);+ self.add_extended(Width::W64, rd_, rn_, scratch, super::Extend::Uxtx, 0);+ }+ }++ // Scalar floating point.++ /// `fadd`, `fsub`, `fmul`, `fdiv`, `fmax` or `fmin` of either precision.+ pub fn float_binary(&mut self, op: FloatBinary, size: FloatSize, rd_: Fpr, rn_: Fpr, rm_: Fpr) {+ self.emit(0x1e20_0800 | ftype(size) | vm(rm_) | ((op as u32) << 12) | vn(rn_) | vd(rd_));+ }++ /// `fmov`, `fabs`, `fneg`, `fsqrt` or `frint*` of either precision.+ pub fn float_unary(&mut self, op: FloatUnary, size: FloatSize, rd_: Fpr, rn_: Fpr) {+ self.emit(0x1e20_4000 | ftype(size) | ((op as u32) << 15) | vn(rn_) | vd(rd_));+ }++ /// `fcmp sn, sm` or `fcmp dn, dm`: NZCV = unordered 0011, less 1000, equal 0110, greater 0010.+ pub fn float_compare(&mut self, size: FloatSize, rn_: Fpr, rm_: Fpr) {+ self.emit(0x1e20_2000 | ftype(size) | vm(rm_) | vn(rn_));+ }++ /// `fcsel rd, rn, rm, cond`.+ pub fn float_select(&mut self, size: FloatSize, rd_: Fpr, rn_: Fpr, rm_: Fpr, cond: Cond) {+ self.emit(0x1e20_0c00 | ftype(size) | vm(rm_) | ((cond as u32) << 12) | vn(rn_) | vd(rd_));+ }++ /// `fcvt`: from `from` to the other precision.+ pub fn float_convert(&mut self, from: FloatSize, rd_: Fpr, rn_: Fpr) {+ let opc = match from {+ FloatSize::Single => 0b01,+ FloatSize::Double => 0b00,+ };+ self.emit(0x1e22_4000 | ftype(from) | (opc << 15) | vn(rn_) | vd(rd_));+ }++ fn float_integer(&mut self, opcode: u32, width: Width, size: FloatSize, register_d: u32, register_n: u32) {+ self.emit(0x1e20_0000 | sf(width) | ftype(size) | (opcode << 16) | (register_n << 5) | register_d);+ }++ /// `scvtf` (signed) or `ucvtf`: the integer in `rn` (wn or xn) to a float.+ pub fn convert_to_float(&mut self, signed: bool, width: Width, size: FloatSize, rd_: Fpr, rn_: Gpr) {+ let opcode = if signed { 0b00_010 } else { 0b00_011 };+ self.float_integer(opcode, width, size, vd(rd_), u32::from(rn_.0 & 31));+ }++ /// `fcvtzs` (signed) or `fcvtzu`: truncates the float in `rn` toward zero, saturating, NaN giving 0.+ pub fn convert_to_integer(&mut self, signed: bool, width: Width, size: FloatSize, rd_: Gpr, rn_: Fpr) {+ let opcode = if signed { 0b11_000 } else { 0b11_001 };+ self.float_integer(opcode, width, size, rd(rd_), u32::from(rn_.0 & 31));+ }++ /// `fmov wd, sn` or `fmov xd, dn`: the bits of a float.+ pub fn float_to_gpr(&mut self, size: FloatSize, rd_: Gpr, rn_: Fpr) {+ let width = if size == FloatSize::Double {+ Width::W64+ } else {+ Width::W32+ };+ self.float_integer(0b00_110, width, size, rd(rd_), u32::from(rn_.0 & 31));+ }++ /// `fmov sd, wn` or `fmov dd, xn`: a float of the bits.+ pub fn gpr_to_float(&mut self, size: FloatSize, rd_: Fpr, rn_: Gpr) {+ let width = if size == FloatSize::Double {+ Width::W64+ } else {+ Width::W32+ };+ self.float_integer(0b00_111, width, size, vd(rd_), u32::from(rn_.0 & 31));+ }++ // Atomics.++ /// `ldar`, `ldarb` or `ldarh`: a load with acquire semantics, zero-extended.+ pub fn load_acquire(&mut self, size: AtomicSize, rt: Gpr, base: Gpr) {+ self.emit(((size as u32) << 30) | 0x08df_fc00 | rn(base) | rd(rt));+ }++ /// `stlr`, `stlrb` or `stlrh`: a store with release semantics.+ pub fn store_release(&mut self, size: AtomicSize, rt: Gpr, base: Gpr) {+ self.emit(((size as u32) << 30) | 0x089f_fc00 | rn(base) | rd(rt));+ }++ /// An LSE read-modify-write: `rt` = the old value at [base] (zero-extended), which becomes old op `rs`.+ pub fn atomic_rmw(&mut self, op: AtomicRmw, size: AtomicSize, rs: Gpr, rt: Gpr, base: Gpr) {+ let o3_opc = op as u32;+ self.emit(((size as u32) << 30) | 0x38e0_0000 | rm(rs) | (o3_opc << 12) | rn(base) | rd(rt));+ }++ /// `casal rs, rt, [base]`: if [base] equals `rs`, stores `rt`; `rs` becomes the old value (zero-extended).+ pub fn compare_and_swap(&mut self, size: AtomicSize, rs: Gpr, rt: Gpr, base: Gpr) {+ self.emit(((size as u32) << 30) | 0x08e0_fc00 | rm(rs) | rn(base) | rd(rt));+ }++ /// `dmb ish`.+ pub fn dmb_ish(&mut self) {+ self.emit(0xd503_3bbf);+ }++ /// Reads the virtual counter, `mrs xt, cntvct_el0`.+ pub fn read_counter(&mut self, rt: Gpr) {+ self.emit(0xd53b_e040 | rd(rt));+ }++ // Advanced SIMD.++ /// `mov vd.16b, vn.16b` (`orr`).+ pub fn mov_vector(&mut self, rd_: Fpr, rn_: Fpr) {+ self.emit(0x4ea0_1c00 | vm(rn_) | vn(rn_) | vd(rd_));+ }++ /// `ins vd.<T>[index], rn` (`mov`): lane `index` of lanes of `1 << size_log2` bytes from a general purpose register.+ pub fn insert_lane_from_gpr(&mut self, rd_: Fpr, size_log2: u32, index: u32, rn_: Gpr) {+ let imm5 = ((index << 1) | 1) << size_log2;+ self.emit(0x4e00_1c00 | (imm5 << 16) | rn(rn_) | vd(rd_));+ }++ /// `cnt vd.8b, vn.8b`: the set bits of each byte.+ pub fn vector_count_bits(&mut self, rd_: Fpr, rn_: Fpr) {+ self.emit(0x0e20_5800 | vn(rn_) | vd(rd_));+ }++ /// `addv`: the sum of the lanes of `rn`, in the lowest lane of `rd`.+ pub fn vector_add_across(&mut self, arrangement: VectorArrangement, rd_: Fpr, rn_: Fpr) {+ self.emit(0x0e31_b800 | arrangement.q() | (arrangement.size() << 22) | vn(rn_) | vd(rd_));+ }++ /// An Advanced SIMD "three same" instruction: `0 Q U 01110 size 1 Rm opcode 1 Rn Rd`. Float ones pass their+ /// size field (the high bit selects among operations, the low bit is the precision) as `size`.+ /// `operation` is the U bit and the opcode.+ pub fn vector_three_same(&mut self, q: bool, (u, opcode): (bool, u32), size: u32, rd_: Fpr, rn_: Fpr, rm_: Fpr) {+ self.emit(+ (u32::from(q) << 30)+ | (u32::from(u) << 29)+ | 0x0e20_0400+ | ((size & 3) << 22)+ | vm(rm_)+ | ((opcode & 31) << 11)+ | vn(rn_)+ | vd(rd_),+ );+ }++ /// An Advanced SIMD "three different" instruction (the long, wide and narrow ones): `0 Q U 01110 size 1 Rm opcode+ /// 00 Rn Rd`, where Q selects the second (high) half.+ /// `operation` is the U bit and the opcode.+ pub fn vector_three_different(+ &mut self,+ q: bool,+ (u, opcode): (bool, u32),+ size: u32,+ rd_: Fpr,+ rn_: Fpr,+ rm_: Fpr,+ ) {+ self.emit(+ (u32::from(q) << 30)+ | (u32::from(u) << 29)+ | 0x0e20_0000+ | ((size & 3) << 22)+ | vm(rm_)+ | ((opcode & 15) << 12)+ | vn(rn_)+ | vd(rd_),+ );+ }++ /// An Advanced SIMD "two-register miscellaneous" instruction: `0 Q U 01110 size 10000 opcode 10 Rn Rd`.+ pub fn vector_two_misc(&mut self, q: bool, u: bool, size: u32, opcode: u32, rd_: Fpr, rn_: Fpr) {+ self.emit(+ (u32::from(q) << 30)+ | (u32::from(u) << 29)+ | 0x0e20_0800+ | ((size & 3) << 22)+ | ((opcode & 31) << 12)+ | vn(rn_)+ | vd(rd_),+ );+ }++ /// An Advanced SIMD "across lanes" instruction: `0 Q U 01110 size 11000 opcode 10 Rn Rd`.+ pub fn vector_across(&mut self, q: bool, u: bool, size: u32, opcode: u32, rd_: Fpr, rn_: Fpr) {+ self.emit(+ (u32::from(q) << 30)+ | (u32::from(u) << 29)+ | 0x0e30_0800+ | ((size & 3) << 22)+ | ((opcode & 31) << 12)+ | vn(rn_)+ | vd(rd_),+ );+ }++ /// An Advanced SIMD shift by an immediate: `0 Q U 011110 immh:immb opcode 1 Rn Rd`. `immh_immb` is the 7-bit+ /// field, which encodes the lane size and the shift.+ pub fn vector_shift_immediate(&mut self, q: bool, u: bool, immh_immb: u32, opcode: u32, rd_: Fpr, rn_: Fpr) {+ self.emit(+ (u32::from(q) << 30)+ | (u32::from(u) << 29)+ | 0x0f00_0400+ | ((immh_immb & 0x7f) << 16)+ | ((opcode & 31) << 11)+ | vn(rn_)+ | vd(rd_),+ );+ }++ /// An Advanced SIMD permute (`uzp1`, `trn1`, `zip1`, ...): `0 Q 001110 size 0 Rm 0 opcode 10 Rn Rd`.+ pub fn vector_permute(&mut self, arrangement: VectorArrangement, opcode: u32, rd_: Fpr, rn_: Fpr, rm_: Fpr) {+ self.emit(+ arrangement.q()+ | 0x0e00_0800+ | (arrangement.size() << 22)+ | vm(rm_)+ | ((opcode & 7) << 12)+ | vn(rn_)+ | vd(rd_),+ );+ }++ /// `ext vd.16b, vn.16b, vm.16b, #index`: bytes `index` to `index + 15` of rm:rn.+ pub fn vector_extract(&mut self, rd_: Fpr, rn_: Fpr, rm_: Fpr, index: u32) {+ self.emit(0x6e00_0000 | vm(rm_) | ((index & 15) << 11) | vn(rn_) | vd(rd_));+ }++ /// `tbl vd.16b, {vn.16b .. vn+count-1.16b}, vm.16b`: a byte of the table per index, zero for indices past it.+ pub fn vector_table(&mut self, rd_: Fpr, rn_: Fpr, count: u32, rm_: Fpr) {+ self.emit(0x4e00_0000 | vm(rm_) | (((count - 1) & 3) << 13) | vn(rn_) | vd(rd_));+ }++ /// The copy instructions: `0 Q op 01110000 imm5 0 imm4 1 Rn Rd` (`dup`, `ins`, `smov`, `umov`).+ pub fn vector_copy(&mut self, q: bool, op: bool, imm5: u32, imm4: u32, rd_: u8, rn_: u8) {+ self.emit(+ (u32::from(q) << 30)+ | (u32::from(op) << 29)+ | 0x0e00_0400+ | ((imm5 & 31) << 16)+ | ((imm4 & 15) << 11)+ | (u32::from(rn_ & 31) << 5)+ | u32::from(rd_ & 31),+ );+ }++ /// The modified immediate instructions (`movi`, `mvni`, `orr`, `bic` of an immediate): `0 Q op 0111100000 abc+ /// cmode o2 1 defgh Rd`.+ pub fn vector_modified_immediate(&mut self, q: bool, op: bool, cmode: u32, imm8: u8, rd_: Fpr) {+ let imm8 = u32::from(imm8);+ self.emit(+ (u32::from(q) << 30)+ | (u32::from(op) << 29)+ | 0x0f00_0400+ | ((imm8 >> 5) << 16)+ | ((cmode & 15) << 12)+ | ((imm8 & 31) << 5)+ | vd(rd_),+ );+ }++ /// An Advanced SIMD scalar instruction of the "two-register miscellaneous" group, as `vector_two_misc()` with the+ /// scalar bit: `01 U 11110 size 10000 opcode 10 Rn Rd`.+ pub fn scalar_two_misc(&mut self, u: bool, size: u32, opcode: u32, rd_: Fpr, rn_: Fpr) {+ self.emit((u32::from(u) << 29) | 0x5e20_0800 | ((size & 3) << 22) | ((opcode & 31) << 12) | vn(rn_) | vd(rd_));+ }++ /// `ld1r {vt.<T>}, [rn]`: one lane loaded and replicated to all, `1 << size_log2` bytes.+ pub fn load_replicate(&mut self, size_log2: u32, rt: Fpr, rn_: Gpr) {+ self.emit(0x4d40_c000 | ((size_log2 & 3) << 10) | rn(rn_) | vd(rt));+ }++ /// `ld1 {vt.<T>}[index], [rn]`: one lane of `1 << size_log2` bytes loaded into lane `index`.+ pub fn load_lane(&mut self, size_log2: u32, index: u32, rt: Fpr, rn_: Gpr) {+ self.emit(0x0d40_0000 | single_structure_fields(size_log2, index) | rn(rn_) | vd(rt));+ }++ /// `st1 {vt.<T>}[index], [rn]`: lane `index` of `1 << size_log2` bytes stored.+ pub fn store_lane(&mut self, size_log2: u32, index: u32, rt: Fpr, rn_: Gpr) {+ self.emit(0x0d00_0000 | single_structure_fields(size_log2, index) | rn(rn_) | vd(rt));+ }+}++/// The Q, opcode, S and size fields of a single-structure load or store of lane `index`, `1 << size_log2` bytes.+const fn single_structure_fields(size_log2: u32, index: u32) -> u32 {+ // Q:S:size holds the index, scaled by the lane size; opcode bits 15:13 are 000 for bytes, 010 for halves and 100+ // for words and doublewords.+ let (opcode, bits) = match size_log2 {+ 0 => (0b000, index),+ 1 => (0b010, index << 1),+ 2 => (0b100, index << 2),+ _ => (0b100, (index << 3) | 1),+ };+ let q = (bits >> 3) & 1;+ let s = (bits >> 2) & 1;+ let size = bits & 3;+ (q << 30) | (opcode << 13) | (s << 12) | (size << 10)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::asm::aarch64::{Cond, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15};++ fn v(index: u8) -> Fpr {+ Fpr(index)+ }++ /// The encodings llvm-mc gives these instructions (`llvm-mc -triple=aarch64 -mattr=+lse,+neon,+rdm`).+ #[test]+ fn encodes_like_llvm_mc() {+ let mut asm = Assembler::new();+ asm.clz(Width::W32, X1, X2); // clz w1, w2+ asm.rbit(Width::W64, X3, X4); // rbit x3, x4+ asm.ror_imm(Width::W64, X5, X6, 13); // ror x5, x6, #13+ asm.float_binary(FloatBinary::Add, FloatSize::Single, v(1), v(2), v(3)); // fadd s1, s2, s3+ asm.float_binary(FloatBinary::Div, FloatSize::Double, v(1), v(2), v(3)); // fdiv d1, d2, d3+ asm.float_binary(FloatBinary::Max, FloatSize::Single, v(4), v(5), v(6)); // fmax s4, s5, s6+ asm.float_binary(FloatBinary::Min, FloatSize::Double, v(7), v(8), v(9)); // fmin d7, d8, d9+ asm.float_unary(FloatUnary::Sqrt, FloatSize::Single, v(1), v(2)); // fsqrt s1, s2+ asm.float_unary(FloatUnary::RoundNearest, FloatSize::Double, v(3), v(4)); // frintn d3, d4+ asm.float_unary(FloatUnary::RoundTowardZero, FloatSize::Single, v(5), v(6)); // frintz s5, s6+ asm.float_compare(FloatSize::Single, v(1), v(2)); // fcmp s1, s2+ asm.float_select(FloatSize::Double, v(1), v(2), v(3), Cond::Ne); // fcsel d1, d2, d3, ne+ asm.float_convert(FloatSize::Single, v(1), v(2)); // fcvt d1, s2+ asm.float_convert(FloatSize::Double, v(3), v(4)); // fcvt s3, d4+ asm.convert_to_float(true, Width::W32, FloatSize::Single, v(1), X2); // scvtf s1, w2+ asm.convert_to_float(false, Width::W64, FloatSize::Double, v(3), X4); // ucvtf d3, x4+ asm.convert_to_integer(true, Width::W32, FloatSize::Double, X5, v(6)); // fcvtzs w5, d6+ asm.convert_to_integer(false, Width::W64, FloatSize::Single, X7, v(8)); // fcvtzu x7, s8+ asm.float_to_gpr(FloatSize::Single, X1, v(2)); // fmov w1, s2+ asm.gpr_to_float(FloatSize::Double, v(3), X4); // fmov d3, x4+ asm.load_acquire(AtomicSize::Word, X1, X2); // ldar w1, [x2]+ asm.load_acquire(AtomicSize::Byte, X3, X4); // ldarb w3, [x4]+ asm.store_release(AtomicSize::Double, X5, X6); // stlr x5, [x6]+ asm.atomic_rmw(AtomicRmw::Add, AtomicSize::Word, X1, X2, X3); // ldaddal w1, w2, [x3]+ asm.atomic_rmw(AtomicRmw::Clear, AtomicSize::Double, X4, X5, X6); // ldclral x4, x5, [x6]+ asm.atomic_rmw(AtomicRmw::Xor, AtomicSize::Half, X7, X8, X9); // ldeoralh w7, w8, [x9]+ asm.atomic_rmw(AtomicRmw::Set, AtomicSize::Byte, X10, X11, X12); // ldsetalb w10, w11, [x12]+ asm.atomic_rmw(AtomicRmw::Swap, AtomicSize::Double, X13, X14, X15); // swpal x13, x14, [x15]+ asm.compare_and_swap(AtomicSize::Word, X1, X2, X3); // casal w1, w2, [x3]+ asm.compare_and_swap(AtomicSize::Byte, X4, X5, X6); // casalb w4, w5, [x6]+ asm.dmb_ish(); // dmb ish+ asm.read_counter(X1); // mrs x1, cntvct_el0+ asm.mov_vector(v(1), v(2)); // mov v1.16b, v2.16b+ asm.insert_lane_from_gpr(v(3), 3, 1, X4); // mov v3.d[1], x4+ asm.vector_count_bits(v(5), v(6)); // cnt v5.8b, v6.8b+ asm.vector_add_across(VectorArrangement::B8, v(7), v(8)); // addv b7, v8.8b+ asm.vector_three_same(true, (false, 0b10000), 2, v(1), v(2), v(3)); // add v1.4s, v2.4s, v3.4s+ asm.vector_three_same(true, (true, 0b00110), 0, v(1), v(2), v(3)); // cmhi v1.16b, v2.16b, v3.16b+ asm.vector_three_same(true, (true, 0b10110), 1, v(1), v(2), v(3)); // sqrdmulh v1.8h, v2.8h, v3.8h+ asm.vector_three_same(true, (true, 0b11100), 3, v(1), v(2), v(3)); // fcmgt v1.2d, v2.2d, v3.2d+ asm.vector_three_same(true, (false, 0b11010), 2, v(1), v(2), v(3)); // fsub v1.4s, v2.4s, v3.4s+ asm.vector_three_same(true, (true, 0b00011), 1, v(1), v(2), v(3)); // bsl v1.16b, v2.16b, v3.16b+ asm.vector_three_same(true, (false, 0b00011), 1, v(1), v(2), v(3)); // bic v1.16b, v2.16b, v3.16b+ asm.vector_three_different(false, (false, 0b1100), 1, v(1), v(2), v(3)); // smull v1.4s, v2.4h, v3.4h+ asm.vector_three_different(true, (true, 0b1100), 2, v(1), v(2), v(3)); // umull2 v1.2d, v2.4s, v3.4s+ asm.vector_three_different(false, (true, 0b1000), 2, v(1), v(2), v(3)); // umlal v1.2d, v2.2s, v3.2s+ asm.vector_two_misc(true, false, 3, 0b01011, v(1), v(2)); // abs v1.2d, v2.2d+ asm.vector_two_misc(false, false, 1, 0b10110, v(1), v(2)); // fcvtn v1.2s, v2.2d+ asm.vector_two_misc(false, false, 1, 0b10111, v(1), v(2)); // fcvtl v1.2d, v2.2s+ asm.vector_two_misc(true, false, 0, 0b10100, v(1), v(2)); // sqxtn2 v1.16b, v2.8h+ asm.vector_two_misc(true, true, 2, 0b00010, v(1), v(2)); // uaddlp v1.2d, v2.4s+ asm.vector_shift_immediate(true, true, 16 - 7, 0b00000, v(1), v(2)); // ushr v1.16b, v2.16b, #7+ asm.vector_shift_immediate(true, true, 128 - 28, 0b00010, v(1), v(2)); // usra v1.2d, v2.2d, #28+ asm.vector_shift_immediate(true, false, 64 + 32, 0b01010, v(1), v(2)); // shl v1.2d, v2.2d, #32+ asm.vector_shift_immediate(true, false, 8, 0b10100, v(1), v(2)); // sshll2 v1.8h, v2.16b, #0+ asm.vector_across(true, true, 2, 0b01010, v(1), v(2)); // umaxv s1, v2.4s+ asm.vector_permute(VectorArrangement::H8, 0b101, v(1), v(2), v(3)); // uzp2 v1.8h, v2.8h, v3.8h+ asm.vector_extract(v(1), v(2), v(3), 5); // ext v1.16b, v2.16b, v3.16b, #5+ asm.vector_table(v(1), v(30), 2, v(2)); // tbl v1.16b, {v30.16b, v31.16b}, v2.16b+ asm.vector_copy(true, false, 0b00100, 0b0001, 1, 2); // dup v1.4s, w2+ asm.vector_copy(true, false, 0b01000, 0b0000, 1, 2); // dup v1.2d, v2.d[0]+ asm.vector_copy(false, false, 17, 0b0111, 1, 2); // umov w1, v2.b[8]+ asm.vector_copy(false, false, 14, 0b0101, 1, 2); // smov w1, v2.h[3]+ asm.vector_copy(true, false, 24, 0b0111, 1, 2); // mov x1, v2.d[1]+ asm.vector_copy(true, true, 20, 0, 1, 2); // mov v1.s[2], v2.s[0]+ asm.load_replicate(2, v(1), X2); // ld1r {v1.4s}, [x2]+ asm.load_lane(1, 5, v(1), X2); // ld1 {v1.h}[5], [x2]+ asm.store_lane(3, 1, v(1), X2); // st1 {v1.d}[1], [x2]+ asm.vector_modified_immediate(true, true, 0b1110, 0, v(1)); // movi v1.2d, #0+ let expected: [u32; 69] = [+ 0x5ac01041, 0xdac00083, 0x93c634c5, 0x1e232841, 0x1e631841, 0x1e2648a4, 0x1e695907, 0x1e21c041, 0x1e644083,+ 0x1e25c0c5, 0x1e222020, 0x1e631c41, 0x1e22c041, 0x1e624083, 0x1e220041, 0x9e630083, 0x1e7800c5, 0x9e390107,+ 0x1e260041, 0x9e670083, 0x88dffc41, 0x08dffc83, 0xc89ffcc5, 0xb8e10062, 0xf8e410c5, 0x78e72128, 0x38ea318b,+ 0xf8ed81ee, 0x88e1fc62, 0x08e4fcc5, 0xd5033bbf, 0xd53be041, 0x4ea21c41, 0x4e181c83, 0x0e2058c5, 0x0e31b907,+ 0x4ea38441, 0x6e233441, 0x6e63b441, 0x6ee3e441, 0x4ea3d441, 0x6e631c41, 0x4e631c41, 0x0e63c041, 0x6ea3c041,+ 0x2ea38041, 0x4ee0b841, 0x0e616841, 0x0e617841, 0x4e214841, 0x6ea02841, 0x6f090441, 0x6f641441, 0x4f605441,+ 0x4f08a441, 0x6eb0a841, 0x4e435841, 0x6e032841, 0x4e0223c1, 0x4e040c41, 0x4e080441, 0x0e113c41, 0x0e0e2c41,+ 0x4e183c41, 0x6e140441, 0x4d40c841, 0x4d404841, 0x4d008441, 0x6f00e401,+ ];+ let code = asm.finish().unwrap();+ let words: Vec<u32> = code+ .chunks(4)+ .map(|word| u32::from_le_bytes(word.try_into().unwrap()))+ .collect();+ for (index, (word, expected)) in words.iter().zip(expected).enumerate() {+ assert_eq!(+ *word, expected,+ "instruction {index}: {word:#010x}, llvm-mc {expected:#010x}"+ );+ }+ assert_eq!(words.len(), expected.len());+ }+}diff --git a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/mod.rs b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/mod.rsindex adf1c486c4a..94a14bb3e8f 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/mod.rs@@ -6,10 +6,12 @@//! AArch64 (A64) instruction encoder.+mod extended;mod macro_assembler;#[cfg(test)]mod tests;+pub use extended::{AtomicRmw, AtomicSize, FloatBinary, FloatSize, FloatUnary, VectorArrangement};pub use macro_assembler::MacroAssembler;use super::Fpr;diff --git a/Libraries/LibWasm/Engine/src/runtime/jit.rs b/Libraries/LibWasm/Engine/src/runtime/jit.rsindex 29114a058bd..9a25ff82ced 100644--- a/Libraries/LibWasm/Engine/src/runtime/jit.rs+++ b/Libraries/LibWasm/Engine/src/runtime/jit.rs@@ -117,7 +117,7 @@ pub fn options() -> Options {}}}- options.enabled &= cfg!(all(unix, target_arch = "x86_64"));+ options.enabled &= cfg!(all(unix, any(target_arch = "x86_64", target_arch = "aarch64")));options})}@@ -316,7 +316,54 @@ pub unsafe fn redirect_fault(context: *mut libc::c_void) -> bool {}}-#[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]+/// Redirects a memory fault in compiled code to the trap exit. `context` is the signal handler's.+///+/// # Safety+///+/// Only the fault handler calls this, with its context.+#[cfg(all(target_os = "linux", target_arch = "aarch64"))]+pub unsafe fn redirect_fault(context: *mut libc::c_void) -> bool {+ unsafe {+ let context = context.cast::<libc::ucontext_t>();+ let mcontext = &mut (*context).uc_mcontext;+ let Some(stubs) = native::STUBS.get() else {+ return false;+ };+ if !CODE_RANGES.contains(mcontext.pc as usize) {+ return false;+ }+ mcontext.pc = stubs.trap_exit;+ mcontext.regs[0] = u64::from(crate::abi::TRAP_MEMORY_OUT_OF_BOUNDS);+ true+ }+}++/// Redirects a memory fault in compiled code to the trap exit. `context` is the signal handler's.+///+/// # Safety+///+/// Only the fault handler calls this, with its context.+#[cfg(all(target_os = "macos", target_arch = "aarch64"))]+pub unsafe fn redirect_fault(context: *mut libc::c_void) -> bool {+ unsafe {+ let context = context.cast::<libc::ucontext_t>();+ let state = &mut (*(*context).uc_mcontext).__ss;+ let Some(stubs) = native::STUBS.get() else {+ return false;+ };+ if !CODE_RANGES.contains(state.__pc as usize) {+ return false;+ }+ state.__pc = stubs.trap_exit;+ state.__x[0] = u64::from(crate::abi::TRAP_MEMORY_OUT_OF_BOUNDS);+ true+ }+}++#[cfg(not(any(+ all(target_os = "linux", target_arch = "x86_64"),+ all(any(target_os = "linux", target_os = "macos"), target_arch = "aarch64")+)))]pub unsafe fn redirect_fault(_context: *mut libc::c_void) -> bool {false}@@ -418,7 +465,7 @@ unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {let words = match *place {Place::Register(_) if params[index].uses_xmm() => {xmms += 1;- ak::slice_from_raw_parts(save_area.add(6 + 2 * (xmms - 1)), 2)+ ak::slice_from_raw_parts(save_area.add(convention::GPR_ARGUMENTS.len() + 2 * (xmms - 1)), 2)}Place::Register(_) => {gprs += 1;@@ -453,7 +500,7 @@ unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {let words = match *place {Place::Register(_) if result_types[index].uses_xmm() => {xmms += 1;- ak::slice_from_raw_parts_mut(save_area.add(6 + 2 * (xmms - 1)), 2)+ ak::slice_from_raw_parts_mut(save_area.add(convention::GPR_ARGUMENTS.len() + 2 * (xmms - 1)), 2)}Place::Register(_) => {gprs += 1;@@ -469,7 +516,7 @@ unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {}}-#[cfg(all(unix, target_arch = "x86_64"))]+#[cfg(all(unix, any(target_arch = "x86_64", target_arch = "aarch64")))]mod native {use super::{CODE_RANGES, ir_types, value_from_words, words_of_value};use crate::abi::{ExecutionContext, FUNCTION_KIND_COMPILED, FunctionHeader, OPCODE_TRAP_FROM_NATIVE};@@ -538,21 +585,28 @@ mod native {used: usize,}- const PAGE_SIZE: usize = 4096;const CHUNK_SIZE: usize = 16 << 20;+ fn page_size() -> usize {+ static PAGE_SIZE: OnceLock<usize> = OnceLock::new();+ *PAGE_SIZE.get_or_init(|| unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize)+ }+impl CodeChunk {fn new(size: usize) -> Self {- let base = unsafe {- libc::mmap(- std::ptr::null_mut(),- size,- libc::PROT_READ | libc::PROT_EXEC,- libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE,- -1,- 0,- )- };+ // NB: macOS on Apple silicon maps code writable and executable at once, with MAP_JIT, and switches each+ // thread's view of it between the two with pthread_jit_write_protect_np().+ #[cfg(target_os = "macos")]+ let (protection, flags) = (+ libc::PROT_READ | libc::PROT_WRITE | libc::PROT_EXEC,+ libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_JIT,+ );+ #[cfg(not(target_os = "macos"))]+ let (protection, flags) = (+ libc::PROT_READ | libc::PROT_EXEC,+ libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE,+ );+ let base = unsafe { libc::mmap(std::ptr::null_mut(), size, protection, flags, -1, 0) };assert_ne!(base, libc::MAP_FAILED, "no memory for compiled code");assert!(CODE_RANGES.add(base as usize, size),@@ -573,9 +627,18 @@ mod native {fn add(&mut self, code: &[u8]) -> u64 {let start = self.used.next_multiple_of(16);assert!(start + code.len() <= self.size);- let first_page = start / PAGE_SIZE * PAGE_SIZE;- let length = (start + code.len()).next_multiple_of(PAGE_SIZE) - first_page;+ #[cfg(target_os = "macos")]+ unsafe {+ libc::pthread_jit_write_protect_np(0);+ std::ptr::copy_nonoverlapping(code.as_ptr(), self.base.add(start), code.len());+ libc::pthread_jit_write_protect_np(1);+ libwasm_jit::runtime::flush_instruction_cache(self.base as usize + start, code.len());+ }+ #[cfg(not(target_os = "macos"))]unsafe {+ let page_size = page_size();+ let first_page = start / page_size * page_size;+ let length = (start + code.len()).next_multiple_of(page_size) - first_page;let region = self.base.add(first_page);assert_eq!(libc::mprotect(region.cast(), length, libc::PROT_READ | libc::PROT_WRITE),@@ -586,6 +649,7 @@ mod native {libc::mprotect(region.cast(), length, libc::PROT_READ | libc::PROT_EXEC),0);+ libwasm_jit::runtime::flush_instruction_cache(self.base as usize + start, code.len());}self.used = start + code.len();self.base as u64 + start as u64@@ -706,7 +770,7 @@ mod native {fn add_code(&mut self, code: &[u8]) -> u64 {if !self.chunks.last().is_some_and(|chunk| chunk.has_room(code.len())) {self.chunks- .push(CodeChunk::new(CHUNK_SIZE.max(code.len().next_multiple_of(PAGE_SIZE))));+ .push(CodeChunk::new(CHUNK_SIZE.max(code.len().next_multiple_of(page_size()))));}self.chunks.last_mut().expect("there is a chunk").add(code)}@@ -1035,7 +1099,7 @@ mod native {}}-#[cfg(not(all(unix, target_arch = "x86_64")))]+#[cfg(not(all(unix, any(target_arch = "x86_64", target_arch = "aarch64"))))]mod native {use crate::abi::ExecutionContext;use crate::runtime::{InstanceAddress, Store};diff --git a/Libraries/LibWasm/JIT/src/builder/memories.rs b/Libraries/LibWasm/JIT/src/builder/memories.rsindex fdbda13678f..eb3ae684222 100644--- a/Libraries/LibWasm/JIT/src/builder/memories.rs+++ b/Libraries/LibWasm/JIT/src/builder/memories.rs@@ -10,7 +10,9 @@use super::{Builder, load_kind, store_size_log2};use crate::decode::{Decoder, MemoryArgument};-use crate::ir::{AtomicOp, CHECKED_ATOMIC, CHECKED_MEMORY64, Func, Helper, LoadKind, Node, Op, Type, Value};+use crate::ir::{+ AtomicOp, CHECKED_ATOMIC, CHECKED_MEMORY64, Func, Helper, LOAD_ATOMIC, LoadKind, Node, Op, Type, Value,+};use libwasm_module::Module;use libwasm_module::abi::TRAP_EXPECTED_SHARED_MEMORY;use libwasm_module::instruction_tables::{AtomicKind, atomic_kind};@@ -132,8 +134,13 @@ impl Builder {(_, 2) => LoadKind::I32U16,_ => LoadKind::I32U8,};- // NB: Plain loads are sequentially consistent on x86-64, where stores are locked exchanges.- let loaded = self.load_at(func, kind, ir(value), address, 0);+ // NB: Plain loads are sequentially consistent on x86-64, where stores are locked exchanges; AArch64+ // loads them with acquire semantics.+ let zero = self.constant(func, Type::I32, 0);+ let loaded = Self::append(+ func,+ Node::new(Op::Load, ir(value), kind as u8 | LOAD_ATOMIC, [address, zero, 0]),+ );self.push(loaded);}AtomicKind::Store { value, size } => {diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/calls.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/calls.rsnew file mode 100644index 00000000000..0ede764e51c--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/calls.rs@@ -0,0 +1,133 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Calls between compiled functions (see `convention`). The allocator moved the arguments into place, so a call+//! only passes the result area, if any, calls through the callee's `FunctionHeader`, and puts sp back where the+//! frame wants it, which also undoes whatever a callee's tail calls did to it.++use super::{ADDRESS, CodeGenerator, FP, LR, SCRATCH, SP, fpr, fpr_access, gpr, gpr_access};+use crate::asm::Width;+use crate::asm::aarch64::{MemOperand, PairOperand};+use crate::convention::{self, Place};+use crate::ir::{FLAG_CHECKS_EXCEPTION, Func, Op, Type, Value};+use crate::regalloc::call_result_types;+use libwasm_module::abi::FunctionHeader;+use std::mem::offset_of;++/// The slots of a call's arguments.+fn argument_slots(func: &Func, call: Value) -> u32 {+ func.inputs(call)[3..]+ .iter()+ .map(|argument| func.node(*argument).ty.slots())+ .sum()+}++impl CodeGenerator<'_> {+ pub(super) fn lower_call(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ match node.op {+ Op::Call => {+ let argument_slots = argument_slots(func, value);+ let results = call_result_types(func, value);+ if convention::has_result_area(&results) {+ let pointer = 8 * i64::from(argument_slots);+ self.asm.add_any(SCRATCH, SP, pointer + 8, ADDRESS);+ let operand = self.operand(SP, pointer, 3);+ self.asm.str(Width::W64, SCRATCH, operand);+ }+ let callee = gpr(convention::CALLEE_REGISTER);+ self.asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(callee, offset_of!(FunctionHeader, native_entry) as i32),+ );+ self.asm.blr(SCRATCH);+ if node.flags & FLAG_CHECKS_EXCEPTION != 0 {+ self.exception_sites.push(self.asm.offset() as u32);+ }+ self.reset_sp();+ }+ Op::CallResult => {+ let call = node.args[0];+ let index = node.args[1] as usize;+ let results = call_result_types(func, call);+ let mut places = Vec::with_capacity(results.len());+ convention::result_places(&results, &mut places);+ if let Place::Memory(slot) = places[index] {+ let output = self.allocation.node(value).output;+ let area = 8 * (i64::from(argument_slots(func, call)) + 1);+ let size_log2 = if node.ty == Type::V128 { 4 } else { 3 };+ let operand = self.operand(SP, area + 8 * i64::from(slot), size_log2);+ if node.ty.uses_xmm() {+ self.asm.load_store(fpr_access(size_log2, true), fpr(output).0, operand);+ } else {+ self.asm.load_store(gpr_access(size_log2, true), gpr(output).0, operand);+ }+ }+ }+ _ => unreachable!("{} is no call", node.op.name()),+ }+ }++ /// A tail call: the allocator put the arguments where a call passes them, which this copies the stack arguments+ /// from into the incoming area (see `convention`). The return address stays in the link register, so where the+ /// stack arguments need more room than the function was called with, only sp moves down.+ pub(super) fn lower_tail_call(&mut self, value: Value) {+ let func = self.func;+ let parameters = func.inputs(value)[3..]+ .iter()+ .map(|argument| func.node(*argument).ty)+ .collect::<Vec<_>>();+ let has_result_area = convention::has_result_area(&func.results);+ let callee_slots = convention::slots(¶meters);+ let own_slots = convention::slots(&func.params);+ let needed = callee_slots + u32::from(has_result_area);+ let available = own_slots + u32::from(has_result_area);+ let slide = if needed > available {+ i64::from((8 * (needed - available)).next_multiple_of(16))+ } else {+ 0+ };+ let mut copied = Vec::new();+ let mut places = Vec::new();+ convention::parameter_places(¶meters, &mut places);+ for (index, place) in places.iter().enumerate() {+ if let Place::Memory(slot) = *place {+ copied.extend(slot..slot + parameters[index].slots());+ }+ }+ if has_result_area {+ // The function's caller gets the callee's results.+ let pointer = convention::home_slot_offset(convention::result_area_pointer(&func.params));+ let operand = self.operand(FP, i64::from(pointer), 3);+ self.asm.ldr(Width::W64, SCRATCH, operand);+ let operand = self.operand(SP, 8 * i64::from(callee_slots), 3);+ self.asm.str(Width::W64, SCRATCH, operand);+ copied.push(callee_slots);+ }+ // The incoming area is above the outgoing one, so copying down from the top never overwrites a source.+ for &slot in copied.iter().rev() {+ let operand = self.operand(SP, 8 * i64::from(slot), 3);+ self.asm.ldr(Width::W64, SCRATCH, operand);+ let operand = self.operand(FP, 8 * i64::from(slot) - slide, 3);+ self.asm.str(Width::W64, SCRATCH, operand);+ }+ // The link register and fp come back from the frame, and sp goes where the function's caller had it, less+ // the slide.+ self.asm+ .ldp(ADDRESS, LR, PairOperand::Offset(FP, convention::FRAME_SAVED_FP));+ self.asm.add_any(SP, FP, -slide, SCRATCH);+ self.asm.mov(Width::W64, FP, ADDRESS);+ let callee = gpr(convention::CALLEE_REGISTER);+ self.asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(callee, offset_of!(FunctionHeader, native_entry) as i32),+ );+ self.asm.br(SCRATCH);+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/gc.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/gc.rsnew file mode 100644index 00000000000..a2e2ca256d6--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/gc.rs@@ -0,0 +1,324 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Accesses of memories without guard pages, atomics, and GC objects: their addresses and checks, and the tests of+//! references against heap types.++use super::{ADDRESS, CodeGenerator, FP, SCRATCH, gpr};+use crate::asm::aarch64::{AtomicRmw, AtomicSize, Cond, Extend, MemOperand, Shift};+use crate::asm::{Gpr, Width};+use crate::convention::{self, Register};+use crate::ir::{AtomicOp, CHECKED_ATOMIC, CHECKED_MEMORY64, HeapTest, Op, REF_TEST_CAST, REF_TEST_NULLABLE, Value};+use crate::regalloc::{CONSTANT_INPUT, NO_REGISTER};+use libwasm_module::abi::{+ ExecutionContext, FunctionHeader, InstanceData, MemoryData, OBJECT_DATA_OFFSET, OBJECT_LENGTH_OFFSET,+ RTT_KIND_ARRAY, RTT_KIND_STRUCT, Rtt, TRAP_ARRAY_OUT_OF_BOUNDS, TRAP_CAST_FAILURE, TRAP_MEMORY_OUT_OF_BOUNDS,+ TRAP_NULL_REFERENCE, TRAP_UNALIGNED_ATOMIC,+};+use std::mem::offset_of;++fn field(offset: usize) -> i32 {+ offset as i32+}++impl CodeGenerator<'_> {+ pub(super) fn lower_gc(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ let input = |index: usize| gpr(record.inputs[index]);+ match node.op {+ Op::CheckedAddress => self.checked_address(value),+ Op::AtomicRmw => {+ let size = AtomicSize::from_log2(u32::from(node.flags));+ let (address, operand) = (input(0), input(1));+ let old = if record.output == NO_REGISTER {+ SCRATCH+ } else {+ gpr(record.output)+ };+ // The acquire-release forms make every atomic access sequentially consistent with the others.+ let (op, source) = match AtomicOp::from_index(node.args[2]) {+ AtomicOp::Add => (AtomicRmw::Add, operand),+ AtomicOp::Sub => {+ self.asm.neg(Width::W64, SCRATCH, operand);+ (AtomicRmw::Add, SCRATCH)+ }+ AtomicOp::And => {+ self.asm.mvn(Width::W64, SCRATCH, operand);+ (AtomicRmw::Clear, SCRATCH)+ }+ AtomicOp::Or => (AtomicRmw::Set, operand),+ AtomicOp::Xor => (AtomicRmw::Xor, operand),+ AtomicOp::Exchange => (AtomicRmw::Swap, operand),+ };+ self.asm.atomic_rmw(op, size, source, old, address);+ }+ Op::AtomicCompareExchange => {+ let size = AtomicSize::from_log2(u32::from(node.flags));+ // NB: Only the low bytes of the expected value are compared, which is the value wrapped at the access+ // width. The old value comes back zero-extended in its place.+ self.asm.mov(Width::W64, SCRATCH, input(1));+ self.asm.compare_and_swap(size, SCRATCH, input(2), input(0));+ self.asm.mov(Width::W64, gpr(record.output), SCRATCH);+ }+ Op::AtomicFence => self.asm.dmb_ish(),+ Op::Rtt => {+ let (instance, output) = (input(0), gpr(record.output));+ self.asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(instance, field(offset_of!(InstanceData, type_identities))),+ );+ let operand = self.operand(SCRATCH, 4 * i64::from(node.args[1]), 2);+ self.asm.ldr(Width::W32, SCRATCH, operand);+ self.rtts(output, instance);+ self.asm.ldr(+ Width::W64,+ output,+ MemOperand::Register {+ base: output,+ index: SCRATCH,+ extend: Extend::Uxtx,+ shifted: true,+ },+ );+ }+ Op::I31New => {+ // NB: Shifting the 32-bit value left drops its bit 31: ((value & 0x7fffffff) << 1) | 1.+ let output = gpr(record.output);+ self.asm.lsl_imm(Width::W32, output, input(0), 1);+ self.asm.orr_imm(Width::W32, output, output, 1);+ }+ Op::I31Get => {+ let output = gpr(record.output);+ if node.flags != 0 {+ self.asm.asr_imm(Width::W32, output, input(0), 1);+ } else {+ self.asm.lsr_imm(Width::W32, output, input(0), 1);+ }+ }+ Op::ElementAddress => {+ let (array, index, output) = (input(0), input(1), gpr(record.output));+ let null = self.trap_label(TRAP_NULL_REFERENCE);+ self.asm.cbz(Width::W64, array, null);+ // NB: The index is zero-extended, so a 64-bit comparison checks it as an unsigned i32.+ let operand = self.operand(array, i64::from(field(OBJECT_LENGTH_OFFSET)), 3);+ self.asm.ldr(Width::W64, SCRATCH, operand);+ self.asm.cmp(Width::W64, index, SCRATCH);+ let out_of_bounds = self.trap_label(TRAP_ARRAY_OUT_OF_BOUNDS);+ self.asm.b_cond(Cond::Hs, out_of_bounds);+ let operand = self.operand(array, i64::from(field(OBJECT_DATA_OFFSET)), 3);+ self.asm.ldr(Width::W64, output, operand);+ // Elements take 8 bytes each, or 16 for v128s.+ self.asm+ .add_extended(Width::W64, output, output, index, Extend::Uxtx, 3);+ if node.flags == 4 {+ self.asm+ .add_extended(Width::W64, output, output, index, Extend::Uxtx, 3);+ }+ }+ Op::RefTest => self.ref_test(value),+ _ => unreachable!("{} is no GC or atomic operation", node.op.name()),+ }+ }++ /// `output` = the runtime types of the store, from `instance`.+ fn rtts(&mut self, output: Gpr, instance: Gpr) {+ self.asm.ldr(+ Width::W64,+ output,+ MemOperand::Offset(instance, field(offset_of!(InstanceData, context))),+ );+ self.asm.ldr(+ Width::W64,+ output,+ MemOperand::Offset(output, field(offset_of!(ExecutionContext, rtts))),+ );+ }++ /// The address of a checked access: the memory's base + index + offset, after checking that index + offset ++ /// size is at most the memory's size, and for atomics that index + offset is aligned.+ fn checked_address(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ let size = 1u64 << (node.flags & 7);+ let memory64 = node.flags & CHECKED_MEMORY64 != 0;+ let (memory, index, output) = (gpr(record.inputs[0]), gpr(record.inputs[1]), gpr(record.output));+ let out_of_bounds = self.trap_label(TRAP_MEMORY_OUT_OF_BOUNDS);+ // The end of the access, which may wrap around for a memory64; i32 indices are zero-extended already.+ let end = SCRATCH;+ if record.inputs[2] == CONSTANT_INPUT {+ let offset = self.immediate(value, 2);+ match offset.checked_add(size) {+ Some(total) if total < (1 << 12) => {+ self.asm.adds_imm(Width::W64, end, index, total as u32, false);+ }+ Some(total) => {+ self.asm.mov_imm(Width::W64, ADDRESS, total);+ self.asm.adds(Width::W64, end, index, ADDRESS, Shift::Lsl, 0);+ }+ None => {+ // The offset alone is within the size of 2^64: every index wraps around.+ self.asm.b(out_of_bounds);+ return;+ }+ }+ if memory64 {+ self.asm.b_cond(Cond::Hs, out_of_bounds);+ }+ } else {+ self.asm+ .adds(Width::W64, end, index, gpr(record.inputs[2]), Shift::Lsl, 0);+ if memory64 {+ self.asm.b_cond(Cond::Hs, out_of_bounds);+ }+ self.asm.adds_imm(Width::W64, end, end, size as u32, false);+ if memory64 {+ self.asm.b_cond(Cond::Hs, out_of_bounds);+ }+ }+ self.asm.ldr(+ Width::W64,+ ADDRESS,+ MemOperand::Offset(memory, field(offset_of!(MemoryData, size))),+ );+ self.asm.cmp(Width::W64, end, ADDRESS);+ self.asm.b_cond(Cond::Hi, out_of_bounds);+ if node.flags & CHECKED_ATOMIC != 0 && size > 1 {+ // NB: The end and the address differ by the size, a multiple of the alignment.+ let unaligned = self.trap_label(TRAP_UNALIGNED_ATOMIC);+ self.asm.tst_imm(Width::W64, end, size - 1);+ self.asm.b_cond(Cond::Ne, unaligned);+ }+ self.asm.ldr(+ Width::W64,+ output,+ MemOperand::Offset(memory, field(offset_of!(MemoryData, base))),+ );+ self.asm.add(Width::W64, output, output, end, Shift::Lsl, 0);+ self.asm.sub_imm(Width::W64, output, output, size as u32, false);+ }++ /// `RefTest`: whether a reference matches a heap type, as 0 or 1, or for a cast a trap where it does not.+ fn ref_test(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ let reference = gpr(record.inputs[0]);+ let identity: Register = record.inputs[1];+ let depth = node.args[2] as i32;+ let cast = node.flags & REF_TEST_CAST != 0;+ let matched = self.asm.new_label();+ let failed = if cast {+ self.trap_label(TRAP_CAST_FAILURE)+ } else {+ self.asm.new_label()+ };+ let null_matches = node.flags & REF_TEST_NULLABLE != 0;+ self.asm+ .cbz(Width::W64, reference, if null_matches { matched } else { failed });+ // Compares the u32 at `operand` with the expected type identity.+ let compare_identity = |generator: &mut Self, operand: MemOperand| {+ generator.asm.ldr(Width::W32, ADDRESS, operand);+ if identity == CONSTANT_INPUT {+ let bits = generator.immediate(value, 1);+ generator.compare_immediate(Width::W32, ADDRESS, bits);+ } else {+ generator.asm.cmp(Width::W32, ADDRESS, gpr(identity));+ }+ };+ // Whether the Rtt in `rtt` is the expected type or a subtype of it: the expected type is in its display at+ // the expected type's depth.+ let subtype_check = |generator: &mut Self, rtt: Gpr| {+ generator.asm.ldr(+ Width::W32,+ ADDRESS,+ MemOperand::Offset(rtt, field(offset_of!(Rtt, depth))),+ );+ generator.compare_immediate(Width::W32, ADDRESS, depth as u64);+ generator.asm.b_cond(Cond::Lo, failed);+ generator.asm.ldr(+ Width::W64,+ rtt,+ MemOperand::Offset(rtt, field(offset_of!(Rtt, display))),+ );+ let operand = generator.operand(rtt, 4 * i64::from(depth), 2);+ compare_identity(generator, operand);+ generator.asm.b_cond(Cond::Ne, failed);+ };+ match HeapTest::from_flags(node.flags) {+ HeapTest::NonNull => {}+ HeapTest::Nothing => self.asm.b(failed),+ HeapTest::I31 => {+ self.asm.tbz(reference, 0, failed);+ }+ HeapTest::Eq => {+ // An i31 (bit 0), or a GC object (bits 1:0 clear) rather than a host value (0b10).+ self.asm.tbnz(reference, 0, matched);+ self.asm.tbnz(reference, 1, failed);+ }+ kind @ (HeapTest::Struct | HeapTest::Array) => {+ let rtt = gpr(record.temps[0]);+ self.asm.tst_imm(Width::W64, reference, 3);+ self.asm.b_cond(Cond::Ne, failed);+ self.asm.ldr(Width::W64, rtt, MemOperand::Offset(reference, 0));+ let expected = if kind == HeapTest::Struct {+ RTT_KIND_STRUCT+ } else {+ RTT_KIND_ARRAY+ };+ self.asm.ldr(+ Width::W32,+ ADDRESS,+ MemOperand::Offset(rtt, field(offset_of!(Rtt, kind))),+ );+ self.compare_immediate(Width::W32, ADDRESS, u64::from(expected));+ self.asm.b_cond(Cond::Ne, failed);+ }+ HeapTest::ConcreteObject => {+ let rtt = gpr(record.temps[0]);+ self.asm.tst_imm(Width::W64, reference, 3);+ self.asm.b_cond(Cond::Ne, failed);+ self.asm.ldr(Width::W64, rtt, MemOperand::Offset(reference, 0));+ subtype_check(self, rtt);+ }+ HeapTest::ConcreteFunction => {+ let [rtt, rtts] = [gpr(record.temps[0]), gpr(record.temps[1])];+ let type_identity = MemOperand::Offset(reference, field(offset_of!(FunctionHeader, type_identity)));+ compare_identity(self, type_identity);+ self.asm.b_cond(Cond::Eq, matched);+ self.asm.ldr(Width::W32, rtt, type_identity);+ self.asm+ .ldr(Width::W64, rtts, MemOperand::Offset(FP, convention::FRAME_INSTANCE));+ self.rtts(rtts, rtts);+ self.asm.ldr(+ Width::W64,+ rtt,+ MemOperand::Register {+ base: rtts,+ index: rtt,+ extend: Extend::Uxtx,+ shifted: true,+ },+ );+ subtype_check(self, rtt);+ }+ }+ self.asm.bind(matched);+ if cast {+ return;+ }+ let output = gpr(record.output);+ let done = self.asm.new_label();+ self.asm.mov_imm(Width::W32, output, 1);+ self.asm.b(done);+ self.asm.bind(failed);+ self.asm.mov_imm(Width::W32, output, 0);+ self.asm.bind(done);+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/memory.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/memory.rsnew file mode 100644index 00000000000..aba9b8d0d58--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/memory.rs@@ -0,0 +1,219 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Loads and stores of memory 0, globals and instance data.+//!+//! Memory 0 is a memory32 with guard pages: an access is at base + zero-extended index + offset, with no bounds+//! check, and faults in the guard region where it is out of bounds. i32 values are always zero-extended in+//! registers, so the index register serves as is.++use super::{ADDRESS, CodeGenerator, SCRATCH, fits_offset, fpr, fpr_access, gpr, gpr_access};+use crate::asm::aarch64::{AtomicSize, Extend, MemOp, MemOperand, XZR};+use crate::asm::{Gpr, Width};+use crate::convention::{self, Register};+use crate::ir::{LOAD_ATOMIC, LoadKind, Op, Type, Value};+use crate::regalloc::CONSTANT_INPUT;++/// The memory operation of a load of kind `kind` into a general purpose register.+fn load_op(kind: LoadKind) -> MemOp {+ match kind {+ LoadKind::I32 | LoadKind::I64U32 => MemOp::LdrW,+ LoadKind::I64 => MemOp::LdrX,+ LoadKind::F32 => MemOp::LdrS,+ LoadKind::F64 => MemOp::LdrD,+ LoadKind::I32S8 => MemOp::LdrsbW,+ LoadKind::I64S8 => MemOp::LdrsbX,+ LoadKind::I32U8 | LoadKind::I64U8 => MemOp::Ldrb,+ LoadKind::I32S16 => MemOp::LdrshW,+ LoadKind::I64S16 => MemOp::LdrshX,+ LoadKind::I32U16 | LoadKind::I64U16 => MemOp::Ldrh,+ LoadKind::I64S32 => MemOp::Ldrsw,+ }+}++impl CodeGenerator<'_> {+ /// The operand of an access of `1 << size_log2` bytes of memory 0 with base `base`, index input `index` and+ /// offset `offset`.+ pub(super) fn memory_operand(+ &mut self,+ value: Value,+ base: Register,+ index: Register,+ offset: u32,+ size_log2: u32,+ ) -> MemOperand {+ let base = gpr(base);+ if index == CONSTANT_INPUT {+ let constant = (self.immediate(value, 1) & 0xffff_ffff) + u64::from(offset);+ if fits_offset(constant as i64, size_log2) {+ return MemOperand::Offset(base, constant as i32);+ }+ self.asm.mov_imm(Width::W64, ADDRESS, constant);+ return MemOperand::Register {+ base,+ index: ADDRESS,+ extend: Extend::Uxtx,+ shifted: false,+ };+ }+ if offset == 0 {+ return MemOperand::Register {+ base,+ index: gpr(index),+ extend: Extend::Uxtx,+ shifted: false,+ };+ }+ // NB: The index and offset, both below 2^32, add up without overflowing 64 bits.+ self.asm.add_any(ADDRESS, gpr(index), i64::from(offset), ADDRESS);+ MemOperand::Register {+ base,+ index: ADDRESS,+ extend: Extend::Uxtx,+ shifted: false,+ }+ }++ /// The address of an access in a register: `base` itself if `operand` is `[base]`, else x17.+ pub(super) fn address_register(&mut self, operand: MemOperand) -> Gpr {+ match operand {+ MemOperand::Offset(base, 0) => base,+ MemOperand::Offset(base, offset) => {+ self.asm.add_any(ADDRESS, base, i64::from(offset), ADDRESS);+ ADDRESS+ }+ MemOperand::Register { base, index, .. } => {+ self.asm.add_extended(Width::W64, ADDRESS, base, index, Extend::Uxtx, 0);+ ADDRESS+ }+ _ => unreachable!("no address of {operand:?}"),+ }+ }++ pub(super) fn lower_memory(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ let [a, b, c] = record.inputs;+ let output = record.output;+ match node.op {+ Op::Load => {+ let kind = LoadKind::from_flags(node.flags & !LOAD_ATOMIC);+ let size_log2 = kind.size().trailing_zeros();+ let operand = self.memory_operand(value, a, b, node.args[2], size_log2);+ if node.flags & LOAD_ATOMIC != 0 {+ // Acquire loads, with the stores' exchanges, make atomic accesses sequentially consistent.+ let address = self.address_register(operand);+ self.asm+ .load_acquire(AtomicSize::from_log2(size_log2), gpr(output), address);+ return;+ }+ let op = load_op(kind);+ let register = if kind.size() >= 4 && matches!(kind, LoadKind::F32 | LoadKind::F64) {+ fpr(output).0+ } else {+ gpr(output).0+ };+ self.asm.load_store(op, register, operand);+ }+ Op::VectorLoad => {+ let operand_of = |generator: &mut Self, size_log2: u32| {+ generator.memory_operand(value, a, b, node.args[2], size_log2)+ };+ self.vector_load(value, operand_of);+ }+ Op::Store => {+ let size = crate::ir::store_size(node.flags);+ let size_log2 = size.trailing_zeros();+ let operand = self.memory_operand(value, a, b, node.args[2], size_log2);+ let stored = func.inputs(value)[2];+ self.store(stored, c, size_log2, operand);+ }+ Op::GlobalGet => {+ let size_log2 = if node.ty == Type::V128 {+ 4+ } else if node.ty.is_64() {+ 3+ } else {+ 2+ };+ let operand = MemOperand::Offset(gpr(a), 0);+ if node.ty.uses_xmm() {+ self.asm.load_store(fpr_access(size_log2, true), fpr(output).0, operand);+ } else {+ self.asm.load_store(gpr_access(size_log2, true), gpr(output).0, operand);+ }+ }+ Op::GlobalSet => {+ let stored = node.args[1];+ let size_log2 = match func.node(stored).ty {+ Type::V128 => 4,+ ty if ty.is_64() => 3,+ _ => 2,+ };+ self.store(stored, b, size_log2, MemOperand::Offset(gpr(a), 0));+ }+ Op::FrameLoad => {+ let size_log2 = if node.ty == Type::V128 {+ 4+ } else if node.ty.is_64() {+ 3+ } else {+ 2+ };+ let mut operand = self.operand(gpr(a), i64::from(node.args[1] as i32), 3);+ if node.flags == 1 {+ self.asm.ldr(Width::W64, ADDRESS, operand);+ operand = MemOperand::Offset(ADDRESS, 0);+ }+ if node.ty.uses_xmm() {+ self.asm.load_store(fpr_access(size_log2, true), fpr(output).0, operand);+ } else {+ self.asm.load_store(gpr_access(size_log2, true), gpr(output).0, operand);+ }+ }+ Op::InstanceField | Op::LoadPointer => {+ let size_log2 = if node.op == Op::LoadPointer && node.flags == 4 {+ 2+ } else {+ 3+ };+ let operand = self.operand(gpr(a), i64::from(node.args[1]), size_log2);+ self.asm.load_store(gpr_access(size_log2, true), gpr(output).0, operand);+ }+ _ => unreachable!("{} is no memory op", node.op.name()),+ }+ }++ /// Stores `1 << size_log2` bytes of `stored`, which is in `register` or a constant immediate, at `operand`.+ pub(super) fn store(&mut self, stored: Value, register: Register, size_log2: u32, operand: MemOperand) {+ if register == CONSTANT_INPUT {+ let node = self.func.node(stored);+ if node.op == Op::Const128 {+ let bits = self.constant_bits(stored);+ self.load_vector_constant(bits, super::SCRATCH_FPR, true);+ self.asm.load_store(fpr_access(4, false), super::SCRATCH_FPR.0, operand);+ return;+ }+ let bits = node.constant().expect("immediates are constants");+ let source = if bits == 0 {+ XZR+ } else {+ self.asm.mov_imm(Width::W64, SCRATCH, bits);+ SCRATCH+ };+ self.asm.load_store(gpr_access(size_log2, false), source.0, operand);+ return;+ }+ if convention::is_fpr(register) {+ self.asm+ .load_store(fpr_access(size_log2.max(2), false), fpr(register).0, operand);+ return;+ }+ self.asm+ .load_store(gpr_access(size_log2, false), gpr(register).0, operand);+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rsnew file mode 100644index 00000000000..802e6c8ff16--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs@@ -0,0 +1,794 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! AArch64 code generation: the blocks in linear order, each node lowered with the registers the allocator gave it+//! (`numeric`, `memory`, `calls`, `tables`, `gc`, `vector`), then the out-of-line code: stubs for edges that need+//! moves, trap stubs and the subtype checks of indirect calls. The code is position independent: it reaches the+//! runtime through absolute addresses, has its jump tables inline, and builds its constants with moves, so it needs+//! no literal pool.+//!+//! x16 and x17 are the scratch registers, v30 and v31 the vector ones; the allocator never gives them out. x17 only+//! ever holds an address being formed (`operand()`), so a lowering may keep a value in x16 across an access.+//! Frame slots are addressed from sp, which is fp minus the frame size everywhere but in tail calls, so that their+//! offsets are positive and fit the scaled immediate forms.++mod calls;+mod gc;+mod memory;+mod numeric;+mod tables;+mod vector;++pub(crate) use vector::{is_vector_shift, vector_temps};++use crate::RuntimeInfo;+use crate::asm::aarch64::{Assembler, Cond, Extend, FloatSize, MemOp, MemOperand, PairOperand, Shift, X16, X17, XZR};+use crate::asm::{Fpr, Gpr, Label, Width};+use crate::convention::{self, Register};+use crate::ir::{BlockId, FloatCondition, Func, IntCondition, NONE, Op, Type, Value};+use crate::passes::cleanup::Liveliness;+use crate::regalloc::{Allocation, Location, Move, NO_REGISTER, NO_SLOT};+use libwasm_module::abi::{ExecutionContext, InstanceData};+use std::mem::offset_of;++pub(crate) fn gpr(register: Register) -> Gpr {+ debug_assert!(+ !convention::is_fpr(register),+ "r{register} is no general purpose register"+ );+ Gpr(register)+}++pub(crate) fn fpr(register: Register) -> Fpr {+ debug_assert!(convention::is_fpr(register), "r{register} is no vector register");+ Fpr(convention::vector_register(register))+}++pub(crate) fn width(ty: Type) -> Width {+ if ty.is_64() { Width::W64 } else { Width::W32 }+}++pub(crate) fn float_size(ty: Type) -> FloatSize {+ if ty == Type::F64 {+ FloatSize::Double+ } else {+ FloatSize::Single+ }+}++pub(crate) const SCRATCH: Gpr = X16;+/// Only for forming addresses (see the module documentation).+pub(crate) const ADDRESS: Gpr = X17;+pub(crate) const SCRATCH_FPR: Fpr = Fpr(31);+pub(crate) const SCRATCH_FPR2: Fpr = Fpr(30);+pub(crate) const FP: Gpr = Gpr(29);+pub(crate) const LR: Gpr = Gpr(30);+pub(crate) const SP: Gpr = Gpr(31);++pub(crate) fn condition(condition: IntCondition) -> Cond {+ match condition {+ IntCondition::Eq => Cond::Eq,+ IntCondition::Ne => Cond::Ne,+ IntCondition::LtS => Cond::Lt,+ IntCondition::LtU => Cond::Lo,+ IntCondition::GtS => Cond::Gt,+ IntCondition::GtU => Cond::Hi,+ IntCondition::LeS => Cond::Le,+ IntCondition::LeU => Cond::Ls,+ IntCondition::GeS => Cond::Ge,+ IntCondition::GeU => Cond::Hs,+ }+}++/// The condition after `fcmp a, b` that holds where a float comparison does; all are false for unordered operands+/// but `Ne`.+pub(crate) fn float_condition(condition: FloatCondition) -> Cond {+ match condition {+ FloatCondition::Eq => Cond::Eq,+ FloatCondition::Ne => Cond::Ne,+ FloatCondition::Lt => Cond::Mi,+ FloatCondition::Le => Cond::Ls,+ FloatCondition::Gt => Cond::Gt,+ FloatCondition::Ge => Cond::Ge,+ }+}++/// Whether `offset` fits the immediate of a load or store of `1 << size_log2` bytes.+pub fn fits_offset(offset: i64, size_log2: u32) -> bool {+ let size = 1i64 << size_log2;+ (offset >= 0 && offset % size == 0 && offset / size < 4096) || (-256..256).contains(&offset)+}++/// The memory operation of a load (`load`) or store of `1 << size_log2` bytes to or from a general purpose register,+/// zero-extended.+pub(crate) fn gpr_access(size_log2: u32, load: bool) -> MemOp {+ match (size_log2, load) {+ (0, true) => MemOp::Ldrb,+ (0, false) => MemOp::Strb,+ (1, true) => MemOp::Ldrh,+ (1, false) => MemOp::Strh,+ (2, true) => MemOp::LdrW,+ (2, false) => MemOp::StrW,+ (_, true) => MemOp::LdrX,+ (_, false) => MemOp::StrX,+ }+}++/// The memory operation of a load or store of `1 << size_log2` bytes to or from a vector register.+pub(crate) fn fpr_access(size_log2: u32, load: bool) -> MemOp {+ match (size_log2, load) {+ (2, true) => MemOp::LdrS,+ (2, false) => MemOp::StrS,+ (3, true) => MemOp::LdrD,+ (3, false) => MemOp::StrD,+ (_, true) => MemOp::LdrQ,+ (_, false) => MemOp::StrQ,+ }+}++/// What code generation produced.+#[derive(Debug, Default)]+pub struct Generated {+ pub code: Vec<u8>,+ pub frame_size: u32,+ /// The offsets of the return addresses of calls that check for an exception once they return.+ pub exception_sites: Vec<u32>,+}++/// Out-of-line code for an edge that needs moves: its label, the edge's slot and its target.+struct EdgeStub {+ label: Label,+ slot: u32,+ target: BlockId,+}++pub struct CodeGenerator<'a> {+ func: &'a Func,+ liveliness: &'a Liveliness,+ allocation: &'a Allocation,+ runtime: &'a RuntimeInfo,+ asm: Assembler,+ block_labels: Vec<Label>,+ trap_labels: Vec<Option<Label>>,+ /// The trap with the code in x0, for the runtime's functions that return one.+ dynamic_trap: Option<Label>,+ subtype_checks: Vec<tables::SubtypeCheck>,+ edge_stubs: Vec<EdgeStub>,+ frame_size: u32,+ /// The block whose code is being generated.+ block: BlockId,+ /// Why the function could not be compiled, if a lowering found out.+ failure: Option<crate::CompileFailure>,+ exception_sites: Vec<u32>,+}++impl<'a> CodeGenerator<'a> {+ pub fn new(+ func: &'a Func,+ liveliness: &'a Liveliness,+ allocation: &'a Allocation,+ runtime: &'a RuntimeInfo,+ ) -> Self {+ let size = convention::FRAME_HEADER_SIZE as u32 + 8 * allocation.slot_count + allocation.outgoing_size;+ Self {+ func,+ liveliness,+ allocation,+ runtime,+ asm: Assembler::new(),+ block_labels: Vec::new(),+ trap_labels: vec![None; 32],+ dynamic_trap: None,+ subtype_checks: Vec::new(),+ edge_stubs: Vec::new(),+ frame_size: size.next_multiple_of(16),+ block: 0,+ failure: None,+ exception_sites: Vec::new(),+ }+ }++ pub fn generate(mut self) -> Result<Generated, crate::CompileFailure> {+ let func = self.func;+ for _ in 0..func.blocks.len() {+ let label = self.asm.new_label();+ self.block_labels.push(label);+ }+ self.prologue();+ for block in 0..func.blocks.len() as BlockId {+ self.block = block;+ let label = self.block_labels[block as usize];+ self.asm.bind(label);+ // Phis in registers that have a slot too are stored there where they are defined.+ for phi in func.phis(block) {+ let record = self.allocation.node(phi);+ let slot = self.allocation.slots[phi as usize];+ if record.output != NO_REGISTER && slot != NO_SLOT {+ self.store_to_slot(record.output, slot, func.node(phi).ty == Type::V128);+ }+ }+ let data = func.blocks[block as usize];+ for value in data.start..data.end {+ let op = func.node(value).op;+ if self.liveliness.is_dead(value) || matches!(op, Op::Phi | Op::Forward) || op.is_entry_value() {+ continue;+ }+ for item in self.allocation.node_moves(value) {+ self.emit_move(item);+ }+ self.lower(value);+ let record = self.allocation.node(value);+ let slot = self.allocation.slots[value as usize];+ if record.output != NO_REGISTER && slot != NO_SLOT {+ self.store_to_slot(record.output, slot, func.node(value).ty == Type::V128);+ }+ }+ if let Some(failure) = self.failure {+ return Err(failure);+ }+ }+ self.out_of_line();+ let code = self.asm.finish().map_err(|_| crate::CompileFailure::CodeGeneration)?;+ Ok(Generated {+ code,+ frame_size: self.frame_size,+ exception_sites: self.exception_sites,+ })+ }++ // Frames.++ fn prologue(&mut self) {+ let func = self.func;+ let instance = gpr(convention::INSTANCE_REGISTER);+ self.asm.stp(FP, LR, PairOperand::PreIndex(SP, -16));+ self.asm.add_imm(Width::W64, FP, SP, 16, false);+ // NB: The header goes below sp first, since nothing may be stored below sp. The instance goes in it before the+ // stack check, which traps through the frame.+ let header = (convention::FRAME_HEADER_SIZE - 16) as u32;+ self.asm.sub_imm(Width::W64, SP, SP, header, false);+ self.asm+ .str(Width::W64, instance, MemOperand::Offset(FP, convention::FRAME_INSTANCE));+ self.asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(instance, offset_of!(InstanceData, context) as i32),+ );+ self.asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(SCRATCH, offset_of!(ExecutionContext, stack_limit) as i32),+ );+ self.asm.add_any(ADDRESS, FP, -i64::from(self.frame_size), ADDRESS);+ self.asm.cmp(Width::W64, ADDRESS, SCRATCH);+ let overflow = self.trap_label(libwasm_module::abi::TRAP_STACK_EXHAUSTED);+ self.asm.b_cond(Cond::Lo, overflow);+ self.asm.mov_sp(SP, ADDRESS);+ // Values arriving in registers that have slots.+ let data = func.blocks[0];+ for value in data.start..data.end {+ let node = func.node(value);+ if self.liveliness.is_dead(value) || !matches!(node.op, Op::Param | Op::MemoryBase) {+ continue;+ }+ let record = self.allocation.node(value);+ let slot = self.allocation.slots[value as usize];+ if record.output != NO_REGISTER && slot != NO_SLOT {+ self.store_to_slot(record.output, slot, node.ty == Type::V128);+ }+ }+ }++ /// Has the runtime unwind the exception in `exception` from this frame, and continues where it says: at a call+ /// that checks for exceptions, or in the entry trampoline.+ fn throw(&mut self, exception: Gpr) {+ let context = SCRATCH;+ self.asm+ .ldr(Width::W64, context, MemOperand::Offset(FP, convention::FRAME_INSTANCE));+ self.asm.ldr(+ Width::W64,+ context,+ MemOperand::Offset(context, offset_of!(InstanceData, context) as i32),+ );+ let arguments = offset_of!(ExecutionContext, arguments) as i32;+ self.asm+ .str(Width::W64, exception, MemOperand::Offset(context, arguments));+ self.asm.str(Width::W64, FP, MemOperand::Offset(context, arguments + 8));+ self.asm.mov(Width::W64, Gpr(0), context);+ self.asm.mov_imm(Width::W64, ADDRESS, self.runtime.throw);+ self.asm.blr(ADDRESS);+ crate::stubs::resume(&mut self.asm, Gpr(0));+ }++ fn epilogue(&mut self) {+ self.asm.sub_imm(Width::W64, SP, FP, 16, false);+ self.asm.ldp(FP, LR, PairOperand::PostIndex(SP, 16));+ self.asm.ret();+ }++ /// Sets sp back to the bottom of the frame, after a call.+ fn reset_sp(&mut self) {+ self.asm.add_any(SP, FP, -i64::from(self.frame_size), ADDRESS);+ }++ fn trap_label(&mut self, code: u32) -> Label {+ if let Some(label) = self.trap_labels[code as usize] {+ return label;+ }+ let label = self.asm.new_label();+ self.trap_labels[code as usize] = Some(label);+ label+ }++ fn dynamic_trap_label(&mut self) -> Label {+ *self.dynamic_trap.get_or_insert_with(|| self.asm.new_label())+ }++ fn out_of_line(&mut self) {+ self.subtype_checks();+ let stubs = std::mem::take(&mut self.edge_stubs);+ for stub in &stubs {+ self.asm.bind(stub.label);+ for item in self.allocation.edge(stub.slot) {+ self.emit_move(item);+ }+ let target = self.block_labels[stub.target as usize];+ self.asm.b(target);+ }+ for code in 0..self.trap_labels.len() {+ if let Some(label) = self.trap_labels[code] {+ self.asm.bind(label);+ self.asm.mov_imm(Width::W32, Gpr(0), code as u64);+ self.asm.mov_imm(Width::W64, SCRATCH, self.runtime.trap_exit);+ self.asm.br(SCRATCH);+ }+ }+ if let Some(label) = self.dynamic_trap {+ // NB: The code is in x0 already.+ self.asm.bind(label);+ self.asm.mov_imm(Width::W64, SCRATCH, self.runtime.trap_exit);+ self.asm.br(SCRATCH);+ }+ }++ // Addresses.++ /// An operand for an access of `1 << size_log2` bytes at `base` + `offset`, through `ADDRESS` where the offset does+ /// not fit.+ pub(crate) fn operand(&mut self, base: Gpr, offset: i64, size_log2: u32) -> MemOperand {+ if fits_offset(offset, size_log2) {+ return MemOperand::Offset(base, offset as i32);+ }+ self.asm.add_any(ADDRESS, base, offset, ADDRESS);+ MemOperand::Offset(ADDRESS, 0)+ }++ /// The sp offset of the frame slot at fp offset `slot`.+ fn frame_offset(&self, slot: i32) -> i64 {+ i64::from(self.frame_size) + i64::from(slot)+ }++ fn location_operand(&mut self, location: Location, size_log2: u32) -> MemOperand {+ let offset = match location {+ Location::Slot(slot) => self.frame_offset(slot),+ Location::Outgoing(index) => 8 * i64::from(index),+ _ => unreachable!("{location:?} is no frame location"),+ };+ self.operand(SP, offset, size_log2)+ }++ // Moves.++ /// Loads (if `load`) or stores the register `register` at `operand`: 8 bytes, or 16 for a vector.+ fn transfer(&mut self, register: Register, operand: MemOperand, vector: bool, load: bool) {+ let op = if vector {+ fpr_access(4, load)+ } else if convention::is_fpr(register) {+ fpr_access(3, load)+ } else {+ gpr_access(3, load)+ };+ let encoding = if convention::is_fpr(register) {+ fpr(register).0+ } else {+ gpr(register).0+ };+ self.asm.load_store(op, encoding, operand);+ }++ fn store_to_slot(&mut self, register: Register, slot: i32, vector: bool) {+ let operand = self.location_operand(Location::Slot(slot), if vector { 4 } else { 3 });+ self.transfer(register, operand, vector, false);+ }++ /// The bits of a constant of any type.+ fn constant_bits(&self, value: Value) -> u128 {+ let node = self.func.node(value);+ match node.op {+ Op::Const128 => self.func.constants[node.args[0] as usize],+ _ => u128::from(node.constant().expect("only constants have bits")),+ }+ }++ /// Puts the constant `bits` into the vector register `register`: its low 64 bits, or all 128 if `vector`.+ pub(crate) fn load_vector_constant(&mut self, bits: u128, register: Fpr, vector: bool) {+ let (low, high) = (bits as u64, (bits >> 64) as u64);+ if low == 0 {+ self.asm.fmov_from_gpr(register, XZR);+ } else {+ self.asm.mov_imm(Width::W64, SCRATCH, low);+ self.asm.fmov_from_gpr(register, SCRATCH);+ }+ if vector && high != 0 {+ let source = if high == low {+ SCRATCH+ } else {+ self.asm.mov_imm(Width::W64, SCRATCH, high);+ SCRATCH+ };+ self.asm.insert_lane_from_gpr(register, 3, 1, source);+ }+ }++ /// Materializes the constant `value` into `register`.+ fn materialize(&mut self, value: Value, register: Register) {+ let ty = self.func.node(value).ty;+ let bits = self.constant_bits(value);+ if convention::is_fpr(register) {+ self.load_vector_constant(bits, fpr(register), ty == Type::V128);+ } else {+ let bits = if ty.is_64() {+ bits as u64+ } else {+ bits as u64 & 0xffff_ffff+ };+ self.asm.mov_imm(Width::W64, gpr(register), bits);+ }+ }++ /// Stores the constant `value` at `operand` (which does not use x16), as 8 bytes, or 16 for a vector.+ fn store_constant(&mut self, value: Value, location: Location) {+ let node = self.func.node(value);+ if node.op == Op::Const128 {+ let bits = self.constant_bits(value);+ for (half, bits) in [(0, bits as u64), (1, (bits >> 64) as u64)] {+ let source = if bits == 0 {+ XZR+ } else {+ self.asm.mov_imm(Width::W64, SCRATCH, bits);+ SCRATCH+ };+ let operand = self.half_operand(location, half);+ self.asm.str(Width::W64, source, operand);+ }+ return;+ }+ let bits = node.constant().expect("only constants are stored as constants");+ let bits = if node.ty.is_64() { bits } else { bits & 0xffff_ffff };+ let source = if bits == 0 {+ XZR+ } else {+ self.asm.mov_imm(Width::W64, SCRATCH, bits);+ SCRATCH+ };+ let operand = self.location_operand(location, 3);+ self.asm.str(Width::W64, source, operand);+ }++ /// The operand of the 8-byte half `half` of the frame location `location`.+ fn half_operand(&mut self, location: Location, half: i32) -> MemOperand {+ let location = match location {+ Location::Slot(slot) => Location::Slot(slot + 8 * half),+ Location::Outgoing(index) => Location::Outgoing(index + half as u32),+ _ => unreachable!("{location:?} is no frame location"),+ };+ self.location_operand(location, 3)+ }++ /// Copies a vector register.+ pub(crate) fn move_vector(&mut self, to: Fpr, from: Fpr) {+ if to != from {+ self.asm.mov_vector(to, from);+ }+ }++ pub(crate) fn emit_move(&mut self, item: &Move) {+ match (item.from, item.to) {+ (Location::Register(from), Location::Register(to)) => {+ if from == to {+ return;+ }+ match (convention::is_fpr(from), convention::is_fpr(to)) {+ (true, true) => self.move_vector(fpr(to), fpr(from)),+ (false, false) => self.asm.mov(Width::W64, gpr(to), gpr(from)),+ (true, false) => self.asm.fmov_to_gpr(gpr(to), fpr(from)),+ (false, true) => self.asm.fmov_from_gpr(fpr(to), gpr(from)),+ }+ }+ (Location::Constant(value), Location::Register(to)) => self.materialize(value, to),+ (Location::Register(from), to @ (Location::Slot(_) | Location::Outgoing(_))) => {+ let operand = self.location_operand(to, if item.vector { 4 } else { 3 });+ self.transfer(from, operand, item.vector, false);+ }+ (from @ (Location::Slot(_) | Location::Outgoing(_)), Location::Register(to)) => {+ let operand = self.location_operand(from, if item.vector { 4 } else { 3 });+ self.transfer(to, operand, item.vector, true);+ }+ (Location::Constant(value), to @ (Location::Slot(_) | Location::Outgoing(_))) => {+ self.store_constant(value, to);+ }+ (from @ Location::Slot(_), to @ (Location::Slot(_) | Location::Outgoing(_))) => {+ let size_log2 = if item.vector { 4 } else { 3 };+ let operand = self.location_operand(from, size_log2);+ let register = if item.vector { SCRATCH_FPR.0 } else { SCRATCH.0 };+ let (load, store) = if item.vector {+ (fpr_access(4, true), fpr_access(4, false))+ } else {+ (gpr_access(3, true), gpr_access(3, false))+ };+ self.asm.load_store(load, register, operand);+ let operand = self.location_operand(to, size_log2);+ self.asm.load_store(store, register, operand);+ }+ (from, Location::ResultArea(index)) => {+ // The value goes through a vector register, or x16; the area's address takes x17.+ let (register, op) = match from {+ Location::Register(register) if convention::is_fpr(register) => (+ fpr(register).0,+ if item.vector {+ fpr_access(4, false)+ } else {+ fpr_access(3, false)+ },+ ),+ Location::Register(register) => (gpr(register).0, gpr_access(3, false)),+ Location::Slot(slot) => {+ let size_log2 = if item.vector { 4 } else { 3 };+ let operand = self.location_operand(Location::Slot(slot), size_log2);+ self.asm.load_store(fpr_access(size_log2, true), SCRATCH_FPR.0, operand);+ (SCRATCH_FPR.0, fpr_access(size_log2, false))+ }+ Location::Constant(value) => {+ let bits = self.constant_bits(value);+ self.load_vector_constant(bits, SCRATCH_FPR, item.vector);+ let size_log2 = if item.vector { 4 } else { 3 };+ (SCRATCH_FPR.0, fpr_access(size_log2, false))+ }+ _ => unreachable!("results do not come from {from:?}"),+ };+ let pointer = convention::home_slot_offset(convention::result_area_pointer(&self.func.params));+ let operand = self.location_operand(Location::Slot(pointer), 3);+ self.asm.ldr(Width::W64, ADDRESS, operand);+ let operand = MemOperand::Offset(ADDRESS, 8 * index as i32);+ let operand = if fits_offset(8 * i64::from(index), op.size_log2()) {+ operand+ } else {+ self.asm.add_any(ADDRESS, ADDRESS, 8 * i64::from(index), ADDRESS);+ MemOperand::Offset(ADDRESS, 0)+ };+ self.asm.load_store(op, register, operand);+ }+ (from, to) => unreachable!("no move from {from:?} to {to:?}"),+ }+ }++ // Control.++ /// The label an edge jumps to: its target's, or a stub's that moves values into place first.+ fn edge_label(&mut self, slot: u32, target: BlockId) -> Label {+ if self.allocation.edge(slot).is_empty() {+ return self.block_labels[target as usize];+ }+ let label = self.asm.new_label();+ self.edge_stubs.push(EdgeStub { label, slot, target });+ label+ }++ /// Ends the block on its edge `index` without a condition.+ fn jump(&mut self, index: usize) {+ let block = self.block;+ let slot = self.func.blocks[block as usize].successors_start + index as u32;+ let target = self.func.successors(block)[index];+ for item in self.allocation.edge(slot) {+ self.emit_move(item);+ }+ if target != block + 1 {+ let label = self.block_labels[target as usize];+ self.asm.b(label);+ }+ }++ /// Ends the block with a two-way branch on `cond`, which holds for the first successor; inverted where the taken+ /// successor comes next and needs no moves.+ fn branch_on(&mut self, cond: Cond) {+ let block = self.block;+ let data = self.func.blocks[block as usize];+ let successors = self.func.successors(block);+ let (taken, fallthrough) = (successors[0], successors[1]);+ if taken == block + 1 && self.allocation.edge(data.successors_start).is_empty() {+ let label = self.edge_label(data.successors_start + 1, fallthrough);+ self.asm.b_cond(cond.invert(), label);+ return;+ }+ let taken_label = self.edge_label(data.successors_start, taken);+ self.asm.b_cond(cond, taken_label);+ for item in self.allocation.edge(data.successors_start + 1) {+ self.emit_move(item);+ }+ if fallthrough != block + 1 {+ let label = self.block_labels[fallthrough as usize];+ self.asm.b(label);+ }+ }++ fn lower_terminator(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ match node.op {+ Op::Jump => self.jump(0),+ Op::Branch => {+ self.asm.cmp_imm(Width::W32, gpr(record.inputs[0]), 0, false);+ self.branch_on(Cond::Ne);+ }+ Op::BranchCompare => {+ let ty = func.node(node.args[0]).ty;+ self.compare(value, ty, record.inputs[0], record.inputs[1], 1);+ self.branch_on(condition(IntCondition::from_flags(node.flags)));+ }+ Op::BranchFloatCompare => {+ let ty = func.node(node.args[0]).ty;+ self.asm+ .float_compare(float_size(ty), fpr(record.inputs[0]), fpr(record.inputs[1]));+ self.branch_on(float_condition(FloatCondition::from_flags(node.flags)));+ }+ Op::BrTable => self.branch_table(value),+ Op::Return => self.epilogue(),+ Op::TailCall => self.lower_tail_call(value),+ Op::Trap => {+ let label = self.trap_label(node.args[0]);+ self.asm.b(label);+ }+ Op::Throw => self.throw(gpr(record.inputs[0])),+ _ => unreachable!("{} is no terminator", node.op.name()),+ }+ }++ fn branch_table(&mut self, value: Value) {+ let func = self.func;+ let block = self.block;+ let data = func.blocks[block as usize];+ let record = *self.allocation.node(value);+ let index = gpr(record.inputs[0]);+ let successors = func.successors(block);+ let mut labels = Vec::with_capacity(successors.len());+ for (position, &successor) in successors.iter().enumerate() {+ let label = self.edge_label(data.successors_start + position as u32, successor);+ labels.push(label);+ }+ let targets = func.table_targets(value);+ let (cases, default) = targets.split_at(targets.len() - 1);+ let default = labels[default[0] as usize];+ self.compare_immediate(Width::W32, index, cases.len() as u64);+ self.asm.b_cond(Cond::Hs, default);+ // The table is a branch per case, right after the indirect branch into it.+ let table = self.asm.new_label();+ self.asm.reserve_room(4 * (cases.len() + 4));+ self.asm.adr(SCRATCH, table);+ self.asm+ .add_extended(Width::W64, SCRATCH, SCRATCH, index, Extend::Uxtw, 2);+ self.asm.br(SCRATCH);+ self.asm.bind(table);+ for case in cases {+ self.asm.b(labels[*case as usize]);+ }+ }++ /// `cmp register, #immediate`, through x16 where the immediate does not fit.+ fn compare_immediate(&mut self, width: Width, register: Gpr, immediate: u64) {+ let immediate = if width == Width::W32 {+ immediate & 0xffff_ffff+ } else {+ immediate+ };+ let negated = match width {+ Width::W32 => (immediate as u32).wrapping_neg() as u64,+ Width::W64 => immediate.wrapping_neg(),+ };+ if immediate < 4096 {+ self.asm.cmp_imm(width, register, immediate as u32, false);+ } else if immediate & 0xfff == 0 && immediate < (1 << 24) {+ self.asm.cmp_imm(width, register, (immediate >> 12) as u32, true);+ } else if negated < 4096 {+ self.asm.cmn_imm(width, register, negated as u32, false);+ } else {+ self.asm.mov_imm(Width::W64, SCRATCH, immediate);+ self.asm.cmp(width, register, SCRATCH);+ }+ }++ /// `cmp a, b` of type `ty`, where `b` is input `index` of `value`: an immediate if it is a constant.+ fn compare(&mut self, value: Value, ty: Type, a: Register, b: Register, index: usize) {+ if b == crate::regalloc::CONSTANT_INPUT {+ let bits = self.immediate(value, index);+ self.compare_immediate(width(ty), gpr(a), bits);+ } else {+ self.asm.cmp(width(ty), gpr(a), gpr(b));+ }+ }++ fn lower(&mut self, value: Value) {+ let node = self.func.node(value);+ match node.op {+ op if op.is_terminator() => self.lower_terminator(value),+ Op::Load+ | Op::Store+ | Op::GlobalGet+ | Op::GlobalSet+ | Op::InstanceField+ | Op::LoadPointer+ | Op::FrameLoad+ | Op::VectorLoad => self.lower_memory(value),+ Op::Call | Op::CallResult => self.lower_call(value),+ Op::Offset+ | Op::ReadField+ | Op::WriteField+ | Op::TableElement+ | Op::TableStore+ | Op::CalleeInstance+ | Op::CheckNull+ | Op::CheckFunction+ | Op::Helper => self.lower_runtime(value),+ Op::CheckedAddress+ | Op::AtomicRmw+ | Op::AtomicCompareExchange+ | Op::AtomicFence+ | Op::Rtt+ | Op::I31New+ | Op::I31Get+ | Op::ElementAddress+ | Op::RefTest => self.lower_gc(value),+ Op::VectorUnary+ | Op::VectorBinary+ | Op::VectorTernary+ | Op::ExtractLane+ | Op::ReplaceLane+ | Op::Shuffle => self.lower_vector(value),+ _ => self.lower_numeric(value),+ }+ }++ /// The constant of input `index` of `value`, which code generation uses as an immediate.+ fn immediate(&self, value: Value, index: usize) -> u64 {+ let input = self.func.inputs(value)[index];+ self.func.node(input).constant().expect("immediates are constants")+ }++ /// The register of an input that may be a constant: its own, or x16 with the constant in it.+ fn input_or_scratch(&mut self, value: Value, index: usize, register: Register, ty: Type) -> Gpr {+ if register != crate::regalloc::CONSTANT_INPUT {+ return gpr(register);+ }+ let bits = self.immediate(value, index);+ let bits = if ty.is_64() { bits } else { bits & 0xffff_ffff };+ if bits == 0 {+ return XZR;+ }+ self.asm.mov_imm(Width::W64, SCRATCH, bits);+ SCRATCH+ }+}++/// Generates the code of `func`.+pub fn generate(+ func: &Func,+ liveliness: &Liveliness,+ allocation: &Allocation,+ runtime: &RuntimeInfo,+) -> Result<Generated, crate::CompileFailure> {+ let _ = (NONE, Shift::Lsl);+ CodeGenerator::new(func, liveliness, allocation, runtime).generate()+}diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/numeric.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/numeric.rsnew file mode 100644index 00000000000..65b6afabf3d--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/numeric.rs@@ -0,0 +1,348 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Integer and float arithmetic, comparisons, selects and conversions.++use super::{ADDRESS, CodeGenerator, SCRATCH, SCRATCH_FPR, condition, float_condition, float_size, fpr, gpr, width};+use crate::asm::Width;+use crate::asm::aarch64::{+ Cond, FloatBinary, FloatSize, FloatUnary, Shift, VectorArrangement, encode_logical_immediate,+};+use crate::convention::Register;+use crate::ir::{FLAG_CANNOT_TRAP, FloatCondition, IntCondition, Op, Type, Value};+use crate::regalloc::CONSTANT_INPUT;+use libwasm_module::abi::{TRAP_INTEGER_DIVIDE_BY_ZERO, TRAP_INTEGER_OVERFLOW, TRAP_INVALID_CONVERSION};++/// The bits of a width.+fn mask(width: Width) -> u64 {+ match width {+ Width::W32 => 0xffff_ffff,+ Width::W64 => u64::MAX,+ }+}++fn float_bits(ty: Type, value: f64) -> u64 {+ if ty == Type::F64 {+ value.to_bits()+ } else {+ u64::from((value as f32).to_bits())+ }+}++impl CodeGenerator<'_> {+ pub(super) fn lower_numeric(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ let [a, b, c] = record.inputs;+ let output = record.output;+ let ty = node.ty;+ match node.op {+ Op::Add | Op::Sub => self.add_sub(value, node.op == Op::Sub, ty, output, a, b),+ Op::And | Op::Or | Op::Xor => self.logic(value, node.op, ty, output, a, b),+ Op::Mul => {+ let rhs = self.input_or_scratch(value, 1, b, ty);+ self.asm.mul(width(ty), gpr(output), gpr(a), rhs);+ }+ Op::Shl | Op::ShrS | Op::ShrU => {+ let (dst, source) = (gpr(output), gpr(a));+ if b == CONSTANT_INPUT {+ let amount = (self.immediate(value, 1) as u32 & (if ty == Type::I64 { 63 } else { 31 })) as u8;+ match node.op {+ Op::Shl => self.asm.lsl_imm(width(ty), dst, source, amount),+ Op::ShrS => self.asm.asr_imm(width(ty), dst, source, amount),+ _ => self.asm.lsr_imm(width(ty), dst, source, amount),+ }+ } else {+ // NB: The register forms take the amount modulo the width, as WebAssembly does.+ match node.op {+ Op::Shl => self.asm.lsl(width(ty), dst, source, gpr(b)),+ Op::ShrS => self.asm.asr(width(ty), dst, source, gpr(b)),+ _ => self.asm.lsr(width(ty), dst, source, gpr(b)),+ }+ }+ }+ Op::Rotl | Op::Rotr => {+ let (dst, source) = (gpr(output), gpr(a));+ let bits = if ty == Type::I64 { 64 } else { 32 };+ if b == CONSTANT_INPUT {+ let amount = self.immediate(value, 1) as u32 % bits;+ let right = if node.op == Op::Rotr {+ amount+ } else {+ (bits - amount) % bits+ };+ self.asm.ror_imm(width(ty), dst, source, right as u8);+ } else if node.op == Op::Rotr {+ self.asm.ror(width(ty), dst, source, gpr(b));+ } else {+ // A left rotation is a right rotation by the negated amount, modulo the width.+ self.asm.neg(width(ty), SCRATCH, gpr(b));+ self.asm.ror(width(ty), dst, source, SCRATCH);+ }+ }+ Op::DivS | Op::DivU | Op::RemS | Op::RemU => self.divide(value, ty, output, a, b),+ Op::Clz => self.asm.clz(width(ty), gpr(output), gpr(a)),+ Op::Ctz => {+ self.asm.rbit(width(ty), SCRATCH, gpr(a));+ self.asm.clz(width(ty), gpr(output), SCRATCH);+ }+ Op::Popcnt => {+ self.asm.fmov_from_gpr(SCRATCH_FPR, gpr(a));+ self.asm.vector_count_bits(SCRATCH_FPR, SCRATCH_FPR);+ self.asm+ .vector_add_across(VectorArrangement::B8, SCRATCH_FPR, SCRATCH_FPR);+ self.asm.fmov_to_gpr(gpr(output), SCRATCH_FPR);+ }+ Op::Eqz => {+ let input_type = func.node(node.args[0]).ty;+ self.asm.cmp_imm(width(input_type), gpr(a), 0, false);+ self.asm.cset(Width::W32, gpr(output), Cond::Eq);+ }+ Op::Compare => {+ let input_type = func.node(node.args[0]).ty;+ self.compare(value, input_type, a, b, 1);+ self.asm+ .cset(Width::W32, gpr(output), condition(IntCondition::from_flags(node.flags)));+ }+ Op::Extend8S => self.asm.sxtb(width(ty), gpr(output), gpr(a)),+ Op::Extend16S => self.asm.sxth(width(ty), gpr(output), gpr(a)),+ Op::Extend32S | Op::ExtendI32S => self.asm.sxtw(gpr(output), gpr(a)),+ Op::ExtendI32U | Op::Wrap => self.asm.mov(Width::W32, gpr(output), gpr(a)),+ Op::Select => {+ if ty == Type::V128 {+ let skip = self.asm.new_label();+ self.move_vector(fpr(output), fpr(c));+ self.asm.cbz(Width::W32, gpr(a), skip);+ self.move_vector(fpr(output), fpr(b));+ self.asm.bind(skip);+ } else if ty.is_float() {+ self.asm.cmp_imm(Width::W32, gpr(a), 0, false);+ self.asm+ .float_select(FloatSize::Double, fpr(output), fpr(b), fpr(c), Cond::Ne);+ } else {+ self.asm.cmp_imm(Width::W32, gpr(a), 0, false);+ self.asm.csel(Width::W64, gpr(output), gpr(b), gpr(c), Cond::Ne);+ }+ }+ Op::FAdd | Op::FSub | Op::FMul | Op::FDiv | Op::FMin | Op::FMax => {+ let op = match node.op {+ Op::FAdd => FloatBinary::Add,+ Op::FSub => FloatBinary::Sub,+ Op::FMul => FloatBinary::Mul,+ Op::FDiv => FloatBinary::Div,+ // NB: fmin and fmax propagate NaNs and order -0 below +0, as WebAssembly's min and max do.+ Op::FMin => FloatBinary::Min,+ _ => FloatBinary::Max,+ };+ self.asm.float_binary(op, float_size(ty), fpr(output), fpr(a), fpr(b));+ }+ Op::FCopysign => {+ let w = width(ty);+ let sign = if ty == Type::F64 { 1u64 << 63 } else { 1 << 31 };+ let size = float_size(ty);+ self.asm.float_to_gpr(size, SCRATCH, fpr(a));+ self.asm.float_to_gpr(size, ADDRESS, fpr(b));+ self.asm.and_imm(w, SCRATCH, SCRATCH, !sign & mask(w));+ self.asm.and_imm(w, ADDRESS, ADDRESS, sign);+ self.asm.orr(w, SCRATCH, SCRATCH, ADDRESS, Shift::Lsl, 0);+ self.asm.gpr_to_float(size, fpr(output), SCRATCH);+ }+ Op::FAbs | Op::FNeg | Op::FSqrt | Op::FCeil | Op::FFloor | Op::FTrunc | Op::FNearest => {+ let op = match node.op {+ Op::FAbs => FloatUnary::Abs,+ Op::FNeg => FloatUnary::Neg,+ Op::FSqrt => FloatUnary::Sqrt,+ Op::FCeil => FloatUnary::RoundUp,+ Op::FFloor => FloatUnary::RoundDown,+ Op::FTrunc => FloatUnary::RoundTowardZero,+ _ => FloatUnary::RoundNearest,+ };+ self.asm.float_unary(op, float_size(ty), fpr(output), fpr(a));+ }+ Op::FloatCompare => {+ let input_type = func.node(node.args[0]).ty;+ self.asm.float_compare(float_size(input_type), fpr(a), fpr(b));+ let cond = float_condition(FloatCondition::from_flags(node.flags));+ self.asm.cset(Width::W32, gpr(output), cond);+ }+ Op::TruncS | Op::TruncU => self.truncate(value, ty, output, a),+ Op::TruncSatS | Op::TruncSatU => {+ // NB: The conversions saturate, and give 0 for NaN, as the saturating truncations want.+ let input = func.node(node.args[0]).ty;+ self.asm.convert_to_integer(+ node.op == Op::TruncSatS,+ width(ty),+ float_size(input),+ gpr(output),+ fpr(a),+ );+ }+ Op::ConvertS | Op::ConvertU => {+ let input = func.node(node.args[0]).ty;+ self.asm.convert_to_float(+ node.op == Op::ConvertS,+ width(input),+ float_size(ty),+ fpr(output),+ gpr(a),+ );+ }+ Op::Demote => self.asm.float_convert(FloatSize::Double, fpr(output), fpr(a)),+ Op::Promote => self.asm.float_convert(FloatSize::Single, fpr(output), fpr(a)),+ Op::Reinterpret => {+ if ty.is_float() {+ self.asm.gpr_to_float(float_size(ty), fpr(output), gpr(a));+ } else {+ let input = func.node(node.args[0]).ty;+ self.asm.float_to_gpr(float_size(input), gpr(output), fpr(a));+ }+ }+ _ => unreachable!("{} is no numeric op", node.op.name()),+ }+ }++ fn add_sub(&mut self, value: Value, subtract: bool, ty: Type, output: Register, a: Register, b: Register) {+ let w = width(ty);+ let (dst, lhs) = (gpr(output), gpr(a));+ if b == CONSTANT_INPUT {+ let bits = self.immediate(value, 1);+ let bits = if ty.is_64() { bits } else { bits & 0xffff_ffff };+ let negated = match w {+ Width::W32 => u64::from((bits as u32).wrapping_neg()),+ Width::W64 => bits.wrapping_neg(),+ };+ // The immediate forms take 12 bits, optionally shifted by 12, and subtracting adds the negation.+ let (add, magnitude) = if bits < (1 << 24) {+ (!subtract, bits)+ } else if negated < (1 << 24) {+ (subtract, negated)+ } else {+ self.asm.mov_imm(Width::W64, SCRATCH, bits);+ if subtract {+ self.asm.sub(w, dst, lhs, SCRATCH, Shift::Lsl, 0);+ } else {+ self.asm.add(w, dst, lhs, SCRATCH, Shift::Lsl, 0);+ }+ return;+ };+ let (high, low) = ((magnitude >> 12) as u32, (magnitude & 0xfff) as u32);+ let mut source = lhs;+ if high != 0 {+ if add {+ self.asm.add_imm(w, dst, source, high, true);+ } else {+ self.asm.sub_imm(w, dst, source, high, true);+ }+ source = dst;+ }+ if low != 0 || source != dst {+ if add {+ self.asm.add_imm(w, dst, source, low, false);+ } else {+ self.asm.sub_imm(w, dst, source, low, false);+ }+ }+ return;+ }+ if subtract {+ self.asm.sub(w, dst, lhs, gpr(b), Shift::Lsl, 0);+ } else {+ self.asm.add(w, dst, lhs, gpr(b), Shift::Lsl, 0);+ }+ }++ fn logic(&mut self, value: Value, op: Op, ty: Type, output: Register, a: Register, b: Register) {+ let w = width(ty);+ let (dst, lhs) = (gpr(output), gpr(a));+ if b == CONSTANT_INPUT {+ let bits = self.immediate(value, 1) & mask(w);+ if encode_logical_immediate(bits, w).is_some() {+ match op {+ Op::And => self.asm.and_imm(w, dst, lhs, bits),+ Op::Or => self.asm.orr_imm(w, dst, lhs, bits),+ _ => self.asm.eor_imm(w, dst, lhs, bits),+ }+ return;+ }+ }+ let rhs = self.input_or_scratch(value, 1, b, ty);+ match op {+ Op::And => self.asm.and(w, dst, lhs, rhs, Shift::Lsl, 0),+ Op::Or => self.asm.orr(w, dst, lhs, rhs, Shift::Lsl, 0),+ _ => self.asm.eor(w, dst, lhs, rhs, Shift::Lsl, 0),+ }+ }++ /// Division and remainder. The hardware gives 0 for a zero divisor and INT_MIN for INT_MIN / -1, so both are+ /// checked; the remainder of INT_MIN and -1 comes out 0 as it should.+ fn divide(&mut self, value: Value, ty: Type, output: Register, a: Register, b: Register) {+ let node = *self.func.node(value);+ let w = width(ty);+ let (dst, dividend, divisor) = (gpr(output), gpr(a), gpr(b));+ let checked = node.flags & FLAG_CANNOT_TRAP == 0;+ if checked {+ let zero = self.trap_label(TRAP_INTEGER_DIVIDE_BY_ZERO);+ self.asm.cbz(w, divisor, zero);+ }+ let signed = matches!(node.op, Op::DivS | Op::RemS);+ if node.op == Op::DivS && checked {+ let divide = self.asm.new_label();+ let overflow = self.trap_label(TRAP_INTEGER_OVERFLOW);+ self.asm.cmn_imm(w, divisor, 1, false);+ self.asm.b_cond(Cond::Ne, divide);+ // INT_MIN - 1 is the only subtraction of 1 that overflows.+ self.asm.cmp_imm(w, dividend, 1, false);+ self.asm.b_cond(Cond::Vs, overflow);+ self.asm.bind(divide);+ }+ let quotient = if matches!(node.op, Op::DivS | Op::DivU) {+ dst+ } else {+ SCRATCH+ };+ if signed {+ self.asm.sdiv(w, quotient, dividend, divisor);+ } else {+ self.asm.udiv(w, quotient, dividend, divisor);+ }+ if quotient == SCRATCH {+ self.asm.msub(w, dst, SCRATCH, divisor, dividend);+ }+ }++ /// Compares `source` with the float constant `bound` of type `input`, with v31 holding the bound.+ fn compare_with_constant(&mut self, input: Type, source: Register, bound: f64) {+ let bits = float_bits(input, bound);+ self.load_vector_constant(u128::from(bits), SCRATCH_FPR, false);+ self.asm.float_compare(float_size(input), fpr(source), SCRATCH_FPR);+ }++ /// The trapping truncations of floats to integers: NaN is invalid, and values out of range overflow.+ fn truncate(&mut self, value: Value, ty: Type, output: Register, source: Register) {+ let node = *self.func.node(value);+ let input = self.func.node(node.args[0]).ty;+ let invalid = self.trap_label(TRAP_INVALID_CONVERSION);+ let overflow = self.trap_label(TRAP_INTEGER_OVERFLOW);+ self.asm.float_compare(float_size(input), fpr(source), fpr(source));+ self.asm.b_cond(Cond::Vs, invalid);+ let signed = node.op == Op::TruncS;+ let bits = if ty == Type::I64 { 64 } else { 32 };+ let limit = 2f64.powi(if signed { bits - 1 } else { bits });+ // The lower bound: values at or below it overflow (or below it, where it is exact).+ let (lower, below_only) = match (signed, bits, input) {+ (true, 32, Type::F64) => (-limit - 1.0, false),+ (true, _, _) => (-limit, true),+ (false, _, _) => (-1.0, false),+ };+ self.compare_with_constant(input, source, lower);+ self.asm.b_cond(if below_only { Cond::Lo } else { Cond::Ls }, overflow);+ self.compare_with_constant(input, source, limit);+ self.asm.b_cond(Cond::Hs, overflow);+ self.asm+ .convert_to_integer(signed, width(ty), float_size(input), gpr(output), fpr(source));+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rsnew file mode 100644index 00000000000..78ff2e40eb2--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rs@@ -0,0 +1,246 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Runtime data: fields of memories, tables and segments, table elements, the checks of indirect calls, and calls of+//! the runtime's functions.++use super::{ADDRESS, CodeGenerator, FP, SCRATCH, gpr};+use crate::asm::aarch64::{Cond, Extend, MemOperand, XZR};+use crate::asm::{Gpr, Label, Width};+use crate::convention;+use crate::ir::{Helper, Op, Value};+use crate::regalloc::CONSTANT_INPUT;+use libwasm_module::abi::{+ ExecutionContext, FunctionHeader, InstanceData, Rtt, TRAP_INDIRECT_CALL_TYPE_MISMATCH, TableData,+};+use std::mem::offset_of;++/// The out-of-line part of a `CheckFunction`: whether a function whose type is not the expected one has a subtype of+/// it, which only GC modules can declare.+pub(super) struct SubtypeCheck {+ label: Label,+ back: Label,+ reference: Gpr,+ identity: Gpr,+ temps: [Gpr; 2],+}++fn field_width(bytes: u8) -> Width {+ if bytes == 4 { Width::W32 } else { Width::W64 }+}++fn field(offset: usize) -> i32 {+ offset as i32+}++impl CodeGenerator<'_> {+ pub(super) fn lower_runtime(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ let input = |index: usize| gpr(record.inputs[index]);+ match node.op {+ Op::Offset => {+ self.asm+ .add_any(gpr(record.output), input(0), i64::from(node.args[1] as i32), ADDRESS);+ }+ Op::ReadField => {+ let width = field_width(node.flags);+ let operand = self.operand(+ input(0),+ i64::from(node.args[1] as i32),+ if width == Width::W32 { 2 } else { 3 },+ );+ self.asm.ldr(width, gpr(record.output), operand);+ }+ Op::WriteField => {+ let width = field_width(node.flags);+ let source = if record.inputs[1] == CONSTANT_INPUT {+ let bits = self.immediate(value, 1);+ if bits == 0 {+ XZR+ } else {+ self.asm.mov_imm(Width::W64, SCRATCH, bits);+ SCRATCH+ }+ } else {+ input(1)+ };+ let operand = self.operand(+ input(0),+ i64::from(node.args[2] as i32),+ if width == Width::W32 { 2 } else { 3 },+ );+ self.asm.str(width, source, operand);+ }+ Op::TableElement | Op::TableStore => {+ let (table, index) = (input(0), input(1));+ self.asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(table, field(offset_of!(TableData, size))),+ );+ self.asm.cmp(Width::W64, index, SCRATCH);+ let out_of_bounds = self.trap_label(u32::from(node.flags));+ self.asm.b_cond(Cond::Hs, out_of_bounds);+ self.asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(table, field(offset_of!(TableData, elements))),+ );+ let element = MemOperand::Register {+ base: SCRATCH,+ index,+ extend: Extend::Uxtx,+ shifted: true,+ };+ if node.op == Op::TableElement {+ self.asm.ldr(Width::W64, gpr(record.output), element);+ } else {+ self.asm.str(Width::W64, input(2), element);+ }+ }+ Op::CalleeInstance => {+ let (header, caller, output) = (input(0), input(1), gpr(record.output));+ self.asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(header, field(offset_of!(FunctionHeader, instance))),+ );+ self.asm.cmp_imm(Width::W64, SCRATCH, 0, false);+ self.asm.csel(Width::W64, output, SCRATCH, caller, Cond::Ne);+ }+ Op::CheckNull => {+ let null = self.trap_label(u32::from(node.flags));+ self.asm.cbz(Width::W64, input(0), null);+ }+ Op::CheckFunction => {+ let (reference, identity) = (input(0), input(1));+ let null = self.trap_label(u32::from(node.flags));+ self.asm.cbz(Width::W64, reference, null);+ self.asm.ldr(+ Width::W32,+ SCRATCH,+ MemOperand::Offset(reference, field(offset_of!(FunctionHeader, type_identity))),+ );+ self.asm.cmp(Width::W32, SCRATCH, identity);+ let label = self.asm.new_label();+ let back = self.asm.new_label();+ self.asm.b_cond(Cond::Ne, label);+ self.asm.bind(back);+ self.subtype_checks.push(SubtypeCheck {+ label,+ back,+ reference,+ identity,+ temps: [gpr(record.temps[0]), gpr(record.temps[1])],+ });+ }+ Op::Helper => {+ let helper = Helper::from_index(node.args[2]);+ let context = Gpr(convention::HELPER_REGISTERS[0]);+ self.asm.ldr(+ Width::W64,+ context,+ MemOperand::Offset(context, field(offset_of!(InstanceData, context))),+ );+ let arguments = offset_of!(ExecutionContext, arguments) as i32;+ for index in 1..func.inputs(value).len() {+ self.asm.str(+ Width::W64,+ Gpr(convention::HELPER_REGISTERS[index]),+ MemOperand::Offset(context, arguments + 8 * (index as i32 - 1)),+ );+ }+ self.asm.mov_imm(+ Width::W64,+ SCRATCH,+ crate::runtime::helper_address(helper, self.runtime),+ );+ self.asm.blr(SCRATCH);+ let result = Gpr(convention::GPR_RESULTS[0]);+ if helper.may_trap() {+ let trap = self.dynamic_trap_label();+ self.asm.cbnz(Width::W64, result, trap);+ } else if helper.traps_on_zero() {+ let trap = self.trap_label(libwasm_module::abi::TRAP_RUNTIME);+ self.asm.cbz(Width::W64, result, trap);+ }+ }+ _ => unreachable!("{} is no runtime operation", node.op.name()),+ }+ }++ pub(super) fn subtype_checks(&mut self) {+ let checks = std::mem::take(&mut self.subtype_checks);+ if checks.is_empty() {+ return;+ }+ let mismatch = self.trap_label(TRAP_INDIRECT_CALL_TYPE_MISMATCH);+ for check in checks {+ let [rtts, actual] = check.temps;+ self.asm.bind(check.label);+ self.asm+ .ldr(Width::W64, rtts, MemOperand::Offset(FP, convention::FRAME_INSTANCE));+ self.asm.ldr(+ Width::W64,+ rtts,+ MemOperand::Offset(rtts, field(offset_of!(InstanceData, context))),+ );+ self.asm.ldr(+ Width::W64,+ rtts,+ MemOperand::Offset(rtts, field(offset_of!(ExecutionContext, rtts))),+ );+ self.asm.ldr(+ Width::W32,+ SCRATCH,+ MemOperand::Offset(check.reference, field(offset_of!(FunctionHeader, type_identity))),+ );+ let indexed = |index: Gpr, shift: bool| MemOperand::Register {+ base: rtts,+ index,+ extend: Extend::Uxtx,+ shifted: shift,+ };+ self.asm.ldr(Width::W64, actual, indexed(SCRATCH, true));+ // The expected type's Rtt, by the identity, which is zero-extended in its register.+ let target = rtts;+ self.asm.ldr(Width::W64, target, indexed(check.identity, true));+ self.asm.ldr(+ Width::W32,+ SCRATCH,+ MemOperand::Offset(target, field(offset_of!(Rtt, depth))),+ );+ // The expected type is a supertype if it is at its depth in the actual type's display.+ self.asm.ldr(+ Width::W32,+ ADDRESS,+ MemOperand::Offset(actual, field(offset_of!(Rtt, depth))),+ );+ self.asm.cmp(Width::W32, ADDRESS, SCRATCH);+ self.asm.b_cond(Cond::Lo, mismatch);+ self.asm.ldr(+ Width::W64,+ actual,+ MemOperand::Offset(actual, field(offset_of!(Rtt, display))),+ );+ self.asm.ldr(+ Width::W32,+ actual,+ MemOperand::Register {+ base: actual,+ index: SCRATCH,+ extend: Extend::Uxtx,+ shifted: true,+ },+ );+ self.asm.cmp(Width::W32, actual, check.identity);+ self.asm.b_cond(Cond::Ne, mismatch);+ self.asm.b(check.back);+ }+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/vector.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/vector.rsnew file mode 100644index 00000000000..a180991d167--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/vector.rs@@ -0,0 +1,828 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Vectors: v128 loads, lanes and SIMD arithmetic, as Advanced SIMD instructions.+//!+//! The allocator gives a vector node an output register apart from its inputs, so a lowering may write its output+//! before it has read all inputs; v30 and v31 are the scratch registers. Inputs may share a register (`i32x4.add x+//! x`), and are never written. Where the interpreter's instruction sequence decides bits the spec leaves open (NaN+//! payloads of min and max, relaxed instructions), the lowering is the same sequence, with each of its operations+//! expanded as the interpreter's AArch64 code expands it, so that both tiers agree bit for bit.++use super::{CodeGenerator, SCRATCH, SCRATCH_FPR, SCRATCH_FPR2, fpr, fpr_access, gpr};+use crate::asm::aarch64::{MemOperand, VectorArrangement};+use crate::asm::{Fpr, Gpr, Width};+use crate::convention::Register;+use crate::ir::{Func, Op, Type, Value};+use crate::regalloc::CONSTANT_INPUT;+use libwasm_module::opcode::simd::*;++/// The extra vector registers the lowering of a vector node takes: none, the scratch registers suffice.+pub(crate) fn vector_temps(_func: &Func, _value: Value) -> usize {+ 0+}++/// Whether a binary SIMD operation is a shift by an i32, whose count may be a constant.+pub(crate) fn is_vector_shift(sub_opcode: u32) -> bool {+ matches!(+ sub_opcode,+ I8X16_SHL+ | I8X16_SHR_S+ | I8X16_SHR_U+ | I16X8_SHL+ | I16X8_SHR_S+ | I16X8_SHR_U+ | I32X4_SHL+ | I32X4_SHR_S+ | I32X4_SHR_U+ | I64X2_SHL+ | I64X2_SHR_S+ | I64X2_SHR_U+ )+}++const V31: Fpr = SCRATCH_FPR;+const V30: Fpr = SCRATCH_FPR2;++// The opcodes of the "three same" instructions, with their U bit.+const ADD: (bool, u32) = (false, 0b10000);+const SUB: (bool, u32) = (true, 0b10000);+const CMEQ: (bool, u32) = (true, 0b10001);+const CMGT: (bool, u32) = (false, 0b00110);+const CMHI: (bool, u32) = (true, 0b00110);+const CMGE: (bool, u32) = (false, 0b00111);+const CMHS: (bool, u32) = (true, 0b00111);+const SQADD: (bool, u32) = (false, 0b00001);+const UQADD: (bool, u32) = (true, 0b00001);+const SQSUB: (bool, u32) = (false, 0b00101);+const UQSUB: (bool, u32) = (true, 0b00101);+const URHADD: (bool, u32) = (true, 0b00010);+const MUL: (bool, u32) = (false, 0b10011);+const SMAX: (bool, u32) = (false, 0b01100);+const UMAX: (bool, u32) = (true, 0b01100);+const SMIN: (bool, u32) = (false, 0b01101);+const UMIN: (bool, u32) = (true, 0b01101);+const SSHL: (bool, u32) = (false, 0b01000);+const USHL: (bool, u32) = (true, 0b01000);+const ADDP: (bool, u32) = (false, 0b10111);+const SQRDMULH: (bool, u32) = (true, 0b10110);++/// The bitwise "three same" instructions: U, size and the opcode 00011.+#[derive(Clone, Copy)]+enum Logic {+ And,+ Bic,+ Orr,+ Eor,+ Bsl,+}++impl Logic {+ const fn fields(self) -> (bool, u32) {+ match self {+ Logic::And => (false, 0),+ Logic::Bic => (false, 1),+ Logic::Orr => (false, 2),+ Logic::Eor => (true, 0),+ Logic::Bsl => (true, 1),+ }+ }+}++// The float "three same" instructions: U, the high bit of the size field, and the opcode.+const FADD: (bool, u32, u32) = (false, 0, 0b11010);+const FSUB: (bool, u32, u32) = (false, 1, 0b11010);+const FMUL: (bool, u32, u32) = (true, 0, 0b11011);+const FDIV: (bool, u32, u32) = (true, 0, 0b11111);+const FCMEQ: (bool, u32, u32) = (false, 0, 0b11100);+const FCMGE: (bool, u32, u32) = (true, 0, 0b11100);+const FCMGT: (bool, u32, u32) = (true, 1, 0b11100);++// The "two-register miscellaneous" instructions: U, the opcode, and for float ones the high bit of the size field.+const ABS: (bool, u32) = (false, 0b01011);+const NEG: (bool, u32) = (true, 0b01011);+const CNT: (bool, u32) = (false, 0b00101);+const NOT: (bool, u32) = (true, 0b00101);+const CMEQ_ZERO: (bool, u32) = (false, 0b01001);+const SADDLP: (bool, u32) = (false, 0b00010);+const UADDLP: (bool, u32) = (true, 0b00010);+const XTN: (bool, u32) = (false, 0b10010);+const SQXTN: (bool, u32) = (false, 0b10100);+const UQXTN: (bool, u32) = (true, 0b10100);+const SQXTUN: (bool, u32) = (true, 0b10010);+const REV64: (bool, u32) = (false, 0b00000);+const FCVTN: (bool, u32, u32) = (false, 0, 0b10110);+const FCVTL: (bool, u32, u32) = (false, 0, 0b10111);+const FABS: (bool, u32, u32) = (false, 1, 0b01111);+const FNEG: (bool, u32, u32) = (true, 1, 0b01111);+const FSQRT: (bool, u32, u32) = (true, 1, 0b11111);+const FRINTN: (bool, u32, u32) = (false, 0, 0b11000);+const FRINTM: (bool, u32, u32) = (false, 0, 0b11001);+const FRINTP: (bool, u32, u32) = (false, 1, 0b11000);+const FRINTZ: (bool, u32, u32) = (false, 1, 0b11001);+const SCVTF: (bool, u32, u32) = (false, 0, 0b11101);+const UCVTF: (bool, u32, u32) = (true, 0, 0b11101);+const FCVTZS: (bool, u32, u32) = (false, 1, 0b11011);+const FCVTZU: (bool, u32, u32) = (true, 1, 0b11011);++// The "three different" instructions: U and the opcode.+const SMULL: (bool, u32) = (false, 0b1100);+const UMULL: (bool, u32) = (true, 0b1100);+const UMLAL: (bool, u32) = (true, 0b1000);++// The shifts by an immediate: U and the opcode.+const SHL: (bool, u32) = (false, 0b01010);+const SSHR: (bool, u32) = (false, 0b00000);+const USHR: (bool, u32) = (true, 0b00000);+const USRA: (bool, u32) = (true, 0b00010);+const SSHLL: (bool, u32) = (false, 0b10100);+const USHLL: (bool, u32) = (true, 0b10100);++// The permutes.+const UZP1: u32 = 0b001;+const UZP2: u32 = 0b101;++// The copies: imm4.+const DUP_ELEMENT: u32 = 0b0000;+const DUP_GENERAL: u32 = 0b0001;+const INS_GENERAL: u32 = 0b0011;+const SMOV: u32 = 0b0101;+const UMOV: u32 = 0b0111;++/// The imm5 field of a copy of lane `index` of lanes of `1 << size` bytes.+const fn lane_imm5(size: u32, index: u32) -> u32 {+ ((index << 1) | 1) << size+}++/// The size field of a float operation: the high bit, and the precision.+const fn float_size_field(high: u32, double: bool) -> u32 {+ (high << 1) | double as u32+}++impl CodeGenerator<'_> {+ // Instructions.++ fn three(&mut self, (u, opcode): (bool, u32), size: u32, d: Fpr, n: Fpr, m: Fpr) {+ self.asm.vector_three_same(true, (u, opcode), size, d, n, m);+ }++ fn bitwise(&mut self, op: Logic, d: Fpr, n: Fpr, m: Fpr) {+ let (u, size) = op.fields();+ self.asm.vector_three_same(true, (u, 0b00011), size, d, n, m);+ }++ fn float_three(&mut self, (u, high, opcode): (bool, u32, u32), double: bool, d: Fpr, n: Fpr, m: Fpr) {+ self.asm+ .vector_three_same(true, (u, opcode), float_size_field(high, double), d, n, m);+ }++ fn misc(&mut self, (u, opcode): (bool, u32), size: u32, d: Fpr, n: Fpr) {+ self.asm.vector_two_misc(true, u, size, opcode, d, n);+ }++ fn float_misc(&mut self, (u, high, opcode): (bool, u32, u32), double: bool, d: Fpr, n: Fpr) {+ self.asm+ .vector_two_misc(true, u, float_size_field(high, double), opcode, d, n);+ }++ /// A shift left by `shift` of lanes of `1 << size` bytes.+ fn shift_left(&mut self, (u, opcode): (bool, u32), size: u32, shift: u32, d: Fpr, n: Fpr) {+ let bits = 8 << size;+ self.asm.vector_shift_immediate(true, u, bits + shift, opcode, d, n);+ }++ /// A shift right by `shift` (1 to the lane width) of lanes of `1 << size` bytes.+ fn shift_right(&mut self, (u, opcode): (bool, u32), size: u32, shift: u32, d: Fpr, n: Fpr) {+ let bits = 8 << size;+ self.asm.vector_shift_immediate(true, u, 2 * bits - shift, opcode, d, n);+ }++ /// `sshll`/`ushll #0` (`high`: `sshll2`/`ushll2`): the low or high half's lanes of `1 << size` bytes, extended.+ fn extend(&mut self, signed: bool, high: bool, size: u32, d: Fpr, n: Fpr) {+ let (u, opcode) = if signed { SSHLL } else { USHLL };+ self.asm.vector_shift_immediate(high, u, 8 << size, opcode, d, n);+ }++ /// A long multiply (`smull`, `umull`, `umlal` and their high forms) of lanes of `1 << size` bytes.+ fn long(&mut self, (u, opcode): (bool, u32), high: bool, size: u32, d: Fpr, n: Fpr, m: Fpr) {+ self.asm.vector_three_different(high, (u, opcode), size, d, n, m);+ }++ /// A narrowing (`xtn`, `sqxtn`, `uqxtn`, `sqxtun`, or with `high` their second forms) to lanes of `1 << size`+ /// bytes.+ fn narrow(&mut self, (u, opcode): (bool, u32), high: bool, size: u32, d: Fpr, n: Fpr) {+ self.asm.vector_two_misc(high, u, size, opcode, d, n);+ }++ fn not(&mut self, d: Fpr, n: Fpr) {+ self.misc(NOT, 0, d, n);+ }++ /// Fills `d` with the constant `bits`.+ fn vector_constant(&mut self, d: Fpr, bits: u128) {+ self.load_vector_constant(bits, d, true);+ }++ /// Fills every lane of `1 << size` bytes of `d` with the general purpose register `n`.+ fn dup_general(&mut self, size: u32, d: Fpr, n: Gpr) {+ self.asm+ .vector_copy(true, false, lane_imm5(size, 0), DUP_GENERAL, d.0, n.0);+ }++ // Lowerings.++ /// A `VectorLoad`, whose operand `operand_of` makes for an access of `1 << size_log2` bytes.+ pub(super) fn vector_load(&mut self, value: Value, operand_of: impl Fn(&mut Self, u32) -> MemOperand) {+ let node = *self.func.node(value);+ let dst = fpr(self.allocation.node(value).output);+ let sub_opcode = u32::from(node.flags);+ let load = |generator: &mut Self, size_log2: u32| {+ let operand = operand_of(generator, size_log2);+ generator.asm.load_store(fpr_access(size_log2, true), dst.0, operand);+ };+ match sub_opcode {+ V128_LOAD => load(self, 4),+ V128_LOAD8X8_S | V128_LOAD8X8_U | V128_LOAD16X4_S | V128_LOAD16X4_U | V128_LOAD32X2_S | V128_LOAD32X2_U => {+ load(self, 3);+ let (size, signed) = match sub_opcode {+ V128_LOAD8X8_S => (0, true),+ V128_LOAD8X8_U => (0, false),+ V128_LOAD16X4_S => (1, true),+ V128_LOAD16X4_U => (1, false),+ V128_LOAD32X2_S => (2, true),+ _ => (2, false),+ };+ self.extend(signed, false, size, dst, dst);+ }+ V128_LOAD8_SPLAT | V128_LOAD16_SPLAT | V128_LOAD32_SPLAT | V128_LOAD64_SPLAT => {+ let size = match sub_opcode {+ V128_LOAD8_SPLAT => 0,+ V128_LOAD16_SPLAT => 1,+ V128_LOAD32_SPLAT => 2,+ _ => 3,+ };+ let operand = operand_of(self, size);+ let address = self.address_register(operand);+ self.asm.load_replicate(size, dst, address);+ }+ // NB: Loads of 32 or 64 bits clear the rest of the register.+ V128_LOAD32_ZERO => load(self, 2),+ _ => load(self, 3),+ }+ }++ pub(super) fn lower_vector(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ let [a, b, c] = record.inputs;+ let output = record.output;+ match node.op {+ Op::VectorUnary => self.vector_unary(node.args[1], node.ty, output, a),+ Op::VectorBinary => self.vector_binary(value, node.args[2], output, a, b),+ Op::VectorTernary => {+ let sub_opcode = if u32::from(node.flags) == V128_BITSELECT {+ V128_BITSELECT+ } else {+ 0x100 | u32::from(node.flags)+ };+ self.vector_ternary(sub_opcode, fpr(output), [fpr(a), fpr(b), fpr(c)]);+ }+ Op::ExtractLane => self.extract_lane(node.args[1], node.args[2], output, fpr(a)),+ Op::ReplaceLane => {+ let sub_opcode = node.args[2] & 0xffff;+ let lane = node.args[2] >> 16;+ let dst = fpr(output);+ self.move_vector(dst, fpr(a));+ let size = match sub_opcode {+ I8X16_REPLACE_LANE => 0,+ I16X8_REPLACE_LANE => 1,+ I32X4_REPLACE_LANE | F32X4_REPLACE_LANE => 2,+ _ => 3,+ };+ if matches!(sub_opcode, F32X4_REPLACE_LANE | F64X2_REPLACE_LANE) {+ // `ins vd.<T>[lane], vn.<T>[0]`+ self.asm+ .vector_copy(true, true, lane_imm5(size, lane), 0, dst.0, fpr(b).0);+ } else {+ self.asm+ .vector_copy(true, false, lane_imm5(size, lane), INS_GENERAL, dst.0, gpr(b).0);+ }+ }+ Op::Shuffle => {+ let lanes = func.constants[node.args[2] as usize];+ let dst = fpr(output);+ if node.args[0] == node.args[1] {+ self.vector_constant(dst, lanes);+ self.asm.vector_table(dst, fpr(a), 1, dst);+ } else {+ // The table of two registers has to be in consecutive ones.+ self.move_vector(V30, fpr(a));+ self.move_vector(V31, fpr(b));+ self.vector_constant(dst, lanes);+ self.asm.vector_table(dst, V30, 2, dst);+ }+ }+ _ => unreachable!("{} is no vector op", node.op.name()),+ }+ }++ fn vector_unary(&mut self, sub_opcode: u32, ty: Type, output: Register, a: Register) {+ if ty == Type::I32 {+ self.vector_test(sub_opcode, gpr(output), fpr(a));+ return;+ }+ let dst = fpr(output);+ match sub_opcode {+ I8X16_SPLAT => self.dup_general(0, dst, gpr(a)),+ I16X8_SPLAT => self.dup_general(1, dst, gpr(a)),+ I32X4_SPLAT => self.dup_general(2, dst, gpr(a)),+ I64X2_SPLAT => self.dup_general(3, dst, gpr(a)),+ F32X4_SPLAT => self+ .asm+ .vector_copy(true, false, lane_imm5(2, 0), DUP_ELEMENT, dst.0, fpr(a).0),+ F64X2_SPLAT => self+ .asm+ .vector_copy(true, false, lane_imm5(3, 0), DUP_ELEMENT, dst.0, fpr(a).0),+ _ => self.vector_lanewise_unary(sub_opcode, dst, fpr(a)),+ }+ }++ /// The unary operations from a vector to a vector.+ fn vector_lanewise_unary(&mut self, sub_opcode: u32, dst: Fpr, a: Fpr) {+ match sub_opcode {+ V128_NOT => self.not(dst, a),+ I8X16_ABS => self.misc(ABS, 0, dst, a),+ I16X8_ABS => self.misc(ABS, 1, dst, a),+ I32X4_ABS => self.misc(ABS, 2, dst, a),+ I64X2_ABS => self.misc(ABS, 3, dst, a),+ I8X16_NEG => self.misc(NEG, 0, dst, a),+ I16X8_NEG => self.misc(NEG, 1, dst, a),+ I32X4_NEG => self.misc(NEG, 2, dst, a),+ I64X2_NEG => self.misc(NEG, 3, dst, a),+ I8X16_POPCNT => self.misc(CNT, 0, dst, a),+ // NB: These only change the sign bit, as the interpreter's masks do.+ F32X4_ABS => self.float_misc(FABS, false, dst, a),+ F32X4_NEG => self.float_misc(FNEG, false, dst, a),+ F64X2_ABS => self.float_misc(FABS, true, dst, a),+ F64X2_NEG => self.float_misc(FNEG, true, dst, a),+ F32X4_SQRT => self.float_misc(FSQRT, false, dst, a),+ F64X2_SQRT => self.float_misc(FSQRT, true, dst, a),+ F32X4_NEAREST => self.float_misc(FRINTN, false, dst, a),+ F32X4_FLOOR => self.float_misc(FRINTM, false, dst, a),+ F32X4_CEIL => self.float_misc(FRINTP, false, dst, a),+ F32X4_TRUNC => self.float_misc(FRINTZ, false, dst, a),+ F64X2_NEAREST => self.float_misc(FRINTN, true, dst, a),+ F64X2_FLOOR => self.float_misc(FRINTM, true, dst, a),+ F64X2_CEIL => self.float_misc(FRINTP, true, dst, a),+ F64X2_TRUNC => self.float_misc(FRINTZ, true, dst, a),+ I16X8_EXTEND_LOW_I8X16_S => self.extend(true, false, 0, dst, a),+ I16X8_EXTEND_HIGH_I8X16_S => self.extend(true, true, 0, dst, a),+ I16X8_EXTEND_LOW_I8X16_U => self.extend(false, false, 0, dst, a),+ I16X8_EXTEND_HIGH_I8X16_U => self.extend(false, true, 0, dst, a),+ I32X4_EXTEND_LOW_I16X8_S => self.extend(true, false, 1, dst, a),+ I32X4_EXTEND_HIGH_I16X8_S => self.extend(true, true, 1, dst, a),+ I32X4_EXTEND_LOW_I16X8_U => self.extend(false, false, 1, dst, a),+ I32X4_EXTEND_HIGH_I16X8_U => self.extend(false, true, 1, dst, a),+ I64X2_EXTEND_LOW_I32X4_S => self.extend(true, false, 2, dst, a),+ I64X2_EXTEND_HIGH_I32X4_S => self.extend(true, true, 2, dst, a),+ I64X2_EXTEND_LOW_I32X4_U => self.extend(false, false, 2, dst, a),+ I64X2_EXTEND_HIGH_I32X4_U => self.extend(false, true, 2, dst, a),+ I16X8_EXTADD_PAIRWISE_I8X16_S => self.misc(SADDLP, 0, dst, a),+ I16X8_EXTADD_PAIRWISE_I8X16_U => self.misc(UADDLP, 0, dst, a),+ I32X4_EXTADD_PAIRWISE_I16X8_S => self.misc(SADDLP, 1, dst, a),+ I32X4_EXTADD_PAIRWISE_I16X8_U => self.misc(UADDLP, 1, dst, a),+ // NB: The conversions from integers round once, as the spec wants, so any exact sequence agrees.+ F32X4_CONVERT_I32X4_S => self.float_misc(SCVTF, false, dst, a),+ F32X4_CONVERT_I32X4_U => self.float_misc(UCVTF, false, dst, a),+ F64X2_CONVERT_LOW_I32X4_S => {+ self.extend(true, false, 2, dst, a);+ self.float_misc(SCVTF, true, dst, dst);+ }+ F64X2_CONVERT_LOW_I32X4_U => {+ self.extend(false, false, 2, dst, a);+ self.float_misc(UCVTF, true, dst, dst);+ }+ // NB: The truncations saturate and give 0 for NaN, as the saturating ones want.+ I32X4_TRUNC_SAT_F32X4_S => self.float_misc(FCVTZS, false, dst, a),+ I32X4_TRUNC_SAT_F32X4_U => self.float_misc(FCVTZU, false, dst, a),+ I32X4_TRUNC_SAT_F64X2_S_ZERO => {+ self.float_misc(FCVTZS, true, dst, a);+ self.narrow(SQXTN, false, 2, dst, dst);+ }+ I32X4_TRUNC_SAT_F64X2_U_ZERO => {+ self.float_misc(FCVTZU, true, dst, a);+ self.narrow(UQXTN, false, 2, dst, dst);+ }+ // The interpreter's demotion and promotion are these instructions.+ F32X4_DEMOTE_F64X2_ZERO => self.asm.vector_two_misc(false, FCVTN.0, 1, FCVTN.2, dst, a),+ F64X2_PROMOTE_LOW_F32X4 => self.asm.vector_two_misc(false, FCVTL.0, 1, FCVTL.2, dst, a),+ _ => unreachable!("SIMD sub-opcode {sub_opcode:#x} is no unary vector operation"),+ }+ }++ /// The reductions of a vector to an i32.+ fn vector_test(&mut self, sub_opcode: u32, dst: Gpr, a: Fpr) {+ match sub_opcode {+ V128_ANY_TRUE => {+ // umaxv s31, a.4s+ self.asm.vector_across(true, true, 2, 0b01010, V31, a);+ self.asm.fmov_to_gpr(dst, V31);+ self.asm.cmp_imm(Width::W64, dst, 0, false);+ self.asm.cset(Width::W32, dst, crate::asm::aarch64::Cond::Ne);+ }+ I8X16_ALL_TRUE | I16X8_ALL_TRUE | I32X4_ALL_TRUE | I64X2_ALL_TRUE => {+ // All lanes are nonzero where no lane equals zero.+ let size = match sub_opcode {+ I8X16_ALL_TRUE => 0,+ I16X8_ALL_TRUE => 1,+ I32X4_ALL_TRUE => 2,+ _ => 3,+ };+ self.misc(CMEQ_ZERO, size, V31, a);+ self.asm.vector_across(true, true, 2, 0b01010, V31, V31);+ self.asm.fmov_to_gpr(dst, V31);+ self.asm.cmp_imm(Width::W64, dst, 0, false);+ self.asm.cset(Width::W32, dst, crate::asm::aarch64::Cond::Eq);+ }+ I8X16_BITMASK | I16X8_BITMASK => {+ // The sign bits gathered: each shift-and-accumulate doubles the bits a lane holds, until the low+ // byte of each 64-bit half holds those of its half.+ let (size, half_bits) = if sub_opcode == I8X16_BITMASK { (0u32, 8) } else { (1, 4) };+ let bits = 8u32 << size;+ self.shift_right(USHR, size, bits - 1, V31, a);+ // Each doubling of the lane width moves the upper half's bits next to the lower half's.+ let mut gathered = 1u32;+ for wider in size + 1..4 {+ self.shift_right(USRA, wider, (8 << (wider - 1)) - gathered, V31, V31);+ gathered *= 2;+ }+ self.asm+ .vector_copy(false, false, lane_imm5(0, 0), UMOV, SCRATCH.0, V31.0);+ self.asm+ .vector_copy(false, false, lane_imm5(0, 8), UMOV, super::ADDRESS.0, V31.0);+ self.asm.orr(+ Width::W32,+ dst,+ SCRATCH,+ super::ADDRESS,+ crate::asm::aarch64::Shift::Lsl,+ half_bits,+ );+ }+ I32X4_BITMASK => {+ self.shift_right(USHR, 2, 31, V31, a);+ self.shift_right(USRA, 3, 31, V31, V31);+ self.asm+ .vector_copy(false, false, lane_imm5(2, 0), UMOV, SCRATCH.0, V31.0);+ self.asm+ .vector_copy(false, false, lane_imm5(2, 2), UMOV, super::ADDRESS.0, V31.0);+ self.asm.orr(+ Width::W32,+ dst,+ SCRATCH,+ super::ADDRESS,+ crate::asm::aarch64::Shift::Lsl,+ 2,+ );+ }+ I64X2_BITMASK => {+ self.shift_right(USHR, 3, 63, V31, a);+ self.asm+ .vector_copy(true, false, lane_imm5(3, 0), UMOV, SCRATCH.0, V31.0);+ self.asm+ .vector_copy(true, false, lane_imm5(3, 1), UMOV, super::ADDRESS.0, V31.0);+ self.asm.orr(+ Width::W32,+ dst,+ SCRATCH,+ super::ADDRESS,+ crate::asm::aarch64::Shift::Lsl,+ 1,+ );+ }+ _ => unreachable!("SIMD sub-opcode {sub_opcode:#x} is no reduction to an i32"),+ }+ }++ /// The interpreter's `v128_min_f*(x, y)`: `y > x ? x : y`, lane by lane.+ fn interpreter_min(&mut self, double: bool, d: Fpr, x: Fpr, y: Fpr) {+ self.float_three(FCMGT, double, d, y, x);+ self.bitwise(Logic::Bsl, d, x, y);+ }++ /// The interpreter's `v128_max_f*(x, y)`: `x > y ? x : y`, lane by lane.+ fn interpreter_max(&mut self, double: bool, d: Fpr, x: Fpr, y: Fpr) {+ self.float_three(FCMGT, double, d, x, y);+ self.bitwise(Logic::Bsl, d, x, y);+ }++ /// The interpreter's `v128_unord_f*(x, y)`, into `d`, through v30.+ fn interpreter_unordered(&mut self, double: bool, d: Fpr, x: Fpr, y: Fpr) {+ self.float_three(FCMEQ, double, V30, x, x);+ self.float_three(FCMEQ, double, d, y, y);+ self.bitwise(Logic::And, d, V30, d);+ self.not(d, d);+ }++ fn vector_binary(&mut self, value: Value, sub_opcode: u32, output: Register, a: Register, b: Register) {+ let dst = fpr(output);+ if is_vector_shift(sub_opcode) {+ let count = (b == CONSTANT_INPUT).then(|| self.immediate(value, 1) as u32);+ self.vector_shift(sub_opcode, dst, fpr(a), b, count);+ return;+ }+ let (a, b) = (fpr(a), fpr(b));+ let integer = |op: (bool, u32), size: u32| (op, size, false);+ let swapped = |op: (bool, u32), size: u32| (op, size, true);+ let simple = match sub_opcode {+ I8X16_EQ => Some(integer(CMEQ, 0)),+ I16X8_EQ => Some(integer(CMEQ, 1)),+ I32X4_EQ => Some(integer(CMEQ, 2)),+ I64X2_EQ => Some(integer(CMEQ, 3)),+ I8X16_GT_S => Some(integer(CMGT, 0)),+ I16X8_GT_S => Some(integer(CMGT, 1)),+ I32X4_GT_S => Some(integer(CMGT, 2)),+ I64X2_GT_S => Some(integer(CMGT, 3)),+ I8X16_LT_S => Some(swapped(CMGT, 0)),+ I16X8_LT_S => Some(swapped(CMGT, 1)),+ I32X4_LT_S => Some(swapped(CMGT, 2)),+ I64X2_LT_S => Some(swapped(CMGT, 3)),+ I8X16_GE_S => Some(integer(CMGE, 0)),+ I16X8_GE_S => Some(integer(CMGE, 1)),+ I32X4_GE_S => Some(integer(CMGE, 2)),+ I64X2_GE_S => Some(integer(CMGE, 3)),+ I8X16_LE_S => Some(swapped(CMGE, 0)),+ I16X8_LE_S => Some(swapped(CMGE, 1)),+ I32X4_LE_S => Some(swapped(CMGE, 2)),+ I64X2_LE_S => Some(swapped(CMGE, 3)),+ I8X16_GT_U => Some(integer(CMHI, 0)),+ I16X8_GT_U => Some(integer(CMHI, 1)),+ I32X4_GT_U => Some(integer(CMHI, 2)),+ I8X16_LT_U => Some(swapped(CMHI, 0)),+ I16X8_LT_U => Some(swapped(CMHI, 1)),+ I32X4_LT_U => Some(swapped(CMHI, 2)),+ I8X16_GE_U => Some(integer(CMHS, 0)),+ I16X8_GE_U => Some(integer(CMHS, 1)),+ I32X4_GE_U => Some(integer(CMHS, 2)),+ I8X16_LE_U => Some(swapped(CMHS, 0)),+ I16X8_LE_U => Some(swapped(CMHS, 1)),+ I32X4_LE_U => Some(swapped(CMHS, 2)),+ I8X16_ADD => Some(integer(ADD, 0)),+ I16X8_ADD => Some(integer(ADD, 1)),+ I32X4_ADD => Some(integer(ADD, 2)),+ I64X2_ADD => Some(integer(ADD, 3)),+ I8X16_SUB => Some(integer(SUB, 0)),+ I16X8_SUB => Some(integer(SUB, 1)),+ I32X4_SUB => Some(integer(SUB, 2)),+ I64X2_SUB => Some(integer(SUB, 3)),+ I8X16_ADD_SAT_S => Some(integer(SQADD, 0)),+ I8X16_ADD_SAT_U => Some(integer(UQADD, 0)),+ I8X16_SUB_SAT_S => Some(integer(SQSUB, 0)),+ I8X16_SUB_SAT_U => Some(integer(UQSUB, 0)),+ I16X8_ADD_SAT_S => Some(integer(SQADD, 1)),+ I16X8_ADD_SAT_U => Some(integer(UQADD, 1)),+ I16X8_SUB_SAT_S => Some(integer(SQSUB, 1)),+ I16X8_SUB_SAT_U => Some(integer(UQSUB, 1)),+ I8X16_AVGR_U => Some(integer(URHADD, 0)),+ I16X8_AVGR_U => Some(integer(URHADD, 1)),+ I16X8_MUL => Some(integer(MUL, 1)),+ I32X4_MUL => Some(integer(MUL, 2)),+ I8X16_MIN_S => Some(integer(SMIN, 0)),+ I8X16_MIN_U => Some(integer(UMIN, 0)),+ I8X16_MAX_S => Some(integer(SMAX, 0)),+ I8X16_MAX_U => Some(integer(UMAX, 0)),+ I16X8_MIN_S => Some(integer(SMIN, 1)),+ I16X8_MIN_U => Some(integer(UMIN, 1)),+ I16X8_MAX_S => Some(integer(SMAX, 1)),+ I16X8_MAX_U => Some(integer(UMAX, 1)),+ I32X4_MIN_S => Some(integer(SMIN, 2)),+ I32X4_MIN_U => Some(integer(UMIN, 2)),+ I32X4_MAX_S => Some(integer(SMAX, 2)),+ I32X4_MAX_U => Some(integer(UMAX, 2)),+ // NB: The rounding doubling multiply saturates the one product that overflows, -1 * -1.+ I16X8_Q15MULR_SAT_S => Some(integer(SQRDMULH, 1)),+ _ => None,+ };+ if let Some((op, size, swap)) = simple {+ let (lhs, rhs) = if swap { (b, a) } else { (a, b) };+ self.three(op, size, dst, lhs, rhs);+ return;+ }+ match sub_opcode {+ V128_AND => self.bitwise(Logic::And, dst, a, b),+ V128_OR => self.bitwise(Logic::Orr, dst, a, b),+ V128_XOR => self.bitwise(Logic::Eor, dst, a, b),+ V128_ANDNOT => self.bitwise(Logic::Bic, dst, a, b),+ I8X16_NE | I16X8_NE | I32X4_NE | I64X2_NE => {+ let size = match sub_opcode {+ I8X16_NE => 0,+ I16X8_NE => 1,+ I32X4_NE => 2,+ _ => 3,+ };+ self.three(CMEQ, size, dst, a, b);+ self.not(dst, dst);+ }+ F32X4_EQ | F64X2_EQ => self.float_three(FCMEQ, sub_opcode == F64X2_EQ, dst, a, b),+ F32X4_NE | F64X2_NE => {+ self.float_three(FCMEQ, sub_opcode == F64X2_NE, dst, a, b);+ self.not(dst, dst);+ }+ F32X4_LT | F64X2_LT => self.float_three(FCMGT, sub_opcode == F64X2_LT, dst, b, a),+ F32X4_LE | F64X2_LE => self.float_three(FCMGE, sub_opcode == F64X2_LE, dst, b, a),+ F32X4_GT | F64X2_GT => self.float_three(FCMGT, sub_opcode == F64X2_GT, dst, a, b),+ F32X4_GE | F64X2_GE => self.float_three(FCMGE, sub_opcode == F64X2_GE, dst, a, b),+ F32X4_ADD | F64X2_ADD => self.float_three(FADD, sub_opcode == F64X2_ADD, dst, a, b),+ F32X4_SUB | F64X2_SUB => self.float_three(FSUB, sub_opcode == F64X2_SUB, dst, a, b),+ F32X4_MUL | F64X2_MUL => self.float_three(FMUL, sub_opcode == F64X2_MUL, dst, a, b),+ F32X4_DIV | F64X2_DIV => self.float_three(FDIV, sub_opcode == F64X2_DIV, dst, a, b),+ // pmin is b < a ? b : a, the interpreter's min of b and a.+ F32X4_PMIN | F64X2_PMIN => self.interpreter_min(sub_opcode == F64X2_PMIN, dst, b, a),+ F32X4_PMAX | F64X2_PMAX => self.interpreter_max(sub_opcode == F64X2_PMAX, dst, b, a),+ F32X4_MIN | F64X2_MIN => {+ // Both orders, so that a NaN or -0 in either operand makes it into the result, and NaN lanes+ // canonical.+ let double = sub_opcode == F64X2_MIN;+ self.interpreter_min(double, V31, a, b);+ self.interpreter_min(double, dst, b, a);+ self.bitwise(Logic::Orr, dst, dst, V31);+ self.interpreter_unordered(double, V31, dst, dst);+ self.bitwise(Logic::Orr, dst, dst, V31);+ self.nan_payload_shift(double, V31);+ self.bitwise(Logic::Bic, dst, dst, V31);+ }+ F32X4_MAX | F64X2_MAX => {+ // Both orders, so that a NaN in either operand makes it into the result, +0 beats -0, and NaN+ // lanes are canonical.+ let double = sub_opcode == F64X2_MAX;+ self.interpreter_max(double, V31, a, b);+ self.interpreter_max(double, dst, b, a);+ self.bitwise(Logic::Eor, V31, V31, dst);+ self.bitwise(Logic::Orr, dst, dst, V31);+ self.float_three(FSUB, double, dst, dst, V31);+ self.interpreter_unordered(double, V31, V31, dst);+ self.nan_payload_shift(double, V31);+ self.bitwise(Logic::Bic, dst, dst, V31);+ }+ I8X16_SWIZZLE => {+ // NB: tbl picks zero for indices of 16 and up.+ self.asm.vector_table(dst, a, 1, b);+ }+ I8X16_NARROW_I16X8_S | I8X16_NARROW_I16X8_U | I16X8_NARROW_I32X4_S | I16X8_NARROW_I32X4_U => {+ let op = if matches!(sub_opcode, I8X16_NARROW_I16X8_S | I16X8_NARROW_I32X4_S) {+ SQXTN+ } else {+ SQXTUN+ };+ let size = if matches!(sub_opcode, I8X16_NARROW_I16X8_S | I8X16_NARROW_I16X8_U) {+ 0+ } else {+ 1+ };+ self.narrow(op, false, size, dst, a);+ self.narrow(op, true, size, dst, b);+ }+ I32X4_DOT_I16X8_S => {+ self.long(SMULL, false, 1, V31, a, b);+ self.long(SMULL, true, 1, V30, a, b);+ self.three(ADDP, 2, dst, V31, V30);+ }+ I64X2_MUL => {+ // The cross products of the halves added, shifted up, plus the low halves' full product.+ self.misc(REV64, 2, V31, b);+ self.three(MUL, 2, V31, V31, a);+ self.misc(UADDLP, 2, dst, V31);+ self.shift_left(SHL, 3, 32, dst, dst);+ self.narrow(XTN, false, 2, V31, a);+ self.narrow(XTN, false, 2, V30, b);+ self.long(UMLAL, false, 2, dst, V31, V30);+ }+ I16X8_EXTMUL_LOW_I8X16_S => self.long(SMULL, false, 0, dst, a, b),+ I16X8_EXTMUL_HIGH_I8X16_S => self.long(SMULL, true, 0, dst, a, b),+ I16X8_EXTMUL_LOW_I8X16_U => self.long(UMULL, false, 0, dst, a, b),+ I16X8_EXTMUL_HIGH_I8X16_U => self.long(UMULL, true, 0, dst, a, b),+ I32X4_EXTMUL_LOW_I16X8_S => self.long(SMULL, false, 1, dst, a, b),+ I32X4_EXTMUL_HIGH_I16X8_S => self.long(SMULL, true, 1, dst, a, b),+ I32X4_EXTMUL_LOW_I16X8_U => self.long(UMULL, false, 1, dst, a, b),+ I32X4_EXTMUL_HIGH_I16X8_U => self.long(UMULL, true, 1, dst, a, b),+ I64X2_EXTMUL_LOW_I32X4_S => self.long(SMULL, false, 2, dst, a, b),+ I64X2_EXTMUL_HIGH_I32X4_S => self.long(SMULL, true, 2, dst, a, b),+ I64X2_EXTMUL_LOW_I32X4_U => self.long(UMULL, false, 2, dst, a, b),+ I64X2_EXTMUL_HIGH_I32X4_U => self.long(UMULL, true, 2, dst, a, b),+ I16X8_RELAXED_DOT_I8X16_I7X16_S => self.multiply_add_unsigned_signed(dst, b, a),+ _ => unreachable!("SIMD sub-opcode {sub_opcode:#x} is no binary vector operation"),+ }+ }++ /// The bits a NaN lane of an all-ones mask in `d` keeps of a value, shifted into place: the interpreter shifts+ /// the mask right by 10 for floats and 13 for doubles, so that the sign, the exponent and the quiet bit remain.+ fn nan_payload_shift(&mut self, double: bool, d: Fpr) {+ if double {+ self.shift_right(USHR, 3, 13, d, d);+ } else {+ self.shift_right(USHR, 2, 10, d, d);+ }+ }++ /// The interpreter's `v128_madd_u8_s8(u, s)`: the unsigned bytes of `u` times the signed bytes of `s`, adjacent+ /// products added into 16-bit lanes with signed saturation.+ fn multiply_add_unsigned_signed(&mut self, dst: Fpr, u: Fpr, s: Fpr) {+ self.extend(false, false, 0, V31, u);+ self.extend(true, false, 0, V30, s);+ self.three(MUL, 1, V31, V31, V30);+ self.extend(false, true, 0, dst, u);+ self.extend(true, true, 0, V30, s);+ self.three(MUL, 1, dst, dst, V30);+ self.asm.vector_permute(VectorArrangement::H8, UZP1, V30, V31, dst);+ self.asm.vector_permute(VectorArrangement::H8, UZP2, dst, V31, dst);+ self.three(SQADD, 1, dst, V30, dst);+ }++ /// A shift of the vector in `a` by the i32 in `count_register`, or by `count` where it is a constant.+ fn vector_shift(&mut self, sub_opcode: u32, dst: Fpr, a: Fpr, count_register: Register, count: Option<u32>) {+ let size = match sub_opcode {+ I8X16_SHL | I8X16_SHR_S | I8X16_SHR_U => 0,+ I16X8_SHL | I16X8_SHR_S | I16X8_SHR_U => 1,+ I32X4_SHL | I32X4_SHR_S | I32X4_SHR_U => 2,+ _ => 3,+ };+ let bits = 8u32 << size;+ let left = matches!(sub_opcode, I8X16_SHL | I16X8_SHL | I32X4_SHL | I64X2_SHL);+ let signed = matches!(sub_opcode, I8X16_SHR_S | I16X8_SHR_S | I32X4_SHR_S | I64X2_SHR_S);+ if let Some(count) = count {+ let count = count & (bits - 1);+ if count == 0 {+ self.move_vector(dst, a);+ } else if left {+ self.shift_left(SHL, size, count, dst, a);+ } else {+ self.shift_right(if signed { SSHR } else { USHR }, size, count, dst, a);+ }+ return;+ }+ // The count masked, negated for right shifts (sshl and ushl shift right by negative counts), in every lane.+ self.asm+ .and_imm(Width::W64, SCRATCH, gpr(count_register), u64::from(bits - 1));+ if !left {+ self.asm.neg(Width::W64, SCRATCH, SCRATCH);+ }+ self.dup_general(size, V31, SCRATCH);+ self.three(if signed { SSHL } else { USHL }, size, dst, a, V31);+ }++ fn vector_ternary(&mut self, sub_opcode: u32, dst: Fpr, [a, b, c]: [Fpr; 3]) {+ match sub_opcode {+ V128_BITSELECT => {+ // (a & c) | (b & !c)+ self.move_vector(dst, c);+ self.bitwise(Logic::Bsl, dst, a, b);+ }+ // The multiply-adds round twice, as the interpreter's do.+ F32X4_RELAXED_MADD | F64X2_RELAXED_MADD => {+ let double = sub_opcode == F64X2_RELAXED_MADD;+ self.float_three(FMUL, double, dst, a, b);+ self.float_three(FADD, double, dst, dst, c);+ }+ F32X4_RELAXED_NMADD | F64X2_RELAXED_NMADD => {+ let double = sub_opcode == F64X2_RELAXED_NMADD;+ self.float_three(FMUL, double, dst, a, b);+ self.float_three(FSUB, double, dst, c, dst);+ }+ I32X4_RELAXED_DOT_I8X16_I7X16_ADD_S => {+ // Pairs as the 16-bit dot product makes them, then added in pairs again, and to c.+ self.multiply_add_unsigned_signed(dst, b, a);+ self.misc(SADDLP, 1, dst, dst);+ self.three(ADD, 2, dst, dst, c);+ }+ _ => unreachable!("SIMD sub-opcode {sub_opcode:#x} is no ternary vector operation"),+ }+ }++ fn extract_lane(&mut self, sub_opcode: u32, lane: u32, output: Register, vector: Fpr) {+ // `smov`, `umov` (Q for a 64-bit lane), or for floats `dup sd/dd, vn.<T>[lane]` (scalar), which clears the+ // rest of the register.+ let (size, copy) = match sub_opcode {+ I8X16_EXTRACT_LANE_S => (0, Some((false, SMOV))),+ I8X16_EXTRACT_LANE_U => (0, Some((false, UMOV))),+ I16X8_EXTRACT_LANE_S => (1, Some((false, SMOV))),+ I16X8_EXTRACT_LANE_U => (1, Some((false, UMOV))),+ I32X4_EXTRACT_LANE => (2, Some((false, UMOV))),+ I64X2_EXTRACT_LANE => (3, Some((true, UMOV))),+ F32X4_EXTRACT_LANE => (2, None),+ _ => (3, None),+ };+ if let Some((q, imm4)) = copy {+ self.asm+ .vector_copy(q, false, lane_imm5(size, lane), imm4, gpr(output).0, vector.0);+ } else {+ let destination = fpr(output);+ self.asm.emit(+ 0x5e00_0400 | (lane_imm5(size, lane) << 16) | (u32::from(vector.0) << 5) | u32::from(destination.0),+ );+ }+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/mod.rs b/Libraries/LibWasm/JIT/src/codegen/mod.rsindex 0ba3e663c6f..ab54c8b019c 100644--- a/Libraries/LibWasm/JIT/src/codegen/mod.rs+++ b/Libraries/LibWasm/JIT/src/codegen/mod.rs@@ -6,4 +6,12 @@//! Code generation, one lowering per architecture.+#[cfg(target_arch = "aarch64")]+pub mod aarch64;+#[cfg(target_arch = "x86_64")]pub mod x86_64;++#[cfg(target_arch = "aarch64")]+pub use aarch64 as target;+#[cfg(target_arch = "x86_64")]+pub use x86_64 as target;diff --git a/Libraries/LibWasm/JIT/src/convention.rs b/Libraries/LibWasm/JIT/src/convention.rsindex 634c7072f8f..e57a3dfdc2d 100644--- a/Libraries/LibWasm/JIT/src/convention.rs+++ b/Libraries/LibWasm/JIT/src/convention.rs@@ -4,19 +4,23 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The calling convention between compiled functions on x86-64, and the layout of their frames.+//! The calling convention between compiled functions, and the layout of their frames. The registers are the+//! architecture's (`x86_64`, `aarch64`).//!-//! - Parameters of integer types go in rdi, rsi, rdx, rcx, r8 and r9, in order, and those of float and vector types-//! in xmm0 to xmm7. Every parameter has a home slot in the caller's outgoing area, at the callee's fp + 8 * the-//! slots of the parameters before it (a v128 takes two, like on the interpreter's operand stack); the parameters-//! that do not fit in registers are passed there.-//! - Results of integer types come back in rax and rdx, and those of float and vector types in xmm0 and xmm1. The-//! results that do not fit go to a result area the caller provides, at 8 * the slots of the results before them;-//! the caller passes its address in the slot after the parameters' home slots.-//! - r14 holds the callee's instance and r15 the base of its memory 0 at the call, and r10 its `FunctionHeader`.-//! - Every register but rsp and rbp is caller-saved. rsp is 16-byte aligned at the call.+//! - Parameters of integer types go in the integer argument registers, in order, and those of float and vector types+//! in the vector argument registers. Every parameter has a home slot in the caller's outgoing area, at the callee's+//! fp + 8 * the slots of the parameters before it (a v128 takes two, like on the interpreter's operand stack); the+//! parameters that do not fit in registers are passed there.+//! - Results of integer types come back in the first two integer result registers, and those of float and vector+//! types in the first two vector ones. The results that do not fit go to a result area the caller provides, at 8 *+//! the slots of the results before them; the caller passes its address in the slot after the parameters' home+//! slots.+//! - `INSTANCE_REGISTER` holds the callee's instance and `MEMORY_BASE_REGISTER` the base of its memory 0 at the call,+//! and `CALLEE_REGISTER` its `FunctionHeader`.+//! - Every register but the stack pointer and fp is caller-saved. The stack pointer is 16-byte aligned at the call.//! - A tail call writes its stack arguments into the incoming area and jumps to the callee. If they do not fit, it-//! slides the return address and saved fp down first; callers set rsp from fp after every call, which undoes it.+//! moves the frame's bottom down first (on x86-64 with the return address and saved fp); callers set the stack+//! pointer from fp after every call, which undoes it.//! - i32 values are zero-extended to 64 bits in registers and slots; f32 values use the low 32 bits.//!//! A compiled frame:@@ -27,99 +31,33 @@//! fp - 16 caller's fp//! fp - 64..-16 the rest of the frame header, of which compiled code only writes FRAME_INSTANCE//! below spill slots, 8 bytes each, two for a v128-//! rsp outgoing area of calls, 8 bytes per argument (and result area pointer, and result area)+//! sp outgoing area of calls, 8 bytes per argument (and result area pointer, and result area)//! ```//!-//! fp is the caller's rsp at the call, and the header is the interpreter's: its first two words are where the call and-//! `push rbp` put them.+//! fp is the caller's stack pointer at the call, and the header is the interpreter's: its first two words are where the+//! call and `push rbp` put them on x86-64, and where `stp x29, x30, [sp, #-16]!` puts them on AArch64.use crate::ir::Type;-/// Registers as the register allocator numbers them: general purpose registers by their encoding, xmm registers+#[cfg(target_arch = "aarch64")]+mod aarch64;+#[cfg(target_arch = "x86_64")]+mod x86_64;++#[cfg(target_arch = "aarch64")]+pub use aarch64::*;+#[cfg(target_arch = "x86_64")]+pub use x86_64::*;++/// Registers as the register allocator numbers them: general purpose registers by their encoding, vector registers/// from `FPR_BASE` on.pub type Register = u8;-pub const FPR_BASE: Register = 16;--pub const RAX: Register = 0;-pub const RCX: Register = 1;-pub const RDX: Register = 2;-pub const RBX: Register = 3;-pub const RSP: Register = 4;-pub const RBP: Register = 5;-pub const RSI: Register = 6;-pub const RDI: Register = 7;-pub const R8: Register = 8;-pub const R9: Register = 9;-pub const R10: Register = 10;-pub const R11: Register = 11;-pub const R12: Register = 12;-pub const R13: Register = 13;-pub const R14: Register = 14;-pub const R15: Register = 15;--pub const fn xmm(index: u8) -> Register {- FPR_BASE + index-}+/// A set of registers, by their numbers.+pub type RegisterMask = u32;-pub const GPR_ARGUMENTS: [Register; 6] = [RDI, RSI, RDX, RCX, R8, R9];-pub const FPR_ARGUMENTS: [Register; 8] = [xmm(0), xmm(1), xmm(2), xmm(3), xmm(4), xmm(5), xmm(6), xmm(7)];-pub const GPR_RESULTS: [Register; 2] = [RAX, RDX];-pub const FPR_RESULTS: [Register; 2] = [xmm(0), xmm(1)];--pub const INSTANCE_REGISTER: Register = R14;-pub const MEMORY_BASE_REGISTER: Register = R15;-pub const CALLEE_REGISTER: Register = R10;--/// Never allocated: moves between memory locations go through them, and lowerings may clobber them.-pub const SCRATCH_GPR: Register = R11;-pub const SCRATCH_FPR: Register = xmm(15);--/// The registers values may live in, in the order the allocator prefers them.-pub const ALLOCATABLE_GPRS: [Register; 13] = [RAX, RCX, RDX, RSI, RDI, R8, R9, R10, RBX, R12, R13, R14, R15];-pub const ALLOCATABLE_FPRS: [Register; 15] = [- xmm(0),- xmm(1),- xmm(2),- xmm(3),- xmm(4),- xmm(5),- xmm(6),- xmm(7),- xmm(8),- xmm(9),- xmm(10),- xmm(11),- xmm(12),- xmm(13),- xmm(14),-];--/// Every allocatable register, as a mask.-pub const ALLOCATABLE: u32 = {- let mut mask = 0;- let mut index = 0;- while index < ALLOCATABLE_GPRS.len() {- mask |= 1 << ALLOCATABLE_GPRS[index];- index += 1;- }- index = 0;- while index < ALLOCATABLE_FPRS.len() {- mask |= 1 << ALLOCATABLE_FPRS[index];- index += 1;- }- mask-};--/// Where a call of a function of the runtime (`Op::Helper`) takes its operands: the instance, from which it finds the-/// context, then the operands, which it stores in the context's `arguments`.-pub const HELPER_REGISTERS: [Register; 7] = [RDI, RSI, RDX, RCX, R8, R9, R10];--/// The registers a call of a function of the runtime overwrites: those the host ABI does not preserve.-pub const HOST_CLOBBERS: u32 = {- let preserved = (1 << RBX) | (1 << RSP) | (1 << RBP) | (1 << R12) | (1 << R13) | (1 << R14) | (1 << R15);- !preserved-};+/// The registers the allocator tracks.+pub const REGISTER_COUNT: usize = 32;pub fn is_fpr(register: Register) -> bool {register >= FPR_BASEdiff --git a/Libraries/LibWasm/JIT/src/convention/aarch64.rs b/Libraries/LibWasm/JIT/src/convention/aarch64.rsnew file mode 100644index 00000000000..3f48950b3d2--- /dev/null+++ b/Libraries/LibWasm/JIT/src/convention/aarch64.rs@@ -0,0 +1,96 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The registers of the calling convention on AArch64.+//!+//! The allocator numbers x0 to x15 as 0 to 15, and v0 to v7 and v16 to v23 as 16 to 31 (`vector_register()`); it+//! never sees the other registers:+//!+//! - Parameters of integer types go in x0 to x7, in order, and those of float and vector types in v0 to v7. Results+//! of integer types come back in x0 and x1, and those of float and vector types in v0 and v1.+//! - x13 holds the callee's instance and x14 the base of its memory 0 at the call, and x15 its `FunctionHeader`.+//! - x16 and x17 are the scratch registers of code generation, and v30 and v31 its vector ones. x18 is the+//! platform's, x19 to x28 and v8 to v15 are left alone (the host ABI preserves them, so compiled code that leaves+//! through the trap exit owes nobody their values), x29 is fp and x30 the link register.+//! - Every register the allocator knows is caller-saved. sp is 16-byte aligned at all times.++use super::{Register, RegisterMask};++pub const FPR_BASE: Register = 16;++pub const X0: Register = 0;+pub const X1: Register = 1;+pub const X2: Register = 2;+pub const X3: Register = 3;+pub const X4: Register = 4;+pub const X5: Register = 5;+pub const X6: Register = 6;+pub const X7: Register = 7;+pub const X8: Register = 8;+pub const X9: Register = 9;+pub const X10: Register = 10;+pub const X11: Register = 11;+pub const X12: Register = 12;+pub const X13: Register = 13;+pub const X14: Register = 14;+pub const X15: Register = 15;++/// The allocator's number of the vector register `index`, of v0 to v7 and v16 to v23.+pub const fn v(index: u8) -> Register {+ FPR_BASE + if index < 8 { index } else { index - 8 }+}++/// The hardware vector register of the allocator's register `register`.+pub const fn vector_register(register: Register) -> u8 {+ let index = register - FPR_BASE;+ if index < 8 { index } else { index + 8 }+}++pub const GPR_ARGUMENTS: [Register; 8] = [X0, X1, X2, X3, X4, X5, X6, X7];+pub const FPR_ARGUMENTS: [Register; 8] = [v(0), v(1), v(2), v(3), v(4), v(5), v(6), v(7)];+pub const GPR_RESULTS: [Register; 2] = [X0, X1];+pub const FPR_RESULTS: [Register; 2] = [v(0), v(1)];++pub const INSTANCE_REGISTER: Register = X13;+pub const MEMORY_BASE_REGISTER: Register = X14;+pub const CALLEE_REGISTER: Register = X15;++/// The registers values may live in, in the order the allocator prefers them.+pub const ALLOCATABLE_GPRS: [Register; 16] = [X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15];+pub const ALLOCATABLE_FPRS: [Register; 16] = [+ v(0),+ v(1),+ v(2),+ v(3),+ v(4),+ v(5),+ v(6),+ v(7),+ v(16),+ v(17),+ v(18),+ v(19),+ v(20),+ v(21),+ v(22),+ v(23),+];++/// Every allocatable register, as a mask.+pub const ALLOCATABLE: RegisterMask = RegisterMask::MAX;++/// Where a call of a function of the runtime (`Op::Helper`) takes its operands: the instance, from which it finds the+/// context, then the operands, which it stores in the context's `arguments`.+pub const HELPER_REGISTERS: [Register; 7] = [X0, X1, X2, X3, X4, X5, X6];++/// The registers a call of a function of the runtime overwrites: those the host ABI does not preserve, which is all of+/// those the allocator knows.+pub const HOST_CLOBBERS: RegisterMask = RegisterMask::MAX;++/// With `stress-registers`, the registers values get besides those of fixed constraints: few enough that most+/// values spill.+pub const STRESS_GPRS: [Register; 3] = [X0, X10, X11];+pub const STRESS_FPRS: [Register; 2] = [v(16), v(17)];diff --git a/Libraries/LibWasm/JIT/src/convention/x86_64.rs b/Libraries/LibWasm/JIT/src/convention/x86_64.rsnew file mode 100644index 00000000000..5347260bc7c--- /dev/null+++ b/Libraries/LibWasm/JIT/src/convention/x86_64.rs@@ -0,0 +1,102 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The registers of the calling convention on x86-64.+//!+//! - Parameters of integer types go in rdi, rsi, rdx, rcx, r8 and r9, in order, and those of float and vector types+//! in xmm0 to xmm7. Results of integer types come back in rax and rdx, and those of float and vector types in xmm0+//! and xmm1.+//! - r14 holds the callee's instance and r15 the base of its memory 0 at the call, and r10 its `FunctionHeader`.+//! - Every register but rsp and rbp is caller-saved. rsp is 16-byte aligned at the call.++use super::{Register, RegisterMask};++pub const FPR_BASE: Register = 16;++pub const RAX: Register = 0;+pub const RCX: Register = 1;+pub const RDX: Register = 2;+pub const RBX: Register = 3;+pub const RSP: Register = 4;+pub const RBP: Register = 5;+pub const RSI: Register = 6;+pub const RDI: Register = 7;+pub const R8: Register = 8;+pub const R9: Register = 9;+pub const R10: Register = 10;+pub const R11: Register = 11;+pub const R12: Register = 12;+pub const R13: Register = 13;+pub const R14: Register = 14;+pub const R15: Register = 15;++pub const fn xmm(index: u8) -> Register {+ FPR_BASE + index+}++pub const GPR_ARGUMENTS: [Register; 6] = [RDI, RSI, RDX, RCX, R8, R9];+pub const FPR_ARGUMENTS: [Register; 8] = [xmm(0), xmm(1), xmm(2), xmm(3), xmm(4), xmm(5), xmm(6), xmm(7)];+pub const GPR_RESULTS: [Register; 2] = [RAX, RDX];+pub const FPR_RESULTS: [Register; 2] = [xmm(0), xmm(1)];++pub const INSTANCE_REGISTER: Register = R14;+pub const MEMORY_BASE_REGISTER: Register = R15;+pub const CALLEE_REGISTER: Register = R10;++/// Never allocated: moves between memory locations go through them, and lowerings may clobber them.+pub const SCRATCH_GPR: Register = R11;+pub const SCRATCH_FPR: Register = xmm(15);++/// The registers values may live in, in the order the allocator prefers them.+pub const ALLOCATABLE_GPRS: [Register; 13] = [RAX, RCX, RDX, RSI, RDI, R8, R9, R10, RBX, R12, R13, R14, R15];+pub const ALLOCATABLE_FPRS: [Register; 15] = [+ xmm(0),+ xmm(1),+ xmm(2),+ xmm(3),+ xmm(4),+ xmm(5),+ xmm(6),+ xmm(7),+ xmm(8),+ xmm(9),+ xmm(10),+ xmm(11),+ xmm(12),+ xmm(13),+ xmm(14),+];++/// Every allocatable register, as a mask.+pub const ALLOCATABLE: RegisterMask = {+ let mut mask = 0;+ let mut index = 0;+ while index < ALLOCATABLE_GPRS.len() {+ mask |= 1 << ALLOCATABLE_GPRS[index];+ index += 1;+ }+ index = 0;+ while index < ALLOCATABLE_FPRS.len() {+ mask |= 1 << ALLOCATABLE_FPRS[index];+ index += 1;+ }+ mask+};++/// Where a call of a function of the runtime (`Op::Helper`) takes its operands: the instance, from which it finds the+/// context, then the operands, which it stores in the context's `arguments`.+pub const HELPER_REGISTERS: [Register; 7] = [RDI, RSI, RDX, RCX, R8, R9, R10];++/// The registers a call of a function of the runtime overwrites: those the host ABI does not preserve.+pub const HOST_CLOBBERS: RegisterMask = {+ let preserved = (1 << RBX) | (1 << RSP) | (1 << RBP) | (1 << R12) | (1 << R13) | (1 << R14) | (1 << R15);+ !preserved+};++/// With `stress-registers`, the registers values get besides those of fixed constraints: few enough that most+/// values spill.+pub const STRESS_GPRS: [Register; 3] = [RAX, RBX, R12];+pub const STRESS_FPRS: [Register; 2] = [xmm(8), xmm(9)];diff --git a/Libraries/LibWasm/JIT/src/ir/mod.rs b/Libraries/LibWasm/JIT/src/ir/mod.rsindex ff32bbb2402..a0a6093b5f5 100644--- a/Libraries/LibWasm/JIT/src/ir/mod.rs+++ b/Libraries/LibWasm/JIT/src/ir/mod.rs@@ -246,6 +246,10 @@ impl FloatCondition {}}+/// In `Node::flags` of a `Load`, besides its `LoadKind`: the load of an atomic access, which has to be ordered with the+/// others where plain loads are not (on AArch64).+pub const LOAD_ATOMIC: u8 = 0x80;+/// How a load reads memory, in `Node::flags` of `Load`.#[derive(Debug, Clone, Copy, PartialEq, Eq)]#[repr(u8)]@@ -285,7 +289,7 @@ impl LoadKind {];pub fn from_flags(flags: u8) -> Self {- Self::ALL[flags as usize]+ Self::ALL[(flags & !LOAD_ATOMIC) as usize]}pub fn size(self) -> u32 {diff --git a/Libraries/LibWasm/JIT/src/lib.rs b/Libraries/LibWasm/JIT/src/lib.rsindex b84274f9bbf..e864d80af3c 100644--- a/Libraries/LibWasm/JIT/src/lib.rs+++ b/Libraries/LibWasm/JIT/src/lib.rs@@ -26,6 +26,10 @@ pub mod ir;pub mod passes;pub mod regalloc;pub mod runtime;+#[cfg(target_arch = "x86_64")]+pub mod stubs;+#[cfg(target_arch = "aarch64")]+#[path = "stubs_aarch64.rs"]pub mod stubs;pub mod table;@@ -144,7 +148,14 @@ pub fn ticks() -> u64 {unsafe {core::arch::x86_64::_rdtsc()}- #[cfg(not(target_arch = "x86_64"))]+ #[cfg(target_arch = "aarch64")]+ {+ let counter: u64;+ // SAFETY: Reading the virtual counter has no effects.+ unsafe { core::arch::asm!("mrs {}, cntvct_el0", out(reg) counter, options(nomem, nostack)) };+ counter+ }+ #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]0}@@ -250,7 +261,7 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Resultregalloc::verify::dump(&context.func, &context.liveliness, &context.allocation));}- let generated = codegen::x86_64::generate(+ let generated = codegen::target::generate(&context.func,&context.liveliness,&context.allocation,@@ -280,7 +291,12 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result));}if request.options.dump_asm {- for line in asm::disassembler::listing(asm::Architecture::X86_64, &compiled.code) {+ let architecture = if cfg!(target_arch = "aarch64") {+ asm::Architecture::AArch64+ } else {+ asm::Architecture::X86_64+ };+ for line in asm::disassembler::listing(architecture, &compiled.code) {text.push_str(&format!("{:6x} {}\n", line.offset, line.text));}}diff --git a/Libraries/LibWasm/JIT/src/regalloc/aarch64.rs b/Libraries/LibWasm/JIT/src/regalloc/aarch64.rsnew file mode 100644index 00000000000..a801b422d8c--- /dev/null+++ b/Libraries/LibWasm/JIT/src/regalloc/aarch64.rs@@ -0,0 +1,93 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The constraints of nodes on AArch64. Instructions have three operands and no fixed registers, and code generation+//! puts any constant that does not fit an immediate into a scratch register, so constants may be inputs anywhere a+//! lowering takes one.++use super::{Constraints, Input, Output, Temp};+use crate::ir::{Func, Op, Type, Value};++/// Whether constant `value` can be an input of its own: any scalar constant can.+pub fn fits_immediate(func: &Func, value: Value) -> bool {+ func.node(value).constant().is_some()+}++pub(super) fn constraints(func: &Func, value: Value) -> Constraints {+ let node = func.node(value);+ let output = if node.ty == Type::None {+ Output::None+ } else {+ Output::Register+ };+ let mut constraints = Constraints {+ inputs: [Input::Register; 3],+ output,+ temps: [Temp::None; 2],+ clobbers: 0,+ reuse_first: false,+ slot_inputs: 0,+ };+ match node.op {+ Op::Add+ | Op::Sub+ | Op::And+ | Op::Or+ | Op::Xor+ | Op::Mul+ | Op::Shl+ | Op::ShrS+ | Op::ShrU+ | Op::Rotl+ | Op::Rotr+ | Op::Compare+ | Op::BranchCompare+ | Op::Load+ | Op::VectorLoad+ | Op::GlobalSet+ | Op::WriteField+ | Op::RefTest => constraints.inputs[1] = Input::RegisterOrConstant,+ Op::Store => {+ constraints.inputs[1] = Input::RegisterOrConstant;+ constraints.inputs[2] = Input::RegisterOrConstant;+ }+ Op::CheckFunction => constraints.temps = [Temp::Gpr, Temp::Gpr],+ Op::CheckedAddress => {+ let size = 1u64 << (node.flags & 7);+ let offset = func.node(node.args[2]).constant();+ // NB: A memory64's offset can be close enough to 2^64 that adding the size wraps around.+ if offset+ .and_then(|offset| offset.checked_add(size))+ .is_some_and(|end| end <= i32::MAX as u64)+ {+ constraints.inputs[2] = Input::RegisterOrConstant;+ }+ }+ _ => {}+ }+ if node.op == Op::RefTest {+ constraints.temps = match crate::ir::HeapTest::from_flags(node.flags) {+ crate::ir::HeapTest::Struct | crate::ir::HeapTest::Array | crate::ir::HeapTest::ConcreteObject => {+ [Temp::Gpr, Temp::None]+ }+ crate::ir::HeapTest::ConcreteFunction => [Temp::Gpr, Temp::Gpr],+ _ => [Temp::None, Temp::None],+ };+ }+ if matches!(+ node.op,+ Op::Shuffle | Op::VectorUnary | Op::VectorBinary | Op::VectorTernary+ ) {+ let temps = crate::codegen::aarch64::vector_temps(func, value);+ for temp in constraints.temps.iter_mut().take(temps) {+ *temp = Temp::Fpr;+ }+ if node.op == Op::VectorBinary && crate::codegen::aarch64::is_vector_shift(node.args[2]) {+ constraints.inputs[1] = Input::RegisterOrConstant;+ }+ }+ constraints+}diff --git a/Libraries/LibWasm/JIT/src/regalloc/mod.rs b/Libraries/LibWasm/JIT/src/regalloc/mod.rsindex e83d240904a..ad32733b658 100644--- a/Libraries/LibWasm/JIT/src/regalloc/mod.rs+++ b/Libraries/LibWasm/JIT/src/regalloc/mod.rs@@ -19,9 +19,17 @@//! the inputs from that predecessor. Every other edge into them moves its values into place, as parallel moves.//! Edges from blocks with several successors that need moves get a stub of their own in code generation.+#[cfg(target_arch = "aarch64")]+mod aarch64;pub mod liveness;pub mod verify;+#[cfg(target_arch = "aarch64")]+use aarch64::constraints;+#[cfg(target_arch = "aarch64")]+pub use aarch64::fits_immediate;++#[cfg(target_arch = "x86_64")]use crate::codegen;use crate::convention::{self, Place, Register};use crate::ir::{BlockId, Func, NONE, Op, Type, Value};@@ -128,6 +136,8 @@ impl Allocation {}}+// NB: AArch64 has no fixed registers and no constant operands in memory.+#[cfg_attr(target_arch = "aarch64", allow(dead_code))]#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Input {Register,@@ -138,6 +148,8 @@ enum Input {RegisterOrVectorConstant,}+// NB: AArch64 has no fixed registers and no constant operands in memory.+#[cfg_attr(target_arch = "aarch64", allow(dead_code))]#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Output {None,@@ -145,6 +157,8 @@ enum Output {Fixed(Register),}+// NB: AArch64 has no fixed registers and no constant operands in memory.+#[cfg_attr(target_arch = "aarch64", allow(dead_code))]#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Temp {None,@@ -167,6 +181,7 @@ struct Constraints {}/// Whether constant `value` fits an instruction as an immediate: sign-extended 32 bits for 64-bit operations.+#[cfg(target_arch = "x86_64")]pub fn fits_immediate(func: &Func, value: Value) -> bool {let node = func.node(value);match node.constant() {@@ -177,12 +192,14 @@ pub fn fits_immediate(func: &Func, value: Value) -> bool {}/// Whether a constant index and offset of a memory access fit its displacement.+#[cfg(target_arch = "x86_64")]pub fn fits_displacement(func: &Func, index: Value, offset: u32) -> bool {func.node(index).constant().is_some_and(|bits| (bits & 0xffff_ffff) + u64::from(offset) <= i32::MAX as u64)}+#[cfg(target_arch = "x86_64")]fn constraints(func: &Func, value: Value) -> Constraints {use convention::{RAX, RCX, RDX};let node = func.node(value);@@ -358,10 +375,7 @@ pub struct Allocator {fprs: &'static [Register],}-/// With `stress-registers`, the registers values get besides those of fixed constraints: few enough that most-/// values spill.-const STRESS_GPRS: [Register; 3] = [convention::RAX, convention::RBX, convention::R12];-const STRESS_FPRS: [Register; 2] = [convention::xmm(8), convention::xmm(9)];+use convention::{STRESS_FPRS, STRESS_GPRS};impl Allocator {/// Allocates registers for `func` into `allocation`.@@ -1162,7 +1176,7 @@ impl Allocator {}}if func.node(value).ty != Type::None {- self.define(func, allocation, value, convention::RAX);+ self.define(func, allocation, value, convention::GPR_RESULTS[0]);}}diff --git a/Libraries/LibWasm/JIT/src/regalloc/verify.rs b/Libraries/LibWasm/JIT/src/regalloc/verify.rsindex 3771f35dd6d..7336de755d9 100644--- a/Libraries/LibWasm/JIT/src/regalloc/verify.rs+++ b/Libraries/LibWasm/JIT/src/regalloc/verify.rs@@ -169,6 +169,7 @@ pub fn verify(func: &Func, liveliness: &Liveliness, allocation: &Allocation) ->simulation.registers[temp as usize] = NONE;}}+ #[cfg(target_arch = "x86_64")]if matches!(node.op, Op::DivS | Op::DivU | Op::RemS | Op::RemU) {simulation.registers[convention::RAX as usize] = NONE;simulation.registers[convention::RDX as usize] = NONE;diff --git a/Libraries/LibWasm/JIT/src/runtime.rs b/Libraries/LibWasm/JIT/src/runtime.rsindex 7666c4f32da..ee7e611076f 100644--- a/Libraries/LibWasm/JIT/src/runtime.rs+++ b/Libraries/LibWasm/JIT/src/runtime.rs@@ -17,6 +17,43 @@ use libwasm_module::abi::{TRAP_TABLE_OUT_OF_BOUNDS, TableData,};+/// Makes instruction fetches see code just written at `start`, `length` bytes. On AArch64 the data cache lines are+/// cleaned to where instruction fetches see them and the instruction cache lines invalidated; x86-64 keeps its caches+/// coherent.+pub fn flush_instruction_cache(start: usize, length: usize) {+ #[cfg(all(target_arch = "aarch64", target_os = "macos"))]+ {+ unsafe extern "C" {+ fn sys_icache_invalidate(start: *mut core::ffi::c_void, length: usize);+ }+ // SAFETY: The range is code the caller just wrote.+ unsafe { sys_icache_invalidate(start as *mut core::ffi::c_void, length) };+ }+ #[cfg(all(target_arch = "aarch64", not(target_os = "macos")))]+ // SAFETY: Cache maintenance by address changes no data.+ unsafe {+ let cache_type: u64;+ core::arch::asm!("mrs {}, ctr_el0", out(reg) cache_type, options(nomem, nostack));+ let data_line = 4usize << ((cache_type >> 16) & 15);+ let instruction_line = 4usize << (cache_type & 15);+ let end = start + length;+ let mut line = start & !(data_line - 1);+ while line < end {+ core::arch::asm!("dc cvau, {}", in(reg) line, options(nostack));+ line += data_line;+ }+ core::arch::asm!("dsb ish", options(nostack));+ let mut line = start & !(instruction_line - 1);+ while line < end {+ core::arch::asm!("ic ivau, {}", in(reg) line, options(nostack));+ line += instruction_line;+ }+ core::arch::asm!("dsb ish", "isb", options(nostack));+ }+ #[cfg(not(target_arch = "aarch64"))]+ let _ = (start, length);+}+/// The address of the function `helper` calls.pub fn helper_address(helper: Helper, runtime: &RuntimeInfo) -> u64 {let function: unsafe extern "C" fn(*mut ExecutionContext) -> u64 = match helper {diff --git a/Libraries/LibWasm/JIT/src/stubs_aarch64.rs b/Libraries/LibWasm/JIT/src/stubs_aarch64.rsnew file mode 100644index 00000000000..46ad19e1270--- /dev/null+++ b/Libraries/LibWasm/JIT/src/stubs_aarch64.rs@@ -0,0 +1,478 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Code around compiled functions on AArch64, which the runtime makes once per process (see `stubs.rs` for what each+//! stub does). The trap exit takes the TRAP_* code in w0.++use crate::RuntimeInfo;+use crate::asm::aarch64::{Assembler, Cond, Extend, MemOp, MemOperand, PairOperand, Shift, X16, X17, XZR};+use crate::asm::{Fpr, Gpr, Width};+use crate::codegen::aarch64::{fits_offset, fpr};+use crate::convention::{self, Place, Register};+use crate::ir::Type;+use libwasm_module::abi::{ExecutionContext, FRAME_CONTEXT, InstanceData, TRAP_RUNTIME, TRAP_STACK_EXHAUSTED};+use std::mem::offset_of;++const FP: Gpr = Gpr(29);+const LR: Gpr = Gpr(30);+const SP: Gpr = Gpr(31);+const SCRATCH: Gpr = X16;+const SCRATCH_FPR: Fpr = Fpr(31);++fn x(index: u8) -> Gpr {+ Gpr(index)+}++fn field(offset: usize) -> i32 {+ offset as i32+}++/// An operand for an access of `1 << size_log2` bytes at `base` + `offset`, through x17 where the offset does not fit.+fn operand(asm: &mut Assembler, base: Gpr, offset: i32, size_log2: u32) -> MemOperand {+ if fits_offset(i64::from(offset), size_log2) {+ return MemOperand::Offset(base, offset);+ }+ asm.add_any(X17, base, i64::from(offset), X17);+ MemOperand::Offset(X17, 0)+}++/// Loads (if `load`) or stores the value of type `ty` in the register `register` (as the allocator numbers it) at+/// `base` + `offset`.+fn transfer(asm: &mut Assembler, ty: Type, register: Register, base: Gpr, offset: i32, load: bool) {+ if ty == Type::V128 || convention::is_fpr(register) {+ transfer_fpr(asm, ty, fpr(register), base, offset, load);+ return;+ }+ // NB: i32 values are zero-extended in registers.+ let op = match (ty == Type::I32, load) {+ (true, true) => MemOp::LdrW,+ (false, true) => MemOp::LdrX,+ (_, false) => MemOp::StrX,+ };+ let size_log2 = if op == MemOp::LdrW { 2 } else { 3 };+ let operand = operand(asm, base, offset, size_log2);+ asm.load_store(op, register, operand);+}++fn transfer_fpr(asm: &mut Assembler, ty: Type, register: Fpr, base: Gpr, offset: i32, load: bool) {+ let (op, size_log2) = match (ty == Type::V128, load) {+ (true, true) => (MemOp::LdrQ, 4),+ (true, false) => (MemOp::StrQ, 4),+ (false, true) => (MemOp::LdrD, 3),+ (false, false) => (MemOp::StrD, 3),+ };+ let operand = operand(asm, base, offset, size_log2);+ asm.load_store(op, register.0, operand);+}++/// Copies a value of type `ty` between memory locations, through the scratch vector register.+fn copy(asm: &mut Assembler, ty: Type, from: (Gpr, i32), to: (Gpr, i32)) {+ let ty = if ty == Type::V128 { Type::V128 } else { Type::F64 };+ transfer_fpr(asm, ty, SCRATCH_FPR, from.0, from.1, true);+ transfer_fpr(asm, ty, SCRATCH_FPR, to.0, to.1, false);+}++/// Jumps to the trap exit with the code `code`.+fn trap(asm: &mut Assembler, code: u32, runtime: &RuntimeInfo) {+ asm.mov_imm(Width::W32, x(0), u64::from(code));+ asm.mov_imm(Width::W64, SCRATCH, runtime.trap_exit);+ asm.br(SCRATCH);+}++/// Pushes a frame record and makes fp the caller's sp, as compiled functions do, then allocates `frame_size` bytes+/// below fp, the header included, and stores the instance in x13 in the header.+fn enter(asm: &mut Assembler, frame_size: i32) {+ asm.stp(FP, LR, PairOperand::PreIndex(SP, -16));+ asm.add_imm(Width::W64, FP, SP, 16, false);+ asm.add_any(SP, SP, -i64::from(frame_size - 16), X17);+ asm.str(+ Width::W64,+ x(convention::INSTANCE_REGISTER),+ MemOperand::Offset(FP, convention::FRAME_INSTANCE),+ );+}++fn leave(asm: &mut Assembler) {+ asm.sub_imm(Width::W64, SP, FP, 16, false);+ asm.ldp(FP, LR, PairOperand::PostIndex(SP, 16));+ asm.ret();+}++/// The host stub for functions with these parameter and result types.+pub fn host_stub(params: &[Type], results: &[Type], runtime: &RuntimeInfo) -> Vec<u8> {+ let mut asm = Assembler::new();+ let parameter_slots = convention::slots(params) as i32;+ let result_slots = convention::slots(results) as i32;+ let buffer_slots = parameter_slots.max(result_slots);+ // Below the frame header: a zero word, which makes the frame the runtime unwinds an exception from look like an+ // entry frame, and the operand stack image at sp.+ let zero = -convention::FRAME_HEADER_SIZE - 8;+ let frame_size = (convention::FRAME_HEADER_SIZE as u32 + 8 + 8 * buffer_slots as u32).next_multiple_of(16) as i32;+ let context = x(9);+ let instance = x(convention::INSTANCE_REGISTER);++ // The stack check comes first, against the frame's bottom, with the header already in place for the trap.+ asm.stp(FP, LR, PairOperand::PreIndex(SP, -16));+ asm.add_imm(Width::W64, FP, SP, 16, false);+ asm.sub_imm(Width::W64, SP, SP, (convention::FRAME_HEADER_SIZE - 16) as u32, false);+ asm.str(Width::W64, instance, MemOperand::Offset(FP, convention::FRAME_INSTANCE));+ asm.ldr(+ Width::W64,+ context,+ MemOperand::Offset(instance, field(offset_of!(InstanceData, context))),+ );+ asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(context, field(offset_of!(ExecutionContext, stack_limit))),+ );+ asm.add_any(X17, FP, -i64::from(frame_size), X17);+ asm.cmp(Width::W64, X17, SCRATCH);+ let exhausted = asm.new_label();+ asm.b_cond(Cond::Lo, exhausted);+ asm.mov_sp(SP, X17);++ // The operand stack grows down, so the first argument is in the highest slots.+ let top = 8 * (buffer_slots - parameter_slots);+ let mut places = Vec::new();+ convention::parameter_places(params, &mut places);+ for (index, place) in places.iter().enumerate() {+ let home = convention::home_slot(params, index) as i32;+ let slot = parameter_slots - home - params[index].slots() as i32;+ let offset = top + 8 * slot;+ match *place {+ Place::Register(register) => transfer(&mut asm, params[index], register, SP, offset, false),+ Place::Memory(home) => copy(&mut asm, params[index], (FP, 8 * home as i32), (SP, offset)),+ }+ }++ let arguments = field(offset_of!(ExecutionContext, arguments));+ asm.str(+ Width::W64,+ x(convention::CALLEE_REGISTER),+ MemOperand::Offset(context, arguments),+ );+ asm.add_any(SCRATCH, SP, i64::from(top), X17);+ asm.str(Width::W64, SCRATCH, MemOperand::Offset(context, arguments + 8));+ asm.str(Width::W64, XZR, MemOperand::Offset(context, arguments + 16));+ asm.str(Width::W64, XZR, MemOperand::Offset(FP, zero));+ asm.sub_imm(+ Width::W64,+ SCRATCH,+ FP,+ (convention::FRAME_INSTANCE - zero) as u32,+ false,+ );+ asm.str(Width::W64, SCRATCH, MemOperand::Offset(context, arguments + 24));+ asm.mov(Width::W64, x(0), context);+ asm.mov_imm(Width::W64, SCRATCH, runtime.call_host);+ asm.blr(SCRATCH);++ // 0 is a trap, which the runtime keeps; 1 would resume at a handler, which the zero word rules out.+ let failed = asm.new_label();+ asm.cmp_imm(Width::W64, x(0), 1, false);+ asm.b_cond(Cond::Ls, failed);+ let return_top = x(9);+ asm.mov(Width::W64, return_top, x(0));+ let area = x(10);+ if convention::has_result_area(results) {+ let operand = operand(&mut asm, FP, 8 * parameter_slots, 3);+ asm.ldr(Width::W64, area, operand);+ }+ convention::result_places(results, &mut places);+ for (index, place) in places.iter().enumerate() {+ let home = convention::home_slot(results, index) as i32;+ let slot = result_slots - home - results[index].slots() as i32;+ let offset = 8 * slot;+ match *place {+ Place::Register(register) => transfer(&mut asm, results[index], register, return_top, offset, true),+ Place::Memory(home) => copy(&mut asm, results[index], (return_top, offset), (area, 8 * home as i32)),+ }+ }+ leave(&mut asm);++ for (label, code) in [(failed, TRAP_RUNTIME), (exhausted, TRAP_STACK_EXHAUSTED)] {+ asm.bind(label);+ trap(&mut asm, code, runtime);+ }+ asm.finish().expect("stubs have no unbound labels")+}++/// What the entry trampoline calls compiled code with, and what it returns.+#[repr(C)]+#[derive(Debug, Default)]+pub struct NativeCall {+ /// The code to call: the callee's `native_entry`, or the entry of an OSR compile.+ pub entry: u64,+ pub header: u64,+ pub instance: u64,+ pub memory_base: u64,+ /// The integer argument registers, in `convention::GPR_ARGUMENTS` order.+ pub gprs: [u64; 8],+ /// The vector argument registers, low half first.+ pub xmms: [[u64; 2]; 8],+ /// The home slots of the call, and a result area if it needs one: copied to the outgoing area before the+ /// call, and back after it.+ pub image: u64,+ pub image_slots: u64,+ /// The slot of the result area pointer in the image, or u64::MAX.+ pub result_pointer_slot: u64,+ /// x0 and x1 after the call.+ pub result_gprs: [u64; 2],+ /// v0 and v1 after the call.+ pub result_xmms: [[u64; 2]; 2],+ /// Where the trampoline keeps its stack pointer during the call.+ pub saved_sp: u64,+}++/// The size of the area the runtime adapter saves the argument registers in: the eight integer ones, then the eight+/// vector ones, 16 bytes each. The runtime function stores the results' registers in the same places: x0 and x1, v0+/// and v1.+pub const ADAPTER_SAVE_AREA: usize = 8 * 8 + 8 * 16;++/// The trap exit: stores the code in w0 as the context's first argument, and the context in the frame that trapped+/// (fp), and continues at the interpreter's TrapFromNative handler at `handler`.+pub fn trap_exit(handler: u64) -> Vec<u8> {+ let mut asm = Assembler::new();+ let context = SCRATCH;+ asm.ldr(Width::W64, context, MemOperand::Offset(FP, convention::FRAME_INSTANCE));+ asm.ldr(+ Width::W64,+ context,+ MemOperand::Offset(context, field(offset_of!(InstanceData, context))),+ );+ asm.str(Width::W64, context, MemOperand::Offset(FP, FRAME_CONTEXT as i32));+ asm.mov(Width::W32, x(0), x(0));+ asm.str(+ Width::W64,+ x(0),+ MemOperand::Offset(context, field(offset_of!(ExecutionContext, arguments))),+ );+ asm.mov_imm(Width::W64, X17, handler);+ asm.br(X17);+ asm.finish().expect("stubs have no unbound labels")+}++/// Continues where the `resume` of the context in `context` says, as the runtime set it after unwinding an+/// exception: loads sp and fp and jumps.+pub fn resume(asm: &mut Assembler, context: Gpr) {+ let resume = field(offset_of!(ExecutionContext, resume));+ asm.ldr(Width::W64, X17, MemOperand::Offset(context, resume));+ asm.mov_sp(SP, X17);+ asm.ldr(Width::W64, FP, MemOperand::Offset(context, resume + 8));+ asm.ldr(Width::W64, X17, MemOperand::Offset(context, resume + 16));+ asm.br(X17);+}++/// Copies `count` 8-byte words from `from` up to `to` through `temp`, clobbering all four.+fn copy_words(asm: &mut Assembler, from: Gpr, to: Gpr, count: Gpr, temp: Gpr) {+ let done = asm.new_label();+ let again = asm.new_label();+ asm.cbz(Width::W64, count, done);+ asm.bind(again);+ asm.ldr(Width::W64, temp, MemOperand::PostIndex(from, 8));+ asm.str(Width::W64, temp, MemOperand::PostIndex(to, 8));+ asm.subs_imm(Width::W64, count, count, 1, false);+ asm.b_cond(Cond::Ne, again);+ asm.bind(done);+}++/// The entry trampoline, `extern "C" fn(*mut NativeCall)`, and the offset of the address its call of compiled code+/// returns to, where an exception the compiled code does not handle continues (see `RuntimeInfo::throw`). It keeps+/// the record in x19, which compiled code never uses, and saves nothing else: compiled code uses only the registers+/// the host ABI does not preserve (see `convention`).+pub fn entry_trampoline() -> (Vec<u8>, usize) {+ let mut asm = Assembler::new();+ let record = Gpr(19);+ let call_field = |offset: usize| field(offset);+ asm.stp(FP, LR, PairOperand::PreIndex(SP, -32));+ asm.mov_sp(FP, SP);+ asm.stp(record, Gpr(20), PairOperand::Offset(SP, 16));+ asm.mov(Width::W64, record, x(0));+ // The image goes at the bottom of the stack, 16-byte aligned.+ let (count, size) = (x(9), x(10));+ asm.ldr(+ Width::W64,+ count,+ MemOperand::Offset(record, call_field(offset_of!(NativeCall, image_slots))),+ );+ asm.lsl_imm(Width::W64, size, count, 3);+ asm.add_imm(Width::W64, size, size, 15, false);+ asm.and_imm(Width::W64, size, size, !15u64);+ asm.sub_extended(Width::W64, SP, SP, size, Extend::Uxtx, 0);+ asm.mov_sp(x(11), SP);+ asm.str(+ Width::W64,+ x(11),+ MemOperand::Offset(record, call_field(offset_of!(NativeCall, saved_sp))),+ );+ asm.ldr(+ Width::W64,+ x(12),+ MemOperand::Offset(record, call_field(offset_of!(NativeCall, image))),+ );+ copy_words(&mut asm, x(12), x(11), count, x(13));+ let no_area = asm.new_label();+ asm.ldr(+ Width::W64,+ x(10),+ MemOperand::Offset(record, call_field(offset_of!(NativeCall, result_pointer_slot))),+ );+ asm.cmn_imm(Width::W64, x(10), 1, false);+ asm.b_cond(Cond::Eq, no_area);+ asm.mov_sp(x(11), SP);+ asm.add(Width::W64, x(11), x(11), x(10), Shift::Lsl, 3);+ asm.add_imm(Width::W64, x(12), x(11), 8, false);+ asm.str(Width::W64, x(12), MemOperand::Offset(x(11), 0));+ asm.bind(no_area);+ for index in 0..8u8 {+ let offset = call_field(offset_of!(NativeCall, xmms) + 16 * index as usize);+ transfer_fpr(+ &mut asm,+ Type::V128,+ fpr(convention::FPR_ARGUMENTS[index as usize]),+ record,+ offset,+ true,+ );+ }+ for (index, register) in convention::GPR_ARGUMENTS.iter().enumerate() {+ let offset = call_field(offset_of!(NativeCall, gprs) + 8 * index);+ asm.ldr(Width::W64, x(*register), MemOperand::Offset(record, offset));+ }+ for (register, offset) in [+ (convention::CALLEE_REGISTER, offset_of!(NativeCall, header)),+ (convention::INSTANCE_REGISTER, offset_of!(NativeCall, instance)),+ (convention::MEMORY_BASE_REGISTER, offset_of!(NativeCall, memory_base)),+ ] {+ asm.ldr(Width::W64, x(register), MemOperand::Offset(record, field(offset)));+ }+ asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(record, call_field(offset_of!(NativeCall, entry))),+ );+ asm.blr(SCRATCH);+ let return_offset = asm.offset();+ // NB: Tail calls may have moved sp; the record has it.+ asm.ldr(+ Width::W64,+ x(11),+ MemOperand::Offset(record, call_field(offset_of!(NativeCall, saved_sp))),+ );+ asm.mov_sp(SP, x(11));+ let results = call_field(offset_of!(NativeCall, result_gprs));+ asm.str(Width::W64, x(0), MemOperand::Offset(record, results));+ asm.str(Width::W64, x(1), MemOperand::Offset(record, results + 8));+ for index in 0..2u8 {+ let offset = call_field(offset_of!(NativeCall, result_xmms) + 16 * index as usize);+ transfer_fpr(+ &mut asm,+ Type::V128,+ fpr(convention::FPR_RESULTS[index as usize]),+ record,+ offset,+ false,+ );+ }+ asm.ldr(+ Width::W64,+ x(9),+ MemOperand::Offset(record, call_field(offset_of!(NativeCall, image_slots))),+ );+ asm.ldr(+ Width::W64,+ x(12),+ MemOperand::Offset(record, call_field(offset_of!(NativeCall, image))),+ );+ asm.mov_sp(x(11), SP);+ copy_words(&mut asm, x(11), x(12), x(9), x(13));+ asm.mov_sp(SP, FP);+ asm.ldp(record, Gpr(20), PairOperand::Offset(SP, 16));+ asm.ldp(FP, LR, PairOperand::PostIndex(SP, 32));+ asm.ret();+ (asm.finish().expect("stubs have no unbound labels"), return_offset)+}++/// What the runtime function of the adapter returns when the call threw an exception, which the runtime unwound: the+/// adapter continues where the context's `resume` says.+pub const ADAPTER_RESUME: u64 = u64::MAX;++/// The runtime adapter. `function` is the runtime's `extern "C" fn(*mut ExecutionContext) -> u64`, which it calls+/// with the callee's header, the save area and fp as the context's first three arguments. A nonzero result is a+/// trap code, or `ADAPTER_RESUME`.+pub fn runtime_adapter(function: u64, runtime: &RuntimeInfo) -> Vec<u8> {+ let mut asm = Assembler::new();+ let instance = x(convention::INSTANCE_REGISTER);+ // Below the frame header, the save area at sp.+ let frame_size = (convention::FRAME_HEADER_SIZE as usize + ADAPTER_SAVE_AREA).next_multiple_of(16) as i32;+ enter(&mut asm, frame_size);+ for (index, register) in convention::GPR_ARGUMENTS.iter().enumerate() {+ asm.str(Width::W64, x(*register), MemOperand::Offset(SP, 8 * index as i32));+ }+ let vectors = 8 * convention::GPR_ARGUMENTS.len() as i32;+ for (index, register) in convention::FPR_ARGUMENTS.iter().enumerate() {+ transfer_fpr(+ &mut asm,+ Type::V128,+ fpr(*register),+ SP,+ vectors + 16 * index as i32,+ false,+ );+ }+ let context = SCRATCH;+ asm.ldr(+ Width::W64,+ context,+ MemOperand::Offset(instance, field(offset_of!(InstanceData, context))),+ );+ let arguments = field(offset_of!(ExecutionContext, arguments));+ asm.str(+ Width::W64,+ x(convention::CALLEE_REGISTER),+ MemOperand::Offset(context, arguments),+ );+ asm.mov_sp(X17, SP);+ asm.str(Width::W64, X17, MemOperand::Offset(context, arguments + 8));+ asm.str(Width::W64, FP, MemOperand::Offset(context, arguments + 16));+ asm.mov(Width::W64, x(0), context);+ asm.mov_imm(Width::W64, SCRATCH, function);+ asm.blr(SCRATCH);+ let trap = asm.new_label();+ asm.cbnz(Width::W64, x(0), trap);+ for (index, register) in convention::GPR_RESULTS.iter().enumerate() {+ asm.ldr(Width::W64, x(*register), MemOperand::Offset(SP, 8 * index as i32));+ }+ for (index, register) in convention::FPR_RESULTS.iter().enumerate() {+ transfer_fpr(+ &mut asm,+ Type::V128,+ fpr(*register),+ SP,+ vectors + 16 * index as i32,+ true,+ );+ }+ leave(&mut asm);+ asm.bind(trap);+ let unwound = asm.new_label();+ asm.cmn_imm(Width::W64, x(0), 1, false);+ asm.b_cond(Cond::Eq, unwound);+ // NB: The code is in x0 already.+ asm.mov_imm(Width::W64, SCRATCH, runtime.trap_exit);+ asm.br(SCRATCH);+ asm.bind(unwound);+ let context = SCRATCH;+ asm.ldr(Width::W64, context, MemOperand::Offset(FP, convention::FRAME_INSTANCE));+ asm.ldr(+ Width::W64,+ context,+ MemOperand::Offset(context, field(offset_of!(InstanceData, context))),+ );+ resume(&mut asm, context);+ asm.finish().expect("stubs have no unbound labels")+}diff --git a/Libraries/LibWasm/JIT/tests/harness/aarch64.rs b/Libraries/LibWasm/JIT/tests/harness/aarch64.rsnew file mode 100644index 00000000000..130815fb1ea--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/harness/aarch64.rs@@ -0,0 +1,188 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The harness's code on AArch64: the trap exit, the stub of functions that did not compile, and the trampolines.++use super::{ENTRY_SP_OFFSET, SessionState, TRAP_NOT_COMPILED, TRAP_OFFSET};+use libwasm_engine::abi::InstanceData;+use libwasm_jit::asm::aarch64::{Assembler, MemOp, MemOperand, PairOperand, X16, X17};+use libwasm_jit::asm::{Fpr, Gpr, Width};+use libwasm_jit::convention::{self, Place};+use libwasm_jit::ir::Type;+use std::mem::offset_of;++const FP: Gpr = Gpr(29);+const LR: Gpr = Gpr(30);+const SP: Gpr = Gpr(31);+const SCRATCH_FPR: Fpr = Fpr(31);+/// The bytes of the trampoline's frame record and saved registers.+const SAVE_AREA: i32 = 96;++fn hardware_fpr(register: u8) -> Fpr {+ Fpr(convention::vector_register(register))+}++/// An operand at `base` + `offset` for an access of `1 << size_log2` bytes, through x17 where it does not fit.+fn operand(asm: &mut Assembler, base: Gpr, offset: i32, size_log2: u32) -> MemOperand {+ if libwasm_jit::codegen::aarch64::fits_offset(i64::from(offset), size_log2) {+ return MemOperand::Offset(base, offset);+ }+ asm.add_any(X17, base, i64::from(offset), X17);+ MemOperand::Offset(X17, 0)+}++/// The trap exit, entered with the trap code in w0: returns 1 from the trampoline.+pub(super) fn trap_exit_code(state: *mut SessionState) -> Vec<u8> {+ let mut asm = Assembler::new();+ asm.mov_imm(Width::W64, X16, state as u64);+ asm.str(Width::W32, Gpr(0), MemOperand::Offset(X16, TRAP_OFFSET));+ asm.ldr(Width::W64, X17, MemOperand::Offset(X16, ENTRY_SP_OFFSET));+ asm.mov_sp(SP, X17);+ restore_and_return(&mut asm, 1);+ asm.finish().unwrap()+}++/// The code of functions the JIT did not compile.+pub(super) fn not_compiled_code(trap_exit: u64) -> Vec<u8> {+ trap_stub(trap_exit, TRAP_NOT_COMPILED)+}++/// Code that traps with `code`.+pub(super) fn trap_stub(trap_exit: u64, code: u32) -> Vec<u8> {+ let mut asm = Assembler::new();+ asm.mov_imm(Width::W32, Gpr(0), u64::from(code));+ asm.mov_imm(Width::W64, X16, trap_exit);+ asm.br(X16);+ asm.finish().unwrap()+}++/// Restores what the trampoline saved, from sp at its entry_sp, and returns `status`.+fn restore_and_return(asm: &mut Assembler, status: u32) {+ asm.add_imm(Width::W64, SP, SP, 16, false);+ for (index, pair) in [(19, 20), (21, 22), (23, 24), (25, 26), (27, 28)].iter().enumerate() {+ asm.ldp(+ Gpr(pair.0),+ Gpr(pair.1),+ PairOperand::Offset(SP, 16 + 16 * index as i32),+ );+ }+ asm.ldp(FP, LR, PairOperand::PostIndex(SP, SAVE_AREA));+ asm.mov_imm(Width::W32, Gpr(0), u64::from(status));+ asm.ret();+}++/// Loads (if `load`) or stores the value of type `ty` in the register `register` at `base` + `offset`.+fn transfer(asm: &mut Assembler, ty: Type, register: u8, base: Gpr, offset: i32, load: bool) {+ let (op, encoding, size_log2) = if ty == Type::V128 {+ (+ if load { MemOp::LdrQ } else { MemOp::StrQ },+ hardware_fpr(register).0,+ 4,+ )+ } else if convention::is_fpr(register) {+ (+ if load { MemOp::LdrD } else { MemOp::StrD },+ hardware_fpr(register).0,+ 3,+ )+ } else {+ (if load { MemOp::LdrX } else { MemOp::StrX }, register, 3)+ };+ let operand = operand(asm, base, offset, size_log2);+ asm.load_store(op, encoding, operand);+}++/// Copies the 8 or 16 bytes of a value of type `ty` between memory locations, through v31.+fn copy(asm: &mut Assembler, ty: Type, from: (Gpr, i32), to: (Gpr, i32)) {+ let (load, store, size_log2) = if ty == Type::V128 {+ (MemOp::LdrQ, MemOp::StrQ, 4)+ } else {+ (MemOp::LdrD, MemOp::StrD, 3)+ };+ let operand_from = operand(asm, from.0, from.1, size_log2);+ asm.load_store(load, SCRATCH_FPR.0, operand_from);+ let operand_to = operand(asm, to.0, to.1, size_log2);+ asm.load_store(store, SCRATCH_FPR.0, operand_to);+}++/// `extern "C" fn(entry, arguments, results, instance) -> u32`: calls `entry` with the arguments' slots under the+/// compiled convention, stores the results' slots, and returns 0, or 1 if the code trapped.+pub(super) fn trampoline_code(params: &[Type], results: &[Type], state: *mut SessionState) -> Vec<u8> {+ let mut asm = Assembler::new();+ asm.stp(FP, LR, PairOperand::PreIndex(SP, -SAVE_AREA));+ asm.mov_sp(FP, SP);+ for (index, pair) in [(19, 20), (21, 22), (23, 24), (25, 26), (27, 28)].iter().enumerate() {+ asm.stp(+ Gpr(pair.0),+ Gpr(pair.1),+ PairOperand::Offset(SP, 16 + 16 * index as i32),+ );+ }+ // The results pointer, at the entry_sp the trap exit restores.+ asm.sub_imm(Width::W64, SP, SP, 16, false);+ asm.str(Width::W64, Gpr(2), MemOperand::Offset(SP, 0));+ asm.mov_imm(Width::W64, X16, state as u64);+ asm.mov_sp(X17, SP);+ asm.str(Width::W64, X17, MemOperand::Offset(X16, ENTRY_SP_OFFSET));+ let outgoing = convention::outgoing_size(params, results).next_multiple_of(16) as i64;+ asm.add_any(SP, SP, -outgoing, X17);+ // The entry goes in x16 and the arguments' pointer in x19, which compiled code never uses.+ let (entry, arguments) = (X16, Gpr(19));+ asm.mov(Width::W64, entry, Gpr(0));+ asm.mov(Width::W64, arguments, Gpr(1));+ asm.mov(Width::W64, Gpr(convention::INSTANCE_REGISTER), Gpr(3));+ asm.ldr(+ Width::W64,+ Gpr(convention::MEMORY_BASE_REGISTER),+ MemOperand::Offset(Gpr(3), offset_of!(InstanceData, memory0_base) as i32),+ );+ let mut places = Vec::new();+ convention::parameter_places(params, &mut places);+ // Argument slots are laid out like home slots, so a parameter's slot is the same in both.+ for (index, place) in places.iter().enumerate() {+ match place {+ Place::Memory(slot) => {+ let offset = 8 * *slot as i32;+ copy(&mut asm, params[index], (arguments, offset), (SP, offset));+ }+ Place::Register(register) => {+ let slot = convention::home_slot(params, index);+ transfer(&mut asm, params[index], *register, arguments, 8 * slot as i32, true);+ }+ }+ }+ let parameter_slots = convention::slots(params) as i32;+ if convention::has_result_area(results) {+ let pointer = 8 * parameter_slots;+ asm.add_any(Gpr(9), SP, i64::from(pointer + 8), X17);+ let operand = operand(&mut asm, SP, pointer, 3);+ asm.str(Width::W64, Gpr(9), operand);+ }+ asm.blr(entry);+ // NB: Tail calls may have moved sp.+ asm.mov_imm(Width::W64, X16, state as u64);+ asm.ldr(Width::W64, X17, MemOperand::Offset(X16, ENTRY_SP_OFFSET));+ asm.mov_sp(SP, X17);+ let results_pointer = Gpr(19);+ asm.ldr(Width::W64, results_pointer, MemOperand::Offset(SP, 0));+ asm.add_any(SP, SP, -outgoing, X17);+ convention::result_places(results, &mut places);+ for (index, place) in places.iter().enumerate() {+ let slot = convention::home_slot(results, index) as i32;+ match place {+ Place::Register(register) => {+ transfer(&mut asm, results[index], *register, results_pointer, 8 * slot, false);+ }+ Place::Memory(area_slot) => {+ let area = 8 * (parameter_slots + 1) + 8 * *area_slot as i32;+ copy(&mut asm, results[index], (SP, area), (results_pointer, 8 * slot));+ }+ }+ }+ asm.add_any(SP, SP, outgoing, X17);+ restore_and_return(&mut asm, 0);+ asm.finish().unwrap()+}diff --git a/Libraries/LibWasm/JIT/tests/harness/mod.rs b/Libraries/LibWasm/JIT/tests/harness/mod.rsindex 59e1663e14f..8ff9bda170d 100644--- a/Libraries/LibWasm/JIT/tests/harness/mod.rs+++ b/Libraries/LibWasm/JIT/tests/harness/mod.rs@@ -12,14 +12,20 @@#![allow(dead_code)]+#[cfg(target_arch = "aarch64")]+mod aarch64;pub mod script;+#[cfg(target_arch = "x86_64")]+mod x86_64;++#[cfg(target_arch = "aarch64")]+use aarch64::{not_compiled_code, trampoline_code, trap_exit_code, trap_stub};+#[cfg(target_arch = "x86_64")]+use x86_64::{not_compiled_code, trampoline_code, trap_exit_code, trap_stub};use libwasm_engine::Module;use libwasm_engine::abi::{ExecutionContext, InstanceData};use libwasm_engine::runtime::{FunctionKind, InstanceAddress, Store, Value, helpers};-use libwasm_jit::asm::x86_64::{Assembler, Precision, VexMap, VexOpcode, VexOperand, VexPrefix};-use libwasm_jit::asm::{Address, Gpr, Width};-use libwasm_jit::convention::{self, Place};use libwasm_jit::ir::Type;use libwasm_jit::{CompileContext, CompileFailure, CompileRequest, Options, RuntimeInfo};use std::cell::RefCell;@@ -49,7 +55,7 @@ pub const TRAP_NOT_COMPILED: u32 = 100;/// Where the trap exit leaves the trampoline's stack pointer and the trap code.#[repr(C)]-struct SessionState {+pub(crate) struct SessionState {entry_sp: u64,trap: u32,}@@ -59,9 +65,6 @@ const TRAP_OFFSET: i32 = offset_of!(SessionState, trap) as i32;const CODE_SPACE_SIZE: usize = 1 << 30;-const VMOVUPS_LOAD: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x10);-const VMOVUPS_STORE: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x11);-/// Executable memory, reserved up front. Code is added in batches, which are written while their pages are not/// executable.pub struct CodeSpace {@@ -70,7 +73,9 @@ pub struct CodeSpace {used: usize,}-const PAGE_SIZE: usize = 4096;+fn page_size() -> usize {+ unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }+}impl CodeSpace {fn new(size: usize) -> Self {@@ -94,7 +99,8 @@ impl CodeSpace {/// Copies each piece of code in and returns their addresses.fn add(&mut self, codes: &[&[u8]]) -> Vec<u64> {- let first_page = self.used / PAGE_SIZE * PAGE_SIZE;+ let page_size = page_size();+ let first_page = self.used / page_size * page_size;let mut end = self.used;let mut starts = Vec::with_capacity(codes.len());for code in codes {@@ -103,7 +109,7 @@ impl CodeSpace {end = start + code.len();}assert!(end <= self.size, "the code space is full");- let pages = end.next_multiple_of(PAGE_SIZE) - first_page;+ let pages = end.next_multiple_of(page_size) - first_page;if pages == 0 {return starts.iter().map(|start| self.base as u64 + *start as u64).collect();}@@ -116,7 +122,7 @@ impl CodeSpace {for (code, start) in codes.iter().zip(&starts) {std::ptr::copy_nonoverlapping(code.as_ptr(), self.base.add(*start), code.len());}- __clear_cache(region.cast(), region.add(pages).cast());+ libwasm_jit::runtime::flush_instruction_cache(region as usize, pages);assert_eq!(libc::mprotect(region.cast(), pages, libc::PROT_READ | libc::PROT_EXEC),0@@ -136,32 +142,6 @@ impl Drop for CodeSpace {// The code spaces that exist, for the fault handler. Tests run on several threads.static CODE_RANGES: std::sync::Mutex<Vec<(u64, u64)>> = std::sync::Mutex::new(Vec::new());-/// The trap exit, entered with the trap code in edi: returns 1 from the trampoline.-fn trap_exit_code(state: *mut SessionState) -> Vec<u8> {- let mut asm = Assembler::new();- let rax = Gpr(convention::RAX);- let sp = Gpr(convention::RSP);- asm.mov_ri(rax, state as u64);- asm.mov_mr(Width::W32, &Address::new(rax, TRAP_OFFSET), Gpr(convention::RDI));- asm.mov_rm(Width::W64, sp, &Address::new(rax, ENTRY_SP_OFFSET));- restore_and_return(&mut asm, 1);- asm.finish().unwrap()-}--/// The code of functions the JIT did not compile.-fn not_compiled_code(trap_exit: u64) -> Vec<u8> {- trap_stub(trap_exit, TRAP_NOT_COMPILED)-}--/// Code that traps with `code`.-fn trap_stub(trap_exit: u64, code: u32) -> Vec<u8> {- let mut asm = Assembler::new();- asm.mov_ri32(Gpr(convention::RDI), code);- asm.mov_ri(Gpr(convention::R11), trap_exit);- asm.jmp_r(Gpr(convention::R11));- asm.finish().unwrap()-}-/// `RuntimeInfo::throw` of the harness: unwinds the exception in `arguments[0]` from the compiled frame whose fp is/// `arguments[1]` to the first exception site its callers return to. An exception that leaves compiled code traps with/// TRAP_UNCAUGHT_EXCEPTION, as host functions that throw do here.@@ -194,151 +174,6 @@ unsafe extern "C" fn throw(context: *mut ExecutionContext) -> u64 {}}-fn restore_and_return(asm: &mut Assembler, status: u32) {- asm.add_ri(Width::W64, Gpr(convention::RSP), 8);- for register in [- convention::R15,- convention::R14,- convention::R13,- convention::R12,- convention::RBX,- convention::RBP,- ] {- asm.pop(Gpr(register));- }- asm.mov_ri32(Gpr(convention::RAX), status);- asm.ret();-}--/// `extern "C" fn(entry, arguments, results, instance) -> u32`: calls `entry` with the arguments' slots under the-/// compiled convention, stores the results' slots, and returns 0, or 1 if the code trapped.-fn trampoline_code(params: &[Type], results: &[Type], state: *mut SessionState) -> Vec<u8> {- let mut asm = Assembler::new();- let g = Gpr;- let (rdi, rsi, rdx, rcx) = (- g(convention::RDI),- g(convention::RSI),- g(convention::RDX),- g(convention::RCX),- );- let sp = g(convention::RSP);- let scratch = g(convention::R11);- for register in [- convention::RBP,- convention::RBX,- convention::R12,- convention::R13,- convention::R14,- convention::R15,- ] {- asm.push(g(register));- }- asm.sub_ri(Width::W64, sp, 8);- asm.mov_mr(Width::W64, &Address::new(sp, 0), rdx);- asm.mov_ri(scratch, state as u64);- asm.mov_mr(Width::W64, &Address::new(scratch, ENTRY_SP_OFFSET), sp);- let outgoing = convention::outgoing_size(params, results).next_multiple_of(16) as i32;- if outgoing > 0 {- asm.sub_ri(Width::W64, sp, outgoing);- }- let entry = g(convention::R10);- asm.mov_rr(Width::W64, entry, rdi);- asm.mov_rr(Width::W64, scratch, rsi);- asm.mov_rr(Width::W64, g(convention::INSTANCE_REGISTER), rcx);- asm.mov_rm(- Width::W64,- g(convention::MEMORY_BASE_REGISTER),- &Address::new(rcx, offset_of!(InstanceData, memory0_base) as i32),- );- // Copies the 8 or 16 bytes of a value of type `ty` between memory locations, through xmm15.- let copy = |asm: &mut Assembler, ty: Type, from: Address, to: Address| {- if ty == Type::V128 {- asm.vex(VMOVUPS_LOAD, 15, 0, VexOperand::Memory(from), None);- asm.vex(VMOVUPS_STORE, 15, 0, VexOperand::Memory(to), None);- } else {- asm.vmovs_rm(Precision::Double, libwasm_jit::asm::Fpr(15), &from);- asm.vmovs_mr(Precision::Double, &to, libwasm_jit::asm::Fpr(15));- }- };- // Loads or stores a value of type `ty` in `register` (true) at `address`.- let transfer = |asm: &mut Assembler, ty: Type, register: u8, address: Address, load: bool| {- if ty == Type::V128 {- let opcode = if load { VMOVUPS_LOAD } else { VMOVUPS_STORE };- asm.vex(- opcode,- register - convention::FPR_BASE,- 0,- VexOperand::Memory(address),- None,- );- } else if convention::is_fpr(register) {- let register = libwasm_jit::asm::Fpr(register - convention::FPR_BASE);- if load {- asm.vmovs_rm(Precision::Double, register, &address);- } else {- asm.vmovs_mr(Precision::Double, &address, register);- }- } else if load {- asm.mov_rm(Width::W64, g(register), &address);- } else {- asm.mov_mr(Width::W64, &address, g(register));- }- };- let mut places = Vec::new();- convention::parameter_places(params, &mut places);- // Stack arguments first, then registers, so that rsi and the others are read before they are written. Argument- // slots are laid out like home slots, so a parameter's slot is the same in both.- for (index, place) in places.iter().enumerate() {- if let Place::Memory(slot) = place {- let from = Address::new(scratch, 8 * *slot as i32);- copy(&mut asm, params[index], from, Address::new(sp, 8 * *slot as i32));- }- }- for (index, place) in places.iter().enumerate() {- if let Place::Register(register) = place {- let slot = convention::home_slot(params, index);- transfer(- &mut asm,- params[index],- *register,- Address::new(scratch, 8 * slot as i32),- true,- );- }- }- let parameter_slots = convention::slots(params) as i32;- if convention::has_result_area(results) {- let pointer = 8 * parameter_slots;- asm.lea(Width::W64, g(convention::RAX), &Address::new(sp, pointer + 8));- asm.mov_mr(Width::W64, &Address::new(sp, pointer), g(convention::RAX));- }- asm.call_r(entry);- // NB: Tail calls may have moved rsp.- asm.mov_ri(scratch, state as u64);- asm.mov_rm(Width::W64, sp, &Address::new(scratch, ENTRY_SP_OFFSET));- if outgoing > 0 {- asm.sub_ri(Width::W64, sp, outgoing);- }- asm.mov_rm(Width::W64, scratch, &Address::new(sp, outgoing));- convention::result_places(results, &mut places);- for (index, place) in places.iter().enumerate() {- let slot = convention::home_slot(results, index);- let address = Address::new(scratch, 8 * slot as i32);- match place {- Place::Register(register) => transfer(&mut asm, results[index], *register, address, false),- Place::Memory(slot) => {- let area = 8 * (parameter_slots + 1) + 8 * *slot as i32;- copy(&mut asm, results[index], Address::new(sp, area), address);- }- }- }- if outgoing > 0 {- asm.add_ri(Width::W64, sp, outgoing);- }- restore_and_return(&mut asm, 0);- asm.finish().unwrap()-}-fn ir_types(types: &[libwasm_engine::types::ValType]) -> Option<Vec<Type>> {types.iter().map(|ty| libwasm_jit::builder::ir_type(*ty)).collect()}@@ -446,10 +281,6 @@ pub struct CompiledModule {pub runnable: Vec<bool>,}-unsafe extern "C" {- fn __clear_cache(start: *mut libc::c_char, end: *mut libc::c_char);-}-impl CompiledModule {pub fn compile(module: Arc<Module>, options: Options) -> Self {let runtime = with_session(|session| session.runtime);@@ -550,6 +381,15 @@ pub enum Outcome {Trap(u32),}+#[cfg(target_os = "macos")]+fn lowest_stack_address() -> u64 {+ unsafe {+ let thread = libc::pthread_self();+ (libc::pthread_get_stackaddr_np(thread) as usize - libc::pthread_get_stacksize_np(thread)) as u64+ }+}++#[cfg(not(target_os = "macos"))]fn lowest_stack_address() -> u64 {unsafe {let mut attributes: libc::pthread_attr_t = std::mem::zeroed();@@ -655,11 +495,41 @@ pub fn function_index(static INSTALL: std::sync::Once = std::sync::Once::new();static mut PREVIOUS: libc::sigaction = unsafe { std::mem::zeroed() };+static mut PREVIOUS_SIGBUS: libc::sigaction = unsafe { std::mem::zeroed() };++/// The program counter of a signal handler's context, and the register the trap exit takes the trap code in.+#[cfg(target_arch = "x86_64")]+unsafe fn fault_registers(context: *mut libc::ucontext_t) -> (*mut u64, *mut u64) {+ unsafe {+ let registers = &raw mut (*context).uc_mcontext.gregs;+ (+ (&raw mut (*registers)[libc::REG_RIP as usize]).cast(),+ (&raw mut (*registers)[libc::REG_RDI as usize]).cast(),+ )+ }+}++#[cfg(all(target_arch = "aarch64", target_os = "linux"))]+unsafe fn fault_registers(context: *mut libc::ucontext_t) -> (*mut u64, *mut u64) {+ unsafe {+ let mcontext = &raw mut (*context).uc_mcontext;+ ((&raw mut (*mcontext).pc), (&raw mut (*mcontext).regs[0]))+ }+}++#[cfg(all(target_arch = "aarch64", target_os = "macos"))]+unsafe fn fault_registers(context: *mut libc::ucontext_t) -> (*mut u64, *mut u64) {+ unsafe {+ let state = &raw mut (*(*context).uc_mcontext).__ss;+ ((&raw mut (*state).__pc), (&raw mut (*state).__x[0]))+ }+}extern "C" fn handle_fault(signal: i32, info: *mut libc::siginfo_t, context: *mut libc::c_void) {unsafe {let context = context.cast::<libc::ucontext_t>();- let pc = (*context).uc_mcontext.gregs[libc::REG_RIP as usize] as u64;+ let (pc_register, code_register) = fault_registers(context);+ let pc = *pc_register;let address = (*info).si_addr() as usize;let exit = CODE_RANGES.try_lock().ok().and_then(|ranges| {ranges@@ -671,12 +541,15 @@ extern "C" fn handle_fault(signal: i32, info: *mut libc::siginfo_t, context: *mu&& libwasm_engine::runtime::memory::is_in_any_reservation(address){// Every code space starts with its trap exit.- (*context).uc_mcontext.gregs[libc::REG_RIP as usize] = start as i64;- (*context).uc_mcontext.gregs[libc::REG_RDI as usize] =- i64::from(libwasm_engine::abi::TRAP_MEMORY_OUT_OF_BOUNDS);+ *pc_register = start;+ *code_register = u64::from(libwasm_engine::abi::TRAP_MEMORY_OUT_OF_BOUNDS);return;}- let previous = std::ptr::read(&raw const PREVIOUS);+ let previous = if signal == libc::SIGSEGV {+ std::ptr::read(&raw const PREVIOUS)+ } else {+ std::ptr::read(&raw const PREVIOUS_SIGBUS)+ };if previous.sa_flags & libc::SA_SIGINFO != 0 && previous.sa_sigaction > libc::SIG_IGN {let handler: extern "C" fn(i32, *mut libc::siginfo_t, *mut libc::c_void) =std::mem::transmute(previous.sa_sigaction);@@ -695,5 +568,7 @@ fn install_fault_handler() {action.sa_flags = libc::SA_SIGINFO | libc::SA_ONSTACK;libc::sigemptyset(&raw mut action.sa_mask);libc::sigaction(libc::SIGSEGV, &raw const action, &raw mut PREVIOUS);+ // NB: Accesses of the guard pages raise SIGBUS on macOS.+ libc::sigaction(libc::SIGBUS, &raw const action, &raw mut PREVIOUS_SIGBUS);});}diff --git a/Libraries/LibWasm/JIT/tests/harness/x86_64.rs b/Libraries/LibWasm/JIT/tests/harness/x86_64.rsnew file mode 100644index 00000000000..a9da2b5bda4--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/harness/x86_64.rs@@ -0,0 +1,189 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The harness's code on x86-64: the trap exit, the stub of functions that did not compile, and the trampolines.++use super::{ENTRY_SP_OFFSET, SessionState, TRAP_NOT_COMPILED, TRAP_OFFSET};+use libwasm_engine::abi::InstanceData;+use libwasm_jit::asm::x86_64::{Assembler, Precision, VexMap, VexOpcode, VexOperand, VexPrefix};+use libwasm_jit::asm::{Address, Gpr, Width};+use libwasm_jit::convention::{self, Place};+use libwasm_jit::ir::Type;+use std::mem::offset_of;++const VMOVUPS_LOAD: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x10);+const VMOVUPS_STORE: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x11);++/// The trap exit, entered with the trap code in edi: returns 1 from the trampoline.+pub(super) fn trap_exit_code(state: *mut SessionState) -> Vec<u8> {+ let mut asm = Assembler::new();+ let rax = Gpr(convention::RAX);+ let sp = Gpr(convention::RSP);+ asm.mov_ri(rax, state as u64);+ asm.mov_mr(Width::W32, &Address::new(rax, TRAP_OFFSET), Gpr(convention::RDI));+ asm.mov_rm(Width::W64, sp, &Address::new(rax, ENTRY_SP_OFFSET));+ restore_and_return(&mut asm, 1);+ asm.finish().unwrap()+}++/// The code of functions the JIT did not compile.+pub(super) fn not_compiled_code(trap_exit: u64) -> Vec<u8> {+ trap_stub(trap_exit, TRAP_NOT_COMPILED)+}++/// Code that traps with `code`.+pub(super) fn trap_stub(trap_exit: u64, code: u32) -> Vec<u8> {+ let mut asm = Assembler::new();+ asm.mov_ri32(Gpr(convention::RDI), code);+ asm.mov_ri(Gpr(convention::R11), trap_exit);+ asm.jmp_r(Gpr(convention::R11));+ asm.finish().unwrap()+}++fn restore_and_return(asm: &mut Assembler, status: u32) {+ asm.add_ri(Width::W64, Gpr(convention::RSP), 8);+ for register in [+ convention::R15,+ convention::R14,+ convention::R13,+ convention::R12,+ convention::RBX,+ convention::RBP,+ ] {+ asm.pop(Gpr(register));+ }+ asm.mov_ri32(Gpr(convention::RAX), status);+ asm.ret();+}++/// `extern "C" fn(entry, arguments, results, instance) -> u32`: calls `entry` with the arguments' slots under the+/// compiled convention, stores the results' slots, and returns 0, or 1 if the code trapped.+pub(super) fn trampoline_code(params: &[Type], results: &[Type], state: *mut SessionState) -> Vec<u8> {+ let mut asm = Assembler::new();+ let g = Gpr;+ let (rdi, rsi, rdx, rcx) = (+ g(convention::RDI),+ g(convention::RSI),+ g(convention::RDX),+ g(convention::RCX),+ );+ let sp = g(convention::RSP);+ let scratch = g(convention::R11);+ for register in [+ convention::RBP,+ convention::RBX,+ convention::R12,+ convention::R13,+ convention::R14,+ convention::R15,+ ] {+ asm.push(g(register));+ }+ asm.sub_ri(Width::W64, sp, 8);+ asm.mov_mr(Width::W64, &Address::new(sp, 0), rdx);+ asm.mov_ri(scratch, state as u64);+ asm.mov_mr(Width::W64, &Address::new(scratch, ENTRY_SP_OFFSET), sp);+ let outgoing = convention::outgoing_size(params, results).next_multiple_of(16) as i32;+ if outgoing > 0 {+ asm.sub_ri(Width::W64, sp, outgoing);+ }+ let entry = g(convention::R10);+ asm.mov_rr(Width::W64, entry, rdi);+ asm.mov_rr(Width::W64, scratch, rsi);+ asm.mov_rr(Width::W64, g(convention::INSTANCE_REGISTER), rcx);+ asm.mov_rm(+ Width::W64,+ g(convention::MEMORY_BASE_REGISTER),+ &Address::new(rcx, offset_of!(InstanceData, memory0_base) as i32),+ );+ // Copies the 8 or 16 bytes of a value of type `ty` between memory locations, through xmm15.+ let copy = |asm: &mut Assembler, ty: Type, from: Address, to: Address| {+ if ty == Type::V128 {+ asm.vex(VMOVUPS_LOAD, 15, 0, VexOperand::Memory(from), None);+ asm.vex(VMOVUPS_STORE, 15, 0, VexOperand::Memory(to), None);+ } else {+ asm.vmovs_rm(Precision::Double, libwasm_jit::asm::Fpr(15), &from);+ asm.vmovs_mr(Precision::Double, &to, libwasm_jit::asm::Fpr(15));+ }+ };+ // Loads or stores a value of type `ty` in `register` (true) at `address`.+ let transfer = |asm: &mut Assembler, ty: Type, register: u8, address: Address, load: bool| {+ if ty == Type::V128 {+ let opcode = if load { VMOVUPS_LOAD } else { VMOVUPS_STORE };+ asm.vex(+ opcode,+ register - convention::FPR_BASE,+ 0,+ VexOperand::Memory(address),+ None,+ );+ } else if convention::is_fpr(register) {+ let register = libwasm_jit::asm::Fpr(register - convention::FPR_BASE);+ if load {+ asm.vmovs_rm(Precision::Double, register, &address);+ } else {+ asm.vmovs_mr(Precision::Double, &address, register);+ }+ } else if load {+ asm.mov_rm(Width::W64, g(register), &address);+ } else {+ asm.mov_mr(Width::W64, &address, g(register));+ }+ };+ let mut places = Vec::new();+ convention::parameter_places(params, &mut places);+ // Stack arguments first, then registers, so that rsi and the others are read before they are written. Argument+ // slots are laid out like home slots, so a parameter's slot is the same in both.+ for (index, place) in places.iter().enumerate() {+ if let Place::Memory(slot) = place {+ let from = Address::new(scratch, 8 * *slot as i32);+ copy(&mut asm, params[index], from, Address::new(sp, 8 * *slot as i32));+ }+ }+ for (index, place) in places.iter().enumerate() {+ if let Place::Register(register) = place {+ let slot = convention::home_slot(params, index);+ transfer(+ &mut asm,+ params[index],+ *register,+ Address::new(scratch, 8 * slot as i32),+ true,+ );+ }+ }+ let parameter_slots = convention::slots(params) as i32;+ if convention::has_result_area(results) {+ let pointer = 8 * parameter_slots;+ asm.lea(Width::W64, g(convention::RAX), &Address::new(sp, pointer + 8));+ asm.mov_mr(Width::W64, &Address::new(sp, pointer), g(convention::RAX));+ }+ asm.call_r(entry);+ // NB: Tail calls may have moved rsp.+ asm.mov_ri(scratch, state as u64);+ asm.mov_rm(Width::W64, sp, &Address::new(scratch, ENTRY_SP_OFFSET));+ if outgoing > 0 {+ asm.sub_ri(Width::W64, sp, outgoing);+ }+ asm.mov_rm(Width::W64, scratch, &Address::new(sp, outgoing));+ convention::result_places(results, &mut places);+ for (index, place) in places.iter().enumerate() {+ let slot = convention::home_slot(results, index);+ let address = Address::new(scratch, 8 * slot as i32);+ match place {+ Place::Register(register) => transfer(&mut asm, results[index], *register, address, false),+ Place::Memory(slot) => {+ let area = 8 * (parameter_slots + 1) + 8 * *slot as i32;+ copy(&mut asm, results[index], Address::new(sp, area), address);+ }+ }+ }+ if outgoing > 0 {+ asm.add_ri(Width::W64, sp, outgoing);+ }+ restore_and_return(&mut asm, 0);+ asm.finish().unwrap()+}