Truly independent web browser
LibJS+LibWasm: Keep JIT compilation available on x86-64-v2 CPUs
Andreas Kling35e4ad0b7b24
diff --git a/Documentation/AdvancedBuildInstructions.md b/Documentation/AdvancedBuildInstructions.mdindex 8f53188cb3e..abbcc1ac2f4 100644--- a/Documentation/AdvancedBuildInstructions.md+++ b/Documentation/AdvancedBuildInstructions.md@@ -31,6 +31,7 @@ There are some optional features that can be enabled during compilation that are- `ENABLE_ALL_THE_DEBUG_MACROS`: used for checking whether debug code compiles on CI. This should not be set normally, as it clutters the console output and makes the system run very slowly. Instead, enable only the needed debug macros, as described below.- `ENABLE_COMPILETIME_FORMAT_CHECK`: checks for the validity of `std::format`-style format string during compilation. Enabled by default.- `ENABLE_JS_JIT`: builds the optimizing JIT for JavaScript. Enabled by default on x86-64 and AArch64 Linux and macOS, the platforms it generates code for. Without it, LibJS runs JavaScript in its interpreter alone, and the interpreter is built without the feedback collection and tier-up checks that only the JIT needs. See [the configuration of the JIT](../Libraries/LibJS/JIT/ARCHITECTURE.md#13-configuration).+- `ENABLE_CI_BASELINE_CPU`: builds C++ and Rust for a common CPU target instead of the build machine. Disabled by default; explicitly set `-DENABLE_CI_BASELINE_CPU=ON` when packaging binaries for older machines. On x86-64 this is x86-64-v2 (SSE4.2 and POPCNT), so distributed binaries run without AVX, AVX2, BMI or LZCNT. Both the JavaScript and WebAssembly JITs remain available; WebAssembly selects newer instructions at runtime when supported.- `INCLUDE_WASM_SPEC_TESTS`: downloads and includes the WebAssembly spec testsuite tests. In order to use this option, you will need to install `prettier` and `wasm-tools`.- `INCLUDE_FLAC_SPEC_TESTS`: downloads and includes the xiph.org FLAC test suite.- `LADYBIRD_CACHE_DIR`: sets the location of a shared cache of downloaded files. Should not need to be set manually unless managing a distribution package.diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rsindex ac2d53c0042..4bc568102c9 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rs@@ -4,13 +4,14 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! Encoders of the x86-64-v3 instructions the WebAssembly JIT uses beyond what LibJS needs: VEX three-operand+//! Encoders of the instructions the WebAssembly JIT uses beyond what LibJS needs: VEX three-operand//! scalar float arithmetic for f32 and f64, rounding and conversions, bitwise operations on xmm registers, BMI1 and//! BMI2 (`andn`, `shlx`, `sarx`, `shrx`, `rorx`), bit counting (`lzcnt`, `tzcnt`, `popcnt`) and unsigned division,//! and `vex()`, which encodes any VEX instruction from its opcode, for the vector instructions.//!//! VEX instructions with a scalar operand ignore VEX.L (they are LIG); this file encodes them with L = 0, like the//! 128-bit forms.+//! With `Assembler::for_host`, SIMD, rotations and bit counts select SSE and bit-scan fallbacks as needed.use super::super::Address;use super::super::Fpr;@@ -141,7 +142,7 @@ impl Assembler {/// Emits a VEX prefix and opcode with ModRM for `reg`, the extra source `vvvv` and `rm`, using the two-byte form/// where it can.#[allow(clippy::too_many_arguments)]- fn vex_instruction(+ pub(super) fn vex_instruction(&mut self,prefix: VexPrefix,map: VexMap,@@ -177,7 +178,12 @@ impl Assembler {/// Emits the VEX instruction `opcode` with `reg` in ModRM.reg, `vvvv` as the extra source (0 where the/// instruction has none), `rm` and an immediate byte. Registers are by their encoding, whatever their class.+ /// With host instruction selection, the Wasm SIMD subset uses equivalent SSE sequences without AVX2.pub fn vex(&mut self, opcode: VexOpcode, reg: u8, vvvv: u8, rm: VexOperand, immediate: Option<u8>) {+ if !self.cpu_features().avx2 {+ self.legacy_vector(opcode, reg, vvvv, rm, immediate);+ return;+ }let rm = match rm {VexOperand::Register(register) => Rm::Reg(register),VexOperand::Memory(address) => Rm::Mem(address),@@ -207,7 +213,7 @@ impl Assembler {/// `vaddss`/`vsubss`/... `dst, lhs, rhs` (and the `sd` forms). The bits above the scalar come from `lhs`.pub fn vfloat_rrr(&mut self, op: FloatOp, precision: Precision, dst: Fpr, lhs: Fpr, rhs: Fpr) {- self.vex_instruction(+ self.simd_instruction(precision.scalar_prefix(),VexMap::Map0F,false,@@ -221,7 +227,7 @@ impl Assembler {/// `vaddss`/`vsubss`/... `dst, lhs, [address]` (and the `sd` forms).pub fn vfloat_rrm(&mut self, op: FloatOp, precision: Precision, dst: Fpr, lhs: Fpr, address: &Address) {- self.vex_instruction(+ self.simd_instruction(precision.scalar_prefix(),VexMap::Map0F,false,@@ -244,7 +250,7 @@ impl Assembler {Precision::Single => 0x0a,Precision::Double => 0x0b,};- self.vex_instruction(+ self.simd_instruction(VexPrefix::OperandSize,VexMap::Map0F3A,false,@@ -259,7 +265,7 @@ impl Assembler {/// `vandps`/`vandnps`/`vorps`/`vxorps dst, lhs, rhs` on all 128 bits. `AndNot` computes `!lhs & rhs`.pub fn vbitwise_rrr(&mut self, op: BitwiseOp, dst: Fpr, lhs: Fpr, rhs: Fpr) {- self.vex_instruction(+ self.simd_instruction(VexPrefix::None,VexMap::Map0F,false,@@ -273,7 +279,7 @@ impl Assembler {/// `vandps`/... `dst, lhs, xmmword [rip + label]`.pub fn vbitwise_r_label(&mut self, op: BitwiseOp, dst: Fpr, lhs: Fpr, label: Label) {- self.vex_instruction(+ self.simd_instruction(VexPrefix::None,VexMap::Map0F,false,@@ -287,7 +293,7 @@ impl Assembler {/// `vmovaps dst, src`.pub fn vmovaps_rr(&mut self, dst: Fpr, src: Fpr) {- self.vex_instruction(VexPrefix::None, VexMap::Map0F, false, 0x28, dst.0, 0, Rm::Reg(src.0), 0);+ self.simd_instruction(VexPrefix::None, VexMap::Map0F, false, 0x28, dst.0, 0, Rm::Reg(src.0), 0);}/// `vucomiss`/`vucomisd lhs, rhs`: ZF/PF/CF = unordered 111, less 001, equal 100, greater 000.@@ -296,14 +302,14 @@ impl Assembler {Precision::Single => VexPrefix::None,Precision::Double => VexPrefix::OperandSize,};- self.vex_instruction(prefix, VexMap::Map0F, false, 0x2e, lhs.0, 0, Rm::Reg(rhs.0), 0);+ self.simd_instruction(prefix, VexMap::Map0F, false, 0x2e, lhs.0, 0, Rm::Reg(rhs.0), 0);}// Loads and stores./// `vmovss`/`vmovsd dst, [address]`, zeroing the bits above the scalar.pub fn vmovs_rm(&mut self, precision: Precision, dst: Fpr, address: &Address) {- self.vex_instruction(+ self.simd_instruction(precision.scalar_prefix(),VexMap::Map0F,false,@@ -317,7 +323,7 @@ impl Assembler {/// `vmovss`/`vmovsd [address], src`.pub fn vmovs_mr(&mut self, precision: Precision, address: &Address, src: Fpr) {- self.vex_instruction(+ self.simd_instruction(precision.scalar_prefix(),VexMap::Map0F,false,@@ -331,7 +337,7 @@ impl Assembler {/// `vmovss`/`vmovsd dst, [rip + label]`.pub fn vmovs_r_label(&mut self, precision: Precision, dst: Fpr, label: Label) {- self.vex_instruction(+ self.simd_instruction(precision.scalar_prefix(),VexMap::Map0F,false,@@ -347,7 +353,7 @@ impl Assembler {/// `vmovd xmm, r32` or `vmovq xmm, r64`, zeroing the rest of the register.pub fn vmov_xr(&mut self, width: Width, dst: Fpr, src: Gpr) {- self.vex_instruction(+ self.simd_instruction(VexPrefix::OperandSize,VexMap::Map0F,width == Width::W64,@@ -361,7 +367,7 @@ impl Assembler {/// `vmovd r32, xmm` or `vmovq r64, xmm`.pub fn vmov_rx(&mut self, width: Width, dst: Gpr, src: Fpr) {- self.vex_instruction(+ self.simd_instruction(VexPrefix::OperandSize,VexMap::Map0F,width == Width::W64,@@ -378,7 +384,7 @@ impl Assembler {/// `vcvtsi2ss`/`vcvtsi2sd dst, upper, r32/r64`: the signed integer as a float, with the bits above the scalar/// from `upper`.pub fn vcvtsi2s(&mut self, precision: Precision, width: Width, dst: Fpr, upper: Fpr, src: Gpr) {- self.vex_instruction(+ self.simd_instruction(precision.scalar_prefix(),VexMap::Map0F,width == Width::W64,@@ -393,7 +399,7 @@ impl Assembler {/// `vcvttss2si`/`vcvttsd2si r32/r64, src`: truncates toward zero. Produces the "integer indefinite" value (only/// the sign bit set) for NaN and out of range inputs.pub fn vcvtts2si(&mut self, precision: Precision, width: Width, dst: Gpr, src: Fpr) {- self.vex_instruction(+ self.simd_instruction(precision.scalar_prefix(),VexMap::Map0F,width == Width::W64,@@ -407,7 +413,7 @@ impl Assembler {/// `vcvtss2sd dst, upper, src`: widens a float to a double.pub fn vcvtss2sd(&mut self, dst: Fpr, upper: Fpr, src: Fpr) {- self.vex_instruction(+ self.simd_instruction(VexPrefix::Rep,VexMap::Map0F,false,@@ -421,7 +427,7 @@ impl Assembler {/// `vcvtsd2ss dst, upper, src`: rounds a double to a float.pub fn vcvtsd2ss(&mut self, dst: Fpr, upper: Fpr, src: Fpr) {- self.vex_instruction(+ self.simd_instruction(VexPrefix::Repne,VexMap::Map0F,false,@@ -437,6 +443,11 @@ impl Assembler {/// `lzcnt`/`tzcnt`/`popcnt dst, src`.pub fn bit_count(&mut self, op: BitCount, width: Width, dst: Gpr, src: Gpr) {+ let features = self.cpu_features();+ if (op == BitCount::Lzcnt && !features.lzcnt) || (op == BitCount::Tzcnt && !features.bmi1) {+ self.count_zeros(op, width, dst, src);+ return;+ }self.emit_instruction(Prefix::Rep,width == Width::W64,@@ -480,8 +491,13 @@ impl Assembler {);}- /// `rorx dst, src, amount`: rotates right by an immediate, leaving the flags alone.+ /// `rorx dst, src, amount`: rotates right by an immediate. Without BMI2, uses MOV and ROR, clobbering flags.pub fn rorx(&mut self, width: Width, dst: Gpr, src: Gpr, amount: u8) {+ if !self.cpu_features().bmi2 {+ self.mov_rr(width, dst, src);+ self.shift_ri(super::ShiftOp::Ror, width, dst, amount);+ return;+ }self.vex_instruction(VexPrefix::Repne,VexMap::Map0F3A,diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rsindex bb49f1de72c..d764e57eff0 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs@@ -8,6 +8,7 @@mod extended;mod macro_assembler;+mod sse;#[cfg(test)]mod tests;@@ -22,6 +23,7 @@ pub use extended::VexOpcode;pub use extended::VexOperand;pub use extended::VexPrefix;pub use macro_assembler::MacroAssembler;+pub use sse::CpuFeatures;use super::Address;use super::Fpr;@@ -164,6 +166,8 @@ enum Prefix {#[derive(Debug, Default)]pub struct Assembler {buffer: CodeBuffer,+ /// None for a raw instruction encoder; host code generation selects the CPU's optional instructions.+ cpu_features: Option<CpuFeatures>,/// Whether a group of instructions that ends in a branch is being emitted (see `BranchGroups::branch_group()`), whose/// branches leave keeping it within a branch window to the group.in_branch_group: bool,@@ -216,6 +220,22 @@ impl Assembler {Self::default()}+ /// Selects AVX, AVX2, BMI and LZCNT only where the executing CPU supports them.+ pub fn for_host() -> Self {+ Self::with_cpu_features(CpuFeatures::host())+ }++ pub fn with_cpu_features(cpu_features: CpuFeatures) -> Self {+ Self {+ cpu_features: Some(cpu_features),+ ..Self::default()+ }+ }++ pub fn cpu_features(&self) -> CpuFeatures {+ self.cpu_features.unwrap_or(CpuFeatures::X86_64_V3)+ }+pub fn offset(&self) -> usize {self.buffer.offset()}diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/sse.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/sse.rsnew file mode 100644index 00000000000..c135b719d6f--- /dev/null+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/sse.rs@@ -0,0 +1,584 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Instruction selection for x86-64-v2 hosts. The raw encoder (`Assembler::new`) retains the requested encoding;+//! `Assembler::for_host` selects SSE sequences where AVX/AVX2 are unavailable. No YMM values are used by either JIT.++use super::{Assembler, BitCount, ByteRegisters, Cond, Fpr, Gpr, Prefix, Rm, VexMap, VexOpcode, VexOperand, VexPrefix};+use crate::asm::{Address, Width};++/// Optional instructions beyond the SSE4.2/POPCNT baseline. These are independent CPU features: AVX2 alone does+/// not imply BMI or LZCNT, and AVX detection must also account for OS support for saving the extended registers.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct CpuFeatures {+ pub avx: bool,+ pub avx2: bool,+ pub bmi1: bool,+ pub bmi2: bool,+ pub lzcnt: bool,+}++impl CpuFeatures {+ pub const X86_64_V2: Self = Self {+ avx: false,+ avx2: false,+ bmi1: false,+ bmi2: false,+ lzcnt: false,+ };+ pub const X86_64_V3: Self = Self {+ avx: true,+ avx2: true,+ bmi1: true,+ bmi2: true,+ lzcnt: true,+ };++ pub fn host() -> Self {+ #[cfg(target_arch = "x86_64")]+ {+ static FEATURES: std::sync::OnceLock<CpuFeatures> = std::sync::OnceLock::new();+ *FEATURES.get_or_init(|| Self {+ avx: std::arch::is_x86_feature_detected!("avx"),+ avx2: std::arch::is_x86_feature_detected!("avx2"),+ bmi1: std::arch::is_x86_feature_detected!("bmi1"),+ bmi2: std::arch::is_x86_feature_detected!("bmi2"),+ lzcnt: std::arch::is_x86_feature_detected!("lzcnt"),+ })+ }+ #[cfg(not(target_arch = "x86_64"))]+ Self::X86_64_V2+ }+}++impl VexOpcode {+ /// Only swap inputs whose complete results are identical in either order. Floating-point arithmetic may+ /// select a NaN payload by operand order, and scalar operations also copy upper lanes from the first input.+ fn has_commutative_inputs(self) -> bool {+ use VexMap::{Map0F, Map0F38};+ use VexPrefix::{None as NoPrefix, OperandSize as P66};+ matches!(+ (self.map, self.prefix, self.opcode),+ (Map0F, NoPrefix | P66, 0x54 | 0x56 | 0x57) // AND/OR/XORPS/PD+ | (Map0F, P66,+ 0xd4 | 0xfc..=0xfe // PADDQ/B/W/D+ | 0xdc | 0xdd | 0xec | 0xed // Saturating byte/word additions+ | 0xd5 | 0xe4 | 0xe5 | 0xf4 | 0xf5 // PMULLW/HUW/HW/UDQ, PMADDWD+ | 0xdb | 0xeb | 0xef // PAND/POR/PXOR+ )+ | (Map0F38, P66, 0x0b | 0x28 | 0x40) // PMULHRSW, PMULDQ, PMULLD+ )+ }+}++impl Assembler {+ /// Emit the legacy encoding with the same opcode map, mandatory prefix and operands as a VEX instruction.+ fn legacy(&mut self, opcode: VexOpcode, reg: u8, rm: Rm, immediate_size: usize) {+ let prefix = match opcode.prefix {+ VexPrefix::None => Prefix::None,+ VexPrefix::OperandSize => Prefix::OperandSize,+ VexPrefix::Rep => Prefix::Rep,+ VexPrefix::Repne => Prefix::Repne,+ };+ let bytes = [+ 0x0f,+ match opcode.map {+ VexMap::Map0F => 0,+ VexMap::Map0F38 => 0x38,+ VexMap::Map0F3A => 0x3a,+ },+ opcode.opcode,+ ];+ let short = [0x0f, opcode.opcode];+ let bytes = if opcode.map == VexMap::Map0F {+ &short[..]+ } else {+ &bytes[..]+ };+ self.emit_instruction(prefix, opcode.w, bytes, reg, rm, ByteRegisters::No, immediate_size);+ }++ /// SSE writes its first input. If the output aliases the second input, swap commutative inputs or preserve the+ /// second input in a temporary register, saving the temporary on the stack. Even the JIT's reserved scratch+ /// register may be an input here. LEA preserves flags, and MOVUPS works with any caller stack alignment.+ fn legacy_binary(&mut self, opcode: VexOpcode, dst: u8, mut lhs: u8, mut rhs: Rm, immediate: Option<u8>) {+ if rhs == Rm::Reg(dst) && dst != lhs && opcode.has_commutative_inputs() {+ rhs = Rm::Reg(lhs);+ lhs = dst;+ }+ let temporary = if rhs == Rm::Reg(dst) && dst != lhs {+ let temp = (0..16).find(|®| reg != dst && reg != lhs).unwrap();+ let sp = super::RSP;+ self.lea(Width::W64, sp, &Address::new(sp, -16));+ self.legacy(+ VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x11),+ temp,+ Rm::Mem(Address::new(sp, 0)),+ 0,+ );+ self.movapd_rr(Fpr(temp), Fpr(dst));+ Some(temp)+ } else {+ None+ };+ if dst != lhs {+ self.movapd_rr(Fpr(dst), Fpr(lhs));+ }+ self.legacy(+ opcode,+ dst,+ temporary.map_or(rhs, Rm::Reg),+ usize::from(immediate.is_some()),+ );+ if let Some(immediate) = immediate {+ self.buffer.emit_u8(immediate);+ }+ if let Some(temp) = temporary {+ let sp = super::RSP;+ self.legacy(+ VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x10),+ temp,+ Rm::Mem(Address::new(sp, 0)),+ 0,+ );+ self.lea(Width::W64, sp, &Address::new(sp, 16));+ }+ }++ /// Scalar AVX instructions all have SSE equivalents. Conversions from a GPR cannot alias an XMM input.+ #[allow(clippy::too_many_arguments)]+ pub(super) fn simd_instruction(+ &mut self,+ prefix: VexPrefix,+ map: VexMap,+ w: bool,+ opcode: u8,+ reg: u8,+ lhs: u8,+ rm: Rm,+ immediate_size: usize,+ ) {+ if self.cpu_features().avx {+ self.vex_instruction(prefix, map, w, opcode, reg, lhs, rm, immediate_size);+ return;+ }+ let opcode = VexOpcode { prefix, map, opcode, w };+ let merges = match (map, prefix, opcode.opcode) {+ (VexMap::Map0F, VexPrefix::Rep | VexPrefix::Repne, 0x2a) => {+ if reg != lhs {+ self.movapd_rr(Fpr(reg), Fpr(lhs));+ }+ false+ }+ (VexMap::Map0F, _, 0x51 | 0x54..=0x5f) | (VexMap::Map0F3A, _, 0x0a | 0x0b) => true,+ _ => false,+ };+ if merges {+ // The immediate, if any, is appended by the scalar emitter. It must be adjacent to the instruction,+ // before restoring a temporary, so handle rounding separately (its two sources are always identical).+ if immediate_size != 0 {+ debug_assert_eq!(rm, Rm::Reg(lhs));+ if reg != lhs {+ self.movapd_rr(Fpr(reg), Fpr(lhs));+ }+ self.legacy(opcode, reg, rm, immediate_size);+ } else {+ self.legacy_binary(opcode, reg, lhs, rm, None);+ }+ } else {+ self.legacy(opcode, reg, rm, immediate_size);+ }+ }++ pub(super) fn legacy_vector(+ &mut self,+ mut opcode: VexOpcode,+ reg: u8,+ lhs: u8,+ operand: VexOperand,+ mut immediate: Option<u8>,+ ) {+ use VexMap::{Map0F, Map0F3A, Map0F38};+ use VexPrefix::{None as NoPrefix, OperandSize as P66, Rep as PF3, Repne as PF2};+ let rm = match operand {+ VexOperand::Register(reg) => Rm::Reg(reg),+ VexOperand::Memory(address) => Rm::Mem(address),+ VexOperand::Label(label) => Rm::Rip(label),+ };+ let key = (opcode.map, opcode.prefix, opcode.opcode);+ match key {+ (Map0F38, P66, 0x18 | 0x58 | 0x59 | 0x78 | 0x79) => {+ self.broadcast(opcode.opcode, reg, rm);+ return;+ }+ (Map0F3A, P66, 0x02) => {+ // PBLENDW selects words; duplicate each of VPBLENDD's four lane bits.+ let mask = immediate.unwrap();+ immediate = Some((0..4).fold(0, |words, lane| words | ((((mask >> lane) & 1) * 3) << (2 * lane))));+ opcode.opcode = 0x0e;+ }+ (Map0F3A, P66, 0x04) => {+ // VPERMILPS with an immediate is PSHUFD on the same 128 bits.+ opcode.map = Map0F;+ opcode.opcode = 0x70;+ self.legacy(opcode, reg, rm, 1);+ self.buffer.emit_u8(immediate.unwrap());+ return;+ }+ (Map0F3A, P66, 0x05) => {+ // SHUFPD with both sources equal selects the same two lanes as VPERMILPD.+ let Rm::Reg(src) = rm else {+ panic!("VPERMILPD needs a register")+ };+ opcode.map = Map0F;+ opcode.opcode = 0xc6;+ self.legacy_binary(opcode, reg, src, rm, immediate);+ return;+ }+ (Map0F, P66, 0x71..=0x73) => {+ // VEX puts the destination in vvvv; SSE's group encoding puts it in r/m.+ let Rm::Reg(src) = rm else {+ panic!("immediate vector shift needs a register")+ };+ if lhs != src {+ self.movapd_rr(Fpr(lhs), Fpr(src));+ }+ self.legacy(opcode, reg, Rm::Reg(lhs), 1);+ self.buffer.emit_u8(immediate.unwrap());+ return;+ }+ (Map0F, P66, 0xc4) | (Map0F3A, P66, 0x20 | 0x22) => {+ // PINSR's second input is a GPR (or memory), not an XMM register.+ if reg != lhs {+ self.movapd_rr(Fpr(reg), Fpr(lhs));+ }+ self.legacy(opcode, reg, rm, 1);+ self.buffer.emit_u8(immediate.unwrap());+ return;+ }+ _ => {}+ }+ let unary = matches!(key,+ (Map0F, NoPrefix | P66, 0x10 | 0x11 | 0x28 | 0x2e | 0x50 | 0x51 | 0x5a | 0x5b)+ | (Map0F, P66, 0x6e | 0x7e | 0x70 | 0xd7 | 0xe6)+ | (Map0F, PF3, 0x7e | 0x5b | 0xe6)+ | (Map0F, PF2, 0x12 | 0xe6)+ | (Map0F38, P66, 0x17 | 0x1c..=0x1e | 0x20..=0x25 | 0x30..=0x35)+ | (Map0F3A, P66, 0x08 | 0x09 | 0x14..=0x17)+ ) || (key == (Map0F, PF2, 0x10) && !matches!(rm, Rm::Reg(_)));+ if unary {+ self.legacy(opcode, reg, rm, usize::from(immediate.is_some()));+ if let Some(immediate) = immediate {+ self.buffer.emit_u8(immediate);+ }+ } else {+ self.legacy_binary(opcode, reg, lhs, rm, immediate);+ }+ }++ /// Broadcasts use exact-width loads: a load8_splat at the end of a Wasm memory must only read one byte.+ fn broadcast(&mut self, opcode: u8, dst: u8, src: Rm) {+ use VexMap::{Map0F, Map0F3A};+ use VexPrefix::OperandSize as P66;+ let sse = |map, opcode| VexOpcode::new(P66, map, opcode);+ match src {+ Rm::Reg(src) => {+ if dst != src {+ self.movapd_rr(Fpr(dst), Fpr(src));+ }+ }+ _ => {+ let (load, immediate) = match opcode {+ 0x78 => (sse(Map0F3A, 0x20), Some(0)), // pinsrb+ 0x79 => (sse(Map0F, 0xc4), Some(0)), // pinsrw+ 0x59 => (VexOpcode::new(VexPrefix::Rep, Map0F, 0x7e), None), // movq+ _ => (sse(Map0F, 0x6e), None), // movd+ };+ self.legacy(load, dst, src, usize::from(immediate.is_some()));+ if let Some(immediate) = immediate {+ self.buffer.emit_u8(immediate);+ }+ }+ }+ if opcode == 0x78 {+ self.legacy(sse(Map0F, 0x60), dst, Rm::Reg(dst), 0); // punpcklbw+ }+ if matches!(opcode, 0x78 | 0x79) {+ self.legacy(sse(Map0F, 0x61), dst, Rm::Reg(dst), 0); // punpcklwd+ }+ if opcode == 0x59 {+ self.legacy(sse(Map0F, 0x6c), dst, Rm::Reg(dst), 0); // punpcklqdq+ } else {+ self.legacy(sse(Map0F, 0x70), dst, Rm::Reg(dst), 1); // pshufd+ self.buffer.emit_u8(0);+ }+ }++ pub(super) fn count_zeros(&mut self, op: BitCount, width: Width, dst: Gpr, src: Gpr) {+ let done = self.new_label();+ let zero = self.new_label();+ self.emit_instruction(+ Prefix::None,+ width == Width::W64,+ &[0x0f, op as u8],+ dst.0,+ Rm::Reg(src.0),+ ByteRegisters::No,+ 0,+ );+ self.jcc(Cond::Equal, zero);+ if op == BitCount::Lzcnt {+ self.xor_ri(Width::W32, dst, if width == Width::W64 { 63 } else { 31 });+ }+ self.jmp(done);+ self.bind(zero);+ self.mov_ri32(dst, if width == Width::W64 { 64 } else { 32 });+ self.bind(done);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::asm::disassembler;+ use crate::asm::x86_64::{BitwiseOp, FloatOp, Precision, RAX, RDI, Rounding, XMM1, XMM8, XMM9};++ #[test]+ fn sse_encodings() {+ type Emit = fn(&mut Assembler);+ let cases: &[(&str, Emit)] = &[+ ("movapd xmm8, xmm9; subss xmm8, xmm1", |a| {+ a.vfloat_rrr(FloatOp::Sub, Precision::Single, XMM8, XMM9, XMM1);+ }),+ ("movapd xmm8, xmm9; addsd xmm8, qword ptr [rdi+8]", |a| {+ a.vfloat_rrm(FloatOp::Add, Precision::Double, XMM8, XMM9, &Address::new(RDI, 8));+ }),+ ("movapd xmm8, xmm9; andnps xmm8, xmm1", |a| {+ a.vbitwise_rrr(BitwiseOp::AndNot, XMM8, XMM9, XMM1);+ }),+ ("movapd xmm8, xmm9; roundsd xmm8, xmm9, 0xb", |a| {+ a.vround(Precision::Double, XMM8, XMM9, Rounding::TowardZero);+ }),+ ("movd xmm8, edi", |a| a.vmov_xr(Width::W32, XMM8, RDI)),+ ("movq rax, xmm8", |a| a.vmov_rx(Width::W64, RAX, XMM8)),+ ("movapd xmm8, xmm9; cvtsi2sd xmm8, rdi", |a| {+ a.vcvtsi2s(Precision::Double, Width::W64, XMM8, XMM9, RDI);+ }),+ ("cvttss2si rax, xmm8", |a| {+ a.vcvtts2si(Precision::Single, Width::W64, RAX, XMM8);+ }),+ ("movapd xmm8, xmm9; pblendw xmm8, xmm1, 0x33", |a| {+ a.vex(+ VexOpcode::new(VexPrefix::OperandSize, VexMap::Map0F3A, 2),+ 8,+ 9,+ VexOperand::Register(1),+ Some(5),+ );+ }),+ (+ "pinsrb xmm8, byte ptr [rdi], 0; punpcklbw xmm8, xmm8; punpcklwd xmm8, xmm8; pshufd xmm8, xmm8, 0",+ |a| {+ a.vex(+ VexOpcode::new(VexPrefix::OperandSize, VexMap::Map0F38, 0x78),+ 8,+ 0,+ VexOperand::Memory(Address::new(RDI, 0)),+ None,+ );+ },+ ),+ ("movapd xmm9, xmm8; psrlq xmm9, 7", |a| {+ a.vex(+ VexOpcode::new(VexPrefix::OperandSize, VexMap::Map0F, 0x73),+ 2,+ 9,+ VexOperand::Register(8),+ Some(7),+ );+ }),+ ];+ for (expected, emit) in cases {+ let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2);+ emit(&mut asm);+ assert_eq!(disassembler::x86_64(&asm.finish().unwrap()).join("; "), *expected);+ }+ }++ #[test]+ fn commutative_aliases_need_no_temporary() {+ use VexMap::{Map0F, Map0F38};+ use VexPrefix::{None as NoPrefix, OperandSize as P66};+ for (map, prefix, opcode, mnemonic) in [+ (Map0F, P66, 0xfc, "paddb"),+ (Map0F, P66, 0xfd, "paddw"),+ (Map0F, P66, 0xfe, "paddd"),+ (Map0F, P66, 0xd4, "paddq"),+ (Map0F, P66, 0xdc, "paddusb"),+ (Map0F, P66, 0xdd, "paddusw"),+ (Map0F, P66, 0xec, "paddsb"),+ (Map0F, P66, 0xed, "paddsw"),+ (Map0F, P66, 0xd5, "pmullw"),+ (Map0F, P66, 0xe4, "pmulhuw"),+ (Map0F, P66, 0xe5, "pmulhw"),+ (Map0F, P66, 0xf4, "pmuludq"),+ (Map0F, P66, 0xf5, "pmaddwd"),+ (Map0F38, P66, 0x0b, "pmulhrsw"),+ (Map0F38, P66, 0x28, "pmuldq"),+ (Map0F38, P66, 0x40, "pmulld"),+ (Map0F, P66, 0xdb, "pand"),+ (Map0F, P66, 0xeb, "por"),+ (Map0F, P66, 0xef, "pxor"),+ (Map0F, NoPrefix, 0x54, "andps"),+ (Map0F, NoPrefix, 0x56, "orps"),+ (Map0F, NoPrefix, 0x57, "xorps"),+ (Map0F, P66, 0x54, "andpd"),+ (Map0F, P66, 0x56, "orpd"),+ (Map0F, P66, 0x57, "xorpd"),+ ] {+ let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2);+ asm.vex(VexOpcode::new(prefix, map, opcode), 9, 8, VexOperand::Register(9), None);+ assert_eq!(+ disassembler::x86_64(&asm.finish().unwrap()),+ [format!("{mnemonic} xmm9, xmm8")],+ "{mnemonic} should reuse its second input without spilling"+ );+ }+ }++ #[cfg(target_arch = "x86_64")]+ use crate::asm::executable_code::ExecutableCode;+ #[cfg(target_arch = "x86_64")]+ use crate::asm::x86_64::{RDX, RSI, XMM0};++ #[test]+ #[cfg(target_arch = "x86_64")]+ fn packed_float_aliases_preserve_nan_payloads() {+ let load = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x10);+ let store = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x11);+ for (prefix, a, b) in [+ (+ VexPrefix::None,+ 0x7fc0_0004_7fc0_0003_7fc0_0002_7fc0_0001u128,+ 0x7fc0_0008_7fc0_0007_7fc0_0006_7fc0_0005u128,+ ),+ (+ VexPrefix::OperandSize,+ 0x7ff8_0000_0000_0002_7ff8_0000_0000_0001u128,+ 0x7ff8_0000_0000_0004_7ff8_0000_0000_0003u128,+ ),+ ] {+ for opcode in [0x58, 0x59] {+ // ADDPS/PD and MULPS/PD+ let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2);+ for (index, dst) in [1, 9].into_iter().enumerate() {+ asm.vex(load, 8, 0, VexOperand::Memory(Address::new(RDI, 0)), None);+ asm.vex(load, 9, 0, VexOperand::Memory(Address::new(RSI, 0)), None);+ asm.vex(+ VexOpcode::new(prefix, VexMap::Map0F, opcode),+ dst,+ 8,+ VexOperand::Register(9),+ None,+ );+ asm.vex(+ store,+ dst,+ 0,+ VexOperand::Memory(Address::new(RDX, index as i32 * 16)),+ None,+ );+ }+ asm.ret();+ let code = ExecutableCode::new(&asm.finish().unwrap());+ let run: extern "sysv64" fn(*const u128, *const u128, *mut u128) =+ unsafe { std::mem::transmute(code.address()) };+ let mut results = [0u128; 2];+ run(&raw const a, &raw const b, results.as_mut_ptr());+ assert_eq!(+ results[0], results[1],+ "{prefix:?} {opcode:#x} changed the NaN payload when dst aliases rhs"+ );+ }+ }+ }++ #[test]+ #[cfg(target_arch = "x86_64")]+ fn sse_three_operand_aliases_preserve_other_registers() {+ for op in [FloatOp::Add, FloatOp::Mul, FloatOp::Sub] {+ let load = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x10);+ let store = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x11);+ for lhs in [1, 8, 9] {+ for rhs in [1, 8, 9] {+ for dst in [1, 8, 9] {+ let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2);+ asm.vex(load, 0, 0, VexOperand::Memory(Address::new(RDI, 0)), None);+ asm.vmovaps_rr(Fpr(lhs), XMM0);+ if lhs != rhs {+ asm.vex(load, rhs, 0, VexOperand::Memory(Address::new(RSI, 0)), None);+ }+ asm.vfloat_rrr(op, Precision::Double, Fpr(dst), Fpr(lhs), Fpr(rhs));+ asm.vex(store, dst, 0, VexOperand::Memory(Address::new(RDX, 0)), None);+ asm.vex(store, 0, 0, VexOperand::Memory(Address::new(RDX, 16)), None);+ asm.ret();+ let code = ExecutableCode::new(&asm.finish().unwrap());+ let run: extern "sysv64" fn(*const u128, *const u128, *mut u128) =+ unsafe { std::mem::transmute(code.address()) };+ let a = (0x1234_5678_9abc_def0u128 << 64) | u128::from(7.5f64.to_bits());+ let b = (0xfedc_ba98_7654_3210u128 << 64) | u128::from(2.0f64.to_bits());+ let mut result = [0u128; 2];+ run(&raw const a, &raw const b, result.as_mut_ptr());+ let rhs_value = if lhs == rhs { 7.5f64 } else { 2.0f64 };+ let expected = match op {+ FloatOp::Add => 7.5 + rhs_value,+ FloatOp::Mul => 7.5 * rhs_value,+ FloatOp::Sub => 7.5 - rhs_value,+ _ => unreachable!(),+ };+ assert_eq!(+ result[0],+ (a & (!0u128 << 64)) | u128::from(expected.to_bits()),+ "dst={dst} lhs={lhs} rhs={rhs}"+ );+ assert_eq!(result[1], a, "temporary register was clobbered");+ }+ }+ }+ }+ }++ #[test]+ #[cfg(target_arch = "x86_64")]+ fn bit_scans_handle_zero_and_aliasing() {+ for width in [Width::W32, Width::W64] {+ for op in [BitCount::Lzcnt, BitCount::Tzcnt] {+ for alias in [false, true] {+ let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2);+ let dst = if alias { RDI } else { RAX };+ asm.bit_count(op, width, dst, RDI);+ asm.mov_rr(Width::W64, RAX, dst);+ asm.ret();+ let code = ExecutableCode::new(&asm.finish().unwrap());+ let run: extern "sysv64" fn(u64) -> u64 = unsafe { std::mem::transmute(code.address()) };+ for input in [0, 1, 2, 3, 1 << 31, 1 << 32, 1 << 63, u64::MAX] {+ let expected = match (op, width) {+ (BitCount::Lzcnt, Width::W32) => (input as u32).leading_zeros(),+ (BitCount::Tzcnt, Width::W32) => (input as u32).trailing_zeros(),+ (BitCount::Lzcnt, _) => input.leading_zeros(),+ _ => input.trailing_zeros(),+ };+ assert_eq!(+ run(input),+ u64::from(expected),+ "{op:?} {width:?} {input:#x} alias={alias}"+ );+ }+ }+ }+ }+ }+}diff --git a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs b/Libraries/LibWasm/Engine/src/runtime/interpreter.rsindex a06b4d82420..8ea7209c84c 100644--- a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs+++ b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs@@ -83,8 +83,8 @@ pub fn check_cpu_features() {);}-/// Whether the CPU has the features the JIT's code uses: those of x86-64-v3 on x86-64, and those of the interpreter on-/// AArch64. Without them, everything runs in the interpreter.+/// Whether the CPU has the JIT's baseline features. On x86-64, optional AVX, BMI and LZCNT instructions are selected+/// at runtime; SSE4.2 and POPCNT suffice for both tiers. AArch64 uses the interpreter's features.pub fn cpu_supports_jit() -> bool {missing_jit_cpu_features().is_empty()}@@ -120,9 +120,7 @@ fn missing_interpreter_cpu_features() -> Vec<&'static str> {#[cfg(target_arch = "x86_64")]fn missing_jit_cpu_features() -> Vec<&'static str> {- missing_cpu_features!(- "sse4.1", "sse4.2", "popcnt", "lzcnt", "bmi1", "bmi2", "avx", "avx2", "fma", "movbe"- )+ missing_cpu_features!("ssse3", "sse4.1", "sse4.2", "popcnt")}#[cfg(target_arch = "aarch64")]diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.mdindex 2956d005a01..d977e002593 100644--- a/Libraries/LibWasm/JIT/ARCHITECTURE.md+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md@@ -306,10 +306,15 @@ There is a backend per target, with the same structure: `codegen/x86_64/` and `c(ARMv8.1 with LSE atomics and NEON), each with its own instruction selection for numbers, vectors,memory, calls, tables and GC objects. The rest of this section describes the x86-64 one.-`codegen/x86_64/` lowers the blocks in linear order with x86-64-v3 instructions (VEX three-operand-float arithmetic, BMI1/BMI2 shifts and rotates, lzcnt, tzcnt, popcnt, and AVX2 for vectors), from-libjs_jit's encoders and the additions in its `asm/x86_64/extended.rs`, whose `vex()` encodes any-VEX instruction from its opcode (`codegen/x86_64/vector.rs` names the SIMD ones). After each node, a value with a slot is stored+`codegen/x86_64/` lowers the blocks in linear order for an x86-64-v2 baseline (SSE4.2 and POPCNT).+The assembler and allocator select optional instructions independently using runtime CPU detection:+AVX for scalar floats, AVX2 for vectors, BMI2 for shifts and rotates, and LZCNT/BMI1 for zero counts.+Without them, `asm/x86_64/sse.rs` emits legacy SSE sequences and bit scans, and variable integer+shifts use CL. This selection also covers entry, exit and host stubs. The shared encoders live in+libjs_jit's `asm/x86_64/`; `codegen/x86_64/vector.rs` names the SIMD opcodes. SSE packed operations+read spilled vectors through registers, since their memory operands require sixteen-byte alignment.+Distributed C++ and Rust builds target the same v2 baseline (`ENABLE_CI_BASELINE_CPU`); native+builds still target the machine building them. After each node, a value with a slot is storedthere; a phi in a register with a slot is stored where its block starts.- **Vectors.** A vector node's output register differs from its inputs and temps, so lowerings may@@ -381,6 +386,11 @@ the interpreter and the host. The JIT is on by default; `LIBWASM_JIT` configurestraps with a code of its own; binding a module's instance points the engine's function headers atthe code. With `--runtime`, the script calls go through `Store::invoke` instead, and the runtimecompiles what `LIBWASM_JIT` says (`eager` by default).+- To check the SSE path on an AVX-capable development machine, build `spec_check` with+ `RUSTFLAGS='-Ctarget-cpu=x86-64-v2' cargo build -p libwasm_jit --example spec_check`, then run+ `qemu-x86_64 -cpu Nehalem target/debug/examples/spec_check SCRIPT_DIRECTORY`. Repeat with+ `--stress-registers` to exercise spills and with `--runtime` to exercise the runtime's tier+ transitions and stubs. `-cpu SandyBridge` also checks AVX scalar floats alongside SSE vectors.- `examples/bench_check.rs` runs a module's entry in an interpreted store and a compiled one, withdeterministic imports, and compares results, exit codes, memories, tables and globals.- `examples/smith_check.rs` does the same for random modules from `wasm-tools smith` in the subsetdiff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rsindex 00c8a9dd296..9cee6fcefad 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs@@ -115,7 +115,7 @@ impl<'a> CodeGenerator<'a> {func,allocation,runtime,- asm: Assembler::new(),+ asm: Assembler::for_host(),block_labels: Vec::new(),trap_labels: vec![None; 32],dynamic_trap: None,diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rsindex f72800ebe6e..643c8e038f8 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rs@@ -74,6 +74,17 @@ impl CodeGenerator<'_> {_ => ShiftOp::Shr,};self.asm.shift_ri(op, width(ty), dst, amount);+ } else if !self.asm.cpu_features().bmi2 {+ debug_assert_eq!(gpr(b), crate::asm::x86_64::RCX);+ if output != a {+ self.asm.mov_rr(width(ty), dst, source);+ }+ let op = match node.op {+ Op::Shl => ShiftOp::Shl,+ Op::ShrS => ShiftOp::Sar,+ _ => ShiftOp::Shr,+ };+ self.asm.shift_rcl(op, width(ty), dst);} else {let op = match node.op {Op::Shl => ShiftX::Shl,diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rsindex 3bd8a085272..06fd0ab4910 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs@@ -4,7 +4,8 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! Vectors: v128 loads, constants, lanes and SIMD arithmetic, as AVX2 instructions on xmm registers.+//! Vectors: v128 loads, constants, lanes and SIMD arithmetic on xmm registers. The assembler selects AVX2 or+//! equivalent SSE sequences for the host CPU.//!//! The allocator gives a vector node an output register apart from its inputs and temps, so a lowering may write//! its output before it has read all inputs. Inputs may share a register (`i32x4.add x x`), and are never written.diff --git a/Libraries/LibWasm/JIT/src/regalloc/mod.rs b/Libraries/LibWasm/JIT/src/regalloc/mod.rsindex 03a42a6551b..e8debe8bcc2 100644--- a/Libraries/LibWasm/JIT/src/regalloc/mod.rs+++ b/Libraries/LibWasm/JIT/src/regalloc/mod.rs@@ -213,6 +213,11 @@ pub fn fits_displacement(func: &Func, index: Value, offset: u32) -> bool {#[cfg(target_arch = "x86_64")]fn constraints(func: &Func, value: Value) -> Constraints {+ constraints_for_cpu(func, value, crate::asm::x86_64::CpuFeatures::host())+}++#[cfg(target_arch = "x86_64")]+fn constraints_for_cpu(func: &Func, value: Value, cpu_features: crate::asm::x86_64::CpuFeatures) -> Constraints {use convention::{RAX, RCX, RDX};let node = func.node(value);let output = if node.ty == Type::None {@@ -235,9 +240,18 @@ fn constraints(func: &Func, value: Value) -> Constraints {constraints.reuse_first = true;constraints.slot_inputs = 0b010;}- Op::Shl | Op::ShrS | Op::ShrU => constraints.inputs[1] = Input::RegisterOrConstant,+ Op::Shl | Op::ShrS | Op::ShrU => {+ // RegisterOrConstant only uses an immediate when fits_immediate() accepts it. Otherwise a legacy+ // shift needs CL even if its count is a constant.+ if fits_immediate(func, node.args[1]) || cpu_features.bmi2 {+ constraints.inputs[1] = Input::RegisterOrConstant;+ } else {+ constraints.inputs[1] = Input::Fixed(RCX);+ constraints.reuse_first = true;+ }+ }Op::Rotl | Op::Rotr => {- if func.node(node.args[1]).op.is_constant() {+ if fits_immediate(func, node.args[1]) {constraints.inputs[1] = Input::RegisterOrConstant;} else {constraints.inputs[1] = Input::Fixed(RCX);@@ -348,7 +362,11 @@ fn constraints(func: &Func, value: Value) -> Constraints {*input = Input::RegisterOrVectorConstant;}}- constraints.slot_inputs = constants;+ // Legacy packed SSE memory operands require alignment; spill slots need only be eight-byte aligned.+ // Constants in the pool are aligned to sixteen bytes on both paths.+ if cpu_features.avx2 {+ constraints.slot_inputs = constants;+ }}_ => {}}@@ -1407,6 +1425,40 @@ mod tests {use super::{Allocation, Allocator, Location, Move, NO_SLOT};use std::collections::HashMap;+ #[test]+ #[cfg(target_arch = "x86_64")]+ fn large_constant_shift_counts_require_rcx_without_bmi2() {+ use super::{Input, constraints_for_cpu};+ use crate::asm::x86_64::CpuFeatures;+ use crate::convention::RCX;+ use crate::ir::{Func, Node, Op, Type};++ for op in [Op::Shl, Op::ShrS, Op::ShrU, Op::Rotl, Op::Rotr] {+ for count in [0x8000_0000u64, 0xffff_ffff, 0x1_0000_0001, 0x8000_0000_0000_003f] {+ let func = Func {+ nodes: vec![+ Node::new(Op::Param, Type::I64, 0, [0, 0, 0]),+ Node::new(Op::Const64, Type::I64, 0, [count as u32, (count >> 32) as u32, 0]),+ Node::new(op, Type::I64, 0, [0, 1, 0]),+ ],+ ..Default::default()+ };+ for features in [CpuFeatures::X86_64_V2, CpuFeatures::X86_64_V3] {+ let constraints = constraints_for_cpu(&func, 2, features);+ let expected = if features.bmi2 && matches!(op, Op::Shl | Op::ShrS | Op::ShrU) {+ Input::RegisterOrConstant+ } else {+ Input::Fixed(RCX)+ };+ assert_eq!(+ constraints.inputs[1], expected,+ "{op:?}, count={count:#x}, {features:?}"+ );+ }+ }+ }+ }+/// Runs `moves` as `resolve()` orders them, and checks that every destination gets what its source had before.fn check(moves: &[(u8, u8)]) {let mut allocator = Allocator::default();diff --git a/Libraries/LibWasm/JIT/src/stubs.rs b/Libraries/LibWasm/JIT/src/stubs.rsindex 1df5e737255..8accce70322 100644--- a/Libraries/LibWasm/JIT/src/stubs.rs+++ b/Libraries/LibWasm/JIT/src/stubs.rs@@ -74,7 +74,7 @@ fn copy(asm: &mut Assembler, ty: Type, from: Address, to: Address) {/// 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 mut asm = Assembler::for_host();let parameter_slots = convention::slots(params) as i32;let result_slots = convention::slots(results) as i32;let buffer_slots = parameter_slots.max(result_slots);@@ -230,7 +230,7 @@ fn field(offset: usize) -> i32 {/// The trap exit: stores the code in edi as the context's first argument, and the context in the frame that/// trapped, and continues at the interpreter's TrapFromNative handler at `handler`.pub fn trap_exit(handler: u64) -> Vec<u8> {- let mut asm = Assembler::new();+ let mut asm = Assembler::for_host();let context = gpr(convention::RAX);asm.mov_rm(Width::W64, context, &Address::new(FP, convention::FRAME_INSTANCE));asm.mov_rm(@@ -277,7 +277,7 @@ fn copy_words(asm: &mut Assembler, from: Gpr, to: Gpr, count: Gpr, temp: Gpr) {/// 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`).pub fn entry_trampoline() -> (Vec<u8>, usize) {- let mut asm = Assembler::new();+ let mut asm = Assembler::for_host();let record = gpr(convention::R11);let (rax, rcx, rdx, rsi, rdi) = (gpr(convention::RAX),@@ -377,7 +377,7 @@ pub const ADAPTER_RESUME: u64 = u64::MAX;/// 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 mut asm = Assembler::for_host();let instance = gpr(convention::INSTANCE_REGISTER);// Below the frame header, the save area at rsp.let frame_size = (convention::FRAME_HEADER_SIZE as usize + ADAPTER_SAVE_AREA).next_multiple_of(16) as i32;diff --git a/Libraries/LibWasm/JIT/tests/harness/x86_64.rs b/Libraries/LibWasm/JIT/tests/harness/x86_64.rsindex 1478d13d640..6a32e88fc51 100644--- a/Libraries/LibWasm/JIT/tests/harness/x86_64.rs+++ b/Libraries/LibWasm/JIT/tests/harness/x86_64.rs@@ -19,7 +19,7 @@ const VMOVUPS_STORE: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F,/// 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 mut asm = Assembler::for_host();let rax = Gpr(convention::RAX);let sp = Gpr(convention::RSP);asm.mov_ri(rax, state as u64);@@ -36,7 +36,7 @@ pub(super) fn not_compiled_code(trap_exit: u64) -> Vec<u8> {/// Code that traps with `code`.pub(super) fn trap_stub(trap_exit: u64, code: u32) -> Vec<u8> {- let mut asm = Assembler::new();+ let mut asm = Assembler::for_host();asm.mov_ri32(Gpr(convention::RDI), code);asm.mov_ri(Gpr(convention::R11), trap_exit);asm.jmp_r(Gpr(convention::R11));@@ -62,7 +62,7 @@ fn restore_and_return(asm: &mut Assembler, status: u32) {/// `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 mut asm = Assembler::for_host();let g = Gpr;let (rdi, rsi, rdx, rcx) = (g(convention::RDI),diff --git a/Libraries/LibWasm/JIT/tests/shift_counts.rs b/Libraries/LibWasm/JIT/tests/shift_counts.rsnew file mode 100644index 00000000000..e7437d80347--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/shift_counts.rs@@ -0,0 +1,120 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Constant i64 shift counts outside the sign-extended immediate range must use CL without BMI2. Check all shifts+//! and rotations against the interpreter, including counts whose low bits wrap, directly and through the runtime.++#![cfg(any(target_arch = "x86_64", all(target_arch = "aarch64", not(windows))))]++mod harness;++use std::fmt::Write as _;+use std::sync::Arc;++use harness::{CompiledModule, Outcome, TestBinding};+use libwasm_engine::runtime::{ExternValue, Store, Value};++const OPERATIONS: [&str; 5] = ["shl", "shr_s", "shr_u", "rotl", "rotr"];+const COUNTS: [u64; 12] = [+ 1,+ 63,+ 64,+ 0x7fff_ffff,+ 0x8000_0000,+ 0xffff_ffff,+ 0x1_0000_0000,+ 0x1_0000_0001,+ 0x1_0000_003f,+ 0x8000_0000_0000_0001,+ 0xffff_ffff_7fff_ffff,+ u64::MAX,+];+const INPUTS: [i64; 6] = [0, 3, -3, i64::MIN, i64::MAX, 0x1234_5678_9abc_def0];++fn script() -> String {+ let mut text = String::from("(module\n");+ for op in OPERATIONS {+ for (index, count) in COUNTS.iter().enumerate() {+ writeln!(+ text,+ " (func (export \"{op}_{index}\") (param i64) (result i64) \+ (i64.{op} (local.get 0) (i64.const {})))",+ *count as i64+ )+ .unwrap();+ }+ }+ text.push_str(")\n");+ text+}++#[test]+fn large_constant_shift_counts_run_the_same_compiled() {+ let panics = harness::panics();+ // SAFETY: Nothing else runs yet.+ unsafe { std::env::set_var("LIBWASM_JIT", "forced,verify-ir") };+ let directory = std::env::temp_dir().join(format!("libwasm-shift-counts-{}", std::process::id()));+ let Some(json) = harness::script::write_wast(&directory, "shift_counts", &script()) else {+ eprintln!("no wasm-tools; skipped");+ return;+ };+ let json: serde_json::Value = serde_json::from_slice(&std::fs::read(json).unwrap()).unwrap();+ let path = directory.join(json["commands"][0]["filename"].as_str().unwrap());+ let module = Arc::new(libwasm_engine::compile(&std::fs::read(path).unwrap()).unwrap());+ for stress_registers in [false, true] {+ for runtime in [false, true] {+ let options = libwasm_jit::Options {+ verify_ir: true,+ stress_registers,+ ..Default::default()+ };+ let mut interpreted = Store::new();+ interpreted.disable_jit();+ let mut jit = Store::new();+ let interpreted_instance = interpreted.instantiate(module.clone(), &[]).unwrap();+ let jit_instance = jit.instantiate(module.clone(), &[]).unwrap();+ let compiled = (!runtime).then(|| CompiledModule::compile(module.clone(), options));+ let mut binding = compiled.as_ref().map(|compiled| {+ assert!(compiled.runnable.iter().all(|runnable| *runnable));+ TestBinding::new(compiled, &jit, jit_instance)+ });+ for op in OPERATIONS {+ for (index, count) in COUNTS.iter().enumerate() {+ let name = format!("{op}_{index}");+ let Some(ExternValue::Function(reference)) =+ interpreted.instance(interpreted_instance).export(&name)+ else {+ panic!("no {name} export");+ };+ let Some(ExternValue::Function(function)) = jit.instance(jit_instance).export(&name) else {+ panic!("no {name} export");+ };+ let index = harness::function_index(&jit, function, jit_instance).unwrap();+ for input in INPUTS {+ let arguments = [Value::I64(input)];+ let expected = interpreted.invoke(reference, &arguments).unwrap();+ let actual = if let Some((compiled, binding)) = compiled.as_ref().zip(binding.as_mut()) {+ binding.call(&mut jit, compiled, index, &arguments)+ } else {+ Outcome::Values(jit.invoke(function, &arguments).unwrap())+ };+ assert_eq!(+ actual,+ Outcome::Values(expected),+ "{op}, count={count:#x}, input={input}, runtime={runtime}, stress_registers={stress_registers}"+ );+ }+ }+ }+ }+ }+ let _ = std::fs::remove_dir_all(&directory);+ assert_eq!(+ panics.load(std::sync::atomic::Ordering::Relaxed),+ 0,+ "a compile panicked"+ );+}diff --git a/Meta/CMake/cmake_options.cmake b/Meta/CMake/cmake_options.cmakeindex a22a618df7a..2db24e0cac8 100644--- a/Meta/CMake/cmake_options.cmake+++ b/Meta/CMake/cmake_options.cmake@@ -38,7 +38,7 @@ option(LADYBIRD_GENERATE_SYMBOL_FILES "Build with debug info and write the symboif (LADYBIRD_GENERATE_SYMBOL_FILES AND MSVC)message(FATAL_ERROR "LADYBIRD_GENERATE_SYMBOL_FILES is not supported with MSVC-style toolchains")endif()-option(ENABLE_CI_BASELINE_CPU "Use a baseline CPU target for improved ccache sharing" OFF)+option(ENABLE_CI_BASELINE_CPU "Use a common CPU baseline for portable binaries and ccache sharing" OFF)set(LADYBIRD_VERSION "" CACHE STRING "Version of a release: year.month.patch, optionally followed by .alpha or .beta")set(LADYBIRD_BUNDLE_VERSION "${PROJECT_VERSION}")diff --git a/Meta/CMake/compile_options.cmake b/Meta/CMake/compile_options.cmakeindex 8e723048718..349bc73e84f 100644--- a/Meta/CMake/compile_options.cmake+++ b/Meta/CMake/compile_options.cmake@@ -66,8 +66,9 @@ if (ENABLE_CI_BASELINE_CPU)add_cxx_compile_options(-march=armv8.2-a)set(RUSTC_TARGET_CPU_FLAGS -Ctarget-feature=+v8.2a)elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$")- add_cxx_compile_options(-march=x86-64-v3)- set(RUSTC_TARGET_CPU_FLAGS -Ctarget-cpu=x86-64-v3)+ # Keep distributed binaries usable on SSE4.2/POPCNT machines without AVX or BMI.+ add_cxx_compile_options(-march=x86-64-v2)+ set(RUSTC_TARGET_CPU_FLAGS -Ctarget-cpu=x86-64-v2)endif()elseif (CMAKE_SYSTEM_PROCESSOR STREQUAL "riscv64")# On RISC-V the generic -march=native is not yet supported and both gcc and clang require an explicitdiff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.pyindex da1fd765090..3d22f9f973e 100755--- a/Meta/Linters/check_rust_process_wide_state.py+++ b/Meta/Linters/check_rust_process_wide_state.py@@ -33,6 +33,7 @@ ALLOWED = {"Libraries/LibCompositing/Rust/src/test_stubs.rs:NEXT": "test stub for LibGfx's C++ counters, in the cargo test binary that has no C++ side","Libraries/LibCompositing/Rust/src/display_list/replay.rs:WARM_REPLAY_SCRATCH_STORAGE": "per-thread replay scratch; a second copy costs memory, never an answer","Libraries/LibJS/Flap/src/low_ir/lowering.rs:LABELS": "per-thread scratch buffer; a second copy costs memory, never an answer",+ "Libraries/LibJS/JIT/Rust/src/asm/x86_64/sse.rs:FEATURES": "immutable CPU/OS feature cache; each copy computes the same supported instructions","Libraries/LibWeb/HTML/Parser/Rust/src/token.rs:SPARE_ATTRIBUTE_LISTS": "per-thread allocation pool; a second copy costs memory, never an answer","Libraries/LibWeb/HTML/Parser/Rust/src/token.rs:SPARE_ATTRIBUTE_VALUES": "per-thread allocation pool; a second copy costs memory, never an answer",}