diff --git a/Cargo.lock b/Cargo.lock index 5b493240f0..17a7b50594 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1932,7 +1932,7 @@ version = "0.1.0" dependencies = [ "rustc_apfloat", "serde", - "sha2", + "stela-fingerprint", ] [[package]] @@ -1969,6 +1969,13 @@ dependencies = [ "zeroize", ] +[[package]] +name = "stela-fingerprint" +version = "0.1.0" +dependencies = [ + "sha2", +] + [[package]] name = "stela-loader" version = "0.1.0" @@ -2014,6 +2021,7 @@ dependencies = [ "smoltcp", "stela-compiler", "stela-drivers", + "stela-fingerprint", "tempfile", "zeroize", ] diff --git a/Cargo.toml b/Cargo.toml index ea9f763792..3123cbae3a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ members = [ "crates/stela-compiler", "crates/stela-drivers", "crates/stela-drivers/src/gpu/metal/input", + "crates/stela-fingerprint", "crates/stela-runtime", "xtask", ] @@ -45,6 +46,7 @@ libc = "0.2" tempfile = "3" stela-boot-core = { path = "crates/stela-boot-core" } stela-compiler = { path = "crates/stela-compiler" } +stela-fingerprint = { path = "crates/stela-fingerprint" } stela-drivers = { path = "crates/stela-drivers" } stela-runtime = { path = "crates/stela-runtime" } stela-loader = { path = "crates/stela-loader" } diff --git a/crates/stela-boot/Cargo.lock b/crates/stela-boot/Cargo.lock index 3061ed9d2a..e9c24d0e9c 100644 --- a/crates/stela-boot/Cargo.lock +++ b/crates/stela-boot/Cargo.lock @@ -641,7 +641,7 @@ version = "0.1.0" dependencies = [ "rustc_apfloat", "serde", - "sha2", + "stela-fingerprint", ] [[package]] @@ -661,6 +661,13 @@ dependencies = [ "zeroize", ] +[[package]] +name = "stela-fingerprint" +version = "0.1.0" +dependencies = [ + "sha2", +] + [[package]] name = "stela-loader" version = "0.1.0" @@ -696,6 +703,7 @@ dependencies = [ "smoltcp", "stela-compiler", "stela-drivers", + "stela-fingerprint", "tempfile", "zeroize", ] diff --git a/crates/stela-boot/src/engine/host/local.rs b/crates/stela-boot/src/engine/host/local.rs index 21b596d4a2..7324632eec 100644 --- a/crates/stela-boot/src/engine/host/local.rs +++ b/crates/stela-boot/src/engine/host/local.rs @@ -122,7 +122,7 @@ impl Owner { /// /// # Safety /// This is the source-qualified registered RAM for this executor. Its - /// all-writer contract is retained. Direct SystemModeV1 guest data writers + /// all-writer contract is retained. Direct `SYSTEM_MODE` guest data writers /// must never bypass this all-writer owner, including between checked calls. /// Only the source-qualified checked service and registered host/table /// publishers may touch data; returning to serial execution additionally diff --git a/crates/stela-boot/src/native_smp.rs b/crates/stela-boot/src/native_smp.rs index 1653de89aa..9d0b3facc1 100644 --- a/crates/stela-boot/src/native_smp.rs +++ b/crates/stela-boot/src/native_smp.rs @@ -1,7 +1,7 @@ //! Native host processors for system execution. Firmware identity/capability //! observations are copied before EBS; persistent APs use owned Stela startup //! and processor-local resources afterward. Production shared-memory admission -//! is distinct from SystemModeV1's single-agent translation contract. +//! is distinct from the direct `SYSTEM_MODE` profile's single-agent translation contract. pub(crate) mod bootstrap; pub(crate) mod canonical; mod context_check; diff --git a/crates/stela-boot/src/native_smp/context_check.rs b/crates/stela-boot/src/native_smp/context_check.rs index b802fba39c..8684c55fec 100644 --- a/crates/stela-boot/src/native_smp/context_check.rs +++ b/crates/stela-boot/src/native_smp/context_check.rs @@ -62,8 +62,10 @@ fn compile(words: &[u32]) -> Result) { - if path.is_dir() { - for entry in fs::read_dir(path).expect("readable source directory") { - collect(&entry.expect("source entry").path(), files); - } - } else { - files.push(path.to_owned()); - } -} - fn main() { - let mut files = Vec::new(); - for input in INPUTS { - println!("cargo:rerun-if-changed={input}"); - collect(Path::new(input), &mut files); - } - files.sort(); - let mut hasher = Sha256::new(); - for file in files { - hasher.update(file.to_string_lossy().as_bytes()); - hasher.update([0]); - hasher.update(fs::read(&file).expect("readable source file")); - } - let digest: String = hasher - .finalize() - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(); - println!("cargo:rustc-env=STELA_COMPILER_SOURCE_SHA256={digest}"); + stela_fingerprint::emit( + "STELA_COMPILER_SOURCE_SHA256", + &["Cargo.toml", "build.rs", "src"], + ); } diff --git a/crates/stela-compiler/src/aarch64.rs b/crates/stela-compiler/src/aarch64.rs index be4509a13a..c97fdb24a3 100644 --- a/crates/stela-compiler/src/aarch64.rs +++ b/crates/stela-compiler/src/aarch64.rs @@ -28,6 +28,21 @@ pub mod tag_arithmetic; pub mod tag_memory; pub mod unprivileged; +/// A word in a decoder's class that the compiler does not translate: a +/// reserved encoding, or an allocated form the lifter reports as an +/// unsupported instruction. A decoder returns `None` for a word outside its +/// class. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Unsupported; + +impl core::fmt::Display for Unsupported { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + formatter.write_str("untranslated A64 encoding") + } +} + +impl core::error::Error for Unsupported {} + const CONDITIONAL_BRANCH_MASK: u32 = 0xff00_0000; const CONDITIONAL_BRANCH_CLASS: u32 = 0x5400_0000; @@ -111,8 +126,7 @@ pub enum FloatingPointOperation { } impl FloatingPointOperation { - #[allow(clippy::result_unit_err)] - pub fn decode(word: u32) -> Option> { + pub fn decode(word: u32) -> Option> { if let Some(result) = simd::arithmetic::decode(word) { Some(result.map(Self::Binary)) } else if let Some(result) = simd::fused::decode(word) { @@ -448,7 +462,7 @@ impl Lifter for Decoder { } else if let Some(decoded) = conditional_select::decode_compare(word) { Operation::ConditionalCompare(decoded) } else if let Some(decoded) = crc::decode(word) { - Operation::Crc(decoded.map_err(|()| unsupported())?) + Operation::Crc(decoded.map_err(|Unsupported| unsupported())?) } else if let Some(decoded) = checked_pointer::decode(word) { Operation::CheckedPointer(decoded) } else if let Some(decoded) = flags::decode(word) { @@ -462,25 +476,25 @@ impl Lifter for Decoder { } else if let Some(decoded) = tag_arithmetic::decode(word) { Operation::TagArithmetic(decoded) } else if let Some(decoded) = integer_math::decode(word) { - Operation::IntegerMath(decoded.map_err(|()| unsupported())?) + Operation::IntegerMath(decoded.map_err(|Unsupported| unsupported())?) } else if simd_fp && let Some(decoded) = FloatingPointOperation::decode(word) { - Operation::FloatingPoint(decoded.map_err(|()| unsupported())?) + Operation::FloatingPoint(decoded.map_err(|Unsupported| unsupported())?) } else if let Some(decoded) = ordered::decode(word) { Operation::Ordered(decoded) } else if let Some(decoded) = atomic::decode(word) { - Operation::Atomic(decoded.map_err(|()| unsupported())?) + Operation::Atomic(decoded.map_err(|Unsupported| unsupported())?) } else if let Some(decoded) = non_temporal::decode(word) { - Operation::MemoryNonTemporal(decoded.map_err(|()| unsupported())?) + Operation::MemoryNonTemporal(decoded.map_err(|Unsupported| unsupported())?) } else if let Some(decoded) = unprivileged::decode(word) { - Operation::MemoryUnprivileged(decoded.map_err(|()| unsupported())?) + Operation::MemoryUnprivileged(decoded.map_err(|Unsupported| unsupported())?) } else if let Some(decoded) = prefetch::decode(pc, word) { - Operation::Prefetch(decoded.map_err(|()| unsupported())?) + Operation::Prefetch(decoded.map_err(|Unsupported| unsupported())?) } else if let Some(decoded) = literal::decode(pc, word) { - Operation::Literal(decoded.map_err(|()| unsupported())?) + Operation::Literal(decoded.map_err(|Unsupported| unsupported())?) } else if simd_fp && let Some(decoded) = simd::decode(word) { - Operation::Simd(decoded.map_err(|()| unsupported())?) + Operation::Simd(decoded.map_err(|Unsupported| unsupported())?) } else if let Some(decoded) = register_offset::decode(word) { - Operation::MemoryRegisterOffset(decoded.map_err(|()| unsupported())?) + Operation::MemoryRegisterOffset(decoded.map_err(|Unsupported| unsupported())?) } else if word & 0x3e000000 == 0x28000000 { // Integer LDP/STP/LDPSW. SIMD, non-temporal pairs, tagged // stores and reserved opcodes are not interchangeable with these accesses. diff --git a/crates/stela-compiler/src/aarch64/atomic.rs b/crates/stela-compiler/src/aarch64/atomic.rs index 2f985ef784..54891cc703 100644 --- a/crates/stela-compiler/src/aarch64/atomic.rs +++ b/crates/stela-compiler/src/aarch64/atomic.rs @@ -1,5 +1,6 @@ //! LSE atomics: LDADD/LDCLR/LDEOR/LDSET/LDSMAX/LDSMIN/LDUMAX/LDUMIN, SWP, CAS and CASP. use super::{Register, register}; +use crate::aarch64::Unsupported; const CAS_MASK: u32 = 0x3fa07c00; const CAS_CLASS: u32 = 0x08a07c00; @@ -92,15 +93,14 @@ pub struct Operand { } /// Reserved RMW operations and odd CASP first registers are errors. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let source = register((word >> SOURCE_SHIFT) & REGISTER_MASK, false); let destination = register(word & REGISTER_MASK, false); let (kind, order, bytes) = if word & CASP_MASK == CASP_CLASS { let first_compare = (word >> SOURCE_SHIFT) & REGISTER_MASK; let first_source = word & REGISTER_MASK; if (first_compare | first_source) & PAIR_FIRST_ODD_BIT != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } ( Kind::CompareExchangePair { @@ -130,7 +130,7 @@ pub fn decode(word: u32) -> Option> { UNSIGNED_MAX_OPCODE => Rmw::UnsignedMax, UNSIGNED_MIN_OPCODE => Rmw::UnsignedMin, SWAP_OPCODE => Rmw::Swap, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; ( Kind::ReadModifyWrite { @@ -228,7 +228,7 @@ mod tests { | if release { CAS_RELEASE } else { 0 }; let decoded = decode(word).unwrap(); if (compare | source) & PAIR_FIRST_ODD_BIT != 0 { - assert_eq!(decoded, Err(())); + assert_eq!(decoded, Err(Unsupported)); } else { assert_eq!( decoded, @@ -264,7 +264,7 @@ mod tests { for operation in 9..=RMW_OPERATION_MASK { assert_eq!( decode(RMW_CLASS | (operation << RMW_OPERATION_SHIFT)), - Some(Err(())) + Some(Err(Unsupported)) ); } for word in [ diff --git a/crates/stela-compiler/src/aarch64/crc.rs b/crates/stela-compiler/src/aarch64/crc.rs index 4529a96385..0f2a84b340 100644 --- a/crates/stela-compiler/src/aarch64/crc.rs +++ b/crates/stela-compiler/src/aarch64/crc.rs @@ -1,5 +1,6 @@ //! CRC32 and CRC32C. use super::{Register, register}; +use crate::aarch64::Unsupported; const CLASS_MASK: u32 = 0x7fe0e000; const CLASS_VALUE: u32 = 0x1ac04000; @@ -53,8 +54,7 @@ pub struct Operand { } /// Register 31 is ZR in every role; sf is set exactly for doubleword data. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if word & CLASS_MASK != CLASS_VALUE { return None; } @@ -65,7 +65,7 @@ pub fn decode(word: u32) -> Option> { _ => DataSize::Doubleword, }; if (word & DOUBLEWORD_BIT != 0) != (size == DataSize::Doubleword) { - return Some(Err(())); + return Some(Err(Unsupported)); } Some(Ok(Operand { size, @@ -128,7 +128,7 @@ mod tests { } } } - assert_eq!(decode(base ^ DOUBLEWORD_BIT), Some(Err(()))); + assert_eq!(decode(base ^ DOUBLEWORD_BIT), Some(Err(Unsupported))); for bit in 0..32 { if CLASS_MASK & (1 << bit) != 0 { assert!(decode(base ^ (1 << bit)).is_none()); diff --git a/crates/stela-compiler/src/aarch64/integer_math.rs b/crates/stela-compiler/src/aarch64/integer_math.rs index 1305877c23..2ccc69ee6a 100644 --- a/crates/stela-compiler/src/aarch64/integer_math.rs +++ b/crates/stela-compiler/src/aarch64/integer_math.rs @@ -1,6 +1,7 @@ //! Integer data processing: MADD/MSUB, SMADDL/SMSUBL/UMADDL/UMSUBL, SMULH/UMULH, //! SDIV/UDIV, LSLV/LSRV/ASRV/RORV, EXTR, CLZ, CLS, RBIT and REV*. Register 31 is ZR. use super::{Register, Shift, Width, register}; +use crate::aarch64::Unsupported; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { @@ -29,8 +30,7 @@ pub struct Operand { /// Match scalar SDIV/UDIV and the product three-source class. Reserved product class /// members return Err, so they cannot accidentally become a nearby multiply. /// MUL/MNEG and long aliases are represented by an ordinary ZR accumulator. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let width = if word >> 31 == 0 { Width::W32 } else { @@ -49,7 +49,7 @@ pub fn decode(word: u32) -> Option> { } else if word & 0x7fa00000 == 0x13800000 { let amount = ((word >> 10) & 63) as u8; if ((word >> 22) & 1) != word >> 31 || (width == Width::W32 && amount >= 32) { - return Some(Err(())); + return Some(Err(Unsupported)); } Some(Kind::Extract { width, amount }) } else { @@ -134,7 +134,7 @@ pub fn decode(word: u32) -> Option> { (5, true, _) => Kind::Long { signed: false }, (2, true, false) => Kind::High { signed: true }, (6, true, false) => Kind::High { signed: false }, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; Some(Ok(Operand { kind, @@ -190,7 +190,7 @@ mod tests { for amount in 0..64 { let decoded = decode(base | (amount << 10) | (31 << 16) | (31 << 5) | 31).unwrap(); if width == Width::W32 && amount >= 32 { - assert_eq!(decoded, Err(())); + assert_eq!(decoded, Err(Unsupported)); } else { let operand = decoded.unwrap(); assert_eq!( @@ -206,7 +206,7 @@ mod tests { ); } } - assert_eq!(decode(base ^ (1 << 22)), Some(Err(()))); // N must match sf. + assert_eq!(decode(base ^ (1 << 22)), Some(Err(Unsupported))); // N must match sf. assert!(decode(base | (1 << 21)).is_none()); // fixed o0 } } diff --git a/crates/stela-compiler/src/aarch64/literal.rs b/crates/stela-compiler/src/aarch64/literal.rs index f31a5b9bf3..abf2122e01 100644 --- a/crates/stela-compiler/src/aarch64/literal.rs +++ b/crates/stela-compiler/src/aarch64/literal.rs @@ -1,6 +1,7 @@ //! PC-relative literal loads: LDR (literal), LDRSW (literal) and PRFM (literal). use super::{Register, Width, register}; use crate::GuestAddress; +use crate::aarch64::Unsupported; const CLASS_MASK: u32 = 0x3b000000; const LITERAL_CLASS: u32 = 0x18000000; @@ -39,8 +40,7 @@ pub struct Operand { /// PRFM (literal) and reserved SIMD opcode 11 are unsupported. The address /// wraps at 64 bits and uses this instruction's guest PC. -#[allow(clippy::result_unit_err)] -pub fn decode(pc: GuestAddress, word: u32) -> Option> { +pub fn decode(pc: GuestAddress, word: u32) -> Option> { if word & CLASS_MASK != LITERAL_CLASS { return None; } @@ -64,7 +64,7 @@ pub fn decode(pc: GuestAddress, word: u32) -> Option> { _ => unreachable!("literal SIMD form is matched above"), }, }, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; let immediate = i64::from((word >> IMMEDIATE_SHIFT) & IMMEDIATE_MASK); let signed = (immediate << IMMEDIATE_SIGN_SHIFT) >> IMMEDIATE_SIGN_SHIFT; @@ -126,7 +126,7 @@ mod tests { #[test] fn prefetch_reserved_and_neighboring_classes_do_not_become_loads() { for unsupported in [0xd8000000, 0xdc000000] { - assert_eq!(decode(GuestAddress(0), unsupported), Some(Err(()))); + assert_eq!(decode(GuestAddress(0), unsupported), Some(Err(Unsupported))); } for bit in [24, 25, 27, 28, 29] { assert!(decode(GuestAddress(0), LDR_W ^ (1 << bit)).is_none()); diff --git a/crates/stela-compiler/src/aarch64/non_temporal.rs b/crates/stela-compiler/src/aarch64/non_temporal.rs index 4ed6f83134..6c45dbf593 100644 --- a/crates/stela-compiler/src/aarch64/non_temporal.rs +++ b/crates/stela-compiler/src/aarch64/non_temporal.rs @@ -1,5 +1,6 @@ //! LDNP and STNP, integer and SIMD. use super::{Register, register}; +use crate::aarch64::Unsupported; const CLASS_MASK: u32 = 0x3b800000; const NON_TEMPORAL_PAIR_CLASS: u32 = 0x28000000; @@ -42,8 +43,7 @@ pub struct Operand { /// Only signed-offset forms match (there is no writeback). Reserved sizes and /// duplicate LDNP destinations are errors; STNP may repeat a source. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if word & CLASS_MASK != NON_TEMPORAL_PAIR_CLASS { return None; } @@ -58,14 +58,14 @@ pub fn decode(word: u32) -> Option> { LDNP_D => (true, QWORD_BYTES, true), STNP_Q => (false, VECTOR_BYTES, true), LDNP_Q => (true, VECTOR_BYTES, true), - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; let first = word & REGISTER_MASK; let second = (word >> SECOND_DATA_SHIFT) & REGISTER_MASK; // LDPOVERLAP allows UNKNOWN/UNDEF/NOP, rather than two ordinary writes. // Decline even two ZRs or two V31s, matching the shared LDP boundary. if load && first == second { - return Some(Err(())); + return Some(Err(Unsupported)); } let immediate = ((word >> IMMEDIATE_SHIFT) & IMMEDIATE_MASK) as i32; let signed = (immediate << IMMEDIATE_SIGN_SHIFT) >> IMMEDIATE_SIGN_SHIFT; @@ -114,7 +114,7 @@ mod tests { for base in 0..=REGISTER_MASK { let result = decode(word(form, 0, [first, second], base)).unwrap(); if load && first == second { - assert_eq!(result, Err(())); + assert_eq!(result, Err(Unsupported)); continue; } assert_eq!( @@ -153,7 +153,10 @@ mod tests { for form in [ 0x68000000, 0x68400000, 0xe8000000, 0xe8400000, 0xec000000, 0xec400000, ] { - assert_eq!(decode(form | (1 << SECOND_DATA_SHIFT)), Some(Err(()))); + assert_eq!( + decode(form | (1 << SECOND_DATA_SHIFT)), + Some(Err(Unsupported)) + ); } for (form, _, _, _) in FORMS { for fixed_bit in [23, 24, 25, 27, 28, 29] { diff --git a/crates/stela-compiler/src/aarch64/prefetch.rs b/crates/stela-compiler/src/aarch64/prefetch.rs index 9801690334..100efb1167 100644 --- a/crates/stela-compiler/src/aarch64/prefetch.rs +++ b/crates/stela-compiler/src/aarch64/prefetch.rs @@ -1,6 +1,7 @@ //! PRFM and PRFUM. use super::{Register, register, register_offset::IndexExtend}; use crate::GuestAddress; +use crate::aarch64::Unsupported; const HINT_MASK: u32 = 31; const REGISTER_SHIFT: u32 = 5; @@ -62,8 +63,7 @@ pub struct Operand { /// No prefetch form checks SP alignment or updates registers. AddressAdd is /// modulo 64 bits in the ordinary-RAM profile with checked arithmetic disabled. /// Register Rt=11xxx belongs to RPRFM, whose metadata semantics stay unsupported. -#[allow(clippy::result_unit_err)] -pub fn decode(pc: GuestAddress, word: u32) -> Option> { +pub fn decode(pc: GuestAddress, word: u32) -> Option> { let base = register((word >> REGISTER_SHIFT) & HINT_MASK, true); let address = if word & UNSIGNED_MASK == UNSIGNED_FORM { Address::Immediate { @@ -84,7 +84,7 @@ pub fn decode(pc: GuestAddress, word: u32) -> Option> { return None; } let Some(extend) = IndexExtend::decode((word >> EXTEND_SHIFT) & EXTEND_MASK) else { - return Some(Err(())); + return Some(Err(Unsupported)); }; Address::Register { base, @@ -176,7 +176,7 @@ mod tests { if hint >= 24 { assert_eq!(decoded, None); } else if option & 2 == 0 { - assert_eq!(decoded, Some(Err(()))); + assert_eq!(decoded, Some(Err(Unsupported))); } else { let operand = decoded.unwrap().unwrap(); assert_eq!(operand.hint.encoding(), hint as u8); diff --git a/crates/stela-compiler/src/aarch64/register_offset.rs b/crates/stela-compiler/src/aarch64/register_offset.rs index 174e1f0c87..621118b939 100644 --- a/crates/stela-compiler/src/aarch64/register_offset.rs +++ b/crates/stela-compiler/src/aarch64/register_offset.rs @@ -1,5 +1,6 @@ //! Integer loads and stores with register-offset addressing. use super::{MemoryTransfer, Register, Width, register}; +use crate::aarch64::Unsupported; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum IndexExtend { @@ -38,8 +39,7 @@ pub struct Operand { /// None means another encoding class; Err means a reserved/unsupported form /// within the scalar register-offset class. SIMD and atomics never match. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if word & 0x3f200c00 != 0x38200800 { return None; } @@ -58,10 +58,10 @@ pub fn decode(word: u32) -> Option> { signed: true, width: Width::W32, }, - _ => return Some(Err(())), // PRFM and reserved signed sizes + _ => return Some(Err(Unsupported)), // PRFM and reserved signed sizes }; let Some(extend) = IndexExtend::decode((word >> 13) & 7) else { - return Some(Err(())); // sub-word index extensions are undefined + return Some(Err(Unsupported)); // sub-word index extensions are undefined }; Some(Ok(Operand { transfer, diff --git a/crates/stela-compiler/src/aarch64/simd.rs b/crates/stela-compiler/src/aarch64/simd.rs index 2f51a1e6be..ce34a1d1dd 100644 --- a/crates/stela-compiler/src/aarch64/simd.rs +++ b/crates/stela-compiler/src/aarch64/simd.rs @@ -1,6 +1,7 @@ //! AdvSIMD and FP: register transfers (LDR/STR/LDUR/STUR/LDP/STP), MOVI and the //! shared operand types of the SIMD families. use super::{AddressMode, Register, register}; +use crate::aarch64::Unsupported; pub mod aes; pub mod arithmetic; pub mod bfloat16; @@ -126,8 +127,7 @@ pub enum Operand { /// None means another encoding class; Err means an unsupported or reserved /// member. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if let Some(operand) = lut::decode(word) { return Some(Ok(Operand::Lut(operand))); } @@ -207,7 +207,7 @@ pub fn decode(word: u32) -> Option> { return None; } if !scalar && !q && size == 3 { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(Operand::Compare { operation, @@ -258,7 +258,7 @@ pub fn decode(word: u32) -> Option> { 1 << ((word >> 22) & 3) }; if vector_math.is_some() && !q && lane_bytes == 8 { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(Operand::Integer { operation, @@ -275,17 +275,17 @@ pub fn decode(word: u32) -> Option> { 1 => AddressMode::PostIndex, 2 => AddressMode::Offset, 3 => AddressMode::PreIndex, - _ => return Some(Err(())), // non-temporal pairs are a separate class + _ => return Some(Err(Unsupported)), // non-temporal pairs are a separate class }; if opcode == 3 { - return Some(Err(())); + return Some(Err(Unsupported)); } let load = word & (1 << 22) != 0; let vectors = [(word & 31) as u8, ((word >> 10) & 31) as u8]; // LDPOVERLAP allows UNKNOWN, UNDEFINED or NOP, never two ordinary // writes, so every duplicate destination is refused (V31 included). if load && vectors[0] == vectors[1] { - return Some(Err(())); + return Some(Err(Unsupported)); } let bytes = 4u8 << opcode; let immediate = ((word >> 15) & 127) as i32; @@ -320,7 +320,7 @@ pub fn decode(word: u32) -> Option> { let opcode = (word >> 22) & 3; // opc[1] selects Q, whose size field must be 00. if opcode & 2 != 0 && size != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } let scale = if opcode & 2 != 0 { 4 } else { size }; let (displacement, mode) = if unsigned { @@ -330,7 +330,7 @@ pub fn decode(word: u32) -> Option> { 0 => AddressMode::Offset, 1 => AddressMode::PostIndex, 3 => AddressMode::PreIndex, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; let immediate = ((word >> 12) & 511) as i32; ((immediate << 23) >> 23, mode) @@ -345,6 +345,23 @@ pub fn decode(word: u32) -> Option> { })) } +/// The scalar FP `ftype` field and its values. +const FORMAT_SHIFT: u32 = 22; +const FORMAT_SINGLE: u32 = 0; +const FORMAT_DOUBLE: u32 = 1; +const FORMAT_HALF: u32 = 3; + +/// A scalar FP instruction's format from its `ftype` field (bits 22-23). +fn scalar_format(word: u32) -> Result { + use crate::aarch64::floating::Format; + match (word >> FORMAT_SHIFT) & 3 { + FORMAT_SINGLE => Ok(Format::Single), + FORMAT_DOUBLE => Ok(Format::Double), + FORMAT_HALF => Ok(Format::Half), + _ => Err(Unsupported), + } +} + #[cfg(test)] mod tests { use super::*; @@ -368,7 +385,7 @@ mod tests { | if unary { 0 } else { 31 << 16 }; let decoded = decode(word).unwrap(); if q == 0 && size == 3 { - assert_eq!(decoded, Err(())); + assert_eq!(decoded, Err(Unsupported)); } else if let Ok(Operand::Integer { destination, left, @@ -429,7 +446,7 @@ mod tests { if scalar != 0 && (q == 0 || size != 3) { assert!(!matches!(decode(word), Some(Ok(Operand::Compare { .. })))); } else if scalar == 0 && q == 0 && size == 3 { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); } else if let Some(Ok(Operand::Compare { destination, left, @@ -597,11 +614,11 @@ mod tests { fn reserved_sizes_and_adjacent_memory_classes_decline() { for size in 1..4 { for prefix in [0x3d800000, 0x3dc00000, 0x3c800000, 0x3cc00000] { - assert_eq!(decode(prefix | (size << 30)), Some(Err(()))); + assert_eq!(decode(prefix | (size << 30)), Some(Err(Unsupported))); } } - assert_eq!(decode(0x3cc00800), Some(Err(()))); // unprivileged/reserved SIMD mode - assert_eq!(decode(0x3ce00800), Some(Err(()))); // register offset with reserved option 000 + assert_eq!(decode(0x3cc00800), Some(Err(Unsupported))); // unprivileged/reserved SIMD mode + assert_eq!(decode(0x3ce00800), Some(Err(Unsupported))); // register offset with reserved option 000 for word in [0xfd000000 ^ (1 << 26), 0x9c000000, 0xc85f7c00] { assert!(decode(word).is_none()); } @@ -632,7 +649,7 @@ mod tests { | (first << 5) | first; let expected = if load && first == second { - Err(()) + Err(Unsupported) } else { Ok(Operand::MemoryPair { load, @@ -661,10 +678,10 @@ mod tests { for load in [false, true] { for opcode in 0..4 { let prefix = (opcode << 30) | 0x2c000400 | (u32::from(load) << 22); - assert_eq!(decode(prefix), Some(Err(()))); // mode00: STNP/LDNP + assert_eq!(decode(prefix), Some(Err(Unsupported))); // mode00: STNP/LDNP for mode in 1..4 { if opcode == 3 { - assert_eq!(decode(prefix | (mode << 23)), Some(Err(()))); + assert_eq!(decode(prefix | (mode << 23)), Some(Err(Unsupported))); } } } diff --git a/crates/stela-compiler/src/aarch64/simd/aes.rs b/crates/stela-compiler/src/aarch64/simd/aes.rs index 3f62bc34c8..c819685b2b 100644 --- a/crates/stela-compiler/src/aarch64/simd/aes.rs +++ b/crates/stela-compiler/src/aarch64/simd/aes.rs @@ -1,4 +1,5 @@ //! AESE, AESD, AESMC and AESIMC. +use crate::aarch64::Unsupported; const FORM_MASK: u32 = 0xffff_fc00; const AESE: u32 = 0x4e28_4800; @@ -25,8 +26,7 @@ pub struct Operand { /// Only the exact .16B encodings are accepted. Other classes and reserved size /// encodings decline and retain the shared decoder's unsupported failure. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let kind = match word & FORM_MASK { AESE => Kind::Encrypt, AESD => Kind::Decrypt, diff --git a/crates/stela-compiler/src/aarch64/simd/arithmetic.rs b/crates/stela-compiler/src/aarch64/simd/arithmetic.rs index a1108a661c..1969fe8917 100644 --- a/crates/stela-compiler/src/aarch64/simd/arithmetic.rs +++ b/crates/stela-compiler/src/aarch64/simd/arithmetic.rs @@ -1,4 +1,5 @@ //! FP arithmetic: scalar, vector, indexed and pairwise FADD/FSUB/FMUL/FDIV/FMULX/FABD. +use crate::aarch64::Unsupported; use crate::aarch64::floating::{BinaryOperation, Format}; const SCALAR_MASK: u32 = 0xff20_fc00; @@ -132,8 +133,7 @@ fn vector_shape(word: u32) -> Shape { /// None is another family; Err is reserved scalar ftype, vector1D, Half scalar /// pair size or indexed Double/L. All ordinary V0–V31 roles are data; indexed /// Half Vm permits only V0–V15 and all eight source indices, including under Q=0. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { decode_scalar(word) .or_else(|| decode_vector(word)) .or_else(|| decode_simd_scalar(word)) @@ -141,7 +141,7 @@ pub fn decode(word: u32) -> Option> { .or_else(|| decode_indexed(word)) } -fn decode_scalar(word: u32) -> Option> { +fn decode_scalar(word: u32) -> Option> { let operation = match word & SCALAR_MASK { FADD => BinaryOperation::Add, FSUB => BinaryOperation::Subtract, @@ -154,7 +154,7 @@ fn decode_scalar(word: u32) -> Option> { FORMAT_SINGLE => Format::Single, FORMAT_DOUBLE => Format::Double, FORMAT_HALF => Format::Half, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; Some(Ok(Operand { operation, @@ -165,7 +165,7 @@ fn decode_scalar(word: u32) -> Option> { })) } -fn decode_vector(word: u32) -> Option> { +fn decode_vector(word: u32) -> Option> { let (operation, half, pairwise) = match word & VECTOR_HALF_MASK { VECTOR_HALF_FADD => (BinaryOperation::Add, true, false), VECTOR_HALF_FSUB => (BinaryOperation::Subtract, true, false), @@ -194,7 +194,7 @@ fn decode_vector(word: u32) -> Option> { Format::Single }; if format == Format::Double && shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } Some(Ok(Operand { operation, @@ -212,7 +212,7 @@ fn decode_vector(word: u32) -> Option> { })) } -fn decode_simd_scalar(word: u32) -> Option> { +fn decode_simd_scalar(word: u32) -> Option> { let (operation, half) = match word & SIMD_SCALAR_HALF_MASK { SCALAR_HALF_FABD => (BinaryOperation::AbsoluteDifference, true), SCALAR_HALF_FMULX => (BinaryOperation::MultiplyExtended, true), @@ -238,7 +238,7 @@ fn decode_simd_scalar(word: u32) -> Option> { })) } -fn decode_pairwise_scalar(word: u32) -> Option> { +fn decode_pairwise_scalar(word: u32) -> Option> { let format = match word & PAIR_SCALAR_MASK { SCALAR_FADDP => { if word & VECTOR_DOUBLE == 0 { @@ -249,7 +249,7 @@ fn decode_pairwise_scalar(word: u32) -> Option> { } SCALAR_HALF_FADDP => { if word & VECTOR_DOUBLE != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } Format::Half } @@ -266,7 +266,7 @@ fn decode_pairwise_scalar(word: u32) -> Option> { })) } -fn decode_indexed(word: u32) -> Option> { +fn decode_indexed(word: u32) -> Option> { let (half, shape) = if word & INDEXED_SCALAR_HALF_MASK == INDEXED_SCALAR_HALF { (true, Shape::Scalar) } else if word & INDEXED_SCALAR_MASK == INDEXED_SCALAR { @@ -295,7 +295,7 @@ fn decode_indexed(word: u32) -> Option> { ) } else { if low != 0 || shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } (Format::Double, register(word, RIGHT_SHIFT), high) }; @@ -372,7 +372,7 @@ mod tests { for destination in 0..=REGISTER_MASK { for left in 0..=REGISTER_MASK { for right in 0..=REGISTER_MASK { - let expected = format.map_or(Err(()), |format| { + let expected = format.map_or(Err(Unsupported), |format| { Ok(Operand { operation, format, @@ -424,7 +424,7 @@ mod tests { | destination; let expected = if format == Format::Double && shape == Shape::Vector64 { - Err(()) + Err(Unsupported) } else { let inputs = if ordinary == VECTOR_FADDP { Inputs::Pairwise { @@ -530,7 +530,7 @@ mod tests { | destination | (source << LEFT_SHIFT) ), - Some(Err(())) + Some(Err(Unsupported)) ); } } @@ -635,9 +635,12 @@ mod tests { | (right << RIGHT_SHIFT) | destination | (left << LEFT_SHIFT); - assert_eq!(decode(word | (1 << INDEX_L_SHIFT)), Some(Err(()))); + assert_eq!( + decode(word | (1 << INDEX_L_SHIFT)), + Some(Err(Unsupported)) + ); if base == INDEXED_VECTOR { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); } } } diff --git a/crates/stela-compiler/src/aarch64/simd/bfloat16.rs b/crates/stela-compiler/src/aarch64/simd/bfloat16.rs index 5c6537e85a..b6e86f43e1 100644 --- a/crates/stela-compiler/src/aarch64/simd/bfloat16.rs +++ b/crates/stela-compiler/src/aarch64/simd/bfloat16.rs @@ -1,5 +1,6 @@ //! AdvSIMD BF16: BFCVT, BFCVTN, BFDOT, BFMMLA and BFMLAL. use super::arithmetic::Shape; +use crate::aarch64::Unsupported; const SCALAR_MASK: u32 = 0xffff_fc00; const BFCVT: u32 = 0x1e63_4000; @@ -103,8 +104,7 @@ pub enum Operand { /// The masks match only this family's formats. Indexed multiplies accept only /// V0-V15. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { decode_conversion(word) .or_else(|| decode_dot(word)) .or_else(|| decode_multiply(word)) diff --git a/crates/stela-compiler/src/aarch64/simd/comparison.rs b/crates/stela-compiler/src/aarch64/simd/comparison.rs index 045da5d496..008a418d6b 100644 --- a/crates/stela-compiler/src/aarch64/simd/comparison.rs +++ b/crates/stela-compiler/src/aarch64/simd/comparison.rs @@ -1,4 +1,6 @@ //! FCMP/FCCMP and AdvSIMD FCMEQ/FCMGE/FCMGT/FACGE/FACGT. +use super::scalar_format; +use crate::aarch64::Unsupported; use crate::aarch64::floating::{Format, comparison::Predicate}; use super::arithmetic::Shape; @@ -6,11 +8,6 @@ use super::arithmetic::Shape; const REGISTER_MASK: u32 = 31; const LEFT_SHIFT: u32 = 5; const RIGHT_SHIFT: u32 = 16; -const FORMAT_SHIFT: u32 = 22; -const FORMAT_MASK: u32 = 3; -const FORMAT_SINGLE: u32 = 0; -const FORMAT_DOUBLE: u32 = 1; -const FORMAT_HALF: u32 = 3; const VECTOR_Q: u32 = 1 << 30; const SIMD_DOUBLE: u32 = 1 << 22; const SIMD_SCALAR_PREFIX: u32 = 0x50000000; @@ -92,20 +89,10 @@ fn register(word: u32, shift: u32) -> u8 { ((word >> shift) & REGISTER_MASK) as u8 } -fn scalar_format(word: u32) -> Result { - match (word >> FORMAT_SHIFT) & FORMAT_MASK { - FORMAT_SINGLE => Ok(Format::Single), - FORMAT_DOUBLE => Ok(Format::Double), - FORMAT_HALF => Ok(Format::Half), - _ => Err(()), - } -} - /// None denotes another family; Err denotes reserved scalar ftype or vector1D. /// Every register field is an ordinary V register, including V31. The Rm field /// remains unconstrained and ignored in FCMP/FCMPE zero encodings. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if word & FLAGS_MASK == FCMP { return Some(scalar_format(word).map(|format| Operand::Flags { format, @@ -144,7 +131,7 @@ fn predicate(opcode: u32, zero: bool) -> Option { }) } -fn decode_predicate(word: u32, zero: bool) -> Option> { +fn decode_predicate(word: u32, zero: bool) -> Option> { let (scalar_mask, vector_mask, scalar_half_mask, vector_half_mask, half_adjustment) = if zero { ( ZERO_SCALAR_MASK, @@ -191,7 +178,7 @@ fn decode_predicate(word: u32, zero: bool) -> Option> { Shape::Vector128 }; if format == Format::Double && shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(Operand::Predicate { operation, @@ -212,6 +199,7 @@ fn decode_predicate(word: u32, zero: bool) -> Option> { #[cfg(test)] mod tests { use super::*; + use crate::aarch64::simd::{FORMAT_DOUBLE, FORMAT_HALF, FORMAT_SHIFT, FORMAT_SINGLE}; const FORMATS: [(u32, Format); 3] = [ (FORMAT_SINGLE, Format::Single), @@ -372,12 +360,12 @@ mod tests { for signal in [0, SIGNAL_ALL_NANS] { assert_eq!( decode(opcode | signal | (RESERVED_FORMAT << FORMAT_SHIFT)), - Some(Err(())) + Some(Err(Unsupported)) ); } } for (opcode, _) in REGISTER_OPERATIONS.into_iter().chain(ZERO_OPERATIONS) { - assert_eq!(decode(opcode | SIMD_DOUBLE), Some(Err(()))); + assert_eq!(decode(opcode | SIMD_DOUBLE), Some(Err(Unsupported))); } for (opcode, _) in ZERO_OPERATIONS { for right in 1..=REGISTER_MASK { diff --git a/crates/stela-compiler/src/aarch64/simd/complex.rs b/crates/stela-compiler/src/aarch64/simd/complex.rs index 254810a85a..5271bf193f 100644 --- a/crates/stela-compiler/src/aarch64/simd/complex.rs +++ b/crates/stela-compiler/src/aarch64/simd/complex.rs @@ -1,4 +1,5 @@ //! FCADD and FCMLA. +use crate::aarch64::Unsupported; use crate::aarch64::floating::{Format, complex::Rotation}; use super::arithmetic::Shape; @@ -57,8 +58,7 @@ pub struct Operand { /// None denotes another family; Err denotes reserved size, width or pair index. /// All register fields, including indexed Half Vm, denote ordinary V0..V31. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let (kind, rotation, indexed) = if word & ADD_MASK == FCADD { ( Kind::Add, @@ -93,7 +93,7 @@ pub fn decode(word: u32) -> Option> { SIZE_HALF => Format::Half, SIZE_SINGLE => Format::Single, SIZE_DOUBLE if !indexed && shape == Shape::Vector128 => Format::Double, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; let right = register(word, RIGHT_SHIFT); let right = if indexed { @@ -103,12 +103,12 @@ pub fn decode(word: u32) -> Option> { // size 01; the decoder follows the specification as written. let index = if format == Format::Half { if shape == Shape::Vector64 && high != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } (high << HALF_PAIR_INDEX_HIGH_SHIFT) | low } else { if shape == Shape::Vector64 || low != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } high }; @@ -300,9 +300,15 @@ mod tests { for (q, _) in SHAPES { for right in 0..=REGISTER_MASK { let base = encoding | q | (right << RIGHT_SHIFT) | REGISTER_MASK; - assert_eq!(decode(base | (SIZE_RESERVED << SIZE_SHIFT)), Some(Err(()))); + assert_eq!( + decode(base | (SIZE_RESERVED << SIZE_SHIFT)), + Some(Err(Unsupported)) + ); if encoding == INDEXED_FCMLA || q == 0 { - assert_eq!(decode(base | (SIZE_DOUBLE << SIZE_SHIFT)), Some(Err(()))); + assert_eq!( + decode(base | (SIZE_DOUBLE << SIZE_SHIFT)), + Some(Err(Unsupported)) + ); } } } @@ -312,18 +318,18 @@ mod tests { let indexes = (high << INDEX_H_SHIFT) | (low << INDEX_L_SHIFT); assert_eq!( decode(INDEXED_FCMLA | (SIZE_SINGLE << SIZE_SHIFT) | indexes), - Some(Err(())) + Some(Err(Unsupported)) ); if low != 0 { assert_eq!( decode(INDEXED_FCMLA | (SIZE_SINGLE << SIZE_SHIFT) | VECTOR_Q | indexes), - Some(Err(())) + Some(Err(Unsupported)) ); } if high != 0 { assert_eq!( decode(INDEXED_FCMLA | (SIZE_HALF << SIZE_SHIFT) | indexes), - Some(Err(())) + Some(Err(Unsupported)) ); } } diff --git a/crates/stela-compiler/src/aarch64/simd/conversion.rs b/crates/stela-compiler/src/aarch64/simd/conversion.rs index 4d0e3aef15..4a23a49b7b 100644 --- a/crates/stela-compiler/src/aarch64/simd/conversion.rs +++ b/crates/stela-compiler/src/aarch64/simd/conversion.rs @@ -1,4 +1,5 @@ //! Scalar and AdvSIMD conversions between H/S/D and integers (FCVT*, SCVTF, UCVTF). +use crate::aarch64::Unsupported; use crate::aarch64::{ Register, floating::{ @@ -199,12 +200,12 @@ fn general_register(value: u8) -> Register { } } -fn format(field: u32) -> Result { +fn format(field: u32) -> Result { match field { FORMAT_SINGLE => Ok(Format::Single), FORMAT_DOUBLE => Ok(Format::Double), FORMAT_HALF => Ok(Format::Half), - _ => Err(()), + _ => Err(Unsupported), } } @@ -227,8 +228,7 @@ fn integer_width(format: Format) -> IntegerWidth { /// None denotes another family, including FPRCVT/FP8. Err denotes a reserved /// field combination in a recognized classic conversion class. All GPR 31 /// operands are ZR; all SIMD 31 operands are ordinary V31. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { decode_precision(word) .or_else(|| decode_general(word)) .or_else(|| decode_simd(word)) @@ -242,21 +242,21 @@ pub fn decode(word: u32) -> Option> { }) } -fn decode_precision(word: u32) -> Option> { +fn decode_precision(word: u32) -> Option> { if word & SCALAR_EXACT_MASK == BFCVT { return None; } let mode = if word & SCALAR_PRECISION_MASK == SCALAR_FCVT { let source = match format((word >> FORMAT_SHIFT) & FORMAT_MASK) { Ok(format) => format, - Err(()) => return Some(Err(())), + Err(Unsupported) => return Some(Err(Unsupported)), }; let destination = match format((word >> DESTINATION_FORMAT_SHIFT) & FORMAT_MASK) { Ok(format) => format, - Err(()) => return Some(Err(())), + Err(Unsupported) => return Some(Err(Unsupported)), }; if source == destination { - return Some(Err(())); + return Some(Err(Unsupported)); } PrecisionMode::Scalar { source, @@ -313,7 +313,7 @@ fn general_direction(opcode: u32) -> Option { }) } -fn decode_general(word: u32) -> Option> { +fn decode_general(word: u32) -> Option> { let (direction, fixed) = if let Some(direction) = general_direction(word & GENERAL_INTEGER_MASK) { (direction, false) @@ -326,13 +326,13 @@ fn decode_general(word: u32) -> Option> { }; let format = match format((word >> FORMAT_SHIFT) & FORMAT_MASK) { Ok(format) => format, - Err(()) => return Some(Err(())), + Err(Unsupported) => return Some(Err(Unsupported)), }; let wide = word & GENERAL_WIDE != 0; let frac_bits = if fixed { let scale = (word >> SCALE_SHIFT) & SCALE_MASK; if !wide && scale < IMMEDIATE_SINGLE_MINIMUM { - return Some(Err(())); + return Some(Err(Unsupported)); } (SCALE_BIAS - scale) as u8 } else { @@ -374,7 +374,7 @@ fn simd_direction(opcode: u32) -> Option { }) } -fn decode_simd(word: u32) -> Option> { +fn decode_simd(word: u32) -> Option> { for (mask, adjustment, scalar, half) in [ (SIMD_SCALAR_MASK, SIMD_SCALAR_PREFIX, true, false), (SIMD_VECTOR_MASK, 0, false, false), @@ -417,7 +417,7 @@ fn decode_simd(word: u32) -> Option> { IMMEDIATE_DOUBLE_MINIMUM..=IMMEDIATE_MASK => Format::Double, IMMEDIATE_SINGLE_MINIMUM..IMMEDIATE_DOUBLE_MINIMUM => Format::Single, IMMEDIATE_HALF_MINIMUM..IMMEDIATE_SINGLE_MINIMUM => Format::Half, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; let frac_bits = (2 * format.bits() - immediate) as u8; return Some(simd_operand(word, direction, format, scalar, frac_bits)); @@ -431,14 +431,14 @@ fn simd_operand( format: Format, scalar: bool, frac_bits: u8, -) -> Result { +) -> Result { let shape = if scalar { Shape::Scalar } else { vector_shape(word) }; if format == Format::Double && shape == Shape::Vector64 { - return Err(()); + return Err(Unsupported); } let destination = vector_register(word, 0); let source = vector_register(word, SOURCE_SHIFT); @@ -598,7 +598,7 @@ mod tests { | (source_field << FORMAT_SHIFT) | (destination_field << DESTINATION_FORMAT_SHIFT); if source == destination { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); } else { precision( word, @@ -800,7 +800,7 @@ mod tests { for wide in [0, GENERAL_WIDE] { assert_eq!( decode(opcode | signed | wide | (FORMAT_RESERVED << FORMAT_SHIFT)), - Some(Err(())) + Some(Err(Unsupported)) ); } } @@ -813,21 +813,24 @@ mod tests { decode( opcode | signed | (field << FORMAT_SHIFT) | (scale << SCALE_SHIFT) ), - Some(Err(())) + Some(Err(Unsupported)) ); } } for wide in [0, GENERAL_WIDE] { assert_eq!( decode(opcode | signed | wide | (FORMAT_RESERVED << FORMAT_SHIFT)), - Some(Err(())) + Some(Err(Unsupported)) ); } } } for (opcode, _) in SIMD_OPERATIONS { for signed in [0, SIMD_UNSIGNED] { - assert_eq!(decode(opcode | signed | SIMD_DOUBLE), Some(Err(()))); + assert_eq!( + decode(opcode | signed | SIMD_DOUBLE), + Some(Err(Unsupported)) + ); } } for opcode in [SIMD_FIXED_SCVTF, SIMD_FIXED_FCVTZS] { @@ -842,14 +845,14 @@ mod tests { for immediate in IMMEDIATE_SHIFT_CLASS_MINIMUM..IMMEDIATE_HALF_MINIMUM { assert_eq!( decode(opcode | signed | prefix | (immediate << IMMEDIATE_SHIFT)), - Some(Err(())) + Some(Err(Unsupported)) ); } } for immediate in IMMEDIATE_DOUBLE_MINIMUM..=IMMEDIATE_MASK { assert_eq!( decode(opcode | signed | (immediate << IMMEDIATE_SHIFT)), - Some(Err(())) + Some(Err(Unsupported)) ); } } @@ -861,7 +864,7 @@ mod tests { | (FORMAT_RESERVED << FORMAT_SHIFT) | (destination << DESTINATION_FORMAT_SHIFT) ), - Some(Err(())) + Some(Err(Unsupported)) ); } } @@ -890,7 +893,7 @@ mod tests { #[test] fn modified_immediates_keep_their_existing_decoder_and_compiler_paths() { - use crate::{GuestAddress, Lifter, aarch64, block}; + use crate::{GuestAddress, Lifter, aarch64}; const MODIFIED_IMMEDIATE: u32 = 0x0f000400; const CMODE_SHIFT: u32 = 12; @@ -941,11 +944,11 @@ mod tests { let mut source = word.to_le_bytes().to_vec(); source.extend(RETURN_X30.to_le_bytes()); assert!( - crate::compile(&source, BASE).is_ok(), + crate::testing::leaf(&source, BASE).is_ok(), "word={word:08x}" ); assert!( - block::compile(&source, BASE).is_ok(), + crate::testing::block(&source, BASE).is_ok(), "word={word:08x}" ); compiled += 1; diff --git a/crates/stela-compiler/src/aarch64/simd/estimate.rs b/crates/stela-compiler/src/aarch64/simd/estimate.rs index 286b9a1bf9..9f552a2339 100644 --- a/crates/stela-compiler/src/aarch64/simd/estimate.rs +++ b/crates/stela-compiler/src/aarch64/simd/estimate.rs @@ -1,4 +1,5 @@ //! FRECPE, FRSQRTE and FRECPX. +use crate::aarch64::Unsupported; use crate::aarch64::floating::Format; use super::arithmetic::Shape; @@ -67,8 +68,7 @@ fn vector_shape(word: u32) -> Shape { /// None denotes another family; Err denotes floating vector1D or unsigned sz1. /// FRECPX is scalar only. All registers, including V31, are ordinary vector data. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let unsigned = match word & VECTOR_MASK { URECPE => Some(Kind::UnsignedReciprocal), URSQRTE => Some(Kind::UnsignedReciprocalSquareRoot), @@ -76,7 +76,7 @@ pub fn decode(word: u32) -> Option> { }; if let Some(kind) = unsigned { if word & DOUBLE_SIZE != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(operand(word, kind, Format::Single, vector_shape(word)))); } @@ -110,7 +110,7 @@ pub fn decode(word: u32) -> Option> { vector_shape(word) }; if format == Format::Double && shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(operand(word, kind, format, shape))); } @@ -176,7 +176,7 @@ mod tests { continue; } if format == Format::Double && shape == Shape::Vector64 { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); continue; } check_registers(word, kind, format, shape); @@ -202,7 +202,7 @@ mod tests { decode( opcode | q | DOUBLE_SIZE | destination | (source << SOURCE_SHIFT) ), - Some(Err(())) + Some(Err(Unsupported)) ); } } @@ -222,7 +222,7 @@ mod tests { for source in 0..=REGISTER_MASK { assert_eq!( decode(opcode | DOUBLE_SIZE | destination | (source << SOURCE_SHIFT)), - Some(Err(())) + Some(Err(Unsupported)) ); } } diff --git a/crates/stela-compiler/src/aarch64/simd/extrema_scale.rs b/crates/stela-compiler/src/aarch64/simd/extrema_scale.rs index 441ceeb01e..70c08259f0 100644 --- a/crates/stela-compiler/src/aarch64/simd/extrema_scale.rs +++ b/crates/stela-compiler/src/aarch64/simd/extrema_scale.rs @@ -1,4 +1,5 @@ //! AdvSIMD FAMIN/FAMAX (FEAT_FAMINMAX) and FSCALE (FEAT_FP8). +use crate::aarch64::Unsupported; use crate::aarch64::floating::{Format, absolute_minmax::AbsoluteMinMaxOperation}; use super::arithmetic::Shape; @@ -35,8 +36,7 @@ pub struct Operand { /// V31 is ordinary data in every position. Q=0 writes clear the upper 64 bits. /// The one-double arrangement is reserved; scalar/pairwise neighbors decline. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { for (mask, half) in [(HALF_MASK, true), (ORDINARY_MASK, false)] { let kind = match (word & mask, half) { (HALF_FAMAX, true) | (FAMAX, false) => Kind::Absolute(AbsoluteMinMaxOperation::Maximum), @@ -57,7 +57,7 @@ pub fn decode(word: u32) -> Option> { Shape::Vector128 }; if format == Format::Double && shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(Operand { kind, @@ -109,7 +109,7 @@ mod tests { let word = base | q | destination | (left << LEFT_SHIFT) | (right << RIGHT_SHIFT); let expected = if format == Format::Double && shape == Shape::Vector64 { - Err(()) + Err(Unsupported) } else { Ok(Operand { kind, diff --git a/crates/stela-compiler/src/aarch64/simd/floating.rs b/crates/stela-compiler/src/aarch64/simd/floating.rs index 0934a55a88..fdf64d5e42 100644 --- a/crates/stela-compiler/src/aarch64/simd/floating.rs +++ b/crates/stela-compiler/src/aarch64/simd/floating.rs @@ -1,4 +1,5 @@ //! FCSEL, FABS and FNEG, including FPCR.AH/NEP behavior. +use crate::aarch64::Unsupported; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SignOperation { @@ -37,17 +38,16 @@ const VECTOR_FLOAT_MASK: u32 = 0xbfbf_fc00; const VECTOR_FLOAT_ABS: u32 = 0x0ea0_f800; const VECTOR_FLOAT_NEG: u32 = 0x2ea0_f800; -fn scalar_lane(word: u32) -> Result { +fn scalar_lane(word: u32) -> Result { match (word >> 22) & 3 { 0 => Ok(4), 1 => Ok(8), 3 => Ok(2), - _ => Err(()), + _ => Err(Unsupported), } } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let destination = (word & 31) as u8; let source = ((word >> 5) & 31) as u8; if word & SELECT_MASK == SELECT { @@ -92,7 +92,7 @@ pub fn decode(word: u32) -> Option> { 4 << ((word >> 22) & 1) }; if lane_bytes == 8 && bytes == 8 { - return Some(Err(())); + return Some(Err(Unsupported)); } Some(Ok(Operand::Sign { operation, @@ -143,10 +143,10 @@ mod tests { } } for base in [SELECT, SCALAR_ABS, SCALAR_NEG] { - assert_eq!(decode(base | (2 << 22)), Some(Err(()))); + assert_eq!(decode(base | (2 << 22)), Some(Err(Unsupported))); } for base in [VECTOR_FLOAT_ABS, VECTOR_FLOAT_NEG] { - assert_eq!(decode(base | (1 << 22)), Some(Err(()))); + assert_eq!(decode(base | (1 << 22)), Some(Err(Unsupported))); assert!(matches!( decode(base | (1 << 22) | (1 << 30)), Some(Ok(Operand::Sign { diff --git a/crates/stela-compiler/src/aarch64/simd/fused.rs b/crates/stela-compiler/src/aarch64/simd/fused.rs index 3d78ec4267..7380a82327 100644 --- a/crates/stela-compiler/src/aarch64/simd/fused.rs +++ b/crates/stela-compiler/src/aarch64/simd/fused.rs @@ -1,4 +1,5 @@ //! FMADD/FMSUB/FNMADD/FNMSUB and AdvSIMD FMLA/FMLS. +use crate::aarch64::Unsupported; use crate::aarch64::floating::{Format, fused::FusedOperation}; use super::arithmetic::Shape; @@ -58,8 +59,7 @@ pub struct Operand { /// None is another family; Err is reserved scalar ftype, vector 1D or indexed D/L. /// Register fields denote ordinary V registers; indexed H permits only V0–V15. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { decode_scalar(word) .or_else(|| decode_vector(word)) .or_else(|| decode_indexed(word)) @@ -77,7 +77,7 @@ fn vector_shape(word: u32) -> Shape { } } -fn decode_scalar(word: u32) -> Option> { +fn decode_scalar(word: u32) -> Option> { let operation = match word & SCALAR_MASK { FMADD => FusedOperation::Add, FMSUB => FusedOperation::Subtract, @@ -89,7 +89,7 @@ fn decode_scalar(word: u32) -> Option> { FORMAT_SINGLE => Format::Single, FORMAT_DOUBLE => Format::Double, FORMAT_HALF => Format::Half, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; Some(Ok(Operand { operation, @@ -103,7 +103,7 @@ fn decode_scalar(word: u32) -> Option> { })) } -fn decode_vector(word: u32) -> Option> { +fn decode_vector(word: u32) -> Option> { let half_operation = match word & VECTOR_HALF_MASK { VECTOR_HALF_FMLA => Some(FusedOperation::Add), VECTOR_HALF_FMLS => Some(FusedOperation::Subtract), @@ -122,7 +122,7 @@ fn decode_vector(word: u32) -> Option> { Format::Single } else { if shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } Format::Double }; @@ -141,7 +141,7 @@ fn decode_vector(word: u32) -> Option> { })) } -fn decode_indexed(word: u32) -> Option> { +fn decode_indexed(word: u32) -> Option> { let (half, shape) = if word & INDEXED_SCALAR_HALF_MASK == INDEXED_SCALAR_HALF { (true, Shape::Scalar) } else if word & INDEXED_SCALAR_MASK == INDEXED_SCALAR { @@ -170,7 +170,7 @@ fn decode_indexed(word: u32) -> Option> { ) } else { if low != 0 || shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } (Format::Double, register(word, RIGHT_SHIFT), high) }; @@ -229,7 +229,7 @@ mod tests { | (addend << ADDEND_SHIFT) | (left << LEFT_SHIFT) | destination; - let expected = format.map_or(Err(()), |format| { + let expected = format.map_or(Err(Unsupported), |format| { Ok(Operand { operation, format, @@ -272,7 +272,7 @@ mod tests { | destination; let expected = if format == Format::Double && shape == Shape::Vector64 { - Err(()) + Err(Unsupported) } else { Ok(Operand { operation, @@ -347,7 +347,7 @@ mod tests { let expected = if format == Format::Double && (l != 0 || shape == Shape::Vector64) { - Err(()) + Err(Unsupported) } else { Ok(Operand { operation, diff --git a/crates/stela-compiler/src/aarch64/simd/halving.rs b/crates/stela-compiler/src/aarch64/simd/halving.rs index 37b6848f65..0e4efcc94b 100644 --- a/crates/stela-compiler/src/aarch64/simd/halving.rs +++ b/crates/stela-compiler/src/aarch64/simd/halving.rs @@ -1,4 +1,5 @@ //! Halving arithmetic (SHADD, URHADD, ...), narrowing and pairwise widening. +use crate::aarch64::Unsupported; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { Half { @@ -51,8 +52,7 @@ const UNSIGNED_ACC_PAIR_LONG: u32 = 0x2e206800; const TRUNCATE: u32 = 0x0e212800; const SHIFT_LONG: u32 = 0x2e213800; -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let q = word & (1 << 30) != 0; let opcode = word & SAME_MASK; let kind = match opcode { @@ -88,7 +88,7 @@ pub fn decode(word: u32) -> Option> { })?; let size = (word >> 22) & 3; if size == 3 { - return Some(Err(())); + return Some(Err(Unsupported)); } let bytes = if matches!(kind, Kind::HighNarrow { .. } | Kind::Truncate { .. }) || (!q && !matches!(kind, Kind::ShiftLong { .. })) diff --git a/crates/stela-compiler/src/aarch64/simd/i8mm.rs b/crates/stela-compiler/src/aarch64/simd/i8mm.rs index bdf9245190..5eee63b9c0 100644 --- a/crates/stela-compiler/src/aarch64/simd/i8mm.rs +++ b/crates/stela-compiler/src/aarch64/simd/i8mm.rs @@ -1,5 +1,6 @@ //! FEAT_I8MM: SMMLA, UMMLA, USMMLA, USDOT and SUDOT. use super::arithmetic::Shape; +use crate::aarch64::Unsupported; const REGISTER_MASK: u32 = 31; const DESTINATION_SHIFT: u32 = 0; @@ -115,8 +116,7 @@ impl Encoding { } } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let (_, _, kind, indexed) = Encoding::ALL .iter() .map(|encoding| encoding.facts()) diff --git a/crates/stela-compiler/src/aarch64/simd/immediates.rs b/crates/stela-compiler/src/aarch64/simd/immediates.rs index 295028a67b..6c65e1f5b8 100644 --- a/crates/stela-compiler/src/aarch64/simd/immediates.rs +++ b/crates/stela-compiler/src/aarch64/simd/immediates.rs @@ -1,6 +1,7 @@ //! Modified immediates (MOVI, MVNI, ORR, BIC, FMOV) and FP register moves. use super::super::register; use super::rearrange::{LaneSource, Operand as LaneMove}; +use crate::aarch64::Unsupported; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ConstantOperation { @@ -58,8 +59,7 @@ fn float_immediate(imm: u8, bytes: u8) -> u64 { | (u64::from(imm & 15) << (fraction_bits - 4)) } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let d = (word & 31) as u8; let n = ((word >> 5) & 31) as u8; let scalar_float = match word & SCALAR_FLOAT_MASK { @@ -145,7 +145,7 @@ pub fn decode(word: u32) -> Option> { let bytes = if q { 16 } else { 8 }; if half { if op || cmode != 15 { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(Operand::Constant { destination: d, @@ -159,7 +159,7 @@ pub fn decode(word: u32) -> Option> { } // Existing D/2D MOVI byte-mask lowering. if cmode == 15 { if op && !q { - return Some(Err(())); + return Some(Err(Unsupported)); } let lane = if op { 8 } else { 4 }; return Some(Ok(Operand::Constant { @@ -219,7 +219,7 @@ mod tests { })) ); } - assert_eq!(decode(0x2f00f400), Some(Err(()))); // vector double requires Q=1 + assert_eq!(decode(0x2f00f400), Some(Err(Unsupported))); // vector double requires Q=1 assert!(decode(0x1ea01000).is_none()); // reserved scalar ftype assert!(decode(0x9e260000).is_none()); // numerical conversion is not a bit move } @@ -231,7 +231,7 @@ mod tests { if cmode == 14 && op == 1 { assert!(decode(word).is_none()); } else if cmode == 15 && op == 1 { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); } else { assert!(decode(word).unwrap().is_ok()); } diff --git a/crates/stela-compiler/src/aarch64/simd/memory.rs b/crates/stela-compiler/src/aarch64/simd/memory.rs index f559eaca96..8df93f42ba 100644 --- a/crates/stela-compiler/src/aarch64/simd/memory.rs +++ b/crates/stela-compiler/src/aarch64/simd/memory.rs @@ -1,5 +1,6 @@ //! SIMD/FP register-offset loads and stores. use super::super::{Register, register, register_offset::IndexExtend}; +use crate::aarch64::Unsupported; const REGISTER_OFFSET_MASK: u32 = 0x3f20_0c00; const REGISTER_OFFSET_CLASS: u32 = 0x3c20_0800; @@ -28,8 +29,7 @@ pub struct Operand { } /// None is a different class; Err is an undefined size or index extension. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if word & REGISTER_OFFSET_MASK != REGISTER_OFFSET_CLASS { return None; } @@ -37,14 +37,14 @@ pub fn decode(word: u32) -> Option> { let opcode = (word >> OPCODE_SHIFT) & OPCODE_MASK; let scale = if opcode & Q_OPCODE_BIT != 0 { if size != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } Q_SCALE } else { size }; let Some(extend) = IndexExtend::decode((word >> EXTENSION_SHIFT) & EXTENSION_MASK) else { - return Some(Err(())); + return Some(Err(Unsupported)); }; Some(Ok(Operand { load: opcode & LOAD_OPCODE_BIT != 0, diff --git a/crates/stela-compiler/src/aarch64/simd/minmax.rs b/crates/stela-compiler/src/aarch64/simd/minmax.rs index 98770e2735..e6b42b72e5 100644 --- a/crates/stela-compiler/src/aarch64/simd/minmax.rs +++ b/crates/stela-compiler/src/aarch64/simd/minmax.rs @@ -1,4 +1,6 @@ //! FP min/max: scalar, vector, pairwise and across-lane forms. +use super::scalar_format; +use crate::aarch64::Unsupported; use crate::aarch64::floating::{Format, minmax::MinMaxOperation}; use super::arithmetic::Shape; @@ -6,11 +8,6 @@ use super::arithmetic::Shape; const REGISTER_MASK: u32 = 31; const LEFT_SHIFT: u32 = 5; const RIGHT_SHIFT: u32 = 16; -const FORMAT_SHIFT: u32 = 22; -const FORMAT_MASK: u32 = 3; -const FORMAT_SINGLE: u32 = 0; -const FORMAT_DOUBLE: u32 = 1; -const FORMAT_HALF: u32 = 3; const VECTOR_Q: u32 = 1 << 30; const SIMD_DOUBLE: u32 = 1 << 22; const VECTOR_PAIRWISE: u32 = 1 << 29; @@ -102,15 +99,6 @@ fn register(word: u32, shift: u32) -> u8 { ((word >> shift) & REGISTER_MASK) as u8 } -fn scalar_format(word: u32) -> Result { - match (word >> FORMAT_SHIFT) & FORMAT_MASK { - FORMAT_SINGLE => Ok(Format::Single), - FORMAT_DOUBLE => Ok(Format::Double), - FORMAT_HALF => Ok(Format::Half), - _ => Err(()), - } -} - fn vector_shape(word: u32) -> Shape { if word & VECTOR_Q == 0 { Shape::Vector64 @@ -122,15 +110,14 @@ fn vector_shape(word: u32) -> Shape { /// None denotes another family; Err denotes reserved scalar ftype, vector1D, /// half scalar-pair size or ordinary reduction size/Q. Registers denote V31 /// normally; pairwise scalar H consumes only the source's first two H lanes. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { decode_scalar(word) .or_else(|| decode_vector(word)) .or_else(|| decode_pairwise_scalar(word)) .or_else(|| decode_reduction(word)) } -fn decode_scalar(word: u32) -> Option> { +fn decode_scalar(word: u32) -> Option> { let operation = match word & SCALAR_MASK { SCALAR_FMAX => MinMaxOperation::Maximum, SCALAR_FMIN => MinMaxOperation::Minimum, @@ -159,7 +146,7 @@ fn vector_operation(opcode: u32) -> Option { }) } -fn decode_vector(word: u32) -> Option> { +fn decode_vector(word: u32) -> Option> { for (mask, adjustment, half) in [ (VECTOR_MASK, 0, false), (VECTOR_HALF_MASK, HALF_REGISTER_ADJUSTMENT, true), @@ -176,7 +163,7 @@ fn decode_vector(word: u32) -> Option> { }; let shape = vector_shape(word); if format == Format::Double && shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(Operand::Binary { operation, @@ -205,13 +192,13 @@ fn pair_operation(opcode: u32) -> Option { }) } -fn decode_pairwise_scalar(word: u32) -> Option> { +fn decode_pairwise_scalar(word: u32) -> Option> { for (adjustment, half) in [(0, false), (HALF_PAIR_ADJUSTMENT, true)] { let Some(operation) = pair_operation((word & PAIR_SCALAR_MASK) ^ adjustment) else { continue; }; if half && word & SIMD_DOUBLE != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } let format = if half { Format::Half @@ -240,7 +227,7 @@ fn reduction_operation(opcode: u32) -> Option { }) } -fn decode_reduction(word: u32) -> Option> { +fn decode_reduction(word: u32) -> Option> { for (mask, adjustment, half) in [ (REDUCTION_MASK, 0, false), (REDUCTION_HALF_MASK, HALF_PAIR_ADJUSTMENT, true), @@ -249,7 +236,7 @@ fn decode_reduction(word: u32) -> Option> { continue; }; if !half && (word & SIMD_DOUBLE != 0 || word & VECTOR_Q == 0) { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(Operand::Reduction { operation, @@ -265,6 +252,7 @@ fn decode_reduction(word: u32) -> Option> { #[cfg(test)] mod tests { use super::*; + use crate::aarch64::simd::{FORMAT_DOUBLE, FORMAT_HALF, FORMAT_SHIFT, FORMAT_SINGLE}; const SCALAR_OPERATIONS: [(u32, MinMaxOperation); 4] = [ (SCALAR_FMAX, MinMaxOperation::Maximum), @@ -466,24 +454,27 @@ mod tests { for (opcode, _) in SCALAR_OPERATIONS { assert_eq!( decode(opcode | (RESERVED_FORMAT << FORMAT_SHIFT)), - Some(Err(())) + Some(Err(Unsupported)) ); } for (opcode, _) in VECTOR_OPERATIONS { for pairwise in [0, VECTOR_PAIRWISE] { - assert_eq!(decode(opcode | SIMD_DOUBLE | pairwise), Some(Err(()))); + assert_eq!( + decode(opcode | SIMD_DOUBLE | pairwise), + Some(Err(Unsupported)) + ); } } for (opcode, _) in PAIR_OPERATIONS { assert_eq!( decode((opcode ^ HALF_PAIR_ADJUSTMENT) | SIMD_DOUBLE), - Some(Err(())) + Some(Err(Unsupported)) ); } for (opcode, _) in REDUCTION_OPERATIONS { - assert_eq!(decode(opcode), Some(Err(()))); + assert_eq!(decode(opcode), Some(Err(Unsupported))); for q in [0, VECTOR_Q] { - assert_eq!(decode(opcode | SIMD_DOUBLE | q), Some(Err(()))); + assert_eq!(decode(opcode | SIMD_DOUBLE | q), Some(Err(Unsupported))); } } } diff --git a/crates/stela-compiler/src/aarch64/simd/products.rs b/crates/stela-compiler/src/aarch64/simd/products.rs index 8d3ac9ab81..fae9a3d069 100644 --- a/crates/stela-compiler/src/aarch64/simd/products.rs +++ b/crates/stela-compiler/src/aarch64/simd/products.rs @@ -1,4 +1,5 @@ //! Integer multiplies and widening arithmetic (MUL, MLA, SMULL, UADDL, ...). +use crate::aarch64::Unsupported; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Accumulate { None, @@ -100,8 +101,7 @@ encodings! { Uabal => (0x2e205000,Difference {signed:false,widen:true,accumulate:true}), } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if let Some(decoded) = decode_dot(word) { return Some(decoded); } @@ -118,7 +118,7 @@ pub fn decode(word: u32) -> Option> { .find(|(value, _)| *value == opcode)?; let size = (word >> 22) & 3; if size == 3 { - return Some(Err(())); + return Some(Err(Unsupported)); } let q = word & (1 << 30) != 0; let widen = kind.widened(); @@ -181,15 +181,14 @@ impl IndexedProductEncoding { } } -#[allow(clippy::result_unit_err)] -fn decode_indexed_product(word: u32) -> Option> { +fn decode_indexed_product(word: u32) -> Option> { let (_, kind) = IndexedProductEncoding::ALL .iter() .map(|e| e.facts()) .find(|(opcode, _)| word & 0xbf00f400 == *opcode)?; let size = (word >> 22) & 3; if !matches!(size, 1 | 2) { - return Some(Err(())); + return Some(Err(Unsupported)); } let q = word & (1 << 30) != 0; let h = ((word >> 11) & 1) as u8; @@ -292,8 +291,7 @@ impl DotEncoding { } } -#[allow(clippy::result_unit_err)] -fn decode_dot(word: u32) -> Option> { +fn decode_dot(word: u32) -> Option> { const REGISTER_MASK: u32 = 0xbf20fc00; const INDEXED_MASK: u32 = 0xbf00f400; const DWORD_SIZE: u32 = 2; @@ -304,7 +302,7 @@ fn decode_dot(word: u32) -> Option> { word & REGISTER_MASK == *register || word & INDEXED_MASK == *indexed })?; if (word >> 22) & 3 != DWORD_SIZE { - return Some(Err(())); + return Some(Err(Unsupported)); } Some(Ok(Operand { kind: Kind::Dot { signed }, @@ -318,8 +316,7 @@ fn decode_dot(word: u32) -> Option> { .then_some((((word >> 11) & 1) << 1 | ((word >> 21) & 1)) as u8), })) } -#[allow(clippy::result_unit_err)] -fn decode_special(word: u32) -> Option> { +fn decode_special(word: u32) -> Option> { let scalar = word & (1 << 28) != 0; let q = word & (1 << 30) != 0; let normalized = word & !(1 << 28); @@ -329,12 +326,12 @@ fn decode_special(word: u32) -> Option> { let kind = if !scalar && word & 0xbf20fc00 == PolynomialEncoding::Multiply.opcode() { if size != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } Kind::Polynomial { widen: false } } else if !scalar && word & 0xbf20fc00 == PolynomialEncoding::MultiplyLong.opcode() { if size != 0 && size != 3 { - return Some(Err(())); + return Some(Err(Unsupported)); } Kind::Polynomial { widen: true } } else { @@ -344,7 +341,7 @@ fn decode_special(word: u32) -> Option> { }, )?; if !matches!(size, 1 | 2) || scalar && !q { - return Some(Err(())); + return Some(Err(Unsupported)); } if normalized & 0xbf00f400 == indexed { let h = ((word >> 11) & 1) as u8; diff --git a/crates/stela-compiler/src/aarch64/simd/rearrange.rs b/crates/stela-compiler/src/aarch64/simd/rearrange.rs index fb3501e368..e040b2ac74 100644 --- a/crates/stela-compiler/src/aarch64/simd/rearrange.rs +++ b/crates/stela-compiler/src/aarch64/simd/rearrange.rs @@ -1,6 +1,7 @@ //! Lane movement and permutes: DUP, INS, SMOV, UMOV, EXT, REV16/32/64, //! ZIP/UZP/TRN, TBL and TBX. use super::super::{Register, register}; +use crate::aarch64::Unsupported; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LaneSource { @@ -77,8 +78,7 @@ encodings! { Table => (0xbfe08c00, 0x0e000000), } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { use Encoding::*; let d = (word & 31) as u8; let n = ((word >> 5) & 31) as u8; @@ -99,7 +99,7 @@ pub fn decode(word: u32) -> Option> { { let imm5 = ((word >> 16) & 31) as u8; if imm5 & 15 == 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } let size = (imm5 & 15).trailing_zeros(); let lane_bytes = 1 << size; @@ -107,7 +107,7 @@ pub fn decode(word: u32) -> Option> { if SignedMove.matches(word) || UnsignedMove.matches(word) { let signed = SignedMove.matches(word); if (signed && lane_bytes >= (4 << q)) || (!signed && ((q == 1) != (lane_bytes == 8))) { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(Operand::Extract { destination: register(u32::from(d), false), @@ -141,7 +141,7 @@ pub fn decode(word: u32) -> Option> { } let scalar = DupScalar.matches(word); if !scalar && q == 0 && lane_bytes == 8 { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(Operand::Duplicate { destination: d, @@ -164,7 +164,7 @@ pub fn decode(word: u32) -> Option> { if ExtractBytes.matches(word) { let offset = ((word >> 11) & 15) as u8; if offset >= bytes { - return Some(Err(())); + return Some(Err(Unsupported)); } for i in 0..bytes { let source = i + offset; @@ -187,7 +187,7 @@ pub fn decode(word: u32) -> Option> { }; let lane = 1 << ((word >> 22) & 3); if lane >= container { - return Some(Err(())); + return Some(Err(Unsupported)); } for i in 0..bytes { selection[usize::from(i)] = @@ -200,7 +200,7 @@ pub fn decode(word: u32) -> Option> { { let lane = 1 << ((word >> 22) & 3); if lane == 8 && q == 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } let elements = bytes / lane; let part = ((word >> 14) & 1) as u8; @@ -258,8 +258,8 @@ mod tests { } // INS ignores low imm4 bits below the selected element size. assert_eq!(decode(0x6e080400), decode(0x6e083c00)); - assert_eq!(decode(0x2e004000), Some(Err(()))); // EXT 8B offset 8 - assert_eq!(decode(0x0e601800), Some(Err(()))); // REV16 halfword + assert_eq!(decode(0x2e004000), Some(Err(Unsupported))); // EXT 8B offset 8 + assert_eq!(decode(0x0e601800), Some(Err(Unsupported))); // REV16 halfword assert!(decode(0x0e800000).is_none()); // adjacent table fixed bit } } diff --git a/crates/stela-compiler/src/aarch64/simd/reductions.rs b/crates/stela-compiler/src/aarch64/simd/reductions.rs index 53b38be9b1..5f4836872e 100644 --- a/crates/stela-compiler/src/aarch64/simd/reductions.rs +++ b/crates/stela-compiler/src/aarch64/simd/reductions.rs @@ -1,4 +1,5 @@ //! Integer across-lane reductions, pairwise combines and per-lane bit counts. +use crate::aarch64::Unsupported; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Combine { Add, @@ -62,8 +63,7 @@ encodings! { Not => (0xbffffc00,0x2e205800), } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { use Encoding::*; let q = word & (1 << 30) != 0; let size = ((word >> 22) & 3) as u8; @@ -97,7 +97,7 @@ pub fn decode(word: u32) -> Option> { if (kind == BitCount::Population && size != 0) || (matches!(kind, BitCount::LeadingZeros | BitCount::LeadingSign) && size == 3) { - return Some(Err(())); + return Some(Err(Unsupported)); } if matches!(kind, BitCount::Reverse | BitCount::Not) { operand.lane_bytes = 1; @@ -177,7 +177,7 @@ pub fn decode(word: u32) -> Option> { if (size == 3 && !(operation == Combine::Add && shape == Shape::Pairs && q)) || (shape == Shape::Across && size == 2 && !q) { - return Some(Err(())); + return Some(Err(Unsupported)); } operand.kind = Kind::Combine { operation, shape }; Some(Ok(operand)) diff --git a/crates/stela-compiler/src/aarch64/simd/refinement.rs b/crates/stela-compiler/src/aarch64/simd/refinement.rs index 7fadd07fdf..0a41343992 100644 --- a/crates/stela-compiler/src/aarch64/simd/refinement.rs +++ b/crates/stela-compiler/src/aarch64/simd/refinement.rs @@ -1,4 +1,5 @@ //! FRECPS and FRSQRTS. +use crate::aarch64::Unsupported; use crate::aarch64::floating::Format; use super::arithmetic::Shape; @@ -43,8 +44,7 @@ fn kind(opcode: u32) -> Option { /// None denotes another family; Err denotes reserved vector1D. Every register /// field is ordinary V data, including V31 and all source/destination aliases. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { for (mask, adjustment, scalar, half) in [ (SCALAR_MASK, SCALAR_PREFIX, true, false), (VECTOR_MASK, 0, false, false), @@ -74,7 +74,7 @@ pub fn decode(word: u32) -> Option> { Shape::Vector128 }; if format == Format::Double && shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } return Some(Ok(Operand { kind, @@ -111,7 +111,7 @@ mod tests { ] { let word = (opcode ^ size) | prefix; if format == Format::Double && shape == Shape::Vector64 { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); continue; } for destination in 0..=REGISTER_MASK { @@ -157,7 +157,7 @@ mod tests { | (left << LEFT_SHIFT) | (right << RIGHT_SHIFT) ), - Some(Err(())) + Some(Err(Unsupported)) ); } } diff --git a/crates/stela-compiler/src/aarch64/simd/rounding.rs b/crates/stela-compiler/src/aarch64/simd/rounding.rs index c5b5bc26bb..08c0dc1f90 100644 --- a/crates/stela-compiler/src/aarch64/simd/rounding.rs +++ b/crates/stela-compiler/src/aarch64/simd/rounding.rs @@ -1,4 +1,5 @@ //! Scalar and AdvSIMD FRINT*. +use crate::aarch64::Unsupported; use crate::aarch64::floating::{Format, rounding::RoundingOperation}; use super::arithmetic::Shape; @@ -86,14 +87,13 @@ fn vector_operation(opcode: u32) -> Option { /// None denotes another family; Err denotes reserved scalar ftype, bounded H /// or vector1D. Every register field denotes ordinary V data, including V31. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let (operation, format, shape) = if let Some(operation) = scalar_operation(word & SCALAR_MASK) { let format = match (word >> FORMAT_SHIFT) & FORMAT_MASK { FORMAT_SINGLE => Format::Single, FORMAT_DOUBLE => Format::Double, FORMAT_HALF if operation.signed_width().is_none() => Format::Half, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; (operation, format, Shape::Scalar) } else { @@ -119,7 +119,7 @@ pub fn decode(word: u32) -> Option> { Shape::Vector128 }; if format == Format::Double && shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } (operation, format, shape) }; @@ -207,7 +207,10 @@ mod tests { (FORMAT_HALF, Format::Half), ] { if format == Format::Half && operation.signed_width().is_some() { - assert_eq!(decode(scalar | (field << FORMAT_SHIFT)), Some(Err(()))); + assert_eq!( + decode(scalar | (field << FORMAT_SHIFT)), + Some(Err(Unsupported)) + ); continue; } check_registers( @@ -238,7 +241,7 @@ mod tests { continue; } if format == Format::Double && shape == Shape::Vector64 { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); continue; } check_registers(word, operation, format, shape); @@ -258,13 +261,16 @@ mod tests { let registers = destination | (source << SOURCE_SHIFT); assert_eq!( decode(scalar | (RESERVED_FORMAT << FORMAT_SHIFT) | registers), - Some(Err(())) + Some(Err(Unsupported)) + ); + assert_eq!( + decode(vector | VECTOR_DOUBLE | registers), + Some(Err(Unsupported)) ); - assert_eq!(decode(vector | VECTOR_DOUBLE | registers), Some(Err(()))); if operation.signed_width().is_some() { assert_eq!( decode(scalar | (FORMAT_HALF << FORMAT_SHIFT) | registers), - Some(Err(())) + Some(Err(Unsupported)) ); } } diff --git a/crates/stela-compiler/src/aarch64/simd/saturating.rs b/crates/stela-compiler/src/aarch64/simd/saturating.rs index e12ba3b0a3..e6eace7a46 100644 --- a/crates/stela-compiler/src/aarch64/simd/saturating.rs +++ b/crates/stela-compiler/src/aarch64/simd/saturating.rs @@ -1,4 +1,5 @@ //! Saturating integer arithmetic, which sets FPSR.QC. +use crate::aarch64::Unsupported; /// Architectural cumulative saturation bit; unrelated FPSR bits stay unchanged. pub use crate::aarch64::floating::FPSR_QC; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -47,8 +48,7 @@ const SIGNED_NARROW: u32 = 0x0e214800; const UNSIGNED_NARROW: u32 = 0x2e214800; const SIGNED_TO_UNSIGNED_NARROW: u32 = 0x2e212800; -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let scalar = word & SCALAR != 0; let q = word & Q != 0; let normalized = word & !SCALAR; @@ -91,7 +91,7 @@ pub fn decode(word: u32) -> Option> { let lane_bytes = 1 << ((word >> 22) & 3); let narrow = matches!(kind, Kind::Narrow { .. }); if (narrow && lane_bytes == 8) || (!narrow && !scalar && !q && lane_bytes == 8) { - return Some(Err(())); + return Some(Err(Unsupported)); } Some(Ok(Operand { kind, diff --git a/crates/stela-compiler/src/aarch64/simd/sha3.rs b/crates/stela-compiler/src/aarch64/simd/sha3.rs index 22c3247cb8..ff9603cca6 100644 --- a/crates/stela-compiler/src/aarch64/simd/sha3.rs +++ b/crates/stela-compiler/src/aarch64/simd/sha3.rs @@ -1,4 +1,5 @@ //! EOR3, BCAX, RAX1 and XAR. +use crate::aarch64::Unsupported; const REGISTER_MASK: u32 = 31; const DESTINATION_SHIFT: u32 = 0; const LEFT_SHIFT: u32 = 5; @@ -58,8 +59,7 @@ impl Encoding { /// Every register and immediate within the four exact fixed-bit masks is valid. /// Same-named SVE forms remain another encoding class and receive no support here. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let encoding = Encoding::ALL.iter().copied().find(|encoding| { let (mask, value) = encoding.facts(); word & mask == value diff --git a/crates/stela-compiler/src/aarch64/simd/sha512.rs b/crates/stela-compiler/src/aarch64/simd/sha512.rs index 28e092f6d6..e896e48d56 100644 --- a/crates/stela-compiler/src/aarch64/simd/sha512.rs +++ b/crates/stela-compiler/src/aarch64/simd/sha512.rs @@ -1,4 +1,5 @@ //! SHA512H, SHA512H2, SHA512SU0 and SHA512SU1. +use crate::aarch64::Unsupported; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { @@ -30,8 +31,7 @@ const RIGHT_SHIFT: u32 = 16; /// Exact allocated forms only: all register aliases are legal and no size/Q /// variants exist. Other members of the crypto classes belong to other families. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let kind = if word & TWO_REGISTER_MASK == SCHEDULE0 { Kind::Schedule0 } else { diff --git a/crates/stela-compiler/src/aarch64/simd/shifts.rs b/crates/stela-compiler/src/aarch64/simd/shifts.rs index abab3adc8c..8c60597c6b 100644 --- a/crates/stela-compiler/src/aarch64/simd/shifts.rs +++ b/crates/stela-compiler/src/aarch64/simd/shifts.rs @@ -1,4 +1,5 @@ //! AdvSIMD shifts by immediate and register: same-width, narrowing and widening. +use crate::aarch64::Unsupported; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { Register { @@ -86,8 +87,7 @@ const ROUND_NARROW: u32 = 1 << 11; const SHIFT_WIDEN_SIGNED: u32 = 0x0f00a400; const SHIFT_WIDEN_UNSIGNED: u32 = 0x2f00a400; -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let scalar = word & SCALAR != 0; let q = word & Q != 0; if let Some(result) = decode_register(word, scalar, q) { @@ -164,7 +164,7 @@ pub fn decode(word: u32) -> Option> { || (changes_width && lane_bytes == 8) || (!scalar && !changes_width && !q && lane_bytes == 8) { - return Some(Err(())); + return Some(Err(Unsupported)); } let bits = lane_bytes * 8; let amount = if matches!( @@ -191,7 +191,7 @@ pub fn decode(word: u32) -> Option> { })) } -fn decode_register(word: u32, scalar: bool, q: bool) -> Option> { +fn decode_register(word: u32, scalar: bool, q: bool) -> Option> { let opcode = (word & !SCALAR) & REGISTER_SHIFT_MASK; if ![ REGISTER_SHIFT_SIGNED, @@ -210,7 +210,7 @@ fn decode_register(word: u32, scalar: bool, q: bool) -> Option> 22) & 3); if (scalar && (!q || (!saturating && lane_bytes != 8))) || (!scalar && !q && lane_bytes == 8) { - return Some(Err(())); + return Some(Err(Unsupported)); } Some(Ok(Operand { kind: Kind::Register { diff --git a/crates/stela-compiler/src/aarch64/simd/sqrt.rs b/crates/stela-compiler/src/aarch64/simd/sqrt.rs index cdef292349..0234bb3fa2 100644 --- a/crates/stela-compiler/src/aarch64/simd/sqrt.rs +++ b/crates/stela-compiler/src/aarch64/simd/sqrt.rs @@ -1,4 +1,5 @@ //! Scalar and AdvSIMD FSQRT. +use crate::aarch64::Unsupported; use crate::aarch64::floating::Format; use super::arithmetic::Shape; @@ -29,14 +30,13 @@ pub struct Operand { /// None denotes another family; Err denotes reserved scalar ftype or vector1D. /// Every register field denotes ordinary V data, including V31. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let (format, shape) = if word & SCALAR_MASK == SCALAR_FSQRT { let format = match (word >> FORMAT_SHIFT) & FORMAT_MASK { FORMAT_SINGLE => Format::Single, FORMAT_DOUBLE => Format::Double, FORMAT_HALF => Format::Half, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; (format, Shape::Scalar) } else { @@ -57,7 +57,7 @@ pub fn decode(word: u32) -> Option> { Shape::Vector128 }; if format == Format::Double && shape == Shape::Vector64 { - return Some(Err(())); + return Some(Err(Unsupported)); } (format, shape) }; @@ -124,11 +124,11 @@ mod tests { let registers = destination | (source << SOURCE_SHIFT); assert_eq!( decode(SCALAR_FSQRT | (FORMAT_RESERVED << FORMAT_SHIFT) | registers), - Some(Err(())) + Some(Err(Unsupported)) ); assert_eq!( decode(VECTOR_FSQRT | VECTOR_DOUBLE | registers), - Some(Err(())) + Some(Err(Unsupported)) ); } } diff --git a/crates/stela-compiler/src/aarch64/simd/structure_memory.rs b/crates/stela-compiler/src/aarch64/simd/structure_memory.rs index 52e60e57ca..1778610575 100644 --- a/crates/stela-compiler/src/aarch64/simd/structure_memory.rs +++ b/crates/stela-compiler/src/aarch64/simd/structure_memory.rs @@ -1,5 +1,6 @@ //! Structured AdvSIMD loads and stores (LD1-4, ST1-4, LD1R-4R), in architectural //! access order, with post-index writeback. +use crate::aarch64::Unsupported; use crate::aarch64::{Register, register}; mod multiple; @@ -135,8 +136,7 @@ fn decode_addressing(word: u32) -> (Register, PostIndex) { (base, post_index) } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { multiple::decode(word).or_else(|| single::decode(word)) } diff --git a/crates/stela-compiler/src/aarch64/simd/structure_memory/multiple.rs b/crates/stela-compiler/src/aarch64/simd/structure_memory/multiple.rs index e72f03f384..bed2d2cf7a 100644 --- a/crates/stela-compiler/src/aarch64/simd/structure_memory/multiple.rs +++ b/crates/stela-compiler/src/aarch64/simd/structure_memory/multiple.rs @@ -1,5 +1,6 @@ //! LD1-4 and ST1-4 (multiple structures). use super::{Direction, Layout, Operand, decode_addressing}; +use crate::aarch64::Unsupported; const CLASS_MASK: u32 = 0xbf20_0000; const CLASS: u32 = 0x0c00_0000; @@ -21,12 +22,12 @@ const TWO_STRUCTURES: u32 = 0b1000; const TWO_REGISTERS: u32 = 0b1010; /// None denotes a different instruction class; Err denotes a reserved encoding. -pub(super) fn decode(word: u32) -> Option> { +pub(super) fn decode(word: u32) -> Option> { if word & CLASS_MASK != CLASS { return None; } if word & POST_INDEX_BIT == 0 && word & INDEX_MASK != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } let (repetitions, structures) = match (word >> OPCODE_SHIFT) & OPCODE_MASK { FOUR_STRUCTURES => (1, 4), @@ -36,12 +37,12 @@ pub(super) fn decode(word: u32) -> Option> { ONE_REGISTER => (1, 1), TWO_STRUCTURES => (1, 2), TWO_REGISTERS => (2, 1), - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; let size = (word >> SIZE_SHIFT) & SIZE_MASK; let vector_bytes = if word & Q_BIT == 0 { 8 } else { 16 }; if structures != 1 && vector_bytes == 8 && size == SIZE_MASK { - return Some(Err(())); + return Some(Err(Unsupported)); } let (base, post_index) = decode_addressing(word); Some(Ok(Operand { diff --git a/crates/stela-compiler/src/aarch64/simd/structure_memory/single.rs b/crates/stela-compiler/src/aarch64/simd/structure_memory/single.rs index 83a0f5a5b1..8f3407dba7 100644 --- a/crates/stela-compiler/src/aarch64/simd/structure_memory/single.rs +++ b/crates/stela-compiler/src/aarch64/simd/structure_memory/single.rs @@ -1,5 +1,6 @@ //! LD1-4 and ST1-4 (single lane) and LD1R-4R (replicate). use super::{Direction, Layout, Operand, decode_addressing}; +use crate::aarch64::Unsupported; const SINGLE_STRUCTURE_MASK: u32 = 0xbf00_0000; const SINGLE_STRUCTURE_CLASS: u32 = 0x0d00_0000; @@ -21,13 +22,12 @@ const DOUBLEWORD_SCALE: u8 = 3; const LOW_VECTOR_BYTES: u8 = 8; /// None denotes a different class; Err denotes a reserved single structure. -#[allow(clippy::result_unit_err)] -pub(super) fn decode(word: u32) -> Option> { +pub(super) fn decode(word: u32) -> Option> { if word & SINGLE_STRUCTURE_MASK != SINGLE_STRUCTURE_CLASS { return None; } if word & POST_INDEX_BIT == 0 && word & OFFSET_REGISTER_MASK != 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } let opcode = ((word >> OPCODE_SHIFT) & OPCODE_MASK) as u8; let structures = ((opcode & 1) << 1) + ((word >> STRUCTURE_LOW_BIT_SHIFT) & 1) as u8 + 1; @@ -75,7 +75,7 @@ pub(super) fn decode(word: u32) -> Option> { vector_bytes: LOW_VECTOR_BYTES << q, }, ), - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; let (base, post_index) = decode_addressing(word); Some(Ok(Operand { diff --git a/crates/stela-compiler/src/aarch64/simd/widening.rs b/crates/stela-compiler/src/aarch64/simd/widening.rs index 493415c612..e701b7a790 100644 --- a/crates/stela-compiler/src/aarch64/simd/widening.rs +++ b/crates/stela-compiler/src/aarch64/simd/widening.rs @@ -1,4 +1,5 @@ //! FMLAL and FMLSL (half to single). +use crate::aarch64::Unsupported; use crate::aarch64::floating::{Format, widening::WideningOperation}; use super::arithmetic::Shape; @@ -59,8 +60,7 @@ pub struct Operand { /// Exact fixed bits keep sz=1 and adjacent FP8/SME forms outside this family. /// All registers are ordinary V registers; indexed Vm is limited to V0..V15. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let (operation, part) = match word & VECTOR_MASK { VECTOR_FMLAL => (WideningOperation::Add, Part::Lower), VECTOR_FMLAL2 => (WideningOperation::Add, Part::Upper), @@ -103,7 +103,7 @@ fn operand( } } -fn decode_indexed(word: u32) -> Option> { +fn decode_indexed(word: u32) -> Option> { let (operation, part) = match word & INDEXED_MASK { INDEXED_FMLAL => (WideningOperation::Add, Part::Lower), INDEXED_FMLAL2 => (WideningOperation::Add, Part::Upper), diff --git a/crates/stela-compiler/src/aarch64/sme.rs b/crates/stela-compiler/src/aarch64/sme.rs index b814da4c50..4297aed3c5 100644 --- a/crates/stela-compiler/src/aarch64/sme.rs +++ b/crates/stela-compiler/src/aarch64/sme.rs @@ -1,4 +1,5 @@ //! SME operands. Callers check streaming mode, ZA state and features. +use crate::aarch64::Unsupported; pub mod extrema_scale; pub mod fp8_conversion; @@ -26,8 +27,7 @@ pub enum Operand { LutV2(lut_v2::Operand), } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if let Some(operand) = lut_v2::decode(word) { return Some(Ok(Operand::LutV2(operand))); } diff --git a/crates/stela-compiler/src/aarch64/sme/integer_vector.rs b/crates/stela-compiler/src/aarch64/sme/integer_vector.rs index 0ea27d389e..76d0847887 100644 --- a/crates/stela-compiler/src/aarch64/sme/integer_vector.rs +++ b/crates/stela-compiler/src/aarch64/sme/integer_vector.rs @@ -1,5 +1,6 @@ //! SME2 multi-vector integer arithmetic and narrowing. Saturation does not set //! FPSR.QC. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{BITS_PER_BYTE, ElementSize, VECTOR_REGISTER_COUNT}; const SIZE_SHIFT: u32 = 22; @@ -668,7 +669,7 @@ fn element(size: u32) -> ElementSize { } } -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { for encoding in &ARITHMETIC_ENCODINGS { if word & encoding.mask != encoding.opcode { continue; @@ -717,7 +718,7 @@ pub fn decode(word: u32) -> Option> { if encoding.rounded_shift { let size = (word >> NARROW_SHIFT_SIZE_SHIFT) & SIZE_MASK; let destination_bits = match size { - 0 => return Some(Err(())), + 0 => return Some(Err(Unsupported)), 1 => ElementSize::Byte.bits(), _ => ElementSize::Halfword.bits(), } as u8; @@ -871,7 +872,7 @@ mod tests { | (size << NARROW_SHIFT_SIZE_SHIFT) | (immediate << NARROW_IMMEDIATE_SHIFT); if size == 0 { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); continue; } let Operand::Narrow(narrow) = decode(word).unwrap().unwrap() else { diff --git a/crates/stela-compiler/src/aarch64/sve.rs b/crates/stela-compiler/src/aarch64/sve.rs index 6cdab6eaae..c6ddcd9b7e 100644 --- a/crates/stela-compiler/src/aarch64/sve.rs +++ b/crates/stela-compiler/src/aarch64/sve.rs @@ -1,4 +1,5 @@ //! SVE operands shared by the SVE instruction families. +use crate::aarch64::Unsupported; pub mod address; pub mod dot; @@ -56,8 +57,7 @@ pub enum Operand { Tables(tables::Operand), } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { tables::decode(word) .map(|operand| operand.map(Operand::Tables)) .or_else(|| address::decode(word).map(|operand| operand.map(Operand::Address))) diff --git a/crates/stela-compiler/src/aarch64/sve/address.rs b/crates/stela-compiler/src/aarch64/sve/address.rs index ffdc6cbb9c..19b68eddcc 100644 --- a/crates/stela-compiler/src/aarch64/sve/address.rs +++ b/crates/stela-compiler/src/aarch64/sve/address.rs @@ -1,5 +1,6 @@ //! ADDVL/ADDPL/RDVL and predicate counts (CNTP, INC/DEC by element count). use super::super::{Register, register, scalable::ElementSize}; +use crate::aarch64::Unsupported; const LENGTH_MASK: u32 = 0xffe0_f800; const READ_LENGTH_MASK: u32 = 0xffff_f800; @@ -98,8 +99,7 @@ pub struct Operand { pub kind: Kind, } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let d = word & REGISTER_MASK; let scalar = |bits| Destination::Scalar { register: register(d, false), @@ -160,7 +160,7 @@ pub fn decode(word: u32) -> Option> { ), INC_VECTOR | DEC_VECTOR | SQINC_VECTOR | UQINC_VECTOR | SQDEC_VECTOR | UQDEC_VECTOR => { if element == ElementSize::Byte { - return Some(Err(())); + return Some(Err(Unsupported)); } let opcode = word & PATTERN_MASK; let subtract = matches!(opcode, DEC_VECTOR | SQDEC_VECTOR | UQDEC_VECTOR); @@ -228,7 +228,7 @@ pub fn decode(word: u32) -> Option> { }; if matches!(destination, Destination::Vector(_)) && element == ElementSize::Byte { - return Some(Err(())); + return Some(Err(Unsupported)); } adjust(destination, predicate, subtract, saturation) } @@ -304,7 +304,7 @@ mod tests { SQDECP_VECTOR, UQDECP_VECTOR, ] { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); } } diff --git a/crates/stela-compiler/src/aarch64/sve/dot.rs b/crates/stela-compiler/src/aarch64/sve/dot.rs index 753d4f56f9..ac9958c95b 100644 --- a/crates/stela-compiler/src/aarch64/sve/dot.rs +++ b/crates/stela-compiler/src/aarch64/sve/dot.rs @@ -1,5 +1,6 @@ //! SVE integer and complex dot products, half-precision FDOT and widening //! multiply-add. Indexed sources select within each 128-bit segment. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; @@ -364,8 +365,7 @@ const ENCODINGS: &[Encoding] = &[ /// Feature and execution-mode validation belongs to the enclosing SVE profile. /// These instructions have no predicate operand; every output lane is active. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let encoding = ENCODINGS .iter() .find(|encoding| word & encoding.mask == encoding.value)?; @@ -375,7 +375,7 @@ pub fn decode(word: u32) -> Option> { SizeShape::Variable => match (word >> SIZE_SHIFT) & SIZE_MASK { 2 => ElementSize::Word, 3 => ElementSize::Doubleword, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }, }; let kind = if let Kind::Complex { .. } = encoding.kind { @@ -417,13 +417,12 @@ pub fn decode(word: u32) -> Option> { /// Integer-only admission shares allocation checks with the numerical decoder. /// Half dot and widening arithmetic remain separate numerical operations. -#[allow(clippy::result_unit_err)] -pub fn decode_integer(word: u32) -> Option> { +pub fn decode_integer(word: u32) -> Option> { match decode(word)? { Ok(operand) if matches!(operand.kind, Kind::Integer { .. } | Kind::Complex { .. }) => { Some(Ok(operand)) } - Err(()) => Some(Err(())), + Err(Unsupported) => Some(Err(Unsupported)), Ok(_) => None, } } @@ -451,7 +450,7 @@ mod tests { } } const CDOT_RESERVED_BYTE: u32 = 0x4400_1000; - assert_eq!(decode_integer(CDOT_RESERVED_BYTE), Some(Err(()))); + assert_eq!(decode_integer(CDOT_RESERVED_BYTE), Some(Err(Unsupported))); assert_eq!(decode_integer(0), None); } @@ -555,7 +554,10 @@ mod tests { #[test] fn complex_reserved_sizes_decline_and_rotations_keep_exact_components() { for size in 0..2 { - assert_eq!(decode(0x44001000 | (size << SIZE_SHIFT)), Some(Err(()))); + assert_eq!( + decode(0x44001000 | (size << SIZE_SHIFT)), + Some(Err(Unsupported)) + ); } for (rotation, expected) in [ (Rotation::Zero, (0, 1, true)), diff --git a/crates/stela-compiler/src/aarch64/sve/floating.rs b/crates/stela-compiler/src/aarch64/sve/floating.rs index 9aac7761d5..eb3fe5af3c 100644 --- a/crates/stela-compiler/src/aarch64/sve/floating.rs +++ b/crates/stela-compiler/src/aarch64/sve/floating.rs @@ -1,4 +1,5 @@ //! SVE floating-point families. +use crate::aarch64::Unsupported; pub mod arithmetic; pub mod bfloat16; @@ -76,8 +77,7 @@ impl Operation { FeatureRequirement::all(required) } - #[allow(clippy::result_unit_err)] - pub fn decode(word: u32) -> Option> { + pub fn decode(word: u32) -> Option> { if let Some(result) = fp8::decode(word) { return Some(result.map(Self::Fp8)); } diff --git a/crates/stela-compiler/src/aarch64/sve/floating/arithmetic.rs b/crates/stela-compiler/src/aarch64/sve/floating/arithmetic.rs index d91812e056..6f68a6e247 100644 --- a/crates/stela-compiler/src/aarch64/sve/floating/arithmetic.rs +++ b/crates/stela-compiler/src/aarch64/sve/floating/arithmetic.rs @@ -1,4 +1,5 @@ //! SVE floating-point arithmetic operands. +use crate::aarch64::Unsupported; use crate::aarch64::{ floating::{ BinaryOperation, Format, complex::Rotation, fused::FusedOperation, minmax::MinMaxOperation, @@ -221,16 +222,14 @@ fn core_binary_encoding(encoding: &Encoding) -> bool { ) } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { decode_encoding(word, matching_encoding(word)?) } /// Supported subset: forward predicated ADD/SUB/MUL/DIV and unpredicated /// ADD/SUB/MUL, for H/S/D. The direction comes from the encoding, since /// reversed forms with aliased registers decode to identical operands. -#[allow(clippy::result_unit_err)] -pub fn decode_core_binary(word: u32) -> Option> { +pub fn decode_core_binary(word: u32) -> Option> { let encoding = matching_encoding(word)?; if !core_binary_encoding(encoding) { return None; @@ -240,8 +239,7 @@ pub fn decode_core_binary(word: u32) -> Option> { /// Arithmetic decoding uses the shared encoding table; FABS/FNEG keep their own /// decoder and emitter. -#[allow(clippy::result_unit_err)] -pub fn decode_numerical(word: u32) -> Option> { +pub fn decode_numerical(word: u32) -> Option> { let encoding = matching_encoding(word)?; if matches!(encoding.kind, Kind::Absolute | Kind::Negate) { return None; @@ -249,13 +247,13 @@ pub fn decode_numerical(word: u32) -> Option> { decode_encoding(word, encoding) } -fn decode_encoding(word: u32, encoding: &Encoding) -> Option> { +fn decode_encoding(word: u32, encoding: &Encoding) -> Option> { let format = match encoding.layout { Layout::IndexedBinary(f) | Layout::IndexedFused(f) | Layout::ComplexIndexed(f) => f, Layout::Logb => format(word, LOGB_SIZE_SHIFT)?, Layout::UnsignedEstimate => { if (word >> SIZE_SHIFT) & SIZE_MASK != SINGLE_SIZE_ENCODING { - return Some(Err(())); + return Some(Err(Unsupported)); } Format::Single } diff --git a/crates/stela-compiler/src/aarch64/sve/floating/bfloat16.rs b/crates/stela-compiler/src/aarch64/sve/floating/bfloat16.rs index 14d839961c..1a9b5c7122 100644 --- a/crates/stela-compiler/src/aarch64/sve/floating/bfloat16.rs +++ b/crates/stela-compiler/src/aarch64/sve/floating/bfloat16.rs @@ -1,5 +1,6 @@ //! SVE BF16 arithmetic, dot products and widening multiply-add. Non-widening //! arithmetic rounds to BF16 and reports exceptions. Predicated forms merge. +use crate::aarch64::Unsupported; use crate::aarch64::sve::dot::{RightOperand, VectorPart}; @@ -266,8 +267,7 @@ const ENCODINGS: &[Encoding] = &[ /// Exact fixed-bit forms contain no additional reserved register/index values. /// The enclosing decoder validates guest feature availability and streaming mode. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let encoding = ENCODINGS .iter() .find(|encoding| word & encoding.mask == encoding.value)?; diff --git a/crates/stela-compiler/src/aarch64/sve/floating/comparison.rs b/crates/stela-compiler/src/aarch64/sve/floating/comparison.rs index 2ad0a720d2..d3c33c75a3 100644 --- a/crates/stela-compiler/src/aarch64/sve/floating/comparison.rs +++ b/crates/stela-compiler/src/aarch64/sve/floating/comparison.rs @@ -1,4 +1,5 @@ //! SVE FCM* and FAC* comparisons into predicates. +use crate::aarch64::Unsupported; use crate::aarch64::flags::{NZCV_V, NZCV_Z}; use crate::aarch64::floating::{ Format, UnsupportedControl, @@ -99,8 +100,7 @@ pub fn evaluate( /// All Z registers and P destinations are ordinary storage. Pg is P0..P7; /// Pd is P0..P15. An allocated byte-size encoding is architecturally reserved. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let (kind, right) = match word & REGISTER_COMPARE_MASK { FCMEQ_REG => ( Kind::Equal, @@ -147,7 +147,7 @@ pub fn decode(word: u32) -> Option> { 1 => Format::Half, 2 => Format::Single, 3 => Format::Double, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; Some(Ok(Operand { kind, @@ -174,7 +174,7 @@ mod tests { (FACGE_REG, Kind::AbsoluteGreaterEqual), (FACGT_REG, Kind::AbsoluteGreater), ] { - assert_eq!(decode(opcode), Some(Err(()))); + assert_eq!(decode(opcode), Some(Err(Unsupported))); for (size, format) in [(1, Format::Half), (2, Format::Single), (3, Format::Double)] { for governing in 0..=GOVERNING_MASK { for destination in 0..=PREDICATE_MASK { @@ -206,7 +206,7 @@ mod tests { for opcode in [ FCMEQ_ZERO, FCMGE_ZERO, FCMGT_ZERO, FCMLE_ZERO, FCMLT_ZERO, FCMNE_ZERO, ] { - assert_eq!(decode(opcode), Some(Err(()))); + assert_eq!(decode(opcode), Some(Err(Unsupported))); assert!( decode(opcode | (2 << SIZE_SHIFT) | (31 << SOURCE_SHIFT) | 15) .unwrap() diff --git a/crates/stela-compiler/src/aarch64/sve/floating/conversion.rs b/crates/stela-compiler/src/aarch64/sve/floating/conversion.rs index 0bff0d43cb..c254190533 100644 --- a/crates/stela-compiler/src/aarch64/sve/floating/conversion.rs +++ b/crates/stela-compiler/src/aarch64/sve/floating/conversion.rs @@ -1,4 +1,5 @@ //! SVE predicated conversions (FCVT, FCVTZS/U, SCVTF/UCVTF, ...). +use crate::aarch64::Unsupported; use crate::aarch64::floating::{ Format, @@ -155,8 +156,7 @@ pub struct Operand { } /// Decodes exactly 28 integer, 12 precision and 2 BF16 forms. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let kind = match word & CONVERSION_MASK { BFCVT_Z_P_Z_S2BF => Kind::Bfloat16 { upper: false }, BFCVTNT_Z_P_Z_S2BF => Kind::Bfloat16 { upper: true }, diff --git a/crates/stela-compiler/src/aarch64/sve/floating/faminmax.rs b/crates/stela-compiler/src/aarch64/sve/floating/faminmax.rs index aac5f111b2..c88c26b399 100644 --- a/crates/stela-compiler/src/aarch64/sve/floating/faminmax.rs +++ b/crates/stela-compiler/src/aarch64/sve/floating/faminmax.rs @@ -1,4 +1,5 @@ //! SVE predicated FAMIN and FAMAX. +use crate::aarch64::Unsupported; use crate::aarch64::floating::{Format, absolute_minmax::AbsoluteMinMaxOperation}; const FORM_MASK: u32 = 0xff3f_e000; @@ -22,8 +23,7 @@ pub struct Operand { } /// Size 00 is reserved. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let operation = match word & FORM_MASK { FAMAX => AbsoluteMinMaxOperation::Maximum, FAMIN => AbsoluteMinMaxOperation::Minimum, @@ -33,7 +33,7 @@ pub fn decode(word: u32) -> Option> { 1 => Format::Half, 2 => Format::Single, 3 => Format::Double, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; Some(Ok(Operand { operation, @@ -54,7 +54,7 @@ mod tests { (FAMAX, AbsoluteMinMaxOperation::Maximum), (FAMIN, AbsoluteMinMaxOperation::Minimum), ] { - assert_eq!(decode(opcode), Some(Err(()))); + assert_eq!(decode(opcode), Some(Err(Unsupported))); for (size, format) in [(1, Format::Half), (2, Format::Single), (3, Format::Double)] { for governing in 0..=GOVERNING_MASK { for destination in 0..=REGISTER_MASK { diff --git a/crates/stela-compiler/src/aarch64/sve/floating/fp8.rs b/crates/stela-compiler/src/aarch64/sve/floating/fp8.rs index 382fc21133..4fc42f7a3a 100644 --- a/crates/stela-compiler/src/aarch64/sve/floating/fp8.rs +++ b/crates/stela-compiler/src/aarch64/sve/floating/fp8.rs @@ -1,4 +1,5 @@ //! SVE FP8 conversions. +use crate::aarch64::Unsupported; const REGISTER_MASK: u32 = 31; const SOURCE_SHIFT: u32 = 5; @@ -170,8 +171,7 @@ pub fn canonical_id(word: u32) -> Option<&'static str> { encoding(word).map(|encoding| encoding.id) } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let encoding = encoding(word)?; let source_mask = match encoding.kind { Kind::Widen { .. } => REGISTER_MASK, diff --git a/crates/stela-compiler/src/aarch64/sve/floating/rounding.rs b/crates/stela-compiler/src/aarch64/sve/floating/rounding.rs index a838df6694..058a3ce14b 100644 --- a/crates/stela-compiler/src/aarch64/sve/floating/rounding.rs +++ b/crates/stela-compiler/src/aarch64/sve/floating/rounding.rs @@ -1,4 +1,5 @@ //! SVE predicated FRINT*. +use crate::aarch64::Unsupported; use crate::aarch64::floating::{Format, rounding::RoundingOperation}; const OPCODE_MASK: u32 = 0xff3f_e000; @@ -27,8 +28,7 @@ pub struct Operand { /// Merging forms only. The FEAT_SVE2p2 zeroing forms and the bounded FRINT /// forms are not decoded. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let operation = match word & OPCODE_MASK { FRINTN => RoundingOperation::NearestEven, FRINTP => RoundingOperation::TowardPositive, @@ -43,7 +43,7 @@ pub fn decode(word: u32) -> Option> { 1 => Format::Half, 2 => Format::Single, 3 => Format::Double, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; Some(Ok(Operand { operation, @@ -61,7 +61,7 @@ mod tests { #[test] fn all_operations_widths_predicates_and_vector_aliases() { for opcode in [FRINTN, FRINTP, FRINTM, FRINTZ, FRINTA, FRINTX, FRINTI] { - assert_eq!(decode(opcode), Some(Err(()))); + assert_eq!(decode(opcode), Some(Err(Unsupported))); for (size, format) in [(1, Format::Half), (2, Format::Single), (3, Format::Double)] { for governing in 0..=GOVERNING_MASK { for register in 0..=REGISTER_MASK { diff --git a/crates/stela-compiler/src/aarch64/sve/floating_copy.rs b/crates/stela-compiler/src/aarch64/sve/floating_copy.rs index 4e4d95565c..37bab3c9b1 100644 --- a/crates/stela-compiler/src/aarch64/sve/floating_copy.rs +++ b/crates/stela-compiler/src/aarch64/sve/floating_copy.rs @@ -1,4 +1,5 @@ //! FCPY (merging) and FDUP. +use crate::aarch64::Unsupported; use crate::aarch64::floating::Format; @@ -43,8 +44,7 @@ fn expand_immediate(format: Format, immediate: u8) -> u64 { | (u64::from(fraction) << (fraction_bits - IMMEDIATE_FRACTION_BITS)) } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let governing = if word & FCPY_MASK == FCPY { Some(((word >> COPY_GOVERNING_SHIFT) & COPY_GOVERNING_MASK) as u8) } else if word & FDUP_MASK == FDUP { @@ -56,7 +56,7 @@ pub fn decode(word: u32) -> Option> { 1 => Format::Half, 2 => Format::Single, 3 => Format::Double, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; Some(Ok(Operand { format, @@ -89,8 +89,8 @@ mod tests { assert_eq!(decode(word).unwrap().unwrap().governing, None); } } - assert_eq!(decode(FCPY), Some(Err(()))); - assert_eq!(decode(FDUP), Some(Err(()))); + assert_eq!(decode(FCPY), Some(Err(Unsupported))); + assert_eq!(decode(FDUP), Some(Err(Unsupported))); // VFP imm8 0x70 is exactly +1.0 in every destination format. assert_eq!(expand_immediate(Format::Half, 0x70), 0x3c00); assert_eq!(expand_immediate(Format::Single, 0x70), 0x3f80_0000); diff --git a/crates/stela-compiler/src/aarch64/sve/integer_arithmetic.rs b/crates/stela-compiler/src/aarch64/sve/integer_arithmetic.rs index 743c977194..3898d6be3a 100644 --- a/crates/stela-compiler/src/aarch64/sve/integer_arithmetic.rs +++ b/crates/stela-compiler/src/aarch64/sve/integer_arithmetic.rs @@ -1,4 +1,5 @@ //! SVE integer arithmetic, widening and carry operations. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ElementSize, Predication}; const REGISTER_MASK: u32 = 31; const SOURCE_SHIFT: u32 = 5; @@ -127,8 +128,7 @@ const USUBLT_Z_ZZ: u32 = 0x4500_1c00; const USUBWB_Z_ZZ: u32 = 0x4500_5800; const USUBWT_Z_ZZ: u32 = 0x4500_5c00; -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let destination = (word & REGISTER_MASK) as u8; let source = ((word >> SOURCE_SHIFT) & REGISTER_MASK) as u8; let right = ((word >> RIGHT_SHIFT) & REGISTER_MASK) as u8; @@ -188,7 +188,7 @@ pub fn decode(word: u32) -> Option> { }; if let Some(operation) = operation { if matches!(operation, Binary::Divide { .. }) && element_bytes < 4 { - return Some(Err(())); + return Some(Err(Unsupported)); } return operand( element_bytes, @@ -225,7 +225,7 @@ pub fn decode(word: u32) -> Option> { if let Some(operation) = operation { let shifted = word & IMMEDIATE_SHIFT_FLAG != 0; if element_bytes == 1 && shifted { - return Some(Err(())); + return Some(Err(Unsupported)); } let value = i64::from(immediate) << if shifted { IMMEDIATE_SHIFT } else { 0 }; return operand( @@ -304,7 +304,7 @@ pub fn decode(word: u32) -> Option> { }; if let Some((unsigned, subtract, wide_left, left_top, right_top)) = widening { if element_bytes == 1 { - return Some(Err(())); + return Some(Err(Unsupported)); } return operand( element_bytes, @@ -326,15 +326,14 @@ pub fn decode(word: u32) -> Option> { impl Operand { /// MOVPRFX requirements of the follower, determined before destructive /// operands are normalized. - #[allow(clippy::result_unit_err)] pub fn prefix_requirement( self, original_word: u32, - ) -> Result, ()> { + ) -> Result, Unsupported> { use crate::aarch64::sve::prefix::{PredicatedPrefixRequirement, PrefixRequirement}; if decode(original_word) != Some(Ok(self)) { - return Err(()); + return Err(Unsupported); } let predicated = match self.predication { Predication::Merging(predicate) => Some(PredicatedPrefixRequirement { @@ -715,33 +714,33 @@ mod tests { let operand = decode(word).unwrap().unwrap(); let mut forged = operand; forged.destination = 32; - assert_eq!(forged.prefix_requirement(word), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); let mut forged = operand; forged.element_size = ElementSize::Doubleword; - assert_eq!(forged.prefix_requirement(word), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); let mut forged = operand; forged.predication = Predication::Merging(7); - assert_eq!(forged.prefix_requirement(word), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); let mut forged = operand; forged.kind = Kind::Binary { operation: Binary::Add, left: 3, right: Source::Vector(3), }; - assert_eq!(forged.prefix_requirement(word), Err(())); - assert_eq!(operand.prefix_requirement(0), Err(())); - assert_eq!(operand.prefix_requirement(SADDLB_Z_ZZ), Err(())); - assert_eq!(operand.prefix_requirement(SDIV_Z_P_ZZ), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); + assert_eq!(operand.prefix_requirement(0), Err(Unsupported)); + assert_eq!(operand.prefix_requirement(SADDLB_Z_ZZ), Err(Unsupported)); + assert_eq!(operand.prefix_requirement(SDIV_Z_P_ZZ), Err(Unsupported)); assert_eq!( operand.prefix_requirement(ADD_Z_ZI | IMMEDIATE_SHIFT_FLAG), - Err(()) + Err(Unsupported) ); // The same binary kind cannot authorize a constructive ADD; its exact // word and unpredicated role must remain distinct from the merging form. let constructive = ADD_Z_ZZ | (3 << SOURCE_SHIFT) | (5 << RIGHT_SHIFT) | 3; let constructive_operand = decode(constructive).unwrap().unwrap(); assert_eq!(constructive_operand.kind, operand.kind); - assert_eq!(operand.prefix_requirement(constructive), Err(())); + assert_eq!(operand.prefix_requirement(constructive), Err(Unsupported)); assert_eq!( constructive_operand.prefix_requirement(constructive), Ok(Some(PrefixRequirement::Forbidden)) @@ -812,7 +811,7 @@ mod tests { let word = opcode | (size << SIZE_SHIFT) | destination; let result = decode(word).unwrap(); if (widening && size == 0) || (division && size < 2) { - assert_eq!(result, Err(())); + assert_eq!(result, Err(Unsupported)); continue; } let operand = result.unwrap(); @@ -837,7 +836,10 @@ mod tests { #[test] fn immediate_byte_shift_is_reserved_and_signed_minmax_extend_imm8() { for opcode in [ADD_Z_ZI, SUB_Z_ZI, SUBR_Z_ZI] { - assert_eq!(decode(opcode | IMMEDIATE_SHIFT_FLAG), Some(Err(()))); + assert_eq!( + decode(opcode | IMMEDIATE_SHIFT_FLAG), + Some(Err(Unsupported)) + ); assert!( decode(opcode | (1 << SIZE_SHIFT) | IMMEDIATE_SHIFT_FLAG) .unwrap() diff --git a/crates/stela-compiler/src/aarch64/sve/integer_bits.rs b/crates/stela-compiler/src/aarch64/sve/integer_bits.rs index 7ccedf31d9..f1da8eaab6 100644 --- a/crates/stela-compiler/src/aarch64/sve/integer_bits.rs +++ b/crates/stela-compiler/src/aarch64/sve/integer_bits.rs @@ -1,4 +1,5 @@ //! SVE predicated bit operations: CLS, CLZ, CNT, RBIT and REVB/REVH/REVW. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ElementSize, Predication}; const OPCODE_MASK: u32 = 0xff3f_e000; @@ -34,8 +35,7 @@ pub struct Operand { pub predication: Predication, } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { use ElementSize::{Byte, Halfword, Word}; use Kind::{LeadingSignBits, LeadingZeros, PopulationCount, ReverseBits, ReverseGroups}; let kind = match word & OPCODE_MASK { @@ -52,12 +52,12 @@ pub fn decode(word: u32) -> Option> { }; let bytes = 1usize << ((word >> SIZE_SHIFT) & SIZE_MASK); let Some(element_size) = ElementSize::from_bytes(bytes) else { - return Some(Err(())); + return Some(Err(Unsupported)); }; if let ReverseGroups { group_size } = kind && element_size <= group_size { - return Some(Err(())); + return Some(Err(Unsupported)); } Some(Ok(Operand { kind, @@ -115,7 +115,7 @@ mod tests { })) ); } else { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); } } } diff --git a/crates/stela-compiler/src/aarch64/sve/integer_comparison.rs b/crates/stela-compiler/src/aarch64/sve/integer_comparison.rs index 4b92c3d942..0081992776 100644 --- a/crates/stela-compiler/src/aarch64/sve/integer_comparison.rs +++ b/crates/stela-compiler/src/aarch64/sve/integer_comparison.rs @@ -1,4 +1,5 @@ //! SVE integer comparisons into predicates (CMP*). +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; const SIZE_SHIFT: u32 = 22; @@ -241,13 +242,13 @@ const ENCODINGS: [Encoding; 26] = [ }, ]; -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let encoding = ENCODINGS .iter() .find(|entry| word & entry.mask == entry.value)?; let element_bytes = 1 << ((word >> SIZE_SHIFT) & SIZE_MASK); if encoding.source == SourceKind::WideVector && element_bytes == 8 { - return Some(Err(())); + return Some(Err(Unsupported)); } let right = match encoding.source { SourceKind::Immediate => { @@ -300,7 +301,7 @@ mod tests { | destination; let operand = decode(word); if encoding.source == SourceKind::WideVector && size == SIZE_MASK { - assert_eq!(operand, Some(Err(()))); + assert_eq!(operand, Some(Err(Unsupported))); } else { let operand = operand.unwrap().unwrap(); assert_eq!(operand.relation, encoding.relation); diff --git a/crates/stela-compiler/src/aarch64/sve/integer_logic.rs b/crates/stela-compiler/src/aarch64/sve/integer_logic.rs index 5d7f418793..86443d9f05 100644 --- a/crates/stela-compiler/src/aarch64/sve/integer_logic.rs +++ b/crates/stela-compiler/src/aarch64/sve/integer_logic.rs @@ -1,5 +1,6 @@ //! SVE vector Boolean operations, copies and prefix moves. use super::super::{Register, Width, logical_mask, register}; +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ElementSize, Predication}; const REGISTER_MASK: u32 = 31; @@ -125,8 +126,7 @@ pub struct Operand { pub kind: Kind, } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let destination = (word & REGISTER_MASK) as u8; let source = ((word >> SOURCE_SHIFT) & REGISTER_MASK) as u8; let right = ((word >> RIGHT_SHIFT) & REGISTER_MASK) as u8; @@ -202,7 +202,7 @@ pub fn decode(word: u32) -> Option> { (encoded >> BITMASK_ROTATION_SHIFT) & BITMASK_FIELD_MASK, encoded & BITMASK_FIELD_MASK, ) else { - return Some(Err(())); + return Some(Err(Unsupported)); }; operand.element_size = ElementSize::Doubleword; operand.kind = Kind::Immediate { operation, value }; @@ -240,7 +240,7 @@ pub fn decode(word: u32) -> Option> { ) { let shifted = word & COPY_SHIFT_FLAG != 0; if element_size == ElementSize::Byte && shifted { - return Some(Err(())); + return Some(Err(Unsupported)); } let value = ((word >> SOURCE_SHIFT) & COPY_IMMEDIATE_MASK_BITS) as u8 as i8; let predicate = ((word >> COPY_PREDICATE_SHIFT) & WIDE_PREDICATE_MASK) as u8; @@ -290,15 +290,14 @@ pub fn decode_prefix(word: u32) -> Option { impl Operand { /// MOVPRFX requirements of the follower word. The typed operand is checked /// again so that normalized kinds cannot admit another encoding. - #[allow(clippy::result_unit_err)] pub fn prefix_requirement( self, word: u32, - ) -> Result, ()> { + ) -> Result, Unsupported> { use super::prefix::{PredicatedPrefixRequirement, PrefixRequirement}; if decode(word) != Some(Ok(self)) { - return Err(()); + return Err(Unsupported); } let predicated = match self.predication { Predication::Merging(predicate) => Some(PredicatedPrefixRequirement { @@ -543,7 +542,7 @@ mod tests { | if shifted { COPY_SHIFT_FLAG } else { 0 }; let result = decode(word).unwrap(); if size == 0 && shifted { - assert_eq!(result, Err(())); + assert_eq!(result, Err(Unsupported)); } else { let operand = result.unwrap(); assert_eq!(operand.predication, Predication::Zeroing(predicate as u8)); @@ -567,7 +566,10 @@ mod tests { #[test] fn reserved_logical_immediates_decline_and_zeroing_unary_is_outside_inventory() { for opcode in [AND_IMMEDIATE, ORR_IMMEDIATE, EOR_IMMEDIATE] { - assert_eq!(decode(opcode | (63 << SOURCE_SHIFT)), Some(Err(()))); + assert_eq!( + decode(opcode | (63 << SOURCE_SHIFT)), + Some(Err(Unsupported)) + ); assert!(decode(opcode).unwrap().is_ok()); } assert_eq!(decode(NOT_PREDICATED ^ (1 << 20)), None); diff --git a/crates/stela-compiler/src/aarch64/sve/integer_predicate_move.rs b/crates/stela-compiler/src/aarch64/sve/integer_predicate_move.rs index 28caaef531..036c2144ce 100644 --- a/crates/stela-compiler/src/aarch64/sve/integer_predicate_move.rs +++ b/crates/stela-compiler/src/aarch64/sve/integer_predicate_move.rs @@ -1,4 +1,5 @@ //! PMOV between predicates and vector bitmaps. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; const DESTINATION_MASK: u32 = 31; @@ -24,8 +25,7 @@ pub struct Operand { pub portion: u8, } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let (element_size, portion) = if word & BYTE_MASK == BYTE { (ElementSize::Byte, 0) } else if word & HALFWORD_MASK == HALFWORD { diff --git a/crates/stela-compiler/src/aarch64/sve/integer_products.rs b/crates/stela-compiler/src/aarch64/sve/integer_products.rs index 6acee37aee..3c03275e09 100644 --- a/crates/stela-compiler/src/aarch64/sve/integer_products.rs +++ b/crates/stela-compiler/src/aarch64/sve/integer_products.rs @@ -1,4 +1,5 @@ //! SVE integer multiplies. Saturation does not set FPSR.QC. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ElementSize, Predication}; const REGISTER_MASK: u32 = 31; @@ -235,7 +236,7 @@ enum Format { IndexedComplexWord, } -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let (kind, format) = classify(word)?; let element_size = match format { Format::IndexedHalfword | Format::IndexedComplexHalfword => ElementSize::Halfword, @@ -251,11 +252,11 @@ pub fn decode(word: u32) -> Option> { }, }; if kind.widening() && element_size == ElementSize::Byte { - return Some(Err(())); + return Some(Err(Unsupported)); } if matches!(kind, Kind::Polynomial { widening: true, .. }) && element_size == ElementSize::Word { - return Some(Err(())); + return Some(Err(Unsupported)); } let destination = (word & REGISTER_MASK) as u8; let source_field = ((word >> SOURCE_SHIFT) & REGISTER_MASK) as u8; @@ -645,15 +646,14 @@ fn classify(word: u32) -> Option<(Kind, Format)> { impl Operand { /// MOVPRFX requirements of the follower word, independent of the normalized /// kind. Unlisted encodings are refused. - #[allow(clippy::result_unit_err)] pub fn prefix_requirement( self, original_word: u32, - ) -> Result, ()> { + ) -> Result, Unsupported> { use crate::aarch64::sve::prefix::{PredicatedPrefixRequirement, PrefixRequirement}; if decode(original_word) != Some(Ok(self)) { - return Err(()); + return Err(Unsupported); } let source_bit = |register: u8| 1_u32 << register; let multiplier_mask = match self.multiplier { @@ -693,7 +693,7 @@ impl Operand { ) { return Ok(Some(vector( predicated, - multiplier_mask | source_bit(self.accumulator.ok_or(())?), + multiplier_mask | source_bit(self.accumulator.ok_or(Unsupported)?), ))); } if matches!( @@ -928,7 +928,7 @@ mod tests { SQDMULLB_Z_ZZ, SQDMULLT_Z_ZZ, ] { - assert_eq!(decode(opcode), Some(Err(()))); + assert_eq!(decode(opcode), Some(Err(Unsupported))); } let cross = decode(SQDMLALBT_Z_ZZZ | (1 << SIZE_SHIFT)) .unwrap() diff --git a/crates/stela-compiler/src/aarch64/sve/integer_saturation.rs b/crates/stela-compiler/src/aarch64/sve/integer_saturation.rs index 0e3ecc1f7d..106064ec5a 100644 --- a/crates/stela-compiler/src/aarch64/sve/integer_saturation.rs +++ b/crates/stela-compiler/src/aarch64/sve/integer_saturation.rs @@ -1,5 +1,6 @@ //! SVE saturating, halving and absolute-difference arithmetic. Saturation does //! not set FPSR.QC. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ElementSize, Predication}; @@ -146,8 +147,7 @@ fn difference(signedness: Signedness, widening: Option, accumulate: bool) } } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { use Arithmetic::{Add, ReverseSubtract, Subtract}; use Half::{Bottom, Top}; use Signedness::{Signed, Unsigned}; @@ -214,7 +214,7 @@ pub fn decode(word: u32) -> Option> { if let Some(kind) = immediate { let scaled = word & IMMEDIATE_SCALE_FLAG != 0; if element_size == ElementSize::Byte && scaled { - return Some(Err(())); + return Some(Err(Unsupported)); } let immediate = ((word >> SOURCE_SHIFT) & IMMEDIATE_MASK) << if scaled { IMMEDIATE_SCALE_SHIFT } else { 0 }; @@ -264,7 +264,7 @@ pub fn decode(word: u32) -> Option> { } ) && element_size == ElementSize::Byte { - return Some(Err(())); + return Some(Err(Unsupported)); } Some(Ok(Operand { destination, @@ -279,15 +279,14 @@ pub fn decode(word: u32) -> Option> { impl Operand { /// MOVPRFX requirements of the follower word. Call before normalizing /// destructive operands; the typed operand must still match the word. - #[allow(clippy::result_unit_err)] pub fn prefix_requirement( self, original_word: u32, - ) -> Result, ()> { + ) -> Result, Unsupported> { use crate::aarch64::sve::prefix::{PredicatedPrefixRequirement, PrefixRequirement}; if decode(original_word) != Some(Ok(self)) { - return Err(()); + return Err(Unsupported); } let vector = |predicated, other_vector_sources| PrefixRequirement::Vector { destination: self.destination, @@ -319,12 +318,12 @@ impl Operand { | USQADD_Z_P_ZZ ) { let Predication::Merging(predicate) = self.predication else { - return Err(()); + return Err(Unsupported); }; let source = match self.right { Input::None => self.left, Input::Vector(source) => source, - Input::Immediate(_) => return Err(()), + Input::Immediate(_) => return Err(Unsupported), }; // All twenty forms use equal destination and first-source widths. return Ok(Some(vector( @@ -343,14 +342,14 @@ impl Operand { } if original_word & COMPLEX_OPCODE_MASK == SQCADD_Z_ZZ { let Input::Vector(source) = self.right else { - return Err(()); + return Err(Unsupported); }; return Ok(Some(vector(None, source_bit(source)))); } let requirement = match original_word & REGISTER_OPCODE_MASK { SABA_Z_ZZZ | SABALB_Z_ZZZ | SABALT_Z_ZZZ | UABA_Z_ZZZ | UABALB_Z_ZZZ | UABALT_Z_ZZZ => { let Input::Vector(right) = self.right else { - return Err(()); + return Err(Unsupported); }; Some(vector(None, source_bit(self.left) | source_bit(right))) } @@ -850,32 +849,35 @@ mod tests { let operand = decode(word).unwrap().unwrap(); let mut forged = operand; forged.destination = 4; - assert_eq!(forged.prefix_requirement(word), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); forged = operand; forged.left ^= 1; - assert_eq!(forged.prefix_requirement(word), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); forged = operand; forged.right = match operand.right { Input::Vector(v) => Input::Vector(v ^ 1), Input::Immediate(v) => Input::Immediate(v ^ 1), Input::None => Input::Vector(0), }; - assert_eq!(forged.prefix_requirement(word), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); forged = operand; forged.element_size = ElementSize::Quadword; - assert_eq!(forged.prefix_requirement(word), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); forged = operand; forged.predication = Predication::Zeroing(2); - assert_eq!(forged.prefix_requirement(word), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); forged = operand; forged.kind = if operand.kind == Kind::Absolute { Kind::Negate } else { Kind::Absolute }; - assert_eq!(forged.prefix_requirement(word), Err(())); - assert_eq!(operand.prefix_requirement(word ^ (1 << 31)), Err(())); - assert_eq!(operand.prefix_requirement(0), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); + assert_eq!( + operand.prefix_requirement(word ^ (1 << 31)), + Err(Unsupported) + ); + assert_eq!(operand.prefix_requirement(0), Err(Unsupported)); } } @@ -892,9 +894,9 @@ mod tests { | 31 | if shifted { 1 << 13 } else { 0 }; if size == 0 && shifted { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); let operand = decode(fact.word).unwrap().unwrap(); - assert_eq!(operand.prefix_requirement(word), Err(())); + assert_eq!(operand.prefix_requirement(word), Err(Unsupported)); } else { let operand = decode(word).unwrap().unwrap(); assert_eq!( @@ -911,9 +913,9 @@ mod tests { } } if fact.minimum_size == 1 { - assert_eq!(decode(fact.word), Some(Err(()))); + assert_eq!(decode(fact.word), Some(Err(Unsupported))); let operand = decode(fact.word | (1 << 22)).unwrap().unwrap(); - assert_eq!(operand.prefix_requirement(fact.word), Err(())); + assert_eq!(operand.prefix_requirement(fact.word), Err(Unsupported)); } } for size in 0..4 { @@ -933,7 +935,7 @@ mod tests { for zeroing in [0x440aa000, 0x440ba000] { assert_eq!(decode(zeroing), None); let operand = decode(0x4408a000).unwrap().unwrap(); - assert_eq!(operand.prefix_requirement(zeroing), Err(())); + assert_eq!(operand.prefix_requirement(zeroing), Err(Unsupported)); } } @@ -1049,7 +1051,10 @@ mod tests { #[test] fn immediate_scaling_and_widening_reserved_sizes_are_explicit() { for opcode in [SQADD_Z_ZI, UQADD_Z_ZI, SQSUB_Z_ZI, UQSUB_Z_ZI] { - assert_eq!(decode(opcode | IMMEDIATE_SCALE_FLAG), Some(Err(()))); + assert_eq!( + decode(opcode | IMMEDIATE_SCALE_FLAG), + Some(Err(Unsupported)) + ); for size in 1..=SIZE_MASK { let operand = decode( opcode @@ -1072,7 +1077,7 @@ mod tests { UABALB_Z_ZZZ, UABALT_Z_ZZZ, ] { - assert_eq!(decode(opcode), Some(Err(()))); + assert_eq!(decode(opcode), Some(Err(Unsupported))); for size in 1..=SIZE_MASK { assert!(decode(opcode | (size << SIZE_SHIFT)).unwrap().is_ok()); } diff --git a/crates/stela-compiler/src/aarch64/sve/memory_load.rs b/crates/stela-compiler/src/aarch64/sve/memory_load.rs index a9863b33a9..d18ca36147 100644 --- a/crates/stela-compiler/src/aarch64/sve/memory_load.rs +++ b/crates/stela-compiler/src/aarch64/sve/memory_load.rs @@ -2,6 +2,7 @@ //! staged in full, so a fault leaves it unchanged. use super::super::register; use super::memory::{Address, Extension, Offset, Scale}; +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; const REGISTER_MASK: u32 = 31; @@ -60,7 +61,7 @@ pub struct Operand { pub tag_checked: bool, } -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if word & WHOLE_VECTOR_MASK == WHOLE_VECTOR { return Some(Ok(whole(word, Kind::WholeVector))); } @@ -94,7 +95,7 @@ pub fn decode(word: u32) -> Option> { } else { let index = (word >> INDEX_SHIFT) & REGISTER_MASK; if index == REGISTER_MASK { - return Some(Err(())); + return Some(Err(Unsupported)); } Offset::Register { index: register(index, false), @@ -222,7 +223,7 @@ const LD1RSW_S64: u32 = 0x84c08000; const LD1RW_U32: u32 = 0x8540c000; const LD1RW_U64: u32 = 0x8540e000; -fn decode_replicate(word: u32) -> Option> { +fn decode_replicate(word: u32) -> Option> { let quad_immediate = word & QUAD_IMMEDIATE_MASK == QUAD_IMMEDIATE; let quad_register = word & QUAD_REGISTER_MASK == QUAD_REGISTER; let (kind, memory_bytes, element_bytes, extension) = if quad_immediate || quad_register { @@ -258,7 +259,7 @@ fn decode_replicate(word: u32) -> Option> { let offset = if quad_register { let index = (word >> INDEX_SHIFT) & REGISTER_MASK; if index == REGISTER_MASK { - return Some(Err(())); + return Some(Err(Unsupported)); } Offset::Register { index: register(index, false), @@ -866,7 +867,10 @@ mod tests { .. } )); - assert_eq!(decode(word | (REGISTER_MASK << INDEX_SHIFT)), Some(Err(()))); + assert_eq!( + decode(word | (REGISTER_MASK << INDEX_SHIFT)), + Some(Err(Unsupported)) + ); } } } diff --git a/crates/stela-compiler/src/aarch64/sve/memory_multi.rs b/crates/stela-compiler/src/aarch64/sve/memory_multi.rs index e2899473a4..a07aa884fc 100644 --- a/crates/stela-compiler/src/aarch64/sve/memory_multi.rs +++ b/crates/stela-compiler/src/aarch64/sve/memory_multi.rs @@ -1,6 +1,7 @@ //! SME2/SVE2.1 multi-vector loads and stores governed by predicate-as-counter. use super::super::{Register, register}; use super::memory::{Address, Offset, Scale}; +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ ElementSize, execution::{GuestMemoryQuantity, ScalableAccessCheck, ScalableAccessRequirements}, @@ -62,15 +63,14 @@ pub(crate) const fn guest_memory_quantity(operand: &Operand) -> GuestMemoryQuant } /// Reserved tuple alignment and immediate fields decline without another decode. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if word & CLASS_MASK != CLASS_VALUE { return None; } let immediate = word & IMMEDIATE_ADDRESS != 0; let quad = word & FOUR_REGISTERS != 0; if (immediate && word & IMMEDIATE_RESERVED != 0) || (quad && word & QUAD_RESERVED != 0) { - return Some(Err(())); + return Some(Err(Unsupported)); } let offset = if immediate { let raw = ((word >> OFFSET_SHIFT) & IMMEDIATE_MASK) as i8; @@ -195,11 +195,11 @@ mod tests { fn reserved_fields_are_explicit_and_other_classes_do_not_match() { assert_eq!( decode(CLASS_VALUE | FOUR_REGISTERS | QUAD_RESERVED), - Some(Err(())) + Some(Err(Unsupported)) ); assert_eq!( decode(CLASS_VALUE | IMMEDIATE_ADDRESS | IMMEDIATE_RESERVED), - Some(Err(())) + Some(Err(Unsupported)) ); for bit in 23..32 { assert_eq!(decode(CLASS_VALUE ^ (1 << bit)), None); diff --git a/crates/stela-compiler/src/aarch64/sve/memory_store.rs b/crates/stela-compiler/src/aarch64/sve/memory_store.rs index 67679a93cb..f005c5de47 100644 --- a/crates/stela-compiler/src/aarch64/sve/memory_store.rs +++ b/crates/stela-compiler/src/aarch64/sve/memory_store.rs @@ -1,6 +1,7 @@ //! SVE contiguous and whole-register stores, and PRF* hints. Structured source //! tuples wrap modulo 32. use super::memory::{Address, Offset, Scale}; +use crate::aarch64::Unsupported; use crate::aarch64::{ register, scalable::{ @@ -231,7 +232,7 @@ const FORMS: &[Form] = &[ ]; /// None means another allocation; Err marks a recognized unallocated operand. -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if let Some(form) = grouped_form(word) { return Some(decode_store(word, form).map(Operand::Store)); } @@ -277,19 +278,19 @@ fn base(word: u32) -> crate::aarch64::Register { register((word >> BASE_SHIFT) & REGISTER_MASK, true) } -fn decode_store(word: u32, form: Form) -> Result { +fn decode_store(word: u32, form: Form) -> Result { let element_bytes = match form.element { Element::Encoded => BYTE_BYTES << ((word >> SIZE_SHIFT) & SIZE_MASK), Element::Word => WORD_BYTES << ((word >> SIZE_SHIFT) & WORD_SIZE_MASK), Element::Fixed(bytes) => bytes, }; if element_bytes < form.memory_bytes { - return Err(()); + return Err(Unsupported); } let offset = if form.register_offset { let index = (word >> OFFSET_SHIFT) & REGISTER_MASK; if index == REGISTER_MASK { - return Err(()); + return Err(Unsupported); } Offset::Register { index: register(index, false), @@ -352,7 +353,7 @@ fn decode_whole(word: u32) -> Option { }) } -fn decode_prefetch(word: u32) -> Option> { +fn decode_prefetch(word: u32) -> Option> { let (offset, size_shift) = if word & PREFETCH_IMMEDIATE_MASK == PREFETCH_IMMEDIATE_CLASS { let offset_mask = (1 << PREFETCH_OFFSET_BITS) - 1; ( @@ -368,7 +369,7 @@ fn decode_prefetch(word: u32) -> Option> { } else if word & PREFETCH_REGISTER_MASK == PREFETCH_REGISTER_CLASS { let index = (word >> OFFSET_SHIFT) & REGISTER_MASK; if index == REGISTER_MASK { - return Some(Err(())); + return Some(Err(Unsupported)); } let shift = ((word >> REGISTER_SIZE_SHIFT) & SIZE_MASK) as u8; ( @@ -452,7 +453,7 @@ mod tests { | (offset << OFFSET_SHIFT); let result = decode(word).expect("owned store class"); if form.register_offset && offset == REGISTER_MASK { - assert_eq!(result, Err(())); + assert_eq!(result, Err(Unsupported)); continue; } let Operand::Store(store) = result.expect("allocated operands") else { @@ -489,7 +490,7 @@ mod tests { #[test] fn narrowing_halfword_rejects_byte_source_elements() { for class in [0xe480_e000, 0xe480_4000] { - assert_eq!(decode(class), Some(Err(()))); + assert_eq!(decode(class), Some(Err(Unsupported))); assert!(matches!( decode(class | (1 << SIZE_SHIFT)), Some(Ok(Operand::Store(_))) @@ -571,7 +572,7 @@ mod tests { | hint | (size << REGISTER_SIZE_SHIFT) | (REGISTER_MASK << OFFSET_SHIFT); - assert_eq!(decode(reserved), Some(Err(()))); + assert_eq!(decode(reserved), Some(Err(Unsupported))); } } } diff --git a/crates/stela-compiler/src/aarch64/sve/memory_structure.rs b/crates/stela-compiler/src/aarch64/sve/memory_structure.rs index c2cc3f8d78..687fe402e4 100644 --- a/crates/stela-compiler/src/aarch64/sve/memory_structure.rs +++ b/crates/stela-compiler/src/aarch64/sve/memory_structure.rs @@ -1,5 +1,6 @@ //! SVE LD2, LD3 and LD4, including 128-bit elements. use super::memory::{Address, Offset, Scale}; +use crate::aarch64::Unsupported; use crate::aarch64::{ register, scalable::{ @@ -58,7 +59,7 @@ impl Operand { /// Predicates select bit `element_index * element_bytes`; inactive lanes zero. /// Base31 denotes SP. Register-offset forms always enable architectural tag /// checks, whereas immediate-offset forms enable them only for a GPR base. -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let (immediate, quadword) = match word { _ if word & IMMEDIATE_MASK == IMMEDIATE_CLASS => (true, false), _ if word & REGISTER_MASK == REGISTER_CLASS => (false, false), @@ -94,7 +95,7 @@ pub fn decode(word: u32) -> Option> { } else { let index = (word >> OFFSET_SHIFT) & REGISTER_FIELD_MASK; if index == REGISTER_FIELD_MASK { - return Some(Err(())); + return Some(Err(Unsupported)); } Offset::Register { index: register(index, false), @@ -218,7 +219,7 @@ mod tests { } else { assert_eq!( decode(class | REGISTER_FIELD_MASK << OFFSET_SHIFT), - Some(Err(())) + Some(Err(Unsupported)) ); } } diff --git a/crates/stela-compiler/src/aarch64/sve/predicate_generation.rs b/crates/stela-compiler/src/aarch64/sve/predicate_generation.rs index 143af42a72..e8c0499bcb 100644 --- a/crates/stela-compiler/src/aarch64/sve/predicate_generation.rs +++ b/crates/stela-compiler/src/aarch64/sve/predicate_generation.rs @@ -1,5 +1,6 @@ //! Predicate generation: PTRUE, PFALSE, WHILE*, BRK* and PNEXT. PN registers are //! P8-P15. +use crate::aarch64::Unsupported; pub use basic::BasicOperand; pub use breaks::{Boundary, BreakKind, BreakOperand}; @@ -28,7 +29,7 @@ impl Operand { /// None means another decoder owns the word; Err means an owned but invalid /// operand. -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if let Some(result) = basic::decode_basic(word) { return Some(result.map(Operand::Basic)); } @@ -41,7 +42,7 @@ pub fn decode(word: u32) -> Option> { mod basic { //! Basic predicate generation. Predicate indices are packed architectural P registers. use crate::aarch64::scalable::ElementSize; - use crate::aarch64::{Register, Width, register}; + use crate::aarch64::{Register, Unsupported, Width, register}; const PREDICATE_MASK: u32 = 15; const SCALAR_REGISTER_MASK: u32 = 31; @@ -108,7 +109,7 @@ mod basic { /// No basic form has reserved operand encodings. Unnamed five-bit PTRUE patterns /// execute with zero active elements; they are not decoder errors. GPR31 is ZR. - pub fn decode_basic(word: u32) -> Option> { + pub fn decode_basic(word: u32) -> Option> { let destination = (word & PREDICATE_MASK) as u8; let element = ElementSize::from_bytes(1 << ((word >> SIZE_SHIFT) & SIZE_MASK))?; let near_source = ((word >> FIRST_SOURCE_SHIFT) & PREDICATE_MASK) as u8; @@ -253,6 +254,8 @@ mod basic { mod breaks { //! Predicate breaks decode operand roles without state-layout assumptions. + use crate::aarch64::Unsupported; + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Boundary { Before, @@ -298,7 +301,7 @@ mod breaks { ((word >> shift) & PREDICATE_FIELD_MASK) as u8 } - pub fn decode(word: u32) -> Option> { + pub fn decode(word: u32) -> Option> { let previous_source = predicate(word, PREVIOUS_SOURCE_SHIFT); let (kind, set_flags) = match word & BREAK_FLAGS_MASK { BRKAS => ( @@ -434,7 +437,7 @@ mod whiles { const PAIR_DESTINATION_MASK: u32 = 14; use crate::aarch64::scalable::ElementSize; - use crate::aarch64::{Register, Width, register}; + use crate::aarch64::{Register, Unsupported, Width, register}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Comparison { SignedLt, @@ -638,7 +641,7 @@ mod whiles { } /// All matching operand fields are allocated; mode/feature checks belong to the caller. /// Scalar sources31 are ZR, never SP. Pair destinations are encoded even first registers. - pub fn decode(word: u32) -> Option> { + pub fn decode(word: u32) -> Option> { let form = FORMS.iter().find(|form| word & form.mask == form.class)?; let element = ElementSize::from_bytes(1 << ((word >> ELEMENT_SIZE_SHIFT) & ELEMENT_SIZE_MASK))?; diff --git a/crates/stela-compiler/src/aarch64/sve/predicate_logic.rs b/crates/stela-compiler/src/aarch64/sve/predicate_logic.rs index 69d53904a0..4c250244e9 100644 --- a/crates/stela-compiler/src/aarch64/sve/predicate_logic.rs +++ b/crates/stela-compiler/src/aarch64/sve/predicate_logic.rs @@ -1,4 +1,5 @@ //! Predicate Boolean operations, permutes and predicate-as-counter extraction. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; @@ -128,8 +129,7 @@ pub struct Operand { } /// Feature and streaming-mode checks belong to the shared SVE decode boundary. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let destination = (word & PREDICATE_MASK) as u8; let left = ((word >> SOURCE_SHIFT) & PREDICATE_MASK) as u8; let right = ((word >> RIGHT_SHIFT) & PREDICATE_MASK) as u8; @@ -194,7 +194,7 @@ pub fn decode(word: u32) -> Option> { let size_encoding = (((word >> PSEL_SIZE_HIGH_SHIFT) & 1) << 3) | ((word >> PSEL_SIZE_LOW_SHIFT) & 7); if size_encoding == 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } let size = size_encoding.trailing_zeros(); let immediate = diff --git a/crates/stela-compiler/src/aarch64/sve/rearrange.rs b/crates/stela-compiler/src/aarch64/sve/rearrange.rs index 67b54df9f2..56fec98966 100644 --- a/crates/stela-compiler/src/aarch64/sve/rearrange.rs +++ b/crates/stela-compiler/src/aarch64/sve/rearrange.rs @@ -1,4 +1,5 @@ //! SVE permutes and vector generation (INDEX, DUP, ZIP, UZP, TRN, REV, TBL, ...). +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; use crate::aarch64::{Register, Width, logical_mask}; @@ -169,7 +170,7 @@ fn index_register(encoded: u8) -> IndexOperand { } /// None is another allocation; Err is an allocated class with reserved operands. -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let destination = (word & REGISTER_MASK) as u8; let source = ((word >> SOURCE_SHIFT) & REGISTER_MASK) as u8; let second = ((word >> SECOND_SHIFT) & REGISTER_MASK) as u8; @@ -183,7 +184,7 @@ pub fn decode(word: u32) -> Option> { let operand = if word & DUPQ_Z_ZI_MASK == DUPQ_Z_ZI_CLASS { let tsz = (word >> SECOND_SHIFT) & SEGMENT_IMMEDIATE_MASK; if tsz == 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } let low_bit = tsz.trailing_zeros(); let element_size = ElementSize::from_bytes(1 << low_bit).expect("nonzero four-bit tsz"); @@ -407,7 +408,7 @@ pub fn decode(word: u32) -> Option> { immediate & LOGICAL_FIELD_MASK, ) { Some(mask) => mask, - None => return Some(Err(())), + None => return Some(Err(Unsupported)), }; Operand::DuplicateMask { destination, mask } } else if word & INDEX_Z_II_MASK == INDEX_Z_II_CLASS { @@ -447,15 +448,14 @@ pub fn decode(word: u32) -> Option> { impl Operand { /// MOVPRFX follower requirements from the specification. Other encodings /// are refused even when their typed operand matches. - #[allow(clippy::result_unit_err)] pub fn prefix_requirement( self, original_word: u32, - ) -> Result, ()> { + ) -> Result, Unsupported> { use crate::aarch64::sve::prefix::PrefixRequirement; if decode(original_word) != Some(Ok(self)) { - return Err(()); + return Err(Unsupported); } let permitted = match self { Self::Extract { @@ -624,7 +624,7 @@ mod tests { DUPM_Z_I_CLASS | (LOGICAL_IMMEDIATE_MASK << SOURCE_SHIFT), REVD_Z_P_Z_M_CLASS | (1 << SIZE_SHIFT), ] { - assert_eq!(decoded.prefix_requirement(other), Err(())); + assert_eq!(decoded.prefix_requirement(other), Err(Unsupported)); } let forged = Operand::Extract { destination: DESTINATION, @@ -633,7 +633,7 @@ mod tests { byte_offset: 0, segment: false, }; - assert_eq!(forged.prefix_requirement(word), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); } #[test] @@ -813,7 +813,7 @@ mod tests { for encoded in 0..=REGISTER_MASK { let decoded = decode(DUPQ_Z_ZI_CLASS | (encoded << SECOND_SHIFT)); if encoded & SEGMENT_IMMEDIATE_MASK == 0 { - assert_eq!(decoded, Some(Err(()))); + assert_eq!(decoded, Some(Err(Unsupported))); } else { let Some(Ok(Operand::DuplicateSegment { element_size, @@ -843,7 +843,7 @@ mod tests { Operand::DuplicateMask { mask, .. } => mask, _ => panic!("wrong duplicate allocation"), })), - Some(expected.ok_or(())) + Some(expected.ok_or(Unsupported)) ); } } diff --git a/crates/stela-compiler/src/aarch64/sve/rearrange_extract.rs b/crates/stela-compiler/src/aarch64/sve/rearrange_extract.rs index 0989fee3d7..776c7f5f45 100644 --- a/crates/stela-compiler/src/aarch64/sve/rearrange_extract.rs +++ b/crates/stela-compiler/src/aarch64/sve/rearrange_extract.rs @@ -1,4 +1,5 @@ //! SVE element extraction, broadcast and insertion (LAST*, CLAST*, INSR, ...). +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; use crate::aarch64::{Register, register}; @@ -84,8 +85,8 @@ fn element_size(word: u32) -> ElementSize { } } -/// None is outside this family; Some(Err(())) is a reserved family encoding. -pub fn decode(word: u32) -> Option> { +/// None is outside this family; Some(Err(Unsupported)) is a reserved family encoding. +pub fn decode(word: u32) -> Option> { let mut element_size = element_size(word); let destination_index = (word & REGISTER_MASK) as u8; let source_index = ((word >> SOURCE_SHIFT) & REGISTER_MASK) as u8; @@ -135,7 +136,7 @@ pub fn decode(word: u32) -> Option> { } else if word & DUP_IMMEDIATE_MASK == DUP_IMMEDIATE { let shifted = word & SHIFT_FLAG != 0; if element_size == ElementSize::Byte && shifted { - return Some(Err(())); + return Some(Err(Unsupported)); } let immediate = ((word >> IMMEDIATE_SHIFT) & IMMEDIATE_MASK) as u8 as i8 as i16; ( @@ -154,7 +155,7 @@ pub fn decode(word: u32) -> Option> { } else if word & DUP_INDEX_MASK == DUP_INDEX { let size = (word >> INDEX_SIZE_SHIFT) & INDEX_SIZE_MASK; if size == 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } let lowest = size.trailing_zeros(); element_size = ElementSize::from_bytes(1 << lowest)?; @@ -189,15 +190,14 @@ pub fn decode(word: u32) -> Option> { impl Operand { /// Canonical-word MOVPRFX requirements for the four documented followers. /// Scalar V sources share Z storage; general-register sources do not. - #[allow(clippy::result_unit_err)] pub fn prefix_requirement( self, original_word: u32, - ) -> Result, ()> { + ) -> Result, Unsupported> { use crate::aarch64::sve::prefix::PrefixRequirement; if decode(original_word) != Some(Ok(self)) { - return Err(()); + return Err(Unsupported); } let Destination::Vector(destination) = self.destination else { return Ok(None); @@ -415,7 +415,7 @@ mod tests { let word = word(INSR_SCALAR, SOURCE, DESTINATION); let decoded = operand(word); for other in [word ^ 1, 0, DUP_INDEX, DUP_IMMEDIATE | SHIFT_FLAG] { - assert_eq!(decoded.prefix_requirement(other), Err(())); + assert_eq!(decoded.prefix_requirement(other), Err(Unsupported)); } for forged in [ Operand { @@ -431,7 +431,7 @@ mod tests { ..decoded }, ] { - assert_eq!(forged.prefix_requirement(word), Err(())); + assert_eq!(forged.prefix_requirement(word), Err(Unsupported)); } } @@ -585,7 +585,7 @@ mod tests { | (immediate << IMMEDIATE_SHIFT) | if shifted { SHIFT_FLAG } else { 0 }; if size == 0 && shifted { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); } else { let signed = immediate as u8 as i8 as i16; let expected = if shifted { @@ -607,7 +607,7 @@ mod tests { for high in 0..=INDEX_HIGH_MASK { let word = DUP_INDEX | (size << INDEX_SIZE_SHIFT) | (high << INDEX_HIGH_SHIFT); if size == 0 { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); continue; } let lowest = size.trailing_zeros(); diff --git a/crates/stela-compiler/src/aarch64/sve/rearrange_widen.rs b/crates/stela-compiler/src/aarch64/sve/rearrange_widen.rs index d6068433b0..81bf83d6b7 100644 --- a/crates/stela-compiler/src/aarch64/sve/rearrange_widen.rs +++ b/crates/stela-compiler/src/aarch64/sve/rearrange_widen.rs @@ -1,4 +1,5 @@ //! SVE unpacks, pairwise arithmetic and high-narrowing operations. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ElementSize, Predication}; const SIZE_SHIFT: u32 = 22; @@ -104,15 +105,14 @@ pub struct Operand { impl Operand { /// MOVPRFX follower requirements from the specification. - #[allow(clippy::result_unit_err)] pub fn prefix_requirement( self, original_word: u32, - ) -> Result, ()> { + ) -> Result, Unsupported> { use super::prefix::{PredicatedPrefixRequirement, PrefixRequirement}; if decode(original_word) != Some(Ok(self)) { - return Err(()); + return Err(Unsupported); } let (source, predicated) = match (original_word & PREDICATED_MASK, self.kind) { (ADDP | SMAXP | UMAXP | SMINP | UMINP, Kind::Pair { right, .. }) => (right, None), @@ -121,7 +121,7 @@ impl Operand { Kind::Extend { source, .. } | Kind::PairAccumulate { source, .. }, ) => { let Predication::Merging(predicate) = self.predication else { - return Err(()); + return Err(Unsupported); }; ( source, @@ -145,8 +145,7 @@ impl Operand { } } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { use Arithmetic::{Add, Subtract}; use Half::{Bottom, Top}; use Signedness::{Signed, Unsigned}; @@ -303,7 +302,7 @@ pub fn decode(word: u32) -> Option> { _ => ElementSize::Halfword.bits(), }; if element_size.bits() < minimum_bits { - return Some(Err(())); + return Some(Err(Unsupported)); } let predication = match kind { Kind::Extend { .. } | Kind::Pair { .. } | Kind::PairAccumulate { .. } => { @@ -635,7 +634,7 @@ mod tests { ..operand }, ] { - assert_eq!(changed.prefix_requirement(original), Err(())); + assert_eq!(changed.prefix_requirement(original), Err(Unsupported)); } if let Kind::NarrowHigh { left, @@ -655,15 +654,18 @@ mod tests { }, ..operand }; - assert_eq!(changed.prefix_requirement(original), Err(())); + assert_eq!(changed.prefix_requirement(original), Err(Unsupported)); } for invalid_original in [0, u32::MAX, original ^ 1] { - assert_eq!(operand.prefix_requirement(invalid_original), Err(())); + assert_eq!( + operand.prefix_requirement(invalid_original), + Err(Unsupported) + ); } for size in 0..first_size { let reserved = encoding | size << SIZE_SHIFT; - assert_eq!(decode(reserved), Some(Err(()))); - assert_eq!(operand.prefix_requirement(reserved), Err(())); + assert_eq!(decode(reserved), Some(Err(Unsupported))); + assert_eq!(operand.prefix_requirement(reserved), Err(Unsupported)); } } } diff --git a/crates/stela-compiler/src/aarch64/sve/reductions.rs b/crates/stela-compiler/src/aarch64/sve/reductions.rs index 684c19768b..8f82876134 100644 --- a/crates/stela-compiler/src/aarch64/sve/reductions.rs +++ b/crates/stela-compiler/src/aarch64/sve/reductions.rs @@ -1,5 +1,6 @@ //! SVE predicated integer reductions to a scalar or 128-bit result. use super::prefix; +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; const REDUCTION_MASK: u32 = 0xff3f_e000; @@ -60,13 +61,12 @@ pub struct Operand { impl Operand { /// The scalar and quadword reductions allow no MOVPRFX; the word is /// re-checked before returning that. - #[allow(clippy::result_unit_err)] pub fn prefix_requirement( self, original_word: u32, - ) -> Result, ()> { + ) -> Result, Unsupported> { if decode(original_word) != Some(Ok(self)) { - return Err(()); + return Err(Unsupported); } Ok(None) } @@ -83,7 +83,7 @@ impl Operand { } } -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let (kind, output) = match word & REDUCTION_MASK { AND_CLASS => (Kind::And, Output::Scalar), OR_CLASS => (Kind::Or, Output::Scalar), @@ -108,7 +108,7 @@ pub fn decode(word: u32) -> Option> { let element_size = ElementSize::from_bytes(element_bytes).expect("two-bit SVE reduction element size"); if kind == Kind::SignedAdd && element_size == ElementSize::Doubleword { - return Some(Err(())); + return Some(Err(Unsupported)); } Some(Ok(Operand { kind, @@ -181,7 +181,7 @@ mod tests { | source << SOURCE_SHIFT | destination; if kind == Kind::SignedAdd && size == SIZE_MASK { - assert_eq!(decode(word), Some(Err(()))); + assert_eq!(decode(word), Some(Err(Unsupported))); } else { let operand = decode(word).unwrap().unwrap(); assert_eq!(operand.kind, kind); @@ -288,9 +288,9 @@ mod tests { ..operand }, ] { - assert_eq!(changed.prefix_requirement(word), Err(())); + assert_eq!(changed.prefix_requirement(word), Err(Unsupported)); } - assert_eq!(operand.prefix_requirement(word ^ 1), Err(())); + assert_eq!(operand.prefix_requirement(word ^ 1), Err(Unsupported)); } } @@ -300,7 +300,7 @@ mod tests { for word in [AND_CLASS, QUADWORD_AND_CLASS] { let operand = decode(word).unwrap().unwrap(); for original_word in [0, u32::MAX, reserved] { - assert_eq!(operand.prefix_requirement(original_word), Err(())); + assert_eq!(operand.prefix_requirement(original_word), Err(Unsupported)); } } let forged_reserved = Operand { @@ -311,7 +311,10 @@ mod tests { governing: 0, source: 0, }; - assert_eq!(forged_reserved.prefix_requirement(reserved), Err(())); + assert_eq!( + forged_reserved.prefix_requirement(reserved), + Err(Unsupported) + ); } #[test] diff --git a/crates/stela-compiler/src/aarch64/sve/shifts.rs b/crates/stela-compiler/src/aarch64/sve/shifts.rs index a93ef64bca..d5798e1600 100644 --- a/crates/stela-compiler/src/aarch64/sve/shifts.rs +++ b/crates/stela-compiler/src/aarch64/sve/shifts.rs @@ -1,4 +1,5 @@ //! SVE shifts, shift-accumulates, shift-inserts and XAR. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ElementSize, Predication}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Kind { @@ -395,8 +396,7 @@ const ENCODINGS: &[Encoding] = &[ }, ]; -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let encoding = ENCODINGS .iter() .find(|entry| word & entry.mask == entry.value)?; @@ -429,7 +429,7 @@ pub fn decode(word: u32) -> Option> { }; let tsize = (size << 2) | ((word >> size_low_shift) & SIZE_MASK); if tsize == 0 { - return Some(Err(())); + return Some(Err(Unsupported)); } let element_bits = BYTE_BITS << (u32::BITS - 1 - tsize.leading_zeros()); let encoded = ((tsize << 3) | ((word >> immediate_shift) & IMMEDIATE_MASK)) as u8; @@ -453,7 +453,7 @@ pub fn decode(word: u32) -> Option> { Format::PredicatedDoublewords | Format::Doublewords ); if wide && size == SIZE_MASK { - return Some(Err(())); + return Some(Err(Unsupported)); } let register_shift = if matches!(encoding.format, Format::Doublewords) { WIDE_SOURCE_SHIFT @@ -477,7 +477,7 @@ pub fn decode(word: u32) -> Option> { let second_source = matches!(encoding.format, Format::XorRotate) .then_some(((word >> SOURCE_SHIFT) & REGISTER_MASK) as u8); let Some(element_size) = ElementSize::from_bytes(usize::from(element_bits / BYTE_BITS)) else { - return Some(Err(())); + return Some(Err(Unsupported)); }; let predication = predicate.map_or(Predication::Unpredicated, Predication::Merging); Some(Ok(Operand { @@ -520,7 +520,7 @@ mod tests { | REGISTER_MASK; let result = decode(word).expect("owned immediate encoding"); if tsize == 0 { - assert_eq!(result, Err(())); + assert_eq!(result, Err(Unsupported)); continue; } let operand = result.unwrap(); @@ -580,7 +580,7 @@ mod tests { }; let result = decode(word).expect("owned register encoding"); if wide && size == SIZE_MASK { - assert_eq!(result, Err(())); + assert_eq!(result, Err(Unsupported)); continue; } let operand = result.unwrap(); diff --git a/crates/stela-compiler/src/aarch64/sve/shifts_narrow.rs b/crates/stela-compiler/src/aarch64/sve/shifts_narrow.rs index fe64b1841b..7d9a70aa47 100644 --- a/crates/stela-compiler/src/aarch64/sve/shifts_narrow.rs +++ b/crates/stela-compiler/src/aarch64/sve/shifts_narrow.rs @@ -1,4 +1,5 @@ //! SVE2 unpredicated widening and narrowing shifts with bottom/top placement. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -257,15 +258,14 @@ const ENCODINGS: &[Encoding] = &[ }, ]; -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let encoding = ENCODINGS .iter() .find(|entry| word & entry.mask == entry.value)?; let tsize = (((word >> TSIZE_HIGH_SHIFT) & 1) << TSIZE_HIGH_OFFSET) | ((word >> TSIZE_LOW_SHIFT) & TSIZE_LOW_MASK); if tsize == 0 || (encoding.kind.is_extract() && !tsize.is_power_of_two()) { - return Some(Err(())); + return Some(Err(Unsupported)); } let size_log = u32::BITS - 1 - tsize.leading_zeros(); let element_bits = BYTE_BITS << size_log; @@ -304,7 +304,7 @@ mod tests { | (immediate << IMMEDIATE_SHIFT); let result = decode(word).expect("owned encoding"); if tsize == 0 || (encoding.kind.is_extract() && !tsize.is_power_of_two()) { - assert_eq!(result, Err(())); + assert_eq!(result, Err(Unsupported)); continue; } let operand = result.unwrap(); diff --git a/crates/stela-compiler/src/aarch64/sve/sign.rs b/crates/stela-compiler/src/aarch64/sve/sign.rs index ee0d35e5e5..aa7df40ce9 100644 --- a/crates/stela-compiler/src/aarch64/sve/sign.rs +++ b/crates/stela-compiler/src/aarch64/sve/sign.rs @@ -1,4 +1,5 @@ //! SVE predicated FABS and FNEG. +use crate::aarch64::Unsupported; use crate::aarch64::floating::Format; @@ -30,8 +31,7 @@ pub struct Operand { pub predicate: u8, } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let kind = match word & OPCODE_MASK { ABSOLUTE_OPCODE => Kind::Absolute, NEGATE_OPCODE => Kind::Negate, @@ -41,7 +41,7 @@ pub fn decode(word: u32) -> Option> { HALF_SIZE => Format::Half, SINGLE_SIZE => Format::Single, DOUBLE_SIZE => Format::Double, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; Some(Ok(Operand { kind, @@ -76,7 +76,7 @@ mod tests { (31, 31, 7) ); } - assert_eq!(decode(opcode), Some(Err(()))); + assert_eq!(decode(opcode), Some(Err(Unsupported))); } assert_eq!(decode(0x6580_8000), None); } diff --git a/crates/stela-compiler/src/aarch64/sve/tables.rs b/crates/stela-compiler/src/aarch64/sve/tables.rs index 7448fa35eb..3672f17f89 100644 --- a/crates/stela-compiler/src/aarch64/sve/tables.rs +++ b/crates/stela-compiler/src/aarch64/sve/tables.rs @@ -1,4 +1,5 @@ //! SVE LUTI2 and LUTI4. +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; const REGISTER_MASK: u32 = 31; @@ -50,8 +51,7 @@ impl Operand { } } -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { let high_part = ((word >> PART_SHIFT) & 3) as u8; let (element, index_bits, part, table_registers) = if word & LUTI2_BYTE_MASK == LUTI2_BYTE { (ElementSize::Byte, 2, high_part, 1) diff --git a/crates/stela-compiler/src/aarch64/unprivileged.rs b/crates/stela-compiler/src/aarch64/unprivileged.rs index 5ac1f0ad97..17641a9af8 100644 --- a/crates/stela-compiler/src/aarch64/unprivileged.rs +++ b/crates/stela-compiler/src/aarch64/unprivileged.rs @@ -1,6 +1,7 @@ //! Unprivileged loads and stores (LDTR*, STTR*). Native code supports EL0 on //! directly mapped RAM only. use super::{MemoryTransfer, Register, Width, register}; +use crate::aarch64::Unsupported; const CLASS_MASK: u32 = 0x3f20_0c00; const UNPRIVILEGED_CLASS: u32 = 0x3800_0800; @@ -31,8 +32,7 @@ pub struct Operand { /// None denotes another encoding class; Err denotes a reserved size/opcode. /// This class has neither writeback nor register-overlap restrictions. -#[allow(clippy::result_unit_err)] -pub fn decode(word: u32) -> Option> { +pub fn decode(word: u32) -> Option> { if word & CLASS_MASK != UNPRIVILEGED_CLASS { return None; } @@ -55,7 +55,7 @@ pub fn decode(word: u32) -> Option> { signed: true, width: Width::W32, }, - _ => return Some(Err(())), + _ => return Some(Err(Unsupported)), }; let immediate = ((word >> IMMEDIATE_SHIFT) & IMMEDIATE_MASK) as i32; Some(Ok(Operand { diff --git a/crates/stela-compiler/src/block.rs b/crates/stela-compiler/src/block.rs index c879cf47cf..7077cb3386 100644 --- a/crates/stela-compiler/src/block.rs +++ b/crates/stela-compiler/src/block.rs @@ -6,6 +6,7 @@ //! runtime helper when software PAuth is enabled. mod analysis; +mod features; pub mod loop_budget; pub mod memory; pub mod pauth_lr; @@ -22,6 +23,7 @@ pub use analysis::{ SuccessorKind, analyze, analyze_with_profile, source_bytes, source_bytes_with_profile, }; use analysis::{ParsedBlock, analyze_parsed, parse}; +pub use features::{BlockProfile, Features}; pub use memory::{ CHECKED_POINTER_PROCESS_MEMORY_PROFILE_ID, CheckedMemoryProfile, ORDINARY_GPR_PROCESS_MEMORY_PROFILE_ID, @@ -42,161 +44,6 @@ use serde::Serialize; const NOP_ENCODING: u32 = 0xd503_201f; -/// Separate from the leaf ABI: RAX/RDX return the next guest PC and exit kind. -pub const BLOCK_ABI: &str = "x86_64-sysv-guest-state-v2-block-exit-direct-ram"; -/// The block ABI with software PAuth helper exits. Keys and the PAuth version -/// are chosen at run time, so cached code contains neither. -pub const PAUTH_BLOCK_ABI: &str = - "x86_64-sysv-guest-state-v2-block-exit-direct-ram-apple-arm64e-software-pauth-v1"; -pub const CLOCK_BLOCK_ABI: &str = - "x86_64-sysv-guest-state-v2-block-exit-direct-ram-apple-arm64e-software-pauth-clock-v1"; - -pub const THREAD_BLOCK_ABI: &str = - "x86_64-sysv-guest-state-v2-block-exit-direct-ram-darwin-arm64-thread-v1"; -pub const PAUTH_THREAD_BLOCK_ABI: &str = - "x86_64-sysv-guest-state-v2-block-exit-direct-ram-apple-arm64e-software-pauth-thread-v1"; -pub const CLOCK_THREAD_BLOCK_ABI: &str = - "x86_64-sysv-guest-state-v2-block-exit-direct-ram-apple-arm64e-software-pauth-clock-thread-v1"; - -/// Restricted context-independent prefixes and checked System runtime exits. -/// This identifies a service boundary, not CPU feature availability. -pub const SYSTEM_BLOCK_ABI: &str = "x86_64-sysv-guest-state-v2-block-exit-system-v1"; -pub const SYSTEM_REGISTER_BLOCK_ABI: &str = - "x86_64-sysv-guest-state-v2-block-exit-system-registers-v1"; -/// Direct-RAM blocks for the system-mode engine: guest VAs are native -/// addresses through shadow paging, `GuestState` is exact at every instruction -/// boundary, and every System-class instruction exits with kind 11. Other -/// PEs run concurrently: atomics are locked and barriers fence. -pub const SYSTEM_MODE_BLOCK_ABI: &str = - "x86_64-sysv-guest-state-v2-block-exit-direct-ram-system-mode-v2"; - -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum BlockProfile { - #[default] - Ordinary, - /// Direct RAM, with non-faulting self-loops kept resident. - OrdinaryResidentV1, - CheckedMemory(CheckedMemoryProfile), - /// Checked memory plus the existing serialized PAC/clock/thread helpers. - /// The immutable ABI keeps every cache entry distinct from direct RAM. - CheckedMemoryPauthClockThread(CheckedMemoryProfile), - SystemV1, - SystemRegistersV1, - /// The system-mode engine's profile; see [`SYSTEM_MODE_BLOCK_ABI`]. - SystemModeV1, - /// All memory uses the checked all-writer service. Every full-system - /// terminal remains unexecuted until the BSP recovers the entire cohort. - SystemModeSharedV1(CheckedMemoryProfile), - AppleArm64eSoftwarePauthV1, - AppleArm64eSoftwarePauthClockV1, - DarwinArm64ThreadV1, - AppleArm64eSoftwarePauthThreadV1, - AppleArm64eSoftwarePauthClockThreadV1, -} - -impl BlockProfile { - pub const fn abi(self) -> &'static str { - match self { - Self::Ordinary => BLOCK_ABI, - Self::OrdinaryResidentV1 => loop_budget::RESIDENT_BLOCK_ABI, - Self::CheckedMemory(profile) => profile.abi(), - Self::CheckedMemoryPauthClockThread(profile) => profile.process_helpers_abi(), - Self::SystemV1 => SYSTEM_BLOCK_ABI, - Self::SystemRegistersV1 => SYSTEM_REGISTER_BLOCK_ABI, - Self::SystemModeV1 => SYSTEM_MODE_BLOCK_ABI, - Self::SystemModeSharedV1(profile) => profile.shared_system_abi(), - Self::AppleArm64eSoftwarePauthV1 => PAUTH_BLOCK_ABI, - Self::AppleArm64eSoftwarePauthClockV1 => CLOCK_BLOCK_ABI, - Self::DarwinArm64ThreadV1 => THREAD_BLOCK_ABI, - Self::AppleArm64eSoftwarePauthThreadV1 => PAUTH_THREAD_BLOCK_ABI, - Self::AppleArm64eSoftwarePauthClockThreadV1 => CLOCK_THREAD_BLOCK_ABI, - } - } - - pub const fn supports_resident_loops(self) -> bool { - matches!(self, Self::OrdinaryResidentV1) - } - - pub const fn checked_memory(self) -> Option { - match self { - Self::CheckedMemory(profile) - | Self::CheckedMemoryPauthClockThread(profile) - | Self::SystemModeSharedV1(profile) => Some(profile), - _ => None, - } - } - - pub const fn supports_checked_process_helpers(self) -> bool { - matches!(self, Self::CheckedMemoryPauthClockThread(_)) - } - - pub const fn supports_full_system(self) -> bool { - matches!(self, Self::SystemModeV1 | Self::SystemModeSharedV1(_)) - } - - pub const fn supports_system(self) -> bool { - matches!( - self, - Self::SystemV1 - | Self::SystemRegistersV1 - | Self::SystemModeV1 - | Self::SystemModeSharedV1(_) - ) - } - - pub const fn supports_system_registers(self) -> bool { - matches!( - self, - Self::SystemRegistersV1 | Self::SystemModeV1 | Self::SystemModeSharedV1(_) - ) - } - - pub const fn supports_pointer_authentication(self) -> bool { - matches!( - self, - Self::AppleArm64eSoftwarePauthV1 - | Self::AppleArm64eSoftwarePauthClockV1 - | Self::AppleArm64eSoftwarePauthThreadV1 - | Self::AppleArm64eSoftwarePauthClockThreadV1 - | Self::CheckedMemoryPauthClockThread(_) - | Self::SystemModeV1 - | Self::SystemModeSharedV1(_) - ) - } - - pub const fn supports_clock(self) -> bool { - matches!( - self, - Self::AppleArm64eSoftwarePauthClockV1 - | Self::AppleArm64eSoftwarePauthClockThreadV1 - | Self::CheckedMemoryPauthClockThread(_) - ) - } - - /// AMX state is per guest thread in the direct-RAM thread profiles and - /// per PE in system mode; those profiles carry AMX exits. - pub const fn supports_amx(self) -> bool { - matches!( - self, - Self::SystemModeV1 - | Self::SystemModeSharedV1(_) - | Self::DarwinArm64ThreadV1 - | Self::AppleArm64eSoftwarePauthThreadV1 - | Self::AppleArm64eSoftwarePauthClockThreadV1 - ) - } - - pub const fn supports_thread_registers(self) -> bool { - matches!( - self, - Self::DarwinArm64ThreadV1 - | Self::AppleArm64eSoftwarePauthThreadV1 - | Self::AppleArm64eSoftwarePauthClockThreadV1 - | Self::CheckedMemoryPauthClockThread(_) - ) - } -} /// Maximum input window; a terminator can consume a shorter prefix. pub const MAX_BLOCK_INSTRUCTIONS: usize = 256; @@ -350,12 +197,24 @@ pub struct CompiledBlock { /// system-mode engine may chain (`x86_64::chain`). pub direct_exits: alloc::vec::Vec, /// Where the native code keeps guest GPRs out of their frame slots - /// across a faultable access. Only `SystemModeV1` emits entries, and + /// across a faultable access. Only the direct system-mode profile emits entries, and /// an engine that recovers from a native fault must apply them /// ([`FaultRecovery::apply`]) before it reads the frame. pub fault_recovery: alloc::vec::Vec, } +impl CompiledBlock { + /// Code with no chainable exits and no fault recovery. + fn unchained(native: NativeBlock, source_bytes: usize) -> Self { + Self { + native, + source_bytes, + direct_exits: alloc::vec::Vec::new(), + fault_recovery: alloc::vec::Vec::new(), + } + } +} + /// While native code at offsets `start..end` of its block runs, each /// `(guest, host)` pair's guest GPR (31 is SP) holds the value of host /// register `host` (its x86 number) rather than its frame slot. A fault @@ -439,79 +298,97 @@ fn decode_terminator(pc: GuestAddress, word: u32) -> Result, })) } -/// Compile through the first transfer, trap or unconditional runtime helper, -/// or exit at the input boundary. -/// Unknown semantics before that boundary are rejected. Bytes following a -/// terminator are unconsumed and do not participate in the returned source map. -pub fn compile(source: &[u8], base: GuestAddress) -> Result { - compile_with_profile(source, base, BlockProfile::Ordinary) -} - -pub fn compile_with_profile( - source: &[u8], - base: GuestAddress, - profile: BlockProfile, -) -> Result { - compile_for_target(source, base, profile, crate::TargetCpu::Baseline) -} -pub fn compile_for_target( - source: &[u8], - base: GuestAddress, - profile: BlockProfile, - target: crate::TargetCpu, -) -> Result { - CompilationPlan::new(source, base, profile, target)?.compile() -} - /// [`analyze_with_profile`] of `source` and [`CompilationPlan::new`] of the /// block it finds (`source[..analysis.source_bytes]`) from one parse. pub fn analyze_and_plan( source: &[u8], base: GuestAddress, - profile: BlockProfile, - target: crate::TargetCpu, + options: &crate::Options, ) -> Result<(BlockAnalysis, Result), BlockAnalysisError> { - let parsed = parse(source, base, profile)?; + let parsed = parse(source, base, options.profile())?; let analysis = analyze_parsed(&parsed); Ok(( analysis, - CompilationPlan::from_parsed(parsed, profile, target), + options + .validate() + .and_then(|()| CompilationPlan::block(parsed, options)), )) } -/// One immutable parsed consumed vector shared by cache requirements and emission. -/// A cache hit may avoid emission; it still derives exact requirements from source. +/// One validated decode of the consumed input, shared by cache requirements +/// and emission. A cache hit may skip emission; it still derives the +/// requirements from source. pub struct CompilationPlan { - parsed: ParsedBlock, - checked: Option, - target: crate::TargetCpu, - profile: BlockProfile, - resident: Option, - checks: crate::x86_64::MemoryChecks, - native: crate::x86_64::NativeSystem, + options: crate::Options, + stage: Stage, } + +enum Stage { + Block { + parsed: ParsedBlock, + checked: Option, + resident: Option, + }, + Leaf { + instructions: alloc::vec::Vec, + source_bytes: usize, + }, + ContextLeaf(crate::scalable_context::Leaf), + ContextBlock(crate::scalable_context::block::Prefix), +} + impl CompilationPlan { pub fn new( source: &[u8], base: GuestAddress, - profile: BlockProfile, - target: crate::TargetCpu, + options: &crate::Options, ) -> Result { - let parsed = parse(source, base, profile).map_err(|error| CompileError(error.detail))?; - Self::from_parsed(parsed, profile, target) + options.validate()?; + let profile = options.profile(); + let target = options.target(); + let stage = match ( + profile.has(Features::CONTEXT), + profile.has(Features::LEAF), + options.scalable(), + ) { + (true, true, Some(scalable)) => Stage::ContextLeaf( + crate::scalable_context::Leaf::decode(source, base, scalable, target)?, + ), + (true, false, Some(scalable)) => { + Stage::ContextBlock(crate::scalable_context::block::Prefix::decode( + source, + base, + scalable, + options.numerical_features(), + target, + )?) + } + (false, true, _) => Stage::Leaf { + instructions: decode_leaf(source, base)?, + source_bytes: source.len(), + }, + _ => { + let parsed = + parse(source, base, profile).map_err(|error| CompileError(error.detail))?; + return Self::block(parsed, options); + } + }; + Ok(Self { + options: *options, + stage, + }) } - fn from_parsed( - parsed: ParsedBlock, - profile: BlockProfile, - target: crate::TargetCpu, - ) -> Result { - let validated = crate::x86_64::MemoryChecks::DEFAULT; + fn block(parsed: ParsedBlock, options: &crate::Options) -> Result { + let profile = options.profile(); + let target = options.target(); + let checks = options.memory_checks(); + let shared_system = + profile.has(Features::FULL_SYSTEM) && profile.checked_memory().is_some(); for instruction in &parsed.instructions { // The shared checked service has a separately required writable - // CX16 read footprint. This does not qualify a direct MOVDQA recipe - // or alter the legacy checked profile's read-only host contract. - if matches!(profile, BlockProfile::SystemModeSharedV1(_)) + // CX16 read footprint, so its ordered accesses need no AVX. + if shared_system && matches!(instruction.operation, Operation::Ordered(_)) && target.supports(crate::TargetCpu::Cx16) { @@ -522,7 +399,12 @@ impl CompilationPlan { Operation::Exclusive(_) | Operation::CheckedPointer(_) ) || profile.checked_memory().is_none() { - crate::x86_64::validate_target_with(instruction, target, validated) + crate::x86_64::validate_target(instruction, target) + .map_err(|error| CompileError(format!("{error:?}")))?; + } + // An unchecked SP needs its own host capability. + if !checks.stack_alignment { + crate::x86_64::validate_target_with(instruction, target, checks) .map_err(|error| CompileError(format!("{error:?}")))?; } } @@ -537,7 +419,7 @@ impl CompilationPlan { ) }) .transpose()?; - let resident = if profile.supports_resident_loops() { + let resident = if profile.has(Features::RESIDENT_LOOPS) { crate::x86_64::block::ResidentLoopPlan::new( &parsed.instructions, parsed.terminal.as_ref(), @@ -547,129 +429,105 @@ impl CompilationPlan { None }; Ok(Self { - parsed, - checked, - target, - profile, - resident, - checks: crate::x86_64::MemoryChecks::DEFAULT, - native: crate::x86_64::NativeSystem::NONE, + options: *options, + stage: Stage::Block { + parsed, + checked, + resident, + }, }) } - /// Emit the memory checks of the regime's SCTLR_ELx: the system-mode - /// engine compiles separate blocks for SA (or SA0 at EL0) clear, where an - /// access through a misaligned SP proceeds; for A set, where any access - /// not aligned to its elements faults; and for nAA set, where an ordered - /// access may cross its 16-byte granule. No other profile admits checks - /// but [`crate::x86_64::MemoryChecks::DEFAULT`], and a host without the - /// capability an unchecked SP then needs refuses. - pub fn with_memory_checks( - mut self, - checks: crate::x86_64::MemoryChecks, - ) -> Result { - if checks != crate::x86_64::MemoryChecks::DEFAULT - && self.profile != BlockProfile::SystemModeV1 - { - return Err(CompileError(format!( - "{:?} makes only the default memory checks", - self.profile - ))); - } - if !checks.stack_alignment { - for instruction in &self.parsed.instructions { - crate::x86_64::validate_target_with(instruction, self.target, checks) - .map_err(|error| CompileError(format!("{error:?}")))?; - } - } - self.checks = checks; - Ok(self) - } - /// Complete a terminal DC ZVA natively, zeroing the aligned `bytes` - /// block holding Xt (DCZID_EL0.BS: a power of two from 4 to 2048) and - /// falling through: the system-mode engine compiles separate blocks for - /// the contexts where DC ZVA neither traps nor is UNDEFINED. `None` - /// keeps its System exit. - pub fn with_zero_block(mut self, bytes: Option) -> Result { - use crate::x86_64::zero_block::{MAX_BYTES, MIN_BYTES}; - if let Some(bytes) = bytes { - if self.profile != BlockProfile::SystemModeV1 { - return Err(CompileError(format!( - "{:?} keeps DC ZVA's System exit", - self.profile - ))); - } - if !bytes.is_power_of_two() || !(MIN_BYTES..=MAX_BYTES).contains(&bytes) { - return Err(CompileError(format!( - "a {bytes}-byte DC ZVA block is not a DCZID_EL0.BS size" - ))); - } - } - self.native.zero_block = bytes; - Ok(self) - } - /// Complete a terminal DC CVAC, DC CVAU or DC CIVAC among `operations` - /// natively, checking that Xt translates for a read and falling through - /// (`x86_64::cache_clean`): the system-mode engine compiles separate - /// blocks for the contexts where those operations neither trap nor are - /// UNDEFINED. Other operations keep their System exit. - pub fn with_cache_clean( - mut self, - operations: crate::x86_64::cache_clean::Operations, - ) -> Result { - if !operations.is_empty() && self.profile != BlockProfile::SystemModeV1 { - return Err(CompileError(format!( - "{:?} keeps the DC clean operations' System exit", - self.profile - ))); - } - self.native.cache_clean = operations; - Ok(self) - } - /// Allow the ordinary runtime to retain eligible internal loop edges. Other - /// service profiles keep their existing admission and call contracts. + /// Let an ordinary block keep eligible internal loop edges resident, with + /// [`Features::RESIDENT_LOOPS`] when it has any. Other profiles keep their + /// admission and call contracts. pub fn with_resident_loops(mut self) -> Self { - if self.profile == BlockProfile::Ordinary { - self.resident = crate::x86_64::block::ResidentLoopPlan::new( - &self.parsed.instructions, - self.parsed.terminal.as_ref(), - self.parsed.next_pc, + if let Stage::Block { + parsed, resident, .. + } = &mut self.stage + && self.options.profile() == BlockProfile::ORDINARY + { + *resident = crate::x86_64::block::ResidentLoopPlan::new( + &parsed.instructions, + parsed.terminal.as_ref(), + parsed.next_pc, ); - if self.resident.is_some() { - self.profile = BlockProfile::OrdinaryResidentV1; + if resident.is_some() { + self.options = crate::Options::new( + BlockProfile::new(Features::RESIDENT_LOOPS), + self.options.target(), + ); } } self } pub fn profile(&self) -> BlockProfile { - self.profile + self.options.profile() + } + + #[cfg(test)] + fn parsed(&self) -> &ParsedBlock { + match &self.stage { + Stage::Block { parsed, .. } => parsed, + _ => panic!("not a block plan"), + } } pub fn source_bytes(&self) -> usize { - self.parsed.source_bytes + match &self.stage { + Stage::Block { parsed, .. } => parsed.source_bytes, + Stage::Leaf { source_bytes, .. } => *source_bytes, + Stage::ContextLeaf(leaf) => leaf.source_bytes(), + Stage::ContextBlock(prefix) => prefix.source_bytes(), + } } + + /// The memory service a checked block or a context leaf needs; `None` for + /// direct RAM. pub fn memory_requirements(&self) -> Option { - self.checked.as_ref().map(|plan| { - let mut requirements = plan.requirements(); - use crate::context::memory::{host_caps, profile_requirements}; - if matches!(self.profile, BlockProfile::SystemModeSharedV1(_)) - && !self.target.supports(crate::TargetCpu::AtomicLoad16) - && self.target.supports(crate::TargetCpu::Cx16) - && requirements.required_host_caps & host_caps::ATOMIC_LOAD16 != 0 - { - requirements.required_host_caps = - requirements.required_host_caps & !host_caps::ATOMIC_LOAD16 | host_caps::CX16; - requirements.required_profile |= profile_requirements::SYSTEM_ATOMIC_READ_WRITEBACK; + match &self.stage { + Stage::Block { + checked: Some(plan), + .. + } => { + let mut requirements = plan.requirements(); + use crate::context::memory::{host_caps, profile_requirements}; + let profile = self.options.profile(); + let target = self.options.target(); + if profile.has(Features::FULL_SYSTEM) + && !target.supports(crate::TargetCpu::AtomicLoad16) + && target.supports(crate::TargetCpu::Cx16) + && requirements.required_host_caps & host_caps::ATOMIC_LOAD16 != 0 + { + requirements.required_host_caps = requirements.required_host_caps + & !host_caps::ATOMIC_LOAD16 + | host_caps::CX16; + requirements.required_profile |= + profile_requirements::SYSTEM_ATOMIC_READ_WRITEBACK; + } + Some(requirements) } - requirements - }) + Stage::ContextLeaf(leaf) => Some(leaf.memory_requirements()), + _ => None, + } } + + /// A context leaf's per-instruction scalable execution requirements. + pub fn execution_requirements( + &self, + ) -> Option { + match &self.stage { + Stage::ContextLeaf(leaf) => Some(leaf.execution_requirements()), + _ => None, + } + } + pub fn compile(self) -> Result { self.compile_impl(None) } - /// Emit identical code while retaining optional selected-recipe observations. - /// Unsupported profiling coverage stays absent, rather than implying zero work. + /// Emit identical code while recording the selected recipes. Coverage a + /// stage does not profile stays absent, rather than implying zero work. pub fn compile_profiled( self, ) -> Result<(CompiledBlock, profile::CompileProfile), CompileError> { @@ -677,82 +535,132 @@ impl CompilationPlan { let block = self.compile_impl(Some(&mut profile))?; Ok((block, profile)) } + fn compile_impl( self, - profile: Option<&mut profile::CompileProfile>, + recipes: Option<&mut profile::CompileProfile>, ) -> Result { - let native = if let Some(checked) = self.checked { - checked.emit( - self.parsed.terminal.as_ref(), - self.parsed.next_pc, - self.target, - profile, - )? - } else if let Some(resident) = self.resident { + let options = self.options; + let profile = options.profile(); + let target = options.target(); + let (parsed, checked, resident) = match self.stage { + Stage::Block { + parsed, + checked, + resident, + } => (parsed, checked, resident), + Stage::Leaf { + instructions, + source_bytes, + } => { + let native = crate::x86_64::Emitter + .emit_for_target(&instructions, target) + .map_err(|e| CompileError(format!("x86 emission failed: {e:?}")))?; + return Ok(CompiledBlock::unchained(native, source_bytes)); + } + Stage::ContextLeaf(leaf) => { + let source_bytes = leaf.source_bytes(); + return Ok(CompiledBlock::unchained(leaf.emit()?, source_bytes)); + } + Stage::ContextBlock(prefix) => return prefix.emit(), + }; + let native = if let Some(checked) = checked { + checked.emit(parsed.terminal.as_ref(), parsed.next_pc, target, recipes)? + } else if let Some(resident) = resident { resident - .emit(&self.parsed.instructions) + .emit(&parsed.instructions) .map_err(|error| CompileError(format!("resident loop emission: {error:?}")))? - } else if self.profile.supports_resident_loops() { + } else if profile.has(Features::RESIDENT_LOOPS) { crate::x86_64::block::emit_resident_fallback_for_target( - &self.parsed.instructions, - self.parsed.terminal.as_ref(), - self.parsed.next_pc, - self.target, + &parsed.instructions, + parsed.terminal.as_ref(), + parsed.next_pc, + target, ) - } else if self.profile == BlockProfile::Ordinary { + } else if profile == BlockProfile::ORDINARY { crate::x86_64::block::emit_ordinary_for_target( - &self.parsed.instructions, - self.parsed.terminal.as_ref(), - self.parsed.next_pc, - self.target, + &parsed.instructions, + parsed.terminal.as_ref(), + parsed.next_pc, + target, ) } else { // Only system mode runs one agent at a time and checks the // guest's ranges; every other profile keeps the locked recipes - // and the default checks (`with_memory_checks`). - let (native, fault_recovery) = if self.profile == BlockProfile::SystemModeV1 { + // and the default checks. + let (native, fault_recovery) = if profile.has(Features::FULL_SYSTEM) { crate::x86_64::block::emit_system_mode( - &self.parsed.instructions, - self.parsed.terminal.as_ref(), - self.parsed.next_pc, - self.target, - self.checks, - self.native, + &parsed.instructions, + parsed.terminal.as_ref(), + parsed.next_pc, + target, + options.memory_checks(), + options.native_system(), ) } else { ( crate::x86_64::block::emit_ordinary_for_target( - &self.parsed.instructions, - self.parsed.terminal.as_ref(), - self.parsed.next_pc, - self.target, + &parsed.instructions, + parsed.terminal.as_ref(), + parsed.next_pc, + target, ), alloc::vec::Vec::new(), ) }; let direct_exits = crate::x86_64::block::successor_exits( &native.x86_64_code, - self.parsed.terminal.as_ref(), - self.parsed.next_pc, + parsed.terminal.as_ref(), + parsed.next_pc, ); return Ok(CompiledBlock { native, - source_bytes: self.parsed.source_bytes, + source_bytes: parsed.source_bytes, direct_exits, fault_recovery, }); }; - Ok(CompiledBlock { - native, - source_bytes: self.parsed.source_bytes, - direct_exits: alloc::vec::Vec::new(), - fault_recovery: alloc::vec::Vec::new(), - }) + Ok(CompiledBlock::unchained(native, parsed.source_bytes)) } } +/// Lift a leaf, which must end in RET X30, instruction by instruction. +fn decode_leaf( + source: &[u8], + base: GuestAddress, +) -> Result, CompileError> { + use crate::Lifter; + if source.is_empty() || !source.len().is_multiple_of(4) || !base.0.is_multiple_of(4) { + return Err(CompileError( + "input and guest base must be nonempty/aligned to 4 bytes".into(), + )); + } + let mut instructions = alloc::vec::Vec::with_capacity(source.len() / 4); + for (index, bytes) in source.as_chunks::<4>().0.iter().enumerate() { + let pc = GuestAddress( + base.0 + .checked_add((index as u64) * 4) + .ok_or_else(|| CompileError("guest address overflow".into()))?, + ); + let instruction = crate::aarch64::Decoder + .lift(pc, u32::from_le_bytes(*bytes)) + .map_err(|e| CompileError(format!("unsupported ARM64 semantics: {e:?}")))?; + instructions.push(instruction); + } + if !matches!( + instructions + .last() + .map(|instruction| &instruction.operation), + Some(Operation::Return) + ) { + return Err(CompileError("leaf region must end in RET X30".into())); + } + Ok(instructions) +} + #[cfg(test)] mod tests { + use crate::x86_64::asm::Code; #[test] fn shared_system_uses_checked_recipes_and_refuses_serial_native_specialization() { use crate::TargetCpu; @@ -771,24 +679,32 @@ mod tests { CheckedMemoryProfile::SpAlignmentEnabled, CheckedMemoryProfile::SpAlignmentDisabled, ] { - let shared = BlockProfile::SystemModeSharedV1(specialization); - let checked = BlockProfile::CheckedMemory(specialization); + let shared = + BlockProfile::new(Features::SYSTEM_MODE).with_checked_memory(specialization); + let checked = BlockProfile::ORDINARY.with_checked_memory(specialization); assert_ne!(shared.abi(), checked.abi()); - assert_ne!(shared.abi(), BlockProfile::SystemModeV1.abi()); + assert_ne!(shared.abi(), BlockProfile::new(Features::SYSTEM_MODE).abi()); let target = TargetCpu::X86_64_V2.with_atomic_load16(); - let plan = - || CompilationPlan::new(&source, GuestAddress(0x4000), shared, target).unwrap(); - assert!(!plan().checks.single_agent); + let options = crate::Options::new(shared, target); + let plan = || CompilationPlan::new(&source, GuestAddress(0x4000), &options).unwrap(); + assert!(!plan().options.memory_checks().single_agent); assert!( - plan() - .with_memory_checks(crate::x86_64::MemoryChecks { + CompilationPlan::new( + &source, + GuestAddress(0x4000), + &options.with_memory_checks(crate::x86_64::MemoryChecks { single_agent: true, ..crate::x86_64::MemoryChecks::DEFAULT }) - .is_err() + ) + .is_err() ); - let expected = - CompilationPlan::new(&source, GuestAddress(0x4000), checked, target).unwrap(); + let expected = CompilationPlan::new( + &source, + GuestAddress(0x4000), + &crate::Options::new(checked, target), + ) + .unwrap(); assert_eq!(plan().memory_requirements(), expected.memory_requirements()); let native = plan().compile().unwrap().native; let expected = expected.compile().unwrap().native; @@ -809,10 +725,15 @@ mod tests { .collect(); let profile = CheckedMemoryProfile::SpAlignmentDisabled; let plan = |outer, target| { - CompilationPlan::new(&source, GuestAddress(0x4000), outer, target).unwrap() + CompilationPlan::new( + &source, + GuestAddress(0x4000), + &crate::Options::new(outer, target), + ) + .unwrap() }; let shared = plan( - BlockProfile::SystemModeSharedV1(profile), + BlockProfile::new(Features::SYSTEM_MODE).with_checked_memory(profile), TargetCpu::X86_64_V2, ); let required = shared.memory_requirements().unwrap(); @@ -825,13 +746,15 @@ mod tests { CompilationPlan::new( &source, GuestAddress(0x4000), - BlockProfile::CheckedMemory(profile), - TargetCpu::X86_64_V2, + &crate::Options::new( + BlockProfile::ORDINARY.with_checked_memory(profile), + TargetCpu::X86_64_V2 + ) ) .is_err() ); let legacy = plan( - BlockProfile::CheckedMemory(profile), + BlockProfile::ORDINARY.with_checked_memory(profile), TargetCpu::X86_64_V2.with_atomic_load16(), ); let required = legacy.memory_requirements().unwrap(); @@ -841,7 +764,7 @@ mod tests { 0 ); let optional = plan( - BlockProfile::SystemModeSharedV1(profile), + BlockProfile::new(Features::SYSTEM_MODE).with_checked_memory(profile), TargetCpu::X86_64_V2.with_atomic_load16(), ); assert_eq!( @@ -854,21 +777,30 @@ mod tests { fn shared_system_control_and_pauth_terminals_keep_the_exact_unexecuted_source_pc() { use crate::TargetCpu; let base = GuestAddress(0x4000); - let shared = BlockProfile::SystemModeSharedV1(CheckedMemoryProfile::SpAlignmentDisabled); - assert!(shared.supports_system_registers() && shared.supports_full_system()); - assert!(!shared.supports_checked_process_helpers()); + let shared = BlockProfile::new(Features::SYSTEM_MODE) + .with_checked_memory(CheckedMemoryProfile::SpAlignmentDisabled); + assert!(shared.has(Features::SYSTEM_REGISTERS) && shared.has(Features::FULL_SYSTEM)); + assert!(!shared.has(Features::PROCESS_HELPERS)); for terminal in [0xd53b_e040u32, 0xd503_3fdf, 0xd503_237f, 0xd400_0001] { let source: Vec<_> = [0x9100_0400u32, terminal, 0xd65f_03c0] .into_iter() .flat_map(u32::to_le_bytes) .collect(); - let plan = CompilationPlan::new(&source, base, shared, TargetCpu::Baseline).unwrap(); + let plan = CompilationPlan::new( + &source, + base, + &crate::Options::new(shared, TargetCpu::Baseline), + ) + .unwrap(); assert_eq!(plan.source_bytes(), 8); assert_eq!( - plan.parsed.terminal.as_ref().unwrap().0, + plan.parsed().terminal.as_ref().unwrap().0, GuestAddress(base.0 + 4) ); - assert_eq!(plan.native, crate::x86_64::NativeSystem::NONE); + assert_eq!( + plan.options.native_system(), + crate::x86_64::NativeSystem::NONE + ); let body = plan.compile().unwrap(); assert_eq!( body.native.source_map.last().unwrap().0, @@ -886,7 +818,8 @@ mod tests { CheckedMemoryProfile::SpAlignmentEnabled, CheckedMemoryProfile::SpAlignmentDisabled, ] { - let shared = BlockProfile::SystemModeSharedV1(specialization); + let shared = + BlockProfile::new(Features::SYSTEM_MODE).with_checked_memory(specialization); for word in [ 0x9e63_0100, // UCVTF D0,X8, reached by the original kernel 0x1e22_2820, // FADD S0,S1,S2 @@ -904,11 +837,14 @@ mod tests { } words.extend([word, u32::MAX]); let source: Vec<_> = words.into_iter().flat_map(u32::to_le_bytes).collect(); - let plan = - CompilationPlan::new(&source, base, shared, crate::TargetCpu::Baseline) - .unwrap(); + let plan = CompilationPlan::new( + &source, + base, + &crate::Options::new(shared, crate::TargetCpu::Baseline), + ) + .unwrap(); let terminal_pc = GuestAddress(base.0 + u64::from(prefix) * 4); - assert!(matches!(plan.parsed.terminal, + assert!(matches!(plan.parsed().terminal, Some((pc, Terminator::FloatingPoint)) if pc == terminal_pc)); assert_eq!(plan.source_bytes(), (usize::from(prefix) + 1) * 4); let analysis = analyze_with_profile(&source, base, shared).unwrap(); @@ -941,9 +877,13 @@ mod tests { .iter() .flat_map(|word| word.to_le_bytes()) .collect(); - for profile in [BlockProfile::Ordinary, BlockProfile::SystemModeV1] { + for profile in [ + BlockProfile::ORDINARY, + BlockProfile::new(Features::SYSTEM_MODE), + ] { let target = crate::TargetCpu::Baseline; - let (analysis, plan) = analyze_and_plan(&source, BASE, profile, target).unwrap(); + let (analysis, plan) = + analyze_and_plan(&source, BASE, &crate::Options::new(profile, target)).unwrap(); assert_eq!( analysis, analyze_with_profile(&source, BASE, profile).unwrap() @@ -955,7 +895,7 @@ mod tests { alloc::format!("{:?}", plan.unwrap().compile().unwrap()), alloc::format!( "{:?}", - compile_for_target(consumed, BASE, profile, target).unwrap() + crate::testing::block_for(consumed, BASE, profile, target).unwrap() ) ); } @@ -963,8 +903,7 @@ mod tests { analyze_and_plan( &[], BASE, - BlockProfile::Ordinary, - crate::TargetCpu::Baseline + &crate::Options::new(BlockProfile::ORDINARY, crate::TargetCpu::Baseline) ) .is_err() ); @@ -985,41 +924,28 @@ mod tests { .into_iter() .flat_map(u32::to_le_bytes) .collect(); - let compile = |checked| { - CompilationPlan::new( - &source, - GuestAddress(0x1000), - BlockProfile::SystemModeV1, + let unaligned = crate::x86_64::MemoryChecks { + stack_alignment: false, + ..crate::x86_64::MemoryChecks::DEFAULT + }; + let compile = |checks| { + let options = crate::Options::new( + BlockProfile::new(Features::SYSTEM_MODE), crate::TargetCpu::detect(), ) - .and_then(|plan| { - plan.with_memory_checks(crate::x86_64::MemoryChecks { - stack_alignment: checked, - ..crate::x86_64::MemoryChecks::DEFAULT - }) - }) - .and_then(CompilationPlan::compile) - .unwrap() - .native - .x86_64_code + .with_memory_checks(checks); + crate::compile(&source, GuestAddress(0x1000), &options) + .unwrap() + .native + .x86_64_code }; let has_check = |code: &[u8]| code.windows(SP_CHECK.len()).any(|bytes| bytes == SP_CHECK); - assert!(has_check(&compile(true))); - assert!(!has_check(&compile(false))); + assert!(has_check(&compile(crate::x86_64::MemoryChecks::DEFAULT))); + assert!(!has_check(&compile(unaligned))); // Only the system-mode profile admits it. - assert!( - CompilationPlan::new( - &source[..4], - GuestAddress(0x1000), - BlockProfile::Ordinary, - crate::TargetCpu::Baseline - ) - .and_then(|plan| plan.with_memory_checks(crate::x86_64::MemoryChecks { - stack_alignment: false, - ..crate::x86_64::MemoryChecks::DEFAULT - })) - .is_err() - ); + let ordinary = crate::Options::new(BlockProfile::ORDINARY, crate::TargetCpu::Baseline) + .with_memory_checks(unaligned); + assert!(crate::compile(&source[..4], GuestAddress(0x1000), &ordinary).is_err()); } /// Every access of a system-mode block, in a clean-load region or not, @@ -1033,19 +959,13 @@ mod tests { .filter(|bytes| *bytes == check) .count() }; - let compile = |words: &[u32], profile, plan: fn(CompilationPlan) -> CompilationPlan| { + let compile = |words: &[u32], profile, options: fn(crate::Options) -> crate::Options| { let source: Vec = words.iter().copied().flat_map(u32::to_le_bytes).collect(); - CompilationPlan::new( - &source, - GuestAddress(0x1000), - profile, - crate::TargetCpu::detect(), - ) - .map(plan) - .and_then(CompilationPlan::compile) - .unwrap() - .native - .x86_64_code + let options = options(crate::Options::new(profile, crate::TargetCpu::detect())); + crate::compile(&source, GuestAddress(0x1000), &options) + .unwrap() + .native + .x86_64_code }; // ldr w0, [x1]; add w0, w0, #1; ldr x0, [x1, #8]; ldp w2, w3, [x1]; // ldr h0, [x1, x2]; ld1 {v0.4s}, [x1]; ldr x4, ; ldadd x4, @@ -1070,7 +990,11 @@ mod tests { ]; // Alone, each access checks, but the prefetch, which never faults. for (index, word) in words.into_iter().enumerate() { - let alone = compile(&[word], BlockProfile::SystemModeV1, |plan| plan); + let alone = compile( + &[word], + BlockProfile::new(Features::SYSTEM_MODE), + |options| options, + ); assert_eq!( count(&alone), usize::from(![1, 14].contains(&index)), @@ -1081,22 +1005,33 @@ mod tests { // needs none (`x86_64::guest_range`): the SIMD register offset, // which forgets every base, makes the LD1 check again, and the // literal always checks. - let system = compile(&words, BlockProfile::SystemModeV1, |plan| plan); + let system = compile( + &words, + BlockProfile::new(Features::SYSTEM_MODE), + |options| options, + ); assert_eq!(count(&system), 4); // Under FEAT_CSV3 each access checks, so each masks its own address. - let masked = compile(&words, BlockProfile::SystemModeV1, |plan| { - plan.with_memory_checks(crate::x86_64::MemoryChecks::system(true, false, true, true)) - .unwrap() - }); + let masked = compile( + &words, + BlockProfile::new(Features::SYSTEM_MODE), + |options| { + options.with_memory_checks(crate::x86_64::MemoryChecks::system( + true, false, true, true, + )) + }, + ); assert_eq!(count(&masked), words.len() - 2); // A four-level host's blocks, clean-load regions included, check // against its placement's ranges. const FOUR_LEVEL: crate::x86_64::MemoryChecks = crate::x86_64::MemoryChecks::system(true, false, true, false) .with_range(crate::x86_64::RangeCheck::four_level(2)); - let four_level = compile(&words, BlockProfile::SystemModeV1, |plan| { - plan.with_memory_checks(FOUR_LEVEL).unwrap() - }); + let four_level = compile( + &words, + BlockProfile::new(Features::SYSTEM_MODE), + |options| options.with_memory_checks(FOUR_LEVEL), + ); let four_level_check = crate::x86_64::RangeCheck::four_level(2).code(); assert_eq!(count(&four_level), 0); assert_eq!( @@ -1107,17 +1042,30 @@ mod tests { count(&system) ); assert_eq!( - count(&compile(&words, BlockProfile::Ordinary, |plan| plan)), + count(&compile(&words, BlockProfile::ORDINARY, |options| options)), 0 ); // DC ZVA and DC CVAC completed natively check Xt. - let zero = compile(&[0xd50b_7423], BlockProfile::SystemModeV1, |plan| { - plan.with_zero_block(Some(64)).unwrap() - }); - let clean = compile(&[0xd50b_7a20], BlockProfile::SystemModeV1, |plan| { - plan.with_cache_clean(crate::x86_64::cache_clean::Operations::ALL) - .unwrap() - }); + let zero = compile( + &[0xd50b_7423], + BlockProfile::new(Features::SYSTEM_MODE), + |options| { + options.with_native_system(crate::x86_64::NativeSystem { + zero_block: Some(64), + ..crate::x86_64::NativeSystem::NONE + }) + }, + ); + let clean = compile( + &[0xd50b_7a20], + BlockProfile::new(Features::SYSTEM_MODE), + |options| { + options.with_native_system(crate::x86_64::NativeSystem { + cache_clean: crate::x86_64::cache_clean::Operations::ALL, + ..crate::x86_64::NativeSystem::NONE + }) + }, + ); assert_eq!((count(&zero), count(&clean)), (1, 1)); // The translated variant checks each access, and each failed check // names the access to the helper: its bytes and whether it writes @@ -1146,9 +1094,11 @@ mod tests { } found }; - let all = compile(&words, BlockProfile::SystemModeV1, |plan| { - plan.with_memory_checks(TRANSLATED).unwrap() - }); + let all = compile( + &words, + BlockProfile::new(Features::SYSTEM_MODE), + |options| options.with_memory_checks(TRANSLATED), + ); assert_eq!( accesses(&all), [ @@ -1168,11 +1118,18 @@ mod tests { ] ); assert_eq!(count(&all), 0); - let zero = compile(&[0xd50b_7423], BlockProfile::SystemModeV1, |plan| { - plan.with_memory_checks(TRANSLATED) - .and_then(|plan| plan.with_zero_block(Some(64))) - .unwrap() - }); + let zero = compile( + &[0xd50b_7423], + BlockProfile::new(Features::SYSTEM_MODE), + |options| { + options.with_memory_checks(TRANSLATED).with_native_system( + crate::x86_64::NativeSystem { + zero_block: Some(64), + ..crate::x86_64::NativeSystem::NONE + }, + ) + }, + ); assert_eq!(accesses(&zero), [(64, 1)]); } @@ -1193,17 +1150,15 @@ mod tests { ]; let source: Vec = words.into_iter().flat_map(u32::to_le_bytes).collect(); let compile = |checks| { - CompilationPlan::new( - &source, - GuestAddress(0x1000), - BlockProfile::SystemModeV1, + let options = crate::Options::new( + BlockProfile::new(Features::SYSTEM_MODE), crate::TargetCpu::detect(), ) - .and_then(|plan| plan.with_memory_checks(checks)) - .and_then(CompilationPlan::compile) - .unwrap() - .native - .x86_64_code + .with_memory_checks(checks); + crate::compile(&source, GuestAddress(0x1000), &options) + .unwrap() + .native + .x86_64_code }; // test al,unit-1; jz +2; ud2 for each element size. let check = |unit: u8| [0xa8, unit - 1, 0x74, 2, 0x0f, 0x0b]; @@ -1267,10 +1222,10 @@ mod tests { (0xd518_1000, vec![]), // msr sctlr_el1, x0 ] { let source: Vec = [ADD, word].into_iter().flat_map(u32::to_le_bytes).collect(); - let compiled = compile_for_target( + let compiled = crate::testing::block_for( &source, GuestAddress(BASE), - BlockProfile::SystemModeV1, + BlockProfile::new(Features::SYSTEM_MODE), crate::TargetCpu::Baseline, ) .unwrap(); @@ -1304,26 +1259,27 @@ mod tests { const DC_ZVA: u32 = 0xd50b_7423; // dc zva, x3 const DC_GVA: u32 = 0xd50b_7463; // dc gva, x3 const MRS: u32 = 0xd538_d080; // mrs x0, tpidr_el1 + let options = |profile, zero_block| { + crate::Options::new(profile, crate::TargetCpu::Baseline).with_native_system( + crate::x86_64::NativeSystem { + zero_block, + ..crate::x86_64::NativeSystem::NONE + }, + ) + }; let compile = |word: u32, bytes| { let source: Vec = [ADD, word, ADD] .into_iter() .flat_map(u32::to_le_bytes) .collect(); - CompilationPlan::new( - &source, - GuestAddress(BASE), - BlockProfile::SystemModeV1, - crate::TargetCpu::Baseline, - ) - .and_then(|plan| plan.with_zero_block(bytes)) - .and_then(CompilationPlan::compile) - .unwrap() + let options = options(BlockProfile::new(Features::SYSTEM_MODE), bytes); + crate::compile(&source, GuestAddress(BASE), &options).unwrap() }; let native = compile(DC_ZVA, Some(64)); assert_eq!(native.source_bytes, 8, "DC ZVA still ends the block"); let code = &native.native.x86_64_code; let at = native.native.source_map[1].1; - let mut zeroing = Vec::new(); + let mut zeroing = Code::new(); crate::x86_64::zero_block::emit(&mut zeroing, 3, 64, crate::x86_64::MemoryChecks::DEFAULT); assert_eq!(code[at..at + zeroing.len()], zeroing); let next = GuestAddress(BASE + 8); @@ -1347,28 +1303,18 @@ mod tests { assert_eq!(code[code.len() - DIRECT_EXIT_BYTES..], system, "{word:#x}"); assert!(compiled.direct_exits.is_empty(), "{word:#x}"); } - let plan = |profile| { - CompilationPlan::new( + let add = |profile, bytes| { + crate::compile( &ADD.to_le_bytes(), GuestAddress(BASE), - profile, - crate::TargetCpu::Baseline, + &options(profile, bytes), ) - .unwrap() }; for bytes in [2, 48, 4096] { - assert!( - plan(BlockProfile::SystemModeV1) - .with_zero_block(Some(bytes)) - .is_err() - ); + assert!(add(BlockProfile::new(Features::SYSTEM_MODE), Some(bytes)).is_err()); } - assert!( - plan(BlockProfile::SystemV1) - .with_zero_block(Some(64)) - .is_err() - ); - assert!(plan(BlockProfile::SystemV1).with_zero_block(None).is_ok()); + assert!(add(BlockProfile::new(Features::SYSTEM), Some(64)).is_err()); + assert!(add(BlockProfile::new(Features::SYSTEM), None).is_ok()); } /// A DC clean operation in the plan's set reads the byte at Xt and falls @@ -1382,26 +1328,27 @@ mod tests { const DC_CIVAC: u32 = 0xd50b_7e20; // dc civac, x0 const DC_CVAU: u32 = 0xd50b_7b20; // dc cvau, x0 const DC_IVAC: u32 = 0xd508_7620; // dc ivac, x0 + let options = |profile, cache_clean| { + crate::Options::new(profile, crate::TargetCpu::Baseline).with_native_system( + crate::x86_64::NativeSystem { + cache_clean, + ..crate::x86_64::NativeSystem::NONE + }, + ) + }; let compile = |word: u32, operations| { let source: Vec = [ADD, word, ADD] .into_iter() .flat_map(u32::to_le_bytes) .collect(); - CompilationPlan::new( - &source, - GuestAddress(BASE), - BlockProfile::SystemModeV1, - crate::TargetCpu::Baseline, - ) - .and_then(|plan| plan.with_cache_clean(operations)) - .and_then(CompilationPlan::compile) - .unwrap() + let options = options(BlockProfile::new(Features::SYSTEM_MODE), operations); + crate::compile(&source, GuestAddress(BASE), &options).unwrap() }; let native = compile(DC_CIVAC, Operations::CIVAC); assert_eq!(native.source_bytes, 8, "the DC still ends the block"); let code = &native.native.x86_64_code; let at = native.native.source_map[1].1; - let mut check = Vec::new(); + let mut check = Code::new(); crate::x86_64::cache_clean::emit(&mut check, 0, crate::x86_64::MemoryChecks::DEFAULT); assert_eq!(code[at..at + check.len()], check); let next = GuestAddress(BASE + 8); @@ -1421,14 +1368,8 @@ mod tests { let code = &compiled.native.x86_64_code; assert_eq!(code[code.len() - DIRECT_EXIT_BYTES..], system, "{word:#x}"); } - let plan = CompilationPlan::new( - &ADD.to_le_bytes(), - GuestAddress(BASE), - BlockProfile::SystemV1, - crate::TargetCpu::Baseline, - ) - .unwrap(); - assert!(plan.with_cache_clean(Operations::CVAC).is_err()); + let system = options(BlockProfile::new(Features::SYSTEM), Operations::CVAC); + assert!(crate::compile(&ADD.to_le_bytes(), GuestAddress(BASE), &system).is_err()); } #[test] @@ -1443,11 +1384,10 @@ mod tests { const BTI_C: u32 = 0xd503_245f; // ISB retires as NOP: what it synchronizes exits on its own. const ISB: u32 = 0xd503_3fdf; - let profile = BlockProfile::SystemModeV1; - assert_eq!(profile.abi(), SYSTEM_MODE_BLOCK_ABI); - assert!(profile.supports_system() && profile.supports_system_registers()); - assert!(profile.supports_pointer_authentication()); - assert!(profile.checked_memory().is_none() && !profile.supports_clock()); + let profile = BlockProfile::new(Features::SYSTEM_MODE); + assert!(profile.has(Features::SYSTEM) && profile.has(Features::SYSTEM_REGISTERS)); + assert!(profile.has(Features::POINTER_AUTHENTICATION)); + assert!(profile.checked_memory().is_none() && !profile.has(Features::CLOCK)); let prefix = [ADD, LDR, STP, DMB, YIELD, NOP, BTI_C, ISB]; for (word, kind) in [ (0xd518_1000_u32, ExitKind::System), // msr sctlr_el1, x0 @@ -1488,7 +1428,8 @@ mod tests { assert_eq!(analysis.terminator_pc, Some(terminal_pc), "{word:#x}"); assert_eq!(analysis.source_bytes, 4 * (prefix.len() + 1)); let compiled = - compile_for_target(&source, BASE, profile, crate::TargetCpu::Baseline).unwrap(); + crate::testing::block_for(&source, BASE, profile, crate::TargetCpu::Baseline) + .unwrap(); let map = &compiled.native.source_map; assert_eq!(map.len(), prefix.len() + 1, "{word:#x}"); assert!( @@ -1505,7 +1446,8 @@ mod tests { assert_eq!(&compiled.native.x86_64_code[at..], expected, "{word:#x}"); } // The shared lane's PEs still end a block at ISB. - let shared = BlockProfile::SystemModeSharedV1(CheckedMemoryProfile::SpAlignmentEnabled); + let shared = BlockProfile::new(Features::SYSTEM_MODE) + .with_checked_memory(CheckedMemoryProfile::SpAlignmentEnabled); let source: Vec = [ADD, ISB, ADD] .iter() .flat_map(|word| word.to_le_bytes()) @@ -1528,7 +1470,8 @@ mod tests { crate::TargetCpu::Baseline, ); let compiled = - compile_for_target(&ordinary, BASE, profile, crate::TargetCpu::Baseline).unwrap(); + crate::testing::block_for(&ordinary, BASE, profile, crate::TargetCpu::Baseline) + .unwrap(); let check = crate::x86_64::RangeCheck::FIVE_LEVEL.code(); let mut unchecked = compiled.native.x86_64_code.clone(); let at = unchecked @@ -1551,18 +1494,19 @@ mod tests { ..aligned }, ); - let compiled = CompilationPlan::new(&ordinary, BASE, profile, crate::TargetCpu::Baseline) - .unwrap() - .with_memory_checks(aligned) - .unwrap() - .compile() - .unwrap(); + let options = + crate::Options::new(profile, crate::TargetCpu::Baseline).with_memory_checks(aligned); + let compiled = crate::compile(&ordinary, BASE, &options).unwrap(); assert_eq!(compiled.native.x86_64_code, expected.x86_64_code); assert_ne!(expected.x86_64_code.len(), 0); // The trap and system decoders of other profiles do not see SYS. assert!( - analyze_with_profile(&0xd508_8723_u32.to_le_bytes(), BASE, BlockProfile::SystemV1) - .is_err() + analyze_with_profile( + &0xd508_8723_u32.to_le_bytes(), + BASE, + BlockProfile::new(Features::SYSTEM) + ) + .is_err() ); } @@ -1581,17 +1525,28 @@ mod tests { .flat_map(u32::to_le_bytes) .collect(); // The pair needs CMPXCHG16B, which the baseline target lacks. - for profile in [BlockProfile::Ordinary, BlockProfile::SystemModeV1] { - let plan = CompilationPlan::new(&source, BASE, profile, crate::TargetCpu::Baseline); + for profile in [ + BlockProfile::ORDINARY, + BlockProfile::new(Features::SYSTEM_MODE), + ] { + let plan = CompilationPlan::new( + &source, + BASE, + &crate::Options::new(profile, crate::TargetCpu::Baseline), + ); assert!(plan.is_err(), "{profile:?}"); } let target = crate::TargetCpu::X86_64_V2.with_atomic_load16(); - let code = CompilationPlan::new(&source, BASE, BlockProfile::SystemModeV1, target) - .unwrap() - .compile() - .unwrap() - .native - .x86_64_code; + let code = CompilationPlan::new( + &source, + BASE, + &crate::Options::new(BlockProfile::new(Features::SYSTEM_MODE), target), + ) + .unwrap() + .compile() + .unwrap() + .native + .x86_64_code; assert!(code.contains(&LOCK), "{code:02x?}"); assert!(code.windows(MFENCE.len()).any(|window| window == MFENCE)); } @@ -1635,25 +1590,29 @@ mod tests { .flat_map(u32::to_le_bytes) .collect(); let code = |profile| { - compile_for_target(&source, BASE, profile, crate::TargetCpu::Baseline) + crate::testing::block_for(&source, BASE, profile, crate::TargetCpu::Baseline) .unwrap() .native .x86_64_code }; - let ordinary = code(BlockProfile::Ordinary); + let ordinary = code(BlockProfile::ORDINARY); for profile in [ - BlockProfile::DarwinArm64ThreadV1, - BlockProfile::AppleArm64eSoftwarePauthV1, - BlockProfile::AppleArm64eSoftwarePauthClockV1, - BlockProfile::AppleArm64eSoftwarePauthThreadV1, - BlockProfile::AppleArm64eSoftwarePauthClockThreadV1, + BlockProfile::new(Features::THREAD_REGISTERS.union(Features::AMX)), + BlockProfile::new(Features::POINTER_AUTHENTICATION), + BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)), + BlockProfile::new( + Features::POINTER_AUTHENTICATION + .union(Features::THREAD_REGISTERS) + .union(Features::AMX), + ), + BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)), ] { assert_eq!(code(profile), ordinary, "{profile:?}"); } let check = crate::x86_64::RangeCheck::FIVE_LEVEL.code(); let has_check = |code: &[u8]| code.windows(check.len()).any(|bytes| bytes == check); assert!(!has_check(&ordinary)); - let system = code(BlockProfile::SystemModeV1); + let system = code(BlockProfile::new(Features::SYSTEM_MODE)); assert!(has_check(&system)); assert_ne!(system, ordinary); } @@ -1674,17 +1633,18 @@ mod tests { .into_iter() .flat_map(u32::to_le_bytes) .collect(); - let analysis = analyze_with_profile(&source, BASE, BlockProfile::SystemV1).unwrap(); + let analysis = + analyze_with_profile(&source, BASE, BlockProfile::new(Features::SYSTEM)).unwrap(); let instruction = analysis.system_instruction.unwrap(); assert_eq!(analysis.source_bytes, 2 * size_of::()); assert_eq!( instruction.instruction_pc, GuestAddress(BASE.0 + size_of::() as u64) ); - let compiled = compile_for_target( + let compiled = crate::testing::block_for( &source, BASE, - BlockProfile::SystemV1, + BlockProfile::new(Features::SYSTEM), crate::TargetCpu::Baseline, ) .unwrap(); @@ -1699,15 +1659,20 @@ mod tests { // Ordinary RAM, exclusives and legacy FP/SIMD cannot bypass shared owners. for word in [0xf940_0000_u32, 0xf900_0000, 0xc85f_fc00, 0x1e20_2800] { let source: Vec<_> = [word, SVC].into_iter().flat_map(u32::to_le_bytes).collect(); - assert!(analyze_with_profile(&source, BASE, BlockProfile::SystemV1).is_err()); + assert!( + analyze_with_profile(&source, BASE, BlockProfile::new(Features::SYSTEM)).is_err() + ); } assert_eq!( ExitKind::try_from(ExitKind::System as u64), Ok(ExitKind::System) ); - assert_ne!(BlockProfile::SystemV1.abi(), BlockProfile::Ordinary.abi()); + assert_ne!( + BlockProfile::new(Features::SYSTEM).abi(), + BlockProfile::ORDINARY.abi() + ); assert!( - analyze_with_profile(&SVC.to_le_bytes(), BASE, BlockProfile::Ordinary) + analyze_with_profile(&SVC.to_le_bytes(), BASE, BlockProfile::ORDINARY) .unwrap() .trap .is_some() @@ -1733,16 +1698,20 @@ mod tests { let continuation = GuestAddress(helper_pc.0 + size_of::() as u64); for operation in HALF_OPERATIONS { for profile in [ - BlockProfile::Ordinary, - BlockProfile::AppleArm64eSoftwarePauthV1, - BlockProfile::AppleArm64eSoftwarePauthClockV1, - BlockProfile::DarwinArm64ThreadV1, - BlockProfile::AppleArm64eSoftwarePauthThreadV1, - BlockProfile::AppleArm64eSoftwarePauthClockThreadV1, + BlockProfile::ORDINARY, + BlockProfile::new(Features::POINTER_AUTHENTICATION), + BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)), + BlockProfile::new(Features::THREAD_REGISTERS.union(Features::AMX)), + BlockProfile::new( + Features::POINTER_AUTHENTICATION + .union(Features::THREAD_REGISTERS) + .union(Features::AMX), + ), + BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)), ] { let source = bytes(&[NOP, operation, UNSUPPORTED]); let analysis = analyze_with_profile(&source, base, profile).unwrap(); - let compiled = compile_with_profile(&source, base, profile).unwrap(); + let compiled = crate::testing::block_with(&source, base, profile).unwrap(); assert_eq!(analysis.source_bytes, 2 * size_of::()); assert_eq!(compiled.source_bytes, analysis.source_bytes); assert_eq!( @@ -1789,17 +1758,21 @@ mod tests { 0x4e401400, 0x4ec01400, 0x6e401c00, // eight lanes ] { for profile in [ - BlockProfile::Ordinary, - BlockProfile::AppleArm64eSoftwarePauthV1, - BlockProfile::AppleArm64eSoftwarePauthClockV1, - BlockProfile::DarwinArm64ThreadV1, - BlockProfile::AppleArm64eSoftwarePauthThreadV1, - BlockProfile::AppleArm64eSoftwarePauthClockThreadV1, - BlockProfile::SystemModeV1, + BlockProfile::ORDINARY, + BlockProfile::new(Features::POINTER_AUTHENTICATION), + BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)), + BlockProfile::new(Features::THREAD_REGISTERS.union(Features::AMX)), + BlockProfile::new( + Features::POINTER_AUTHENTICATION + .union(Features::THREAD_REGISTERS) + .union(Features::AMX), + ), + BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)), + BlockProfile::new(Features::SYSTEM_MODE), ] { let source = bytes(&[NOP, operation, NOP]); let analysis = analyze_with_profile(&source, base, profile).unwrap(); - let compiled = compile_with_profile(&source, base, profile).unwrap(); + let compiled = crate::testing::block_with(&source, base, profile).unwrap(); assert_eq!(analysis.source_bytes, source.len()); assert_eq!(compiled.source_bytes, analysis.source_bytes); assert_eq!( @@ -1815,7 +1788,7 @@ mod tests { .pc, suffix_pc ); - assert!(compile_with_profile(&invalid, base, profile).is_err()); + assert!(crate::testing::block_with(&invalid, base, profile).is_err()); assert!(source_bytes_with_profile(&invalid, base, profile).is_err()); } } @@ -1889,7 +1862,7 @@ mod tests { assert_eq!(analysis.source_bytes, source_bytes(&source, base).unwrap()); assert_eq!( analysis.source_bytes, - compile(&source, base).unwrap().source_bytes + crate::testing::block(&source, base).unwrap().source_bytes ); assert_eq!(analysis.source_bytes, 4); assert_eq!( @@ -2008,12 +1981,12 @@ mod tests { #[test] fn clock_profile_boundaries_share_analysis_and_do_not_widen_old_profiles() { let base = GuestAddress(0x4000); - let profile = BlockProfile::AppleArm64eSoftwarePauthClockV1; + let profile = BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)); for word in [0xd5033fdf, 0xd53be040, 0xd53be05f] { let source = bytes(&[0xd2800020, word, 0]); for previous in [ - BlockProfile::Ordinary, - BlockProfile::AppleArm64eSoftwarePauthV1, + BlockProfile::ORDINARY, + BlockProfile::new(Features::POINTER_AUTHENTICATION), ] { assert_eq!( analyze_with_profile(&source, base, previous) @@ -2021,11 +1994,11 @@ mod tests { .pc, GuestAddress(base.0 + 4) ); - assert!(compile_with_profile(&source, base, previous).is_err()); + assert!(crate::testing::block_with(&source, base, previous).is_err()); assert!(source_bytes_with_profile(&source, base, previous).is_err()); } let analysis = analyze_with_profile(&source, base, profile).unwrap(); - let compiled = compile_with_profile(&source, base, profile).unwrap(); + let compiled = crate::testing::block_with(&source, base, profile).unwrap(); assert_eq!(analysis.source_bytes, 8); assert_eq!(compiled.source_bytes, 8); assert_eq!( @@ -2060,19 +2033,23 @@ mod tests { let source = bytes(&[word, 0]); assert_eq!( analyze_with_profile(&source, base, profile).unwrap(), - analyze_with_profile(&source, base, BlockProfile::AppleArm64eSoftwarePauthV1) - .unwrap() + analyze_with_profile( + &source, + base, + BlockProfile::new(Features::POINTER_AUTHENTICATION) + ) + .unwrap() ); } - assert!(profile.supports_pointer_authentication() && profile.supports_clock()); - assert!(!BlockProfile::Ordinary.supports_pointer_authentication()); - assert!(!BlockProfile::AppleArm64eSoftwarePauthV1.supports_clock()); + assert!(profile.has(Features::POINTER_AUTHENTICATION) && profile.has(Features::CLOCK)); + assert!(!BlockProfile::ORDINARY.has(Features::POINTER_AUTHENTICATION)); + assert!(!BlockProfile::new(Features::POINTER_AUTHENTICATION).has(Features::CLOCK)); } #[test] fn clock_boundary_respects_window_limit_and_does_not_skip_prior_unknown_words() { let base = GuestAddress(0x1000); - let profile = BlockProfile::AppleArm64eSoftwarePauthClockV1; + let profile = BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)); let first = analyze_with_profile(&bytes(&[0xd53be05f, 0]), base, profile).unwrap(); assert_eq!(first.source_bytes, 4); assert_eq!( @@ -2088,7 +2065,7 @@ mod tests { GuestAddress(base.0 + (MAX_BLOCK_INSTRUCTIONS as u64 - 1) * 4) ); assert!( - compile_with_profile( + crate::testing::block_with( &bytes(&[0xd53be040; MAX_BLOCK_INSTRUCTIONS + 1]), base, profile @@ -2177,7 +2154,7 @@ mod tests { }) ); assert_eq!(request.operation.required_key(), Some(key)); - assert!(compile(&bytes(&[word]), pc).is_err()); + assert!(crate::testing::block(&bytes(&[word]), pc).is_err()); let zero_word = word | (1 << 13); let zero = decode_pointer_authentication(pc, zero_word).unwrap(); assert_eq!( @@ -2215,7 +2192,7 @@ mod tests { const PACGA_X1_X2_X3: u32 = 0x9ac3_3041; let pc = GuestAddress(0x1000); let source = bytes(&[PACGA_X1_X2_X3]); - assert!(compile(&source, pc).is_err()); + assert!(crate::testing::block(&source, pc).is_err()); let instruction = decode_pointer_authentication(pc, PACGA_X1_X2_X3) .unwrap() .unwrap(); @@ -2227,8 +2204,12 @@ mod tests { modifier: 3, }) ); - let analysis = - analyze_with_profile(&source, pc, BlockProfile::AppleArm64eSoftwarePauthV1).unwrap(); + let analysis = analyze_with_profile( + &source, + pc, + BlockProfile::new(Features::POINTER_AUTHENTICATION), + ) + .unwrap(); assert_eq!(analysis.pointer_authentication, Some(instruction)); assert_eq!(analysis.terminator_pc, Some(pc)); assert_eq!( @@ -2250,7 +2231,7 @@ mod tests { let analysis = analyze_with_profile( &bytes(&[word]), pc, - BlockProfile::AppleArm64eSoftwarePauthV1, + BlockProfile::new(Features::POINTER_AUTHENTICATION), ) .unwrap(); assert_eq!( @@ -2318,7 +2299,7 @@ mod tests { assert!(value.operation.is_transfer()); assert!(!value.operation.is_return()); assert_eq!(value.operation.required_key(), Some(key)); - assert!(compile(&bytes(&[word]), pc).is_err()); + assert!(crate::testing::block(&bytes(&[word]), pc).is_err()); } } } @@ -2494,15 +2475,15 @@ mod tests { ); } for profile in [ - BlockProfile::AppleArm64eSoftwarePauthV1, - BlockProfile::AppleArm64eSoftwarePauthClockV1, + BlockProfile::new(Features::POINTER_AUTHENTICATION), + BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)), ] { let analysis = analyze_with_profile(&bytes(&[word, 0]), pc, profile).unwrap(); assert_eq!(analysis.source_bytes, 4); assert_eq!(analysis.dynamic_edge.is_some(), expected.is_return()); assert_eq!(analysis.static_successors.is_empty(), expected.is_return()); } - assert!(compile(&bytes(&[word]), pc).is_err()); + assert!(crate::testing::block(&bytes(&[word]), pc).is_err()); } for data in [false, true] { for destination in 0..32u32 { @@ -2534,15 +2515,15 @@ mod tests { #[test] fn pointer_authentication_profile_consumes_only_native_prefix_and_boundary() { let base = GuestAddress(0x4000); - let profile = BlockProfile::AppleArm64eSoftwarePauthV1; + let profile = BlockProfile::new(Features::POINTER_AUTHENTICATION); for word in [0xd503237f, 0xd50323ff, 0xd65f0fff] { let source = bytes(&[0xd2800020, word, 0]); // MOV X0,#1; helper; unknown data let ordinary = analyze(&source, base).unwrap_err(); assert_eq!(ordinary.pc, GuestAddress(base.0 + 4)); - assert!(compile(&source, base).is_err()); + assert!(crate::testing::block(&source, base).is_err()); assert!(source_bytes(&source, base).is_err()); let analysis = analyze_with_profile(&source, base, profile).unwrap(); - let compiled = compile_with_profile(&source, base, profile).unwrap(); + let compiled = crate::testing::block_with(&source, base, profile).unwrap(); assert_eq!( source_bytes_with_profile(&source, base, profile).unwrap(), 8 @@ -2585,8 +2566,7 @@ mod tests { let failure = analyze_with_profile(&bytes(&[0, word]), base, profile).unwrap_err(); assert_eq!(failure.pc, base); } - assert_eq!(BlockProfile::default().abi(), BLOCK_ABI); - assert_ne!(profile.abi(), BLOCK_ABI); + assert_ne!(profile.abi(), BlockProfile::ORDINARY.abi()); // Ordinary transfers and trap behavior are identical in either profile. for word in [0xd65f03c0, 0x14000002, 0xd4001001] { let source = bytes(&[word, 0]); @@ -2628,7 +2608,7 @@ mod tests { } } for encoding in [0xd65f0bff, 0xd65f0fff, 0xd71f0800, 0xd73f0800, 0xd69f03e0] { - assert!(compile(&bytes(&[encoding]), GuestAddress(0x1000)).is_err()); + assert!(crate::testing::block(&bytes(&[encoding]), GuestAddress(0x1000)).is_err()); } } @@ -2652,7 +2632,7 @@ mod tests { 0x14000001, 0x54000020, 0xb4000020, 0x36000020, 0x94000001, 0xd61f0000, 0xd63f03c0, 0xd65f03c0, ] { - let compiled = compile( + let compiled = crate::testing::block( &bytes(&[0xd503201f, terminator, 0xffffffff]), GuestAddress(0x1000), ) @@ -2670,13 +2650,16 @@ mod tests { assert_eq!(compiled.native.source_map[0], (GuestAddress(0x1000), 0)); assert_eq!(compiled.native.source_map[1], (GuestAddress(0x1004), 1)); } - let compiled = compile(&bytes(&[0xd503201f, 0xd503201f]), GuestAddress(0x1000)).unwrap(); + let compiled = + crate::testing::block(&bytes(&[0xd503201f, 0xd503201f]), GuestAddress(0x1000)).unwrap(); assert_eq!(compiled.source_bytes, 8); assert_eq!( compiled.native.source_map, [(GuestAddress(0x1000), 0), (GuestAddress(0x1004), 1)] ); - assert!(compile(&bytes(&[0xffffffff, 0xd65f03c0]), GuestAddress(0x1000)).is_err()); + assert!( + crate::testing::block(&bytes(&[0xffffffff, 0xd65f03c0]), GuestAddress(0x1000)).is_err() + ); } #[test] @@ -2688,10 +2671,10 @@ mod tests { (bytes(&[0xd503201f]), u64::MAX - 3), (bytes(&vec![0xd503201f; MAX_BLOCK_INSTRUCTIONS + 1]), 0), ] { - assert!(compile(&input, GuestAddress(base)).is_err()); + assert!(crate::testing::block(&input, GuestAddress(base)).is_err()); assert!(source_bytes(&input, GuestAddress(base)).is_err()); } - let compiled = compile( + let compiled = crate::testing::block( &bytes(&vec![0xd503201f; MAX_BLOCK_INSTRUCTIONS]), GuestAddress(0x1000), ) @@ -2762,7 +2745,7 @@ mod tests { 0xd4200001, // reserved BRK neighbor ] { assert_eq!(decode_trap(GuestAddress(0x2000), word).unwrap(), None); - assert!(compile(&bytes(&[word]), GuestAddress(0x2000)).is_err()); + assert!(crate::testing::block(&bytes(&[word]), GuestAddress(0x2000)).is_err()); } } @@ -2770,7 +2753,7 @@ mod tests { fn trap_is_a_consumed_boundary_with_its_own_source_map_and_no_leaf_fallback() { for word in [0xd4000001, 0xd4200000, 0xd41fffe1, 0xd43fffe0] { let source = bytes(&[0xd503201f, word, 0xffffffff, 0xd65f03c0]); - let compiled = compile(&source, GuestAddress(0x2ffc)).unwrap(); + let compiled = crate::testing::block(&source, GuestAddress(0x2ffc)).unwrap(); assert_eq!(compiled.source_bytes, 8); assert_eq!(source_bytes(&source, GuestAddress(0x2ffc)).unwrap(), 8); assert_eq!( @@ -2779,12 +2762,14 @@ mod tests { ); assert_eq!(compiled.native.x86_64_code.len(), 17); assert_eq!(compiled.native.x86_64_code[0], 0x90); - assert!(crate::compile(&bytes(&[word, 0xd65f03c0]), GuestAddress(0x3000)).is_err()); + assert!( + crate::testing::leaf(&bytes(&[word, 0xd65f03c0]), GuestAddress(0x3000)).is_err() + ); } // Original block input-window policy still forbids wrapping extents, // even though BRK's standalone preferred return PC is representable. for word in [0xd4000001, 0xd4200000] { - assert!(compile(&bytes(&[word]), GuestAddress(u64::MAX - 3)).is_err()); + assert!(crate::testing::block(&bytes(&[word]), GuestAddress(u64::MAX - 3)).is_err()); } } } diff --git a/crates/stela-compiler/src/block/analysis.rs b/crates/stela-compiler/src/block/analysis.rs index bfa2b63991..9fca4347cf 100644 --- a/crates/stela-compiler/src/block/analysis.rs +++ b/crates/stela-compiler/src/block/analysis.rs @@ -1,6 +1,6 @@ //! Block boundaries, static successors and dynamic edges, found without emitting code. use super::{ - BlockProfile, ClockInstruction, ExitKind, MAX_BLOCK_INSTRUCTIONS, NOP_ENCODING, + BlockProfile, ClockInstruction, ExitKind, Features, MAX_BLOCK_INSTRUCTIONS, NOP_ENCODING, PointerAuthentication, PointerAuthenticationOperation, SynchronousTrap, SystemInstruction, Terminator, ThreadRegisterInstruction, decode_clock_instruction, decode_pointer_authentication, decode_system_instruction, decode_terminator, decode_thread_register_instruction, memory, @@ -77,7 +77,7 @@ pub struct BlockAnalysis { /// continuations are candidates, since the callee may not return; dynamic /// targets and trap resumption are resolved at run time. pub fn analyze(source: &[u8], base: GuestAddress) -> Result { - analyze_with_profile(source, base, BlockProfile::Ordinary) + analyze_with_profile(source, base, BlockProfile::ORDINARY) } pub fn analyze_with_profile( @@ -243,7 +243,7 @@ pub(super) fn parse( })?); source_bytes += 4; let word = u32::from_le_bytes(*bytes); - if profile.supports_full_system() { + if profile.has(Features::FULL_SYSTEM) { // PAuth hints share the hint space, so they are matched first. if let Some(decoded) = decode_pointer_authentication(pc, word).map_err(|error| BlockAnalysisError { @@ -273,7 +273,7 @@ pub(super) fn parse( // maintenance, exception entry and return, ends its block and // completes in the engine, which recomputes what derives from // it before the next fetch. The shared lane's PEs keep it. - if profile == BlockProfile::SystemModeV1 + if profile == BlockProfile::new(Features::SYSTEM_MODE) && matches!( crate::aarch64::system::synchronization::decode(word), Some( @@ -297,7 +297,8 @@ pub(super) fn parse( { // The shared lane executes these through the existing typed // all-writer memory service, not the single-agent CPU monitor. - let checked = matches!(profile, BlockProfile::SystemModeSharedV1(_)) + let checked = (profile.has(Features::FULL_SYSTEM) + && profile.checked_memory().is_some()) && matches!(decoded.operation, system::SystemOperation::Exclusive(Ok(_))); if !checked { terminal = Some((pc, Terminator::System(decoded))); @@ -305,14 +306,14 @@ pub(super) fn parse( } } } - if profile.supports_system() - && !profile.supports_full_system() + if profile.has(Features::SYSTEM) + && !profile.has(Features::FULL_SYSTEM) && let Some(decoded) = decode_system_instruction(pc, word).map_err(|error| BlockAnalysisError { pc, detail: error.0, })? - && (profile.supports_system_registers() + && (profile.has(Features::SYSTEM_REGISTERS) || !matches!( decoded.operation, system::SystemOperation::Register(_) @@ -322,7 +323,7 @@ pub(super) fn parse( terminal = Some((pc, Terminator::System(decoded))); break; } - if profile.supports_pointer_authentication() + if profile.has(Features::POINTER_AUTHENTICATION) && let Some(decoded) = decode_pointer_authentication(pc, word).map_err(|error| BlockAnalysisError { pc, @@ -332,7 +333,7 @@ pub(super) fn parse( terminal = Some((pc, Terminator::PointerAuthentication(decoded))); break; } - if profile.supports_clock() + if profile.has(Features::CLOCK) && let Some(decoded) = decode_clock_instruction(pc, word).map_err(|error| BlockAnalysisError { pc, @@ -342,7 +343,7 @@ pub(super) fn parse( terminal = Some((pc, Terminator::Clock(decoded))); break; } - if profile.supports_thread_registers() + if profile.has(Features::THREAD_REGISTERS) && let Some(decoded) = decode_thread_register_instruction(pc, word).map_err(|error| { BlockAnalysisError { @@ -354,7 +355,7 @@ pub(super) fn parse( terminal = Some((pc, Terminator::ThreadRegister(decoded))); break; } - if profile.supports_amx() + if profile.has(Features::AMX) && let Some(decoded) = crate::amx::decode(pc, word).map_err(|error| BlockAnalysisError { pc, @@ -384,9 +385,9 @@ pub(super) fn parse( detail: "unadmitted original NOP provenance in checked memory profile".into(), }); } - if profile.supports_system() - && !profile.supports_full_system() - && !crate::extended::ordinary_permitted(&instruction.operation) + if profile.has(Features::SYSTEM) + && !profile.has(Features::FULL_SYSTEM) + && !crate::scalable_context::ordinary_permitted(&instruction.operation) { return Err(BlockAnalysisError { pc, @@ -394,7 +395,7 @@ pub(super) fn parse( }); } if let Operation::FloatingPoint(operand) = &instruction.operation - && (matches!(profile, BlockProfile::SystemModeSharedV1(_)) + && ((profile.has(Features::FULL_SYSTEM) && profile.checked_memory().is_some()) || crate::x86_64::numerical_always_exits(operand)) { // The checked full-system prefix has no inline numerical recipe. @@ -426,7 +427,7 @@ pub(super) fn parse( /// Validate and identify the consumed prefix without generating native code. /// Uses the same semantic lift and transfer boundaries as [`compile`]. pub fn source_bytes(source: &[u8], base: GuestAddress) -> Result { - source_bytes_with_profile(source, base, BlockProfile::Ordinary) + source_bytes_with_profile(source, base, BlockProfile::ORDINARY) } pub fn source_bytes_with_profile( diff --git a/crates/stela-compiler/src/block/features.rs b/crates/stela-compiler/src/block/features.rs new file mode 100644 index 0000000000..7e41a955d8 --- /dev/null +++ b/crates/stela-compiler/src/block/features.rs @@ -0,0 +1,287 @@ +//! Guest services a compiled function provides, and the ABI identity derived +//! from them. +use super::CheckedMemoryProfile; +use crate::CompileError; +use alloc::{format, string::String}; +use serde::{Serialize, Serializer, ser::SerializeSeq}; + +/// Shared by every compiled function; the features follow it in the identity. +const ABI_PREFIX: &str = "x86_64-sysv-guest-state-v4"; + +/// A set of guest services. Each member admits the instructions that need the +/// service, as runtime exits or native completions, and names itself in the +/// ABI identity. +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct Features(u16); + +impl Features { + pub const NONE: Self = Self(0); + /// Software pointer authentication through helper exits. Keys and the PAuth + /// version are chosen at run time, so cached code contains neither. + pub const POINTER_AUTHENTICATION: Self = Self(1 << 0); + /// CNTVCT_EL0 reads and ISB through the clock exit. + pub const CLOCK: Self = Self(1 << 1); + /// Thread-register reads and writes through the thread exit. + pub const THREAD_REGISTERS: Self = Self(1 << 2); + /// Apple AMX instructions through the AMX exit, against per-thread or per-PE + /// state. + pub const AMX: Self = Self(1 << 3); + /// Restricted context-independent prefixes and checked System exits. This + /// identifies a service boundary, not CPU feature availability. + pub const SYSTEM: Self = Self(1 << 4); + /// System-register accesses through the System exit. + pub const SYSTEM_REGISTERS: Self = Self(1 << 5); + /// The system-mode engine: guest VAs are native addresses through shadow + /// paging, `GuestState` is exact at every instruction boundary, and every + /// System-class instruction exits with kind 11. Other PEs run concurrently, + /// so atomics are locked and barriers fence. + pub const FULL_SYSTEM: Self = Self(1 << 6); + /// Non-faulting self-loops stay resident, counted by a + /// [`super::loop_budget::LoopBudget`]. + pub const RESIDENT_LOOPS: Self = Self(1 << 7); + /// The two-argument entry with an [`crate::context::ExecutionContext`] in + /// RSI, kept in R15, and a scalable specialization. + pub const CONTEXT: Self = Self(1 << 8); + /// The function returns at the guest's RET X30 instead of exiting to the + /// dispatcher. + pub const LEAF: Self = Self(1 << 9); + + /// The system-mode engine's services. + pub const SYSTEM_MODE: Self = Self::FULL_SYSTEM + .union(Self::SYSTEM) + .union(Self::SYSTEM_REGISTERS) + .union(Self::POINTER_AUTHENTICATION) + .union(Self::AMX); + /// The process helpers a checked-memory block can call. + pub const PROCESS_HELPERS: Self = Self::POINTER_AUTHENTICATION + .union(Self::CLOCK) + .union(Self::THREAD_REGISTERS); + + const NAMES: [(Self, &'static str); 10] = [ + (Self::CONTEXT, "context"), + (Self::POINTER_AUTHENTICATION, "pointer-authentication"), + (Self::CLOCK, "clock"), + (Self::THREAD_REGISTERS, "thread-registers"), + (Self::AMX, "amx"), + (Self::SYSTEM, "system"), + (Self::SYSTEM_REGISTERS, "system-registers"), + (Self::FULL_SYSTEM, "full-system"), + (Self::RESIDENT_LOOPS, "resident-loops"), + (Self::LEAF, "leaf"), + ]; + + pub const fn union(self, other: Self) -> Self { + Self(self.0 | other.0) + } + pub const fn difference(self, other: Self) -> Self { + Self(self.0 & !other.0) + } + pub const fn contains(self, other: Self) -> bool { + self.0 & other.0 == other.0 + } + pub const fn is_empty(self) -> bool { + self.0 == 0 + } + fn names(self) -> impl Iterator { + Self::NAMES + .into_iter() + .filter(move |(feature, _)| self.contains(*feature)) + .map(|(_, name)| name) + } +} + +impl core::ops::BitOr for Features { + type Output = Self; + fn bitor(self, other: Self) -> Self { + self.union(other) + } +} + +impl core::fmt::Debug for Features { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("Features(")?; + for (index, name) in self.names().enumerate() { + if index > 0 { + f.write_str("|")?; + } + f.write_str(name)?; + } + f.write_str(")") + } +} + +impl Serialize for Features { + fn serialize(&self, serializer: S) -> Result { + let mut names = serializer.serialize_seq(None)?; + for name in self.names() { + names.serialize_element(name)?; + } + names.end() + } +} + +/// The services a compiled function provides and how its memory accesses are +/// checked. Without checked memory, accesses go directly to guest RAM. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct BlockProfile { + features: Features, + checked: Option, +} + +impl BlockProfile { + /// A direct-RAM block that exits to the dispatcher at every transfer. + pub const ORDINARY: Self = Self::new(Features::NONE); + + pub const fn new(features: Features) -> Self { + Self { + features, + checked: None, + } + } + /// The same services with every memory access through the checked memory + /// service. + pub const fn with_checked_memory(self, checked: CheckedMemoryProfile) -> Self { + Self { + checked: Some(checked), + ..self + } + } + pub const fn features(self) -> Features { + self.features + } + /// Whether the profile provides every service in `features`. + pub const fn has(self, features: Features) -> bool { + self.features.contains(features) + } + pub const fn checked_memory(self) -> Option { + self.checked + } + + /// The identity cached code is keyed by: one name per feature, then the + /// checked memory profile. + pub fn abi(self) -> String { + let mut abi = String::from(ABI_PREFIX); + abi.push_str(if self.has(Features::LEAF) { + "-leaf" + } else { + "-block-exit" + }); + for name in self.features.difference(Features::LEAF).names() { + abi.push('+'); + abi.push_str(name); + } + if let Some(checked) = self.checked { + abi.push('+'); + abi.push_str(checked.id()); + } + abi + } + + /// Refuse the combinations no emitter implements. + pub fn validate(self) -> Result<(), CompileError> { + use Features as F; + let features = self.features; + let direct = self.checked.is_none(); + let valid = if features.contains(F::LEAF) || features.contains(F::CONTEXT) { + direct && features.difference(F::LEAF | F::CONTEXT).is_empty() + } else if features.contains(F::FULL_SYSTEM) { + // The shared full-system lane checks SP alignment only. + features == F::SYSTEM_MODE + && !matches!(self.checked, Some(CheckedMemoryProfile::AddressChecks(_))) + } else if features.contains(F::SYSTEM) { + direct + && features + .difference(F::SYSTEM | F::SYSTEM_REGISTERS) + .is_empty() + } else if features.contains(F::RESIDENT_LOOPS) { + direct && features == F::RESIDENT_LOOPS + } else if !direct { + features.is_empty() || features == F::PROCESS_HELPERS + } else { + // The clock exit shares the PAuth helper interface, and AMX state is + // per guest thread. + features.difference(F::PROCESS_HELPERS | F::AMX).is_empty() + && (!features.contains(F::CLOCK) || features.contains(F::POINTER_AUTHENTICATION)) + && features.contains(F::THREAD_REGISTERS) == features.contains(F::AMX) + }; + if valid { + Ok(()) + } else { + Err(CompileError(format!("no emitter implements {self:?}"))) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use CheckedMemoryProfile::{SpAlignmentDisabled, SpAlignmentEnabled}; + use Features as F; + + #[test] + fn the_abi_names_each_feature_and_the_checked_profile() { + assert_eq!( + BlockProfile::ORDINARY.abi(), + "x86_64-sysv-guest-state-v4-block-exit" + ); + assert_eq!( + BlockProfile::new(F::LEAF | F::CONTEXT).abi(), + "x86_64-sysv-guest-state-v4-leaf+context" + ); + assert_eq!( + BlockProfile::new(F::PROCESS_HELPERS) + .with_checked_memory(SpAlignmentEnabled) + .abi(), + "x86_64-sysv-guest-state-v4-block-exit+pointer-authentication+clock\ + +thread-registers+checked-gpr-memory-sa0-on-normal-wb-v4" + ); + } + + #[test] + fn profiles_have_distinct_abis() { + let mut profiles = alloc::vec![ + BlockProfile::ORDINARY, + BlockProfile::new(F::LEAF), + BlockProfile::new(F::LEAF | F::CONTEXT), + BlockProfile::new(F::CONTEXT), + BlockProfile::new(F::RESIDENT_LOOPS), + BlockProfile::new(F::SYSTEM), + BlockProfile::new(F::SYSTEM | F::SYSTEM_REGISTERS), + BlockProfile::new(F::SYSTEM_MODE), + BlockProfile::new(F::POINTER_AUTHENTICATION), + BlockProfile::new(F::POINTER_AUTHENTICATION | F::CLOCK), + BlockProfile::new(F::THREAD_REGISTERS | F::AMX), + BlockProfile::new(F::POINTER_AUTHENTICATION | F::THREAD_REGISTERS | F::AMX), + BlockProfile::new(F::PROCESS_HELPERS | F::AMX), + ]; + for checked in [SpAlignmentEnabled, SpAlignmentDisabled] { + profiles.push(BlockProfile::ORDINARY.with_checked_memory(checked)); + profiles.push(BlockProfile::new(F::PROCESS_HELPERS).with_checked_memory(checked)); + profiles.push(BlockProfile::new(F::SYSTEM_MODE).with_checked_memory(checked)); + } + let mut abis = alloc::collections::BTreeSet::new(); + for profile in &profiles { + assert_eq!(profile.validate(), Ok(()), "{profile:?}"); + assert!(abis.insert(profile.abi()), "{profile:?}"); + } + } + + #[test] + fn combinations_without_an_emitter_are_refused() { + for profile in [ + BlockProfile::new(F::CLOCK), + BlockProfile::new(F::THREAD_REGISTERS), + BlockProfile::new(F::AMX), + BlockProfile::new(F::SYSTEM_REGISTERS), + BlockProfile::new(F::FULL_SYSTEM), + BlockProfile::new(F::LEAF | F::POINTER_AUTHENTICATION), + BlockProfile::new(F::RESIDENT_LOOPS | F::POINTER_AUTHENTICATION), + BlockProfile::new(F::SYSTEM | F::POINTER_AUTHENTICATION), + BlockProfile::new(F::POINTER_AUTHENTICATION).with_checked_memory(SpAlignmentEnabled), + BlockProfile::new(F::LEAF).with_checked_memory(SpAlignmentEnabled), + BlockProfile::new(F::SYSTEM).with_checked_memory(SpAlignmentEnabled), + ] { + assert!(profile.validate().is_err(), "{profile:?}"); + } + } +} diff --git a/crates/stela-compiler/src/block/loop_budget.rs b/crates/stela-compiler/src/block/loop_budget.rs index 65e7e127d7..29e7fcd474 100644 --- a/crates/stela-compiler/src/block/loop_budget.rs +++ b/crates/stela-compiler/src/block/loop_budget.rs @@ -1,8 +1,5 @@ //! Per-invocation iteration budget for resident blocks. -pub const RESIDENT_BLOCK_ABI: &str = - "x86_64-sysv-guest-state-v2-block-exit-direct-ram-resident-budget-v1"; - /// Native code counts the basic blocks it completes, including internal back /// edges. The caller keeps this context alive until native return. #[repr(C)] diff --git a/crates/stela-compiler/src/block/memory.rs b/crates/stela-compiler/src/block/memory.rs index 39af191e11..bf52d9f447 100644 --- a/crates/stela-compiler/src/block/memory.rs +++ b/crates/stela-compiler/src/block/memory.rs @@ -68,46 +68,7 @@ impl CheckedMemoryProfile { } } - pub const fn abi(self) -> &'static str { - match self { - Self::AddressChecks(_) => { - "x86_64-sysv-guest-state-v3-context-block-exit-checked-memory-address-v5" - } - Self::SpAlignmentEnabled => { - "x86_64-sysv-guest-state-v3-context-block-exit-checked-gpr-memory-sa0-on-normal-wb-v4" - } - Self::SpAlignmentDisabled => { - "x86_64-sysv-guest-state-v3-context-block-exit-checked-gpr-memory-sa0-off-normal-wb-v4" - } - } - } - /// Immutable identity for the distinct all-writer full-system lane. - /// Preparation rejects other specializations before native emission. - pub const fn shared_system_abi(self) -> &'static str { - match self { - Self::SpAlignmentEnabled => { - "x86_64-sysv-guest-state-v3-context-block-exit-system-shared-normal-wb-sa-on-v1" - } - Self::SpAlignmentDisabled => { - "x86_64-sysv-guest-state-v3-context-block-exit-system-shared-normal-wb-sa-off-v1" - } - _ => "unadmitted-system-shared-memory-specialization-v1", - } - } - - pub const fn process_helpers_abi(self) -> &'static str { - match self { - Self::AddressChecks(_) => { - "x86_64-sysv-guest-state-v3-context-block-exit-checked-memory-address-pauth-clock-thread-v3" - } - Self::SpAlignmentEnabled => { - "x86_64-sysv-guest-state-v3-context-block-exit-checked-gpr-memory-sa0-on-normal-wb-pauth-clock-thread-v2" - } - Self::SpAlignmentDisabled => { - "x86_64-sysv-guest-state-v3-context-block-exit-checked-gpr-memory-sa0-off-normal-wb-pauth-clock-thread-v2" - } - } - } + /// The profile's name in a checked block's ABI identity. pub const fn id(self) -> &'static str { match self { Self::AddressChecks(_) => "checked-memory-address-v5", @@ -167,8 +128,8 @@ impl CheckedPlan { profile: CheckedMemoryProfile, outer: super::BlockProfile, ) -> Result { - let process_helpers = outer.supports_checked_process_helpers(); - let system_helpers = matches!(outer, super::BlockProfile::SystemModeSharedV1(_)); + let process_helpers = outer.has(super::Features::PROCESS_HELPERS); + let system_helpers = outer.has(super::Features::FULL_SYSTEM); if system_helpers && !matches!( profile, @@ -250,6 +211,7 @@ impl CheckedPlan { #[cfg(test)] mod tests { use super::*; + use crate::block::Features; use alloc::vec::Vec; #[test] fn checked_process_helpers_use_distinct_immutable_abi_and_exact_terminals() { @@ -259,25 +221,31 @@ mod tests { CheckedMemoryProfile::SpAlignmentEnabled, CheckedMemoryProfile::SpAlignmentDisabled, ] { - let selected = BlockProfile::CheckedMemoryPauthClockThread(recipe); - assert_ne!(selected.abi(), BlockProfile::CheckedMemory(recipe).abi()); + let selected = BlockProfile::new(Features::PROCESS_HELPERS).with_checked_memory(recipe); assert_ne!( selected.abi(), - BlockProfile::AppleArm64eSoftwarePauthClockThreadV1.abi() + BlockProfile::ORDINARY.with_checked_memory(recipe).abi() ); - assert!(selected.supports_pointer_authentication()); - assert!(selected.supports_clock()); - assert!(selected.supports_thread_registers()); - assert!(!selected.supports_system()); + assert_ne!( + selected.abi(), + BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)).abi() + ); + assert!(selected.has(Features::POINTER_AUTHENTICATION)); + assert!(selected.has(Features::CLOCK)); + assert!(selected.has(Features::THREAD_REGISTERS)); + assert!(!selected.has(Features::SYSTEM)); for terminal in [0xd503237fu32, 0xd53be040, 0xd5033fdf, 0xd53bd061] { // Original MOV X3,#0x44 prefix must survive before the helper. let source: Vec<_> = [0xd2800883u32, terminal, 0xd65f03c0] .into_iter() .flat_map(u32::to_le_bytes) .collect(); - let plan = - CompilationPlan::new(&source, base, selected, crate::TargetCpu::Baseline) - .unwrap(); + let plan = CompilationPlan::new( + &source, + base, + &crate::Options::new(selected, crate::TargetCpu::Baseline), + ) + .unwrap(); assert_eq!(plan.source_bytes(), 8); assert!(plan.memory_requirements().is_some()); let compiled = plan.compile().unwrap(); @@ -287,8 +255,10 @@ mod tests { CompilationPlan::new( &source, base, - BlockProfile::CheckedMemory(recipe), - crate::TargetCpu::Baseline + &crate::Options::new( + BlockProfile::ORDINARY.with_checked_memory(recipe), + crate::TargetCpu::Baseline + ) ) .is_err() ); @@ -296,7 +266,12 @@ mod tests { // Authenticated data loads still need the helper reader. let load = 0xf8200400u32.to_le_bytes(); assert!( - CompilationPlan::new(&load, base, selected, crate::TargetCpu::Baseline).is_err() + CompilationPlan::new( + &load, + base, + &crate::Options::new(selected, crate::TargetCpu::Baseline) + ) + .is_err() ); } } @@ -315,8 +290,11 @@ mod tests { let plan = crate::block::CompilationPlan::new( &source, GuestAddress(0x1000), - crate::block::BlockProfile::CheckedMemoryPauthClockThread(profile), - TargetCpu::Baseline, + &crate::Options::new( + crate::block::BlockProfile::new(Features::PROCESS_HELPERS) + .with_checked_memory(profile), + TargetCpu::Baseline, + ), ) .unwrap(); let required = plan.memory_requirements().unwrap(); @@ -352,8 +330,11 @@ mod tests { let plan = crate::block::CompilationPlan::new( &source, GuestAddress(0x1000), - crate::block::BlockProfile::SystemModeSharedV1(specialization), - target, + &crate::Options::new( + crate::block::BlockProfile::new(Features::SYSTEM_MODE) + .with_checked_memory(specialization), + target, + ), ) .unwrap(); let required = plan.memory_requirements().unwrap(); @@ -417,8 +398,11 @@ mod tests { let plan = crate::block::CompilationPlan::new( &source, GuestAddress(pc), - crate::block::BlockProfile::SystemModeSharedV1(profile), - target, + &crate::Options::new( + crate::block::BlockProfile::new(Features::SYSTEM_MODE) + .with_checked_memory(profile), + target, + ), ) .unwrap(); let requirements = plan.memory_requirements().unwrap(); @@ -506,8 +490,10 @@ mod tests { let plan = crate::block::CompilationPlan::new( &source, GuestAddress(0x1000), - crate::block::BlockProfile::CheckedMemory(recipe), - TargetCpu::Baseline, + &crate::Options::new( + crate::block::BlockProfile::ORDINARY.with_checked_memory(recipe), + TargetCpu::Baseline, + ), ) .unwrap(); let requirements = plan diff --git a/crates/stela-compiler/src/block/memory/address.rs b/crates/stela-compiler/src/block/memory/address.rs index aa75c3fe3e..bf62aef6ba 100644 --- a/crates/stela-compiler/src/block/memory/address.rs +++ b/crates/stela-compiler/src/block/memory/address.rs @@ -159,8 +159,10 @@ mod tests { let legacy = CompilationPlan::new( &bytes, SOURCE_PC, - BlockProfile::CheckedMemory(original), - TargetCpu::Baseline, + &crate::Options::new( + BlockProfile::ORDINARY.with_checked_memory(original), + TargetCpu::Baseline, + ), ) .unwrap(); assert!( @@ -175,8 +177,10 @@ mod tests { let specialized = CompilationPlan::new( &bytes, SOURCE_PC, - BlockProfile::CheckedMemory(selected), - TargetCpu::Baseline, + &crate::Options::new( + BlockProfile::ORDINARY.with_checked_memory(selected), + TargetCpu::Baseline, + ), ) .unwrap(); let required = specialized @@ -208,8 +212,10 @@ mod tests { let plan = CompilationPlan::new( &bytes, SOURCE_PC, - BlockProfile::CheckedMemory(profile), - TargetCpu::Baseline, + &crate::Options::new( + BlockProfile::ORDINARY.with_checked_memory(profile), + TargetCpu::Baseline, + ), ) .unwrap(); let required = plan.memory_requirements().unwrap().required_address_checks; diff --git a/crates/stela-compiler/src/block/memory/pointer.rs b/crates/stela-compiler/src/block/memory/pointer.rs index 0e4dffe04b..bd64d19921 100644 --- a/crates/stela-compiler/src/block/memory/pointer.rs +++ b/crates/stela-compiler/src/block/memory/pointer.rs @@ -1,10 +1,11 @@ //! FEAT_CPA arithmetic within checked memory plans. +use crate::x86_64::asm::Code; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{Instruction, Operation}, context::{memory::MemoryRequirements, pointer::PointerArithmeticRequirement}, - extended::Decoded, + scalable_context::Decoded, }; use alloc::vec::Vec; @@ -79,7 +80,7 @@ impl CheckedOperation { pub(crate) fn emit( &self, - code: &mut Vec, + code: &mut Code, pc: GuestAddress, target: TargetCpu, fixups: &mut Vec<(GuestAddress, GuestAddress, usize)>, @@ -160,8 +161,10 @@ mod tests { let plan = CompilationPlan::new( &bytes, SOURCE_PC, - BlockProfile::CheckedMemory(profile(mode)), - TargetCpu::Baseline, + &crate::Options::new( + BlockProfile::ORDINARY.with_checked_memory(profile(mode)), + TargetCpu::Baseline, + ), ) .unwrap(); let requirements = plan.memory_requirements().unwrap(); @@ -202,8 +205,10 @@ mod tests { CompilationPlan::new( &bytes, SOURCE_PC, - BlockProfile::CheckedMemory(profile), - TargetCpu::Baseline + &crate::Options::new( + BlockProfile::ORDINARY.with_checked_memory(profile), + TargetCpu::Baseline + ) ) .is_err() ); @@ -214,8 +219,11 @@ mod tests { let plan = CompilationPlan::new( &bytes, SOURCE_PC, - BlockProfile::CheckedMemory(profile(EffectivePointerChecks::Unchecked)), - TargetCpu::Baseline, + &crate::Options::new( + BlockProfile::ORDINARY + .with_checked_memory(profile(EffectivePointerChecks::Unchecked)), + TargetCpu::Baseline, + ), ) .unwrap(); assert_eq!( @@ -251,13 +259,13 @@ mod tests { #[test] fn combined_profile_keeps_exact_raw_nop_provenance() { - let profile = BlockProfile::CheckedMemory(profile(EffectivePointerChecks::Addition)); + let profile = + BlockProfile::ORDINARY.with_checked_memory(profile(EffectivePointerChecks::Addition)); assert!( CompilationPlan::new( &source(&[NOP, ADDPT_X0_X1_X2, RET_X30]), SOURCE_PC, - profile, - TargetCpu::Baseline + &crate::Options::new(profile, TargetCpu::Baseline) ) .is_ok() ); @@ -265,8 +273,7 @@ mod tests { CompilationPlan::new( &source(&[LDP_X0_X0_X9_16, ADDPT_X0_X1_X2, RET_X30]), SOURCE_PC, - profile, - TargetCpu::Baseline + &crate::Options::new(profile, TargetCpu::Baseline) ) .is_err() ); diff --git a/crates/stela-compiler/src/block/profile.rs b/crates/stela-compiler/src/block/profile.rs index e1c15ea6b6..1c471bba88 100644 --- a/crates/stela-compiler/src/block/profile.rs +++ b/crates/stela-compiler/src/block/profile.rs @@ -143,7 +143,7 @@ mod tests { use super::*; use crate::{ GuestAddress, TargetCpu, - block::{BlockProfile, CheckedMemoryProfile, CompilationPlan}, + block::{BlockProfile, CheckedMemoryProfile, CompilationPlan, Features}, }; use alloc::vec; @@ -156,10 +156,14 @@ mod tests { CheckedMemoryProfile::SpAlignmentEnabled, CheckedMemoryProfile::SpAlignmentDisabled, ] { - let profile = BlockProfile::SystemModeSharedV1(memory); + let profile = BlockProfile::new(Features::SYSTEM_MODE).with_checked_memory(memory); let plan = || { - CompilationPlan::new(&source, GuestAddress(0x4000), profile, TargetCpu::Baseline) - .unwrap() + CompilationPlan::new( + &source, + GuestAddress(0x4000), + &crate::Options::new(profile, TargetCpu::Baseline), + ) + .unwrap() }; let baseline = plan().compile().unwrap(); let (actual, metadata) = plan().compile_profiled().unwrap(); @@ -224,8 +228,11 @@ mod tests { let (_, metadata) = CompilationPlan::new( &source, GuestAddress(0x4000), - BlockProfile::SystemModeSharedV1(CheckedMemoryProfile::SpAlignmentEnabled), - TargetCpu::Baseline, + &crate::Options::new( + BlockProfile::new(Features::SYSTEM_MODE) + .with_checked_memory(CheckedMemoryProfile::SpAlignmentEnabled), + TargetCpu::Baseline, + ), ) .unwrap() .compile_profiled() diff --git a/crates/stela-compiler/src/block/scalable.rs b/crates/stela-compiler/src/block/scalable.rs index f31e8a86d2..9a09d785f7 100644 --- a/crates/stela-compiler/src/block/scalable.rs +++ b/crates/stela-compiler/src/block/scalable.rs @@ -1,4 +1,5 @@ //! Scalable numerical instructions that exit to a runtime service. +use crate::aarch64::Unsupported; use crate::{ CompileError, GuestAddress, @@ -9,7 +10,7 @@ use crate::{ sme::{extrema_scale, fp_matrix, fp_vector, fp8_conversion, fp8_matrix}, sve::floating, }, - extended::ScalableProfile, + scalable_context::ScalableProfile, }; use alloc::format; @@ -215,8 +216,8 @@ pub fn decode_scalable_numerical_instruction( } else if let Some(operand) = extrema_scale::decode(word) { ScalableNumericalOperation::SmeExtremaScale(operand) } else if let Some(result) = floating::Operation::decode(word) { - let operand = - result.map_err(|()| CompileError("reserved scalable numerical encoding".into()))?; + let operand = result + .map_err(|Unsupported| CompileError("reserved scalable numerical encoding".into()))?; if !operand.requires_numerical_completion() { return Ok(None); } @@ -250,8 +251,6 @@ mod tests { use crate::{ TargetCpu, aarch64::scalable::{ScalableMode, VectorLength, profile::ScalableControls}, - block::BlockProfile, - extended::block::{ExtendedBlockProfile, compile_for_profile}, }; const PC: GuestAddress = GuestAddress(0x1000); @@ -342,10 +341,11 @@ mod tests { admit_scalable_numerical_instruction(decoded, profile, numerical).unwrap(); assert_eq!(admitted.word(), word); assert_eq!(admitted.next_pc(), GuestAddress(0x1004)); - let compiled = compile_for_profile( + let compiled = crate::testing::context_block( &word.to_le_bytes(), PC, - ExtendedBlockProfile::new(profile, BlockProfile::Ordinary, numerical), + profile, + numerical, TargetCpu::Baseline, ) .unwrap(); @@ -378,14 +378,11 @@ mod tests { .unwrap(); assert_eq!(admitted.word(), word, "{id}"); assert_eq!(admitted.next_pc(), GuestAddress(0x1004), "{id}"); - let compiled = compile_for_profile( + let compiled = crate::testing::context_block( &word.to_le_bytes(), PC, - ExtendedBlockProfile::new( - profile, - BlockProfile::Ordinary, - NumericalFeatures::default(), - ), + profile, + NumericalFeatures::default(), TargetCpu::Baseline, ) .unwrap(); diff --git a/crates/stela-compiler/src/block/system.rs b/crates/stela-compiler/src/block/system.rs index c83c81013d..6b63566a6c 100644 --- a/crates/stela-compiler/src/block/system.rs +++ b/crates/stela-compiler/src/block/system.rs @@ -2,6 +2,7 @@ //! //! Native blocks return only the instruction's PC and exit kind; the runtime //! re-decodes the source word before applying the effect. +use crate::aarch64::Unsupported; use crate::{ CompileError, GuestAddress, @@ -345,7 +346,7 @@ pub fn decode_system_mode_instruction( // Reserved sizes and opcodes stay with the ordinary decoder. match decoded { Ok(operand) => SystemOperation::Unprivileged(operand), - Err(()) => return Ok(None), + Err(Unsupported) => return Ok(None), } } else if let Some(access) = registers::decode_sys(word) { SystemOperation::Maintenance(access) diff --git a/crates/stela-compiler/src/block/thread.rs b/crates/stela-compiler/src/block/thread.rs index 3732dd7f9a..0ccc96b91e 100644 --- a/crates/stela-compiler/src/block/thread.rs +++ b/crates/stela-compiler/src/block/thread.rs @@ -66,7 +66,7 @@ mod tests { fn shared_parser_requires_thread_profile_and_stops_before_unknown_successor() { use crate::{ Lifter, - block::{self, BlockProfile, SuccessorKind}, + block::{self, BlockProfile, Features, SuccessorKind}, }; use alloc::collections::BTreeSet; let base = GuestAddress(0x1000); @@ -77,12 +77,16 @@ mod tests { .flat_map(u32::to_le_bytes) .collect(); let profiles = [ - BlockProfile::Ordinary, - BlockProfile::AppleArm64eSoftwarePauthV1, - BlockProfile::AppleArm64eSoftwarePauthClockV1, - BlockProfile::DarwinArm64ThreadV1, - BlockProfile::AppleArm64eSoftwarePauthThreadV1, - BlockProfile::AppleArm64eSoftwarePauthClockThreadV1, + BlockProfile::ORDINARY, + BlockProfile::new(Features::POINTER_AUTHENTICATION), + BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)), + BlockProfile::new(Features::THREAD_REGISTERS.union(Features::AMX)), + BlockProfile::new( + Features::POINTER_AUTHENTICATION + .union(Features::THREAD_REGISTERS) + .union(Features::AMX), + ), + BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)), ]; let mut abis = BTreeSet::new(); for profile in profiles { @@ -91,8 +95,8 @@ mod tests { "cache ABI identities must be distinct" ); let analyzed = block::analyze_with_profile(&source, base, profile); - let compiled = block::compile_with_profile(&source, base, profile); - if !profile.supports_thread_registers() { + let compiled = crate::testing::block_with(&source, base, profile); + if !profile.has(Features::THREAD_REGISTERS) { assert_eq!(analyzed.unwrap_err().pc.0, base.0 + INSTRUCTION_BYTES); assert!(compiled.is_err()); continue; diff --git a/crates/stela-compiler/src/context.rs b/crates/stela-compiler/src/context.rs index ef5c6cc4eb..1e82f4537f 100644 --- a/crates/stela-compiler/src/context.rs +++ b/crates/stela-compiler/src/context.rs @@ -1,4 +1,4 @@ -//! Execution context passed to native code using the extended ABI. +//! Execution context passed to native code using the context ABI. pub mod memory; pub mod pointer; @@ -6,9 +6,6 @@ use core::ffi::c_void; pub const EXECUTION_CONTEXT_VERSION: u32 = 1; pub const EXECUTION_CONTEXT_BYTES: u32 = 32; -pub const CONTEXT_LEAF_ABI: &str = "x86_64-sysv-guest-state-v3-context-memory-v2-direct-ram"; -pub const CONTEXT_BLOCK_ABI: &str = - "x86_64-sysv-guest-state-v3-context-memory-v2-block-exit-direct-ram"; pub const SCALABLE_STATE_VIEW_BYTES: usize = 72; pub const EXECUTION_CONTEXT_MEMORY_OFFSET: u32 = 8; pub const EXECUTION_CONTEXT_SCALABLE_OFFSET: u32 = 16; diff --git a/crates/stela-compiler/src/extended/block.rs b/crates/stela-compiler/src/extended/block.rs deleted file mode 100644 index 998b5a414e..0000000000 --- a/crates/stela-compiler/src/extended/block.rs +++ /dev/null @@ -1,486 +0,0 @@ -//! Blocks compiled with an execution context. A service exit returns the PC of -//! the instruction still to execute. - -use super::{Decoded, INSTRUCTION_BYTES, ScalableProfile, context_wrapper, decode}; -use crate::{ - CompileError, GuestAddress, Lifter, NativeBlock, TargetCpu, - aarch64::{Decoder, Operation, floating::features::NumericalFeatures}, - block::{ - self, BlockProfile, CompiledBlock, ExitKind, MAX_BLOCK_INSTRUCTIONS, - scalable::{ - AdmittedScalableNumericalInstruction, ScalableNumericalOperation, - admit_scalable_numerical_instruction, decode_scalable_numerical_instruction, - }, - }, - context::memory::MemoryRequirements, - x86_64, -}; -use alloc::format; -use alloc::string::ToString; -use alloc::vec::Vec; - -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const MOV_EDX_IMMEDIATE: u8 = 0xba; -const RETURN: u8 = 0xc3; - -/// Guest services and numerical feature availability remain distinct from host -/// capabilities and the set of instruction mappings currently implemented. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ExtendedBlockProfile { - scalable: ScalableProfile, - services: BlockProfile, - numerical_features: NumericalFeatures, -} - -impl ExtendedBlockProfile { - pub const fn new( - scalable: ScalableProfile, - services: BlockProfile, - numerical_features: NumericalFeatures, - ) -> Self { - Self { - scalable, - services, - numerical_features, - } - } - - pub const fn scalable(self) -> ScalableProfile { - self.scalable - } - pub const fn services(self) -> BlockProfile { - self.services - } - pub const fn numerical_features(self) -> NumericalFeatures { - self.numerical_features - } -} - -enum Terminal { - Shared(CompiledBlock), - Numerical(AdmittedScalableNumericalInstruction), -} - -/// Existing Ordinary traps remain ordinary boundaries. Other typed services -/// cannot acquire permission from a successful decode or memory-effect result. -fn reject_unavailable_service(pc: GuestAddress, word: u32) -> Result<(), CompileError> { - if block::decode_trap(pc, word)?.is_some() { - return Ok(()); - } - if block::decode_system_instruction(pc, word)?.is_some() - || block::decode_pointer_authentication(pc, word)?.is_some() - || block::decode_clock_instruction(pc, word)?.is_some() - || block::decode_thread_register_instruction(pc, word)?.is_some() - || crate::amx::decode(pc, word)?.is_some() - { - return Err(CompileError(format!( - "context block service is not integrated at {:#x}", - pc.0 - ))); - } - Ok(()) -} - -fn shared_terminal( - bytes: &[u8; INSTRUCTION_BYTES], - pc: GuestAddress, - profile: BlockProfile, - target: TargetCpu, -) -> Result, CompileError> { - if let Ok(instruction) = Decoder.lift(pc, u32::from_le_bytes(*bytes)) - && matches!(instruction.operation, Operation::FloatingPoint(_)) - { - return Ok(None); - } - let analysis = block::analyze_with_profile(bytes, pc, profile) - .map_err(|error| CompileError(error.to_string()))?; - // The ordinary scalar numerical boundary is deliberately excluded until - // its low-V/upper-Z effects have been integrated in context mode. - let permitted = analysis.trap.is_some() - || analysis.dynamic_edge.is_some() - || (analysis.terminator_pc.is_some() && !analysis.static_successors.is_empty()); - if permitted { - block::compile_for_target(bytes, pc, profile, target).map(Some) - } else { - Ok(None) - } -} - -fn is_transfer(operation: &Operation) -> bool { - matches!( - operation, - Operation::Branch { .. } - | Operation::BranchCondition { .. } - | Operation::BranchZero { .. } - | Operation::BranchBit { .. } - | Operation::Return - ) -} - -/// Compile a block prefix. Direct RAM, AdvSIMD/FP, mode writes and MOVPRFX are -/// refused as in the context leaf compiler. `NumericalFeatures` must match the -/// guest identity the runtime uses for completion. -pub fn compile_for_profile( - source: &[u8], - base: GuestAddress, - profile: ExtendedBlockProfile, - target: TargetCpu, -) -> Result { - if profile.services != BlockProfile::Ordinary { - return Err(CompileError( - "context block services are not integrated".into(), - )); - } - if source.is_empty() - || !source.len().is_multiple_of(INSTRUCTION_BYTES) - || !base.0.is_multiple_of(INSTRUCTION_BYTES as u64) - || source.len() / INSTRUCTION_BYTES > MAX_BLOCK_INSTRUCTIONS - { - return Err(CompileError( - "context block input must be aligned, nonempty and bounded".into(), - )); - } - let mut instructions = Vec::new(); - let mut terminal = None; - let mut next_pc = base; - let mut source_bytes = 0; - for bytes in source.as_chunks::().0 { - let pc = next_pc; - next_pc = GuestAddress( - pc.0.checked_add(INSTRUCTION_BYTES as u64) - .ok_or_else(|| CompileError("context block guest address overflow".into()))?, - ); - source_bytes += INSTRUCTION_BYTES; - let word = u32::from_le_bytes(*bytes); - reject_unavailable_service(pc, word)?; - if let Some(numerical) = decode_scalable_numerical_instruction(pc, word)? { - let admitted = admit_scalable_numerical_instruction( - numerical, - profile.scalable, - profile.numerical_features, - )?; - terminal = Some(Terminal::Numerical(admitted)); - break; - } - match decode(pc, word, profile.scalable, target) { - Ok(instruction) - if instruction.memory_requirements() != MemoryRequirements::default() => - { - return Err(CompileError(format!( - "context block memory entry is not integrated at {:#x}", - pc.0 - ))); - } - Ok(Decoded::Ordinary(instruction)) if is_transfer(&instruction.operation) => { - terminal = - shared_terminal(bytes, pc, profile.services, target)?.map(Terminal::Shared); - debug_assert!( - terminal.is_some(), - "ordinary transfer has a shared boundary" - ); - break; - } - Ok(instruction) => instructions.push((pc, instruction)), - Err(error) => { - if let Some(shared) = shared_terminal(bytes, pc, profile.services, target)? { - terminal = Some(Terminal::Shared(shared)); - break; - } - return Err(error); - } - } - } - let mut code = context_wrapper(); - let mut source_map = Vec::with_capacity(instructions.len() + usize::from(terminal.is_some())); - let mut fixups = Vec::new(); - for (pc, instruction) in instructions { - source_map.push((pc, code.len())); - super::emit_decoded( - &mut code, - pc, - instruction, - profile.scalable, - target, - &mut fixups, - )?; - } - debug_assert!(fixups.is_empty(), "context block prefix cannot transfer"); - match terminal { - Some(Terminal::Shared(shared)) => { - let offset = code.len(); - source_map.extend( - shared - .native - .source_map - .into_iter() - .map(|(pc, at)| (pc, at + offset)), - ); - code.extend(shared.native.x86_64_code); - } - Some(Terminal::Numerical(instruction)) => { - let pc = instruction.instruction_pc(); - source_map.push((pc, code.len())); - let emitted = match *instruction.operation() { - ScalableNumericalOperation::Sve(operation) => x86_64::sve::floating::emit( - &mut code, - instruction.word(), - operation, - profile.scalable.vector_length(), - profile.numerical_features, - pc, - target, - )?, - ScalableNumericalOperation::SmeExtremaScale(operand) => { - x86_64::sme::extrema_scale::emit( - &mut code, - operand, - profile.scalable.vector_length(), - profile.numerical_features, - pc, - target, - )? - } - ScalableNumericalOperation::SmeVector(_) - | ScalableNumericalOperation::SmeMatrix(_) - | ScalableNumericalOperation::FixedFp8Conversion(_) - | ScalableNumericalOperation::SmeFp8Conversion(_) - | ScalableNumericalOperation::SmeFp8Matrix(_) => false, - }; - if emitted { - // The guarded family mapping owns the exact-PC cold exit. - // Only its committed fast path reaches the continuation. - code.extend( - x86_64::block::emit_for_target( - &[], - None, - instruction.next_pc(), - target, - x86_64::MemoryChecks::DEFAULT, - ) - .x86_64_code, - ); - } else { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(pc.0.to_le_bytes()); - code.push(MOV_EDX_IMMEDIATE); - code.extend((ExitKind::ScalableNumerical as u32).to_le_bytes()); - code.push(RETURN); - } - } - None => code.extend( - x86_64::block::emit_for_target( - &[], - None, - next_pc, - target, - x86_64::MemoryChecks::DEFAULT, - ) - .x86_64_code, - ), - } - Ok(CompiledBlock { - native: NativeBlock { - x86_64_code: code, - source_map, - }, - source_bytes, - direct_exits: Vec::new(), - fault_recovery: Vec::new(), - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::aarch64::scalable::{ScalableMode, VectorLength}; - use alloc::format; - use alloc::string::ToString; - use alloc::vec; - use alloc::vec::Vec; - - const BASE: GuestAddress = GuestAddress(0x1000); - const ADD_X5_ONE: u32 = 0x9100_04a5; - const FADD_Z0_SINGLE: u32 = 0x6580_8020; - const SVC: u32 = 0xd400_0001; - const BRK: u32 = 0xd420_0000; - const ERET: u32 = 0xd69f_03e0; - const IRG: u32 = 0x9ac0_1000; - const PACIBSP: u32 = 0xd503_237f; - const CNTVCT: u32 = 0xd53b_e040; - const TPIDRRO: u32 = 0xd53b_d060; - const RET: u32 = 0xd65f_03c0; - const PACGA_X1_X2_X3: u32 = 0x9ac3_3041; - const LDRAA_X1_X2: u32 = 0xf820_0441; - const LDRAB_X1_X2: u32 = 0xf8a0_0441; - const SERVICE_WORDS: &[u32] = &[ - ERET, - IRG, - PACIBSP, - CNTVCT, - TPIDRRO, - PACGA_X1_X2_X3, - LDRAA_X1_X2, - LDRAB_X1_X2, - ]; - - fn source(words: &[u32]) -> Vec { - words.iter().flat_map(|word| word.to_le_bytes()).collect() - } - - fn profile(services: BlockProfile) -> ExtendedBlockProfile { - ExtendedBlockProfile::new( - ScalableProfile::new( - VectorLength::from_bytes(16).unwrap(), - ScalableMode::new(true, false), - ), - services, - NumericalFeatures::default(), - ) - } - - #[test] - fn context_entry_declines_every_nonordinary_service_profile() { - for services in [ - BlockProfile::SystemV1, - BlockProfile::AppleArm64eSoftwarePauthV1, - BlockProfile::AppleArm64eSoftwarePauthClockV1, - BlockProfile::DarwinArm64ThreadV1, - BlockProfile::AppleArm64eSoftwarePauthThreadV1, - BlockProfile::AppleArm64eSoftwarePauthClockThreadV1, - ] { - let error = compile_for_profile( - &source(&[RET]), - BASE, - profile(services), - TargetCpu::Baseline, - ) - .unwrap_err(); - assert!(error.to_string().contains("services are not integrated")); - } - } - - #[test] - fn ordinary_trap_extent_stays_distinct_from_forbidden_system_completion() { - for trap in [SVC, BRK] { - let compiled = compile_for_profile( - &source(&[ADD_X5_ONE, trap, ERET]), - BASE, - profile(BlockProfile::Ordinary), - TargetCpu::Baseline, - ) - .unwrap(); - assert_eq!(compiled.source_bytes, 2 * INSTRUCTION_BYTES); - assert_eq!( - compiled - .native - .source_map - .iter() - .map(|row| row.0) - .collect::>(), - [BASE, GuestAddress(BASE.0 + INSTRUCTION_BYTES as u64)] - ); - } - for &service in SERVICE_WORDS { - for words in [vec![service, RET], vec![ADD_X5_ONE, service, RET]] { - let offset = if words[0] == ADD_X5_ONE { - INSTRUCTION_BYTES - } else { - 0 - }; - let error = compile_for_profile( - &source(&words), - BASE, - profile(BlockProfile::Ordinary), - TargetCpu::Baseline, - ) - .unwrap_err(); - assert!(error.to_string().contains("service is not integrated")); - assert!( - error - .to_string() - .contains(&format!("{:#x}", BASE.0 + offset as u64)) - ); - } - } - } - - #[test] - fn unconsumed_service_after_numerical_boundary_does_not_expand_extent() { - for &service in SERVICE_WORDS { - let compiled = compile_for_profile( - &source(&[ADD_X5_ONE, FADD_Z0_SINGLE, service]), - BASE, - profile(BlockProfile::Ordinary), - TargetCpu::Baseline, - ) - .unwrap(); - assert_eq!(compiled.source_bytes, 2 * INSTRUCTION_BYTES); - assert_eq!(compiled.native.source_map.len(), 2); - assert_eq!( - compiled.native.source_map[1].0, - GuestAddress(BASE.0 + INSTRUCTION_BYTES as u64) - ); - } - } - - #[test] - fn strict_ordinary_ram_atomic_legacy_fp_and_prefix_declines_stay_explicit() { - const LDR_X0_X1: u32 = 0xf940_0020; - const CAS_X0_X1_X2: u32 = 0xc8a0_7c41; - const FADD_S0_S1_S2: u32 = 0x1e22_2820; - const MOVPRFX_Z0_Z1: u32 = 0x0420_bc20; - for word in [LDR_X0_X1, CAS_X0_X1_X2, FADD_S0_S1_S2, MOVPRFX_Z0_Z1] { - assert!( - compile_for_profile( - &source(&[ADD_X5_ONE, word, RET]), - BASE, - profile(BlockProfile::Ordinary), - TargetCpu::Baseline, - ) - .is_err() - ); - } - } - #[test] - fn movprfx_pairs_remain_leaf_only_and_numerical_followers_decline() { - const UNPREDICATED_PREFIX: u32 = 0x0420_bc20; - const ZEROING_PREFIX: u32 = 0x0410_2020; - const MERGING_PREFIX: u32 = 0x0411_2020; - const AND_DESTRUCTIVE: u32 = 0x041a_0040; - let block_profile = profile(BlockProfile::Ordinary); - for prefix in [UNPREDICATED_PREFIX, ZEROING_PREFIX, MERGING_PREFIX] { - let bytes = source(&[prefix, AND_DESTRUCTIVE, RET]); - let leaf = crate::extended::compile_for_profile( - &bytes, - BASE, - block_profile.scalable(), - TargetCpu::Baseline, - ) - .unwrap(); - assert_eq!( - leaf.source_map.iter().map(|row| row.0).collect::>(), - [ - BASE, - GuestAddress(BASE.0 + INSTRUCTION_BYTES as u64), - GuestAddress(BASE.0 + 2 * INSTRUCTION_BYTES as u64), - ] - ); - let error = - compile_for_profile(&bytes, BASE, block_profile, TargetCpu::Baseline).unwrap_err(); - assert!(error.to_string().contains(&format!("{:#x}", BASE.0))); - } - let error = crate::extended::compile_for_profile( - &source(&[UNPREDICATED_PREFIX, FADD_Z0_SINGLE, RET]), - BASE, - block_profile.scalable(), - TargetCpu::Baseline, - ) - .unwrap_err(); - assert!(error.to_string().contains("unsupported follower")); - assert!( - error - .to_string() - .contains(&format!("{:#x}", BASE.0 + INSTRUCTION_BYTES as u64)) - ); - } -} diff --git a/crates/stela-compiler/src/lib.rs b/crates/stela-compiler/src/lib.rs index 2fff729b35..03527e5967 100644 --- a/crates/stela-compiler/src/lib.rs +++ b/crates/stela-compiler/src/lib.rs @@ -8,19 +8,20 @@ extern crate std; use alloc::format; use alloc::string::String; -use alloc::vec; use alloc::vec::Vec; pub mod aarch64; pub mod amx; pub mod block; pub mod context; -pub mod extended; +pub mod scalable_context; mod state; mod target; +#[cfg(test)] +mod testing; pub mod wkdm; pub mod x86_64; -pub use state::{GuestState, NATIVE_ABI}; +pub use state::GuestState; pub use target::TargetCpu; use serde::{Deserialize, Serialize}; @@ -84,44 +85,138 @@ impl core::fmt::Display for CompileError { } impl core::error::Error for CompileError {} -/// Compile one raw ARM64 leaf region ending in RET X30. -/// Input addresses are retained in the output map. No Mach-O loading, external -/// calls, PAC, privileged operations, or arbitrary RET targets. -pub fn compile(code: &[u8], base: GuestAddress) -> Result { - compile_for_target(code, base, TargetCpu::Baseline) -} -pub fn compile_for_target( - code: &[u8], - base: GuestAddress, +/// What [`compile`] translates for: the guest services and memory checks of a +/// [`block::BlockProfile`], the host's [`TargetCpu`], and the guest's scalable +/// and numerical specialization for the context ABI. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Options { + profile: block::BlockProfile, target: TargetCpu, -) -> Result { - if code.is_empty() || !code.len().is_multiple_of(4) || !base.0.is_multiple_of(4) { - return Err(CompileError( - "input and guest base must be nonempty/aligned to 4 bytes".into(), - )); + scalable: Option, + numerical: aarch64::floating::features::NumericalFeatures, + checks: x86_64::MemoryChecks, + native: x86_64::NativeSystem, +} + +impl Options { + pub const fn new(profile: block::BlockProfile, target: TargetCpu) -> Self { + Self { + profile, + target, + scalable: None, + numerical: aarch64::floating::features::NumericalFeatures::new(false, false, false), + checks: x86_64::MemoryChecks::DEFAULT, + native: x86_64::NativeSystem::NONE, + } } - let mut instructions = vec![]; - for (index, bytes) in code.as_chunks::<4>().0.iter().enumerate() { - let pc = GuestAddress( - base.0 - .checked_add((index as u64) * 4) - .ok_or_else(|| CompileError("guest address overflow".into()))?, - ); - let encoding = u32::from_le_bytes(*bytes); - let instruction = aarch64::Decoder - .lift(pc, encoding) - .map_err(|e| CompileError(format!("unsupported ARM64 semantics: {e:?}")))?; - instructions.push(instruction); + /// The guest's scalable specialization, which [`block::Features::CONTEXT`] + /// requires. + pub const fn with_scalable(self, scalable: scalable_context::ScalableProfile) -> Self { + Self { + scalable: Some(scalable), + ..self + } } - if !matches!( - instructions.last().unwrap().operation, - aarch64::Operation::Return - ) { - return Err(CompileError("leaf region must end in RET X30".into())); + /// The numerical features a context block's numerical completions assume; + /// they must match the guest identity the runtime completes with. + pub const fn with_numerical_features( + self, + numerical: aarch64::floating::features::NumericalFeatures, + ) -> Self { + Self { numerical, ..self } } - x86_64::Emitter - .emit_for_target(&instructions, target) - .map_err(|e| CompileError(format!("x86 emission failed: {e:?}"))) + /// Emit the memory checks of the regime's SCTLR_ELx: the system-mode engine + /// compiles separate blocks for SA (or SA0 at EL0) clear, where an access + /// through a misaligned SP proceeds; for A set, where any access not + /// aligned to its elements faults; and for nAA set, where an ordered access + /// may cross its 16-byte granule. Only the direct system-mode profile admits + /// checks other than [`x86_64::MemoryChecks::DEFAULT`], and a host without + /// the capability an unchecked SP then needs refuses. + pub const fn with_memory_checks(self, checks: x86_64::MemoryChecks) -> Self { + Self { checks, ..self } + } + /// Complete a terminal DC ZVA or DC clean operation natively + /// ([`x86_64::NativeSystem`]): the system-mode engine compiles separate + /// blocks for the contexts where those operations neither trap nor are + /// UNDEFINED. Only the direct system-mode profile admits them. + pub const fn with_native_system(self, native: x86_64::NativeSystem) -> Self { + Self { native, ..self } + } + + pub const fn profile(&self) -> block::BlockProfile { + self.profile + } + pub const fn target(&self) -> TargetCpu { + self.target + } + pub const fn scalable(&self) -> Option { + self.scalable + } + pub const fn numerical_features(&self) -> aarch64::floating::features::NumericalFeatures { + self.numerical + } + pub const fn memory_checks(&self) -> x86_64::MemoryChecks { + self.checks + } + pub const fn native_system(&self) -> x86_64::NativeSystem { + self.native + } + + /// Refuse options no emitter implements. + pub fn validate(&self) -> Result<(), CompileError> { + use block::Features; + self.profile.validate()?; + let context = self.profile.has(Features::CONTEXT); + if context != self.scalable.is_some() { + return Err(CompileError(format!( + "{:?} {} a scalable specialization", + self.profile, + if context { "requires" } else { "takes no" } + ))); + } + let system_mode = self.profile == block::BlockProfile::new(Features::SYSTEM_MODE); + if self.checks != x86_64::MemoryChecks::DEFAULT && !system_mode { + return Err(CompileError(format!( + "{:?} makes only the default memory checks", + self.profile + ))); + } + if let Some(bytes) = self.native.zero_block { + use x86_64::zero_block::{MAX_BYTES, MIN_BYTES}; + if !system_mode { + return Err(CompileError(format!( + "{:?} keeps DC ZVA's System exit", + self.profile + ))); + } + if !bytes.is_power_of_two() || !(MIN_BYTES..=MAX_BYTES).contains(&bytes) { + return Err(CompileError(format!( + "a {bytes}-byte DC ZVA block is not a DCZID_EL0.BS size" + ))); + } + } + if !self.native.cache_clean.is_empty() && !system_mode { + return Err(CompileError(format!( + "{:?} keeps the DC clean operations' System exit", + self.profile + ))); + } + Ok(()) + } +} + +/// Translate the guest code at `source`, whose first instruction is at +/// `base`, for `options`: one validated decode, then the emitters its +/// profile's features select. A block ends at its first transfer, trap or +/// runtime exit, or at the input boundary, and bytes after it are unconsumed; +/// a [`block::Features::LEAF`] function translates the whole input, which ends +/// in RET X30. Unknown semantics are compile errors. +pub fn compile( + source: &[u8], + base: GuestAddress, + options: &Options, +) -> Result { + block::CompilationPlan::new(source, base, options)?.compile() } pub trait Backend { @@ -147,8 +242,49 @@ pub mod platform { #[cfg(test)] mod tests { use super::*; + use crate::x86_64::asm::Code; use alloc::vec; use alloc::vec::Vec; + + #[test] + fn options_without_an_emitter_are_refused() { + use aarch64::scalable::{ScalableMode, VectorLength}; + use block::{BlockProfile, Features}; + let scalable = scalable_context::ScalableProfile::new( + VectorLength::from_bytes(16).unwrap(), + ScalableMode::new(true, false), + ); + let options = |features| Options::new(BlockProfile::new(features), TargetCpu::Baseline); + let unaligned = x86_64::MemoryChecks { + stack_alignment: false, + ..x86_64::MemoryChecks::DEFAULT + }; + let zero = |bytes| x86_64::NativeSystem { + zero_block: Some(bytes), + ..x86_64::NativeSystem::NONE + }; + for valid in [ + options(Features::NONE), + options(Features::LEAF), + options(Features::CONTEXT).with_scalable(scalable), + options(Features::SYSTEM_MODE).with_memory_checks(unaligned), + options(Features::SYSTEM_MODE).with_native_system(zero(64)), + ] { + assert_eq!(valid.validate(), Ok(()), "{valid:?}"); + } + for invalid in [ + options(Features::CONTEXT), + options(Features::NONE).with_scalable(scalable), + options(Features::NONE).with_memory_checks(unaligned), + options(Features::NONE).with_native_system(zero(64)), + options(Features::SYSTEM_MODE).with_native_system(zero(48)), + options(Features::CLOCK), + ] { + assert!(invalid.validate().is_err(), "{invalid:?}"); + assert!(compile(&0xd65f_03c0_u32.to_le_bytes(), GuestAddress(0), &invalid).is_err()); + } + } + #[test] fn polynomial64_lowering_requires_independent_pclmul_and_selects_original_halves() { use x86_64::isa::SimdOpcode; @@ -157,7 +293,7 @@ mod tests { assert!(!TargetCpu::Sse42.supports(opcode.requires())); assert!( std::panic::catch_unwind(|| { - opcode.register(&mut Vec::new(), 0, 1, TargetCpu::Sse42); + opcode.register(&mut Code::new(), 0, 1, TargetCpu::Sse42); }) .is_err() ); @@ -166,13 +302,14 @@ mod tests { .into_iter() .flat_map(u32::to_le_bytes) .collect(); - let baseline = compile(&source, GuestAddress(0x1000)).unwrap(); + let baseline = crate::testing::leaf(&source, GuestAddress(0x1000)).unwrap(); let sse42 = - compile_for_target(&source, GuestAddress(0x1000), TargetCpu::Sse42).unwrap(); + crate::testing::leaf_for(&source, GuestAddress(0x1000), TargetCpu::Sse42).unwrap(); assert_eq!(baseline.x86_64_code, sse42.x86_64_code); let pclmul = - compile_for_target(&source, GuestAddress(0x1000), TargetCpu::Pclmulqdq).unwrap(); - let combined = compile_for_target( + crate::testing::leaf_for(&source, GuestAddress(0x1000), TargetCpu::Pclmulqdq) + .unwrap(); + let combined = crate::testing::leaf_for( &source, GuestAddress(0x1000), TargetCpu::Sse42.with_pclmulqdq(), @@ -195,8 +332,10 @@ mod tests { .flat_map(u32::to_le_bytes) .collect(); assert_eq!( - compile(&source, GuestAddress(0x1000)).unwrap().x86_64_code, - compile_for_target(&source, GuestAddress(0x1000), TargetCpu::Pclmulqdq) + crate::testing::leaf(&source, GuestAddress(0x1000)) + .unwrap() + .x86_64_code, + crate::testing::leaf_for(&source, GuestAddress(0x1000), TargetCpu::Pclmulqdq) .unwrap() .x86_64_code, ); @@ -210,16 +349,18 @@ mod tests { .flat_map(|word| word.to_le_bytes()) .collect(); assert!( - compile(&source, GuestAddress(0)) + crate::testing::leaf(&source, GuestAddress(0)) .unwrap_err() .0 .contains("HostCapabilityRequired") ); - assert!(compile_for_target(&source, GuestAddress(0), TargetCpu::AtomicLoad16).is_ok()); - let blocked = block::compile(&source, GuestAddress(0)).unwrap_err(); + assert!( + crate::testing::leaf_for(&source, GuestAddress(0), TargetCpu::AtomicLoad16).is_ok() + ); + let blocked = crate::testing::block(&source, GuestAddress(0)).unwrap_err(); assert!(blocked.0.contains("HostCapabilityRequired")); assert!( - block::compile_for_target( + crate::testing::block_for( &source, GuestAddress(0), block::BlockProfile::default(), @@ -233,7 +374,7 @@ mod tests { .iter() .flat_map(|word| word.to_le_bytes()) .collect(); - assert!(compile(&source, GuestAddress(0)).is_ok()); + assert!(crate::testing::leaf(&source, GuestAddress(0)).is_ok()); } } @@ -254,8 +395,8 @@ mod tests { TargetCpu::Cx16, ] { let permitted = !requires_cx16 || target.supports(TargetCpu::Cx16); - let leaf = compile_for_target(&source, GuestAddress(0), target); - let block = block::compile_for_target( + let leaf = crate::testing::leaf_for(&source, GuestAddress(0), target); + let block = crate::testing::block_for( &source, GuestAddress(0), block::BlockProfile::default(), @@ -290,14 +431,14 @@ mod tests { vec![0xd65f0000], ] { let bytes: Vec<_> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - assert!(compile(&bytes, GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&bytes, GuestAddress(0)).is_err()); } - assert!(compile(&[0, 0, 0], GuestAddress(0)).is_err()); - assert!(compile(&0xd65f03c0u32.to_le_bytes(), GuestAddress(1)).is_err()); + assert!(crate::testing::leaf(&[0, 0, 0], GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&0xd65f03c0u32.to_le_bytes(), GuestAddress(1)).is_err()); let code: Vec<_> = [0xd503201fu32, 0xd65f03c0] .iter() .flat_map(|w| w.to_le_bytes()) .collect(); - assert!(compile(&code, GuestAddress(u64::MAX - 3)).is_err()); + assert!(crate::testing::leaf(&code, GuestAddress(u64::MAX - 3)).is_err()); } } diff --git a/crates/stela-compiler/src/extended.rs b/crates/stela-compiler/src/scalable_context.rs similarity index 91% rename from crates/stela-compiler/src/extended.rs rename to crates/stela-compiler/src/scalable_context.rs index da2fcd9091..ea96e8124b 100644 --- a/crates/stela-compiler/src/extended.rs +++ b/crates/stela-compiler/src/scalable_context.rs @@ -1,4 +1,5 @@ //! Leaf compilation with an execution context and a scalable specialization. +use crate::x86_64::asm::Code; mod admission; pub mod block; @@ -28,28 +29,26 @@ use alloc::{collections::BTreeMap, format, vec, vec::Vec}; pub const PROFILE_ID: &str = "apple-sme2-streaming-v1"; pub const DECLARED_PROFILE_ID: &str = "sme-streaming-v2"; const INSTRUCTION_BYTES: usize = size_of::(); -const PUSH_R15: &[u8] = &[0x41, 0x57]; -const MOV_R15_RSI: &[u8] = &[0x49, 0x89, 0xf7]; -const CALL_REL32: u8 = 0xe8; -const POP_R15: &[u8] = &[0x41, 0x5f]; -const RET: u8 = 0xc3; -const CALL_BYTES: usize = 1 + size_of::(); -const CALL_END: usize = PUSH_R15.len() + MOV_R15_RSI.len() + CALL_BYTES; -pub const CONTEXT_WRAPPER_BYTES: usize = CALL_END + POP_R15.len() + 1; +/// `push r15; mov r15, rsi; call body; pop r15; ret`: the context ABI's +/// entry, which keeps the context pointer in R15 across the body. +pub const CONTEXT_WRAPPER_BYTES: usize = 13; -pub(crate) fn context_wrapper() -> Vec { - let mut code = Vec::with_capacity(CONTEXT_WRAPPER_BYTES); - code.extend(PUSH_R15); - code.extend(MOV_R15_RSI); - code.push(CALL_REL32); - code.extend(((CONTEXT_WRAPPER_BYTES - CALL_END) as i32).to_le_bytes()); - code.extend(POP_R15); - code.push(RET); +pub(crate) fn context_wrapper() -> Code { + use x86_64::asm::{Gpr, Size}; + let mut code = Code::new(); + let mut asm = code.asm(); + asm.push(Gpr::R15); + asm.mov(Size::Qword, Gpr::R15, Gpr::Rsi); + let body = asm.call(); + asm.pop(Gpr::R15); + asm.ret(); + asm.bind(body); + debug_assert_eq!(code.len(), CONTEXT_WRAPPER_BYTES); code } fn emit_decoded( - code: &mut Vec, + code: &mut Code, pc: GuestAddress, instruction: Decoded, profile: ScalableProfile, @@ -303,118 +302,116 @@ fn decode_leaf( Ok(instructions) } -/// Derive the whole body's service requirements with the same parser used to -/// compile it. Leaves with no memory access return empty requirements. -pub fn memory_requirements( - source: &[u8], - base: GuestAddress, - profile: ScalableProfile, - target: TargetCpu, -) -> Result { - leaf_memory_requirements(&decode_leaf(source, base, profile, target)?) -} - -fn leaf_memory_requirements( - instructions: &[DecodedLeafInstruction], -) -> Result { - instructions - .iter() - .try_fold(MemoryRequirements::default(), |requirements, decoded| { - requirements - .merge(decoded.instruction.memory_requirements()) - .ok_or_else(|| { - CompileError(format!( - "conflicting memory control requirements at {:#x}", - decoded.pc.0 - )) - }) - }) -} - -/// All outputs derive from one validated source vector. No caller-supplied -/// execution metadata or service requirements are accepted. -pub struct PreparedLeafCode { - pub native: NativeBlock, - pub memory_requirements: MemoryRequirements, - pub execution_requirements: ScalableExecutionRequirements, -} - -pub fn prepare_leaf( - source: &[u8], - base: GuestAddress, - profile: ScalableProfile, - target: TargetCpu, -) -> Result { - let instructions = decode_leaf(source, base, profile, target)?; - let memory_requirements = leaf_memory_requirements(&instructions)?; - let execution_requirements = ScalableExecutionRequirements::new( - instructions - .iter() - .map(|decoded| { - InstructionExecutionRequirements::new( - decoded.pc, - decoded.feature_clauses.clone(), - decoded.instruction.execution_access_requirements(), - decoded.instruction.guest_memory_quantity(), - ) - }) - .collect(), - ); - let native = emit_leaf(instructions, profile, target)?; - Ok(PreparedLeafCode { - native, - memory_requirements, - execution_requirements, - }) -} - -/// Compile a two-argument context leaf ending in RET X30. The runtime validates -/// this profile against its state before calling it. -pub fn compile_for_profile( - source: &[u8], - base: GuestAddress, - profile: ScalableProfile, - target: TargetCpu, -) -> Result { - emit_leaf(decode_leaf(source, base, profile, target)?, profile, target) -} - -fn emit_leaf( +/// A validated context leaf: one decode of the whole body, from which its +/// service and execution requirements and its code all derive. No +/// caller-supplied execution metadata or service requirements are accepted. +pub struct Leaf { instructions: Vec, + memory_requirements: MemoryRequirements, profile: ScalableProfile, target: TargetCpu, -) -> Result { - let mut code = context_wrapper(); - let mut source_map = Vec::with_capacity(instructions.len()); - let mut fixups = Vec::new(); - for DecodedLeafInstruction { - pc, instruction, .. - } in instructions - { - source_map.push((pc, code.len())); - emit_decoded(&mut code, pc, instruction, profile, target, &mut fixups)?; + source_bytes: usize, +} + +impl Leaf { + /// Decode a two-argument context leaf ending in RET X30. The runtime + /// validates `profile` against its state before calling it. + pub(crate) fn decode( + source: &[u8], + base: GuestAddress, + profile: ScalableProfile, + target: TargetCpu, + ) -> Result { + let instructions = decode_leaf(source, base, profile, target)?; + let memory_requirements = instructions.iter().try_fold( + MemoryRequirements::default(), + |requirements, decoded| { + requirements + .merge(decoded.instruction.memory_requirements()) + .ok_or_else(|| { + CompileError(format!( + "conflicting memory control requirements at {:#x}", + decoded.pc.0 + )) + }) + }, + )?; + Ok(Self { + instructions, + memory_requirements, + profile, + target, + source_bytes: source.len(), + }) } - let offsets: BTreeMap<_, _> = source_map - .iter() - .map(|(pc, offset)| (pc.0, *offset)) - .collect(); - for (pc, target, displacement) in fixups { - let destination = offsets.get(&target.0).ok_or_else(|| { - CompileError(format!( - "unresolved direct target {:#x} from {:#x}", - target.0, pc.0 - )) - })?; - let relative = - i32::try_from(*destination as i128 - (displacement + size_of::()) as i128) - .map_err(|_| CompileError("native branch displacement overflow".into()))?; - code[displacement..displacement + size_of::()] - .copy_from_slice(&relative.to_le_bytes()); + + pub(crate) const fn source_bytes(&self) -> usize { + self.source_bytes + } + + /// The whole body's service requirements; empty for a leaf with no + /// memory access. + pub(crate) const fn memory_requirements(&self) -> MemoryRequirements { + self.memory_requirements + } + + /// Each instruction's scalable execution requirements, in source order. + pub(crate) fn execution_requirements(&self) -> ScalableExecutionRequirements { + ScalableExecutionRequirements::new( + self.instructions + .iter() + .map(|decoded| { + InstructionExecutionRequirements::new( + decoded.pc, + decoded.feature_clauses.clone(), + decoded.instruction.execution_access_requirements(), + decoded.instruction.guest_memory_quantity(), + ) + }) + .collect(), + ) + } + + pub(crate) fn emit(self) -> Result { + let mut code = context_wrapper(); + let mut source_map = Vec::with_capacity(self.instructions.len()); + let mut fixups = Vec::new(); + for DecodedLeafInstruction { + pc, instruction, .. + } in self.instructions + { + source_map.push((pc, code.len())); + emit_decoded( + &mut code, + pc, + instruction, + self.profile, + self.target, + &mut fixups, + )?; + } + let offsets: BTreeMap<_, _> = source_map + .iter() + .map(|(pc, offset)| (pc.0, *offset)) + .collect(); + for (pc, target, displacement) in fixups { + let destination = offsets.get(&target.0).ok_or_else(|| { + CompileError(format!( + "unresolved direct target {:#x} from {:#x}", + target.0, pc.0 + )) + })?; + let relative = + i32::try_from(*destination as i128 - (displacement + size_of::()) as i128) + .map_err(|_| CompileError("native branch displacement overflow".into()))?; + code[displacement..displacement + size_of::()] + .copy_from_slice(&relative.to_le_bytes()); + } + Ok(NativeBlock { + x86_64_code: code.into_bytes(), + source_map, + }) } - Ok(NativeBlock { - x86_64_code: code, - source_map, - }) } #[cfg(test)] @@ -434,6 +431,9 @@ mod tests { }; use alloc::{vec, vec::Vec}; + /// x86 `ret`, which ends a context leaf's code. + const RET: u8 = 0xc3; + mod address { use super::*; @@ -460,7 +460,7 @@ mod tests { ScalableMode::new(true, za), ); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), selected, @@ -473,7 +473,7 @@ mod tests { ScalableMode::new(false, za), ); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), inactive, @@ -484,10 +484,12 @@ mod tests { .contains("streaming mode required") ); } - assert!(crate::compile(&words(&[word, RET_X30]), GuestAddress(0)).is_err()); + assert!( + crate::testing::leaf(&words(&[word, RET_X30]), GuestAddress(0)).is_err() + ); } assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[RDSVL_X0_ONE, RET_X30]), GuestAddress(0), profile(bytes, false), @@ -517,7 +519,7 @@ mod tests { for word in RESERVED_BYTE_VECTOR_WORDS { for streaming in [false, true] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), profile(16, streaming), @@ -544,7 +546,7 @@ mod tests { ) .unwrap(); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[ADDVL_X0_ONE, RET_X30]), GuestAddress(0), selected, @@ -553,7 +555,7 @@ mod tests { .is_ok() ); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[CNTP_X0_PN0, RET_X30]), GuestAddress(0), selected, @@ -571,8 +573,8 @@ mod tests { #[test] fn ordinary_payload_and_maps_preserve_original_bytes() { let source = words(&[NOP, 0xd280_00e0, RET_X30]); - let old = crate::compile(&source, GuestAddress(0x1000)).unwrap(); - let new = compile_for_profile( + let old = crate::testing::leaf(&source, GuestAddress(0x1000)).unwrap(); + let new = crate::testing::context_leaf( &source, GuestAddress(0x1000), profile(32, true), @@ -600,7 +602,7 @@ mod tests { for bytes in [16, 32, 64, 128, 256] { let source = words(&[AND_Z0_Z1_Z2, RDSVL_X0_ONE, RET_X30]); assert!( - compile_for_profile( + crate::testing::context_leaf( &source, GuestAddress(0), profile(bytes, true), @@ -609,7 +611,7 @@ mod tests { .is_ok() ); assert!( - compile_for_profile( + crate::testing::context_leaf( &source, GuestAddress(0), profile(bytes, false), @@ -620,7 +622,7 @@ mod tests { .contains("streaming mode required") ); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[RDSVL_X0_ONE, RET_X30]), GuestAddress(0), profile(bytes, false), @@ -630,7 +632,7 @@ mod tests { ); } assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[MOVPRFX_Z0_Z1, AND_Z0_Z1_Z2, RET_X30]), GuestAddress(0), profile(32, true), @@ -642,7 +644,7 @@ mod tests { ); for word in [0xf940_0020, 0x4e22_8420, 0x1e22_2820] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), profile(32, true), @@ -655,7 +657,7 @@ mod tests { #[test] fn branches_resolve_across_scalable_instruction_bodies() { const BRANCH_PLUS_EIGHT: u32 = 0x1400_0002; - let native = compile_for_profile( + let native = crate::testing::context_leaf( &words(&[BRANCH_PLUS_EIGHT, AND_Z0_Z1_Z2, RET_X30]), GuestAddress(0), profile(32, true), @@ -695,8 +697,8 @@ mod tests { }; for word in [ADD_PAIR, SQCVT_PAIR, SVE_SQCVTN_PAIR, SRSHL_PAIR] { let source = words(&[word, RET_X30]); - assert!(crate::compile(&source, GuestAddress(0)).is_err()); - let compatible = compile_for_profile( + assert!(crate::testing::leaf(&source, GuestAddress(0)).is_err()); + let compatible = crate::testing::context_leaf( &source, GuestAddress(0), profile(16, true), @@ -709,7 +711,7 @@ mod tests { ); for bytes in [16, 32, 64, 128, 256] { for streaming in [false, true] { - let result = compile_for_profile( + let result = crate::testing::context_leaf( &source, GuestAddress(0), declared(bytes, streaming), @@ -729,7 +731,7 @@ mod tests { } } assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[RESERVED_QUARTET_SHIFT, RET_X30]), GuestAddress(0), declared(16, true), @@ -748,7 +750,7 @@ mod tests { .unwrap(); for word in [ADD_PAIR, SQCVT_PAIR, SVE_SQCVTN_PAIR, SRSHL_PAIR] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), sme_only, @@ -771,8 +773,12 @@ mod tests { ScalableMode::from_svcr(svcr).unwrap(), ); let source = words(&[FCPY_HALF_P15_Z31, FDUP_DOUBLE_Z31, RET_X30]); - let result = - compile_for_profile(&source, GuestAddress(0), profile, TargetCpu::Baseline); + let result = crate::testing::context_leaf( + &source, + GuestAddress(0), + profile, + TargetCpu::Baseline, + ); if profile.mode().streaming() { let native = result.unwrap(); assert_eq!( @@ -787,10 +793,11 @@ mod tests { } } assert!( - crate::compile(&words(&[FCPY_HALF_P15_Z31, RET_X30]), GuestAddress(0)).is_err() + crate::testing::leaf(&words(&[FCPY_HALF_P15_Z31, RET_X30]), GuestAddress(0)) + .is_err() ); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[RESERVED_FCPY_SIZE, RET_X30]), GuestAddress(0), profile(16, true), @@ -806,7 +813,7 @@ mod tests { //! Checked store-pair routing. use super::*; use crate::{ - block::{BlockProfile, CheckedMemoryProfile, CompilationPlan}, + block::{BlockProfile, CheckedMemoryProfile, CompilationPlan, Features}, context::memory::{SpAlignmentRequirement, flags, host_caps}, }; use alloc::vec::Vec; @@ -864,12 +871,16 @@ mod tests { .flat_map(u32::to_le_bytes) .collect(); for profile in [ - BlockProfile::CheckedMemory(recipe), - BlockProfile::CheckedMemoryPauthClockThread(recipe), + BlockProfile::ORDINARY.with_checked_memory(recipe), + BlockProfile::new(Features::PROCESS_HELPERS) + .with_checked_memory(recipe), ] { - let plan = - CompilationPlan::new(&source, BASE, profile, TargetCpu::Cx16) - .unwrap(); + let plan = CompilationPlan::new( + &source, + BASE, + &crate::Options::new(profile, TargetCpu::Cx16), + ) + .unwrap(); assert_eq!(plan.memory_requirements(), Some(required)); let compiled = plan.compile().unwrap(); assert_eq!( @@ -938,14 +949,14 @@ mod tests { let source: Vec<_> = [load, RET].into_iter().flat_map(u32::to_le_bytes).collect(); for profile in [ - BlockProfile::CheckedMemory(recipe), - BlockProfile::CheckedMemoryPauthClockThread(recipe), + BlockProfile::ORDINARY.with_checked_memory(recipe), + BlockProfile::new(Features::PROCESS_HELPERS) + .with_checked_memory(recipe), ] { let plan = CompilationPlan::new( &source, BASE, - profile, - TargetCpu::AtomicLoad16, + &crate::Options::new(profile, TargetCpu::AtomicLoad16), ) .unwrap(); assert_eq!(plan.memory_requirements(), Some(required)); @@ -974,7 +985,7 @@ mod tests { const SDOT_Z0_S_Z1_B_Z2_B: u32 = 0x4482_0020; const CDOT_RESERVED_BYTE: u32 = 0x4400_1000; let source = words(&[SDOT_Z0_S_Z1_B_Z2_B, RET_X30]); - assert!(crate::compile(&source, GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&source, GuestAddress(0)).is_err()); assert!(matches!( crate::aarch64::sve::decode(SDOT_Z0_S_Z1_B_Z2_B), Some(Ok(crate::aarch64::sve::Operand::Dot(_))) @@ -986,7 +997,7 @@ mod tests { VectorLength::from_bytes(bytes).unwrap(), ScalableMode::new(streaming, za), ); - let result = compile_for_profile( + let result = crate::testing::context_leaf( &source, GuestAddress(0), profile, @@ -1000,7 +1011,7 @@ mod tests { } } assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[CDOT_RESERVED_BYTE, RET_X30]), GuestAddress(0), profile(bytes, true), @@ -1032,7 +1043,7 @@ mod tests { assert!(dot::decode(word).unwrap().is_ok()); assert_eq!(crate::aarch64::sve::decode(word), None); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), profile(32, true), @@ -1042,7 +1053,7 @@ mod tests { ); } assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[MOVPRFX_Z0_Z1, SDOT_Z0_S_Z1_B_Z2_B, RET_X30]), GuestAddress(0), profile(32, true), @@ -1067,7 +1078,7 @@ mod tests { ScalableMode::new(true, za), ); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), profile, @@ -1102,7 +1113,7 @@ mod tests { ), (vec![MOVPRFX_Z0_Z1, CMPEQ_BYTE, RET_X30], true, "MOVPRFX"), ] { - let error = compile_for_profile( + let error = crate::testing::context_leaf( &words(&input), GuestAddress(0), profile(32, streaming), @@ -1126,16 +1137,20 @@ mod tests { ) .unwrap(); let source = words(&[CMPEQ_BYTE, RET_X30]); - let fixed = compile_for_profile( + let fixed = crate::testing::context_leaf( &source, GuestAddress(0), ScalableProfile::new(length, mode), TargetCpu::Baseline, ) .unwrap(); - let explicit = - compile_for_profile(&source, GuestAddress(0), declared, TargetCpu::Baseline) - .unwrap(); + let explicit = crate::testing::context_leaf( + &source, + GuestAddress(0), + declared, + TargetCpu::Baseline, + ) + .unwrap(); assert_eq!(fixed.x86_64_code, explicit.x86_64_code); assert_eq!(fixed.source_map, explicit.source_map); } @@ -1208,14 +1223,14 @@ mod tests { ); for bytes in [16, 32, 64, 128, 256] { for target in [TargetCpu::Baseline, TargetCpu::Sse42] { - let native = compile_for_profile( + let native = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0x1000), profile(bytes, true), target, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::integer_arithmetic::emit( &mut expected, operand, @@ -1259,7 +1274,7 @@ mod tests { ADD_RESERVED_BYTE_SHIFT8, ] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[NOP, word, RET_X30]), GuestAddress(0), profile(32, true), @@ -1272,7 +1287,7 @@ mod tests { } for bytes in [16, 32, 64, 128, 256] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[ADD_Z0_Z1_Z2, RET_X30]), GuestAddress(0), profile(bytes, false), @@ -1284,7 +1299,7 @@ mod tests { ); } assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[MOVPRFX_Z0_Z1, ADD_Z0_Z1_Z2, RET_X30]), GuestAddress(0), profile(32, true), @@ -1294,7 +1309,9 @@ mod tests { .0 .contains("MOVPRFX pair validation") ); - assert!(crate::compile(&words(&[ADD_Z0_Z1_Z2, RET_X30]), GuestAddress(0)).is_err()); + assert!( + crate::testing::leaf(&words(&[ADD_Z0_Z1_Z2, RET_X30]), GuestAddress(0)).is_err() + ); } #[test] @@ -1355,14 +1372,14 @@ mod tests { ); for bytes in [16, 32, 64, 128, 256] { for target in [TargetCpu::Baseline, TargetCpu::Sse42] { - let native = compile_for_profile( + let native = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0x1000), profile(bytes, true), target, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::integer_saturation::emit( &mut expected, operand, @@ -1400,7 +1417,7 @@ mod tests { const MOVPRFX_PREDICATED_Z0_Z1: u32 = 0x0410_2020; for word in [SQADD_RESERVED_BYTE_SHIFT8, SABDLB_RESERVED_BYTE] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[NOP, word, RET_X30]), GuestAddress(0), profile(32, true), @@ -1413,7 +1430,7 @@ mod tests { } for bytes in [16, 32, 64, 128, 256] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[SQADD_Z0_Z1_Z2, RET_X30]), GuestAddress(0), profile(bytes, false), @@ -1426,7 +1443,7 @@ mod tests { } for prefix in [MOVPRFX_Z0_Z1, MOVPRFX_PREDICATED_Z0_Z1] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[prefix, SQADD_Z0_Z1_Z2, RET_X30]), GuestAddress(0), profile(32, true), @@ -1437,7 +1454,9 @@ mod tests { .contains("MOVPRFX pair validation") ); } - assert!(crate::compile(&words(&[SQADD_Z0_Z1_Z2, RET_X30]), GuestAddress(0)).is_err()); + assert!( + crate::testing::leaf(&words(&[SQADD_Z0_Z1_Z2, RET_X30]), GuestAddress(0)).is_err() + ); } #[test] @@ -1452,8 +1471,12 @@ mod tests { ScalableMode::from_svcr(svcr).unwrap(), ); let source = words(&[FABS_HALF, FNEG_DOUBLE, RET_X30]); - let result = - compile_for_profile(&source, GuestAddress(0), profile, TargetCpu::Baseline); + let result = crate::testing::context_leaf( + &source, + GuestAddress(0), + profile, + TargetCpu::Baseline, + ); if profile.mode().streaming() { let native = result.unwrap(); assert_eq!( @@ -1467,9 +1490,9 @@ mod tests { } } } - assert!(crate::compile(&words(&[FABS_HALF, RET_X30]), GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&words(&[FABS_HALF, RET_X30]), GuestAddress(0)).is_err()); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[RESERVED_SIGN_SIZE, RET_X30]), GuestAddress(0), profile(16, true), @@ -1504,14 +1527,14 @@ mod tests { ); for bytes in [16, 32, 64, 128, 256] { for target in [TargetCpu::Baseline, TargetCpu::Ssse3, TargetCpu::Sse41] { - let native = compile_for_profile( + let native = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0x1000), profile(bytes, true), target, ) .unwrap(); - let mut body = Vec::new(); + let mut body = Code::new(); x86_64::sve::integer_bits::emit( &mut body, operand, @@ -1548,7 +1571,7 @@ mod tests { ScalableControls::new(length, false), ) .unwrap(); - let result = compile_for_profile( + let result = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), selected, @@ -1576,7 +1599,7 @@ mod tests { ]; for word in RESERVED_REVERSE_WORDS { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[NOP, word, RET_X30]), GuestAddress(0), profile(16, true), @@ -1598,7 +1621,7 @@ mod tests { ]; for word in ZEROING_WORDS { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), profile(16, true), @@ -1609,7 +1632,7 @@ mod tests { } const CLS_Z0_B_P0_Z1_B: u32 = 0x0418_a020; assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[MOVPRFX_Z0_Z1, CLS_Z0_B_P0_Z1_B, RET_X30]), GuestAddress(0), profile(16, true), @@ -1619,7 +1642,10 @@ mod tests { .0 .contains("MOVPRFX pair validation") ); - assert!(crate::compile(&words(&[CLS_Z0_B_P0_Z1_B, RET_X30]), GuestAddress(0)).is_err()); + assert!( + crate::testing::leaf(&words(&[CLS_Z0_B_P0_Z1_B, RET_X30]), GuestAddress(0)) + .is_err() + ); } #[test] fn integer_bits_bsr_recipes_require_declared_dit_zero() { @@ -1654,20 +1680,20 @@ mod tests { .unwrap(); assert_eq!(declared.required_dit(), Some(false)); for target in [TargetCpu::Baseline, TargetCpu::Ssse3, TargetCpu::Sse41] { - let positive = compile_for_profile( + let positive = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), declared, target, ) .unwrap(); - let mut body = Vec::new(); + let mut body = Code::new(); x86_64::sve::integer_bits::emit(&mut body, operand, length, target); assert_eq!( &positive.x86_64_code[CONTEXT_WRAPPER_BYTES..][..body.len()], body ); - let legacy = compile_for_profile( + let legacy = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), profile(bytes, true), @@ -1820,14 +1846,14 @@ mod tests { } else { profile(bytes, true) }; - let native = compile_for_profile( + let native = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0x1000), selected_profile, target, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::integer_products::emit( &mut expected, operand, @@ -1862,7 +1888,7 @@ mod tests { const PMULLB_RESERVED_WORD: u32 = 0x4580_6800; for word in [SMULLB_RESERVED_BYTE, PMULLB_RESERVED_WORD] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[NOP, word, RET_X30]), GuestAddress(0), profile(32, true), @@ -1874,7 +1900,7 @@ mod tests { ); } assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[MUL_Z0_Z1_Z2, RET_X30]), GuestAddress(0), profile(32, false), @@ -1885,7 +1911,7 @@ mod tests { .contains("streaming mode required") ); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[MOVPRFX_Z0_Z1, MUL_Z0_Z1_Z2, RET_X30]), GuestAddress(0), profile(32, true), @@ -2004,14 +2030,14 @@ mod tests { ); for bytes in [16, 32, 64, 128, 256] { let profile = profile(bytes, true); - let native = compile_for_profile( + let native = crate::testing::context_leaf( &source(&[word, RET_X30]), GUEST_BASE, profile, TargetCpu::Baseline, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::memory_load::emit( &mut expected, operand, @@ -2039,7 +2065,7 @@ mod tests { ); assert_eq!(&native.x86_64_code[native.source_map[1].1..], [RET]); assert_eq!( - memory_requirements( + crate::testing::context_leaf_memory( &source(&[word, RET_X30]), GUEST_BASE, profile, @@ -2056,7 +2082,7 @@ mod tests { fn requirements_cover_the_complete_body_and_explicit_pure_case() { let profile = profile(16, true); assert_eq!( - memory_requirements( + crate::testing::context_leaf_memory( &source(&[NOP, RET_X30]), GUEST_BASE, profile, @@ -2066,7 +2092,7 @@ mod tests { MemoryRequirements::default() ); assert_eq!( - memory_requirements( + crate::testing::context_leaf_memory( &source(&[LD1B_Z1_P0_X5, LD1D_Z1_P0_SP, LD1D_Z1_P0_X5, RET_X30]), GUEST_BASE, profile, @@ -2114,10 +2140,16 @@ mod tests { profile(16, false), ), ] { - let scan = - memory_requirements(&source, base, profile, TargetCpu::Baseline).unwrap_err(); + let scan = crate::testing::context_leaf_memory( + &source, + base, + profile, + TargetCpu::Baseline, + ) + .unwrap_err(); let compile = - compile_for_profile(&source, base, profile, TargetCpu::Baseline).unwrap_err(); + crate::testing::context_leaf(&source, base, profile, TargetCpu::Baseline) + .unwrap_err(); assert_eq!(scan.0, compile.0); } } @@ -2232,10 +2264,14 @@ mod tests { for bytes in [16, 256] { let profile = profile(bytes, true); let bytes = source(&[word, RET_X30]); - let native = - compile_for_profile(&bytes, GUEST_BASE, profile, TargetCpu::Baseline) - .unwrap(); - let mut expected = Vec::new(); + let native = crate::testing::context_leaf( + &bytes, + GUEST_BASE, + profile, + TargetCpu::Baseline, + ) + .unwrap(); + let mut expected = Code::new(); x86_64::sve::memory_multi::emit( &mut expected, &operand, @@ -2263,8 +2299,13 @@ mod tests { ); assert_eq!(&native.x86_64_code[native.source_map[1].1..], [RET]); assert_eq!( - memory_requirements(&bytes, GUEST_BASE, profile, TargetCpu::Baseline) - .unwrap(), + crate::testing::context_leaf_memory( + &bytes, + GUEST_BASE, + profile, + TargetCpu::Baseline + ) + .unwrap(), x86_64::sve::memory_multi::requirements(&operand) ); } @@ -2275,7 +2316,7 @@ mod tests { fn multi_requirements_fold_every_effect_and_preserve_four_argument_descriptor() { let profile = profile(16, true); assert_eq!( - memory_requirements( + crate::testing::context_leaf_memory( &source(&[NOP, RET_X30]), GUEST_BASE, profile, @@ -2285,7 +2326,7 @@ mod tests { MemoryRequirements::default() ); assert_eq!( - memory_requirements( + crate::testing::context_leaf_memory( &source(&[ LD1D_Z0_Z1_PN8_X5_X0, LD1D_Z0_Z1_PN8_SP, @@ -2310,7 +2351,7 @@ mod tests { } ); assert_eq!( - memory_requirements( + crate::testing::context_leaf_memory( &source(&[LD1D_Z0_Z1_PN8_SP, RET_X30]), GUEST_BASE, profile, @@ -2347,10 +2388,16 @@ mod tests { (vec![LD1D_Z0_Z1_PN8_X5_X0], profile(16, true)), ] { let bytes = source(&words); - let scan = memory_requirements(&bytes, GUEST_BASE, profile, TargetCpu::Baseline) - .unwrap_err(); - let compile = compile_for_profile(&bytes, GUEST_BASE, profile, TargetCpu::Baseline) - .unwrap_err(); + let scan = crate::testing::context_leaf_memory( + &bytes, + GUEST_BASE, + profile, + TargetCpu::Baseline, + ) + .unwrap_err(); + let compile = + crate::testing::context_leaf(&bytes, GUEST_BASE, profile, TargetCpu::Baseline) + .unwrap_err(); assert_eq!(scan.0, compile.0); } } @@ -2463,14 +2510,14 @@ mod tests { ); for bytes in [16, 32, 64, 128, 256] { let profile = profile(bytes, true, true); - let native = compile_for_profile( + let native = crate::testing::context_leaf( &source(&[word, RET_X30]), GUEST_BASE, profile, TargetCpu::Baseline, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::memory_store::emit( &mut expected, &operand, @@ -2499,7 +2546,7 @@ mod tests { ); assert_eq!(&native.x86_64_code[native.source_map[1].1..], [RET]); assert_eq!( - memory_requirements( + crate::testing::context_leaf_memory( &source(&[word, RET_X30]), GUEST_BASE, profile, @@ -2516,8 +2563,13 @@ mod tests { fn stores_preflight_write_caps_tags_and_original_sp_for_the_complete_body() { let profile = profile(16, true, true); let requirements = |words: &[u32]| { - memory_requirements(&source(words), GUEST_BASE, profile, TargetCpu::Baseline) - .unwrap() + crate::testing::context_leaf_memory( + &source(words), + GUEST_BASE, + profile, + TargetCpu::Baseline, + ) + .unwrap() }; assert_eq!( requirements(&[NOP, PRFB_P0_SP, RET_X30]), @@ -2594,10 +2646,15 @@ mod tests { (ST2Q_Z1_P0_X5, profile(16, true, false), "FEAT_SME2p1"), ] { let source = source(&[word, RET_X30]); - let scan = memory_requirements(&source, GUEST_BASE, profile, TargetCpu::Baseline) - .unwrap_err(); + let scan = crate::testing::context_leaf_memory( + &source, + GUEST_BASE, + profile, + TargetCpu::Baseline, + ) + .unwrap_err(); let compile = - compile_for_profile(&source, GUEST_BASE, profile, TargetCpu::Baseline) + crate::testing::context_leaf(&source, GUEST_BASE, profile, TargetCpu::Baseline) .unwrap_err(); assert_eq!(scan.0, compile.0); assert!(scan.0.contains(reason), "{}", scan.0); @@ -2695,10 +2752,14 @@ mod tests { for bytes in LENGTHS { let profile = profile(bytes, true, true); let input = source(&[word, RET_X30]); - let native = - compile_for_profile(&input, GUEST_BASE, profile, TargetCpu::Baseline) - .unwrap(); - let mut expected = Vec::new(); + let native = crate::testing::context_leaf( + &input, + GUEST_BASE, + profile, + TargetCpu::Baseline, + ) + .unwrap(); + let mut expected = Code::new(); x86_64::sve::memory_structure::emit( &mut expected, &operand, @@ -2726,8 +2787,13 @@ mod tests { ); assert_eq!(&native.x86_64_code[native.source_map[1].1..], [RET]); assert_eq!( - memory_requirements(&input, GUEST_BASE, profile, TargetCpu::Baseline) - .unwrap(), + crate::testing::context_leaf_memory( + &input, + GUEST_BASE, + profile, + TargetCpu::Baseline + ) + .unwrap(), x86_64::sve::memory_structure::requirements(operand) ); } @@ -2751,12 +2817,20 @@ mod tests { } for (word, profile) in declines { let input = source(&[NOP, word, RET_X30]); - let scan = - memory_requirements(&input, GUEST_BASE, profile, TargetCpu::Baseline) - .unwrap_err(); - let compile = - compile_for_profile(&input, GUEST_BASE, profile, TargetCpu::Baseline) - .unwrap_err(); + let scan = crate::testing::context_leaf_memory( + &input, + GUEST_BASE, + profile, + TargetCpu::Baseline, + ) + .unwrap_err(); + let compile = crate::testing::context_leaf( + &input, + GUEST_BASE, + profile, + TargetCpu::Baseline, + ) + .unwrap_err(); assert_eq!(scan.0, compile.0); } } @@ -2771,7 +2845,7 @@ mod tests { RET_X30, ]); assert_eq!( - memory_requirements( + crate::testing::context_leaf_memory( &input, GUEST_BASE, profile(16, true, true), @@ -2899,7 +2973,7 @@ mod tests { } fn rejection(word: u32, profile: ScalableProfile) -> String { - compile_for_profile( + crate::testing::context_leaf( &words(&[NOP, word, RET_X30]), SOURCE_BASE, profile, @@ -2928,13 +3002,15 @@ mod tests { < usize::from(operand.requirements.minimum_current_svl_bits) { assert!( - compile_for_profile(&source, SOURCE_BASE, profile, target).is_err() + crate::testing::context_leaf(&source, SOURCE_BASE, profile, target) + .is_err() ); continue; } let native = - compile_for_profile(&source, SOURCE_BASE, profile, target).unwrap(); - let mut body = Vec::new(); + crate::testing::context_leaf(&source, SOURCE_BASE, profile, target) + .unwrap(); + let mut body = Code::new(); x86_64::sme::movement::emit( &mut body, &operand, @@ -2967,7 +3043,7 @@ mod tests { ); } } - assert!(crate::compile(&words(&[word, RET_X30]), SOURCE_BASE).is_err()); + assert!(crate::testing::leaf(&words(&[word, RET_X30]), SOURCE_BASE).is_err()); } } @@ -2999,7 +3075,7 @@ mod tests { } for word in [ZERO_ZA_EMPTY, ZERO_ZA_ALL, ZERO_ZT0] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), SOURCE_BASE, no_stream, @@ -3022,7 +3098,7 @@ mod tests { for word in [MOVAZ_Z0_ZA0H_BYTE, ZERO_ZA_VECTOR_GROUP] { assert!(rejection(word, no_sme2p1).contains("FEAT_SME2p1")); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), SOURCE_BASE, no_sme2p1, @@ -3095,7 +3171,7 @@ mod tests { }; profile.validate_view(&context, &view).unwrap(); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[ZERO_ZA_ALL, RET_X30]), SOURCE_BASE, profile, @@ -3119,10 +3195,15 @@ mod tests { ] { let source = words(&[word, RET_X30]); let first = - compile_for_profile(&source, SOURCE_BASE, legacy, TargetCpu::Baseline).unwrap(); - let second = - compile_for_profile(&source, SOURCE_BASE, declared, TargetCpu::Baseline) + crate::testing::context_leaf(&source, SOURCE_BASE, legacy, TargetCpu::Baseline) .unwrap(); + let second = crate::testing::context_leaf( + &source, + SOURCE_BASE, + declared, + TargetCpu::Baseline, + ) + .unwrap(); assert_eq!(first.x86_64_code, second.x86_64_code); assert_eq!(first.source_map, second.source_map); } @@ -3212,14 +3293,14 @@ mod tests { for bytes in [16, 32, 64, 128, 256] { for svcr in [1, 3] { for target in [TargetCpu::Baseline, TargetCpu::Bmi1] { - let native = compile_for_profile( + let native = crate::testing::context_leaf( &source(&[word, RET_X30]), GuestAddress(0x1000), profile(bytes, svcr, true), target, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::predicate_generation::emit( &mut expected, &operand, @@ -3256,7 +3337,7 @@ mod tests { for bytes in [16, 32, 64, 128, 256] { for svcr in [0, 2] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[word, RET_X30]), GuestAddress(0), profile(bytes, svcr, true), @@ -3268,7 +3349,7 @@ mod tests { ); } for svcr in [1, 3] { - let result = compile_for_profile( + let result = crate::testing::context_leaf( &source(&[word, RET_X30]), GuestAddress(0), profile(bytes, svcr, false), @@ -3281,7 +3362,7 @@ mod tests { } } } - assert!(crate::compile(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); } assert_eq!(sme2_forms, 17); } @@ -3355,14 +3436,14 @@ mod tests { ); for bytes in [16, 32, 64, 128, 256] { for target in [TargetCpu::Baseline, TargetCpu::Sse42] { - let native = compile_for_profile( + let native = crate::testing::context_leaf( &source(&[word, RET_X30]), GuestAddress(0x1000), profile(bytes, 3, features), target, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::predicate_logic::emit( &mut expected, &operand, @@ -3405,7 +3486,7 @@ mod tests { move_forms += usize::from(vector_move); for svcr in [0, 2] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[word, RET_X30]), GuestAddress(0), profile(16, svcr, all), @@ -3429,7 +3510,7 @@ mod tests { (sme2, !vector_move, "FEAT_SME2p1"), (all, true, ""), ] { - let result = compile_for_profile( + let result = crate::testing::context_leaf( &source(&[word, RET_X30]), GuestAddress(0), profile(16, 3, features), @@ -3445,7 +3526,7 @@ mod tests { VectorLength::from_bytes(16).unwrap(), ScalableMode::from_svcr(3).unwrap(), ); - let result = compile_for_profile( + let result = crate::testing::context_leaf( &source(&[word, RET_X30]), GuestAddress(0), v1, @@ -3456,12 +3537,12 @@ mod tests { } else { assert!(result.is_ok()); } - assert!(crate::compile(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); } assert_eq!(counter_forms, 2); assert_eq!(move_forms, 4); assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[RESERVED_PSEL_SIZE, RET_X30]), GuestAddress(0), profile(16, 3, all), @@ -3525,14 +3606,14 @@ mod tests { for bytes in [16, 32, 64, 128, 256] { for za in [false, true] { for target in [TargetCpu::Baseline, TargetCpu::Sse42] { - let native = compile_for_profile( + let native = crate::testing::context_leaf( &source(word), GuestAddress(0x1000), profile(bytes, true, za, true), target, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::integer_predicate_move::emit( &mut expected, operand, @@ -3569,7 +3650,7 @@ mod tests { #[test] fn predicate_move_requires_sme2p1_streaming_without_requiring_za() { for word in BASES { - let error = compile_for_profile( + let error = crate::testing::context_leaf( &source(word), GuestAddress(0), profile(16, true, false, false), @@ -3578,7 +3659,7 @@ mod tests { .unwrap_err(); assert!(error.0.contains("FEAT_SME2p1")); for za in [false, true] { - let error = compile_for_profile( + let error = crate::testing::context_leaf( &source(word), GuestAddress(0), profile(16, false, za, true), @@ -3587,7 +3668,7 @@ mod tests { .unwrap_err(); assert!(error.0.contains("streaming mode required")); assert!( - compile_for_profile( + crate::testing::context_leaf( &source(word), GuestAddress(0), profile(16, true, za, true), @@ -3597,7 +3678,7 @@ mod tests { ); } assert!( - compile_for_profile( + crate::testing::context_leaf( &source(word), GuestAddress(0), ScalableProfile::new( @@ -3637,7 +3718,8 @@ mod tests { .flat_map(|word| word.to_le_bytes()) .collect(); let native = - compile_for_profile(&source, BASE, profile, TargetCpu::Baseline).unwrap(); + crate::testing::context_leaf(&source, BASE, profile, TargetCpu::Baseline) + .unwrap(); assert_eq!( native .source_map @@ -3673,9 +3755,11 @@ mod tests { .iter() .flat_map(|word| word.to_le_bytes()) .collect(); - let prepared = prepare_leaf(&source, BASE, profile, TargetCpu::Baseline).unwrap(); + let prepared = + crate::testing::prepared_context_leaf(&source, BASE, profile, TargetCpu::Baseline) + .unwrap(); let ordinary = - compile_for_profile(&source, BASE, profile, TargetCpu::Baseline).unwrap(); + crate::testing::context_leaf(&source, BASE, profile, TargetCpu::Baseline).unwrap(); assert_eq!(prepared.native.x86_64_code, ordinary.x86_64_code); assert_eq!(prepared.native.source_map, ordinary.source_map); let instructions = prepared.execution_requirements.instructions(); @@ -3705,7 +3789,12 @@ mod tests { .iter() .flat_map(|word| word.to_le_bytes()) .collect(); - let error = match prepare_leaf(&refused, BASE, profile, TargetCpu::Baseline) { + let error = match crate::testing::prepared_context_leaf( + &refused, + BASE, + profile, + TargetCpu::Baseline, + ) { Err(error) => error, Ok(_) => panic!("unreviewed MOVPRFX pair accepted"), }; @@ -3927,7 +4016,7 @@ mod tests { .unwrap(); for word in BASE_SME_WORDS { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0x1234), profile, @@ -3956,7 +4045,7 @@ mod tests { .unwrap() }; let compile = |word, profile| { - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0x1234), profile, @@ -4052,14 +4141,14 @@ mod tests { } else { profile(bytes, svcr) }; - let native = compile_for_profile( + let native = crate::testing::context_leaf( &source(&[NOP, word, RET_X30]), GuestAddress(0x1000), execution, target, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::rearrange::emit( &mut expected, operand, @@ -4099,7 +4188,7 @@ mod tests { for bytes in [16, 32, 64, 128, 256] { for svcr in [0, 2] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[NOP, word, RET_X30]), GuestAddress(0), profile(bytes, svcr), @@ -4111,9 +4200,9 @@ mod tests { ); } } - assert!(crate::compile(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[MOVPRFX_Z0_Z1, word, RET_X30]), GuestAddress(0), profile(32, 3), @@ -4125,7 +4214,7 @@ mod tests { ); } assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[NOP, RESERVED_LOGICAL_MASK, RET_X30]), GuestAddress(0), profile(32, 3), @@ -4140,7 +4229,7 @@ mod tests { #[test] fn rearrangement_declines_nonzero_revd_size_and_both_prefix_forms() { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[NONZERO_REVD_SIZE, RET_X30]), GuestAddress(0), profile(32, 3), @@ -4150,7 +4239,7 @@ mod tests { ); for prefix in [MOVPRFX_Z0_Z1, MOVPRFX_PREDICATED_Z0_Z1] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[prefix, REARRANGEMENT_WORDS[0], RET_X30]), GuestAddress(0), profile(32, 3), @@ -4177,7 +4266,7 @@ mod tests { VectorLength::from_bytes(bytes).unwrap(), target, ); - let legacy = compile_for_profile( + let legacy = crate::testing::context_leaf( &source(&[word, RET_X30]), GuestAddress(0x1000), profile(bytes, svcr), @@ -4194,7 +4283,7 @@ mod tests { let declared = dit_zero_profile(bytes, svcr); assert_eq!(declared.required_dit(), Some(false)); assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[word, RET_X30]), GuestAddress(0x1000), declared, @@ -4285,14 +4374,14 @@ mod tests { for bytes in [16, 32, 64, 128, 256] { for svcr in [1, 3] { for target in [TargetCpu::Baseline, TargetCpu::Ssse3] { - let native = compile_for_profile( + let native = crate::testing::context_leaf( &source(&[NOP, word, RET_X30]), GuestAddress(0x1000), profile(bytes, svcr), target, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::rearrange_extract::emit( &mut expected, operand, @@ -4332,7 +4421,7 @@ mod tests { for bytes in [16, 32, 64, 128, 256] { for svcr in [0, 2] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[NOP, word, RET_X30]), GuestAddress(0), profile(bytes, svcr), @@ -4344,9 +4433,9 @@ mod tests { ); } } - assert!(crate::compile(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[MOVPRFX_Z0_Z1, word, RET_X30]), GuestAddress(0), profile(32, 3), @@ -4359,7 +4448,7 @@ mod tests { } for word in [RESERVED_BYTE_SHIFT, RESERVED_ZERO_INDEX_SIZE] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[NOP, word, RET_X30]), GuestAddress(0), profile(32, 3), @@ -4390,10 +4479,15 @@ mod tests { for target in [TargetCpu::Baseline, TargetCpu::Ssse3] { let input = source(&[word, RET_X30]); let base = GuestAddress(0x1000); - let v1 = - compile_for_profile(&input, base, profile(bytes, svcr), target) - .unwrap(); - let v2 = compile_for_profile(&input, base, declared, target).unwrap(); + let v1 = crate::testing::context_leaf( + &input, + base, + profile(bytes, svcr), + target, + ) + .unwrap(); + let v2 = crate::testing::context_leaf(&input, base, declared, target) + .unwrap(); assert_eq!(v1.x86_64_code, v2.x86_64_code); assert_eq!(v1.source_map, v2.source_map); } @@ -4465,14 +4559,14 @@ mod tests { for bytes in [16, 32, 64, 128, 256] { for svcr in [1, 3] { for target in [TargetCpu::Baseline, TargetCpu::Sse41, TargetCpu::Sse42] { - let native = compile_for_profile( + let native = crate::testing::context_leaf( &source(&[NOP, word, RET_X30]), GuestAddress(0x1000), profile(bytes, svcr), target, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); x86_64::sve::reductions::emit( &mut expected, operand, @@ -4512,7 +4606,7 @@ mod tests { for bytes in [16, 32, 64, 128, 256] { for svcr in [0, 2] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[NOP, word, RET_X30]), GuestAddress(0), profile(bytes, svcr), @@ -4524,10 +4618,10 @@ mod tests { ); } } - assert!(crate::compile(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); for prefix in [MOVPRFX_Z0_Z1, MOVPRFX_PREDICATED_Z0_Z1] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[prefix, word, RET_X30]), GuestAddress(0), profile(32, 3), @@ -4541,10 +4635,10 @@ mod tests { } assert_eq!( reductions::decode(RESERVED_SIGNED_DOUBLEWORD), - Some(Err(())) + Some(Err(crate::aarch64::Unsupported)) ); assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[NOP, RESERVED_SIGNED_DOUBLEWORD, RET_X30]), GuestAddress(0), profile(32, 3), @@ -4627,14 +4721,14 @@ mod tests { ); for bytes in [16, 32, 64, 128, 256] { for target in [TargetCpu::Baseline, TargetCpu::Sse41] { - let native = compile_for_profile( + let native = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0x1000), declared_dit_zero_profile(bytes), target, ) .unwrap(); - let mut body = Vec::new(); + let mut body = Code::new(); x86_64::sve::shifts::emit( &mut body, operand, @@ -4669,7 +4763,7 @@ mod tests { ) .unwrap(); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), base_sme, @@ -4683,7 +4777,7 @@ mod tests { VectorLength::from_bytes(16).unwrap(), ScalableMode::new(streaming, za), ); - let result = compile_for_profile( + let result = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), selected, @@ -4886,7 +4980,7 @@ mod tests { "{word:#x} at {bytes} bytes", ); let source = words(&[NOP, word, RET_X30]); - let legacy = compile_for_profile( + let legacy = crate::testing::context_leaf( &source, GuestAddress(0), profile(bytes, true), @@ -4898,7 +4992,7 @@ mod tests { assert!(legacy.is_ok()); } assert!( - compile_for_profile( + crate::testing::context_leaf( &source, GuestAddress(0), declared_dit_zero_profile(bytes), @@ -4917,7 +5011,7 @@ mod tests { const LSL_Z0_B_P0_Z0_B_ZERO: u32 = 0x0403_8100; for word in [LSL_RESERVED_SIZE, ASR_RESERVED_DOUBLEWORDS] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[NOP, word, RET_X30]), GuestAddress(0), profile(16, true), @@ -4929,7 +5023,7 @@ mod tests { ); } assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[MOVPRFX_Z0_Z1, LSL_Z0_B_P0_Z0_B_ZERO, RET_X30]), GuestAddress(0), profile(16, true), @@ -4940,7 +5034,8 @@ mod tests { .contains("MOVPRFX pair validation") ); assert!( - crate::compile(&words(&[LSL_Z0_B_P0_Z0_B_ZERO, RET_X30]), GuestAddress(0)).is_err() + crate::testing::leaf(&words(&[LSL_Z0_B_P0_Z0_B_ZERO, RET_X30]), GuestAddress(0)) + .is_err() ); } @@ -4982,14 +5077,14 @@ mod tests { ); for bytes in [16, 32, 64, 128, 256] { for target in [TargetCpu::Baseline, TargetCpu::Sse41] { - let native = compile_for_profile( + let native = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0x1000), profile(bytes, true), target, ) .unwrap(); - let mut body = Vec::new(); + let mut body = Code::new(); x86_64::sve::shifts_narrow::emit( &mut body, operand, @@ -5021,7 +5116,7 @@ mod tests { VectorLength::from_bytes(16).unwrap(), ScalableMode::new(streaming, za), ); - let result = compile_for_profile( + let result = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0), selected, @@ -5044,7 +5139,7 @@ mod tests { const SSHLLB_Z0_H_Z1_B: u32 = 0x4508_a020; for word in [SSHLLB_RESERVED_SIZE, SQXTNB_RESERVED_SIZE] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[NOP, word, RET_X30]), GuestAddress(0), profile(16, true), @@ -5056,7 +5151,7 @@ mod tests { ); } assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[MOVPRFX_Z0_Z1, SSHLLB_Z0_H_Z1_B, RET_X30]), GuestAddress(0), profile(16, true), @@ -5066,7 +5161,10 @@ mod tests { .0 .contains("MOVPRFX pair validation") ); - assert!(crate::compile(&words(&[SSHLLB_Z0_H_Z1_B, RET_X30]), GuestAddress(0)).is_err()); + assert!( + crate::testing::leaf(&words(&[SSHLLB_Z0_H_Z1_B, RET_X30]), GuestAddress(0)) + .is_err() + ); } } mod sme2p1 { @@ -5234,14 +5332,14 @@ mod tests { TargetCpu::Sse42, ] { let length = VectorLength::from_bytes(bytes).unwrap(); - let native = compile_for_profile( + let native = crate::testing::context_leaf( &source(&[NOP, word, RET_X30]), GuestAddress(0x1000), declared(bytes, svcr, true), target, ) .unwrap(); - let mut expected = Vec::new(); + let mut expected = Code::new(); if let Some(Ok(operand)) = reductions::decode(word) { assert_eq!(operand.output, reductions::Output::Quadword); x86_64::sve::reductions::emit( @@ -5302,7 +5400,7 @@ mod tests { ScalableProfile::new(length, ScalableMode::from_svcr(svcr).unwrap()), declared(bytes, svcr, false), ] { - let error = compile_for_profile( + let error = crate::testing::context_leaf( &source(&[NOP, word, RET_X30]), GuestAddress(0x1000), profile, @@ -5316,7 +5414,7 @@ mod tests { } for svcr in [0, 2] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[NOP, word, RET_X30]), GuestAddress(0x1000), declared(bytes, svcr, true), @@ -5328,10 +5426,10 @@ mod tests { ); } } - assert!(crate::compile(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&source(&[word, RET_X30]), GuestAddress(0)).is_err()); for prefix in [0x0420_bc20, 0x0410_2020] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[prefix, word, RET_X30]), GuestAddress(0), declared(32, 3, true), @@ -5372,7 +5470,7 @@ mod tests { } for svcr in [1, 3] { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[word, RET_X30]), GuestAddress(0), declared(bytes, svcr, true), @@ -5492,10 +5590,14 @@ mod tests { for bytes in [16, 32, 64, 128, 256] { for target in [TargetCpu::Baseline, TargetCpu::Ssse3] { let profile = profile(bytes, ScalableMode::new(true, true), features()); - let native = - compile_for_profile(&dot_body(word), GUEST_BASE, profile, target) - .unwrap(); - let mut expected = Vec::new(); + let native = crate::testing::context_leaf( + &dot_body(word), + GUEST_BASE, + profile, + target, + ) + .unwrap(); + let mut expected = Code::new(); x86_64::sme::integer_dots::emit( &mut expected, &operand, @@ -5523,7 +5625,7 @@ mod tests { assert_eq!(native.x86_64_code[native.source_map[1].1..], [RET]); } } - assert!(crate::compile(&dot_body(word), GUEST_BASE).is_err()); + assert!(crate::testing::leaf(&dot_body(word), GUEST_BASE).is_err()); } } @@ -5536,7 +5638,7 @@ mod tests { (DOT_WORD, sme_only, "FEAT_SME2"), (DOT_DOUBLEWORD, sme2, "FEAT_SME_I16I64"), ] { - let error = compile_for_profile( + let error = crate::testing::context_leaf( &dot_body(word), GUEST_BASE, profile(bytes, ScalableMode::new(true, true), available), @@ -5553,7 +5655,7 @@ mod tests { (false, true, "streaming mode required"), (true, false, "ZA enable required"), ] { - let error = compile_for_profile( + let error = crate::testing::context_leaf( &dot_body(DOT_WORD), GUEST_BASE, profile(bytes, ScalableMode::new(streaming, za), features()), @@ -5570,7 +5672,7 @@ mod tests { ScalableMode::new(true, true), ); assert!( - compile_for_profile( + crate::testing::context_leaf( &dot_body(DOT_WORD), GUEST_BASE, fixed, @@ -5579,7 +5681,7 @@ mod tests { .is_ok() ); assert!( - compile_for_profile( + crate::testing::context_leaf( &dot_body(DOT_DOUBLEWORD), GUEST_BASE, fixed, @@ -5605,13 +5707,17 @@ mod tests { for word in MATRIX_WORDS { let operand = integer_matrix::decode(word).unwrap(); let source = words(&[word, RET_X30]); - assert!(crate::compile(&source, GuestAddress(0)).is_err()); + assert!(crate::testing::leaf(&source, GuestAddress(0)).is_err()); let legacy = ScalableProfile::new( VectorLength::from_bytes(16).unwrap(), ScalableMode::new(true, true), ); - let legacy_result = - compile_for_profile(&source, GuestAddress(0), legacy, TargetCpu::Baseline); + let legacy_result = crate::testing::context_leaf( + &source, + GuestAddress(0), + legacy, + TargetCpu::Baseline, + ); assert_eq!(legacy_result.is_ok(), !operand.requires_i16i64()); if operand.requires_i16i64() { assert!(legacy_result.unwrap_err().0.contains("FEAT_SME_I16I64")); @@ -5636,7 +5742,7 @@ mod tests { ScalableControls::new(length, false), ) .unwrap(); - let result = compile_for_profile( + let result = crate::testing::context_leaf( &source, GuestAddress(0), profile, @@ -5652,7 +5758,7 @@ mod tests { "word={word:#x} bytes={bytes} sme2={sme2} i16i64={i16i64} sm={streaming} za={za}" ); if let Ok(native) = result { - let mut body = Vec::new(); + let mut body = Code::new(); x86_64::sme::integer_matrix::emit( &mut body, &operand, @@ -5799,8 +5905,10 @@ mod tests { fn assert_declined(word: u32, profile: ScalableProfile, target: TargetCpu) { let bytes = source(&[word, RET_X30]); - let scan = memory_requirements(&bytes, GUEST_BASE, profile, target).unwrap_err(); - let compile = compile_for_profile(&bytes, GUEST_BASE, profile, target).unwrap_err(); + let scan = crate::testing::context_leaf_memory(&bytes, GUEST_BASE, profile, target) + .unwrap_err(); + let compile = + crate::testing::context_leaf(&bytes, GUEST_BASE, profile, target).unwrap_err(); assert_eq!(scan.0, compile.0); } @@ -5814,8 +5922,9 @@ mod tests { ); let profile = declared_profile(true, true, true, true); let bytes = source(&[word, RET_X30]); - let native = compile_for_profile(&bytes, GUEST_BASE, profile, target()).unwrap(); - let mut expected = Vec::new(); + let native = + crate::testing::context_leaf(&bytes, GUEST_BASE, profile, target()).unwrap(); + let mut expected = Code::new(); x86_64::sme::memory::emit( &mut expected, &operand, @@ -5844,7 +5953,8 @@ mod tests { ); assert_eq!(&native.x86_64_code[native.source_map[1].1..], [RET]); assert_eq!( - memory_requirements(&bytes, GUEST_BASE, profile, target()).unwrap(), + crate::testing::context_leaf_memory(&bytes, GUEST_BASE, profile, target()) + .unwrap(), x86_64::sme::memory::requirements(&operand) ); } @@ -5862,7 +5972,7 @@ mod tests { ); assert_declined(word, declared_profile(true, true, false, false), target()); assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[word, RET_X30]), GUEST_BASE, declared_profile(true, false, true, false), @@ -5875,7 +5985,7 @@ mod tests { assert_declined(word, declared_profile(false, true, true, false), target()); assert_declined(word, declared_profile(true, false, true, false), target()); assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[word, RET_X30]), GUEST_BASE, declared_profile(true, true, false, false), @@ -5887,7 +5997,7 @@ mod tests { SmeMemoryOperand::ZaVector(_) => { assert_declined(word, declared_profile(true, false, true, false), target()); assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[word, RET_X30]), GUEST_BASE, declared_profile(false, true, false, false), @@ -5901,7 +6011,7 @@ mod tests { assert_declined(word, declared_profile(true, true, false, false), target()); assert_declined(word, declared_profile(true, true, true, false), target()); assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[word, RET_X30]), GUEST_BASE, declared_profile(false, true, true, true), @@ -5946,7 +6056,7 @@ mod tests { assert_declined(word, profile, target()); } else { assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[word, RET_X30]), GUEST_BASE, profile, @@ -5957,7 +6067,7 @@ mod tests { } } assert!( - compile_for_profile( + crate::testing::context_leaf( &source(&[NOP, RET_X30]), GUEST_BASE, profile, @@ -5982,13 +6092,17 @@ mod tests { } words.push(RET_X30); assert_eq!( - memory_requirements(&source(&words), GUEST_BASE, profile, target()).unwrap(), + crate::testing::context_leaf_memory(&source(&words), GUEST_BASE, profile, target()) + .unwrap(), expected ); - assert!(compile_for_profile(&source(&words), GUEST_BASE, profile, target()).is_ok()); + assert!( + crate::testing::context_leaf(&source(&words), GUEST_BASE, profile, target()) + .is_ok() + ); } - // Append to extended/sme_memory_tests.rs; reuse its source/profile/target helpers. + // Append to scalable_context/sme_memory_tests.rs; reuse its source/profile/target helpers. #[test] fn prepared_memory_metadata_retains_per_pc_features_helpers_and_quantities() { @@ -6008,7 +6122,7 @@ mod tests { ZT_LOAD, RET_X30, ]; - let prepared = prepare_leaf( + let prepared = crate::testing::prepared_context_leaf( &source(&words), GUEST_BASE, declared_profile(true, true, true, true), @@ -6088,7 +6202,7 @@ mod tests { ], ), ] { - let prepared = prepare_leaf( + let prepared = crate::testing::prepared_context_leaf( &source(&words), GUEST_BASE, declared_profile(false, true, sme2, sme2), @@ -6143,7 +6257,7 @@ mod tests { ); for word in [TABLE_SELECT, TABLE_ZIP_PAIR_Q, TABLE_ZIP_QUAD_Q, 0xc165e000] { assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0x1000), legacy, @@ -6200,7 +6314,7 @@ mod tests { )); let legacy = ScalableProfile::new(short, ScalableMode::new(true, true)); let scalar_word = TABLE_LOOKUP | (2 << 12); - let error = compile_for_profile( + let error = crate::testing::context_leaf( &words(&[scalar_word, RET_X30]), GuestAddress(0x1000), legacy, @@ -6219,7 +6333,7 @@ mod tests { table_features(), zt0_enabled, ); - let error = compile_for_profile( + let error = crate::testing::context_leaf( &words(&[TABLE_LOOKUP, RET_X30]), GuestAddress(0x1000), profile, @@ -6230,7 +6344,7 @@ mod tests { } let profile = table_profile(16, ScalableMode::new(true, true), table_features(), true); assert!( - compile_for_profile( + crate::testing::context_leaf( &words(&[TABLE_LOOKUP, RET_X30]), GuestAddress(0x1000), profile, @@ -6248,12 +6362,16 @@ mod tests { let complete = table_profile(16, ScalableMode::new(true, true), table_features(), true); for word in [0xc09c4000, 0xc09c8000, 0xc09a4000, 0xc09a9000] { let input = words(&[word, RET_X30]); - let error = - compile_for_profile(&input, GuestAddress(0x1000), base, TargetCpu::Baseline) - .unwrap_err(); + let error = crate::testing::context_leaf( + &input, + GuestAddress(0x1000), + base, + TargetCpu::Baseline, + ) + .unwrap_err(); assert!(error.0.contains("FEAT_SME2p1")); assert!( - compile_for_profile( + crate::testing::context_leaf( &input, GuestAddress(0x1000), complete, @@ -6276,9 +6394,13 @@ mod tests { table_features(), false, ); - let error = - compile_for_profile(&input, GuestAddress(0x1000), short, TargetCpu::Baseline) - .unwrap_err(); + let error = crate::testing::context_leaf( + &input, + GuestAddress(0x1000), + short, + TargetCpu::Baseline, + ) + .unwrap_err(); assert!(error.0.contains("require SVL")); let valid = table_profile( minimum, @@ -6287,8 +6409,13 @@ mod tests { false, ); assert!( - compile_for_profile(&input, GuestAddress(0x1000), valid, TargetCpu::Baseline) - .is_ok() + crate::testing::context_leaf( + &input, + GuestAddress(0x1000), + valid, + TargetCpu::Baseline + ) + .is_ok() ); } } @@ -6302,7 +6429,7 @@ mod tests { 0xc165e001, 0xc175e001, 0xc136e002, 0xc137e002, 0xc120d001, 0xc120d401, 0xc136e000, 0xc137e000, 0xc120d000, 0xc120d400, ] { - let result = compile_for_profile( + let result = crate::testing::context_leaf( &words(&[word, RET_X30]), GuestAddress(0x1000), profile, @@ -6327,7 +6454,7 @@ mod tests { ScalableFeatures::of(ScalableFeature::Sme), false, ); - let error = compile_for_profile( + let error = crate::testing::context_leaf( &words(&[TABLE_SELECT, RET_X30]), GuestAddress(0x1000), sme_only, @@ -6337,7 +6464,7 @@ mod tests { assert!(error.0.contains("FEAT_SME2")); let non_streaming = table_profile(16, ScalableMode::new(false, false), table_features(), false); - let error = compile_for_profile( + let error = crate::testing::context_leaf( &words(&[TABLE_SELECT, RET_X30]), GuestAddress(0x1000), non_streaming, diff --git a/crates/stela-compiler/src/extended/admission.rs b/crates/stela-compiler/src/scalable_context/admission.rs similarity index 97% rename from crates/stela-compiler/src/extended/admission.rs rename to crates/stela-compiler/src/scalable_context/admission.rs index 6fb57483d7..3a9adeb93d 100644 --- a/crates/stela-compiler/src/extended/admission.rs +++ b/crates/stela-compiler/src/scalable_context/admission.rs @@ -1,4 +1,5 @@ //! Decoding one instruction and admitting it under a scalable profile. +use crate::aarch64::Unsupported; use alloc::{format, vec::Vec}; use super::{Decoded, ScalableProfile, ordinary_permitted}; @@ -69,8 +70,12 @@ impl Admission<'_> { } } - fn operand(&self, decoded: Result, encoding: &str) -> Result { - decoded.map_err(|()| self.error(&format!("reserved {encoding} encoding"))) + fn operand( + &self, + decoded: Result, + encoding: &str, + ) -> Result { + decoded.map_err(|Unsupported| self.error(&format!("reserved {encoding} encoding"))) } fn require(&mut self, features: ScalableFeatures) -> Result<(), CompileError> { @@ -89,7 +94,7 @@ impl Admission<'_> { /// The common streaming SVE admission: a valid operand, streaming mode and SME. fn streaming_sme( &mut self, - decoded: Result, + decoded: Result, encoding: &str, ) -> Result { let operand = self.operand(decoded, encoding)?; @@ -273,7 +278,7 @@ pub(super) fn decode_recording_features( if let Some(decoded) = integer_products::decode(word) { let operand = check.streaming_sme(decoded, "streaming integer product")?; x86_64::sve::integer_products::validate(operand) - .map_err(|()| check.error("invalid streaming integer product operand"))?; + .map_err(|Unsupported| check.error("invalid streaming integer product operand"))?; return Ok(Decoded::IntegerProducts(operand)); } if let Some(operand) = integer_dots::decode(word) { diff --git a/crates/stela-compiler/src/scalable_context/block.rs b/crates/stela-compiler/src/scalable_context/block.rs new file mode 100644 index 0000000000..4052967764 --- /dev/null +++ b/crates/stela-compiler/src/scalable_context/block.rs @@ -0,0 +1,469 @@ +//! Blocks compiled with an execution context. A service exit returns the PC of +//! the instruction still to execute. +use super::{Decoded, INSTRUCTION_BYTES, ScalableProfile, context_wrapper, decode}; +use crate::{ + CompileError, GuestAddress, Lifter, NativeBlock, Options, TargetCpu, + aarch64::{Decoder, Operation, floating::features::NumericalFeatures}, + block::{ + self, BlockProfile, CompilationPlan, CompiledBlock, ExitKind, MAX_BLOCK_INSTRUCTIONS, + scalable::{ + AdmittedScalableNumericalInstruction, ScalableNumericalOperation, + admit_scalable_numerical_instruction, decode_scalable_numerical_instruction, + }, + }, + context::memory::MemoryRequirements, + x86_64, +}; +use alloc::boxed::Box; +use alloc::format; +use alloc::string::ToString; +use alloc::vec::Vec; + +enum Terminal { + /// An ordinary block of the one terminal instruction. + Shared(Box), + Numerical(AdmittedScalableNumericalInstruction), +} + +/// Existing Ordinary traps remain ordinary boundaries. Other typed services +/// cannot acquire permission from a successful decode or memory-effect result. +fn reject_unavailable_service(pc: GuestAddress, word: u32) -> Result<(), CompileError> { + if block::decode_trap(pc, word)?.is_some() { + return Ok(()); + } + if block::decode_system_instruction(pc, word)?.is_some() + || block::decode_pointer_authentication(pc, word)?.is_some() + || block::decode_clock_instruction(pc, word)?.is_some() + || block::decode_thread_register_instruction(pc, word)?.is_some() + || crate::amx::decode(pc, word)?.is_some() + { + return Err(CompileError(format!( + "context block service is not integrated at {:#x}", + pc.0 + ))); + } + Ok(()) +} + +fn shared_terminal( + bytes: &[u8; INSTRUCTION_BYTES], + pc: GuestAddress, + target: TargetCpu, +) -> Result, CompileError> { + if let Ok(instruction) = Decoder.lift(pc, u32::from_le_bytes(*bytes)) + && matches!(instruction.operation, Operation::FloatingPoint(_)) + { + return Ok(None); + } + let analysis = block::analyze_with_profile(bytes, pc, BlockProfile::ORDINARY) + .map_err(|error| CompileError(error.to_string()))?; + // The ordinary scalar numerical boundary is deliberately excluded until + // its low-V/upper-Z effects have been integrated in context mode. + let permitted = analysis.trap.is_some() + || analysis.dynamic_edge.is_some() + || (analysis.terminator_pc.is_some() && !analysis.static_successors.is_empty()); + if permitted { + CompilationPlan::new(bytes, pc, &Options::new(BlockProfile::ORDINARY, target)).map(Some) + } else { + Ok(None) + } +} + +fn is_transfer(operation: &Operation) -> bool { + matches!( + operation, + Operation::Branch { .. } + | Operation::BranchCondition { .. } + | Operation::BranchZero { .. } + | Operation::BranchBit { .. } + | Operation::Return + ) +} + +/// A decoded context block prefix. Direct RAM, AdvSIMD/FP, mode writes and +/// MOVPRFX are refused as in the context leaf compiler. +pub struct Prefix { + instructions: Vec<(GuestAddress, Decoded)>, + terminal: Option, + next_pc: GuestAddress, + source_bytes: usize, + scalable: ScalableProfile, + numerical: NumericalFeatures, + target: TargetCpu, +} + +impl Prefix { + /// Decode a block prefix. `numerical` must match the guest identity the + /// runtime uses for completion. + pub(crate) fn decode( + source: &[u8], + base: GuestAddress, + scalable: ScalableProfile, + numerical: NumericalFeatures, + target: TargetCpu, + ) -> Result { + if source.is_empty() + || !source.len().is_multiple_of(INSTRUCTION_BYTES) + || !base.0.is_multiple_of(INSTRUCTION_BYTES as u64) + || source.len() / INSTRUCTION_BYTES > MAX_BLOCK_INSTRUCTIONS + { + return Err(CompileError( + "context block input must be aligned, nonempty and bounded".into(), + )); + } + let mut instructions = Vec::new(); + let mut terminal = None; + let mut next_pc = base; + let mut source_bytes = 0; + for bytes in source.as_chunks::().0 { + let pc = next_pc; + next_pc = GuestAddress( + pc.0.checked_add(INSTRUCTION_BYTES as u64) + .ok_or_else(|| CompileError("context block guest address overflow".into()))?, + ); + source_bytes += INSTRUCTION_BYTES; + let word = u32::from_le_bytes(*bytes); + reject_unavailable_service(pc, word)?; + if let Some(numerical_instruction) = decode_scalable_numerical_instruction(pc, word)? { + let admitted = admit_scalable_numerical_instruction( + numerical_instruction, + scalable, + numerical, + )?; + terminal = Some(Terminal::Numerical(admitted)); + break; + } + match decode(pc, word, scalable, target) { + Ok(instruction) + if instruction.memory_requirements() != MemoryRequirements::default() => + { + return Err(CompileError(format!( + "context block memory entry is not integrated at {:#x}", + pc.0 + ))); + } + Ok(Decoded::Ordinary(instruction)) if is_transfer(&instruction.operation) => { + terminal = shared_terminal(bytes, pc, target)? + .map(|plan| Terminal::Shared(Box::new(plan))); + debug_assert!( + terminal.is_some(), + "ordinary transfer has a shared boundary" + ); + break; + } + Ok(instruction) => instructions.push((pc, instruction)), + Err(error) => { + if let Some(shared) = shared_terminal(bytes, pc, target)? { + terminal = Some(Terminal::Shared(Box::new(shared))); + break; + } + return Err(error); + } + } + } + Ok(Self { + instructions, + terminal, + next_pc, + source_bytes, + scalable, + numerical, + target, + }) + } + + pub(crate) const fn source_bytes(&self) -> usize { + self.source_bytes + } + + pub(crate) fn emit(self) -> Result { + let target = self.target; + let vector_length = self.scalable.vector_length(); + let mut code = context_wrapper(); + let mut source_map = + Vec::with_capacity(self.instructions.len() + usize::from(self.terminal.is_some())); + let mut fixups = Vec::new(); + for (pc, instruction) in self.instructions { + source_map.push((pc, code.len())); + super::emit_decoded( + &mut code, + pc, + instruction, + self.scalable, + target, + &mut fixups, + )?; + } + debug_assert!(fixups.is_empty(), "context block prefix cannot transfer"); + match self.terminal { + Some(Terminal::Shared(plan)) => { + let shared = plan.compile()?; + let offset = code.len(); + source_map.extend( + shared + .native + .source_map + .into_iter() + .map(|(pc, at)| (pc, at + offset)), + ); + code.extend(shared.native.x86_64_code); + } + Some(Terminal::Numerical(instruction)) => { + let pc = instruction.instruction_pc(); + source_map.push((pc, code.len())); + let emitted = match *instruction.operation() { + ScalableNumericalOperation::Sve(operation) => x86_64::sve::floating::emit( + &mut code, + instruction.word(), + operation, + vector_length, + self.numerical, + pc, + target, + )?, + ScalableNumericalOperation::SmeExtremaScale(operand) => { + x86_64::sme::extrema_scale::emit( + &mut code, + operand, + vector_length, + self.numerical, + pc, + target, + )? + } + ScalableNumericalOperation::SmeVector(_) + | ScalableNumericalOperation::SmeMatrix(_) + | ScalableNumericalOperation::FixedFp8Conversion(_) + | ScalableNumericalOperation::SmeFp8Conversion(_) + | ScalableNumericalOperation::SmeFp8Matrix(_) => false, + }; + if emitted { + // The guarded family mapping owns the exact-PC cold exit. + // Only its committed fast path reaches the continuation. + x86_64::block::direct_exit( + &mut code, + instruction.next_pc(), + ExitKind::Fallthrough, + ); + } else { + x86_64::block::direct_exit(&mut code, pc, ExitKind::ScalableNumerical); + } + } + None => x86_64::block::direct_exit(&mut code, self.next_pc, ExitKind::Fallthrough), + } + Ok(CompiledBlock { + native: NativeBlock { + x86_64_code: code.into_bytes(), + source_map, + }, + source_bytes: self.source_bytes, + direct_exits: Vec::new(), + fault_recovery: Vec::new(), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::aarch64::scalable::{ScalableMode, VectorLength}; + use crate::block::Features; + use alloc::format; + use alloc::string::ToString; + use alloc::vec; + use alloc::vec::Vec; + + const BASE: GuestAddress = GuestAddress(0x1000); + const ADD_X5_ONE: u32 = 0x9100_04a5; + const FADD_Z0_SINGLE: u32 = 0x6580_8020; + const SVC: u32 = 0xd400_0001; + const BRK: u32 = 0xd420_0000; + const ERET: u32 = 0xd69f_03e0; + const IRG: u32 = 0x9ac0_1000; + const PACIBSP: u32 = 0xd503_237f; + const CNTVCT: u32 = 0xd53b_e040; + const TPIDRRO: u32 = 0xd53b_d060; + const RET: u32 = 0xd65f_03c0; + const PACGA_X1_X2_X3: u32 = 0x9ac3_3041; + const LDRAA_X1_X2: u32 = 0xf820_0441; + const LDRAB_X1_X2: u32 = 0xf8a0_0441; + const SERVICE_WORDS: &[u32] = &[ + ERET, + IRG, + PACIBSP, + CNTVCT, + TPIDRRO, + PACGA_X1_X2_X3, + LDRAA_X1_X2, + LDRAB_X1_X2, + ]; + + fn source(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() + } + + const CONTEXT_BLOCK: BlockProfile = BlockProfile::new(Features::CONTEXT); + + fn scalable() -> ScalableProfile { + ScalableProfile::new( + VectorLength::from_bytes(16).unwrap(), + ScalableMode::new(true, false), + ) + } + + fn context_block( + source: &[u8], + base: GuestAddress, + profile: BlockProfile, + target: TargetCpu, + ) -> Result { + crate::compile( + source, + base, + &Options::new(profile, target) + .with_scalable(scalable()) + .with_numerical_features(NumericalFeatures::default()), + ) + } + + #[test] + fn context_blocks_refuse_other_services() { + for services in [ + BlockProfile::new(Features::SYSTEM), + BlockProfile::new(Features::POINTER_AUTHENTICATION), + BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)), + BlockProfile::new(Features::THREAD_REGISTERS.union(Features::AMX)), + BlockProfile::new( + Features::POINTER_AUTHENTICATION + .union(Features::THREAD_REGISTERS) + .union(Features::AMX), + ), + BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)), + ] { + let error = context_block( + &source(&[RET]), + BASE, + BlockProfile::new(Features::CONTEXT | services.features()), + TargetCpu::Baseline, + ) + .unwrap_err(); + assert!(error.to_string().contains("no emitter implements")); + } + } + + #[test] + fn ordinary_trap_extent_stays_distinct_from_forbidden_system_completion() { + for trap in [SVC, BRK] { + let compiled = context_block( + &source(&[ADD_X5_ONE, trap, ERET]), + BASE, + CONTEXT_BLOCK, + TargetCpu::Baseline, + ) + .unwrap(); + assert_eq!(compiled.source_bytes, 2 * INSTRUCTION_BYTES); + assert_eq!( + compiled + .native + .source_map + .iter() + .map(|row| row.0) + .collect::>(), + [BASE, GuestAddress(BASE.0 + INSTRUCTION_BYTES as u64)] + ); + } + for &service in SERVICE_WORDS { + for words in [vec![service, RET], vec![ADD_X5_ONE, service, RET]] { + let offset = if words[0] == ADD_X5_ONE { + INSTRUCTION_BYTES + } else { + 0 + }; + let error = + context_block(&source(&words), BASE, CONTEXT_BLOCK, TargetCpu::Baseline) + .unwrap_err(); + assert!(error.to_string().contains("service is not integrated")); + assert!( + error + .to_string() + .contains(&format!("{:#x}", BASE.0 + offset as u64)) + ); + } + } + } + + #[test] + fn unconsumed_service_after_numerical_boundary_does_not_expand_extent() { + for &service in SERVICE_WORDS { + let compiled = context_block( + &source(&[ADD_X5_ONE, FADD_Z0_SINGLE, service]), + BASE, + CONTEXT_BLOCK, + TargetCpu::Baseline, + ) + .unwrap(); + assert_eq!(compiled.source_bytes, 2 * INSTRUCTION_BYTES); + assert_eq!(compiled.native.source_map.len(), 2); + assert_eq!( + compiled.native.source_map[1].0, + GuestAddress(BASE.0 + INSTRUCTION_BYTES as u64) + ); + } + } + + #[test] + fn strict_ordinary_ram_atomic_legacy_fp_and_prefix_declines_stay_explicit() { + const LDR_X0_X1: u32 = 0xf940_0020; + const CAS_X0_X1_X2: u32 = 0xc8a0_7c41; + const FADD_S0_S1_S2: u32 = 0x1e22_2820; + const MOVPRFX_Z0_Z1: u32 = 0x0420_bc20; + for word in [LDR_X0_X1, CAS_X0_X1_X2, FADD_S0_S1_S2, MOVPRFX_Z0_Z1] { + assert!( + context_block( + &source(&[ADD_X5_ONE, word, RET]), + BASE, + CONTEXT_BLOCK, + TargetCpu::Baseline, + ) + .is_err() + ); + } + } + #[test] + fn movprfx_pairs_remain_leaf_only_and_numerical_followers_decline() { + const UNPREDICATED_PREFIX: u32 = 0x0420_bc20; + const ZEROING_PREFIX: u32 = 0x0410_2020; + const MERGING_PREFIX: u32 = 0x0411_2020; + const AND_DESTRUCTIVE: u32 = 0x041a_0040; + let block_profile = CONTEXT_BLOCK; + for prefix in [UNPREDICATED_PREFIX, ZEROING_PREFIX, MERGING_PREFIX] { + let bytes = source(&[prefix, AND_DESTRUCTIVE, RET]); + let leaf = crate::testing::context_leaf(&bytes, BASE, scalable(), TargetCpu::Baseline) + .unwrap(); + assert_eq!( + leaf.source_map.iter().map(|row| row.0).collect::>(), + [ + BASE, + GuestAddress(BASE.0 + INSTRUCTION_BYTES as u64), + GuestAddress(BASE.0 + 2 * INSTRUCTION_BYTES as u64), + ] + ); + let error = + context_block(&bytes, BASE, block_profile, TargetCpu::Baseline).unwrap_err(); + assert!(error.to_string().contains(&format!("{:#x}", BASE.0))); + } + let error = crate::testing::context_leaf( + &source(&[UNPREDICATED_PREFIX, FADD_Z0_SINGLE, RET]), + BASE, + scalable(), + TargetCpu::Baseline, + ) + .unwrap_err(); + assert!(error.to_string().contains("unsupported follower")); + assert!( + error + .to_string() + .contains(&format!("{:#x}", BASE.0 + INSTRUCTION_BYTES as u64)) + ); + } +} diff --git a/crates/stela-compiler/src/extended/debug_movement.rs b/crates/stela-compiler/src/scalable_context/debug_movement.rs similarity index 92% rename from crates/stela-compiler/src/extended/debug_movement.rs rename to crates/stela-compiler/src/scalable_context/debug_movement.rs index 7d91c70c82..670dbf96e8 100644 --- a/crates/stela-compiler/src/extended/debug_movement.rs +++ b/crates/stela-compiler/src/scalable_context/debug_movement.rs @@ -1,5 +1,6 @@ //! MOVT (vector to ZT0) prepared for execution from the halted-debug ITR. -use super::{MOV_R15_RSI, POP_R15, PUSH_R15, RET, ScalableProfile}; +use super::ScalableProfile; +use crate::x86_64::asm::{Code, Gpr, Size}; use crate::{ CompileError, GuestAddress, aarch64::{ @@ -12,9 +13,10 @@ use crate::{ }, sme::movement::{self, Direction, Kind, Operand}, }, - context::CONTEXT_LEAF_ABI, + block::{BlockProfile, Features}, x86_64, }; +use alloc::string::String; use alloc::vec; use alloc::vec::Vec; @@ -54,8 +56,9 @@ impl PreparedDebugMovement { pub const fn recipe(&self) -> Recipe { self.recipe } - pub const fn abi(&self) -> &'static str { - CONTEXT_LEAF_ABI + /// The context leaf ABI the code is called with. + pub fn abi(&self) -> String { + BlockProfile::new(Features::LEAF | Features::CONTEXT).abi() } pub fn code(&self) -> &[u8] { &self.code @@ -108,25 +111,27 @@ pub fn prepare( ), GuestMemoryQuantity::None, )]); - let mut code = Vec::new(); + let mut code = Code::new(); let discarded = direction == Direction::FromZa && register == ZERO_REGISTER; if !discarded { - code.extend(PUSH_R15); - code.extend(MOV_R15_RSI); + let mut asm = code.asm(); + asm.push(Gpr::R15); + asm.mov(Size::Qword, Gpr::R15, Gpr::Rsi); } let native_offset = code.len(); x86_64::sme::movement::emit_debug_table_gpr(&mut code, &operand, recipe) .map_err(|error| CompileError(error.into()))?; + let mut asm = code.asm(); if !discarded { - code.extend(POP_R15); + asm.pop(Gpr::R15); } - code.push(RET); + asm.ret(); Ok(PreparedDebugMovement { word, operand, profile, recipe, - code, + code: code.into_bytes(), word_to_native: [(EXTERNAL_WORD_ORDINAL, native_offset)], requirements, }) @@ -178,7 +183,7 @@ mod tests { fn discarded_read_emits_only_transport_return_after_runtime_checks() { for recipe in [Recipe::Scalar, Recipe::Sse2Comparison] { let output = prepare(FROM_ZT0 | 31, profile(false), recipe).unwrap(); - assert_eq!(output.code(), &[RET]); + assert_eq!(output.code(), &[0xc3]); } } #[test] diff --git a/crates/stela-compiler/src/extended/decoded.rs b/crates/stela-compiler/src/scalable_context/decoded.rs similarity index 98% rename from crates/stela-compiler/src/extended/decoded.rs rename to crates/stela-compiler/src/scalable_context/decoded.rs index c07281a1a7..bd077af01c 100644 --- a/crates/stela-compiler/src/extended/decoded.rs +++ b/crates/stela-compiler/src/scalable_context/decoded.rs @@ -1,4 +1,6 @@ //! Decoded instructions and the state, memory and prefix requirements they carry. +use crate::aarch64::Unsupported; +use crate::x86_64::asm::Code; use alloc::{boxed::Box, format, vec::Vec}; use crate::{ @@ -232,7 +234,7 @@ impl Decoded { pub(super) fn prefix_requirement( &self, original_word: u32, - ) -> Result, ()> { + ) -> Result, Unsupported> { match self { Self::PrefetchHint => Ok(None), Self::SharedMemory(_) @@ -385,7 +387,7 @@ impl Decoded { } pub(crate) fn emit_checked_ordinary( &self, - code: &mut Vec, + code: &mut Code, pc: GuestAddress, target: TargetCpu, fixups: &mut Vec<(GuestAddress, GuestAddress, usize)>, @@ -527,7 +529,7 @@ mod checked_register_tests { use crate::{ Lifter, aarch64::Decoder, - block::{BlockProfile, CheckedMemoryProfile, CompilationPlan}, + block::{BlockProfile, CheckedMemoryProfile, CompilationPlan, Features}, }; use alloc::vec; @@ -569,7 +571,7 @@ mod checked_register_tests { let decoded = Decoded::checked_ordinary(instruction.clone(), profile).unwrap(); assert!(matches!(decoded, Decoded::PrefetchHint)); assert_eq!(decoded.memory_requirements(), Default::default()); - let mut code = Vec::new(); + let mut code = Code::new(); let mut recovery = Vec::new(); decoded .emit_checked_ordinary(&mut code, pc, TargetCpu::Baseline, &mut recovery) @@ -592,8 +594,11 @@ mod checked_register_tests { let compiled = CompilationPlan::new( &source, pc, - BlockProfile::SystemModeSharedV1(CheckedMemoryProfile::SpAlignmentDisabled), - TargetCpu::Baseline, + &crate::Options::new( + BlockProfile::new(Features::SYSTEM_MODE) + .with_checked_memory(CheckedMemoryProfile::SpAlignmentDisabled), + TargetCpu::Baseline, + ), ) .unwrap() .compile() @@ -677,8 +682,10 @@ mod checked_register_tests { let plan = CompilationPlan::new( &source, base, - BlockProfile::SystemModeSharedV1(specialization), - TargetCpu::Baseline, + &crate::Options::new( + BlockProfile::new(Features::SYSTEM_MODE).with_checked_memory(specialization), + TargetCpu::Baseline, + ), ) .unwrap(); assert_eq!(plan.source_bytes(), 24); @@ -744,7 +751,7 @@ mod checked_register_tests { decoded.memory_requirements().required_flags & flags::ASIMD, flags::ASIMD ); - let mut code = Vec::new(); + let mut code = Code::new(); decoded .emit_checked_ordinary(&mut code, pc, TargetCpu::Baseline, &mut Vec::new()) .unwrap(); diff --git a/crates/stela-compiler/src/extended/prefix.rs b/crates/stela-compiler/src/scalable_context/prefix.rs similarity index 98% rename from crates/stela-compiler/src/extended/prefix.rs rename to crates/stela-compiler/src/scalable_context/prefix.rs index 34d3c1d21d..9bb6a2154b 100644 --- a/crates/stela-compiler/src/extended/prefix.rs +++ b/crates/stela-compiler/src/scalable_context/prefix.rs @@ -1,4 +1,5 @@ //! MOVPRFX pairs compiled as one unit with their follower. +use crate::aarch64::Unsupported; use super::{Decoded, INSTRUCTION_BYTES, ScalableProfile, decode_recording_features}; use crate::{ @@ -117,7 +118,7 @@ pub(super) fn decode_pair( follower.require_total_inline_prefix(follower_pc)?; let requirement = follower .prefix_requirement(follower_word) - .map_err(|()| CompileError("MOVPRFX follower source/operand mismatch".into()))? + .map_err(|Unsupported| CompileError("MOVPRFX follower source/operand mismatch".into()))? .ok_or_else(|| { CompileError(format!( "MOVPRFX pair validation: follower metadata not reviewed at {:#x}", @@ -240,7 +241,7 @@ mod tests { #[test] fn direct_follower_targets_retain_the_follower_map_entry() { for bytes in [16, 32, 64, 128, 256] { - let native = super::super::super::compile_for_profile( + let native = crate::testing::context_leaf( &source(&[BRANCH_TO_FOLLOWER, PREFIX, AND_DESTRUCTIVE, RET]), BASE, profile(bytes), diff --git a/crates/stela-compiler/src/extended/profile.rs b/crates/stela-compiler/src/scalable_context/profile.rs similarity index 100% rename from crates/stela-compiler/src/extended/profile.rs rename to crates/stela-compiler/src/scalable_context/profile.rs diff --git a/crates/stela-compiler/src/state.rs b/crates/stela-compiler/src/state.rs index 54583d524a..35e62c33a1 100644 --- a/crates/stela-compiler/src/state.rs +++ b/crates/stela-compiler/src/state.rs @@ -1,11 +1,9 @@ //! Guest register state, shared by hosted and freestanding execution. -/// Native code requires the direct ordinary-RAM profile documented in compiler.md. -pub const NATIVE_ABI: &str = "x86_64-sysv-guest-state-v3-direct-ram"; - -/// Native ABI v3: System V x86-64 `void function(GuestState *state)`. Registers -/// enter and leave native code in this layout. Only NZCV bits 31:28 of PSTATE -/// are held here. V registers are little-endian pairs of 64-bit halves. +/// The register state every compiled function takes in RDI +/// ([`crate::block::BlockProfile::abi`] names the ABI). Registers enter and +/// leave native code in this layout. Only NZCV bits 31:28 of PSTATE are held +/// here. V registers are little-endian pairs of 64-bit halves. /// Arithmetic preserves unrelated FPCR/FPSR bits, and register accesses apply /// the declared field masks; saturating integer SIMD sets QC and floating-point /// arithmetic accumulates exception flags. @@ -23,12 +21,15 @@ pub struct GuestState { #[cfg(test)] mod tests { - use super::{GuestState, NATIVE_ABI}; + use super::GuestState; + use crate::block::{BlockProfile, Features}; use core::mem::{align_of, offset_of, size_of}; #[test] fn layout_matches_native_abi() { - assert_eq!(NATIVE_ABI, "x86_64-sysv-guest-state-v3-direct-ram"); + for profile in [BlockProfile::ORDINARY, BlockProfile::new(Features::LEAF)] { + assert!(profile.abi().starts_with("x86_64-sysv-guest-state-v4-")); + } assert_eq!(size_of::(), 784); assert_eq!(align_of::(), 8); assert_eq!(offset_of!(GuestState, x), 0); diff --git a/crates/stela-compiler/src/target.rs b/crates/stela-compiler/src/target.rs index 1c5c87d876..43df776f03 100644 --- a/crates/stela-compiler/src/target.rs +++ b/crates/stela-compiler/src/target.rs @@ -3,72 +3,27 @@ use alloc::borrow::ToOwned; use alloc::format; use alloc::string::String; -#[cfg(all(any(feature = "std", test), target_arch = "x86_64"))] -const CPUID_BASIC_FEATURES: u32 = 1; + const CPUID_AVX_HARDWARE: u32 = 1 << 28; -#[cfg(all(any(feature = "std", test), target_arch = "x86_64"))] -const CPUID_CX16: u32 = 1 << 13; -#[cfg(all(any(feature = "std", test), target_arch = "x86_64"))] -const CPUID_CX8: u32 = 1 << 8; +/// CPUID.1:ECX bit 27: the OS set CR4.OSXSAVE, so XGETBV reads XCR0. +const CPUID_OSXSAVE: u32 = 1 << 27; +/// XCR0 bits 1 and 2: the OS saves XMM and YMM state. +const XCR0_AVX_STATE: u64 = 0x6; +/// XCR0 bits 5 to 7: the OS saves opmask, ZMM_Hi256 and Hi16_ZMM state. +const XCR0_AVX512_STATE: u64 = 0xe0; +/// XCR0 bit 19: the OS saves the extended GPRs R16..R31. +const XCR0_APX_STATE: u64 = 1 << 19; /// Explicit host requirements bind generated code and persistent cache identity. /// SSE tiers are nested; every other capability is independent. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct TargetCpu { tier: SseTier, - pclmulqdq: bool, - fma: bool, - f16c: bool, - popcnt: bool, - bmi1: bool, - aes: bool, - sha: bool, - atomic_load16: bool, - /// An Intel processor: since the P6 family, an unaligned load that lies - /// within one cache line is single-copy atomic (Intel SDM Vol. 3A, - /// 9.1.1, "Guaranteed Atomic Operations"). A 16-byte granule never - /// crosses a line, so an ordered load inside one is a plain load. AMD - /// guarantees this only inside a naturally aligned quadword. - line_atomic: bool, - cx8: bool, - cx16: bool, - avx2: bool, - avx512f: bool, - /// The host runs the instructions on Intel's data operand independent - /// timing list with timing independent of their data: Intel's - /// IA32_UARCH_MISC_CTL.DOITM (MSR 1B01H bit 0, enumerated by - /// IA32_ARCH_CAPABILITIES bit 12) is set on every logical processor that - /// runs guest code, or the processor predates Ice Lake (Core) or - /// Gracemont (Atom) and does not enumerate it. A hosted process can - /// neither read nor set it; the bare-metal boot declares it. AMD - /// documents no equivalent. - doit: bool, - /// Lower for FEAT_DIT's PSTATE.DIT: the listed instructions that have a - /// data-independent lowering (CLZ, CLS, CTZ, CNT, CRC32, CRC32C) compile - /// to instructions on Intel's list, without a branch on or a memory index - /// by their data, at a cost in speed. The LSE atomics, acquire loads, - /// store-releases and barriers become plain loads and stores (no LOCK, - /// XCHG or MFENCE), as for a single agent, so the mode requires that no - /// other agent accesses guest - /// memory while its code runs: the system engine runs one PE at a time, - /// and a multi-threaded process must not use it. A compilation mode, not - /// a host capability, honored on the - /// [`Self::DATA_INDEPENDENT_TIMING_TIERS`]. - data_independent_timing: bool, + /// One bit per [`Feature`]. + features: u64, } -#[derive( - Debug, - Default, - Clone, - Copy, - PartialEq, - Eq, - PartialOrd, - Ord, - serde::Serialize, - serde::Deserialize, -)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] enum SseTier { #[default] Baseline, @@ -77,26 +32,338 @@ enum SseTier { Sse42, } +/// The CPUID leaves and XCR0 value host feature detection reads. Leaves above +/// the maximum CPUID leaf 0 reports read as zero. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct HostCpuid { + /// Leaf 0 EBX, EDX and ECX: the vendor string. + pub vendor: [u32; 3], + /// Leaf 1 ECX. + pub leaf1_ecx: u32, + /// Leaf 1 EDX. + pub leaf1_edx: u32, + /// Leaf 1 EAX: family, model and stepping. + pub leaf1_eax: u32, + /// Leaf 7 subleaf 0 EBX. + pub leaf7_ebx: u32, + /// Leaf 7 subleaf 0 ECX. + pub leaf7_ecx: u32, + /// Leaf 7 subleaf 0 EDX. + pub leaf7_edx: u32, + /// Leaf 7 subleaf 1 EAX. + pub leaf7_1_eax: u32, + /// Leaf 7 subleaf 1 EDX. + pub leaf7_1_edx: u32, + /// Leaf 8000_0001H ECX. + pub extended1_ecx: u32, + /// XCR0, or zero when the OS has not enabled XSAVE ([`CPUID_OSXSAVE`]). + pub xcr0: u64, + /// The OS enables AVX-512 state on a thread's first EVEX instruction, so + /// XCR0 lacks it until then (xnu, which reports usable support in + /// `hw.optional.avx512f`). + pub avx512_on_demand: bool, +} + +impl HostCpuid { + /// Read this processor's CPUID leaves and XCR0, querying leaf 0 once. + #[cfg(target_arch = "x86_64")] + pub fn read() -> Self { + use core::arch::x86_64::{__cpuid, __cpuid_count, CpuidResult}; + let identity = __cpuid(0); + let leaf = |leaf: u32| { + if identity.eax >= leaf { + __cpuid_count(leaf, 0) + } else { + CpuidResult { + eax: 0, + ebx: 0, + ecx: 0, + edx: 0, + } + } + }; + let (leaf1, leaf7) = (leaf(1), leaf(7)); + let leaf7_1 = if identity.eax >= 7 && leaf7.eax >= 1 { + __cpuid_count(7, 1) + } else { + CpuidResult { + eax: 0, + ebx: 0, + ecx: 0, + edx: 0, + } + }; + let extended1_ecx = if __cpuid(0x8000_0000).eax >= 0x8000_0001 { + __cpuid(0x8000_0001).ecx + } else { + 0 + }; + let xcr0 = if leaf1.ecx & CPUID_OSXSAVE != 0 { + // SAFETY: CR4.OSXSAVE is set, so XGETBV with ECX = 0 is defined. + unsafe { core::arch::x86_64::_xgetbv(0) } + } else { + 0 + }; + Self { + vendor: [identity.ebx, identity.edx, identity.ecx], + leaf1_ecx: leaf1.ecx, + leaf1_edx: leaf1.edx, + leaf1_eax: leaf1.eax, + leaf7_ebx: leaf7.ebx, + leaf7_ecx: leaf7.ecx, + leaf7_edx: leaf7.edx, + leaf7_1_eax: leaf7_1.eax, + leaf7_1_edx: leaf7_1.edx, + extended1_ecx, + xcr0, + avx512_on_demand: false, + } + } + + const fn bit(register: u32, bit: u32) -> bool { + register & (1 << bit) != 0 + } + /// AVX hardware with OS-enabled XMM and YMM state. + const fn avx(&self) -> bool { + Self::bit(self.leaf1_ecx, 28) && self.xcr0 & XCR0_AVX_STATE == XCR0_AVX_STATE + } + /// The display family: the base family plus, for family 0FH, the + /// extended family (SDM Vol. 2A, CPUID leaf 1). + const fn family(&self) -> u32 { + let base = (self.leaf1_eax >> 8) & 0xf; + if base == 0xf { + base + ((self.leaf1_eax >> 20) & 0xff) + } else { + base + } + } + /// BMI2. Intel's Pentium and Celeron parts without AVX enumerate BMI1 + /// and BMI2 but fault on their VEX encodings, so an Intel host needs AVX + /// for them (as Rust's `std_detect`). + const fn bmi2(&self) -> bool { + Self::bit(self.leaf7_ebx, 8) + && (!matches!(Vendor::from_cpuid(self.vendor), Vendor::Intel) || self.avx()) + } + /// [`Self::avx512_state`] with AVX-512F. + const fn avx512f(&self) -> bool { + self.avx512_state() && Self::bit(self.leaf7_ebx, 16) + } + /// [`Self::avx`] with OS-enabled opmask and ZMM state. + const fn avx512_state(&self) -> bool { + self.avx() && (self.xcr0 & XCR0_AVX512_STATE == XCR0_AVX512_STATE || self.avx512_on_demand) + } +} + +/// The vendor of a host CPU as its documented memory-ordering guarantees +/// apply, from the CPUID leaf 0 vendor string. This is the compiler's one +/// vendor policy: +/// +/// - Intel (`GenuineIntel`): an unaligned load within one cache line is +/// single-copy atomic (SDM Vol. 3A 9.1.1, [`TargetCpu::LineAtomic`]), and +/// with AVX an aligned 16-byte load is ([`TargetCpu::AtomicLoad16`]). +/// - AMD (`AuthenticAMD`) and Hygon (`HygonGenuine`): with AVX an aligned +/// 16-byte load is single-copy atomic (APM 24593 rev. 3.44 7.3.2); an +/// unaligned load is atomic only inside an aligned quadword. Hygon's cores +/// are licensed AMD Zen designs that follow AMD's manuals, as Linux treats +/// them (`arch/x86/kernel/cpu/hygon.c`). +/// - Zhaoxin (` Shanghai `), Centaur (`CentaurHauls`) and every other +/// vendor: no published guarantee for either, so their hosts take the +/// CMPXCHG16B and split-load paths until one is documented. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Vendor { + Intel, + Amd, + Other, +} + +impl Vendor { + /// The vendor of the CPUID leaf 0 EBX, EDX and ECX values `vendor`. + pub const fn from_cpuid(vendor: [u32; 3]) -> Self { + match vendor { + TargetCpu::INTEL_VENDOR => Self::Intel, + TargetCpu::AMD_VENDOR | TargetCpu::HYGON_VENDOR => Self::Amd, + _ => Self::Other, + } + } +} + +/// A feature that detection leaves to the caller: the bare-metal boot +/// declares it, or it is a compilation mode. +const fn declared(_: &HostCpuid) -> bool { + false +} + +/// Declares the optional features, in canonical identity order: each one's +/// `TargetCpu` constant, `with_*` builder, `+name` in [`TargetCpu::id`] and +/// CPUID probe. Each feature's bit is its position. The names and their order +/// spell the target identities that persistent caches and users key on; the +/// compilation modes stay last. +macro_rules! features { + ($($(#[$doc:meta])* $constant:ident, $with:ident, $name:literal, $probe:expr;)*) => { + /// One optional feature of a [`TargetCpu`], numbered by its bit. + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + #[allow(clippy::upper_case_acronyms)] + enum Feature { + $($constant,)* + } + + /// Each feature with its `+name` and probe, in identity order. + const FEATURES: &[(Feature, &str, fn(&HostCpuid) -> bool)] = + &[$((Feature::$constant, $name, $probe),)*]; + + // Keep the published feature names and their cache identities. + #[allow(non_upper_case_globals)] + impl TargetCpu { + $( + $(#[$doc])* + pub const $constant: Self = Self::Baseline.with_feature(Feature::$constant); + pub const fn $with(self) -> Self { + self.with_feature(Feature::$constant) + } + )* + } + }; +} + +features! { + /// Minimum requirements for legacy XMM PCLMULQDQ, independent of SSE tiers. + Pclmulqdq, with_pclmulqdq, "+pclmulqdq", |cpu| HostCpuid::bit(cpu.leaf1_ecx, 1); + /// Minimum requirements for VEX FMA3, including OS-enabled AVX register state. + Fma, with_fma, "+fma", |cpu| cpu.avx() && HostCpuid::bit(cpu.leaf1_ecx, 12); + /// Minimum requirements for F16C, including OS-enabled AVX register state. + F16c, with_f16c, "+f16c", |cpu| cpu.avx() && HostCpuid::bit(cpu.leaf1_ecx, 29); + Popcnt, with_popcnt, "+popcnt", |cpu| HostCpuid::bit(cpu.leaf1_ecx, 23); + /// BMI1. Intel's Pentium and Celeron parts without AVX enumerate BMI1 but + /// fault on its VEX encodings, so an Intel host needs AVX for it (as + /// Rust's `std_detect`). + Bmi1, with_bmi1, "+bmi1", |cpu| { + HostCpuid::bit(cpu.leaf7_ebx, 3) + && (!matches!(Vendor::from_cpuid(cpu.vendor), Vendor::Intel) || cpu.avx()) + }; + /// Minimum requirements for legacy XMM AES instructions, independent of SSE tiers. + Aes, with_aes, "+aes", |cpu| HostCpuid::bit(cpu.leaf1_ecx, 25); + /// Minimum requirements for legacy XMM SHA instructions, independent of SSE tiers. + Sha, with_sha, "+sha", |cpu| HostCpuid::bit(cpu.leaf7_ebx, 29); + /// Aligned 16-byte atomic loads: the [`Vendor`] guarantee with AVX hardware. + /// Lowering uses legacy SSE2, independently of OS-enabled AVX state. + AtomicLoad16, with_atomic_load16, "+atomic-load16", |cpu| { + TargetCpu::atomic_load16_guaranteed(cpu.vendor, cpu.leaf1_ecx) + }; + /// CMPXCHG8B, independently enumerated for the W-pair optimized recipe. + Cx8, with_cx8, "+cx8", |cpu| HostCpuid::bit(cpu.leaf1_edx, 8); + /// CMPXCHG16B, independent of aligned16 load atomicity and AVX state. + Cx16, with_cx16, "+cx16", |cpu| HostCpuid::bit(cpu.leaf1_ecx, 13); + /// AVX2 integer recipes, including OS-enabled XMM/YMM register state. + Avx2, with_avx2, "+avx2", |cpu| cpu.avx() && HostCpuid::bit(cpu.leaf7_ebx, 5); + /// EVEX.512 AVX-512 Foundation, including OS-enabled opmask and ZMM state. + Avx512f, with_avx512f, "+avx512f", |cpu| { + cpu.avx512_state() && HostCpuid::bit(cpu.leaf7_ebx, 16) + }; + /// LZCNT (ABM on AMD). + Lzcnt, with_lzcnt, "+lzcnt", |cpu| HostCpuid::bit(cpu.extended1_ecx, 5); + /// BMI2: SHLX/SHRX/SARX/RORX, BZHI, MULX and PDEP/PEXT. + Bmi2, with_bmi2, "+bmi2", HostCpuid::bmi2; + /// BMI2 whose PDEP and PEXT run in hardware: AMD's Zen 1 and Zen 2 (and + /// Hygon's Zen-derived cores) microcode them at tens of cycles. + FastPdep, with_fast_pdep, "+fast-pdep", |cpu| { + let amd = matches!(Vendor::from_cpuid(cpu.vendor), Vendor::Amd); + cpu.bmi2() && !(amd && cpu.family() < 0x19) + }; + /// MOVBE: byte-swapping loads and stores. + Movbe, with_movbe, "+movbe", |cpu| HostCpuid::bit(cpu.leaf1_ecx, 22); + /// GFNI in its legacy SSE encoding (GF2P8AFFINEQB and relatives). + Gfni, with_gfni, "+gfni", |cpu| HostCpuid::bit(cpu.leaf7_ecx, 8); + /// AVX-512VL: EVEX forms on XMM and YMM registers. + Avx512vl, with_avx512vl, "+avx512vl", |cpu| cpu.avx512f() && HostCpuid::bit(cpu.leaf7_ebx, 31); + /// AVX-512BW: byte and word elements and 64-bit opmasks. + Avx512bw, with_avx512bw, "+avx512bw", |cpu| cpu.avx512f() && HostCpuid::bit(cpu.leaf7_ebx, 30); + /// AVX-512CD: VPLZCNTD/Q and VPCONFLICTD/Q. + Avx512cd, with_avx512cd, "+avx512cd", |cpu| cpu.avx512f() && HostCpuid::bit(cpu.leaf7_ebx, 28); + /// AVX-512DQ: quadword multiplies and FP-integer conversions. + Avx512dq, with_avx512dq, "+avx512dq", |cpu| cpu.avx512f() && HostCpuid::bit(cpu.leaf7_ebx, 17); + /// AVX-512 VPOPCNTD/Q. + Avx512vpopcntdq, with_avx512vpopcntdq, "+avx512vpopcntdq", |cpu| { + cpu.avx512f() && HostCpuid::bit(cpu.leaf7_ecx, 14) + }; + /// AVX-512 BITALG: VPOPCNTB/W and VPSHUFBITQMB. + Avx512bitalg, with_avx512bitalg, "+avx512bitalg", |cpu| { + cpu.avx512f() && HostCpuid::bit(cpu.leaf7_ecx, 12) + }; + /// AVX-512 VNNI: VPDPBUSD and VPDPWSSD. + Avx512vnni, with_avx512vnni, "+avx512vnni", |cpu| { + cpu.avx512f() && HostCpuid::bit(cpu.leaf7_ecx, 11) + }; + /// AVX-VNNI: the VEX forms of VPDPBUSD and VPDPWSSD. + AvxVnni, with_avx_vnni, "+avxvnni", |cpu| cpu.avx() && HostCpuid::bit(cpu.leaf7_1_eax, 4); + /// AVX-512 BF16: VDPBF16PS and VCVTNE2PS2BF16. + Avx512bf16, with_avx512bf16, "+avx512bf16", |cpu| { + cpu.avx512f() && HostCpuid::bit(cpu.leaf7_1_eax, 5) + }; + /// AVX-NE-CONVERT: VEX BF16 and FP16 conversions. + AvxNeConvert, with_avx_ne_convert, "+avxneconvert", |cpu| { + cpu.avx() && HostCpuid::bit(cpu.leaf7_1_edx, 5) + }; + /// AVX-512 FP16: half-precision arithmetic. + Avx512fp16, with_avx512fp16, "+avx512fp16", |cpu| { + cpu.avx512f() && HostCpuid::bit(cpu.leaf7_edx, 23) + }; + /// VAES: VEX and EVEX AES rounds on wide vectors. + Vaes, with_vaes, "+vaes", |cpu| cpu.avx() && HostCpuid::bit(cpu.leaf7_ecx, 9); + /// VPCLMULQDQ: carry-less multiplies on wide vectors. + Vpclmulqdq, with_vpclmulqdq, "+vpclmulqdq", |cpu| { + cpu.avx() && HostCpuid::bit(cpu.leaf7_ecx, 10) + }; + /// SHA512: VSHA512RNDS2, VSHA512MSG1 and VSHA512MSG2. + Sha512, with_sha512, "+sha512", |cpu| cpu.avx() && HostCpuid::bit(cpu.leaf7_1_eax, 0); + /// SM3: VSM3RNDS2, VSM3MSG1 and VSM3MSG2. + Sm3, with_sm3, "+sm3", |cpu| cpu.avx() && HostCpuid::bit(cpu.leaf7_1_eax, 1); + /// SM4: VSM4KEY4 and VSM4RNDS4. + Sm4, with_sm4, "+sm4", |cpu| cpu.avx() && HostCpuid::bit(cpu.leaf7_1_eax, 2); + /// APX: sixteen more general-purpose registers (R16..R31) and the + /// REX2 and extended EVEX encodings, with OS-enabled APX state (XCR0 + /// bit 19). + Apx, with_apx, "+apx", |cpu| { + HostCpuid::bit(cpu.leaf7_1_edx, 21) && cpu.xcr0 & XCR0_APX_STATE != 0 + }; + /// An unaligned load that lies within one cache line is single-copy + /// atomic: an Intel processor since the P6 family ([`Vendor`]). A 16-byte + /// granule never crosses a line, so an ordered load inside one is a + /// plain load. + LineAtomic, with_line_atomic, "+line-atomic", |cpu| { + matches!(Vendor::from_cpuid(cpu.vendor), Vendor::Intel) + }; + /// The host runs the instructions on Intel's data operand independent + /// timing list with timing independent of their data: Intel's + /// IA32_UARCH_MISC_CTL.DOITM (MSR 1B01H bit 0, enumerated by + /// IA32_ARCH_CAPABILITIES bit 12) is set on every logical processor that + /// runs guest code, or the processor predates Ice Lake (Core) or + /// Gracemont (Atom) and does not enumerate it. A hosted process can + /// neither read nor set it; the bare-metal boot declares it. AMD + /// documents no equivalent. + Doit, with_doit, "+doit", declared; + /// Code lowered for FEAT_DIT's PSTATE.DIT: the listed instructions that + /// have a data-independent lowering (CLZ, CLS, CTZ, CNT, CRC32, CRC32C) + /// compile to instructions on Intel's list, without a branch on or a + /// memory index by their data, at a cost in speed. The LSE atomics, + /// acquire loads, store-releases and barriers become plain loads and + /// stores (no LOCK, XCHG or MFENCE), as for a single agent, so the mode + /// requires that no other agent accesses guest memory while its code + /// runs: the system engine runs one PE at a time, and a multi-threaded + /// process must not use it. A compilation mode, not a host capability, + /// honored on the [`Self::DATA_INDEPENDENT_TIMING_TIERS`]. + DataIndependentTiming, with_data_independent_timing, "+dit", declared; +} + +/// Features that are compilation modes: part of the identity, not host +/// requirements. +const MODES: u64 = 1 << Feature::DataIndependentTiming as u32; + // Keep the published tier names and their cache identities. #[allow(non_upper_case_globals)] impl TargetCpu { pub const Baseline: Self = Self { tier: SseTier::Baseline, - pclmulqdq: false, - fma: false, - f16c: false, - popcnt: false, - bmi1: false, - aes: false, - sha: false, - atomic_load16: false, - line_atomic: false, - cx8: false, - cx16: false, - avx2: false, - avx512f: false, - doit: false, - data_independent_timing: false, + features: 0, }; pub const Ssse3: Self = Self { tier: SseTier::Ssse3, @@ -110,35 +377,6 @@ impl TargetCpu { tier: SseTier::Sse42, ..Self::Baseline }; - /// Minimum requirements for legacy XMM PCLMULQDQ, independent of SSE tiers. - pub const Pclmulqdq: Self = Self::Baseline.with_pclmulqdq(); - /// Minimum requirements for VEX FMA3, including OS-enabled AVX register state. - pub const Fma: Self = Self::Baseline.with_fma(); - /// Minimum requirements for F16C, including OS-enabled AVX register state. - pub const F16c: Self = Self::Baseline.with_f16c(); - pub const Popcnt: Self = Self::Baseline.with_popcnt(); - pub const Bmi1: Self = Self::Baseline.with_bmi1(); - /// Minimum requirements for legacy XMM AES instructions, independent of SSE tiers. - pub const Aes: Self = Self::Baseline.with_aes(); - /// Minimum requirements for legacy XMM SHA instructions, independent of SSE tiers. - pub const Sha: Self = Self::Baseline.with_sha(); - /// Aligned 16-byte atomic loads: Intel/AMD vendor guarantees with AVX hardware. - /// Lowering uses legacy SSE2, independently of OS-enabled AVX state. - pub const AtomicLoad16: Self = Self::Baseline.with_atomic_load16(); - /// Single-copy atomic unaligned loads within a cache line ([`Self::line_atomic`]). - pub const LineAtomic: Self = Self::Baseline.with_line_atomic(); - /// CMPXCHG8B, independently enumerated for the W-pair optimized recipe. - pub const Cx8: Self = Self::Baseline.with_cx8(); - /// CMPXCHG16B, independent of aligned16 load atomicity and AVX state. - pub const Cx16: Self = Self::Baseline.with_cx16(); - /// AVX2 integer recipes, including OS-enabled XMM/YMM register state. - pub const Avx2: Self = Self::Baseline.with_avx2(); - /// EVEX.512 AVX-512 Foundation, including OS-enabled opmask and ZMM state. - pub const Avx512f: Self = Self::Baseline.with_avx512f(); - /// A host with Intel's data operand independent timing ([`Self::doit`]). - pub const Doit: Self = Self::Baseline.with_doit(); - /// Code lowered for PSTATE.DIT ([`Self::data_independent_timing`]). - pub const DataIndependentTiming: Self = Self::Baseline.with_data_independent_timing(); /// `GenuineIntel` as CPUID leaf 0 returns it in EBX, EDX and ECX, which /// identifies a [`Self::line_atomic`] host. pub const INTEL_VENDOR: [u32; 3] = [ @@ -152,110 +390,74 @@ impl TargetCpu { u32::from_le_bytes(*b"enti"), u32::from_le_bytes(*b"cAMD"), ]; + /// Hygon's vendor identity in CPUID0 EBX, EDX, ECX order. + pub const HYGON_VENDOR: [u32; 3] = [ + u32::from_le_bytes(*b"Hygo"), + u32::from_le_bytes(*b"nGen"), + u32::from_le_bytes(*b"uine"), + ]; /// Classify the documented aligned cacheable 16-byte load guarantee from - /// CPUID.0 vendor and CPUID.1 ECX. Intel SDM Guaranteed Atomic Operations and - /// AMD APM 24593 rev. 3.44 §7.3.2 require AVX hardware; OS AVX state is separate. - /// These raw values alone are not authority to enter native code or RAM. + /// CPUID.0 vendor and CPUID.1 ECX ([`Vendor`]): it requires AVX hardware; + /// OS AVX state is separate. These raw values alone are not authority to + /// enter native code or RAM. pub const fn atomic_load16_guaranteed(vendor: [u32; 3], leaf1_ecx: u32) -> bool { - matches!(vendor, Self::INTEL_VENDOR | Self::AMD_VENDOR) + matches!(Vendor::from_cpuid(vendor), Vendor::Intel | Vendor::Amd) && leaf1_ecx & CPUID_AVX_HARDWARE != 0 } - /// x86-64-v2 (SSE4.2, POPCNT, CMPXCHG8B, CMPXCHG16B): the least host - /// Stela runs on. Every other feature is optional and has a fallback. + /// x86-64-v2 of the x86-64 psABI (SSE4.2, POPCNT, CMPXCHG8B, + /// CMPXCHG16B): the least host Stela runs on. Every other feature is + /// optional and has a fallback. pub const X86_64_V2: Self = Self::Sse42.with_popcnt().with_cx8().with_cx16(); - /// SSE4.2 with every other feature the compiler uses that needs no - /// OS-enabled AVX state: the bare-metal boot's target on a current host. - pub const Sse42Complete: Self = Self::Sse42 - .with_pclmulqdq() - .with_popcnt() + /// x86-64-v3: x86-64-v2 with AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT and + /// MOVBE. The AVX features' probes include OS-enabled XSAVE state. + pub const X86_64_V3: Self = Self::X86_64_V2 + .with_fma() + .with_f16c() .with_bmi1() - .with_aes() - .with_sha() - .with_cx8() - .with_cx16() - .with_atomic_load16(); - /// [`Self::Sse42Complete`] with FMA, F16C and AVX2. - pub const Avx2Complete: Self = Self::Sse42Complete.with_fma().with_f16c().with_avx2(); - /// [`Self::Avx2Complete`] with AVX-512F. - pub const Avx512Complete: Self = Self::Avx2Complete.with_avx512f(); - /// The host tiers whose data-independent-timing lowerings are audited, - /// largest first. + .with_avx2() + .with_lzcnt() + .with_bmi2() + .with_movbe(); + /// x86-64-v4: x86-64-v3 with AVX-512F, BW, CD, DQ and VL. + pub const X86_64_V4: Self = Self::X86_64_V3 + .with_avx512f() + .with_avx512vl() + .with_avx512bw() + .with_avx512cd() + .with_avx512dq(); + /// The host tiers whose data-independent-timing lowerings the DIT unit + /// tests check (`x86_64::{integer_math, integer_unary, crc}`), largest + /// first: each psABI level with PCLMULQDQ, AES, SHA and aligned 16-byte + /// atomic loads, and x86-64-v2 also with BMI1. pub const DATA_INDEPENDENT_TIMING_TIERS: [Self; 3] = [ - Self::Avx512Complete, - Self::Avx2Complete, - Self::Sse42Complete, + Self::X86_64_V4.with_audited_extras(), + Self::X86_64_V3.with_audited_extras(), + Self::X86_64_V2.with_bmi1().with_audited_extras(), ]; - pub const fn with_pclmulqdq(self) -> Self { + const fn with_audited_extras(self) -> Self { + self.with_pclmulqdq() + .with_aes() + .with_sha() + .with_atomic_load16() + } + + const fn with_feature(self, feature: Feature) -> Self { Self { - pclmulqdq: true, + features: self.features | 1 << feature as u32, ..self } } - pub const fn with_fma(self) -> Self { - Self { fma: true, ..self } - } - pub const fn with_f16c(self) -> Self { - Self { f16c: true, ..self } - } - pub const fn with_popcnt(self) -> Self { - Self { - popcnt: true, - ..self - } - } - pub const fn with_bmi1(self) -> Self { - Self { bmi1: true, ..self } - } - pub const fn with_aes(self) -> Self { - Self { aes: true, ..self } - } - pub const fn with_sha(self) -> Self { - Self { sha: true, ..self } - } - pub const fn with_atomic_load16(self) -> Self { - Self { - atomic_load16: true, - ..self - } - } - pub const fn with_line_atomic(self) -> Self { - Self { - line_atomic: true, - ..self - } - } - pub const fn with_cx8(self) -> Self { - Self { cx8: true, ..self } - } - pub const fn with_cx16(self) -> Self { - Self { cx16: true, ..self } - } - pub const fn with_avx2(self) -> Self { - Self { avx2: true, ..self } - } - pub const fn with_avx512f(self) -> Self { - Self { - avx512f: true, - ..self - } - } - pub const fn with_doit(self) -> Self { - Self { doit: true, ..self } - } - pub const fn with_data_independent_timing(self) -> Self { - Self { - data_independent_timing: true, - ..self - } + const fn has(self, feature: Feature) -> bool { + self.features & 1 << feature as u32 != 0 } pub const fn doit(self) -> bool { - self.doit + self.has(Feature::Doit) } pub const fn data_independent_timing(self) -> bool { - self.data_independent_timing + self.has(Feature::DataIndependentTiming) } /// The target to compile PSTATE.DIT code for on this host: the largest /// audited tier ([`Self::DATA_INDEPENDENT_TIMING_TIERS`]) it supports, in @@ -263,7 +465,7 @@ impl TargetCpu { /// Intel's data operand independent timing ([`Self::doit`]) and supports /// one of them, as no audit covers another tier's lowerings. pub fn data_independent_timing_target(self) -> Option { - if !self.doit { + if !self.doit() { return None; } Self::DATA_INDEPENDENT_TIMING_TIERS @@ -273,22 +475,25 @@ impl TargetCpu { } /// True only when every required feature is present in this target. /// The data-independent-timing mode is not a host feature. - pub fn supports(self, required: Self) -> bool { - self.tier >= required.tier - && (!required.pclmulqdq || self.pclmulqdq) - && (!required.fma || self.fma) - && (!required.f16c || self.f16c) - && (!required.popcnt || self.popcnt) - && (!required.bmi1 || self.bmi1) - && (!required.aes || self.aes) - && (!required.sha || self.sha) - && (!required.atomic_load16 || self.atomic_load16) - && (!required.line_atomic || self.line_atomic) - && (!required.cx16 || self.cx16) - && (!required.cx8 || self.cx8) - && (!required.avx2 || self.avx2) - && (!required.avx512f || self.avx512f) - && (!required.doit || self.doit) + pub const fn supports(self, required: Self) -> bool { + self.tier as u8 >= required.tier as u8 && required.features & !MODES & !self.features == 0 + } + /// The target CPUID values describe: every feature whose probe holds. + /// Declared features ([`Self::doit`]) are left to the caller. + pub fn from_cpuid(cpu: &HostCpuid) -> Self { + let bit = |bit| HostCpuid::bit(cpu.leaf1_ecx, bit); + let tier = match (bit(9), bit(19), bit(20)) { + (false, _, _) => SseTier::Baseline, + (true, false, _) => SseTier::Ssse3, + (true, true, false) => SseTier::Sse41, + (true, true, true) => SseTier::Sse42, + }; + FEATURES + .iter() + .filter(|(_, _, probe)| probe(cpu)) + .fold(Self { tier, features: 0 }, |target, (feature, _, _)| { + target.with_feature(*feature) + }) } /// Detect the host's usable CPU features. Freestanding callers supply a /// target explicitly. @@ -302,70 +507,16 @@ impl TargetCpu { fn probe() -> Self { #[cfg(target_arch = "x86_64")] { - let basic = core::arch::x86_64::__cpuid(CPUID_BASIC_FEATURES); - let identity = core::arch::x86_64::__cpuid(0); - let vendor = [identity.ebx, identity.edx, identity.ecx]; - Self { - popcnt: std::is_x86_feature_detected!("popcnt"), - bmi1: std::is_x86_feature_detected!("bmi1"), - aes: std::is_x86_feature_detected!("aes"), - sha: std::is_x86_feature_detected!("sha"), - cx16: basic.ecx & CPUID_CX16 != 0, - cx8: basic.edx & CPUID_CX8 != 0, - // Hardware atomicity, rather than permission to execute VEX. - atomic_load16: Self::atomic_load16_guaranteed(vendor, basic.ecx), - line_atomic: intel(), - // Rust's detector checks CPUID and XSAVE/OSXSAVE/XCR0 state. - avx2: std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("avx2"), - avx512f: avx512f_usable(), - ..Self::for_features_with_vex( - std::is_x86_feature_detected!("ssse3"), - std::is_x86_feature_detected!("sse4.1"), - std::is_x86_feature_detected!("sse4.2"), - std::is_x86_feature_detected!("pclmulqdq"), - std::is_x86_feature_detected!("avx"), - std::is_x86_feature_detected!("fma"), - std::is_x86_feature_detected!("f16c"), - ) - } + Self::from_cpuid(&HostCpuid { + avx512_on_demand: darwin_on_demand_avx512f(), + ..HostCpuid::read() + }) } #[cfg(not(target_arch = "x86_64"))] { Self::Baseline } } - #[cfg(any(all(feature = "std", target_arch = "x86_64"), test))] - fn for_features(ssse3: bool, sse41: bool, sse42: bool, pclmulqdq: bool) -> Self { - let tier = match (ssse3, sse41, sse42) { - (false, _, _) => SseTier::Baseline, - (true, false, _) => SseTier::Ssse3, - (true, true, false) => SseTier::Sse41, - (true, true, true) => SseTier::Sse42, - }; - Self { - tier, - pclmulqdq, - ..Self::Baseline - } - } - #[cfg(any(all(feature = "std", target_arch = "x86_64"), test))] - fn for_features_with_vex( - ssse3: bool, - sse41: bool, - sse42: bool, - pclmulqdq: bool, - avx: bool, - fma: bool, - f16c: bool, - ) -> Self { - // Rust's AVX detector checks XSAVE, OSXSAVE and XCR0's SSE/AVX state. - // Gate each VEX feature independently on that usable register state. - Self { - fma: avx && fma, - f16c: avx && f16c, - ..Self::for_features(ssse3, sse41, sse42, pclmulqdq) - } - } /// Canonical metadata identity; serialization is outside emitted execution. pub fn id(self) -> String { let mut id = match self.tier { @@ -375,25 +526,9 @@ impl TargetCpu { SseTier::Sse42 => "x86_64-baseline+ssse3+sse4.1+sse4.2", } .to_owned(); - for (enabled, suffix) in [ - (self.pclmulqdq, "+pclmulqdq"), - (self.fma, "+fma"), - (self.f16c, "+f16c"), - (self.popcnt, "+popcnt"), - (self.bmi1, "+bmi1"), - (self.aes, "+aes"), - (self.sha, "+sha"), - (self.atomic_load16, "+atomic-load16"), - (self.cx8, "+cx8"), - (self.cx16, "+cx16"), - (self.avx2, "+avx2"), - (self.avx512f, "+avx512f"), - (self.line_atomic, "+line-atomic"), - (self.doit, "+doit"), - (self.data_independent_timing, "+dit"), - ] { - if enabled { - id.push_str(suffix); + for (feature, name, _) in FEATURES { + if self.has(*feature) { + id.push_str(name); } } id @@ -405,22 +540,6 @@ impl TargetCpu { } } -/// Whether CPUID's vendor string is `GenuineIntel` ([`TargetCpu::line_atomic`]). -#[cfg(all(any(feature = "std", test), target_arch = "x86_64"))] -fn intel() -> bool { - let vendor = core::arch::x86_64::__cpuid(0); - [vendor.ebx, vendor.edx, vendor.ecx] == TargetCpu::INTEL_VENDOR -} - -/// AVX-512F with OS-enabled opmask and ZMM state. Rust's detector reads XCR0, -/// which xnu leaves without that state until a thread first executes EVEX: -/// xnu enables it on demand and reports usable support in -/// `hw.optional.avx512f`. -#[cfg(all(any(feature = "std", test), target_arch = "x86_64"))] -fn avx512f_usable() -> bool { - std::is_x86_feature_detected!("avx512f") || darwin_on_demand_avx512f() -} - #[cfg(all( any(feature = "std", test), target_arch = "x86_64", @@ -467,8 +586,7 @@ fn darwin_on_demand_avx512f() -> bool { impl PartialOrd for TargetCpu { fn partial_cmp(&self, other: &Self) -> Option { let contains = |outer: &Self, inner: &Self| { - outer.supports(*inner) - && (outer.data_independent_timing || !inner.data_independent_timing) + outer.tier >= inner.tier && inner.features & !outer.features == 0 }; match (contains(self, other), contains(other, self)) { (true, true) => Some(core::cmp::Ordering::Equal), @@ -486,26 +604,10 @@ impl core::str::FromStr for TargetCpu { let mut tier_name = value; // Strip each optional suffix once, in reverse order. A duplicate, // unknown or out-of-order suffix is left behind and fails parsing. - for (suffix, enabled) in [ - ("+dit", &mut target.data_independent_timing), - ("+doit", &mut target.doit), - ("+line-atomic", &mut target.line_atomic), - ("+avx512f", &mut target.avx512f), - ("+avx2", &mut target.avx2), - ("+cx16", &mut target.cx16), - ("+cx8", &mut target.cx8), - ("+atomic-load16", &mut target.atomic_load16), - ("+sha", &mut target.sha), - ("+aes", &mut target.aes), - ("+bmi1", &mut target.bmi1), - ("+popcnt", &mut target.popcnt), - ("+f16c", &mut target.f16c), - ("+fma", &mut target.fma), - ("+pclmulqdq", &mut target.pclmulqdq), - ] { - if let Some(prefix) = tier_name.strip_suffix(suffix) { + for (feature, name, _) in FEATURES.iter().rev() { + if let Some(prefix) = tier_name.strip_suffix(name) { tier_name = prefix; - *enabled = true; + target = target.with_feature(*feature); } } target.tier = match tier_name { @@ -519,10 +621,24 @@ impl core::str::FromStr for TargetCpu { } } +impl serde::Serialize for TargetCpu { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.id()) + } +} + +impl<'de> serde::Deserialize<'de> for TargetCpu { + fn deserialize>(deserializer: D) -> Result { + let id = >::deserialize(deserializer)?; + id.parse().map_err(serde::de::Error::custom) + } +} + #[cfg(test)] mod tests { use super::*; use alloc::format; + use alloc::vec::Vec; const TIERS: [(TargetCpu, &str, &str); 4] = [ (TargetCpu::Baseline, "baseline", "x86_64-baseline"), @@ -534,48 +650,42 @@ mod tests { "x86_64-baseline+ssse3+sse4.1+sse4.2", ), ]; - const FEATURES: [TargetCpu; 14] = [ - TargetCpu::Pclmulqdq, - TargetCpu::Fma, - TargetCpu::F16c, - TargetCpu::Popcnt, - TargetCpu::Bmi1, - TargetCpu::Aes, - TargetCpu::Sha, - TargetCpu::AtomicLoad16, - TargetCpu::Cx8, - TargetCpu::Cx16, - TargetCpu::Avx2, - TargetCpu::Avx512f, - TargetCpu::Doit, - TargetCpu::LineAtomic, - ]; + /// The host features, one target each. + fn host_features() -> impl Iterator { + FEATURES + .iter() + .filter(|(feature, _, _)| MODES & 1 << *feature as u32 == 0) + .map(|(feature, _, _)| (*feature, TargetCpu::Baseline.with_feature(*feature))) + } + + /// Every tier with no feature, each single feature, each pair, and a + /// fixed pseudo-random sample of larger feature sets. fn profiles() -> impl Iterator { - TIERS.into_iter().flat_map(|(tier, _, _)| { - (0..32768).map(move |bits| TargetCpu { - pclmulqdq: bits & 1 != 0, - fma: bits & 2 != 0, - f16c: bits & 4 != 0, - popcnt: bits & 8 != 0, - bmi1: bits & 16 != 0, - aes: bits & 32 != 0, - sha: bits & 64 != 0, - atomic_load16: bits & 128 != 0, - cx8: bits & 256 != 0, - cx16: bits & 512 != 0, - avx2: bits & 1024 != 0, - avx512f: bits & 2048 != 0, - doit: bits & 4096 != 0, - data_independent_timing: bits & 8192 != 0, - line_atomic: bits & 16384 != 0, - ..tier - }) + let count = FEATURES.len() as u32; + let all = (1u64 << count) - 1; + let mut sets = Vec::from([0, all]); + for first in 0..count { + for second in first..count { + sets.push(1u64 << first | 1u64 << second); + } + } + let mut state = 0x9e37_79b9_7f4a_7c15u64; + for _ in 0..512 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + sets.push(state & all); + } + TIERS.into_iter().flat_map(move |(tier, _, _)| { + sets.clone() + .into_iter() + .map(move |features| TargetCpu { features, ..tier }) }) } #[test] - fn old_canonical_ids_and_aliases_keep_exact_bytes() { + fn canonical_ids_and_aliases_keep_their_spelling() { for (tier, alias, canonical) in TIERS { for (suffix, target) in [ ("", tier), @@ -594,14 +704,27 @@ mod tests { assert_eq!(format!("{alias}{suffix}").parse::(), Ok(target)); } } + let every = FEATURES + .iter() + .fold(TargetCpu::Sse42, |target, (feature, _, _)| { + target.with_feature(*feature) + }); + assert_eq!( + every.id(), + "x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+fma+f16c+popcnt+bmi1+aes+sha\ + +atomic-load16+cx8+cx16+avx2+avx512f+lzcnt+bmi2+fast-pdep+movbe+gfni\ + +avx512vl+avx512bw+avx512cd+avx512dq+avx512vpopcntdq+avx512bitalg+avx512vnni\ + +avxvnni+avx512bf16+avxneconvert+avx512fp16+vaes+vpclmulqdq+sha512+sm3+sm4\ + +apx+line-atomic+doit+dit" + ); } #[test] fn every_profile_has_one_canonical_identity_and_alias() { - let mut ids = alloc::collections::BTreeSet::new(); + let mut ids = alloc::collections::BTreeMap::new(); for target in profiles() { let id = target.id(); - assert!(ids.insert(id.clone())); + assert_eq!(*ids.entry(id.clone()).or_insert(target), target); assert_eq!(id.parse::(), Ok(target)); let (_, alias, canonical) = TIERS .into_iter() @@ -610,19 +733,17 @@ mod tests { let suffix = id.strip_prefix(canonical).unwrap(); assert_eq!(format!("{alias}{suffix}").parse::(), Ok(target)); } - assert_eq!(ids.len(), 131072); - assert_eq!( - TargetCpu::Sse42 - .with_sha() - .with_aes() - .with_bmi1() - .with_popcnt() - .with_f16c() - .with_fma() - .with_pclmulqdq() - .id(), - "x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+fma+f16c+popcnt+bmi1+aes+sha" - ); + } + + #[test] + fn deserialization_parses_the_canonical_identity() { + use serde::{Deserialize, de::value::StrDeserializer}; + fn parse(id: &str) -> Result { + TargetCpu::deserialize(StrDeserializer::new(id)) + } + let target = TargetCpu::X86_64_V3.with_line_atomic(); + assert_eq!(parse(&target.id()), Ok(target)); + assert!(parse("baseline+avx").is_err()); } #[test] @@ -663,25 +784,9 @@ mod tests { ] { assert!(invalid.parse::().is_err(), "{invalid}"); } - for suffix in [ - "pclmulqdq", - "fma", - "f16c", - "popcnt", - "bmi1", - "aes", - "sha", - "atomic-load16", - "cx16", - "cx8", - "avx2", - "avx512f", - "doit", - "dit", - "line-atomic", - ] { + for (_, name, _) in FEATURES { for tier in ["baseline", "x86_64-baseline+ssse3+sse4.1+sse4.2"] { - let duplicate = format!("{tier}+{suffix}+{suffix}"); + let duplicate = format!("{tier}{name}{name}"); assert!(duplicate.parse::().is_err(), "{duplicate}"); } } @@ -689,7 +794,11 @@ mod tests { #[test] fn atomic_load16_requires_a_documented_vendor_and_independent_avx_hardware() { - for vendor in [TargetCpu::INTEL_VENDOR, TargetCpu::AMD_VENDOR] { + for vendor in [ + TargetCpu::INTEL_VENDOR, + TargetCpu::AMD_VENDOR, + TargetCpu::HYGON_VENDOR, + ] { assert!(!TargetCpu::atomic_load16_guaranteed(vendor, 0)); // OSXSAVE/XSAVE/CX16 do not grant the independent plain-load fact. assert!(!TargetCpu::atomic_load16_guaranteed( @@ -703,22 +812,50 @@ mod tests { } for vendor in [ [0; 3], - [ - u32::from_le_bytes(*b"Hygo"), - u32::from_le_bytes(*b"nGen"), - u32::from_le_bytes(*b"uine"), - ], + vendor_id(b" Shanghai "), + vendor_id(b"CentaurHauls"), ] { + assert_eq!(Vendor::from_cpuid(vendor), Vendor::Other); assert!(!TargetCpu::atomic_load16_guaranteed(vendor, u32::MAX)); } } + /// A vendor string in CPUID leaf 0 EBX, EDX, ECX order. + fn vendor_id(name: &[u8; 12]) -> [u32; 3] { + let word = |at: usize| u32::from_le_bytes(name[at..at + 4].try_into().unwrap()); + [word(0), word(4), word(8)] + } + + #[test] + fn hygon_follows_amd_and_only_intel_is_line_atomic() { + assert_eq!(vendor_id(b"HygonGenuine"), TargetCpu::HYGON_VENDOR); + assert_eq!(vendor_id(b"AuthenticAMD"), TargetCpu::AMD_VENDOR); + for (name, vendor) in [ + (b"GenuineIntel", Vendor::Intel), + (b"AuthenticAMD", Vendor::Amd), + (b"HygonGenuine", Vendor::Amd), + (b" Shanghai ", Vendor::Other), + (b"CentaurHauls", Vendor::Other), + ] { + assert_eq!(Vendor::from_cpuid(vendor_id(name)), vendor); + let target = TargetCpu::from_cpuid(&HostCpuid { + vendor: vendor_id(name), + ..RICH + }); + assert_eq!( + target.supports(TargetCpu::LineAtomic), + vendor == Vendor::Intel + ); + assert_eq!( + target.supports(TargetCpu::AtomicLoad16), + vendor != Vendor::Other + ); + } + } + #[test] fn unqualified_plain_load_does_not_remove_v2_casp_or_cx16() { - use crate::{ - GuestAddress, - block::{BlockProfile, compile_for_target}, - }; + use crate::{GuestAddress, block::BlockProfile}; let source: alloc::vec::Vec<_> = [0x4822_7c04u32, 0xd65f_03c0] .into_iter() .flat_map(u32::to_le_bytes) @@ -727,17 +864,17 @@ mod tests { assert!(!TargetCpu::atomic_load16_guaranteed([0; 3], u32::MAX)); assert!(!baseline.supports(TargetCpu::AtomicLoad16)); assert!(baseline.supports(TargetCpu::Cx16)); - let original = compile_for_target( + let original = crate::testing::block_for( &source, GuestAddress(0x1000), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, baseline, ) .unwrap(); - let optional = compile_for_target( + let optional = crate::testing::block_for( &source, GuestAddress(0x1000), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, baseline.with_atomic_load16(), ) .unwrap(); @@ -755,49 +892,30 @@ mod tests { #[test] fn every_independent_feature_requires_full_containment() { for host in profiles() { - for (required, present) in FEATURES.into_iter().zip([ - host.pclmulqdq, - host.fma, - host.f16c, - host.popcnt, - host.bmi1, - host.aes, - host.sha, - host.atomic_load16, - host.cx8, - host.cx16, - host.avx2, - host.avx512f, - host.doit, - host.line_atomic, - ]) { - assert_eq!(host.supports(required), present); - assert_eq!(host >= required, present); + for (feature, required) in host_features() { + assert_eq!(host.supports(required), host.has(feature)); + assert_eq!(host >= required, host.has(feature)); } // The timing mode is no host requirement, but orders as a // feature: equality stays identity. let timed = host.with_data_independent_timing(); assert!(host.supports(timed) && timed.supports(host)); assert!(timed >= host); - assert_eq!(host >= timed, host.data_independent_timing); + assert_eq!(host >= timed, host.data_independent_timing()); for (required, _, _) in TIERS { assert_eq!(host.supports(required), host.tier >= required.tier); } assert!(host.supports(host)); assert!(host.supports(TargetCpu::Baseline)); } - for feature in FEATURES { + for (_, feature) in host_features() { assert!(!TargetCpu::Sse42.supports(feature)); assert_eq!(TargetCpu::Sse42.partial_cmp(&feature), None); - for other in FEATURES { + for (_, other) in host_features() { assert_eq!(feature.supports(other), feature == other); assert_eq!( feature.partial_cmp(&other), - if feature == other { - Some(core::cmp::Ordering::Equal) - } else { - None - } + (feature == other).then_some(core::cmp::Ordering::Equal) ); } } @@ -821,7 +939,7 @@ mod tests { let expected = TargetCpu::DATA_INDEPENDENT_TIMING_TIERS .into_iter() .find(|tier| host.supports(*tier)) - .filter(|_| host.doit); + .filter(|_| host.doit()); let target = host.data_independent_timing_target(); assert_eq!(target.is_some(), expected.is_some(), "{host:?}"); if let (Some(target), Some(tier)) = (target, expected) { @@ -830,58 +948,176 @@ mod tests { } } // The tiers nest, largest first. - let [avx512, avx2, sse42] = TargetCpu::DATA_INDEPENDENT_TIMING_TIERS; - assert!(avx512 > avx2 && avx2 > sse42 && sse42 > TargetCpu::Sse42); + let [v4, v3, v2] = TargetCpu::DATA_INDEPENDENT_TIMING_TIERS; + assert!(v4 > v3 && v3 > v2 && v2 > TargetCpu::X86_64_V2); + assert!(v4 > TargetCpu::X86_64_V4 && v3 > TargetCpu::X86_64_V3); assert_eq!( - TargetCpu::Avx2Complete + v3.with_avx512f() .with_doit() .data_independent_timing_target(), - Some(avx2.with_doit().with_data_independent_timing()) - ); - assert_eq!( - TargetCpu::Avx2Complete.data_independent_timing_target(), - None + Some(v3.with_doit().with_data_independent_timing()) ); + assert_eq!(v3.data_independent_timing_target(), None); + } + + /// CPUID values of an Intel family 6 host with every feature bit set. + const RICH: HostCpuid = HostCpuid { + vendor: TargetCpu::INTEL_VENDOR, + leaf1_eax: 6 << 8, + leaf1_ecx: u32::MAX, + leaf1_edx: u32::MAX, + leaf7_ebx: u32::MAX, + leaf7_ecx: u32::MAX, + leaf7_edx: u32::MAX, + leaf7_1_eax: u32::MAX, + leaf7_1_edx: u32::MAX, + extended1_ecx: u32::MAX, + xcr0: XCR0_AVX_STATE | XCR0_AVX512_STATE | XCR0_APX_STATE, + avx512_on_demand: false, + }; + + #[test] + fn a_rich_host_has_every_feature_and_the_psabi_levels() { + let rich = TargetCpu::from_cpuid(&RICH); + assert!(rich.supports(TargetCpu::X86_64_V4)); + for (feature, required) in host_features() { + let declared = matches!(feature, Feature::Doit); + assert_eq!(rich.supports(required), !declared, "{feature:?}"); + } + assert!(TargetCpu::X86_64_V4 > TargetCpu::X86_64_V3); + assert!(TargetCpu::X86_64_V3 > TargetCpu::X86_64_V2); } #[test] - fn tier_and_vex_detection_keep_each_prerequisite() { - for bits in 0..128 { - let ssse3 = bits & 1 != 0; - let sse41 = bits & 2 != 0; - let sse42 = bits & 4 != 0; - let pclmulqdq = bits & 8 != 0; - let avx = bits & 16 != 0; - let fma = bits & 32 != 0; - let f16c = bits & 64 != 0; - let original = TargetCpu::for_features(ssse3, sse41, sse42, pclmulqdq); - assert!(!original.supports(TargetCpu::Fma)); - assert!(!original.supports(TargetCpu::F16c)); - let target = - TargetCpu::for_features_with_vex(ssse3, sse41, sse42, pclmulqdq, avx, fma, f16c); - assert_eq!(target >= TargetCpu::Ssse3, ssse3); - assert_eq!(target >= TargetCpu::Sse41, ssse3 && sse41); - assert_eq!(target >= TargetCpu::Sse42, ssse3 && sse41 && sse42); - assert_eq!(target.supports(TargetCpu::Pclmulqdq), pclmulqdq); - assert_eq!(target.supports(TargetCpu::Fma), avx && fma); - assert_eq!(target.supports(TargetCpu::F16c), avx && f16c); - for independent in [ - TargetCpu::Popcnt, - TargetCpu::Bmi1, - TargetCpu::Aes, - TargetCpu::Sha, - ] { - assert!(!target.supports(independent)); - } + fn evex_features_need_zmm_state_and_apx_its_own() { + let no_zmm = TargetCpu::from_cpuid(&HostCpuid { + xcr0: XCR0_AVX_STATE | XCR0_APX_STATE, + ..RICH + }); + for evex in [ + TargetCpu::Avx512vl, + TargetCpu::Avx512bw, + TargetCpu::Avx512cd, + TargetCpu::Avx512dq, + TargetCpu::Avx512vpopcntdq, + TargetCpu::Avx512bitalg, + TargetCpu::Avx512vnni, + TargetCpu::Avx512bf16, + TargetCpu::Avx512fp16, + ] { + assert!(!no_zmm.supports(evex), "{evex:?}"); + } + assert!(no_zmm.supports(TargetCpu::AvxVnni.with_vaes().with_vpclmulqdq())); + let no_apx = HostCpuid { + xcr0: XCR0_AVX_STATE | XCR0_AVX512_STATE, + ..RICH + }; + assert!(!TargetCpu::from_cpuid(&no_apx).supports(TargetCpu::Apx)); + } + + #[test] + fn pdep_is_slow_on_amd_before_family_19h() { + for (vendor, family, fast) in [ + (TargetCpu::INTEL_VENDOR, 6, true), + (TargetCpu::AMD_VENDOR, 0x17, false), + (TargetCpu::HYGON_VENDOR, 0x18, false), + (TargetCpu::AMD_VENDOR, 0x19, true), + (TargetCpu::AMD_VENDOR, 0x1a, true), + ] { + // Families from 10H carry the extended family over base 0FH. + let leaf1_eax = if family > 0xf { + 0xf << 8 | (family - 0xf) << 20 + } else { + family << 8 + }; + let target = TargetCpu::from_cpuid(&HostCpuid { + vendor, + leaf1_eax, + ..RICH + }); + assert!(target.supports(TargetCpu::Bmi2)); + assert_eq!(target.supports(TargetCpu::FastPdep), fast, "{family:#x}"); } } #[test] - fn native_detection_reads_independent_bits_without_tier_gating() { + fn sse_tiers_nest_from_cpuid() { + for bits in 0..8u32 { + let (ssse3, sse41, sse42) = (bits & 1 != 0, bits & 2 != 0, bits & 4 != 0); + let leaf1_ecx = u32::from(ssse3) << 9 | u32::from(sse41) << 19 | u32::from(sse42) << 20; + let target = TargetCpu::from_cpuid(&HostCpuid { + leaf1_ecx, + ..HostCpuid::default() + }); + assert_eq!(target >= TargetCpu::Ssse3, ssse3); + assert_eq!(target >= TargetCpu::Sse41, ssse3 && sse41); + assert_eq!(target >= TargetCpu::Sse42, ssse3 && sse41 && sse42); + assert_eq!(target.features, 0); + } + } + + #[test] + fn vex_features_need_os_enabled_avx_state() { + let rich = TargetCpu::from_cpuid(&RICH); + for tier in TargetCpu::DATA_INDEPENDENT_TIMING_TIERS { + assert!(rich.supports(tier.with_line_atomic())); + } + assert!(!rich.doit() && !rich.data_independent_timing()); + let no_ymm = TargetCpu::from_cpuid(&HostCpuid { xcr0: 0x3, ..RICH }); + for vex in [ + TargetCpu::Fma, + TargetCpu::F16c, + TargetCpu::Avx2, + TargetCpu::Avx512f, + ] { + assert!(!no_ymm.supports(vex), "{vex:?}"); + } + // Legacy-encoded features, BMI1 off Intel and the plain-load + // guarantee keep only their hardware bits. + let amd_no_ymm = TargetCpu::from_cpuid(&HostCpuid { + vendor: TargetCpu::AMD_VENDOR, + xcr0: 0x3, + ..RICH + }); + let [_, _, v2] = TargetCpu::DATA_INDEPENDENT_TIMING_TIERS; + assert!(amd_no_ymm.supports(v2.with_movbe().with_lzcnt().with_gfni())); + assert!(!amd_no_ymm.supports(TargetCpu::X86_64_V3)); + let no_zmm = TargetCpu::from_cpuid(&HostCpuid { + xcr0: XCR0_AVX_STATE, + ..RICH + }); + assert!(no_zmm.supports(TargetCpu::X86_64_V3)); + assert!(!no_zmm.supports(TargetCpu::Avx512f)); + let on_demand = TargetCpu::from_cpuid(&HostCpuid { + xcr0: XCR0_AVX_STATE, + avx512_on_demand: true, + ..RICH + }); + assert!(on_demand.supports(TargetCpu::Avx512f)); + } + + #[test] + fn intel_bmi_needs_avx() { + let no_avx = HostCpuid { xcr0: 0, ..RICH }; + let bmi = TargetCpu::Bmi1.with_bmi2(); + for required in [TargetCpu::Bmi1, TargetCpu::Bmi2, TargetCpu::FastPdep] { + assert!(!TargetCpu::from_cpuid(&no_avx).supports(required)); + } + let amd = HostCpuid { + vendor: TargetCpu::AMD_VENDOR, + ..no_avx + }; + assert!(TargetCpu::from_cpuid(&amd).supports(bmi)); + } + + #[test] + fn native_detection_matches_std_detect() { let target = TargetCpu::detect(); #[cfg(target_arch = "x86_64")] { + let cpuid = HostCpuid::read(); for (required, detected) in [ + (TargetCpu::Ssse3, std::is_x86_feature_detected!("ssse3")), ( TargetCpu::Pclmulqdq, std::is_x86_feature_detected!("pclmulqdq"), @@ -902,25 +1138,82 @@ mod tests { TargetCpu::Avx2, std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("avx2"), ), - (TargetCpu::Avx512f, avx512f_usable()), - (TargetCpu::AtomicLoad16, { - let vendor = core::arch::x86_64::__cpuid(0); - TargetCpu::atomic_load16_guaranteed( - [vendor.ebx, vendor.edx, vendor.ecx], - core::arch::x86_64::__cpuid(CPUID_BASIC_FEATURES).ecx, - ) - }), ( - TargetCpu::Cx16, - core::arch::x86_64::__cpuid(CPUID_BASIC_FEATURES).ecx & CPUID_CX16 != 0, + TargetCpu::Avx512f, + std::is_x86_feature_detected!("avx512f") || darwin_on_demand_avx512f(), ), ( - TargetCpu::Cx8, - core::arch::x86_64::__cpuid(CPUID_BASIC_FEATURES).edx & CPUID_CX8 != 0, + TargetCpu::AtomicLoad16, + TargetCpu::atomic_load16_guaranteed(cpuid.vendor, cpuid.leaf1_ecx), ), - (TargetCpu::LineAtomic, intel()), + (TargetCpu::Cx16, std::is_x86_feature_detected!("cmpxchg16b")), + (TargetCpu::Cx8, cpuid.leaf1_edx & 1 << 8 != 0), + ( + TargetCpu::LineAtomic, + Vendor::from_cpuid(cpuid.vendor) == Vendor::Intel, + ), + (TargetCpu::Lzcnt, std::is_x86_feature_detected!("lzcnt")), + (TargetCpu::Bmi2, std::is_x86_feature_detected!("bmi2")), + (TargetCpu::Movbe, std::is_x86_feature_detected!("movbe")), + (TargetCpu::Gfni, std::is_x86_feature_detected!("gfni")), + (TargetCpu::Vaes, std::is_x86_feature_detected!("vaes")), + ( + TargetCpu::Vpclmulqdq, + std::is_x86_feature_detected!("vpclmulqdq"), + ), + (TargetCpu::AvxVnni, std::is_x86_feature_detected!("avxvnni")), + ( + TargetCpu::AvxNeConvert, + std::is_x86_feature_detected!("avxneconvert"), + ), + (TargetCpu::Sha512, std::is_x86_feature_detected!("sha512")), + (TargetCpu::Sm3, std::is_x86_feature_detected!("sm3")), + (TargetCpu::Sm4, std::is_x86_feature_detected!("sm4")), ] { - assert_eq!(target.supports(required), detected); + assert_eq!(target.supports(required), detected, "{required:?}"); + } + // xnu enables ZMM state on demand, which std_detect does not see. + if !darwin_on_demand_avx512f() { + for (required, detected) in [ + ( + TargetCpu::Avx512vl, + std::is_x86_feature_detected!("avx512vl"), + ), + ( + TargetCpu::Avx512bw, + std::is_x86_feature_detected!("avx512bw"), + ), + ( + TargetCpu::Avx512cd, + std::is_x86_feature_detected!("avx512cd"), + ), + ( + TargetCpu::Avx512dq, + std::is_x86_feature_detected!("avx512dq"), + ), + ( + TargetCpu::Avx512vpopcntdq, + std::is_x86_feature_detected!("avx512vpopcntdq"), + ), + ( + TargetCpu::Avx512bitalg, + std::is_x86_feature_detected!("avx512bitalg"), + ), + ( + TargetCpu::Avx512vnni, + std::is_x86_feature_detected!("avx512vnni"), + ), + ( + TargetCpu::Avx512bf16, + std::is_x86_feature_detected!("avx512bf16"), + ), + ( + TargetCpu::Avx512fp16, + std::is_x86_feature_detected!("avx512fp16"), + ), + ] { + assert_eq!(target.supports(required), detected, "{required:?}"); + } } assert!(target.supported()); } diff --git a/crates/stela-compiler/src/testing.rs b/crates/stela-compiler/src/testing.rs new file mode 100644 index 0000000000..e4d0a877b9 --- /dev/null +++ b/crates/stela-compiler/src/testing.rs @@ -0,0 +1,118 @@ +//! [`crate::compile`] with the options most tests use. +use crate::{ + CompileError, GuestAddress, NativeBlock, Options, TargetCpu, + aarch64::floating::features::NumericalFeatures, + block::{BlockProfile, CompiledBlock, Features}, + scalable_context::ScalableProfile, +}; + +/// A leaf, which must end in RET X30, for the baseline host. +pub(crate) fn leaf(source: &[u8], base: GuestAddress) -> Result { + leaf_for(source, base, TargetCpu::Baseline) +} + +pub(crate) fn leaf_for( + source: &[u8], + base: GuestAddress, + target: TargetCpu, +) -> Result { + let options = Options::new(BlockProfile::new(Features::LEAF), target); + crate::compile(source, base, &options).map(|block| block.native) +} + +/// An ordinary block for the baseline host. +pub(crate) fn block(source: &[u8], base: GuestAddress) -> Result { + block_for(source, base, BlockProfile::ORDINARY, TargetCpu::Baseline) +} + +pub(crate) fn block_with( + source: &[u8], + base: GuestAddress, + profile: BlockProfile, +) -> Result { + block_for(source, base, profile, TargetCpu::Baseline) +} + +pub(crate) fn block_for( + source: &[u8], + base: GuestAddress, + profile: BlockProfile, + target: TargetCpu, +) -> Result { + crate::compile(source, base, &Options::new(profile, target)) +} + +/// A context leaf for `scalable`. +pub(crate) fn context_leaf( + source: &[u8], + base: GuestAddress, + scalable: ScalableProfile, + target: TargetCpu, +) -> Result { + let options = Options::new( + BlockProfile::new(Features::LEAF | Features::CONTEXT), + target, + ) + .with_scalable(scalable); + crate::compile(source, base, &options).map(|block| block.native) +} + +/// A context block for `scalable`, completing numerical forms for +/// `numerical`. +pub(crate) fn context_block( + source: &[u8], + base: GuestAddress, + scalable: ScalableProfile, + numerical: NumericalFeatures, + target: TargetCpu, +) -> Result { + let options = Options::new(BlockProfile::new(Features::CONTEXT), target) + .with_scalable(scalable) + .with_numerical_features(numerical); + crate::compile(source, base, &options) +} + +/// A context leaf's code with the execution requirements its plan derives. +pub(crate) struct PreparedLeaf { + pub(crate) native: NativeBlock, + pub(crate) execution_requirements: + crate::aarch64::scalable::execution::ScalableExecutionRequirements, +} + +pub(crate) fn prepared_context_leaf( + source: &[u8], + base: GuestAddress, + scalable: ScalableProfile, + target: TargetCpu, +) -> Result { + let options = Options::new( + BlockProfile::new(Features::LEAF | Features::CONTEXT), + target, + ) + .with_scalable(scalable); + let plan = crate::block::CompilationPlan::new(source, base, &options)?; + let execution_requirements = plan + .execution_requirements() + .expect("a context leaf has execution requirements"); + Ok(PreparedLeaf { + native: plan.compile()?.native, + execution_requirements, + }) +} + +/// The memory service a context leaf needs, from its plan alone. +pub(crate) fn context_leaf_memory( + source: &[u8], + base: GuestAddress, + scalable: ScalableProfile, + target: TargetCpu, +) -> Result { + let options = Options::new( + BlockProfile::new(Features::LEAF | Features::CONTEXT), + target, + ) + .with_scalable(scalable); + Ok(crate::block::CompilationPlan::new(source, base, &options)? + .memory_requirements() + .expect("a context leaf has memory requirements")) +} diff --git a/crates/stela-compiler/src/x86_64.rs b/crates/stela-compiler/src/x86_64.rs index 8f44d4e527..a9db602e5d 100644 --- a/crates/stela-compiler/src/x86_64.rs +++ b/crates/stela-compiler/src/x86_64.rs @@ -1,4 +1,5 @@ //! x86-64 code emission. RDI holds the guest state pointer throughout. +use crate::x86_64::asm::Code; use crate::{ Backend, GuestAddress, NativeBlock, UnsupportedReason, aarch64::{ @@ -67,7 +68,26 @@ pub(crate) fn validate_target_with( } Ok(()) } + +/// Native code under construction, with its counted instructions and the +/// native offset of each guest instruction. +#[derive(Debug, Default)] +pub(crate) struct Emitted { + pub(crate) x86_64_code: asm::Code, + pub(crate) source_map: Vec<(crate::GuestAddress, usize)>, +} + +impl Emitted { + pub(crate) fn into_native(self) -> crate::NativeBlock { + crate::NativeBlock { + x86_64_code: self.x86_64_code.into_bytes(), + source_map: self.source_map, + } + } +} + pub mod amx; +pub(crate) mod asm; mod atomic; mod bitfield; pub(crate) mod block; @@ -86,6 +106,12 @@ pub mod isa; mod literal; pub(crate) mod memory_context; pub(crate) mod memory_store; +#[cfg(all( + test, + target_arch = "x86_64", + any(target_os = "macos", target_os = "linux") +))] +mod native; mod non_temporal; mod ordered; mod pc_relative; @@ -147,25 +173,91 @@ fn offset(register: Register) -> Option { } } +/// `[rdi+offset]` with a 32-bit displacement: a field of the guest frame. +fn frame(offset: u32) -> asm::Mem { + asm::Mem::base_disp32(asm::Gpr::Rdi, offset as i32) +} + +/// `[rax]`: the access address the memory emitters compute. +fn accessed() -> asm::Mem { + asm::Mem::base(asm::Gpr::Rax, 0) +} + +fn logical(kind: Logical) -> asm::Alu { + match kind { + Logical::And => asm::Alu::And, + Logical::Or => asm::Alu::Or, + Logical::Xor => asm::Alu::Xor, + } +} + +/// `add` or `sub (e/r)ax,(e/r)cx`. +fn add_sub(code: &mut Code, width: Width, subtract: bool) { + let op = if subtract { + asm::Alu::Sub + } else { + asm::Alu::Add + }; + code.asm().alu( + op, + asm::Size::of(width == Width::X64), + asm::Gpr::Rax, + asm::Gpr::Rcx, + ); +} + +/// `test (e/r)ax,(e/r)ax`: the condition under which RAX at `width` is +/// nonzero, or zero. +pub(super) fn test_zero(code: &mut Code, width: Width, nonzero: bool) -> asm::Cond { + use asm::Gpr::Rax; + code.asm() + .test(asm::Size::of(width == Width::X64), Rax, Rax); + if nonzero { asm::Cond::Ne } else { asm::Cond::E } +} + +/// `bt rax,bit`: the condition under which the bit is set, or clear. +pub(super) fn test_bit(code: &mut Code, bit: u8, nonzero: bool) -> asm::Cond { + code.asm() + .bit_imm(asm::BitTest::Bt, asm::Size::Qword, asm::Gpr::Rax, bit); + if nonzero { asm::Cond::B } else { asm::Cond::Ae } +} + /// Backend policy shared by block parsing and emission. Terminal numerical /// mappings consume only their own word; conditional mappings retain a suffix. pub(crate) fn numerical_always_exits(operation: &crate::aarch64::FloatingPointOperation) -> bool { simd::numerical_always_exits(operation) } -fn load(code: &mut Vec, register: Register) { - if let Some(offset) = offset(register) { - code.extend([0x48, 0x8b, 0x87]); // mov rax,[rdi+disp32] - code.extend(offset.to_le_bytes()); - } else { - code.extend([0x31, 0xc0]); +fn load(code: &mut Code, register: Register) { + load_with(&mut code.asm(), register); +} + +/// RAX = the guest register (zero for XZR), from the frame at RDI. +fn load_with(asm: &mut asm::Asm, register: Register) { + use asm::{Alu, Gpr, Mem, Size}; + match offset(register) { + Some(offset) => asm.mov_load( + Size::Qword, + Gpr::Rax, + Mem::base_disp32(Gpr::Rdi, offset as i32), + ), + None => asm.alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax), } } -fn store(code: &mut Vec, register: Register) { +fn store(code: &mut Code, register: Register) { + store_with(&mut code.asm(), register); +} + +/// The guest register (nothing for XZR) = RAX, in the frame at RDI. +fn store_with(asm: &mut asm::Asm, register: Register) { + use asm::{Gpr, Mem, Size}; if let Some(offset) = offset(register) { - code.extend([0x48, 0x89, 0x87]); // mov [rdi+disp32],rax - code.extend(offset.to_le_bytes()); + asm.mov_store( + Size::Qword, + Mem::base_disp32(Gpr::Rdi, offset as i32), + Gpr::Rax, + ); } } @@ -173,7 +265,7 @@ fn store(code: &mut Vec, register: Register) { /// the caller keeps code/state separate from guest mappings. Guest NZCV is untouched. #[allow(clippy::too_many_arguments)] fn memory( - code: &mut Vec, + code: &mut Code, checks: MemoryChecks, transfer: MemoryTransfer, bytes: u8, @@ -197,22 +289,25 @@ fn memory( ); } MemoryTransfer::Load { signed, width } => { - if width == Width::X64 { - code.push(0x48); - } + use asm::{Gpr::Rcx, Size}; + let size = Size::of(width == Width::X64); + let source = accessed(); + let mut asm = code.asm(); match (bytes, signed) { - (1, false) => code.extend([0x0f, 0xb6, 0x08]), - (2, false) => code.extend([0x0f, 0xb7, 0x08]), - (1, true) => code.extend([0x0f, 0xbe, 0x08]), - (2, true) => code.extend([0x0f, 0xbf, 0x08]), - (4, true) => code.extend([0x63, 0x08]), // movsxd rcx,[rax] - (4 | 8, false) => code.extend([0x8b, 0x08]), + (1, false) => asm.movzx(size, Rcx, Size::Byte, source), + (2, false) => asm.movzx(size, Rcx, Size::Word, source), + (1, true) => asm.movsx(size, Rcx, Size::Byte, source), + (2, true) => asm.movsx(size, Rcx, Size::Word, source), + (4, true) => { + debug_assert!(width == Width::X64, "LDRSW writes an X register"); + asm.movsxd(Rcx, source); + } + (4 | 8, false) => asm.mov_load(size, Rcx, source), _ => unreachable!("decoder validates signed scalar size"), } // Even a discarded load performs the memory access and can fault. if let Some(offset) = offset(data) { - code.extend([0x48, 0x89, 0x8f]); // mov [rdi+disp32],rcx - code.extend(offset.to_le_bytes()); + asm.mov_store(Size::Qword, frame(offset), Rcx); } } } @@ -237,14 +332,14 @@ pub struct MemoryChecks { /// 16-byte granule faults. Atomics always fault there (FEAT_LSE2). pub ordered_granule: bool, /// Every access checks its address against the guest's native ranges - /// ([`RangeCheck`]). `SystemModeV1` sets it for every block, whatever + /// ([`RangeCheck`]). The direct system-mode profile sets it for every block, whatever /// the engine asks, and no other profile does. pub(crate) guest_range: bool, /// No other agent accesses guest memory while the block runs: the /// system engine runs one PE at a time, and no device or host agent /// writes guest RAM meanwhile. Atomics, ordered accesses and barriers /// then need no LOCK, XCHG, MFENCE or 16-byte snapshot - /// ([`plain_ordering`]). `SystemModeV1` sets it for every block, and no + /// ([`plain_ordering`]). The direct system-mode profile sets it for every block, and no /// other profile does. pub(crate) single_agent: bool, /// FEAT_CSV3: every access checks the guest range, those @@ -422,30 +517,43 @@ impl RangeCheck { self.shift < u64::BITS as u8 && self.bias <= IMM8_MAX && self.bound <= IMM8_MAX } - /// The bytes before the failure: the shift, the bias, the comparison - /// and the branch over the failure, of `failure` bytes. - fn test(self, code: &mut Vec, failure: u8) { - code.extend([0x48, 0x89, 0xc1, 0x48, 0xc1, 0xf9, self.shift]); // mov rcx,rax; sar rcx,shift + /// The shift, the bias and the comparison, and the branch past the + /// failure, which the caller binds. + fn test(self, asm: &mut asm::Asm) -> asm::Patch { + use asm::{ + Alu, Cond, + Gpr::{Rax, Rcx}, + ShiftOp, Size, + }; + asm.mov(Size::Qword, Rcx, Rax); + asm.shift_imm(ShiftOp::Sar, Size::Qword, Rcx, self.shift); if self.bias == OPCODE_INC { - code.extend([0xff, 0xc1]); // inc ecx + asm.inc(Size::Dword, Rcx); } else { - code.extend([0x83, 0xc1, self.bias]); // add ecx,bias + asm.alu_imm8(Alu::Add, Size::Dword, Rcx, self.bias as i8); } - code.extend([0x83, 0xf9, self.bound, 0x76, failure]); // cmp ecx,bound; jbe past the failure + asm.alu_imm8(Alu::Cmp, Size::Dword, Rcx, self.bound as i8); + asm.jcc8(Cond::Be) } /// The mask after the check. - fn mask(self, code: &mut Vec) { - code.extend([0x48, 0xb9]); // mov rcx,masked - code.extend(self.masked.to_le_bytes()); - code.extend([0x48, 0x0f, 0x47, 0xc1]); // cmova rax,rcx + fn mask(self, asm: &mut asm::Asm) { + use asm::{ + Cond, + Gpr::{Rax, Rcx}, + Size, + }; + asm.mov_imm64(Rcx, self.masked); + asm.cmov(Cond::A, Size::Qword, Rax, Rcx); } /// The check with a UD2 failure. - pub(crate) fn emit(self, code: &mut Vec) { - self.test(code, UD2.len() as u8); - code.extend(UD2); - self.mask(code); + pub(crate) fn emit(self, code: &mut Code) { + let mut asm = code.asm(); + let passed = self.test(&mut asm); + asm.ud2(); + asm.bind(passed); + self.mask(&mut asm); } /// The translated variant's check: a failure calls the translation @@ -453,21 +561,29 @@ impl RangeCheck { /// address in RCX and `access` in the two bytes after the call; the /// helper returns past them with the host address of the access in RAX, /// which skips the mask (docs/design/system.md, "Host placement"). - pub(crate) fn emit_translated(self, code: &mut Vec, helper: u64, access: Access) { - self.test(code, TRANSLATION_CALL_BYTES); - code.extend([0x48, 0x89, 0xc1, 0x48, 0xa1]); // mov rcx,rax; movabs rax,[helper] - code.extend(helper.to_le_bytes()); - code.extend([0xff, 0xd0, access.bytes, access.flags]); // call rax; the access - code.extend([0xeb, MASK_BYTES]); // jmp past the mask - self.mask(code); + pub(crate) fn emit_translated(self, code: &mut Code, helper: u64, access: Access) { + use asm::{ + Gpr::{Rax, Rcx}, + Size, + }; + let mut asm = code.asm(); + let passed = self.test(&mut asm); + asm.mov(Size::Qword, Rcx, Rax); + asm.mov_rax_moffs(helper); + asm.call_rm(Rax); + asm.data(&[access.bytes, access.flags]); + let translated = asm.jmp8(); + asm.bind(passed); + self.mask(&mut asm); + asm.bind(translated); } /// [`Self::emit`]'s bytes. #[cfg(test)] pub(crate) fn code(self) -> Vec { - let mut code = Vec::new(); + let mut code = Code::new(); self.emit(&mut code); - code + code.into_bytes() } /// If `code` starts with a check of any placement, its length and the @@ -552,7 +668,6 @@ impl RangeCheck { } } -const UD2: [u8; 2] = [0x0f, 0x0b]; /// The translated variant's call, from `mov rcx,rax` through the jump /// past the mask. const TRANSLATION_CALL_BYTES: u8 = 19; @@ -603,11 +718,21 @@ impl Access { /// SCTLR_ELx.SA's check of an SP base in RAX, before the address addition /// as Arm checks it ([`MemoryChecks::stack_alignment`]). -pub(crate) const STACK_ALIGNMENT_CHECK: [u8; 6] = [ - 0xa8, 15, // test al,15 - 0x74, 2, // jz +2 - 0x0f, 0x0b, // ud2 -]; +pub(crate) fn stack_alignment_check(code: &mut Code) { + alignment_test(&mut code.asm(), 16); +} + +/// `test al,unit-1; jz +2; ud2`: #UD unless RAX is a multiple of `unit`. +fn alignment_test(asm: &mut asm::Asm, unit: u8) { + asm.test_accumulator_imm(asm::Size::Byte, i32::from(unit - 1)); + let aligned = asm.jcc8(asm::Cond::E); + asm.ud2(); + asm.bind(aligned); +} + +/// The bytes of [`stack_alignment_check`], which the region cost gates +/// find it by. +pub(crate) const STACK_ALIGNMENT_CHECK: [u8; 6] = [0xa8, 15, 0x74, 2, 0x0f, 0x0b]; /// The end of each of the three host instructions of /// [`STACK_ALIGNMENT_CHECK`], which the region cost gates count. @@ -615,7 +740,7 @@ pub(crate) const STACK_ALIGNMENT_CHECK_ENDS: [usize; 3] = [2, 4, 6]; /// The guest range check of `access`'s address in RAX, in the variant /// `checks` selects. -pub(crate) fn range_check(code: &mut Vec, checks: MemoryChecks, access: Access) { +pub(crate) fn range_check(code: &mut Code, checks: MemoryChecks, access: Access) { if checks.translated { checks .range @@ -625,7 +750,7 @@ pub(crate) fn range_check(code: &mut Vec, checks: MemoryChecks, access: Acce } } -fn guest_range_check(code: &mut Vec, checks: MemoryChecks, access: Access) { +fn guest_range_check(code: &mut Code, checks: MemoryChecks, access: Access) { if checks.guest_range { range_check(code, checks, access); } @@ -635,17 +760,17 @@ fn guest_range_check(code: &mut Vec, checks: MemoryChecks, access: Access) { /// SCTLR_ELx.A against `unit`, the bytes of each element it transfers. The /// translated variant's host address keeps the guest address's offset in /// its page, so the alignment checks see the same low bits. -fn address_checks(code: &mut Vec, checks: MemoryChecks, unit: u8, access: Access) { +fn address_checks(code: &mut Code, checks: MemoryChecks, unit: u8, access: Access) { guest_range_check(code, checks, access); alignment_check(code, checks, unit); } /// SCTLR_ELx.A's check of the effective address in RAX against `unit`, the /// bytes of each element the access transfers. -fn alignment_check(code: &mut Vec, checks: MemoryChecks, unit: u8) { +fn alignment_check(code: &mut Code, checks: MemoryChecks, unit: u8) { if checks.alignment && unit > 1 { debug_assert!(unit.is_power_of_two() && unit <= 16); - code.extend([0xa8, unit - 1, 0x74, 2, 0x0f, 0x0b]); // test al,unit-1; jz +2; ud2 + alignment_test(&mut code.asm(), unit); } } @@ -655,7 +780,7 @@ fn alignment_check(code: &mut Vec, checks: MemoryChecks, unit: u8) { /// access. #[allow(clippy::too_many_arguments)] fn memory_address( - code: &mut Vec, + code: &mut Code, checks: MemoryChecks, base: Register, displacement: i32, @@ -667,55 +792,44 @@ fn memory_address( if base == Register::Sp && checks.stack_alignment && !checks.stack_checked { // Arm checks SP alignment before address addition. A native UD2 is a // mapped fault boundary, not guest exception delivery. - code.extend(STACK_ALIGNMENT_CHECK); + stack_alignment_check(code); } address_add(code, displacement, mode); address_checks(code, checks, unit, access); } -const LEA_RAX_RAX_DISP8: [u8; 3] = [0x48, 0x8d, 0x40]; -const LEA_RAX_RAX_DISP32: [u8; 3] = [0x48, 0x8d, 0x80]; -const LEA_RDX_RAX_DISP8: [u8; 3] = [0x48, 0x8d, 0x50]; -const LEA_RDX_RAX_DISP32: [u8; 3] = [0x48, 0x8d, 0x90]; -const MOV_RDX_RAX: [u8; 3] = [0x48, 0x89, 0xc2]; -const MOV_RAX_RDX: [u8; 3] = [0x48, 0x89, 0xd0]; - /// An immediate offset added to the base in RAX, modulo 2^64 and without /// touching host flags: RAX becomes the access address, and pre- and /// post-index forms leave the pending writeback in RDX. An Offset access /// leaves RDX unspecified and emits nothing for a zero offset. -pub(crate) fn address_add(code: &mut Vec, displacement: i32, mode: AddressMode) { +pub(crate) fn address_add(code: &mut Code, displacement: i32, mode: AddressMode) { + use asm::{ + Gpr::{Rax, Rdx}, + Mem, Size, + }; let offset = mode == AddressMode::Offset; + let mut asm = code.asm(); if displacement == 0 { if !offset { - code.extend(MOV_RDX_RAX); + asm.mov(Size::Qword, Rdx, Rax); } return; } - let compact = i8::try_from(displacement).ok(); - code.extend(match (offset, compact.is_some()) { - (true, true) => LEA_RAX_RAX_DISP8, - (true, false) => LEA_RAX_RAX_DISP32, - (false, true) => LEA_RDX_RAX_DISP8, - (false, false) => LEA_RDX_RAX_DISP32, - }); - match compact { - Some(value) => code.push(value as u8), - None => code.extend(displacement.to_le_bytes()), - } + let sum = match i8::try_from(displacement) { + Ok(short) => Mem::base_disp8(Rax, short), + Err(_) => Mem::base_disp32(Rax, displacement), + }; + asm.lea(Size::Qword, if offset { Rax } else { Rdx }, sum); if mode == AddressMode::PreIndex { - code.extend(MOV_RAX_RDX); + asm.mov(Size::Qword, Rax, Rdx); } } -fn memory_writeback(code: &mut Vec, base: Register, mode: AddressMode) { +fn memory_writeback(code: &mut Code, base: Register, mode: AddressMode) { if mode != AddressMode::Offset { - code.extend([0x48, 0x89, 0x97]); // mov [rdi+disp32],rdx - code.extend( - offset(base) - .expect("memory base cannot be ZR") - .to_le_bytes(), - ); + let offset = offset(base).expect("memory base cannot be ZR"); + code.asm() + .mov_store(asm::Size::Qword, frame(offset), asm::Gpr::Rdx); } } @@ -724,7 +838,7 @@ fn memory_writeback(code: &mut Vec, base: Register, mode: AddressMode) { /// Concurrent/128-bit single-copy atomic semantics are outside this RAM profile. #[allow(clippy::too_many_arguments)] fn memory_pair( - code: &mut Vec, + code: &mut Code, checks: MemoryChecks, transfer: MemoryTransfer, bytes: u8, @@ -737,12 +851,11 @@ fn memory_pair( memory_address(code, checks, base, displacement, mode, bytes, access); match transfer { MemoryTransfer::Store => { + use asm::{Alu, Gpr::R8, Size}; right_operand(code, data[0], Width::X64, Shift::Lsl, 0); - if let Some(offset) = offset(data[1]) { - code.extend([0x4c, 0x8b, 0x87]); // mov r8,[rdi+disp32] - code.extend(offset.to_le_bytes()); - } else { - code.extend([0x45, 0x31, 0xc0]); // xor r8d,r8d + match offset(data[1]) { + Some(offset) => code.asm().mov_load(Size::Qword, R8, frame(offset)), + None => code.asm().alu(Alu::Xor, Size::Dword, R8, R8), } let aligned = checks.stack_alignment && memory_store::aligned_immediate(base, displacement, mode, bytes); @@ -750,22 +863,27 @@ fn memory_pair( memory_store::emit(code, bytes, bytes, memory_store::Source::R8, aligned); } MemoryTransfer::Load { signed, width } => { - if width == Width::X64 { - code.push(0x48); + use asm::{ + Gpr::{R8, Rax, Rcx}, + Mem, Size, + }; + let size = Size::of(width == Width::X64); + let mut asm = code.asm(); + for (destination, source) in + [(Rcx, accessed()), (R8, Mem::base_disp8(Rax, bytes as i8))] + { + if signed { + debug_assert!(width == Width::X64, "LDPSW writes X registers"); + asm.movsxd(destination, source); + } else { + asm.mov_load(size, destination, source); + } } - code.extend([if signed { 0x63 } else { 0x8b }, 0x08]); - code.extend([ - if width == Width::X64 { 0x4c } else { 0x44 }, - if signed { 0x63 } else { 0x8b }, - 0x40, - bytes, - ]); // Commit only after both loads succeeded, including discarded/ZR // destinations. RAX/RDX retain address and potential writeback. - for (register, rex, modrm) in [(data[0], 0x48, 0x8f), (data[1], 0x4c, 0x87)] { + for (register, staged) in [(data[0], Rcx), (data[1], R8)] { if let Some(offset) = offset(register) { - code.extend([rex, 0x89, modrm]); - code.extend(offset.to_le_bytes()); + asm.mov_store(Size::Qword, frame(offset), staged); } } } @@ -773,84 +891,106 @@ fn memory_pair( memory_writeback(code, base, mode); } -fn right_operand(code: &mut Vec, register: Register, width: Width, shift: Shift, amount: u8) { - if let Some(offset) = offset(register) { - code.extend([0x48, 0x8b, 0x8f]); - code.extend(offset.to_le_bytes()); - } else { - code.extend([0x31, 0xc9]); +fn right_operand(code: &mut Code, register: Register, width: Width, shift: Shift, amount: u8) { + right_operand_with(&mut code.asm(), register, width, shift, amount); +} + +/// RCX = the guest register (zero for XZR) shifted by `amount`. +fn right_operand_with( + asm: &mut asm::Asm, + register: Register, + width: Width, + shift: Shift, + amount: u8, +) { + use asm::{Alu, Gpr, Mem, ShiftOp, Size}; + match offset(register) { + Some(offset) => asm.mov_load( + Size::Qword, + Gpr::Rcx, + Mem::base_disp32(Gpr::Rdi, offset as i32), + ), + None => asm.alu(Alu::Xor, Size::Dword, Gpr::Rcx, Gpr::Rcx), } if amount != 0 { - if width == Width::X64 { - code.push(0x48); - } - code.extend([ - 0xc1, - match shift { - Shift::Lsl => 0xe1, - Shift::Lsr => 0xe9, - Shift::Asr => 0xf9, - Shift::Ror => 0xc9, - }, - amount, - ]); + let op = match shift { + Shift::Lsl => ShiftOp::Shl, + Shift::Lsr => ShiftOp::Shr, + Shift::Asr => ShiftOp::Sar, + Shift::Ror => ShiftOp::Ror, + }; + asm.shift_imm(op, Size::of(width == Width::X64), Gpr::Rcx, amount); } } +/// A rel32 jump to guest `target`, taken under `cond` or always, whose +/// displacement field `fixups` records for `pc`. fn jump( - code: &mut Vec, - opcode: Option, + code: &mut Code, + cond: Option, pc: GuestAddress, target: GuestAddress, fixups: &mut Vec<(GuestAddress, GuestAddress, usize)>, ) { - if let Some(opcode) = opcode { - code.extend([0x0f, opcode]); - } else { - code.push(0xe9); - } - fixups.push((pc, target, code.len())); - code.extend([0; 4]); + let mut asm = code.asm(); + let patch = match cond { + Some(cond) => asm.jcc(cond), + None => asm.jmp(), + }; + fixups.push((pc, target, patch.offset())); } -/// Evaluate ARM conditions from saved NZCV, independent of incidental host flags. -fn condition(code: &mut Vec, condition: u8) -> Option { - condition_of(code, condition, false) +/// Evaluate ARM conditions from saved NZCV, independent of incidental host +/// flags: the second opcode byte of the `jcc rel32` taken when it holds. +fn condition(code: &mut Code, condition: u8) -> Option { + const JCC_REL32: u8 = 0x80; + condition_holds(code, condition, false).map(|cond| JCC_REL32 | cond as u8) } -/// [`condition`], from the NZCV word already in EAX when `loaded` -/// ([`Rax::Nzcv`]). Clobbers EAX and ECX. -fn condition_of(code: &mut Vec, condition: u8, loaded: bool) -> Option { +/// The host condition under which ARM `condition` holds, from saved NZCV or +/// from the NZCV word already in EAX when `loaded` ([`Rax::Nzcv`]). Clobbers +/// EAX and ECX. +fn condition_holds(code: &mut Code, condition: u8, loaded: bool) -> Option { + use asm::{ + Alu, Cond, + Gpr::{Rax, Rcx}, + ShiftOp, Size, + }; + const NZCV: u32 = core::mem::offset_of!(crate::GuestState, nzcv) as u32; if condition >= 14 { return None; } // AL and NV both satisfy ConditionHolds. + let mut asm = code.asm(); if !loaded { - code.extend([0x8b, 0x87, 0, 1, 0, 0]); // mov eax,[rdi+256] + asm.mov_load(Size::Dword, Rax, frame(NZCV)); } - let positive = match condition / 2 { + let (positive, negative) = match condition / 2 { 0..=3 => { let bit = [30, 29, 31, 28][usize::from(condition / 2)]; - code.push(0xa9); - code.extend((1u32 << bit).to_le_bytes()); - 0x85 // flag set -> JNZ + asm.test_accumulator_imm(Size::Dword, (1u32 << bit) as i32); + (Cond::Ne, Cond::E) // flag set } 4 => { - code.push(0x25); - code.extend(0x60000000u32.to_le_bytes()); - code.push(0x3d); - code.extend(0x20000000u32.to_le_bytes()); - 0x84 // C && !Z + asm.alu_accumulator_imm32(Alu::And, Size::Dword, 0x60000000); + asm.alu_accumulator_imm32(Alu::Cmp, Size::Dword, 0x20000000); + (Cond::E, Cond::Ne) // C && !Z } group => { // EAX ^= EAX >> 3 leaves N ^ V in bit 28 and Z in bit 30, whatever // the bits below NZCV hold. - code.extend([0x89, 0xc1, 0xc1, 0xe9, 3, 0x31, 0xc8, 0xa9]); + asm.mov(Size::Dword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rcx, 3); + asm.alu(Alu::Xor, Size::Dword, Rax, Rcx); let mask: u32 = if group == 5 { 0x10000000 } else { 0x50000000 }; - code.extend(mask.to_le_bytes()); - 0x84 // N == V, and for GT !Z + asm.test_accumulator_imm(Size::Dword, mask as i32); + (Cond::E, Cond::Ne) // N == V, and for GT !Z } }; - Some(positive ^ (condition & 1)) + Some(if condition & 1 == 0 { + positive + } else { + negative + }) } /// What RAX holds after an instruction's emission, for the next one to @@ -897,47 +1037,42 @@ pub(super) fn rax_after(operation: &Operation) -> Rax { /// [`load`]'s bytes for a frame register. pub(super) fn frame_load(register: Register) -> Option<[u8; 7]> { - let mut code = Vec::new(); + let mut code = Code::new(); load(&mut code, register); code.try_into().ok() } /// [`store`]'s bytes for a frame register. pub(super) fn frame_store(register: Register) -> Option<[u8; 7]> { - let mut code = Vec::new(); + let mut code = Code::new(); store(&mut code, register); code.try_into().ok() } -fn immediate(code: &mut Vec, value: u64) { - code.extend([0x48, 0xb8]); // movabs rax,imm64 - code.extend(value.to_le_bytes()); +/// `movabs rax,value`. +fn immediate(code: &mut Code, value: u64) { + code.asm().mov_imm64(asm::Gpr::Rax, value); } -fn nzcv(code: &mut Vec, subtract: bool) { - const STATE_NZCV_OFFSET: u32 = core::mem::offset_of!(crate::GuestState, nzcv) as u32; +fn nzcv(code: &mut Code, subtract: bool) { capture_nzcv(code, subtract); - code.extend([0x89, 0x87]); // mov dword [rdi+GuestState.nzcv],eax - code.extend(STATE_NZCV_OFFSET.to_le_bytes()); + store_nzcv(&mut code.asm()); } -/// SETcc into AL, AH, DL and DH: N | Z << 8 and C | V << 8. -const CAPTURE_SIGN_AL: [u8; 3] = [0x0f, 0x98, 0xc0]; -const CAPTURE_ZERO_AH: [u8; 3] = [0x0f, 0x94, 0xc4]; -const CAPTURE_BELOW_DL: [u8; 3] = [0x0f, 0x92, 0xc2]; -const CAPTURE_ABOVE_EQUAL_DL: [u8; 3] = [0x0f, 0x93, 0xc2]; -const CAPTURE_OVERFLOW_DH: [u8; 3] = [0x0f, 0x90, 0xc6]; -const AND_EAX_IMM32: u8 = 0x25; -/// `lea eax,[rax+rdx*4]`: C and V move above N and Z, giving -/// N | C << 2 | Z << 8 | V << 10 in the low 16 bits. +/// `mov dword [rdi+GuestState.nzcv],eax`. +fn store_nzcv(asm: &mut asm::Asm) { + const NZCV: u32 = core::mem::offset_of!(crate::GuestState, nzcv) as u32; + asm.mov_store(asm::Size::Dword, frame(NZCV), asm::Gpr::Rax); +} + +/// The bytes of the capture's `lea eax,[rax+rdx*4]`, which the region cost +/// gates find it by. pub(crate) const CAPTURE_COMBINE: [u8; 3] = [0x8d, 0x04, 0x90]; -const IMUL_EAX_EAX_IMM32: [u8; 2] = [0x69, 0xc0]; +/// The scale of the capture's LEA: C and V move above N and Z. +const CAPTURE_CARRY_SHIFT: u8 = 2; /// The SETcc bytes' low bits. #[cfg(test)] const CAPTURED_BITS: u32 = 0x0101; -/// The scale of [`CAPTURE_COMBINE`]. -#[cfg(test)] -const CAPTURE_CARRY_SHIFT: u8 = 2; /// One product moves N (bit 0) to 31, Z (8) to 30, C (2) to 29 and V (10) /// to 28. Every other partial product of the low 16 bits lands below bit 28 /// or above bit 31, on a bit no other lands on, so nothing carries into @@ -951,30 +1086,41 @@ const _: () = assert!(CAPTURE_MULTIPLIER.trailing_zeros() + u16::BITS >= u32::BI /// branch or an instruction outside Intel's data operand independent timing /// list (SETcc, LEA, IMUL, AND). `borrow` takes C as an Arm subtraction /// does, the complement of the host carry. Clobbers RDX; RCX is intact. -pub(crate) fn capture_nzcv(code: &mut Vec, borrow: bool) { - code.extend(CAPTURE_SIGN_AL); - code.extend(CAPTURE_ZERO_AH); - code.extend(if borrow { - CAPTURE_ABOVE_EQUAL_DL - } else { - CAPTURE_BELOW_DL - }); - code.extend(CAPTURE_OVERFLOW_DH); - code.extend(CAPTURE_COMBINE); - code.extend(IMUL_EAX_EAX_IMM32); - code.extend(CAPTURE_MULTIPLIER.to_le_bytes()); - code.push(AND_EAX_IMM32); - code.extend(CAPTURE_NZCV_MASK.to_le_bytes()); +pub(crate) fn capture_nzcv(code: &mut Code, borrow: bool) { + use asm::{ + Alu, Cond, + Gpr::{Rax, Rdx}, + Mem, Size, + control::HighByte, + }; + let mut asm = code.asm(); + // N | Z << 8 in AX and C | V << 8 in DX. + asm.setcc(Cond::S, Rax); + asm.setcc_high(Cond::E, HighByte::Ah); + asm.setcc(if borrow { Cond::Ae } else { Cond::B }, Rdx); + asm.setcc_high(Cond::O, HighByte::Dh); + // N | C << 2 | Z << 8 | V << 10 in the low 16 bits. + asm.lea( + Size::Dword, + Rax, + Mem::indexed(Rax, Rdx, 1 << CAPTURE_CARRY_SHIFT, 0), + ); + asm.imul_imm32(Size::Dword, Rax, Rax, CAPTURE_MULTIPLIER as i32); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, CAPTURE_NZCV_MASK as i32); } /// Shared semantic emission. Block compilation handles control transfers itself. pub(crate) fn emit_instruction( - code: &mut Vec, + code: &mut Code, instruction: &Instruction, fixups: &mut Vec<(GuestAddress, GuestAddress, usize)>, target: crate::TargetCpu, checks: MemoryChecks, ) { + use asm::{ + Alu, BitTest, + Gpr::{Rax, Rcx}, + }; match instruction.operation { Operation::FloatingPoint(_) => { unreachable!("numerical instructions require block emission") @@ -1036,8 +1182,8 @@ pub(crate) fn emit_instruction( target, condition: cond, } => { - let opcode = condition(code, cond); - jump(code, opcode, instruction.pc, target, fixups); + let holds = condition_holds(code, cond, false); + jump(code, holds, instruction.pc, target, fixups); } Operation::BranchZero { target, @@ -1046,17 +1192,8 @@ pub(crate) fn emit_instruction( nonzero, } => { load(code, source); - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x85, 0xc0]); - jump( - code, - Some(if nonzero { 0x85 } else { 0x84 }), - instruction.pc, - target, - fixups, - ); + let holds = test_zero(code, width, nonzero); + jump(code, Some(holds), instruction.pc, target, fixups); } Operation::BranchBit { target, @@ -1065,14 +1202,8 @@ pub(crate) fn emit_instruction( nonzero, } => { load(code, source); - code.extend([0x48, 0x0f, 0xba, 0xe0, bit]); // bt rax,imm8 - jump( - code, - Some(if nonzero { 0x82 } else { 0x83 }), - instruction.pc, - target, - fixups, - ); + let holds = test_bit(code, bit, nonzero); + jump(code, Some(holds), instruction.pc, target, fixups); } Operation::AddSubCarry { width, @@ -1087,19 +1218,17 @@ pub(crate) fn emit_instruction( // Arm's SBC is AddWithCarry(left, NOT(right), C): ADC of the // complement, whose host CF and OF are Arm's C and V. (CMC is // not on Intel's data operand independent timing list.) + const NZCV: u32 = core::mem::offset_of!(crate::GuestState, nzcv) as u32; + const CARRY_BIT: u8 = 29; + let size = asm::Size::of(width == Width::X64); + let mut asm = code.asm(); if subtract { - if width == Width::X64 { - code.push(0x48); - } - code.extend([0xf7, 0xd1]); // not (e/r)cx + asm.unary(asm::Unary::Not, size, Rcx); } // Recover guest C after operand loads, including XOR-based // ZR loads that clobber host flags. - code.extend([0x0f, 0xba, 0xa7, 0, 1, 0, 0, 29]); // bt [rdi+256],29 - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x11, 0xc8]); // adc (e/r)ax,(e/r)cx + asm.bit_imm(BitTest::Bt, asm::Size::Dword, frame(NZCV), CARRY_BIT); + asm.alu(Alu::Adc, size, Rax, Rcx); store(code, destination); if flags { nzcv(code, false); @@ -1117,10 +1246,7 @@ pub(crate) fn emit_instruction( } => { load(code, left); right_operand(code, right, width, shift, amount); - if width == Width::X64 { - code.push(0x48); - } - code.extend([if subtract { 0x29 } else { 0x01 }, 0xc8]); + add_sub(code, width, subtract); store(code, destination); if flags { nzcv(code, subtract); @@ -1139,23 +1265,22 @@ pub(crate) fn emit_instruction( // Read both operands before a possibly overlapping destination/SP write. load(code, left); right_operand(code, right, Width::X64, Shift::Lsl, 0); + use asm::Size::{Byte, Dword, Qword, Word}; + let mut asm = code.asm(); match extend { - RegisterExtend::Uxtb => code.extend([0x0f, 0xb6, 0xc9]), // movzx ecx,cl - RegisterExtend::Uxth => code.extend([0x0f, 0xb7, 0xc9]), // movzx ecx,cx - RegisterExtend::Uxtw => code.extend([0x89, 0xc9]), // mov ecx,ecx - RegisterExtend::Sxtb => code.extend([0x48, 0x0f, 0xbe, 0xc9]), - RegisterExtend::Sxth => code.extend([0x48, 0x0f, 0xbf, 0xc9]), - RegisterExtend::Sxtw => code.extend([0x48, 0x63, 0xc9]), + RegisterExtend::Uxtb => asm.movzx(Dword, Rcx, Byte, Rcx), + RegisterExtend::Uxth => asm.movzx(Dword, Rcx, Word, Rcx), + RegisterExtend::Uxtw => asm.mov(Dword, Rcx, Rcx), + RegisterExtend::Sxtb => asm.movsx(Qword, Rcx, Byte, Rcx), + RegisterExtend::Sxth => asm.movsx(Qword, Rcx, Word, Rcx), + RegisterExtend::Sxtw => asm.movsxd(Rcx, Rcx), RegisterExtend::Uxtx | RegisterExtend::Sxtx => {} } if amount != 0 { - code.extend([0x48, 0xc1, 0xe1, amount]); - } - if width == Width::X64 { - code.push(0x48); + asm.shift_imm(asm::ShiftOp::Shl, Qword, Rcx, amount); } // W32 arithmetic truncates both operands and zero-extends even WSP. - code.extend([if subtract { 0x29 } else { 0x01 }, 0xc8]); + add_sub(code, width, subtract); store(code, destination); if flags { nzcv(code, subtract); @@ -1177,19 +1302,9 @@ pub(crate) fn emit_instruction( immediate, } => { load(code, source); - code.extend([0x48, 0xb9]); // movabs rcx,logical bitmask - code.extend(immediate.to_le_bytes()); - if width == Width::X64 { - code.push(0x48); - } - code.extend([ - match kind { - Logical::And => 0x21, - Logical::Or => 0x09, - Logical::Xor => 0x31, - }, - 0xc8, - ]); + let mut asm = code.asm(); + asm.mov_imm64(Rcx, immediate); + asm.alu(logical(kind), asm::Size::of(width == Width::X64), Rax, Rcx); store(code, destination); // MOV preserves the logical result flags. if flags { nzcv(code, false); // AND clears CF/OF, matching ARM C/V=0. @@ -1208,34 +1323,23 @@ pub(crate) fn emit_instruction( } => { load(code, left); right_operand(code, right, width, shift, amount); + let size = asm::Size::of(width == Width::X64); + let mut asm = code.asm(); if invert { - if width == Width::X64 { - code.push(0x48); - } - code.extend([0xf7, 0xd1]); + asm.unary(asm::Unary::Not, size, Rcx); } - if width == Width::X64 { - code.push(0x48); - } - code.extend([ - match kind { - Logical::And => 0x21, - Logical::Or => 0x09, - Logical::Xor => 0x31, - }, - 0xc8, - ]); + asm.alu(logical(kind), size, Rax, Rcx); store(code, destination); if flags { nzcv(code, false); } // AND clears host CF/OF, matching ARM C/V=0. } - Operation::Return => code.push(0xc3), + Operation::Return => code.asm().ret(), Operation::Exclusive(_) => unreachable!("exclusive requires checked context emitter"), Operation::CheckedPointer(_) => { unreachable!("CPA arithmetic requires checked context emitter") } - Operation::Nop => code.push(NOP), + Operation::Nop => code.asm().nop(), Operation::MoveWide { width, kind, @@ -1243,22 +1347,24 @@ pub(crate) fn emit_instruction( immediate: value, shift, } => { + use asm::Size::{Dword, Qword}; let value = u64::from(value) << shift; match kind { WideMove::Zero => immediate(code, value), WideMove::Not => immediate(code, !value), WideMove::Keep => { load(code, destination); - code.extend([0x48, 0xb9]); // movabs rcx,mask - code.extend((!(0xffffu64 << shift)).to_le_bytes()); - code.extend([0x48, 0x21, 0xc8, 0x48, 0xb9]); // and rax,rcx; movabs rcx,value - code.extend(value.to_le_bytes()); - code.extend([0x48, 0x09, 0xc8]); + let mut asm = code.asm(); + asm.mov_imm64(Rcx, !(0xffffu64 << shift)); + asm.alu(Alu::And, Qword, Rax, Rcx); + asm.mov_imm64(Rcx, value); + asm.alu(Alu::Or, Qword, Rax, Rcx); } } if width == Width::W32 { - code.extend([0x89, 0xc0]); - } // mov eax,eax: zero-extend + // Zero-extend. + code.asm().mov(Dword, Rax, Rax); + } store(code, destination); } Operation::AddSub { @@ -1270,11 +1376,12 @@ pub(crate) fn emit_instruction( immediate, } => { load(code, source); - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x81, if subtract { 0xe8 } else { 0xc0 }]); - code.extend(immediate.to_le_bytes()); + code.asm().alu_imm32( + if subtract { Alu::Sub } else { Alu::Add }, + asm::Size::of(width == Width::X64), + Rax, + immediate as i32, + ); store(code, destination); // MOV leaves arithmetic flags unchanged. if flags { nzcv(code, subtract); @@ -1294,10 +1401,7 @@ impl Emitter { instructions: &[Instruction], target: crate::TargetCpu, ) -> Result { - let mut block = NativeBlock { - x86_64_code: vec![], - source_map: vec![], - }; + let mut block = Emitted::default(); let code = &mut block.x86_64_code; let mut fixups = vec![]; for instruction in instructions { @@ -1331,7 +1435,7 @@ impl Emitter { let relative = i32::try_from(relative).map_err(|_| error())?; code[displacement..displacement + 4].copy_from_slice(&relative.to_le_bytes()); } - Ok(block) + Ok(block.into_native()) } } @@ -1401,7 +1505,7 @@ mod tests { n << 31 | z << 30 | c << 29 | v << 28 }; for borrow in [false, true] { - let mut code = MOV_RAX_RDI.to_vec(); + let mut code = Code::from(MOV_RAX_RDI.to_vec()); code.extend(MOVABS_RDX); code.extend(OTHER_BITS.to_le_bytes()); code.extend(if borrow { SUB_RAX_RSI } else { ADD_RAX_RSI }); @@ -1453,7 +1557,6 @@ mod tests { const MAP_ANONYMOUS: i32 = 0x20; const PAGE: usize = 4096; const LOAD_EAX_NZCV: [u8; 6] = [0x8b, 0x87, 0, 1, 0, 0]; - const SET_FROM_JUMP: u8 = 0x10; const MOVZX_EAX_AL_RET: [u8; 4] = [0x0f, 0xb6, 0xc0, 0xc3]; const LOW_BITS: u32 = 0x0fff_ffff; let holds = |condition: u8, nzcv: u32| { @@ -1471,13 +1574,13 @@ mod tests { }; for loaded in [false, true] { for condition in 0..14 { - let mut code = if loaded { + let mut code = Code::from(if loaded { LOAD_EAX_NZCV.to_vec() } else { vec![] - }; - let jcc = condition_of(&mut code, condition, loaded).unwrap(); - code.extend([0x0f, jcc + SET_FROM_JUMP, 0xc0]); + }); + let host = condition_holds(&mut code, condition, loaded).unwrap(); + code.asm().setcc(host, asm::Gpr::Rax); code.extend(MOVZX_EAX_AL_RET); // SAFETY: private anonymous memory, RX after the copy and // unmapped after the calls; the code reads only `state`. @@ -1544,8 +1647,8 @@ mod tests { rax: u64, rdx: u64, } - let run = |body: &dyn Fn(&mut Vec)| -> Result { - let mut code = MOV_RAX_RSI.to_vec(); + let run = |body: &dyn Fn(&mut Code)| -> Result { + let mut code = Code::from(MOV_RAX_RSI.to_vec()); body(&mut code); code.push(RET); let mut state = crate::GuestState::default(); @@ -1641,7 +1744,7 @@ mod tests { assert_eq!(bytes, full.len()); let (check, rest) = full.split_at(ends[4]); let (trap, mask) = rest.split_at(ends[5] - ends[4]); - assert_eq!(trap, UD2); + assert_eq!(trap, [0x0f, 0x0b]); assert_eq!(full.len(), if range.bias == 1 { 30 } else { 31 }); // mov rax,rdi; the check with `xor eax,eax` (a failure, also two // bytes, whose flags the mask then leaves alone) where its UD2 @@ -1772,7 +1875,7 @@ mod tests { let slot = alloc::boxed::Box::new(page as u64); // mov rax,rdi; the check; ret, then the same with the branch // always taken, as a misprediction runs it. - let mut check = vec![]; + let mut check = Code::new(); range.emit_translated(&mut check, &*slot as *const u64 as u64, access); let (bytes, ends) = RangeCheck::at(&check).unwrap(); assert_eq!(bytes, check.len()); @@ -1831,7 +1934,7 @@ mod tests { assert!(range.valid()); assert!(range.masked >= upper - (1 << SLICE_SHIFT) && range.masked < upper); assert!(upper - range.masked >= 1 << 35); - let mut code = Vec::new(); + let mut code = Code::new(); range.emit(&mut code); // A bias of 1 (63 slices) is INC, as five-level paging's. let ends = if slices == HALF_SLICES - 1 { @@ -1912,13 +2015,37 @@ mod tests { let packed = combined.wrapping_mul(CAPTURE_MULTIPLIER) & CAPTURE_NZCV_MASK; assert_eq!(packed, flags << 28, "NZCV {flags:#06b}"); } - let mut code = Vec::new(); + let mut code = Code::new(); capture_nzcv(&mut code, false); - let mut borrow = Vec::new(); + let mut borrow = Code::new(); capture_nzcv(&mut borrow, true); - // Only the carry's SETcc differs. + // Only the carry's SETcc differs: SETB or SETAE DL. assert_eq!(code.len(), borrow.len()); - assert_eq!(code[6..9], CAPTURE_BELOW_DL); - assert_eq!(borrow[6..9], CAPTURE_ABOVE_EQUAL_DL); + assert_eq!(code[6..9], [0x0f, 0x92, 0xc2]); + assert_eq!(borrow[6..9], [0x0f, 0x93, 0xc2]); + assert_eq!(code[12..15], CAPTURE_COMBINE); + assert_eq!((code.instructions(), borrow.instructions()), (7, 7)); + } + + /// The checks emit the bytes the region cost gates find them by, one + /// counted instruction for each end. + #[test] + fn checks_emit_the_patterns_the_cost_gates_match() { + let mut code = Code::new(); + stack_alignment_check(&mut code); + assert_eq!(code, STACK_ALIGNMENT_CHECK); + assert_eq!(code.instructions(), STACK_ALIGNMENT_CHECK_ENDS.len()); + for range in [RangeCheck::FIVE_LEVEL, RangeCheck::four_level(2)] { + let mut code = Code::new(); + range.emit(&mut code); + let (_, ends) = RangeCheck::at(&code).unwrap(); + assert_eq!(code.instructions(), ends.len()); + let mut code = Code::new(); + range.emit_translated(&mut code, 0x1000, Access::read(8)); + let (bytes, ends) = RangeCheck::at(&code).unwrap(); + assert_eq!(bytes, code.len()); + // The access's two bytes after the call are data. + assert_eq!(code.instructions(), ends.len() - 1); + } } } diff --git a/crates/stela-compiler/src/x86_64/amx.rs b/crates/stela-compiler/src/x86_64/amx.rs index fddf45900e..7cb1fd4719 100644 --- a/crates/stela-compiler/src/x86_64/amx.rs +++ b/crates/stela-compiler/src/x86_64/amx.rs @@ -14,11 +14,10 @@ //! where `z` is the 4 KiB Z grid, `x`/`y` are the 64-byte operands after the //! circular-pool wrap, and `row` is operand bits 25:20. The kernel writes only //! the Z rows its shape selects. -mod encoding; - +use crate::x86_64::asm::{Alu, Asm, Code, Evex, Gpr, Map, Mem, Pp, Rm, ShiftOp, Size, Vex}; use crate::{TargetCpu, amx::AmxOperation}; +use Gpr::{Rax, Rcx, Rdi, Rdx, Rsi, Rsp}; use alloc::vec::Vec; -use encoding::{Gpr, Map, Operand, Prefix, at, evex, legacy_memory, vex}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Precision { @@ -230,11 +229,19 @@ const UNORDERED: u8 = 5; const SIGN: u8 = 6; const DEFAULT_NAN: u8 = 7; const OPMASK: u8 = 1; +/// The kernel frame: [rsp] AMX MXCSR, [rsp+4] caller MXCSR, [rsp+8] a +/// constant being broadcast. +const FRAME_BYTES: i8 = 16; +const CALLER_MXCSR: i32 = 4; +const CONSTANT: i32 = 8; +/// log2 of the 64-byte Z row. +const ROW_SHIFT: u8 = 6; /// Emit one kernel for one tier. pub fn emit(kernel: Kernel, tier: Tier) -> Vec { - let mut code = Vec::new(); - prologue(&mut code, kernel, tier); + let mut code = Code::new(); + let mut asm = code.asm(); + prologue(&mut asm, kernel, tier); let rows = match kernel.shape { Shape::Matrix => kernel.lanes(), Shape::Vector => 1, @@ -248,73 +255,92 @@ pub fn emit(kernel: Kernel, tier: Tier) -> Vec { for row in 0..rows { let offset = row * stride; match tier { - Tier::Fma => vex_row(&mut code, kernel, row, offset), + Tier::Fma => vex_row(&mut asm, kernel, row, offset), Tier::Avx512 => { let accumulator = EVEX_Z_FIRST + (row as u8 % EVEX_Z_ROTATION); - evex_row(&mut code, kernel, row, offset, accumulator); + evex_row(&mut asm, kernel, row, offset, accumulator); } } } - epilogue(&mut code); - code + epilogue(&mut asm); + code.into_bytes() } -fn prologue(code: &mut Vec, kernel: Kernel, tier: Tier) { - // sub rsp, 16: [rsp+4] caller MXCSR, [rsp] AMX MXCSR, [rsp+8] constants. - code.extend([0x48, 0x83, 0xec, 0x10]); - legacy_memory(code, &[0x0f, 0xae], 3, at(Gpr::Rsp, 4)); - code.extend([0xc7, 0x04, 0x24]); - code.extend(MXCSR_ARM_ENVIRONMENT.to_le_bytes()); - legacy_memory(code, &[0x0f, 0xae], 2, at(Gpr::Rsp, 0)); +/// VEX.256 fields. +const fn ymm(map: Map, pp: Pp, w: bool) -> Vex { + Vex { + map, + pp, + w, + l: true, + } +} + +/// EVEX.512 fields. A broadcast reads one element; other memory operands +/// compress their displacement by the 64-byte vector. +const fn zmm(map: Map, pp: Pp, w: bool, broadcast: bool, mask: u8) -> Evex { + Evex { + map, + pp, + w, + length: 2, + mask, + zeroing: false, + broadcast, + scale: match (broadcast, w) { + (false, _) => 64, + (true, false) => 4, + (true, true) => 8, + }, + } +} + +/// `vbroadcastss/sd ymm, m` (VEX.256.66.0F38.W0 18/19). +fn vbroadcast(asm: &mut Asm<'_>, double: bool, register: u8, memory: Mem) { + let opcode = if double { 0x19 } else { 0x18 }; + asm.vex( + ymm(Map::M0f38, Pp::P66, false), + opcode, + register, + 0, + memory.into(), + ); +} + +/// Load `value` into every lane of `register`, through [rsp+8] for VEX. +fn constant(asm: &mut Asm<'_>, tier: Tier, double: bool, value: u64, register: u8) { + asm.mov_imm64(Rax, value); + match tier { + Tier::Fma => { + asm.mov_store(Size::Qword, Mem::base(Rsp, CONSTANT), Rax); + vbroadcast(asm, double, register, Mem::base(Rsp, CONSTANT)); + } + // vpbroadcastd/q zmm, eax/rax + Tier::Avx512 => asm.evex( + zmm(Map::M0f38, Pp::P66, double, false, 0), + 0x7c, + register, + 0, + Rm::Reg(Rax), + ), + } +} + +fn prologue(asm: &mut Asm<'_>, kernel: Kernel, tier: Tier) { + asm.alu_imm8(Alu::Sub, Size::Qword, Rsp, FRAME_BYTES); + asm.stmxcsr(Mem::base(Rsp, CALLER_MXCSR)); + asm.mov_rm_imm32(Size::Dword, Mem::base(Rsp, 0), MXCSR_ARM_ENVIRONMENT as i32); + asm.ldmxcsr(Mem::base(Rsp, 0)); let double = kernel.precision == Precision::Double; let sign = if double { 1u64 << 63 } else { 1 << 31 }; - let constant = |code: &mut Vec, value: u64, register: u8| { - // mov rax, imm64 - code.extend([0x48, 0xb8]); - code.extend(value.to_le_bytes()); - match tier { - Tier::Fma => { - // mov [rsp+8], rax; vbroadcastss/sd ymm, [rsp+8] - code.extend([0x48, 0x89, 0x44, 0x24, 0x08]); - let opcode = if double { 0x19 } else { 0x18 }; - vex( - code, - Map::Escape38, - Prefix::OperandSize, - false, - true, - opcode, - register, - 0, - Operand::Memory(at(Gpr::Rsp, 8)), - ); - } - // vpbroadcastd/q zmm, eax/rax - Tier::Avx512 => evex( - code, - Map::Escape38, - Prefix::OperandSize, - double, - 0x7c, - register, - 0, - Operand::Register(Gpr::Rax as u8), - false, - 0, - ), - } + let nan = if double { + DOUBLE_DEFAULT_NAN + } else { + u64::from(SINGLE_DEFAULT_NAN) }; - constant( - code, - if double { - DOUBLE_DEFAULT_NAN - } else { - u64::from(SINGLE_DEFAULT_NAN) - }, - DEFAULT_NAN, - ); + constant(asm, tier, double, nan, DEFAULT_NAN); if kernel.subtract && kernel.product_only { - constant(code, sign, SIGN); + constant(asm, tier, double, sign, SIGN); } // Select the Z row group: rdi += (row & (rows per group - 1)) * 64. let group_mask = match (kernel.shape, kernel.precision) { @@ -322,271 +348,165 @@ fn prologue(code: &mut Vec, kernel: Kernel, tier: Tier) { (Shape::Matrix, Precision::Double) => 7, (Shape::Vector, _) => 63, }; - code.extend([0x83, 0xe1, group_mask]); // and ecx, mask - code.extend([0xc1, 0xe1, 0x06]); // shl ecx, 6 - code.extend([0x48, 0x01, 0xcf]); // add rdi, rcx + asm.alu_imm8(Alu::And, Size::Dword, Rcx, group_mask); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rcx, ROW_SHIFT); + asm.alu(Alu::Add, Size::Qword, Rdi, Rcx); match tier { Tier::Fma => { for half in 0..2u8 { - vmovups_load(code, X + half, at(Gpr::Rsi, i32::from(half) * 32)); + vmovups_load(asm, X + half, Mem::base(Rsi, i32::from(half) * 32)); } } - Tier::Avx512 => evex( - code, - Map::Primary, - Prefix::None, - false, + Tier::Avx512 => asm.evex( + zmm(Map::M0f, Pp::None, false, false, 0), 0x10, X, 0, - Operand::Memory(at(Gpr::Rsi, 0)), - false, - 0, + Mem::base(Rsi, 0).into(), ), } } -fn epilogue(code: &mut Vec) { - code.extend([0xc5, 0xf8, 0x77]); // vzeroupper - legacy_memory(code, &[0x0f, 0xae], 2, at(Gpr::Rsp, 4)); - code.extend([0x48, 0x83, 0xc4, 0x10, 0xc3]); // add rsp, 16; ret +fn epilogue(asm: &mut Asm<'_>) { + asm.vzeroupper(); + asm.ldmxcsr(Mem::base(Rsp, CALLER_MXCSR)); + asm.alu_imm8(Alu::Add, Size::Qword, Rsp, FRAME_BYTES); + asm.ret(); } -fn vmovups_load(code: &mut Vec, register: u8, memory: encoding::Memory) { - vex( - code, - Map::Primary, - Prefix::None, - false, - true, +fn vmovups_load(asm: &mut Asm<'_>, register: u8, memory: Mem) { + asm.vex( + ymm(Map::M0f, Pp::None, false), 0x10, register, 0, - Operand::Memory(memory), + memory.into(), ); } -fn vmovups_store(code: &mut Vec, register: u8, memory: encoding::Memory) { - vex( - code, - Map::Primary, - Prefix::None, - false, - true, +fn vmovups_store(asm: &mut Asm<'_>, register: u8, memory: Mem) { + asm.vex( + ymm(Map::M0f, Pp::None, false), 0x11, register, 0, - Operand::Memory(memory), + memory.into(), ); } /// The packed-arithmetic prefix and W bit for the precision. -fn packed(kernel: Kernel) -> (Prefix, bool) { +fn packed(kernel: Kernel) -> (Pp, bool) { match kernel.precision { - Precision::Single => (Prefix::None, false), - Precision::Double => (Prefix::OperandSize, true), + Precision::Single => (Pp::None, false), + Precision::Double => (Pp::P66, true), } } -fn vex_row(code: &mut Vec, kernel: Kernel, row: i32, offset: i32) { +fn vex_row(asm: &mut Asm<'_>, kernel: Kernel, row: i32, offset: i32) { let double = kernel.precision == Precision::Double; - let (prefix, wide) = packed(kernel); - match kernel.shape { - Shape::Matrix => vex( - code, - Map::Escape38, - Prefix::OperandSize, - false, - true, - if double { 0x19 } else { 0x18 }, - Y, - 0, - Operand::Memory(at(Gpr::Rdx, row * kernel.element_bytes())), - ), - Shape::Vector => {} + let (pp, wide) = packed(kernel); + if kernel.shape == Shape::Matrix { + vbroadcast(asm, double, Y, Mem::base(Rdx, row * kernel.element_bytes())); } for half in 0..2u8 { let z = Z_FIRST + half; - let memory = at(Gpr::Rdi, offset + i32::from(half) * 32); - let y = match kernel.shape { - Shape::Matrix => Y, - Shape::Vector => { - vmovups_load(code, Y, at(Gpr::Rdx, i32::from(half) * 32)); - Y - } - }; + let memory = Mem::base(Rdi, offset + i32::from(half) * 32); + if kernel.shape == Shape::Vector { + vmovups_load(asm, Y, Mem::base(Rdx, i32::from(half) * 32)); + } if kernel.product_only { // vmulps/pd z, x, y - vex( - code, - Map::Primary, - prefix, - false, - true, - 0x59, - z, - X + half, - Operand::Register(y), - ); + asm.vex(ymm(Map::M0f, pp, false), 0x59, z, X + half, Rm::Xmm(Y)); if kernel.subtract { // vxorps/pd z, z, sign - vex( - code, - Map::Primary, - prefix, - false, - true, - 0x57, - z, - z, - Operand::Register(SIGN), - ); + asm.vex(ymm(Map::M0f, pp, false), 0x57, z, z, Rm::Xmm(SIGN)); } } else { - vmovups_load(code, z, memory); - // vfmadd231 / vfnmadd231: z = ±(x*y) + z + vmovups_load(asm, z, memory); + // vfmadd231 / vfnmadd231: z = ??(x*y) + z let opcode = if kernel.subtract { 0xbc } else { 0xb8 }; - vex( - code, - Map::Escape38, - Prefix::OperandSize, - wide, - true, + asm.vex( + ymm(Map::M0f38, Pp::P66, wide), opcode, z, X + half, - Operand::Register(y), + Rm::Xmm(Y), ); } // vcmpunordps/pd mask, z, z; vblendvps/pd z, z, nan, mask - vex( - code, - Map::Primary, - prefix, - false, - true, - 0xc2, - UNORDERED, - z, - Operand::Register(z), - ); - code.push(CMP_UNORDERED); - vex( - code, - Map::Escape3a, - Prefix::OperandSize, - false, - true, + asm.vex(ymm(Map::M0f, pp, false), 0xc2, UNORDERED, z, Rm::Xmm(z)); + asm.data(&[CMP_UNORDERED]); + asm.vex( + ymm(Map::M0f3a, Pp::P66, false), if double { 0x4b } else { 0x4a }, z, z, - Operand::Register(DEFAULT_NAN), + Rm::Xmm(DEFAULT_NAN), ); - code.push(UNORDERED << 4); - vmovups_store(code, z, memory); + asm.data(&[UNORDERED << 4]); + vmovups_store(asm, z, memory); } } -fn evex_row(code: &mut Vec, kernel: Kernel, row: i32, offset: i32, z: u8) { - let (prefix, wide) = packed(kernel); - let memory = at(Gpr::Rdi, offset); +fn evex_row(asm: &mut Asm<'_>, kernel: Kernel, row: i32, offset: i32, z: u8) { + let (pp, wide) = packed(kernel); + let memory = Mem::base(Rdi, offset); let (y, broadcast) = match kernel.shape { - Shape::Matrix => (at(Gpr::Rdx, row * kernel.element_bytes()), true), - Shape::Vector => (at(Gpr::Rdx, 0), false), + Shape::Matrix => (Mem::base(Rdx, row * kernel.element_bytes()), true), + Shape::Vector => (Mem::base(Rdx, 0), false), }; if kernel.product_only { // vmulps/pd z, x, y - evex( - code, - Map::Primary, - prefix, - wide, - 0x59, - z, - X, - Operand::Memory(y), - broadcast, - 0, - ); + asm.evex(zmm(Map::M0f, pp, wide, broadcast, 0), 0x59, z, X, y.into()); if kernel.subtract { // vpxord/q z, z, sign - evex( - code, - Map::Primary, - Prefix::OperandSize, - wide, + asm.evex( + zmm(Map::M0f, Pp::P66, wide, false, 0), 0xef, z, z, - Operand::Register(SIGN), - false, - 0, + Rm::Xmm(SIGN), ); } } else { - evex( - code, - Map::Primary, - Prefix::None, - false, + asm.evex( + zmm(Map::M0f, Pp::None, false, false, 0), 0x10, z, 0, - Operand::Memory(memory), - false, - 0, + memory.into(), ); let opcode = if kernel.subtract { 0xbc } else { 0xb8 }; - evex( - code, - Map::Escape38, - Prefix::OperandSize, - wide, + asm.evex( + zmm(Map::M0f38, Pp::P66, wide, broadcast, 0), opcode, z, X, - Operand::Memory(y), - broadcast, - 0, + y.into(), ); } // vcmpunordps/pd k1, z, z; vmovaps/pd z{k1}, nan - evex( - code, - Map::Primary, - prefix, - wide, + asm.evex( + zmm(Map::M0f, pp, wide, false, 0), 0xc2, OPMASK, z, - Operand::Register(z), - false, - 0, + Rm::Xmm(z), ); - code.push(CMP_UNORDERED); - evex( - code, - Map::Primary, - prefix, - wide, + asm.data(&[CMP_UNORDERED]); + asm.evex( + zmm(Map::M0f, pp, wide, false, OPMASK), 0x28, z, 0, - Operand::Register(DEFAULT_NAN), - false, - OPMASK, + Rm::Xmm(DEFAULT_NAN), ); - evex( - code, - Map::Primary, - Prefix::None, - false, + asm.evex( + zmm(Map::M0f, Pp::None, false, false, 0), 0x11, z, 0, - Operand::Memory(memory), - false, - 0, + memory.into(), ); } diff --git a/crates/stela-compiler/src/x86_64/amx/encoding.rs b/crates/stela-compiler/src/x86_64/amx/encoding.rs deleted file mode 100644 index a701829f0d..0000000000 --- a/crates/stela-compiler/src/x86_64/amx/encoding.rs +++ /dev/null @@ -1,174 +0,0 @@ -//! The VEX and EVEX forms the AMX kernels use (Intel SDM Vol. 2, sections 2.3 -//! and 2.7). Operands are named registers and base+displacement memory; no -//! index registers are needed. - -/// General-purpose register numbers. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Gpr { - Rax = 0, - Rdx = 2, - Rsp = 4, - Rsi = 6, - Rdi = 7, -} - -/// `[base + displacement]`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) struct Memory { - pub base: Gpr, - pub displacement: i32, -} - -pub(crate) const fn at(base: Gpr, displacement: i32) -> Memory { - Memory { base, displacement } -} - -/// Opcode maps. -#[derive(Clone, Copy)] -pub(crate) enum Map { - Primary = 1, - Escape38 = 2, - Escape3a = 3, -} - -/// Implied mandatory prefixes. -#[derive(Clone, Copy)] -pub(crate) enum Prefix { - None = 0, - OperandSize = 1, -} - -/// The register-or-memory operand. -#[derive(Clone, Copy)] -pub(crate) enum Operand { - Register(u8), - Memory(Memory), -} - -/// ModRM, SIB and displacement for `reg` and `rm`. `scale` is the EVEX -/// disp8*N factor (1 for VEX and legacy encodings). RBP is never a base, so -/// mod 00 always means no displacement. -fn modrm(code: &mut alloc::vec::Vec, reg: u8, rm: Operand, scale: i32) { - match rm { - Operand::Register(register) => code.push(0xc0 | ((reg & 7) << 3) | (register & 7)), - Operand::Memory(Memory { base, displacement }) => { - let base = base as u8; - let short = (displacement % scale == 0) - .then_some(displacement / scale) - .and_then(|value| i8::try_from(value).ok()); - let mode = match (displacement, short) { - (0, _) => 0, - (_, Some(_)) => 1, - _ => 2, - }; - code.push((mode << 6) | ((reg & 7) << 3) | (base & 7)); - if base & 7 == Gpr::Rsp as u8 { - // SIB: no index, base RSP. - code.push(0x24); - } - match (mode, short) { - (1, Some(value)) => code.push(value as u8), - (2, _) => code.extend(displacement.to_le_bytes()), - _ => {} - } - } - } -} - -/// Three-byte VEX: C4, RXB.mmmmm, W.vvvv.L.pp, opcode, ModRM. -#[allow(clippy::too_many_arguments)] -pub(crate) fn vex( - code: &mut alloc::vec::Vec, - map: Map, - prefix: Prefix, - wide: bool, - long: bool, - opcode: u8, - reg: u8, - source: u8, - rm: Operand, -) { - let rm_high = match rm { - Operand::Register(register) => register >> 3, - Operand::Memory(memory) => memory.base as u8 >> 3, - }; - debug_assert!(reg < 16 && source < 16); - code.push(0xc4); - code.push(((!reg >> 3) & 1) << 7 | 1 << 6 | ((!rm_high) & 1) << 5 | map as u8); - code.push(u8::from(wide) << 7 | ((!source) & 15) << 3 | u8::from(long) << 2 | prefix as u8); - code.push(opcode); - modrm(code, reg, rm, 1); -} - -/// EVEX.512: 62, P0 (R X B R' 0 0 mm), P1 (W vvvv 1 pp), P2 (z L'L b V' aaa). -#[allow(clippy::too_many_arguments)] -pub(crate) fn evex( - code: &mut alloc::vec::Vec, - map: Map, - prefix: Prefix, - wide: bool, - opcode: u8, - reg: u8, - source: u8, - rm: Operand, - broadcast: bool, - mask: u8, -) { - let (rm_high, scale) = match rm { - Operand::Register(register) => (register >> 3, 1), - Operand::Memory(memory) => ( - memory.base as u8 >> 3, - if broadcast { - if wide { 8 } else { 4 } - } else { - 64 - }, - ), - }; - debug_assert!(reg < 32 && source < 32 && mask < 8); - debug_assert!(matches!(rm, Operand::Memory(_)) || !broadcast); - let rm_extended = match rm { - // EVEX.X extends a register rm to 16..31. - Operand::Register(register) => (register >> 4) & 1, - Operand::Memory(_) => 0, - }; - code.push(0x62); - code.push( - ((!reg >> 3) & 1) << 7 - | ((!rm_extended) & 1) << 6 - | ((!rm_high) & 1) << 5 - | ((!reg >> 4) & 1) << 4 - | map as u8, - ); - code.push(u8::from(wide) << 7 | ((!source) & 15) << 3 | 1 << 2 | prefix as u8); - // L'L = 10 selects 512 bits. - code.push(2 << 5 | u8::from(broadcast) << 4 | ((!source >> 4) & 1) << 3 | mask); - code.push(opcode); - modrm(code, reg, rm, scale); -} - -/// A legacy-encoded `opcode /digit` with a memory operand, such as LDMXCSR. -pub(crate) fn legacy_memory( - code: &mut alloc::vec::Vec, - opcode: &[u8], - digit: u8, - memory: Memory, -) { - code.extend(opcode); - modrm(code, digit, Operand::Memory(memory), 1); -} - -#[cfg(test)] -mod tests { - use super::*; - use alloc::vec::Vec; - - #[test] - fn memory_forms_use_sib_for_rsp_and_compress_evex_displacements() { - let mut code = Vec::new(); - // ldmxcsr [rsp]; stmxcsr [rsp+4] - legacy_memory(&mut code, &[0x0f, 0xae], 2, at(Gpr::Rsp, 0)); - legacy_memory(&mut code, &[0x0f, 0xae], 3, at(Gpr::Rsp, 4)); - assert_eq!(code, [0x0f, 0xae, 0x14, 0x24, 0x0f, 0xae, 0x5c, 0x24, 0x04]); - } -} diff --git a/crates/stela-compiler/src/x86_64/asm.rs b/crates/stela-compiler/src/x86_64/asm.rs new file mode 100644 index 0000000000..734438b5fe --- /dev/null +++ b/crates/stela-compiler/src/x86_64/asm.rs @@ -0,0 +1,1409 @@ +//! A typed x86-64 encoder (Intel SDM Vol. 2, chapter 2). Operands are typed +//! registers and memory; operand-size prefixes, REX, VEX, ModRM, SIB and +//! displacements are derived from them, and [`Asm`] counts every instruction +//! it emits. +//! +//! Emitters take a [`Code`], which carries the instruction count across +//! every [`Asm`] built over it. +//! +//! The scalar integer families emit through it; the rest still emit bytes +//! directly, so some operand kinds and forms wait for their first user. +#![allow(dead_code)] +use alloc::vec::Vec; + +pub(crate) mod control; +mod integer; +pub(crate) mod memory; +mod sse; +pub(crate) use integer::BitTest; +pub(crate) use sse::{FloatLanes, FloatOp}; + +/// Emitted bytes and the number of instructions among them. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub(crate) struct Code { + bytes: Vec, + instructions: usize, +} + +impl Code { + pub(crate) const fn new() -> Self { + Self { + bytes: Vec::new(), + instructions: 0, + } + } + /// An encoder that appends here and adds to this count. + pub(crate) fn asm(&mut self) -> Asm<'_> { + Asm { + code: &mut self.bytes, + instructions: 0, + shared: Some(&mut self.instructions), + } + } + /// The instructions emitted through [`Self::asm`]. + pub(crate) const fn instructions(&self) -> usize { + self.instructions + } + pub(crate) fn into_bytes(self) -> Vec { + self.bytes + } + /// Append `other`'s bytes and instructions. + pub(crate) fn append(&mut self, other: Code) { + self.bytes.extend(other.bytes); + self.instructions += other.instructions; + } + /// Remove every byte and instruction. + pub(crate) fn clear(&mut self) { + self.bytes.clear(); + self.instructions = 0; + } +} + +impl From> for Code { + fn from(bytes: Vec) -> Self { + Self { + bytes, + instructions: 0, + } + } +} + +impl PartialEq<[u8]> for Code { + fn eq(&self, other: &[u8]) -> bool { + self.bytes == other + } +} + +impl PartialEq> for Code { + fn eq(&self, other: &Vec) -> bool { + self.bytes == *other + } +} + +impl PartialEq<[u8; N]> for Code { + fn eq(&self, other: &[u8; N]) -> bool { + self.bytes == other + } +} + +impl PartialEq<&[u8]> for Code { + fn eq(&self, other: &&[u8]) -> bool { + self.bytes == *other + } +} + +impl PartialEq for [u8] { + fn eq(&self, other: &Code) -> bool { + self == other.bytes + } +} + +impl PartialEq for &[u8] { + fn eq(&self, other: &Code) -> bool { + *self == other.bytes + } +} + +impl PartialEq for Vec { + fn eq(&self, other: &Code) -> bool { + *self == other.bytes + } +} + +impl PartialEq for [u8; N] { + fn eq(&self, other: &Code) -> bool { + self[..] == other.bytes + } +} + +impl From for Vec { + fn from(code: Code) -> Self { + code.bytes + } +} + +impl TryFrom for [u8; N] { + type Error = Vec; + fn try_from(code: Code) -> Result> { + code.bytes.try_into() + } +} + +impl<'a> IntoIterator for &'a Code { + type Item = &'a u8; + type IntoIter = core::slice::Iter<'a, u8>; + fn into_iter(self) -> Self::IntoIter { + self.bytes.iter() + } +} + +impl IntoIterator for Code { + type Item = u8; + type IntoIter = alloc::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { + self.bytes.into_iter() + } +} + +impl core::ops::Deref for Code { + type Target = Vec; + fn deref(&self) -> &Vec { + &self.bytes + } +} + +impl core::ops::DerefMut for Code { + fn deref_mut(&mut self) -> &mut Vec { + &mut self.bytes + } +} + +/// General-purpose registers by encoding number. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum Gpr { + Rax, + Rcx, + Rdx, + Rbx, + Rsp, + Rbp, + Rsi, + Rdi, + R8, + R9, + R10, + R11, + R12, + R13, + R14, + R15, +} + +impl Gpr { + const fn number(self) -> u8 { + self as u8 + } + const fn low(self) -> u8 { + self as u8 & 7 + } + const fn high(self) -> bool { + self as u8 >= 8 + } +} + +/// Operand sizes of integer instructions. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Size { + Byte, + Word, + Dword, + Qword, +} + +impl Size { + /// The 32- or 64-bit size of an A64 W or X register operation. + pub(crate) const fn of(wide: bool) -> Self { + if wide { Self::Qword } else { Self::Dword } + } + pub(crate) const fn bits(self) -> u32 { + match self { + Self::Byte => 8, + Self::Word => 16, + Self::Dword => 32, + Self::Qword => 64, + } + } +} + +/// `[base + index * scale + displacement]`, or `[rip + displacement]` when +/// `base` is `None`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Mem { + pub base: Option, + pub index: Option<(Gpr, u8)>, + pub displacement: i32, + pub width: Disp, +} + +/// How a base register's displacement is encoded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Disp { + /// The shortest form: none for zero (but RBP and R13), else 8 or 32 bits. + Auto, + /// An 8-bit field, even for zero. + Byte, + /// A 32-bit field, even when 8 bits would do. + Dword, +} + +impl Mem { + pub(crate) const fn base(base: Gpr, displacement: i32) -> Self { + Self { + base: Some(base), + index: None, + displacement, + width: Disp::Auto, + } + } + /// `[base + displacement]` with a 32-bit displacement field. + pub(crate) const fn base_disp32(base: Gpr, displacement: i32) -> Self { + Self { + width: Disp::Dword, + ..Self::base(base, displacement) + } + } + /// `[base + displacement]` with an 8-bit displacement field. + pub(crate) const fn base_disp8(base: Gpr, displacement: i8) -> Self { + Self { + width: Disp::Byte, + ..Self::base(base, displacement as i32) + } + } + /// This operand with its displacement field `width`. + pub(crate) const fn with_width(self, width: Disp) -> Self { + Self { width, ..self } + } + /// `[rip + displacement]`. + pub(crate) const fn rip(displacement: i32) -> Self { + Self { + base: None, + index: None, + displacement, + width: Disp::Dword, + } + } + pub(crate) const fn indexed(base: Gpr, index: Gpr, scale: u8, displacement: i32) -> Self { + Self { + base: Some(base), + index: Some((index, scale)), + displacement, + width: Disp::Auto, + } + } +} + +/// A register or memory operand (the ModRM r/m field). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Rm { + Reg(Gpr), + Xmm(u8), + Mem(Mem), +} + +impl From for Rm { + fn from(register: Gpr) -> Self { + Self::Reg(register) + } +} + +impl From for Rm { + fn from(memory: Mem) -> Self { + Self::Mem(memory) + } +} + +impl Rm { + /// REX.X and REX.B. + fn extensions(self) -> (bool, bool) { + match self { + Self::Reg(register) => (false, register.high()), + Self::Xmm(register) => (false, register & 8 != 0), + Self::Mem(memory) => ( + memory.index.is_some_and(|(index, _)| index.high()), + memory.base.is_some_and(Gpr::high), + ), + } + } + /// Whether a byte-sized access to this operand needs a REX prefix to + /// name SPL, BPL, SIL or DIL. + fn needs_byte_rex(self) -> bool { + matches!(self, Self::Reg(register) if (4..8).contains(®ister.number())) + } +} + +/// Two-operand ALU operations, numbered by their ModRM reg digit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum Alu { + Add, + Or, + Adc, + Sbb, + And, + Sub, + Xor, + Cmp, +} + +/// Group 2 rotate and shift operations, numbered by their ModRM reg digit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum ShiftOp { + Rol, + Ror, + Rcl, + Rcr, + Shl, + Shr, + Sal, + Sar, +} + +/// Condition codes, numbered as in Jcc, SETcc and CMOVcc. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum Cond { + O, + No, + B, + Ae, + E, + Ne, + Be, + A, + S, + Ns, + P, + Np, + L, + Ge, + Le, + G, +} + +/// Group 3 unary operations, numbered by their ModRM reg digit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum Unary { + Not = 2, + Neg = 3, + Mul = 4, + Imul = 5, + Div = 6, + Idiv = 7, +} + +/// The VEX opcode maps. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Map { + M0f = 1, + M0f38 = 2, + M0f3a = 3, +} + +/// VEX implied mandatory prefixes (VEX.pp). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Pp { + None = 0, + P66 = 1, + Pf3 = 2, + Pf2 = 3, +} + +/// The fields of a VEX prefix besides its registers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Vex { + pub(crate) map: Map, + pub(crate) pp: Pp, + /// VEX.W: a 64-bit general-purpose operand size. + pub(crate) w: bool, + /// VEX.L: 256-bit vectors. + pub(crate) l: bool, +} + +/// The displacement field of a rel8 or rel32 branch, resolved by +/// [`Asm::bind`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[must_use] +pub(crate) struct Patch { + at: usize, + short: bool, +} + +impl Patch { + /// The offset of the displacement field in the code. + pub(crate) const fn offset(self) -> usize { + self.at + } + /// The offset just past the branch, which its displacement counts from. + pub(crate) const fn end(self) -> usize { + self.at + if self.short { 1 } else { 4 } + } +} + +/// The fields of an EVEX prefix besides its registers (SDM Vol. 2A 2.7). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Evex { + pub(crate) map: Map, + pub(crate) pp: Pp, + pub(crate) w: bool, + /// EVEX.L'L: 0, 1 and 2 for 128, 256 and 512 bits. + pub(crate) length: u8, + /// EVEX.aaa: the opmask register, zero for none. + pub(crate) mask: u8, + /// EVEX.z: zero masked elements instead of merging. + pub(crate) zeroing: bool, + /// EVEX.b: embedded broadcast for memory, or rounding control. + pub(crate) broadcast: bool, + /// N of the compressed disp8*N displacement (SDM 2.7.5). + pub(crate) scale: u8, +} + +/// An encoder that appends to `code` and counts the instructions it emits, +/// into the [`Code`] it was built over as well. +pub(crate) struct Asm<'a> { + code: &'a mut Vec, + instructions: usize, + shared: Option<&'a mut usize>, +} + +impl<'a> Asm<'a> { + pub(crate) fn new(code: &'a mut Vec) -> Self { + Self { + code, + instructions: 0, + shared: None, + } + } + fn count(&mut self) { + self.instructions += 1; + if let Some(shared) = self.shared.as_deref_mut() { + *shared += 1; + } + } + /// The number of instructions emitted through this encoder. + pub(crate) const fn instructions(&self) -> usize { + self.instructions + } + /// The code length, the offset of the next instruction. + pub(crate) fn len(&self) -> usize { + self.code.len() + } + /// Instruction bytes this encoder does not model, counted as + /// `instructions` instructions. + pub(crate) fn raw(&mut self, bytes: &[u8], instructions: usize) { + self.code.extend(bytes); + for _ in 0..instructions { + self.count(); + } + } + /// A prefix byte (LOCK, REP, a segment override) of the next + /// instruction, which counts it. + pub(crate) fn prefix(&mut self, byte: u8) { + self.code.push(byte); + } + /// `lock` for the next instruction. + pub(crate) fn lock(&mut self) { + self.prefix(0xf0); + } + /// Data or immediates that belong to the instruction just emitted. + pub(crate) fn data(&mut self, bytes: &[u8]) { + self.code.extend(bytes); + } + + fn modrm(&mut self, reg: u8, rm: Rm) { + self.modrm_scaled(reg, rm, 1); + } + + /// ModRM, SIB and displacement, with an 8-bit displacement counted in + /// units of `scale` bytes (EVEX disp8*N; 1 elsewhere). + fn modrm_scaled(&mut self, reg: u8, rm: Rm, scale: u8) { + let reg = (reg & 7) << 3; + match rm { + Rm::Reg(register) => self.code.push(0xc0 | reg | register.low()), + Rm::Xmm(register) => self.code.push(0xc0 | reg | (register & 7)), + Rm::Mem(Mem { + base: None, + index, + displacement, + .. + }) => { + debug_assert!(index.is_none(), "RIP-relative addressing has no index"); + self.code.push(reg | 5); + self.code.extend(displacement.to_le_bytes()); + } + Rm::Mem(Mem { + base: Some(base), + index, + displacement, + width, + }) => { + // RBP and R13 have no mod-00 form; RSP and R12 need a SIB. + let scale = i32::from(scale); + let short = displacement % scale == 0 && i8::try_from(displacement / scale).is_ok(); + let mode = match width { + Disp::Dword => 2, + Disp::Byte => { + debug_assert!(short, "displacement fits its 8-bit field"); + 1 + } + Disp::Auto if displacement == 0 && base.low() != 5 => 0, + Disp::Auto if short => 1, + Disp::Auto => 2, + }; + match index { + None if base.low() != 4 => self.code.push(mode << 6 | reg | base.low()), + None => self.code.extend([mode << 6 | reg | 4, 0x24]), + Some((index, scale)) => { + debug_assert!(index != Gpr::Rsp, "RSP cannot be an index"); + let scale = match scale { + 1 => 0, + 2 => 1, + 4 => 2, + 8 => 3, + _ => unreachable!("scale of 1, 2, 4 or 8"), + }; + self.code.extend([ + mode << 6 | reg | 4, + scale << 6 | index.low() << 3 | base.low(), + ]); + } + } + match mode { + 1 => self.code.push((displacement / scale) as u8), + 2 => self.code.extend(displacement.to_le_bytes()), + _ => {} + } + } + } + } + + /// A legacy-encoded instruction: the operand-size prefix for words, the + /// mandatory `prefix`, REX when any field needs it, `opcode` and ModRM. + pub(crate) fn legacy( + &mut self, + size: Size, + prefix: Option, + opcode: &[u8], + reg: u8, + reg_byte: bool, + rm: Rm, + ) { + if size == Size::Word { + self.code.push(0x66); + } + if let Some(prefix) = prefix { + self.code.push(prefix); + } + let (x, b) = rm.extensions(); + let w = size == Size::Qword; + let r = reg & 8 != 0; + let byte_rex = + size == Size::Byte && (rm.needs_byte_rex() || (reg_byte && (4..8).contains(®))); + if w || r || x || b || byte_rex { + self.code + .push(0x40 | u8::from(w) << 3 | u8::from(r) << 2 | u8::from(x) << 1 | u8::from(b)); + } + self.code.extend(opcode); + self.modrm(reg, rm); + self.count(); + } + + /// A VEX-encoded instruction: two-byte C5 when the fields allow it, + /// otherwise three-byte C4. + pub(crate) fn vex(&mut self, prefix: Vex, opcode: u8, reg: u8, vvvv: u8, rm: Rm) { + let Vex { map, pp, w, l } = prefix; + let (x, b) = rm.extensions(); + let r = reg & 8 != 0; + let tail = u8::from(l) << 2 | pp as u8 | (!vvvv & 15) << 3; + if map == Map::M0f && !w && !x && !b { + self.code.extend([0xc5, u8::from(!r) << 7 | tail]); + } else { + self.code.extend([ + 0xc4, + u8::from(!r) << 7 | u8::from(!x) << 6 | u8::from(!b) << 5 | map as u8, + u8::from(w) << 7 | tail, + ]); + } + self.code.push(opcode); + self.modrm(reg, rm); + self.count(); + } + + /// An EVEX-encoded instruction. Registers number 0 to 31; `rm` names + /// an XMM register or memory. + pub(crate) fn evex(&mut self, prefix: Evex, opcode: u8, reg: u8, vvvv: u8, rm: Rm) { + let Evex { + map, + pp, + w, + length, + mask, + zeroing, + broadcast, + scale, + } = prefix; + let (x, b) = match rm { + // EVEX.X extends a register r/m to 32 registers. + Rm::Xmm(register) => (register & 16 != 0, register & 8 != 0), + other => other.extensions(), + }; + let r = reg & 8 != 0; + let r2 = reg & 16 != 0; + let v2 = vvvv & 16 != 0; + self.code.extend([ + 0x62, + u8::from(!r) << 7 + | u8::from(!x) << 6 + | u8::from(!b) << 5 + | u8::from(!r2) << 4 + | map as u8, + u8::from(w) << 7 | (!vvvv & 15) << 3 | 4 | pp as u8, + u8::from(zeroing) << 7 + | (length & 3) << 5 + | u8::from(broadcast) << 4 + | u8::from(!v2) << 3 + | (mask & 7), + opcode, + ]); + let scale = if matches!(rm, Rm::Mem(_)) { + scale.max(1) + } else { + 1 + }; + self.modrm_scaled(reg, rm, scale); + self.count(); + } + + /// A legacy SSE instruction on XMM registers: the mandatory `prefix`, + /// REX when a register needs it, `opcode` and ModRM. + pub(crate) fn sse(&mut self, prefix: Option, opcode: &[u8], xmm: u8, rm: impl Into) { + self.legacy(Size::Dword, prefix, opcode, xmm, false, rm.into()); + } + /// [`Self::sse`] with an 8-bit immediate. + pub(crate) fn sse_imm( + &mut self, + prefix: Option, + opcode: &[u8], + xmm: u8, + rm: impl Into, + immediate: u8, + ) { + self.sse(prefix, opcode, xmm, rm); + self.code.push(immediate); + } + /// An opcode that names its register in its low three bits (`+r`). + pub(crate) fn opcode_reg(&mut self, size: Size, opcode: u8, register: Gpr) { + if size == Size::Word { + self.code.push(0x66); + } + let w = size == Size::Qword; + if w || register.high() { + self.code + .push(0x40 | u8::from(w) << 3 | u8::from(register.high())); + } + self.code.push(opcode | register.low()); + self.count(); + } + /// An instruction of fixed bytes and no operands (`ret`, `ud2`, `mfence`). + pub(crate) fn fixed(&mut self, bytes: &[u8]) { + self.code.extend(bytes); + self.count(); + } + + // Stack and control transfer. + + /// `push r64`. + pub(crate) fn push(&mut self, register: Gpr) { + self.opcode_reg(Size::Dword, 0x50, register); + } + /// `pop r64`. + pub(crate) fn pop(&mut self, register: Gpr) { + self.opcode_reg(Size::Dword, 0x58, register); + } + /// `ret`. + pub(crate) fn ret(&mut self) { + self.fixed(&[0xc3]); + } + /// `call rm64`. + pub(crate) fn call_rm(&mut self, rm: impl Into) { + self.legacy(Size::Dword, None, &[0xff], 2, false, rm.into()); + } + /// `jmp rm64`. + pub(crate) fn jmp_rm(&mut self, rm: impl Into) { + self.legacy(Size::Dword, None, &[0xff], 4, false, rm.into()); + } + /// `call rel32`, resolved later by [`Self::bind`] or [`resolve`]. + pub(crate) fn call(&mut self) -> Patch { + self.code.push(0xe8); + self.patch() + } + + // Moves. + + /// `mov rm, src`. + pub(crate) fn mov_store(&mut self, size: Size, rm: impl Into, source: Gpr) { + let opcode = if size == Size::Byte { 0x88 } else { 0x89 }; + self.legacy(size, None, &[opcode], source.number(), true, rm.into()); + } + /// `mov dst, rm`. + pub(crate) fn mov_load(&mut self, size: Size, destination: Gpr, rm: impl Into) { + let opcode = if size == Size::Byte { 0x8a } else { 0x8b }; + self.legacy(size, None, &[opcode], destination.number(), true, rm.into()); + } + /// `mov dst, src` in the 89 direction (`mov rm, reg`). + pub(crate) fn mov(&mut self, size: Size, destination: Gpr, source: Gpr) { + self.mov_store(size, destination, source); + } + /// `mov r32, imm32` (B8+r), which zero-extends to 64 bits. + pub(crate) fn mov_imm32(&mut self, destination: Gpr, value: u32) { + if destination.high() { + self.code.push(0x41); + } + self.code.push(0xb8 | destination.low()); + self.code.extend(value.to_le_bytes()); + self.count(); + } + /// `movabs r64, imm64` (REX.W B8+r). + pub(crate) fn mov_imm64(&mut self, destination: Gpr, value: u64) { + self.code.push(0x48 | u8::from(destination.high())); + self.code.push(0xb8 | destination.low()); + self.code.extend(value.to_le_bytes()); + self.count(); + } + /// `mov rm, imm32` (C7 /0), sign-extended for a quadword. + pub(crate) fn mov_rm_imm32(&mut self, size: Size, rm: impl Into, value: i32) { + debug_assert!(size != Size::Byte && size != Size::Word); + self.legacy(size, None, &[0xc7], 0, false, rm.into()); + self.code.extend(value.to_le_bytes()); + } + /// `movzx dst, rm8/rm16`. + pub(crate) fn movzx(&mut self, size: Size, destination: Gpr, from: Size, rm: impl Into) { + let opcode = if from == Size::Byte { 0xb6 } else { 0xb7 }; + let rm = rm.into(); + let byte_rex = from == Size::Byte && rm.needs_byte_rex(); + self.extended( + size, + byte_rex, + None, + &[0x0f, opcode], + destination.number(), + rm, + ); + } + /// `movsx dst, rm8/rm16`. + pub(crate) fn movsx(&mut self, size: Size, destination: Gpr, from: Size, rm: impl Into) { + let opcode = if from == Size::Byte { 0xbe } else { 0xbf }; + let rm = rm.into(); + let byte_rex = from == Size::Byte && rm.needs_byte_rex(); + self.extended( + size, + byte_rex, + None, + &[0x0f, opcode], + destination.number(), + rm, + ); + } + /// `movsxd r64, rm32`. + pub(crate) fn movsxd(&mut self, destination: Gpr, rm: impl Into) { + self.legacy( + Size::Qword, + None, + &[0x63], + destination.number(), + false, + rm.into(), + ); + } + /// `lea dst, [mem]`. + pub(crate) fn lea(&mut self, size: Size, destination: Gpr, memory: Mem) { + self.legacy( + size, + None, + &[0x8d], + destination.number(), + false, + Rm::Mem(memory), + ); + } + + /// A legacy instruction whose operand size is `size` but whose REX also + /// carries `byte_rex` for a byte-sized r/m source (MOVZX, MOVSX). + fn extended( + &mut self, + size: Size, + byte_rex: bool, + prefix: Option, + opcode: &[u8], + reg: u8, + rm: Rm, + ) { + if byte_rex && size != Size::Qword && reg & 8 == 0 && rm.extensions() == (false, false) { + if size == Size::Word { + self.code.push(0x66); + } + if let Some(prefix) = prefix { + self.code.push(prefix); + } + self.code.push(0x40); + self.code.extend(opcode); + self.modrm(reg, rm); + self.count(); + } else { + self.legacy(size, prefix, opcode, reg, false, rm); + } + } + + // Arithmetic. + + /// `op rm, src` (the 01-direction ALU forms). + pub(crate) fn alu(&mut self, op: Alu, size: Size, rm: impl Into, source: Gpr) { + let opcode = (op as u8) << 3 | u8::from(size != Size::Byte); + self.legacy(size, None, &[opcode], source.number(), true, rm.into()); + } + /// `op dst, rm` (the 03-direction ALU forms). + pub(crate) fn alu_load(&mut self, op: Alu, size: Size, destination: Gpr, rm: impl Into) { + let opcode = (op as u8) << 3 | 2 | u8::from(size != Size::Byte); + self.legacy(size, None, &[opcode], destination.number(), true, rm.into()); + } + /// `op rm, imm8` sign-extended (83 /digit). + pub(crate) fn alu_imm8(&mut self, op: Alu, size: Size, rm: impl Into, value: i8) { + debug_assert!(size != Size::Byte); + self.legacy(size, None, &[0x83], op as u8, false, rm.into()); + self.code.push(value as u8); + } + /// `op rm, imm32` (81 /digit), sign-extended for a quadword. + pub(crate) fn alu_imm32(&mut self, op: Alu, size: Size, rm: impl Into, value: i32) { + debug_assert!(size == Size::Dword || size == Size::Qword); + self.legacy(size, None, &[0x81], op as u8, false, rm.into()); + self.code.extend(value.to_le_bytes()); + } + /// `op eax/rax, imm32`, the accumulator short form. + pub(crate) fn alu_accumulator_imm32(&mut self, op: Alu, size: Size, value: i32) { + debug_assert!(size == Size::Dword || size == Size::Qword); + if size == Size::Qword { + self.code.push(0x48); + } + self.code.push((op as u8) << 3 | 5); + self.code.extend(value.to_le_bytes()); + self.count(); + } + /// `op rm, imm`: the sign-extended imm8 form when it fits, else imm32. + pub(crate) fn alu_imm(&mut self, op: Alu, size: Size, rm: impl Into, value: i32) { + match i8::try_from(value) { + Ok(short) => self.alu_imm8(op, size, rm, short), + Err(_) => self.alu_imm32(op, size, rm, value), + } + } + /// `test rm, src`. + pub(crate) fn test(&mut self, size: Size, rm: impl Into, source: Gpr) { + let opcode = if size == Size::Byte { 0x84 } else { 0x85 }; + self.legacy(size, None, &[opcode], source.number(), true, rm.into()); + } + /// Group 3 `op rm`: NOT, NEG, MUL, IMUL, DIV, IDIV. + pub(crate) fn unary(&mut self, op: Unary, size: Size, rm: impl Into) { + let opcode = if size == Size::Byte { 0xf6 } else { 0xf7 }; + self.legacy(size, None, &[opcode], op as u8, false, rm.into()); + } + /// `imul dst, rm`. + pub(crate) fn imul(&mut self, size: Size, destination: Gpr, rm: impl Into) { + self.legacy( + size, + None, + &[0x0f, 0xaf], + destination.number(), + false, + rm.into(), + ); + } + /// `cdq` or `cqo`: sign-extend EAX/RAX into EDX/RDX. + pub(crate) fn sign_extend_accumulator(&mut self, size: Size) { + if size == Size::Qword { + self.code.push(0x48); + } + self.code.push(0x99); + self.count(); + } + /// A group 2 shift or rotate by CL. + pub(crate) fn shift_cl(&mut self, op: ShiftOp, size: Size, rm: impl Into) { + let opcode = if size == Size::Byte { 0xd2 } else { 0xd3 }; + self.legacy(size, None, &[opcode], op as u8, false, rm.into()); + } + /// A group 2 shift or rotate by one (D1 /digit). + pub(crate) fn shift_one(&mut self, op: ShiftOp, size: Size, rm: impl Into) { + let opcode = if size == Size::Byte { 0xd0 } else { 0xd1 }; + self.legacy(size, None, &[opcode], op as u8, false, rm.into()); + } + /// `imul dst, rm, imm32`. + pub(crate) fn imul_imm32( + &mut self, + size: Size, + destination: Gpr, + rm: impl Into, + value: i32, + ) { + self.legacy(size, None, &[0x69], destination.number(), false, rm.into()); + self.code.extend(value.to_le_bytes()); + } + /// `nop`. + pub(crate) fn nop(&mut self) { + self.code.push(0x90); + self.count(); + } + /// A group 2 shift or rotate by an immediate (C1 /digit ib). + pub(crate) fn shift_imm(&mut self, op: ShiftOp, size: Size, rm: impl Into, amount: u8) { + let opcode = if size == Size::Byte { 0xc0 } else { 0xc1 }; + self.legacy(size, None, &[opcode], op as u8, false, rm.into()); + self.code.push(amount); + } + /// `shrd rm, src, imm8`. + pub(crate) fn shrd_imm(&mut self, size: Size, rm: impl Into, source: Gpr, amount: u8) { + self.legacy(size, None, &[0x0f, 0xac], source.number(), false, rm.into()); + self.code.push(amount); + } + + // Bit operations. + + /// `bsr dst, rm`. + pub(crate) fn bsr(&mut self, size: Size, destination: Gpr, rm: impl Into) { + self.legacy( + size, + None, + &[0x0f, 0xbd], + destination.number(), + false, + rm.into(), + ); + } + /// `bsf dst, rm`. + pub(crate) fn bsf(&mut self, size: Size, destination: Gpr, rm: impl Into) { + self.legacy( + size, + None, + &[0x0f, 0xbc], + destination.number(), + false, + rm.into(), + ); + } + /// `lzcnt dst, rm` (LZCNT; ABM on AMD). + pub(crate) fn lzcnt(&mut self, size: Size, destination: Gpr, rm: impl Into) { + self.legacy( + size, + Some(0xf3), + &[0x0f, 0xbd], + destination.number(), + false, + rm.into(), + ); + } + /// `tzcnt dst, rm` (BMI1). + pub(crate) fn tzcnt(&mut self, size: Size, destination: Gpr, rm: impl Into) { + self.legacy( + size, + Some(0xf3), + &[0x0f, 0xbc], + destination.number(), + false, + rm.into(), + ); + } + /// `popcnt dst, rm`. + pub(crate) fn popcnt(&mut self, size: Size, destination: Gpr, rm: impl Into) { + self.legacy( + size, + Some(0xf3), + &[0x0f, 0xb8], + destination.number(), + false, + rm.into(), + ); + } + /// `bswap reg`. + pub(crate) fn bswap(&mut self, size: Size, register: Gpr) { + debug_assert!(size == Size::Dword || size == Size::Qword); + if size == Size::Qword || register.high() { + self.code + .push(0x40 | u8::from(size == Size::Qword) << 3 | u8::from(register.high())); + } + self.code.extend([0x0f, 0xc8 | register.low()]); + self.count(); + } + /// `cmovcc dst, rm`. + pub(crate) fn cmov(&mut self, cond: Cond, size: Size, destination: Gpr, rm: impl Into) { + self.legacy( + size, + None, + &[0x0f, 0x40 | cond as u8], + destination.number(), + false, + rm.into(), + ); + } + /// `setcc rm8`. + pub(crate) fn setcc(&mut self, cond: Cond, rm: impl Into) { + self.legacy( + Size::Byte, + None, + &[0x0f, 0x90 | cond as u8], + 0, + false, + rm.into(), + ); + } + + // SSE moves and GFNI. + + /// `movq xmm, r64`. + pub(crate) fn movq_to_xmm(&mut self, xmm: u8, source: Gpr) { + self.legacy( + Size::Qword, + Some(0x66), + &[0x0f, 0x6e], + xmm, + false, + Rm::Reg(source), + ); + } + /// `movq r64, xmm`. + pub(crate) fn movq_from_xmm(&mut self, destination: Gpr, xmm: u8) { + self.legacy( + Size::Qword, + Some(0x66), + &[0x0f, 0x7e], + xmm, + false, + Rm::Reg(destination), + ); + } + /// `gf2p8affineqb xmm, xmm/m128, imm8`: each byte of `xmm` becomes the + /// GF(2) affine transform by the matching qword's 8x8 bit matrix in + /// `matrix`, XOR `constant` (GFNI). + pub(crate) fn gf2p8affineqb(&mut self, xmm: u8, matrix: Rm, constant: u8) { + self.legacy( + Size::Dword, + Some(0x66), + &[0x0f, 0x3a, 0xce], + xmm, + false, + matrix, + ); + self.code.push(constant); + } + + // BMI2 (VEX-encoded general-purpose forms). + + /// `shlx`, `shrx` or `sarx dst, rm, count`: a shift by the count register + /// modulo the operand width, without flags (BMI2). + pub(crate) fn shift_x( + &mut self, + op: ShiftOp, + size: Size, + destination: Gpr, + rm: impl Into, + count: Gpr, + ) { + let pp = match op { + ShiftOp::Shl | ShiftOp::Sal => Pp::P66, + ShiftOp::Shr => Pp::Pf2, + ShiftOp::Sar => Pp::Pf3, + _ => unreachable!("SHLX, SHRX and SARX only"), + }; + self.vex( + Vex { + map: Map::M0f38, + pp, + w: size == Size::Qword, + l: false, + }, + 0xf7, + destination.number(), + count.number(), + rm.into(), + ); + } + /// `rorx dst, rm, imm8`: rotate right without flags (BMI2). + pub(crate) fn rorx(&mut self, size: Size, destination: Gpr, rm: impl Into, amount: u8) { + self.vex( + Vex { + map: Map::M0f3a, + pp: Pp::Pf2, + w: size == Size::Qword, + l: false, + }, + 0xf0, + destination.number(), + 0, + rm.into(), + ); + self.code.push(amount); + } + + // Control flow. + + /// `jmp rel32`, resolved later by [`Self::bind`]. + pub(crate) fn jmp(&mut self) -> Patch { + self.code.push(0xe9); + self.patch() + } + /// `jcc rel32`, resolved later by [`Self::bind`]. + pub(crate) fn jcc(&mut self, cond: Cond) -> Patch { + self.code.extend([0x0f, 0x80 | cond as u8]); + self.patch() + } + /// `jmp rel8`, resolved later by [`Self::bind`]. + pub(crate) fn jmp8(&mut self) -> Patch { + self.code.push(0xeb); + self.short_patch() + } + /// `jcc rel8`, resolved later by [`Self::bind`]. + pub(crate) fn jcc8(&mut self, cond: Cond) -> Patch { + self.code.push(0x70 | cond as u8); + self.short_patch() + } + fn patch(&mut self) -> Patch { + let at = self.code.len(); + self.code.extend([0; 4]); + self.count(); + Patch { at, short: false } + } + fn short_patch(&mut self) -> Patch { + let at = self.code.len(); + self.code.push(0); + self.count(); + Patch { at, short: true } + } + /// Point `patch` at the current position. + pub(crate) fn bind(&mut self, patch: Patch) { + let target = self.code.len(); + resolve(self.code, patch, target); + } +} + +/// Point `patch` in `code` at `target`. +pub(crate) fn resolve(code: &mut [u8], patch: Patch, target: usize) { + let distance = target as i64 - patch.end() as i64; + if patch.short { + code[patch.at] = i8::try_from(distance).expect("rel8 branch in range") as u8; + } else { + let distance = i32::try_from(distance).expect("rel32 branch in range"); + code[patch.at..patch.at + 4].copy_from_slice(&distance.to_le_bytes()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + + fn bytes(build: impl FnOnce(&mut Asm)) -> (Vec, usize) { + let mut code = vec![]; + let mut asm = Asm::new(&mut code); + build(&mut asm); + let count = asm.instructions(); + (code, count) + } + + #[test] + fn integer_forms_match_the_sdm_encodings() { + use Gpr::*; + use Size::*; + for (expected, build) in [ + ( + &[0x89, 0xc1][..], + (|a: &mut Asm| a.mov(Dword, Rcx, Rax)) as fn(&mut Asm), + ), + (&[0x48, 0x89, 0xc1], |a| a.mov(Qword, Rcx, Rax)), + (&[0x4d, 0x89, 0xc8], |a| a.mov(Qword, R8, R9)), + (&[0x48, 0x8b, 0x47, 0x08], |a| { + a.mov_load(Qword, Rax, Mem::base(Rdi, 8)) + }), + (&[0x48, 0x8b, 0x87, 0x00, 0x01, 0, 0], |a| { + a.mov_load(Qword, Rax, Mem::base(Rdi, 256)) + }), + (&[0x48, 0x89, 0x87, 0x08, 0, 0, 0], |a| { + a.mov_store(Qword, Mem::base_disp32(Rdi, 8), Rax) + }), + (&[0x48, 0x8b, 0x04, 0x24], |a| { + a.mov_load(Qword, Rax, Mem::base(Rsp, 0)) + }), + (&[0x49, 0x8b, 0x45, 0x00], |a| { + a.mov_load(Qword, Rax, Mem::base(R13, 0)) + }), + (&[0x41, 0x33, 0x04, 0x90], |a| { + a.alu_load(Alu::Xor, Dword, Rax, Mem::indexed(R8, Rdx, 4, 0)) + }), + (&[0x40, 0x88, 0xf0], |a| a.mov_store(Byte, Rax, Rsi)), + (&[0x0f, 0xb6, 0xc9], |a| a.movzx(Dword, Rcx, Byte, Rcx)), + (&[0x40, 0x0f, 0xb6, 0xc6], |a| { + a.movzx(Dword, Rax, Byte, Rsi) + }), + (&[0x48, 0x63, 0xc0], |a| a.movsxd(Rax, Rax)), + (&[0x48, 0x0f, 0xbd, 0xc0], |a| a.bsr(Qword, Rax, Rax)), + (&[0xf3, 0x48, 0x0f, 0xbd, 0xc0], |a| { + a.lzcnt(Qword, Rax, Rax) + }), + (&[0x0f, 0xc8], |a| a.bswap(Dword, Rax)), + (&[0x49, 0x0f, 0xc9], |a| a.bswap(Qword, R9)), + (&[0x48, 0x0f, 0x44, 0xc1], |a| { + a.cmov(Cond::E, Qword, Rax, Rcx) + }), + (&[0x83, 0xf0, 0x1f], |a| { + a.alu_imm8(Alu::Xor, Dword, Rax, 31) + }), + (&[0x81, 0xe1, 0x55, 0x55, 0x55, 0x55], |a| { + a.alu_imm32(Alu::And, Dword, Rcx, 0x5555_5555) + }), + (&[0x25, 0x55, 0x55, 0x55, 0x55], |a| { + a.alu_accumulator_imm32(Alu::And, Dword, 0x5555_5555) + }), + (&[0x48, 0xd3, 0xf8], |a| { + a.shift_cl(ShiftOp::Sar, Qword, Rax) + }), + (&[0xc1, 0xc8, 0x10], |a| { + a.shift_imm(ShiftOp::Ror, Dword, Rax, 16) + }), + (&[0x48, 0x0f, 0xac, 0xc1, 0x07], |a| { + a.shrd_imm(Qword, Rcx, Rax, 7) + }), + (&[0x48, 0xf7, 0xe9], |a| a.unary(Unary::Imul, Qword, Rcx)), + (&[0x48, 0x99], |a| a.sign_extend_accumulator(Qword)), + (&[0xb9, 0x3f, 0, 0, 0], |a| a.mov_imm32(Rcx, 63)), + (&[0x48, 0xba, 1, 2, 3, 4, 5, 6, 7, 8], |a| { + a.mov_imm64(Rdx, 0x0807_0605_0403_0201) + }), + (&[0x4c, 0x8d, 0x05, 0, 0, 0, 0], |a| { + a.lea(Qword, R8, Mem::rip(0)) + }), + (&[0xc4, 0xe2, 0xf1, 0xf7, 0xc0], |a| { + a.shift_x(ShiftOp::Shl, Qword, Rax, Rax, Rcx) + }), + (&[0xc4, 0xe2, 0x72, 0xf7, 0xc0], |a| { + a.shift_x(ShiftOp::Sar, Dword, Rax, Rax, Rcx) + }), + (&[0xc4, 0xe2, 0x73, 0xf7, 0xc0], |a| { + a.shift_x(ShiftOp::Shr, Dword, Rax, Rax, Rcx) + }), + (&[0xc4, 0xe3, 0xfb, 0xf0, 0xc0, 0x05], |a| { + a.rorx(Qword, Rax, Rax, 5) + }), + (&[0x66, 0x48, 0x0f, 0x6e, 0xc0], |a| a.movq_to_xmm(0, Rax)), + (&[0x66, 0x48, 0x0f, 0x7e, 0xc8], |a| a.movq_from_xmm(Rax, 1)), + (&[0x66, 0x49, 0x0f, 0x6e, 0xca], |a| a.movq_to_xmm(1, R10)), + (&[0x66, 0x0f, 0x3a, 0xce, 0xc1, 0x00], |a| { + a.gf2p8affineqb(0, Rm::Xmm(1), 0) + }), + (&[0x66, 0x44, 0x0f, 0x3a, 0xce, 0xc1, 0x00], |a| { + a.gf2p8affineqb(8, Rm::Xmm(1), 0) + }), + ] { + let (code, count) = bytes(build); + assert_eq!(code, expected); + assert_eq!(count, 1); + } + } + + #[test] + fn core_forms_match_the_sdm_encodings() { + use Gpr::*; + for (expected, build) in [ + ( + &[0x48, 0x8b, 0x47, 0x00][..], + (|a: &mut Asm| a.mov_load(Size::Qword, Rax, Mem::base_disp8(Rdi, 0))) + as fn(&mut Asm), + ), + (&[0x41, 0x57], |a| a.push(R15)), + (&[0x5d], |a| a.pop(Rbp)), + (&[0xff, 0xd0], |a| a.call_rm(Rax)), + (&[0x41, 0xff, 0xe3], |a| a.jmp_rm(R11)), + (&[0x66, 0x0f, 0xef, 0xc1], |a| { + a.sse(Some(0x66), &[0x0f, 0xef], 0, Rm::Xmm(1)) + }), + (&[0x66, 0x45, 0x0f, 0xef, 0xc1], |a| { + a.sse(Some(0x66), &[0x0f, 0xef], 8, Rm::Xmm(9)) + }), + (&[0x66, 0x0f, 0x70, 0xc1, 0x1b], |a| { + a.sse_imm(Some(0x66), &[0x0f, 0x70], 0, Rm::Xmm(1), 0x1b) + }), + (&[0x0f, 0xae, 0xf0], |a| a.fixed(&[0x0f, 0xae, 0xf0])), + // vpaddd zmm0{k1}, zmm1, zmm2 + (&[0x62, 0xf1, 0x75, 0x49, 0xfe, 0xc2], |a| { + a.evex( + Evex { + map: Map::M0f, + pp: Pp::P66, + w: false, + length: 2, + mask: 1, + zeroing: false, + broadcast: false, + scale: 64, + }, + 0xfe, + 0, + 1, + Rm::Xmm(2), + ) + }), + // vpaddd zmm16, zmm17, [rdi+0x40]: disp8*64 = 1. + (&[0x62, 0xe1, 0x75, 0x40, 0xfe, 0x47, 0x01], |a| { + a.evex( + Evex { + map: Map::M0f, + pp: Pp::P66, + w: false, + length: 2, + mask: 0, + zeroing: false, + broadcast: false, + scale: 64, + }, + 0xfe, + 16, + 17, + Rm::Mem(Mem::base(Rdi, 0x40)), + ) + }), + ] { + let (code, count) = bytes(build); + assert_eq!(code, expected); + assert_eq!(count, 1); + } + } + + #[test] + fn code_counts_across_encoders_and_prefixes_join_their_instruction() { + let mut code = Code::new(); + code.asm().mov(Size::Dword, Gpr::Rax, Gpr::Rcx); + let mut asm = code.asm(); + asm.lock(); + asm.alu(Alu::Add, Size::Dword, Mem::base(Gpr::Rdi, 0), Gpr::Rax); + assert_eq!(code.instructions(), 2); + assert_eq!(*code, [0x89, 0xc8, 0xf0, 0x01, 0x07]); + code.clear(); + assert_eq!((code.len(), code.instructions()), (0, 0)); + } + + #[test] + fn short_branches_resolve_relative_to_the_next_instruction() { + let (code, count) = bytes(|a| { + let forward = a.jcc8(Cond::Ne); + a.mov(Size::Dword, Gpr::Rax, Gpr::Rax); + a.bind(forward); + let back = a.jmp8(); + resolve(a.code, back, 0); + }); + assert_eq!(code, [0x75, 2, 0x89, 0xc0, 0xeb, 0xfa]); + assert_eq!(count, 3); + } + + #[test] + fn branches_resolve_relative_to_the_next_instruction() { + let (code, count) = bytes(|a| { + let forward = a.jcc(Cond::E); + a.mov(Size::Dword, Gpr::Rax, Gpr::Rax); + a.bind(forward); + let back = a.jmp(); + resolve(a.code, back, 0); + }); + assert_eq!( + code, + [ + 0x0f, 0x84, 2, 0, 0, 0, 0x89, 0xc0, 0xe9, 0xf3, 0xff, 0xff, 0xff + ] + ); + assert_eq!(count, 3); + } +} diff --git a/crates/stela-compiler/src/x86_64/asm/control.rs b/crates/stela-compiler/src/x86_64/asm/control.rs new file mode 100644 index 0000000000..1fe6b83a17 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/asm/control.rs @@ -0,0 +1,92 @@ +//! Typed control, flag-capture and absolute-address forms (Intel SDM Vol. 2) +//! beyond the core's branch, move and SETcc forms. +use super::{Asm, Cond, Patch}; + +/// The legacy high-byte registers AH, CH, DH and BH, which ModRM r/m +/// values 4 to 7 name in an instruction without a REX prefix. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum HighByte { + Ah = 4, + Ch = 5, + Dh = 6, + Bh = 7, +} + +impl Asm<'_> { + /// `ud2` (0F 0B): raise #UD. + pub(crate) fn ud2(&mut self) { + self.fixed(&[0x0f, 0x0b]); + } + /// `setcc r/m8` (0F 90+cc /0) into AH, CH, DH or BH, without REX. + pub(crate) fn setcc_high(&mut self, cond: Cond, register: HighByte) { + self.fixed(&[0x0f, 0x90 | cond as u8, 0xc0 | register as u8]); + } + /// `mov rax, moffs64` (REX.W A1): RAX from the absolute `address`. + pub(crate) fn mov_rax_moffs(&mut self, address: u64) { + self.fixed(&[0x48, 0xa1]); + self.data(&address.to_le_bytes()); + } + /// `cpuid` (0F A2): processor identification for leaf EAX, serializing. + pub(crate) fn cpuid(&mut self) { + self.fixed(&[0x0f, 0xa2]); + } + /// `pause` (F3 90): a spin-wait hint. + pub(crate) fn pause(&mut self) { + self.fixed(&[0xf3, 0x90]); + } + /// `jrcxz rel8` (E3 cb): branch when RCX is zero, without reading or + /// writing flags; resolved later by [`Self::bind`] or [`resolve`]. + /// + /// [`resolve`]: super::resolve + pub(crate) fn jrcxz(&mut self) -> Patch { + self.code.push(0xe3); + self.short_patch() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::x86_64::asm::Code; + + fn one(build: impl FnOnce(&mut Asm)) -> Code { + let mut code = Code::new(); + build(&mut code.asm()); + assert_eq!(code.instructions(), 1); + code + } + + #[test] + fn forms_match_the_sdm_encodings() { + for (expected, code) in [ + (&[0x0f, 0x0b][..], one(|a| a.ud2())), + (&[0x0f, 0xa2], one(|a| a.cpuid())), + (&[0xf3, 0x90], one(|a| a.pause())), + ( + &[0x0f, 0x94, 0xc4], + one(|a| a.setcc_high(Cond::E, HighByte::Ah)), + ), + ( + &[0x0f, 0x90, 0xc6], + one(|a| a.setcc_high(Cond::O, HighByte::Dh)), + ), + ( + &[0x48, 0xa1, 8, 7, 6, 5, 4, 3, 2, 1], + one(|a| a.mov_rax_moffs(0x0102_0304_0506_0708)), + ), + ] { + assert_eq!(code, expected); + } + } + + #[test] + fn jrcxz_resolves_relative_to_the_next_instruction() { + let mut code = Code::new(); + let mut asm = code.asm(); + let skip = asm.jrcxz(); + asm.nop(); + asm.bind(skip); + assert_eq!((code.instructions(), &code[..]), (2, &[0xe3, 1, 0x90][..])); + } +} diff --git a/crates/stela-compiler/src/x86_64/asm/integer.rs b/crates/stela-compiler/src/x86_64/asm/integer.rs new file mode 100644 index 0000000000..33a42065a4 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/asm/integer.rs @@ -0,0 +1,204 @@ +//! Typed general-purpose forms (Intel SDM Vol. 2) beyond the core's ALU, +//! move, shift and branch forms. +use super::{Alu, Asm, Gpr, Map, Pp, Rm, Size, Vex}; + +/// Bit test operations, numbered by their group 8 ModRM reg digit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum BitTest { + Bt = 4, + Bts = 5, + Btr = 6, + Btc = 7, +} + +impl Asm<'_> { + /// `sub rsp, imm32`: reserve `bytes` of private stack. + pub(crate) fn reserve_stack(&mut self, bytes: usize) { + self.alu_imm32(Alu::Sub, Size::Qword, Gpr::Rsp, bytes as i32); + } + /// `add rsp, imm32`: release `bytes` of private stack. + pub(crate) fn release_stack(&mut self, bytes: usize) { + self.alu_imm32(Alu::Add, Size::Qword, Gpr::Rsp, bytes as i32); + } + /// `op r/m8, imm8` (80 /digit). + pub(crate) fn alu_byte_imm(&mut self, op: Alu, rm: impl Into, value: u8) { + self.legacy(Size::Byte, None, &[0x80], op as u8, false, rm.into()); + self.data(&[value]); + } + /// `test r/m, imm`: imm8 for a byte, imm16 for a word, otherwise imm32 + /// (sign-extended for a quadword). + pub(crate) fn test_imm(&mut self, size: Size, rm: impl Into, value: i32) { + let opcode = if size == Size::Byte { 0xf6 } else { 0xf7 }; + self.legacy(size, None, &[opcode], 0, false, rm.into()); + match size { + Size::Byte => self.data(&[value as u8]), + Size::Word => self.data(&(value as u16).to_le_bytes()), + Size::Dword | Size::Qword => self.data(&value.to_le_bytes()), + } + } + /// `test al/ax/eax/rax, imm`, the accumulator short form (A8 ib, A9 iw/id). + pub(crate) fn test_accumulator_imm(&mut self, size: Size, value: i32) { + match size { + Size::Byte => { + self.fixed(&[0xa8]); + self.data(&[value as u8]); + } + Size::Word => { + self.fixed(&[0x66, 0xa9]); + self.data(&(value as u16).to_le_bytes()); + } + Size::Dword => { + self.fixed(&[0xa9]); + self.data(&value.to_le_bytes()); + } + Size::Qword => { + self.fixed(&[0x48, 0xa9]); + self.data(&value.to_le_bytes()); + } + } + } + /// `inc r/m`. + pub(crate) fn inc(&mut self, size: Size, rm: impl Into) { + let opcode = if size == Size::Byte { 0xfe } else { 0xff }; + self.legacy(size, None, &[opcode], 0, false, rm.into()); + } + /// `dec r/m`. + pub(crate) fn dec(&mut self, size: Size, rm: impl Into) { + let opcode = if size == Size::Byte { 0xfe } else { 0xff }; + self.legacy(size, None, &[opcode], 1, false, rm.into()); + } + /// `bt`, `bts`, `btr` or `btc r/m, imm8` (0F BA /digit ib). + pub(crate) fn bit_imm(&mut self, op: BitTest, size: Size, rm: impl Into, bit: u8) { + self.legacy(size, None, &[0x0f, 0xba], op as u8, false, rm.into()); + self.data(&[bit]); + } + /// `bt`, `bts`, `btr` or `btc r/m, reg` (0F A3, AB, B3, BB): the bit + /// index is modulo the operand width for a register and unbounded for + /// memory. + pub(crate) fn bit(&mut self, op: BitTest, size: Size, rm: impl Into, source: Gpr) { + let opcode = 0xa3 | (op as u8 - BitTest::Bt as u8) << 3; + self.legacy(size, None, &[0x0f, opcode], source as u8, false, rm.into()); + } + /// `shld r/m, src, imm8`. + pub(crate) fn shld_imm(&mut self, size: Size, rm: impl Into, source: Gpr, amount: u8) { + self.legacy(size, None, &[0x0f, 0xa4], source as u8, false, rm.into()); + self.data(&[amount]); + } + /// A BMI1 group 17 form (VEX.0F38 F3 /digit) writing `destination`. + fn bmi1_group(&mut self, digit: u8, size: Size, destination: Gpr, rm: Rm) { + self.vex( + Vex { + map: Map::M0f38, + pp: Pp::None, + w: size == Size::Qword, + l: false, + }, + 0xf3, + digit, + destination as u8, + rm, + ); + } + /// `blsi dst, r/m`: the lowest set bit of `rm` (BMI1). + pub(crate) fn blsi(&mut self, size: Size, destination: Gpr, rm: impl Into) { + self.bmi1_group(3, size, destination, rm.into()); + } + /// `blsmsk dst, r/m`: the bits up to and including the lowest set bit of + /// `rm` (BMI1). + pub(crate) fn blsmsk(&mut self, size: Size, destination: Gpr, rm: impl Into) { + self.bmi1_group(2, size, destination, rm.into()); + } + /// `rep movsb`: copy RCX bytes from [RSI] to [RDI]. + pub(crate) fn rep_movsb(&mut self) { + self.prefix(0xf3); + self.fixed(&[0xa4]); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::x86_64::asm::{Code, Gpr::*, Mem}; + + fn one(build: impl FnOnce(&mut Asm)) -> Code { + let mut code = Code::new(); + build(&mut code.asm()); + assert_eq!(code.instructions(), 1); + code + } + + #[test] + fn forms_match_the_sdm_encodings() { + use BitTest::*; + use Size::*; + for (expected, code) in [ + ( + &[0xf7, 0xc1, 0x1f, 0, 0, 0][..], + one(|a| a.test_imm(Dword, Rcx, 0x1f)), + ), + ( + &[0xf7, 0x87, 0x10, 0, 0, 0, 0x20, 0, 0, 0], + one(|a| a.test_imm(Dword, Mem::base_disp32(Rdi, 0x10), 0x20)), + ), + ( + &[0xf6, 0x84, 0x24, 8, 0, 0, 0, 1], + one(|a| a.test_imm(Byte, Mem::base_disp32(Rsp, 8), 1)), + ), + (&[0xa8, 0x3f], one(|a| a.test_accumulator_imm(Byte, 0x3f))), + ( + &[0xa9, 0xff, 0xff, 0xff, 0x1f], + one(|a| a.test_accumulator_imm(Dword, 0x1fff_ffff)), + ), + ( + &[0x80, 0xf9, 0x10], + one(|a| a.alu_byte_imm(Alu::Cmp, Rcx, 0x10)), + ), + (&[0x41, 0xff, 0xc3], one(|a| a.inc(Dword, R11))), + (&[0x48, 0xff, 0xc1], one(|a| a.inc(Qword, Rcx))), + (&[0x41, 0xff, 0xc8], one(|a| a.dec(Dword, R8))), + ( + &[0x48, 0x0f, 0xa3, 0xc8], + one(|a| a.bit(Bt, Qword, Rax, Rcx)), + ), + ( + &[0x41, 0x0f, 0xba, 0xe0, 15], + one(|a| a.bit_imm(Bt, Dword, R8, 15)), + ), + ( + &[0x48, 0x0f, 0xba, 0xe8, 3], + one(|a| a.bit_imm(Bts, Qword, Rax, 3)), + ), + ( + &[0x48, 0x0f, 0xba, 0xf0, 63], + one(|a| a.bit_imm(Btr, Qword, Rax, 63)), + ), + ( + &[0x48, 0x0f, 0xba, 0xf8, 63], + one(|a| a.bit_imm(Btc, Qword, Rax, 63)), + ), + ( + &[0x48, 0x0f, 0xa4, 0xc2, 1], + one(|a| a.shld_imm(Qword, Rdx, Rax, 1)), + ), + ( + &[0xc4, 0xc2, 0xb0, 0xf3, 0xdb], + one(|a| a.blsi(Qword, R9, R11)), + ), + ( + &[0xc4, 0xc2, 0xf8, 0xf3, 0xd1], + one(|a| a.blsmsk(Qword, Rax, R9)), + ), + ( + &[0x48, 0x81, 0xec, 0x40, 0, 0, 0], + one(|a| a.reserve_stack(0x40)), + ), + ( + &[0x48, 0x81, 0xc4, 0x40, 0, 0, 0], + one(|a| a.release_stack(0x40)), + ), + ] { + assert_eq!(code, expected); + } + } +} diff --git a/crates/stela-compiler/src/x86_64/asm/memory.rs b/crates/stela-compiler/src/x86_64/asm/memory.rs new file mode 100644 index 0000000000..5109209756 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/asm/memory.rs @@ -0,0 +1,141 @@ +//! Typed memory-access, atomic and fence forms (Intel SDM Vol. 2) on the +//! generic legacy encoding. +use super::{Alu, Asm, Gpr, Mem, Rm, Size}; + +/// PREFETCHh cache hints, numbered by their ModRM reg digit (0F 18 /digit). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum Prefetch { + /// `prefetchnta`: non-temporal, minimizing cache pollution. + Nta, + /// `prefetcht0`: into every cache level. + T0, + /// `prefetcht1`: into level 2 and outward. + T1, + /// `prefetcht2`: into level 3 and outward. + T2, +} + +impl Asm<'_> { + /// `prefetchnta`, `prefetcht0`, `prefetcht1` or `prefetcht2 m8` + /// (0F 18 /digit). + pub(crate) fn prefetch(&mut self, hint: Prefetch, memory: Mem) { + self.legacy( + Size::Dword, + None, + &[0x0f, 0x18], + hint as u8, + false, + Rm::Mem(memory), + ); + } + /// `rdtsc` (0F 31): EDX:EAX = the time-stamp counter. + pub(crate) fn rdtsc(&mut self) { + self.fixed(&[0x0f, 0x31]); + } + /// `mfence` (0F AE F0): order every earlier load and store before every + /// later one. + pub(crate) fn mfence(&mut self) { + self.fixed(&[0x0f, 0xae, 0xf0]); + } + /// `op al, imm8`, the byte accumulator short form (04 + 8 * op, ib). + pub(crate) fn alu_accumulator_imm8(&mut self, op: Alu, value: u8) { + self.fixed(&[(op as u8) << 3 | 4]); + self.data(&[value]); + } + /// `shrd r/m, src, cl` (0F AD). + pub(crate) fn shrd_cl(&mut self, size: Size, rm: impl Into, source: Gpr) { + self.legacy(size, None, &[0x0f, 0xad], source as u8, false, rm.into()); + } + /// `cmpxchg r/m, src` (0F B0, 0F B1): compare the accumulator with + /// `rm`, storing `source` when equal and loading `rm` otherwise. + pub(crate) fn cmpxchg(&mut self, size: Size, rm: impl Into, source: Gpr) { + let opcode = if size == Size::Byte { 0xb0 } else { 0xb1 }; + self.legacy(size, None, &[0x0f, opcode], source as u8, true, rm.into()); + } + /// `xadd r/m, src` (0F C0, 0F C1): `rm` += `source`, and `source` the + /// old `rm`. + pub(crate) fn xadd(&mut self, size: Size, rm: impl Into, source: Gpr) { + let opcode = if size == Size::Byte { 0xc0 } else { 0xc1 }; + self.legacy(size, None, &[0x0f, opcode], source as u8, true, rm.into()); + } + /// `xchg r/m, src` (86, 87), implicitly locked for memory. + pub(crate) fn xchg(&mut self, size: Size, rm: impl Into, source: Gpr) { + let opcode = if size == Size::Byte { 0x86 } else { 0x87 }; + self.legacy(size, None, &[opcode], source as u8, true, rm.into()); + } + /// `cmpxchg8b m64` (0F C7 /1): compare EDX:EAX with memory, storing + /// ECX:EBX when equal and loading it otherwise. + pub(crate) fn cmpxchg8b(&mut self, memory: Mem) { + self.legacy(Size::Dword, None, &[0x0f, 0xc7], 1, false, Rm::Mem(memory)); + } + /// `cmpxchg16b m128` (REX.W 0F C7 /1): compare RDX:RAX with memory, + /// storing RCX:RBX when equal and loading it otherwise. + pub(crate) fn cmpxchg16b(&mut self, memory: Mem) { + self.legacy(Size::Qword, None, &[0x0f, 0xc7], 1, false, Rm::Mem(memory)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::x86_64::asm::{Code, Gpr::*}; + + fn one(build: impl FnOnce(&mut Asm)) -> Code { + let mut code = Code::new(); + build(&mut code.asm()); + assert_eq!(code.instructions(), 1); + code + } + + #[test] + fn forms_match_the_sdm_encodings() { + use Size::*; + let rdx = Mem::base(Rdx, 0); + for (expected, code) in [ + (&[0x0f, 0x0b][..], one(|a| a.ud2())), + (&[0x0f, 0x31], one(|a| a.rdtsc())), + ( + &[0x0f, 0x18, 0x00], + one(|a| a.prefetch(Prefetch::Nta, Mem::base(Rax, 0))), + ), + ( + &[0x0f, 0x18, 0x5c, 0xc8, 0x10], + one(|a| a.prefetch(Prefetch::T2, Mem::indexed(Rax, Rcx, 8, 0x10))), + ), + ( + &[0x0f, 0x18, 0x90, 0, 1, 0, 0], + one(|a| a.prefetch(Prefetch::T1, Mem::base(Rax, 0x100))), + ), + (&[0x0f, 0xae, 0xf0], one(|a| a.mfence())), + (&[0x3c, 12], one(|a| a.alu_accumulator_imm8(Alu::Cmp, 12))), + ( + &[0x4c, 0x0f, 0xad, 0xc0], + one(|a| a.shrd_cl(Qword, Rax, R8)), + ), + (&[0x0f, 0xb0, 0x0a], one(|a| a.cmpxchg(Byte, rdx, Rcx))), + ( + &[0x66, 0x44, 0x0f, 0xb1, 0x02], + one(|a| a.cmpxchg(Word, rdx, R8)), + ), + ( + &[0x4c, 0x0f, 0xb1, 0x02], + one(|a| a.cmpxchg(Qword, rdx, R8)), + ), + (&[0x0f, 0xc0, 0x02], one(|a| a.xadd(Byte, rdx, Rax))), + (&[0x48, 0x0f, 0xc1, 0x02], one(|a| a.xadd(Qword, rdx, Rax))), + (&[0x86, 0x02], one(|a| a.xchg(Byte, rdx, Rax))), + (&[0x66, 0x87, 0x02], one(|a| a.xchg(Word, rdx, Rax))), + ( + &[0x41, 0x0f, 0xc7, 0x08], + one(|a| a.cmpxchg8b(Mem::base(R8, 0))), + ), + ( + &[0x49, 0x0f, 0xc7, 0x08], + one(|a| a.cmpxchg16b(Mem::base(R8, 0))), + ), + ] { + assert_eq!(code, expected); + } + } +} diff --git a/crates/stela-compiler/src/x86_64/asm/sse.rs b/crates/stela-compiler/src/x86_64/asm/sse.rs new file mode 100644 index 0000000000..14f2af2c14 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/asm/sse.rs @@ -0,0 +1,354 @@ +//! Typed SSE and AVX forms (Intel SDM Vol. 2) on the generic legacy and SSE +//! encodings. +use super::{Asm, Gpr, Rm, Size}; + +/// Legacy SSE forms `name xmm, xmm/m`: an optional mandatory prefix and the +/// opcode bytes. +macro_rules! sse { + ($($(#[$doc:meta])* $name:ident => $prefix:expr, [$($opcode:literal),+];)+) => { + impl Asm<'_> { + $( + $(#[$doc])* + pub(crate) fn $name(&mut self, xmm: u8, rm: impl Into) { + self.sse($prefix, &[$($opcode),+], xmm, rm); + } + )+ + } + }; +} + +/// Legacy SSE forms `name xmm, xmm/m, imm8`. +macro_rules! sse_imm { + ($($(#[$doc:meta])* $name:ident => $prefix:expr, [$($opcode:literal),+];)+) => { + impl Asm<'_> { + $( + $(#[$doc])* + pub(crate) fn $name(&mut self, xmm: u8, rm: impl Into, immediate: u8) { + self.sse_imm($prefix, &[$($opcode),+], xmm, rm, immediate); + } + )+ + } + }; +} + +sse! { + /// `movlhps xmm, xmm`: the low qword of the source to the high qword. + movlhps => None, [0x0f, 0x16]; + /// `movhps xmm, m64`: memory to the high qword. + movhps => None, [0x0f, 0x16]; + /// `movhlps xmm, xmm`: the high qword of the source to the low qword. + movhlps => None, [0x0f, 0x12]; + /// `movq m64, xmm` (66 0F D6), named by its register first. + movq_store => Some(0x66), [0x0f, 0xd6]; + /// `movq xmm, xmm/m64`: the low qword, zeroing the high one. + movq_xmm => Some(0xf3), [0x0f, 0x7e]; + /// `movdqu xmm, xmm/m128`. + movdqu_load => Some(0xf3), [0x0f, 0x6f]; + /// `unpcklps xmm, xmm/m128`. + unpcklps => None, [0x0f, 0x14]; + /// `unpcklpd xmm, xmm/m128`. + unpcklpd => Some(0x66), [0x0f, 0x14]; + /// `unpckhpd xmm, xmm/m128`. + unpckhpd => Some(0x66), [0x0f, 0x15]; + /// `cvtss2sd xmm, xmm/m32`. + cvtss2sd => Some(0xf3), [0x0f, 0x5a]; + /// `cvtsd2ss xmm, xmm/m64`. + cvtsd2ss => Some(0xf2), [0x0f, 0x5a]; + /// `cvtps2pd xmm, xmm/m64`. + cvtps2pd => None, [0x0f, 0x5a]; + /// `cvtpd2ps xmm, xmm/m128`. + cvtpd2ps => Some(0x66), [0x0f, 0x5a]; + /// `cvtdq2pd xmm, xmm/m64`. + cvtdq2pd => Some(0xf3), [0x0f, 0xe6]; + /// `cvttps2dq xmm, xmm/m128`. + cvttps2dq => Some(0xf3), [0x0f, 0x5b]; + /// `ucomiss xmm, xmm/m32`: unordered compare into ZF/PF/CF. + ucomiss => None, [0x0f, 0x2e]; + /// `ucomisd xmm, xmm/m64`: unordered compare into ZF/PF/CF. + ucomisd => Some(0x66), [0x0f, 0x2e]; + /// `psadbw xmm, xmm/m128`: sums of absolute byte differences per qword. + psadbw => Some(0x66), [0x0f, 0xf6]; + /// `pblendvb xmm, xmm/m128, ` (SSE4.1): bytes of `rm` where XMM0 + /// bytes have their sign set. + pblendvb => Some(0x66), [0x0f, 0x38, 0x10]; +} + +sse_imm! { + /// `pinsrw xmm, r32/m16, imm8`. + pinsrw => Some(0x66), [0x0f, 0xc4]; + /// `pinsrd xmm, r/m32, imm8` (SSE4.1). + pinsrd => Some(0x66), [0x0f, 0x3a, 0x22]; + /// `shufps xmm, xmm/m128, imm8`. + shufps => None, [0x0f, 0xc6]; +} + +/// The lanes an SSE floating-point operation covers, which select its +/// mandatory prefix. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum FloatLanes { + PackedSingle, + ScalarSingle, + PackedDouble, + ScalarDouble, +} + +impl FloatLanes { + const fn prefix(self) -> Option { + match self { + Self::PackedSingle => None, + Self::ScalarSingle => Some(0xf3), + Self::PackedDouble => Some(0x66), + Self::ScalarDouble => Some(0xf2), + } + } +} + +/// SSE floating-point operations that share the `0F op` opcode across the +/// four lane forms (`ps`, `ss`, `pd`, `sd`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum FloatOp { + Sqrt = 0x51, + Add = 0x58, + Mul = 0x59, + Sub = 0x5c, + Min = 0x5d, + Div = 0x5e, + Max = 0x5f, +} + +impl Asm<'_> { + /// `op{ps,ss,pd,sd} xmm, xmm/m`. MIN and MAX return the second operand + /// when either is NaN or both are zero. + pub(crate) fn float(&mut self, op: FloatOp, lanes: FloatLanes, xmm: u8, rm: impl Into) { + self.sse(lanes.prefix(), &[0x0f, op as u8], xmm, rm); + } + /// `cmp{ps,ss,pd,sd} xmm, xmm/m, predicate`. + pub(crate) fn float_compare( + &mut self, + lanes: FloatLanes, + xmm: u8, + rm: impl Into, + predicate: u8, + ) { + self.sse_imm(lanes.prefix(), &[0x0f, 0xc2], xmm, rm, predicate); + } + /// `cvtsi2ss`/`cvtsi2sd xmm, r/m32/64` (F3/F2 [REX.W] 0F 2A) for a scalar + /// `lanes` form. + pub(crate) fn cvtsi2float( + &mut self, + lanes: FloatLanes, + size: Size, + xmm: u8, + rm: impl Into, + ) { + self.legacy(size, lanes.prefix(), &[0x0f, 0x2a], xmm, false, rm.into()); + } + /// `cvtss2si`/`cvtsd2si r32/64, xmm/m` (0F 2D), or the truncating + /// `cvtt` forms (0F 2C), for a scalar `lanes` form. + pub(crate) fn cvtfloat2si( + &mut self, + lanes: FloatLanes, + truncate: bool, + size: Size, + destination: Gpr, + rm: impl Into, + ) { + let opcode = if truncate { 0x2c } else { 0x2d }; + self.legacy( + size, + lanes.prefix(), + &[0x0f, opcode], + destination as u8, + false, + rm.into(), + ); + } + /// `movdqu xmm/m128, xmm`. + pub(crate) fn movdqu_store(&mut self, rm: impl Into, xmm: u8) { + self.sse(Some(0xf3), &[0x0f, 0x7f], xmm, rm); + } + /// `pextrw r32, xmm, imm8` (66 0F C5): zero-extends word `lane`. + pub(crate) fn pextrw(&mut self, destination: Gpr, xmm: u8, lane: u8) { + self.sse_imm( + Some(0x66), + &[0x0f, 0xc5], + destination as u8, + Rm::Xmm(xmm), + lane, + ); + } + /// `pextrd r/m32, xmm, imm8` (66 0F 3A 16, SSE4.1). + pub(crate) fn pextrd(&mut self, rm: impl Into, xmm: u8, lane: u8) { + self.sse_imm(Some(0x66), &[0x0f, 0x3a, 0x16], xmm, rm, lane); + } + /// `pextrq r/m64, xmm, imm8` (66 REX.W 0F 3A 16, SSE4.1). + pub(crate) fn pextrq(&mut self, rm: impl Into, xmm: u8, lane: u8) { + self.legacy( + Size::Qword, + Some(0x66), + &[0x0f, 0x3a, 0x16], + xmm, + false, + rm.into(), + ); + self.data(&[lane]); + } + /// `movd xmm, r/m32`, zeroing the rest of `xmm`. + pub(crate) fn movd_to_xmm(&mut self, xmm: u8, rm: impl Into) { + self.sse(Some(0x66), &[0x0f, 0x6e], xmm, rm); + } + /// `movd r/m32, xmm`. + pub(crate) fn movd_from_xmm(&mut self, rm: impl Into, xmm: u8) { + self.sse(Some(0x66), &[0x0f, 0x7e], xmm, rm); + } + /// `stmxcsr m32`. + pub(crate) fn stmxcsr(&mut self, memory: impl Into) { + self.legacy(Size::Dword, None, &[0x0f, 0xae], 3, false, memory.into()); + } + /// `ldmxcsr m32`. + pub(crate) fn ldmxcsr(&mut self, memory: impl Into) { + self.legacy(Size::Dword, None, &[0x0f, 0xae], 2, false, memory.into()); + } + /// `vzeroupper` (AVX). + pub(crate) fn vzeroupper(&mut self) { + self.fixed(&[0xc5, 0xf8, 0x77]); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::x86_64::asm::{Code, Gpr::*, Mem}; + + fn one(build: impl FnOnce(&mut Asm)) -> Code { + let mut code = Code::new(); + build(&mut code.asm()); + assert_eq!(code.instructions(), 1); + code + } + + #[test] + fn forms_match_the_sdm_encodings() { + use FloatLanes::*; + use Size::*; + for (expected, code) in [ + (&[0xc5, 0xf8, 0x77][..], one(|a| a.vzeroupper())), + (&[0x0f, 0x16, 0xca], one(|a| a.movlhps(1, Rm::Xmm(2)))), + (&[0x66, 0x0f, 0x7e, 0xf0], one(|a| a.movd_from_xmm(Rax, 6))), + (&[0x66, 0x0f, 0x6e, 0xe0], one(|a| a.movd_to_xmm(4, Rax))), + (&[0x66, 0x0f, 0x6e, 0xf1], one(|a| a.movd_to_xmm(6, Rcx))), + ( + &[0x66, 0x0f, 0xd6, 0x48, 0x08], + one(|a| a.movq_store(1, Mem::base(Rax, 8))), + ), + ( + &[0xf3, 0x0f, 0x6f, 0x44, 0x24, 0x10], + one(|a| a.movdqu_load(0, Mem::base_disp8(Rsp, 0x10))), + ), + ( + &[0xf3, 0x0f, 0x7f, 0x9c, 0x24, 0x20, 0, 0, 0], + one(|a| a.movdqu_store(Mem::base_disp32(Rsp, 0x20), 3)), + ), + ( + &[0x66, 0x0f, 0xc4, 0xc0, 0x01], + one(|a| a.pinsrw(0, Rax, 1)), + ), + ( + &[0x66, 0x0f, 0x3a, 0x22, 0xc8, 2], + one(|a| a.pinsrd(1, Rax, 2)), + ), + ( + &[0x0f, 0xae, 0x1c, 0x24], + one(|a| a.stmxcsr(Mem::base(Rsp, 0))), + ), + ( + &[0x0f, 0xae, 0x54, 0x24, 0x04], + one(|a| a.ldmxcsr(Mem::base(Rsp, 4))), + ), + ( + &[0x0f, 0xc6, 0xc1, 0x88], + one(|a| a.shufps(0, Rm::Xmm(1), 0x88)), + ), + (&[0x0f, 0x14, 0xc1], one(|a| a.unpcklps(0, Rm::Xmm(1)))), + ( + &[0x66, 0x0f, 0x14, 0xea], + one(|a| a.unpcklpd(5, Rm::Xmm(2))), + ), + ( + &[0x66, 0x0f, 0x15, 0xc6], + one(|a| a.unpckhpd(0, Rm::Xmm(6))), + ), + (&[0x66, 0x0f, 0x2e, 0xc1], one(|a| a.ucomisd(0, Rm::Xmm(1)))), + (&[0x0f, 0x2e, 0xc7], one(|a| a.ucomiss(0, Rm::Xmm(7)))), + ( + &[0xf3, 0x0f, 0x5a, 0xf6], + one(|a| a.cvtss2sd(6, Rm::Xmm(6))), + ), + ( + &[0xf2, 0x0f, 0x5a, 0xc1], + one(|a| a.cvtsd2ss(0, Rm::Xmm(1))), + ), + (&[0x0f, 0x5a, 0xf0], one(|a| a.cvtps2pd(6, Rm::Xmm(0)))), + ( + &[0x66, 0x0f, 0x5a, 0xc1], + one(|a| a.cvtpd2ps(0, Rm::Xmm(1))), + ), + ( + &[0xf2, 0x48, 0x0f, 0x2a, 0xc0], + one(|a| a.cvtsi2float(ScalarDouble, Qword, 0, Rax)), + ), + ( + &[0xf3, 0x48, 0x0f, 0x2a, 0xf0], + one(|a| a.cvtsi2float(ScalarSingle, Qword, 6, Rax)), + ), + ( + &[0xf3, 0x0f, 0x2c, 0xc0], + one(|a| a.cvtfloat2si(ScalarSingle, true, Dword, Rax, Rm::Xmm(0))), + ), + ( + &[0xf2, 0x48, 0x0f, 0x2c, 0xc2], + one(|a| a.cvtfloat2si(ScalarDouble, true, Qword, Rax, Rm::Xmm(2))), + ), + (&[0x66, 0x0f, 0xc5, 0xc0, 0], one(|a| a.pextrw(Rax, 0, 0))), + ( + &[0x66, 0x41, 0x0f, 0xc5, 0xc9, 3], + one(|a| a.pextrw(Rcx, 9, 3)), + ), + ( + &[0x66, 0x49, 0x0f, 0x3a, 0x16, 0x88, 0x40, 0, 0, 0, 1], + one(|a| a.pextrq(Mem::base_disp32(R8, 0x40), 1, 1)), + ), + ( + &[0x41, 0x0f, 0x16, 0x90, 8, 0, 0, 0], + one(|a| a.movhps(2, Mem::base_disp32(R8, 8))), + ), + ( + &[0xf3, 0x0f, 0xc2, 0xc8, 2], + one(|a| a.float_compare(ScalarSingle, 1, Rm::Xmm(0), 2)), + ), + ( + &[0x66, 0x41, 0x0f, 0xc2, 0xc0, 0], + one(|a| a.float_compare(PackedDouble, 0, Rm::Xmm(8), 0)), + ), + ( + &[0xf2, 0x0f, 0x5d, 0xc1], + one(|a| a.float(FloatOp::Min, ScalarDouble, 0, Rm::Xmm(1))), + ), + ( + &[0x0f, 0x5f, 0xf1], + one(|a| a.float(FloatOp::Max, PackedSingle, 6, Rm::Xmm(1))), + ), + ( + &[0x66, 0x0f, 0x51, 0xc0], + one(|a| a.float(FloatOp::Sqrt, PackedDouble, 0, Rm::Xmm(0))), + ), + ( + &[0x0f, 0x58, 0xd4], + one(|a| a.float(FloatOp::Add, PackedSingle, 2, Rm::Xmm(4))), + ), + ] { + assert_eq!(code, expected); + } + } +} diff --git a/crates/stela-compiler/src/x86_64/atomic.rs b/crates/stela-compiler/src/x86_64/atomic.rs index 52f2592d0b..55c1fc00ce 100644 --- a/crates/stela-compiler/src/x86_64/atomic.rs +++ b/crates/stela-compiler/src/x86_64/atomic.rs @@ -4,7 +4,7 @@ use crate::aarch64::{ Register, atomic::{Kind, Operand}, }; -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, Size}; mod compare_exchange; mod compare_exchange_pair; @@ -17,49 +17,18 @@ const QWORD_BYTES: u8 = 8; const ATOMIC_GRANULE_BYTES: u8 = 16; const DOUBLEWORD_PAIR_BYTES: u8 = 2 * QWORD_BYTES; const ATOMIC_GRANULE_MASK: u8 = ATOMIC_GRANULE_BYTES - 1; -const TEST_AL_IMM8: &[u8] = &[0xa8]; -const JE_REL8: u8 = 0x74; -const JBE_REL8: u8 = 0x76; -const UD2: &[u8] = &[0x0f, 0x0b]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const AND_ECX_IMM8: &[u8] = &[0x83, 0xe1]; -const CMP_CL_IMM8: &[u8] = &[0x80, 0xf9]; -const ADD_RAX_IMM32: &[u8] = &[0x48, 0x05]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const LOCK: u8 = 0xf0; -const OPERAND_SIZE_PREFIX: u8 = 0x66; -const REX_PREFIX: u8 = 0x40; -const REX_W_BIT: u8 = 0x08; -const REX_R_BIT: u8 = 0x04; -const TWO_BYTE_OPCODE: u8 = 0x0f; -const CMPXCHG_BYTE: u8 = 0xb0; -const CMPXCHG_WIDER: u8 = 0xb1; -const RDX_ADDRESS: u8 = 2; -const REGISTER_SHIFT: u8 = 3; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const XOR_ECX_ECX: &[u8] = &[0x31, 0xc9]; -const STATE_RAX: u8 = 0x87; -const STATE_RCX: u8 = 0x8f; -const MOVZX_BYTE: u8 = 0xb6; -const MOVZX_HALFWORD: u8 = 0xb7; -const MOV: u8 = 0x8b; -const MOV_STORE_BYTE: u8 = 0x88; -const MOV_STORE: u8 = 0x89; -/// `[rdx], rcx`. -const RCX_RDX_MEMORY: u8 = 0x0a; -const MOV_EAX_IMM32: u8 = 0xb8; -const MOV_ECX_IMM32: u8 = 0xb9; +/// `[rdx]`, the checked guest address. +const ADDRESS: Mem = Mem::base(Gpr::Rdx, 0); -#[derive(Clone, Copy)] -enum InputRegister { - Rax, - Rcx, -} - -#[derive(Clone, Copy)] -pub(super) enum ValueRegister { - Rcx, - R8, +/// The operand size of a `bytes`-wide access. +fn size(bytes: u8) -> Size { + match bytes { + BYTE_BYTES => Size::Byte, + HALFWORD_BYTES => Size::Word, + DWORD_BYTES => Size::Dword, + QWORD_BYTES => Size::Qword, + _ => unreachable!("decoder validates atomic widths"), + } } /// A CASP of two doublewords needs CMPXCHG16B, unless it is a plain access @@ -80,7 +49,7 @@ pub(super) fn requires_cx16( /// a store to read-only memory WnR 1, as Arm requires of an atomic that /// reads and writes (ESR_ELx.WnR); a locked x86 update faults as a write. pub(super) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, target: crate::TargetCpu, checks: super::MemoryChecks, @@ -98,7 +67,7 @@ pub(super) fn emit( /// SP is checked first. LSE2 accesses must fit the selected aligned 16-byte granule. /// RAX/RCX are scratch, RDX receives the address, and guest state is untouched. -pub(super) fn address(code: &mut Vec, base: Register, bytes: u8, checks: super::MemoryChecks) { +pub(super) fn address(code: &mut Code, base: Register, bytes: u8, checks: super::MemoryChecks) { let access = super::Access::write(bytes.into()).atomic(); address_offset(code, base, bytes, 0, checks, true, access); } @@ -108,7 +77,7 @@ pub(super) fn address(code: &mut Vec, base: Register, bytes: u8, checks: sup /// a known-aligned SP needs no run-time boundary test. Without the SP /// alignment check, SP is an ordinary base. pub(super) fn address_offset( - code: &mut Vec, + code: &mut Code, base: Register, bytes: u8, displacement: i32, @@ -119,120 +88,103 @@ pub(super) fn address_offset( load(code, base); let aligned_sp = base == Register::Sp && checks.stack_alignment; if aligned_sp { - code.extend(TEST_AL_IMM8); - code.push(ATOMIC_GRANULE_MASK); - code.extend([JE_REL8, UD2.len() as u8]); - code.extend(UD2); + let mut asm = code.asm(); + asm.test_accumulator_imm(Size::Byte, ATOMIC_GRANULE_MASK.into()); + let aligned = asm.jcc8(Cond::E); + asm.ud2(); + asm.bind(aligned); } if displacement != 0 { - code.extend(ADD_RAX_IMM32); - code.extend(displacement.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Add, Size::Qword, displacement); } super::address_checks(code, checks, bytes, access); if granule && bytes != BYTE_BYTES { + let mut asm = code.asm(); if !aligned_sp { - code.extend(MOV_ECX_EAX); - code.extend(AND_ECX_IMM8); - code.push(ATOMIC_GRANULE_MASK); - code.extend(CMP_CL_IMM8); - code.push(ATOMIC_GRANULE_BYTES - bytes); - code.extend([JBE_REL8, UD2.len() as u8]); - code.extend(UD2); + asm.mov(Size::Dword, Gpr::Rcx, Gpr::Rax); + asm.alu_imm8(Alu::And, Size::Dword, Gpr::Rcx, ATOMIC_GRANULE_MASK as i8); + asm.alu_byte_imm(Alu::Cmp, Gpr::Rcx, ATOMIC_GRANULE_BYTES - bytes); + let within = asm.jcc8(Cond::Be); + asm.ud2(); + asm.bind(within); } else if displacement.rem_euclid(i32::from(ATOMIC_GRANULE_BYTES)) > i32::from(ATOMIC_GRANULE_BYTES - bytes) { - code.extend(UD2); + asm.ud2(); } } - code.extend(MOV_RDX_RAX); + code.asm().mov(Size::Qword, Gpr::Rdx, Gpr::Rax); } -fn input(code: &mut Vec, bytes: u8, register: Register, destination: InputRegister) { - let rcx = matches!(destination, InputRegister::Rcx); +/// The guest `register` at `bytes`, zero-extended, into `destination`. +fn input(code: &mut Code, bytes: u8, register: Register, destination: Gpr) { + let mut asm = code.asm(); let Some(displacement) = offset(register) else { - code.extend(if rcx { XOR_ECX_ECX } else { XOR_EAX_EAX }); + asm.alu(Alu::Xor, Size::Dword, destination, destination); return; }; - let modrm = if rcx { STATE_RCX } else { STATE_RAX }; + let state = Mem::base_disp32(Gpr::Rdi, displacement as i32); match bytes { - BYTE_BYTES => code.extend([TWO_BYTE_OPCODE, MOVZX_BYTE, modrm]), - HALFWORD_BYTES => code.extend([TWO_BYTE_OPCODE, MOVZX_HALFWORD, modrm]), - DWORD_BYTES => code.extend([MOV, modrm]), - QWORD_BYTES => code.extend([REX_PREFIX | REX_W_BIT, MOV, modrm]), - _ => unreachable!("decoder validates atomic widths"), + BYTE_BYTES | HALFWORD_BYTES => { + asm.movzx(Size::Dword, destination, size(bytes), state); + } + _ => asm.mov_load(size(bytes), destination, state), } - code.extend(displacement.to_le_bytes()); } -pub(super) fn input_rax(code: &mut Vec, bytes: u8, register: Register) { - input(code, bytes, register, InputRegister::Rax); +pub(super) fn input_rax(code: &mut Code, bytes: u8, register: Register) { + input(code, bytes, register, Gpr::Rax); } -pub(super) fn input_rcx(code: &mut Vec, bytes: u8, register: Register) { - input(code, bytes, register, InputRegister::Rcx); +pub(super) fn input_rcx(code: &mut Code, bytes: u8, register: Register) { + input(code, bytes, register, Gpr::Rcx); } /// [`input_rcx`] without changing the host flags: ZR is a MOV of zero. -pub(super) fn input_rcx_keeping_flags(code: &mut Vec, bytes: u8, register: Register) { +pub(super) fn input_rcx_keeping_flags(code: &mut Code, bytes: u8, register: Register) { if register == Register::Zero { - code.push(MOV_ECX_IMM32); - code.extend(0u32.to_le_bytes()); + code.asm().mov_imm32(Gpr::Rcx, 0); } else { input_rcx(code, bytes, register); } } /// [`input_rax`] without changing the host flags: ZR is a MOV of zero. -pub(super) fn input_rax_keeping_flags(code: &mut Vec, bytes: u8, register: Register) { +pub(super) fn input_rax_keeping_flags(code: &mut Code, bytes: u8, register: Register) { if register == Register::Zero { - code.push(MOV_EAX_IMM32); - code.extend(0u32.to_le_bytes()); + code.asm().mov_imm32(Gpr::Rax, 0); } else { input_rax(code, bytes, register); } } -pub(super) fn read_rax(code: &mut Vec, bytes: u8) { - read(code, bytes, 0); +pub(super) fn read_rax(code: &mut Code, bytes: u8) { + read(code, bytes, Gpr::Rax); } /// [RDX] at `bytes` into R8, zero-extended. -pub(super) fn read_r8(code: &mut Vec, bytes: u8) { - read(code, bytes, REX_R_BIT); +pub(super) fn read_r8(code: &mut Code, bytes: u8) { + read(code, bytes, Gpr::R8); } -fn read(code: &mut Vec, bytes: u8, rex: u8) { - let wide = if bytes == QWORD_BYTES { REX_W_BIT } else { 0 }; - if rex | wide != 0 { - code.push(REX_PREFIX | rex | wide); - } +fn read(code: &mut Code, bytes: u8, destination: Gpr) { + let mut asm = code.asm(); match bytes { - BYTE_BYTES => code.extend([TWO_BYTE_OPCODE, MOVZX_BYTE, RDX_ADDRESS]), - HALFWORD_BYTES => code.extend([TWO_BYTE_OPCODE, MOVZX_HALFWORD, RDX_ADDRESS]), - DWORD_BYTES | QWORD_BYTES => code.extend([MOV, RDX_ADDRESS]), - _ => unreachable!("decoder validates atomic widths"), + BYTE_BYTES | HALFWORD_BYTES => { + asm.movzx(Size::Dword, destination, size(bytes), ADDRESS); + } + _ => asm.mov_load(size(bytes), destination, ADDRESS), } } /// MOV of RCX's low `bytes` to [RDX]. -pub(super) fn store_rcx(code: &mut Vec, bytes: u8) { - match bytes { - HALFWORD_BYTES => code.push(OPERAND_SIZE_PREFIX), - QWORD_BYTES => code.push(REX_PREFIX | REX_W_BIT), - _ => {} - } - code.extend([ - if bytes == BYTE_BYTES { - MOV_STORE_BYTE - } else { - MOV_STORE - }, - RCX_RDX_MEMORY, - ]); +pub(super) fn store_rcx(code: &mut Code, bytes: u8) { + code.asm().mov_store(size(bytes), ADDRESS, Gpr::Rcx); } /// Input staging and exact-width updates keep the complete old value zero-extended. -pub(super) fn commit_rax(code: &mut Vec, bytes: u8, destination: Register) { +pub(super) fn commit_rax(code: &mut Code, bytes: u8, destination: Register) { debug_assert!(matches!( bytes, BYTE_BYTES | HALFWORD_BYTES | DWORD_BYTES | QWORD_BYTES @@ -240,25 +192,9 @@ pub(super) fn commit_rax(code: &mut Vec, bytes: u8, destination: Register) { store(code, destination); } -pub(super) fn locked_compare_exchange(code: &mut Vec, bytes: u8, source: ValueRegister) { - code.push(LOCK); - if bytes == HALFWORD_BYTES { - code.push(OPERAND_SIZE_PREFIX); - } - let extended = matches!(source, ValueRegister::R8); - let rex = - if bytes == QWORD_BYTES { REX_W_BIT } else { 0 } | if extended { REX_R_BIT } else { 0 }; - if rex != 0 { - code.push(REX_PREFIX | rex); - } - code.extend([ - TWO_BYTE_OPCODE, - if bytes == BYTE_BYTES { - CMPXCHG_BYTE - } else { - CMPXCHG_WIDER - }, - ]); - let source_low = u8::from(!extended); // RCX=1; R8's low register bits=0. - code.push((source_low << REGISTER_SHIFT) | RDX_ADDRESS); +/// `lock cmpxchg [rdx], source` at `bytes`. +pub(super) fn locked_compare_exchange(code: &mut Code, bytes: u8, source: Gpr) { + let mut asm = code.asm(); + asm.lock(); + asm.cmpxchg(size(bytes), ADDRESS, source); } diff --git a/crates/stela-compiler/src/x86_64/atomic/compare_exchange.rs b/crates/stela-compiler/src/x86_64/atomic/compare_exchange.rs index 7248ce5ce8..17ca3a6d52 100644 --- a/crates/stela-compiler/src/x86_64/atomic/compare_exchange.rs +++ b/crates/stela-compiler/src/x86_64/atomic/compare_exchange.rs @@ -1,28 +1,13 @@ //! CAS through a same-width LOCK CMPXCHG, or for a single agent a plain //! load, compare, CMOVNE and store ([`plain`]). use super::{ - QWORD_BYTES, REX_PREFIX, REX_W_BIT, ValueRegister, commit_rax, input_rax, input_rcx, - locked_compare_exchange, read_r8, store_rcx, + QWORD_BYTES, commit_rax, input_rax, input_rcx, locked_compare_exchange, read_r8, size, + store_rcx, }; use crate::aarch64::atomic::{Kind, Operand}; -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Size}; -const BYTE_BYTES: u8 = 1; -const HALFWORD_BYTES: u8 = 2; -const OPERAND_SIZE_PREFIX: u8 = 0x66; -const REX_R_BIT: u8 = 0x04; -const REX_B_BIT: u8 = 0x01; -const TWO_BYTE_OPCODE: u8 = 0x0f; -const CMP_BYTE: u8 = 0x38; -const CMP_WORD_OR_WIDER: u8 = 0x39; -const CMOVNE: u8 = 0x45; -const MOV_STORE: u8 = 0x89; -/// `eax, r8d` (CMP and MOV with REX.R). -const MODRM_RAX_R8: u8 = 0xc0; -/// `ecx, r8d` (CMOVNE with REX.B). -const MODRM_RCX_R8: u8 = 0xc8; - -pub(super) fn emit(code: &mut Vec, operand: &Operand, plain_access: bool) { +pub(super) fn emit(code: &mut Code, operand: &Operand, plain_access: bool) { let Kind::CompareExchange { compare, source } = operand.kind else { unreachable!("compare-exchange emitter receives a CAS operand"); }; @@ -33,7 +18,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, plain_access: bool) { if plain_access { plain(code, operand.bytes); } else { - locked_compare_exchange(code, operand.bytes, ValueRegister::Rcx); + locked_compare_exchange(code, operand.bytes, Gpr::Rcx); } // Narrow inputs already zero the accumulator's upper bits. Both success // and failure therefore return the zero-extended old value without another @@ -46,35 +31,24 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, plain_access: bool) { /// LOCK CMPXCHG writes back a failed comparison's old value (Arm permits a /// failed CAS to write, `Unpredictable_WRITEFAILEDCAS`). RAX then returns /// the old value. No branch, LOCK prefix or retry. -fn plain(code: &mut Vec, bytes: u8) { - let wide = if bytes == QWORD_BYTES { REX_W_BIT } else { 0 }; +fn plain(code: &mut Code, bytes: u8) { + let wide = Size::of(bytes == QWORD_BYTES); read_r8(code, bytes); - if bytes == HALFWORD_BYTES { - code.push(OPERAND_SIZE_PREFIX); - } - code.extend([ - REX_PREFIX | REX_R_BIT | wide, - if bytes == BYTE_BYTES { - CMP_BYTE - } else { - CMP_WORD_OR_WIDER - }, - MODRM_RAX_R8, - ]); - code.extend([ - REX_PREFIX | REX_B_BIT | wide, - TWO_BYTE_OPCODE, - CMOVNE, - MODRM_RCX_R8, - ]); + let mut asm = code.asm(); + asm.alu(Alu::Cmp, size(bytes), Gpr::Rax, Gpr::R8); + asm.cmov(Cond::Ne, wide, Gpr::Rcx, Gpr::R8); store_rcx(code, bytes); - code.extend([REX_PREFIX | REX_R_BIT | wide, MOV_STORE, MODRM_RAX_R8]); + code.asm().mov(wide, Gpr::Rax, Gpr::R8); } #[cfg(test)] mod tests { use super::*; use crate::aarch64::{Register, atomic::Order}; + use alloc::vec::Vec; + + const BYTE_BYTES: u8 = 1; + const HALFWORD_BYTES: u8 = 2; #[test] fn a_single_agent_cas_loads_compares_selects_and_stores() { @@ -121,7 +95,7 @@ mod tests { source: Register::X(2), }, }; - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, true); let expected: Vec = [load, compare, select, store, result].concat(); let at = code @@ -130,7 +104,7 @@ mod tests { .unwrap_or_else(|| panic!("{bytes}: {code:02x?}")); // Then only the commit of the old value to X1. assert_eq!(&code[at + expected.len()..], [0x48, 0x89, 0x87, 8, 0, 0, 0]); - let mut locked = Vec::new(); + let mut locked = Code::new(); emit(&mut locked, &operand, false); assert!(locked.contains(&0xf0) && !code.contains(&0xf0)); } diff --git a/crates/stela-compiler/src/x86_64/atomic/compare_exchange_pair.rs b/crates/stela-compiler/src/x86_64/atomic/compare_exchange_pair.rs index f2435cad2d..f4b4de4714 100644 --- a/crates/stela-compiler/src/x86_64/atomic/compare_exchange_pair.rs +++ b/crates/stela-compiler/src/x86_64/atomic/compare_exchange_pair.rs @@ -1,9 +1,10 @@ //! CASP through same-width atomic updates (CMPXCHG8B/CMPXCHG16B), or for a //! single agent a plain load, compare, CMOVNE and store. use super::{ - DWORD_BYTES, QWORD_BYTES, ValueRegister, XOR_EAX_EAX, XOR_ECX_ECX, commit_rax, input_rax, - input_rax_keeping_flags, input_rcx, input_rcx_keeping_flags, locked_compare_exchange, + ADDRESS, DWORD_BYTES, QWORD_BYTES, commit_rax, input_rax, input_rax_keeping_flags, input_rcx, + input_rcx_keeping_flags, locked_compare_exchange, }; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, ShiftOp, Size}; use crate::{ TargetCpu, aarch64::{ @@ -11,50 +12,16 @@ use crate::{ atomic::{Kind, Operand}, }, }; -use alloc::vec::Vec; +use Gpr::{R8, R9, Rax, Rbx, Rcx, Rdx}; +use Size::{Dword, Qword}; const WORD_PAIR_BYTES: u8 = 2 * DWORD_BYTES; const DOUBLEWORD_PAIR_BYTES: u8 = 2 * QWORD_BYTES; const WORD_BITS: u8 = 32; -const SHL_RCX_WORD_BITS: &[u8] = &[0x48, 0xc1, 0xe1, WORD_BITS]; -const SHR_RCX_WORD_BITS: &[u8] = &[0x48, 0xc1, 0xe9, WORD_BITS]; -const OR_RAX_RCX: &[u8] = &[0x48, 0x09, 0xc8]; -const OR_RCX_R8: &[u8] = &[0x4c, 0x09, 0xc1]; -const MOV_R8_RCX: &[u8] = &[0x49, 0x89, 0xc8]; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const MOV_EAX_EAX: &[u8] = &[0x89, 0xc0]; -const MOV_RAX_RCX: &[u8] = &[0x48, 0x89, 0xc8]; -const MOV_R8_RDX: &[u8] = &[0x49, 0x89, 0xd0]; -const MOV_R9_RBX: &[u8] = &[0x49, 0x89, 0xd9]; -const MOV_RDX_RCX: &[u8] = &[0x48, 0x89, 0xca]; -const MOV_RBX_RCX: &[u8] = &[0x48, 0x89, 0xcb]; -const MOV_EDX_ECX: &[u8] = &[0x89, 0xca]; -const MOV_EBX_ECX: &[u8] = &[0x89, 0xcb]; -const MOV_EAX_EDX: &[u8] = &[0x89, 0xd0]; -const MOV_RBX_R9: &[u8] = &[0x4c, 0x89, 0xcb]; -const MOV_RAX_RDX: &[u8] = &[0x48, 0x89, 0xd0]; -const XOR_EDX_EDX: &[u8] = &[0x31, 0xd2]; -const XOR_EBX_EBX: &[u8] = &[0x31, 0xdb]; -const LOCK_XADD_RDX_RAX: &[u8] = &[0xf0, 0x48, 0x0f, 0xc1, 0x02]; -const LOCK_CMPXCHG8B_R8: &[u8] = &[0xf0, 0x41, 0x0f, 0xc7, 0x08]; -const LOCK_CMPXCHG16B_R8: &[u8] = &[0xf0, 0x49, 0x0f, 0xc7, 0x08]; -const MOV_R8_RDX_MEMORY: &[u8] = &[0x4c, 0x8b, 0x02]; -const MOV_R9_RDX_MEMORY: &[u8] = &[0x4c, 0x8b, 0x0a]; -/// `mov r9, [rdx+8]`: the high doubleword. -const MOV_R9_RDX_HIGH_MEMORY: &[u8] = &[0x4c, 0x8b, 0x4a, QWORD_BYTES]; -const MOV_RDX_MEMORY_RAX: &[u8] = &[0x48, 0x89, 0x02]; -const MOV_RDX_MEMORY_RCX: &[u8] = &[0x48, 0x89, 0x0a]; -/// `mov [rdx+8], rcx`. -const MOV_RDX_HIGH_MEMORY_RCX: &[u8] = &[0x48, 0x89, 0x4a, QWORD_BYTES]; -const MOV_RAX_R8: &[u8] = &[0x4c, 0x89, 0xc0]; -const MOV_RAX_R9: &[u8] = &[0x4c, 0x89, 0xc8]; -const CMP_RAX_R9: &[u8] = &[0x4c, 0x39, 0xc8]; -const XOR_RAX_R8: &[u8] = &[0x4c, 0x31, 0xc0]; -const XOR_RCX_R9: &[u8] = &[0x4c, 0x31, 0xc9]; -const CMOVNE_RAX_R8: &[u8] = &[0x49, 0x0f, 0x45, 0xc0]; -const CMOVNE_RCX_R9: &[u8] = &[0x49, 0x0f, 0x45, 0xc9]; +/// `[rdx+8]`: the high doubleword. +const HIGH_ADDRESS: Mem = Mem::base(Rdx, QWORD_BYTES as i32); -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu, plain: bool) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu, plain: bool) { let Kind::CompareExchangePair { compare, source } = operand.kind else { unreachable!("pair compare-exchange emitter receives a CASP operand"); }; @@ -69,24 +36,26 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu, pla } /// Pack the compare pair into RAX and the new pair into RCX, low word first. -fn pack_word_pairs(code: &mut Vec, compare: [Register; 2], source: [Register; 2]) { +fn pack_word_pairs(code: &mut Code, compare: [Register; 2], source: [Register; 2]) { input_rax(code, DWORD_BYTES, compare[0]); if compare[1] != Register::Zero { input_rcx(code, DWORD_BYTES, compare[1]); - code.extend(SHL_RCX_WORD_BITS); - code.extend(OR_RAX_RCX); + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shl, Qword, Rcx, WORD_BITS); + asm.alu(Alu::Or, Qword, Rax, Rcx); } input_rcx(code, DWORD_BYTES, source[0]); if source[1] != Register::Zero { - code.extend(MOV_R8_RCX); + code.asm().mov(Qword, R8, Rcx); input_rcx(code, DWORD_BYTES, source[1]); - code.extend(SHL_RCX_WORD_BITS); - code.extend(OR_RCX_R8); + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shl, Qword, Rcx, WORD_BITS); + asm.alu(Alu::Or, Qword, Rcx, R8); } } fn word_pair( - code: &mut Vec, + code: &mut Code, compare: [Register; 2], source: [Register; 2], target: TargetCpu, @@ -98,16 +67,19 @@ fn word_pair( // (Arm `Unpredictable_WRITEFAILEDCAS`). The load comes first, so a // read that would fault reports WnR 0. pack_word_pairs(code, compare, source); - code.extend(MOV_R9_RDX_MEMORY); - code.extend(CMP_RAX_R9); - code.extend(CMOVNE_RCX_R9); - code.extend(MOV_RDX_MEMORY_RCX); - code.extend(MOV_RAX_R9); + let mut asm = code.asm(); + asm.mov_load(Qword, R9, ADDRESS); + asm.alu(Alu::Cmp, Qword, Rax, R9); + asm.cmov(Cond::Ne, Qword, Rcx, R9); + asm.mov_store(Qword, ADDRESS, Rcx); + asm.mov(Qword, Rax, R9); } else if source == compare { // Equal compare/new pairs always leave RAM unchanged. XADD of zero still // checks write permission and atomically returns the complete old pair. - code.extend(XOR_EAX_EAX); - code.extend(LOCK_XADD_RDX_RAX); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Dword, Rax, Rax); + asm.lock(); + asm.xadd(Qword, ADDRESS, Rax); } else if target.supports(TargetCpu::Cx8) && compare[1] != Register::Zero && source[1] != Register::Zero @@ -116,41 +88,45 @@ fn word_pair( return; } else { pack_word_pairs(code, compare, source); - locked_compare_exchange(code, QWORD_BYTES, ValueRegister::Rcx); + locked_compare_exchange(code, QWORD_BYTES, Rcx); } commit_word_pair(code, compare); } -fn commit_word_pair(code: &mut Vec, compare: [Register; 2]) { +fn commit_word_pair(code: &mut Code, compare: [Register; 2]) { // Preserve the upper old word before normalizing and committing the lower // word. Both returned W values independently zero-extend into their X slots. + let mut asm = code.asm(); if compare[1] != Register::Zero { - code.extend(MOV_RCX_RAX); - code.extend(SHR_RCX_WORD_BITS); + asm.mov(Qword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, Qword, Rcx, WORD_BITS); } - code.extend(MOV_EAX_EAX); + asm.mov(Dword, Rax, Rax); commit_rax(code, DWORD_BYTES, compare[0]); if compare[1] != Register::Zero { - code.extend(MOV_RAX_RCX); + code.asm().mov(Qword, Rax, Rcx); commit_rax(code, DWORD_BYTES, compare[1]); } } -fn word_pair_cx8(code: &mut Vec, compare: [Register; 2], source: [Register; 2]) { - code.extend(MOV_R8_RDX); +fn word_pair_cx8(code: &mut Code, compare: [Register; 2], source: [Register; 2]) { + code.asm().mov(Qword, R8, Rdx); input_rax(code, DWORD_BYTES, compare[0]); input_rcx(code, DWORD_BYTES, compare[1]); - code.extend(MOV_EDX_ECX); - code.extend(MOV_R9_RBX); + let mut asm = code.asm(); + asm.mov(Dword, Rdx, Rcx); + asm.mov(Qword, R9, Rbx); input_rcx(code, DWORD_BYTES, source[0]); - code.extend(MOV_EBX_ECX); + code.asm().mov(Dword, Rbx, Rcx); input_rcx(code, DWORD_BYTES, source[1]); - code.extend(LOCK_CMPXCHG8B_R8); - code.extend(MOV_RBX_R9); + let mut asm = code.asm(); + asm.lock(); + asm.cmpxchg8b(Mem::base(R8, 0)); + asm.mov(Qword, Rbx, R9); // Every input half is zero-extended. Failed CX8 writes EAX/EDX, while success // retains those staged halves, so both paths return complete W results. commit_rax(code, DWORD_BYTES, compare[0]); - code.extend(MOV_EAX_EDX); + code.asm().mov(Dword, Rax, Rdx); commit_rax(code, DWORD_BYTES, compare[1]); } @@ -161,54 +137,60 @@ fn word_pair_cx8(code: &mut Vec, compare: [Register; 2], source: [Register; /// failed comparison's old value (Arm `Unpredictable_WRITEFAILEDCAS`). The /// pair is 16-byte aligned, so both halves are in one page. No CMPXCHG16B, /// and RBX stays the host's. -fn plain_doubleword_pair(code: &mut Vec, compare: [Register; 2], source: [Register; 2]) { - code.extend(MOV_R8_RDX_MEMORY); - code.extend(MOV_R9_RDX_HIGH_MEMORY); +fn plain_doubleword_pair(code: &mut Code, compare: [Register; 2], source: [Register; 2]) { + let mut asm = code.asm(); + asm.mov_load(Qword, R8, ADDRESS); + asm.mov_load(Qword, R9, HIGH_ADDRESS); input_rax(code, QWORD_BYTES, compare[0]); input_rcx(code, QWORD_BYTES, compare[1]); - code.extend(XOR_RAX_R8); - code.extend(XOR_RCX_R9); - code.extend(OR_RAX_RCX); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Qword, Rax, R8); + asm.alu(Alu::Xor, Qword, Rcx, R9); + asm.alu(Alu::Or, Qword, Rax, Rcx); input_rax_keeping_flags(code, QWORD_BYTES, source[0]); input_rcx_keeping_flags(code, QWORD_BYTES, source[1]); - code.extend(CMOVNE_RAX_R8); - code.extend(CMOVNE_RCX_R9); - code.extend(MOV_RDX_MEMORY_RAX); - code.extend(MOV_RDX_HIGH_MEMORY_RCX); - code.extend(MOV_RAX_R8); + let mut asm = code.asm(); + asm.cmov(Cond::Ne, Qword, Rax, R8); + asm.cmov(Cond::Ne, Qword, Rcx, R9); + asm.mov_store(Qword, ADDRESS, Rax); + asm.mov_store(Qword, HIGH_ADDRESS, Rcx); + asm.mov(Qword, Rax, R8); commit_rax(code, QWORD_BYTES, compare[0]); if compare[1] != Register::Zero { - code.extend(MOV_RAX_R9); + code.asm().mov(Qword, Rax, R9); commit_rax(code, QWORD_BYTES, compare[1]); } } -fn doubleword_pair(code: &mut Vec, compare: [Register; 2], source: [Register; 2]) { - code.extend(MOV_R8_RDX); +fn doubleword_pair(code: &mut Code, compare: [Register; 2], source: [Register; 2]) { + code.asm().mov(Qword, R8, Rdx); if source == compare { - code.extend(MOV_R9_RBX); + let mut asm = code.asm(); + asm.mov(Qword, R9, Rbx); // CAS128(0, 0) never changes RAM and always returns the old 128 bits, // even when the pair comparison would have succeeded. - code.extend(XOR_EAX_EAX); - code.extend(XOR_EDX_EDX); - code.extend(XOR_EBX_EBX); - code.extend(XOR_ECX_ECX); + for register in [Rax, Rdx, Rbx, Rcx] { + asm.alu(Alu::Xor, Dword, register, register); + } } else { input_rax(code, QWORD_BYTES, compare[0]); input_rcx(code, QWORD_BYTES, compare[1]); - code.extend(MOV_RDX_RCX); - code.extend(MOV_R9_RBX); + let mut asm = code.asm(); + asm.mov(Qword, Rdx, Rcx); + asm.mov(Qword, R9, Rbx); input_rcx(code, QWORD_BYTES, source[0]); - code.extend(MOV_RBX_RCX); + code.asm().mov(Qword, Rbx, Rcx); input_rcx(code, QWORD_BYTES, source[1]); } - code.extend(LOCK_CMPXCHG16B_R8); + let mut asm = code.asm(); + asm.lock(); + asm.cmpxchg16b(Mem::base(R8, 0)); // Restore the host callee-saved register immediately after the only guest // memory access. Target faults occur before either compare-pair commit. - code.extend(MOV_RBX_R9); + asm.mov(Qword, Rbx, R9); commit_rax(code, QWORD_BYTES, compare[0]); if compare[1] != Register::Zero { - code.extend(MOV_RAX_RDX); + code.asm().mov(Qword, Rax, Rdx); commit_rax(code, QWORD_BYTES, compare[1]); } } @@ -217,6 +199,25 @@ fn doubleword_pair(code: &mut Vec, compare: [Register; 2], source: [Register mod tests { use super::*; use crate::aarch64::atomic::Order; + use alloc::vec::Vec; + + const OR_RAX_RCX: &[u8] = &[0x48, 0x09, 0xc8]; + const MOV_R9_RBX: &[u8] = &[0x49, 0x89, 0xd9]; + const MOV_RBX_R9: &[u8] = &[0x4c, 0x89, 0xcb]; + const LOCK_CMPXCHG16B_R8: &[u8] = &[0xf0, 0x49, 0x0f, 0xc7, 0x08]; + const MOV_R8_RDX_MEMORY: &[u8] = &[0x4c, 0x8b, 0x02]; + const MOV_R9_RDX_MEMORY: &[u8] = &[0x4c, 0x8b, 0x0a]; + const MOV_R9_RDX_HIGH_MEMORY: &[u8] = &[0x4c, 0x8b, 0x4a, 8]; + const MOV_RDX_MEMORY_RAX: &[u8] = &[0x48, 0x89, 0x02]; + const MOV_RDX_MEMORY_RCX: &[u8] = &[0x48, 0x89, 0x0a]; + const MOV_RDX_HIGH_MEMORY_RCX: &[u8] = &[0x48, 0x89, 0x4a, 8]; + const MOV_RAX_R8: &[u8] = &[0x4c, 0x89, 0xc0]; + const MOV_RAX_R9: &[u8] = &[0x4c, 0x89, 0xc8]; + const CMP_RAX_R9: &[u8] = &[0x4c, 0x39, 0xc8]; + const XOR_RAX_R8: &[u8] = &[0x4c, 0x31, 0xc0]; + const XOR_RCX_R9: &[u8] = &[0x4c, 0x31, 0xc9]; + const CMOVNE_RAX_R8: &[u8] = &[0x49, 0x0f, 0x45, 0xc0]; + const CMOVNE_RCX_R9: &[u8] = &[0x49, 0x0f, 0x45, 0xc9]; fn pair(bytes: u8, compare: [Register; 2], source: [Register; 2], plain: bool) -> Vec { let operand = Operand { @@ -225,9 +226,9 @@ mod tests { order: Order::AcquireRelease, kind: Kind::CompareExchangePair { compare, source }, }; - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, TargetCpu::detect(), plain); - code + code.into_bytes() } fn has(code: &[u8], bytes: &[u8]) -> bool { @@ -242,7 +243,7 @@ mod tests { let word_recipe = [ MOV_R9_RDX_MEMORY, CMP_RAX_R9, - CMOVNE_RCX_R9, + &[0x49, 0x0f, 0x45, 0xc9], MOV_RDX_MEMORY_RCX, MOV_RAX_R9, ] diff --git a/crates/stela-compiler/src/x86_64/atomic/read_modify_write.rs b/crates/stela-compiler/src/x86_64/atomic/read_modify_write.rs index 3e1535f9ef..5a726bb6a4 100644 --- a/crates/stela-compiler/src/x86_64/atomic/read_modify_write.rs +++ b/crates/stela-compiler/src/x86_64/atomic/read_modify_write.rs @@ -2,55 +2,16 @@ //! CMPXCHG retry loop. The old value is written only after the update succeeds. //! For a single agent or PSTATE.DIT they are a plain load, update and store //! ([`plain`]). -use super::{ValueRegister, commit_rax, input_rax, input_rcx, locked_compare_exchange, read_rax}; +use super::{ + ADDRESS, QWORD_BYTES, commit_rax, input_rax, input_rcx, locked_compare_exchange, read_rax, size, +}; use crate::aarch64::{ Register, atomic::{Kind, Operand, Rmw}, }; -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Size, Unary, resolve}; -const BYTE_BYTES: u8 = 1; -const HALFWORD_BYTES: u8 = 2; -const DWORD_BYTES: u8 = 4; -const QWORD_BYTES: u8 = 8; -const LOCK: u8 = 0xf0; -const OPERAND_SIZE_PREFIX: u8 = 0x66; -const REX_W_PREFIX: u8 = 0x48; -const REX_R_PREFIX: u8 = 0x44; -const REX_B_PREFIX: u8 = 0x41; -const REX_W_BIT: u8 = 0x08; -const OPCODE_ESCAPE: u8 = 0x0f; -const MODRM_RDX_RAX: u8 = 0x02; -const MODRM_RDX_RCX: u8 = 0x0a; -const MODRM_R8_RCX: u8 = 0xc1; -/// `[rdx], r8` under REX.R. -const MODRM_RDX_R8: u8 = 0x02; -const MOV_BYTE: u8 = 0x88; -const MOV_WORD_OR_WIDER: u8 = 0x89; -const ADD_BYTE: u8 = 0x00; -const ADD_WORD_OR_WIDER: u8 = 0x01; -const OR_BYTE: u8 = 0x08; -const OR_WORD_OR_WIDER: u8 = 0x09; -const AND_BYTE: u8 = 0x20; -const AND_WORD_OR_WIDER: u8 = 0x21; -const XOR_BYTE: u8 = 0x30; -const XOR_WORD_OR_WIDER: u8 = 0x31; -const CMP_BYTE: u8 = 0x38; -const CMP_WORD_OR_WIDER: u8 = 0x39; -const XCHG_BYTE: u8 = 0x86; -const XCHG_WORD_OR_WIDER: u8 = 0x87; -const XADD_BYTE: u8 = 0xc0; -const XADD_WORD_OR_WIDER: u8 = 0xc1; -const CMOVB: u8 = 0x42; -const CMOVA: u8 = 0x47; -const CMOVL: u8 = 0x4c; -const CMOVG: u8 = 0x4f; -const JNE_REL8: u8 = 0x75; -const MOV_R8_EAX_OPERANDS: &[u8] = &[0x89, 0xc0]; -const NOT_ECX: &[u8] = &[0xf7, 0xd1]; -const MODRM_EAX_ECX: u8 = 0xc8; - -pub(super) fn emit(code: &mut Vec, operand: &Operand, plain_access: bool) { +pub(super) fn emit(code: &mut Code, operand: &Operand, plain_access: bool) { let Kind::ReadModifyWrite { operation, source, @@ -78,8 +39,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, plain_access: bool) { } input_rcx(code, operand.bytes, source); if operation == Rmw::Clear { - wide_prefix(code, operand.bytes); - code.extend(NOT_ECX); + invert_rcx(code, operand.bytes); } if destination == Register::Zero && matches!(operation, Rmw::Clear | Rmw::Xor | Rmw::Set) { direct(code, operand.bytes, operation, true); @@ -89,6 +49,16 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, plain_access: bool) { } } +/// The 32- or 64-bit size that holds a `bytes`-wide value. +const fn register_size(bytes: u8) -> Size { + Size::of(bytes == QWORD_BYTES) +} + +/// `not ecx` or `not rcx`: the operand LDCLR clears with. +fn invert_rcx(code: &mut Code, bytes: u8) { + code.asm().unary(Unary::Not, register_size(bytes), Gpr::Rcx); +} + /// The single-agent and data-independent-timing lowering: load the old value /// into RAX, form the new one in R8 with MOV, ADD, AND (of the inverted /// operand), XOR, OR, or CMP and CMOVcc, store it, then commit the old value. @@ -101,156 +71,104 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, plain_access: bool) { /// first, so an address a read would fault on faults there with WnR 0 and a /// read-only one at the store with WnR 1, as Arm requires of an atomic that /// both reads and writes; nothing is committed before the store completes. -fn plain(code: &mut Vec, bytes: u8, operation: Rmw, source: Register, destination: Register) { +fn plain(code: &mut Code, bytes: u8, operation: Rmw, source: Register, destination: Register) { input_rcx(code, bytes, source); if operation == Rmw::Clear { - wide_prefix(code, bytes); - code.extend(NOT_ECX); + invert_rcx(code, bytes); } read_rax(code, bytes); - extended_prefix(code, bytes, REX_B_PREFIX); - code.extend(MOV_R8_EAX_OPERANDS); + let wide = register_size(bytes); + code.asm().mov(wide, Gpr::R8, Gpr::Rax); match operation { Rmw::SignedMax | Rmw::SignedMin | Rmw::UnsignedMax | Rmw::UnsignedMin => { select_min_max(code, bytes, operation); } - Rmw::Swap | Rmw::Add | Rmw::Clear | Rmw::Xor | Rmw::Set => { - extended_prefix(code, bytes, REX_B_PREFIX); - code.extend([ - match operation { - Rmw::Swap => MOV_WORD_OR_WIDER, - Rmw::Add => ADD_WORD_OR_WIDER, - Rmw::Clear => AND_WORD_OR_WIDER, - Rmw::Xor => XOR_WORD_OR_WIDER, - _ => OR_WORD_OR_WIDER, - }, - MODRM_EAX_ECX, - ]); + Rmw::Swap => code.asm().mov(wide, Gpr::R8, Gpr::Rcx), + Rmw::Add | Rmw::Clear | Rmw::Xor | Rmw::Set => { + code.asm().alu(alu(operation), wide, Gpr::R8, Gpr::Rcx); } } - if bytes == HALFWORD_BYTES { - code.push(OPERAND_SIZE_PREFIX); - } - extended_prefix(code, bytes, REX_R_PREFIX); - code.extend([ - if bytes == BYTE_BYTES { - MOV_BYTE - } else { - MOV_WORD_OR_WIDER - }, - MODRM_RDX_R8, - ]); + code.asm().mov_store(size(bytes), ADDRESS, Gpr::R8); commit_rax(code, bytes, destination); } -fn wide_prefix(code: &mut Vec, bytes: u8) { - if bytes == QWORD_BYTES { - code.push(REX_W_PREFIX); +/// The x86 ALU operation of an LDADD, LDCLR (of the inverted operand), LDEOR +/// or LDSET. +fn alu(operation: Rmw) -> Alu { + match operation { + Rmw::Add => Alu::Add, + Rmw::Clear => Alu::And, + Rmw::Xor => Alu::Xor, + Rmw::Set => Alu::Or, + _ => unreachable!("swap and min/max have no ALU form"), } } -fn width_prefix(code: &mut Vec, bytes: u8) { - match bytes { - HALFWORD_BYTES => code.push(OPERAND_SIZE_PREFIX), - QWORD_BYTES => code.push(REX_W_PREFIX), - BYTE_BYTES | DWORD_BYTES => {} - _ => unreachable!("decoder validates scalar atomic width"), - } -} - -fn extended_prefix(code: &mut Vec, bytes: u8, extension: u8) { - code.push(extension | if bytes == QWORD_BYTES { REX_W_BIT } else { 0 }); -} - -fn direct(code: &mut Vec, bytes: u8, operation: Rmw, discard: bool) { - if operation != Rmw::Swap { - code.push(LOCK); - } - width_prefix(code, bytes); - let (byte, wider) = match operation { - Rmw::Swap => (XCHG_BYTE, XCHG_WORD_OR_WIDER), +fn direct(code: &mut Code, bytes: u8, operation: Rmw, discard: bool) { + let size = size(bytes); + let mut asm = code.asm(); + match operation { + Rmw::Swap => asm.xchg(size, ADDRESS, Gpr::Rax), Rmw::Add if !discard => { - code.push(OPCODE_ESCAPE); - (XADD_BYTE, XADD_WORD_OR_WIDER) + asm.lock(); + asm.xadd(size, ADDRESS, Gpr::Rax); + } + Rmw::Add => { + asm.lock(); + asm.alu(Alu::Add, size, ADDRESS, Gpr::Rax); + } + Rmw::Clear | Rmw::Xor | Rmw::Set => { + asm.lock(); + asm.alu(alu(operation), size, ADDRESS, Gpr::Rcx); } - Rmw::Add => (ADD_BYTE, ADD_WORD_OR_WIDER), - Rmw::Clear => (AND_BYTE, AND_WORD_OR_WIDER), - Rmw::Xor => (XOR_BYTE, XOR_WORD_OR_WIDER), - Rmw::Set => (OR_BYTE, OR_WORD_OR_WIDER), _ => unreachable!("min/max uses the shared compare-exchange retry"), - }; - code.extend([ - if bytes == BYTE_BYTES { byte } else { wider }, - if matches!(operation, Rmw::Swap | Rmw::Add) { - MODRM_RDX_RAX - } else { - MODRM_RDX_RCX - }, - ]); + } } -fn retry(code: &mut Vec, bytes: u8, operation: Rmw) { +fn retry(code: &mut Code, bytes: u8, operation: Rmw) { read_rax(code, bytes); let repeat = code.len(); // Failed narrow CMPXCHG replaces AL/AX, retaining the zero upper bits from // the initial exact-width read. R8 holds proposed data; RAX stays old data. - extended_prefix(code, bytes, REX_B_PREFIX); - code.extend(MOV_R8_EAX_OPERANDS); + let wide = register_size(bytes); + code.asm().mov(wide, Gpr::R8, Gpr::Rax); match operation { Rmw::Clear | Rmw::Xor | Rmw::Set => { - extended_prefix(code, bytes, REX_B_PREFIX); - code.extend([ - match operation { - Rmw::Clear => AND_WORD_OR_WIDER, - Rmw::Xor => XOR_WORD_OR_WIDER, - Rmw::Set => OR_WORD_OR_WIDER, - _ => unreachable!(), - }, - MODRM_EAX_ECX, - ]); + code.asm().alu(alu(operation), wide, Gpr::R8, Gpr::Rcx); } Rmw::SignedMax | Rmw::SignedMin | Rmw::UnsignedMax | Rmw::UnsignedMin => { select_min_max(code, bytes, operation); } _ => unreachable!("direct instructions handle swap and addition"), } - locked_compare_exchange(code, bytes, ValueRegister::R8); - code.push(JNE_REL8); - let displacement = i8::try_from(repeat as isize - (code.len() + size_of::()) as isize) - .expect("bounded scalar atomic retry body"); - code.extend(displacement.to_le_bytes()); + locked_compare_exchange(code, bytes, Gpr::R8); + let again = code.asm().jcc8(Cond::Ne); + resolve(code, again, repeat); } -fn select_min_max(code: &mut Vec, bytes: u8, operation: Rmw) { - width_prefix(code, bytes); - code.extend([ - if bytes == BYTE_BYTES { - CMP_BYTE - } else { - CMP_WORD_OR_WIDER - }, - MODRM_EAX_ECX, - ]); +fn select_min_max(code: &mut Code, bytes: u8, operation: Rmw) { + let mut asm = code.asm(); + asm.alu(Alu::Cmp, size(bytes), Gpr::Rax, Gpr::Rcx); // Byte/halfword CMP supplies signed flags at the guest width. CMOV may use // 32 bits because CMPXCHG consumes only the selected low guest-width bits. - extended_prefix(code, bytes, REX_R_PREFIX); - code.extend([ - OPCODE_ESCAPE, - match operation { - Rmw::SignedMax => CMOVL, - Rmw::SignedMin => CMOVG, - Rmw::UnsignedMax => CMOVB, - Rmw::UnsignedMin => CMOVA, - _ => unreachable!("selector accepts only min/max operations"), - }, - MODRM_R8_RCX, - ]); + let keep = match operation { + Rmw::SignedMax => Cond::L, + Rmw::SignedMin => Cond::G, + Rmw::UnsignedMax => Cond::B, + Rmw::UnsignedMin => Cond::A, + _ => unreachable!("selector accepts only min/max operations"), + }; + asm.cmov(keep, register_size(bytes), Gpr::R8, Gpr::Rcx); } #[cfg(test)] mod tests { use super::*; + const BYTE_BYTES: u8 = 1; + const HALFWORD_BYTES: u8 = 2; + const DWORD_BYTES: u8 = 4; + const LOCK: u8 = 0xf0; const OPERATIONS: [Rmw; 9] = [ Rmw::Add, Rmw::Clear, @@ -286,7 +204,7 @@ mod tests { }; for ((bytes, load), (_, store)) in loads.into_iter().zip(stores) { for operation in OPERATIONS { - let mut code = Vec::new(); + let mut code = Code::new(); plain(&mut code, bytes, operation, Register::X(1), Register::X(2)); // X1 and X2 sit at frame offsets 8 and 16, so no other byte // is a LOCK prefix or a conditional jump. @@ -302,7 +220,7 @@ mod tests { } } // A ZR destination performs the access and commits nothing. - let mut code = Vec::new(); + let mut code = Code::new(); plain( &mut code, DWORD_BYTES, diff --git a/crates/stela-compiler/src/x86_64/bitfield.rs b/crates/stela-compiler/src/x86_64/bitfield.rs index 7ea1d81d2a..132c189272 100644 --- a/crates/stela-compiler/src/x86_64/bitfield.rs +++ b/crates/stela-compiler/src/x86_64/bitfield.rs @@ -1,21 +1,24 @@ //! Bitfield moves using shifts and masks. Guest NZCV is untouched. use super::{Register, Shift, Width, load, right_operand, store}; use crate::aarch64::bitfield::{Kind, Operand}; -use alloc::vec::Vec; +use crate::x86_64::asm::{ + Alu, Code, + Gpr::{Rax, Rcx, Rdx}, + ShiftOp, Size, +}; -fn shift(code: &mut Vec, width: Width, opcode: u8, amount: u8) { +/// `op (e/r)ax,amount`, or nothing for a zero amount. +fn shift(code: &mut Code, width: Width, op: ShiftOp, amount: u8) { if amount != 0 { - if width == Width::X64 { - code.push(0x48); - } - code.extend([0xc1, opcode, amount]); + code.asm() + .shift_imm(op, Size::of(width == Width::X64), Rax, amount); } } -pub(super) fn emit(code: &mut Vec, operand: &Operand) { +pub(super) fn emit(code: &mut Code, operand: &Operand) { if operand.destination == Register::Zero { // Discarding a result must still own a nonempty source-map interval. - code.push(0x90); + code.asm().nop(); return; } let bits = match operand.width { @@ -32,7 +35,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { load(code, operand.source); if operand.width == Width::W32 { // Required even when both shifts are absent (the full-width MOV alias). - code.extend([0x89, 0xc0]); // mov eax,eax + code.asm().mov(Size::Dword, Rax, Rax); } // Move the source field to the operand's MSB, then extract it. Arithmetic // extraction replicates source[imms], including wrapping SBFIZ aliases. @@ -41,36 +44,34 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { shift( code, operand.width, - 0xe0, // shl (e/r)ax,imm8 + ShiftOp::Shl, bits - source_shift - field_width, ); shift( code, operand.width, if operand.kind == Kind::Signed { - 0xf8 // sar (e/r)ax,imm8 + ShiftOp::Sar } else { - 0xe8 // shr (e/r)ax,imm8 + ShiftOp::Shr }, bits - field_width, ); - shift(code, operand.width, 0xe0, destination_shift); + shift(code, operand.width, ShiftOp::Shl, destination_shift); if operand.kind == Kind::Insert { let field_mask = (u64::MAX >> (64 - field_width)) << destination_shift; // Nothing has been written yet, so source and destination may alias. // RCX receives the old destination after the source is staged. right_operand(code, operand.destination, Width::X64, Shift::Lsl, 0); + let mut asm = code.asm(); if operand.width == Width::X64 { - code.extend([0x48, 0xba]); // movabs rdx,~field_mask - code.extend((!field_mask).to_le_bytes()); - code.extend([0x48, 0x21, 0xd1]); // and rcx,rdx - code.push(0x48); + asm.mov_imm64(Rdx, !field_mask); + asm.alu(Alu::And, Size::Qword, Rcx, Rdx); } else { - code.extend([0x81, 0xe1]); // and ecx,imm32 - code.extend((!(field_mask as u32)).to_le_bytes()); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, !(field_mask as u32) as i32); } - code.extend([0x09, 0xc8]); // or (e/r)ax,(e/r)cx + asm.alu(Alu::Or, Size::of(operand.width == Width::X64), Rax, Rcx); } store(code, operand.destination); } @@ -78,11 +79,11 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { #[cfg(test)] mod tests { use super::*; - use alloc::vec; + use alloc::vec::Vec; fn code(width: Width, kind: Kind, rotation: u8, mask_end: u8) -> Vec { - let mut result = vec![]; + let mut result = Code::new(); emit( &mut result, &Operand { @@ -94,7 +95,7 @@ mod tests { mask_end, }, ); - result + result.into_bytes() } #[test] @@ -168,7 +169,7 @@ mod tests { #[test] fn aliased_insert_stages_both_original_operands_before_the_only_state_store() { - let mut emitted = vec![]; + let mut emitted = Code::new(); emit( &mut emitted, &Operand { @@ -207,7 +208,7 @@ mod tests { rotation: 0, mask_end: 63, }; - let mut emitted = vec![]; + let mut emitted = Code::new(); emit(&mut emitted, &operand); assert_eq!(&emitted[..2], [0x31, 0xc0]); operand.destination = Register::Zero; @@ -219,8 +220,8 @@ mod tests { .into_iter() .flat_map(u32::to_le_bytes) .collect(); - let leaf = crate::compile(&source, crate::GuestAddress(0x100000)).unwrap(); - let block = crate::block::compile(&source, crate::GuestAddress(0x100000)).unwrap(); + let leaf = crate::testing::leaf(&source, crate::GuestAddress(0x100000)).unwrap(); + let block = crate::testing::block(&source, crate::GuestAddress(0x100000)).unwrap(); for native in [&leaf, &block.native] { assert_eq!( native.source_map, diff --git a/crates/stela-compiler/src/x86_64/block.rs b/crates/stela-compiler/src/x86_64/block.rs index 0da60e3743..e3bd637ed9 100644 --- a/crates/stela-compiler/src/x86_64/block.rs +++ b/crates/stela-compiler/src/x86_64/block.rs @@ -1,4 +1,5 @@ //! Block control transfers: every branch returns to the dispatcher. +use crate::x86_64::asm::{Asm, Code, Cond, Gpr, Size}; use alloc::vec; use alloc::vec::Vec; pub(crate) mod checked_memory; @@ -6,37 +7,46 @@ pub(crate) use super::region::ResidentLoopPlan; use crate::{ GuestAddress, NativeBlock, - aarch64::{Instruction, Operation, Register, Width}, + aarch64::{Instruction, Operation, Register}, block::{ExitKind, Terminator}, }; -pub(super) fn exit_kind(code: &mut Vec, kind: ExitKind) { - code.push(0xba); // mov edx,kind: zero-extends to the ABI's u64 - code.extend((kind as u32).to_le_bytes()); - code.push(0xc3); +pub(super) fn exit_kind(code: &mut Code, kind: ExitKind) { + exit_kind_with(&mut code.asm(), kind); } -pub(super) fn direct_exit(code: &mut Vec, target: GuestAddress, kind: ExitKind) { - code.extend(super::chain::direct_exit(target, kind)); +/// `mov edx,kind; ret`: the exit to the target in RAX. +pub(super) fn exit_kind_with(asm: &mut Asm, kind: ExitKind) { + // MOV EDX zero-extends to the ABI's u64. + asm.mov_imm32(Gpr::Rdx, kind as u32); + asm.ret(); +} + +pub(crate) fn direct_exit(code: &mut Code, target: GuestAddress, kind: ExitKind) { + direct_exit_with(&mut code.asm(), target, kind); +} + +/// `movabs rax,target; mov edx,kind; ret`. +pub(super) fn direct_exit_with(asm: &mut Asm, target: GuestAddress, kind: ExitKind) { + asm.mov_imm64(Gpr::Rax, target.0); + exit_kind_with(asm, kind); } fn conditional_exit( - code: &mut Vec, - opcode: Option, + code: &mut Code, + taken: Option, target: GuestAddress, fallthrough: GuestAddress, ) { - if let Some(opcode) = opcode { - code.extend([0x0f, opcode]); - let fixup = code.len(); - code.extend([0; 4]); - direct_exit(code, fallthrough, ExitKind::Fallthrough); + let mut asm = code.asm(); + if let Some(taken) = taken { + let branch = asm.jcc(taken); + direct_exit_with(&mut asm, fallthrough, ExitKind::Fallthrough); // The taken branch skips the complete fallthrough exit. Both paths // leave saved NZCV untouched regardless of host predicate evaluation. - let relative = (code.len() - fixup - 4) as i32; - code[fixup..fixup + 4].copy_from_slice(&relative.to_le_bytes()); + asm.bind(branch); } - direct_exit(code, target, ExitKind::Direct); + direct_exit_with(&mut asm, target, ExitKind::Direct); } #[cfg(test)] @@ -89,6 +99,7 @@ pub(crate) fn emit_resident_fallback_for_target( super::region::prefix_with_budget(native, base) } +#[cfg(test)] pub(crate) fn emit_for_target( instructions: &[Instruction], terminal: Option<&(GuestAddress, Terminator)>, @@ -109,8 +120,8 @@ pub(crate) fn emit_for_target( .0 } -/// [`emit_for_target`] for the system-mode engine, which may also complete -/// a terminal System instruction natively and fall through: DC ZVA by +/// A block for the system-mode engine, which may also complete a terminal +/// System instruction natively and fall through: DC ZVA by /// zeroing its block (`x86_64::zero_block`) and DC CVAC, DC CVAU and DC /// CIVAC by reading the byte at Xt (`x86_64::cache_clean`). pub(crate) fn emit_system_mode( @@ -156,10 +167,7 @@ fn emit_selected( native: super::NativeSystem, ) -> (NativeBlock, Vec) { let mut fault_recovery = vec![]; - let mut block = NativeBlock { - x86_64_code: vec![], - source_map: vec![], - }; + let mut block = super::Emitted::default(); let code = &mut block.x86_64_code; let mut fixups = vec![]; // The DIT audit covers each instruction's own lowering, not the @@ -200,7 +208,7 @@ fn emit_selected( && let Ok(Some(region)) = super::region::emit_allocated_prefix(&instructions[cursor..]) { let count = region.consumed_instructions; - let mut baseline = vec![]; + let mut baseline = Code::new(); let mut candidate_fixups = vec![]; for (index, instruction) in instructions[cursor..cursor + count].iter().enumerate() { super::emit_instruction( @@ -216,7 +224,7 @@ fn emit_selected( block .source_map .extend(region.source_map.iter().map(|(pc, at)| (*pc, offset + at))); - code.extend(region.code); + code.append(region.code); cursor += count; continue; } @@ -233,7 +241,7 @@ fn emit_selected( let count = region.consumed_instructions; let chunk = &instructions[cursor..cursor + count]; let baseline = |checks_at: &dyn Fn(usize) -> super::MemoryChecks| { - let mut code = vec![]; + let mut code = Code::new(); let mut map = vec![]; let mut fixups = vec![]; let mut after = held; @@ -264,7 +272,7 @@ fn emit_selected( ..entry } })); - code.extend(region.code); + code.append(region.code); } else { // Reject the complete eligible chunk. Rescanning its suffix // could bypass the measured cost gate with a different shape. @@ -272,7 +280,7 @@ fn emit_selected( block .source_map .extend(baseline_map.iter().map(|(pc, at)| (*pc, offset + at))); - code.extend(baseline_code); + code.append(baseline_code); after = baseline_after; } // Each region wrote back the full register frame, so what follows @@ -307,7 +315,7 @@ fn emit_selected( checks, after.rax, ); - (block, fault_recovery) + (block.into_native(), fault_recovery) } /// What registers hold where an instruction outside the regions begins, @@ -333,7 +341,7 @@ impl Held { /// `out_of_line`, numerical instructions move their slow paths there. #[allow(clippy::too_many_arguments)] fn emit_single( - code: &mut Vec, + code: &mut Code, out_of_line: Option<&mut OutOfLine>, instruction: &Instruction, fixups: &mut Vec<(GuestAddress, GuestAddress, usize)>, @@ -383,7 +391,7 @@ fn emit_single( let rax = super::rax_after(&instruction.operation); debug_assert!(match rax { super::Rax::Unknown => true, - super::Rax::Nzcv => code.ends_with(&STORE_EAX_NZCV), + super::Rax::Nzcv => code.ends_with(&nzcv_store()), super::Rax::Guest(register) => super::frame_store(register).is_some_and(|store| code.ends_with(&store)), }); @@ -421,7 +429,7 @@ const JMP_REL32_BYTES: usize = 1 + REL32_BYTES; /// [`ColdSplit`]: super::simd::numerical::ColdSplit #[derive(Default)] struct OutOfLine { - code: Vec, + code: Code, /// rel32 fields with the places they target. fixups: Vec<(Place, Place)>, /// The jump ending the last moved part and where its instruction ended @@ -442,7 +450,7 @@ impl OutOfLine { /// `start` to the end of `code`, which ends its emission. fn take( &mut self, - code: &mut Vec, + code: &mut Code, start: usize, split: Option, ) { @@ -478,14 +486,13 @@ impl OutOfLine { .push((place(site, inline), place(target, inline))); } self.code.extend(&code[split.cold..]); - self.code.push(JMP_REL32); - self.open = Some((self.code.len(), inline_end)); - self.code.extend([0; REL32_BYTES]); + let back = self.code.asm().jmp(); + self.open = Some((back.offset(), inline_end)); code.truncate(inline_end); } /// Lay out the moved code at the end of `code` behind a jump over it. - fn place(mut self, code: &mut Vec) { + fn place(mut self, code: &mut Code) { if let Some((site, end)) = self.open.take() { self.fixups .push((Place::OutOfLine(site), Place::Inline(end))); @@ -493,14 +500,10 @@ impl OutOfLine { if self.code.is_empty() { return; } - code.push(JMP_REL32); - code.extend( - i32::try_from(self.code.len()) - .expect("bounded block") - .to_le_bytes(), - ); + let over = code.asm().jmp(); let base = code.len(); - code.extend(&self.code); + code.append(self.code); + code.asm().bind(over); let at = |place| match place { Place::Inline(offset) => offset, Place::OutOfLine(offset) => base + offset, @@ -519,10 +522,11 @@ fn target_of(code: &[u8], site: usize) -> usize { /// `mov [rdi+GuestState.nzcv],eax`, which ends each emission after which /// RAX holds [`super::Rax::Nzcv`]. -const STORE_EAX_NZCV: [u8; 6] = { - let offset = (core::mem::offset_of!(crate::GuestState, nzcv) as u32).to_le_bytes(); - [0x89, 0x87, offset[0], offset[1], offset[2], offset[3]] -}; +fn nzcv_store() -> Code { + let mut code = Code::new(); + super::store_nzcv(&mut code.asm()); + code +} /// The direct exits to static successors that [`emit_terminal`] ended /// `code` with: the target's last, after a conditional branch's fallthrough. pub(crate) fn successor_exits( @@ -571,7 +575,7 @@ pub(crate) fn successor_exits( #[allow(clippy::too_many_arguments)] fn emit_terminal( - code: &mut Vec, + code: &mut Code, source_map: &mut Vec<(GuestAddress, usize)>, terminal: Option<&(GuestAddress, Terminator)>, fallthrough: GuestAddress, @@ -580,7 +584,7 @@ fn emit_terminal( rax: super::Rax, ) { // The terminal's own load of a register RAX already holds. - let load = |code: &mut Vec, register| { + let load = |code: &mut Code, register| { if rax != super::Rax::Guest(register) { super::load(code, register); } @@ -642,18 +646,18 @@ fn emit_terminal( load(code, *source); if *kind == ExitKind::Call { // Capture BLR X30's target before LR is overwritten. - code.extend([0x48, 0x89, 0xc1]); // mov rcx,rax + code.asm().mov(Size::Qword, Gpr::Rcx, Gpr::Rax); super::immediate(code, fallthrough.0); super::store(code, Register::X(30)); - code.extend([0x48, 0x89, 0xc8]); // mov rax,rcx + code.asm().mov(Size::Qword, Gpr::Rax, Gpr::Rcx); } exit_kind(code, *kind); } Terminator::Branch(operation) => match *operation { Operation::Branch { target } => direct_exit(code, target, ExitKind::Direct), Operation::BranchCondition { target, condition } => { - let opcode = super::condition_of(code, condition, rax == super::Rax::Nzcv); - conditional_exit(code, opcode, target, fallthrough); + let taken = super::condition_holds(code, condition, rax == super::Rax::Nzcv); + conditional_exit(code, taken, target, fallthrough); } Operation::BranchZero { target, @@ -662,16 +666,8 @@ fn emit_terminal( nonzero, } => { load(code, source); - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x85, 0xc0]); // test (e/r)ax,(e/r)ax - conditional_exit( - code, - Some(if nonzero { 0x85 } else { 0x84 }), - target, - fallthrough, - ); + let taken = super::test_zero(code, width, nonzero); + conditional_exit(code, Some(taken), target, fallthrough); } Operation::BranchBit { target, @@ -680,13 +676,8 @@ fn emit_terminal( nonzero, } => { load(code, source); - code.extend([0x48, 0x0f, 0xba, 0xe0, bit]); // bt rax,bit - conditional_exit( - code, - Some(if nonzero { 0x82 } else { 0x83 }), - target, - fallthrough, - ); + let taken = super::test_bit(code, bit, nonzero); + conditional_exit(code, Some(taken), target, fallthrough); } _ => unreachable!("block decoder restricts branch terminators"), }, @@ -703,6 +694,26 @@ mod tests { use alloc::vec; use alloc::vec::Vec; + /// A conditional exit's branch skips its fallthrough exit, and each of + /// its instructions counts. + #[test] + fn conditional_exits_branch_over_the_fallthrough_exit() { + let mut code = Code::new(); + conditional_exit( + &mut code, + Some(Cond::Ne), + GuestAddress(0x2000), + GuestAddress(0x1004), + ); + let fallthrough = + super::super::chain::direct_exit(GuestAddress(0x1004), ExitKind::Fallthrough); + let taken = super::super::chain::direct_exit(GuestAddress(0x2000), ExitKind::Direct); + assert_eq!(code[..6], [0x0f, 0x85, 16, 0, 0, 0]); + assert_eq!(code[6..22], fallthrough); + assert_eq!(code[22..], taken); + assert_eq!(code.instructions(), 7); + } + /// add x10, x10, #4; cmp x10, #0x600; b.ne: the CMP takes X10 from /// RAX where the ADD stored it, and the branch tests the NZCV word the /// CMP left in EAX, so neither reloads from the frame. @@ -945,7 +956,7 @@ mod tests { for instruction in &instructions { before.push((instruction.pc.0, expected.clone(), expected_memory)); let next = GuestAddress(instruction.pc.0 + 4); - let mut code = vec![]; + let mut code = Code::new(); match &instruction.operation { Operation::FloatingPoint(operand) => { super::super::simd::emit_numerical( @@ -1198,7 +1209,7 @@ mod tests { // Replays the system-mode selection with its cost gates: a // rejected chunk is emitted as baseline and skipped whole. let baseline = |count: usize| { - let mut code = vec![]; + let mut code = Code::new(); let mut fixups = vec![]; for (index, instruction) in rest[..count].iter().enumerate() { super::super::emit_instruction( @@ -1268,7 +1279,7 @@ mod tests { operation => category(operation), }; *outside.entry(detail).or_default() += 1; - let mut code = vec![]; + let mut code = Code::new(); let mut fixups = vec![]; if let Operation::FloatingPoint(operand) = &instruction.operation { super::super::simd::emit_numerical( diff --git a/crates/stela-compiler/src/x86_64/block/checked_memory.rs b/crates/stela-compiler/src/x86_64/block/checked_memory.rs index f4f3f750bc..05bccc4eff 100644 --- a/crates/stela-compiler/src/x86_64/block/checked_memory.rs +++ b/crates/stela-compiler/src/x86_64/block/checked_memory.rs @@ -3,7 +3,8 @@ use crate::{ CompileError, GuestAddress, NativeBlock, TargetCpu, aarch64::Instruction, block::{Terminator, memory::CheckedOperation}, - extended, + scalable_context, + x86_64::Emitted, }; use alloc::vec::Vec; @@ -15,8 +16,8 @@ pub(crate) fn emit( register_regions: bool, mut profile: Option<&mut crate::block::profile::CompileProfile>, ) -> Result { - let mut block = NativeBlock { - x86_64_code: extended::context_wrapper(), + let mut block = Emitted { + x86_64_code: scalable_context::context_wrapper(), source_map: Vec::new(), }; let mut fixups = Vec::new(); @@ -88,11 +89,11 @@ pub(crate) fn emit( traffic, }); } - Ok(block) + Ok(block.into_native()) } fn emit_register_span( - block: &mut NativeBlock, + block: &mut Emitted, instructions: &[Instruction], target: TargetCpu, source_start: usize, @@ -109,10 +110,7 @@ fn emit_register_span( let count = candidate .as_ref() .map_or(1, |region| region.consumed_instructions.max(1)); - let mut baseline = NativeBlock { - x86_64_code: Vec::new(), - source_map: Vec::new(), - }; + let mut baseline = Emitted::default(); let mut fixups = Vec::new(); for instruction in &remaining[..count] { baseline @@ -159,7 +157,7 @@ fn emit_register_span( .into_iter() .map(|(pc, at)| (pc, offset + at)), ); - block.x86_64_code.extend(region.code); + block.x86_64_code.append(region.code); } else { // A rejected candidate consumes its exact original span. Trying // shorter suffixes could evade the candidate's measured cost gate. @@ -169,7 +167,7 @@ fn emit_register_span( .into_iter() .map(|(pc, at)| (pc, offset + at)), ); - block.x86_64_code.extend(baseline.x86_64_code); + block.x86_64_code.append(baseline.x86_64_code); } cursor += count; } @@ -179,7 +177,7 @@ fn emit_register_span( #[cfg(test)] mod tests { use super::*; - use crate::block::{BlockProfile, CheckedMemoryProfile, CompilationPlan}; + use crate::block::{BlockProfile, CheckedMemoryProfile, CompilationPlan, Features}; use alloc::vec; const PC: GuestAddress = GuestAddress(0x4000); @@ -200,15 +198,19 @@ mod tests { let baseline = CompilationPlan::new( &source, PC, - BlockProfile::CheckedMemory(recipe), - TargetCpu::Baseline, + &crate::Options::new( + BlockProfile::ORDINARY.with_checked_memory(recipe), + TargetCpu::Baseline, + ), ) .unwrap(); let selected = CompilationPlan::new( &source, PC, - BlockProfile::SystemModeSharedV1(recipe), - TargetCpu::Baseline, + &crate::Options::new( + BlockProfile::new(Features::SYSTEM_MODE).with_checked_memory(recipe), + TargetCpu::Baseline, + ), ) .unwrap(); assert_eq!( @@ -260,14 +262,15 @@ mod tests { ] { let source: Vec<_> = words.into_iter().flat_map(u32::to_le_bytes).collect(); let compile = |profile| { - CompilationPlan::new(&source, PC, profile, target) + CompilationPlan::new(&source, PC, &crate::Options::new(profile, target)) .unwrap() .compile() .unwrap() }; let recipe = CheckedMemoryProfile::SpAlignmentEnabled; - let baseline = compile(BlockProfile::CheckedMemory(recipe)); - let selected = compile(BlockProfile::SystemModeSharedV1(recipe)); + let baseline = compile(BlockProfile::ORDINARY.with_checked_memory(recipe)); + let selected = + compile(BlockProfile::new(Features::SYSTEM_MODE).with_checked_memory(recipe)); assert_eq!(baseline.native.x86_64_code, selected.native.x86_64_code); assert_eq!(baseline.native.source_map, selected.native.source_map); } diff --git a/crates/stela-compiler/src/x86_64/cache_clean.rs b/crates/stela-compiler/src/x86_64/cache_clean.rs index b35b5b4dd9..5f2ccaecce 100644 --- a/crates/stela-compiler/src/x86_64/cache_clean.rs +++ b/crates/stela-compiler/src/x86_64/cache_clean.rs @@ -1,6 +1,6 @@ //! DC CVAC, DC CVAU and DC CIVAC in system-mode blocks the engine compiles //! where they neither trap nor are UNDEFINED -//! (`CompilationPlan::with_cache_clean`). The host is cache-coherent, so +//! (`Options::with_native_system`). The host is cache-coherent, so //! all the engine does for them is translate Xt as a read, taking the Data //! Abort of a failed translation (`engine::system` `check_maintenance`). //! Native code makes the same check by reading the byte at Xt through the @@ -15,7 +15,7 @@ use crate::aarch64::{ system::registers::{Direction, Encoding}, }; use crate::block::{SystemInstruction, system::SystemOperation}; -use alloc::vec::Vec; +use crate::x86_64::asm::{Code, Gpr, Mem, Size}; /// SYS #3, C7, Cm, #1 of each operation. const DC_CVAC: Encoding = Encoding::new(1, 3, 7, 10, 1); @@ -78,7 +78,7 @@ pub fn operand(instruction: &SystemInstruction) -> Option<(Operations, u8)> { } /// Read the byte at Xt, so the access faults where its translation would. -pub(crate) fn emit(code: &mut Vec, rt: u8, checks: super::MemoryChecks) { +pub(crate) fn emit(code: &mut Code, rt: u8, checks: super::MemoryChecks) { super::load( code, if rt == 31 { @@ -88,7 +88,8 @@ pub(crate) fn emit(code: &mut Vec, rt: u8, checks: super::MemoryChecks) { }, ); super::range_check(code, checks, super::Access::read(1)); - code.extend([0x0f, 0xb6, 0x08]); // movzx ecx,byte [rax] + code.asm() + .movzx(Size::Dword, Gpr::Rcx, Size::Byte, Mem::base(Gpr::Rax, 0)); } #[cfg(test)] @@ -155,9 +156,11 @@ mod tests { let memory = [0x5au8, 0xc3]; let mut state = GuestState::default(); state.x[7] = memory.as_ptr() as u64 + 1; - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, 7, super::super::MemoryChecks::DEFAULT); - code.extend([0x89, 0xc8, 0xc3]); // mov eax,ecx; ret + let mut asm = code.asm(); + asm.mov(Size::Dword, Gpr::Rax, Gpr::Rcx); + asm.ret(); // SAFETY: private anonymous memory, RX after the copy, unmapped // after the call; the code reads one byte of `memory`. let read = unsafe { diff --git a/crates/stela-compiler/src/x86_64/chain.rs b/crates/stela-compiler/src/x86_64/chain.rs index 66e94efcbb..cdd3e0ec8c 100644 --- a/crates/stela-compiler/src/x86_64/chain.rs +++ b/crates/stela-compiler/src/x86_64/chain.rs @@ -29,6 +29,12 @@ //! keeps live. The thunk of an exit that sets a nonzero BTYPE (BR or BLR) //! also requires the entry to accept that BTYPE (`LookupEntry::targets`), //! as a Branch Target check of the entered block's first instruction would. +use crate::x86_64::asm::{ + Alu, BitTest, Code, Cond, + Gpr::{R8, Rax, Rcx, Rdx}, + Mem, ShiftOp, + Size::{self, Dword, Qword}, +}; use crate::{GuestAddress, block::ExitKind}; use alloc::vec::Vec; @@ -112,28 +118,24 @@ pub const fn lookup_slot(pc: u64) -> usize { // `sub qword [rcx],1` addresses the budget at offset 0. const _: () = assert!(core::mem::offset_of!(ChainControl, budget) == 0); -const RETIRED: u8 = core::mem::offset_of!(ChainControl, retired) as u8; -const BLOCK: u8 = core::mem::offset_of!(ChainControl, block) as u8; -const CONTEXTS: u8 = core::mem::offset_of!(ChainControl, contexts) as u8; -const TABLE: u8 = core::mem::offset_of!(ChainControl, table) as u8; -const HITS: u8 = core::mem::offset_of!(ChainControl, hits) as u8; -const LINKED: u8 = core::mem::offset_of!(ChainControl, linked) as u8; +const RETIRED: i32 = core::mem::offset_of!(ChainControl, retired) as i32; +const BLOCK: i32 = core::mem::offset_of!(ChainControl, block) as i32; +const CONTEXTS: i32 = core::mem::offset_of!(ChainControl, contexts) as i32; +const TABLE: i32 = core::mem::offset_of!(ChainControl, table) as i32; +const HITS: i32 = core::mem::offset_of!(ChainControl, hits) as i32; +const LINKED: i32 = core::mem::offset_of!(ChainControl, linked) as i32; const _: () = assert!(core::mem::size_of::() == 32); const _: () = assert!(core::mem::offset_of!(LookupEntry, pc) == 0); -const ENTRY_CONTEXT: u8 = core::mem::offset_of!(LookupEntry, context) as u8; -const ENTRY_CODE: u8 = core::mem::offset_of!(LookupEntry, entry) as u8; -const ENTRY_BLOCK: u8 = core::mem::offset_of!(LookupEntry, block) as u8; -const ENTRY_TARGETS: u8 = core::mem::offset_of!(LookupEntry, targets) as u8; +const ENTRY_CONTEXT: i32 = core::mem::offset_of!(LookupEntry, context) as i32; +const ENTRY_CODE: i32 = core::mem::offset_of!(LookupEntry, entry) as i32; +const ENTRY_BLOCK: i32 = core::mem::offset_of!(LookupEntry, block) as i32; +const ENTRY_TARGETS: i32 = core::mem::offset_of!(LookupEntry, targets) as i32; /// A direct exit to `target` with `kind`, as every block emits it. pub fn direct_exit(target: GuestAddress, kind: ExitKind) -> [u8; DIRECT_EXIT_BYTES] { - let mut code = [0; DIRECT_EXIT_BYTES]; - code[..2].copy_from_slice(&[0x48, 0xb8]); // movabs rax,target - code[2..10].copy_from_slice(&target.0.to_le_bytes()); - code[10] = 0xba; // mov edx,kind: zero-extends to the ABI's u64 - code[11..15].copy_from_slice(&(kind as u32).to_le_bytes()); - code[15] = 0xc3; // ret - code + let mut code = Code::new(); + super::block::direct_exit_with(&mut code.asm(), target, kind); + code.try_into().expect("a direct exit's length") } /// A thunk at host address `at` that chains a block of `retired` @@ -152,22 +154,22 @@ pub fn thunk( ) -> Option> { let retired = i32::try_from(retired).ok()?; let block = i32::try_from(block).ok()?; - let mut code = Vec::with_capacity(64); - code.extend([0x48, 0xb9]); // movabs rcx,control - code.extend(control.to_le_bytes()); - code.extend([0x48, 0x83, 0x29, 0x01]); // sub qword [rcx],1 - code.extend([0x72, 0]); // jb exit - let skip = code.len(); - code.extend([0x48, 0x81, 0x41, RETIRED]); // add qword [rcx+retired],imm32 - code.extend(retired.to_le_bytes()); - code.extend([0x48, 0x83, 0x41, LINKED, 0x01]); // add qword [rcx+linked],1 - code.extend([0x48, 0xc7, 0x41, BLOCK]); // mov qword [rcx+block],imm32 - code.extend(block.to_le_bytes()); - code.extend(jump(at + code.len() as u64, entry)?); - code[skip - 1] = (code.len() - skip) as u8; - code.extend(direct_exit(target, kind)); + let mut code = Code::new(); + let mut asm = code.asm(); + asm.mov_imm64(Rcx, control); + // Take one transfer from the budget. + asm.alu_imm8(Alu::Sub, Qword, Mem::base(Rcx, 0), 1); + let exhausted = asm.jcc8(Cond::B); + asm.alu_imm32(Alu::Add, Qword, Mem::base(Rcx, RETIRED), retired); + asm.alu_imm8(Alu::Add, Qword, Mem::base(Rcx, LINKED), 1); + asm.mov_rm_imm32(Qword, Mem::base(Rcx, BLOCK), block); + let transfer = asm.jmp(); + let relative = relative(at + transfer.end() as u64, entry)?; + asm.bind(exhausted); + super::block::direct_exit_with(&mut asm, target, kind); + code[transfer.offset()..transfer.end()].copy_from_slice(&relative.to_le_bytes()); debug_assert_eq!(code.len(), THUNK_BYTES); - Some(code) + Some(code.into_bytes()) } /// A lookup thunk for an exit of `kind` from a block of `retired` @@ -185,56 +187,49 @@ pub fn lookup_thunk( if btype > 3 { return None; } - let mut code = Vec::with_capacity(STATIC_LOOKUP_THUNK_BYTES); + let mut code = Code::new(); + let mut asm = code.asm(); if let Some(target) = target { - code.extend([0x48, 0xb8]); // movabs rax,target - code.extend(target.0.to_le_bytes()); + asm.mov_imm64(Rax, target.0); } - code.extend([0x48, 0xb9]); // movabs rcx,control - code.extend(control.to_le_bytes()); - code.extend([0x89, 0xc2]); // mov edx,eax - code.extend([0xc1, 0xea, 0x02]); // shr edx,2 - code.extend([0x81, 0xe2]); // and edx,LOOKUP_ENTRIES-1 - code.extend((LOOKUP_ENTRIES as u32 - 1).to_le_bytes()); - code.extend([0xc1, 0xe2, 0x05]); // shl edx,5 - code.extend([0x48, 0x03, 0x51, TABLE]); // add rdx,[rcx+table] + asm.mov_imm64(Rcx, control); + // RDX = the target's entry in the table. + asm.mov(Dword, Rdx, Rax); + asm.shift_imm(ShiftOp::Shr, Dword, Rdx, 2); + asm.alu_imm32(Alu::And, Dword, Rdx, LOOKUP_ENTRIES as i32 - 1); + asm.shift_imm(ShiftOp::Shl, Dword, Rdx, 5); + asm.alu_load(Alu::Add, Qword, Rdx, Mem::base(Rcx, TABLE)); let mut misses = Vec::new(); - code.extend([0x48, 0x3b, 0x02]); // cmp rax,[rdx] - code.extend([0x75, 0]); // jne miss - misses.push(code.len()); - code.extend([0x49, 0x89, 0xc0]); // mov r8,rax - code.extend([0x49, 0xc1, 0xe8, 55]); // shr r8,55 - code.extend([0x41, 0x83, 0xe0, 0x01]); // and r8d,1: the target's half - code.extend([0x4e, 0x8b, 0x44, 0xc1, CONTEXTS]); // mov r8,[rcx+r8*8+contexts] - code.extend([0x4c, 0x3b, 0x42, ENTRY_CONTEXT]); // cmp r8,[rdx+context] - code.extend([0x75, 0]); // jne miss - misses.push(code.len()); + asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rdx, 0)); + misses.push(asm.jcc8(Cond::Ne)); + // R8 = the context of the target's half. + asm.mov(Qword, R8, Rax); + asm.shift_imm(ShiftOp::Shr, Qword, R8, 55); + asm.alu_imm8(Alu::And, Dword, R8, 1); + asm.mov_load(Qword, R8, Mem::indexed(Rcx, R8, 8, CONTEXTS)); + asm.alu_load(Alu::Cmp, Qword, R8, Mem::base(Rdx, ENTRY_CONTEXT)); + misses.push(asm.jcc8(Cond::Ne)); if btype != 0 { - code.extend([0xf6, 0x42, ENTRY_TARGETS, 1 << btype]); // test byte [rdx+targets],1< [u8; DYNAMIC_EXIT_BYTES] { - let mut code = [0xba, 0, 0, 0, 0, 0xc3]; // mov edx,kind; ret - code[1..5].copy_from_slice(&(kind as u32).to_le_bytes()); - code + let mut code = Code::new(); + super::block::exit_kind_with(&mut code.asm(), kind); + code.try_into().expect("a dynamic exit's length") } /// `jmp rel32` at host address `at` to `to`, or `None` out of reach. pub fn jump(at: u64, to: u64) -> Option<[u8; JUMP_BYTES]> { - let relative = i32::try_from(to.wrapping_sub(at + JUMP_BYTES as u64) as i64).ok()?; - let mut code = [0xe9, 0, 0, 0, 0]; - code[1..].copy_from_slice(&relative.to_le_bytes()); - Some(code) + let relative = relative(at + JUMP_BYTES as u64, to)?; + let mut code = Code::new(); + let field = code.asm().jmp(); + code[field.offset()..field.end()].copy_from_slice(&relative.to_le_bytes()); + code.try_into().ok() +} + +/// The rel32 displacement of a branch ending at host address `end` to +/// `to`, or `None` out of reach. +fn relative(end: u64, to: u64) -> Option { + i32::try_from(to.wrapping_sub(end) as i64).ok() } #[cfg(test)] mod tests { use super::*; + use crate::x86_64::asm::Code; use alloc::vec; #[test] fn direct_exits_match_the_block_emitter() { - let mut emitted = Vec::new(); + let mut emitted = Code::new(); super::super::block::direct_exit(&mut emitted, GuestAddress(0x1234), ExitKind::Direct); assert_eq!(emitted, direct_exit(GuestAddress(0x1234), ExitKind::Direct)); } @@ -308,7 +311,7 @@ mod tests { #[test] fn dynamic_exits_match_the_block_emitter() { - let mut emitted = Vec::new(); + let mut emitted = Code::new(); super::super::block::exit_kind(&mut emitted, ExitKind::Return); assert_eq!(emitted, dynamic_exit(ExitKind::Return)); let span = 4 * LOOKUP_ENTRIES as u64; diff --git a/crates/stela-compiler/src/x86_64/checked_pointer.rs b/crates/stela-compiler/src/x86_64/checked_pointer.rs index 88e52898e6..c6dbbed4b0 100644 --- a/crates/stela-compiler/src/x86_64/checked_pointer.rs +++ b/crates/stela-compiler/src/x86_64/checked_pointer.rs @@ -1,27 +1,17 @@ //! FEAT_CPA checked pointer arithmetic. Clobbers caller-saved GPRs and host flags //! only. use super::{Register, Shift, Width, load, right_operand, store}; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Size, Unary}; use crate::{ aarch64::checked_pointer::{Kind, Operand}, context::pointer::EffectivePointerChecks, }; -use alloc::vec::Vec; -const NOP: u8 = 0x90; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const MOV_RDX_RCX: &[u8] = &[0x48, 0x89, 0xca]; -const XOR_R8D_R8D: &[u8] = &[0x45, 0x31, 0xc0]; -const ADD_RAX_RCX: &[u8] = &[0x48, 0x01, 0xc8]; -const SUB_RAX_RCX: &[u8] = &[0x48, 0x29, 0xc8]; -const IMUL_RAX_RCX: &[u8] = &[0x48, 0x0f, 0xaf, 0xc1]; -const NEG_RAX: &[u8] = &[0x48, 0xf7, 0xd8]; -const SETO_R8B: &[u8] = &[0x41, 0x0f, 0x90, 0xc0]; - -pub(crate) fn emit(code: &mut Vec, operand: &Operand, checks: EffectivePointerChecks) { +pub(crate) fn emit(code: &mut Code, operand: &Operand, checks: EffectivePointerChecks) { // These arithmetic checks mark a pointer and cannot fault by themselves. // Feature/control admission must precede this discarded-result shortcut. if operand.destination == Register::Zero { - code.push(NOP); + code.asm().nop(); return; } let unchanged_base = match operand.kind { @@ -39,7 +29,7 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, checks: EffectivePoint // Zero offset/product cannot change the top byte or overflow a product. // An already marked base has bit54=NOT bit55, so marking is idempotent. if operand.destination == base { - code.push(NOP); + code.asm().nop(); } else { load(code, base); store(code, operand.destination); @@ -57,10 +47,11 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, checks: EffectivePoint } => { load(code, base); if checking { - code.extend(MOV_RDX_RAX); + code.asm().mov(Size::Qword, Gpr::Rdx, Gpr::Rax); } right_operand(code, offset, Width::X64, Shift::Lsl, amount); - code.extend(if subtract { SUB_RAX_RCX } else { ADD_RAX_RCX }); + let op = if subtract { Alu::Sub } else { Alu::Add }; + code.asm().alu(op, Size::Qword, Gpr::Rax, Gpr::Rcx); false } Kind::Product { @@ -71,25 +62,27 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, checks: EffectivePoint } => { load(code, left); right_operand(code, right, Width::X64, Shift::Lsl, 0); + let mut asm = code.asm(); if multiply_checking { - code.extend(XOR_R8D_R8D); + asm.alu(Alu::Xor, Size::Dword, Gpr::R8, Gpr::R8); } - code.extend(IMUL_RAX_RCX); + asm.imul(Size::Qword, Gpr::Rax, Gpr::Rcx); if multiply_checking { // IMUL OF is exactly full signed product != sign_extend(low64). // Capture it before NEG, ZR materialization or ADD changes flags. - code.extend(SETO_R8B); + asm.setcc(Cond::O, Gpr::R8); } if subtract { - code.extend(NEG_RAX); + asm.unary(Unary::Neg, Size::Qword, Gpr::Rax); } if checking || base != Register::Zero { right_operand(code, base, Width::X64, Shift::Lsl, 0); + let mut asm = code.asm(); if checking { - code.extend(MOV_RDX_RCX); + asm.mov(Size::Qword, Gpr::Rdx, Gpr::Rcx); } if base != Register::Zero { - code.extend(ADD_RAX_RCX); + asm.alu(Alu::Add, Size::Qword, Gpr::Rax, Gpr::Rcx); } } true diff --git a/crates/stela-compiler/src/x86_64/conditional_select.rs b/crates/stela-compiler/src/x86_64/conditional_select.rs index da43443d36..b987faa250 100644 --- a/crates/stela-compiler/src/x86_64/conditional_select.rs +++ b/crates/stela-compiler/src/x86_64/conditional_select.rs @@ -1,83 +1,70 @@ //! Branchless conditional select from the saved guest NZCV. -use super::{capture_nzcv, condition, load, right_operand, store}; +use super::{capture_nzcv, condition_holds, load, right_operand, store, store_nzcv}; use crate::aarch64::{ Shift, Width, conditional_select::{CompareOperand, CompareRight, Operand, Otherwise}, }; -use alloc::vec::Vec; +use crate::x86_64::asm::{ + Alu, Code, Cond, + Gpr::{R8, Rax, Rcx, Rdx}, + Size, Unary, +}; -/// MOV EDX,imm32: the fallback NZCV word. -const MOV_EDX_IMM32: u8 = 0xba; -/// SETcc R8B (the condition's opcode plus this) and TEST R8B,R8B. -const SET_FROM_JUMP: u8 = 0x10; -const TEST_R8B: [u8; 3] = [0x45, 0x84, 0xc0]; -const CMOVZ_EAX_EDX: [u8; 3] = [0x0f, 0x44, 0xc2]; -const STORE_EAX_NZCV: [u8; 2] = [0x89, 0x87]; -const STATE_NZCV_OFFSET: u32 = core::mem::offset_of!(crate::GuestState, nzcv) as u32; const NZCV_SHIFT: u8 = 28; /// The comparison runs on both arms and a CMOV picks its flags or the /// fallback, so the timing depends on neither the condition nor the data. -pub(super) fn emit_compare(code: &mut Vec, operand: &CompareOperand) { - let predicate = condition(code, operand.condition); - if let Some(jcc) = predicate { +pub(super) fn emit_compare(code: &mut Code, operand: &CompareOperand) { + let predicate = condition_holds(code, operand.condition, false); + if let Some(cond) = predicate { // R8 is scratch under the native leaf ABI. - code.extend([0x41, 0x0f, jcc + SET_FROM_JUMP, 0xc0]); // setcc r8b + code.asm().setcc(cond, R8); } load(code, operand.left); match operand.right { CompareRight::Register(register) => { right_operand(code, register, operand.width, Shift::Lsl, 0) } - CompareRight::Immediate(value) => { - code.push(0xb9); - code.extend(u32::from(value).to_le_bytes()); - } + CompareRight::Immediate(value) => code.asm().mov_imm32(Rcx, u32::from(value)), } - if operand.width == Width::X64 { - code.push(0x48); - } - code.extend([if operand.subtract { 0x29 } else { 0x01 }, 0xc8]); + let op = if operand.subtract { Alu::Sub } else { Alu::Add }; + code.asm() + .alu(op, Size::of(operand.width == Width::X64), Rax, Rcx); capture_nzcv(code, operand.subtract); + let mut asm = code.asm(); if predicate.is_some() { - code.push(MOV_EDX_IMM32); - code.extend((u32::from(operand.fallback) << NZCV_SHIFT).to_le_bytes()); - code.extend(TEST_R8B); - code.extend(CMOVZ_EAX_EDX); + // The fallback NZCV word where the condition fails. + asm.mov_imm32(Rdx, u32::from(operand.fallback) << NZCV_SHIFT); + asm.test(Size::Byte, R8, R8); + asm.cmov(Cond::E, Size::Dword, Rax, Rdx); } - code.extend(STORE_EAX_NZCV); - code.extend(STATE_NZCV_OFFSET.to_le_bytes()); + store_nzcv(&mut asm); } -pub(super) fn emit(code: &mut Vec, operand: &Operand) { - let predicate = condition(code, operand.condition); - if let Some(jcc) = predicate { +pub(super) fn emit(code: &mut Code, operand: &Operand) { + let predicate = condition_holds(code, operand.condition, false); + if let Some(cond) = predicate { // Save the condition before zero-register loads or false-arm arithmetic // clobber host flags. R8 is scratch under the native leaf ABI. - code.extend([0x41, 0x0f, jcc + SET_FROM_JUMP, 0xc0]); // setcc r8b + code.asm().setcc(cond, R8); } load(code, operand.left); + let size = Size::of(operand.width == Width::X64); if operand.width == Width::W32 { - code.extend([0x89, 0xc0]); // mov eax,eax: clear Xd's upper half on both arms + // Clear Xd's upper half on both arms. + code.asm().mov(Size::Dword, Rax, Rax); } if predicate.is_some() { right_operand(code, operand.right, operand.width, Shift::Lsl, 0); - if operand.otherwise != Otherwise::Unchanged { - if operand.width == Width::X64 { - code.push(0x48); - } - match operand.otherwise { - Otherwise::Increment => code.extend([0xff, 0xc1]), // inc (e/r)cx - Otherwise::Invert => code.extend([0xf7, 0xd1]), // not (e/r)cx - Otherwise::Negate => code.extend([0xf7, 0xd9]), // neg (e/r)cx - Otherwise::Unchanged => unreachable!(), - } + let mut asm = code.asm(); + match operand.otherwise { + Otherwise::Increment => asm.inc(size, Rcx), + Otherwise::Invert => asm.unary(Unary::Not, size, Rcx), + Otherwise::Negate => asm.unary(Unary::Neg, size, Rcx), + Otherwise::Unchanged => {} } - code.extend([0x45, 0x84, 0xc0]); // test r8b,r8b - if operand.width == Width::X64 { - code.push(0x48); - } - code.extend([0x0f, 0x44, 0xc1]); // cmovz (e/r)ax,(e/r)cx + asm.test(Size::Byte, R8, R8); + asm.cmov(Cond::E, size, Rax, Rcx); } // AL and NV both satisfy ConditionHolds: select Rn without transforming Rm. store(code, operand.destination); diff --git a/crates/stela-compiler/src/x86_64/crc.rs b/crates/stela-compiler/src/x86_64/crc.rs index 3acc949738..da50e9032b 100644 --- a/crates/stela-compiler/src/x86_64/crc.rs +++ b/crates/stela-compiler/src/x86_64/crc.rs @@ -2,30 +2,19 @@ //! bit-serial for data-independent timing. use super::isa::{CrcOpcode, CrcTableInstruction as Table}; use super::{Register, Shift, Width, load, right_operand, store}; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, ShiftOp, Size, Unary}; use crate::{ TargetCpu, aarch64::crc::{DataSize, Operand, Polynomial}, }; -use alloc::vec::Vec; const TABLE_ENTRIES: u32 = 256; const ENTRY_BYTES: u32 = 4; const TABLE_BYTES: u32 = TABLE_ENTRIES * ENTRY_BYTES; const BITS_PER_BYTE: u8 = 8; const DATA_WORD_BYTES: u8 = 4; -const MOV_EAX_EAX: [u8; 2] = [0x89, 0xc0]; -const MOVZX_ECX_CL: [u8; 3] = [0x0f, 0xb6, 0xc9]; -const MOVZX_ECX_CX: [u8; 3] = [0x0f, 0xb7, 0xc9]; -const MOV_ECX_ECX: [u8; 2] = [0x89, 0xc9]; -const XOR_RAX_RCX: [u8; 3] = [0x48, 0x31, 0xc8]; -const MOV_EDX_EAX: [u8; 2] = [0x89, 0xc2]; -const AND_EDX_ONE: [u8; 3] = [0x83, 0xe2, 0x01]; -const NEG_EDX: [u8; 2] = [0xf7, 0xda]; -const AND_EDX_IMM32: [u8; 2] = [0x81, 0xe2]; -const SHR_RAX_ONE: [u8; 3] = [0x48, 0xd1, 0xe8]; -const XOR_RAX_RDX: [u8; 3] = [0x48, 0x31, 0xd0]; -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { if operand.destination == Register::Zero { Table::Discard.emit(code); return; @@ -45,15 +34,16 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { store(code, operand.destination); } -fn emit_table(code: &mut Vec, operand: &Operand) { +fn emit_table(code: &mut Code, operand: &Operand) { match operand.size { DataSize::Byte => Table::TruncateByteData.emit(code), DataSize::Halfword => Table::TruncateHalfwordData.emit(code), DataSize::Word | DataSize::Doubleword => {} } - Table::TableBaseRip.emit(code); - let table_address = code.len(); - code.extend(0i32.to_le_bytes()); + // R8 = the table, placed after the jump over it; its displacement is + // the lea's last field. + code.asm().lea(Size::Qword, Gpr::R8, Mem::rip(0)); + let table_base = code.len() - size_of::(); Table::MergeWordData.emit(code); // W operation also truncates accumulator. emit_bytes(code, operand.size.bytes().min(DATA_WORD_BYTES)); if operand.size == DataSize::Doubleword { @@ -61,22 +51,24 @@ fn emit_table(code: &mut Vec, operand: &Operand) { Table::MergeWordData.emit(code); emit_bytes(code, DATA_WORD_BYTES); } - Table::JumpOverTable.emit(code); - code.extend(TABLE_BYTES.to_le_bytes()); - let displacement = i32::try_from(code.len() - table_address - size_of::()) - .expect("bounded CRC instruction table displacement"); - code[table_address..table_address + size_of::()] - .copy_from_slice(&displacement.to_le_bytes()); + let mut asm = code.asm(); + let over = asm.jmp(); // The branch skips this immutable data. All runtime indexes are zero-extended // bytes; every read is one dword inside the readable native-code allocation. + let table = asm.len(); for byte in 0..TABLE_ENTRIES { let mut remainder = byte; for _ in 0..BITS_PER_BYTE { remainder = (remainder >> 1) ^ (operand.polynomial.reflected() & 0u32.wrapping_sub(remainder & 1)); } - code.extend(remainder.to_le_bytes()); + asm.data(&remainder.to_le_bytes()); } + asm.bind(over); + debug_assert_eq!(code.len() - table, TABLE_BYTES as usize); + let displacement = i32::try_from(table - table_base - size_of::()) + .expect("bounded CRC instruction table displacement"); + code[table_base..table_base + size_of::()].copy_from_slice(&displacement.to_le_bytes()); } /// The reflected CRC one data bit at a time over the accumulator XOR the @@ -84,27 +76,30 @@ fn emit_table(code: &mut Vec, operand: &Operand) { /// polynomial masked by the bit shifted out, with no branch or table. The /// data's upper bits enter as they reach the low 32, which is the bytewise /// CRC by linearity; after the last step the value is 32 bits. -fn emit_serial(code: &mut Vec, operand: &Operand) { - code.extend(MOV_EAX_EAX); +fn emit_serial(code: &mut Code, operand: &Operand) { + use Gpr::{Rax, Rcx, Rdx}; + use Size::{Byte, Dword, Qword, Word}; + let mut asm = code.asm(); + asm.mov(Dword, Rax, Rax); match operand.size { - DataSize::Byte => code.extend(MOVZX_ECX_CL), - DataSize::Halfword => code.extend(MOVZX_ECX_CX), - DataSize::Word => code.extend(MOV_ECX_ECX), + DataSize::Byte => asm.movzx(Dword, Rcx, Byte, Rcx), + DataSize::Halfword => asm.movzx(Dword, Rcx, Word, Rcx), + DataSize::Word => asm.mov(Dword, Rcx, Rcx), DataSize::Doubleword => {} } - code.extend(XOR_RAX_RCX); + asm.alu(Alu::Xor, Qword, Rax, Rcx); for _ in 0..operand.size.bytes() * BITS_PER_BYTE { - code.extend(MOV_EDX_EAX); - code.extend(AND_EDX_ONE); - code.extend(NEG_EDX); - code.extend(AND_EDX_IMM32); - code.extend(operand.polynomial.reflected().to_le_bytes()); - code.extend(SHR_RAX_ONE); - code.extend(XOR_RAX_RDX); + // EDX = the polynomial where bit 0 is set, else zero. + asm.mov(Dword, Rdx, Rax); + asm.alu_imm8(Alu::And, Dword, Rdx, 1); + asm.unary(Unary::Neg, Dword, Rdx); + asm.alu_imm32(Alu::And, Dword, Rdx, operand.polynomial.reflected() as i32); + asm.shift_one(ShiftOp::Shr, Qword, Rax); + asm.alu(Alu::Xor, Qword, Rax, Rdx); } } -fn emit_bytes(code: &mut Vec, count: u8) { +fn emit_bytes(code: &mut Code, count: u8) { for _ in 0..count { Table::IndexLowByte.emit(code); Table::ShiftAccumulatorByte.emit(code); @@ -115,7 +110,6 @@ fn emit_bytes(code: &mut Vec, count: u8) { #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; /// The bit-serial model over the full data width matches the bytewise /// CRC, and the lowering has no table, jump or CRC32 instruction. @@ -172,13 +166,13 @@ mod tests { accumulator: Register::X(1), data: Register::X(2), }; - let mut timed = Vec::new(); + let mut timed = Code::new(); emit( &mut timed, &operand, TargetCpu::Sse42.with_data_independent_timing(), ); - let mut baseline = Vec::new(); + let mut baseline = Code::new(); emit(&mut baseline, &operand, TargetCpu::DataIndependentTiming); assert_eq!(timed, baseline); // No RIP-relative table base and no CRC32 (F2 0F 38 F0/F1). @@ -208,13 +202,13 @@ mod tests { accumulator: Register::X(1), data: Register::X(2), }; - let mut baseline = Vec::new(); - let mut checked = Vec::new(); + let mut baseline = Code::new(); + let mut checked = Code::new(); emit(&mut baseline, &operand, TargetCpu::Baseline); emit(&mut checked, &operand, TargetCpu::Sse42); if polynomial == Polynomial::Castagnoli { assert!(checked.len() < baseline.len()); - let mut expected = Vec::new(); + let mut expected = Code::new(); load(&mut expected, operand.accumulator); right_operand(&mut expected, operand.data, Width::X64, Shift::Lsl, 0); CrcOpcode::for_bytes(size.bytes()).emit(&mut expected, TargetCpu::Sse42); @@ -225,9 +219,9 @@ mod tests { } operand.destination = Register::Zero; for target in [TargetCpu::Baseline, TargetCpu::Sse42] { - let mut discarded = Vec::new(); + let mut discarded = Code::new(); emit(&mut discarded, &operand, target); - let mut nop = Vec::new(); + let mut nop = Code::new(); Table::Discard.emit(&mut nop); assert_eq!(discarded, nop); } diff --git a/crates/stela-compiler/src/x86_64/exclusive.rs b/crates/stela-compiler/src/x86_64/exclusive.rs index 827e9d20ca..5e51bc6206 100644 --- a/crates/stela-compiler/src/x86_64/exclusive.rs +++ b/crates/stela-compiler/src/x86_64/exclusive.rs @@ -1,5 +1,7 @@ //! Exclusive loads and stores through the per-thread reservation in the memory //! service, which owns the access, ordering, faults and monitor state. +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Rm, Size}; +use crate::x86_64::isa::SimdOpcode; use super::{load, memory_context as memory, store}; use crate::{ @@ -19,7 +21,6 @@ use crate::{ flags, host_caps, profile_requirements, }, }; -use alloc::vec::Vec; const BYTE_BYTES: u8 = 1; const HALFWORD_BYTES: u8 = 2; @@ -36,20 +37,11 @@ const SCRATCH_BYTES: u32 = (DATA_OFFSET + EXCLUSIVE_DATA_BYTES as u32) .div_ceil(STACK_ALIGNMENT_BYTES) * STACK_ALIGNMENT_BYTES; const _: () = assert!(SCRATCH_BYTES <= i8::MAX as u32); -const SUB_RSP_IMM8: &[u8] = &[0x48, 0x83, 0xec]; -const ADD_RSP_IMM8: &[u8] = &[0x48, 0x83, 0xc4]; -const PXOR_XMM0_XMM0: &[u8] = &[0x66, 0x0f, 0xef, 0xc0]; -const MOVDQU_RSP_DISP8_XMM0: &[u8] = &[0xf3, 0x0f, 0x7f, 0x44, 0x24]; -const MOV_RSP_DISP8_IMM32: &[u8] = &[0xc7, 0x44, 0x24]; -const MOV_RSP_DISP8_AL: &[u8] = &[0x88, 0x44, 0x24]; -const MOV_RSP_DISP8_AX: &[u8] = &[0x66, 0x89, 0x44, 0x24]; -const MOV_RSP_DISP8_EAX: &[u8] = &[0x89, 0x44, 0x24]; -const MOV_RSP_DISP8_RAX: &[u8] = &[0x48, 0x89, 0x44, 0x24]; -const MOVZX_EAX_BYTE_RSP_DISP8: &[u8] = &[0x0f, 0xb6, 0x44, 0x24]; -const MOVZX_EAX_WORD_RSP_DISP8: &[u8] = &[0x0f, 0xb7, 0x44, 0x24]; -const MOV_EAX_RSP_DISP8: &[u8] = &[0x8b, 0x44, 0x24]; -const MOV_RAX_RSP_DISP8: &[u8] = &[0x48, 0x8b, 0x44, 0x24]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; + +/// The scratch payload field at `offset`. +fn scratch(offset: u32) -> Mem { + Mem::base_disp8(Gpr::Rsp, (DATA_OFFSET + offset) as i8) +} /// One control specialization drives both the body's metadata and its emission. /// The checked entry selects it from the live controls. @@ -201,54 +193,53 @@ pub(crate) fn requirements(checked: &CheckedOperand) -> MemoryRequirements { } } -fn initialize(code: &mut Vec) { - code.extend(PXOR_XMM0_XMM0); +fn initialize(code: &mut Code) { + let mut asm = code.asm(); + asm.simd(SimdOpcode::Xor, 0, Rm::Xmm(0), crate::TargetCpu::Baseline); for offset in (0..EXCLUSIVE_DATA_BYTES as u32).step_by(VECTOR_BYTES as usize) { - code.extend(MOVDQU_RSP_DISP8_XMM0); - code.push((DATA_OFFSET + offset) as u8); + asm.movdqu_store(scratch(offset), 0); } } -fn set_field(code: &mut Vec, offset: u32, value: u32) { +fn set_field(code: &mut Code, offset: u32, value: u32) { // The complete payload was initialized. Zero-valued fields need no rewrite. if value != 0 { - code.extend(MOV_RSP_DISP8_IMM32); - code.push((DATA_OFFSET + offset) as u8); - code.extend(value.to_le_bytes()); + code.asm() + .mov_rm_imm32(Size::Dword, scratch(offset), value as i32); } } -fn stage(code: &mut Vec, register: Register, bytes: u8, offset: u32) { +fn stage(code: &mut Code, register: Register, bytes: u8, offset: u32) { if register == Register::Zero { return; } load(code, register); - code.extend(match bytes { - BYTE_BYTES => MOV_RSP_DISP8_AL, - HALFWORD_BYTES => MOV_RSP_DISP8_AX, - WORD_BYTES => MOV_RSP_DISP8_EAX, - DOUBLEWORD_BYTES => MOV_RSP_DISP8_RAX, + let size = match bytes { + BYTE_BYTES => Size::Byte, + HALFWORD_BYTES => Size::Word, + WORD_BYTES => Size::Dword, + DOUBLEWORD_BYTES => Size::Qword, _ => unreachable!("validated exclusive element width"), - }); - code.push((DATA_OFFSET + offset) as u8); + }; + code.asm().mov_store(size, scratch(offset), Gpr::Rax); } -fn commit(code: &mut Vec, register: Register, bytes: u8, offset: u32) { +fn commit(code: &mut Code, register: Register, bytes: u8, offset: u32) { if register == Register::Zero { return; } - code.extend(match bytes { - BYTE_BYTES => MOVZX_EAX_BYTE_RSP_DISP8, - HALFWORD_BYTES => MOVZX_EAX_WORD_RSP_DISP8, - WORD_BYTES => MOV_EAX_RSP_DISP8, - DOUBLEWORD_BYTES => MOV_RAX_RSP_DISP8, + let mut asm = code.asm(); + match bytes { + BYTE_BYTES => asm.movzx(Size::Dword, Gpr::Rax, Size::Byte, scratch(offset)), + HALFWORD_BYTES => asm.movzx(Size::Dword, Gpr::Rax, Size::Word, scratch(offset)), + WORD_BYTES => asm.mov_load(Size::Dword, Gpr::Rax, scratch(offset)), + DOUBLEWORD_BYTES => asm.mov_load(Size::Qword, Gpr::Rax, scratch(offset)), _ => unreachable!("validated exclusive result width"), - }); - code.push((DATA_OFFSET + offset) as u8); + } store(code, register); } -fn transfer_data(code: &mut Vec, data: Data, element_bytes: u8, loading: bool) { +fn transfer_data(code: &mut Code, data: Data, element_bytes: u8, loading: bool) { let emit = if loading { commit } else { stage }; match data { Data::Scalar(register) => emit(code, register, element_bytes, EXCLUSIVE_VALUE_OFFSET), @@ -269,14 +260,14 @@ fn transfer_data(code: &mut Vec, data: Data, element_bytes: u8, loading: boo /// owner before execution. Each callback handles one exclusive access or CLREX; /// on failure scratch space is released first. pub(crate) fn emit_context( - code: &mut Vec, + code: &mut Code, checked: &CheckedOperand, pc: u64, ) -> Result<(), CompileError> { let operand = &checked.operand; validate(operand)?; - code.extend(SUB_RSP_IMM8); - code.push(SCRATCH_BYTES as u8); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Gpr::Rsp, SCRATCH_BYTES as i8); memory::begin(code); let (base, bytes, operation, order, shape) = match *operand { Operand::Clear => ( @@ -331,7 +322,7 @@ pub(crate) fn emit_context( if let Some(base) = base { memory::address::immediate(code, base, 0, AddressMode::Offset); } else { - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); } memory::request( code, @@ -369,14 +360,14 @@ pub(crate) fn emit_context( } => commit(code, status, WORD_BYTES, EXCLUSIVE_STATUS_OFFSET), Operand::Clear => {} } - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); let cleanup = code.len(); memory::patch_branch(code, callback_failure, cleanup); if let Some(failure) = sp_failure { memory::patch_branch(code, failure, cleanup); } - code.extend(ADD_RSP_IMM8); - code.push(SCRATCH_BYTES as u8); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Gpr::Rsp, SCRATCH_BYTES as i8); memory::address::return_if_failed(code); Ok(()) } @@ -441,7 +432,7 @@ mod tests { } impl Executable { fn new(operand: &Operand) -> Self { - let mut bytes = ENTRY.to_vec(); + let mut bytes = Code::from(ENTRY.to_vec()); emit_context(&mut bytes, operand, TEST_PC).unwrap(); bytes.push(RET); assert!(bytes.len() <= CODE_ALLOCATION_BYTES); @@ -464,7 +455,10 @@ mod tests { unsafe { mprotect(pointer, CODE_ALLOCATION_BYTES, PROT_READ_EXECUTE) }, 0 ); - Self { pointer, bytes } + Self { + pointer, + bytes: bytes.into_bytes(), + } } fn run(&self, state: &mut GuestState, view: &mut MemoryContextView) -> u32 { let context = ExecutionContext { @@ -927,7 +921,7 @@ mod tests { CheckedMemoryProfile::SpAlignmentEnabled, )?)) } - fn emit_context(code: &mut Vec, operand: &Operand, pc: u64) -> Result<(), CompileError> { + fn emit_context(code: &mut Code, operand: &Operand, pc: u64) -> Result<(), CompileError> { super::emit_context( code, &CheckedOperand::new(*operand, CheckedMemoryProfile::SpAlignmentEnabled)?, @@ -1149,7 +1143,7 @@ mod tests { ]; for operand in invalid { assert!(requirements(&operand).is_err()); - let mut code = vec![0x90]; + let mut code = Code::from(vec![0x90]); assert!(emit_context(&mut code, &operand, 0x1000).is_err()); assert_eq!(code, [0x90]); } @@ -1339,8 +1333,8 @@ mod tests { let historical = std::env::var_os("STELA_EXCLUSIVE_HISTORICAL_BODIES").map(std::path::PathBuf::from); for (operand, historical_body) in cases { - let mut enabled = ENTRY.to_vec(); - let mut disabled = ENTRY.to_vec(); + let mut enabled = Code::from(ENTRY.to_vec()); + let mut disabled = Code::from(ENTRY.to_vec()); super::emit_context( &mut enabled, &CheckedOperand::new(operand, CheckedMemoryProfile::SpAlignmentEnabled).unwrap(), diff --git a/crates/stela-compiler/src/x86_64/flags.rs b/crates/stela-compiler/src/x86_64/flags.rs index 3471469b5c..17128abe54 100644 --- a/crates/stela-compiler/src/x86_64/flags.rs +++ b/crates/stela-compiler/src/x86_64/flags.rs @@ -1,11 +1,16 @@ //! FlagM/FlagM2 on the in-memory guest NZCV. use super::load; +use crate::x86_64::asm::{ + Alu, Code, Cond, + Gpr::{Rax, Rcx, Rdx}, + Mem, ShiftOp, + Size::{self, Dword, Qword}, +}; use crate::{ GuestState, aarch64::Register, aarch64::flags::{Operand, SetWidth}, }; -use alloc::vec::Vec; const NZCV_OFFSET: u32 = core::mem::offset_of!(GuestState, nzcv) as u32; const NZCV_SHIFT: u8 = 28; @@ -39,86 +44,11 @@ const EXTERNAL_TO_ARM_TABLE: u32 = NEGATIVE | ((CARRY | OVERFLOW) << (2 * TABLE_ENTRY_BITS)) | ((ZERO | CARRY) << (3 * TABLE_ENTRY_BITS)); -/// Family-local instruction encodings. Immediates/displacements follow separately. -#[derive(Clone, Copy)] -enum Opcode { - Nop, - LoadEaxNzcv, - LoadEcxNzcv, - StoreEaxNzcv, - XorNzcvImmediate, - AndNzcvImmediate, - MoveEcxEax, - MoveEdxEax, - MoveEaxEdx, - MoveEaxImmediate, - RotateRax, - ShiftLeftEax, - ShiftLeftEcx, - ShiftRightEax, - ShiftRightEcx, - ShiftRightEdx, - ShiftRightEaxCl, - AndEaxImmediate, - AndEcxImmediate, - OrEaxImmediate, - OrEaxEcx, - OrEcxEdx, - XorEaxEdx, - TestAl, - TestAx, - SetZeroDl, - ZeroExtendEdxDl, - ShiftLeftEdx, -} -impl Opcode { - fn emit(self, code: &mut Vec) { - code.extend(match self { - Self::Nop => &[0x90][..], - Self::LoadEaxNzcv => &[0x8b, 0x87][..], - Self::LoadEcxNzcv => &[0x8b, 0x8f], - Self::StoreEaxNzcv => &[0x89, 0x87], - Self::XorNzcvImmediate => &[0x81, 0xb7], - Self::AndNzcvImmediate => &[0x81, 0xa7], - Self::MoveEcxEax => &[0x89, 0xc1], - Self::MoveEdxEax => &[0x89, 0xc2], - Self::MoveEaxEdx => &[0x89, 0xd0], - Self::MoveEaxImmediate => &[0xb8], - Self::RotateRax => &[0x48, 0xc1, 0xc8], - Self::ShiftLeftEax => &[0xc1, 0xe0], - Self::ShiftLeftEcx => &[0xc1, 0xe1], - Self::ShiftRightEax => &[0xc1, 0xe8], - Self::ShiftRightEcx => &[0xc1, 0xe9], - Self::ShiftRightEdx => &[0xc1, 0xea], - Self::ShiftRightEaxCl => &[0xd3, 0xe8], - Self::AndEaxImmediate => &[0x25], - Self::AndEcxImmediate => &[0x81, 0xe1], - Self::OrEaxImmediate => &[0x0d], - Self::OrEaxEcx => &[0x09, 0xc8], - Self::OrEcxEdx => &[0x09, 0xd1], - Self::XorEaxEdx => &[0x31, 0xd0], - Self::TestAl => &[0x84, 0xc0], - Self::TestAx => &[0x66, 0x85, 0xc0], - Self::SetZeroDl => &[0x0f, 0x94, 0xc2], - Self::ZeroExtendEdxDl => &[0x0f, 0xb6, 0xd2], - Self::ShiftLeftEdx => &[0xc1, 0xe2], - }); - } - fn immediate(self, code: &mut Vec, value: u32) { - self.emit(code); - code.extend(value.to_le_bytes()); - } - fn shift(self, code: &mut Vec, amount: u8) { - self.emit(code); - code.push(amount); - } -} - -pub(super) fn emit(code: &mut Vec, operand: &Operand) { +pub(super) fn emit(code: &mut Code, operand: &Operand) { match *operand { Operand::InvertCarry => { - Opcode::XorNzcvImmediate.immediate(code, NZCV_OFFSET); - code.extend(CARRY_MASK.to_le_bytes()); + code.asm() + .alu_imm32(Alu::Xor, Dword, nzcv(), CARRY_MASK as i32); return; } Operand::RotateMask { @@ -128,59 +58,62 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { } => { if mask == 0 { // Every instruction keeps a non-empty source-map range. - Opcode::Nop.emit(code); + code.asm().nop(); return; } + let keep = !(u32::from(mask) << NZCV_SHIFT) as i32; if source == Register::Zero { - Opcode::AndNzcvImmediate.immediate(code, NZCV_OFFSET); - code.extend((!(u32::from(mask) << NZCV_SHIFT)).to_le_bytes()); + code.asm().alu_imm32(Alu::And, Dword, nzcv(), keep); return; } load(code, source); + let mut asm = code.asm(); if rotation != 0 { - Opcode::RotateRax.shift(code, rotation); + asm.shift_imm(ShiftOp::Ror, Qword, Rax, rotation); } - Opcode::AndEaxImmediate.immediate(code, u32::from(mask)); - Opcode::ShiftLeftEax.shift(code, NZCV_SHIFT); - Opcode::LoadEcxNzcv.immediate(code, NZCV_OFFSET); - Opcode::AndEcxImmediate.immediate(code, !(u32::from(mask) << NZCV_SHIFT)); - Opcode::OrEaxEcx.emit(code); + asm.alu_accumulator_imm32(Alu::And, Dword, i32::from(mask)); + asm.shift_imm(ShiftOp::Shl, Dword, Rax, NZCV_SHIFT); + asm.mov_load(Dword, Rcx, nzcv()); + asm.alu_imm32(Alu::And, Dword, Rcx, keep); + asm.alu(Alu::Or, Dword, Rax, Rcx); } Operand::Set { source, width } => { if source == Register::Zero { - Opcode::LoadEaxNzcv.immediate(code, NZCV_OFFSET); - Opcode::AndEaxImmediate.immediate(code, CARRY_MASK); - Opcode::OrEaxImmediate.immediate(code, ZERO << NZCV_SHIFT); - Opcode::StoreEaxNzcv.immediate(code, NZCV_OFFSET); + let mut asm = code.asm(); + asm.mov_load(Dword, Rax, nzcv()); + asm.alu_accumulator_imm32(Alu::And, Dword, CARRY_MASK as i32); + asm.alu_accumulator_imm32(Alu::Or, Dword, (ZERO << NZCV_SHIFT) as i32); + asm.mov_store(Dword, nzcv(), Rax); return; } load(code, source); + let mut asm = code.asm(); // TEST observes only the architectural byte/halfword; SETZ's // partial write is zero-extended before the full-register use. - Opcode::MoveEcxEax.emit(code); - Opcode::ShiftRightEcx.shift(code, width.bits() - 1); - Opcode::AndEcxImmediate.immediate(code, 1); - Opcode::ShiftLeftEcx.shift(code, NZCV_SHIFT + NEGATIVE_BIT); - match width { - SetWidth::Byte => Opcode::TestAl, - SetWidth::Halfword => Opcode::TestAx, - } - .emit(code); - Opcode::SetZeroDl.emit(code); - Opcode::ZeroExtendEdxDl.emit(code); - Opcode::ShiftLeftEdx.shift(code, NZCV_SHIFT + ZERO_BIT); - Opcode::OrEcxEdx.emit(code); - Opcode::MoveEdxEax.emit(code); - Opcode::ShiftRightEdx.shift(code, width.bits() - 1); - Opcode::MoveEaxEdx.emit(code); - Opcode::ShiftRightEax.shift(code, 1); - Opcode::XorEaxEdx.emit(code); - Opcode::AndEaxImmediate.immediate(code, OVERFLOW); - Opcode::ShiftLeftEax.shift(code, NZCV_SHIFT); - Opcode::OrEaxEcx.emit(code); - Opcode::LoadEcxNzcv.immediate(code, NZCV_OFFSET); - Opcode::AndEcxImmediate.immediate(code, CARRY_MASK); - Opcode::OrEaxEcx.emit(code); + asm.mov(Dword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, Dword, Rcx, width.bits() - 1); + asm.alu_imm32(Alu::And, Dword, Rcx, 1); + asm.shift_imm(ShiftOp::Shl, Dword, Rcx, NZCV_SHIFT + NEGATIVE_BIT); + let tested = match width { + SetWidth::Byte => Size::Byte, + SetWidth::Halfword => Size::Word, + }; + asm.test(tested, Rax, Rax); + asm.setcc(Cond::E, Rdx); + asm.movzx(Dword, Rdx, Size::Byte, Rdx); + asm.shift_imm(ShiftOp::Shl, Dword, Rdx, NZCV_SHIFT + ZERO_BIT); + asm.alu(Alu::Or, Dword, Rcx, Rdx); + asm.mov(Dword, Rdx, Rax); + asm.shift_imm(ShiftOp::Shr, Dword, Rdx, width.bits() - 1); + asm.mov(Dword, Rax, Rdx); + asm.shift_imm(ShiftOp::Shr, Dword, Rax, 1); + asm.alu(Alu::Xor, Dword, Rax, Rdx); + asm.alu_accumulator_imm32(Alu::And, Dword, OVERFLOW as i32); + asm.shift_imm(ShiftOp::Shl, Dword, Rax, NZCV_SHIFT); + asm.alu(Alu::Or, Dword, Rax, Rcx); + asm.mov_load(Dword, Rcx, nzcv()); + asm.alu_imm32(Alu::And, Dword, Rcx, CARRY_MASK as i32); + asm.alu(Alu::Or, Dword, Rax, Rcx); } Operand::ArmToExternal => { emit_conversion(code, ARM_TO_EXTERNAL_TABLE, ARM_INDEX_SHIFT, ARM_INDEX_MASK); @@ -194,24 +127,29 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { ); } } - Opcode::StoreEaxNzcv.immediate(code, NZCV_OFFSET); + code.asm().mov_store(Dword, nzcv(), Rax); } -fn emit_conversion(code: &mut Vec, table: u32, index_shift: u8, index_mask: u32) { - Opcode::LoadEcxNzcv.immediate(code, NZCV_OFFSET); +/// The guest NZCV word. +fn nzcv() -> Mem { + super::frame(NZCV_OFFSET) +} + +fn emit_conversion(code: &mut Code, table: u32, index_shift: u8, index_mask: u32) { + let mut asm = code.asm(); + asm.mov_load(Dword, Rcx, nzcv()); // Each architectural flag result occupies one nibble of the immediate. - Opcode::ShiftRightEcx.shift(code, index_shift); - Opcode::AndEcxImmediate.immediate(code, index_mask); - Opcode::MoveEaxImmediate.immediate(code, table); - Opcode::ShiftRightEaxCl.emit(code); - Opcode::AndEaxImmediate.immediate(code, u32::from(NZCV_NIBBLE)); - Opcode::ShiftLeftEax.shift(code, NZCV_SHIFT); + asm.shift_imm(ShiftOp::Shr, Dword, Rcx, index_shift); + asm.alu_imm32(Alu::And, Dword, Rcx, index_mask as i32); + asm.mov_imm32(Rax, table); + asm.shift_cl(ShiftOp::Shr, Dword, Rax); + asm.alu_accumulator_imm32(Alu::And, Dword, i32::from(NZCV_NIBBLE)); + asm.shift_imm(ShiftOp::Shl, Dword, Rax, NZCV_SHIFT); } #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; #[test] fn external_table_matches_all_architectural_flag_inputs() { @@ -240,7 +178,7 @@ mod tests { #[test] fn zero_rotate_mask_keeps_a_nonempty_mapping_interval() { - let mut code = Vec::new(); + let mut code = Code::new(); emit( &mut code, &Operand::RotateMask { diff --git a/crates/stela-compiler/src/x86_64/fp_register.rs b/crates/stela-compiler/src/x86_64/fp_register.rs index bc8db44a8c..63507aed91 100644 --- a/crates/stela-compiler/src/x86_64/fp_register.rs +++ b/crates/stela-compiler/src/x86_64/fp_register.rs @@ -1,5 +1,6 @@ //! FPCR/FPSR reads and writes, using integer instructions only. use super::{load, store}; +use crate::x86_64::asm::{Alu, Code, Gpr::Rax, Size}; use crate::{ GuestState, aarch64::{ @@ -7,28 +8,24 @@ use crate::{ fp_register::{Operand, SystemRegister}, }, }; -use alloc::vec::Vec; const FPCR_OFFSET: u32 = core::mem::offset_of!(GuestState, fpcr) as u32; const FPSR_OFFSET: u32 = core::mem::offset_of!(GuestState, fpsr) as u32; -const MOV_EAX_STATE_DISP32: &[u8] = &[0x8b, 0x87]; -const MOV_STATE_DISP32_EAX: &[u8] = &[0x89, 0x87]; -const AND_EAX_IMM32: u8 = 0x25; -const NOP: u8 = 0x90; -fn field_offset(register: SystemRegister) -> u32 { - match register { +/// The register's field of the guest frame. +fn field(register: SystemRegister) -> crate::x86_64::asm::Mem { + super::frame(match register { SystemRegister::Fpcr => FPCR_OFFSET, SystemRegister::Fpsr => FPSR_OFFSET, - } + }) } -fn mask(code: &mut Vec, register: SystemRegister) { - code.push(AND_EAX_IMM32); - code.extend(register.mask().to_le_bytes()); +fn mask(code: &mut Code, register: SystemRegister) { + code.asm() + .alu_accumulator_imm32(Alu::And, Size::Dword, register.mask() as i32); } -pub(super) fn emit(code: &mut Vec, operand: &Operand) { +pub(super) fn emit(code: &mut Code, operand: &Operand) { match *operand { Operand::Read { register, @@ -37,13 +34,12 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { if destination == Register::Zero { // Access is enabled by this profile. Keep a distinct native // interval for the discarded read under strict source maps. - code.push(NOP); + code.asm().nop(); return; } // The u32 load never reads the adjacent field. AND EAX masks raw // imported storage and zero-extends before the full Xt store. - code.extend(MOV_EAX_STATE_DISP32); - code.extend(field_offset(register).to_le_bytes()); + code.asm().mov_load(Size::Dword, Rax, field(register)); mask(code, register); store(code, destination); } @@ -56,8 +52,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { } // A four-byte replacement cannot corrupt the other FP field. // The common XZR load supplies XOR EAX,EAX for a zero write. - code.extend(MOV_STATE_DISP32_EAX); - code.extend(field_offset(register).to_le_bytes()); + code.asm().mov_store(Size::Dword, field(register), Rax); } } } diff --git a/crates/stela-compiler/src/x86_64/integer_math.rs b/crates/stela-compiler/src/x86_64/integer_math.rs index 2f0626494a..0fee8677fc 100644 --- a/crates/stela-compiler/src/x86_64/integer_math.rs +++ b/crates/stela-compiler/src/x86_64/integer_math.rs @@ -1,63 +1,78 @@ //! Integer multiply, divide, shifts and bit operations. Guest NZCV is unchanged. -use super::{Register, Shift, Width, integer_unary, load, right_operand, store}; +use super::{ + Register, Shift, Width, + asm::{Alu, Asm, Cond, Gpr, Rm, ShiftOp, Size, Unary}, + integer_unary, load_with, right_operand_with, store_with, +}; +use crate::x86_64::asm::Code; use crate::{ TargetCpu, aarch64::integer_math::{Kind, Operand}, }; -use alloc::vec::Vec; -/// SHR RCX,imm8 and OR RAX,RCX (REX.W widens both). -const MOV_ECX_EAX: [u8; 2] = [0x89, 0xc1]; -const SHR_ECX_IMM8: [u8; 2] = [0xc1, 0xe9]; -const OR_EAX_ECX: [u8; 2] = [0x09, 0xc8]; -const NEG_EAX: [u8; 2] = [0xf7, 0xd8]; -const ADD_EAX_IMM8: [u8; 2] = [0x83, 0xc0]; -const REX_W: u8 = 0x48; +use Gpr::{Rax, Rcx, Rdx}; -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { - load(code, operand.left); +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { + emit_with(&mut code.asm(), operand, target); +} + +fn size(width: Width) -> Size { + Size::of(width == Width::X64) +} + +pub(super) fn emit_with(asm: &mut Asm, operand: &Operand, target: TargetCpu) { + load_with(asm, operand.left); match operand.kind { Kind::LeadingZeros { width } | Kind::LeadingSignBits { width } => { let sign_bits = matches!(operand.kind, Kind::LeadingSignBits { .. }); + let size = size(width); if sign_bits { - let rex = if width == Width::X64 { - &[0x48][..] - } else { - &[][..] - }; - code.extend(rex); - code.extend([0x89, 0xc1]); // mov (r/e)cx,(r/e)ax - code.extend(rex); - code.extend([0xc1, 0xf9, if width == Width::X64 { 63 } else { 31 }]); // sar sign mask - code.extend(rex); - code.extend([0x31, 0xc8]); // xor (r/e)ax,(r/e)cx: nonnegative original/complement + // XOR with the sign mask: the value or its complement, nonnegative. + asm.mov(size, Rcx, Rax); + asm.shift_imm(ShiftOp::Sar, size, Rcx, size.bits() as u8 - 1); + asm.alu(Alu::Xor, size, Rax, Rcx); } if target.data_independent_timing() { - leading_zeros_without_bsr(code, width, sign_bits); - store(code, operand.destination); - return; + leading_zeros_without_bsr(asm, size, sign_bits); + } else if target.supports(TargetCpu::Lzcnt) { + // LZCNT counts a zero input as the operand width. + asm.lzcnt(size, Rax, Rax); + if sign_bits { + // Omit the sign bit itself. + asm.alu_imm8(Alu::Sub, Size::Dword, Rax, 1); + } + } else { + let bits = size.bits(); + asm.bsr(size, Rax, Rax); + // MOV preserves BSR's ZF; BSR leaves a zero input's + // destination undefined, so CMOVZ replaces it before use. + asm.mov_imm32(Rcx, 2 * bits - 1); + asm.cmov(Cond::E, size, Rax, Rcx); + // Nonzero: (width-1)-MSB. Zero: (2*width-1) XOR (width-1)=width. + asm.alu_imm8(Alu::Xor, size, Rax, (bits - 1) as i8); + if sign_bits { + // Omit the sign bit itself. + asm.alu_imm8(Alu::Sub, Size::Dword, Rax, 1); + } } - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x0f, 0xbd, 0xc0]); // bsr (r/e)ax,(r/e)ax - let bits = if width == Width::X64 { 64u32 } else { 32 }; - code.push(0xb9); // mov ecx,2*width-1: preserves BSR ZF - code.extend((2 * bits - 1).to_le_bytes()); - if width == Width::X64 { - code.push(0x48); - } - // BSR's zero-input destination is undefined: replace it before use. - code.extend([0x0f, 0x44, 0xc1]); // cmovz (r/e)ax,(r/e)cx - if width == Width::X64 { - code.push(0x48); - } - // Nonzero: (width-1)-MSB. Zero: (2*width-1) XOR (width-1)=width. - code.extend([0x83, 0xf0, (bits - 1) as u8]); - if sign_bits { - code.extend([0x83, 0xe8, 1]); // sub eax,1: omit the sign bit itself - } - store(code, operand.destination); + store_with(asm, operand.destination); + return; + } + Kind::ReverseBits { width } + if target.supports(TargetCpu::Gfni) && !target.data_independent_timing() => + { + // The affine transform by the anti-diagonal bit matrix reverses + // each byte's bits. XMM0 and XMM1 are scratch: no guest vector + // stays in them across an integer instruction. The DIT + // lowering keeps to the audited shifts and masks. + const REVERSE_EACH_BYTE: u64 = 0x8040_2010_0804_0201; + asm.movq_to_xmm(0, Rax); + asm.mov_imm64(Rdx, REVERSE_EACH_BYTE); + asm.movq_to_xmm(1, Rdx); + asm.gf2p8affineqb(0, Rm::Xmm(1), 0); + asm.movq_from_xmm(Rax, 0); + asm.bswap(size(width), Rax); + store_with(asm, operand.destination); return; } Kind::ReverseBits { width } => { @@ -66,94 +81,100 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { (2, 0x3333333333333333), (4, 0x0f0f0f0f0f0f0f0f), ] { - swap_groups(code, width, shift, mask); + swap_groups(asm, width, shift, mask); } - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x0f, 0xc8]); // bswap: complete reversal of the independently reversed bytes - store(code, operand.destination); + // BSWAP completes the reversal of the independently reversed bytes. + asm.bswap(size(width), Rax); + store_with(asm, operand.destination); return; } Kind::ReverseBytes { width, group_bytes } => { if width == Width::X64 && group_bytes == 2 { - swap_groups(code, width, 8, 0x00ff00ff00ff00ff); + swap_groups(asm, width, 8, 0x00ff00ff00ff00ff); } else { - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x0f, 0xc8]); // bswap (r/e)ax + asm.bswap(size(width), Rax); let rotate = match (width, group_bytes) { (Width::W32, 2) => Some(16), (Width::X64, 4) => Some(32), _ => None, }; if let Some(amount) = rotate { - if width == Width::X64 { - code.push(0x48); - } - code.extend([0xc1, 0xc8, amount]); // ror restores container order + // ROR restores container order. + asm.shift_imm(ShiftOp::Ror, size(width), Rax, amount); } } - store(code, operand.destination); + store_with(asm, operand.destination); return; } _ => {} } - right_operand(code, operand.right, Width::X64, Shift::Lsl, 0); + right_operand_with(asm, operand.right, Width::X64, Shift::Lsl, 0); match operand.kind { + Kind::VariableShift { width, shift } + if shift != Shift::Ror + && target.supports(TargetCpu::Bmi2) + && !target.data_independent_timing() => + { + // One flagless uop; SHL r,CL is three on Skylake-family cores. The + // count is modulo the width, as Arm's, and a 32-bit result + // clears Xd's upper half. The DIT lowering keeps to the audited + // CL shifts. + let op = match shift { + Shift::Lsl => ShiftOp::Shl, + Shift::Lsr => ShiftOp::Shr, + _ => ShiftOp::Sar, + }; + asm.shift_x(op, size(width), Rax, Rax, Rcx); + store_with(asm, operand.destination); + return; + } Kind::VariableShift { width, shift } => { - // A zero shift must still clear Xd's upper half for a W result. + // A zero shift must still clear Xd's upper half for a W result, + // so the W form starts with a zero-extending move. if width == Width::W32 { - code.extend([0x89, 0xc0]); - } else { - code.push(0x48); + asm.mov(Size::Dword, Rax, Rax); } - // CL masking implements Arm's modulo-width count without BMI2. - code.extend([ - 0xd3, - match shift { - Shift::Lsl => 0xe0, - Shift::Lsr => 0xe8, - Shift::Asr => 0xf8, - Shift::Ror => 0xc8, - }, - ]); - store(code, operand.destination); + // CL masking implements Arm's modulo-width count. + let op = match shift { + Shift::Lsl => ShiftOp::Shl, + Shift::Lsr => ShiftOp::Shr, + Shift::Asr => ShiftOp::Sar, + Shift::Ror => ShiftOp::Ror, + }; + asm.shift_cl(op, size(width), Rax); + store_with(asm, operand.destination); return; } Kind::Extract { width, amount } => { - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x0f, 0xac, 0xc1, amount]); // shrd (r/e)cx,(r/e)ax,imm - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x89, 0xc8]); // mov (r/e)ax,(r/e)cx; W also clears at shift zero - store(code, operand.destination); + asm.shrd_imm(size(width), Rcx, Rax, amount); + // The W move also clears the upper half at shift zero. + asm.mov(size(width), Rax, Rcx); + store_with(asm, operand.destination); return; } _ => {} } if let Kind::Divide { signed, width } = operand.kind { - divide(code, signed, width); - store(code, operand.destination); + divide(asm, signed, width); + store_with(asm, operand.destination); return; } let width = match operand.kind { Kind::High { signed } => { // One-operand x86 multiply produces the complete RDX:RAX product. - code.extend([0x48, 0xf7, if signed { 0xe9 } else { 0xe1 }]); - code.extend([0x48, 0x89, 0xd0]); // mov rax,rdx - store(code, operand.destination); + let op = if signed { Unary::Imul } else { Unary::Mul }; + asm.unary(op, Size::Qword, Rcx); + asm.mov(Size::Qword, Rax, Rdx); + store_with(asm, operand.destination); return; } Kind::Long { signed } => { if signed { - code.extend([0x48, 0x63, 0xc0, 0x48, 0x63, 0xc9]); // movsxd rax,eax; rcx,ecx + asm.movsxd(Rax, Rax); + asm.movsxd(Rcx, Rcx); } else { - code.extend([0x89, 0xc0, 0x89, 0xc9]); // zero-extend both W operands + asm.mov(Size::Dword, Rax, Rax); + asm.mov(Size::Dword, Rcx, Rcx); } Width::X64 } @@ -168,153 +189,325 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { unreachable!("division and unary operations emitted above") } }; - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x0f, 0xaf, 0xc1]); // imul (e/r)ax,(e/r)cx: low product + asm.imul(size(width), Rax, Rcx); if operand.subtract { - if width == Width::X64 { - code.push(0x48); - } - code.extend([0xf7, 0xd8]); // neg (e/r)ax, modulo destination width + // Negation modulo the destination width. + asm.unary(Unary::Neg, size(width), Rax); } // Guest sources are memory-backed and no destination has been committed, // so Rd may alias Rn, Rm or Ra without destroying a still-needed source. if operand.accumulator != Register::Zero { - right_operand(code, operand.accumulator, width, Shift::Lsl, 0); - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x01, 0xc8]); // add (e/r)ax,(e/r)cx + right_operand_with(asm, operand.accumulator, width, Shift::Lsl, 0); + asm.alu(Alu::Add, size(width), Rax, Rcx); } - store(code, operand.destination); + store_with(asm, operand.destination); } -/// Swap adjacent bit groups with baseline shifts/masks. Inputs remain in RAX; -/// only caller-saved RCX/RDX are scratch. No BMI, LZCNT, SIMD or helper calls. /// CLZ (or, after the sign fold, CLS) without BSR or LZCNT, neither on /// Intel's data operand independent timing list: every bit below the /// highest set one is set by shifted ORs, so the count is the width less the /// population count of the smear. -fn leading_zeros_without_bsr(code: &mut Vec, width: Width, sign_bits: bool) { - let bits: u8 = if width == Width::X64 { 64 } else { 32 }; +fn leading_zeros_without_bsr(asm: &mut Asm, size: Size, sign_bits: bool) { + let bits = size.bits() as u8; let mut shift = 1; while shift < bits { - wide(code, width); - code.extend(MOV_ECX_EAX); - wide(code, width); - code.extend(SHR_ECX_IMM8); - code.push(shift); - wide(code, width); - code.extend(OR_EAX_ECX); + asm.mov(size, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, size, Rcx, shift); + asm.alu(Alu::Or, size, Rax, Rcx); shift *= 2; } - integer_unary::population_count(code, width); + integer_unary::population_count(asm, size == Size::Qword); // The count fits 32 bits: bits - popcount (less the sign bit for CLS). - code.extend(NEG_EAX); - code.extend(ADD_EAX_IMM8); - code.push(bits - u8::from(sign_bits)); + asm.unary(Unary::Neg, Size::Dword, Rax); + asm.alu_imm8( + Alu::Add, + Size::Dword, + Rax, + (bits - u8::from(sign_bits)) as i8, + ); } -fn wide(code: &mut Vec, width: Width) { +/// Swap adjacent `shift`-bit groups of RAX with baseline shifts and masks; +/// RCX and RDX are scratch. +fn swap_groups(asm: &mut Asm, width: Width, shift: u8, mask: u64) { + let size = size(width); + asm.mov(size, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, size, Rax, shift); if width == Width::X64 { - code.push(REX_W); - } -} - -fn swap_groups(code: &mut Vec, width: Width, shift: u8, mask: u64) { - let rex = if width == Width::X64 { - &[0x48][..] + asm.mov_imm64(Rdx, mask); + asm.alu(Alu::And, size, Rax, Rdx); + asm.alu(Alu::And, size, Rcx, Rdx); } else { - &[][..] - }; - code.extend(rex); - code.extend([0x89, 0xc1]); // mov (r/e)cx,(r/e)ax - code.extend(rex); - code.extend([0xc1, 0xe8, shift]); // shr (r/e)ax,shift - if width == Width::X64 { - code.extend([0x48, 0xba]); // movabs rdx,mask - code.extend(mask.to_le_bytes()); - code.extend([0x48, 0x21, 0xd0, 0x48, 0x21, 0xd1]); // and rax,rdx; and rcx,rdx - } else { - code.push(0x25); // and eax,mask32 - code.extend((mask as u32).to_le_bytes()); - code.extend([0x81, 0xe1]); // and ecx,mask32 - code.extend((mask as u32).to_le_bytes()); + asm.alu_accumulator_imm32(Alu::And, size, mask as u32 as i32); + asm.alu_imm32(Alu::And, size, Rcx, mask as u32 as i32); } - code.extend(rex); - code.extend([0xc1, 0xe1, shift]); // shl (r/e)cx,shift - code.extend(rex); - code.extend([0x09, 0xc8]); // or (r/e)ax,(r/e)cx -} - -fn branch(code: &mut Vec, opcode: Option) -> usize { - if let Some(opcode) = opcode { - code.extend([0x0f, opcode]); - } else { - code.push(0xe9); - } - let displacement = code.len(); - code.extend([0; 4]); - displacement -} - -fn bind(code: &mut [u8], displacement: usize, target: usize) { - let offset = i32::try_from(target as i64 - (displacement + 4) as i64) - .expect("bounded integer division lowering"); - code[displacement..displacement + 4].copy_from_slice(&offset.to_le_bytes()); + asm.shift_imm(ShiftOp::Shl, size, Rcx, shift); + asm.alu(Alu::Or, size, Rax, Rcx); } /// RAX and RCX hold the operands. x86 DIV/IDIV fault on a zero divisor, and /// IDIV also on MIN / -1, where Arm returns zero or the wrapped MIN. A divisor /// of -1 is handled by negation instead of IDIV. -fn divide(code: &mut Vec, signed: bool, width: Width) { +fn divide(asm: &mut Asm, signed: bool, width: Width) { + let size = size(width); if width == Width::W32 { - code.extend([0x89, 0xc0]); // mov eax,eax: clear discarded high dividend - } else { - code.push(0x48); + // Clear the discarded high dividend. + asm.mov(Size::Dword, Rax, Rax); } - code.extend([0x85, 0xc9]); // test (r/e)cx,(r/e)cx - let zero = branch(code, Some(0x84)); + asm.test(size, Rcx, Rcx); + let zero = asm.jcc(Cond::E); let mut minus_one_done = None; if signed { - if width == Width::X64 { - code.push(0x48); - } - code.extend([0x83, 0xf9, 0xff]); // cmp (r/e)cx,-1 - let ordinary = branch(code, Some(0x85)); - if width == Width::X64 { - code.push(0x48); - } - code.extend([0xf7, 0xd8]); // neg (r/e)ax, including MIN wraparound - minus_one_done = Some(branch(code, None)); - let target = code.len(); - bind(code, ordinary, target); - if width == Width::X64 { - code.push(0x48); - } - code.push(0x99); // cqo or cdq: signed high dividend + asm.alu_imm8(Alu::Cmp, size, Rcx, -1); + let ordinary = asm.jcc(Cond::Ne); + // Negation, including MIN wraparound. + asm.unary(Unary::Neg, size, Rax); + minus_one_done = Some(asm.jmp()); + asm.bind(ordinary); + asm.sign_extend_accumulator(size); } else { - code.extend([0x31, 0xd2]); // xor edx,edx: unsigned high dividend + // Unsigned high dividend. + asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); } - if width == Width::X64 { - code.push(0x48); - } - code.extend([0xf7, if signed { 0xf9 } else { 0xf1 }]); // idiv/div (r/e)cx - let ordinary_done = branch(code, None); - let target = code.len(); - bind(code, zero, target); - code.extend([0x31, 0xc0]); // zero divisor produces zero, never native #DE - let target = code.len(); - bind(code, ordinary_done, target); - if let Some(displacement) = minus_one_done { - bind(code, displacement, target); + let op = if signed { Unary::Idiv } else { Unary::Div }; + asm.unary(op, size, Rcx); + let ordinary_done = asm.jmp(); + asm.bind(zero); + // A zero divisor produces zero, never a native #DE. + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); + asm.bind(ordinary_done); + if let Some(patch) = minus_one_done { + asm.bind(patch); } } #[cfg(test)] mod tests { use super::*; + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + use crate::GuestState; + + const VALUES: [u64; 12] = [ + 0, + 1, + 0x7fff, + 0x8000_0000, + 0xffff_ffff, + 0x1_0000_0000, + 0x0000_0001_ffff_ffff, + 0x7fff_ffff_ffff_ffff, + 0x8000_0000_0000_0000, + 0xffff_ffff_0000_0000, + 0x0123_4567_89ab_cdef, + u64::MAX, + ]; + + /// The result of `kind` on X1 = `value` after running its code on the + /// host. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + fn run(kind: Kind, target: TargetCpu, value: u64, right: u64) -> u64 { + let mut code = Code::new(); + emit(&mut code, &operand(kind), target); + let mut state = GuestState::default(); + state.x[1] = value; + state.x[2] = right; + super::super::native::run(&code, &mut state); + state.x[0] + } + + fn lzcnt(code: &[u8]) -> bool { + code.windows(3).any(|bytes| bytes == [0xf3, 0x0f, 0xbd]) + || code + .windows(4) + .any(|bytes| bytes == [0xf3, 0x48, 0x0f, 0xbd]) + } + + #[test] + fn leading_counts_use_lzcnt_only_where_the_host_has_it() { + for width in [Width::W32, Width::X64] { + for kind in [ + Kind::LeadingZeros { width }, + Kind::LeadingSignBits { width }, + ] { + let code = |target| { + let mut code = Code::new(); + emit(&mut code, &operand(kind), target); + code + }; + let (fast, fallback) = (code(TargetCpu::Lzcnt), code(TargetCpu::X86_64_V2)); + assert!(lzcnt(&fast) && !lzcnt(&fallback), "{kind:?}"); + assert!(fast.len() < fallback.len()); + assert!(!lzcnt(&code( + TargetCpu::Lzcnt.with_data_independent_timing() + ))); + } + } + } + + /// SHLX/SHRX/SARX's VEX opcode byte (map 0F38, opcode F7). + fn shift_x(code: &[u8]) -> bool { + code.windows(4) + .any(|bytes| bytes[0] == 0xc4 && bytes[1] & 0x1f == 2 && bytes[3] == 0xf7) + } + + #[test] + fn variable_shifts_use_bmi2_except_rotation() { + for width in [Width::W32, Width::X64] { + for shift in [Shift::Lsl, Shift::Lsr, Shift::Asr, Shift::Ror] { + let kind = Kind::VariableShift { width, shift }; + let code = |target| { + let mut code = Code::new(); + emit(&mut code, &operand(kind), target); + code + }; + let (fast, fallback) = (code(TargetCpu::Bmi2), code(TargetCpu::X86_64_V2)); + assert!(!shift_x(&fallback)); + assert_eq!(shift_x(&fast), shift != Shift::Ror, "{kind:?}"); + if shift == Shift::Ror { + assert_eq!(fast, fallback); + } + } + } + } + + /// The variable shifts on the host with and without BMI2, against Arm's + /// modulo-width counts. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn variable_shifts_match_on_the_host() { + let host = TargetCpu::detect(); + for target in [TargetCpu::X86_64_V2, TargetCpu::Bmi2] { + if !host.supports(target) { + continue; + } + for value in VALUES { + for count in [0u64, 1, 31, 32, 33, 63, 64, 65, 0xffff_ffff_ffff_ffc1] { + let narrow = value as u32; + let (w, x) = ((count % 32) as u32, (count % 64) as u32); + for (width, shift, expected) in [ + (Width::W32, Shift::Lsl, u64::from(narrow << w)), + (Width::W32, Shift::Lsr, u64::from(narrow >> w)), + ( + Width::W32, + Shift::Asr, + u64::from((narrow as i32 >> w) as u32), + ), + (Width::W32, Shift::Ror, u64::from(narrow.rotate_right(w))), + (Width::X64, Shift::Lsl, value << x), + (Width::X64, Shift::Lsr, value >> x), + (Width::X64, Shift::Asr, (value as i64 >> x) as u64), + (Width::X64, Shift::Ror, value.rotate_right(x)), + ] { + let kind = Kind::VariableShift { width, shift }; + assert_eq!( + run(kind, target, value, count), + expected, + "{kind:?} {value:#x} {count} {target:?}" + ); + } + } + } + } + } + + /// GF2P8AFFINEQB (66 0F 3A CE). + fn gfni(code: &[u8]) -> bool { + code.windows(3).any(|bytes| bytes == [0x3a, 0xce, 0xc1]) + } + + #[test] + fn bit_reversal_uses_gfni_only_where_the_host_has_it() { + for width in [Width::W32, Width::X64] { + let kind = Kind::ReverseBits { width }; + let code = |target| { + let mut code = Code::new(); + emit(&mut code, &operand(kind), target); + code + }; + let (fast, fallback) = (code(TargetCpu::Gfni), code(TargetCpu::X86_64_V2)); + assert!(gfni(&fast) && !gfni(&fallback), "{kind:?}"); + assert!(fast.len() < fallback.len()); + } + } + + /// RBIT on the host with and without GFNI, against Rust's reversal. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn bit_reversal_matches_on_the_host() { + let host = TargetCpu::detect(); + for target in [TargetCpu::X86_64_V2, TargetCpu::Gfni] { + if !host.supports(target) { + continue; + } + for value in VALUES { + let narrow = Kind::ReverseBits { width: Width::W32 }; + let wide = Kind::ReverseBits { width: Width::X64 }; + assert_eq!( + run(narrow, target, value, 0), + u64::from((value as u32).reverse_bits()), + "{value:#x} {target:?}" + ); + assert_eq!(run(wide, target, value, 0), value.reverse_bits()); + } + } + } + + /// CLZ and CLS on the host through LZCNT, BSR and the DIT smear, against + /// Rust's counts. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn leading_counts_match_on_the_host() { + let host = TargetCpu::detect(); + for target in [ + TargetCpu::X86_64_V2, + TargetCpu::Lzcnt, + TargetCpu::DataIndependentTiming, + ] { + if !host.supports(target) { + continue; + } + for value in VALUES { + let narrow = value as u32; + let wide_fold = value ^ ((value as i64 >> 63) as u64); + let narrow_fold = narrow ^ ((narrow as i32 >> 31) as u32); + for (kind, expected) in [ + ( + Kind::LeadingZeros { width: Width::W32 }, + narrow.leading_zeros(), + ), + ( + Kind::LeadingZeros { width: Width::X64 }, + value.leading_zeros(), + ), + ( + Kind::LeadingSignBits { width: Width::W32 }, + narrow_fold.leading_zeros() - 1, + ), + ( + Kind::LeadingSignBits { width: Width::X64 }, + wide_fold.leading_zeros() - 1, + ), + ] { + assert_eq!( + run(kind, target, value, 0), + u64::from(expected), + "{kind:?} {value:#x} {target:?}" + ); + } + } + } + } + + fn operand(kind: Kind) -> Operand { + Operand { + kind, + subtract: false, + destination: Register::X(0), + left: Register::X(1), + right: Register::X(2), + accumulator: Register::Zero, + } + } /// The smear-and-count model of the DIT lowering, on every leading-zero /// count of both widths. @@ -341,18 +534,10 @@ mod tests { Kind::LeadingZeros { width }, Kind::LeadingSignBits { width }, ] { - let operand = Operand { - kind, - subtract: false, - destination: Register::X(0), - left: Register::X(1), - right: Register::X(2), - accumulator: Register::Zero, - }; - let mut ordinary = Vec::new(); - emit(&mut ordinary, &operand, TargetCpu::Baseline); - let mut timed = Vec::new(); - emit(&mut timed, &operand, TargetCpu::DataIndependentTiming); + let mut ordinary = Code::new(); + emit(&mut ordinary, &operand(kind), TargetCpu::Baseline); + let mut timed = Code::new(); + emit(&mut timed, &operand(kind), TargetCpu::DataIndependentTiming); let bsr = |code: &[u8]| code.windows(2).any(|pair| pair == [0x0f, 0xbd]); assert!(bsr(&ordinary)); assert!(!bsr(&timed)); diff --git a/crates/stela-compiler/src/x86_64/integer_minmax.rs b/crates/stela-compiler/src/x86_64/integer_minmax.rs index 0a325d48b5..3bd5a8f694 100644 --- a/crates/stela-compiler/src/x86_64/integer_minmax.rs +++ b/crates/stela-compiler/src/x86_64/integer_minmax.rs @@ -1,61 +1,43 @@ //! FEAT_CSSC min/max through CMP and CMOV. use super::{Register, Shift, Width, load, right_operand, store}; use crate::aarch64::integer_minmax::{Kind, Operand, Right}; -use alloc::vec::Vec; +use crate::x86_64::asm::{ + Alu, Code, Cond, + Gpr::{Rax, Rcx}, + Size, +}; -const REX_W: u8 = 0x48; -const NOP: u8 = 0x90; -const MOV_ECX_IMM32: u8 = 0xb9; // MOV ECX,imm32 -const MOV_RCX_IMM32: &[u8] = &[REX_W, 0xc7, 0xc1]; -const CMP_EAX_ECX: &[u8] = &[0x39, 0xc8]; -const OPCODE_ESCAPE: u8 = 0x0f; -const MODRM_EAX_ECX: u8 = 0xc1; -const CMOVG: u8 = 0x4f; -const CMOVL: u8 = 0x4c; -const CMOVA: u8 = 0x47; -const CMOVB: u8 = 0x42; - -pub(super) fn emit(code: &mut Vec, operand: &Operand) { +pub(super) fn emit(code: &mut Code, operand: &Operand) { if operand.destination == Register::Zero { - code.push(NOP); + code.asm().nop(); return; } load(code, operand.left); match operand.right { Right::Register(register) => right_operand(code, register, Width::X64, Shift::Lsl, 0), - Right::Immediate(value) => { - let immediate = if operand.kind.signed() { - i32::from(value as i8) as u32 + Right::Immediate(value) if operand.kind.signed() => { + let immediate = i32::from(value as i8); + if operand.width == Width::X64 && immediate < 0 { + // Sign-extended to 64 bits. + code.asm().mov_rm_imm32(Size::Qword, Rcx, immediate); } else { - u32::from(value) - }; - if operand.width == Width::X64 && operand.kind.signed() && (value as i8) < 0 { - code.extend(MOV_RCX_IMM32); - } else { - code.push(MOV_ECX_IMM32); + code.asm().mov_imm32(Rcx, immediate as u32); } - code.extend(immediate.to_le_bytes()); } + Right::Immediate(value) => code.asm().mov_imm32(Rcx, u32::from(value)), } // All flag-changing source preparation precedes CMP, including ZR loads. - if operand.width == Width::X64 { - code.push(REX_W); - } - code.extend(CMP_EAX_ECX); - if operand.width == Width::X64 { - code.push(REX_W); - } + let size = Size::of(operand.width == Width::X64); + let mut asm = code.asm(); + asm.alu(Alu::Cmp, size, Rax, Rcx); // A false 32-bit CMOV also clears the destination's high half. - code.extend([ - OPCODE_ESCAPE, - match operand.kind { - Kind::SignedMinimum => CMOVG, - Kind::SignedMaximum => CMOVL, - Kind::UnsignedMinimum => CMOVA, - Kind::UnsignedMaximum => CMOVB, - }, - MODRM_EAX_ECX, - ]); + let replace = match operand.kind { + Kind::SignedMinimum => Cond::G, + Kind::SignedMaximum => Cond::L, + Kind::UnsignedMinimum => Cond::A, + Kind::UnsignedMaximum => Cond::B, + }; + asm.cmov(replace, size, Rax, Rcx); store(code, operand.destination); } @@ -63,7 +45,17 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { mod tests { use super::*; use alloc::vec; - use alloc::vec::Vec; + + const REX_W: u8 = 0x48; + const NOP: u8 = 0x90; + const MOV_ECX_IMM32: u8 = 0xb9; + const MOV_RCX_IMM32: &[u8] = &[REX_W, 0xc7, 0xc1]; + const OPCODE_ESCAPE: u8 = 0x0f; + const MODRM_EAX_ECX: u8 = 0xc1; + const CMOVG: u8 = 0x4f; + const CMOVL: u8 = 0x4c; + const CMOVA: u8 = 0x47; + const CMOVB: u8 = 0x42; #[test] fn signed_x_immediates_sign_extend_but_unsigned_do_not() { @@ -75,7 +67,7 @@ mod tests { Kind::UnsignedMinimum, Kind::UnsignedMaximum, ] { - let mut code = Vec::new(); + let mut code = Code::new(); emit( &mut code, &Operand { @@ -86,7 +78,7 @@ mod tests { right: Right::Immediate(value), }, ); - let mut prefix = Vec::new(); + let mut prefix = Code::new(); load(&mut prefix, Register::X(1)); let signed_negative_x = width == Width::X64 && kind.signed() && value >= 0x80; let materialization = if signed_negative_x { @@ -122,7 +114,7 @@ mod tests { (Kind::UnsignedMaximum, CMOVB), ] { for width in [Width::W32, Width::X64] { - let mut code = Vec::new(); + let mut code = Code::new(); emit( &mut code, &Operand { @@ -133,7 +125,7 @@ mod tests { right: Right::Register(Register::Zero), }, ); - let mut prefix = Vec::new(); + let mut prefix = Code::new(); load(&mut prefix, Register::X(1)); right_operand(&mut prefix, Register::Zero, Width::X64, Shift::Lsl, 0); let expected = if width == Width::X64 { @@ -149,16 +141,16 @@ mod tests { } else { vec![0x39, 0xc8, OPCODE_ESCAPE, condition, MODRM_EAX_ECX] }; - let mut suffix = Vec::new(); + let mut suffix = Code::new(); store(&mut suffix, Register::X(1)); - assert_eq!(code, [prefix, expected, suffix].concat()); + assert_eq!(code, [&prefix[..], &expected[..], &suffix[..]].concat()); } } } #[test] fn discarded_result_preserves_a_nonempty_interval() { - let mut code = Vec::new(); + let mut code = Code::new(); emit( &mut code, &Operand { diff --git a/crates/stela-compiler/src/x86_64/integer_unary.rs b/crates/stela-compiler/src/x86_64/integer_unary.rs index 5adfc7dde9..42e130a8c1 100644 --- a/crates/stela-compiler/src/x86_64/integer_unary.rs +++ b/crates/stela-compiler/src/x86_64/integer_unary.rs @@ -1,39 +1,17 @@ //! FEAT_CSSC ABS, CNT and CTZ. -use super::{Register, Width, load, offset, store}; +use super::{ + Register, Width, + asm::{Alu, Asm, Cond, Gpr, Mem, ShiftOp, Size, Unary}, + load_with, offset, store_with, +}; +use crate::x86_64::asm::Code; use crate::{ TargetCpu, aarch64::integer_unary::{Kind, Operand}, }; -use alloc::vec::Vec; -const REX_W: u8 = 0x48; -const NOP: u8 = 0x90; // NOP keeps the source-map interval nonempty. -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const MOV_EAX_IMM32: u8 = 0xb8; -const NEG_EAX: &[u8] = &[0xf7, 0xd8]; -const CMOVS_EAX_ECX: &[u8] = &[0x0f, 0x48, 0xc1]; -const BSF_EAX_RDI_DISP32: &[u8] = &[0x0f, 0xbc, 0x87]; -const TZCNT_EAX_RDI_DISP32: &[u8] = &[0x0f, 0xbc, 0x87]; -const POPCNT_EAX_RDI_DISP32: &[u8] = &[0x0f, 0xb8, 0x87]; -const PREFIX_F3: u8 = 0xf3; -const MOV_ECX_IMM32: u8 = 0xb9; -const CMOVZ_EAX_ECX: &[u8] = &[0x0f, 0x44, 0xc1]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const NEG_ECX: &[u8] = &[0xf7, 0xd9]; -const AND_EAX_ECX: &[u8] = &[0x21, 0xc8]; -const SUB_EAX_ONE: &[u8] = &[0x83, 0xe8, 0x01]; -const SHR_ECX_ONE: &[u8] = &[0xd1, 0xe9]; -const SHR_ECX_IMM8: &[u8] = &[0xc1, 0xe9]; -const SUB_EAX_ECX: &[u8] = &[0x29, 0xc8]; -const ADD_EAX_ECX: &[u8] = &[0x01, 0xc8]; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const AND_EAX_IMM32: u8 = 0x25; -const MOV_RDX_IMM64: &[u8] = &[REX_W, 0xba]; // MOV RDX,imm64 -const AND_ECX_EDX: &[u8] = &[0x21, 0xd1]; -const AND_EAX_EDX: &[u8] = &[0x21, 0xd0]; -const IMUL_EAX_EAX_IMM32: &[u8] = &[0x69, 0xc0]; -const IMUL_EAX_EDX: &[u8] = &[0x0f, 0xaf, 0xc2]; -const SHR_EAX_IMM8: &[u8] = &[0xc1, 0xe8]; +use Gpr::{Rax, Rcx, Rdi, Rdx}; + const PAIR_MASK: u64 = 0x5555_5555_5555_5555; const TWO_BIT_MASK: u64 = 0x3333_3333_3333_3333; const NIBBLE_MASK: u64 = 0x0f0f_0f0f_0f0f_0f0f; @@ -41,164 +19,148 @@ const BYTE_SUM_MULTIPLIER: u64 = 0x0101_0101_0101_0101; const TWO_BIT_SHIFT: u8 = 2; const NIBBLE_SHIFT: u8 = 4; -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { + emit_with(&mut code.asm(), operand, target); +} + +fn size(width: Width) -> Size { + Size::of(width == Width::X64) +} + +pub(super) fn emit_with(asm: &mut Asm, operand: &Operand, target: TargetCpu) { + let size = size(operand.width); if operand.destination == Register::Zero { - code.push(NOP); + // NOP keeps the source-map interval nonempty. + asm.nop(); return; } if operand.source == Register::Zero { match operand.kind { - Kind::Absolute | Kind::PopulationCount => code.extend(XOR_EAX_EAX), - Kind::TrailingZeros => { - code.push(MOV_EAX_IMM32); - code.extend(bits(operand.width).to_le_bytes()); - } + Kind::Absolute | Kind::PopulationCount => asm.alu(Alu::Xor, Size::Dword, Rax, Rax), + Kind::TrailingZeros => asm.mov_imm32(Rax, size.bits()), } - store(code, operand.destination); + store_with(asm, operand.destination); return; } match operand.kind { Kind::Absolute => { - load(code, operand.source); - instruction(code, operand.width, MOV_ECX_EAX); - instruction(code, operand.width, NEG_EAX); - instruction(code, operand.width, CMOVS_EAX_ECX); + load_with(asm, operand.source); + asm.mov(size, Rcx, Rax); + asm.unary(Unary::Neg, size, Rax); + asm.cmov(Cond::S, size, Rax, Rcx); } // POPCNT, TZCNT and BSF are not on Intel's data operand // independent timing list. Kind::PopulationCount | Kind::TrailingZeros if target.data_independent_timing() => { - load(code, operand.source); + load_with(asm, operand.source); if operand.kind == Kind::TrailingZeros { // (x & -x) - 1 sets exactly the trailing zeros (all bits for 0). - instruction(code, operand.width, MOV_ECX_EAX); - instruction(code, operand.width, NEG_ECX); - instruction(code, operand.width, AND_EAX_ECX); - instruction(code, operand.width, SUB_EAX_ONE); + asm.mov(size, Rcx, Rax); + asm.unary(Unary::Neg, size, Rcx); + asm.alu(Alu::And, size, Rax, Rcx); + asm.alu_imm8(Alu::Sub, size, Rax, 1); } - population_count(code, operand.width); + population_count(asm, operand.width == Width::X64); } Kind::PopulationCount if target.supports(TargetCpu::Popcnt) => { - memory_count(code, operand, POPCNT_EAX_RDI_DISP32, Some(PREFIX_F3)); + memory_count(asm, operand, |asm, size, to, from| { + asm.popcnt(size, to, from) + }); } Kind::PopulationCount => { - load(code, operand.source); - population_count(code, operand.width); + load_with(asm, operand.source); + population_count(asm, operand.width == Width::X64); } Kind::TrailingZeros if target.supports(TargetCpu::Bmi1) => { - memory_count(code, operand, TZCNT_EAX_RDI_DISP32, Some(PREFIX_F3)); + memory_count(asm, operand, |asm, size, to, from| { + asm.tzcnt(size, to, from) + }); } Kind::TrailingZeros => { - memory_count(code, operand, BSF_EAX_RDI_DISP32, None); + memory_count(asm, operand, |asm, size, to, from| asm.bsf(size, to, from)); // MOV preserves BSF's ZF. Replace its undefined zero-input result // before use; a 32-bit CMOV is sufficient for either count width. - code.push(MOV_ECX_IMM32); - code.extend(bits(operand.width).to_le_bytes()); - code.extend(CMOVZ_EAX_ECX); + asm.mov_imm32(Rcx, size.bits()); + asm.cmov(Cond::E, Size::Dword, Rax, Rcx); } } - store(code, operand.destination); + store_with(asm, operand.destination); } -fn memory_count(code: &mut Vec, operand: &Operand, opcode: &[u8], prefix: Option) { +/// A count of the guest source read straight from the frame. +fn memory_count(asm: &mut Asm, operand: &Operand, count: fn(&mut Asm, Size, Gpr, Mem)) { // Break the count destination dependency before its folded memory read. // The memory read precedes the guest destination write, including aliases. - code.extend(XOR_EAX_EAX); - if let Some(prefix) = prefix { - code.push(prefix); - } - instruction(code, operand.width, opcode); + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); let source = offset(operand.source).expect("nonzero scalar count source"); - code.extend(source.to_le_bytes()); + count( + asm, + size(operand.width), + Rax, + Mem::base_disp32(Rdi, source as i32), + ); } -// REX.W widens the named 32-bit GPR operands. -fn instruction(code: &mut Vec, width: Width, opcode: &[u8]) { - if width == Width::X64 { - code.push(REX_W); - } - code.extend(opcode); -} - -fn bits(width: Width) -> u32 { - match width { - Width::W32 => u32::BITS, - Width::X64 => u64::BITS, - } -} - -fn load_mask(code: &mut Vec, width: Width, value: u64) { - if width == Width::X64 { - code.extend(MOV_RDX_IMM64); - code.extend(value.to_le_bytes()); - } -} - -fn mask_copy(code: &mut Vec, width: Width, value: u64) { - match width { - Width::W32 => { - code.extend(AND_ECX_IMM32); - code.extend((value as u32).to_le_bytes()); - } - Width::X64 => instruction(code, width, AND_ECX_EDX), - } -} - -fn mask_accumulator(code: &mut Vec, width: Width, value: u64) { - match width { - Width::W32 => { - code.push(AND_EAX_IMM32); - code.extend((value as u32).to_le_bytes()); - } - Width::X64 => instruction(code, width, AND_EAX_EDX), - } -} - -/// The population count of RAX (EAX for W32) in EAX, from integer +/// The population count of RAX (EAX unless `wide`) in EAX, from integer /// operations only. Clobbers RCX and RDX. -pub(super) fn population_count(code: &mut Vec, width: Width) { +pub(super) fn population_count(asm: &mut Asm, wide: bool) { + let size = Size::of(wide); + // A wide mask goes through RDX; a narrow one is an imm32. + let mask_copy = |asm: &mut Asm, value: u64| { + if wide { + asm.mov_imm64(Rdx, value); + asm.alu(Alu::And, size, Rcx, Rdx); + } else { + asm.alu_imm32(Alu::And, size, Rcx, value as u32 as i32); + } + }; + let mask_accumulator = |asm: &mut Asm, value: u64, loaded: bool| { + if wide { + if !loaded { + asm.mov_imm64(Rdx, value); + } + asm.alu(Alu::And, size, Rax, Rdx); + } else { + asm.alu_accumulator_imm32(Alu::And, size, value as u32 as i32); + } + }; // Each subtraction produces a two-bit count without borrowing across pairs. - instruction(code, width, MOV_ECX_EAX); - instruction(code, width, SHR_ECX_ONE); - load_mask(code, width, PAIR_MASK); - mask_copy(code, width, PAIR_MASK); - instruction(code, width, SUB_EAX_ECX); + asm.mov(size, Rcx, Rax); + asm.shift_one(ShiftOp::Shr, size, Rcx); + mask_copy(asm, PAIR_MASK); + asm.alu(Alu::Sub, size, Rax, Rcx); - instruction(code, width, MOV_ECX_EAX); - instruction(code, width, SHR_ECX_IMM8); - code.push(TWO_BIT_SHIFT); - load_mask(code, width, TWO_BIT_MASK); - mask_copy(code, width, TWO_BIT_MASK); - mask_accumulator(code, width, TWO_BIT_MASK); - instruction(code, width, ADD_EAX_ECX); + asm.mov(size, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, size, Rcx, TWO_BIT_SHIFT); + mask_copy(asm, TWO_BIT_MASK); + mask_accumulator(asm, TWO_BIT_MASK, true); + asm.alu(Alu::Add, size, Rax, Rcx); - instruction(code, width, MOV_ECX_EAX); - instruction(code, width, SHR_ECX_IMM8); - code.push(NIBBLE_SHIFT); - instruction(code, width, ADD_EAX_ECX); - load_mask(code, width, NIBBLE_MASK); - mask_accumulator(code, width, NIBBLE_MASK); + asm.mov(size, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, size, Rcx, NIBBLE_SHIFT); + asm.alu(Alu::Add, size, Rax, Rcx); + mask_accumulator(asm, NIBBLE_MASK, false); - match width { - Width::W32 => { - code.extend(IMUL_EAX_EAX_IMM32); - code.extend((BYTE_SUM_MULTIPLIER as u32).to_le_bytes()); - } - Width::X64 => { - load_mask(code, width, BYTE_SUM_MULTIPLIER); - instruction(code, width, IMUL_EAX_EDX); - } + if wide { + asm.mov_imm64(Rdx, BYTE_SUM_MULTIPLIER); + asm.imul(size, Rax, Rdx); + } else { + asm.imul_imm32(size, Rax, Rax, BYTE_SUM_MULTIPLIER as u32 as i32); } - instruction(code, width, SHR_EAX_IMM8); - code.push((bits(width) - u8::BITS) as u8); + asm.shift_imm(ShiftOp::Shr, size, Rax, (size.bits() - u8::BITS) as u8); } #[cfg(test)] mod tests { use super::*; + + const NOP: u8 = 0x90; + const BSF_EAX_RDI_DISP32: &[u8] = &[0x0f, 0xbc, 0x87]; + const POPCNT_EAX_RDI_DISP32: &[u8] = &[0x0f, 0xb8, 0x87]; use alloc::vec::Vec; fn emitted(kind: Kind, width: Width, source: Register, target: TargetCpu) -> Vec { - let mut code = Vec::new(); + let mut code = Code::new(); emit( &mut code, &Operand { @@ -209,7 +171,7 @@ mod tests { }, target, ); - code + code.into_bytes() } #[test] @@ -284,7 +246,7 @@ mod tests { TargetCpu::Baseline, TargetCpu::Baseline.with_popcnt().with_bmi1(), ] { - let mut code = Vec::new(); + let mut code = Code::new(); emit( &mut code, &Operand { diff --git a/crates/stela-compiler/src/x86_64/isa.rs b/crates/stela-compiler/src/x86_64/isa.rs index a1c07b23c5..bd0e42f57c 100644 --- a/crates/stela-compiler/src/x86_64/isa.rs +++ b/crates/stela-compiler/src/x86_64/isa.rs @@ -1,136 +1,191 @@ -//! x86 SIMD opcodes and their minimum CPU features. ModRM, displacement and -//! immediates are supplied by the emitter. +//! x86 SIMD opcodes and their minimum CPU features, emitted through the +//! typed encoder with the emitter's register, memory and immediate operands. use crate::TargetCpu; -use alloc::vec::Vec; +use crate::x86_64::asm::{Asm, Code, Gpr, Map, Mem, Pp, Rm, Size, Vex}; +use crate::x86_64::simd::encode::gpr; + +/// How a catalog opcode is encoded. +#[derive(Debug, Clone, Copy)] +enum Form { + /// Legacy SSE: an optional mandatory prefix and the opcode bytes. + Sse(Option, &'static [u8]), + /// Legacy SSE with REX.W, whose r/m operand is a general register. + Wide(Option, &'static [u8]), + /// VEX.128.W0 with no VEX.vvvv operand. + Vex(Pp, Map, u8), +} + +macro_rules! legacy_prefix { + (P66) => { + 0x66 + }; + (Pf3) => { + 0xf3 + }; + (Pf2) => { + 0xf2 + }; +} + +macro_rules! form { + (form [$($opcode:literal),+]) => { + Form::Sse(None, &[$($opcode),+]) + }; + (form $prefix:ident [$($opcode:literal),+]) => { + Form::Sse(Some(legacy_prefix!($prefix)), &[$($opcode),+]) + }; + (form $prefix:ident W [$($opcode:literal),+]) => { + Form::Wide(Some(legacy_prefix!($prefix)), &[$($opcode),+]) + }; + (form Vex $pp:ident $map:ident $opcode:literal) => { + Form::Vex(Pp::$pp, Map::$map, $opcode) + }; + (bytes [$($opcode:literal),+]) => { + &[$($opcode),+] + }; + (bytes $prefix:ident [$($opcode:literal),+]) => { + &[legacy_prefix!($prefix), $($opcode),+] + }; + (bytes $prefix:ident W [$($opcode:literal),+]) => { + &[legacy_prefix!($prefix), 0x48, $($opcode),+] + }; + (bytes Vex $pp:ident $map:ident $opcode:literal) => {{ + const BYTES: &[u8] = &[0xc4, 0xe0 | Map::$map as u8, 0x78 | Pp::$pp as u8, $opcode]; + BYTES + }}; +} macro_rules! catalog { - ($($name:ident => ($mnemonic:literal, $cpu:ident, [$($byte:expr),+])),+ $(,)?) => { + ($($name:ident => ($mnemonic:literal, $cpu:ident, $($form:tt)+)),+ $(,)?) => { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SimdOpcode { $($name),+ } impl SimdOpcode { pub const ALL: &'static [Self] = &[$(Self::$name),+]; pub fn mnemonic(self) -> &'static str { match self { $(Self::$name => $mnemonic),+ } } pub fn requires(self) -> TargetCpu { match self { $(Self::$name => TargetCpu::$cpu),+ } } - pub fn encoding(self) -> &'static [u8] { match self { $(Self::$name => &[$($byte),+]),+ } } + /// The prefix and opcode bytes with registers 0 to 7: the + /// mandatory prefix, any REX.W or VEX prefix, and the opcode. + pub fn encoding(self) -> &'static [u8] { match self { $(Self::$name => form!(bytes $($form)+)),+ } } + fn form(self) -> Form { match self { $(Self::$name => form!(form $($form)+)),+ } } } }; } catalog! { - AesEncryptRound => ("aesenc", Aes, [0x66,0x0f,0x38,0xdc]), - AesEncryptLast => ("aesenclast", Aes, [0x66,0x0f,0x38,0xdd]), - AesDecryptRound => ("aesdec", Aes, [0x66,0x0f,0x38,0xde]), - AesDecryptLast => ("aesdeclast", Aes, [0x66,0x0f,0x38,0xdf]), - AesInverseMixColumns => ("aesimc", Aes, [0x66,0x0f,0x38,0xdb]), - HorizontalAddDword => ("phaddd", Ssse3, [0x66,0x0f,0x38,0x02]), - Sha1Rounds4 => ("sha1rnds4", Sha, [0x0f,0x3a,0xcc]), - Sha1Message2 => ("sha1msg2", Sha, [0x0f,0x38,0xca]), - Sha256Rounds2 => ("sha256rnds2", Sha, [0x0f,0x38,0xcb]), - Sha256Message1 => ("sha256msg1", Sha, [0x0f,0x38,0xcc]), - Sha256Message2 => ("sha256msg2", Sha, [0x0f,0x38,0xcd]), - And => ("pand", Baseline, [0x66,0x0f,0xdb]), - AndNot => ("pandn", Baseline, [0x66,0x0f,0xdf]), - Or => ("por", Baseline, [0x66,0x0f,0xeb]), - Xor => ("pxor", Baseline, [0x66,0x0f,0xef]), - EqualByte => ("pcmpeqb", Baseline, [0x66,0x0f,0x74]), - EqualWord => ("pcmpeqw", Baseline, [0x66,0x0f,0x75]), - EqualDword => ("pcmpeqd", Baseline, [0x66,0x0f,0x76]), - EqualQword => ("pcmpeqq", Sse41, [0x66,0x0f,0x38,0x29]), - GreaterByte => ("pcmpgtb", Baseline, [0x66,0x0f,0x64]), - GreaterWord => ("pcmpgtw", Baseline, [0x66,0x0f,0x65]), - GreaterDword => ("pcmpgtd", Baseline, [0x66,0x0f,0x66]), - GreaterQword => ("pcmpgtq", Sse42, [0x66,0x0f,0x38,0x37]), - AddByte => ("paddb", Baseline, [0x66,0x0f,0xfc]), - AddWord => ("paddw", Baseline, [0x66,0x0f,0xfd]), - AddDword => ("paddd", Baseline, [0x66,0x0f,0xfe]), - AddQword => ("paddq", Baseline, [0x66,0x0f,0xd4]), - SubByte => ("psubb", Baseline, [0x66,0x0f,0xf8]), - SubWord => ("psubw", Baseline, [0x66,0x0f,0xf9]), - SubDword => ("psubd", Baseline, [0x66,0x0f,0xfa]), - SubQword => ("psubq", Baseline, [0x66,0x0f,0xfb]), - AbsByte => ("pabsb", Ssse3, [0x66,0x0f,0x38,0x1c]), - AbsWord => ("pabsw", Ssse3, [0x66,0x0f,0x38,0x1d]), - AbsDword => ("pabsd", Ssse3, [0x66,0x0f,0x38,0x1e]), - UnpackLowQword => ("punpcklqdq", Baseline, [0x66,0x0f,0x6c]), - UnpackLowByte => ("punpcklbw", Baseline, [0x66,0x0f,0x60]), - UnpackLowWord => ("punpcklwd", Baseline, [0x66,0x0f,0x61]), - UnpackLowDword => ("punpckldq", Baseline, [0x66,0x0f,0x62]), - PackUnsignedWordToByte => ("packuswb", Baseline, [0x66,0x0f,0x67]), - PackSignedDwordToWord => ("packssdw", Baseline, [0x66,0x0f,0x6b]), - UnpackHighByte => ("punpckhbw", Baseline, [0x66,0x0f,0x68]), - UnpackHighWord => ("punpckhwd", Baseline, [0x66,0x0f,0x69]), - UnpackHighDword => ("punpckhdq", Baseline, [0x66,0x0f,0x6a]), - UnpackHighQword => ("punpckhqdq", Baseline, [0x66,0x0f,0x6d]), - MinUnsignedByte => ("pminub", Baseline, [0x66,0x0f,0xda]), - MaxUnsignedByte => ("pmaxub", Baseline, [0x66,0x0f,0xde]), - MinSignedWord => ("pminsw", Baseline, [0x66,0x0f,0xea]), - MaxSignedWord => ("pmaxsw", Baseline, [0x66,0x0f,0xee]), - MinSignedByte => ("pminsb", Sse41, [0x66,0x0f,0x38,0x38]), - MaxSignedByte => ("pmaxsb", Sse41, [0x66,0x0f,0x38,0x3c]), - MinUnsignedWord => ("pminuw", Sse41, [0x66,0x0f,0x38,0x3a]), - MaxUnsignedWord => ("pmaxuw", Sse41, [0x66,0x0f,0x38,0x3e]), - MinSignedDword => ("pminsd", Sse41, [0x66,0x0f,0x38,0x39]), - MaxSignedDword => ("pmaxsd", Sse41, [0x66,0x0f,0x38,0x3d]), - MinUnsignedDword => ("pminud", Sse41, [0x66,0x0f,0x38,0x3b]), - MaxUnsignedDword => ("pmaxud", Sse41, [0x66,0x0f,0x38,0x3f]), - AddSignedSaturatingByte => ("paddsb", Baseline, [0x66,0x0f,0xec]), - AddSignedSaturatingWord => ("paddsw", Baseline, [0x66,0x0f,0xed]), - AddUnsignedSaturatingByte => ("paddusb", Baseline, [0x66,0x0f,0xdc]), - AddUnsignedSaturatingWord => ("paddusw", Baseline, [0x66,0x0f,0xdd]), - SubSignedSaturatingByte => ("psubsb", Baseline, [0x66,0x0f,0xe8]), - SubSignedSaturatingWord => ("psubsw", Baseline, [0x66,0x0f,0xe9]), - SubUnsignedSaturatingByte => ("psubusb", Baseline, [0x66,0x0f,0xd8]), - SubUnsignedSaturatingWord => ("psubusw", Baseline, [0x66,0x0f,0xd9]), - PackSignedWordToByte => ("packsswb", Baseline, [0x66,0x0f,0x63]), - PackUnsignedDwordToWord => ("packusdw", Sse41, [0x66,0x0f,0x38,0x2b]), - ByteSignMask => ("pmovmskb", Baseline, [0x66,0x0f,0xd7]), - DwordSignMask => ("movmskps", Baseline, [0x0f,0x50]), - MultiplyLowWord => ("pmullw", Baseline, [0x66,0x0f,0xd5]), - MultiplyHighSignedWord => ("pmulhw", Baseline, [0x66,0x0f,0xe5]), - MultiplyHighUnsignedWord => ("pmulhuw", Baseline, [0x66,0x0f,0xe4]), - MultiplyHighRoundedScaledWord => ("pmulhrsw", Ssse3, [0x66,0x0f,0x38,0x0b]), - MultiplyUnsignedDword => ("pmuludq", Baseline, [0x66,0x0f,0xf4]), - MultiplyLowDword => ("pmulld", Sse41, [0x66,0x0f,0x38,0x40]), - MultiplySignedDword => ("pmuldq", Sse41, [0x66,0x0f,0x38,0x28]), - CarrylessMultiplyQword => ("pclmulqdq", Pclmulqdq, [0x66,0x0f,0x3a,0x44]), - AverageByte => ("pavgb", Baseline, [0x66,0x0f,0xe0]), - AverageWord => ("pavgw", Baseline, [0x66,0x0f,0xe3]), - MultiplyAddWords => ("pmaddwd", Baseline, [0x66,0x0f,0xf5]), - MultiplyAddUnsignedBytes => ("pmaddubsw", Ssse3, [0x66,0x0f,0x38,0x04]), - SignExtendByteToWord => ("pmovsxbw", Sse41, [0x66,0x0f,0x38,0x20]), - ZeroExtendByteToWord => ("pmovzxbw", Sse41, [0x66,0x0f,0x38,0x30]), - MinimumPositionWord => ("phminposuw", Sse41, [0x66,0x0f,0x38,0x41]), - SignExtendWordToDword => ("pmovsxwd", Sse41, [0x66,0x0f,0x38,0x23]), - ZeroExtendWordToDword => ("pmovzxwd", Sse41, [0x66,0x0f,0x38,0x33]), - SignExtendWordToQword => ("pmovsxwq", Sse41, [0x66,0x0f,0x38,0x24]), - ZeroExtendWordToQword => ("pmovzxwq", Sse41, [0x66,0x0f,0x38,0x34]), - SignExtendDwordToQword => ("pmovsxdq", Sse41, [0x66,0x0f,0x38,0x25]), - ZeroExtendDwordToQword => ("pmovzxdq", Sse41, [0x66,0x0f,0x38,0x35]), - RoundPackedSingle => ("roundps", Sse41, [0x66,0x0f,0x3a,0x08]), - RoundPackedDouble => ("roundpd", Sse41, [0x66,0x0f,0x3a,0x09]), - RoundScalarSingle => ("roundss", Sse41, [0x66,0x0f,0x3a,0x0a]), - RoundScalarDouble => ("roundsd", Sse41, [0x66,0x0f,0x3a,0x0b]), - InsertSingle => ("insertps", Sse41, [0x66,0x0f,0x3a,0x21]), - SquareRootPackedSingle => ("sqrtps", Baseline, [0x0f,0x51]), - SquareRootPackedDouble => ("sqrtpd", Baseline, [0x66,0x0f,0x51]), - SquareRootScalarSingle => ("sqrtss", Baseline, [0xf3,0x0f,0x51]), - SquareRootScalarDouble => ("sqrtsd", Baseline, [0xf2,0x0f,0x51]), - ReciprocalPackedSingle => ("rcpps", Baseline, [0x0f,0x53]), - ConvertPackedDwordToSingle => ("cvtdq2ps", Baseline, [0x0f,0x5b]), - ConvertPackedSingleToDword => ("cvtps2dq", Baseline, [0x66,0x0f,0x5b]), - ConvertHalfToSingle => ("vcvtph2ps", F16c, [0xc4,0xe2,0x79,0x13]), - ConvertSingleToHalf => ("vcvtps2ph", F16c, [0xc4,0xe3,0x79,0x1d]), - MoveGprQword => ("movq", Baseline, [0x66,0x48,0x0f,0x6e]), - MoveAligned => ("movdqa", Baseline, [0x66,0x0f,0x6f]), - ShuffleDword => ("pshufd", Baseline, [0x66,0x0f,0x70]), - ShuffleLowWord => ("pshuflw", Baseline, [0xf2,0x0f,0x70]), - ShuffleHighWord => ("pshufhw", Baseline, [0xf3,0x0f,0x70]), - LoadUnaligned => ("movdqu", Baseline, [0xf3,0x0f,0x6f]), - StoreUnaligned => ("movdqu", Baseline, [0xf3,0x0f,0x7f]), - MoveQword => ("movq", Baseline, [0xf3,0x0f,0x7e]), - MoveScalarSingle => ("movss", Baseline, [0xf3,0x0f,0x10]), - MoveScalarDouble => ("movsd", Baseline, [0xf2,0x0f,0x10]), - ByteShuffle => ("pshufb", Ssse3, [0x66,0x0f,0x38,0x00]), - AlignBytes => ("palignr", Ssse3, [0x66,0x0f,0x3a,0x0f]), + AesEncryptRound => ("aesenc", Aes, P66 [0x0f, 0x38, 0xdc]), + AesEncryptLast => ("aesenclast", Aes, P66 [0x0f, 0x38, 0xdd]), + AesDecryptRound => ("aesdec", Aes, P66 [0x0f, 0x38, 0xde]), + AesDecryptLast => ("aesdeclast", Aes, P66 [0x0f, 0x38, 0xdf]), + AesInverseMixColumns => ("aesimc", Aes, P66 [0x0f, 0x38, 0xdb]), + HorizontalAddDword => ("phaddd", Ssse3, P66 [0x0f, 0x38, 0x02]), + Sha1Rounds4 => ("sha1rnds4", Sha, [0x0f, 0x3a, 0xcc]), + Sha1Message2 => ("sha1msg2", Sha, [0x0f, 0x38, 0xca]), + Sha256Rounds2 => ("sha256rnds2", Sha, [0x0f, 0x38, 0xcb]), + Sha256Message1 => ("sha256msg1", Sha, [0x0f, 0x38, 0xcc]), + Sha256Message2 => ("sha256msg2", Sha, [0x0f, 0x38, 0xcd]), + And => ("pand", Baseline, P66 [0x0f, 0xdb]), + AndNot => ("pandn", Baseline, P66 [0x0f, 0xdf]), + Or => ("por", Baseline, P66 [0x0f, 0xeb]), + Xor => ("pxor", Baseline, P66 [0x0f, 0xef]), + EqualByte => ("pcmpeqb", Baseline, P66 [0x0f, 0x74]), + EqualWord => ("pcmpeqw", Baseline, P66 [0x0f, 0x75]), + EqualDword => ("pcmpeqd", Baseline, P66 [0x0f, 0x76]), + EqualQword => ("pcmpeqq", Sse41, P66 [0x0f, 0x38, 0x29]), + GreaterByte => ("pcmpgtb", Baseline, P66 [0x0f, 0x64]), + GreaterWord => ("pcmpgtw", Baseline, P66 [0x0f, 0x65]), + GreaterDword => ("pcmpgtd", Baseline, P66 [0x0f, 0x66]), + GreaterQword => ("pcmpgtq", Sse42, P66 [0x0f, 0x38, 0x37]), + AddByte => ("paddb", Baseline, P66 [0x0f, 0xfc]), + AddWord => ("paddw", Baseline, P66 [0x0f, 0xfd]), + AddDword => ("paddd", Baseline, P66 [0x0f, 0xfe]), + AddQword => ("paddq", Baseline, P66 [0x0f, 0xd4]), + SubByte => ("psubb", Baseline, P66 [0x0f, 0xf8]), + SubWord => ("psubw", Baseline, P66 [0x0f, 0xf9]), + SubDword => ("psubd", Baseline, P66 [0x0f, 0xfa]), + SubQword => ("psubq", Baseline, P66 [0x0f, 0xfb]), + AbsByte => ("pabsb", Ssse3, P66 [0x0f, 0x38, 0x1c]), + AbsWord => ("pabsw", Ssse3, P66 [0x0f, 0x38, 0x1d]), + AbsDword => ("pabsd", Ssse3, P66 [0x0f, 0x38, 0x1e]), + UnpackLowQword => ("punpcklqdq", Baseline, P66 [0x0f, 0x6c]), + UnpackLowByte => ("punpcklbw", Baseline, P66 [0x0f, 0x60]), + UnpackLowWord => ("punpcklwd", Baseline, P66 [0x0f, 0x61]), + UnpackLowDword => ("punpckldq", Baseline, P66 [0x0f, 0x62]), + PackUnsignedWordToByte => ("packuswb", Baseline, P66 [0x0f, 0x67]), + PackSignedDwordToWord => ("packssdw", Baseline, P66 [0x0f, 0x6b]), + UnpackHighByte => ("punpckhbw", Baseline, P66 [0x0f, 0x68]), + UnpackHighWord => ("punpckhwd", Baseline, P66 [0x0f, 0x69]), + UnpackHighDword => ("punpckhdq", Baseline, P66 [0x0f, 0x6a]), + UnpackHighQword => ("punpckhqdq", Baseline, P66 [0x0f, 0x6d]), + MinUnsignedByte => ("pminub", Baseline, P66 [0x0f, 0xda]), + MaxUnsignedByte => ("pmaxub", Baseline, P66 [0x0f, 0xde]), + MinSignedWord => ("pminsw", Baseline, P66 [0x0f, 0xea]), + MaxSignedWord => ("pmaxsw", Baseline, P66 [0x0f, 0xee]), + MinSignedByte => ("pminsb", Sse41, P66 [0x0f, 0x38, 0x38]), + MaxSignedByte => ("pmaxsb", Sse41, P66 [0x0f, 0x38, 0x3c]), + MinUnsignedWord => ("pminuw", Sse41, P66 [0x0f, 0x38, 0x3a]), + MaxUnsignedWord => ("pmaxuw", Sse41, P66 [0x0f, 0x38, 0x3e]), + MinSignedDword => ("pminsd", Sse41, P66 [0x0f, 0x38, 0x39]), + MaxSignedDword => ("pmaxsd", Sse41, P66 [0x0f, 0x38, 0x3d]), + MinUnsignedDword => ("pminud", Sse41, P66 [0x0f, 0x38, 0x3b]), + MaxUnsignedDword => ("pmaxud", Sse41, P66 [0x0f, 0x38, 0x3f]), + AddSignedSaturatingByte => ("paddsb", Baseline, P66 [0x0f, 0xec]), + AddSignedSaturatingWord => ("paddsw", Baseline, P66 [0x0f, 0xed]), + AddUnsignedSaturatingByte => ("paddusb", Baseline, P66 [0x0f, 0xdc]), + AddUnsignedSaturatingWord => ("paddusw", Baseline, P66 [0x0f, 0xdd]), + SubSignedSaturatingByte => ("psubsb", Baseline, P66 [0x0f, 0xe8]), + SubSignedSaturatingWord => ("psubsw", Baseline, P66 [0x0f, 0xe9]), + SubUnsignedSaturatingByte => ("psubusb", Baseline, P66 [0x0f, 0xd8]), + SubUnsignedSaturatingWord => ("psubusw", Baseline, P66 [0x0f, 0xd9]), + PackSignedWordToByte => ("packsswb", Baseline, P66 [0x0f, 0x63]), + PackUnsignedDwordToWord => ("packusdw", Sse41, P66 [0x0f, 0x38, 0x2b]), + ByteSignMask => ("pmovmskb", Baseline, P66 [0x0f, 0xd7]), + DwordSignMask => ("movmskps", Baseline, [0x0f, 0x50]), + MultiplyLowWord => ("pmullw", Baseline, P66 [0x0f, 0xd5]), + MultiplyHighSignedWord => ("pmulhw", Baseline, P66 [0x0f, 0xe5]), + MultiplyHighUnsignedWord => ("pmulhuw", Baseline, P66 [0x0f, 0xe4]), + MultiplyHighRoundedScaledWord => ("pmulhrsw", Ssse3, P66 [0x0f, 0x38, 0x0b]), + MultiplyUnsignedDword => ("pmuludq", Baseline, P66 [0x0f, 0xf4]), + MultiplyLowDword => ("pmulld", Sse41, P66 [0x0f, 0x38, 0x40]), + MultiplySignedDword => ("pmuldq", Sse41, P66 [0x0f, 0x38, 0x28]), + CarrylessMultiplyQword => ("pclmulqdq", Pclmulqdq, P66 [0x0f, 0x3a, 0x44]), + AverageByte => ("pavgb", Baseline, P66 [0x0f, 0xe0]), + AverageWord => ("pavgw", Baseline, P66 [0x0f, 0xe3]), + MultiplyAddWords => ("pmaddwd", Baseline, P66 [0x0f, 0xf5]), + MultiplyAddUnsignedBytes => ("pmaddubsw", Ssse3, P66 [0x0f, 0x38, 0x04]), + SignExtendByteToWord => ("pmovsxbw", Sse41, P66 [0x0f, 0x38, 0x20]), + ZeroExtendByteToWord => ("pmovzxbw", Sse41, P66 [0x0f, 0x38, 0x30]), + MinimumPositionWord => ("phminposuw", Sse41, P66 [0x0f, 0x38, 0x41]), + SignExtendWordToDword => ("pmovsxwd", Sse41, P66 [0x0f, 0x38, 0x23]), + ZeroExtendWordToDword => ("pmovzxwd", Sse41, P66 [0x0f, 0x38, 0x33]), + SignExtendWordToQword => ("pmovsxwq", Sse41, P66 [0x0f, 0x38, 0x24]), + ZeroExtendWordToQword => ("pmovzxwq", Sse41, P66 [0x0f, 0x38, 0x34]), + SignExtendDwordToQword => ("pmovsxdq", Sse41, P66 [0x0f, 0x38, 0x25]), + ZeroExtendDwordToQword => ("pmovzxdq", Sse41, P66 [0x0f, 0x38, 0x35]), + RoundPackedSingle => ("roundps", Sse41, P66 [0x0f, 0x3a, 0x08]), + RoundPackedDouble => ("roundpd", Sse41, P66 [0x0f, 0x3a, 0x09]), + RoundScalarSingle => ("roundss", Sse41, P66 [0x0f, 0x3a, 0x0a]), + RoundScalarDouble => ("roundsd", Sse41, P66 [0x0f, 0x3a, 0x0b]), + InsertSingle => ("insertps", Sse41, P66 [0x0f, 0x3a, 0x21]), + SquareRootPackedSingle => ("sqrtps", Baseline, [0x0f, 0x51]), + SquareRootPackedDouble => ("sqrtpd", Baseline, P66 [0x0f, 0x51]), + SquareRootScalarSingle => ("sqrtss", Baseline, Pf3 [0x0f, 0x51]), + SquareRootScalarDouble => ("sqrtsd", Baseline, Pf2 [0x0f, 0x51]), + ReciprocalPackedSingle => ("rcpps", Baseline, [0x0f, 0x53]), + ConvertPackedDwordToSingle => ("cvtdq2ps", Baseline, [0x0f, 0x5b]), + ConvertPackedSingleToDword => ("cvtps2dq", Baseline, P66 [0x0f, 0x5b]), + ConvertHalfToSingle => ("vcvtph2ps", F16c, Vex P66 M0f38 0x13), + ConvertSingleToHalf => ("vcvtps2ph", F16c, Vex P66 M0f3a 0x1d), + MoveGprQword => ("movq", Baseline, P66 W [0x0f, 0x6e]), + MoveAligned => ("movdqa", Baseline, P66 [0x0f, 0x6f]), + ShuffleDword => ("pshufd", Baseline, P66 [0x0f, 0x70]), + ShuffleLowWord => ("pshuflw", Baseline, Pf2 [0x0f, 0x70]), + ShuffleHighWord => ("pshufhw", Baseline, Pf3 [0x0f, 0x70]), + LoadUnaligned => ("movdqu", Baseline, Pf3 [0x0f, 0x6f]), + StoreUnaligned => ("movdqu", Baseline, Pf3 [0x0f, 0x7f]), + MoveQword => ("movq", Baseline, Pf3 [0x0f, 0x7e]), + MoveScalarSingle => ("movss", Baseline, Pf3 [0x0f, 0x10]), + MoveScalarDouble => ("movsd", Baseline, Pf2 [0x0f, 0x10]), + ByteShuffle => ("pshufb", Ssse3, P66 [0x0f, 0x38, 0x00]), + AlignBytes => ("palignr", Ssse3, P66 [0x0f, 0x3a, 0x0f]), } /// Packed immediate shifts use an opcode group, rather than a source ModRM field. @@ -183,39 +238,116 @@ impl ShiftOpcode { Self::RightBytes => ("psrldq", 0x73, 3), } } - pub(crate) fn emit(self, code: &mut Vec, register: u8, amount: u8) { - assert!(register < 8, "legacy SIMD register needs REX encoding"); - code.extend([ - 0x66, - 0x0f, - self.opcode(), - 0xc0 | (self.group() << 3) | register, + /// Shift XMM `register` by `amount`. + pub(crate) fn emit(self, code: &mut Code, register: u8, amount: u8) { + code.asm().sse_imm( + Some(0x66), + &[0x0f, self.opcode()], + self.group(), + Rm::Xmm(register), amount, - ]); + ); } } impl SimdOpcode { - pub(crate) fn append(self, code: &mut Vec, target: TargetCpu) { + fn check(self, target: TargetCpu) { assert!( target.supports(self.requires()), "selected CPU requirements cannot emit {}", self.mnemonic() ); - code.extend(self.encoding()); } - pub(crate) fn register( + /// This opcode with ModRM.reg `register` and r/m `rm`. + pub(crate) fn emit(self, code: &mut Code, register: u8, rm: impl Into, target: TargetCpu) { + code.asm().simd(self, register, rm, target); + } + /// [`Self::emit`] with an 8-bit immediate. + pub(crate) fn emit_imm( self, - code: &mut Vec, - destination: u8, - source: u8, + code: &mut Code, + register: u8, + rm: impl Into, + immediate: u8, target: TargetCpu, ) { - assert!( - destination < 8 && source < 8, - "legacy SIMD register needs REX encoding" - ); - self.append(code, target); - code.push(0xc0 | (destination << 3) | source); + self.emit(code, register, rm, target); + code.asm().data(&[immediate]); + } + /// This opcode on registers: XMM `destination` and XMM `source`, or the + /// general register numbered `source` for [`Self::MoveGprQword`]. + pub(crate) fn register(self, code: &mut Code, destination: u8, source: u8, target: TargetCpu) { + let source = match self.form() { + Form::Wide(..) => Rm::Reg(gpr(source)), + _ => Rm::Xmm(source), + }; + self.emit(code, destination, source, target); + } + /// [`Self::register`] with an 8-bit immediate. + pub(crate) fn register_imm( + self, + code: &mut Code, + destination: u8, + source: u8, + immediate: u8, + target: TargetCpu, + ) { + self.register(code, destination, source, target); + code.asm().data(&[immediate]); + } +} + +impl Asm<'_> { + /// The catalog instruction `opcode` with ModRM.reg `register` and r/m + /// `rm`; the selected CPU must provide its features. + pub(crate) fn simd( + &mut self, + opcode: SimdOpcode, + register: u8, + rm: impl Into, + target: TargetCpu, + ) { + opcode.check(target); + match opcode.form() { + Form::Sse(prefix, bytes) => self.sse(prefix, bytes, register, rm), + Form::Wide(prefix, bytes) => { + self.legacy(Size::Qword, prefix, bytes, register, false, rm.into()); + } + Form::Vex(pp, map, byte) => self.vex( + Vex { + map, + pp, + w: false, + l: false, + }, + byte, + register, + 0, + rm.into(), + ), + } + } + /// The catalog instruction `opcode` writing general-purpose + /// `destination` from `xmm` (PMOVMSKB, MOVMSKPS). + pub(crate) fn simd_to_gpr( + &mut self, + opcode: SimdOpcode, + destination: Gpr, + xmm: u8, + target: TargetCpu, + ) { + self.simd(opcode, destination as u8, Rm::Xmm(xmm), target); + } + /// [`Self::simd`] with an 8-bit immediate. + pub(crate) fn simd_imm( + &mut self, + opcode: SimdOpcode, + register: u8, + rm: impl Into, + immediate: u8, + target: TargetCpu, + ) { + self.simd(opcode, register, rm, target); + self.data(&[immediate]); } } @@ -234,7 +366,7 @@ pub(crate) enum VexShiftOpcode { impl VexShiftOpcode { pub(crate) fn register( self, - code: &mut Vec, + code: &mut Code, destination: u8, source: u8, counts: u8, @@ -244,44 +376,37 @@ impl VexShiftOpcode { target.supports(TargetCpu::Avx2), "AVX2 shifts require usable AVX2 state" ); - assert!( - destination < 8 && source < 8 && counts < 8, - "AVX2 shift writer requires XMM0..7" - ); - const VEX3: u8 = 0xc4; - const MAP_0F38_LOW_REGISTERS: u8 = 0xe2; - const PREFIX_66: u8 = 1; - const QWORD_W: u8 = 0x80; - const REGISTER_DIRECT: u8 = 0xc0; - const REGISTER_SHIFT: u8 = 3; - let (opcode, width) = match self { - Self::LeftDword => (0x47, 0), - Self::RightDword => (0x45, 0), - Self::ArithmeticDword => (0x46, 0), - Self::LeftQword => (0x47, QWORD_W), - Self::RightQword => (0x45, QWORD_W), + let (opcode, w) = match self { + Self::LeftDword => (0x47, false), + Self::RightDword => (0x45, false), + Self::ArithmeticDword => (0x46, false), + Self::LeftQword => (0x47, true), + Self::RightQword => (0x45, true), }; - // VEX.vvvv complements the nondestructive data source. L=0 selects128. - let operands = width | ((!source & 15) << REGISTER_SHIFT) | PREFIX_66; - code.extend([ - VEX3, - MAP_0F38_LOW_REGISTERS, - operands, + // VEX.vvvv names the data source, ModRM.rm the per-element counts. + code.asm().vex( + Vex { + map: Map::M0f38, + pp: Pp::P66, + w, + l: false, + }, opcode, - REGISTER_DIRECT | (destination << REGISTER_SHIFT) | counts, - ]); + destination, + source, + Rm::Xmm(counts), + ); } } /// Clear caller-volatile upper vector state before an AVX2 body starts mixing /// VEX128 arithmetic with its legacy SSE state-access and predication wrapper. -pub(crate) fn clear_upper_vector_state(code: &mut Vec, target: TargetCpu) { +pub(crate) fn clear_upper_vector_state(code: &mut Code, target: TargetCpu) { assert!( target.supports(TargetCpu::Avx2), "VZEROUPPER requires usable AVX state" ); - const VZEROUPPER: [u8; 3] = [0xc5, 0xf8, 0x77]; - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } /// SSE4.2 CRC32 computes Castagnoli, never the IEEE polynomial. @@ -303,60 +428,67 @@ impl CrcOpcode { } } /// Accumulator RAX, data RCX; every form zero-extends its 32-bit remainder. - pub(crate) fn emit(self, code: &mut Vec, target: TargetCpu) { + pub(crate) fn emit(self, code: &mut Code, target: TargetCpu) { assert!(target.supports(TargetCpu::Sse42)); - code.push(0xf2); - match self { - Self::Halfword => code.push(0x66), - Self::Doubleword => code.push(0x48), - _ => {} - } - code.extend([ - 0x0f, - 0x38, - if self == Self::Byte { 0xf0 } else { 0xf1 }, - 0xc1, - ]); + let (size, opcode) = match self { + Self::Byte => (Size::Byte, 0xf0), + Self::Halfword => (Size::Word, 0xf1), + Self::Word => (Size::Dword, 0xf1), + Self::Doubleword => (Size::Qword, 0xf1), + }; + // F2 ahead of the operand-size prefix, as the SDM lists CRC32. + let mut asm = code.asm(); + asm.prefix(0xf2); + asm.legacy( + size, + None, + &[0x0f, 0x38, opcode], + 0, + false, + Rm::Reg(Gpr::Rcx), + ); } } /// Register recipe for the table-driven CRC: RAX is the W accumulator, RCX the -/// data, RDX the table index and R8 the RIP-relative table base. RDI holds -/// GuestState. +/// data, RDX the table index and R8 the RIP-relative table base, which the +/// caller loads. RDI holds GuestState. #[derive(Debug, Clone, Copy)] pub(crate) enum CrcTableInstruction { TruncateByteData, TruncateHalfwordData, - TableBaseRip, MergeWordData, SelectHighDataWord, IndexLowByte, ShiftAccumulatorByte, XorTableEntry, - JumpOverTable, Discard, } impl CrcTableInstruction { - pub(crate) fn emit(self, code: &mut Vec) { - code.extend(match self { - Self::TruncateByteData => &[0x0f, 0xb6, 0xc9][..], // movzx ecx,cl - Self::TruncateHalfwordData => &[0x0f, 0xb7, 0xc9], // movzx ecx,cx - Self::TableBaseRip => &[0x4c, 0x8d, 0x05], // lea r8,[rip+disp32] - Self::MergeWordData => &[0x31, 0xc8], // xor eax,ecx - Self::SelectHighDataWord => &[0x48, 0xc1, 0xe9, 32], // shr rcx,32 - Self::IndexLowByte => &[0x0f, 0xb6, 0xd0], // movzx edx,al - Self::ShiftAccumulatorByte => &[0xc1, 0xe8, 8], // shr eax,8 - Self::XorTableEntry => &[0x41, 0x33, 0x04, 0x90], // xor eax,[r8+rdx*4] - Self::JumpOverTable => &[0xe9], // jmp rel32 - Self::Discard => &[0x90], // nop, nonempty source-map interval - }); + /// Emit this step. + pub(crate) fn emit(self, code: &mut Code) { + use crate::x86_64::asm::{Alu, ShiftOp}; + use Gpr::{R8, Rax, Rcx, Rdx}; + let mut asm = code.asm(); + match self { + Self::TruncateByteData => asm.movzx(Size::Dword, Rcx, Size::Byte, Rcx), + Self::TruncateHalfwordData => asm.movzx(Size::Dword, Rcx, Size::Word, Rcx), + Self::MergeWordData => asm.alu(Alu::Xor, Size::Dword, Rax, Rcx), + Self::SelectHighDataWord => asm.shift_imm(ShiftOp::Shr, Size::Qword, Rcx, 32), + Self::IndexLowByte => asm.movzx(Size::Dword, Rdx, Size::Byte, Rax), + Self::ShiftAccumulatorByte => asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, 8), + Self::XorTableEntry => { + asm.alu_load(Alu::Xor, Size::Dword, Rax, Mem::indexed(R8, Rdx, 4, 0)); + } + // A nonempty source-map interval. + Self::Discard => asm.nop(), + } } } #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; #[test] fn avx2_shift_encodings_keep_data_count_and_destination_fields_distinct() { @@ -367,7 +499,7 @@ mod tests { (VexShiftOpcode::LeftQword, 0x47, 0x80), (VexShiftOpcode::RightQword, 0x45, 0x80), ] { - let mut code = Vec::new(); + let mut code = Code::new(); opcode.register(&mut code, 3, 6, 7, TargetCpu::Avx2); assert_eq!(code, [0xc4, 0xe2, width | 0x49, operation, 0xdf]); for target in [TargetCpu::Baseline, TargetCpu::Sse42, TargetCpu::Fma] { @@ -399,17 +531,17 @@ mod tests { assert_eq!(opcode.encoding(), encoding); assert_eq!(opcode.requires(), TargetCpu::Sse41); for target in [TargetCpu::Baseline, TargetCpu::Ssse3] { - let mut code = Vec::new(); + let mut code = Code::new(); let declined = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - opcode.append(&mut code, target) + opcode.register(&mut code, 0, 1, target) })); assert!(declined.is_err()); assert!(code.is_empty()); } for target in [TargetCpu::Sse41, TargetCpu::Sse42] { - let mut code = Vec::new(); - opcode.append(&mut code, target); - assert_eq!(code, encoding); + let mut code = Code::new(); + opcode.register(&mut code, 0, 1, target); + assert_eq!(code, [&encoding[..], &[0xc1]].concat()); } } } @@ -422,17 +554,79 @@ mod tests { assert_eq!(opcode.encoding(), encoding); assert_eq!(opcode.requires(), TargetCpu::Sse41); for target in [TargetCpu::Baseline, TargetCpu::Ssse3] { - let mut code = Vec::new(); + let mut code = Code::new(); let declined = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - opcode.append(&mut code, target); + opcode.register(&mut code, 0, 1, target); })); assert!(declined.is_err()); assert!(code.is_empty()); } for target in [TargetCpu::Sse41, TargetCpu::Sse42] { - let mut code = Vec::new(); - opcode.append(&mut code, target); - assert_eq!(code, encoding); + let mut code = Code::new(); + opcode.register(&mut code, 0, 1, target); + assert_eq!(code, [&encoding[..], &[0xc1]].concat()); } } + + #[test] + fn catalog_forms_match_their_encodings() { + use Gpr::*; + let one = |build: &dyn Fn(&mut Asm)| { + let mut code = Code::new(); + build(&mut code.asm()); + assert_eq!(code.instructions(), 1); + code + }; + let v3 = TargetCpu::X86_64_V3; + for (expected, code) in [ + ( + &[0x66, 0x0f, 0xdb, 0xca][..], + one(&|a| a.simd(SimdOpcode::And, 1, Rm::Xmm(2), v3)), + ), + ( + &[0x66, 0x48, 0x0f, 0x6e, 0xf8], + one(&|a| a.simd(SimdOpcode::MoveGprQword, 7, Rax, v3)), + ), + ( + &[0x0f, 0x50, 0xc1], + one(&|a| a.simd_to_gpr(SimdOpcode::DwordSignMask, Rax, 1, v3)), + ), + ( + &[0x66, 0x0f, 0x70, 0xc1, 0x1b], + one(&|a| a.simd_imm(SimdOpcode::ShuffleDword, 0, Rm::Xmm(1), 0x1b, v3)), + ), + ( + &[0xf3, 0x0f, 0x6f, 0x87, 8, 1, 0, 0], + one(&|a| { + a.simd( + SimdOpcode::LoadUnaligned, + 0, + Mem::base_disp32(Rdi, 0x108), + v3, + ) + }), + ), + ( + &[0xc4, 0xe2, 0x79, 0x13, 0xc1], + one(&|a| a.simd(SimdOpcode::ConvertHalfToSingle, 0, Rm::Xmm(1), v3)), + ), + ( + &[0xc4, 0xe3, 0x79, 0x1d, 0xc8, 4], + one(&|a| a.simd_imm(SimdOpcode::ConvertSingleToHalf, 1, Rm::Xmm(0), 4, v3)), + ), + ] { + assert_eq!(code, expected); + } + } + + #[test] + #[should_panic(expected = "selected CPU requirements cannot emit pmulld")] + fn catalog_forms_require_their_features() { + Code::new().asm().simd( + SimdOpcode::MultiplyLowDword, + 0, + Rm::Xmm(1), + TargetCpu::Baseline, + ); + } } diff --git a/crates/stela-compiler/src/x86_64/literal.rs b/crates/stela-compiler/src/x86_64/literal.rs index 9166eaec3e..4099dd090b 100644 --- a/crates/stela-compiler/src/x86_64/literal.rs +++ b/crates/stela-compiler/src/x86_64/literal.rs @@ -4,31 +4,10 @@ use crate::aarch64::{ Width, literal::{Operand, Transfer}, }; -use alloc::vec::Vec; +use crate::x86_64::asm::{Code, Gpr, Mem, Size}; -/// Family-local baseline opcodes; address/state displacements follow separately. -#[derive(Clone, Copy)] -enum Opcode { - MoveAddress, - LoadWord, - LoadDoubleword, - LoadSignedWord, -} - -impl Opcode { - fn emit(self, code: &mut Vec) { - code.extend(match self { - Self::MoveAddress => &[0x48, 0xb8][..], // movabs rax,imm64 - Self::LoadWord => &[0x8b, 0x00], // mov eax,[rax], zeroextends RAX - Self::LoadDoubleword => &[0x48, 0x8b, 0x00], // mov rax,[rax] - Self::LoadSignedWord => &[0x48, 0x63, 0x00], // movsxd rax,[rax] - }); - } -} - -pub(super) fn emit(code: &mut Vec, operand: &Operand, checks: super::MemoryChecks) { - Opcode::MoveAddress.emit(code); - code.extend(operand.address.to_le_bytes()); +pub(super) fn emit(code: &mut Code, operand: &Operand, checks: super::MemoryChecks) { + code.asm().mov_imm64(Gpr::Rax, operand.address); let bytes = match operand.transfer { Transfer::Integer { width: Width::X64, @@ -45,13 +24,15 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, checks: super::MemoryC width, signed, } => { + let address = Mem::base(Gpr::Rax, 0); + let mut asm = code.asm(); match (width, signed) { - (Width::W32, false) => Opcode::LoadWord, - (Width::X64, false) => Opcode::LoadDoubleword, - (Width::X64, true) => Opcode::LoadSignedWord, + // MOV EAX zero-extends RAX. + (Width::W32, false) => asm.mov_load(Size::Dword, Gpr::Rax, address), + (Width::X64, false) => asm.mov_load(Size::Qword, Gpr::Rax, address), + (Width::X64, true) => asm.movsxd(Gpr::Rax, address), (Width::W32, true) => unreachable!("literal signed load writes X register"), } - .emit(code); // ZR discards only the result; its access and possible fault remain. store(code, destination); } @@ -65,7 +46,6 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, checks: super::MemoryC mod tests { use super::*; use crate::{GuestState, aarch64::Register}; - use alloc::vec; #[test] fn integer_discard_still_loads_and_signed_load_has_exact_width() { @@ -74,7 +54,7 @@ mod tests { (Width::X64, false, &[0x48, 0x8b, 0x00][..]), (Width::X64, true, &[0x48, 0x63, 0x00][..]), ] { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &Operand { @@ -100,7 +80,7 @@ mod tests { (Width::X64, false, 8), (Width::X64, true, 4), ] { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &Operand { @@ -127,7 +107,7 @@ mod tests { (8, [0xf3, 0x0f, 0x7e, 0x00]), (16, [0xf3, 0x0f, 0x6f, 0x00]), ] { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &Operand { diff --git a/crates/stela-compiler/src/x86_64/memory_context/address.rs b/crates/stela-compiler/src/x86_64/memory_context/address.rs index 9dd72e1ca4..beab714ded 100644 --- a/crates/stela-compiler/src/x86_64/memory_context/address.rs +++ b/crates/stela-compiler/src/x86_64/memory_context/address.rs @@ -1,56 +1,45 @@ //! SP alignment checks and address arithmetic for checked accesses. -use super::{fault, patch_branch}; +use super::fault; +use crate::x86_64::asm::{Code, Cond, Gpr, Mem, Size}; use crate::x86_64::load; use crate::{ aarch64::{AddressMode, Register, register_offset::IndexExtend}, context::memory::{MemoryStatus, address::AddressAddChecks}, }; -use alloc::vec::Vec; const STACK_ALIGNMENT_MASK: u8 = 15; -const TEST_AL_IMM8: u8 = 0xa8; -const JE_REL32: &[u8] = &[0x0f, 0x84]; -const JMP_REL32: u8 = 0xe9; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const JE_REL8: u8 = 0x74; -const RET: u8 = 0xc3; -const LEA_RAX_RAX_DISP8: &[u8] = &[0x48, 0x8d, 0x40]; -const LEA_RAX_RAX_DISP32: &[u8] = &[0x48, 0x8d, 0x80]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const MOV_R8_RAX: &[u8] = &[0x49, 0x89, 0xc0]; -const MOV_RAX_R8: &[u8] = &[0x4c, 0x89, 0xc0]; /// Check SP before the offset is applied. The caller patches the returned rel32 /// to its cleanup. On failure RAX holds the faulting SP. Clobbers RAX/RCX/RDX /// and flags. -pub(crate) fn check_sp(code: &mut Vec, base: Register, pc: u64) -> Option { +pub(crate) fn check_sp(code: &mut Code, base: Register, pc: u64) -> Option { if base != Register::Sp { return None; } load(code, Register::Sp); - code.extend([TEST_AL_IMM8, STACK_ALIGNMENT_MASK]); - code.extend(JE_REL32); - let aligned = code.len(); - code.extend(0_i32.to_le_bytes()); + let mut asm = code.asm(); + asm.test_accumulator_imm(Size::Byte, STACK_ALIGNMENT_MASK.into()); + let aligned = asm.jcc(Cond::E); fault(code, MemoryStatus::StackAlignment, pc); - code.push(JMP_REL32); - let failed = code.len(); - code.extend(0_i32.to_le_bytes()); - let destination = code.len(); - patch_branch(code, aligned, destination); - Some(failed) + let mut asm = code.asm(); + let failed = asm.jmp(); + asm.bind(aligned); + Some(failed.offset()) } /// Return only after scratch cleanup. The checked outer CALL wrapper owns R15. /// The runtime inspects the fault view before interpreting native block returns. -pub(crate) fn return_if_failed(code: &mut Vec) { - code.extend(TEST_EAX_EAX); - code.extend([JE_REL8, 1, RET]); +pub(crate) fn return_if_failed(code: &mut Code) { + let mut asm = code.asm(); + asm.test(Size::Dword, Gpr::Rax, Gpr::Rax); + let succeeded = asm.jcc8(Cond::E); + asm.ret(); + asm.bind(succeeded); } /// Unchecked arithmetic AFTER check_sp ([`crate::x86_64::address_add`]). /// Snapshot pending writeback before callbacks; commit only on full success. -pub(crate) fn immediate(code: &mut Vec, base: Register, displacement: i32, mode: AddressMode) { +pub(crate) fn immediate(code: &mut Code, base: Register, displacement: i32, mode: AddressMode) { load(code, base); crate::x86_64::address_add(code, displacement, mode); } @@ -60,7 +49,7 @@ pub(crate) fn immediate(code: &mut Vec, base: Register, displacement: i32, m /// leave the pending writeback in RDX. Post-index keeps the original access /// address and marks only the writeback. pub(crate) fn immediate_with_checks( - code: &mut Vec, + code: &mut Code, base: Register, displacement: i32, mode: AddressMode, @@ -72,32 +61,29 @@ pub(crate) fn immediate_with_checks( return; } load(code, base); - code.extend(MOV_RDX_RAX); + let mut asm = code.asm(); + asm.mov(Size::Qword, Gpr::Rdx, Gpr::Rax); if mode == AddressMode::PostIndex { - code.extend(MOV_R8_RAX); - } - if let Ok(compact) = i8::try_from(displacement) { - code.extend(LEA_RAX_RAX_DISP8); - code.push(compact as u8); - } else { - code.extend(LEA_RAX_RAX_DISP32); - code.extend(displacement.to_le_bytes()); + asm.mov(Size::Qword, Gpr::R8, Gpr::Rax); } + // A nonzero displacement: disp8 when it fits, else disp32. + asm.lea(Size::Qword, Gpr::Rax, Mem::base(Gpr::Rax, displacement)); // The CPA recipe preserves RDX and, without multiplication, R8. // RAX/RCX/R9/R10/R11 and flags are scratch. crate::x86_64::pointer_checks::emit(code, false); + let mut asm = code.asm(); if mode != AddressMode::Offset { - code.extend(MOV_RDX_RAX); + asm.mov(Size::Qword, Gpr::Rdx, Gpr::Rax); } if mode == AddressMode::PostIndex { - code.extend(MOV_RAX_R8); + asm.mov(Size::Qword, Gpr::Rax, Gpr::R8); } } /// Unchecked arithmetic AFTER check_sp. RAX=EA; no base writeback. Operands are /// the existing validated decoder types, including W extension and ZR index. pub(crate) fn register_offset( - code: &mut Vec, + code: &mut Code, base: Register, index: Register, extend: IndexExtend, @@ -110,7 +96,7 @@ pub(crate) fn register_offset( /// AddressAdd for an extended or shifted register offset. RAX is the effective /// address and RDX keeps the base. There is no writeback. pub(crate) fn register_offset_with_checks( - code: &mut Vec, + code: &mut Code, base: Register, index: Register, extend: IndexExtend, @@ -125,7 +111,7 @@ pub(crate) fn register_offset_with_checks( if index == Register::Zero { return; } - code.extend(MOV_RDX_RAX); + code.asm().mov(Size::Qword, Gpr::Rdx, Gpr::Rax); crate::x86_64::register_offset::index_add(code, index, extend, shift); crate::x86_64::pointer_checks::emit(code, false); } diff --git a/crates/stela-compiler/src/x86_64/memory_context/callback.rs b/crates/stela-compiler/src/x86_64/memory_context/callback.rs index f95406b69e..c9b2a3c038 100644 --- a/crates/stela-compiler/src/x86_64/memory_context/callback.rs +++ b/crates/stela-compiler/src/x86_64/memory_context/callback.rs @@ -1,8 +1,8 @@ //! The shared memory-service call. Instruction families supply predicates, //! addresses and load staging; the service performs translation, splitting, //! tag checks and writer tracking. +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, Size}; -use alloc::vec::Vec; use core::mem::offset_of; use crate::context::{ @@ -12,62 +12,54 @@ use crate::context::{ const HOST_POINTER_BYTES: u32 = size_of::() as u32; const CALLBACK_SAVE_BYTES: u32 = 16; -const SUB_RSP_SAVE: &[u8] = &[0x48, 0x83, 0xec, CALLBACK_SAVE_BYTES as u8]; -const ADD_RSP_SAVE: &[u8] = &[0x48, 0x83, 0xc4, CALLBACK_SAVE_BYTES as u8]; -const STMXCSR_RSP: &[u8] = &[0x0f, 0xae, 0x1c, 0x24]; -const LDMXCSR_RSP: &[u8] = &[0x0f, 0xae, 0x14, 0x24]; -// Reuse the existing 16-byte reservation: original MXCSR at 0, default at 4. -// This baseline recipe costs 2 instructions/13 bytes, with no literal relocation -// or additional GPR spill. Actual emitted-code/timing gates remain separate. -const MOV_DEFAULT_MXCSR_RSP_4: &[u8] = &[0xc7, 0x44, 0x24, 4, 0x80, 0x1f, 0, 0]; -const LDMXCSR_RSP_4: &[u8] = &[0x0f, 0xae, 0x54, 0x24, 4]; -const PUSH_RDI: &[u8] = &[0x57]; -const POP_RDI: &[u8] = &[0x5f]; -const MOV_RDI_CONTEXT_DISP8: &[u8] = &[0x49, 0x8b, 0x7f]; -const LEA_RSI_RSP_DISP32: &[u8] = &[0x48, 0x8d, 0xb4, 0x24]; -const CALL_RDI_DISP8: &[u8] = &[0xff, 0x57]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const JNE_REL32: &[u8] = &[0x0f, 0x85]; -const MOV_RSP_DISP32_RAX: &[u8] = &[0x48, 0x89, 0x84, 0x24]; -const LEA_RDX_RSP_DISP32: &[u8] = &[0x48, 0x8d, 0x94, 0x24]; -const MOV_RSP_DISP32_RDX: &[u8] = &[0x48, 0x89, 0x94, 0x24]; -const MOV_RSP_DISP32_IMM32: &[u8] = &[0xc7, 0x84, 0x24]; -const MOVABS_RCX_IMM64: &[u8] = &[0x48, 0xb9]; -const MOV_RSP_DISP32_RCX: &[u8] = &[0x48, 0x89, 0x8c, 0x24]; -const MOV_RDX_CONTEXT_DISP8: &[u8] = &[0x49, 0x8b, 0x57]; -const MOV_RDX_DISP8_IMM32: &[u8] = &[0xc7, 0x42]; -const MOV_RDX_DISP8_RAX: &[u8] = &[0x48, 0x89, 0x42]; -const MOV_RDX_DISP8_RCX: &[u8] = &[0x48, 0x89, 0x4a]; -const MOV_RDX_DISP8_IMM32_QWORD: &[u8] = &[0x48, 0xc7, 0x42]; -const MOV_EAX_IMM32: u8 = 0xb8; +/// MXCSR's power-on value: every exception masked, round to nearest. +const DEFAULT_MXCSR: i32 = 0x1f80; +/// The caller's MXCSR, in the 16-byte reservation. +const SAVED_MXCSR: Mem = Mem::base(Gpr::Rsp, 0); +/// The default MXCSR, after the caller's. This baseline recipe costs 2 +/// instructions/13 bytes, with no literal relocation or additional GPR spill. +const LOADED_MXCSR: Mem = Mem::base(Gpr::Rsp, 4); -fn field_offset(offset: usize) -> u8 { - u8::try_from(offset).expect("memory view field fits positive disp8") +/// The memory view field at `offset` from RDX. +fn field(offset: usize) -> Mem { + Mem::base_disp8( + Gpr::Rdx, + i8::try_from(offset).expect("memory view field fits positive disp8"), + ) } -fn memory_pointer(code: &mut Vec) { - code.extend(MOV_RDX_CONTEXT_DISP8); - code.push(EXECUTION_CONTEXT_MEMORY_OFFSET as u8); +/// The memory view pointer in the execution context at R15. +const fn memory_view() -> Mem { + Mem::base_disp8(Gpr::R15, EXECUTION_CONTEXT_MEMORY_OFFSET as i8) +} + +fn memory_pointer(code: &mut Code) { + code.asm().mov_load(Size::Qword, Gpr::Rdx, memory_view()); } /// Start one instruction's exact reached-prefix record. Clobbers RDX only. -pub(crate) fn begin(code: &mut Vec) { +pub(crate) fn begin(code: &mut Code) { use crate::context::memory::MemoryContextView; memory_pointer(code); // v2 places the validated fault-access code directly after fault_kind. // Clear both before each reached instruction, including local faults. - code.extend(MOV_RDX_DISP8_IMM32_QWORD); - code.push(field_offset(offset_of!(MemoryContextView, fault_kind))); - code.extend((MemoryStatus::Success as u32).to_le_bytes()); - code.extend(MOV_RDX_DISP8_IMM32_QWORD); - code.push(field_offset(offset_of!(MemoryContextView, completed_bytes))); - code.extend(0_u32.to_le_bytes()); + let mut asm = code.asm(); + asm.mov_rm_imm32( + Size::Qword, + field(offset_of!(MemoryContextView, fault_kind)), + MemoryStatus::Success as i32, + ); + asm.mov_rm_imm32( + Size::Qword, + field(offset_of!(MemoryContextView, completed_bytes)), + 0, + ); } /// Build a request at a private stack offset. RAX supplies the guest address; /// data_offset names private staging relative to the current RSP. Clobbers RCX/RDX. pub(crate) fn request( - code: &mut Vec, + code: &mut Code, request_offset: u32, data_offset: u32, bytes: u32, @@ -78,24 +70,31 @@ pub(crate) fn request( MEMORY_REQUEST_ADDRESS_OFFSET, MEMORY_REQUEST_DATA_OFFSET, MEMORY_REQUEST_FLAGS_OFFSET, MEMORY_REQUEST_LENGTH_OFFSET, MEMORY_REQUEST_PC_OFFSET, }; - code.extend(MOV_RSP_DISP32_RAX); - code.extend((request_offset + MEMORY_REQUEST_ADDRESS_OFFSET).to_le_bytes()); - code.extend(LEA_RDX_RSP_DISP32); - code.extend(data_offset.to_le_bytes()); - code.extend(MOV_RSP_DISP32_RDX); - code.extend((request_offset + MEMORY_REQUEST_DATA_OFFSET).to_le_bytes()); + let stack = |offset: u32| Mem::base_disp32(Gpr::Rsp, offset as i32); + let mut asm = code.asm(); + asm.mov_store( + Size::Qword, + stack(request_offset + MEMORY_REQUEST_ADDRESS_OFFSET), + Gpr::Rax, + ); + asm.lea(Size::Qword, Gpr::Rdx, stack(data_offset)); + asm.mov_store( + Size::Qword, + stack(request_offset + MEMORY_REQUEST_DATA_OFFSET), + Gpr::Rdx, + ); for (field, value) in [ (MEMORY_REQUEST_LENGTH_OFFSET, bytes), (MEMORY_REQUEST_FLAGS_OFFSET, flags), ] { - code.extend(MOV_RSP_DISP32_IMM32); - code.extend((request_offset + field).to_le_bytes()); - code.extend(value.to_le_bytes()); + asm.mov_rm_imm32(Size::Dword, stack(request_offset + field), value as i32); } - code.extend(MOVABS_RCX_IMM64); - code.extend(pc.to_le_bytes()); - code.extend(MOV_RSP_DISP32_RCX); - code.extend((request_offset + MEMORY_REQUEST_PC_OFFSET).to_le_bytes()); + asm.mov_imm64(Gpr::Rcx, pc); + asm.mov_store( + Size::Qword, + stack(request_offset + MEMORY_REQUEST_PC_OFFSET), + Gpr::Rcx, + ); } /// Invoke the validated memory service. Before entry RSP must be 8 modulo16, @@ -104,30 +103,33 @@ pub(crate) fn request( /// Runs the callback under default MXCSR, then preserves the full caller /// MXCSR, including exception status bits, on success and refusal. Returns the /// typed MemoryStatus encoding in EAX. No callback address is embedded. -pub(crate) fn call(code: &mut Vec, request_offset: u32) { - code.extend(PUSH_RDI); - code.extend(SUB_RSP_SAVE); - code.extend(STMXCSR_RSP); - code.extend(MOV_DEFAULT_MXCSR_RSP_4); - code.extend(LDMXCSR_RSP_4); - code.extend(MOV_RDI_CONTEXT_DISP8); - code.push(EXECUTION_CONTEXT_MEMORY_OFFSET as u8); - code.extend(LEA_RSI_RSP_DISP32); - code.extend((request_offset + HOST_POINTER_BYTES + CALLBACK_SAVE_BYTES).to_le_bytes()); - code.extend(CALL_RDI_DISP8); - code.push(MEMORY_CALLBACK_OFFSET as u8); - code.extend(LDMXCSR_RSP); - code.extend(ADD_RSP_SAVE); - code.extend(POP_RDI); +pub(crate) fn call(code: &mut Code, request_offset: u32) { + let mut asm = code.asm(); + asm.push(Gpr::Rdi); + asm.alu_imm8(Alu::Sub, Size::Qword, Gpr::Rsp, CALLBACK_SAVE_BYTES as i8); + asm.stmxcsr(SAVED_MXCSR); + asm.mov_rm_imm32(Size::Dword, LOADED_MXCSR, DEFAULT_MXCSR); + asm.ldmxcsr(LOADED_MXCSR); + asm.mov_load(Size::Qword, Gpr::Rdi, memory_view()); + asm.lea( + Size::Qword, + Gpr::Rsi, + Mem::base_disp32( + Gpr::Rsp, + (request_offset + HOST_POINTER_BYTES + CALLBACK_SAVE_BYTES) as i32, + ), + ); + asm.call_rm(Mem::base_disp8(Gpr::Rdi, MEMORY_CALLBACK_OFFSET as i8)); + asm.ldmxcsr(SAVED_MXCSR); + asm.alu_imm8(Alu::Add, Size::Qword, Gpr::Rsp, CALLBACK_SAVE_BYTES as i8); + asm.pop(Gpr::Rdi); } /// Emit a failure branch; patch the returned displacement to family cleanup. -pub(crate) fn branch_failed(code: &mut Vec) -> usize { - code.extend(TEST_EAX_EAX); - code.extend(JNE_REL32); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement +pub(crate) fn branch_failed(code: &mut Code) -> usize { + let mut asm = code.asm(); + asm.test(Size::Dword, Gpr::Rax, Gpr::Rax); + asm.jcc(Cond::Ne).offset() } pub(crate) fn patch_branch(code: &mut [u8], displacement: usize, destination: usize) { @@ -139,18 +141,25 @@ pub(crate) fn patch_branch(code: &mut [u8], displacement: usize, destination: us /// Record a fault found in emitted code (such as SP misalignment). RAX is the /// faulting address; the completed prefix stays. Clobbers RCX/RDX. -pub(crate) fn fault(code: &mut Vec, status: MemoryStatus, pc: u64) { +pub(crate) fn fault(code: &mut Code, status: MemoryStatus, pc: u64) { use crate::context::memory::MemoryContextView; memory_pointer(code); - code.extend(MOV_RDX_DISP8_IMM32); - code.push(field_offset(offset_of!(MemoryContextView, fault_kind))); - code.extend((status as u32).to_le_bytes()); - code.extend(MOV_RDX_DISP8_RAX); - code.push(field_offset(offset_of!(MemoryContextView, fault_address))); - code.extend(MOVABS_RCX_IMM64); - code.extend(pc.to_le_bytes()); - code.extend(MOV_RDX_DISP8_RCX); - code.push(field_offset(offset_of!(MemoryContextView, fault_pc))); - code.push(MOV_EAX_IMM32); - code.extend((status as u32).to_le_bytes()); + let mut asm = code.asm(); + asm.mov_rm_imm32( + Size::Dword, + field(offset_of!(MemoryContextView, fault_kind)), + status as i32, + ); + asm.mov_store( + Size::Qword, + field(offset_of!(MemoryContextView, fault_address)), + Gpr::Rax, + ); + asm.mov_imm64(Gpr::Rcx, pc); + asm.mov_store( + Size::Qword, + field(offset_of!(MemoryContextView, fault_pc)), + Gpr::Rcx, + ); + asm.mov_imm32(Gpr::Rax, status as u32); } diff --git a/crates/stela-compiler/src/x86_64/memory_store.rs b/crates/stela-compiler/src/x86_64/memory_store.rs index 638170fd85..c7978df43f 100644 --- a/crates/stela-compiler/src/x86_64/memory_store.rs +++ b/crates/stela-compiler/src/x86_64/memory_store.rs @@ -1,5 +1,6 @@ //! Direct stores to private RAM, keeping the completed prefix when a later page //! faults. The protection granule is assumed to be at least 4 KiB. +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, ShiftOp, Size}; use alloc::vec::Vec; pub(crate) mod checked_pair; pub(crate) mod checked_scalar; @@ -15,30 +16,6 @@ const VECTOR_BYTES: u8 = 16; /// input at this boundary; a full-width shuffle also avoids a merge dependency. const HIGH_QWORD_SCRATCH_XMM: u8 = 2; const DUPLICATE_HIGH_QWORD: u8 = 0xee; -const OPERAND_SIZE_PREFIX: u8 = 0x66; -const REP_PREFIX: u8 = 0xf3; -const SSE_ESCAPE: u8 = 0x0f; -const MOVD_STORE: u8 = 0x7e; -const MOVQ_STORE: u8 = 0xd6; -const MOVDQU_STORE: u8 = 0x7f; -const REX_PREFIX: u8 = 0x40; -const REX_WIDE: u8 = 0x08; -const REX_EXTENDED_SOURCE: u8 = 0x04; -const REGISTER_SHIFT: u8 = 3; -const RCX_REGISTER: u8 = 1; -const R8_REGISTER_LOW: u8 = 0; -const MODRM_DISP8: u8 = 0x40; -const MOV_BYTE: u8 = 0x88; -const MOV_WORD_OR_WIDER: u8 = 0x89; -const LEA_R10D_RAX_DISP8: &[u8] = &[0x44, 0x8d, 0x50]; -const XOR_R10D_EAX: &[u8] = &[0x41, 0x31, 0xc2]; -const TEST_R10D_IMM32: &[u8] = &[0x41, 0xf7, 0xc2]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JMP_REL32: u8 = 0xe9; -const MOV_RCX_R8: &[u8] = &[0x4c, 0x89, 0xc1]; -const MOVQ_RCX_XMM: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const SHR_RCX_IMM8: &[u8] = &[0x48, 0xc1, 0xe9]; -const MODRM_RCX: u8 = 0xc1; #[derive(Clone, Copy)] pub(super) enum Source { @@ -70,30 +47,56 @@ pub(super) fn aligned_register_offset( /// RCX, R10 and XMM2 are scratch on the crossing path. The selected XMM0/XMM1 /// source remains whole, including where the block retains XMM0 for a later /// instruction. -pub(super) fn emit(code: &mut Vec, bytes: u8, displacement: u8, source: Source, aligned: bool) { +pub(super) fn emit(code: &mut Code, bytes: u8, displacement: u8, source: Source, aligned: bool) { + emit_marking(code, bytes, displacement, source, aligned, &mut None); +} + +/// [`emit`], pushing the end of each instruction to `ends` when given. +fn emit_marking( + code: &mut Code, + bytes: u8, + displacement: u8, + source: Source, + aligned: bool, + ends: &mut Option>, +) { debug_assert!(bytes.is_power_of_two() && bytes <= VECTOR_BYTES); debug_assert!(displacement == 0 || displacement == bytes); if bytes == 1 || aligned { fast(code, bytes, displacement, source); + mark(code, ends); return; } // An access crossing a 4 KiB boundary flips address bit 12. Comparing // against the pair's base may conservatively include the second element. - code.extend(LEA_R10D_RAX_DISP8); - code.push(displacement + bytes - 1); - code.extend(XOR_R10D_EAX); - code.extend(TEST_R10D_IMM32); - code.extend(PROTECTION_GRANULE_BYTES.to_le_bytes()); - code.extend(JZ_REL32); - let fast_jump = code.len(); - code.extend(0i32.to_le_bytes()); - prefix_store(code, bytes, displacement, source); - code.push(JMP_REL32); - let done_jump = code.len(); - code.extend(0i32.to_le_bytes()); - patch_jump(code, fast_jump); + let mut asm = code.asm(); + asm.lea( + Size::Dword, + Gpr::R10, + Mem::base_disp8(Gpr::Rax, (displacement + bytes - 1) as i8), + ); + mark(code, ends); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::R10, Gpr::Rax); + mark(code, ends); + code.asm() + .test_imm(Size::Dword, Gpr::R10, PROTECTION_GRANULE_BYTES as i32); + mark(code, ends); + let fast_jump = code.asm().jcc(Cond::E); + mark(code, ends); + prefix_store(code, bytes, displacement, source, ends); + let done_jump = code.asm().jmp(); + mark(code, ends); + code.asm().bind(fast_jump); fast(code, bytes, displacement, source); - patch_jump(code, done_jump); + mark(code, ends); + code.asm().bind(done_jump); +} + +/// Push the code's length, the end of the instruction just emitted, to `ends`. +fn mark(code: &Code, ends: &mut Option>) { + if let Some(ends) = ends { + ends.push(code.len()); + } } /// The page-crossing store of a halfword, word or doubleword staged in RCX to @@ -104,85 +107,59 @@ pub(super) fn crossing_store(bytes: u8) -> Option<(Vec, Vec)> { if !matches!(bytes, HALFWORD_BYTES | DWORD_BYTES | QWORD_BYTES) { return None; } - let mut code = Vec::new(); - emit(&mut code, bytes, 0, Source::Rcx, false); + let mut code = Code::new(); // LEA, XOR, TEST and JZ; every byte's shift but the first and its byte // store; JMP; then the fast path's one store. - let mut ends = Vec::new(); - let mut end = 0; - for length in [ - LEA_R10D_RAX_DISP8.len() + 1, - XOR_R10D_EAX.len(), - TEST_R10D_IMM32.len() + size_of::(), - JZ_REL32.len() + size_of::(), - ] { - end += length; - ends.push(end); - } - for byte in 0..bytes { - if byte != 0 { - end += SHR_RCX_IMM8.len() + 1; - ends.push(end); - } - // MOV [RAX], CL, or MOV [RAX+disp8], CL. - end += if byte == 0 { 2 } else { 3 }; - ends.push(end); - } - end += 1 + size_of::(); - ends.push(end); - ends.push(code.len()); - Some((code, ends)) + let mut ends = Some(Vec::new()); + emit_marking(&mut code, bytes, 0, Source::Rcx, false, &mut ends); + Some((code.into_bytes(), ends.unwrap_or_default())) } -fn fast(code: &mut Vec, bytes: u8, displacement: u8, source: Source) { - let register = match source { - Source::Xmm(xmm) => { - let (prefix, opcode) = match bytes { - DWORD_BYTES => (OPERAND_SIZE_PREFIX, MOVD_STORE), - QWORD_BYTES => (OPERAND_SIZE_PREFIX, MOVQ_STORE), - VECTOR_BYTES => (REP_PREFIX, MOVDQU_STORE), - _ => unreachable!("narrow vectors are staged through RCX"), - }; - code.extend([prefix, SSE_ESCAPE, opcode]); - xmm - } +fn fast(code: &mut Code, bytes: u8, displacement: u8, source: Source) { + let target = Mem::base(Gpr::Rax, i32::from(displacement)); + let mut asm = code.asm(); + match source { + Source::Xmm(xmm) => match bytes { + DWORD_BYTES => asm.movd_from_xmm(target, xmm), + QWORD_BYTES => asm.movq_store(xmm, target), + VECTOR_BYTES => asm.movdqu_store(target, xmm), + _ => unreachable!("narrow vectors are staged through RCX"), + }, Source::Rcx | Source::R8 => { debug_assert!(bytes <= QWORD_BYTES); - if bytes == HALFWORD_BYTES { - code.push(OPERAND_SIZE_PREFIX); - } - let rex = if bytes == QWORD_BYTES { REX_WIDE } else { 0 } - | if matches!(source, Source::R8) { - REX_EXTENDED_SOURCE - } else { - 0 - }; - if rex != 0 { - code.push(REX_PREFIX | rex); - } - code.push(if bytes == 1 { - MOV_BYTE + let size = match bytes { + 1 => Size::Byte, + HALFWORD_BYTES => Size::Word, + DWORD_BYTES => Size::Dword, + _ => Size::Qword, + }; + let register = if matches!(source, Source::R8) { + Gpr::R8 } else { - MOV_WORD_OR_WIDER - }); - if matches!(source, Source::R8) { - R8_REGISTER_LOW - } else { - RCX_REGISTER - } + Gpr::Rcx + }; + asm.mov_store(size, target, register); } - }; - code.push((register << REGISTER_SHIFT) | if displacement == 0 { 0 } else { MODRM_DISP8 }); - if displacement != 0 { - code.push(displacement); } } -fn prefix_store(code: &mut Vec, bytes: u8, displacement: u8, source: Source) { +fn prefix_store( + code: &mut Code, + bytes: u8, + displacement: u8, + source: Source, + ends: &mut Option>, +) { match source { Source::Rcx => {} - Source::R8 => code.extend(MOV_RCX_R8), - Source::Xmm(xmm) => extract_qword(code, xmm), + Source::R8 => { + code.asm().mov(Size::Qword, Gpr::Rcx, Gpr::R8); + mark(code, ends); + } + Source::Xmm(xmm) => { + extract_qword(code, xmm); + mark(code, ends); + } } for byte in 0..bytes { if byte == QWORD_BYTES { @@ -193,31 +170,29 @@ fn prefix_store(code: &mut Vec, bytes: u8, displacement: u8, source: Source) xmm, HIGH_QWORD_SCRATCH_XMM, "store input aliases its scratch" ); - SimdOpcode::ShuffleDword.register( + SimdOpcode::ShuffleDword.register_imm( code, HIGH_QWORD_SCRATCH_XMM, xmm, + DUPLICATE_HIGH_QWORD, crate::TargetCpu::Baseline, ); - code.push(DUPLICATE_HIGH_QWORD); + mark(code, ends); extract_qword(code, HIGH_QWORD_SCRATCH_XMM); + mark(code, ends); } else if byte != 0 { - code.extend(SHR_RCX_IMM8); - code.push(BYTE_BITS); + code.asm() + .shift_imm(ShiftOp::Shr, Size::Qword, Gpr::Rcx, BYTE_BITS); + mark(code, ends); } fast(code, 1, displacement + byte, Source::Rcx); + mark(code, ends); } } -fn extract_qword(code: &mut Vec, xmm: u8) { - code.extend(MOVQ_RCX_XMM); - code.push(MODRM_RCX | (xmm << REGISTER_SHIFT)); -} - -fn patch_jump(code: &mut [u8], displacement: usize) { - let relative = i32::try_from(code.len() - displacement - size_of::()) - .expect("bounded ordinary-store branch"); - code[displacement..displacement + size_of::()].copy_from_slice(&relative.to_le_bytes()); +/// RCX = the low qword of `xmm`. +fn extract_qword(code: &mut Code, xmm: u8) { + code.asm().movq_from_xmm(Gpr::Rcx, xmm); } #[cfg(test)] diff --git a/crates/stela-compiler/src/x86_64/memory_store/checked_pair.rs b/crates/stela-compiler/src/x86_64/memory_store/checked_pair.rs index 76a96a5ca4..78eef556c8 100644 --- a/crates/stela-compiler/src/x86_64/memory_store/checked_pair.rs +++ b/crates/stela-compiler/src/x86_64/memory_store/checked_pair.rs @@ -1,6 +1,7 @@ //! Checked LDP/LDPSW/STP/LDNP/STNP as one pair request to the memory service. //! Load destinations and base writeback are written only after both elements //! succeed. +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Size}; use crate::{ aarch64::{AddressMode, MemoryTransfer, Operation, Register, Width, non_temporal::Data}, @@ -14,7 +15,6 @@ use crate::{ store, }, }; -use alloc::vec::Vec; const WORD_BYTES: u8 = size_of::() as u8; const DOUBLEWORD_BYTES: u8 = size_of::() as u8; @@ -30,17 +30,14 @@ const STACK_ALIGNMENT_BYTES: u32 = 16; const STACK_BYTES: u32 = (WRITEBACK_OFFSET + size_of::() as u32) .div_ceil(STACK_ALIGNMENT_BYTES) * STACK_ALIGNMENT_BYTES; -const SUB_RSP_IMM8: &[u8] = &[0x48, 0x83, 0xec]; -const ADD_RSP_IMM8: &[u8] = &[0x48, 0x83, 0xc4]; -const MOV_RSP_DISP8_EAX: &[u8] = &[0x89, 0x44, 0x24]; -const MOV_RSP_DISP8_RAX: &[u8] = &[0x48, 0x89, 0x44, 0x24]; -const MOV_RAX_RSP_DISP8: &[u8] = &[0x48, 0x8b, 0x44, 0x24]; -const MOV_RSP_DISP8_RDX: &[u8] = &[0x48, 0x89, 0x54, 0x24]; -const REX_W: u8 = 0x48; -const MOV_FROM_STAGING: u8 = 0x8b; -const MOVSXD_FROM_STAGING: u8 = 0x63; -const RAX_RSP_DISP8: &[u8] = &[0x44, 0x24]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; + +/// The private staging slot at `offset`. +fn staging(offset: u32) -> Mem { + Mem::base_disp8( + Gpr::Rsp, + i8::try_from(offset).expect("pair private staging fits disp8"), + ) +} /// Validated source operands, shared by temporal and non-temporal GPR pairs. /// Source-permitted constrained NOP encodings are decoded as Operation::Nop @@ -230,42 +227,40 @@ pub(crate) fn requirements(operand: &Operand) -> MemoryRequirements { } } -fn save_source(code: &mut Vec, register: Register, bytes: u8, destination: u32) { +/// The operand size of a `bytes`-wide pair element. +fn size(bytes: u8) -> Size { + Size::of(bytes == DOUBLEWORD_BYTES) +} + +fn save_source(code: &mut Code, register: Register, bytes: u8, destination: u32) { load(code, register); - code.extend(if bytes == WORD_BYTES { - MOV_RSP_DISP8_EAX - } else { - MOV_RSP_DISP8_RAX - }); - code.push(u8::try_from(destination).expect("pair private staging fits disp8")); + code.asm() + .mov_store(size(bytes), staging(destination), Gpr::Rax); } /// Read the private callback output with the source extension semantics. -fn load_result(code: &mut Vec, bytes: u8, signed: bool, width: Width, source: u32) { - if width == Width::X64 { - code.push(REX_W); - } - code.push(if signed { - MOVSXD_FROM_STAGING - } else { - MOV_FROM_STAGING - }); +fn load_result(code: &mut Code, bytes: u8, signed: bool, width: Width, source: u32) { debug_assert!(matches!( (bytes, signed), (WORD_BYTES, true) | (WORD_BYTES | DOUBLEWORD_BYTES, false) )); - code.extend(RAX_RSP_DISP8); - code.push(u8::try_from(source).expect("pair private staging fits disp8")); + let mut asm = code.asm(); + if signed { + debug_assert!(width == Width::X64); + asm.movsxd(Gpr::Rax, staging(source)); + } else { + asm.mov_load(Size::of(width == Width::X64), Gpr::Rax, staging(source)); + } } /// Emit an inner checked-context body. The caller has validated the descriptor, /// memory profile, capabilities and effective SP-alignment controls. RDI points /// to GuestState and R15 to ExecutionContext; callback failures leave completed /// RAM prefixes visible and return through the enclosing context wrapper. -pub(crate) fn emit_context(code: &mut Vec, operand: &Operand, pc: u64) { +pub(crate) fn emit_context(code: &mut Code, operand: &Operand, pc: u64) { debug_assert!(operand.is_valid()); - code.extend(SUB_RSP_IMM8); - code.push(STACK_BYTES as u8); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Gpr::Rsp, STACK_BYTES as i8); memory::begin(code); let sp_failure = if matches!(operand.profile, Profile::NormalWb(profile) if profile.sp_requirement() == SpAlignmentRequirement::Enabled) @@ -295,8 +290,8 @@ pub(crate) fn emit_context(code: &mut Vec, operand: &Operand, pc: u64) { }, ); if operand.mode != AddressMode::Offset { - code.extend(MOV_RSP_DISP8_RDX); - code.push(WRITEBACK_OFFSET as u8); + code.asm() + .mov_store(Size::Qword, staging(WRITEBACK_OFFSET), Gpr::Rdx); } memory::request( code, @@ -324,19 +319,19 @@ pub(crate) fn emit_context(code: &mut Vec, operand: &Operand, pc: u64) { } } if operand.mode != AddressMode::Offset { - code.extend(MOV_RAX_RSP_DISP8); - code.push(WRITEBACK_OFFSET as u8); + code.asm() + .mov_load(Size::Qword, Gpr::Rax, staging(WRITEBACK_OFFSET)); // A validated base is never ZR; no source is re-read after callback. store(code, operand.base); } - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); let cleanup = code.len(); memory::patch_branch(code, callback_failure, cleanup); if let Some(failure) = sp_failure { memory::patch_branch(code, failure, cleanup); } - code.extend(ADD_RSP_IMM8); - code.push(STACK_BYTES as u8); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Gpr::Rsp, STACK_BYTES as i8); address::return_if_failed(code); } diff --git a/crates/stela-compiler/src/x86_64/memory_store/checked_scalar.rs b/crates/stela-compiler/src/x86_64/memory_store/checked_scalar.rs index c675c5c360..b1fc312ed7 100644 --- a/crates/stela-compiler/src/x86_64/memory_store/checked_scalar.rs +++ b/crates/stela-compiler/src/x86_64/memory_store/checked_scalar.rs @@ -1,5 +1,6 @@ //! Checked scalar loads and stores through the memory service. Guest registers //! are written after the access completes. +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Size}; use crate::x86_64::{ load, memory_context::{self as service, address}, @@ -16,19 +17,17 @@ use crate::{ }, }; use alloc::vec; -use alloc::vec::Vec; const DOUBLEWORD_BYTES: u8 = size_of::() as u8; const REQUEST_OFFSET: u32 = 0; const DATA_OFFSET: u32 = 32; const WRITEBACK_OFFSET: u32 = 40; const SCRATCH_BYTES: u8 = 48; -const SUB_RSP: &[u8] = &[0x48, 0x83, 0xec, SCRATCH_BYTES]; -const ADD_RSP: &[u8] = &[0x48, 0x83, 0xc4, SCRATCH_BYTES]; -const MOV_RSP_RAX: &[u8] = &[0x48, 0x89, 0x84, 0x24]; -const MOV_RSP_RDX: &[u8] = &[0x48, 0x89, 0x94, 0x24]; -const MOV_RAX_RSP: &[u8] = &[0x48, 0x8b, 0x84, 0x24]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; + +/// The private scratch slot at `offset`. +const fn scratch(offset: u32) -> Mem { + Mem::base_disp32(Gpr::Rsp, offset as i32) +} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Address { @@ -286,26 +285,28 @@ pub(crate) fn requirements(operand: &Operand) -> MemoryRequirements { } } -fn result(code: &mut Vec, bytes: u8, signed: bool, width: Width) { - if width == Width::X64 { - code.push(0x48); - } +fn result(code: &mut Code, bytes: u8, signed: bool, width: Width) { + let size = Size::of(width == Width::X64); + let data = scratch(DATA_OFFSET); + let mut asm = code.asm(); match (bytes, signed) { - (1, false) => code.extend([0x0f, 0xb6]), - (2, false) => code.extend([0x0f, 0xb7]), - (1, true) => code.extend([0x0f, 0xbe]), - (2, true) => code.extend([0x0f, 0xbf]), - (4, true) => code.push(0x63), - (4 | 8, false) => code.push(0x8b), + (1, false) => asm.movzx(size, Gpr::Rax, Size::Byte, data), + (2, false) => asm.movzx(size, Gpr::Rax, Size::Word, data), + (1, true) => asm.movsx(size, Gpr::Rax, Size::Byte, data), + (2, true) => asm.movsx(size, Gpr::Rax, Size::Word, data), + (4, true) => { + debug_assert!(size == Size::Qword); + asm.movsxd(Gpr::Rax, data); + } + (4 | 8, false) => asm.mov_load(size, Gpr::Rax, data), _ => unreachable!("validated scalar result"), } - code.extend([0x84, 0x24]); - code.extend(DATA_OFFSET.to_le_bytes()); } -pub(crate) fn emit_context(code: &mut Vec, operand: &Operand, pc: u64) { +pub(crate) fn emit_context(code: &mut Code, operand: &Operand, pc: u64) { let req = requirements(operand); - code.extend(SUB_RSP); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Gpr::Rsp, SCRATCH_BYTES as i8); service::begin(code); let mut failures = vec![]; if operand.profile.sp_requirement() == SpAlignmentRequirement::Enabled @@ -315,8 +316,8 @@ pub(crate) fn emit_context(code: &mut Vec, operand: &Operand, pc: u64) { } if matches!(operand.transfer, MemoryTransfer::Store) { load(code, operand.data); - code.extend(MOV_RSP_RAX); - code.extend(DATA_OFFSET.to_le_bytes()); + code.asm() + .mov_store(Size::Qword, scratch(DATA_OFFSET), Gpr::Rax); } match operand.address { Address::Literal { address } => crate::x86_64::immediate(code, address), @@ -341,8 +342,8 @@ pub(crate) fn emit_context(code: &mut Vec, operand: &Operand, pc: u64) { ), } if operand.writeback() { - code.extend(MOV_RSP_RDX); - code.extend(WRITEBACK_OFFSET.to_le_bytes()); + code.asm() + .mov_store(Size::Qword, scratch(WRITEBACK_OFFSET), Gpr::Rdx); } service::request( code, @@ -361,16 +362,17 @@ pub(crate) fn emit_context(code: &mut Vec, operand: &Operand, pc: u64) { store(code, operand.data); } if operand.writeback() { - code.extend(MOV_RAX_RSP); - code.extend(WRITEBACK_OFFSET.to_le_bytes()); + code.asm() + .mov_load(Size::Qword, Gpr::Rax, scratch(WRITEBACK_OFFSET)); store(code, operand.base); } - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); let cleanup = code.len(); for failed in failures { service::patch_branch(code, failed, cleanup); } - code.extend(ADD_RSP); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Gpr::Rsp, SCRATCH_BYTES as i8); address::return_if_failed(code); } @@ -396,10 +398,10 @@ mod tests { .unwrap(); let traffic = operand.profile_success_traffic(); assert_eq!((traffic.gpr_frame_loads, traffic.gpr_direct_stores), (4, 0)); - let mut code = Vec::new(); + let mut code = Code::new(); emit_context(&mut code, &operand, 0x4000); for (register, count) in [(Register::X(0), 1), (Register::Sp, 2)] { - let mut expected = Vec::new(); + let mut expected = Code::new(); load(&mut expected, register); assert_eq!( code.windows(expected.len()) diff --git a/crates/stela-compiler/src/x86_64/native.rs b/crates/stela-compiler/src/x86_64/native.rs new file mode 100644 index 0000000000..d441ec3d68 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/native.rs @@ -0,0 +1,47 @@ +//! Running emitted code on the host in tests. +use crate::GuestState; + +/// Run `code`, followed by a RET, on the host with RDI = `state`. +pub(crate) fn run(code: &[u8], state: &mut GuestState) { + use core::ffi::c_void; + unsafe extern "C" { + fn mmap( + address: *mut c_void, + bytes: usize, + protection: i32, + flags: i32, + fd: i32, + offset: i64, + ) -> *mut c_void; + fn mprotect(address: *mut c_void, bytes: usize, protection: i32) -> i32; + fn munmap(address: *mut c_void, bytes: usize) -> i32; + } + #[cfg(target_os = "macos")] + const MAP_ANONYMOUS: i32 = 0x1000; + #[cfg(target_os = "linux")] + const MAP_ANONYMOUS: i32 = 0x20; + const PROT_READ_WRITE: i32 = 3; + const PROT_READ_EXECUTE: i32 = 5; + const MAP_PRIVATE: i32 = 2; + const RET: u8 = 0xc3; + let bytes = (code.len() + 1).next_multiple_of(4096); + // SAFETY: private anonymous memory, RX after the copy and unmapped after + // the call; the code touches only `state`. + unsafe { + let page = mmap( + core::ptr::null_mut(), + bytes, + PROT_READ_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0, + ); + assert_ne!(page as usize, usize::MAX); + core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); + page.cast::().add(code.len()).write(RET); + assert_eq!(mprotect(page, bytes, PROT_READ_EXECUTE), 0); + let entry: unsafe extern "sysv64" fn(*mut GuestState) = core::mem::transmute(page); + entry(state); + assert_eq!(munmap(page, bytes), 0); + } +} diff --git a/crates/stela-compiler/src/x86_64/non_temporal.rs b/crates/stela-compiler/src/x86_64/non_temporal.rs index 2e24b19d55..bbdb7e4855 100644 --- a/crates/stela-compiler/src/x86_64/non_temporal.rs +++ b/crates/stela-compiler/src/x86_64/non_temporal.rs @@ -5,12 +5,12 @@ use crate::aarch64::{ non_temporal::{Data, Operand}, simd::Operand as SimdOperand, }; -use alloc::vec::Vec; +use crate::x86_64::asm::Code; const DWORD_BYTES: u8 = 4; const QWORD_BYTES: u8 = 8; -pub(super) fn emit(code: &mut Vec, operand: &Operand, checks: super::MemoryChecks) { +pub(super) fn emit(code: &mut Code, operand: &Operand, checks: super::MemoryChecks) { match operand.data { Data::Integer(data) => { let transfer = if operand.load { diff --git a/crates/stela-compiler/src/x86_64/ordered.rs b/crates/stela-compiler/src/x86_64/ordered.rs index 04e7773a54..bce8b341e5 100644 --- a/crates/stela-compiler/src/x86_64/ordered.rs +++ b/crates/stela-compiler/src/x86_64/ordered.rs @@ -7,6 +7,8 @@ //! DMB emits nothing: no other agent observes guest memory, and one PE //! observes its own accesses in program order. use super::atomic::{address_offset, commit_rax, input_rcx, read_rax, store_rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, Patch, Rm, ShiftOp, Size}; +use crate::x86_64::isa::SimdOpcode; use crate::{ TargetCpu, aarch64::{ @@ -14,7 +16,6 @@ use crate::{ ordered::{Barrier, Kind, LoadExtension, Operand}, }, }; -use alloc::vec::Vec; const BYTE_BYTES: u8 = 1; const HALFWORD_BYTES: u8 = 2; @@ -24,41 +25,19 @@ const ATOMIC_QUANTITY_BYTES: u8 = 16; const BASELINE_ATOMIC_BYTES: u8 = 8; const BASELINE_ATOMIC_MASK: u8 = BASELINE_ATOMIC_BYTES - 1; const BITS_PER_BYTE_SHIFT: u8 = 3; -const OPERAND_SIZE_PREFIX: u8 = 0x66; -const REX_W_PREFIX: u8 = 0x48; -const TWO_BYTE_OPCODE: u8 = 0x0f; -const MOVSX_BYTE: u8 = 0xbe; -const MOVSX_HALFWORD: u8 = 0xbf; -const MOVSXD: u8 = 0x63; -const RDX_ADDRESS: u8 = 2; -const RAX_REGISTER: u8 = 0xc0; -const XCHG_BYTE: u8 = 0x86; -const XCHG_WIDER: u8 = 0x87; -const RCX_RDX_MEMORY: u8 = 0x0a; -const MFENCE: &[u8] = &[0x0f, 0xae, 0xf0]; -const NOP: u8 = 0x90; -const MOV_ECX_EDX: &[u8] = &[0x89, 0xd1]; -const AND_ECX_IMM8: &[u8] = &[0x83, 0xe1]; -const CMP_CL_IMM8: &[u8] = &[0x80, 0xf9]; -const JA_REL8: u8 = 0x77; -const JMP_REL8: u8 = 0xeb; -const SHL_ECX_IMM8: &[u8] = &[0xc1, 0xe1]; -const AND_RDX_IMM8: &[u8] = &[0x48, 0x83, 0xe2]; -const MOVDQA_XMM0_RDX: &[u8] = &[0x66, 0x0f, 0x6f, 0x02]; -const MOVQ_RAX_XMM0: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xc0]; -/// The high quadword to the low one. (MOVHLPS is not on Intel's data operand -/// independent timing list.) -const PUNPCKHQDQ_XMM0_XMM0: &[u8] = &[0x66, 0x0f, 0x6d, 0xc0]; -const MOVQ_R8_XMM0: &[u8] = &[0x66, 0x49, 0x0f, 0x7e, 0xc0]; -const SHRD_RAX_R8_CL: &[u8] = &[0x4c, 0x0f, 0xad, 0xc0]; -const SHRD_RAX_R8_IMM8: &[u8] = &[0x4c, 0x0f, 0xac, 0xc0]; -const MOVZX_EAX_AX: &[u8] = &[0x0f, 0xb7, 0xc0]; -const MOV_EAX_EAX: &[u8] = &[0x89, 0xc0]; -const MOV_EAX_EDX: &[u8] = &[0x89, 0xd0]; -const AND_EAX_IMM8: &[u8] = &[0x83, 0xe0]; -const CMP_AL_IMM8: u8 = 0x3c; -const JBE_REL8: u8 = 0x76; const ATOMIC_QUANTITY_MASK: u8 = ATOMIC_QUANTITY_BYTES - 1; +/// `[rdx]`, the checked guest address. +const ADDRESS: Mem = Mem::base(Gpr::Rdx, 0); + +/// The operand size of a `bytes`-wide access. +fn size(bytes: u8) -> Size { + match bytes { + BYTE_BYTES => Size::Byte, + HALFWORD_BYTES => Size::Word, + DWORD_BYTES => Size::Dword, + _ => Size::Qword, + } +} /// Whether an ordered access crosses its 16-byte granule, which it may only /// with SCTLR_ELx.nAA set (no granule check). @@ -86,26 +65,22 @@ fn crossing(base: Register, bytes: u8, displacement: i32, checks: super::MemoryC } } -/// Jump, by a rel8 the caller patches, when the access at RDX lies inside +/// Jump, by a rel8 the caller binds, when the access at RDX lies inside /// its 16-byte granule. EAX is scratch. -fn branch_within_granule(code: &mut Vec, bytes: u8) -> usize { - code.extend(MOV_EAX_EDX); - code.extend(AND_EAX_IMM8); - code.push(ATOMIC_QUANTITY_MASK); - code.extend([CMP_AL_IMM8, ATOMIC_QUANTITY_BYTES - bytes, JBE_REL8]); - code.push(0); - code.len() - 1 +fn branch_within_granule(code: &mut Code, bytes: u8) -> Patch { + let mut asm = code.asm(); + asm.mov(Size::Dword, Gpr::Rax, Gpr::Rdx); + asm.alu_imm8(Alu::And, Size::Dword, Gpr::Rax, ATOMIC_QUANTITY_MASK as i8); + asm.alu_accumulator_imm8(Alu::Cmp, ATOMIC_QUANTITY_BYTES - bytes); + asm.jcc8(Cond::Be) } -fn jump_over(code: &mut Vec) -> usize { - code.extend([JMP_REL8, 0]); - code.len() - 1 +fn jump_over(code: &mut Code) -> Patch { + code.asm().jmp8() } -fn patch(code: &mut [u8], at: usize) { - code[at] = i8::try_from(code.len() - at - 1) - .expect("ordered path fits rel8") - .to_le_bytes()[0]; +fn patch(code: &mut Code, branch: Patch) { + code.asm().bind(branch); } /// Generic wider loads can cross eight bytes. A checked, so aligned, SP makes @@ -141,7 +116,7 @@ pub(super) fn requires_atomic_load16( } pub(super) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, target: TargetCpu, checks: super::MemoryChecks, @@ -153,8 +128,8 @@ pub(super) fn emit( // and writes→writes. Full barriers additionally close store→load, // which only another agent could observe. match requirement { - Barrier::All if !plain => code.extend(MFENCE), - Barrier::All | Barrier::Reads | Barrier::Writes => code.push(NOP), + Barrier::All if !plain => code.asm().mfence(), + Barrier::All | Barrier::Reads | Barrier::Writes => code.asm().nop(), } } Operand::Transfer { @@ -221,9 +196,15 @@ pub(super) fn emit( if base == Register::Sp && checks.stack_alignment { let offset = displacement.rem_euclid(i32::from(BASELINE_ATOMIC_BYTES)) as u8; - snapshot_value(code, bytes, extension, Some(offset << BITS_PER_BYTE_SHIFT)); + snapshot_value( + code, + bytes, + extension, + Some(offset << BITS_PER_BYTE_SHIFT), + target, + ); } else { - acquire_snapshot(code, bytes, extension); + acquire_snapshot(code, bytes, extension, target); } } else { read_extended(code, bytes, extension); @@ -241,97 +222,83 @@ pub(super) fn emit( /// A store-release that crosses its granule: a plain store, which x86 keeps /// in order after earlier accesses, and MFENCE, which keeps later /// load-acquires after it (RCsc). -fn crossing_release(code: &mut Vec, bytes: u8) { +fn crossing_release(code: &mut Code, bytes: u8) { store_rcx(code, bytes); - code.extend(MFENCE); + code.asm().mfence(); } -fn release(code: &mut Vec, bytes: u8) { - if bytes == HALFWORD_BYTES { - code.push(OPERAND_SIZE_PREFIX); - } else if bytes == QWORD_BYTES { - code.push(REX_W_PREFIX); - } - code.extend([ - if bytes == BYTE_BYTES { - XCHG_BYTE - } else { - XCHG_WIDER - }, - RCX_RDX_MEMORY, - ]); +fn release(code: &mut Code, bytes: u8) { + code.asm().xchg(size(bytes), ADDRESS, Gpr::Rcx); } -fn read_extended(code: &mut Vec, bytes: u8, extension: LoadExtension) { +fn read_extended(code: &mut Code, bytes: u8, extension: LoadExtension) { match extension { LoadExtension::Zero => read_rax(code, bytes), - LoadExtension::Sign(width) => sign_extend(code, bytes, width, RDX_ADDRESS), + LoadExtension::Sign(width) => sign_extend(code, bytes, width, ADDRESS.into()), } } /// The memory and register forms share the same extension semantics. A W result /// clears upper X bits through its 32-bit destination; an X result sign-fills them. -fn sign_extend(code: &mut Vec, bytes: u8, width: Width, operand: u8) { - if width == Width::X64 { - code.push(REX_W_PREFIX); - } +fn sign_extend(code: &mut Code, bytes: u8, width: Width, operand: Rm) { + let wide = Size::of(width == Width::X64); + let mut asm = code.asm(); match bytes { - BYTE_BYTES => code.extend([TWO_BYTE_OPCODE, MOVSX_BYTE, operand]), - HALFWORD_BYTES => code.extend([TWO_BYTE_OPCODE, MOVSX_HALFWORD, operand]), - DWORD_BYTES if width == Width::X64 => code.extend([MOVSXD, operand]), + BYTE_BYTES | HALFWORD_BYTES => asm.movsx(wide, Gpr::Rax, size(bytes), operand), + DWORD_BYTES if width == Width::X64 => asm.movsxd(Gpr::Rax, operand), _ => unreachable!("decoder validates ordered signed widths"), } } /// A legal ordered access is contained inside 16 bytes. Exact reads contained inside eight bytes /// use the baseline guarantee; only the crossing path reads the containing 16 bytes. -fn acquire_snapshot(code: &mut Vec, bytes: u8, extension: LoadExtension) { - code.extend(MOV_ECX_EDX); - code.extend(AND_ECX_IMM8); - code.push(BASELINE_ATOMIC_MASK); - code.extend(CMP_CL_IMM8); - code.push(BASELINE_ATOMIC_BYTES - bytes); - code.push(JA_REL8); - let snapshot_branch = code.len(); - code.push(0); +fn acquire_snapshot(code: &mut Code, bytes: u8, extension: LoadExtension, target: TargetCpu) { + let mut asm = code.asm(); + asm.mov(Size::Dword, Gpr::Rcx, Gpr::Rdx); + asm.alu_imm8(Alu::And, Size::Dword, Gpr::Rcx, BASELINE_ATOMIC_MASK as i8); + asm.alu_byte_imm(Alu::Cmp, Gpr::Rcx, BASELINE_ATOMIC_BYTES - bytes); + let snapshot = asm.jcc8(Cond::A); read_extended(code, bytes, extension); - code.push(JMP_REL8); - let done_branch = code.len(); - code.push(0); - code[snapshot_branch] = i8::try_from(code.len() - snapshot_branch - 1) - .expect("exact load branch fits rel8") - .to_le_bytes()[0]; - - snapshot_value(code, bytes, extension, None); - code[done_branch] = i8::try_from(code.len() - done_branch - 1) - .expect("snapshot branch fits rel8") - .to_le_bytes()[0]; + let done = jump_over(code); + patch(code, snapshot); + snapshot_value(code, bytes, extension, None, target); + patch(code, done); } /// A known SP residue avoids a runtime boundary branch and variable shift setup. /// Generic crossings retain their established CL recipe and output bytes. -fn snapshot_value(code: &mut Vec, bytes: u8, extension: LoadExtension, shift: Option) { +fn snapshot_value( + code: &mut Code, + bytes: u8, + extension: LoadExtension, + shift: Option, + target: TargetCpu, +) { + let mut asm = code.asm(); if shift.is_none() { - code.extend(SHL_ECX_IMM8); - code.push(BITS_PER_BYTE_SHIFT); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Gpr::Rcx, BITS_PER_BYTE_SHIFT); } - code.extend(AND_RDX_IMM8); - code.push(0u8.wrapping_sub(ATOMIC_QUANTITY_BYTES)); - code.extend(MOVDQA_XMM0_RDX); - code.extend(MOVQ_RAX_XMM0); - code.extend(PUNPCKHQDQ_XMM0_XMM0); - code.extend(MOVQ_R8_XMM0); - if let Some(shift) = shift { - code.extend(SHRD_RAX_R8_IMM8); - code.push(shift); - } else { - code.extend(SHRD_RAX_R8_CL); + asm.alu_imm8( + Alu::And, + Size::Qword, + Gpr::Rdx, + -i8::try_from(ATOMIC_QUANTITY_BYTES).expect("granule fits imm8"), + ); + asm.simd(SimdOpcode::MoveAligned, 0, ADDRESS, target); + asm.movq_from_xmm(Gpr::Rax, 0); + // The high quadword to the low one. (MOVHLPS is not on Intel's data + // operand independent timing list.) + asm.simd(SimdOpcode::UnpackHighQword, 0, Rm::Xmm(0), target); + asm.movq_from_xmm(Gpr::R8, 0); + match shift { + Some(shift) => asm.shrd_imm(Size::Qword, Gpr::Rax, Gpr::R8, shift), + None => asm.shrd_cl(Size::Qword, Gpr::Rax, Gpr::R8), } match extension { - LoadExtension::Sign(width) => sign_extend(code, bytes, width, RAX_REGISTER), + LoadExtension::Sign(width) => sign_extend(code, bytes, width, Gpr::Rax.into()), LoadExtension::Zero => match bytes { - HALFWORD_BYTES => code.extend(MOVZX_EAX_AX), - DWORD_BYTES => code.extend(MOV_EAX_EAX), + HALFWORD_BYTES => asm.movzx(Size::Dword, Gpr::Rax, Size::Word, Gpr::Rax), + DWORD_BYTES => asm.mov(Size::Dword, Gpr::Rax, Gpr::Rax), QWORD_BYTES => {} _ => unreachable!("only wider ordered loads can cross eight bytes"), }, @@ -343,6 +310,8 @@ mod tests { use super::*; use crate::x86_64::MemoryChecks; + const MFENCE: &[u8] = &[0x0f, 0xae, 0xf0]; + const MOVDQA_XMM0_RDX: &[u8] = &[0x66, 0x0f, 0x6f, 0x02]; const UNCHECKED: MemoryChecks = MemoryChecks { stack_alignment: false, ..MemoryChecks::DEFAULT @@ -437,7 +406,7 @@ mod tests { }; let has = |code: &[u8], bytes: &[u8]| code.windows(bytes.len()).any(|window| window == bytes); - let mut barrier = Vec::new(); + let mut barrier = Code::new(); emit( &mut barrier, &Operand::Barrier { @@ -447,7 +416,7 @@ mod tests { TargetCpu::detect(), single, ); - assert_eq!(barrier, [NOP]); + assert_eq!(barrier, [0x90]); for kind in [Kind::Acquire, Kind::AcquirePc, Kind::Release] { let operand = Operand::Transfer { feature: crate::aarch64::ordered::Feature::Base, @@ -458,7 +427,7 @@ mod tests { displacement: 0, extension: LoadExtension::Zero, }; - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, TargetCpu::detect(), single); // No XCHG, MFENCE, 16-byte snapshot or granule branch. assert!(!has(&code, &[0x48, 0x87, 0x0a]) && !has(&code, MFENCE)); @@ -480,7 +449,7 @@ mod tests { ..MemoryChecks::DEFAULT }; let emitted = |kind, base, displacement, checks| { - let mut code = Vec::new(); + let mut code = Code::new(); let operand = Operand::Transfer { feature: crate::aarch64::ordered::Feature::Base, kind, @@ -544,7 +513,7 @@ mod tests { displacement: 0, extension: LoadExtension::Zero, }; - let mut code = Vec::new(); + let mut code = Code::new(); emit( &mut code, &operand, diff --git a/crates/stela-compiler/src/x86_64/pc_relative.rs b/crates/stela-compiler/src/x86_64/pc_relative.rs index 16c027aba0..310ac595ae 100644 --- a/crates/stela-compiler/src/x86_64/pc_relative.rs +++ b/crates/stela-compiler/src/x86_64/pc_relative.rs @@ -1,28 +1,28 @@ //! ADR and ADRP as MOV of the computed guest address. use super::store; use crate::aarch64::{Register, pc_relative::Operand}; -use alloc::vec::Vec; +use crate::x86_64::asm::Code; -pub(super) fn emit(code: &mut Vec, operand: &Operand) { +pub(super) fn emit(code: &mut Code, operand: &Operand) { if operand.destination == Register::Zero { // Keep each guest instruction's native source-map interval nonempty. - code.push(0x90); + code.asm().nop(); return; } - code.extend([0x48, 0xb8]); // movabs rax,imm64; leaves guest NZCV untouched - code.extend(operand.address.to_le_bytes()); + // MOVABS leaves guest NZCV untouched. + super::immediate(code, operand.address); store(code, operand.destination); } #[cfg(test)] mod tests { use super::*; - use alloc::vec; + use alloc::vec::Vec; #[test] fn address_is_full_width_and_discarded_destination_keeps_map_interval() { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &Operand { @@ -46,8 +46,8 @@ mod tests { .into_iter() .flat_map(u32::to_le_bytes) .collect(); - let leaf = crate::compile(&source, crate::GuestAddress(0x100ffc)).unwrap(); - let block = crate::block::compile(&source, crate::GuestAddress(0x100ffc)).unwrap(); + let leaf = crate::testing::leaf(&source, crate::GuestAddress(0x100ffc)).unwrap(); + let block = crate::testing::block(&source, crate::GuestAddress(0x100ffc)).unwrap(); for native in [&leaf, &block.native] { assert_eq!( native.source_map, diff --git a/crates/stela-compiler/src/x86_64/pointer.rs b/crates/stela-compiler/src/x86_64/pointer.rs index a5a76f0fab..0f10d93979 100644 --- a/crates/stela-compiler/src/x86_64/pointer.rs +++ b/crates/stela-compiler/src/x86_64/pointer.rs @@ -25,6 +25,7 @@ //! clobbers RAX, RCX, RDX, R8, R9 and flags; a service call every register //! the SysV ABI lets a call clobber, which no block keeps live across its //! exit. The call aligns the stack to 16 bytes itself. +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, ShiftOp, Size, resolve}; use crate::{ GuestAddress, block::{ @@ -103,9 +104,9 @@ pub struct MemoEntry { } const _: () = assert!(core::mem::size_of::() == 32); -const MODIFIER: u8 = core::mem::offset_of!(MemoEntry, modifier) as u8; -const TAG: u8 = core::mem::offset_of!(MemoEntry, tag) as u8; -const VALUE: u8 = core::mem::offset_of!(MemoEntry, value) as u8; +const MODIFIER: i32 = core::mem::offset_of!(MemoEntry, modifier) as i32; +const TAG: i32 = core::mem::offset_of!(MemoEntry, tag) as i32; +const VALUE: i32 = core::mem::offset_of!(MemoEntry, value) as i32; /// The multiplier and shift of [`slot`]: the top 14 bits index the memo. const MIX: u64 = 0x9e37_79b9_7f4a_7c15; const SLOT_SHIFT: u8 = 50; @@ -230,143 +231,114 @@ pub struct Thunk { /// at `memo` under the tag words at `tags`, or through `service`, else /// exiting at `pc` for the engine. pub fn thunk(form: Form, pc: GuestAddress, memo: u64, tags: u64, service: Service) -> Thunk { - let mut code = Vec::with_capacity(256); + use Gpr::{R8, R9, R11, Rax, Rcx, Rdi, Rdx, Rsi, Rsp}; + use Size::{Dword, Qword}; + let mut code = Code::new(); + let mut asm = code.asm(); let mut exits = Vec::new(); - let pointer = u32::from(form.pointer) * 8; - code.extend([0x48, 0x8b, 0x87]); // mov rax,[rdi+pointer] - code.extend(pointer.to_le_bytes()); + let pointer = frame(u32::from(form.pointer) * 8); + asm.mov_load(Qword, Rax, pointer); match form.modifier { Modifier::Register(register) => { - code.extend([0x48, 0x8b, 0x97]); // mov rdx,[rdi+modifier] - code.extend((u32::from(register) * 8).to_le_bytes()); + asm.mov_load(Qword, Rdx, frame(u32::from(register) * 8)); } - Modifier::StackPointer => { - code.extend([0x48, 0x8b, 0x97]); - code.extend(STACK_POINTER.to_le_bytes()); - } - Modifier::Zero => code.extend([0x31, 0xd2]), // xor edx,edx + Modifier::StackPointer => asm.mov_load(Qword, Rdx, frame(STACK_POINTER)), + Modifier::Zero => asm.alu(Alu::Xor, Dword, Rdx, Rdx), } - code.extend([0x49, 0xb8]); // movabs r8,&tags[key] - code.extend((tags + u64::from(key_index(form.key)) * 8).to_le_bytes()); - code.extend([0x4d, 0x8b, 0x00]); // mov r8,[r8] - code.extend([0x4d, 0x85, 0xc0]); // test r8,r8 - jump(&mut code, &mut exits, JZ); // jz: the key is not open - let mut identities = Vec::new(); - code.extend([0x49, 0x83, 0xf8, DISABLED as u8]); // cmp r8,DISABLED - jump(&mut code, &mut identities, JZ); // je: the result is the pointer in RAX - code.extend([0x48, 0x89, 0xd1]); // mov rcx,rdx - code.extend([0x48, 0xc1, 0xc1, 29]); // rol rcx,29 - code.extend([0x48, 0x31, 0xc1]); // xor rcx,rax - code.extend([0x49, 0xb9]); // movabs r9,MIX - code.extend(MIX.to_le_bytes()); - code.extend([0x49, 0x0f, 0xaf, 0xc9]); // imul rcx,r9 - code.extend([0x48, 0xc1, 0xe9, SLOT_SHIFT]); // shr rcx,50 - code.extend([0x48, 0xc1, 0xe1, 5]); // shl rcx,5: 32-byte entries - code.extend([0x49, 0xb9]); // movabs r9,memo - code.extend(memo.to_le_bytes()); - code.extend([0x4c, 0x01, 0xc9]); // add rcx,r9 + asm.mov_imm64(R8, tags + u64::from(key_index(form.key)) * 8); + asm.mov_load(Qword, R8, Mem::base(R8, 0)); + asm.test(Qword, R8, R8); + // The key is not open. + exits.push(asm.jcc(Cond::E)); + // The result is the pointer in RAX. + asm.alu_imm8(Alu::Cmp, Qword, R8, DISABLED as i8); + let identity = asm.jcc(Cond::E); + asm.mov(Qword, Rcx, Rdx); + asm.shift_imm(ShiftOp::Rol, Qword, Rcx, 29); + asm.alu(Alu::Xor, Qword, Rcx, Rax); + asm.mov_imm64(R9, MIX); + asm.imul(Qword, Rcx, R9); + asm.shift_imm(ShiftOp::Shr, Qword, Rcx, SLOT_SHIFT); + // 32-byte entries. + asm.shift_imm(ShiftOp::Shl, Qword, Rcx, 5); + asm.mov_imm64(R9, memo); + asm.alu(Alu::Add, Qword, Rcx, R9); let mut misses = Vec::new(); - code.extend([0x48, 0x3b, 0x01]); // cmp rax,[rcx] - jump(&mut code, &mut misses, JNZ); - code.extend([0x48, 0x3b, 0x51, MODIFIER]); // cmp rdx,[rcx+modifier] - jump(&mut code, &mut misses, JNZ); - code.extend([0x49, 0x83, 0xc8, form.kind as u8]); // or r8,kind - code.extend([0x4c, 0x3b, 0x41, TAG]); // cmp r8,[rcx+tag] - jump(&mut code, &mut misses, JNZ); - code.extend([0x48, 0x8b, 0x41, VALUE]); // mov rax,[rcx+value] - land(&mut code, &identities); - let complete = code.len(); + asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rcx, 0)); + misses.push(asm.jcc(Cond::Ne)); + asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rcx, MODIFIER)); + misses.push(asm.jcc(Cond::Ne)); + asm.alu_imm8(Alu::Or, Qword, R8, form.kind as i8); + asm.alu_load(Alu::Cmp, Qword, R8, Mem::base(Rcx, TAG)); + misses.push(asm.jcc(Cond::Ne)); + asm.mov_load(Qword, Rax, Mem::base(Rcx, VALUE)); + asm.bind(identity); + let complete = asm.len(); let next_pc = GuestAddress(pc.0.wrapping_add(4)); let mut next = None; let mut dynamic = None; match form.completion { Finish::Register => { - code.extend([0x48, 0x89, 0x87]); // mov [rdi+pointer],rax - code.extend(pointer.to_le_bytes()); - next = Some(code.len()); - code.extend(super::chain::direct_exit(next_pc, ExitKind::Fallthrough)); + asm.mov_store(Qword, pointer, Rax); + next = Some(asm.len()); + super::block::direct_exit_with(&mut asm, next_pc, ExitKind::Fallthrough); } Finish::Return => { - dynamic = Some(code.len()); - exit_kind(&mut code, ExitKind::Return); + dynamic = Some(asm.len()); + super::block::exit_kind_with(&mut asm, ExitKind::Return); } Finish::Branch { link } => { if link { - code.extend([0x48, 0xb9]); // movabs rcx,next_pc - code.extend(next_pc.0.to_le_bytes()); - code.extend([0x48, 0x89, 0x8f]); // mov [rdi+x30],rcx - code.extend((30u32 * 8).to_le_bytes()); + asm.mov_imm64(Rcx, next_pc.0); + asm.mov_store(Qword, frame(30 * 8), Rcx); } - dynamic = Some(code.len()); - exit_kind( - &mut code, - if link { - ExitKind::Call - } else { - ExitKind::Indirect - }, - ); + dynamic = Some(asm.len()); + let kind = if link { + ExitKind::Call + } else { + ExitKind::Indirect + }; + super::block::exit_kind_with(&mut asm, kind); } } - land(&mut code, &misses); + for miss in misses { + asm.bind(miss); + } // service(state, request, pointer, modifier) on a 16-byte aligned stack. - code.extend([0x49, 0x89, 0xe3]); // mov r11,rsp - code.extend([0x48, 0x83, 0xe4, 0xf0]); // and rsp,-16 - code.extend([0x41, 0x53, 0x57]); // push r11; push rdi - code.extend([0x48, 0x89, 0xd1]); // mov rcx,rdx - code.extend([0x48, 0x89, 0xc2]); // mov rdx,rax - code.push(0xbe); // mov esi,request - code.extend(form.request().to_le_bytes()); - code.extend([0x48, 0xbf]); // movabs rdi,state - code.extend(service.state.to_le_bytes()); - code.extend([0x48, 0xb8]); // movabs rax,routine - code.extend(service.routine.to_le_bytes()); - code.extend([0xff, 0xd0]); // call rax - code.extend([0x5f, 0x5c]); // pop rdi; pop rsp - code.extend([0x48, 0x85, 0xc0]); // test rax,rax - jump(&mut code, &mut exits, JZ); // jz: not completed - code.extend([0x48, 0x89, 0xd0]); // mov rax,rdx - code.push(0xe9); // jmp complete - let back = complete as i64 - (code.len() + 4) as i64; - code.extend((back as i32).to_le_bytes()); - land(&mut code, &exits); - code.extend(super::chain::direct_exit( - pc, - ExitKind::PointerAuthentication, - )); + asm.mov(Qword, R11, Rsp); + asm.alu_imm8(Alu::And, Qword, Rsp, -16); + asm.push(R11); + asm.push(Rdi); + asm.mov(Qword, Rcx, Rdx); + asm.mov(Qword, Rdx, Rax); + asm.mov_imm32(Rsi, form.request()); + asm.mov_imm64(Rdi, service.state); + asm.mov_imm64(Rax, service.routine); + asm.call_rm(Rax); + asm.pop(Rdi); + asm.pop(Rsp); + asm.test(Qword, Rax, Rax); + // Not completed. + exits.push(asm.jcc(Cond::E)); + asm.mov(Qword, Rax, Rdx); + let back = asm.jmp(); + for exit in exits { + asm.bind(exit); + } + super::block::direct_exit_with(&mut asm, pc, ExitKind::PointerAuthentication); + resolve(&mut code, back, complete); Thunk { - code, + code: code.into_bytes(), next, dynamic, } } -/// The second opcode bytes of `jz` and `jnz` with a 32-bit displacement. -const JZ: u8 = 0x84; -const JNZ: u8 = 0x85; - const STACK_POINTER: u32 = core::mem::offset_of!(crate::GuestState, sp) as u32; -/// A `jcc` (`opcode` after 0x0f) whose displacement [`land`] fixes up. -fn jump(code: &mut Vec, fixups: &mut Vec, opcode: u8) { - code.extend([0x0f, opcode]); - fixups.push(code.len()); - code.extend([0; 4]); -} - -/// Point the jumps at `fixups` here. -fn land(code: &mut [u8], fixups: &[usize]) { - let here = code.len(); - for &fixup in fixups { - let relative = (here - fixup - 4) as i32; - code[fixup..fixup + 4].copy_from_slice(&relative.to_le_bytes()); - } -} - -fn exit_kind(code: &mut Vec, kind: ExitKind) { - code.push(0xba); // mov edx,kind - code.extend((kind as u32).to_le_bytes()); - code.push(0xc3); // ret +/// `[rdi+offset]` with a 32-bit displacement: a field of the guest frame. +fn frame(offset: u32) -> Mem { + Mem::base_disp32(Gpr::Rdi, offset as i32) } #[cfg(test)] @@ -655,6 +627,9 @@ mod tests { /// `mov [rdi+disp32],rax`. const REGISTER_WRITE_BYTES: usize = 7; + /// The second opcode bytes of `jz` and `jnz` with a 32-bit displacement. + const JZ: u8 = 0x84; + const JNZ: u8 = 0x85; #[test] fn register_completions_chain_onward_and_misses_exit_unchanged() { diff --git a/crates/stela-compiler/src/x86_64/pointer/strip.rs b/crates/stela-compiler/src/x86_64/pointer/strip.rs index 681c871398..3e9cf60f61 100644 --- a/crates/stela-compiler/src/x86_64/pointer/strip.rs +++ b/crates/stela-compiler/src/x86_64/pointer/strip.rs @@ -4,9 +4,9 @@ //! The runtime derives both keep masks through its authoritative PAC layout //! and closes this cell whenever derived state changes. A closed cell takes //! the original instruction exit, without changing architectural state. -use super::{JZ, Thunk, jump, land}; +use super::{Thunk, frame}; +use crate::x86_64::asm::{Alu, BitTest, Code, Cond, Gpr, Mem, Size}; use crate::{GuestAddress, block::ExitKind}; -use alloc::vec::Vec; /// Fixed-address state read by a strip thunk. Each keep mask excludes the /// extension field that is restored from bit 55; tagged bytes remain set. @@ -20,50 +20,49 @@ pub struct Cell { pub upper_extension: u64, } -const LOWER: u8 = core::mem::offset_of!(Cell, keep) as u8; -const UPPER: u8 = LOWER + 8; -const UPPER_EXTENSION: u8 = core::mem::offset_of!(Cell, upper_extension) as u8; +const LOWER: i32 = core::mem::offset_of!(Cell, keep) as i32; +const UPPER: i32 = LOWER + 8; +const UPPER_EXTENSION: i32 = core::mem::offset_of!(Cell, upper_extension) as i32; const REGION_BIT: u8 = 55; /// Complete XPAC on `register`, with no key access, from `cell` while open. /// Only RAX, RCX, RDX, R8 and host flags are clobbered, as at a block exit; /// guest NZCV, SP and every other register remain in their canonical frame. pub fn thunk(pc: GuestAddress, register: u8, cell: u64) -> Option { + use Gpr::{R8, Rax, Rcx, Rdx}; + use Size::Qword; if register > 31 { return None; } - let mut code = Vec::with_capacity(96); - let mut closed = Vec::new(); + let mut code = Code::new(); + let mut asm = code.asm(); + let mut closed = None; // XZR has no effect and depends on no regime state. if register != 31 { - code.extend([0x48, 0xba]); // movabs rdx,cell - code.extend(cell.to_le_bytes()); - code.extend([0x48, 0x83, 0x3a, 0]); // cmp qword [rdx],0 - jump(&mut code, &mut closed, JZ); - code.extend([0x48, 0x8b, 0x87]); // mov rax,[rdi+register] - code.extend((u32::from(register) * 8).to_le_bytes()); - code.extend([0x48, 0x8b, 0x4a, LOWER]); // mov rcx,[rdx+lower] - code.extend([0x48, 0x0f, 0xba, 0xe0, REGION_BIT]); // bt rax,55 - code.extend([0x48, 0x0f, 0x42, 0x4a, UPPER]); // cmovc rcx,[rdx+upper] - code.extend([0x4d, 0x19, 0xc0]); // sbb r8,r8: bit 55 replicated - code.extend([0x4c, 0x23, 0x42, UPPER_EXTENSION]); // and r8,[rdx+extension] - code.extend([0x48, 0x21, 0xc8]); // and rax,rcx - code.extend([0x4c, 0x09, 0xc0]); // or rax,r8 - code.extend([0x48, 0x89, 0x87]); // mov [rdi+register],rax - code.extend((u32::from(register) * 8).to_le_bytes()); + let pointer = frame(u32::from(register) * 8); + asm.mov_imm64(Rdx, cell); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rdx, 0), 0); + closed = Some(asm.jcc(Cond::E)); + asm.mov_load(Qword, Rax, pointer); + asm.mov_load(Qword, Rcx, Mem::base(Rdx, LOWER)); + asm.bit_imm(BitTest::Bt, Qword, Rax, REGION_BIT); + asm.cmov(Cond::B, Qword, Rcx, Mem::base(Rdx, UPPER)); + // Bit 55 replicated. + asm.alu(Alu::Sbb, Qword, R8, R8); + asm.alu_load(Alu::And, Qword, R8, Mem::base(Rdx, UPPER_EXTENSION)); + asm.alu(Alu::And, Qword, Rax, Rcx); + asm.alu(Alu::Or, Qword, Rax, R8); + asm.mov_store(Qword, pointer, Rax); } - let next = code.len(); - code.extend(super::super::chain::direct_exit( - GuestAddress(pc.0.wrapping_add(4)), - ExitKind::Fallthrough, - )); - land(&mut code, &closed); - code.extend(super::super::chain::direct_exit( - pc, - ExitKind::PointerAuthentication, - )); + let next = asm.len(); + let fallthrough = GuestAddress(pc.0.wrapping_add(4)); + super::super::block::direct_exit_with(&mut asm, fallthrough, ExitKind::Fallthrough); + if let Some(closed) = closed { + asm.bind(closed); + } + super::super::block::direct_exit_with(&mut asm, pc, ExitKind::PointerAuthentication); Some(Thunk { - code, + code: code.into_bytes(), next: Some(next), dynamic: None, }) diff --git a/crates/stela-compiler/src/x86_64/pointer_checks.rs b/crates/stela-compiler/src/x86_64/pointer_checks.rs index 3fddb9506e..cf2b8609b0 100644 --- a/crates/stela-compiler/src/x86_64/pointer_checks.rs +++ b/crates/stela-compiler/src/x86_64/pointer_checks.rs @@ -1,77 +1,47 @@ //! Result marking shared by the checked pointer arithmetic forms. +use crate::x86_64::asm::{Alu, BitTest, Code, Cond, Gpr, ShiftOp, Size}; -use alloc::vec::Vec; const TOP_BYTE_SHIFT: u8 = 56; const POINTER_SIGN_BIT: u8 = 55; const DETECTION_BIT: u8 = 54; const LOW_RESULT_MASK: u64 = (1 << DETECTION_BIT) - 1; const ONE_BIT_SHIFT: u8 = 1; -const ONE_BIT_MASK: u8 = 1; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const MOV_RCX_RDX: &[u8] = &[0x48, 0x89, 0xd1]; -const MOV_R9_RAX: &[u8] = &[0x49, 0x89, 0xc1]; -const MOV_R10_RCX: &[u8] = &[0x49, 0x89, 0xca]; -const MOVABS_R10: &[u8] = &[0x49, 0xba]; -const XOR_R9_RDX: &[u8] = &[0x49, 0x31, 0xd1]; -const XOR_RCX_R10: &[u8] = &[0x4c, 0x31, 0xd1]; -const SHR_R9_IMM8: &[u8] = &[0x49, 0xc1, 0xe9]; -const SHR_RCX_IMM8: &[u8] = &[0x48, 0xc1, 0xe9]; -const SHR_R10_IMM8: &[u8] = &[0x49, 0xc1, 0xea]; -const SHL_R11_IMM8: &[u8] = &[0x49, 0xc1, 0xe3]; -const AND_ECX_IMM8: &[u8] = &[0x83, 0xe1]; -const AND_RCX_R10: &[u8] = &[0x4c, 0x21, 0xd1]; -const AND_R10_RDX: &[u8] = &[0x49, 0x21, 0xd2]; -const NOT_R10: &[u8] = &[0x49, 0xf7, 0xd2]; -const BTR_R10_IMM8: &[u8] = &[0x49, 0x0f, 0xba, 0xf2]; -const BT_RDX_IMM8: &[u8] = &[0x48, 0x0f, 0xba, 0xe2]; -const SETNC_R11B: &[u8] = &[0x41, 0x0f, 0x93, 0xc3]; -const MOVZX_R11D_R11B: &[u8] = &[0x45, 0x0f, 0xb6, 0xdb]; -const OR_R9_RCX: &[u8] = &[0x49, 0x09, 0xc9]; -const OR_R9_R8: &[u8] = &[0x4d, 0x09, 0xc1]; -const OR_RCX_R10: &[u8] = &[0x4c, 0x09, 0xd1]; -const OR_RCX_R11: &[u8] = &[0x4c, 0x09, 0xd9]; -const TEST_R9_R9: &[u8] = &[0x4d, 0x85, 0xc9]; -const CMOVNZ_RAX_RCX: &[u8] = &[0x48, 0x0f, 0x45, 0xc1]; +const ONE_BIT_MASK: i8 = 1; /// RAX is the result and RDX the base; R8 holds the normalized multiplication /// predicate when requested. RCX/R9/R10/R11 are scratch. No branch depends on /// guest data. -pub(super) fn emit(code: &mut Vec, multiplication: bool) { - code.extend(MOV_R9_RAX); - code.extend(XOR_R9_RDX); - code.extend(SHR_R9_IMM8); - code.push(TOP_BYTE_SHIFT); - code.extend(MOV_RCX_RDX); - code.extend(SHR_RCX_IMM8); - code.push(DETECTION_BIT); - code.extend(MOV_R10_RCX); - code.extend(SHR_R10_IMM8); - code.push(ONE_BIT_SHIFT); - code.extend(XOR_RCX_R10); - code.extend(AND_ECX_IMM8); - code.push(ONE_BIT_MASK); - code.extend(OR_R9_RCX); +pub(super) fn emit(code: &mut Code, multiplication: bool) { + use Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdx}; + use Size::{Dword, Qword}; + let mut asm = code.asm(); + asm.mov(Qword, R9, Rax); + asm.alu(Alu::Xor, Qword, R9, Rdx); + asm.shift_imm(ShiftOp::Shr, Qword, R9, TOP_BYTE_SHIFT); + asm.mov(Qword, Rcx, Rdx); + asm.shift_imm(ShiftOp::Shr, Qword, Rcx, DETECTION_BIT); + asm.mov(Qword, R10, Rcx); + asm.shift_imm(ShiftOp::Shr, Qword, R10, ONE_BIT_SHIFT); + asm.alu(Alu::Xor, Qword, Rcx, R10); + asm.alu_imm8(Alu::And, Dword, Rcx, ONE_BIT_MASK); + asm.alu(Alu::Or, Qword, R9, Rcx); if multiplication { - code.extend(OR_R9_R8); + asm.alu(Alu::Or, Qword, R9, R8); } // Preserve result[53:0] and base[63:55], then set bit54 to NOT base[55]. - code.extend(MOV_RCX_RAX); - code.extend(MOVABS_R10); - code.extend(LOW_RESULT_MASK.to_le_bytes()); - code.extend(AND_RCX_R10); - code.extend(NOT_R10); - code.extend(AND_R10_RDX); - code.extend(BTR_R10_IMM8); - code.push(DETECTION_BIT); - code.extend(BT_RDX_IMM8); - code.push(POINTER_SIGN_BIT); - code.extend(SETNC_R11B); - code.extend(MOVZX_R11D_R11B); - code.extend(SHL_R11_IMM8); - code.push(DETECTION_BIT); - code.extend(OR_RCX_R10); - code.extend(OR_RCX_R11); - code.extend(TEST_R9_R9); - code.extend(CMOVNZ_RAX_RCX); + asm.mov(Qword, Rcx, Rax); + asm.mov_imm64(R10, LOW_RESULT_MASK); + asm.alu(Alu::And, Qword, Rcx, R10); + asm.unary(crate::x86_64::asm::Unary::Not, Qword, R10); + asm.alu(Alu::And, Qword, R10, Rdx); + asm.bit_imm(BitTest::Btr, Qword, R10, DETECTION_BIT); + asm.bit_imm(BitTest::Bt, Qword, Rdx, POINTER_SIGN_BIT); + asm.setcc(Cond::Ae, R11); + asm.movzx(Dword, R11, Size::Byte, R11); + asm.shift_imm(ShiftOp::Shl, Qword, R11, DETECTION_BIT); + asm.alu(Alu::Or, Qword, Rcx, R10); + asm.alu(Alu::Or, Qword, Rcx, R11); + asm.test(Qword, R9, R9); + asm.cmov(Cond::Ne, Qword, Rax, Rcx); } diff --git a/crates/stela-compiler/src/x86_64/prefetch.rs b/crates/stela-compiler/src/x86_64/prefetch.rs index 89140e46a6..3ffdf644c9 100644 --- a/crates/stela-compiler/src/x86_64/prefetch.rs +++ b/crates/stela-compiler/src/x86_64/prefetch.rs @@ -1,37 +1,12 @@ //! PRFM as SSE PREFETCH hints. -use super::{NOP, load, offset}; +use super::{load, offset}; use crate::aarch64::{ prefetch::{Address, Hint, Operand}, register_offset::IndexExtend, }; -use alloc::vec::Vec; +use crate::x86_64::asm::{Code, Gpr, Mem, Size, memory::Prefetch}; -const MOVABS_RAX: &[u8] = &[0x48, 0xb8]; -const MOV_ECX_STATE: &[u8] = &[0x8b, 0x8f]; -const MOVSXD_RCX_STATE: &[u8] = &[0x48, 0x63, 0x8f]; -const MOV_RCX_STATE: &[u8] = &[0x48, 0x8b, 0x8f]; -const PREFETCH: &[u8] = &[0x0f, 0x18]; -const MOD_DISP8: u8 = 0x40; -const MOD_DISP32: u8 = 0x80; -const SIB_ADDRESS: u8 = 4; -const SIB_RAX_RCX: u8 = 1 << 3; -const SIB_SCALE_SHIFT: u8 = 6; - -#[derive(Clone, Copy)] -enum Locality { - NonTemporal = 0, - Level1 = 1, - Level2 = 2, - Level3 = 3, -} - -impl Locality { - const fn modrm(self) -> u8 { - (self as u8) << 3 - } -} - -fn locality(hint: Hint) -> Option { +fn locality(hint: Hint) -> Option { const STORE_HINT: u8 = 0b10000; const TYPE_MASK: u8 = 0b11000; const TARGET_MASK: u8 = 0b00110; @@ -45,21 +20,21 @@ fn locality(hint: Hint) -> Option { return None; } Some(if raw & STREAMING != 0 { - Locality::NonTemporal + Prefetch::Nta } else { match (raw & TARGET_MASK) >> 1 { - 0 => Locality::Level1, - 1 => Locality::Level2, - 2 => Locality::Level3, + 0 => Prefetch::T0, + 1 => Prefetch::T1, + 2 => Prefetch::T2, _ => unreachable!("system cache hints use the explicit NOP policy"), } }) } -pub(super) fn emit(code: &mut Vec, operand: &Operand) { +pub(super) fn emit(code: &mut Code, operand: &Operand) { let Some(locality) = locality(operand.hint) else { // One byte preserves strict source-map intervals for the no-action hint. - code.push(NOP); + code.asm().nop(); return; }; match operand.address { @@ -77,54 +52,47 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { if let Some(displacement) = offset(index) { // Read precisely the bits used by ExtendReg. W forms avoid an // unnecessary 64-bit load followed by a separate conversion. - code.extend(match extend { - IndexExtend::Uxtw => MOV_ECX_STATE, - IndexExtend::Sxtw => MOVSXD_RCX_STATE, - IndexExtend::Lsl | IndexExtend::Sxtx => MOV_RCX_STATE, - }); - code.extend(displacement.to_le_bytes()); - code.extend(PREFETCH); - code.push(locality.modrm() | SIB_ADDRESS); + let state = Mem::base_disp32(Gpr::Rdi, displacement as i32); + let mut asm = code.asm(); + match extend { + IndexExtend::Uxtw => asm.mov_load(Size::Dword, Gpr::Rcx, state), + IndexExtend::Sxtw => asm.movsxd(Gpr::Rcx, state), + IndexExtend::Lsl | IndexExtend::Sxtx => { + asm.mov_load(Size::Qword, Gpr::Rcx, state); + } + } // Decoder restricts shift to 0 or 3. SIB performs the shift and // modulo-64 addition without an extra SHL/LEA instruction. - code.push((shift << SIB_SCALE_SHIFT) | SIB_RAX_RCX); + asm.prefetch(locality, Mem::indexed(Gpr::Rax, Gpr::Rcx, 1 << shift, 0)); } else { immediate(code, locality, 0); // XZR index contributes zero. } } Address::Literal(address) => { - code.extend(MOVABS_RAX); - code.extend(address.to_le_bytes()); + code.asm().mov_imm64(Gpr::Rax, address); immediate(code, locality, 0); } } } -fn immediate(code: &mut Vec, locality: Locality, displacement: i32) { - code.extend(PREFETCH); - if displacement == 0 { - code.push(locality.modrm()); // [rax] - } else if let Ok(short) = i8::try_from(displacement) { - code.push(locality.modrm() | MOD_DISP8); - code.extend(short.to_le_bytes()); - } else { - code.push(locality.modrm() | MOD_DISP32); - code.extend(displacement.to_le_bytes()); - } +/// Prefetch [RAX + displacement], in its shortest form. +fn immediate(code: &mut Code, locality: Prefetch, displacement: i32) { + code.asm() + .prefetch(locality, Mem::base(Gpr::Rax, displacement)); } #[cfg(test)] mod tests { use super::*; use crate::{GuestAddress, aarch64::prefetch}; - use alloc::vec; + use alloc::vec::Vec; fn emitted(word: u32) -> Vec { let operand = prefetch::decode(GuestAddress(0), word).unwrap().unwrap(); - let mut code = vec![]; + let mut code = Code::new(); emit(&mut code, &operand); - code + code.into_bytes() } #[test] @@ -139,7 +107,7 @@ mod tests { }; assert_eq!(&code[7..], &[0x0f, 0x18, modrm as u8]); } else { - assert_eq!(code, [NOP]); + assert_eq!(code, [0x90]); } } } diff --git a/crates/stela-compiler/src/x86_64/region.rs b/crates/stela-compiler/src/x86_64/region.rs index 688c76aa8a..4dd468df83 100644 --- a/crates/stela-compiler/src/x86_64/region.rs +++ b/crates/stela-compiler/src/x86_64/region.rs @@ -1,5 +1,6 @@ //! Multi-instruction scalar regions that keep guest values in host registers and //! settle the full register bank at every exit. +use crate::x86_64::asm::Code; use alloc::vec; use alloc::vec::Vec; mod allocation; @@ -68,7 +69,7 @@ pub struct AllocationStats { #[derive(Debug, Clone, PartialEq, Eq)] pub struct OptimizedRegion { - pub code: Vec, + pub code: Code, pub consumed_instructions: usize, pub source_map: Vec<(GuestAddress, usize)>, pub stats: AllocationStats, @@ -110,7 +111,7 @@ struct Emitter<'a> { } impl Emitter<'_> { - fn emit(&mut self, encode: impl FnOnce(&mut Vec)) { + fn emit(&mut self, encode: impl FnOnce(&mut Code)) { let start = self.output.code.len(); encode(&mut self.output.code); let end = self.output.code.len(); @@ -317,7 +318,7 @@ impl Emitter<'_> { && bytes != BYTE_LOAD_BYTES && !(self.checks.stack_alignment && super::memory_store::aligned_immediate(base, displacement, mode, bytes)); - let mut raw = vec![]; + let mut raw = Code::new(); let selected = if let &[first, second] = data { super::memory_pair( &mut raw, @@ -390,7 +391,7 @@ impl Emitter<'_> { { self.emit(|code| encoding::copy(code, STAGING[index], host, Width::X64)); } else { - self.emit(|code| code.extend_from_slice(&raw[start..end])); + self.emit(|code| code.asm().fixed(&raw[start..end])); } } self.finish_access(access_start, live, &[]); @@ -424,7 +425,7 @@ impl Emitter<'_> { ) -> Result<(), RegionError> { // Obtain the real existing raw-memory emission before mutating output. // If its selected form changes, decline this whole candidate prefix. - let mut raw = vec![]; + let mut raw = Code::new(); super::memory( &mut raw, self.memory_checks(), @@ -512,10 +513,11 @@ impl Emitter<'_> { index } - /// Each shared instruction `raw[ends[k - 1]..ends[k]]`. + /// Each shared instruction `raw[ends[k - 1]..ends[k]]`, one + /// instruction of the shared recipe each. fn emit_segments(&mut self, raw: &[u8], ends: &[usize]) { for pair in ends.windows(2) { - self.emit(|code| code.extend_from_slice(&raw[pair[0]..pair[1]])); + self.emit(|code| code.asm().fixed(&raw[pair[0]..pair[1]])); } } @@ -650,7 +652,7 @@ impl Emitter<'_> { displacement: i32, mode: AddressMode, ) -> Result<(), RegionError> { - let mut raw = vec![]; + let mut raw = Code::new(); super::memory_pair( &mut raw, self.memory_checks(), @@ -1202,7 +1204,7 @@ fn emit_prefix_selected<'a>( } let mut emitter = Emitter { output: OptimizedRegion { - code: vec![], + code: Code::from(vec![]), consumed_instructions: consumed, source_map: vec![], stats: AllocationStats::default(), @@ -1738,7 +1740,7 @@ mod tests { ); assert_eq!(checked.code.len(), unchecked.code.len() + 3 * check.len()); // The cost gate counts each check's six instructions on both sides. - let mut baseline = vec![]; + let mut baseline = Code::new(); for instruction in &instructions { super::super::emit_instruction( &mut baseline, @@ -1857,7 +1859,7 @@ mod tests { #[test] fn shared_byte_load_recipe_rejects_any_clobber_or_offset_change() { - let mut raw = vec![]; + let mut raw = Code::new(); super::super::memory( &mut raw, super::super::MemoryChecks::DEFAULT, @@ -1920,7 +1922,7 @@ mod tests { ]; for (width, bytes) in sizes { for data in [Register::X(16), Register::Zero] { - let mut raw = vec![]; + let mut raw = Code::new(); super::super::memory( &mut raw, super::super::MemoryChecks::DEFAULT, @@ -1994,7 +1996,7 @@ mod tests { .windows(3) .any(|bytes| bytes == [0x48, 0x8b, 0x08]) ); - let mut baseline = vec![]; + let mut baseline = Code::new(); for instruction in &instructions { super::super::emit_instruction( &mut baseline, @@ -2056,7 +2058,7 @@ mod tests { let region = emit_clean_load_prefix(&source, true, None).unwrap(); assert_eq!(region.consumed_instructions, source.len()); assert_eq!(region.stats.pair_loads, 1); - let mut raw = vec![]; + let mut raw = Code::new(); super::super::memory_pair( &mut raw, super::super::MemoryChecks::DEFAULT, @@ -2085,7 +2087,7 @@ mod tests { (Register::Sp, true), (Register::Sp, false), ] { - let mut raw = vec![]; + let mut raw = Code::new(); super::super::memory_pair( &mut raw, super::super::MemoryChecks::system(stack_alignment, false, true, false), @@ -2176,7 +2178,7 @@ mod tests { .filter(|bytes| *bytes == check) .count(); assert_eq!(checks, if stack_alignment { 2 } else { 0 }); - let mut baseline = vec![]; + let mut baseline = Code::new(); for instruction in &instructions { super::super::emit_instruction( &mut baseline, @@ -2570,7 +2572,7 @@ mod tests { assert!(contains(&[0x4c, 0x89, 0x40, 0x08])); assert!(contains(&[0x88, 0x08])); assert!(contains(&[0x66, 0x89, 0x08])); - let mut baseline = vec![]; + let mut baseline = Code::new(); for instruction in &instructions { super::super::emit_instruction( &mut baseline, @@ -2658,7 +2660,7 @@ mod tests { (DOUBLEWORD_LOAD_BYTES, Register::Sp), ] { for data in [Register::X(16), Register::Zero] { - let mut raw = vec![]; + let mut raw = Code::new(); super::super::memory( &mut raw, super::super::MemoryChecks::DEFAULT, @@ -2718,7 +2720,7 @@ mod tests { [Register::Zero, Register::X(16)], [Register::X(16), Register::Zero], ] { - let mut raw = vec![]; + let mut raw = Code::new(); super::super::memory_pair( &mut raw, super::super::MemoryChecks::DEFAULT, @@ -2933,7 +2935,7 @@ mod tests { ); let ordinary = super::super::block::emit_ordinary_for_target(&instructions, None, fallthrough, target); - let mut baseline_prefix = vec![]; + let mut baseline_prefix = Code::new(); let mut fixups = vec![]; for instruction in &instructions { super::super::emit_instruction( @@ -2955,7 +2957,7 @@ mod tests { assert_eq!(ordinary.x86_64_code, baseline.x86_64_code); assert_eq!(ordinary.source_map, baseline.source_map); } - let mut capture = Vec::new(); + let mut capture = Code::new(); crate::x86_64::capture_nzcv(&mut capture, true); assert_eq!(analysis::selected_output_instruction_count(&capture), None); assert_eq!( diff --git a/crates/stela-compiler/src/x86_64/region/allocation.rs b/crates/stela-compiler/src/x86_64/region/allocation.rs index 3efe7d8a6c..8723411607 100644 --- a/crates/stela-compiler/src/x86_64/region/allocation.rs +++ b/crates/stela-compiler/src/x86_64/region/allocation.rs @@ -2,6 +2,7 @@ //! overwritten before the next exit. use super::{Emitter, Resident, analysis::Effects, encoding, flags, location::GPR_SLOTS}; use crate::aarch64::{Register, Width}; +use crate::x86_64::asm::Code; use alloc::vec; use alloc::vec::Vec; use encoding::{CALLEE_POOL, HostGpr, POOL, RESULT}; @@ -407,7 +408,7 @@ pub(super) fn emitter<'a>( ) -> Emitter<'a> { Emitter { output: super::OptimizedRegion { - code: vec![], + code: Code::new(), consumed_instructions: gprs.len(), source_map: vec![], stats: super::AllocationStats::default(), diff --git a/crates/stela-compiler/src/x86_64/region/encoding.rs b/crates/stela-compiler/src/x86_64/region/encoding.rs index c12453171a..86b4ed0a4e 100644 --- a/crates/stela-compiler/src/x86_64/region/encoding.rs +++ b/crates/stela-compiler/src/x86_64/region/encoding.rs @@ -1,6 +1,7 @@ //! Integer encodings, including flag-preserving variants. use super::{BYTE_LOAD_BYTES, DOUBLEWORD_LOAD_BYTES, HALFWORD_LOAD_BYTES, WORD_LOAD_BYTES}; use crate::aarch64::{AddressMode, Logical, Shift, Width}; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, ShiftOp, Size, Unary, resolve}; use alloc::vec; use alloc::vec::Vec; @@ -28,6 +29,23 @@ impl HostGpr { pub const fn mask(self) -> u16 { 1u16 << self as u8 } + /// The encoder's register. + const fn gpr(self) -> Gpr { + crate::x86_64::simd::encode::gpr(self as u8) + } +} + +fn size(width: Width) -> Size { + Size::of(width == Width::X64) +} + +/// `[base + displacement]` with an 8-bit displacement field when it fits, +/// else a 32-bit one. +fn displaced(base: HostGpr, displacement: i32) -> Mem { + match i8::try_from(displacement) { + Ok(short) => Mem::base_disp8(base.gpr(), short), + Err(_) => Mem::base_disp32(base.gpr(), displacement), + } } pub const RESULT: HostGpr = HostGpr::Rax; @@ -59,176 +77,126 @@ pub fn pool_host(index: usize) -> HostGpr { CALLEE_POOL[index - POOL.len()] } } -const REX: u8 = 0x40; -const REX_W: u8 = 8; -const REX_R: u8 = 4; -const REX_B: u8 = 1; -const REGISTER_MODE: u8 = 0xc0; -const DISP32_MODE: u8 = 0x80; -const DISP8_MODE: u8 = 0x40; -const MOV_LOAD: u8 = 0x8b; -const MOV_STORE: u8 = 0x89; -const MOV_IMMEDIATE: u8 = 0xb8; -const IMMEDIATE_GROUP: u8 = 0x81; -const SHIFT_IMMEDIATE_GROUP: u8 = 0xc1; -const UNARY_GROUP: u8 = 0xf7; -const NOP: u8 = 0x90; -const TWO_BYTE_OPCODE: u8 = 0x0f; -const IMUL: u8 = 0xaf; - #[derive(Debug, Clone, Copy)] -#[repr(u8)] pub enum ImmediateExtension { - Add = 0, - And = 4, - Subtract = 5, - Compare = 7, + Add, + And, + Subtract, + Compare, } -pub fn nop(code: &mut Vec) { - code.push(NOP); -} - -fn rex(code: &mut Vec, width: Width, reg: HostGpr, rm: HostGpr) { - let value = REX - | if width == Width::X64 { REX_W } else { 0 } - | if reg as u8 >= 8 { REX_R } else { 0 } - | if rm as u8 >= 8 { REX_B } else { 0 }; - if value != REX { - code.push(value); +impl ImmediateExtension { + const fn alu(self) -> Alu { + match self { + Self::Add => Alu::Add, + Self::And => Alu::And, + Self::Subtract => Alu::Sub, + Self::Compare => Alu::Cmp, + } } } -pub fn copy(code: &mut Vec, destination: HostGpr, source: HostGpr, width: Width) { - rex(code, width, source, destination); - code.extend([ - MOV_STORE, - REGISTER_MODE | ((source as u8 & 7) << 3) | (destination as u8 & 7), - ]); +pub fn nop(code: &mut Code) { + code.asm().nop(); +} + +pub fn copy(code: &mut Code, destination: HostGpr, source: HostGpr, width: Width) { + code.asm().mov(size(width), destination.gpr(), source.gpr()); } /// `lea destination, [base + displacement]`, 64-bit, with the shortest -/// displacement. -pub fn lea(code: &mut Vec, destination: HostGpr, base: HostGpr, displacement: i32) { - const SIB_BASE: u8 = 4; - debug_assert!(base as u8 & 7 != SIB_BASE, "an RSP or R12 base needs a SIB"); - rex(code, Width::X64, destination, base); - let registers = ((destination as u8 & 7) << 3) | (base as u8 & 7); - if let Ok(short) = i8::try_from(displacement) { - code.extend([LEA, DISP8_MODE | registers, short as u8]); - } else { - code.extend([LEA, DISP32_MODE | registers]); - code.extend(displacement.to_le_bytes()); - } +/// displacement field, 8 bits for zero. +pub fn lea(code: &mut Code, destination: HostGpr, base: HostGpr, displacement: i32) { + code.asm().lea( + Size::Qword, + destination.gpr(), + displaced(base, displacement), + ); } -/// `test register8, immediate`: the low byte of any GPR. -pub fn test_low_byte(code: &mut Vec, register: HostGpr, immediate: u8) { - const TEST_BYTE_IMMEDIATE: u8 = 0xf6; - const FIRST_REX_BYTE_REGISTER: u8 = 4; - let number = register as u8; - if number >= 8 { - code.push(REX | REX_B); - } else if number >= FIRST_REX_BYTE_REGISTER { - // SPL, BPL, SIL and DIL rather than AH, CH, DH and BH. - code.push(REX); - } - code.extend([TEST_BYTE_IMMEDIATE, REGISTER_MODE | (number & 7), immediate]); +/// `test register8, immediate`: the low byte of any GPR (SPL, BPL, SIL and +/// DIL rather than AH, CH, DH and BH). +pub fn test_low_byte(code: &mut Code, register: HostGpr, immediate: u8) { + code.asm() + .test_imm(Size::Byte, register.gpr(), i32::from(immediate)); } -fn frame_access(code: &mut Vec, register: HostGpr, slot: usize, opcode: u8) { - rex(code, Width::X64, register, FRAME); - let offset = (slot * GPR_BYTES) as u32; - let mode = if offset <= 127 { - DISP8_MODE - } else { - DISP32_MODE - }; - code.extend([opcode, mode | ((register as u8 & 7) << 3) | FRAME as u8]); - if mode == DISP8_MODE { - code.push(offset as u8); - } else { - code.extend(offset.to_le_bytes()); - } +/// The frame slot of guest register `slot`. +fn frame_slot(slot: usize) -> Mem { + displaced(FRAME, (slot * GPR_BYTES) as i32) } -pub fn load(code: &mut Vec, destination: HostGpr, slot: usize) { - frame_access(code, destination, slot, MOV_LOAD); +pub fn load(code: &mut Code, destination: HostGpr, slot: usize) { + code.asm() + .mov_load(Size::Qword, destination.gpr(), frame_slot(slot)); } -pub fn store(code: &mut Vec, source: HostGpr, slot: usize) { - frame_access(code, source, slot, MOV_STORE); +pub fn store(code: &mut Code, source: HostGpr, slot: usize) { + code.asm() + .mov_store(Size::Qword, frame_slot(slot), source.gpr()); } -fn nzcv_access(code: &mut Vec, register: HostGpr, opcode: u8) { - const NZCV_OFFSET: u32 = core::mem::offset_of!(crate::GuestState, nzcv) as u32; - rex(code, Width::W32, register, FRAME); - code.extend([ - opcode, - DISP32_MODE | ((register as u8 & 7) << 3) | FRAME as u8, - ]); - code.extend(NZCV_OFFSET.to_le_bytes()); +/// The guest NZCV word. +fn nzcv() -> Mem { + const NZCV_OFFSET: i32 = core::mem::offset_of!(crate::GuestState, nzcv) as i32; + Mem::base_disp32(FRAME.gpr(), NZCV_OFFSET) } -pub fn load_nzcv(code: &mut Vec, destination: HostGpr) { - nzcv_access(code, destination, MOV_LOAD); +pub fn load_nzcv(code: &mut Code, destination: HostGpr) { + code.asm().mov_load(Size::Dword, destination.gpr(), nzcv()); } -pub fn store_nzcv(code: &mut Vec, source: HostGpr) { - nzcv_access(code, source, MOV_STORE); +pub fn store_nzcv(code: &mut Code, source: HostGpr) { + code.asm().mov_store(Size::Dword, nzcv(), source.gpr()); } -pub fn immediate(code: &mut Vec, destination: HostGpr, value: u64, width: Width) { - rex(code, width, HostGpr::Rax, destination); - code.push(MOV_IMMEDIATE | (destination as u8 & 7)); - if width == Width::X64 { - code.extend(value.to_le_bytes()); - } else { - code.extend((value as u32).to_le_bytes()); +pub fn immediate(code: &mut Code, destination: HostGpr, value: u64, width: Width) { + match width { + Width::X64 => code.asm().mov_imm64(destination.gpr(), value), + Width::W32 => code.asm().mov_imm32(destination.gpr(), value as u32), } } pub fn binary( - code: &mut Vec, + code: &mut Code, destination: HostGpr, source: HostGpr, opcode: Binary, width: Width, ) { - rex(code, width, source, destination); - code.extend([ - opcode as u8, - REGISTER_MODE | ((source as u8 & 7) << 3) | (destination as u8 & 7), - ]); + code.asm() + .alu(opcode.alu(), size(width), destination.gpr(), source.gpr()); } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[repr(u8)] pub enum Binary { - Add = 0x01, - Sub = 0x29, - And = 0x21, - Or = 0x09, - Xor = 0x31, + Add, + Sub, + And, + Or, + Xor, +} + +impl Binary { + const fn alu(self) -> Alu { + match self { + Self::Add => Alu::Add, + Self::Sub => Alu::Sub, + Self::And => Alu::And, + Self::Or => Alu::Or, + Self::Xor => Alu::Xor, + } + } } /// Low product modulo operand width; only destination and host flags change. -pub fn multiply(code: &mut Vec, destination: HostGpr, source: HostGpr, width: Width) { - rex(code, width, destination, source); - code.extend([ - TWO_BYTE_OPCODE, - IMUL, - REGISTER_MODE | ((destination as u8 & 7) << 3) | (source as u8 & 7), - ]); +pub fn multiply(code: &mut Code, destination: HostGpr, source: HostGpr, width: Width) { + code.asm() + .imul(size(width), destination.gpr(), source.gpr()); } -pub fn negate(code: &mut Vec, destination: HostGpr, width: Width) { - const NEG_EXTENSION: u8 = 3; - rex(code, width, HostGpr::Rax, destination); - code.extend([ - UNARY_GROUP, - REGISTER_MODE | (NEG_EXTENSION << 3) | (destination as u8 & 7), - ]); +pub fn negate(code: &mut Code, destination: HostGpr, width: Width) { + code.asm().unary(Unary::Neg, size(width), destination.gpr()); } pub fn logical_opcode(kind: Logical) -> Binary { @@ -240,7 +208,7 @@ pub fn logical_opcode(kind: Logical) -> Binary { } pub fn arithmetic_immediate( - code: &mut Vec, + code: &mut Code, destination: HostGpr, subtract: bool, value: u32, @@ -259,80 +227,70 @@ pub fn arithmetic_immediate( ); } +/// `op destination, imm32`, in its accumulator form for RAX. pub fn integer_immediate( - code: &mut Vec, + code: &mut Code, destination: HostGpr, extension: ImmediateExtension, value: u32, width: Width, ) { if destination == HostGpr::Rax { - const ADD_ACCUMULATOR: u8 = 0x05; - const SUBTRACT_ACCUMULATOR: u8 = 0x2d; - const AND_ACCUMULATOR: u8 = 0x25; - const COMPARE_ACCUMULATOR: u8 = 0x3d; - rex(code, width, HostGpr::Rax, destination); - code.push(match extension { - ImmediateExtension::Add => ADD_ACCUMULATOR, - ImmediateExtension::Subtract => SUBTRACT_ACCUMULATOR, - ImmediateExtension::And => AND_ACCUMULATOR, - ImmediateExtension::Compare => COMPARE_ACCUMULATOR, - }); - code.extend(value.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(extension.alu(), size(width), value as i32); } else { group_immediate(code, destination, extension, value, width); } } +/// `op destination, imm32` (81 /digit). fn group_immediate( - code: &mut Vec, + code: &mut Code, destination: HostGpr, extension: ImmediateExtension, value: u32, width: Width, ) { - rex(code, width, HostGpr::Rax, destination); - code.extend([ - IMMEDIATE_GROUP, - REGISTER_MODE | ((extension as u8) << 3) | (destination as u8 & 7), - ]); - code.extend(value.to_le_bytes()); + code.asm().alu_imm32( + extension.alu(), + size(width), + destination.gpr(), + value as i32, + ); } -pub fn shift(code: &mut Vec, kind: Shift, amount: u8, width: Width) { +pub fn shift(code: &mut Code, kind: Shift, amount: u8, width: Width) { shift_register(code, RIGHT, kind, amount, width); } pub fn shift_register( - code: &mut Vec, + code: &mut Code, destination: HostGpr, kind: Shift, amount: u8, width: Width, ) { - rex(code, width, HostGpr::Rax, destination); - let extension = match kind { - Shift::Lsl => 4, - Shift::Lsr => 5, - Shift::Asr => 7, - Shift::Ror => 1, + let op = match kind { + Shift::Lsl => ShiftOp::Shl, + Shift::Lsr => ShiftOp::Shr, + Shift::Asr => ShiftOp::Sar, + Shift::Ror => ShiftOp::Ror, }; - code.extend([ - SHIFT_IMMEDIATE_GROUP, - REGISTER_MODE | (extension << 3) | (destination as u8 & 7), - amount, - ]); + code.asm() + .shift_imm(op, size(width), destination.gpr(), amount); } -pub fn invert(code: &mut Vec, width: Width) { - rex(code, width, HostGpr::Rax, RIGHT); - const NOT_EXTENSION: u8 = 2; - code.extend([ - UNARY_GROUP, - REGISTER_MODE | (NOT_EXTENSION << 3) | RIGHT as u8, - ]); +pub fn invert(code: &mut Code, width: Width) { + code.asm().unary(Unary::Not, size(width), RIGHT.gpr()); } +const REX: u8 = 0x40; +const REX_W: u8 = 8; +const REX_R: u8 = 4; +const REX_B: u8 = 1; +const MOV_LOAD: u8 = 0x8b; +const MOV_STORE: u8 = 0x89; +const TWO_BYTE_OPCODE: u8 = 0x0f; const FRAME_STORE_BYTES: usize = 7; const GPR_BYTES: usize = core::mem::size_of::(); const ECX_FROM_RAX_MEMORY: u8 = 0x08; @@ -361,7 +319,7 @@ fn ordinary_address_ends(code: &[u8], base: usize, displacement: i32) -> Option< cursor += STACK_ALIGNMENT_CHECK.len(); } // The Offset form's one LEA, or nothing for a zero offset. - let mut add = vec![]; + let mut add = Code::new(); super::super::address_add(&mut add, displacement, AddressMode::Offset); if !add.is_empty() { if code.get(cursor..cursor + add.len())? != add { @@ -596,22 +554,21 @@ pub fn ordinary_pair_store_ends( /// Native conditions after a full-width ARM subtraction (C is inverted CF). #[derive(Debug, Clone, Copy)] -#[repr(u8)] pub enum NativeCondition { - Equal = 0x84, - NotEqual = 0x85, - AboveEqual = 0x83, - Below = 0x82, - Sign = 0x88, - NotSign = 0x89, - Overflow = 0x80, - NotOverflow = 0x81, - Above = 0x87, - BelowEqual = 0x86, - GreaterEqual = 0x8d, - Less = 0x8c, - Greater = 0x8f, - LessEqual = 0x8e, + Equal, + NotEqual, + AboveEqual, + Below, + Sign, + NotSign, + Overflow, + NotOverflow, + Above, + BelowEqual, + GreaterEqual, + Less, + Greater, + LessEqual, } pub const SUBTRACTION_CONDITIONS: [NativeCondition; 14] = [ @@ -632,6 +589,26 @@ pub const SUBTRACTION_CONDITIONS: [NativeCondition; 14] = [ ]; impl NativeCondition { + /// The encoder's condition code. + const fn cond(self) -> Cond { + match self { + Self::Equal => Cond::E, + Self::NotEqual => Cond::Ne, + Self::AboveEqual => Cond::Ae, + Self::Below => Cond::B, + Self::Sign => Cond::S, + Self::NotSign => Cond::Ns, + Self::Overflow => Cond::O, + Self::NotOverflow => Cond::No, + Self::Above => Cond::A, + Self::BelowEqual => Cond::Be, + Self::GreaterEqual => Cond::Ge, + Self::Less => Cond::L, + Self::Greater => Cond::G, + Self::LessEqual => Cond::Le, + } + } + pub fn inverse(self) -> Self { match self { Self::Equal => Self::NotEqual, @@ -653,52 +630,40 @@ impl NativeCondition { } pub fn conditional_copy( - code: &mut Vec, + code: &mut Code, destination: HostGpr, source: HostGpr, condition: NativeCondition, width: Width, ) { - const JCC_TO_CMOV: u8 = 0x40; - rex(code, width, destination, source); - code.extend([ - TWO_BYTE_OPCODE, - condition as u8 - JCC_TO_CMOV, - REGISTER_MODE | ((destination as u8 & 7) << 3) | (source as u8 & 7), - ]); + code.asm().cmov( + condition.cond(), + size(width), + destination.gpr(), + source.gpr(), + ); } -pub fn increment_preserving_flags(code: &mut Vec, register: HostGpr, width: Width) { - rex(code, width, register, register); - code.extend([ - LEA, - DISP8_MODE | ((register as u8 & 7) << 3) | (register as u8 & 7), - 1, - ]); +/// `lea register, [register + 1]`. +pub fn increment_preserving_flags(code: &mut Code, register: HostGpr, width: Width) { + code.asm().lea( + size(width), + register.gpr(), + Mem::base_disp8(register.gpr(), 1), + ); } -const NEAR_JUMP: u8 = 0xe9; -const JRCXZ: u8 = 0xe3; -const PUSH_REGISTER: u8 = 0x50; -const POP_REGISTER: u8 = 0x58; -const LEA: u8 = 0x8d; -const INC_DEC_GROUP: u8 = 0xff; -const DEC_EXTENSION: u8 = 1; const RELATIVE_BYTES: usize = core::mem::size_of::(); -const NEAR_JUMP_BYTES: u8 = 1 + RELATIVE_BYTES as u8; -pub fn near_jump(code: &mut Vec) -> usize { - code.push(NEAR_JUMP); - let displacement = code.len(); - code.extend(0i32.to_le_bytes()); - displacement +/// `jmp rel32`; the offset of its displacement field, which +/// [`patch_relative`] points. +pub fn near_jump(code: &mut Code) -> usize { + code.asm().jmp().offset() } -pub fn conditional_jump(code: &mut Vec, condition: NativeCondition) -> usize { - code.extend([TWO_BYTE_OPCODE, condition as u8]); - let displacement = code.len(); - code.extend(0i32.to_le_bytes()); - displacement +/// `jcc rel32`; the offset of its displacement field. +pub fn conditional_jump(code: &mut Code, condition: NativeCondition) -> usize { + code.asm().jcc(condition.cond()).offset() } pub fn patch_relative(code: &mut [u8], displacement: usize, target: usize) { @@ -708,65 +673,53 @@ pub fn patch_relative(code: &mut [u8], displacement: usize, target: usize) { } /// Zero skips exactly the following near jump; no host flags change. -pub fn skip_jump_if_budget_zero(code: &mut Vec) { - code.extend([JRCXZ, NEAR_JUMP_BYTES]); +pub fn skip_jump_if_budget_zero(code: &mut Code) { + const NEAR_JUMP_BYTES: usize = 1 + RELATIVE_BYTES; + let skip = code.asm().jrcxz(); + resolve(code, skip, skip.end() + NEAR_JUMP_BYTES); } -pub fn push_budget_pointer(code: &mut Vec) { +pub fn push_budget_pointer(code: &mut Code) { push(code, HostGpr::Rsi); } -pub fn pop_budget_pointer(code: &mut Vec) { +pub fn pop_budget_pointer(code: &mut Code) { pop(code, HostGpr::Rsi); } -pub fn push(code: &mut Vec, register: HostGpr) { - if register as u8 >= 8 { - code.push(REX | REX_B); - } - code.push(PUSH_REGISTER | (register as u8 & 7)); +pub fn push(code: &mut Code, register: HostGpr) { + code.asm().push(register.gpr()); } -pub fn pop(code: &mut Vec, register: HostGpr) { - if register as u8 >= 8 { - code.push(REX | REX_B); - } - code.push(POP_REGISTER | (register as u8 & 7)); +pub fn pop(code: &mut Code, register: HostGpr) { + code.asm().pop(register.gpr()); } -pub fn load_budget(code: &mut Vec) { +/// The budget pointer's remaining count. +fn budget() -> Mem { const _: () = assert!(crate::block::loop_budget::REMAINING_OFFSET == 0); - code.extend([ - REX | REX_W, - MOV_LOAD, - (HostGpr::Rcx as u8) << 3 | HostGpr::Rsi as u8, - ]); + Mem::base(HostGpr::Rsi.gpr(), 0) } -pub fn store_budget(code: &mut Vec) { - code.extend([ - REX | REX_W, - MOV_STORE, - (HostGpr::Rcx as u8) << 3 | HostGpr::Rsi as u8, - ]); +pub fn load_budget(code: &mut Code) { + code.asm() + .mov_load(Size::Qword, HostGpr::Rcx.gpr(), budget()); } -pub fn decrement_budget_preserving_flags(code: &mut Vec) { - code.extend([ - REX | REX_W, - LEA, - DISP8_MODE | ((HostGpr::Rcx as u8) << 3) | HostGpr::Rcx as u8, - ]); - code.extend((-1i8).to_le_bytes()); +pub fn store_budget(code: &mut Code) { + code.asm() + .mov_store(Size::Qword, budget(), HostGpr::Rcx.gpr()); +} + +/// `lea rcx, [rcx - 1]`. +pub fn decrement_budget_preserving_flags(code: &mut Code) { + let rcx = HostGpr::Rcx.gpr(); + code.asm().lea(Size::Qword, rcx, Mem::base_disp8(rcx, -1)); } /// The fallback path counts one block before running its body. -pub fn decrement_stored_budget(code: &mut Vec) { - code.extend([ - REX | REX_W, - INC_DEC_GROUP, - (DEC_EXTENSION << 3) | HostGpr::Rsi as u8, - ]); +pub fn decrement_stored_budget(code: &mut Code) { + code.asm().dec(Size::Qword, budget()); } #[cfg(test)] @@ -775,8 +728,8 @@ mod tests { #[test] fn region_address_forms_encode_as_the_assembler_does() { - let encode = |emit: &dyn Fn(&mut Vec)| { - let mut code = vec![]; + let encode = |emit: &dyn Fn(&mut Code)| { + let mut code = Code::new(); emit(&mut code); code }; diff --git a/crates/stela-compiler/src/x86_64/region/flags.rs b/crates/stela-compiler/src/x86_64/region/flags.rs index 93ebdfd4f3..bfcd939a9f 100644 --- a/crates/stela-compiler/src/x86_64/region/flags.rs +++ b/crates/stela-compiler/src/x86_64/region/flags.rs @@ -10,7 +10,7 @@ use crate::aarch64::{ conditional_select::{Operand, Otherwise}, flags::{NZCV_C, NZCV_N, NZCV_V, NZCV_Z}, }; -use alloc::vec::Vec; +use crate::x86_64::asm::Code; use encoding::{NativeCondition, RESULT, RIGHT}; const ARM_CS: u8 = 0b0010; @@ -239,7 +239,7 @@ const _: () = assert!(matches!(RIGHT, encoding::HostGpr::Rdx)); /// The two-scratch SETcc capture into RESULT (EAX), clobbering RIGHT (RDX). /// RCX (a live value or budget) is intact. -fn pack_native(code: &mut Vec, carry: Carry) { +fn pack_native(code: &mut Code, carry: Carry) { crate::x86_64::capture_nzcv(code, matches!(carry, Carry::Inverted)); } @@ -467,7 +467,7 @@ fn packed_predicate(emitter: &mut Emitter<'_>, condition: u8) -> Predicate { } /// Complete exit capture after all native-resident GPR outputs have been stored. -pub(super) fn settle_native_exit(code: &mut Vec, carry: Carry) { +pub(super) fn settle_native_exit(code: &mut Code, carry: Carry) { pack_native(code, carry); encoding::store_nzcv(code, RESULT); } diff --git a/crates/stela-compiler/src/x86_64/region/self_loop.rs b/crates/stela-compiler/src/x86_64/region/self_loop.rs index 719df7f8d4..ce6a59c0da 100644 --- a/crates/stela-compiler/src/x86_64/region/self_loop.rs +++ b/crates/stela-compiler/src/x86_64/region/self_loop.rs @@ -4,6 +4,7 @@ use super::{ AllocationStats, Effects, Emitter, FRAME_LOCATIONS, GPR_SLOTS, HostGpr, Location, MAX_INSTRUCTIONS, OptimizedRegion, POOL, Resident, analysis, constant, encoding, flags, }; +use crate::x86_64::asm::Code; use crate::{ GuestAddress, NativeBlock, aarch64::{Instruction, Operation}, @@ -16,7 +17,7 @@ const ARM_CONDITION_INVERSE_BIT: u8 = 1; const INSTRUCTION_BYTES: u64 = core::mem::size_of::() as u64; pub(crate) fn prefix_with_budget(mut native: NativeBlock, base: GuestAddress) -> NativeBlock { - let mut code = vec![]; + let mut code = Code::new(); encoding::load_budget(&mut code); encoding::skip_jump_if_budget_zero(&mut code); let body_jump = encoding::near_jump(&mut code); @@ -32,7 +33,7 @@ pub(crate) fn prefix_with_budget(mut native: NativeBlock, base: GuestAddress) -> if let Some((_, offset)) = native.source_map.first_mut() { *offset = 0; } - native.x86_64_code = code; + native.x86_64_code = code.into_bytes(); native } @@ -210,7 +211,7 @@ impl LegacyPlan { }; let prefix = &instructions[..instructions.len() - 1]; let available = (0..POOL.len()).filter(|&index| POOL[index] != HostGpr::Rcx); - let mut code = vec![]; + let mut code = Code::new(); encoding::push_budget_pointer(&mut code); encoding::load_budget(&mut code); encoding::skip_jump_if_budget_zero(&mut code); @@ -305,18 +306,13 @@ impl LegacyPlan { *offset = 0; } Ok(NativeBlock { - x86_64_code: emitter.output.code, + x86_64_code: emitter.output.code.into_bytes(), source_map: emitter.output.source_map, }) } } -fn settle_exit( - code: &mut Vec, - dirty: &[(HostGpr, usize)], - next_pc: GuestAddress, - kind: ExitKind, -) { +fn settle_exit(code: &mut Code, dirty: &[(HostGpr, usize)], next_pc: GuestAddress, kind: ExitKind) { // Every instruction before NZCV capture preserves host subtraction flags. for &(host, guest) in dirty { encoding::store(code, host, guest); @@ -451,7 +447,7 @@ fn allocated_loop( // complete body, then the smaller native callee-save footprint. let cost = (hot_frame, emitter.output.code.len(), callee_slots); let native = NativeBlock { - x86_64_code: emitter.output.code, + x86_64_code: emitter.output.code.into_bytes(), source_map: emitter.output.source_map, }; if best.as_ref().is_none_or(|(old, _)| cost < *old) { @@ -462,7 +458,7 @@ fn allocated_loop( } fn settle_allocated_exit( - code: &mut Vec, + code: &mut Code, dirty: &[(HostGpr, usize)], callee_slots: usize, carry: flags::Carry, diff --git a/crates/stela-compiler/src/x86_64/register_offset.rs b/crates/stela-compiler/src/x86_64/register_offset.rs index e13e53e1e8..1a9de356a7 100644 --- a/crates/stela-compiler/src/x86_64/register_offset.rs +++ b/crates/stela-compiler/src/x86_64/register_offset.rs @@ -4,9 +4,9 @@ use super::{ offset, right_operand, }; use crate::aarch64::register_offset::{IndexExtend, Operand}; -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, ShiftOp, Size}; -pub(super) fn emit(code: &mut Vec, operand: &Operand, checks: super::MemoryChecks) { +pub(super) fn emit(code: &mut Code, operand: &Operand, checks: super::MemoryChecks) { address( code, checks, @@ -25,7 +25,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, checks: super::MemoryC /// and SCTLR_ELx.A checks the result against the access's `bytes`. #[allow(clippy::too_many_arguments)] pub(super) fn address( - code: &mut Vec, + code: &mut Code, checks: super::MemoryChecks, base: Register, index: Register, @@ -47,48 +47,42 @@ pub(super) fn address( super::address_checks(code, checks, bytes, access); } -const MOV_ECX_STATE: [u8; 2] = [0x8b, 0x8f]; -const MOVSXD_RCX_STATE: [u8; 3] = [0x48, 0x63, 0x8f]; -const MOV_RCX_STATE: [u8; 3] = [0x48, 0x8b, 0x8f]; -const ADD_RAX_STATE: [u8; 3] = [0x48, 0x03, 0x87]; -const SHL_RCX_IMM8: [u8; 3] = [0x48, 0xc1, 0xe1]; -/// LEA RAX,[RAX+RCX*scale]: the SIB byte's scale field, RCX index, RAX base. -const LEA_RAX_RAX_RCX: [u8; 3] = [0x48, 0x8d, 0x04]; -const SIB_RCX_INDEX_RAX_BASE: u8 = 0x08; -const SIB_SCALE_SHIFT: u8 = 6; /// The largest shift a SIB scale applies (times eight). const MAX_SCALE_SHIFT: u8 = 3; /// The index register, extended and shifted, added to the base in RAX /// modulo 2^64. A W index is read with its extension from its frame slot; /// a ZR index adds nothing. RCX and host flags are scratch. -pub(crate) fn index_add(code: &mut Vec, index: Register, extend: IndexExtend, shift: u8) { +pub(crate) fn index_add(code: &mut Code, index: Register, extend: IndexExtend, shift: u8) { let Some(slot) = offset(index) else { return; }; + let state = Mem::base_disp32(Gpr::Rdi, slot as i32); + let mut asm = code.asm(); match extend { - IndexExtend::Uxtw => code.extend(MOV_ECX_STATE), - IndexExtend::Sxtw => code.extend(MOVSXD_RCX_STATE), + IndexExtend::Uxtw => asm.mov_load(Size::Dword, Gpr::Rcx, state), + IndexExtend::Sxtw => asm.movsxd(Gpr::Rcx, state), IndexExtend::Lsl | IndexExtend::Sxtx if shift == 0 => { - code.extend(ADD_RAX_STATE); - code.extend(slot.to_le_bytes()); + asm.alu_load(Alu::Add, Size::Qword, Gpr::Rax, state); return; } - IndexExtend::Lsl | IndexExtend::Sxtx => code.extend(MOV_RCX_STATE), + IndexExtend::Lsl | IndexExtend::Sxtx => asm.mov_load(Size::Qword, Gpr::Rcx, state), } - code.extend(slot.to_le_bytes()); let scale = if shift > MAX_SCALE_SHIFT { - code.extend(SHL_RCX_IMM8); - code.push(shift); + asm.shift_imm(ShiftOp::Shl, Size::Qword, Gpr::Rcx, shift); 0 } else { shift }; - code.extend(LEA_RAX_RAX_RCX); - code.push(scale << SIB_SCALE_SHIFT | SIB_RCX_INDEX_RAX_BASE); + // RAX + RCX * 2^scale, the SIB scale applying the shift. + asm.lea( + Size::Qword, + Gpr::Rax, + Mem::indexed(Gpr::Rax, Gpr::Rcx, 1 << scale, 0), + ); } -fn transfer(code: &mut Vec, operand: &Operand, checks: super::MemoryChecks) { +fn transfer(code: &mut Code, operand: &Operand, checks: super::MemoryChecks) { match operand.transfer { MemoryTransfer::Store => { right_operand(code, operand.data, Width::X64, Shift::Lsl, 0); @@ -107,22 +101,28 @@ fn transfer(code: &mut Vec, operand: &Operand, checks: super::MemoryChecks) ); } MemoryTransfer::Load { signed, width } => { - if width == Width::X64 { - code.push(0x48); - } + let size = Size::of(width == Width::X64); + let address = Mem::base(Gpr::Rax, 0); + let mut asm = code.asm(); match (operand.bytes, signed) { - (1, false) => code.extend([0x0f, 0xb6, 0x08]), - (2, false) => code.extend([0x0f, 0xb7, 0x08]), - (1, true) => code.extend([0x0f, 0xbe, 0x08]), - (2, true) => code.extend([0x0f, 0xbf, 0x08]), - (4, true) => code.extend([0x63, 0x08]), - (4 | 8, false) => code.extend([0x8b, 0x08]), + (1, false) => asm.movzx(size, Gpr::Rcx, Size::Byte, address), + (2, false) => asm.movzx(size, Gpr::Rcx, Size::Word, address), + (1, true) => asm.movsx(size, Gpr::Rcx, Size::Byte, address), + (2, true) => asm.movsx(size, Gpr::Rcx, Size::Word, address), + (4, true) => { + debug_assert!(size == Size::Qword); + asm.movsxd(Gpr::Rcx, address); + } + (4 | 8, false) => asm.mov_load(size, Gpr::Rcx, address), _ => unreachable!("decoder validates signed register-offset size"), } // A load to ZR still accesses memory and can fault. if let Some(displacement) = offset(operand.data) { - code.extend([0x48, 0x89, 0x8f]); - code.extend(displacement.to_le_bytes()); + asm.mov_store( + Size::Qword, + Mem::base_disp32(Gpr::Rdi, displacement as i32), + Gpr::Rcx, + ); } } } diff --git a/crates/stela-compiler/src/x86_64/register_read.rs b/crates/stela-compiler/src/x86_64/register_read.rs index 896ac5ff91..3fbc69c85d 100644 --- a/crates/stela-compiler/src/x86_64/register_read.rs +++ b/crates/stela-compiler/src/x86_64/register_read.rs @@ -17,6 +17,7 @@ //! clock shows at the host's TSC ([`Count`]), less the cell's `value`. //! It also clobbers RCX and RDX, which are dead at every block exit (the //! direct exit returns in RAX and RDX, and chaining uses RCX). +use super::asm::{Alu, Asm, Cond, Gpr, Mem, Patch, ShiftOp, Size, Unary, resolve}; use super::pointer::Thunk; use crate::{GuestAddress, block::ExitKind}; use alloc::vec::Vec; @@ -30,7 +31,7 @@ pub struct Cell { pub value: u64, } -const VALUE: u8 = core::mem::offset_of!(Cell, value) as u8; +const VALUE: i8 = core::mem::offset_of!(Cell, value) as i8; const _: () = assert!(core::mem::offset_of!(Cell, readable) == 0); /// The engine's system count at a host TSC value `tsc`: the larger of @@ -45,72 +46,75 @@ pub struct Count { pub last: u64, } -const BASE: u8 = core::mem::offset_of!(Count, base) as u8; -const PER_TSC: u8 = core::mem::offset_of!(Count, per_tsc) as u8; -const OFFSET: u8 = core::mem::offset_of!(Count, offset) as u8; -const LAST: u8 = core::mem::offset_of!(Count, last) as u8; +const BASE: i8 = core::mem::offset_of!(Count, base) as i8; +const PER_TSC: i8 = core::mem::offset_of!(Count, per_tsc) as i8; +const OFFSET: i8 = core::mem::offset_of!(Count, offset) as i8; +const LAST: i8 = core::mem::offset_of!(Count, last) as i8; + +/// Xt's frame slot. +fn register(rt: u8) -> Mem { + Mem::base_disp32(Gpr::Rdi, i32::from(rt) * 8) +} /// The thunk completing `MRS Xt, ` at `pc` from the cell at /// `cell`, else exiting at `pc` for the engine. pub fn thunk(pc: GuestAddress, rt: u8, cell: u64) -> Thunk { - let mut code = open(cell); - let fixup = code.len() - 4; + let (mut code, miss) = open(cell); if rt != 31 { - code.extend([0x48, 0x8b, 0x40, VALUE]); // mov rax,[rax+value] - code.extend([0x48, 0x89, 0x87]); // mov [rdi+x(rt)],rax - code.extend((u32::from(rt) * 8).to_le_bytes()); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rax, Mem::base_disp8(Gpr::Rax, VALUE)); + asm.mov_store(Size::Qword, register(rt), Gpr::Rax); } - finish(code, fixup, pc) + finish(code, miss, pc) } /// The thunk completing `MRS Xt, ` at `pc` with the count at /// `count` less the `value` of the cell at `cell`, else exiting at `pc`. pub fn count_thunk(pc: GuestAddress, rt: u8, cell: u64, count: u64) -> Thunk { - let mut code = open(cell); - let fixup = code.len() - 4; - code.extend([0x48, 0xb9]); // movabs rcx,count - code.extend(count.to_le_bytes()); - code.extend([0x0f, 0x31]); // rdtsc - code.extend([0x48, 0xc1, 0xe2, 0x20]); // shl rdx,32 - code.extend([0x48, 0x09, 0xd0]); // or rax,rdx - code.extend([0x48, 0x2b, 0x41, BASE]); // sub rax,[rcx+base] - code.extend([0x48, 0xf7, 0x61, PER_TSC]); // mul qword [rcx+per_tsc] - code.extend([0x48, 0x03, 0x51, OFFSET]); // add rdx,[rcx+offset] - code.extend([0x48, 0x8b, 0x41, LAST]); // mov rax,[rcx+last] - code.extend([0x48, 0x39, 0xc2]); // cmp rdx,rax - code.extend([0x48, 0x0f, 0x42, 0xd0]); // cmovb rdx,rax - code.extend([0x48, 0x89, 0x51, LAST]); // mov [rcx+last],rdx + use Gpr::{Rax, Rcx, Rdx}; + use Size::Qword; + let (mut code, miss) = open(cell); + let field = |offset| Mem::base_disp8(Rcx, offset); + let mut asm = Asm::new(&mut code); + asm.mov_imm64(Rcx, count); + asm.rdtsc(); + asm.shift_imm(ShiftOp::Shl, Qword, Rdx, 32); + asm.alu(Alu::Or, Qword, Rax, Rdx); + asm.alu_load(Alu::Sub, Qword, Rax, field(BASE)); + asm.unary(Unary::Mul, Qword, field(PER_TSC)); + asm.alu_load(Alu::Add, Qword, Rdx, field(OFFSET)); + asm.mov_load(Qword, Rax, field(LAST)); + asm.alu(Alu::Cmp, Qword, Rdx, Rax); + asm.cmov(Cond::B, Qword, Rdx, Rax); + asm.mov_store(Qword, field(LAST), Rdx); if rt != 31 { - code.extend([0x48, 0xb8]); // movabs rax,cell - code.extend(cell.to_le_bytes()); - code.extend([0x48, 0x2b, 0x50, VALUE]); // sub rdx,[rax+value] - code.extend([0x48, 0x89, 0x97]); // mov [rdi+x(rt)],rdx - code.extend((u32::from(rt) * 8).to_le_bytes()); + asm.mov_imm64(Rax, cell); + asm.alu_load(Alu::Sub, Qword, Rdx, Mem::base_disp8(Rax, VALUE)); + asm.mov_store(Qword, register(rt), Rdx); } - finish(code, fixup, pc) + finish(code, miss, pc) } -/// Load `cell` and branch to the miss while it is not readable; the -/// branch's 32-bit displacement ends the code. -fn open(cell: u64) -> Vec { +/// Load `cell` and branch to the miss while it is not readable. +fn open(cell: u64) -> (Vec, Patch) { let mut code = Vec::with_capacity(128); - code.extend([0x48, 0xb8]); // movabs rax,cell - code.extend(cell.to_le_bytes()); - code.extend([0x48, 0x83, 0x38, 0x00]); // cmp qword [rax],0 - code.extend([0x0f, 0x84, 0, 0, 0, 0]); // je miss - code + let mut asm = Asm::new(&mut code); + asm.mov_imm64(Gpr::Rax, cell); + asm.alu_imm8(Alu::Cmp, Size::Qword, Mem::base(Gpr::Rax, 0), 0); + let miss = asm.jcc(Cond::E); + (code, miss) } -/// The direct exit to the next instruction, then the miss at `fixup`'s -/// branch: the original exit at `pc`. -fn finish(mut code: Vec, fixup: usize, pc: GuestAddress) -> Thunk { +/// The direct exit to the next instruction, then the `miss` branch's +/// target: the original exit at `pc`. +fn finish(mut code: Vec, miss: Patch, pc: GuestAddress) -> Thunk { let next = code.len(); code.extend(super::chain::direct_exit( GuestAddress(pc.0.wrapping_add(4)), ExitKind::Fallthrough, )); - let relative = (code.len() - fixup - 4) as i32; - code[fixup..fixup + 4].copy_from_slice(&relative.to_le_bytes()); + let original = code.len(); + resolve(&mut code, miss, original); code.extend(super::chain::direct_exit(pc, ExitKind::System)); Thunk { code, diff --git a/crates/stela-compiler/src/x86_64/scalable.rs b/crates/stela-compiler/src/x86_64/scalable.rs index aee74062f7..4b6836a9aa 100644 --- a/crates/stela-compiler/src/x86_64/scalable.rs +++ b/crates/stela-compiler/src/x86_64/scalable.rs @@ -3,15 +3,16 @@ //! RDI holds GuestState and R15 the ExecutionContext. The low 128 bits of each Z //! register live in `GuestState::v`; the upper bytes and packed predicates live //! in the scalable view. Helpers clobber only RAX/RCX/RDX and XMM0-7. +use crate::x86_64::asm::Gpr::{R15, Rax, Rcx, Rdi, Rdx}; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Rm, Size, Unary}; pub(crate) use super::memory_context as memory; -use alloc::vec::Vec; -mod legacy; pub(crate) mod lut; pub(crate) mod numerical; pub(crate) mod routing; -pub(crate) use legacy::clear_z_upper; +mod z_upper; +pub(crate) use z_upper::clear_z_upper; mod predicate; pub(crate) use predicate::{write_predicate_chunk, zero_predicate}; @@ -29,28 +30,12 @@ use crate::{ }; const XMM_REGISTER_COUNT: u8 = 8; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_DISP32: u8 = 0x80; -const REGISTER_SHIFT: u8 = 3; -const STATE_RDI: u8 = 7; -const ADDRESS_RDX: u8 = 2; const HALFWORD_BYTES: usize = core::mem::size_of::(); const DWORD_BYTES: usize = core::mem::size_of::(); const QWORD_BYTES: usize = core::mem::size_of::(); const PREDICATE_CHUNK_BYTES: usize = QWORD_BYTES; const PREDICATE_MASK_BYTES: usize = VECTOR_CHUNK_BYTES / BITS_PER_BYTE; -const MOV_RDX_CONTEXT_DISP8: &[u8] = &[0x49, 0x8b, 0x57]; -const MOV_RDX_RDX_DISP8: &[u8] = &[0x48, 0x8b, 0x52]; -const MOVZX_EAX_WORD_RDX_DISP32: &[u8] = &[0x0f, 0xb7, 0x82]; -const MOV_EAX_RDX_DISP32: &[u8] = &[0x8b, 0x82]; -const MOV_RAX_RDX_DISP32: &[u8] = &[0x48, 0x8b, 0x82]; -const MOVD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; -const MOVABS_RCX_IMM64: &[u8] = &[0x48, 0xb9]; -const MOVQ_XMM_RCX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e]; -const AND_EAX_IMM8: &[u8] = &[0x83, 0xe0]; -const NEG_EAX: &[u8] = &[0xf7, 0xd8]; const DWORD_SIGN_BIT: u8 = (u32::BITS - 1) as u8; -const RCX_REGISTER: u8 = 1; const REPEAT_LOW_DWORD: u8 = 0; const REPEAT_LOW_TWO_DWORDS: u8 = 0x50; const FIRST_PREDICATE_BIT: u8 = 1; @@ -62,14 +47,17 @@ fn xmm(register: u8) { ); } -fn storage_pointer(code: &mut Vec, field: u32) { +fn storage_pointer(code: &mut Code, field: u32) { // Both fields fit positive signed disp8 in the versioned shared ABI. debug_assert!(EXECUTION_CONTEXT_SCALABLE_OFFSET <= i8::MAX as u32); debug_assert!(field <= i8::MAX as u32); - code.extend(MOV_RDX_CONTEXT_DISP8); - code.push(EXECUTION_CONTEXT_SCALABLE_OFFSET as u8); - code.extend(MOV_RDX_RDX_DISP8); - code.push(field as u8); + let mut asm = code.asm(); + asm.mov_load( + Size::Qword, + Rdx, + Mem::base_disp8(R15, EXECUTION_CONTEXT_SCALABLE_OFFSET as i8), + ); + asm.mov_load(Size::Qword, Rdx, Mem::base_disp8(Rdx, field as i8)); } fn vector_offset(register: u8) -> u32 { @@ -85,22 +73,25 @@ fn upper_offset(register: u8, chunk: usize, length: VectorLength) -> u32 { } fn vector_memory( - code: &mut Vec, + code: &mut Code, opcode: Host, register: u8, - base: u8, + base: Gpr, displacement: u32, target: TargetCpu, ) { xmm(register); - opcode.append(code, target); - code.push(MODRM_DISP32 | (register << REGISTER_SHIFT) | base); - code.extend(displacement.to_le_bytes()); + code.asm().simd( + opcode, + register, + Mem::base_disp32(base, displacement as i32), + target, + ); } /// Read one 16-byte Z segment into XMM0..7. Upper chunks clobber RDX only. pub(crate) fn load_z_chunk( - code: &mut Vec, + code: &mut Code, register: u8, chunk: usize, destination: u8, @@ -109,10 +100,10 @@ pub(crate) fn load_z_chunk( ) { assert!(chunk < length.chunks()); let (base, displacement) = if chunk == 0 { - (STATE_RDI, vector_offset(register)) + (Rdi, vector_offset(register)) } else { storage_pointer(code, SCALABLE_Z_UPPER_OFFSET); - (ADDRESS_RDX, upper_offset(register, chunk, length)) + (Rdx, upper_offset(register, chunk, length)) }; vector_memory( code, @@ -126,7 +117,7 @@ pub(crate) fn load_z_chunk( /// Commit one 16-byte Z segment from XMM0..7. Upper chunks clobber RDX only. pub(crate) fn store_z_chunk( - code: &mut Vec, + code: &mut Code, register: u8, chunk: usize, source: u8, @@ -135,10 +126,10 @@ pub(crate) fn store_z_chunk( ) { assert!(chunk < length.chunks()); let (base, displacement) = if chunk == 0 { - (STATE_RDI, vector_offset(register)) + (Rdi, vector_offset(register)) } else { storage_pointer(code, SCALABLE_Z_UPPER_OFFSET); - (ADDRESS_RDX, upper_offset(register, chunk, length)) + (Rdx, upper_offset(register, chunk, length)) }; vector_memory( code, @@ -156,14 +147,15 @@ fn predicate_offset(predicate: u8, byte_offset: usize, length: VectorLength) -> (usize::from(predicate) * length.predicate_bytes() + byte_offset) as u32 } -fn read_predicate_at(code: &mut Vec, displacement: u32, bytes: usize) { - code.extend(match bytes { - HALFWORD_BYTES => MOVZX_EAX_WORD_RDX_DISP32, - DWORD_BYTES => MOV_EAX_RDX_DISP32, - QWORD_BYTES => MOV_RAX_RDX_DISP32, +fn read_predicate_at(code: &mut Code, displacement: u32, bytes: usize) { + let source = Mem::base_disp32(Rdx, displacement as i32); + let mut asm = code.asm(); + match bytes { + HALFWORD_BYTES => asm.movzx(Size::Dword, Rax, Size::Word, source), + DWORD_BYTES => asm.mov_load(Size::Dword, Rax, source), + QWORD_BYTES => asm.mov_load(Size::Qword, Rax, source), _ => unreachable!("validated streaming length has 2/4/8-byte predicate chunks"), - }); - code.extend(displacement.to_le_bytes()); + } } fn predicate_bit_pattern(element: ElementSize) -> u64 { @@ -181,7 +173,7 @@ fn predicate_bit_pattern(element: ElementSize) -> u64 { /// Clobbers RAX/RCX/RDX and those two XMMs; preserves other XMMs, RDI and R15. #[allow(clippy::too_many_arguments)] pub(crate) fn read_predicate_mask( - code: &mut Vec, + code: &mut Code, predicate: u8, chunk: usize, element: ElementSize, @@ -207,7 +199,7 @@ pub(crate) fn read_predicate_mask( /// bits are ignored. Used by packed P and compressed-counter predicate readers. /// Clobbers RAX/RCX and destination/scratch XMMs; leaves RDX and other XMMs live. pub(crate) fn expand_predicate_mask( - code: &mut Vec, + code: &mut Code, element: ElementSize, destination: u8, scratch: u8, @@ -217,17 +209,20 @@ pub(crate) fn expand_predicate_mask( xmm(scratch); assert_ne!(destination, scratch); if element == ElementSize::Quadword { - code.extend(AND_EAX_IMM8); - code.push(FIRST_PREDICATE_BIT); - code.extend(NEG_EAX); - code.extend(MOVD_XMM_EAX); - code.push(MODRM_REGISTER | (destination << REGISTER_SHIFT)); - Host::ShuffleDword.register(code, destination, destination, target); - code.push(REPEAT_LOW_DWORD); + let mut asm = code.asm(); + asm.alu_imm8(Alu::And, Size::Dword, Rax, FIRST_PREDICATE_BIT as i8); + asm.unary(Unary::Neg, Size::Dword, Rax); + code.asm().movd_to_xmm(destination, Rax); + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(destination), + REPEAT_LOW_DWORD, + target, + ); return; } - code.extend(MOVD_XMM_EAX); - code.push(MODRM_REGISTER | (destination << REGISTER_SHIFT)); + code.asm().movd_to_xmm(destination, Rax); Host::UnpackLowByte.register(code, destination, destination, target); Host::UnpackLowWord.register(code, destination, destination, target); if element == ElementSize::Doubleword { @@ -235,16 +230,24 @@ pub(crate) fn expand_predicate_mask( // 8-byte element; arithmetic shifts replicate exactly that bit. ShiftOpcode::LeftDword.emit(code, destination, DWORD_SIGN_BIT); ShiftOpcode::ArithmeticDword.emit(code, destination, DWORD_SIGN_BIT); - Host::ShuffleDword.register(code, destination, destination, target); - code.push(REPEAT_LOW_TWO_DWORDS); + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(destination), + REPEAT_LOW_TWO_DWORDS, + target, + ); return; } - Host::ShuffleDword.register(code, destination, destination, target); - code.push(REPEAT_LOW_TWO_DWORDS); - code.extend(MOVABS_RCX_IMM64); - code.extend(predicate_bit_pattern(element).to_le_bytes()); - code.extend(MOVQ_XMM_RCX); - code.push(MODRM_REGISTER | (scratch << REGISTER_SHIFT) | RCX_REGISTER); + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(destination), + REPEAT_LOW_TWO_DWORDS, + target, + ); + code.asm().mov_imm64(Rcx, predicate_bit_pattern(element)); + code.asm().movq_to_xmm(scratch, Rcx); Host::UnpackLowQword.register(code, scratch, scratch, target); Host::And.register(code, destination, scratch, target); Host::EqualByte.register(code, destination, scratch, target); @@ -260,7 +263,7 @@ fn predicate_chunk(chunk: usize, length: VectorLength) -> (usize, usize) { /// Read an 8-byte packed-P chunk into RAX, zero-extending a final 2/4-byte chunk. /// The chunk index addresses packed bytes, not Z chunks. Clobbers RDX only. pub(crate) fn read_predicate_chunk( - code: &mut Vec, + code: &mut Code, predicate: u8, chunk: usize, length: VectorLength, diff --git a/crates/stela-compiler/src/x86_64/scalable/lut.rs b/crates/stela-compiler/src/x86_64/scalable/lut.rs index 7f43b47b47..9b4d1e5ff2 100644 --- a/crates/stela-compiler/src/x86_64/scalable/lut.rs +++ b/crates/stela-compiler/src/x86_64/scalable/lut.rs @@ -1,14 +1,11 @@ //! Constant-time packed-index table lookup shared by the LUTI forms. +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Code, Rm}; use crate::{ TargetCpu, aarch64::scalable::{ElementSize, VECTOR_CHUNK_BYTES}, x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}, }; -use alloc::vec::Vec; -const MOV_EAX: u8 = 0xb8; -const MOVD: &[u8] = &[0x66, 0x0f, 0x6e]; -const REGISTER: u8 = 0xc0; -const XMM_SHIFT: u8 = 3; const REPEAT_LOW: u8 = 0; const LOW_TABLE: u8 = 4; const HIGH_TABLE: u8 = 5; @@ -20,15 +17,13 @@ const HALFWORD_OFFSETS: u32 = 0x0100_0100; const SHUFFLE_DISABLE: u32 = 0x8080_8080; const TABLE_BANK_TO_DISABLE_SHIFT: u8 = 3; -fn splat(code: &mut Vec, xmm: u8, value: u32, target: TargetCpu) { - code.push(MOV_EAX); - code.extend(value.to_le_bytes()); - code.extend(MOVD); - code.push(REGISTER | (xmm << XMM_SHIFT)); - Host::ShuffleDword.register(code, xmm, xmm, target); - code.push(REPEAT_LOW); +fn splat(code: &mut Code, xmm: u8, value: u32, target: TargetCpu) { + code.asm().mov_imm32(Rax, value); + code.asm().movd_to_xmm(xmm, Rax); + code.asm() + .simd_imm(Host::ShuffleDword, xmm, Rm::Xmm(xmm), REPEAT_LOW, target); } -fn expand(code: &mut Vec, index_bits: u8, target: TargetCpu) { +fn expand(code: &mut Code, index_bits: u8, target: TargetCpu) { splat( code, MASK, @@ -57,7 +52,7 @@ fn expand(code: &mut Vec, index_bits: u8, target: TargetCpu) { Host::UnpackLowWord.register(code, 0, 2, target); } } -fn boolean(code: &mut Vec, element: ElementSize, index_bits: u8, target: TargetCpu) { +fn boolean(code: &mut Code, element: ElementSize, index_bits: u8, target: TargetCpu) { if element == ElementSize::Halfword { Host::UnpackLowByte.register(code, 0, 0, target); } @@ -82,15 +77,15 @@ fn boolean(code: &mut Vec, element: ElementSize, index_bits: u8, target: Tar if element == ElementSize::Byte { Host::UnpackLowByte.register(code, 2, 2, target); } - Host::ShuffleLowWord.register(code, 2, 2, target); - code.push(REPEAT_LOW); - Host::ShuffleDword.register(code, 2, 2, target); - code.push(REPEAT_LOW); + code.asm() + .simd_imm(Host::ShuffleLowWord, 2, Rm::Xmm(2), REPEAT_LOW, target); + code.asm() + .simd_imm(Host::ShuffleDword, 2, Rm::Xmm(2), REPEAT_LOW, target); Host::And.register(code, 1, 2, target); Host::Or.register(code, OUTPUT, 1, target); } } -fn shuffle(code: &mut Vec, element: ElementSize, index_bits: u8, target: TargetCpu) { +fn shuffle(code: &mut Code, element: ElementSize, index_bits: u8, target: TargetCpu) { if element == ElementSize::Halfword { Host::UnpackLowByte.register(code, 0, 0, target); Shift::LeftWord.emit(code, 0, 1); @@ -118,12 +113,7 @@ fn shuffle(code: &mut Vec, element: ElementSize, index_bits: u8, target: Tar /// XMM0 holds packed indices; XMM4/5 hold the low/high 16-byte table. /// Returns XMM6, preserves XMM4/5, clobbers XMM0..3,7 and RAX. /// Four-bit halfword lookup requires both table chunks. No indexed memory. -pub(crate) fn emit_chunk( - code: &mut Vec, - index_bits: u8, - element: ElementSize, - target: TargetCpu, -) { +pub(crate) fn emit_chunk(code: &mut Code, index_bits: u8, element: ElementSize, target: TargetCpu) { assert!( matches!(index_bits, 2 | 4) && matches!(element, ElementSize::Byte | ElementSize::Halfword) ); diff --git a/crates/stela-compiler/src/x86_64/scalable/numerical.rs b/crates/stela-compiler/src/x86_64/scalable/numerical.rs index 9dd4b2a3c4..c43981baed 100644 --- a/crates/stela-compiler/src/x86_64/scalable/numerical.rs +++ b/crates/stela-compiler/src/x86_64/scalable/numerical.rs @@ -4,6 +4,8 @@ //! stay readable until `finish`, which commits every staged output byte at once. //! No CALL or mode change may occur while the frame is live. RDI, R15 and //! callee-saved GPRs survive; RAX/RCX/RDX, flags and the chosen XMM are clobbered. +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rdi, Rsp}; +use crate::x86_64::asm::{Alu, Code, Mem, Size}; use super::{ DWORD_BYTES, HALFWORD_BYTES, Host, QWORD_BYTES, clear_z_upper, store_z_chunk, @@ -32,29 +34,9 @@ const MXCSR_STATUS_MASK: u32 = 0x3f; const PACKED_P_CHUNK_BYTES: usize = core::mem::size_of::(); const PREDICATE_BITS16_BYTES: usize = core::mem::size_of::(); const REL32_BYTES: usize = core::mem::size_of::(); -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; -const STMXCSR_RSP_DISP32: &[u8] = &[0x0f, 0xae, 0x9c, 0x24]; -const LDMXCSR_RSP_DISP32: &[u8] = &[0x0f, 0xae, 0x94, 0x24]; -const MOV_RSP_DISP32_IMM32: &[u8] = &[0xc7, 0x84, 0x24]; -const MOV_RSP_DISP32_EAX: &[u8] = &[0x89, 0x84, 0x24]; -const MOV_RSP_DISP32_AX: &[u8] = &[0x66, 0x89, 0x84, 0x24]; -const MOV_EAX_RSP_DISP32: &[u8] = &[0x8b, 0x84, 0x24]; -const MOV_ECX_RSP_DISP32: &[u8] = &[0x8b, 0x8c, 0x24]; -const MOVZX_EAX_WORD_RSP_DISP32: &[u8] = &[0x0f, 0xb7, 0x84, 0x24]; -const MOV_RAX_RSP_DISP32: &[u8] = &[0x48, 0x8b, 0x84, 0x24]; -const OR_RSP_DISP32_EAX: &[u8] = &[0x09, 0x84, 0x24]; -const AND_EAX_IMM32: &[u8] = &[0x25]; -const OR_EAX_IMM32: &[u8] = &[0x0d]; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const OR_STATE_FPSR_EAX: &[u8] = &[0x09, 0x87]; -const JMP_REL32: u8 = 0xe9; const CONDITIONAL_ESCAPE: u8 = 0x0f; const FIRST_CONDITIONAL_REL32: u8 = 0x80; const LAST_CONDITIONAL_REL32: u8 = 0x8f; -const MODRM_STACK_DISP32: u8 = 0x84; -const XMM_REGISTER_SHIFT: u8 = 3; -const SIB_STACK: u8 = 0x24; const COMMIT_XMM: u8 = 0; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -113,25 +95,20 @@ pub(crate) struct Frame { guards_start: usize, } -fn memory(code: &mut Vec, opcode: &[u8], offset: u32) { - code.extend(opcode); - code.extend(offset.to_le_bytes()); +/// `[rsp + offset]` with a 32-bit displacement field. +fn stack(offset: u32) -> Mem { + Mem::base_disp32(Rsp, offset as i32) } -fn stack_vector(code: &mut Vec, opcode: Host, register: u8, offset: u32, target: TargetCpu) { +fn stack_vector(code: &mut Code, opcode: Host, register: u8, offset: u32, target: TargetCpu) { xmm(register); - opcode.append(code, target); - code.extend([ - MODRM_STACK_DISP32 | (register << XMM_REGISTER_SHIFT), - SIB_STACK, - ]); - code.extend(offset.to_le_bytes()); + code.asm().simd(opcode, register, stack(offset), target); } /// Validate the full constant layout before emitting or reserving any bytes. /// A source may alias a destination; two output slots may not overlap. pub(crate) fn begin( - code: &mut Vec, + code: &mut Code, length: VectorLength, outputs: &[Output], environment: Environment, @@ -166,12 +143,11 @@ pub(crate) fn begin( .collect(); let bytes = (offset + CALL_ALIGNMENT_PAD) as u32; assert!(bytes as usize <= MAX_FRAME_BYTES); - code.extend(SUB_RSP_IMM32); - code.extend(bytes.to_le_bytes()); + let mut asm = code.asm(); + asm.alu_imm32(Alu::Sub, Size::Qword, Rsp, bytes as i32); if environment == Environment::PrivateMxcsr { - memory(code, STMXCSR_RSP_DISP32, SAVED_MXCSR); - memory(code, MOV_RSP_DISP32_IMM32, PENDING_GUEST_FPSR); - code.extend(0u32.to_le_bytes()); + asm.stmxcsr(stack(SAVED_MXCSR)); + asm.mov_rm_imm32(Size::Dword, stack(PENDING_GUEST_FPSR), 0); } Ok(Frame { length, @@ -184,7 +160,7 @@ pub(crate) fn begin( /// Stage one complete 16-byte Z/V segment; other XMMs and guest banks survive. pub(crate) fn stage_vector_chunk( - code: &mut Vec, + code: &mut Code, frame: &Frame, output: usize, chunk: usize, @@ -206,7 +182,7 @@ pub(crate) fn stage_vector_chunk( /// Stage exactly two packed P bytes from low16 RAX, one per 16-byte Z chunk. /// The caller has already cleared inactive and nonleading predicate bits. pub(crate) fn stage_predicate_bits16( - code: &mut Vec, + code: &mut Code, frame: &Frame, output: usize, z_chunk: usize, @@ -214,10 +190,10 @@ pub(crate) fn stage_predicate_bits16( let slot = &frame.slots[output]; assert!(matches!(slot.output, Output::Predicate(_))); assert!(z_chunk < frame.length.chunks()); - memory( - code, - MOV_RSP_DISP32_AX, - slot.offset + (z_chunk * PREDICATE_BITS16_BYTES) as u32, + code.asm().mov_store( + Size::Word, + stack(slot.offset + (z_chunk * PREDICATE_BITS16_BYTES) as u32), + Rax, ); } @@ -227,46 +203,46 @@ fn private(frame: &Frame) { /// Install only EAX rounding bits, masked exceptions, fresh status and no flush. /// Effective guest control interpretation remains the instruction family's job. -pub(crate) fn install_mxcsr(code: &mut Vec, frame: &Frame) { +pub(crate) fn install_mxcsr(code: &mut Code, frame: &Frame) { private(frame); - code.extend(AND_EAX_IMM32); - code.extend(MXCSR_ROUNDING_MASK.to_le_bytes()); - code.extend(OR_EAX_IMM32); - code.extend(MXCSR_EXCEPTION_MASKS.to_le_bytes()); - memory(code, MOV_RSP_DISP32_EAX, PRIVATE_MXCSR); - memory(code, LDMXCSR_RSP_DISP32, PRIVATE_MXCSR); + let mut asm = code.asm(); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_ROUNDING_MASK as i32); + asm.alu_accumulator_imm32(Alu::Or, Size::Dword, MXCSR_EXCEPTION_MASKS as i32); + asm.mov_store(Size::Dword, stack(PRIVATE_MXCSR), Rax); + asm.ldmxcsr(stack(PRIVATE_MXCSR)); } /// Return the six raw host status bits in ECX. This is not an ARM FPSR mapping. -pub(crate) fn capture_status(code: &mut Vec, frame: &Frame) { +pub(crate) fn capture_status(code: &mut Code, frame: &Frame) { private(frame); - memory(code, STMXCSR_RSP_DISP32, CAPTURED_HOST_STATUS); - memory(code, MOV_ECX_RSP_DISP32, CAPTURED_HOST_STATUS); - code.extend(AND_ECX_IMM32); - code.extend(MXCSR_STATUS_MASK.to_le_bytes()); + let mut asm = code.asm(); + asm.stmxcsr(stack(CAPTURED_HOST_STATUS)); + asm.mov_load(Size::Dword, Rcx, stack(CAPTURED_HOST_STATUS)); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, MXCSR_STATUS_MASK as i32); } /// Clear host stage status after installation, retaining approved pending FPSR. -pub(crate) fn clear_status(code: &mut Vec, frame: &Frame) { +pub(crate) fn clear_status(code: &mut Code, frame: &Frame) { private(frame); - memory(code, LDMXCSR_RSP_DISP32, PRIVATE_MXCSR); + code.asm().ldmxcsr(stack(PRIVATE_MXCSR)); } /// Accumulate only family-approved guest FPSR bits from EAX, without committing. -pub(crate) fn add_fpsr(code: &mut Vec, frame: &Frame) { +pub(crate) fn add_fpsr(code: &mut Code, frame: &Frame) { private(frame); - memory(code, OR_RSP_DISP32_EAX, PENDING_GUEST_FPSR); + code.asm() + .alu(Alu::Or, Size::Dword, stack(PENDING_GUEST_FPSR), Rax); } -fn restore(code: &mut Vec, frame: &Frame) { +fn restore(code: &mut Code, frame: &Frame) { if frame.environment == Environment::PrivateMxcsr { - memory(code, LDMXCSR_RSP_DISP32, SAVED_MXCSR); + code.asm().ldmxcsr(stack(SAVED_MXCSR)); } } -fn release(code: &mut Vec, frame: &Frame) { - code.extend(ADD_RSP_IMM32); - code.extend(frame.bytes.to_le_bytes()); +fn release(code: &mut Code, frame: &Frame) { + code.asm() + .alu_imm32(Alu::Add, Size::Qword, Rsp, frame.bytes as i32); } fn patch(code: &mut [u8], displacement: usize, destination: usize) { @@ -280,7 +256,7 @@ fn patch(code: &mut [u8], displacement: usize, destination: usize) { /// Failure restores MXCSR/RSP before returning the still-unexecuted exact PC. /// Success clobbers XMM0 and RAX/RDX, and private mode ORs approved FPSR once. pub(crate) fn finish( - code: &mut Vec, + code: &mut Code, frame: &Frame, failures: &[usize], pc: GuestAddress, @@ -314,13 +290,14 @@ pub(crate) fn finish( Output::Predicate(register) => { for offset in (0..frame.length.predicate_bytes()).step_by(PACKED_P_CHUNK_BYTES) { let bytes = (frame.length.predicate_bytes() - offset).min(PACKED_P_CHUNK_BYTES); - let opcode = match bytes { - HALFWORD_BYTES => MOVZX_EAX_WORD_RSP_DISP32, - DWORD_BYTES => MOV_EAX_RSP_DISP32, - QWORD_BYTES => MOV_RAX_RSP_DISP32, + let source = stack(slot.offset + offset as u32); + let mut asm = code.asm(); + match bytes { + HALFWORD_BYTES => asm.movzx(Size::Dword, Rax, Size::Word, source), + DWORD_BYTES => asm.mov_load(Size::Dword, Rax, source), + QWORD_BYTES => asm.mov_load(Size::Qword, Rax, source), _ => unreachable!("validated predicate width"), - }; - memory(code, opcode, slot.offset + offset as u32); + } write_predicate_chunk( code, register, @@ -332,20 +309,16 @@ pub(crate) fn finish( } } if frame.environment == Environment::PrivateMxcsr { - memory(code, MOV_EAX_RSP_DISP32, PENDING_GUEST_FPSR); - memory( - code, - OR_STATE_FPSR_EAX, - core::mem::offset_of!(GuestState, fpsr) as u32, - ); + let fpsr = core::mem::offset_of!(GuestState, fpsr) as i32; + let mut asm = code.asm(); + asm.mov_load(Size::Dword, Rax, stack(PENDING_GUEST_FPSR)); + asm.alu(Alu::Or, Size::Dword, Mem::base_disp32(Rdi, fpsr), Rax); } release(code, frame); if failures.is_empty() { return; } - code.push(JMP_REL32); - let success = code.len(); - code.extend([0; REL32_BYTES]); + let success = code.asm().jmp(); let abort = code.len(); restore(code, frame); release(code, frame); @@ -353,15 +326,13 @@ pub(crate) fn finish( for &displacement in failures { patch(code, displacement, abort); } - let end = code.len(); - patch(code, success, end); + code.asm().bind(success); } #[cfg(test)] mod tests { use super::*; use alloc::vec; - use alloc::vec::Vec; #[test] fn invalid_layout_does_not_emit() { @@ -375,7 +346,7 @@ mod tests { vec![Output::Predicate(1); 2], vec![Output::Z(0); 5], ] { - let mut code = vec![0xaa]; + let mut code = Code::from(vec![0xaa]); assert!(begin(&mut code, length, &outputs, Environment::Exact).is_err()); assert_eq!(code, [0xaa]); } @@ -392,7 +363,7 @@ mod tests { vec![Output::Z(0)], vec![Output::Z(0), Output::Z(1), Output::Z(2), Output::Z(3)], ] { - let frame = begin(&mut Vec::new(), length, &outputs, environment).unwrap(); + let frame = begin(&mut Code::new(), length, &outputs, environment).unwrap(); assert_eq!( frame.bytes as usize % VECTOR_CHUNK_BYTES, CALL_ALIGNMENT_PAD diff --git a/crates/stela-compiler/src/x86_64/scalable/predicate.rs b/crates/stela-compiler/src/x86_64/scalable/predicate.rs index 1b04290c1f..cca5ac5a2c 100644 --- a/crates/stela-compiler/src/x86_64/scalable/predicate.rs +++ b/crates/stela-compiler/src/x86_64/scalable/predicate.rs @@ -1,31 +1,28 @@ //! Packed predicate writes and chunk access. +use crate::x86_64::asm::Gpr::{Rax, Rdx}; +use crate::x86_64::asm::{Alu, Code, Mem, Size}; use super::{ DWORD_BYTES, HALFWORD_BYTES, PREDICATE_CHUNK_BYTES, QWORD_BYTES, predicate_chunk, predicate_offset, storage_pointer, }; use crate::{aarch64::scalable::VectorLength, context::SCALABLE_PREDICATES_OFFSET}; -use alloc::vec::Vec; -const MOV_RDX_DISP32_AX: &[u8] = &[0x66, 0x89, 0x82]; -const MOV_RDX_DISP32_EAX: &[u8] = &[0x89, 0x82]; -const MOV_RDX_DISP32_RAX: &[u8] = &[0x48, 0x89, 0x82]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; - -pub(super) fn write_predicate_at(code: &mut Vec, displacement: u32, bytes: usize) { - code.extend(match bytes { - HALFWORD_BYTES => MOV_RDX_DISP32_AX, - DWORD_BYTES => MOV_RDX_DISP32_EAX, - QWORD_BYTES => MOV_RDX_DISP32_RAX, +pub(super) fn write_predicate_at(code: &mut Code, displacement: u32, bytes: usize) { + let size = match bytes { + HALFWORD_BYTES => Size::Word, + DWORD_BYTES => Size::Dword, + QWORD_BYTES => Size::Qword, _ => unreachable!("validated streaming length has 2/4/8-byte predicate chunks"), - }); - code.extend(displacement.to_le_bytes()); + }; + code.asm() + .mov_store(size, Mem::base_disp32(Rdx, displacement as i32), Rax); } /// Write low RAX bytes to one packed-P chunk without touching adjacent P slots. /// Final 2/4-byte chunks use that exact width. RAX is preserved; RDX is scratch. pub(crate) fn write_predicate_chunk( - code: &mut Vec, + code: &mut Code, predicate: u8, chunk: usize, length: VectorLength, @@ -36,9 +33,9 @@ pub(crate) fn write_predicate_chunk( } /// Clear a complete packed P register. Clobbers RAX/RDX; all XMMs survive. -pub(crate) fn zero_predicate(code: &mut Vec, predicate: u8, length: VectorLength) { +pub(crate) fn zero_predicate(code: &mut Code, predicate: u8, length: VectorLength) { storage_pointer(code, SCALABLE_PREDICATES_OFFSET); - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); for offset in (0..length.predicate_bytes()).step_by(PREDICATE_CHUNK_BYTES) { let bytes = (length.predicate_bytes() - offset).min(PREDICATE_CHUNK_BYTES); write_predicate_at(code, predicate_offset(predicate, offset, length), bytes); diff --git a/crates/stela-compiler/src/x86_64/scalable/routing.rs b/crates/stela-compiler/src/x86_64/scalable/routing.rs index ba4428aa11..ed0c4e2fd0 100644 --- a/crates/stela-compiler/src/x86_64/scalable/routing.rs +++ b/crates/stela-compiler/src/x86_64/scalable/routing.rs @@ -1,16 +1,16 @@ //! SSE2 interleave and deinterleave networks for whole 128-bit chunks. +use crate::x86_64::asm::{Code, Mem, Rm}; use crate::TargetCpu; use crate::aarch64::scalable::ElementSize; use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; -use alloc::vec::Vec; const SECOND_EVEN_XMM: u8 = 6; const SECOND_ODD_XMM: u8 = 7; const EVEN_DWORDS: u8 = 0x88; const ODD_DWORDS: u8 = 0xdd; -fn copy(code: &mut Vec, destination: u8, source: u8, target: TargetCpu) { +fn copy(code: &mut Code, destination: u8, source: u8, target: TargetCpu) { if destination != source { Host::MoveAligned.register(code, destination, source, target); } @@ -19,7 +19,7 @@ fn copy(code: &mut Vec, destination: u8, source: u8, target: TargetCpu) { /// Preserve both inputs, producing their concatenated even/odd element streams. /// Outputs differ from inputs and XMM6/7. XMM6/7 are clobbered. pub(crate) fn split( - code: &mut Vec, + code: &mut Code, first: u8, second: u8, even: u8, @@ -41,8 +41,13 @@ pub(crate) fn split( (odd, first, ODD_DWORDS), (SECOND_ODD_XMM, second, ODD_DWORDS), ] { - Host::ShuffleDword.register(code, destination, source, target); - code.push(control); + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(source), + control, + target, + ); } Host::UnpackLowQword.register(code, even, SECOND_EVEN_XMM, target); Host::UnpackLowQword.register(code, odd, SECOND_ODD_XMM, target); @@ -106,7 +111,7 @@ fn unpack(element: ElementSize, high: bool) -> Host { /// Interleave two chunks into low/high outputs. Outputs differ from each other /// and from second. First may be an output; no GPRs or extra XMMs are clobbered. pub(crate) fn merge( - code: &mut Vec, + code: &mut Code, first: u8, second: u8, low: u8, @@ -133,7 +138,7 @@ const ODD_MASK_XMM: u8 = 7; /// into the low qword and zero the upper qword. Byte/Halfword lane masks belong /// to the caller; this kernel does not infer element sizes or access state. pub(crate) fn split_destructive( - code: &mut Vec, + code: &mut Code, first: u8, second: u8, even: u8, @@ -156,10 +161,7 @@ pub(crate) fn split_destructive( Host::UnpackLowQword.register(code, odd, second, target); } -const MODRM_RIP: u8 = 0x05; -const MODRM_REGISTER_SHIFT: u8 = 3; const SHUFFLE_ZERO: u8 = 0x80; -const JMP_REL32: u8 = 0xe9; const REL32_BYTES: usize = core::mem::size_of::(); const JUMP_BYTES: usize = core::mem::size_of::() + REL32_BYTES; const CHUNK_BYTES: usize = crate::aarch64::scalable::VECTOR_CHUNK_BYTES; @@ -168,29 +170,34 @@ const HALF_CHUNK_BYTES: usize = CHUNK_BYTES / 2; /// Prepare even/odd Byte or Halfword routing masks in XMM6/7. Embedded masks /// use MOVDQU loads, avoiding the alignment requirement of legacy PSHUFB memory. /// Preserves XMM0..5 and every GPR. The caller owns checked SSSE3 selection. -pub(crate) fn prepare_split_masks(code: &mut Vec, element: ElementSize, target: TargetCpu) { +pub(crate) fn prepare_split_masks(code: &mut Code, element: ElementSize, target: TargetCpu) { assert!(target.supports(TargetCpu::Ssse3)); assert!(matches!(element, ElementSize::Byte | ElementSize::Halfword)); let load_bytes = Host::LoadUnaligned.encoding().len() + core::mem::size_of::() + REL32_BYTES; + let mut asm = code.asm(); for (register, displacement) in [ (EVEN_MASK_XMM, load_bytes + JUMP_BYTES), (ODD_MASK_XMM, JUMP_BYTES + CHUNK_BYTES), ] { - Host::LoadUnaligned.append(code, target); - code.push(MODRM_RIP | (register << MODRM_REGISTER_SHIFT)); - code.extend((displacement as i32).to_le_bytes()); + asm.simd( + Host::LoadUnaligned, + register, + Mem::rip(displacement as i32), + target, + ); } - code.push(JMP_REL32); - code.extend((2 * CHUNK_BYTES as i32).to_le_bytes()); + let over_masks = asm.jmp(); for parity in 0..2 { - for byte in 0..CHUNK_BYTES { - code.push(if byte < HALF_CHUNK_BYTES { + let mask: [u8; CHUNK_BYTES] = core::array::from_fn(|byte| { + if byte < HALF_CHUNK_BYTES { ((byte / element.bytes() * 2 + parity) * element.bytes() + byte % element.bytes()) as u8 } else { SHUFFLE_ZERO - }); - } + } + }); + asm.data(&mask); } + asm.bind(over_masks); } diff --git a/crates/stela-compiler/src/x86_64/scalable/legacy.rs b/crates/stela-compiler/src/x86_64/scalable/z_upper.rs similarity index 85% rename from crates/stela-compiler/src/x86_64/scalable/legacy.rs rename to crates/stela-compiler/src/x86_64/scalable/z_upper.rs index 201127b424..8c638d38b8 100644 --- a/crates/stela-compiler/src/x86_64/scalable/legacy.rs +++ b/crates/stela-compiler/src/x86_64/scalable/z_upper.rs @@ -1,18 +1,19 @@ //! Clearing upper Z bytes after AdvSIMD writes to V registers. +use crate::x86_64::asm::Code; +use crate::x86_64::asm::Gpr::Rdx; -use super::{ADDRESS_RDX, Host, storage_pointer, upper_offset, vector_memory, xmm}; +use super::{Host, storage_pointer, upper_offset, vector_memory, xmm}; use crate::{ TargetCpu, aarch64::scalable::{VectorLength, is_z_register}, context::SCALABLE_Z_UPPER_OFFSET, }; -use alloc::vec::Vec; /// Clear the upper Z bytes after an AdvSIMD write to V. The caller decides /// which destinations need it. Clobbers the chosen zero XMM and RDX; the low /// 128 bits are kept. pub(crate) fn clear_z_upper( - code: &mut Vec, + code: &mut Code, register: u8, zero: u8, length: VectorLength, @@ -30,7 +31,7 @@ pub(crate) fn clear_z_upper( code, Host::StoreUnaligned, zero, - ADDRESS_RDX, + Rdx, upper_offset(register, chunk, length), target, ); @@ -40,11 +41,10 @@ pub(crate) fn clear_z_upper( #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; #[test] fn minimum_length_upper_clear_has_no_native_effects() { - let mut code = Vec::new(); + let mut code = Code::new(); clear_z_upper( &mut code, 31, diff --git a/crates/stela-compiler/src/x86_64/scalable_matrix.rs b/crates/stela-compiler/src/x86_64/scalable_matrix.rs index 0303086743..a8b974c51e 100644 --- a/crates/stela-compiler/src/x86_64/scalable_matrix.rs +++ b/crates/stela-compiler/src/x86_64/scalable_matrix.rs @@ -1,59 +1,54 @@ //! ZA storage access for the extended native ABI. R15 holds the //! ExecutionContext; callers handle slice selection and bounds. +use crate::x86_64::asm::Gpr::{R8, R15}; +use crate::x86_64::asm::{Code, Mem, Size}; use super::isa::SimdOpcode as Host; use crate::{ TargetCpu, context::{EXECUTION_CONTEXT_SCALABLE_OFFSET, SCALABLE_ZA_OFFSET}, }; -use alloc::vec::Vec; const XMM_REGISTER_COUNT: u8 = 8; -const REX_R8_BASE: u8 = 0x41; -const MODRM_DISP32_R8: u8 = 0x80; -const REGISTER_SHIFT: u8 = 3; -const MOV_R8_CONTEXT_DISP8: &[u8] = &[0x4d, 0x8b, 0x47]; -const MOV_R8_R8_DISP8: &[u8] = &[0x4d, 0x8b, 0x40]; /// Load the ZA bank base into R8. Every other GPR/XMM and host flag survives. /// The runtime must have validated a live scalable view and ZA allocation. -pub(crate) fn load_za_pointer_r8(code: &mut Vec) { +pub(crate) fn load_za_pointer_r8(code: &mut Code) { // Versioned pointer fields fit a positive signed disp8. debug_assert!(EXECUTION_CONTEXT_SCALABLE_OFFSET <= i8::MAX as u32); debug_assert!(SCALABLE_ZA_OFFSET <= i8::MAX as u32); - code.extend(MOV_R8_CONTEXT_DISP8); - code.push(EXECUTION_CONTEXT_SCALABLE_OFFSET as u8); - code.extend(MOV_R8_R8_DISP8); - code.push(SCALABLE_ZA_OFFSET as u8); + let mut asm = code.asm(); + asm.mov_load( + Size::Qword, + R8, + Mem::base_disp8(R15, EXECUTION_CONTEXT_SCALABLE_OFFSET as i8), + ); + asm.mov_load( + Size::Qword, + R8, + Mem::base_disp8(R8, SCALABLE_ZA_OFFSET as i8), + ); } -fn chunk_memory( - code: &mut Vec, - opcode: Host, - register: u8, - displacement: u32, - target: TargetCpu, -) { +fn chunk_memory(code: &mut Code, opcode: Host, register: u8, displacement: u32, target: TargetCpu) { assert!(register < XMM_REGISTER_COUNT, "ZA helper requires XMM0..7"); assert!( displacement <= i32::MAX as u32, "ZA displacement must be positive disp32" ); - assert!(target.supports(opcode.requires())); - // MOVDQU's mandatory F3 prefix precedes REX.B for the R8 memory base. - let encoding = opcode.encoding(); - code.push(encoding[0]); - code.push(REX_R8_BASE); - code.extend(&encoding[1..]); - code.push(MODRM_DISP32_R8 | (register << REGISTER_SHIFT)); - code.extend(displacement.to_le_bytes()); + code.asm().simd( + opcode, + register, + Mem::base_disp32(R8, displacement as i32), + target, + ); } /// Read exactly 16 unaligned bytes at R8+displacement into the chosen XMM. /// Preserves R8, every other GPR/XMM and host flags. The caller may first add a /// validated dynamic row offset to R8; displacement is relative to that base. pub(crate) fn load_za_chunk_at_r8( - code: &mut Vec, + code: &mut Code, destination: u8, displacement: u32, target: TargetCpu, @@ -65,7 +60,7 @@ pub(crate) fn load_za_chunk_at_r8( /// Preserves every GPR/XMM and host flags. The caller stages aliased sources /// before invoking stores when an instruction requires simultaneous results. pub(crate) fn store_za_chunk_at_r8( - code: &mut Vec, + code: &mut Code, source: u8, displacement: u32, target: TargetCpu, @@ -76,11 +71,10 @@ pub(crate) fn store_za_chunk_at_r8( #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; #[test] fn pointer_chase_uses_the_shared_context_contract() { - let mut code = Vec::new(); + let mut code = Code::new(); load_za_pointer_r8(&mut code); assert_eq!(code, [0x4d, 0x8b, 0x47, 16, 0x4d, 0x8b, 0x40, 56]); } @@ -88,11 +82,11 @@ mod tests { #[test] fn rex_base_follows_mandatory_simd_prefix() { for register in 0..XMM_REGISTER_COUNT { - let mut load = Vec::new(); + let mut load = Code::new(); load_za_chunk_at_r8(&mut load, register, 0x1234, TargetCpu::Baseline); assert_eq!(load[..5], [0xf3, 0x41, 0x0f, 0x6f, 0x80 | register << 3]); assert_eq!(load[5..], 0x1234u32.to_le_bytes()); - let mut store = Vec::new(); + let mut store = Code::new(); store_za_chunk_at_r8(&mut store, register, 0x5678, TargetCpu::Baseline); assert_eq!(store[..5], [0xf3, 0x41, 0x0f, 0x7f, 0x80 | register << 3]); assert_eq!(store[5..], 0x5678u32.to_le_bytes()); diff --git a/crates/stela-compiler/src/x86_64/shared_memory.rs b/crates/stela-compiler/src/x86_64/shared_memory.rs index 94c7391060..b1db62fdf5 100644 --- a/crates/stela-compiler/src/x86_64/shared_memory.rs +++ b/crates/stela-compiler/src/x86_64/shared_memory.rs @@ -1,6 +1,8 @@ //! Typed checked LSE, acquire/release and DMB requests. No guest RAM pointer //! is embedded in native code; the shared writer/monitor owner performs effects. use super::{load, memory_context as memory, store}; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Rm, Size}; +use crate::x86_64::isa::SimdOpcode; use crate::{ CompileError, aarch64::{AddressMode, Operation, Register, Width, atomic, ordered}, @@ -11,30 +13,14 @@ use crate::{ profile_requirements, }, }; -use alloc::vec::Vec; const DATA_OFFSET: u32 = MEMORY_REQUEST_BYTES as u32; const STACK_ALIGNMENT: u32 = 16; -const SUB_RSP: &[u8] = &[0x48, 0x83, 0xec]; -const ADD_RSP: &[u8] = &[0x48, 0x83, 0xc4]; -const ZERO_EAX: &[u8] = &[0x31, 0xc0]; -const ZERO_XMM0: &[u8] = &[0x66, 0x0f, 0xef, 0xc0]; -const STORE_VECTOR: &[u8] = &[0xf3, 0x0f, 0x7f, 0x44, 0x24]; -const STORE_FIELD: &[u8] = &[0xc7, 0x44, 0x24]; -const STORE_BYTE: &[u8] = &[0x88, 0x44, 0x24]; -const STORE_HALF: &[u8] = &[0x66, 0x89, 0x44, 0x24]; -const STORE_WORD: &[u8] = &[0x89, 0x44, 0x24]; -const STORE_DOUBLE: &[u8] = &[0x48, 0x89, 0x44, 0x24]; -const LOAD_BYTE: &[u8] = &[0x0f, 0xb6, 0x44, 0x24]; -const LOAD_HALF: &[u8] = &[0x0f, 0xb7, 0x44, 0x24]; -const LOAD_WORD: &[u8] = &[0x8b, 0x44, 0x24]; -const LOAD_DOUBLE: &[u8] = &[0x48, 0x8b, 0x44, 0x24]; -const SIGN_BYTE_TO_X: &[u8] = &[0x48, 0x0f, 0xbe, 0x44, 0x24]; -const SIGN_HALF_TO_X: &[u8] = &[0x48, 0x0f, 0xbf, 0x44, 0x24]; -const SIGN_WORD_TO_X: &[u8] = &[0x48, 0x63, 0x44, 0x24]; -const SIGN_BYTE_TO_W: &[u8] = &[0x0f, 0xbe, 0x44, 0x24]; -const SIGN_HALF_TO_W: &[u8] = &[0x0f, 0xbf, 0x44, 0x24]; +/// The scratch payload field at `offset`. +fn payload(offset: u32) -> Mem { + Mem::base_disp8(Gpr::Rsp, (DATA_OFFSET + offset) as i8) +} #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Operand { @@ -248,15 +234,15 @@ impl CheckedOperand { ..MemoryRequirements::default() } } - pub(crate) fn emit(&self, code: &mut Vec, pc: u64) { + pub(crate) fn emit(&self, code: &mut Code, pc: u64) { let data_bytes = match self.operand { Operand::Atomic(_) => wire_atomic::DATA_BYTES, Operand::Ordered(_) => wire_ordered::DATA_BYTES, } as u32; let scratch = (DATA_OFFSET + data_bytes).div_ceil(STACK_ALIGNMENT) * STACK_ALIGNMENT; assert!(scratch <= i8::MAX as u32); - code.extend(SUB_RSP); - code.push(scratch as u8); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Gpr::Rsp, scratch as i8); memory::begin(code); let sp_failure = if self.profile.sp_requirement() == SpAlignmentRequirement::Enabled { self.base() @@ -271,13 +257,13 @@ impl CheckedOperand { }; memory::address::immediate(code, base, displacement, AddressMode::Offset); } else { - code.extend(ZERO_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); } memory::request(code, 0, DATA_OFFSET, self.bytes(), self.descriptor(), pc); - code.extend(ZERO_XMM0); + let mut asm = code.asm(); + asm.simd(SimdOpcode::Xor, 0, Rm::Xmm(0), crate::TargetCpu::Baseline); for offset in (0..data_bytes).step_by(STACK_ALIGNMENT as usize) { - code.extend(STORE_VECTOR); - code.push((DATA_OFFSET + offset) as u8); + asm.movdqu_store(payload(offset), 0); } match self.operand { Operand::Atomic(operand) => stage_atomic(code, operand), @@ -298,40 +284,32 @@ impl CheckedOperand { } Operand::Ordered(_) => {} } - code.extend(ZERO_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); let cleanup = code.len(); memory::patch_branch(code, failure, cleanup); if let Some(failure) = sp_failure { memory::patch_branch(code, failure, cleanup); } - code.extend(ADD_RSP); - code.push(scratch as u8); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Gpr::Rsp, scratch as i8); memory::address::return_if_failed(code); } } -fn field(code: &mut Vec, offset: u32, value: u32) { +fn field(code: &mut Code, offset: u32, value: u32) { if value != 0 { - code.extend(STORE_FIELD); - code.push((DATA_OFFSET + offset) as u8); - code.extend(value.to_le_bytes()); + code.asm() + .mov_rm_imm32(Size::Dword, payload(offset), value as i32); } } -fn stage(code: &mut Vec, register: Register, bytes: u8, offset: u32) { +fn stage(code: &mut Code, register: Register, bytes: u8, offset: u32) { if register == Register::Zero { return; } load(code, register); - code.extend(match bytes { - 1 => STORE_BYTE, - 2 => STORE_HALF, - 4 => STORE_WORD, - 8 => STORE_DOUBLE, - _ => unreachable!("validated width"), - }); - code.push((DATA_OFFSET + offset) as u8); + code.asm().mov_store(size(bytes), payload(offset), Gpr::Rax); } fn commit( - code: &mut Vec, + code: &mut Code, register: Register, bytes: u8, offset: u32, @@ -340,22 +318,29 @@ fn commit( if register == Register::Zero { return; } - let prefix: &[u8] = match (bytes, extension) { - (1, ordered::LoadExtension::Sign(Width::X64)) => SIGN_BYTE_TO_X, - (2, ordered::LoadExtension::Sign(Width::X64)) => SIGN_HALF_TO_X, - (4, ordered::LoadExtension::Sign(Width::X64)) => SIGN_WORD_TO_X, - (1, ordered::LoadExtension::Sign(Width::W32)) => SIGN_BYTE_TO_W, - (2, ordered::LoadExtension::Sign(Width::W32)) => SIGN_HALF_TO_W, - (1, _) => LOAD_BYTE, - (2, _) => LOAD_HALF, - (4, _) => LOAD_WORD, - (8, _) => LOAD_DOUBLE, + let field = payload(offset); + let mut asm = code.asm(); + match (bytes, extension) { + (4, ordered::LoadExtension::Sign(Width::X64)) => asm.movsxd(Gpr::Rax, field), + (1 | 2, ordered::LoadExtension::Sign(width)) => { + asm.movsx(Size::of(width == Width::X64), Gpr::Rax, size(bytes), field); + } + (1 | 2, _) => asm.movzx(Size::Dword, Gpr::Rax, size(bytes), field), + (4 | 8, _) => asm.mov_load(size(bytes), Gpr::Rax, field), _ => unreachable!("validated result width"), - }; - code.extend(prefix); - code.push((DATA_OFFSET + offset) as u8); + } store(code, register); } +/// The operand size of a `bytes`-wide field. +fn size(bytes: u8) -> Size { + match bytes { + 1 => Size::Byte, + 2 => Size::Word, + 4 => Size::Dword, + 8 => Size::Qword, + _ => unreachable!("validated width"), + } +} fn atomic_operation(kind: atomic::Kind) -> wire_atomic::AtomicOperation { use atomic::{Kind, Rmw}; use wire_atomic::AtomicOperation as W; @@ -375,7 +360,7 @@ fn atomic_operation(kind: atomic::Kind) -> wire_atomic::AtomicOperation { }, } } -fn stage_atomic(code: &mut Vec, operand: atomic::Operand) { +fn stage_atomic(code: &mut Code, operand: atomic::Operand) { use atomic::{Kind, Order}; let acquire = match operand.kind { Kind::CompareExchange { compare, .. } => operand.order.acquires(compare), @@ -424,7 +409,7 @@ fn stage_atomic(code: &mut Vec, operand: atomic::Operand) { } } } -fn commit_atomic(code: &mut Vec, operand: atomic::Operand) { +fn commit_atomic(code: &mut Code, operand: atomic::Operand) { use atomic::Kind; let extension = ordered::LoadExtension::Zero; match operand.kind { @@ -464,7 +449,7 @@ fn wire_feature(feature: ordered::Feature) -> wire_ordered::OrderedFeature { ordered::Feature::Lor => wire_ordered::OrderedFeature::Lor, } } -fn stage_ordered(code: &mut Vec, operand: ordered::Operand) { +fn stage_ordered(code: &mut Code, operand: ordered::Operand) { use wire_ordered::{ BARRIER_OFFSET, FEATURE_OFFSET, OPERATION_OFFSET, ORDER_OFFSET, OrderedOperation, VALUE_OFFSET, diff --git a/crates/stela-compiler/src/x86_64/simd.rs b/crates/stela-compiler/src/x86_64/simd.rs index db14ea7505..7fa9d106a3 100644 --- a/crates/stela-compiler/src/x86_64/simd.rs +++ b/crates/stela-compiler/src/x86_64/simd.rs @@ -3,6 +3,7 @@ use super::isa::SimdOpcode; use super::isa::SimdOpcode as Host; use super::{MemoryChecks, memory_address, memory_writeback}; use crate::aarch64::simd::{Comparison, IntegerOperation, Operand}; +use crate::x86_64::asm::{Code, Gpr, Mem}; use alloc::vec::Vec; pub(in crate::x86_64) mod absolute_selection; mod aes; @@ -10,6 +11,7 @@ pub(super) mod arithmetic; pub(in crate::x86_64) mod bfloat16; mod comparison; mod complex; +pub(in crate::x86_64) mod encode; mod estimate; pub(in crate::x86_64) mod exponent_scale; mod extrema_scale; @@ -71,7 +73,7 @@ impl CheckedMemoryOperand { } } - pub(crate) fn emit_context(&self, code: &mut Vec, pc: u64, target: crate::TargetCpu) { + pub(crate) fn emit_context(&self, code: &mut Code, pc: u64, target: crate::TargetCpu) { match self { Self::Fixed(operand) => operand.emit_context(code, pc), Self::Structure(operand) => operand.emit_context(code, pc, target), @@ -83,23 +85,35 @@ fn vector_offset(vector: u8) -> u32 { (core::mem::offset_of!(crate::GuestState, v) + usize::from(vector) * 16) as u32 } -fn commit(code: &mut Vec, vector: u8, xmm: u8) { +/// Guest vector `vector` in GuestState, `[rdi+disp32]`. +fn vector_memory(vector: u8) -> Mem { + Mem::base_disp32(Gpr::Rdi, vector_offset(vector) as i32) +} + +fn commit(code: &mut Code, vector: u8, xmm: u8) { // GuestState has only 8-byte alignment; V0 begins at byte264. - Host::StoreUnaligned.append(code, crate::TargetCpu::Baseline); - code.push(0x87 | (xmm << 3)); // [rdi+disp32] - code.extend(vector_offset(vector).to_le_bytes()); + Host::StoreUnaligned.emit(code, xmm, vector_memory(vector), crate::TargetCpu::Baseline); } -fn read_vector(code: &mut Vec, vector: u8, xmm: u8) { - Host::LoadUnaligned.append(code, crate::TargetCpu::Baseline); - code.push(0x87 | (xmm << 3)); // [rdi+disp32] - code.extend(vector_offset(vector).to_le_bytes()); +fn read_vector(code: &mut Code, vector: u8, xmm: u8) { + Host::LoadUnaligned.emit(code, xmm, vector_memory(vector), crate::TargetCpu::Baseline); } -fn packed(code: &mut Vec, opcode: SimdOpcode, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: SimdOpcode, destination: u8, source: u8) { opcode.register(code, destination, source, crate::TargetCpu::Baseline); } +/// [`packed`] with an 8-bit immediate. +fn packed_imm(code: &mut Code, opcode: SimdOpcode, destination: u8, source: u8, immediate: u8) { + opcode.emit_imm( + code, + destination, + crate::x86_64::asm::Rm::Xmm(source), + immediate, + crate::TargetCpu::Baseline, + ); +} + fn subtract_opcode(lane_bytes: u8) -> SimdOpcode { match lane_bytes { 1 => Host::SubByte, @@ -110,27 +124,31 @@ fn subtract_opcode(lane_bytes: u8) -> SimdOpcode { } } -fn shuffle(code: &mut Vec, destination: u8, source: u8, control: u8) { - packed(code, Host::ShuffleDword, destination, source); - code.push(control); +fn shuffle(code: &mut Code, destination: u8, source: u8, control: u8) { + packed_imm(code, Host::ShuffleDword, destination, source, control); } -fn unsigned_bias(code: &mut Vec, lane_bytes: u8) { +/// `movabs rcx, value`, then `movq xmm, rcx`, which clears the high qword. +fn move_constant(code: &mut Code, xmm: u8, value: u64) { + let mut asm = code.asm(); + asm.mov_imm64(Gpr::Rcx, value); + asm.movq_to_xmm(xmm, Gpr::Rcx); +} + +fn unsigned_bias(code: &mut Code, lane_bytes: u8) { let mask: u64 = match lane_bytes { 1 => 0x8080808080808080, 2 => 0x8000800080008000, 4 | 8 => 0x8000000080000000, _ => unreachable!("reviewed comparison lane"), }; - code.extend([0x48, 0xb9]); - code.extend(mask.to_le_bytes()); - code.extend([0x66, 0x48, 0x0f, 0x6e, 0xe1]); // movq xmm4,rcx + move_constant(code, 4, mask); packed(code, Host::UnpackLowQword, 4, 4); packed(code, Host::Xor, 0, 4); packed(code, Host::Xor, 1, 4); } -fn equal(code: &mut Vec, lane_bytes: u8, target: crate::TargetCpu) { +fn equal(code: &mut Code, lane_bytes: u8, target: crate::TargetCpu) { if lane_bytes == 8 && target >= crate::TargetCpu::Sse41 { Host::EqualQword.register(code, 0, 1, target); // pcmpeqq xmm0,xmm1 return; @@ -152,17 +170,10 @@ fn equal(code: &mut Vec, lane_bytes: u8, target: crate::TargetCpu) { } } -pub(super) fn greater( - code: &mut Vec, - lane_bytes: u8, - unsigned: bool, - target: crate::TargetCpu, -) { +pub(super) fn greater(code: &mut Code, lane_bytes: u8, unsigned: bool, target: crate::TargetCpu) { if lane_bytes == 8 && target >= crate::TargetCpu::Sse42 { if unsigned { - code.extend([0x48, 0xb9]); - code.extend(0x8000000000000000u64.to_le_bytes()); - code.extend([0x66, 0x48, 0x0f, 0x6e, 0xe1]); + move_constant(code, 4, 0x8000000000000000); packed(code, Host::UnpackLowQword, 4, 4); packed(code, Host::Xor, 0, 4); packed(code, Host::Xor, 1, 4); @@ -234,7 +245,7 @@ pub(super) fn numerical_always_exits(operation: &crate::aarch64::FloatingPointOp } pub(super) fn emit_numerical( - code: &mut Vec, + code: &mut Code, operation: &crate::aarch64::FloatingPointOperation, pc: crate::GuestAddress, target: crate::TargetCpu, @@ -245,7 +256,7 @@ pub(super) fn emit_numerical( /// [`emit_numerical`] after what `entry` says, returning the /// [`numerical::ColdSplit`] of an emission with a sticky-inexact path. pub(super) fn emit_numerical_split( - code: &mut Vec, + code: &mut Code, operation: &crate::aarch64::FloatingPointOperation, pc: crate::GuestAddress, target: crate::TargetCpu, @@ -307,7 +318,7 @@ pub(super) fn emit_numerical_split( } #[cfg(test)] -pub(super) fn emit(code: &mut Vec, operand: &Operand) { +pub(super) fn emit(code: &mut Code, operand: &Operand) { emit_for_target( code, operand, @@ -316,7 +327,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { ); } pub(super) fn emit_for_target( - code: &mut Vec, + code: &mut Code, operand: &Operand, target: crate::TargetCpu, checks: MemoryChecks, @@ -327,7 +338,7 @@ pub(super) fn emit_for_target( /// [`emit_for_target`] where XMM0 holds guest vector `xmm0` whole: a /// store of it takes it from there. pub(super) fn emit_after( - code: &mut Vec, + code: &mut Code, operand: &Operand, target: crate::TargetCpu, checks: MemoryChecks, @@ -545,15 +556,13 @@ pub(super) fn emit_after( two_lanes, } => { if mask == 0 { - code.extend([0x66, 0x0f, 0xef, 0xc0]); // pxor xmm0,xmm0 + packed(code, Host::Xor, 0, 0); commit(code, vector, 0); return; } - code.extend([0x48, 0xb9]); // movabs rcx,mask - code.extend(mask.to_le_bytes()); - code.extend([0x66, 0x48, 0x0f, 0x6e, 0xc1]); // movq xmm0,rcx (zeros high64) + move_constant(code, 0, mask); if two_lanes { - code.extend([0x66, 0x0f, 0x6c, 0xc0]); // punpcklqdq xmm0,xmm0 + packed(code, Host::UnpackLowQword, 0, 0); } commit(code, vector, 0); } @@ -590,7 +599,7 @@ pub(super) fn emit_after( /// alone, what it held. pub(super) fn xmm0_after(operand: &Operand, code: &[u8], held: Option) -> Option { let committed = |vector: u8| { - let mut store = Vec::new(); + let mut store = Code::new(); commit(&mut store, vector, 0); code.ends_with(&store).then_some(vector) }; @@ -624,9 +633,9 @@ pub(super) fn xmm0_after(operand: &Operand, code: &[u8], held: Option) -> Op /// [`read_vector`]'s bytes for `vector` into XMM0, which an emission that /// begins with them does not need where XMM0 holds the vector already. pub(super) fn xmm0_load(vector: u8) -> Vec { - let mut load = Vec::new(); + let mut load = Code::new(); read_vector(&mut load, vector, 0); - load + load.into_bytes() } #[cfg(test)] @@ -636,7 +645,7 @@ mod tests { use alloc::vec; mod numerical_boundary { - use crate::{GuestAddress, block}; + use crate::GuestAddress; use alloc::vec::Vec; const FCVT_H_S: u32 = 0x1e23c020; @@ -655,7 +664,7 @@ mod tests { .iter() .flat_map(|word| word.to_le_bytes()) .collect(); - let compiled = block::compile(&bytes, GuestAddress(0x1000)).unwrap(); + let compiled = crate::testing::block(&bytes, GuestAddress(0x1000)).unwrap(); assert_eq!(compiled.source_bytes, size_of::()); assert_eq!(compiled.native.source_map, [(GuestAddress(0x1000), 0)]); } @@ -664,14 +673,14 @@ mod tests { .iter() .flat_map(|word| word.to_le_bytes()) .collect(); - assert!(block::compile(&bytes, GuestAddress(0x1000)).is_err()); + assert!(crate::testing::block(&bytes, GuestAddress(0x1000)).is_err()); } } } #[test] fn q_load_is_unaligned_staged_and_committed_before_writeback() { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &Operand::Memory { @@ -708,7 +717,7 @@ mod tests { (8, vec![0xf3, 0x0f, 0x7e, 0], vec![0x66, 0x0f, 0xd6, 0]), ] { for load in [false, true] { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &Operand::Memory { @@ -733,7 +742,7 @@ mod tests { #[test] fn movi_d_clears_high_half_and_two_d_replicates_without_new_cpu_features() { for two_lanes in [false, true] { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &Operand::MoveImmediate { @@ -755,7 +764,7 @@ mod tests { #[test] fn zero_byte_masks_share_compact_full_vector_zeroing() { for two_lanes in [false, true] { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &Operand::MoveImmediate { @@ -774,7 +783,7 @@ mod tests { #[test] fn pair_loads_stage_both_exact_width_values_before_guest_commits_and_writeback() { for (bytes, prefix, opcode) in [(4, 0x66, 0x6e), (8, 0xf3, 0x7e), (16, 0xf3, 0x6f)] { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &Operand::MemoryPair { @@ -799,7 +808,7 @@ mod tests { #[test] fn pair_stores_capture_duplicate_sources_before_two_writes_and_delay_writeback() { for (bytes, prefix, opcode) in [(4, 0x66, 0x7e), (8, 0x66, 0xd6), (16, 0xf3, 0x7f)] { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &Operand::MemoryPair { diff --git a/crates/stela-compiler/src/x86_64/simd/absolute_selection.rs b/crates/stela-compiler/src/x86_64/simd/absolute_selection.rs index 0f21efc9af..e366949ad2 100644 --- a/crates/stela-compiler/src/x86_64/simd/absolute_selection.rs +++ b/crates/stela-compiler/src/x86_64/simd/absolute_selection.rs @@ -1,4 +1,5 @@ //! Integer magnitude selection for FAMIN/FAMAX, exact under any host MXCSR. +use crate::x86_64::asm::{Code, Cond, Gpr, Size}; use crate::{ TargetCpu, aarch64::floating::{Format, absolute_minmax::AbsoluteMinMaxOperation}, @@ -6,30 +7,22 @@ use crate::{ }; use alloc::vec::Vec; -const REGISTER_DIRECT: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; -const RCX: u8 = 1; const RAX: u8 = 0; const HIGH_DWORDS: u8 = 0xf5; const LOW_DWORDS: u8 = 0xa0; const REPEAT_LOW_DWORD: u8 = 0; -const TEST_EAX: &[u8] = &[0x85, 0xc0]; -const JNZ: &[u8] = &[0x0f, 0x85]; -fn shuffle(code: &mut Vec, register: u8, order: u8, target: TargetCpu) { - Host::ShuffleDword.register(code, register, register, target); - code.push(order); +fn shuffle(code: &mut Code, register: u8, order: u8, target: TargetCpu) { + Host::ShuffleDword.register_imm(code, register, register, order, target); } -fn infinity(code: &mut Vec, format: Format, register: u8, target: TargetCpu) { - code.extend([0x48, 0xb9]); // mov rcx, imm64 +fn infinity(code: &mut Code, format: Format, register: u8, target: TargetCpu) { let bits = match format { Format::Half => format.exponent_mask() | format.exponent_mask() << Format::Half.bits(), _ => format.exponent_mask(), }; - code.extend(bits.to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(REGISTER_DIRECT | register << REGISTER_SHIFT | RCX); + code.asm().mov_imm64(Gpr::Rcx, bits); + Host::MoveGprQword.emit(code, register, Gpr::Rcx, target); if format == Format::Double { Host::UnpackLowQword.register(code, register, register, target); } else { @@ -37,7 +30,7 @@ fn infinity(code: &mut Vec, format: Format, register: u8, target: TargetCpu) } } -fn magnitude(code: &mut Vec, format: Format, register: u8) { +fn magnitude(code: &mut Code, format: Format, register: u8) { let (left, right) = match format { Format::Half => (ShiftOpcode::LeftWord, ShiftOpcode::RightWord), Format::Single => (ShiftOpcode::LeftDword, ShiftOpcode::RightDword), @@ -51,7 +44,7 @@ fn magnitude(code: &mut Vec, format: Format, register: u8) { /// scratch registers must be distinct from each other and the two inputs. NaN /// edges are rel32 displacements for the owner's transactional completion exit. pub(in crate::x86_64) fn guard_and_magnitudes( - code: &mut Vec, + code: &mut Code, format: Format, left: u8, right: u8, @@ -86,17 +79,16 @@ pub(in crate::x86_64) fn guard_and_magnitudes( } } Host::ByteSignMask.register(code, RAX, greater, target); - code.extend(TEST_EAX); - code.extend(JNZ); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); + let mut asm = code.asm(); + asm.test(Size::Dword, Gpr::Rax, Gpr::Rax); + failures.push(asm.jcc(Cond::Ne).offset()); } } /// Inputs must be sign-cleared, non-NaN magnitudes. Produces the result in left, /// preserves right, and clobbers four scratch XMMs. No guest or host FP effects. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, format: Format, operation: AbsoluteMinMaxOperation, left: u8, diff --git a/crates/stela-compiler/src/x86_64/simd/aes.rs b/crates/stela-compiler/src/x86_64/simd/aes.rs index 4f00618c93..97a37c4fd6 100644 --- a/crates/stela-compiler/src/x86_64/simd/aes.rs +++ b/crates/stela-compiler/src/x86_64/simd/aes.rs @@ -1,6 +1,6 @@ //! AES: constant-time SSE2 circuits, or AES-NI when available. All sources are //! read before the destination is written. -use alloc::vec::Vec; +use crate::x86_64::asm::{Code, Gpr}; mod sbox; use super::{Host, commit, packed, read_vector, rearrange::constant, shuffle}; @@ -25,20 +25,19 @@ const FORWARD_COLUMN_ORDER: [u8; 4] = [0xe4, 0x39, 0x4e, 0x93]; const INVERSE_COLUMN_ORDER: [u8; 4] = [0xe4, 0x93, 0x4e, 0x39]; const BYTE_REPLICATION: u64 = 0x0101_0101_0101_0101; const FIELD_REDUCTION: u8 = 0x1b; -const MOVABS_RCX: [u8; 2] = [0x48, 0xb9]; const SHIFT_ROWS: [u8; 16] = [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11]; const INVERSE_SHIFT_ROWS: [u8; 16] = [0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3]; /// Broadcast a byte without a memory pool or an additional SIMD clobber. -fn byte_constant(code: &mut Vec, destination: u8, value: u8) { - code.extend(MOVABS_RCX); - code.extend((u64::from(value) * BYTE_REPLICATION).to_le_bytes()); - packed(code, Host::MoveGprQword, destination, RCX); // RCX -> XMM. +fn byte_constant(code: &mut Code, destination: u8, value: u8) { + code.asm() + .mov_imm64(Gpr::Rcx, u64::from(value) * BYTE_REPLICATION); + packed(code, Host::MoveGprQword, destination, RCX); packed(code, Host::UnpackLowQword, destination, destination); } /// Per-byte multiplication by x modulo x^8+x^4+x^3+x+1. MASK holds 1b; /// HIGH is scratch. PADDB avoids carries between adjacent byte lanes. -fn xtime(code: &mut Vec, value: u8) { +fn xtime(code: &mut Code, value: u8) { packed(code, Host::Xor, HIGH, HIGH); packed(code, Host::GreaterByte, HIGH, value); packed(code, Host::AddByte, value, value); @@ -46,7 +45,7 @@ fn xtime(code: &mut Vec, value: u8) { packed(code, Host::Xor, value, HIGH); } -fn shift_rows(code: &mut Vec, inverse: bool, target: TargetCpu) { +fn shift_rows(code: &mut Code, inverse: bool, target: TargetCpu) { let selection = if inverse { INVERSE_SHIFT_ROWS } else { @@ -66,8 +65,7 @@ fn shift_rows(code: &mut Vec, inverse: bool, target: TargetCpu) { }; for (row, control) in order.into_iter().enumerate() { let mask = u64::from(u8::MAX) << (row * usize::from(BYTE_BITS)); - code.extend(MOVABS_RCX); - code.extend((mask * COLUMN_REPLICATION).to_le_bytes()); + code.asm().mov_imm64(Gpr::Rcx, mask * COLUMN_REPLICATION); packed(code, Host::MoveGprQword, MASK, RCX); packed(code, Host::UnpackLowQword, MASK, MASK); if row == 0 { @@ -84,7 +82,7 @@ fn shift_rows(code: &mut Vec, inverse: bool, target: TargetCpu) { /// Rotate each four-byte AES column right, keeping the input. MASK and HIGH /// stay free for xtime; RESULT may be the destination. -fn rotate_column(code: &mut Vec, destination: u8, source: u8, bits: u8) { +fn rotate_column(code: &mut Code, destination: u8, source: u8, bits: u8) { packed(code, Host::MoveAligned, TERM, source); packed(code, Host::MoveAligned, destination, source); Shift::LeftDword.emit(code, TERM, COLUMN_BITS - bits); @@ -92,7 +90,7 @@ fn rotate_column(code: &mut Vec, destination: u8, source: u8, bits: u8) { packed(code, Host::Or, destination, TERM); } -fn mix_columns(code: &mut Vec, inverse: bool) { +fn mix_columns(code: &mut Code, inverse: bool) { byte_constant(code, MASK, FIELD_REDUCTION); if inverse { rotate_column(code, RIGHT, RESULT, BYTE_BITS * 2); @@ -115,7 +113,7 @@ fn mix_columns(code: &mut Vec, inverse: bool) { // rot24(a): a XOR columnXor simplifies away the duplicate a. } -fn aes(code: &mut Vec, kind: Kind, target: TargetCpu) { +fn aes(code: &mut Code, kind: Kind, target: TargetCpu) { if kind == Kind::InverseMixColumns { Host::AesInverseMixColumns.register(code, RESULT, RESULT, target); return; @@ -132,7 +130,7 @@ fn aes(code: &mut Vec, kind: Kind, target: TargetCpu) { } } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { read_vector(code, operand.source, RESULT); if matches!(operand.kind, Kind::Encrypt | Kind::Decrypt) { read_vector(code, operand.destination, OLD_DESTINATION); @@ -190,7 +188,7 @@ mod tests { destination: 31, source: 31, }; - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, TargetCpu::Aes); assert_eq!(code.len(), bytes); // Complete body, excludes harness RET. for opcode in [ @@ -217,7 +215,7 @@ mod tests { Kind::MixColumns, Kind::InverseMixColumns, ] { - let mut code = Vec::new(); + let mut code = Code::new(); emit( &mut code, &Operand { @@ -316,7 +314,7 @@ mod tests { .iter() .map(|&row| table[usize::from(state_bytes[usize::from(row)])]) .collect(); - let mut code = WRAPPER.to_vec(); + let mut code = Code::from(WRAPPER.to_vec()); emit( &mut code, &Operand { diff --git a/crates/stela-compiler/src/x86_64/simd/aes/sbox.rs b/crates/stela-compiler/src/x86_64/simd/aes/sbox.rs index e5a6bdda9b..374804fbf9 100644 --- a/crates/stela-compiler/src/x86_64/simd/aes/sbox.rs +++ b/crates/stela-compiler/src/x86_64/simd/aes/sbox.rs @@ -5,19 +5,11 @@ //! for the AES constants) carries the caller's RSP into the frame's last slot. //! The frame is restored before the destination is written. use super::{BYTE_BITS, Host, LEFT, MASK, RESULT, Shift, TargetCpu, byte_constant, packed}; -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Size}; const VECTOR_BYTES: u32 = 16; const INPUT_PLANES: usize = 8; -const RCX: u8 = 1; -const RSP: u8 = 4; -const STACK_MODRM_DISP32: u8 = 0x84; -const STACK_SIB: u8 = 0x24; -const MOV_RCX_RSP: [u8; 3] = [0x48, 0x89, 0xe1]; -const SUB_RSP_IMMEDIATE: [u8; 3] = [0x48, 0x81, 0xec]; -const AND_RSP_ALIGN_16: [u8; 4] = [0x48, 0x83, 0xe4, 0xf0]; -const MOV_STORE_QWORD: [u8; 2] = [0x48, 0x89]; -const MOV_LOAD_QWORD: [u8; 2] = [0x48, 0x8b]; +const STACK_ALIGNMENT: i8 = 16; // Boyar-Peralta 113-gate forward and Calik 121-gate inverse S-box circuits // (https://www.cs.yale.edu/homes/peralta/CircuitStuff/{SLP_AES_113.txt,Sinv.txt}), @@ -273,18 +265,16 @@ const INVERSE_GATES: [Gate; 121] = [ ]; const INVERSE_OUTPUTS: [u8; 8] = [118, 123, 125, 116, 128, 120, 117, 113]; -fn stack_plane(code: &mut Vec, register: u8, plane: usize, opcode: Host) { - opcode.append(code, TargetCpu::Baseline); - stack_slot(code, register, plane); +fn stack_plane(code: &mut Code, register: u8, plane: usize, opcode: Host) { + opcode.emit(code, register, stack_slot(plane), TargetCpu::Baseline); } -/// The `[rsp + plane * 16]` operand of `register`, after its opcode. -fn stack_slot(code: &mut Vec, register: u8, plane: usize) { - code.extend([STACK_MODRM_DISP32 | (register << 3), STACK_SIB]); - code.extend((plane as u32 * VECTOR_BYTES).to_le_bytes()); +/// `[rsp + plane * 16]`, with a 32-bit displacement. +fn stack_slot(plane: usize) -> Mem { + Mem::base_disp32(Gpr::Rsp, (plane as u32 * VECTOR_BYTES) as i32) } -pub(super) fn emit(code: &mut Vec, inverse: bool) { +pub(super) fn emit(code: &mut Code, inverse: bool) { let (gates, outputs): (&[Gate], [u8; 8]) = if inverse { (&INVERSE_GATES, INVERSE_OUTPUTS) } else { @@ -292,12 +282,16 @@ pub(super) fn emit(code: &mut Vec, inverse: bool) { }; let planes = INPUT_PLANES + gates.len(); // The planes, then one aligned slot for the caller's RSP. - code.extend(MOV_RCX_RSP); - code.extend(SUB_RSP_IMMEDIATE); - code.extend((planes as u32 * VECTOR_BYTES + VECTOR_BYTES).to_le_bytes()); - code.extend(AND_RSP_ALIGN_16); - code.extend(MOV_STORE_QWORD); - stack_slot(code, RCX, planes); + let mut asm = code.asm(); + asm.mov(Size::Qword, Gpr::Rcx, Gpr::Rsp); + asm.alu_imm32( + Alu::Sub, + Size::Qword, + Gpr::Rsp, + (planes as u32 * VECTOR_BYTES + VECTOR_BYTES) as i32, + ); + asm.alu_imm8(Alu::And, Size::Qword, Gpr::Rsp, -STACK_ALIGNMENT); + asm.mov_store(Size::Qword, stack_slot(planes), Gpr::Rcx); byte_constant(code, MASK, 1); for input in 0..INPUT_PLANES { packed(code, Host::MoveAligned, LEFT, RESULT); @@ -330,6 +324,6 @@ pub(super) fn emit(code: &mut Vec, inverse: bool) { } packed(code, Host::Or, RESULT, LEFT); } - code.extend(MOV_LOAD_QWORD); - stack_slot(code, RSP, planes); + code.asm() + .mov_load(Size::Qword, Gpr::Rsp, stack_slot(planes)); } diff --git a/crates/stela-compiler/src/x86_64/simd/arithmetic.rs b/crates/stela-compiler/src/x86_64/simd/arithmetic.rs index 0a2c5785d1..1f5e25f7c5 100644 --- a/crates/stela-compiler/src/x86_64/simd/arithmetic.rs +++ b/crates/stela-compiler/src/x86_64/simd/arithmetic.rs @@ -1,16 +1,18 @@ //! FP binary arithmetic: guarded SSE2 values and precise software fallback. +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::{Alu, Code, Gpr, Rm, Size}; use alloc::vec; use alloc::vec::Vec; mod half; use super::super::isa::ShiftOpcode; use super::numerical::{ ArithmeticOpcode, ColdSplit, Condition, EXPONENT_VECTOR, Entry, INPUT_MINIMUM_EXPONENT, Input, - LEFT_VECTOR, MOVLHPS_XMM1_XMM2, MOVQ_XMM0_XMM0, RESULT_MINIMUM_EXPONENT, RIGHT_VECTOR, - SINGLE_EXPONENT_BIAS_BITS, ZeroProduct, branch, clear_scalar, commit_inexact, emit_opcode, - environment, exponent_range, jump, prepare_vector_input_range, prepare_vector_result_range, - read_inputs, read_numerical_right, read_numerical_vector, reject_other_status, resolve, - restore_environment, scalar_range_or_zero, sticky_inexact, sticky_result_check, test_control, - vector_exponent_range, vector_normal_or_zero_range, zero_product_check, + LEFT_VECTOR, RESULT_MINIMUM_EXPONENT, RIGHT_VECTOR, SINGLE_EXPONENT_BIAS_BITS, ZeroProduct, + branch, clear_high_qword, clear_scalar, commit_inexact, emit_opcode, environment, + exponent_range, jump, prepare_vector_input_range, prepare_vector_result_range, read_inputs, + read_numerical_right, read_numerical_vector, reject_other_status, resolve, restore_environment, + scalar_range_or_zero, sticky_inexact, sticky_result_check, test_control, vector_exponent_range, + vector_normal_or_zero_range, zero_product_check, }; use super::{Host, commit, packed, read_vector, shuffle}; use crate::{ @@ -25,12 +27,6 @@ use crate::{ const PAIRED_RIGHT: u8 = 6; const ZERO_RANGE_SCRATCH: u8 = 7; const SIGN_MASK_VECTOR: u8 = 2; -const SSE_ESCAPE: u8 = 0x0f; -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const SHUFPS: u8 = 0xc6; -const UNPCKLPS_XMM0_XMM1: &[u8] = &[0x0f, 0x14, 0xc1]; -const MOVHLPS_XMM1_XMM0: &[u8] = &[0x0f, 0x12, 0xc8]; const EVEN_SINGLE_LANES: u8 = 0x88; const ODD_SINGLE_LANES: u8 = 0xdd; const FIRST_LANE: u8 = 0; @@ -38,16 +34,6 @@ const REPLICATE_SINGLE_LANE: u8 = 0x55; const REPLICATE_LOW_DOUBLE: u8 = 0x44; const REPLICATE_HIGH_DOUBLE: u8 = 0xee; const SIGN_BITS: u8 = 1; -const MOVD_EAX_XMM0: &[u8] = &[0x66, 0x0f, 0x7e, 0xc0]; -const MOVQ_RAX_XMM0: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xc0]; -const MOVD_XMM2_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xd0]; -const MOVQ_XMM2_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xd0]; -const MOVSS_XMM0_XMM2: &[u8] = &[0xf3, 0x0f, 0x10, 0xc2]; -const MOVSD_XMM0_XMM2: &[u8] = &[0xf2, 0x0f, 0x10, 0xc2]; -const AND_EAX_IMM32: u8 = 0x25; -const XOR_EAX_IMM32: u8 = 0x35; -const BTR_RAX_IMM8: &[u8] = &[0x48, 0x0f, 0xba, 0xf0]; -const BTC_RAX_IMM8: &[u8] = &[0x48, 0x0f, 0xba, 0xf8]; fn arithmetic_opcode(operation: BinaryOperation) -> ArithmeticOpcode { match operation { @@ -62,24 +48,20 @@ fn arithmetic_opcode(operation: BinaryOperation) -> ArithmeticOpcode { } } -fn shuffle_single(code: &mut Vec, destination: u8, source: u8, lanes: u8) { - code.extend([ - SSE_ESCAPE, - SHUFPS, - REGISTER_DIRECT | (destination << MODRM_REGISTER_SHIFT) | source, - lanes, - ]); +fn shuffle_single(code: &mut Code, destination: u8, source: u8, lanes: u8) { + code.asm().shufps(destination, Rm::Xmm(source), lanes); } /// Stage adjacent Vn pairs before adjacent Vm pairs without numerical work. /// Return the right host register; classifier scratch XMM2/3/4/5 must not alias it. -fn prepare_pairs(code: &mut Vec, format: Format, shape: Shape) -> u8 { +fn prepare_pairs(code: &mut Code, format: Format, shape: Shape) -> u8 { match (format, shape) { (Format::Single, Shape::Vector64) => { // Q0 loads zero both high qwords. The extra packed sums are normal // values plus zero, so they cannot add exceptions to active lanes. - code.extend(UNPCKLPS_XMM0_XMM1); - code.extend(MOVHLPS_XMM1_XMM0); + let mut asm = code.asm(); + asm.unpcklps(LEFT_VECTOR, Rm::Xmm(RIGHT_VECTOR)); + asm.movhlps(RIGHT_VECTOR, Rm::Xmm(LEFT_VECTOR)); RIGHT_VECTOR } (Format::Single, Shape::Vector128) => { @@ -98,7 +80,7 @@ fn prepare_pairs(code: &mut Vec, format: Format, shape: Shape) -> u8 { } } -fn prepare_inputs(code: &mut Vec, operand: &Operand) -> u8 { +fn prepare_inputs(code: &mut Code, operand: &Operand) -> u8 { match operand.inputs { Inputs::Elementwise { left, right } => { read_numerical_vector(code, operand.shape, left, LEFT_VECTOR); @@ -148,7 +130,7 @@ fn prepare_inputs(code: &mut Vec, operand: &Operand) -> u8 { /// FNMUL/FABD transform the rounded result. Only finite normal or zero results reach /// this point, so AH's NaN sign policy stays on the exact helper path. -fn result_sign(code: &mut Vec, operand: &Operand) { +fn result_sign(code: &mut Code, operand: &Operand) { let negate = match operand.operation { BinaryOperation::NegatedMultiply => true, BinaryOperation::AbsoluteDifference => false, @@ -157,19 +139,38 @@ fn result_sign(code: &mut Vec, operand: &Operand) { if operand.shape == Shape::Scalar { match operand.format { Format::Single => { - code.extend(MOVD_EAX_XMM0); - code.push(if negate { XOR_EAX_IMM32 } else { AND_EAX_IMM32 }); let sign = operand.format.sign_mask() as u32; - code.extend((if negate { sign } else { !sign }).to_le_bytes()); - code.extend(MOVD_XMM2_EAX); - code.extend(MOVSS_XMM0_XMM2); + let mut asm = code.asm(); + asm.movd_from_xmm(Gpr::Rax, LEFT_VECTOR); + if negate { + asm.alu_accumulator_imm32(Alu::Xor, Size::Dword, sign as i32); + } else { + asm.alu_accumulator_imm32(Alu::And, Size::Dword, !sign as i32); + } + asm.movd_to_xmm(SIGN_MASK_VECTOR, Gpr::Rax); + Host::MoveScalarSingle.register( + code, + LEFT_VECTOR, + SIGN_MASK_VECTOR, + TargetCpu::Baseline, + ); } Format::Double => { - code.extend(MOVQ_RAX_XMM0); - code.extend(if negate { BTC_RAX_IMM8 } else { BTR_RAX_IMM8 }); - code.push(operand.format.bits() as u8 - SIGN_BITS); - code.extend(MOVQ_XMM2_RAX); - code.extend(MOVSD_XMM0_XMM2); + let mut asm = code.asm(); + asm.movq_from_xmm(Gpr::Rax, LEFT_VECTOR); + asm.bit_imm( + if negate { BitTest::Btc } else { BitTest::Btr }, + Size::Qword, + Gpr::Rax, + operand.format.bits() as u8 - SIGN_BITS, + ); + asm.movq_to_xmm(SIGN_MASK_VECTOR, Gpr::Rax); + Host::MoveScalarDouble.register( + code, + LEFT_VECTOR, + SIGN_MASK_VECTOR, + TargetCpu::Baseline, + ); } Format::Half => unreachable!("Half has its own mapping policy"), } @@ -253,12 +254,7 @@ fn product_left(operand: &Operand) -> u8 { /// ([`zero_product`]). Returns the branches to the full path, to the helper /// and past the full path, and those between the sticky path and the /// rest ([`ColdSplit`]). -fn sticky_path( - code: &mut Vec, - operand: &Operand, - entry: Entry, - target: TargetCpu, -) -> StickyPath { +fn sticky_path(code: &mut Code, operand: &Operand, entry: Entry, target: TargetCpu) -> StickyPath { let full = sticky_inexact(code, entry); // Zeroing loads leave a scalar result's upper bits clear. let zeroed = @@ -297,7 +293,7 @@ fn sticky_path( result_sign(code, operand); match operand.shape { Shape::Scalar if !zeroed => clear_scalar(code, operand.format, LEFT_VECTOR), - Shape::Vector64 => code.extend(MOVQ_XMM0_XMM0), + Shape::Vector64 => clear_high_qword(code, 0), Shape::Scalar | Shape::Vector128 => {} } commit(code, operand.destination, LEFT_VECTOR); @@ -352,7 +348,7 @@ fn enter_full(code: &mut [u8], sticky: &mut StickyPath) -> usize { } fn emit_scalar( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, entry: Entry, @@ -436,7 +432,7 @@ fn finish(code: &mut [u8], sticky: StickyPath, full: usize, operand: &Operand) - } fn emit_vector( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, entry: Entry, @@ -473,7 +469,7 @@ fn emit_vector( u32::BITS as u8 - SINGLE_EXPONENT_BIAS_BITS, ); ShiftOpcode::LeftDword.emit(code, EXPONENT_VECTOR, Format::Single.fraction_bits() as u8); - code.extend(MOVLHPS_XMM1_XMM2); + code.asm().movlhps(1, crate::x86_64::asm::Rm::Xmm(2)); } environment(code); emit_opcode( @@ -508,7 +504,7 @@ fn emit_vector( commit_inexact(code); result_sign(code, operand); if operand.shape == Shape::Vector64 { - code.extend(MOVQ_XMM0_XMM0); + clear_high_qword(code, 0); } commit(code, operand.destination, LEFT_VECTOR); finish(code, sticky, full, operand) @@ -520,7 +516,7 @@ pub(super) fn always_exits(operand: &Operand) -> bool { /// The S/D forms return their [`ColdSplit`]. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu, @@ -567,12 +563,12 @@ mod tests { .flat_map(|value| value.to_le_bytes()) .collect(); assert!( - crate::compile(&bytes, GuestAddress(0x1000)) + crate::testing::leaf(&bytes, GuestAddress(0x1000)) .unwrap_err() .0 .contains("NumericalRuntimeRequired") ); - let block = crate::block::compile(&bytes, GuestAddress(0x1000)).unwrap(); + let block = crate::testing::block(&bytes, GuestAddress(0x1000)).unwrap(); assert_eq!(block.source_bytes, bytes.len()); assert_eq!(block.native.source_map.len(), 2); assert_eq!(block.native.source_map[1].0, GuestAddress(0x1004)); @@ -582,7 +578,7 @@ mod tests { .iter() .flat_map(|value| value.to_le_bytes()) .collect(); - let block = crate::block::compile(&bytes, GuestAddress(0x1000)).unwrap(); + let block = crate::testing::block(&bytes, GuestAddress(0x1000)).unwrap(); assert_eq!(block.source_bytes, size_of::()); assert_eq!(block.native.source_map, [(GuestAddress(0x1000), 0)]); } diff --git a/crates/stela-compiler/src/x86_64/simd/arithmetic/half.rs b/crates/stela-compiler/src/x86_64/simd/arithmetic/half.rs index deef3b7281..0dcbcee996 100644 --- a/crates/stela-compiler/src/x86_64/simd/arithmetic/half.rs +++ b/crates/stela-compiler/src/x86_64/simd/arithmetic/half.rs @@ -1,13 +1,14 @@ //! Half-precision arithmetic through exact widened intermediates. +use crate::x86_64::asm::Code; use alloc::vec::Vec; mod product; use super::super::super::isa::ShiftOpcode; use super::super::numerical::{ - ArithmeticOpcode, Condition, VZEROUPPER, branch, emit_opcode_to, prepare_vector_input_range, + ArithmeticOpcode, Condition, branch, emit_opcode_to, prepare_vector_input_range, read_numerical_right, read_numerical_vector, test_control, vector_exponent_range, }; -use super::super::{Host, commit, half as lanes, packed, read_vector}; +use super::super::{Host, commit, half as lanes, packed, packed_imm, read_vector}; use crate::{ GuestAddress, TargetCpu, aarch64::{ @@ -21,14 +22,13 @@ const RIGHT_ODD: u8 = 3; const EVEN_HALF_WORDS: u8 = 0x88; const SECOND_HALF_WORD: u8 = 0x55; -fn compact_even_words(code: &mut Vec, source: u8) { - packed(code, Host::ShuffleLowWord, source, source); - code.push(EVEN_HALF_WORDS); +fn compact_even_words(code: &mut Code, source: u8) { + packed_imm(code, Host::ShuffleLowWord, source, source, EVEN_HALF_WORDS); } /// Normalize adjacent Vn pairs followed by Vm pairs into two Half vectors. /// Q0 inputs were loaded with MOVQ; only the assembled active words are guarded. -fn prepare_pairs(code: &mut Vec, shape: Shape) { +fn prepare_pairs(code: &mut Code, shape: Shape) { packed(code, Host::MoveAligned, LEFT_ODD, lanes::LEFT); if shape == Shape::Vector128 { packed(code, Host::MoveAligned, RIGHT_ODD, lanes::RIGHT); @@ -56,7 +56,7 @@ fn prepare_pairs(code: &mut Vec, shape: Shape) { packed(code, Host::MoveAligned, lanes::RIGHT, LEFT_ODD); } -fn prepare_inputs(code: &mut Vec, operand: &Operand) { +fn prepare_inputs(code: &mut Code, operand: &Operand) { match operand.inputs { Inputs::Elementwise { left, right } => { read_numerical_vector(code, operand.shape, left, lanes::LEFT); @@ -78,8 +78,13 @@ fn prepare_inputs(code: &mut Vec, operand: &Operand) { } Inputs::PairwiseScalar { source } => { read_vector(code, source, lanes::LEFT); - packed(code, Host::ShuffleLowWord, lanes::RIGHT, lanes::LEFT); - code.push(SECOND_HALF_WORD); + packed_imm( + code, + Host::ShuffleLowWord, + lanes::RIGHT, + lanes::LEFT, + SECOND_HALF_WORD, + ); } } if operand.shape == Shape::Scalar && !matches!(operand.inputs, Inputs::PairwiseScalar { .. }) { @@ -102,7 +107,7 @@ fn operation(operation: BinaryOperation) -> (ArithmeticOpcode, lanes::ResultSign } } -pub(super) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu) { debug_assert_eq!(operand.format, Format::Half); let mut helper = Vec::new(); let mut rollback = Vec::new(); @@ -110,7 +115,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress, targ let checked_widening = !packed_product && operand.shape != Shape::Scalar && target.supports(TargetCpu::F16c); if checked_widening { - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } // Ordinary binary keeps retained enables and fresh status under every AH. test_control(code, FPCR_EXCEPTION_ENABLE_MASK); diff --git a/crates/stela-compiler/src/x86_64/simd/arithmetic/half/product.rs b/crates/stela-compiler/src/x86_64/simd/arithmetic/half/product.rs index 00724a2cea..19f8c190b6 100644 --- a/crates/stela-compiler/src/x86_64/simd/arithmetic/half/product.rs +++ b/crates/stela-compiler/src/x86_64/simd/arithmetic/half/product.rs @@ -6,6 +6,7 @@ use super::super::super::numerical::{ widen_half_to_single, }; use super::super::super::{Host, packed, shuffle}; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, ShiftOp, Size, Unary}; use crate::{ GuestAddress, aarch64::{ @@ -43,40 +44,21 @@ const MINIMUM_PRODUCT: u32 = const MAXIMUM_PRODUCT: u32 = SINGLE_HALF_BIAS + (((Format::Half.exponent_mask() >> Format::Half.fraction_bits()) as u32) << Format::Single.fraction_bits()); -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MOVD_XMM_EAX_PREFIX: &[u8] = &[0x66, 0x0f, 0x6e]; -const MOV_EAX_IMM32: u8 = 0xb8; -const SETNE_AL: &[u8] = &[0x0f, 0x95, 0xc0]; -const MOVZX_EAX_AL: &[u8] = &[0x0f, 0xb6, 0xc0]; -const TEST_EAX_IMM32: u8 = 0xa9; -const NOT_EAX: &[u8] = &[0xf7, 0xd0]; -const AND_EAX_IMM8: &[u8] = &[0x83, 0xe0]; -const OR_R10D_EAX: &[u8] = &[0x41, 0x09, 0xc2]; -const TEST_R10D_R10D: &[u8] = &[0x45, 0x85, 0xd2]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const MOV_R10D_EAX: &[u8] = &[0x41, 0x89, 0xc2]; -const MOV_ECX_IMM32: u8 = 0xb9; -const DEC_ECX: &[u8] = &[0xff, 0xc9]; -const JMP_REL32: u8 = 0xe9; +use Gpr::{R10, Rax, Rcx}; -fn jump(code: &mut Vec) -> usize { - code.push(JMP_REL32); - let patch = code.len(); - code.extend(0i32.to_le_bytes()); - patch +fn jump(code: &mut Code) -> usize { + code.asm().jmp().offset() } -fn constant(code: &mut Vec, vector: u8, value: u32) { - code.push(MOV_EAX_IMM32); - code.extend(value.to_le_bytes()); - code.extend(MOVD_XMM_EAX_PREFIX); - code.push(REGISTER_DIRECT | vector << MODRM_REGISTER_SHIFT); +fn constant(code: &mut Code, vector: u8, value: u32) { + let mut asm = code.asm(); + asm.mov_imm32(Rax, value); + asm.movd_to_xmm(vector, Rax); shuffle(code, vector, vector, REPLICATE_FIRST_DWORD); } /// One four-lane group, with fresh IXC accumulating only in private R10D. -fn group(code: &mut Vec, helper: &mut Vec) { +fn group(code: &mut Code, helper: &mut Vec) { packed(code, Host::Xor, ZERO, ZERO); constant(code, CONSTANT, SINGLE_HALF_BIAS); widen_half_to_single(code, RESULT, LEFT, SIGN, ZERO, CONSTANT); @@ -101,8 +83,8 @@ fn group(code: &mut Vec, helper: &mut Vec) { packed(code, Host::SubDword, CONSTANT, TEMPORARY); packed(code, Host::Or, TEMPORARY, CONSTANT); packed(code, Host::DwordSignMask, EAX, TEMPORARY); - code.push(TEST_EAX_IMM32); - code.extend(ACTIVE_LANE_MASK.to_le_bytes()); + code.asm() + .test_accumulator_imm(Size::Dword, ACTIVE_LANE_MASK as i32); helper.push(branch(code, Condition::NotZero)); // MULPS was exact; Half IXC comes from the discarded thirteen bits. packed(code, Host::MoveAligned, TEMPORARY, RESULT); @@ -110,10 +92,10 @@ fn group(code: &mut Vec, helper: &mut Vec) { packed(code, Host::Xor, ZERO, ZERO); packed(code, Host::EqualDword, TEMPORARY, ZERO); packed(code, Host::DwordSignMask, EAX, TEMPORARY); - code.extend(NOT_EAX); - code.extend(AND_EAX_IMM8); - code.push(ACTIVE_LANE_MASK as u8); - code.extend(OR_R10D_EAX); + let mut asm = code.asm(); + asm.unary(Unary::Not, Size::Dword, Rax); + asm.alu_imm8(Alu::And, Size::Dword, Rax, ACTIVE_LANE_MASK as i8); + asm.alu(Alu::Or, Size::Dword, R10, Rax); // Increment = retained parity + ((product sign & direction) XOR bias). packed(code, Host::MoveAligned, TEMPORARY, RESULT); ShiftOpcode::RightDword.emit(code, TEMPORARY, DISCARDED_BITS); @@ -129,9 +111,9 @@ fn group(code: &mut Vec, helper: &mut Vec) { constant(code, CONSTANT, MAXIMUM_PRODUCT); packed(code, Host::GreaterDword, CONSTANT, RESULT); packed(code, Host::DwordSignMask, EAX, CONSTANT); - code.extend(NOT_EAX); - code.push(TEST_EAX_IMM32); - code.extend(ACTIVE_LANE_MASK.to_le_bytes()); + let mut asm = code.asm(); + asm.unary(Unary::Not, Size::Dword, Rax); + asm.test_accumulator_imm(Size::Dword, ACTIVE_LANE_MASK as i32); helper.push(branch(code, Condition::NotZero)); constant(code, CONSTANT, SINGLE_HALF_BIAS); packed(code, Host::SubDword, RESULT, CONSTANT); @@ -152,12 +134,11 @@ pub(super) fn supports(operand: &Operand) -> bool { /// Return XMM0 and private fresh IXC after every group passes. No stack or host /// environment changes are needed, so every failed guard enters the cold helper. -pub(super) fn emit(code: &mut Vec, shape: Shape, mut helper: Vec, pc: GuestAddress) { +pub(super) fn emit(code: &mut Code, shape: Shape, mut helper: Vec, pc: GuestAddress) { integer_rounding_policy(code, DISCARDED_BITS, false); if shape == Shape::Vector128 { // ECX is dead after integer_rounding_policy; group scratch uses only EAX. - code.push(MOV_ECX_IMM32); - code.extend(GROUP_COUNT.to_le_bytes()); + code.asm().mov_imm32(Rcx, GROUP_COUNT); packed(code, Host::Xor, ACCUMULATED, ACCUMULATED); let repeat = code.len(); group(code, &mut helper); @@ -165,7 +146,7 @@ pub(super) fn emit(code: &mut Vec, shape: Shape, mut helper: Vec, pc: packed(code, Host::UnpackLowQword, ACCUMULATED, RESULT); ShiftOpcode::RightBytes.emit(code, LEFT, GROUP_BYTES); ShiftOpcode::RightBytes.emit(code, RIGHT, GROUP_BYTES); - code.extend(DEC_ECX); + code.asm().dec(Size::Dword, Rcx); let more = branch(code, Condition::NotZero); resolve(code, more, repeat); packed(code, Host::MoveAligned, LEFT, ACCUMULATED); @@ -174,12 +155,17 @@ pub(super) fn emit(code: &mut Vec, shape: Shape, mut helper: Vec, pc: // Q0 clears the complete upper qword, despite PACKSSDW duplication. packed(code, Host::MoveQword, LEFT, RESULT); } - code.extend(TEST_R10D_R10D); - code.extend(SETNE_AL); - code.extend(MOVZX_EAX_AL); - code.extend(SHL_EAX_IMM8); - code.push(INEXACT.trailing_zeros() as u8); - code.extend(MOV_R10D_EAX); + let mut asm = code.asm(); + asm.test(Size::Dword, R10, R10); + asm.setcc(Cond::Ne, Rax); + asm.movzx(Size::Dword, Rax, Size::Byte, Rax); + asm.shift_imm( + ShiftOp::Shl, + Size::Dword, + Rax, + INEXACT.trailing_zeros() as u8, + ); + asm.mov(Size::Dword, R10, Rax); let completed = jump(code); let helper_start = code.len(); super::super::super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); diff --git a/crates/stela-compiler/src/x86_64/simd/bfloat16.rs b/crates/stela-compiler/src/x86_64/simd/bfloat16.rs index e479ba33d5..999903e2eb 100644 --- a/crates/stela-compiler/src/x86_64/simd/bfloat16.rs +++ b/crates/stela-compiler/src/x86_64/simd/bfloat16.rs @@ -1,5 +1,5 @@ //! AdvSIMD BF16 instructions. -use alloc::vec::Vec; +use crate::x86_64::asm::Code; mod conversion; mod dot; mod multiply; @@ -7,7 +7,7 @@ mod multiply; use crate::{GuestAddress, TargetCpu, aarch64::simd::bfloat16::Operand}; pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu, diff --git a/crates/stela-compiler/src/x86_64/simd/bfloat16/conversion.rs b/crates/stela-compiler/src/x86_64/simd/bfloat16/conversion.rs index 3f13edd39f..5da1d9dc7f 100644 --- a/crates/stela-compiler/src/x86_64/simd/bfloat16/conversion.rs +++ b/crates/stela-compiler/src/x86_64/simd/bfloat16/conversion.rs @@ -1,11 +1,14 @@ //! BFCVT/BFCVTN by integer rounding, with a software path for special values. use super::super::super::isa::ShiftOpcode; +use super::super::numerical::helper_section; use super::super::numerical::{ Condition, INPUT_MINIMUM_EXPONENT, branch, exponent_range, guard_ah0_exceptions, integer_rounding_policy, prepare_vector_input_range, quantize_bfloat_packed, quantize_bfloat_scalar_bits, resolve, test_control, vector_exponent_range, }; use super::super::{Host, commit, packed, read_vector}; +use crate::x86_64::asm::{Alu, Code, Gpr, Rm, ShiftOp, Size}; +use crate::x86_64::simd::encode::guest; use crate::{ GuestAddress, GuestState, aarch64::{ @@ -15,7 +18,6 @@ use crate::{ bfloat16::{ConversionMode, ConversionOperand}, }, }, - block::ExitKind, }; use alloc::vec::Vec; @@ -33,21 +35,9 @@ const SINGLE_EXPONENT_BITS: u8 = const EXPONENT_TO_LOW_SHIFT: u8 = SINGLE_BITS - SINGLE_EXPONENT_BITS; const VECTOR_LANES: u32 = 4; const VECTOR_LANE_MASK: u32 = (1 << VECTOR_LANES) - 1; -const TEST_EAX_IMM32: u8 = 0xa9; -const TEST_R10D_R10D: &[u8] = &[0x45, 0x85, 0xd2]; -const MOVD_EAX_XMM1: &[u8] = &[0x66, 0x0f, 0x7e, 0xc8]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const CMP_ECX_IMM32: &[u8] = &[0x81, 0xf9]; -const SHR_EAX_IMM8: &[u8] = &[0xc1, 0xe8]; -const OR_STATE_IMM32: &[u8] = &[0x81, 0x8f]; -const PEXTRW_EAX_XMM0_LOW: &[u8] = &[0x66, 0x0f, 0xc5, 0xc0, 0]; -const MOVD_XMM0_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xc0]; -const PINSRW_XMM0_EAX_LOW: &[u8] = &[0x66, 0x0f, 0xc4, 0xc0, 0]; -const MOVLHPS_XMM1_XMM0: &[u8] = &[0x0f, 0x16, 0xc8]; -const JMP_REL32: u8 = 0xe9; +const LOW_WORD: u8 = 0; -fn input_guard(code: &mut Vec, mode: ConversionMode, helper: &mut Vec) { +fn input_guard(code: &mut Code, mode: ConversionMode, helper: &mut Vec) { if mode == ConversionMode::Scalar { exponent_range(code, Format::Single, SOURCE, INPUT_MINIMUM_EXPONENT); helper.push(branch(code, Condition::AboveOrEqual)); @@ -60,25 +50,24 @@ fn input_guard(code: &mut Vec, mode: ConversionMode, helper: &mut Vec /// Quantize one active Single without packed broadcasts or inactive lane work. /// Shared selectors remain in R8D/R9D/R11D; R10D records only discarded bits. -fn quantize_scalar(code: &mut Vec, helper: &mut Vec) { +fn quantize_scalar(code: &mut Code, helper: &mut Vec) { packed(code, Host::Xor, RESULT, RESULT); - code.extend(MOVD_EAX_XMM1); + code.asm().movd_from_xmm(Gpr::Rax, SOURCE); quantize_bfloat_scalar_bits(code); // Rounded infinity takes the same precise cold OFC/IXC path as narrowing. - code.extend(MOV_ECX_EAX); - code.extend(AND_ECX_IMM32); - code.extend(SINGLE_EXPONENT_MASK.to_le_bytes()); - code.extend(CMP_ECX_IMM32); - code.extend(SINGLE_EXPONENT_MASK.to_le_bytes()); + let mut asm = code.asm(); + asm.mov(Size::Dword, Gpr::Rcx, Gpr::Rax); + asm.alu_imm32(Alu::And, Size::Dword, Gpr::Rcx, SINGLE_EXPONENT_MASK as i32); + asm.alu_imm32(Alu::Cmp, Size::Dword, Gpr::Rcx, SINGLE_EXPONENT_MASK as i32); helper.push(branch(code, Condition::Zero)); - code.extend(SHR_EAX_IMM8); - code.push(DISCARDED_BITS); - code.extend(PINSRW_XMM0_EAX_LOW); + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Gpr::Rax, DISCARDED_BITS); + asm.pinsrw(RESULT, Gpr::Rax, LOW_WORD); } /// Rounding can carry a finite Single into BF16 infinity. The cold core owns /// its OFC/IXC policy; no guest state has changed at this guard. -fn packed_overflow_guard(code: &mut Vec, helper: &mut Vec) { +fn packed_overflow_guard(code: &mut Code, helper: &mut Vec) { packed(code, Host::MoveAligned, TEMPORARY, RESULT); ShiftOpcode::LeftDword.emit(code, TEMPORARY, SIGN_BITS); ShiftOpcode::RightDword.emit(code, TEMPORARY, EXPONENT_TO_LOW_SHIFT); @@ -86,51 +75,42 @@ fn packed_overflow_guard(code: &mut Vec, helper: &mut Vec) { ShiftOpcode::RightDword.emit(code, CONSTANT, EXPONENT_TO_LOW_SHIFT); packed(code, Host::EqualDword, TEMPORARY, CONSTANT); packed(code, Host::DwordSignMask, GPR_RAX, TEMPORARY); - code.push(TEST_EAX_IMM32); - code.extend(VECTOR_LANE_MASK.to_le_bytes()); + code.asm() + .test_accumulator_imm(Size::Dword, VECTOR_LANE_MASK as i32); helper.push(branch(code, Condition::NotZero)); } -fn helper_section(code: &mut Vec, helper: &[usize], pc: GuestAddress) { - code.push(JMP_REL32); - let completed = code.len(); - code.extend(0i32.to_le_bytes()); - let helper_start = code.len(); - super::super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); - let success = code.len(); - for &patch in helper { - resolve(code, patch, helper_start); - } - resolve(code, completed, success); -} - -fn commit_inexact(code: &mut Vec) { +fn commit_inexact(code: &mut Code) { test_control(code, FPCR_AH); let suppressed = branch(code, Condition::NotZero); - code.extend(TEST_R10D_R10D); + code.asm().test(Size::Dword, Gpr::R10, Gpr::R10); let exact = branch(code, Condition::Zero); - code.extend(OR_STATE_IMM32); - code.extend((core::mem::offset_of!(GuestState, fpsr) as u32).to_le_bytes()); - code.extend(INEXACT.to_le_bytes()); + code.asm().alu_imm32( + Alu::Or, + Size::Dword, + guest(core::mem::offset_of!(GuestState, fpsr) as u32), + INEXACT as i32, + ); let ready = code.len(); resolve(code, exact, ready); resolve(code, suppressed, ready); } -fn scalar_commit(code: &mut Vec, destination: u8) { +fn scalar_commit(code: &mut Code, destination: u8) { // PEXTRW zero-extends the low BF16 encoding before MOVD clears all upper bits. - code.extend(PEXTRW_EAX_XMM0_LOW); - code.extend(MOVD_XMM0_EAX); + let mut asm = code.asm(); + asm.pextrw(Gpr::Rax, RESULT, LOW_WORD); + asm.movd_to_xmm(RESULT, Gpr::Rax); test_control(code, FPCR_NEP); let clearing = branch(code, Condition::Zero); read_vector(code, destination, RESULT); - code.extend(PINSRW_XMM0_EAX_LOW); + code.asm().pinsrw(RESULT, Gpr::Rax, LOW_WORD); let ready = code.len(); resolve(code, clearing, ready); commit(code, destination, RESULT); } -pub(in crate::x86_64) fn emit(code: &mut Vec, operand: &ConversionOperand, pc: GuestAddress) { +pub(in crate::x86_64) fn emit(code: &mut Code, operand: &ConversionOperand, pc: GuestAddress) { let mut helper = Vec::new(); guard_ah0_exceptions(code, &mut helper); read_vector(code, operand.source, SOURCE); @@ -157,7 +137,7 @@ pub(in crate::x86_64) fn emit(code: &mut Vec, operand: &ConversionOperand, p ConversionMode::Narrow { upper: true } => { // Original Vd is still available, including when Vd aliases Vn. read_vector(code, operand.destination, SOURCE); - code.extend(MOVLHPS_XMM1_XMM0); + code.asm().movlhps(SOURCE, Rm::Xmm(RESULT)); commit(code, operand.destination, SOURCE); } } @@ -165,7 +145,7 @@ pub(in crate::x86_64) fn emit(code: &mut Vec, operand: &ConversionOperand, p /// Prepare selectors once; preserves every XMM and RSP. R8/R9/R11 retain /// rounding selectors and R10 starts fresh. AH selects mandatory nearest-even. -pub(in crate::x86_64) fn prepare_conversion_rounding(code: &mut Vec) { +pub(in crate::x86_64) fn prepare_conversion_rounding(code: &mut Code) { integer_rounding_policy(code, DISCARDED_BITS, true); } @@ -173,29 +153,26 @@ pub(in crate::x86_64) fn prepare_conversion_rounding(code: &mut Vec) { /// survives; result XMM0 retains rounded Single fields, XMM2..5 are scratch. /// R8/R9/R11 selectors survive; R10 records discarded lanes. RAX/RCX/RDX and /// flags are scratch. No frame, environment, state writes, or packed slot layout. -pub(in crate::x86_64) fn quantize_normal_conversion(code: &mut Vec, failures: &mut Vec) { +pub(in crate::x86_64) fn quantize_normal_conversion(code: &mut Code, failures: &mut Vec) { input_guard(code, ConversionMode::Narrow { upper: false }, failures); quantize_bfloat_packed(code); packed_overflow_guard(code, failures); } /// Callers gate this on any active lane and the effective FA64 policy. -pub(in crate::x86_64) fn guard_conversion_enables(code: &mut Vec, failures: &mut Vec) { +pub(in crate::x86_64) fn guard_conversion_enables(code: &mut Code, failures: &mut Vec) { guard_ah0_exceptions(code, failures); } /// Return approved fresh BF IXC in EAX without committing guest state. AH1 /// suppresses all numerical exceptions; accepted normal lanes can only add IXC. -pub(in crate::x86_64) fn conversion_inexact(code: &mut Vec) { - const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; - const MOV_EAX_IMM32: u8 = 0xb8; - code.extend(XOR_EAX_EAX); +pub(in crate::x86_64) fn conversion_inexact(code: &mut Code) { + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); test_control(code, FPCR_AH); let suppressed = branch(code, Condition::NotZero); - code.extend(TEST_R10D_R10D); + code.asm().test(Size::Dword, Gpr::R10, Gpr::R10); let exact = branch(code, Condition::Zero); - code.push(MOV_EAX_IMM32); - code.extend(INEXACT.to_le_bytes()); + code.asm().mov_imm32(Gpr::Rax, INEXACT); let end = code.len(); resolve(code, exact, end); resolve(code, suppressed, end); diff --git a/crates/stela-compiler/src/x86_64/simd/bfloat16/dot.rs b/crates/stela-compiler/src/x86_64/simd/bfloat16/dot.rs index 5f53586741..6518ce2850 100644 --- a/crates/stela-compiler/src/x86_64/simd/bfloat16/dot.rs +++ b/crates/stela-compiler/src/x86_64/simd/bfloat16/dot.rs @@ -1,12 +1,15 @@ //! BFDOT with fixed round-to-odd intermediates. use super::super::super::isa::ShiftOpcode; +use super::super::numerical::single_vector_arithmetic; use super::super::numerical::{ ArithmeticOpcode, Condition, ENVIRONMENT_STACK_BYTES, MXCSR_INEXACT, Rounding, branch, - capture_environment_status, clear_environment_status, emit_opcode_to, environment_round, + capture_environment_status, clear_environment_status, environment_round, jump, prepare_vector_input_range, read_numerical_vector, reject_other_status, resolve, restore_environment, vector_exponent_range, }; use super::super::{Host, commit, packed, read_vector, shuffle}; +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Rm, Size}; use crate::{ GuestAddress, TargetCpu, aarch64::{ @@ -42,24 +45,22 @@ const MATRIX_LEFT_PAIRS: u8 = 0xa0; // Dwords [0, 0, 2, 2]. const MATRIX_RIGHT_PAIRS: u8 = 0x88; // Dwords [0, 2, 0, 2]. const MATRIX_STAGES: u8 = 2; const PAIR_BYTES: u8 = (2 * BFLOAT16_BITS / u8::BITS) as u8; -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const SSE_ESCAPE: u8 = 0x0f; -const FLOAT_COMPARE_OPCODE: u8 = 0xc2; const EQUAL_PREDICATE: u8 = 0; -const JMP_REL32: u8 = 0xe9; -const AND_EAX_IMM8: &[u8] = &[0x83, 0xe0]; -const CMP_EAX_IMM8: &[u8] = &[0x83, 0xf8]; -const TEST_ECX_IMM32: &[u8] = &[0xf7, 0xc1]; const MATRIX_FRAME_BYTES: u8 = 16; -const SUB_RSP_MATRIX_FRAME: &[u8] = &[0x48, 0x83, 0xec, MATRIX_FRAME_BYTES]; -const ADD_RSP_MATRIX_FRAME: &[u8] = &[0x48, 0x83, 0xc4, MATRIX_FRAME_BYTES]; -const RSP_DISPLACEMENT_MODRM: u8 = 0x44; -const RSP_SIB: u8 = 0x24; -const ZERO_MATRIX_COUNTER: &[u8] = &[0x45, 0x31, 0xc0]; // XOR R8D,R8D. -const TEST_MATRIX_COUNTER: &[u8] = &[0x45, 0x85, 0xc0]; // TEST R8D,R8D. -const INCREMENT_MATRIX_COUNTER: &[u8] = &[0x41, 0xff, 0xc0]; -const CMP_MATRIX_COUNTER_IMM8: &[u8] = &[0x41, 0x83, 0xf8]; +/// R8D counts completed matrix stages. +const MATRIX_COUNTER: Gpr = Gpr::R8; + +/// Reserve (`Alu::Sub`) or release (`Alu::Add`) the matrix accumulator frame. +fn matrix_frame(code: &mut Code, op: Alu) { + code.asm() + .alu_imm8(op, Size::Qword, Gpr::Rsp, MATRIX_FRAME_BYTES as i8); +} + +/// The matrix's private accumulator, above the numerical environment's +/// sixteen-byte save area. +fn accumulator_slot() -> Mem { + Mem::base_disp8(Gpr::Rsp, ENVIRONMENT_STACK_BYTES as i8) +} #[derive(Clone, Copy)] enum SumCheck { @@ -67,32 +68,21 @@ enum SumCheck { ExactVector, } -fn arithmetic(code: &mut Vec, opcode: ArithmeticOpcode, destination: u8, source: u8) { - emit_opcode_to( - code, - Format::Single, - Shape::Vector128, - opcode, +fn compare_equal(code: &mut Code, destination: u8, source: u8) { + code.asm().float_compare( + FloatLanes::PackedSingle, destination, - source, + Rm::Xmm(source), + EQUAL_PREDICATE, ); } -fn compare_equal(code: &mut Vec, destination: u8, source: u8) { - code.extend([ - SSE_ESCAPE, - FLOAT_COMPARE_OPCODE, - REGISTER_DIRECT | destination << MODRM_REGISTER_SHIFT | source, - EQUAL_PREDICATE, - ]); -} - -fn guard_normal(code: &mut Vec, shape: Shape, source: u8, rollback: &mut Vec) { +fn guard_normal(code: &mut Code, shape: Shape, source: u8, rollback: &mut Vec) { vector_exponent_range(code, Format::Single, shape, source); rollback.push(branch(code, Condition::NotZero)); } -fn guard_normal_or_zero(code: &mut Vec, shape: Shape, source: u8, rollback: &mut Vec) { +fn guard_normal_or_zero(code: &mut Code, shape: Shape, source: u8, rollback: &mut Vec) { // The shared classifier leaves its per-lane normal mask in XMM2. Admit // only raw signed zeros as well; BF subnormals require architectural flush. vector_exponent_range(code, Format::Single, shape, source); @@ -106,21 +96,20 @@ fn guard_normal_or_zero(code: &mut Vec, shape: Shape, source: u8, rollback: Shape::Vector128 => ALL_SINGLE_LANE_MASK, Shape::Scalar => unreachable!("BF16 dot requires vector lanes"), }; + let mut asm = code.asm(); if shape == Shape::Vector64 { - code.extend(AND_EAX_IMM8); - code.push(mask); + asm.alu_imm8(Alu::And, Size::Dword, Gpr::Rax, mask as i8); } - code.extend(CMP_EAX_IMM8); - code.push(mask); + asm.alu_imm8(Alu::Cmp, Size::Dword, Gpr::Rax, mask as i8); rollback.push(branch(code, Condition::NotZero)); } -fn guard_real_status(code: &mut Vec, rollback: &mut Vec) { +fn guard_real_status(code: &mut Code, rollback: &mut Vec) { capture_environment_status(code); rollback.push(reject_other_status(code)); } -fn widen_pairs(code: &mut Vec, shape: Shape) { +fn widen_pairs(code: &mut Code, shape: Shape) { for (even, odd) in [(LEFT, LEFT_ODD), (RIGHT, RIGHT_ODD)] { packed(code, Host::MoveAligned, odd, even); ShiftOpcode::RightDword.emit(code, odd, BFLOAT16_BITS as u8); @@ -135,9 +124,9 @@ fn widen_pairs(code: &mut Vec, shape: Shape) { } } -fn odd_add(code: &mut Vec, shape: Shape, rollback: &mut Vec, check: SumCheck) { +fn odd_add(code: &mut Code, shape: Shape, rollback: &mut Vec, check: SumCheck) { packed(code, Host::MoveAligned, ORIGINAL_LEFT, LEFT); - arithmetic(code, ArithmeticOpcode::Add, LEFT, RIGHT); + single_vector_arithmetic(code, ArithmeticOpcode::Add, LEFT, RIGHT); // Round-toward-zero overflow can clamp to the largest finite value, so // check the host status before the result classifier or residual hides it. guard_real_status(code, rollback); @@ -148,8 +137,8 @@ fn odd_add(code: &mut Vec, shape: Shape, rollback: &mut Vec, check: S // inexact vectors retain the per-lane residual check. Keep the preceding // result guard: exact subnormal cancellation must still use BF flushing. let exact = if matches!(check, SumCheck::ExactVector) { - code.extend(TEST_ECX_IMM32); - code.extend(MXCSR_INEXACT.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Gpr::Rcx, MXCSR_INEXACT as i32); Some(branch(code, Condition::Zero)) } else { None @@ -159,7 +148,7 @@ fn odd_add(code: &mut Vec, shape: Shape, rollback: &mut Vec, check: S // operand's residual is exact by Sterbenz and differs from the other input. // Numeric equality also admits signed-zero inputs and exact cancellation. packed(code, Host::MoveAligned, FIRST_RESIDUAL, LEFT); - arithmetic( + single_vector_arithmetic( code, ArithmeticOpcode::Subtract, FIRST_RESIDUAL, @@ -167,7 +156,7 @@ fn odd_add(code: &mut Vec, shape: Shape, rollback: &mut Vec, check: S ); compare_equal(code, FIRST_RESIDUAL, RIGHT); packed(code, Host::MoveAligned, SECOND_RESIDUAL, LEFT); - arithmetic(code, ArithmeticOpcode::Subtract, SECOND_RESIDUAL, RIGHT); + single_vector_arithmetic(code, ArithmeticOpcode::Subtract, SECOND_RESIDUAL, RIGHT); compare_equal(code, SECOND_RESIDUAL, ORIGINAL_LEFT); packed(code, Host::And, FIRST_RESIDUAL, SECOND_RESIDUAL); packed(code, Host::EqualDword, ODD_BIT, ODD_BIT); @@ -183,14 +172,14 @@ fn odd_add(code: &mut Vec, shape: Shape, rollback: &mut Vec, check: S clear_environment_status(code); } -fn pair_sum(code: &mut Vec, shape: Shape, rollback: &mut Vec, check: SumCheck) { +fn pair_sum(code: &mut Code, shape: Shape, rollback: &mut Vec, check: SumCheck) { widen_pairs(code, shape); prepare_vector_input_range(code, Format::Single); for source in [LEFT, RIGHT, LEFT_ODD, RIGHT_ODD] { guard_normal(code, shape, source, rollback); } - arithmetic(code, ArithmeticOpcode::Multiply, LEFT, RIGHT); - arithmetic(code, ArithmeticOpcode::Multiply, LEFT_ODD, RIGHT_ODD); + single_vector_arithmetic(code, ArithmeticOpcode::Multiply, LEFT, RIGHT); + single_vector_arithmetic(code, ArithmeticOpcode::Multiply, LEFT_ODD, RIGHT_ODD); guard_real_status(code, rollback); // BF16 products have at most sixteen significant bits. Every admitted // normal Single product is exact; tiny/overflowing stages use the core. @@ -200,21 +189,20 @@ fn pair_sum(code: &mut Vec, shape: Shape, rollback: &mut Vec, check: odd_add(code, shape, rollback, check); } -fn add_accumulator(code: &mut Vec, shape: Shape, rollback: &mut Vec, check: SumCheck) { +fn add_accumulator(code: &mut Code, shape: Shape, rollback: &mut Vec, check: SumCheck) { prepare_vector_input_range(code, Format::Single); guard_normal_or_zero(code, shape, RIGHT, rollback); odd_add(code, shape, rollback, check); } -fn matrix_accumulator(code: &mut Vec, opcode: Host) { +fn matrix_accumulator(code: &mut Code, opcode: Host) { // The matrix's private accumulator is above the numerical environment's // sixteen-byte save area; no guest destination is written between stages. - opcode.append(code, TargetCpu::Baseline); - code.extend([RSP_DISPLACEMENT_MODRM, RSP_SIB, ENVIRONMENT_STACK_BYTES]); + opcode.emit(code, LEFT, accumulator_slot(), TargetCpu::Baseline); } fn finish( - code: &mut Vec, + code: &mut Code, shape: Shape, destination: u8, pc: GuestAddress, @@ -223,16 +211,14 @@ fn finish( ) { restore_environment(code); if matrix { - code.extend(ADD_RSP_MATRIX_FRAME); + matrix_frame(code, Alu::Add); } // A successful path must skip the cold helper regardless of arithmetic flags. - code.push(JMP_REL32); - let completed = code.len(); - code.extend(0_i32.to_le_bytes()); + let completed = jump(code); let rollback_start = code.len(); restore_environment(code); if matrix { - code.extend(ADD_RSP_MATRIX_FRAME); + matrix_frame(code, Alu::Add); } super::super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); let commit_start = code.len(); @@ -246,7 +232,7 @@ fn finish( commit(code, destination, LEFT); } -pub(in crate::x86_64) fn emit_dot(code: &mut Vec, operand: &DotOperand, pc: GuestAddress) { +pub(in crate::x86_64) fn emit_dot(code: &mut Code, operand: &DotOperand, pc: GuestAddress) { let mut rollback = Vec::new(); environment_round(code, Rounding::Zero); read_vector(code, operand.left, LEFT); @@ -272,23 +258,20 @@ pub(in crate::x86_64) fn emit_dot(code: &mut Vec, operand: &DotOperand, pc: ); } -pub(in crate::x86_64) fn emit_matrix( - code: &mut Vec, - operand: &MatrixOperand, - pc: GuestAddress, -) { +pub(in crate::x86_64) fn emit_matrix(code: &mut Code, operand: &MatrixOperand, pc: GuestAddress) { let mut rollback = Vec::new(); - code.extend(SUB_RSP_MATRIX_FRAME); + matrix_frame(code, Alu::Sub); environment_round(code, Rounding::Zero); read_vector(code, operand.destination, LEFT); matrix_accumulator(code, Host::StoreUnaligned); - code.extend(ZERO_MATRIX_COUNTER); + code.asm() + .alu(Alu::Xor, Size::Dword, MATRIX_COUNTER, MATRIX_COUNTER); let next_stage = code.len(); // Reloads see the original inputs until the single final commit, including // Vd=Vn, Vd=Vm and full aliasing. read_vector(code, operand.left, LEFT); read_vector(code, operand.right, RIGHT); - code.extend(TEST_MATRIX_COUNTER); + code.asm().test(Size::Dword, MATRIX_COUNTER, MATRIX_COUNTER); let first_stage = branch(code, Condition::Zero); for source in [LEFT, RIGHT] { ShiftOpcode::RightBytes.emit(code, source, PAIR_BYTES); @@ -299,17 +282,12 @@ pub(in crate::x86_64) fn emit_matrix( shuffle(code, RIGHT, RIGHT, MATRIX_RIGHT_PAIRS); pair_sum(code, Shape::Vector128, &mut rollback, SumCheck::ExactVector); // Load the previous accumulator into XMM1, then save the new XMM0 value. - Host::LoadUnaligned.append(code, TargetCpu::Baseline); - code.extend([ - RSP_DISPLACEMENT_MODRM | RIGHT << MODRM_REGISTER_SHIFT, - RSP_SIB, - ENVIRONMENT_STACK_BYTES, - ]); + Host::LoadUnaligned.emit(code, RIGHT, accumulator_slot(), TargetCpu::Baseline); add_accumulator(code, Shape::Vector128, &mut rollback, SumCheck::ExactVector); matrix_accumulator(code, Host::StoreUnaligned); - code.extend(INCREMENT_MATRIX_COUNTER); - code.extend(CMP_MATRIX_COUNTER_IMM8); - code.push(MATRIX_STAGES); + let mut asm = code.asm(); + asm.inc(Size::Dword, MATRIX_COUNTER); + asm.alu_imm8(Alu::Cmp, Size::Dword, MATRIX_COUNTER, MATRIX_STAGES as i8); let repeat = branch(code, Condition::Below); resolve(code, repeat, next_stage); finish( diff --git a/crates/stela-compiler/src/x86_64/simd/bfloat16/multiply.rs b/crates/stela-compiler/src/x86_64/simd/bfloat16/multiply.rs index df94a00472..f20631932f 100644 --- a/crates/stela-compiler/src/x86_64/simd/bfloat16/multiply.rs +++ b/crates/stela-compiler/src/x86_64/simd/bfloat16/multiply.rs @@ -1,13 +1,14 @@ //! BFMLAL with SSE2 or FMA3. use super::super::super::isa::ShiftOpcode; use super::super::numerical::{ - ArithmeticOpcode, Condition, FusedOpcode, VZEROUPPER, branch, commit_ah0_inexact, emit_fma, - emit_opcode, environment_alternative_nearest, guard_ah0_exceptions, prepare_vector_input_range, + ArithmeticOpcode, Condition, FusedOpcode, branch, commit_ah0_inexact, emit_fma, emit_opcode, + environment_alternative_nearest, guard_ah0_exceptions, prepare_vector_input_range, prepare_vector_result_range, reject_other_status, reject_product_status, resolve, restore_environment, restore_environment_with_product, save_product_status, vector_exponent_range, }; use super::super::{commit, read_vector, shuffle}; +use crate::x86_64::asm::Code; use crate::{ GuestAddress, TargetCpu, aarch64::{ @@ -31,7 +32,7 @@ const FIRST_LANE: u8 = 0; const OUTPUT_SHAPE: Shape = Shape::Vector128; const BFLOAT16_BYTES: u32 = BFLOAT16_BITS / u8::BITS; -fn select_vector(code: &mut Vec, source: u8, vector: u8, parity: Parity) { +fn select_vector(code: &mut Code, source: u8, vector: u8, parity: Parity) { read_vector(code, source, vector); if parity == Parity::Odd { ShiftOpcode::RightDword.emit(code, vector, BFLOAT16_BITS as u8); @@ -41,7 +42,7 @@ fn select_vector(code: &mut Vec, source: u8, vector: u8, parity: Parity) { ShiftOpcode::LeftDword.emit(code, vector, BFLOAT16_TO_SINGLE_SHIFT as u8); } -fn prepare_sources(code: &mut Vec, operand: &MultiplyOperand) { +fn prepare_sources(code: &mut Code, operand: &MultiplyOperand) { select_vector(code, operand.left, LEFT, operand.parity); match operand.right { MultiplySource::Vector(source) => select_vector(code, source, RIGHT, operand.parity), @@ -66,14 +67,14 @@ fn prepare_sources(code: &mut Vec, operand: &MultiplyOperand) { } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &MultiplyOperand, pc: GuestAddress, target: TargetCpu, ) { let native_fma = target.supports(TargetCpu::Fma); if native_fma { - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } let mut helper = Vec::new(); guard_ah0_exceptions(code, &mut helper); diff --git a/crates/stela-compiler/src/x86_64/simd/comparison.rs b/crates/stela-compiler/src/x86_64/simd/comparison.rs index ff7dfd93d5..027928dc9c 100644 --- a/crates/stela-compiler/src/x86_64/simd/comparison.rs +++ b/crates/stela-compiler/src/x86_64/simd/comparison.rs @@ -5,7 +5,11 @@ use super::numerical::{ clear_scalar, exponent_range, prepare_vector_input_range, read_numerical_vector, resolve, test_control, vector_exponent_range, }; +use super::numerical::{helper_section, jump}; use super::{Host, commit, packed, read_vector}; +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Rm, ShiftOp, Size}; +use crate::x86_64::simd::encode::{cond, guest}; use crate::{ GuestAddress, GuestState, TargetCpu, aarch64::{ @@ -16,7 +20,6 @@ use crate::{ comparison::{CompareSource, Operand}, }, }, - block::ExitKind, }; use alloc::vec::Vec; @@ -30,15 +33,6 @@ const TEMP_VECTOR: u8 = 7; const SIGN_BITS: u8 = 1; const HALF_SIGN_SHIFT: u8 = u16::BITS as u8 - SIGN_BITS; const SINGLE_SIGN_SHIFT: u8 = u32::BITS as u8 - SIGN_BITS; -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const CMOV_EAX_EDX_MODRM: u8 = 0xc2; -const MOVD_EAX_XMM_PREFIX: &[u8] = &[0x66, 0x0f, 0x7e]; -const SSE_ESCAPE: u8 = 0x0f; -const FLOAT_COMPARE_OPCODE: u8 = 0xc2; -const SCALAR_SINGLE_PREFIX: u8 = 0xf3; -const SCALAR_DOUBLE_PREFIX: u8 = 0xf2; -const PACKED_DOUBLE_PREFIX: u8 = 0x66; const COMPARE_EQUAL: u8 = 0; const COMPARE_LESS: u8 = 1; const COMPARE_LESS_EQUAL: u8 = 2; @@ -49,65 +43,45 @@ const SINGLE_FULL_MASK: u32 = 0x0f; const DOUBLE_FULL_MASK: u32 = 0x05; const ADJACENT_DWORDS: u8 = 0xb1; const QWORD_HIGH_DWORDS: u8 = 0xf5; -const UCOMISS_XMM0_XMM1: &[u8] = &[0x0f, 0x2e, 0xc1]; -const UCOMISD_XMM0_XMM1: &[u8] = &[0x66, 0x0f, 0x2e, 0xc1]; -const CMP_AX_CX: &[u8] = &[0x66, 0x39, 0xc8]; -const MOVD_EAX_XMM0: &[u8] = &[0x66, 0x0f, 0x7e, 0xc0]; -const MOVD_ECX_XMM0: &[u8] = &[0x66, 0x0f, 0x7e, 0xc1]; -const MOVD_ECX_XMM1: &[u8] = &[0x66, 0x0f, 0x7e, 0xc9]; -const MOVQ_RAX_XMM0: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xc0]; -const MOVQ_RCX_XMM0: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xc1]; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_EDX_IMMEDIATE: u8 = 0xba; -const STORE_STATE_EAX: &[u8] = &[0x89, 0x87]; -const STORE_STATE_IMMEDIATE: &[u8] = &[0xc7, 0x87]; -const SHL_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe0]; -const SHL_RAX_IMMEDIATE: &[u8] = &[0x48, 0xc1, 0xe0]; -const SHL_CX_1: &[u8] = &[0x66, 0xc1, 0xe1, 1]; -const SHL_ECX_1: &[u8] = &[0xc1, 0xe1, 1]; -const SHL_RCX_1: &[u8] = &[0x48, 0xc1, 0xe1, 1]; -const TEST_CX_CX: &[u8] = &[0x66, 0x85, 0xc9]; -const TEST_ECX_ECX: &[u8] = &[0x85, 0xc9]; -const TEST_RCX_RCX: &[u8] = &[0x48, 0x85, 0xc9]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const CMP_EAX_IMMEDIATE: u8 = 0x3d; -const JMP_RELATIVE: u8 = 0xe9; -const MOVSS_XMM6_XMM0: &[u8] = &[0xf3, 0x0f, 0x10, 0xf0]; -const MOVSD_XMM6_XMM0: &[u8] = &[0xf2, 0x0f, 0x10, 0xf0]; -const PINSRW_XMM6_EAX_0: &[u8] = &[0x66, 0x0f, 0xc4, 0xf0, 0]; -#[repr(u8)] -enum FlagSelect { - Equal = 0x44, - Below = 0x42, - Less = 0x4c, - Sign = 0x48, -} - -fn jump(code: &mut Vec) -> usize { - code.push(JMP_RELATIVE); - let patch = code.len(); - code.extend(0i32.to_le_bytes()); - patch -} - -fn helper_section(code: &mut Vec, helper: &[usize], pc: GuestAddress) { - let completed = jump(code); - let helper_start = code.len(); - super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); - let success_start = code.len(); - for &patch in helper { - resolve(code, patch, helper_start); +/// The lane-width operand size of a scalar `format` value. +fn lane_size(format: Format) -> Size { + match format { + Format::Half => Size::Word, + Format::Single => Size::Dword, + Format::Double => Size::Qword, } - resolve(code, completed, success_start); } -fn exception_guard(code: &mut Vec, helper: &mut Vec) { +/// The GPR width that holds a scalar `format` value: a quadword for Double, +/// otherwise a doubleword. +fn register_size(format: Format) -> Size { + if format == Format::Double { + Size::Qword + } else { + Size::Dword + } +} + +/// Move the low `format` lane of `vector` into `register`. +fn move_scalar(code: &mut Code, format: Format, register: Gpr, vector: u8) { + if format == Format::Double { + code.asm().movq_from_xmm(register, vector); + } else { + code.asm().movd_from_xmm(register, vector); + } +} + +fn nzcv() -> crate::x86_64::asm::Mem { + guest(core::mem::offset_of!(GuestState, nzcv) as u32) +} + +fn exception_guard(code: &mut Code, helper: &mut Vec) { test_control(code, FPCR_EXCEPTION_ENABLE_MASK); helper.push(branch(code, Condition::NotZero)); } -fn scalar_normal_guard(code: &mut Vec, format: Format, source: u8, helper: &mut Vec) { +fn scalar_normal_guard(code: &mut Code, format: Format, source: u8, helper: &mut Vec) { exponent_range(code, format, source, INPUT_MINIMUM_EXPONENT); helper.push(branch(code, Condition::AboveOrEqual)); } @@ -115,20 +89,19 @@ fn scalar_normal_guard(code: &mut Vec, format: Format, source: u8, helper: & /// A zero comparison also accepts signed zero and infinity. A zero fraction /// proves one of those classes or an exact normal power of two; remaining /// values must pass the ordinary normal guard. No subnormal or NaN executes. -fn scalar_zero_guard(code: &mut Vec, format: Format, helper: &mut Vec) { - code.extend(if format == Format::Double { - MOVQ_RAX_XMM0 - } else { - MOVD_EAX_XMM0 - }); +fn scalar_zero_guard(code: &mut Code, format: Format, helper: &mut Vec) { + move_scalar(code, format, Gpr::Rax, LEFT_VECTOR); let register_bits = if format == Format::Double { - code.extend(SHL_RAX_IMMEDIATE); u64::BITS } else { - code.extend(SHL_EAX_IMMEDIATE); u32::BITS }; - code.push((register_bits - format.fraction_bits()) as u8); + code.asm().shift_imm( + ShiftOp::Shl, + register_size(format), + Gpr::Rax, + (register_bits - format.fraction_bits()) as u8, + ); let zero_fraction = branch(code, Condition::Zero); scalar_normal_guard(code, format, LEFT_VECTOR, helper); let accepted = code.len(); @@ -162,7 +135,7 @@ fn shift_right(format: Format) -> ShiftOpcode { } } -fn equal_zero(code: &mut Vec, format: Format, value: u8, zero: u8, temporary: u8) { +fn equal_zero(code: &mut Code, format: Format, value: u8, zero: u8, temporary: u8) { packed( code, if format == Format::Half { @@ -179,7 +152,7 @@ fn equal_zero(code: &mut Vec, format: Format, value: u8, zero: u8, temporary } } -fn vector_zero_guard(code: &mut Vec, format: Format, shape: Shape, helper: &mut Vec) { +fn vector_zero_guard(code: &mut Code, format: Format, shape: Shape, helper: &mut Vec) { // The shared range leaves per-lane normal validity in EXPONENT_VECTOR. // OR fraction-zero validity into it: only zeros/infinities are newly // admitted, and none can change host MXCSR or guest FPSR. @@ -204,86 +177,57 @@ fn vector_zero_guard(code: &mut Vec, format: Format, shape: Shape, helper: & } else { Host::DwordSignMask.register(code, 0, EXPONENT_VECTOR, TargetCpu::Baseline); } - let mask = active_mask(format, shape); - code.push(AND_EAX_IMMEDIATE); - code.extend(mask.to_le_bytes()); - code.push(CMP_EAX_IMMEDIATE); - code.extend(mask.to_le_bytes()); + let mask = active_mask(format, shape) as i32; + let mut asm = code.asm(); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, mask); + asm.alu_accumulator_imm32(Alu::Cmp, Size::Dword, mask); helper.push(branch(code, Condition::NotZero)); } /// Signed order key for nonzero normal half values. Sign-complementing the /// fraction/exponent reverses negative magnitudes without a host FP operation. -fn half_order_key(code: &mut Vec, vector: u8) { +fn half_order_key(code: &mut Code, vector: u8) { packed(code, Host::MoveAligned, TEMP_VECTOR, vector); ShiftOpcode::ArithmeticWord.emit(code, TEMP_VECTOR, HALF_SIGN_SHIFT); ShiftOpcode::RightWord.emit(code, TEMP_VECTOR, SIGN_BITS); packed(code, Host::Xor, vector, TEMP_VECTOR); } -fn select_flags(code: &mut Vec, condition: FlagSelect) { - code.extend([SSE_ESCAPE, condition as u8, CMOV_EAX_EDX_MODRM]); +/// EAX takes EDX's flags when `condition` holds. +fn select_flags(code: &mut Code, condition: Cond) { + code.asm().cmov(condition, Size::Dword, Gpr::Rax, Gpr::Rdx); } -fn store_flags(code: &mut Vec) { - code.extend(STORE_STATE_EAX); - code.extend((core::mem::offset_of!(GuestState, nzcv) as u32).to_le_bytes()); +fn store_flags(code: &mut Code) { + code.asm().mov_store(Size::Dword, nzcv(), Gpr::Rax); } -fn ordered_flags(code: &mut Vec, integer: bool) { - code.push(MOV_EAX_IMMEDIATE); - code.extend(NZCV_C.to_le_bytes()); - code.push(MOV_EDX_IMMEDIATE); - code.extend(NZCV_N.to_le_bytes()); - select_flags( - code, - if integer { - FlagSelect::Less - } else { - FlagSelect::Below - }, - ); - code.push(MOV_EDX_IMMEDIATE); - code.extend((NZCV_Z | NZCV_C).to_le_bytes()); - select_flags(code, FlagSelect::Equal); +fn ordered_flags(code: &mut Code, integer: bool) { + let mut asm = code.asm(); + asm.mov_imm32(Gpr::Rax, NZCV_C); + asm.mov_imm32(Gpr::Rdx, NZCV_N); + select_flags(code, if integer { Cond::L } else { Cond::B }); + code.asm().mov_imm32(Gpr::Rdx, NZCV_Z | NZCV_C); + select_flags(code, Cond::E); store_flags(code); } -fn zero_flags(code: &mut Vec, format: Format) { - code.extend(if format == Format::Double { - MOVQ_RCX_XMM0 - } else { - MOVD_ECX_XMM0 - }); - code.extend(match format { - Format::Half => TEST_CX_CX, - Format::Single => TEST_ECX_ECX, - Format::Double => TEST_RCX_RCX, - }); - code.push(MOV_EAX_IMMEDIATE); - code.extend(NZCV_C.to_le_bytes()); - code.push(MOV_EDX_IMMEDIATE); - code.extend(NZCV_N.to_le_bytes()); - select_flags(code, FlagSelect::Sign); +fn zero_flags(code: &mut Code, format: Format) { + move_scalar(code, format, Gpr::Rcx, LEFT_VECTOR); + let mut asm = code.asm(); + asm.test(lane_size(format), Gpr::Rcx, Gpr::Rcx); + asm.mov_imm32(Gpr::Rax, NZCV_C); + asm.mov_imm32(Gpr::Rdx, NZCV_N); + select_flags(code, Cond::S); // Shift off the sign at the lane width; both +0 and -0 set ZF. - code.extend(match format { - Format::Half => SHL_CX_1, - Format::Single => SHL_ECX_1, - Format::Double => SHL_RCX_1, - }); - code.push(MOV_EDX_IMMEDIATE); - code.extend((NZCV_Z | NZCV_C).to_le_bytes()); - select_flags(code, FlagSelect::Equal); + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shl, lane_size(format), Gpr::Rcx, 1); + asm.mov_imm32(Gpr::Rdx, NZCV_Z | NZCV_C); + select_flags(code, Cond::E); store_flags(code); } -fn emit_flags( - code: &mut Vec, - format: Format, - left: u8, - right: CompareSource, - pc: GuestAddress, -) { +fn emit_flags(code: &mut Code, format: Format, left: u8, right: CompareSource, pc: GuestAddress) { let mut helper = Vec::new(); exception_guard(code, &mut helper); read_vector(code, left, LEFT_VECTOR); @@ -295,15 +239,14 @@ fn emit_flags( if format == Format::Half { half_order_key(code, LEFT_VECTOR); half_order_key(code, RIGHT_VECTOR); - code.extend(MOVD_EAX_XMM0); - code.extend(MOVD_ECX_XMM1); - code.extend(CMP_AX_CX); + let mut asm = code.asm(); + asm.movd_from_xmm(Gpr::Rax, LEFT_VECTOR); + asm.movd_from_xmm(Gpr::Rcx, RIGHT_VECTOR); + asm.alu(Alu::Cmp, Size::Word, Gpr::Rax, Gpr::Rcx); + } else if format == Format::Double { + code.asm().ucomisd(LEFT_VECTOR, Rm::Xmm(RIGHT_VECTOR)); } else { - code.extend(if format == Format::Double { - UCOMISD_XMM0_XMM1 - } else { - UCOMISS_XMM0_XMM1 - }); + code.asm().ucomiss(LEFT_VECTOR, Rm::Xmm(RIGHT_VECTOR)); } // JMP and the unexecuted helper preserve the comparison flags. helper_section(code, &helper, pc); @@ -316,7 +259,7 @@ fn emit_flags( } fn emit_conditional_flags( - code: &mut Vec, + code: &mut Code, format: Format, left: u8, right: u8, @@ -325,20 +268,18 @@ fn emit_conditional_flags( pc: GuestAddress, ) { // A false condition bypasses numerical enables and every operand effect. - let failed = super::super::condition(code, condition).map(|condition| { - code.extend([SSE_ESCAPE, condition ^ 1]); - let patch = code.len(); - code.extend(0i32.to_le_bytes()); - patch - }); + let failed = super::super::condition(code, condition) + .map(|condition| code.asm().jcc(cond(condition ^ 1)).offset()); emit_flags(code, format, left, CompareSource::Register(right), pc); if let Some(failed) = failed { let completed = jump(code); let fallback_start = code.len(); resolve(code, failed, fallback_start); - code.extend(STORE_STATE_IMMEDIATE); - code.extend((core::mem::offset_of!(GuestState, nzcv) as u32).to_le_bytes()); - code.extend((u32::from(fallback) << NZCV_SHIFT).to_le_bytes()); + code.asm().mov_rm_imm32( + Size::Dword, + nzcv(), + (u32::from(fallback) << NZCV_SHIFT) as i32, + ); let completed_target = code.len(); resolve(code, completed, completed_target); } @@ -351,19 +292,19 @@ fn absolute(operation: Predicate) -> bool { ) } -fn magnitude(code: &mut Vec, format: Format) { +fn magnitude(code: &mut Code, format: Format) { packed(code, Host::EqualDword, TEMP_VECTOR, TEMP_VECTOR); shift_right(format).emit(code, TEMP_VECTOR, SIGN_BITS); packed(code, Host::And, LEFT_VECTOR, TEMP_VECTOR); packed(code, Host::And, RIGHT_VECTOR, TEMP_VECTOR); } -fn invert_mask(code: &mut Vec, vector: u8) { +fn invert_mask(code: &mut Code, vector: u8) { packed(code, Host::EqualDword, TEMP_VECTOR, TEMP_VECTOR); packed(code, Host::Xor, vector, TEMP_VECTOR); } -fn half_predicate(code: &mut Vec, operation: Predicate) -> u8 { +fn half_predicate(code: &mut Code, operation: Predicate) -> u8 { if operation == Predicate::Equal { packed(code, Host::EqualWord, LEFT_VECTOR, RIGHT_VECTOR); return LEFT_VECTOR; @@ -398,12 +339,7 @@ fn half_predicate(code: &mut Vec, operation: Predicate) -> u8 { } } -fn floating_predicate( - code: &mut Vec, - operation: Predicate, - format: Format, - shape: Shape, -) -> u8 { +fn floating_predicate(code: &mut Code, operation: Predicate, format: Format, shape: Shape) -> u8 { if absolute(operation) { magnitude(code, format); } @@ -418,27 +354,20 @@ fn floating_predicate( Predicate::Less => (RIGHT_VECTOR, LEFT_VECTOR, COMPARE_LESS), Predicate::LessEqual => (RIGHT_VECTOR, LEFT_VECTOR, COMPARE_LESS_EQUAL), }; - if shape == Shape::Scalar { - code.push(if format == Format::Double { - SCALAR_DOUBLE_PREFIX - } else { - SCALAR_SINGLE_PREFIX - }); - } else if format == Format::Double { - code.push(PACKED_DOUBLE_PREFIX); - } - code.extend([ - SSE_ESCAPE, - FLOAT_COMPARE_OPCODE, - REGISTER_DIRECT | (destination << MODRM_REGISTER_SHIFT) | source, - predicate, - ]); + let lanes = match (shape == Shape::Scalar, format == Format::Double) { + (true, true) => FloatLanes::ScalarDouble, + (true, false) => FloatLanes::ScalarSingle, + (false, true) => FloatLanes::PackedDouble, + (false, false) => FloatLanes::PackedSingle, + }; + code.asm() + .float_compare(lanes, destination, Rm::Xmm(source), predicate); destination } /// Zero predicates use signed magnitude tests instead of numerical host FP. /// This also gives exact equality for both signs of zero at every lane width. -fn zero_predicate(code: &mut Vec, operation: Predicate, format: Format) -> u8 { +fn zero_predicate(code: &mut Code, operation: Predicate, format: Format) -> u8 { packed(code, Host::MoveAligned, ZERO_RESULT_VECTOR, LEFT_VECTOR); shift_left(format).emit(code, ZERO_RESULT_VECTOR, SIGN_BITS); shift_right(format).emit(code, ZERO_RESULT_VECTOR, SIGN_BITS); @@ -485,24 +414,28 @@ fn zero_predicate(code: &mut Vec, operation: Predicate, format: Format) -> u } } -fn merge_scalar(code: &mut Vec, format: Format, result: u8) -> u8 { +fn merge_scalar(code: &mut Code, format: Format, result: u8) -> u8 { if result != LEFT_VECTOR && format != Format::Half { packed(code, Host::MoveAligned, LEFT_VECTOR, result); } match format { Format::Half => { - code.extend(MOVD_EAX_XMM_PREFIX); - code.push(REGISTER_DIRECT | (result << MODRM_REGISTER_SHIFT)); - code.extend(PINSRW_XMM6_EAX_0); + let mut asm = code.asm(); + asm.movd_from_xmm(Gpr::Rax, result); + asm.pinsrw(MERGE_VECTOR, Gpr::Rax, 0); + } + Format::Single => { + Host::MoveScalarSingle.register(code, MERGE_VECTOR, LEFT_VECTOR, TargetCpu::Baseline) + } + Format::Double => { + Host::MoveScalarDouble.register(code, MERGE_VECTOR, LEFT_VECTOR, TargetCpu::Baseline) } - Format::Single => code.extend(MOVSS_XMM6_XMM0), - Format::Double => code.extend(MOVSD_XMM6_XMM0), } MERGE_VECTOR } fn commit_predicate( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, destination: u8, @@ -534,7 +467,7 @@ fn commit_predicate( } } -fn emit_predicate(code: &mut Vec, operand: &Operand, pc: GuestAddress) { +fn emit_predicate(code: &mut Code, operand: &Operand, pc: GuestAddress) { let Operand::Predicate { operation, format, @@ -592,7 +525,7 @@ fn emit_predicate(code: &mut Vec, operand: &Operand, pc: GuestAddress) { commit_predicate(code, format, shape, destination, result, merge, zero); } -pub(in crate::x86_64) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress) { +pub(in crate::x86_64) fn emit(code: &mut Code, operand: &Operand, pc: GuestAddress) { match *operand { Operand::Flags { format, diff --git a/crates/stela-compiler/src/x86_64/simd/complex.rs b/crates/stela-compiler/src/x86_64/simd/complex.rs index 64825eff1d..d014b468ab 100644 --- a/crates/stela-compiler/src/x86_64/simd/complex.rs +++ b/crates/stela-compiler/src/x86_64/simd/complex.rs @@ -1,16 +1,16 @@ //! FCADD and FCMLA. +use crate::x86_64::asm::Code; use alloc::vec::Vec; mod half; use super::super::isa::ShiftOpcode; use super::numerical::{ - ArithmeticOpcode, Condition, FusedOpcode, VZEROUPPER, branch, commit_inexact, emit_fma, - emit_opcode, environment, prepare_vector_input_range, prepare_vector_result_range, - read_numerical_vector, reject_other_status, reject_product_status, resolve, - restore_environment, restore_environment_with_product, save_product_status, test_control, - vector_exponent_range, + ArithmeticOpcode, Condition, FusedOpcode, branch, commit_inexact, emit_fma, emit_opcode, + environment, prepare_vector_input_range, prepare_vector_result_range, read_numerical_vector, + reject_other_status, reject_product_status, resolve, restore_environment, + restore_environment_with_product, save_product_status, test_control, vector_exponent_range, }; -use super::{Host, commit, packed, read_vector, shuffle}; +use super::{Host, commit, packed, packed_imm, read_vector, shuffle}; use crate::{ GuestAddress, TargetCpu, aarch64::{ @@ -40,16 +40,14 @@ const BROADCAST_LOW_SINGLE_PAIR: u8 = 0x44; // Dwords [0, 1, 0, 1]. const BROADCAST_HIGH_SINGLE_PAIR: u8 = 0xee; // Dwords [2, 3, 2, 3]. const BROADCAST_HALF_PAIR_STRIDE: u8 = 0x55; // Repeat one selected dword in all positions. -fn half_shuffle(code: &mut Vec, shape: Shape, vector: u8, control: u8) { - packed(code, Host::ShuffleLowWord, vector, vector); - code.push(control); +fn half_shuffle(code: &mut Code, shape: Shape, vector: u8, control: u8) { + packed_imm(code, Host::ShuffleLowWord, vector, vector, control); if shape == Shape::Vector128 { - packed(code, Host::ShuffleHighWord, vector, vector); - code.push(control); + packed_imm(code, Host::ShuffleHighWord, vector, vector, control); } } -fn duplicate_left_component(code: &mut Vec, operand: &Operand) { +fn duplicate_left_component(code: &mut Code, operand: &Operand) { let imaginary = operand.rotation.left_component() == IMAGINARY; let control = if imaginary { DUPLICATE_IMAGINARY @@ -72,7 +70,7 @@ fn duplicate_left_component(code: &mut Vec, operand: &Operand) { } } -fn prepare_right(code: &mut Vec, operand: &Operand) { +fn prepare_right(code: &mut Code, operand: &Operand) { match operand.right { Source::Vector(source) => { read_numerical_vector(code, operand.shape, source, RIGHT); @@ -110,7 +108,7 @@ fn prepare_right(code: &mut Vec, operand: &Operand) { } } -fn prepare_sources(code: &mut Vec, operand: &Operand) { +fn prepare_sources(code: &mut Code, operand: &Operand) { read_numerical_vector(code, operand.shape, operand.left, LEFT); if operand.kind == Kind::MultiplyAdd { // Unselected N real/imaginary components, including signaling NaNs, @@ -122,7 +120,7 @@ fn prepare_sources(code: &mut Vec, operand: &Operand) { /// Toggle only the architectural rotated M signs after normal-input guards. /// XMM2 is scratch; staged XMM0/1 and the accumulator retain their source roles. -pub(super) fn rotate_right_sign(code: &mut Vec, format: Format, rotation: Rotation) { +pub(super) fn rotate_right_sign(code: &mut Code, format: Format, rotation: Rotation) { if rotation == Rotation::Degrees0 { return; } @@ -153,7 +151,7 @@ pub(super) fn rotate_right_sign(code: &mut Vec, format: Format, rotation: Ro packed(code, Host::Xor, RIGHT, SIGN_MASK); } -fn input_guard(code: &mut Vec, operand: &Operand, helper: &mut Vec) { +fn input_guard(code: &mut Code, operand: &Operand, helper: &mut Vec) { prepare_vector_input_range(code, operand.format); vector_exponent_range(code, operand.format, operand.shape, LEFT); helper.push(branch(code, Condition::NotZero)); @@ -164,7 +162,7 @@ fn input_guard(code: &mut Vec, operand: &Operand, helper: &mut Vec) { } } -fn arithmetic(code: &mut Vec, operand: &Operand, native_fma: bool, target: TargetCpu) { +fn arithmetic(code: &mut Code, operand: &Operand, native_fma: bool, target: TargetCpu) { let negative_product = native_fma && operand.rotation == Rotation::Degrees180; if !negative_product { rotate_right_sign(code, operand.format, operand.rotation); @@ -215,7 +213,7 @@ fn arithmetic(code: &mut Vec, operand: &Operand, native_fma: bool, target: T } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu, @@ -225,7 +223,7 @@ pub(in crate::x86_64) fn emit( && target.supports(TargetCpu::Fma); let native_f16c = operand.format == Format::Half && target.supports(TargetCpu::F16c); if native_fma || native_f16c { - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } prepare_sources(code, operand); if operand.format == Format::Half { diff --git a/crates/stela-compiler/src/x86_64/simd/complex/half.rs b/crates/stela-compiler/src/x86_64/simd/complex/half.rs index f46ac29757..551255aab6 100644 --- a/crates/stela-compiler/src/x86_64/simd/complex/half.rs +++ b/crates/stela-compiler/src/x86_64/simd/complex/half.rs @@ -6,6 +6,7 @@ use super::super::numerical::{ vector_exponent_range, }; use super::super::{Host, commit, half as lanes, packed, read_vector}; +use crate::x86_64::asm::{Alu, Code, Gpr, Rm, ShiftOp, Size}; use crate::{ GuestAddress, TargetCpu, aarch64::{ @@ -22,21 +23,8 @@ const HALF_BYTES: u8 = (Format::Half.bits() / u8::BITS) as u8; const HALF_TO_DOUBLE_FRACTION_SHIFT: u8 = (Format::Double.fraction_bits() - Format::Half.fraction_bits()) as u8; const HALF_TO_DOUBLE_SIGN_SHIFT: u8 = (Format::Double.bits() - Format::Half.bits()) as u8; -const MOVD_EAX_XMM7: &[u8] = &[0x66, 0x0f, 0x7e, 0xf8]; -const MOVZX_EAX_AX: &[u8] = &[0x0f, 0xb7, 0xc0]; -const MOVD_XMM6_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xf0]; -const CVTSS2SD_XMM6_XMM6: &[u8] = &[0xf3, 0x0f, 0x5a, 0xf6]; -const MOV_EDX_EAX: &[u8] = &[0x89, 0xc2]; -const AND_EAX_IMM32: u8 = 0x25; -const AND_EDX_IMM32: &[u8] = &[0x81, 0xe2]; -const SHL_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe0]; -const SHL_RDX_IMM8: &[u8] = &[0x48, 0xc1, 0xe2]; -const ADD_RAX_R9: &[u8] = &[0x4c, 0x01, 0xc8]; -const OR_RAX_RDX: &[u8] = &[0x48, 0x09, 0xd0]; -const MOVQ_XMM6_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xf0]; -const TEST_ECX_IMM32: &[u8] = &[0xf7, 0xc1]; -fn normal_inputs(code: &mut Vec, operand: &Operand, helper: &mut Vec) { +fn normal_inputs(code: &mut Code, operand: &Operand, helper: &mut Vec) { test_control(code, FPCR_EXCEPTION_ENABLE_MASK); helper.push(branch(code, Condition::NotZero)); if operand.kind == Kind::MultiplyAdd { @@ -57,34 +45,43 @@ fn normal_inputs(code: &mut Vec, operand: &Operand, helper: &mut Vec) super::rotate_right_sign(code, Format::Half, operand.rotation); } -fn widen_addend(code: &mut Vec, target: TargetCpu) { +fn widen_addend(code: &mut Code, target: TargetCpu) { // The addend's private XMM7 snapshot advances one Half per completed lane. // R9 is the shared unscaled Half-to-Double bias and survives MXCSR setup. - code.extend(MOVD_EAX_XMM7); + code.asm().movd_from_xmm(Gpr::Rax, lanes::ORIGINAL_LEFT); if target.supports(TargetCpu::F16c) { // Isolate the selected Half before packed conversion: the next lane in // XMM7 may be an inactive sNaN. MOVD also zeros every higher Half lane. - code.extend(MOVZX_EAX_AX); - code.extend(MOVD_XMM6_EAX); + let mut asm = code.asm(); + asm.movzx(Size::Dword, Gpr::Rax, Size::Word, Gpr::Rax); + asm.movd_to_xmm(lanes::RESULT, Gpr::Rax); Host::ConvertHalfToSingle.register(code, lanes::RESULT, lanes::RESULT, target); - code.extend(CVTSS2SD_XMM6_XMM6); + code.asm().cvtss2sd(lanes::RESULT, Rm::Xmm(lanes::RESULT)); return; } - code.extend(MOV_EDX_EAX); - code.push(AND_EAX_IMM32); - code.extend((Format::Half.sign_mask() as u32 - 1).to_le_bytes()); - code.extend(SHL_RAX_IMM8); - code.push(HALF_TO_DOUBLE_FRACTION_SHIFT); - code.extend(ADD_RAX_R9); - code.extend(AND_EDX_IMM32); - code.extend((Format::Half.sign_mask() as u32).to_le_bytes()); - code.extend(SHL_RDX_IMM8); - code.push(HALF_TO_DOUBLE_SIGN_SHIFT); - code.extend(OR_RAX_RDX); - code.extend(MOVQ_XMM6_RAX); + let sign = Format::Half.sign_mask() as u32; + let mut asm = code.asm(); + asm.mov(Size::Dword, Gpr::Rdx, Gpr::Rax); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, (sign - 1) as i32); + asm.shift_imm( + ShiftOp::Shl, + Size::Qword, + Gpr::Rax, + HALF_TO_DOUBLE_FRACTION_SHIFT, + ); + asm.alu(Alu::Add, Size::Qword, Gpr::Rax, Gpr::R9); + asm.alu_imm32(Alu::And, Size::Dword, Gpr::Rdx, sign as i32); + asm.shift_imm( + ShiftOp::Shl, + Size::Qword, + Gpr::Rdx, + HALF_TO_DOUBLE_SIGN_SHIFT, + ); + asm.alu(Alu::Or, Size::Qword, Gpr::Rax, Gpr::Rdx); + asm.movq_to_xmm(lanes::RESULT, Gpr::Rax); } -fn arithmetic(code: &mut Vec, kind: Kind, target: TargetCpu, rollback: &mut Vec) { +fn arithmetic(code: &mut Code, kind: Kind, target: TargetCpu, rollback: &mut Vec) { if kind == Kind::Add { packed(code, Host::MoveAligned, lanes::RESULT, lanes::LEFT); // Normal Half sums need at most 41 bits; nonzero sums are normal Double. @@ -125,12 +122,12 @@ fn arithmetic(code: &mut Vec, kind: Kind, target: TargetCpu, rollback: &mut // Normal Half inputs bound every Double result to finite normal or exact // zero, so PE is the only possible fresh status. Test it after restoration: // the shared rollback then drops exactly its own 48-byte frame. - code.extend(TEST_ECX_IMM32); - code.extend(MXCSR_INEXACT.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Gpr::Rcx, MXCSR_INEXACT as i32); rollback.push(branch(code, Condition::NotZero)); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu) { debug_assert_eq!(operand.format, Format::Half); let mut helper = Vec::new(); let mut rollback = Vec::new(); diff --git a/crates/stela-compiler/src/x86_64/simd/encode.rs b/crates/stela-compiler/src/x86_64/simd/encode.rs new file mode 100644 index 0000000000..3bc5a490a6 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/encode.rs @@ -0,0 +1,42 @@ +//! Operands the SIMD, SME and AMX lowerings name by number or by frame. +use crate::x86_64::asm::{Cond, Gpr, Mem}; + +/// The general-purpose register numbered `number`. +pub(in crate::x86_64) const fn gpr(number: u8) -> Gpr { + use Gpr::*; + const REGISTERS: [Gpr; 16] = [ + Rax, Rcx, Rdx, Rbx, Rsp, Rbp, Rsi, Rdi, R8, R9, R10, R11, R12, R13, R14, R15, + ]; + REGISTERS[number as usize] +} + +/// The condition numbered `number` in Jcc, SETcc and CMOVcc encodings; the +/// low nibble of a Jcc rel32 second opcode byte. +pub(in crate::x86_64) const fn cond(number: u8) -> Cond { + use Cond::*; + const CONDITIONS: [Cond; 16] = [O, No, B, Ae, E, Ne, Be, A, S, Ns, P, Np, L, Ge, Le, G]; + CONDITIONS[(number & 0xf) as usize] +} + +/// `[rsp + offset]` with a 32-bit displacement: a private stack slot. +pub(in crate::x86_64) const fn stack(offset: usize) -> Mem { + Mem::base_disp32(Gpr::Rsp, offset as i32) +} + +/// `[rdi + offset]` in GuestState, with a 32-bit displacement. +pub(in crate::x86_64) const fn guest(offset: u32) -> Mem { + Mem::base_disp32(Gpr::Rdi, offset as i32) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn registers_number_as_encoded() { + assert_eq!(gpr(0), Gpr::Rax); + assert_eq!(gpr(9), Gpr::R9); + assert_eq!(cond(0x84), Cond::E); + assert_eq!(cond(0x0f), Cond::G); + } +} diff --git a/crates/stela-compiler/src/x86_64/simd/estimate.rs b/crates/stela-compiler/src/x86_64/simd/estimate.rs index 06e47813a0..01c3e36b45 100644 --- a/crates/stela-compiler/src/x86_64/simd/estimate.rs +++ b/crates/stela-compiler/src/x86_64/simd/estimate.rs @@ -1,5 +1,6 @@ //! FRECPE/FRSQRTE/FRECPX through exact integer arithmetic. use super::super::isa::ShiftOpcode; +use super::numerical::helper_section; use super::numerical::{ ArithmeticOpcode, Condition, INPUT_MINIMUM_EXPONENT, Rounding, branch, clear_scalar, emit_opcode, environment_round, exponent_range, exponent_range_below, positive_exponent_range, @@ -7,6 +8,7 @@ use super::numerical::{ restore_environment, test_control, vector_exponent_range, vector_positive_exponent_range, }; use super::{Host, commit, packed, read_vector}; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, ShiftOp, Size, Unary}; use crate::{ GuestAddress, TargetCpu, aarch64::{ @@ -16,8 +18,8 @@ use crate::{ estimate::{Kind, Operand}, }, }, - block::ExitKind, }; +use Gpr::{R8, R9, Rax, Rcx, Rdx}; use alloc::vec::Vec; const RESULT: u8 = 0; @@ -41,40 +43,15 @@ const COMPACT_QWORD_LOW_DWORDS: u8 = 0x88; const BROADCAST_LOW_DWORD: u8 = 0; const FIRST_LANE: u8 = 0; const ACCUMULATOR_GPR: u8 = 0; -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const JMP_REL32: u8 = 0xe9; -const MOV_EAX_IMM32: u8 = 0xb8; -const MOVD_EAX_XMM_PREFIX: &[u8] = &[0x66, 0x0f, 0x7e]; -const MOVQ_RAX_XMM_PREFIX: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const MOVD_XMM_EAX_PREFIX: &[u8] = &[0x66, 0x0f, 0x6e]; -const PINSRW_XMM_EAX_PREFIX: &[u8] = &[0x66, 0x0f, 0xc4]; -const MOVSS_XMM7_XMM0: &[u8] = &[0xf3, 0x0f, 0x10, 0xf8]; -const MOVSD_XMM7_XMM0: &[u8] = &[0xf2, 0x0f, 0x10, 0xf8]; -const XOR_EAX_IMM32: u8 = 0x35; -const AND_EAX_IMM32: u8 = 0x25; -const MOVABS_RDX: &[u8] = &[0x48, 0xba]; -const MOVABS_RCX: &[u8] = &[0x48, 0xb9]; -const XOR_RAX_RDX: &[u8] = &[0x48, 0x31, 0xd0]; -const AND_RAX_RCX: &[u8] = &[0x48, 0x21, 0xc8]; -const OR_EAX_IMM32: u8 = 0x0d; -const ADD_EAX_IMM32: u8 = 0x05; -const MOV_ECX_IMM32: u8 = 0xb9; -const MOV_R8_RAX: &[u8] = &[0x49, 0x89, 0xc0]; -const MOV_R9_RAX: &[u8] = &[0x49, 0x89, 0xc1]; -const MOV_RAX_R8: &[u8] = &[0x4c, 0x89, 0xc0]; -const SHR_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe8]; -const SHL_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe0]; -const SHL_RCX_IMM8: &[u8] = &[0x48, 0xc1, 0xe1]; -const SHR_R8_IMM8: &[u8] = &[0x49, 0xc1, 0xe8]; -const SHL_R8_IMM8: &[u8] = &[0x49, 0xc1, 0xe0]; -const LEA_ECX_DOUBLE_RAX_PLUS_ONE: &[u8] = &[0x8d, 0x4c, 0x00, 0x01]; -const XOR_EDX_EDX: &[u8] = &[0x31, 0xd2]; -const DIV_ECX: &[u8] = &[0xf7, 0xf1]; -const SUB_ECX_EAX: &[u8] = &[0x29, 0xc1]; -const OR_R9_RCX: &[u8] = &[0x49, 0x09, 0xc9]; -const OR_R9_R8: &[u8] = &[0x4d, 0x09, 0xc1]; -const MOVQ_XMM0_R9: &[u8] = &[0x66, 0x49, 0x0f, 0x6e, 0xc1]; + +/// Move the low `format` lane of `vector` into RAX/EAX. +fn lane_to_rax(code: &mut Code, format: Format, vector: u8) { + if format == Format::Double { + code.asm().movq_from_xmm(Rax, vector); + } else { + code.asm().movd_from_xmm(Rax, vector); + } +} fn reciprocal_sqrt(kind: Kind) -> bool { matches!( @@ -100,58 +77,53 @@ fn checked_reciprocal(operand: &Operand, target: TargetCpu) -> bool { /// Exact table rounding: r=(2^18+a)/(2a+1), a=256+fraction_top8. /// The odd denominator cannot tie, so integer DIV needs no FP environment. -fn scalar_reciprocal(code: &mut Vec, format: Format) { - code.extend(if format == Format::Double { - MOVQ_RAX_XMM_PREFIX - } else { - MOVD_EAX_XMM_PREFIX - }); - code.push(REGISTER_DIRECT | (SOURCE << MODRM_REGISTER_SHIFT)); - code.extend(MOV_R8_RAX); - code.extend(SHR_RAX_IMM8); - code.push(fraction_shift(format)); - code.push(AND_EAX_IMM32); - code.extend((ESTIMATE_UNIT - 1).to_le_bytes()); - code.push(OR_EAX_IMM32); - code.extend(ESTIMATE_UNIT.to_le_bytes()); - code.extend(LEA_ECX_DOUBLE_RAX_PLUS_ONE); - code.push(ADD_EAX_IMM32); - code.extend((1u32 << RECIPROCAL_QUOTIENT_EXPONENT).to_le_bytes()); - code.extend(XOR_EDX_EDX); - code.extend(DIV_ECX); - code.push(AND_EAX_IMM32); - code.extend((ESTIMATE_UNIT - 1).to_le_bytes()); - code.extend(SHL_RAX_IMM8); - code.push(fraction_shift(format)); - code.extend(MOV_R9_RAX); - code.extend(MOV_RAX_R8); - code.extend(SHR_RAX_IMM8); - code.push(format.fraction_bits() as u8); - code.push(AND_EAX_IMM32); - code.extend((2 * format.exponent_bias() + 1).to_le_bytes()); - code.push(MOV_ECX_IMM32); - code.extend((2 * format.exponent_bias() - 1).to_le_bytes()); - code.extend(SUB_ECX_EAX); - code.extend(SHL_RCX_IMM8); - code.push(format.fraction_bits() as u8); - code.extend(OR_R9_RCX); - code.extend(SHR_R8_IMM8); - code.push(format.bits() as u8 - SIGN_BITS); - code.extend(SHL_R8_IMM8); - code.push(format.bits() as u8 - SIGN_BITS); - code.extend(OR_R9_R8); - code.extend(MOVQ_XMM0_R9); +fn scalar_reciprocal(code: &mut Code, format: Format) { + let fraction_mask = (ESTIMATE_UNIT - 1) as i32; + let fraction_bits = format.fraction_bits() as u8; + let sign_bit = format.bits() as u8 - SIGN_BITS; + lane_to_rax(code, format, SOURCE); + let mut asm = code.asm(); + asm.mov(Size::Qword, R8, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rax, fraction_shift(format)); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, fraction_mask); + asm.alu_accumulator_imm32(Alu::Or, Size::Dword, ESTIMATE_UNIT as i32); + // ECX = 2a+1. + asm.lea(Size::Dword, Rcx, Mem::indexed(Rax, Rax, 1, 1)); + asm.alu_accumulator_imm32( + Alu::Add, + Size::Dword, + (1u32 << RECIPROCAL_QUOTIENT_EXPONENT) as i32, + ); + asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); + asm.unary(Unary::Div, Size::Dword, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, fraction_mask); + asm.shift_imm(ShiftOp::Shl, Size::Qword, Rax, fraction_shift(format)); + asm.mov(Size::Qword, R9, Rax); + asm.mov(Size::Qword, Rax, R8); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rax, fraction_bits); + asm.alu_accumulator_imm32( + Alu::And, + Size::Dword, + (2 * format.exponent_bias() + 1) as i32, + ); + asm.mov_imm32(Rcx, 2 * format.exponent_bias() - 1); + asm.alu(Alu::Sub, Size::Dword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shl, Size::Qword, Rcx, fraction_bits); + asm.alu(Alu::Or, Size::Qword, R9, Rcx); + asm.shift_imm(ShiftOp::Shr, Size::Qword, R8, sign_bit); + asm.shift_imm(ShiftOp::Shl, Size::Qword, R8, sign_bit); + asm.alu(Alu::Or, Size::Qword, R9, R8); + asm.movq_to_xmm(RESULT, R9); } -fn dword_constant(code: &mut Vec, vector: u8, value: u32) { - code.push(MOV_EAX_IMM32); - code.extend(value.to_le_bytes()); - code.extend(MOVD_XMM_EAX_PREFIX); - code.push(REGISTER_DIRECT | (vector << MODRM_REGISTER_SHIFT)); +fn dword_constant(code: &mut Code, vector: u8, value: u32) { + let mut asm = code.asm(); + asm.mov_imm32(Rax, value); + asm.movd_to_xmm(vector, Rax); super::shuffle(code, vector, vector, BROADCAST_LOW_DWORD); } -fn source_guard(code: &mut Vec, operand: &Operand, helper: &mut Vec) { +fn source_guard(code: &mut Code, operand: &Operand, helper: &mut Vec) { if !operand.kind.is_unsigned() { // AH suppresses every estimate exception, including retained enables. test_control(code, FPCR_AH); @@ -198,25 +170,9 @@ fn source_guard(code: &mut Vec, operand: &Operand, helper: &mut Vec) } } -fn helper_section(code: &mut Vec, helper: &[usize], pc: GuestAddress) { - if helper.is_empty() { - return; - } - code.push(JMP_REL32); - let completed = code.len(); - code.extend(0i32.to_le_bytes()); - let helper_start = code.len(); - super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); - let success_start = code.len(); - for &patch in helper { - resolve(code, patch, helper_start); - } - resolve(code, completed, success_start); -} - /// Keep sign, biased exponent and the top eight fraction bits in each dword. /// D metadata is compacted before any host floating operation; H expands first. -fn compact_source(code: &mut Vec, format: Format, upper: bool) { +fn compact_source(code: &mut Code, format: Format, upper: bool) { packed(code, Host::MoveAligned, COMPACT, SOURCE); if upper { ShiftOpcode::RightBytes.emit(code, COMPACT, UPPER_HALF_BYTES); @@ -233,7 +189,7 @@ fn compact_source(code: &mut Vec, format: Format, upper: bool) { } } -fn result_exponent(code: &mut Vec, format: Format, sqrt: bool) { +fn result_exponent(code: &mut Code, format: Format, sqrt: bool) { let bits = exponent_bits(format); packed(code, Host::MoveAligned, TEMP, COMPACT); ShiftOpcode::LeftDword.emit(code, TEMP, DWORD_BITS - bits - ESTIMATE_FRACTION_BITS); @@ -247,7 +203,7 @@ fn result_exponent(code: &mut Vec, format: Format, sqrt: bool) { ShiftOpcode::LeftDword.emit(code, EXPONENT, ESTIMATE_FRACTION_BITS); } -fn floating_denominator(code: &mut Vec, sqrt: bool) { +fn floating_denominator(code: &mut Code, sqrt: bool) { packed(code, Host::MoveAligned, DENOMINATOR, COMPACT); ShiftOpcode::LeftDword.emit(code, DENOMINATOR, DWORD_BITS - ESTIMATE_FRACTION_BITS); ShiftOpcode::RightDword.emit(code, DENOMINATOR, DWORD_BITS - ESTIMATE_FRACTION_BITS); @@ -273,7 +229,7 @@ fn floating_denominator(code: &mut Vec, sqrt: bool) { /// Bounded denominators are exact Single integers. Primary-derived midpoint /// bounds prove nearest(DIV[+SQRT]) followed by nearest integer conversion /// reproduces every standard estimate key. Host PE is not guest estimate IXC. -fn integer_estimate(code: &mut Vec, sqrt: bool) { +fn integer_estimate(code: &mut Code, sqrt: bool) { packed( code, Host::ConvertPackedDwordToSingle, @@ -302,7 +258,7 @@ fn integer_estimate(code: &mut Vec, sqrt: bool) { /// RCP raises no exceptions. Its error bound makes floor(q') either r or r - 1; /// the exact odd product A*(2*r0+1) decides the increment. -fn corrected_reciprocal(code: &mut Vec, target: TargetCpu) { +fn corrected_reciprocal(code: &mut Code, target: TargetCpu) { packed(code, Host::ConvertPackedDwordToSingle, RESULT, DENOMINATOR); packed(code, Host::ReciprocalPackedSingle, RESULT, RESULT); ShiftOpcode::RightDword.emit(code, RESULT, fraction_shift(Format::Single)); @@ -319,7 +275,7 @@ fn corrected_reciprocal(code: &mut Vec, target: TargetCpu) { packed(code, Host::SubDword, RESULT, TEMP); } -fn pack_half(code: &mut Vec, signed: bool, target: TargetCpu) { +fn pack_half(code: &mut Code, signed: bool, target: TargetCpu) { if signed && target.supports(TargetCpu::Sse41) { Host::PackUnsignedDwordToWord.register(code, RESULT, RESULT, target); } else { @@ -333,7 +289,7 @@ fn pack_half(code: &mut Vec, signed: bool, target: TargetCpu) { } } -fn floating_group(code: &mut Vec, operand: &Operand, upper: bool, target: TargetCpu) { +fn floating_group(code: &mut Code, operand: &Operand, upper: bool, target: TargetCpu) { let sqrt = reciprocal_sqrt(operand.kind); compact_source(code, operand.format, upper); result_exponent(code, operand.format, sqrt); @@ -366,7 +322,7 @@ fn floating_group(code: &mut Vec, operand: &Operand, upper: bool, target: Ta } } -fn floating_estimate(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn floating_estimate(code: &mut Code, operand: &Operand, target: TargetCpu) { if operand.shape == Shape::Scalar { clear_scalar(code, operand.format, SOURCE); } @@ -392,7 +348,7 @@ fn floating_estimate(code: &mut Vec, operand: &Operand, target: TargetCpu) { } } -fn unsigned_estimate(code: &mut Vec, kind: Kind, target: TargetCpu) { +fn unsigned_estimate(code: &mut Code, kind: Kind, target: TargetCpu) { let sqrt = reciprocal_sqrt(kind); let checked = !sqrt && target.supports(TargetCpu::Sse41); if !checked { @@ -442,44 +398,38 @@ fn unsigned_estimate(code: &mut Vec, kind: Kind, target: TargetCpu) { } } -fn reciprocal_exponent(code: &mut Vec, format: Format) { - code.extend(if format == Format::Double { - MOVQ_RAX_XMM_PREFIX - } else { - MOVD_EAX_XMM_PREFIX - }); - code.push(REGISTER_DIRECT | (SOURCE << MODRM_REGISTER_SHIFT)); +fn reciprocal_exponent(code: &mut Code, format: Format) { + lane_to_rax(code, format, SOURCE); + let kept = format.sign_mask() | format.exponent_mask(); + let mut asm = code.asm(); if format == Format::Double { - code.extend(MOVABS_RDX); - code.extend(format.exponent_mask().to_le_bytes()); - code.extend(XOR_RAX_RDX); - code.extend(MOVABS_RCX); - code.extend((format.sign_mask() | format.exponent_mask()).to_le_bytes()); - code.extend(AND_RAX_RCX); + asm.mov_imm64(Rdx, format.exponent_mask()); + asm.alu(Alu::Xor, Size::Qword, Rax, Rdx); + asm.mov_imm64(Rcx, kept); + asm.alu(Alu::And, Size::Qword, Rax, Rcx); packed(code, Host::MoveGprQword, RESULT, ACCUMULATOR_GPR); } else { - code.push(XOR_EAX_IMM32); - code.extend((format.exponent_mask() as u32).to_le_bytes()); - code.push(AND_EAX_IMM32); - code.extend(((format.sign_mask() | format.exponent_mask()) as u32).to_le_bytes()); - code.extend(MOVD_XMM_EAX_PREFIX); - code.push(REGISTER_DIRECT | (RESULT << MODRM_REGISTER_SHIFT)); + asm.alu_accumulator_imm32(Alu::Xor, Size::Dword, format.exponent_mask() as i32); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, kept as i32); + asm.movd_to_xmm(RESULT, Rax); } } -fn commit_result(code: &mut Vec, operand: &Operand) { +fn commit_result(code: &mut Code, operand: &Operand) { let result = if operand.shape == Shape::Scalar { read_vector(code, operand.destination, SAVED); match operand.format { Format::Half => { - code.extend(MOVD_EAX_XMM_PREFIX); - code.push(REGISTER_DIRECT | (RESULT << MODRM_REGISTER_SHIFT)); - code.extend(PINSRW_XMM_EAX_PREFIX); - code.push(REGISTER_DIRECT | (SAVED << MODRM_REGISTER_SHIFT)); - code.push(FIRST_LANE); + let mut asm = code.asm(); + asm.movd_from_xmm(Rax, RESULT); + asm.pinsrw(SAVED, Rax, FIRST_LANE); + } + Format::Single => { + Host::MoveScalarSingle.register(code, SAVED, RESULT, TargetCpu::Baseline) + } + Format::Double => { + Host::MoveScalarDouble.register(code, SAVED, RESULT, TargetCpu::Baseline) } - Format::Single => code.extend(MOVSS_XMM7_XMM0), - Format::Double => code.extend(MOVSD_XMM7_XMM0), } test_control(code, FPCR_NEP); let merging = branch(code, Condition::NotZero); @@ -497,7 +447,7 @@ fn commit_result(code: &mut Vec, operand: &Operand) { } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu, @@ -511,6 +461,8 @@ pub(in crate::x86_64) fn emit( } else { floating_estimate(code, operand, target); } - helper_section(code, &helper, pc); + if !helper.is_empty() { + helper_section(code, &helper, pc); + } commit_result(code, operand); } diff --git a/crates/stela-compiler/src/x86_64/simd/exponent_scale.rs b/crates/stela-compiler/src/x86_64/simd/exponent_scale.rs index a1ce6d68cf..1153e64be8 100644 --- a/crates/stela-compiler/src/x86_64/simd/exponent_scale.rs +++ b/crates/stela-compiler/src/x86_64/simd/exponent_scale.rs @@ -4,8 +4,9 @@ use super::{ Host, numerical::{Condition, branch, prepare_vector_input_range, vector_exponent_range}, - packed, + packed, packed_imm, }; +use crate::x86_64::asm::{Alu, Code, Gpr, ShiftOp, Size}; use crate::{ TargetCpu, aarch64::{floating::Format, simd::arithmetic::Shape}, @@ -20,33 +21,16 @@ const VALID: u8 = 3; const MAXIMUM: u8 = 4; const ZERO: u8 = 5; const ONE_BIT: u8 = 1; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOVD_XMM4_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xe0]; const REPEAT_LOW_DWORD: u8 = 0; -const PMOVMSKB_EAX_XMM3: &[u8] = &[0x66, 0x0f, 0xd7, 0xc3]; -const CMP_EAX_IMMEDIATE: u8 = 0x3d; const LOW_VECTOR_BYTE_MASK: u32 = 0xff; const FULL_VECTOR_BYTE_MASK: u32 = 0xffff; -const MOVQ_RAX_XMM2: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xd0]; -const MOVQ_RCX_XMM3: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xd9]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const SHR_RDX: &[u8] = &[0x48, 0xc1, 0xea]; -const AND_EDX: &[u8] = &[0x81, 0xe2]; -const SUB_RDX_ONE: &[u8] = &[0x48, 0x83, 0xea, 1]; -const ADD_RDX_ONE: &[u8] = &[0x48, 0x83, 0xc2, 1]; -const ADD_RDX_RCX: &[u8] = &[0x48, 0x01, 0xca]; -const CMP_RDX: &[u8] = &[0x48, 0x81, 0xfa]; -const SHL_RCX: &[u8] = &[0x48, 0xc1, 0xe1]; -const ADD_RAX_RCX: &[u8] = &[0x48, 0x01, 0xc8]; -const MOVQ_XMM4_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xe0]; -const MOVQ_XMM5_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xe8]; const DOUBLE_EXPONENT_SHIFT: u8 = Format::Double.fraction_bits() as u8; const DOUBLE_EXPONENT_MASK: u32 = (Format::Double.exponent_mask() >> Format::Double.fraction_bits()) as u32; const DOUBLE_MAXIMUM_NORMAL_MINUS_ONE: u32 = DOUBLE_EXPONENT_MASK - 1; pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, failures: &mut Vec, @@ -95,20 +79,17 @@ pub(in crate::x86_64) fn emit( } else { maximum }; - code.push(MOV_EAX_IMMEDIATE); - code.extend(constant.to_le_bytes()); + code.asm().mov_imm32(Gpr::Rax, constant); if format == Format::Double { - code.extend(MOVQ_XMM4_RAX); + code.asm().movq_to_xmm(MAXIMUM, Gpr::Rax); packed(code, Host::UnpackLowQword, MAXIMUM, MAXIMUM); } else { - code.extend(MOVD_XMM4_EAX); - packed(code, Host::ShuffleDword, MAXIMUM, MAXIMUM); - code.push(REPEAT_LOW_DWORD); + code.asm().movd_to_xmm(MAXIMUM, Gpr::Rax); + packed_imm(code, Host::ShuffleDword, MAXIMUM, MAXIMUM, REPEAT_LOW_DWORD); } greater.register(code, MAXIMUM, EXPONENT, target); packed(code, Host::And, VALID, MAXIMUM); - code.extend(PMOVMSKB_EAX_XMM3); - code.push(CMP_EAX_IMMEDIATE); + Host::ByteSignMask.register(code, 0, VALID, TargetCpu::Baseline); // Q0's upper zero lanes are outside the architectural vector and must not // reject an otherwise valid operation. let mask = if shape == Shape::Vector64 { @@ -116,13 +97,14 @@ pub(in crate::x86_64) fn emit( } else { FULL_VECTOR_BYTE_MASK }; - code.extend(mask.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Cmp, Size::Dword, mask as i32); failures.push(branch(code, Condition::NotZero)); left_shift.emit(code, RIGHT, format.fraction_bits() as u8); packed(code, add, LEFT, RIGHT); } -fn scale_double(code: &mut Vec, failures: &mut Vec) { +fn scale_double(code: &mut Code, failures: &mut Vec) { for lane in 0..2 { packed(code, Host::MoveAligned, EXPONENT, LEFT); packed(code, Host::MoveAligned, VALID, RIGHT); @@ -130,32 +112,36 @@ fn scale_double(code: &mut Vec, failures: &mut Vec) { ShiftOpcode::RightBytes.emit(code, EXPONENT, size_of::() as u8); ShiftOpcode::RightBytes.emit(code, VALID, size_of::() as u8); } - code.extend(MOVQ_RAX_XMM2); - code.extend(MOVQ_RCX_XMM3); - code.extend(MOV_RDX_RAX); - code.extend(SHR_RDX); - code.push(DOUBLE_EXPONENT_SHIFT); - code.extend(AND_EDX); - code.extend(DOUBLE_EXPONENT_MASK.to_le_bytes()); + let mut asm = code.asm(); + asm.movq_from_xmm(Gpr::Rax, EXPONENT); + asm.movq_from_xmm(Gpr::Rcx, VALID); + asm.mov(Size::Qword, Gpr::Rdx, Gpr::Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Gpr::Rdx, DOUBLE_EXPONENT_SHIFT); + asm.alu_imm32(Alu::And, Size::Dword, Gpr::Rdx, DOUBLE_EXPONENT_MASK as i32); // (exponent - 1) < 2046 admits exactly normal exponent fields. - code.extend(SUB_RDX_ONE); - code.extend(CMP_RDX); - code.extend(DOUBLE_MAXIMUM_NORMAL_MINUS_ONE.to_le_bytes()); + asm.alu_imm8(Alu::Sub, Size::Qword, Gpr::Rdx, 1); + asm.alu_imm32( + Alu::Cmp, + Size::Qword, + Gpr::Rdx, + DOUBLE_MAXIMUM_NORMAL_MINUS_ONE as i32, + ); failures.push(branch(code, Condition::AboveOrEqual)); - code.extend(ADD_RDX_ONE); - code.extend(ADD_RDX_RCX); - code.extend(SUB_RDX_ONE); - code.extend(CMP_RDX); - code.extend(DOUBLE_MAXIMUM_NORMAL_MINUS_ONE.to_le_bytes()); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Add, Size::Qword, Gpr::Rdx, 1); + asm.alu(Alu::Add, Size::Qword, Gpr::Rdx, Gpr::Rcx); + asm.alu_imm8(Alu::Sub, Size::Qword, Gpr::Rdx, 1); + asm.alu_imm32( + Alu::Cmp, + Size::Qword, + Gpr::Rdx, + DOUBLE_MAXIMUM_NORMAL_MINUS_ONE as i32, + ); failures.push(branch(code, Condition::AboveOrEqual)); - code.extend(SHL_RCX); - code.push(DOUBLE_EXPONENT_SHIFT); - code.extend(ADD_RAX_RCX); - code.extend(if lane == 0 { - MOVQ_XMM4_RAX - } else { - MOVQ_XMM5_RAX - }); + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shl, Size::Qword, Gpr::Rcx, DOUBLE_EXPONENT_SHIFT); + asm.alu(Alu::Add, Size::Qword, Gpr::Rax, Gpr::Rcx); + asm.movq_to_xmm(if lane == 0 { MAXIMUM } else { ZERO }, Gpr::Rax); } packed(code, Host::UnpackLowQword, MAXIMUM, ZERO); packed(code, Host::MoveAligned, LEFT, MAXIMUM); diff --git a/crates/stela-compiler/src/x86_64/simd/extrema_scale.rs b/crates/stela-compiler/src/x86_64/simd/extrema_scale.rs index 01a2ff0244..f7f2ce4fd9 100644 --- a/crates/stela-compiler/src/x86_64/simd/extrema_scale.rs +++ b/crates/stela-compiler/src/x86_64/simd/extrema_scale.rs @@ -1,4 +1,5 @@ //! FAMIN/FAMAX and FSCALE. FSCALE on normal values changes only exponent bits. +use crate::x86_64::asm::Code; use crate::{ GuestAddress, TargetCpu, aarch64::{ @@ -14,7 +15,9 @@ use alloc::vec::Vec; use super::{ commit, - numerical::{Condition, MOVQ_XMM0_XMM0, branch, read_numerical_vector, resolve, test_control}, + numerical::{ + Condition, branch, clear_high_qword, jump, read_numerical_vector, resolve, test_control, + }, }; const LEFT: u8 = 0; @@ -26,7 +29,7 @@ pub(super) fn always_exits(_operand: &Operand) -> bool { } fn absolute( - code: &mut Vec, + code: &mut Code, operand: &Operand, operation: AbsoluteMinMaxOperation, failures: &mut Vec, @@ -52,7 +55,7 @@ fn absolute( ); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu) { let mut failures = Vec::new(); test_control(code, FPCR_EXCEPTION_ENABLE_MASK); failures.push(branch(code, Condition::NotZero)); @@ -65,12 +68,11 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress, targ } } if operand.shape == Shape::Vector64 { - code.extend(MOVQ_XMM0_XMM0); + clear_high_qword(code, 0); } commit(code, operand.destination, LEFT); - code.push(0xe9); // JMP rel32 skips the cold numerical exit. - let success = code.len(); - code.extend([0; size_of::()]); + // Skip the cold numerical exit. + let success = jump(code); let fallback = code.len(); super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); let end = code.len(); diff --git a/crates/stela-compiler/src/x86_64/simd/floating.rs b/crates/stela-compiler/src/x86_64/simd/floating.rs index 41575e1159..300a6cf842 100644 --- a/crates/stela-compiler/src/x86_64/simd/floating.rs +++ b/crates/stela-compiler/src/x86_64/simd/floating.rs @@ -2,27 +2,39 @@ use super::super::isa::ShiftOpcode; use super::{Host, commit, packed, read_vector, vector_offset}; use crate::aarch64::floating::{FPCR_AH, FPCR_NEP}; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Size}; +use crate::x86_64::simd::encode::{cond, guest}; use crate::{ TargetCpu, aarch64::simd::floating::{Operand, SignOperation}, }; -use alloc::vec::Vec; -fn test_control(code: &mut Vec, mask: u32) { - code.extend([0xf7, 0x87]); // test dword [rdi+fpcr],mask - code.extend((core::mem::offset_of!(crate::GuestState, fpcr) as u32).to_le_bytes()); - code.extend(mask.to_le_bytes()); +fn test_control(code: &mut Code, mask: u32) { + code.asm().test_imm( + Size::Dword, + guest(core::mem::offset_of!(crate::GuestState, fpcr) as u32), + mask as i32, + ); } -fn jump(code: &mut Vec, condition: Option) -> usize { - if let Some(condition) = condition { - code.extend([0x0f, condition]); - } else { - code.push(0xe9); +fn jump(code: &mut Code, condition: Option) -> usize { + let mut asm = code.asm(); + match condition { + Some(condition) => asm.jcc(condition), + None => asm.jmp(), + } + .offset() +} + +/// The operand size of a `bytes`-byte scalar lane. +fn size(bytes: u8) -> Size { + match bytes { + 2 => Size::Word, + 4 => Size::Dword, + 8 => Size::Qword, + _ => unreachable!("reviewed FP scalar size"), } - let patch = code.len(); - code.extend([0; 4]); - patch } fn resolve(code: &mut [u8], patch: usize) { @@ -30,91 +42,75 @@ fn resolve(code: &mut [u8], patch: usize) { code[patch..patch + 4].copy_from_slice(&delta.to_le_bytes()); } -fn load_lane(code: &mut Vec, vector: u8, bytes: u8, rcx: bool) { - match bytes { - 2 => code.extend([0x0f, 0xb7]), - 4 => code.push(0x8b), - 8 => code.extend([0x48, 0x8b]), - _ => unreachable!("reviewed FP scalar size"), +fn load_lane(code: &mut Code, vector: u8, bytes: u8, rcx: bool) { + let register = if rcx { Gpr::Rcx } else { Gpr::Rax }; + let lane = guest(vector_offset(vector)); + if bytes == 2 { + code.asm().movzx(Size::Dword, register, Size::Word, lane); + } else { + code.asm().mov_load(size(bytes), register, lane); } - code.push(if rcx { 0x8f } else { 0x87 }); - code.extend(vector_offset(vector).to_le_bytes()); } -fn zero_extended_commit(code: &mut Vec, destination: u8) { +fn zero_extended_commit(code: &mut Code, destination: u8) { packed(code, Host::MoveGprQword, 0, 0); // RAX was loaded at the exact scalar width. commit(code, destination, 0); } -fn scalar_sign( - code: &mut Vec, - operation: SignOperation, - destination: u8, - source: u8, - bytes: u8, -) { +fn scalar_sign(code: &mut Code, operation: SignOperation, destination: u8, source: u8, bytes: u8) { load_lane(code, source, bytes, false); test_control(code, FPCR_AH); - let ordinary = jump(code, Some(0x84)); // AH=0 skips all NaN classification. + let ordinary = jump(code, Some(Cond::E)); // AH=0 skips all NaN classification. // Compare unsigned magnitude to positive infinity. Strictly greater means // NaN, including signaling payloads; no numerical host FP instruction runs. - code.extend([0x48, 0x89, 0xc1]); // mov rcx,rax + let mut asm = code.asm(); + asm.mov(Size::Qword, Gpr::Rcx, Gpr::Rax); if bytes == 8 { - code.extend([0x48, 0x0f, 0xba, 0xf1, 63]); // btr rcx,63 - code.extend([0x48, 0xba]); // movabs rdx,+infinity - code.extend(0x7ff0_0000_0000_0000u64.to_le_bytes()); - code.extend([0x48, 0x39, 0xd1]); // cmp rcx,rdx + asm.bit_imm(BitTest::Btr, Size::Qword, Gpr::Rcx, 63); + asm.mov_imm64(Gpr::Rdx, 0x7ff0_0000_0000_0000); + asm.alu(Alu::Cmp, Size::Qword, Gpr::Rcx, Gpr::Rdx); } else { - code.extend([0x81, 0xe1]); // and ecx,magnitude_mask - code.extend((if bytes == 2 { 0x7fffu32 } else { 0x7fff_ffff }).to_le_bytes()); - code.extend([0x81, 0xf9]); // cmp ecx,+infinity - code.extend((if bytes == 2 { 0x7c00u32 } else { 0x7f80_0000 }).to_le_bytes()); + let magnitude: u32 = if bytes == 2 { 0x7fff } else { 0x7fff_ffff }; + let infinity: u32 = if bytes == 2 { 0x7c00 } else { 0x7f80_0000 }; + asm.alu_imm32(Alu::And, Size::Dword, Gpr::Rcx, magnitude as i32); + asm.alu_imm32(Alu::Cmp, Size::Dword, Gpr::Rcx, infinity as i32); } - let nan = jump(code, Some(0x87)); // AH=1 leaves every original NaN bit unchanged. + let nan = jump(code, Some(Cond::A)); // AH=1 leaves every original NaN bit unchanged. resolve(code, ordinary); - if bytes == 8 { - code.push(0x48); - } - code.extend([ - 0x0f, - 0xba, + code.asm().bit_imm( if operation == SignOperation::Abs { - 0xf0 + BitTest::Btr } else { - 0xf8 + BitTest::Btc }, + if bytes == 8 { Size::Qword } else { Size::Dword }, + Gpr::Rax, bytes * 8 - 1, - ]); // BTR/BTC RAX/EAX,sign + ); resolve(code, nan); test_control(code, FPCR_NEP); - let merging = jump(code, Some(0x85)); + let merging = jump(code, Some(Cond::Ne)); zero_extended_commit(code, destination); let completed = jump(code, None); resolve(code, merging); // NEP merges with old Vd, not Vn. Exact-width store avoids a destination load. - match bytes { - 2 => code.extend([0x66, 0x89, 0x87]), - 4 => code.extend([0x89, 0x87]), - 8 => code.extend([0x48, 0x89, 0x87]), - _ => unreachable!(), - } - code.extend(vector_offset(destination).to_le_bytes()); + code.asm() + .mov_store(size(bytes), guest(vector_offset(destination)), Gpr::Rax); resolve(code, completed); } -fn splat(code: &mut Vec, xmm: u8, lane: u64, lane_bytes: u8) { +fn splat(code: &mut Code, xmm: u8, lane: u64, lane_bytes: u8) { let mut low = 0; for index in 0..8 / lane_bytes { low |= lane << (index * lane_bytes * 8); } - code.extend([0x48, 0xb9]); - code.extend(low.to_le_bytes()); + code.asm().mov_imm64(Gpr::Rcx, low); packed(code, Host::MoveGprQword, xmm, 1); packed(code, Host::UnpackLowQword, xmm, xmm); } fn vector_sign( - code: &mut Vec, + code: &mut Code, operation: SignOperation, destination: u8, source: u8, @@ -134,7 +130,7 @@ fn vector_sign( } .emit(code, 1, lane_bytes * 8 - 1); test_control(code, FPCR_AH); - let ordinary = jump(code, Some(0x84)); + let ordinary = jump(code, Some(Cond::E)); packed(code, Host::MoveAligned, 2, 1); packed(code, Host::AndNot, 2, 0); // XMM2 = unsigned magnitude. let infinity = match lane_bytes { @@ -179,7 +175,7 @@ fn vector_sign( commit(code, destination, result); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { match *operand { Operand::Select { destination, @@ -192,10 +188,17 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { load_lane(code, left, lane_bytes, false); if let Some(jcc) = predicate { load_lane(code, right, lane_bytes, true); // MOV loads preserve predicate flags. - if lane_bytes == 8 { - code.push(0x48); - } - code.extend([0x0f, (jcc ^ 1) - 0x40, 0xc1]); // CMOV false RAX/EAX,RCX/ECX + // CMOV on the false condition: RAX/EAX takes RCX/ECX. + code.asm().cmov( + cond(jcc ^ 1), + if lane_bytes == 8 { + Size::Qword + } else { + Size::Dword + }, + Gpr::Rax, + Gpr::Rcx, + ); } zero_extended_commit(code, destination); } @@ -233,7 +236,6 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; #[test] fn checked_qword_classifier_and_no_numeric_host_fp() { @@ -245,9 +247,9 @@ mod tests { bytes: 16, scalar: false, }; - let mut baseline = Vec::new(); + let mut baseline = Code::new(); emit(&mut baseline, &operation, TargetCpu::Baseline); - let mut optimized = Vec::new(); + let mut optimized = Code::new(); emit(&mut optimized, &operation, TargetCpu::Sse42); assert!( !baseline diff --git a/crates/stela-compiler/src/x86_64/simd/fused.rs b/crates/stela-compiler/src/x86_64/simd/fused.rs index bac499460d..0eb4d35bde 100644 --- a/crates/stela-compiler/src/x86_64/simd/fused.rs +++ b/crates/stela-compiler/src/x86_64/simd/fused.rs @@ -10,10 +10,11 @@ use super::numerical::{ test_control, vector_exponent_range, zero_product_check, }; use super::{Host, commit, packed}; +use crate::x86_64::asm::Code; use crate::{ GuestAddress, TargetCpu, aarch64::{ - floating::{FPCR_EXCEPTION_ENABLE_MASK, FPCR_NEP, Format, fused::FusedOperation}, + floating::{FPCR_EXCEPTION_ENABLE_MASK, FPCR_NEP, Format}, simd::{arithmetic::Shape, fused::Operand}, }, block::ExitKind, @@ -27,33 +28,18 @@ const RIGHT: u8 = 1; const SIGN_MASK: u8 = 2; const ADDEND: u8 = 6; const ORIGINAL_ADDEND: u8 = 7; -const SSE_ESCAPE: u8 = 0x0f; -const MOV_SCALAR: u8 = 0x10; -const SINGLE_PREFIX: u8 = 0xf3; -const DOUBLE_PREFIX: u8 = 0xf2; -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -fn fused_opcode(operation: FusedOperation) -> FusedOpcode { - match operation { - FusedOperation::Add => FusedOpcode::MultiplyAdd, - FusedOperation::Subtract => FusedOpcode::NegativeMultiplyAdd, - FusedOperation::NegatedAdd => FusedOpcode::NegativeMultiplySubtract, - FusedOperation::NegatedSubtract => FusedOpcode::MultiplySubtract, - } -} - -fn emit_checked_fma(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn emit_checked_fma(code: &mut Code, operand: &Operand, target: TargetCpu) { emit_fma( code, operand.format, operand.shape, - fused_opcode(operand.operation), + FusedOpcode::from(operand.operation), target, ); } -fn prepare_right(code: &mut Vec, operand: &Operand) { +fn prepare_right(code: &mut Code, operand: &Operand) { read_numerical_right( code, operand.format, @@ -63,7 +49,7 @@ fn prepare_right(code: &mut Vec, operand: &Operand) { ); } -fn prepare_negation(code: &mut Vec, operand: &Operand) -> u8 { +fn prepare_negation(code: &mut Code, operand: &Operand) -> u8 { let merge = if operand.shape == Shape::Scalar && operand.operation.negate_addend() { packed(code, Host::MoveAligned, ORIGINAL_ADDEND, ADDEND); ORIGINAL_ADDEND @@ -90,7 +76,7 @@ fn prepare_negation(code: &mut Vec, operand: &Operand) -> u8 { /// With FMA3, S/D forms return their [`ColdSplit`]. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu, @@ -179,16 +165,12 @@ pub(in crate::x86_64) fn emit( commit_inexact(code); if operand.shape == Shape::Scalar { // Register MOVSS/MOVSD replaces only the result lane of A. - code.extend([ - if operand.format == Format::Single { - SINGLE_PREFIX - } else { - DOUBLE_PREFIX - }, - SSE_ESCAPE, - MOV_SCALAR, - REGISTER_DIRECT | (merge << MODRM_REGISTER_SHIFT) | LEFT, - ]); + if operand.format == Format::Single { + Host::MoveScalarSingle + } else { + Host::MoveScalarDouble + } + .register(code, merge, LEFT, crate::TargetCpu::Baseline); test_control(code, FPCR_NEP); let merging = branch(code, Condition::NotZero); clear_scalar(code, operand.format, merge); @@ -222,7 +204,7 @@ pub(in crate::x86_64) fn emit( /// and past the full path, and those between the sticky path and the rest /// ([`ColdSplit`]). fn sticky_path( - code: &mut Vec, + code: &mut Code, operand: &Operand, target: TargetCpu, entry: Entry, diff --git a/crates/stela-compiler/src/x86_64/simd/fused/half.rs b/crates/stela-compiler/src/x86_64/simd/fused/half.rs index ba0e9e40e4..17e4f88833 100644 --- a/crates/stela-compiler/src/x86_64/simd/fused/half.rs +++ b/crates/stela-compiler/src/x86_64/simd/fused/half.rs @@ -1,10 +1,11 @@ //! Exact finite Half FMA, with one integer rounding to the target format. use super::super::super::isa::ShiftOpcode; use super::super::numerical::{ - ArithmeticOpcode, Condition, VZEROUPPER, branch, emit_fma, emit_opcode_to, jump, + ArithmeticOpcode, Condition, branch, emit_fma, emit_opcode_to, jump, prepare_vector_input_range, resolve, test_control, vector_exponent_range, }; use super::super::{Host, commit, half as lanes, packed}; +use crate::x86_64::asm::{Alu, Code, Disp, Gpr, Mem, ShiftOp, Size}; use crate::{ GuestAddress, TargetCpu, aarch64::{ @@ -27,30 +28,48 @@ const HALF_EXPONENT_MASK: u8 = 31; const EXPONENT_SPAN_BIAS: u8 = 16; const MAXIMUM_BIASED_SPAN: u8 = 71; -fn load_half(code: &mut Vec, slot: u8) { - // MOVZX EAX, word [RSP + R11*2 + slot]. R11 is the active lane index. - code.extend([0x42, 0x0f, 0xb7, 0x44, 0x5c, slot]); +use Gpr::{R11, Rax, Rcx, Rsp}; + +/// `[rsp + r11*2 + slot]`: the active lane, R11, of a frame slot. +fn lane(slot: u8) -> Mem { + Mem::indexed(Rsp, R11, 2, slot.into()).with_width(Disp::Byte) } -fn exponent(code: &mut Vec, slot: u8) { +/// `[rsp + slot]`, a frame slot. +fn frame(slot: u8) -> Mem { + Mem::base(Rsp, slot.into()) +} + +fn load_half(code: &mut Code, slot: u8) { + code.asm().movzx(Size::Dword, Rax, Size::Word, lane(slot)); +} + +fn exponent(code: &mut Code, slot: u8) { load_half(code, slot); - code.extend([0xc1, 0xe8, Format::Half.fraction_bits() as u8]); // SHR EAX,10 - code.extend([0x83, 0xe0, HALF_EXPONENT_MASK]); + let mut asm = code.asm(); + asm.shift_imm( + ShiftOp::Shr, + Size::Dword, + Rax, + Format::Half.fraction_bits() as u8, + ); + asm.alu_imm8(Alu::And, Size::Dword, Rax, HALF_EXPONENT_MASK as i8); } -fn exact_span(code: &mut Vec, rollback: &mut Vec) { +fn exact_span(code: &mut Code, rollback: &mut Vec) { exponent(code, LEFT_SLOT); - code.extend([0x89, 0xc1]); // MOV ECX,EAX + code.asm().mov(Size::Dword, Rcx, Rax); exponent(code, RIGHT_SLOT); - code.extend([0x01, 0xc1]); // ADD ECX,EAX + code.asm().alu(Alu::Add, Size::Dword, Rcx, Rax); exponent(code, ADDEND_SLOT); - code.extend([0x29, 0xc1]); // SUB ECX,EAX - code.extend([0x83, 0xc1, EXPONENT_SPAN_BIAS]); - code.extend([0x83, 0xf9, MAXIMUM_BIASED_SPAN]); + let mut asm = code.asm(); + asm.alu(Alu::Sub, Size::Dword, Rcx, Rax); + asm.alu_imm8(Alu::Add, Size::Dword, Rcx, EXPONENT_SPAN_BIAS as i8); + asm.alu_imm8(Alu::Cmp, Size::Dword, Rcx, MAXIMUM_BIASED_SPAN as i8); rollback.push(branch(code, Condition::Above)); } -fn widen_sources(code: &mut Vec, target: TargetCpu) { +fn widen_sources(code: &mut Code, target: TargetCpu) { load_half(code, LEFT_SLOT); lanes::widen_normal(code, target); packed(code, Host::MoveAligned, lanes::LEFT, lanes::RESULT); @@ -61,14 +80,14 @@ fn widen_sources(code: &mut Vec, target: TargetCpu) { lanes::widen_normal(code, target); } -fn arithmetic(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn arithmetic(code: &mut Code, operand: &Operand, target: TargetCpu) { if target.supports(TargetCpu::Fma) { // Original signs: the FMA opcode performs the pre-round sign changes. emit_fma( code, Format::Double, Shape::Scalar, - super::fused_opcode(operand.operation), + super::super::numerical::FusedOpcode::from(operand.operation), target, ); } else { @@ -98,7 +117,7 @@ fn arithmetic(code: &mut Vec, operand: &Operand, target: TargetCpu) { packed(code, Host::MoveAligned, lanes::RESULT, lanes::LEFT); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu) { debug_assert_eq!(operand.format, Format::Half); let mut helper = Vec::new(); let mut rollback = Vec::new(); @@ -110,7 +129,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress, targ target }; if widening.supports(TargetCpu::F16c) || target.supports(TargetCpu::Fma) { - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } // FPMulAdd retains enabled exceptions under either AH setting. test_control(code, FPCR_EXCEPTION_ENABLE_MASK); @@ -126,12 +145,14 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress, targ vector_exponent_range(code, Format::Half, operand.shape, source); helper.push(branch(code, Condition::NotZero)); } - code.extend([0x48, 0x83, 0xec, FRAME_BYTES]); - code.extend([0xf3, 0x0f, 0x7f, 0x04, 0x24]); // MOVDQU [RSP],XMM0 - code.extend([0xf3, 0x0f, 0x7f, 0x4c, 0x24, RIGHT_SLOT]); - code.extend([0xf3, 0x0f, 0x7f, 0x74, 0x24, ADDEND_SLOT]); + let baseline = TargetCpu::Baseline; + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Rsp, FRAME_BYTES as i8); + Host::StoreUnaligned.emit(code, lanes::LEFT, frame(LEFT_SLOT), baseline); + Host::StoreUnaligned.emit(code, lanes::RIGHT, frame(RIGHT_SLOT), baseline); + Host::StoreUnaligned.emit(code, lanes::RESULT, frame(ADDEND_SLOT), baseline); packed(code, Host::Xor, SIGN_MASK, SIGN_MASK); - code.extend([0xf3, 0x0f, 0x7f, 0x54, 0x24, RESULT_SLOT]); + Host::StoreUnaligned.emit(code, SIGN_MASK, frame(RESULT_SLOT), baseline); if !target.supports(TargetCpu::Fma) && (operand.operation.negate_left() || operand.operation.negate_addend()) { @@ -156,21 +177,24 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress, targ lanes::RoundingPolicy::Fpcr, lanes::ResultSign::Preserve, ); - code.extend([0x66, 0x42, 0x89, 0x44, 0x5c, RESULT_SLOT]); - code.extend([0x41, 0xff, 0xc3]); // INC R11D - code.extend([ - 0x41, - 0x83, - 0xfb, - operand.shape.lane_count(Format::Half) as u8, - ]); + let mut asm = code.asm(); + asm.mov_store(Size::Word, lane(RESULT_SLOT), Rax); + asm.inc(Size::Dword, R11); + asm.alu_imm8( + Alu::Cmp, + Size::Dword, + R11, + operand.shape.lane_count(Format::Half) as i8, + ); let more = branch(code, Condition::Below); resolve(code, more, loop_start); - code.extend([0xf3, 0x0f, 0x6f, 0x44, 0x24, RESULT_SLOT]); - code.extend([0x48, 0x83, 0xc4, FRAME_BYTES]); + Host::LoadUnaligned.emit(code, lanes::LEFT, frame(RESULT_SLOT), baseline); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Rsp, FRAME_BYTES as i8); let success = jump(code); let rollback_start = code.len(); - code.extend([0x48, 0x83, 0xc4, FRAME_BYTES]); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Rsp, FRAME_BYTES as i8); let helper_start = code.len(); super::super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); let commit_start = code.len(); diff --git a/crates/stela-compiler/src/x86_64/simd/half.rs b/crates/stela-compiler/src/x86_64/simd/half.rs index d912dd2126..61c8a9b3c1 100644 --- a/crates/stela-compiler/src/x86_64/simd/half.rs +++ b/crates/stela-compiler/src/x86_64/simd/half.rs @@ -1,4 +1,8 @@ //! Half-precision lane unpacking, rounding and packing for normal values. +use super::numerical::jump; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::{Alu, Asm, Code, Gpr, Mem, Rm, ShiftOp, Size}; +use crate::x86_64::simd::encode::guest; use alloc::vec::Vec; mod kernel; use super::numerical::{Condition, RESULT_MINIMUM_EXPONENT, branch, resolve, test_control}; @@ -15,11 +19,9 @@ pub(super) const RESULT: u8 = 6; pub(super) const ORIGINAL_LEFT: u8 = 7; const ZERO: u8 = 2; const FIRST_LANE: u8 = 0; -const JMP_REL32: u8 = 0xe9; const SIGN_BITS: u32 = 1; const FPCR_ROUNDING_LOW: u32 = 1 << FPCR_ROUNDING_SHIFT; const FPCR_ROUNDING_HIGH: u32 = FPCR_ROUNDING_LOW << 1; -const XOR_EAX_IMM32: u8 = 0x35; #[derive(Clone, Copy, PartialEq, Eq)] pub(in crate::x86_64) enum RoundingPolicy { @@ -46,66 +48,12 @@ const HOST_VECTOR_BYTES: u8 = 16; const HALF_RIGHT_SLOT: u8 = HOST_VECTOR_BYTES; const HALF_RESULT_SLOT: u8 = HOST_VECTOR_BYTES * 2; const HALF_STACK_BYTES: u8 = HALF_RESULT_SLOT + HOST_VECTOR_BYTES; -const SUB_RSP: &[u8] = &[0x48, 0x83, 0xec]; -const ADD_RSP: &[u8] = &[0x48, 0x83, 0xc4]; -const SAVE_LEFT: &[u8] = &[0xf3, 0x0f, 0x7f, 0x04, 0x24]; -const SAVE_RIGHT: &[u8] = &[0xf3, 0x0f, 0x7f, 0x4c, 0x24, HALF_RIGHT_SLOT]; -const SAVE_ZERO_RESULT: &[u8] = &[0xf3, 0x0f, 0x7f, 0x54, 0x24, HALF_RESULT_SLOT]; -const LOAD_RESULT: &[u8] = &[0xf3, 0x0f, 0x6f, 0x44, 0x24, HALF_RESULT_SLOT]; -const LOAD_LEFT_HALF: &[u8] = &[0x42, 0x0f, 0xb7, 0x04, 0x5c]; -const LOAD_RIGHT_HALF: &[u8] = &[0x42, 0x0f, 0xb7, 0x4c, 0x5c, HALF_RIGHT_SLOT]; -const STORE_RESULT_HALF: &[u8] = &[0x66, 0x42, 0x89, 0x44, 0x5c, HALF_RESULT_SLOT]; -const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; -const XOR_R11D_R11D: &[u8] = &[0x45, 0x31, 0xdb]; -const INC_R11D: &[u8] = &[0x41, 0xff, 0xc3]; -const CMP_R11D: &[u8] = &[0x41, 0x83, 0xfb]; -const MOVABS_R8: &[u8] = &[0x49, 0xb8]; -const MOVABS_R9: &[u8] = &[0x49, 0xb9]; -const MOVABS_RDX: &[u8] = &[0x48, 0xba]; -const MOV_EDX_EAX: &[u8] = &[0x89, 0xc2]; -const MOV_EDX_ECX: &[u8] = &[0x89, 0xca]; -const AND_EAX_IMM32: u8 = 0x25; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const AND_EDX_IMM32: &[u8] = &[0x81, 0xe2]; -const SHL_RAX: &[u8] = &[0x48, 0xc1, 0xe0]; -const SHL_RCX: &[u8] = &[0x48, 0xc1, 0xe1]; -const SHL_RDX: &[u8] = &[0x48, 0xc1, 0xe2]; -const SHR_RAX: &[u8] = &[0x48, 0xc1, 0xe8]; -const SHR_RCX: &[u8] = &[0x48, 0xc1, 0xe9]; -const SHR_RDX: &[u8] = &[0x48, 0xc1, 0xea]; -const SHR_EDX: &[u8] = &[0xc1, 0xea]; -const SHL_EDX: &[u8] = &[0xc1, 0xe2]; -const SHL_ECX: &[u8] = &[0xc1, 0xe1]; -const ADD_RAX_R8: &[u8] = &[0x4c, 0x01, 0xc0]; -const ADD_RCX_R9: &[u8] = &[0x4c, 0x01, 0xc9]; -const SUB_RAX_R9: &[u8] = &[0x4c, 0x29, 0xc8]; -const OR_RAX_RDX: &[u8] = &[0x48, 0x09, 0xd0]; -const OR_RCX_RDX: &[u8] = &[0x48, 0x09, 0xd1]; -const OR_EAX_ECX: &[u8] = &[0x09, 0xc8]; -const MOVQ_XMM0_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xc0]; -const MOVQ_XMM1_RCX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xc9]; -const MOVD_XMM0_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xc0]; -const MOVD_XMM1_ECX: &[u8] = &[0x66, 0x0f, 0x6e, 0xc9]; -const CVTSS2SD_XMM0_XMM0: &[u8] = &[0xf3, 0x0f, 0x5a, 0xc0]; -const CVTSS2SD_XMM1_XMM1: &[u8] = &[0xf3, 0x0f, 0x5a, 0xc9]; -const MOVQ_RAX_XMM6: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xf0]; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const BTR_RDX_IMM8: &[u8] = &[0x48, 0x0f, 0xba, 0xf2]; -const TEST_RDX_RDX: &[u8] = &[0x48, 0x85, 0xd2]; -const BTR_RAX: &[u8] = &[0x48, 0x0f, 0xba, 0xf0]; -const BT_RAX: &[u8] = &[0x48, 0x0f, 0xba, 0xe0]; -const SUB_EDX_IMM32: &[u8] = &[0x81, 0xea]; -const SUB_EDX_IMM8: &[u8] = &[0x83, 0xea]; -const CMP_EDX_IMM8: &[u8] = &[0x83, 0xfa]; -const SETNE_DL: &[u8] = &[0x0f, 0x95, 0xc2]; -const MOVZX_EDX_DL: &[u8] = &[0x0f, 0xb6, 0xd2]; -const OR_R10D_EDX: &[u8] = &[0x41, 0x09, 0xd2]; -const ADC_RAX_RDX: &[u8] = &[0x48, 0x11, 0xd0]; -const ADD_RAX_RDX: &[u8] = &[0x48, 0x01, 0xd0]; -const TEST_ECX_ECX: &[u8] = &[0x85, 0xc9]; -const OR_STATE_R10D: &[u8] = &[0x44, 0x09, 0x97]; -const PINSRW_XMM7_EAX: &[u8] = &[0x66, 0x0f, 0xc4, 0xf8, FIRST_LANE]; +/// R10D accumulates fresh IXC; R11D indexes the active lane. +const INEXACT_LANES: Gpr = Gpr::R10; +const LANE: Gpr = Gpr::R11; +/// R8 and R9 hold the left and unscaled Half-to-Double biases. +const LEFT_BIAS: Gpr = Gpr::R8; +const PACK_BIAS: Gpr = Gpr::R9; const HALF_TO_DOUBLE_SHIFT: u8 = (Format::Double.fraction_bits() - Format::Half.fraction_bits()) as u8; const HALF_TO_DOUBLE_SIGN_SHIFT: u8 = (Format::Double.bits() - Format::Half.bits()) as u8; @@ -117,132 +65,137 @@ const HALF_NORMAL_EXPONENT_COUNT: u8 = ((Format::Half.exponent_mask() >> Format::Half.fraction_bits()) - RESULT_MINIMUM_EXPONENT as u64) as u8; -const MOVZX_EAX_AX: &[u8] = &[0x0f, 0xb7, 0xc0]; -const MOVD_XMM6_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xf0]; -const CVTSS2SD_XMM6_XMM6: &[u8] = &[0xf3, 0x0f, 0x5a, 0xf6]; -const MOVQ_XMM6_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xf0]; -const ADD_RAX_R9: &[u8] = &[0x4c, 0x01, 0xc8]; - -fn jump(code: &mut Vec) -> usize { - code.push(JMP_REL32); - let patch = code.len(); - code.extend(0i32.to_le_bytes()); - patch +/// `[rsp + slot]` in the private frame. +fn slot(offset: u8) -> Mem { + Mem::base(Gpr::Rsp, offset.into()) } -fn shift(code: &mut Vec, opcode: &[u8], amount: u8) { - code.extend(opcode); - code.push(amount); +/// `[rsp + r11*2 + slot]`: the active Half lane of a frame slot. +fn lane(offset: u8) -> Mem { + Mem::indexed(Gpr::Rsp, LANE, 2, offset.into()) } -fn immediate64(code: &mut Vec, opcode: &[u8], value: u64) { - code.extend(opcode); - code.extend(value.to_le_bytes()); +/// Reserve (`Alu::Sub`) or release (`Alu::Add`) the private frame. +fn frame(code: &mut Code, op: Alu) { + code.asm() + .alu_imm8(op, Size::Qword, Gpr::Rsp, HALF_STACK_BYTES as i8); +} + +/// `and register32, imm32`, in the accumulator short form for EAX. +fn and_imm32(asm: &mut Asm, register: Gpr, value: u32) { + if register == Gpr::Rax { + asm.alu_accumulator_imm32(Alu::And, Size::Dword, value as i32); + } else { + asm.alu_imm32(Alu::And, Size::Dword, register, value as i32); + } +} + +/// Widen the normal raw Half in `value` to exact Double fields in `vector`, +/// rebasing its exponent by `bias`. EDX and flags are clobbered. +fn widen_fields(code: &mut Code, value: Gpr, bias: Gpr, vector: u8) { + let sign = Format::Half.sign_mask() as u32; + let mut asm = code.asm(); + asm.mov(Size::Dword, Gpr::Rdx, value); + and_imm32(&mut asm, value, sign - 1); + asm.shift_imm(ShiftOp::Shl, Size::Qword, value, HALF_TO_DOUBLE_SHIFT); + asm.alu(Alu::Add, Size::Qword, value, bias); + asm.alu_imm32(Alu::And, Size::Dword, Gpr::Rdx, sign as i32); + asm.shift_imm( + ShiftOp::Shl, + Size::Qword, + Gpr::Rdx, + HALF_TO_DOUBLE_SIGN_SHIFT, + ); + asm.alu(Alu::Or, Size::Qword, value, Gpr::Rdx); + asm.movq_to_xmm(vector, value); } /// Inputs XMM0/XMM1 are snapshotted before any widened lane overwrites them. -pub(super) fn allocate_frame(code: &mut Vec) { - code.extend(SUB_RSP); - code.push(HALF_STACK_BYTES); - code.extend(SAVE_LEFT); - code.extend(SAVE_RIGHT); +pub(super) fn allocate_frame(code: &mut Code) { + let baseline = TargetCpu::Baseline; + frame(code, Alu::Sub); + Host::StoreUnaligned.emit(code, LEFT, slot(0), baseline); + Host::StoreUnaligned.emit(code, RIGHT, slot(HALF_RIGHT_SLOT), baseline); packed(code, Host::Xor, ZERO, ZERO); - code.extend(SAVE_ZERO_RESULT); + Host::StoreUnaligned.emit(code, ZERO, slot(HALF_RESULT_SLOT), baseline); } -pub(super) fn set_biases(code: &mut Vec, scale: LeftScale) { +pub(super) fn set_biases(code: &mut Code, scale: LeftScale) { let left_bias = HALF_TO_DOUBLE_BIAS - match scale { LeftScale::Identity => 0, LeftScale::Halved => 1u64 << Format::Double.fraction_bits(), }; - immediate64(code, MOVABS_R8, left_bias); + code.asm().mov_imm64(LEFT_BIAS, left_bias); set_pack_bias(code); } /// Checked hardware widening needs only the integer packer's unscaled bias. -pub(super) fn set_pack_bias(code: &mut Vec) { - immediate64(code, MOVABS_R9, HALF_TO_DOUBLE_BIAS); +pub(super) fn set_pack_bias(code: &mut Code) { + code.asm().mov_imm64(PACK_BIAS, HALF_TO_DOUBLE_BIAS); } /// Family constants may be prepared after biases and before this loop label. -pub(super) fn start_lanes(code: &mut Vec) -> usize { - code.extend(XOR_R10D_R10D); - code.extend(XOR_R11D_R11D); +pub(super) fn start_lanes(code: &mut Code) -> usize { + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, INEXACT_LANES, INEXACT_LANES); + asm.alu(Alu::Xor, Size::Dword, LANE, LANE); code.len() } /// Normal Half field construction is exact and cannot raise host FP status. -pub(super) fn widen_lane(code: &mut Vec) { - code.extend(LOAD_LEFT_HALF); - code.extend(MOV_EDX_EAX); - code.push(AND_EAX_IMM32); - code.extend((Format::Half.sign_mask() as u32 - 1).to_le_bytes()); - shift(code, SHL_RAX, HALF_TO_DOUBLE_SHIFT); - code.extend(ADD_RAX_R8); - code.extend(AND_EDX_IMM32); - code.extend((Format::Half.sign_mask() as u32).to_le_bytes()); - shift(code, SHL_RDX, HALF_TO_DOUBLE_SIGN_SHIFT); - code.extend(OR_RAX_RDX); - code.extend(MOVQ_XMM0_RAX); - code.extend(LOAD_RIGHT_HALF); - code.extend(MOV_EDX_ECX); - code.extend(AND_ECX_IMM32); - code.extend((Format::Half.sign_mask() as u32 - 1).to_le_bytes()); - shift(code, SHL_RCX, HALF_TO_DOUBLE_SHIFT); - code.extend(ADD_RCX_R9); - code.extend(AND_EDX_IMM32); - code.extend((Format::Half.sign_mask() as u32).to_le_bytes()); - shift(code, SHL_RDX, HALF_TO_DOUBLE_SIGN_SHIFT); - code.extend(OR_RCX_RDX); - code.extend(MOVQ_XMM1_RCX); +pub(super) fn widen_lane(code: &mut Code) { + code.asm().movzx(Size::Dword, Gpr::Rax, Size::Word, lane(0)); + widen_fields(code, Gpr::Rax, LEFT_BIAS, LEFT); + code.asm() + .movzx(Size::Dword, Gpr::Rcx, Size::Word, lane(HALF_RIGHT_SLOT)); + widen_fields(code, Gpr::Rcx, PACK_BIAS, RIGHT); } /// Normal Half to Single to Double is exact. MOVZX and MOVD zero all inactive /// lanes before the packed hardware conversion, including poisoned scalar bits. -pub(super) fn widen_lane_checked(code: &mut Vec, target: TargetCpu) { - code.extend(LOAD_LEFT_HALF); - code.extend(MOVD_XMM0_EAX); - Host::ConvertHalfToSingle.register(code, LEFT, LEFT, target); - code.extend(CVTSS2SD_XMM0_XMM0); - code.extend(LOAD_RIGHT_HALF); - code.extend(MOVD_XMM1_ECX); - Host::ConvertHalfToSingle.register(code, RIGHT, RIGHT, target); - code.extend(CVTSS2SD_XMM1_XMM1); +pub(super) fn widen_lane_checked(code: &mut Code, target: TargetCpu) { + for (register, vector) in [(Gpr::Rax, LEFT), (Gpr::Rcx, RIGHT)] { + let offset = if vector == LEFT { 0 } else { HALF_RIGHT_SLOT }; + let mut asm = code.asm(); + asm.movzx(Size::Dword, register, Size::Word, lane(offset)); + asm.movd_to_xmm(vector, register); + Host::ConvertHalfToSingle.register(code, vector, vector, target); + code.asm().cvtss2sd(vector, Rm::Xmm(vector)); + } } pub(super) fn pack_lane( - code: &mut Vec, + code: &mut Code, rollback: &mut Vec, rounding: RoundingPolicy, sign: ResultSign, ) { kernel::emit_normal(code, rollback, rounding, sign); - code.extend(STORE_RESULT_HALF); + code.asm() + .mov_store(Size::Word, lane(HALF_RESULT_SLOT), Gpr::Rax); } /// Every failed output guard drops private status/results and restores RSP. /// Successful lanes return an assembled XMM0, final Half EAX and fresh IXC R10D. pub(super) fn finish_lanes( - code: &mut Vec, + code: &mut Code, lanes: u8, loop_start: usize, helper: &[usize], rollback: &[usize], pc: GuestAddress, ) { - code.extend(INC_R11D); - code.extend(CMP_R11D); - code.push(lanes); + let mut asm = code.asm(); + asm.inc(Size::Dword, LANE); + asm.alu_imm8(Alu::Cmp, Size::Dword, LANE, lanes as i8); let more = branch(code, Condition::Below); resolve(code, more, loop_start); - code.extend(LOAD_RESULT); - code.extend(ADD_RSP); - code.push(HALF_STACK_BYTES); + Host::LoadUnaligned.emit(code, LEFT, slot(HALF_RESULT_SLOT), TargetCpu::Baseline); + frame(code, Alu::Add); let success = jump(code); let rollback_start = code.len(); - code.extend(ADD_RSP); - code.push(HALF_STACK_BYTES); + frame(code, Alu::Add); let helper_start = code.len(); super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); let commit_start = code.len(); @@ -256,16 +209,20 @@ pub(super) fn finish_lanes( } /// The caller applies instruction-specific AH status policy before this store. -pub(super) fn commit_inexact(code: &mut Vec) { - code.extend(OR_STATE_R10D); - code.extend((core::mem::offset_of!(GuestState, fpsr) as u32).to_le_bytes()); +pub(super) fn commit_inexact(code: &mut Code) { + code.asm().alu( + Alu::Or, + Size::Dword, + guest(core::mem::offset_of!(GuestState, fpsr) as u32), + INEXACT_LANES, + ); } /// Original Vn is XMM7. Scalar-pair callers skip NEP merging entirely. -pub(super) fn merge_scalar(code: &mut Vec) { +pub(super) fn merge_scalar(code: &mut Code) { test_control(code, FPCR_NEP); let clearing = branch(code, Condition::Zero); - code.extend(PINSRW_XMM7_EAX); + code.asm().pinsrw(ORIGINAL_LEFT, Gpr::Rax, FIRST_LANE); packed(code, Host::MoveAligned, LEFT, ORIGINAL_LEFT); let merged = code.len(); resolve(code, clearing, merged); @@ -278,18 +235,25 @@ pub(super) fn merge_scalar(code: &mut Vec) { /// Callers own enabled-exception policy, finite-domain proofs, staging, fallback /// cleanup and guest commit. No frame, host environment, store or CALL is emitted. /// Clobbers RAX/RCX/RDX/R9/R10 and flags; every XMM and other GPR survives. -pub(in crate::x86_64) fn emit_normal_or_zero(code: &mut Vec, failures: &mut Vec) { +pub(in crate::x86_64) fn emit_normal_or_zero(code: &mut Code, failures: &mut Vec) { set_pack_bias(code); - code.extend(MOVQ_RAX_XMM6); - code.extend(MOV_RDX_RAX); - shift( - code, - BTR_RDX_IMM8, + let mut asm = code.asm(); + asm.movq_from_xmm(Gpr::Rax, RESULT); + asm.mov(Size::Qword, Gpr::Rdx, Gpr::Rax); + asm.bit_imm( + BitTest::Btr, + Size::Qword, + Gpr::Rdx, (Format::Double.bits() - SIGN_BITS) as u8, ); - code.extend(TEST_RDX_RDX); + asm.test(Size::Qword, Gpr::Rdx, Gpr::Rdx); let nonzero = branch(code, Condition::NotZero); - shift(code, SHR_RAX, HALF_TO_DOUBLE_SIGN_SHIFT); + code.asm().shift_imm( + ShiftOp::Shr, + Size::Qword, + Gpr::Rax, + HALF_TO_DOUBLE_SIGN_SHIFT, + ); let zero_done = jump(code); let normal_start = code.len(); resolve(code, nonzero, normal_start); @@ -304,26 +268,16 @@ pub(in crate::x86_64) use kernel::emit_normal as pack_normal; /// XMM6. R9 contains the unscaled Half-to-Double bias. Only RAX/RDX/flags and /// XMM6 are clobbered; no frame or MXCSR change occurs. Checked F16C receives /// an isolated Half with zero upper lanes, preserving the existing kernel. -pub(in crate::x86_64) fn widen_normal(code: &mut Vec, target: TargetCpu) { +pub(in crate::x86_64) fn widen_normal(code: &mut Code, target: TargetCpu) { if target.supports(TargetCpu::F16c) { // Isolate the selected Half before packed conversion: the next lane in // XMM7 may be an inactive sNaN. MOVD also zeros every higher Half lane. - code.extend(MOVZX_EAX_AX); - code.extend(MOVD_XMM6_EAX); + let mut asm = code.asm(); + asm.movzx(Size::Dword, Gpr::Rax, Size::Word, Gpr::Rax); + asm.movd_to_xmm(RESULT, Gpr::Rax); Host::ConvertHalfToSingle.register(code, RESULT, RESULT, target); - code.extend(CVTSS2SD_XMM6_XMM6); + code.asm().cvtss2sd(RESULT, Rm::Xmm(RESULT)); return; } - code.extend(MOV_EDX_EAX); - code.push(AND_EAX_IMM32); - code.extend((Format::Half.sign_mask() as u32 - 1).to_le_bytes()); - code.extend(SHL_RAX); - code.push(HALF_TO_DOUBLE_SHIFT); - code.extend(ADD_RAX_R9); - code.extend(AND_EDX_IMM32); - code.extend((Format::Half.sign_mask() as u32).to_le_bytes()); - code.extend(SHL_RDX); - code.push(HALF_TO_DOUBLE_SIGN_SHIFT); - code.extend(OR_RAX_RDX); - code.extend(MOVQ_XMM6_RAX); + widen_fields(code, Gpr::Rax, PACK_BIAS, RESULT); } diff --git a/crates/stela-compiler/src/x86_64/simd/half/kernel.rs b/crates/stela-compiler/src/x86_64/simd/half/kernel.rs index 6c64b454ab..f44b7291a8 100644 --- a/crates/stela-compiler/src/x86_64/simd/half/kernel.rs +++ b/crates/stela-compiler/src/x86_64/simd/half/kernel.rs @@ -1,16 +1,16 @@ //! Half-precision pack arithmetic, without frame or stores. use super::{ - ADC_RAX_RDX, ADD_RAX_RDX, AND_EAX_IMM32, BT_RAX, BTR_RAX, CMP_EDX_IMM8, Condition, FPCR_AH, - FPCR_ROUNDING_HIGH, FPCR_ROUNDING_LOW, Format, HALF_DISCARDED_MASK, HALF_NORMAL_EXPONENT_COUNT, - HALF_TO_DOUBLE_SHIFT, INEXACT, MOV_EDX_EAX, MOV_RCX_RAX, MOV_RDX_RAX, MOVABS_RDX, - MOVQ_RAX_XMM6, MOVZX_EDX_DL, OR_EAX_ECX, OR_R10D_EDX, RESULT_MINIMUM_EXPONENT, ResultSign, - RoundingPolicy, SETNE_DL, SHL_ECX, SHL_EDX, SHL_RDX, SHR_EDX, SHR_RAX, SHR_RCX, SHR_RDX, - SIGN_BITS, SUB_EDX_IMM8, SUB_EDX_IMM32, SUB_RAX_R9, TEST_ECX_ECX, XOR_EAX_IMM32, branch, - immediate64, jump, resolve, shift, test_control, + Condition, FPCR_AH, FPCR_ROUNDING_HIGH, FPCR_ROUNDING_LOW, Format, HALF_DISCARDED_MASK, + HALF_NORMAL_EXPONENT_COUNT, HALF_TO_DOUBLE_SHIFT, INEXACT, INEXACT_LANES, PACK_BIAS, RESULT, + RESULT_MINIMUM_EXPONENT, ResultSign, RoundingPolicy, SIGN_BITS, branch, jump, resolve, + test_control, }; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, ShiftOp, Size}; +use Gpr::{Rax, Rcx, Rdx}; use alloc::vec::Vec; -fn round_half_magnitude(code: &mut Vec, rounding: RoundingPolicy) { +fn round_half_magnitude(code: &mut Code, rounding: RoundingPolicy) { // RAX holds the rebased double fields, RCX the sign. let nearest_ah = if rounding == RoundingPolicy::AhNearestEven { test_control(code, FPCR_AH); @@ -26,25 +26,27 @@ fn round_half_magnitude(code: &mut Vec, rounding: RoundingPolicy) { if let Some(patch) = nearest_ah { resolve(code, patch, nearest); } - immediate64(code, MOVABS_RDX, HALF_DISCARDED_MASK >> 1); - shift(code, BT_RAX, HALF_TO_DOUBLE_SHIFT); - code.extend(ADC_RAX_RDX); + let mut asm = code.asm(); + asm.mov_imm64(Rdx, HALF_DISCARDED_MASK >> 1); + asm.bit_imm(BitTest::Bt, Size::Qword, Rax, HALF_TO_DOUBLE_SHIFT); + asm.alu(Alu::Adc, Size::Qword, Rax, Rdx); let nearest_done = jump(code); let high_start = code.len(); resolve(code, high, high_start); test_control(code, FPCR_ROUNDING_LOW); let truncating = branch(code, Condition::NotZero); - code.extend(TEST_ECX_ECX); + code.asm().test(Size::Dword, Rcx, Rcx); let negative_unmatched = branch(code, Condition::Zero); let negative_bias = jump(code); let positive_start = code.len(); resolve(code, positive, positive_start); - code.extend(TEST_ECX_ECX); + code.asm().test(Size::Dword, Rcx, Rcx); let positive_unmatched = branch(code, Condition::NotZero); let bias_start = code.len(); resolve(code, negative_bias, bias_start); - immediate64(code, MOVABS_RDX, HALF_DISCARDED_MASK); - code.extend(ADD_RAX_RDX); + let mut asm = code.asm(); + asm.mov_imm64(Rdx, HALF_DISCARDED_MASK); + asm.alu(Alu::Add, Size::Qword, Rax, Rdx); let end = code.len(); for patch in [ nearest_done, @@ -54,61 +56,79 @@ fn round_half_magnitude(code: &mut Vec, rounding: RoundingPolicy) { ] { resolve(code, patch, end); } - shift(code, SHR_RAX, HALF_TO_DOUBLE_SHIFT); + code.asm() + .shift_imm(ShiftOp::Shr, Size::Qword, Rax, HALF_TO_DOUBLE_SHIFT); } pub(in crate::x86_64) fn emit_normal( - code: &mut Vec, + code: &mut Code, rollback: &mut Vec, rounding: RoundingPolicy, sign: ResultSign, ) { - code.extend(MOVQ_RAX_XMM6); - code.extend(MOV_RCX_RAX); - shift(code, SHR_RCX, (Format::Double.bits() - SIGN_BITS) as u8); - shift(code, BTR_RAX, (Format::Double.bits() - SIGN_BITS) as u8); - code.extend(MOV_RDX_RAX); - shift(code, SHR_RDX, Format::Double.fraction_bits() as u8); - code.extend(SUB_EDX_IMM32); - code.extend( - (Format::Double.exponent_bias() - Format::Half.exponent_bias() - + u32::from(RESULT_MINIMUM_EXPONENT)) - .to_le_bytes(), + let sign_bit = (Format::Double.bits() - SIGN_BITS) as u8; + let rebase = Format::Double.exponent_bias() - Format::Half.exponent_bias() + + u32::from(RESULT_MINIMUM_EXPONENT); + let mut asm = code.asm(); + asm.movq_from_xmm(Rax, RESULT); + asm.mov(Size::Qword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rcx, sign_bit); + asm.bit_imm(BitTest::Btr, Size::Qword, Rax, sign_bit); + asm.mov(Size::Qword, Rdx, Rax); + asm.shift_imm( + ShiftOp::Shr, + Size::Qword, + Rdx, + Format::Double.fraction_bits() as u8, ); - code.extend(CMP_EDX_IMM8); - code.push(HALF_NORMAL_EXPONENT_COUNT); + asm.alu_imm32(Alu::Sub, Size::Dword, Rdx, rebase as i32); + asm.alu_imm8(Alu::Cmp, Size::Dword, Rdx, HALF_NORMAL_EXPONENT_COUNT as i8); rollback.push(branch(code, Condition::AboveOrEqual)); - code.extend(SUB_RAX_R9); - code.extend(MOV_RDX_RAX); - shift( - code, - SHL_RDX, + let mut asm = code.asm(); + asm.alu(Alu::Sub, Size::Qword, Rax, PACK_BIAS); + asm.mov(Size::Qword, Rdx, Rax); + asm.shift_imm( + ShiftOp::Shl, + Size::Qword, + Rdx, Format::Double.bits() as u8 - HALF_TO_DOUBLE_SHIFT, ); - code.extend(SETNE_DL); - code.extend(MOVZX_EDX_DL); - shift(code, SHL_EDX, INEXACT.trailing_zeros() as u8); - code.extend(OR_R10D_EDX); + asm.setcc(Cond::Ne, Rdx); + asm.movzx(Size::Dword, Rdx, Size::Byte, Rdx); + asm.shift_imm( + ShiftOp::Shl, + Size::Dword, + Rdx, + INEXACT.trailing_zeros() as u8, + ); + asm.alu(Alu::Or, Size::Dword, INEXACT_LANES, Rdx); round_half_magnitude(code, rounding); - code.extend(MOV_EDX_EAX); - shift(code, SHR_EDX, Format::Half.fraction_bits() as u8); - code.extend(SUB_EDX_IMM8); - code.push(RESULT_MINIMUM_EXPONENT); - code.extend(CMP_EDX_IMM8); - code.push(HALF_NORMAL_EXPONENT_COUNT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rdx, Rax); + asm.shift_imm( + ShiftOp::Shr, + Size::Dword, + Rdx, + Format::Half.fraction_bits() as u8, + ); + asm.alu_imm8(Alu::Sub, Size::Dword, Rdx, RESULT_MINIMUM_EXPONENT as i8); + asm.alu_imm8(Alu::Cmp, Size::Dword, Rdx, HALF_NORMAL_EXPONENT_COUNT as i8); rollback.push(branch(code, Condition::AboveOrEqual)); - shift(code, SHL_ECX, (Format::Half.bits() - SIGN_BITS) as u8); - code.extend(OR_EAX_ECX); + let mut asm = code.asm(); + asm.shift_imm( + ShiftOp::Shl, + Size::Dword, + Rcx, + (Format::Half.bits() - SIGN_BITS) as u8, + ); + asm.alu(Alu::Or, Size::Dword, Rax, Rcx); // Transform the target-rounded bits, preserving directed-rounding order. + let half_sign = Format::Half.sign_mask() as u32; match sign { ResultSign::Preserve => {} - ResultSign::Negate => { - code.push(XOR_EAX_IMM32); - code.extend((Format::Half.sign_mask() as u32).to_le_bytes()); - } + ResultSign::Negate => asm.alu_accumulator_imm32(Alu::Xor, Size::Dword, half_sign as i32), ResultSign::Absolute => { - code.push(AND_EAX_IMM32); - code.extend((Format::Half.sign_mask() as u32 - 1).to_le_bytes()); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, (half_sign - 1) as i32) } } } diff --git a/crates/stela-compiler/src/x86_64/simd/halving.rs b/crates/stela-compiler/src/x86_64/simd/halving.rs index 8b6e6a19e1..abbe5d807f 100644 --- a/crates/stela-compiler/src/x86_64/simd/halving.rs +++ b/crates/stela-compiler/src/x86_64/simd/halving.rs @@ -1,4 +1,5 @@ //! Overflow-safe halving arithmetic and narrowing/widening helpers. +use super::rearrange::{add_or_subtract, lane_constant}; use super::{ Host, commit, packed, products::extend, @@ -6,35 +7,14 @@ use super::{ rearrange::constant, shifts::{pack_truncated, right_shift, rounded_right}, }; +use crate::x86_64::asm::Code; use crate::{ TargetCpu, aarch64::simd::halving::{Kind, Operand}, x86_64::isa::ShiftOpcode as Shift, }; -use alloc::vec::Vec; -fn arithmetic(lane: u8, subtract: bool) -> Host { - match (subtract, lane) { - (false, 1) => Host::AddByte, - (false, 2) => Host::AddWord, - (false, 4) => Host::AddDword, - (false, 8) => Host::AddQword, - (true, 1) => Host::SubByte, - (true, 2) => Host::SubWord, - (true, 4) => Host::SubDword, - (true, 8) => Host::SubQword, - _ => unreachable!(), - } -} -fn lane_constant(code: &mut Vec, xmm: u8, lane: u8, value: u64) { - let bytes = value.to_le_bytes(); - constant( - code, - xmm, - core::array::from_fn(|i| bytes[i % usize::from(lane)]), - ); -} -fn half(code: &mut Vec, lane: u8, signed: bool, subtract: bool, round: bool) { +fn half(code: &mut Code, lane: u8, signed: bool, subtract: bool, round: bool) { if round && lane <= 2 { if signed { lane_constant(code, 2, lane, 1u64 << (lane * 8 - 1)); @@ -62,8 +42,8 @@ fn half(code: &mut Vec, lane: u8, signed: bool, subtract: bool, round: bool) packed(code, Host::And, 2, 3); right_shift(code, 0, lane, 1, signed); right_shift(code, 1, lane, 1, signed); - packed(code, arithmetic(lane, true), 0, 1); - packed(code, arithmetic(lane, true), 0, 2); + packed(code, add_or_subtract(lane, true), 0, 1); + packed(code, add_or_subtract(lane, true), 0, 2); } else { // floor average: (a&b)+((a^b)>>1). Ceil average: (a|b)-((a^b)>>1). packed(code, Host::MoveAligned, 2, 0); @@ -71,14 +51,14 @@ fn half(code: &mut Vec, lane: u8, signed: bool, subtract: bool, round: bool) packed(code, Host::Xor, 0, 1); right_shift(code, 0, lane, 1, signed); if round { - packed(code, arithmetic(lane, true), 2, 0); + packed(code, add_or_subtract(lane, true), 2, 0); packed(code, Host::MoveAligned, 0, 2); } else { - packed(code, arithmetic(lane, false), 0, 2); + packed(code, add_or_subtract(lane, false), 0, 2); } } } -fn pair_long(code: &mut Vec, lane: u8, signed: bool, target: TargetCpu) { +fn pair_long(code: &mut Code, lane: u8, signed: bool, target: TargetCpu) { if lane == 1 && !signed && target >= TargetCpu::Ssse3 { constant(code, 1, [1; 16]); Host::MultiplyAddUnsignedBytes.register(code, 0, 1, target); @@ -130,10 +110,10 @@ fn pair_long(code: &mut Vec, lane: u8, signed: bool, target: TargetCpu) { .emit(code, 1, lane * 8); } } - packed(code, arithmetic(lane * 2, false), 0, 1); + packed(code, add_or_subtract(lane * 2, false), 0, 1); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { let Operand { kind, destination, @@ -158,7 +138,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { upper, } => { read_vector(code, right, 1); - packed(code, arithmetic(lane * 2, subtract), 0, 1); + packed(code, add_or_subtract(lane * 2, subtract), 0, 1); rounded_right(code, lane * 2, lane * 8, false, round); pack_truncated(code, lane, upper, destination); return; @@ -181,7 +161,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { pair_long(code, lane, signed, target); if accumulate { read_vector(code, destination, 1); - packed(code, arithmetic(lane * 2, false), 0, 1); + packed(code, add_or_subtract(lane * 2, false), 0, 1); } } } diff --git a/crates/stela-compiler/src/x86_64/simd/i8mm.rs b/crates/stela-compiler/src/x86_64/simd/i8mm.rs index 7a26840f70..6734c3789d 100644 --- a/crates/stela-compiler/src/x86_64/simd/i8mm.rs +++ b/crates/stela-compiler/src/x86_64/simd/i8mm.rs @@ -1,5 +1,6 @@ //! Byte dot products and 2x8-by-8x2 matrix multiply-accumulate. use super::{Host, commit, packed, read_vector, shuffle}; +use crate::x86_64::asm::Code; use crate::{ TargetCpu, aarch64::simd::{ @@ -8,7 +9,6 @@ use crate::{ }, x86_64::isa::ShiftOpcode as Shift, }; -use alloc::vec::Vec; const LEFT: u8 = 0; const RIGHT: u8 = 1; @@ -33,7 +33,7 @@ const MATRIX_RIGHT_HIGH: u8 = 0xdd; // Dwords [1, 3, 1, 3]. /// XMM0/1 hold four byte groups. Separate even/odd bytes into exact signed /// words (unsigned bytes fit positive signed words), then combine PMADDWD sums. /// Six shifts avoid materializing the low-byte mask for one guest instruction. -fn dot_sum(code: &mut Vec, left_signed: bool, right_signed: bool) { +fn dot_sum(code: &mut Code, left_signed: bool, right_signed: bool) { packed(code, Host::MoveAligned, LEFT_HIGH, LEFT); packed(code, Host::MoveAligned, RIGHT_HIGH, RIGHT); for (low, high, signed) in [ @@ -54,7 +54,7 @@ fn dot_sum(code: &mut Vec, left_signed: bool, right_signed: bool) { packed(code, Host::AddDword, RESULT, LEFT_HIGH); } -fn matrix_sse2(code: &mut Vec, left_signed: bool, right_signed: bool) { +fn matrix_sse2(code: &mut Code, left_signed: bool, right_signed: bool) { // XMM5/6 keep the left and right inputs for both halves. shuffle(code, LEFT, ORIGINAL_LEFT, MATRIX_LEFT_LOW); shuffle(code, RIGHT, ORIGINAL_RIGHT, MATRIX_RIGHT_LOW); @@ -66,7 +66,7 @@ fn matrix_sse2(code: &mut Vec, left_signed: bool, right_signed: bool) { packed(code, Host::AddDword, RESULT, FIRST_HALF_SUM); } -fn matrix_ssse3(code: &mut Vec, left_signed: bool, right_signed: bool, target: TargetCpu) { +fn matrix_ssse3(code: &mut Code, left_signed: bool, right_signed: bool, target: TargetCpu) { // Widen the two contiguous rows/columns to words. XMM0/2 are rows 0/1; // XMM1/3 are columns 0/1. A single zero mask serves both unsigned inputs. packed(code, Host::Xor, EXTENSION_MASK, EXTENSION_MASK); @@ -106,7 +106,7 @@ fn matrix_ssse3(code: &mut Vec, left_signed: bool, right_signed: bool, targe Host::HorizontalAddDword.register(code, RESULT, LEFT_HIGH, target); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { let (left_signed, right_signed) = operand.kind.signedness(); match operand.kind { Kind::Matrix(_) if target.supports(TargetCpu::Ssse3) => { @@ -143,9 +143,9 @@ mod tests { fn emitted(word: u32, target: TargetCpu) -> Vec { let operand = crate::aarch64::simd::i8mm::decode(word).unwrap().unwrap(); - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, target); - code + code.into_bytes() } #[test] diff --git a/crates/stela-compiler/src/x86_64/simd/immediates.rs b/crates/stela-compiler/src/x86_64/simd/immediates.rs index 12d504cf61..541413cf18 100644 --- a/crates/stela-compiler/src/x86_64/simd/immediates.rs +++ b/crates/stela-compiler/src/x86_64/simd/immediates.rs @@ -1,12 +1,12 @@ //! Immediate construction and lane moves. use super::{Host, commit, packed, read_vector, rearrange}; +use crate::x86_64::asm::Code; use crate::{ TargetCpu, aarch64::simd::immediates::{ConstantOperation, Operand}, }; -use alloc::vec::Vec; -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { let Operand::Constant { destination, value, @@ -22,8 +22,8 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { if value == 0 { packed(code, Host::Xor, 0, 0); } else { - code.extend([0x48, 0xb9]); // MOVABS RCX, expanded low 64 bits - code.extend(value.to_le_bytes()); + // The expanded low 64 bits. + code.asm().mov_imm64(crate::x86_64::asm::Gpr::Rcx, value); packed(code, Host::MoveGprQword, 0, 1); if bytes == 16 { packed(code, Host::UnpackLowQword, 0, 0); diff --git a/crates/stela-compiler/src/x86_64/simd/integer_conversion.rs b/crates/stela-compiler/src/x86_64/simd/integer_conversion.rs index 83d51bc2be..27be3b9968 100644 --- a/crates/stela-compiler/src/x86_64/simd/integer_conversion.rs +++ b/crates/stela-compiler/src/x86_64/simd/integer_conversion.rs @@ -1,4 +1,5 @@ //! Conversions between FP and integers. +use super::numerical::jump; use super::numerical::{ ArithmeticOpcode, Condition, INPUT_MINIMUM_EXPONENT, Rounding, branch, clear_scalar, commit_inexact, emit_opcode, environment_round, exponent_range, prepare_vector_input_range, @@ -6,6 +7,11 @@ use super::numerical::{ vector_exponent_range, }; use super::{Host, commit, packed, read_vector, vector_offset}; +use crate::TargetCpu; +use crate::x86_64::asm::{Alu, Code, Gpr, Rm, ShiftOp, Size}; +use crate::x86_64::asm::{BitTest, FloatLanes}; +use crate::x86_64::isa::ShiftOpcode; +use crate::x86_64::simd::encode::guest; use crate::{ GuestAddress, aarch64::{ @@ -21,48 +27,11 @@ use crate::{ }, block::ExitKind, }; +use Gpr::{Rax, Rcx, Rdx}; use alloc::vec::Vec; -const SINGLE_PREFIX: u8 = 0xf3; -const DOUBLE_PREFIX: u8 = 0xf2; -const SSE_ESCAPE: u8 = 0x0f; -const REX_W: u8 = 0x48; -const REGISTER_DIRECT: u8 = 0xc0; -const CVT_INTEGER_TO_FLOAT: u8 = 0x2a; -const CVT_FLOAT_TO_INTEGER: u8 = 0x2d; -const CVTT_FLOAT_TO_INTEGER: u8 = 0x2c; -const CVT_DWORDS_TO_SINGLE: &[u8] = &[0x0f, 0x5b, 0xc0]; -const CVT_SINGLE_TO_DWORDS: &[u8] = &[0x66, 0x0f, 0x5b, 0xc0]; -const CVTT_SINGLE_TO_DWORDS: &[u8] = &[0xf3, 0x0f, 0x5b, 0xc0]; -const MOV_EAX_STATE: &[u8] = &[0x8b, 0x87]; -const MOV_RAX_STATE: &[u8] = &[0x48, 0x8b, 0x87]; -const MOVD_XMM0_STATE: &[u8] = &[0x66, 0x0f, 0x6e, 0x87]; -const MOVQ_XMM0_STATE: &[u8] = &[0xf3, 0x0f, 0x7e, 0x87]; -const MOV_EAX_EAX: &[u8] = &[0x89, 0xc0]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const SHR_RDX_32: &[u8] = &[0x48, 0xc1, 0xea, 32]; -const TEST_EDX_EDX: &[u8] = &[0x85, 0xd2]; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const SHR_RCX_63: &[u8] = &[0x48, 0xc1, 0xe9, 63]; -const SHR_RAX_1: &[u8] = &[0x48, 0xd1, 0xe8]; -const AND_ECX_1: &[u8] = &[0x83, 0xe1, 1]; -const OR_RAX_RCX: &[u8] = &[0x48, 0x09, 0xc8]; -const BT_RAX_63: &[u8] = &[0x48, 0x0f, 0xba, 0xe0, 63]; -const BTS_RAX_63: &[u8] = &[0x48, 0x0f, 0xba, 0xe8, 63]; -const MOVABS_RDX: &[u8] = &[0x48, 0xba]; -const MOVQ_XMM1_RDX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xca]; -const MOVD_EAX_XMM0: &[u8] = &[0x66, 0x0f, 0x7e, 0xc0]; -const MOVQ_RAX_XMM0: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xc0]; -const MOVD_XMM1_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xc8]; -const MOVQ_XMM1_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xc8]; -const MOVSS_XMM0_XMM1: &[u8] = &[0xf3, 0x0f, 0x10, 0xc1]; -const MOVSD_XMM0_XMM1: &[u8] = &[0xf2, 0x0f, 0x10, 0xc1]; -const PSLLDQ_XMM1: &[u8] = &[0x66, 0x0f, 0x73, 0xf9]; -const SHUFPS_XMM1_BROADCAST: &[u8] = &[0x0f, 0xc6, 0xc9, 0]; -const UNPCKLPD_XMM1_XMM1: &[u8] = &[0x66, 0x0f, 0x14, 0xc9]; -const UCOMISS_XMM0_XMM1: &[u8] = &[0x0f, 0x2e, 0xc1]; -const UCOMISD_XMM0_XMM1: &[u8] = &[0x66, 0x0f, 0x2e, 0xc1]; -const JMP_REL32: u8 = 0xe9; +const BROADCAST_LOW_SINGLE: u8 = 0; +const SIGN_BIT: u8 = 63; const RESULT_VECTOR: u8 = 0; const TEMPORARY_VECTOR: u8 = 1; const INTEGER_ACCUMULATOR: u8 = 6; @@ -71,27 +40,55 @@ const SINGLE_EXPONENT_BIAS: i16 = 127; const DOUBLE_EXPONENT_BIAS: i16 = 1023; const UNSIGNED_HIGH_EXPONENT: i16 = 63; -fn helper(code: &mut Vec, pc: GuestAddress) { +fn helper(code: &mut Code, pc: GuestAddress) { super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); } -fn jump(code: &mut Vec) -> usize { - code.push(JMP_REL32); - let patch = code.len(); - code.extend(0i32.to_le_bytes()); - patch +fn scalar_lanes(format: Format) -> FloatLanes { + match format { + Format::Single => FloatLanes::ScalarSingle, + Format::Double => FloatLanes::ScalarDouble, + Format::Half => unreachable!("half conversions use the exact core"), + } } -fn scalar_conversion(code: &mut Vec, format: Format, opcode: u8, wide: bool) { - code.push(match format { - Format::Single => SINGLE_PREFIX, - Format::Double => DOUBLE_PREFIX, - Format::Half => unreachable!("half conversions use the exact core"), - }); +fn width(wide: bool) -> Size { + if wide { Size::Qword } else { Size::Dword } +} + +/// `cvtsi2ss/sd xmm0, eax/rax`. +fn to_float(code: &mut Code, format: Format, wide: bool) { + code.asm() + .cvtsi2float(scalar_lanes(format), width(wide), RESULT_VECTOR, Rax); +} + +/// `cvt(t)ss/sd2si eax/rax, xmm0`. +fn from_float(code: &mut Code, format: Format, truncate: bool, wide: bool) { + code.asm().cvtfloat2si( + scalar_lanes(format), + truncate, + width(wide), + Rax, + Rm::Xmm(RESULT_VECTOR), + ); +} + +/// Move the low `width` lane of `vector` into RAX/EAX. +fn lane_from_vector(code: &mut Code, wide: bool, vector: u8) { if wide { - code.push(REX_W); + code.asm().movq_from_xmm(Rax, vector); + } else { + code.asm().movd_from_xmm(Rax, vector); + } +} + +/// Move RAX/EAX into the low lane of `vector`, zeroing the rest. +fn lane_to_vector(code: &mut Code, wide: bool, vector: u8) { + if wide { + code.asm().movq_to_xmm(vector, Rax); + } else { + code.asm().movd_to_xmm(vector, Rax); } - code.extend([SSE_ESCAPE, opcode, REGISTER_DIRECT]); } fn rounding(rounding: IntegerRounding) -> Rounding { @@ -114,47 +111,50 @@ fn integer_offset(integer: IntegerOperand, lane: u32) -> u32 { vector_offset(register) + lane * (format.width.bits() / BITS_PER_BYTE) } -fn read_integer(code: &mut Vec, integer: IntegerOperand, lane: u32) { +fn read_integer(code: &mut Code, integer: IntegerOperand, lane: u32) { let format = integer.format(); match integer { IntegerOperand::General { register, .. } => super::super::load(code, register), IntegerOperand::Simd { .. } => { - code.extend(if format.width == IntegerWidth::Bits64 { - MOV_RAX_STATE - } else { - MOV_EAX_STATE - }); - code.extend(integer_offset(integer, lane).to_le_bytes()); + code.asm().mov_load( + width(format.width == IntegerWidth::Bits64), + Rax, + guest(integer_offset(integer, lane)), + ); } } if !format.signed && format.width == IntegerWidth::Bits32 { // The shared GPR load is 64-bit; unsigned W conversion reads only Wn. - code.extend(MOV_EAX_EAX); + code.asm().mov(Size::Dword, Rax, Rax); } } -fn float_constant(code: &mut Vec, format: Format, exponent: i16, shape: Shape) { +fn float_constant(code: &mut Code, format: Format, exponent: i16, shape: Shape) { let (bias, fraction_bits) = match format { Format::Single => (SINGLE_EXPONENT_BIAS, Format::Single.fraction_bits()), Format::Double => (DOUBLE_EXPONENT_BIAS, Format::Double.fraction_bits()), Format::Half => unreachable!("half conversions use the exact core"), }; - code.extend(MOVABS_RDX); - code.extend( - (u64::try_from(bias + exponent).expect("normal conversion scale") << fraction_bits) - .to_le_bytes(), + let mut asm = code.asm(); + asm.mov_imm64( + Rdx, + u64::try_from(bias + exponent).expect("normal conversion scale") << fraction_bits, ); - code.extend(MOVQ_XMM1_RDX); + asm.movq_to_xmm(TEMPORARY_VECTOR, Rdx); if shape != Shape::Scalar { - code.extend(if format == Format::Single { - SHUFPS_XMM1_BROADCAST + if format == Format::Single { + asm.shufps( + TEMPORARY_VECTOR, + Rm::Xmm(TEMPORARY_VECTOR), + BROADCAST_LOW_SINGLE, + ); } else { - UNPCKLPD_XMM1_XMM1 - }); + asm.unpcklpd(TEMPORARY_VECTOR, Rm::Xmm(TEMPORARY_VECTOR)); + } } } -fn scale(code: &mut Vec, operand: &IntegerConversion, shape: Shape, direction: i16) { +fn scale(code: &mut Code, operand: &IntegerConversion, shape: Shape, direction: i16) { if operand.frac_bits != 0 { float_constant( code, @@ -172,23 +172,25 @@ fn scale(code: &mut Vec, operand: &IntegerConversion, shape: Shape, directio } } -fn convert_integer_lane(code: &mut Vec, operand: &IntegerConversion, lane: u32) { +fn convert_integer_lane(code: &mut Code, operand: &IntegerConversion, lane: u32) { let integer = operand.integer.format(); read_integer(code, operand.integer, lane); let wide = integer.width == IntegerWidth::Bits64 || !integer.signed; if integer.signed || integer.width != IntegerWidth::Bits64 { - scalar_conversion(code, operand.format, CVT_INTEGER_TO_FLOAT, wide); + to_float(code, operand.format, wide); } else { // High unsigned values do not fit CVTSI's signed input. Retaining a // sticky low bit before halving preserves all four rounding modes. - code.extend(MOV_RCX_RAX); - code.extend(SHR_RCX_63); + let mut asm = code.asm(); + asm.mov(Size::Qword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rcx, SIGN_BIT); let low = branch(code, Condition::Zero); - code.extend(MOV_RCX_RAX); - code.extend(AND_ECX_1); - code.extend(SHR_RAX_1); - code.extend(OR_RAX_RCX); - scalar_conversion(code, operand.format, CVT_INTEGER_TO_FLOAT, true); + let mut asm = code.asm(); + asm.mov(Size::Qword, Rcx, Rax); + asm.alu_imm8(Alu::And, Size::Dword, Rcx, 1); + asm.shift_one(ShiftOp::Shr, Size::Qword, Rax); + asm.alu(Alu::Or, Size::Qword, Rax, Rcx); + to_float(code, operand.format, true); emit_opcode( code, operand.format, @@ -199,7 +201,7 @@ fn convert_integer_lane(code: &mut Vec, operand: &IntegerConversion, lane: u let done = jump(code); let low_start = code.len(); resolve(code, low, low_start); - scalar_conversion(code, operand.format, CVT_INTEGER_TO_FLOAT, true); + to_float(code, operand.format, true); let end = code.len(); resolve(code, done, end); } @@ -207,20 +209,19 @@ fn convert_integer_lane(code: &mut Vec, operand: &IntegerConversion, lane: u scale(code, operand, Shape::Scalar, -1); } -fn pack_integer_lane(code: &mut Vec, width: IntegerWidth, lane: u32) { - code.extend(if width == IntegerWidth::Bits64 { - MOVQ_XMM1_RAX - } else { - MOVD_XMM1_EAX - }); +fn pack_integer_lane(code: &mut Code, width: IntegerWidth, lane: u32) { + lane_to_vector(code, width == IntegerWidth::Bits64, TEMPORARY_VECTOR); if lane != 0 { - code.extend(PSLLDQ_XMM1); - code.push((lane * (width.bits() / BITS_PER_BYTE)) as u8); + ShiftOpcode::LeftBytes.emit( + code, + TEMPORARY_VECTOR, + (lane * (width.bits() / BITS_PER_BYTE)) as u8, + ); } packed(code, Host::Or, INTEGER_ACCUMULATOR, TEMPORARY_VECTOR); } -fn finish_float(code: &mut Vec, operand: &IntegerConversion) { +fn finish_float(code: &mut Code, operand: &IntegerConversion) { commit_inexact(code); if operand.integer.shape() == Shape::Scalar { test_control(code, FPCR_NEP); @@ -233,7 +234,7 @@ fn finish_float(code: &mut Vec, operand: &IntegerConversion) { } pub(in crate::x86_64) fn from_integer( - code: &mut Vec, + code: &mut Code, operand: &IntegerConversion, pc: GuestAddress, ) { @@ -255,7 +256,12 @@ pub(in crate::x86_64) fn from_integer( unreachable!("vector integer source") }; read_numerical_vector(code, shape, register, RESULT_VECTOR); - code.extend(CVT_DWORDS_TO_SINGLE); + Host::ConvertPackedDwordToSingle.register( + code, + RESULT_VECTOR, + RESULT_VECTOR, + TargetCpu::Baseline, + ); scale(code, operand, shape, -1); } else if shape == Shape::Scalar { convert_integer_lane(code, operand, 0); @@ -263,11 +269,7 @@ pub(in crate::x86_64) fn from_integer( packed(code, Host::Xor, INTEGER_ACCUMULATOR, INTEGER_ACCUMULATOR); for lane in 0..shape.lane_count(operand.format) { convert_integer_lane(code, operand, lane); - code.extend(if operand.format == Format::Single { - MOVD_EAX_XMM0 - } else { - MOVQ_RAX_XMM0 - }); + lane_from_vector(code, operand.format == Format::Double, RESULT_VECTOR); pack_integer_lane(code, integer.width, lane); } packed(code, Host::MoveAligned, RESULT_VECTOR, INTEGER_ACCUMULATOR); @@ -284,7 +286,7 @@ pub(in crate::x86_64) fn from_integer( finish_float(code, operand); } -fn guard_float_source(code: &mut Vec, operand: &IntegerConversion) -> usize { +fn guard_float_source(code: &mut Code, operand: &IntegerConversion) -> usize { let shape = operand.integer.shape(); read_numerical_vector(code, shape, operand.float, RESULT_VECTOR); if shape == Shape::Scalar { @@ -297,50 +299,45 @@ fn guard_float_source(code: &mut Vec, operand: &IntegerConversion) -> usize } } -fn read_float_lane(code: &mut Vec, operand: &IntegerConversion, lane: u32) { - code.extend(if operand.format == Format::Single { - MOVD_XMM0_STATE +fn read_float_lane(code: &mut Code, operand: &IntegerConversion, lane: u32) { + let element = + guest(vector_offset(operand.float) + lane * (operand.format.bits() / BITS_PER_BYTE)); + if operand.format == Format::Single { + code.asm().movd_to_xmm(RESULT_VECTOR, element); } else { - MOVQ_XMM0_STATE - }); - code.extend( - (vector_offset(operand.float) + lane * (operand.format.bits() / BITS_PER_BYTE)) - .to_le_bytes(), - ); + Host::MoveQword.emit(code, RESULT_VECTOR, element, TargetCpu::Baseline); + } } fn convert_float_lane( - code: &mut Vec, + code: &mut Code, operand: &IntegerConversion, mode: IntegerRounding, failures: &mut Vec, ) { let integer = operand.integer.format(); - let opcode = if mode == IntegerRounding::TowardZero { - CVTT_FLOAT_TO_INTEGER - } else { - CVT_FLOAT_TO_INTEGER - }; + let truncate = mode == IntegerRounding::TowardZero; if integer.signed { - scalar_conversion( + from_float( code, operand.format, - opcode, + truncate, integer.width == IntegerWidth::Bits64, ); } else if integer.width == IntegerWidth::Bits32 { - scalar_conversion(code, operand.format, opcode, true); - code.extend(MOV_RDX_RAX); - code.extend(SHR_RDX_32); - code.extend(TEST_EDX_EDX); + from_float(code, operand.format, truncate, true); + let mut asm = code.asm(); + asm.mov(Size::Qword, Rdx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rdx, u32::BITS as u8); + asm.test(Size::Dword, Rdx, Rdx); failures.push(branch(code, Condition::NotZero)); } else { float_constant(code, operand.format, UNSIGNED_HIGH_EXPONENT, Shape::Scalar); - code.extend(if operand.format == Format::Single { - UCOMISS_XMM0_XMM1 + if operand.format == Format::Single { + code.asm().ucomiss(RESULT_VECTOR, Rm::Xmm(TEMPORARY_VECTOR)); } else { - UCOMISD_XMM0_XMM1 - }); + code.asm().ucomisd(RESULT_VECTOR, Rm::Xmm(TEMPORARY_VECTOR)); + } let low = branch(code, Condition::Below); // Subtraction is exact throughout [2^63,2^64) (Sterbenz). Anything // beyond that interval raises native invalid and is retried by the core. @@ -351,20 +348,20 @@ fn convert_float_lane( ArithmeticOpcode::Subtract, TEMPORARY_VECTOR, ); - scalar_conversion(code, operand.format, opcode, true); - code.extend(BTS_RAX_63); + from_float(code, operand.format, truncate, true); + code.asm().bit_imm(BitTest::Bts, Size::Qword, Rax, SIGN_BIT); let done = jump(code); let low_start = code.len(); resolve(code, low, low_start); - scalar_conversion(code, operand.format, opcode, true); - code.extend(BT_RAX_63); + from_float(code, operand.format, truncate, true); + code.asm().bit_imm(BitTest::Bt, Size::Qword, Rax, SIGN_BIT); failures.push(branch(code, Condition::Below)); let end = code.len(); resolve(code, done, end); } } -fn finish_integer(code: &mut Vec, operand: &IntegerConversion, packed_result: bool) { +fn finish_integer(code: &mut Code, operand: &IntegerConversion, packed_result: bool) { commit_inexact(code); match operand.integer { IntegerOperand::General { register, .. } => super::super::store(code, register), @@ -379,16 +376,19 @@ fn finish_integer(code: &mut Vec, operand: &IntegerConversion, packed_result } } else { read_vector(code, register, RESULT_VECTOR); - code.extend(if format.width == IntegerWidth::Bits64 { - MOVQ_XMM1_RAX + let wide = format.width == IntegerWidth::Bits64; + lane_to_vector(code, wide, TEMPORARY_VECTOR); + if wide { + Host::MoveScalarDouble } else { - MOVD_XMM1_EAX - }); - code.extend(if format.width == IntegerWidth::Bits64 { - MOVSD_XMM0_XMM1 - } else { - MOVSS_XMM0_XMM1 - }); + Host::MoveScalarSingle + } + .register( + code, + RESULT_VECTOR, + TEMPORARY_VECTOR, + TargetCpu::Baseline, + ); test_control(code, FPCR_NEP); let merge = branch(code, Condition::NotZero); clear_scalar(code, operand.format, RESULT_VECTOR); @@ -401,7 +401,7 @@ fn finish_integer(code: &mut Vec, operand: &IntegerConversion, packed_result } pub(in crate::x86_64) fn to_integer( - code: &mut Vec, + code: &mut Code, operand: &IntegerConversion, mode: IntegerRounding, pc: GuestAddress, @@ -424,11 +424,16 @@ pub(in crate::x86_64) fn to_integer( let mut environment_failures = Vec::new(); if packed_result { scale(code, operand, shape, 1); - code.extend(if mode == IntegerRounding::TowardZero { - CVTT_SINGLE_TO_DWORDS + if mode == IntegerRounding::TowardZero { + code.asm().cvttps2dq(RESULT_VECTOR, Rm::Xmm(RESULT_VECTOR)); } else { - CVT_SINGLE_TO_DWORDS - }); + Host::ConvertPackedSingleToDword.register( + code, + RESULT_VECTOR, + RESULT_VECTOR, + TargetCpu::Baseline, + ); + } } else { if shape != Shape::Scalar { packed(code, Host::Xor, INTEGER_ACCUMULATOR, INTEGER_ACCUMULATOR); @@ -465,14 +470,11 @@ pub(in crate::x86_64) fn to_integer( } pub(in crate::x86_64) fn javascript( - code: &mut Vec, + code: &mut Code, destination: Register, source: u8, pc: GuestAddress, ) { - const XOR_ECX_IMMEDIATE: &[u8] = &[0x83, 0xf1]; - const SHL_ECX_IMMEDIATE: &[u8] = &[0xc1, 0xe1]; - const MOV_STATE_ECX: &[u8] = &[0x89, 0x8f]; const NZCV_ZERO_SHIFT: u32 = 30; const INEXACT_TO_NZCV_SHIFT: u8 = (NZCV_ZERO_SHIFT - INEXACT.trailing_zeros()) as u8; let operand = IntegerConversion { @@ -493,10 +495,12 @@ pub(in crate::x86_64) fn javascript( to_integer(code, &operand, IntegerRounding::TowardZero, pc); // commit_inexact leaves only fresh IXC in ECX. Accumulated FPSR.IXC must // not clear Z for a later exact input, including a discarded WZR result. - code.extend(XOR_ECX_IMMEDIATE); - code.push(INEXACT as u8); - code.extend(SHL_ECX_IMMEDIATE); - code.push(INEXACT_TO_NZCV_SHIFT); - code.extend(MOV_STATE_ECX); - code.extend((core::mem::offset_of!(crate::GuestState, nzcv) as u32).to_le_bytes()); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Xor, Size::Dword, Rcx, INEXACT as i8); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rcx, INEXACT_TO_NZCV_SHIFT); + asm.mov_store( + Size::Dword, + guest(core::mem::offset_of!(crate::GuestState, nzcv) as u32), + Rcx, + ); } diff --git a/crates/stela-compiler/src/x86_64/simd/lut.rs b/crates/stela-compiler/src/x86_64/simd/lut.rs index 19859bb169..2ea1c1be80 100644 --- a/crates/stela-compiler/src/x86_64/simd/lut.rs +++ b/crates/stela-compiler/src/x86_64/simd/lut.rs @@ -1,4 +1,5 @@ //! AdvSIMD LUTI2/LUTI4 on the shared constant-time lookup. +use crate::x86_64::asm::Code; use super::{commit, read_vector}; use crate::TargetCpu; @@ -6,14 +7,13 @@ use crate::aarch64::scalable::{ElementSize, VECTOR_REGISTER_COUNT}; use crate::aarch64::simd::lut::Operand; use crate::x86_64::isa::ShiftOpcode; use crate::x86_64::scalable::lut; -use alloc::vec::Vec; const INDICES_XMM: u8 = 0; const LOW_TABLE_XMM: u8 = 4; const HIGH_TABLE_XMM: u8 = 5; const RESULT_XMM: u8 = 6; -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { read_vector(code, operand.indices, INDICES_XMM); let offset = operand.index_byte_offset(); if offset != 0 { diff --git a/crates/stela-compiler/src/x86_64/simd/memory.rs b/crates/stela-compiler/src/x86_64/simd/memory.rs index 880d658f1a..beea6fa9f2 100644 --- a/crates/stela-compiler/src/x86_64/simd/memory.rs +++ b/crates/stela-compiler/src/x86_64/simd/memory.rs @@ -1,29 +1,20 @@ //! SIMD loads and stores to private RAM, immediate and register offsets. +use super::Host; use super::{commit, read_vector, vector_offset}; +use crate::TargetCpu; use crate::aarch64::simd::memory::Operand; -use alloc::vec::Vec; +use crate::x86_64::asm::{Code, Gpr, Mem, Size}; +use crate::x86_64::simd::encode::guest; const BYTE_BYTES: u8 = 1; const HALFWORD_BYTES: u8 = 2; const DWORD_BYTES: u8 = 4; const QWORD_BYTES: u8 = 8; const VECTOR_BYTES: u8 = 16; -const OPERAND_SIZE_PREFIX: u8 = 0x66; -const REP_PREFIX: u8 = 0xf3; -const TWO_BYTE_OPCODE: u8 = 0x0f; -const MOVD_LOAD_OPCODE: u8 = 0x6e; -const MOVQ_LOAD_OPCODE: u8 = 0x7e; -const MOVDQU_LOAD_OPCODE: u8 = 0x6f; -const DISP8_ADDRESS: u8 = 0x40; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MOVZX_ECX_BYTE_AT_RAX: [u8; 3] = [0x0f, 0xb6, 0x08]; -const MOVZX_ECX_WORD_AT_RAX: [u8; 3] = [0x0f, 0xb7, 0x08]; -const MOVD_XMM0_ECX: [u8; 4] = [0x66, 0x0f, 0x6e, 0xc1]; -const MOV_RCX_STATE_DISP32: [u8; 3] = [0x48, 0x8b, 0x8f]; /// With `held`, XMM0 holds the vector whole ([`transfer`]). pub(super) fn emit_register_offset( - code: &mut Vec, + code: &mut Code, operand: &Operand, checks: super::super::MemoryChecks, held: bool, @@ -58,7 +49,7 @@ pub(super) fn emit_register_offset( /// S/D/Q at [RAX+displacement], using XMM0/XMM1. Loads zero higher bits. /// Pair transfers use only positive second-element displacements 4/8/16. pub(super) fn wide_transfer( - code: &mut Vec, + code: &mut Code, load: bool, bytes: u8, xmm: u8, @@ -75,17 +66,12 @@ pub(super) fn wide_transfer( ); return; } - let (prefix, opcode) = match bytes { - DWORD_BYTES => (OPERAND_SIZE_PREFIX, MOVD_LOAD_OPCODE), - QWORD_BYTES => (REP_PREFIX, MOVQ_LOAD_OPCODE), - VECTOR_BYTES => (REP_PREFIX, MOVDQU_LOAD_OPCODE), + let address = Mem::base(Gpr::Rax, displacement.into()); + match bytes { + DWORD_BYTES => code.asm().movd_to_xmm(xmm, address), + QWORD_BYTES => Host::MoveQword.emit(code, xmm, address, TargetCpu::Baseline), + VECTOR_BYTES => Host::LoadUnaligned.emit(code, xmm, address, TargetCpu::Baseline), _ => unreachable!("decoder validates wide vector memory width"), - }; - let address_mode = if displacement == 0 { 0 } else { DISP8_ADDRESS }; - let modrm = (xmm << MODRM_REGISTER_SHIFT) | address_mode; - code.extend([prefix, TWO_BYTE_OPCODE, opcode, modrm]); - if displacement != 0 { - code.push(displacement); } } @@ -100,7 +86,7 @@ pub(super) fn transfers_xmm0(load: bool, bytes: u8) -> bool { /// commits nothing. With `held`, XMM0 holds the vector whole, and a store /// through XMM0 ([`transfers_xmm0`]) takes it from there. pub(in crate::x86_64) fn transfer( - code: &mut Vec, + code: &mut Code, load: bool, bytes: u8, vector: u8, @@ -111,12 +97,14 @@ pub(in crate::x86_64) fn transfer( match bytes { BYTE_BYTES | HALFWORD_BYTES => { // Never widen a guest access. MOVD clears every upper vector bit. - code.extend(if bytes == BYTE_BYTES { - MOVZX_ECX_BYTE_AT_RAX + let from = if bytes == BYTE_BYTES { + Size::Byte } else { - MOVZX_ECX_WORD_AT_RAX - }); - code.extend(MOVD_XMM0_ECX); + Size::Word + }; + let mut asm = code.asm(); + asm.movzx(Size::Dword, Gpr::Rcx, from, Mem::base(Gpr::Rax, 0)); + asm.movd_to_xmm(0, Gpr::Rcx); } DWORD_BYTES | QWORD_BYTES | VECTOR_BYTES => { wide_transfer(code, true, bytes, 0, 0, aligned) @@ -125,8 +113,8 @@ pub(in crate::x86_64) fn transfer( } commit(code, vector, 0); } else if bytes <= HALFWORD_BYTES { - code.extend(MOV_RCX_STATE_DISP32); - code.extend(vector_offset(vector).to_le_bytes()); + code.asm() + .mov_load(Size::Qword, Gpr::Rcx, guest(vector_offset(vector))); super::super::memory_store::emit( code, bytes, diff --git a/crates/stela-compiler/src/x86_64/simd/memory_checked.rs b/crates/stela-compiler/src/x86_64/simd/memory_checked.rs index 2fc7b6e425..4a43efdb50 100644 --- a/crates/stela-compiler/src/x86_64/simd/memory_checked.rs +++ b/crates/stela-compiler/src/x86_64/simd/memory_checked.rs @@ -1,8 +1,10 @@ //! SIMD loads and stores through the memory service. One request covers the whole //! access, including both pair elements; destinations and base writeback are //! written only after it succeeds. +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Size}; +use crate::x86_64::simd::encode::guest; -use super::{commit, read_vector, vector_offset}; +use super::{Host, commit, read_vector, vector_offset}; use crate::aarch64::{ AddressMode, Operation, Register, literal, non_temporal, register_offset::IndexExtend, simd::Operand, @@ -29,20 +31,10 @@ const WRITEBACK_OFFSET: u8 = STAGING_BYTES + MEMORY_REQUEST_BYTES as u8; const STACK_ALIGNMENT: u8 = VECTOR_BYTES; const SCRATCH_BYTES: u8 = WRITEBACK_OFFSET + STACK_ALIGNMENT; -const SUB_RSP_IMM8: &[u8] = &[0x48, 0x83, 0xec]; -const ADD_RSP_IMM8: &[u8] = &[0x48, 0x83, 0xc4]; -const MOV_RSP_DISP8_RDX: &[u8] = &[0x48, 0x89, 0x54, 0x24]; -const MOV_RAX_RSP_DISP8: &[u8] = &[0x48, 0x8b, 0x44, 0x24]; -const MOV_RCX_STATE_DISP32: &[u8] = &[0x48, 0x8b, 0x8f]; -const MOV_RSP_DISP8_RCX: &[u8] = &[0x48, 0x89, 0x4c, 0x24]; -const MOVDQU_RSP_DISP8_XMM0: &[u8] = &[0xf3, 0x0f, 0x7f, 0x44, 0x24]; -const MOVDQU_XMM0_RSP_DISP8: &[u8] = &[0xf3, 0x0f, 0x6f, 0x44, 0x24]; -const MOVQ_XMM0_RSP_DISP8: &[u8] = &[0xf3, 0x0f, 0x7e, 0x44, 0x24]; -const MOVD_XMM0_RSP_DISP8: &[u8] = &[0x66, 0x0f, 0x6e, 0x44, 0x24]; -const MOVZX_ECX_BYTE_RSP_DISP8: &[u8] = &[0x0f, 0xb6, 0x4c, 0x24]; -const MOVZX_ECX_WORD_RSP_DISP8: &[u8] = &[0x0f, 0xb7, 0x4c, 0x24]; -const MOVD_XMM0_ECX: &[u8] = &[0x66, 0x0f, 0x6e, 0xc1]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; +/// `[rsp + offset]` in the scratch frame, with an 8-bit displacement. +fn scratch(offset: u8) -> Mem { + Mem::base_disp8(Gpr::Rsp, offset as i8) +} #[derive(Clone, Copy)] enum Address { @@ -272,7 +264,7 @@ impl CheckedOperand { transfer_requirements(self.transfer, self.non_temporal, self.profile) } - pub(crate) fn emit_context(&self, code: &mut Vec, pc: u64) { + pub(crate) fn emit_context(&self, code: &mut Code, pc: u64) { emit_transfer(code, self.transfer, pc, self.non_temporal, self.profile); } } @@ -339,7 +331,7 @@ fn transfer_requirements( } } -fn address(code: &mut Vec, transfer: Transfer, profile: CheckedMemoryProfile) { +fn address(code: &mut Code, transfer: Transfer, profile: CheckedMemoryProfile) { match transfer.address { Address::Literal { address } => crate::x86_64::immediate(code, address), Address::Immediate { displacement, mode } => { @@ -351,8 +343,8 @@ fn address(code: &mut Vec, transfer: Transfer, profile: CheckedMemoryProfile profile.address_checks(false), ); if transfer.writeback() { - code.extend(MOV_RSP_DISP8_RDX); - code.push(WRITEBACK_OFFSET); + code.asm() + .mov_store(Size::Qword, scratch(WRITEBACK_OFFSET), Gpr::Rdx); } } Address::Register { @@ -372,39 +364,38 @@ fn address(code: &mut Vec, transfer: Transfer, profile: CheckedMemoryProfile } } -fn stage_sources(code: &mut Vec, transfer: Transfer) { +fn stage_sources(code: &mut Code, transfer: Transfer) { for element in 0..transfer.elements { let vector = transfer.vectors[usize::from(element)]; let displacement = element * transfer.bytes; if transfer.bytes == VECTOR_BYTES { read_vector(code, vector, 0); - code.extend(MOVDQU_RSP_DISP8_XMM0); + Host::StoreUnaligned.emit(code, 0, scratch(displacement), crate::TargetCpu::Baseline); } else { // Reading full64 from independently live State is safe. The service // sees only the exact quantity; S-pair's second stage overwrites the // first stage's unused high32 before the callback can see it. - code.extend(MOV_RCX_STATE_DISP32); - code.extend(vector_offset(vector).to_le_bytes()); - code.extend(MOV_RSP_DISP8_RCX); + let mut asm = code.asm(); + asm.mov_load(Size::Qword, Gpr::Rcx, guest(vector_offset(vector))); + asm.mov_store(Size::Qword, scratch(displacement), Gpr::Rcx); } - code.push(displacement); } } -fn commit_loads(code: &mut Vec, transfer: Transfer) { +fn commit_loads(code: &mut Code, transfer: Transfer) { for element in 0..transfer.elements { - let displacement = element * transfer.bytes; - code.extend(match transfer.bytes { - BYTE_BYTES => MOVZX_ECX_BYTE_RSP_DISP8, - HALFWORD_BYTES => MOVZX_ECX_WORD_RSP_DISP8, - DWORD_BYTES => MOVD_XMM0_RSP_DISP8, - QWORD_BYTES => MOVQ_XMM0_RSP_DISP8, - VECTOR_BYTES => MOVDQU_XMM0_RSP_DISP8, + let staged = scratch(element * transfer.bytes); + let baseline = crate::TargetCpu::Baseline; + match transfer.bytes { + BYTE_BYTES => code.asm().movzx(Size::Dword, Gpr::Rcx, Size::Byte, staged), + HALFWORD_BYTES => code.asm().movzx(Size::Dword, Gpr::Rcx, Size::Word, staged), + DWORD_BYTES => code.asm().movd_to_xmm(0, staged), + QWORD_BYTES => Host::MoveQword.emit(code, 0, staged, baseline), + VECTOR_BYTES => Host::LoadUnaligned.emit(code, 0, staged, baseline), _ => unreachable!("decoder validates fixed SIMD memory width"), - }); - code.push(displacement); + } if transfer.bytes <= HALFWORD_BYTES { - code.extend(MOVD_XMM0_ECX); + code.asm().movd_to_xmm(0, Gpr::Rcx); } commit(code, transfer.vectors[usize::from(element)], 0); } @@ -414,7 +405,7 @@ fn commit_loads(code: &mut Vec, transfer: Transfer) { /// validates CPU/profile requirements; failure returns through its inner-body /// epilogue after releasing scratch. RDI/R15 and full host MXCSR survive calls. #[cfg(test)] -pub(crate) fn emit_context(code: &mut Vec, operand: &Operand, pc: u64) { +pub(crate) fn emit_context(code: &mut Code, operand: &Operand, pc: u64) { emit_transfer( code, Transfer::from_operand(operand).expect("checked fixed SIMD memory operand"), @@ -425,11 +416,7 @@ pub(crate) fn emit_context(code: &mut Vec, operand: &Operand, pc: u64) { } #[cfg(test)] -pub(crate) fn emit_non_temporal_context( - code: &mut Vec, - operand: &non_temporal::Operand, - pc: u64, -) { +pub(crate) fn emit_non_temporal_context(code: &mut Code, operand: &non_temporal::Operand, pc: u64) { emit_transfer( code, Transfer::from_non_temporal(operand), @@ -440,15 +427,15 @@ pub(crate) fn emit_non_temporal_context( } fn emit_transfer( - code: &mut Vec, + code: &mut Code, transfer: Transfer, pc: u64, non_temporal: bool, profile: CheckedMemoryProfile, ) { debug_assert!(transfer.base.is_none_or(|base| offset(base).is_some())); - code.extend(SUB_RSP_IMM8); - code.push(SCRATCH_BYTES); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Gpr::Rsp, SCRATCH_BYTES as i8); service::begin(code); let mut failed = Vec::new(); if profile.sp_requirement() == SpAlignmentRequirement::Enabled @@ -475,20 +462,20 @@ fn emit_transfer( commit_loads(code, transfer); } if transfer.writeback() { - code.extend(MOV_RAX_RSP_DISP8); - code.push(WRITEBACK_OFFSET); + code.asm() + .mov_load(Size::Qword, Gpr::Rax, scratch(WRITEBACK_OFFSET)); store( code, transfer.base.expect("writeback requires a register base"), ); } - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); let cleanup = code.len(); for failure in failed { service::patch_branch(code, failure, cleanup); } - code.extend(ADD_RSP_IMM8); - code.push(SCRATCH_BYTES); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Gpr::Rsp, SCRATCH_BYTES as i8); service::address::return_if_failed(code); } @@ -894,7 +881,7 @@ mod tests { } } let operation = operand(true, 8, false, Register::X(2), 0, AddressMode::Offset); - let mut body = vec![]; + let mut body = Code::new(); emit_context(&mut body, &operation, GUEST_PC); let code = NativeCode::new(&body); for caller in [0x1fa1, 0x3fa5, 0x5f85, 0x7fa1] { @@ -950,7 +937,7 @@ mod tests { for residue in [0, 1, 4, 7, 8, 12, 15] { let operation = operand(load, bytes, pair, Register::X(2), residue, mode); - let mut body = vec![]; + let mut body = Code::new(); emit_context(&mut body, &operation, GUEST_PC); let code = NativeCode::new(&body); for fail_part in [None, Some(1)] { @@ -1081,7 +1068,7 @@ mod tests { CheckedMemoryProfile::SpAlignmentEnabled, ) .unwrap(); - let mut body = vec![]; + let mut body = Code::new(); checked.emit_context(&mut body, GUEST_PC); let code = NativeCode::new(&body); for fail_part in [None, Some(0), Some(1)] { @@ -1147,7 +1134,7 @@ mod tests { #[test] fn original_sp_fault_precedes_offset_and_callback() { let operation = operand(false, 16, true, Register::Sp, -1, AddressMode::PreIndex); - let mut body = vec![]; + let mut body = Code::new(); emit_context(&mut body, &operation, GUEST_PC); let code = NativeCode::new(&body); let mut actual = state(); @@ -1198,7 +1185,7 @@ mod tests { extend, shift, }); - let mut body = vec![]; + let mut body = Code::new(); emit_context(&mut body, &operation, GUEST_PC); let code = NativeCode::new(&body); let mut harness = Harness { @@ -1259,7 +1246,7 @@ mod tests { extend: IndexExtend::Lsl, shift: 0, }); - let mut body = vec![]; + let mut body = Code::new(); emit_context(&mut body, &operation, GUEST_PC); let code = NativeCode::new(&body); let mut actual = state(); @@ -1293,7 +1280,7 @@ mod tests { base: Register::Sp, displacement: 8, }; - let mut body = vec![]; + let mut body = Code::new(); emit_non_temporal_context(&mut body, &operation, GUEST_PC); let code = NativeCode::new(&body); let mut actual = state(); @@ -1376,8 +1363,8 @@ mod tests { disabled.requirements().required_host_caps, host_caps::ATOMIC_LOAD16 ); - let mut enabled_code = Vec::new(); - let mut disabled_code = Vec::new(); + let mut enabled_code = Code::new(); + let mut disabled_code = Code::new(); enabled.emit_context(&mut enabled_code, GUEST_PC); disabled.emit_context(&mut disabled_code, GUEST_PC); assert!(enabled_code.len() > disabled_code.len()); diff --git a/crates/stela-compiler/src/x86_64/simd/minmax.rs b/crates/stela-compiler/src/x86_64/simd/minmax.rs index 2130ca76f4..46b4281845 100644 --- a/crates/stela-compiler/src/x86_64/simd/minmax.rs +++ b/crates/stela-compiler/src/x86_64/simd/minmax.rs @@ -1,11 +1,14 @@ //! FP min/max: normal-or-zero S/D selection and normal H integer ordering. use super::super::isa::ShiftOpcode; +use super::numerical::helper_section; use super::numerical::{ - Condition, INPUT_MINIMUM_EXPONENT, MOVQ_XMM0_XMM0, branch, clear_scalar, exponent_range, jump, - prepare_vector_input_range, read_numerical_vector, resolve, test_control, + Condition, INPUT_MINIMUM_EXPONENT, branch, clear_high_qword, clear_scalar, exponent_range, + jump, prepare_vector_input_range, read_numerical_vector, resolve, test_control, vector_exponent_range, vector_normal_or_zero_range, zero_scalar, }; -use super::{Host, commit, packed, read_vector}; +use super::{Host, commit, packed, packed_imm, read_vector}; +use crate::x86_64::asm::{Code, Gpr, Rm}; +use crate::x86_64::asm::{FloatLanes, FloatOp}; use crate::{ GuestAddress, aarch64::{ @@ -17,7 +20,6 @@ use crate::{ minmax::{BinaryMode, Operand}, }, }, - block::ExitKind, }; use alloc::vec::Vec; @@ -32,31 +34,12 @@ const SELECTION_SCRATCH: u8 = 3; const HALF_SIGN_SHIFT: u8 = u16::BITS as u8 - 1; const SIGN_MASK_TO_MAGNITUDE_SHIFT: u8 = 1; const BITS_PER_BYTE: u32 = u8::BITS; -const REGISTER_DIRECT: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; -const SSE_ESCAPE: u8 = 0x0f; -const SINGLE_SCALAR_PREFIX: u8 = 0xf3; -const DOUBLE_SCALAR_PREFIX: u8 = 0xf2; -const DOUBLE_PACKED_PREFIX: u8 = 0x66; -const SHUFFLE_SINGLE: u8 = 0xc6; -const UNPACK_LOW_SINGLE: u8 = 0x14; -const MOVE_HIGH_TO_LOW_SINGLE: u8 = 0x12; -const UNPACK_LOW_DOUBLE: u8 = 0x14; -const UNPACK_HIGH_DOUBLE: u8 = 0x15; const EVEN_DWORDS: u8 = 0x88; const ODD_DWORDS: u8 = 0xdd; const SWAP_ADJACENT_WORDS: u8 = 0xb1; const EVEN_WORDS: u8 = 0x88; const TWO_HALF_BYTES: u8 = 2 * (u16::BITS / BITS_PER_BYTE) as u8; const FOUR_HALF_BYTES: u8 = 4 * (u16::BITS / BITS_PER_BYTE) as u8; -const MOVD_EAX_XMM0: &[u8] = &[0x66, 0x0f, 0x7e, 0xc0]; -const PINSRW_XMM7_EAX_LOW: &[u8] = &[0x66, 0x0f, 0xc4, 0xf8, 0]; - -#[repr(u8)] -enum SelectionOpcode { - Minimum = 0x5d, - Maximum = 0x5f, -} fn is_minimum(operation: MinMaxOperation) -> bool { matches!( @@ -66,7 +49,7 @@ fn is_minimum(operation: MinMaxOperation) -> bool { } fn raw_selection( - code: &mut Vec, + code: &mut Code, operation: MinMaxOperation, format: Format, shape: Shape, @@ -86,30 +69,26 @@ fn raw_selection( ); return; } - match (format, shape) { - (Format::Single, Shape::Scalar) => code.push(SINGLE_SCALAR_PREFIX), - (Format::Double, Shape::Scalar) => code.push(DOUBLE_SCALAR_PREFIX), - (Format::Double, _) => code.push(DOUBLE_PACKED_PREFIX), - (Format::Single, _) => (), + let lanes = match (format, shape) { + (Format::Single, Shape::Scalar) => FloatLanes::ScalarSingle, + (Format::Double, Shape::Scalar) => FloatLanes::ScalarDouble, + (Format::Double, _) => FloatLanes::PackedDouble, + (Format::Single, _) => FloatLanes::PackedSingle, (Format::Half, _) => unreachable!("half selection is integer-only"), - } - let opcode = if is_minimum(operation) { - SelectionOpcode::Minimum - } else { - SelectionOpcode::Maximum }; - code.extend([ - SSE_ESCAPE, - opcode as u8, - REGISTER_DIRECT | (destination << REGISTER_SHIFT) | right, - ]); + let op = if is_minimum(operation) { + FloatOp::Min + } else { + FloatOp::Max + }; + code.asm().float(op, lanes, destination, Rm::Xmm(right)); } /// Legacy SSE selects operand2 on a zero tie. Symmetric selection followed by /// sign AND (maximum) or OR (minimum) gives Arm's standard zero sign. Plain /// AH=1 retains operand2 instead. No inactive scalar lane undergoes FP work. fn selection( - code: &mut Vec, + code: &mut Code, operation: MinMaxOperation, format: Format, shape: Shape, @@ -176,25 +155,19 @@ fn selection( /// Normal half-precision values map to a signed-word order key, and the same /// transform restores the bit pattern after integer min/max. -fn half_order(code: &mut Vec, vector: u8) { +fn half_order(code: &mut Code, vector: u8) { packed(code, Host::MoveAligned, SIGN_VECTOR, vector); ShiftOpcode::ArithmeticWord.emit(code, SIGN_VECTOR, HALF_SIGN_SHIFT); ShiftOpcode::RightWord.emit(code, SIGN_VECTOR, SIGN_MASK_TO_MAGNITUDE_SHIFT); packed(code, Host::Xor, vector, SIGN_VECTOR); } -fn exception_guard(code: &mut Vec, helper: &mut Vec) { +fn exception_guard(code: &mut Code, helper: &mut Vec) { test_control(code, FPCR_EXCEPTION_ENABLE_MASK); helper.push(branch(code, Condition::NotZero)); } -fn input_guard( - code: &mut Vec, - format: Format, - shape: Shape, - source: u8, - helper: &mut Vec, -) { +fn input_guard(code: &mut Code, format: Format, shape: Shape, source: u8, helper: &mut Vec) { if shape == Shape::Scalar { let zero = if format != Format::Half { zero_scalar(code, format, source); @@ -218,49 +191,25 @@ fn input_guard( } } -fn helper_section(code: &mut Vec, helper: &[usize], pc: GuestAddress) { - // Scalar zero and normal success have different flags. Every failed guard - // has its own helper patch, so success must not depend on stale flags. - let success = jump(code); - let helper_start = code.len(); - super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); - let success_start = code.len(); - for &patch in helper { - resolve(code, patch, helper_start); +fn shuffle(code: &mut Code, opcode: Host, destination: u8, source: u8, control: u8) { + packed_imm(code, opcode, destination, source, control); +} + +fn shuffle_single(code: &mut Code, destination: u8, right: u8, control: u8) { + code.asm().shufps(destination, Rm::Xmm(right), control); +} + +fn unpack_double(code: &mut Code, destination: u8, right: u8, high: bool) { + if high { + code.asm().unpckhpd(destination, Rm::Xmm(right)); + } else { + code.asm().unpcklpd(destination, Rm::Xmm(right)); } - resolve(code, success, success_start); -} - -fn shuffle(code: &mut Vec, opcode: Host, destination: u8, source: u8, control: u8) { - packed(code, opcode, destination, source); - code.push(control); -} - -fn shuffle_single(code: &mut Vec, destination: u8, right: u8, control: u8) { - code.extend([ - SSE_ESCAPE, - SHUFFLE_SINGLE, - REGISTER_DIRECT | (destination << REGISTER_SHIFT) | right, - control, - ]); -} - -fn unpack_double(code: &mut Vec, destination: u8, right: u8, high: bool) { - code.extend([ - DOUBLE_PACKED_PREFIX, - SSE_ESCAPE, - if high { - UNPACK_HIGH_DOUBLE - } else { - UNPACK_LOW_DOUBLE - }, - REGISTER_DIRECT | (destination << REGISTER_SHIFT) | right, - ]); } /// Pairwise results fill both words of each pair. Only integer operations run, /// so inactive or duplicated lanes have no effect. -fn half_pairs(code: &mut Vec, operation: MinMaxOperation, source: u8) { +fn half_pairs(code: &mut Code, operation: MinMaxOperation, source: u8) { shuffle( code, Host::ShuffleLowWord, @@ -285,7 +234,7 @@ fn half_pairs(code: &mut Vec, operation: MinMaxOperation, source: u8) { ); } -fn compact_half_pairs(code: &mut Vec, shape: Shape, source: u8) { +fn compact_half_pairs(code: &mut Code, shape: Shape, source: u8) { shuffle(code, Host::ShuffleLowWord, source, source, EVEN_WORDS); if shape == Shape::Vector128 { shuffle(code, Host::ShuffleHighWord, source, source, EVEN_WORDS); @@ -293,7 +242,7 @@ fn compact_half_pairs(code: &mut Vec, shape: Shape, source: u8) { } } -fn vector_pairs(code: &mut Vec, operation: MinMaxOperation, format: Format, shape: Shape) { +fn vector_pairs(code: &mut Code, operation: MinMaxOperation, format: Format, shape: Shape) { match format { Format::Half => { for source in [RESULT_VECTOR, RIGHT_VECTOR] { @@ -314,16 +263,9 @@ fn vector_pairs(code: &mut Vec, operation: MinMaxOperation, format: Format, Format::Single if shape == Shape::Vector64 => { // Q0 loads zero both upper qwords. Gather [n0,m0,n1,m1], then // compare against [n1,m1,0,0]; only the low two results survive. - code.extend([ - SSE_ESCAPE, - UNPACK_LOW_SINGLE, - REGISTER_DIRECT | (RESULT_VECTOR << REGISTER_SHIFT) | RIGHT_VECTOR, - ]); - code.extend([ - SSE_ESCAPE, - MOVE_HIGH_TO_LOW_SINGLE, - REGISTER_DIRECT | (RIGHT_VECTOR << REGISTER_SHIFT) | RESULT_VECTOR, - ]); + let mut asm = code.asm(); + asm.unpcklps(RESULT_VECTOR, Rm::Xmm(RIGHT_VECTOR)); + asm.movhlps(RIGHT_VECTOR, Rm::Xmm(RESULT_VECTOR)); selection(code, operation, format, shape, RESULT_VECTOR, RIGHT_VECTOR); } Format::Single => { @@ -341,7 +283,7 @@ fn vector_pairs(code: &mut Vec, operation: MinMaxOperation, format: Format, } } -fn finish_binary(code: &mut Vec, format: Format, shape: Shape, destination: u8) { +fn finish_binary(code: &mut Code, format: Format, shape: Shape, destination: u8) { if shape == Shape::Scalar { test_control(code, FPCR_NEP); let merge = branch(code, Condition::NotZero); @@ -353,17 +295,18 @@ fn finish_binary(code: &mut Vec, format: Format, shape: Shape, destination: let merge_target = code.len(); resolve(code, merge, merge_target); if format == Format::Half { - code.extend(MOVD_EAX_XMM0); - code.extend(PINSRW_XMM7_EAX_LOW); + let mut asm = code.asm(); + asm.movd_from_xmm(Gpr::Rax, RESULT_VECTOR); + asm.pinsrw(ORIGINAL_LEFT_VECTOR, Gpr::Rax, 0); packed(code, Host::MoveAligned, RESULT_VECTOR, ORIGINAL_LEFT_VECTOR); } } else if shape == Shape::Vector64 { - code.extend(MOVQ_XMM0_XMM0); + clear_high_qword(code, 0); } commit(code, destination, RESULT_VECTOR); } -fn binary(code: &mut Vec, operand: &Operand, pc: GuestAddress) { +fn binary(code: &mut Code, operand: &Operand, pc: GuestAddress) { let Operand::Binary { operation, format, @@ -405,7 +348,7 @@ fn binary(code: &mut Vec, operand: &Operand, pc: GuestAddress) { } fn pairwise_scalar( - code: &mut Vec, + code: &mut Code, operation: MinMaxOperation, format: Format, destination: u8, @@ -440,7 +383,7 @@ fn pairwise_scalar( } fn reduction( - code: &mut Vec, + code: &mut Code, operation: MinMaxOperation, format: Format, shape: Shape, @@ -503,7 +446,7 @@ fn reduction( commit(code, destination, RESULT_VECTOR); } -pub(in crate::x86_64) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress) { +pub(in crate::x86_64) fn emit(code: &mut Code, operand: &Operand, pc: GuestAddress) { match *operand { Operand::Binary { .. } => binary(code, operand, pc), Operand::PairwiseScalar { diff --git a/crates/stela-compiler/src/x86_64/simd/numerical.rs b/crates/stela-compiler/src/x86_64/simd/numerical.rs index 74f8970e8d..3e6e354c32 100644 --- a/crates/stela-compiler/src/x86_64/simd/numerical.rs +++ b/crates/stela-compiler/src/x86_64/simd/numerical.rs @@ -1,19 +1,24 @@ //! Shared FP emission: integer lane classification and a private MXCSR. +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Map, Mem, Pp, Rm, ShiftOp, Size, Vex}; +use crate::x86_64::asm::{FloatLanes, FloatOp}; use alloc::vec; use alloc::vec::Vec; mod control; use super::super::isa::ShiftOpcode; -use super::{Host, packed, read_vector, vector_offset}; +use super::{Host, packed, packed_imm, read_vector, vector_offset}; use crate::{ GuestState, aarch64::{floating::Format, simd::arithmetic::Shape}, }; +use Gpr::{Rax, Rcx, Rdi, Rsp}; pub(in crate::x86_64) use control::rounding_control; const MXCSR_EXCEPTION_MASKS: u32 = 0x3f << 7; pub(super) const MXCSR_INEXACT: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; +/// Every MXCSR status flag. +const MXCSR_STATUS_FLAGS: u8 = 0x3f; const MXCSR_POSITIVE_ROUNDING: u32 = 1 << 14; const MXCSR_NEGATIVE_ROUNDING: u32 = 1 << 13; const FPCR_POSITIVE_TO_MXCSR_SHIFT: u8 = 8; @@ -21,12 +26,6 @@ const FPCR_NEGATIVE_TO_MXCSR_SHIFT: u8 = 10; const MXCSR_TO_FPSR_INEXACT_SHIFT: u8 = 1; pub(super) const INPUT_MINIMUM_EXPONENT: u8 = 1; pub(super) const RESULT_MINIMUM_EXPONENT: u8 = 2; -/// Callers must prove usable AVX through their independent FMA/F16C capability. -pub(in crate::x86_64) const VZEROUPPER: &[u8] = &[0xc5, 0xf8, 0x77]; -const SCALAR_SINGLE_PREFIX: u8 = 0xf3; -const SCALAR_DOUBLE_PREFIX: u8 = 0xf2; -const PACKED_DOUBLE_PREFIX: u8 = 0x66; -const SSE_ESCAPE: u8 = 0x0f; pub(super) const LEFT_VECTOR: u8 = 0; pub(super) const RIGHT_VECTOR: u8 = 1; pub(super) const EXPONENT_VECTOR: u8 = 2; @@ -42,56 +41,45 @@ const HALF_LOW_BYTE_MASK: u32 = 0xff; const HALF_VECTOR_BYTE_MASK: u32 = 0xffff; const SIGN_BITS: u8 = 1; pub(super) const SINGLE_EXPONENT_BIAS_BITS: u8 = 7; -pub(super) const MOVLHPS_XMM1_XMM2: &[u8] = &[0x0f, 0x16, 0xca]; -const TEST_STATE_IMM32: &[u8] = &[0xf7, 0x87]; -const MOV_ECX_STATE: &[u8] = &[0x8b, 0x8f]; -const OR_STATE_ECX: &[u8] = &[0x09, 0x8f]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const SHR_EAX_IMM8: &[u8] = &[0xc1, 0xe8]; -const SHR_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe8]; -const SHR_ECX_IMM8: &[u8] = &[0xc1, 0xe9]; -const AND_EAX_IMM32: u8 = 0x25; -const OR_EAX_IMM32: u8 = 0x0d; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const TEST_ECX_IMM32: &[u8] = &[0xf7, 0xc1]; -const OR_EAX_ECX: &[u8] = &[0x09, 0xc8]; -const SUB_EAX_IMM8: &[u8] = &[0x83, 0xe8]; -const CMP_EAX_IMM32: u8 = 0x3d; -const CMP_EAX_IMM8: &[u8] = &[0x83, 0xf8]; -const AND_EAX_IMM8: &[u8] = &[0x83, 0xe0]; -const MOVD_EAX_XMM0: &[u8] = &[0x66, 0x0f, 0x7e, 0xc0]; -const MOVD_EAX_XMM6: &[u8] = &[0x66, 0x0f, 0x7e, 0xf0]; -const MOVQ_RAX_XMM6: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xf0]; -const MOVD_EAX_XMM1: &[u8] = &[0x66, 0x0f, 0x7e, 0xc8]; -const MOVQ_RAX_XMM0: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xc0]; -const MOVQ_RAX_XMM1: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xc8]; -pub(super) const MOVQ_XMM0_XMM0: &[u8] = &[0xf3, 0x0f, 0x7e, 0xc0]; pub(super) const ENVIRONMENT_STACK_BYTES: u8 = 16; +/// The environment frame: the saved MXCSR, then the installed control, +/// then the captured status, then a product's status. +const MXCSR_SAVED_OFFSET: u8 = 0; const MXCSR_CONTROL_OFFSET: u8 = 4; const MXCSR_STATUS_OFFSET: u8 = 8; -const SUB_RSP_ENVIRONMENT: &[u8] = &[0x48, 0x83, 0xec, ENVIRONMENT_STACK_BYTES]; -const ADD_RSP_ENVIRONMENT: &[u8] = &[0x48, 0x83, 0xc4, ENVIRONMENT_STACK_BYTES]; -const STMXCSR_SAVED: &[u8] = &[0x0f, 0xae, 0x1c, 0x24]; -const MOV_CONTROL_EAX: &[u8] = &[0x89, 0x44, 0x24, MXCSR_CONTROL_OFFSET]; -const LDMXCSR_CONTROL: &[u8] = &[0x0f, 0xae, 0x54, 0x24, MXCSR_CONTROL_OFFSET]; -const STMXCSR_STATUS: &[u8] = &[0x0f, 0xae, 0x5c, 0x24, MXCSR_STATUS_OFFSET]; -const LDMXCSR_SAVED: &[u8] = &[0x0f, 0xae, 0x14, 0x24]; -const MOV_ECX_STATUS: &[u8] = &[0x8b, 0x4c, 0x24, MXCSR_STATUS_OFFSET]; -const MOV_EAX_IMM32: u8 = 0xb8; - -const FMA_VEX3: u8 = 0xc4; -const FMA_MAP_0F38: u8 = 0xe2; -const FMA_128_ADDEND_XMM6: u8 = 0x49; -const FMA_DOUBLE_W: u8 = 0x80; +const MXCSR_PRODUCT_OFFSET: u8 = 12; +/// The FMA addend of the shared numerical allocation. +const ADDEND_VECTOR: u8 = 6; const FMA_SCALAR_OPCODE_BIT: u8 = 1; -#[repr(u8)] pub(in crate::x86_64) enum Condition { - Below = 0x82, - AboveOrEqual = 0x83, - Zero = 0x84, - NotZero = 0x85, - Above = 0x87, + Below, + AboveOrEqual, + Zero, + NotZero, + Above, +} + +impl Condition { + const fn cond(self) -> Cond { + match self { + Self::Below => Cond::B, + Self::AboveOrEqual => Cond::Ae, + Self::Zero => Cond::E, + Self::NotZero => Cond::Ne, + Self::Above => Cond::A, + } + } +} + +/// `[rdi + offset]` in GuestState, with a 32-bit displacement. +pub(in crate::x86_64) fn state(offset: usize) -> Mem { + Mem::base_disp32(Rdi, offset as i32) +} + +/// `[rsp + offset]` in the environment frame. +fn frame(offset: u8) -> Mem { + Mem::base(Rsp, offset.into()) } #[repr(u8)] @@ -102,6 +90,28 @@ pub(in crate::x86_64) enum ArithmeticOpcode { Divide = 0x5e, } +impl ArithmeticOpcode { + const fn float_op(self) -> FloatOp { + match self { + Self::Add => FloatOp::Add, + Self::Subtract => FloatOp::Sub, + Self::Multiply => FloatOp::Mul, + Self::Divide => FloatOp::Div, + } + } +} + +/// The SSE lane form of a `format` operation over `shape`: scalar Half +/// operates on its exact Double widening. +pub(in crate::x86_64) const fn float_lanes(format: Format, shape: Shape) -> FloatLanes { + match (shape, format) { + (Shape::Scalar, Format::Single) => FloatLanes::ScalarSingle, + (Shape::Scalar, _) => FloatLanes::ScalarDouble, + (_, Format::Double) => FloatLanes::PackedDouble, + _ => FloatLanes::PackedSingle, + } +} + #[repr(u8)] pub(in crate::x86_64) enum FusedOpcode { MultiplyAdd = 0x98, @@ -110,6 +120,18 @@ pub(in crate::x86_64) enum FusedOpcode { NegativeMultiplySubtract = 0x9e, } +impl From for FusedOpcode { + fn from(operation: crate::aarch64::floating::fused::FusedOperation) -> Self { + use crate::aarch64::floating::fused::FusedOperation; + match operation { + FusedOperation::Add => Self::MultiplyAdd, + FusedOperation::Subtract => Self::NegativeMultiplyAdd, + FusedOperation::NegatedAdd => Self::NegativeMultiplySubtract, + FusedOperation::NegatedSubtract => Self::MultiplySubtract, + } + } +} + #[derive(Clone, Copy)] pub(super) enum Rounding { Fpcr, @@ -130,42 +152,39 @@ pub(in crate::x86_64) use quantization::{ /// Checked FMA132 with the shared numerical allocation: XMM0 is the product /// destination, XMM1 the multiplier and XMM6 the addend. All are caller-volatile. pub(in crate::x86_64) fn emit_fma( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, opcode: FusedOpcode, target: crate::TargetCpu, ) { - const REGISTER_DIRECT: u8 = 0xc0; assert!( target.supports(crate::TargetCpu::Fma), "FMA3 requires usable AVX/FMA state" ); // 132 order: XMM0 = XMM0 * XMM1 + XMM6, with the selected sign variant. - code.extend([ - FMA_VEX3, - FMA_MAP_0F38, - FMA_128_ADDEND_XMM6 - | if format == Format::Double { - FMA_DOUBLE_W - } else { - 0 - }, + code.asm().vex( + Vex { + map: Map::M0f38, + pp: Pp::P66, + w: format == Format::Double, + l: false, + }, opcode as u8 | if shape == Shape::Scalar { FMA_SCALAR_OPCODE_BIT } else { 0 }, - REGISTER_DIRECT | RIGHT_VECTOR, - ]); + LEFT_VECTOR, + ADDEND_VECTOR, + Rm::Xmm(RIGHT_VECTOR), + ); } -pub(in crate::x86_64) fn branch(code: &mut Vec, condition: Condition) -> usize { - code.extend([SSE_ESCAPE, condition as u8]); - let patch = code.len(); - code.extend(0i32.to_le_bytes()); - patch +/// A `jcc rel32` to resolve later, returning its displacement field. +pub(in crate::x86_64) fn branch(code: &mut Code, condition: Condition) -> usize { + code.asm().jcc(condition.cond()).offset() } pub(in crate::x86_64) fn resolve(code: &mut [u8], patch: usize, target: usize) { let target = i64::try_from(target).expect("numerical branch target fits i64"); @@ -174,7 +193,7 @@ pub(in crate::x86_64) fn resolve(code: &mut [u8], patch: usize, target: usize) { code[patch..patch + size_of::()].copy_from_slice(&distance.to_le_bytes()); } /// Refuse retained numerical enables unless AH suppresses exceptions. -pub(super) fn guard_ah0_exceptions(code: &mut Vec, helper: &mut Vec) { +pub(super) fn guard_ah0_exceptions(code: &mut Code, helper: &mut Vec) { use crate::aarch64::floating::{FPCR_AH, FPCR_EXCEPTION_ENABLE_MASK}; test_control(code, FPCR_AH); let suppressed = branch(code, Condition::NotZero); @@ -186,15 +205,12 @@ pub(super) fn guard_ah0_exceptions(code: &mut Vec, helper: &mut Vec) /// Select guest RC for AH0 and mandatory nearest-even for AH1. /// Inputs are already normal, so the forced AH1 flush controls are immaterial. -pub(super) fn environment_alternative_nearest(code: &mut Vec) { +pub(super) fn environment_alternative_nearest(code: &mut Code) { use crate::aarch64::floating::FPCR_AH; test_control(code, FPCR_AH); let nearest = branch(code, Condition::NotZero); environment(code); - const JMP_REL32: u8 = 0xe9; - code.push(JMP_REL32); - let done = code.len(); - code.extend(0i32.to_le_bytes()); + let done = jump(code); let nearest_start = code.len(); resolve(code, nearest, nearest_start); environment_round(code, Rounding::NearestEven); @@ -204,7 +220,7 @@ pub(super) fn environment_alternative_nearest(code: &mut Vec) { /// Commit the accepted host inexact status, only when FPCR.AH allows fresh /// status. -pub(super) fn commit_ah0_inexact(code: &mut Vec) { +pub(super) fn commit_ah0_inexact(code: &mut Code) { use crate::aarch64::floating::FPCR_AH; test_control(code, FPCR_AH); let suppressed = branch(code, Condition::NotZero); @@ -233,8 +249,6 @@ pub(super) const FPCR_STICKY_MASK: u32 = { }; /// FPSR.IXC. const FPSR_INEXACT: u8 = 1 << 4; -const TEST_STATE_BYTE_IMM8: &[u8] = &[0xf6, 0x87]; -const JMP_REL32: u8 = 0xe9; /// Enter the sticky-inexact path, or take one of the returned branches to /// the full path. With FPCR at its defaults ([`FPCR_STICKY_MASK`]) and @@ -253,15 +267,17 @@ const JMP_REL32: u8 = 0xe9; /// /// Unless `entry.checked`, the caller knows the conditions hold /// ([`Entry`]). There are then no branches. -pub(super) fn sticky_inexact(code: &mut Vec, entry: Entry) -> Vec { +pub(super) fn sticky_inexact(code: &mut Code, entry: Entry) -> Vec { if !entry.checked { return vec![]; } test_control(code, FPCR_STICKY_MASK); let control = branch(code, Condition::NotZero); - code.extend(TEST_STATE_BYTE_IMM8); - code.extend((core::mem::offset_of!(GuestState, fpsr) as u32).to_le_bytes()); - code.push(FPSR_INEXACT); + code.asm().test_imm( + Size::Byte, + state(core::mem::offset_of!(GuestState, fpsr)), + FPSR_INEXACT.into(), + ); let status = branch(code, Condition::Zero); vec![control, status] } @@ -305,12 +321,44 @@ pub(in crate::x86_64) struct ColdSplit { pub(in crate::x86_64) result: u8, } +/// Jump over a cold section that exits to software completion at `pc`, and +/// point each `helper` branch at that section. Every branch enters it with +/// the caller's MXCSR and stack restored; success continues after it. +pub(in crate::x86_64) fn helper_section( + code: &mut Code, + helper: &[usize], + pc: crate::GuestAddress, +) { + let completed = jump(code); + let helper_start = code.len(); + super::super::block::direct_exit(code, pc, crate::block::ExitKind::FloatingPoint); + let success = code.len(); + for &patch in helper { + resolve(code, patch, helper_start); + } + resolve(code, completed, success); +} + +/// Packed single-precision `opcode` on whole XMM registers. +pub(in crate::x86_64) fn single_vector_arithmetic( + code: &mut Code, + opcode: ArithmeticOpcode, + destination: u8, + source: u8, +) { + emit_opcode_to( + code, + crate::aarch64::floating::Format::Single, + crate::aarch64::simd::arithmetic::Shape::Vector128, + opcode, + destination, + source, + ); +} + /// An unconditional `jmp rel32` to resolve later. -pub(super) fn jump(code: &mut Vec) -> usize { - code.push(JMP_REL32); - let patch = code.len(); - code.extend(0i32.to_le_bytes()); - patch +pub(in crate::x86_64) fn jump(code: &mut Code) -> usize { + code.asm().jmp().offset() } /// Classify the active result lanes in `source` for the sticky-inexact @@ -320,7 +368,7 @@ pub(super) fn jump(code: &mut Vec) -> usize { /// so does every lane below twice the minimum normal, which may be tiny /// before rounding, zero included. pub(super) fn sticky_result_check( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, source: u8, @@ -352,28 +400,45 @@ pub(super) fn sticky_result_check( /// [`exponent_range`] of a Single in `source` (XMM0 or XMM1) with one /// instruction fewer: doubling its bits drops the sign and puts the /// exponent field at the top, so the range bounds shift with it. -fn single_exponent_range(code: &mut Vec, source: u8, minimum: u8) { - const SUB_EAX_IMM32: u8 = 0x2d; +fn single_exponent_range(code: &mut Code, source: u8, minimum: u8) { const FIELD_SHIFT: u32 = u32::BITS - 8; let maximum = (Format::Single.exponent_mask() >> Format::Single.fraction_bits()) as u32; - code.extend(match source { - 0 => MOVD_EAX_XMM0, - 1 => MOVD_EAX_XMM1, - _ => unreachable!("allocated numerical source register"), - }); - code.extend(ADD_EAX_EAX); + assert!( + matches!(source, 0 | 1), + "allocated numerical source register" + ); + let mut asm = code.asm(); + asm.movd_from_xmm(Rax, source); + asm.alu(Alu::Add, Size::Dword, Rax, Rax); if minimum != 0 { - code.push(SUB_EAX_IMM32); - code.extend((u32::from(minimum) << FIELD_SHIFT).to_le_bytes()); + asm.alu_accumulator_imm32( + Alu::Sub, + Size::Dword, + (u32::from(minimum) << FIELD_SHIFT) as i32, + ); } - code.push(CMP_EAX_IMM32); - code.extend(((maximum - u32::from(minimum)) << FIELD_SHIFT).to_le_bytes()); + asm.alu_accumulator_imm32( + Alu::Cmp, + Size::Dword, + ((maximum - u32::from(minimum)) << FIELD_SHIFT) as i32, + ); +} + +/// `op eax, imm8`. +fn eax_imm8(code: &mut Code, op: Alu, value: u8) { + code.asm().alu_imm8(op, Size::Dword, Rax, value as i8); +} + +/// `op eax, imm32`, the accumulator short form. +fn eax_imm32(code: &mut Code, op: Alu, value: u32) { + code.asm() + .alu_accumulator_imm32(op, Size::Dword, value as i32); } /// Leave ZF set when every active S/D lane of `source` has an exponent /// below all ones, with the maximum from [`prepare_vector_input_range`]. /// The high dwords of Double lanes hold zero, which is below it too. -fn vector_below_maximum(code: &mut Vec, format: Format, shape: Shape, source: u8) { +fn vector_below_maximum(code: &mut Code, format: Format, shape: Shape, source: u8) { vector_exponent_fields(code, format, source, false); packed( code, @@ -385,15 +450,13 @@ fn vector_below_maximum(code: &mut Vec, format: Format, shape: Shape, source Host::DwordSignMask.register(code, 0, VALIDITY_VECTOR, crate::TargetCpu::Baseline); let mask = match (shape, format) { (Shape::Vector64, Format::Single) => { - code.extend(AND_EAX_IMM8); - code.push(SINGLE_LOW_VECTOR_MASK); + eax_imm8(code, Alu::And, SINGLE_LOW_VECTOR_MASK); SINGLE_LOW_VECTOR_MASK } (Shape::Vector128, Format::Single | Format::Double) => SINGLE_VECTOR_MASK, _ => unreachable!("allocated S/D vector shape"), }; - code.extend(CMP_EAX_IMM8); - code.push(mask); + eax_imm8(code, Alu::Cmp, mask); } /// The operands of a product whose result the sticky classification @@ -421,12 +484,6 @@ const SWAP_DWORD_PAIRS: u8 = 0xb1; /// MOVMSKPS lanes that are active: the low dword of each D lane holds its /// classification. const DOUBLE_LOW_DWORDS: u8 = 0b0101; -const MOV_RAX_STATE: &[u8] = &[0x48, 0x8b, 0x87]; -const MOV_EAX_STATE: &[u8] = &[0x8b, 0x87]; -const ADD_RAX_RAX: &[u8] = &[0x48, 0x01, 0xc0]; -const ADD_EAX_EAX: &[u8] = &[0x01, 0xc0]; -const MOVQ_RAX_XMM_PREFIX: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const MOVD_EAX_XMM_PREFIX: &[u8] = &[0x66, 0x0f, 0x7e]; /// Out of line after a sticky-inexact product (`sticky_inexact`): return /// to `resume` when every active lane the classification rejected is a @@ -436,7 +493,7 @@ const MOVD_EAX_XMM_PREFIX: &[u8] = &[0x66, 0x0f, 0x7e]; /// branches to `resume`. Other zeros and tiny /// results may have underflowed, and need the helper. pub(super) fn zero_product_check( - code: &mut Vec, + code: &mut Code, product: &ZeroProduct, resume: usize, resumes: &mut Vec, @@ -458,17 +515,10 @@ pub(super) fn zero_product_check( let right_zero = branch(code, Condition::Zero); resolve(code, right_zero, resume); resumes.push(right_zero); - code.extend(if format == Format::Double { - MOV_RAX_STATE - } else { - MOV_EAX_STATE - }); - code.extend(vector_offset(left).to_le_bytes()); - code.extend(if format == Format::Double { - ADD_RAX_RAX - } else { - ADD_EAX_EAX - }); + let size = Size::of(format == Format::Double); + let mut asm = code.asm(); + asm.mov_load(size, Rax, state(vector_offset(left) as usize)); + asm.alu(Alu::Add, size, Rax, Rax); let left_zero = branch(code, Condition::Zero); resolve(code, left_zero, resume); resumes.push(left_zero); @@ -494,10 +544,8 @@ pub(super) fn zero_product_check( (Shape::Vector128, Format::Double) => DOUBLE_LOW_DWORDS, _ => unreachable!("allocated S/D vector shape"), }; - code.extend(AND_EAX_IMM8); - code.push(mask); - code.extend(CMP_EAX_IMM8); - code.push(mask); + eax_imm8(code, Alu::And, mask); + eax_imm8(code, Alu::Cmp, mask); let passed = branch(code, Condition::Zero); resolve(code, passed, resume); resumes.push(passed); @@ -505,24 +553,21 @@ pub(super) fn zero_product_check( } /// Leave ZF set when the low S/D lane of `xmm` is a zero of either sign. -pub(super) fn zero_scalar(code: &mut Vec, format: Format, xmm: u8) { - const REGISTER_DIRECT: u8 = 0xc0; - const MODRM_REGISTER_SHIFT: u8 = 3; +pub(super) fn zero_scalar(code: &mut Code, format: Format, xmm: u8) { + let mut asm = code.asm(); if format == Format::Double { - code.extend(MOVQ_RAX_XMM_PREFIX); - code.push(REGISTER_DIRECT | xmm << MODRM_REGISTER_SHIFT); - code.extend(ADD_RAX_RAX); + asm.movq_from_xmm(Rax, xmm); } else { - code.extend(MOVD_EAX_XMM_PREFIX); - code.push(REGISTER_DIRECT | xmm << MODRM_REGISTER_SHIFT); - code.extend(ADD_EAX_EAX); + asm.movd_from_xmm(Rax, xmm); } + let size = Size::of(format == Format::Double); + asm.alu(Alu::Add, size, Rax, Rax); } /// Return the failure branch for a finite S/D exponent range or an actual /// signed zero. Preserve ECX, which may hold the pending fresh host status. pub(super) fn scalar_range_or_zero( - code: &mut Vec, + code: &mut Code, format: Format, source: u8, minimum: u8, @@ -533,19 +578,18 @@ pub(super) fn scalar_range_or_zero( let maximum = (format.exponent_mask() >> format.fraction_bits()) as u32; if format == Format::Single { // Doubling discarded the sign and moved the exponent above the fraction. - const SUB_EAX_IMM32: u8 = 0x2d; let shift = format.fraction_bits() + u32::from(SIGN_BITS); - code.push(SUB_EAX_IMM32); - code.extend((u32::from(minimum) << shift).to_le_bytes()); - code.push(CMP_EAX_IMM32); - code.extend(((maximum - u32::from(minimum)) << shift).to_le_bytes()); + eax_imm32(code, Alu::Sub, u32::from(minimum) << shift); + eax_imm32(code, Alu::Cmp, (maximum - u32::from(minimum)) << shift); } else { - code.extend(SHR_RAX_IMM8); - code.push((format.fraction_bits() + u32::from(SIGN_BITS)) as u8); - code.extend(SUB_EAX_IMM8); - code.push(minimum); - code.push(CMP_EAX_IMM32); - code.extend((maximum - u32::from(minimum)).to_le_bytes()); + code.asm().shift_imm( + ShiftOp::Shr, + Size::Qword, + Rax, + (format.fraction_bits() + u32::from(SIGN_BITS)) as u8, + ); + eax_imm8(code, Alu::Sub, minimum); + eax_imm32(code, Alu::Cmp, maximum - u32::from(minimum)); } let failed = branch(code, Condition::AboveOrEqual); let end = code.len(); @@ -556,7 +600,7 @@ pub(super) fn scalar_range_or_zero( /// Set every S lane, or both dwords of every D lane, of `destination` to /// all ones where `source` holds a zero of either sign, using ZERO_VECTOR /// and, for D, ZERO_PAIR. -fn zero_lanes(code: &mut Vec, format: Format, destination: u8, source: u8) { +fn zero_lanes(code: &mut Code, format: Format, destination: u8, source: u8) { if destination != source { packed(code, Host::MoveAligned, destination, source); } @@ -567,28 +611,35 @@ fn zero_lanes(code: &mut Vec, format: Format, destination: u8, source: u8) { } packed(code, Host::EqualDword, destination, ZERO_VECTOR); if format == Format::Double { - packed(code, Host::ShuffleDword, ZERO_PAIR, destination); - code.push(SWAP_DWORD_PAIRS); + packed_imm( + code, + Host::ShuffleDword, + ZERO_PAIR, + destination, + SWAP_DWORD_PAIRS, + ); packed(code, Host::And, destination, ZERO_PAIR); } } -pub(super) fn test_control(code: &mut Vec, mask: u32) { - code.extend(TEST_STATE_IMM32); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(mask.to_le_bytes()); +pub(super) fn test_control(code: &mut Code, mask: u32) { + code.asm().test_imm( + Size::Dword, + state(core::mem::offset_of!(GuestState, fpcr)), + mask as i32, + ); } /// Leave flags from (exponent-minimum) versus the exclusive range length. /// Below is allocated normal; zero/all-ones exponents fail one unsigned test. -pub(super) fn exponent_range(code: &mut Vec, format: Format, source: u8, minimum: u8) { +pub(super) fn exponent_range(code: &mut Code, format: Format, source: u8, minimum: u8) { let maximum = (format.exponent_mask() >> format.fraction_bits()) as u32; exponent_range_impl(code, format, source, minimum, maximum, false); } /// A stricter exclusive upper exponent bounds finite arithmetic outputs too. pub(super) fn exponent_range_below( - code: &mut Vec, + code: &mut Code, format: Format, source: u8, minimum: u8, @@ -598,74 +649,67 @@ pub(super) fn exponent_range_below( } /// Keep the sign alongside the exponent so every negative input also fails. -pub(super) fn positive_exponent_range(code: &mut Vec, format: Format, source: u8, minimum: u8) { +pub(super) fn positive_exponent_range(code: &mut Code, format: Format, source: u8, minimum: u8) { let maximum = (format.exponent_mask() >> format.fraction_bits()) as u32; exponent_range_impl(code, format, source, minimum, maximum, true); } fn exponent_range_impl( - code: &mut Vec, + code: &mut Code, format: Format, source: u8, minimum: u8, maximum: u32, positive_only: bool, ) { - code.extend(match (format, source) { - (Format::Half | Format::Single, 0) => MOVD_EAX_XMM0, - (Format::Half | Format::Single, 1) => MOVD_EAX_XMM1, - (Format::Double, 0) => MOVQ_RAX_XMM0, - (Format::Double, 1) => MOVQ_RAX_XMM1, - (Format::Half | Format::Single, 6) => MOVD_EAX_XMM6, - (Format::Double, 6) => MOVQ_RAX_XMM6, - _ => unreachable!("allocated numerical source register"), - }); - code.extend(if format == Format::Double { - SHR_RAX_IMM8 + assert!( + matches!(source, 0 | 1 | 6), + "allocated numerical source register" + ); + let size = Size::of(format == Format::Double); + let mut asm = code.asm(); + if format == Format::Double { + asm.movq_from_xmm(Rax, source); } else { - SHR_EAX_IMM8 - }); - code.push(format.fraction_bits() as u8); + asm.movd_from_xmm(Rax, source); + } + asm.shift_imm(ShiftOp::Shr, size, Rax, format.fraction_bits() as u8); let exponent_mask = (1u32 << (format.bits() - format.fraction_bits() - 1)) - 1; - code.push(AND_EAX_IMM32); let field_mask = if positive_only { exponent_mask * 2 + 1 } else { exponent_mask }; - code.extend(field_mask.to_le_bytes()); + eax_imm32(code, Alu::And, field_mask); if minimum != 0 { - code.extend(SUB_EAX_IMM8); - code.push(minimum); + eax_imm8(code, Alu::Sub, minimum); } - code.push(CMP_EAX_IMM32); - code.extend((maximum - u32::from(minimum)).to_le_bytes()); + eax_imm32(code, Alu::Cmp, maximum - u32::from(minimum)); } -pub(super) fn environment(code: &mut Vec) { +pub(super) fn environment(code: &mut Code) { environment_round(code, Rounding::Fpcr); } /// Save the complete caller environment and install masked, nonflushing SSE /// control. Conversion instructions may select rounding independently of FPCR. -pub(super) fn environment_round(code: &mut Vec, rounding: Rounding) { - code.extend(SUB_RSP_ENVIRONMENT); - code.extend(STMXCSR_SAVED); +pub(super) fn environment_round(code: &mut Code, rounding: Rounding) { + let mut asm = code.asm(); + asm.alu_imm8(Alu::Sub, Size::Qword, Rsp, ENVIRONMENT_STACK_BYTES as i8); + asm.stmxcsr(frame(MXCSR_SAVED_OFFSET)); if matches!(rounding, Rounding::Fpcr) { - code.extend(MOV_ECX_STATE); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(MOV_EAX_ECX); - code.extend(SHR_EAX_IMM8); - code.push(FPCR_POSITIVE_TO_MXCSR_SHIFT); - code.push(AND_EAX_IMM32); - code.extend(MXCSR_POSITIVE_ROUNDING.to_le_bytes()); - code.extend(SHR_ECX_IMM8); - code.push(FPCR_NEGATIVE_TO_MXCSR_SHIFT); - code.extend(AND_ECX_IMM32); - code.extend(MXCSR_NEGATIVE_ROUNDING.to_le_bytes()); - code.extend(OR_EAX_ECX); - code.push(OR_EAX_IMM32); - code.extend(MXCSR_EXCEPTION_MASKS.to_le_bytes()); + asm.mov_load( + Size::Dword, + Rcx, + state(core::mem::offset_of!(GuestState, fpcr)), + ); + asm.mov(Size::Dword, Rax, Rcx); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, FPCR_POSITIVE_TO_MXCSR_SHIFT); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_POSITIVE_ROUNDING as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rcx, FPCR_NEGATIVE_TO_MXCSR_SHIFT); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, MXCSR_NEGATIVE_ROUNDING as i32); + asm.alu(Alu::Or, Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::Or, Size::Dword, MXCSR_EXCEPTION_MASKS as i32); } else { let direction = match rounding { Rounding::NearestEven => 0, @@ -674,46 +718,50 @@ pub(super) fn environment_round(code: &mut Vec, rounding: Rounding) { Rounding::Zero => MXCSR_POSITIVE_ROUNDING | MXCSR_NEGATIVE_ROUNDING, Rounding::Fpcr => unreachable!("FPCR control emitted above"), }; - code.push(MOV_EAX_IMM32); - code.extend((MXCSR_EXCEPTION_MASKS | direction).to_le_bytes()); + asm.mov_imm32(Rax, MXCSR_EXCEPTION_MASKS | direction); } - code.extend(MOV_CONTROL_EAX); - code.extend(LDMXCSR_CONTROL); + asm.mov_store(Size::Dword, frame(MXCSR_CONTROL_OFFSET), Rax); + asm.ldmxcsr(frame(MXCSR_CONTROL_OFFSET)); } -pub(super) fn restore_environment(code: &mut Vec) { - code.extend(STMXCSR_STATUS); - code.extend(LDMXCSR_SAVED); - code.extend(MOV_ECX_STATUS); - code.extend(ADD_RSP_ENVIRONMENT); +pub(super) fn restore_environment(code: &mut Code) { + let mut asm = code.asm(); + asm.stmxcsr(frame(MXCSR_STATUS_OFFSET)); + asm.ldmxcsr(frame(MXCSR_SAVED_OFFSET)); + asm.mov_load(Size::Dword, Rcx, frame(MXCSR_STATUS_OFFSET)); + asm.alu_imm8(Alu::Add, Size::Qword, Rsp, ENVIRONMENT_STACK_BYTES as i8); } /// Observe a real arithmetic stage without leaving the private environment. -pub(super) fn capture_environment_status(code: &mut Vec) { - code.extend(STMXCSR_STATUS); - code.extend(MOV_ECX_STATUS); +pub(super) fn capture_environment_status(code: &mut Code) { + let mut asm = code.asm(); + asm.stmxcsr(frame(MXCSR_STATUS_OFFSET)); + asm.mov_load(Size::Dword, Rcx, frame(MXCSR_STATUS_OFFSET)); } /// Discard private scratch-operation status before the next arithmetic stage. -pub(super) fn clear_environment_status(code: &mut Vec) { - code.extend(LDMXCSR_CONTROL); +pub(super) fn clear_environment_status(code: &mut Code) { + code.asm().ldmxcsr(frame(MXCSR_CONTROL_OFFSET)); } /// Accumulate status and leave ECX holding only fresh guest IXC (zero or INEXACT). -pub(super) fn commit_inexact(code: &mut Vec) { - code.extend(AND_ECX_IMM32); - code.extend(MXCSR_INEXACT.to_le_bytes()); - code.extend(SHR_ECX_IMM8); - code.push(MXCSR_TO_FPSR_INEXACT_SHIFT); - code.extend(OR_STATE_ECX); - code.extend((core::mem::offset_of!(GuestState, fpsr) as u32).to_le_bytes()); +pub(super) fn commit_inexact(code: &mut Code) { + let mut asm = code.asm(); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, MXCSR_INEXACT as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rcx, MXCSR_TO_FPSR_INEXACT_SHIFT); + asm.alu( + Alu::Or, + Size::Dword, + state(core::mem::offset_of!(GuestState, fpsr)), + Rcx, + ); } /// Extract exponent magnitudes into words/dwords and compare an open range. /// Double exponents occupy the low dword of each qword; their high dwords and /// inactive S lanes are excluded from the dword sign mask. No numerical FP runs here. pub(in crate::x86_64) fn vector_exponent_range( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, source: u8, @@ -723,7 +771,7 @@ pub(in crate::x86_64) fn vector_exponent_range( /// Reject negative inputs as well as zero and all-ones exponents. pub(super) fn vector_positive_exponent_range( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, source: u8, @@ -733,7 +781,7 @@ pub(super) fn vector_positive_exponent_range( /// Copy `source` to EXPONENT_VECTOR and reduce every lane to its exponent /// field, with the sign above it if `positive_only`. -fn vector_exponent_fields(code: &mut Vec, format: Format, source: u8, positive_only: bool) { +fn vector_exponent_fields(code: &mut Code, format: Format, source: u8, positive_only: bool) { packed(code, Host::MoveAligned, EXPONENT_VECTOR, source); let (left, right) = match format { Format::Single => (ShiftOpcode::LeftDword, ShiftOpcode::RightDword), @@ -752,7 +800,7 @@ fn vector_exponent_fields(code: &mut Vec, format: Format, source: u8, positi } } -fn vector_exponent_validity(code: &mut Vec, format: Format, source: u8, positive_only: bool) { +fn vector_exponent_validity(code: &mut Code, format: Format, source: u8, positive_only: bool) { vector_exponent_fields(code, format, source, positive_only); packed( code, @@ -770,26 +818,20 @@ fn vector_exponent_validity(code: &mut Vec, format: Format, source: u8, posi packed(code, Host::And, EXPONENT_VECTOR, VALIDITY_VECTOR); } -fn half_validity_mask(code: &mut Vec, byte_mask: u32) { +fn half_validity_mask(code: &mut Code, byte_mask: u32) { Host::ByteSignMask.register(code, 0, EXPONENT_VECTOR, crate::TargetCpu::Baseline); - code.push(AND_EAX_IMM32); - code.extend(byte_mask.to_le_bytes()); - code.push(CMP_EAX_IMM32); - code.extend(byte_mask.to_le_bytes()); + eax_imm32(code, Alu::And, byte_mask); + eax_imm32(code, Alu::Cmp, byte_mask); } /// Classify a caller-selected low Half lane span without inventing a vector shape. -pub(in crate::x86_64) fn vector_half_exponent_range( - code: &mut Vec, - source: u8, - byte_mask: u32, -) { +pub(in crate::x86_64) fn vector_half_exponent_range(code: &mut Code, source: u8, byte_mask: u32) { vector_exponent_validity(code, Format::Half, source, false); half_validity_mask(code, byte_mask); } fn vector_exponent_range_impl( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, source: u8, @@ -803,7 +845,7 @@ fn vector_exponent_range_impl( /// remain live in XMM4/5; XMM3 and `scratch` are classifier scratch. Unlike a zero /// fraction test, clearing just the sign rejects infinities and subnormals. pub(super) fn vector_normal_or_zero_range( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, source: u8, @@ -833,15 +875,20 @@ pub(super) fn vector_normal_or_zero_range( packed(code, Host::Xor, scratch, scratch); packed(code, Host::EqualDword, VALIDITY_VECTOR, scratch); if format == Format::Double { - packed(code, Host::ShuffleDword, scratch, VALIDITY_VECTOR); - code.push(SWAP_DWORD_PAIRS); + packed_imm( + code, + Host::ShuffleDword, + scratch, + VALIDITY_VECTOR, + SWAP_DWORD_PAIRS, + ); packed(code, Host::And, VALIDITY_VECTOR, scratch); } packed(code, Host::Or, EXPONENT_VECTOR, VALIDITY_VECTOR); vector_validity_mask(code, format, shape); } -fn vector_validity_mask(code: &mut Vec, format: Format, shape: Shape) { +fn vector_validity_mask(code: &mut Code, format: Format, shape: Shape) { if format == Format::Half { let mask = match shape { Shape::Scalar => HALF_SCALAR_BYTE_MASK, @@ -854,34 +901,30 @@ fn vector_validity_mask(code: &mut Vec, format: Format, shape: Shape) { Host::DwordSignMask.register(code, 0, EXPONENT_VECTOR, crate::TargetCpu::Baseline); let mask = match (shape, format) { (Shape::Scalar, _) => { - code.extend(AND_EAX_IMM8); - code.push(SCALAR_VECTOR_MASK); + eax_imm8(code, Alu::And, SCALAR_VECTOR_MASK); SCALAR_VECTOR_MASK } (Shape::Vector64, Format::Single) => { - code.extend(AND_EAX_IMM8); - code.push(SINGLE_LOW_VECTOR_MASK); + eax_imm8(code, Alu::And, SINGLE_LOW_VECTOR_MASK); SINGLE_LOW_VECTOR_MASK } (Shape::Vector128, Format::Single) => SINGLE_VECTOR_MASK, (Shape::Vector128, Format::Double) => { // Normal exponent validity occupies the low dword; exact-zero // validity fills both. Reduce one bit per architectural D lane. - code.extend(AND_EAX_IMM8); - code.push(DOUBLE_VECTOR_MASK); + eax_imm8(code, Alu::And, DOUBLE_VECTOR_MASK); DOUBLE_VECTOR_MASK } _ => unreachable!("allocated vector shape"), }; - code.extend(CMP_EAX_IMM8); - code.push(mask); + eax_imm8(code, Alu::Cmp, mask); } /// Widen four staged Half fields with integer operations. Callers guard active /// inputs and supply zero and the broadcast Single-minus-Half exponent bias. /// Inactive raw fields also become finite normal Single values without status. pub(in crate::x86_64) fn widen_half_to_single( - code: &mut Vec, + code: &mut Code, destination: u8, source: u8, sign: u8, @@ -910,14 +953,15 @@ pub(in crate::x86_64) fn widen_half_to_single( packed(code, Host::Or, destination, sign); } -pub(super) fn read_numerical_vector(code: &mut Vec, shape: Shape, source: u8, xmm: u8) { +pub(super) fn read_numerical_vector(code: &mut Code, shape: Shape, source: u8, xmm: u8) { if shape == Shape::Vector64 { // MOVQ loads only active bits and clears the high qword, even for DIV. - Host::MoveQword.append(code, crate::TargetCpu::Baseline); - const STATE_MEMORY: u8 = 0x87; - const MODRM_REGISTER_SHIFT: u8 = 3; - code.push(STATE_MEMORY | (xmm << MODRM_REGISTER_SHIFT)); - code.extend(vector_offset(source).to_le_bytes()); + Host::MoveQword.emit( + code, + xmm, + state(vector_offset(source) as usize), + crate::TargetCpu::Baseline, + ); } else { read_vector(code, source, xmm); } @@ -927,17 +971,18 @@ pub(super) fn read_numerical_vector(code: &mut Vec, shape: Shape, source: u8 /// it clear (MOVSS or MOVSD from memory), so that a scalar operation with /// `xmm` as its destination leaves the upper bits an Arm scalar write /// clears already clear. -pub(super) fn read_numerical_scalar(code: &mut Vec, format: Format, source: u8, xmm: u8) { - const STATE_MEMORY: u8 = 0x87; - const MODRM_REGISTER_SHIFT: u8 = 3; +pub(super) fn read_numerical_scalar(code: &mut Code, format: Format, source: u8, xmm: u8) { match format { Format::Single => Host::MoveScalarSingle, Format::Double => Host::MoveScalarDouble, Format::Half => unreachable!("Half has its own mapping policy"), } - .append(code, crate::TargetCpu::Baseline); - code.push(STATE_MEMORY | (xmm << MODRM_REGISTER_SHIFT)); - code.extend(vector_offset(source).to_le_bytes()); + .emit( + code, + xmm, + state(vector_offset(source) as usize), + crate::TargetCpu::Baseline, + ); } /// How a sticky path reads one input from the frame: a zeroing scalar @@ -959,7 +1004,7 @@ const INSERT_LOW_LANE_ALONE: u8 = 0b1110; /// read into XMM0 replaces it. A Single scalar copy needs SSE4.1's /// INSERTPS; without it the frame provides the input. pub(super) fn read_inputs( - code: &mut Vec, + code: &mut Code, xmm0: Option, target: crate::TargetCpu, inputs: &[(Input, u8, u8)], @@ -968,10 +1013,15 @@ pub(super) fn read_inputs( xmm0 == Some(source) && !matches!(input, Input::Scalar(Format::Single) if !target.supports(crate::TargetCpu::Sse41)) }; - let copy = |code: &mut Vec, input: Input, xmm: u8| match input { + let copy = |code: &mut Code, input: Input, xmm: u8| match input { Input::Scalar(Format::Single) => { - Host::InsertSingle.register(code, xmm, LEFT_VECTOR, target); - code.push(INSERT_LOW_LANE_ALONE); + Host::InsertSingle.emit_imm( + code, + xmm, + Rm::Xmm(LEFT_VECTOR), + INSERT_LOW_LANE_ALONE, + target, + ); } Input::Scalar(Format::Double) | Input::Vector(Shape::Vector64) => { packed(code, Host::MoveQword, xmm, LEFT_VECTOR); @@ -1003,7 +1053,7 @@ pub(super) fn read_inputs( /// Select from the whole indexed source before broadcasting. A 64-bit indexed /// form may read a lane in the upper qword. pub(super) fn read_numerical_right( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, source: u8, @@ -1019,12 +1069,22 @@ pub(super) fn read_numerical_right( ); if shape != Shape::Scalar { if format == Format::Half { - packed(code, Host::ShuffleLowWord, RIGHT_VECTOR, RIGHT_VECTOR); - code.push(BROADCAST_LOW_LANE); + packed_imm( + code, + Host::ShuffleLowWord, + RIGHT_VECTOR, + RIGHT_VECTOR, + BROADCAST_LOW_LANE, + ); } if format != Format::Double { - packed(code, Host::ShuffleDword, RIGHT_VECTOR, RIGHT_VECTOR); - code.push(BROADCAST_LOW_LANE); + packed_imm( + code, + Host::ShuffleDword, + RIGHT_VECTOR, + RIGHT_VECTOR, + BROADCAST_LOW_LANE, + ); } else { packed(code, Host::UnpackLowQword, RIGHT_VECTOR, RIGHT_VECTOR); } @@ -1034,7 +1094,7 @@ pub(super) fn read_numerical_right( } } -pub(in crate::x86_64) fn prepare_vector_input_range(code: &mut Vec, format: Format) { +pub(in crate::x86_64) fn prepare_vector_input_range(code: &mut Code, format: Format) { prepare_vector_maximum(code, format); packed( code, @@ -1046,7 +1106,7 @@ pub(in crate::x86_64) fn prepare_vector_input_range(code: &mut Vec, format: /// The all-ones exponent of `format` in every lane of /// MAXIMUM_EXPONENT_VECTOR. -fn prepare_vector_maximum(code: &mut Vec, format: Format) { +fn prepare_vector_maximum(code: &mut Code, format: Format) { packed( code, Host::EqualDword, @@ -1063,24 +1123,23 @@ fn prepare_vector_maximum(code: &mut Vec, format: Format) { } /// Set an exclusive upper bound, keeping the normal lower bound used by /// `vector_exponent_range`. Half precision repeats the limit in both words. -pub(super) fn prepare_vector_input_range_below(code: &mut Vec, format: Format, maximum: u32) { - const MOVD_MAXIMUM_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xe0]; +pub(super) fn prepare_vector_input_range_below(code: &mut Code, format: Format, maximum: u32) { const BROADCAST_LOW_DWORD: u8 = 0; let limit = if format == Format::Half { maximum | maximum << u16::BITS } else { maximum }; - code.push(MOV_EAX_IMM32); - code.extend(limit.to_le_bytes()); - code.extend(MOVD_MAXIMUM_EAX); - packed( + let mut asm = code.asm(); + asm.mov_imm32(Rax, limit); + asm.movd_to_xmm(MAXIMUM_EXPONENT_VECTOR, Rax); + packed_imm( code, Host::ShuffleDword, MAXIMUM_EXPONENT_VECTOR, MAXIMUM_EXPONENT_VECTOR, + BROADCAST_LOW_DWORD, ); - code.push(BROADCAST_LOW_DWORD); packed( code, Host::Xor, @@ -1089,7 +1148,7 @@ pub(super) fn prepare_vector_input_range_below(code: &mut Vec, format: Forma ); } -pub(in crate::x86_64) fn prepare_vector_result_range(code: &mut Vec) { +pub(in crate::x86_64) fn prepare_vector_result_range(code: &mut Code) { packed( code, Host::EqualDword, @@ -1099,7 +1158,7 @@ pub(in crate::x86_64) fn prepare_vector_result_range(code: &mut Vec) { ShiftOpcode::RightDword.emit(code, MINIMUM_EXPONENT_VECTOR, u32::BITS as u8 - SIGN_BITS); } pub(super) fn emit_opcode( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, opcode: ArithmeticOpcode, @@ -1110,78 +1169,53 @@ pub(super) fn emit_opcode( /// Arithmetic encoding with an explicit destination register. pub(in crate::x86_64) fn emit_opcode_to( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, opcode: ArithmeticOpcode, destination: u8, source: u8, ) { - if shape == Shape::Scalar { - code.push(if format == Format::Single { - SCALAR_SINGLE_PREFIX - } else { - SCALAR_DOUBLE_PREFIX - }); - } else if format == Format::Double { - code.push(PACKED_DOUBLE_PREFIX); - } - const REGISTER_DIRECT: u8 = 0xc0; - const MODRM_REGISTER_SHIFT: u8 = 3; - code.extend([ - SSE_ESCAPE, - opcode as u8, - REGISTER_DIRECT | destination << MODRM_REGISTER_SHIFT | source, - ]); + code.asm().float( + opcode.float_op(), + float_lanes(format, shape), + destination, + Rm::Xmm(source), + ); } -pub(super) fn reject_other_status(code: &mut Vec) -> usize { - code.extend(TEST_ECX_IMM32); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); +pub(super) fn reject_other_status(code: &mut Code) -> usize { + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_OTHER_STATUS as i32); branch(code, Condition::NotZero) } -pub(super) fn save_product_status(code: &mut Vec) { - const STMXCSR_PRODUCT: &[u8] = &[0x0f, 0xae, 0x5c, 0x24, 12]; - code.extend(STMXCSR_PRODUCT); +pub(super) fn save_product_status(code: &mut Code) { + code.asm().stmxcsr(frame(MXCSR_PRODUCT_OFFSET)); } -pub(super) fn restore_environment_with_product(code: &mut Vec) { - const MOV_EAX_PRODUCT: &[u8] = &[0x8b, 0x44, 0x24, 12]; - code.extend(STMXCSR_STATUS); - code.extend(LDMXCSR_SAVED); - code.extend(MOV_EAX_PRODUCT); - code.extend(MOV_ECX_STATUS); - code.extend(ADD_RSP_ENVIRONMENT); +pub(super) fn restore_environment_with_product(code: &mut Code) { + let mut asm = code.asm(); + asm.stmxcsr(frame(MXCSR_STATUS_OFFSET)); + asm.ldmxcsr(frame(MXCSR_SAVED_OFFSET)); + asm.mov_load(Size::Dword, Rax, frame(MXCSR_PRODUCT_OFFSET)); + asm.mov_load(Size::Dword, Rcx, frame(MXCSR_STATUS_OFFSET)); + asm.alu_imm8(Alu::Add, Size::Qword, Rsp, ENVIRONMENT_STACK_BYTES as i8); } -pub(super) fn reject_product_status(code: &mut Vec) -> usize { - const TEST_AL_STATUS: &[u8] = &[0xa8, 0x3f]; - code.extend(TEST_AL_STATUS); +pub(super) fn reject_product_status(code: &mut Code) -> usize { + code.asm() + .test_accumulator_imm(Size::Byte, MXCSR_STATUS_FLAGS.into()); branch(code, Condition::NotZero) } -pub(super) fn clear_scalar(code: &mut Vec, format: Format, xmm: u8) { - const REGISTER_DIRECT: u8 = 0xc0; - const MODRM_REGISTER_SHIFT: u8 = 3; +/// `movq xmm, xmm`: clear the high qword of `xmm`. +pub(super) fn clear_high_qword(code: &mut Code, xmm: u8) { + Host::MoveQword.register(code, xmm, xmm, crate::TargetCpu::Baseline); +} +pub(super) fn clear_scalar(code: &mut Code, format: Format, xmm: u8) { if format == Format::Double { - code.extend([ - 0xf3, - 0x0f, - 0x7e, - REGISTER_DIRECT | (xmm << MODRM_REGISTER_SHIFT) | xmm, - ]); + Host::MoveQword.register(code, xmm, xmm, crate::TargetCpu::Baseline); } else { - code.extend([ - 0x66, - 0x0f, - 0x7e, - REGISTER_DIRECT | (xmm << MODRM_REGISTER_SHIFT), - ]); + code.asm().movd_from_xmm(Rax, xmm); if format == Format::Half { - code.push(AND_EAX_IMM32); - code.extend(u32::from(u16::MAX).to_le_bytes()); + eax_imm32(code, Alu::And, u32::from(u16::MAX)); } - code.extend([ - 0x66, - 0x0f, - 0x6e, - REGISTER_DIRECT | (xmm << MODRM_REGISTER_SHIFT), - ]); + code.asm().movd_to_xmm(xmm, Rax); } } diff --git a/crates/stela-compiler/src/x86_64/simd/numerical/bfloat16.rs b/crates/stela-compiler/src/x86_64/simd/numerical/bfloat16.rs index 8199b7839b..da0b9959da 100644 --- a/crates/stela-compiler/src/x86_64/simd/numerical/bfloat16.rs +++ b/crates/stela-compiler/src/x86_64/simd/numerical/bfloat16.rs @@ -3,7 +3,7 @@ use super::super::super::isa::ShiftOpcode; use super::super::{Host, packed}; use super::quantization::{IntegerRoundingRegister, broadcast_integer_rounding}; use crate::aarch64::floating::bfloat16::BFLOAT16_TO_SINGLE_SHIFT; -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Gpr, ShiftOp, Size, Unary}; const RESULT: u8 = 0; const SOURCE: u8 = 1; @@ -19,34 +19,20 @@ const DISCARDED_BITS: u8 = BFLOAT16_TO_SINGLE_SHIFT as u8; const DISCARDED_MASK: u32 = (1 << DISCARDED_BITS) - 1; const VECTOR_LANES: u32 = 4; const VECTOR_LANE_MASK: u32 = (1 << VECTOR_LANES) - 1; -const NOT_EAX: &[u8] = &[0xf7, 0xd0]; -const AND_EAX_IMM8: &[u8] = &[0x83, 0xe0]; -const MOV_R10D_EAX: &[u8] = &[0x41, 0x89, 0xc2]; -const MOV_EDX_EAX: &[u8] = &[0x89, 0xc2]; -const AND_EDX_IMM32: &[u8] = &[0x81, 0xe2]; -const OR_R10D_EDX: &[u8] = &[0x41, 0x09, 0xd2]; -const SHR_EDX_IMM8: &[u8] = &[0xc1, 0xea]; -const AND_EDX_R11D: &[u8] = &[0x44, 0x21, 0xda]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const SAR_ECX_IMM8: &[u8] = &[0xc1, 0xf9]; -const AND_ECX_R9D: &[u8] = &[0x44, 0x21, 0xc9]; -const XOR_ECX_R8D: &[u8] = &[0x44, 0x31, 0xc1]; -const ADD_ECX_EDX: &[u8] = &[0x01, 0xd1]; -const ADD_EAX_ECX: &[u8] = &[0x01, 0xc8]; /// Record four lanes' discarded bits in R10D and apply shared selectors. /// XMM0 is output, XMM1 input, XMM2..5 scratch; XMM6/7 and R8/9/11 survive. -pub(in crate::x86_64) fn quantize_bfloat_packed(code: &mut Vec) { +pub(in crate::x86_64) fn quantize_bfloat_packed(code: &mut Code) { packed(code, Host::MoveAligned, RESULT, SOURCE); packed(code, Host::MoveAligned, TEMPORARY, SOURCE); ShiftOpcode::LeftDword.emit(code, TEMPORARY, SINGLE_BITS - DISCARDED_BITS); packed(code, Host::Xor, ZERO, ZERO); packed(code, Host::EqualDword, TEMPORARY, ZERO); packed(code, Host::DwordSignMask, GPR_RAX, TEMPORARY); - code.extend(NOT_EAX); - code.extend(AND_EAX_IMM8); - code.push(VECTOR_LANE_MASK as u8); - code.extend(MOV_R10D_EAX); + let mut asm = code.asm(); + asm.unary(Unary::Not, Size::Dword, Gpr::Rax); + asm.alu_imm8(Alu::And, Size::Dword, Gpr::Rax, VECTOR_LANE_MASK as i8); + asm.mov(Size::Dword, Gpr::R10, Gpr::Rax); packed(code, Host::MoveAligned, SIGN, SOURCE); ShiftOpcode::ArithmeticDword.emit(code, SIGN, SIGN_POSITION); @@ -65,20 +51,20 @@ pub(in crate::x86_64) fn quantize_bfloat_packed(code: &mut Vec) { /// Round the single-precision bits in EAX to BF16, ORing the discarded bits /// into R10D. ECX/EDX are scratch; XMM registers, state, stack and MXCSR are /// untouched. -pub(in crate::x86_64) fn quantize_bfloat_scalar_bits(code: &mut Vec) { - code.extend(MOV_EDX_EAX); - code.extend(AND_EDX_IMM32); - code.extend(DISCARDED_MASK.to_le_bytes()); - code.extend(OR_R10D_EDX); - code.extend(MOV_EDX_EAX); - code.extend(SHR_EDX_IMM8); - code.push(DISCARDED_BITS); - code.extend(AND_EDX_R11D); - code.extend(MOV_ECX_EAX); - code.extend(SAR_ECX_IMM8); - code.push(SIGN_POSITION); - code.extend(AND_ECX_R9D); - code.extend(XOR_ECX_R8D); - code.extend(ADD_ECX_EDX); - code.extend(ADD_EAX_ECX); +pub(in crate::x86_64) fn quantize_bfloat_scalar_bits(code: &mut Code) { + use Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdx}; + use Size::Dword; + let mut asm = code.asm(); + asm.mov(Dword, Rdx, Rax); + asm.alu_imm32(Alu::And, Dword, Rdx, DISCARDED_MASK as i32); + asm.alu(Alu::Or, Dword, R10, Rdx); + asm.mov(Dword, Rdx, Rax); + asm.shift_imm(ShiftOp::Shr, Dword, Rdx, DISCARDED_BITS); + asm.alu(Alu::And, Dword, Rdx, R11); + asm.mov(Dword, Rcx, Rax); + asm.shift_imm(ShiftOp::Sar, Dword, Rcx, SIGN_POSITION); + asm.alu(Alu::And, Dword, Rcx, R9); + asm.alu(Alu::Xor, Dword, Rcx, R8); + asm.alu(Alu::Add, Dword, Rcx, Rdx); + asm.alu(Alu::Add, Dword, Rax, Rcx); } diff --git a/crates/stela-compiler/src/x86_64/simd/numerical/control.rs b/crates/stela-compiler/src/x86_64/simd/numerical/control.rs index 78c68f7c64..fce438f663 100644 --- a/crates/stela-compiler/src/x86_64/simd/numerical/control.rs +++ b/crates/stela-compiler/src/x86_64/simd/numerical/control.rs @@ -1,7 +1,7 @@ //! Translate FPCR rounding controls into a private MXCSR. +use crate::x86_64::asm::{Alu, Code, Gpr, ShiftOp, Size}; use crate::{GuestState, aarch64::floating::FPCR_ROUNDING_SHIFT}; -use alloc::vec::Vec; const MXCSR_POSITIVE_ROUNDING_SHIFT: u8 = 14; const MXCSR_NEGATIVE_ROUNDING_SHIFT: u8 = 13; @@ -10,29 +10,23 @@ const MXCSR_NEGATIVE_ROUNDING: u32 = 1 << MXCSR_NEGATIVE_ROUNDING_SHIFT; const FPCR_POSITIVE_TO_MXCSR_SHIFT: u8 = FPCR_ROUNDING_SHIFT as u8 - MXCSR_POSITIVE_ROUNDING_SHIFT; const FPCR_NEGATIVE_TO_MXCSR_SHIFT: u8 = FPCR_ROUNDING_SHIFT as u8 + 1 - MXCSR_NEGATIVE_ROUNDING_SHIFT; -const MOV_EAX_STATE: &[u8] = &[0x8b, 0x87]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; -const SHR_ECX_IMMEDIATE: &[u8] = &[0xc1, 0xe9]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const AND_ECX_IMMEDIATE: &[u8] = &[0x81, 0xe1]; -const OR_EAX_ECX: &[u8] = &[0x09, 0xc8]; /// Read raw guest FPCR and leave only positioned host RC bits in EAX. /// Clobbers ECX and host flags; preserves every XMM, RDI/R15 and guest state. /// Operation-specific AH/rounding policy and MXCSR installation remain callers' /// responsibilities. This helper neither installs nor reads host MXCSR. -pub(in crate::x86_64) fn rounding_control(code: &mut Vec) { - code.extend(MOV_EAX_STATE); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(MOV_ECX_EAX); - code.extend(SHR_EAX_IMMEDIATE); - code.push(FPCR_POSITIVE_TO_MXCSR_SHIFT); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_POSITIVE_ROUNDING.to_le_bytes()); - code.extend(SHR_ECX_IMMEDIATE); - code.push(FPCR_NEGATIVE_TO_MXCSR_SHIFT); - code.extend(AND_ECX_IMMEDIATE); - code.extend(MXCSR_NEGATIVE_ROUNDING.to_le_bytes()); - code.extend(OR_EAX_ECX); +pub(in crate::x86_64) fn rounding_control(code: &mut Code) { + use Gpr::{Rax, Rcx}; + let mut asm = code.asm(); + asm.mov_load( + Size::Dword, + Rax, + super::state(core::mem::offset_of!(GuestState, fpcr)), + ); + asm.mov(Size::Dword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, FPCR_POSITIVE_TO_MXCSR_SHIFT); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_POSITIVE_ROUNDING as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rcx, FPCR_NEGATIVE_TO_MXCSR_SHIFT); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, MXCSR_NEGATIVE_ROUNDING as i32); + asm.alu(Alu::Or, Size::Dword, Rax, Rcx); } diff --git a/crates/stela-compiler/src/x86_64/simd/numerical/quantization.rs b/crates/stela-compiler/src/x86_64/simd/numerical/quantization.rs index 7b666c0db9..46a2a91a9e 100644 --- a/crates/stela-compiler/src/x86_64/simd/numerical/quantization.rs +++ b/crates/stela-compiler/src/x86_64/simd/numerical/quantization.rs @@ -1,33 +1,13 @@ //! Rounding selectors shared by the half and BF16 conversions. use super::super::shuffle; -use super::{ - AND_ECX_IMM32, Condition, MOV_ECX_STATE, SHR_ECX_IMM8, TEST_ECX_IMM32, branch, resolve, -}; +use super::{Condition, branch, jump, resolve, state}; use crate::GuestState; -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, ShiftOp, Size, Unary}; const ROUND_TOWARD_POSITIVE: u8 = 1; -const MOVD_XMM_EXTENDED_GPR_PREFIX: &[u8] = &[0x66, 0x41, 0x0f, 0x6e]; -const AND_ECX_IMM8: &[u8] = &[0x83, 0xe1]; -const TEST_ECX_ECX: &[u8] = &[0x85, 0xc9]; -const SETE_AL: &[u8] = &[0x0f, 0x94, 0xc0]; -const MOV_R11D_EAX: &[u8] = &[0x44, 0x8b, 0xd8]; -const LEA_EDX_RCX_PLUS_ONE: &[u8] = &[0x8d, 0x51, 0x01]; -const SHR_EDX_ONE: &[u8] = &[0xd1, 0xea]; -const AND_EDX_ONE: &[u8] = &[0x83, 0xe2, 0x01]; -const NEG_EDX: &[u8] = &[0xf7, 0xda]; -const AND_EDX_IMM32: &[u8] = &[0x81, 0xe2]; -const MOV_R9D_EDX: &[u8] = &[0x41, 0x89, 0xd1]; -const XOR_R8D_R8D: &[u8] = &[0x45, 0x31, 0xc0]; -const MOV_R8D_IMM32: &[u8] = &[0x41, 0xb8]; -const CMP_ECX_IMM8: &[u8] = &[0x83, 0xf9]; -const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; -const MOVZX_EAX_AL: &[u8] = &[0x0f, 0xb6, 0xc0]; -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; const REPLICATE_FIRST_DWORD: u8 = 0; -/// Low ModRM bits of the caller-volatile extended rounding registers. +/// The caller-volatile extended rounding registers. #[repr(u8)] pub(in crate::x86_64) enum IntegerRoundingRegister { Bias = 0, // R8D @@ -35,13 +15,22 @@ pub(in crate::x86_64) enum IntegerRoundingRegister { Parity = 3, // R11D } +impl IntegerRoundingRegister { + const fn register(self) -> Gpr { + match self { + Self::Bias => Gpr::R8, + Self::Direction => Gpr::R9, + Self::Parity => Gpr::R11, + } + } +} + pub(in crate::x86_64) fn broadcast_integer_rounding( - code: &mut Vec, + code: &mut Code, vector: u8, register: IntegerRoundingRegister, ) { - code.extend(MOVD_XMM_EXTENDED_GPR_PREFIX); - code.push(REGISTER_DIRECT | vector << MODRM_REGISTER_SHIFT | register as u8); + code.asm().movd_to_xmm(vector, register.register()); shuffle(code, vector, vector, REPLICATE_FIRST_DWORD); } @@ -49,59 +38,57 @@ pub(in crate::x86_64) fn broadcast_integer_rounding( /// R10D starts fresh exception accumulation; ordinary arithmetic keeps guest RC, /// while BF16 conversion selects nearest-even when alternative handling is set. pub(in crate::x86_64) fn integer_rounding_policy( - code: &mut Vec, + code: &mut Code, discarded_bits: u8, alternative_nearest: bool, ) { use crate::aarch64::floating::{FPCR_AH, FPCR_ROUNDING_MASK, FPCR_ROUNDING_SHIFT}; + use Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdx}; + use Size::Dword; assert!(discarded_bits > 0 && u32::from(discarded_bits) < u32::BITS); let discarded_mask = (1u32 << discarded_bits) - 1; let nearest_bias = discarded_mask >> 1; - code.extend(MOV_ECX_STATE); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); + code.asm() + .mov_load(Dword, Rcx, state(core::mem::offset_of!(GuestState, fpcr))); if alternative_nearest { - code.extend(TEST_ECX_IMM32); - code.extend(FPCR_AH.to_le_bytes()); + code.asm().test_imm(Dword, Rcx, FPCR_AH as i32); let ordinary = branch(code, Condition::Zero); - code.extend(AND_ECX_IMM32); - code.extend((!(FPCR_ROUNDING_MASK << FPCR_ROUNDING_SHIFT)).to_le_bytes()); + code.asm().alu_imm32( + Alu::And, + Dword, + Rcx, + !(FPCR_ROUNDING_MASK << FPCR_ROUNDING_SHIFT) as i32, + ); let ready = code.len(); resolve(code, ordinary, ready); } - code.extend(SHR_ECX_IMM8); - code.push(FPCR_ROUNDING_SHIFT as u8); - code.extend(AND_ECX_IMM8); - code.push(FPCR_ROUNDING_MASK as u8); - code.extend(TEST_ECX_ECX); - code.extend(SETE_AL); - code.extend(MOVZX_EAX_AL); - code.extend(MOV_R11D_EAX); + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shr, Dword, Rcx, FPCR_ROUNDING_SHIFT as u8); + asm.alu_imm8(Alu::And, Dword, Rcx, FPCR_ROUNDING_MASK as i8); + asm.test(Dword, Rcx, Rcx); + asm.setcc(Cond::E, Rax); + asm.movzx(Dword, Rax, Size::Byte, Rax); + asm.mov_load(Dword, R11, Rax); // -(((mode+1)>>1)&1) selects both directed modes, independent of sign. - code.extend(LEA_EDX_RCX_PLUS_ONE); - code.extend(SHR_EDX_ONE); - code.extend(AND_EDX_ONE); - code.extend(NEG_EDX); - code.extend(AND_EDX_IMM32); - code.extend(discarded_mask.to_le_bytes()); - code.extend(MOV_R9D_EDX); - code.extend(XOR_R8D_R8D); - code.extend(TEST_ECX_ECX); + asm.lea(Dword, Rdx, crate::x86_64::asm::Mem::base(Rcx, 1)); + asm.shift_one(ShiftOp::Shr, Dword, Rdx); + asm.alu_imm8(Alu::And, Dword, Rdx, 1); + asm.unary(Unary::Neg, Dword, Rdx); + asm.alu_imm32(Alu::And, Dword, Rdx, discarded_mask as i32); + asm.mov(Dword, R9, Rdx); + asm.alu(Alu::Xor, Dword, R8, R8); + asm.test(Dword, Rcx, Rcx); let not_nearest = branch(code, Condition::NotZero); - code.extend(MOV_R8D_IMM32); - code.extend(nearest_bias.to_le_bytes()); - const JMP_REL32: u8 = 0xe9; - code.push(JMP_REL32); - let nearest = code.len(); - code.extend(0i32.to_le_bytes()); + code.asm().mov_imm32(R8, nearest_bias); + let nearest = jump(code); let directed = code.len(); resolve(code, not_nearest, directed); - code.extend(CMP_ECX_IMM8); - code.push(ROUND_TOWARD_POSITIVE); + code.asm() + .alu_imm8(Alu::Cmp, Dword, Rcx, ROUND_TOWARD_POSITIVE as i8); let not_positive = branch(code, Condition::NotZero); - code.extend(MOV_R8D_IMM32); - code.extend(discarded_mask.to_le_bytes()); + code.asm().mov_imm32(R8, discarded_mask); let ready = code.len(); resolve(code, not_positive, ready); resolve(code, nearest, ready); - code.extend(XOR_R10D_R10D); + code.asm().alu(Alu::Xor, Dword, R10, R10); } diff --git a/crates/stela-compiler/src/x86_64/simd/precision.rs b/crates/stela-compiler/src/x86_64/simd/precision.rs index 663bd63eb1..07cc93f1aa 100644 --- a/crates/stela-compiler/src/x86_64/simd/precision.rs +++ b/crates/stela-compiler/src/x86_64/simd/precision.rs @@ -1,5 +1,6 @@ //! FCVT between FP formats: SSE2 or integer paths, software fallback otherwise. use super::super::isa::ShiftOpcode; +use super::numerical::helper_section; use super::numerical::{ Condition, INPUT_MINIMUM_EXPONENT, MINIMUM_EXPONENT_VECTOR, RESULT_MINIMUM_EXPONENT, Rounding, branch, clear_scalar, commit_inexact, environment_round, exponent_range, @@ -7,6 +8,8 @@ use super::numerical::{ reject_other_status, resolve, restore_environment, test_control, vector_exponent_range, }; use super::{Host, commit, packed, read_vector}; +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Rm, ShiftOp, Size}; use crate::{ GuestAddress, aarch64::{ @@ -18,37 +21,14 @@ use crate::{ }, block::ExitKind, }; +use Gpr::{Rax, Rcx}; use alloc::vec::Vec; const RESULT_VECTOR: u8 = 0; const SOURCE_VECTOR: u8 = 1; const JAM_VECTOR: u8 = 6; -const CVTSS2SD_XMM0_XMM1: &[u8] = &[0xf3, 0x0f, 0x5a, 0xc1]; -const CVTSD2SS_XMM0_XMM1: &[u8] = &[0xf2, 0x0f, 0x5a, 0xc1]; -const CVTPS2PD_XMM0_XMM1: &[u8] = &[0x0f, 0x5a, 0xc1]; -const CVTPS2PD_XMM6_XMM0: &[u8] = &[0x0f, 0x5a, 0xf0]; -const CMPEQPD_XMM6_XMM1: &[u8] = &[0x66, 0x0f, 0xc2, 0xf1, 0]; -const CVTPD2PS_XMM0_XMM1: &[u8] = &[0x66, 0x0f, 0x5a, 0xc1]; -const PSRLDQ_XMM1_8: &[u8] = &[0x66, 0x0f, 0x73, 0xd9, 8]; -const MOVLHPS_XMM1_XMM0: &[u8] = &[0x0f, 0x16, 0xc8]; -const MOVSS_XMM0_XMM1: &[u8] = &[0xf3, 0x0f, 0x10, 0xc1]; -const MOVD_EAX_XMM1: &[u8] = &[0x66, 0x0f, 0x7e, 0xc8]; -const MOVD_XMM1_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xc8]; -const MOVQ_RAX_XMM1: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xc8]; -const MOVD_XMM6_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xf0]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const AND_EAX_IMM32: u8 = 0x25; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const ADD_EAX_IMM32: u8 = 0x05; -const OR_EAX_ECX: &[u8] = &[0x09, 0xc8]; -const SHR_EAX_IMM8: &[u8] = &[0xc1, 0xe8]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const SHL_ECX_IMM8: &[u8] = &[0xc1, 0xe1]; -const SUB_EAX_1: &[u8] = &[0x83, 0xe8, 1]; -const CMP_EAX_IMM8: &[u8] = &[0x83, 0xf8]; -const SETNE_AL: &[u8] = &[0x0f, 0x95, 0xc0]; -const MOVZX_EAX_AL: &[u8] = &[0x0f, 0xb6, 0xc0]; -const JMP_REL32: u8 = 0xe9; +const COMPARE_EQUAL: u8 = 0; +const UPPER_QWORD_BYTES: u8 = 8; const HALF_EXPONENT_BITS: u8 = 5; const HALF_EXPONENT_MASK: u32 = (1 << HALF_EXPONENT_BITS) - 1; const HALF_NORMAL_EXPONENT_COUNT: u8 = HALF_EXPONENT_MASK as u8 - 1; @@ -74,27 +54,12 @@ const DOUBLE_TO_SINGLE_DISCARDED_MASK: u32 = (1 << DOUBLE_TO_SINGLE_DISCARDED_BI const COMPACT_QWORD_LOW_DWORDS: u8 = 0x88; const DWORD_SIGN_TO_LSB_SHIFT: u8 = u32::BITS as u8 - 1; -fn exception_guard(code: &mut Vec, helper: &mut Vec) { +fn exception_guard(code: &mut Code, helper: &mut Vec) { test_control(code, FPCR_EXCEPTION_ENABLE_MASK); helper.push(branch(code, Condition::NotZero)); } -/// Keep all failure branches ahead of guest-state commit. No private host -/// environment may remain installed when this common helper section is emitted. -fn helper_section(code: &mut Vec, helper: &[usize], pc: GuestAddress) { - code.push(JMP_REL32); - let completed = code.len(); - code.extend(0i32.to_le_bytes()); - let helper_start = code.len(); - super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); - let success_start = code.len(); - for &patch in helper { - resolve(code, patch, helper_start); - } - resolve(code, completed, success_start); -} - -fn scalar_commit(code: &mut Vec, destination: u8, format: Format) { +fn scalar_commit(code: &mut Code, destination: u8, format: Format) { test_control(code, FPCR_NEP); let merging = branch(code, Condition::NotZero); clear_scalar(code, format, RESULT_VECTOR); @@ -103,56 +68,70 @@ fn scalar_commit(code: &mut Vec, destination: u8, format: Format) { commit(code, destination, RESULT_VECTOR); } -fn half_normal_guard(code: &mut Vec, helper: &mut Vec) { - code.extend(MOVD_EAX_XMM1); - code.extend(SHR_EAX_IMM8); - code.push(Format::Half.fraction_bits() as u8); - code.push(AND_EAX_IMM32); - code.extend(HALF_EXPONENT_MASK.to_le_bytes()); - code.extend(SUB_EAX_1); - code.extend(CMP_EAX_IMM8); - code.push(HALF_NORMAL_EXPONENT_COUNT); +fn half_normal_guard(code: &mut Code, helper: &mut Vec) { + let mut asm = code.asm(); + asm.movd_from_xmm(Rax, SOURCE_VECTOR); + asm.shift_imm( + ShiftOp::Shr, + Size::Dword, + Rax, + Format::Half.fraction_bits() as u8, + ); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, HALF_EXPONENT_MASK as i32); + asm.alu_imm8(Alu::Sub, Size::Dword, Rax, 1); + asm.alu_imm8(Alu::Cmp, Size::Dword, Rax, HALF_NORMAL_EXPONENT_COUNT as i8); helper.push(branch(code, Condition::AboveOrEqual)); } /// Exact normal half widening uses only field construction. In particular, /// conversion ignores FZ16, and no host numerical half extension is assumed. -fn half_to_single(code: &mut Vec) { - code.extend(MOVD_EAX_XMM1); - code.extend(MOV_ECX_EAX); - code.push(AND_EAX_IMM32); - code.extend(HALF_MAGNITUDE.to_le_bytes()); - code.extend(SHL_EAX_IMM8); - code.push(HALF_TO_SINGLE_FRACTION_SHIFT); - code.push(ADD_EAX_IMM32); - code.extend(HALF_TO_SINGLE_BIAS.to_le_bytes()); - code.extend(AND_ECX_IMM32); - code.extend(HALF_SIGN.to_le_bytes()); - code.extend(SHL_ECX_IMM8); - code.push(HALF_TO_SINGLE_SIGN_SHIFT); - code.extend(OR_EAX_ECX); - code.extend(MOVD_XMM1_EAX); +fn half_to_single(code: &mut Code) { + let mut asm = code.asm(); + asm.movd_from_xmm(Rax, SOURCE_VECTOR); + asm.mov(Size::Dword, Rcx, Rax); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, HALF_MAGNITUDE as i32); + asm.shift_imm( + ShiftOp::Shl, + Size::Dword, + Rax, + HALF_TO_SINGLE_FRACTION_SHIFT, + ); + asm.alu_accumulator_imm32(Alu::Add, Size::Dword, HALF_TO_SINGLE_BIAS as i32); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, HALF_SIGN as i32); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rcx, HALF_TO_SINGLE_SIGN_SHIFT); + asm.alu(Alu::Or, Size::Dword, Rax, Rcx); + asm.movd_to_xmm(SOURCE_VECTOR, Rax); } -fn scalar_odd_jam(code: &mut Vec) { +fn scalar_odd_jam(code: &mut Code) { // The source is a normal double and the result a normal single, so exactly // the low 29 fraction bits are discarded. - code.extend(MOVQ_RAX_XMM1); - code.push(AND_EAX_IMM32); - code.extend(DOUBLE_TO_SINGLE_DISCARDED_MASK.to_le_bytes()); - code.extend(SETNE_AL); - code.extend(MOVZX_EAX_AL); - code.extend(MOVD_XMM6_EAX); + let mut asm = code.asm(); + asm.movq_from_xmm(Rax, SOURCE_VECTOR); + asm.alu_accumulator_imm32( + Alu::And, + Size::Dword, + DOUBLE_TO_SINGLE_DISCARDED_MASK as i32, + ); + asm.setcc(Cond::Ne, Rax); + asm.movzx(Size::Dword, Rax, Size::Byte, Rax); + asm.movd_to_xmm(JAM_VECTOR, Rax); packed(code, Host::Or, RESULT_VECTOR, JAM_VECTOR); } -pub(in crate::x86_64) fn jam_odd_pair(code: &mut Vec, one_vector: u8) { +pub(in crate::x86_64) fn jam_odd_pair(code: &mut Code, one_vector: u8) { // The normal single widens exactly and is compared with its source double // lane without raising host status. A lane's sticky bit never comes from // the aggregate PE flag. The range preparation leaves 1 in every dword of // MINIMUM_EXPONENT_VECTOR. - code.extend(CVTPS2PD_XMM6_XMM0); - code.extend(CMPEQPD_XMM6_XMM1); + let mut asm = code.asm(); + asm.cvtps2pd(JAM_VECTOR, Rm::Xmm(RESULT_VECTOR)); + asm.float_compare( + FloatLanes::PackedDouble, + JAM_VECTOR, + Rm::Xmm(SOURCE_VECTOR), + COMPARE_EQUAL, + ); super::shuffle(code, JAM_VECTOR, JAM_VECTOR, COMPACT_QWORD_LOW_DWORDS); packed(code, Host::AndNot, JAM_VECTOR, one_vector); // PSHUFD duplicates masks into inactive upper lanes. Clear those masks so @@ -161,12 +140,12 @@ pub(in crate::x86_64) fn jam_odd_pair(code: &mut Vec, one_vector: u8) { packed(code, Host::Or, RESULT_VECTOR, JAM_VECTOR); } -fn vector_odd_jam(code: &mut Vec) { +fn vector_odd_jam(code: &mut Code) { jam_odd_pair(code, MINIMUM_EXPONENT_VECTOR); } fn emit_scalar( - code: &mut Vec, + code: &mut Code, operand: &PrecisionOperand, source: Format, destination: Format, @@ -182,9 +161,14 @@ fn emit_scalar( half_normal_guard(code, &mut helper); half_to_single(code); if destination == Format::Double { - code.extend(CVTSS2SD_XMM0_XMM1); + code.asm().cvtss2sd(RESULT_VECTOR, Rm::Xmm(SOURCE_VECTOR)); } else { - code.extend(MOVSS_XMM0_XMM1); + Host::MoveScalarSingle.register( + code, + RESULT_VECTOR, + SOURCE_VECTOR, + crate::TargetCpu::Baseline, + ); } } else { exponent_range(code, source, SOURCE_VECTOR, INPUT_MINIMUM_EXPONENT); @@ -192,7 +176,7 @@ fn emit_scalar( if destination == Format::Double { // Normal S→D is exact, unaffected by ambient RC/DAZ/FTZ/masks, // and raises neither Intel Invalid nor Denormal. Preserve MXCSR. - code.extend(CVTSS2SD_XMM0_XMM1); + code.asm().cvtss2sd(RESULT_VECTOR, Rm::Xmm(SOURCE_VECTOR)); } else { environment_round( code, @@ -202,7 +186,7 @@ fn emit_scalar( Rounding::Fpcr }, ); - code.extend(CVTSD2SS_XMM0_XMM1); + code.asm().cvtsd2ss(RESULT_VECTOR, Rm::Xmm(SOURCE_VECTOR)); restore_environment(code); helper.push(reject_other_status(code)); exponent_range(code, destination, RESULT_VECTOR, RESULT_MINIMUM_EXPONENT); @@ -219,7 +203,7 @@ fn emit_scalar( scalar_commit(code, operand.destination, destination); } -fn half_vector_guard(code: &mut Vec, helper: &mut Vec) { +fn half_vector_guard(code: &mut Code, helper: &mut Vec) { packed( code, Host::EqualDword, @@ -251,17 +235,17 @@ fn half_vector_guard(code: &mut Vec, helper: &mut Vec) { ); packed(code, Host::And, HALF_EXPONENT_VECTOR, HALF_VALIDITY_VECTOR); Host::DwordSignMask.register(code, 0, HALF_EXPONENT_VECTOR, crate::TargetCpu::Baseline); - code.extend(CMP_EAX_IMM8); - code.push(HALF_VALIDITY_MASK); + code.asm() + .alu_imm8(Alu::Cmp, Size::Dword, Rax, HALF_VALIDITY_MASK as i8); helper.push(branch(code, Condition::NotZero)); } -fn emit_widen_half(code: &mut Vec, operand: &PrecisionOperand, upper: bool, pc: GuestAddress) { +fn emit_widen_half(code: &mut Code, operand: &PrecisionOperand, upper: bool, pc: GuestAddress) { let mut helper = Vec::new(); exception_guard(code, &mut helper); read_vector(code, operand.source, SOURCE_VECTOR); if upper { - code.extend(PSRLDQ_XMM1_8); + ShiftOpcode::RightBytes.emit(code, SOURCE_VECTOR, UPPER_QWORD_BYTES); } packed(code, Host::Xor, RESULT_VECTOR, RESULT_VECTOR); packed(code, Host::UnpackLowWord, SOURCE_VECTOR, RESULT_VECTOR); @@ -287,23 +271,23 @@ fn emit_widen_half(code: &mut Vec, operand: &PrecisionOperand, upper: bool, commit(code, operand.destination, RESULT_VECTOR); } -fn emit_widen(code: &mut Vec, operand: &PrecisionOperand, upper: bool, pc: GuestAddress) { +fn emit_widen(code: &mut Code, operand: &PrecisionOperand, upper: bool, pc: GuestAddress) { let mut helper = Vec::new(); exception_guard(code, &mut helper); read_vector(code, operand.source, SOURCE_VECTOR); if upper { - code.extend(PSRLDQ_XMM1_8); + ShiftOpcode::RightBytes.emit(code, SOURCE_VECTOR, UPPER_QWORD_BYTES); } prepare_vector_input_range(code, Format::Single); vector_exponent_range(code, Format::Single, Shape::Vector64, SOURCE_VECTOR); helper.push(branch(code, Condition::NotZero)); - code.extend(CVTPS2PD_XMM0_XMM1); + code.asm().cvtps2pd(RESULT_VECTOR, Rm::Xmm(SOURCE_VECTOR)); helper_section(code, &helper, pc); commit(code, operand.destination, RESULT_VECTOR); } fn emit_narrow( - code: &mut Vec, + code: &mut Code, operand: &PrecisionOperand, upper: bool, rounding: PrecisionRounding, @@ -323,7 +307,7 @@ fn emit_narrow( Rounding::Fpcr }, ); - code.extend(CVTPD2PS_XMM0_XMM1); + code.asm().cvtpd2ps(RESULT_VECTOR, Rm::Xmm(SOURCE_VECTOR)); restore_environment(code); helper.push(reject_other_status(code)); // Conversion changes both element size and lane count. Rebuild the bounds @@ -339,14 +323,14 @@ fn emit_narrow( commit_inexact(code); if upper { read_vector(code, operand.destination, SOURCE_VECTOR); - code.extend(MOVLHPS_XMM1_XMM0); + code.asm().movlhps(SOURCE_VECTOR, Rm::Xmm(RESULT_VECTOR)); commit(code, operand.destination, SOURCE_VECTOR); } else { commit(code, operand.destination, RESULT_VECTOR); } } -pub(in crate::x86_64) fn emit(code: &mut Vec, operand: &PrecisionOperand, pc: GuestAddress) { +pub(in crate::x86_64) fn emit(code: &mut Code, operand: &PrecisionOperand, pc: GuestAddress) { match operand.mode { PrecisionMode::Scalar { source, diff --git a/crates/stela-compiler/src/x86_64/simd/products.rs b/crates/stela-compiler/src/x86_64/simd/products.rs index fa1c0e1b89..05a491a1b9 100644 --- a/crates/stela-compiler/src/x86_64/simd/products.rs +++ b/crates/stela-compiler/src/x86_64/simd/products.rs @@ -1,28 +1,16 @@ //! Integer multiplies, widening arithmetic and absolute differences. -use super::{Host, commit, greater, packed, read_vector, rearrange::constant, shuffle}; +use super::rearrange::{add_or_subtract, lane_constant}; +use super::{Host, commit, greater, packed, packed_imm, read_vector, rearrange::constant, shuffle}; +use crate::x86_64::asm::{Code, Cond, Gpr, Size, resolve}; use crate::{ TargetCpu, aarch64::simd::products::{Accumulate, Kind, Operand}, x86_64::isa::ShiftOpcode as Shift, }; -use alloc::vec::Vec; -fn arithmetic(lane: u8, subtract: bool) -> Host { - match (subtract, lane) { - (false, 1) => Host::AddByte, - (false, 2) => Host::AddWord, - (false, 4) => Host::AddDword, - (false, 8) => Host::AddQword, - (true, 1) => Host::SubByte, - (true, 2) => Host::SubWord, - (true, 4) => Host::SubDword, - (true, 8) => Host::SubQword, - _ => unreachable!("reviewed lane size"), - } -} /// Extend the selected 64-bit input half into doubled-width lanes. XMM3 is the /// extension mask; extending one operand never changes the other in XMM0/1. -pub(super) fn extend(code: &mut Vec, xmm: u8, lane: u8, upper: bool, signed: bool) { +pub(super) fn extend(code: &mut Code, xmm: u8, lane: u8, upper: bool, signed: bool) { if upper { Shift::RightBytes.emit(code, xmm, 8); } @@ -52,7 +40,7 @@ pub(super) fn extend(code: &mut Vec, xmm: u8, lane: u8, upper: bool, signed: 3, ); } -fn low_product(code: &mut Vec, lane: u8, target: TargetCpu) { +fn low_product(code: &mut Code, lane: u8, target: TargetCpu) { match lane { 1 => { // Multiply even and odd bytes separately in 16-bit lanes, then mask @@ -92,7 +80,7 @@ fn low_product(code: &mut Vec, lane: u8, target: TargetCpu) { _ => unreachable!("allocated product lane size"), } } -fn long_product(code: &mut Vec, lane: u8, signed: bool, target: TargetCpu) { +fn long_product(code: &mut Code, lane: u8, signed: bool, target: TargetCpu) { if lane < 4 { low_product(code, lane * 2, target); return; @@ -119,20 +107,20 @@ fn long_product(code: &mut Vec, lane: u8, signed: bool, target: TargetCpu) { packed(code, Host::MultiplyUnsignedDword, 0, 1); } } -fn accumulate(code: &mut Vec, destination: u8, lane: u8, operation: Accumulate) -> u8 { +fn accumulate(code: &mut Code, destination: u8, lane: u8, operation: Accumulate) -> u8 { if operation == Accumulate::None { return 0; } read_vector(code, destination, 1); if operation == Accumulate::Subtract { - packed(code, arithmetic(lane, true), 1, 0); + packed(code, add_or_subtract(lane, true), 1, 0); 1 } else { - packed(code, arithmetic(lane, false), 0, 1); + packed(code, add_or_subtract(lane, false), 0, 1); 0 } } -fn absolute_difference(code: &mut Vec, lane: u8, signed: bool, target: TargetCpu) { +fn absolute_difference(code: &mut Code, lane: u8, signed: bool, target: TargetCpu) { if lane <= 2 { if signed { let bits = (1u64 << (lane * 8 - 1)).to_le_bytes(); @@ -155,31 +143,23 @@ fn absolute_difference(code: &mut Vec, lane: u8, signed: bool, target: Targe packed(code, Host::Or, 0, 1); } else { packed(code, Host::MoveAligned, 5, 0); - packed(code, arithmetic(lane, true), 5, 1); + packed(code, add_or_subtract(lane, true), 5, 1); // Keep the wrapped difference in XMM5 while comparison uses XMM0..4. // Ordering decides the direction of subtraction before interpreting ABS. greater(code, lane, !signed, target); packed(code, Host::EqualDword, 1, 1); packed(code, Host::Xor, 0, 1); packed(code, Host::Xor, 5, 0); - packed(code, arithmetic(lane, true), 5, 0); + packed(code, add_or_subtract(lane, true), 5, 0); packed(code, Host::MoveAligned, 0, 5); } } -fn lane_constant(code: &mut Vec, xmm: u8, lane: u8, value: u64) { - let bytes = value.to_le_bytes(); - constant( - code, - xmm, - core::array::from_fn(|i| bytes[i % usize::from(lane)]), - ); -} -fn indexed(code: &mut Vec, lane: u8, index: u8) { +fn indexed(code: &mut Code, lane: u8, index: u8) { if lane == 2 { // Halfword shuffles leave the other 64-bit half unchanged. Broadcast // one repeated dword from the selected half to complete all eight lanes. - packed( + packed_imm( code, if index < 4 { Host::ShuffleLowWord @@ -188,8 +168,8 @@ fn indexed(code: &mut Vec, lane: u8, index: u8) { }, 1, 1, + (index % 4) * 0x55, ); - code.push((index % 4) * 0x55); shuffle(code, 1, 1, if index < 4 { 0 } else { 0xaa }); } else { // Select and broadcast the dword in one shuffle. @@ -199,13 +179,7 @@ fn indexed(code: &mut Vec, lane: u8, index: u8) { /// Indexed long products have a uniform right operand; avoid materializing /// widened input lanes which the native multiply does not consume. -fn indexed_long_product( - code: &mut Vec, - lane: u8, - upper: bool, - signed: bool, - target: TargetCpu, -) { +fn indexed_long_product(code: &mut Code, lane: u8, upper: bool, signed: bool, target: TargetCpu) { if lane == 2 && !upper && target >= TargetCpu::Sse41 { let extension = if signed { Host::SignExtendWordToDword @@ -244,7 +218,7 @@ fn indexed_long_product( } } -fn indexed_low_product(code: &mut Vec, lane: u8, bytes: u8, target: TargetCpu) { +fn indexed_low_product(code: &mut Code, lane: u8, bytes: u8, target: TargetCpu) { if lane != 4 || target >= TargetCpu::Sse41 { low_product(code, lane, target); } else if bytes == 8 { @@ -266,7 +240,7 @@ fn indexed_low_product(code: &mut Vec, lane: u8, bytes: u8, target: TargetCp /// Even/odd byte products form two exact PMADDWD pair sums per dword. Their /// sum is the four-byte dot product, with no saturating intermediate operation. -fn dot(code: &mut Vec, operand: &Operand, signed: bool) { +fn dot(code: &mut Code, operand: &Operand, signed: bool) { const BYTE_BITS: u8 = 8; const LOW_BYTE_MASK: u64 = 0x00ff; if let Some(index) = operand.index { @@ -299,7 +273,7 @@ fn dot(code: &mut Vec, operand: &Operand, signed: bool) { /// Clamp the doubled-width sums once, after the rounded product is added to the /// accumulator. XMM6 survives for assembling the halves. -fn clamp_rounded_accumulate(code: &mut Vec, lane: u8, active: u8) { +fn clamp_rounded_accumulate(code: &mut Code, lane: u8, active: u8) { packed(code, Host::MoveAligned, 5, 0); if lane == 2 { packed(code, Host::PackSignedDwordToWord, 0, 0); @@ -341,7 +315,7 @@ fn clamp_rounded_accumulate(code: &mut Vec, lane: u8, active: u8) { /// acc + floor((+/- a*b + 2^(n-2))/2^(n-1)). The latter needs only /// signed2n intermediates and preserves MIN*MIN cancellation and subtract ties. fn rounded_accumulate_half( - code: &mut Vec, + code: &mut Code, operand: &Operand, upper: bool, active: u8, @@ -388,11 +362,11 @@ fn rounded_accumulate_half( } if subtract { packed(code, Host::Xor, 1, 1); - packed(code, arithmetic(lane * 2, true), 1, 0); + packed(code, add_or_subtract(lane * 2, true), 1, 0); packed(code, Host::MoveAligned, 0, 1); } lane_constant(code, 1, lane * 2, 1u64 << (bits - 2)); - packed(code, arithmetic(lane * 2, false), 0, 1); + packed(code, add_or_subtract(lane * 2, false), 0, 1); if lane == 2 { Shift::ArithmeticDword.emit(code, 0, bits - 1); } else { @@ -406,11 +380,11 @@ fn rounded_accumulate_half( packed(code, Host::MoveAligned, 5, 0); read_vector(code, operand.destination, 0); extend(code, 0, lane, upper, true); - packed(code, arithmetic(lane * 2, false), 0, 5); + packed(code, add_or_subtract(lane * 2, false), 0, 5); clamp_rounded_accumulate(code, lane, active); } -fn rounded_accumulate(code: &mut Vec, operand: &Operand, subtract: bool, target: TargetCpu) { +fn rounded_accumulate(code: &mut Code, operand: &Operand, subtract: bool, target: TargetCpu) { const SOURCE_HALF_BYTES: u8 = 8; rounded_accumulate_half( code, @@ -429,7 +403,7 @@ fn rounded_accumulate(code: &mut Vec, operand: &Operand, subtract: bool, tar } /// Full-width 16-bit high products need no widening or per-half processing. /// PMULHRSW shares Arm's ties-up rounding but wraps MIN*MIN instead of clamping. -fn high_product_words(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn high_product_words(code: &mut Code, operand: &Operand, target: TargetCpu) { let Kind::Doubling { rounding, .. } = operand.kind else { unreachable!() }; @@ -467,7 +441,7 @@ fn high_product_words(code: &mut Vec, operand: &Operand, target: TargetCpu) super::saturating::publish_qc(code, operand.bytes); } /// One selected 64-bit half -> a low 64-bit high-product result. XMM6 survives. -fn high_product(code: &mut Vec, operand: &Operand, upper: bool, active: u8, target: TargetCpu) { +fn high_product(code: &mut Code, operand: &Operand, upper: bool, active: u8, target: TargetCpu) { let Kind::Doubling { rounding, .. } = operand.kind else { unreachable!() }; @@ -483,7 +457,7 @@ fn high_product(code: &mut Vec, operand: &Operand, upper: bool, active: u8, // Compute (product + 2^(n-2)) >> (n-1), avoiding a doubled-product overflow. if rounding { lane_constant(code, 1, lane * 2, 1u64 << (lane * 8 - 2)); - packed(code, arithmetic(lane * 2, false), 0, 1); + packed(code, add_or_subtract(lane * 2, false), 0, 1); } if lane == 2 { Shift::ArithmeticDword.emit(code, 0, 15); @@ -497,7 +471,7 @@ fn high_product(code: &mut Vec, operand: &Operand, upper: bool, active: u8, shuffle(code, 3, 4, 0xb1); packed(code, Host::And, 4, 3); } - packed(code, arithmetic(lane * 2, false), 0, 4); + packed(code, add_or_subtract(lane * 2, false), 0, 4); super::saturating::publish_qc(code, active * 2); if lane == 2 { packed(code, Host::PackSignedDwordToWord, 0, 0); @@ -505,7 +479,7 @@ fn high_product(code: &mut Vec, operand: &Operand, upper: bool, active: u8, shuffle(code, 0, 0, 0x88); } } -fn doubling(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn doubling(code: &mut Code, operand: &Operand, target: TargetCpu) { let Kind::Doubling { high, accumulate, .. } = operand.kind @@ -547,12 +521,17 @@ fn doubling(code: &mut Vec, operand: &Operand, target: TargetCpu) { } } } -fn polynomial(code: &mut Vec, lane: u8, widen: bool, upper: bool, target: TargetCpu) { +fn polynomial(code: &mut Code, lane: u8, widen: bool, upper: bool, target: TargetCpu) { if lane == 8 { if target.supports(TargetCpu::Pclmulqdq) { - Host::CarrylessMultiplyQword.register(code, 0, 1, target); // Immediate bit 0 selects the left half; bit 4 selects the right. - code.push(if upper { 0x11 } else { 0x00 }); + Host::CarrylessMultiplyQword.register_imm( + code, + 0, + 1, + if upper { 0x11 } else { 0x00 }, + target, + ); return; } if upper { @@ -565,7 +544,7 @@ fn polynomial(code: &mut Vec, lane: u8, widen: bool, upper: bool, target: Ta lane_constant(code, 4, 8, 1); // A counted loop bounds native code size; this register-only operation // has no intermediate guest fault or precise-entry boundary. - code.extend([0x41, 0xba, 64, 0, 0, 0]); // mov r10d,64 + code.asm().mov_imm32(Gpr::R10, 64); let loop_start = code.len(); { packed(code, Host::MoveAligned, 2, 4); @@ -583,11 +562,10 @@ fn polynomial(code: &mut Vec, lane: u8, widen: bool, upper: bool, target: Ta packed(code, Host::Or, 0, 3); Shift::RightQword.emit(code, 1, 1); } - code.extend([0x41, 0xff, 0xca]); // dec r10d - code.extend([0x0f, 0x85]); // jnz loop_start - let displacement = i32::try_from(loop_start as isize - (code.len() + 4) as isize) - .expect("bounded polynomial loop"); - code.extend(displacement.to_le_bytes()); + let mut asm = code.asm(); + asm.dec(Size::Dword, Gpr::R10); + let repeat = asm.jcc(Cond::Ne); + resolve(code, repeat, loop_start); } else { let output_lane = if widen { 2 } else { 1 }; if widen { @@ -626,7 +604,7 @@ fn polynomial(code: &mut Vec, lane: u8, widen: bool, upper: bool, target: Ta packed(code, Host::MoveAligned, 0, 5); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { let Operand { kind, destination, @@ -687,7 +665,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { extend(code, 0, lane, upper, signed); } extend(code, 1, lane, upper, signed); - packed(code, arithmetic(lane * 2, subtract), 0, 1); + packed(code, add_or_subtract(lane * 2, subtract), 0, 1); } Kind::Difference { signed, @@ -722,7 +700,6 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; #[test] fn dot_products_use_exact_unsaturated_pairs_on_every_target() { @@ -731,7 +708,7 @@ mod tests { .unwrap() .unwrap(); for target in [TargetCpu::Baseline, TargetCpu::Ssse3, TargetCpu::Sse41] { - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, target); let count = |opcode: Host| { code.windows(opcode.encoding().len()) @@ -756,7 +733,7 @@ mod tests { .unwrap() .unwrap(); for target in [TargetCpu::Baseline, TargetCpu::Sse41] { - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, target); let count = |opcode: Host| { code.windows(opcode.encoding().len()) @@ -802,7 +779,7 @@ mod tests { .unwrap() .unwrap(); for target in [TargetCpu::Baseline, TargetCpu::Sse41] { - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, target); let has = |opcode: Host| { code.windows(opcode.encoding().len()) @@ -857,7 +834,7 @@ mod tests { .unwrap() .unwrap(); for target in [TargetCpu::Baseline, TargetCpu::Ssse3, TargetCpu::Pclmulqdq] { - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, target); let has = |opcode: Host| { code.windows(opcode.encoding().len()) diff --git a/crates/stela-compiler/src/x86_64/simd/rearrange.rs b/crates/stela-compiler/src/x86_64/simd/rearrange.rs index cb49a13686..799adb1fd9 100644 --- a/crates/stela-compiler/src/x86_64/simd/rearrange.rs +++ b/crates/stela-compiler/src/x86_64/simd/rearrange.rs @@ -1,26 +1,53 @@ //! Lane moves and permutes. All inputs are read before the destination is written. use super::{Host, commit, packed, read_vector, vector_offset}; +use crate::x86_64::asm::{Alu, Code, Cond, Disp, Gpr, Mem, ShiftOp, Size}; +use crate::x86_64::simd::encode::guest; use crate::{ TargetCpu, aarch64::simd::rearrange::{LaneSource, Operand}, }; -use alloc::vec::Vec; +use Gpr::{R8, Rax, Rcx, Rdi, Rdx}; -pub(super) fn constant(code: &mut Vec, xmm: u8, bytes: [u8; 16]) { +pub(super) fn constant(code: &mut Code, xmm: u8, bytes: [u8; 16]) { // MOVQ from a GPR followed by PUNPCKLQDQ avoids constant-pool relocations. for (register, limb) in [(xmm, &bytes[..8]), (7, &bytes[8..])] { - code.extend([0x48, 0xb9]); // movabs rcx,imm64 - code.extend(limb); + let limb = u64::from_le_bytes(limb.try_into().expect("an eight-byte limb")); + code.asm().mov_imm64(Rcx, limb); packed(code, Host::MoveGprQword, register, 1); } packed(code, Host::UnpackLowQword, xmm, 7); } -fn load_lane(code: &mut Vec, source: LaneSource, bytes: u8) { +/// Load `value` repeated in each `lane`-byte lane of `xmm` (clobbers RCX and XMM7). +pub(super) fn lane_constant(code: &mut Code, xmm: u8, lane: u8, value: u64) { + let bytes = value.to_le_bytes(); + constant( + code, + xmm, + core::array::from_fn(|i| bytes[i % usize::from(lane)]), + ); +} + +/// Packed ADD or SUB for `lane`-byte lanes. +pub(super) fn add_or_subtract(lane: u8, subtract: bool) -> Host { + match (subtract, lane) { + (false, 1) => Host::AddByte, + (false, 2) => Host::AddWord, + (false, 4) => Host::AddDword, + (false, 8) => Host::AddQword, + (true, 1) => Host::SubByte, + (true, 2) => Host::SubWord, + (true, 4) => Host::SubDword, + (true, 8) => Host::SubQword, + _ => unreachable!("lane of 1, 2, 4 or 8 bytes"), + } +} + +fn load_lane(code: &mut Code, source: LaneSource, bytes: u8) { use crate::aarch64::Register; let offset = match source { LaneSource::General(Register::Zero) => { - code.extend([0x31, 0xc0]); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); return; } LaneSource::General(Register::X(index)) => u32::from(index) * 8, @@ -28,27 +55,20 @@ fn load_lane(code: &mut Vec, source: LaneSource, bytes: u8) { LaneSource::General(Register::Sp) => unreachable!("lane transfers use ZR, not SP"), }; // Zero-extending load of the exact width into RAX, from GuestState. + let mut asm = code.asm(); match bytes { - 1 => code.extend([0x0f, 0xb6, 0x87]), - 2 => code.extend([0x0f, 0xb7, 0x87]), - 4 => code.extend([0x8b, 0x87]), - 8 => code.extend([0x48, 0x8b, 0x87]), + 1 => asm.movzx(Size::Dword, Rax, Size::Byte, guest(offset)), + 2 => asm.movzx(Size::Dword, Rax, Size::Word, guest(offset)), + 4 => asm.mov_load(Size::Dword, Rax, guest(offset)), + 8 => asm.mov_load(Size::Qword, Rax, guest(offset)), _ => unreachable!("reviewed lane size"), } - code.extend(offset.to_le_bytes()); } -/// MOVD EAX,XMM0 and MOVQ RAX,XMM0. -const MOVD_EAX_XMM0: [u8; 4] = [0x66, 0x0f, 0x7e, 0xc0]; -const MOVQ_RAX_XMM0: [u8; 5] = [0x66, 0x48, 0x0f, 0x7e, 0xc0]; -/// MOVZX EAX,AL and MOVZX EAX,AX. -const MOVZX_EAX_AL: [u8; 3] = [0x0f, 0xb6, 0xc0]; -const MOVZX_EAX_AX: [u8; 3] = [0x0f, 0xb7, 0xc0]; - /// UMOV, SMOV and FMOV to a general register ([`Operand::Extract`]), /// which ends with the destination's store from RAX. With `held`, XMM0 /// holds the source vector whole and the lane is its lowest. -pub(super) fn extract(code: &mut Vec, operand: &Operand, held: bool) { +pub(super) fn extract(code: &mut Code, operand: &Operand, held: bool) { let Operand::Extract { destination, source, @@ -62,14 +82,15 @@ pub(super) fn extract(code: &mut Vec, operand: &Operand, held: bool) { }; if held { debug_assert_eq!(byte, 0); + let mut asm = code.asm(); match lane_bytes { - 1 | 2 | 4 => code.extend(MOVD_EAX_XMM0), - 8 => code.extend(MOVQ_RAX_XMM0), + 1 | 2 | 4 => asm.movd_from_xmm(Rax, 0), + 8 => asm.movq_from_xmm(Rax, 0), _ => unreachable!("reviewed lane size"), } match lane_bytes { - 1 => code.extend(MOVZX_EAX_AL), - 2 => code.extend(MOVZX_EAX_AX), + 1 => asm.movzx(Size::Dword, Rax, Size::Byte, Rax), + 2 => asm.movzx(Size::Dword, Rax, Size::Word, Rax), _ => {} } } else { @@ -84,29 +105,36 @@ pub(super) fn extract(code: &mut Vec, operand: &Operand, held: bool) { } if signed { let shift = 64 - lane_bytes * 8; - code.extend([0x48, 0xc1, 0xe0, shift, 0x48, 0xc1, 0xf8, shift]); // shl/sar rax for sign extension + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shl, Size::Qword, Rax, shift); + asm.shift_imm(ShiftOp::Sar, Size::Qword, Rax, shift); if !x64 { - code.extend([0x89, 0xc0]); // W writes clear X high half + // W writes clear X high half. + asm.mov(Size::Dword, Rax, Rax); } } // An unsigned lane of at most four bytes is zero-extended already. super::super::store(code, destination); } -fn insert_lane(code: &mut Vec, destination: u8, byte: u8, bytes: u8) { +fn insert_lane(code: &mut Code, destination: u8, byte: u8, bytes: u8) { // Only the selected lane changes; even scalar-size INS preserves all others. - match bytes { - 1 => code.extend([0x88, 0x87]), - 2 => code.extend([0x66, 0x89, 0x87]), - 4 => code.extend([0x89, 0x87]), - 8 => code.extend([0x48, 0x89, 0x87]), + let size = match bytes { + 1 => Size::Byte, + 2 => Size::Word, + 4 => Size::Dword, + 8 => Size::Qword, _ => unreachable!("reviewed lane size"), - } - code.extend((vector_offset(destination) + u32::from(byte)).to_le_bytes()); + }; + code.asm().mov_store( + size, + guest(vector_offset(destination) + u32::from(byte)), + Rax, + ); } fn permutation( - code: &mut Vec, + code: &mut Code, destination: u8, left: u8, right: u8, @@ -133,45 +161,49 @@ fn permutation( } // Scalar byte gather fallback. RAX/RDX accumulate both halves before stores; // RCX is the zero-extended byte scratch. No guest RAM or host stack accesses. - code.extend([0x31, 0xc0, 0x31, 0xd2]); + clear_halves(code); for (output, input) in selection.into_iter().enumerate() { if input == 255 { continue; } let vector = if input < 16 { left } else { right }; - code.extend([0x0f, 0xb6, 0x8f]); // movzx ecx,byte [rdi+disp32] - code.extend((vector_offset(vector) + u32::from(input % 16)).to_le_bytes()); + code.asm().movzx( + Size::Dword, + Rcx, + Size::Byte, + guest(vector_offset(vector) + u32::from(input % 16)), + ); accumulate_byte(code, output, false); } commit_halves(code, destination); } -fn accumulate_byte(code: &mut Vec, output: usize, r8: bool) { - let shift = (output % 8 * 8) as u8; - if shift != 0 { - code.extend(if r8 { - [0x49, 0xc1, 0xe0, shift] - } else { - [0x48, 0xc1, 0xe1, shift] - }); // shl r8/rcx,imm8 - } - code.extend(match (r8, output < 8) { - (false, true) => [0x48, 0x09, 0xc8], // or rax,rcx - (false, false) => [0x48, 0x09, 0xca], // or rdx,rcx - (true, true) => [0x4c, 0x09, 0xc0], // or rax,r8 - (true, false) => [0x4c, 0x09, 0xc2], // or rdx,r8 - }); +/// Clear RAX and RDX, the low and high halves of a gathered vector. +fn clear_halves(code: &mut Code) { + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); + asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); } -fn commit_halves(code: &mut Vec, destination: u8) { - code.extend([0x48, 0x89, 0x87]); // mov [rdi+disp32],rax - code.extend(vector_offset(destination).to_le_bytes()); - code.extend([0x48, 0x89, 0x97]); // mov [rdi+disp32+8],rdx - code.extend((vector_offset(destination) + 8).to_le_bytes()); + +fn accumulate_byte(code: &mut Code, output: usize, r8: bool) { + let shift = (output % 8 * 8) as u8; + let byte = if r8 { R8 } else { Rcx }; + let mut asm = code.asm(); + if shift != 0 { + asm.shift_imm(ShiftOp::Shl, Size::Qword, byte, shift); + } + let half = if output < 8 { Rax } else { Rdx }; + asm.alu(Alu::Or, Size::Qword, half, byte); +} +fn commit_halves(code: &mut Code, destination: u8) { + let mut asm = code.asm(); + asm.mov_store(Size::Qword, guest(vector_offset(destination)), Rax); + asm.mov_store(Size::Qword, guest(vector_offset(destination) + 8), Rdx); } #[allow(clippy::too_many_arguments)] fn table( - code: &mut Vec, + code: &mut Code, destination: u8, first: u8, registers: u8, @@ -207,33 +239,44 @@ fn table( commit(code, destination, 0); return; } - code.extend([0x31, 0xc0, 0x31, 0xd2]); + clear_halves(code); for output in 0..bytes { + let mut asm = code.asm(); if preserve { - code.extend([0x44, 0x0f, 0xb6, 0x87]); // movzx r8d,old destination byte - code.extend((vector_offset(destination) + u32::from(output)).to_le_bytes()); + // The old destination byte. + asm.movzx( + Size::Dword, + R8, + Size::Byte, + guest(vector_offset(destination) + u32::from(output)), + ); } else { - code.extend([0x45, 0x31, 0xc0]); + asm.alu(Alu::Xor, Size::Dword, R8, R8); } - code.extend([0x0f, 0xb6, 0x8f]); // movzx ecx,index byte - code.extend((vector_offset(indices) + u32::from(output)).to_le_bytes()); - code.extend([0x83, 0xf9, registers * 16, 0x0f, 0x83]); // cmp ecx,bound; jae fallback - let fixup = code.len(); - code.extend([0; 4]); - code.extend([0x81, 0xc1]); // add ecx,first register byte offset - code.extend((u32::from(first) * 16).to_le_bytes()); - code.extend([0x81, 0xe1]); // and ecx,511: vector bank wraps at V31 - code.extend((32u32 * 16 - 1).to_le_bytes()); - code.extend([0x44, 0x0f, 0xb6, 0x84, 0x0f]); // movzx r8d,[rdi+rcx+V0] - code.extend(vector_offset(0).to_le_bytes()); - let distance = (code.len() - fixup - 4) as u32; - code[fixup..fixup + 4].copy_from_slice(&distance.to_le_bytes()); + asm.movzx( + Size::Dword, + Rcx, + Size::Byte, + guest(vector_offset(indices) + u32::from(output)), + ); + asm.alu_imm8(Alu::Cmp, Size::Dword, Rcx, (registers * 16) as i8); + let fallback = asm.jcc(Cond::Ae); + // The first register's byte offset; the vector bank wraps at V31. + asm.alu_imm32(Alu::Add, Size::Dword, Rcx, i32::from(first) * 16); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, 32 * 16 - 1); + asm.movzx( + Size::Dword, + R8, + Size::Byte, + Mem::indexed(Rdi, Rcx, 1, vector_offset(0) as i32).with_width(Disp::Dword), + ); + asm.bind(fallback); accumulate_byte(code, usize::from(output), true); } commit_halves(code, destination); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { match *operand { Operand::Duplicate { destination, diff --git a/crates/stela-compiler/src/x86_64/simd/reductions.rs b/crates/stela-compiler/src/x86_64/simd/reductions.rs index e91d95f2ab..05e77ec214 100644 --- a/crates/stela-compiler/src/x86_64/simd/reductions.rs +++ b/crates/stela-compiler/src/x86_64/simd/reductions.rs @@ -1,13 +1,14 @@ //! Integer pairwise combines, across-lane reductions and bit counts. +use super::rearrange::lane_constant; use super::{ Host, commit, packed, read_vector, rearrange::constant, shifts::logical_shift, shuffle, }; +use crate::x86_64::asm::Code; use crate::{ TargetCpu, aarch64::simd::reductions::{BitCount, Combine, Kind, Operand, Shape}, x86_64::isa::ShiftOpcode as Shift, }; -use alloc::vec::Vec; fn add_opcode(lane: u8) -> Host { match lane { @@ -34,15 +35,7 @@ fn equal_opcode(lane: u8) -> Host { _ => unreachable!(), } } -fn lane_constant(code: &mut Vec, xmm: u8, lane: u8, value: u64) { - let bytes = value.to_le_bytes(); - constant( - code, - xmm, - core::array::from_fn(|i| bytes[i % usize::from(lane)]), - ); -} -fn select_minmax(code: &mut Vec, lane: u8, signed: bool, maximum: bool, target: TargetCpu) { +fn select_minmax(code: &mut Code, lane: u8, signed: bool, maximum: bool, target: TargetCpu) { let native = match (signed, maximum, lane) { (false, false, 1) => Host::MinUnsignedByte, (false, true, 1) => Host::MaxUnsignedByte, @@ -79,7 +72,7 @@ fn select_minmax(code: &mut Vec, lane: u8, signed: bool, maximum: bool, targ packed(code, Host::And, 0, 2); packed(code, Host::Xor, 0, 1); } -fn combine(code: &mut Vec, operation: Combine, lane: u8, target: TargetCpu) { +fn combine(code: &mut Code, operation: Combine, lane: u8, target: TargetCpu) { match operation { Combine::Add | Combine::LongAdd { .. } => packed(code, add_opcode(lane), 0, 1), Combine::Minimum { signed } => select_minmax(code, lane, signed, false, target), @@ -89,7 +82,7 @@ fn combine(code: &mut Vec, operation: Combine, lane: u8, target: TargetCpu) /// Produce adjacent even or odd lanes from XMM2/XMM3, respecting active width. /// XMM6 preserves the first selection while the second uses XMM0/XMM4/XMM5/7. -fn pair_selection(code: &mut Vec, lane: u8, bytes: u8, odd: bool) { +fn pair_selection(code: &mut Code, lane: u8, bytes: u8, odd: bool) { packed(code, Host::MoveAligned, 0, 2); packed(code, Host::MoveAligned, 4, 3); match lane { @@ -147,7 +140,7 @@ fn pair_selection(code: &mut Vec, lane: u8, bytes: u8, odd: bool) { _ => unreachable!("allocated pair lane"), } } -fn pair_operands(code: &mut Vec, operand: &Operand) { +fn pair_operands(code: &mut Code, operand: &Operand) { read_vector(code, operand.left, 2); read_vector(code, operand.right, 3); pair_selection(code, operand.lane_bytes, operand.bytes, false); @@ -157,7 +150,7 @@ fn pair_operands(code: &mut Vec, operand: &Operand) { packed(code, Host::MoveAligned, 0, 6); } -fn long_sum_inputs(code: &mut Vec, lane: u8, bytes: u8, signed: bool) { +fn long_sum_inputs(code: &mut Code, lane: u8, bytes: u8, signed: bool) { packed(code, Host::Xor, 1, 1); if signed { packed(code, compare_opcode(lane), 1, 0); @@ -195,13 +188,7 @@ fn long_sum_inputs(code: &mut Vec, lane: u8, bytes: u8, signed: bool) { /// the minimum of eight unsigned words, into its low word; the bits above /// the result lane are left for the caller to clear. A maximum is the /// complement of the minimum of the complements. -fn unsigned_word_extremum( - code: &mut Vec, - maximum: bool, - lane: u8, - bytes: u8, - target: TargetCpu, -) { +fn unsigned_word_extremum(code: &mut Code, maximum: bool, lane: u8, bytes: u8, target: TargetCpu) { const ONES: u8 = 1; const SCRATCH: u8 = 2; if maximum { @@ -231,7 +218,7 @@ fn unsigned_word_extremum( } } -fn across(code: &mut Vec, operation: Combine, mut lane: u8, mut bytes: u8, target: TargetCpu) { +fn across(code: &mut Code, operation: Combine, mut lane: u8, mut bytes: u8, target: TargetCpu) { if let Combine::LongAdd { signed } = operation { long_sum_inputs(code, lane, bytes, signed); lane *= 2; @@ -265,7 +252,7 @@ fn across(code: &mut Vec, operation: Combine, mut lane: u8, mut bytes: u8, t /// The bytes of an XMM register. const VECTOR_BYTES: u8 = 16; -fn nibble_lookup(code: &mut Vec, reverse: bool, target: TargetCpu) { +fn nibble_lookup(code: &mut Code, reverse: bool, target: TargetCpu) { let table = core::array::from_fn(|i| { if reverse { (i as u8).reverse_bits() >> 4 @@ -290,7 +277,7 @@ fn nibble_lookup(code: &mut Vec, reverse: bool, target: TargetCpu) { } packed(code, Host::MoveAligned, 0, 2); } -fn bit_population(code: &mut Vec, target: TargetCpu) { +fn bit_population(code: &mut Code, target: TargetCpu) { if target >= TargetCpu::Ssse3 { nibble_lookup(code, false, target); return; @@ -312,7 +299,7 @@ fn bit_population(code: &mut Vec, target: TargetCpu) { constant(code, 2, [15; 16]); packed(code, Host::And, 0, 2); } -fn bit_reverse(code: &mut Vec, target: TargetCpu) { +fn bit_reverse(code: &mut Code, target: TargetCpu) { if target >= TargetCpu::Ssse3 { nibble_lookup(code, true, target); return; @@ -327,7 +314,7 @@ fn bit_reverse(code: &mut Vec, target: TargetCpu) { packed(code, Host::Or, 0, 1); } } -fn leading_count(code: &mut Vec, lane: u8, sign: bool) { +fn leading_count(code: &mut Code, lane: u8, sign: bool) { if sign { packed(code, Host::Xor, 1, 1); packed(code, compare_opcode(lane), 1, 0); @@ -370,7 +357,7 @@ fn leading_count(code: &mut Vec, lane: u8, sign: bool) { packed(code, Host::MoveAligned, 0, 2); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { let Operand { kind, destination, @@ -430,7 +417,6 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { mod tests { use super::*; use crate::GuestState; - use alloc::vec; /// UMINV and UMAXV of bytes and halfwords, both widths, run on the host /// for each target tier and agree with Arm's definition: the extremum @@ -455,7 +441,6 @@ mod tests { #[cfg(target_os = "linux")] const MAP_ANONYMOUS: i32 = 0x20; const PAGE: usize = 4096; - const RET: u8 = 0xc3; const SOURCE: u8 = 1; const DESTINATION: u8 = 2; fn run(code: &[u8], state: &mut GuestState) { @@ -497,9 +482,9 @@ mod tests { bytes, lane_bytes, }; - let mut code = vec![]; + let mut code = Code::new(); emit(&mut code, &operand, target); - code.push(RET); + code.asm().ret(); for sample in 0..256 { // Edge vectors: all zeros, all ones and lone extrema. let value = match sample { diff --git a/crates/stela-compiler/src/x86_64/simd/refinement.rs b/crates/stela-compiler/src/x86_64/simd/refinement.rs index b3ba25c241..41f0b2a3f7 100644 --- a/crates/stela-compiler/src/x86_64/simd/refinement.rs +++ b/crates/stela-compiler/src/x86_64/simd/refinement.rs @@ -1,14 +1,16 @@ //! FRECPS/FRSQRTS: exact-product SSE2, FMA3, or widened arithmetic for half. use super::super::isa::ShiftOpcode; +use super::numerical::jump; use super::numerical::{ ArithmeticOpcode, Condition, FusedOpcode, INPUT_MINIMUM_EXPONENT, MINIMUM_EXPONENT_VECTOR, - RESULT_MINIMUM_EXPONENT, VZEROUPPER, branch, clear_scalar, commit_ah0_inexact, emit_fma, - emit_opcode_to, environment_alternative_nearest, exponent_range, guard_ah0_exceptions, + RESULT_MINIMUM_EXPONENT, branch, clear_scalar, commit_ah0_inexact, emit_fma, emit_opcode_to, + environment_alternative_nearest, exponent_range, guard_ah0_exceptions, prepare_vector_input_range, prepare_vector_result_range, read_numerical_vector, reject_other_status, reject_product_status, resolve, restore_environment, restore_environment_with_product, save_product_status, test_control, vector_exponent_range, }; use super::{Host, commit, half, packed}; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Rm, Size}; use crate::{ GuestAddress, TargetCpu, aarch64::{ @@ -20,6 +22,7 @@ use crate::{ }, block::ExitKind, }; +use Gpr::{R9, R10, Rax, Rcx, Rsp}; use alloc::vec::Vec; const LEFT: u8 = 0; @@ -32,55 +35,22 @@ const SPLIT_SINGLE_LEFT: u8 = 7; const HALF_CONSTANT: u8 = 5; const CONSTANT: u8 = 6; const ORIGINAL_LEFT: u8 = 7; -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const SSE_ESCAPE: u8 = 0x0f; -const SINGLE_PREFIX: u8 = 0xf3; -const DOUBLE_PREFIX: u8 = 0xf2; -const MOV_SCALAR: u8 = 0x10; -const JMP_REL32: u8 = 0xe9; const SIGN_BITS: u32 = 1; -const MOVD_EAX_XMM0: &[u8] = &[0x66, 0x0f, 0x7e, 0xc0]; -const MOVD_XMM0_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xc0]; -const SUB_EAX_IMM32: u8 = 0x2d; // Fixed registers for the cold Single-to-Double refinement path. The private // environment uses the same four-slot scratch layout as numerical.rs. -const CVTSS2SD_XMM0_XMM0: &[u8] = &[0xf3, 0x0f, 0x5a, 0xc0]; -const CVTSS2SD_XMM1_XMM1: &[u8] = &[0xf3, 0x0f, 0x5a, 0xc9]; -const CVTSD2SS_XMM6_XMM6: &[u8] = &[0xf2, 0x0f, 0x5a, 0xf6]; -const CVTPS2PD_XMM0_XMM0: &[u8] = &[0x0f, 0x5a, 0xc0]; -const CVTPS2PD_XMM1_XMM1: &[u8] = &[0x0f, 0x5a, 0xc9]; -const CVTPS2PD_XMM0_XMM7: &[u8] = &[0x0f, 0x5a, 0xc7]; -const CVTPS2PD_XMM1_XMM5: &[u8] = &[0x0f, 0x5a, 0xcd]; -const CVTPD2PS_XMM6_XMM6: &[u8] = &[0x66, 0x0f, 0x5a, 0xf6]; -const MOVHLPS_XMM0_XMM7: &[u8] = &[0x0f, 0x12, 0xc7]; -const MOVHLPS_XMM1_XMM5: &[u8] = &[0x0f, 0x12, 0xcd]; -const MOVLHPS_XMM3_XMM6: &[u8] = &[0x0f, 0x16, 0xde]; +const MXCSR_SAVED_SLOT: u8 = 0; const MXCSR_CONTROL_SLOT: u8 = 4; const MXCSR_STATUS_SLOT: u8 = 8; const MXCSR_PRODUCT_SLOT: u8 = 12; const MXCSR_STACK_BYTES: u8 = 16; -const STMXCSR_STATUS: &[u8] = &[0x0f, 0xae, 0x5c, 0x24, MXCSR_STATUS_SLOT]; -const LDMXCSR_SAVED: &[u8] = &[0x0f, 0xae, 0x14, 0x24]; -const LDMXCSR_CONTROL: &[u8] = &[0x0f, 0xae, 0x54, 0x24, MXCSR_CONTROL_SLOT]; -const MOV_R9D_PRODUCT: &[u8] = &[0x44, 0x8b, 0x4c, 0x24, MXCSR_PRODUCT_SLOT]; -const MOV_R10D_STATUS: &[u8] = &[0x44, 0x8b, 0x54, 0x24, MXCSR_STATUS_SLOT]; -const MOV_EAX_PRODUCT: &[u8] = &[0x8b, 0x44, 0x24, MXCSR_PRODUCT_SLOT]; -const MOV_ECX_STATUS: &[u8] = &[0x8b, 0x4c, 0x24, MXCSR_STATUS_SLOT]; -const MOV_PRODUCT_EAX: &[u8] = &[0x89, 0x44, 0x24, MXCSR_PRODUCT_SLOT]; -const OR_EAX_R9D: &[u8] = &[0x44, 0x09, 0xc8]; -const OR_ECX_R10D: &[u8] = &[0x44, 0x09, 0xd1]; -const ADD_RSP_MXCSR: &[u8] = &[0x48, 0x83, 0xc4, MXCSR_STACK_BYTES]; -fn jump(code: &mut Vec) -> usize { - code.push(JMP_REL32); - let patch = code.len(); - code.extend(0i32.to_le_bytes()); - patch +/// `[rsp + offset]` in the private environment frame. +fn slot(offset: u8) -> Mem { + Mem::base(Rsp, offset.into()) } -fn constant(code: &mut Vec, format: Format, kind: Kind, destination: u8) { +fn constant(code: &mut Code, format: Format, kind: Kind, destination: u8) { packed(code, Host::EqualDword, destination, destination); let (right, left) = if format == Format::Single { (ShiftOpcode::RightDword, ShiftOpcode::LeftDword) @@ -98,7 +68,7 @@ fn constant(code: &mut Vec, format: Format, kind: Kind, destination: u8) { left.emit(code, destination, left_bits as u8); } -fn normal_sources(code: &mut Vec, operand: &Operand, helper: &mut Vec) { +fn normal_sources(code: &mut Code, operand: &Operand, helper: &mut Vec) { let minimum = if operand.kind == Kind::ReciprocalSquareRoot { RESULT_MINIMUM_EXPONENT } else { @@ -121,12 +91,16 @@ fn normal_sources(code: &mut Vec, operand: &Operand, helper: &mut Vec } } -fn prehalve(code: &mut Vec, operand: &Operand) { +fn prehalve(code: &mut Code, operand: &Operand) { if operand.format == Format::Single && operand.shape == Shape::Scalar { - code.extend(MOVD_EAX_XMM0); - code.push(SUB_EAX_IMM32); - code.extend((1u32 << operand.format.fraction_bits()).to_le_bytes()); - code.extend(MOVD_XMM0_EAX); + let mut asm = code.asm(); + asm.movd_from_xmm(Rax, LEFT); + asm.alu_accumulator_imm32( + Alu::Sub, + Size::Dword, + (1u32 << operand.format.fraction_bits()) as i32, + ); + asm.movd_to_xmm(LEFT, Rax); return; } if operand.shape == Shape::Scalar { @@ -150,24 +124,27 @@ fn prehalve(code: &mut Vec, operand: &Operand) { /// The first pair's target PE must not contaminate the second pair's exact /// Double-affine status. R9D/R10D retain wide/target flags across the reset. -fn widen_single_pairs(code: &mut Vec) { +fn widen_single_pairs(code: &mut Code) { packed(code, Host::MoveAligned, SPLIT_SINGLE_LEFT, LEFT); packed(code, Host::MoveAligned, SAVED_SINGLE_RIGHT, RIGHT); packed(code, Host::MoveAligned, SAVED_SINGLE_CONSTANT, CONSTANT); - code.extend(CVTPS2PD_XMM0_XMM7); - code.extend(CVTPS2PD_XMM1_XMM5); + let mut asm = code.asm(); + asm.cvtps2pd(LEFT, Rm::Xmm(SPLIT_SINGLE_LEFT)); + asm.cvtps2pd(RIGHT, Rm::Xmm(SAVED_SINGLE_RIGHT)); widened_product(code, Shape::Vector128); save_product_status(code); - code.extend(MOV_R9D_PRODUCT); - code.extend(CVTPD2PS_XMM6_XMM6); - code.extend(STMXCSR_STATUS); - code.extend(MOV_R10D_STATUS); - code.extend(LDMXCSR_CONTROL); + let mut asm = code.asm(); + asm.mov_load(Size::Dword, R9, slot(MXCSR_PRODUCT_SLOT)); + asm.cvtpd2ps(CONSTANT, Rm::Xmm(CONSTANT)); + asm.stmxcsr(slot(MXCSR_STATUS_SLOT)); + asm.mov_load(Size::Dword, R10, slot(MXCSR_STATUS_SLOT)); + asm.ldmxcsr(slot(MXCSR_CONTROL_SLOT)); packed(code, Host::MoveAligned, FIRST_SINGLE_PAIR, CONSTANT); - code.extend(MOVHLPS_XMM0_XMM7); - code.extend(MOVHLPS_XMM1_XMM5); - code.extend(CVTPS2PD_XMM0_XMM0); - code.extend(CVTPS2PD_XMM1_XMM1); + let mut asm = code.asm(); + asm.movhlps(LEFT, Rm::Xmm(SPLIT_SINGLE_LEFT)); + asm.movhlps(RIGHT, Rm::Xmm(SAVED_SINGLE_RIGHT)); + asm.cvtps2pd(LEFT, Rm::Xmm(LEFT)); + asm.cvtps2pd(RIGHT, Rm::Xmm(RIGHT)); emit_opcode_to( code, Format::Double, @@ -186,21 +163,22 @@ fn widen_single_pairs(code: &mut Vec) { LEFT, ); save_product_status(code); - code.extend(MOV_EAX_PRODUCT); - code.extend(OR_EAX_R9D); - code.extend(MOV_PRODUCT_EAX); - code.extend(CVTPD2PS_XMM6_XMM6); - code.extend(STMXCSR_STATUS); - code.extend(LDMXCSR_SAVED); - code.extend(MOV_EAX_PRODUCT); - code.extend(MOV_ECX_STATUS); - code.extend(OR_ECX_R10D); - code.extend(ADD_RSP_MXCSR); - code.extend(MOVLHPS_XMM3_XMM6); + let mut asm = code.asm(); + asm.mov_load(Size::Dword, Rax, slot(MXCSR_PRODUCT_SLOT)); + asm.alu(Alu::Or, Size::Dword, Rax, R9); + asm.mov_store(Size::Dword, slot(MXCSR_PRODUCT_SLOT), Rax); + asm.cvtpd2ps(CONSTANT, Rm::Xmm(CONSTANT)); + asm.stmxcsr(slot(MXCSR_STATUS_SLOT)); + asm.ldmxcsr(slot(MXCSR_SAVED_SLOT)); + asm.mov_load(Size::Dword, Rax, slot(MXCSR_PRODUCT_SLOT)); + asm.mov_load(Size::Dword, Rcx, slot(MXCSR_STATUS_SLOT)); + asm.alu(Alu::Or, Size::Dword, Rcx, R10); + asm.alu_imm8(Alu::Add, Size::Qword, Rsp, MXCSR_STACK_BYTES as i8); + asm.movlhps(FIRST_SINGLE_PAIR, Rm::Xmm(CONSTANT)); packed(code, Host::MoveAligned, CONSTANT, FIRST_SINGLE_PAIR); } -fn widened_product(code: &mut Vec, shape: Shape) { +fn widened_product(code: &mut Code, shape: Shape) { emit_opcode_to( code, Format::Double, @@ -223,25 +201,27 @@ fn widened_product(code: &mut Vec, shape: Shape) { /// environment. The double product of widened singles is exact (at most 48 /// bits), and the affine step must also be exact before the single final /// rounding. -fn widened_single_fallback(code: &mut Vec, operand: &Operand, helper_start: usize) { +fn widened_single_fallback(code: &mut Code, operand: &Operand, helper_start: usize) { packed(code, Host::MoveAligned, LEFT, SAVED_SINGLE_LEFT); constant(code, Format::Double, operand.kind, CONSTANT); environment_alternative_nearest(code); match operand.shape { Shape::Scalar => { - code.extend(CVTSS2SD_XMM0_XMM0); - code.extend(CVTSS2SD_XMM1_XMM1); + let mut asm = code.asm(); + asm.cvtss2sd(LEFT, Rm::Xmm(LEFT)); + asm.cvtss2sd(RIGHT, Rm::Xmm(RIGHT)); widened_product(code, Shape::Scalar); save_product_status(code); - code.extend(CVTSD2SS_XMM6_XMM6); + code.asm().cvtsd2ss(CONSTANT, Rm::Xmm(CONSTANT)); restore_environment_with_product(code); } Shape::Vector64 => { - code.extend(CVTPS2PD_XMM0_XMM0); - code.extend(CVTPS2PD_XMM1_XMM1); + let mut asm = code.asm(); + asm.cvtps2pd(LEFT, Rm::Xmm(LEFT)); + asm.cvtps2pd(RIGHT, Rm::Xmm(RIGHT)); widened_product(code, Shape::Vector128); save_product_status(code); - code.extend(CVTPD2PS_XMM6_XMM6); + code.asm().cvtpd2ps(CONSTANT, Rm::Xmm(CONSTANT)); restore_environment_with_product(code); } Shape::Vector128 => widen_single_pairs(code), @@ -252,10 +232,10 @@ fn widened_single_fallback(code: &mut Vec, operand: &Operand, helper_start: resolve(code, invalid_target, helper_start); } -fn emit_single_double(code: &mut Vec, operand: &Operand, pc: GuestAddress, target: TargetCpu) { +fn emit_single_double(code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu) { let native_fma = target.supports(TargetCpu::Fma); if native_fma { - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } let mut helper = Vec::new(); guard_ah0_exceptions(code, &mut helper); @@ -338,16 +318,12 @@ fn emit_single_double(code: &mut Vec, operand: &Operand, pc: GuestAddress, t commit_ah0_inexact(code); if operand.shape == Shape::Scalar { if merge != result { - code.extend([ - if operand.format == Format::Single { - SINGLE_PREFIX - } else { - DOUBLE_PREFIX - }, - SSE_ESCAPE, - MOV_SCALAR, - REGISTER_DIRECT | merge << MODRM_REGISTER_SHIFT | result, - ]); + if operand.format == Format::Single { + Host::MoveScalarSingle + } else { + Host::MoveScalarDouble + } + .register(code, merge, result, TargetCpu::Baseline); } test_control(code, FPCR_NEP); let merging = branch(code, Condition::NotZero); @@ -363,7 +339,7 @@ fn emit_single_double(code: &mut Vec, operand: &Operand, pc: GuestAddress, t } } -fn emit_half(code: &mut Vec, operand: &Operand, pc: GuestAddress) { +fn emit_half(code: &mut Code, operand: &Operand, pc: GuestAddress) { let mut helper = Vec::new(); let mut rollback = Vec::new(); guard_ah0_exceptions(code, &mut helper); @@ -434,7 +410,7 @@ fn emit_half(code: &mut Vec, operand: &Operand, pc: GuestAddress) { } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu, diff --git a/crates/stela-compiler/src/x86_64/simd/rounding.rs b/crates/stela-compiler/src/x86_64/simd/rounding.rs index e61b04045e..3e6c551b53 100644 --- a/crates/stela-compiler/src/x86_64/simd/rounding.rs +++ b/crates/stela-compiler/src/x86_64/simd/rounding.rs @@ -1,4 +1,9 @@ //! FRINT*: integer baseline, or SSE4.1 ROUND with exceptions masked. +use super::numerical::{emit_opcode_to, float_lanes, helper_section, jump}; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Rm, ShiftOp, Size}; +use crate::x86_64::simd::encode::guest; +use Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdx}; use alloc::vec::Vec; pub(in crate::x86_64) mod kernel; use super::super::isa::ShiftOpcode; @@ -16,7 +21,6 @@ use crate::{ }, simd::{arithmetic::Shape, rounding::Operand}, }, - block::ExitKind, }; const RESULT: u8 = 0; @@ -35,67 +39,6 @@ const SINGLE_LOW_MASK: u32 = 0x03; const SINGLE_FULL_MASK: u32 = 0x0f; const DOUBLE_FULL_MASK: u32 = 0x05; const BITS_PER_BYTE: u32 = u8::BITS; -const REGISTER_DIRECT: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; -const SSE_ESCAPE: u8 = 0x0f; -const JMP_RELATIVE: u8 = 0xe9; -const MOVD_TO_EAX: &[u8] = &[0x66, 0x0f, 0x7e]; -const MOVD_FROM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; -const MOVQ_TO_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const PINSRW_FROM_EAX: &[u8] = &[0x66, 0x0f, 0xc4]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const SHR_RCX: &[u8] = &[0x48, 0xc1, 0xe9]; -const AND_ECX: &[u8] = &[0x81, 0xe1]; -const CMP_ECX: &[u8] = &[0x81, 0xf9]; -const MOV_R8D_ECX: &[u8] = &[0x41, 0x89, 0xc8]; -const DEC_R8D: &[u8] = &[0x41, 0xff, 0xc8]; -const CMP_R8D: &[u8] = &[0x41, 0x81, 0xf8]; -const MOV_R9_RDX: &[u8] = &[0x49, 0x89, 0xd1]; -const MOV_R9_RAX: &[u8] = &[0x49, 0x89, 0xc1]; -const SHL_R9: &[u8] = &[0x49, 0xc1, 0xe1]; -const MOV_R8D: &[u8] = &[0x41, 0xb8]; -const MOVABS_R8: &[u8] = &[0x49, 0xb8]; -const SUB_R8D_ECX: &[u8] = &[0x41, 0x29, 0xc8]; -const MOV_ECX_R8D: &[u8] = &[0x44, 0x89, 0xc1]; -const SHL_R8_CL: &[u8] = &[0x49, 0xd3, 0xe0]; -const MOV_R9_R8: &[u8] = &[0x4d, 0x89, 0xc1]; -const DEC_R9: &[u8] = &[0x49, 0xff, 0xc9]; -const SHR_R8_1: &[u8] = &[0x49, 0xd1, 0xe8]; -const DEC_R8: &[u8] = &[0x49, 0xff, 0xc8]; -const BT_RAX_RCX: &[u8] = &[0x48, 0x0f, 0xa3, 0xc8]; -const ADC_R8_ZERO: &[u8] = &[0x49, 0x83, 0xd0, 0]; -const XOR_R8D_R8D: &[u8] = &[0x45, 0x31, 0xc0]; -const BT_RDX: &[u8] = &[0x48, 0x0f, 0xba, 0xe2]; -const BT_RAX: &[u8] = &[0x48, 0x0f, 0xba, 0xe0]; -const BTR_R9: &[u8] = &[0x49, 0x0f, 0xba, 0xf1]; -const CMOVB_R8_R9: &[u8] = &[0x4d, 0x0f, 0x42, 0xc1]; -const CMOVAE_R8_R9: &[u8] = &[0x4d, 0x0f, 0x43, 0xc1]; -const ADD_RAX_R8: &[u8] = &[0x4c, 0x01, 0xc0]; -const OR_RAX_R8: &[u8] = &[0x4c, 0x09, 0xc0]; -const OR_RAX_R9: &[u8] = &[0x4c, 0x09, 0xc8]; -const XOR_RAX_R9: &[u8] = &[0x4c, 0x31, 0xc8]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const OR_EAX_IMMEDIATE: u8 = 0x0d; -const SHR_RAX: &[u8] = &[0x48, 0xc1, 0xe8]; -const SHL_RAX: &[u8] = &[0x48, 0xc1, 0xe0]; -const CMP_R9_R8: &[u8] = &[0x4d, 0x39, 0xc1]; -const CMP_RAX_RDX: &[u8] = &[0x48, 0x39, 0xd0]; -const SETNE_R8B: &[u8] = &[0x41, 0x0f, 0x95, 0xc0]; -const MOVZX_R8D_R8B: &[u8] = &[0x45, 0x0f, 0xb6, 0xc0]; -const OR_R10D_R8D: &[u8] = &[0x45, 0x09, 0xc2]; -const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; -const SETNE_R10B: &[u8] = &[0x41, 0x0f, 0x95, 0xc2]; -const SHL_R10D: &[u8] = &[0x41, 0xc1, 0xe2]; -const OR_STATE_R10D: &[u8] = &[0x44, 0x09, 0x97]; -const MOV_R11D: &[u8] = &[0x41, 0xbb]; -const DEC_R11D: &[u8] = &[0x41, 0xff, 0xcb]; -const PSLLDQ_XMM2: &[u8] = &[0x66, 0x0f, 0x73, 0xfa]; -const MOVLHPS_XMM0_XMM2: &[u8] = &[0x0f, 0x16, 0xc2]; -const MOVSS_XMM6_XMM0: &[u8] = &[0xf3, 0x0f, 0x10, 0xf0]; -const MOVSD_XMM6_XMM0: &[u8] = &[0xf2, 0x0f, 0x10, 0xf0]; -const MOVABS_RAX: &[u8] = &[0x48, 0xb8]; -const CMP_EAX_IMMEDIATE: u8 = 0x3d; const PRECISION_SUPPRESSED: u8 = 1 << 3; const ROUND_NEAREST: u8 = 0; const ROUND_NEGATIVE: u8 = 1; @@ -105,10 +48,6 @@ const FPCR_LOW_ROUNDING_BIT: u32 = 1 << FPCR_ROUNDING_SHIFT; const FPCR_HIGH_ROUNDING_BIT: u32 = 1 << (FPCR_ROUNDING_SHIFT + 1); const INEXACT_SHIFT: u8 = INEXACT.trailing_zeros() as u8; const COMPARE_LESS_EQUAL: u8 = 2; -const COMPARE_OPCODE: u8 = 0xc2; -const SCALAR_SINGLE_PREFIX: u8 = 0xf3; -const SCALAR_DOUBLE_PREFIX: u8 = 0xf2; -const PACKED_DOUBLE_PREFIX: u8 = 0x66; const ADJACENT_DWORDS: u8 = 0xb1; #[derive(Clone, Copy)] @@ -120,16 +59,11 @@ enum Direction { Zero, } -fn jump(code: &mut Vec) -> usize { - code.push(JMP_RELATIVE); - let patch = code.len(); - code.extend(0i32.to_le_bytes()); - patch -} - -fn immediate(code: &mut Vec, instruction: &[u8], value: u32) { - code.extend(instruction); - code.extend(value.to_le_bytes()); +/// `and eax, value; cmp eax, value`: ZF is set when every `value` bit is set. +fn all_bits(code: &mut Code, value: u32) { + let mut asm = code.asm(); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, value as i32); + asm.alu_accumulator_imm32(Alu::Cmp, Size::Dword, value as i32); } fn exponent_mask(format: Format) -> u32 { @@ -166,7 +100,7 @@ fn fixed_direction(operation: RoundingOperation) -> Option { } /// Dynamic FPCR is read at execution time, without installing host control. -fn current_direction(code: &mut Vec, mut emit: impl FnMut(&mut Vec, Direction)) { +fn current_direction(code: &mut Code, mut emit: impl FnMut(&mut Code, Direction)) { test_control(code, FPCR_HIGH_ROUNDING_BIT); let high = branch(code, Condition::NotZero); test_control(code, FPCR_LOW_ROUNDING_BIT); @@ -193,9 +127,9 @@ fn current_direction(code: &mut Vec, mut emit: impl FnMut(&mut Vec, Dire } fn direction( - code: &mut Vec, + code: &mut Code, operation: RoundingOperation, - mut emit: impl FnMut(&mut Vec, Direction), + mut emit: impl FnMut(&mut Code, Direction), ) { if let Some(fixed) = fixed_direction(operation) { emit(code, fixed); @@ -204,88 +138,107 @@ fn direction( } } -fn read_lane(code: &mut Vec, format: Format, xmm: u8) { - code.extend(if format == Format::Double { - MOVQ_TO_RAX +fn read_lane(code: &mut Code, format: Format, xmm: u8) { + let mut asm = code.asm(); + if format == Format::Double { + asm.movq_from_xmm(Rax, xmm); } else { - MOVD_TO_EAX - }); - code.push(REGISTER_DIRECT | (xmm << REGISTER_SHIFT)); + asm.movd_from_xmm(Rax, xmm); + } if format == Format::Half { - code.push(AND_EAX_IMMEDIATE); - code.extend(u32::from(u16::MAX).to_le_bytes()); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, u16::MAX.into()); } } -fn source_class(code: &mut Vec, format: Format, helper: &mut Vec) { - code.extend(MOV_RDX_RAX); - code.extend(MOV_RCX_RAX); - code.extend(SHR_RCX); - code.push(format.fraction_bits() as u8); - immediate(code, AND_ECX, exponent_mask(format)); - code.extend(MOV_R8D_ECX); - code.extend(DEC_R8D); - immediate(code, CMP_R8D, exponent_mask(format) - 1); +fn source_class(code: &mut Code, format: Format, helper: &mut Vec) { + let mut asm = code.asm(); + asm.mov(Size::Qword, Rdx, Rax); + asm.mov(Size::Qword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rcx, format.fraction_bits() as u8); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, exponent_mask(format) as i32); + asm.mov(Size::Dword, R8, Rcx); + asm.dec(Size::Dword, R8); + asm.alu_imm32( + Alu::Cmp, + Size::Dword, + R8, + (exponent_mask(format) - 1) as i32, + ); let normal = branch(code, Condition::Below); - code.extend(MOV_R9_RDX); - code.extend(SHL_R9); - code.push((u64::BITS - (format.bits() - SIGN_BITS)) as u8); + shifted_out(code, (u64::BITS - (format.bits() - SIGN_BITS)) as u8); helper.push(branch(code, Condition::NotZero)); // only signed zero survives the nonnormal case let accepted = code.len(); resolve(code, normal, accepted); } -fn fractional_bias(code: &mut Vec, format: Format, rounding: Direction) { +/// `mov r9, rdx; shl r9, amount`: ZF reports whether the source's low +/// `64 - amount` bits are all zero. +fn shifted_out(code: &mut Code, amount: u8) { + let mut asm = code.asm(); + asm.mov(Size::Qword, R9, Rdx); + asm.shift_imm(ShiftOp::Shl, Size::Qword, R9, amount); +} + +/// `xor r8d, r8d`. +fn clear_bias(code: &mut Code) { + code.asm().alu(Alu::Xor, Size::Dword, R8, R8); +} + +/// `bt rdx, sign`: CF is the source sign. +fn test_sign(code: &mut Code, format: Format) { + code.asm() + .bit_imm(BitTest::Bt, Size::Qword, Rdx, sign_bit(format)); +} + +fn fractional_bias(code: &mut Code, format: Format, rounding: Direction) { match rounding { Direction::NearestEven => { - code.extend(SHR_R8_1); - code.extend(DEC_R8); - code.extend(BT_RAX_RCX); - code.extend(ADC_R8_ZERO); + let mut asm = code.asm(); + asm.shift_one(ShiftOp::Shr, Size::Qword, R8); + asm.dec(Size::Qword, R8); + asm.bit(BitTest::Bt, Size::Qword, Rax, Rcx); + asm.alu_imm8(Alu::Adc, Size::Qword, R8, 0); } - Direction::NearestAway => code.extend(SHR_R8_1), + Direction::NearestAway => code.asm().shift_one(ShiftOp::Shr, Size::Qword, R8), Direction::Positive | Direction::Negative => { - code.extend(XOR_R8D_R8D); - code.extend(BT_RDX); - code.push(sign_bit(format)); - code.extend(if matches!(rounding, Direction::Positive) { - CMOVAE_R8_R9 + clear_bias(code); + test_sign(code, format); + let condition = if matches!(rounding, Direction::Positive) { + Cond::Ae } else { - CMOVB_R8_R9 - }); + Cond::B + }; + code.asm().cmov(condition, Size::Qword, R8, R9); } - Direction::Zero => code.extend(XOR_R8D_R8D), + Direction::Zero => clear_bias(code), } } -fn or_one(code: &mut Vec, format: Format) { +fn or_one(code: &mut Code, format: Format) { let one = u64::from(bias(format)) << format.fraction_bits(); + let mut asm = code.asm(); if format == Format::Double { - code.extend(MOVABS_R8); - code.extend(one.to_le_bytes()); - code.extend(OR_RAX_R8); + asm.mov_imm64(R8, one); + asm.alu(Alu::Or, Size::Qword, Rax, R8); } else { - code.push(OR_EAX_IMMEDIATE); - code.extend((one as u32).to_le_bytes()); + asm.alu_accumulator_imm32(Alu::Or, Size::Dword, one as i32); } } -fn small_increment(code: &mut Vec, format: Format, rounding: Direction, done: &mut Vec) { +fn small_increment(code: &mut Code, format: Format, rounding: Direction, done: &mut Vec) { match rounding { Direction::NearestEven | Direction::NearestAway => { - immediate(code, CMP_ECX, bias(format) - 1); + code.asm() + .alu_imm32(Alu::Cmp, Size::Dword, Rcx, (bias(format) - 1) as i32); done.push(branch(code, Condition::Below)); if matches!(rounding, Direction::NearestEven) { - code.extend(MOV_R9_RDX); - code.extend(SHL_R9); - code.push((u64::BITS - format.fraction_bits()) as u8); + shifted_out(code, (u64::BITS - format.fraction_bits()) as u8); done.push(branch(code, Condition::Zero)); } or_one(code, format); } Direction::Positive | Direction::Negative => { - code.extend(BT_RDX); - code.push(sign_bit(format)); + test_sign(code, format); done.push(branch( code, if matches!(rounding, Direction::Positive) { @@ -300,59 +253,62 @@ fn small_increment(code: &mut Vec, format: Format, rounding: Direction, done } } -fn bounded(code: &mut Vec, format: Format, width: u32, helper: &mut Vec) { - code.extend(MOV_R9_RAX); - code.extend(BTR_R9); - code.push(sign_bit(format)); - code.extend(MOVABS_R8); - code.extend((u64::from(bias(format) + width - 1) << format.fraction_bits()).to_le_bytes()); - code.extend(CMP_R9_R8); +fn bounded(code: &mut Code, format: Format, width: u32, helper: &mut Vec) { + let mut asm = code.asm(); + asm.mov(Size::Qword, R9, Rax); + asm.bit_imm(BitTest::Btr, Size::Qword, R9, sign_bit(format)); + asm.mov_imm64( + R8, + u64::from(bias(format) + width - 1) << format.fraction_bits(), + ); + asm.alu(Alu::Cmp, Size::Qword, R9, R8); helper.push(branch(code, Condition::Above)); let smaller = branch(code, Condition::Below); - code.extend(BT_RAX); - code.push(sign_bit(format)); + code.asm() + .bit_imm(BitTest::Bt, Size::Qword, Rax, sign_bit(format)); helper.push(branch(code, Condition::AboveOrEqual)); // equality is valid only at the negative limit let accepted = code.len(); resolve(code, smaller, accepted); } -fn integer_lane(code: &mut Vec, operand: &Operand, helper: &mut Vec) { +fn integer_lane(code: &mut Code, operand: &Operand, helper: &mut Vec) { let format = operand.format; read_lane(code, format, SOURCE); source_class(code, format, helper); let mut done = Vec::new(); - immediate(code, CMP_ECX, bias(format)); + let integral = bias(format) + format.fraction_bits(); + code.asm() + .alu_imm32(Alu::Cmp, Size::Dword, Rcx, bias(format) as i32); let small = branch(code, Condition::Below); - immediate(code, CMP_ECX, bias(format) + format.fraction_bits()); + code.asm() + .alu_imm32(Alu::Cmp, Size::Dword, Rcx, integral as i32); done.push(branch(code, Condition::AboveOrEqual)); - immediate(code, MOV_R8D, bias(format) + format.fraction_bits()); - code.extend(SUB_R8D_ECX); - code.extend(MOV_ECX_R8D); - immediate(code, MOV_R8D, 1); - code.extend(SHL_R8_CL); - code.extend(MOV_R9_R8); - code.extend(DEC_R9); + let mut asm = code.asm(); + asm.mov_imm32(R8, integral); + asm.alu(Alu::Sub, Size::Dword, R8, Rcx); + asm.mov(Size::Dword, Rcx, R8); + asm.mov_imm32(R8, 1); + asm.shift_cl(ShiftOp::Shl, Size::Qword, R8); + asm.mov(Size::Qword, R9, R8); + asm.dec(Size::Qword, R9); direction(code, operand.operation, |code, rounding| { fractional_bias(code, format, rounding) }); - code.extend(ADD_RAX_R8); - code.extend(OR_RAX_R9); - code.extend(XOR_RAX_R9); + let mut asm = code.asm(); + asm.alu(Alu::Add, Size::Qword, Rax, R8); + asm.alu(Alu::Or, Size::Qword, Rax, R9); + asm.alu(Alu::Xor, Size::Qword, Rax, R9); done.push(jump(code)); let small_start = code.len(); resolve(code, small, small_start); + let mut asm = code.asm(); if format == Format::Double { - code.extend(SHR_RAX); - code.push(sign_bit(format)); - code.extend(SHL_RAX); - code.push(sign_bit(format)); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rax, sign_bit(format)); + asm.shift_imm(ShiftOp::Shl, Size::Qword, Rax, sign_bit(format)); } else { - code.push(AND_EAX_IMMEDIATE); - code.extend((1u32 << sign_bit(format)).to_le_bytes()); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, (1u32 << sign_bit(format)) as i32); } - code.extend(MOV_R9_RDX); - code.extend(SHL_R9); - code.push((u64::BITS - (format.bits() - SIGN_BITS)) as u8); + shifted_out(code, (u64::BITS - (format.bits() - SIGN_BITS)) as u8); done.push(branch(code, Condition::Zero)); direction(code, operand.operation, |code, rounding| { small_increment(code, format, rounding, &mut done) @@ -365,56 +321,61 @@ fn integer_lane(code: &mut Vec, operand: &Operand, helper: &mut Vec) bounded(code, format, width, helper); } if operand.operation.exact() { - code.extend(CMP_RAX_RDX); - code.extend(SETNE_R8B); - code.extend(MOVZX_R8D_R8B); - code.extend(OR_R10D_R8D); + let mut asm = code.asm(); + asm.alu(Alu::Cmp, Size::Qword, Rax, Rdx); + asm.setcc(Cond::Ne, R8); + asm.movzx(Size::Dword, R8, Size::Byte, R8); + asm.alu(Alu::Or, Size::Dword, R10, R8); } } -fn insert_lane(code: &mut Vec, operand: &Operand) { +fn insert_lane(code: &mut Code, operand: &Operand) { match operand.format { Format::Half => { - code.extend(PINSRW_FROM_EAX); - code.push(REGISTER_DIRECT); - code.push((lanes(operand) - 1) as u8); + code.asm().pinsrw(RESULT, Rax, (lanes(operand) - 1) as u8); } Format::Single => { - code.extend(MOVD_FROM_EAX); - code.push(REGISTER_DIRECT | (TEMP << REGISTER_SHIFT)); - code.extend(PSLLDQ_XMM2); - code.push(((lanes(operand) - 1) * (Format::Single.bits() / BITS_PER_BYTE)) as u8); + code.asm().movd_to_xmm(TEMP, Rax); + ShiftOpcode::LeftBytes.emit( + code, + TEMP, + ((lanes(operand) - 1) * (Format::Single.bits() / BITS_PER_BYTE)) as u8, + ); packed(code, Host::Or, RESULT, TEMP); } Format::Double => { packed(code, Host::MoveGprQword, TEMP, ACCUMULATOR_GPR); - code.extend(MOVLHPS_XMM0_XMM2); + code.asm().movlhps(RESULT, Rm::Xmm(TEMP)); } } } -fn integer_rounding(code: &mut Vec, operand: &Operand, helper: &mut Vec) { +/// `xor r10d, r10d`: R10D accumulates whether any lane was inexact. +fn clear_inexact(code: &mut Code) { + code.asm().alu(Alu::Xor, Size::Dword, R10, R10); +} + +fn integer_rounding(code: &mut Code, operand: &Operand, helper: &mut Vec) { if operand.operation.exact() { - code.extend(XOR_R10D_R10D); + clear_inexact(code); } if operand.shape == Shape::Scalar { integer_lane(code, operand, helper); if operand.format == Format::Double { packed(code, Host::MoveGprQword, RESULT, ACCUMULATOR_GPR); } else { - code.extend(MOVD_FROM_EAX); - code.push(REGISTER_DIRECT); + code.asm().movd_to_xmm(RESULT, Rax); } } else { packed(code, Host::Xor, RESULT, RESULT); - immediate(code, MOV_R11D, lanes(operand)); + code.asm().mov_imm32(R11, lanes(operand)); let repeat = code.len(); integer_lane(code, operand, helper); let lane_bytes = (operand.format.bits() / BITS_PER_BYTE) as u8; ShiftOpcode::RightBytes.emit(code, SOURCE, lane_bytes); ShiftOpcode::RightBytes.emit(code, RESULT, lane_bytes); insert_lane(code, operand); - code.extend(DEC_R11D); + code.asm().dec(Size::Dword, R11); let repeat_branch = branch(code, Condition::NotZero); resolve(code, repeat_branch, repeat); } @@ -436,7 +397,7 @@ fn packed_right(format: Format) -> ShiftOpcode { } } -fn checked_source(code: &mut Vec, operand: &Operand, helper: &mut Vec) { +fn checked_source(code: &mut Code, operand: &Operand, helper: &mut Vec) { let format = operand.format; prepare_vector_input_range(code, format); vector_exponent_range(code, format, operand.shape, SOURCE); @@ -472,15 +433,12 @@ fn checked_source(code: &mut Vec, operand: &Operand, helper: &mut Vec _ => unreachable!("decoded checked round arrangement"), } }; - code.push(AND_EAX_IMMEDIATE); - code.extend(mask.to_le_bytes()); - code.push(CMP_EAX_IMMEDIATE); - code.extend(mask.to_le_bytes()); + all_bits(code, mask); helper.push(branch(code, Condition::NotZero)); } fn round_instruction( - code: &mut Vec, + code: &mut Code, format: Format, shape: Shape, rounding: Direction, @@ -500,41 +458,11 @@ fn round_instruction( Direction::Zero => ROUND_ZERO, Direction::NearestAway => unreachable!("ties-away uses an exact residual"), }; - opcode.register(code, RESULT, SOURCE, target); - code.push(PRECISION_SUPPRESSED | mode); + opcode.register_imm(code, RESULT, SOURCE, PRECISION_SUPPRESSED | mode, target); } -fn fp_prefix(code: &mut Vec, format: Format, shape: Shape) { - if shape == Shape::Scalar { - code.push(if format == Format::Double { - SCALAR_DOUBLE_PREFIX - } else { - SCALAR_SINGLE_PREFIX - }); - } else if format == Format::Double { - code.push(PACKED_DOUBLE_PREFIX); - } -} - -fn fp_arithmetic( - code: &mut Vec, - format: Format, - shape: Shape, - opcode: ArithmeticOpcode, - destination: u8, - source: u8, -) { - fp_prefix(code, format, shape); - code.extend([ - SSE_ESCAPE, - opcode as u8, - REGISTER_DIRECT | (destination << REGISTER_SHIFT) | source, - ]); -} - -fn splat(code: &mut Vec, format: Format, vector: u8, bits: u64) { - code.extend(MOVABS_RAX); - code.extend(bits.to_le_bytes()); +fn splat(code: &mut Code, format: Format, vector: u8, bits: u64) { + code.asm().mov_imm64(Rax, bits); packed(code, Host::MoveGprQword, vector, ACCUMULATOR_GPR); if format == Format::Single { super::shuffle(code, vector, vector, BROADCAST_LOW_DWORD); @@ -543,15 +471,15 @@ fn splat(code: &mut Vec, format: Format, vector: u8, bits: u64) { } } -fn magnitude_mask(code: &mut Vec, format: Format, vector: u8) { +fn magnitude_mask(code: &mut Code, format: Format, vector: u8) { packed(code, Host::EqualDword, vector, vector); packed_right(format).emit(code, vector, SIGN_BITS as u8); } -fn ties_away(code: &mut Vec, format: Format, shape: Shape, target: TargetCpu) { +fn ties_away(code: &mut Code, format: Format, shape: Shape, target: TargetCpu) { round_instruction(code, format, shape, Direction::Zero, target); packed(code, Host::MoveAligned, RESIDUAL, SOURCE); - fp_arithmetic( + emit_opcode_to( code, format, shape, @@ -568,13 +496,12 @@ fn ties_away(code: &mut Vec, format: Format, shape: Shape, target: TargetCpu u64::from(bias(format) - 1) << format.fraction_bits(), ); // 0.5 <= abs(x-trunc(x)), with an ordered predicate and guarded finite data. - fp_prefix(code, format, shape); - code.extend([ - SSE_ESCAPE, - COMPARE_OPCODE, - REGISTER_DIRECT | (CONSTANT << REGISTER_SHIFT) | RESIDUAL, + code.asm().float_compare( + float_lanes(format, shape), + CONSTANT, + Rm::Xmm(RESIDUAL), COMPARE_LESS_EQUAL, - ]); + ); packed(code, Host::EqualDword, MASK, MASK); packed_left(format).emit(code, MASK, sign_bit(format)); packed(code, Host::And, MASK, SOURCE); @@ -586,7 +513,7 @@ fn ties_away(code: &mut Vec, format: Format, shape: Shape, target: TargetCpu ); packed(code, Host::Or, RESIDUAL, MASK); packed(code, Host::And, RESIDUAL, CONSTANT); - fp_arithmetic(code, format, shape, ArithmeticOpcode::Add, RESULT, RESIDUAL); + emit_opcode_to(code, format, shape, ArithmeticOpcode::Add, RESULT, RESIDUAL); // An exact zero sum can take the host rounding mode's sign, so force the // architectural sign on every result, including signed zero. magnitude_mask(code, format, MASK); @@ -598,7 +525,7 @@ fn ties_away(code: &mut Vec, format: Format, shape: Shape, target: TargetCpu } fn checked_compute( - code: &mut Vec, + code: &mut Code, operation: RoundingOperation, format: Format, shape: Shape, @@ -613,7 +540,7 @@ fn checked_compute( } } -fn half_bias(code: &mut Vec, vector: u8) { +fn half_bias(code: &mut Code, vector: u8) { let adjustment = (bias(Format::Single) - bias(Format::Half)) << Format::Single.fraction_bits(); let position = adjustment.trailing_zeros(); let digits = (adjustment >> position).ilog2() + 1; @@ -622,7 +549,7 @@ fn half_bias(code: &mut Vec, vector: u8) { ShiftOpcode::LeftDword.emit(code, vector, position as u8); } -fn widen_half(code: &mut Vec, upper: bool) { +fn widen_half(code: &mut Code, upper: bool) { let sign_shift = (Format::Single.bits() - Format::Half.bits()) as u8; let strip_sign = sign_shift + SIGN_BITS as u8; let fraction_shift = (Format::Single.fraction_bits() - Format::Half.fraction_bits()) as u8; @@ -649,7 +576,7 @@ fn widen_half(code: &mut Vec, upper: bool) { packed(code, Host::MoveAligned, SOURCE, RESIDUAL); } -fn pack_half(code: &mut Vec, target: TargetCpu) { +fn pack_half(code: &mut Code, target: TargetCpu) { packed(code, Host::MoveAligned, TEMP, RESULT); ShiftOpcode::RightDword.emit(code, TEMP, sign_bit(Format::Single)); ShiftOpcode::LeftDword.emit(code, TEMP, sign_bit(Format::Half)); @@ -671,7 +598,7 @@ fn pack_half(code: &mut Vec, target: TargetCpu) { Host::PackUnsignedDwordToWord.register(code, MASK, MASK, target); } -fn checked_half(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn checked_half(code: &mut Code, operand: &Operand, target: TargetCpu) { packed(code, Host::MoveAligned, ORIGINAL_HALF, SOURCE); widen_half(code, false); checked_compute( @@ -701,7 +628,7 @@ fn checked_half(code: &mut Vec, operand: &Operand, target: TargetCpu) { packed(code, Host::MoveAligned, SOURCE, ORIGINAL_HALF); } -fn checked_bounds(code: &mut Vec, operand: &Operand, helper: &mut Vec) { +fn checked_bounds(code: &mut Code, operand: &Operand, helper: &mut Vec) { let Some(width) = operand.operation.signed_width() else { return; }; @@ -713,24 +640,21 @@ fn checked_bounds(code: &mut Vec, operand: &Operand, helper: &mut Vec } } -fn checked_inexact(code: &mut Vec, operand: &Operand) { +fn checked_inexact(code: &mut Code, operand: &Operand) { if !operand.operation.exact() { return; } - code.extend(XOR_R10D_R10D); + clear_inexact(code); packed(code, Host::MoveAligned, TEMP, RESULT); packed(code, Host::EqualByte, TEMP, SOURCE); Host::ByteSignMask.register(code, 0, TEMP, TargetCpu::Baseline); let mask = (1u32 << (lanes(operand) * (operand.format.bits() / BITS_PER_BYTE))) - 1; - code.push(AND_EAX_IMMEDIATE); - code.extend(mask.to_le_bytes()); - code.push(CMP_EAX_IMMEDIATE); - code.extend(mask.to_le_bytes()); - code.extend(SETNE_R10B); + all_bits(code, mask); + code.asm().setcc(Cond::Ne, R10); } fn checked_rounding( - code: &mut Vec, + code: &mut Code, operand: &Operand, helper: &mut Vec, target: TargetCpu, @@ -751,35 +675,30 @@ fn checked_rounding( checked_inexact(code, operand); } -fn helper_section(code: &mut Vec, helper: &[usize], pc: GuestAddress) { - let completed = jump(code); - let helper_start = code.len(); - super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); - let success = code.len(); - for &patch in helper { - resolve(code, patch, helper_start); - } - resolve(code, completed, success); -} - -fn commit_result(code: &mut Vec, operand: &Operand) { +fn commit_result(code: &mut Code, operand: &Operand) { if operand.operation.exact() { - code.extend(SHL_R10D); - code.push(INEXACT_SHIFT); - code.extend(OR_STATE_R10D); - code.extend((core::mem::offset_of!(GuestState, fpsr) as u32).to_le_bytes()); + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shl, Size::Dword, R10, INEXACT_SHIFT); + asm.alu( + Alu::Or, + Size::Dword, + guest(core::mem::offset_of!(GuestState, fpsr) as u32), + R10, + ); } let result = if operand.shape == Shape::Scalar { read_vector(code, operand.destination, SAVED_HALF); match operand.format { Format::Half => { read_lane(code, Format::Half, RESULT); - code.extend(PINSRW_FROM_EAX); - code.push(REGISTER_DIRECT | (SAVED_HALF << REGISTER_SHIFT)); - code.push(FIRST_LANE); + code.asm().pinsrw(SAVED_HALF, Rax, FIRST_LANE); + } + Format::Single => { + Host::MoveScalarSingle.register(code, SAVED_HALF, RESULT, TargetCpu::Baseline) + } + Format::Double => { + Host::MoveScalarDouble.register(code, SAVED_HALF, RESULT, TargetCpu::Baseline) } - Format::Single => code.extend(MOVSS_XMM6_XMM0), - Format::Double => code.extend(MOVSD_XMM6_XMM0), } test_control(code, FPCR_NEP); let merging = branch(code, Condition::NotZero); @@ -797,7 +716,7 @@ fn commit_result(code: &mut Vec, operand: &Operand) { } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu, diff --git a/crates/stela-compiler/src/x86_64/simd/rounding/kernel.rs b/crates/stela-compiler/src/x86_64/simd/rounding/kernel.rs index eff98cc005..6e08a73d34 100644 --- a/crates/stela-compiler/src/x86_64/simd/rounding/kernel.rs +++ b/crates/stela-compiler/src/x86_64/simd/rounding/kernel.rs @@ -1,4 +1,5 @@ //! Single and double rounding arithmetic shared by the FRINT forms. +use crate::x86_64::asm::Code; use crate::{ TargetCpu, @@ -23,7 +24,7 @@ const UNUSED_ARCHITECTURAL_REGISTER: u8 = 0; /// produces a fresh fractional-change Boolean in R10D. No guest storage, RSP, /// callee-saved GPR, frame, control-enable policy or instruction exit is changed. pub(in crate::x86_64) fn emit_chunk( - code: &mut Vec, + code: &mut Code, operation: RoundingOperation, format: Format, failures: &mut Vec, @@ -54,7 +55,7 @@ const ROUND_CURRENT_MXCSR_DIRECTION: u8 = 1 << 2; /// no suppressed host precision status is imported as guest FPSR. /// Clobbers and architectural commit ownership match `emit_chunk` above. pub(in crate::x86_64) fn emit_checked_current_direction( - code: &mut Vec, + code: &mut Code, operation: RoundingOperation, format: Format, failures: &mut Vec, @@ -78,7 +79,12 @@ pub(in crate::x86_64) fn emit_checked_current_direction( source: UNUSED_ARCHITECTURAL_REGISTER, }; super::checked_source(code, &operand, failures); - opcode.register(code, RESULT_XMM, SOURCE_XMM, target); - code.push(ROUND_CURRENT_MXCSR_DIRECTION | super::PRECISION_SUPPRESSED); + opcode.register_imm( + code, + RESULT_XMM, + SOURCE_XMM, + ROUND_CURRENT_MXCSR_DIRECTION | super::PRECISION_SUPPRESSED, + target, + ); super::checked_inexact(code, &operand); } diff --git a/crates/stela-compiler/src/x86_64/simd/saturating.rs b/crates/stela-compiler/src/x86_64/simd/saturating.rs index fa1e7d401e..a59c390674 100644 --- a/crates/stela-compiler/src/x86_64/simd/saturating.rs +++ b/crates/stela-compiler/src/x86_64/simd/saturating.rs @@ -1,35 +1,16 @@ //! Saturating arithmetic. XMM4 accumulates the per-lane FPSR.QC mask; overflow is //! detected before clamping. +use super::rearrange::{add_or_subtract, lane_constant}; use super::{Host, commit, greater, packed, read_vector, rearrange::constant, shuffle}; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, ShiftOp, Size}; +use crate::x86_64::simd::encode::guest; use crate::{ GuestState, TargetCpu, aarch64::simd::saturating::{FPSR_QC, Kind, Operand}, x86_64::isa::ShiftOpcode as Shift, }; -use alloc::vec::Vec; -fn lane_constant(code: &mut Vec, xmm: u8, lane: u8, value: u64) { - let bytes = value.to_le_bytes(); - constant( - code, - xmm, - core::array::from_fn(|i| bytes[i % usize::from(lane)]), - ); -} -fn arithmetic(lane: u8, sub: bool) -> Host { - match (sub, lane) { - (false, 1) => Host::AddByte, - (false, 2) => Host::AddWord, - (false, 4) => Host::AddDword, - (false, 8) => Host::AddQword, - (true, 1) => Host::SubByte, - (true, 2) => Host::SubWord, - (true, 4) => Host::SubDword, - (true, 8) => Host::SubQword, - _ => unreachable!("reviewed lane width"), - } -} -pub(super) fn sign_mask(code: &mut Vec, destination: u8, source: u8, lane: u8) { +pub(super) fn sign_mask(code: &mut Code, destination: u8, source: u8, lane: u8) { if lane == 1 { packed(code, Host::Xor, destination, destination); packed(code, Host::GreaterByte, destination, source); @@ -46,7 +27,7 @@ pub(super) fn sign_mask(code: &mut Vec, destination: u8, source: u8, lane: u } } /// XMM0=a, XMM1=b, XMM2=wrapped a+b; produce the unsigned carry mask in XMM4. -fn unsigned_carry(code: &mut Vec, lane: u8) { +fn unsigned_carry(code: &mut Code, lane: u8) { packed(code, Host::MoveAligned, 3, 0); packed(code, Host::And, 3, 1); packed(code, Host::MoveAligned, 4, 0); @@ -57,15 +38,15 @@ fn unsigned_carry(code: &mut Vec, lane: u8) { sign_mask(code, 4, 3, lane); } /// Merge wrapped XMM2 and clamping bound XMM5 using saturation mask XMM4. -fn clamp_result(code: &mut Vec) { +fn clamp_result(code: &mut Code) { packed(code, Host::Xor, 5, 2); packed(code, Host::And, 5, 4); packed(code, Host::Xor, 2, 5); packed(code, Host::MoveAligned, 0, 2); } -pub(super) fn add_sub(code: &mut Vec, lane: u8, signed: bool, sub: bool) { +pub(super) fn add_sub(code: &mut Code, lane: u8, signed: bool, sub: bool) { packed(code, Host::MoveAligned, 2, 0); - packed(code, arithmetic(lane, sub), 2, 1); + packed(code, add_or_subtract(lane, sub), 2, 1); if lane <= 2 { let opcode = match (signed, sub, lane) { (true, false, 1) => Host::AddSignedSaturatingByte, @@ -117,7 +98,7 @@ pub(super) fn add_sub(code: &mut Vec, lane: u8, signed: bool, sub: bool) { packed(code, Host::MoveAligned, 0, 5); } } -fn absolute_or_negate(code: &mut Vec, lane: u8, negate: bool, target: TargetCpu) { +fn absolute_or_negate(code: &mut Code, lane: u8, negate: bool, target: TargetCpu) { lane_constant(code, 4, lane, 1u64 << (lane * 8 - 1)); packed( code, @@ -136,7 +117,7 @@ fn absolute_or_negate(code: &mut Vec, lane: u8, negate: bool, target: Target } if negate { packed(code, Host::Xor, 1, 1); - packed(code, arithmetic(lane, true), 1, 0); + packed(code, add_or_subtract(lane, true), 1, 0); packed(code, Host::MoveAligned, 0, 1); } else if lane <= 4 && target >= TargetCpu::Ssse3 { match lane { @@ -149,12 +130,12 @@ fn absolute_or_negate(code: &mut Vec, lane: u8, negate: bool, target: Target } else { sign_mask(code, 1, 0, lane); packed(code, Host::Xor, 0, 1); - packed(code, arithmetic(lane, true), 0, 1); + packed(code, add_or_subtract(lane, true), 0, 1); } // Wrapped -MIN/ABS(MIN) is MIN: adding the all-one mask produces MAX. - packed(code, arithmetic(lane, false), 0, 4); + packed(code, add_or_subtract(lane, false), 0, 4); } -fn mixed_add(code: &mut Vec, lane: u8, unsigned_result: bool) { +fn mixed_add(code: &mut Code, lane: u8, unsigned_result: bool) { if !unsigned_result { lane_constant(code, 5, lane, 1u64 << (lane * 8 - 1)); packed(code, Host::Xor, 0, 5); @@ -164,7 +145,7 @@ fn mixed_add(code: &mut Vec, lane: u8, unsigned_result: bool) { } else { sign_mask(code, 6, 1, lane); packed(code, Host::MoveAligned, 2, 0); - packed(code, arithmetic(lane, false), 2, 1); + packed(code, add_or_subtract(lane, false), 2, 1); unsigned_carry(code, lane); packed(code, Host::Xor, 4, 6); packed(code, Host::EqualDword, 5, 5); @@ -176,7 +157,7 @@ fn mixed_add(code: &mut Vec, lane: u8, unsigned_result: bool) { /// Clamp the wide source lanes. XMM6 holds the upper-bound mask across the /// second comparison; the compare recipe uses only XMM0-4 and XMM7. fn narrow( - code: &mut Vec, + code: &mut Code, operand: &Operand, unsigned_source: bool, unsigned_result: bool, @@ -231,26 +212,35 @@ fn narrow( _ => unreachable!("allocated narrowing width"), } } -pub(super) fn publish_qc(code: &mut Vec, active_bytes: u8) { +pub(super) fn publish_qc(code: &mut Code, active_bytes: u8) { Host::ByteSignMask.register(code, 1, 4, TargetCpu::Baseline); // pmovmskb ecx,xmm4 - code.extend([0x81, 0xe1]); // AND ECX, active byte mask: inactive lanes cannot set QC - code.extend(((1u32 << active_bytes) - 1).to_le_bytes()); - code.extend([ - 0x0f, - 0x95, - 0xc1, - 0x0f, - 0xb6, - 0xc9, - 0xc1, - 0xe1, + use Gpr::Rcx; + let mut asm = code.asm(); + // The active byte mask: inactive lanes cannot set QC. + asm.alu_imm32( + Alu::And, + Size::Dword, + Rcx, + ((1u32 << active_bytes) - 1) as i32, + ); + asm.setcc(Cond::Ne, Rcx); + asm.movzx(Size::Dword, Rcx, Size::Byte, Rcx); + asm.shift_imm( + ShiftOp::Shl, + Size::Dword, + Rcx, FPSR_QC.trailing_zeros() as u8, - ]); // setne cl; movzx ecx,cl; shl ecx,QC - code.extend([0x09, 0x8f]); // or [rdi+FPSR],ecx: sticky QC, preserve every other bit - code.extend((core::mem::offset_of!(GuestState, fpsr) as u32).to_le_bytes()); + ); + // Sticky QC, preserving every other bit. + asm.alu( + Alu::Or, + Size::Dword, + guest(core::mem::offset_of!(GuestState, fpsr) as u32), + Rcx, + ); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { let Operand { kind, destination, diff --git a/crates/stela-compiler/src/x86_64/simd/sha1.rs b/crates/stela-compiler/src/x86_64/simd/sha1.rs index f97ac864a0..fdae3a7d79 100644 --- a/crates/stela-compiler/src/x86_64/simd/sha1.rs +++ b/crates/stela-compiler/src/x86_64/simd/sha1.rs @@ -4,12 +4,12 @@ use super::sha32::{ move_to_vector, pack_state, read_scalar_vector, }; use super::{Host, commit, packed, read_vector, shuffle}; +use crate::x86_64::asm::Code; use crate::{ TargetCpu, aarch64::simd::sha1::{Kind, Operand}, x86_64::isa::ShiftOpcode as Shift, }; -use alloc::vec::Vec; const EAX: u8 = 0; const ECX: u8 = 1; @@ -35,14 +35,13 @@ const MAJORITY_FUNCTION: u8 = 2; const REVERSE_DWORDS: u8 = 0x1b; const SWAP_QWORDS: u8 = 0x4e; const BROADCAST_LOW_DWORD: u8 = 0; -const MOV_EAX_IMM32: u8 = 0xb8; // Intel SHA1RNDS4's immediate selects these FIPS 180-4 section 4.2.1 constants. // Arm's message operand already contains whatever round constants it requires. const CHOOSE_CONSTANT: u32 = 0x5a827999; const PARITY_CONSTANT: u32 = 0x6ed9eba1; const MAJORITY_CONSTANT: u32 = 0x8f1bbcdc; -fn rounds_baseline(code: &mut Vec, operand: &Operand) { +fn rounds_baseline(code: &mut Code, operand: &Operand) { use Scalar32::*; let mut state = [EAX, ECX, EDX, ESI, R8D]; for (lane, register) in state[..WORDS_PER_VECTOR].iter().enumerate() { @@ -85,7 +84,7 @@ fn rounds_baseline(code: &mut Vec, operand: &Operand) { pack_state(code, [state[0], state[1], state[2], state[3]]); } -fn rounds_sha(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn rounds_sha(code: &mut Code, operand: &Operand, target: TargetCpu) { let (function, constant) = match operand.kind { Kind::Choose => (CHOOSE_FUNCTION, CHOOSE_CONSTANT), Kind::Parity => (PARITY_FUNCTION, PARITY_CONSTANT), @@ -97,19 +96,17 @@ fn rounds_sha(code: &mut Vec, operand: &Operand, target: TargetCpu) { // MOVD reads only Sn[31:0], zeros its upper lanes, and adds E to W0 only. read_scalar_vector(code, LEFT, operand.left); packed(code, Host::AddDword, RIGHT, LEFT); - code.push(MOV_EAX_IMM32); - code.extend(constant.to_le_bytes()); + code.asm().mov_imm32(crate::x86_64::asm::Gpr::Rax, constant); move_to_vector(code, TEMPORARY, EAX); shuffle(code, TEMPORARY, TEMPORARY, BROADCAST_LOW_DWORD); packed(code, Host::SubDword, RIGHT, TEMPORARY); // cancel Intel's built-in K in all rounds shuffle(code, RESULT, RESULT, REVERSE_DWORDS); shuffle(code, RIGHT, RIGHT, REVERSE_DWORDS); - Host::Sha1Rounds4.register(code, RESULT, RIGHT, target); - code.push(function); + Host::Sha1Rounds4.register_imm(code, RESULT, RIGHT, function, target); shuffle(code, RESULT, RESULT, REVERSE_DWORDS); } -fn schedule0(code: &mut Vec, operand: &Operand) { +fn schedule0(code: &mut Code, operand: &Operand) { read_vector(code, operand.destination, RESULT); read_vector(code, operand.left, LEFT); read_vector(code, operand.right, RIGHT); @@ -119,13 +116,13 @@ fn schedule0(code: &mut Vec, operand: &Operand) { packed(code, Host::Xor, RESULT, TEMPORARY); packed(code, Host::Xor, RESULT, RIGHT); } -fn rotate_lanes(code: &mut Vec, vector: u8, temporary: u8, amount: u8) { +fn rotate_lanes(code: &mut Code, vector: u8, temporary: u8, amount: u8) { packed(code, Host::MoveAligned, temporary, vector); Shift::LeftDword.emit(code, vector, amount); Shift::RightDword.emit(code, temporary, WORD_BITS - amount); packed(code, Host::Or, vector, temporary); } -fn schedule1(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn schedule1(code: &mut Code, operand: &Operand, target: TargetCpu) { read_vector(code, operand.destination, RESULT); read_vector(code, operand.left, LEFT); if target.supports(TargetCpu::Sha) { @@ -144,7 +141,7 @@ fn schedule1(code: &mut Vec, operand: &Operand, target: TargetCpu) { } } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { match operand.kind { Kind::Choose | Kind::Parity | Kind::Majority => { if target.supports(TargetCpu::Sha) { @@ -167,7 +164,6 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; #[test] fn baseline_has_no_sha_and_checked_rounds_cancel_the_selected_constant() { @@ -182,10 +178,10 @@ mod tests { left: 31, right: 31, }; - let mut baseline = Vec::new(); + let mut baseline = Code::new(); emit(&mut baseline, &operand, TargetCpu::Baseline); assert!(!baseline.windows(3).any(|w| w == [0x0f, 0x3a, 0xcc])); - let mut checked = Vec::new(); + let mut checked = Code::new(); emit(&mut checked, &operand, TargetCpu::Sha); assert!(checked.windows(3).any(|w| w == [0x0f, 0x3a, 0xcc])); assert!(checked.windows(4).any(|w| w == constant.to_le_bytes())); diff --git a/crates/stela-compiler/src/x86_64/simd/sha256.rs b/crates/stela-compiler/src/x86_64/simd/sha256.rs index 8298e70087..f8057857df 100644 --- a/crates/stela-compiler/src/x86_64/simd/sha256.rs +++ b/crates/stela-compiler/src/x86_64/simd/sha256.rs @@ -5,12 +5,13 @@ use super::sha32::{ WORDS_PER_VECTOR, pack_state, }; use super::{Host, commit, packed, read_vector, shuffle}; +use crate::x86_64::asm::Code; +use crate::x86_64::simd::encode::gpr; use crate::{ TargetCpu, aarch64::simd::sha256::{Kind, Operand}, x86_64::isa::ShiftOpcode as Shift, }; -use alloc::vec::Vec; const EAX: u8 = 0; const ECX: u8 = 1; @@ -30,35 +31,26 @@ const SIGMA_TEMPORARY: u8 = 4; const SAVED_RBX: u8 = 4; const SAVED_RBP: u8 = 5; const SAVED_R12: u8 = 6; -const LOW_REGISTER_MASK: u8 = 7; -const EXTENDED_REGISTER_SHIFT: u8 = 3; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MODRM_REGISTER: u8 = 0xc0; const REVERSE_DWORDS: u8 = 0x1b; const REVERSE_DWORD_PAIRS: u8 = 0xb1; -const MOVQ_XMM_RM64: [u8; 2] = [0x0f, 0x6e]; -const MOVQ_RM64_XMM: [u8; 2] = [0x0f, 0x7e]; -const PACKED_PREFIX: u8 = 0x66; -const REX_W: u8 = 0x48; const BIG_SIGMA0: [u8; 3] = [2, 13, 22]; const BIG_SIGMA1: [u8; 3] = [6, 11, 25]; const SMALL_SIGMA0: [u8; 3] = [7, 18, 3]; const SMALL_SIGMA1: [u8; 3] = [17, 19, 10]; -fn preserve_scratch(code: &mut Vec, restore: bool) { +fn preserve_scratch(code: &mut Code, restore: bool) { // Full host RBX/RBP/R12 values stay in SysV caller-saved XMM4..6. // No host stack or guest RAM is touched; these XMMs survive the scalar body. for (xmm, register) in [(SAVED_RBX, EBX), (SAVED_RBP, EBP), (SAVED_R12, R12D)] { - code.extend([PACKED_PREFIX, REX_W | (register >> EXTENDED_REGISTER_SHIFT)]); - code.extend(if restore { - MOVQ_RM64_XMM + let mut asm = code.asm(); + if restore { + asm.movq_from_xmm(gpr(register), xmm); } else { - MOVQ_XMM_RM64 - }); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) | (register & LOW_REGISTER_MASK)); + asm.movq_to_xmm(xmm, gpr(register)); + } } } -fn big_sigma(code: &mut Vec, input: u8, result: u8, temporary: u8, amounts: [u8; 3]) { +fn big_sigma(code: &mut Code, input: u8, result: u8, temporary: u8, amounts: [u8; 3]) { Scalar32::Move.register(code, result, input); Rotate32::Right.emit(code, result, amounts[0]); for amount in &amounts[1..] { @@ -67,7 +59,7 @@ fn big_sigma(code: &mut Vec, input: u8, result: u8, temporary: u8, amounts: Scalar32::Xor.register(code, result, temporary); } } -fn rounds_baseline(code: &mut Vec, operand: &Operand) { +fn rounds_baseline(code: &mut Code, operand: &Operand) { use Scalar32::*; preserve_scratch(code, false); let (x, y) = if operand.kind == Kind::Hash { @@ -115,7 +107,7 @@ fn rounds_baseline(code: &mut Vec, operand: &Operand) { pack_state(code, [part[0], part[1], part[2], part[3]]); preserve_scratch(code, true); } -fn rounds_sha(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn rounds_sha(code: &mut Code, operand: &Operand, target: TargetCpu) { let (x, y) = if operand.kind == Kind::Hash { (operand.destination, operand.left) } else { @@ -145,7 +137,7 @@ fn rounds_sha(code: &mut Vec, operand: &Operand, target: TargetCpu) { shuffle(code, RESULT, TEMPORARY, REVERSE_DWORD_PAIRS); } -fn small_sigma(code: &mut Vec, input: u8, result: u8, temporary: u8, amounts: [u8; 3]) { +fn small_sigma(code: &mut Code, input: u8, result: u8, temporary: u8, amounts: [u8; 3]) { // Two rotates and a logical shift are a linear XOR of five shifted copies. // Destructively consume input for the final shift, avoiding a sixth copy. packed(code, Host::MoveAligned, result, input); @@ -164,7 +156,7 @@ fn small_sigma(code: &mut Vec, input: u8, result: u8, temporary: u8, amounts Shift::RightDword.emit(code, input, amounts[2]); packed(code, Host::Xor, result, input); } -fn schedule0(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn schedule0(code: &mut Code, operand: &Operand, target: TargetCpu) { read_vector(code, operand.destination, RESULT); read_vector(code, operand.left, LEFT); if target.supports(TargetCpu::Sha) { @@ -172,8 +164,7 @@ fn schedule0(code: &mut Vec, operand: &Operand, target: TargetCpu) { } else { if target.supports(TargetCpu::Ssse3) { packed(code, Host::MoveAligned, RIGHT, LEFT); - Host::AlignBytes.register(code, RIGHT, RESULT, target); - code.push(WORD_BYTES); // [d1,d2,d3,n0] + Host::AlignBytes.register_imm(code, RIGHT, RESULT, WORD_BYTES, target); // [d1,d2,d3,n0] } else { packed(code, Host::MoveAligned, RIGHT, RESULT); Shift::RightBytes.emit(code, RIGHT, WORD_BYTES); @@ -184,15 +175,14 @@ fn schedule0(code: &mut Vec, operand: &Operand, target: TargetCpu) { packed(code, Host::AddDword, RESULT, TEMPORARY); } } -fn schedule1(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn schedule1(code: &mut Code, operand: &Operand, target: TargetCpu) { read_vector(code, operand.destination, RESULT); read_vector(code, operand.left, LEFT); read_vector(code, operand.right, RIGHT); if target.supports(TargetCpu::Ssse3) { // Keep the M vector for schedule feedback and SHA256MSG2. packed(code, Host::MoveAligned, TEMPORARY, RIGHT); - Host::AlignBytes.register(code, TEMPORARY, LEFT, target); - code.push(WORD_BYTES); // [n1,n2,n3,m0] + Host::AlignBytes.register_imm(code, TEMPORARY, LEFT, WORD_BYTES, target); // [n1,n2,n3,m0] packed(code, Host::AddDword, RESULT, TEMPORARY); } else { Shift::RightBytes.emit(code, LEFT, WORD_BYTES); @@ -214,7 +204,7 @@ fn schedule1(code: &mut Vec, operand: &Operand, target: TargetCpu) { } } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { match operand.kind { Kind::Hash | Kind::Hash2 => { if target.supports(TargetCpu::Sha) { @@ -232,7 +222,6 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; #[test] fn schedule_gathers_require_ssse3_independently_of_sha() { @@ -249,7 +238,7 @@ mod tests { left: 31, right: 31, }; - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, target); let alignment = Host::AlignBytes.encoding(); let used = code @@ -271,29 +260,26 @@ mod tests { left: 31, right: 31, }; - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, TargetCpu::Sha); assert_eq!( code.windows(3).filter(|w| *w == [0x0f, 0x38, 0xcb]).count(), 2 ); - let mut baseline = Vec::new(); + let mut baseline = Code::new(); emit(&mut baseline, &operand, TargetCpu::Baseline); assert!(!baseline.windows(3).any(|w| w == [0x0f, 0x38, 0xcb])); // Full-width saves/restores cover every callee-saved GPR used. - for (xmm, register) in [(SAVED_RBX, EBX), (SAVED_RBP, EBP), (SAVED_R12, R12D)] { - for opcode in [MOVQ_XMM_RM64, MOVQ_RM64_XMM] { - let expected = [ - PACKED_PREFIX, - REX_W | (register >> EXTENDED_REGISTER_SHIFT), - opcode[0], - opcode[1], - MODRM_REGISTER - | (xmm << MODRM_REGISTER_SHIFT) - | (register & LOW_REGISTER_MASK), - ]; - assert!(baseline.windows(expected.len()).any(|w| w == expected)); - } + // movq xmm4/5/6, rbx/rbp/r12 and back. + for expected in [ + [0x66, 0x48, 0x0f, 0x6e, 0xe3], + [0x66, 0x48, 0x0f, 0x6e, 0xed], + [0x66, 0x49, 0x0f, 0x6e, 0xf4], + [0x66, 0x48, 0x0f, 0x7e, 0xe3], + [0x66, 0x48, 0x0f, 0x7e, 0xed], + [0x66, 0x49, 0x0f, 0x7e, 0xf4], + ] { + assert!(baseline.windows(expected.len()).any(|w| w == expected)); } } } diff --git a/crates/stela-compiler/src/x86_64/simd/sha3.rs b/crates/stela-compiler/src/x86_64/simd/sha3.rs index bd181585a5..4e93a1b8eb 100644 --- a/crates/stela-compiler/src/x86_64/simd/sha3.rs +++ b/crates/stela-compiler/src/x86_64/simd/sha3.rs @@ -1,10 +1,10 @@ //! EOR3, BCAX, RAX1 and XAR with SSE2. -use super::{Host, commit, packed, read_vector}; +use super::{Host, commit, packed, packed_imm, read_vector}; +use crate::x86_64::asm::Code; use crate::{ aarch64::simd::sha3::{Kind, Operand}, x86_64::isa::ShiftOpcode, }; -use alloc::vec::Vec; const RESULT: u8 = 0; const SECOND: u8 = 1; @@ -19,12 +19,17 @@ const SWAP_DWORDS_IN_QWORDS: u8 = 0xb1; const ROTATE_WORDS_RIGHT_ONE: u8 = 0x39; const ROTATE_WORDS_RIGHT_THREE: u8 = 0x93; -fn rotate_right(code: &mut Vec, rotation: u8) { +fn rotate_right(code: &mut Code, rotation: u8) { match rotation { NO_ROTATION => {} DWORD_BITS => { - packed(code, Host::ShuffleDword, RESULT, RESULT); - code.push(SWAP_DWORDS_IN_QWORDS); + packed_imm( + code, + Host::ShuffleDword, + RESULT, + RESULT, + SWAP_DWORDS_IN_QWORDS, + ); } WORD_BITS | ROTATE_RIGHT_THREE_WORDS => { let selector = if rotation == WORD_BITS { @@ -33,8 +38,7 @@ fn rotate_right(code: &mut Vec, rotation: u8) { ROTATE_WORDS_RIGHT_THREE }; for opcode in [Host::ShuffleLowWord, Host::ShuffleHighWord] { - packed(code, opcode, RESULT, RESULT); - code.push(selector); + packed_imm(code, opcode, RESULT, RESULT, selector); } } _ => { @@ -46,7 +50,7 @@ fn rotate_right(code: &mut Vec, rotation: u8) { } } -pub(super) fn emit(code: &mut Vec, operand: &Operand) { +pub(super) fn emit(code: &mut Code, operand: &Operand) { match operand.kind { Kind::Eor3 { third } => { read_vector(code, operand.left, RESULT); @@ -87,7 +91,6 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { mod tests { use super::*; use alloc::vec; - use alloc::vec::Vec; #[test] fn staging_cost_accounts_for_complete_state_access_and_immediate_specializations() { @@ -101,7 +104,7 @@ mod tests { (Kind::Xar { rotation: 48 }, 38), (Kind::Xar { rotation: 63 }, 46), ] { - let mut code = Vec::new(); + let mut code = Code::new(); emit( &mut code, &Operand { diff --git a/crates/stela-compiler/src/x86_64/simd/sha32.rs b/crates/stela-compiler/src/x86_64/simd/sha32.rs index e1514c483c..aa393cf8eb 100644 --- a/crates/stela-compiler/src/x86_64/simd/sha32.rs +++ b/crates/stela-compiler/src/x86_64/simd/sha32.rs @@ -1,6 +1,7 @@ //! 32-bit lane encodings shared by the SHA1 and SHA256 recipes. use super::{Host, packed, vector_offset}; -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Rm, ShiftOp, Size}; +use crate::x86_64::simd::encode::{gpr, guest}; pub(super) const WORD_BITS: u8 = 32; pub(super) const WORD_BYTES: u8 = WORD_BITS / 8; @@ -10,19 +11,6 @@ pub(super) const HIGH_WORD_BYTE: u8 = WORD_BYTES * 3; pub(super) const RESULT: u8 = 0; const PACK_PAIR: u8 = 1; const PACK_LAST: u8 = 2; -const LOW_REGISTER_MASK: u8 = 7; -const EXTENDED_REGISTER_SHIFT: u8 = 3; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_STATE_DISPLACEMENT: u8 = 0x87; // [rdi+disp32] -const REX_BASE: u8 = 0x40; -const REX_REGISTER_SHIFT: u8 = 2; -const NO_EXTENDED_OPERAND: u8 = 0; -const PACKED_PREFIX: u8 = 0x66; -const MOVD_XMM_RM32: [u8; 2] = [0x0f, 0x6e]; -const ROTATE_IMMEDIATE: u8 = 0xc1; -const ROL_GROUP: u8 = 0; -const ROR_GROUP: u8 = 1; #[derive(Clone, Copy)] pub(super) enum Scalar32 { @@ -33,41 +21,24 @@ pub(super) enum Scalar32 { Or, } impl Scalar32 { - fn opcode(self) -> u8 { - match self { - Self::Move => 0x8b, - Self::Add => 0x03, - Self::Xor => 0x33, - Self::And => 0x23, - Self::Or => 0x0b, - } + /// `op destination, rm` in the load direction. + fn emit(self, code: &mut Code, destination: u8, rm: Rm) { + let mut asm = code.asm(); + let op = match self { + Self::Move => return asm.mov_load(Size::Dword, gpr(destination), rm), + Self::Add => Alu::Add, + Self::Xor => Alu::Xor, + Self::And => Alu::And, + Self::Or => Alu::Or, + }; + asm.alu_load(op, Size::Dword, gpr(destination), rm); } - pub(super) fn register(self, code: &mut Vec, destination: u8, source: u8) { - rex(code, destination, source); - code.extend([ - self.opcode(), - MODRM_REGISTER - | ((destination & LOW_REGISTER_MASK) << MODRM_REGISTER_SHIFT) - | (source & LOW_REGISTER_MASK), - ]); + pub(super) fn register(self, code: &mut Code, destination: u8, source: u8) { + self.emit(code, destination, Rm::Reg(gpr(source))); } - pub(super) fn state(self, code: &mut Vec, destination: u8, vector: u8, lane: u8) { - rex(code, destination, NO_EXTENDED_OPERAND); - code.extend([ - self.opcode(), - MODRM_STATE_DISPLACEMENT | ((destination & LOW_REGISTER_MASK) << MODRM_REGISTER_SHIFT), - ]); - code.extend( - (vector_offset(vector) + u32::from(lane) * u32::from(WORD_BYTES)).to_le_bytes(), - ); - } -} -fn rex(code: &mut Vec, destination: u8, source: u8) { - let prefix = REX_BASE - | ((destination >> EXTENDED_REGISTER_SHIFT) << REX_REGISTER_SHIFT) - | (source >> EXTENDED_REGISTER_SHIFT); - if prefix != REX_BASE { - code.push(prefix); + pub(super) fn state(self, code: &mut Code, destination: u8, vector: u8, lane: u8) { + let offset = vector_offset(vector) + u32::from(lane) * u32::from(WORD_BYTES); + self.emit(code, destination, Rm::Mem(guest(offset))); } } @@ -76,34 +47,22 @@ pub(super) enum Rotate32 { Right, } impl Rotate32 { - pub(super) fn emit(self, code: &mut Vec, register: u8, amount: u8) { - rex(code, NO_EXTENDED_OPERAND, register); - let group = match self { - Self::Left => ROL_GROUP, - Self::Right => ROR_GROUP, + pub(super) fn emit(self, code: &mut Code, register: u8, amount: u8) { + let op = match self { + Self::Left => ShiftOp::Rol, + Self::Right => ShiftOp::Ror, }; - code.extend([ - ROTATE_IMMEDIATE, - MODRM_REGISTER | (group << MODRM_REGISTER_SHIFT) | (register & LOW_REGISTER_MASK), - amount, - ]); + code.asm().shift_imm(op, Size::Dword, gpr(register), amount); } } -pub(super) fn move_to_vector(code: &mut Vec, xmm: u8, register: u8) { - code.push(PACKED_PREFIX); - rex(code, xmm, register); - code.extend(MOVD_XMM_RM32); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) | (register & LOW_REGISTER_MASK)); +pub(super) fn move_to_vector(code: &mut Code, xmm: u8, register: u8) { + code.asm().movd_to_xmm(xmm, gpr(register)); } -pub(super) fn read_scalar_vector(code: &mut Vec, xmm: u8, vector: u8) { - code.push(PACKED_PREFIX); - rex(code, xmm, NO_EXTENDED_OPERAND); - code.extend(MOVD_XMM_RM32); - code.push(MODRM_STATE_DISPLACEMENT | (xmm << MODRM_REGISTER_SHIFT)); - code.extend(vector_offset(vector).to_le_bytes()); +pub(super) fn read_scalar_vector(code: &mut Code, xmm: u8, vector: u8) { + code.asm().movd_to_xmm(xmm, guest(vector_offset(vector))); } /// Pack four zero-extended words into RESULT; PACK_PAIR/PACK_LAST are scratch. -pub(super) fn pack_state(code: &mut Vec, words: [u8; WORDS_PER_VECTOR]) { +pub(super) fn pack_state(code: &mut Code, words: [u8; WORDS_PER_VECTOR]) { move_to_vector(code, RESULT, words[0]); move_to_vector(code, PACK_PAIR, words[1]); packed(code, Host::UnpackLowDword, RESULT, PACK_PAIR); diff --git a/crates/stela-compiler/src/x86_64/simd/sha512.rs b/crates/stela-compiler/src/x86_64/simd/sha512.rs index e60cd4f68f..b72cf4b23c 100644 --- a/crates/stela-compiler/src/x86_64/simd/sha512.rs +++ b/crates/stela-compiler/src/x86_64/simd/sha512.rs @@ -1,11 +1,12 @@ //! SHA512: scalar large sigmas and packed small sigmas. use super::{Host, commit, packed, read_vector, shuffle, vector_offset}; +use crate::x86_64::asm::{Alu, Code, Gpr, ShiftOp, Size}; +use crate::x86_64::simd::encode::guest; use crate::{ TargetCpu, aarch64::simd::sha512::{Kind, Operand}, x86_64::isa::ShiftOpcode as Shift, }; -use alloc::vec::Vec; const QWORD_BITS: u8 = 64; const QWORD_BYTES: u32 = 8; @@ -26,19 +27,6 @@ const LARGE_SIGMA0_ROTATIONS: [u8; 3] = [28, 34, 39]; const LARGE_SIGMA1_ROTATIONS: [u8; 3] = [14, 18, 41]; // Only caller-saved registers; RDI remains the GuestState pointer. -#[derive(Clone, Copy)] -#[repr(u8)] -enum Gpr { - Rax = 0, - Rcx = 1, - Rdx = 2, - Rsi = 6, - R8 = 8, - R9 = 9, - R10 = 10, - R11 = 11, -} - const W0: Gpr = Gpr::Rax; const W1: Gpr = Gpr::Rcx; const X0: Gpr = Gpr::Rdx; @@ -48,67 +36,46 @@ const Y1: Gpr = Gpr::R9; const VALUE: Gpr = Gpr::R10; const SIGMA: Gpr = Gpr::R11; -const REX_W: u8 = 0x48; -const REX_R: u8 = 0x04; -const REX_B: u8 = 0x01; -const REGISTER_LOW_MASK: u8 = 7; -const MODRM_REGISTER_SHIFT: u8 = 3; -const REGISTER_DIRECT: u8 = 0xc0; -const STATE_DISPLACEMENT: u8 = 0x87; // mod=10, base=RDI -const QWORD_LOAD: u8 = 0x8b; -const QWORD_STORE: u8 = 0x89; -const SHIFT_IMMEDIATE: u8 = 0xc1; -const ROTATE_RIGHT_GROUP: u8 = 1 << MODRM_REGISTER_SHIFT; - -/// Baseline REX.W register/register instructions, destination in ModRM:r/m. +/// Baseline 64-bit register/register instructions. #[derive(Clone, Copy)] -#[repr(u8)] enum QwordOpcode { - Add = 0x01, - Or = 0x09, - And = 0x21, - Xor = 0x31, - Move = 0x89, + Add, + Or, + And, + Xor, + Move, } impl QwordOpcode { - fn emit(self, code: &mut Vec, destination: Gpr, source: Gpr) { - let destination = destination as u8; - let source = source as u8; - let rex = - REX_W | if source >= 8 { REX_R } else { 0 } | if destination >= 8 { REX_B } else { 0 }; - code.extend([ - rex, - self as u8, - REGISTER_DIRECT - | ((source & REGISTER_LOW_MASK) << MODRM_REGISTER_SHIFT) - | (destination & REGISTER_LOW_MASK), - ]); + fn emit(self, code: &mut Code, destination: Gpr, source: Gpr) { + let mut asm = code.asm(); + let op = match self { + Self::Add => Alu::Add, + Self::Or => Alu::Or, + Self::And => Alu::And, + Self::Xor => Alu::Xor, + Self::Move => return asm.mov(Size::Qword, destination, source), + }; + asm.alu(op, Size::Qword, destination, source); } } -fn state_qword(code: &mut Vec, vector: u8, lane: u32, register: Gpr, load: bool) { - let register = register as u8; - code.extend([ - REX_W | if register >= 8 { REX_R } else { 0 }, - if load { QWORD_LOAD } else { QWORD_STORE }, - STATE_DISPLACEMENT | ((register & REGISTER_LOW_MASK) << MODRM_REGISTER_SHIFT), - ]); - code.extend((vector_offset(vector) + lane * QWORD_BYTES).to_le_bytes()); +fn state_qword(code: &mut Code, vector: u8, lane: u32, register: Gpr, load: bool) { + let memory = guest(vector_offset(vector) + lane * QWORD_BYTES); + if load { + code.asm().mov_load(Size::Qword, register, memory); + } else { + code.asm().mov_store(Size::Qword, memory, register); + } } -fn rotate(code: &mut Vec, destination: Gpr, amount: u8) { - let register = destination as u8; - code.extend([ - REX_W | if register >= 8 { REX_B } else { 0 }, - SHIFT_IMMEDIATE, - REGISTER_DIRECT | ROTATE_RIGHT_GROUP | (register & REGISTER_LOW_MASK), - amount, - ]); +fn rotate(code: &mut Code, destination: Gpr, amount: u8) { + code.asm() + .shift_imm(ShiftOp::Ror, Size::Qword, destination, amount); } fn large_sigma( - code: &mut Vec, + code: &mut Code, destination: Gpr, source: Gpr, scratch: [Gpr; 2], @@ -128,14 +95,14 @@ fn large_sigma( QwordOpcode::Xor.emit(code, destination, second); } -fn choose(code: &mut Vec, destination: Gpr, selector: Gpr, yes: Gpr, no: Gpr) { +fn choose(code: &mut Code, destination: Gpr, selector: Gpr, yes: Gpr, no: Gpr) { QwordOpcode::Move.emit(code, destination, yes); QwordOpcode::Xor.emit(code, destination, no); QwordOpcode::And.emit(code, destination, selector); QwordOpcode::Xor.emit(code, destination, no); } -fn majority(code: &mut Vec, destination: Gpr, scratch: Gpr, x: Gpr, y: Gpr, z: Gpr) { +fn majority(code: &mut Code, destination: Gpr, scratch: Gpr, x: Gpr, y: Gpr, z: Gpr) { QwordOpcode::Move.emit(code, destination, x); QwordOpcode::And.emit(code, destination, y); QwordOpcode::Move.emit(code, scratch, x); @@ -144,7 +111,7 @@ fn majority(code: &mut Vec, destination: Gpr, scratch: Gpr, x: Gpr, y: Gpr, QwordOpcode::Or.emit(code, destination, scratch); } -fn hash(code: &mut Vec, operand: &Operand, second: bool) { +fn hash(code: &mut Code, operand: &Operand, second: bool) { let right = operand.right.expect("three-register SHA512 hash form"); // Stage every needed qword before either destination store, so the high // result can be stored before the low one is computed even when all three @@ -195,7 +162,7 @@ fn hash(code: &mut Vec, operand: &Operand, second: bool) { } } -fn packed_rotate(code: &mut Vec, destination: u8, scratch: u8, source: u8, amount: u8) { +fn packed_rotate(code: &mut Code, destination: u8, scratch: u8, source: u8, amount: u8) { packed(code, Host::MoveAligned, destination, source); Shift::RightQword.emit(code, destination, amount); packed(code, Host::MoveAligned, scratch, source); @@ -203,7 +170,7 @@ fn packed_rotate(code: &mut Vec, destination: u8, scratch: u8, source: u8, a packed(code, Host::Or, destination, scratch); } -fn small_sigma(code: &mut Vec, rotations: [u8; 2], shift: u8) { +fn small_sigma(code: &mut Code, rotations: [u8; 2], shift: u8) { // XMM2 holds both independent sigma inputs. XMM0/1 retain old W/Y. packed_rotate( code, @@ -224,7 +191,7 @@ fn small_sigma(code: &mut Vec, rotations: [u8; 2], shift: u8) { packed(code, Host::Xor, SIGMA_OUTPUT_XMM, SIGMA_INPUT_XMM); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, _target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, _target: TargetCpu) { match operand.kind { Kind::Hash | Kind::Hash2 => hash(code, operand, operand.kind == Kind::Hash2), Kind::Schedule0 => { @@ -260,11 +227,10 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, _target: TargetCpu) { #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; #[test] fn scoped_qword_encodings_keep_rex_operand_roles_and_state_base() { - let mut code = Vec::new(); + let mut code = Code::new(); QwordOpcode::Move.emit(&mut code, Gpr::R10, Gpr::Rdx); QwordOpcode::And.emit(&mut code, Gpr::R10, Gpr::R9); rotate(&mut code, Gpr::R11, 23); diff --git a/crates/stela-compiler/src/x86_64/simd/shifts.rs b/crates/stela-compiler/src/x86_64/simd/shifts.rs index 8dafa97bb9..325550a014 100644 --- a/crates/stela-compiler/src/x86_64/simd/shifts.rs +++ b/crates/stela-compiler/src/x86_64/simd/shifts.rs @@ -2,11 +2,14 @@ use super::{ Host, commit, greater, packed, read_vector, rearrange::constant, shuffle, vector_offset, }; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, ShiftOp, Size, Unary}; +use crate::x86_64::simd::encode::guest; use crate::{ TargetCpu, aarch64::simd::shifts::{Kind, Operand}, x86_64::isa::ShiftOpcode as Shift, }; +use Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdx}; use alloc::vec::Vec; const BITS_PER_BYTE: u8 = 8; @@ -14,7 +17,7 @@ const VECTOR_BYTES: u8 = 16; const LOW_DWORDS_OF_QWORDS: u8 = 0x88; const HIGH_DWORDS_OF_QWORDS: u8 = 0xdd; -fn lane_mask(code: &mut Vec, xmm: u8, lane_bytes: u8, value: u64) { +fn lane_mask(code: &mut Code, xmm: u8, lane_bytes: u8, value: u64) { let bytes = value.to_le_bytes(); constant( code, @@ -22,7 +25,7 @@ fn lane_mask(code: &mut Vec, xmm: u8, lane_bytes: u8, value: u64) { core::array::from_fn(|i| bytes[i % usize::from(lane_bytes)]), ); } -fn add(code: &mut Vec, destination: u8, source: u8, lane_bytes: u8) { +fn add(code: &mut Code, destination: u8, source: u8, lane_bytes: u8) { packed( code, match lane_bytes { @@ -36,7 +39,7 @@ fn add(code: &mut Vec, destination: u8, source: u8, lane_bytes: u8) { source, ); } -pub(crate) fn logical_shift(code: &mut Vec, xmm: u8, lane_bytes: u8, amount: u8, left: bool) { +pub(crate) fn logical_shift(code: &mut Code, xmm: u8, lane_bytes: u8, amount: u8, left: bool) { if amount == 0 { return; } @@ -61,7 +64,7 @@ pub(crate) fn logical_shift(code: &mut Vec, xmm: u8, lane_bytes: u8, amount: packed(code, Host::And, xmm, 5); } } -pub(crate) fn right_shift(code: &mut Vec, xmm: u8, lane_bytes: u8, amount: u8, signed: bool) { +pub(crate) fn right_shift(code: &mut Code, xmm: u8, lane_bytes: u8, amount: u8, signed: bool) { if amount == 0 { return; } @@ -91,7 +94,7 @@ pub(crate) fn right_shift(code: &mut Vec, xmm: u8, lane_bytes: u8, amount: u } } pub(crate) fn rounded_right( - code: &mut Vec, + code: &mut Code, lane_bytes: u8, amount: u8, signed: bool, @@ -108,14 +111,7 @@ pub(crate) fn rounded_right( add(code, 0, 1, lane_bytes); } } -fn narrow( - code: &mut Vec, - lane_bytes: u8, - amount: u8, - round: bool, - upper: bool, - destination: u8, -) { +fn narrow(code: &mut Code, lane_bytes: u8, amount: u8, round: bool, upper: bool, destination: u8) { rounded_right(code, lane_bytes * 2, amount, false, round); pack_truncated(code, lane_bytes, upper, destination); } @@ -123,7 +119,7 @@ fn narrow( /// Shift first, then clamp. Rounding is computed as shifted value plus the /// discarded high bit, so signed overflow and unsigned carry are never lost. fn saturating_narrow( - code: &mut Vec, + code: &mut Code, operand: &Operand, signed_source: bool, unsigned_result: bool, @@ -192,7 +188,7 @@ fn saturating_narrow( /// with the shifted source derives QC without reimplementing the pack bounds. /// XMM6 retains the packed result and XMM4 receives the wide saturation mask. fn saturating_narrow_pack( - code: &mut Vec, + code: &mut Code, lane: u8, signed_source: bool, unsigned_result: bool, @@ -261,7 +257,7 @@ fn saturating_narrow_pack( /// SSE2 has no saturating qword pack. Compare both bounds before selecting /// clamped qwords; the checked SSE4.2 comparison replaces its baseline recipe. fn saturating_narrow_qword( - code: &mut Vec, + code: &mut Code, unsigned_result: bool, signed_source: bool, target: TargetCpu, @@ -301,7 +297,7 @@ fn saturating_narrow_qword( packed(code, Host::Or, 4, 6); shuffle(code, 6, 5, LOW_DWORDS_OF_QWORDS); } -pub(super) fn pack_truncated(code: &mut Vec, lane_bytes: u8, upper: bool, destination: u8) { +pub(super) fn pack_truncated(code: &mut Code, lane_bytes: u8, upper: bool, destination: u8) { match lane_bytes { 1 => { lane_mask(code, 2, 2, 0xff); @@ -327,7 +323,7 @@ pub(super) fn pack_truncated(code: &mut Vec, lane_bytes: u8, upper: bool, de commit(code, destination, 0); } } -fn widen(code: &mut Vec, lane_bytes: u8, amount: u8, signed: bool, upper: bool) { +fn widen(code: &mut Code, lane_bytes: u8, amount: u8, signed: bool, upper: bool) { if upper { Shift::RightBytes.emit(code, 0, 8); } @@ -359,7 +355,7 @@ fn widen(code: &mut Vec, lane_bytes: u8, amount: u8, signed: bool, upper: bo logical_shift(code, 0, lane_bytes * 2, amount, true); } -pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu) { let Operand { kind, destination, @@ -486,7 +482,7 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { /// results in XMM3 and the originals in XMM6; the sign bits of XMM4's active /// bytes set QC. fn saturating_immediate_vector( - code: &mut Vec, + code: &mut Code, operand: &Operand, signed_source: bool, unsigned_result: bool, @@ -578,7 +574,7 @@ fn saturating_immediate_vector( finish_immediate_vector(code, operand, 3); } -fn finish_immediate_vector(code: &mut Vec, operand: &Operand, result: u8) { +fn finish_immediate_vector(code: &mut Code, operand: &Operand, result: u8) { if operand.bytes == 8 { packed(code, Host::MoveQword, result, result); } @@ -594,17 +590,16 @@ enum LaneBranch { Above, AboveOrEqual, } -fn lane_branch(code: &mut Vec, condition: LaneBranch) -> usize { +fn lane_branch(code: &mut Code, condition: LaneBranch) -> usize { + let mut asm = code.asm(); match condition { - LaneBranch::Always => code.push(0xe9), - LaneBranch::Nonnegative => code.extend([0x0f, 0x89]), - LaneBranch::Equal => code.extend([0x0f, 0x84]), - LaneBranch::Above => code.extend([0x0f, 0x87]), - LaneBranch::AboveOrEqual => code.extend([0x0f, 0x83]), + LaneBranch::Always => asm.jmp(), + LaneBranch::Nonnegative => asm.jcc(Cond::Ns), + LaneBranch::Equal => asm.jcc(Cond::E), + LaneBranch::Above => asm.jcc(Cond::A), + LaneBranch::AboveOrEqual => asm.jcc(Cond::Ae), } - let patch = code.len(); - code.extend([0; 4]); - patch + .offset() } fn resolve_lane_branch(code: &mut [u8], patch: usize) { let relative = i32::try_from(code.len() - patch - 4).expect("lane recipe rel32"); @@ -618,46 +613,49 @@ enum LaneShift { } impl LaneShift { /// RAX or R10, count CL, baseline 64-bit shift group. - fn count(self, code: &mut Vec, r10: bool) { - let group = match self { - Self::Left => 4, - Self::LogicalRight => 5, - Self::ArithmeticRight => 7, + fn count(self, code: &mut Code, r10: bool) { + let op = match self { + Self::Left => ShiftOp::Shl, + Self::LogicalRight => ShiftOp::Shr, + Self::ArithmeticRight => ShiftOp::Sar, }; - code.extend([ - if r10 { 0x49 } else { 0x48 }, - 0xd3, - 0xc0 | (group << 3) | if r10 { 2 } else { 0 }, - ]); + code.asm() + .shift_cl(op, Size::Qword, if r10 { R10 } else { Rax }); } } -fn normalize_lane(code: &mut Vec, bits: u8, signed: bool) { +fn normalize_lane(code: &mut Code, bits: u8, signed: bool) { if bits < 64 { - code.extend([0x48, 0xc1, 0xe0, 64 - bits]); // shl rax,64-width - code.extend([0x48, 0xc1, if signed { 0xf8 } else { 0xe8 }, 64 - bits]); + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shl, Size::Qword, Rax, 64 - bits); + let right = if signed { ShiftOp::Sar } else { ShiftOp::Shr }; + asm.shift_imm(right, Size::Qword, Rax, 64 - bits); } } -fn load_shift_lane(code: &mut Vec, operand: &Operand, byte: u8, signed: bool) { +fn load_shift_lane(code: &mut Code, operand: &Operand, byte: u8, signed: bool) { + let lane = guest(vector_offset(operand.source) + u32::from(byte)); + let mut asm = code.asm(); match (operand.lane_bytes, signed) { - (1, false) => code.extend([0x0f, 0xb6, 0x87]), - (1, true) => code.extend([0x48, 0x0f, 0xbe, 0x87]), - (2, false) => code.extend([0x0f, 0xb7, 0x87]), - (2, true) => code.extend([0x48, 0x0f, 0xbf, 0x87]), - (4, false) => code.extend([0x8b, 0x87]), - (4, true) => code.extend([0x48, 0x63, 0x87]), - (8, _) => code.extend([0x48, 0x8b, 0x87]), + (1, false) => asm.movzx(Size::Dword, Rax, Size::Byte, lane), + (1, true) => asm.movsx(Size::Qword, Rax, Size::Byte, lane), + (2, false) => asm.movzx(Size::Dword, Rax, Size::Word, lane), + (2, true) => asm.movsx(Size::Qword, Rax, Size::Word, lane), + (4, false) => asm.mov_load(Size::Dword, Rax, lane), + (4, true) => asm.movsxd(Rax, lane), + (8, _) => asm.mov_load(Size::Qword, Rax, lane), _ => unreachable!("allocated shift lane"), } - code.extend((vector_offset(operand.source) + u32::from(byte)).to_le_bytes()); } -fn load_bound(code: &mut Vec, bound: u64) { - code.extend([0x48, 0xb8]); // movabs rax,bound - code.extend(bound.to_le_bytes()); +fn load_bound(code: &mut Code, bound: u64) { + code.asm().mov_imm64(Rax, bound); +} +/// `xor eax, eax`. +fn zero_lane(code: &mut Code) { + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); } /// CL is 1 to 128. Rounding adds CF from the last discarded bit instead of /// adding a bias that could overflow the qword. -fn register_right(code: &mut Vec, signed: bool, round: bool) { - code.extend([0x83, 0xf9, 64]); // cmp ecx,64 +fn register_right(code: &mut Code, signed: bool, round: bool) { + code.asm().alu_imm8(Alu::Cmp, Size::Dword, Rcx, 64); let large = lane_branch(code, LaneBranch::AboveOrEqual); if signed { LaneShift::ArithmeticRight @@ -666,28 +664,29 @@ fn register_right(code: &mut Vec, signed: bool, round: bool) { } .count(code, false); if round { - code.extend([0x48, 0x83, 0xd0, 0]); - } // adc rax,0 + code.asm().alu_imm8(Alu::Adc, Size::Qword, Rax, 0); + } let done = lane_branch(code, LaneBranch::Always); resolve_lane_branch(code, large); if signed && !round { - code.extend([0x48, 0xc1, 0xf8, 63]); // sign fill + // Sign fill. + code.asm().shift_imm(ShiftOp::Sar, Size::Qword, Rax, 63); } else if !signed && round { // At exactly 64 the rounded result is the source top bit. Above 64 // every unsigned 64-bit value rounds to zero. let beyond = lane_branch(code, LaneBranch::Above); - code.extend([0x48, 0xc1, 0xe8, 63]); + code.asm().shift_imm(ShiftOp::Shr, Size::Qword, Rax, 63); let end = lane_branch(code, LaneBranch::Always); resolve_lane_branch(code, beyond); - code.extend([0x31, 0xc0]); + zero_lane(code); resolve_lane_branch(code, end); } else { - code.extend([0x31, 0xc0]); + zero_lane(code); } resolve_lane_branch(code, done); } fn register_left( - code: &mut Vec, + code: &mut Code, bits: u8, signed_source: bool, unsigned_result: bool, @@ -696,31 +695,33 @@ fn register_left( let mut finished = Vec::new(); let mut negative_mixed = None; if saturating { - code.extend([0x48, 0x89, 0xc2]); - } // rdx=original + // RDX keeps the original. + code.asm().mov(Size::Qword, Rdx, Rax); + } if signed_source && unsigned_result { - code.extend([0x48, 0x85, 0xc0]); + code.asm().test(Size::Qword, Rax, Rax); let nonnegative = lane_branch(code, LaneBranch::Nonnegative); negative_mixed = Some(lane_branch(code, LaneBranch::Always)); resolve_lane_branch(code, nonnegative); } - code.extend([0x83, 0xf9, bits]); // cmp ecx,width + code.asm().alu_imm8(Alu::Cmp, Size::Dword, Rcx, bits as i8); let large = lane_branch(code, LaneBranch::AboveOrEqual); LaneShift::Left.count(code, false); if saturating { normalize_lane(code, bits, !unsigned_result); - code.extend([0x49, 0x89, 0xc2]); // mov r10,rax + code.asm().mov(Size::Qword, R10, Rax); if unsigned_result { LaneShift::LogicalRight } else { LaneShift::ArithmeticRight } .count(code, true); - code.extend([0x49, 0x39, 0xd2]); // cmp r10,rdx + code.asm().alu(Alu::Cmp, Size::Qword, R10, Rdx); finished.push(lane_branch(code, LaneBranch::Equal)); let clamp = lane_branch(code, LaneBranch::Always); resolve_lane_branch(code, large); - code.extend([0x48, 0x85, 0xc0]); // zero never saturates, even huge counts + // Zero never saturates, even for huge counts. + code.asm().test(Size::Qword, Rax, Rax); finished.push(lane_branch(code, LaneBranch::Equal)); resolve_lane_branch(code, clamp); if let Some(patch) = negative_mixed { @@ -733,7 +734,8 @@ fn register_left( }; load_bound(code, maximum); if signed_source { - code.extend([0x48, 0x85, 0xd2]); // original sign + // The original sign. + code.asm().test(Size::Qword, Rdx, Rdx); let positive = lane_branch(code, LaneBranch::Nonnegative); load_bound( code, @@ -745,13 +747,17 @@ fn register_left( ); resolve_lane_branch(code, positive); } - code.extend([0x81, 0x8f]); // or dword [rdi+fpsr],QC: sticky, other bits preserved - code.extend((core::mem::offset_of!(crate::GuestState, fpsr) as u32).to_le_bytes()); - code.extend(crate::aarch64::simd::saturating::FPSR_QC.to_le_bytes()); + // Sticky QC, other bits preserved. + code.asm().alu_imm32( + Alu::Or, + Size::Dword, + guest(core::mem::offset_of!(crate::GuestState, fpsr) as u32), + crate::aarch64::simd::saturating::FPSR_QC as i32, + ); } else { finished.push(lane_branch(code, LaneBranch::Always)); resolve_lane_branch(code, large); - code.extend([0x31, 0xc0]); + zero_lane(code); } for patch in finished { resolve_lane_branch(code, patch); @@ -763,40 +769,43 @@ fn register_left( /// both). A left count of 64 or more gives zero; a right count is clamped to /// 63, which fills with the sign (SSHL) or, below -63, is replaced by zero /// (USHL of a 64-bit lane). Narrower lanes are truncated by the caller. -fn register_plain(code: &mut Vec, signed: bool) { - const LEFT_LIMIT: u8 = 64; - const RIGHT_LIMIT: u8 = 63; - const RIGHT_ZERO: u8 = (-64i8) as u8; - code.extend([0x49, 0x89, 0xc2]); // mov r10,rax - code.extend([0x49, 0xd3, 0xe2]); // shl r10,cl - code.extend([0x31, 0xd2]); // xor edx,edx - code.extend([0x83, 0xf9, LEFT_LIMIT]); // cmp ecx,64 - code.extend([0x4c, 0x0f, 0x4d, 0xd2]); // cmovge r10,rdx - code.extend([0x89, 0xca, 0xf7, 0xda]); // mov edx,ecx; neg edx - code.extend([0x41, 0xbb]); // mov r11d,63 - code.extend(u32::from(RIGHT_LIMIT).to_le_bytes()); - code.extend([0x44, 0x39, 0xda]); // cmp edx,r11d - code.extend([0x41, 0x0f, 0x4f, 0xd3]); // cmovg edx,r11d - code.extend([0x41, 0x89, 0xcb]); // mov r11d,ecx: the signed count - code.extend([0x89, 0xd1]); // mov ecx,edx +fn register_plain(code: &mut Code, signed: bool) { + const LEFT_LIMIT: i8 = 64; + const RIGHT_LIMIT: u32 = 63; + const RIGHT_ZERO: i8 = -64; + let mut asm = code.asm(); + asm.mov(Size::Qword, R10, Rax); + asm.shift_cl(ShiftOp::Shl, Size::Qword, R10); + asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); + asm.alu_imm8(Alu::Cmp, Size::Dword, Rcx, LEFT_LIMIT); + asm.cmov(Cond::Ge, Size::Qword, R10, Rdx); + asm.mov(Size::Dword, Rdx, Rcx); + asm.unary(Unary::Neg, Size::Dword, Rdx); + asm.mov_imm32(R11, RIGHT_LIMIT); + asm.alu(Alu::Cmp, Size::Dword, Rdx, R11); + asm.cmov(Cond::G, Size::Dword, Rdx, R11); + // R11D keeps the signed count. + asm.mov(Size::Dword, R11, Rcx); + asm.mov(Size::Dword, Rcx, Rdx); if signed { LaneShift::ArithmeticRight } else { LaneShift::LogicalRight } .count(code, false); + let mut asm = code.asm(); if !signed { - code.extend([0x31, 0xd2]); // xor edx,edx - code.extend([0x41, 0x83, 0xfb, RIGHT_ZERO]); // cmp r11d,-64 - code.extend([0x48, 0x0f, 0x4e, 0xc2]); // cmovle rax,rdx + asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); + asm.alu_imm8(Alu::Cmp, Size::Dword, R11, RIGHT_ZERO); + asm.cmov(Cond::Le, Size::Qword, Rax, Rdx); } - code.extend([0x45, 0x85, 0xdb]); // test r11d,r11d - code.extend([0x49, 0x0f, 0x49, 0xc2]); // cmovns rax,r10 + asm.test(Size::Dword, R11, R11); + asm.cmov(Cond::Ns, Size::Qword, Rax, R10); } #[allow(clippy::too_many_arguments)] fn register_shift( - code: &mut Vec, + code: &mut Code, operand: &Operand, counts: Option, signed_source: bool, @@ -806,19 +815,27 @@ fn register_shift( ) { // R8/R9 hold staged result halves. Guest sources remain unchanged until both // have been consumed, including d=n=m and scalar inactive-lane poisoning. - code.extend([0x45, 0x31, 0xc0, 0x45, 0x31, 0xc9]); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, R8, R8); + asm.alu(Alu::Xor, Size::Dword, R9, R9); let bits = operand.lane_bytes * 8; for byte in (0..operand.bytes).step_by(usize::from(operand.lane_bytes)) { load_shift_lane(code, operand, byte, signed_source); if let Some(counts) = counts { - code.extend([0x0f, 0xbe, 0x8f]); // movsx ecx,byte [rdi+count lane] - code.extend((vector_offset(counts) + u32::from(byte)).to_le_bytes()); + // The count lane. + code.asm().movsx( + Size::Dword, + Rcx, + Size::Byte, + guest(vector_offset(counts) + u32::from(byte)), + ); if !round && !saturating { register_plain(code, signed_source); } else { - code.extend([0x85, 0xc9]); + code.asm().test(Size::Dword, Rcx, Rcx); let left = lane_branch(code, LaneBranch::Nonnegative); - code.extend([0xf7, 0xd9]); // neg ecx (signed byte -128 becomes +128) + // A signed byte -128 becomes +128. + code.asm().unary(Unary::Neg, Size::Dword, Rcx); register_right(code, signed_source, round); let merged = lane_branch(code, LaneBranch::Always); resolve_lane_branch(code, left); @@ -826,20 +843,24 @@ fn register_shift( resolve_lane_branch(code, merged); } } else { - code.push(0xb9); // mov ecx,imm32 - code.extend(u32::from(operand.amount).to_le_bytes()); + code.asm().mov_imm32(Rcx, u32::from(operand.amount)); register_left(code, bits, signed_source, unsigned_result, true); } normalize_lane(code, bits, false); + let mut asm = code.asm(); if byte % 8 != 0 { - code.extend([0x48, 0xc1, 0xe0, byte % 8 * 8]); + asm.shift_imm(ShiftOp::Shl, Size::Qword, Rax, byte % 8 * 8); } - code.extend([0x49, 0x09, if byte < 8 { 0xc0 } else { 0xc1 }]); // or r8/r9,rax + asm.alu(Alu::Or, Size::Qword, if byte < 8 { R8 } else { R9 }, Rax); } - code.extend([0x4c, 0x89, 0x87]); // commit both staged halves - code.extend(vector_offset(operand.destination).to_le_bytes()); - code.extend([0x4c, 0x89, 0x8f]); - code.extend((vector_offset(operand.destination) + 8).to_le_bytes()); + // Commit both staged halves. + let mut asm = code.asm(); + asm.mov_store(Size::Qword, guest(vector_offset(operand.destination)), R8); + asm.mov_store( + Size::Qword, + guest(vector_offset(operand.destination) + 8), + R9, + ); } #[cfg(test)] @@ -872,9 +893,9 @@ mod tests { amount: lane * BITS_PER_BYTE, bytes: if scalar { lane } else { VECTOR_BYTES }, }; - let mut code = vec![]; + let mut code = Code::new(); emit(&mut code, &operand, TargetCpu::Baseline); - let mut qc = vec![]; + let mut qc = Code::new(); Host::ByteSignMask.register(&mut qc, 1, 4, TargetCpu::Baseline); assert_eq!( code.windows(qc.len()).any(|w| w == qc), @@ -905,9 +926,9 @@ mod tests { amount: 1, bytes: if scalar { lane } else { VECTOR_BYTES }, }; - let mut code = vec![]; + let mut code = Code::new(); emit(&mut code, &operand, target); - let mut checked_pack = vec![]; + let mut checked_pack = Code::new(); Host::PackUnsignedDwordToWord.register( &mut checked_pack, 0, @@ -949,7 +970,7 @@ mod tests { continue; } for signed in [false, true] { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &immediate(lane, bytes, 0, signed), @@ -972,13 +993,13 @@ mod tests { (2, false, Host::AddUnsignedSaturatingWord), ] { for bytes in [8, 16] { - let mut code = vec![]; + let mut code = Code::new(); emit( &mut code, &immediate(lane, bytes, 1, signed), TargetCpu::Baseline, ); - let mut saturating_add = vec![]; + let mut saturating_add = Code::new(); packed(&mut saturating_add, opcode, 0, 0); assert!( code.windows(saturating_add.len()) @@ -1019,7 +1040,7 @@ mod tests { if matches!(kind, Kind::Right { .. }) { operand.amount = lane * 8; } - let mut code = vec![]; + let mut code = Code::new(); emit(&mut code, &operand, TargetCpu::Baseline); assert_eq!(code.len(), if bytes == 8 { 20 } else { 16 }); } diff --git a/crates/stela-compiler/src/x86_64/simd/sqrt.rs b/crates/stela-compiler/src/x86_64/simd/sqrt.rs index 15e862e071..9229d043bd 100644 --- a/crates/stela-compiler/src/x86_64/simd/sqrt.rs +++ b/crates/stela-compiler/src/x86_64/simd/sqrt.rs @@ -1,21 +1,23 @@ //! FSQRT: SSE2 for positive normals, software fallback otherwise. use super::super::isa::ShiftOpcode; use super::numerical::{ - ColdSplit, Condition, Entry, INPUT_MINIMUM_EXPONENT, Input, Rounding, VZEROUPPER, branch, - clear_scalar, commit_inexact, environment_round, positive_exponent_range, - prepare_vector_input_range, read_inputs, read_numerical_vector, reject_other_status, resolve, - restore_environment, sticky_inexact, sticky_result_check, test_control, - vector_positive_exponent_range, + ColdSplit, Condition, Entry, INPUT_MINIMUM_EXPONENT, Input, Rounding, branch, clear_scalar, + commit_inexact, environment_round, positive_exponent_range, prepare_vector_input_range, + read_inputs, read_numerical_vector, reject_other_status, resolve, restore_environment, + sticky_inexact, sticky_result_check, test_control, vector_positive_exponent_range, }; +use super::numerical::{helper_section, jump}; use super::{Host, commit, packed, read_vector}; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::{Alu, Code, Gpr, ShiftOp, Size}; use crate::{ GuestAddress, TargetCpu, aarch64::{ floating::{FPCR_EXCEPTION_ENABLE_MASK, FPCR_NEP, FPCR_ROUNDING_SHIFT, Format}, simd::{arithmetic::Shape, sqrt::Operand}, }, - block::ExitKind, }; +use Gpr::Rax; use alloc::vec::Vec; const RESULT: u8 = 0; @@ -27,19 +29,6 @@ const ROUNDING_BIAS: u8 = 5; const SAVED_HALF: u8 = 6; const ROUNDING_PARITY: u8 = 7; const FIRST_LANE: u8 = 0; -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const JMP_REL32: u8 = 0xe9; -const MOVD_EAX_XMM_PREFIX: &[u8] = &[0x66, 0x0f, 0x7e]; -const MOVD_XMM_EAX_PREFIX: &[u8] = &[0x66, 0x0f, 0x6e]; -const PINSRW_XMM_EAX_PREFIX: &[u8] = &[0x66, 0x0f, 0xc4]; -const MOVZX_EAX_AX: &[u8] = &[0x0f, 0xb7, 0xc0]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const SHR_EAX_IMM8: &[u8] = &[0xc1, 0xe8]; -const BT_EAX_IMM8: &[u8] = &[0x0f, 0xba, 0xe0]; -const ADD_EAX_IMM32: u8 = 0x05; -const ADC_EAX_IMM32: u8 = 0x15; -const SUB_EAX_IMM32: u8 = 0x2d; const CONVERT_USING_MXCSR: u8 = 1 << 2; const FPCR_LOW_ROUNDING_BIT: u32 = 1 << FPCR_ROUNDING_SHIFT; const FPCR_HIGH_ROUNDING_BIT: u32 = 1 << (FPCR_ROUNDING_SHIFT + 1); @@ -52,14 +41,7 @@ const HALF_BIAS_POSITION: u8 = HALF_TO_SINGLE_BIAS.trailing_zeros() as u8; const HALF_BIAS_DIGITS: u8 = (HALF_TO_SINGLE_BIAS >> HALF_BIAS_POSITION).ilog2() as u8 + 1; const UPPER_HALF_BYTES: u8 = (u64::BITS / u8::BITS) as u8; -fn jump(code: &mut Vec) -> usize { - code.push(JMP_REL32); - let patch = code.len(); - code.extend(0i32.to_le_bytes()); - patch -} - -fn source_guard(code: &mut Vec, operand: &Operand, helper: &mut Vec) { +fn source_guard(code: &mut Code, operand: &Operand, helper: &mut Vec) { test_control(code, FPCR_EXCEPTION_ENABLE_MASK); helper.push(branch(code, Condition::NotZero)); read_numerical_vector(code, operand.shape, operand.source, SOURCE); @@ -73,20 +55,7 @@ fn source_guard(code: &mut Vec, operand: &Operand, helper: &mut Vec) } } -/// Every branch enters with the caller's complete MXCSR and stack restored. -/// Guest status and destination commits follow this common cold helper section. -fn helper_section(code: &mut Vec, helper: &[usize], pc: GuestAddress) { - let completed = jump(code); - let helper_start = code.len(); - super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); - let success_start = code.len(); - for &patch in helper { - resolve(code, patch, helper_start); - } - resolve(code, completed, success_start); -} - -fn square_root(code: &mut Vec, format: Format, shape: Shape, source: u8) { +fn square_root(code: &mut Code, format: Format, shape: Shape, source: u8) { let opcode = match (format, shape) { (Format::Single, Shape::Scalar) => Host::SquareRootScalarSingle, (Format::Double, Shape::Scalar) => Host::SquareRootScalarDouble, @@ -100,7 +69,7 @@ fn square_root(code: &mut Vec, format: Format, shape: Shape, source: u8) { /// Select positive-result narrowing bias once for both four-lane H groups. /// Nearest-even adds half-minus-one plus retained parity. Positive rounding /// adds the entire discarded mask; negative/zero rounding simply truncates. -fn half_constants(code: &mut Vec) { +fn half_constants(code: &mut Code) { packed(code, Host::Xor, ZERO, ZERO); packed(code, Host::EqualDword, HALF_BIAS, HALF_BIAS); ShiftOpcode::RightDword.emit(code, HALF_BIAS, u32::BITS as u8 - HALF_BIAS_DIGITS); @@ -123,7 +92,7 @@ fn half_constants(code: &mut Vec) { } /// All active inputs were positive normal H. Integer field construction is exact. -fn widen_half(code: &mut Vec, upper: bool) { +fn widen_half(code: &mut Code, upper: bool) { packed(code, Host::MoveAligned, RESULT, SOURCE); if upper { ShiftOpcode::RightBytes.emit(code, RESULT, UPPER_HALF_BYTES); @@ -137,7 +106,7 @@ fn widen_half(code: &mut Vec, upper: bool) { /// result as direct half-precision sqrt, with single PE exactly matching half /// inexact. Results are positive normal halves of at most 256, so signed dword /// packing is exact. -fn half_fields(code: &mut Vec) { +fn half_fields(code: &mut Code) { packed(code, Host::SubDword, RESULT, HALF_BIAS); packed(code, Host::MoveAligned, TEMP, RESULT); ShiftOpcode::RightDword.emit(code, TEMP, HALF_FRACTION_SHIFT); @@ -149,45 +118,39 @@ fn half_fields(code: &mut Vec) { /// The scalar integer recipe avoids vector constant preparation and packing. /// BT captures retained parity before ADC adds half-minus-one plus that bit. -fn scalar_half_root(code: &mut Vec) { - code.extend(MOVD_EAX_XMM_PREFIX); - code.push(REGISTER_DIRECT | (SOURCE << MODRM_REGISTER_SHIFT)); - code.extend(MOVZX_EAX_AX); - code.extend(SHL_EAX_IMM8); - code.push(HALF_FRACTION_SHIFT); - code.push(ADD_EAX_IMM32); - code.extend(HALF_TO_SINGLE_BIAS.to_le_bytes()); - code.extend(MOVD_XMM_EAX_PREFIX); - code.push(REGISTER_DIRECT | (RESULT << MODRM_REGISTER_SHIFT)); +fn scalar_half_root(code: &mut Code) { + let mut asm = code.asm(); + asm.movd_from_xmm(Rax, SOURCE); + asm.movzx(Size::Dword, Rax, Size::Word, Rax); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, HALF_FRACTION_SHIFT); + asm.alu_accumulator_imm32(Alu::Add, Size::Dword, HALF_TO_SINGLE_BIAS as i32); + asm.movd_to_xmm(RESULT, Rax); square_root(code, Format::Single, Shape::Scalar, RESULT); - code.extend(MOVD_EAX_XMM_PREFIX); - code.push(REGISTER_DIRECT | (RESULT << MODRM_REGISTER_SHIFT)); - code.push(SUB_EAX_IMM32); - code.extend(HALF_TO_SINGLE_BIAS.to_le_bytes()); + let mut asm = code.asm(); + asm.movd_from_xmm(Rax, RESULT); + asm.alu_accumulator_imm32(Alu::Sub, Size::Dword, HALF_TO_SINGLE_BIAS as i32); test_control(code, FPCR_HIGH_ROUNDING_BIT); let truncating = branch(code, Condition::NotZero); test_control(code, FPCR_LOW_ROUNDING_BIT); let positive = branch(code, Condition::NotZero); - code.extend(BT_EAX_IMM8); - code.push(HALF_FRACTION_SHIFT); - code.push(ADC_EAX_IMM32); - code.extend((HALF_DISCARDED_MASK >> 1).to_le_bytes()); + let mut asm = code.asm(); + asm.bit_imm(BitTest::Bt, Size::Dword, Rax, HALF_FRACTION_SHIFT); + asm.alu_accumulator_imm32(Alu::Adc, Size::Dword, (HALF_DISCARDED_MASK >> 1) as i32); let nearest_done = jump(code); let positive_start = code.len(); resolve(code, positive, positive_start); - code.push(ADD_EAX_IMM32); - code.extend(HALF_DISCARDED_MASK.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Add, Size::Dword, HALF_DISCARDED_MASK as i32); let shift_start = code.len(); for patch in [truncating, nearest_done] { resolve(code, patch, shift_start); } - code.extend(SHR_EAX_IMM8); - code.push(HALF_FRACTION_SHIFT); - code.extend(MOVD_XMM_EAX_PREFIX); - code.push(REGISTER_DIRECT | (RESULT << MODRM_REGISTER_SHIFT)); + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, HALF_FRACTION_SHIFT); + asm.movd_to_xmm(RESULT, Rax); } -fn vector_half_root(code: &mut Vec, shape: Shape) { +fn vector_half_root(code: &mut Code, shape: Shape) { half_constants(code); widen_half(code, false); square_root(code, Format::Single, shape, RESULT); @@ -204,14 +167,13 @@ fn vector_half_root(code: &mut Vec, shape: Shape) { } } -fn narrow_half(code: &mut Vec, destination: u8, source: u8, target: TargetCpu) { +fn narrow_half(code: &mut Code, destination: u8, source: u8, target: TargetCpu) { // VCVTPS2PH encodes source in ModRM.reg and destination in ModRM.r/m, // reversing the register field roles of ordinary two-operand SIMD ops. - Host::ConvertSingleToHalf.register(code, source, destination, target); - code.push(CONVERT_USING_MXCSR); + Host::ConvertSingleToHalf.register_imm(code, source, destination, CONVERT_USING_MXCSR, target); } -fn checked_half_root(code: &mut Vec, shape: Shape, target: TargetCpu) { +fn checked_half_root(code: &mut Code, shape: Shape, target: TargetCpu) { if shape == Shape::Scalar { clear_scalar(code, Format::Half, SOURCE); } @@ -232,17 +194,14 @@ fn checked_half_root(code: &mut Vec, shape: Shape, target: TargetCpu) { } } -fn commit_result(code: &mut Vec, operand: &Operand) { +fn commit_result(code: &mut Code, operand: &Operand) { if operand.shape == Shape::Scalar { if operand.format == Format::Half { // Rebuild the half-precision scalar result in Vd after the // arithmetic and packing, which handles source aliases and V31. - code.extend(MOVD_EAX_XMM_PREFIX); - code.push(REGISTER_DIRECT | (RESULT << MODRM_REGISTER_SHIFT)); + code.asm().movd_from_xmm(Rax, RESULT); read_vector(code, operand.destination, RESULT); - code.extend(PINSRW_XMM_EAX_PREFIX); - code.push(REGISTER_DIRECT | (RESULT << MODRM_REGISTER_SHIFT)); - code.push(FIRST_LANE); + code.asm().pinsrw(RESULT, Rax, FIRST_LANE); } test_control(code, FPCR_NEP); let merging = branch(code, Condition::NotZero); @@ -257,7 +216,7 @@ fn commit_result(code: &mut Vec, operand: &Operand) { /// S/D forms return their [`ColdSplit`]. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu, @@ -267,7 +226,7 @@ pub(in crate::x86_64) fn emit( if checked_half { // F16C requires usable AVX. Pay this prefix per body before legacy // guards, avoiding a transition from arbitrary caller upper YMM state. - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } let mut helper = Vec::new(); // The sticky-inexact path (`numerical::sticky_inexact`) for S and D: the diff --git a/crates/stela-compiler/src/x86_64/simd/structure_checked.rs b/crates/stela-compiler/src/x86_64/simd/structure_checked.rs index 8756c98252..3daa1a791e 100644 --- a/crates/stela-compiler/src/x86_64/simd/structure_checked.rs +++ b/crates/stela-compiler/src/x86_64/simd/structure_checked.rs @@ -1,6 +1,8 @@ //! Fixed-width AdvSIMD structures through exact element memory-service requests. //! The typed schedule owns access order and partial load commits. Guest addresses //! are never host pointers; only private State and stack staging are dereferenced. +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Size}; +use crate::x86_64::simd::encode::guest; use super::{commit, vector_offset}; use crate::{ @@ -36,25 +38,6 @@ const WRITEBACK_OFFSET: u8 = BASE_OFFSET + QWORD_BYTES; const REQUEST_OFFSET: u32 = 2 * VECTOR_BYTES as u32; const SCRATCH_BYTES: u8 = REQUEST_OFFSET as u8 + MEMORY_REQUEST_BYTES as u8; -const SUB_RSP: &[u8] = &[0x48, 0x83, 0xec]; -const ADD_RSP: &[u8] = &[0x48, 0x83, 0xc4]; -const MOV_RSP_RAX: &[u8] = &[0x48, 0x89, 0x44, 0x24]; -const MOV_RSP_RDX: &[u8] = &[0x48, 0x89, 0x54, 0x24]; -const MOV_RSP_RCX: &[u8] = &[0x48, 0x89, 0x4c, 0x24]; -const MOV_RAX_RSP: &[u8] = &[0x48, 0x8b, 0x44, 0x24]; -const LEA_RAX_RAX_DISP8: &[u8] = &[0x48, 0x8d, 0x40]; -const MOVZX_ECX_BYTE: &[u8] = &[0x0f, 0xb6]; -const MOVZX_ECX_HALFWORD: &[u8] = &[0x0f, 0xb7]; -const MOV_LOAD: u8 = 0x8b; -const MOV_STORE: u8 = 0x89; -const MOV_BYTE_STORE: u8 = 0x88; -const OPERAND_SIZE_PREFIX: u8 = 0x66; -const REX_W: u8 = 0x48; -const RCX_STATE_DISP32: u8 = 0x8f; -const RCX_STACK_DISP8: &[u8] = &[0x4c, 0x24]; -const MOV_ZERO_QWORD_STATE: &[u8] = &[0x48, 0xc7, 0x87]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; - #[derive(Clone, Copy)] pub(crate) struct CheckedOperand { operand: Operand, @@ -164,10 +147,10 @@ impl CheckedOperand { } } - pub(crate) fn emit_context(self, code: &mut Vec, pc: u64, target: TargetCpu) { + pub(crate) fn emit_context(self, code: &mut Code, pc: u64, target: TargetCpu) { let operand = self.operand; - code.extend(SUB_RSP); - code.push(SCRATCH_BYTES); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Gpr::Rsp, SCRATCH_BYTES as i8); service::begin(code); let mut failures = Vec::new(); if self.profile.sp_requirement() == SpAlignmentRequirement::Enabled @@ -176,7 +159,7 @@ impl CheckedOperand { failures.push(failure); } crate::x86_64::load(code, operand.base); - stack(code, MOV_RSP_RAX, BASE_OFFSET); + save(code, Gpr::Rax, BASE_OFFSET); // Save original Rn and Xm-derived writeback before any callback. CPA2 // result marking has no fault or guest effect and can be computed early. match operand.post_index { @@ -189,7 +172,7 @@ impl CheckedOperand { AddressMode::PostIndex, self.profile.address_checks(false), ); - stack(code, MOV_RSP_RDX, WRITEBACK_OFFSET); + save(code, Gpr::Rdx, WRITEBACK_OFFSET); } PostIndex::Register(index) => { service::address::register_offset_with_checks( @@ -200,7 +183,7 @@ impl CheckedOperand { 0, self.profile.address_checks(false), ); - stack(code, MOV_RSP_RAX, WRITEBACK_OFFSET); + save(code, Gpr::Rax, WRITEBACK_OFFSET); } } for access in operand.accesses() { @@ -208,20 +191,23 @@ impl CheckedOperand { let LoadCommit::Lane { index, .. } = access.commit else { unreachable!("validated stores have lane sources") }; - scalar_state( + scalar( code, false, operand.element_bytes, - vector_offset(access.vector) + u32::from(index * operand.element_bytes), + guest(vector_offset(access.vector) + u32::from(index * operand.element_bytes)), ); // A full private staging store is safe; the request retains the // exact element width and does not expose unused staging bytes. - stack(code, MOV_RSP_RCX, DATA_OFFSET); + save(code, Gpr::Rcx, DATA_OFFSET); } - stack(code, MOV_RAX_RSP, BASE_OFFSET); + restore(code, BASE_OFFSET); if access.byte_offset != 0 { - code.extend(LEA_RAX_RAX_DISP8); - code.push(access.byte_offset); + code.asm().lea( + Size::Qword, + Gpr::Rax, + Mem::base_disp8(Gpr::Rax, access.byte_offset as i8), + ); } service::request( code, @@ -234,16 +220,17 @@ impl CheckedOperand { service::call(code, REQUEST_OFFSET); failures.push(service::branch_failed(code)); if operand.direction == Direction::Load { - scalar_opcode(code, false, operand.element_bytes); - code.extend(RCX_STACK_DISP8); - code.push(DATA_OFFSET); + scalar(code, false, operand.element_bytes, slot(DATA_OFFSET)); match access.commit { LoadCommit::Lane { index, clear_upper } => { - scalar_state( + scalar( code, true, operand.element_bytes, - vector_offset(access.vector) + u32::from(index * operand.element_bytes), + guest( + vector_offset(access.vector) + + u32::from(index * operand.element_bytes), + ), ); if clear_upper { clear_upper_half(code, access.vector); @@ -257,65 +244,66 @@ impl CheckedOperand { } } if operand.post_index != PostIndex::None { - stack(code, MOV_RAX_RSP, WRITEBACK_OFFSET); + restore(code, WRITEBACK_OFFSET); store(code, operand.base); } - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); let cleanup = code.len(); for failure in failures { service::patch_branch(code, failure, cleanup); } - code.extend(ADD_RSP); - code.push(SCRATCH_BYTES); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Gpr::Rsp, SCRATCH_BYTES as i8); service::address::return_if_failed(code); } } -fn stack(code: &mut Vec, opcode: &[u8], displacement: u8) { - code.extend(opcode); - code.push(displacement); +/// `[rsp + offset]` in the scratch frame, with an 8-bit displacement. +fn slot(offset: u8) -> Mem { + Mem::base_disp8(Gpr::Rsp, offset as i8) } -/// Exact-width state/staging reads zero-extend narrow elements into RCX. -fn scalar_opcode(code: &mut Vec, write: bool, bytes: u8) { - if !write && bytes <= HALFWORD_BYTES { - code.extend(if bytes == BYTE_BYTES { - MOVZX_ECX_BYTE - } else { - MOVZX_ECX_HALFWORD - }); +/// Save `register` in the scratch slot at `offset`. +fn save(code: &mut Code, register: Gpr, offset: u8) { + code.asm().mov_store(Size::Qword, slot(offset), register); +} + +/// Reload RAX from the scratch slot at `offset`. +fn restore(code: &mut Code, offset: u8) { + code.asm().mov_load(Size::Qword, Gpr::Rax, slot(offset)); +} + +/// Exact-width state/staging reads zero-extend narrow elements into RCX; +/// writes store RCX's low `bytes`. +fn scalar(code: &mut Code, write: bool, bytes: u8, memory: Mem) { + let size = match bytes { + BYTE_BYTES => Size::Byte, + HALFWORD_BYTES => Size::Word, + DWORD_BYTES => Size::Dword, + QWORD_BYTES => Size::Qword, + _ => unreachable!("validated structure element width"), + }; + let mut asm = code.asm(); + if write { + asm.mov_store(size, memory, Gpr::Rcx); + } else if bytes <= HALFWORD_BYTES { + asm.movzx(Size::Dword, Gpr::Rcx, size, memory); } else { - if bytes == HALFWORD_BYTES { - code.push(OPERAND_SIZE_PREFIX); - } - if bytes == QWORD_BYTES { - code.push(REX_W); - } - code.push(if !write { - MOV_LOAD - } else if bytes == BYTE_BYTES { - MOV_BYTE_STORE - } else { - MOV_STORE - }); + asm.mov_load(size, Gpr::Rcx, memory); } } -fn scalar_state(code: &mut Vec, write: bool, bytes: u8, displacement: u32) { - scalar_opcode(code, write, bytes); - code.push(RCX_STATE_DISP32); - code.extend(displacement.to_le_bytes()); -} - -fn clear_upper_half(code: &mut Vec, vector: u8) { - code.extend(MOV_ZERO_QWORD_STATE); - code.extend((vector_offset(vector) + u32::from(QWORD_BYTES)).to_le_bytes()); - code.extend(0_i32.to_le_bytes()); +fn clear_upper_half(code: &mut Code, vector: u8) { + code.asm().mov_rm_imm32( + Size::Qword, + guest(vector_offset(vector) + u32::from(QWORD_BYTES)), + 0, + ); } /// RCX contains one zero-extended, successfully read element. Rebuild an /// optional shuffle mask after each callback; no host vector survives it. -fn replicate(code: &mut Vec, bytes: u8, vector_bytes: u8, target: TargetCpu) { +fn replicate(code: &mut Code, bytes: u8, vector_bytes: u8, target: TargetCpu) { Host::MoveGprQword.register(code, 0, 1, TargetCpu::Baseline); // XMM0 <- RCX if bytes == BYTE_BYTES && vector_bytes == VECTOR_BYTES && target.supports(TargetCpu::Ssse3) { Host::Xor.register(code, 1, 1, TargetCpu::Baseline); @@ -327,17 +315,14 @@ fn replicate(code: &mut Vec, bytes: u8, vector_bytes: u8, target: TargetCpu) } match bytes { BYTE_BYTES | HALFWORD_BYTES if vector_bytes == QWORD_BYTES => { - Host::ShuffleLowWord.register(code, 0, 0, TargetCpu::Baseline); - code.push(0); // repeat low word, retaining the zero upper64 + Host::ShuffleLowWord.register_imm(code, 0, 0, 0, TargetCpu::Baseline); // repeat low word, retaining the zero upper64 } BYTE_BYTES | HALFWORD_BYTES => { Host::UnpackLowWord.register(code, 0, 0, TargetCpu::Baseline); - Host::ShuffleDword.register(code, 0, 0, TargetCpu::Baseline); - code.push(0); // repeat low dword + Host::ShuffleDword.register_imm(code, 0, 0, 0, TargetCpu::Baseline); // repeat low dword } DWORD_BYTES if vector_bytes == VECTOR_BYTES => { - Host::ShuffleDword.register(code, 0, 0, TargetCpu::Baseline); - code.push(0); + Host::ShuffleDword.register_imm(code, 0, 0, 0, TargetCpu::Baseline); } DWORD_BYTES => Host::UnpackLowDword.register(code, 0, 0, TargetCpu::Baseline), QWORD_BYTES if vector_bytes == VECTOR_BYTES => { @@ -840,7 +825,7 @@ mod tests { profile: CheckedMemoryProfile, target: TargetCpu, ) -> Self { - let mut code = crate::extended::context_wrapper(); + let mut code = crate::scalable_context::context_wrapper(); checked(operand, profile).emit_context(&mut code, GUEST_PC, target); code.push(0xc3); Self::new(&code) @@ -1176,20 +1161,21 @@ mod tests { #[test] fn original_ld4_word_uses_checked_block_routing_and_real_source_intervals() { - use crate::block::{BlockProfile, CompilationPlan}; + use crate::block::{BlockProfile, CompilationPlan, Features}; let source: Vec<_> = [0x4c40_0044, RET] .into_iter() .flat_map(u32::to_le_bytes) .collect(); for profile in [ - BlockProfile::CheckedMemory(CheckedMemoryProfile::SpAlignmentDisabled), - BlockProfile::SystemModeSharedV1(CheckedMemoryProfile::SpAlignmentDisabled), + BlockProfile::ORDINARY + .with_checked_memory(CheckedMemoryProfile::SpAlignmentDisabled), + BlockProfile::new(Features::SYSTEM_MODE) + .with_checked_memory(CheckedMemoryProfile::SpAlignmentDisabled), ] { let plan = CompilationPlan::new( &source, GuestAddress(GUEST_PC), - profile, - TargetCpu::X86_64_V2, + &crate::Options::new(profile, TargetCpu::X86_64_V2), ) .unwrap(); let required = plan.memory_requirements().unwrap(); diff --git a/crates/stela-compiler/src/x86_64/simd/structure_memory.rs b/crates/stela-compiler/src/x86_64/simd/structure_memory.rs index cde35842fc..01d7d1615c 100644 --- a/crates/stela-compiler/src/x86_64/simd/structure_memory.rs +++ b/crates/stela-compiler/src/x86_64/simd/structure_memory.rs @@ -6,7 +6,8 @@ use crate::aarch64::simd::structure_memory::{ Access, Direction, Layout, LoadCommit, Operand, PostIndex, }; use crate::aarch64::{AddressMode, Register}; -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, Size}; +use crate::x86_64::simd::encode::guest; mod multiple; mod single; @@ -16,29 +17,25 @@ const HALFWORD_BYTES: u8 = 2; const DWORD_BYTES: u8 = 4; const QWORD_BYTES: u8 = 8; const STACK_ALIGNMENT_BYTES: u8 = 16; -const OPERAND_SIZE_PREFIX: u8 = 0x66; -const REX_W: u8 = 0x48; -const MOV_BYTE_STORE: u8 = 0x88; -const MOV_STORE: u8 = 0x89; -const MOV_LOAD: u8 = 0x8b; -const MODRM_RCX_STATE_DISP32: u8 = 0x8f; -const MODRM_RCX_RAX: u8 = 0x08; -const MODRM_DISP8: u8 = 0x40; -const MOVZX_ECX_BYTE: &[u8] = &[0x0f, 0xb6]; -const MOVZX_ECX_HALFWORD: &[u8] = &[0x0f, 0xb7]; -const LEA_RDX_RAX_DISP32: &[u8] = &[0x48, 0x8d, 0x90]; -/// LEA RDX,[RAX+RCX]: the address plus the post-index register. -const LEA_RDX_RAX_RCX: &[u8] = &[0x48, 0x8d, 0x14, 0x08]; -const ADD_RAX_IMM8: &[u8] = &[0x48, 0x83, 0xc0]; -const LEA_R10D_RAX_DISP8: &[u8] = &[0x44, 0x8d, 0x50]; -const XOR_R10D_EAX: &[u8] = &[0x41, 0x31, 0xc2]; -const TEST_R10D_IMM32: &[u8] = &[0x41, 0xf7, 0xc2]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -const JMP_REL32: u8 = 0xe9; -const MOV_ZERO_QWORD_STATE: &[u8] = &[0x48, 0xc7, 0x87]; + +/// The operand size of a `bytes`-byte element. +fn size(bytes: u8) -> Size { + match bytes { + BYTE_BYTES => Size::Byte, + HALFWORD_BYTES => Size::Word, + DWORD_BYTES => Size::Dword, + QWORD_BYTES => Size::Qword, + _ => unreachable!("decoder validates scalar structure width"), + } +} + +/// `[rax + displacement]`, the element at `displacement` in the footprint. +fn element(displacement: u8) -> Mem { + Mem::base(Gpr::Rax, displacement.into()) +} pub(super) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, target: TargetCpu, checks: super::super::MemoryChecks, @@ -60,8 +57,11 @@ pub(super) fn emit( match operand.post_index { PostIndex::None => {} PostIndex::TransferredBytes => { - code.extend(LEA_RDX_RAX_DISP32); - code.extend(i32::from(operand.transferred_bytes()).to_le_bytes()); + code.asm().lea( + Size::Qword, + Gpr::Rdx, + Mem::base_disp32(Gpr::Rax, operand.transferred_bytes().into()), + ); } PostIndex::Register(index) => { scalar_state_transfer( @@ -70,7 +70,12 @@ pub(super) fn emit( QWORD_BYTES, super::super::offset(Register::X(index)).expect("post-index is X0..X30"), ); - code.extend(LEA_RDX_RAX_RCX); + // The address plus the post-index register. + code.asm().lea( + Size::Qword, + Gpr::Rdx, + Mem::indexed(Gpr::Rax, Gpr::Rcx, 1, 0), + ); } } // A checked SP is 16-byte aligned; an unchecked one is an ordinary base. @@ -82,16 +87,21 @@ pub(super) fn emit( } else { // N <= 64: bit12 changes exactly when this footprint crosses a 4KiB // boundary, including wrapping addresses. No memory is read by the guard. - code.extend(LEA_R10D_RAX_DISP8); - code.push(operand.transferred_bytes() - 1); - code.extend(XOR_R10D_EAX); - code.extend(TEST_R10D_IMM32); - code.extend(super::super::memory_store::PROTECTION_GRANULE_BYTES.to_le_bytes()); - code.extend(JNZ_REL32); - let crossing_jump = branch_placeholder(code); + let mut asm = code.asm(); + asm.lea( + Size::Dword, + Gpr::R10, + Mem::base_disp8(Gpr::Rax, (operand.transferred_bytes() - 1) as i8), + ); + asm.alu(Alu::Xor, Size::Dword, Gpr::R10, Gpr::Rax); + asm.test_imm( + Size::Dword, + Gpr::R10, + super::super::memory_store::PROTECTION_GRANULE_BYTES as i32, + ); + let crossing_jump = asm.jcc(Cond::Ne).offset(); packed(code, operand, target); - code.push(JMP_REL32); - let complete_jump = branch_placeholder(code); + let complete_jump = code.asm().jmp().offset(); patch_jump(code, crossing_jump); ordered(code, operand, aligned_sp); patch_jump(code, complete_jump); @@ -101,7 +111,7 @@ pub(super) fn emit( } } -fn packed(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn packed(code: &mut Code, operand: &Operand, target: TargetCpu) { match operand.layout { Layout::Multiple { .. } => multiple::packed(code, operand, target), Layout::Lane { .. } | Layout::Replicate { .. } => single::packed(code, operand, target), @@ -110,27 +120,27 @@ fn packed(code: &mut Vec, operand: &Operand, target: TargetCpu) { /// Source-width accesses and immediate successful assignments. RDX/RDI survive; /// RAX advances through the footprint, RCX/R10/XMM0 are scratch. -fn ordered(code: &mut Vec, operand: &Operand, aligned_sp: bool) { +fn ordered(code: &mut Code, operand: &Operand, aligned_sp: bool) { let count = operand.transferred_bytes() / operand.element_bytes; for (ordinal, access) in operand.accesses().enumerate() { transfer_access(code, operand, access, 0, false, aligned_sp); if ordinal + 1 != usize::from(count) { - code.extend(ADD_RAX_IMM8); - code.push(operand.element_bytes); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Gpr::Rax, operand.element_bytes as i8); } } } /// The whole footprint is within one granule, so elements are accessed at fixed /// displacements without per-element store guards. -fn ordered_in_granule(code: &mut Vec, operand: &Operand) { +fn ordered_in_granule(code: &mut Code, operand: &Operand) { for access in operand.accesses() { transfer_access(code, operand, access, access.byte_offset, true, false); } } fn transfer_access( - code: &mut Vec, + code: &mut Code, operand: &Operand, access: Access, displacement: u8, @@ -147,9 +157,11 @@ fn transfer_access( vector_offset(access.vector) + u32::from(index * operand.element_bytes), ); if clear_upper { - code.extend(MOV_ZERO_QWORD_STATE); - code.extend((vector_offset(access.vector) + u32::from(QWORD_BYTES)).to_le_bytes()); - code.extend(0i32.to_le_bytes()); + code.asm().mov_rm_imm32( + Size::Qword, + guest(vector_offset(access.vector) + u32::from(QWORD_BYTES)), + 0, + ); } } (Direction::Load, LoadCommit::Replicate { vector_bytes }) => { @@ -183,68 +195,33 @@ fn transfer_access( } /// Exact-width RAM read into zero-extended RCX; no guest state commit yet. -fn element_load(code: &mut Vec, bytes: u8, displacement: u8) { +fn element_load(code: &mut Code, bytes: u8, displacement: u8) { + let mut asm = code.asm(); match bytes { - BYTE_BYTES => code.extend(MOVZX_ECX_BYTE), - HALFWORD_BYTES => code.extend(MOVZX_ECX_HALFWORD), - DWORD_BYTES => code.push(MOV_LOAD), - QWORD_BYTES => code.extend([REX_W, MOV_LOAD]), - _ => unreachable!("decoder validates scalar structure width"), - } - code.push(MODRM_RCX_RAX | if displacement == 0 { 0 } else { MODRM_DISP8 }); - if displacement != 0 { - code.push(displacement); + BYTE_BYTES | HALFWORD_BYTES => { + asm.movzx(Size::Dword, Gpr::Rcx, size(bytes), element(displacement)); + } + _ => asm.mov_load(size(bytes), Gpr::Rcx, element(displacement)), } } /// Exact scalar RCX store, used only after the whole-footprint granule proof. -fn element_store(code: &mut Vec, bytes: u8, displacement: u8) { - if bytes == HALFWORD_BYTES { - code.push(OPERAND_SIZE_PREFIX); - } else if bytes == QWORD_BYTES { - code.push(REX_W); - } - code.push(if bytes == BYTE_BYTES { - MOV_BYTE_STORE - } else { - MOV_STORE - }); - code.push(MODRM_RCX_RAX | if displacement == 0 { 0 } else { MODRM_DISP8 }); - if displacement != 0 { - code.push(displacement); - } +fn element_store(code: &mut Code, bytes: u8, displacement: u8) { + code.asm() + .mov_store(size(bytes), element(displacement), Gpr::Rcx); } /// true writes RCX to the selected state lane; false reads it into RCX. -fn scalar_state_transfer(code: &mut Vec, load: bool, bytes: u8, state_offset: u32) { - if !load && bytes <= HALFWORD_BYTES { - code.extend(if bytes == BYTE_BYTES { - MOVZX_ECX_BYTE - } else { - MOVZX_ECX_HALFWORD - }); +fn scalar_state_transfer(code: &mut Code, load: bool, bytes: u8, state_offset: u32) { + let lane = guest(state_offset); + let mut asm = code.asm(); + if load { + asm.mov_store(size(bytes), lane, Gpr::Rcx); + } else if bytes <= HALFWORD_BYTES { + asm.movzx(Size::Dword, Gpr::Rcx, size(bytes), lane); } else { - if bytes == HALFWORD_BYTES { - code.push(OPERAND_SIZE_PREFIX); - } else if bytes == QWORD_BYTES { - code.push(REX_W); - } - code.push(if !load { - MOV_LOAD - } else if bytes == BYTE_BYTES { - MOV_BYTE_STORE - } else { - MOV_STORE - }); + asm.mov_load(size(bytes), Gpr::Rcx, lane); } - code.push(MODRM_RCX_STATE_DISP32); - code.extend(state_offset.to_le_bytes()); -} - -fn branch_placeholder(code: &mut Vec) -> usize { - let offset = code.len(); - code.extend(0i32.to_le_bytes()); - offset } fn patch_jump(code: &mut [u8], offset: usize) { diff --git a/crates/stela-compiler/src/x86_64/simd/structure_memory/multiple.rs b/crates/stela-compiler/src/x86_64/simd/structure_memory/multiple.rs index 4206949ef6..24e5dff67b 100644 --- a/crates/stela-compiler/src/x86_64/simd/structure_memory/multiple.rs +++ b/crates/stela-compiler/src/x86_64/simd/structure_memory/multiple.rs @@ -3,6 +3,7 @@ use super::super::{commit, read_vector}; use crate::TargetCpu; use crate::aarch64::scalable::ElementSize; use crate::aarch64::simd::structure_memory::{Direction, Layout, Operand}; +use crate::x86_64::asm::{Code, Gpr, Mem}; use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; use crate::x86_64::scalable::routing; use alloc::vec::Vec; @@ -17,15 +18,10 @@ const THREE_STRUCTURES: u8 = 3; const RESULT_XMM: u8 = 4; const PARTIAL_XMM: u8 = 5; const SCRATCH_XMM: u8 = 6; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MODRM_DISP8: u8 = 0x40; -const MODRM_RIP: u8 = 0x05; -const MOVQ_STORE: &[u8] = &[0x66, 0x0f, 0xd6]; -const JMP_REL32: u8 = 0xe9; const SHUFFLE_ZERO: u8 = 0x80; /// RAX is the guest address; RDI and the pending writeback in RDX survive. -pub(super) fn packed(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn packed(code: &mut Code, operand: &Operand, target: TargetCpu) { let Layout::Multiple { repetitions, structures, @@ -60,29 +56,27 @@ pub(super) fn packed(code: &mut Vec, operand: &Operand, target: TargetCpu) { } } -fn simd(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn simd(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn copy(code: &mut Vec, destination: u8, source: u8) { +fn copy(code: &mut Code, destination: u8, source: u8) { simd(code, Host::MoveAligned, destination, source); } -fn chunk(code: &mut Vec, load: bool, bytes: u8, xmm: u8, displacement: u8) { +fn chunk(code: &mut Code, load: bool, bytes: u8, xmm: u8, displacement: u8) { + let address = Mem::base(Gpr::Rax, displacement.into()); + let baseline = TargetCpu::Baseline; match (load, bytes) { - (true, QWORD_BYTES) => Host::MoveQword.append(code, TargetCpu::Baseline), - (true, VECTOR_BYTES) => Host::LoadUnaligned.append(code, TargetCpu::Baseline), - (false, QWORD_BYTES) => code.extend(MOVQ_STORE), - (false, VECTOR_BYTES) => Host::StoreUnaligned.append(code, TargetCpu::Baseline), + (true, QWORD_BYTES) => Host::MoveQword.emit(code, xmm, address, baseline), + (true, VECTOR_BYTES) => Host::LoadUnaligned.emit(code, xmm, address, baseline), + (false, QWORD_BYTES) => code.asm().movq_store(xmm, address), + (false, VECTOR_BYTES) => Host::StoreUnaligned.emit(code, xmm, address, baseline), _ => unreachable!("multiple footprint consists of exact qword/vector chunks"), } - code.push((xmm << MODRM_REGISTER_SHIFT) | if displacement == 0 { 0 } else { MODRM_DISP8 }); - if displacement != 0 { - code.push(displacement); - } } -fn contiguous(code: &mut Vec, operand: &Operand, repetitions: u8, bytes: u8) { +fn contiguous(code: &mut Code, operand: &Operand, repetitions: u8, bytes: u8) { for register in 0..repetitions { let vector = (operand.first_vector + register) % VECTOR_REGISTER_COUNT; let offset = register * bytes; @@ -98,14 +92,13 @@ fn contiguous(code: &mut Vec, operand: &Operand, repetitions: u8, bytes: u8) /// Gather the low two dwords, repeating that pair in the upper half. Distinct /// inputs first broadcast their selected lanes, then interleave the low dwords. -fn dword_pair(code: &mut Vec, destination: u8, first: (u8, u8), second: (u8, u8)) { - let shuffle = |code: &mut Vec, destination, source, low, high| { - simd(code, Host::ShuffleDword, destination, source); +fn dword_pair(code: &mut Code, destination: u8, first: (u8, u8), second: (u8, u8)) { + let shuffle = |code: &mut Code, destination, source, low, high| { let control = low | high << DWORD_INDEX_BITS | low << (2 * DWORD_INDEX_BITS) | high << (3 * DWORD_INDEX_BITS); - code.push(control); + Host::ShuffleDword.register_imm(code, destination, source, control, TargetCpu::Baseline); }; if first.0 == second.0 { shuffle(code, destination, first.0, first.1, second.1); @@ -118,7 +111,7 @@ fn dword_pair(code: &mut Vec, destination: u8, first: (u8, u8), second: (u8, /// Three-way dword routing uses fewer state/RAM accesses than the scalar stream /// without SSSE3 masks. Each output combines two independently gathered pairs. -fn dword_three(code: &mut Vec, operand: &Operand, bytes: u8) { +fn dword_three(code: &mut Code, operand: &Operand, bytes: u8) { let load = operand.direction == Direction::Load; let footprint = THREE_STRUCTURES * bytes; let memory_chunks = footprint.div_ceil(VECTOR_BYTES); @@ -191,7 +184,7 @@ fn dword_three(code: &mut Vec, operand: &Operand, bytes: u8) { /// Reuse the shared exact-width SSE2 chunk network, preserving the established /// multiple-structure operand API and complete baseline recipe. -fn split(code: &mut Vec, first: u8, second: u8, even: u8, odd: u8, bytes: u8) { +fn split(code: &mut Code, first: u8, second: u8, even: u8, odd: u8, bytes: u8) { routing::split( code, first, @@ -203,7 +196,7 @@ fn split(code: &mut Vec, first: u8, second: u8, even: u8, odd: u8, bytes: u8 ); } -fn load_interleaved(code: &mut Vec, operand: &Operand, structures: u8, bytes: u8) { +fn load_interleaved(code: &mut Code, operand: &Operand, structures: u8, bytes: u8) { let chunks = structures * bytes / VECTOR_BYTES; for source in 0..chunks { chunk(code, true, VECTOR_BYTES, source, source * VECTOR_BYTES); @@ -247,7 +240,7 @@ fn load_interleaved(code: &mut Vec, operand: &Operand, structures: u8, bytes } } -fn merge(code: &mut Vec, first: u8, second: u8, low: u8, high: u8, bytes: u8) { +fn merge(code: &mut Code, first: u8, second: u8, low: u8, high: u8, bytes: u8) { routing::merge( code, first, @@ -259,7 +252,7 @@ fn merge(code: &mut Vec, first: u8, second: u8, low: u8, high: u8, bytes: u8 ); } -fn store_interleaved(code: &mut Vec, operand: &Operand, structures: u8, bytes: u8) { +fn store_interleaved(code: &mut Code, operand: &Operand, structures: u8, bytes: u8) { for source in 0..structures { read_vector( code, @@ -304,7 +297,7 @@ fn store_interleaved(code: &mut Vec, operand: &Operand, structures: u8, byte /// exact chunks. Embedded masks use MOVDQU: legacy PSHUFB memory operands would /// impose unwanted alignment. Three-way Q0 transfers have an exact 8-byte tail. fn shuffled_interleaved( - code: &mut Vec, + code: &mut Code, operand: &Operand, structures: u8, bytes: u8, @@ -365,10 +358,8 @@ fn shuffled_interleaved( } let destination = if first { RESULT_XMM } else { PARTIAL_XMM }; copy(code, destination, input); - Host::LoadUnaligned.append(code, TargetCpu::Baseline); - code.push((SCRATCH_XMM << MODRM_REGISTER_SHIFT) | MODRM_RIP); - let displacement = code.len(); - code.extend(0i32.to_le_bytes()); + Host::LoadUnaligned.emit(code, SCRATCH_XMM, Mem::rip(0), TargetCpu::Baseline); + let displacement = code.len() - size_of::(); masks.push((mask, displacement)); Host::ByteShuffle.register(code, destination, SCRATCH_XMM, target); if !first { @@ -388,13 +379,11 @@ fn shuffled_interleaved( } // Every mask is exactly sixteen bytes. One unconditional branch skips the // trailing mask pool, and each RIP-relative load targets its own mask. - code.push(JMP_REL32); - let done = code.len(); - code.extend(0i32.to_le_bytes()); + let done = code.asm().jmp().offset(); for (mask, displacement) in masks { let target = code.len(); patch_relative(code, displacement, target); - code.extend(mask); + code.asm().data(&mask); } let target = code.len(); patch_relative(code, done, target); diff --git a/crates/stela-compiler/src/x86_64/simd/structure_memory/single.rs b/crates/stela-compiler/src/x86_64/simd/structure_memory/single.rs index 4b1e45bbfa..f134e80d3e 100644 --- a/crates/stela-compiler/src/x86_64/simd/structure_memory/single.rs +++ b/crates/stela-compiler/src/x86_64/simd/structure_memory/single.rs @@ -1,12 +1,12 @@ //! LD1-4/ST1-4 (single lane) and LD1R-4R within one page. use super::super::{commit, vector_offset}; use super::{element_load, element_store, scalar_state_transfer}; +use crate::x86_64::asm::{Code, Gpr}; use crate::{ TargetCpu, aarch64::simd::structure_memory::{Direction, Layout, Operand}, x86_64::isa::SimdOpcode as Host, }; -use alloc::vec::Vec; const BYTE_BYTES: u8 = 1; const HALFWORD_BYTES: u8 = 2; @@ -17,12 +17,11 @@ const VECTOR_REGISTER_MASK: u8 = 31; const RESULT_XMM: u8 = 0; const BROADCAST_MASK_XMM: u8 = 1; const ECX: u8 = 1; -const MOVD_XMM0_ECX: [u8; 4] = [0x66, 0x0f, 0x6e, 0xc1]; const REPEAT_LOW_ELEMENT: u8 = 0; /// RAX is the address; the pending writeback in RDX and the state in RDI /// survive. -pub(super) fn packed(code: &mut Vec, operand: &Operand, target: TargetCpu) { +pub(super) fn packed(code: &mut Code, operand: &Operand, target: TargetCpu) { match operand.layout { Layout::Lane { structures, index } => lane(code, operand, structures, index), Layout::Replicate { @@ -35,7 +34,7 @@ pub(super) fn packed(code: &mut Vec, operand: &Operand, target: TargetCpu) { } } -fn lane(code: &mut Vec, operand: &Operand, structures: u8, index: u8) { +fn lane(code: &mut Code, operand: &Operand, structures: u8, index: u8) { let load = operand.direction == Direction::Load; for structure in 0..structures { let vector = (operand.first_vector + structure) & VECTOR_REGISTER_MASK; @@ -52,7 +51,7 @@ fn lane(code: &mut Vec, operand: &Operand, structures: u8, index: u8) { } fn replicate( - code: &mut Vec, + code: &mut Code, operand: &Operand, structures: u8, vector_bytes: u8, @@ -76,7 +75,7 @@ fn replicate( match operand.element_bytes { BYTE_BYTES | HALFWORD_BYTES => { element_load(code, operand.element_bytes, displacement); - code.extend(MOVD_XMM0_ECX); + code.asm().movd_to_xmm(RESULT_XMM, Gpr::Rcx); } DWORD_BYTES | QWORD_BYTES => super::super::memory::wide_transfer( code, @@ -100,16 +99,16 @@ fn replicate( /// Ordered fallback: a completed exact-width read is zero-extended in RCX. /// Construct XMM0 without touching the address or pending writeback. -pub(super) fn broadcast(code: &mut Vec, bytes: u8, vector_bytes: u8) { +pub(super) fn broadcast(code: &mut Code, bytes: u8, vector_bytes: u8) { if bytes == QWORD_BYTES { Host::MoveGprQword.register(code, RESULT_XMM, ECX, TargetCpu::Baseline); } else { - code.extend(MOVD_XMM0_ECX); + code.asm().movd_to_xmm(RESULT_XMM, Gpr::Rcx); } broadcast_xmm(code, bytes, vector_bytes); } -fn broadcast_xmm(code: &mut Vec, bytes: u8, vector_bytes: u8) { +fn broadcast_xmm(code: &mut Code, bytes: u8, vector_bytes: u8) { let full_vector = vector_bytes == VECTOR_BYTES; match bytes { BYTE_BYTES => { @@ -141,7 +140,12 @@ fn broadcast_xmm(code: &mut Vec, bytes: u8, vector_bytes: u8) { } } -fn shuffle(code: &mut Vec, opcode: Host) { - opcode.register(code, RESULT_XMM, RESULT_XMM, TargetCpu::Baseline); - code.push(REPEAT_LOW_ELEMENT); +fn shuffle(code: &mut Code, opcode: Host) { + opcode.register_imm( + code, + RESULT_XMM, + RESULT_XMM, + REPEAT_LOW_ELEMENT, + TargetCpu::Baseline, + ); } diff --git a/crates/stela-compiler/src/x86_64/simd/widening.rs b/crates/stela-compiler/src/x86_64/simd/widening.rs index 311f12b5cb..4de5a5de8f 100644 --- a/crates/stela-compiler/src/x86_64/simd/widening.rs +++ b/crates/stela-compiler/src/x86_64/simd/widening.rs @@ -1,12 +1,13 @@ //! FMLAL/FMLSL on normal half inputs with one final rounding. use super::super::isa::ShiftOpcode; use super::numerical::{ - ArithmeticOpcode, Condition, FusedOpcode, VZEROUPPER, branch, clear_scalar, commit_inexact, - emit_fma, emit_opcode, environment, prepare_vector_input_range, read_numerical_right, + ArithmeticOpcode, Condition, FusedOpcode, branch, clear_scalar, commit_inexact, emit_fma, + emit_opcode, environment, prepare_vector_input_range, read_numerical_right, read_numerical_vector, reject_other_status, resolve, restore_environment, test_control, vector_exponent_range, vector_half_exponent_range, widen_half_to_single, }; use super::{Host, commit, packed, read_vector, shuffle}; +use crate::x86_64::asm::{Code, Gpr}; use crate::{ GuestAddress, TargetCpu, aarch64::{ @@ -24,7 +25,6 @@ const WIDEN_SIGN: u8 = 4; const ZERO: u8 = 5; const ADDEND: u8 = 6; const WIDEN_BIAS: u8 = 7; -const EAX: u8 = 0; const FIRST_LANE: u8 = 0; const HALF_BYTES: u32 = Format::Half.bits() / u8::BITS; const HALF_LOW_BYTE_MASK: u32 = (1 << (2 * HALF_BYTES)) - 1; @@ -33,12 +33,8 @@ const SIGN_BITS: u8 = 1; const SINGLE_SIGN_SHIFT: u8 = Format::Single.bits() as u8 - SIGN_BITS; const HALF_TO_SINGLE_BIAS: u32 = (Format::Single.exponent_bias() - Format::Half.exponent_bias()) << Format::Single.fraction_bits(); -const MOV_EAX_IMM32: u8 = 0xb8; -const MOVD_XMM_EAX_PREFIX: &[u8] = &[0x66, 0x0f, 0x6e]; -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -fn select_part(code: &mut Vec, operand: &Operand, source: u8, vector: u8) { +fn select_part(code: &mut Code, operand: &Operand, source: u8, vector: u8) { read_vector(code, source, vector); let offset = operand.part.source_lane_offset(operand.shape) * HALF_BYTES; if offset != 0 { @@ -46,7 +42,7 @@ fn select_part(code: &mut Vec, operand: &Operand, source: u8, vector: u8) { } } -fn prepare_sources(code: &mut Vec, operand: &Operand) { +fn prepare_sources(code: &mut Code, operand: &Operand) { // Snapshot every guest source before the single eventual destination store. select_part(code, operand, operand.left, LEFT); if operand.right_lane.is_some() { @@ -63,19 +59,18 @@ fn prepare_sources(code: &mut Vec, operand: &Operand) { read_numerical_vector(code, operand.shape, operand.destination, ADDEND); } -fn prepare_integer_widening(code: &mut Vec) { +fn prepare_integer_widening(code: &mut Code) { packed(code, Host::Xor, ZERO, ZERO); - code.push(MOV_EAX_IMM32); - code.extend(HALF_TO_SINGLE_BIAS.to_le_bytes()); - code.extend(MOVD_XMM_EAX_PREFIX); - code.push(REGISTER_DIRECT | WIDEN_BIAS << MODRM_REGISTER_SHIFT | EAX); + let mut asm = code.asm(); + asm.mov_imm32(Gpr::Rax, HALF_TO_SINGLE_BIAS); + asm.movd_to_xmm(WIDEN_BIAS, Gpr::Rax); shuffle(code, WIDEN_BIAS, WIDEN_BIAS, FIRST_LANE); for vector in [LEFT, RIGHT] { widen_half_to_single(code, vector, vector, WIDEN_SIGN, ZERO, WIDEN_BIAS); } } -fn prepare_checked_widening(code: &mut Vec, shape: Shape, target: TargetCpu) { +fn prepare_checked_widening(code: &mut Code, shape: Shape, target: TargetCpu) { for vector in [LEFT, RIGHT] { if shape == Shape::Vector64 { // Exactly two half lanes are active. Clear H2/H3 before VCVTPH2PS @@ -91,7 +86,7 @@ fn use_fma(operand: &Operand, target: TargetCpu) -> bool { && (operand.operation == WideningOperation::Add || operand.shape == Shape::Vector64) } -fn arithmetic(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn arithmetic(code: &mut Code, operand: &Operand, target: TargetCpu) { if use_fma(operand, target) { let opcode = match operand.operation { WideningOperation::Add => FusedOpcode::MultiplyAdd, @@ -127,14 +122,14 @@ fn arithmetic(code: &mut Vec, operand: &Operand, target: TargetCpu) { } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, pc: GuestAddress, target: TargetCpu, ) { assert!(operand.shape != Shape::Scalar, "FHM requires vector lanes"); if target.supports(TargetCpu::F16c) || use_fma(operand, target) { - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } let mut helper = Vec::new(); test_control(code, FPCR_EXCEPTION_ENABLE_MASK); diff --git a/crates/stela-compiler/src/x86_64/sme/extrema_scale.rs b/crates/stela-compiler/src/x86_64/sme/extrema_scale.rs index 22807a4a37..71ad11a2b2 100644 --- a/crates/stela-compiler/src/x86_64/sme/extrema_scale.rs +++ b/crates/stela-compiler/src/x86_64/sme/extrema_scale.rs @@ -1,4 +1,6 @@ //! SME2 FAMIN/FAMAX and FSCALE over whole staged groups. +use crate::x86_64::asm::{Code, Cond, Size}; +use crate::x86_64::simd::encode::guest; use crate::{ CompileError, GuestAddress, GuestState, TargetCpu, aarch64::{ @@ -20,8 +22,6 @@ use alloc::vec::Vec; const LEFT: u8 = 0; const RIGHT: u8 = 1; const SCRATCH: [u8; 4] = [2, 3, 4, 5]; -const TEST_STATE_IMMEDIATE: &[u8] = &[0xf7, 0x87]; -const JNZ: &[u8] = &[0x0f, 0x85]; /// Absolute extrema admit every numeric lane. FSCALE admits normal inputs and /// normal results using the shared exact exponent-adjustment kernel. All other @@ -29,7 +29,7 @@ const JNZ: &[u8] = &[0x0f, 0x85]; /// Integer operations preserve complete caller MXCSR. /// Clobbers RAX/RCX/RDX, host flags, XMM0..5; preserves RDI/R15 and guest NZCV. pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -56,12 +56,13 @@ pub(crate) fn emit( let frame = numerical::begin(code, length, &outputs, Environment::Exact)?; let mut failures = Vec::new(); if features.full_a64() { - code.extend(TEST_STATE_IMMEDIATE); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(FPCR_EXCEPTION_ENABLE_MASK.to_le_bytes()); - code.extend(JNZ); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); + let mut asm = code.asm(); + asm.test_imm( + Size::Dword, + guest(core::mem::offset_of!(GuestState, fpcr) as u32), + FPCR_EXCEPTION_ENABLE_MASK as i32, + ); + failures.push(asm.jcc(Cond::Ne).offset()); } for index in 0..count { for chunk in 0..length.chunks() { diff --git a/crates/stela-compiler/src/x86_64/sme/integer_dots.rs b/crates/stela-compiler/src/x86_64/sme/integer_dots.rs index a61c711591..a346f0861e 100644 --- a/crates/stela-compiler/src/x86_64/sme/integer_dots.rs +++ b/crates/stela-compiler/src/x86_64/sme/integer_dots.rs @@ -1,4 +1,6 @@ //! SME2 integer dot products, including 16-to-64-bit products. +use crate::x86_64::asm::{Alu, Code, Gpr, ShiftOp, Size}; +use crate::x86_64::simd::encode::guest; use crate::{ GuestState, TargetCpu, aarch64::{ @@ -15,14 +17,11 @@ use crate::{ }, }, }; -use alloc::vec::Vec; const ACCUMULATOR: u8 = 2; const TEMPORARY: u8 = 5; const SIGN_MASK: u8 = 6; const VERTICAL_MASK: u8 = 7; -const MODRM_REGISTER: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; const SWAP_ADJACENT_DWORDS: u8 = 0xb1; const PACK_EVEN_DWORDS: u8 = 0x88; const SWAP_QWORDS: u8 = 0x4e; @@ -32,54 +31,50 @@ const REPEAT_HIGH_QWORD: u8 = 0xee; const DWORD_SIGN_SHIFT: u8 = 31; const GPR_BYTES: u32 = core::mem::size_of::() as u32; const BROADCAST_DWORD_INDEX: u8 = 0x55; -const MOV_ECX_STATE_DISP32: &[u8] = &[0x8b, 0x8f]; -const ADD_ECX_IMM8: &[u8] = &[0x83, 0xc1]; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const SHL_RCX_IMM8: &[u8] = &[0x48, 0xc1, 0xe1]; -const ADD_R8_RCX: &[u8] = &[0x49, 0x01, 0xc8]; -const MOV_EAX_IMM32: u8 = 0xb8; -const MOVD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; // At 16 bytes the longer SSE2 reduction wins for ordinary dots; 64-byte // candidates favor PHADDD. Unmeasured 32-byte ordinary shapes stay on SSE2. const MIN_PHADDD_VECTOR_BYTES: usize = 64; -fn copy(code: &mut Vec, destination: u8, source: u8, target: TargetCpu) { +fn copy(code: &mut Code, destination: u8, source: u8, target: TargetCpu) { Host::MoveAligned.register(code, destination, source, target); } -fn shuffle(code: &mut Vec, destination: u8, source: u8, control: u8, target: TargetCpu) { - Host::ShuffleDword.register(code, destination, source, target); - code.push(control); +fn shuffle(code: &mut Code, destination: u8, source: u8, control: u8, target: TargetCpu) { + Host::ShuffleDword.register_imm(code, destination, source, control, target); } /// ZA pointer stays in caller-saved R8; shared Z helpers clobber only RDX. -fn za_pointer(code: &mut Vec, operand: &Operand, length: VectorLength) { +fn za_pointer(code: &mut Code, operand: &Operand, length: VectorLength) { load_za_pointer_r8(code); - code.extend(MOV_ECX_STATE_DISP32); - code.extend( - (core::mem::offset_of!(GuestState, x) as u32 + u32::from(operand.selector) * GPR_BYTES) - .to_le_bytes(), + let mut asm = code.asm(); + asm.mov_load( + Size::Dword, + Gpr::Rcx, + guest( + core::mem::offset_of!(GuestState, x) as u32 + u32::from(operand.selector) * GPR_BYTES, + ), ); // Partition rows are powers of two dividing 2^32. ECX wrap therefore // preserves (UInt(Wselector)+offset) modulo the selected partition. if operand.offset != 0 { - code.extend(ADD_ECX_IMM8); - code.push(operand.offset); + asm.alu_imm8(Alu::Add, Size::Dword, Gpr::Rcx, operand.offset as i8); } let partition_rows = length.bytes() / usize::from(operand.groups); - code.extend(AND_ECX_IMM32); - code.extend(((partition_rows - 1) as u32).to_le_bytes()); - code.extend(SHL_RCX_IMM8); - code.push(length.bytes().trailing_zeros() as u8); - code.extend(ADD_R8_RCX); + asm.alu_imm32(Alu::And, Size::Dword, Gpr::Rcx, (partition_rows - 1) as i32); + asm.shift_imm( + ShiftOp::Shl, + Size::Qword, + Gpr::Rcx, + length.bytes().trailing_zeros() as u8, + ); + asm.alu(Alu::Add, Size::Qword, Gpr::R8, Gpr::Rcx); } -fn vertical_mask(code: &mut Vec, operand: &Operand, target: TargetCpu) { +fn vertical_mask(code: &mut Code, operand: &Operand, target: TargetCpu) { let source_bits = operand.accumulator.bits() / usize::from(operand.terms); - code.push(MOV_EAX_IMM32); - code.extend(((1u32 << source_bits) - 1).to_le_bytes()); - code.extend(MOVD_XMM_EAX); - code.push(MODRM_REGISTER | (VERTICAL_MASK << REGISTER_SHIFT)); + let mut asm = code.asm(); + asm.mov_imm32(Gpr::Rax, (1u32 << source_bits) - 1); + asm.movd_to_xmm(VERTICAL_MASK, Gpr::Rax); shuffle( code, VERTICAL_MASK, @@ -94,7 +89,7 @@ fn vertical_mask(code: &mut Vec, operand: &Operand, target: TargetCpu) { } fn left_chunk( - code: &mut Vec, + code: &mut Code, operand: &Operand, group: u8, chunk: usize, @@ -139,7 +134,7 @@ fn left_chunk( } } -fn adjacent_pair_sums(code: &mut Vec, low: u8, high: u8, target: TargetCpu, horizontal: bool) { +fn adjacent_pair_sums(code: &mut Code, low: u8, high: u8, target: TargetCpu, horizontal: bool) { if horizontal { Host::HorizontalAddDword.register(code, low, high, target); return; @@ -153,7 +148,7 @@ fn adjacent_pair_sums(code: &mut Vec, low: u8, high: u8, target: TargetCpu, Host::UnpackLowQword.register(code, low, high, target); } -fn extend_bytes(code: &mut Vec, low: u8, high: u8, signed: bool, target: TargetCpu) { +fn extend_bytes(code: &mut Code, low: u8, high: u8, signed: bool, target: TargetCpu) { copy(code, high, low, target); Host::Xor.register(code, SIGN_MASK, SIGN_MASK, target); if signed { @@ -165,7 +160,7 @@ fn extend_bytes(code: &mut Vec, low: u8, high: u8, signed: bool, target: Tar /// Four exact 32-bit products become a duplicated 64-bit sum. Widen first: /// PMADDWD's 0x8000*0x8000 pair overflow cannot be sign-extended to 64 bits. -fn reduce_four_products(code: &mut Vec, source: u8, signed: bool, target: TargetCpu) { +fn reduce_four_products(code: &mut Code, source: u8, signed: bool, target: TargetCpu) { if signed { copy(code, SIGN_MASK, source, target); Shift::ArithmeticDword.emit(code, SIGN_MASK, DWORD_SIGN_SHIFT); @@ -181,7 +176,7 @@ fn reduce_four_products(code: &mut Vec, source: u8, signed: bool, target: Ta } /// XMM0/1 inputs, XMM2 accumulator, XMM0 result; XMM3..6 scratch, XMM7 preserved. -fn dot_chunk(code: &mut Vec, operand: &Operand, target: TargetCpu, horizontal: bool) { +fn dot_chunk(code: &mut Code, operand: &Operand, target: TargetCpu, horizontal: bool) { if operand.accumulator == ElementSize::Doubleword { word_products(code, operand.left_signed, target); reduce_four_products(code, LEFT, operand.left_signed, target); @@ -209,7 +204,7 @@ fn dot_chunk(code: &mut Vec, operand: &Operand, target: TargetCpu, horizonta /// Caller validates SME2, SM+ZA, SVL and I16I64 before entry. This unpredicated /// family touches only selected ZA vectors; all Z/P/flags/control state survives. -pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu) { za_pointer(code, operand, length); if operand.kind == Kind::VerticalDot { vertical_mask(code, operand, target); diff --git a/crates/stela-compiler/src/x86_64/sme/integer_matrix.rs b/crates/stela-compiler/src/x86_64/sme/integer_matrix.rs index d74564a3ee..cf82be25bc 100644 --- a/crates/stela-compiler/src/x86_64/sme/integer_matrix.rs +++ b/crates/stela-compiler/src/x86_64/sme/integer_matrix.rs @@ -1,5 +1,6 @@ //! SME integer ZA arithmetic. -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Gpr, ShiftOp, Size}; +use crate::x86_64::simd::encode::guest; mod long; mod outer; @@ -19,13 +20,8 @@ use crate::{ const LEFT: u8 = 0; const RIGHT: u8 = 1; const GPR_BYTES: usize = core::mem::size_of::(); -const MOV_ECX_STATE_DISP32: &[u8] = &[0x8b, 0x8f]; -const ADD_ECX_IMM8: &[u8] = &[0x83, 0xc1]; -const AND_ECX_IMM8: &[u8] = &[0x83, 0xe1]; -const SHL_RCX_IMM8: &[u8] = &[0x48, 0xc1, 0xe1]; -const ADD_R8_RCX: &[u8] = &[0x49, 0x01, 0xc8]; -pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu) { match operand { Operand::AddSub(operation) => { emit_add_sub(code, operation, length, target); @@ -46,7 +42,7 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, } fn emit_add_sub( - code: &mut Vec, + code: &mut Code, operand: &AddSubOperation, length: VectorLength, target: TargetCpu, @@ -60,22 +56,28 @@ fn emit_add_sub( _ => unreachable!("integer ZA add/sub has 32- or 64-bit elements"), }; load_za_pointer_r8(code); - code.extend(MOV_ECX_STATE_DISP32); - code.extend( - ((core::mem::offset_of!(GuestState, x) + usize::from(operand.selector) * GPR_BYTES) as u32) - .to_le_bytes(), + let mut asm = code.asm(); + asm.mov_load( + Size::Dword, + Gpr::Rcx, + guest( + (core::mem::offset_of!(GuestState, x) + usize::from(operand.selector) * GPR_BYTES) + as u32, + ), ); if operand.offset != 0 { - code.extend(ADD_ECX_IMM8); - code.push(operand.offset); + asm.alu_imm8(Alu::Add, Size::Dword, Gpr::Rcx, operand.offset as i8); } // All accepted SME lengths and group counts are powers of two. Low32 // addition followed by this mask equals UInt(Wselector)+offset modulo stride. - code.extend(AND_ECX_IMM8); - code.push((stride - 1) as u8); - code.extend(SHL_RCX_IMM8); - code.push(length.bytes().trailing_zeros() as u8); - code.extend(ADD_R8_RCX); + asm.alu_imm8(Alu::And, Size::Dword, Gpr::Rcx, (stride - 1) as i8); + asm.shift_imm( + ShiftOp::Shl, + Size::Qword, + Gpr::Rcx, + length.bytes().trailing_zeros() as u8, + ); + asm.alu(Alu::Add, Size::Qword, Gpr::R8, Gpr::Rcx); for group in 0..operand.groups { for chunk in 0..length.chunks() { let displacement = diff --git a/crates/stela-compiler/src/x86_64/sme/integer_matrix/long.rs b/crates/stela-compiler/src/x86_64/sme/integer_matrix/long.rs index 0ed7dd13fb..7f3f31b3b6 100644 --- a/crates/stela-compiler/src/x86_64/sme/integer_matrix/long.rs +++ b/crates/stela-compiler/src/x86_64/sme/integer_matrix/long.rs @@ -1,4 +1,6 @@ //! Long integer accumulation into ZA rows. +use crate::x86_64::asm::{Alu, Code, Gpr, ShiftOp, Size}; +use crate::x86_64::simd::encode::guest; use crate::{ GuestState, TargetCpu, aarch64::{ @@ -12,7 +14,6 @@ use crate::{ sme::integer_products::{PRODUCT_HIGH, PRODUCT_LEFT, PRODUCT_RIGHT, word_products}, }, }; -use alloc::vec::Vec; const ACCUMULATOR: u8 = 2; const COMPONENT: u8 = 6; @@ -29,12 +30,6 @@ const REPEAT_HIGH_QWORD: u8 = 0xee; const HALFWORDS_PER_QWORD: u8 = 4; const BYTES_PER_DWORD: u8 = core::mem::size_of::() as u8; const GPR_BYTES: usize = core::mem::size_of::(); -const MOV_ECX_STATE_DISP32: &[u8] = &[0x8b, 0x8f]; -const ADD_ECX_IMM8: &[u8] = &[0x83, 0xc1]; -const AND_ECX_IMM8: &[u8] = &[0x83, 0xe1]; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const SHL_RCX_IMM8: &[u8] = &[0x48, 0xc1, 0xe1]; -const ADD_R8_RCX: &[u8] = &[0x49, 0x01, 0xc8]; /// Recipe controls; the parent selects the mapping. #[derive(Clone, Copy)] @@ -56,21 +51,23 @@ impl Recipe { } } -fn shuffle(code: &mut Vec, destination: u8, source: u8, control: u8, target: TargetCpu) { - Host::ShuffleDword.register(code, destination, source, target); - code.push(control); +fn shuffle(code: &mut Code, destination: u8, source: u8, control: u8, target: TargetCpu) { + Host::ShuffleDword.register_imm(code, destination, source, control, target); } -fn za_pointer(code: &mut Vec, operand: &LongOperation, length: VectorLength) { +fn za_pointer(code: &mut Code, operand: &LongOperation, length: VectorLength) { load_za_pointer_r8(code); - code.extend(MOV_ECX_STATE_DISP32); - code.extend( - ((core::mem::offset_of!(GuestState, x) + usize::from(operand.selector) * GPR_BYTES) as u32) - .to_le_bytes(), + let mut asm = code.asm(); + asm.mov_load( + Size::Dword, + Gpr::Rcx, + guest( + (core::mem::offset_of!(GuestState, x) + usize::from(operand.selector) * GPR_BYTES) + as u32, + ), ); if operand.offset != 0 { - code.extend(ADD_ECX_IMM8); - code.push(operand.offset); + asm.alu_imm8(Alu::Add, Size::Dword, Gpr::Rcx, operand.offset as i8); } // Accepted SME lengths, group counts and component counts are powers of two. // Low32 addition retains the exact mathematical result modulo the partition. @@ -78,26 +75,33 @@ fn za_pointer(code: &mut Vec, operand: &LongOperation, length: VectorLength) let partition_rows = length.bytes() / usize::from(operand.group_size); let row_mask = ((partition_rows - 1) & !(usize::from(operand.factor) - 1)) as u32; if row_mask <= i8::MAX as u32 { - code.extend(AND_ECX_IMM8); - code.push(row_mask as u8); + asm.alu_imm8(Alu::And, Size::Dword, Gpr::Rcx, row_mask as i8); } else { - code.extend(AND_ECX_IMM32); - code.extend(row_mask.to_le_bytes()); + asm.alu_imm32(Alu::And, Size::Dword, Gpr::Rcx, row_mask as i32); } - code.extend(SHL_RCX_IMM8); - code.push(length.bytes().trailing_zeros() as u8); - code.extend(ADD_R8_RCX); + asm.shift_imm( + ShiftOp::Shl, + Size::Qword, + Gpr::Rcx, + length.bytes().trailing_zeros() as u8, + ); + asm.alu(Alu::Add, Size::Qword, Gpr::R8, Gpr::Rcx); } -fn broadcast_word(code: &mut Vec, index: u8, target: TargetCpu) { +fn broadcast_word(code: &mut Code, index: u8, target: TargetCpu) { let high = index >= HALFWORDS_PER_QWORD; (if high { Host::ShuffleHighWord } else { Host::ShuffleLowWord }) - .register(code, PRODUCT_RIGHT, PRODUCT_RIGHT, target); - code.push((index % HALFWORDS_PER_QWORD) * DWORD_BROADCAST); + .register_imm( + code, + PRODUCT_RIGHT, + PRODUCT_RIGHT, + (index % HALFWORDS_PER_QWORD) * DWORD_BROADCAST, + target, + ); shuffle( code, PRODUCT_RIGHT, @@ -113,7 +117,7 @@ fn broadcast_word(code: &mut Vec, index: u8, target: TargetCpu) { /// Select one byte from every dword and sign/zero extend it to a dword. fn extract_bytes( - code: &mut Vec, + code: &mut Code, destination: u8, source: u8, component: u8, @@ -135,7 +139,7 @@ fn extract_bytes( .emit(code, destination, DWORD_BITS - BYTE_BITS); } -fn extend_products(code: &mut Vec, signed: bool, checked: bool, target: TargetCpu) { +fn extend_products(code: &mut Code, signed: bool, checked: bool, target: TargetCpu) { if checked { (if signed { Host::SignExtendDwordToQword @@ -155,7 +159,7 @@ fn extend_products(code: &mut Vec, signed: bool, checked: bool, target: Targ } fn accumulate( - code: &mut Vec, + code: &mut Code, product: u8, displacement: u32, operand: &LongOperation, @@ -177,7 +181,7 @@ fn accumulate( /// All inputs remain in architectural storage; only selected ZA rows are written. /// R8 holds the selected ZA base, RDX is shared access scratch, XMM0..7 scratch. pub(crate) fn emit_long( - code: &mut Vec, + code: &mut Code, operand: &LongOperation, length: VectorLength, target: TargetCpu, diff --git a/crates/stela-compiler/src/x86_64/sme/integer_matrix/outer.rs b/crates/stela-compiler/src/x86_64/sme/integer_matrix/outer.rs index 27d882e7ee..03a4de51a0 100644 --- a/crates/stela-compiler/src/x86_64/sme/integer_matrix/outer.rs +++ b/crates/stela-compiler/src/x86_64/sme/integer_matrix/outer.rs @@ -1,4 +1,7 @@ //! SME integer outer products. +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, Size}; +use crate::x86_64::simd::encode::stack; use crate::{ TargetCpu, aarch64::{ @@ -14,7 +17,7 @@ use crate::{ }, }, }; -use alloc::vec::Vec; +use Gpr::{R8, R9, R11, Rax, Rsp}; const MIXED_CORRECTION: u8 = 5; const WORD_SIGN_SHIFT: u8 = 15; @@ -25,7 +28,7 @@ const WORD_SIGN_SHIFT: u8 = 15; /// clobber XMM5. Correcting the unsigned high word by the unsigned other input /// for each negative signed input reconstructs the full signed 32-bit product. fn word_products_signedness( - code: &mut Vec, + code: &mut Code, left_signed: bool, right_signed: bool, target: TargetCpu, @@ -74,51 +77,29 @@ const SWAR_BYTES: u32 = 0x0f0f_0f0f; const BYTE_ONES: u32 = 0x0101_0101; const WORD_ONES: u32 = 0x0001_0001; const NIBBLE_POPCOUNTS: [u8; VECTOR_CHUNK_BYTES] = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]; -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; -const MOV_RSP_DISP32_RAX: &[u8] = &[0x48, 0x89, 0x84, 0x24]; -const LEA_R11_RSP_DISP32: &[u8] = &[0x4c, 0x8d, 0x9c, 0x24]; -const XOR_R9D_R9D: &[u8] = &[0x45, 0x31, 0xc9]; -const BT_WORD_R11_R9W: &[u8] = &[0x66, 0x45, 0x0f, 0xa3, 0x0b]; -const JNC_REL32: &[u8] = &[0x0f, 0x83]; -const JB_REL32: &[u8] = &[0x0f, 0x82]; -const ADD_R9D_IMM8: &[u8] = &[0x41, 0x83, 0xc1]; -const ADD_R8_IMM32: &[u8] = &[0x49, 0x81, 0xc0]; -const CMP_R9D_IMM32: &[u8] = &[0x41, 0x81, 0xf9]; -const MOVD_ROW_RSP_R9: &[u8] = &[0x66, 0x42, 0x0f, 0x6e, 0x14, 0x0c]; -const MOVQ_ROW_RSP_R9: &[u8] = &[0xf3, 0x42, 0x0f, 0x7e, 0x14, 0x0c]; -const MOV_EAX_IMM32: u8 = 0xb8; -const MOVABS_RAX_IMM64: &[u8] = &[0x48, 0xb8]; -const MOVD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; -const XMM_MODRM_REGISTER: u8 = 0xc0; -const XMM_MODRM_RSP_DISP32: u8 = 0x84; -const RSP_SIB: u8 = 0x24; -const XMM_REGISTER_SHIFT: u8 = 3; +/// R9 is the source group byte offset and the row predicate bit index; R11 +/// points at the staged predicate. +const ROW_OFFSET: Gpr = R9; +const PREDICATE: Gpr = R11; -fn stack_chunk(code: &mut Vec, register: u8, offset: usize, store: bool, target: TargetCpu) { +fn stack_chunk(code: &mut Code, register: u8, offset: usize, store: bool, target: TargetCpu) { (if store { Host::StoreUnaligned } else { Host::LoadUnaligned }) - .append(code, target); - code.push(XMM_MODRM_RSP_DISP32 | (register << XMM_REGISTER_SHIFT)); - code.push(RSP_SIB); - code.extend((offset as u32).to_le_bytes()); + .emit(code, register, stack(offset), target); } -fn splat_dword(code: &mut Vec, register: u8, value: u32, target: TargetCpu) { - code.push(MOV_EAX_IMM32); - code.extend(value.to_le_bytes()); - code.extend(MOVD_XMM_EAX); - code.push(XMM_MODRM_REGISTER | (register << XMM_REGISTER_SHIFT)); - Host::ShuffleDword.register(code, register, register, target); - code.push(REPEAT_LOW_DWORD); +fn splat_dword(code: &mut Code, register: u8, value: u32, target: TargetCpu) { + let mut asm = code.asm(); + asm.mov_imm32(Rax, value); + asm.movd_to_xmm(register, Rax); + Host::ShuffleDword.register_imm(code, register, register, REPEAT_LOW_DWORD, target); } -fn shuffle(code: &mut Vec, dst: u8, src: u8, control: u8, target: TargetCpu) { - Host::ShuffleDword.register(code, dst, src, target); - code.push(control); +fn shuffle(code: &mut Code, dst: u8, src: u8, control: u8, target: TargetCpu) { + Host::ShuffleDword.register_imm(code, dst, src, control, target); } fn patch_relative(code: &mut [u8], immediate: usize, destination: usize) { @@ -128,7 +109,7 @@ fn patch_relative(code: &mut [u8], immediate: usize, destination: usize) { } fn stage_vector( - code: &mut Vec, + code: &mut Code, vector: u8, predicate: Option, source: ElementSize, @@ -154,17 +135,17 @@ fn stage_vector( } } -fn prepare_popcount(code: &mut Vec, target: TargetCpu) { +fn prepare_popcount(code: &mut Code, target: TargetCpu) { if target.supports(TargetCpu::Ssse3) { splat_dword(code, HIGH, SWAR_BYTES, target); - code.extend(MOVABS_RAX_IMM64); - code.extend( - u64::from_le_bytes(NIBBLE_POPCOUNTS[..QWORD_BYTES].try_into().unwrap()).to_le_bytes(), + code.asm().mov_imm64( + Rax, + u64::from_le_bytes(NIBBLE_POPCOUNTS[..QWORD_BYTES].try_into().unwrap()), ); Host::MoveGprQword.register(code, WORK, 0, target); - code.extend(MOVABS_RAX_IMM64); - code.extend( - u64::from_le_bytes(NIBBLE_POPCOUNTS[QWORD_BYTES..].try_into().unwrap()).to_le_bytes(), + code.asm().mov_imm64( + Rax, + u64::from_le_bytes(NIBBLE_POPCOUNTS[QWORD_BYTES..].try_into().unwrap()), ); Host::MoveGprQword.register(code, SCRATCH, 0, target); Host::UnpackLowQword.register(code, WORK, SCRATCH, target); @@ -177,7 +158,7 @@ fn prepare_popcount(code: &mut Vec, target: TargetCpu) { } } -fn popcount_dwords(code: &mut Vec, target: TargetCpu) { +fn popcount_dwords(code: &mut Code, target: TargetCpu) { if target.supports(TargetCpu::Ssse3) { Host::MoveAligned.register(code, TEMP, RESULT, target); Host::And.register(code, RESULT, HIGH, target); @@ -215,7 +196,7 @@ fn popcount_dwords(code: &mut Vec, target: TargetCpu) { } } -fn adjacent_pair_sums(code: &mut Vec, target: TargetCpu) { +fn adjacent_pair_sums(code: &mut Code, target: TargetCpu) { if target.supports(TargetCpu::Ssse3) { Host::HorizontalAddDword.register(code, RESULT, HIGH, target); } else { @@ -229,7 +210,7 @@ fn adjacent_pair_sums(code: &mut Vec, target: TargetCpu) { } } -fn extend_row_bytes(code: &mut Vec, signed: bool, target: TargetCpu) { +fn extend_row_bytes(code: &mut Code, signed: bool, target: TargetCpu) { Host::Xor.register(code, SCRATCH, SCRATCH, target); if signed { Host::GreaterByte.register(code, SCRATCH, ROW, target); @@ -237,7 +218,7 @@ fn extend_row_bytes(code: &mut Vec, signed: bool, target: TargetCpu) { Host::UnpackLowByte.register(code, ROW, SCRATCH, target); } -fn byte_dot(code: &mut Vec, right_signed: bool, target: TargetCpu) { +fn byte_dot(code: &mut Code, right_signed: bool, target: TargetCpu) { Host::MoveAligned.register(code, HIGH, RESULT, target); Host::Xor.register(code, SCRATCH, SCRATCH, target); if right_signed { @@ -250,7 +231,7 @@ fn byte_dot(code: &mut Vec, right_signed: bool, target: TargetCpu) { adjacent_pair_sums(code, target); } -fn sum_four_products_qword(code: &mut Vec, register: u8, signed: bool, target: TargetCpu) { +fn sum_four_products_qword(code: &mut Code, register: u8, signed: bool, target: TargetCpu) { Host::MoveAligned.register(code, WORK, register, target); if signed { Host::MoveAligned.register(code, SCRATCH, register, target); @@ -267,7 +248,7 @@ fn sum_four_products_qword(code: &mut Vec, register: u8, signed: bool, targe } pub(crate) fn emit_outer( - code: &mut Vec, + code: &mut Code, operand: &OuterOperation, length: VectorLength, target: TargetCpu, @@ -290,8 +271,7 @@ pub(crate) fn emit_outer( } _ => operand.accumulator_size, }; - code.extend(SUB_RSP_IMM32); - code.extend((stack_bytes as u32).to_le_bytes()); + code.asm().reserve_stack(stack_bytes); stage_vector( code, operand.vector_n, @@ -315,37 +295,44 @@ pub(crate) fn emit_outer( if !multiply { for chunk in 0..length.predicate_bytes().div_ceil(QWORD_BYTES) { read_predicate_chunk(code, operand.predicate_n, chunk, length); - code.extend(MOV_RSP_DISP32_RAX); - code.extend(((predicate_offset + chunk * QWORD_BYTES) as u32).to_le_bytes()); + code.asm().mov_store( + Size::Qword, + stack(predicate_offset + chunk * QWORD_BYTES), + Rax, + ); } - code.extend(LEA_R11_RSP_DISP32); - code.extend((predicate_offset as u32).to_le_bytes()); + code.asm() + .lea(Size::Qword, PREDICATE, stack(predicate_offset)); } load_za_pointer_r8(code); - code.extend(ADD_R8_IMM32); - code.extend((usize::from(operand.tile) as u32 * length.bytes() as u32).to_le_bytes()); + code.asm().alu_imm32( + Alu::Add, + Size::Qword, + R8, + (usize::from(operand.tile) * length.bytes()) as i32, + ); if operand.kind == OuterKind::BitwiseXnor { prepare_popcount(code, target); } - code.extend(XOR_R9D_R9D); + code.asm() + .alu(Alu::Xor, Size::Dword, ROW_OFFSET, ROW_OFFSET); let row_start = code.len(); let inactive_row = if multiply { None } else { // R9 is the source group byte offset and therefore the row predicate // bit index. Word BT reads at most one staged two-byte predicate block. - code.extend(BT_WORD_R11_R9W); - code.extend(JNC_REL32); - let immediate = code.len(); - code.extend(0i32.to_le_bytes()); - Some(immediate) + let mut asm = code.asm(); + asm.bit(BitTest::Bt, Size::Word, Mem::base(PREDICATE, 0), ROW_OFFSET); + Some(asm.jcc(Cond::Ae).offset()) }; if operand.kind != OuterKind::AddHorizontal { - code.extend(if element_bytes == QWORD_BYTES { - MOVQ_ROW_RSP_R9 + let row = Mem::indexed(Rsp, ROW_OFFSET, 1, 0); + if element_bytes == QWORD_BYTES { + Host::MoveQword.emit(code, ROW, row, target); } else { - MOVD_ROW_RSP_R9 - }); + code.asm().movd_to_xmm(ROW, row); + } shuffle( code, ROW, @@ -433,16 +420,16 @@ pub(crate) fn emit_outer( if let Some(immediate) = inactive_row { patch_relative(code, immediate, row_advance); } - code.extend(ADD_R9D_IMM8); - code.push(element_bytes as u8); - code.extend(ADD_R8_IMM32); - code.extend(((element_bytes * length.bytes()) as u32).to_le_bytes()); - code.extend(CMP_R9D_IMM32); - code.extend((length.bytes() as u32).to_le_bytes()); - code.extend(JB_REL32); - let immediate = code.len(); - code.extend(0i32.to_le_bytes()); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Add, Size::Dword, ROW_OFFSET, element_bytes as i8); + asm.alu_imm32( + Alu::Add, + Size::Qword, + R8, + (element_bytes * length.bytes()) as i32, + ); + asm.alu_imm32(Alu::Cmp, Size::Dword, ROW_OFFSET, length.bytes() as i32); + let immediate = asm.jcc(Cond::B).offset(); patch_relative(code, immediate, row_start); - code.extend(ADD_RSP_IMM32); - code.extend((stack_bytes as u32).to_le_bytes()); + code.asm().release_stack(stack_bytes); } diff --git a/crates/stela-compiler/src/x86_64/sme/integer_products.rs b/crates/stela-compiler/src/x86_64/sme/integer_products.rs index 686a7ed3ff..376703548e 100644 --- a/crates/stela-compiler/src/x86_64/sme/integer_products.rs +++ b/crates/stela-compiler/src/x86_64/sme/integer_products.rs @@ -1,6 +1,6 @@ //! Integer product kernels shared by the SME families. +use crate::x86_64::asm::Code; use crate::{TargetCpu, x86_64::isa::SimdOpcode as Host}; -use alloc::vec::Vec; pub(crate) const PRODUCT_LEFT: u8 = 0; pub(crate) const PRODUCT_RIGHT: u8 = 1; @@ -13,7 +13,7 @@ pub(crate) const PRODUCT_HIGH: u8 = 4; /// XMM3 is scratch. All other XMM/GPR registers, memory and FP state survive. /// Widen each resulting product before any 64-bit sum; PMADDWD overflow cannot /// be repaired by sign-extending its already truncated pair result. -pub(crate) fn word_products(code: &mut Vec, signed: bool, target: TargetCpu) { +pub(crate) fn word_products(code: &mut Code, signed: bool, target: TargetCpu) { Host::MoveAligned.register(code, PRODUCT_TEMPORARY, PRODUCT_LEFT, target); Host::MultiplyLowWord.register(code, PRODUCT_LEFT, PRODUCT_RIGHT, target); (if signed { diff --git a/crates/stela-compiler/src/x86_64/sme/integer_vector.rs b/crates/stela-compiler/src/x86_64/sme/integer_vector.rs index c8eb0af29e..cf352bbbb1 100644 --- a/crates/stela-compiler/src/x86_64/sme/integer_vector.rs +++ b/crates/stela-compiler/src/x86_64/sme/integer_vector.rs @@ -1,4 +1,6 @@ //! SME2 multi-vector integer arithmetic on the shared SVE kernels. +use crate::x86_64::asm::Code; +use crate::x86_64::simd::encode::stack; use crate::{ TargetCpu, aarch64::{ @@ -10,7 +12,7 @@ use crate::{ }, }, x86_64::{ - isa::SimdOpcode as Host, + isa::{ShiftOpcode, SimdOpcode as Host}, scalable::{load_z_chunk, store_z_chunk}, sve::{ integer_arithmetic::emit_binary_chunk, @@ -20,53 +22,40 @@ use crate::{ }, }, }; -use alloc::vec::Vec; const RESULT: u8 = 0; const RIGHT: u8 = 1; const SAVED: u8 = 7; -const MOD_REGISTER: u8 = 0xc0; -const MOD_STACK_DISP32: u8 = 0x84; -const REGISTER_SHIFT: u8 = 3; -const STACK_SIB: u8 = 0x24; -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; -const PSLLDQ: &[u8] = &[0x66, 0x0f, 0x73]; -const LEFT_BYTES_GROUP: u8 = 7; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn copy(code: &mut Vec, destination: u8, source: u8) { +fn copy(code: &mut Code, destination: u8, source: u8) { packed(code, Host::MoveAligned, destination, source); } -fn stack_space(code: &mut Vec, bytes: usize, reserve: bool) { - code.extend(if reserve { - SUB_RSP_IMM32 +fn stack_space(code: &mut Code, bytes: usize, reserve: bool) { + if reserve { + code.asm().reserve_stack(bytes); } else { - ADD_RSP_IMM32 - }); - code.extend((bytes as u32).to_le_bytes()); + code.asm().release_stack(bytes); + } } -fn stack_chunk(code: &mut Vec, register: u8, offset: usize, store: bool, target: TargetCpu) { +fn stack_chunk(code: &mut Code, register: u8, offset: usize, store: bool, target: TargetCpu) { if store { Host::StoreUnaligned } else { Host::LoadUnaligned } - .append(code, target); - code.push(MOD_STACK_DISP32 | (register << REGISTER_SHIFT)); - code.push(STACK_SIB); - code.extend((offset as u32).to_le_bytes()); + .emit(code, register, stack(offset), target); } -fn byte_shift(code: &mut Vec, bytes: usize, group: u8) { +/// Shift the RESULT chunk left by `bytes`. +fn byte_shift(code: &mut Code, bytes: usize) { if bytes != 0 { - code.extend(PSLLDQ); - code.extend([MOD_REGISTER | group << REGISTER_SHIFT, bytes as u8]); + ShiftOpcode::LeftBytes.emit(code, RESULT, bytes as u8); } } @@ -76,7 +65,7 @@ fn unsigned(signedness: Signedness) -> bool { /// RDI/R15 preserve the shared entry context; all kernels preserve XMM7. /// Access/profile checks are performed before entering this emitter. -pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu) { match operand { Operand::Arithmetic(operand) => { arithmetic(code, operand, length, target); @@ -85,7 +74,7 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, } } -fn arithmetic(code: &mut Vec, operand: &Arithmetic, length: VectorLength, target: TargetCpu) { +fn arithmetic(code: &mut Code, operand: &Arithmetic, length: VectorLength, target: TargetCpu) { let clamp = matches!(operand.kind, ArithmeticKind::Clamp(_)); if clamp { stack_space(code, VECTOR_CHUNK_BYTES, true); @@ -200,7 +189,7 @@ fn narrow_kind(source: Signedness, destination: Signedness, rounded: bool) -> Na } } -fn narrow_source_chunk(code: &mut Vec, operand: &Narrow, target: TargetCpu) { +fn narrow_source_chunk(code: &mut Code, operand: &Narrow, target: TargetCpu) { let intermediate = ElementSize::from_bytes(operand.source_element.bytes() / 2).unwrap(); let project = if operand.interleaved { narrow_chunk @@ -233,7 +222,7 @@ fn narrow_source_chunk(code: &mut Vec, operand: &Narrow, target: TargetCpu) } } -fn narrow(code: &mut Vec, operand: &Narrow, length: VectorLength, target: TargetCpu) { +fn narrow(code: &mut Code, operand: &Narrow, length: VectorLength, target: TargetCpu) { let register_count = usize::from(operand.group.count()); let aliases = (operand.source..operand.source + operand.group.count()).contains(&operand.destination); @@ -275,17 +264,9 @@ fn narrow(code: &mut Vec, operand: &Narrow, length: VectorLength, target: Ta } narrow_source_chunk(code, operand, target); if operand.interleaved { - byte_shift( - code, - piece * operand.destination_element.bytes(), - LEFT_BYTES_GROUP, - ); + byte_shift(code, piece * operand.destination_element.bytes()); } else { - byte_shift( - code, - piece * (VECTOR_CHUNK_BYTES / register_count), - LEFT_BYTES_GROUP, - ); + byte_shift(code, piece * (VECTOR_CHUNK_BYTES / register_count)); } packed(code, Host::Or, SAVED, RESULT); } diff --git a/crates/stela-compiler/src/x86_64/sme/length.rs b/crates/stela-compiler/src/x86_64/sme/length.rs index 72bb22eac8..ed5ec334cb 100644 --- a/crates/stela-compiler/src/x86_64/sme/length.rs +++ b/crates/stela-compiler/src/x86_64/sme/length.rs @@ -2,22 +2,15 @@ use crate::aarch64::Register; use crate::aarch64::scalable::VectorLength; use crate::aarch64::sme::length::{Kind, Operand, Scale}; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Size}; +use crate::x86_64::simd::encode::guest; use crate::x86_64::{load, offset, store}; -use alloc::vec::Vec; -const NOP: u8 = 0x90; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const LEA_RAX_RAX_DISP8: &[u8] = &[0x48, 0x8d, 0x40]; -const ADD_RAX_IMM32: &[u8] = &[0x48, 0x05]; -const ADD_STATE_IMM8: &[u8] = &[0x48, 0x83, 0x87]; -const ADD_STATE_IMM32: &[u8] = &[0x48, 0x81, 0x87]; -const MOV_STATE_IMM32_SIGNED: &[u8] = &[0x48, 0xc7, 0x87]; - -pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength) { +pub(crate) fn emit(code: &mut Code, operand: &Operand, length: VectorLength) { // The caller must check SME access before entering this emitter, including // discarded results and identity operations. SM and ZA need not be enabled. if operand.destination == Register::Zero { - code.push(NOP); + code.asm().nop(); return; } let scale = match operand.kind { @@ -35,52 +28,37 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength) match operand.kind { Kind::Add { source, .. } => { if displacement == 0 && source == operand.destination { - code.push(NOP); + code.asm().nop(); return; } if source == operand.destination { - let short = i8::try_from(displacement).ok(); - code.extend(if short.is_some() { - ADD_STATE_IMM8 - } else { - ADD_STATE_IMM32 - }); - code.extend( - offset(source) - .expect("length add source is GPR or SP") - .to_le_bytes(), - ); - if let Some(displacement) = short { - code.push(displacement as u8); - } else { - code.extend(displacement.to_le_bytes()); - } + let state = guest(offset(source).expect("length add source is GPR or SP")); + code.asm() + .alu_imm(Alu::Add, Size::Qword, state, displacement); return; } load(code, source); if displacement != 0 { if let Ok(displacement) = i8::try_from(displacement) { - code.extend(LEA_RAX_RAX_DISP8); - code.extend(displacement.to_le_bytes()); + code.asm().lea( + Size::Qword, + Gpr::Rax, + Mem::base_disp8(Gpr::Rax, displacement), + ); } else { - code.extend(ADD_RAX_IMM32); - code.extend(displacement.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Add, Size::Qword, displacement); } } store(code, operand.destination); } Kind::Read => { if displacement == 0 { - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); store(code, operand.destination); } else { - code.extend(MOV_STATE_IMM32_SIGNED); - code.extend( - offset(operand.destination) - .expect("RDSVL destination is a GPR") - .to_le_bytes(), - ); - code.extend(displacement.to_le_bytes()); + let state = guest(offset(operand.destination).expect("RDSVL destination is a GPR")); + code.asm().mov_rm_imm32(Size::Qword, state, displacement); } } } diff --git a/crates/stela-compiler/src/x86_64/sme/memory.rs b/crates/stela-compiler/src/x86_64/sme/memory.rs index a858a64f9f..c5ecf615a2 100644 --- a/crates/stela-compiler/src/x86_64/sme/memory.rs +++ b/crates/stela-compiler/src/x86_64/sme/memory.rs @@ -1,5 +1,8 @@ //! SME loads and stores through the memory service. Loads commit after every //! element succeeds; stores submit one active element at a time. +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, ShiftOp, Size}; +use crate::x86_64::simd::encode::stack; use alloc::vec::Vec; mod za; @@ -39,32 +42,7 @@ const PREDICATE_GROUP_BITS_PER_BYTE: usize = 8; const MIN_PREDICATE_SCRATCH_BYTES: usize = 32; const ZT_BYTES: usize = 64; const VALUE_XMM: u8 = 0; -const MODRM_STACK_DISP32: u8 = 0x84; -const STACK_SIB: u8 = 0x24; -const REGISTER_SHIFT: u8 = 3; -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; -const MOV_RAX_RSP_DISP32: &[u8] = &[0x48, 0x8b, 0x84, 0x24]; -const MOV_RSP_DISP32_RAX: &[u8] = &[0x48, 0x89, 0x84, 0x24]; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const ADD_RAX_RCX: &[u8] = &[0x48, 0x01, 0xc8]; -const ADD_RAX_IMM32: &[u8] = &[0x48, 0x05]; -const SHL_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe0]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const TEST_AL_IMM8: &[u8] = &[0xa8]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JNC_REL32: &[u8] = &[0x0f, 0x83]; -const JB_REL32: &[u8] = &[0x0f, 0x82]; -const JMP_REL32: &[u8] = &[0xe9]; -const RET: u8 = 0xc3; -const MOV_RCX_RSP_DISP32: &[u8] = &[0x48, 0x8b, 0x8c, 0x24]; -const BT_RSP_DISP32_IMM8: &[u8] = &[0x48, 0x0f, 0xba, 0xa4, 0x24]; const FIRST_PREDICATE_BIT: u8 = 0; -const BT_RSP_DISP32_RCX: &[u8] = &[0x48, 0x0f, 0xa3, 0x8c, 0x24]; -const ADD_RSP_DISP32_IMM8: &[u8] = &[0x48, 0x83, 0x84, 0x24]; -const CMP_RSP_DISP32_IMM32: &[u8] = &[0x48, 0x81, 0xbc, 0x24]; -const MOV_R8_CONTEXT_DISP8: &[u8] = &[0x4d, 0x8b, 0x47]; -const MOV_R8_R8_DISP8: &[u8] = &[0x4d, 0x8b, 0x40]; struct Scratch { request: u32, @@ -198,7 +176,7 @@ pub(crate) fn validate_target(operand: &Operand, target: TargetCpu) -> Result<() } pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu, @@ -216,10 +194,10 @@ pub(crate) fn emit( _ => emit_za_body(code, operand, length, target, pc, &scratch, &mut failures), } stack_space(code, scratch.bytes, false); - let success = jump(code, JMP_REL32); + let success = jump(code, None); let failure = code.len(); stack_space(code, scratch.bytes, false); - code.push(RET); + code.asm().ret(); let done = code.len(); service::patch_branch(code, success, done); for displacement in failures { @@ -228,71 +206,104 @@ pub(crate) fn emit( Ok(()) } -fn stack_space(code: &mut Vec, bytes: u32, reserve: bool) { - code.extend(if reserve { - SUB_RSP_IMM32 +fn stack_space(code: &mut Code, bytes: u32, reserve: bool) { + if reserve { + code.asm().reserve_stack(bytes as usize); } else { - ADD_RSP_IMM32 - }); - code.extend(bytes.to_le_bytes()); + code.asm().release_stack(bytes as usize); + } } -fn load_guest(code: &mut Vec, register: Register) { +/// `[rsp + offset]` in the private scratch frame. +fn slot(offset: u32) -> Mem { + stack(offset as usize) +} + +/// The operand size of a `bytes`-byte scalar element. +fn scalar_size(bytes: usize) -> Size { + match bytes { + 1 => Size::Byte, + 2 => Size::Word, + 4 => Size::Dword, + 8 => Size::Qword, + _ => unreachable!("ZA scalar transfers require 1,2,4 or8 bytes"), + } +} + +/// Load a `bytes`-byte element from `memory` into RAX, zero-extended, or +/// store RAX's low `bytes` to it. +fn scalar_transfer(code: &mut Code, load: bool, bytes: usize, memory: Mem) { + let size = scalar_size(bytes); + let mut asm = code.asm(); + if !load { + asm.mov_store(size, memory, Gpr::Rax); + } else if bytes <= 2 { + asm.movzx(Size::Dword, Gpr::Rax, size, memory); + } else { + asm.mov_load(size, Gpr::Rax, memory); + } +} + +fn load_guest(code: &mut Code, register: Register) { crate::x86_64::load(code, register); } -fn stack_load(code: &mut Vec, offset: u32) { - code.extend(MOV_RAX_RSP_DISP32); - code.extend(offset.to_le_bytes()); +fn stack_load(code: &mut Code, offset: u32) { + code.asm().mov_load(Size::Qword, Gpr::Rax, slot(offset)); } -fn stack_store(code: &mut Vec, offset: u32) { - code.extend(MOV_RSP_DISP32_RAX); - code.extend(offset.to_le_bytes()); +fn stack_store(code: &mut Code, offset: u32) { + code.asm().mov_store(Size::Qword, slot(offset), Gpr::Rax); } -fn stack_vector(code: &mut Vec, load: bool, xmm: u8, offset: u32, target: TargetCpu) { +fn stack_vector(code: &mut Code, load: bool, xmm: u8, offset: u32, target: TargetCpu) { if load { Host::LoadUnaligned } else { Host::StoreUnaligned } - .append(code, target); - code.push(MODRM_STACK_DISP32 | (xmm << REGISTER_SHIFT)); - code.push(STACK_SIB); - code.extend(offset.to_le_bytes()); + .emit(code, xmm, slot(offset), target); } -fn pointer(code: &mut Vec, field: u32) { - code.extend(MOV_R8_CONTEXT_DISP8); - code.push(EXECUTION_CONTEXT_SCALABLE_OFFSET as u8); - code.extend(MOV_R8_R8_DISP8); - code.push(field as u8); +/// `mov r8, [r15 + scalable]; mov r8, [r8 + field]`: R8 points at the +/// scalable context `field`. +fn pointer(code: &mut Code, field: u32) { + let mut asm = code.asm(); + asm.mov_load( + Size::Qword, + Gpr::R8, + Mem::base_disp8(Gpr::R15, EXECUTION_CONTEXT_SCALABLE_OFFSET as i8), + ); + asm.mov_load(Size::Qword, Gpr::R8, Mem::base_disp8(Gpr::R8, field as i8)); } -fn jump(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement +/// A rel32 `jcc` on `condition`, or a `jmp` without one; returns the +/// displacement offset. +fn jump(code: &mut Code, condition: Option) -> usize { + let mut asm = code.asm(); + match condition { + Some(condition) => asm.jcc(condition), + None => asm.jmp(), + } + .offset() } -fn check_sp(code: &mut Vec, base: Register, pc: u64, failures: &mut Vec) { +fn check_sp(code: &mut Code, base: Register, pc: u64, failures: &mut Vec) { if base != Register::Sp { return; } load_guest(code, base); - code.extend(TEST_AL_IMM8); - code.push((STACK_ALIGNMENT - 1) as u8); - let aligned = jump(code, JZ_REL32); + code.asm() + .test_accumulator_imm(Size::Byte, (STACK_ALIGNMENT - 1) as i32); + let aligned = jump(code, Some(Cond::E)); service::fault(code, MemoryStatus::StackAlignment, pc); - failures.push(jump(code, JMP_REL32)); + failures.push(jump(code, None)); let destination = code.len(); service::patch_branch(code, aligned, destination); } fn transfer_loop( - code: &mut Vec, + code: &mut Code, transfer: Transfer, pc: u64, scratch: &Scratch, @@ -308,10 +319,13 @@ fn transfer_loop( ); if transfer.bytes == transfer.element_bytes { let inactive = if transfer.predicated { - code.extend(BT_RSP_DISP32_IMM8); - code.extend(scratch.predicate.to_le_bytes()); - code.push(FIRST_PREDICATE_BIT); - Some(jump(code, JNC_REL32)) + code.asm().bit_imm( + BitTest::Bt, + Size::Qword, + slot(scratch.predicate), + FIRST_PREDICATE_BIT, + ); + Some(jump(code, Some(Cond::Ae))) } else { None }; @@ -325,17 +339,16 @@ fn transfer_loop( // the supported no-CPA profile. No later access consumes those values. return; } - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); stack_store(code, scratch.iteration); let head = code.len(); let inactive = if transfer.predicated { - code.extend(MOV_RCX_RSP_DISP32); - code.extend(scratch.iteration.to_le_bytes()); + let mut asm = code.asm(); + asm.mov_load(Size::Qword, Gpr::Rcx, slot(scratch.iteration)); // Memory BT uses the complete nonnegative register bit index, advancing // its qword address for mask bits above63. - code.extend(BT_RSP_DISP32_RCX); - code.extend(scratch.predicate.to_le_bytes()); - Some(jump(code, JNC_REL32)) + asm.bit(BitTest::Bt, Size::Qword, slot(scratch.predicate), Gpr::Rcx); + Some(jump(code, Some(Cond::Ae))) } else { None }; @@ -350,19 +363,25 @@ fn transfer_loop( scratch.request + MEMORY_REQUEST_DATA_OFFSET, scratch.iteration, ] { - code.extend(ADD_RSP_DISP32_IMM8); - code.extend(offset.to_le_bytes()); - code.push(transfer.element_bytes as u8); + code.asm().alu_imm8( + Alu::Add, + Size::Qword, + slot(offset), + transfer.element_bytes as i8, + ); } - code.extend(CMP_RSP_DISP32_IMM32); - code.extend(scratch.iteration.to_le_bytes()); - code.extend(transfer.bytes.to_le_bytes()); - let repeat = jump(code, JB_REL32); + code.asm().alu_imm32( + Alu::Cmp, + Size::Qword, + slot(scratch.iteration), + transfer.bytes as i32, + ); + let repeat = jump(code, Some(Cond::B)); service::patch_branch(code, repeat, head); } fn emit_vectors( - code: &mut Vec, + code: &mut Code, operand: &VectorTransfer, length: VectorLength, target: TargetCpu, @@ -400,8 +419,8 @@ fn emit_vectors( let bytes = i32::from(offset) * i32::from(operand.registers.count) * length.bytes() as i32; if bytes != 0 { - code.extend(ADD_RAX_IMM32); - code.extend(bytes.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Add, Size::Qword, bytes); } } Offset::Register(register) => { @@ -409,12 +428,12 @@ fn emit_vectors( load_guest(code, register); let scale = operand.element.bytes().trailing_zeros() as u8; if scale != 0 { - code.extend(SHL_RAX_IMM8); - code.push(scale); + code.asm() + .shift_imm(ShiftOp::Shl, Size::Qword, Gpr::Rax, scale); } - code.extend(MOV_RCX_RAX); + code.asm().mov(Size::Qword, Gpr::Rcx, Gpr::Rax); stack_load(code, scratch.address); - code.extend(ADD_RAX_RCX); + code.asm().alu(Alu::Add, Size::Qword, Gpr::Rax, Gpr::Rcx); } } transfer_loop( @@ -464,7 +483,7 @@ mod tests { (QUADWORD_TILE_LOAD, TargetCpu::Cx16), (QUADWORD_TILE_STORE, TargetCpu::AtomicLoad16), ] { - let mut code = vec![NOP]; + let mut code = Code::from(vec![NOP]); assert!(emit(&mut code, &decode(word).unwrap(), length, target, 0).is_err()); assert_eq!(code, [NOP]); } diff --git a/crates/stela-compiler/src/x86_64/sme/memory/za.rs b/crates/stela-compiler/src/x86_64/sme/memory/za.rs index 05f710f64d..f9dec07f24 100644 --- a/crates/stela-compiler/src/x86_64/sme/memory/za.rs +++ b/crates/stela-compiler/src/x86_64/sme/memory/za.rs @@ -1,10 +1,12 @@ //! ZA and ZT0 staging and slice addressing. use super::{ - ADD_RAX_IMM32, SHL_RAX_IMM8, Scratch, Transfer, VALUE_XMM, ZT_BYTES, check_sp, load_guest, - pointer, stack_load, stack_store, stack_vector, transfer_loop, + Scratch, Transfer, VALUE_XMM, ZT_BYTES, check_sp, load_guest, pointer, scalar_transfer, slot, + stack_load, stack_store, stack_vector, transfer_loop, }; use crate::aarch64::sme::memory::TileTransfer; use crate::context::{SCALABLE_ZA_OFFSET, SCALABLE_ZT0_OFFSET}; +use crate::x86_64::asm::Code; +use crate::x86_64::asm::{Alu, Cond, Gpr, Mem, ShiftOp, Size}; use crate::{ TargetCpu, aarch64::{ @@ -17,71 +19,54 @@ use crate::{ use alloc::vec::Vec; const ZA_PACKED_PREDICATE_BYTES: usize = size_of::(); -const ZA_LEA_R9_RSP_DISP32: &[u8] = &[0x4c, 0x8d, 0x8c, 0x24]; -const ZA_ADD_R8_IMM32: &[u8] = &[0x49, 0x81, 0xc0]; -const ZA_ADD_R9_IMM8: &[u8] = &[0x49, 0x83, 0xc1]; -const ZA_MOV_ECX_IMM32: &[u8] = &[0xb9]; -const ZA_DEC_ECX: &[u8] = &[0xff, 0xc9]; -const ZA_JNZ_REL32: &[u8] = &[0x0f, 0x85]; -const ZA_LOAD_BYTE_R9: &[u8] = &[0x41, 0x0f, 0xb6, 0x01]; -const ZA_LOAD_HALFWORD_R9: &[u8] = &[0x41, 0x0f, 0xb7, 0x01]; -const ZA_LOAD_WORD_R9: &[u8] = &[0x41, 0x8b, 0x01]; -const ZA_LOAD_DOUBLEWORD_R9: &[u8] = &[0x49, 0x8b, 0x01]; -const ZA_STORE_BYTE_R9: &[u8] = &[0x41, 0x88, 0x01]; -const ZA_STORE_HALFWORD_R9: &[u8] = &[0x66, 0x41, 0x89, 0x01]; -const ZA_STORE_WORD_R9: &[u8] = &[0x41, 0x89, 0x01]; -const ZA_STORE_DOUBLEWORD_R9: &[u8] = &[0x49, 0x89, 0x01]; -const ZA_LOAD_XMM0_R9: &[u8] = &[0xf3, 0x41, 0x0f, 0x6f, 0x01]; -const ZA_STORE_XMM0_R9: &[u8] = &[0xf3, 0x41, 0x0f, 0x7f, 0x01]; -const ZA_ADD_EAX_IMM32: &[u8] = &[0x05]; -const ZA_AND_EAX_IMM32: &[u8] = &[0x25]; -const ZA_ADD_R8_RAX: &[u8] = &[0x49, 0x01, 0xc0]; -const ZA_ADD_RAX_RSP_DISP32: &[u8] = &[0x48, 0x03, 0x84, 0x24]; -const ZA_LOAD_BYTE_R8_DISP32: &[u8] = &[0x41, 0x0f, 0xb6, 0x80]; -const ZA_LOAD_HALFWORD_R8_DISP32: &[u8] = &[0x41, 0x0f, 0xb7, 0x80]; -const ZA_LOAD_WORD_R8_DISP32: &[u8] = &[0x41, 0x8b, 0x80]; -const ZA_LOAD_DOUBLEWORD_R8_DISP32: &[u8] = &[0x49, 0x8b, 0x80]; -const ZA_STORE_BYTE_R8_DISP32: &[u8] = &[0x41, 0x88, 0x80]; -const ZA_STORE_HALFWORD_R8_DISP32: &[u8] = &[0x66, 0x41, 0x89, 0x80]; -const ZA_STORE_WORD_R8_DISP32: &[u8] = &[0x41, 0x89, 0x80]; -const ZA_STORE_DOUBLEWORD_R8_DISP32: &[u8] = &[0x49, 0x89, 0x80]; +/// R8 walks the selected ZA rows; R9 walks the staged elements. +const ZA_CURSOR: Gpr = Gpr::R8; +const STAGING_CURSOR: Gpr = Gpr::R9; -fn za_add_rax(code: &mut Vec, immediate: usize) { +/// `add r8, imm32`. +fn za_advance(code: &mut Code, bytes: usize) { + code.asm().alu_imm32( + Alu::Add, + Size::Qword, + ZA_CURSOR, + u32::try_from(bytes).expect("ZA offset fits imm32") as i32, + ); +} + +fn za_add_rax(code: &mut Code, immediate: usize) { if immediate != 0 { - code.extend(ADD_RAX_IMM32); - code.extend( - u32::try_from(immediate) - .expect("ZA offset fits imm32") - .to_le_bytes(), + code.asm().alu_accumulator_imm32( + Alu::Add, + Size::Qword, + u32::try_from(immediate).expect("ZA offset fits imm32") as i32, ); } } -fn za_shift_rax(code: &mut Vec, shift: u32) { +fn za_shift_rax(code: &mut Code, shift: u32) { if shift != 0 { - code.extend(SHL_RAX_IMM8); - code.push(shift as u8); + code.asm() + .shift_imm(ShiftOp::Shl, Size::Qword, Gpr::Rax, shift as u8); } } -fn za_selector(code: &mut Vec, register: u8, offset: u8, count: usize, scale: usize) { +fn za_selector(code: &mut Code, register: u8, offset: u8, count: usize, scale: usize) { debug_assert!(count.is_power_of_two() && scale.is_power_of_two()); load_guest(code, Register::X(register)); // Addition modulo32 is equivalent before the power-of-two slice modulus. + let mut asm = code.asm(); if offset != 0 { - code.extend(ZA_ADD_EAX_IMM32); - code.extend(u32::from(offset).to_le_bytes()); + asm.alu_accumulator_imm32(Alu::Add, Size::Dword, offset.into()); } - code.extend(ZA_AND_EAX_IMM32); - code.extend( - u32::try_from(count - 1) - .expect("ZA selector mask fits u32") - .to_le_bytes(), + asm.alu_accumulator_imm32( + Alu::And, + Size::Dword, + u32::try_from(count - 1).expect("ZA selector mask fits u32") as i32, ); za_shift_rax(code, scale.trailing_zeros()); } -fn za_selected_pointer(code: &mut Vec, field: u32, selector: Option) { +fn za_selected_pointer(code: &mut Code, field: u32, selector: Option) { if field == SCALABLE_ZA_OFFSET { crate::x86_64::scalable_matrix::load_za_pointer_r8(code); } else { @@ -89,29 +74,22 @@ fn za_selected_pointer(code: &mut Vec, field: u32, selector: Option) { } if let Some(offset) = selector { stack_load(code, offset); - code.extend(ZA_ADD_R8_RAX); + code.asm().alu(Alu::Add, Size::Qword, ZA_CURSOR, Gpr::Rax); } } -fn za_scalar_memory(code: &mut Vec, load: bool, bytes: usize, offset: u32) { - let encoding = match (load, bytes) { - (true, 1) => ZA_LOAD_BYTE_R8_DISP32, - (true, 2) => ZA_LOAD_HALFWORD_R8_DISP32, - (true, 4) => ZA_LOAD_WORD_R8_DISP32, - (true, 8) => ZA_LOAD_DOUBLEWORD_R8_DISP32, - (false, 1) => ZA_STORE_BYTE_R8_DISP32, - (false, 2) => ZA_STORE_HALFWORD_R8_DISP32, - (false, 4) => ZA_STORE_WORD_R8_DISP32, - (false, 8) => ZA_STORE_DOUBLEWORD_R8_DISP32, - _ => unreachable!("ZA scalar transfers require 1,2,4 or8 bytes"), - }; - code.extend(encoding); - code.extend(offset.to_le_bytes()); +fn za_scalar_memory(code: &mut Code, load: bool, bytes: usize, offset: u32) { + scalar_transfer( + code, + load, + bytes, + Mem::base_disp32(ZA_CURSOR, offset as i32), + ); } // Copy one internal-state chunk to/from staging; no guest RAM is accessed here. fn za_copy_chunk( - code: &mut Vec, + code: &mut Code, to_staging: bool, bank_offset: usize, data_offset: u32, @@ -128,7 +106,7 @@ fn za_copy_chunk( } fn za_copy_bank( - code: &mut Vec, + code: &mut Code, to_staging: bool, field: u32, selector: Option, @@ -142,22 +120,12 @@ fn za_copy_bank( } } -fn za_staging_pointer_scalar(code: &mut Vec, load: bool, bytes: usize) { - code.extend(match (load, bytes) { - (true, 1) => ZA_LOAD_BYTE_R9, - (true, 2) => ZA_LOAD_HALFWORD_R9, - (true, 4) => ZA_LOAD_WORD_R9, - (true, 8) => ZA_LOAD_DOUBLEWORD_R9, - (false, 1) => ZA_STORE_BYTE_R9, - (false, 2) => ZA_STORE_HALFWORD_R9, - (false, 4) => ZA_STORE_WORD_R9, - (false, 8) => ZA_STORE_DOUBLEWORD_R9, - _ => unreachable!("ZA scalar transfers require 1,2,4 or8 bytes"), - }); +fn za_staging_pointer_scalar(code: &mut Code, load: bool, bytes: usize) { + scalar_transfer(code, load, bytes, Mem::base(STAGING_CURSOR, 0)); } fn za_copy_tile( - code: &mut Vec, + code: &mut Code, to_staging: bool, transfer: &TileTransfer, length: VectorLength, @@ -182,24 +150,22 @@ fn za_copy_tile( // loop makes no callbacks. za_selected_pointer(code, SCALABLE_ZA_OFFSET, Some(scratch.selector)); if transfer.tile != 0 { - code.extend(ZA_ADD_R8_IMM32); - code.extend((u32::from(transfer.tile) * bytes as u32).to_le_bytes()); + za_advance(code, usize::from(transfer.tile) * bytes); } - code.extend(ZA_LEA_R9_RSP_DISP32); - code.extend(scratch.data.to_le_bytes()); - code.extend(ZA_MOV_ECX_IMM32); - code.extend( - u32::try_from(bytes / element) - .expect("ZA lane count fits u32") - .to_le_bytes(), + let mut asm = code.asm(); + asm.lea(Size::Qword, STAGING_CURSOR, slot(scratch.data)); + asm.mov_imm32( + Gpr::Rcx, + u32::try_from(bytes / element).expect("ZA lane count fits u32"), ); let loop_start = code.len(); + let staged = Mem::base(STAGING_CURSOR, 0); if element == VECTOR_CHUNK_BYTES { if to_staging { crate::x86_64::scalable_matrix::load_za_chunk_at_r8(code, 0, 0, target); - code.extend(ZA_STORE_XMM0_R9); + Host::StoreUnaligned.emit(code, 0, staged, TargetCpu::Baseline); } else { - code.extend(ZA_LOAD_XMM0_R9); + Host::LoadUnaligned.emit(code, 0, staged, TargetCpu::Baseline); crate::x86_64::scalable_matrix::store_za_chunk_at_r8(code, 0, 0, target); } } else if to_staging { @@ -209,18 +175,11 @@ fn za_copy_tile( za_staging_pointer_scalar(code, true, element); za_scalar_memory(code, false, element, 0); } - code.extend(ZA_ADD_R8_IMM32); - code.extend( - u32::try_from(element * bytes) - .expect("ZA row stride fits u32") - .to_le_bytes(), - ); - code.extend(ZA_ADD_R9_IMM8); - code.push(element as u8); - code.extend(ZA_DEC_ECX); - code.extend(ZA_JNZ_REL32); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); + za_advance(code, element * bytes); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Add, Size::Qword, STAGING_CURSOR, element as i8); + asm.dec(Size::Dword, Gpr::Rcx); + let displacement = asm.jcc(Cond::Ne).offset(); crate::x86_64::scalable::memory::patch_branch(code, displacement, loop_start); } @@ -236,7 +195,7 @@ pub(super) fn access_flags(direction: Direction, tag_checked: bool) -> u32 { } fn za_tile_body( - code: &mut Vec, + code: &mut Code, transfer: &TileTransfer, length: VectorLength, target: TargetCpu, @@ -270,8 +229,8 @@ fn za_tile_body( za_shift_rax(code, element.trailing_zeros()); stack_store(code, scratch.address); load_guest(code, transfer.address.base); - code.extend(ZA_ADD_RAX_RSP_DISP32); - code.extend(scratch.address.to_le_bytes()); + code.asm() + .alu_load(Alu::Add, Size::Qword, Gpr::Rax, slot(scratch.address)); stack_store(code, scratch.address); let loading = transfer.direction == Direction::Load; if loading { @@ -308,7 +267,7 @@ fn za_tile_body( } fn za_whole_body( - code: &mut Vec, + code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu, @@ -361,7 +320,7 @@ fn za_whole_body( } pub(super) fn emit_za_body( - code: &mut Vec, + code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu, diff --git a/crates/stela-compiler/src/x86_64/sme/movement.rs b/crates/stela-compiler/src/x86_64/sme/movement.rs index 8e49a88f2d..976b444c76 100644 --- a/crates/stela-compiler/src/x86_64/sme/movement.rs +++ b/crates/stela-compiler/src/x86_64/sme/movement.rs @@ -1,5 +1,7 @@ //! ZA moves and zeroing. R8 holds the selected ZA address across helper calls, //! which clobber only RAX/RCX/RDX. +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, ShiftOp, Size, resolve}; +use crate::x86_64::simd::encode::guest; use super::super::{ isa::{ShiftOpcode, SimdOpcode as Host}, @@ -14,7 +16,6 @@ use crate::{ }, context::{EXECUTION_CONTEXT_SCALABLE_OFFSET, SCALABLE_ZT0_OFFSET}, }; -use alloc::vec::Vec; const VALUE: u8 = 0; const PREVIOUS: u8 = 1; @@ -23,46 +24,21 @@ const GATHER_HIGH: u8 = 3; const MASK: u8 = 4; const MASK_SCRATCH: u8 = 5; const ZERO: u8 = 6; -const MODRM_DISP32_R8: u8 = 0x80; -const MODRM_REGISTER: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; -const PREFIX_WORD: u8 = 0x66; -const PREFIX_REP: u8 = 0xf3; -const REX_R8_BASE: u8 = 0x41; const GPR_BYTES: usize = core::mem::size_of::(); const D_TILE_COUNT: usize = 8; const ZT0_BYTES: usize = 64; -const MOV_R8_CONTEXT_DISP8: &[u8] = &[0x4d, 0x8b, 0x47]; -const MOV_R8_R8_DISP8: &[u8] = &[0x4d, 0x8b, 0x40]; -const MOV_EAX_STATE_DISP32: &[u8] = &[0x8b, 0x87]; -const ADD_EAX_IMM32: &[u8] = &[0x05]; -const AND_EAX_IMM32: &[u8] = &[0x25]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const ADD_R8_RAX: &[u8] = &[0x49, 0x01, 0xc0]; -const ADD_R8_IMM32: &[u8] = &[0x49, 0x81, 0xc0]; -const MOV_ECX_IMM32: &[u8] = &[0xb9]; -const DEC_ECX: &[u8] = &[0xff, 0xc9]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -const MOVZX_EAX_BYTE_R8_DISP32: &[u8] = &[0x41, 0x0f, 0xb6, 0x80]; -const MOVZX_ECX_BYTE_R8_DISP32: &[u8] = &[0x41, 0x0f, 0xb6, 0x88]; -const SHL_ECX_BYTE: &[u8] = &[0xc1, 0xe1, 8]; -const OR_EAX_ECX: &[u8] = &[0x09, 0xc8]; -const PINSRW_XMM_EAX: &[u8] = &[0x66, 0x0f, 0xc4]; -const PINSRW_XMM_R8: &[u8] = &[0x66, 0x41, 0x0f, 0xc4]; -const MOVD_XMM_R8: &[u8] = &[0x66, 0x41, 0x0f, 0x6e]; -const MOVHPS_XMM_R8: &[u8] = &[0x41, 0x0f, 0x16]; -const PEXTRW_EAX_XMM: &[u8] = &[0x66, 0x0f, 0xc5]; -const MOVD_EAX_XMM: &[u8] = &[0x66, 0x0f, 0x7e]; -const MOVQ_RAX_XMM: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const SHR_EAX_BYTE: &[u8] = &[0xc1, 0xe8, 8]; -const PEXTRQ_R8_XMM: &[u8] = &[0x66, 0x49, 0x0f, 0x3a, 0x16]; -const MOV_BYTE_R8_AL: &[u8] = &[0x41, 0x88, 0x80]; -const MOV_WORD_R8_AX: &[u8] = &[0x66, 0x41, 0x89, 0x80]; -const MOV_DWORD_R8_EAX: &[u8] = &[0x41, 0x89, 0x80]; -const MOV_QWORD_R8_RAX: &[u8] = &[0x49, 0x89, 0x80]; +const BYTE_BITS: u8 = u8::BITS as u8; +/// R8 holds the selected ZA (or ZT0) address. +const ZA: Gpr = Gpr::R8; +use Gpr::{Rax, Rcx}; + +/// `[r8 + displacement]` with a 32-bit displacement. +fn za(displacement: usize) -> Mem { + Mem::base_disp32(ZA, displacement as i32) +} pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu, @@ -96,7 +72,7 @@ pub(crate) fn emit( }; scale_index(code, index_scale); add_address(code, usize::from(tile) * length.bytes()); - code.extend(ADD_R8_RAX); + add_index(code); for register in 0..count { for chunk in 0..length.chunks() { if direction == Direction::ToZa { @@ -151,7 +127,7 @@ pub(crate) fn emit( let stride = length.bytes() / usize::from(count); index_offset(code, index, offset, 1, stride); scale_index(code, length.bytes()); - code.extend(ADD_R8_RAX); + add_index(code); for register in 0..count { for chunk in 0..length.chunks() { if direction == Direction::ToZa { @@ -190,10 +166,13 @@ pub(crate) fn emit( load_za_pointer_r8(code); let stride = length.bytes() / usize::from(groups); index_offset(code, index, offset, 1, stride); - code.extend(AND_EAX_IMM32); - code.extend((!u32::from(vectors_per_group - 1)).to_le_bytes()); + code.asm().alu_accumulator_imm32( + Alu::And, + Size::Dword, + !u32::from(vectors_per_group - 1) as i32, + ); scale_index(code, length.bytes()); - code.extend(ADD_R8_RAX); + add_index(code); Host::Xor.register(code, ZERO, ZERO, target); for group in 0..groups { for chunk in 0..length.chunks() * usize::from(vectors_per_group) { @@ -244,23 +223,13 @@ pub(crate) fn emit( /// Called only by the halted-ITR entry; the ordinary movement emitter still /// rejects TableGpr. pub(crate) fn emit_debug_table_gpr( - code: &mut Vec, + code: &mut Code, operand: &Operand, - recipe: crate::extended::debug_movement::Recipe, + recipe: crate::scalable_context::debug_movement::Recipe, ) -> Result<(), &'static str> { - use crate::extended::debug_movement::Recipe; + use crate::scalable_context::debug_movement::Recipe; const ZERO_REGISTER: u8 = 31; const TABLE_LANES: u8 = 8; - const MOV_RAX_STATE_DISP32: &[u8] = &[0x48, 0x8b, 0x87]; - const MOV_STATE_DISP32_RAX: &[u8] = &[0x48, 0x89, 0x87]; - const MOV_RAX_R8_DISP8: &[u8] = &[0x49, 0x8b, 0x40]; - const MOV_R8_DISP8_RAX: &[u8] = &[0x49, 0x89, 0x40]; - const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; - const MOVQ_XMM0_STATE_DISP32: &[u8] = &[0xf3, 0x0f, 0x7e, 0x87]; - const MOVQ_STATE_DISP32_XMM0: &[u8] = &[0x66, 0x0f, 0xd6, 0x87]; - const MOVQ_XMM0_R8_DISP8: &[u8] = &[0xf3, 0x41, 0x0f, 0x7e, 0x40]; - const MOVQ_R8_DISP8_XMM0: &[u8] = &[0x66, 0x41, 0x0f, 0xd6, 0x40]; - const PXOR_XMM0_XMM0: &[u8] = &[0x66, 0x0f, 0xef, 0xc0]; let Kind::TableGpr { direction, register, @@ -276,89 +245,92 @@ pub(crate) fn emit_debug_table_gpr( return Ok(()); } pointer(code, SCALABLE_ZT0_OFFSET); - let state_offset = - (core::mem::offset_of!(GuestState, x) + usize::from(register) * GPR_BYTES) as u32; - let lane_offset = lane * GPR_BYTES as u8; + let state = + guest((core::mem::offset_of!(GuestState, x) + usize::from(register) * GPR_BYTES) as u32); + let entry = Mem::base_disp8(ZA, (lane * GPR_BYTES as u8) as i8); + let baseline = TargetCpu::Baseline; match (direction, recipe) { (Direction::ToZa, Recipe::Scalar) => { + let mut asm = code.asm(); if register == ZERO_REGISTER { - code.extend(XOR_EAX_EAX); + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); } else { - code.extend(MOV_RAX_STATE_DISP32); - code.extend(state_offset.to_le_bytes()); + asm.mov_load(Size::Qword, Rax, state); } - code.extend(MOV_R8_DISP8_RAX); - code.push(lane_offset); + asm.mov_store(Size::Qword, entry, Rax); } (Direction::FromZa, Recipe::Scalar) => { - code.extend(MOV_RAX_R8_DISP8); - code.push(lane_offset); - code.extend(MOV_STATE_DISP32_RAX); - code.extend(state_offset.to_le_bytes()); + let mut asm = code.asm(); + asm.mov_load(Size::Qword, Rax, entry); + asm.mov_store(Size::Qword, state, Rax); } (Direction::ToZa, Recipe::Sse2Comparison) => { if register == ZERO_REGISTER { - code.extend(PXOR_XMM0_XMM0); + Host::Xor.register(code, VALUE, VALUE, baseline); } else { - code.extend(MOVQ_XMM0_STATE_DISP32); - code.extend(state_offset.to_le_bytes()); + Host::MoveQword.emit(code, VALUE, state, baseline); } - code.extend(MOVQ_R8_DISP8_XMM0); - code.push(lane_offset); + code.asm().movq_store(VALUE, entry); } (Direction::FromZa, Recipe::Sse2Comparison) => { - code.extend(MOVQ_XMM0_R8_DISP8); - code.push(lane_offset); - code.extend(MOVQ_STATE_DISP32_XMM0); - code.extend(state_offset.to_le_bytes()); + Host::MoveQword.emit(code, VALUE, entry, baseline); + code.asm().movq_store(VALUE, state); } } Ok(()) } -fn pointer(code: &mut Vec, field: u32) { - code.extend(MOV_R8_CONTEXT_DISP8); - code.push(EXECUTION_CONTEXT_SCALABLE_OFFSET as u8); - code.extend(MOV_R8_R8_DISP8); - code.push(field as u8); +/// `mov r8, [r15 + scalable]; mov r8, [r8 + field]`: R8 points at the +/// scalable context `field`. +fn pointer(code: &mut Code, field: u32) { + let mut asm = code.asm(); + asm.mov_load( + Size::Qword, + ZA, + Mem::base_disp8(Gpr::R15, EXECUTION_CONTEXT_SCALABLE_OFFSET as i8), + ); + asm.mov_load(Size::Qword, ZA, Mem::base_disp8(ZA, field as i8)); } -fn index_offset(code: &mut Vec, register: u8, offset: u8, align: usize, modulus: usize) { - code.extend(MOV_EAX_STATE_DISP32); - code.extend( - (core::mem::offset_of!(GuestState, x) as u32 + u32::from(register) * GPR_BYTES as u32) - .to_le_bytes(), +fn index_offset(code: &mut Code, register: u8, offset: u8, align: usize, modulus: usize) { + let mut asm = code.asm(); + asm.mov_load( + Size::Dword, + Rax, + guest(core::mem::offset_of!(GuestState, x) as u32 + u32::from(register) * GPR_BYTES as u32), ); if align > 1 { - code.extend(AND_EAX_IMM32); - code.extend((!(align as u32 - 1)).to_le_bytes()); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, !(align as u32 - 1) as i32); } if offset != 0 { - code.extend(ADD_EAX_IMM32); - code.extend(u32::from(offset).to_le_bytes()); + asm.alu_accumulator_imm32(Alu::Add, Size::Dword, offset.into()); } // All supported SME lengths and all divisors here are powers of two. A // wrapped 32-bit addition therefore has the same residue as UInt(W)+offset. - code.extend(AND_EAX_IMM32); - code.extend((modulus as u32 - 1).to_le_bytes()); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, (modulus as u32 - 1) as i32); } -fn scale_index(code: &mut Vec, scale: usize) { +fn scale_index(code: &mut Code, scale: usize) { debug_assert!(scale.is_power_of_two()); if scale > 1 { - code.extend(SHL_EAX_IMM8); - code.push(scale.trailing_zeros() as u8); + code.asm() + .shift_imm(ShiftOp::Shl, Size::Dword, Rax, scale.trailing_zeros() as u8); } } -fn add_address(code: &mut Vec, displacement: usize) { +/// `add r8, rax`: apply the scaled slice index. +fn add_index(code: &mut Code) { + code.asm().alu(Alu::Add, Size::Qword, ZA, Rax); +} + +fn add_address(code: &mut Code, displacement: usize) { if displacement != 0 { - code.extend(ADD_R8_IMM32); - code.extend((displacement as u32).to_le_bytes()); + code.asm() + .alu_imm32(Alu::Add, Size::Qword, ZA, displacement as i32); } } -fn contiguous(code: &mut Vec, opcode: Host, xmm: u8, displacement: usize) { +fn contiguous(code: &mut Code, opcode: Host, xmm: u8, displacement: usize) { match opcode { Host::LoadUnaligned => { load_za_chunk_at_r8(code, xmm, displacement as u32, TargetCpu::Baseline); @@ -371,29 +343,11 @@ fn contiguous(code: &mut Vec, opcode: Host, xmm: u8, displacement: usize) { Host::MoveQword => {} _ => unreachable!("movement memory uses MOVDQU or MOVQ only"), } - - let bytes = opcode.encoding(); - debug_assert!(matches!(bytes[0], PREFIX_WORD | PREFIX_REP)); - code.push(bytes[0]); - code.push(REX_R8_BASE); - code.extend(&bytes[1..]); - code.push(MODRM_DISP32_R8 | (xmm << REGISTER_SHIFT)); - code.extend((displacement as u32).to_le_bytes()); -} - -fn memory(code: &mut Vec, opcode: &[u8], displacement: usize) { - code.extend(opcode); - code.extend((displacement as u32).to_le_bytes()); -} - -fn simd_memory(code: &mut Vec, opcode: &[u8], xmm: u8, displacement: usize) { - code.extend(opcode); - code.push(MODRM_DISP32_R8 | (xmm << REGISTER_SHIFT)); - code.extend((displacement as u32).to_le_bytes()); + opcode.emit(code, xmm, za(displacement), TargetCpu::Baseline); } fn load_slice( - code: &mut Vec, + code: &mut Code, output: u8, chunk: usize, element: ElementSize, @@ -416,40 +370,40 @@ fn load_slice( match element { ElementSize::Byte => { for pair in 0..VECTOR_CHUNK_BYTES / 2 { - memory(code, MOVZX_EAX_BYTE_R8_DISP32, address(pair * 2)); - memory(code, MOVZX_ECX_BYTE_R8_DISP32, address(pair * 2 + 1)); - code.extend(SHL_ECX_BYTE); - code.extend(OR_EAX_ECX); - code.extend(PINSRW_XMM_EAX); - code.push(MODRM_REGISTER | (output << REGISTER_SHIFT)); - code.push(pair as u8); + let mut asm = code.asm(); + asm.movzx(Size::Dword, Rax, Size::Byte, za(address(pair * 2))); + asm.movzx(Size::Dword, Rcx, Size::Byte, za(address(pair * 2 + 1))); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rcx, BYTE_BITS); + asm.alu(Alu::Or, Size::Dword, Rax, Rcx); + asm.pinsrw(output, Rax, pair as u8); } } ElementSize::Halfword => { for lane in 0..VECTOR_CHUNK_BYTES / size { - simd_memory(code, PINSRW_XMM_R8, output, address(lane)); - code.push(lane as u8); + code.asm().pinsrw(output, za(address(lane)), lane as u8); } } ElementSize::Word => { - simd_memory(code, MOVD_XMM_R8, output, address(0)); - simd_memory(code, MOVD_XMM_R8, GATHER_SCRATCH, address(1)); + let mut asm = code.asm(); + asm.movd_to_xmm(output, za(address(0))); + asm.movd_to_xmm(GATHER_SCRATCH, za(address(1))); Host::UnpackLowDword.register(code, output, GATHER_SCRATCH, target); - simd_memory(code, MOVD_XMM_R8, GATHER_SCRATCH, address(2)); - simd_memory(code, MOVD_XMM_R8, GATHER_HIGH, address(3)); + let mut asm = code.asm(); + asm.movd_to_xmm(GATHER_SCRATCH, za(address(2))); + asm.movd_to_xmm(GATHER_HIGH, za(address(3))); Host::UnpackLowDword.register(code, GATHER_SCRATCH, GATHER_HIGH, target); Host::UnpackLowQword.register(code, output, GATHER_SCRATCH, target); } ElementSize::Doubleword => { contiguous(code, Host::MoveQword, output, address(0)); - simd_memory(code, MOVHPS_XMM_R8, output, address(1)); + code.asm().movhps(output, za(address(1))); } ElementSize::Quadword => unreachable!("contiguous quadword handled above"), } } fn store_slice( - code: &mut Vec, + code: &mut Code, input: u8, chunk: usize, element: ElementSize, @@ -471,43 +425,34 @@ fn store_slice( let address = |lane| (first + lane) * size * length.bytes(); if element == ElementSize::Doubleword && target.supports(TargetCpu::Sse41) { for lane in 0..VECTOR_CHUNK_BYTES / size { - simd_memory(code, PEXTRQ_R8_XMM, input, address(lane)); - code.push(lane as u8); + code.asm().pextrq(za(address(lane)), input, lane as u8); } return; } match element { ElementSize::Byte | ElementSize::Halfword => { for pair in 0..VECTOR_CHUNK_BYTES / 2 { - code.extend(PEXTRW_EAX_XMM); - code.push(MODRM_REGISTER | input); - code.push(pair as u8); + let mut asm = code.asm(); + asm.pextrw(Rax, input, pair as u8); if element == ElementSize::Byte { - memory(code, MOV_BYTE_R8_AL, address(pair * 2)); - code.extend(SHR_EAX_BYTE); - memory(code, MOV_BYTE_R8_AL, address(pair * 2 + 1)); + asm.mov_store(Size::Byte, za(address(pair * 2)), Rax); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, BYTE_BITS); + asm.mov_store(Size::Byte, za(address(pair * 2 + 1)), Rax); } else { - memory(code, MOV_WORD_R8_AX, address(pair)); + asm.mov_store(Size::Word, za(address(pair)), Rax); } } } ElementSize::Word | ElementSize::Doubleword => { for lane in 0..VECTOR_CHUNK_BYTES / size { - code.extend(if element == ElementSize::Word { - MOVD_EAX_XMM + let mut asm = code.asm(); + if element == ElementSize::Word { + asm.movd_from_xmm(Rax, input); + asm.mov_store(Size::Dword, za(address(lane)), Rax); } else { - MOVQ_RAX_XMM - }); - code.push(MODRM_REGISTER | (input << REGISTER_SHIFT)); - memory( - code, - if element == ElementSize::Word { - MOV_DWORD_R8_EAX - } else { - MOV_QWORD_R8_RAX - }, - address(lane), - ); + asm.movq_from_xmm(Rax, input); + asm.mov_store(Size::Qword, za(address(lane)), Rax); + } if lane + 1 < VECTOR_CHUNK_BYTES / size { ShiftOpcode::RightBytes.emit(code, input, size as u8); } @@ -517,18 +462,17 @@ fn store_slice( } } -fn zero_rows(code: &mut Vec, count: usize, step: usize, length: VectorLength, zero: u8) { - code.extend(MOV_ECX_IMM32); - code.extend((count as u32).to_le_bytes()); +fn zero_rows(code: &mut Code, count: usize, step: usize, length: VectorLength, zero: u8) { + code.asm().mov_imm32(Rcx, count as u32); let start = code.len(); for chunk in 0..length.chunks() { contiguous(code, Host::StoreUnaligned, zero, chunk * VECTOR_CHUNK_BYTES); } add_address(code, step); - code.extend(DEC_ECX); - code.extend(JNZ_REL32); - let relative = start as i64 - (code.len() as i64 + core::mem::size_of::() as i64); - code.extend((relative as i32).to_le_bytes()); + let mut asm = code.asm(); + asm.dec(Size::Dword, Rcx); + let repeat = asm.jcc(Cond::Ne); + resolve(code, repeat, start); } #[cfg(test)] @@ -536,7 +480,6 @@ mod tests { use super::*; use crate::aarch64::sme::movement::decode; use alloc::vec; - use alloc::vec::Vec; #[test] fn rejected_debug_and_short_length_emit_nothing() { @@ -549,7 +492,7 @@ mod tests { 0xc0c4_0400, ] { let operand = decode(word).unwrap(); - let mut code = vec![0x90]; + let mut code = Code::from(vec![0x90]); assert!(emit(&mut code, &operand, length, TargetCpu::Baseline).is_err()); assert_eq!(code, [0x90]); } @@ -559,7 +502,7 @@ mod tests { fn empty_tile_mask_has_no_output_and_full_mask_is_bounded() { for bytes in [16, 32, 64, 128, 256] { let length = VectorLength::from_bytes(bytes).unwrap(); - let mut code = Vec::new(); + let mut code = Code::new(); emit( &mut code, &decode(0xc008_0000).unwrap(), @@ -590,15 +533,15 @@ mod tests { 0xc0c2_8000, ] { let operand = decode(word).unwrap(); - let mut baseline = Vec::new(); - let mut checked = Vec::new(); + let mut baseline = Code::new(); + let mut checked = Code::new(); emit(&mut baseline, &operand, length, TargetCpu::Baseline).unwrap(); emit(&mut checked, &operand, length, TargetCpu::Sse41).unwrap(); assert_eq!(baseline, checked); } let operand = decode(0xc0c0_8000).unwrap(); - let mut baseline = Vec::new(); - let mut checked = Vec::new(); + let mut baseline = Code::new(); + let mut checked = Code::new(); emit(&mut baseline, &operand, length, TargetCpu::Baseline).unwrap(); emit(&mut checked, &operand, length, TargetCpu::Sse41).unwrap(); assert!(checked.len() < baseline.len()); diff --git a/crates/stela-compiler/src/x86_64/sme/tables.rs b/crates/stela-compiler/src/x86_64/sme/tables.rs index 4b3cd94309..f025ab7e22 100644 --- a/crates/stela-compiler/src/x86_64/sme/tables.rs +++ b/crates/stela-compiler/src/x86_64/sme/tables.rs @@ -1,5 +1,7 @@ //! SME2 multi-vector permutes, specialized to the streaming vector length. //! Sources are staged whole so aliases are preserved across chunks. +use crate::x86_64::asm::Code; +use crate::x86_64::simd::encode::stack; use crate::TargetCpu; use crate::aarch64::scalable::{ElementSize, MAX_VECTOR_BYTES, VECTOR_CHUNK_BYTES, VectorLength}; @@ -7,44 +9,30 @@ use crate::aarch64::sme::tables::{Kind, Operand, PermuteSources}; use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; use crate::x86_64::scalable::{load_z_chunk, read_predicate_chunk, routing, store_z_chunk}; use crate::x86_64::sve::predicate::{emit_prepared_counter_mask, prepare_counter}; -use alloc::vec::Vec; mod lookup; const MAX_SOURCE_REGISTERS: usize = 4; const MAX_PRIVATE_FRAME_BYTES: usize = MAX_SOURCE_REGISTERS * MAX_VECTOR_BYTES; -const MODRM_STACK_DISP32: u8 = 0x84; -const SIB_STACK: u8 = 0x24; -const MODRM_REGISTER_SHIFT: u8 = 3; -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; - -fn stack_chunk(code: &mut Vec, load: bool, offset: usize, xmm: u8, target: TargetCpu) { +fn stack_chunk(code: &mut Code, load: bool, offset: usize, xmm: u8, target: TargetCpu) { if load { Host::LoadUnaligned } else { Host::StoreUnaligned } - .append(code, target); - code.extend([ - MODRM_STACK_DISP32 | (xmm << MODRM_REGISTER_SHIFT), - SIB_STACK, - ]); - code.extend((offset as u32).to_le_bytes()); + .emit(code, xmm, stack(offset), target); } -fn allocate_frame(code: &mut Vec, bytes: usize) { +fn allocate_frame(code: &mut Code, bytes: usize) { assert!(bytes <= MAX_PRIVATE_FRAME_BYTES && bytes.is_multiple_of(VECTOR_CHUNK_BYTES)); - code.extend(SUB_RSP_IMM32); - code.extend((bytes as u32).to_le_bytes()); + code.asm().reserve_stack(bytes); } -fn release_frame(code: &mut Vec, bytes: usize) { - code.extend(ADD_RSP_IMM32); - code.extend((bytes as u32).to_le_bytes()); +fn release_frame(code: &mut Code, bytes: usize) { + code.asm().release_stack(bytes); } -fn stage(code: &mut Vec, sources: &[u8], length: VectorLength, target: TargetCpu) { +fn stage(code: &mut Code, sources: &[u8], length: VectorLength, target: TargetCpu) { assert!(sources.len() <= MAX_SOURCE_REGISTERS); for (source_index, register) in sources.iter().enumerate() { for chunk in 0..length.chunks() { @@ -61,7 +49,7 @@ fn stage(code: &mut Vec, sources: &[u8], length: VectorLength, target: Targe } fn commit_global_chunk( - code: &mut Vec, + code: &mut Code, operand: &Operand, global_chunk: usize, xmm: u8, @@ -82,7 +70,7 @@ fn commit_global_chunk( } fn load_source_chunk( - code: &mut Vec, + code: &mut Code, registers: &[u8], source_chunk: usize, xmm: u8, @@ -105,7 +93,7 @@ fn load_source_chunk( } fn permutation( - code: &mut Vec, + code: &mut Code, operand: &Operand, sources: PermuteSources, unzip: bool, @@ -137,7 +125,7 @@ fn permutation( if shuffled { routing::prepare_split_masks(code, operand.element, target); } - let split = |code: &mut Vec, first, second, even, odd| { + let split = |code: &mut Code, first, second, even, odd| { if shuffled { routing::split_destructive(code, first, second, even, odd, target); } else { @@ -217,7 +205,7 @@ fn permutation( } fn unpack( - code: &mut Vec, + code: &mut Code, operand: &Operand, source: crate::aarch64::sme::tables::VectorGroup, signed: bool, @@ -293,7 +281,7 @@ fn unpack( } fn select( - code: &mut Vec, + code: &mut Code, operand: &Operand, left: crate::aarch64::sme::tables::VectorGroup, right: crate::aarch64::sme::tables::VectorGroup, @@ -365,7 +353,7 @@ pub(crate) fn requires_dit_zero( } } -pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu) { assert!(length.bits() >= operand.minimum_svl_bits()); match operand.kind { Kind::Lookup { @@ -386,7 +374,7 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, } pub(crate) fn emit_lut_v2( - code: &mut Vec, + code: &mut Code, operand: &crate::aarch64::sme::lut_v2::Operand, length: VectorLength, target: TargetCpu, diff --git a/crates/stela-compiler/src/x86_64/sme/tables/lookup.rs b/crates/stela-compiler/src/x86_64/sme/tables/lookup.rs index c0338e73e4..9257ee5bcd 100644 --- a/crates/stela-compiler/src/x86_64/sme/tables/lookup.rs +++ b/crates/stela-compiler/src/x86_64/sme/tables/lookup.rs @@ -1,13 +1,11 @@ //! LUTI2/LUTI4 from ZT0 with scalar gathers, SSE2 selects and SSSE3 shuffles. //! ZT0 entries always have a 32-bit stride. Scratch registers are XMM0-7. +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, ShiftOp, Size}; +use crate::x86_64::simd::encode::stack; -use alloc::vec::Vec; pub(super) mod lut_v2; -use super::{ - MODRM_REGISTER_SHIFT, MODRM_STACK_DISP32, SIB_STACK, allocate_frame, release_frame, - stack_chunk, stage, -}; +use super::{allocate_frame, release_frame, stack_chunk, stage}; use crate::TargetCpu; use crate::aarch64::scalable::{ BITS_PER_BYTE, ElementSize, LOOKUP_TABLE_BYTES, VECTOR_CHUNK_BYTES, VectorLength, @@ -29,8 +27,6 @@ const FIRST_INDEX_SPREAD_SHIFT: u8 = 12; const SECOND_INDEX_SPREAD_SHIFT: u8 = 6; const TABLE_ENTRY_BYTE_SHIFT: u8 = 2; const NIBBLE_BITS: u8 = 4; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_DISP8: u8 = 0x40; const XMM0: u8 = 0; const XMM1: u8 = 1; const XMM2: u8 = 2; @@ -39,24 +35,8 @@ const XMM4: u8 = 4; const XMM5: u8 = 5; const XMM6: u8 = 6; const XMM7: u8 = 7; -const MOV_R8_CONTEXT_DISP8: &[u8] = &[0x4d, 0x8b, 0x47]; -const MOV_R8_R8_DISP8: &[u8] = &[0x4d, 0x8b, 0x40]; -const MOV_EAX_IMM32: &[u8] = &[0xb8]; -const MOVABS_RAX_IMM64: &[u8] = &[0x48, 0xb8]; -const MOVD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; -const MOVQ_XMM_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e]; -const MOVDQU_XMM_R8_DISP8: &[u8] = &[0xf3, 0x41, 0x0f, 0x6f]; -const MOVD_XMM_STACK_DISP32: &[u8] = &[0x66, 0x0f, 0x6e]; -const MOVQ_XMM_STACK_DISP32: &[u8] = &[0xf3, 0x0f, 0x7e]; -const MOVZX_EAX_BYTE: &[u8] = &[0x0f, 0xb6]; -const MOVZX_EAX_WORD: &[u8] = &[0x0f, 0xb7]; -const MOVZX_EAX_STACK_BYTE: &[u8] = &[0x0f, 0xb6, 0x84, SIB_STACK]; -const SHR_EAX_IMM8: &[u8] = &[0xc1, 0xe8]; -const AND_EAX_IMM8: &[u8] = &[0x83, 0xe0]; -const MOV_EDX_R8_RAX_SCALE4: &[u8] = &[0x41, 0x8b, 0x14, 0x80]; -const MOV_STACK_DL: &[u8] = &[0x88, 0x94, SIB_STACK]; -const MOV_STACK_DX: &[u8] = &[0x66, 0x89, 0x94, SIB_STACK]; -const MOV_STACK_EDX: &[u8] = &[0x89, 0x94, SIB_STACK]; +/// R8 points at ZT0 while a lookup runs. +const TABLE: Gpr = Gpr::R8; const INDEX_SPLIT_NIBBLE_MASK: u32 = 0x000f_000f; const TWO_BIT_BYTE_MASK: u32 = 0x0303_0303; @@ -72,7 +52,7 @@ const LOCAL_BYTE_TRANSPOSE_HIGH: u64 = 0x0f0b_0703_0e0a_0602; const MIN_POLYNOMIAL_HALFWORD_OUTPUT_CHUNKS: usize = 4; fn stage_source_and_table( - code: &mut Vec, + code: &mut Code, source: u8, frame_bytes: usize, length: VectorLength, @@ -80,14 +60,26 @@ fn stage_source_and_table( ) { allocate_frame(code, frame_bytes); stage(code, &[source], length, target); - code.extend(MOV_R8_CONTEXT_DISP8); - code.push(EXECUTION_CONTEXT_SCALABLE_OFFSET as u8); - code.extend(MOV_R8_R8_DISP8); - code.push(SCALABLE_ZT0_OFFSET as u8); + table_pointer(code); +} + +/// `mov r8, [r15 + scalable]; mov r8, [r8 + zt0]`: R8 points at ZT0. +fn table_pointer(code: &mut Code) { + let mut asm = code.asm(); + asm.mov_load( + Size::Qword, + TABLE, + Mem::base_disp8(Gpr::R15, EXECUTION_CONTEXT_SCALABLE_OFFSET as i8), + ); + asm.mov_load( + Size::Qword, + TABLE, + Mem::base_disp8(TABLE, SCALABLE_ZT0_OFFSET as i8), + ); } fn lookup_scalar( - code: &mut Vec, + code: &mut Code, operand: &Operand, source: u8, index_bits: u8, @@ -108,24 +100,39 @@ fn lookup_scalar( for lane in 0..VECTOR_CHUNK_BYTES / operand.element.bytes() { let global_lane = chunk * (VECTOR_CHUNK_BYTES / operand.element.bytes()) + lane; let index_bit = (base + global_lane) * usize::from(index_bits); - code.extend(MOVZX_EAX_STACK_BYTE); - code.extend(((index_bit / BITS_PER_BYTE) as u32).to_le_bytes()); + let mut asm = code.asm(); + asm.movzx( + Size::Dword, + Gpr::Rax, + Size::Byte, + stack(index_bit / BITS_PER_BYTE), + ); if !index_bit.is_multiple_of(BITS_PER_BYTE) { - code.extend(SHR_EAX_IMM8); - code.push((index_bit % BITS_PER_BYTE) as u8); + asm.shift_imm( + ShiftOp::Shr, + Size::Dword, + Gpr::Rax, + (index_bit % BITS_PER_BYTE) as u8, + ); } - code.extend(AND_EAX_IMM8); - code.push((1 << index_bits) - 1); + asm.alu_imm8( + Alu::And, + Size::Dword, + Gpr::Rax, + ((1 << index_bits) - 1) as i8, + ); // All ZT0 entries are 32 bits, even for Byte/Halfword outputs. - code.extend(MOV_EDX_R8_RAX_SCALE4); - code.extend(match operand.element { - ElementSize::Byte => MOV_STACK_DL, - ElementSize::Halfword => MOV_STACK_DX, - ElementSize::Word => MOV_STACK_EDX, + asm.mov_load(Size::Dword, Gpr::Rdx, Mem::indexed(TABLE, Gpr::Rax, 4, 0)); + let size = match operand.element { + ElementSize::Byte => Size::Byte, + ElementSize::Halfword => Size::Word, + ElementSize::Word => Size::Dword, _ => unreachable!("LUTI output is at most Word"), - }); - code.extend( - ((output_offset + lane * operand.element.bytes()) as u32).to_le_bytes(), + }; + asm.mov_store( + size, + stack(output_offset + lane * operand.element.bytes()), + Gpr::Rdx, ); } stack_chunk(code, true, output_offset, XMM0, target); @@ -142,30 +149,31 @@ fn lookup_scalar( release_frame(code, frame_bytes); } -fn splat_dword(code: &mut Vec, xmm: u8, value: u32, target: TargetCpu) { - code.extend(MOV_EAX_IMM32); - code.extend(value.to_le_bytes()); - code.extend(MOVD_XMM_EAX); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT)); - Host::ShuffleDword.register(code, xmm, xmm, target); - code.push(REPEAT_FIRST_ELEMENT); +fn splat_dword(code: &mut Code, xmm: u8, value: u32, target: TargetCpu) { + let mut asm = code.asm(); + asm.mov_imm32(Gpr::Rax, value); + asm.movd_to_xmm(xmm, Gpr::Rax); + Host::ShuffleDword.register_imm(code, xmm, xmm, REPEAT_FIRST_ELEMENT, target); } -fn qword_constant(code: &mut Vec, xmm: u8, value: u64) { - code.extend(MOVABS_RAX_IMM64); - code.extend(value.to_le_bytes()); - code.extend(MOVQ_XMM_RAX); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT)); +fn qword_constant(code: &mut Code, xmm: u8, value: u64) { + let mut asm = code.asm(); + asm.mov_imm64(Gpr::Rax, value); + asm.movq_to_xmm(xmm, Gpr::Rax); } -fn transpose_constant(code: &mut Vec, target: TargetCpu) { +fn transpose_constant(code: &mut Code, target: TargetCpu) { qword_constant(code, XMM0, LOCAL_BYTE_TRANSPOSE_LOW); qword_constant(code, XMM1, LOCAL_BYTE_TRANSPOSE_HIGH); Host::UnpackLowQword.register(code, XMM0, XMM1, target); } -fn load_table_chunk(code: &mut Vec, xmm: u8, offset: u8) { - code.extend(MOVDQU_XMM_R8_DISP8); - code.extend([MODRM_DISP8 | (xmm << MODRM_REGISTER_SHIFT), offset]); +fn load_table_chunk(code: &mut Code, xmm: u8, offset: u8) { + Host::LoadUnaligned.emit( + code, + xmm, + Mem::base_disp8(TABLE, offset as i8), + TargetCpu::Baseline, + ); } -fn prepare_planes(code: &mut Vec, element: ElementSize, target: TargetCpu) { +fn prepare_planes(code: &mut Code, element: ElementSize, target: TargetCpu) { for i in 0..ZT0_CHUNKS { load_table_chunk(code, XMM4 + i, i * VECTOR_CHUNK_BYTES as u8); } @@ -205,37 +213,20 @@ fn prepare_planes(code: &mut Vec, element: ElementSize, target: TargetCpu) { Host::MoveAligned.register(code, XMM7, XMM0, target); } } -fn load_packed_indexes(code: &mut Vec, bytes: usize, offset: usize) { +fn load_packed_indexes(code: &mut Code, bytes: usize, offset: usize) { match bytes { 1 | 2 => { - code.extend(if bytes == 1 { - MOVZX_EAX_BYTE - } else { - MOVZX_EAX_WORD - }); - code.extend([MODRM_STACK_DISP32, SIB_STACK]); - code.extend((offset as u32).to_le_bytes()); - code.extend(MOVD_XMM_EAX); - code.push(MODRM_REGISTER); - } - 4 | 8 => { - code.extend(if bytes == 4 { - MOVD_XMM_STACK_DISP32 - } else { - MOVQ_XMM_STACK_DISP32 - }); - code.extend([MODRM_STACK_DISP32, SIB_STACK]); - code.extend((offset as u32).to_le_bytes()); + let from = if bytes == 1 { Size::Byte } else { Size::Word }; + let mut asm = code.asm(); + asm.movzx(Size::Dword, Gpr::Rax, from, stack(offset)); + asm.movd_to_xmm(XMM0, Gpr::Rax); } + 4 => code.asm().movd_to_xmm(XMM0, stack(offset)), + 8 => Host::MoveQword.emit(code, XMM0, stack(offset), TargetCpu::Baseline), _ => unreachable!("LUTI packs one, two, four or eight source bytes per output chunk"), } } -fn shuffle_lookup_chunk( - code: &mut Vec, - element: ElementSize, - index_bits: u8, - target: TargetCpu, -) { +fn shuffle_lookup_chunk(code: &mut Code, element: ElementSize, index_bits: u8, target: TargetCpu) { let zero = if index_bits == LUTI4_INDEX_BITS && element == ElementSize::Word { Host::Xor.register(code, XMM2, XMM2, target); splat_dword(code, XMM3, FOUR_BIT_BYTE_MASK, target); @@ -300,7 +291,7 @@ fn shuffle_lookup_chunk( } fn lookup_simd( - code: &mut Vec, + code: &mut Code, operand: &Operand, source: u8, index_bits: u8, @@ -357,7 +348,7 @@ fn lookup_simd( /// Expand packed two-bit indices and evaluate the two-variable table polynomial. /// Table coefficients occupy XMM4..7; return the result's scratch register. -fn polynomial_lookup_chunk(code: &mut Vec, element: ElementSize, target: TargetCpu) -> u8 { +fn polynomial_lookup_chunk(code: &mut Code, element: ElementSize, target: TargetCpu) -> u8 { Host::Xor.register(code, XMM2, XMM2, target); Host::UnpackLowByte.register(code, XMM0, XMM2, target); Host::UnpackLowWord.register(code, XMM0, XMM2, target); @@ -409,7 +400,7 @@ fn polynomial_lookup_chunk(code: &mut Vec, element: ElementSize, target: Tar } fn lookup_sse2_poly( - code: &mut Vec, + code: &mut Code, operand: &Operand, source: u8, immediate: u8, @@ -423,18 +414,33 @@ fn lookup_sse2_poly( stage_source_and_table(code, source, length.bytes(), length, target); load_table_chunk(code, XMM0, 0); for i in 0..LUTI2_TABLE_ENTRIES { - Host::ShuffleDword.register(code, XMM4 + i, XMM0, target); - code.push(DWORD_REPEAT_SELECTORS[usize::from(i)]); + Host::ShuffleDword.register_imm( + code, + XMM4 + i, + XMM0, + DWORD_REPEAT_SELECTORS[usize::from(i)], + target, + ); match operand.element { ElementSize::Byte => { Host::UnpackLowByte.register(code, XMM4 + i, XMM4 + i, target); Host::UnpackLowWord.register(code, XMM4 + i, XMM4 + i, target); - Host::ShuffleDword.register(code, XMM4 + i, XMM4 + i, target); - code.push(REPEAT_FIRST_ELEMENT); + Host::ShuffleDword.register_imm( + code, + XMM4 + i, + XMM4 + i, + REPEAT_FIRST_ELEMENT, + target, + ); } ElementSize::Halfword => { - Host::ShuffleLowWord.register(code, XMM4 + i, XMM4 + i, target); - code.push(REPEAT_FIRST_ELEMENT); + Host::ShuffleLowWord.register_imm( + code, + XMM4 + i, + XMM4 + i, + REPEAT_FIRST_ELEMENT, + target, + ); Host::UnpackLowQword.register(code, XMM4 + i, XMM4 + i, target); } _ => unreachable!("Polynomial lookup has Byte/Halfword output"), @@ -507,7 +513,7 @@ pub(super) fn recipe( } pub(super) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, source: u8, index_bits: u8, diff --git a/crates/stela-compiler/src/x86_64/sme/tables/lookup/lut_v2.rs b/crates/stela-compiler/src/x86_64/sme/tables/lookup/lut_v2.rs index 59027cc4bb..167e74a843 100644 --- a/crates/stela-compiler/src/x86_64/sme/tables/lookup/lut_v2.rs +++ b/crates/stela-compiler/src/x86_64/sme/tables/lookup/lut_v2.rs @@ -1,42 +1,24 @@ //! SME_LUTv2: LUTI4 with two index vectors, and MOVT to ZT0. +use crate::x86_64::asm::{Code, Mem}; use super::super::{allocate_frame, release_frame, stage}; -use super::{MOV_R8_CONTEXT_DISP8, MOV_R8_R8_DISP8, XMM0, load_packed_indexes, prepare_planes}; +use super::{TABLE, XMM0, load_packed_indexes, prepare_planes, table_pointer}; use crate::TargetCpu; use crate::aarch64::scalable::{ElementSize, LOOKUP_TABLE_BYTES, VECTOR_CHUNK_BYTES, VectorLength}; use crate::aarch64::sme::lut_v2::Operand; -use crate::context::{EXECUTION_CONTEXT_SCALABLE_OFFSET, SCALABLE_ZT0_OFFSET}; use crate::x86_64::isa::SimdOpcode as Host; use crate::x86_64::scalable::{load_z_chunk, lut, store_z_chunk}; -use alloc::vec::Vec; const INDEX_BITS: u8 = 4; const RESULT_XMM: u8 = 6; const ZERO_XMM: u8 = 1; -const MODRM_DISP32_R8: u8 = 0x80; -const REGISTER_SHIFT: u8 = 3; -const REX_R8_BASE: u8 = 0x41; -fn table_pointer(code: &mut Vec) { - code.extend(MOV_R8_CONTEXT_DISP8); - code.push(EXECUTION_CONTEXT_SCALABLE_OFFSET as u8); - code.extend(MOV_R8_R8_DISP8); - code.push(SCALABLE_ZT0_OFFSET as u8); -} - -fn store_table_chunk(code: &mut Vec, xmm: u8, offset: usize, target: TargetCpu) { - assert!(target.supports(Host::StoreUnaligned.requires())); - let opcode = Host::StoreUnaligned.encoding(); - // REX.B selects R8 after the mandatory REP prefix and before the opcode. - code.push(opcode[0]); - code.push(REX_R8_BASE); - code.extend(&opcode[1..]); - code.push(MODRM_DISP32_R8 | (xmm << REGISTER_SHIFT)); - code.extend((offset as u32).to_le_bytes()); +fn store_table_chunk(code: &mut Code, xmm: u8, offset: usize, target: TargetCpu) { + Host::StoreUnaligned.emit(code, xmm, Mem::base_disp32(TABLE, offset as i32), target); } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu, diff --git a/crates/stela-compiler/src/x86_64/sve/address.rs b/crates/stela-compiler/src/x86_64/sve/address.rs index 067151a00e..59d67903e4 100644 --- a/crates/stela-compiler/src/x86_64/sve/address.rs +++ b/crates/stela-compiler/src/x86_64/sve/address.rs @@ -6,26 +6,11 @@ use crate::aarch64::{ scalable::{ElementSize, VectorLength}, sve::address::{Count, Destination, Kind, Operand, Saturation}, }; +use crate::x86_64::asm::Gpr::{R8, Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use crate::x86_64::isa::{ShiftOpcode, SimdOpcode as Host}; use crate::x86_64::scalable::{load_z_chunk, read_predicate_chunk, store_z_chunk}; -use alloc::vec::Vec; -const MOV_EAX_IMM32: u8 = 0xb8; -const MOV_RAX_IMM32: &[u8] = &[0x48, 0xc7, 0xc0]; -const MOV_EDX_IMM32: u8 = 0xba; -const MOV_RDX_IMM64: &[u8] = &[0x48, 0xba]; -const ADD_RAX_IMM8: &[u8] = &[0x48, 0x83, 0xc0]; -const ADD_RAX_IMM32: &[u8] = &[0x48, 0x05]; -const ADD_EAX_IMM8: &[u8] = &[0x83, 0xc0]; -const SUB_EAX_IMM8: &[u8] = &[0x83, 0xe8]; -const ADD_EAX_IMM32: u8 = 0x05; -const SUB_EAX_IMM32: u8 = 0x2d; -const ADD_EAX_ECX: &[u8] = &[0x01, 0xc8]; -const SUB_EAX_ECX: &[u8] = &[0x29, 0xc8]; -const CMOVO_EAX_EDX: &[u8] = &[0x0f, 0x40, 0xc2]; -const CMOVB_EAX_EDX: &[u8] = &[0x0f, 0x42, 0xc2]; -const MOVSXD_RAX_EAX: &[u8] = &[0x48, 0x63, 0xc0]; -const REX_W: u8 = 0x48; const BITS32: u8 = 32; const BITS64: u8 = 64; const PATTERN_POW2: u8 = 0; @@ -49,11 +34,7 @@ pub(super) fn pattern_count(pattern: u8, element: ElementSize, length: VectorLen /// Handles scalar operations whose count is known from the selected profile. /// Returns false before emitting anything for instructions needing P/Z access. -pub(super) fn emit_static_scalar( - code: &mut Vec, - operand: &Operand, - length: VectorLength, -) -> bool { +pub(super) fn emit_static_scalar(code: &mut Code, operand: &Operand, length: VectorLength) -> bool { let Destination::Scalar { register, .. } = operand.destination else { return false; }; @@ -73,19 +54,16 @@ pub(super) fn emit_static_scalar( load(code, source); if displacement != 0 { if let Ok(short) = i8::try_from(displacement) { - code.extend(ADD_RAX_IMM8); - code.push(short as u8); + code.asm().alu_imm8(Alu::Add, Size::Qword, Rax, short); } else { - code.extend(ADD_RAX_IMM32); - code.extend(displacement.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Add, Size::Qword, displacement); } } } else if displacement >= 0 { - code.push(MOV_EAX_IMM32); - code.extend((displacement as u32).to_le_bytes()); + code.asm().mov_imm32(Rax, displacement as u32); } else { - code.extend(MOV_RAX_IMM32); - code.extend(displacement.to_le_bytes()); + code.asm().mov_rm_imm32(Size::Qword, Rax, displacement); } store(code, register); } @@ -94,8 +72,7 @@ pub(super) fn emit_static_scalar( multiplier, }) => { let count = pattern_count(pattern, operand.element, length) * u32::from(multiplier); - code.push(MOV_EAX_IMM32); - code.extend(count.to_le_bytes()); + code.asm().mov_imm32(Rax, count); store(code, register); } Kind::Adjust { @@ -116,11 +93,11 @@ pub(super) fn emit_static_scalar( /// Consume a nonnegative architectural population count in RCX. Scalar32 /// saturation always extends its W result, even when the runtime count is zero. -pub(super) fn emit_scalar_adjust(code: &mut Vec, operand: &Operand) { +pub(super) fn emit_scalar_adjust(code: &mut Code, operand: &Operand) { scalar_adjust(code, operand, None); } -fn scalar_adjust(code: &mut Vec, operand: &Operand, constant_count: Option) { +fn scalar_adjust(code: &mut Code, operand: &Operand, constant_count: Option) { let Destination::Scalar { register, bits } = operand.destination else { unreachable!("scalar count backend received a vector destination"); }; @@ -139,7 +116,7 @@ fn scalar_adjust(code: &mut Vec, operand: &Operand, constant_count: Option, + code: &mut Code, bits: u8, subtract: bool, saturation: Saturation, @@ -157,66 +134,36 @@ fn scalar_value_adjust( _ => unreachable!("invalid scalar saturation width"), }; if bound <= u64::from(u32::MAX) { - code.push(MOV_EDX_IMM32); - code.extend((bound as u32).to_le_bytes()); + code.asm().mov_imm32(Rdx, bound as u32); } else { - code.extend(MOV_RDX_IMM64); - code.extend(bound.to_le_bytes()); + code.asm().mov_imm64(Rdx, bound); } } - if bits == BITS64 { - code.push(REX_W); - } - if let Some(count) = constant_count { - if count <= i8::MAX as u32 { - code.extend(if subtract { SUB_EAX_IMM8 } else { ADD_EAX_IMM8 }); - code.push(count as u8); - } else { - code.push(if subtract { - SUB_EAX_IMM32 - } else { - ADD_EAX_IMM32 - }); - code.extend(count.to_le_bytes()); - } + let size = if bits == BITS64 { + Size::Qword } else { - code.extend(if subtract { SUB_EAX_ECX } else { ADD_EAX_ECX }); + Size::Dword + }; + let op = if subtract { Alu::Sub } else { Alu::Add }; + let mut asm = code.asm(); + match constant_count { + Some(count) if count <= i8::MAX as u32 => asm.alu_imm8(op, size, Rax, count as i8), + Some(count) => asm.alu_accumulator_imm32(op, size, count as i32), + None => asm.alu(op, size, Rax, Rcx), } if saturation != Saturation::Wrapping { - if bits == BITS64 { - code.push(REX_W); - } - code.extend(if saturation == Saturation::Signed { - CMOVO_EAX_EDX + let overflow = if saturation == Saturation::Signed { + Cond::O } else { - CMOVB_EAX_EDX - }); + Cond::B + }; + asm.cmov(overflow, size, Rax, Rdx); } if bits == BITS32 && saturation == Saturation::Signed { - code.extend(MOVSXD_RAX_EAX); + code.asm().movsxd(Rax, Rax); } } -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const MOV_R8_IMM64: &[u8] = &[0x49, 0xb8]; -const AND_RAX_R8: &[u8] = &[0x4c, 0x21, 0xc0]; -const AND_RDX_R8: &[u8] = &[0x4c, 0x21, 0xc2]; -const AND_RAX_RDX: &[u8] = &[0x48, 0x21, 0xd0]; -const SUB_RAX_RDX: &[u8] = &[0x48, 0x29, 0xd0]; -const ADD_RAX_RDX: &[u8] = &[0x48, 0x01, 0xd0]; -const SHR_RDX_IMM8: &[u8] = &[0x48, 0xc1, 0xea]; -const SHR_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe8]; -const IMUL_RAX_R8: &[u8] = &[0x49, 0x0f, 0xaf, 0xc0]; -const POPCNT_RAX_RAX: &[u8] = &[0xf3, 0x48, 0x0f, 0xb8, 0xc0]; -const XOR_ECX_ECX: &[u8] = &[0x31, 0xc9]; -const ADD_RCX_RAX: &[u8] = &[0x48, 0x01, 0xc1]; -const MOV_RAX_RCX: &[u8] = &[0x48, 0x89, 0xc8]; -const MOVD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; -const MOVQ_RDX_XMM7: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xfa]; -const MOVQ_XMM7_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xf8]; -const MOVQ_RAX_XMM0: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xc0]; -const MODRM_REGISTER: u8 = 0xc0; -const HOST_REGISTER_SHIFT: u8 = 3; const QWORD_BITS: usize = 64; const QWORD_BYTES: usize = 8; const POPCOUNT_PAIRS: u64 = 0x5555_5555_5555_5555; @@ -235,46 +182,45 @@ const VECTOR_TEMPORARY: u8 = 7; const BROADCAST_LOW_DWORD: u8 = 0; const DWORD_SIGN_BIT: u32 = 1 << 31; -fn mask_r8(code: &mut Vec, mask: u64) { - code.extend(MOV_R8_IMM64); - code.extend(mask.to_le_bytes()); +fn mask_r8(code: &mut Code, mask: u64) { + code.asm().mov_imm64(R8, mask); } /// Count low RAX bits. Preserves RCX; clobbers RAX/RDX/R8 and host flags. -fn population_count(code: &mut Vec, target: TargetCpu) { +fn population_count(code: &mut Code, target: TargetCpu) { if target.supports(TargetCpu::Popcnt) { - code.extend(POPCNT_RAX_RAX); + code.asm().popcnt(Size::Qword, Rax, Rax); return; } - code.extend(MOV_RDX_RAX); - code.extend(SHR_RDX_IMM8); - code.push(1); + let mut asm = code.asm(); + asm.mov(Size::Qword, Rdx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rdx, 1); mask_r8(code, POPCOUNT_PAIRS); - code.extend(AND_RDX_R8); - code.extend(SUB_RAX_RDX); - code.extend(MOV_RDX_RAX); + let mut asm = code.asm(); + asm.alu(Alu::And, Size::Qword, Rdx, R8); + asm.alu(Alu::Sub, Size::Qword, Rax, Rdx); + asm.mov(Size::Qword, Rdx, Rax); mask_r8(code, POPCOUNT_QUADS); - code.extend(AND_RAX_R8); - code.extend(SHR_RDX_IMM8); - code.push(2); - code.extend(AND_RDX_R8); - code.extend(ADD_RAX_RDX); - code.extend(MOV_RDX_RAX); - code.extend(SHR_RDX_IMM8); - code.push(4); - code.extend(ADD_RAX_RDX); + let mut asm = code.asm(); + asm.alu(Alu::And, Size::Qword, Rax, R8); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rdx, 2); + asm.alu(Alu::And, Size::Qword, Rdx, R8); + asm.alu(Alu::Add, Size::Qword, Rax, Rdx); + asm.mov(Size::Qword, Rdx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rdx, 4); + asm.alu(Alu::Add, Size::Qword, Rax, Rdx); mask_r8(code, POPCOUNT_NIBBLES); - code.extend(AND_RAX_R8); + code.asm().alu(Alu::And, Size::Qword, Rax, R8); mask_r8(code, POPCOUNT_BYTE_SUM); - code.extend(IMUL_RAX_R8); - code.extend(SHR_RAX_IMM8); - code.push(POPCOUNT_SUM_SHIFT); + let mut asm = code.asm(); + asm.imul(Size::Qword, Rax, R8); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rax, POPCOUNT_SUM_SHIFT); } /// Read one or two complete P values, count element-leading bits into RCX. /// Clobbers RAX/RDX/R8/XMM7; preserves architectural status, RDI and R15. fn count_predicate( - code: &mut Vec, + code: &mut Code, source: u8, governing: Option, element: ElementSize, @@ -284,59 +230,58 @@ fn count_predicate( let mask = (0..QWORD_BITS) .step_by(element.bytes()) .fold(0, |mask, bit| mask | (1u64 << bit)); - code.extend(XOR_ECX_ECX); + code.asm().alu(Alu::Xor, Size::Dword, Rcx, Rcx); for chunk in 0..length.predicate_bytes().div_ceil(QWORD_BYTES) { read_predicate_chunk(code, source, chunk, length); if let Some(governing) = governing { - code.extend(MOVQ_XMM7_RAX); + code.asm().movq_to_xmm(7, Rax); read_predicate_chunk(code, governing, chunk, length); - code.extend(MOVQ_RDX_XMM7); - code.extend(AND_RAX_RDX); + let mut asm = code.asm(); + asm.movq_from_xmm(Rdx, 7); + asm.alu(Alu::And, Size::Qword, Rax, Rdx); } if mask != u64::MAX { mask_r8(code, mask); - code.extend(AND_RAX_R8); + code.asm().alu(Alu::And, Size::Qword, Rax, R8); } population_count(code, target); - code.extend(ADD_RCX_RAX); + code.asm().alu(Alu::Add, Size::Qword, Rcx, Rax); } } -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn broadcast_eax(code: &mut Vec, destination: u8, element: ElementSize) { +fn broadcast_eax(code: &mut Code, destination: u8, element: ElementSize) { if element == ElementSize::Doubleword { - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MODRM_REGISTER | destination << HOST_REGISTER_SHIFT); + code.asm() + .simd(Host::MoveGprQword, destination, Rax, TargetCpu::Baseline); packed(code, Host::UnpackLowQword, destination, destination); } else { - code.extend(MOVD_XMM_EAX); - code.push(MODRM_REGISTER | destination << HOST_REGISTER_SHIFT); + code.asm().movd_to_xmm(destination, Rax); if element == ElementSize::Halfword { packed(code, Host::UnpackLowWord, destination, destination); } - packed(code, Host::ShuffleDword, destination, destination); - code.push(BROADCAST_LOW_DWORD); + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(destination), + BROADCAST_LOW_DWORD, + TargetCpu::Baseline, + ); } } -fn broadcast_constant(code: &mut Vec, value: u32, destination: u8) { - code.push(MOV_EAX_IMM32); - code.extend(value.to_le_bytes()); +fn broadcast_constant(code: &mut Code, value: u32, destination: u8) { + code.asm().mov_imm32(Rax, value); broadcast_eax(code, destination, ElementSize::Word); } /// RCX contains one nonnegative count applied to all vector elements. /// SSE2 handles H directly and W with threshold masks. Saturating D uses two /// scalar ADD/SUB+CMOV lanes per chunk until a measured checked recipe wins. -fn emit_vector_adjust( - code: &mut Vec, - operand: &Operand, - length: VectorLength, - target: TargetCpu, -) { +fn emit_vector_adjust(code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu) { let Destination::Vector(destination) = operand.destination else { unreachable!("vector adjustment"); }; @@ -349,7 +294,7 @@ fn emit_vector_adjust( unreachable!("vector adjustment"); }; let element = operand.element; - code.extend(MOV_RAX_RCX); + code.asm().mov(Size::Qword, Rax, Rcx); broadcast_eax(code, VECTOR_DELTA, element); if element == ElementSize::Word && saturation != Saturation::Wrapping { let limit = match (saturation, subtract) { @@ -361,7 +306,12 @@ fn emit_vector_adjust( }; broadcast_constant(code, limit, VECTOR_LIMIT); // EAX still holds limit: threshold is limit -/+ count. - code.extend(if subtract { ADD_EAX_ECX } else { SUB_EAX_ECX }); + code.asm().alu( + if subtract { Alu::Add } else { Alu::Sub }, + Size::Dword, + Rax, + Rcx, + ); broadcast_eax(code, VECTOR_THRESHOLD, ElementSize::Word); if saturation == Saturation::Unsigned { broadcast_constant(code, DWORD_SIGN_BIT, VECTOR_BIAS); @@ -419,33 +369,30 @@ fn emit_vector_adjust( } } -fn saturating_qwords(code: &mut Vec, subtract: bool, saturation: Saturation) { +fn saturating_qwords(code: &mut Code, subtract: bool, saturation: Saturation) { for lane in 0..2 { if lane != 0 { ShiftOpcode::RightBytes.emit(code, VECTOR_RESULT, QWORD_BYTES as u8); } - code.extend(MOVQ_RAX_XMM0); + code.asm().movq_from_xmm(Rax, 0); scalar_value_adjust(code, BITS64, subtract, saturation, None); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push( - MODRM_REGISTER - | (if lane == 0 { - VECTOR_DELTA - } else { - VECTOR_LIMIT - }) << HOST_REGISTER_SHIFT, + code.asm().simd( + Host::MoveGprQword, + if lane == 0 { + VECTOR_DELTA + } else { + VECTOR_LIMIT + }, + Rax, + TargetCpu::Baseline, ); } packed(code, Host::UnpackLowQword, VECTOR_DELTA, VECTOR_LIMIT); } -const MOV_ECX_IMM32: u8 = 0xb9; -const PUSH_RCX: u8 = 0x51; -const POP_RCX: u8 = 0x59; - /// Emit a complete scalable count instruction after the shared entry profile /// checks. Clobbers caller-saved GPRs/XMM0..7; keeps RDI/R15 and guest status. -pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu) { if emit_static_scalar(code, operand, length) { return; } @@ -458,10 +405,9 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, pattern, multiplier, } => { - code.push(MOV_ECX_IMM32); - code.extend( - (pattern_count(pattern, operand.element, length) * u32::from(multiplier)) - .to_le_bytes(), + code.asm().mov_imm32( + Rcx, + pattern_count(pattern, operand.element, length) * u32::from(multiplier), ); } Count::Predicate(source) => { @@ -477,30 +423,30 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, ), Count::Counter { source, vectors } => { let bits = length.bytes() * usize::from(vectors); - code.extend(XOR_ECX_ECX); + code.asm().alu(Alu::Xor, Size::Dword, Rcx, Rcx); for chunk in 0..bits.div_ceil(QWORD_BITS) { read_predicate_chunk(code, source, 0, length); // Shared CounterToPredicate uses RCX/R8..11; preserve only the // accumulating count. No helper emits a host CALL here. - code.push(PUSH_RCX); + code.asm().push(Rcx); emit_counter_chunk(code, chunk, length); - code.push(POP_RCX); + code.asm().pop(Rcx); let remaining = (bits - chunk * QWORD_BITS).min(QWORD_BITS); let mask = (0..remaining) .step_by(operand.element.bytes()) .fold(0, |mask, bit| mask | (1u64 << bit)); if mask != u64::MAX { mask_r8(code, mask); - code.extend(AND_RAX_R8); + code.asm().alu(Alu::And, Size::Qword, Rax, R8); } population_count(code, target); - code.extend(ADD_RCX_RAX); + code.asm().alu(Alu::Add, Size::Qword, Rcx, Rax); } } } match (operand.destination, operand.kind) { (Destination::Scalar { register, .. }, Kind::Count(_)) => { - code.extend(MOV_RAX_RCX); + code.asm().mov(Size::Qword, Rax, Rcx); store(code, register); } (Destination::Scalar { .. }, Kind::Adjust { .. }) => emit_scalar_adjust(code, operand), diff --git a/crates/stela-compiler/src/x86_64/sve/dot.rs b/crates/stela-compiler/src/x86_64/sve/dot.rs index 1ecbe07b53..9b0498b3b4 100644 --- a/crates/stela-compiler/src/x86_64/sve/dot.rs +++ b/crates/stela-compiler/src/x86_64/sve/dot.rs @@ -1,12 +1,12 @@ //! SVE integer dot products, one 128-bit segment at a time. All sources are //! staged before each destination chunk is written. +use crate::x86_64::asm::{Code, Rm}; use crate::TargetCpu; use crate::aarch64::scalable::{ElementSize, VECTOR_CHUNK_BYTES, VectorLength, is_z_register}; use crate::aarch64::sve::dot::{Kind, Operand, Products, RightOperand, Signedness}; use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; use crate::x86_64::scalable::{load_z_chunk, store_z_chunk}; -use alloc::vec::Vec; const LEFT: u8 = 0; const RIGHT: u8 = 1; @@ -28,16 +28,21 @@ const BROADCAST_DWORD: u8 = 0x55; const INDEXED_WORD_REGISTERS: u8 = 8; const INDEXED_DOUBLEWORD_REGISTERS: u8 = 16; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn shuffle(code: &mut Vec, destination: u8, source: u8, control: u8) { - packed(code, Host::ShuffleDword, destination, source); - code.push(control); +fn shuffle(code: &mut Code, destination: u8, source: u8, control: u8) { + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(source), + control, + TargetCpu::Baseline, + ); } -fn index_right(code: &mut Vec, operand: &Operand) { +fn index_right(code: &mut Code, operand: &Operand) { if let RightOperand::Indexed { index, .. } = operand.right { let control = if operand.element_size == ElementSize::Word { index * BROADCAST_DWORD @@ -52,7 +57,7 @@ fn index_right(code: &mut Vec, operand: &Operand) { /// Split byte pairs into signed or unsigned word lanes. XMM0/2 receive the /// even/odd left bytes, XMM1/3 the even/odd right bytes. -fn byte_components(code: &mut Vec, left_signed: bool, right_signed: bool) { +fn byte_components(code: &mut Code, left_signed: bool, right_signed: bool) { packed(code, Host::MoveAligned, LEFT_HIGH, LEFT); packed(code, Host::MoveAligned, RIGHT_HIGH, RIGHT); for (low, high, signed) in [ @@ -70,7 +75,7 @@ fn byte_components(code: &mut Vec, left_signed: bool, right_signed: bool) { } } -fn byte_dot(code: &mut Vec, signedness: Signedness) { +fn byte_dot(code: &mut Code, signedness: Signedness) { let left_signed = matches!(signedness, Signedness::Signed | Signedness::SignedUnsigned); let right_signed = matches!(signedness, Signedness::Signed | Signedness::UnsignedSigned); byte_components(code, left_signed, right_signed); @@ -82,7 +87,7 @@ fn byte_dot(code: &mut Vec, signedness: Signedness) { /// Reconstruct each individual 32-bit product before any horizontal sum. /// The low/high four products finish in XMM0/XMM3. Unsigned halfword products /// must be zero-extended later; signed pair overflow must never be widened. -fn halfword_products(code: &mut Vec, signed: bool) { +fn halfword_products(code: &mut Code, signed: bool) { packed(code, Host::MoveAligned, LEFT_HIGH, LEFT); packed(code, Host::MultiplyLowWord, LEFT, RIGHT); packed( @@ -100,7 +105,7 @@ fn halfword_products(code: &mut Vec, signed: bool) { packed(code, Host::UnpackHighWord, RIGHT_HIGH, LEFT_HIGH); } -fn sum_halfword_pairs(code: &mut Vec, target: TargetCpu) { +fn sum_halfword_pairs(code: &mut Code, target: TargetCpu) { if target.supports(TargetCpu::Ssse3) { Host::HorizontalAddDword.register(code, LEFT, RIGHT_HIGH, target); } else { @@ -117,7 +122,7 @@ fn sum_halfword_pairs(code: &mut Vec, target: TargetCpu) { /// Four 32-bit products become one exact 64-bit sum, replicated. For complex /// subtraction the even and odd products are summed separately first; each /// signed product fits in 32 bits, but pair sums may not. -fn sum_four_wide(code: &mut Vec, source: u8, signed: bool, subtract_odd: bool) { +fn sum_four_wide(code: &mut Code, source: u8, signed: bool, subtract_odd: bool) { packed(code, Host::MoveAligned, WIDE_HIGH, source); if signed { packed(code, Host::MoveAligned, SIGNS, source); @@ -141,7 +146,7 @@ fn sum_four_wide(code: &mut Vec, source: u8, signed: bool, subtract_odd: boo ); } -fn halfword_dot(code: &mut Vec, signed: bool, wide: bool, target: TargetCpu) { +fn halfword_dot(code: &mut Code, signed: bool, wide: bool, target: TargetCpu) { if signed && !wide { // The PMADDWD overflow case is exactly the required modulo32 result. packed(code, Host::MultiplyAddWords, LEFT, RIGHT); @@ -157,7 +162,7 @@ fn halfword_dot(code: &mut Vec, signed: bool, wide: bool, target: TargetCpu) } } -fn complex_byte_dot(code: &mut Vec, select_imaginary: bool, subtract: bool) { +fn complex_byte_dot(code: &mut Code, select_imaginary: bool, subtract: bool) { byte_components(code, true, true); let (real, imaginary) = if select_imaginary { (RIGHT_HIGH, RIGHT) @@ -178,11 +183,16 @@ fn complex_byte_dot(code: &mut Vec, select_imaginary: bool, subtract: bool) ); } -fn complex_halfword_dot(code: &mut Vec, select_imaginary: bool, subtract: bool) { +fn complex_halfword_dot(code: &mut Code, select_imaginary: bool, subtract: bool) { if select_imaginary { for opcode in [Host::ShuffleLowWord, Host::ShuffleHighWord] { - packed(code, opcode, RIGHT, RIGHT); - code.push(SWAP_ADJACENT_DWORDS); + code.asm().simd_imm( + opcode, + RIGHT, + Rm::Xmm(RIGHT), + SWAP_ADJACENT_DWORDS, + TargetCpu::Baseline, + ); } } halfword_products(code, true); @@ -194,7 +204,7 @@ fn complex_halfword_dot(code: &mut Vec, select_imaginary: bool, subtract: bo /// Emit the integer dot forms only. Any other operand returns false before /// appending bytes. pub(crate) fn emit_integer( - code: &mut Vec, + code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu, @@ -285,7 +295,6 @@ pub(crate) fn emit_integer( mod tests { use super::*; use alloc::vec; - use alloc::vec::Vec; #[test] fn floating_and_unallocated_operands_decline_without_partial_output() { @@ -319,7 +328,7 @@ mod tests { ..base }, ] { - let mut code = vec![0xcc]; + let mut code = Code::from(vec![0xcc]); assert!(!emit_integer( &mut code, &operand, @@ -332,14 +341,14 @@ mod tests { #[test] fn horizontal_unsigned_pair_recipe_requires_ssse3() { - let mut baseline = Vec::new(); + let mut baseline = Code::new(); sum_halfword_pairs(&mut baseline, TargetCpu::Baseline); assert!( !baseline .windows(Host::HorizontalAddDword.encoding().len()) .any(|bytes| bytes == Host::HorizontalAddDword.encoding()) ); - let mut checked = Vec::new(); + let mut checked = Code::new(); sum_halfword_pairs(&mut checked, TargetCpu::Ssse3); assert!(checked.starts_with(Host::HorizontalAddDword.encoding())); assert!(checked.len() < baseline.len()); diff --git a/crates/stela-compiler/src/x86_64/sve/floating.rs b/crates/stela-compiler/src/x86_64/sve/floating.rs index 05061155ea..a9ef51a930 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating.rs @@ -1,11 +1,10 @@ //! SVE floating-point emission: native paths for ordinary values, software //! completion for the rest. +use crate::x86_64::asm::Code; -use alloc::vec::Vec; mod add_reductions; mod arithmetic; mod arithmetic_dispatch; -mod arithmetic_remaining; mod bfloat16; mod classify; mod comparison; @@ -36,7 +35,7 @@ use crate::{ /// Try the admitted instruction's native mapping. A declined shape leaves its /// architectural effects to the shared exact numerical completion boundary. pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, word: u32, operation: Operation, length: VectorLength, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/add_reductions.rs b/crates/stela-compiler/src/x86_64/sve/floating/add_reductions.rs index 72dfa72339..fa54bc7089 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/add_reductions.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/add_reductions.rs @@ -1,5 +1,7 @@ //! FADDP, FADDV and FADDQV. NaNs, subnormals and any host status other than //! inexact take the software path for the whole instruction. +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, @@ -36,16 +38,9 @@ const FIRST_SUBTREE: u8 = 6; const ACCUMULATOR: u8 = 7; const REGISTER_ONLY_DEPTH: usize = 2; const OUTPUT_SLOT: usize = 0; -const MODRM_REGISTER: u8 = 0xc0; -const TEST_EAX_LOW_PREDICATE: &[u8] = &[0xa8, 1]; -const JUMP_REL32: u8 = 0xe9; const MXCSR_INEXACT: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; const MXCSR_TO_FPSR_INEXACT_SHIFT: u8 = 1; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; fn element(format: Format) -> ElementSize { match format { @@ -55,7 +50,7 @@ fn element(format: Format) -> ElementSize { } } -fn low_lane(code: &mut Vec, format: Format, lane: usize, register: u8) { +fn low_lane(code: &mut Code, format: Format, lane: usize, register: u8) { let bytes = format.bits() as usize / BITS_PER_BYTE; if lane != 0 { ShiftOpcode::RightBytes.emit(code, register, (lane * bytes) as u8); @@ -66,7 +61,7 @@ fn low_lane(code: &mut Vec, format: Format, lane: usize, register: u8) { } fn guard( - code: &mut Vec, + code: &mut Code, classification: Classification, failures: &mut Vec, target: TargetCpu, @@ -97,7 +92,7 @@ impl Tree { // inactive. fn emit( &self, - code: &mut Vec, + code: &mut Code, start: usize, count: usize, depth: usize, @@ -147,22 +142,21 @@ impl Tree { } } -fn status(code: &mut Vec, frame: &numerical::Frame, failures: &mut Vec) { +fn status(code: &mut Code, frame: &numerical::Frame, failures: &mut Vec) { numerical::capture_status(code, frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_OTHER_STATUS as i32); failures.push(branch(code, Condition::NotZero)); - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_INEXACT.to_le_bytes()); - code.extend(SHR_EAX_IMMEDIATE); - code.push(MXCSR_TO_FPSR_INEXACT_SHIFT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_INEXACT as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, MXCSR_TO_FPSR_INEXACT_SHIFT); numerical::add_fpsr(code, frame); } #[allow(clippy::too_many_arguments)] fn pairwise( - code: &mut Vec, + code: &mut Code, operand: Operand, left: u8, right: u8, @@ -193,9 +187,9 @@ fn pairwise( if lane != 0 { ShiftOpcode::RightBytes.emit(code, FIRST_SUBTREE, (lane * lane_bytes) as u8); } - Host::ByteSignMask.append(code, target); - code.push(MODRM_REGISTER | FIRST_SUBTREE); // EAX receives the mask. - code.extend(TEST_EAX_LOW_PREDICATE); + code.asm() + .simd_to_gpr(Host::ByteSignMask, Rax, FIRST_SUBTREE, target); + code.asm().test_accumulator_imm(Size::Byte, 1); let inactive = branch(code, Condition::Zero); guard_active_exception_enables(code, FIRST_SUBTREE, features, failures, target); let source = if lane % 2 == 0 { left } else { right }; @@ -219,9 +213,7 @@ fn pairwise( RIGHT, ); guard(code, classification, failures, target); - code.push(JUMP_REL32); - let selected = code.len(); - code.extend(0_i32.to_le_bytes()); + let selected = code.asm().jmp().offset(); let inactive_start = code.len(); resolve(code, inactive, inactive_start); load_z_chunk(code, operand.destination, chunk, VALUE, length, target); @@ -240,7 +232,7 @@ fn pairwise( /// Unsupported lengths or formats return false before emitting, leaving the /// instruction to software completion. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/arithmetic.rs b/crates/stela-compiler/src/x86_64/sve/floating/arithmetic.rs index 954c399d6c..d4ee58f8ca 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/arithmetic.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/arithmetic.rs @@ -1,5 +1,11 @@ -//! SVE single/double binary arithmetic on normal values, staged per instruction. -//! Half precision and exceptional values use software completion. +//! SVE single/double binary arithmetic on normal values, staged per +//! instruction: the core vector forms ([`emit_core`]) and the immediate, +//! indexed and reverse forms with FABD and FMULX ([`emit_operand_forms`]). +//! Half precision and exceptional values use software completion. With DAZ +//! clear, a normal output with only inexact status implies no denormal +//! operand. +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, @@ -13,7 +19,7 @@ use crate::{ isa::SimdOpcode as Host, scalable::{ load_z_chunk, - numerical::{self, Environment, Output}, + numerical::{self, Environment, Frame, Output}, read_predicate_mask, }, simd::numerical::{ @@ -32,60 +38,155 @@ const CONSTANT_SCRATCH: u8 = 3; const ACTIVE: u8 = 6; const OLD_DESTINATION: u8 = 7; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; const REPEAT_LOW_DWORD: u8 = 0; +const REPEAT_SELECTED_DWORD: u8 = 0x55; +const SINGLE_LANES_PER_CHUNK: u8 = 4; +const DOUBLE_LANES_PER_CHUNK: u8 = 2; +const SINGLE_SIGN_SHIFT: u8 = 31; +const DOUBLE_SIGN_SHIFT: u8 = 63; const BENIGN_LEFT_EXPONENT_INCREMENT: u32 = 1; const MXCSR_INEXACT: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; const MXCSR_TO_FPSR_INEXACT_SHIFT: u8 = 1; -const REL32_BYTES: usize = size_of::(); -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -fn reject(code: &mut Vec, failures: &mut Vec) { - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend([0; REL32_BYTES]); +fn reject(code: &mut Code, failures: &mut Vec) { + failures.push(code.asm().jcc(Cond::Ne).offset()); +} + +/// Broadcast `bits` to every lane of `destination`. +fn broadcast_bits(code: &mut Code, format: Format, bits: u64, destination: u8, target: TargetCpu) { + match format { + Format::Single => { + code.asm().mov_imm32(Rax, bits as u32); + } + Format::Double => { + code.asm().mov_imm64(Rax, bits); + } + Format::Half => unreachable!("Half remains whole-instruction completion"), + } + code.asm() + .simd(Host::MoveGprQword, destination, Rax, target); + if format == Format::Single { + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(destination), + REPEAT_LOW_DWORD, + target, + ); + } else { + Host::UnpackLowQword.register(code, destination, destination, target); + } } /// Replace inactive lanes with exact benign normals before any host arithmetic. /// Left=2 and right=1 make every admitted operation exact in inactive lanes. -fn benign_inactive(code: &mut Vec, format: Format, input: u8, target: TargetCpu) { +fn benign_inactive(code: &mut Code, format: Format, input: u8, target: TargetCpu) { let increment = if input == LEFT { BENIGN_LEFT_EXPONENT_INCREMENT } else { 0 }; let bits = u64::from(format.exponent_bias() + increment) << format.fraction_bits(); - if format == Format::Single { - code.push(MOV_EAX_IMMEDIATE); - code.extend((bits as u32).to_le_bytes()); - } else { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(bits.to_le_bytes()); - } - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (CONSTANT_SCRATCH << MODRM_REGISTER_SHIFT) | GPR_RAX); - if format == Format::Single { - Host::ShuffleDword.register(code, CONSTANT_SCRATCH, CONSTANT_SCRATCH, target); - code.push(REPEAT_LOW_DWORD); - } else { - Host::UnpackLowQword.register(code, CONSTANT_SCRATCH, CONSTANT_SCRATCH, target); - } + broadcast_bits(code, format, bits, CONSTANT_SCRATCH, target); Host::MoveAligned.register(code, MASK_SCRATCH, ACTIVE, target); Host::AndNot.register(code, MASK_SCRATCH, CONSTANT_SCRATCH, target); Host::And.register(code, input, ACTIVE, target); Host::Or.register(code, input, MASK_SCRATCH, target); } -fn inputs(operand: Operand) -> Option<(BinaryOperation, u8, u8)> { +fn arithmetic_opcode(operation: BinaryOperation) -> ArithmeticOpcode { + match operation { + BinaryOperation::Add => ArithmeticOpcode::Add, + BinaryOperation::Subtract | BinaryOperation::AbsoluteDifference => { + ArithmeticOpcode::Subtract + } + BinaryOperation::Multiply | BinaryOperation::MultiplyExtended => ArithmeticOpcode::Multiply, + BinaryOperation::Divide => ArithmeticOpcode::Divide, + _ => unreachable!("the input selectors validated the binary operation"), + } +} + +/// The lanes element-sized for `format`, or `None` for Half. +fn element(format: Format) -> Option { + match format { + Format::Single => Some(ElementSize::Word), + Format::Double => Some(ElementSize::Doubleword), + Format::Half => None, + } +} + +/// Load the active-lane mask for `chunk` into ACTIVE: the governing +/// predicate's lanes, or all lanes when unpredicated under full A64 rules. +fn active_lanes( + code: &mut Code, + operand: Operand, + element: ElementSize, + chunk: usize, + length: VectorLength, + features: NumericalFeatures, + target: TargetCpu, +) { + if let Some(predicate) = operand.predicate { + read_predicate_mask( + code, + predicate, + chunk, + element, + ACTIVE, + MASK_SCRATCH, + length, + target, + ); + } else if features.full_a64() { + Host::EqualDword.register(code, ACTIVE, ACTIVE, target); + } +} + +/// Merge LEFT into the old destination's inactive lanes when predicated. +fn merge_inactive( + code: &mut Code, + operand: Operand, + chunk: usize, + length: VectorLength, + target: TargetCpu, +) { + if operand.predicate.is_some() { + load_z_chunk( + code, + operand.destination, + chunk, + OLD_DESTINATION, + length, + target, + ); + Host::And.register(code, LEFT, ACTIVE, target); + Host::AndNot.register(code, ACTIVE, OLD_DESTINATION, target); + Host::Or.register(code, LEFT, ACTIVE, target); + } +} + +/// Reject any status other than inexact, add inexact to FPSR and commit. +fn finish_status( + code: &mut Code, + frame: &Frame, + failures: &mut Vec, + pc: GuestAddress, + target: TargetCpu, +) { + numerical::capture_status(code, frame); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_OTHER_STATUS as i32); + reject(code, failures); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_INEXACT as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, MXCSR_TO_FPSR_INEXACT_SHIFT); + numerical::add_fpsr(code, frame); + numerical::finish(code, frame, failures, pc, target); +} + +fn core_inputs(operand: Operand) -> Option<(BinaryOperation, u8, u8)> { let Inputs::Binary { left: Source::Vector(left), right: Source::Vector(right), @@ -96,8 +197,8 @@ fn inputs(operand: Operand) -> Option<(BinaryOperation, u8, u8)> { if operand.shape != ResultShape::Vector { return None; } - // The first batch owns forward destructive forms and unpredicated ADD/SUB/MUL. - // Reverse forms retain the same exact fallback until their own admission. + // The core forms are the forward destructive forms and unpredicated + // ADD/SUB/MUL; reverse forms go to [`emit_operand_forms`]. if operand.predicate.is_some() && left != operand.destination { return None; } @@ -115,34 +216,22 @@ fn inputs(operand: Operand) -> Option<(BinaryOperation, u8, u8)> { Some((operation, left, right)) } -fn arithmetic_opcode(operation: BinaryOperation) -> ArithmeticOpcode { - match operation { - BinaryOperation::Add => ArithmeticOpcode::Add, - BinaryOperation::Subtract => ArithmeticOpcode::Subtract, - BinaryOperation::Multiply => ArithmeticOpcode::Multiply, - BinaryOperation::Divide => ArithmeticOpcode::Divide, - _ => unreachable!("validated core binary operation"), - } -} - /// Emit seven core vector-register forms within a conservative normal domain. /// Unsupported shapes/formats leave `code` untouched. The caller owns immutable /// feature admission and streaming entry checks. RDI/R15, guest NZCV and every /// source survive; RAX/RCX/RDX, flags and XMM0..7 are caller-volatile. -pub(crate) fn emit( - code: &mut Vec, +pub(crate) fn emit_core( + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, pc: GuestAddress, target: TargetCpu, ) -> Result { - let element = match operand.format { - Format::Single => ElementSize::Word, - Format::Double => ElementSize::Doubleword, - Format::Half => return Ok(false), + let Some(element) = element(operand.format) else { + return Ok(false); }; - let Some((operation, left, right)) = inputs(operand) else { + let Some((operation, left, right)) = core_inputs(operand) else { return Ok(false); }; let frame = numerical::begin( @@ -155,20 +244,7 @@ pub(crate) fn emit( numerical::install_mxcsr(code, &frame); let mut failures = Vec::new(); for chunk in 0..length.chunks() { - if let Some(predicate) = operand.predicate { - read_predicate_mask( - code, - predicate, - chunk, - element, - ACTIVE, - MASK_SCRATCH, - length, - target, - ); - } else if features.full_a64() { - Host::EqualDword.register(code, ACTIVE, ACTIVE, target); - } + active_lanes(code, operand, element, chunk, length, features, target); guard_active_exception_enables(code, ACTIVE, features, &mut failures, target); load_z_chunk(code, left, chunk, LEFT, length, target); load_z_chunk(code, right, chunk, RIGHT, length, target); @@ -192,31 +268,165 @@ pub(crate) fn emit( prepare_vector_result_range(code); vector_exponent_range(code, operand.format, Shape::Vector128, LEFT); reject(code, &mut failures); - if operand.predicate.is_some() { - load_z_chunk( - code, - operand.destination, - chunk, - OLD_DESTINATION, - length, - target, - ); - Host::And.register(code, LEFT, ACTIVE, target); - Host::AndNot.register(code, ACTIVE, OLD_DESTINATION, target); - Host::Or.register(code, LEFT, ACTIVE, target); - } + merge_inactive(code, operand, chunk, length, target); numerical::stage_vector_chunk(code, &frame, OUTPUT_SLOT, chunk, LEFT, target); } - numerical::capture_status(code, &frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); - reject(code, &mut failures); - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_INEXACT.to_le_bytes()); - code.extend(SHR_EAX_IMMEDIATE); - code.push(MXCSR_TO_FPSR_INEXACT_SHIFT); - numerical::add_fpsr(code, &frame); - numerical::finish(code, &frame, &failures, pc, target); + finish_status(code, &frame, &mut failures, pc, target); + Ok(true) +} + +/// Decoded sources already encode reversed operand order. With both source +/// registers aliased, forward and reverse forms decode identically. +fn operand_form_inputs(operand: Operand) -> Option<(BinaryOperation, Source, Source)> { + let Inputs::Binary { left, right } = operand.inputs else { + return None; + }; + if operand.shape != ResultShape::Vector { + return None; + } + let Kind::Binary(operation) = operand.kind else { + return None; + }; + let owned = match (operation, left, right, operand.predicate) { + ( + BinaryOperation::AbsoluteDifference | BinaryOperation::MultiplyExtended, + Source::Vector(left), + Source::Vector(_), + Some(_), + ) => left == operand.destination, + ( + BinaryOperation::Add | BinaryOperation::Subtract | BinaryOperation::Multiply, + Source::Vector(left), + Source::ImmediateBits(_), + Some(_), + ) => left == operand.destination, + (BinaryOperation::Subtract, Source::ImmediateBits(_), Source::Vector(right), Some(_)) => { + right == operand.destination + } + ( + BinaryOperation::Subtract | BinaryOperation::Divide, + Source::Vector(_), + Source::Vector(right), + Some(_), + ) => right == operand.destination, + (BinaryOperation::Multiply, Source::Vector(_), Source::Indexed { .. }, None) => true, + _ => false, + }; + owned.then_some((operation, left, right)) +} + +/// Indexed inputs select one lane separately in each guest 128-bit segment. +/// No source is loaded from a previously staged destination chunk. +fn load_source( + code: &mut Code, + source: Source, + format: Format, + chunk: usize, + destination: u8, + length: VectorLength, + target: TargetCpu, +) { + match source { + Source::Vector(register) => { + load_z_chunk(code, register, chunk, destination, length, target) + } + Source::ImmediateBits(bits) => broadcast_bits(code, format, bits, destination, target), + Source::Indexed { register, index } => { + load_z_chunk(code, register, chunk, destination, length, target); + if format == Format::Single { + debug_assert!(index < SINGLE_LANES_PER_CHUNK); + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(destination), + index * REPEAT_SELECTED_DWORD, + target, + ); + } else { + debug_assert!(format == Format::Double && index < DOUBLE_LANES_PER_CHUNK); + let opcode = if index == 0 { + Host::UnpackLowQword + } else { + Host::UnpackHighQword + }; + opcode.register(code, destination, destination, target); + } + } + } +} + +/// FPAbs transforms the rounded subtraction result. Active NaNs fail the result +/// exponent guard before this finite-only sign clear, preserving AH NaN policy. +fn absolute_result(code: &mut Code, format: Format, target: TargetCpu) { + let sign_shift = if format == Format::Single { + SINGLE_SIGN_SHIFT + } else { + DOUBLE_SIGN_SHIFT + }; + let magnitude = if format == Format::Single { + u64::from(u32::MAX) + } else { + u64::MAX + } >> 1; + debug_assert_eq!(magnitude, (1_u64 << sign_shift) - 1); + broadcast_bits(code, format, magnitude, MASK_SCRATCH, target); + Host::And.register(code, LEFT, MASK_SCRATCH, target); +} + +/// Emit immediate/indexed/reverse arithmetic and finite FABD/FMULX mappings. +/// Unsupported shapes/formats leave `code` untouched. The caller owns immutable +/// feature admission and streaming entry checks. RDI/R15, guest NZCV and every +/// source survive; RAX/RCX/RDX, flags and XMM0..7 are caller-volatile. +pub(in crate::x86_64) fn emit_operand_forms( + code: &mut Code, + operand: Operand, + length: VectorLength, + features: NumericalFeatures, + pc: GuestAddress, + target: TargetCpu, +) -> Result { + let Some(element) = element(operand.format) else { + return Ok(false); + }; + let Some((operation, left, right)) = operand_form_inputs(operand) else { + return Ok(false); + }; + let frame = numerical::begin( + code, + length, + &[Output::Z(operand.destination)], + Environment::PrivateMxcsr, + )?; + rounding_control(code); + numerical::install_mxcsr(code, &frame); + prepare_vector_input_range(code, operand.format); + prepare_vector_result_range(code); + let mut failures = Vec::new(); + for chunk in 0..length.chunks() { + active_lanes(code, operand, element, chunk, length, features, target); + guard_active_exception_enables(code, ACTIVE, features, &mut failures, target); + load_source(code, left, operand.format, chunk, LEFT, length, target); + load_source(code, right, operand.format, chunk, RIGHT, length, target); + if operand.predicate.is_some() { + benign_inactive(code, operand.format, LEFT, target); + benign_inactive(code, operand.format, RIGHT, target); + } + emit_opcode_to( + code, + operand.format, + Shape::Vector128, + arithmetic_opcode(operation), + LEFT, + RIGHT, + ); + vector_exponent_range(code, operand.format, Shape::Vector128, LEFT); + reject(code, &mut failures); + if operation == BinaryOperation::AbsoluteDifference { + absolute_result(code, operand.format, target); + } + merge_inactive(code, operand, chunk, length, target); + numerical::stage_vector_chunk(code, &frame, OUTPUT_SLOT, chunk, LEFT, target); + } + finish_status(code, &frame, &mut failures, pc, target); Ok(true) } diff --git a/crates/stela-compiler/src/x86_64/sve/floating/arithmetic_dispatch.rs b/crates/stela-compiler/src/x86_64/sve/floating/arithmetic_dispatch.rs index 754671775c..f0103e59aa 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/arithmetic_dispatch.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/arithmetic_dispatch.rs @@ -1,4 +1,6 @@ //! Selection between native and software arithmetic paths. +use crate::aarch64::Unsupported; +use crate::x86_64::asm::Code; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -8,11 +10,10 @@ use crate::{ sve::floating::arithmetic::{self as guest, Inputs, Kind, Operand, ResultShape}, }, }; -use alloc::vec::Vec; use super::{ - add_reductions, arithmetic_remaining, complex, estimate_exponent, floating_estimates, fused, - minmax, pairwise_clamp, reduction_minmax as minmax_reductions, refinement, scale, square_root, + add_reductions, arithmetic, complex, estimate_exponent, floating_estimates, fused, minmax, + pairwise_clamp, reduction_minmax as minmax_reductions, refinement, scale, square_root, unsigned_estimates, }; @@ -20,7 +21,7 @@ use super::{ /// encoding class comes from the shared metadata, so reversed forms with /// aliased registers cannot reach the forward-only emitter. pub(super) fn emit( - code: &mut Vec, + code: &mut Code, word: u32, operand: Operand, length: VectorLength, @@ -29,9 +30,10 @@ pub(super) fn emit( target: TargetCpu, ) -> Result { if let Some(core) = guest::decode_core_binary(word) { - let core = core.map_err(|()| CompileError("reserved core binary allocation".into()))?; + let core = + core.map_err(|Unsupported| CompileError("reserved core binary allocation".into()))?; assert_eq!(core, operand, "admitted source/operand identity changed"); - return super::arithmetic::emit(code, core, length, features, pc, target); + return arithmetic::emit_core(code, core, length, features, pc, target); } let before = code.len(); if super::indexed_half::emit(code, operand, length, features, pc, target)? { @@ -44,7 +46,7 @@ pub(super) fn emit( ); match (operand.kind, operand.inputs, operand.shape) { (Kind::Binary(_), Inputs::Binary { .. }, ResultShape::Vector) => { - arithmetic_remaining::emit(code, operand, length, features, pc, target) + arithmetic::emit_operand_forms(code, operand, length, features, pc, target) } (Kind::Fused(_), Inputs::Fused { .. }, ResultShape::Vector) => { fused::emit(code, operand, length, features, pc, target) diff --git a/crates/stela-compiler/src/x86_64/sve/floating/arithmetic_remaining.rs b/crates/stela-compiler/src/x86_64/sve/floating/arithmetic_remaining.rs deleted file mode 100644 index 121b0517f8..0000000000 --- a/crates/stela-compiler/src/x86_64/sve/floating/arithmetic_remaining.rs +++ /dev/null @@ -1,320 +0,0 @@ -//! The remaining SVE binary arithmetic forms on the staged arithmetic kernel. -//! With DAZ clear, a normal output with only inexact status implies no denormal -//! operand. - -use crate::{ - CompileError, GuestAddress, TargetCpu, - aarch64::{ - floating::{BinaryOperation, Format, features::NumericalFeatures}, - scalable::{ElementSize, VectorLength}, - simd::arithmetic::Shape, - sve::floating::arithmetic::{Inputs, Kind, Operand, ResultShape, Source}, - }, - x86_64::{ - isa::SimdOpcode as Host, - scalable::{ - load_z_chunk, - numerical::{self, Environment, Output}, - read_predicate_mask, - }, - simd::numerical::{ - ArithmeticOpcode, emit_opcode_to, prepare_vector_input_range, - prepare_vector_result_range, rounding_control, vector_exponent_range, - }, - sve::floating::classify::guard_active_exception_enables, - }, -}; -use alloc::vec::Vec; - -const LEFT: u8 = 0; -const RIGHT: u8 = 1; -const MASK_SCRATCH: u8 = 2; -const CONSTANT_SCRATCH: u8 = 3; -const ACTIVE: u8 = 6; -const OLD_DESTINATION: u8 = 7; -const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const REPEAT_LOW_DWORD: u8 = 0; -const REPEAT_SELECTED_DWORD: u8 = 0x55; -const SINGLE_LANES_PER_CHUNK: u8 = 4; -const DOUBLE_LANES_PER_CHUNK: u8 = 2; -const SINGLE_SIGN_SHIFT: u8 = 31; -const DOUBLE_SIGN_SHIFT: u8 = 63; -const BENIGN_LEFT_EXPONENT_INCREMENT: u32 = 1; -const MXCSR_INEXACT: u32 = 1 << 5; -const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; -const MXCSR_TO_FPSR_INEXACT_SHIFT: u8 = 1; -const REL32_BYTES: usize = size_of::(); -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; - -fn reject(code: &mut Vec, failures: &mut Vec) { - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend([0; REL32_BYTES]); -} - -/// Replace inactive lanes with exact benign normals before any host arithmetic. -/// Left=2 and right=1 make every admitted operation exact in inactive lanes. -fn benign_inactive(code: &mut Vec, format: Format, input: u8, target: TargetCpu) { - let increment = if input == LEFT { - BENIGN_LEFT_EXPONENT_INCREMENT - } else { - 0 - }; - let bits = u64::from(format.exponent_bias() + increment) << format.fraction_bits(); - if format == Format::Single { - code.push(MOV_EAX_IMMEDIATE); - code.extend((bits as u32).to_le_bytes()); - } else { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(bits.to_le_bytes()); - } - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (CONSTANT_SCRATCH << MODRM_REGISTER_SHIFT) | GPR_RAX); - if format == Format::Single { - Host::ShuffleDword.register(code, CONSTANT_SCRATCH, CONSTANT_SCRATCH, target); - code.push(REPEAT_LOW_DWORD); - } else { - Host::UnpackLowQword.register(code, CONSTANT_SCRATCH, CONSTANT_SCRATCH, target); - } - Host::MoveAligned.register(code, MASK_SCRATCH, ACTIVE, target); - Host::AndNot.register(code, MASK_SCRATCH, CONSTANT_SCRATCH, target); - Host::And.register(code, input, ACTIVE, target); - Host::Or.register(code, input, MASK_SCRATCH, target); -} - -/// Decoded sources already encode reversed operand order. With both source -/// registers aliased, forward and reverse forms decode identically. -fn inputs(operand: Operand) -> Option<(BinaryOperation, Source, Source)> { - let Inputs::Binary { left, right } = operand.inputs else { - return None; - }; - if operand.shape != ResultShape::Vector { - return None; - } - let Kind::Binary(operation) = operand.kind else { - return None; - }; - let owned = match (operation, left, right, operand.predicate) { - ( - BinaryOperation::AbsoluteDifference | BinaryOperation::MultiplyExtended, - Source::Vector(left), - Source::Vector(_), - Some(_), - ) => left == operand.destination, - ( - BinaryOperation::Add | BinaryOperation::Subtract | BinaryOperation::Multiply, - Source::Vector(left), - Source::ImmediateBits(_), - Some(_), - ) => left == operand.destination, - (BinaryOperation::Subtract, Source::ImmediateBits(_), Source::Vector(right), Some(_)) => { - right == operand.destination - } - ( - BinaryOperation::Subtract | BinaryOperation::Divide, - Source::Vector(_), - Source::Vector(right), - Some(_), - ) => right == operand.destination, - (BinaryOperation::Multiply, Source::Vector(_), Source::Indexed { .. }, None) => true, - _ => false, - }; - owned.then_some((operation, left, right)) -} - -fn broadcast_bits( - code: &mut Vec, - format: Format, - bits: u64, - destination: u8, - target: TargetCpu, -) { - match format { - Format::Single => { - code.push(MOV_EAX_IMMEDIATE); - code.extend((bits as u32).to_le_bytes()); - } - Format::Double => { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(bits.to_le_bytes()); - } - Format::Half => unreachable!("Half remains whole-instruction completion"), - } - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (destination << MODRM_REGISTER_SHIFT) | GPR_RAX); - if format == Format::Single { - Host::ShuffleDword.register(code, destination, destination, target); - code.push(REPEAT_LOW_DWORD); - } else { - Host::UnpackLowQword.register(code, destination, destination, target); - } -} - -/// Indexed inputs select one lane separately in each guest 128-bit segment. -/// No source is loaded from a previously staged destination chunk. -fn load_source( - code: &mut Vec, - source: Source, - format: Format, - chunk: usize, - destination: u8, - length: VectorLength, - target: TargetCpu, -) { - match source { - Source::Vector(register) => { - load_z_chunk(code, register, chunk, destination, length, target) - } - Source::ImmediateBits(bits) => broadcast_bits(code, format, bits, destination, target), - Source::Indexed { register, index } => { - load_z_chunk(code, register, chunk, destination, length, target); - if format == Format::Single { - debug_assert!(index < SINGLE_LANES_PER_CHUNK); - Host::ShuffleDword.register(code, destination, destination, target); - code.push(index * REPEAT_SELECTED_DWORD); - } else { - debug_assert!(format == Format::Double && index < DOUBLE_LANES_PER_CHUNK); - let opcode = if index == 0 { - Host::UnpackLowQword - } else { - Host::UnpackHighQword - }; - opcode.register(code, destination, destination, target); - } - } - } -} - -/// FPAbs transforms the rounded subtraction result. Active NaNs fail the result -/// exponent guard before this finite-only sign clear, preserving AH NaN policy. -fn absolute_result(code: &mut Vec, format: Format, target: TargetCpu) { - let sign_shift = if format == Format::Single { - SINGLE_SIGN_SHIFT - } else { - DOUBLE_SIGN_SHIFT - }; - let magnitude = if format == Format::Single { - u64::from(u32::MAX) - } else { - u64::MAX - } >> 1; - debug_assert_eq!(magnitude, (1_u64 << sign_shift) - 1); - broadcast_bits(code, format, magnitude, MASK_SCRATCH, target); - Host::And.register(code, LEFT, MASK_SCRATCH, target); -} - -fn arithmetic_opcode(operation: BinaryOperation) -> ArithmeticOpcode { - match operation { - BinaryOperation::Add => ArithmeticOpcode::Add, - BinaryOperation::Subtract | BinaryOperation::AbsoluteDifference => { - ArithmeticOpcode::Subtract - } - BinaryOperation::Multiply | BinaryOperation::MultiplyExtended => ArithmeticOpcode::Multiply, - BinaryOperation::Divide => ArithmeticOpcode::Divide, - _ => unreachable!("private source selector validated the binary operation"), - } -} - -/// Emit immediate/indexed/reverse arithmetic and finite FABD/FMULX mappings. -/// Unsupported shapes/formats leave `code` untouched. The caller owns immutable -/// feature admission and streaming entry checks. RDI/R15, guest NZCV and every -/// source survive; RAX/RCX/RDX, flags and XMM0..7 are caller-volatile. -pub(in crate::x86_64) fn emit( - code: &mut Vec, - operand: Operand, - length: VectorLength, - features: NumericalFeatures, - pc: GuestAddress, - target: TargetCpu, -) -> Result { - let element = match operand.format { - Format::Single => ElementSize::Word, - Format::Double => ElementSize::Doubleword, - Format::Half => return Ok(false), - }; - let Some((operation, left, right)) = inputs(operand) else { - return Ok(false); - }; - let frame = numerical::begin( - code, - length, - &[Output::Z(operand.destination)], - Environment::PrivateMxcsr, - )?; - rounding_control(code); - numerical::install_mxcsr(code, &frame); - prepare_vector_input_range(code, operand.format); - prepare_vector_result_range(code); - let mut failures = Vec::new(); - for chunk in 0..length.chunks() { - if let Some(predicate) = operand.predicate { - read_predicate_mask( - code, - predicate, - chunk, - element, - ACTIVE, - MASK_SCRATCH, - length, - target, - ); - } else if features.full_a64() { - Host::EqualDword.register(code, ACTIVE, ACTIVE, target); - } - guard_active_exception_enables(code, ACTIVE, features, &mut failures, target); - load_source(code, left, operand.format, chunk, LEFT, length, target); - load_source(code, right, operand.format, chunk, RIGHT, length, target); - if operand.predicate.is_some() { - benign_inactive(code, operand.format, LEFT, target); - benign_inactive(code, operand.format, RIGHT, target); - } - emit_opcode_to( - code, - operand.format, - Shape::Vector128, - arithmetic_opcode(operation), - LEFT, - RIGHT, - ); - vector_exponent_range(code, operand.format, Shape::Vector128, LEFT); - reject(code, &mut failures); - if operation == BinaryOperation::AbsoluteDifference { - absolute_result(code, operand.format, target); - } - if operand.predicate.is_some() { - load_z_chunk( - code, - operand.destination, - chunk, - OLD_DESTINATION, - length, - target, - ); - Host::And.register(code, LEFT, ACTIVE, target); - Host::AndNot.register(code, ACTIVE, OLD_DESTINATION, target); - Host::Or.register(code, LEFT, ACTIVE, target); - } - numerical::stage_vector_chunk(code, &frame, OUTPUT_SLOT, chunk, LEFT, target); - } - numerical::capture_status(code, &frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); - reject(code, &mut failures); - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_INEXACT.to_le_bytes()); - code.extend(SHR_EAX_IMMEDIATE); - code.push(MXCSR_TO_FPSR_INEXACT_SHIFT); - numerical::add_fpsr(code, &frame); - numerical::finish(code, &frame, &failures, pc, target); - Ok(true) -} diff --git a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16.rs b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16.rs index 298cd4726f..c468fcd6a4 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16.rs @@ -1,5 +1,5 @@ //! SVE BF16 arithmetic and single-precision accumulation. -use alloc::vec::Vec; +use crate::x86_64::asm::Code; mod accumulation; mod arithmetic; @@ -13,7 +13,7 @@ use crate::{ }; pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation.rs b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation.rs index 0aa6c76f3b..eb2c4f5e1e 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation.rs @@ -1,4 +1,6 @@ //! BFDOT (classic and FEAT_EBF16) and BFMLAL/BFMLSL. +use crate::x86_64::asm::Gpr::Rdi; +use crate::x86_64::asm::{Code, Mem, Rm, Size}; use alloc::vec::Vec; mod classic_dot; mod enhanced_dot; @@ -29,25 +31,29 @@ const RIGHT: u8 = 1; const ADDEND: u8 = 6; const OUTPUT_SLOT: usize = 0; const REPEAT_DWORD: u8 = 0x55; -const TEST_STATE_IMMEDIATE: &[u8] = &[0xf7, 0x87]; -const JMP_REL32: u8 = 0xe9; -const REL32_BYTES: usize = size_of::(); -fn test_control(code: &mut Vec, mask: u32) { - code.extend(TEST_STATE_IMMEDIATE); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(mask.to_le_bytes()); +fn test_control(code: &mut Code, mask: u32) { + code.asm().test_imm( + Size::Dword, + Mem::base_disp32(Rdi, (core::mem::offset_of!(GuestState, fpcr)) as i32), + mask as i32, + ); } -fn shuffle(code: &mut Vec, register: u8, order: u8, target: TargetCpu) { - Host::ShuffleDword.register(code, register, register, target); - code.push(order); +fn shuffle(code: &mut Code, register: u8, order: u8, target: TargetCpu) { + code.asm().simd_imm( + Host::ShuffleDword, + register, + Rm::Xmm(register), + order, + target, + ); } /// Returns false before emitting for the BF16 arithmetic forms, which are /// emitted elsewhere. Outputs stay private until every guard passes. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -104,9 +110,7 @@ pub(in crate::x86_64) fn emit( numerical::stage_vector_chunk(code, &frame, OUTPUT_SLOT, chunk, LEFT, target); } if let Some(enhanced) = enhanced { - code.push(JMP_REL32); - let classic_done = code.len(); - code.extend([0; REL32_BYTES]); + let classic_done = code.asm().jmp().offset(); let enhanced_start = code.len(); resolve(code, enhanced, enhanced_start); // Enhanced BFDOT uses guest RC under both AH values; status/traps are diff --git a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/classic_dot.rs b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/classic_dot.rs index 2771d9eb94..9474f72659 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/classic_dot.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/classic_dot.rs @@ -1,5 +1,9 @@ //! Classic BFDOT with round-to-odd intermediates. use super::{LEFT, RIGHT}; +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Rm, Size}; +use crate::x86_64::simd::numerical::single_vector_arithmetic; use crate::{ TargetCpu, aarch64::{ @@ -10,8 +14,7 @@ use crate::{ isa::{ShiftOpcode, SimdOpcode as Host}, scalable::numerical::{self, Frame}, simd::numerical::{ - ArithmeticOpcode, Condition, branch, emit_opcode_to, prepare_vector_input_range, - vector_exponent_range, + ArithmeticOpcode, Condition, branch, prepare_vector_input_range, vector_exponent_range, }, }, }; @@ -27,83 +30,61 @@ const ORIGINAL_LEFT: u8 = 7; const BFLOAT_BITS: u8 = BFLOAT16_BITS as u8; const SIGN_BITS: u8 = 1; const SINGLE_TOP_BIT: u8 = Format::Single.bits() as u8 - SIGN_BITS; -const GPR_RAX: u8 = 0; const ALL_SINGLE_LANES: u8 = 15; const MXCSR_INEXACT: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; const MXCSR_ROUND_ZERO: u32 = 3 << 13; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const CMP_EAX_IMMEDIATE: &[u8] = &[0x83, 0xf8]; -const COMPARE_EQUAL_SINGLE: &[u8] = &[0x0f, 0xc2]; -const REGISTER_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; const EQUAL_PREDICATE: u8 = 0; -pub(super) fn install_environment(code: &mut Vec, frame: &Frame) { - code.push(MOV_EAX_IMMEDIATE); - code.extend(MXCSR_ROUND_ZERO.to_le_bytes()); +pub(super) fn install_environment(code: &mut Code, frame: &Frame) { + code.asm().mov_imm32(Rax, MXCSR_ROUND_ZERO); numerical::install_mxcsr(code, frame); } -fn arithmetic(code: &mut Vec, opcode: ArithmeticOpcode, destination: u8, source: u8) { - emit_opcode_to( - code, - Format::Single, - Shape::Vector128, - opcode, - destination, - source, - ); -} - -fn guard_normal(code: &mut Vec, source: u8, failures: &mut Vec) { +fn guard_normal(code: &mut Code, source: u8, failures: &mut Vec) { vector_exponent_range(code, Format::Single, Shape::Vector128, source); failures.push(branch(code, Condition::NotZero)); } -fn guard_normal_or_zero( - code: &mut Vec, - source: u8, - failures: &mut Vec, - target: TargetCpu, -) { +fn guard_normal_or_zero(code: &mut Code, source: u8, failures: &mut Vec, target: TargetCpu) { vector_exponent_range(code, Format::Single, Shape::Vector128, source); Host::MoveAligned.register(code, SECOND_RESIDUAL, source, target); ShiftOpcode::LeftDword.emit(code, SECOND_RESIDUAL, SIGN_BITS); Host::EqualDword.register(code, SECOND_RESIDUAL, ZERO, target); Host::Or.register(code, FIRST_RESIDUAL, SECOND_RESIDUAL, target); - Host::DwordSignMask.register(code, GPR_RAX, FIRST_RESIDUAL, target); - code.extend(CMP_EAX_IMMEDIATE); - code.push(ALL_SINGLE_LANES); + code.asm() + .simd_to_gpr(Host::DwordSignMask, Rax, FIRST_RESIDUAL, target); + code.asm() + .alu_imm8(Alu::Cmp, Size::Dword, Rax, ALL_SINGLE_LANES as i8); failures.push(branch(code, Condition::NotZero)); } -fn guard_real_status(code: &mut Vec, frame: &Frame, failures: &mut Vec) { +fn guard_real_status(code: &mut Code, frame: &Frame, failures: &mut Vec) { numerical::capture_status(code, frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_OTHER_STATUS as i32); failures.push(branch(code, Condition::NotZero)); } -fn compare_equal(code: &mut Vec, destination: u8, source: u8) { - code.extend(COMPARE_EQUAL_SINGLE); - code.extend([ - REGISTER_DIRECT | destination << MODRM_REGISTER_SHIFT | source, +fn compare_equal(code: &mut Code, destination: u8, source: u8) { + code.asm().float_compare( + FloatLanes::PackedSingle, + destination, + Rm::Xmm(source), EQUAL_PREDICATE, - ]); + ); } -fn odd_add(code: &mut Vec, frame: &Frame, failures: &mut Vec, target: TargetCpu) { +fn odd_add(code: &mut Code, frame: &Frame, failures: &mut Vec, target: TargetCpu) { Host::MoveAligned.register(code, ORIGINAL_LEFT, LEFT, target); - arithmetic(code, ArithmeticOpcode::Add, LEFT, RIGHT); + single_vector_arithmetic(code, ArithmeticOpcode::Add, LEFT, RIGHT); guard_real_status(code, frame, failures); prepare_vector_input_range(code, Format::Single); guard_normal_or_zero(code, LEFT, failures, target); // Both residuals are exact only for an exact sum. For an inexact sum, the // dominant operand residual is exact (Sterbenz), and the other differs. Host::MoveAligned.register(code, FIRST_RESIDUAL, LEFT, target); - arithmetic( + single_vector_arithmetic( code, ArithmeticOpcode::Subtract, FIRST_RESIDUAL, @@ -111,7 +92,7 @@ fn odd_add(code: &mut Vec, frame: &Frame, failures: &mut Vec, target: ); compare_equal(code, FIRST_RESIDUAL, RIGHT); Host::MoveAligned.register(code, SECOND_RESIDUAL, LEFT, target); - arithmetic(code, ArithmeticOpcode::Subtract, SECOND_RESIDUAL, RIGHT); + single_vector_arithmetic(code, ArithmeticOpcode::Subtract, SECOND_RESIDUAL, RIGHT); compare_equal(code, SECOND_RESIDUAL, ORIGINAL_LEFT); Host::And.register(code, FIRST_RESIDUAL, SECOND_RESIDUAL, target); Host::EqualDword.register(code, ODD_BIT, ODD_BIT, target); @@ -123,7 +104,7 @@ fn odd_add(code: &mut Vec, frame: &Frame, failures: &mut Vec, target: } pub(super) fn pair_sum( - code: &mut Vec, + code: &mut Code, frame: &Frame, failures: &mut Vec, target: TargetCpu, @@ -138,8 +119,8 @@ pub(super) fn pair_sum( for source in [LEFT, RIGHT, LEFT_ODD, RIGHT_ODD] { guard_normal(code, source, failures); } - arithmetic(code, ArithmeticOpcode::Multiply, LEFT, RIGHT); - arithmetic(code, ArithmeticOpcode::Multiply, LEFT_ODD, RIGHT_ODD); + single_vector_arithmetic(code, ArithmeticOpcode::Multiply, LEFT, RIGHT); + single_vector_arithmetic(code, ArithmeticOpcode::Multiply, LEFT_ODD, RIGHT_ODD); guard_real_status(code, frame, failures); guard_normal(code, LEFT, failures); guard_normal(code, LEFT_ODD, failures); @@ -148,7 +129,7 @@ pub(super) fn pair_sum( } pub(super) fn add_accumulator( - code: &mut Vec, + code: &mut Code, frame: &Frame, failures: &mut Vec, target: TargetCpu, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/enhanced_dot.rs b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/enhanced_dot.rs index 2927e558f4..c55858c95f 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/enhanced_dot.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/enhanced_dot.rs @@ -4,6 +4,13 @@ //! MXCSR and restores it afterwards; host status is discarded. Inputs: XMM0/XMM1 //! hold eight BF16 values, XMM6 four single accumulators. Output: XMM0 holds four //! singles. Clobbers XMM2-5, XMM7, RAX, RCX and flags. +use crate::TargetCpu; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::FloatOp; +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; +use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; use crate::x86_64::scalable::numerical; use alloc::vec::Vec; @@ -16,18 +23,9 @@ const WORK_PAIR: u8 = 4; const OUTPUT: u8 = 5; const ACCUMULATOR: u8 = 6; const WORK_MASK: u8 = 7; -const EAX: u8 = 0; const SIGN_DISCARD_SHIFT: u8 = 1; const DOUBLE_SIGN_BIT: u8 = 63; const DWORD_BITS: u8 = 32; -const REGISTER_MODRM: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const REL32_BYTES: usize = core::mem::size_of::(); -const CONDITIONAL_ESCAPE: u8 = 0x0f; -const EQUAL: u8 = 0x84; -const NOT_EQUAL: u8 = 0x85; -const BELOW: u8 = 0x82; -const BELOW_OR_EQUAL: u8 = 0x86; const BFLOAT_EXPONENT_PAIR: u32 = 0x7f80_7f80; const SINGLE_EXPONENT: u32 = 0x7f80_0000; const SINGLE_MAGNITUDE: u32 = 0x7fff_ffff; @@ -38,202 +36,141 @@ const HALF_CHUNK_BYTES: u8 = 8; const UPPER_TWO_SINGLES: u8 = 0xee; const SPLAT_LOW_DWORD: u8 = 0; -const MOVDQA: &[u8] = &[0x66, 0x0f, 0x6f]; -const MOVQ_XMM: &[u8] = &[0xf3, 0x0f, 0x7e]; -const PXOR: &[u8] = &[0x66, 0x0f, 0xef]; -const PAND: &[u8] = &[0x66, 0x0f, 0xdb]; -const PANDN: &[u8] = &[0x66, 0x0f, 0xdf]; -const POR: &[u8] = &[0x66, 0x0f, 0xeb]; -const PCMPEQW: &[u8] = &[0x66, 0x0f, 0x75]; -const PCMPEQD: &[u8] = &[0x66, 0x0f, 0x76]; -const PUNPCKLWD: &[u8] = &[0x66, 0x0f, 0x61]; -const PSHUFD: &[u8] = &[0x66, 0x0f, 0x70]; -const PSLLW_IMM: &[u8] = &[0x66, 0x0f, 0x71]; -const PSLLD_IMM: &[u8] = &[0x66, 0x0f, 0x72]; -const PSRLDQ_IMM: &[u8] = &[0x66, 0x0f, 0x73]; -const SHIFT_LEFT_GROUP: u8 = 6; -const SHIFT_RIGHT_BYTES_GROUP: u8 = 3; -const CVTPS2PD: &[u8] = &[0x0f, 0x5a]; -const CVTPD2PS: &[u8] = &[0x66, 0x0f, 0x5a]; -const MULPD: &[u8] = &[0x66, 0x0f, 0x59]; -const ADDPD: &[u8] = &[0x66, 0x0f, 0x58]; -const ADDPS: &[u8] = &[0x0f, 0x58]; -const UNPCKLPD: &[u8] = &[0x66, 0x0f, 0x14]; -const UNPCKHPD: &[u8] = &[0x66, 0x0f, 0x15]; -const MOVD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; -const MOVQ_RAX_XMM: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const PMOVMSKB_EAX_XMM: &[u8] = &[0x66, 0x0f, 0xd7]; -const MOV_EAX_IMM32: u8 = 0xb8; -const MOV_RCX_IMM64: &[u8] = &[0x48, 0xb9]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const CMP_ECX_IMM32: &[u8] = &[0x81, 0xf9]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const TEST_ECX_ECX: &[u8] = &[0x85, 0xc9]; -const TEST_RAX_RAX: &[u8] = &[0x48, 0x85, 0xc0]; -const CMP_RAX_RCX: &[u8] = &[0x48, 0x39, 0xc8]; -const BTR_RAX_SIGN: &[u8] = &[0x48, 0x0f, 0xba, 0xf0, DOUBLE_SIGN_BIT]; -const SHR_RAX_DWORD: &[u8] = &[0x48, 0xc1, 0xe8, DWORD_BITS]; - -fn vector(code: &mut Vec, opcode: &[u8], destination: u8, source: u8) { - code.extend(opcode); - code.push(REGISTER_MODRM | destination << MODRM_REGISTER_SHIFT | source); +fn vector(code: &mut Code, opcode: Host, destination: u8, source: u8) { + code.asm() + .simd(opcode, destination, Rm::Xmm(source), TargetCpu::Baseline); } -fn shuffle(code: &mut Vec, destination: u8, source: u8, lanes: u8) { - vector(code, PSHUFD, destination, source); - code.push(lanes); +fn shuffle(code: &mut Code, destination: u8, source: u8, lanes: u8) { + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(source), + lanes, + TargetCpu::Baseline, + ); } -fn shift(code: &mut Vec, opcode: &[u8], group: u8, register: u8, amount: u8) { - code.extend(opcode); - code.extend([ - REGISTER_MODRM | group << MODRM_REGISTER_SHIFT | register, - amount, - ]); -} - -fn branch(code: &mut Vec, condition: u8) -> usize { - code.extend([CONDITIONAL_ESCAPE, condition]); - let displacement = code.len(); - code.extend([0; REL32_BYTES]); - displacement -} - -fn skip_to_here(code: &mut [u8], displacement: usize) { - let relative = i32::try_from(code.len() - displacement - REL32_BYTES) - .expect("bounded enhanced BFDOT chunk"); - code[displacement..displacement + REL32_BYTES].copy_from_slice(&relative.to_le_bytes()); -} - -fn mask(code: &mut Vec, value: u32) { - code.push(MOV_EAX_IMM32); - code.extend(value.to_le_bytes()); - vector(code, MOVD_XMM_EAX, WORK_MASK, EAX); +fn mask(code: &mut Code, value: u32) { + let mut asm = code.asm(); + asm.mov_imm32(Rax, value); + asm.movd_to_xmm(WORK_MASK, Rax); shuffle(code, WORK_MASK, WORK_MASK, SPLAT_LOW_DWORD); } -fn reject_mask(code: &mut Vec, register: u8, failures: &mut Vec) { - vector(code, PMOVMSKB_EAX_XMM, EAX, register); - code.extend(TEST_EAX_EAX); - failures.push(branch(code, NOT_EQUAL)); +fn reject_mask(code: &mut Code, register: u8, failures: &mut Vec) { + let mut asm = code.asm(); + asm.simd_to_gpr(Host::ByteSignMask, Rax, register, TargetCpu::Baseline); + asm.test(Size::Dword, Rax, Rax); + failures.push(asm.jcc(Cond::Ne).offset()); } -fn guard_bfloat(code: &mut Vec, source: u8, failures: &mut Vec) { - vector(code, MOVDQA, WORK_LEFT, source); - vector(code, PAND, WORK_LEFT, WORK_MASK); - vector(code, MOVDQA, WORK_RIGHT, WORK_LEFT); - vector(code, PCMPEQW, WORK_RIGHT, WORK_MASK); - vector(code, PCMPEQW, WORK_LEFT, OUTPUT); - vector(code, MOVDQA, WORK_PAIR, source); - shift( - code, - PSLLW_IMM, - SHIFT_LEFT_GROUP, - WORK_PAIR, - SIGN_DISCARD_SHIFT, - ); - vector(code, PCMPEQW, WORK_PAIR, OUTPUT); - vector(code, PANDN, WORK_PAIR, WORK_LEFT); - vector(code, POR, WORK_RIGHT, WORK_PAIR); +fn guard_bfloat(code: &mut Code, source: u8, failures: &mut Vec) { + vector(code, Host::MoveAligned, WORK_LEFT, source); + vector(code, Host::And, WORK_LEFT, WORK_MASK); + vector(code, Host::MoveAligned, WORK_RIGHT, WORK_LEFT); + vector(code, Host::EqualWord, WORK_RIGHT, WORK_MASK); + vector(code, Host::EqualWord, WORK_LEFT, OUTPUT); + vector(code, Host::MoveAligned, WORK_PAIR, source); + Shift::LeftWord.emit(code, WORK_PAIR, SIGN_DISCARD_SHIFT); + vector(code, Host::EqualWord, WORK_PAIR, OUTPUT); + vector(code, Host::AndNot, WORK_PAIR, WORK_LEFT); + vector(code, Host::Or, WORK_RIGHT, WORK_PAIR); reject_mask(code, WORK_RIGHT, failures); } -fn guard_accumulator(code: &mut Vec, failures: &mut Vec) { - vector(code, MOVDQA, WORK_LEFT, ACCUMULATOR); - shift( - code, - PSLLD_IMM, - SHIFT_LEFT_GROUP, - WORK_LEFT, - SIGN_DISCARD_SHIFT, - ); - vector(code, PCMPEQD, WORK_LEFT, OUTPUT); - vector(code, MOVDQA, WORK_RIGHT, ACCUMULATOR); - vector(code, PAND, WORK_RIGHT, WORK_MASK); - vector(code, MOVDQA, WORK_PAIR, WORK_RIGHT); - vector(code, PCMPEQD, WORK_RIGHT, OUTPUT); - vector(code, PANDN, WORK_LEFT, WORK_RIGHT); - vector(code, PCMPEQD, WORK_PAIR, WORK_MASK); - vector(code, POR, WORK_LEFT, WORK_PAIR); +fn guard_accumulator(code: &mut Code, failures: &mut Vec) { + vector(code, Host::MoveAligned, WORK_LEFT, ACCUMULATOR); + Shift::LeftDword.emit(code, WORK_LEFT, SIGN_DISCARD_SHIFT); + vector(code, Host::EqualDword, WORK_LEFT, OUTPUT); + vector(code, Host::MoveAligned, WORK_RIGHT, ACCUMULATOR); + vector(code, Host::And, WORK_RIGHT, WORK_MASK); + vector(code, Host::MoveAligned, WORK_PAIR, WORK_RIGHT); + vector(code, Host::EqualDword, WORK_RIGHT, OUTPUT); + vector(code, Host::AndNot, WORK_LEFT, WORK_RIGHT); + vector(code, Host::EqualDword, WORK_PAIR, WORK_MASK); + vector(code, Host::Or, WORK_LEFT, WORK_PAIR); reject_mask(code, WORK_LEFT, failures); } -fn guard_double(code: &mut Vec, register: u8, failures: &mut Vec) { +fn guard_double(code: &mut Code, register: u8, failures: &mut Vec) { // All inputs/products/sums are finite Double. Unsigned magnitude bits sort // numerically. Strict > excludes pre-round tininess obscured by directed // rounding up to min-normal; exact signed zero is admitted separately. - vector(code, MOVQ_RAX_XMM, register, EAX); - code.extend(BTR_RAX_SIGN); - code.extend(TEST_RAX_RAX); - let zero = branch(code, EQUAL); - code.extend(MOV_RCX_IMM64); - code.extend(SINGLE_MINIMUM_NORMAL_AS_DOUBLE.to_le_bytes()); - code.extend(CMP_RAX_RCX); - failures.push(branch(code, BELOW_OR_EQUAL)); - skip_to_here(code, zero); + let mut asm = code.asm(); + asm.movq_from_xmm(Rax, register); + asm.bit_imm(BitTest::Btr, Size::Qword, Rax, DOUBLE_SIGN_BIT); + asm.test(Size::Qword, Rax, Rax); + let zero = asm.jcc(Cond::E); + asm.mov_imm64(Rcx, SINGLE_MINIMUM_NORMAL_AS_DOUBLE); + asm.alu(Alu::Cmp, Size::Qword, Rax, Rcx); + failures.push(asm.jcc(Cond::Be).offset()); + asm.bind(zero); } -fn guard_single(code: &mut Vec, failures: &mut Vec) { - code.extend(MOV_ECX_EAX); - code.extend(AND_ECX_IMM32); - code.extend(SINGLE_MAGNITUDE.to_le_bytes()); - code.extend(TEST_ECX_ECX); - let zero = branch(code, EQUAL); - code.extend(CMP_ECX_IMM32); - code.extend(SINGLE_MINIMUM_NORMAL.to_le_bytes()); - failures.push(branch(code, BELOW)); - skip_to_here(code, zero); +fn guard_single(code: &mut Code, failures: &mut Vec) { + let mut asm = code.asm(); + asm.mov(Size::Dword, Rcx, Rax); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, SINGLE_MAGNITUDE as i32); + asm.test(Size::Dword, Rcx, Rcx); + let zero = asm.jcc(Cond::E); + asm.alu_imm32(Alu::Cmp, Size::Dword, Rcx, SINGLE_MINIMUM_NORMAL as i32); + failures.push(asm.jcc(Cond::B).offset()); + asm.bind(zero); } -fn product_pair(code: &mut Vec, upper: bool) { - vector(code, PXOR, WORK_MASK, WORK_MASK); - vector(code, MOVDQA, WORK_LEFT, LEFT); - vector(code, MOVDQA, WORK_RIGHT, RIGHT); +fn product_pair(code: &mut Code, upper: bool) { + vector(code, Host::Xor, WORK_MASK, WORK_MASK); + vector(code, Host::MoveAligned, WORK_LEFT, LEFT); + vector(code, Host::MoveAligned, WORK_RIGHT, RIGHT); if upper { - shift( - code, - PSRLDQ_IMM, - SHIFT_RIGHT_BYTES_GROUP, - WORK_LEFT, - HALF_CHUNK_BYTES, - ); - shift( - code, - PSRLDQ_IMM, - SHIFT_RIGHT_BYTES_GROUP, - WORK_RIGHT, - HALF_CHUNK_BYTES, - ); + Shift::RightBytes.emit(code, WORK_LEFT, HALF_CHUNK_BYTES); + Shift::RightBytes.emit(code, WORK_RIGHT, HALF_CHUNK_BYTES); } for register in [WORK_LEFT, WORK_RIGHT] { - vector(code, PUNPCKLWD, register, WORK_MASK); - shift( - code, - PSLLD_IMM, - SHIFT_LEFT_GROUP, - register, - BFLOAT_TO_SINGLE_SHIFT, - ); + vector(code, Host::UnpackLowWord, register, WORK_MASK); + Shift::LeftDword.emit(code, register, BFLOAT_TO_SINGLE_SHIFT); } - vector(code, CVTPS2PD, WORK_PAIR, WORK_LEFT); - vector(code, CVTPS2PD, WORK_MASK, WORK_RIGHT); - vector(code, MULPD, WORK_PAIR, WORK_MASK); + let mut asm = code.asm(); + asm.cvtps2pd(WORK_PAIR, Rm::Xmm(WORK_LEFT)); + asm.cvtps2pd(WORK_MASK, Rm::Xmm(WORK_RIGHT)); + asm.float( + FloatOp::Mul, + FloatLanes::PackedDouble, + WORK_PAIR, + Rm::Xmm(WORK_MASK), + ); shuffle(code, WORK_LEFT, WORK_LEFT, UPPER_TWO_SINGLES); shuffle(code, WORK_RIGHT, WORK_RIGHT, UPPER_TWO_SINGLES); - vector(code, CVTPS2PD, WORK_LEFT, WORK_LEFT); - vector(code, CVTPS2PD, WORK_RIGHT, WORK_RIGHT); - vector(code, MULPD, WORK_LEFT, WORK_RIGHT); - vector(code, MOVDQA, WORK_RIGHT, WORK_PAIR); - vector(code, UNPCKLPD, WORK_RIGHT, WORK_LEFT); - vector(code, UNPCKHPD, WORK_PAIR, WORK_LEFT); - vector(code, ADDPD, WORK_RIGHT, WORK_PAIR); + let mut asm = code.asm(); + asm.cvtps2pd(WORK_LEFT, Rm::Xmm(WORK_LEFT)); + asm.cvtps2pd(WORK_RIGHT, Rm::Xmm(WORK_RIGHT)); + asm.float( + FloatOp::Mul, + FloatLanes::PackedDouble, + WORK_LEFT, + Rm::Xmm(WORK_RIGHT), + ); + asm.simd( + Host::MoveAligned, + WORK_RIGHT, + Rm::Xmm(WORK_PAIR), + TargetCpu::Baseline, + ); + asm.unpcklpd(WORK_RIGHT, Rm::Xmm(WORK_LEFT)); + asm.unpckhpd(WORK_PAIR, Rm::Xmm(WORK_LEFT)); + asm.float( + FloatOp::Add, + FloatLanes::PackedDouble, + WORK_RIGHT, + Rm::Xmm(WORK_PAIR), + ); } /// Shared-frame guarded enhanced branch. Failures target the outer frame's /// common cleanup; pending guest FPSR must remain zero throughout this branch. -pub(super) fn emit_chunk(code: &mut Vec, _frame: &numerical::Frame, failures: &mut Vec) { - vector(code, PXOR, OUTPUT, OUTPUT); +pub(super) fn emit_chunk(code: &mut Code, _frame: &numerical::Frame, failures: &mut Vec) { + vector(code, Host::Xor, OUTPUT, OUTPUT); mask(code, BFLOAT_EXPONENT_PAIR); guard_bfloat(code, LEFT, failures); guard_bfloat(code, RIGHT, failures); @@ -242,25 +179,37 @@ pub(super) fn emit_chunk(code: &mut Vec, _frame: &numerical::Frame, failures for upper in [false, true] { product_pair(code, upper); guard_double(code, WORK_RIGHT, failures); - vector(code, MOVDQA, WORK_PAIR, WORK_RIGHT); - vector(code, UNPCKHPD, WORK_PAIR, WORK_PAIR); + vector(code, Host::MoveAligned, WORK_PAIR, WORK_RIGHT); + code.asm().unpckhpd(WORK_PAIR, Rm::Xmm(WORK_PAIR)); guard_double(code, WORK_PAIR, failures); - vector(code, CVTPD2PS, WORK_RIGHT, WORK_RIGHT); + code.asm().cvtpd2ps(WORK_RIGHT, Rm::Xmm(WORK_RIGHT)); if upper { shuffle(code, WORK_PAIR, ACCUMULATOR, UPPER_TWO_SINGLES); - vector(code, ADDPS, WORK_RIGHT, WORK_PAIR); + code.asm().float( + FloatOp::Add, + FloatLanes::PackedSingle, + WORK_RIGHT, + Rm::Xmm(WORK_PAIR), + ); } else { - vector(code, ADDPS, WORK_RIGHT, ACCUMULATOR); + code.asm().float( + FloatOp::Add, + FloatLanes::PackedSingle, + WORK_RIGHT, + Rm::Xmm(ACCUMULATOR), + ); } - vector(code, MOVQ_RAX_XMM, WORK_RIGHT, EAX); + code.asm().movq_from_xmm(Rax, WORK_RIGHT); guard_single(code, failures); - code.extend(SHR_RAX_DWORD); + code.asm() + .shift_imm(ShiftOp::Shr, Size::Qword, Rax, DWORD_BITS); guard_single(code, failures); + let mut asm = code.asm(); if upper { - vector(code, UNPCKLPD, OUTPUT, WORK_RIGHT); + asm.unpcklpd(OUTPUT, Rm::Xmm(WORK_RIGHT)); } else { - vector(code, MOVQ_XMM, OUTPUT, WORK_RIGHT); + asm.movq_xmm(OUTPUT, Rm::Xmm(WORK_RIGHT)); } } - vector(code, MOVDQA, LEFT, OUTPUT); + vector(code, Host::MoveAligned, LEFT, OUTPUT); } diff --git a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/multiply_long.rs b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/multiply_long.rs index cf012cb846..74eb11cc97 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/multiply_long.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/accumulation/multiply_long.rs @@ -1,5 +1,7 @@ //! BFMLALB/BFMLALT with exact SSE2 products or FMA3. use super::{ADDEND, LEFT, RIGHT, shuffle, test_control}; +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, ShiftOp, Size}; use crate::{ TargetCpu, aarch64::{ @@ -31,15 +33,9 @@ const FIRST_DWORD: u8 = 0; const MXCSR_INEXACT: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; const MXCSR_INEXACT_TO_FPSR_SHIFT: u8 = 1; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const JMP_REL32: u8 = 0xe9; -const VZEROUPPER: &[u8] = &[0xc5, 0xf8, 0x77]; pub(super) fn install_environment( - code: &mut Vec, + code: &mut Code, frame: &Frame, features: NumericalFeatures, failures: &mut Vec, @@ -52,19 +48,17 @@ pub(super) fn install_environment( } // The rounding-control encoder has no frame, MXCSR or guest-state effect. rounding_control(code); - code.push(JMP_REL32); - let installed = code.len(); - code.extend(0_i32.to_le_bytes()); + let installed = code.asm().jmp().offset(); let alternative_start = code.len(); resolve(code, alternative, alternative_start); - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); let install_start = code.len(); resolve(code, installed, install_start); numerical::install_mxcsr(code, frame); } pub(super) fn prepare_sources( - code: &mut Vec, + code: &mut Code, part: VectorPart, index: Option, subtract: bool, @@ -92,20 +86,19 @@ pub(super) fn prepare_sources( } } -fn guard_normal(code: &mut Vec, source: u8, failures: &mut Vec) { +fn guard_normal(code: &mut Code, source: u8, failures: &mut Vec) { vector_exponent_range(code, Format::Single, Shape::Vector128, source); failures.push(branch(code, Condition::NotZero)); } -fn guard_status(code: &mut Vec, frame: &Frame, mask: u32, failures: &mut Vec) { +fn guard_status(code: &mut Code, frame: &Frame, mask: u32, failures: &mut Vec) { numerical::capture_status(code, frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(mask.to_le_bytes()); + code.asm().test_imm(Size::Dword, Rcx, mask as i32); failures.push(branch(code, Condition::NotZero)); } pub(super) fn evaluate( - code: &mut Vec, + code: &mut Code, frame: &Frame, failures: &mut Vec, target: TargetCpu, @@ -123,7 +116,7 @@ pub(super) fn evaluate( FusedOpcode::MultiplyAdd, target, ); - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } else { emit_opcode_to( code, @@ -152,14 +145,13 @@ pub(super) fn evaluate( guard_normal(code, LEFT, failures); test_control(code, FPCR_AH); let suppressed = branch(code, Condition::NotZero); - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_INEXACT.to_le_bytes()); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_INEXACT as i32); // MXCSR status precision bit5 maps to the cumulative FPSR precision bit4. // Keep ECX live until capture_status after the next real arithmetic stage. - const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; - code.extend(SHR_EAX_IMMEDIATE); - code.push(MXCSR_INEXACT_TO_FPSR_SHIFT); + code.asm() + .shift_imm(ShiftOp::Shr, Size::Dword, Rax, MXCSR_INEXACT_TO_FPSR_SHIFT); numerical::add_fpsr(code, frame); let status_complete = code.len(); resolve(code, suppressed, status_complete); diff --git a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic.rs b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic.rs index ce6740400d..2df51b263d 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic.rs @@ -1,5 +1,5 @@ //! Non-widening BF16 arithmetic. -use alloc::vec::Vec; +use crate::x86_64::asm::Code; mod binary; mod fused; mod selection; @@ -14,7 +14,7 @@ use crate::{ }; pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/binary.rs b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/binary.rs index 097b0596e7..b588467cb4 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/binary.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/binary.rs @@ -1,6 +1,8 @@ //! BF16 binary arithmetic. Normal inputs widen exactly to single; a nearest-even //! double rounding can differ only at a BF16 midpoint, which with host inexact //! takes software completion. +use crate::x86_64::asm::Gpr::{R10, Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, @@ -33,7 +35,6 @@ use crate::{ use alloc::vec::Vec; const RESULT: u8 = 0; -const GPR_RAX: u8 = 0; const SOURCE: u8 = 1; const TEMPORARY: u8 = 2; const CONSTANT: u8 = 3; @@ -46,38 +47,24 @@ const DISCARDED_BITS: u8 = BFLOAT16_TO_SINGLE_SHIFT as u8; const BF_MIDPOINT: u32 = 1 << (DISCARDED_BITS - 1); const REPEAT_LOW_LANE: u8 = 0; const BF_BYTES: u8 = size_of::() as u8; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; const MXCSR_INEXACT: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; const MXCSR_TO_FPSR_INEXACT_SHIFT: u8 = 1; -const TEST_ECX_IMM32: &[u8] = &[0xf7, 0xc1]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const AND_EAX_IMM32: u8 = 0x25; -const SHR_EAX_IMM8: &[u8] = &[0xc1, 0xe8]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const MOV_EAX_IMM32: u8 = 0xb8; -const JMP_REL32: u8 = 0xe9; -const MOVD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; -const TEST_R10D_R10D: &[u8] = &[0x45, 0x85, 0xd2]; -const SETNE_AL: &[u8] = &[0x0f, 0x95, 0xc0]; -const MOVZX_EAX_AL: &[u8] = &[0x0f, 0xb6, 0xc0]; -fn jump(code: &mut Vec) -> usize { - code.push(JMP_REL32); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement +fn jump(code: &mut Code) -> usize { + code.asm().jmp().offset() } -fn constant(code: &mut Vec, vector: u8, value: u32, target: TargetCpu) { - code.push(MOV_EAX_IMM32); - code.extend(value.to_le_bytes()); - code.extend(MOVD_XMM_EAX); - code.push(MODRM_REGISTER | vector << MODRM_REGISTER_SHIFT); - Host::ShuffleDword.register(code, vector, vector, target); - code.push(REPEAT_LOW_LANE); +fn constant(code: &mut Code, vector: u8, value: u32, target: TargetCpu) { + code.asm().mov_imm32(Rax, value); + code.asm().movd_to_xmm(vector, Rax); + code.asm().simd_imm( + Host::ShuffleDword, + vector, + Rm::Xmm(vector), + REPEAT_LOW_LANE, + target, + ); } fn half_group(group: usize) -> Host { @@ -89,7 +76,7 @@ fn half_group(group: usize) -> Host { } fn active_mask( - code: &mut Vec, + code: &mut Code, operand: Operand, chunk: usize, group: usize, @@ -113,13 +100,13 @@ fn active_mask( } } -fn widen(code: &mut Vec, register: u8, group: usize, target: TargetCpu) { +fn widen(code: &mut Code, register: u8, group: usize, target: TargetCpu) { Host::Xor.register(code, TEMPORARY, TEMPORARY, target); half_group(group).register(code, register, TEMPORARY, target); ShiftOpcode::LeftDword.emit(code, register, DISCARDED_BITS); } -fn benign_inactive(code: &mut Vec, register: u8, value: u32, target: TargetCpu) { +fn benign_inactive(code: &mut Code, register: u8, value: u32, target: TargetCpu) { constant(code, CONSTANT, value, target); Host::MoveAligned.register(code, TEMPORARY, ACTIVE, target); Host::AndNot.register(code, TEMPORARY, CONSTANT, target); @@ -128,7 +115,7 @@ fn benign_inactive(code: &mut Vec, register: u8, value: u32, target: TargetC } fn load_right( - code: &mut Vec, + code: &mut Code, operand: Operand, chunk: usize, group: usize, @@ -144,10 +131,20 @@ fn load_right( if index != 0 { ShiftOpcode::RightBytes.emit(code, SOURCE, index * BF_BYTES); } - Host::ShuffleLowWord.register(code, SOURCE, SOURCE, target); - code.push(REPEAT_LOW_LANE); - Host::ShuffleDword.register(code, SOURCE, SOURCE, target); - code.push(REPEAT_LOW_LANE); + code.asm().simd_imm( + Host::ShuffleLowWord, + SOURCE, + Rm::Xmm(SOURCE), + REPEAT_LOW_LANE, + target, + ); + code.asm().simd_imm( + Host::ShuffleDword, + SOURCE, + Rm::Xmm(SOURCE), + REPEAT_LOW_LANE, + target, + ); } } widen(code, SOURCE, group, target); @@ -156,17 +153,17 @@ fn load_right( /// Reject possible first-rounding ambiguity before the integer BF rounding. /// This conservative check also rejects directed/inactive cross-lane ties; it /// never accepts an ambiguous nearest-even double rounding. -fn midpoint_guard(code: &mut Vec, failures: &mut Vec, target: TargetCpu) { - code.extend(TEST_ECX_IMM32); - code.extend(MXCSR_INEXACT.to_le_bytes()); +fn midpoint_guard(code: &mut Code, failures: &mut Vec, target: TargetCpu) { + code.asm().test_imm(Size::Dword, Rcx, MXCSR_INEXACT as i32); let exact = branch(code, Condition::Zero); Host::MoveAligned.register(code, TEMPORARY, SOURCE, target); ShiftOpcode::LeftDword.emit(code, TEMPORARY, u32::BITS as u8 - DISCARDED_BITS); ShiftOpcode::RightDword.emit(code, TEMPORARY, u32::BITS as u8 - DISCARDED_BITS); constant(code, CONSTANT, BF_MIDPOINT, target); Host::EqualDword.register(code, TEMPORARY, CONSTANT, target); - Host::DwordSignMask.register(code, GPR_RAX, TEMPORARY, target); - code.extend(TEST_EAX_EAX); + code.asm() + .simd_to_gpr(Host::DwordSignMask, Rax, TEMPORARY, target); + code.asm().test(Size::Dword, Rax, Rax); failures.push(branch(code, Condition::NotZero)); let end = code.len(); resolve(code, exact, end); @@ -184,7 +181,7 @@ fn arithmetic_opcode(operation: BinaryOperation) -> Option { /// Emit the seven nonwidening BFADD/BFSUB/BFMUL forms. All sources remain in /// architectural storage until the shared frame commits the complete vector. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -219,8 +216,9 @@ pub(in crate::x86_64) fn emit( length, target, ); - Host::ByteSignMask.register(code, GPR_RAX, ACTIVE, target); - code.extend(TEST_EAX_EAX); + code.asm() + .simd_to_gpr(Host::ByteSignMask, Rax, ACTIVE, target); + code.asm().test(Size::Dword, Rax, Rax); branch(code, Condition::Zero) }); for group in 0..HALF_GROUPS { @@ -260,15 +258,14 @@ pub(in crate::x86_64) fn emit( // operation retains the non-IXC status guard. A nonexceptional BF // p8 product has at most sixteen bits and is exact at Single p24. numerical::capture_status(code, &frame); - code.extend(TEST_ECX_IMM32); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_OTHER_STATUS as i32); failures.push(branch(code, Condition::NotZero)); if operation != BinaryOperation::Multiply { - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMM32); - code.extend(MXCSR_INEXACT.to_le_bytes()); - code.extend(SHR_EAX_IMM8); - code.push(MXCSR_TO_FPSR_INEXACT_SHIFT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_INEXACT as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, MXCSR_TO_FPSR_INEXACT_SHIFT); numerical::add_fpsr(code, &frame); midpoint_guard(code, &mut failures, target); } @@ -276,11 +273,16 @@ pub(in crate::x86_64) fn emit( prepare_vector_input_range(code, Format::Single); vector_exponent_range(code, Format::Single, Shape::Vector128, RESULT); failures.push(branch(code, Condition::NotZero)); - code.extend(TEST_R10D_R10D); - code.extend(SETNE_AL); - code.extend(MOVZX_EAX_AL); - code.extend(SHL_EAX_IMM8); - code.push(INEXACT.trailing_zeros() as u8); + let mut asm = code.asm(); + asm.test(Size::Dword, R10, R10); + asm.setcc(Cond::Ne, Rax); + asm.movzx(Size::Dword, Rax, Size::Byte, Rax); + asm.shift_imm( + ShiftOp::Shl, + Size::Dword, + Rax, + INEXACT.trailing_zeros() as u8, + ); numerical::add_fpsr(code, &frame); ShiftOpcode::ArithmeticDword.emit(code, RESULT, DISCARDED_BITS); Host::PackSignedDwordToWord.register(code, RESULT, RESULT, target); diff --git a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/fused.rs b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/fused.rs index b2ef585db5..ddda38d559 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/fused.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/fused.rs @@ -1,5 +1,9 @@ //! BF16 fused multiply-add through exact double arithmetic. Close exponents make //! the product and sum exact in double; round-to-odd then feeds BF16 rounding. +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::FloatOp; +use crate::x86_64::asm::Gpr::{R10, Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size, Unary}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -17,16 +21,13 @@ use crate::{ numerical::{self, Environment, Output}, read_predicate_mask, }, - simd::numerical::{ - Condition, branch, integer_rounding_policy, quantize_bfloat_scalar_bits, resolve, - }, + simd::numerical::{integer_rounding_policy, quantize_bfloat_scalar_bits}, sve::floating::classify::guard_active_exception_enables, }, }; use alloc::vec::Vec; const RESULT: u8 = 0; -const GPR_RAX: u8 = 0; const ACCUMULATOR: u8 = 1; const LEFT: u8 = 2; const RIGHT: u8 = 3; @@ -50,158 +51,102 @@ const EXPONENT_REBIAS: u64 = (1023 - 127) << 23; const MINIMUM_DOUBLE_EXPONENT: u32 = 1023 - 127 + 1; const NORMAL_EXPONENT_INTERVAL: u32 = 253; const EXACT_EXPONENT_DISTANCE: u8 = 32; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const PEXTRW: &[u8] = &[0x66, 0x0f, 0xc5]; -const PINSRW: &[u8] = &[0x66, 0x0f, 0xc4]; -const MOVD: &[u8] = &[0x66, 0x0f, 0x6e]; -const CVTSS2SD: &[u8] = &[0xf3, 0x0f, 0x5a]; -const MULSD: &[u8] = &[0xf2, 0x0f, 0x59]; -const ADDSD: &[u8] = &[0xf2, 0x0f, 0x58]; -const MOVQ_RAX_XMM6: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xf0]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const MOV_EDX_ECX: &[u8] = &[0x89, 0xca]; -const MOV_R10D_ECX: &[u8] = &[0x41, 0x89, 0xca]; -const NEG_R10D: &[u8] = &[0x41, 0xf7, 0xda]; -const ADD_R10D_ECX: &[u8] = &[0x41, 0x01, 0xca]; -const SUB_R10D_IMM8: &[u8] = &[0x41, 0x83, 0xea]; -const ADD_R10D_IMM8: &[u8] = &[0x41, 0x83, 0xc2]; -const CMP_R10D_IMM8: &[u8] = &[0x41, 0x83, 0xfa]; -const SHR_ECX_IMM8: &[u8] = &[0xc1, 0xe9]; -const SHR_EAX_IMM8: &[u8] = &[0xc1, 0xe8]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const SUB_EDX_ONE: &[u8] = &[0x83, 0xea, 1]; -const CMP_EDX_IMM32: &[u8] = &[0x81, 0xfa]; -const XOR_EAX_IMM32: u8 = 0x35; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const TEST_EAX_IMM32: u8 = 0xa9; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const SHR_RCX_IMM8: &[u8] = &[0x48, 0xc1, 0xe9]; -const SUB_ECX_IMM32: &[u8] = &[0x81, 0xe9]; -const CMP_ECX_IMM32: &[u8] = &[0x81, 0xf9]; -const SETNZ_CL: &[u8] = &[0x0f, 0x95, 0xc1]; -const MOVZX_R10D_CL: &[u8] = &[0x44, 0x0f, 0xb6, 0xd1]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const SHR_RDX_IMM8: &[u8] = &[0x48, 0xc1, 0xea]; -const AND_EDX_IMM32: &[u8] = &[0x81, 0xe2]; -const SHR_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe8]; -const MOV_RCX_IMM64: &[u8] = &[0x48, 0xb9]; -const SUB_RAX_RCX: &[u8] = &[0x48, 0x29, 0xc8]; -const OR_EAX_R10D: &[u8] = &[0x44, 0x09, 0xd0]; -const OR_EAX_EDX: &[u8] = &[0x09, 0xd0]; -const TEST_R10D_R10D: &[u8] = &[0x45, 0x85, 0xd2]; -const MOV_R10D_EAX: &[u8] = &[0x41, 0x89, 0xc2]; -const MOV_EAX_R10D: &[u8] = &[0x44, 0x89, 0xd0]; -const MOV_EAX_IMM32: u8 = 0xb8; -fn scalar(code: &mut Vec, opcode: &[u8], destination: u8, source: u8) { - code.extend(opcode); - code.push(MODRM_REGISTER | destination << MODRM_REGISTER_SHIFT | source); -} - -fn extract(code: &mut Vec, source: u8, lane: usize) { - scalar(code, PEXTRW, GPR_RAX, source); - code.push(lane as u8); +fn extract(code: &mut Code, source: u8, lane: usize) { + code.asm().pextrw(Rax, source, lane as u8); } /// Preserve raw BF16 in EAX and its biased exponent in ECX. Reject zeros, /// subnormals and nonfinite values before any host floating-point instruction. -fn normal_input(code: &mut Vec, failures: &mut Vec) { - code.extend(MOV_ECX_EAX); - code.extend(SHR_ECX_IMM8); - code.push(BFLOAT_FRACTION_BITS); - code.extend(AND_ECX_IMM32); - code.extend(BFLOAT_EXPONENT_MASK.to_le_bytes()); - code.extend(MOV_EDX_ECX); - code.extend(SUB_EDX_ONE); - code.extend(CMP_EDX_IMM32); - code.extend(NORMAL_EXPONENT_INTERVAL.to_le_bytes()); - failures.push(branch(code, Condition::Above)); +fn normal_input(code: &mut Code, failures: &mut Vec) { + let mut asm = code.asm(); + asm.mov(Size::Dword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rcx, BFLOAT_FRACTION_BITS); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, BFLOAT_EXPONENT_MASK as i32); + asm.mov(Size::Dword, Rdx, Rcx); + asm.alu_imm8(Alu::Sub, Size::Dword, Rdx, 1); + asm.alu_imm32(Alu::Cmp, Size::Dword, Rdx, NORMAL_EXPONENT_INTERVAL as i32); + failures.push(asm.jcc(Cond::A).offset()); } -fn widen(code: &mut Vec, destination: u8) { - code.extend(SHL_EAX_IMM8); - code.push(SINGLE_TO_BFLOAT_SHIFT); - scalar(code, MOVD, destination, GPR_RAX); - scalar(code, CVTSS2SD, destination, destination); +fn widen(code: &mut Code, destination: u8) { + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, SINGLE_TO_BFLOAT_SHIFT); + asm.movd_to_xmm(destination, Rax); + asm.cvtss2sd(destination, Rm::Xmm(destination)); } /// Product precision is at most16 bits. With |eL+eR-eA| <=32, aligning the /// accumulator and product requires at most48 significant bits plus one carry, /// fitting Double53 even before cancellation. Both Double operations are exact. -fn exact_exponent_guard(code: &mut Vec, failures: &mut Vec) { - code.extend(SUB_R10D_IMM8); - code.push(BFLOAT_EXPONENT_BIAS as u8); - code.extend(ADD_R10D_IMM8); - code.push(EXACT_EXPONENT_DISTANCE); - code.extend(CMP_R10D_IMM8); - code.push(EXACT_EXPONENT_DISTANCE * 2); - failures.push(branch(code, Condition::Above)); +fn exact_exponent_guard(code: &mut Code, failures: &mut Vec) { + let mut asm = code.asm(); + asm.alu_imm8(Alu::Sub, Size::Dword, R10, BFLOAT_EXPONENT_BIAS as i8); + asm.alu_imm8(Alu::Add, Size::Dword, R10, EXACT_EXPONENT_DISTANCE as i8); + asm.alu_imm8( + Alu::Cmp, + Size::Dword, + R10, + (EXACT_EXPONENT_DISTANCE * 2) as i8, + ); + failures.push(asm.jcc(Cond::A).offset()); } /// Compress an exact Double to a rebased Single-shaped integer representation. /// The low29 discarded bits become one sticky bit. Sixteen retained guard bits /// remain below BF precision, so every final BF rounding mode sees the same /// below-half/equal-half/above-half and nonzero-remainder classification. -fn compress(code: &mut Vec, failures: &mut Vec) { - code.extend(MOVQ_RAX_XMM6); - code.extend(MOV_RCX_RAX); - code.extend(SHR_RCX_IMM8); - code.push(Format::Double.fraction_bits() as u8); - code.extend(AND_ECX_IMM32); - code.extend(0x7ff_u32.to_le_bytes()); - code.extend(SUB_ECX_IMM32); - code.extend(MINIMUM_DOUBLE_EXPONENT.to_le_bytes()); - code.extend(CMP_ECX_IMM32); - code.extend(NORMAL_EXPONENT_INTERVAL.to_le_bytes()); - failures.push(branch(code, Condition::Above)); - code.push(TEST_EAX_IMM32); - code.extend(STICKY_MASK.to_le_bytes()); - code.extend(SETNZ_CL); - code.extend(MOVZX_R10D_CL); - code.extend(MOV_RDX_RAX); - code.extend(SHR_RDX_IMM8); - code.push(u32::BITS as u8); - code.extend(AND_EDX_IMM32); - code.extend(SINGLE_SIGN_MASK.to_le_bytes()); - code.extend(SHR_RAX_IMM8); - code.push(DOUBLE_TO_SINGLE_SHIFT); - code.extend(MOV_RCX_IMM64); - code.extend(EXPONENT_REBIAS.to_le_bytes()); - code.extend(SUB_RAX_RCX); - code.extend(OR_EAX_R10D); - code.extend(OR_EAX_EDX); +fn compress(code: &mut Code, failures: &mut Vec) { + let mut asm = code.asm(); + asm.movq_from_xmm(Rax, 6); + asm.mov(Size::Qword, Rcx, Rax); + asm.shift_imm( + ShiftOp::Shr, + Size::Qword, + Rcx, + Format::Double.fraction_bits() as u8, + ); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, 0x7ff); + asm.alu_imm32(Alu::Sub, Size::Dword, Rcx, MINIMUM_DOUBLE_EXPONENT as i32); + asm.alu_imm32(Alu::Cmp, Size::Dword, Rcx, NORMAL_EXPONENT_INTERVAL as i32); + failures.push(asm.jcc(Cond::A).offset()); + asm.test_accumulator_imm(Size::Dword, STICKY_MASK as i32); + asm.setcc(Cond::Ne, Rcx); + asm.movzx(Size::Dword, R10, Size::Byte, Rcx); + asm.mov(Size::Qword, Rdx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rdx, u32::BITS as u8); + asm.alu_imm32(Alu::And, Size::Dword, Rdx, SINGLE_SIGN_MASK as i32); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rax, DOUBLE_TO_SINGLE_SHIFT); + asm.mov_imm64(Rcx, EXPONENT_REBIAS); + asm.alu(Alu::Sub, Size::Qword, Rax, Rcx); + asm.alu(Alu::Or, Size::Dword, Rax, R10); + asm.alu(Alu::Or, Size::Dword, Rax, Rdx); } /// Shared R8D/R9D/R11D selectors own RC and nearest-even parity. Every discarded /// bit records true-BF IXC, including AH1. Pending status commits only at finish. -fn quantize(code: &mut Vec, frame: &numerical::Frame, failures: &mut Vec) { +fn quantize(code: &mut Code, frame: &numerical::Frame, failures: &mut Vec) { // R10D holds the compression sticky bit, which is already part of EAX. // The shared helper's OR-accumulation therefore records exactly low16. quantize_bfloat_scalar_bits(code); - code.extend(TEST_R10D_R10D); - let exact = branch(code, Condition::Zero); - code.extend(MOV_R10D_EAX); - code.push(MOV_EAX_IMM32); - code.extend(INEXACT.to_le_bytes()); + let mut asm = code.asm(); + asm.test(Size::Dword, R10, R10); + let exact = asm.jcc(Cond::E); + asm.mov(Size::Dword, R10, Rax); + asm.mov_imm32(Rax, INEXACT); numerical::add_fpsr(code, frame); - code.extend(MOV_EAX_R10D); - let destination = code.len(); - resolve(code, exact, destination); - code.extend(MOV_ECX_EAX); - code.extend(AND_ECX_IMM32); - code.extend(SINGLE_EXPONENT_MASK.to_le_bytes()); - code.extend(CMP_ECX_IMM32); - code.extend(SINGLE_EXPONENT_MASK.to_le_bytes()); - failures.push(branch(code, Condition::Zero)); - code.extend(SHR_EAX_IMM8); - code.push(SINGLE_TO_BFLOAT_SHIFT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, R10); + asm.bind(exact); + asm.mov(Size::Dword, Rcx, Rax); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, SINGLE_EXPONENT_MASK as i32); + asm.alu_imm32(Alu::Cmp, Size::Dword, Rcx, SINGLE_EXPONENT_MASK as i32); + failures.push(asm.jcc(Cond::E).offset()); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, SINGLE_TO_BFLOAT_SHIFT); } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -227,7 +172,7 @@ pub(in crate::x86_64) fn emit( let mut failures = Vec::new(); // Exact admitted arithmetic is independent of host RC. Fixed RN also makes // the private environment auditable; final BF RC remains the shared policy. - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); numerical::install_mxcsr(code, &frame); integer_rounding_policy(code, SINGLE_TO_BFLOAT_SHIFT, false); for chunk in 0..length.chunks() { @@ -259,34 +204,46 @@ pub(in crate::x86_64) fn emit( Host::MoveAligned.register(code, RESULT, ACCUMULATOR, target); for lane in 0..CHUNK_LANES { extract(code, ACTIVE, lane); - code.extend(TEST_EAX_EAX); - let inactive = branch(code, Condition::Zero); + let mut asm = code.asm(); + asm.test(Size::Dword, Rax, Rax); + let inactive = asm.jcc(Cond::E); extract(code, ACCUMULATOR, lane); normal_input(code, &mut failures); - code.extend(MOV_R10D_ECX); - code.extend(NEG_R10D); + let mut asm = code.asm(); + asm.mov(Size::Dword, R10, Rcx); + asm.unary(Unary::Neg, Size::Dword, R10); widen(code, DOUBLE_ACCUMULATOR); extract(code, LEFT, lane); normal_input(code, &mut failures); - code.extend(ADD_R10D_ECX); + code.asm().alu(Alu::Add, Size::Dword, R10, Rcx); if subtract { - code.push(XOR_EAX_IMM32); - code.extend(BFLOAT_SIGN_MASK.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Xor, Size::Dword, BFLOAT_SIGN_MASK as i32); } widen(code, DOUBLE_LEFT); extract(code, RIGHT, index.map_or(lane, usize::from)); normal_input(code, &mut failures); - code.extend(ADD_R10D_ECX); + code.asm().alu(Alu::Add, Size::Dword, R10, Rcx); exact_exponent_guard(code, &mut failures); widen(code, DOUBLE_RIGHT); - scalar(code, MULSD, DOUBLE_LEFT, DOUBLE_RIGHT); - scalar(code, ADDSD, DOUBLE_LEFT, DOUBLE_ACCUMULATOR); + let mut asm = code.asm(); + asm.float( + FloatOp::Mul, + FloatLanes::ScalarDouble, + DOUBLE_LEFT, + Rm::Xmm(DOUBLE_RIGHT), + ); + asm.float( + FloatOp::Add, + FloatLanes::ScalarDouble, + DOUBLE_LEFT, + Rm::Xmm(DOUBLE_ACCUMULATOR), + ); compress(code, &mut failures); quantize(code, &frame, &mut failures); - scalar(code, PINSRW, RESULT, GPR_RAX); - code.push(lane as u8); - let destination = code.len(); - resolve(code, inactive, destination); + let mut asm = code.asm(); + asm.pinsrw(RESULT, Rax, lane as u8); + asm.bind(inactive); } numerical::stage_vector_chunk(code, &frame, OUTPUT_SLOT, chunk, RESULT, target); } diff --git a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/selection.rs b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/selection.rs index f5c25854d9..0c04893544 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/selection.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/bfloat16/arithmetic/selection.rs @@ -1,4 +1,6 @@ //! BF16 min/max and clamp on finite values and zeros, without FP status. +use crate::x86_64::asm::Gpr::{Rax, Rdi}; +use crate::x86_64::asm::{Code, Mem, Rm, Size}; use crate::{ CompileError, GuestAddress, GuestState, TargetCpu, aarch64::{ @@ -37,12 +39,6 @@ const BFLOAT_EXPONENT_BITS: u8 = 8; const BFLOAT_SIGN_BITS: u8 = 1; const SIGN_SHIFT: u8 = BFLOAT_BITS - BFLOAT_SIGN_BITS; const FRACTION_TO_SIGN_SHIFT: u8 = BFLOAT_BITS - BFLOAT_FRACTION_BITS; -const GPR_RAX: u8 = 0; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const TEST_STATE_IMMEDIATE: &[u8] = &[0xf7, 0x87]; -const PBLENDVB: &[u8] = &[0x66, 0x0f, 0x38, 0x10]; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Recipe { @@ -50,14 +46,14 @@ enum Recipe { CheckedBlend, } -fn reject_mask(code: &mut Vec, failures: &mut Vec, target: TargetCpu) { - Host::ByteSignMask.append(code, target); - code.push(MODRM_REGISTER | (GPR_RAX << MODRM_REGISTER_SHIFT) | TEMPORARY); - code.extend(TEST_EAX_EAX); +fn reject_mask(code: &mut Code, failures: &mut Vec, target: TargetCpu) { + code.asm() + .simd_to_gpr(Host::ByteSignMask, Rax, TEMPORARY, target); + code.asm().test(Size::Dword, Rax, Rax); failures.push(branch(code, Condition::NotZero)); } -fn constants(code: &mut Vec, target: TargetCpu) { +fn constants(code: &mut Code, target: TargetCpu) { Host::Xor.register(code, ZERO, ZERO, target); Host::EqualWord.register(code, EXPONENT_MAXIMUM, EXPONENT_MAXIMUM, target); ShiftOpcode::RightWord.emit(code, EXPONENT_MAXIMUM, BFLOAT_BITS - BFLOAT_EXPONENT_BITS); @@ -66,7 +62,7 @@ fn constants(code: &mut Vec, target: TargetCpu) { /// Preserve raw inputs and classify only active lanes. Exponent-all-ones values /// and nonzero subnormals use shared exact completion; signed zeros pass. fn guard( - code: &mut Vec, + code: &mut Code, input: u8, predicated: bool, failures: &mut Vec, @@ -91,7 +87,7 @@ fn guard( /// LEFT and RIGHT keep their inputs until the comparison. Equal encodings may /// return either source; opposite zeros follow the standard numeric order. -fn select(code: &mut Vec, minimum: bool, alternative: bool, recipe: Recipe, target: TargetCpu) { +fn select(code: &mut Code, minimum: bool, alternative: bool, recipe: Recipe, target: TargetCpu) { if alternative { Host::MoveAligned.register(code, TEMPORARY, LEFT, target); Host::Or.register(code, TEMPORARY, RIGHT, target); @@ -109,9 +105,11 @@ fn select(code: &mut Vec, minimum: bool, alternative: bool, recipe: Recipe, Host::Xor.register(code, RESULT, SECOND_TEMPORARY, target); } if alternative { - code.extend(TEST_STATE_IMMEDIATE); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(FPCR_AH.to_le_bytes()); + code.asm().test_imm( + Size::Dword, + Mem::base_disp32(Rdi, (core::mem::offset_of!(GuestState, fpcr)) as i32), + FPCR_AH as i32, + ); let ordinary = branch(code, Condition::Zero); Host::AndNot.register(code, TEMPORARY, RESULT, target); Host::MoveAligned.register(code, RESULT, TEMPORARY, target); @@ -120,8 +118,7 @@ fn select(code: &mut Vec, minimum: bool, alternative: bool, recipe: Recipe, } if recipe == Recipe::CheckedBlend { debug_assert!(target.supports(TargetCpu::Sse41)); - code.extend(PBLENDVB); - code.push(MODRM_REGISTER | (RIGHT << MODRM_REGISTER_SHIFT) | LEFT); + code.asm().pblendvb(RIGHT, Rm::Xmm(LEFT)); Host::MoveAligned.register(code, RESULT, RIGHT, target); } else { Host::And.register(code, LEFT, RESULT, target); @@ -131,7 +128,7 @@ fn select(code: &mut Vec, minimum: bool, alternative: bool, recipe: Recipe, } fn emit_with_recipe( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -220,7 +217,7 @@ fn emit_with_recipe( } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -242,7 +239,6 @@ pub(in crate::x86_64) fn emit( #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; const DESTINATION: u8 = 0; const CLAMP_LEFT: u8 = 1; @@ -284,16 +280,16 @@ mod tests { changes_default: bool, ) { let length = VectorLength::from_bytes(bytes).unwrap(); - let mut selected = Vec::new(); + let mut selected = Code::new(); assert!(emit(&mut selected, operand, length, FEATURES, PC, target).unwrap()); - let mut expected = Vec::new(); + let mut expected = Code::new(); assert!( emit_with_recipe(&mut expected, operand, length, FEATURES, PC, target, recipe,) .unwrap() ); assert_eq!(selected, expected, "{operand:?}, {bytes}, {target:?}"); if changes_default { - let mut baseline = Vec::new(); + let mut baseline = Code::new(); assert!( emit_with_recipe( &mut baseline, @@ -349,7 +345,7 @@ mod tests { #[test] fn explicit_blend_declines_missing_capability_before_emission() { for operand in operands() { - let mut code = Vec::new(); + let mut code = Code::new(); assert!( !emit_with_recipe( &mut code, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/classify.rs b/crates/stela-compiler/src/x86_64/sve/floating/classify.rs index 9a7ce1a5d5..ec8ef8a348 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/classify.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/classify.rs @@ -1,5 +1,7 @@ //! Integer guards selecting which lanes may use native FP. Inactive operands are //! replaced with +0 before classification. +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rdi}; +use crate::x86_64::asm::{Code, Cond, Mem, Rm, Size}; use crate::{ GuestState, TargetCpu, @@ -9,53 +11,28 @@ use crate::{ use alloc::vec::Vec; const XMM_REGISTER_COUNT: u8 = 8; -const MODRM_REGISTER: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; -const RCX_REGISTER: u8 = 1; -const RAX_REGISTER: u8 = 0; -const MOV_ECX_IMMEDIATE: &[u8] = &[0xb9]; -const MOV_RCX_IMMEDIATE: &[u8] = &[0x48, 0xb9]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const TEST_STATE_IMMEDIATE: &[u8] = &[0xf7, 0x87]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; const REPEAT_LOW_DWORD: u8 = 0; const SWAP_ADJACENT_DWORDS: u8 = 0xb1; const REPEAT_HIGH_DWORDS: u8 = 0xf5; -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement -} - -fn resolve(code: &mut [u8], displacement: usize, destination: usize) { - let next = displacement + size_of::(); - let distance = i64::try_from(destination).expect("guard destination fits i64") - - i64::try_from(next).expect("guard source fits i64"); - code[displacement..next].copy_from_slice( - &i32::try_from(distance) - .expect("bounded floating guard branch") - .to_le_bytes(), +fn shuffle(code: &mut Code, destination: u8, source: u8, order: u8, target: TargetCpu) { + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(source), + order, + target, ); } -fn shuffle(code: &mut Vec, destination: u8, source: u8, order: u8, target: TargetCpu) { - Host::ShuffleDword.register(code, destination, source, target); - code.push(order); -} - -fn broadcast(code: &mut Vec, format: Format, value: u64, destination: u8, target: TargetCpu) { +fn broadcast(code: &mut Code, format: Format, value: u64, destination: u8, target: TargetCpu) { if format == Format::Single { - code.extend(MOV_ECX_IMMEDIATE); - code.extend((value as u32).to_le_bytes()); + code.asm().mov_imm32(Rcx, value as u32); } else { - code.extend(MOV_RCX_IMMEDIATE); - code.extend(value.to_le_bytes()); + code.asm().mov_imm64(Rcx, value); } - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (destination << REGISTER_SHIFT) | RCX_REGISTER); + code.asm() + .simd(Host::MoveGprQword, destination, Rcx, target); if format == Format::Single { shuffle(code, destination, destination, REPEAT_LOW_DWORD, target); } else { @@ -63,9 +40,9 @@ fn broadcast(code: &mut Vec, format: Format, value: u64, destination: u8, ta } } -fn sign_mask(code: &mut Vec, source: u8, target: TargetCpu) { - Host::ByteSignMask.append(code, target); - code.push(MODRM_REGISTER | (RAX_REGISTER << REGISTER_SHIFT) | source); +fn sign_mask(code: &mut Code, source: u8, target: TargetCpu) { + code.asm() + .simd_to_gpr(Host::ByteSignMask, Rax, source, target); } /// Masks remain live in these caller-selected XMMs for one whole instruction. @@ -80,7 +57,7 @@ pub(in crate::x86_64) struct Classification { /// Load invariant masks once, rather than rebroadcasting them for every source /// in every vector chunk. Callers preserve these XMMs until staging is finished. pub(in crate::x86_64) fn prepare_classification( - code: &mut Vec, + code: &mut Code, format: Format, registers: [u8; 2], target: TargetCpu, @@ -104,7 +81,7 @@ pub(in crate::x86_64) fn prepare_classification( /// RAX/RCX and host arithmetic flags, without touching MXCSR or guest state. /// Failure indices identify rel32 displacements consumed by numerical::finish. pub(in crate::x86_64) fn guard_normal_zero_or_infinity( - code: &mut Vec, + code: &mut Code, classification: Classification, input: u8, scratch: [u8; 3], @@ -161,8 +138,9 @@ pub(in crate::x86_64) fn guard_normal_zero_or_infinity( Host::Xor.register(code, exponent, maximum_exponent, target); Host::Or.register(code, exponent, fraction_zero, target); sign_mask(code, exponent, target); - code.extend(TEST_EAX_EAX); - failures.push(branch(code, JNZ_REL32)); + let mut asm = code.asm(); + asm.test(Size::Dword, Rax, Rax); + failures.push(asm.jcc(Cond::Ne).offset()); } /// Active numerical work with retained guest exception enables takes the whole @@ -171,7 +149,7 @@ pub(in crate::x86_64) fn guard_normal_zero_or_infinity( /// All-inactive work bypasses the raw control read. Preserves every XMM register; /// clobbers RAX and host arithmetic flags only. pub(in crate::x86_64) fn guard_active_exception_enables( - code: &mut Vec, + code: &mut Code, active: u8, features: NumericalFeatures, failures: &mut Vec, @@ -182,12 +160,14 @@ pub(in crate::x86_64) fn guard_active_exception_enables( return; } sign_mask(code, active, target); - code.extend(TEST_EAX_EAX); - let inactive = branch(code, JZ_REL32); - code.extend(TEST_STATE_IMMEDIATE); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(FPCR_EXCEPTION_ENABLE_MASK.to_le_bytes()); - failures.push(branch(code, JNZ_REL32)); - let next = code.len(); - resolve(code, inactive, next); + let mut asm = code.asm(); + asm.test(Size::Dword, Rax, Rax); + let inactive = asm.jcc(Cond::E); + asm.test_imm( + Size::Dword, + Mem::base_disp32(Rdi, core::mem::offset_of!(GuestState, fpcr) as i32), + FPCR_EXCEPTION_ENABLE_MASK as i32, + ); + failures.push(asm.jcc(Cond::Ne).offset()); + asm.bind(inactive); } diff --git a/crates/stela-compiler/src/x86_64/sve/floating/comparison.rs b/crates/stela-compiler/src/x86_64/sve/floating/comparison.rs index 70bbf8c13b..8f37e4e3e2 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/comparison.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/comparison.rs @@ -1,4 +1,7 @@ //! SVE FP comparisons without exceptions; signaling cases use software completion. +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Alu, Code, Rm, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -25,12 +28,6 @@ const PREDICATE_SCRATCH: u8 = CLASSIFICATION_SCRATCH[0]; const CLASSIFICATION_MASKS: [u8; 2] = [6, 7]; const MAGNITUDE_MASK: u8 = CLASSIFICATION_SCRATCH[0]; const EAX_REGISTER: u8 = 0; -const REGISTER_DIRECT: u8 = 0xc0; -const REGISTER_FIELD_SHIFT: u8 = 3; -const CMPPS: &[u8] = &[0x0f, 0xc2]; -const CMPPD: &[u8] = &[0x66, 0x0f, 0xc2]; -const AND_EAX_IMMEDIATE: &[u8] = &[0x25]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; const SIGN_BITS: u8 = 1; #[repr(u8)] @@ -42,7 +39,7 @@ enum Comparison { NotEqual = 4, } -fn magnitudes(code: &mut Vec, format: Format, target: TargetCpu) { +fn magnitudes(code: &mut Code, format: Format, target: TargetCpu) { Host::EqualDword.register(code, MAGNITUDE_MASK, MAGNITUDE_MASK, target); match format { Format::Single => ShiftOpcode::RightDword, @@ -56,7 +53,7 @@ fn magnitudes(code: &mut Vec, format: Format, target: TargetCpu) { /// Operands contain only normals, signed zero or infinity. Return FF/00 lanes. /// Masking inactive lanes and classification belong to the instruction emitter. -fn compare_mask(code: &mut Vec, kind: Kind, format: Format, target: TargetCpu) -> u8 { +fn compare_mask(code: &mut Code, kind: Kind, format: Format, target: TargetCpu) -> u8 { if matches!(kind, Kind::AbsoluteGreaterEqual | Kind::AbsoluteGreater) { magnitudes(code, format, target); } @@ -74,15 +71,22 @@ fn compare_mask(code: &mut Vec, kind: Kind, format: Format, target: TargetCp return LEFT; } }; - code.extend(match format { - Format::Single => CMPPS, - Format::Double => CMPPD, + let mut asm = code.asm(); + match format { + Format::Single => asm.float_compare( + FloatLanes::PackedSingle, + destination, + Rm::Xmm(source), + comparison as u8, + ), + Format::Double => asm.float_compare( + FloatLanes::PackedDouble, + destination, + Rm::Xmm(source), + comparison as u8, + ), Format::Half => unreachable!("native comparison width validated before emission"), - }); - code.extend([ - REGISTER_DIRECT | (destination << REGISTER_FIELD_SHIFT) | source, - comparison as u8, - ]); + } destination } @@ -97,7 +101,7 @@ fn packed_leading_bits(element: ElementSize) -> u32 { /// Accepted host comparisons preserve caller MXCSR without saving/installing it. /// Clobbers RAX/RCX/RDX, host flags and XMM0..7; preserves RDI/R15 and guest NZCV. pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -149,10 +153,13 @@ pub(crate) fn emit( Kind::Equal | Kind::GreaterEqual | Kind::LessEqual | Kind::AbsoluteGreaterEqual ) { Host::ByteSignMask.register(code, EAX_REGISTER, ACTIVE, target); - code.extend(AND_EAX_IMMEDIATE); - code.extend(packed_leading_bits(element).to_le_bytes()); + code.asm().alu_accumulator_imm32( + Alu::And, + Size::Dword, + (packed_leading_bits(element)) as i32, + ); } else { - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); } } else { if let Some(right) = operand.right { @@ -172,8 +179,11 @@ pub(crate) fn emit( let result = compare_mask(code, operand.kind, operand.format, target); Host::And.register(code, result, ACTIVE, target); Host::ByteSignMask.register(code, EAX_REGISTER, result, target); - code.extend(AND_EAX_IMMEDIATE); - code.extend(packed_leading_bits(element).to_le_bytes()); + code.asm().alu_accumulator_imm32( + Alu::And, + Size::Dword, + (packed_leading_bits(element)) as i32, + ); } numerical::stage_predicate_bits16(code, &frame, 0, chunk); } @@ -188,7 +198,7 @@ mod tests { #[test] fn half_refusal_emits_no_frame_or_guard() { - let mut code = vec![0x90]; + let mut code = Code::from(vec![0x90]); let operand = Operand { kind: Kind::Equal, format: Format::Half, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/complex.rs b/crates/stela-compiler/src/x86_64/sve/floating/complex.rs index 047f5d5109..f5b7c445df 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/complex.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/complex.rs @@ -1,4 +1,6 @@ //! SVE FCADD (packed ADD) and FCMLA (FMA3, one rounding per component). +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -15,9 +17,8 @@ use crate::{ read_predicate_mask, }, simd::numerical::{ - ArithmeticOpcode, FusedOpcode, VZEROUPPER, emit_fma, emit_opcode_to, - prepare_vector_input_range, prepare_vector_result_range, rounding_control, - vector_exponent_range, + ArithmeticOpcode, FusedOpcode, emit_fma, emit_opcode_to, prepare_vector_input_range, + prepare_vector_result_range, rounding_control, vector_exponent_range, }, sve::floating::classify::guard_active_exception_enables, }, @@ -31,9 +32,6 @@ const CONSTANT_SCRATCH: u8 = 3; const ADDEND: u8 = 6; const ACTIVE: u8 = 7; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; const REPEAT_LOW_DWORD: u8 = 0; const SWAP_SINGLE_COMPONENTS: u8 = 0xb1; const SWAP_DOUBLE_COMPONENTS: u8 = 0x4e; @@ -47,13 +45,6 @@ const DOUBLE_COMPONENT_BYTES: u8 = size_of::() as u8; const MXCSR_PRECISION: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_PRECISION - 1; const MXCSR_TO_FPSR_INEXACT_SHIFT: u8 = 1; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; #[derive(Clone, Copy)] enum Operation { @@ -111,21 +102,24 @@ fn admitted(operand: Operand, target: TargetCpu) -> Option { } } -fn reject(code: &mut Vec, failures: &mut Vec) { - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); +fn reject(code: &mut Code, failures: &mut Vec) { + failures.push(code.asm().jcc(Cond::Ne).offset()); } -fn shuffle(code: &mut Vec, register: u8, order: u8, target: TargetCpu) { - Host::ShuffleDword.register(code, register, register, target); - code.push(order); +fn shuffle(code: &mut Code, register: u8, order: u8, target: TargetCpu) { + code.asm().simd_imm( + Host::ShuffleDword, + register, + Rm::Xmm(register), + order, + target, + ); } /// Rotate M before active-lane masking; an active output may read an inactive /// partner input. NaN sign rules remain with fallback because active NaNs fail /// the following integer exponent guards before any architectural commit. -fn rotate_right(code: &mut Vec, format: Format, rotation: Rotation, target: TargetCpu) { +fn rotate_right(code: &mut Code, format: Format, rotation: Rotation, target: TargetCpu) { if matches!(rotation, Rotation::Degrees90 | Rotation::Degrees270) { shuffle( code, @@ -167,7 +161,7 @@ fn rotate_right(code: &mut Vec, format: Format, rotation: Rotation, target: Host::Xor.register(code, RIGHT, MASK_SCRATCH, target); } -fn selected_left(code: &mut Vec, format: Format, rotation: Rotation, target: TargetCpu) { +fn selected_left(code: &mut Code, format: Format, rotation: Rotation, target: TargetCpu) { let imaginary = matches!(rotation, Rotation::Degrees90 | Rotation::Degrees270); let order = match (format, imaginary) { (Format::Single, false) => DUPLICATE_SINGLE_REAL, @@ -180,7 +174,7 @@ fn selected_left(code: &mut Vec, format: Format, rotation: Rotation, target: } fn load_right( - code: &mut Vec, + code: &mut Code, source: Source, chunk: usize, length: VectorLength, @@ -206,7 +200,7 @@ fn load_right( } /// Inactive FCADD uses1+1; inactive FCMLA uses2+1*1, both exact normals. -fn benign_inactive(code: &mut Vec, format: Format, input: u8, target: TargetCpu) { +fn benign_inactive(code: &mut Code, format: Format, input: u8, target: TargetCpu) { let increment = if input == ADDEND { BENIGN_ADDEND_INCREMENT } else { @@ -214,14 +208,12 @@ fn benign_inactive(code: &mut Vec, format: Format, input: u8, target: Target }; let bits = u64::from(format.exponent_bias() + increment) << format.fraction_bits(); if format == Format::Single { - code.push(MOV_EAX_IMMEDIATE); - code.extend((bits as u32).to_le_bytes()); + code.asm().mov_imm32(Rax, bits as u32); } else { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(bits.to_le_bytes()); + code.asm().mov_imm64(Rax, bits); } - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (CONSTANT_SCRATCH << MODRM_REGISTER_SHIFT) | GPR_RAX); + code.asm() + .simd(Host::MoveGprQword, CONSTANT_SCRATCH, Rax, target); if format == Format::Single { shuffle(code, CONSTANT_SCRATCH, REPEAT_LOW_DWORD, target); } else { @@ -237,7 +229,7 @@ fn benign_inactive(code: &mut Vec, format: Format, input: u8, target: Target /// normal; indexed half precision and FCMLA without FMA return false without /// emitting. RAX/RCX/RDX, flags and XMM0-7 are clobbered. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -325,7 +317,7 @@ pub(in crate::x86_64) fn emit( FusedOpcode::MultiplyAdd, target, ); - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } else { emit_opcode_to( code, @@ -348,14 +340,13 @@ pub(in crate::x86_64) fn emit( numerical::stage_vector_chunk(code, &frame, OUTPUT_SLOT, chunk, LEFT, target); } numerical::capture_status(code, &frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_OTHER_STATUS as i32); reject(code, &mut failures); - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_PRECISION.to_le_bytes()); - code.extend(SHR_EAX_IMMEDIATE); - code.push(MXCSR_TO_FPSR_INEXACT_SHIFT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_PRECISION as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, MXCSR_TO_FPSR_INEXACT_SHIFT); numerical::add_fpsr(code, &frame); numerical::finish(code, &frame, &failures, pc, target); Ok(true) diff --git a/crates/stela-compiler/src/x86_64/sve/floating/conversion.rs b/crates/stela-compiler/src/x86_64/sve/floating/conversion.rs index d2be0ce60b..1063487293 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/conversion.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/conversion.rs @@ -1,5 +1,5 @@ //! SVE predicated conversions. -use alloc::vec::Vec; +use crate::x86_64::asm::Code; mod bfloat; mod double_narrowing; mod half_integer; @@ -21,7 +21,7 @@ use crate::{ /// Preserve existing Single-to-Double mappings and use the verified baseline /// for integer conversions. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/conversion/bfloat.rs b/crates/stela-compiler/src/x86_64/sve/floating/conversion/bfloat.rs index f32349e779..09207f56e7 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/conversion/bfloat.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/conversion/bfloat.rs @@ -1,4 +1,6 @@ //! SVE BFCVT and BFCVTNT through integer rounding. +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Code, Cond, Rm, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -26,19 +28,12 @@ const SOURCE: u8 = 1; const ACTIVE: u8 = 6; const TEMPORARY: u8 = 7; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOVD_XMM0_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xc0]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; const REPEAT_LOW_DWORD: u8 = 0; const BFLOAT_SHIFT: u8 = BFLOAT16_TO_SINGLE_SHIFT as u8; const SINGLE_ONE: u32 = Format::Single.exponent_bias() << Format::Single.fraction_bits(); fn guard_enables( - code: &mut Vec, + code: &mut Code, features: NumericalFeatures, failures: &mut Vec, target: TargetCpu, @@ -46,22 +41,18 @@ fn guard_enables( if !features.full_a64() { return; } - Host::ByteSignMask.append(code, target); - code.push(MODRM_REGISTER | (GPR_RAX << MODRM_REGISTER_SHIFT) | ACTIVE); - code.extend(TEST_EAX_EAX); - code.extend(JZ_REL32); - let inactive = code.len(); - code.extend(0_i32.to_le_bytes()); + let mut asm = code.asm(); + asm.simd_to_gpr(Host::ByteSignMask, Rax, ACTIVE, target); + asm.test(Size::Dword, Rax, Rax); + let inactive = asm.jcc(Cond::E); // Unlike precision conversion, BF AH1 suppresses numerical exceptions and // retained enables. Reuse the mature BF policy after the active-lane test. guard_conversion_enables(code, failures); - let next = inactive + size_of::(); - let relative = i32::try_from(code.len() - next).expect("bounded BF enable guard"); - code[inactive..next].copy_from_slice(&relative.to_le_bytes()); + code.asm().bind(inactive); } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -96,11 +87,16 @@ pub(in crate::x86_64) fn emit( load_z_chunk(code, operand.source, chunk, SOURCE, length, target); Host::And.register(code, SOURCE, ACTIVE, target); // Neutralize inactive poison to exactly BF16 1.0 before normal guards. - code.push(MOV_EAX_IMMEDIATE); - code.extend(SINGLE_ONE.to_le_bytes()); - code.extend(MOVD_XMM0_EAX); - Host::ShuffleDword.register(code, RESULT, RESULT, target); - code.push(REPEAT_LOW_DWORD); + let mut asm = code.asm(); + asm.mov_imm32(Rax, SINGLE_ONE); + asm.movd_to_xmm(0, Rax); + code.asm().simd_imm( + Host::ShuffleDword, + RESULT, + Rm::Xmm(RESULT), + REPEAT_LOW_DWORD, + target, + ); Host::MoveAligned.register(code, TEMPORARY, ACTIVE, target); Host::AndNot.register(code, TEMPORARY, RESULT, target); Host::Or.register(code, SOURCE, TEMPORARY, target); diff --git a/crates/stela-compiler/src/x86_64/sve/floating/conversion/double_narrowing.rs b/crates/stela-compiler/src/x86_64/sve/floating/conversion/double_narrowing.rs index 9715f688be..9087f3ee62 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/conversion/double_narrowing.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/conversion/double_narrowing.rs @@ -1,4 +1,6 @@ //! SVE double-to-single FCVT and round-to-odd FCVTX on normal values. +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -30,19 +32,6 @@ const CLASSIFICATION_SCRATCH: [u8; 3] = [SCRATCH, 6, 7]; const MAXIMUM_EXPONENT: u8 = 6; const ONE_VECTOR: u8 = 7; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const GPR_RCX: u8 = 1; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MOV_RCX_IMMEDIATE: &[u8] = &[0x48, 0xb9]; -const MOV_EAX_IMMEDIATE: &[u8] = &[0xb8]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const AND_EAX_IMMEDIATE: &[u8] = &[0x25]; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const CMP_EAX_IMMEDIATE8: &[u8] = &[0x83, 0xf8]; -const SHR_EAX_IMMEDIATE8: &[u8] = &[0xc1, 0xe8]; -const JNE_REL32: &[u8] = &[0x0f, 0x85]; -const CVTPD2PS_XMM0_XMM1: &[u8] = &[0x66, 0x0f, 0x5a, 0xc1]; const DOUBLE_ONE: u64 = (Format::Double.exponent_bias() as u64) << Format::Double.fraction_bits(); const SIGN_BITS: u8 = 1; const SINGLE_EXPONENT_BITS: u8 = @@ -60,17 +49,13 @@ const HOST_TO_GUEST_INEXACT_SHIFT: u8 = const LOW_SINGLE_IN_QWORDS: u8 = 0xd8; // dword [0,2,1,3], with original upper64 zero. const TOP_SINGLE_IN_QWORDS: u8 = 0x72; // dword [2,0,3,1]. -fn failure(code: &mut Vec, failures: &mut Vec) { - code.extend(JNE_REL32); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); +fn failure(code: &mut Code, failures: &mut Vec) { + failures.push(code.asm().jcc(Cond::Ne).offset()); } -fn neutralize_inactive(code: &mut Vec, target: TargetCpu) { - code.extend(MOV_RCX_IMMEDIATE); - code.extend(DOUBLE_ONE.to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (RESULT << MODRM_REGISTER_SHIFT) | GPR_RCX); +fn neutralize_inactive(code: &mut Code, target: TargetCpu) { + code.asm().mov_imm64(Rcx, DOUBLE_ONE); + code.asm().simd(Host::MoveGprQword, RESULT, Rcx, target); Host::UnpackLowQword.register(code, RESULT, RESULT, target); Host::MoveAligned.register(code, SCRATCH, ACTIVE, target); Host::AndNot.register(code, SCRATCH, RESULT, target); @@ -81,7 +66,7 @@ fn neutralize_inactive(code: &mut Vec, target: TargetCpu) { /// The mature conservative result range is exponent2..254. This excludes the /// minimum-normal binade as well as zero/tiny/Inf/NaN, preventing before/after /// rounding tininess differences from being hidden by host status alone. -fn guard_result(code: &mut Vec, failures: &mut Vec, target: TargetCpu) { +fn guard_result(code: &mut Code, failures: &mut Vec, target: TargetCpu) { Host::MoveAligned.register(code, SCRATCH, RESULT, target); ShiftOpcode::LeftDword.emit(code, SCRATCH, SIGN_BITS); ShiftOpcode::RightDword.emit(code, SCRATCH, SINGLE_EXPONENT_TO_BOTTOM); @@ -92,17 +77,21 @@ fn guard_result(code: &mut Vec, failures: &mut Vec, target: TargetCpu ShiftOpcode::RightDword.emit(code, ONE_VECTOR, u32::BITS as u8 - SIGN_BITS); Host::GreaterDword.register(code, SCRATCH, ONE_VECTOR, target); Host::And.register(code, SCRATCH, MAXIMUM_EXPONENT, target); - Host::DwordSignMask.register(code, GPR_RAX, SCRATCH, target); + code.asm() + .simd_to_gpr(Host::DwordSignMask, Rax, SCRATCH, target); // CVTPD2PS sets the upper64 bits to zero. Only its two converted lanes count. - code.extend(AND_EAX_IMMEDIATE); - code.extend(u32::from(LOW_TWO_DWORD_MASK).to_le_bytes()); - code.extend(CMP_EAX_IMMEDIATE8); - code.push(LOW_TWO_DWORD_MASK); + let mut asm = code.asm(); + asm.alu_accumulator_imm32( + Alu::And, + Size::Dword, + (u32::from(LOW_TWO_DWORD_MASK)) as i32, + ); + asm.alu_imm8(Alu::Cmp, Size::Dword, Rax, LOW_TWO_DWORD_MASK as i8); failure(code, failures); } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -125,8 +114,7 @@ pub(in crate::x86_64) fn emit( Environment::PrivateMxcsr, )?; if rounding == PrecisionRounding::ToOdd { - code.extend(MOV_EAX_IMMEDIATE); - code.extend(MXCSR_TOWARD_ZERO.to_le_bytes()); + code.asm().mov_imm32(Rax, MXCSR_TOWARD_ZERO); } else { rounding_control(code); } @@ -157,27 +145,31 @@ pub(in crate::x86_64) fn emit( target, ); numerical::clear_status(code, &frame); - code.extend(CVTPD2PS_XMM0_XMM1); + code.asm().cvtpd2ps(0, Rm::Xmm(1)); numerical::capture_status(code, &frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_REJECTED_STATUS.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_REJECTED_STATUS as i32); failure(code, &mut failures); - code.extend(MOV_EAX_ECX); - code.extend(AND_EAX_IMMEDIATE); - code.extend(MXCSR_PRECISION.to_le_bytes()); - code.extend(SHR_EAX_IMMEDIATE8); - code.push(HOST_TO_GUEST_INEXACT_SHIFT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_PRECISION as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, HOST_TO_GUEST_INEXACT_SHIFT); numerical::add_fpsr(code, &frame); guard_result(code, &mut failures, target); if rounding == PrecisionRounding::ToOdd { jam_odd_pair(code, ONE_VECTOR); } - Host::ShuffleDword.register(code, RESULT, RESULT, target); - code.push(if placement == Placement::UpperDestination { - TOP_SINGLE_IN_QWORDS - } else { - LOW_SINGLE_IN_QWORDS - }); + code.asm().simd_imm( + Host::ShuffleDword, + RESULT, + Rm::Xmm(RESULT), + if placement == Placement::UpperDestination { + TOP_SINGLE_IN_QWORDS + } else { + LOW_SINGLE_IN_QWORDS + }, + target, + ); // Neutral inactive one results are removed before top-slot mask shaping. Host::And.register(code, RESULT, ACTIVE, target); if placement == Placement::UpperDestination { diff --git a/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_integer.rs b/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_integer.rs index 5d3d411e1b..198c4b1e4b 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_integer.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_integer.rs @@ -1,4 +1,7 @@ //! SVE conversions between half precision and integers. +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use super::half_widening::{guard_normal_half_fields, normal_half_to_single_fields}; use crate::{ @@ -24,11 +27,7 @@ const SIGN: u8 = GUARD_SCRATCH[0]; const SCRATCH: u8 = GUARD_SCRATCH[1]; const REJECTIONS: u8 = GUARD_SCRATCH[2]; const INTEGER_FLOAT: u8 = 6; -const EAX: u8 = 0; -const RCX: u8 = 1; const REPEAT_LOW_DWORD: u8 = 0; -const REGISTER_DIRECT: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; const HALF_BITS: u8 = u16::BITS as u8; const HALF_MAGNITUDE_TO_TOP: u8 = u32::BITS as u8 - HALF_BITS + 1; const DWORD_SIGN_BIT: u8 = u32::BITS as u8 - 1; @@ -42,64 +41,40 @@ const SIGNED_HALF_LIMIT_BITS: u32 = (Format::Half.exponent_bias() + u16::BITS - 1) << Format::Half.fraction_bits(); const MAXIMUM_FINITE_HALF_INTEGER: u32 = 65_504; pub(super) const USE_MXCSR_ROUNDING: u8 = 1 << 2; -const MOV_ECX_IMMEDIATE: &[u8] = &[0xb9]; -const CVTTPS2DQ: &[u8] = &[0xf3, 0x0f, 0x5b]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -const JA_REL32: &[u8] = &[0x0f, 0x87]; -const MOVSX_RAX_AX: &[u8] = &[0x48, 0x0f, 0xbf, 0xc0]; -const MOVSXD_RAX_EAX: &[u8] = &[0x48, 0x63, 0xc0]; -const MOVZX_EAX_AX: &[u8] = &[0x0f, 0xb7, 0xc0]; -const MOV_EAX_EAX: &[u8] = &[0x89, 0xc0]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const SAR_RDX_IMMEDIATE: &[u8] = &[0x48, 0xc1, 0xfa]; -const XOR_RAX_RDX: &[u8] = &[0x48, 0x31, 0xd0]; -const SUB_RAX_RDX: &[u8] = &[0x48, 0x29, 0xd0]; -const XOR_EDX_EDX: &[u8] = &[0x31, 0xd2]; -const CMP_RAX_IMMEDIATE: &[u8] = &[0x48, 0x3d]; -const CVTSI2SD_XMM6_RAX: &[u8] = &[0xf2, 0x48, 0x0f, 0x2a, 0xf0]; -const CVTSI2SS_XMM6_RAX: &[u8] = &[0xf3, 0x48, 0x0f, 0x2a, 0xf0]; -const MOVQ_RCX_XMM6: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xf1]; -const MOVD_ECX_XMM6: &[u8] = &[0x66, 0x0f, 0x7e, 0xf1]; -const SHL_RDX_IMMEDIATE: &[u8] = &[0x48, 0xc1, 0xe2]; -const SHL_EDX_IMMEDIATE: &[u8] = &[0xc1, 0xe2]; -const OR_RCX_RDX: &[u8] = &[0x48, 0x09, 0xd1]; -const OR_ECX_EDX: &[u8] = &[0x09, 0xd1]; -const MOVQ_XMM6_RCX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xf1]; -const MOVD_XMM6_ECX: &[u8] = &[0x66, 0x0f, 0x6e, 0xf1]; -const MOVD_EAX_XMM0: &[u8] = &[0x66, 0x0f, 0x7e, 0xc0]; -const AND_EAX_IMMEDIATE: &[u8] = &[0x25]; -fn broadcast(code: &mut Vec, register: u8, value: u32, target: TargetCpu) { - code.extend(MOV_ECX_IMMEDIATE); - code.extend(value.to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(REGISTER_DIRECT | (register << REGISTER_SHIFT) | RCX); - Host::ShuffleDword.register(code, register, register, target); - code.push(REPEAT_LOW_DWORD); +fn broadcast(code: &mut Code, register: u8, value: u32, target: TargetCpu) { + let mut asm = code.asm(); + asm.mov_imm32(Rcx, value); + asm.simd(Host::MoveGprQword, register, Rcx, target); + asm.simd_imm( + Host::ShuffleDword, + register, + Rm::Xmm(register), + REPEAT_LOW_DWORD, + target, + ); } -fn failure(code: &mut Vec, opcode: &[u8], failures: &mut Vec) { - code.extend(opcode); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); +fn failure(code: &mut Code, condition: Cond, failures: &mut Vec) { + failures.push(code.asm().jcc(condition).offset()); } -fn reject_mask(code: &mut Vec, mask: u8, failures: &mut Vec, target: TargetCpu) { - Host::ByteSignMask.register(code, EAX, mask, target); - code.extend(TEST_EAX_EAX); - failure(code, JNZ_REL32, failures); +fn reject_mask(code: &mut Code, mask: u8, failures: &mut Vec, target: TargetCpu) { + let mut asm = code.asm(); + asm.simd_to_gpr(Host::ByteSignMask, Rax, mask, target); + asm.test(Size::Dword, Rax, Rax); + failure(code, Cond::Ne, failures); } /// Prepare invariant normal-Half guard, field projection and neutral input. /// Preserved by to_integer_words; caller may hoist once per guest instruction. -pub(crate) fn prepare_to_integer(code: &mut Vec, target: TargetCpu) { +pub(crate) fn prepare_to_integer(code: &mut Code, target: TargetCpu) { broadcast(code, MAXIMUM_EXPONENT, HALF_EXPONENT_MAX, target); broadcast(code, SINGLE_BIAS, HALF_TO_SINGLE_BIAS, target); broadcast(code, HALF_ONE, HALF_ONE_BITS, target); } -fn signed_half_range(code: &mut Vec, failures: &mut Vec, target: TargetCpu) { +fn signed_half_range(code: &mut Code, failures: &mut Vec, target: TargetCpu) { Host::MoveAligned.register(code, SIGN, INPUT, target); ShiftOpcode::LeftDword.emit(code, SIGN, HALF_MAGNITUDE_TO_TOP); ShiftOpcode::RightDword.emit(code, SIGN, HALF_MAGNITUDE_TO_TOP); @@ -123,7 +98,7 @@ fn signed_half_range(code: &mut Vec, failures: &mut Vec, target: Targ /// The caller checks for F16C first. Host PE is the only status accepted, /// mapped to guest inexact by the caller. pub(crate) fn to_integer_words( - code: &mut Vec, + code: &mut Code, destination: IntegerFormat, f16c: bool, failures: &mut Vec, @@ -166,18 +141,18 @@ pub(crate) fn to_integer_words( // and sanitized inactive zero before host conversion, preventing false IXC. Host::AndNot.register(code, ZERO_LANES, INPUT, target); Host::MoveAligned.register(code, INPUT, ZERO_LANES, target); - code.extend(CVTTPS2DQ); - code.push(REGISTER_DIRECT | (INPUT << REGISTER_SHIFT) | INPUT); + code.asm().cvttps2dq(INPUT, Rm::Xmm(INPUT)); } -fn normalize_integer(code: &mut Vec, source: IntegerFormat) { - code.extend(match (source.width, source.signed) { - (IntegerWidth::Bits16, true) => MOVSX_RAX_AX, - (IntegerWidth::Bits16, false) => MOVZX_EAX_AX, - (IntegerWidth::Bits32, true) => MOVSXD_RAX_EAX, - (IntegerWidth::Bits32, false) => MOV_EAX_EAX, - (IntegerWidth::Bits64, _) => &[], - }); +fn normalize_integer(code: &mut Code, source: IntegerFormat) { + let mut asm = code.asm(); + match (source.width, source.signed) { + (IntegerWidth::Bits16, true) => asm.movsx(Size::Qword, Rax, Size::Word, Rax), + (IntegerWidth::Bits16, false) => asm.movzx(Size::Dword, Rax, Size::Word, Rax), + (IntegerWidth::Bits32, true) => asm.movsxd(Rax, Rax), + (IntegerWidth::Bits32, false) => asm.mov(Size::Dword, Rax, Rax), + (IntegerWidth::Bits64, _) => {} + } } /// Convert one small signed/unsigned integer in RAX to raw IEEE Half in EAX. @@ -190,7 +165,7 @@ fn normalize_integer(code: &mut Vec, source: IntegerFormat) { /// No frame/store/commit/exit; host PE remains a separate pending channel. /// Clobbers XMM0/6, RAX/RCX/RDX/R9/R10 and flags; preserves other registers. pub(crate) fn from_integer_lane( - code: &mut Vec, + code: &mut Code, source: IntegerFormat, f16c: bool, failures: &mut Vec, @@ -198,38 +173,43 @@ pub(crate) fn from_integer_lane( ) { normalize_integer(code, source); if source.signed { - code.extend(MOV_RDX_RAX); - code.extend(SAR_RDX_IMMEDIATE); - code.push(QWORD_SIGN_BIT); - code.extend(XOR_RAX_RDX); - code.extend(SUB_RAX_RDX); + let mut asm = code.asm(); + asm.mov(Size::Qword, Rdx, Rax); + asm.shift_imm(ShiftOp::Sar, Size::Qword, Rdx, QWORD_SIGN_BIT); + asm.alu(Alu::Xor, Size::Qword, Rax, Rdx); + asm.alu(Alu::Sub, Size::Qword, Rax, Rdx); } else { - code.extend(XOR_EDX_EDX); + code.asm().alu(Alu::Xor, Size::Dword, Rdx, Rdx); } - code.extend(CMP_RAX_IMMEDIATE); - code.extend(MAXIMUM_FINITE_HALF_INTEGER.to_le_bytes()); - failure(code, JA_REL32, failures); + code.asm() + .alu_accumulator_imm32(Alu::Cmp, Size::Qword, MAXIMUM_FINITE_HALF_INTEGER as i32); + failure(code, Cond::A, failures); Host::Xor.register(code, INTEGER_FLOAT, INTEGER_FLOAT, target); if f16c { - code.extend(CVTSI2SS_XMM6_RAX); - code.extend(MOVD_ECX_XMM6); - code.extend(SHL_EDX_IMMEDIATE); - code.push(DWORD_SIGN_BIT); - code.extend(OR_ECX_EDX); - code.extend(MOVD_XMM6_ECX); + let mut asm = code.asm(); + asm.cvtsi2float(FloatLanes::ScalarSingle, Size::Qword, 6, Rax); + asm.movd_from_xmm(Rcx, 6); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rdx, DWORD_SIGN_BIT); + asm.alu(Alu::Or, Size::Dword, Rcx, Rdx); + asm.movd_to_xmm(6, Rcx); // VCVTPS2PH source is ModRM.reg; destination is ModRM.r/m. - Host::ConvertSingleToHalf.register(code, INTEGER_FLOAT, INPUT, target); - code.push(USE_MXCSR_ROUNDING); - code.extend(MOVD_EAX_XMM0); - code.extend(AND_EAX_IMMEDIATE); - code.extend(u32::from(u16::MAX).to_le_bytes()); + code.asm().simd_imm( + Host::ConvertSingleToHalf, + INTEGER_FLOAT, + Rm::Xmm(INPUT), + USE_MXCSR_ROUNDING, + target, + ); + let mut asm = code.asm(); + asm.movd_from_xmm(Rax, 0); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, (u32::from(u16::MAX)) as i32); } else { - code.extend(CVTSI2SD_XMM6_RAX); - code.extend(MOVQ_RCX_XMM6); - code.extend(SHL_RDX_IMMEDIATE); - code.push(QWORD_SIGN_BIT); - code.extend(OR_RCX_RDX); - code.extend(MOVQ_XMM6_RCX); + let mut asm = code.asm(); + asm.cvtsi2float(FloatLanes::ScalarDouble, Size::Qword, 6, Rax); + asm.movq_from_xmm(Rcx, 6); + asm.shift_imm(ShiftOp::Shl, Size::Qword, Rdx, QWORD_SIGN_BIT); + asm.alu(Alu::Or, Size::Qword, Rcx, Rdx); + asm.movq_to_xmm(6, Rcx); half::emit_normal_or_zero(code, failures); } } diff --git a/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_narrowing.rs b/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_narrowing.rs index add4b47201..5a3d0b4766 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_narrowing.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_narrowing.rs @@ -1,4 +1,6 @@ //! SVE conversions narrowing to half precision. +use crate::x86_64::asm::Gpr::{R10, Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Rm, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -25,50 +27,17 @@ const SCRATCH: u8 = 2; const PACK_INPUT: u8 = 6; const ACTIVE: u8 = 7; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const GPR_RCX: u8 = 1; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MOVD_EAX_XMM2: &[u8] = &[0x66, 0x0f, 0x7e, 0xd0]; -const MOV_EAX_R10D: &[u8] = &[0x44, 0x89, 0xd0]; -const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; -const XOR_ECX_ECX: &[u8] = &[0x31, 0xc9]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const TEST_ECX_ECX: &[u8] = &[0x85, 0xc9]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -const PINSRW: &[u8] = &[0x66, 0x0f, 0xc4]; -const CVTSS2SD_XMM6_XMM6: &[u8] = &[0xf3, 0x0f, 0x5a, 0xf6]; const HALF_BYTES: usize = size_of::(); const BITS_PER_BYTE: u32 = u8::BITS; -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement -} - -fn resolve(code: &mut [u8], displacement: usize, end: usize) { - let next = displacement + size_of::(); - let relative = i64::try_from(end).expect("bounded Half instruction") - - i64::try_from(next).expect("bounded Half instruction"); - code[displacement..next].copy_from_slice( - &i32::try_from(relative) - .expect("bounded Half branch") - .to_le_bytes(), - ); -} - -fn insert_half(code: &mut Vec, gpr: u8, byte_offset: usize) { +fn insert_half(code: &mut Code, gpr: Gpr, byte_offset: usize) { assert!(byte_offset < VECTOR_CHUNK_BYTES && byte_offset.is_multiple_of(HALF_BYTES)); - code.extend(PINSRW); - code.push(MODRM_REGISTER | (RESULT << MODRM_REGISTER_SHIFT) | gpr); - code.push((byte_offset / HALF_BYTES) as u8); + code.asm() + .pinsrw(RESULT, gpr, (byte_offset / HALF_BYTES) as u8); } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -115,15 +84,16 @@ pub(in crate::x86_64) fn emit( guard_active_exception_enables(code, ACTIVE, features, &mut failures, target); load_z_chunk(code, operand.source, chunk, SOURCE, length, target); load_z_chunk(code, operand.destination, chunk, RESULT, length, target); - code.extend(XOR_R10D_R10D); + code.asm().alu(Alu::Xor, Size::Dword, R10, R10); for slot in (0..VECTOR_CHUNK_BYTES).step_by(slot_bytes) { Host::MoveAligned.register(code, SCRATCH, ACTIVE, target); if slot != 0 { ShiftOpcode::RightBytes.emit(code, SCRATCH, slot as u8); } - code.extend(MOVD_EAX_XMM2); - code.extend(TEST_EAX_EAX); - let inactive = branch(code, JZ_REL32); + let mut asm = code.asm(); + asm.movd_from_xmm(Rax, SCRATCH); + asm.test(Size::Dword, Rax, Rax); + let inactive = asm.jcc(Cond::E); Host::MoveAligned.register(code, PACK_INPUT, SOURCE, target); if slot != 0 { ShiftOpcode::RightBytes.emit(code, PACK_INPUT, slot as u8); @@ -133,10 +103,11 @@ pub(in crate::x86_64) fn emit( // inputs. Any widening status takes whole completion before // packing; no intermediate status is mapped to guest FPSR. numerical::clear_status(code, &frame); - code.extend(CVTSS2SD_XMM6_XMM6); + code.asm().cvtss2sd(PACK_INPUT, Rm::Xmm(PACK_INPUT)); numerical::capture_status(code, &frame); - code.extend(TEST_ECX_ECX); - failures.push(branch(code, JNZ_REL32)); + let mut asm = code.asm(); + asm.test(Size::Dword, Rcx, Rcx); + failures.push(asm.jcc(Cond::Ne).offset()); } emit_normal_or_zero(code, &mut failures); let destination_offset = if placement == Placement::UpperDestination { @@ -144,20 +115,19 @@ pub(in crate::x86_64) fn emit( } else { 0 }; - insert_half(code, GPR_RAX, slot + destination_offset); + insert_half(code, Rax, slot + destination_offset); if placement == Placement::Low { // Ordinary precision narrowing zero-extends the whole source // slot. Top narrowing replaces exactly its high Half instead. - code.extend(XOR_ECX_ECX); + code.asm().alu(Alu::Xor, Size::Dword, Rcx, Rcx); for upper in (slot + HALF_BYTES..slot + slot_bytes).step_by(HALF_BYTES) { - insert_half(code, GPR_RCX, upper); + insert_half(code, Rcx, upper); } } - let end = code.len(); - resolve(code, inactive, end); + code.asm().bind(inactive); } // Consume private IXC before the next predicate/access helper reload. - code.extend(MOV_EAX_R10D); + code.asm().mov(Size::Dword, Rax, R10); numerical::add_fpsr(code, &frame); numerical::stage_vector_chunk(code, &frame, OUTPUT_SLOT, chunk, RESULT, target); } diff --git a/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_widening.rs b/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_widening.rs index 525b8aec4f..14d1c934b5 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_widening.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/conversion/half_widening.rs @@ -1,4 +1,6 @@ //! SVE half-precision widening of normal values, without host FP controls. +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, @@ -28,14 +30,6 @@ const VALIDITY: u8 = 5; const SINGLE_BIAS: u8 = 6; const INACTIVE_HALF_ONE: u8 = 7; const OUTPUT_SLOT: usize = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const GPR_RCX: u8 = 1; -const GPR_RAX: u8 = 0; -const MOV_ECX_IMMEDIATE: &[u8] = &[0xb9]; -const CMP_EAX_IMMEDIATE8: &[u8] = &[0x83, 0xf8]; -const JNE_REL32: &[u8] = &[0x0f, 0x85]; -const CVTPS2PD_XMM0_XMM0: &[u8] = &[0x0f, 0x5a, 0xc0]; const REPEAT_DWORD: u8 = 0; const COMPACT_LOW_QWORD_DWORDS: u8 = 0x88; const DWORD_SIGN_POSITION: u8 = u32::BITS as u8 - 1; @@ -51,20 +45,23 @@ const HALF_TO_SINGLE_BIAS: u32 = (Format::Single.exponent_bias() - Format::Half. const HALF_ONE: u32 = Format::Half.exponent_bias() << Format::Half.fraction_bits(); const ALL_DWORDS_NORMAL: u8 = (1 << (u128::BITS / u32::BITS)) - 1; -fn broadcast(code: &mut Vec, register: u8, value: u32, target: TargetCpu) { - code.extend(MOV_ECX_IMMEDIATE); - code.extend(value.to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (register << MODRM_REGISTER_SHIFT) | GPR_RCX); - Host::ShuffleDword.register(code, register, register, target); - code.push(REPEAT_DWORD); +fn broadcast(code: &mut Code, register: u8, value: u32, target: TargetCpu) { + code.asm().mov_imm32(Rcx, value); + code.asm().simd(Host::MoveGprQword, register, Rcx, target); + code.asm().simd_imm( + Host::ShuffleDword, + register, + Rm::Xmm(register), + REPEAT_DWORD, + target, + ); } /// Preserve four dword-low16 inputs and the repeated31 exponent constant; /// clobber three distinct scratch XMMs, EAX and flags. Append a shared-finish /// failure offset for any exponent outside1..30, with no frame/state effects. pub(in crate::x86_64) fn guard_normal_half_fields( - code: &mut Vec, + code: &mut Code, input: u8, maximum_exponent: u8, scratch: [u8; 3], @@ -85,12 +82,11 @@ pub(in crate::x86_64) fn guard_normal_half_fields( Host::Xor.register(code, zero, zero, target); Host::GreaterDword.register(code, exponent, zero, target); Host::And.register(code, exponent, validity, target); - Host::DwordSignMask.register(code, GPR_RAX, exponent, target); - code.extend(CMP_EAX_IMMEDIATE8); - code.push(ALL_DWORDS_NORMAL); - code.extend(JNE_REL32); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); + code.asm() + .simd_to_gpr(Host::DwordSignMask, Rax, exponent, target); + code.asm() + .alu_imm8(Alu::Cmp, Size::Dword, Rax, ALL_DWORDS_NORMAL as i8); + failures.push(code.asm().jcc(Cond::Ne).offset()); } /// Compute-only extraction of the mature SIMD precision widening projection. @@ -98,7 +94,7 @@ pub(in crate::x86_64) fn guard_normal_half_fields( /// Output: four exact Single encodings. `bias` already holds the repeated H→S /// exponent-bias difference. No frame/state/rounding/status/commit operations. pub(in crate::x86_64) fn normal_half_to_single_fields( - code: &mut Vec, + code: &mut Code, input: u8, sign: u8, bias: u8, @@ -116,7 +112,7 @@ pub(in crate::x86_64) fn normal_half_to_single_fields( } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -167,8 +163,13 @@ pub(in crate::x86_64) fn emit( guard_active_exception_enables(code, ACTIVE, features, &mut failures, target); load_z_chunk(code, operand.source, chunk, RESULT, length, target); if destination == Format::Double { - Host::ShuffleDword.register(code, RESULT, RESULT, target); - code.push(COMPACT_LOW_QWORD_DWORDS); + code.asm().simd_imm( + Host::ShuffleDword, + RESULT, + Rm::Xmm(RESULT), + COMPACT_LOW_QWORD_DWORDS, + target, + ); } if placement == Placement::UpperSource { ShiftOpcode::RightDword.emit(code, RESULT, HALF_BITS); @@ -178,8 +179,13 @@ pub(in crate::x86_64) fn emit( } Host::MoveAligned.register(code, SCRATCH, ACTIVE, target); if destination == Format::Double { - Host::ShuffleDword.register(code, SCRATCH, SCRATCH, target); - code.push(COMPACT_LOW_QWORD_DWORDS); + code.asm().simd_imm( + Host::ShuffleDword, + SCRATCH, + Rm::Xmm(SCRATCH), + COMPACT_LOW_QWORD_DWORDS, + target, + ); } // Neutralize inactive values before the normal-only guard. Their exact // one results are removed again by the architectural destination mask. @@ -196,7 +202,7 @@ pub(in crate::x86_64) fn emit( ); normal_half_to_single_fields(code, RESULT, SCRATCH, SINGLE_BIAS, target); if destination == Format::Double { - code.extend(CVTPS2PD_XMM0_XMM0); + code.asm().cvtps2pd(0, Rm::Xmm(0)); } load_z_chunk( code, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/conversion/integer.rs b/crates/stela-compiler/src/x86_64/sve/floating/conversion/integer.rs index 7672665f6a..936c70155f 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/conversion/integer.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/conversion/integer.rs @@ -1,4 +1,7 @@ //! SVE conversions between single/double and integers. +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::Gpr::{R8, R10, Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use super::{half_integer, unsigned64}; use alloc::vec::Vec; @@ -52,37 +55,7 @@ const SIGNED_DWORD_SIGN_SHIFT: u8 = u32::BITS as u8 - 1; const UNSIGNED_HALF_PACK_BIAS: u32 = 1 << (u16::BITS - 1); const UNSIGNED_HALF_PACK_SIGN_BITS: u32 = UNSIGNED_HALF_PACK_BIAS | (UNSIGNED_HALF_PACK_BIAS << u16::BITS); -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const SSE_ESCAPE: u8 = 0x0f; -const SINGLE_PREFIX: u8 = 0xf3; -const DOUBLE_PREFIX: u8 = 0xf2; -const REX_W: u8 = 0x48; -const CVTSI_TO_FLOAT: u8 = 0x2a; -const CVTT_TO_INTEGER: u8 = 0x2c; -const CVTDQ2PD: &[u8] = &[0xf3, 0x0f, 0xe6]; -const CVTTPS2DQ: &[u8] = &[0xf3, 0x0f, 0x5b]; -const MOVD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; -const MOVD_EAX_XMM: &[u8] = &[0x66, 0x0f, 0x7e]; -const MOVQ_RAX_XMM: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const MOVSXD_RAX_EAX: &[u8] = &[0x48, 0x63, 0xc0]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const SHR_RDX_IMMEDIATE: &[u8] = &[0x48, 0xc1, 0xea]; -const TEST_EDX_EDX: &[u8] = &[0x85, 0xd2]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const MOV_ECX_IMMEDIATE: &[u8] = &[0xb9]; -const MOVQ_R8_XMM0: &[u8] = &[0x66, 0x49, 0x0f, 0x7e, 0xc0]; -const MOVQ_XMM7_R8: &[u8] = &[0x66, 0x49, 0x0f, 0x6e, 0xf8]; -const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; -const OR_EAX_R10D: &[u8] = &[0x44, 0x09, 0xd0]; -const GPR_RCX: u8 = 1; -const GPR_RAX: u8 = 0; const REPEAT_LOW_DWORD: u8 = 0; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; const MXCSR_PRECISION: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_PRECISION - 1; const MXCSR_TO_FPSR_PRECISION_SHIFT: u8 = 1; @@ -237,27 +210,46 @@ impl Conversion { } } -fn reject(code: &mut Vec, failures: &mut Vec) { - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); +fn reject(code: &mut Code, failures: &mut Vec) { + failures.push(code.asm().jcc(Cond::Ne).offset()); } -fn scalar_opcode(code: &mut Vec, conversion: Conversion, opcode: u8) { - code.push(match conversion.float { - Format::Single => SINGLE_PREFIX, - Format::Double => DOUBLE_PREFIX, - Format::Half => unreachable!("Half conversion belongs to its compute leaf"), - }); +fn host_size(conversion: Conversion) -> Size { if conversion.host_wide() { - code.push(REX_W); + Size::Qword + } else { + Size::Dword + } +} + +/// CVTSI2SS/CVTSI2SD of RAX/EAX into XMM0. +fn convert_from_integer(code: &mut Code, conversion: Conversion) { + let size = host_size(conversion); + let mut asm = code.asm(); + match conversion.float { + Format::Single => asm.cvtsi2float(FloatLanes::ScalarSingle, size, SCALAR, Rax), + Format::Double => asm.cvtsi2float(FloatLanes::ScalarDouble, size, SCALAR, Rax), + Format::Half => unreachable!("Half conversion belongs to its compute leaf"), + } +} + +/// CVTTSS2SI/CVTTSD2SI of XMM0 into RAX/EAX. +fn truncate_to_integer(code: &mut Code, conversion: Conversion) { + let size = host_size(conversion); + let mut asm = code.asm(); + match conversion.float { + Format::Single => { + asm.cvtfloat2si(FloatLanes::ScalarSingle, true, size, Rax, Rm::Xmm(SCALAR)) + } + Format::Double => { + asm.cvtfloat2si(FloatLanes::ScalarDouble, true, size, Rax, Rm::Xmm(SCALAR)) + } + Format::Half => unreachable!("Half conversion belongs to its compute leaf"), } - // Both directions use XMM0 and RAX/EAX, with the appropriate ModRM role. - code.extend([SSE_ESCAPE, opcode, MODRM_REGISTER]); } fn scalar_chunk( - code: &mut Vec, + code: &mut Code, conversion: Conversion, slot_bytes: u8, failures: &mut Vec, @@ -272,12 +264,12 @@ fn scalar_chunk( } match conversion.direction { Direction::FromInteger => { - code.extend(if conversion.integer.width == IntegerWidth::Bits64 { - MOVQ_RAX_XMM + let mut asm = code.asm(); + if conversion.integer.width == IntegerWidth::Bits64 { + asm.movq_from_xmm(Rax, SCALAR); } else { - MOVD_EAX_XMM - }); - code.push(MODRM_REGISTER | (GPR_RAX << MODRM_REGISTER_SHIFT) | SCALAR); + asm.movd_from_xmm(Rax, SCALAR); + } // MOVD writes EAX and zero-extends unsigned W before CVTSI64. // Reset all scalar upper bits so X→S zero-fills its full slot. Host::Xor.register(code, SCALAR, SCALAR, target); @@ -294,7 +286,7 @@ fn scalar_chunk( if conversion.unsigned_x() { unsigned64::from_integer(code, conversion.float); } else { - scalar_opcode(code, conversion, CVTSI_TO_FLOAT); + convert_from_integer(code, conversion); } Host::MoveAligned.register(code, PACK, SCALAR, target); } @@ -303,20 +295,20 @@ fn scalar_chunk( if conversion.unsigned_x() { unsigned64::to_integer(code, conversion.float, failures); } else { - scalar_opcode(code, conversion, CVTT_TO_INTEGER); + truncate_to_integer(code, conversion); } if !conversion.integer.signed && !conversion.unsigned_x() { // CVTT64 admits unsigned W only when high32 is zero. // Negative fractions truncating to zero are valid too. - code.extend(MOV_RDX_RAX); - code.extend(SHR_RDX_IMMEDIATE); - code.push(u32::BITS as u8); - code.extend(TEST_EDX_EDX); + let mut asm = code.asm(); + asm.mov(Size::Qword, Rdx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rdx, u32::BITS as u8); + asm.test(Size::Dword, Rdx, Rdx); reject(code, failures); } else if slot_bytes == QWORD_BYTES && conversion.integer.width == IntegerWidth::Bits32 { - code.extend(MOVSXD_RAX_EAX); + code.asm().movsxd(Rax, Rax); } pack_integer(code, slot_bytes, target); } @@ -330,13 +322,12 @@ fn scalar_chunk( /// MOVD/MOVQ clear all unused packed bits. A returned raw Half also clears the /// rest of its H/W/X slot, so the shift/OR assembly cannot contaminate a neighbor. -fn pack_integer(code: &mut Vec, slot_bytes: u8, target: TargetCpu) { +fn pack_integer(code: &mut Code, slot_bytes: u8, target: TargetCpu) { if slot_bytes == QWORD_BYTES { - Host::MoveGprQword.append(code, target); + code.asm().simd(Host::MoveGprQword, PACK, Rax, target); } else { - code.extend(MOVD_XMM_EAX); + code.asm().movd_to_xmm(PACK, Rax); } - code.push(MODRM_REGISTER | (PACK << MODRM_REGISTER_SHIFT) | GPR_RAX); } /// Compile-time access bookkeeping for the single instruction frame. No guest @@ -351,7 +342,7 @@ struct ChunkAccess { } impl ChunkAccess { - fn mask(self, code: &mut Vec, chunk: usize, destination: u8, scratch: u8) { + fn mask(self, code: &mut Code, chunk: usize, destination: u8, scratch: u8) { read_predicate_mask( code, self.operand.governing, @@ -364,7 +355,7 @@ impl ChunkAccess { ); } - fn source(self, code: &mut Vec, chunk: usize, destination: u8) { + fn source(self, code: &mut Code, chunk: usize, destination: u8) { load_z_chunk( code, self.operand.source, @@ -376,17 +367,21 @@ impl ChunkAccess { } } -fn broadcast_dword(code: &mut Vec, register: u8, value: u32, target: TargetCpu) { - code.extend(MOV_ECX_IMMEDIATE); - code.extend(value.to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (register << MODRM_REGISTER_SHIFT) | GPR_RCX); - Host::ShuffleDword.register(code, register, register, target); - code.push(REPEAT_LOW_DWORD); +fn broadcast_dword(code: &mut Code, register: u8, value: u32, target: TargetCpu) { + let mut asm = code.asm(); + asm.mov_imm32(Rcx, value); + asm.simd(Host::MoveGprQword, register, Rcx, target); + asm.simd_imm( + Host::ShuffleDword, + register, + Rm::Xmm(register), + REPEAT_LOW_DWORD, + target, + ); } fn half_forward_group( - code: &mut Vec, + code: &mut Code, access: ChunkAccess, chunk: usize, integer: IntegerFormat, @@ -416,20 +411,20 @@ fn half_forward_group( IntegerWidth::Bits64 => { // Half0/Half4 are the only architectural operands. Duplicate them // in internal extra dwords rather than reading Half2/Half6 poison. - Host::ShuffleDword.register(code, SCALAR, SCALAR, access.target); - code.push(LOW_DWORDS_FROM_QWORDS); + code.asm().simd_imm( + Host::ShuffleDword, + SCALAR, + Rm::Xmm(SCALAR), + LOW_DWORDS_FROM_QWORDS, + access.target, + ); } } half_integer::to_integer_words(code, integer, mapping.half_f16c(), failures, access.target); } /// Every selected H result is in range before these lossless integer packs. -fn pack_half_results( - code: &mut Vec, - integer: IntegerFormat, - mapping: Mapping, - target: TargetCpu, -) { +fn pack_half_results(code: &mut Code, integer: IntegerFormat, mapping: Mapping, target: TargetCpu) { if integer.signed { Host::PackSignedDwordToWord.register(code, SCALAR, SCALAR, target); } else if mapping.unsigned_half_pack() { @@ -451,7 +446,7 @@ fn pack_half_results( /// Return the complete converted chunk register, preserving constants2/3/4. fn half_forward_chunk( - code: &mut Vec, + code: &mut Code, access: ChunkAccess, chunk: usize, integer: IntegerFormat, @@ -462,11 +457,11 @@ fn half_forward_chunk( match integer.width { IntegerWidth::Bits16 => { pack_half_results(code, integer, mapping, access.target); - code.extend(MOVQ_R8_XMM0); + code.asm().movq_from_xmm(R8, 0); half_forward_group(code, access, chunk, integer, mapping, true, failures); pack_half_results(code, integer, mapping, access.target); // RDX cannot hold group one: the Z and P reloads clobber it. - code.extend(MOVQ_XMM7_R8); + code.asm().movq_to_xmm(7, R8); Host::UnpackLowQword.register(code, PACK, SCALAR, access.target); PACK } @@ -489,7 +484,7 @@ fn half_forward_chunk( /// The caller owns RC installation, active-trap guards and whole-state commit. /// Input SOURCE1 is read-only; RESULT3 is output; SCALAR0 and XMM4 are scratch. /// Preserves ACTIVE6, all other XMMs, GPRs, EFLAGS and pending status channels. -fn packed_signed_half_chunk(code: &mut Vec, target: TargetCpu) { +fn packed_signed_half_chunk(code: &mut Code, target: TargetCpu) { Host::MoveAligned.register(code, RESULT, SOURCE, target); Host::MoveAligned.register(code, SCALAR, SOURCE, target); Host::MoveAligned.register(code, SIGNED_HALF_SIGN_MASK, SOURCE, target); @@ -499,14 +494,24 @@ fn packed_signed_half_chunk(code: &mut Vec, target: TargetCpu) { Host::ConvertPackedDwordToSingle.register(code, RESULT, RESULT, target); Host::ConvertPackedDwordToSingle.register(code, SCALAR, SCALAR, target); // This instruction's ModRM.reg is the Single source, r/m the Half result. - Host::ConvertSingleToHalf.register(code, RESULT, RESULT, target); - code.push(half_integer::USE_MXCSR_ROUNDING); - Host::ConvertSingleToHalf.register(code, SCALAR, SCALAR, target); - code.push(half_integer::USE_MXCSR_ROUNDING); + code.asm().simd_imm( + Host::ConvertSingleToHalf, + RESULT, + Rm::Xmm(RESULT), + half_integer::USE_MXCSR_ROUNDING, + target, + ); + code.asm().simd_imm( + Host::ConvertSingleToHalf, + SCALAR, + Rm::Xmm(SCALAR), + half_integer::USE_MXCSR_ROUNDING, + target, + ); Host::UnpackLowQword.register(code, RESULT, SCALAR, target); } -fn packed_chunk(code: &mut Vec, conversion: Conversion, target: TargetCpu) { +fn packed_chunk(code: &mut Code, conversion: Conversion, target: TargetCpu) { Host::MoveAligned.register(code, RESULT, SOURCE, target); match (conversion.direction, conversion.float) { (Direction::FromInteger, Format::Single) => { @@ -514,14 +519,17 @@ fn packed_chunk(code: &mut Vec, conversion: Conversion, target: TargetCpu) { } (Direction::FromInteger, Format::Double) => { // W→D selects each qword's low dword, not adjacent packed W lanes. - Host::ShuffleDword.register(code, RESULT, RESULT, target); - code.push(LOW_DWORDS_FROM_QWORDS); - code.extend(CVTDQ2PD); - code.push(MODRM_REGISTER | (RESULT << MODRM_REGISTER_SHIFT) | RESULT); + code.asm().simd_imm( + Host::ShuffleDword, + RESULT, + Rm::Xmm(RESULT), + LOW_DWORDS_FROM_QWORDS, + target, + ); + code.asm().cvtdq2pd(RESULT, Rm::Xmm(RESULT)); } (Direction::ToInteger, Format::Single) => { - code.extend(CVTTPS2DQ); - code.push(MODRM_REGISTER | (RESULT << MODRM_REGISTER_SHIFT) | RESULT); + code.asm().cvttps2dq(RESULT, Rm::Xmm(RESULT)); } _ => unreachable!("packed mapping was checked before emission"), } @@ -531,7 +539,7 @@ fn packed_chunk(code: &mut Vec, conversion: Conversion, target: TargetCpu) { /// Unsupported forms leave `code` unchanged. No guest state is changed /// until numerical::finish, including when source aliases destination. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -569,12 +577,13 @@ pub(in crate::x86_64) fn emit( )?; match conversion.direction { Direction::FromInteger => rounding_control(code), - Direction::ToInteger => code.extend(XOR_EAX_EAX), // CVTT ignores RC. + // CVTT ignores RC. + Direction::ToInteger => code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax), } numerical::install_mxcsr(code, &frame); if manual_inexact { // This is an approved guest-IXC bitmask, not a Boolean or host status. - code.extend(XOR_R10D_R10D); + code.asm().alu(Alu::Xor, Size::Dword, R10, R10); } if half_forward { half_integer::prepare_to_integer(code, target); @@ -645,18 +654,22 @@ pub(in crate::x86_64) fn emit( // All admitted conversions can raise only guest IXC. Earlier chunks and // caller MXCSR remain untouched if any later lane needs exact completion. numerical::capture_status(code, &frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_OTHER_STATUS as i32); reject(code, &mut failures); - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_PRECISION.to_le_bytes()); - code.extend(SHR_EAX_IMMEDIATE); - code.push(MXCSR_TO_FPSR_PRECISION_SHIFT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_PRECISION as i32); + asm.shift_imm( + ShiftOp::Shr, + Size::Dword, + Rax, + MXCSR_TO_FPSR_PRECISION_SHIFT, + ); if manual_inexact { - code.extend(OR_EAX_R10D); - code.push(AND_EAX_IMMEDIATE); - code.extend(INEXACT.to_le_bytes()); + let mut asm = code.asm(); + asm.alu(Alu::Or, Size::Dword, Rax, R10); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, INEXACT as i32); } numerical::add_fpsr(code, &frame); numerical::finish(code, &frame, &failures, pc, target); diff --git a/crates/stela-compiler/src/x86_64/sve/floating/conversion/unsigned64.rs b/crates/stela-compiler/src/x86_64/sve/floating/conversion/unsigned64.rs index f758436e99..7528dd9719 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/conversion/unsigned64.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/conversion/unsigned64.rs @@ -1,146 +1,152 @@ //! SSE2 conversions between single/double and unsigned 64-bit integers. The //! caller owns the MXCSR frame, lane guards and staging. +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::FloatOp; +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use crate::aarch64::floating::Format; use alloc::vec::Vec; const SCALAR: u8 = 0; const TEMPORARY: u8 = 7; -const DATA_GPR: u8 = 2; const INTEGER_HIGH_BIT: u8 = u64::BITS as u8 - 1; const SINGLE_EXPONENT_BIAS: u64 = 127; const DOUBLE_EXPONENT_BIAS: u64 = 1023; -const SINGLE_PREFIX: u8 = 0xf3; -const DOUBLE_PREFIX: u8 = 0xf2; -const SSE_ESCAPE: u8 = 0x0f; -const REX_W: u8 = 0x48; -const REGISTER_DIRECT: u8 = 0xc0; -const REGISTER_FIELD_SHIFT: u8 = 3; -const CVTSI_TO_FLOAT: u8 = 0x2a; -const CVTT_TO_INTEGER: u8 = 0x2c; -const ADD_SCALAR: u8 = 0x58; -const SUBTRACT_SCALAR: u8 = 0x5c; -const UCOMIS: u8 = 0x2e; -const DOUBLE_COMPARE_PREFIX: u8 = 0x66; -const TEST_RAX_RAX: &[u8] = &[0x48, 0x85, 0xc0]; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const AND_ECX_ONE: &[u8] = &[0x83, 0xe1, 1]; -const SHR_RAX_ONE: &[u8] = &[0x48, 0xd1, 0xe8]; -const OR_RAX_RCX: &[u8] = &[0x48, 0x09, 0xc8]; -const MOVABS_RDX: &[u8] = &[0x48, 0xba]; -const MOVQ_XMM_RDX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e]; -const BT_RAX_IMMEDIATE: &[u8] = &[0x48, 0x0f, 0xba, 0xe0]; -const BTS_RAX_IMMEDIATE: &[u8] = &[0x48, 0x0f, 0xba, 0xe8]; -const JNS_REL32: &[u8] = &[0x0f, 0x89]; -const JB_REL32: &[u8] = &[0x0f, 0x82]; -const JMP_REL32: &[u8] = &[0xe9]; -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement +fn check(format: Format) { + assert!( + matches!(format, Format::Single | Format::Double), + "unsigned64 candidate admits only S/D" + ); } -fn resolve(code: &mut [u8], displacement: usize, destination: usize) { - let next = displacement + size_of::(); - let relative = i32::try_from(destination as isize - next as isize) - .expect("conversion lane branch fits rel32"); - code[displacement..next].copy_from_slice(&relative.to_le_bytes()); -} - -fn prefix(format: Format) -> u8 { - match format { - Format::Single => SINGLE_PREFIX, - Format::Double => DOUBLE_PREFIX, - Format::Half => unreachable!("unsigned64 candidate admits only S/D"), +/// CVTSI2SS/CVTSI2SD XMM0 from RAX. +fn convert_from_integer(code: &mut Code, format: Format) { + let mut asm = code.asm(); + if format == Format::Single { + asm.cvtsi2float(FloatLanes::ScalarSingle, Size::Qword, SCALAR, Rax); + } else { + asm.cvtsi2float(FloatLanes::ScalarDouble, Size::Qword, SCALAR, Rax); } } -fn convert(code: &mut Vec, format: Format, opcode: u8) { - // Both directions use RAX and XMM0; the opcode assigns their roles. - code.extend([prefix(format), REX_W, SSE_ESCAPE, opcode, REGISTER_DIRECT]); +/// CVTTSS2SI/CVTTSD2SI RAX from XMM0. +fn convert_to_integer(code: &mut Code, format: Format) { + let mut asm = code.asm(); + if format == Format::Single { + asm.cvtfloat2si( + FloatLanes::ScalarSingle, + true, + Size::Qword, + Rax, + Rm::Xmm(SCALAR), + ); + } else { + asm.cvtfloat2si( + FloatLanes::ScalarDouble, + true, + Size::Qword, + Rax, + Rm::Xmm(SCALAR), + ); + } } -fn scalar(code: &mut Vec, format: Format, opcode: u8, source: u8) { - code.extend([ - prefix(format), - SSE_ESCAPE, - opcode, - REGISTER_DIRECT | (SCALAR << REGISTER_FIELD_SHIFT) | source, - ]); -} - -fn unsigned_split_constant(code: &mut Vec, format: Format) { +fn unsigned_split_constant(code: &mut Code, format: Format) { let bias = match format { Format::Single => SINGLE_EXPONENT_BIAS, Format::Double => DOUBLE_EXPONENT_BIAS, Format::Half => unreachable!("unsigned64 candidate admits only S/D"), }; let bits = (bias + u64::from(INTEGER_HIGH_BIT)) << format.fraction_bits(); - code.extend(MOVABS_RDX); - code.extend(bits.to_le_bytes()); - code.extend(MOVQ_XMM_RDX); - code.push(REGISTER_DIRECT | (TEMPORARY << REGISTER_FIELD_SHIFT) | DATA_GPR); + let mut asm = code.asm(); + asm.mov_imm64(Rdx, bits); + asm.movq_to_xmm(TEMPORARY, Rdx); } /// Consume unsigned RAX, produce low S/D in XMM0. Upper XMM0 must start zero. /// Scratch RAX/RCX and flags; preserves XMM1..7, RDX and all caller pointers. /// Private MXCSR must contain effective guest RC, clear status and masked traps. -pub(crate) fn from_integer(code: &mut Vec, format: Format) { - let _ = prefix(format); // Reject a violated S/D contract before emitting bytes. - code.extend(TEST_RAX_RAX); - let low = branch(code, JNS_REL32); +pub(crate) fn from_integer(code: &mut Code, format: Format) { + check(format); + let mut asm = code.asm(); + asm.test(Size::Qword, Rax, Rax); + let low = asm.jcc(Cond::Ns); // For n >= 2^63, n/2 fits signed X. OR the discarded low bit into the // quotient: it retains sticky information for all four IEEE rounding modes. - code.extend(MOV_RCX_RAX); - code.extend(AND_ECX_ONE); - code.extend(SHR_RAX_ONE); - code.extend(OR_RAX_RCX); - convert(code, format, CVTSI_TO_FLOAT); + asm.mov(Size::Qword, Rcx, Rax); + asm.alu_imm8(Alu::And, Size::Dword, Rcx, 1); + asm.shift_one(ShiftOp::Shr, Size::Qword, Rax); + asm.alu(Alu::Or, Size::Qword, Rax, Rcx); + convert_from_integer(code, format); // The rounded quotient is normal and finite; doubling is exact, including // the rounded-up 2^63 quotient. Only the CVTSI can contribute host PE. - scalar(code, format, ADD_SCALAR, SCALAR); - let done = branch(code, JMP_REL32); - let low_start = code.len(); - resolve(code, low, low_start); - convert(code, format, CVTSI_TO_FLOAT); - let end = code.len(); - resolve(code, done, end); + let mut asm = code.asm(); + if format == Format::Single { + asm.float( + FloatOp::Add, + FloatLanes::ScalarSingle, + SCALAR, + Rm::Xmm(SCALAR), + ); + } else { + asm.float( + FloatOp::Add, + FloatLanes::ScalarDouble, + SCALAR, + Rm::Xmm(SCALAR), + ); + } + let done = asm.jmp(); + asm.bind(low); + convert_from_integer(code, format); + code.asm().bind(done); } /// Consume low S/D XMM0, produce unsigned RAX. Scratch XMM0/XMM7/RDX/flags. /// Caller must reject NaNs/subnormals, then reject all private status except PE. /// This appends a negative-result failure to the shared transactional rollback. -pub(crate) fn to_integer(code: &mut Vec, format: Format, failures: &mut Vec) { - let _ = prefix(format); +pub(crate) fn to_integer(code: &mut Code, format: Format, failures: &mut Vec) { + check(format); unsigned_split_constant(code, format); + let mut asm = code.asm(); if format == Format::Double { - code.push(DOUBLE_COMPARE_PREFIX); + asm.ucomisd(SCALAR, Rm::Xmm(TEMPORARY)); + } else { + asm.ucomiss(SCALAR, Rm::Xmm(TEMPORARY)); } - code.extend([ - SSE_ESCAPE, - UCOMIS, - REGISTER_DIRECT | (SCALAR << REGISTER_FIELD_SHIFT) | TEMPORARY, - ]); - let low = branch(code, JB_REL32); + let low = asm.jcc(Cond::B); // Subtraction is exact on [2^63, 2^64) by Sterbenz. The remainder fits // signed X; restoring bit63 reconstructs the unsigned integer exactly. // >=2^64 and infinities instead raise private invalid and must roll back. - scalar(code, format, SUBTRACT_SCALAR, TEMPORARY); - convert(code, format, CVTT_TO_INTEGER); - code.extend(BTS_RAX_IMMEDIATE); - code.push(INTEGER_HIGH_BIT); - let done = branch(code, JMP_REL32); - let low_start = code.len(); - resolve(code, low, low_start); - convert(code, format, CVTT_TO_INTEGER); + if format == Format::Single { + asm.float( + FloatOp::Sub, + FloatLanes::ScalarSingle, + SCALAR, + Rm::Xmm(TEMPORARY), + ); + } else { + asm.float( + FloatOp::Sub, + FloatLanes::ScalarDouble, + SCALAR, + Rm::Xmm(TEMPORARY), + ); + } + convert_to_integer(code, format); + let mut asm = code.asm(); + asm.bit_imm(BitTest::Bts, Size::Qword, Rax, INTEGER_HIGH_BIT); + let done = asm.jmp(); + asm.bind(low); + convert_to_integer(code, format); // Negative fractions truncating to zero (and -0) are valid. Reject the // negative integer result, not the input sign. Private invalid catches the // signed sentinel too; the bit test alone never establishes success. - code.extend(BT_RAX_IMMEDIATE); - code.push(INTEGER_HIGH_BIT); - failures.push(branch(code, JB_REL32)); - let end = code.len(); - resolve(code, done, end); + let mut asm = code.asm(); + asm.bit_imm(BitTest::Bt, Size::Qword, Rax, INTEGER_HIGH_BIT); + failures.push(asm.jcc(Cond::B).offset()); + asm.bind(done); } diff --git a/crates/stela-compiler/src/x86_64/sve/floating/conversion/widening.rs b/crates/stela-compiler/src/x86_64/sve/floating/conversion/widening.rs index 0009f9e05b..15b403b765 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/conversion/widening.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/conversion/widening.rs @@ -1,4 +1,5 @@ //! SVE single-to-double widening. +use crate::x86_64::asm::{Code, Rm}; use crate::{ CompileError, GuestAddress, TargetCpu, @@ -32,7 +33,6 @@ const DWORD_SELECTOR_BITS: u8 = 2; const LOW_SINGLE: u8 = 0; const HIGH_SINGLE: u8 = 1; const NEXT_QWORD_SINGLE: u8 = 2; -const CVTPS2PD_XMM0_XMM0: &[u8] = &[0x0f, 0x5a, 0xc0]; /// Compact the selected Single from each qword into the low two dwords. /// Duplicating them above those dwords lets the shared classifier check all @@ -54,7 +54,7 @@ const fn source_shuffle(placement: Placement) -> u8 { /// untouched for their normal numerical completion path. The caller owns /// instruction availability and the streaming-mode entry guard. pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -95,8 +95,13 @@ pub(crate) fn emit( // Replace every inactive input with +0 before any host FP operation. // The shuffle also discards the unselected half of each source slot. SimdOpcode::And.register(code, RESULT, ACTIVE, target); - SimdOpcode::ShuffleDword.register(code, RESULT, RESULT, target); - code.push(source_shuffle(placement)); + code.asm().simd_imm( + SimdOpcode::ShuffleDword, + RESULT, + Rm::Xmm(RESULT), + source_shuffle(placement), + target, + ); guard_normal_zero_or_infinity( code, classification, @@ -107,7 +112,7 @@ pub(crate) fn emit( ); // Normals, signed zeros and infinities widen exactly under every // caller RC/DAZ/FTZ/mask setting, without changing MXCSR or FPSR. - code.extend(CVTPS2PD_XMM0_XMM0); + code.asm().cvtps2pd(0, Rm::Xmm(0)); load_z_chunk( code, operand.destination, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/estimate_exponent.rs b/crates/stela-compiler/src/x86_64/sve/floating/estimate_exponent.rs index c471319ae9..4bce9ff82d 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/estimate_exponent.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/estimate_exponent.rs @@ -1,4 +1,6 @@ //! SVE FRECPX and FLOGB by integer arithmetic. +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Code, Cond, Rm, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -31,13 +33,6 @@ const EXPONENT_MASK: u8 = MASKS[1]; const TEST_MASK: u8 = SCRATCH[0]; const TEMPORARY: u8 = SCRATCH[1]; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; const REPEAT_LOW_DWORD: u8 = 0; const REPEAT_HIGH_DWORDS: u8 = 0xf5; const REMOVE_SIGN_BITS: u8 = 1; @@ -63,38 +58,40 @@ fn inputs(operand: Operand) -> Option<(Operation, u8, u8)> { Some((operation, source, operand.predicate?)) } -fn broadcast(code: &mut Vec, format: Format, value: u64, register: u8, target: TargetCpu) { +fn broadcast(code: &mut Code, format: Format, value: u64, register: u8, target: TargetCpu) { if format == Format::Single { - code.push(MOV_EAX_IMMEDIATE); - code.extend((value as u32).to_le_bytes()); + code.asm().mov_imm32(Rax, value as u32); } else { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(value.to_le_bytes()); + code.asm().mov_imm64(Rax, value); } - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (register << MODRM_REGISTER_SHIFT) | GPR_RAX); + code.asm().simd(Host::MoveGprQword, register, Rax, target); if format == Format::Single { - Host::ShuffleDword.register(code, register, register, target); - code.push(REPEAT_LOW_DWORD); + code.asm().simd_imm( + Host::ShuffleDword, + register, + Rm::Xmm(register), + REPEAT_LOW_DWORD, + target, + ); } else { Host::UnpackLowQword.register(code, register, register, target); } } -fn replicate_exponent_comparison( - code: &mut Vec, - format: Format, - register: u8, - target: TargetCpu, -) { +fn replicate_exponent_comparison(code: &mut Code, format: Format, register: u8, target: TargetCpu) { if format == Format::Double { // Only the high dword contains exponent bits in a Double lane. - Host::ShuffleDword.register(code, register, register, target); - code.push(REPEAT_HIGH_DWORDS); + code.asm().simd_imm( + Host::ShuffleDword, + register, + Rm::Xmm(register), + REPEAT_HIGH_DWORDS, + target, + ); } } -fn subtract(code: &mut Vec, format: Format, destination: u8, source: u8, target: TargetCpu) { +fn subtract(code: &mut Code, format: Format, destination: u8, source: u8, target: TargetCpu) { match format { Format::Single => Host::SubDword, Format::Double => Host::SubQword, @@ -103,7 +100,7 @@ fn subtract(code: &mut Vec, format: Format, destination: u8, source: u8, tar .register(code, destination, source, target); } -fn right_shift(code: &mut Vec, format: Format, register: u8, amount: u8) { +fn right_shift(code: &mut Code, format: Format, register: u8, amount: u8) { match format { Format::Single => ShiftOpcode::RightDword, Format::Double => ShiftOpcode::RightQword, @@ -112,7 +109,7 @@ fn right_shift(code: &mut Vec, format: Format, register: u8, amount: u8) { .emit(code, register, amount); } -fn reciprocal_exponent(code: &mut Vec, format: Format, target: TargetCpu) { +fn reciprocal_exponent(code: &mut Code, format: Format, target: TargetCpu) { Host::MoveAligned.register(code, TEST_MASK, VALUE, target); Host::And.register(code, TEST_MASK, EXPONENT_MASK, target); Host::Xor.register(code, TEMPORARY, TEMPORARY, target); @@ -129,7 +126,7 @@ fn reciprocal_exponent(code: &mut Vec, format: Format, target: TargetCpu) { } fn logarithm_exponent( - code: &mut Vec, + code: &mut Code, format: Format, failures: &mut Vec, target: TargetCpu, @@ -139,11 +136,10 @@ fn logarithm_exponent( Host::EqualDword.register(code, TEST_MASK, VALUE, target); replicate_exponent_comparison(code, format, TEST_MASK, target); Host::And.register(code, TEST_MASK, ACTIVE, target); - Host::ByteSignMask.register(code, GPR_RAX, TEST_MASK, target); - code.extend(TEST_EAX_EAX); - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); + code.asm() + .simd_to_gpr(Host::ByteSignMask, Rax, TEST_MASK, target); + code.asm().test(Size::Dword, Rax, Rax); + failures.push(code.asm().jcc(Cond::Ne).offset()); // Zero raises Invalid in FPLogB, so it falls back before staging. Infinity // selects signed integer MAX; normals subtract the bias from the field. Host::MoveAligned.register(code, TEST_MASK, EXPONENT_MASK, target); @@ -163,7 +159,7 @@ fn logarithm_exponent( /// Clobbers volatile RAX/RCX/RDX, host flags and XMM0..7. RDI/R15, guest NZCV, /// FPSR, raw FPCR, sources and caller MXCSR survive until the only staged commit. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/faminmax.rs b/crates/stela-compiler/src/x86_64/sve/floating/faminmax.rs index 686e59d352..657d45aaf2 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/faminmax.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/faminmax.rs @@ -1,6 +1,7 @@ //! SVE FAMIN/FAMAX by integer magnitude comparison. Active NaNs use software //! completion. use super::classify::guard_active_exception_enables; +use crate::x86_64::asm::Code; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -36,7 +37,7 @@ fn element(format: Format) -> ElementSize { /// Reviewed static scopes use checked SSE4.1/SSE4.2 tiers for Single/Double. /// Complete output staging preserves sources/aliases on any guard failure. pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/floating_estimates.rs b/crates/stela-compiler/src/x86_64/sve/floating/floating_estimates.rs index 5ec06e48dc..fe15f0d0e2 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/floating_estimates.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/floating_estimates.rs @@ -1,5 +1,9 @@ //! SVE FRECPE/FRSQRTE tables on normal values. Host RCP/RSQRT approximations //! are never used; integer DIV and a masked SQRTSD compute the exact table values. +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdi, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Disp, Gpr, Mem, Rm, ShiftOp, Size, Unary}; use crate::{ CompileError, GuestAddress, GuestState, TargetCpu, aarch64::{ @@ -37,107 +41,28 @@ const RECIPROCAL_NUMERATOR_BITS: u32 = 19; const ENHANCED_RECIPROCAL_NUMERATOR_BITS: u32 = 26; const ROOT_NUMERATOR_BITS: u32 = 28; const ENHANCED_ROOT_NUMERATOR_BITS: u32 = 39; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const GPR_RAX: u8 = 0; -const GPR_RCX: u8 = 1; -const GPR_RDX: u8 = 2; -const REL32_BYTES: usize = size_of::(); -const TEST_STATE_IMMEDIATE: &[u8] = &[0xf7, 0x87]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -const JAE_REL32: &[u8] = &[0x0f, 0x83]; -const JC_REL32: &[u8] = &[0x0f, 0x82]; -const JMP_REL32: &[u8] = &[0xe9]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const XOR_EDX_EDX: &[u8] = &[0x31, 0xd2]; -const MOV_EAX_EAX: &[u8] = &[0x89, 0xc0]; -const MOVZX_EAX_AX: &[u8] = &[0x0f, 0xb7, 0xc0]; -const MOV_R8_RAX: &[u8] = &[0x49, 0x89, 0xc0]; -const SHR_R8_IMMEDIATE: &[u8] = &[0x49, 0xc1, 0xe8]; -const AND_R8D_IMMEDIATE: &[u8] = &[0x41, 0x81, 0xe0]; -const TEST_R8D_R8D: &[u8] = &[0x45, 0x85, 0xc0]; -const CMP_R8D_IMMEDIATE: &[u8] = &[0x41, 0x81, 0xf8]; -const TEST_R8B_PARITY: &[u8] = &[0x41, 0xf6, 0xc0, 1]; -const BT_RAX_IMMEDIATE: &[u8] = &[0x48, 0x0f, 0xba, 0xe0]; -const MOV_ECX_IMMEDIATE: u8 = 0xb9; -const SUB_ECX_R8D: &[u8] = &[0x44, 0x29, 0xc1]; -const SHR_ECX_ONE: &[u8] = &[0xd1, 0xe9]; -const SHL_RCX_IMMEDIATE: &[u8] = &[0x48, 0xc1, 0xe1]; -const MOV_R9_RAX: &[u8] = &[0x49, 0x89, 0xc1]; -const SHR_R9_IMMEDIATE: &[u8] = &[0x49, 0xc1, 0xe9]; -const SHL_R9_IMMEDIATE: &[u8] = &[0x49, 0xc1, 0xe1]; -const OR_R9_RCX: &[u8] = &[0x49, 0x09, 0xc9]; -const MOV_R9_RCX: &[u8] = &[0x49, 0x89, 0xc9]; -const SHL_RAX_IMMEDIATE: &[u8] = &[0x48, 0xc1, 0xe0]; -const SHR_RAX_IMMEDIATE: &[u8] = &[0x48, 0xc1, 0xe8]; -const SHL_RAX_CL: &[u8] = &[0x48, 0xd3, 0xe0]; -const SHR_RAX_CL: &[u8] = &[0x48, 0xd3, 0xe8]; -const MOV_ECX_R10D: &[u8] = &[0x44, 0x89, 0xd1]; -const MOV_ECX_R11D: &[u8] = &[0x44, 0x89, 0xd9]; -const MOV_R10D_IMMEDIATE: &[u8] = &[0x41, 0xba]; -const MOV_R11D_IMMEDIATE: &[u8] = &[0x41, 0xbb]; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const OR_EAX_IMMEDIATE: u8 = 0x0d; -const OR_RAX_RCX: &[u8] = &[0x48, 0x09, 0xc8]; -const AND_EAX_EVEN: &[u8] = &[0x83, 0xe0, 0xfe]; -const LEA_ECX_TWICE_RAX_PLUS_ONE: &[u8] = &[0x8d, 0x4c, 0x00, 1]; -const LEA_ECX_TWICE_RAX_PLUS_TWO: &[u8] = &[0x8d, 0x4c, 0x00, 2]; -const SHR_EAX_ONE: &[u8] = &[0xd1, 0xe8]; -const DIV_RCX: &[u8] = &[0x48, 0xf7, 0xf1]; -const DIV_ECX: &[u8] = &[0xf7, 0xf1]; -const ADD_EAX_ONE: &[u8] = &[0x83, 0xc0, 1]; -const SUB_EAX_IMMEDIATE: u8 = 0x2d; -const SUB_EAX_EDX: &[u8] = &[0x29, 0xd0]; -const OR_RAX_R9: &[u8] = &[0x4c, 0x09, 0xc8]; -const MOVQ_GPR_XMM: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const CVTSI2SD_XMM2_RAX: &[u8] = &[0xf2, 0x48, 0x0f, 0x2a, 0xd0]; -const CVTTSD2SI_RAX_XMM2: &[u8] = &[0xf2, 0x48, 0x0f, 0x2c, 0xc2]; -const PINSRW_XMM1_EAX: &[u8] = &[0x66, 0x0f, 0xc4, 0xc8]; -const PINSRD_XMM1_EAX: &[u8] = &[0x66, 0x0f, 0x3a, 0x22, 0xc8]; - #[derive(Clone, Copy, PartialEq, Eq)] enum Operation { Reciprocal, ReciprocalSquareRoot, } -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement +fn test_ah(code: &mut Code) { + code.asm().test_imm( + Size::Dword, + Mem::base_disp32(Rdi, core::mem::offset_of!(GuestState, fpcr) as i32), + FPCR_AH as i32, + ); } -fn resolve(code: &mut [u8], displacement: usize, destination: usize) { - let next = displacement + REL32_BYTES; - let relative = i32::try_from(destination as i64 - next as i64) - .expect("bounded estimate branch fits rel32"); - code[displacement..next].copy_from_slice(&relative.to_le_bytes()); +fn xmm_to_gpr(code: &mut Code, source: u8, destination: Gpr) { + code.asm().movq_from_xmm(destination, source); } -fn immediate(code: &mut Vec, opcode: &[u8], value: u32) { - code.extend(opcode); - code.extend(value.to_le_bytes()); -} - -fn test_ah(code: &mut Vec) { - code.extend(TEST_STATE_IMMEDIATE); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(FPCR_AH.to_le_bytes()); -} - -fn xmm_to_gpr(code: &mut Vec, source: u8, destination: u8) { - code.extend(MOVQ_GPR_XMM); - code.push(MODRM_REGISTER | (source << MODRM_REGISTER_SHIFT) | destination); -} - -fn xmm_constant(code: &mut Vec, destination: u8, bits: u64, target: TargetCpu) { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(bits.to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (destination << MODRM_REGISTER_SHIFT) | GPR_RAX); +fn xmm_constant(code: &mut Code, destination: u8, bits: u64, target: TargetCpu) { + let mut asm = code.asm(); + asm.mov_imm64(Rax, bits); + asm.simd(Host::MoveGprQword, destination, Rax, target); } fn numerator(operation: Operation, enhanced: bool) -> u64 { @@ -150,7 +75,7 @@ fn numerator(operation: Operation, enhanced: bool) -> u64 { } fn constants( - code: &mut Vec, + code: &mut Code, operation: Operation, format: Format, enhanced: bool, @@ -166,126 +91,138 @@ fn constants( } else { STANDARD_RESULT_BITS }; - immediate(code, MOV_R10D_IMMEDIATE, GPR_BITS - input_bits); - immediate( - code, - MOV_R11D_IMMEDIATE, - format.fraction_bits() - result_bits, - ); + let mut asm = code.asm(); + asm.mov_imm32(R10, GPR_BITS - input_bits); + asm.mov_imm32(R11, format.fraction_bits() - result_bits); xmm_constant(code, NUMERATOR, numerator(operation, enhanced), target); xmm_constant(code, INPUT_UNIT, 1 << input_bits, target); xmm_constant(code, RESULT_UNIT, 1 << result_bits, target); } -fn guard_normal( - code: &mut Vec, - operation: Operation, - format: Format, - failures: &mut Vec, -) { - code.extend(MOV_R8_RAX); - code.extend(SHR_R8_IMMEDIATE); - code.push(format.fraction_bits() as u8); - immediate( - code, - AND_R8D_IMMEDIATE, - (format.exponent_mask() >> format.fraction_bits()) as u32, +fn guard_normal(code: &mut Code, operation: Operation, format: Format, failures: &mut Vec) { + let mut asm = code.asm(); + asm.mov(Size::Qword, R8, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, R8, format.fraction_bits() as u8); + asm.alu_imm32( + Alu::And, + Size::Dword, + R8, + (format.exponent_mask() >> format.fraction_bits()) as i32, ); - code.extend(TEST_R8D_R8D); - failures.push(branch(code, JZ_REL32)); + asm.test(Size::Dword, R8, R8); + failures.push(asm.jcc(Cond::E).offset()); let ceiling = match operation { Operation::Reciprocal => format.exponent_bias() * 2 - 1, Operation::ReciprocalSquareRoot => { (format.exponent_mask() >> format.fraction_bits()) as u32 } }; - immediate(code, CMP_R8D_IMMEDIATE, ceiling); - failures.push(branch(code, JAE_REL32)); + asm.alu_imm32(Alu::Cmp, Size::Dword, R8, ceiling as i32); + failures.push(asm.jcc(Cond::Ae).offset()); if operation == Operation::ReciprocalSquareRoot { - code.extend(BT_RAX_IMMEDIATE); - code.push((format.bits() - 1) as u8); - failures.push(branch(code, JC_REL32)); + asm.bit_imm(BitTest::Bt, Size::Qword, Rax, (format.bits() - 1) as u8); + failures.push(asm.jcc(Cond::B).offset()); } } -fn result_exponent(code: &mut Vec, operation: Operation, format: Format) { +fn result_exponent(code: &mut Code, operation: Operation, format: Format) { let exponent_base = match operation { Operation::Reciprocal => format.exponent_bias() * 2 - 1, Operation::ReciprocalSquareRoot => format.exponent_bias() * 3 - 1, }; - immediate(code, &[MOV_ECX_IMMEDIATE], exponent_base); - code.extend(SUB_ECX_R8D); + let mut asm = code.asm(); + asm.mov_imm32(Rcx, exponent_base); + asm.alu(Alu::Sub, Size::Dword, Rcx, R8); if operation == Operation::ReciprocalSquareRoot { - code.extend(SHR_ECX_ONE); + code.asm().shift_one(ShiftOp::Shr, Size::Dword, Rcx); } - code.extend(SHL_RCX_IMMEDIATE); - code.push(format.fraction_bits() as u8); + code.asm() + .shift_imm(ShiftOp::Shl, Size::Qword, Rcx, format.fraction_bits() as u8); if operation == Operation::Reciprocal { - code.extend(MOV_R9_RAX); - code.extend(SHR_R9_IMMEDIATE); - code.push((format.bits() - 1) as u8); - code.extend(SHL_R9_IMMEDIATE); - code.push((format.bits() - 1) as u8); - code.extend(OR_R9_RCX); + let mut asm = code.asm(); + asm.mov(Size::Qword, R9, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, R9, (format.bits() - 1) as u8); + asm.shift_imm(ShiftOp::Shl, Size::Qword, R9, (format.bits() - 1) as u8); + asm.alu(Alu::Or, Size::Qword, R9, Rcx); } else { - code.extend(MOV_R9_RCX); + code.asm().mov(Size::Qword, R9, Rcx); } } -fn midpoint(code: &mut Vec, operation: Operation, format: Format, dynamic: bool) { +fn midpoint(code: &mut Code, operation: Operation, format: Format, dynamic: bool) { // Strip sign/exponent first. The second shift selects only the top fixed // fraction bits, including the enhanced Single table's eleven-bit input. - code.extend(SHL_RAX_IMMEDIATE); - code.push((GPR_BITS - format.fraction_bits()) as u8); + code.asm().shift_imm( + ShiftOp::Shl, + Size::Qword, + Rax, + (GPR_BITS - format.fraction_bits()) as u8, + ); if dynamic { - code.extend(MOV_ECX_R10D); - code.extend(SHR_RAX_CL); - xmm_to_gpr(code, INPUT_UNIT, GPR_RCX); - code.extend(OR_RAX_RCX); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rcx, R10); + asm.shift_cl(ShiftOp::Shr, Size::Qword, Rax); + xmm_to_gpr(code, INPUT_UNIT, Rcx); + code.asm().alu(Alu::Or, Size::Qword, Rax, Rcx); } else { - code.extend(SHR_RAX_IMMEDIATE); - code.push((GPR_BITS - STANDARD_INPUT_BITS) as u8); - immediate(code, &[OR_EAX_IMMEDIATE], 1 << STANDARD_INPUT_BITS); + code.asm().shift_imm( + ShiftOp::Shr, + Size::Qword, + Rax, + (GPR_BITS - STANDARD_INPUT_BITS) as u8, + ); + code.asm() + .alu_accumulator_imm32(Alu::Or, Size::Dword, 1 << STANDARD_INPUT_BITS); } if operation == Operation::Reciprocal { - code.extend(LEA_ECX_TWICE_RAX_PLUS_ONE); + code.asm().lea( + Size::Dword, + Rcx, + Mem::indexed(Rax, Rax, 1, 1).with_width(Disp::Byte), + ); } else { - code.extend(TEST_R8B_PARITY); - let odd = branch(code, JNZ_REL32); - code.extend(AND_EAX_EVEN); - code.extend(LEA_ECX_TWICE_RAX_PLUS_TWO); - let ready = branch(code, JMP_REL32); - let odd_start = code.len(); - resolve(code, odd, odd_start); - code.extend(SHR_EAX_ONE); - code.extend(LEA_ECX_TWICE_RAX_PLUS_ONE); - let end = code.len(); - resolve(code, ready, end); + let mut asm = code.asm(); + asm.test_imm(Size::Byte, R8, 1); + let odd = asm.jcc(Cond::Ne); + asm.alu_imm8(Alu::And, Size::Dword, Rax, -2); + asm.lea( + Size::Dword, + Rcx, + Mem::indexed(Rax, Rax, 1, 2).with_width(Disp::Byte), + ); + let ready = asm.jmp(); + asm.bind(odd); + asm.shift_one(ShiftOp::Shr, Size::Dword, Rax); + asm.lea( + Size::Dword, + Rcx, + Mem::indexed(Rax, Rax, 1, 1).with_width(Disp::Byte), + ); + asm.bind(ready); } } fn estimate( - code: &mut Vec, + code: &mut Code, operation: Operation, format: Format, dynamic: bool, target: TargetCpu, ) { if dynamic { - xmm_to_gpr(code, NUMERATOR, GPR_RAX); + xmm_to_gpr(code, NUMERATOR, Rax); } else { - immediate( - code, - &[MOV_EAX_IMMEDIATE], - numerator(operation, false) as u32, - ); + code.asm() + .mov_imm32(Rax, numerator(operation, false) as u32); } if dynamic && operation == Operation::ReciprocalSquareRoot { - code.extend(XOR_EDX_EDX); - code.extend(DIV_RCX); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); + asm.unary(Unary::Div, Size::Qword, Rcx); } else { - code.extend(XOR_EDX_EDX); - code.extend(DIV_ECX); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); + asm.unary(Unary::Div, Size::Dword, Rcx); } if operation == Operation::ReciprocalSquareRoot { // q=floor((2^n-1)/midpoint) is a positive integer below 2^28 in @@ -293,44 +230,51 @@ fn estimate( // root is below 2^14; for nonsquares distance to either neighboring // integer exceeds 2^-15, while RNE error is at most 2^-40. An exact // square rounds exactly. Truncating SQRTSD is consequently isqrt(q). - code.extend(CVTSI2SD_XMM2_RAX); + code.asm() + .cvtsi2float(FloatLanes::ScalarDouble, Size::Qword, 2, Rax); Host::SquareRootScalarDouble.register(code, ROOT, ROOT, target); - code.extend(CVTTSD2SI_RAX_XMM2); + code.asm() + .cvtfloat2si(FloatLanes::ScalarDouble, true, Size::Qword, Rax, Rm::Xmm(2)); } - code.extend(ADD_EAX_ONE); - code.extend(SHR_EAX_ONE); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Add, Size::Dword, Rax, 1); + asm.shift_one(ShiftOp::Shr, Size::Dword, Rax); if dynamic { - xmm_to_gpr(code, RESULT_UNIT, GPR_RDX); - code.extend(SUB_EAX_EDX); - code.extend(MOV_ECX_R11D); - code.extend(SHL_RAX_CL); + xmm_to_gpr(code, RESULT_UNIT, Rdx); + let mut asm = code.asm(); + asm.alu(Alu::Sub, Size::Dword, Rax, Rdx); + asm.mov(Size::Dword, Rcx, R11); + asm.shift_cl(ShiftOp::Shl, Size::Qword, Rax); } else { - immediate(code, &[SUB_EAX_IMMEDIATE], 1 << STANDARD_RESULT_BITS); - code.extend(SHL_RAX_IMMEDIATE); - code.push((format.fraction_bits() - STANDARD_RESULT_BITS) as u8); + code.asm() + .alu_accumulator_imm32(Alu::Sub, Size::Dword, 1 << STANDARD_RESULT_BITS); + code.asm().shift_imm( + ShiftOp::Shl, + Size::Qword, + Rax, + (format.fraction_bits() - STANDARD_RESULT_BITS) as u8, + ); } - code.extend(OR_RAX_R9); + code.asm().alu(Alu::Or, Size::Qword, Rax, R9); } -fn insert(code: &mut Vec, format: Format, lane: usize, checked: bool, target: TargetCpu) { +fn insert(code: &mut Code, format: Format, lane: usize, checked: bool, target: TargetCpu) { match format { Format::Half => { - code.extend(PINSRW_XMM1_EAX); - code.push(lane as u8); + code.asm().pinsrw(1, Rax, lane as u8); } Format::Single if checked => { assert!(target.supports(TargetCpu::Sse41)); - code.extend(PINSRD_XMM1_EAX); - code.push(lane as u8); + code.asm().pinsrd(1, Rax, lane as u8); } Format::Single | Format::Double => { // The unpredicated first lane initializes the complete chunk: // MOVQ clears its high64 bits. Later lanes only OR fresh disjoint // bits; no initial PXOR or first-lane temporary/OR is needed. let destination = if lane == 0 { RESULT } else { INSERT }; - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (destination << MODRM_REGISTER_SHIFT) | GPR_RAX); + code.asm() + .simd(Host::MoveGprQword, destination, Rax, target); if lane != 0 { ShiftOpcode::LeftBytes.emit( code, @@ -351,7 +295,7 @@ fn insert(code: &mut Vec, format: Format, lane: usize, checked: bool, target /// raised. Clobbers RAX/RCX/RDX/R8-R11, flags and XMM0-7; preserves the /// callee-saved GPRs, RDI/R15, the sources and the caller's MXCSR. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -387,38 +331,37 @@ pub(in crate::x86_64) fn emit( }; let frame = numerical::begin(code, length, &[Output::Z(operand.destination)], environment)?; if environment == Environment::PrivateMxcsr { - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); numerical::install_mxcsr(code, &frame); } let mut failures = Vec::new(); if features.full_a64() { test_ah(code); - let suppressed = branch(code, JNZ_REL32); + let suppressed = code.asm().jcc(Cond::Ne); Host::EqualDword.register(code, ACTIVE, ACTIVE, target); guard_active_exception_enables(code, ACTIVE, features, &mut failures, target); - let next = code.len(); - resolve(code, suppressed, next); + code.asm().bind(suppressed); } let dynamic = operand.format == Format::Single && features.rpres(); if dynamic { test_ah(code); - let standard = branch(code, JZ_REL32); + let standard = code.asm().jcc(Cond::E); constants(code, operation, operand.format, true, target); - let ready = branch(code, JMP_REL32); - let standard_start = code.len(); - resolve(code, standard, standard_start); + let mut asm = code.asm(); + let ready = asm.jmp(); + asm.bind(standard); constants(code, operation, operand.format, false, target); - let next = code.len(); - resolve(code, ready, next); + code.asm().bind(ready); } let element_bytes = operand.format.bits() as usize / u8::BITS as usize; for chunk in 0..length.chunks() { load_z_chunk(code, source, chunk, SOURCE, length, target); for lane in 0..VECTOR_CHUNK_BYTES / element_bytes { - xmm_to_gpr(code, SOURCE, GPR_RAX); + xmm_to_gpr(code, SOURCE, Rax); + let mut asm = code.asm(); match operand.format { - Format::Half => code.extend(MOVZX_EAX_AX), - Format::Single => code.extend(MOV_EAX_EAX), + Format::Half => asm.movzx(Size::Dword, Rax, Size::Word, Rax), + Format::Single => asm.mov(Size::Dword, Rax, Rax), Format::Double => (), } guard_normal(code, operation, operand.format, &mut failures); diff --git a/crates/stela-compiler/src/x86_64/sve/floating/fused.rs b/crates/stela-compiler/src/x86_64/sve/floating/fused.rs index e506382e22..4cd6ecb958 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/fused.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/fused.rs @@ -1,4 +1,6 @@ //! SVE fused multiply-add: FMA3, or an exact-product SSE2 path. +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -15,9 +17,8 @@ use crate::{ read_predicate_mask, }, simd::numerical::{ - ArithmeticOpcode, FusedOpcode, VZEROUPPER, emit_fma, emit_opcode_to, - prepare_vector_input_range, prepare_vector_result_range, rounding_control, - vector_exponent_range, + ArithmeticOpcode, FusedOpcode, emit_fma, emit_opcode_to, prepare_vector_input_range, + prepare_vector_result_range, rounding_control, vector_exponent_range, }, sve::floating::classify::guard_active_exception_enables, }, @@ -31,9 +32,6 @@ const CONSTANT_SCRATCH: u8 = 3; const ADDEND: u8 = 6; const ACTIVE: u8 = 7; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; const SINGLE_BROADCAST_STRIDE: u8 = 0x55; const DOUBLE_LOW_BROADCAST: u8 = 0x44; const DOUBLE_HIGH_BROADCAST: u8 = 0xee; @@ -42,41 +40,34 @@ const BENIGN_ADDEND_INCREMENT: u32 = 1; const MXCSR_INEXACT: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; const MXCSR_TO_FPSR_INEXACT_SHIFT: u8 = 1; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const TEST_ECX_ECX: &[u8] = &[0x85, 0xc9]; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -fn reject(code: &mut Vec, failures: &mut Vec) { - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); +fn reject(code: &mut Code, failures: &mut Vec) { + failures.push(code.asm().jcc(Cond::Ne).offset()); } -fn broadcast(code: &mut Vec, format: Format, bits: u64, target: TargetCpu) { +fn broadcast(code: &mut Code, format: Format, bits: u64, target: TargetCpu) { if format == Format::Single { - code.push(MOV_EAX_IMMEDIATE); - code.extend((bits as u32).to_le_bytes()); + code.asm().mov_imm32(Rax, bits as u32); } else { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(bits.to_le_bytes()); + code.asm().mov_imm64(Rax, bits); } - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (CONSTANT_SCRATCH << MODRM_REGISTER_SHIFT) | GPR_RAX); + code.asm() + .simd(Host::MoveGprQword, CONSTANT_SCRATCH, Rax, target); if format == Format::Single { - Host::ShuffleDword.register(code, CONSTANT_SCRATCH, CONSTANT_SCRATCH, target); - code.push(REPEAT_LOW_DWORD); + code.asm().simd_imm( + Host::ShuffleDword, + CONSTANT_SCRATCH, + Rm::Xmm(CONSTANT_SCRATCH), + REPEAT_LOW_DWORD, + target, + ); } else { Host::UnpackLowQword.register(code, CONSTANT_SCRATCH, CONSTANT_SCRATCH, target); } } /// Inactive 2 + 1*1 and every signed variant are exact normal results. -fn benign_inactive(code: &mut Vec, format: Format, input: u8, target: TargetCpu) { +fn benign_inactive(code: &mut Code, format: Format, input: u8, target: TargetCpu) { let increment = if input == ADDEND { BENIGN_ADDEND_INCREMENT } else { @@ -91,7 +82,7 @@ fn benign_inactive(code: &mut Vec, format: Format, input: u8, target: Target } fn load_right( - code: &mut Vec, + code: &mut Code, source: Source, format: Format, chunk: usize, @@ -115,17 +106,12 @@ fn load_right( } Format::Half => unreachable!("Half uses exact completion"), }; - Host::ShuffleDword.register(code, RIGHT, RIGHT, target); - code.push(order); + code.asm() + .simd_imm(Host::ShuffleDword, RIGHT, Rm::Xmm(RIGHT), order, target); } } -fn negate_baseline( - code: &mut Vec, - operation: FusedOperation, - format: Format, - target: TargetCpu, -) { +fn negate_baseline(code: &mut Code, operation: FusedOperation, format: Format, target: TargetCpu) { if !operation.negate_left() && !operation.negate_addend() { return; } @@ -144,21 +130,12 @@ fn negate_baseline( } } -fn fused_opcode(operation: FusedOperation) -> FusedOpcode { - match operation { - FusedOperation::Add => FusedOpcode::MultiplyAdd, - FusedOperation::Subtract => FusedOpcode::NegativeMultiplyAdd, - FusedOperation::NegatedAdd => FusedOpcode::NegativeMultiplySubtract, - FusedOperation::NegatedSubtract => FusedOpcode::MultiplySubtract, - } -} - /// Emit the fourteen fused forms, natively only for normal single and double /// values; software completion handles the rest. RDI/R15 and the guest sources /// survive; RAX/RCX/RDX, flags and XMM0-7 are clobbered. `TargetCpu::Fma` /// implies OS-enabled AVX state; the baseline target never emits VEX. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -234,12 +211,12 @@ pub(in crate::x86_64) fn emit( code, operand.format, Shape::Vector128, - fused_opcode(operation), + FusedOpcode::from(operation), target, ); // FMA has completed; clean upper AVX state before legacy guards or any exit. // Every host SIMD register is caller-volatile under this backend ABI. - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } else { negate_baseline(code, operation, operand.format, target); emit_opcode_to( @@ -253,7 +230,7 @@ pub(in crate::x86_64) fn emit( // An exact normal product allows a separate ADD with one rounding; // any product status rejects the instruction. numerical::capture_status(code, &frame); - code.extend(TEST_ECX_ECX); + code.asm().test(Size::Dword, Rcx, Rcx); reject(code, &mut failures); prepare_vector_result_range(code); vector_exponent_range(code, operand.format, Shape::Vector128, LEFT); @@ -272,14 +249,13 @@ pub(in crate::x86_64) fn emit( vector_exponent_range(code, operand.format, Shape::Vector128, LEFT); reject(code, &mut failures); numerical::capture_status(code, &frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_OTHER_STATUS as i32); reject(code, &mut failures); - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_INEXACT.to_le_bytes()); - code.extend(SHR_EAX_IMMEDIATE); - code.push(MXCSR_TO_FPSR_INEXACT_SHIFT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_INEXACT as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, MXCSR_TO_FPSR_INEXACT_SHIFT); numerical::add_fpsr(code, &frame); if operand.predicate.is_some() { load_z_chunk(code, operand.destination, chunk, RIGHT, length, target); diff --git a/crates/stela-compiler/src/x86_64/sve/floating/half_dot.rs b/crates/stela-compiler/src/x86_64/sve/floating/half_dot.rs index af53da8a4c..22012d56ac 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/half_dot.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/half_dot.rs @@ -1,5 +1,9 @@ //! SVE half-precision FDOT and FMLALB/FMLALT. Half products are exact singles, so //! the pair add and accumulator add keep their two separate roundings. +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::FloatOp; +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, @@ -16,7 +20,7 @@ use crate::{ numerical::{self, Environment, Output}, }, simd::numerical::{ - Condition, FusedOpcode, branch, emit_fma, prepare_vector_input_range, rounding_control, + FusedOpcode, emit_fma, prepare_vector_input_range, rounding_control, vector_half_exponent_range, widen_half_to_single, }, sve::floating::classify::{ @@ -37,9 +41,6 @@ const WIDEN_BIAS: u8 = 7; const CLASSIFICATION_CONSTANTS: [u8; 2] = [WIDEN_SIGN, ZERO]; const CLASSIFICATION_SCRATCH: [u8; 3] = [RIGHT_HIGH, LEFT_HIGH, WIDEN_BIAS]; const OUTPUT_SLOT: usize = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const GPR_RAX: u8 = 0; const HALF_BYTES: usize = size_of::(); const SINGLE_DWORD_BYTES: usize = size_of::(); const SINGLE_LANES_PER_CHUNK: usize = VECTOR_CHUNK_BYTES / SINGLE_DWORD_BYTES; @@ -59,19 +60,8 @@ const HALF_TO_SINGLE_BIAS: u32 = (Format::Single.exponent_bias() - Format::Half. const MXCSR_INEXACT: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; const MXCSR_TO_FPSR_INEXACT_SHIFT: u8 = 1; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; const BOTTOM_HALF_BYTES: [u8; 8] = [0, 1, 4, 5, 8, 9, 12, 13]; const TOP_HALF_BYTES: [u8; 8] = [2, 3, 6, 7, 10, 11, 14, 15]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const MULPS: &[u8] = &[0x0f, 0x59]; -const ADDPS: &[u8] = &[0x0f, 0x58]; -const SUBPS: &[u8] = &[0x0f, 0x5c]; -const SHUFPS: &[u8] = &[0x0f, 0xc6]; -const VZEROUPPER: &[u8] = &[0xc5, 0xf8, 0x77]; /// Which native kernels to use. #[derive(Debug, Clone, Copy, Default)] @@ -81,18 +71,13 @@ pub(in crate::x86_64) struct Recipe { pub fused_widening: bool, } -fn register(code: &mut Vec, opcode: &[u8], destination: u8, source: u8) { - code.extend(opcode); - code.push(MODRM_REGISTER | destination << MODRM_REGISTER_SHIFT | source); +fn shuffle(code: &mut Code, opcode: Host, vector: u8, order: u8, target: TargetCpu) { + code.asm() + .simd_imm(opcode, vector, Rm::Xmm(vector), order, target); } -fn shuffle(code: &mut Vec, opcode: Host, vector: u8, order: u8, target: TargetCpu) { - opcode.register(code, vector, vector, target); - code.push(order); -} - -fn reject(code: &mut Vec, failures: &mut Vec) { - failures.push(branch(code, Condition::NotZero)); +fn reject(code: &mut Code, failures: &mut Vec) { + failures.push(code.asm().jcc(Cond::Ne).offset()); } fn source_register(right: RightOperand) -> u8 { @@ -102,7 +87,7 @@ fn source_register(right: RightOperand) -> u8 { } /// Compact H0/H2/H4/H6 or H1/H3/H5/H7 into the low four Half fields. -fn select_part(code: &mut Vec, vector: u8, part: VectorPart, target: TargetCpu) { +fn select_part(code: &mut Code, vector: u8, part: VectorPart, target: TargetCpu) { let order = match part { VectorPart::Bottom => BOTTOM_WORD_ORDER, VectorPart::Top => TOP_WORD_ORDER, @@ -112,7 +97,7 @@ fn select_part(code: &mut Vec, vector: u8, part: VectorPart, target: TargetC shuffle(code, Host::ShuffleDword, vector, GROUP_DWORD_ORDER, target); } -fn select_sources(code: &mut Vec, operand: Operand, recipe: Recipe, target: TargetCpu) { +fn select_sources(code: &mut Code, operand: Operand, recipe: Recipe, target: TargetCpu) { match operand.kind { Kind::HalfDot => { if let RightOperand::Indexed { index, .. } = operand.right { @@ -132,10 +117,9 @@ fn select_sources(code: &mut Vec, operand: Operand, recipe: Recipe, target: VectorPart::Bottom => BOTTOM_HALF_BYTES, VectorPart::Top => TOP_HALF_BYTES, }; - code.extend(MOV_RAX_IMMEDIATE); - code.extend(u64::from_le_bytes(selector).to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | RIGHT_HIGH << MODRM_REGISTER_SHIFT | GPR_RAX); + let mut asm = code.asm(); + asm.mov_imm64(Rax, u64::from_le_bytes(selector)); + asm.simd(Host::MoveGprQword, RIGHT_HIGH, Rax, target); // The upper selector can repeat: widening consumes only low64. Host::UnpackLowQword.register(code, RIGHT_HIGH, RIGHT_HIGH, target); Host::ByteShuffle.register(code, LEFT, RIGHT_HIGH, target); @@ -159,12 +143,11 @@ fn select_sources(code: &mut Vec, operand: Operand, recipe: Recipe, target: } } -fn prepare_widening(code: &mut Vec, target: TargetCpu) { +fn prepare_widening(code: &mut Code, target: TargetCpu) { Host::Xor.register(code, ZERO, ZERO, target); - code.push(MOV_EAX_IMMEDIATE); - code.extend(HALF_TO_SINGLE_BIAS.to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | WIDEN_BIAS << MODRM_REGISTER_SHIFT | GPR_RAX); + let mut asm = code.asm(); + asm.mov_imm32(Rax, HALF_TO_SINGLE_BIAS); + asm.simd(Host::MoveGprQword, WIDEN_BIAS, Rax, target); shuffle( code, Host::ShuffleDword, @@ -174,7 +157,7 @@ fn prepare_widening(code: &mut Vec, target: TargetCpu) { ); } -fn widen(code: &mut Vec, vector: u8, recipe: Recipe, target: TargetCpu) { +fn widen(code: &mut Code, vector: u8, recipe: Recipe, target: TargetCpu) { if recipe.half_convert { Host::ConvertHalfToSingle.register(code, vector, vector, target); } else { @@ -182,7 +165,7 @@ fn widen(code: &mut Vec, vector: u8, recipe: Recipe, target: TargetCpu) { } } -fn dot(code: &mut Vec, operand: Operand, recipe: Recipe, target: TargetCpu) { +fn dot(code: &mut Code, operand: Operand, recipe: Recipe, target: TargetCpu) { Host::MoveAligned.register(code, LEFT_HIGH, LEFT, target); ShiftOpcode::RightBytes.emit(code, LEFT_HIGH, HALF_GROUP_BYTES); let indexed = matches!(operand.right, RightOperand::Indexed { .. }); @@ -199,25 +182,34 @@ fn dot(code: &mut Vec, operand: Operand, recipe: Recipe, target: TargetCpu) if !indexed { widen(code, RIGHT_HIGH, recipe, target); } - register(code, MULPS, LEFT, RIGHT); - register( - code, - MULPS, + let mut asm = code.asm(); + asm.float(FloatOp::Mul, FloatLanes::PackedSingle, LEFT, Rm::Xmm(RIGHT)); + asm.float( + FloatOp::Mul, + FloatLanes::PackedSingle, LEFT_HIGH, - if indexed { RIGHT } else { RIGHT_HIGH }, + Rm::Xmm(if indexed { RIGHT } else { RIGHT_HIGH }), + ); + asm.simd(Host::MoveAligned, RIGHT_HIGH, Rm::Xmm(LEFT), target); + asm.shufps(LEFT, Rm::Xmm(LEFT_HIGH), EVEN_PRODUCT_ORDER); + asm.shufps(RIGHT_HIGH, Rm::Xmm(LEFT_HIGH), ODD_PRODUCT_ORDER); + asm.float( + FloatOp::Add, + FloatLanes::PackedSingle, + LEFT, + Rm::Xmm(RIGHT_HIGH), ); - Host::MoveAligned.register(code, RIGHT_HIGH, LEFT, target); - register(code, SHUFPS, LEFT, LEFT_HIGH); - code.push(EVEN_PRODUCT_ORDER); - register(code, SHUFPS, RIGHT_HIGH, LEFT_HIGH); - code.push(ODD_PRODUCT_ORDER); - register(code, ADDPS, LEFT, RIGHT_HIGH); // The preceding ADDPS is the architectural FPDot rounding. This ADDPS is // a separate FPAdd; never combine either with an accumulator FMA. - register(code, ADDPS, LEFT, ADDEND); + asm.float( + FloatOp::Add, + FloatLanes::PackedSingle, + LEFT, + Rm::Xmm(ADDEND), + ); } -fn multiply_long(code: &mut Vec, subtract: bool, recipe: Recipe, target: TargetCpu) { +fn multiply_long(code: &mut Code, subtract: bool, recipe: Recipe, target: TargetCpu) { if !recipe.half_convert { prepare_widening(code, target); } @@ -237,18 +229,29 @@ fn multiply_long(code: &mut Vec, subtract: bool, recipe: Recipe, target: Tar target, ); } else { - register(code, MULPS, LEFT, RIGHT); + let mut asm = code.asm(); + asm.float(FloatOp::Mul, FloatLanes::PackedSingle, LEFT, Rm::Xmm(RIGHT)); if subtract { - register(code, SUBPS, ADDEND, LEFT); - Host::MoveAligned.register(code, LEFT, ADDEND, target); + asm.float( + FloatOp::Sub, + FloatLanes::PackedSingle, + ADDEND, + Rm::Xmm(LEFT), + ); + asm.simd(Host::MoveAligned, LEFT, Rm::Xmm(ADDEND), target); } else { - register(code, ADDPS, LEFT, ADDEND); + asm.float( + FloatOp::Add, + FloatLanes::PackedSingle, + LEFT, + Rm::Xmm(ADDEND), + ); } } } pub(in crate::x86_64) fn emit_candidate( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -271,7 +274,7 @@ pub(in crate::x86_64) fn emit_candidate( )); } if recipe.half_convert || recipe.fused_widening { - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } let frame = numerical::begin( code, @@ -328,21 +331,20 @@ pub(in crate::x86_64) fn emit_candidate( numerical::stage_vector_chunk(code, &frame, OUTPUT_SLOT, chunk, LEFT, target); } numerical::capture_status(code, &frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_OTHER_STATUS as i32); reject(code, &mut failures); - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_INEXACT.to_le_bytes()); - code.extend(SHR_EAX_IMMEDIATE); - code.push(MXCSR_TO_FPSR_INEXACT_SHIFT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_INEXACT as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, MXCSR_TO_FPSR_INEXACT_SHIFT); numerical::add_fpsr(code, &frame); numerical::finish(code, &frame, &failures, pc, target); Ok(true) } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -376,7 +378,6 @@ pub(in crate::x86_64) fn emit( #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; const DESTINATION: u8 = 0; const LEFT_SOURCE: u8 = 1; @@ -413,15 +414,15 @@ mod tests { changes_default: bool, ) { let length = VectorLength::from_bytes(bytes).unwrap(); - let mut selected = Vec::new(); + let mut selected = Code::new(); assert!(emit(&mut selected, operand, length, FEATURES, PC, target).unwrap()); - let mut expected = Vec::new(); + let mut expected = Code::new(); assert!( emit_candidate(&mut expected, operand, length, FEATURES, PC, target, recipe,).unwrap() ); assert_eq!(selected, expected, "{operand:?}, {bytes}, {target:?}"); if changes_default { - let mut baseline = Vec::new(); + let mut baseline = Code::new(); assert!( emit_candidate( &mut baseline, @@ -538,7 +539,7 @@ mod tests { ..Recipe::default() }; for target in [TargetCpu::Baseline, TargetCpu::F16c, TargetCpu::Fma] { - let mut code = Vec::new(); + let mut code = Code::new(); assert!( emit_candidate( &mut code, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/indexed_half.rs b/crates/stela-compiler/src/x86_64/sve/floating/indexed_half.rs index ba0d8ba93a..1f6f8cd611 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/indexed_half.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/indexed_half.rs @@ -1,4 +1,6 @@ //! SVE indexed half-precision arithmetic through exact double intermediates. +use crate::x86_64::asm::Gpr::{R9, R10, R11, Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Alu, Code, Rm, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, @@ -19,7 +21,7 @@ use crate::{ }, simd::{ half::{self, ResultSign, RoundingPolicy}, - numerical::{ArithmeticOpcode, Condition, VZEROUPPER, branch, emit_opcode_to, resolve}, + numerical::{ArithmeticOpcode, Condition, branch, emit_opcode_to, resolve}, }, sve::floating::classify::guard_active_exception_enables, }, @@ -35,9 +37,6 @@ const ORIGINAL_RIGHT: u8 = 5; const RESULT: u8 = 6; const ASSEMBLED: u8 = 7; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; const HALF_BYTES: usize = size_of::(); const HALF_LANES: usize = VECTOR_CHUNK_BYTES / HALF_BYTES; const FIRST_HALF: u8 = 0; @@ -49,10 +48,6 @@ const DUPLICATE_REAL_WORDS: u8 = 0xa0; const DUPLICATE_IMAGINARY_WORDS: u8 = 0xf5; const SWAP_WORD_COMPONENTS: u8 = 0xb1; const SIGN_MASK: u8 = ADDEND; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const XOR_R11D_R11D: &[u8] = &[0x45, 0x31, 0xdb]; -const INC_R11D: &[u8] = &[0x41, 0xff, 0xc3]; -const CMP_R11D_IMMEDIATE: &[u8] = &[0x41, 0x83, 0xfb]; const NORMAL_HALF_EXPONENT_COUNT: u32 = (Format::Half.exponent_mask() >> Format::Half.fraction_bits()) as u32 - 1; const FIRST_NORMAL_HALF_EXPONENT: u32 = 1 << Format::Half.fraction_bits(); @@ -60,17 +55,6 @@ const HALF_TO_DOUBLE_BIAS: u64 = ((Format::Double.exponent_bias() - Format::Half as u64) << Format::Double.fraction_bits(); const MXCSR_STATUS_MASK: u32 = 0x3f; -const PEXTRW_EAX_XMM: &[u8] = &[0x66, 0x0f, 0xc5]; -const PINSRW_XMM_EAX: &[u8] = &[0x66, 0x0f, 0xc4]; -const MOV_EDX_EAX: &[u8] = &[0x89, 0xc2]; -const AND_EDX_IMMEDIATE: &[u8] = &[0x81, 0xe2]; -const SUB_EDX_IMMEDIATE: &[u8] = &[0x81, 0xea]; -const CMP_EDX_IMMEDIATE: &[u8] = &[0x81, 0xfa]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; -const MOVABS_R9_IMMEDIATE: &[u8] = &[0x49, 0xb9]; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const MOV_EAX_R10D: &[u8] = &[0x44, 0x89, 0xd0]; #[derive(Debug, Clone, Copy, Default)] pub(in crate::x86_64) enum Recipe { @@ -157,14 +141,14 @@ fn admitted(operand: Operand) -> Option { } } -fn shuffle(code: &mut Vec, opcode: Host, register: u8, order: u8, target: TargetCpu) { - opcode.register(code, register, register, target); - code.push(order); +fn shuffle(code: &mut Code, opcode: Host, register: u8, order: u8, target: TargetCpu) { + code.asm() + .simd_imm(opcode, register, Rm::Xmm(register), order, target); } /// Materialize the effective eight Half fields once per segment. Real and /// imaginary selection occurs before any classification or FP conversion. -fn select_sources(code: &mut Vec, operation: Operation, target: TargetCpu) { +fn select_sources(code: &mut Code, operation: Operation, target: TargetCpu) { let sign = Format::Half.sign_mask() as u32; let sign_pair = if let Some(rotation) = operation.rotation { let imaginary = matches!(rotation, Rotation::Degrees90 | Rotation::Degrees270); @@ -229,10 +213,8 @@ fn select_sources(code: &mut Vec, operation: Operation, target: TargetCpu) { } }; if sign_pair != 0 { - code.push(MOV_EAX_IMMEDIATE); - code.extend(sign_pair.to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (SIGN_MASK << MODRM_REGISTER_SHIFT) | GPR_RAX); + code.asm().mov_imm32(Rax, sign_pair); + code.asm().simd(Host::MoveGprQword, SIGN_MASK, Rax, target); shuffle( code, Host::ShuffleDword, @@ -248,22 +230,33 @@ fn select_sources(code: &mut Vec, operation: Operation, target: TargetCpu) { /// never reach a hardware conversion. The unsigned interval admits exponents /// 1..30, rejecting zeros, subnormals, infinities and every NaN payload. fn widen_input( - code: &mut Vec, + code: &mut Code, original: u8, output: u8, failures: &mut Vec, target: TargetCpu, ) { - code.extend(PEXTRW_EAX_XMM); - code.push(MODRM_REGISTER | (GPR_RAX << MODRM_REGISTER_SHIFT) | original); - code.push(FIRST_HALF); - code.extend(MOV_EDX_EAX); - code.extend(AND_EDX_IMMEDIATE); - code.extend((Format::Half.exponent_mask() as u32).to_le_bytes()); - code.extend(SUB_EDX_IMMEDIATE); - code.extend(FIRST_NORMAL_HALF_EXPONENT.to_le_bytes()); - code.extend(CMP_EDX_IMMEDIATE); - code.extend((NORMAL_HALF_EXPONENT_COUNT << Format::Half.fraction_bits()).to_le_bytes()); + code.asm().pextrw(Rax, original, FIRST_HALF); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rdx, Rax); + asm.alu_imm32( + Alu::And, + Size::Dword, + Rdx, + Format::Half.exponent_mask() as i32, + ); + asm.alu_imm32( + Alu::Sub, + Size::Dword, + Rdx, + FIRST_NORMAL_HALF_EXPONENT as i32, + ); + asm.alu_imm32( + Alu::Cmp, + Size::Dword, + Rdx, + (NORMAL_HALF_EXPONENT_COUNT << Format::Half.fraction_bits()) as i32, + ); failures.push(branch(code, Condition::AboveOrEqual)); half::widen_normal(code, target); Host::MoveAligned.register(code, output, RESULT, target); @@ -272,7 +265,7 @@ fn widen_input( /// Optional selection changes only exact input widening. No feature is assumed /// from the guest profile; unsupported checked selection declines untouched. pub(in crate::x86_64) fn emit_candidate( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -297,11 +290,11 @@ pub(in crate::x86_64) fn emit_candidate( &[Output::Z(operand.destination)], Environment::PrivateMxcsr, )?; - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); numerical::install_mxcsr(code, &frame); - code.extend(MOVABS_R9_IMMEDIATE); - code.extend(HALF_TO_DOUBLE_BIAS.to_le_bytes()); - code.extend(XOR_R10D_R10D); + let mut asm = code.asm(); + asm.mov_imm64(R9, HALF_TO_DOUBLE_BIAS); + asm.alu(Alu::Xor, Size::Dword, R10, R10); let mut failures = Vec::new(); Host::EqualDword.register(code, ASSEMBLED, ASSEMBLED, target); guard_active_exception_enables(code, ASSEMBLED, features, &mut failures, target); @@ -320,7 +313,7 @@ pub(in crate::x86_64) fn emit_candidate( } Host::Xor.register(code, ASSEMBLED, ASSEMBLED, target); select_sources(code, operation, target); - code.extend(XOR_R11D_R11D); + code.asm().alu(Alu::Xor, Size::Dword, R11, R11); let repeat = code.len(); widen_input(code, ORIGINAL_LEFT, LEFT, &mut failures, widening_target); @@ -357,8 +350,8 @@ pub(in crate::x86_64) fn emit_candidate( // single half rounding, so no rounded intermediate or lost exception // reaches the packer. numerical::capture_status(code, &frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_STATUS_MASK.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_STATUS_MASK as i32); failures.push(branch(code, Condition::NotZero)); Host::MoveAligned.register(code, RESULT, LEFT, target); half::pack_normal( @@ -368,33 +361,31 @@ pub(in crate::x86_64) fn emit_candidate( ResultSign::Preserve, ); ShiftOpcode::RightBytes.emit(code, ASSEMBLED, HALF_BYTES as u8); - code.extend(PINSRW_XMM_EAX); - code.push(MODRM_REGISTER | (ASSEMBLED << MODRM_REGISTER_SHIFT) | GPR_RAX); - code.push(LAST_HALF); + code.asm().pinsrw(ASSEMBLED, Rax, LAST_HALF); for input in [ORIGINAL_LEFT, ORIGINAL_RIGHT] { ShiftOpcode::RightBytes.emit(code, input, HALF_BYTES as u8); } if operation.fused { ShiftOpcode::RightBytes.emit(code, ORIGINAL_ADDEND, HALF_BYTES as u8); } - code.extend(INC_R11D); - code.extend(CMP_R11D_IMMEDIATE); - code.push(HALF_LANES as u8); + let mut asm = code.asm(); + asm.inc(Size::Dword, R11); + asm.alu_imm8(Alu::Cmp, Size::Dword, R11, HALF_LANES as i8); let more = branch(code, Condition::Below); resolve(code, more, repeat); numerical::stage_vector_chunk(code, &frame, OUTPUT_SLOT, chunk, ASSEMBLED, target); } if matches!(recipe, Recipe::CheckedWidening) { - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } - code.extend(MOV_EAX_R10D); + code.asm().mov(Size::Dword, Rax, R10); numerical::add_fpsr(code, &frame); numerical::finish(code, &frame, &failures, pc, target); Ok(true) } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -433,7 +424,6 @@ fn selected_recipe(operand: Operand, length: VectorLength, target: TargetCpu) -> mod tests { use super::*; use crate::aarch64::sve::floating::arithmetic; - use alloc::vec::Vec; const INDEXED_FCMLA_HALF: u32 = 0x64a21020; const INDEXED_FMLA_HALF: u32 = 0x64220020; @@ -463,8 +453,8 @@ mod tests { && matches!(word, INDEXED_FMLA_HALF | INDEXED_FMLS_HALF)); let recipe = selected_recipe(operand, length, target); assert_eq!(matches!(recipe, Recipe::CheckedWidening), checked); - let mut selected = Vec::new(); - let mut explicit = Vec::new(); + let mut selected = Code::new(); + let mut explicit = Code::new(); let features = NumericalFeatures::new(false, true, true); let pc = GuestAddress(0x123456789abcdef0); assert!(emit(&mut selected, operand, length, features, pc, target).unwrap()); diff --git a/crates/stela-compiler/src/x86_64/sve/floating/minmax.rs b/crates/stela-compiler/src/x86_64/sve/floating/minmax.rs index b3f24ffc38..700c2c9b71 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/minmax.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/minmax.rs @@ -1,5 +1,9 @@ //! SVE single/double min/max. NaNs, subnormals and zero/zero ties use software //! completion. +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::FloatOp; +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Code, Cond, Rm, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -33,24 +37,9 @@ const ZERO_VECTOR: u8 = CLASSIFICATION_SCRATCH[1]; const DOUBLE_ZERO_SCRATCH: u8 = CLASSIFICATION_SCRATCH[2]; const OLD_DESTINATION: u8 = CLASSIFICATION_SCRATCH[0]; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const SSE_ESCAPE: u8 = 0x0f; -const PACKED_DOUBLE_PREFIX: u8 = 0x66; const REMOVE_SIGN_BITS: u8 = 1; const REPEAT_LOW_DWORD: u8 = 0; const SWAP_ADJACENT_DWORDS: u8 = 0xb1; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; - -#[repr(u8)] -enum SelectionOpcode { - Minimum = 0x5d, - Maximum = 0x5f, -} fn inputs(operand: Operand) -> Option<(MinMaxOperation, u8, Source, u8)> { let Kind::MinMax(operation) = operand.kind else { @@ -79,23 +68,25 @@ fn inputs(operand: Operand) -> Option<(MinMaxOperation, u8, Source, u8)> { Some((operation, left, right, predicate)) } -fn immediate(code: &mut Vec, format: Format, bits: u64, target: TargetCpu) { +fn immediate(code: &mut Code, format: Format, bits: u64, target: TargetCpu) { if bits == 0 { Host::Xor.register(code, RIGHT, RIGHT, target); return; } if format == Format::Single { - code.push(MOV_EAX_IMMEDIATE); - code.extend((bits as u32).to_le_bytes()); + code.asm().mov_imm32(Rax, bits as u32); } else { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(bits.to_le_bytes()); + code.asm().mov_imm64(Rax, bits); } - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (RIGHT << MODRM_REGISTER_SHIFT) | GPR_RAX); + code.asm().simd(Host::MoveGprQword, RIGHT, Rax, target); if format == Format::Single { - Host::ShuffleDword.register(code, RIGHT, RIGHT, target); - code.push(REPEAT_LOW_DWORD); + code.asm().simd_imm( + Host::ShuffleDword, + RIGHT, + Rm::Xmm(RIGHT), + REPEAT_LOW_DWORD, + target, + ); } else { Host::UnpackLowQword.register(code, RIGHT, RIGHT, target); } @@ -105,8 +96,8 @@ fn immediate(code: &mut Vec, format: Format, bits: u64, target: TargetCpu) { /// after OR accepts exactly-one-zero inputs while retaining every signed-zero /// tie for the shared semantic helper. Double requires both dwords to be zero. /// LEFT/RIGHT/ACTIVE and the invariant classification masks remain live. -fn guard_zero_pairs( - code: &mut Vec, +pub(super) fn guard_zero_pairs( + code: &mut Code, format: Format, failures: &mut Vec, target: TargetCpu, @@ -122,31 +113,34 @@ fn guard_zero_pairs( Host::Xor.register(code, ZERO_VECTOR, ZERO_VECTOR, target); Host::EqualDword.register(code, ZERO_PAIR, ZERO_VECTOR, target); if format == Format::Double { - Host::ShuffleDword.register(code, DOUBLE_ZERO_SCRATCH, ZERO_PAIR, target); - code.push(SWAP_ADJACENT_DWORDS); + code.asm().simd_imm( + Host::ShuffleDword, + DOUBLE_ZERO_SCRATCH, + Rm::Xmm(ZERO_PAIR), + SWAP_ADJACENT_DWORDS, + target, + ); Host::And.register(code, ZERO_PAIR, DOUBLE_ZERO_SCRATCH, target); } Host::And.register(code, ZERO_PAIR, ACTIVE, target); - Host::ByteSignMask.register(code, GPR_RAX, ZERO_PAIR, target); - code.extend(TEST_EAX_EAX); - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); + code.asm() + .simd_to_gpr(Host::ByteSignMask, Rax, ZERO_PAIR, target); + code.asm().test(Size::Dword, Rax, Rax); + failures.push(code.asm().jcc(Cond::Ne).offset()); } -fn selection(code: &mut Vec, operation: MinMaxOperation, format: Format) { - let opcode = match operation { - MinMaxOperation::Minimum | MinMaxOperation::MinimumNumber => SelectionOpcode::Minimum, - MinMaxOperation::Maximum | MinMaxOperation::MaximumNumber => SelectionOpcode::Maximum, - }; - if format == Format::Double { - code.push(PACKED_DOUBLE_PREFIX); +pub(super) fn selection(code: &mut Code, operation: MinMaxOperation, format: Format) { + let minimum = matches!( + operation, + MinMaxOperation::Minimum | MinMaxOperation::MinimumNumber + ); + let mut asm = code.asm(); + match (format == Format::Double, minimum) { + (true, true) => asm.float(FloatOp::Min, FloatLanes::PackedDouble, LEFT, Rm::Xmm(RIGHT)), + (true, false) => asm.float(FloatOp::Max, FloatLanes::PackedDouble, LEFT, Rm::Xmm(RIGHT)), + (false, true) => asm.float(FloatOp::Min, FloatLanes::PackedSingle, LEFT, Rm::Xmm(RIGHT)), + (false, false) => asm.float(FloatOp::Max, FloatLanes::PackedSingle, LEFT, Rm::Xmm(RIGHT)), } - code.extend([ - SSE_ESCAPE, - opcode as u8, - MODRM_REGISTER | (LEFT << MODRM_REGISTER_SHIFT) | RIGHT, - ]); } /// Emit the eight predicated vector and immediate min/max forms. Half precision @@ -155,7 +149,7 @@ fn selection(code: &mut Vec, operation: MinMaxOperation, format: Format) { /// MXCSR and add no FPSR bits. Clobbers RAX/RCX/RDX, flags and XMM0-7; /// preserves RDI/R15 and NZCV. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -274,7 +268,7 @@ mod tests { ..base }, ] { - let mut code = vec![0x90]; + let mut code = Code::from(vec![0x90]); assert!( !emit( &mut code, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/pairwise_clamp.rs b/crates/stela-compiler/src/x86_64/sve/floating/pairwise_clamp.rs index 588bfbe3ec..a25ee3e11b 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/pairwise_clamp.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/pairwise_clamp.rs @@ -1,4 +1,6 @@ //! SVE pairwise min/max and FCLAMP. +use super::minmax::{guard_zero_pairs, selection}; +use crate::x86_64::asm::{Code, Rm}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -7,7 +9,7 @@ use crate::{ sve::floating::arithmetic::{Inputs, Kind, Operand, ResultShape}, }, x86_64::{ - isa::{ShiftOpcode, SimdOpcode as Host}, + isa::SimdOpcode as Host, scalable::{ load_z_chunk, numerical::{self, Environment, Output}, @@ -25,88 +27,27 @@ const ACTIVE: u8 = 2; const CLASSIFICATION_SCRATCH: [u8; 3] = [3, 4, 5]; const PREDICATE_SCRATCH: u8 = CLASSIFICATION_SCRATCH[0]; const CLASSIFICATION_MASKS: [u8; 2] = [6, 7]; -const ZERO_PAIR: u8 = CLASSIFICATION_SCRATCH[0]; -const ZERO_VECTOR: u8 = CLASSIFICATION_SCRATCH[1]; -const DOUBLE_ZERO_SCRATCH: u8 = CLASSIFICATION_SCRATCH[2]; const OLD_DESTINATION: u8 = CLASSIFICATION_SCRATCH[0]; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const SSE_ESCAPE: u8 = 0x0f; -const PACKED_DOUBLE_PREFIX: u8 = 0x66; -const REMOVE_SIGN_BITS: u8 = 1; -const SWAP_ADJACENT_DWORDS: u8 = 0xb1; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; - -#[repr(u8)] -enum SelectionOpcode { - Minimum = 0x5d, - Maximum = 0x5f, -} - -/// Reject only active pairs whose two magnitudes are zero. Removing the sign -/// after OR accepts exactly-one-zero inputs while retaining every signed-zero -/// tie for the shared semantic helper. Double requires both dwords to be zero. -/// LEFT/RIGHT/ACTIVE and the invariant classification masks remain live. -fn guard_zero_pairs( - code: &mut Vec, - format: Format, - failures: &mut Vec, - target: TargetCpu, -) { - Host::MoveAligned.register(code, ZERO_PAIR, LEFT, target); - Host::Or.register(code, ZERO_PAIR, RIGHT, target); - match format { - Format::Single => ShiftOpcode::LeftDword, - Format::Double => ShiftOpcode::LeftQword, - Format::Half => unreachable!("native min/max width validated before emission"), - } - .emit(code, ZERO_PAIR, REMOVE_SIGN_BITS); - Host::Xor.register(code, ZERO_VECTOR, ZERO_VECTOR, target); - Host::EqualDword.register(code, ZERO_PAIR, ZERO_VECTOR, target); - if format == Format::Double { - Host::ShuffleDword.register(code, DOUBLE_ZERO_SCRATCH, ZERO_PAIR, target); - code.push(SWAP_ADJACENT_DWORDS); - Host::And.register(code, ZERO_PAIR, DOUBLE_ZERO_SCRATCH, target); - } - Host::And.register(code, ZERO_PAIR, ACTIVE, target); - Host::ByteSignMask.register(code, GPR_RAX, ZERO_PAIR, target); - code.extend(TEST_EAX_EAX); - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); -} - -fn selection(code: &mut Vec, operation: MinMaxOperation, format: Format) { - let opcode = match operation { - MinMaxOperation::Minimum | MinMaxOperation::MinimumNumber => SelectionOpcode::Minimum, - MinMaxOperation::Maximum | MinMaxOperation::MaximumNumber => SelectionOpcode::Maximum, - }; - if format == Format::Double { - code.push(PACKED_DOUBLE_PREFIX); - } - code.extend([ - SSE_ESCAPE, - opcode as u8, - MODRM_REGISTER | (LEFT << MODRM_REGISTER_SHIFT) | RIGHT, - ]); -} const EVEN_DWORDS: u8 = 0x88; const ODD_DWORDS: u8 = 0xdd; const PREPARED_EVEN: u8 = CLASSIFICATION_SCRATCH[0]; const PREPARED_RIGHT: u8 = CLASSIFICATION_SCRATCH[1]; -fn shuffle(code: &mut Vec, destination: u8, source: u8, order: u8, target: TargetCpu) { - Host::ShuffleDword.register(code, destination, source, target); - code.push(order); +fn shuffle(code: &mut Code, destination: u8, source: u8, order: u8, target: TargetCpu) { + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(source), + order, + target, + ); } /// Interleave source pairs by output lane; the output predicate is applied only /// after this permutation, so inactive-index source operands remain available. -fn paired_inputs(code: &mut Vec, format: Format, target: TargetCpu) { +fn paired_inputs(code: &mut Code, format: Format, target: TargetCpu) { if format == Format::Single { shuffle(code, PREPARED_EVEN, LEFT, EVEN_DWORDS, target); shuffle(code, PREPARED_RIGHT, RIGHT, EVEN_DWORDS, target); @@ -134,7 +75,7 @@ fn element(format: Format) -> Option { /// Four predicated pairwise min/max forms; every failed guard remains atomic /// at instruction scope. Exactly-one-zero pairs are allowed, ties are not. pub(in crate::x86_64) fn emit_pairwise( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -212,7 +153,7 @@ pub(in crate::x86_64) fn emit_pairwise( /// Destructive FCLAMP: MaxNum(lower, old Zd), then MinNum(result, upper). /// Aliases stay intact until the final staged commit. pub(in crate::x86_64) fn emit_clamp( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -283,7 +224,7 @@ pub(in crate::x86_64) fn emit_clamp( /// Common-capsule entry point; unrelated arithmetic remains untouched. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/reduction_minmax.rs b/crates/stela-compiler/src/x86_64/sve/floating/reduction_minmax.rs index 109da9f844..187a0f45b7 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/reduction_minmax.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/reduction_minmax.rs @@ -1,5 +1,9 @@ //! SVE FMAXV/FMINV/FMAXNMV/FMINNMV and their QV forms. Only trees of nonzero //! normals and infinities take the native path. +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::FloatOp; +use crate::x86_64::asm::Gpr::{Rax, Rdi}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, Rm, Size}; use crate::{ CompileError, GuestAddress, GuestState, TargetCpu, aarch64::{ @@ -29,21 +33,8 @@ const CLASSIFICATION: [u8; 2] = [6, 7]; const TREE_SCRATCH: u8 = 5; const TREE_ACTIVE: u8 = 6; const TREE_PREDICATE_SCRATCH: u8 = 7; -const GPR_RAX: u8 = 0; const OUTPUT_SLOT: usize = 0; const OUTPUT_CHUNK: usize = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const SSE_ESCAPE: u8 = 0x0f; -const DOUBLE_PREFIX: u8 = 0x66; -const MINIMUM_OPCODE: u8 = 0x5d; -const MAXIMUM_OPCODE: u8 = 0x5f; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const TEST_STATE_IMMEDIATE: &[u8] = &[0xf7, 0x87]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const CMP_EAX_ALL_BYTES: &[u8] = &[0x3d, 0xff, 0xff, 0, 0]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; const SWAP_DWORDS: u8 = 0xb1; const BROADCAST_DWORD_0: u8 = 0x00; const BROADCAST_DWORD_1: u8 = 0x55; @@ -55,39 +46,30 @@ const REMOVE_SIGN_BIT: u8 = 1; const TREE_BRANCHES: usize = 2; const NEXT_TREE_REGISTER: u8 = 1; -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement +fn state_test(code: &mut Code, mask: u32) { + code.asm().test_imm( + Size::Dword, + Mem::base_disp32(Rdi, core::mem::offset_of!(GuestState, fpcr) as i32), + mask as i32, + ); } -fn resolve(code: &mut [u8], displacement: usize, destination: usize) { - let end = displacement + size_of::(); - let relative = - i32::try_from(destination as i64 - end as i64).expect("bounded reduction branch"); - code[displacement..end].copy_from_slice(&relative.to_le_bytes()); +fn reject(code: &mut Code, failures: &mut Vec) { + failures.push(code.asm().jcc(Cond::Ne).offset()); } -fn state_test(code: &mut Vec, mask: u32) { - code.extend(TEST_STATE_IMMEDIATE); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(mask.to_le_bytes()); +fn shuffle(code: &mut Code, dst: u8, src: u8, order: u8, target: TargetCpu) { + code.asm() + .simd_imm(Host::ShuffleDword, dst, Rm::Xmm(src), order, target); } -fn shuffle(code: &mut Vec, dst: u8, src: u8, order: u8, target: TargetCpu) { - Host::ShuffleDword.register(code, dst, src, target); - code.push(order); -} - -fn broadcast(code: &mut Vec, format: Format, mut bits: u64, dst: u8, target: TargetCpu) { +fn broadcast(code: &mut Code, format: Format, mut bits: u64, dst: u8, target: TargetCpu) { if format == Format::Half { bits |= bits << Format::Half.bits(); } - code.extend(MOV_RAX_IMMEDIATE); - code.extend(bits.to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | dst << MODRM_REGISTER_SHIFT | GPR_RAX); + let mut asm = code.asm(); + asm.mov_imm64(Rax, bits); + asm.simd(Host::MoveGprQword, dst, Rax, target); if format == Format::Double { Host::UnpackLowQword.register(code, dst, dst, target); } else { @@ -112,7 +94,7 @@ fn minimum(operation: MinMaxOperation) -> bool { /// Identity construction is bitwise; no numerical control validation is allowed /// in the raw QV base case. DefaultNaN's sign alone depends on stored AH. fn identity( - code: &mut Vec, + code: &mut Code, operation: MinMaxOperation, format: Format, dst: u8, @@ -131,30 +113,24 @@ fn identity( broadcast(code, format, bits, dst, target); if number(operation) { state_test(code, FPCR_AH); - let positive = branch(code, JZ_REL32); + let positive = code.asm().jcc(Cond::E); broadcast(code, format, bits | format.sign_mask(), dst, target); - let next = code.len(); - resolve(code, positive, next); + code.asm().bind(positive); } } -fn selection(code: &mut Vec, operation: MinMaxOperation, format: Format, lo: u8, hi: u8) { - if format == Format::Double { - code.push(DOUBLE_PREFIX); +fn selection(code: &mut Code, operation: MinMaxOperation, format: Format, lo: u8, hi: u8) { + let mut asm = code.asm(); + match (format == Format::Double, minimum(operation)) { + (true, true) => asm.float(FloatOp::Min, FloatLanes::PackedDouble, lo, Rm::Xmm(hi)), + (true, false) => asm.float(FloatOp::Max, FloatLanes::PackedDouble, lo, Rm::Xmm(hi)), + (false, true) => asm.float(FloatOp::Min, FloatLanes::PackedSingle, lo, Rm::Xmm(hi)), + (false, false) => asm.float(FloatOp::Max, FloatLanes::PackedSingle, lo, Rm::Xmm(hi)), } - code.extend([ - SSE_ESCAPE, - if minimum(operation) { - MINIMUM_OPCODE - } else { - MAXIMUM_OPCODE - }, - MODRM_REGISTER | lo << MODRM_REGISTER_SHIFT | hi, - ]); } /// Reject every active zero, deliberately narrower than pairwise zero-tie guards. -fn guard_nonzero(code: &mut Vec, format: Format, failures: &mut Vec, target: TargetCpu) { +fn guard_nonzero(code: &mut Code, format: Format, failures: &mut Vec, target: TargetCpu) { let [magnitude, zero, other_half] = SCRATCH; Host::MoveAligned.register(code, magnitude, RESULT, target); match format { @@ -170,9 +146,10 @@ fn guard_nonzero(code: &mut Vec, format: Format, failures: &mut Vec, Host::And.register(code, magnitude, other_half, target); } Host::And.register(code, magnitude, ACTIVE, target); - Host::ByteSignMask.register(code, GPR_RAX, magnitude, target); - code.extend(TEST_EAX_EAX); - failures.push(branch(code, JNZ_REL32)); + let mut asm = code.asm(); + asm.simd_to_gpr(Host::ByteSignMask, Rax, magnitude, target); + asm.test(Size::Dword, Rax, Rax); + reject(code, failures); } struct Tree { @@ -188,7 +165,7 @@ struct Tree { } impl Tree { - fn leaf(&self, code: &mut Vec, chunk: usize, dst: u8) { + fn leaf(&self, code: &mut Code, chunk: usize, dst: u8) { if !self.all_active { read_predicate_mask( code, @@ -229,7 +206,7 @@ impl Tree { } } - fn emit(&self, code: &mut Vec, start: usize, count: usize, dst: u8) { + fn emit(&self, code: &mut Code, start: usize, count: usize, dst: u8) { if count == 1 { self.leaf(code, start, dst); return; @@ -252,7 +229,7 @@ impl Tree { /// Uses baseline SSE2 only. Clobbers RAX/RCX/RDX, flags and XMM0..7, preserves /// caller MXCSR, guest FPSR/NZCV, source aliases and all unrelated state. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -295,7 +272,7 @@ pub(in crate::x86_64) fn emit( // active-only, unlike ordinary predicated elementwise arithmetic. if features.full_a64() { state_test(code, FPCR_EXCEPTION_ENABLE_MASK); - failures.push(branch(code, JNZ_REL32)); + reject(code, &mut failures); } let classification = prepare_classification(code, operand.format, CLASSIFICATION, target); for chunk in 0..length.chunks() { @@ -303,9 +280,10 @@ pub(in crate::x86_64) fn emit( code, predicate, chunk, element, ACTIVE, SCRATCH[0], length, target, ); if number(operation) { - Host::ByteSignMask.register(code, GPR_RAX, ACTIVE, target); - code.extend(CMP_EAX_ALL_BYTES); - failures.push(branch(code, JNZ_REL32)); + let mut asm = code.asm(); + asm.simd_to_gpr(Host::ByteSignMask, Rax, ACTIVE, target); + asm.alu_accumulator_imm32(Alu::Cmp, Size::Dword, 0xffff); + reject(code, &mut failures); } load_z_chunk(code, source, chunk, RESULT, length, target); Host::And.register(code, RESULT, ACTIVE, target); diff --git a/crates/stela-compiler/src/x86_64/sve/floating/refinement.rs b/crates/stela-compiler/src/x86_64/sve/floating/refinement.rs index 9bf30c313b..dafc59d47e 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/refinement.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/refinement.rs @@ -1,5 +1,7 @@ //! SVE FRECPS/FRSQRTS on normal values. A baseline multiply is used only when the //! host status shows it was exact. +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rdi}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, Rm, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, GuestState, TargetCpu, aarch64::{ @@ -15,9 +17,8 @@ use crate::{ numerical::{self, Environment, Output}, }, simd::numerical::{ - ArithmeticOpcode, FusedOpcode, VZEROUPPER, emit_fma, emit_opcode_to, - prepare_vector_input_range, prepare_vector_result_range, rounding_control, - vector_exponent_range, + ArithmeticOpcode, FusedOpcode, emit_fma, emit_opcode_to, prepare_vector_input_range, + prepare_vector_result_range, rounding_control, vector_exponent_range, }, }, }; @@ -27,9 +28,6 @@ const LEFT: u8 = 0; const RIGHT: u8 = 1; const ADDEND: u8 = 6; const OUTPUT_SLOT: usize = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const GPR_RAX: u8 = 0; const BROADCAST_LOW_DWORD: u8 = 0; const MXCSR_STATUS_MASK: u32 = 0x3f; const MXCSR_INEXACT: u32 = 1 << 5; @@ -37,56 +35,35 @@ const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; const MXCSR_TO_FPSR_INEXACT_SHIFT: u8 = 1; const RECIPROCAL_ADDEND_EXPONENT: u32 = 1; const RECIPROCAL_SQUARE_ROOT_FRACTION_SHIFT: u32 = 1; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const TEST_STATE_IMMEDIATE: &[u8] = &[0xf7, 0x87]; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -const REL32_BYTES: usize = size_of::(); -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement +fn test_control(code: &mut Code, mask: u32) { + code.asm().test_imm( + Size::Dword, + Mem::base_disp32(Rdi, (core::mem::offset_of!(GuestState, fpcr)) as i32), + mask as i32, + ); } -fn resolve(code: &mut [u8], displacement: usize, destination: usize) { - let distance = i32::try_from(destination as i64 - (displacement + REL32_BYTES) as i64) - .expect("bounded refinement branch"); - code[displacement..displacement + REL32_BYTES].copy_from_slice(&distance.to_le_bytes()); +fn reject_status(code: &mut Code, mask: u32, failures: &mut Vec) { + code.asm().test_imm(Size::Dword, Rcx, mask as i32); + failures.push(code.asm().jcc(Cond::Ne).offset()); } -fn test_control(code: &mut Vec, mask: u32) { - code.extend(TEST_STATE_IMMEDIATE); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(mask.to_le_bytes()); -} - -fn reject_status(code: &mut Vec, mask: u32, failures: &mut Vec) { - code.extend(TEST_ECX_IMMEDIATE); - code.extend(mask.to_le_bytes()); - failures.push(branch(code, JNZ_REL32)); -} - -fn broadcast(code: &mut Vec, format: Format, bits: u64, target: TargetCpu) { +fn broadcast(code: &mut Code, format: Format, bits: u64, target: TargetCpu) { if format == Format::Single { - code.push(MOV_EAX_IMMEDIATE); - code.extend((bits as u32).to_le_bytes()); + code.asm().mov_imm32(Rax, bits as u32); } else { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(bits.to_le_bytes()); + code.asm().mov_imm64(Rax, bits); } - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (ADDEND << MODRM_REGISTER_SHIFT) | GPR_RAX); + code.asm().simd(Host::MoveGprQword, ADDEND, Rax, target); if format == Format::Single { - Host::ShuffleDword.register(code, ADDEND, ADDEND, target); - code.push(BROADCAST_LOW_DWORD); + code.asm().simd_imm( + Host::ShuffleDword, + ADDEND, + Rm::Xmm(ADDEND), + BROADCAST_LOW_DWORD, + target, + ); } else { Host::UnpackLowQword.register(code, ADDEND, ADDEND, target); } @@ -106,7 +83,7 @@ fn addend_bits(format: Format, kind: RefinementKind) -> u64 { /// Inputs already passed a normal-domain classifier. For FRSQRTS the left /// exponent is >=2, so subtracting one exponent unit is exact and stays normal. -fn halve_left(code: &mut Vec, format: Format, target: TargetCpu) { +fn halve_left(code: &mut Code, format: Format, target: TargetCpu) { broadcast(code, format, 1 << format.fraction_bits(), target); let opcode = if format == Format::Single { Host::SubDword @@ -116,9 +93,9 @@ fn halve_left(code: &mut Vec, format: Format, target: TargetCpu) { opcode.register(code, LEFT, ADDEND, target); } -fn reject_non_normal(code: &mut Vec, format: Format, register: u8, failures: &mut Vec) { +fn reject_non_normal(code: &mut Code, format: Format, register: u8, failures: &mut Vec) { vector_exponent_range(code, format, Shape::Vector128, register); - failures.push(branch(code, JNZ_REL32)); + failures.push(code.asm().jcc(Cond::Ne).offset()); } /// Owns only unpredicated vector FRECPS/FRSQRTS, without registration or feature @@ -127,7 +104,7 @@ fn reject_non_normal(code: &mut Vec, format: Format, register: u8, failures: /// cancellation, tiny/overflowing results and nonprecision host status decline. /// All chunks stage before one guest commit; every refusal restores MXCSR/RSP. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -159,18 +136,16 @@ pub(in crate::x86_64) fn emit( let mut failures = Vec::new(); if features.full_a64() { test_control(code, FPCR_AH); - let suppressed = branch(code, JNZ_REL32); + let suppressed = code.asm().jcc(Cond::Ne); test_control(code, FPCR_EXCEPTION_ENABLE_MASK); - failures.push(branch(code, JNZ_REL32)); - let next = code.len(); - resolve(code, suppressed, next); + failures.push(code.asm().jcc(Cond::Ne).offset()); + code.asm().bind(suppressed); } rounding_control(code); test_control(code, FPCR_AH); - let ordinary = branch(code, JZ_REL32); - code.extend(XOR_EAX_EAX); - let next = code.len(); - resolve(code, ordinary, next); + let ordinary = code.asm().jcc(Cond::E); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); + code.asm().bind(ordinary); numerical::install_mxcsr(code, &frame); for chunk in 0..length.chunks() { numerical::clear_status(code, &frame); @@ -199,7 +174,7 @@ pub(in crate::x86_64) fn emit( FusedOpcode::NegativeMultiplyAdd, target, ); - code.extend(VZEROUPPER); + code.asm().vzeroupper(); } else { emit_opcode_to( code, @@ -231,15 +206,13 @@ pub(in crate::x86_64) fn emit( numerical::capture_status(code, &frame); reject_status(code, MXCSR_OTHER_STATUS, &mut failures); test_control(code, FPCR_AH); - let suppressed = branch(code, JNZ_REL32); - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_INEXACT.to_le_bytes()); - code.extend(SHR_EAX_IMMEDIATE); - code.push(MXCSR_TO_FPSR_INEXACT_SHIFT); + let suppressed = code.asm().jcc(Cond::Ne); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_INEXACT as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, MXCSR_TO_FPSR_INEXACT_SHIFT); numerical::add_fpsr(code, &frame); - let next = code.len(); - resolve(code, suppressed, next); + code.asm().bind(suppressed); } numerical::finish(code, &frame, &failures, pc, target); Ok(true) @@ -300,7 +273,7 @@ mod tests { ..base }, ] { - let mut code = vec![0xaa]; + let mut code = Code::from(vec![0xaa]); assert!( !emit( &mut code, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/rounding.rs b/crates/stela-compiler/src/x86_64/sve/floating/rounding.rs index 2c7663d008..dc6bcb232b 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/rounding.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/rounding.rs @@ -1,4 +1,6 @@ //! SVE FRINT*. +use crate::x86_64::asm::Gpr::{R10, Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, @@ -29,12 +31,6 @@ const ACTIVE: u8 = 2; const PREDICATE_SCRATCH: u8 = 3; const OLD_DESTINATION: u8 = 4; const OUTPUT_SLOT: usize = 0; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const MOV_EAX_R10D: &[u8] = &[0x44, 0x89, 0xd0]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const TEST_ECX_ECX: &[u8] = &[0x85, 0xc9]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -const REL32_BYTES: usize = size_of::(); const INEXACT_SHIFT: u8 = INEXACT.trailing_zeros() as u8; /// Handle the seven FRINT forms for active single/double lanes that are normal @@ -42,7 +38,7 @@ const INEXACT_SHIFT: u8 = INEXACT.trailing_zeros() as u8; /// rejection discards the staged result and restores the caller's MXCSR at the /// instruction. pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -80,7 +76,7 @@ pub(crate) fn emit( } else { // The kernels use explicit direction immediates; the ties-away residual // arithmetic uses round-to-nearest. - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); } numerical::install_mxcsr(code, &frame); let mut failures = Vec::new(); @@ -116,9 +112,9 @@ pub(crate) fn emit( ); } if operand.operation.exact() { - code.extend(MOV_EAX_R10D); - code.extend(SHL_EAX_IMM8); - code.push(INEXACT_SHIFT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, R10); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, INEXACT_SHIFT); numerical::add_fpsr(code, &frame); } // Both recipes may destroy the active mask; P and the destination stay @@ -150,10 +146,8 @@ pub(crate) fn emit( // precision (ROUND suppresses it; ties-away residual arithmetic is exact). // A fresh private status value detects any unexpected effect before commit. numerical::capture_status(code, &frame); - code.extend(TEST_ECX_ECX); - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend([0; REL32_BYTES]); + code.asm().test(Size::Dword, Rcx, Rcx); + failures.push(code.asm().jcc(Cond::Ne).offset()); numerical::finish(code, &frame, &failures, pc, target); Ok(true) } diff --git a/crates/stela-compiler/src/x86_64/sve/floating/scale.rs b/crates/stela-compiler/src/x86_64/sve/floating/scale.rs index a61b171481..176c4c05e0 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/scale.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/scale.rs @@ -1,4 +1,6 @@ //! SVE FSCALE on normal values through packed integer exponent arithmetic. +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Code, Cond, Rm, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -26,17 +28,10 @@ const TEMPORARY: u8 = 4; const MAXIMUM_EXPONENT: u8 = 5; const ACTIVE: u8 = 6; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; const REPEAT_LOW_DWORD: u8 = 0; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_RAX_IMMEDIATE: &[u8] = &[0x48, 0xb8]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; fn packed( - code: &mut Vec, + code: &mut Code, format: Format, single: Host, double: Host, @@ -52,17 +47,16 @@ fn packed( .register(code, destination, source, target); } -fn reject_invalid_active(code: &mut Vec, failures: &mut Vec, target: TargetCpu) { +fn reject_invalid_active(code: &mut Code, failures: &mut Vec, target: TargetCpu) { Host::AndNot.register(code, VALID, ACTIVE, target); - Host::ByteSignMask.register(code, GPR_RAX, VALID, target); - code.extend(TEST_EAX_EAX); - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); + code.asm() + .simd_to_gpr(Host::ByteSignMask, Rax, VALID, target); + code.asm().test(Size::Dword, Rax, Rax); + failures.push(code.asm().jcc(Cond::Ne).offset()); } fn guard_normal_exponent( - code: &mut Vec, + code: &mut Code, format: Format, failures: &mut Vec, target: TargetCpu, @@ -93,7 +87,7 @@ fn guard_normal_exponent( } fn guard_bounded_scale( - code: &mut Vec, + code: &mut Code, format: Format, failures: &mut Vec, target: TargetCpu, @@ -132,20 +126,23 @@ fn guard_bounded_scale( reject_invalid_active(code, failures, target); } -fn broadcast_maximum(code: &mut Vec, format: Format, target: TargetCpu) { +fn broadcast_maximum(code: &mut Code, format: Format, target: TargetCpu) { let maximum = format.exponent_mask() >> format.fraction_bits(); if format == Format::Single { - code.push(MOV_EAX_IMMEDIATE); - code.extend((maximum as u32).to_le_bytes()); + code.asm().mov_imm32(Rax, maximum as u32); } else { - code.extend(MOV_RAX_IMMEDIATE); - code.extend(maximum.to_le_bytes()); + code.asm().mov_imm64(Rax, maximum); } - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (MAXIMUM_EXPONENT << MODRM_REGISTER_SHIFT) | GPR_RAX); + code.asm() + .simd(Host::MoveGprQword, MAXIMUM_EXPONENT, Rax, target); if format == Format::Single { - Host::ShuffleDword.register(code, MAXIMUM_EXPONENT, MAXIMUM_EXPONENT, target); - code.push(REPEAT_LOW_DWORD); + code.asm().simd_imm( + Host::ShuffleDword, + MAXIMUM_EXPONENT, + Rm::Xmm(MAXIMUM_EXPONENT), + REPEAT_LOW_DWORD, + target, + ); } else { Host::UnpackLowQword.register(code, MAXIMUM_EXPONENT, MAXIMUM_EXPONENT, target); } @@ -157,7 +154,7 @@ fn broadcast_maximum(code: &mut Vec, format: Format, target: TargetCpu) { /// Every accepted value changes only its exponent field, preserving sign and /// fraction exactly, independent of all FPCR rounding/flush/AH controls. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, diff --git a/crates/stela-compiler/src/x86_64/sve/floating/square_root.rs b/crates/stela-compiler/src/x86_64/sve/floating/square_root.rs index 97daa3ff99..9717a19745 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/square_root.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/square_root.rs @@ -1,4 +1,8 @@ //! SVE FSQRT: SQRTPS/SQRTPD for positive normals, +0 and +infinity. +use crate::x86_64::asm::FloatLanes; +use crate::x86_64::asm::FloatOp; +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -27,18 +31,6 @@ const SCRATCH: [u8; 3] = [3, 4, 5]; const OLD_DESTINATION: u8 = SCRATCH[0]; const MASKS: [u8; 2] = [6, 7]; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const PACKED_DOUBLE_PREFIX: u8 = 0x66; -const SQRT_PACKED: &[u8] = &[0x0f, 0x51]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const TEST_EAX_IMMEDIATE: u8 = 0xa9; -const TEST_ECX_IMMEDIATE: &[u8] = &[0xf7, 0xc1]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -const MOV_EAX_ECX: &[u8] = &[0x89, 0xc8]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const SHR_EAX_IMMEDIATE: &[u8] = &[0xc1, 0xe8]; const DOUBLE_LOW_SIGN_DWORD: u32 = 1; const DOUBLE_HIGH_SIGN_DWORD: u32 = 3; const DOUBLE_SIGN_LANES: u32 = (1 << DOUBLE_LOW_SIGN_DWORD) | (1 << DOUBLE_HIGH_SIGN_DWORD); @@ -46,36 +38,45 @@ const MXCSR_INEXACT: u32 = 1 << 5; const MXCSR_OTHER_STATUS: u32 = MXCSR_INEXACT - 1; const MXCSR_TO_FPSR_INEXACT_SHIFT: u8 = 1; -fn reject(code: &mut Vec, failures: &mut Vec) { - code.extend(JNZ_REL32); - failures.push(code.len()); - code.extend(0_i32.to_le_bytes()); +fn reject(code: &mut Code, failures: &mut Vec) { + failures.push(code.asm().jcc(Cond::Ne).offset()); } fn guard_nonnegative( - code: &mut Vec, + code: &mut Code, format: Format, failures: &mut Vec, target: TargetCpu, ) { - Host::DwordSignMask.register(code, GPR_RAX, VALUE, target); + code.asm() + .simd_to_gpr(Host::DwordSignMask, Rax, VALUE, target); if format == Format::Double { // MOVMSKPS sees all four dwords. Only high dwords contain Double signs; // the low-dword fraction sign bits must not reject positive operands. - code.push(TEST_EAX_IMMEDIATE); - code.extend(DOUBLE_SIGN_LANES.to_le_bytes()); + code.asm() + .test_accumulator_imm(Size::Dword, DOUBLE_SIGN_LANES as i32); } else { - code.extend(TEST_EAX_EAX); + code.asm().test(Size::Dword, Rax, Rax); } reject(code, failures); } -fn square_root(code: &mut Vec, format: Format) { +fn square_root(code: &mut Code, format: Format) { if format == Format::Double { - code.push(PACKED_DOUBLE_PREFIX); + code.asm().float( + FloatOp::Sqrt, + FloatLanes::PackedDouble, + VALUE, + Rm::Xmm(VALUE), + ); + } else { + code.asm().float( + FloatOp::Sqrt, + FloatLanes::PackedSingle, + VALUE, + Rm::Xmm(VALUE), + ); } - code.extend(SQRT_PACKED); - code.push(MODRM_REGISTER | (VALUE << MODRM_REGISTER_SHIFT) | VALUE); } /// Predicated merging FSQRT over a positive exact/rounded IEEE domain. Shared @@ -84,7 +85,7 @@ fn square_root(code: &mut Vec, format: Format) { /// Clobbers volatile RAX/RCX/RDX, host flags and XMM0..7, preserving RDI/R15 and /// caller MXCSR through both accepted and exceptional whole-instruction exits. pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, features: NumericalFeatures, @@ -143,14 +144,13 @@ pub(in crate::x86_64) fn emit( numerical::stage_vector_chunk(code, &frame, OUTPUT_SLOT, chunk, VALUE, target); } numerical::capture_status(code, &frame); - code.extend(TEST_ECX_IMMEDIATE); - code.extend(MXCSR_OTHER_STATUS.to_le_bytes()); + code.asm() + .test_imm(Size::Dword, Rcx, MXCSR_OTHER_STATUS as i32); reject(code, &mut failures); - code.extend(MOV_EAX_ECX); - code.push(AND_EAX_IMMEDIATE); - code.extend(MXCSR_INEXACT.to_le_bytes()); - code.extend(SHR_EAX_IMMEDIATE); - code.push(MXCSR_TO_FPSR_INEXACT_SHIFT); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rax, Rcx); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, MXCSR_INEXACT as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, MXCSR_TO_FPSR_INEXACT_SHIFT); numerical::add_fpsr(code, &frame); numerical::finish(code, &frame, &failures, pc, target); Ok(true) diff --git a/crates/stela-compiler/src/x86_64/sve/floating/unsigned_estimates.rs b/crates/stela-compiler/src/x86_64/sve/floating/unsigned_estimates.rs index 054f84addb..00280752ef 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating/unsigned_estimates.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating/unsigned_estimates.rs @@ -1,4 +1,6 @@ //! SVE URECPE and URSQRTE by table lookup. +use crate::x86_64::asm::Gpr::{Rax, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Disp, Mem, ShiftOp, Size}; use crate::{ CompileError, GuestAddress, TargetCpu, aarch64::{ @@ -24,9 +26,6 @@ const MERGE: u8 = 2; const RESULT: u8 = 3; const CANDIDATE: u8 = 4; const OUTPUT_SLOT: usize = 0; -const GPR_RAX: u8 = 0; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; const DWORD_BYTES: usize = core::mem::size_of::(); const REL32_BYTES: usize = core::mem::size_of::(); const ESTIMATE_FRACTION_BITS: u32 = 8; @@ -36,42 +35,13 @@ const RECIPROCAL_FIRST_BIN: u32 = ESTIMATE_UNIT; const RSQRT_FIRST_BIN: u32 = ESTIMATE_UNIT / 2; const LAST_BIN_EXCLUSIVE: u32 = ESTIMATE_UNIT * 2; -const MOVD_GPR_XMM: &[u8] = &[0x66, 0x0f, 0x7e]; -const MOV_EAX_IMM32: u8 = 0xb8; -const SHR_EAX_IMM8: &[u8] = &[0xc1, 0xe8]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const CMP_EAX_IMM32: u8 = 0x3d; -const OR_EAX_IMM32: u8 = 0x0d; -const LEA_RDX_RIP_REL32: &[u8] = &[0x48, 0x8d, 0x15]; -const MOVZX_EAX_BYTE_RDX_RAX_DISP32: &[u8] = &[0x0f, 0xb6, 0x84, 0x02]; -const PEXTRD_EAX_XMM: &[u8] = &[0x66, 0x0f, 0x3a, 0x16]; -const PINSRD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x3a, 0x22]; -const JB_REL32: &[u8] = &[0x0f, 0x82]; -const JMP_REL32: u8 = 0xe9; - -fn patch(code: &mut [u8], displacement: usize, destination: usize) { +/// Point the RIP-relative displacement field at `displacement` to `destination`. +fn patch_rip(code: &mut [u8], displacement: usize, destination: usize) { let relative = i32::try_from(destination as i64 - (displacement + REL32_BYTES) as i64) .expect("unsigned estimate body exceeds rel32 range"); code[displacement..displacement + REL32_BYTES].copy_from_slice(&relative.to_le_bytes()); } -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement -} - -fn movd_from_xmm(code: &mut Vec, xmm: u8, gpr: u8) { - code.extend(MOVD_GPR_XMM); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) | gpr); -} - -fn movq_to_xmm(code: &mut Vec, xmm: u8, gpr: u8, target: TargetCpu) { - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) | gpr); -} - fn first_bin(kind: EstimateKind) -> u32 { match kind { EstimateKind::UnsignedReciprocal => RECIPROCAL_FIRST_BIN, @@ -81,7 +51,7 @@ fn first_bin(kind: EstimateKind) -> u32 { } pub(in crate::x86_64) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, _features: NumericalFeatures, @@ -126,50 +96,41 @@ pub(in crate::x86_64) fn emit( ); load_z_chunk(code, source, chunk, SOURCE, length, target); - code.extend(LEA_RDX_RIP_REL32); - table_addresses.push(code.len()); - code.extend(0_i32.to_le_bytes()); + code.asm().lea(Size::Qword, Rdx, Mem::rip(0)); + table_addresses.push(code.len() - REL32_BYTES); for lane in 0..VECTOR_CHUNK_BYTES / DWORD_BYTES { if checked { - code.extend(PEXTRD_EAX_XMM); - code.push(MODRM_REGISTER | (SOURCE << MODRM_REGISTER_SHIFT) | GPR_RAX); - code.push(lane as u8); + code.asm().pextrd(Rax, SOURCE, lane as u8); } else { - movd_from_xmm(code, SOURCE, GPR_RAX); + code.asm().movd_from_xmm(Rax, SOURCE); } - code.extend(SHR_EAX_IMM8); - code.push(ESTIMATE_INPUT_SHIFT); - code.push(CMP_EAX_IMM32); - code.extend(first_bin(kind).to_le_bytes()); - let below = branch(code, JB_REL32); - - code.extend(MOVZX_EAX_BYTE_RDX_RAX_DISP32); - code.extend((-(first_bin(kind) as i32)).to_le_bytes()); - code.push(OR_EAX_IMM32); - code.extend(ESTIMATE_UNIT.to_le_bytes()); - - code.extend(SHL_EAX_IMM8); - code.push(ESTIMATE_INPUT_SHIFT); - let valid = branch(code, &[JMP_REL32]); - let below_start = code.len(); - patch(code, below, below_start); - code.push(MOV_EAX_IMM32); - code.extend(u32::MAX.to_le_bytes()); - let value_done = code.len(); - patch(code, valid, value_done); + let mut asm = code.asm(); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rax, ESTIMATE_INPUT_SHIFT); + asm.alu_accumulator_imm32(Alu::Cmp, Size::Dword, first_bin(kind) as i32); + let below = asm.jcc(Cond::B); + asm.movzx( + Size::Dword, + Rax, + Size::Byte, + Mem::indexed(Rdx, Rax, 1, -(first_bin(kind) as i32)).with_width(Disp::Dword), + ); + asm.alu_accumulator_imm32(Alu::Or, Size::Dword, ESTIMATE_UNIT as i32); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, ESTIMATE_INPUT_SHIFT); + let valid = asm.jmp(); + asm.bind(below); + asm.mov_imm32(Rax, u32::MAX); + asm.bind(valid); if checked { - code.extend(PINSRD_XMM_EAX); - code.push(MODRM_REGISTER | (RESULT << MODRM_REGISTER_SHIFT) | GPR_RAX); - code.push(lane as u8); + code.asm().pinsrd(RESULT, Rax, lane as u8); } else { if lane == 0 { // MOVQ writes the first dword and clears every upper byte. - movq_to_xmm(code, RESULT, GPR_RAX, target); + code.asm().simd(Host::MoveGprQword, RESULT, Rax, target); } else { - movq_to_xmm(code, CANDIDATE, GPR_RAX, target); + code.asm().simd(Host::MoveGprQword, CANDIDATE, Rax, target); ShiftOpcode::LeftBytes.emit(code, CANDIDATE, (lane * DWORD_BYTES) as u8); Host::Or.register(code, RESULT, CANDIDATE, target); } @@ -186,8 +147,9 @@ pub(in crate::x86_64) fn emit( } numerical::finish(code, &frame, &[], pc, target); - let skip = branch(code, &[JMP_REL32]); - let table_start = code.len(); + let mut asm = code.asm(); + let skip = asm.jmp(); + let table_start = asm.len(); for scaled in first_bin(kind)..LAST_BIN_EXCLUSIVE { // Compile-time only: compact exact architectural table; no host // address, CALL, mutable storage or runtime FP operation is emitted. @@ -199,12 +161,11 @@ pub(in crate::x86_64) fn emit( ) .expect("unsigned estimate ignores every control"); let estimate = (result.bits >> ESTIMATE_INPUT_SHIFT) as u32; - code.push(u8::try_from(estimate - ESTIMATE_UNIT).expect("estimate table byte")); + asm.data(&[u8::try_from(estimate - ESTIMATE_UNIT).expect("estimate table byte")]); } - let table_end = code.len(); - patch(code, skip, table_end); + asm.bind(skip); for displacement in table_addresses { - patch(code, displacement, table_start); + patch_rip(code, displacement, table_start); } Ok(true) diff --git a/crates/stela-compiler/src/x86_64/sve/floating_copy.rs b/crates/stela-compiler/src/x86_64/sve/floating_copy.rs index 72de9ab2d2..abd5ce9843 100644 --- a/crates/stela-compiler/src/x86_64/sve/floating_copy.rs +++ b/crates/stela-compiler/src/x86_64/sve/floating_copy.rs @@ -1,4 +1,6 @@ //! SVE FCPY and FDUP. +use crate::x86_64::asm::Gpr::Rcx; +use crate::x86_64::asm::{Code, Rm}; use crate::{ TargetCpu, aarch64::{ @@ -10,18 +12,12 @@ use crate::{ scalable::{load_z_chunk, read_predicate_mask, store_z_chunk}, }, }; -use alloc::vec::Vec; const IMMEDIATE: u8 = 0; const ACTIVE: u8 = 1; const PREDICATE_SCRATCH: u8 = 2; const OLD_DESTINATION: u8 = 3; const SELECTED: u8 = 4; -const RCX_REGISTER: u8 = 1; -const REGISTER_DIRECT: u8 = 0xc0; -const REGISTER_FIELD_SHIFT: u8 = 3; -const MOV_RCX_IMM64: &[u8] = &[0x48, 0xb9]; -const MOV_ECX_IMM32: &[u8] = &[0xb9]; const REPEAT_LOW_DWORD: u8 = 0; // Only this H/S vector shape has a measured ComplementXor win. Other lengths // and Double retain AndSelect; this is an empirical shape, not a threshold. @@ -30,7 +26,7 @@ const COMPLEMENT_XOR_MEASURED_VECTOR_BYTES: usize = 64; /// Fill active SVE lanes with the already expanded VFP immediate. All inactive /// lanes preserve their old destination; FDUP supplies no governing predicate. /// Full SVE writes cover current VL and do not clear any other Z register tail. -pub(crate) fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let bits = operand.format.bits(); let complement_xor = bits != u64::BITS && length.bytes() == COMPLEMENT_XOR_MEASURED_VECTOR_BYTES; @@ -41,19 +37,22 @@ pub(crate) fn emit(code: &mut Vec, operand: Operand, length: VectorLength, t qword |= operand.value << shift; } if bits == u64::BITS { - code.extend(MOV_RCX_IMM64); - code.extend(qword.to_le_bytes()); + code.asm().mov_imm64(Rcx, qword); } else { - code.extend(MOV_ECX_IMM32); - code.extend((qword as u32).to_le_bytes()); + code.asm().mov_imm32(Rcx, qword as u32); } - SimdOpcode::MoveGprQword.append(code, target); - code.push(REGISTER_DIRECT | (IMMEDIATE << REGISTER_FIELD_SHIFT) | RCX_REGISTER); + code.asm() + .simd(SimdOpcode::MoveGprQword, IMMEDIATE, Rcx, target); if bits == u64::BITS { SimdOpcode::UnpackLowQword.register(code, IMMEDIATE, IMMEDIATE, target); } else { - SimdOpcode::ShuffleDword.register(code, IMMEDIATE, IMMEDIATE, target); - code.push(REPEAT_LOW_DWORD); + code.asm().simd_imm( + SimdOpcode::ShuffleDword, + IMMEDIATE, + Rm::Xmm(IMMEDIATE), + REPEAT_LOW_DWORD, + target, + ); } for chunk in 0..length.chunks() { let output = if let Some(governing) = operand.governing { diff --git a/crates/stela-compiler/src/x86_64/sve/integer_arithmetic.rs b/crates/stela-compiler/src/x86_64/sve/integer_arithmetic.rs index fcb4601515..6fd2fdcdae 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_arithmetic.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_arithmetic.rs @@ -2,9 +2,11 @@ use crate::TargetCpu; use crate::aarch64::scalable::{ElementSize, Predication, VectorLength}; use crate::aarch64::sve::integer_arithmetic::{Binary, Kind, Operand, Source}; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, Size, Unary}; use crate::x86_64::isa::{ShiftOpcode, SimdOpcode as Host}; use crate::x86_64::scalable::{load_z_chunk, read_predicate_mask, store_z_chunk}; -use alloc::vec::Vec; const RESULT: u8 = 0; const RIGHT: u8 = 1; @@ -15,40 +17,6 @@ const SAVED_RIGHT: u8 = 6; const PREVIOUS: u8 = 7; const CHUNK_BYTES: usize = 16; const QWORD_BYTES: usize = 8; -const MOD_REGISTER: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; -const MOVABS_RAX: [u8; 2] = [0x48, 0xb8]; -const MOVABS_RDX: [u8; 2] = [0x48, 0xba]; -const MOVQ_RAX_XMM: [u8; 4] = [0x66, 0x48, 0x0f, 0x7e]; -const MOVQ_RCX_XMM: [u8; 4] = [0x66, 0x48, 0x0f, 0x7e]; -const MOVQ_RDX_XMM: [u8; 4] = [0x66, 0x48, 0x0f, 0x7e]; -const MOVD_EAX_XMM: [u8; 3] = [0x66, 0x0f, 0x7e]; -const MOVD_ECX_XMM: [u8; 3] = [0x66, 0x0f, 0x7e]; -const TEST_ECX: [u8; 2] = [0x85, 0xc9]; -const TEST_RCX: [u8; 3] = [0x48, 0x85, 0xc9]; -const XOR_EAX: [u8; 2] = [0x31, 0xc0]; -const XOR_EDX: [u8; 2] = [0x31, 0xd2]; -const CMP_ECX_MINUS_ONE: [u8; 3] = [0x83, 0xf9, 0xff]; -const CMP_RCX_MINUS_ONE: [u8; 4] = [0x48, 0x83, 0xf9, 0xff]; -const CMP_EAX_IMMEDIATE: u8 = 0x3d; -const CMP_RAX_RDX: [u8; 3] = [0x48, 0x39, 0xd0]; -const CDQ: u8 = 0x99; -const CQO: [u8; 2] = [0x48, 0x99]; -const DIV_ECX: [u8; 2] = [0xf7, 0xf1]; -const DIV_RCX: [u8; 3] = [0x48, 0xf7, 0xf1]; -const IDIV_ECX: [u8; 2] = [0xf7, 0xf9]; -const IDIV_RCX: [u8; 3] = [0x48, 0xf7, 0xf9]; -const NOT_RCX: [u8; 3] = [0x48, 0xf7, 0xd1]; -const BT_EDX_ZERO: [u8; 4] = [0x0f, 0xba, 0xe2, 0]; -const ADC_RAX_RCX: [u8; 3] = [0x48, 0x11, 0xc8]; -const SETC_DL: [u8; 3] = [0x0f, 0x92, 0xc2]; -const MOVZX_EDX_DL: [u8; 3] = [0x0f, 0xb6, 0xd2]; -const GPR_RCX: u8 = 1; -const GPR_RDX: u8 = 2; -const JZ: [u8; 2] = [0x0f, 0x84]; -const JNZ: [u8; 2] = [0x0f, 0x85]; -const JMP: [u8; 1] = [0xe9]; -const REL32_BYTES: usize = 4; const SWAP_DWORDS: u8 = 0xb1; const SWAP_QWORDS: u8 = 0x4e; const BROADCAST_HIGH_DWORDS: u8 = 0xf5; @@ -57,23 +25,32 @@ const HALFWORD_SIGN_SHIFT: u8 = (u16::BITS - 1) as u8; const SELECT_EVEN_DWORDS: u8 = 0x88; const SELECT_ODD_DWORDS: u8 = 0xdd; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn copy(code: &mut Vec, destination: u8, source: u8) { +fn copy(code: &mut Code, destination: u8, source: u8) { packed(code, Host::MoveAligned, destination, source); } -fn zero(code: &mut Vec, register: u8) { +fn zero(code: &mut Code, register: u8) { packed(code, Host::Xor, register, register); } -fn constant(code: &mut Vec, destination: u8, value: u64) { - code.extend(MOVABS_RAX); - code.extend(value.to_le_bytes()); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MOD_REGISTER | destination << REGISTER_SHIFT); +fn shuffle(code: &mut Code, register: u8, control: u8) { + code.asm().simd_imm( + Host::ShuffleDword, + register, + Rm::Xmm(register), + control, + TargetCpu::Baseline, + ); +} + +fn constant(code: &mut Code, destination: u8, value: u64) { + let mut asm = code.asm(); + asm.mov_imm64(Rax, value); + asm.simd(Host::MoveGprQword, destination, Rax, TargetCpu::Baseline); packed(code, Host::UnpackLowQword, destination, destination); } @@ -118,13 +95,7 @@ fn right_shift(element: ElementSize) -> ShiftOpcode { } /// XMM0/XMM1 inputs; XMM0 result. XMM2..6 scratch, XMM7 preserved. -fn minmax( - code: &mut Vec, - element: ElementSize, - unsigned: bool, - maximum: bool, - target: TargetCpu, -) { +fn minmax(code: &mut Code, element: ElementSize, unsigned: bool, maximum: bool, target: TargetCpu) { let direct = match (element, unsigned, maximum) { (ElementSize::Byte, true, false) => Some(Host::MinUnsignedByte), (ElementSize::Byte, true, true) => Some(Host::MaxUnsignedByte), @@ -161,7 +132,7 @@ fn minmax( /// XMM0 is the result; XMM0..6, RAX/RCX/RDX and host flags are scratch. /// XMM7, RDI/R15 and architectural NZCV/FP state remain unchanged. pub(crate) fn emit_binary_chunk( - code: &mut Vec, + code: &mut Code, operation: Binary, element: ElementSize, target: TargetCpu, @@ -190,7 +161,7 @@ pub(crate) fn emit_binary_chunk( } } -fn unary(code: &mut Vec, element: ElementSize, absolute: bool, target: TargetCpu) { +fn unary(code: &mut Code, element: ElementSize, absolute: bool, target: TargetCpu) { let direct = match element { ElementSize::Byte => Some(Host::AbsByte), ElementSize::Halfword => Some(Host::AbsWord), @@ -215,8 +186,7 @@ fn unary(code: &mut Vec, element: ElementSize, absolute: bool, target: Targe ElementSize::Halfword | ElementSize::Word | ElementSize::Doubleword => { copy(code, RIGHT, RESULT); if element == ElementSize::Doubleword { - packed(code, Host::ShuffleDword, RIGHT, RIGHT); - code.push(BROADCAST_HIGH_DWORDS); + shuffle(code, RIGHT, BROADCAST_HIGH_DWORDS); } if element == ElementSize::Halfword { ShiftOpcode::ArithmeticWord.emit(code, RIGHT, HALFWORD_SIGN_SHIFT); @@ -232,7 +202,7 @@ fn unary(code: &mut Vec, element: ElementSize, absolute: bool, target: Targe /// Keep every other narrow lane in its containing wide lane, then extend it. fn widen( - code: &mut Vec, + code: &mut Code, register: u8, element: ElementSize, unsigned: bool, @@ -241,12 +211,15 @@ fn widen( ) { let half_bits = (element.bits() / 2) as u8; if element == ElementSize::Doubleword && !unsigned { - packed(code, Host::ShuffleDword, register, register); - code.push(if top { - SELECT_ODD_DWORDS - } else { - SELECT_EVEN_DWORDS - }); + shuffle( + code, + register, + if top { + SELECT_ODD_DWORDS + } else { + SELECT_EVEN_DWORDS + }, + ); if target.supports(TargetCpu::Sse41) { Host::SignExtendDwordToQword.register(code, register, register, target); } else { @@ -271,14 +244,17 @@ fn widen( } } -fn complex(code: &mut Vec, element: ElementSize, rotate_270: bool) { +fn complex(code: &mut Code, element: ElementSize, rotate_270: bool) { if matches!(element, ElementSize::Word | ElementSize::Doubleword) { - packed(code, Host::ShuffleDword, RIGHT, RIGHT); - code.push(if element == ElementSize::Word { - SWAP_DWORDS - } else { - SWAP_QWORDS - }); + shuffle( + code, + RIGHT, + if element == ElementSize::Word { + SWAP_DWORDS + } else { + SWAP_QWORDS + }, + ); } else { let wider = if element == ElementSize::Byte { ElementSize::Halfword @@ -315,35 +291,31 @@ fn complex(code: &mut Vec, element: ElementSize, rotate_270: bool) { } /// One qword pair fits the host ADC result and its carry flag directly. -fn carry_qword(code: &mut Vec, subtract: bool, top: bool) { - code.extend(MOVQ_RAX_XMM); - code.push(MOD_REGISTER | PREVIOUS << REGISTER_SHIFT); +fn carry_qword(code: &mut Code, subtract: bool, top: bool) { + code.asm().movq_from_xmm(Rax, PREVIOUS); if top { ShiftOpcode::RightBytes.emit(code, RIGHT, QWORD_BYTES as u8); } - code.extend(MOVQ_RCX_XMM); - code.push(MOD_REGISTER | RIGHT << REGISTER_SHIFT | GPR_RCX); + code.asm().movq_from_xmm(Rcx, RIGHT); ShiftOpcode::RightBytes.emit(code, TEMPORARY, QWORD_BYTES as u8); - code.extend(MOVQ_RDX_XMM); - code.push(MOD_REGISTER | TEMPORARY << REGISTER_SHIFT | GPR_RDX); + code.asm().movq_from_xmm(Rdx, TEMPORARY); if subtract { - code.extend(NOT_RCX); + code.asm().unary(Unary::Not, Size::Qword, Rcx); } // BT consumes only the architectural carry-in low bit. Keep ADC and SETC // adjacent so intervening host flags cannot alter the published carry. - code.extend(BT_EDX_ZERO); - code.extend(ADC_RAX_RCX); - code.extend(SETC_DL); - code.extend(MOVZX_EDX_DL); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MOD_REGISTER | RESULT << REGISTER_SHIFT); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MOD_REGISTER | RIGHT << REGISTER_SHIFT | GPR_RDX); + let mut asm = code.asm(); + asm.bit_imm(BitTest::Bt, Size::Dword, Rdx, 0); + asm.alu(Alu::Adc, Size::Qword, Rax, Rcx); + asm.setcc(Cond::B, Rdx); + asm.movzx(Size::Dword, Rdx, Size::Byte, Rdx); + asm.simd(Host::MoveGprQword, RESULT, Rax, TargetCpu::Baseline); + asm.simd(Host::MoveGprQword, RIGHT, Rdx, TargetCpu::Baseline); packed(code, Host::UnpackLowQword, RESULT, RIGHT); } /// Paired even result / odd carry; word pairs use packed overflow comparisons. -fn carry(code: &mut Vec, element: ElementSize, subtract: bool, top: bool, target: TargetCpu) { +fn carry(code: &mut Code, element: ElementSize, subtract: bool, top: bool, target: TargetCpu) { if element == ElementSize::Doubleword { carry_qword(code, subtract, top); return; @@ -387,50 +359,35 @@ fn carry(code: &mut Vec, element: ElementSize, subtract: bool, top: bool, ta packed(code, Host::Or, RESULT, SAVED_LEFT); } -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend_from_slice(opcode); - let displacement = code.len(); - code.extend(0i32.to_le_bytes()); - displacement -} - -fn resolve(code: &mut [u8], displacement: usize) { - let relative = - i32::try_from(code.len() - displacement - REL32_BYTES).expect("bounded arithmetic body"); - code[displacement..displacement + REL32_BYTES].copy_from_slice(&relative.to_le_bytes()); -} - -fn extract(code: &mut Vec, source: u8, lane: usize, element: ElementSize, to_rcx: bool) { +fn extract(code: &mut Code, source: u8, lane: usize, element: ElementSize, to_rcx: bool) { copy(code, TEMPORARY, source); if lane != 0 { ShiftOpcode::RightBytes.emit(code, TEMPORARY, (lane * element.bytes()) as u8); } - let opcode = match (element, to_rcx) { - (ElementSize::Word, false) => MOVD_EAX_XMM.as_slice(), - (ElementSize::Word, true) => MOVD_ECX_XMM.as_slice(), - (ElementSize::Doubleword, false) => MOVQ_RAX_XMM.as_slice(), - (ElementSize::Doubleword, true) => MOVQ_RCX_XMM.as_slice(), + let destination = if to_rcx { Rcx } else { Rax }; + let mut asm = code.asm(); + match element { + ElementSize::Word => asm.movd_from_xmm(destination, TEMPORARY), + ElementSize::Doubleword => asm.movq_from_xmm(destination, TEMPORARY), _ => unreachable!("division width"), - }; - code.extend_from_slice(opcode); - code.push(MOD_REGISTER | TEMPORARY << REGISTER_SHIFT | u8::from(to_rcx)); + } } /// Scalar IDIV has no packed counterpart. Guard zero, signed overflow and /// inactive lanes before issuing it; no guest or host arithmetic exception leaks. -fn divide( - code: &mut Vec, - element: ElementSize, - unsigned: bool, - reverse: bool, - predicated: bool, -) { +fn divide(code: &mut Code, element: ElementSize, unsigned: bool, reverse: bool, predicated: bool) { + let size = match element { + ElementSize::Word => Size::Dword, + ElementSize::Doubleword => Size::Qword, + _ => unreachable!("division width"), + }; zero(code, SAVED_RIGHT); for lane in 0..CHUNK_BYTES / element.bytes() { let inactive = if predicated { extract(code, SAVED_LEFT, lane, element, true); - code.extend(TEST_ECX); - Some(branch(code, &JZ)) + let mut asm = code.asm(); + asm.test(Size::Dword, Rcx, Rcx); + Some(asm.jcc(Cond::E)) } else { None }; @@ -441,12 +398,9 @@ fn divide( element, true, ); - code.extend_from_slice(if element == ElementSize::Word { - &TEST_ECX - } else { - &TEST_RCX - }); - let zero_divisor = branch(code, &JZ); + let mut asm = code.asm(); + asm.test(size, Rcx, Rcx); + let zero_divisor = asm.jcc(Cond::E); extract( code, if reverse { RIGHT } else { RESULT }, @@ -454,51 +408,38 @@ fn divide( element, false, ); + let mut asm = code.asm(); let mut overflow = None; if !unsigned { - code.extend_from_slice(if element == ElementSize::Word { - &CMP_ECX_MINUS_ONE - } else { - &CMP_RCX_MINUS_ONE - }); - let ordinary_divisor = branch(code, &JNZ); + asm.alu_imm8(Alu::Cmp, size, Rcx, -1); + let ordinary_divisor = asm.jcc(Cond::Ne); if element == ElementSize::Word { - code.push(CMP_EAX_IMMEDIATE); - code.extend(i32::MIN.to_le_bytes()); + asm.alu_accumulator_imm32(Alu::Cmp, Size::Dword, i32::MIN); } else { - code.extend(MOVABS_RDX); - code.extend(i64::MIN.to_le_bytes()); - code.extend(CMP_RAX_RDX); + asm.mov_imm64(Rdx, i64::MIN as u64); + asm.alu(Alu::Cmp, Size::Qword, Rax, Rdx); } - overflow = Some(branch(code, &JZ)); - resolve(code, ordinary_divisor); + overflow = Some(asm.jcc(Cond::E)); + asm.bind(ordinary_divisor); } if unsigned { - code.extend(XOR_EDX); - } else if element == ElementSize::Word { - code.push(CDQ); + asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); + asm.unary(Unary::Div, size, Rcx); } else { - code.extend(CQO); + asm.sign_extend_accumulator(size); + asm.unary(Unary::Idiv, size, Rcx); } - code.extend_from_slice(match (element, unsigned) { - (ElementSize::Word, true) => &DIV_ECX, - (ElementSize::Word, false) => &IDIV_ECX, - (ElementSize::Doubleword, true) => &DIV_RCX, - (ElementSize::Doubleword, false) => &IDIV_RCX, - _ => unreachable!("division width"), - }); - let finished = branch(code, &JMP); - if let Some(position) = inactive { - resolve(code, position); + let finished = asm.jmp(); + if let Some(patch) = inactive { + asm.bind(patch); } - resolve(code, zero_divisor); - code.extend(XOR_EAX); - resolve(code, finished); - if let Some(position) = overflow { - resolve(code, position); + asm.bind(zero_divisor); + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); + asm.bind(finished); + if let Some(patch) = overflow { + asm.bind(patch); } - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MOD_REGISTER | MASK << REGISTER_SHIFT); + asm.simd(Host::MoveGprQword, MASK, Rax, TargetCpu::Baseline); if lane != 0 { ShiftOpcode::LeftBytes.emit(code, MASK, (lane * element.bytes()) as u8); } @@ -507,7 +448,7 @@ fn divide( copy(code, RESULT, SAVED_RIGHT); } -pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let needs_previous = matches!(operand.predication, Predication::Merging(_)) || matches!( operand.kind, diff --git a/crates/stela-compiler/src/x86_64/sve/integer_bits.rs b/crates/stela-compiler/src/x86_64/sve/integer_bits.rs index 64637fe2e0..0c5946e592 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_bits.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_bits.rs @@ -1,4 +1,6 @@ //! SVE predicated bit operations with SSE2 or SSSE3. +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Code, Rm}; use crate::{ TargetCpu, aarch64::{ @@ -10,16 +12,12 @@ use crate::{ scalable::{load_z_chunk, read_predicate_mask, store_z_chunk}, }, }; -use alloc::vec::Vec; mod scalar; const ALTERNATING_BIT_MASK: u8 = 0x55; const TWO_BIT_GROUP_MASK: u8 = 0x33; const SCALAR_WORD_VECTOR_BYTES: usize = 256; -const MOV_RAX_IMM64: [u8; 2] = [0x48, 0xb8]; -const PSADBW: [u8; 3] = [0x66, 0x0f, 0xf6]; -const REGISTER_MODRM: u8 = 0xc0; const SOURCE_XMM: u8 = 0; const OLD_DESTINATION_XMM: u8 = 7; const PREDICATE_XMM: u8 = 6; @@ -33,24 +31,23 @@ const SWAP_ADJACENT: u8 = 0xb1; const REVERSE_FOUR: u8 = 0x1b; const DUPLICATE_HIGH_DWORDS: u8 = 0xf5; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn constant_qword(code: &mut Vec, destination: u8, value: u64) { - code.extend(MOV_RAX_IMM64); - code.extend(value.to_le_bytes()); +fn constant_qword(code: &mut Code, destination: u8, value: u64) { + code.asm().mov_imm64(Rax, value); packed(code, Host::MoveGprQword, destination, 0); } -fn repeated_constant(code: &mut Vec, destination: u8, element: ElementSize, value: u64) { +fn repeated_constant(code: &mut Code, destination: u8, element: ElementSize, value: u64) { let source = value.to_le_bytes(); let repeated = core::array::from_fn(|i| source[i % element.bytes()]); constant_qword(code, destination, u64::from_le_bytes(repeated)); packed(code, Host::UnpackLowQword, destination, destination); } -fn table_constant(code: &mut Vec, destination: u8, scratch: u8, values: [u8; 16]) { +fn table_constant(code: &mut Code, destination: u8, scratch: u8, values: [u8; 16]) { constant_qword( code, destination, @@ -64,9 +61,14 @@ fn table_constant(code: &mut Vec, destination: u8, scratch: u8, values: [u8; packed(code, Host::UnpackLowQword, destination, scratch); } -fn shuffle(code: &mut Vec, opcode: Host, destination: u8, source: u8, control: u8) { - packed(code, opcode, destination, source); - code.push(control); +fn shuffle(code: &mut Code, opcode: Host, destination: u8, source: u8, control: u8) { + code.asm().simd_imm( + opcode, + destination, + Rm::Xmm(source), + control, + TargetCpu::Baseline, + ); } fn add(element: ElementSize) -> Host { @@ -90,7 +92,7 @@ fn subtract(element: ElementSize) -> Host { } /// Immediate logical element shifts. SSE2 byte shifts need a post-shift mask. -fn logical_shift(code: &mut Vec, xmm: u8, element: ElementSize, amount: u8, left: bool) { +fn logical_shift(code: &mut Code, xmm: u8, element: ElementSize, amount: u8, left: bool) { let opcode = match (element, left) { (ElementSize::Byte | ElementSize::Halfword, false) => Shift::RightWord, (ElementSize::Byte | ElementSize::Halfword, true) => Shift::LeftWord, @@ -113,7 +115,7 @@ fn logical_shift(code: &mut Vec, xmm: u8, element: ElementSize, amount: u8, } /// Compare against zero in XMM3. Qword equality requires both dwords to match. -fn equal_zero(code: &mut Vec, xmm: u8, element: ElementSize, target: TargetCpu) { +fn equal_zero(code: &mut Code, xmm: u8, element: ElementSize, target: TargetCpu) { if element == ElementSize::Doubleword && target.supports(TargetCpu::Sse41) { Host::EqualQword.register(code, xmm, 3, target); return; @@ -131,7 +133,7 @@ fn equal_zero(code: &mut Vec, xmm: u8, element: ElementSize, target: TargetC } } -fn leading_count(code: &mut Vec, element: ElementSize, sign: bool, target: TargetCpu) { +fn leading_count(code: &mut Code, element: ElementSize, sign: bool, target: TargetCpu) { if sign { if element == ElementSize::Doubleword { packed(code, Host::MoveAligned, 1, SOURCE_XMM); @@ -177,7 +179,7 @@ fn leading_count(code: &mut Vec, element: ElementSize, sign: bool, target: T packed(code, Host::MoveAligned, SOURCE_XMM, 2); } -fn nibble_lookup(code: &mut Vec, reverse: bool, target: TargetCpu) { +fn nibble_lookup(code: &mut Code, reverse: bool, target: TargetCpu) { let values = core::array::from_fn(|i| { if reverse { (i as u8).reverse_bits() >> NIBBLE_BITS @@ -203,7 +205,7 @@ fn nibble_lookup(code: &mut Vec, reverse: bool, target: TargetCpu) { packed(code, Host::MoveAligned, SOURCE_XMM, 2); } -fn population_bytes(code: &mut Vec, target: TargetCpu) { +fn population_bytes(code: &mut Code, target: TargetCpu) { if target.supports(TargetCpu::Ssse3) { nibble_lookup(code, false, target); return; @@ -226,12 +228,11 @@ fn population_bytes(code: &mut Vec, target: TargetCpu) { packed(code, Host::And, SOURCE_XMM, 2); } -fn population(code: &mut Vec, element: ElementSize, target: TargetCpu) { +fn population(code: &mut Code, element: ElementSize, target: TargetCpu) { population_bytes(code, target); if element == ElementSize::Doubleword { packed(code, Host::Xor, 1, 1); - code.extend(PSADBW); - code.push(REGISTER_MODRM | (SOURCE_XMM << 3) | 1); + code.asm().psadbw(SOURCE_XMM, Rm::Xmm(1)); return; } for (width, shift, mask) in [ @@ -249,7 +250,7 @@ fn population(code: &mut Vec, element: ElementSize, target: TargetCpu) { } } -fn reverse_groups(code: &mut Vec, element: ElementSize, group: ElementSize) { +fn reverse_groups(code: &mut Code, element: ElementSize, group: ElementSize) { if group == ElementSize::Byte { packed(code, Host::MoveAligned, 1, SOURCE_XMM); Shift::RightWord.emit(code, 1, BYTE_BITS); @@ -275,7 +276,7 @@ fn reverse_groups(code: &mut Vec, element: ElementSize, group: ElementSize) } } -fn reverse_bits(code: &mut Vec, element: ElementSize, target: TargetCpu) { +fn reverse_bits(code: &mut Code, element: ElementSize, target: TargetCpu) { if target.supports(TargetCpu::Ssse3) { nibble_lookup(code, true, target); } else { @@ -308,7 +309,7 @@ pub(crate) fn requires_declared_dit_zero(operand: Operand, length: VectorLength) && length.bytes() == SCALAR_WORD_VECTOR_BYTES)) } -pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let Predication::Merging(predicate) = operand.predication else { unreachable!("bit-operation decoder owns only merging forms"); }; diff --git a/crates/stela-compiler/src/x86_64/sve/integer_bits/scalar.rs b/crates/stela-compiler/src/x86_64/sve/integer_bits/scalar.rs index 8c6505e1a3..64c67d555b 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_bits/scalar.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_bits/scalar.rs @@ -1,77 +1,52 @@ //! Scalar leading-bit counts. BSR's result is undefined for zero and is fixed up. use crate::aarch64::scalable::ElementSize; -use alloc::vec::Vec; +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rdx, Rsp}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, ShiftOp, Size}; + const CHUNK_BYTES: usize = 16; const RESULT_SLOT: u8 = CHUNK_BYTES as u8; const STACK_BYTES: u8 = 2 * CHUNK_BYTES as u8; -const SUB_RSP: [u8; 3] = [0x48, 0x83, 0xec]; -const ADD_RSP: [u8; 3] = [0x48, 0x83, 0xc4]; -const MOVDQU_STORE_RSP: [u8; 4] = [0xf3, 0x0f, 0x7f, 0x44]; -const MOVDQU_LOAD_RSP: [u8; 4] = [0xf3, 0x0f, 0x6f, 0x44]; -const STACK_SIB: u8 = 0x24; -const MOVZX_EAX_BYTE: [u8; 3] = [0x0f, 0xb6, 0x44]; -const MOVSX_RAX_BYTE: [u8; 4] = [0x48, 0x0f, 0xbe, 0x44]; -const MOVZX_EAX_WORD: [u8; 3] = [0x0f, 0xb7, 0x44]; -const MOVSX_RAX_WORD: [u8; 4] = [0x48, 0x0f, 0xbf, 0x44]; -const MOV_EAX_DWORD: [u8; 2] = [0x8b, 0x44]; -const MOVSXD_RAX_DWORD: [u8; 3] = [0x48, 0x63, 0x44]; -const MOV_RAX_QWORD: [u8; 3] = [0x48, 0x8b, 0x44]; -const MOV_BYTE_AL: [u8; 2] = [0x88, 0x44]; -const MOV_WORD_AX: [u8; 3] = [0x66, 0x89, 0x44]; -const MOV_DWORD_EAX: [u8; 2] = [0x89, 0x44]; -const MOV_QWORD_RAX: [u8; 3] = [0x48, 0x89, 0x44]; -const MOV_RDX_RAX: [u8; 3] = [0x48, 0x89, 0xc2]; -const SAR_RDX: [u8; 3] = [0x48, 0xc1, 0xfa]; -const XOR_RAX_RDX: [u8; 3] = [0x48, 0x31, 0xd0]; -const BSR_RDX_RAX: [u8; 4] = [0x48, 0x0f, 0xbd, 0xd0]; -const MOV_RCX_SIGNED_IMM32: [u8; 3] = [0x48, 0xc7, 0xc1]; -const CMOVZ_RDX_RCX: [u8; 4] = [0x48, 0x0f, 0x44, 0xd1]; -const MOV_EAX_IMM32: u8 = 0xb8; -const SUB_RAX_RDX: [u8; 3] = [0x48, 0x29, 0xd0]; -fn stack(code: &mut Vec, opcode: &[u8], slot: u8) { - code.extend(opcode); - code.extend([STACK_SIB, slot]); + +fn stack(slot: u8) -> Mem { + Mem::base_disp8(Rsp, slot as i8) } -pub(super) fn chunk(code: &mut Vec, element: ElementSize, sign: bool) { - code.extend(SUB_RSP); - code.push(STACK_BYTES); - stack(code, &MOVDQU_STORE_RSP, 0); + +pub(super) fn chunk(code: &mut Code, element: ElementSize, sign: bool) { + let mut asm = code.asm(); + asm.alu_imm8(Alu::Sub, Size::Qword, Rsp, STACK_BYTES as i8); + asm.movdqu_store(stack(0), 0); for offset in (0..CHUNK_BYTES).step_by(element.bytes()) { - let load: &[u8] = match (element, sign) { - (ElementSize::Byte, false) => &MOVZX_EAX_BYTE, - (ElementSize::Byte, true) => &MOVSX_RAX_BYTE, - (ElementSize::Halfword, false) => &MOVZX_EAX_WORD, - (ElementSize::Halfword, true) => &MOVSX_RAX_WORD, - (ElementSize::Word, false) => &MOV_EAX_DWORD, - (ElementSize::Word, true) => &MOVSXD_RAX_DWORD, - (ElementSize::Doubleword, _) => &MOV_RAX_QWORD, + let lane = stack(offset as u8); + match (element, sign) { + (ElementSize::Byte, false) => asm.movzx(Size::Dword, Rax, Size::Byte, lane), + (ElementSize::Byte, true) => asm.movsx(Size::Qword, Rax, Size::Byte, lane), + (ElementSize::Halfword, false) => asm.movzx(Size::Dword, Rax, Size::Word, lane), + (ElementSize::Halfword, true) => asm.movsx(Size::Qword, Rax, Size::Word, lane), + (ElementSize::Word, false) => asm.mov_load(Size::Dword, Rax, lane), + (ElementSize::Word, true) => asm.movsxd(Rax, lane), + (ElementSize::Doubleword, _) => asm.mov_load(Size::Qword, Rax, lane), _ => unreachable!(), - }; - stack(code, load, offset as u8); - if sign { - code.extend(MOV_RDX_RAX); - code.extend(SAR_RDX); - code.push(u64::BITS as u8 - 1); - code.extend(XOR_RAX_RDX); } - code.extend(BSR_RDX_RAX); + if sign { + asm.mov(Size::Qword, Rdx, Rax); + asm.shift_imm(ShiftOp::Sar, Size::Qword, Rdx, u64::BITS as u8 - 1); + asm.alu(Alu::Xor, Size::Qword, Rax, Rdx); + } + asm.bsr(Size::Qword, Rdx, Rax); // MOV preserves BSR's ZF. Zero maps to -1 before any arithmetic uses it. - code.extend(MOV_RCX_SIGNED_IMM32); - code.extend((-1_i32).to_le_bytes()); - code.extend(CMOVZ_RDX_RCX); - code.push(MOV_EAX_IMM32); - code.extend((element.bits() as u32 - 1 - u32::from(sign)).to_le_bytes()); - code.extend(SUB_RAX_RDX); - let store: &[u8] = match element { - ElementSize::Byte => &MOV_BYTE_AL, - ElementSize::Halfword => &MOV_WORD_AX, - ElementSize::Word => &MOV_DWORD_EAX, - ElementSize::Doubleword => &MOV_QWORD_RAX, + asm.mov_rm_imm32(Size::Qword, Rcx, -1); + asm.cmov(Cond::E, Size::Qword, Rdx, Rcx); + asm.mov_imm32(Rax, element.bits() as u32 - 1 - u32::from(sign)); + asm.alu(Alu::Sub, Size::Qword, Rax, Rdx); + let size = match element { + ElementSize::Byte => Size::Byte, + ElementSize::Halfword => Size::Word, + ElementSize::Word => Size::Dword, + ElementSize::Doubleword => Size::Qword, _ => unreachable!(), }; - stack(code, store, RESULT_SLOT + offset as u8); + asm.mov_store(size, stack(RESULT_SLOT + offset as u8), Rax); } - stack(code, &MOVDQU_LOAD_RSP, RESULT_SLOT); - code.extend(ADD_RSP); - code.push(STACK_BYTES); + asm.movdqu_load(0, stack(RESULT_SLOT)); + asm.alu_imm8(Alu::Add, Size::Qword, Rsp, STACK_BYTES as i8); } diff --git a/crates/stela-compiler/src/x86_64/sve/integer_comparison.rs b/crates/stela-compiler/src/x86_64/sve/integer_comparison.rs index a0f6577d6d..08974283a3 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_comparison.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_comparison.rs @@ -1,20 +1,20 @@ //! SVE integer comparisons into predicates. use crate::TargetCpu; +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ElementSize, VectorLength}; use crate::aarch64::sve::integer_comparison::{Operand, Relation, Right}; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdi, Rdx, Rsp}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, Rm, ShiftOp, Size}; use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; -use alloc::vec::Vec; const XMM_LEFT: u8 = 0; const XMM_RIGHT: u8 = 1; const XMM_HIGH_GREATER: u8 = 2; const XMM_HIGH_EQUAL: u8 = 3; const XMM_BIAS: u8 = 4; -const MOD_REGISTER: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; const REPEAT_BYTE_IN_DWORD: u32 = 0x0101_0101; const REPEAT_HALFWORD_IN_DWORD: u32 = 0x0001_0001; -const MOVD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; const XMM_CHUNK_BYTES: usize = 16; const BYTE_SIGN_SHIFT: u8 = 7; const HALFWORD_SIGN_SHIFT: u8 = 15; @@ -23,7 +23,6 @@ const DOUBLEWORD_SIGN_SHIFT: u8 = 63; const REPLICATE_HIGH_WORDS: u8 = 0xf5; const REPLICATE_LOW_WORDS: u8 = 0xa0; const SWAP_ADJACENT_WORDS: u8 = 0xb1; -const XOR_EAX_IMMEDIATE: u8 = 0x35; const TRUTH_BYTE_MASK: u32 = 0xffff; const PREDICATE_RESULT_STACK_BYTES: u8 = 32; @@ -32,51 +31,6 @@ const VECTOR_CHUNKS_PER_PREDICATE_QWORD: usize = 4; const PREDICATE_RESULT_CHUNK_BYTES: usize = 2; const QWORD_BYTES: usize = 8; const BYTE_BITS: u8 = 8; -const MOV_EAX_IMMEDIATE: u8 = 0xb8; -const MOV_RAX_SIGNED_IMMEDIATE: &[u8] = &[0x48, 0xc7, 0xc0]; -const MOVQ_XMM_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e]; -const MOV_R8D_EAX: &[u8] = &[0x41, 0x89, 0xc0]; -const MOV_EAX_R8D: &[u8] = &[0x44, 0x89, 0xc0]; -const MOV_EDX_EAX: &[u8] = &[0x89, 0xc2]; -const AND_EAX_EDX: &[u8] = &[0x21, 0xd0]; -const AND_EAX_IMMEDIATE: u8 = 0x25; -const SHR_ECX: &[u8] = &[0xc1, 0xe9]; -const SHL_ECX: &[u8] = &[0xc1, 0xe1]; -const SHL_EAX: &[u8] = &[0xc1, 0xe0]; -const SHR_RAX: &[u8] = &[0x48, 0xc1, 0xe8]; -const SUB_RSP_IMMEDIATE: &[u8] = &[0x48, 0x83, 0xec]; -const ADD_RSP_IMMEDIATE: &[u8] = &[0x48, 0x83, 0xc4]; -const STORE_STACK_AX: &[u8] = &[0x66, 0x89, 0x44, 0x24]; -const LOAD_STACK_RAX: &[u8] = &[0x48, 0x8b, 0x44, 0x24]; -const LOAD_STACK_EAX: &[u8] = &[0x8b, 0x44, 0x24]; -const LOAD_STACK_WORD_EAX: &[u8] = &[0x0f, 0xb7, 0x44, 0x24]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const MOVABS_RCX_IMMEDIATE: &[u8] = &[0x48, 0xb9]; -const AND_RDX_RCX: &[u8] = &[0x48, 0x21, 0xca]; -const XOR_R9D_R9D: &[u8] = &[0x45, 0x31, 0xc9]; -const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; -const MOV_R11D_IMMEDIATE: &[u8] = &[0x41, 0xbb]; -const OR_R10_RAX: &[u8] = &[0x49, 0x09, 0xc2]; -const TEST_RDX_RDX: &[u8] = &[0x48, 0x85, 0xd2]; -const TEST_R9D_IMMEDIATE: &[u8] = &[0x41, 0xf7, 0xc1]; -const BSF_RCX_RDX: &[u8] = &[0x48, 0x0f, 0xbc, 0xca]; -const BSR_RCX_RDX: &[u8] = &[0x48, 0x0f, 0xbd, 0xca]; -const BT_RAX_RCX: &[u8] = &[0x48, 0x0f, 0xa3, 0xc8]; -const SETC_CL: &[u8] = &[0x0f, 0x92, 0xc1]; -const MOVZX_ECX_CL: &[u8] = &[0x0f, 0xb6, 0xc9]; -const OR_R9D_ECX: &[u8] = &[0x41, 0x09, 0xc9]; -const OR_R9D_ONE: &[u8] = &[0x41, 0x83, 0xc9, 1]; -const SETNC_R11B: &[u8] = &[0x41, 0x0f, 0x93, 0xc3]; -const TEST_R10_R10: &[u8] = &[0x4d, 0x85, 0xd2]; -const SETZ_AL: &[u8] = &[0x0f, 0x94, 0xc0]; -const MOVZX_EAX_AL: &[u8] = &[0x0f, 0xb6, 0xc0]; -const AND_R9D_IMMEDIATE: &[u8] = &[0x41, 0x81, 0xe1]; -const SHL_R11D: &[u8] = &[0x41, 0xc1, 0xe3]; -const OR_EAX_R9D: &[u8] = &[0x44, 0x09, 0xc8]; -const OR_EAX_R11D: &[u8] = &[0x44, 0x09, 0xd8]; -const STORE_STATE_EAX: &[u8] = &[0x89, 0x87]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; const NZCV_N_SHIFT: u8 = 31; const NZCV_Z_SHIFT: u8 = 30; const NZCV_C_SHIFT: u8 = 29; @@ -86,17 +40,17 @@ const XMM_IMMEDIATE: u8 = 5; mod wide; -fn register_fields(code: &mut Vec, opcode: &[u8], reg: u8, rm: u8) { - code.extend_from_slice(opcode); - code.push(MOD_REGISTER | (reg << REGISTER_SHIFT) | rm); +fn shuffle(code: &mut Code, destination: u8, source: u8, control: u8) { + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(source), + control, + TargetCpu::Baseline, + ); } -fn shuffle(code: &mut Vec, destination: u8, source: u8, control: u8) { - Host::ShuffleDword.register(code, destination, source, TargetCpu::Baseline); - code.push(control); -} - -fn sign_bias(code: &mut Vec, size: ElementSize) { +fn sign_bias(code: &mut Code, size: ElementSize) { Host::EqualDword.register(code, XMM_BIAS, XMM_BIAS, TargetCpu::Baseline); let (opcode, amount) = match size { ElementSize::Byte => (Shift::LeftWord, BYTE_SIGN_SHIFT), @@ -111,13 +65,13 @@ fn sign_bias(code: &mut Vec, size: ElementSize) { } } -fn equal_doublewords(code: &mut Vec, left: u8, right: u8) { +fn equal_doublewords(code: &mut Code, left: u8, right: u8) { Host::EqualDword.register(code, left, right, TargetCpu::Baseline); shuffle(code, XMM_HIGH_GREATER, left, SWAP_ADJACENT_WORDS); Host::And.register(code, left, XMM_HIGH_GREATER, TargetCpu::Baseline); } -fn greater_doublewords(code: &mut Vec, left: u8, right: u8) { +fn greater_doublewords(code: &mut Code, left: u8, right: u8) { Host::MoveAligned.register(code, XMM_HIGH_GREATER, left, TargetCpu::Baseline); Host::GreaterDword.register(code, XMM_HIGH_GREATER, right, TargetCpu::Baseline); shuffle( @@ -139,14 +93,14 @@ fn greater_doublewords(code: &mut Vec, left: u8, right: u8) { } fn compare_lanes( - code: &mut Vec, + code: &mut Code, relation: Relation, unsigned: bool, size: ElementSize, target: TargetCpu, -) -> Result<(u8, bool), ()> { +) -> Result<(u8, bool), Unsupported> { if size == ElementSize::Quadword { - return Err(()); + return Err(Unsupported); } let equality = matches!(relation, Relation::Equal | Relation::NotEqual); let reverse = matches!(relation, Relation::GreaterEqual | Relation::Less); @@ -197,12 +151,12 @@ fn compare_lanes( /// Clobbers XMM0..XMM4; preserves all GPRs, host flags and MXCSR. Callers that /// select source values must preserve their originals outside this scratch set. pub(crate) fn emit_compare_mask( - code: &mut Vec, + code: &mut Code, relation: Relation, unsigned: bool, size: ElementSize, target: TargetCpu, -) -> Result { +) -> Result { let (result, invert) = compare_lanes(code, relation, unsigned, size, target)?; if invert { Host::EqualDword.register(code, XMM_BIAS, XMM_BIAS, TargetCpu::Baseline); @@ -216,43 +170,29 @@ pub(crate) fn emit_compare_mask( /// Governing masks, packed lane-start bits, NZCV and state commits belong to the /// outer instruction emitter. Immediate/wide operands must be prepared there. pub(crate) fn emit_compare_chunk( - code: &mut Vec, + code: &mut Code, relation: Relation, unsigned: bool, size: ElementSize, target: TargetCpu, -) -> Result<(), ()> { +) -> Result<(), Unsupported> { let (result, invert) = compare_lanes(code, relation, unsigned, size, target)?; Host::ByteSignMask.register(code, 0, result, TargetCpu::Baseline); if invert { - code.push(XOR_EAX_IMMEDIATE); - code.extend_from_slice(&TRUTH_BYTE_MASK.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Xor, Size::Dword, TRUTH_BYTE_MASK as i32); } Ok(()) } -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend_from_slice(opcode); - let position = code.len(); - code.extend(0i32.to_le_bytes()); - position -} - -fn finish_branch(code: &mut [u8], position: usize) { - let displacement = (code.len() - position - size_of::()) as i32; - code[position..position + size_of::()].copy_from_slice(&displacement.to_le_bytes()); -} - -fn splat_immediate(code: &mut Vec, value: i16, size: ElementSize) { +fn splat_immediate(code: &mut Code, value: i16, size: ElementSize) { if size == ElementSize::Doubleword { if value < 0 { - code.extend_from_slice(MOV_RAX_SIGNED_IMMEDIATE); - code.extend(i32::from(value).to_le_bytes()); + code.asm().mov_rm_imm32(Size::Qword, Rax, i32::from(value)); } else { - code.push(MOV_EAX_IMMEDIATE); - code.extend((value as u32).to_le_bytes()); + code.asm().mov_imm32(Rax, value as u32); } - register_fields(code, MOVQ_XMM_RAX, XMM_IMMEDIATE, 0); + code.asm().movq_to_xmm(XMM_IMMEDIATE, Rax); Host::UnpackLowQword.register(code, XMM_IMMEDIATE, XMM_IMMEDIATE, TargetCpu::Baseline); } else { let bits = match size { @@ -261,62 +201,65 @@ fn splat_immediate(code: &mut Vec, value: i16, size: ElementSize) { ElementSize::Word => value as u32, _ => unreachable!("decoded comparison element size"), }; - code.push(MOV_EAX_IMMEDIATE); - code.extend(bits.to_le_bytes()); - register_fields(code, MOVD_XMM_EAX, XMM_IMMEDIATE, 0); + code.asm().mov_imm32(Rax, bits); + code.asm().movd_to_xmm(XMM_IMMEDIATE, Rax); shuffle(code, XMM_IMMEDIATE, XMM_IMMEDIATE, 0); } } -fn load_result_chunk(code: &mut Vec, chunk: usize, predicate_bytes: usize) { +fn load_result_chunk(code: &mut Code, chunk: usize, predicate_bytes: usize) { let offset = chunk * QWORD_BYTES; - code.extend_from_slice(match (predicate_bytes - offset).min(QWORD_BYTES) { - 2 => LOAD_STACK_WORD_EAX, - 4 => LOAD_STACK_EAX, - 8 => LOAD_STACK_RAX, + let source = Mem::base_disp8(Rsp, offset as i8); + let mut asm = code.asm(); + match (predicate_bytes - offset).min(QWORD_BYTES) { + 2 => asm.movzx(Size::Dword, Rax, Size::Word, source), + 4 => asm.mov_load(Size::Dword, Rax, source), + 8 => asm.mov_load(Size::Qword, Rax, source), _ => unreachable!("validated packed predicate chunk size"), - }); - code.push(offset as u8); + } } -fn accumulate_predtest(code: &mut Vec) { +fn accumulate_predtest(code: &mut Code) { // RDX is the effective governing64-bit mask; RAX is the governed result. // R9 holds N plus a first-active-seen marker, R10 any result and R11 !last. - code.extend_from_slice(OR_R10_RAX); - code.extend_from_slice(TEST_RDX_RDX); - let empty = branch(code, JZ_REL32); - code.extend_from_slice(TEST_R9D_IMMEDIATE); - code.extend(FIRST_ACTIVE_SEEN.to_le_bytes()); - let seen = branch(code, JNZ_REL32); - code.extend_from_slice(BSF_RCX_RDX); - code.extend_from_slice(BT_RAX_RCX); - code.extend_from_slice(SETC_CL); - code.extend_from_slice(MOVZX_ECX_CL); - code.extend_from_slice(SHL_ECX); - code.push(NZCV_N_SHIFT); - code.extend_from_slice(OR_R9D_ECX); - code.extend_from_slice(OR_R9D_ONE); - finish_branch(code, seen); - code.extend_from_slice(BSR_RCX_RDX); - code.extend_from_slice(BT_RAX_RCX); - code.extend_from_slice(SETNC_R11B); - finish_branch(code, empty); + let mut asm = code.asm(); + asm.alu(Alu::Or, Size::Qword, R10, Rax); + asm.test(Size::Qword, Rdx, Rdx); + let empty = asm.jcc(Cond::E); + asm.test_imm(Size::Dword, R9, FIRST_ACTIVE_SEEN as i32); + let seen = asm.jcc(Cond::Ne); + asm.bsf(Size::Qword, Rcx, Rdx); + asm.bit(BitTest::Bt, Size::Qword, Rax, Rcx); + asm.setcc(Cond::B, Rcx); + asm.movzx(Size::Dword, Rcx, Size::Byte, Rcx); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rcx, NZCV_N_SHIFT); + asm.alu(Alu::Or, Size::Dword, R9, Rcx); + asm.alu_imm8(Alu::Or, Size::Dword, R9, 1); + asm.bind(seen); + asm.bsr(Size::Qword, Rcx, Rdx); + asm.bit(BitTest::Bt, Size::Qword, Rax, Rcx); + asm.setcc(Cond::Ae, R11); + asm.bind(empty); } /// Comparison results are staged on the stack until every governing bit and /// PredTest input is consumed, so Pd == Pg sees the original predicate /// throughout. -pub(crate) fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { use crate::x86_64::scalable::{load_z_chunk, read_predicate_chunk, write_predicate_chunk}; let single_chunk = length.chunks() == 1; if !single_chunk { - code.extend_from_slice(SUB_RSP_IMMEDIATE); - code.push(PREDICATE_RESULT_STACK_BYTES); + code.asm().alu_imm8( + Alu::Sub, + Size::Qword, + Rsp, + PREDICATE_RESULT_STACK_BYTES as i8, + ); } - code.extend_from_slice(XOR_R9D_R9D); - code.extend_from_slice(XOR_R10D_R10D); - code.extend_from_slice(MOV_R11D_IMMEDIATE); - code.extend(INITIAL_CARRY.to_le_bytes()); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, R9, R9); + asm.alu(Alu::Xor, Size::Dword, R10, R10); + asm.mov_imm32(R11, INITIAL_CARRY); if let Right::Immediate(value) = operand.right { splat_immediate(code, value, operand.element_size); } @@ -354,7 +297,7 @@ pub(crate) fn emit(code: &mut Vec, operand: Operand, length: VectorLength, t .expect("decoded comparison element size"); } } - code.extend_from_slice(MOV_R8D_EAX); + code.asm().mov(Size::Dword, R8, Rax); read_predicate_chunk( code, operand.governing, @@ -363,20 +306,23 @@ pub(crate) fn emit(code: &mut Vec, operand: Operand, length: VectorLength, t ); let shift = (chunk % VECTOR_CHUNKS_PER_PREDICATE_QWORD) * PREDICATE_BITS_PER_VECTOR_CHUNK; if shift != 0 { - code.extend_from_slice(SHR_RAX); - code.push(shift as u8); + code.asm() + .shift_imm(ShiftOp::Shr, Size::Qword, Rax, shift as u8); } - code.push(AND_EAX_IMMEDIATE); - code.extend(leading.to_le_bytes()); - code.extend_from_slice(MOV_EDX_EAX); - code.extend_from_slice(MOV_EAX_R8D); - code.extend_from_slice(AND_EAX_EDX); + let mut asm = code.asm(); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, leading as i32); + asm.mov(Size::Dword, Rdx, Rax); + asm.mov(Size::Dword, Rax, R8); + asm.alu(Alu::And, Size::Dword, Rax, Rdx); if single_chunk { - code.extend_from_slice(MOV_R8D_EAX); + code.asm().mov(Size::Dword, R8, Rax); accumulate_predtest(code); } else { - code.extend_from_slice(STORE_STACK_AX); - code.push((chunk * PREDICATE_RESULT_CHUNK_BYTES) as u8); + code.asm().mov_store( + Size::Word, + Mem::base_disp8(Rsp, (chunk * PREDICATE_RESULT_CHUNK_BYTES) as i8), + Rax, + ); } } if !single_chunk { @@ -386,38 +332,43 @@ pub(crate) fn emit(code: &mut Vec, operand: Operand, length: VectorLength, t .sum(); for chunk in 0..length.predicate_bytes().div_ceil(QWORD_BYTES) { read_predicate_chunk(code, operand.governing, chunk, length); - code.extend_from_slice(MOV_RDX_RAX); - code.extend_from_slice(MOVABS_RCX_IMMEDIATE); - code.extend(packed_leading.to_le_bytes()); - code.extend_from_slice(AND_RDX_RCX); + let mut asm = code.asm(); + asm.mov(Size::Qword, Rdx, Rax); + asm.mov_imm64(Rcx, packed_leading); + asm.alu(Alu::And, Size::Qword, Rdx, Rcx); load_result_chunk(code, chunk, length.predicate_bytes()); accumulate_predtest(code); } } - code.extend_from_slice(TEST_R10_R10); - code.extend_from_slice(SETZ_AL); - code.extend_from_slice(MOVZX_EAX_AL); - code.extend_from_slice(SHL_EAX); - code.push(NZCV_Z_SHIFT); - code.extend_from_slice(AND_R9D_IMMEDIATE); - code.extend((1u32 << NZCV_N_SHIFT).to_le_bytes()); - code.extend_from_slice(SHL_R11D); - code.push(NZCV_C_SHIFT); - code.extend_from_slice(OR_EAX_R9D); - code.extend_from_slice(OR_EAX_R11D); - code.extend_from_slice(STORE_STATE_EAX); - code.extend((core::mem::offset_of!(crate::GuestState, nzcv) as u32).to_le_bytes()); + let mut asm = code.asm(); + asm.test(Size::Qword, R10, R10); + asm.setcc(Cond::E, Rax); + asm.movzx(Size::Dword, Rax, Size::Byte, Rax); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, NZCV_Z_SHIFT); + asm.alu_imm32(Alu::And, Size::Dword, R9, (1u32 << NZCV_N_SHIFT) as i32); + asm.shift_imm(ShiftOp::Shl, Size::Dword, R11, NZCV_C_SHIFT); + asm.alu(Alu::Or, Size::Dword, Rax, R9); + asm.alu(Alu::Or, Size::Dword, Rax, R11); + asm.mov_store( + Size::Dword, + Mem::base_disp32(Rdi, (core::mem::offset_of!(crate::GuestState, nzcv)) as i32), + Rax, + ); for chunk in 0..length.predicate_bytes().div_ceil(QWORD_BYTES) { if single_chunk { - code.extend_from_slice(MOV_EAX_R8D); + code.asm().mov(Size::Dword, Rax, R8); } else { load_result_chunk(code, chunk, length.predicate_bytes()); } write_predicate_chunk(code, operand.destination, chunk, length); } if !single_chunk { - code.extend_from_slice(ADD_RSP_IMMEDIATE); - code.push(PREDICATE_RESULT_STACK_BYTES); + code.asm().alu_imm8( + Alu::Add, + Size::Qword, + Rsp, + PREDICATE_RESULT_STACK_BYTES as i8, + ); } } @@ -425,7 +376,6 @@ pub(crate) fn emit(code: &mut Vec, operand: Operand, length: VectorLength, t mod tests { use super::*; use alloc::vec; - use alloc::vec::Vec; #[test] fn optional_doubleword_opcodes_require_exact_tier() { @@ -441,7 +391,7 @@ mod tests { Host::GreaterQword.encoding(), ), ] { - let mut baseline = Vec::new(); + let mut baseline = Code::new(); emit_compare_chunk( &mut baseline, relation, @@ -455,7 +405,7 @@ mod tests { .windows(optional.len()) .any(|bytes| bytes == optional) ); - let mut checked = Vec::new(); + let mut checked = Code::new(); emit_compare_chunk( &mut checked, relation, @@ -475,7 +425,7 @@ mod tests { #[test] fn reserved_element_width_does_not_emit_prefix() { - let mut code = vec![0x90]; + let mut code = Code::from(vec![0x90]); assert_eq!( emit_compare_chunk( &mut code, @@ -484,7 +434,7 @@ mod tests { ElementSize::Quadword, TargetCpu::Sse42 ), - Err(()) + Err(Unsupported) ); assert_eq!(code, [0x90]); } diff --git a/crates/stela-compiler/src/x86_64/sve/integer_comparison/wide.rs b/crates/stela-compiler/src/x86_64/sve/integer_comparison/wide.rs index ba8eddfb5d..d00cd117dc 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_comparison/wide.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_comparison/wide.rs @@ -1,42 +1,20 @@ //! Wide-element right-hand sides for SVE comparisons. use super::{ - AND_EAX_IMMEDIATE, BYTE_BITS, ElementSize, Host, MOV_EAX_R8D, MOV_EDX_EAX, MOVD_XMM_EAX, - MOVQ_XMM_RAX, MOVZX_EAX_AL, MOVZX_ECX_CL, Operand, QWORD_BYTES, REPEAT_BYTE_IN_DWORD, - REPEAT_HALFWORD_IN_DWORD, Relation, SHL_EAX, SHL_ECX, SHR_ECX, Shift, TargetCpu, VectorLength, - WORD_SIGN_SHIFT, XMM_BIAS, XMM_CHUNK_BYTES, XMM_HIGH_GREATER, XMM_LEFT, XMM_RIGHT, - emit_compare_chunk, emit_compare_mask, register_fields, shuffle, + BYTE_BITS, ElementSize, Host, Operand, QWORD_BYTES, REPEAT_BYTE_IN_DWORD, + REPEAT_HALFWORD_IN_DWORD, Relation, Shift, TargetCpu, VectorLength, WORD_SIGN_SHIFT, XMM_BIAS, + XMM_CHUNK_BYTES, XMM_HIGH_GREATER, XMM_LEFT, XMM_RIGHT, emit_compare_chunk, emit_compare_mask, + shuffle, }; +use crate::x86_64::asm::Gpr::{R8, Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, ShiftOp, Size, Unary}; use crate::x86_64::scalable::load_z_chunk; -use alloc::vec::Vec; const XMM_WIDE_LEFT: u8 = 6; const XMM_WIDE_RIGHT: u8 = 7; const LOW_ELEMENT_BIT: u32 = 1; const REPEAT_LOW_QWORD: u8 = 0x44; const REPEAT_HIGH_QWORD: u8 = 0xee; -const XOR_R8D_R8D: &[u8] = &[0x45, 0x31, 0xc0]; -const OR_R8D_EAX: &[u8] = &[0x41, 0x09, 0xc0]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const AND_ECX_IMMEDIATE: &[u8] = &[0x81, 0xe1]; -const OR_EAX_ECX: &[u8] = &[0x09, 0xc8]; const HALFWORD_BITS: u8 = 16; -const MOVSX_RDX_AL: &[u8] = &[0x48, 0x0f, 0xbe, 0xd0]; -const MOVSX_RDX_AX: &[u8] = &[0x48, 0x0f, 0xbf, 0xd0]; -const MOVSXD_RDX_EAX: &[u8] = &[0x48, 0x63, 0xd0]; -const MOVZX_EDX_AL: &[u8] = &[0x0f, 0xb6, 0xd0]; -const MOVZX_EDX_AX: &[u8] = &[0x0f, 0xb7, 0xd0]; -const MOVQ_RAX_XMM: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const CMP_RAX_RDX: &[u8] = &[0x48, 0x39, 0xd0]; -const SETE_CL: &[u8] = &[0x0f, 0x94, 0xc1]; -const MOVZX_EDX_DL: &[u8] = &[0x0f, 0xb6, 0xd2]; -const NEG_RDX: &[u8] = &[0x48, 0xf7, 0xda]; -const NEG_RCX: &[u8] = &[0x48, 0xf7, 0xd9]; -const CMP_RAX_SIGNED_IMMEDIATE: &[u8] = &[0x48, 0x3d]; -const SETL_DL: &[u8] = &[0x0f, 0x9c, 0xc2]; -const SETG_DL: &[u8] = &[0x0f, 0x9f, 0xc2]; -const SETNE_DL: &[u8] = &[0x0f, 0x95, 0xc2]; -const MOVZX_EAX_AX: &[u8] = &[0x0f, 0xb7, 0xc0]; -const IMUL_EAX_EAX_IMMEDIATE: &[u8] = &[0x69, 0xc0]; const IN_RANGE: u8 = 5; const OVERRIDE: u8 = 6; const HIGH_IN_RANGE: u8 = 3; @@ -82,7 +60,7 @@ fn recipe(operand: Operand, length: VectorLength, target: TargetCpu) -> Recipe { } pub(super) fn emit_chunk( - code: &mut Vec, + code: &mut Code, operand: Operand, right: u8, chunk: usize, @@ -99,7 +77,7 @@ pub(super) fn emit_chunk( } fn widen_left_pair( - code: &mut Vec, + code: &mut Code, size: ElementSize, offset: usize, unsigned: bool, @@ -150,8 +128,8 @@ fn widen_left_pair( } } -fn pair_chunk(code: &mut Vec, operand: Operand, target: TargetCpu, checked: bool) { - code.extend_from_slice(XOR_R8D_R8D); +fn pair_chunk(code: &mut Code, operand: Operand, target: TargetCpu, checked: bool) { + code.asm().alu(Alu::Xor, Size::Dword, R8, R8); let bytes = operand.element_size.bytes(); for offset in (0..XMM_CHUNK_BYTES).step_by(bytes * 2) { widen_left_pair( @@ -180,26 +158,22 @@ fn pair_chunk(code: &mut Vec, operand: Operand, target: TargetCpu, checked: target, ) .expect("wide compare stages allocated doubleword operands"); - code.extend_from_slice(MOV_ECX_EAX); - code.push(AND_EAX_IMMEDIATE); - code.extend(LOW_ELEMENT_BIT.to_le_bytes()); - code.extend_from_slice(SHR_ECX); - code.push(BYTE_BITS); - code.extend_from_slice(AND_ECX_IMMEDIATE); - code.extend(LOW_ELEMENT_BIT.to_le_bytes()); - code.extend_from_slice(SHL_ECX); - code.push(bytes as u8); - code.extend_from_slice(OR_EAX_ECX); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rcx, Rax); + asm.alu_accumulator_imm32(Alu::And, Size::Dword, LOW_ELEMENT_BIT as i32); + asm.shift_imm(ShiftOp::Shr, Size::Dword, Rcx, BYTE_BITS); + asm.alu_imm32(Alu::And, Size::Dword, Rcx, LOW_ELEMENT_BIT as i32); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rcx, bytes as u8); + asm.alu(Alu::Or, Size::Dword, Rax, Rcx); if offset != 0 { - code.extend_from_slice(SHL_EAX); - code.push(offset as u8); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, offset as u8); } - code.extend_from_slice(OR_R8D_EAX); + asm.alu(Alu::Or, Size::Dword, R8, Rax); } - code.extend_from_slice(MOV_EAX_R8D); + code.asm().mov(Size::Dword, Rax, R8); } -fn range_chunk(code: &mut Vec, operand: Operand, target: TargetCpu) { +fn range_chunk(code: &mut Code, operand: Operand, target: TargetCpu) { // Classify each full64 RHS before narrow packed comparison. let bits = operand.element_size.bits(); let ordered = !matches!(operand.relation, Relation::Equal | Relation::NotEqual); @@ -210,58 +184,56 @@ fn range_chunk(code: &mut Vec, operand: Operand, target: TargetCpu) { let (right, range, constant) = if high { Host::MoveAligned.register(code, XMM_RIGHT + 1, XMM_WIDE_RIGHT, target); Shift::RightBytes.emit(code, XMM_RIGHT + 1, QWORD_BYTES as u8); - register_fields(code, MOVQ_RAX_XMM, XMM_RIGHT + 1, 0); + code.asm().movq_from_xmm(Rax, XMM_RIGHT + 1); (XMM_RIGHT + 1, HIGH_IN_RANGE, HIGH_OVERRIDE) } else { - register_fields(code, MOVQ_RAX_XMM, XMM_WIDE_RIGHT, 0); + code.asm().movq_from_xmm(Rax, XMM_WIDE_RIGHT); (XMM_RIGHT, IN_RANGE, OVERRIDE) }; - code.extend_from_slice(match (operand.element_size, operand.unsigned) { - (ElementSize::Byte, false) => MOVSX_RDX_AL, - (ElementSize::Halfword, false) => MOVSX_RDX_AX, - (ElementSize::Word, false) => MOVSXD_RDX_EAX, - (ElementSize::Byte, true) => MOVZX_EDX_AL, - (ElementSize::Halfword, true) => MOVZX_EDX_AX, - (ElementSize::Word, true) => MOV_EDX_EAX, + let mut asm = code.asm(); + match (operand.element_size, operand.unsigned) { + (ElementSize::Byte, false) => asm.movsx(Size::Qword, Rdx, Size::Byte, Rax), + (ElementSize::Halfword, false) => asm.movsx(Size::Qword, Rdx, Size::Word, Rax), + (ElementSize::Word, false) => asm.movsxd(Rdx, Rax), + (ElementSize::Byte, true) => asm.movzx(Size::Dword, Rdx, Size::Byte, Rax), + (ElementSize::Halfword, true) => asm.movzx(Size::Dword, Rdx, Size::Word, Rax), + (ElementSize::Word, true) => asm.mov(Size::Dword, Rdx, Rax), _ => unreachable!("allocated wide source width"), - }); - code.extend_from_slice(CMP_RAX_RDX); - code.extend_from_slice(SETE_CL); + } + asm.alu(Alu::Cmp, Size::Qword, Rax, Rdx); + asm.setcc(Cond::E, Rcx); if override_needed { if operand.unsigned { - code.extend_from_slice(SETNE_DL); + asm.setcc(Cond::Ne, Rdx); } else { - code.extend_from_slice(CMP_RAX_SIGNED_IMMEDIATE); let bound = if less { (1i64 << (bits - 1)) - 1 } else { -(1i64 << (bits - 1)) }; - code.extend((bound as i32).to_le_bytes()); - code.extend_from_slice(if less { SETG_DL } else { SETL_DL }); + asm.alu_accumulator_imm32(Alu::Cmp, Size::Qword, bound as i32); + asm.setcc(if less { Cond::G } else { Cond::L }, Rdx); } - code.extend_from_slice(MOVZX_EDX_DL); - code.extend_from_slice(NEG_RDX); - register_fields(code, MOVQ_XMM_RAX, constant, 2); + asm.movzx(Size::Dword, Rdx, Size::Byte, Rdx); + asm.unary(Unary::Neg, Size::Qword, Rdx); + asm.movq_to_xmm(constant, Rdx); } - code.extend_from_slice(MOVZX_ECX_CL); - code.extend_from_slice(NEG_RCX); - register_fields(code, MOVQ_XMM_RAX, range, 1); + asm.movzx(Size::Dword, Rcx, Size::Byte, Rcx); + asm.unary(Unary::Neg, Size::Qword, Rcx); + asm.movq_to_xmm(range, Rcx); match operand.element_size { ElementSize::Byte => { - code.extend_from_slice(MOVZX_EAX_AL); - code.extend_from_slice(IMUL_EAX_EAX_IMMEDIATE); - code.extend(REPEAT_BYTE_IN_DWORD.to_le_bytes()); + asm.movzx(Size::Dword, Rax, Size::Byte, Rax); + asm.imul_imm32(Size::Dword, Rax, Rax, REPEAT_BYTE_IN_DWORD as i32); } ElementSize::Halfword => { - code.extend_from_slice(MOVZX_EAX_AX); - code.extend_from_slice(IMUL_EAX_EAX_IMMEDIATE); - code.extend(REPEAT_HALFWORD_IN_DWORD.to_le_bytes()); + asm.movzx(Size::Dword, Rax, Size::Word, Rax); + asm.imul_imm32(Size::Dword, Rax, Rax, REPEAT_HALFWORD_IN_DWORD as i32); } ElementSize::Word => {} _ => unreachable!("allocated wide source width"), } - register_fields(code, MOVD_XMM_EAX, right, 0); + asm.movd_to_xmm(right, Rax); shuffle(code, right, right, 0); } Host::UnpackLowQword.register(code, XMM_RIGHT, XMM_RIGHT + 1, target); @@ -290,7 +262,8 @@ fn range_chunk(code: &mut Vec, operand: Operand, target: TargetCpu) { Host::EqualDword.register(code, XMM_BIAS, XMM_BIAS, target); Host::Xor.register(code, result, XMM_BIAS, target); } - Host::ByteSignMask.register(code, 0, result, target); + code.asm() + .simd_to_gpr(Host::ByteSignMask, Rax, result, target); } #[cfg(test)] diff --git a/crates/stela-compiler/src/x86_64/sve/integer_logic.rs b/crates/stela-compiler/src/x86_64/sve/integer_logic.rs index dc3e5d4f6e..af4ce28775 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_logic.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_logic.rs @@ -2,9 +2,10 @@ use crate::TargetCpu; use crate::aarch64::scalable::{ElementSize, Predication, VECTOR_CHUNK_BYTES, VectorLength}; use crate::aarch64::sve::integer_logic::{Boolean, CopySource, Kind, Operand, Ternary}; +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Code, Rm}; use crate::x86_64::isa::{ShiftOpcode, SimdOpcode as Host}; use crate::x86_64::scalable::{load_z_chunk, read_predicate_mask, store_z_chunk}; -use alloc::vec::Vec; const RESULT: u8 = 0; const RIGHT: u8 = 1; @@ -14,22 +15,19 @@ const CONSTANT: u8 = 4; const PREDICATE: u8 = 5; const PREDICATE_SCRATCH: u8 = 6; const PREVIOUS: u8 = 7; -const MOVABS_RAX: [u8; 2] = [0x48, 0xb8]; -const MODRM_REGISTER: u8 = 0xc0; const QWORD_BYTES: usize = 8; const BITS_PER_BYTE: usize = 8; const ADJACENT_DWORD_SWAP: u8 = 0xb1; const BROADCAST_LOW_DWORD: u8 = 0; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn constant(code: &mut Vec, value: u64) { - code.extend(MOVABS_RAX); - code.extend(value.to_le_bytes()); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MODRM_REGISTER | (CONSTANT << 3)); +fn constant(code: &mut Code, value: u64) { + code.asm().mov_imm64(Rax, value); + code.asm() + .simd(Host::MoveGprQword, CONSTANT, Rax, TargetCpu::Baseline); packed(code, Host::UnpackLowQword, CONSTANT, CONSTANT); } @@ -42,7 +40,7 @@ fn repeat_qword(value: u64, element: ElementSize) -> u64 { (0..QWORD_BYTES / element.bytes()).fold(0, |result, lane| result | (value << (lane * bits))) } -fn broadcast_scalar(code: &mut Vec, element: ElementSize) { +fn broadcast_scalar(code: &mut Code, element: ElementSize) { if element == ElementSize::Byte { packed(code, Host::UnpackLowByte, CONSTANT, CONSTANT); } @@ -52,14 +50,19 @@ fn broadcast_scalar(code: &mut Vec, element: ElementSize) { if element == ElementSize::Doubleword { packed(code, Host::UnpackLowQword, CONSTANT, CONSTANT); } else { - packed(code, Host::ShuffleDword, CONSTANT, CONSTANT); - code.push(BROADCAST_LOW_DWORD); + code.asm().simd_imm( + Host::ShuffleDword, + CONSTANT, + Rm::Xmm(CONSTANT), + BROADCAST_LOW_DWORD, + TargetCpu::Baseline, + ); } } /// Inputs XMM0/XMM1 are snapshotted source chunks. Produces XMM0 and may /// consume XMM1; RDI/R15 and guest architectural status are untouched. -pub fn emit_binary_chunk(code: &mut Vec, operation: Boolean) { +pub fn emit_binary_chunk(code: &mut Code, operation: Boolean) { match operation { Boolean::And => packed(code, Host::And, RESULT, RIGHT), Boolean::Or => packed(code, Host::Or, RESULT, RIGHT), @@ -73,7 +76,7 @@ pub fn emit_binary_chunk(code: &mut Vec, operation: Boolean) { /// XMM0 is the old destructive destination, XMM1 the right operand, XMM2 /// the mask/third source. All three must be staged before entering. -pub fn emit_ternary_chunk(code: &mut Vec, operation: Ternary) { +pub fn emit_ternary_chunk(code: &mut Code, operation: Ternary) { match operation { Ternary::BitClearXor => { packed(code, Host::AndNot, THIRD, RIGHT); @@ -103,7 +106,7 @@ pub fn emit_ternary_chunk(code: &mut Vec, operation: Ternary) { } } -fn emit_unary_chunk(code: &mut Vec, conditional: bool, element: ElementSize) { +fn emit_unary_chunk(code: &mut Code, conditional: bool, element: ElementSize) { if !conditional { packed(code, Host::EqualDword, RIGHT, RIGHT); packed(code, Host::Xor, RESULT, RIGHT); @@ -122,14 +125,19 @@ fn emit_unary_chunk(code: &mut Vec, conditional: bool, element: ElementSize) RIGHT, ); if element == ElementSize::Doubleword { - packed(code, Host::ShuffleDword, THIRD, RESULT); - code.push(ADJACENT_DWORD_SWAP); + code.asm().simd_imm( + Host::ShuffleDword, + THIRD, + Rm::Xmm(RESULT), + ADJACENT_DWORD_SWAP, + TargetCpu::Baseline, + ); packed(code, Host::And, RESULT, THIRD); } packed(code, Host::And, RESULT, CONSTANT); } -fn merge(code: &mut Vec, predication: Predication) { +fn merge(code: &mut Code, predication: Predication) { packed(code, Host::And, RESULT, PREDICATE); if matches!(predication, Predication::Merging(_)) { packed(code, Host::AndNot, PREDICATE, PREVIOUS); @@ -142,7 +150,7 @@ fn merge(code: &mut Vec, predication: Predication) { /// has no RAM accesses or guest flag changes. Per-chunk source staging is enough /// because its only cross-lane accesses remain within one 128-bit chunk; scalar /// sources are broadcast once before an aliased low-V destination can change. -pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { match operand.kind { Kind::Immediate { value, .. } => constant(code, value), Kind::Copy(CopySource::Immediate(value)) => { @@ -150,8 +158,8 @@ pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: } Kind::Copy(CopySource::General(register)) => { crate::x86_64::load(code, register); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MODRM_REGISTER | (CONSTANT << 3)); + code.asm() + .simd(Host::MoveGprQword, CONSTANT, Rax, TargetCpu::Baseline); broadcast_scalar(code, operand.element_size); } Kind::Copy(CopySource::ScalarVector(register)) => { diff --git a/crates/stela-compiler/src/x86_64/sve/integer_predicate_move.rs b/crates/stela-compiler/src/x86_64/sve/integer_predicate_move.rs index e216fe24ff..496ad728d7 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_predicate_move.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_predicate_move.rs @@ -1,12 +1,13 @@ //! PMOV between predicates and vector bitmaps. use crate::aarch64::sve::integer_predicate_move::Operand; +use crate::x86_64::asm::Gpr::{R8, R9, Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, ShiftOp, Size}; use crate::x86_64::isa::SimdOpcode as Host; use crate::x86_64::scalable::{clear_z_upper, load_z_chunk, read_predicate_chunk, store_z_chunk}; use crate::{ TargetCpu, aarch64::scalable::{BITS_PER_BYTE, ElementSize, VECTOR_CHUNK_BYTES, VectorLength}, }; -use alloc::vec::Vec; const QWORD_BITS: usize = u64::BITS as usize; const QWORD_BYTES: usize = core::mem::size_of::(); @@ -15,40 +16,22 @@ const RESULT: u8 = 0; const HIGH: u8 = 1; const MASK: u8 = 2; const PREVIOUS: u8 = 3; -const XOR_R8D_R8D: &[u8] = &[0x45, 0x31, 0xc0]; -const XOR_R9D_R9D: &[u8] = &[0x45, 0x31, 0xc9]; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const MOVABS_RAX: &[u8] = &[0x48, 0xb8]; -const MOVABS_RCX: &[u8] = &[0x48, 0xb9]; -const AND_RAX_RCX: &[u8] = &[0x48, 0x21, 0xc8]; -const AND_EAX_IMM32: &[u8] = &[0x25]; -const OR_RAX_RCX: &[u8] = &[0x48, 0x09, 0xc8]; -const SHR_RCX_IMM8: &[u8] = &[0x48, 0xc1, 0xe9]; -const SHR_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe8]; -const SHL_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe0]; -const OR_R8_RAX: &[u8] = &[0x49, 0x09, 0xc0]; -const OR_R9_RAX: &[u8] = &[0x49, 0x09, 0xc1]; -const MOVQ_XMM0_R8: &[u8] = &[0x66, 0x49, 0x0f, 0x6e, 0xc0]; -const MOVQ_XMM1_R9: &[u8] = &[0x66, 0x49, 0x0f, 0x6e, 0xc9]; -const IMUL_RAX_RCX: &[u8] = &[0x48, 0x0f, 0xaf, 0xc1]; const BYTE_LOW_BITS: u64 = 0x0101_0101_0101_0101; const BYTE_GATHER_MULTIPLIER: u64 = 0x0102_0408_1020_4080; const BYTE_GATHER_SHIFT: usize = QWORD_BITS - BITS_PER_BYTE; -const MODRM_REGISTER: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn mask_rax(code: &mut Vec, mask: u64) { +fn mask_rax(code: &mut Code, mask: u64) { if mask <= u64::from(u32::MAX) { - code.extend(AND_EAX_IMM32); - code.extend((mask as u32).to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::And, Size::Dword, mask as i32); } else { - code.extend(MOVABS_RCX); - code.extend(mask.to_le_bytes()); - code.extend(AND_RAX_RCX); + let mut asm = code.asm(); + asm.mov_imm64(Rcx, mask); + asm.alu(Alu::And, Size::Qword, Rax, Rcx); } } @@ -61,43 +44,41 @@ fn compact_mask(stride: usize, group: usize) -> u64 { } /// Compress each element-leading P bit in RAX to consecutive low bits. -fn compact(code: &mut Vec, element: ElementSize, input_bits: usize) { +fn compact(code: &mut Code, element: ElementSize, input_bits: usize) { let stride = element.bytes(); if stride == 1 { return; } if element == ElementSize::Doubleword { mask_rax(code, BYTE_LOW_BITS); - code.extend(MOVABS_RCX); - code.extend(BYTE_GATHER_MULTIPLIER.to_le_bytes()); - code.extend(IMUL_RAX_RCX); - code.extend(SHR_RAX_IMM8); - code.push(BYTE_GATHER_SHIFT as u8); + let mut asm = code.asm(); + asm.mov_imm64(Rcx, BYTE_GATHER_MULTIPLIER); + asm.imul(Size::Qword, Rax, Rcx); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rax, BYTE_GATHER_SHIFT as u8); return; } let input_mask = u64::MAX >> (QWORD_BITS - input_bits); mask_rax(code, compact_mask(stride, 1) & input_mask); let mut group = 1; while group < input_bits / stride { - code.extend(MOV_RCX_RAX); - code.extend(SHR_RCX_IMM8); - code.push(((stride - 1) * group) as u8); - code.extend(OR_RAX_RCX); + let mut asm = code.asm(); + asm.mov(Size::Qword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rcx, ((stride - 1) * group) as u8); + asm.alu(Alu::Or, Size::Qword, Rax, Rcx); group *= 2; mask_rax(code, compact_mask(stride, group) & input_mask); } } -fn constant_half(code: &mut Vec, value: u64, destination: u8) { - code.extend(MOVABS_RAX); - code.extend(value.to_le_bytes()); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MODRM_REGISTER | (destination << REGISTER_SHIFT)); +fn constant_half(code: &mut Code, value: u64, destination: u8) { + code.asm().mov_imm64(Rax, value); + code.asm() + .simd(Host::MoveGprQword, destination, Rax, TargetCpu::Baseline); } /// No guest RAM, flags or other register-bank effects. P/Z are separate banks, /// so each P chunk may be read immediately before its Z chunk is committed. -pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let stride = operand.element_size.bytes(); assert!(stride <= QWORD_BYTES); assert!(usize::from(operand.portion) < stride); @@ -114,8 +95,9 @@ pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: if chunk_start >= end || chunk_start + CHUNK_BITS <= start { continue; } - code.extend(XOR_R8D_R8D); - code.extend(XOR_R9D_R9D); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, R8, R8); + asm.alu(Alu::Xor, Size::Dword, R9, R9); for source_chunk in 0..length.predicate_bytes().div_ceil(QWORD_BYTES) { let bit_position = start + source_chunk * (QWORD_BITS / stride); if bit_position / CHUNK_BITS != destination_chunk { @@ -126,17 +108,19 @@ pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: compact(code, operand.element_size, input_bits); let shift = bit_position % QWORD_BITS; if shift != 0 { - code.extend(SHL_RAX_IMM8); - code.push(shift as u8); + code.asm() + .shift_imm(ShiftOp::Shl, Size::Qword, Rax, shift as u8); } - code.extend(if bit_position % CHUNK_BITS < QWORD_BITS { - OR_R8_RAX + let destination = if bit_position % CHUNK_BITS < QWORD_BITS { + R8 } else { - OR_R9_RAX - }); + R9 + }; + code.asm().alu(Alu::Or, Size::Qword, destination, Rax); } - code.extend(MOVQ_XMM0_R8); - code.extend(MOVQ_XMM1_R9); + let mut asm = code.asm(); + asm.movq_to_xmm(0, R8); + asm.movq_to_xmm(1, R9); packed(code, Host::UnpackLowQword, RESULT, HIGH); if operand.portion != 0 { let mut mask = 0u128; diff --git a/crates/stela-compiler/src/x86_64/sve/integer_products.rs b/crates/stela-compiler/src/x86_64/sve/integer_products.rs index b4897999df..72fad41218 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_products.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_products.rs @@ -1,11 +1,13 @@ //! SVE integer multiplies with SSE2. Indexed multipliers select within the same //! 128-bit chunk, so aliases never read an already written chunk. use crate::TargetCpu; +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ElementSize, Predication, VectorLength}; use crate::aarch64::sve::integer_products::{Kind, Multiplier, Operand, Selection}; +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Code, Rm, Size, Unary}; use crate::x86_64::isa::{ShiftOpcode, SimdOpcode as Host}; use crate::x86_64::scalable::{load_z_chunk, read_predicate_mask, store_z_chunk}; -use alloc::vec::Vec; mod complex; mod complex_wrapping; @@ -23,9 +25,6 @@ const ACCUMULATOR_OR_CONSTANT: u8 = 4; const PREDICATE: u8 = 5; const PREDICATE_SCRATCH: u8 = 6; const PREVIOUS: u8 = 7; -const MOVABS_RAX: [u8; 2] = [0x48, 0xb8]; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; const Z_REGISTERS: u8 = 32; const GOVERNING_PREDICATES: u8 = 8; const CHUNK_BYTES: usize = 16; @@ -40,20 +39,19 @@ const SELECT_LOW_PRODUCT_DWORDS: u8 = 0x88; const WORDS_PER_HALF_CHUNK: u8 = 4; const BYTE_BITS: u8 = 8; const DWORD_SIGN_SHIFT: u8 = DWORD_BITS - 1; -const MOVQ_XMM_TO_GPR: [u8; 4] = [0x66, 0x48, 0x0f, 0x7e]; -const MUL_RCX: [u8; 3] = [0x48, 0xf7, 0xe1]; -const IMUL_RCX: [u8; 3] = [0x48, 0xf7, 0xe9]; -const RAX: u8 = 0; -const RCX: u8 = 1; -const RDX: u8 = 2; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn shuffle(code: &mut Vec, opcode: Host, register: u8, control: u8) { - packed(code, opcode, register, register); - code.push(control); +fn shuffle(code: &mut Code, opcode: Host, register: u8, control: u8) { + code.asm().simd_imm( + opcode, + register, + Rm::Xmm(register), + control, + TargetCpu::Baseline, + ); } fn multiplier_element(operand: Operand) -> ElementSize { @@ -183,7 +181,7 @@ fn supported(operand: Operand) -> bool { } } -fn immediate(code: &mut Vec, value: i8, element: ElementSize) { +fn immediate(code: &mut Code, value: i8, element: ElementSize) { let bits = element.bits(); let value = value as i64 as u64; let repeated = if element == ElementSize::Doubleword { @@ -193,10 +191,14 @@ fn immediate(code: &mut Vec, value: i8, element: ElementSize) { (0..QWORD_BYTES / element.bytes()) .fold(0, |result, index| result | (lane << (index * bits))) }; - code.extend(MOVABS_RAX); - code.extend(repeated.to_le_bytes()); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MODRM_REGISTER | (ACCUMULATOR_OR_CONSTANT << MODRM_REGISTER_SHIFT)); + let mut asm = code.asm(); + asm.mov_imm64(Rax, repeated); + asm.simd( + Host::MoveGprQword, + ACCUMULATOR_OR_CONSTANT, + Rax, + TargetCpu::Baseline, + ); packed( code, Host::UnpackLowQword, @@ -205,7 +207,7 @@ fn immediate(code: &mut Vec, value: i8, element: ElementSize) { ); } -fn broadcast_lane(code: &mut Vec, element: ElementSize, lane: u8) { +fn broadcast_lane(code: &mut Code, element: ElementSize, lane: u8) { match element { ElementSize::Byte => { // Move the containing word to every word, then select its byte. @@ -270,7 +272,7 @@ fn broadcast_lane(code: &mut Vec, element: ElementSize, lane: u8) { /// Low products are identical for signed and unsigned interpretations. SSE2 /// PMULUDQ multiplies even dwords; shifted odd lanes or cross terms supply the /// remaining low bits without widening guest results or touching host MXCSR. -fn multiply_low(code: &mut Vec, element: ElementSize) { +fn multiply_low(code: &mut Code, element: ElementSize) { match element { ElementSize::Byte => multiply_low_bytes(code), ElementSize::Halfword => packed(code, Host::MultiplyLowWord, RESULT, RIGHT), @@ -313,7 +315,7 @@ fn multiply_low(code: &mut Vec, element: ElementSize) { /// The checked dword multiply replaces the complete two-part SSE2 low-product /// recipe. Keep the baseline kernel shared with callers lacking SSE4.1. -fn multiply_low_for_target(code: &mut Vec, element: ElementSize, target: TargetCpu) { +fn multiply_low_for_target(code: &mut Code, element: ElementSize, target: TargetCpu) { if element == ElementSize::Word && target.supports(TargetCpu::Sse41) { Host::MultiplyLowDword.register(code, RESULT, RIGHT, target); } else { @@ -321,7 +323,7 @@ fn multiply_low_for_target(code: &mut Vec, element: ElementSize, target: Tar } } -fn multiply_low_bytes(code: &mut Vec) { +fn multiply_low_bytes(code: &mut Code) { // Whole-word multiplication already has the correct low byte. Compute the // product of the two high bytes separately and replace the contaminated // high byte of each whole-word result. @@ -338,7 +340,7 @@ fn multiply_low_bytes(code: &mut Vec) { packed(code, Host::Or, RESULT, FIRST_PARTIAL); } -fn multiply_high_bytes(code: &mut Vec, signed: bool) { +fn multiply_high_bytes(code: &mut Code, signed: bool) { packed(code, Host::MoveAligned, FIRST_PARTIAL, RESULT); packed(code, Host::MoveAligned, SECOND_PARTIAL, RIGHT); packed(code, Host::Xor, PREDICATE, PREDICATE); @@ -371,7 +373,7 @@ fn multiply_high_bytes(code: &mut Vec, signed: bool) { packed(code, Host::PackUnsignedWordToByte, RESULT, FIRST_PARTIAL); } -fn multiply_high_words(code: &mut Vec, signed: bool) { +fn multiply_high_words(code: &mut Code, signed: bool) { if signed { packed(code, Host::MoveAligned, FIRST_PARTIAL, RESULT); packed(code, Host::MoveAligned, SECOND_PARTIAL, RIGHT); @@ -410,34 +412,27 @@ fn multiply_high_words(code: &mut Vec, signed: bool) { } } -fn extract_low_qword(code: &mut Vec, xmm: u8, gpr: u8) { - code.extend(MOVQ_XMM_TO_GPR); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) | gpr); -} - -fn insert_low_qword(code: &mut Vec, xmm: u8, gpr: u8) { - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) | gpr); -} - -fn multiply_high_doublewords(code: &mut Vec, signed: bool) { +fn multiply_high_doublewords(code: &mut Code, signed: bool) { packed(code, Host::MoveAligned, SECOND_PARTIAL, RESULT); packed(code, Host::MoveAligned, PREDICATE, RIGHT); ShiftOpcode::RightBytes.emit(code, SECOND_PARTIAL, QWORD_BYTES as u8); ShiftOpcode::RightBytes.emit(code, PREDICATE, QWORD_BYTES as u8); - extract_low_qword(code, RESULT, RAX); - extract_low_qword(code, RIGHT, RCX); - code.extend(if signed { IMUL_RCX } else { MUL_RCX }); - insert_low_qword(code, FIRST_PARTIAL, RDX); - extract_low_qword(code, SECOND_PARTIAL, RAX); - extract_low_qword(code, PREDICATE, RCX); - code.extend(if signed { IMUL_RCX } else { MUL_RCX }); - insert_low_qword(code, RESULT, RDX); + let multiply = if signed { Unary::Imul } else { Unary::Mul }; + let mut asm = code.asm(); + for (left, right, high) in [ + (RESULT, RIGHT, FIRST_PARTIAL), + (SECOND_PARTIAL, PREDICATE, RESULT), + ] { + asm.movq_from_xmm(Rax, left); + asm.movq_from_xmm(Rcx, right); + asm.unary(multiply, Size::Qword, Rcx); + asm.simd(Host::MoveGprQword, high, Rdx, TargetCpu::Baseline); + } packed(code, Host::UnpackLowQword, FIRST_PARTIAL, RESULT); packed(code, Host::MoveAligned, RESULT, FIRST_PARTIAL); } -fn multiply_high(code: &mut Vec, element: ElementSize, signed: bool) { +fn multiply_high(code: &mut Code, element: ElementSize, signed: bool) { match element { ElementSize::Byte => multiply_high_bytes(code, signed), ElementSize::Halfword => { @@ -454,7 +449,7 @@ fn multiply_high(code: &mut Vec, element: ElementSize, signed: bool) { } } -fn accumulate(code: &mut Vec, element: ElementSize, subtract: bool) { +fn accumulate(code: &mut Code, element: ElementSize, subtract: bool) { let opcode = match (element, subtract) { (ElementSize::Byte, false) => Host::AddByte, (ElementSize::Halfword, false) => Host::AddWord, @@ -475,8 +470,12 @@ fn accumulate(code: &mut Vec, element: ElementSize, subtract: bool) { } /// Validate emitter operand shape before the caller appends instruction bytes. -pub fn validate(operand: Operand) -> Result<(), ()> { - if supported(operand) { Ok(()) } else { Err(()) } +pub fn validate(operand: Operand) -> Result<(), Unsupported> { + if supported(operand) { + Ok(()) + } else { + Err(Unsupported) + } } /// Emit ordinary vector effects for an operand accepted by `validate`. @@ -484,7 +483,7 @@ pub fn validate(operand: Operand) -> Result<(), ()> { /// This mapping preserves guest NZCV, FPSR.QC, FPCR and RAM; all arithmetic is /// integer host instructions and leaves host MXCSR untouched. Optional faster /// kernels are gated by their exact host capabilities. -pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { assert!(supported(operand), "validated integer product operand"); if let Multiplier::Immediate(value) = operand.multiplier { immediate(code, value, operand.element_size); diff --git a/crates/stela-compiler/src/x86_64/sve/integer_products/complex.rs b/crates/stela-compiler/src/x86_64/sve/integer_products/complex.rs index 2a15e944d4..ebcdaf8800 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_products/complex.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_products/complex.rs @@ -1,8 +1,10 @@ //! SVE integer complex multiplies with rounding (SQRDCMLAH, ...). use crate::TargetCpu; +use crate::aarch64::Unsupported; use crate::aarch64::scalable::{ElementSize, VECTOR_CHUNK_BYTES}; use crate::aarch64::sve::integer_products::Kind; -use alloc::vec::Vec; +use crate::x86_64::asm::Gpr::{Rax, Rsp}; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, Size}; use super::complex_wrapping::{blend_directions, prepare_products}; use super::emit_saturating_chunk; @@ -15,47 +17,20 @@ const SNAPSHOT_BYTES: u8 = (3 * VECTOR_CHUNK_BYTES) as u8; const PLUS_RESULT_OFFSET: u8 = SNAPSHOT_BYTES; const DUAL_RESULT_SNAPSHOT_BYTES: u8 = (4 * VECTOR_CHUNK_BYTES) as u8; const HALF_TURN_DEGREES: u16 = 180; -const SUB_RSP_IMM8: [u8; 3] = [0x48, 0x83, 0xec]; -const ADD_RSP_IMM8: [u8; 3] = [0x48, 0x83, 0xc4]; -const MOVDQU_RSP_DISP8_XMM0: [u8; 5] = [0xf3, 0x0f, 0x7f, 0x44, 0x24]; -const MOVDQU_XMM0_RSP: [u8; 5] = [0xf3, 0x0f, 0x6f, 0x04, 0x24]; -const MOVDQU_XMM1_RSP_DISP8: [u8; 5] = [0xf3, 0x0f, 0x6f, 0x4c, 0x24]; -const MOVDQU_XMM4_RSP_DISP8: [u8; 5] = [0xf3, 0x0f, 0x6f, 0x64, 0x24]; -const MOVDQU_XMM2_RSP_DISP8: [u8; 5] = [0xf3, 0x0f, 0x6f, 0x54, 0x24]; -const MOVDQU_RSP_XMM0: [u8; 5] = [0xf3, 0x0f, 0x7f, 0x04, 0x24]; -const MOVDQU_RSP_DISP8_XMM1: [u8; 5] = [0xf3, 0x0f, 0x7f, 0x4c, 0x24]; -const MOVDQU_RSP_DISP8_XMM4: [u8; 5] = [0xf3, 0x0f, 0x7f, 0x64, 0x24]; -const MOVDQU_XMM0_RSP_DISP8: [u8; 5] = [0xf3, 0x0f, 0x6f, 0x44, 0x24]; -const REX_W: u8 = 0x48; -const REX_REGISTER_HIGH: u8 = 0x04; -const MODRM_DISP8_RSP: u8 = 0x44; -const SIB_RSP: u8 = 0x24; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MODRM_REGISTER_MASK: u8 = 7; -const MOVSXD: u8 = 0x63; -const MOV_QWORD: u8 = 0x8b; -const MOV_STORE: u8 = 0x89; const COMPLEX_COMPONENTS: usize = 2; const QUARTER_TURN_DEGREES: u16 = 90; -#[derive(Clone, Copy)] -enum Gpr { - Rax = 0, - Rcx = 1, - R9 = 9, -} - /// Inputs: XMM0=Zn, XMM1=Zm, XMM4=accumulator. Output XMM0; preserve XMM7. /// Clobbers caller-saved RAX/RCX/RDX/R8/R9/R10/R11 and restores RSP exactly. pub(super) fn emit_chunk( - code: &mut Vec, + code: &mut Code, element: ElementSize, rounded: bool, rotation_degrees: u16, target: TargetCpu, -) -> Result<(), ()> { +) -> Result<(), Unsupported> { if element == ElementSize::Quadword || ![0, 90, 180, 270].contains(&rotation_degrees) { - return Err(()); + return Err(Unsupported); } if !rounded { return super::complex_wrapping::emit_chunk(code, element, rotation_degrees, target); @@ -64,13 +39,11 @@ pub(super) fn emit_chunk( emit_rounded_packed(code, element, rotation_degrees); return Ok(()); } - code.extend_from_slice(&SUB_RSP_IMM8); - code.push(SNAPSHOT_BYTES); - code.extend_from_slice(&MOVDQU_RSP_XMM0); - code.extend_from_slice(&MOVDQU_RSP_DISP8_XMM1); - code.push(SOURCE_M_OFFSET); - code.extend_from_slice(&MOVDQU_RSP_DISP8_XMM4); - code.push(ACCUMULATOR_OFFSET); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Sub, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); + asm.movdqu_store(Mem::base(Rsp, 0), 0); + asm.movdqu_store(Mem::base_disp8(Rsp, SOURCE_M_OFFSET as i8), 1); + asm.movdqu_store(Mem::base_disp8(Rsp, ACCUMULATOR_OFFSET as i8), 4); let rotation = usize::from(rotation_degrees / QUARTER_TURN_DEGREES); let select_a = rotation & 1; let select_b = select_a ^ 1; @@ -100,47 +73,34 @@ pub(super) fn emit_chunk( store_result(code, element, accumulator_offset); } } - code.extend_from_slice(&MOVDQU_XMM0_RSP_DISP8); - code.push(ACCUMULATOR_OFFSET); - code.extend_from_slice(&ADD_RSP_IMM8); - code.push(SNAPSHOT_BYTES); + let mut asm = code.asm(); + asm.movdqu_load(0, Mem::base_disp8(Rsp, ACCUMULATOR_OFFSET as i8)); + asm.alu_imm8(Alu::Add, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); Ok(()) } -fn load_signed(code: &mut Vec, register: Gpr, element: ElementSize, offset: u8) { - let register = register as u8; - code.push( - REX_W - | if register > MODRM_REGISTER_MASK { - REX_REGISTER_HIGH - } else { - 0 - }, - ); +fn load_signed(code: &mut Code, register: Gpr, element: ElementSize, offset: u8) { + let slot = Mem::base_disp8(Rsp, offset as i8); match element { - ElementSize::Word => code.push(MOVSXD), - ElementSize::Doubleword => code.push(MOV_QWORD), + ElementSize::Word => code.asm().movsxd(register, slot), + ElementSize::Doubleword => code.asm().mov_load(Size::Qword, register, slot), _ => unreachable!("scalar complex components are word or doubleword"), } - code.extend_from_slice(&[ - MODRM_DISP8_RSP | ((register & MODRM_REGISTER_MASK) << MODRM_REGISTER_SHIFT), - SIB_RSP, - offset, - ]); } -fn store_result(code: &mut Vec, element: ElementSize, offset: u8) { - match element { - ElementSize::Word => {} - ElementSize::Doubleword => code.push(REX_W), +fn store_result(code: &mut Code, element: ElementSize, offset: u8) { + let size = match element { + ElementSize::Word => Size::Dword, + ElementSize::Doubleword => Size::Qword, _ => unreachable!("scalar complex components are word or doubleword"), - } - code.extend_from_slice(&[MOV_STORE, MODRM_DISP8_RSP, SIB_RSP, offset]); + }; + code.asm() + .mov_store(size, Mem::base_disp8(Rsp, offset as i8), Rax); } /// Mixed component signs operate on wide products, preserving min*min. Running /// both exact packed directions and blending avoids negating a narrow operand. -fn emit_rounded_packed(code: &mut Vec, element: ElementSize, rotation: u16) { +fn emit_rounded_packed(code: &mut Code, element: ElementSize, rotation: u16) { prepare_products(code, element, rotation); if rotation == 0 || rotation == HALF_TURN_DEGREES { emit_saturating_chunk( @@ -152,33 +112,28 @@ fn emit_rounded_packed(code: &mut Vec, element: ElementSize, rotation: u16) ); return; } - code.extend_from_slice(&SUB_RSP_IMM8); - code.push(DUAL_RESULT_SNAPSHOT_BYTES); - code.extend_from_slice(&MOVDQU_RSP_XMM0); - code.extend_from_slice(&MOVDQU_RSP_DISP8_XMM1); - code.push(SOURCE_M_OFFSET); - code.extend_from_slice(&MOVDQU_RSP_DISP8_XMM4); - code.push(ACCUMULATOR_OFFSET); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Sub, Size::Qword, Rsp, DUAL_RESULT_SNAPSHOT_BYTES as i8); + asm.movdqu_store(Mem::base(Rsp, 0), 0); + asm.movdqu_store(Mem::base_disp8(Rsp, SOURCE_M_OFFSET as i8), 1); + asm.movdqu_store(Mem::base_disp8(Rsp, ACCUMULATOR_OFFSET as i8), 4); emit_saturating_chunk( code, Kind::RoundedHighAccumulate { subtract: false }, element, ); - code.extend_from_slice(&MOVDQU_RSP_DISP8_XMM0); - code.push(PLUS_RESULT_OFFSET); - code.extend_from_slice(&MOVDQU_XMM0_RSP); - code.extend_from_slice(&MOVDQU_XMM1_RSP_DISP8); - code.push(SOURCE_M_OFFSET); - code.extend_from_slice(&MOVDQU_XMM4_RSP_DISP8); - code.push(ACCUMULATOR_OFFSET); + let mut asm = code.asm(); + asm.movdqu_store(Mem::base_disp8(Rsp, PLUS_RESULT_OFFSET as i8), 0); + asm.movdqu_load(0, Mem::base(Rsp, 0)); + asm.movdqu_load(1, Mem::base_disp8(Rsp, SOURCE_M_OFFSET as i8)); + asm.movdqu_load(4, Mem::base_disp8(Rsp, ACCUMULATOR_OFFSET as i8)); emit_saturating_chunk( code, Kind::RoundedHighAccumulate { subtract: true }, element, ); - code.extend_from_slice(&MOVDQU_XMM2_RSP_DISP8); - code.push(PLUS_RESULT_OFFSET); - code.extend_from_slice(&ADD_RSP_IMM8); - code.push(DUAL_RESULT_SNAPSHOT_BYTES); + let mut asm = code.asm(); + asm.movdqu_load(2, Mem::base_disp8(Rsp, PLUS_RESULT_OFFSET as i8)); + asm.alu_imm8(Alu::Add, Size::Qword, Rsp, DUAL_RESULT_SNAPSHOT_BYTES as i8); blend_directions(code, element, rotation); } diff --git a/crates/stela-compiler/src/x86_64/sve/integer_products/complex_wrapping.rs b/crates/stela-compiler/src/x86_64/sve/integer_products/complex_wrapping.rs index 50b5e48c29..48c4feab49 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_products/complex_wrapping.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_products/complex_wrapping.rs @@ -1,9 +1,11 @@ //! SVE CMLA (integer, wrapping). use super::{multiply_low_for_target, packed}; use crate::TargetCpu; +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Code, Gpr, Rm, Size}; use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; -use alloc::vec::Vec; const RESULT: u8 = 0; const RIGHT: u8 = 1; @@ -23,31 +25,27 @@ const SWAP_QWORDS: u8 = 0x4e; const QUARTER_TURN_DEGREES: u16 = 90; const HALF_TURN_DEGREES: u16 = 180; const THREE_QUARTER_TURN_DEGREES: u16 = 270; -const RAX: u8 = 0; -const RCX: u8 = 1; -const RDX: u8 = 2; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MOVQ_TO_GPR: [u8; 4] = [0x66, 0x48, 0x0f, 0x7e]; -const IMUL_RCX_RAX: [u8; 4] = [0x48, 0x0f, 0xaf, 0xc8]; -const IMUL_RDX_RAX: [u8; 4] = [0x48, 0x0f, 0xaf, 0xd0]; -fn shuffle(code: &mut Vec, opcode: Host, register: u8, control: u8) { - packed(code, opcode, register, register); - code.push(control); +fn shuffle(code: &mut Code, opcode: Host, register: u8, control: u8) { + code.asm().simd_imm( + opcode, + register, + Rm::Xmm(register), + control, + TargetCpu::Baseline, + ); } -fn extract_qword(code: &mut Vec, xmm: u8, gpr: u8) { - code.extend(MOVQ_TO_GPR); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) | gpr); +fn extract_qword(code: &mut Code, xmm: u8, gpr: Gpr) { + code.asm().movq_from_xmm(gpr, xmm); } -fn insert_qword(code: &mut Vec, xmm: u8, gpr: u8) { - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) | gpr); +fn insert_qword(code: &mut Code, xmm: u8, gpr: Gpr) { + code.asm() + .simd(Host::MoveGprQword, xmm, gpr, TargetCpu::Baseline); } -fn doubleword_products(code: &mut Vec, rotation_degrees: u16) { +fn doubleword_products(code: &mut Code, rotation_degrees: u16) { // A doubleword chunk contains one complex pair. Extract its selected Zn // component once, then form both low products without stack snapshots. let imaginary = matches!( @@ -57,21 +55,22 @@ fn doubleword_products(code: &mut Vec, rotation_degrees: u16) { if imaginary { Shift::RightBytes.emit(code, RESULT, QWORD_BYTES); } - extract_qword(code, RESULT, RAX); - extract_qword(code, RIGHT, RCX); + extract_qword(code, RESULT, Rax); + extract_qword(code, RIGHT, Rcx); Shift::RightBytes.emit(code, RIGHT, QWORD_BYTES); - extract_qword(code, RIGHT, RDX); - code.extend(IMUL_RCX_RAX); - code.extend(IMUL_RDX_RAX); - insert_qword(code, RESULT, if imaginary { RDX } else { RCX }); - insert_qword(code, RIGHT, if imaginary { RCX } else { RDX }); + extract_qword(code, RIGHT, Rdx); + let mut asm = code.asm(); + asm.imul(Size::Qword, Rcx, Rax); + asm.imul(Size::Qword, Rdx, Rax); + insert_qword(code, RESULT, if imaginary { Rdx } else { Rcx }); + insert_qword(code, RIGHT, if imaginary { Rcx } else { Rdx }); packed(code, Host::UnpackLowQword, RESULT, RIGHT); } /// Replicate the selected Zn component into each complex pair and rotate Zm's /// component order when selecting imaginary Zn. Preserves XMM4 and XMM7; /// consumes XMM0..2. The caller validates component width and rotation. -pub(super) fn prepare_products(code: &mut Vec, element: ElementSize, rotation_degrees: u16) { +pub(super) fn prepare_products(code: &mut Code, element: ElementSize, rotation_degrees: u16) { let imaginary = matches!( rotation_degrees, QUARTER_TURN_DEGREES | THREE_QUARTER_TURN_DEGREES @@ -133,7 +132,7 @@ pub(super) fn prepare_products(code: &mut Vec, element: ElementSize, rotatio } } -fn negative_component_mask(code: &mut Vec, element: ElementSize, rotation_degrees: u16) { +fn negative_component_mask(code: &mut Code, element: ElementSize, rotation_degrees: u16) { let odd = rotation_degrees == THREE_QUARTER_TURN_DEGREES; let (shift, amount) = match (element, odd) { (ElementSize::Byte, false) => (Shift::RightWord, BYTE_BITS), @@ -158,7 +157,7 @@ fn negative_component_mask(code: &mut Vec, element: ElementSize, rotation_de /// Select between XMM0=minus result and XMM2=plus result for a quarter-turn /// rotation. Returns XMM0, consumes XMM5 and preserves XMM2/4/7. This also /// serves rounded complex arithmetic, whose directions must saturate separately. -pub(super) fn blend_directions(code: &mut Vec, element: ElementSize, rotation_degrees: u16) { +pub(super) fn blend_directions(code: &mut Code, element: ElementSize, rotation_degrees: u16) { negative_component_mask(code, element, rotation_degrees); packed(code, Host::And, RESULT, NEGATIVE_COMPONENTS); packed(code, Host::AndNot, NEGATIVE_COMPONENTS, TEMPORARY); @@ -170,11 +169,11 @@ pub(super) fn blend_directions(code: &mut Vec, element: ElementSize, rotatio /// guest architectural status, host MXCSR, RAM and the stack pointer. Doubleword /// products additionally consume caller-saved RAX/RCX/RDX. pub(super) fn emit_chunk( - code: &mut Vec, + code: &mut Code, element: ElementSize, rotation_degrees: u16, target: TargetCpu, -) -> Result<(), ()> { +) -> Result<(), Unsupported> { if element == ElementSize::Quadword || ![ 0, @@ -184,7 +183,7 @@ pub(super) fn emit_chunk( ] .contains(&rotation_degrees) { - return Err(()); + return Err(Unsupported); } if element == ElementSize::Doubleword { doubleword_products(code, rotation_degrees); diff --git a/crates/stela-compiler/src/x86_64/sve/integer_products/polynomial.rs b/crates/stela-compiler/src/x86_64/sve/integer_products/polynomial.rs index a56ed1c172..2e9a470253 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_products/polynomial.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_products/polynomial.rs @@ -1,9 +1,11 @@ //! SVE PMULLB/PMULLT carryless multiplies. use crate::TargetCpu; +use crate::aarch64::Unsupported; use crate::aarch64::scalable::ElementSize; use crate::aarch64::sve::integer_products::Selection; +use crate::x86_64::asm::Gpr::R10; +use crate::x86_64::asm::{Code, Cond, Rm, Size, resolve}; use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; -use alloc::vec::Vec; const LEFT: u8 = 0; const RIGHT: u8 = 1; @@ -16,23 +18,19 @@ const DWORD_SIGN_SHIFT: u8 = DWORD_BITS - 1; const LOW_DWORD_MASK_DUPLICATE: u8 = 0xa0; const PCLMUL_LOW_QWORDS: u8 = 0x00; const PCLMUL_HIGH_QWORDS: u8 = 0x11; -const MOV_R10D_IMMEDIATE: [u8; 2] = [0x41, 0xba]; -const DEC_R10D: [u8; 3] = [0x41, 0xff, 0xca]; -const JNZ_REL32: [u8; 2] = [0x0f, 0x85]; -const REL32_BYTES: usize = 4; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn low_lane_mask(code: &mut Vec, shift: Shift, bits: u8) { +fn low_lane_mask(code: &mut Code, shift: Shift, bits: u8) { packed(code, Host::EqualDword, CONSTANT, CONSTANT); shift.emit(code, CONSTANT, bits); } /// Eight Horner steps per byte. PADDB doubles modulo x^8 without permitting /// carries between lanes, and signed-byte comparison extracts each top bit. -fn low_bytes(code: &mut Vec) { +fn low_bytes(code: &mut Code) { packed(code, Host::Xor, RESULT, RESULT); for bit in 0..BYTE_BITS { if bit != 0 { @@ -48,7 +46,7 @@ fn low_bytes(code: &mut Vec) { } } -fn widen_bytes(code: &mut Vec, top: bool) { +fn widen_bytes(code: &mut Code, top: bool) { if top { Shift::RightWord.emit(code, LEFT, BYTE_BITS); Shift::RightWord.emit(code, RIGHT, BYTE_BITS); @@ -74,7 +72,7 @@ fn widen_bytes(code: &mut Vec, top: bool) { } } -fn widen_dwords(code: &mut Vec, top: bool) { +fn widen_dwords(code: &mut Code, top: bool) { if top { Shift::RightQword.emit(code, LEFT, DWORD_BITS); Shift::RightQword.emit(code, RIGHT, DWORD_BITS); @@ -82,25 +80,28 @@ fn widen_dwords(code: &mut Vec, top: bool) { low_lane_mask(code, Shift::RightQword, DWORD_BITS); packed(code, Host::And, LEFT, CONSTANT); packed(code, Host::Xor, RESULT, RESULT); - code.extend(MOV_R10D_IMMEDIATE); - code.extend(u32::from(DWORD_BITS).to_le_bytes()); + code.asm().mov_imm32(R10, u32::from(DWORD_BITS)); let loop_start = code.len(); Shift::LeftQword.emit(code, RESULT, 1); packed(code, Host::MoveAligned, MASK, RIGHT); Shift::ArithmeticDword.emit(code, MASK, DWORD_SIGN_SHIFT); - packed(code, Host::ShuffleDword, MASK, MASK); - code.push(LOW_DWORD_MASK_DUPLICATE); + code.asm().simd_imm( + Host::ShuffleDword, + MASK, + Rm::Xmm(MASK), + LOW_DWORD_MASK_DUPLICATE, + TargetCpu::Baseline, + ); packed(code, Host::And, MASK, LEFT); packed(code, Host::Xor, RESULT, MASK); Shift::LeftDword.emit(code, RIGHT, 1); - code.extend(DEC_R10D); - code.extend(JNZ_REL32); - let displacement = i32::try_from(loop_start as isize - (code.len() + REL32_BYTES) as isize) - .expect("bounded polynomial loop"); - code.extend(displacement.to_le_bytes()); + let mut asm = code.asm(); + asm.dec(Size::Dword, R10); + let repeat = asm.jcc(Cond::Ne); + resolve(code, repeat, loop_start); } -fn widen_dwords_pclmul(code: &mut Vec, top: bool, target: TargetCpu) { +fn widen_dwords_pclmul(code: &mut Code, top: bool, target: TargetCpu) { if top { Shift::RightQword.emit(code, LEFT, DWORD_BITS); Shift::RightQword.emit(code, RIGHT, DWORD_BITS); @@ -110,10 +111,20 @@ fn widen_dwords_pclmul(code: &mut Vec, top: bool, target: TargetCpu) { packed(code, Host::And, RIGHT, CONSTANT); } packed(code, Host::MoveAligned, RESULT, LEFT); - Host::CarrylessMultiplyQword.register(code, LEFT, RIGHT, target); - code.push(PCLMUL_LOW_QWORDS); - Host::CarrylessMultiplyQword.register(code, RESULT, RIGHT, target); - code.push(PCLMUL_HIGH_QWORDS); + code.asm().simd_imm( + Host::CarrylessMultiplyQword, + LEFT, + Rm::Xmm(RIGHT), + PCLMUL_LOW_QWORDS, + target, + ); + code.asm().simd_imm( + Host::CarrylessMultiplyQword, + RESULT, + Rm::Xmm(RIGHT), + PCLMUL_HIGH_QWORDS, + target, + ); packed(code, Host::UnpackLowQword, LEFT, RESULT); } @@ -121,14 +132,14 @@ fn widen_dwords_pclmul(code: &mut Vec, top: bool, target: TargetCpu) { /// R15. Each widening result selects even (bottom) or odd (top) narrow lanes. /// Reject unallocated widths before emitting any bytes. No RAM or FP effects. pub(super) fn emit_chunk( - code: &mut Vec, + code: &mut Code, element: ElementSize, widening: bool, selection: Selection, target: TargetCpu, -) -> Result<(), ()> { +) -> Result<(), Unsupported> { if selection == Selection::Cross { - return Err(()); + return Err(Unsupported); } let top = selection == Selection::Top; if widening && element == ElementSize::Doubleword && target.supports(TargetCpu::Pclmulqdq) { @@ -139,7 +150,7 @@ pub(super) fn emit_chunk( (false, ElementSize::Byte) => low_bytes(code), (true, ElementSize::Halfword) => widen_bytes(code, top), (true, ElementSize::Doubleword) => widen_dwords(code, top), - _ => return Err(()), + _ => return Err(Unsupported), } packed(code, Host::MoveAligned, LEFT, RESULT); Ok(()) diff --git a/crates/stela-compiler/src/x86_64/sve/integer_products/saturating.rs b/crates/stela-compiler/src/x86_64/sve/integer_products/saturating.rs index e6f2401611..e1a35cd591 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_products/saturating.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_products/saturating.rs @@ -4,8 +4,9 @@ use super::packed; use crate::TargetCpu; use crate::aarch64::scalable::ElementSize; use crate::aarch64::sve::integer_products::{Accumulate, Kind, Selection}; +use crate::x86_64::asm::Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdx, Rsp}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, ShiftOp, Size, Unary}; use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; -use alloc::vec::Vec; const RESULT: u8 = 0; const RIGHT: u8 = 1; @@ -25,64 +26,15 @@ const STACK_LEFT: usize = 0; const STACK_RIGHT: usize = CHUNK_BYTES; const STACK_ACCUMULATOR: usize = CHUNK_BYTES * 2; const STACK_BYTES: u8 = (CHUNK_BYTES * 3) as u8; -const MODRM_STACK_DISP8: u8 = 0x44; -const MODRM_DIRECT: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const SIB_STACK: u8 = 0x24; -const REX_W: u8 = 0x48; -const REX_WR: u8 = 0x4c; -const WORD_PREFIX: u8 = 0x66; -const MOVSX_BYTE: [u8; 2] = [0x0f, 0xbe]; -const MOVSX_WORD: [u8; 2] = [0x0f, 0xbf]; -const MOVSXD: u8 = 0x63; -const MOV_LOAD: u8 = 0x8b; -const MOV_STORE: u8 = 0x89; -const MOV_STORE_BYTE: u8 = 0x88; -const MOVABS_RAX: [u8; 2] = [0x48, 0xb8]; -const MOVABS_R10: [u8; 2] = [0x49, 0xba]; -const MOVABS_R11: [u8; 2] = [0x49, 0xbb]; -const SUB_RSP_IMM8: [u8; 3] = [0x48, 0x83, 0xec]; -const ADD_RSP_IMM8: [u8; 3] = [0x48, 0x83, 0xc4]; -const MOVDQU_STORE: [u8; 3] = [0xf3, 0x0f, 0x7f]; -const MOVDQU_LOAD: [u8; 3] = [0xf3, 0x0f, 0x6f]; -const IMUL_RCX: [u8; 3] = [0x48, 0xf7, 0xe9]; -const NEG_RAX: [u8; 3] = [0x48, 0xf7, 0xd8]; -const ADC_RDX_ZERO: [u8; 4] = [0x48, 0x83, 0xd2, 0x00]; -const NEG_RDX: [u8; 3] = [0x48, 0xf7, 0xda]; -const ADD_RAX_R10: [u8; 3] = [0x4c, 0x01, 0xd0]; -const SHRD_RAX_RDX: [u8; 4] = [0x48, 0x0f, 0xac, 0xd0]; -const SAR_RDX: [u8; 3] = [0x48, 0xc1, 0xfa]; -const MOV_R8_R9: [u8; 3] = [0x4d, 0x89, 0xc8]; -const SAR_R8: [u8; 3] = [0x49, 0xc1, 0xf8]; -const ADD_RAX_R9: [u8; 3] = [0x4c, 0x01, 0xc8]; -const ADC_RDX_R8: [u8; 3] = [0x4c, 0x11, 0xc2]; -const MOV_R8_RAX: [u8; 3] = [0x49, 0x89, 0xc0]; -const MOV_R10_RDX: [u8; 3] = [0x49, 0x89, 0xd2]; -const SAR_R10: [u8; 3] = [0x49, 0xc1, 0xfa]; -const XOR_R10_R11: [u8; 3] = [0x4d, 0x31, 0xda]; -const CMP_RDX_R8: [u8; 3] = [0x4c, 0x39, 0xc2]; -const CMOVNE_RAX_R10: [u8; 4] = [0x49, 0x0f, 0x45, 0xc2]; -const CMP_RAX_R10: [u8; 3] = [0x4c, 0x39, 0xd0]; -const CMOVG_RAX_R10: [u8; 4] = [0x49, 0x0f, 0x4f, 0xc2]; -const CMP_RAX_R11: [u8; 3] = [0x4c, 0x39, 0xd8]; -const CMOVL_RAX_R11: [u8; 4] = [0x49, 0x0f, 0x4c, 0xc3]; -const SHLD_RDX_RAX_ONE: [u8; 5] = [0x48, 0x0f, 0xa4, 0xc2, 0x01]; -const SHL_RAX_ONE: [u8; 3] = [0x48, 0xd1, 0xe0]; -const CQO: [u8; 2] = [0x48, 0x99]; -const MOV_R10_RAX: [u8; 3] = [0x49, 0x89, 0xc2]; -const MOV_RAX_R9: [u8; 3] = [0x4c, 0x89, 0xc8]; -const SUB_RAX_R10: [u8; 3] = [0x4c, 0x29, 0xd0]; -const SBB_RDX_R8: [u8; 3] = [0x4c, 0x19, 0xc2]; -fn constant(code: &mut Vec, register: u8, value: u64) { - code.extend(MOVABS_RAX); - code.extend(value.to_le_bytes()); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MODRM_DIRECT | (register << MODRM_REGISTER_SHIFT)); +fn constant(code: &mut Code, register: u8, value: u64) { + let mut asm = code.asm(); + asm.mov_imm64(Rax, value); + asm.simd(Host::MoveGprQword, register, Rax, TargetCpu::Baseline); packed(code, Host::UnpackLowQword, register, register); } -fn sign_extend_bytes(code: &mut Vec, register: u8, upper: u8, sign: u8) { +fn sign_extend_bytes(code: &mut Code, register: u8, upper: u8, sign: u8) { packed(code, Host::MoveAligned, upper, register); packed(code, Host::Xor, sign, sign); packed(code, Host::GreaterByte, sign, register); @@ -90,7 +42,7 @@ fn sign_extend_bytes(code: &mut Vec, register: u8, upper: u8, sign: u8) { packed(code, Host::UnpackHighByte, upper, sign); } -fn negate_products(code: &mut Vec, word: bool) { +fn negate_products(code: &mut Code, word: bool) { let subtract = if word { Host::SubWord } else { Host::SubDword }; packed(code, Host::Xor, RIGHT, RIGHT); packed(code, subtract, RIGHT, RESULT); @@ -102,7 +54,7 @@ fn negate_products(code: &mut Vec, word: bool) { /// Eight byte products fit in each signed-word half. Sixteen-bit inputs use /// PMULLW/PMULHW and interleave to retain every bit of each signed-dword product. -fn narrow_high(code: &mut Vec, element: ElementSize, rounding: bool, subtract: Option) { +fn narrow_high(code: &mut Code, element: ElementSize, rounding: bool, subtract: Option) { let bytes = element == ElementSize::Byte; if bytes { sign_extend_bytes(code, RESULT, UPPER_PRODUCT, LEFT_SIGN); @@ -163,7 +115,7 @@ fn narrow_high(code: &mut Vec, element: ElementSize, rounding: bool, subtrac packed(code, pack, RESULT, UPPER_PRODUCT); } -fn select_narrow(code: &mut Vec, register: u8, top: bool, element: ElementSize) { +fn select_narrow(code: &mut Code, register: u8, top: bool, element: ElementSize) { let (left, right, narrow_bits) = match element { ElementSize::Halfword => (Shift::LeftWord, Shift::ArithmeticWord, BITS_PER_BYTE as u8), ElementSize::Word => (Shift::LeftDword, Shift::RightDword, WORD_BITS), @@ -175,7 +127,7 @@ fn select_narrow(code: &mut Vec, register: u8, top: bool, element: ElementSi right.emit(code, register, narrow_bits); } -fn saturating_dword_accumulate(code: &mut Vec, subtract: bool) { +fn saturating_dword_accumulate(code: &mut Code, subtract: bool) { packed(code, Host::MoveAligned, UPPER_PRODUCT, ACCUMULATOR); packed( code, @@ -215,7 +167,7 @@ fn saturating_dword_accumulate(code: &mut Vec, subtract: bool) { } fn narrow_long( - code: &mut Vec, + code: &mut Code, element: ElementSize, accumulate: Accumulate, selection: Selection, @@ -248,52 +200,49 @@ fn narrow_long( } } -fn saturate_scalar(code: &mut Vec, bits: u32) { +fn saturate_scalar(code: &mut Code, bits: u32) { let maximum = (1u64 << (bits - 1)) - 1; if bits == QWORD_BITS { // A signed result fits iff the high half equals the sign extension of // the low half. The high half's sign chooses the appropriate endpoint. - code.extend(MOV_R8_RAX); - code.extend(SAR_R8); - code.push(SIGN_SHIFT); - code.extend(MOV_R10_RDX); - code.extend(SAR_R10); - code.push(SIGN_SHIFT); - code.extend(MOVABS_R11); - code.extend(maximum.to_le_bytes()); - code.extend(XOR_R10_R11); - code.extend(CMP_RDX_R8); - code.extend(CMOVNE_RAX_R10); + let mut asm = code.asm(); + asm.mov(Size::Qword, R8, Rax); + asm.shift_imm(ShiftOp::Sar, Size::Qword, R8, SIGN_SHIFT); + asm.mov(Size::Qword, R10, Rdx); + asm.shift_imm(ShiftOp::Sar, Size::Qword, R10, SIGN_SHIFT); + asm.mov_imm64(R11, maximum); + asm.alu(Alu::Xor, Size::Qword, R10, R11); + asm.alu(Alu::Cmp, Size::Qword, Rdx, R8); + asm.cmov(Cond::Ne, Size::Qword, Rax, R10); } else { - code.extend(MOVABS_R10); - code.extend(maximum.to_le_bytes()); - code.extend(MOVABS_R11); - code.extend((!maximum).to_le_bytes()); - code.extend(CMP_RAX_R10); - code.extend(CMOVG_RAX_R10); - code.extend(CMP_RAX_R11); - code.extend(CMOVL_RAX_R11); + let mut asm = code.asm(); + asm.mov_imm64(R10, maximum); + asm.mov_imm64(R11, !maximum); + asm.alu(Alu::Cmp, Size::Qword, Rax, R10); + asm.cmov(Cond::G, Size::Qword, Rax, R10); + asm.alu(Alu::Cmp, Size::Qword, Rax, R11); + asm.cmov(Cond::L, Size::Qword, Rax, R11); } } -fn shifted_product(code: &mut Vec, bits: u32, rounding: bool, subtract: bool) { - code.extend(IMUL_RCX); +fn shifted_product(code: &mut Code, bits: u32, rounding: bool, subtract: bool) { + code.asm().unary(Unary::Imul, Size::Qword, Rcx); if subtract { - code.extend(NEG_RAX); - code.extend(ADC_RDX_ZERO); - code.extend(NEG_RDX); + let mut asm = code.asm(); + asm.unary(Unary::Neg, Size::Qword, Rax); + asm.alu_imm8(Alu::Adc, Size::Qword, Rdx, 0); + asm.unary(Unary::Neg, Size::Qword, Rdx); } if rounding { - code.extend(MOVABS_R10); - code.extend((1u64 << (bits - 2)).to_le_bytes()); - code.extend(ADD_RAX_R10); - code.extend(ADC_RDX_ZERO); + let mut asm = code.asm(); + asm.mov_imm64(R10, 1u64 << (bits - 2)); + asm.alu(Alu::Add, Size::Qword, Rax, R10); + asm.alu_imm8(Alu::Adc, Size::Qword, Rdx, 0); } let shift = (bits - 1) as u8; - code.extend(SHRD_RAX_RDX); - code.push(shift); - code.extend(SAR_RDX); - code.push(shift); + let mut asm = code.asm(); + asm.shrd_imm(Size::Qword, Rax, Rdx, shift); + asm.shift_imm(ShiftOp::Sar, Size::Qword, Rdx, shift); } /// Exact rounded doubling-high accumulation for a signed lane. Inputs are lhs @@ -301,40 +250,41 @@ fn shifted_product(code: &mut Vec, bits: u32, rounding: bool, subtract: bool /// the shifted product wide also represents the positive 2^63 min*min quotient. /// Rounding after adding the integral accumulator is exactly equivalent to /// adding it after the wide product's arithmetic shift, including subtraction. -pub(super) fn emit_rounded_scalar(code: &mut Vec, bits: u32, subtract: bool) { +pub(super) fn emit_rounded_scalar(code: &mut Code, bits: u32, subtract: bool) { shifted_product(code, bits, true, subtract); - code.extend(MOV_R8_R9); - code.extend(SAR_R8); - code.push(SIGN_SHIFT); - code.extend(ADD_RAX_R9); - code.extend(ADC_RDX_R8); + let mut asm = code.asm(); + asm.mov(Size::Qword, R8, R9); + asm.shift_imm(ShiftOp::Sar, Size::Qword, R8, SIGN_SHIFT); + asm.alu(Alu::Add, Size::Qword, Rax, R9); + asm.alu(Alu::Adc, Size::Qword, Rdx, R8); saturate_scalar(code, bits); } -fn scalar_long(code: &mut Vec, bits: u32, accumulate: Accumulate) { - code.extend(IMUL_RCX); - code.extend(SHLD_RDX_RAX_ONE); - code.extend(SHL_RAX_ONE); +fn scalar_long(code: &mut Code, bits: u32, accumulate: Accumulate) { + let mut asm = code.asm(); + asm.unary(Unary::Imul, Size::Qword, Rcx); + asm.shld_imm(Size::Qword, Rdx, Rax, 1); + asm.shift_one(ShiftOp::Shl, Size::Qword, Rax); saturate_scalar(code, bits); if accumulate == Accumulate::None { return; } if accumulate == Accumulate::Add { - code.extend(CQO); - code.extend(MOV_R8_R9); - code.extend(SAR_R8); - code.push(SIGN_SHIFT); - code.extend(ADD_RAX_R9); - code.extend(ADC_RDX_R8); + let mut asm = code.asm(); + asm.sign_extend_accumulator(Size::Qword); + asm.mov(Size::Qword, R8, R9); + asm.shift_imm(ShiftOp::Sar, Size::Qword, R8, SIGN_SHIFT); + asm.alu(Alu::Add, Size::Qword, Rax, R9); + asm.alu(Alu::Adc, Size::Qword, Rdx, R8); } else { - code.extend(MOV_R10_RAX); - code.extend(MOV_R8_RAX); - code.extend(SAR_R8); - code.push(SIGN_SHIFT); - code.extend(MOV_RAX_R9); - code.extend(CQO); - code.extend(SUB_RAX_R10); - code.extend(SBB_RDX_R8); + let mut asm = code.asm(); + asm.mov(Size::Qword, R10, Rax); + asm.mov(Size::Qword, R8, Rax); + asm.shift_imm(ShiftOp::Sar, Size::Qword, R8, SIGN_SHIFT); + asm.mov(Size::Qword, Rax, R9); + asm.sign_extend_accumulator(Size::Qword); + asm.alu(Alu::Sub, Size::Qword, Rax, R10); + asm.alu(Alu::Sbb, Size::Qword, Rdx, R8); } saturate_scalar(code, bits); } @@ -346,50 +296,50 @@ enum ScalarInput { Accumulator, } -fn load_scalar(code: &mut Vec, input: ScalarInput, bytes: usize, offset: usize) { - let (rex, register) = match input { - ScalarInput::Left => (REX_W, 0), - ScalarInput::Right => (REX_W, 1), - ScalarInput::Accumulator => (REX_WR, 1), +fn stack(offset: usize) -> Mem { + Mem::base_disp8(Rsp, offset as i8) +} + +fn load_scalar(code: &mut Code, input: ScalarInput, bytes: usize, offset: usize) { + let destination = match input { + ScalarInput::Left => Rax, + ScalarInput::Right => Rcx, + ScalarInput::Accumulator => R9, }; - code.push(rex); + let source = stack(offset); + let mut asm = code.asm(); match bytes { - 1 => code.extend(MOVSX_BYTE), - 2 => code.extend(MOVSX_WORD), - 4 => code.push(MOVSXD), - 8 => code.push(MOV_LOAD), + 1 => asm.movsx(Size::Qword, destination, Size::Byte, source), + 2 => asm.movsx(Size::Qword, destination, Size::Word, source), + 4 => asm.movsxd(destination, source), + 8 => asm.mov_load(Size::Qword, destination, source), _ => unreachable!("allocated signed lane width"), } - code.extend([ - MODRM_STACK_DISP8 | (register << MODRM_REGISTER_SHIFT), - SIB_STACK, - offset as u8, - ]); } -fn store_scalar(code: &mut Vec, bytes: usize, offset: usize) { - match bytes { - 1 => code.push(MOV_STORE_BYTE), - 2 => code.extend([WORD_PREFIX, MOV_STORE]), - 4 => code.push(MOV_STORE), - 8 => code.extend([REX_W, MOV_STORE]), +fn store_scalar(code: &mut Code, bytes: usize, offset: usize) { + let size = match bytes { + 1 => Size::Byte, + 2 => Size::Word, + 4 => Size::Dword, + 8 => Size::Qword, _ => unreachable!("allocated result lane width"), + }; + code.asm().mov_store(size, stack(offset), Rax); +} + +fn stack_chunk(code: &mut Code, register: u8, offset: usize, load: bool) { + let mut asm = code.asm(); + if load { + asm.movdqu_load(register, stack(offset)); + } else { + asm.movdqu_store(stack(offset), register); } - code.extend([MODRM_STACK_DISP8, SIB_STACK, offset as u8]); } -fn stack_chunk(code: &mut Vec, register: u8, offset: usize, load: bool) { - code.extend(if load { MOVDQU_LOAD } else { MOVDQU_STORE }); - code.extend([ - MODRM_STACK_DISP8 | (register << MODRM_REGISTER_SHIFT), - SIB_STACK, - offset as u8, - ]); -} - -fn scalar_chunk(code: &mut Vec, kind: Kind, element: ElementSize) { - code.extend(SUB_RSP_IMM8); - code.push(STACK_BYTES); +fn scalar_chunk(code: &mut Code, kind: Kind, element: ElementSize) { + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Rsp, STACK_BYTES as i8); stack_chunk(code, RESULT, STACK_LEFT, false); stack_chunk(code, RIGHT, STACK_RIGHT, false); stack_chunk(code, ACCUMULATOR, STACK_ACCUMULATOR, false); @@ -449,14 +399,14 @@ fn scalar_chunk(code: &mut Vec, kind: Kind, element: ElementSize) { store_scalar(code, bytes, STACK_LEFT + lane * bytes); } stack_chunk(code, RESULT, STACK_LEFT, true); - code.extend(ADD_RSP_IMM8); - code.push(STACK_BYTES); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Rsp, STACK_BYTES as i8); } /// Chunk ABI: XMM0/1 are staged sources, XMM4 the old accumulator; XMM7 is /// preserved for the caller's merge. Indexed operands are already broadcast at /// source width. Result XMM0; scratch XMM1..6 and caller-saved integer registers. -pub(crate) fn emit_chunk(code: &mut Vec, kind: Kind, element: ElementSize) { +pub(crate) fn emit_chunk(code: &mut Code, kind: Kind, element: ElementSize) { match kind { Kind::DoublingHigh { rounding } if element.bytes() <= 2 => { narrow_high(code, element, rounding, None) @@ -482,7 +432,7 @@ pub(crate) fn emit_chunk(code: &mut Vec, kind: Kind, element: ElementSize) { /// rounded products are within [-32767, 32767], so equality identifies it /// exactly. Flipping that lane's bits produces the required saturated +32767. pub(super) fn emit_chunk_for_target( - code: &mut Vec, + code: &mut Code, kind: Kind, element: ElementSize, target: TargetCpu, diff --git a/crates/stela-compiler/src/x86_64/sve/integer_products/widening.rs b/crates/stela-compiler/src/x86_64/sve/integer_products/widening.rs index 06ccad9f2d..842b17efef 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_products/widening.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_products/widening.rs @@ -3,8 +3,8 @@ use super::packed; use crate::TargetCpu; use crate::aarch64::scalable::ElementSize; use crate::aarch64::sve::integer_products::{Accumulate, Selection}; +use crate::x86_64::asm::{Code, Rm}; use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; -use alloc::vec::Vec; const RESULT: u8 = 0; const RIGHT: u8 = 1; @@ -18,7 +18,7 @@ const WORD_SIGN_SHIFT: u8 = WORD_BITS - 1; const SELECT_EVEN_DWORDS: u8 = 0x88; const SELECT_ODD_DWORDS: u8 = 0xdd; -fn select_bytes(code: &mut Vec, signed: bool, top: bool) { +fn select_bytes(code: &mut Code, signed: bool, top: bool) { let right = if signed { Shift::ArithmeticWord } else { @@ -33,7 +33,7 @@ fn select_bytes(code: &mut Vec, signed: bool, top: bool) { packed(code, Host::MultiplyLowWord, RESULT, RIGHT); } -fn select_halfwords(code: &mut Vec, top: bool) { +fn select_halfwords(code: &mut Code, top: bool) { // Leave the selected halfword in each dword's low half, with zero above // it. Signed PMADDWD adds a zero product; checked PMULLD sees zero extension. for register in [RESULT, RIGHT] { @@ -44,12 +44,12 @@ fn select_halfwords(code: &mut Vec, top: bool) { } } -fn signed_halfwords(code: &mut Vec, top: bool) { +fn signed_halfwords(code: &mut Code, top: bool) { select_halfwords(code, top); packed(code, Host::MultiplyAddWords, RESULT, RIGHT); } -fn unsigned_halfwords(code: &mut Vec, top: bool, target: TargetCpu) { +fn unsigned_halfwords(code: &mut Code, top: bool, target: TargetCpu) { if target.supports(TargetCpu::Sse41) { select_halfwords(code, top); Host::MultiplyLowDword.register(code, RESULT, RIGHT, target); @@ -68,13 +68,18 @@ fn unsigned_halfwords(code: &mut Vec, top: bool, target: TargetCpu) { SELECT_EVEN_DWORDS }; for register in [RESULT, SECOND_PARTIAL] { - packed(code, Host::ShuffleDword, register, register); - code.push(control); + code.asm().simd_imm( + Host::ShuffleDword, + register, + Rm::Xmm(register), + control, + TargetCpu::Baseline, + ); } packed(code, Host::UnpackLowQword, RESULT, SECOND_PARTIAL); } -fn words(code: &mut Vec, signed: bool, top: bool, target: TargetCpu) { +fn words(code: &mut Code, signed: bool, top: bool, target: TargetCpu) { if top { Shift::RightQword.emit(code, RESULT, WORD_BITS); Shift::RightQword.emit(code, RIGHT, WORD_BITS); @@ -106,7 +111,7 @@ fn words(code: &mut Vec, signed: bool, top: bool, target: TargetCpu) { /// narrow source width. XMM4 holds the old wide accumulator. Returns XMM0, /// consumes XMM0..4 and preserves XMM5..7, guest status, RAM and host MXCSR. pub(super) fn emit_chunk( - code: &mut Vec, + code: &mut Code, element: ElementSize, signed: bool, accumulate: Accumulate, diff --git a/crates/stela-compiler/src/x86_64/sve/integer_saturation.rs b/crates/stela-compiler/src/x86_64/sve/integer_saturation.rs index 81300eb3f4..d0e2f905cf 100644 --- a/crates/stela-compiler/src/x86_64/sve/integer_saturation.rs +++ b/crates/stela-compiler/src/x86_64/sve/integer_saturation.rs @@ -5,7 +5,8 @@ use crate::aarch64::{ scalable::{ElementSize, Predication, VectorLength}, sve::integer_saturation::{Arithmetic, Half, Input, Kind, Operand, Signedness}, }; -use alloc::vec::Vec; +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Code, Rm}; use super::super::isa::{ShiftOpcode, SimdOpcode as Host}; @@ -13,7 +14,6 @@ const REPLICATE_HIGH_DWORDS: u8 = 0xf5; const SWAP_DWORD_PAIRS: u8 = 0xb1; const SWAP_QWORDS: u8 = 0x4e; const SWAP_WORD_PAIRS: u8 = 0xb1; -const MOV_RAX_IMM64: &[u8] = &[0x48, 0xb8]; #[derive(Clone, Copy)] enum ShiftKind { @@ -30,17 +30,17 @@ const WORD_LOW_BITS: u64 = 0x0000_0001_0000_0001; const QWORD_LOW_BITS: u64 = 1; const BITS_PER_BYTE: usize = 8; -fn binary(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn binary(code: &mut Code, opcode: Host, destination: u8, source: u8) { // This family's packed recipes deliberately require only the SSE2 baseline. opcode.register(code, destination, source, TargetCpu::Baseline); } -fn copy(code: &mut Vec, destination: u8, source: u8) { +fn copy(code: &mut Code, destination: u8, source: u8) { if destination != source { binary(code, Host::MoveAligned, destination, source); } } fn shift_immediate( - code: &mut Vec, + code: &mut Code, element: ElementSize, operation: ShiftKind, register: u8, @@ -59,17 +59,21 @@ fn shift_immediate( }; opcode.emit(code, register, amount as u8); } -fn shuffle(code: &mut Vec, opcode: Host, register: u8, order: u8) { - opcode.register(code, register, register, TargetCpu::Baseline); - code.push(order); +fn shuffle(code: &mut Code, opcode: Host, register: u8, order: u8) { + code.asm().simd_imm( + opcode, + register, + Rm::Xmm(register), + order, + TargetCpu::Baseline, + ); } -fn splat(code: &mut Vec, register: u8, pattern: u64) { - code.extend(MOV_RAX_IMM64); - code.extend(pattern.to_le_bytes()); +fn splat(code: &mut Code, register: u8, pattern: u64) { + code.asm().mov_imm64(Rax, pattern); Host::MoveGprQword.register(code, register, 0, TargetCpu::Baseline); binary(code, Host::UnpackLowQword, register, register); } -fn all_ones(code: &mut Vec, register: u8) { +fn all_ones(code: &mut Code, register: u8) { binary(code, Host::EqualDword, register, register); } fn arithmetic_opcode(element: ElementSize, subtract: bool) -> Host { @@ -86,7 +90,7 @@ fn arithmetic_opcode(element: ElementSize, subtract: bool) -> Host { } } /// Expand each lane's sign bit to a complete lane mask. XMM7 is byte scratch. -fn sign_mask(code: &mut Vec, destination: u8, source: u8, element: ElementSize) { +fn sign_mask(code: &mut Code, destination: u8, source: u8, element: ElementSize) { if element == ElementSize::Byte { let source = if destination == source { copy(code, 7, source); @@ -116,7 +120,7 @@ fn sign_mask(code: &mut Vec, destination: u8, source: u8, element: ElementSi } } /// Shift a packed lane without leaking neighboring bytes; clobbers XMM6/7. -fn half_shift(code: &mut Vec, register: u8, element: ElementSize, signed: bool, amount: usize) { +fn half_shift(code: &mut Code, register: u8, element: ElementSize, signed: bool, amount: usize) { if element == ElementSize::Byte { debug_assert_eq!(amount, 1); if signed { @@ -150,14 +154,14 @@ fn half_shift(code: &mut Vec, register: u8, element: ElementSize, signed: bo } } /// Select replacement XMM5 where mask XMM4 is set, preserving result XMM0 elsewhere. -fn select_saturated(code: &mut Vec) { +fn select_saturated(code: &mut Code) { binary(code, Host::And, 5, 4); binary(code, Host::AndNot, 4, 0); binary(code, Host::Or, 5, 4); copy(code, 0, 5); } /// XMM0=a, XMM1=b. Leaves a in XMM3 and the unsigned carry mask in XMM5. -fn add_with_carry_mask(code: &mut Vec, element: ElementSize) { +fn add_with_carry_mask(code: &mut Code, element: ElementSize) { copy(code, 3, 0); binary(code, arithmetic_opcode(element, false), 0, 1); copy(code, 4, 3); @@ -169,7 +173,7 @@ fn add_with_carry_mask(code: &mut Vec, element: ElementSize) { binary(code, Host::Or, 5, 6); sign_mask(code, 5, 5, element); } -fn saturating(code: &mut Vec, element: ElementSize, signedness: Signedness, subtract: bool) { +fn saturating(code: &mut Code, element: ElementSize, signedness: Signedness, subtract: bool) { let direct = match (element, signedness, subtract) { (ElementSize::Byte, Signedness::Signed, false) => Some(Host::AddSignedSaturatingByte), (ElementSize::Halfword, Signedness::Signed, false) => Some(Host::AddSignedSaturatingWord), @@ -221,7 +225,7 @@ fn saturating(code: &mut Vec, element: ElementSize, signedness: Signedness, copy(code, 0, 4); } } -fn subtract_with_borrow_mask(code: &mut Vec, element: ElementSize) { +fn subtract_with_borrow_mask(code: &mut Code, element: ElementSize) { copy(code, 3, 0); binary(code, arithmetic_opcode(element, true), 0, 1); copy(code, 4, 3); @@ -234,7 +238,7 @@ fn subtract_with_borrow_mask(code: &mut Vec, element: ElementSize) { sign_mask(code, 5, 5, element); } /// Signed destination minus an unsigned magnitude; only negative saturation occurs. -fn mixed_subtract(code: &mut Vec, element: ElementSize) { +fn mixed_subtract(code: &mut Code, element: ElementSize) { subtract_with_borrow_mask(code, element); sign_mask(code, 4, 3, element); sign_mask(code, 6, 0, element); @@ -253,7 +257,7 @@ fn mixed_subtract(code: &mut Vec, element: ElementSize) { } select_saturated(code); } -fn mixed_add(code: &mut Vec, element: ElementSize, signed_destination: bool) { +fn mixed_add(code: &mut Code, element: ElementSize, signed_destination: bool) { add_with_carry_mask(code, element); if signed_destination { sign_mask(code, 4, 3, element); @@ -284,7 +288,7 @@ fn mixed_add(code: &mut Vec, element: ElementSize, signed_destination: bool) } } fn halving( - code: &mut Vec, + code: &mut Code, element: ElementSize, signedness: Signedness, subtract: bool, @@ -345,7 +349,7 @@ fn halving( } } fn widen_interleaved( - code: &mut Vec, + code: &mut Code, register: u8, element: ElementSize, signedness: Signedness, @@ -364,7 +368,7 @@ fn widen_interleaved( ); } fn difference( - code: &mut Vec, + code: &mut Code, element: ElementSize, signedness: Signedness, widening: Option, @@ -420,7 +424,7 @@ fn difference( binary(code, arithmetic_opcode(element, true), 0, 4); } } -fn complex_partner(code: &mut Vec, element: ElementSize) { +fn complex_partner(code: &mut Code, element: ElementSize) { match element { ElementSize::Byte => { copy(code, 3, 1); @@ -460,7 +464,7 @@ fn repeat_lane(value: u64, element: ElementSize) -> u64 { pattern } -pub(crate) fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let element = operand.element_size; for chunk in 0..length.chunks() { load_z_chunk(code, operand.left, chunk, 0, length, target); diff --git a/crates/stela-compiler/src/x86_64/sve/memory.rs b/crates/stela-compiler/src/x86_64/sve/memory.rs index 46b40a97f9..35ca22a4e8 100644 --- a/crates/stela-compiler/src/x86_64/sve/memory.rs +++ b/crates/stela-compiler/src/x86_64/sve/memory.rs @@ -1,4 +1,6 @@ //! Address computation and fault exits shared by the SVE memory families. +use crate::x86_64::asm::Gpr::{Rax, Rcx}; +use crate::x86_64::asm::{Alu, Code, Cond, ShiftOp, Size}; use super::super::{load, scalable::memory as service}; use crate::aarch64::{ @@ -7,20 +9,7 @@ use crate::aarch64::{ sve::memory::{Address, Offset, Scale}, }; use crate::context::memory::MemoryStatus; -use alloc::vec::Vec; -const ADD_RAX_IMM8: &[u8] = &[0x48, 0x83, 0xc0]; -const ADD_RAX_IMM32: &[u8] = &[0x48, 0x05]; -const SHIFT_RAX_LEFT_IMM8: &[u8] = &[0x48, 0xc1, 0xe0]; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const ADD_RAX_RCX: &[u8] = &[0x48, 0x01, 0xc8]; -const TEST_AL_IMM8: u8 = 0xa8; -const JE_REL32: &[u8] = &[0x0f, 0x84]; -const JMP_REL32: u8 = 0xe9; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const JE_REL8: u8 = 0x74; -const RET: u8 = 0xc3; -const RET_BYTES: u8 = 1; const STACK_ALIGNMENT_BYTES: u8 = 16; const STACK_ALIGNMENT_MASK: u8 = STACK_ALIGNMENT_BYTES - 1; @@ -46,7 +35,7 @@ fn scale_bytes(scale: Scale, length: VectorLength) -> usize { /// Return the effective guest address in RAX, with 64-bit wrapping arithmetic. /// CPA2 is disabled; translation owns TBI handling. Clobbers RCX; RDI/R15 survive. -pub(crate) fn address(code: &mut Vec, operand: Address, length: VectorLength) { +pub(crate) fn address(code: &mut Code, operand: Address, length: VectorLength) { match operand.offset { Offset::Immediate { value, scale } => { load(code, operand.base); @@ -56,11 +45,10 @@ pub(crate) fn address(code: &mut Vec, operand: Address, length: VectorLength return; } if let Ok(short) = i8::try_from(displacement) { - code.extend(ADD_RAX_IMM8); - code.push(short as u8); + code.asm().alu_imm8(Alu::Add, Size::Qword, Rax, short); } else { - code.extend(ADD_RAX_IMM32); - code.extend(displacement.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Add, Size::Qword, displacement); } } Offset::Register { @@ -70,12 +58,11 @@ pub(crate) fn address(code: &mut Vec, operand: Address, length: VectorLength Offset::Register { index, shift } => { load(code, index); if shift != 0 { - code.extend(SHIFT_RAX_LEFT_IMM8); - code.push(shift); + code.asm().shift_imm(ShiftOp::Shl, Size::Qword, Rax, shift); } - code.extend(MOV_RCX_RAX); + code.asm().mov(Size::Qword, Rcx, Rax); load(code, operand.base); - code.extend(ADD_RAX_RCX); + code.asm().alu(Alu::Add, Size::Qword, Rax, Rcx); } } } @@ -83,33 +70,30 @@ pub(crate) fn address(code: &mut Vec, operand: Address, length: VectorLength /// Check SP before applying the displacement. Requires SA/SA0 enabled, with /// CHECKSPNONEACTIVE true. Prefetches must not call this. The caller patches /// the fault site to its cleanup. -pub(crate) fn check_sp(code: &mut Vec, base: Register, pc: u64) -> Option { +pub(crate) fn check_sp(code: &mut Code, base: Register, pc: u64) -> Option { if base != Register::Sp { return None; } load(code, Register::Sp); - code.push(TEST_AL_IMM8); - code.push(STACK_ALIGNMENT_MASK); - code.extend(JE_REL32); - let aligned = code.len(); - code.extend(0_i32.to_le_bytes()); + let mut asm = code.asm(); + asm.test_accumulator_imm(Size::Byte, i32::from(STACK_ALIGNMENT_MASK)); + let aligned = asm.jcc(Cond::E); service::fault(code, MemoryStatus::StackAlignment, pc); - code.push(JMP_REL32); - let failed = code.len(); - code.extend(0_i32.to_le_bytes()); - let destination = code.len(); - service::patch_branch(code, aligned, destination); - Some(failed) + let mut asm = code.asm(); + let failed = asm.jmp(); + asm.bind(aligned); + Some(failed.offset()) } /// After family scratch cleanup, return a failed inner body to its outer entry. /// The outer entry CALLs the body and owns POP_R15; this RET cannot bypass it. /// Success (EAX=0) falls through to the next translated guest instruction. -pub(crate) fn return_if_failed(code: &mut Vec) { - code.extend(TEST_EAX_EAX); - code.push(JE_REL8); - code.push(RET_BYTES); - code.push(RET); +pub(crate) fn return_if_failed(code: &mut Code) { + let mut asm = code.asm(); + asm.test(Size::Dword, Rax, Rax); + let succeeded = asm.jcc8(Cond::E); + asm.ret(); + asm.bind(succeeded); } #[cfg(test)] diff --git a/crates/stela-compiler/src/x86_64/sve/memory_load.rs b/crates/stela-compiler/src/x86_64/sve/memory_load.rs index 4c8c4a2ee6..f902efdcb5 100644 --- a/crates/stela-compiler/src/x86_64/sve/memory_load.rs +++ b/crates/stela-compiler/src/x86_64/sve/memory_load.rs @@ -1,6 +1,9 @@ //! SVE loads through the memory service into a private staging buffer, so a //! fault leaves the destination unchanged. use super::super::{isa::SimdOpcode as Host, scalable}; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rsp}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, Patch, Rm, Size}; use crate::{ TargetCpu, aarch64::{ @@ -21,34 +24,7 @@ use alloc::vec::Vec; const STACK_ALIGNMENT: u32 = 16; const QWORD_BYTES: u32 = size_of::() as u32; const PREDICATE_WORD_BITS: usize = u64::BITS as usize; -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; -const ADD_RAX_IMM32: &[u8] = &[0x48, 0x05]; -const MOV_RAX_RSP_DISP32: &[u8] = &[0x48, 0x8b, 0x84, 0x24]; -const MOV_EAX_RSP_DISP32: &[u8] = &[0x8b, 0x84, 0x24]; -const MOVZX_EAX_BYTE_RSP_DISP32: &[u8] = &[0x0f, 0xb6, 0x84, 0x24]; -const MOVZX_EAX_WORD_RSP_DISP32: &[u8] = &[0x0f, 0xb7, 0x84, 0x24]; -const MOVSX_RAX_BYTE_RSP_DISP32: &[u8] = &[0x48, 0x0f, 0xbe, 0x84, 0x24]; -const MOVSX_RAX_WORD_RSP_DISP32: &[u8] = &[0x48, 0x0f, 0xbf, 0x84, 0x24]; -const MOVSXD_RAX_RSP_DISP32: &[u8] = &[0x48, 0x63, 0x84, 0x24]; -const MOV_RSP_DISP32_RAX: &[u8] = &[0x48, 0x89, 0x84, 0x24]; -const MOV_RSP_DISP32_EAX: &[u8] = &[0x89, 0x84, 0x24]; -const MOV_RSP_DISP32_AX: &[u8] = &[0x66, 0x89, 0x84, 0x24]; -const MOV_RSP_DISP32_AL: &[u8] = &[0x88, 0x84, 0x24]; -const MOVDQU_RSP_DISP32_XMM0: &[u8] = &[0xf3, 0x0f, 0x7f, 0x84, 0x24]; -const MOVDQU_RSP_DISP32_XMM3: &[u8] = &[0xf3, 0x0f, 0x7f, 0x9c, 0x24]; -const SIMD_MODRM_REGISTER: u8 = 0xc0; const REPEAT_LOW_DWORD: u8 = 0; -const MOVDQU_XMM0_RSP_DISP32: &[u8] = &[0xf3, 0x0f, 0x6f, 0x84, 0x24]; -const PXOR_XMM0_XMM0: &[u8] = &[0x66, 0x0f, 0xef, 0xc0]; -const BT_RAX_IMM8: &[u8] = &[0x48, 0x0f, 0xba, 0xe0]; -const TEST_RAX_RAX: &[u8] = &[0x48, 0x85, 0xc0]; -const MOVABS_RCX_IMM64: &[u8] = &[0x48, 0xb9]; -const AND_RAX_RCX: &[u8] = &[0x48, 0x21, 0xc8]; -const JNZ_REL32: &[u8] = &[0x0f, 0x85]; -const JNC_REL32: &[u8] = &[0x0f, 0x83]; -const JMP_REL32: &[u8] = &[0xe9]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; #[derive(Clone, Copy)] struct Scratch { @@ -77,48 +53,45 @@ impl Scratch { } } -fn displacement(code: &mut Vec, opcode: &[u8], offset: u32) { - code.extend(opcode); - code.extend(offset.to_le_bytes()); +fn stack(offset: u32) -> Mem { + Mem::base_disp32(Rsp, offset as i32) } -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let position = code.len(); - code.extend(0_i32.to_le_bytes()); - position -} - -fn add_immediate(code: &mut Vec, value: i32) { +fn add_immediate(code: &mut Code, value: i32) { if value != 0 { - code.extend(ADD_RAX_IMM32); - code.extend(value.to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Add, Size::Qword, value); } } -fn predicate(code: &mut Vec, operand: Operand, length: VectorLength, scratch: Scratch) { +fn predicate(code: &mut Code, operand: Operand, length: VectorLength, scratch: Scratch) { if let Some(predicate) = operand.predicate { for word in 0..length.predicate_bytes().div_ceil(QWORD_BYTES as usize) { scalable::read_predicate_chunk(code, predicate, word, length); - displacement( - code, - MOV_RSP_DISP32_RAX, - scratch.predicate + word as u32 * QWORD_BYTES, + code.asm().mov_store( + Size::Qword, + stack(scratch.predicate + word as u32 * QWORD_BYTES), + Rax, ); } } } -fn inactive_branch(code: &mut Vec, bit: usize, scratch: Scratch) -> usize { +fn inactive_branch(code: &mut Code, bit: usize, scratch: Scratch) -> Patch { let word = bit / PREDICATE_WORD_BITS; - displacement( - code, - MOV_RAX_RSP_DISP32, - scratch.predicate + word as u32 * QWORD_BYTES, + let mut asm = code.asm(); + asm.mov_load( + Size::Qword, + Rax, + stack(scratch.predicate + word as u32 * QWORD_BYTES), ); - code.extend(BT_RAX_IMM8); - code.push((bit % PREDICATE_WORD_BITS) as u8); - branch(code, JNC_REL32) + asm.bit_imm( + BitTest::Bt, + Size::Qword, + Rax, + (bit % PREDICATE_WORD_BITS) as u8, + ); + asm.jcc(Cond::Ae) } fn access_flags(operand: Operand) -> u32 { @@ -168,7 +141,7 @@ pub(crate) fn requirements(operand: Operand) -> MemoryRequirements { } fn request( - code: &mut Vec, + code: &mut Code, operand: Operand, scratch: Scratch, source_offset: usize, @@ -176,7 +149,8 @@ fn request( pc: u64, failed: &mut Vec, ) { - displacement(code, MOV_RAX_RSP_DISP32, scratch.address); + code.asm() + .mov_load(Size::Qword, Rax, stack(scratch.address)); add_immediate(code, source_offset as i32); scalable::memory::request( code, @@ -190,33 +164,34 @@ fn request( failed.push(scalable::memory::branch_failed(code)); } -fn read_value(code: &mut Vec, source: u32, element: ElementSize, extension: Extension) { - let opcode = match (element, extension) { - (ElementSize::Byte, Extension::Zero) => MOVZX_EAX_BYTE_RSP_DISP32, - (ElementSize::Halfword, Extension::Zero) => MOVZX_EAX_WORD_RSP_DISP32, - (ElementSize::Word, Extension::Zero) => MOV_EAX_RSP_DISP32, - (ElementSize::Byte, Extension::Sign) => MOVSX_RAX_BYTE_RSP_DISP32, - (ElementSize::Halfword, Extension::Sign) => MOVSX_RAX_WORD_RSP_DISP32, - (ElementSize::Word, Extension::Sign) => MOVSXD_RAX_RSP_DISP32, - (ElementSize::Doubleword, _) => MOV_RAX_RSP_DISP32, +fn read_value(code: &mut Code, source: u32, element: ElementSize, extension: Extension) { + let source = stack(source); + let mut asm = code.asm(); + match (element, extension) { + (ElementSize::Byte, Extension::Zero) => asm.movzx(Size::Dword, Rax, Size::Byte, source), + (ElementSize::Halfword, Extension::Zero) => asm.movzx(Size::Dword, Rax, Size::Word, source), + (ElementSize::Word, Extension::Zero) => asm.mov_load(Size::Dword, Rax, source), + (ElementSize::Byte, Extension::Sign) => asm.movsx(Size::Qword, Rax, Size::Byte, source), + (ElementSize::Halfword, Extension::Sign) => asm.movsx(Size::Qword, Rax, Size::Word, source), + (ElementSize::Word, Extension::Sign) => asm.movsxd(Rax, source), + (ElementSize::Doubleword, _) => asm.mov_load(Size::Qword, Rax, source), (ElementSize::Quadword, _) => unreachable!("SVE load scalar element is at most64 bits"), - }; - displacement(code, opcode, source); + } } -fn write_value(code: &mut Vec, destination: u32, element: ElementSize) { - let opcode = match element { - ElementSize::Byte => MOV_RSP_DISP32_AL, - ElementSize::Halfword => MOV_RSP_DISP32_AX, - ElementSize::Word => MOV_RSP_DISP32_EAX, - ElementSize::Doubleword => MOV_RSP_DISP32_RAX, +fn write_value(code: &mut Code, destination: u32, element: ElementSize) { + let size = match element { + ElementSize::Byte => Size::Byte, + ElementSize::Halfword => Size::Word, + ElementSize::Word => Size::Dword, + ElementSize::Doubleword => Size::Qword, ElementSize::Quadword => unreachable!("SVE load scalar element is at most64 bits"), }; - displacement(code, opcode, destination); + code.asm().mov_store(size, stack(destination), Rax); } fn lanes( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, scratch: Scratch, @@ -244,13 +219,12 @@ fn lanes( read_value(code, destination, operand.memory_element, operand.extension); write_value(code, destination, operand.element); } - let end = code.len(); - scalable::memory::patch_branch(code, inactive, end); + code.asm().bind(inactive); } } fn scalar_replicate( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, scratch: Scratch, @@ -260,10 +234,10 @@ fn scalar_replicate( ) { let mut active = Vec::new(); for word in 0..length.predicate_bytes().div_ceil(QWORD_BYTES as usize) { - displacement( - code, - MOV_RAX_RSP_DISP32, - scratch.predicate + word as u32 * QWORD_BYTES, + code.asm().mov_load( + Size::Qword, + Rax, + stack(scratch.predicate + word as u32 * QWORD_BYTES), ); let first_bit = word * PREDICATE_WORD_BITS; let valid_bits = (length.bytes() - first_bit).min(PREDICATE_WORD_BITS); @@ -271,17 +245,18 @@ fn scalar_replicate( .step_by(operand.element.bytes()) .fold(0_u64, |mask, bit| mask | 1_u64 << bit); if mask != u64::MAX { - code.extend(MOVABS_RCX_IMM64); - code.extend(mask.to_le_bytes()); - code.extend(AND_RAX_RCX); + let mut asm = code.asm(); + asm.mov_imm64(Rcx, mask); + asm.alu(Alu::And, Size::Qword, Rax, Rcx); } - code.extend(TEST_RAX_RAX); - active.push(branch(code, JNZ_REL32)); + let mut asm = code.asm(); + asm.test(Size::Qword, Rax, Rax); + active.push(asm.jcc(Cond::Ne)); } - let empty = branch(code, JMP_REL32); - let start = code.len(); + let mut asm = code.asm(); + let empty = asm.jmp(); for active in active { - scalable::memory::patch_branch(code, active, start); + asm.bind(active); } request(code, operand, scratch, 0, scratch.scalar, pc, failed); read_value( @@ -290,23 +265,22 @@ fn scalar_replicate( operand.memory_element, operand.extension, ); - Host::MoveGprQword.append(code, target); - code.push(SIMD_MODRM_REGISTER); + code.asm().simd(Host::MoveGprQword, 0, Rax, target); match operand.element { ElementSize::Byte => { Host::UnpackLowByte.register(code, 0, 0, target); Host::UnpackLowWord.register(code, 0, 0, target); - Host::ShuffleDword.register(code, 0, 0, target); - code.push(REPEAT_LOW_DWORD); + code.asm() + .simd_imm(Host::ShuffleDword, 0, Rm::Xmm(0), REPEAT_LOW_DWORD, target); } ElementSize::Halfword => { Host::UnpackLowWord.register(code, 0, 0, target); - Host::ShuffleDword.register(code, 0, 0, target); - code.push(REPEAT_LOW_DWORD); + code.asm() + .simd_imm(Host::ShuffleDword, 0, Rm::Xmm(0), REPEAT_LOW_DWORD, target); } ElementSize::Word => { - Host::ShuffleDword.register(code, 0, 0, target); - code.push(REPEAT_LOW_DWORD); + code.asm() + .simd_imm(Host::ShuffleDword, 0, Rm::Xmm(0), REPEAT_LOW_DWORD, target); } ElementSize::Doubleword => Host::UnpackLowQword.register(code, 0, 0, target), ElementSize::Quadword => unreachable!("scalar replicate element is at most64 bits"), @@ -324,33 +298,27 @@ fn scalar_replicate( ); Host::MoveAligned.register(code, 3, 0, target); Host::And.register(code, 3, 1, target); - displacement( - code, - MOVDQU_RSP_DISP32_XMM3, - (chunk * VECTOR_CHUNK_BYTES) as u32, - ); + code.asm() + .movdqu_store(stack((chunk * VECTOR_CHUNK_BYTES) as u32), 3); } - let end = code.len(); - scalable::memory::patch_branch(code, empty, end); + code.asm().bind(empty); } -fn commit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +fn commit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { if operand.kind == Kind::WholePredicate { for word in 0..length.predicate_bytes().div_ceil(QWORD_BYTES as usize) { - displacement(code, MOV_RAX_RSP_DISP32, word as u32 * QWORD_BYTES); + code.asm() + .mov_load(Size::Qword, Rax, stack(word as u32 * QWORD_BYTES)); scalable::write_predicate_chunk(code, operand.data, word, length); } } else { if operand.kind == Kind::ReplicateQuad { - displacement(code, MOVDQU_XMM0_RSP_DISP32, 0); + code.asm().movdqu_load(0, stack(0)); } for chunk in 0..length.chunks() { if operand.kind != Kind::ReplicateQuad { - displacement( - code, - MOVDQU_XMM0_RSP_DISP32, - (chunk * VECTOR_CHUNK_BYTES) as u32, - ); + code.asm() + .movdqu_load(0, stack((chunk * VECTOR_CHUNK_BYTES) as u32)); } scalable::store_z_chunk(code, operand.data, chunk, 0, length, target); } @@ -361,29 +329,27 @@ fn commit(code: &mut Vec, operand: Operand, length: VectorLength, target: Ta /// and returns through the shared epilogue; success falls through. Both restore /// the private stack allocation. SCTLR.A is 0; SP alignment is still checked. pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu, pc: u64, ) { let scratch = Scratch::new(length); - displacement(code, SUB_RSP_IMM32, scratch.bytes); + code.asm() + .alu_imm32(Alu::Sub, Size::Qword, Rsp, scratch.bytes as i32); scalable::memory::begin(code); let zero_chunks = match operand.kind { Kind::WholeVector | Kind::WholePredicate => 0, Kind::ReplicateQuad => 1, Kind::Contiguous | Kind::ReplicateScalar => length.chunks(), }; + let mut asm = code.asm(); if zero_chunks != 0 { - code.extend(PXOR_XMM0_XMM0); + asm.simd(Host::Xor, 0, Rm::Xmm(0), TargetCpu::Baseline); } for chunk in 0..zero_chunks { - displacement( - code, - MOVDQU_RSP_DISP32_XMM0, - (chunk * VECTOR_CHUNK_BYTES) as u32, - ); + asm.movdqu_store(stack((chunk * VECTOR_CHUNK_BYTES) as u32), 0); } predicate(code, operand, length, scratch); let mut failed = Vec::new(); @@ -391,7 +357,8 @@ pub(crate) fn emit( failed.push(fault); } super::memory::address(code, operand.address, length); - displacement(code, MOV_RSP_DISP32_RAX, scratch.address); + code.asm() + .mov_store(Size::Qword, stack(scratch.address), Rax); match operand.kind { Kind::Contiguous | Kind::ReplicateQuad => { lanes(code, operand, length, scratch, pc, &mut failed) @@ -411,12 +378,13 @@ pub(crate) fn emit( } } commit(code, operand, length, target); - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); let cleanup = code.len(); for failed in failed { scalable::memory::patch_branch(code, failed, cleanup); } - displacement(code, ADD_RSP_IMM32, scratch.bytes); + code.asm() + .alu_imm32(Alu::Add, Size::Qword, Rsp, scratch.bytes as i32); super::memory::return_if_failed(code); } diff --git a/crates/stela-compiler/src/x86_64/sve/memory_multi.rs b/crates/stela-compiler/src/x86_64/sve/memory_multi.rs index 9574afb947..a2143d2a31 100644 --- a/crates/stela-compiler/src/x86_64/sve/memory_multi.rs +++ b/crates/stela-compiler/src/x86_64/sve/memory_multi.rs @@ -3,6 +3,9 @@ use super::super::{isa::SimdOpcode as Host, scalable}; use super::memory as common; use super::predicate::{emit_prepared_counter_chunk, prepare_counter}; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::Gpr::{Rax, Rcx, Rsp}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, Size, resolve}; use crate::{ TargetCpu, aarch64::{ @@ -15,7 +18,6 @@ use crate::{ SpAlignmentRequirement, flags, host_caps, profile_requirements, }, }; -use alloc::vec::Vec; const HOST_QWORD_BYTES: u32 = size_of::() as u32; const STACK_ALIGNMENT: u32 = 16; @@ -25,22 +27,6 @@ const ADDRESS_OFFSET: u32 = MEMORY_REQUEST_BYTES as u32; const INDEX_OFFSET: u32 = ADDRESS_OFFSET + HOST_QWORD_BYTES; const MASK_OFFSET: u32 = INDEX_OFFSET + HOST_QWORD_BYTES; const VECTOR_TEMPORARY: u8 = 0; -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; -const MOV_RSP_DISP32_RAX: &[u8] = &[0x48, 0x89, 0x84, 0x24]; -const MOV_RAX_RSP_DISP32: &[u8] = &[0x48, 0x8b, 0x84, 0x24]; -const MOV_RCX_RSP_DISP32: &[u8] = &[0x48, 0x8b, 0x8c, 0x24]; -const MOV_RSP_DISP32_IMM32: &[u8] = &[0x48, 0xc7, 0x84, 0x24]; -const ADD_RAX_RCX: &[u8] = &[0x48, 0x01, 0xc8]; -const BT_RSP_DISP32_RCX: &[u8] = &[0x48, 0x0f, 0xa3, 0x8c, 0x24]; -const ADD_RSP_DISP32_RCX: &[u8] = &[0x48, 0x01, 0x8c, 0x24]; -const ADD_RSP_DISP32_IMM8: &[u8] = &[0x48, 0x83, 0x84, 0x24]; -const CMP_RSP_DISP32_IMM32: &[u8] = &[0x48, 0x81, 0xbc, 0x24]; -const JNC_REL32: &[u8] = &[0x0f, 0x83]; -const JB_REL32: &[u8] = &[0x0f, 0x82]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const STACK_MEMORY_MODRM: u8 = 0x84; -const STACK_SIB: u8 = 0x24; #[derive(Debug, Clone, Copy)] struct Scratch { @@ -59,35 +45,29 @@ impl Scratch { } } -fn stack_vector(code: &mut Vec, offset: u32, loading: bool, target: TargetCpu) { +fn stack_vector(code: &mut Code, offset: u32, loading: bool, target: TargetCpu) { let opcode = if loading { Host::LoadUnaligned } else { Host::StoreUnaligned }; - opcode.append(code, target); - code.extend([STACK_MEMORY_MODRM, STACK_SIB]); - code.extend(offset.to_le_bytes()); + code.asm() + .simd(opcode, VECTOR_TEMPORARY, stack(offset), target); } -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement +fn stack(offset: u32) -> Mem { + Mem::base_disp32(Rsp, offset as i32) } -fn prepare_iteration(code: &mut Vec, operand: &Operand, length: VectorLength) { +fn prepare_iteration(code: &mut Code, operand: &Operand, length: VectorLength) { common::address(code, operand.address, length); - code.extend(MOV_RSP_DISP32_RAX); - code.extend(ADDRESS_OFFSET.to_le_bytes()); - code.extend(MOV_RSP_DISP32_IMM32); - code.extend(INDEX_OFFSET.to_le_bytes()); - code.extend(0_u32.to_le_bytes()); + let mut asm = code.asm(); + asm.mov_store(Size::Qword, stack(ADDRESS_OFFSET), Rax); + asm.mov_rm_imm32(Size::Qword, stack(INDEX_OFFSET), 0); } fn prepare_vector_staging( - code: &mut Vec, + code: &mut Code, operand: &Operand, scratch: Scratch, length: VectorLength, @@ -117,19 +97,22 @@ fn prepare_vector_staging( /// Decode PN once, then spill its packed mask before any memory callback. /// The published chunk helper preserves R8/R9/R10 preparation state. Only /// private-stack stores intervene, so no callback clobber crosses that interval. -fn prepare_predicate_staging(code: &mut Vec, operand: &Operand, length: VectorLength) { +fn prepare_predicate_staging(code: &mut Code, operand: &Operand, length: VectorLength) { let predicate_bits = usize::from(operand.registers) * length.bytes(); scalable::read_predicate_chunk(code, operand.predicate, 0, length); prepare_counter(code, length); for chunk in 0..predicate_bits.div_ceil(PACKED_CHUNK_BITS) { emit_prepared_counter_chunk(code, chunk, length); - code.extend(MOV_RSP_DISP32_RAX); - code.extend((MASK_OFFSET + chunk as u32 * HOST_QWORD_BYTES).to_le_bytes()); + code.asm().mov_store( + Size::Qword, + stack(MASK_OFFSET + chunk as u32 * HOST_QWORD_BYTES), + Rax, + ); } } fn commit_load( - code: &mut Vec, + code: &mut Code, operand: &Operand, scratch: Scratch, length: VectorLength, @@ -204,7 +187,7 @@ pub(crate) fn requirements(operand: &Operand) -> MemoryRequirements { /// RSP=8 modulo16. Failure restores scratch then returns the inner body to its /// outer context wrapper; success has EAX=0 and falls through. RDI/R15 survive. pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu, @@ -213,22 +196,20 @@ pub(crate) fn emit( use scalable::memory; let tuple_bytes = usize::from(operand.registers) * length.bytes(); let scratch = Scratch::new(tuple_bytes); - code.extend(SUB_RSP_IMM32); - code.extend(scratch.bytes.to_le_bytes()); + code.asm() + .alu_imm32(Alu::Sub, Size::Qword, Rsp, scratch.bytes as i32); memory::begin(code); let alignment_failure = common::check_sp(code, operand.address.base, pc); prepare_iteration(code, operand, length); prepare_vector_staging(code, operand, scratch, length, target); prepare_predicate_staging(code, operand, length); let loop_start = code.len(); - code.extend(MOV_RCX_RSP_DISP32); - code.extend(INDEX_OFFSET.to_le_bytes()); - code.extend(BT_RSP_DISP32_RCX); - code.extend(MASK_OFFSET.to_le_bytes()); - let inactive = branch(code, JNC_REL32); - code.extend(MOV_RAX_RSP_DISP32); - code.extend(ADDRESS_OFFSET.to_le_bytes()); - code.extend(ADD_RAX_RCX); + let mut asm = code.asm(); + asm.mov_load(Size::Qword, Rcx, stack(INDEX_OFFSET)); + asm.bit(BitTest::Bt, Size::Qword, stack(MASK_OFFSET), Rcx); + let inactive = asm.jcc(Cond::Ae); + asm.mov_load(Size::Qword, Rax, stack(ADDRESS_OFFSET)); + asm.alu(Alu::Add, Size::Qword, Rax, Rcx); memory::request( code, REQUEST_OFFSET, @@ -239,40 +220,52 @@ pub(crate) fn emit( ); // request() clobbers RCX/RDX. Reload the saved linear byte offset before // selecting this element's private staging, never an architectural Z slot. - code.extend(MOV_RCX_RSP_DISP32); - code.extend(INDEX_OFFSET.to_le_bytes()); - code.extend(ADD_RSP_DISP32_RCX); - code.extend((REQUEST_OFFSET + MEMORY_REQUEST_DATA_OFFSET).to_le_bytes()); + let mut asm = code.asm(); + asm.mov_load(Size::Qword, Rcx, stack(INDEX_OFFSET)); + asm.alu( + Alu::Add, + Size::Qword, + stack(REQUEST_OFFSET + MEMORY_REQUEST_DATA_OFFSET), + Rcx, + ); memory::call(code, REQUEST_OFFSET); let callback_failure = memory::branch_failed(code); - let next_element = code.len(); - memory::patch_branch(code, inactive, next_element); - code.extend(ADD_RSP_DISP32_IMM8); - code.extend(INDEX_OFFSET.to_le_bytes()); - code.push(operand.element.bytes() as u8); - code.extend(CMP_RSP_DISP32_IMM32); - code.extend(INDEX_OFFSET.to_le_bytes()); - code.extend((tuple_bytes as u32).to_le_bytes()); - let repeat = branch(code, JB_REL32); - memory::patch_branch(code, repeat, loop_start); + let mut asm = code.asm(); + asm.bind(inactive); + asm.alu_imm8( + Alu::Add, + Size::Qword, + stack(INDEX_OFFSET), + operand.element.bytes() as i8, + ); + asm.alu_imm32( + Alu::Cmp, + Size::Qword, + stack(INDEX_OFFSET), + tuple_bytes as i32, + ); + let repeat = asm.jcc(Cond::B); + resolve(code, repeat, loop_start); if operand.loading { commit_load(code, operand, scratch, length, target); } - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); let cleanup = code.len(); memory::patch_branch(code, callback_failure, cleanup); if let Some(failure) = alignment_failure { memory::patch_branch(code, failure, cleanup); } - code.extend(ADD_RSP_IMM32); - code.extend(scratch.bytes.to_le_bytes()); + code.asm() + .alu_imm32(Alu::Add, Size::Qword, Rsp, scratch.bytes as i32); common::return_if_failed(code); } #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; + + const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; + const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; #[test] fn private_scratch_is_bounded_aligned_and_disjoint() { @@ -296,7 +289,7 @@ mod tests { let operand = crate::aarch64::sve::memory_multi::decode(word) .unwrap() .unwrap(); - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, length, TargetCpu::Baseline, 0x1000); let scratch = Scratch::new(usize::from(operand.registers) * vector_bytes); assert!(code.starts_with(SUB_RSP_IMM32)); diff --git a/crates/stela-compiler/src/x86_64/sve/memory_store.rs b/crates/stela-compiler/src/x86_64/sve/memory_store.rs index 412b5bc6ca..1a3e4e8228 100644 --- a/crates/stela-compiler/src/x86_64/sve/memory_store.rs +++ b/crates/stela-compiler/src/x86_64/sve/memory_store.rs @@ -1,6 +1,9 @@ //! SVE stores through the memory service, one element per request in ascending //! order. Sources and loop state live on the stack across calls. use super::memory as shared_address; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::Gpr::{R8, Rax, Rcx, Rsp}; +use crate::x86_64::asm::{Alu, Code, Cond, Disp, Mem, Patch, Size, resolve}; use crate::{ TargetCpu, aarch64::{ @@ -29,32 +32,8 @@ const PREDICATE_OFFSET: u32 = INDEX_OFFSET + size_of::() as u32; const STACK_ALIGNMENT_BYTES: u32 = 16; const HOST_QWORD_BYTES: usize = size_of::(); const SOURCE_XMM: u8 = 0; -const X86_MODRM_DISP32: u8 = 0x84; -const X86_SIB_RSP: u8 = 0x24; -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; -const MOV_RSP_DISP32_RAX: &[u8] = &[0x48, 0x89, 0x84, 0x24]; -const MOV_RAX_RSP_DISP32: &[u8] = &[0x48, 0x8b, 0x84, 0x24]; -const MOV_ECX_RSP_DISP8: &[u8] = &[0x8b, 0x4c, 0x24]; -const MOV_RSP_DISP32_IMM32_QWORD: &[u8] = &[0x48, 0xc7, 0x84, 0x24]; -const ADD_RSP_DISP32_IMM8: &[u8] = &[0x48, 0x83, 0x84, 0x24]; -const LEA_RAX_RSP_RCX_DISP8: &[u8] = &[0x48, 0x8d, 0x44, 0x0c]; -const LEA_RAX_RSP_RCX_DISP32: &[u8] = &[0x48, 0x8d, 0x84, 0x0c]; -const MOV_RSP_DISP8_RAX: &[u8] = &[0x48, 0x89, 0x44, 0x24]; const _: () = assert!(INDEX_OFFSET <= i8::MAX as u32); const _: () = assert!(REQUEST_OFFSET + MEMORY_REQUEST_DATA_OFFSET <= i8::MAX as u32); -const CMP_RSP_DISP32_IMM32: &[u8] = &[0x48, 0x81, 0xbc, 0x24]; -const BT_RSP_DISP32_RCX: &[u8] = &[0x48, 0x0f, 0xa3, 0x8c, 0x24]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const XOR_R8D_R8D: &[u8] = &[0x45, 0x31, 0xc0]; -const MOVABS_RCX_IMM64: &[u8] = &[0x48, 0xb9]; -const AND_RAX_RCX: &[u8] = &[0x48, 0x21, 0xc8]; -const OR_R8_RAX: &[u8] = &[0x49, 0x09, 0xc0]; -const TEST_R8_R8: &[u8] = &[0x4d, 0x85, 0xc0]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JMP_REL32: &[u8] = &[0xe9]; -const JNC_REL32: &[u8] = &[0x0f, 0x83]; -const JB_REL32: &[u8] = &[0x0f, 0x82]; struct Layout { source: u32, @@ -75,48 +54,41 @@ fn align(bytes: u32) -> u32 { bytes.div_ceil(STACK_ALIGNMENT_BYTES) * STACK_ALIGNMENT_BYTES } -fn store_stack_chunk(code: &mut Vec, offset: u32, target: TargetCpu) { - Host::StoreUnaligned.append(code, target); - code.extend([X86_MODRM_DISP32, X86_SIB_RSP]); - code.extend(offset.to_le_bytes()); +fn stack(offset: u32) -> Mem { + Mem::base_disp32(Rsp, offset as i32) } -fn stack_rax(code: &mut Vec, offset: u32, store: bool) { - code.extend(if store { - MOV_RSP_DISP32_RAX +fn store_stack_chunk(code: &mut Code, offset: u32, target: TargetCpu) { + code.asm() + .simd(Host::StoreUnaligned, SOURCE_XMM, stack(offset), target); +} + +fn stack_rax(code: &mut Code, offset: u32, store: bool) { + let mut asm = code.asm(); + if store { + asm.mov_store(Size::Qword, stack(offset), Rax); } else { - MOV_RAX_RSP_DISP32 - }); - code.extend(offset.to_le_bytes()); + asm.mov_load(Size::Qword, Rax, stack(offset)); + } } -fn set_index(code: &mut Vec) { - code.extend(MOV_RSP_DISP32_IMM32_QWORD); - code.extend(INDEX_OFFSET.to_le_bytes()); - code.extend(0_u32.to_le_bytes()); +fn set_index(code: &mut Code) { + code.asm().mov_rm_imm32(Size::Qword, stack(INDEX_OFFSET), 0); } -fn load_index(code: &mut Vec) { - code.extend(MOV_ECX_RSP_DISP8); - code.push(INDEX_OFFSET as u8); +fn load_index(code: &mut Code) { + code.asm() + .mov_load(Size::Dword, Rcx, Mem::base_disp8(Rsp, INDEX_OFFSET as i8)); } -fn add_stack(code: &mut Vec, offset: u32, bytes: u8) { +fn add_stack(code: &mut Code, offset: u32, bytes: u8) { debug_assert!(bytes <= i8::MAX as u8); - code.extend(ADD_RSP_DISP32_IMM8); - code.extend(offset.to_le_bytes()); - code.push(bytes); -} - -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement + code.asm() + .alu_imm8(Alu::Add, Size::Qword, stack(offset), bytes as i8); } fn copy_sources( - code: &mut Vec, + code: &mut Code, source: u8, count: u8, layout: &Layout, @@ -135,7 +107,7 @@ fn copy_sources( } } -fn copy_predicate(code: &mut Vec, predicate: u8, destination: u32, length: VectorLength) { +fn copy_predicate(code: &mut Code, predicate: u8, destination: u32, length: VectorLength) { for chunk in 0..length.predicate_bytes().div_ceil(HOST_QWORD_BYTES) { read_predicate_chunk(code, predicate, chunk, length); stack_rax(code, destination + (chunk * HOST_QWORD_BYTES) as u32, true); @@ -143,11 +115,11 @@ fn copy_predicate(code: &mut Vec, predicate: u8, destination: u32, length: V } /// Snapshot P and branch around all source staging when no element is active. -fn copy_active_predicate(code: &mut Vec, store: &Store, length: VectorLength) -> usize { +fn copy_active_predicate(code: &mut Code, store: &Store, length: VectorLength) -> Patch { let mask = (0..u64::BITS as usize) .step_by(store.element.bytes()) .fold(0_u64, |bits, bit| bits | (1_u64 << bit)); - code.extend(XOR_R8D_R8D); + code.asm().alu(Alu::Xor, Size::Dword, R8, R8); for chunk in 0..length.predicate_bytes().div_ceil(HOST_QWORD_BYTES) { read_predicate_chunk(code, store.predicate, chunk, length); stack_rax( @@ -156,18 +128,19 @@ fn copy_active_predicate(code: &mut Vec, store: &Store, length: VectorLength true, ); if mask != u64::MAX { - code.extend(MOVABS_RCX_IMM64); - code.extend(mask.to_le_bytes()); - code.extend(AND_RAX_RCX); + let mut asm = code.asm(); + asm.mov_imm64(Rcx, mask); + asm.alu(Alu::And, Size::Qword, Rax, Rcx); } - code.extend(OR_R8_RAX); + code.asm().alu(Alu::Or, Size::Qword, R8, Rax); } - code.extend(TEST_R8_R8); - branch(code, JZ_REL32) + let mut asm = code.asm(); + asm.test(Size::Qword, R8, R8); + asm.jcc(Cond::E) } fn submit( - code: &mut Vec, + code: &mut Code, source: u32, bytes: u32, descriptor: u32, @@ -180,30 +153,36 @@ fn submit( // point at the reached element in the immutable private source snapshot. // The request width selects its exact low bytes, including narrowing stores. load_index(code); - if source <= i8::MAX as u32 { - code.extend(LEA_RAX_RSP_RCX_DISP8); - code.push(source as u8); + let width = if source <= i8::MAX as u32 { + Disp::Byte } else { - code.extend(LEA_RAX_RSP_RCX_DISP32); - code.extend(source.to_le_bytes()); - } - code.extend(MOV_RSP_DISP8_RAX); - code.push((REQUEST_OFFSET + MEMORY_REQUEST_DATA_OFFSET) as u8); + Disp::Dword + }; + let mut asm = code.asm(); + asm.lea( + Size::Qword, + Rax, + Mem::indexed(Rsp, Rcx, 1, source as i32).with_width(width), + ); + asm.mov_store( + Size::Qword, + Mem::base_disp8(Rsp, (REQUEST_OFFSET + MEMORY_REQUEST_DATA_OFFSET) as i8), + Rax, + ); memory::call(code, REQUEST_OFFSET); failures.push(memory::branch_failed(code)); } -fn loop_end(code: &mut Vec, step: u8, limit: u32, start: usize) { +fn loop_end(code: &mut Code, step: u8, limit: u32, start: usize) { add_stack(code, INDEX_OFFSET, step); - code.extend(CMP_RSP_DISP32_IMM32); - code.extend(INDEX_OFFSET.to_le_bytes()); - code.extend(limit.to_le_bytes()); - let repeat = branch(code, JB_REL32); - memory::patch_branch(code, repeat, start); + let mut asm = code.asm(); + asm.alu_imm32(Alu::Cmp, Size::Qword, stack(INDEX_OFFSET), limit as i32); + let repeat = asm.jcc(Cond::B); + resolve(code, repeat, start); } fn store_loop( - code: &mut Vec, + code: &mut Code, store: &Store, layout: &Layout, length: VectorLength, @@ -212,9 +191,9 @@ fn store_loop( ) { let start = code.len(); load_index(code); - code.extend(BT_RSP_DISP32_RCX); - code.extend(PREDICATE_OFFSET.to_le_bytes()); - let inactive = branch(code, JNC_REL32); + let mut asm = code.asm(); + asm.bit(BitTest::Bt, Size::Qword, stack(PREDICATE_OFFSET), Rcx); + let inactive = asm.jcc(Cond::Ae); let descriptor = descriptor(store.address, store.non_temporal, true); for member in 0..store.register_count { let source = layout.source + u32::from(member) * length.bytes() as u32; @@ -228,16 +207,15 @@ fn store_loop( ); add_stack(code, ADDRESS_OFFSET, store.memory_element.bytes() as u8); } - let active_done = branch(code, JMP_REL32); - let inactive_start = code.len(); - memory::patch_branch(code, inactive, inactive_start); + let mut asm = code.asm(); + let active_done = asm.jmp(); + asm.bind(inactive); add_stack( code, ADDRESS_OFFSET, store.memory_element.bytes() as u8 * store.register_count, ); - let next_lane = code.len(); - memory::patch_branch(code, active_done, next_lane); + code.asm().bind(active_done); loop_end( code, store.element.bytes() as u8, @@ -247,7 +225,7 @@ fn store_loop( } fn whole_loop( - code: &mut Vec, + code: &mut Code, store: &WholeStore, layout: &Layout, bytes: usize, @@ -322,7 +300,7 @@ pub(crate) fn requirements(operand: &Operand) -> MemoryRequirements { /// exits on nonzero. Alignment is not enforced, but the 16-byte SP check runs /// before any offset, even with an empty predicate. pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu, @@ -332,7 +310,7 @@ pub(crate) fn emit( Operand::Prefetch(_) => { // Hint_Prefetch has a documented implementation-defined ignored // behavior. The shared dispatcher already checked the mode. - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); return; } Operand::Store(store) => ( @@ -348,8 +326,8 @@ pub(crate) fn emit( ), }; let layout = Layout::new(length, source_bytes); - code.extend(SUB_RSP_IMM32); - code.extend(layout.bytes.to_le_bytes()); + code.asm() + .alu_imm32(Alu::Sub, Size::Qword, Rsp, layout.bytes as i32); memory::begin(code); let mut failures = Vec::new(); if let Some(failure) = shared_address::check_sp(code, address.base, pc) { @@ -386,16 +364,16 @@ pub(crate) fn emit( } Operand::Prefetch(_) => unreachable!("prefetch returned before stack allocation"), }; - let success = code.len(); + let mut asm = code.asm(); if let Some(empty) = empty { - memory::patch_branch(code, empty, success); + asm.bind(empty); } - code.extend(XOR_EAX_EAX); + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); let cleanup = code.len(); for failure in failures { memory::patch_branch(code, failure, cleanup); } - code.extend(ADD_RSP_IMM32); - code.extend(layout.bytes.to_le_bytes()); + code.asm() + .alu_imm32(Alu::Add, Size::Qword, Rsp, layout.bytes as i32); shared_address::return_if_failed(code); } diff --git a/crates/stela-compiler/src/x86_64/sve/memory_structure.rs b/crates/stela-compiler/src/x86_64/sve/memory_structure.rs index bfca1c8470..8053f4bf67 100644 --- a/crates/stela-compiler/src/x86_64/sve/memory_structure.rs +++ b/crates/stela-compiler/src/x86_64/sve/memory_structure.rs @@ -5,6 +5,8 @@ use super::super::{ scalable::{self, memory}, }; use super::memory as transfer; +use crate::x86_64::asm::Gpr::{R8, Rax, Rsp}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, ShiftOp, Size, resolve}; use crate::{ TargetCpu, aarch64::{ @@ -23,24 +25,7 @@ const POINTER_BYTES: u32 = size_of::() as u32; const STACK_ALIGNMENT: u32 = 16; const PREDICATE_CHUNK_BITS: usize = u64::BITS as usize; const PREDICATE_SELECTED: u8 = 1; -const STACK_SIB: u8 = 0x24; -const STACK_DISP32_XMM0: u8 = 0x84; const ZERO_XMM: u8 = 0; -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; -const MOV_RSP_DISP32_RAX: &[u8] = &[0x48, 0x89, 0x84, STACK_SIB]; -const MOV_RAX_RSP_DISP32: &[u8] = &[0x48, 0x8b, 0x84, STACK_SIB]; -const MOV_R8_RSP_DISP32: &[u8] = &[0x4c, 0x8b, 0x84, STACK_SIB]; -const ADD_RSP_DISP32_R8: &[u8] = &[0x4c, 0x01, 0x84, STACK_SIB]; -const MOV_RSP_DISP32_IMM32: &[u8] = &[0x48, 0xc7, 0x84, STACK_SIB]; -const ADD_RSP_DISP32_IMM32: &[u8] = &[0x48, 0x81, 0x84, STACK_SIB]; -const CMP_RSP_DISP32_IMM32: &[u8] = &[0x48, 0x81, 0xbc, STACK_SIB]; -const SHR_RSP_DISP32_IMM8: &[u8] = &[0x48, 0xc1, 0xac, STACK_SIB]; -const TEST_RSP_DISP32_IMM8: &[u8] = &[0xf6, 0x84, STACK_SIB]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JB_REL32: &[u8] = &[0x0f, 0x82]; -const JMP_REL32: &[u8] = &[0xe9]; #[derive(Debug, Clone, Copy)] struct Scratch { @@ -72,28 +57,12 @@ impl Scratch { } } -fn stack_immediate(code: &mut Vec, opcode: &[u8], offset: u32, value: u32) { - code.extend(opcode); - code.extend(offset.to_le_bytes()); - code.extend(value.to_le_bytes()); +fn stack(offset: u32) -> Mem { + Mem::base_disp32(Rsp, offset as i32) } -fn stack_operand(code: &mut Vec, opcode: &[u8], offset: u32) { - code.extend(opcode); - code.extend(offset.to_le_bytes()); -} - -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement -} - -fn stack_vector(code: &mut Vec, opcode: Host, offset: u32, target: TargetCpu) { - opcode.append(code, target); - code.extend([STACK_DISP32_XMM0, STACK_SIB]); - code.extend(offset.to_le_bytes()); +fn stack_vector(code: &mut Code, opcode: Host, offset: u32, target: TargetCpu) { + code.asm().simd(opcode, ZERO_XMM, stack(offset), target); } fn access_flags(operand: Operand) -> u32 { @@ -143,7 +112,7 @@ pub(crate) fn requirements(operand: Operand) -> MemoryRequirements { /// in EAX; success sets EAX to 0 and falls through. SP is checked even when /// every lane is inactive. pub(crate) fn emit( - code: &mut Vec, + code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu, @@ -153,15 +122,16 @@ pub(crate) fn emit( let width = operand.element.bytes() as u32; let access_flags = access_flags(*operand); let mut failures = Vec::new(); - code.extend(SUB_RSP_IMM32); - code.extend(scratch.bytes.to_le_bytes()); + code.asm() + .alu_imm32(Alu::Sub, Size::Qword, Rsp, scratch.bytes as i32); memory::begin(code); if let Some(failure) = transfer::check_sp(code, operand.address.base, pc) { failures.push(failure); } transfer::address(code, operand.address, length); - stack_operand(code, MOV_RSP_DISP32_RAX, scratch.address); - stack_immediate(code, MOV_RSP_DISP32_IMM32, scratch.lane, 0); + let mut asm = code.asm(); + asm.mov_store(Size::Qword, stack(scratch.address), Rax); + asm.mov_rm_imm32(Size::Qword, stack(scratch.lane), 0); Host::Xor.register(code, ZERO_XMM, ZERO_XMM, target); for offset in (0..scratch.data_bytes).step_by(VECTOR_CHUNK_BYTES) { stack_vector(code, Host::StoreUnaligned, offset, target); @@ -172,13 +142,19 @@ pub(crate) fn emit( let predicate_chunks = length.bytes().div_ceil(PREDICATE_CHUNK_BITS); for chunk in 0..predicate_chunks { scalable::read_predicate_chunk(code, operand.predicate, chunk, length); - stack_operand(code, MOV_RSP_DISP32_RAX, scratch.predicate); + code.asm() + .mov_store(Size::Qword, stack(scratch.predicate), Rax); let start = code.len(); - stack_operand(code, TEST_RSP_DISP32_IMM8, scratch.predicate); - code.push(PREDICATE_SELECTED); - let inactive = branch(code, JZ_REL32); + let mut asm = code.asm(); + asm.test_imm( + Size::Byte, + stack(scratch.predicate), + i32::from(PREDICATE_SELECTED), + ); + let inactive = asm.jcc(Cond::E); for tuple_index in 0..operand.registers { - stack_operand(code, MOV_RAX_RSP_DISP32, scratch.address); + code.asm() + .mov_load(Size::Qword, Rax, stack(scratch.address)); memory::request( code, scratch.request, @@ -187,34 +163,40 @@ pub(crate) fn emit( access_flags, pc, ); - stack_operand(code, MOV_R8_RSP_DISP32, scratch.lane); - stack_operand( - code, - ADD_RSP_DISP32_R8, - scratch.request + MEMORY_REQUEST_DATA_OFFSET, + let mut asm = code.asm(); + asm.mov_load(Size::Qword, R8, stack(scratch.lane)); + asm.alu( + Alu::Add, + Size::Qword, + stack(scratch.request + MEMORY_REQUEST_DATA_OFFSET), + R8, ); memory::call(code, scratch.request); failures.push(memory::branch_failed(code)); - stack_immediate(code, ADD_RSP_DISP32_IMM32, scratch.address, width); + code.asm() + .alu_imm32(Alu::Add, Size::Qword, stack(scratch.address), width as i32); } - let active_done = branch(code, JMP_REL32); - let inactive_start = code.len(); - memory::patch_branch(code, inactive, inactive_start); - stack_immediate( - code, - ADD_RSP_DISP32_IMM32, - scratch.address, - u32::from(operand.registers) * width, + let mut asm = code.asm(); + let active_done = asm.jmp(); + asm.bind(inactive); + asm.alu_imm32( + Alu::Add, + Size::Qword, + stack(scratch.address), + (u32::from(operand.registers) * width) as i32, ); - let advance = code.len(); - memory::patch_branch(code, active_done, advance); - stack_operand(code, SHR_RSP_DISP32_IMM8, scratch.predicate); - code.push(width as u8); - stack_immediate(code, ADD_RSP_DISP32_IMM32, scratch.lane, width); + asm.bind(active_done); + asm.shift_imm( + ShiftOp::Shr, + Size::Qword, + stack(scratch.predicate), + width as u8, + ); + asm.alu_imm32(Alu::Add, Size::Qword, stack(scratch.lane), width as i32); let end = ((chunk + 1) * PREDICATE_CHUNK_BITS).min(length.bytes()) as u32; - stack_immediate(code, CMP_RSP_DISP32_IMM32, scratch.lane, end); - let repeat = branch(code, JB_REL32); - memory::patch_branch(code, repeat, start); + asm.alu_imm32(Alu::Cmp, Size::Qword, stack(scratch.lane), end as i32); + let repeat = asm.jcc(Cond::B); + resolve(code, repeat, start); } // Architectural Z writes begin only after all callbacks have succeeded. for tuple_index in 0..operand.registers { @@ -231,13 +213,13 @@ pub(crate) fn emit( ); } } - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); let cleanup = code.len(); for failure in failures { memory::patch_branch(code, failure, cleanup); } - code.extend(ADD_RSP_IMM32); - code.extend(scratch.bytes.to_le_bytes()); + code.asm() + .alu_imm32(Alu::Add, Size::Qword, Rsp, scratch.bytes as i32); transfer::return_if_failed(code); } @@ -245,11 +227,12 @@ pub(crate) fn emit( mod tests { use super::*; use crate::aarch64::{scalable::ElementSize, sve::memory_structure}; - use alloc::vec::Vec; const LENGTHS: [usize; 5] = [16, 32, 64, 128, 256]; const TEST_PC: u64 = 0x1_4000_1000; const MAX_REFERENCE_BODY_BYTES: usize = 8 * 1024; + const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; + const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; const CALL_MEMORY_CALLBACK: &[u8] = &[ 0xff, 0x57, @@ -332,7 +315,7 @@ mod tests { assert_eq!(operand.element, ElementSize::Byte); for bytes in LENGTHS { let length = VectorLength::from_bytes(bytes).unwrap(); - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, &operand, length, TargetCpu::Baseline, TEST_PC); let calls = code .windows(CALL_MEMORY_CALLBACK.len()) diff --git a/crates/stela-compiler/src/x86_64/sve/predicate.rs b/crates/stela-compiler/src/x86_64/sve/predicate.rs index 666b2e4556..ea4d6c47f0 100644 --- a/crates/stela-compiler/src/x86_64/sve/predicate.rs +++ b/crates/stela-compiler/src/x86_64/sve/predicate.rs @@ -1,5 +1,4 @@ //! Packed predicate helpers. -use alloc::vec::Vec; mod counter; mod counter_mask; mod flags; @@ -9,16 +8,3 @@ pub(crate) use counter_mask::emit_prepared_counter_mask; pub(crate) use flags::{accumulate_predtest, begin_predtest, finish_predtest, leading_bits}; const CHUNK_BITS: usize = 64; -const REL32_BYTES: usize = 4; - -fn jump(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend([0; REL32_BYTES]); - displacement -} - -fn bind(code: &mut [u8], displacement: usize) { - let relative = i32::try_from(code.len() - displacement - REL32_BYTES).unwrap(); - code[displacement..displacement + REL32_BYTES].copy_from_slice(&relative.to_le_bytes()); -} diff --git a/crates/stela-compiler/src/x86_64/sve/predicate/counter.rs b/crates/stela-compiler/src/x86_64/sve/predicate/counter.rs index 28b8e08d12..66151bc73f 100644 --- a/crates/stela-compiler/src/x86_64/sve/predicate/counter.rs +++ b/crates/stela-compiler/src/x86_64/sve/predicate/counter.rs @@ -1,49 +1,16 @@ //! Expanding predicate-as-counter registers into packed predicate chunks. -use super::{CHUNK_BITS, bind, jump}; +use super::CHUNK_BITS; use crate::aarch64::scalable::VectorLength; -use alloc::vec::Vec; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, ShiftOp, Size, Unary}; -const XOR_R9D_R9D: &[u8] = &[0x45, 0x31, 0xc9]; -const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; const COUNTER_FORMAT_MASK: u8 = 15; const COUNTER_INVERT_BIT: u8 = 15; const ALL_LEADING_BITS: u64 = u64::MAX; const HALFWORD_LEADING_BITS: u64 = 0x5555_5555_5555_5555; const WORD_LEADING_BITS: u64 = 0x1111_1111_1111_1111; const DOUBLEWORD_LEADING_BITS: u64 = 0x0101_0101_0101_0101; -const MOVZX_R8D_AX: &[u8] = &[0x44, 0x0f, 0xb7, 0xc0]; -const MOV_ECX_R8D: &[u8] = &[0x44, 0x89, 0xc1]; -const AND_ECX_IMM8: &[u8] = &[0x83, 0xe1]; -const BSF_ECX_ECX: &[u8] = &[0x0f, 0xbc, 0xc9]; -const MOV_EDX_ONE: &[u8] = &[0xba, 1, 0, 0, 0]; -const SHL_EDX_CL: &[u8] = &[0xd3, 0xe2]; -const MOV_R9D_R8D: &[u8] = &[0x45, 0x89, 0xc1]; -const AND_R9D_IMM32: &[u8] = &[0x41, 0x81, 0xe1]; -const SHR_R9D_ONE: &[u8] = &[0x41, 0xd1, 0xe9]; -const NEG_EDX: &[u8] = &[0xf7, 0xda]; -const AND_R9D_EDX: &[u8] = &[0x41, 0x21, 0xd1]; -const MOVABS_R10: &[u8] = &[0x49, 0xba]; -const MOVABS_R11: &[u8] = &[0x49, 0xbb]; -const CMP_CL_IMM8: &[u8] = &[0x80, 0xf9]; -const CMOVAE_R10_R11: &[u8] = &[0x4d, 0x0f, 0x43, 0xd3]; -const MOV_EAX_R9D: &[u8] = &[0x44, 0x89, 0xc8]; -const SUB_EAX_IMM32: &[u8] = &[0x2d]; -const CMP_EAX_CHUNK_BITS: &[u8] = &[0x83, 0xf8, CHUNK_BITS as u8]; -const TEST_EAX_EAX: &[u8] = &[0x85, 0xc0]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const MOV_EAX_ONE: &[u8] = &[0xb8, 1, 0, 0, 0]; -const SHL_RAX_CL: &[u8] = &[0x48, 0xd3, 0xe0]; -const DEC_RAX: &[u8] = &[0x48, 0xff, 0xc8]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const MOV_RAX_ALL_BITS: &[u8] = &[0x48, 0xc7, 0xc0, 0xff, 0xff, 0xff, 0xff]; -const BT_R8D_IMM8: &[u8] = &[0x41, 0x0f, 0xba, 0xe0]; -const SBB_R11_R11: &[u8] = &[0x4d, 0x19, 0xdb]; -const XOR_RAX_R11: &[u8] = &[0x4c, 0x31, 0xd8]; -const AND_RAX_R10: &[u8] = &[0x4c, 0x21, 0xd0]; -const JZ: &[u8] = &[0x0f, 0x84]; -const JGE: &[u8] = &[0x0f, 0x8d]; -const JLE: &[u8] = &[0x0f, 0x8e]; -const JMP: &[u8] = &[0xe9]; /// Input RAX is the compressed low16 counter. Output RAX is one64-bit chunk of /// its PL*4-bit expansion, where PL is the vector length in bytes. Other high @@ -51,7 +18,7 @@ const JMP: &[u8] = &[0xe9]; /// The instruction's own element size is deliberately absent: a consumer samples /// this mask using its independent stride, including mismatched counter sizes. /// This baseline mapping uses no optional host capability or guest RAM access. -pub(crate) fn emit_counter_chunk(code: &mut Vec, chunk: usize, length: VectorLength) { +pub(crate) fn emit_counter_chunk(code: &mut Code, chunk: usize, length: VectorLength) { prepare_counter(code, length); emit_prepared_counter_chunk(code, chunk, length); } @@ -60,87 +27,90 @@ pub(crate) fn emit_counter_chunk(code: &mut Vec, chunk: usize, length: Vecto /// low16 input, R9 the exclusive active-bit boundary, R10 the leading-bit pattern. /// Zero format initializes a zero pattern regardless of the inversion bit. /// Clobbers RAX/RCX/RDX/R8..R11; preserves RDI/R15 and all XMMs. -pub(crate) fn prepare_counter(code: &mut Vec, length: VectorLength) { +pub(crate) fn prepare_counter(code: &mut Code, length: VectorLength) { let expanded_bits = length.bytes() * 4; let counter_bits = expanded_bits.ilog2() + 1; let count_mask = (1u32 << counter_bits) - 1; - code.extend(MOVZX_R8D_AX); - code.extend(MOV_ECX_R8D); - code.extend(AND_ECX_IMM8); - code.push(COUNTER_FORMAT_MASK); - let empty_format = jump(code, JZ); - code.extend(BSF_ECX_ECX); - code.extend(MOV_EDX_ONE); - code.extend(SHL_EDX_CL); - code.extend(MOV_R9D_R8D); - code.extend(AND_R9D_IMM32); - code.extend(count_mask.to_le_bytes()); - code.extend(SHR_R9D_ONE); - code.extend(NEG_EDX); - code.extend(AND_R9D_EDX); - code.extend(MOVABS_R10); - code.extend(ALL_LEADING_BITS.to_le_bytes()); + let mut asm = code.asm(); + asm.movzx(Size::Dword, R8, Size::Word, Rax); + asm.mov(Size::Dword, Rcx, R8); + asm.alu_imm8(Alu::And, Size::Dword, Rcx, COUNTER_FORMAT_MASK as i8); + let empty_format = code.asm().jcc(Cond::E); + let mut asm = code.asm(); + asm.bsf(Size::Dword, Rcx, Rcx); + asm.mov_imm32(Rdx, 1); + asm.shift_cl(ShiftOp::Shl, Size::Dword, Rdx); + asm.mov(Size::Dword, R9, R8); + asm.alu_imm32(Alu::And, Size::Dword, R9, count_mask as i32); + asm.shift_one(ShiftOp::Shr, Size::Dword, R9); + asm.unary(Unary::Neg, Size::Dword, Rdx); + asm.alu(Alu::And, Size::Dword, R9, Rdx); + asm.mov_imm64(R10, ALL_LEADING_BITS); for (minimum_size, mask) in [ (1, HALFWORD_LEADING_BITS), (2, WORD_LEADING_BITS), (3, DOUBLEWORD_LEADING_BITS), ] { - code.extend(MOVABS_R11); - code.extend(mask.to_le_bytes()); - code.extend(CMP_CL_IMM8); - code.push(minimum_size); - code.extend(CMOVAE_R10_R11); + let mut asm = code.asm(); + asm.mov_imm64(R11, mask); + asm.alu_byte_imm(Alu::Cmp, Rcx, minimum_size); + asm.cmov(Cond::Ae, Size::Qword, R10, R11); } - let ready = jump(code, JMP); - bind(code, empty_format); - code.extend(XOR_R9D_R9D); - code.extend(XOR_R10D_R10D); - bind(code, ready); + let ready = code.asm().jmp(); + code.asm().bind(empty_format); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, R9, R9); + asm.alu(Alu::Xor, Size::Dword, R10, R10); + code.asm().bind(ready); } /// Produce a chunk from prepare_counter state without changing R8/R9/R10. /// Clobbers RAX/RCX/R11 and host flags; preserves RDX/RDI/R15 and XMMs. -pub(crate) fn emit_prepared_counter_chunk(code: &mut Vec, chunk: usize, length: VectorLength) { +pub(crate) fn emit_prepared_counter_chunk(code: &mut Code, chunk: usize, length: VectorLength) { assert!(chunk < length.bytes() * 4 / CHUNK_BITS); - code.extend(MOV_EAX_R9D); + code.asm().mov(Size::Dword, Rax, R9); if chunk != 0 { - code.extend(SUB_EAX_IMM32); - code.extend(((chunk * CHUNK_BITS) as u32).to_le_bytes()); + code.asm() + .alu_accumulator_imm32(Alu::Sub, Size::Dword, (chunk * CHUNK_BITS) as i32); } - code.extend(CMP_EAX_CHUNK_BITS); - let full_chunk = jump(code, JGE); - code.extend(TEST_EAX_EAX); - let empty_chunk = jump(code, JLE); - code.extend(MOV_ECX_EAX); - code.extend(MOV_EAX_ONE); - code.extend(SHL_RAX_CL); - code.extend(DEC_RAX); - let partial_ready = jump(code, JMP); - bind(code, empty_chunk); - code.extend(XOR_EAX_EAX); - let empty_ready = jump(code, JMP); - bind(code, full_chunk); - code.extend(MOV_RAX_ALL_BITS); - bind(code, partial_ready); - bind(code, empty_ready); - code.extend(BT_R8D_IMM8); - code.push(COUNTER_INVERT_BIT); - code.extend(SBB_R11_R11); - code.extend(XOR_RAX_R11); - code.extend(AND_RAX_R10); + code.asm() + .alu_imm8(Alu::Cmp, Size::Dword, Rax, CHUNK_BITS as i8); + let full_chunk = code.asm().jcc(Cond::Ge); + code.asm().test(Size::Dword, Rax, Rax); + let empty_chunk = code.asm().jcc(Cond::Le); + let mut asm = code.asm(); + asm.mov(Size::Dword, Rcx, Rax); + asm.mov_imm32(Rax, 1); + asm.shift_cl(ShiftOp::Shl, Size::Qword, Rax); + asm.dec(Size::Qword, Rax); + let partial_ready = code.asm().jmp(); + code.asm().bind(empty_chunk); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); + let empty_ready = code.asm().jmp(); + code.asm().bind(full_chunk); + code.asm().mov_rm_imm32(Size::Qword, Rax, -1); + code.asm().bind(partial_ready); + code.asm().bind(empty_ready); + let mut asm = code.asm(); + asm.bit_imm(BitTest::Bt, Size::Dword, R8, COUNTER_INVERT_BIT); + asm.alu(Alu::Sbb, Size::Qword, R11, R11); + asm.alu(Alu::Xor, Size::Qword, Rax, R11); + asm.alu(Alu::And, Size::Qword, Rax, R10); } #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; + + const MOVZX_R8D_AX: &[u8] = &[0x44, 0x0f, 0xb7, 0xc0]; + const AND_RAX_R10: &[u8] = &[0x4c, 0x21, 0xd0]; #[test] fn every_streaming_length_emits_bounded_chunks_without_optional_instructions() { for bytes in [16, 32, 64, 128, 256] { let length = VectorLength::from_bytes(bytes).unwrap(); for chunk in 0..bytes * 4 / CHUNK_BITS { - let mut code = Vec::new(); + let mut code = Code::new(); emit_counter_chunk(&mut code, chunk, length); assert!(code.starts_with(MOVZX_R8D_AX)); assert!(code.ends_with(AND_RAX_R10)); diff --git a/crates/stela-compiler/src/x86_64/sve/predicate/counter_mask.rs b/crates/stela-compiler/src/x86_64/sve/predicate/counter_mask.rs index 80540f0699..b2dd74ec07 100644 --- a/crates/stela-compiler/src/x86_64/sve/predicate/counter_mask.rs +++ b/crates/stela-compiler/src/x86_64/sve/predicate/counter_mask.rs @@ -1,16 +1,16 @@ //! Vector expansion of predicate-as-counter masks. use super::{CHUNK_BITS, emit_prepared_counter_chunk}; use crate::aarch64::scalable::VectorLength; -use alloc::vec::Vec; +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Code, ShiftOp, Size}; -const SHR_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe8]; const VECTOR_MASK_BYTES: usize = 16; /// Expand one16-byte counter segment from prepare_counter state. Preserves /// R8/R9/R10/RDX/RDI/R15 and other XMMs; clobbers RAX/RCX/R11 and both mask XMMs. #[allow(clippy::too_many_arguments)] pub(crate) fn emit_prepared_counter_mask( - code: &mut Vec, + code: &mut Code, group: usize, chunk: usize, element: crate::aarch64::scalable::ElementSize, @@ -24,8 +24,8 @@ pub(crate) fn emit_prepared_counter_mask( emit_prepared_counter_chunk(code, bit_offset / CHUNK_BITS, length); let shift = bit_offset % CHUNK_BITS; if shift != 0 { - code.extend(SHR_RAX_IMM8); - code.push(shift as u8); + code.asm() + .shift_imm(ShiftOp::Shr, Size::Qword, Rax, shift as u8); } crate::x86_64::scalable::expand_predicate_mask(code, element, destination, scratch, target); } diff --git a/crates/stela-compiler/src/x86_64/sve/predicate/flags.rs b/crates/stela-compiler/src/x86_64/sve/predicate/flags.rs index 62278ac898..7226cdb26e 100644 --- a/crates/stela-compiler/src/x86_64/sve/predicate/flags.rs +++ b/crates/stela-compiler/src/x86_64/sve/predicate/flags.rs @@ -1,37 +1,10 @@ //! Incremental NZCV for predicate-setting instructions (PTEST semantics). +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdi, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, ShiftOp, Size}; -use super::{CHUNK_BITS, bind, jump}; -use alloc::vec::Vec; +use super::CHUNK_BITS; -const JZ: &[u8] = &[0x0f, 0x84]; -const MOV_R8D_IMM32: &[u8] = &[0x41, 0xb8]; -const XOR_R9D_R9D: &[u8] = &[0x45, 0x31, 0xc9]; -const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; -const MOV_RDX_R11: &[u8] = &[0x4c, 0x89, 0xda]; -const MOVABS_RCX: &[u8] = &[0x48, 0xb9]; -const AND_RDX_RCX: &[u8] = &[0x48, 0x21, 0xca]; -const TEST_RDX_RDX: &[u8] = &[0x48, 0x85, 0xd2]; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const AND_RCX_RDX: &[u8] = &[0x48, 0x21, 0xd1]; -const OR_R9_RCX: &[u8] = &[0x49, 0x09, 0xc9]; -const TEST_R10D_R10D: &[u8] = &[0x45, 0x85, 0xd2]; -const JNZ: &[u8] = &[0x0f, 0x85]; -const BSF_RCX_RDX: &[u8] = &[0x48, 0x0f, 0xbc, 0xca]; -const BSR_RCX_RDX: &[u8] = &[0x48, 0x0f, 0xbd, 0xca]; -const BT_RAX_RCX: &[u8] = &[0x48, 0x0f, 0xa3, 0xc8]; -const SETC_CL: &[u8] = &[0x0f, 0x92, 0xc1]; -const SETNC_CL: &[u8] = &[0x0f, 0x93, 0xc1]; -const MOVZX_ECX_CL: &[u8] = &[0x0f, 0xb6, 0xc9]; -const SHL_ECX_IMM8: &[u8] = &[0xc1, 0xe1]; -const OR_R8D_ECX: &[u8] = &[0x41, 0x09, 0xc8]; -const AND_R8D_IMM32: &[u8] = &[0x41, 0x81, 0xe0]; -const MOV_R10D_ONE: &[u8] = &[0x41, 0xba, 1, 0, 0, 0]; -const TEST_R9_R9: &[u8] = &[0x4d, 0x85, 0xc9]; -const SETZ_AL: &[u8] = &[0x0f, 0x94, 0xc0]; -const MOVZX_EAX_AL: &[u8] = &[0x0f, 0xb6, 0xc0]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const OR_EAX_R8D: &[u8] = &[0x44, 0x09, 0xc0]; -const MOV_STATE_DISP32_EAX: &[u8] = &[0x89, 0x87]; const NZCV_N_SHIFT: u8 = 31; const NZCV_Z_SHIFT: u8 = 30; const NZCV_C_SHIFT: u8 = 29; @@ -42,58 +15,58 @@ pub(crate) fn leading_bits(element: crate::aarch64::scalable::ElementSize) -> u6 .fold(0, |mask, bit| mask | (1 << bit)) } -pub(crate) fn begin_predtest(code: &mut Vec) { - code.extend(MOV_R8D_IMM32); - code.extend((1u32 << NZCV_C_SHIFT).to_le_bytes()); - code.extend(XOR_R9D_R9D); - code.extend(XOR_R10D_R10D); +pub(crate) fn begin_predtest(code: &mut Code) { + let mut asm = code.asm(); + asm.mov_imm32(R8, 1u32 << NZCV_C_SHIFT); + asm.alu(Alu::Xor, Size::Dword, R9, R9); + asm.alu(Alu::Xor, Size::Dword, R10, R10); } -pub(crate) fn accumulate_predtest( - code: &mut Vec, - element: crate::aarch64::scalable::ElementSize, -) { - code.extend(MOV_RDX_R11); +pub(crate) fn accumulate_predtest(code: &mut Code, element: crate::aarch64::scalable::ElementSize) { + code.asm().mov(Size::Qword, Rdx, R11); if element != crate::aarch64::scalable::ElementSize::Byte { - code.extend(MOVABS_RCX); - code.extend(leading_bits(element).to_le_bytes()); - code.extend(AND_RDX_RCX); + let mut asm = code.asm(); + asm.mov_imm64(Rcx, leading_bits(element)); + asm.alu(Alu::And, Size::Qword, Rdx, Rcx); } - code.extend(TEST_RDX_RDX); - let empty = jump(code, JZ); - code.extend(MOV_RCX_RAX); - code.extend(AND_RCX_RDX); - code.extend(OR_R9_RCX); - code.extend(TEST_R10D_R10D); - let seen = jump(code, JNZ); - code.extend(BSF_RCX_RDX); - code.extend(BT_RAX_RCX); - code.extend(SETC_CL); - code.extend(MOVZX_ECX_CL); - code.extend(SHL_ECX_IMM8); - code.push(NZCV_N_SHIFT); - code.extend(OR_R8D_ECX); - bind(code, seen); - code.extend(BSR_RCX_RDX); - code.extend(BT_RAX_RCX); - code.extend(SETNC_CL); - code.extend(MOVZX_ECX_CL); - code.extend(SHL_ECX_IMM8); - code.push(NZCV_C_SHIFT); - code.extend(AND_R8D_IMM32); - code.extend((!(1u32 << NZCV_C_SHIFT)).to_le_bytes()); - code.extend(OR_R8D_ECX); - code.extend(MOV_R10D_ONE); - bind(code, empty); + code.asm().test(Size::Qword, Rdx, Rdx); + let empty = code.asm().jcc(Cond::E); + let mut asm = code.asm(); + asm.mov(Size::Qword, Rcx, Rax); + asm.alu(Alu::And, Size::Qword, Rcx, Rdx); + asm.alu(Alu::Or, Size::Qword, R9, Rcx); + asm.test(Size::Dword, R10, R10); + let seen = code.asm().jcc(Cond::Ne); + let mut asm = code.asm(); + asm.bsf(Size::Qword, Rcx, Rdx); + asm.bit(BitTest::Bt, Size::Qword, Rax, Rcx); + asm.setcc(Cond::B, Rcx); + asm.movzx(Size::Dword, Rcx, Size::Byte, Rcx); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rcx, NZCV_N_SHIFT); + asm.alu(Alu::Or, Size::Dword, R8, Rcx); + code.asm().bind(seen); + let mut asm = code.asm(); + asm.bsr(Size::Qword, Rcx, Rdx); + asm.bit(BitTest::Bt, Size::Qword, Rax, Rcx); + asm.setcc(Cond::Ae, Rcx); + asm.movzx(Size::Dword, Rcx, Size::Byte, Rcx); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rcx, NZCV_C_SHIFT); + asm.alu_imm32(Alu::And, Size::Dword, R8, (!(1u32 << NZCV_C_SHIFT)) as i32); + asm.alu(Alu::Or, Size::Dword, R8, Rcx); + asm.mov_imm32(R10, 1); + code.asm().bind(empty); } -pub(crate) fn finish_predtest(code: &mut Vec) { - code.extend(TEST_R9_R9); - code.extend(SETZ_AL); - code.extend(MOVZX_EAX_AL); - code.extend(SHL_EAX_IMM8); - code.push(NZCV_Z_SHIFT); - code.extend(OR_EAX_R8D); - code.extend(MOV_STATE_DISP32_EAX); - code.extend((core::mem::offset_of!(crate::GuestState, nzcv) as u32).to_le_bytes()); +pub(crate) fn finish_predtest(code: &mut Code) { + let mut asm = code.asm(); + asm.test(Size::Qword, R9, R9); + asm.setcc(Cond::E, Rax); + asm.movzx(Size::Dword, Rax, Size::Byte, Rax); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, NZCV_Z_SHIFT); + asm.alu(Alu::Or, Size::Dword, Rax, R8); + asm.mov_store( + Size::Dword, + Mem::base_disp32(Rdi, (core::mem::offset_of!(crate::GuestState, nzcv)) as i32), + Rax, + ); } diff --git a/crates/stela-compiler/src/x86_64/sve/predicate_generation.rs b/crates/stela-compiler/src/x86_64/sve/predicate_generation.rs index 7247f9d1f6..1a125a98a1 100644 --- a/crates/stela-compiler/src/x86_64/sve/predicate_generation.rs +++ b/crates/stela-compiler/src/x86_64/sve/predicate_generation.rs @@ -1,5 +1,7 @@ //! Predicate generation, using BMI1 when available. use super::predicate; +use crate::x86_64::asm::Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdi, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, ShiftOp, Size, Unary}; use crate::{ GuestState, TargetCpu, aarch64::{ @@ -12,81 +14,21 @@ use crate::{ scalable::{read_predicate_chunk, write_predicate_chunk, zero_predicate}, }, }; -use alloc::vec::Vec; const CHUNK_BITS: usize = u64::BITS as usize; const CHUNK_BYTES: usize = core::mem::size_of::(); -const REL32_BYTES: usize = core::mem::size_of::(); const NZCV_OFFSET: u32 = core::mem::offset_of!(GuestState, nzcv) as u32; const N_FLAG: u32 = 1 << 31; const Z_FLAG: u32 = 1 << 30; const C_FLAG: u32 = 1 << 29; const V_FLAG: u32 = 1 << 28; const COUNTER_INVERT_BIT: u64 = 1 << 15; -const MOV_EAX_IMM32: u8 = 0xb8; -const MOV_RAX_SIGN_EXTENDED_IMM32: &[u8] = &[0x48, 0xc7, 0xc0]; const PATTERN_POW2: u8 = 0; const PATTERN_MUL4: u8 = 29; const PATTERN_MUL3: u8 = 30; const PATTERN_ALL: u8 = 31; -const MOVABS_RAX: &[u8] = &[0x48, 0xb8]; -const MOVABS_R11: &[u8] = &[0x49, 0xbb]; -const MOV_R11_RAX: &[u8] = &[0x49, 0x89, 0xc3]; -const MOV_R9_R11: &[u8] = &[0x4d, 0x89, 0xd9]; -const BLSI_R9_R11: &[u8] = &[0xc4, 0xc2, 0xb0, 0xf3, 0xdb]; -const NEG_R9: &[u8] = &[0x49, 0xf7, 0xd9]; -const AND_R9_R11: &[u8] = &[0x4d, 0x21, 0xd9]; -const AND_R9_R10: &[u8] = &[0x4d, 0x21, 0xd1]; -const CMP_R11_ONE: &[u8] = &[0x49, 0x83, 0xfb, 1]; -const SBB_RCX_RCX: &[u8] = &[0x48, 0x19, 0xc9]; -const AND_R10_RCX: &[u8] = &[0x49, 0x21, 0xca]; -const OR_RAX_R9: &[u8] = &[0x4c, 0x09, 0xc8]; -const ALL_R10: &[u8] = &[0x49, 0xc7, 0xc2, 0xff, 0xff, 0xff, 0xff]; -const ALL_R9: &[u8] = &[0x49, 0xc7, 0xc1, 0xff, 0xff, 0xff, 0xff]; -const AND_RAX_R11: &[u8] = &[0x4c, 0x21, 0xd8]; -const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; -const TEST_RAX_RAX: &[u8] = &[0x48, 0x85, 0xc0]; -const BSR_RCX_RAX: &[u8] = &[0x48, 0x0f, 0xbd, 0xc8]; -const LEA_R10D_RCX_DISP32: &[u8] = &[0x44, 0x8d, 0x91]; -const CMP_R10D_IMM32: &[u8] = &[0x41, 0x81, 0xfa]; -const MOV_ECX_R10D: &[u8] = &[0x44, 0x89, 0xd1]; -const SUB_ECX_IMM32: &[u8] = &[0x81, 0xe9]; -const SHL_R11_CL: &[u8] = &[0x49, 0xd3, 0xe3]; -const NEG_R11: &[u8] = &[0x49, 0xf7, 0xdb]; -const AND_RAX_R9: &[u8] = &[0x4c, 0x21, 0xc8]; -const CMP_RAX_ONE: &[u8] = &[0x48, 0x83, 0xf8, 1]; -const AND_R9_RCX: &[u8] = &[0x49, 0x21, 0xc9]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const MOV_STATE_IMM32: &[u8] = &[0xc7, 0x87]; -const MOV_STATE_EAX: &[u8] = &[0x89, 0x87]; -const MOV_EDX_STATE: &[u8] = &[0x8b, 0x97]; -const CMP_RAX_RCX: &[u8] = &[0x48, 0x39, 0xc8]; -const CMP_EAX_ECX: &[u8] = &[0x39, 0xc8]; -const SETE_AL: &[u8] = &[0x0f, 0x94, 0xc0]; -const SETNE_AL: &[u8] = &[0x0f, 0x95, 0xc0]; -const MOVZX_EAX_AL: &[u8] = &[0x0f, 0xb6, 0xc0]; -const MOV_ECX_EAX: &[u8] = &[0x89, 0xc1]; -const XOR_ECX_ONE: &[u8] = &[0x83, 0xf1, 1]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const SHL_ECX_IMM8: &[u8] = &[0xc1, 0xe1]; -const AND_EDX_IMM32: &[u8] = &[0x81, 0xe2]; -const OR_EAX_EDX: &[u8] = &[0x09, 0xd0]; -const MOV_R11D_EDX: &[u8] = &[0x41, 0x89, 0xd3]; -const SHR_R11D_IMM8: &[u8] = &[0x41, 0xc1, 0xeb]; -const XOR_R11D_ONE: &[u8] = &[0x41, 0x83, 0xf3, 1]; -const AND_ECX_R11D: &[u8] = &[0x44, 0x21, 0xd9]; -const OR_EAX_ECX: &[u8] = &[0x09, 0xc8]; -const MOVQ_XMM_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e]; -const MOVQ_RAX_XMM: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const MODRM_REGISTER: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const AND_R11D_ONE: &[u8] = &[0x41, 0x83, 0xe3, 1]; -const JZ: &[u8] = &[0x0f, 0x84]; -const JBE: &[u8] = &[0x0f, 0x86]; -const JAE: &[u8] = &[0x0f, 0x83]; -const JMP: &[u8] = &[0xe9]; -pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu) { match operand { Operand::Basic(basic) => emit_basic(code, basic, length, target), Operand::Break(operand) => breaks::emit_break(code, *operand, length, target), @@ -97,54 +39,39 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, fn chunks(length: VectorLength) -> usize { length.predicate_bytes().div_ceil(CHUNK_BYTES) } -fn constant(code: &mut Vec, value: u64) { +fn constant(code: &mut Code, value: u64) { if value == 0 { - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); } else if let Ok(value) = u32::try_from(value) { - code.push(MOV_EAX_IMM32); - code.extend(value.to_le_bytes()); + code.asm().mov_imm32(Rax, value); } else if let Ok(value) = i32::try_from(value as i64) { - code.extend(MOV_RAX_SIGN_EXTENDED_IMM32); - code.extend(value.to_le_bytes()); + code.asm().mov_rm_imm32(Size::Qword, Rax, value); } else { - code.extend(MOVABS_RAX); - code.extend(value.to_le_bytes()); + code.asm().mov_imm64(Rax, value); } } fn marker_mask(element: ElementSize) -> u64 { predicate::leading_bits(element) } -fn stage(code: &mut Vec, xmm: u8) { +fn stage(code: &mut Code, xmm: u8) { assert!(xmm < 8); - code.extend(MOVQ_XMM_RAX); - code.push(MODRM_REGISTER | xmm << MODRM_REGISTER_SHIFT); + code.asm().movq_to_xmm(xmm, Rax); } -fn restore(code: &mut Vec, xmm: u8) { +fn restore(code: &mut Code, xmm: u8) { assert!(xmm < 8); - code.extend(MOVQ_RAX_XMM); - code.push(MODRM_REGISTER | xmm << MODRM_REGISTER_SHIFT); + code.asm().movq_from_xmm(Rax, xmm); } -fn restore_guard(code: &mut Vec, xmm: u8) { +fn restore_guard(code: &mut Code, xmm: u8) { restore(code, xmm); - code.extend(MOV_R11_RAX); + code.asm().mov(Size::Qword, R11, Rax); } -fn jump(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let at = code.len(); - code.extend([0; REL32_BYTES]); - at -} -fn bind(code: &mut [u8], at: usize) { - let displacement = i32::try_from(code.len() - at - REL32_BYTES).unwrap(); - code[at..at + REL32_BYTES].copy_from_slice(&displacement.to_le_bytes()); -} -fn commit_staged(code: &mut Vec, destination: u8, length: VectorLength) { +fn commit_staged(code: &mut Code, destination: u8, length: VectorLength) { for chunk in 0..chunks(length) { restore(code, chunk as u8); write_predicate_chunk(code, destination, chunk, length); } } -fn test_staged(code: &mut Vec, element: ElementSize, length: VectorLength) { +fn test_staged(code: &mut Code, element: ElementSize, length: VectorLength) { predicate::begin_predtest(code); for chunk in 0..chunks(length) { restore_guard(code, 4 + chunk as u8); @@ -153,10 +80,12 @@ fn test_staged(code: &mut Vec, element: ElementSize, length: VectorLength) { } predicate::finish_predtest(code); } -fn immediate_flags(code: &mut Vec, flags: u32) { - code.extend(MOV_STATE_IMM32); - code.extend(NZCV_OFFSET.to_le_bytes()); - code.extend(flags.to_le_bytes()); +fn immediate_flags(code: &mut Code, flags: u32) { + code.asm().mov_rm_imm32( + Size::Dword, + Mem::base_disp32(Rdi, NZCV_OFFSET as i32), + flags as i32, + ); } fn pattern_count(pattern: u8, elements: usize) -> usize { let count = match pattern { @@ -170,7 +99,7 @@ fn pattern_count(pattern: u8, elements: usize) -> usize { }; if count <= elements { count } else { 0 } } -fn emit_basic(code: &mut Vec, operand: &BasicOperand, length: VectorLength, target: TargetCpu) { +fn emit_basic(code: &mut Code, operand: &BasicOperand, length: VectorLength, target: TargetCpu) { match *operand { BasicOperand::False { destination } => zero_predicate(code, destination, length), BasicOperand::True { @@ -206,7 +135,7 @@ fn emit_basic(code: &mut Vec, operand: &BasicOperand, length: VectorLength, predicate::begin_predtest(code); for chunk in 0..chunks(length) { read_predicate_chunk(code, governing, chunk, length); - code.extend(MOV_R11_RAX); + code.asm().mov(Size::Qword, R11, Rax); read_predicate_chunk(code, source, chunk, length); predicate::accumulate_predtest(code, ElementSize::Byte); } @@ -230,148 +159,144 @@ fn emit_basic(code: &mut Vec, operand: &BasicOperand, length: VectorLength, } } fn emit_first( - code: &mut Vec, + code: &mut Code, destination: u8, governing: u8, length: VectorLength, target: TargetCpu, ) { - code.extend(ALL_R10); + code.asm().mov_rm_imm32(Size::Qword, R10, -1); for chunk in 0..chunks(length) { read_predicate_chunk(code, governing, chunk, length); stage(code, 4 + chunk as u8); - code.extend(MOV_R11_RAX); + code.asm().mov(Size::Qword, R11, Rax); // Shorter profiles retain the baseline recipe: some measured short // cohorts regressed with BMI1, while the maximum profile improved. if target.supports(TargetCpu::Bmi1) && length.bytes() == MAX_VECTOR_BYTES { - code.extend(BLSI_R9_R11); + code.asm().blsi(Size::Qword, R9, R11); } else { - code.extend(MOV_R9_R11); - code.extend(NEG_R9); - code.extend(AND_R9_R11); + let mut asm = code.asm(); + asm.mov(Size::Qword, R9, R11); + asm.unary(Unary::Neg, Size::Qword, R9); + asm.alu(Alu::And, Size::Qword, R9, R11); } - code.extend(AND_R9_R10); - code.extend(CMP_R11_ONE); - code.extend(SBB_RCX_RCX); - code.extend(AND_R10_RCX); + let mut asm = code.asm(); + asm.alu(Alu::And, Size::Qword, R9, R10); + asm.alu_imm8(Alu::Cmp, Size::Qword, R11, 1); + asm.alu(Alu::Sbb, Size::Qword, Rcx, Rcx); + asm.alu(Alu::And, Size::Qword, R10, Rcx); read_predicate_chunk(code, destination, chunk, length); - code.extend(OR_RAX_R9); + code.asm().alu(Alu::Or, Size::Qword, Rax, R9); stage(code, chunk as u8); } commit_staged(code, destination, length); test_staged(code, ElementSize::Byte, length); } fn emit_next( - code: &mut Vec, + code: &mut Code, destination: u8, governing: u8, element: ElementSize, length: VectorLength, ) { - code.extend(XOR_R10D_R10D); + code.asm().alu(Alu::Xor, Size::Dword, R10, R10); for chunk in 0..chunks(length) { read_predicate_chunk(code, governing, chunk, length); stage(code, 4 + chunk as u8); read_predicate_chunk(code, destination, chunk, length); - code.extend(MOVABS_R11); - code.extend(marker_mask(element).to_le_bytes()); - code.extend(AND_RAX_R11); - code.extend(TEST_RAX_RAX); - let empty = jump(code, JZ); - code.extend(BSR_RCX_RAX); - code.extend(LEA_R10D_RCX_DISP32); - code.extend(((chunk * CHUNK_BITS + element.bytes()) as u32).to_le_bytes()); - bind(code, empty); + let mut asm = code.asm(); + asm.mov_imm64(R11, marker_mask(element)); + asm.alu(Alu::And, Size::Qword, Rax, R11); + asm.test(Size::Qword, Rax, Rax); + let empty = asm.jcc(Cond::E); + asm.bsr(Size::Qword, Rcx, Rax); + asm.lea( + Size::Dword, + R10, + Mem::base_disp32(Rcx, (chunk * CHUNK_BITS + element.bytes()) as i32), + ); + asm.bind(empty); } - code.extend(ALL_R9); + code.asm().mov_rm_imm32(Size::Qword, R9, -1); for chunk in 0..chunks(length) { restore(code, 4 + chunk as u8); - code.extend(MOVABS_R11); - code.extend(marker_mask(element).to_le_bytes()); - code.extend(AND_RAX_R11); - code.extend(CMP_R10D_IMM32); - code.extend(((chunk * CHUNK_BITS) as u32).to_le_bytes()); - let keep = jump(code, JBE); - code.extend(CMP_R10D_IMM32); - code.extend((((chunk + 1) * CHUNK_BITS) as u32).to_le_bytes()); - let empty = jump(code, JAE); - code.extend(MOV_ECX_R10D); - code.extend(SUB_ECX_IMM32); - code.extend(((chunk * CHUNK_BITS) as u32).to_le_bytes()); - code.extend(MOVABS_R11); - code.extend(u64::MAX.to_le_bytes()); - code.extend(SHL_R11_CL); - code.extend(AND_RAX_R11); - bind(code, keep); - code.extend(MOV_R11_RAX); - code.extend(NEG_R11); - code.extend(AND_RAX_R11); - code.extend(AND_RAX_R9); - code.extend(CMP_RAX_ONE); - code.extend(SBB_RCX_RCX); - code.extend(AND_R9_RCX); - let ready = jump(code, JMP); - bind(code, empty); - code.extend(XOR_EAX_EAX); - bind(code, ready); + let mut asm = code.asm(); + asm.mov_imm64(R11, marker_mask(element)); + asm.alu(Alu::And, Size::Qword, Rax, R11); + asm.alu_imm32(Alu::Cmp, Size::Dword, R10, (chunk * CHUNK_BITS) as i32); + let keep = asm.jcc(Cond::Be); + asm.alu_imm32( + Alu::Cmp, + Size::Dword, + R10, + ((chunk + 1) * CHUNK_BITS) as i32, + ); + let empty = asm.jcc(Cond::Ae); + asm.mov(Size::Dword, Rcx, R10); + asm.alu_imm32(Alu::Sub, Size::Dword, Rcx, (chunk * CHUNK_BITS) as i32); + asm.mov_imm64(R11, u64::MAX); + asm.shift_cl(ShiftOp::Shl, Size::Qword, R11); + asm.alu(Alu::And, Size::Qword, Rax, R11); + asm.bind(keep); + asm.mov(Size::Qword, R11, Rax); + asm.unary(Unary::Neg, Size::Qword, R11); + asm.alu(Alu::And, Size::Qword, Rax, R11); + asm.alu(Alu::And, Size::Qword, Rax, R9); + asm.alu_imm8(Alu::Cmp, Size::Qword, Rax, 1); + asm.alu(Alu::Sbb, Size::Qword, Rcx, Rcx); + asm.alu(Alu::And, Size::Qword, R9, Rcx); + let ready = asm.jmp(); + asm.bind(empty); + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); + asm.bind(ready); stage(code, chunk as u8); } commit_staged(code, destination, length); test_staged(code, element, length); } -fn emit_terminate( - code: &mut Vec, - first: Register, - second: Register, - width: Width, - equal: bool, -) { +fn emit_terminate(code: &mut Code, first: Register, second: Register, width: Width, equal: bool) { load(code, first); right_operand(code, second, width, Shift::Lsl, 0); - code.extend(if width == Width::X64 { - CMP_RAX_RCX - } else { - CMP_EAX_ECX - }); - code.extend(if equal { SETE_AL } else { SETNE_AL }); - code.extend(MOVZX_EAX_AL); - code.extend(MOV_ECX_EAX); - code.extend(XOR_ECX_ONE); - code.extend(SHL_EAX_IMM8); - code.push(N_FLAG.trailing_zeros() as u8); - code.extend(MOV_EDX_STATE); - code.extend(NZCV_OFFSET.to_le_bytes()); - code.extend(AND_EDX_IMM32); - code.extend((Z_FLAG | C_FLAG).to_le_bytes()); - code.extend(OR_EAX_EDX); - code.extend(MOV_R11D_EDX); - code.extend(SHR_R11D_IMM8); - code.push(C_FLAG.trailing_zeros() as u8); + let mut asm = code.asm(); + asm.alu(Alu::Cmp, Size::of(width == Width::X64), Rax, Rcx); + asm.setcc(if equal { Cond::E } else { Cond::Ne }, Rax); + asm.movzx(Size::Dword, Rax, Size::Byte, Rax); + asm.mov(Size::Dword, Rcx, Rax); + asm.alu_imm8(Alu::Xor, Size::Dword, Rcx, 1); + asm.shift_imm( + ShiftOp::Shl, + Size::Dword, + Rax, + N_FLAG.trailing_zeros() as u8, + ); + asm.mov_load(Size::Dword, Rdx, Mem::base_disp32(Rdi, NZCV_OFFSET as i32)); + asm.alu_imm32(Alu::And, Size::Dword, Rdx, (Z_FLAG | C_FLAG) as i32); + asm.alu(Alu::Or, Size::Dword, Rax, Rdx); + asm.mov(Size::Dword, R11, Rdx); + asm.shift_imm( + ShiftOp::Shr, + Size::Dword, + R11, + C_FLAG.trailing_zeros() as u8, + ); // Z survives independently; isolate C before forming !C. - code.extend(AND_R11D_ONE); - code.extend(XOR_R11D_ONE); - code.extend(AND_ECX_R11D); - code.extend(SHL_ECX_IMM8); - code.push(V_FLAG.trailing_zeros() as u8); - code.extend(OR_EAX_ECX); - code.extend(MOV_STATE_EAX); - code.extend(NZCV_OFFSET.to_le_bytes()); + asm.alu_imm8(Alu::And, Size::Dword, R11, 1); + asm.alu_imm8(Alu::Xor, Size::Dword, R11, 1); + asm.alu(Alu::And, Size::Dword, Rcx, R11); + asm.shift_imm( + ShiftOp::Shl, + Size::Dword, + Rcx, + V_FLAG.trailing_zeros() as u8, + ); + asm.alu(Alu::Or, Size::Dword, Rax, Rcx); + asm.mov_store(Size::Dword, Mem::base_disp32(Rdi, NZCV_OFFSET as i32), Rax); } -const MOV_R9D_R8D: &[u8] = &[0x45, 0x89, 0xc1]; -const MOV_R9D_IMM32: &[u8] = &[0x41, 0xb9]; -const SUB_R9D_R8D: &[u8] = &[0x45, 0x29, 0xc1]; -const SHL_R9D_IMM8: &[u8] = &[0x41, 0xc1, 0xe1]; -const CMP_R9D_IMM32: &[u8] = &[0x41, 0x81, 0xf9]; -const MOV_ECX_R9D: &[u8] = &[0x44, 0x89, 0xc9]; -const SHL_RAX_CL: &[u8] = &[0x48, 0xd3, 0xe0]; -const DEC_RAX: &[u8] = &[0x48, 0xff, 0xc8]; -const NOT_RAX: &[u8] = &[0x48, 0xf7, 0xd0]; - /// Emit a complete P/PP prefix or suffix from the clamped R8D element count. /// R8 survives; packed physical chunks need not align to a pair's global64 bits. fn write_counted( - code: &mut Vec, + code: &mut Code, destination: Destination, element: ElementSize, length: VectorLength, @@ -384,47 +309,45 @@ fn write_counted( Destination::Counter { .. } => unreachable!("counter uses architectural encoding"), }; if suffix { - code.extend(MOV_R9D_IMM32); - code.extend(capacity.to_le_bytes()); - code.extend(SUB_R9D_R8D); + let mut asm = code.asm(); + asm.mov_imm32(R9, capacity); + asm.alu(Alu::Sub, Size::Dword, R9, R8); } else { - code.extend(MOV_R9D_R8D); + code.asm().mov(Size::Dword, R9, R8); } let shift = element.bytes().trailing_zeros() as u8; if shift != 0 { - code.extend(SHL_R9D_IMM8); - code.push(shift); + code.asm().shift_imm(ShiftOp::Shl, Size::Dword, R9, shift); } for vector in 0..vectors { for chunk in 0..chunks(length) { let start = vector * length.bytes() + chunk * CHUNK_BITS; let width = (length.bytes() - chunk * CHUNK_BITS).min(CHUNK_BITS); - code.extend(CMP_R9D_IMM32); - code.extend((start as u32).to_le_bytes()); - let low = jump(code, JBE); - code.extend(CMP_R9D_IMM32); - code.extend(((start + width) as u32).to_le_bytes()); - let high = jump(code, JAE); - code.extend(MOV_ECX_R9D); - code.extend(SUB_ECX_IMM32); - code.extend((start as u32).to_le_bytes()); + let mut asm = code.asm(); + asm.alu_imm32(Alu::Cmp, Size::Dword, R9, start as i32); + let low = asm.jcc(Cond::Be); + asm.alu_imm32(Alu::Cmp, Size::Dword, R9, (start + width) as i32); + let high = asm.jcc(Cond::Ae); + asm.mov(Size::Dword, Rcx, R9); + asm.alu_imm32(Alu::Sub, Size::Dword, Rcx, start as i32); constant(code, 1); - code.extend(SHL_RAX_CL); - code.extend(DEC_RAX); + let mut asm = code.asm(); + asm.shift_cl(ShiftOp::Shl, Size::Qword, Rax); + asm.dec(Size::Qword, Rax); if suffix { - code.extend(NOT_RAX); + asm.unary(Unary::Not, Size::Qword, Rax); } - let partial = jump(code, JMP); - bind(code, low); + let partial = asm.jmp(); + asm.bind(low); constant(code, if suffix { u64::MAX } else { 0 }); - let low_ready = jump(code, JMP); - bind(code, high); + let low_ready = code.asm().jmp(); + code.asm().bind(high); constant(code, if suffix { 0 } else { u64::MAX }); - bind(code, partial); - bind(code, low_ready); - code.extend(MOVABS_R11); - code.extend(marker_mask(element).to_le_bytes()); - code.extend(AND_RAX_R11); + let mut asm = code.asm(); + asm.bind(partial); + asm.bind(low_ready); + asm.mov_imm64(R11, marker_mask(element)); + asm.alu(Alu::And, Size::Qword, Rax, R11); write_predicate_chunk(code, first + vector as u8, chunk, length); } } @@ -436,6 +359,9 @@ mod breaks { //! Only packed P storage is accessed. RDI/R15 and the host stack survive. //! Results use XMM0-3; flag-setting forms other than BRKN keep Pg in //! XMM4-7. + use crate::x86_64::asm::BitTest; + use crate::x86_64::asm::Gpr::{R8, R9, R10, R11, Rax, Rcx}; + use crate::x86_64::asm::{Alu, Code, Cond, Mem, Size, Unary}; use crate::aarch64::scalable::{ElementSize, VectorLength}; use crate::aarch64::sve::predicate_generation::{Boundary, BreakKind, BreakOperand}; @@ -445,107 +371,58 @@ mod breaks { use crate::TargetCpu; - const BLSMSK_RAX_R9: &[u8] = &[0xc4, 0xc2, 0xf8, 0xf3, 0xd1]; - const BLSI_RAX_R9: &[u8] = &[0xc4, 0xc2, 0xf8, 0xf3, 0xd9]; - const DEC_RAX: &[u8] = &[0x48, 0xff, 0xc8]; const QWORD_BYTES: usize = core::mem::size_of::(); const BITS_PER_BYTE: usize = u8::BITS as usize; const ORIGINAL_GUARD_XMM_BASE: usize = 4; - const MOV_R8_RAX: &[u8] = &[0x49, 0x89, 0xc0]; - const MOV_R9_RAX: &[u8] = &[0x49, 0x89, 0xc1]; - const MOV_R11_RAX: &[u8] = &[0x49, 0x89, 0xc3]; - const MOV_R11_R9: &[u8] = &[0x4d, 0x89, 0xcb]; - const MOV_R10_SIGN_EXTENDED_IMM32: &[u8] = &[0x49, 0xc7, 0xc2]; - const MOV_R11_SIGN_EXTENDED_IMM32: &[u8] = &[0x49, 0xc7, 0xc3]; - const MOVABS_R11_IMM64: &[u8] = &[0x49, 0xbb]; - const XOR_R10D_R10D: &[u8] = &[0x45, 0x31, 0xd2]; - const TEST_RAX_RAX: &[u8] = &[0x48, 0x85, 0xc0]; - const BSR_RCX_RAX: &[u8] = &[0x48, 0x0f, 0xbd, 0xc8]; - const BT_RAX_RCX: &[u8] = &[0x48, 0x0f, 0xa3, 0xc8]; - const SBB_R10_R10: &[u8] = &[0x4d, 0x19, 0xd2]; - const LEA_RAX_R9_MINUS_ONE: &[u8] = &[0x49, 0x8d, 0x41, 0xff]; - const XOR_RAX_R9: &[u8] = &[0x4c, 0x31, 0xc8]; - const NOT_R11: &[u8] = &[0x49, 0xf7, 0xd3]; - const NOT_R8: &[u8] = &[0x49, 0xf7, 0xd0]; - const AND_RAX_R11: &[u8] = &[0x4c, 0x21, 0xd8]; - const AND_RAX_R8: &[u8] = &[0x4c, 0x21, 0xc0]; - const AND_RAX_R10: &[u8] = &[0x4c, 0x21, 0xd0]; - const OR_RAX_R11: &[u8] = &[0x4c, 0x09, 0xd8]; - const CMP_R9_ONE: &[u8] = &[0x49, 0x83, 0xf9, 0x01]; - const SBB_R11_R11: &[u8] = &[0x4d, 0x19, 0xdb]; - const AND_R10_R11: &[u8] = &[0x4d, 0x21, 0xda]; - const MOVQ_XMM_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e]; - const MOVQ_RAX_XMM: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; - const MODRM_REGISTER: u8 = 0xc0; - const MODRM_REGISTER_SHIFT: usize = 3; - const JZ_REL32: &[u8] = &[0x0f, 0x84]; - const JMP_REL32: &[u8] = &[0xe9]; const ALL_BITS: i32 = -1; - fn stage(code: &mut Vec, xmm: usize) { - code.extend(MOVQ_XMM_RAX); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) as u8); + fn stage(code: &mut Code, xmm: usize) { + code.asm().movq_to_xmm(xmm as u8, Rax); } - fn restore(code: &mut Vec, xmm: usize) { - code.extend(MOVQ_RAX_XMM); - code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) as u8); - } - - fn jump(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend(0_i32.to_le_bytes()); - displacement - } - - fn patch(code: &mut [u8], displacement: usize, destination: usize) { - let after = displacement + core::mem::size_of::(); - let relative = i32::try_from(destination as isize - after as isize) - .expect("predicate-break local branch must fit rel32"); - code[displacement..after].copy_from_slice(&relative.to_le_bytes()); + fn restore(code: &mut Code, xmm: usize) { + code.asm().movq_from_xmm(Rax, xmm as u8); } /// R10=-1 iff Pn at the last active Pg bit is one; otherwise R10=0. /// Read all selection inputs before any result is committed. BSR is never /// consumed on zero. Scalable storage reads preserve RCX and R10. - fn last_active(code: &mut Vec, guard: u8, source: u8, length: VectorLength) { + fn last_active(code: &mut Code, guard: u8, source: u8, length: VectorLength) { let chunks = length.predicate_bytes().div_ceil(QWORD_BYTES); - code.extend(XOR_R10D_R10D); + code.asm().alu(Alu::Xor, Size::Dword, R10, R10); let mut completed = Vec::with_capacity(chunks); for chunk in (0..chunks).rev() { read_predicate_chunk(code, guard, chunk, length); - code.extend(TEST_RAX_RAX); - let absent = jump(code, JZ_REL32); - code.extend(BSR_RCX_RAX); + let mut asm = code.asm(); + asm.test(Size::Qword, Rax, Rax); + let absent = asm.jcc(Cond::E); + asm.bsr(Size::Qword, Rcx, Rax); read_predicate_chunk(code, source, chunk, length); - code.extend(BT_RAX_RCX); - code.extend(SBB_R10_R10); - completed.push(jump(code, JMP_REL32)); - let next = code.len(); - patch(code, absent, next); + let mut asm = code.asm(); + asm.bit(BitTest::Bt, Size::Qword, Rax, Rcx); + asm.alu(Alu::Sbb, Size::Qword, R10, R10); + completed.push(asm.jmp()); + asm.bind(absent); } - let done = code.len(); - for displacement in completed { - patch(code, displacement, done); + let mut asm = code.asm(); + for done in completed { + asm.bind(done); } } - fn all_chunk_bits(code: &mut Vec, chunk: usize, length: VectorLength) { + fn all_chunk_bits(code: &mut Code, chunk: usize, length: VectorLength) { let bytes = (length.predicate_bytes() - chunk * QWORD_BYTES).min(QWORD_BYTES); if bytes == QWORD_BYTES { - code.extend(MOV_R11_SIGN_EXTENDED_IMM32); - code.extend(ALL_BITS.to_le_bytes()); + code.asm().mov_rm_imm32(Size::Qword, R11, ALL_BITS); } else { // Full physical tail width matters to BRKNS's C flag. let bits = bytes * BITS_PER_BYTE; - code.extend(MOVABS_R11_IMM64); - code.extend(((1_u64 << bits) - 1).to_le_bytes()); + code.asm().mov_imm64(R11, (1_u64 << bits) - 1); } } pub(crate) fn emit_break( - code: &mut Vec, + code: &mut Code, operand: BreakOperand, length: VectorLength, target: TargetCpu, @@ -554,8 +431,7 @@ mod breaks { debug_assert!(chunks <= ORIGINAL_GUARD_XMM_BASE); let (boundary, merging, breaking) = match operand.kind { BreakKind::Break { boundary, merging } => { - code.extend(MOV_R10_SIGN_EXTENDED_IMM32); - code.extend(ALL_BITS.to_le_bytes()); + code.asm().mov_rm_imm32(Size::Qword, R10, ALL_BITS); (Some(boundary), merging, operand.source) } BreakKind::Previous { boundary, source } => { @@ -573,45 +449,48 @@ mod breaks { if operand.set_flags { stage(code, ORIGINAL_GUARD_XMM_BASE + chunk); } - code.extend(MOV_R8_RAX); + code.asm().mov(Size::Qword, R8, Rax); read_predicate_chunk(code, breaking, chunk, length); - code.extend(AND_RAX_R8); - code.extend(MOV_R9_RAX); + let mut asm = code.asm(); + asm.alu(Alu::And, Size::Qword, Rax, R8); + asm.mov(Size::Qword, R9, Rax); match boundary { Boundary::After if target.supports(TargetCpu::Bmi1) => { - code.extend(BLSMSK_RAX_R9) + asm.blsmsk(Size::Qword, Rax, R9); } Boundary::Before if target.supports(TargetCpu::Bmi1) => { - code.extend(BLSI_RAX_R9); - code.extend(DEC_RAX); + asm.blsi(Size::Qword, Rax, R9); + asm.dec(Size::Qword, Rax); } Boundary::After => { - code.extend(LEA_RAX_R9_MINUS_ONE); - code.extend(XOR_RAX_R9); + asm.lea(Size::Qword, Rax, Mem::base_disp8(R9, -1)); + asm.alu(Alu::Xor, Size::Qword, Rax, R9); } Boundary::Before => { - code.extend(LEA_RAX_R9_MINUS_ONE); - code.extend(MOV_R11_R9); - code.extend(NOT_R11); - code.extend(AND_RAX_R11); + asm.lea(Size::Qword, Rax, Mem::base_disp8(R9, -1)); + asm.mov(Size::Qword, R11, R9); + asm.unary(Unary::Not, Size::Qword, R11); + asm.alu(Alu::And, Size::Qword, Rax, R11); } } - code.extend(AND_RAX_R8); - code.extend(AND_RAX_R10); + asm.alu(Alu::And, Size::Qword, Rax, R8); + asm.alu(Alu::And, Size::Qword, Rax, R10); if merging { - code.extend(MOV_R11_RAX); + code.asm().mov(Size::Qword, R11, Rax); read_predicate_chunk(code, operand.destination, chunk, length); - code.extend(NOT_R8); - code.extend(AND_RAX_R8); - code.extend(OR_RAX_R11); + let mut asm = code.asm(); + asm.unary(Unary::Not, Size::Qword, R8); + asm.alu(Alu::And, Size::Qword, Rax, R8); + asm.alu(Alu::Or, Size::Qword, Rax, R11); } stage(code, chunk); - code.extend(CMP_R9_ONE); - code.extend(SBB_R11_R11); - code.extend(AND_R10_R11); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Cmp, Size::Qword, R9, 1); + asm.alu(Alu::Sbb, Size::Qword, R11, R11); + asm.alu(Alu::And, Size::Qword, R10, R11); } else { read_predicate_chunk(code, operand.destination, chunk, length); - code.extend(AND_RAX_R10); + code.asm().alu(Alu::And, Size::Qword, Rax, R10); stage(code, chunk); } } @@ -625,7 +504,7 @@ mod breaks { for chunk in 0..chunks { if boundary.is_some() { restore(code, ORIGINAL_GUARD_XMM_BASE + chunk); - code.extend(MOV_R11_RAX); + code.asm().mov(Size::Qword, R11, Rax); } else { all_chunk_bits(code, chunk, length); } @@ -642,6 +521,8 @@ mod whiles { //! //! Count is retained in R8D across state helpers; RAX/RCX/RDX are scratch. //! No callee-saved register is used. Scalar inputs are read before guest writes. + use crate::x86_64::asm::Gpr::{R8, Rax, Rcx, Rdi, Rdx}; + use crate::x86_64::asm::{Alu, Code, Cond, Mem, ShiftOp, Size, Unary}; use crate::{ GuestState, @@ -655,7 +536,6 @@ mod whiles { scalable::{write_predicate_chunk, zero_predicate}, }, }; - use alloc::vec::Vec; const GPR_BYTES: usize = core::mem::size_of::(); const NZCV_OFFSET: u32 = core::mem::offset_of!(GuestState, nzcv) as u32; @@ -667,121 +547,24 @@ mod whiles { const Z_NIBBLE_SHIFT: u8 = 2; const PN_INVERT_BIT: u32 = 1 << 15; const PN_COUNT_SCALE_SHIFT: u32 = 1; - const REL32_BYTES: usize = core::mem::size_of::(); - const TWO_BYTE_OPCODE: u8 = 0x0f; - const JMP_REL32: u8 = 0xe9; - const MOV_EAX_STATE: &[u8] = &[0x8b, 0x87]; - const MOV_RAX_STATE: &[u8] = &[0x48, 0x8b, 0x87]; - const MOVSXD_RAX_STATE: &[u8] = &[0x48, 0x63, 0x87]; - const MOV_ECX_STATE: &[u8] = &[0x8b, 0x8f]; - const MOV_RCX_STATE: &[u8] = &[0x48, 0x8b, 0x8f]; - const MOVSXD_RCX_STATE: &[u8] = &[0x48, 0x63, 0x8f]; - const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; - const XOR_ECX_ECX: &[u8] = &[0x31, 0xc9]; - const XOR_R8D_R8D: &[u8] = &[0x45, 0x31, 0xc0]; - const MOV_EAX_IMM32: u8 = 0xb8; - const MOV_EDX_IMM32: u8 = 0xba; - const MOV_R8D_IMM32: &[u8] = &[0x41, 0xb8]; - const MOVABS_RDX_IMM64: &[u8] = &[0x48, 0xba]; - const MOV_RAX_RCX: &[u8] = &[0x48, 0x89, 0xc8]; - const MOV_EAX_R8D: &[u8] = &[0x44, 0x89, 0xc0]; - const MOV_R8D_EAX: &[u8] = &[0x41, 0x89, 0xc0]; - const CMP_RAX_RCX: &[u8] = &[0x48, 0x39, 0xc8]; - const CMP_RCX_RAX: &[u8] = &[0x48, 0x39, 0xc1]; - const CMP_RCX_RDX: &[u8] = &[0x48, 0x39, 0xd1]; - const CMP_RAX_RDX: &[u8] = &[0x48, 0x39, 0xd0]; - const CMP_ECX_IMM32: &[u8] = &[0x81, 0xf9]; - const CMP_RCX_NEGATIVE_ONE: &[u8] = &[0x48, 0x83, 0xf9, 0xff]; - const CMP_R8D_IMM32: &[u8] = &[0x41, 0x81, 0xf8]; - const TEST_RAX_RAX: &[u8] = &[0x48, 0x85, 0xc0]; - const TEST_RCX_RCX: &[u8] = &[0x48, 0x85, 0xc9]; - const TEST_R8D_R8D: &[u8] = &[0x45, 0x85, 0xc0]; - const SUB_RAX_RCX: &[u8] = &[0x48, 0x29, 0xc8]; - const SUB_RCX_RAX: &[u8] = &[0x48, 0x29, 0xc1]; - const SUB_EAX_R8D: &[u8] = &[0x44, 0x29, 0xc0]; - const NEG_RAX: &[u8] = &[0x48, 0xf7, 0xd8]; - const CMOVA_RAX_RDX: &[u8] = &[0x48, TWO_BYTE_OPCODE, 0x47, 0xc2]; - const CMOVE_R8D_EDX: &[u8] = &[0x44, TWO_BYTE_OPCODE, 0x44, 0xc2]; - const LEA_R8D_RAX_PLUS_ONE: &[u8] = &[0x44, 0x8d, 0x40, 1]; - const JAE_REL8: u8 = 0x73; - const SHR_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe8]; - const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; - const SHL_ECX_IMM8: &[u8] = &[0xc1, 0xe1]; - const SHL_EDX_IMM8: &[u8] = &[0xc1, 0xe2]; - const SETE_CL: &[u8] = &[TWO_BYTE_OPCODE, 0x94, 0xc1]; - const SETE_DL: &[u8] = &[TWO_BYTE_OPCODE, 0x94, 0xc2]; - const MOVZX_ECX_CL: &[u8] = &[TWO_BYTE_OPCODE, 0xb6, 0xc9]; - const MOVZX_EDX_DL: &[u8] = &[TWO_BYTE_OPCODE, 0xb6, 0xd2]; - const LEA_EAX_RDX_TIMES_THREE: &[u8] = &[0x8d, 0x04, 0x52]; - const ADD_EAX_EAX: &[u8] = &[0x01, 0xc0]; - const ADD_ECX_ECX: &[u8] = &[0x01, 0xc9]; - const SUB_EAX_ECX: &[u8] = &[0x29, 0xc8]; - const SUB_EAX_EDX: &[u8] = &[0x29, 0xd0]; - const OR_EAX_ECX: &[u8] = &[0x09, 0xc8]; - const OR_EAX_IMM32: u8 = 0x0d; - const MOV_STATE_EAX: &[u8] = &[0x89, 0x87]; - - #[repr(u8)] - #[derive(Clone, Copy)] - enum JumpCondition { - Below = 0x82, - Equal = 0x84, - BelowEqual = 0x86, - Above = 0x87, - Less = 0x8c, - GreaterEqual = 0x8d, - LessEqual = 0x8e, - Greater = 0x8f, - AboveEqual = 0x83, - } - - fn conditional_jump(code: &mut Vec, condition: JumpCondition) -> usize { - code.extend([TWO_BYTE_OPCODE, condition as u8]); - relative_jump_slot(code) - } - - fn jump(code: &mut Vec) -> usize { - code.push(JMP_REL32); - relative_jump_slot(code) - } - - fn relative_jump_slot(code: &mut Vec) -> usize { - let slot = code.len(); - code.extend(0i32.to_le_bytes()); - slot - } - - fn bind_jump(code: &mut [u8], slot: usize) { - let displacement = - i32::try_from(code.len() - slot - REL32_BYTES).expect("one WHILE mapping fits rel32"); - code[slot..slot + REL32_BYTES].copy_from_slice(&displacement.to_le_bytes()); - } - - fn immediate(code: &mut Vec, instruction: &[u8], value: u32) { - code.extend(instruction); - code.extend(value.to_le_bytes()); - } - - fn scalar(code: &mut Vec, source: Register, width: Width, signed: bool, first: bool) { + fn scalar(code: &mut Code, source: Register, width: Width, signed: bool, first: bool) { + let destination = if first { Rax } else { Rcx }; + let mut asm = code.asm(); if source == Register::Zero { - code.extend(if first { XOR_EAX_EAX } else { XOR_ECX_ECX }); + asm.alu(Alu::Xor, Size::Dword, destination, destination); return; } debug_assert!(matches!(source, Register::X(_))); - let instruction = match (first, width, signed) { - (true, Width::X64, _) => MOV_RAX_STATE, - (false, Width::X64, _) => MOV_RCX_STATE, - (true, Width::W32, false) => MOV_EAX_STATE, - (false, Width::W32, false) => MOV_ECX_STATE, - (true, Width::W32, true) => MOVSXD_RAX_STATE, - (false, Width::W32, true) => MOVSXD_RCX_STATE, - }; - immediate( - code, - instruction, - offset(source).expect("WHILE scalar source is GPR"), + let state = Mem::base_disp32( + Rdi, + offset(source).expect("WHILE scalar source is GPR") as i32, ); + match (width, signed) { + (Width::X64, _) => asm.mov_load(Size::Qword, destination, state), + (Width::W32, false) => asm.mov_load(Size::Dword, destination, state), + (Width::W32, true) => asm.movsxd(destination, state), + } } fn descending(comparison: Comparison) -> bool { @@ -814,26 +597,26 @@ mod whiles { ) } - fn failed_condition(comparison: Comparison) -> JumpCondition { + fn failed_condition(comparison: Comparison) -> Cond { match comparison { - Comparison::SignedLt => JumpCondition::GreaterEqual, - Comparison::SignedLe => JumpCondition::Greater, - Comparison::SignedGe => JumpCondition::Less, - Comparison::SignedGt => JumpCondition::LessEqual, - Comparison::UnsignedLt => JumpCondition::AboveEqual, - Comparison::UnsignedLe => JumpCondition::Above, - Comparison::UnsignedGe => JumpCondition::Below, - Comparison::UnsignedGt => JumpCondition::BelowEqual, + Comparison::SignedLt => Cond::Ge, + Comparison::SignedLe => Cond::G, + Comparison::SignedGe => Cond::L, + Comparison::SignedGt => Cond::Le, + Comparison::UnsignedLt => Cond::Ae, + Comparison::UnsignedLe => Cond::A, + Comparison::UnsignedGe => Cond::B, + Comparison::UnsignedGt => Cond::Be, _ => unreachable!("address distance has its own count mapping"), } } /// Compare RCX to the inclusive bound covering the entire modular domain. - fn endpoint_compare(code: &mut Vec, comparison: Comparison, width: Width) { + fn endpoint_compare(code: &mut Code, comparison: Comparison, width: Width) { if comparison == Comparison::UnsignedGe { - code.extend(TEST_RCX_RCX); + code.asm().test(Size::Qword, Rcx, Rcx); } else if comparison == Comparison::UnsignedLe && width == Width::X64 { - code.extend(CMP_RCX_NEGATIVE_ONE); + code.asm().alu_imm8(Alu::Cmp, Size::Qword, Rcx, -1); } else if width == Width::W32 { let endpoint = match comparison { Comparison::SignedLe => i32::MAX as u32, @@ -841,37 +624,39 @@ mod whiles { Comparison::UnsignedLe => u32::MAX, _ => unreachable!("inclusive comparison"), }; - immediate(code, CMP_ECX_IMM32, endpoint); + code.asm() + .alu_imm32(Alu::Cmp, Size::Dword, Rcx, endpoint as i32); } else { let endpoint = if comparison == Comparison::SignedLe { i64::MAX as u64 } else { i64::MIN as u64 }; - code.extend(MOVABS_RDX_IMM64); - code.extend(endpoint.to_le_bytes()); - code.extend(CMP_RCX_RDX); + let mut asm = code.asm(); + asm.mov_imm64(Rdx, endpoint); + asm.alu(Alu::Cmp, Size::Qword, Rcx, Rdx); } } - fn clamped_distance(code: &mut Vec, capacity: u32, add_one: bool) { + fn clamped_distance(code: &mut Code, capacity: u32, add_one: bool) { // The unsigned distance can be UINT64_MAX even for signed64 operands. // Clamp BEFORE increment, so inclusive full-domain distance cannot overflow. - immediate(code, &[MOV_EDX_IMM32], capacity - u32::from(add_one)); - code.extend(CMP_RAX_RDX); - code.extend(CMOVA_RAX_RDX); - code.extend(if add_one { - LEA_R8D_RAX_PLUS_ONE + let mut asm = code.asm(); + asm.mov_imm32(Rdx, capacity - u32::from(add_one)); + asm.alu(Alu::Cmp, Size::Qword, Rax, Rdx); + asm.cmov(Cond::A, Size::Qword, Rax, Rdx); + if add_one { + asm.lea(Size::Dword, R8, Mem::base_disp8(Rax, 1)); } else { - MOV_R8D_EAX - }); + asm.mov(Size::Dword, R8, Rax); + } } - fn comparison_count(code: &mut Vec, operand: &WhileOperand, capacity: u32) { + fn comparison_count(code: &mut Code, operand: &WhileOperand, capacity: u32) { let add_one = inclusive(operand.comparison); if operand.first == operand.limit { if !add_one { - code.extend(XOR_R8D_R8D); + code.asm().alu(Alu::Xor, Size::Dword, R8, R8); } else { // Equal inputs produce one active element except at the inclusive // domain endpoint, where comparison remains true across scalar wrap. @@ -882,10 +667,11 @@ mod whiles { signed(operand.comparison), false, ); - immediate(code, MOV_R8D_IMM32, 1); + code.asm().mov_imm32(R8, 1); endpoint_compare(code, operand.comparison, operand.width); - immediate(code, &[MOV_EDX_IMM32], capacity); - code.extend(CMOVE_R8D_EDX); + let mut asm = code.asm(); + asm.mov_imm32(Rdx, capacity); + asm.cmov(Cond::E, Size::Dword, R8, Rdx); } return; } @@ -904,93 +690,95 @@ mod whiles { false, ); let endpoint = if add_one { - immediate(code, MOV_R8D_IMM32, capacity); + code.asm().mov_imm32(R8, capacity); endpoint_compare(code, operand.comparison, operand.width); - Some(conditional_jump(code, JumpCondition::Equal)) + Some(code.asm().jcc(Cond::E)) } else { None }; - code.extend(XOR_R8D_R8D); - code.extend(CMP_RAX_RCX); - let failed = conditional_jump(code, failed_condition(operand.comparison)); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, R8, R8); + asm.alu(Alu::Cmp, Size::Qword, Rax, Rcx); + let failed = asm.jcc(failed_condition(operand.comparison)); if descending(operand.comparison) { - code.extend(SUB_RAX_RCX); + asm.alu(Alu::Sub, Size::Qword, Rax, Rcx); } else { - code.extend(SUB_RCX_RAX); - code.extend(MOV_RAX_RCX); + asm.alu(Alu::Sub, Size::Qword, Rcx, Rax); + asm.mov(Size::Qword, Rax, Rcx); } clamped_distance(code, capacity, add_one); - bind_jump(code, failed); + let mut asm = code.asm(); + asm.bind(failed); if let Some(endpoint) = endpoint { - bind_jump(code, endpoint); + asm.bind(endpoint); } } - fn address_count(code: &mut Vec, operand: &WhileOperand, capacity: u32) { - immediate(code, MOV_R8D_IMM32, capacity); + fn address_count(code: &mut Code, operand: &WhileOperand, capacity: u32) { + code.asm().mov_imm32(R8, capacity); if operand.first == operand.limit { return; } scalar(code, operand.first, Width::X64, false, true); scalar(code, operand.limit, Width::X64, false, false); + let mut asm = code.asm(); let backward = if operand.comparison == Comparison::WriteReadDistance { - code.extend(CMP_RCX_RAX); - let backward = conditional_jump(code, JumpCondition::BelowEqual); - code.extend(SUB_RCX_RAX); - code.extend(MOV_RAX_RCX); + asm.alu(Alu::Cmp, Size::Qword, Rcx, Rax); + let backward = asm.jcc(Cond::Be); + asm.alu(Alu::Sub, Size::Qword, Rcx, Rax); + asm.mov(Size::Qword, Rax, Rcx); Some(backward) } else { // A borrowed unsigned subtraction followed by NEG recovers abs(a-b), // including differences above INT64_MAX; signed ABS would be incorrect. - code.extend(SUB_RAX_RCX); - code.extend([JAE_REL8, NEG_RAX.len() as u8]); - code.extend(NEG_RAX); + asm.alu(Alu::Sub, Size::Qword, Rax, Rcx); + let borrowed = asm.jcc8(Cond::Ae); + asm.unary(Unary::Neg, Size::Qword, Rax); + asm.bind(borrowed); None }; let divisor_shift = operand.element.bytes().trailing_zeros() as u8; if divisor_shift != 0 { - code.extend(SHR_RAX_IMM8); - code.push(divisor_shift); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Rax, divisor_shift); } - code.extend(TEST_RAX_RAX); - let unrestricted = conditional_jump(code, JumpCondition::Equal); + asm.test(Size::Qword, Rax, Rax); + let unrestricted = asm.jcc(Cond::E); clamped_distance(code, capacity, false); - bind_jump(code, unrestricted); + let mut asm = code.asm(); + asm.bind(unrestricted); if let Some(backward) = backward { - bind_jump(code, backward); + asm.bind(backward); } } - fn count_flags(code: &mut Vec, capacity: u32, suffix: bool) { - immediate(code, CMP_R8D_IMM32, capacity); - code.extend(SETE_CL); - code.extend(TEST_R8D_R8D); - code.extend(SETE_DL); - code.extend(MOVZX_ECX_CL); - code.extend(MOVZX_EDX_DL); + fn count_flags(code: &mut Code, capacity: u32, suffix: bool) { + let mut asm = code.asm(); + asm.alu_imm32(Alu::Cmp, Size::Dword, R8, capacity as i32); + asm.setcc(Cond::E, Rcx); + asm.test(Size::Dword, R8, R8); + asm.setcc(Cond::E, Rdx); + asm.movzx(Size::Dword, Rcx, Size::Byte, Rcx); + asm.movzx(Size::Dword, Rdx, Size::Byte, Rdx); if suffix { // nibble = 8*full + 6*none; partial suffix has nibble0. - code.extend(LEA_EAX_RDX_TIMES_THREE); - code.extend(ADD_EAX_EAX); - code.extend(SHL_ECX_IMM8); - code.push(N_NIBBLE_SHIFT); - code.extend(OR_EAX_ECX); + asm.lea(Size::Dword, Rax, Mem::indexed(Rdx, Rdx, 2, 0)); + asm.alu(Alu::Add, Size::Dword, Rax, Rax); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rcx, N_NIBBLE_SHIFT); + asm.alu(Alu::Or, Size::Dword, Rax, Rcx); } else { // nibble = 10 - 4*none - 2*full. - immediate(code, &[MOV_EAX_IMM32], ASCENDING_PARTIAL_FLAGS); - code.extend(SHL_EDX_IMM8); - code.push(Z_NIBBLE_SHIFT); - code.extend(SUB_EAX_EDX); - code.extend(ADD_ECX_ECX); - code.extend(SUB_EAX_ECX); + asm.mov_imm32(Rax, ASCENDING_PARTIAL_FLAGS); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rdx, Z_NIBBLE_SHIFT); + asm.alu(Alu::Sub, Size::Dword, Rax, Rdx); + asm.alu(Alu::Add, Size::Dword, Rcx, Rcx); + asm.alu(Alu::Sub, Size::Dword, Rax, Rcx); } - code.extend(SHL_EAX_IMM8); - code.push(NZCV_STATE_SHIFT); - immediate(code, MOV_STATE_EAX, NZCV_OFFSET); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, NZCV_STATE_SHIFT); + asm.mov_store(Size::Dword, Mem::base_disp32(Rdi, NZCV_OFFSET as i32), Rax); } fn counter( - code: &mut Vec, + code: &mut Code, destination: u8, element: ElementSize, length: VectorLength, @@ -999,48 +787,47 @@ mod whiles { ) { let single_chunk = length.predicate_bytes() <= GPR_BYTES; if single_chunk { - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); } else { zero_predicate(code, destination, length); } - code.extend(TEST_R8D_R8D); - let empty = conditional_jump(code, JumpCondition::Equal); + let mut asm = code.asm(); + asm.test(Size::Dword, R8, R8); + let empty = asm.jcc(Cond::E); let tag = element.bytes() as u32; let shift = (element.bytes().trailing_zeros() + PN_COUNT_SCALE_SHIFT) as u8; if suffix { - immediate(code, &[MOV_EAX_IMM32], capacity); - code.extend(SUB_EAX_R8D); - code.extend(SHL_EAX_IMM8); - code.push(shift); - immediate(code, &[OR_EAX_IMM32], PN_INVERT_BIT | tag); + asm.mov_imm32(Rax, capacity); + asm.alu(Alu::Sub, Size::Dword, Rax, R8); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, shift); + asm.alu_accumulator_imm32(Alu::Or, Size::Dword, (PN_INVERT_BIT | tag) as i32); } else { - immediate(code, CMP_R8D_IMM32, capacity); - let full = conditional_jump(code, JumpCondition::Equal); - code.extend(MOV_EAX_R8D); - code.extend(SHL_EAX_IMM8); - code.push(shift); - immediate(code, &[OR_EAX_IMM32], tag); - let encoded = jump(code); - bind_jump(code, full); - immediate(code, &[MOV_EAX_IMM32], PN_INVERT_BIT | tag); - bind_jump(code, encoded); + asm.alu_imm32(Alu::Cmp, Size::Dword, R8, capacity as i32); + let full = asm.jcc(Cond::E); + asm.mov(Size::Dword, Rax, R8); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, shift); + asm.alu_accumulator_imm32(Alu::Or, Size::Dword, tag as i32); + let encoded = asm.jmp(); + asm.bind(full); + asm.mov_imm32(Rax, PN_INVERT_BIT | tag); + asm.bind(encoded); } if single_chunk { - bind_jump(code, empty); + asm.bind(empty); write_predicate_chunk(code, destination, 0, length); } else { write_predicate_chunk(code, destination, 0, length); - bind_jump(code, empty); + code.asm().bind(empty); } } /// Parent callback emits the complete prefix/suffix P or PP write from R8D. /// It must preserve R8D. `capacity` spans both destinations for a pair. pub(super) fn emit_while( - code: &mut Vec, + code: &mut Code, operand: &WhileOperand, length: VectorLength, - write_counted: impl FnOnce(&mut Vec, Destination, ElementSize, VectorLength, bool, u32), + write_counted: impl FnOnce(&mut Code, Destination, ElementSize, VectorLength, bool, u32), ) { debug_assert!(operand.element.bytes() <= GPR_BYTES); let vectors = match operand.destination { diff --git a/crates/stela-compiler/src/x86_64/sve/predicate_logic.rs b/crates/stela-compiler/src/x86_64/sve/predicate_logic.rs index c956df4544..c2ed34efec 100644 --- a/crates/stela-compiler/src/x86_64/sve/predicate_logic.rs +++ b/crates/stela-compiler/src/x86_64/sve/predicate_logic.rs @@ -1,6 +1,9 @@ //! Predicate Boolean operations and permutes. use super::super::scalable; use super::predicate; +use crate::x86_64::asm::BitTest; +use crate::x86_64::asm::Gpr::{R8, R11, Rax, Rcx, Rdi, Rdx, Rsp}; +use crate::x86_64::asm::{Alu, Code, Gpr, Mem, ShiftOp, Size, Unary}; use crate::{ TargetCpu, aarch64::{ @@ -8,44 +11,12 @@ use crate::{ sve::predicate_logic::{Boolean, Kind, Operand, Permutation}, }, }; -use alloc::vec::Vec; const CHUNK_BITS: usize = 64; const CHUNK_BYTES: usize = 8; const SOURCE_SLOT_BYTES: usize = 32; const SNAPSHOT_BYTES: u8 = 64; const HALF_CHUNK_BITS: usize = 32; -const SUB_RSP_SNAPSHOT: &[u8] = &[0x48, 0x83, 0xec, SNAPSHOT_BYTES]; -const ADD_RSP_SNAPSHOT: &[u8] = &[0x48, 0x83, 0xc4, SNAPSHOT_BYTES]; -const MOV_STACK_RAX: &[u8] = &[0x48, 0x89, 0x84, 0x24]; -const MOV_RAX_STACK: &[u8] = &[0x48, 0x8b, 0x84, 0x24]; -const MOV_RCX_RAX: &[u8] = &[0x48, 0x89, 0xc1]; -const MOV_R11_RAX: &[u8] = &[0x49, 0x89, 0xc3]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const BSWAP_RAX: &[u8] = &[0x48, 0x0f, 0xc8]; -const AND_EAX_IMM32: &[u8] = &[0x25]; -const MOV_EAX_EAX: &[u8] = &[0x89, 0xc0]; -const AND_RAX_RCX: &[u8] = &[0x48, 0x21, 0xc8]; -const OR_RAX_RCX: &[u8] = &[0x48, 0x09, 0xc8]; -const XOR_RAX_RCX: &[u8] = &[0x48, 0x31, 0xc8]; -const OR_RAX_RDX: &[u8] = &[0x48, 0x09, 0xd0]; -const AND_RAX_R11: &[u8] = &[0x4c, 0x21, 0xd8]; -const AND_RDX_R11: &[u8] = &[0x4c, 0x21, 0xda]; -const XOR_RAX_R11: &[u8] = &[0x4c, 0x31, 0xd8]; -const NOT_RAX: &[u8] = &[0x48, 0xf7, 0xd0]; -const MOVABS_R11: &[u8] = &[0x49, 0xbb]; -const SHR_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe8]; -const SHL_RAX_IMM8: &[u8] = &[0x48, 0xc1, 0xe0]; -const SHR_RDX_IMM8: &[u8] = &[0x48, 0xc1, 0xea]; -const SHL_RDX_IMM8: &[u8] = &[0x48, 0xc1, 0xe2]; -const MOVDQU_STACK_XMM0: &[u8] = &[0xf3, 0x0f, 0x7f, 0x84, 0x24]; -const MOV_ECX_STATE: &[u8] = &[0x8b, 0x8f]; -const ADD_ECX_IMM8: &[u8] = &[0x83, 0xc1]; -const AND_ECX_IMM32: &[u8] = &[0x81, 0xe1]; -const SHL_ECX_IMM8: &[u8] = &[0xc1, 0xe1]; -const BT_STACK_RCX: &[u8] = &[0x48, 0x0f, 0xa3, 0x0c, 0x24]; -const SBB_R8_R8: &[u8] = &[0x4d, 0x19, 0xc0]; -const AND_RAX_R8: &[u8] = &[0x4c, 0x21, 0xc0]; const SPREAD_STAGES: [(u8, u64); 5] = [ (16, 0x0000_ffff_0000_ffff), (8, 0x00ff_00ff_00ff_00ff), @@ -54,7 +25,7 @@ const SPREAD_STAGES: [(u8, u64); 5] = [ (1, 0x5555_5555_5555_5555), ]; -pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu) { match operand.kind { Kind::Boolean { operation, @@ -68,33 +39,38 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, } for chunk in 0..length.predicate_bytes().div_ceil(CHUNK_BYTES) { scalable::read_predicate_chunk(code, left, chunk, length); - code.extend(MOV_RCX_RAX); + code.asm().mov(Size::Qword, Rcx, Rax); scalable::read_predicate_chunk(code, right, chunk, length); match operation { - Boolean::And => code.extend(AND_RAX_RCX), + Boolean::And => code.asm().alu(Alu::And, Size::Qword, Rax, Rcx), Boolean::BitClear => { - code.extend(NOT_RAX); - code.extend(AND_RAX_RCX); + let mut asm = code.asm(); + asm.unary(Unary::Not, Size::Qword, Rax); + asm.alu(Alu::And, Size::Qword, Rax, Rcx); } - Boolean::ExclusiveOr => code.extend(XOR_RAX_RCX), + Boolean::ExclusiveOr => code.asm().alu(Alu::Xor, Size::Qword, Rax, Rcx), Boolean::Nand => { - code.extend(AND_RAX_RCX); - code.extend(NOT_RAX); + let mut asm = code.asm(); + asm.alu(Alu::And, Size::Qword, Rax, Rcx); + asm.unary(Unary::Not, Size::Qword, Rax); } Boolean::Nor => { - code.extend(OR_RAX_RCX); - code.extend(NOT_RAX); + let mut asm = code.asm(); + asm.alu(Alu::Or, Size::Qword, Rax, Rcx); + asm.unary(Unary::Not, Size::Qword, Rax); } Boolean::OrNot => { - code.extend(NOT_RAX); - code.extend(OR_RAX_RCX); + let mut asm = code.asm(); + asm.unary(Unary::Not, Size::Qword, Rax); + asm.alu(Alu::Or, Size::Qword, Rax, Rcx); } - Boolean::Or => code.extend(OR_RAX_RCX), + Boolean::Or => code.asm().alu(Alu::Or, Size::Qword, Rax, Rcx), } - code.extend(MOV_RCX_RAX); + code.asm().mov(Size::Qword, Rcx, Rax); scalable::read_predicate_chunk(code, governor, chunk, length); - code.extend(MOV_R11_RAX); - code.extend(AND_RAX_RCX); + let mut asm = code.asm(); + asm.mov(Size::Qword, R11, Rax); + asm.alu(Alu::And, Size::Qword, Rax, Rcx); if flags { predicate::accumulate_predtest(code, ElementSize::Byte); } @@ -111,14 +87,16 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, } => { for chunk in 0..length.predicate_bytes().div_ceil(CHUNK_BYTES) { scalable::read_predicate_chunk(code, left, chunk, length); - code.extend(MOV_RCX_RAX); + code.asm().mov(Size::Qword, Rcx, Rax); scalable::read_predicate_chunk(code, right, chunk, length); - code.extend(MOV_R11_RAX); - code.extend(XOR_RAX_RCX); - code.extend(MOV_RCX_RAX); + let mut asm = code.asm(); + asm.mov(Size::Qword, R11, Rax); + asm.alu(Alu::Xor, Size::Qword, Rax, Rcx); + asm.mov(Size::Qword, Rcx, Rax); scalable::read_predicate_chunk(code, governor, chunk, length); - code.extend(AND_RAX_RCX); - code.extend(XOR_RAX_R11); + let mut asm = code.asm(); + asm.alu(Alu::And, Size::Qword, Rax, Rcx); + asm.alu(Alu::Xor, Size::Qword, Rax, R11); scalable::write_predicate_chunk(code, operand.destination, chunk, length); } } @@ -129,32 +107,46 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, index_register, immediate, } => { - code.extend(SUB_RSP_SNAPSHOT); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); snapshot(code, selector, 0, length); - code.extend(MOV_ECX_STATE); - code.extend( - ((core::mem::offset_of!(crate::GuestState, x) - + usize::from(index_register) * CHUNK_BYTES) as u32) - .to_le_bytes(), + code.asm().mov_load( + Size::Dword, + Rcx, + Mem::base_disp32( + Rdi, + (core::mem::offset_of!(crate::GuestState, x) + + usize::from(index_register) * CHUNK_BYTES) as i32, + ), ); if immediate != 0 { - code.extend(ADD_ECX_IMM8); - code.push(immediate); + code.asm() + .alu_imm8(Alu::Add, Size::Dword, Rcx, immediate as i8); } - code.extend(AND_ECX_IMM32); - code.extend(((length.bytes() / element.bytes() - 1) as u32).to_le_bytes()); + code.asm().alu_imm32( + Alu::And, + Size::Dword, + Rcx, + (length.bytes() / element.bytes() - 1) as i32, + ); if element != ElementSize::Byte { - code.extend(SHL_ECX_IMM8); - code.push(element.bytes().ilog2() as u8); + code.asm().shift_imm( + ShiftOp::Shl, + Size::Dword, + Rcx, + element.bytes().ilog2() as u8, + ); } - code.extend(BT_STACK_RCX); - code.extend(SBB_R8_R8); + let mut asm = code.asm(); + asm.bit(BitTest::Bt, Size::Qword, Mem::base(Rsp, 0), Rcx); + asm.alu(Alu::Sbb, Size::Qword, R8, R8); for chunk in 0..length.predicate_bytes().div_ceil(CHUNK_BYTES) { scalable::read_predicate_chunk(code, source, chunk, length); - code.extend(AND_RAX_R8); + code.asm().alu(Alu::And, Size::Qword, Rax, R8); scalable::write_predicate_chunk(code, operand.destination, chunk, length); } - code.extend(ADD_RSP_SNAPSHOT); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); } Kind::ExtractCounter { element, @@ -170,7 +162,7 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, let offset = (usize::from(part) * outputs + output) * length.bytes() + chunk * CHUNK_BITS; predicate::emit_prepared_counter_chunk(code, offset / CHUNK_BITS, length); - shift(code, SHR_RAX_IMM8, offset % CHUNK_BITS); + shift(code, ShiftOp::Shr, Rax, offset % CHUNK_BITS); and_mask(code, predicate::leading_bits(element)); scalable::write_predicate_chunk( code, @@ -186,12 +178,13 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, source, part, } => { - code.extend(SUB_RSP_SNAPSHOT); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); let needed = length.predicate_bytes().div_ceil(16); for chunk in 0..needed { scalable::load_z_chunk(code, source, chunk, 0, length, target); - code.extend(MOVDQU_STACK_XMM0); - code.extend(((chunk * 16) as u32).to_le_bytes()); + code.asm() + .movdqu_store(Mem::base_disp32(Rsp, (chunk * 16) as i32), 0); } for chunk in 0..length.predicate_bytes().div_ceil(CHUNK_BYTES) { let bit = length.bytes() / element.bytes() * usize::from(part) @@ -200,7 +193,8 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, dilate(code, element.bytes()); scalable::write_predicate_chunk(code, operand.destination, chunk, length); } - code.extend(ADD_RSP_SNAPSHOT); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); } Kind::Permute { operation, @@ -208,17 +202,20 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, left, right, } => { - code.extend(SUB_RSP_SNAPSHOT); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); snapshot(code, left, 0, length); snapshot(code, right, SOURCE_SLOT_BYTES, length); for chunk in 0..length.predicate_bytes().div_ceil(CHUNK_BYTES) { permutation(code, operation, element, chunk, length); scalable::write_predicate_chunk(code, operand.destination, chunk, length); } - code.extend(ADD_RSP_SNAPSHOT); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); } Kind::Unpack { high, source } => { - code.extend(SUB_RSP_SNAPSHOT); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); snapshot(code, source, 0, length); for chunk in 0..length.predicate_bytes().div_ceil(CHUNK_BYTES) { load_bits( @@ -229,100 +226,106 @@ pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, spread(code, 1, length.bytes().min(CHUNK_BITS)); scalable::write_predicate_chunk(code, operand.destination, chunk, length); } - code.extend(ADD_RSP_SNAPSHOT); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); } Kind::Reverse { element, source } => { - code.extend(SUB_RSP_SNAPSHOT); + code.asm() + .alu_imm8(Alu::Sub, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); snapshot(code, source, 0, length); let chunks = length.predicate_bytes().div_ceil(CHUNK_BYTES); for chunk in 0..chunks { load_snapshot(code, (chunks - 1 - chunk) * CHUNK_BYTES); for distance in [1, 2, 4].into_iter().filter(|&d| d >= element.bytes()) { - code.extend(MOV_RDX_RAX); - shift(code, SHR_RDX_IMM8, distance); + code.asm().mov(Size::Qword, Rdx, Rax); + shift(code, ShiftOp::Shr, Rdx, distance); and_mask(code, low_group_mask(distance)); - shift(code, SHL_RAX_IMM8, distance); + shift(code, ShiftOp::Shl, Rax, distance); // RDX already contains the opposite half; mask it via R11. - code.extend(AND_RDX_R11); - code.extend(OR_RAX_RDX); + let mut asm = code.asm(); + asm.alu(Alu::And, Size::Qword, Rdx, R11); + asm.alu(Alu::Or, Size::Qword, Rax, Rdx); } - code.extend(BSWAP_RAX); + code.asm().bswap(Size::Qword, Rax); if length.bytes() < CHUNK_BITS { - shift(code, SHR_RAX_IMM8, CHUNK_BITS - length.bytes()); + shift(code, ShiftOp::Shr, Rax, CHUNK_BITS - length.bytes()); } scalable::write_predicate_chunk(code, operand.destination, chunk, length); } - code.extend(ADD_RSP_SNAPSHOT); + code.asm() + .alu_imm8(Alu::Add, Size::Qword, Rsp, SNAPSHOT_BYTES as i8); } } } -fn snapshot(code: &mut Vec, source: u8, slot: usize, length: VectorLength) { +fn snapshot(code: &mut Code, source: u8, slot: usize, length: VectorLength) { for chunk in 0..length.predicate_bytes().div_ceil(CHUNK_BYTES) { scalable::read_predicate_chunk(code, source, chunk, length); store_snapshot(code, slot + chunk * CHUNK_BYTES); } } -fn store_snapshot(code: &mut Vec, offset: usize) { - code.extend(MOV_STACK_RAX); - code.extend((offset as u32).to_le_bytes()); +fn store_snapshot(code: &mut Code, offset: usize) { + code.asm() + .mov_store(Size::Qword, Mem::base_disp32(Rsp, offset as i32), Rax); } -fn load_snapshot(code: &mut Vec, offset: usize) { - code.extend(MOV_RAX_STACK); - code.extend((offset as u32).to_le_bytes()); +fn load_snapshot(code: &mut Code, offset: usize) { + code.asm() + .mov_load(Size::Qword, Rax, Mem::base_disp32(Rsp, offset as i32)); } -fn load_bits(code: &mut Vec, slot: usize, bit: usize) { +fn load_bits(code: &mut Code, slot: usize, bit: usize) { load_snapshot(code, slot + (bit / CHUNK_BITS) * CHUNK_BYTES); - shift(code, SHR_RAX_IMM8, bit % CHUNK_BITS); + shift(code, ShiftOp::Shr, Rax, bit % CHUNK_BITS); } -fn shift(code: &mut Vec, opcode: &[u8], bits: usize) { +fn shift(code: &mut Code, op: ShiftOp, register: Gpr, bits: usize) { if bits != 0 { - code.extend(opcode); - code.push(bits as u8); + code.asm().shift_imm(op, Size::Qword, register, bits as u8); } } -fn and_mask(code: &mut Vec, mask: u64) { - code.extend(MOVABS_R11); - code.extend(mask.to_le_bytes()); - code.extend(AND_RAX_R11); +fn and_mask(code: &mut Code, mask: u64) { + let mut asm = code.asm(); + asm.mov_imm64(R11, mask); + asm.alu(Alu::And, Size::Qword, Rax, R11); } fn low_group_mask(group: usize) -> u64 { (0..CHUNK_BITS) .filter(|bit| (bit / group).is_multiple_of(2)) .fold(0, |mask, bit| mask | (1 << bit)) } -fn spread(code: &mut Vec, group: usize, output_bits: usize) { +fn spread(code: &mut Code, group: usize, output_bits: usize) { if output_bits < CHUNK_BITS { - code.extend(AND_EAX_IMM32); - code.extend(((1u32 << (output_bits / 2)) - 1).to_le_bytes()); + code.asm().alu_accumulator_imm32( + Alu::And, + Size::Dword, + ((1u32 << (output_bits / 2)) - 1) as i32, + ); } else { - code.extend(MOV_EAX_EAX); + code.asm().mov(Size::Dword, Rax, Rax); } for (distance, mask) in SPREAD_STAGES.into_iter().filter(|&(distance, _)| { usize::from(distance) >= group && usize::from(distance) < output_bits / 2 }) { - code.extend(MOV_RDX_RAX); - shift(code, SHL_RDX_IMM8, usize::from(distance)); - code.extend(OR_RAX_RDX); + code.asm().mov(Size::Qword, Rdx, Rax); + shift(code, ShiftOp::Shl, Rdx, usize::from(distance)); + code.asm().alu(Alu::Or, Size::Qword, Rax, Rdx); and_mask(code, mask); } } -fn compact(code: &mut Vec, group: usize, odd: bool) { - shift(code, SHR_RAX_IMM8, usize::from(odd) * group); +fn compact(code: &mut Code, group: usize, odd: bool) { + shift(code, ShiftOp::Shr, Rax, usize::from(odd) * group); and_mask(code, low_group_mask(group)); for distance in [1, 2, 4, 8, 16] .into_iter() .filter(|&distance| distance >= group) { - code.extend(MOV_RDX_RAX); - shift(code, SHR_RDX_IMM8, distance); - code.extend(OR_RAX_RDX); + code.asm().mov(Size::Qword, Rdx, Rax); + shift(code, ShiftOp::Shr, Rdx, distance); + code.asm().alu(Alu::Or, Size::Qword, Rax, Rdx); and_mask(code, low_group_mask(distance * 2)); } - code.extend(MOV_EAX_EAX); + code.asm().mov(Size::Dword, Rax, Rax); } fn permutation( - code: &mut Vec, + code: &mut Code, operation: Permutation, element: ElementSize, chunk: usize, @@ -334,32 +337,32 @@ fn permutation( let bit = usize::from(high) * length.bytes() / 2 + chunk * HALF_CHUNK_BITS; load_bits(code, 0, bit); spread(code, group, length.bytes().min(CHUNK_BITS)); - code.extend(MOV_RCX_RAX); + code.asm().mov(Size::Qword, Rcx, Rax); load_bits(code, SOURCE_SLOT_BYTES, bit); spread(code, group, length.bytes().min(CHUNK_BITS)); - shift(code, SHL_RAX_IMM8, group); - code.extend(OR_RAX_RCX); + shift(code, ShiftOp::Shl, Rax, group); + code.asm().alu(Alu::Or, Size::Qword, Rax, Rcx); } Permutation::Transpose { odd } => { load_snapshot(code, chunk * CHUNK_BYTES); - shift(code, SHR_RAX_IMM8, usize::from(odd) * group); + shift(code, ShiftOp::Shr, Rax, usize::from(odd) * group); and_mask(code, low_group_mask(group)); - code.extend(MOV_RCX_RAX); + code.asm().mov(Size::Qword, Rcx, Rax); load_snapshot(code, SOURCE_SLOT_BYTES + chunk * CHUNK_BYTES); - shift(code, SHR_RAX_IMM8, usize::from(odd) * group); + shift(code, ShiftOp::Shr, Rax, usize::from(odd) * group); and_mask(code, low_group_mask(group)); - shift(code, SHL_RAX_IMM8, group); - code.extend(OR_RAX_RCX); + shift(code, ShiftOp::Shl, Rax, group); + code.asm().alu(Alu::Or, Size::Qword, Rax, Rcx); } Permutation::Unzip { odd } => { if length.bytes() <= CHUNK_BITS { load_snapshot(code, 0); compact(code, group, odd); - code.extend(MOV_RCX_RAX); + code.asm().mov(Size::Qword, Rcx, Rax); load_snapshot(code, SOURCE_SLOT_BYTES); compact(code, group, odd); - shift(code, SHL_RAX_IMM8, length.bytes() / 2); - code.extend(OR_RAX_RCX); + shift(code, ShiftOp::Shl, Rax, length.bytes() / 2); + code.asm().alu(Alu::Or, Size::Qword, Rax, Rcx); } else { let half = length.bytes() / 2; let bit = chunk * CHUNK_BITS; @@ -367,29 +370,29 @@ fn permutation( let source_chunk = (bit % half) / HALF_CHUNK_BITS; load_snapshot(code, slot + source_chunk * CHUNK_BYTES); compact(code, group, odd); - code.extend(MOV_RCX_RAX); + code.asm().mov(Size::Qword, Rcx, Rax); load_snapshot(code, slot + (source_chunk + 1) * CHUNK_BYTES); compact(code, group, odd); - shift(code, SHL_RAX_IMM8, HALF_CHUNK_BITS); - code.extend(OR_RAX_RCX); + shift(code, ShiftOp::Shl, Rax, HALF_CHUNK_BITS); + code.asm().alu(Alu::Or, Size::Qword, Rax, Rcx); } } } } -fn dilate(code: &mut Vec, stride: usize) { +fn dilate(code: &mut Code, stride: usize) { if stride == 1 { return; } let input_bits = CHUNK_BITS / stride; // The first dilation mask discards unused low32 bits; this clears the // only higher bits that could otherwise overlap its retained groups. - code.extend(MOV_EAX_EAX); + code.asm().mov(Size::Dword, Rax, Rax); let mut block = input_bits / 2; while block != 0 { - code.extend(MOV_RDX_RAX); - shift(code, SHL_RDX_IMM8, (stride - 1) * block); - code.extend(OR_RAX_RDX); + code.asm().mov(Size::Qword, Rdx, Rax); + shift(code, ShiftOp::Shl, Rdx, (stride - 1) * block); + code.asm().alu(Alu::Or, Size::Qword, Rax, Rdx); let mask = (0..CHUNK_BITS) .filter(|bit| bit % (block * stride) < block) .fold(0, |mask, bit| mask | (1 << bit)); diff --git a/crates/stela-compiler/src/x86_64/sve/rearrange.rs b/crates/stela-compiler/src/x86_64/sve/rearrange.rs index 0748e67d29..0b709d656b 100644 --- a/crates/stela-compiler/src/x86_64/sve/rearrange.rs +++ b/crates/stela-compiler/src/x86_64/sve/rearrange.rs @@ -1,6 +1,7 @@ //! SVE permutes with SSE2 or SSSE3. Sources are snapshotted only for permutes //! that cross chunks. -use alloc::vec::Vec; +use crate::x86_64::asm::Gpr::{Rax, Rsp}; +use crate::x86_64::asm::{Alu, Code, Mem, Rm, Size}; mod dynamic; use crate::TargetCpu; @@ -9,13 +10,6 @@ use crate::aarch64::sve::rearrange::{InterleaveKind, Operand}; use crate::x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}; use crate::x86_64::scalable::{load_z_chunk, read_predicate_mask, store_z_chunk}; -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; -const MOVABS_RAX_IMM64: &[u8] = &[0x48, 0xb8]; -const MODRM_STACK_DISP32: u8 = 0x84; -const STACK_SIB: u8 = 0x24; -const XMM_FIELD_SHIFT: u8 = 3; -const MODRM_REGISTER: u8 = 0xc0; const FIRST: u8 = 0; const SECOND: u8 = 1; const REVERSE_SCRATCH: u8 = 2; @@ -34,23 +28,19 @@ const LOW_BYTE_EACH_WORD: u64 = 0x00ff_00ff_00ff_00ff; const BYTE_REVERSE_LOW: u64 = 0x0809_0a0b_0c0d_0e0f; const BYTE_REVERSE_HIGH: u64 = 0x0001_0203_0405_0607; -fn stack_memory(code: &mut Vec, opcode: Host, xmm: u8, offset: usize, target: TargetCpu) { - opcode.append(code, target); - code.push(MODRM_STACK_DISP32 | (xmm << XMM_FIELD_SHIFT)); - code.push(STACK_SIB); - code.extend((offset as u32).to_le_bytes()); +fn stack_memory(code: &mut Code, opcode: Host, xmm: u8, offset: usize, target: TargetCpu) { + code.asm() + .simd(opcode, xmm, Mem::base_disp32(Rsp, offset as i32), target); } -fn constant(code: &mut Vec, value: u64, xmm: u8, target: TargetCpu) { - code.extend(MOVABS_RAX_IMM64); - code.extend(value.to_le_bytes()); - Host::MoveGprQword.append(code, target); - code.push(MODRM_REGISTER | (xmm << XMM_FIELD_SHIFT)); +fn constant(code: &mut Code, value: u64, xmm: u8, target: TargetCpu) { + code.asm().mov_imm64(Rax, value); + code.asm().simd(Host::MoveGprQword, xmm, Rax, target); } -fn shuffle(code: &mut Vec, opcode: Host, xmm: u8, control: u8, target: TargetCpu) { - opcode.register(code, xmm, xmm, target); - code.push(control); +fn shuffle(code: &mut Code, opcode: Host, xmm: u8, control: u8, target: TargetCpu) { + code.asm() + .simd_imm(opcode, xmm, Rm::Xmm(xmm), control, target); } struct Snapshot { @@ -60,7 +50,7 @@ struct Snapshot { impl Snapshot { fn new( - code: &mut Vec, + code: &mut Code, destination: u8, sources: &[u8], crossing: bool, @@ -70,8 +60,8 @@ impl Snapshot { let register = (crossing && length.chunks() > 1 && sources.contains(&destination)) .then_some(destination); if register.is_some() { - code.extend(SUB_RSP_IMM32); - code.extend((length.bytes() as u32).to_le_bytes()); + code.asm() + .alu_imm32(Alu::Sub, Size::Qword, Rsp, length.bytes() as i32); for chunk in 0..length.chunks() { load_z_chunk(code, destination, chunk, FIRST, length, target); stack_memory( @@ -86,7 +76,7 @@ impl Snapshot { Self { register, length } } - fn load(&self, code: &mut Vec, register: u8, chunk: usize, xmm: u8, target: TargetCpu) { + fn load(&self, code: &mut Code, register: u8, chunk: usize, xmm: u8, target: TargetCpu) { if self.register == Some(register) { stack_memory( code, @@ -100,10 +90,10 @@ impl Snapshot { } } - fn finish(self, code: &mut Vec) { + fn finish(self, code: &mut Code) { if self.register.is_some() { - code.extend(ADD_RSP_IMM32); - code.extend((self.length.bytes() as u32).to_le_bytes()); + code.asm() + .alu_imm32(Alu::Add, Size::Qword, Rsp, self.length.bytes() as i32); } } } @@ -123,7 +113,7 @@ fn unpack(element: ElementSize, high: bool) -> Host { } /// Compact selected odd/even elements into the low qword without saturation loss. -fn compact(code: &mut Vec, xmm: u8, element: ElementSize, part: u8, target: TargetCpu) { +fn compact(code: &mut Code, xmm: u8, element: ElementSize, part: u8, target: TargetCpu) { match element { ElementSize::Byte => { if part == 0 { @@ -160,7 +150,7 @@ fn compact(code: &mut Vec, xmm: u8, element: ElementSize, part: u8, target: } } -fn interleave(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +fn interleave(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let Operand::Interleave { kind, part, @@ -230,7 +220,7 @@ fn interleave(code: &mut Vec, operand: Operand, length: VectorLength, target snapshot.finish(code); } -fn extract(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +fn extract(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let Operand::Extract { destination, source, @@ -282,8 +272,8 @@ fn extract(code: &mut Vec, operand: Operand, length: VectorLength, target: T }; snapshot.load(code, next_register, next_chunk, SECOND, target); if target.supports(TargetCpu::Ssse3) { - Host::AlignBytes.register(code, SECOND, FIRST, target); - code.push(shift); + code.asm() + .simd_imm(Host::AlignBytes, SECOND, Rm::Xmm(FIRST), shift, target); Host::MoveAligned.register(code, FIRST, SECOND, target); } else { Shift::RightBytes.emit(code, FIRST, shift); @@ -296,13 +286,7 @@ fn extract(code: &mut Vec, operand: Operand, length: VectorLength, target: T snapshot.finish(code); } -fn reverse_chunk( - code: &mut Vec, - xmm: u8, - scratch: u8, - element: ElementSize, - target: TargetCpu, -) { +fn reverse_chunk(code: &mut Code, xmm: u8, scratch: u8, element: ElementSize, target: TargetCpu) { if element == ElementSize::Byte && target.supports(TargetCpu::Ssse3) { Host::ByteShuffle.register(code, xmm, MASK, target); return; @@ -333,7 +317,7 @@ fn reverse_chunk( } fn reverse( - code: &mut Vec, + code: &mut Code, destination: u8, source: u8, element: ElementSize, @@ -388,7 +372,7 @@ pub(crate) fn requires_explicit_dit_zero( } /// Emit a fully decoded operand under the validated scalable execution profile. -pub(crate) fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { match operand { operand @ Operand::Interleave { .. } => interleave(code, operand, length, target), operand @ Operand::Extract { .. } => extract(code, operand, length, target), diff --git a/crates/stela-compiler/src/x86_64/sve/rearrange/dynamic.rs b/crates/stela-compiler/src/x86_64/sve/rearrange/dynamic.rs index 7df140b522..8874eb9864 100644 --- a/crates/stela-compiler/src/x86_64/sve/rearrange/dynamic.rs +++ b/crates/stela-compiler/src/x86_64/sve/rearrange/dynamic.rs @@ -2,6 +2,8 @@ //! //! Scratch: RAX/RCX/RDX, XMM0-7 and a stack frame; large SPLICE copies also use //! R8-R11/RSI and REP MOVSB (RDI is restored; SysV guarantees DF=0). +use crate::x86_64::asm::Gpr::{R8, R9, R10, R11, Rax, Rcx, Rdi, Rsi, Rsp}; +use crate::x86_64::asm::{Alu, Code, Cond, Disp, Gpr, Mem, Rm, ShiftOp, Size, Unary, resolve}; use crate::aarch64::Register; use crate::aarch64::scalable::{ElementSize, MAX_VECTOR_BYTES, VECTOR_CHUNK_BYTES, VectorLength}; @@ -9,49 +11,7 @@ use crate::aarch64::sve::rearrange::{IndexOperand, Operand}; use crate::x86_64::isa::SimdOpcode as Host; use crate::x86_64::scalable::{load_z_chunk, read_predicate_chunk, store_z_chunk}; use crate::{GuestState, TargetCpu}; -use alloc::vec::Vec; -const RAX: u8 = 0; -const RCX: u8 = 1; -const RSP: u8 = 4; -const NO_INDEX: u8 = RSP; -const REGISTER_SHIFT: u8 = 3; -const SCALE_SHIFT: u8 = 6; -const MODRM_DISP32_SIB: u8 = 0x84; -const SIB_RSP_NO_INDEX: u8 = 0x24; -const MODRM_DISP32_RDI: u8 = 0x87; -const MODRM_REGISTER: u8 = 0xc0; -const REX_QWORD: u8 = 0x48; -const WORD_PREFIX: u8 = 0x66; -const MOVZX_BYTE: &[u8] = &[0x0f, 0xb6]; -const MOVZX_WORD: &[u8] = &[0x0f, 0xb7]; -const MOV_LOAD: u8 = 0x8b; -const MOV_STORE_BYTE: u8 = 0x88; -const MOV_STORE: u8 = 0x89; -const SUB_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP_IMM32: &[u8] = &[0x48, 0x81, 0xc4]; -const CMP_RAX_IMM32: &[u8] = &[0x48, 0x3d]; -const MOV_RAX_IMM32: &[u8] = &[0x48, 0xc7, 0xc0]; -const MOV_RCX_IMM32: &[u8] = &[0x48, 0xc7, 0xc1]; -const MOVABS_RCX_IMM64: &[u8] = &[0x48, 0xb9]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const XOR_ECX_ECX: &[u8] = &[0x31, 0xc9]; -const ADD_RAX_RCX: &[u8] = &[0x48, 0x01, 0xc8]; -const SUB_RAX_RCX: &[u8] = &[0x48, 0x29, 0xc8]; -const ADD_RAX_IMM32: &[u8] = &[0x48, 0x05]; -const ADD_RCX_IMM32: &[u8] = &[0x48, 0x81, 0xc1]; -const NEG_RAX: &[u8] = &[0x48, 0xf7, 0xd8]; -const SHL_RCX_IMM8: &[u8] = &[0x48, 0xc1, 0xe1]; -const AND_RAX_RCX: &[u8] = &[0x48, 0x21, 0xc8]; -const TEST_RAX_RAX: &[u8] = &[0x48, 0x85, 0xc0]; -const BSF_RCX_RAX: &[u8] = &[0x48, 0x0f, 0xbc, 0xc8]; -const BSR_RAX_RAX: &[u8] = &[0x48, 0x0f, 0xbd, 0xc0]; -const JUMP_REL32: &[u8] = &[0xe9]; -const JAE_REL32: &[u8] = &[0x0f, 0x83]; -const JBE_REL32: &[u8] = &[0x0f, 0x86]; -const JE_REL32: &[u8] = &[0x0f, 0x84]; -const JNE_REL32: &[u8] = &[0x0f, 0x85]; -const REL32_BYTES: usize = core::mem::size_of::(); const QWORD_BYTES: usize = core::mem::size_of::(); const PREDICATE_CHUNK_BITS: usize = u64::BITS as usize; const FIRST: u8 = 0; @@ -63,8 +23,6 @@ const MATCHED: u8 = 5; const CHUNK_BASE: u8 = 6; const MAX_INDEX: u8 = 7; const FIRST_DWORD: u8 = 0; -const MOV_EAX_IMM32: u8 = 0xb8; -const MOVD_XMM_EAX: &[u8] = &[0x66, 0x0f, 0x6e]; const BYTE_BROADCAST_MULTIPLIER: u32 = 0x0101_0101; const TABLE_CHUNK_LAST_INDEX: u8 = VECTOR_CHUNK_BYTES as u8 - 1; const BYTE_INDEX_VALUES: usize = u8::MAX as usize + 1; @@ -72,101 +30,76 @@ const BYTE_INDEX_VALUES: usize = u8::MAX as usize + 1; const BYTE_TABLE_SHUFFLE_LIMIT_BYTES: usize = 64; const Z_REGISTER_MASK: u8 = 31; -const REX_EXTENDED_BASE: u8 = 0x41; -const REX_QWORD_EXTENDED_BASE: u8 = 0x49; -const LEA_R8_STACK_RAX: &[u8] = &[0x4c, 0x8d, 0x04, 0x04]; -const LEA_R9_STACK: &[u8] = &[0x4c, 0x8d, 0x8c, 0x24]; -const LEA_R10_STACK: &[u8] = &[0x4c, 0x8d, 0x94, 0x24]; -const LEA_R11_STACK: &[u8] = &[0x4c, 0x8d, 0x9c, 0x24]; -const LEA_RDI_STACK: &[u8] = &[0x48, 0x8d, 0xbc, 0x24]; -const LEA_RSI_STACK: &[u8] = &[0x48, 0x8d, 0xb4, 0x24]; -const LEA_RSI_STACK_RAX: &[u8] = &[0x48, 0x8d, 0x34, 0x04]; -const MOV_R8_RDI: &[u8] = &[0x49, 0x89, 0xf8]; -const MOV_RDI_R8: &[u8] = &[0x4c, 0x89, 0xc7]; -const REP_MOVSB: &[u8] = &[0xf3, 0xa4]; -const SUB_RCX_RAX: &[u8] = &[0x48, 0x29, 0xc1]; -const TEST_RCX_RCX: &[u8] = &[0x48, 0x85, 0xc9]; -const SUB_RCX_IMM8: &[u8] = &[0x48, 0x83, 0xe9]; -const ADD_R8_IMM8: &[u8] = &[0x49, 0x83, 0xc0]; -const ADD_R9_IMM8: &[u8] = &[0x49, 0x83, 0xc1]; -const ADD_R10_IMM8: &[u8] = &[0x49, 0x83, 0xc2]; -const CMP_R10_R11: &[u8] = &[0x4d, 0x39, 0xda]; -const JB_REL32: &[u8] = &[0x0f, 0x82]; -const R8_BASE: u8 = 0; -const R9_BASE: u8 = 1; -const R10_BASE: u8 = 2; - -fn stack_adjust(code: &mut Vec, bytes: usize, allocate: bool) { +fn stack_adjust(code: &mut Code, bytes: usize, allocate: bool) { assert!(bytes.is_multiple_of(VECTOR_CHUNK_BYTES)); - code.extend(if allocate { - SUB_RSP_IMM32 - } else { - ADD_RSP_IMM32 - }); - code.extend(i32::try_from(bytes).unwrap().to_le_bytes()); + let op = if allocate { Alu::Sub } else { Alu::Add }; + code.asm() + .alu_imm32(op, Size::Qword, Rsp, i32::try_from(bytes).unwrap()); } -fn branch(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend(opcode); - let displacement = code.len(); - code.extend([0; REL32_BYTES]); - displacement +/// `[rsp + index * scale + displacement]` with a 32-bit displacement field. +fn stack_slot(displacement: usize, index: Option, scale: usize) -> Mem { + let displacement = i32::try_from(displacement).unwrap(); + match index { + None => Mem::base_disp32(Rsp, displacement), + Some(index) => Mem::indexed(Rsp, index, scale as u8, displacement).with_width(Disp::Dword), + } } -fn bind(code: &mut [u8], displacement: usize) { - let target = code.len(); - let relative = i32::try_from(target as isize - (displacement + REL32_BYTES) as isize).unwrap(); - code[displacement..displacement + REL32_BYTES].copy_from_slice(&relative.to_le_bytes()); +/// The operand size of a B/H/S/D lane. +fn lane_size(bytes: usize) -> Size { + match bytes { + 1 => Size::Byte, + 2 => Size::Word, + 4 => Size::Dword, + QWORD_BYTES => Size::Qword, + _ => unreachable!("dynamic rearrangement has scalar B/H/S/D lanes"), + } } -/// Scalar stack load. Index is RAX/RCX or NO_INDEX; scale is element byte size. +/// Zero-extending lane load into RAX/RCX. +fn load_lane(code: &mut Code, destination: Gpr, source: Mem, bytes: usize) { + let mut asm = code.asm(); + match lane_size(bytes) { + Size::Dword => asm.mov_load(Size::Dword, destination, source), + Size::Qword => asm.mov_load(Size::Qword, destination, source), + narrow => asm.movzx(Size::Dword, destination, narrow, source), + } +} + +/// Scalar stack load. Index is RAX/RCX or none; scale is element byte size. fn load_stack( - code: &mut Vec, - destination: u8, + code: &mut Code, + destination: Gpr, displacement: usize, - index: u8, + index: Option, scale: usize, bytes: usize, ) { - assert!(matches!(destination, RAX | RCX)); - assert!(matches!(index, RAX | RCX | NO_INDEX)); + assert!(matches!(destination, Rax | Rcx)); + assert!(matches!(index, Some(Rax | Rcx) | None)); assert!(matches!(scale, 1 | 2 | 4 | 8)); - match bytes { - 1 => code.extend(MOVZX_BYTE), - 2 => code.extend(MOVZX_WORD), - 4 => code.push(MOV_LOAD), - QWORD_BYTES => code.extend([REX_QWORD, MOV_LOAD]), - _ => unreachable!("dynamic rearrangement has scalar B/H/S/D lanes"), - } - code.push(MODRM_DISP32_SIB | (destination << REGISTER_SHIFT)); - code.push(((scale.trailing_zeros() as u8) << SCALE_SHIFT) | (index << REGISTER_SHIFT) | RSP); - code.extend(i32::try_from(displacement).unwrap().to_le_bytes()); + load_lane( + code, + destination, + stack_slot(displacement, index, scale), + bytes, + ); } -fn store_stack(code: &mut Vec, source: u8, displacement: usize, bytes: usize) { - assert!(matches!(source, RAX | RCX)); - match bytes { - 1 => code.push(MOV_STORE_BYTE), - 2 => code.extend([WORD_PREFIX, MOV_STORE]), - 4 => code.push(MOV_STORE), - QWORD_BYTES => code.extend([REX_QWORD, MOV_STORE]), - _ => unreachable!("dynamic rearrangement has scalar B/H/S/D lanes"), - } - code.extend([ - MODRM_DISP32_SIB | (source << REGISTER_SHIFT), - SIB_RSP_NO_INDEX, - ]); - code.extend(i32::try_from(displacement).unwrap().to_le_bytes()); +fn store_stack(code: &mut Code, source: Gpr, displacement: usize, bytes: usize) { + assert!(matches!(source, Rax | Rcx)); + code.asm() + .mov_store(lane_size(bytes), stack_slot(displacement, None, 1), source); } -fn xmm_stack(code: &mut Vec, opcode: Host, xmm: u8, offset: usize, target: TargetCpu) { - opcode.append(code, target); - code.extend([MODRM_DISP32_SIB | (xmm << REGISTER_SHIFT), SIB_RSP_NO_INDEX]); - code.extend(i32::try_from(offset).unwrap().to_le_bytes()); +fn xmm_stack(code: &mut Code, opcode: Host, xmm: u8, offset: usize, target: TargetCpu) { + code.asm() + .simd(opcode, xmm, stack_slot(offset, None, 1), target); } fn snapshot_z( - code: &mut Vec, + code: &mut Code, register: u8, offset: usize, length: VectorLength, @@ -184,13 +117,7 @@ fn snapshot_z( } } -fn commit_z( - code: &mut Vec, - register: u8, - offset: usize, - length: VectorLength, - target: TargetCpu, -) { +fn commit_z(code: &mut Code, register: u8, offset: usize, length: VectorLength, target: TargetCpu) { for chunk in 0..length.chunks() { xmm_stack( code, @@ -222,7 +149,7 @@ struct TableFrame { } impl TableFrame { - fn snapshot(code: &mut Vec, op: Table, length: VectorLength, target: TargetCpu) -> Self { + fn snapshot(code: &mut Code, op: Table, length: VectorLength, target: TargetCpu) -> Self { assert!(matches!(op.register_count, 1 | 2)); assert!(!op.segment || op.register_count == 1); let table_bytes = usize::from(op.register_count) * length.bytes(); @@ -251,7 +178,7 @@ impl TableFrame { } } - fn finish(self, code: &mut Vec, destination: u8, length: VectorLength, target: TargetCpu) { + fn finish(self, code: &mut Code, destination: u8, length: VectorLength, target: TargetCpu) { commit_z(code, destination, self.output, length, target); stack_adjust(code, self.bytes, false); } @@ -296,7 +223,7 @@ pub(super) fn requires_explicit_dit_zero( } } -fn emit_table(code: &mut Vec, op: Table, length: VectorLength, target: TargetCpu) { +fn emit_table(code: &mut Code, op: Table, length: VectorLength, target: TargetCpu) { match table_recipe(op.element_size, op.segment, length, target) { TableRecipe::ByteShuffle => emit_table_ssse3(code, op, length, target), TableRecipe::ScalarGather => emit_table_unrolled(code, op, length, target), @@ -305,7 +232,7 @@ fn emit_table(code: &mut Vec, op: Table, length: VectorLength, target: Targe /// SSE2 baseline: a full unsigned bounds check of B/H/S/D indices before a /// bounded gather. -fn emit_table_unrolled(code: &mut Vec, op: Table, length: VectorLength, target: TargetCpu) { +fn emit_table_unrolled(code: &mut Code, op: Table, length: VectorLength, target: TargetCpu) { let width = op.element_size.bytes(); assert!(width <= QWORD_BYTES); let frame = TableFrame::snapshot(code, op, length, target); @@ -320,36 +247,44 @@ fn emit_table_unrolled(code: &mut Vec, op: Table, length: VectorLength, targ } else { 0 }; - load_stack(code, RAX, frame.indexes + offset, NO_INDEX, 1, width); - code.extend(CMP_RAX_IMM32); - code.extend(i32::try_from(table_bytes / width).unwrap().to_le_bytes()); - let out_of_range = branch(code, JAE_REL32); - load_stack(code, RCX, base, RAX, width, width); - store_stack(code, RCX, frame.output + offset, width); - let next = branch(code, JUMP_REL32); - bind(code, out_of_range); + load_stack(code, Rax, frame.indexes + offset, None, 1, width); + let mut asm = code.asm(); + asm.alu_accumulator_imm32( + Alu::Cmp, + Size::Qword, + i32::try_from(table_bytes / width).unwrap(), + ); + let out_of_range = asm.jcc(Cond::Ae); + load_stack(code, Rcx, base, Some(Rax), width, width); + store_stack(code, Rcx, frame.output + offset, width); + let next = code.asm().jmp(); + code.asm().bind(out_of_range); if !op.extension { - code.extend(XOR_ECX_ECX); - store_stack(code, RCX, frame.output + offset, width); + code.asm().alu(Alu::Xor, Size::Dword, Rcx, Rcx); + store_stack(code, Rcx, frame.output + offset, width); } - bind(code, next); + code.asm().bind(next); } frame.finish(code, op.destination, length, target); } -fn broadcast_byte(code: &mut Vec, value: u8, destination: u8, target: TargetCpu) { - code.push(MOV_EAX_IMM32); - code.extend((u32::from(value) * BYTE_BROADCAST_MULTIPLIER).to_le_bytes()); - code.extend(MOVD_XMM_EAX); - code.push(MODRM_REGISTER | (destination << REGISTER_SHIFT)); - Host::ShuffleDword.register(code, destination, destination, target); - code.push(FIRST_DWORD); +fn broadcast_byte(code: &mut Code, value: u8, destination: u8, target: TargetCpu) { + code.asm() + .mov_imm32(Rax, u32::from(value) * BYTE_BROADCAST_MULTIPLIER); + code.asm().movd_to_xmm(destination, Rax); + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(destination), + FIRST_DWORD, + target, + ); } /// PSHUFB with every index masked to below 16, so indices 16-127 cannot wrap /// and two-table TBL at a 256-bit vector length cannot reach the upper table /// through byte indices. The scalar baseline handles full-width H/S/D indices. -fn emit_table_ssse3(code: &mut Vec, op: Table, length: VectorLength, target: TargetCpu) { +fn emit_table_ssse3(code: &mut Code, op: Table, length: VectorLength, target: TargetCpu) { assert_eq!(op.element_size, ElementSize::Byte); assert!(target.supports(TargetCpu::Ssse3)); let frame = TableFrame::snapshot(code, op, length, target); @@ -427,74 +362,52 @@ struct Splice { element_size: ElementSize, } -fn address(code: &mut Vec, opcode: &[u8], displacement: usize) { - code.extend(opcode); - code.extend(i32::try_from(displacement).unwrap().to_le_bytes()); +fn address(code: &mut Code, destination: Gpr, displacement: usize) { + code.asm() + .lea(Size::Qword, destination, stack_slot(displacement, None, 1)); } -fn pointer_load(code: &mut Vec, bytes: usize, base: u8) { - code.push(if bytes == QWORD_BYTES { - REX_QWORD_EXTENDED_BASE - } else { - REX_EXTENDED_BASE - }); - code.extend(match bytes { - 1 => MOVZX_BYTE, - 2 => MOVZX_WORD, - 4 | QWORD_BYTES => &[MOV_LOAD], - _ => unreachable!("SPLICE lane width"), - }); - code.push(base); +fn pointer_load(code: &mut Code, bytes: usize, base: Gpr) { + load_lane(code, Rax, Mem::base(base, 0), bytes); } -fn pointer_store(code: &mut Vec, bytes: usize) { - if bytes == 2 { - code.push(WORD_PREFIX); - } - code.push(if bytes == QWORD_BYTES { - REX_QWORD_EXTENDED_BASE - } else { - REX_EXTENDED_BASE - }); - code.push(if bytes == 1 { - MOV_STORE_BYTE - } else { - MOV_STORE - }); - code.push(R10_BASE); +fn pointer_store(code: &mut Code, bytes: usize) { + code.asm() + .mov_store(lane_size(bytes), Mem::base(R10, 0), Rax); } -fn backward(code: &mut Vec, opcode: &[u8], target: usize) { - let displacement = branch(code, opcode); - let relative = i32::try_from(target as isize - (displacement + REL32_BYTES) as isize).unwrap(); - code[displacement..displacement + REL32_BYTES].copy_from_slice(&relative.to_le_bytes()); +fn backward(code: &mut Code, condition: Cond, target: usize) { + let branch = code.asm().jcc(condition); + resolve(code, branch, target); } fn copy_splice_rep( - code: &mut Vec, + code: &mut Code, second: usize, output: usize, first: usize, end: usize, bytes: usize, ) { - code.extend(MOV_R8_RDI); - address(code, LEA_RDI_STACK, output); - load_stack(code, RAX, first, NO_INDEX, 1, QWORD_BYTES); - code.extend(LEA_RSI_STACK_RAX); - load_stack(code, RCX, end, NO_INDEX, 1, QWORD_BYTES); - code.extend(REP_MOVSB); - code.extend(MOV_RCX_IMM32); - code.extend(i32::try_from(bytes).unwrap().to_le_bytes()); - load_stack(code, RAX, end, NO_INDEX, 1, QWORD_BYTES); - code.extend(SUB_RCX_RAX); - address(code, LEA_RSI_STACK, second); - code.extend(REP_MOVSB); - code.extend(MOV_RDI_R8); + code.asm().mov(Size::Qword, R8, Rdi); + address(code, Rdi, output); + load_stack(code, Rax, first, None, 1, QWORD_BYTES); + code.asm() + .lea(Size::Qword, Rsi, Mem::indexed(Rsp, Rax, 1, 0)); + load_stack(code, Rcx, end, None, 1, QWORD_BYTES); + let mut asm = code.asm(); + asm.rep_movsb(); + asm.mov_rm_imm32(Size::Qword, Rcx, i32::try_from(bytes).unwrap()); + load_stack(code, Rax, end, None, 1, QWORD_BYTES); + code.asm().alu(Alu::Sub, Size::Qword, Rcx, Rax); + address(code, Rsi, second); + let mut asm = code.asm(); + asm.rep_movsb(); + asm.mov(Size::Qword, Rdi, R8); } fn copy_splice_counted( - code: &mut Vec, + code: &mut Code, second: usize, output: usize, first: usize, @@ -502,42 +415,42 @@ fn copy_splice_counted( bytes: usize, width: usize, ) { - load_stack(code, RAX, first, NO_INDEX, 1, QWORD_BYTES); - code.extend(LEA_R8_STACK_RAX); - address(code, LEA_R9_STACK, second); - address(code, LEA_R10_STACK, output); - address(code, LEA_R11_STACK, output + bytes); - load_stack(code, RCX, end, NO_INDEX, 1, QWORD_BYTES); - code.extend(TEST_RCX_RCX); - let empty = branch(code, JE_REL32); + load_stack(code, Rax, first, None, 1, QWORD_BYTES); + code.asm() + .lea(Size::Qword, R8, Mem::indexed(Rsp, Rax, 1, 0)); + address(code, R9, second); + address(code, R10, output); + address(code, R11, output + bytes); + load_stack(code, Rcx, end, None, 1, QWORD_BYTES); + let mut asm = code.asm(); + asm.test(Size::Qword, Rcx, Rcx); + let empty = asm.jcc(Cond::E); let prefix_loop = code.len(); - pointer_load(code, width, R8_BASE); + pointer_load(code, width, R8); pointer_store(code, width); - code.extend(ADD_R8_IMM8); - code.push(width as u8); - code.extend(ADD_R10_IMM8); - code.push(width as u8); - code.extend(SUB_RCX_IMM8); - code.push(width as u8); - backward(code, JNE_REL32, prefix_loop); - bind(code, empty); - code.extend(CMP_R10_R11); - let full = branch(code, JE_REL32); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Add, Size::Qword, R8, width as i8); + asm.alu_imm8(Alu::Add, Size::Qword, R10, width as i8); + asm.alu_imm8(Alu::Sub, Size::Qword, Rcx, width as i8); + backward(code, Cond::Ne, prefix_loop); + let mut asm = code.asm(); + asm.bind(empty); + asm.alu(Alu::Cmp, Size::Qword, R10, R11); + let full = asm.jcc(Cond::E); let suffix_loop = code.len(); - pointer_load(code, width, R9_BASE); + pointer_load(code, width, R9); pointer_store(code, width); - code.extend(ADD_R9_IMM8); - code.push(width as u8); - code.extend(ADD_R10_IMM8); - code.push(width as u8); - code.extend(CMP_R10_R11); - backward(code, JB_REL32, suffix_loop); - bind(code, full); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Add, Size::Qword, R9, width as i8); + asm.alu_imm8(Alu::Add, Size::Qword, R10, width as i8); + asm.alu(Alu::Cmp, Size::Qword, R10, R11); + backward(code, Cond::B, suffix_loop); + code.asm().bind(full); } /// SSE2 baseline SPLICE copies the contiguous first..last active hull, including /// inactive holes, then fills from operand2. Empty predicates copy operand2. -fn emit_splice(code: &mut Vec, op: Splice, length: VectorLength, target: TargetCpu) { +fn emit_splice(code: &mut Code, op: Splice, length: VectorLength, target: TargetCpu) { let width = op.element_size.bytes(); assert!(width <= QWORD_BYTES); let second = length.bytes(); @@ -548,55 +461,60 @@ fn emit_splice(code: &mut Vec, op: Splice, length: VectorLength, target: Tar stack_adjust(code, frame_bytes, true); snapshot_z(code, op.source, 0, length, target); snapshot_z(code, op.second, second, length, target); - code.extend(MOV_RAX_IMM32); - code.extend(i32::try_from(length.bytes()).unwrap().to_le_bytes()); - store_stack(code, RAX, first, QWORD_BYTES); - code.extend(XOR_EAX_EAX); - store_stack(code, RAX, end, QWORD_BYTES); + code.asm() + .mov_rm_imm32(Size::Qword, Rax, i32::try_from(length.bytes()).unwrap()); + store_stack(code, Rax, first, QWORD_BYTES); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); + store_stack(code, Rax, end, QWORD_BYTES); let mut leading_bits = 0u64; for bit in (0..PREDICATE_CHUNK_BITS).step_by(width) { leading_bits |= 1u64 << bit; } for chunk in 0..length.predicate_bytes().div_ceil(QWORD_BYTES) { read_predicate_chunk(code, op.governing, chunk, length); + let mut asm = code.asm(); if width != 1 { - code.extend(MOVABS_RCX_IMM64); - code.extend(leading_bits.to_le_bytes()); - code.extend(AND_RAX_RCX); + asm.mov_imm64(Rcx, leading_bits); + asm.alu(Alu::And, Size::Qword, Rax, Rcx); } - code.extend(TEST_RAX_RAX); - let inactive = branch(code, JE_REL32); - code.extend(BSF_RCX_RAX); - code.extend(BSR_RAX_RAX); - code.extend(ADD_RAX_IMM32); - code.extend( - i32::try_from(chunk * PREDICATE_CHUNK_BITS + width) - .unwrap() - .to_le_bytes(), + asm.test(Size::Qword, Rax, Rax); + let inactive = asm.jcc(Cond::E); + asm.bsf(Size::Qword, Rcx, Rax); + asm.bsr(Size::Qword, Rax, Rax); + asm.alu_accumulator_imm32( + Alu::Add, + Size::Qword, + i32::try_from(chunk * PREDICATE_CHUNK_BITS + width).unwrap(), ); - store_stack(code, RAX, end, QWORD_BYTES); - load_stack(code, RAX, first, NO_INDEX, 1, QWORD_BYTES); - code.extend(CMP_RAX_IMM32); - code.extend(i32::try_from(length.bytes()).unwrap().to_le_bytes()); - let already_found = branch(code, JNE_REL32); - code.extend(ADD_RCX_IMM32); - code.extend( - i32::try_from(chunk * PREDICATE_CHUNK_BITS) - .unwrap() - .to_le_bytes(), + store_stack(code, Rax, end, QWORD_BYTES); + load_stack(code, Rax, first, None, 1, QWORD_BYTES); + let mut asm = code.asm(); + asm.alu_accumulator_imm32( + Alu::Cmp, + Size::Qword, + i32::try_from(length.bytes()).unwrap(), ); - store_stack(code, RCX, first, QWORD_BYTES); - bind(code, already_found); - bind(code, inactive); + let already_found = asm.jcc(Cond::Ne); + asm.alu_imm32( + Alu::Add, + Size::Qword, + Rcx, + i32::try_from(chunk * PREDICATE_CHUNK_BITS).unwrap(), + ); + store_stack(code, Rcx, first, QWORD_BYTES); + let mut asm = code.asm(); + asm.bind(already_found); + asm.bind(inactive); } - load_stack(code, RAX, end, NO_INDEX, 1, QWORD_BYTES); - code.extend(TEST_RAX_RAX); - let nonempty = branch(code, JNE_REL32); - store_stack(code, RAX, first, QWORD_BYTES); // Empty: first=end=0. - bind(code, nonempty); - load_stack(code, RCX, first, NO_INDEX, 1, QWORD_BYTES); - code.extend(SUB_RAX_RCX); - store_stack(code, RAX, end, QWORD_BYTES); // End slot now holds hull byte length. + load_stack(code, Rax, end, None, 1, QWORD_BYTES); + let mut asm = code.asm(); + asm.test(Size::Qword, Rax, Rax); + let nonempty = asm.jcc(Cond::Ne); + store_stack(code, Rax, first, QWORD_BYTES); // Empty: first=end=0. + code.asm().bind(nonempty); + load_stack(code, Rcx, first, None, 1, QWORD_BYTES); + code.asm().alu(Alu::Sub, Size::Qword, Rax, Rcx); + store_stack(code, Rax, end, QWORD_BYTES); // End slot now holds hull byte length. if length.bytes() == MAX_VECTOR_BYTES { if width <= ElementSize::Halfword.bytes() { copy_splice_rep(code, second, output, first, end, length.bytes()); @@ -605,51 +523,42 @@ fn emit_splice(code: &mut Vec, op: Splice, length: VectorLength, target: Tar } } else { for offset in (0..length.bytes()).step_by(width) { - load_stack(code, RAX, end, NO_INDEX, 1, QWORD_BYTES); - code.extend(CMP_RAX_IMM32); - code.extend(i32::try_from(offset).unwrap().to_le_bytes()); - let from_second = branch(code, JBE_REL32); - load_stack(code, RCX, first, NO_INDEX, 1, QWORD_BYTES); - load_stack(code, RAX, offset, RCX, 1, width); - let selected = branch(code, JUMP_REL32); - bind(code, from_second); - code.extend(NEG_RAX); - load_stack(code, RAX, second + offset, RAX, 1, width); - bind(code, selected); - store_stack(code, RAX, output + offset, width); + load_stack(code, Rax, end, None, 1, QWORD_BYTES); + let mut asm = code.asm(); + asm.alu_accumulator_imm32(Alu::Cmp, Size::Qword, i32::try_from(offset).unwrap()); + let from_second = asm.jcc(Cond::Be); + load_stack(code, Rcx, first, None, 1, QWORD_BYTES); + load_stack(code, Rax, offset, Some(Rcx), 1, width); + let selected = code.asm().jmp(); + let mut asm = code.asm(); + asm.bind(from_second); + asm.unary(Unary::Neg, Size::Qword, Rax); + load_stack(code, Rax, second + offset, Some(Rax), 1, width); + code.asm().bind(selected); + store_stack(code, Rax, output + offset, width); } } commit_z(code, op.destination, output, length, target); stack_adjust(code, frame_bytes, false); } -fn read_index_operand(code: &mut Vec, operand: IndexOperand, destination: u8) { - assert!(matches!(destination, RAX | RCX)); +fn read_index_operand(code: &mut Code, operand: IndexOperand, destination: Gpr) { + assert!(matches!(destination, Rax | Rcx)); + let mut asm = code.asm(); match operand { IndexOperand::Immediate(value) => { - code.extend(if destination == RAX { - MOV_RAX_IMM32 - } else { - MOV_RCX_IMM32 - }); - code.extend(i32::from(value).to_le_bytes()); + asm.mov_rm_imm32(Size::Qword, destination, i32::from(value)); + } + IndexOperand::Register(Register::Zero) => { + asm.alu(Alu::Xor, Size::Dword, destination, destination); } - IndexOperand::Register(Register::Zero) => code.extend(if destination == RAX { - XOR_EAX_EAX - } else { - XOR_ECX_ECX - }), IndexOperand::Register(Register::X(register)) => { assert!(register < 31); - code.extend([ - REX_QWORD, - MOV_LOAD, - MODRM_DISP32_RDI | (destination << REGISTER_SHIFT), - ]); - code.extend( - ((core::mem::offset_of!(GuestState, x) + usize::from(register) * QWORD_BYTES) - as u32) - .to_le_bytes(), + let offset = core::mem::offset_of!(GuestState, x) + usize::from(register) * QWORD_BYTES; + asm.mov_load( + Size::Qword, + destination, + Mem::base_disp32(Rdi, offset as i32), ); } IndexOperand::Register(Register::Sp) => unreachable!("INDEX register31 is ZR, never SP"), @@ -666,38 +575,58 @@ struct Index { /// SSE2 packed ramp: synthesize only the first16 bytes, broadcast the /// modulo-width chunk step, then use PADD B/H/S/D for each additional chunk. -fn emit_index(code: &mut Vec, op: Index, length: VectorLength, target: TargetCpu) { +fn emit_index(code: &mut Code, op: Index, length: VectorLength, target: TargetCpu) { let width = op.element_size.bytes(); assert!(width <= QWORD_BYTES); stack_adjust(code, VECTOR_CHUNK_BYTES, true); - read_index_operand(code, op.start, RAX); - read_index_operand(code, op.step, RCX); + read_index_operand(code, op.start, Rax); + read_index_operand(code, op.step, Rcx); for offset in (0..VECTOR_CHUNK_BYTES).step_by(width) { - store_stack(code, RAX, offset, width); + store_stack(code, Rax, offset, width); if offset + width < VECTOR_CHUNK_BYTES { - code.extend(ADD_RAX_RCX); + code.asm().alu(Alu::Add, Size::Qword, Rax, Rcx); } } xmm_stack(code, Host::LoadUnaligned, FIRST, 0, target); if length.chunks() > 1 { - code.extend(SHL_RCX_IMM8); - code.push((VECTOR_CHUNK_BYTES / width).trailing_zeros() as u8); - Host::MoveGprQword.register(code, SECOND, RCX, target); + let mut asm = code.asm(); + asm.shift_imm( + ShiftOp::Shl, + Size::Qword, + Rcx, + (VECTOR_CHUNK_BYTES / width).trailing_zeros() as u8, + ); + asm.simd(Host::MoveGprQword, SECOND, Rcx, target); match op.element_size { ElementSize::Byte => { Host::UnpackLowByte.register(code, SECOND, SECOND, target); Host::UnpackLowWord.register(code, SECOND, SECOND, target); - Host::ShuffleDword.register(code, SECOND, SECOND, target); - code.push(FIRST_DWORD); + code.asm().simd_imm( + Host::ShuffleDword, + SECOND, + Rm::Xmm(SECOND), + FIRST_DWORD, + target, + ); } ElementSize::Halfword => { Host::UnpackLowWord.register(code, SECOND, SECOND, target); - Host::ShuffleDword.register(code, SECOND, SECOND, target); - code.push(FIRST_DWORD); + code.asm().simd_imm( + Host::ShuffleDword, + SECOND, + Rm::Xmm(SECOND), + FIRST_DWORD, + target, + ); } ElementSize::Word => { - Host::ShuffleDword.register(code, SECOND, SECOND, target); - code.push(FIRST_DWORD); + code.asm().simd_imm( + Host::ShuffleDword, + SECOND, + Rm::Xmm(SECOND), + FIRST_DWORD, + target, + ); } ElementSize::Doubleword => Host::UnpackLowQword.register(code, SECOND, SECOND, target), ElementSize::Quadword => unreachable!("INDEX has no128-bit element allocation"), @@ -721,7 +650,7 @@ fn emit_index(code: &mut Vec, op: Index, length: VectorLength, target: Targe /// Complete validated Table/Splice/Index operands. The family dispatcher owns /// allocation and streaming-profile checks before calling this module. -pub(crate) fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { match operand { Operand::Table { destination, diff --git a/crates/stela-compiler/src/x86_64/sve/rearrange_extract.rs b/crates/stela-compiler/src/x86_64/sve/rearrange_extract.rs index b02b25dbbc..680c3ac4a6 100644 --- a/crates/stela-compiler/src/x86_64/sve/rearrange_extract.rs +++ b/crates/stela-compiler/src/x86_64/sve/rearrange_extract.rs @@ -1,4 +1,6 @@ //! SVE extraction and broadcast (SSE2) and insertion (SSSE3). +use crate::x86_64::asm::Gpr::{R8, Rax, Rcx, Rsp}; +use crate::x86_64::asm::{Alu, Code, Cond, Mem, Rm, Size}; use crate::{ TargetCpu, aarch64::{ @@ -19,7 +21,6 @@ const VALUE_XMM: u8 = 0; const INSERT_XMM: u8 = 1; const PREVIOUS_XMM: u8 = 2; const ZERO_XMM: u8 = 3; -const RAX_REGISTER: u8 = 0; const LOW_DWORD_CONTROL: u8 = 0; const PREDICATE_CHUNK_BITS: usize = u64::BITS as usize; const PREDICATE_CHUNK_BYTES: usize = core::mem::size_of::(); @@ -27,62 +28,27 @@ const STAGING_FRAME_BYTES: u8 = VECTOR_CHUNK_BYTES as u8; const CHUNK_OFFSET_MASK: u8 = (VECTOR_CHUNK_BYTES - 1) as u8; const GOVERNING_PREDICATE_COUNT: u8 = 8; const INDEXED_SOURCE_BYTES: usize = 64; -const JUMP_REL32: u8 = 0xe9; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const JB_REL32: &[u8] = &[0x0f, 0x82]; -const MOV_RAX_SIGNED_IMM32: &[u8] = &[0x48, 0xc7, 0xc0]; -const MOV_EAX_IMM32: u8 = 0xb8; -const MOV_RCX_IMM64: &[u8] = &[0x48, 0xb9]; -const AND_RAX_RCX: &[u8] = &[0x48, 0x21, 0xc8]; -const TEST_RAX_RAX: &[u8] = &[0x48, 0x85, 0xc0]; -const BSR_R8_RAX: &[u8] = &[0x4c, 0x0f, 0xbd, 0xc0]; -const OR_R8D_IMM32: &[u8] = &[0x41, 0x81, 0xc8]; -const ADD_R8D_IMM8: &[u8] = &[0x41, 0x83, 0xc0]; -const AND_R8D_IMM32: &[u8] = &[0x41, 0x81, 0xe0]; -const AND_R8D_IMM8: &[u8] = &[0x41, 0x83, 0xe0]; -const CMP_R8D_IMM32: &[u8] = &[0x41, 0x81, 0xf8]; -const MOV_R8D_IMM32: &[u8] = &[0x41, 0xb8]; -const XOR_R8D_R8D: &[u8] = &[0x45, 0x31, 0xc0]; -const SUB_RSP_IMM8: &[u8] = &[0x48, 0x83, 0xec]; -const ADD_RSP_IMM8: &[u8] = &[0x48, 0x83, 0xc4]; -const MOVDQU_STACK_XMM0: &[u8] = &[0xf3, 0x0f, 0x7f, 0x04, 0x24]; -const MOVZX_EAX_STACK_R8_BYTE: &[u8] = &[0x42, 0x0f, 0xb6, 0x04, 0x04]; -const MOVZX_EAX_STACK_R8_WORD: &[u8] = &[0x42, 0x0f, 0xb7, 0x04, 0x04]; -const MOV_EAX_STACK_R8: &[u8] = &[0x42, 0x8b, 0x04, 0x04]; -const MOV_RAX_STACK_R8: &[u8] = &[0x4a, 0x8b, 0x04, 0x04]; -const MOVZX_EAX_AL: &[u8] = &[0x0f, 0xb6, 0xc0]; -const MOVZX_EAX_AX: &[u8] = &[0x0f, 0xb7, 0xc0]; -const MOV_EAX_EAX: &[u8] = &[0x89, 0xc0]; -const NOP: u8 = 0x90; -fn jump(code: &mut Vec, opcode: &[u8]) -> usize { - code.extend_from_slice(opcode); - let displacement = code.len(); - code.extend(0i32.to_le_bytes()); - displacement -} - -fn resolve(code: &mut [u8], displacement: usize, target: usize) { - let next = displacement + core::mem::size_of::(); - let offset = i32::try_from(target as i64 - next as i64).expect("bounded extraction body"); - code[displacement..next].copy_from_slice(&offset.to_le_bytes()); -} - -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8, target: TargetCpu) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8, target: TargetCpu) { opcode.register(code, destination, source, target); } -fn narrow_general(code: &mut Vec, element: ElementSize) { - code.extend_from_slice(match element { - ElementSize::Byte => MOVZX_EAX_AL, - ElementSize::Halfword => MOVZX_EAX_AX, - ElementSize::Word => MOV_EAX_EAX, - ElementSize::Doubleword => &[], +fn narrow_general(code: &mut Code, element: ElementSize) { + let mut asm = code.asm(); + match element { + ElementSize::Byte => asm.movzx(Size::Dword, Rax, Size::Byte, Rax), + ElementSize::Halfword => asm.movzx(Size::Dword, Rax, Size::Word, Rax), + ElementSize::Word => asm.mov(Size::Dword, Rax, Rax), + ElementSize::Doubleword => {} ElementSize::Quadword => unreachable!("general extraction has at most 64 bits"), - }); + } } -fn broadcast(code: &mut Vec, element: ElementSize, target: TargetCpu) { +fn move_rax(code: &mut Code, register: u8, target: TargetCpu) { + code.asm().simd(Host::MoveGprQword, register, Rax, target); +} + +fn broadcast(code: &mut Code, element: ElementSize, target: TargetCpu) { match element { ElementSize::Byte => { packed(code, Host::UnpackLowByte, VALUE_XMM, VALUE_XMM, target); @@ -98,11 +64,16 @@ fn broadcast(code: &mut Vec, element: ElementSize, target: TargetCpu) { } ElementSize::Quadword => return, } - packed(code, Host::ShuffleDword, VALUE_XMM, VALUE_XMM, target); - code.push(LOW_DWORD_CONTROL); + code.asm().simd_imm( + Host::ShuffleDword, + VALUE_XMM, + Rm::Xmm(VALUE_XMM), + LOW_DWORD_CONTROL, + target, + ); } -fn broadcast_last(code: &mut Vec, element: ElementSize, target: TargetCpu) { +fn broadcast_last(code: &mut Code, element: ElementSize, target: TargetCpu) { if element == ElementSize::Byte && target.supports(TargetCpu::Ssse3) { packed(code, Host::Xor, ZERO_XMM, ZERO_XMM, target); packed(code, Host::ByteShuffle, VALUE_XMM, ZERO_XMM, target); @@ -111,7 +82,7 @@ fn broadcast_last(code: &mut Vec, element: ElementSize, target: TargetCpu) { } } -fn store_broadcast(code: &mut Vec, destination: u8, length: VectorLength, target: TargetCpu) { +fn store_broadcast(code: &mut Code, destination: u8, length: VectorLength, target: TargetCpu) { for chunk in 0..length.chunks() { store_z_chunk(code, destination, chunk, VALUE_XMM, length, target); } @@ -125,7 +96,7 @@ fn predicate_start_mask(element: ElementSize) -> u64 { mask } -fn emit_last(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +fn emit_last(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let Kind::Last { source, predicate, @@ -137,7 +108,7 @@ fn emit_last(code: &mut Vec, operand: Operand, length: VectorLength, target: }; if operand.destination == Destination::General(Register::Zero) { // Shared instruction permission checks still precede this recipe. - code.push(NOP); + code.asm().nop(); return; } let mut found = Vec::new(); @@ -146,114 +117,124 @@ fn emit_last(code: &mut Vec, operand: Operand, length: VectorLength, target: for chunk in (0..chunks).rev() { read_predicate_chunk(code, predicate, chunk, length); if operand.element_size != ElementSize::Byte { - code.extend(MOV_RCX_IMM64); - code.extend(predicate_start_mask(operand.element_size).to_le_bytes()); - code.extend(AND_RAX_RCX); + let mut asm = code.asm(); + asm.mov_imm64(Rcx, predicate_start_mask(operand.element_size)); + asm.alu(Alu::And, Size::Qword, Rax, Rcx); } - code.extend(TEST_RAX_RAX); - let empty = jump(code, JZ_REL32); - code.extend(BSR_R8_RAX); + let mut asm = code.asm(); + asm.test(Size::Qword, Rax, Rax); + let empty = asm.jcc(Cond::E); + asm.bsr(Size::Qword, R8, Rax); if chunk != 0 { - code.extend(OR_R8D_IMM32); - code.extend(((chunk * PREDICATE_CHUNK_BITS) as u32).to_le_bytes()); + asm.alu_imm32( + Alu::Or, + Size::Dword, + R8, + (chunk * PREDICATE_CHUNK_BITS) as i32, + ); } - found.push(jump(code, &[JUMP_REL32])); - let next = code.len(); - resolve(code, empty, next); + found.push(asm.jmp()); + asm.bind(empty); } let mut scalar_fallback = None; let mut unconditional_fallback = None; if conditional { match operand.destination { - Destination::Vector(_) => finished.push(jump(code, &[JUMP_REL32])), + Destination::Vector(_) => finished.push(code.asm().jmp()), Destination::General(destination) => { load(code, destination); narrow_general(code, operand.element_size); store(code, destination); - finished.push(jump(code, &[JUMP_REL32])); + finished.push(code.asm().jmp()); } Destination::Scalar(destination) => { load_z_chunk(code, destination, 0, VALUE_XMM, length, target); - code.extend(XOR_R8D_R8D); - scalar_fallback = Some(jump(code, &[JUMP_REL32])); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, R8, R8); + scalar_fallback = Some(asm.jmp()); } } } else { - code.extend(MOV_R8D_IMM32); let offset = if position == LastPosition::LastActive { length.bytes() - operand.element_size.bytes() } else { 0 }; - code.extend((offset as u32).to_le_bytes()); - unconditional_fallback = Some(jump(code, &[JUMP_REL32])); + let mut asm = code.asm(); + asm.mov_imm32(R8, offset as u32); + unconditional_fallback = Some(asm.jmp()); } - let active = code.len(); + let mut asm = code.asm(); for branch in found { - resolve(code, branch, active); + asm.bind(branch); } if position == LastPosition::AfterLastActive { - code.extend(ADD_R8D_IMM8); - code.push(operand.element_size.bytes() as u8); - code.extend(AND_R8D_IMM32); - code.extend(((length.bytes() - 1) as u32).to_le_bytes()); + asm.alu_imm8( + Alu::Add, + Size::Dword, + R8, + operand.element_size.bytes() as i8, + ); + asm.alu_imm32(Alu::And, Size::Dword, R8, (length.bytes() - 1) as i32); } - let select = code.len(); if let Some(branch) = unconditional_fallback { - resolve(code, branch, select); + asm.bind(branch); } let mut loaded = Vec::new(); for chunk in (1..length.chunks()).rev() { - code.extend(CMP_R8D_IMM32); - code.extend(((chunk * VECTOR_CHUNK_BYTES) as u32).to_le_bytes()); - let lower = jump(code, JB_REL32); + let mut asm = code.asm(); + asm.alu_imm32( + Alu::Cmp, + Size::Dword, + R8, + (chunk * VECTOR_CHUNK_BYTES) as i32, + ); + let lower = asm.jcc(Cond::B); load_z_chunk(code, source, chunk, VALUE_XMM, length, target); - loaded.push(jump(code, &[JUMP_REL32])); - let next = code.len(); - resolve(code, lower, next); + let mut asm = code.asm(); + loaded.push(asm.jmp()); + asm.bind(lower); } load_z_chunk(code, source, 0, VALUE_XMM, length, target); - let staging = code.len(); + let mut asm = code.asm(); for branch in loaded.into_iter().chain(scalar_fallback) { - resolve(code, branch, staging); + asm.bind(branch); } - code.extend(AND_R8D_IMM8); - code.push(CHUNK_OFFSET_MASK); + asm.alu_imm8(Alu::And, Size::Dword, R8, CHUNK_OFFSET_MASK as i8); // Only the selected 16-byte chunk is staged, in the same bounded frame for // every path. - code.extend(SUB_RSP_IMM8); - code.push(STAGING_FRAME_BYTES); - code.extend(MOVDQU_STACK_XMM0); - code.extend_from_slice(match operand.element_size { - ElementSize::Byte => MOVZX_EAX_STACK_R8_BYTE, - ElementSize::Halfword => MOVZX_EAX_STACK_R8_WORD, - ElementSize::Word => MOV_EAX_STACK_R8, - ElementSize::Doubleword => MOV_RAX_STACK_R8, + asm.alu_imm8(Alu::Sub, Size::Qword, Rsp, STAGING_FRAME_BYTES as i8); + asm.movdqu_store(Mem::base(Rsp, 0), 0); + let lane = Mem::indexed(Rsp, R8, 1, 0); + match operand.element_size { + ElementSize::Byte => asm.movzx(Size::Dword, Rax, Size::Byte, lane), + ElementSize::Halfword => asm.movzx(Size::Dword, Rax, Size::Word, lane), + ElementSize::Word => asm.mov_load(Size::Dword, Rax, lane), + ElementSize::Doubleword => asm.mov_load(Size::Qword, Rax, lane), ElementSize::Quadword => unreachable!("LAST excludes 128-bit elements"), - }); - code.extend(ADD_RSP_IMM8); - code.push(STAGING_FRAME_BYTES); + } + asm.alu_imm8(Alu::Add, Size::Qword, Rsp, STAGING_FRAME_BYTES as i8); match operand.destination { Destination::General(destination) => store(code, destination), Destination::Scalar(destination) => { - packed(code, Host::MoveGprQword, VALUE_XMM, RAX_REGISTER, target); + move_rax(code, VALUE_XMM, target); store_z_chunk(code, destination, 0, VALUE_XMM, length, target); clear_z_upper(code, destination, ZERO_XMM, length, target); } Destination::Vector(destination) => { - packed(code, Host::MoveGprQword, VALUE_XMM, RAX_REGISTER, target); + move_rax(code, VALUE_XMM, target); broadcast_last(code, operand.element_size, target); store_broadcast(code, destination, length, target); } } - let end = code.len(); + let mut asm = code.asm(); for branch in finished { - resolve(code, branch, end); + asm.bind(branch); } } fn emit_insert( - code: &mut Vec, + code: &mut Code, destination: u8, element: ElementSize, length: VectorLength, @@ -265,8 +246,13 @@ fn emit_insert( load_z_chunk(code, destination, chunk, VALUE_XMM, length, target); load_z_chunk(code, destination, chunk - 1, PREVIOUS_XMM, length, target); if target.supports(TargetCpu::Ssse3) { - packed(code, Host::AlignBytes, VALUE_XMM, PREVIOUS_XMM, target); - code.push(carry); + code.asm().simd_imm( + Host::AlignBytes, + VALUE_XMM, + Rm::Xmm(PREVIOUS_XMM), + carry, + target, + ); } else { Shift::LeftBytes.emit(code, VALUE_XMM, width); Shift::RightBytes.emit(code, PREVIOUS_XMM, carry); @@ -333,7 +319,7 @@ fn valid(operand: Operand) -> bool { /// Emit a decoded register-only operation after shared streaming permission checks. /// Uses caller-saved RAX/RCX/RDX/R8 and XMM0..3, preserving RDI/R15 and MXCSR. -pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { assert!( valid(operand), "extraction emitter requires validated operands" @@ -347,17 +333,17 @@ pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: }; match operand.kind { Kind::DuplicateImmediate(immediate) => { + let mut asm = code.asm(); if operand.element_size == ElementSize::Doubleword { - code.extend(MOV_RAX_SIGNED_IMM32); + asm.mov_rm_imm32(Size::Qword, Rax, i32::from(immediate)); } else { - code.push(MOV_EAX_IMM32); + asm.mov_imm32(Rax, i32::from(immediate) as u32); } - code.extend(i32::from(immediate).to_le_bytes()); - packed(code, Host::MoveGprQword, VALUE_XMM, RAX_REGISTER, target); + move_rax(code, VALUE_XMM, target); } Kind::DuplicateGeneral(source) => { load(code, source); - packed(code, Host::MoveGprQword, VALUE_XMM, RAX_REGISTER, target); + move_rax(code, VALUE_XMM, target); } Kind::DuplicateElement { source, index } => { let offset = usize::from(index) * operand.element_size.bytes(); @@ -380,7 +366,7 @@ pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: Kind::InsertGeneral(source) => { load(code, source); narrow_general(code, operand.element_size); - packed(code, Host::MoveGprQword, INSERT_XMM, RAX_REGISTER, target); + move_rax(code, INSERT_XMM, target); emit_insert(code, destination, operand.element_size, length, target); return; } diff --git a/crates/stela-compiler/src/x86_64/sve/rearrange_widen.rs b/crates/stela-compiler/src/x86_64/sve/rearrange_widen.rs index 6b1e2cf1fa..e0ffb7deb9 100644 --- a/crates/stela-compiler/src/x86_64/sve/rearrange_widen.rs +++ b/crates/stela-compiler/src/x86_64/sve/rearrange_widen.rs @@ -6,10 +6,11 @@ use crate::aarch64::sve::integer_arithmetic::Binary; use crate::aarch64::sve::rearrange_widen::{ Arithmetic, Half, Kind, Operand, PairOperation, Signedness, }; +use crate::x86_64::asm::Gpr::Rax; +use crate::x86_64::asm::{Code, Rm}; use crate::x86_64::isa::{ShiftOpcode, SimdOpcode as Host}; use crate::x86_64::scalable::{load_z_chunk, read_predicate_mask, store_z_chunk}; use crate::x86_64::sve::integer_arithmetic::emit_binary_chunk; -use alloc::vec::Vec; const RESULT: u8 = 0; const RIGHT: u8 = 1; @@ -23,9 +24,6 @@ const QWORD_BYTES: usize = 8; const QWORD_BITS: usize = QWORD_BYTES * 8; const DWORD_BITS: u8 = 32; const DWORD_SIGN_SHIFT: u8 = DWORD_BITS - 1; -const MODRM_REGISTER: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; -const MOVABS_RAX: [u8; 2] = [0x48, 0xb8]; const SELECT_EVEN_DWORDS: u8 = 0x88; const SELECT_ODD_DWORDS: u8 = 0xdd; const REPEAT_HIGH_DWORDS: u8 = 0xf5; @@ -36,27 +34,26 @@ const LOW_DWORD_MASK: u64 = 0x0000_0000_ffff_ffff; const BYTE_WEIGHTS: u64 = 0x0101_0101_0101_0101; const WORD_WEIGHTS: u64 = 0x0001_0001_0001_0001; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn copy(code: &mut Vec, destination: u8, source: u8) { +fn copy(code: &mut Code, destination: u8, source: u8) { packed(code, Host::MoveAligned, destination, source); } -fn qword_constant(code: &mut Vec, destination: u8, value: u64) { - code.extend(MOVABS_RAX); - code.extend(value.to_le_bytes()); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(MODRM_REGISTER | destination << REGISTER_SHIFT); +fn qword_constant(code: &mut Code, destination: u8, value: u64) { + code.asm().mov_imm64(Rax, value); + code.asm() + .simd(Host::MoveGprQword, destination, Rax, TargetCpu::Baseline); } -fn constant(code: &mut Vec, destination: u8, value: u64) { +fn constant(code: &mut Code, destination: u8, value: u64) { qword_constant(code, destination, value); packed(code, Host::UnpackLowQword, destination, destination); } -fn constant_bytes(code: &mut Vec, destination: u8, value: [u8; VECTOR_CHUNK_BYTES]) { +fn constant_bytes(code: &mut Code, destination: u8, value: [u8; VECTOR_CHUNK_BYTES]) { let low = u64::from_le_bytes(value[..QWORD_BYTES].try_into().unwrap()); let high = u64::from_le_bytes(value[QWORD_BYTES..].try_into().unwrap()); qword_constant(code, destination, low); @@ -110,12 +107,17 @@ fn right_shift(element: ElementSize) -> ShiftOpcode { } } -fn shuffle(code: &mut Vec, destination: u8, source: u8, immediate: u8) { - packed(code, Host::ShuffleDword, destination, source); - code.push(immediate); +fn shuffle(code: &mut Code, destination: u8, source: u8, immediate: u8) { + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(source), + immediate, + TargetCpu::Baseline, + ); } -fn signed_qword(code: &mut Vec, destination: u8, input_size: ElementSize, target: TargetCpu) { +fn signed_qword(code: &mut Code, destination: u8, input_size: ElementSize, target: TargetCpu) { if target.supports(TargetCpu::Sse41) { if input_size != ElementSize::Word { let shift = (ElementSize::Word.bits() - input_size.bits()) as u8; @@ -136,7 +138,7 @@ fn signed_qword(code: &mut Vec, destination: u8, input_size: ElementSize, ta } fn extension( - code: &mut Vec, + code: &mut Code, element: ElementSize, input_size: ElementSize, signedness: Signedness, @@ -165,7 +167,7 @@ fn extension( .emit(code, RESULT, shift); } -fn unpack(code: &mut Vec, element: ElementSize, signedness: Signedness, target: TargetCpu) { +fn unpack(code: &mut Code, element: ElementSize, signedness: Signedness, target: TargetCpu) { let checked = match (element, signedness) { (ElementSize::Word, Signedness::Signed) => Some(Host::SignExtendWordToDword), (ElementSize::Word, Signedness::Unsigned) => Some(Host::ZeroExtendWordToDword), @@ -204,13 +206,7 @@ fn unpack(code: &mut Vec, element: ElementSize, signedness: Signedness, targ ); } -fn narrow( - code: &mut Vec, - element: ElementSize, - arithmetic: Arithmetic, - round: bool, - half: Half, -) { +fn narrow(code: &mut Code, element: ElementSize, arithmetic: Arithmetic, round: bool, half: Half) { packed( code, if arithmetic == Arithmetic::Add { @@ -234,7 +230,7 @@ fn narrow( } } -fn signed_pair_dwords(code: &mut Vec, target: TargetCpu) { +fn signed_pair_dwords(code: &mut Code, target: TargetCpu) { copy(code, RIGHT, RESULT); if target.supports(TargetCpu::Sse41) { shuffle(code, RESULT, RESULT, SELECT_EVEN_DWORDS); @@ -259,7 +255,7 @@ fn signed_pair_dwords(code: &mut Vec, target: TargetCpu) { packed(code, Host::SubQword, RESULT, AUXILIARY); } -fn pair_delta(code: &mut Vec, element: ElementSize, signedness: Signedness, target: TargetCpu) { +fn pair_delta(code: &mut Code, element: ElementSize, signedness: Signedness, target: TargetCpu) { if element == ElementSize::Halfword && target.supports(TargetCpu::Ssse3) { if signedness == Signedness::Signed { // Unsigned weights times signed data: saturation cannot occur. @@ -292,7 +288,7 @@ fn pair_delta(code: &mut Vec, element: ElementSize, signedness: Signedness, packed(code, add(element), RESULT, RIGHT); } -fn gather_even_odd(code: &mut Vec, register: u8, element: ElementSize, target: TargetCpu) { +fn gather_even_odd(code: &mut Code, register: u8, element: ElementSize, target: TargetCpu) { if target.supports(TargetCpu::Ssse3) { Host::ByteShuffle.register(code, register, CONSTANT, target); } else if element == ElementSize::Byte { @@ -302,15 +298,25 @@ fn gather_even_odd(code: &mut Vec, register: u8, element: ElementSize, targe // Every input word is 0..255, so PACKUSWB never saturates. packed(code, Host::PackUnsignedWordToByte, register, TEMPORARY); } else { - Host::ShuffleLowWord.register(code, register, register, target); - code.push(EVEN_ODD_WORD_GROUPS); - Host::ShuffleHighWord.register(code, register, register, target); - code.push(EVEN_ODD_WORD_GROUPS); + code.asm().simd_imm( + Host::ShuffleLowWord, + register, + Rm::Xmm(register), + EVEN_ODD_WORD_GROUPS, + target, + ); + code.asm().simd_imm( + Host::ShuffleHighWord, + register, + Rm::Xmm(register), + EVEN_ODD_WORD_GROUPS, + target, + ); shuffle(code, register, register, EVEN_ODD_WORD_GROUPS); } } -fn pair_inputs(code: &mut Vec, element: ElementSize, target: TargetCpu) { +fn pair_inputs(code: &mut Code, element: ElementSize, target: TargetCpu) { if matches!(element, ElementSize::Byte | ElementSize::Halfword) { if target.supports(TargetCpu::Ssse3) { let mut shuffle_bytes = [0; VECTOR_CHUNK_BYTES]; @@ -348,7 +354,7 @@ fn pair_inputs(code: &mut Vec, element: ElementSize, target: TargetCpu) { } } -fn pair(code: &mut Vec, element: ElementSize, operation: PairOperation, target: TargetCpu) { +fn pair(code: &mut Code, element: ElementSize, operation: PairOperation, target: TargetCpu) { if operation == PairOperation::Add && element == ElementSize::Word && target.supports(TargetCpu::Ssse3) @@ -371,7 +377,7 @@ fn pair(code: &mut Vec, element: ElementSize, operation: PairOperation, targ } fn merge( - code: &mut Vec, + code: &mut Code, predicate: u8, chunk: usize, operand: Operand, @@ -417,7 +423,7 @@ fn recipe_target(operand: Operand, length: VectorLength, target: TargetCpu) -> T } } -pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let target = recipe_target(operand, length, target); if let Kind::Unpack { source, diff --git a/crates/stela-compiler/src/x86_64/sve/reductions.rs b/crates/stela-compiler/src/x86_64/sve/reductions.rs index 200178e72d..7f649627a2 100644 --- a/crates/stela-compiler/src/x86_64/sve/reductions.rs +++ b/crates/stela-compiler/src/x86_64/sve/reductions.rs @@ -2,9 +2,10 @@ use crate::TargetCpu; use crate::aarch64::scalable::{ElementSize, VECTOR_CHUNK_BYTES, VectorLength}; use crate::aarch64::sve::reductions::{Kind, Operand, Output}; +use crate::x86_64::asm::Gpr::{R8, R9, Rax}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, Size}; use crate::x86_64::isa::{ShiftOpcode, SimdOpcode as Host}; use crate::x86_64::scalable::{clear_z_upper, load_z_chunk, read_predicate_mask, store_z_chunk}; -use alloc::vec::Vec; const RESULT: u8 = 0; const SOURCE: u8 = 1; @@ -14,39 +15,16 @@ const NEUTRAL: u8 = 4; const CONSTANT: u8 = 5; const PREDICATE: u8 = 6; const PREDICATE_SCRATCH: u8 = 7; -const REGISTER_MODE: u8 = 0xc0; -const REGISTER_SHIFT: u8 = 3; const QWORD_BYTES: usize = core::mem::size_of::(); const DWORD_BYTES: usize = core::mem::size_of::(); -const R8_FIELD: u8 = 0; -const R9_FIELD: u8 = 1; const WORD_ONES: u64 = 0x0001_0001_0001_0001; const WORD_ONES_SHIFT: u8 = (u16::BITS - 1) as u8; -const MOVABS_RAX: &[u8] = &[0x48, 0xb8]; -const MOVQ_RAX_XMM: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const MOVD_EAX_XMM: &[u8] = &[0x66, 0x0f, 0x7e]; -const MOVSXD_RAX_EAX: &[u8] = &[0x48, 0x63, 0xc0]; -const MOVZX_EAX_AL: &[u8] = &[0x0f, 0xb6, 0xc0]; -const MOVZX_EAX_AX: &[u8] = &[0x0f, 0xb7, 0xc0]; -const MOVQ_XMM_EXTENDED_GPR: &[u8] = &[0x66, 0x49, 0x0f, 0x6e]; -const MOVQ_EXTENDED_GPR_XMM: &[u8] = &[0x66, 0x49, 0x0f, 0x7e]; -const CMP_R8_RAX: &[u8] = &[0x49, 0x39, 0xc0]; -const CMP_R9_RAX: &[u8] = &[0x49, 0x39, 0xc1]; -const CMP_R8_R9: &[u8] = &[0x4d, 0x39, 0xc8]; -const CMOV_R8_RAX: &[u8] = &[0x4c, 0x0f]; -const CMOV_R9_RAX: &[u8] = &[0x4c, 0x0f]; -const CMOV_R8_R9: &[u8] = &[0x4d, 0x0f]; -const CMOV_BELOW: u8 = 0x42; -const CMOV_ABOVE: u8 = 0x47; -const CMOV_LESS: u8 = 0x4c; -const CMOV_GREATER: u8 = 0x4f; -const PSADBW: &[u8] = &[0x66, 0x0f, 0xf6]; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8, target: TargetCpu) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8, target: TargetCpu) { opcode.register(code, destination, source, target); } -fn constant(code: &mut Vec, destination: u8, value: u64) { +fn constant(code: &mut Code, destination: u8, value: u64) { match value { u64::MAX => { packed( @@ -71,10 +49,9 @@ fn constant(code: &mut Vec, destination: u8, value: u64) { } _ => {} } - code.extend(MOVABS_RAX); - code.extend(value.to_le_bytes()); - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(REGISTER_MODE | destination << REGISTER_SHIFT); + let mut asm = code.asm(); + asm.mov_imm64(Rax, value); + asm.simd(Host::MoveGprQword, destination, Rax, TargetCpu::Baseline); packed( code, Host::UnpackLowQword, @@ -178,7 +155,7 @@ fn reduction_opcode(kind: Kind, element: ElementSize, target: TargetCpu) -> Opti } /// XMM0/XMM1 hold accumulator and next lanes. Compare/select consumes XMM3. -fn combine(code: &mut Vec, kind: Kind, element: ElementSize, target: TargetCpu) { +fn combine(code: &mut Code, kind: Kind, element: ElementSize, target: TargetCpu) { if let Some(opcode) = reduction_opcode(kind, element, target) { packed(code, opcode, RESULT, SOURCE, target); return; @@ -195,7 +172,7 @@ fn combine(code: &mut Vec, kind: Kind, element: ElementSize, target: TargetC packed(code, Host::Or, RESULT, SIGN, target); } -fn mask_source(code: &mut Vec, neutral_nonzero: bool, target: TargetCpu) { +fn mask_source(code: &mut Code, neutral_nonzero: bool, target: TargetCpu) { packed(code, Host::And, SOURCE, PREDICATE, target); if neutral_nonzero { packed(code, Host::AndNot, PREDICATE, NEUTRAL, target); @@ -203,11 +180,10 @@ fn mask_source(code: &mut Vec, neutral_nonzero: bool, target: TargetCpu) { } } -fn sum_chunk(code: &mut Vec, kind: Kind, element: ElementSize, target: TargetCpu) { +fn sum_chunk(code: &mut Code, kind: Kind, element: ElementSize, target: TargetCpu) { let signed = kind == Kind::SignedAdd; if element == ElementSize::Byte && !signed { - code.extend(PSADBW); - code.push(REGISTER_MODE | SOURCE << REGISTER_SHIFT | NEUTRAL); + code.asm().psadbw(SOURCE, Rm::Xmm(NEUTRAL)); packed(code, Host::AddQword, RESULT, SOURCE, target); return; } @@ -259,55 +235,48 @@ fn sum_chunk(code: &mut Vec, kind: Kind, element: ElementSize, target: Targe packed(code, add, RESULT, SOURCE, target); } -fn scalar_result(code: &mut Vec, element: ElementSize, sign_extend: bool) { - code.extend(if element == ElementSize::Doubleword { - MOVQ_RAX_XMM +fn scalar_result(code: &mut Code, element: ElementSize, sign_extend: bool) { + let mut asm = code.asm(); + if element == ElementSize::Doubleword { + asm.movq_from_xmm(Rax, RESULT); } else { - MOVD_EAX_XMM - }); - code.push(REGISTER_MODE | RESULT << REGISTER_SHIFT); + asm.movd_from_xmm(Rax, RESULT); + } match element { - ElementSize::Byte => code.extend(MOVZX_EAX_AL), - ElementSize::Halfword => code.extend(MOVZX_EAX_AX), - ElementSize::Word if sign_extend => code.extend(MOVSXD_RAX_EAX), + ElementSize::Byte => asm.movzx(Size::Dword, Rax, Size::Byte, Rax), + ElementSize::Halfword => asm.movzx(Size::Dword, Rax, Size::Word, Rax), + ElementSize::Word if sign_extend => asm.movsxd(Rax, Rax), _ => {} } - Host::MoveGprQword.append(code, TargetCpu::Baseline); - code.push(REGISTER_MODE | RESULT << REGISTER_SHIFT); + asm.simd(Host::MoveGprQword, RESULT, Rax, TargetCpu::Baseline); } -fn conditional_move(kind: Kind) -> u8 { +fn conditional_move(kind: Kind) -> Cond { match (is_signed(kind), is_minimum(kind)) { - (true, true) => CMOV_GREATER, - (true, false) => CMOV_LESS, - (false, true) => CMOV_ABOVE, - (false, false) => CMOV_BELOW, + (true, true) => Cond::G, + (true, false) => Cond::L, + (false, true) => Cond::A, + (false, false) => Cond::B, } } -fn seed_qword_columns(code: &mut Vec) { - for destination in [R8_FIELD, R9_FIELD] { - code.extend(MOVQ_EXTENDED_GPR_XMM); - code.push(REGISTER_MODE | SOURCE << REGISTER_SHIFT | destination); - if destination == R8_FIELD { +fn seed_qword_columns(code: &mut Code) { + for destination in [R8, R9] { + code.asm().movq_from_xmm(destination, SOURCE); + if destination == R8 { ShiftOpcode::RightBytes.emit(code, SOURCE, QWORD_BYTES as u8); } } } -fn combine_qword_columns(code: &mut Vec, kind: Kind) { +fn combine_qword_columns(code: &mut Code, kind: Kind) { let condition = conditional_move(kind); - for (compare, move_prefix, destination) in [ - (CMP_R8_RAX, CMOV_R8_RAX, R8_FIELD), - (CMP_R9_RAX, CMOV_R9_RAX, R9_FIELD), - ] { - code.extend(MOVQ_RAX_XMM); - code.push(REGISTER_MODE | SOURCE << REGISTER_SHIFT); - code.extend(compare); - code.extend(move_prefix); - code.push(condition); - code.push(REGISTER_MODE | destination << REGISTER_SHIFT); - if destination == R8_FIELD { + for destination in [R8, R9] { + let mut asm = code.asm(); + asm.movq_from_xmm(Rax, SOURCE); + asm.alu(Alu::Cmp, Size::Qword, destination, Rax); + asm.cmov(condition, Size::Qword, destination, Rax); + if destination == R8 { ShiftOpcode::RightBytes.emit(code, SOURCE, QWORD_BYTES as u8); } } @@ -315,7 +284,7 @@ fn combine_qword_columns(code: &mut Vec, kind: Kind) { /// Complete ordinary data effects. All source chunks precede any destination /// writes, including Vd==Zn. Integer operations leave guest status unchanged. -pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let sum = operand.output == Output::Scalar && is_sum(operand.kind); let qword_extrema = matches!( operand.kind, @@ -382,16 +351,13 @@ pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: } if qword_columns { if operand.output == Output::Scalar { - code.extend(CMP_R8_R9); - code.extend(CMOV_R8_R9); - code.push(conditional_move(operand.kind)); - code.push(REGISTER_MODE | R9_FIELD); + let mut asm = code.asm(); + asm.alu(Alu::Cmp, Size::Qword, R8, R9); + asm.cmov(conditional_move(operand.kind), Size::Qword, R8, R9); } - code.extend(MOVQ_XMM_EXTENDED_GPR); - code.push(REGISTER_MODE | RESULT << REGISTER_SHIFT); + code.asm().movq_to_xmm(RESULT, R8); if operand.output == Output::Quadword { - code.extend(MOVQ_XMM_EXTENDED_GPR); - code.push(REGISTER_MODE | TEMPORARY << REGISTER_SHIFT | R9_FIELD); + code.asm().movq_to_xmm(TEMPORARY, R9); packed(code, Host::UnpackLowQword, RESULT, TEMPORARY, target); } } else { diff --git a/crates/stela-compiler/src/x86_64/sve/shifts.rs b/crates/stela-compiler/src/x86_64/sve/shifts.rs index 55bd59294d..c8b469c0f0 100644 --- a/crates/stela-compiler/src/x86_64/sve/shifts.rs +++ b/crates/stela-compiler/src/x86_64/sve/shifts.rs @@ -1,4 +1,6 @@ //! SVE shifts. Scalar recipes use host flags only as scratch. +use crate::x86_64::asm::Gpr::{Rax, Rsp}; +use crate::x86_64::asm::{Alu, Code, Mem, Size}; use crate::{ TargetCpu, aarch64::{ @@ -11,22 +13,40 @@ use crate::{ simd::shifts::{logical_shift, right_shift, rounded_right}, }, }; -use alloc::vec::Vec; mod saturating; mod scalar; mod variable; pub(crate) use scalar::rounding_variable_chunk; -const SUB_RSP_IMM8: [u8; 3] = [0x48, 0x83, 0xec]; -const ADD_RSP_IMM8: [u8; 3] = [0x48, 0x83, 0xc4]; const BITS_PER_BYTE: u8 = 8; const PACKED_SATURATION_VECTOR_BYTES: usize = 256; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8, target: TargetCpu) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8, target: TargetCpu) { opcode.register(code, destination, source, target); } +/// Load `value` repeated in each `element` lane of `xmm`, through RAX. +pub(super) fn repeated_constant(code: &mut Code, xmm: u8, element: ElementSize, value: u64) { + let limbs = value.to_le_bytes(); + let repeated: [u8; core::mem::size_of::()] = + core::array::from_fn(|i| limbs[i % element.bytes()]); + let mut asm = code.asm(); + asm.mov_imm64(Rax, u64::from_le_bytes(repeated)); + asm.simd(Host::MoveGprQword, xmm, Rax, TargetCpu::Baseline); + packed(code, Host::UnpackLowQword, xmm, xmm, TargetCpu::Baseline); +} + +/// Store `xmm` to, or load it from, the stack slot at RSP + `slot`. +pub(super) fn stack_vector(code: &mut Code, xmm: u8, slot: u8, store: bool) { + let slot = Mem::base_disp8(Rsp, slot as i8); + if store { + code.asm().movdqu_store(slot, xmm); + } else { + code.asm().movdqu_load(xmm, slot); + } +} + #[derive(Clone, Copy)] enum Mapping { Immediate, @@ -73,14 +93,14 @@ pub(crate) fn requires_declared_dit_zero(operand: Operand, length: VectorLength) && matches!(mapping(operand, length), Mapping::Scalar) } -fn adjust_stack(code: &mut Vec, bytes: u8, allocate: bool) { +fn adjust_stack(code: &mut Code, bytes: u8, allocate: bool) { if bytes != 0 { - code.extend(if allocate { SUB_RSP_IMM8 } else { ADD_RSP_IMM8 }); - code.push(bytes); + let op = if allocate { Alu::Sub } else { Alu::Add }; + code.asm().alu_imm8(op, Size::Qword, Rsp, bytes as i8); } } -pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let mapping = mapping(operand, length); let avx2 = variable::avx2_opcode(operand.kind, operand.element_size, operand.count, target); let scratch = match (avx2, mapping) { @@ -141,7 +161,7 @@ pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: adjust_stack(code, scratch, false); } -fn immediate_chunk(code: &mut Vec, operand: Operand, target: TargetCpu) { +fn immediate_chunk(code: &mut Code, operand: Operand, target: TargetCpu) { let Count::Immediate(amount) = operand.count else { unreachable!() }; @@ -214,7 +234,6 @@ fn immediate_chunk(code: &mut Vec, operand: Operand, target: TargetCpu) { #[cfg(test)] mod tests { use super::*; - use alloc::vec::Vec; fn variable_operand(element_size: ElementSize, kind: Kind) -> Operand { Operand { @@ -233,8 +252,8 @@ mod tests { fn avx2_variable_shift_body_replaces_scalar_scratch_without_widening_state_access() { let length = VectorLength::from_bytes(64).unwrap(); let operand = variable_operand(ElementSize::Word, Kind::LogicalLeft); - let mut baseline = Vec::new(); - let mut avx2 = Vec::new(); + let mut baseline = Code::new(); + let mut avx2 = Code::new(); emit(&mut baseline, operand, length, TargetCpu::Baseline); emit(&mut avx2, operand, length, TargetCpu::Avx2); assert!(baseline.starts_with(&[0x48, 0x83, 0xec, scalar::STACK_BYTES])); @@ -251,8 +270,8 @@ mod tests { assert!(requires_declared_dit_zero(operand, length)); let excluded = variable_operand(ElementSize::Doubleword, Kind::ArithmeticRight); - baseline.clear(); - avx2.clear(); + baseline = Code::new(); + avx2 = Code::new(); emit(&mut baseline, excluded, length, TargetCpu::Baseline); emit(&mut avx2, excluded, length, TargetCpu::Avx2); assert_eq!(baseline, avx2); diff --git a/crates/stela-compiler/src/x86_64/sve/shifts/saturating.rs b/crates/stela-compiler/src/x86_64/sve/shifts/saturating.rs index 2ba53f3249..edca9d630b 100644 --- a/crates/stela-compiler/src/x86_64/sve/shifts/saturating.rs +++ b/crates/stela-compiler/src/x86_64/sve/shifts/saturating.rs @@ -1,44 +1,23 @@ //! SVE saturating shifts by signed counts. +use super::{repeated_constant, stack_vector}; +use crate::x86_64::asm::{Code, Rm}; use crate::{ TargetCpu, aarch64::{scalable::ElementSize, sve::shifts::Kind}, x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host}, }; -use alloc::vec::Vec; -const MOV_RAX_IMM64: [u8; 2] = [0x48, 0xb8]; const SOURCE_SLOT: u8 = 0; const COUNTS_SLOT: u8 = 16; const LEFT_SLOT: u8 = 32; const QUOTIENT_SLOT: u8 = 48; pub(super) const STACK_BYTES: u8 = 64; -const MODRM_STACK_DISP8: u8 = 0x44; -const STACK_SIB: u8 = 0x24; -const MOVDQU_LOAD_RSP: [u8; 3] = [0xf3, 0x0f, 0x6f]; -const MOVDQU_STORE_RSP: [u8; 3] = [0xf3, 0x0f, 0x7f]; const DWORD_SIGN_SHIFT: u8 = u32::BITS as u8 - 1; const WORD_SIGN_SHIFT: u8 = u16::BITS as u8 - 1; const DUPLICATE_HIGH_DWORDS: u8 = 0xf5; const ADJACENT_DWORDS: u8 = 0xb1; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn constant(code: &mut Vec, xmm: u8, element: ElementSize, value: u64) { - let limbs = value.to_le_bytes(); - let repeated: [u8; core::mem::size_of::()] = - core::array::from_fn(|i| limbs[i % element.bytes()]); - code.extend(MOV_RAX_IMM64); - code.extend(repeated); - packed(code, Host::MoveGprQword, xmm, 0); - packed(code, Host::UnpackLowQword, xmm, xmm); -} -fn stack_vector(code: &mut Vec, xmm: u8, slot: u8, store: bool) { - code.extend(if store { - MOVDQU_STORE_RSP - } else { - MOVDQU_LOAD_RSP - }); - code.extend([MODRM_STACK_DISP8 | xmm << 3, STACK_SIB, slot]); -} fn add(element: ElementSize) -> Host { match element { ElementSize::Byte => Host::AddByte, @@ -57,7 +36,7 @@ fn subtract(element: ElementSize) -> Host { _ => unreachable!(), } } -fn sign_mask(code: &mut Vec, destination: u8, source: u8, element: ElementSize) { +fn sign_mask(code: &mut Code, destination: u8, source: u8, element: ElementSize) { if element == ElementSize::Byte { let input = if source == destination { packed(code, Host::MoveAligned, 4, source); @@ -74,14 +53,19 @@ fn sign_mask(code: &mut Vec, destination: u8, source: u8, element: ElementSi ElementSize::Word => Shift::ArithmeticDword.emit(code, destination, DWORD_SIGN_SHIFT), ElementSize::Doubleword => { Shift::ArithmeticDword.emit(code, destination, DWORD_SIGN_SHIFT); - packed(code, Host::ShuffleDword, destination, destination); - code.push(DUPLICATE_HIGH_DWORDS); + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(destination), + DUPLICATE_HIGH_DWORDS, + TargetCpu::Baseline, + ); } _ => unreachable!(), } } } -fn equal(code: &mut Vec, element: ElementSize) { +fn equal(code: &mut Code, element: ElementSize) { let opcode = match element { ElementSize::Byte => Host::EqualByte, ElementSize::Halfword => Host::EqualWord, @@ -90,15 +74,20 @@ fn equal(code: &mut Vec, element: ElementSize) { }; packed(code, opcode, 0, 3); if element == ElementSize::Doubleword { - packed(code, Host::ShuffleDword, 4, 0); - code.push(ADJACENT_DWORDS); + code.asm().simd_imm( + Host::ShuffleDword, + 4, + Rm::Xmm(0), + ADJACENT_DWORDS, + TargetCpu::Baseline, + ); packed(code, Host::And, 0, 4); } packed(code, Host::MoveAligned, 2, 0); } /// Inputs XMM0=data, XMM1=full signed counts; preserve counts1 and old merge6. /// Caller owns a64-byte stack scratch frame at RSP. -pub(super) fn chunk(code: &mut Vec, kind: Kind, element: ElementSize) { +pub(super) fn chunk(code: &mut Code, kind: Kind, element: ElementSize) { let signed = matches!( kind, Kind::SaturatingSigned | Kind::SaturatingRoundingSigned @@ -129,7 +118,7 @@ pub(super) fn chunk(code: &mut Vec, kind: Kind, element: ElementSize) { equal(code, element); if signed { sign_mask(code, 3, 3, element); - constant(code, 4, element, (1u64 << (element.bits() - 1)) - 1); + repeated_constant(code, 4, element, (1u64 << (element.bits() - 1)) - 1); packed(code, Host::Xor, 3, 4); } else { packed(code, Host::EqualDword, 3, 3); @@ -147,11 +136,11 @@ pub(super) fn chunk(code: &mut Vec, kind: Kind, element: ElementSize) { super::variable::chunk(code, right, element); if rounded { stack_vector(code, 0, QUOTIENT_SLOT, true); - constant(code, 2, element, 1); + repeated_constant(code, 2, element, 1); packed(code, subtract(element), 1, 2); stack_vector(code, 0, SOURCE_SLOT, false); super::variable::chunk(code, right, element); - constant(code, 2, element, 1); + repeated_constant(code, 2, element, 1); packed(code, Host::And, 0, 2); stack_vector(code, 3, QUOTIENT_SLOT, false); packed(code, add(element), 0, 3); diff --git a/crates/stela-compiler/src/x86_64/sve/shifts/scalar.rs b/crates/stela-compiler/src/x86_64/sve/shifts/scalar.rs index e61f27dd0d..40af64447f 100644 --- a/crates/stela-compiler/src/x86_64/sve/shifts/scalar.rs +++ b/crates/stela-compiler/src/x86_64/sve/shifts/scalar.rs @@ -1,8 +1,11 @@ //! Scalar element shifts and saturation. +use super::stack_vector; use crate::aarch64::{ scalable::ElementSize, sve::shifts::{Count, Kind}, }; +use crate::x86_64::asm::Gpr::{R10, Rax, Rcx, Rdx, Rsp}; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, ShiftOp, Size, Unary}; use alloc::vec::Vec; const CHUNK_BYTES: usize = 16; @@ -12,150 +15,63 @@ const SOURCE_SLOT: u8 = 0; const COUNT_SLOT: u8 = 16; const RESULT_SLOT: u8 = 32; pub(super) const STACK_BYTES: u8 = 48; -const MOVDQU_STORE_RSP: [u8; 3] = [0xf3, 0x0f, 0x7f]; -const MOVDQU_LOAD_RSP: [u8; 3] = [0xf3, 0x0f, 0x6f]; -const MODRM_STACK_DISP8: u8 = 0x44; -const STACK_SIB: u8 = 0x24; -const MOVZX_EAX_BYTE_RSP: [u8; 3] = [0x0f, 0xb6, 0x44]; -const MOVSX_RAX_BYTE_RSP: [u8; 4] = [0x48, 0x0f, 0xbe, 0x44]; -const MOVZX_EAX_WORD_RSP: [u8; 3] = [0x0f, 0xb7, 0x44]; -const MOVSX_RAX_WORD_RSP: [u8; 4] = [0x48, 0x0f, 0xbf, 0x44]; -const MOV_EAX_DWORD_RSP: [u8; 2] = [0x8b, 0x44]; -const MOVSXD_RAX_DWORD_RSP: [u8; 3] = [0x48, 0x63, 0x44]; -const MOV_RAX_QWORD_RSP: [u8; 3] = [0x48, 0x8b, 0x44]; -const MOV_ECX_IMM32: u8 = 0xb9; -const MOVABS_RAX: [u8; 2] = [0x48, 0xb8]; -const MOVABS_RDX: [u8; 2] = [0x48, 0xba]; -const MOV_RCX_RAX: [u8; 3] = [0x48, 0x89, 0xc1]; -const MOV_RDX_RAX: [u8; 3] = [0x48, 0x89, 0xc2]; -const MOV_R10_RAX: [u8; 3] = [0x49, 0x89, 0xc2]; -const CMP_R10_RDX: [u8; 3] = [0x49, 0x39, 0xd2]; -const CMP_RCX_RDX: [u8; 3] = [0x48, 0x39, 0xd1]; -const CMOVG_RCX_RDX: [u8; 3] = [0x48, 0x0f, 0x4f]; -const CMOVL_RCX_RDX: [u8; 3] = [0x48, 0x0f, 0x4c]; -const CMP_ECX_IMM8: [u8; 2] = [0x83, 0xf9]; -const TEST_RAX: [u8; 3] = [0x48, 0x85, 0xc0]; -const TEST_RDX: [u8; 3] = [0x48, 0x85, 0xd2]; -const TEST_RCX: [u8; 3] = [0x48, 0x85, 0xc9]; -const NEG_RCX: [u8; 3] = [0x48, 0xf7, 0xd9]; -const XOR_EAX: [u8; 2] = [0x31, 0xc0]; -const ADC_RAX_ZERO: [u8; 4] = [0x48, 0x83, 0xd0, 0]; -const ADD_RAX_RDX: [u8; 3] = [0x48, 0x01, 0xd0]; -const CMOVNS_RDX_RCX: [u8; 4] = [0x48, 0x0f, 0x49, 0xd1]; -const XOR_ECX: [u8; 2] = [0x31, 0xc9]; -const MOV_BYTE_RSP_AL: [u8; 2] = [0x88, 0x44]; -const MOV_WORD_RSP_AX: [u8; 3] = [0x66, 0x89, 0x44]; -const MOV_DWORD_RSP_EAX: [u8; 2] = [0x89, 0x44]; -const MOV_QWORD_RSP_RAX: [u8; 3] = [0x48, 0x89, 0x44]; -fn stack_vector(code: &mut Vec, xmm: u8, slot: u8, store: bool) { - code.extend(if store { - MOVDQU_STORE_RSP - } else { - MOVDQU_LOAD_RSP - }); - code.extend([MODRM_STACK_DISP8 | xmm << 3, STACK_SIB, slot]); +fn slot(offset: u8) -> Mem { + Mem::base_disp8(Rsp, offset as i8) } -fn load_lane(code: &mut Vec, bytes: usize, signed: bool, slot: u8) { - code.extend_from_slice(match (bytes, signed) { - (1, false) => &MOVZX_EAX_BYTE_RSP, - (1, true) => &MOVSX_RAX_BYTE_RSP, - (2, false) => &MOVZX_EAX_WORD_RSP, - (2, true) => &MOVSX_RAX_WORD_RSP, - (4, false) => &MOV_EAX_DWORD_RSP, - (4, true) => &MOVSXD_RAX_DWORD_RSP, - (8, _) => &MOV_RAX_QWORD_RSP, +fn load_lane(code: &mut Code, bytes: usize, signed: bool, offset: u8) { + let source = slot(offset); + let mut asm = code.asm(); + match (bytes, signed) { + (1, false) => asm.movzx(Size::Dword, Rax, Size::Byte, source), + (1, true) => asm.movsx(Size::Qword, Rax, Size::Byte, source), + (2, false) => asm.movzx(Size::Dword, Rax, Size::Word, source), + (2, true) => asm.movsx(Size::Qword, Rax, Size::Word, source), + (4, false) => asm.mov_load(Size::Dword, Rax, source), + (4, true) => asm.movsxd(Rax, source), + (8, _) => asm.mov_load(Size::Qword, Rax, source), _ => unreachable!("integer element width"), - }); - code.extend([STACK_SIB, slot]); + } } -fn store_lane(code: &mut Vec, bytes: usize, slot: u8) { - code.extend_from_slice(match bytes { - 1 => &MOV_BYTE_RSP_AL, - 2 => &MOV_WORD_RSP_AX, - 4 => &MOV_DWORD_RSP_EAX, - 8 => &MOV_QWORD_RSP_RAX, +fn store_lane(code: &mut Code, bytes: usize, offset: u8) { + let size = match bytes { + 1 => Size::Byte, + 2 => Size::Word, + 4 => Size::Dword, + 8 => Size::Qword, _ => unreachable!("integer element width"), - }); - code.extend([STACK_SIB, slot]); + }; + code.asm().mov_store(size, slot(offset), Rax); } -#[derive(Clone, Copy)] -enum Branch { - Always, - Nonnegative, - Equal, - Above, - AboveOrEqual, -} -fn branch(code: &mut Vec, condition: Branch) -> usize { - match condition { - Branch::Always => code.push(0xe9), - Branch::Nonnegative => code.extend([0x0f, 0x89]), - Branch::Equal => code.extend([0x0f, 0x84]), - Branch::Above => code.extend([0x0f, 0x87]), - Branch::AboveOrEqual => code.extend([0x0f, 0x83]), - } - let patch = code.len(); - code.extend([0; 4]); - patch -} -fn resolve(code: &mut [u8], patch: usize) { - let distance = i32::try_from(code.len() - patch - 4).expect("shift recipe branch span"); - code[patch..patch + 4].copy_from_slice(&distance.to_le_bytes()); +fn shift_count(code: &mut Code, op: ShiftOp, register: Gpr) { + code.asm().shift_cl(op, Size::Qword, register); } -#[derive(Clone, Copy)] -enum Shift { - Left, - LogicalRight, - ArithmeticRight, -} -impl Shift { - fn count(self, code: &mut Vec, temporary: bool) { - let group = match self { - Self::Left => 4, - Self::LogicalRight => 5, - Self::ArithmeticRight => 7, - }; - code.extend([ - if temporary { 0x49 } else { 0x48 }, - 0xd3, - 0xc0 | group << 3 | if temporary { 2 } else { 0 }, - ]); - } - fn immediate(self, code: &mut Vec, amount: u8) { - let group = match self { - Self::Left => 4, - Self::LogicalRight => 5, - Self::ArithmeticRight => 7, - }; - code.extend([0x48, 0xc1, 0xc0 | group << 3, amount]); - } +fn shift_immediate(code: &mut Code, op: ShiftOp, amount: u8) { + code.asm().shift_imm(op, Size::Qword, Rax, amount); } -fn bound(code: &mut Vec, value: u64, rdx: bool) { - code.extend(if rdx { MOVABS_RDX } else { MOVABS_RAX }); - code.extend(value.to_le_bytes()); +fn bound(code: &mut Code, value: u64, rdx: bool) { + code.asm().mov_imm64(if rdx { Rdx } else { Rax }, value); } -fn normalize(code: &mut Vec, bits: u8, signed: bool) { +fn normalize(code: &mut Code, bits: u8, signed: bool) { if bits < HOST_BITS { - Shift::Left.immediate(code, HOST_BITS - bits); - if signed { - Shift::ArithmeticRight - } else { - Shift::LogicalRight - } - .immediate(code, HOST_BITS - bits); + shift_immediate(code, ShiftOp::Shl, HOST_BITS - bits); + shift_immediate( + code, + if signed { ShiftOp::Sar } else { ShiftOp::Shr }, + HOST_BITS - bits, + ); } } /// Preloaded XMM0=data and XMM1=complete signed counts; result XMM0. /// Preserves other XMMs and RDI/R15, clobbers RAX/RCX/RDX/R10, restores RSP. /// Group instructions own source snapshots, group ordering and destination commit. -pub(crate) fn rounding_variable_chunk(code: &mut Vec, element_size: ElementSize, signed: bool) { +pub(crate) fn rounding_variable_chunk(code: &mut Code, element_size: ElementSize, signed: bool) { super::adjust_stack(code, STACK_BYTES, true); chunk( code, @@ -170,7 +86,7 @@ pub(crate) fn rounding_variable_chunk(code: &mut Vec, element_size: ElementS super::adjust_stack(code, STACK_BYTES, false); } -pub(super) fn chunk(code: &mut Vec, kind: Kind, element_size: ElementSize, count: Count) { +pub(super) fn chunk(code: &mut Code, kind: Kind, element_size: ElementSize, count: Count) { stack_vector(code, 0, SOURCE_SLOT, true); if !matches!(count, Count::Immediate(_)) { stack_vector(code, 1, COUNT_SLOT, true); @@ -193,8 +109,7 @@ pub(super) fn chunk(code: &mut Vec, kind: Kind, element_size: ElementSize, c if kind == Kind::DivideSigned { divide_signed(code, bits, amount); } else { - code.push(MOV_ECX_IMM32); - code.extend(u32::from(amount).to_le_bytes()); + code.asm().mov_imm32(Rcx, u32::from(amount)); left(code, bits, signed, kind != Kind::SaturatingSigned, true); } } @@ -220,15 +135,16 @@ pub(super) fn chunk(code: &mut Vec, kind: Kind, element_size: ElementSize, c bidirectional, COUNT_SLOT + count_offset as u8, ); - code.extend(MOV_RCX_RAX); + code.asm().mov(Size::Qword, Rcx, Rax); if bidirectional { clamp_signed_count(code, bits); } load_lane(code, bytes, signed, SOURCE_SLOT + offset as u8); if bidirectional { - code.extend(TEST_RCX); - let positive = branch(code, Branch::Nonnegative); - code.extend(NEG_RCX); + let mut asm = code.asm(); + asm.test(Size::Qword, Rcx, Rcx); + let positive = asm.jcc(Cond::Ns); + asm.unary(Unary::Neg, Size::Qword, Rcx); right( code, signed, @@ -240,8 +156,9 @@ pub(super) fn chunk(code: &mut Vec, kind: Kind, element_size: ElementSize, c | Kind::SaturatingRoundingUnsigned ), ); - let done = branch(code, Branch::Always); - resolve(code, positive); + let mut asm = code.asm(); + let done = asm.jmp(); + asm.bind(positive); left( code, bits, @@ -255,7 +172,7 @@ pub(super) fn chunk(code: &mut Vec, kind: Kind, element_size: ElementSize, c | Kind::SaturatingRoundingUnsigned ), ); - resolve(code, done); + code.asm().bind(done); } else if kind == Kind::LogicalLeft { // Full unsigned counts must not truncate to ECX/CL first. clamp_unsigned_count(code, bits); @@ -271,101 +188,105 @@ pub(super) fn chunk(code: &mut Vec, kind: Kind, element_size: ElementSize, c stack_vector(code, 0, RESULT_SLOT, false); } -fn clamp_unsigned_count(code: &mut Vec, bits: u8) { +fn clamp_unsigned_count(code: &mut Code, bits: u8) { // Compare the full count before x86 CL masking; source RAX remains intact. bound(code, u64::from(bits), true); - code.extend(CMP_RCX_RDX); - code.extend([0x48, 0x0f, 0x47, 0xca]); // cmova rcx,rdx + let mut asm = code.asm(); + asm.alu(Alu::Cmp, Size::Qword, Rcx, Rdx); + asm.cmov(Cond::A, Size::Qword, Rcx, Rdx); } -fn clamp_signed_count(code: &mut Vec, bits: u8) { +fn clamp_signed_count(code: &mut Code, bits: u8) { let ceiling = i64::from(bits) + 1; bound(code, ceiling as u64, true); - code.extend(CMP_RCX_RDX); - code.extend(CMOVG_RCX_RDX); - code.push(0xca); + let mut asm = code.asm(); + asm.alu(Alu::Cmp, Size::Qword, Rcx, Rdx); + asm.cmov(Cond::G, Size::Qword, Rcx, Rdx); bound(code, (-ceiling) as u64, true); - code.extend(CMP_RCX_RDX); - code.extend(CMOVL_RCX_RDX); - code.push(0xca); + let mut asm = code.asm(); + asm.alu(Alu::Cmp, Size::Qword, Rcx, Rdx); + asm.cmov(Cond::L, Size::Qword, Rcx, Rdx); } -fn divide_signed(code: &mut Vec, bits: u8, amount: u8) { +fn divide_signed(code: &mut Code, bits: u8, amount: u8) { if amount == bits { - code.extend(XOR_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); return; } bound(code, (1_u64 << amount) - 1, true); - code.extend(XOR_ECX); - code.extend(TEST_RAX); - code.extend(CMOVNS_RDX_RCX); - code.extend(ADD_RAX_RDX); - Shift::ArithmeticRight.immediate(code, amount); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, Rcx, Rcx); + asm.test(Size::Qword, Rax, Rax); + asm.cmov(Cond::Ns, Size::Qword, Rdx, Rcx); + asm.alu(Alu::Add, Size::Qword, Rax, Rdx); + shift_immediate(code, ShiftOp::Sar, amount); } -fn right(code: &mut Vec, signed: bool, round: bool) { - code.extend(CMP_ECX_IMM8); - code.push(HOST_BITS); - let large = branch(code, Branch::AboveOrEqual); - if signed { - Shift::ArithmeticRight - } else { - Shift::LogicalRight - } - .count(code, false); +fn right(code: &mut Code, signed: bool, round: bool) { + let mut asm = code.asm(); + asm.alu_imm8(Alu::Cmp, Size::Dword, Rcx, HOST_BITS as i8); + let large = asm.jcc(Cond::Ae); + shift_count(code, if signed { ShiftOp::Sar } else { ShiftOp::Shr }, Rax); + let mut asm = code.asm(); if round { - code.extend(ADC_RAX_ZERO); + asm.alu_imm8(Alu::Adc, Size::Qword, Rax, 0); } - let done = branch(code, Branch::Always); - resolve(code, large); + let done = asm.jmp(); + asm.bind(large); if signed && !round { - Shift::ArithmeticRight.immediate(code, HOST_BITS - 1); + shift_immediate(code, ShiftOp::Sar, HOST_BITS - 1); } else if !signed && round { - let beyond = branch(code, Branch::Above); - Shift::LogicalRight.immediate(code, HOST_BITS - 1); - let end = branch(code, Branch::Always); - resolve(code, beyond); - code.extend(XOR_EAX); - resolve(code, end); + let beyond = asm.jcc(Cond::A); + shift_immediate(code, ShiftOp::Shr, HOST_BITS - 1); + let mut asm = code.asm(); + let end = asm.jmp(); + asm.bind(beyond); + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); + asm.bind(end); } else { - code.extend(XOR_EAX); + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); } - resolve(code, done); + code.asm().bind(done); } -fn left(code: &mut Vec, bits: u8, signed: bool, unsigned_result: bool, saturating: bool) { +fn left(code: &mut Code, bits: u8, signed: bool, unsigned_result: bool, saturating: bool) { let mut done = Vec::new(); let mut negative = None; if saturating { - code.extend(MOV_RDX_RAX); + code.asm().mov(Size::Qword, Rdx, Rax); } if signed && unsigned_result { - code.extend(TEST_RAX); - let nonnegative = branch(code, Branch::Nonnegative); - negative = Some(branch(code, Branch::Always)); - resolve(code, nonnegative); + let mut asm = code.asm(); + asm.test(Size::Qword, Rax, Rax); + let nonnegative = asm.jcc(Cond::Ns); + negative = Some(asm.jmp()); + asm.bind(nonnegative); } - code.extend(CMP_ECX_IMM8); - code.push(bits); - let large = branch(code, Branch::AboveOrEqual); - Shift::Left.count(code, false); + let mut asm = code.asm(); + asm.alu_imm8(Alu::Cmp, Size::Dword, Rcx, bits as i8); + let large = asm.jcc(Cond::Ae); + shift_count(code, ShiftOp::Shl, Rax); if saturating { normalize(code, bits, !unsigned_result); - code.extend(MOV_R10_RAX); - if unsigned_result { - Shift::LogicalRight - } else { - Shift::ArithmeticRight - } - .count(code, true); - code.extend(CMP_R10_RDX); - done.push(branch(code, Branch::Equal)); - let overflow = branch(code, Branch::Always); - resolve(code, large); - code.extend(TEST_RAX); - done.push(branch(code, Branch::Equal)); - resolve(code, overflow); + code.asm().mov(Size::Qword, R10, Rax); + shift_count( + code, + if unsigned_result { + ShiftOp::Shr + } else { + ShiftOp::Sar + }, + R10, + ); + let mut asm = code.asm(); + asm.alu(Alu::Cmp, Size::Qword, R10, Rdx); + done.push(asm.jcc(Cond::E)); + let overflow = asm.jmp(); + asm.bind(large); + asm.test(Size::Qword, Rax, Rax); + done.push(asm.jcc(Cond::E)); + asm.bind(overflow); if let Some(patch) = negative { - resolve(code, patch); + asm.bind(patch); } let maximum = if unsigned_result { u64::MAX >> (HOST_BITS - bits) @@ -374,8 +295,9 @@ fn left(code: &mut Vec, bits: u8, signed: bool, unsigned_result: bool, satur }; bound(code, maximum, false); if signed { - code.extend(TEST_RDX); - let nonnegative = branch(code, Branch::Nonnegative); + let mut asm = code.asm(); + asm.test(Size::Qword, Rdx, Rdx); + let nonnegative = asm.jcc(Cond::Ns); bound( code, if unsigned_result { @@ -385,14 +307,16 @@ fn left(code: &mut Vec, bits: u8, signed: bool, unsigned_result: bool, satur }, false, ); - resolve(code, nonnegative); + code.asm().bind(nonnegative); } } else { - done.push(branch(code, Branch::Always)); - resolve(code, large); - code.extend(XOR_EAX); + let mut asm = code.asm(); + done.push(asm.jmp()); + asm.bind(large); + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); } + let mut asm = code.asm(); for patch in done { - resolve(code, patch); + asm.bind(patch); } } diff --git a/crates/stela-compiler/src/x86_64/sve/shifts/variable.rs b/crates/stela-compiler/src/x86_64/sve/shifts/variable.rs index b75074cf0d..15e7c9096d 100644 --- a/crates/stela-compiler/src/x86_64/sve/shifts/variable.rs +++ b/crates/stela-compiler/src/x86_64/sve/shifts/variable.rs @@ -1,4 +1,6 @@ //! Per-lane variable shifts by unsigned counts. +use super::repeated_constant; +use crate::x86_64::asm::{Code, Rm}; use crate::x86_64::simd::shifts::{ logical_shift as shared_logical_shift, right_shift as shared_right_shift, }; @@ -10,7 +12,6 @@ use crate::{ }, x86_64::isa::{ShiftOpcode as Shift, SimdOpcode as Host, VexShiftOpcode}, }; -use alloc::vec::Vec; /// Only complete unsigned per-element counts map directly. Wide counts, /// signed bidirectional/rounded shifts and narrower lanes retain their own @@ -33,25 +34,15 @@ pub(super) fn avx2_opcode( _ => None, } } -const MOV_RAX_IMM64: [u8; 2] = [0x48, 0xb8]; const ADJACENT_DWORDS: u8 = 0xb1; const HIGH_DWORD_SIGN: u8 = 0xf5; const DWORD_SIGN_SHIFT: u8 = u32::BITS as u8 - 1; const WORD_SIGN_SHIFT: u8 = u16::BITS as u8 - 1; -fn packed(code: &mut Vec, opcode: Host, destination: u8, source: u8) { +fn packed(code: &mut Code, opcode: Host, destination: u8, source: u8) { opcode.register(code, destination, source, TargetCpu::Baseline); } -fn constant(code: &mut Vec, xmm: u8, element: ElementSize, value: u64) { - let limbs = value.to_le_bytes(); - let repeated: [u8; core::mem::size_of::()] = - core::array::from_fn(|i| limbs[i % element.bytes()]); - code.extend(MOV_RAX_IMM64); - code.extend(repeated); - packed(code, Host::MoveGprQword, xmm, 0); - packed(code, Host::UnpackLowQword, xmm, xmm); -} /// Byte logical masks use one repeated qword constant, avoiding two-limb setup. -fn logical_shift(code: &mut Vec, xmm: u8, lane: u8, amount: u8, left: bool) { +fn logical_shift(code: &mut Code, xmm: u8, lane: u8, amount: u8, left: bool) { if lane != 1 { shared_logical_shift(code, xmm, lane, amount, left); return; @@ -70,12 +61,12 @@ fn logical_shift(code: &mut Vec, xmm: u8, lane: u8, amount: u8, left: bool) } else { u16::from(u8::MAX) >> amount }; - constant(code, 5, ElementSize::Byte, u64::from(mask)); + repeated_constant(code, 5, ElementSize::Byte, u64::from(mask)); packed(code, Host::And, xmm, 5); } /// Arithmetic word shifts independently sign-extend each even and odd byte. /// XMM4 is scratch; XMM1, XMM2 and old mergeXMM6 survive unchanged. -fn right_shift(code: &mut Vec, xmm: u8, lane: u8, amount: u8, signed: bool) { +fn right_shift(code: &mut Code, xmm: u8, lane: u8, amount: u8, signed: bool) { if !signed { logical_shift(code, xmm, lane, amount, false); return; @@ -98,7 +89,7 @@ fn right_shift(code: &mut Vec, xmm: u8, lane: u8, amount: u8, signed: bool) Shift::LeftWord.emit(code, 4, BYTE_BITS); packed(code, Host::Or, xmm, 4); } -fn equal_zero(code: &mut Vec, xmm: u8, element: ElementSize) { +fn equal_zero(code: &mut Code, xmm: u8, element: ElementSize) { packed(code, Host::Xor, 4, 4); let op = match element { ElementSize::Byte => Host::EqualByte, @@ -108,12 +99,17 @@ fn equal_zero(code: &mut Vec, xmm: u8, element: ElementSize) { }; packed(code, op, xmm, 4); if element == ElementSize::Doubleword { - packed(code, Host::ShuffleDword, 5, xmm); - code.push(ADJACENT_DWORDS); + code.asm().simd_imm( + Host::ShuffleDword, + 5, + Rm::Xmm(xmm), + ADJACENT_DWORDS, + TargetCpu::Baseline, + ); packed(code, Host::And, xmm, 5); } } -fn sign_mask(code: &mut Vec, element: ElementSize) { +fn sign_mask(code: &mut Code, element: ElementSize) { if element == ElementSize::Byte { packed(code, Host::Xor, 3, 3); packed(code, Host::GreaterByte, 3, 0); @@ -125,13 +121,18 @@ fn sign_mask(code: &mut Vec, element: ElementSize) { ElementSize::Word => Shift::ArithmeticDword.emit(code, 3, DWORD_SIGN_SHIFT), ElementSize::Doubleword => { Shift::ArithmeticDword.emit(code, 3, DWORD_SIGN_SHIFT); - packed(code, Host::ShuffleDword, 3, 3); - code.push(HIGH_DWORD_SIGN); + code.asm().simd_imm( + Host::ShuffleDword, + 3, + Rm::Xmm(3), + HIGH_DWORD_SIGN, + TargetCpu::Baseline, + ); } _ => unreachable!(), } } -pub(super) fn chunk(code: &mut Vec, kind: Kind, element: ElementSize) { +pub(super) fn chunk(code: &mut Code, kind: Kind, element: ElementSize) { assert!(matches!( kind, Kind::LogicalLeft | Kind::LogicalRight | Kind::ArithmeticRight @@ -161,8 +162,13 @@ pub(super) fn chunk(code: &mut Vec, kind: Kind, element: ElementSize) { ElementSize::Doubleword => { Shift::LeftQword.emit(code, 2, shift); Shift::ArithmeticDword.emit(code, 2, DWORD_SIGN_SHIFT); - packed(code, Host::ShuffleDword, 2, 2); - code.push(HIGH_DWORD_SIGN); + code.asm().simd_imm( + Host::ShuffleDword, + 2, + Rm::Xmm(2), + HIGH_DWORD_SIGN, + TargetCpu::Baseline, + ); } _ => unreachable!(), } @@ -179,7 +185,7 @@ pub(super) fn chunk(code: &mut Vec, kind: Kind, element: ElementSize) { } packed(code, Host::MoveAligned, 2, 1); if element == ElementSize::Byte { - constant(code, 5, element, u64::from(u8::MAX) ^ (bits as u64 - 1)); + repeated_constant(code, 5, element, u64::from(u8::MAX) ^ (bits as u64 - 1)); packed(code, Host::And, 2, 5); } else { logical_shift(code, 2, lane, bits.trailing_zeros() as u8, false); diff --git a/crates/stela-compiler/src/x86_64/sve/shifts_narrow.rs b/crates/stela-compiler/src/x86_64/sve/shifts_narrow.rs index 1fe959fbc5..fa4707a1a3 100644 --- a/crates/stela-compiler/src/x86_64/sve/shifts_narrow.rs +++ b/crates/stela-compiler/src/x86_64/sve/shifts_narrow.rs @@ -1,4 +1,6 @@ //! SVE2 widening and narrowing shifts with SSE2 or SSE4.1. +use crate::x86_64::asm::Gpr::{Rax, Rdx}; +use crate::x86_64::asm::{Alu, Code, Cond, Rm, ShiftOp, Size}; use crate::{ TargetCpu, aarch64::{ @@ -6,11 +8,10 @@ use crate::{ sve::shifts_narrow::{Kind, Operand, Part}, }, x86_64::{ - isa::SimdOpcode as Host, + isa::{ShiftOpcode as Shift, SimdOpcode as Host}, scalable::{load_z_chunk, store_z_chunk}, }, }; -use alloc::vec::Vec; const SOURCE_XMM: u8 = 0; const TEMP_XMM: u8 = 1; @@ -23,36 +24,6 @@ const BYTE_BITS: u8 = 8; const WORD_BITS: u8 = 16; const DWORD_BITS: u8 = 32; const QWORD_BITS: u8 = 64; -const SSE_PREFIX: &[u8] = &[0x66, 0x0f]; -const REGISTER_MODE: u8 = 0xc0; -const MODRM_REGISTER_SHIFT: u8 = 3; -const MOVDQA: u8 = 0x6f; -const PAND: u8 = 0xdb; -const PANDN: u8 = 0xdf; -const POR: u8 = 0xeb; -const PXOR: u8 = 0xef; -const PSHUFD: u8 = 0x70; -const PUNPCKLQDQ: u8 = 0x6c; -const PUNPCKLBW: u8 = 0x60; -const PUNPCKLWD: u8 = 0x61; -const PACKSSWB: u8 = 0x63; -const PACKSSDW: u8 = 0x6b; -const PACKUSWB: u8 = 0x67; -const PCMPGTD: u8 = 0x66; -const PSUBUSW: u8 = 0xd9; -const PSUBW: u8 = 0xf9; -const PSUBD: u8 = 0xfa; -const PADDW: u8 = 0xfd; -const PADDD: u8 = 0xfe; -const PADDQ: u8 = 0xd4; -const SHIFT_WORD: u8 = 0x71; -const SHIFT_DWORD: u8 = 0x72; -const SHIFT_QWORD: u8 = 0x73; -const RIGHT_LOGICAL: u8 = 2; -const RIGHT_BYTES: u8 = 3; -const RIGHT_ARITHMETIC: u8 = 4; -const LEFT_LOGICAL: u8 = 6; -const LEFT_BYTES: u8 = 7; const SIGNED_BOTTOM_SHUFFLE: u8 = 0xa0; const SIGNED_TOP_SHUFFLE: u8 = 0xf5; const EVEN_DWORDS_SHUFFLE: u8 = 0x88; @@ -68,28 +39,8 @@ const UNSIGNED_WORD_MAX_DWORDS: u64 = 0x0000ffff0000ffff; const BIASED_UNSIGNED_WORD_MAX: u64 = 0x8000ffff8000ffff; const PACK_WORD_BIAS: u64 = 0x0000800000008000; const PACKED_WORD_SIGN: u64 = 0x8000800080008000; -const MOV_RAX_IMM64: &[u8] = &[0x48, 0xb8]; -const MOV_RDX_IMM64: &[u8] = &[0x48, 0xba]; -const MOVQ_XMM_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e]; -const MOVQ_RAX_XMM: &[u8] = &[0x66, 0x48, 0x0f, 0x7e]; -const MOVQ_XMM_XMM: &[u8] = &[0xf3, 0x0f, 0x7e]; -const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; -const SHR_RAX: &[u8] = &[0x48, 0xc1, 0xe8]; -const SAR_RAX: &[u8] = &[0x48, 0xc1, 0xf8]; -const SHR_RDX: &[u8] = &[0x48, 0xc1, 0xea]; -const AND_EDX_ONE: &[u8] = &[0x83, 0xe2, 0x01]; -const ADD_RAX_RDX: &[u8] = &[0x48, 0x01, 0xd0]; -const CMP_RAX_RDX: &[u8] = &[0x48, 0x39, 0xd0]; -const TEST_RAX_RAX: &[u8] = &[0x48, 0x85, 0xc0]; -const XOR_EDX_EDX: &[u8] = &[0x31, 0xd2]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const CMOVL_RAX_RDX: &[u8] = &[0x48, 0x0f, 0x4c, 0xc2]; -const CMOVG_RAX_RDX: &[u8] = &[0x48, 0x0f, 0x4f, 0xc2]; -const CMOVA_RAX_RDX: &[u8] = &[0x48, 0x0f, 0x47, 0xc2]; -const CMOVS_RAX_RDX: &[u8] = &[0x48, 0x0f, 0x48, 0xc2]; -const MOV_EAX_EAX: &[u8] = &[0x89, 0xc0]; -pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: TargetCpu) { +pub fn emit(code: &mut Code, operand: Operand, length: VectorLength, target: TargetCpu) { let small_bits = operand.element_size.bits() as u8; for chunk in 0..length.chunks() { load_z_chunk(code, operand.source, chunk, SOURCE_XMM, length, target); @@ -115,7 +66,7 @@ pub fn emit(code: &mut Vec, operand: Operand, length: VectorLength, target: /// `element` is Byte/Halfword/Word. Right shifts accept 1..=source bits; /// extract kinds require zero. Widening kinds are outside this kernel's contract. pub(crate) fn narrow_chunk( - code: &mut Vec, + code: &mut Code, kind: Kind, element: ElementSize, amount: u8, @@ -134,7 +85,7 @@ pub(crate) fn narrow_chunk( /// Narrow XMM0 into consecutive low-eight-byte results, clearing the upper eight. /// Operand and clobber contracts match `narrow_chunk`; group staging stays outside. pub(crate) fn narrow_packed_chunk( - code: &mut Vec, + code: &mut Code, kind: Kind, element: ElementSize, amount: u8, @@ -157,7 +108,7 @@ enum NarrowProjection { } fn narrow_projected( - code: &mut Vec, + code: &mut Code, kind: Kind, element: ElementSize, amount: u8, @@ -190,73 +141,82 @@ fn narrow_projected( } } -fn clear_packed_upper(code: &mut Vec) { - code.extend(MOVQ_XMM_XMM); - code.push(REGISTER_MODE | (SOURCE_XMM << MODRM_REGISTER_SHIFT) | SOURCE_XMM); +fn clear_packed_upper(code: &mut Code) { + code.asm().movq_xmm(SOURCE_XMM, Rm::Xmm(SOURCE_XMM)); } -fn compact_even_lanes(code: &mut Vec, small: u8) { +fn compact_even_lanes(code: &mut Code, small: u8) { match small { - BYTE_BITS => binary(code, PACKUSWB, SOURCE_XMM, SOURCE_XMM), + BYTE_BITS => binary(code, Host::PackUnsignedWordToByte, SOURCE_XMM, SOURCE_XMM), WORD_BITS => { // Sign-extend the retained bits before packing: every lane is representable. - shift(code, DWORD_BITS, LEFT_LOGICAL, SOURCE_XMM, WORD_BITS); - shift(code, DWORD_BITS, RIGHT_ARITHMETIC, SOURCE_XMM, WORD_BITS); - binary(code, PACKSSDW, SOURCE_XMM, SOURCE_XMM); - } - DWORD_BITS => { - binary(code, PSHUFD, SOURCE_XMM, SOURCE_XMM); - code.push(EVEN_DWORDS_SHUFFLE); + shift(code, DWORD_BITS, Direction::Left, SOURCE_XMM, WORD_BITS); + shift( + code, + DWORD_BITS, + Direction::Arithmetic, + SOURCE_XMM, + WORD_BITS, + ); + binary(code, Host::PackSignedDwordToWord, SOURCE_XMM, SOURCE_XMM); } + DWORD_BITS => shuffle(code, SOURCE_XMM, SOURCE_XMM, EVEN_DWORDS_SHUFFLE), _ => unreachable!(), } clear_packed_upper(code); } -fn binary(code: &mut Vec, opcode: u8, destination: u8, source: u8) { - code.extend(SSE_PREFIX); - code.extend([ - opcode, - REGISTER_MODE | (destination << MODRM_REGISTER_SHIFT) | source, - ]); +fn binary(code: &mut Code, opcode: Host, destination: u8, source: u8) { + code.asm() + .simd(opcode, destination, Rm::Xmm(source), TargetCpu::Baseline); } -fn shift(code: &mut Vec, bits: u8, group: u8, register: u8, amount: u8) { +fn shuffle(code: &mut Code, destination: u8, source: u8, control: u8) { + code.asm().simd_imm( + Host::ShuffleDword, + destination, + Rm::Xmm(source), + control, + TargetCpu::Baseline, + ); +} + +#[derive(Clone, Copy)] +enum Direction { + Left, + Right, + Arithmetic, +} + +fn shift(code: &mut Code, bits: u8, direction: Direction, register: u8, amount: u8) { if amount == 0 { return; } - let opcode = match bits { - WORD_BITS => SHIFT_WORD, - DWORD_BITS => SHIFT_DWORD, - QWORD_BITS => SHIFT_QWORD, + let opcode = match (bits, direction) { + (WORD_BITS, Direction::Left) => Shift::LeftWord, + (WORD_BITS, Direction::Right) => Shift::RightWord, + (WORD_BITS, Direction::Arithmetic) => Shift::ArithmeticWord, + (DWORD_BITS, Direction::Left) => Shift::LeftDword, + (DWORD_BITS, Direction::Right) => Shift::RightDword, + (DWORD_BITS, Direction::Arithmetic) => Shift::ArithmeticDword, + (QWORD_BITS, Direction::Left) => Shift::LeftQword, + (QWORD_BITS, Direction::Right) => Shift::RightQword, _ => unreachable!(), }; - code.extend(SSE_PREFIX); - code.extend([ - opcode, - REGISTER_MODE | (group << MODRM_REGISTER_SHIFT) | register, - amount, - ]); + opcode.emit(code, register, amount); } -fn byte_shift(code: &mut Vec, group: u8, register: u8, amount: usize) { - if amount == 0 { - return; +fn byte_shift(code: &mut Code, opcode: Shift, register: u8, amount: usize) { + if amount != 0 { + opcode.emit(code, register, amount as u8); } - code.extend(SSE_PREFIX); - code.extend([ - SHIFT_QWORD, - REGISTER_MODE | (group << MODRM_REGISTER_SHIFT) | register, - amount as u8, - ]); } -fn constant(code: &mut Vec, register: u8, value: u64) { - code.extend(MOV_RAX_IMM64); - code.extend(value.to_le_bytes()); - code.extend(MOVQ_XMM_RAX); - code.push(REGISTER_MODE | (register << MODRM_REGISTER_SHIFT)); - binary(code, PUNPCKLQDQ, register, register); +fn constant(code: &mut Code, register: u8, value: u64) { + let mut asm = code.asm(); + asm.mov_imm64(Rax, value); + asm.movq_to_xmm(register, Rax); + binary(code, Host::UnpackLowQword, register, register); } fn low_mask(bits: u8) -> u64 { @@ -268,62 +228,77 @@ fn low_mask(bits: u8) -> u64 { } } -fn widen(code: &mut Vec, operand: Operand, small: u8, target: TargetCpu) { +fn widen(code: &mut Code, operand: Operand, small: u8, target: TargetCpu) { let wide = 2 * small; let top = operand.part == Part::Top; if operand.kind == Kind::WidenSigned && small == DWORD_BITS && target.supports(TargetCpu::Sse41) { - Host::ShuffleDword.register(code, SOURCE_XMM, SOURCE_XMM, target); - code.push(if top { - ODD_DWORDS_SHUFFLE - } else { - EVEN_DWORDS_SHUFFLE - }); + code.asm().simd_imm( + Host::ShuffleDword, + SOURCE_XMM, + Rm::Xmm(SOURCE_XMM), + if top { + ODD_DWORDS_SHUFFLE + } else { + EVEN_DWORDS_SHUFFLE + }, + target, + ); Host::SignExtendDwordToQword.register(code, SOURCE_XMM, SOURCE_XMM, target); - shift(code, wide, LEFT_LOGICAL, SOURCE_XMM, operand.shift); + shift(code, wide, Direction::Left, SOURCE_XMM, operand.shift); return; } if operand.kind == Kind::WidenUnsigned { if top { - shift(code, wide, RIGHT_LOGICAL, SOURCE_XMM, small); + shift(code, wide, Direction::Right, SOURCE_XMM, small); } else { constant(code, MASK_XMM, low_mask(small)); - binary(code, PAND, SOURCE_XMM, MASK_XMM); + binary(code, Host::And, SOURCE_XMM, MASK_XMM); } } else if small != DWORD_BITS { if !top { - shift(code, wide, LEFT_LOGICAL, SOURCE_XMM, small); + shift(code, wide, Direction::Left, SOURCE_XMM, small); // The first shift already creates the low zero bits of the widened result. shift( code, wide, - RIGHT_ARITHMETIC, + Direction::Arithmetic, SOURCE_XMM, small - operand.shift, ); return; } - shift(code, wide, RIGHT_ARITHMETIC, SOURCE_XMM, small); + shift(code, wide, Direction::Arithmetic, SOURCE_XMM, small); } else { - binary(code, MOVDQA, TEMP_XMM, SOURCE_XMM); - shift(code, DWORD_BITS, RIGHT_ARITHMETIC, TEMP_XMM, DWORD_BITS - 1); - binary(code, PSHUFD, TEMP_XMM, TEMP_XMM); - code.push(if top { - SIGNED_TOP_SHUFFLE - } else { - SIGNED_BOTTOM_SHUFFLE - }); + binary(code, Host::MoveAligned, TEMP_XMM, SOURCE_XMM); + shift( + code, + DWORD_BITS, + Direction::Arithmetic, + TEMP_XMM, + DWORD_BITS - 1, + ); + shuffle( + code, + TEMP_XMM, + TEMP_XMM, + if top { + SIGNED_TOP_SHUFFLE + } else { + SIGNED_BOTTOM_SHUFFLE + }, + ); constant(code, MASK_XMM, HIGH_DWORDS); - binary(code, PAND, TEMP_XMM, MASK_XMM); + binary(code, Host::And, TEMP_XMM, MASK_XMM); if top { - shift(code, QWORD_BITS, RIGHT_LOGICAL, SOURCE_XMM, DWORD_BITS); + shift(code, QWORD_BITS, Direction::Right, SOURCE_XMM, DWORD_BITS); } else { constant(code, MASK_XMM, LOW_DWORDS); - binary(code, PAND, SOURCE_XMM, MASK_XMM); + binary(code, Host::And, SOURCE_XMM, MASK_XMM); } - binary(code, POR, SOURCE_XMM, TEMP_XMM); + binary(code, Host::Or, SOURCE_XMM, TEMP_XMM); } - shift(code, wide, LEFT_LOGICAL, SOURCE_XMM, operand.shift); + shift(code, wide, Direction::Left, SOURCE_XMM, operand.shift); } fn signed_input(kind: Kind) -> bool { @@ -357,13 +332,13 @@ fn signed_output(kind: Kind) -> bool { ) } -fn shift_narrow_input(code: &mut Vec, operand: Operand, wide: u8) { +fn shift_narrow_input(code: &mut Code, operand: Operand, wide: u8) { if operand.kind.is_extract() { return; } if rounded(operand.kind) { - binary(code, MOVDQA, TEMP_XMM, SOURCE_XMM); - shift(code, wide, RIGHT_LOGICAL, TEMP_XMM, operand.shift - 1); + binary(code, Host::MoveAligned, TEMP_XMM, SOURCE_XMM); + shift(code, wide, Direction::Right, TEMP_XMM, operand.shift - 1); constant( code, MASK_XMM, @@ -374,15 +349,15 @@ fn shift_narrow_input(code: &mut Vec, operand: Operand, wide: u8) { _ => unreachable!(), }, ); - binary(code, PAND, TEMP_XMM, MASK_XMM); + binary(code, Host::And, TEMP_XMM, MASK_XMM); } shift( code, wide, if signed_input(operand.kind) { - RIGHT_ARITHMETIC + Direction::Arithmetic } else { - RIGHT_LOGICAL + Direction::Right }, SOURCE_XMM, operand.shift, @@ -391,9 +366,9 @@ fn shift_narrow_input(code: &mut Vec, operand: Operand, wide: u8) { binary( code, match wide { - WORD_BITS => PADDW, - DWORD_BITS => PADDD, - QWORD_BITS => PADDQ, + WORD_BITS => Host::AddWord, + DWORD_BITS => Host::AddDword, + QWORD_BITS => Host::AddQword, _ => unreachable!(), }, SOURCE_XMM, @@ -403,7 +378,7 @@ fn shift_narrow_input(code: &mut Vec, operand: Operand, wide: u8) { } fn narrow( - code: &mut Vec, + code: &mut Code, operand: Operand, small: u8, projection: NarrowProjection, @@ -413,7 +388,7 @@ fn narrow( shift_narrow_input(code, operand, wide); if matches!(operand.kind, Kind::ShiftRight | Kind::RoundRight) { constant(code, MASK_XMM, low_mask(small)); - binary(code, PAND, SOURCE_XMM, MASK_XMM); + binary(code, Host::And, SOURCE_XMM, MASK_XMM); if projection == NarrowProjection::Packed { compact_even_lanes(code, small); } @@ -423,9 +398,9 @@ fn narrow( binary( code, if small == BYTE_BITS { - PACKSSWB + Host::PackSignedWordToByte } else { - PACKSSDW + Host::PackSignedDwordToWord }, SOURCE_XMM, SOURCE_XMM, @@ -436,12 +411,12 @@ fn narrow( if target.supports(TargetCpu::Sse41) { Host::MinUnsignedWord.register(code, SOURCE_XMM, TEMP_XMM, target); } else { - binary(code, MOVDQA, MASK_XMM, SOURCE_XMM); - binary(code, PSUBUSW, MASK_XMM, TEMP_XMM); - binary(code, PSUBW, SOURCE_XMM, MASK_XMM); + binary(code, Host::MoveAligned, MASK_XMM, SOURCE_XMM); + binary(code, Host::SubUnsignedSaturatingWord, MASK_XMM, TEMP_XMM); + binary(code, Host::SubWord, SOURCE_XMM, MASK_XMM); } } - binary(code, PACKUSWB, SOURCE_XMM, SOURCE_XMM); + binary(code, Host::PackUnsignedWordToByte, SOURCE_XMM, SOURCE_XMM); } else if target.supports(TargetCpu::Sse41) { if !signed_input(operand.kind) { constant(code, TEMP_XMM, UNSIGNED_WORD_MAX_DWORDS); @@ -449,52 +424,52 @@ fn narrow( } Host::PackUnsignedDwordToWord.register(code, SOURCE_XMM, SOURCE_XMM, target); } else { - // PACKSSDW after a 32768 bias represents the full unsigned word range. + // Host::PackSignedDwordToWord after a 32768 bias represents the full unsigned word range. if signed_input(operand.kind) { - binary(code, PXOR, TEMP_XMM, TEMP_XMM); - binary(code, PCMPGTD, TEMP_XMM, SOURCE_XMM); - binary(code, PANDN, TEMP_XMM, SOURCE_XMM); - binary(code, MOVDQA, SOURCE_XMM, TEMP_XMM); + binary(code, Host::Xor, TEMP_XMM, TEMP_XMM); + binary(code, Host::GreaterDword, TEMP_XMM, SOURCE_XMM); + binary(code, Host::AndNot, TEMP_XMM, SOURCE_XMM); + binary(code, Host::MoveAligned, SOURCE_XMM, TEMP_XMM); } unsigned_min_words(code); constant(code, TEMP_XMM, PACK_WORD_BIAS); - binary(code, PSUBD, SOURCE_XMM, TEMP_XMM); - binary(code, PACKSSDW, SOURCE_XMM, SOURCE_XMM); + binary(code, Host::SubDword, SOURCE_XMM, TEMP_XMM); + binary(code, Host::PackSignedDwordToWord, SOURCE_XMM, SOURCE_XMM); constant(code, TEMP_XMM, PACKED_WORD_SIGN); - binary(code, PXOR, SOURCE_XMM, TEMP_XMM); + binary(code, Host::Xor, SOURCE_XMM, TEMP_XMM); } if projection == NarrowProjection::Packed { clear_packed_upper(code); return; } - binary(code, PXOR, TEMP_XMM, TEMP_XMM); + binary(code, Host::Xor, TEMP_XMM, TEMP_XMM); binary( code, if small == BYTE_BITS { - PUNPCKLBW + Host::UnpackLowByte } else { - PUNPCKLWD + Host::UnpackLowWord }, SOURCE_XMM, TEMP_XMM, ); } -fn unsigned_min_words(code: &mut Vec) { - binary(code, MOVDQA, TEMP_XMM, SOURCE_XMM); +fn unsigned_min_words(code: &mut Code) { + binary(code, Host::MoveAligned, TEMP_XMM, SOURCE_XMM); constant(code, MASK_XMM, SIGN_DWORDS); - binary(code, PXOR, TEMP_XMM, MASK_XMM); + binary(code, Host::Xor, TEMP_XMM, MASK_XMM); constant(code, MASK_XMM, BIASED_UNSIGNED_WORD_MAX); - binary(code, PCMPGTD, TEMP_XMM, MASK_XMM); + binary(code, Host::GreaterDword, TEMP_XMM, MASK_XMM); constant(code, MASK_XMM, UNSIGNED_WORD_MAX_DWORDS); - binary(code, PAND, MASK_XMM, TEMP_XMM); - binary(code, PANDN, TEMP_XMM, SOURCE_XMM); - binary(code, POR, TEMP_XMM, MASK_XMM); - binary(code, MOVDQA, SOURCE_XMM, TEMP_XMM); + binary(code, Host::And, MASK_XMM, TEMP_XMM); + binary(code, Host::AndNot, TEMP_XMM, SOURCE_XMM); + binary(code, Host::Or, TEMP_XMM, MASK_XMM); + binary(code, Host::MoveAligned, SOURCE_XMM, TEMP_XMM); } fn merge_top( - code: &mut Vec, + code: &mut Code, operand: Operand, chunk: usize, result: u8, @@ -505,79 +480,79 @@ fn merge_top( return; } let small = operand.element_size.bits() as u8; - shift(code, 2 * small, LEFT_LOGICAL, result, small); + shift(code, 2 * small, Direction::Left, result, small); load_z_chunk(code, operand.destination, chunk, TEMP_XMM, length, target); constant(code, MASK_XMM, low_mask(small)); - binary(code, PAND, TEMP_XMM, MASK_XMM); - binary(code, POR, result, TEMP_XMM); + binary(code, Host::And, TEMP_XMM, MASK_XMM); + binary(code, Host::Or, result, TEMP_XMM); } -fn scalar_narrow_qwords(code: &mut Vec, operand: Operand) { - binary(code, PXOR, RESULT_XMM, RESULT_XMM); +fn scalar_narrow_qwords(code: &mut Code, operand: Operand) { + binary(code, Host::Xor, RESULT_XMM, RESULT_XMM); for offset in (0..CHUNK_BYTES).step_by(QWORD_BYTES) { - binary(code, MOVDQA, MASK_XMM, SOURCE_XMM); - byte_shift(code, RIGHT_BYTES, MASK_XMM, offset); - code.extend(MOVQ_RAX_XMM); - code.push(REGISTER_MODE | (MASK_XMM << MODRM_REGISTER_SHIFT)); + binary(code, Host::MoveAligned, MASK_XMM, SOURCE_XMM); + byte_shift(code, Shift::RightBytes, MASK_XMM, offset); + code.asm().movq_from_xmm(Rax, MASK_XMM); if !operand.kind.is_extract() { if operand.shift == QWORD_BITS { // x86 scalar shift counts are masked to six bits, so full-width // shifts are handled explicitly. if rounded(operand.kind) && signed_input(operand.kind) { - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); } else if rounded(operand.kind) || signed_input(operand.kind) { - code.extend(if signed_input(operand.kind) { - SAR_RAX - } else { - SHR_RAX - }); - code.push(QWORD_BITS - 1); + code.asm() + .shift_imm(right(operand.kind), Size::Qword, Rax, QWORD_BITS - 1); } else { - code.extend(XOR_EAX_EAX); + code.asm().alu(Alu::Xor, Size::Dword, Rax, Rax); } } else { if rounded(operand.kind) { - code.extend(MOV_RDX_RAX); + code.asm().mov(Size::Qword, Rdx, Rax); } - code.extend(if signed_input(operand.kind) { - SAR_RAX - } else { - SHR_RAX - }); - code.push(operand.shift); + code.asm() + .shift_imm(right(operand.kind), Size::Qword, Rax, operand.shift); if rounded(operand.kind) { if operand.shift != 1 { - code.extend(SHR_RDX); - code.push(operand.shift - 1); + code.asm() + .shift_imm(ShiftOp::Shr, Size::Qword, Rdx, operand.shift - 1); } - code.extend(AND_EDX_ONE); - code.extend(ADD_RAX_RDX); + let mut asm = code.asm(); + asm.alu_imm8(Alu::And, Size::Dword, Rdx, 1); + asm.alu(Alu::Add, Size::Qword, Rax, Rdx); } } } if signed_output(operand.kind) { - scalar_bound(code, i64::from(i32::MIN) as u64, CMOVL_RAX_RDX); - scalar_bound(code, i32::MAX as u64, CMOVG_RAX_RDX); + scalar_bound(code, i64::from(i32::MIN) as u64, Cond::L); + scalar_bound(code, i32::MAX as u64, Cond::G); } else { if signed_input(operand.kind) { - code.extend(XOR_EDX_EDX); - code.extend(TEST_RAX_RAX); - code.extend(CMOVS_RAX_RDX); + let mut asm = code.asm(); + asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); + asm.test(Size::Qword, Rax, Rax); + asm.cmov(Cond::S, Size::Qword, Rax, Rdx); } - scalar_bound(code, u64::from(u32::MAX), CMOVA_RAX_RDX); + scalar_bound(code, u64::from(u32::MAX), Cond::A); } - code.extend(MOV_EAX_EAX); - code.extend(MOVQ_XMM_RAX); - code.push(REGISTER_MODE | (LANE_XMM << MODRM_REGISTER_SHIFT)); - byte_shift(code, LEFT_BYTES, LANE_XMM, offset); - binary(code, POR, RESULT_XMM, LANE_XMM); + code.asm().mov(Size::Dword, Rax, Rax); + code.asm().movq_to_xmm(LANE_XMM, Rax); + byte_shift(code, Shift::LeftBytes, LANE_XMM, offset); + binary(code, Host::Or, RESULT_XMM, LANE_XMM); } - binary(code, MOVDQA, SOURCE_XMM, RESULT_XMM); + binary(code, Host::MoveAligned, SOURCE_XMM, RESULT_XMM); } -fn scalar_bound(code: &mut Vec, bound: u64, move_condition: &[u8]) { - code.extend(MOV_RDX_IMM64); - code.extend(bound.to_le_bytes()); - code.extend(CMP_RAX_RDX); - code.extend(move_condition); +fn right(kind: Kind) -> ShiftOp { + if signed_input(kind) { + ShiftOp::Sar + } else { + ShiftOp::Shr + } +} + +fn scalar_bound(code: &mut Code, bound: u64, condition: Cond) { + let mut asm = code.asm(); + asm.mov_imm64(Rdx, bound); + asm.alu(Alu::Cmp, Size::Qword, Rax, Rdx); + asm.cmov(condition, Size::Qword, Rax, Rdx); } diff --git a/crates/stela-compiler/src/x86_64/sve/sign.rs b/crates/stela-compiler/src/x86_64/sve/sign.rs index 320d195fd6..78589e5f8a 100644 --- a/crates/stela-compiler/src/x86_64/sve/sign.rs +++ b/crates/stela-compiler/src/x86_64/sve/sign.rs @@ -1,4 +1,6 @@ //! SVE predicated FABS and FNEG by integer masking; no FP exceptions. +use crate::x86_64::asm::Gpr::{Rcx, Rdi}; +use crate::x86_64::asm::{Code, Cond, Mem, Rm, Size}; use crate::{ GuestState, TargetCpu, aarch64::{ @@ -11,7 +13,6 @@ use crate::{ scalable::{load_z_chunk, read_predicate_mask, store_z_chunk}, }, }; -use alloc::vec::Vec; const SOURCE: u8 = 0; const SIGN: u8 = 1; @@ -21,30 +22,29 @@ const HIGH_GREATER: u8 = 4; const ZERO: u8 = 5; const ACTIVE: u8 = 6; const PREDICATE_SCRATCH: u8 = 7; -const XMM_GPR_RCX: u8 = 1; const BITS_PER_BYTE: u8 = 8; const QWORD_BYTES: u8 = 8; -const REGISTER_DIRECT: u8 = 0xc0; -const REGISTER_FIELD_SHIFT: u8 = 3; const BROADCAST_HIGH_DWORDS: u8 = 0xf5; const BROADCAST_LOW_DWORDS: u8 = 0xa0; -const TEST_STATE_IMM32: &[u8] = &[0xf7, 0x87]; -const JZ_REL32: &[u8] = &[0x0f, 0x84]; -const MOV_RCX_IMM64: &[u8] = &[0x48, 0xb9]; const HALF_INFINITY: u64 = 0x7c00; const SINGLE_INFINITY: u64 = 0x7f80_0000; const DOUBLE_INFINITY: u64 = 0x7ff0_0000_0000_0000; -fn packed(code: &mut Vec, opcode: SimdOpcode, destination: u8, source: u8, target: TargetCpu) { +fn packed(code: &mut Code, opcode: SimdOpcode, destination: u8, source: u8, target: TargetCpu) { opcode.register(code, destination, source, target); } -fn shuffle(code: &mut Vec, register: u8, control: u8, target: TargetCpu) { - packed(code, SimdOpcode::ShuffleDword, register, register, target); - code.push(control); +fn shuffle(code: &mut Code, register: u8, control: u8, target: TargetCpu) { + code.asm().simd_imm( + SimdOpcode::ShuffleDword, + register, + Rm::Xmm(register), + control, + target, + ); } -fn infinity(code: &mut Vec, format: Format, target: TargetCpu) { +fn infinity(code: &mut Code, format: Format, target: TargetCpu) { let (lane, lane_bytes) = match format { Format::Half => (HALF_INFINITY, 2), Format::Single => (SINGLE_INFINITY, 4), @@ -54,21 +54,20 @@ fn infinity(code: &mut Vec, format: Format, target: TargetCpu) { for index in 0..QWORD_BYTES / lane_bytes { low |= lane << (index * lane_bytes * BITS_PER_BYTE); } - code.extend(MOV_RCX_IMM64); - code.extend(low.to_le_bytes()); - // MOVQ's source field denotes a GPR, unlike the other packed helpers. - SimdOpcode::MoveGprQword.append(code, target); - code.push(REGISTER_DIRECT | (INFINITY << REGISTER_FIELD_SHIFT) | XMM_GPR_RCX); + let mut asm = code.asm(); + asm.mov_imm64(Rcx, low); + asm.simd(SimdOpcode::MoveGprQword, INFINITY, Rcx, target); packed(code, SimdOpcode::UnpackLowQword, INFINITY, INFINITY, target); } -fn suppress_nan_sign(code: &mut Vec, format: Format, target: TargetCpu) { - code.extend(TEST_STATE_IMM32); - code.extend((core::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); - code.extend(FPCR_AH.to_le_bytes()); - code.extend(JZ_REL32); - let ordinary_patch = code.len(); - code.extend(0i32.to_le_bytes()); +fn suppress_nan_sign(code: &mut Code, format: Format, target: TargetCpu) { + let mut asm = code.asm(); + asm.test_imm( + Size::Dword, + Mem::base_disp32(Rdi, core::mem::offset_of!(GuestState, fpcr) as i32), + FPCR_AH as i32, + ); + let ordinary = asm.jcc(Cond::E); packed(code, SimdOpcode::MoveAligned, SELECTED_SIGN, SIGN, target); packed(code, SimdOpcode::AndNot, SELECTED_SIGN, SOURCE, target); @@ -131,15 +130,11 @@ fn suppress_nan_sign(code: &mut Vec, format: Format, target: TargetCpu) { } } packed(code, SimdOpcode::AndNot, SELECTED_SIGN, SIGN, target); - let end = code.len(); - let distance = i32::try_from(end - ordinary_patch - size_of::()) - .expect("bounded sign-classification branch"); - code[ordinary_patch..ordinary_patch + size_of::()] - .copy_from_slice(&distance.to_le_bytes()); + code.asm().bind(ordinary); } /// Access and profile checks must precede this total, register-only emitter. -pub(crate) fn emit(code: &mut Vec, operand: &Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, operand: &Operand, length: VectorLength, target: TargetCpu) { let operation = match operand.kind { Kind::Absolute => SimdOpcode::AndNot, Kind::Negate => SimdOpcode::Xor, diff --git a/crates/stela-compiler/src/x86_64/sve/tables.rs b/crates/stela-compiler/src/x86_64/sve/tables.rs index 6eac7dc728..3923dc0c88 100644 --- a/crates/stela-compiler/src/x86_64/sve/tables.rs +++ b/crates/stela-compiler/src/x86_64/sve/tables.rs @@ -1,5 +1,7 @@ //! SVE LUTI2/LUTI4: fixed-load SSE2 selection or SSSE3 PSHUFB. Neither path //! branches on or addresses memory with index values. +use crate::x86_64::asm::Gpr::Rsp; +use crate::x86_64::asm::{Alu, Code, Mem, Size}; use crate::{ TargetCpu, aarch64::{ @@ -11,25 +13,18 @@ use crate::{ scalable::{load_z_chunk, store_z_chunk}, }, }; -use alloc::vec::Vec; -const SUB_RSP: &[u8] = &[0x48, 0x81, 0xec]; -const ADD_RSP: &[u8] = &[0x48, 0x81, 0xc4]; -const STACK_DISP32: u8 = 0x84; -const STACK_SIB: u8 = 0x24; -const XMM_SHIFT: u8 = 3; const LOW_TABLE: u8 = 4; const HIGH_TABLE: u8 = 5; const OUTPUT: u8 = 6; -fn stack(code: &mut Vec, opcode: Host, xmm: u8, offset: usize, target: TargetCpu) { - opcode.append(code, target); - code.extend([STACK_DISP32 | (xmm << XMM_SHIFT), STACK_SIB]); - code.extend((offset as u32).to_le_bytes()); +fn stack(code: &mut Code, opcode: Host, xmm: u8, offset: usize, target: TargetCpu) { + code.asm() + .simd(opcode, xmm, Mem::base_disp32(Rsp, offset as i32), target); } -pub(crate) fn emit(code: &mut Vec, op: &Operand, length: VectorLength, target: TargetCpu) { +pub(crate) fn emit(code: &mut Code, op: &Operand, length: VectorLength, target: TargetCpu) { assert!(length.bits() >= op.minimum_vl_bits()); - code.extend(SUB_RSP); - code.extend((length.bytes() as u32).to_le_bytes()); + code.asm() + .alu_imm32(Alu::Sub, Size::Qword, Rsp, length.bytes() as i32); for chunk in 0..length.chunks() { load_z_chunk(code, op.indexes, chunk, 0, length, target); stack( @@ -74,6 +69,6 @@ pub(crate) fn emit(code: &mut Vec, op: &Operand, length: VectorLength, targe crate::x86_64::scalable::lut::emit_chunk(code, op.index_bits, op.element, target); store_z_chunk(code, op.destination, chunk, OUTPUT, length, target); } - code.extend(ADD_RSP); - code.extend((length.bytes() as u32).to_le_bytes()); + code.asm() + .alu_imm32(Alu::Add, Size::Qword, Rsp, length.bytes() as i32); } diff --git a/crates/stela-compiler/src/x86_64/system/synchronization.rs b/crates/stela-compiler/src/x86_64/system/synchronization.rs index c7cf1f6a0b..5a61d32fdc 100644 --- a/crates/stela-compiler/src/x86_64/system/synchronization.rs +++ b/crates/stela-compiler/src/x86_64/system/synchronization.rs @@ -1,12 +1,10 @@ //! Barriers and hints (ISB, SB, NOP, YIELD, ...). use crate::aarch64::system::synchronization::Operation; -use alloc::vec::Vec; - -const MOV_R8_RBX: &[u8] = &[0x49, 0x89, 0xd8]; -const XOR_EAX_EAX: &[u8] = &[0x31, 0xc0]; -const CPUID: &[u8] = &[0x0f, 0xa2]; -const MOV_RBX_R8: &[u8] = &[0x4c, 0x89, 0xc3]; -const PAUSE: &[u8] = &[0xf3, 0x90]; +use crate::x86_64::asm::{ + Alu, Code, + Gpr::{R8, Rax, Rbx}, + Size, +}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum EmitError { @@ -16,16 +14,17 @@ pub enum EmitError { /// Emit the barriers and hints that need no system context. R8 is scratch. /// CPUID leaf 0 serializes; RBX is saved around it. Other operations go to the /// runtime. -pub fn emit(code: &mut Vec, operation: &Operation) -> Result<(), EmitError> { +pub fn emit(code: &mut Code, operation: &Operation) -> Result<(), EmitError> { match operation { - Operation::Yield => code.extend_from_slice(PAUSE), + Operation::Yield => code.asm().pause(), Operation::ConsumptionBarrier | Operation::SpeculationBarrier | Operation::StoreBypassBarrier { .. } => { - code.extend_from_slice(MOV_R8_RBX); - code.extend_from_slice(XOR_EAX_EAX); - code.extend_from_slice(CPUID); - code.extend_from_slice(MOV_RBX_R8); + let mut asm = code.asm(); + asm.mov(Size::Qword, R8, Rbx); + asm.alu(Alu::Xor, Size::Dword, Rax, Rax); + asm.cpuid(); + asm.mov(Size::Qword, Rbx, R8); } _ => return Err(EmitError::ContextRequired), } @@ -37,29 +36,32 @@ mod tests { use super::*; use crate::aarch64::system::synchronization::{Requirement, Scope, WaitKind}; use alloc::vec; - use alloc::vec::Vec; + + /// `mov r8,rbx; xor eax,eax; cpuid; mov rbx,r8`. + const SERIALIZATION: [u8; 10] = [0x49, 0x89, 0xd8, 0x31, 0xc0, 0x0f, 0xa2, 0x4c, 0x89, 0xc3]; #[test] fn baseline_barriers_share_real_serialization() { - let expected: Vec<_> = [MOV_R8_RBX, XOR_EAX_EAX, CPUID, MOV_RBX_R8].concat(); - assert_eq!(expected.len(), 10); + let expected = SERIALIZATION; for operation in [ Operation::ConsumptionBarrier, Operation::SpeculationBarrier, Operation::StoreBypassBarrier { physical: false }, Operation::StoreBypassBarrier { physical: true }, ] { - let mut code = vec![]; + let mut code = Code::new(); assert_eq!(emit(&mut code, &operation), Ok(())); assert_eq!(code, expected); + assert_eq!(code.instructions(), 4); } } #[test] fn yield_uses_pause() { - let mut code = vec![]; + let mut code = Code::new(); assert_eq!(emit(&mut code, &Operation::Yield), Ok(())); - assert_eq!(code, PAUSE); + assert_eq!(code, [0xf3, 0x90]); + assert_eq!(code.instructions(), 1); } #[test] @@ -88,7 +90,7 @@ mod tests { Operation::TraceSynchronization, Operation::OtherHint { immediate: 127 }, ] { - let mut code = sentinel.clone(); + let mut code = Code::from(sentinel.clone()); assert_eq!(emit(&mut code, &operation), Err(EmitError::ContextRequired)); assert_eq!(code, sentinel); } diff --git a/crates/stela-compiler/src/x86_64/tag_arithmetic.rs b/crates/stela-compiler/src/x86_64/tag_arithmetic.rs index 1d340c5579..2b390092bf 100644 --- a/crates/stela-compiler/src/x86_64/tag_arithmetic.rs +++ b/crates/stela-compiler/src/x86_64/tag_arithmetic.rs @@ -1,14 +1,11 @@ //! MTE tag arithmetic under the fixed guest tag controls. use super::{Register, Shift, Width, load, offset, right_operand, store}; +use crate::x86_64::asm::{Alu, BitTest, Code, Cond, Gpr, Mem, ShiftOp, Size}; use crate::{ GuestState, aarch64::tag_arithmetic::{Kind, Operand}, }; -use alloc::vec::Vec; -const NOP: u8 = 0x90; -const REX_W_PREFIX: u8 = 0x48; -const TWO_BYTE_OPCODE: u8 = 0x0f; const HIGH_BYTE_OFFSET: u32 = 7; const TOP_BYTE_ROTATE: u8 = 8; const SIGN_EXTEND_SHIFT: u8 = 8; @@ -19,43 +16,17 @@ const NZCV_OFFSET: u32 = core::mem::offset_of!(GuestState, nzcv) as u32; const N_SHIFT: u8 = 31; const Z_SHIFT: u8 = 30; const C_SHIFT: u8 = 29; -const MOVZX_ECX_STATE_BYTE: &[u8] = &[TWO_BYTE_OPCODE, 0xb6, 0x8f]; -const ADD_ECX_IMM8: &[u8] = &[0x83, 0xc1]; -const AND_ECX_IMM8: &[u8] = &[0x83, 0xe1]; -const ADD_RAX_IMM32: &[u8] = &[REX_W_PREFIX, 0x05]; -const SUB_RAX_IMM32: &[u8] = &[REX_W_PREFIX, 0x2d]; -const LEA_RAX_RAX_DISP8: &[u8] = &[REX_W_PREFIX, 0x8d, 0x40]; -const ROL_RAX_IMM8: &[u8] = &[REX_W_PREFIX, 0xc1, 0xc0]; -const ROR_RAX_IMM8: &[u8] = &[REX_W_PREFIX, 0xc1, 0xc8]; -const AND_AL_IMM8: u8 = 0x24; -const OR_AL_CL: &[u8] = &[0x08, 0xc8]; -const SHL_RAX_IMM8: &[u8] = &[REX_W_PREFIX, 0xc1, 0xe0]; -const SAR_RAX_IMM8: &[u8] = &[REX_W_PREFIX, 0xc1, 0xf8]; -const SHL_RCX_IMM8: &[u8] = &[REX_W_PREFIX, 0xc1, 0xe1]; -const SAR_RCX_IMM8: &[u8] = &[REX_W_PREFIX, 0xc1, 0xf9]; -const SUB_RAX_RCX: &[u8] = &[REX_W_PREFIX, 0x29, 0xc8]; -const BTS_RAX_RCX: &[u8] = &[REX_W_PREFIX, TWO_BYTE_OPCODE, 0xab, 0xc8]; -const MOV_EDX_IMM32: u8 = 0xba; -const SHL_EDX_CL: &[u8] = &[0xd3, 0xe2]; -const OR_STATE_RDX: &[u8] = &[REX_W_PREFIX, 0x09, 0x97]; -const SETS_AL: &[u8] = &[TWO_BYTE_OPCODE, 0x98, 0xc0]; -const SETE_CL: &[u8] = &[TWO_BYTE_OPCODE, 0x94, 0xc1]; -const SETAE_DL: &[u8] = &[TWO_BYTE_OPCODE, 0x93, 0xc2]; -const MOVZX_EAX_AL: &[u8] = &[TWO_BYTE_OPCODE, 0xb6, 0xc0]; -const MOVZX_ECX_CL: &[u8] = &[TWO_BYTE_OPCODE, 0xb6, 0xc9]; -const MOVZX_EDX_DL: &[u8] = &[TWO_BYTE_OPCODE, 0xb6, 0xd2]; -const SHL_EAX_IMM8: &[u8] = &[0xc1, 0xe0]; -const SHL_ECX_IMM8: &[u8] = &[0xc1, 0xe1]; -const SHL_EDX_IMM8: &[u8] = &[0xc1, 0xe2]; -const OR_EAX_ECX: &[u8] = &[0x09, 0xc8]; -const OR_EAX_EDX: &[u8] = &[0x09, 0xd0]; -const MOV_STATE_EAX: &[u8] = &[0x89, 0x87]; -pub(super) fn emit(code: &mut Vec, operand: &Operand) { +/// The guest state field at `offset` from RDI. +const fn state(offset: u32) -> Mem { + Mem::base_disp32(Gpr::Rdi, offset as i32) +} + +pub(super) fn emit(code: &mut Code, operand: &Operand) { if operand.destination == Register::Zero && !matches!(operand.kind, Kind::Difference { flags: true, .. }) { - code.push(NOP); + code.asm().nop(); return; } match operand.kind { @@ -79,11 +50,12 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { right_operand(code, right, Width::X64, Shift::Lsl, 0); // Each signed56 input must be extended independently: their difference // requires57 bits and cannot be recovered from a wrapped shifted SUB. - for instruction in [SHL_RAX_IMM8, SAR_RAX_IMM8, SHL_RCX_IMM8, SAR_RCX_IMM8] { - code.extend(instruction); - code.push(SIGN_EXTEND_SHIFT); + let mut asm = code.asm(); + for register in [Gpr::Rax, Gpr::Rcx] { + asm.shift_imm(ShiftOp::Shl, Size::Qword, register, SIGN_EXTEND_SHIFT); + asm.shift_imm(ShiftOp::Sar, Size::Qword, register, SIGN_EXTEND_SHIFT); } - code.extend(SUB_RAX_RCX); + asm.alu(Alu::Sub, Size::Qword, Gpr::Rax, Gpr::Rcx); store(code, operand.destination); if flags { emit_difference_flags(code); @@ -95,20 +67,23 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { } } -fn tag_input(code: &mut Vec, source: Register, increment: u8) { +fn tag_input(code: &mut Code, source: Register, increment: u8) { let source_offset = offset(source).expect("tag address source is GPR or SP"); - code.extend(MOVZX_ECX_STATE_BYTE); - code.extend((source_offset + HIGH_BYTE_OFFSET).to_le_bytes()); + let mut asm = code.asm(); + asm.movzx( + Size::Dword, + Gpr::Rcx, + Size::Byte, + state(source_offset + HIGH_BYTE_OFFSET), + ); if increment != 0 { - code.extend(ADD_ECX_IMM8); - code.push(increment); + asm.alu_imm8(Alu::Add, Size::Dword, Gpr::Rcx, increment as i8); } - code.extend(AND_ECX_IMM8); - code.push(TAG_MASK); + asm.alu_imm8(Alu::And, Size::Dword, Gpr::Rcx, TAG_MASK as i8); } fn emit_offset( - code: &mut Vec, + code: &mut Code, destination: Register, source: Register, subtract: bool, @@ -117,7 +92,7 @@ fn emit_offset( ) { if address_offset == 0 && tag_offset == 0 { if destination == source { - code.push(NOP); + code.asm().nop(); } else { load(code, source); store(code, destination); @@ -128,73 +103,65 @@ fn emit_offset( // Extract the tag before the address arithmetic; the carry or borrow may // cross the tag field and must still reach the preserved high nibble. tag_input(code, source, tag_offset); + let mut asm = code.asm(); if address_offset != 0 { let displacement = i32::from(address_offset) * if subtract { -1 } else { 1 }; if let Ok(displacement) = i8::try_from(displacement) { - code.extend(LEA_RAX_RAX_DISP8); - code.extend(displacement.to_le_bytes()); + asm.lea( + Size::Qword, + Gpr::Rax, + Mem::base_disp8(Gpr::Rax, displacement), + ); } else { - code.extend(if subtract { - SUB_RAX_IMM32 - } else { - ADD_RAX_IMM32 - }); - code.extend(u32::from(address_offset).to_le_bytes()); + let op = if subtract { Alu::Sub } else { Alu::Add }; + asm.alu_accumulator_imm32(op, Size::Qword, i32::from(address_offset)); } } - code.extend(ROL_RAX_IMM8); - code.extend([TOP_BYTE_ROTATE, AND_AL_IMM8, TOP_NIBBLE_MASK]); - code.extend(OR_AL_CL); - code.extend(ROR_RAX_IMM8); - code.push(TOP_BYTE_ROTATE); + asm.shift_imm(ShiftOp::Rol, Size::Qword, Gpr::Rax, TOP_BYTE_ROTATE); + asm.alu_accumulator_imm8(Alu::And, TOP_NIBBLE_MASK); + asm.alu(Alu::Or, Size::Byte, Gpr::Rax, Gpr::Rcx); + asm.shift_imm(ShiftOp::Ror, Size::Qword, Gpr::Rax, TOP_BYTE_ROTATE); store(code, destination); } -fn emit_mask(code: &mut Vec, destination: Register, address: Register, mask: Register) { +fn emit_mask(code: &mut Code, destination: Register, address: Register, mask: Register) { if destination == mask { // Read the tag before any in-place update, including when the address // aliases the mask. EDX's high half stays zero for tags 0-15. tag_input(code, address, 0); - code.push(MOV_EDX_IMM32); - code.extend(MASK_BIT.to_le_bytes()); - code.extend(SHL_EDX_CL); - code.extend(OR_STATE_RDX); - code.extend( - offset(mask) - .expect("discarded GMI was handled before emission") - .to_le_bytes(), - ); + let mask = offset(mask).expect("discarded GMI was handled before emission"); + let mut asm = code.asm(); + asm.mov_imm32(Gpr::Rdx, MASK_BIT); + asm.shift_cl(ShiftOp::Shl, Size::Dword, Gpr::Rdx); + asm.alu(Alu::Or, Size::Qword, state(mask), Gpr::Rdx); } else { load(code, mask); tag_input(code, address, 0); - code.extend(BTS_RAX_RCX); + code.asm() + .bit(BitTest::Bts, Size::Qword, Gpr::Rax, Gpr::Rcx); store(code, destination); } } -fn emit_difference_flags(code: &mut Vec) { +fn emit_difference_flags(code: &mut Code) { // Signed56 differences cannot overflow signed64, so guest V is always0. // Capture all three predicates before shifts/ORs alter the host flags. - for instruction in [ - SETS_AL, - SETE_CL, - SETAE_DL, - MOVZX_EAX_AL, - MOVZX_ECX_CL, - MOVZX_EDX_DL, - ] { - code.extend(instruction); + let flags = [ + (Cond::S, Gpr::Rax, N_SHIFT), + (Cond::E, Gpr::Rcx, Z_SHIFT), + (Cond::Ae, Gpr::Rdx, C_SHIFT), + ]; + let mut asm = code.asm(); + for (condition, register, _) in flags { + asm.setcc(condition, register); } - for (instruction, amount) in [ - (SHL_EAX_IMM8, N_SHIFT), - (SHL_ECX_IMM8, Z_SHIFT), - (SHL_EDX_IMM8, C_SHIFT), - ] { - code.extend(instruction); - code.push(amount); + for (_, register, _) in flags { + asm.movzx(Size::Dword, register, Size::Byte, register); } - code.extend(OR_EAX_ECX); - code.extend(OR_EAX_EDX); - code.extend(MOV_STATE_EAX); - code.extend(NZCV_OFFSET.to_le_bytes()); + for (_, register, amount) in flags { + asm.shift_imm(ShiftOp::Shl, Size::Dword, register, amount); + } + asm.alu(Alu::Or, Size::Dword, Gpr::Rax, Gpr::Rcx); + asm.alu(Alu::Or, Size::Dword, Gpr::Rax, Gpr::Rdx); + asm.mov_store(Size::Dword, state(NZCV_OFFSET), Gpr::Rax); } diff --git a/crates/stela-compiler/src/x86_64/unprivileged.rs b/crates/stela-compiler/src/x86_64/unprivileged.rs index 1b30e6b69b..34d333ca98 100644 --- a/crates/stela-compiler/src/x86_64/unprivileged.rs +++ b/crates/stela-compiler/src/x86_64/unprivileged.rs @@ -2,9 +2,9 @@ //! incoming SP and keeps completed store prefixes on a fault. use super::{AddressMode, memory}; use crate::aarch64::unprivileged::Operand; -use alloc::vec::Vec; +use crate::x86_64::asm::Code; -pub(super) fn emit(code: &mut Vec, operand: &Operand, checks: super::MemoryChecks) { +pub(super) fn emit(code: &mut Code, operand: &Operand, checks: super::MemoryChecks) { memory( code, checks, diff --git a/crates/stela-compiler/src/x86_64/zero_block.rs b/crates/stela-compiler/src/x86_64/zero_block.rs index 66b52fbcba..63948a94f5 100644 --- a/crates/stela-compiler/src/x86_64/zero_block.rs +++ b/crates/stela-compiler/src/x86_64/zero_block.rs @@ -1,5 +1,5 @@ //! DC ZVA in system-mode blocks the engine compiles where it neither traps -//! nor is UNDEFINED (`CompilationPlan::with_zero_block`): Arm +//! nor is UNDEFINED (`Options::with_native_system`): Arm //! `AArch64_MemZero` writes zeroes to the DCZID_EL0.BS block holding Xt, //! aligned down, through the same direct guest-VA stores as STR, after the //! guest range check. The block is at most 2 KiB and naturally aligned, so @@ -13,7 +13,7 @@ use crate::aarch64::{ system::registers::{Direction, Encoding}, }; use crate::block::{SystemInstruction, system::SystemOperation}; -use alloc::vec::Vec; +use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, Size, resolve}; /// DC ZVA: SYS #3, C7, C4, #1. const DC_ZVA: Encoding = Encoding::new(1, 3, 7, 4, 1); @@ -39,7 +39,7 @@ pub fn operand(instruction: &SystemInstruction) -> Option { /// Zero the `bytes` block (a power of two in [`MIN_BYTES`]..=[`MAX_BYTES`]) /// holding Xt. -pub(crate) fn emit(code: &mut Vec, rt: u8, bytes: u16, checks: super::MemoryChecks) { +pub(crate) fn emit(code: &mut Code, rt: u8, bytes: u16, checks: super::MemoryChecks) { debug_assert!(bytes.is_power_of_two() && (MIN_BYTES..=MAX_BYTES).contains(&bytes)); super::load( code, @@ -53,24 +53,33 @@ pub(crate) fn emit(code: &mut Vec, rt: u8, bytes: u16, checks: super::Memory // block is. super::range_check(code, checks, super::Access::write(bytes)); let mask = -i32::from(bytes); - if let Ok(mask) = i8::try_from(mask) { - code.extend([0x48, 0x83, 0xe0, mask as u8]); // and rax,-bytes - } else { - code.extend([0x48, 0x25]); // and rax,-bytes - code.extend(mask.to_le_bytes()); + let mut asm = code.asm(); + match i8::try_from(mask) { + Ok(mask) => asm.alu_imm8(Alu::And, Size::Qword, Gpr::Rax, mask), + Err(_) => asm.alu_accumulator_imm32(Alu::And, Size::Qword, mask), } - code.extend([0x31, 0xc9]); // xor ecx,ecx + asm.alu(Alu::Xor, Size::Dword, Gpr::Rcx, Gpr::Rcx); if bytes < 8 { - code.extend([0x89, 0x08]); // mov [rax],ecx + asm.mov_store(Size::Dword, Mem::base(Gpr::Rax, 0), Gpr::Rcx); } else if bytes <= UNROLLED_BYTES { for offset in (0..bytes).step_by(8) { - code.extend([0x48, 0x89, 0x48, offset as u8]); // mov [rax+offset],rcx + asm.mov_store( + Size::Qword, + Mem::base_disp8(Gpr::Rax, offset as i8), + Gpr::Rcx, + ); } } else { - code.push(0xba); // mov edx,bytes/8 - code.extend((u32::from(bytes) / 8).to_le_bytes()); - // mov [rax+rdx*8-8],rcx; dec edx; jnz back to the store - code.extend([0x48, 0x89, 0x4c, 0xd0, 0xf8, 0xff, 0xca, 0x75, 0xf7]); + asm.mov_imm32(Gpr::Rdx, u32::from(bytes) / 8); + let store = asm.len(); + asm.mov_store( + Size::Qword, + Mem::indexed(Gpr::Rax, Gpr::Rdx, 8, -8), + Gpr::Rcx, + ); + asm.dec(Size::Dword, Gpr::Rdx); + let back = asm.jcc8(Cond::Ne); + resolve(code, back, store); } } @@ -126,9 +135,9 @@ mod tests { let mut state = GuestState::default(); // Xt points inside the block, past its start. state.x[5] = block + u64::from(bytes) - 1; - let mut code = Vec::new(); + let mut code = Code::new(); emit(&mut code, 5, bytes, super::super::MemoryChecks::DEFAULT); - code.push(0xc3); // ret + code.asm().ret(); // SAFETY: private anonymous memory, RX after the copy, unmapped // after the call; the code writes only inside `memory`. unsafe { diff --git a/crates/stela-dev/src/compile.rs b/crates/stela-dev/src/compile.rs index a53c87d57e..094e5b2766 100644 --- a/crates/stela-dev/src/compile.rs +++ b/crates/stela-dev/src/compile.rs @@ -4,8 +4,9 @@ use anyhow::{Context, Result, ensure}; use clap::Args; use std::path::{Path, PathBuf}; use stela_compiler::{ - block::BlockProfile, - extended::{ScalableProfile, block::ExtendedBlockProfile}, + GuestAddress, Options, + block::{BlockProfile, CompilationPlan, Features}, + scalable_context::ScalableProfile, }; use stela_runtime::write_json; @@ -22,7 +23,7 @@ pub(crate) struct CompileBlock { #[arg(long, default_value = "0x100000", value_parser = parse_address)] guest_base: u64, /// Compile for a guest execution profile. - #[arg(long, requires_all = ["svl_bytes", "svcr"], value_parser = [stela_compiler::extended::PROFILE_ID, stela_compiler::extended::DECLARED_PROFILE_ID])] + #[arg(long, requires_all = ["svl_bytes", "svcr"], value_parser = [stela_compiler::scalable_context::PROFILE_ID, stela_compiler::scalable_context::DECLARED_PROFILE_ID])] guest_profile: Option, /// Streaming vector length in bytes: 16, 32, 64, 128 or 256. #[arg(long, requires = "guest_profile", value_parser = parse_scalable_vector_length)] @@ -98,7 +99,7 @@ pub(crate) struct CompileLeaf { #[arg(long, default_value = "0x100000", value_parser = parse_address)] guest_base: u64, /// Compile for a guest execution profile. - #[arg(long, requires_all = ["svl_bytes", "svcr"], value_parser = [stela_compiler::extended::PROFILE_ID, stela_compiler::extended::DECLARED_PROFILE_ID])] + #[arg(long, requires_all = ["svl_bytes", "svcr"], value_parser = [stela_compiler::scalable_context::PROFILE_ID, stela_compiler::scalable_context::DECLARED_PROFILE_ID])] guest_profile: Option, /// Streaming vector length in bytes: 16, 32, 64, 128 or 256. #[arg(long, requires = "guest_profile", value_parser = parse_scalable_vector_length)] @@ -164,18 +165,20 @@ pub(crate) fn cpu_info() -> Result<()> { } impl CompileBlock { - /// The service profile and, for scalable guests, the contextual profile. - fn profiles(&self) -> Result<(BlockProfile, Option)> { + /// What the block compiles for: its services, or for a scalable guest + /// the context block's specialization. + fn options(&self) -> Result { let services = if self.system_mode { - BlockProfile::SystemModeV1 + BlockProfile::new(Features::SYSTEM_MODE) } else if self.checked_process_sa0_off { - BlockProfile::CheckedMemoryPauthClockThread(checked_process(self.checked_pointer_mode)?) + BlockProfile::new(Features::PROCESS_HELPERS) + .with_checked_memory(checked_process(self.checked_pointer_mode)?) } else if self.checked_memory_sa0_off { - BlockProfile::CheckedMemory( + BlockProfile::ORDINARY.with_checked_memory( stela_compiler::block::CheckedMemoryProfile::SpAlignmentDisabled, ) } else if self.system_boundaries { - BlockProfile::SystemV1 + BlockProfile::new(Features::SYSTEM) } else { block_profile( self.software_pauth, @@ -199,55 +202,33 @@ impl CompileBlock { self.ebf16, self.rpres, )?; - Ok((services, context)) + Ok(match context { + Some((scalable, numerical)) => { + Options::new(BlockProfile::new(Features::CONTEXT), self.cpu_target) + .with_scalable(scalable) + .with_numerical_features(numerical) + } + None => Options::new(services, self.cpu_target), + }) } fn compile(self, source: &[u8]) -> Result { - let (profile, context_profile) = self.profiles()?; + let options = self.options()?; let Self { cpu_target, guest_base, fpmr_enabled, - checked_memory_sa0_off, - checked_process_sa0_off, .. } = self; let window = &source[..source .len() .min(stela_compiler::block::MAX_BLOCK_INSTRUCTIONS * 4)]; - let preparation_plan = if checked_memory_sa0_off || checked_process_sa0_off { - Some(stela_compiler::block::CompilationPlan::new( - window, - stela_compiler::GuestAddress(guest_base), - profile, - cpu_target, - )?) - } else { - None - }; - let preparation_requirements = preparation_plan - .as_ref() - .and_then(|plan| plan.memory_requirements()); - let compiled = if let Some(context_profile) = context_profile { - stela_compiler::extended::block::compile_for_profile( - window, - stela_compiler::GuestAddress(guest_base), - context_profile, - cpu_target, - )? - } else if let Some(plan) = preparation_plan { - plan.compile()? - } else { - stela_compiler::block::compile_for_target( - window, - stela_compiler::GuestAddress(guest_base), - profile, - cpu_target, - )? - }; + let plan = CompilationPlan::new(window, GuestAddress(guest_base), &options)?; + let preparation_requirements = plan.memory_requirements(); + let compiled = plan.compile()?; let mut manifest = serde_json::json!({"schema_version":1,"kind":"raw_arm64_block_aot","target_cpu":cpu_target.id(), "source_bytes":compiled.source_bytes,"source_sha256":stela_runtime::sha256(&source[..compiled.source_bytes]), - "guest_base":guest_base,"abi":profile.abi(), + "guest_base":guest_base,"abi":options.profile().abi(), "native_sha256":stela_runtime::sha256(&compiled.native.x86_64_code), "native_bytes":compiled.native.x86_64_code.len(),"source_map":compiled.native.source_map, "compiler_source_sha256":stela_compiler::SOURCE_SHA256, @@ -255,17 +236,14 @@ impl CompileBlock { if preparation_requirements.is_some() { manifest["memory_requirements"] = serde_json::to_value(preparation_requirements)?; } - if let Some(context_profile) = context_profile { + if let Some(scalable) = options.scalable() { manifest["schema_version"] = serde_json::json!(2); - manifest["abi"] = serde_json::json!(stela_compiler::context::CONTEXT_BLOCK_ABI); - manifest["execution_profile"] = - scalable_execution_manifest(context_profile.scalable(), fpmr_enabled)?; - manifest["numerical_features"] = - serde_json::to_value(context_profile.numerical_features())?; + manifest["execution_profile"] = scalable_execution_manifest(scalable, fpmr_enabled)?; + manifest["numerical_features"] = serde_json::to_value(options.numerical_features())?; manifest["guest_instructions"] = serde_json::json!(compiled.source_bytes / size_of::()); manifest["entry_prefix_bytes"] = - serde_json::json!(stela_compiler::extended::CONTEXT_WRAPPER_BYTES); + serde_json::json!(stela_compiler::scalable_context::CONTEXT_WRAPPER_BYTES); } Ok(Compiled { native: compiled.native.x86_64_code, @@ -320,30 +298,17 @@ impl CompileLeaf { fpmr_enabled, .. } = self; - let memory_requirements = profile - .map(|profile| { - stela_compiler::extended::memory_requirements( - source, - stela_compiler::GuestAddress(guest_base), - profile, - cpu_target, - ) - }) - .transpose()?; - let block = if let Some(profile) = profile { - stela_compiler::extended::compile_for_profile( - source, - stela_compiler::GuestAddress(guest_base), - profile, + let options = match profile { + Some(scalable) => Options::new( + BlockProfile::new(Features::LEAF | Features::CONTEXT), cpu_target, - )? - } else { - stela_compiler::compile_for_target( - source, - stela_compiler::GuestAddress(guest_base), - cpu_target, - )? + ) + .with_scalable(scalable), + None => Options::new(BlockProfile::new(Features::LEAF), cpu_target), }; + let plan = CompilationPlan::new(source, GuestAddress(guest_base), &options)?; + let memory_requirements = plan.memory_requirements(); + let block = plan.compile()?.native; let mut manifest = serde_json::json!({ "schema_version": 1, "kind": "raw_arm64_leaf_aot", @@ -354,16 +319,15 @@ impl CompileLeaf { "native_sha256": stela_runtime::sha256(&block.x86_64_code), "native_bytes": block.x86_64_code.len(), "source_map": block.source_map, - "abi": stela_compiler::NATIVE_ABI, + "abi": options.profile().abi(), "compiler_source_sha256": stela_compiler::SOURCE_SHA256, "verified": false, }); if let Some(profile) = profile { manifest["schema_version"] = serde_json::json!(2); - manifest["abi"] = serde_json::json!(stela_compiler::context::CONTEXT_LEAF_ABI); manifest["execution_profile"] = scalable_execution_manifest(profile, fpmr_enabled)?; manifest["entry_prefix_bytes"] = - serde_json::json!(stela_compiler::extended::CONTEXT_WRAPPER_BYTES); + serde_json::json!(stela_compiler::scalable_context::CONTEXT_WRAPPER_BYTES); let requirements = memory_requirements .context("context leaf requires compiler-derived memory metadata")?; use stela_compiler::context::memory::SpAlignmentRequirement; @@ -428,7 +392,9 @@ mod tests { mod scalable { use super::*; - fn resolve(extra: &[&str]) -> Result> { + fn resolve( + extra: &[&str], + ) -> Result> { let mut args = vec!["stela", "compile-leaf", "input.bin", "--output-dir", "out"]; args.extend_from_slice(extra); let Command::CompileLeaf(crate::compile::CompileLeaf { @@ -526,9 +492,7 @@ mod tests { use super::*; use stela_compiler::{aarch64::floating::features::NumericalFeatures, block::BlockProfile}; - fn resolve( - extra: &[&str], - ) -> Result> { + fn resolve(extra: &[&str]) -> Result> { let mut args = vec!["stela", "compile-block", "input.bin", "--output-dir", "out"]; args.extend_from_slice(extra); let Command::CompileBlock(crate::compile::CompileBlock { @@ -563,7 +527,7 @@ mod tests { compile_context_block_profile( scalable, if system_boundaries { - BlockProfile::SystemV1 + BlockProfile::new(Features::SYSTEM) } else { block_profile(software_pauth, software_clock, thread_registers) }, @@ -608,14 +572,10 @@ mod tests { } let mut args = guest.to_vec(); args.extend(numerical); - let profile = resolve(&args)?.unwrap(); - assert_eq!(profile.services(), BlockProfile::Ordinary); + let (scalable, numerical) = resolve(&args)?.unwrap(); + assert_eq!(numerical, NumericalFeatures::new(false, false, false)); assert_eq!( - profile.numerical_features(), - NumericalFeatures::new(false, false, false) - ); - assert_eq!( - scalable_execution_manifest(profile.scalable(), None)?, + scalable_execution_manifest(scalable, None)?, serde_json::json!({ "id":"sme-streaming-v2", "svl_bytes":32, "svcr":3, "features":["FEAT_SME"], "max_svl_bytes":256, "zt0_enabled":false, "dit":false @@ -748,15 +708,17 @@ mod tests { ); assert_eq!( block_profile(true, true, false), - stela_compiler::block::BlockProfile::AppleArm64eSoftwarePauthClockV1 + stela_compiler::block::BlockProfile::new( + Features::POINTER_AUTHENTICATION.union(Features::CLOCK) + ) ); assert_eq!( block_profile(true, false, false), - stela_compiler::block::BlockProfile::AppleArm64eSoftwarePauthV1 + stela_compiler::block::BlockProfile::new(Features::POINTER_AUTHENTICATION) ); assert_eq!( block_profile(false, false, false), - stela_compiler::block::BlockProfile::Ordinary + stela_compiler::block::BlockProfile::ORDINARY ); } @@ -806,15 +768,19 @@ mod tests { ); assert_eq!( block_profile(false, false, true), - BlockProfile::DarwinArm64ThreadV1 + BlockProfile::new(Features::THREAD_REGISTERS.union(Features::AMX)) ); assert_eq!( block_profile(true, false, true), - BlockProfile::AppleArm64eSoftwarePauthThreadV1 + BlockProfile::new( + Features::POINTER_AUTHENTICATION + .union(Features::THREAD_REGISTERS) + .union(Features::AMX) + ) ); assert_eq!( block_profile(true, true, true), - BlockProfile::AppleArm64eSoftwarePauthClockThreadV1 + BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)) ); } } @@ -822,7 +788,7 @@ mod tests { mod fpmr { use super::*; use std::hash::{Hash, Hasher}; - use stela_compiler::extended::ScalableProfile; + use stela_compiler::scalable_context::ScalableProfile; fn resolve( command: &str, @@ -989,7 +955,7 @@ mod tests { ); assert!( compile_scalable_profile( - Some(stela_compiler::extended::PROFILE_ID), + Some(stela_compiler::scalable_context::PROFILE_ID), Some( stela_compiler::aarch64::scalable::VectorLength::from_bytes(32) .unwrap() diff --git a/crates/stela-dev/src/compile/profile.rs b/crates/stela-dev/src/compile/profile.rs index 8982120f8b..b0ad2f2a08 100644 --- a/crates/stela-dev/src/compile/profile.rs +++ b/crates/stela-dev/src/compile/profile.rs @@ -1,5 +1,6 @@ //! Resolve declared guest execution profiles from command-line options. use anyhow::{Context, Result, ensure}; +use stela_compiler::block::Features; use stela_compiler::{ CompileError, block::CheckedMemoryProfile, @@ -47,12 +48,18 @@ pub(crate) fn block_profile( ) -> stela_compiler::block::BlockProfile { use stela_compiler::block::BlockProfile; match (software_pauth, software_clock, thread_registers) { - (_, true, true) => BlockProfile::AppleArm64eSoftwarePauthClockThreadV1, - (_, true, false) => BlockProfile::AppleArm64eSoftwarePauthClockV1, - (true, false, true) => BlockProfile::AppleArm64eSoftwarePauthThreadV1, - (true, false, false) => BlockProfile::AppleArm64eSoftwarePauthV1, - (false, false, true) => BlockProfile::DarwinArm64ThreadV1, - (false, false, false) => BlockProfile::Ordinary, + (_, true, true) => BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)), + (_, true, false) => { + BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)) + } + (true, false, true) => BlockProfile::new( + Features::POINTER_AUTHENTICATION + .union(Features::THREAD_REGISTERS) + .union(Features::AMX), + ), + (true, false, false) => BlockProfile::new(Features::POINTER_AUTHENTICATION), + (false, false, true) => BlockProfile::new(Features::THREAD_REGISTERS.union(Features::AMX)), + (false, false, false) => BlockProfile::ORDINARY, } } @@ -65,10 +72,10 @@ pub(crate) fn compile_scalable_profile( max_length: Option, zt0_enabled: Option, fpmr_enabled: Option, -) -> Result> { +) -> Result> { use stela_compiler::{ aarch64::scalable::{features::ScalableFeatures, profile::ScalableControls}, - extended::{DECLARED_PROFILE_ID, PROFILE_ID, ScalableProfile}, + scalable_context::{DECLARED_PROFILE_ID, PROFILE_ID, ScalableProfile}, }; let Some(id) = id else { ensure!( @@ -115,16 +122,18 @@ pub(crate) fn compile_scalable_profile( } pub(crate) fn compile_context_block_profile( - scalable: Option, + scalable: Option, services: stela_compiler::block::BlockProfile, full_a64: Option, ebf16: Option, rpres: Option, -) -> Result> { - use stela_compiler::{ - aarch64::floating::features::NumericalFeatures, block::BlockProfile, - extended::block::ExtendedBlockProfile, - }; +) -> Result< + Option<( + stela_compiler::scalable_context::ScalableProfile, + stela_compiler::aarch64::floating::features::NumericalFeatures, + )>, +> { + use stela_compiler::{aarch64::floating::features::NumericalFeatures, block::BlockProfile}; let Some(scalable) = scalable else { ensure!( full_a64.is_none() && ebf16.is_none() && rpres.is_none(), @@ -133,7 +142,7 @@ pub(crate) fn compile_context_block_profile( return Ok(None); }; ensure!( - services == BlockProfile::Ordinary, + services == BlockProfile::ORDINARY, "context block services are not integrated" ); let numerical = NumericalFeatures::new( @@ -141,13 +150,11 @@ pub(crate) fn compile_context_block_profile( ebf16.context("context block requires explicit extended BF16 availability")?, rpres.context("context block requires explicit reciprocal precision availability")?, ); - Ok(Some(ExtendedBlockProfile::new( - scalable, services, numerical, - ))) + Ok(Some((scalable, numerical))) } pub(crate) fn scalable_execution_manifest( - profile: stela_compiler::extended::ScalableProfile, + profile: stela_compiler::scalable_context::ScalableProfile, fpmr_enabled: Option, ) -> Result { let mut execution = serde_json::json!({ diff --git a/crates/stela-dev/src/dyld_entry.rs b/crates/stela-dev/src/dyld_entry.rs index 92b6de81fd..2e1be6bc93 100644 --- a/crates/stela-dev/src/dyld_entry.rs +++ b/crates/stela-dev/src/dyld_entry.rs @@ -3,6 +3,7 @@ //! mapped and owned together. use anyhow::{Context, Result, ensure}; use std::path::{Path, PathBuf}; +use stela_compiler::block::Features; use stela_compiler::{GuestAddress, GuestState}; use stela_loader::{load_plan, mapped_image}; use stela_runtime::{ @@ -314,9 +315,11 @@ pub fn probe( 0x534f524544594c44, options.cache_dir, if options.bootstrap_clock { - stela_compiler::block::BlockProfile::AppleArm64eSoftwarePauthClockV1 + stela_compiler::block::BlockProfile::new( + Features::POINTER_AUTHENTICATION.union(Features::CLOCK), + ) } else if context.is_some() { - stela_compiler::block::BlockProfile::CheckedMemoryPauthClockThread( + stela_compiler::block::BlockProfile::new(Features::PROCESS_HELPERS).with_checked_memory( stela_compiler::block::CheckedMemoryProfile::SpAlignmentDisabled, ) } else { diff --git a/crates/stela-fingerprint/Cargo.toml b/crates/stela-fingerprint/Cargo.toml new file mode 100644 index 0000000000..14c5e42327 --- /dev/null +++ b/crates/stela-fingerprint/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "stela-fingerprint" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +sha2.workspace = true diff --git a/crates/stela-fingerprint/src/lib.rs b/crates/stela-fingerprint/src/lib.rs new file mode 100644 index 0000000000..f563c82ee6 --- /dev/null +++ b/crates/stela-fingerprint/src/lib.rs @@ -0,0 +1,147 @@ +//! Source fingerprints for build scripts. +//! +//! A fingerprint is the SHA-256 of every file under a crate's inputs, keyed +//! by its `/`-separated path relative to the crate root and hashed with +//! CRLF line endings folded to LF. Checkouts of one commit on Windows +//! (`core.autocrlf`), Linux and macOS therefore produce the same digest, so +//! translation caches keyed by it move between hosts. Hidden entries (names +//! starting with `.`, such as `.DS_Store` or editor swap files) are skipped. +use sha2::{Digest, Sha256}; +use std::{fs, path::Path}; + +/// Prints `cargo:rerun-if-changed` for each input of the crate whose build +/// script is running and sets the environment variable `variable` to the +/// inputs' fingerprint for the crate's compilation. +pub fn emit(variable: &str, inputs: &[&str]) { + for input in inputs { + println!("cargo:rerun-if-changed={input}"); + } + let root = std::env::var_os("CARGO_MANIFEST_DIR").expect("build script environment"); + println!( + "cargo:rustc-env={variable}={}", + source_sha256(Path::new(&root), inputs) + ); +} + +/// The lowercase hex SHA-256 of the files under `inputs`, each a file or +/// directory relative to `root`. +pub fn source_sha256(root: &Path, inputs: &[&str]) -> String { + let mut files = Vec::new(); + for input in inputs { + collect( + root, + &mut input.split('/').map(str::to_owned).collect(), + &mut files, + ); + } + files.sort(); + files.dedup(); + let mut hasher = Sha256::new(); + for file in files { + let content = normalize(&fs::read(root.join(&file)).expect("readable source file")); + hasher.update(file.as_bytes()); + hasher.update([0]); + hasher.update((content.len() as u64).to_le_bytes()); + hasher.update(&content); + } + hasher + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +/// Adds the `/`-joined relative paths of the files at `components` to `files`. +fn collect(root: &Path, components: &mut Vec, files: &mut Vec) { + let path = components + .iter() + .fold(root.to_owned(), |path, part| path.join(part)); + if path.is_dir() { + for entry in fs::read_dir(&path).expect("readable source directory") { + let name = entry.expect("source entry").file_name(); + let name = name.into_string().expect("UTF-8 source file name"); + if name.starts_with('.') { + continue; + } + components.push(name); + collect(root, components, files); + components.pop(); + } + } else { + files.push(components.join("/")); + } +} + +/// `bytes` with each CRLF pair replaced by LF. +fn normalize(bytes: &[u8]) -> Vec { + let mut out = Vec::with_capacity(bytes.len()); + for (index, &byte) in bytes.iter().enumerate() { + if byte == b'\r' && bytes.get(index + 1) == Some(&b'\n') { + continue; + } + out.push(byte); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tree(name: &str, files: &[(&str, &[u8])]) -> std::path::PathBuf { + let root = + std::env::temp_dir().join(format!("stela-fingerprint-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + for (path, content) in files { + let path = root.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } + root + } + + #[test] + fn crlf_and_lf_checkouts_match() { + let lf = tree( + "lf", + &[("src/a.rs", b"fn a() {}\n"), ("src/b/c.rs", b"x\n")], + ); + let crlf = tree( + "crlf", + &[("src/a.rs", b"fn a() {}\r\n"), ("src/b/c.rs", b"x\r\n")], + ); + assert_eq!(source_sha256(&lf, &["src"]), source_sha256(&crlf, &["src"])); + fs::remove_dir_all(lf).unwrap(); + fs::remove_dir_all(crlf).unwrap(); + } + + #[test] + fn hidden_entries_are_skipped() { + let plain = tree("plain", &[("src/a.rs", b"a")]); + let hidden = tree("hidden", &[("src/a.rs", b"a"), ("src/.DS_Store", b"\0")]); + assert_eq!( + source_sha256(&plain, &["src"]), + source_sha256(&hidden, &["src"]) + ); + fs::remove_dir_all(plain).unwrap(); + fs::remove_dir_all(hidden).unwrap(); + } + + #[test] + fn content_and_path_changes_change_the_digest() { + let base = tree("base", &[("src/a.rs", b"a")]); + let edited = tree("edited", &[("src/a.rs", b"b")]); + let moved = tree("moved", &[("src/b.rs", b"a")]); + let digest = source_sha256(&base, &["src"]); + assert_ne!(digest, source_sha256(&edited, &["src"])); + assert_ne!(digest, source_sha256(&moved, &["src"])); + for root in [base, edited, moved] { + fs::remove_dir_all(root).unwrap(); + } + } + + #[test] + fn lone_carriage_returns_are_kept() { + assert_eq!(normalize(b"a\r\nb\rc\r"), b"a\nb\rc\r"); + } +} diff --git a/crates/stela-runtime/Cargo.toml b/crates/stela-runtime/Cargo.toml index b5eedc0d97..984921dd84 100644 --- a/crates/stela-runtime/Cargo.toml +++ b/crates/stela-runtime/Cargo.toml @@ -42,7 +42,7 @@ smoltcp = { version = "0.14", default-features = false, features = ["alloc", "me httparse = { version = "1.10", default-features = false } [build-dependencies] -sha2.workspace = true +stela-fingerprint.workspace = true [dev-dependencies] # The drivers' RAM disk, which the device model tests run on. diff --git a/crates/stela-runtime/build.rs b/crates/stela-runtime/build.rs index c2a6f025fa..b8f3651c49 100644 --- a/crates/stela-runtime/build.rs +++ b/crates/stela-runtime/build.rs @@ -1,34 +1,13 @@ -//! Fingerprint the engine's compile-driver sources: with the compiler's own -//! fingerprint they make the persistent translation store's translator id +//! Fingerprint the runtime sources: with the compiler's own fingerprint they +//! make the persistent translation store's translator id //! (`translations::translator_id`). -use sha2::{Digest, Sha256}; -use std::{ - fs, - path::{Path, PathBuf}, -}; - -/// What decides the input the engine gives the compiler for a block: the -/// dispatch loop's fetch and compile, the chip's admission and checks, and -/// the store format itself. -const INPUTS: &[&str] = &[ - "src/machine/engine.rs", - "src/machine/engine", - "src/machine/chip.rs", - "src/machine/chip", - "src/machine/identification.rs", - "src/translations.rs", -]; - -fn collect(path: &Path, files: &mut Vec) { - if path.is_dir() { - for entry in fs::read_dir(path).expect("readable source directory") { - collect(&entry.expect("source entry").path(), files); - } - } else { - files.push(path.to_owned()); - } -} - +//! +//! The whole crate is fingerprinted. What the engine gives the compiler for a +//! block depends on the dispatch loop, guest memory layout, block +//! translation, PAuth services, the CPU model and the store format, which +//! span most of the crate; a hand-maintained file list or ABI version +//! constant goes stale silently when one of them changes, while a whole-crate +//! digest at worst discards translations that were still valid. fn main() { // `host_memory`: guest memory on the host's POSIX mappings, which hosted // execution runs on. A std build elsewhere (Windows, for setup) has none @@ -39,22 +18,8 @@ fn main() { { println!("cargo::rustc-cfg=host_memory"); } - let mut files = Vec::new(); - for input in INPUTS { - println!("cargo:rerun-if-changed={input}"); - collect(Path::new(input), &mut files); - } - files.sort(); - let mut hasher = Sha256::new(); - for file in files { - hasher.update(file.to_string_lossy().as_bytes()); - hasher.update([0]); - hasher.update(fs::read(&file).expect("readable source file")); - } - let digest: String = hasher - .finalize() - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(); - println!("cargo:rustc-env=STELA_ENGINE_SOURCE_SHA256={digest}"); + stela_fingerprint::emit( + "STELA_ENGINE_SOURCE_SHA256", + &["Cargo.toml", "build.rs", "src"], + ); } diff --git a/crates/stela-runtime/src/artifact/prepare.rs b/crates/stela-runtime/src/artifact/prepare.rs index d1df71832d..ccc031ae9a 100644 --- a/crates/stela-runtime/src/artifact/prepare.rs +++ b/crates/stela-runtime/src/artifact/prepare.rs @@ -108,14 +108,20 @@ mod tests { .flat_map(u32::to_le_bytes) .collect(); let base = GuestAddress(0x1000); - let plan = - CompilationPlan::new(&source, base, BlockProfile::Ordinary, TargetCpu::Baseline)?; + let plan = CompilationPlan::new( + &source, + base, + &stela_compiler::Options::new(BlockProfile::ORDINARY, TargetCpu::Baseline), + )?; let identity = crate::block_plan_identity(&source, base, TargetCpu::Baseline, &plan)?; let requirements = plan.memory_requirements(); - let original = - CompilationPlan::new(&source, base, BlockProfile::Ordinary, TargetCpu::Baseline)? - .compile()? - .native; + let original = CompilationPlan::new( + &source, + base, + &stela_compiler::Options::new(BlockProfile::ORDINARY, TargetCpu::Baseline), + )? + .compile()? + .native; let calls = core::cell::Cell::new(0); let (manifest, native) = generate(identity.clone(), requirements, || { calls.set(calls.get() + 1); diff --git a/crates/stela-runtime/src/blocks.rs b/crates/stela-runtime/src/blocks.rs index 4ca70942a4..de8e3222e5 100644 --- a/crates/stela-runtime/src/blocks.rs +++ b/crates/stela-runtime/src/blocks.rs @@ -39,8 +39,8 @@ use std::{io::Read, path::PathBuf}; use stela_compiler::{ GuestAddress, block::{ - BlockExit, BlockProfile, ExitKind, MAX_BLOCK_INSTRUCTIONS, PointerAuthenticationOperation, - analyze_with_profile, + BlockExit, BlockProfile, ExitKind, Features, MAX_BLOCK_INSTRUCTIONS, + PointerAuthenticationOperation, analyze_with_profile, }, }; use validate::{ @@ -94,7 +94,7 @@ pub struct BlockRuntime { impl BlockRuntime { #[cfg(feature = "std")] pub fn new(address_space: u64, cache_root: PathBuf) -> Self { - Self::new_with_profile(address_space, cache_root, BlockProfile::Ordinary) + Self::new_with_profile(address_space, cache_root, BlockProfile::ORDINARY) } /// Explicit helper profile is part of every persistent translation identity. @@ -317,7 +317,7 @@ impl BlockRuntime { context: &pauth::Context, ) -> Result { ensure!( - self.profile.supports_pointer_authentication(), + self.profile.has(Features::POINTER_AUTHENTICATION), "PAuth execution requires the explicit software PAuth block profile" ); ensure!( @@ -354,7 +354,7 @@ impl BlockRuntime { controls: pauth::memory::Controls, ) -> Result { ensure!( - self.profile.supports_pointer_authentication(), + self.profile.has(Features::POINTER_AUTHENTICATION), "PAuth execution requires the explicit software PAuth block profile" ); ensure!( @@ -396,7 +396,7 @@ impl BlockRuntime { clock: &mut clock::Context, ) -> Result { ensure!( - self.profile.supports_clock(), + self.profile.has(Features::CLOCK), "clock execution requires the explicit software clock block profile" ); ensure!( @@ -432,7 +432,7 @@ impl BlockRuntime { clock: Option<&mut clock::Context>, ) -> Result { ensure!( - self.profile.supports_thread_registers(), + self.profile.has(Features::THREAD_REGISTERS), "thread-register execution requires the explicit thread block profile" ); ensure!( @@ -441,7 +441,7 @@ impl BlockRuntime { ); if let Some(pauth) = pauth { ensure!( - self.profile.supports_pointer_authentication(), + self.profile.has(Features::POINTER_AUTHENTICATION), "PAuth execution requires the explicit software PAuth block profile" ); ensure!( @@ -451,7 +451,7 @@ impl BlockRuntime { } if let Some(clock) = clock.as_ref() { ensure!( - self.profile.supports_clock() && pauth.is_some(), + self.profile.has(Features::CLOCK) && pauth.is_some(), "clock execution requires the explicit software clock profile and PAC context" ); ensure!( @@ -484,7 +484,7 @@ impl BlockRuntime { dispatcher: &mut dyn system::execution::Dispatcher, ) -> Result { ensure!( - self.profile.supports_system(), + self.profile.has(Features::SYSTEM), "System execution requires the explicit System block profile" ); ensure!( @@ -536,14 +536,14 @@ impl BlockRuntime { loop { let pc = state.pc; // A zero budget requests no instruction fetch or execution. - if self.profile.supports_pointer_authentication() && block_budget == 0 { + if self.profile.has(Features::POINTER_AUTHENTICATION) && block_budget == 0 { break; } // Instruction TBI is disabled in the fixed VA47 software profile. // This also prevents a resumed poisoned RETAB target from becoming // executable through a registered snapshot or matching stop sentinel. let extension = pc.0 >> 47; - if self.profile.supports_pointer_authentication() + if self.profile.has(Features::POINTER_AUTHENTICATION) && extension != 0 && extension != u64::MAX >> 47 { @@ -571,7 +571,7 @@ impl BlockRuntime { } // Current PSTATE and CPU controls take precedence over decoding an // available word. This guard performs no architectural effect. - let system_entry = if self.profile.supports_system() + let system_entry = if self.profile.has(Features::SYSTEM) || self.profile.checked_memory().is_some() { let Some(dispatcher) = system_dispatcher.as_deref_mut() else { @@ -629,7 +629,7 @@ impl BlockRuntime { "refusing stale block execution" ); let mut completed_blocks = 1; - let native_exit = if block.profile.supports_resident_loops() { + let native_exit = if block.profile.has(Features::RESIDENT_LOOPS) { let available = block_budget - outcome.blocks_executed; let mut budget = stela_compiler::block::loop_budget::LoopBudget::new(available); // SAFETY: the distinct immutable profile/ABI binds this source @@ -667,7 +667,7 @@ impl BlockRuntime { }; let pointer_authentication = if exit_kind == ExitKind::PointerAuthentication { ensure!( - self.profile.supports_pointer_authentication(), + self.profile.has(Features::POINTER_AUTHENTICATION), "ordinary block produced an unrequested PAuth helper exit" ); Some(validate_pauth_exit( @@ -682,7 +682,7 @@ impl BlockRuntime { }; let clock_instruction = if exit_kind == ExitKind::Clock { ensure!( - self.profile.supports_clock(), + self.profile.has(Features::CLOCK), "block produced an unrequested clock helper exit" ); Some(validate_clock_exit( @@ -697,7 +697,7 @@ impl BlockRuntime { }; let thread_register_instruction = if exit_kind == ExitKind::ThreadRegister { ensure!( - self.profile.supports_thread_registers(), + self.profile.has(Features::THREAD_REGISTERS), "block produced an unrequested thread-register helper exit" ); Some(validate_thread_register_exit( @@ -712,7 +712,7 @@ impl BlockRuntime { }; let amx_instruction = if exit_kind == ExitKind::Amx { ensure!( - self.profile.supports_amx(), + self.profile.has(Features::AMX), "block produced an unrequested AMX exit" ); Some(validate_amx_exit( @@ -727,7 +727,7 @@ impl BlockRuntime { }; let system_boundary = if exit_kind == ExitKind::System { ensure!( - self.profile.supports_system(), + self.profile.has(Features::SYSTEM), "block produced an unrequested System helper exit" ); let instruction = validate_system_exit( @@ -1025,7 +1025,7 @@ mod tests { let mut vm = BlockRuntime::new_with_profile( 9, cache.into(), - BlockProfile::AppleArm64eSoftwarePauthV1, + BlockProfile::new(Features::POINTER_AUTHENTICATION), ); vm.register_code( BASE, @@ -1365,7 +1365,8 @@ mod tests { const BASE: GuestAddress = GuestAddress(0x1000); const STOP: GuestAddress = GuestAddress(0x1400); - const PROFILE: BlockProfile = BlockProfile::AppleArm64eSoftwarePauthClockV1; + const PROFILE: BlockProfile = + BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)); fn runtime(path: &std::path::Path, words: &[u32]) -> Result { let mut runtime = BlockRuntime::new_with_profile(1, path.to_path_buf(), PROFILE); @@ -1691,7 +1692,7 @@ mod tests { let mut runtime = BlockRuntime::new_with_profile( 1, path.to_path_buf(), - BlockProfile::OrdinaryResidentV1, + BlockProfile::new(Features::RESIDENT_LOOPS), ); runtime.register_code( BASE, @@ -1765,7 +1766,7 @@ mod tests { assert_eq!(outcome.reason, StopReason::StopAddress); assert_eq!( runtime.loaded_manifest(BASE).unwrap().identity.abi, - stela_compiler::block::loop_budget::RESIDENT_BLOCK_ABI + BlockProfile::new(Features::RESIDENT_LOOPS).abi() ); Ok(()) } @@ -1817,7 +1818,7 @@ mod tests { let mut runtime = BlockRuntime::new_for_target( 1, path.to_path_buf(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, stela_compiler::TargetCpu::Baseline, ); runtime.register_code( @@ -1867,11 +1868,11 @@ mod tests { assert_eq!(outcome.memory_cache_hits, if loaded { 2 } else { 0 }); assert_eq!( runtime.loaded_manifest(BASE).unwrap().identity.abi, - BlockProfile::OrdinaryResidentV1.abi() + BlockProfile::new(Features::RESIDENT_LOOPS).abi() ); assert_eq!( runtime.loaded_manifest(return_pc).unwrap().identity.abi, - BlockProfile::Ordinary.abi() + BlockProfile::ORDINARY.abi() ); } let mut disk_runtime = ordinary(cache.path(), &words)?; @@ -1896,7 +1897,7 @@ mod tests { assert_eq!(state.registers.x[0], 3); assert_eq!( runtime.loaded_manifest(BASE).unwrap().identity.abi, - BlockProfile::OrdinaryResidentV1.abi() + BlockProfile::new(Features::RESIDENT_LOOPS).abi() ); runtime.register_code( BASE, @@ -1915,7 +1916,7 @@ mod tests { assert_eq!(state.registers, expected); assert_eq!( runtime.loaded_manifest(BASE).unwrap().identity.abi, - BlockProfile::Ordinary.abi() + BlockProfile::ORDINARY.abi() ); runtime.register_code( BASE, @@ -1938,7 +1939,7 @@ mod tests { assert_eq!(outcome.reason, StopReason::StopAddress); assert_eq!( runtime.loaded_manifest(BASE).unwrap().identity.abi, - BlockProfile::OrdinaryResidentV1.abi() + BlockProfile::new(Features::RESIDENT_LOOPS).abi() ); Ok(()) } @@ -1970,7 +1971,7 @@ mod tests { assert_eq!(outcome.blocks_executed, 1); assert_eq!( runtime.loaded_manifest(BASE).unwrap().identity.abi, - BlockProfile::OrdinaryResidentV1.abi() + BlockProfile::new(Features::RESIDENT_LOOPS).abi() ); Ok(()) } @@ -2019,7 +2020,7 @@ mod tests { assert_eq!(outcome.reason, StopReason::BudgetExhausted); assert_eq!( runtime.loaded_manifest(BASE).unwrap().identity.abi, - BlockProfile::OrdinaryResidentV1.abi() + BlockProfile::new(Features::RESIDENT_LOOPS).abi() ); Ok(()) } @@ -2074,7 +2075,7 @@ mod tests { let mut runtime = BlockRuntime::new_with_profile( ADDRESS_SPACE, cache.path().into(), - BlockProfile::SystemV1, + BlockProfile::new(Features::SYSTEM), ); let mut state = ThreadState { registers: GuestState::default(), @@ -2114,7 +2115,7 @@ mod tests { let mut runtime = BlockRuntime::new_with_profile( ADDRESS_SPACE, cache.path().into(), - BlockProfile::SystemV1, + BlockProfile::new(Features::SYSTEM), ); runtime.register_code( BASE, diff --git a/crates/stela-runtime/src/blocks/aot.rs b/crates/stela-runtime/src/blocks/aot.rs index 0c1222a732..2db8d5bb57 100644 --- a/crates/stela-runtime/src/blocks/aot.rs +++ b/crates/stela-runtime/src/blocks/aot.rs @@ -137,8 +137,12 @@ impl BlockRuntime { let generation = region.generation; let window = ®ion.source[offset..offset + available]; let analysis = analyze_with_profile(window, pc, self.profile)?; - let plan = - CompilationPlan::new(window, pc, self.profile, self.target)?.with_resident_loops(); + let plan = CompilationPlan::new( + window, + pc, + &stela_compiler::Options::new(self.profile, self.target), + )? + .with_resident_loops(); let profile = plan.profile(); let source_bytes = plan.source_bytes(); ensure!( @@ -212,8 +216,12 @@ mod tests { } fn artifact(source: &[u8], profile: BlockProfile) -> Result<(crate::Manifest, Vec)> { - let plan = - CompilationPlan::new(source, BASE, profile, TargetCpu::Baseline)?.with_resident_loops(); + let plan = CompilationPlan::new( + source, + BASE, + &stela_compiler::Options::new(profile, TargetCpu::Baseline), + )? + .with_resident_loops(); let identity = crate::block_plan_identity(source, BASE, TargetCpu::Baseline, &plan)?; let memory_requirements = plan.memory_requirements(); let native = plan.compile()?.native; @@ -261,9 +269,9 @@ mod tests { #[test] fn standard_artifact_enters_original_loaded_hit_path_without_disk_or_execution() -> Result<()> { let source = source(&[MOVZ_X0_42, B_NEXT]); - let (manifest, native) = artifact(&source, BlockProfile::Ordinary)?; + let (manifest, native) = artifact(&source, BlockProfile::ORDINARY)?; let (bytes, checksum) = serialized(&manifest)?; - let mut runtime = runtime(&source, BlockProfile::Ordinary)?; + let mut runtime = runtime(&source, BlockProfile::ORDINARY)?; runtime.preload_artifact(BASE, &bytes, &checksum, &native)?; assert_eq!( runtime.loaded_manifest(BASE).unwrap().identity, @@ -289,7 +297,7 @@ mod tests { // Unsupported instruction distinguishes availability refusal from invoking // the absent runtime miss compiler. Registered bytes remain unchanged. let source = [0; size_of::()]; - let mut runtime = runtime(&source, BlockProfile::Ordinary)?; + let mut runtime = runtime(&source, BlockProfile::ORDINARY)?; let error = runtime.prepare(BASE).unwrap_err(); assert_eq!( error.to_string(), @@ -308,7 +316,7 @@ mod tests { fn stale_source_native_map_and_verification_claim_cannot_publish_loaded_blocks() -> Result<()> { let source = source(&[MOVZ_X0_42, B_NEXT]); for change in 0..4 { - let (mut manifest, native) = artifact(&source, BlockProfile::Ordinary)?; + let (mut manifest, native) = artifact(&source, BlockProfile::ORDINARY)?; match change { 0 => manifest.identity.source_sha256.push('0'), 1 => manifest.native_sha256.push('0'), @@ -317,7 +325,7 @@ mod tests { _ => unreachable!(), } let (bytes, checksum) = serialized(&manifest)?; - let mut runtime = runtime(&source, BlockProfile::Ordinary)?; + let mut runtime = runtime(&source, BlockProfile::ORDINARY)?; assert!( runtime .preload_artifact(BASE, &bytes, &checksum, &native) @@ -335,7 +343,7 @@ mod tests { let checks = EffectiveAddressChecks::new(AddressAddChecks::Disabled, AddressAddChecks::Enabled); let profile = |normal, unprivileged| { - BlockProfile::CheckedMemory( + BlockProfile::ORDINARY.with_checked_memory( CheckedMemoryProfile::SpAlignmentDisabled.with_address_checks( normal, unprivileged, @@ -371,9 +379,9 @@ mod tests { #[test] fn replacing_registered_source_retires_preloaded_native_generation() -> Result<()> { let source = source(&[MOVZ_X0_42, B_NEXT]); - let (manifest, native) = artifact(&source, BlockProfile::Ordinary)?; + let (manifest, native) = artifact(&source, BlockProfile::ORDINARY)?; let (bytes, checksum) = serialized(&manifest)?; - let mut runtime = runtime(&source, BlockProfile::Ordinary)?; + let mut runtime = runtime(&source, BlockProfile::ORDINARY)?; runtime.preload_artifact(BASE, &bytes, &checksum, &native)?; assert!(runtime.unregister_code(BASE)); assert!(runtime.loaded.is_empty()); diff --git a/crates/stela-runtime/src/blocks/discovery.rs b/crates/stela-runtime/src/blocks/discovery.rs index c26191936b..dd8b246cda 100644 --- a/crates/stela-runtime/src/blocks/discovery.rs +++ b/crates/stela-runtime/src/blocks/discovery.rs @@ -140,9 +140,12 @@ impl BlockRuntime { let generation = region.generation; let window = ®ion.source[offset..offset + available]; let analysis = analyze_with_profile(window, pc, self.profile)?; - let plan = - stela_compiler::block::CompilationPlan::new(window, pc, self.profile, self.target)? - .with_resident_loops(); + let plan = stela_compiler::block::CompilationPlan::new( + window, + pc, + &stela_compiler::Options::new(self.profile, self.target), + )? + .with_resident_loops(); let artifact_profile = plan.profile(); let source_bytes = plan.source_bytes(); ensure!( diff --git a/crates/stela-runtime/src/blocks/retirement/checked/source.rs b/crates/stela-runtime/src/blocks/retirement/checked/source.rs index 08855ee53a..6f54c57aa9 100644 --- a/crates/stela-runtime/src/blocks/retirement/checked/source.rs +++ b/crates/stela-runtime/src/blocks/retirement/checked/source.rs @@ -11,7 +11,7 @@ use stela_compiler::{ aarch64::{Decoder, Operation}, block::{ BlockAnalysis, BlockExit, BlockProfile, ClockInstruction, CompilationPlan, DynamicEdgeKind, - ExitKind, PointerAuthentication, SynchronousTrap, ThreadRegisterInstruction, + ExitKind, Features, PointerAuthentication, SynchronousTrap, ThreadRegisterInstruction, analyze_with_profile, }, context::memory::{MemoryRequirements, MemoryStatus}, @@ -203,17 +203,22 @@ impl<'code> BoundSource<'code> { ); validate_source_map(&block.prepared.manifest, pc, block.source_bytes)?; // Re-parse without emitting, and compare that plan with the loaded one. - let plan = CompilationPlan::new(source, pc, runtime.profile, runtime.target_cpu())?; + let plan = CompilationPlan::new( + source, + pc, + &stela_compiler::Options::new(runtime.profile, runtime.target_cpu()), + )?; let requirements = plan.memory_requirements(); - match runtime.profile { - BlockProfile::SystemV1 => anyhow::ensure!( + if runtime.profile == BlockProfile::new(Features::SYSTEM) { + anyhow::ensure!( requirements.is_none() && source.len() == size_of::(), - "SystemV1 requires one original no-context source word" - ), - _ => anyhow::ensure!( + "a System block requires one original no-context source word" + ); + } else { + anyhow::ensure!( runtime.profile.checked_memory().is_some() && requirements.is_some(), "checked plan requirements absent" - ), + ); } anyhow::ensure!( plan.source_bytes() == block.source_bytes @@ -502,7 +507,8 @@ mod tests { #[test] fn checked_memory_bound_source_keeps_plan_requirements() { let cache = tempfile::tempdir().unwrap(); - let profile = BlockProfile::CheckedMemory(CheckedMemoryProfile::SpAlignmentEnabled); + let profile = + BlockProfile::ORDINARY.with_checked_memory(CheckedMemoryProfile::SpAlignmentEnabled); let mut runtime = runtime(cache.path(), profile); let mut accounting = super::super::empty_accounting(); runtime.load(BASE, &mut accounting).unwrap(); diff --git a/crates/stela-runtime/src/blocks/retirement/checked/source/conditional.rs b/crates/stela-runtime/src/blocks/retirement/checked/source/conditional.rs index 229b812f13..49afc5c756 100644 --- a/crates/stela-runtime/src/blocks/retirement/checked/source/conditional.rs +++ b/crates/stela-runtime/src/blocks/retirement/checked/source/conditional.rs @@ -132,7 +132,7 @@ mod tests { fn check(word: u32, registers: &GuestState, taken: bool) { let source = word.to_le_bytes(); - let analysis = analyze_with_profile(&source, BASE, BlockProfile::Ordinary).unwrap(); + let analysis = analyze_with_profile(&source, BASE, BlockProfile::ORDINARY).unwrap(); let target = if taken { GuestAddress(0x1008) } else { @@ -212,7 +212,7 @@ mod tests { // applies only to the taken branch, so target equality is insufficient. const BRANCH_EQUAL_NEXT: u32 = 0x5400_0020; let source = BRANCH_EQUAL_NEXT.to_le_bytes(); - let analysis = analyze_with_profile(&source, BASE, BlockProfile::Ordinary).unwrap(); + let analysis = analyze_with_profile(&source, BASE, BlockProfile::ORDINARY).unwrap(); for (nzcv, kind, wrong) in [ (NZCV_Z, ExitKind::Direct, ExitKind::Fallthrough), (0, ExitKind::Fallthrough, ExitKind::Direct), @@ -243,7 +243,7 @@ mod tests { ] { // NOP; B +8; BL +8; BR X3; BLR X3; RET X30 let source = word.to_le_bytes(); - let analysis = analyze_with_profile(&source, BASE, BlockProfile::Ordinary).unwrap(); + let analysis = analyze_with_profile(&source, BASE, BlockProfile::ORDINARY).unwrap(); assert!( validate( &analysis, diff --git a/crates/stela-runtime/src/blocks/scalable.rs b/crates/stela-runtime/src/blocks/scalable.rs index 7d43161b01..4743cee8e1 100644 --- a/crates/stela-runtime/src/blocks/scalable.rs +++ b/crates/stela-runtime/src/blocks/scalable.rs @@ -8,7 +8,7 @@ use stela_compiler::{ AdmittedScalableNumericalInstruction, admit_scalable_numerical_instruction, decode_scalable_numerical_instruction, }, - extended::ScalableProfile, + scalable_context::ScalableProfile, }; use super::validate_interior_word; diff --git a/crates/stela-runtime/src/blocks/validate.rs b/crates/stela-runtime/src/blocks/validate.rs index 2dee1670f5..f42e3fe30c 100644 --- a/crates/stela-runtime/src/blocks/validate.rs +++ b/crates/stela-runtime/src/blocks/validate.rs @@ -50,7 +50,9 @@ pub(super) fn validate_numerical_exit( let word = validate_interior_word(entry, exit, source_bytes, region_base, source)?; let operand = stela_compiler::aarch64::FloatingPointOperation::decode(word) .context("numerical exit does not identify arithmetic")? - .map_err(|()| anyhow::anyhow!("numerical exit identifies reserved arithmetic"))?; + .map_err(|stela_compiler::aarch64::Unsupported| { + anyhow::anyhow!("numerical exit identifies reserved arithmetic") + })?; let next = GuestAddress( exit.0 .checked_add(INSTRUCTION_BYTES as u64) @@ -197,7 +199,7 @@ pub(super) fn validate_source_map( source_bytes: usize, ) -> Result<()> { let first_native_offset = if manifest.memory_requirements.is_some() { - stela_compiler::extended::CONTEXT_WRAPPER_BYTES + stela_compiler::scalable_context::CONTEXT_WRAPPER_BYTES } else { 0 }; diff --git a/crates/stela-runtime/src/darwin.rs b/crates/stela-runtime/src/darwin.rs index a2c2111a27..b2bfb3e3b3 100644 --- a/crates/stela-runtime/src/darwin.rs +++ b/crates/stela-runtime/src/darwin.rs @@ -575,11 +575,11 @@ pub unsafe fn run_services( "refusing execution in an unusable guest address space" ); let mut part = unsafe { - if let Some(thread) = services - .thread - .as_deref() - .filter(|_| runtime.profile().supports_thread_registers()) - { + if let Some(thread) = services.thread.as_deref().filter(|_| { + runtime + .profile() + .has(stela_compiler::block::Features::THREAD_REGISTERS) + }) { runtime.run_with_thread( state, stop, diff --git a/crates/stela-runtime/src/darwin/csr.rs b/crates/stela-runtime/src/darwin/csr.rs index 35260742d5..823faadbf2 100644 --- a/crates/stela-runtime/src/darwin/csr.rs +++ b/crates/stela-runtime/src/darwin/csr.rs @@ -511,7 +511,7 @@ mod tests { let mut runtime = BlockRuntime::new_for_target( ADDRESS_SPACE, cache.path().to_owned(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, TargetCpu::Baseline, ); runtime.register_code( diff --git a/crates/stela-runtime/src/darwin/entropy.rs b/crates/stela-runtime/src/darwin/entropy.rs index 659dcfe710..0f1e5bc52f 100644 --- a/crates/stela-runtime/src/darwin/entropy.rs +++ b/crates/stela-runtime/src/darwin/entropy.rs @@ -495,7 +495,7 @@ mod tests { let mut runtime = BlockRuntime::new_for_target( ADDRESS_SPACE, cache.path().to_owned(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, TargetCpu::Baseline, ); runtime.register_code( diff --git a/crates/stela-runtime/src/execution.rs b/crates/stela-runtime/src/execution.rs index 4b02933ef3..bff8a73e45 100644 --- a/crates/stela-runtime/src/execution.rs +++ b/crates/stela-runtime/src/execution.rs @@ -25,7 +25,7 @@ use core::marker::PhantomData; #[cfg(feature = "std")] use std::io::Read; #[cfg(feature = "std")] -use stela_compiler::{GuestState, NATIVE_ABI}; +use stela_compiler::GuestState; // Bounds a cached artifact so it cannot force an unbounded allocation or // mapping. @@ -67,7 +67,12 @@ impl ExecutableLeaf { identity.compiler_source_sha256 == crate::compiler_source_sha256(), "generated code uses a different compiler" ); - ensure!(identity.abi == NATIVE_ABI, "unsupported generated-code ABI"); + ensure!( + identity.abi + == stela_compiler::block::BlockProfile::new(stela_compiler::block::Features::LEAF) + .abi(), + "unsupported generated-code ABI" + ); let target = identity .target_cpu .parse::() diff --git a/crates/stela-runtime/src/execution/checked_memory.rs b/crates/stela-runtime/src/execution/checked_memory.rs index 01bab2b177..6370dff045 100644 --- a/crates/stela-runtime/src/execution/checked_memory.rs +++ b/crates/stela-runtime/src/execution/checked_memory.rs @@ -38,7 +38,7 @@ pub struct Identity { pub native_bytes: usize, pub compiler_source_sha256: &'static str, pub target: TargetCpu, - pub abi: &'static str, + pub abi: String, /// Distinguishes this all-writer checked contract from direct-RAM profiles. pub memory_model: &'static str, } @@ -125,8 +125,14 @@ impl CheckedMemoryBlock { entry.0.checked_add(source.len() as u64).is_some(), "source address overflow" ); - let plan = - CompilationPlan::new(&source, entry, BlockProfile::CheckedMemory(profile), target)?; + let plan = CompilationPlan::new( + &source, + entry, + &stela_compiler::Options::new( + BlockProfile::ORDINARY.with_checked_memory(profile), + target, + ), + )?; ensure!( plan.source_bytes() == source.len(), "source contains unconsumed trailing bytes" @@ -173,7 +179,9 @@ impl CheckedMemoryBlock { native_bytes: compiled.native.x86_64_code.len(), compiler_source_sha256: stela_compiler::SOURCE_SHA256, target, - abi: profile.abi(), + abi: stela_compiler::block::BlockProfile::ORDINARY + .with_checked_memory(profile) + .abi(), memory_model: "checked-normal-wb-all-writers-reservations-lse-ordered-memory-v2", }; let mapping = platform::Mapping::new(&compiled.native.x86_64_code)?; @@ -458,6 +466,7 @@ mod tests { time::{Duration, Instant}, }; use stela_compiler::GuestState; + use stela_compiler::block::Features; use stela_compiler::context::memory::MemoryStatus; const ASID: u64 = 7; @@ -976,8 +985,10 @@ mod tests { let emitted = CompilationPlan::new( &body.source, PC, - BlockProfile::CheckedMemory(body.profile), - body.identity.target, + &stela_compiler::Options::new( + BlockProfile::ORDINARY.with_checked_memory(body.profile), + body.identity.target, + ), ) .unwrap() .compile() @@ -1259,7 +1270,10 @@ mod tests { let original = block(&[LDXR, RET]); let other = block(&[STR, RET]); assert_ne!(original.identity(), other.identity()); - assert_ne!(original.identity().abi, BlockProfile::SystemModeV1.abi()); + assert_ne!( + original.identity().abi, + BlockProfile::new(Features::SYSTEM_MODE).abi() + ); assert_eq!( original.identity().compiler_source_sha256, stela_compiler::SOURCE_SHA256 @@ -1962,8 +1976,10 @@ mod tests { let emitted = CompilationPlan::new( &body.source, PC, - BlockProfile::CheckedMemory(body.profile), - body.identity.target, + &stela_compiler::Options::new( + BlockProfile::ORDINARY.with_checked_memory(body.profile), + body.identity.target, + ), ) .unwrap() .compile() diff --git a/crates/stela-runtime/src/floating/arithmetic/native_tests.rs b/crates/stela-runtime/src/floating/arithmetic/native_tests.rs index 254f306779..c1989ddccf 100644 --- a/crates/stela-runtime/src/floating/arithmetic/native_tests.rs +++ b/crates/stela-runtime/src/floating/arithmetic/native_tests.rs @@ -4,7 +4,7 @@ use crate::execution::platform::Mapping; use stela_compiler::{ GuestAddress, TargetCpu, aarch64::{floating::*, simd::arithmetic::decode}, - block::{BlockProfile, CompilationPlan, ExitKind}, + block::{BlockProfile, CompilationPlan, ExitKind, Features}, }; const PC: u64 = 0x1000; @@ -258,8 +258,7 @@ fn full_path_zeros_rounding_aliases_and_host_environment_match_completion() { let block = CompilationPlan::new( &source, GuestAddress(PC), - BlockProfile::SystemModeV1, - target, + &stela_compiler::Options::new(BlockProfile::new(Features::SYSTEM_MODE), target), ) .unwrap() .compile() @@ -337,8 +336,10 @@ fn full_path_enabled_exceptions_keep_the_prefix_and_original_state() { let block = CompilationPlan::new( &source, GuestAddress(PC), - BlockProfile::SystemModeV1, - TargetCpu::Baseline, + &stela_compiler::Options::new( + BlockProfile::new(Features::SYSTEM_MODE), + TargetCpu::Baseline, + ), ) .unwrap() .compile() @@ -372,8 +373,10 @@ fn full_path_mixed_lanes_preserve_distinct_pairs_and_reject_late_bad_inputs() { let block = CompilationPlan::new( &source, GuestAddress(PC), - BlockProfile::SystemModeV1, - TargetCpu::Baseline, + &stela_compiler::Options::new( + BlockProfile::new(Features::SYSTEM_MODE), + TargetCpu::Baseline, + ), ) .unwrap() .compile() diff --git a/crates/stela-runtime/src/floating/fused_native_tests.rs b/crates/stela-runtime/src/floating/fused_native_tests.rs index 9a98895fa2..6160fbf4e4 100644 --- a/crates/stela-runtime/src/floating/fused_native_tests.rs +++ b/crates/stela-runtime/src/floating/fused_native_tests.rs @@ -7,7 +7,7 @@ use stela_compiler::{ floating::{fused::FusedOperation, *}, simd::fused::{Operand, decode}, }, - block::{BlockProfile, CompilationPlan, ExitKind}, + block::{BlockProfile, CompilationPlan, ExitKind, Features}, }; const PC: u64 = 0x1000; @@ -60,8 +60,7 @@ fn compile(word: u32, target: TargetCpu) -> (Operand, Mapping) { let block = CompilationPlan::new( &source, GuestAddress(PC), - BlockProfile::SystemModeV1, - target, + &stela_compiler::Options::new(BlockProfile::new(Features::SYSTEM_MODE), target), ) .unwrap() .compile() diff --git a/crates/stela-runtime/src/floating/minmax/native_tests.rs b/crates/stela-runtime/src/floating/minmax/native_tests.rs index 3df4a411bc..b9221ccc71 100644 --- a/crates/stela-runtime/src/floating/minmax/native_tests.rs +++ b/crates/stela-runtime/src/floating/minmax/native_tests.rs @@ -4,7 +4,7 @@ use crate::execution::platform::Mapping; use stela_compiler::{ GuestAddress, TargetCpu, aarch64::{floating::*, simd::minmax::decode}, - block::{BlockProfile, CompilationPlan, ExitKind}, + block::{BlockProfile, CompilationPlan, ExitKind, Features}, }; const PC: u64 = 0x1000; @@ -223,8 +223,7 @@ fn signed_zero_and_normal_selection_match_full_helper_state() { let block = CompilationPlan::new( &source, GuestAddress(PC), - BlockProfile::SystemModeV1, - target, + &stela_compiler::Options::new(BlockProfile::new(Features::SYSTEM_MODE), target), ) .unwrap() .compile() @@ -334,8 +333,10 @@ fn exceptional_active_lanes_and_enables_exit_before_any_effect() { let block = CompilationPlan::new( &source, GuestAddress(PC), - BlockProfile::SystemModeV1, - TargetCpu::Baseline, + &stela_compiler::Options::new( + BlockProfile::new(Features::SYSTEM_MODE), + TargetCpu::Baseline, + ), ) .unwrap() .compile() diff --git a/crates/stela-runtime/src/floating/scalable.rs b/crates/stela-runtime/src/floating/scalable.rs index ed68d34ea3..27d35c3cac 100644 --- a/crates/stela-runtime/src/floating/scalable.rs +++ b/crates/stela-runtime/src/floating/scalable.rs @@ -167,7 +167,7 @@ mod tests { AdmittedScalableNumericalInstruction, ScalableNumericalOperation, admit_scalable_numerical_instruction, decode_scalable_numerical_instruction, }, - extended::ScalableProfile, + scalable_context::ScalableProfile, }; const PC: GuestAddress = GuestAddress(0x1008); diff --git a/crates/stela-runtime/src/lib.rs b/crates/stela-runtime/src/lib.rs index 56846b2faa..b118a88a5d 100644 --- a/crates/stela-runtime/src/lib.rs +++ b/crates/stela-runtime/src/lib.rs @@ -70,7 +70,7 @@ use std::io::Read; use std::path::{Path, PathBuf}; use stela_compiler::GuestAddress; #[cfg(feature = "std")] -use stela_compiler::{NATIVE_ABI, NativeBlock}; +use stela_compiler::NativeBlock; fn compiler_source_sha256() -> &'static str { stela_compiler::SOURCE_SHA256 @@ -158,22 +158,21 @@ pub fn prepare_leaf_for_target( root: &Path, target: stela_compiler::TargetCpu, ) -> Result { + use stela_compiler::block::{BlockProfile, Features}; + let profile = BlockProfile::new(Features::LEAF); let identity = Identity { schema_version: 1, source_sha256: sha256(source), compiler_source_sha256: compiler_source_sha256().to_owned(), guest_base: base.0, - abi: NATIVE_ABI.into(), + abi: profile.abi(), target_cpu: target.id(), memory_specialization_sha256: None, }; - prepare( - identity, - root, - None, - stela_compiler::block::BlockProfile::Ordinary, - || stela_compiler::compile_for_target(source, base, target), - ) + prepare(identity, root, None, profile, || { + stela_compiler::compile(source, base, &stela_compiler::Options::new(profile, target)) + .map(|block| block.native) + }) } #[derive(Debug, Serialize)] @@ -190,7 +189,7 @@ pub fn prepare_block(source: &[u8], base: GuestAddress, root: &Path) -> Result

Result { - let plan = stela_compiler::block::CompilationPlan::new(source, base, profile, target)?; + let plan = stela_compiler::block::CompilationPlan::new( + source, + base, + &stela_compiler::Options::new(profile, target), + )?; prepare_block_plan(source, base, root, target, plan) } @@ -233,8 +236,12 @@ pub(crate) fn prepare_runtime_block_for_target( profile: stela_compiler::block::BlockProfile, target: stela_compiler::TargetCpu, ) -> Result<(PreparedBlock, stela_compiler::block::BlockProfile)> { - let plan = stela_compiler::block::CompilationPlan::new(source, base, profile, target)? - .with_resident_loops(); + let plan = stela_compiler::block::CompilationPlan::new( + source, + base, + &stela_compiler::Options::new(profile, target), + )? + .with_resident_loops(); let artifact_profile = plan.profile(); Ok(( prepare_block_plan(source, base, root, target, plan)?, @@ -278,7 +285,7 @@ fn block_plan_identity( source_sha256: sha256(prefix), compiler_source_sha256: compiler_source_sha256().to_owned(), guest_base: base.0, - abi: profile.abi().into(), + abi: profile.abi(), target_cpu: target.id(), memory_specialization_sha256: memory_specialization_sha256( profile, @@ -378,7 +385,7 @@ mod tests { &input, GuestAddress(0x1000), root.path(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, target, )? .prepared; @@ -438,15 +445,15 @@ mod tests { } #[test] fn clock_profile_cache_isolated_from_both_previous_profiles_and_exact_operands() -> Result<()> { - use stela_compiler::block::BlockProfile; + use stela_compiler::block::{BlockProfile, Features}; let root = tempfile::tempdir()?; let base = GuestAddress(0x1000); - let profile = BlockProfile::AppleArm64eSoftwarePauthClockV1; + let profile = BlockProfile::new(Features::POINTER_AUTHENTICATION.union(Features::CLOCK)); let ordinary_source = source(42); let mut keys = std::collections::BTreeSet::new(); for selected in [ - BlockProfile::Ordinary, - BlockProfile::AppleArm64eSoftwarePauthV1, + BlockProfile::ORDINARY, + BlockProfile::new(Features::POINTER_AUTHENTICATION), profile, ] { let block = prepare_block_with_profile(&ordinary_source, base, root.path(), selected)?; @@ -458,8 +465,8 @@ mod tests { .flat_map(|w| w.to_le_bytes()) .collect(); for previous in [ - BlockProfile::Ordinary, - BlockProfile::AppleArm64eSoftwarePauthV1, + BlockProfile::ORDINARY, + BlockProfile::new(Features::POINTER_AUTHENTICATION), ] { assert!(prepare_block_with_profile(&input, base, root.path(), previous).is_err()); } @@ -491,17 +498,17 @@ mod tests { } #[test] fn pac_profile_cache_identity_is_explicit_and_reuses_only_consumed_prefix() -> Result<()> { - use stela_compiler::block::BlockProfile; + use stela_compiler::block::{BlockProfile, Features}; let root = tempfile::tempdir()?; let base = GuestAddress(0x1000); - let profile = BlockProfile::AppleArm64eSoftwarePauthV1; + let profile = BlockProfile::new(Features::POINTER_AUTHENTICATION); let ordinary_source = source(42); let ordinary = prepare_block(&ordinary_source, base, root.path())?; let opted_in = prepare_block_with_profile(&ordinary_source, base, root.path(), profile)?; assert_ne!(ordinary.prepared.key, opted_in.prepared.key); assert_eq!( ordinary.prepared.manifest.identity.abi, - BlockProfile::Ordinary.abi() + BlockProfile::ORDINARY.abi() ); assert_eq!(opted_in.prepared.manifest.identity.abi, profile.abi()); assert_eq!( @@ -538,7 +545,7 @@ mod tests { // Preparation never maps or invokes the artifact; an intact checksum // cannot make metadata from another profile acceptable under this key. let mut manifest = first.prepared.manifest; - manifest.identity.abi = BlockProfile::Ordinary.abi().into(); + manifest.identity.abi = BlockProfile::ORDINARY.abi(); write_json(&first.prepared.directory.join("manifest.json"), &manifest)?; let hash = sha256(&std::fs::read( first.prepared.directory.join("manifest.json"), @@ -640,11 +647,12 @@ mod tests { source[..size_of::()].copy_from_slice(&stack_word.to_le_bytes()); for el0 in [AddressAddChecks::Disabled, AddressAddChecks::Enabled] { for el1 in [AddressAddChecks::Disabled, AddressAddChecks::Enabled] { - let profile = BlockProfile::CheckedMemory(stack.with_address_checks( - AccessEl::El1, - AccessEl::El0, - EffectiveAddressChecks::new(el0, el1), - )); + let profile = + BlockProfile::ORDINARY.with_checked_memory(stack.with_address_checks( + AccessEl::El1, + AccessEl::El0, + EffectiveAddressChecks::new(el0, el1), + )); let first = prepare_block_for_target( &source, GuestAddress(0x1000), @@ -698,7 +706,7 @@ mod tests { let effects = EffectiveAddressChecks::new(AddressAddChecks::Disabled, AddressAddChecks::Enabled); let profile = |normal, unprivileged| { - BlockProfile::CheckedMemory( + BlockProfile::ORDINARY.with_checked_memory( CheckedMemoryProfile::SpAlignmentDisabled.with_address_checks( normal, unprivileged, @@ -711,14 +719,12 @@ mod tests { let first_plan = CompilationPlan::new( &source, GuestAddress(0x1000), - first_profile, - TargetCpu::Baseline, + &stela_compiler::Options::new(first_profile, TargetCpu::Baseline), )?; let second_plan = CompilationPlan::new( &source, GuestAddress(0x1000), - second_profile, - TargetCpu::Baseline, + &stela_compiler::Options::new(second_profile, TargetCpu::Baseline), )?; assert_eq!( first_plan.memory_requirements(), @@ -788,7 +794,7 @@ mod tests { .into_iter() .flat_map(u32::to_le_bytes) .collect(); - let profile = BlockProfile::CheckedMemory( + let profile = BlockProfile::ORDINARY.with_checked_memory( CheckedMemoryProfile::SpAlignmentDisabled.with_address_checks( AccessEl::El0, AccessEl::El0, @@ -834,7 +840,7 @@ mod tests { AccessEl, AddressAddChecks, AddressCheckRequirements, IncrementChoice, }; use stela_compiler::context::memory::{MemoryRequirements, flags}; - let profile = stela_compiler::block::BlockProfile::CheckedMemory( + let profile = stela_compiler::block::BlockProfile::ORDINARY.with_checked_memory( stela_compiler::block::CheckedMemoryProfile::SpAlignmentDisabled.with_address_checks( AccessEl::El0, AccessEl::El0, @@ -878,7 +884,7 @@ mod tests { ); assert!( memory_specialization_sha256( - stela_compiler::block::BlockProfile::Ordinary, + stela_compiler::block::BlockProfile::ORDINARY, Some(MemoryRequirements::default()) )? .is_none() @@ -932,7 +938,8 @@ mod tests { .into_iter() .flat_map(u32::to_le_bytes) .collect(); - let profile = BlockProfile::CheckedMemory(CheckedMemoryProfile::SpAlignmentDisabled); + let profile = + BlockProfile::ORDINARY.with_checked_memory(CheckedMemoryProfile::SpAlignmentDisabled); for version in [None, Some(0), Some(1), Some(3)] { let root = tempfile::tempdir()?; let prepared = prepare_block_for_target( diff --git a/crates/stela-runtime/src/machine/engine.rs b/crates/stela-runtime/src/machine/engine.rs index 7d4e4ec4db..8e71f3fa90 100644 --- a/crates/stela-runtime/src/machine/engine.rs +++ b/crates/stela-runtime/src/machine/engine.rs @@ -114,7 +114,7 @@ use stela_compiler::{ }, }, block::{ - self, BlockProfile, ExitKind, PointerAuthentication, PointerAuthenticationKey, + self, BlockProfile, ExitKind, Features, PointerAuthentication, PointerAuthenticationKey, PointerAuthenticationModifier, PointerAuthenticationOperation, scalar::{ScalarLoad, ScalarLoadAddress, ScalarStore}, system::SystemOperation, @@ -128,7 +128,7 @@ use stela_compiler::{ pub use stored::{Offer, Translations}; pub use system::FP_TRAPS_WRITABLE; -const PROFILE: BlockProfile = BlockProfile::SystemModeV1; +const PROFILE: BlockProfile = BlockProfile::new(Features::SYSTEM_MODE); const INSTRUCTION: u64 = 4; const FETCH_PAGE: u64 = 4096; const MAX_BLOCK_BYTES: u64 = block::MAX_BLOCK_INSTRUCTIONS as u64 * INSTRUCTION; @@ -515,7 +515,7 @@ pub trait Host { } /// The address to call installed context-leaf code at, with - /// `stela_compiler::extended`'s two-argument ABI (the SVE and SME + /// `stela_compiler::scalable_context`'s two-argument ABI (the SVE and SME /// instructions run so), or `None` on a host that cannot run it. The /// engine calls it outside any borrow of the host, whose RAM the leaf's /// memory service then reads and writes. @@ -1964,7 +1964,7 @@ pub struct Machine { /// The context leaves SVE and SME instructions run as, by PC, word and /// scalable profile ([`scalable`]); discarded with the blocks. scalable_leaves: - BTreeMap<(u64, u32, stela_compiler::extended::ScalableProfile), scalable::Leaf>, + BTreeMap<(u64, u32, stela_compiler::scalable_context::ScalableProfile), scalable::Leaf>, /// The Allocation Tags of guest memory (FEAT_MTE2). tags: crate::machine::tags::Store, /// The current [`Regime::tag_checks`]. @@ -8027,7 +8027,7 @@ mod tests { // With one, PSTATE.DIT selects a block of its own, of plain accesses // (LOCK has no listed timing), which load first and so report WnR as // Arm requires: such a host runs one PE at a time. - machine.target = TargetCpu::Sse42Complete.with_doit(); + machine.target = TargetCpu::DATA_INDEPENDENT_TIMING_TIERS[2].with_doit(); machine.cpu.pstate.dit = true; let Ok(Fetched::Block(timed)) = machine.fetch_block(BASE, false) else { panic!("timed block") diff --git a/crates/stela-runtime/src/machine/engine/installed_code.rs b/crates/stela-runtime/src/machine/engine/installed_code.rs index a7b4b0396b..e96922ef66 100644 --- a/crates/stela-runtime/src/machine/engine/installed_code.rs +++ b/crates/stela-runtime/src/machine/engine/installed_code.rs @@ -349,8 +349,13 @@ mod tests { .into_iter() .flat_map(u32::to_le_bytes) .collect(); - stela_compiler::compile(&source, GuestAddress(0x1000)) + let leaf = stela_compiler::Options::new( + stela_compiler::block::BlockProfile::new(stela_compiler::block::Features::LEAF), + stela_compiler::TargetCpu::Baseline, + ); + stela_compiler::compile(&source, GuestAddress(0x1000), &leaf) .unwrap() + .native .x86_64_code }; let mut arena = ExecutableArena { diff --git a/crates/stela-runtime/src/machine/engine/prepare.rs b/crates/stela-runtime/src/machine/engine/prepare.rs index ba5d68e365..1eeef4ba05 100644 --- a/crates/stela-runtime/src/machine/engine/prepare.rs +++ b/crates/stela-runtime/src/machine/engine/prepare.rs @@ -175,23 +175,14 @@ impl Preparation { /// Compile the admitted words `input` at `pc` as the engine compiles a /// block's consumed prefix. pub fn compile_input(&self, input: &[u8], pc: u64) -> Result { - self.compile_plan(CompilationPlan::new( - input, - GuestAddress(pc), - PROFILE, - self.target, - )) + stela_compiler::compile(input, GuestAddress(pc), &self.options()) } - /// Compile a plan of this preparation's target as the engine compiles. - fn compile_plan( - &self, - plan: Result, - ) -> Result { - plan.and_then(|plan| plan.with_memory_checks(self.checks)) - .and_then(|plan| plan.with_zero_block(self.system.zero_block)) - .and_then(|plan| plan.with_cache_clean(self.system.cache_clean)) - .and_then(CompilationPlan::compile) + /// What the engine compiles this preparation's blocks for. + fn options(&self) -> stela_compiler::Options { + stela_compiler::Options::new(PROFILE, self.target) + .with_memory_checks(self.checks) + .with_native_system(self.system) } /// Prepare the block at `pc` from the admitted window `source`, which @@ -244,7 +235,7 @@ impl Preparation { } let refused = |at: u64, detail: String| Refused { pc: at, detail }; let analyze = |length: usize| { - block::analyze_and_plan(&source[..length], GuestAddress(pc), PROFILE, self.target) + block::analyze_and_plan(&source[..length], GuestAddress(pc), &self.options()) }; let (analysis, plan) = match analyze(length) { Ok(analyzed) => analyzed, @@ -286,7 +277,7 @@ impl Preparation { pc, detail: error.0, }; - match self.compile_plan(plan) { + match plan.and_then(CompilationPlan::compile) { Ok(compiled) => Ok((compiled, source.len())), Err(error) => { // A host-capability refusal names no PC; find the longest diff --git a/crates/stela-runtime/src/machine/engine/scalable.rs b/crates/stela-runtime/src/machine/engine/scalable.rs index e7e4c9cfd0..e4532bef6a 100644 --- a/crates/stela-runtime/src/machine/engine/scalable.rs +++ b/crates/stela-runtime/src/machine/engine/scalable.rs @@ -1,6 +1,6 @@ //! SVE and SME instructions that passed their access checks //! (`machine::streaming`), run one at a time as context leaves of the shared -//! compiler (`stela_compiler::extended::prepare_leaf`) on the PE's scalable +//! compiler (a `Features::LEAF | Features::CONTEXT` plan) on the PE's scalable //! state (`crate::scalable`) at the streaming vector length. The leaf's //! profile is the PE's mode (PSTATE.SM and ZA) and the chip's scalable //! features the engine implements; leaves are cached by PC, word and profile @@ -30,7 +30,7 @@ use crate::machine::{ use crate::scalable::ScalableState; use alloc::{format, string::String, vec::Vec}; use stela_compiler::{ - GuestAddress, GuestState, + GuestAddress, GuestState, Options, TargetCpu, aarch64::{ floating::features::NumericalFeatures, scalable::{ @@ -40,9 +40,12 @@ use stela_compiler::{ }, sme::movement, }, - block::scalable::{ - AdmittedScalableNumericalInstruction, admit_scalable_numerical_instruction, - decode_scalable_numerical_instruction, + block::{ + BlockProfile, CompilationPlan, Features, + scalable::{ + AdmittedScalableNumericalInstruction, admit_scalable_numerical_instruction, + decode_scalable_numerical_instruction, + }, }, context::{ ExecutionContext, @@ -51,7 +54,7 @@ use stela_compiler::{ MemoryRequirements, MemoryStatus, SpAlignmentRequirement, flags, profile_requirements, }, }, - extended::{self, ScalableProfile}, + scalable_context::ScalableProfile, }; /// The numerical features of every Apple chip's identification: no @@ -168,7 +171,16 @@ impl Movprfx { } } -/// A context leaf's entry: `extended::prepare_leaf`'s two-argument ABI. +/// What a PE's context leaf of `profile` compiles for. +fn leaf_options(profile: ScalableProfile, target: TargetCpu) -> Options { + Options::new( + BlockProfile::new(Features::LEAF | Features::CONTEXT), + target, + ) + .with_scalable(profile) +} + +/// A context leaf's entry: the two-argument context ABI. type Entry = unsafe extern "sysv64" fn(*mut GuestState, *mut ExecutionContext); /// An installed leaf and what its memory accesses require of the PE. @@ -732,7 +744,8 @@ impl Machine { .iter() .flat_map(|word| word.to_le_bytes()) .collect(); - extended::prepare_leaf(&source, GuestAddress(pc), profile, self.target).is_ok() + let options = leaf_options(profile, self.target); + stela_compiler::compile(&source, GuestAddress(pc), &options).is_ok() } Err(_) => false, } @@ -773,9 +786,17 @@ impl Machine { .iter() .flat_map(|word| word.to_le_bytes()) .collect(); - let prepared = extended::prepare_leaf(&source, GuestAddress(pc), profile, self.target) - .map_err(|error| error.0)?; - let native = &prepared.native.x86_64_code; + let plan = CompilationPlan::new( + &source, + GuestAddress(pc), + &leaf_options(profile, self.target), + ) + .map_err(|error| error.0)?; + let memory = plan + .memory_requirements() + .ok_or_else(|| String::from("a context leaf without memory requirements"))?; + let compiled = plan.compile().map_err(|error| error.0)?; + let native = &compiled.native.x86_64_code; let code = match self.host.install(native) { Ok(code) => code, Err(InstallError::Full) => { @@ -786,10 +807,7 @@ impl Machine { } }; self.statistics.compiled += 1; - let leaf = Leaf { - code, - memory: prepared.memory_requirements, - }; + let leaf = Leaf { code, memory }; self.scalable_leaves.insert((pc, word, profile), leaf); Ok(leaf) } diff --git a/crates/stela-runtime/src/machine/engine/shared_memory/native_run.rs b/crates/stela-runtime/src/machine/engine/shared_memory/native_run.rs index f04957b5ac..7dea557f2f 100644 --- a/crates/stela-runtime/src/machine/engine/shared_memory/native_run.rs +++ b/crates/stela-runtime/src/machine/engine/shared_memory/native_run.rs @@ -7,6 +7,7 @@ pub use epoch::{ }; mod preparation; use preparation::PreparationFailure; +use stela_compiler::block::Features; pub(super) mod source; #[cfg(feature = "native-profile")] use super::super::NativeTimingWork as Work; @@ -34,7 +35,7 @@ pub struct Identity { pub native_sha256: alloc::string::String, pub controls_sha256: alloc::string::String, pub compiler_source_sha256: &'static str, - pub abi: &'static str, + pub abi: alloc::string::String, pub target: stela_compiler::TargetCpu, pub requirements: MemoryRequirements, } @@ -76,7 +77,7 @@ struct ArtifactKey { admission: AdmissionPolicy, controls_sha256: Arc, compiler_source_sha256: &'static str, - abi: &'static str, + abi: alloc::string::String, target: stela_compiler::TargetCpu, guarded: bool, } @@ -720,7 +721,7 @@ impl Machine { /// the scheduler. The actual Cpu owns the persistent canonical memory/event /// service; its inactive legacy fields cannot authorize serial fallback. /// Stopped services must use that same owner and held-generation protocol. - /// Direct SystemModeV1 data writers remain excluded, including between calls. + /// Direct `SYSTEM_MODE` data writers remain excluded, including between calls. /// This bounded frame alone is not full machine SMP admission. pub unsafe fn shared_native_run<'a>( &'a mut self, @@ -842,7 +843,8 @@ fn prepare<'a>( { return Err(at("branch target compatibility", MemoryStatus::Unsupported)); } - let profile = stela_compiler::block::BlockProfile::SystemModeSharedV1(controls.sp); + let profile = stela_compiler::block::BlockProfile::new(Features::SYSTEM_MODE) + .with_checked_memory(controls.sp); let target = memory.ram.target(); let key = ArtifactKey { pe, @@ -931,8 +933,7 @@ fn prepare<'a>( let plan = stela_compiler::block::CompilationPlan::new( &input, stela_compiler::GuestAddress(pc), - profile, - target, + &stela_compiler::Options::new(profile, target), ) .map_err(|error| { at("compilation planning", MemoryStatus::Unsupported).detail(error.0) diff --git a/crates/stela-runtime/src/machine/identification.rs b/crates/stela-runtime/src/machine/identification.rs index 2ddeeff6eb..d824bc59bf 100644 --- a/crates/stela-runtime/src/machine/identification.rs +++ b/crates/stela-runtime/src/machine/identification.rs @@ -19,7 +19,7 @@ use alloc::vec::Vec; use stela_compiler::{ GuestAddress, TargetCpu, aarch64::system::registers::Encoding, - block::{BlockProfile, CompilationPlan}, + block::{BlockProfile, CompilationPlan, Features}, }; /// Why a row's level holds on this engine. @@ -1377,8 +1377,7 @@ fn holds(row: &Row, chip: Chip, target: TargetCpu, el2: bool, speculation: Specu CompilationPlan::new( &word.to_le_bytes(), GuestAddress(0x1000), - BlockProfile::SystemModeV1, - target, + &stela_compiler::Options::new(BlockProfile::new(Features::SYSTEM_MODE), target), ) .and_then(CompilationPlan::compile) .is_ok() @@ -1876,8 +1875,7 @@ mod tests { CompilationPlan::new( &word.to_le_bytes(), GuestAddress(0x1000), - BlockProfile::SystemModeV1, - target, + &stela_compiler::Options::new(BlockProfile::new(Features::SYSTEM_MODE), target), ) .and_then(CompilationPlan::compile) .is_ok() diff --git a/crates/stela-runtime/src/memory/domain/native_target.rs b/crates/stela-runtime/src/memory/domain/native_target.rs index ce571d7963..eb7831eaa1 100644 --- a/crates/stela-runtime/src/memory/domain/native_target.rs +++ b/crates/stela-runtime/src/memory/domain/native_target.rs @@ -31,6 +31,13 @@ pub(in crate::memory) fn restrict(actual: TargetCpu, limit: TargetCpu) -> Target mod tests { use super::*; + /// Every capability `restrict` keeps. + const LEGACY: TargetCpu = TargetCpu::X86_64_V2 + .with_pclmulqdq() + .with_aes() + .with_sha() + .with_atomic_load16(); + #[test] fn neither_limit_nor_current_target_can_promote_the_other() { for left in [ @@ -38,8 +45,8 @@ mod tests { TargetCpu::Ssse3, TargetCpu::Sse41, TargetCpu::Sse42, - TargetCpu::Sse42Complete, - TargetCpu::Avx512Complete, + LEGACY, + TargetCpu::X86_64_V4, ] { for right in [ TargetCpu::Baseline, @@ -49,7 +56,7 @@ mod tests { TargetCpu::Aes, TargetCpu::Sha, TargetCpu::AtomicLoad16, - TargetCpu::Sse42Complete, + LEGACY, ] { let common = restrict(left, right); assert!(left.supports(common)); @@ -66,14 +73,14 @@ mod tests { let worker = TargetCpu::Sse41.with_aes().with_cx16(); assert_eq!(restrict(actual, worker), TargetCpu::Sse41.with_aes()); assert_eq!( - restrict(TargetCpu::Baseline, TargetCpu::Avx512Complete), + restrict(TargetCpu::Baseline, TargetCpu::X86_64_V4), TargetCpu::Baseline ); } #[test] fn caller_modes_and_extended_state_are_never_promoted_by_a_limit() { - let rich = TargetCpu::Avx512Complete + let rich = TargetCpu::X86_64_V4 .with_doit() .with_line_atomic() .with_data_independent_timing(); diff --git a/crates/stela-runtime/src/scalable/block.rs b/crates/stela-runtime/src/scalable/block.rs index a8b57b79b7..c1553a1c18 100644 --- a/crates/stela-runtime/src/scalable/block.rs +++ b/crates/stela-runtime/src/scalable/block.rs @@ -9,10 +9,10 @@ use core::marker::PhantomData; use crate::sha256; use anyhow::{Context, Result, ensure}; use stela_compiler::{ - GuestAddress, TargetCpu, - block::{BlockExit, BlockProfile, ExitKind, MAX_BLOCK_INSTRUCTIONS}, - context::{CONTEXT_BLOCK_ABI, ExecutionContext}, - extended::{CONTEXT_WRAPPER_BYTES, block::ExtendedBlockProfile}, + GuestAddress, Options, TargetCpu, + block::{BlockExit, BlockProfile, ExitKind, Features, MAX_BLOCK_INSTRUCTIONS}, + context::ExecutionContext, + scalable_context::CONTEXT_WRAPPER_BYTES, }; pub use crate::floating::scalable::CompletionError; @@ -34,9 +34,9 @@ pub struct ScalableBlockIdentity { pub native_sha256: String, pub compiler_source_sha256: String, pub guest_base: GuestAddress, - pub abi: &'static str, + pub abi: String, pub target_cpu: String, - pub profile: ExtendedBlockProfile, + pub options: Options, } /// Owns the exact consumed source and its immutable RX translation. The caller @@ -53,16 +53,14 @@ pub struct PreparedScalableBlock { } impl PreparedScalableBlock { - pub fn prepare( - source: &[u8], - base: GuestAddress, - profile: ExtendedBlockProfile, - target: TargetCpu, - ) -> Result { + /// Prepare the block at `base` for `options`, whose profile must be the + /// context block's. + pub fn prepare(source: &[u8], base: GuestAddress, options: &Options) -> Result { ensure!( - profile.services() == BlockProfile::Ordinary, + options.profile() == BlockProfile::new(Features::CONTEXT), "context block services are not integrated" ); + let target = options.target(); ensure!( source.len() <= MAX_BLOCK_INSTRUCTIONS * INSTRUCTION_BYTES, "context block exceeds the compiler instruction bound" @@ -72,8 +70,7 @@ impl PreparedScalableBlock { crate::platform::cpu::admitted(target), "host lacks context-block requirements" ); - let compiled = - stela_compiler::extended::block::compile_for_profile(source, base, profile, target)?; + let compiled = stela_compiler::compile(source, base, options)?; ensure!( compiled.source_bytes > 0 && compiled.source_bytes.is_multiple_of(INSTRUCTION_BYTES) @@ -110,9 +107,9 @@ impl PreparedScalableBlock { native_sha256: sha256(&native.x86_64_code), compiler_source_sha256: stela_compiler::SOURCE_SHA256.into(), guest_base: base, - abi: CONTEXT_BLOCK_ABI, + abi: options.profile().abi(), target_cpu: target.id(), - profile, + options: *options, }; let mapping = platform::Mapping::new(&native.x86_64_code)?; Ok(Self { @@ -130,6 +127,13 @@ impl PreparedScalableBlock { &self.identity } + fn scalable(&self) -> Result { + self.identity + .options + .scalable() + .context("context block options lack a scalable specialization") + } + pub fn source(&self) -> &[u8] { &self.source } @@ -173,7 +177,7 @@ impl PreparedScalableBlock { state.pc == self.identity.guest_base, "context block invocation PC differs from prepared entry" ); - let profile = self.identity.profile.scalable(); + let profile = self.scalable()?; ensure!( scalable.vector_length() == profile.vector_length() && scalable.mode() == profile.mode(), @@ -244,8 +248,8 @@ impl PreparedScalableBlock { self.source.len(), self.identity.guest_base.0, &self.source, - self.identity.profile.scalable(), - self.identity.profile.numerical_features(), + self.scalable()?, + self.identity.options.numerical_features(), ) } } @@ -254,6 +258,15 @@ impl PreparedScalableBlock { mod tests { use super::*; + fn context_options( + scalable: stela_compiler::scalable_context::ScalableProfile, + numerical: stela_compiler::aarch64::floating::features::NumericalFeatures, + ) -> Options { + Options::new(BlockProfile::new(Features::CONTEXT), TargetCpu::Baseline) + .with_scalable(scalable) + .with_numerical_features(numerical) + } + mod fp8 { //! Fixed-width FP8 completion, access and failure. #![cfg(all(target_os = "macos", target_arch = "x86_64"))] @@ -270,7 +283,7 @@ mod tests { }, }, context::ScalableStateView, - extended::ScalableProfile, + scalable_context::ScalableProfile, }; const BASE: GuestAddress = GuestAddress(0x8000); @@ -282,13 +295,7 @@ mod tests { const NUMERICAL_PC: GuestAddress = GuestAddress(BASE.0 + 4); const NEXT_PC: GuestAddress = GuestAddress(BASE.0 + 8); - fn profile( - bytes: usize, - streaming: bool, - enabled: bool, - fp8: bool, - fpmr: bool, - ) -> ExtendedBlockProfile { + fn profile(bytes: usize, streaming: bool, enabled: bool, fp8: bool, fpmr: bool) -> Options { let length = VectorLength::from_bytes(bytes).unwrap(); let mut features = ScalableFeatures::of(Feature::Sme); if fp8 { @@ -300,7 +307,7 @@ mod tests { if streaming { features = features.with(Feature::SmeFa64); } - ExtendedBlockProfile::new( + context_options( ScalableProfile::new_with_features( length, ScalableMode::new(streaming, false), @@ -308,7 +315,6 @@ mod tests { ScalableControls::new(length, false).with_fpmr_enabled(enabled), ) .unwrap(), - BlockProfile::Ordinary, NumericalFeatures::new(streaming, false, false), ) } @@ -321,8 +327,7 @@ mod tests { PreparedScalableBlock::prepare( &source, BASE, - profile(bytes, streaming, true, true, true), - TargetCpu::Baseline, + &profile(bytes, streaming, true, true, true), ) } @@ -516,14 +521,13 @@ mod tests { PreparedScalableBlock::prepare( &source, BASE, - profile(16, false, enabled, fp8, fpmr), - TargetCpu::Baseline + &profile(16, false, enabled, fp8, fpmr) ) .is_err() ); } let length = VectorLength::from_bytes(16).unwrap(); - let streaming_without_fa64 = ExtendedBlockProfile::new( + let streaming_without_fa64 = context_options( ScalableProfile::new_with_features( length, ScalableMode::new(true, false), @@ -533,17 +537,10 @@ mod tests { ScalableControls::new(length, false).with_fpmr_enabled(true), ) .unwrap(), - BlockProfile::Ordinary, NumericalFeatures::default(), ); assert!( - PreparedScalableBlock::prepare( - &source, - BASE, - streaming_without_fa64, - TargetCpu::Baseline - ) - .is_err() + PreparedScalableBlock::prepare(&source, BASE, &streaming_without_fa64).is_err() ); } } @@ -567,7 +564,7 @@ mod tests { ScalableNumericalOperation, admit_scalable_numerical_instruction, decode_scalable_numerical_instruction, }, - extended::ScalableProfile, + scalable_context::ScalableProfile, }; const BASE: GuestAddress = GuestAddress(0x1000); @@ -602,12 +599,7 @@ mod tests { let prepared = PreparedScalableBlock::prepare( &source, BASE, - ExtendedBlockProfile::new( - profile, - BlockProfile::Ordinary, - NumericalFeatures::default(), - ), - TargetCpu::Baseline, + &context_options(profile, NumericalFeatures::default()), )?; assert_eq!(prepared.source(), &source[..2 * size_of::()]); assert_eq!(prepared.source_map().len(), 2); @@ -640,17 +632,15 @@ mod tests { let compiled = PreparedScalableBlock::prepare( &word.to_le_bytes(), BASE, - ExtendedBlockProfile::new( - profile(bytes), - BlockProfile::Ordinary, - NumericalFeatures::default(), - ), - TargetCpu::Baseline, + &context_options(profile(bytes), NumericalFeatures::default()), )?; assert_eq!(compiled.source(), word.to_le_bytes()); assert_eq!( compiled.source_map(), - &[(BASE, stela_compiler::extended::CONTEXT_WRAPPER_BYTES)] + &[( + BASE, + stela_compiler::scalable_context::CONTEXT_WRAPPER_BYTES + )] ); } } @@ -675,7 +665,7 @@ mod tests { }, }, context::ScalableStateView, - extended::ScalableProfile, + scalable_context::ScalableProfile, }; const BASE: GuestAddress = GuestAddress(0x1000); @@ -857,14 +847,14 @@ mod tests { } } - fn profile(bytes: usize, features: NumericalFeatures) -> ExtendedBlockProfile { + fn profile(bytes: usize, features: NumericalFeatures) -> Options { let length = VectorLength::from_bytes(bytes).unwrap(); let mut declared = ScalableFeatures::of(ScalableFeature::Sme).with(ScalableFeature::Sme2); if features.full_a64() { declared = declared.with(ScalableFeature::SmeFa64); } - ExtendedBlockProfile::new( + context_options( ScalableProfile::new_with_features( length, ScalableMode::new(true, true), @@ -872,7 +862,6 @@ mod tests { ScalableControls::new(length, false), ) .unwrap(), - BlockProfile::Ordinary, features, ) } @@ -889,12 +878,7 @@ mod tests { word: u32, features: NumericalFeatures, ) -> Result { - PreparedScalableBlock::prepare( - &source(word), - BASE, - profile(bytes, features), - TargetCpu::Baseline, - ) + PreparedScalableBlock::prepare(&source(word), BASE, &profile(bytes, features)) } fn context() -> ExecutionContext { @@ -997,8 +981,7 @@ mod tests { let prepared = PreparedScalableBlock::prepare( &caller_source, BASE, - profile(bytes, NumericalFeatures::default()), - TargetCpu::Baseline, + &profile(bytes, NumericalFeatures::default()), )?; caller_source.fill(0); // Owned source recovery must ignore this changed caller buffer. let mut fixture = Fixture::new(bytes, true)?; @@ -1235,8 +1218,8 @@ mod tests { access: bool, mode: ScalableMode, numerical: NumericalFeatures, - ) -> Result { - Ok(ExtendedBlockProfile::new( + ) -> Result { + Ok(context_options( ScalableProfile::new_with_features( VectorLength::from_bytes(bytes).unwrap(), mode, @@ -1244,7 +1227,6 @@ mod tests { ScalableControls::new(VectorLength::from_bytes(256).unwrap(), false) .with_fpmr_enabled(access), )?, - BlockProfile::Ordinary, numerical, )) } @@ -1262,10 +1244,7 @@ mod tests { let numerical = NumericalFeatures::default(); // Missing EnFPM permission is refused after exact source re-decoding. let denied = new19_profile(32, declared, false, mode, numerical)?; - assert!( - PreparedScalableBlock::prepare(&source(FP8), BASE, denied, TargetCpu::Baseline) - .is_err() - ); + assert!(PreparedScalableBlock::prepare(&source(FP8), BASE, &denied).is_err()); let instruction = decode_scalable_numerical_instruction(NUMERICAL_PC, FP8)?.unwrap(); assert!( admit_scalable_numerical_instruction(instruction, denied.scalable(), numerical) @@ -1307,15 +1286,7 @@ mod tests { mode, numerical, )?; - assert!( - PreparedScalableBlock::prepare( - &source(word), - BASE, - only_sme, - TargetCpu::Baseline - ) - .is_err() - ); + assert!(PreparedScalableBlock::prepare(&source(word), BASE, &only_sme).is_err()); let nonstreaming = new19_profile( 32, declared, @@ -1324,22 +1295,12 @@ mod tests { numerical, )?; assert!( - PreparedScalableBlock::prepare( - &source(word), - BASE, - nonstreaming, - TargetCpu::Baseline - ) - .is_err() + PreparedScalableBlock::prepare(&source(word), BASE, &nonstreaming).is_err() ); } let short = new19_profile(16, declared, true, mode, numerical)?; - assert!( - PreparedScalableBlock::prepare(&source(LUT), BASE, short, TargetCpu::Baseline) - .is_err() - ); - let entry = - PreparedScalableBlock::prepare(&source(FP8), BASE, allowed, TargetCpu::Baseline)?; + assert!(PreparedScalableBlock::prepare(&source(LUT), BASE, &short).is_err()); + let entry = PreparedScalableBlock::prepare(&source(FP8), BASE, &allowed)?; let mut fixture = Fixture::new(32, false)?; fixture.scalable.set_fpmr(0); let mut context = context(); @@ -1395,12 +1356,7 @@ mod tests { NumericalFeatures::new(true, false, false), )?; for active in [false, true] { - let entry = PreparedScalableBlock::prepare( - &source(ABSOLUTE), - BASE, - fa64, - TargetCpu::Baseline, - )?; + let entry = PreparedScalableBlock::prepare(&source(ABSOLUTE), BASE, &fa64)?; let mut fixture = Fixture::new(32, false)?; fixture.thread.registers.fpcr = FPCR_EXCEPTION_ENABLE_MASK; fixture @@ -1441,8 +1397,7 @@ mod tests { } } // Retained enables under effective FullA64 must refuse without partial commit. - let entry = - PreparedScalableBlock::prepare(&source(FP8), BASE, fa64, TargetCpu::Baseline)?; + let entry = PreparedScalableBlock::prepare(&source(FP8), BASE, &fa64)?; fixture.thread.pc = BASE; fixture.thread.registers.fpcr = FPCR_EXCEPTION_ENABLE_MASK; // SAFETY: the declared FA64 and control profile is bound. @@ -1474,7 +1429,7 @@ mod tests { profile::ScalableControls, }, }, - extended::ScalableProfile, + scalable_context::ScalableProfile, }; const BASE: GuestAddress = GuestAddress(0x1000); @@ -1544,7 +1499,7 @@ mod tests { } const LENGTHS: [usize; 5] = [16, 32, 64, 128, 256]; - fn profile(bytes: usize, za: bool) -> ExtendedBlockProfile { + fn profile(bytes: usize, za: bool) -> Options { let scalable = ScalableProfile::new_with_features( VectorLength::from_bytes(bytes).unwrap(), ScalableMode::new(true, za), @@ -1552,11 +1507,7 @@ mod tests { ScalableControls::new(VectorLength::from_bytes(256).unwrap(), false), ) .unwrap(); - ExtendedBlockProfile::new( - scalable, - BlockProfile::Ordinary, - NumericalFeatures::default(), - ) + context_options(scalable, NumericalFeatures::default()) } fn owner(bytes: usize, za: bool) -> (ThreadState, ScalableState) { @@ -1607,13 +1558,8 @@ mod tests { .iter() .flat_map(|word| word.to_le_bytes()) .collect(); - let block = PreparedScalableBlock::prepare( - &source, - BASE, - profile(bytes, za), - TargetCpu::Baseline, - ) - .unwrap(); + let block = + PreparedScalableBlock::prepare(&source, BASE, &profile(bytes, za)).unwrap(); assert_eq!(block.source(), &source[..2 * size_of::()]); assert_eq!(block.source_map()[1].0, GuestAddress(BASE.0 + WORD_BYTES)); let (mut thread, mut scalable) = owner(bytes, za); @@ -1656,13 +1602,9 @@ mod tests { #[test] fn sme_owned_completion_declines_forged_exit_pc_and_current_owner_without_mutation() { for (word, za) in [(FRINTN_PAIR, false), (FADD_ZA_SINGLE, true)] { - let block = PreparedScalableBlock::prepare( - &word.to_le_bytes(), - BASE, - profile(16, za), - TargetCpu::Baseline, - ) - .unwrap(); + let block = + PreparedScalableBlock::prepare(&word.to_le_bytes(), BASE, &profile(16, za)) + .unwrap(); let (mut thread, mut scalable) = owner(16, za); let valid = BlockExit { next_pc: BASE.0, diff --git a/crates/stela-runtime/src/scalable/leaf.rs b/crates/stela-runtime/src/scalable/leaf.rs index 65249e918c..d884582508 100644 --- a/crates/stela-runtime/src/scalable/leaf.rs +++ b/crates/stela-runtime/src/scalable/leaf.rs @@ -7,18 +7,19 @@ use core::marker::PhantomData; use crate::sha256; use anyhow::{Context, Result, ensure}; use stela_compiler::{ - GuestAddress, GuestState, TargetCpu, + GuestAddress, GuestState, Options, TargetCpu, aarch64::scalable::execution::{ SCALABLE_EXECUTION_REQUIREMENTS_VERSION, ScalableExecutionRequirements, }, + block::{BlockProfile, CompilationPlan, Features}, context::{ - CONTEXT_LEAF_ABI, ExecutionContext, + ExecutionContext, memory::{ MEMORY_IMPLEMENTATION_PROFILE_ID, MemoryRequirements, MemoryStatus, profile_requirements, }, }, - extended::{self, ScalableProfile}, + scalable_context::ScalableProfile, }; use super::{ScalableState, context::ContextLoan}; @@ -34,7 +35,7 @@ pub struct ScalableLeafIdentity { pub native_sha256: String, pub compiler_source_sha256: String, pub guest_base: GuestAddress, - pub abi: &'static str, + pub abi: String, pub target_cpu: String, pub profile: ScalableProfile, pub memory_requirements: MemoryRequirements, @@ -103,10 +104,20 @@ impl PreparedScalableLeaf { "host lacks context-leaf CPU requirements" ); let source: Box<[u8]> = source.into(); - let prepared = extended::prepare_leaf(&source, base, profile, target) + let options = Options::new( + BlockProfile::new(Features::LEAF | Features::CONTEXT), + target, + ) + .with_scalable(profile); + let plan = CompilationPlan::new(&source, base, &options) .context("prepare context leaf and source requirements")?; - let native = prepared.native; - let requirements = prepared.memory_requirements; + let requirements = plan + .memory_requirements() + .context("context leaf memory requirements absent")?; + let execution_requirements = plan + .execution_requirements() + .context("context leaf execution requirements absent")?; + let native = plan.compile().context("compile context leaf")?.native; ensure!( !native.x86_64_code.is_empty() && native.x86_64_code.len() <= MAX_NATIVE_BYTES, "generated context leaf exceeds the native preparation bound" @@ -116,12 +127,12 @@ impl PreparedScalableLeaf { native_sha256: sha256(&native.x86_64_code), compiler_source_sha256: stela_compiler::SOURCE_SHA256.into(), guest_base: base, - abi: CONTEXT_LEAF_ABI, + abi: options.profile().abi(), target_cpu: target.id(), profile, memory_requirements: requirements, execution_requirements_version: SCALABLE_EXECUTION_REQUIREMENTS_VERSION, - execution_requirements: prepared.execution_requirements, + execution_requirements, memory_implementation_profile: (requirements.required_profile & profile_requirements::NATIVE_ACCESS != 0) @@ -463,14 +474,17 @@ mod tests { input.fill(0); assert_eq!(leaf.source(), original); assert_eq!(leaf.identity().source_sha256, sha256(&original)); - assert_eq!(leaf.identity().abi, CONTEXT_LEAF_ABI); + assert_eq!( + leaf.identity().abi, + BlockProfile::new(Features::LEAF | Features::CONTEXT).abi() + ); assert_eq!( leaf.identity().memory_implementation_profile, Some(MEMORY_IMPLEMENTATION_PROFILE_ID) ); assert_eq!(leaf.identity().memory_requirements.required_host_caps, 0); assert_eq!(leaf.source_map()[0].0, GuestAddress(GUEST_BASE)); - assert!(leaf.native_bytes() > extended::CONTEXT_WRAPPER_BYTES); + assert!(leaf.native_bytes() > stela_compiler::scalable_context::CONTEXT_WRAPPER_BYTES); } #[test] diff --git a/crates/stela-runtime/src/system/process_memory/scalable.rs b/crates/stela-runtime/src/system/process_memory/scalable.rs index d6c4a7f397..4e3d2a30a8 100644 --- a/crates/stela-runtime/src/system/process_memory/scalable.rs +++ b/crates/stela-runtime/src/system/process_memory/scalable.rs @@ -254,7 +254,7 @@ mod tests { profile::ScalableControls, }, context::{ScalableStateView, memory::MemoryImplementationProfile}, - extended::ScalableProfile, + scalable_context::ScalableProfile, }; pub(super) const PC: u64 = 0x1000; diff --git a/crates/stela-runtime/src/system/scalable_controls.rs b/crates/stela-runtime/src/system/scalable_controls.rs index 4e50c6f774..f147b65727 100644 --- a/crates/stela-runtime/src/system/scalable_controls.rs +++ b/crates/stela-runtime/src/system/scalable_controls.rs @@ -25,7 +25,7 @@ use stela_compiler::{ features::{ScalableFeature, ScalableFeatures}, }, context::memory::MemoryImplementationProfile, - extended::ScalableProfile, + scalable_context::ScalableProfile, }; const ZEN_SHIFT: u32 = 16; @@ -614,6 +614,23 @@ mod tests { ) .unwrap() } + /// The scalable execution requirements of the context leaf `source`. + fn execution_requirements( + source: &[u8], + profile: ScalableProfile, + ) -> stela_compiler::aarch64::scalable::execution::ScalableExecutionRequirements { + use stela_compiler::block::{BlockProfile, CompilationPlan, Features}; + let options = stela_compiler::Options::new( + BlockProfile::new(Features::LEAF | Features::CONTEXT), + TargetCpu::Baseline, + ) + .with_scalable(profile); + CompilationPlan::new(source, PC, &options) + .unwrap() + .execution_requirements() + .unwrap() + } + fn profile(owner: &ScalableControlOwner<'_>, mode: ScalableMode) -> ScalableProfile { ScalableProfile::new_with_features( owner.current_svl(), @@ -854,12 +871,10 @@ mod tests { let mut registers = GuestState::default(); let profile = profile(&owner, scalable.mode()); let source: Vec = [NOP, RET].into_iter().flat_map(u32::to_le_bytes).collect(); - let prepared = - stela_compiler::extended::prepare_leaf(&source, PC, profile, TargetCpu::Baseline) - .unwrap(); + let requirements = execution_requirements(&source, profile); let mut called = false; let result = owner.with_checked_execution( - &prepared.execution_requirements, + &requirements, profile, &state, &mut registers, @@ -891,12 +906,10 @@ mod tests { .unwrap(); let profile = profile(&owner, scalable.mode()); let source: Vec = [NOP, RET].into_iter().flat_map(u32::to_le_bytes).collect(); - let prepared = - stela_compiler::extended::prepare_leaf(&source, PC, profile, TargetCpu::Baseline) - .unwrap(); + let requirements = execution_requirements(&source, profile); owner .with_checked_execution( - &prepared.execution_requirements, + &requirements, profile, &state, &mut registers, @@ -927,13 +940,11 @@ mod tests { .unwrap(); let profile = profile(&owner, scalable.mode()); let source: Vec = [NOP, RET].into_iter().flat_map(u32::to_le_bytes).collect(); - let prepared = - stela_compiler::extended::prepare_leaf(&source, PC, profile, TargetCpu::Baseline) - .unwrap(); + let requirements = execution_requirements(&source, profile); let mut called = false; assert_eq!( owner.with_checked_execution( - &prepared.execution_requirements, + &requirements, profile, &state, &mut registers, @@ -949,7 +960,7 @@ mod tests { .unwrap(); owner .with_checked_execution( - &prepared.execution_requirements, + &requirements, profile, &state, &mut registers, @@ -989,12 +1000,10 @@ mod tests { let mut scalable = ScalableState::new(length(16), true); let profile = profile(&owner, scalable.mode()); let source: Vec = [NOP, RET].into_iter().flat_map(u32::to_le_bytes).collect(); - let prepared = - stela_compiler::extended::prepare_leaf(&source, PC, profile, TargetCpu::Baseline) - .unwrap(); + let requirements = execution_requirements(&source, profile); assert_eq!( owner.with_checked_execution( - &prepared.execution_requirements, + &requirements, profile, &state, &mut registers, diff --git a/crates/stela-runtime/src/translations.rs b/crates/stela-runtime/src/translations.rs index 6df259e641..0cdc0b4d97 100644 --- a/crates/stela-runtime/src/translations.rs +++ b/crates/stela-runtime/src/translations.rs @@ -11,6 +11,7 @@ pub mod pack; use alloc::{string::String, vec::Vec}; use sha2::{Digest as _, Sha256}; +use stela_compiler::block::Features; use stela_compiler::{ GuestAddress, NativeBlock, block::{CompiledBlock, ExitKind, FaultRecovery}, @@ -53,8 +54,9 @@ pub fn translator_id() -> Digest { let mut hasher = Sha256::new(); hasher.update(RECORD_MAGIC); hasher.update(SCHEMA.to_le_bytes()); + let abi = stela_compiler::block::BlockProfile::new(Features::SYSTEM_MODE).abi(); for part in [ - stela_compiler::block::SYSTEM_MODE_BLOCK_ABI, + abi.as_str(), stela_compiler::SOURCE_SHA256, ENGINE_SOURCE_SHA256, ] { @@ -64,7 +66,7 @@ pub fn translator_id() -> Digest { Digest(hasher.finalize().into()) } -/// The engine's compile-driver sources (`build.rs`). +/// The runtime crate's sources (`build.rs`). pub const ENGINE_SOURCE_SHA256: &str = env!("STELA_ENGINE_SOURCE_SHA256"); /// The address class of a page: bits 47..63 of its address. @@ -559,11 +561,7 @@ pub fn prove( #[cfg(test)] mod tests { use super::*; - use stela_compiler::{ - TargetCpu, - block::{BlockProfile, CompilationPlan}, - x86_64::MemoryChecks, - }; + use stela_compiler::{TargetCpu, block::BlockProfile, x86_64::MemoryChecks}; const PAGE: u64 = 0x1_0000_4000; @@ -572,15 +570,12 @@ mod tests { } fn compile(source: &[u8], pc: u64) -> CompiledBlock { - CompilationPlan::new( - source, - GuestAddress(pc), - BlockProfile::SystemModeV1, + let options = stela_compiler::Options::new( + BlockProfile::new(Features::SYSTEM_MODE), TargetCpu::Baseline, ) - .and_then(|plan| plan.with_memory_checks(MemoryChecks::system(true, false, true, true))) - .and_then(CompilationPlan::compile) - .unwrap() + .with_memory_checks(MemoryChecks::system(true, false, true, true)); + stela_compiler::compile(source, GuestAddress(pc), &options).unwrap() } fn proved(source: &[u8], offset: u64) -> Option { diff --git a/crates/stela-runtime/tests/blocks.rs b/crates/stela-runtime/tests/blocks.rs index 7e46081417..19c2fe3391 100644 --- a/crates/stela-runtime/tests/blocks.rs +++ b/crates/stela-runtime/tests/blocks.rs @@ -86,7 +86,7 @@ mod numerical { let mut runtime = BlockRuntime::new_for_target( 71, cache.path().into(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, target, ); runtime.register_code(GuestAddress(BASE), source.clone())?; @@ -130,7 +130,7 @@ mod numerical { let mut runtime = BlockRuntime::new_for_target( 72, cache.path().into(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, target, ); runtime.register_code(GuestAddress(BASE), source.clone())?; @@ -161,7 +161,7 @@ mod numerical { let mut runtime = BlockRuntime::new_for_target( 72, cache.path().into(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, TargetCpu::Baseline, ); runtime.register_code( @@ -205,7 +205,7 @@ mod numerical { let mut runtime = BlockRuntime::new_for_target( 73, cache.path().into(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, TargetCpu::Baseline, ); runtime.register_code(GuestAddress(BASE), words(&[FADD_S0_S1_S2, RET]))?; @@ -349,7 +349,7 @@ fn simd_family_chain_uses_shared_block_lowering_and_cpu_bound_disk_cache() -> Re let mut runtime = BlockRuntime::new_for_target( 802, cache.path().into(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, target, ); runtime.register_code(GuestAddress(BASE), program.clone())?; @@ -446,7 +446,7 @@ fn simd_register_shifts_and_doubled_products_share_dispatch_and_persistent_code( let mut runtime = BlockRuntime::new_for_target( 803, cache.path().into(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, target, ); runtime.register_code(GuestAddress(BASE), program.clone())?; diff --git a/crates/stela-runtime/tests/context_block_abi_refusal.rs b/crates/stela-runtime/tests/context_block_abi_refusal.rs index f2a9bc3cf7..4ea0a36d09 100644 --- a/crates/stela-runtime/tests/context_block_abi_refusal.rs +++ b/crates/stela-runtime/tests/context_block_abi_refusal.rs @@ -1,7 +1,10 @@ //! Persistent, image-backed and normal-thread paths refuse the context ABI. use anyhow::Result; use std::path::Path; -use stela_compiler::{GuestAddress, GuestState, TargetCpu, context::CONTEXT_BLOCK_ABI}; +use stela_compiler::{ + GuestAddress, GuestState, TargetCpu, + block::{BlockProfile, Features}, +}; use stela_runtime::{ Manifest, Prepared, blocks::{BlockRuntime, ThreadState}, @@ -25,7 +28,7 @@ fn substitute_context_abi(prepared: &Prepared) -> Result<()> { let directory = &prepared.directory; let path = directory.join("manifest.json"); let mut manifest: Manifest = serde_json::from_slice(&std::fs::read(&path)?)?; - manifest.identity.abi = CONTEXT_BLOCK_ABI.into(); + manifest.identity.abi = BlockProfile::new(Features::CONTEXT).abi(); write_json(&path, &manifest)?; write_json( &directory.join("manifest.sha256.json"), diff --git a/crates/stela-runtime/tests/darwin_syscalls/main.rs b/crates/stela-runtime/tests/darwin_syscalls/main.rs index ae4f35e735..bffe228bd6 100644 --- a/crates/stela-runtime/tests/darwin_syscalls/main.rs +++ b/crates/stela-runtime/tests/darwin_syscalls/main.rs @@ -806,7 +806,7 @@ mod native_crossarch { #[cfg(target_os = "macos")] mod native_thread_services { use super::*; - use stela_compiler::block::BlockProfile; + use stela_compiler::block::{BlockProfile, Features}; use stela_runtime::{ clock, darwin::{ExecutionServices, ServiceRunOutcome, platform, run_services}, @@ -925,7 +925,7 @@ mod native_thread_services { let mut runtime = BlockRuntime::new_with_profile( ADDRESS_SPACE_ID, cache.into(), - BlockProfile::DarwinArm64ThreadV1, + BlockProfile::new(Features::THREAD_REGISTERS.union(Features::AMX)), ); runtime.register_code( GuestAddress(BASE), @@ -1145,29 +1145,37 @@ mod native_thread_services { let cache = tempfile::tempdir()?; let foreign = ADDRESS_SPACE_ID + 1; for (profile, pauth_owner, clock_owner) in [ - (BlockProfile::Ordinary, None, None), + (BlockProfile::ORDINARY, None, None), ( - BlockProfile::DarwinArm64ThreadV1, + BlockProfile::new(Features::THREAD_REGISTERS.union(Features::AMX)), Some(ADDRESS_SPACE_ID), None, ), ( - BlockProfile::AppleArm64eSoftwarePauthThreadV1, + BlockProfile::new( + Features::POINTER_AUTHENTICATION + .union(Features::THREAD_REGISTERS) + .union(Features::AMX), + ), Some(foreign), None, ), ( - BlockProfile::AppleArm64eSoftwarePauthClockThreadV1, + BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)), Some(ADDRESS_SPACE_ID), Some(foreign), ), ( - BlockProfile::AppleArm64eSoftwarePauthClockThreadV1, + BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)), None, Some(ADDRESS_SPACE_ID), ), ( - BlockProfile::AppleArm64eSoftwarePauthThreadV1, + BlockProfile::new( + Features::POINTER_AUTHENTICATION + .union(Features::THREAD_REGISTERS) + .union(Features::AMX), + ), Some(ADDRESS_SPACE_ID), Some(ADDRESS_SPACE_ID), ), @@ -1223,7 +1231,7 @@ mod native_thread_services { let mut runtime = BlockRuntime::new_with_profile( ADDRESS_SPACE_ID, cache.path().into(), - BlockProfile::AppleArm64eSoftwarePauthClockThreadV1, + BlockProfile::new(Features::PROCESS_HELPERS.union(Features::AMX)), ); runtime.register_code( GuestAddress(BASE), diff --git a/crates/stela-runtime/tests/darwin_syscalls/native_amx.rs b/crates/stela-runtime/tests/darwin_syscalls/native_amx.rs index 6a2506d900..7f96b4708c 100644 --- a/crates/stela-runtime/tests/darwin_syscalls/native_amx.rs +++ b/crates/stela-runtime/tests/darwin_syscalls/native_amx.rs @@ -6,7 +6,7 @@ use super::*; use stela_compiler::{ TargetCpu, amx::{AmxOperation, AmxRegisters, model}, - block::BlockProfile, + block::{BlockProfile, Features}, }; use stela_runtime::{ amx::Failure, @@ -27,7 +27,7 @@ fn amx_runtime(cache: &std::path::Path, words: &[u32], target: TargetCpu) -> Res let mut runtime = BlockRuntime::new_for_target( ADDRESS_SPACE_ID, cache.into(), - BlockProfile::DarwinArm64ThreadV1, + BlockProfile::new(Features::THREAD_REGISTERS.union(Features::AMX)), target, ); runtime.register_code( @@ -233,7 +233,7 @@ fn profiles_without_thread_state_refuse_amx() -> Result<()> { let mut runtime = BlockRuntime::new_with_profile( ADDRESS_SPACE_ID, cache.path().into(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, ); runtime.register_code( GuestAddress(BASE), diff --git a/crates/stela-runtime/tests/pointer_authentication/main.rs b/crates/stela-runtime/tests/pointer_authentication/main.rs index a901336f88..d32b285385 100644 --- a/crates/stela-runtime/tests/pointer_authentication/main.rs +++ b/crates/stela-runtime/tests/pointer_authentication/main.rs @@ -4,7 +4,7 @@ use anyhow::Result; use std::path::Path; use stela_compiler::{ GuestAddress, GuestState, - block::{BlockProfile, PointerAuthenticationOperation}, + block::{BlockProfile, Features, PointerAuthenticationOperation}, }; use stela_runtime::{ blocks::{BlockRuntime, StopReason, ThreadState}, @@ -18,7 +18,7 @@ const AUTIBSP: u32 = 0xd50323ff; const RETAB: u32 = 0xd65f0fff; const RET: u32 = 0xd65f03c0; const ADD: u32 = 0x91000400; -const PROFILE: BlockProfile = BlockProfile::AppleArm64eSoftwarePauthV1; +const PROFILE: BlockProfile = BlockProfile::new(Features::POINTER_AUTHENTICATION); fn context(address_space: u64) -> Context { Context::new( diff --git a/crates/stela-runtime/tests/pointer_authentication/memory.rs b/crates/stela-runtime/tests/pointer_authentication/memory.rs index 0e57a1637c..af6c689ac8 100644 --- a/crates/stela-runtime/tests/pointer_authentication/memory.rs +++ b/crates/stela-runtime/tests/pointer_authentication/memory.rs @@ -8,7 +8,9 @@ use std::{ sync::Arc, }; use stela_compiler::{ - GuestAddress, GuestState, TargetCpu, block::BlockProfile, context::memory::MemoryStatus, + GuestAddress, GuestState, TargetCpu, + block::{BlockProfile, Features}, + context::memory::MemoryStatus, }; use stela_runtime::{ blocks::{BlockRuntime, StopReason, ThreadState}, @@ -30,7 +32,7 @@ const TAG: u8 = 7; const OTHER_TAG: u8 = TAG + 1; const VALUE: u64 = 0x8877_6655_4433_2211; const KEY: [u64; 2] = [0x1122_3344_5566_7788, 0x99aa_bbcc_ddee_ff00]; -const PROFILE: BlockProfile = BlockProfile::AppleArm64eSoftwarePauthV1; +const PROFILE: BlockProfile = BlockProfile::new(Features::POINTER_AUTHENTICATION); const LDRAA_X1_X0: u32 = 0xf820_0401; const LDRAA_X1_SP: u32 = 0xf820_07e1; const LDRAA_X1_SP_WRITEBACK: u32 = 0xf820_0fe1; diff --git a/crates/stela-runtime/tests/pointer_authentication/modern.rs b/crates/stela-runtime/tests/pointer_authentication/modern.rs index c4d6cb41ec..5d2a5cbab7 100644 --- a/crates/stela-runtime/tests/pointer_authentication/modern.rs +++ b/crates/stela-runtime/tests/pointer_authentication/modern.rs @@ -2,7 +2,10 @@ #![cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] use anyhow::Result; -use stela_compiler::{GuestAddress, GuestState, block::BlockProfile}; +use stela_compiler::{ + GuestAddress, GuestState, + block::{BlockProfile, Features}, +}; use stela_runtime::{ blocks::{BlockRuntime, StopReason, ThreadState}, pauth::{Context, Key, Keys, Version}, @@ -12,7 +15,7 @@ const ADDRESS_SPACE: u64 = 73; const BASE: GuestAddress = GuestAddress(0x1000); const NEXT: GuestAddress = GuestAddress(BASE.0 + 4); const STOP: GuestAddress = GuestAddress(0x1400); -const PROFILE: BlockProfile = BlockProfile::AppleArm64eSoftwarePauthV1; +const PROFILE: BlockProfile = BlockProfile::new(Features::POINTER_AUTHENTICATION); const KEY: [u64; 2] = [0x1122_3344_5566_7788, 0x99aa_bbcc_ddee_ff00]; const PACGA_X1_X2_X3: u32 = 0x9ac3_3041; const PACGA_XZR_X2_SP: u32 = 0x9adf_305f; diff --git a/xtask/src/bench/engines.rs b/xtask/src/bench/engines.rs index cadad8989c..c4f8b9b139 100644 --- a/xtask/src/bench/engines.rs +++ b/xtask/src/bench/engines.rs @@ -8,7 +8,10 @@ use super::fixtures::{Arena, PADDING, PADDING_SPAN, PADDING_STEP}; use anyhow::{Result, bail, ensure}; #[cfg(all(target_os = "macos", target_arch = "x86_64"))] use std::sync::Arc; -use stela_compiler::{GuestAddress, GuestState, TargetCpu, block::BlockProfile}; +use stela_compiler::{ + GuestAddress, GuestState, TargetCpu, + block::{BlockProfile, Features}, +}; use stela_runtime::blocks::{BlockRuntime, StopReason, ThreadState}; #[cfg(all(target_os = "macos", target_arch = "x86_64"))] use stela_runtime::hosted::{hardware::Hardware, host::ProcessHost, pe, tables::Tables}; @@ -63,8 +66,8 @@ pub(super) fn compile_blocks( use stela_compiler::x86_64::MemoryChecks; let target = TargetCpu::detect(); let block_profile = match profile { - Profile::Ordinary => BlockProfile::Ordinary, - Profile::System => BlockProfile::SystemModeV1, + Profile::Ordinary => BlockProfile::ORDINARY, + Profile::System => BlockProfile::new(Features::SYSTEM_MODE), }; let mut seen = std::collections::BTreeSet::new(); let mut pending = vec![entry]; @@ -76,15 +79,17 @@ pub(super) fn compile_blocks( let source = &code[(pc - entry) as usize..]; let analysis = analyze_with_profile(source, GuestAddress(pc), block_profile).map_err(refused)?; - let plan = CompilationPlan::new(source, GuestAddress(pc), block_profile, target) - .map_err(refused)?; + let options = match profile { + Profile::Ordinary => stela_compiler::Options::new(block_profile, target), + Profile::System => stela_compiler::Options::new(block_profile, target) + .with_memory_checks(MemoryChecks::system(true, false, true, false)), + }; + let plan = CompilationPlan::new(source, GuestAddress(pc), &options).map_err(refused)?; let plan = match profile { Profile::Ordinary => plan.with_resident_loops(), - Profile::System => plan - .with_memory_checks(MemoryChecks::system(true, false, true, false)) - .map_err(refused)?, + Profile::System => plan, }; - let resident = plan.profile() == BlockProfile::OrdinaryResidentV1; + let resident = plan.profile() == BlockProfile::new(Features::RESIDENT_LOOPS); let compiled = plan.compile().map_err(refused)?; blocks.push(NativeBlock { pc, @@ -206,7 +211,7 @@ impl Blocks { let mut runtime = BlockRuntime::new_for_target( ADDRESS_SPACE, cache.path().to_owned(), - BlockProfile::Ordinary, + BlockProfile::ORDINARY, TargetCpu::detect(), ); runtime.register_code(GuestAddress(entry), code.to_vec())?;