diff --git a/crates/stela-compiler/src/aarch64.rs b/crates/stela-compiler/src/aarch64.rs index 429c3d394a..ae59e01026 100644 --- a/crates/stela-compiler/src/aarch64.rs +++ b/crates/stela-compiler/src/aarch64.rs @@ -7,6 +7,8 @@ pub mod flags; pub mod floating; pub mod fp_register; pub mod integer_math; +pub mod integer_minmax; +pub mod integer_unary; pub mod literal; pub mod pc_relative; pub mod register_offset; @@ -194,6 +196,8 @@ pub enum Operation { Crc(crc::Operand), Flags(flags::Operand), IntegerMath(integer_math::Operand), + IntegerMinMax(integer_minmax::Operand), + IntegerUnary(integer_unary::Operand), Literal(literal::Operand), MemoryRegisterOffset(register_offset::Operand), MemoryPair { @@ -394,6 +398,10 @@ impl Lifter for Decoder { Operation::Flags(decoded) } else if let Some(decoded) = fp_register::decode(word) { Operation::FloatingPointRegister(decoded) + } else if let Some(decoded) = integer_unary::decode(word) { + Operation::IntegerUnary(decoded) + } else if let Some(decoded) = integer_minmax::decode(word) { + Operation::IntegerMinMax(decoded) } else if let Some(decoded) = integer_math::decode(word) { Operation::IntegerMath(decoded.map_err(|()| unsupported())?) } else if let Some(decoded) = FloatingPointOperation::decode(word) { diff --git a/crates/stela-compiler/src/aarch64/integer_minmax.rs b/crates/stela-compiler/src/aarch64/integer_minmax.rs new file mode 100644 index 0000000000..4cf08bd569 --- /dev/null +++ b/crates/stela-compiler/src/aarch64/integer_minmax.rs @@ -0,0 +1,183 @@ +//! Signed and unsigned scalar register/immediate min/max from FEAT_CSSC. +use super::{Register, Width, register}; + +const REGISTER_OPCODE_MASK: u32 = 0x7fe0_fc00; +const IMMEDIATE_OPCODE_MASK: u32 = 0x7ffc_0000; +const WIDTH_BIT: u32 = 1 << 31; +const REGISTER_MASK: u32 = 31; +const LEFT_SHIFT: u32 = 5; +const RIGHT_SHIFT: u32 = 16; +const IMMEDIATE_SHIFT: u32 = 10; +const IMMEDIATE_MASK: u32 = u8::MAX as u32; +const SIGNED_MAXIMUM_REGISTER: u32 = 0x1ac0_6000; +const SIGNED_MINIMUM_REGISTER: u32 = 0x1ac0_6800; +const UNSIGNED_MAXIMUM_REGISTER: u32 = 0x1ac0_6400; +const UNSIGNED_MINIMUM_REGISTER: u32 = 0x1ac0_6c00; +const SIGNED_MAXIMUM_IMMEDIATE: u32 = 0x11c0_0000; +const SIGNED_MINIMUM_IMMEDIATE: u32 = 0x11c8_0000; +const UNSIGNED_MAXIMUM_IMMEDIATE: u32 = 0x11c4_0000; +const UNSIGNED_MINIMUM_IMMEDIATE: u32 = 0x11cc_0000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + SignedMinimum, + SignedMaximum, + UnsignedMinimum, + UnsignedMaximum, +} + +impl Kind { + pub fn signed(self) -> bool { + matches!(self, Self::SignedMinimum | Self::SignedMaximum) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Right { + Register(Register), + Immediate(u8), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operand { + pub kind: Kind, + pub width: Width, + pub destination: Register, + pub left: Register, + pub right: Right, +} + +pub fn decode(word: u32) -> Option { + let register_kind = match word & REGISTER_OPCODE_MASK { + SIGNED_MINIMUM_REGISTER => Some(Kind::SignedMinimum), + SIGNED_MAXIMUM_REGISTER => Some(Kind::SignedMaximum), + UNSIGNED_MINIMUM_REGISTER => Some(Kind::UnsignedMinimum), + UNSIGNED_MAXIMUM_REGISTER => Some(Kind::UnsignedMaximum), + _ => None, + }; + let (kind, right) = if let Some(kind) = register_kind { + ( + kind, + Right::Register(register((word >> RIGHT_SHIFT) & REGISTER_MASK, false)), + ) + } else { + let kind = match word & IMMEDIATE_OPCODE_MASK { + SIGNED_MINIMUM_IMMEDIATE => Kind::SignedMinimum, + SIGNED_MAXIMUM_IMMEDIATE => Kind::SignedMaximum, + UNSIGNED_MINIMUM_IMMEDIATE => Kind::UnsignedMinimum, + UNSIGNED_MAXIMUM_IMMEDIATE => Kind::UnsignedMaximum, + _ => return None, + }; + ( + kind, + Right::Immediate(((word >> IMMEDIATE_SHIFT) & IMMEDIATE_MASK) as u8), + ) + }; + Some(Operand { + kind, + width: if word & WIDTH_BIT == 0 { + Width::W32 + } else { + Width::X64 + }, + destination: register(word & REGISTER_MASK, false), + left: register((word >> LEFT_SHIFT) & REGISTER_MASK, false), + right, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const FORMS: [(u32, u32, Kind); 4] = [ + ( + SIGNED_MINIMUM_REGISTER, + SIGNED_MINIMUM_IMMEDIATE, + Kind::SignedMinimum, + ), + ( + SIGNED_MAXIMUM_REGISTER, + SIGNED_MAXIMUM_IMMEDIATE, + Kind::SignedMaximum, + ), + ( + UNSIGNED_MINIMUM_REGISTER, + UNSIGNED_MINIMUM_IMMEDIATE, + Kind::UnsignedMinimum, + ), + ( + UNSIGNED_MAXIMUM_REGISTER, + UNSIGNED_MAXIMUM_IMMEDIATE, + Kind::UnsignedMaximum, + ), + ]; + + #[test] + fn every_register_field_including_zero_is_allocated() { + for (opcode, _, kind) in FORMS { + for (width_bit, width) in [(0, Width::W32), (WIDTH_BIT, Width::X64)] { + for destination in 0..=REGISTER_MASK { + for left in 0..=REGISTER_MASK { + for right in 0..=REGISTER_MASK { + assert_eq!( + decode( + opcode + | width_bit + | destination + | (left << LEFT_SHIFT) + | (right << RIGHT_SHIFT) + ), + Some(Operand { + kind, + width, + destination: register(destination, false), + left: register(left, false), + right: Right::Register(register(right, false)), + }) + ); + } + } + } + } + } + } + + #[test] + fn every_immediate_and_each_register_role_retains_raw_bits() { + for (_, opcode, kind) in FORMS { + for (width_bit, width) in [(0, Width::W32), (WIDTH_BIT, Width::X64)] { + for immediate in 0..=u8::MAX { + for destination in 0..=REGISTER_MASK { + for left in [destination, REGISTER_MASK - destination, REGISTER_MASK] { + assert_eq!( + decode( + opcode + | width_bit + | destination + | (left << LEFT_SHIFT) + | (u32::from(immediate) << IMMEDIATE_SHIFT) + ), + Some(Operand { + kind, + width, + destination: register(destination, false), + left: register(left, false), + right: Right::Immediate(immediate), + }) + ); + } + } + } + } + } + } + + #[test] + fn neighboring_integer_classes_are_not_claimed() { + for word in [0x1ac0_2000, 0x1ac0_7000, 0x11d0_0000, 0x1180_0000] { + assert!(decode(word).is_none()); + assert!(decode(word | WIDTH_BIT).is_none()); + } + } +} diff --git a/crates/stela-compiler/src/aarch64/integer_unary.rs b/crates/stela-compiler/src/aarch64/integer_unary.rs new file mode 100644 index 0000000000..db50d96248 --- /dev/null +++ b/crates/stela-compiler/src/aarch64/integer_unary.rs @@ -0,0 +1,93 @@ +//! Scalar absolute value and bit counts from FEAT_CSSC. +use super::{Register, Width, register}; + +const OPCODE_MASK: u32 = 0xffff_fc00; +const WIDTH_BIT: u32 = 1 << 31; +const REGISTER_MASK: u32 = 31; +const SOURCE_SHIFT: u32 = 5; +const ABSOLUTE: u32 = 0x5ac0_2000; +const POPULATION_COUNT: u32 = 0x5ac0_1c00; +const TRAILING_ZEROS: u32 = 0x5ac0_1800; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Absolute, + PopulationCount, + TrailingZeros, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operand { + pub kind: Kind, + pub width: Width, + pub destination: Register, + pub source: Register, +} + +pub fn decode(word: u32) -> Option { + let kind = match word & OPCODE_MASK & !WIDTH_BIT { + ABSOLUTE => Kind::Absolute, + POPULATION_COUNT => Kind::PopulationCount, + TRAILING_ZEROS => Kind::TrailingZeros, + _ => return None, + }; + Some(Operand { + kind, + width: if word & WIDTH_BIT == 0 { + Width::W32 + } else { + Width::X64 + }, + destination: register(word & REGISTER_MASK, false), + source: register((word >> SOURCE_SHIFT) & REGISTER_MASK, false), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn all_register_roles_are_allocated_at_both_widths() { + for (opcode, kind) in [ + (ABSOLUTE, Kind::Absolute), + (POPULATION_COUNT, Kind::PopulationCount), + (TRAILING_ZEROS, Kind::TrailingZeros), + ] { + for (width_bit, width) in [(0, Width::W32), (WIDTH_BIT, Width::X64)] { + for destination in 0..=REGISTER_MASK { + for source in 0..=REGISTER_MASK { + let word = opcode | width_bit | (source << SOURCE_SHIFT) | destination; + assert_eq!( + decode(word), + Some(Operand { + kind, + width, + destination: register(destination, false), + source: register(source, false), + }) + ); + } + } + } + } + } + + #[test] + fn adjacent_historical_and_reserved_opcodes_are_not_claimed() { + // CLZ, CLS, RBIT, REV, and the unallocated opcode above ABS. + for word in [ + 0x5ac0_1000, + 0x5ac0_1400, + 0x5ac0_0000, + 0x5ac0_0800, + 0x5ac0_2400, + ] { + assert!(decode(word).is_none()); + assert!(decode(word | WIDTH_BIT).is_none()); + } + for fixed_bit in [10, 21, 29, 30] { + assert!(decode(ABSOLUTE ^ (1 << fixed_bit)).is_none()); + } + } +} diff --git a/crates/stela-compiler/src/aarch64/simd.rs b/crates/stela-compiler/src/aarch64/simd.rs index 49c21b65ca..1586b716a1 100644 --- a/crates/stela-compiler/src/aarch64/simd.rs +++ b/crates/stela-compiler/src/aarch64/simd.rs @@ -2,6 +2,7 @@ //! Encoding facts: Arm ISA_A64_xml_A_profile-2026-06/{ldr_imm_fpsimd, //! str_imm_fpsimd,ldur_fpsimd,stur_fpsimd,movi_advsimd,ldp_fpsimd,stp_fpsimd}.xml. use super::{AddressMode, Register, register}; +pub mod aes; pub mod arithmetic; pub mod bfloat16; pub mod comparison; @@ -11,6 +12,7 @@ pub mod estimate; pub mod floating; pub mod fused; pub mod halving; +pub mod i8mm; pub mod immediates; pub mod memory; pub mod minmax; @@ -20,6 +22,10 @@ pub mod reductions; pub mod refinement; pub mod rounding; pub mod saturating; +pub mod sha1; +pub mod sha256; +pub mod sha3; +pub mod sha512; pub mod shifts; pub mod sqrt; pub mod widening; @@ -54,6 +60,12 @@ pub enum Comparison { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Operand { + Aes(aes::Operand), + I8mm(i8mm::Operand), + Sha1(sha1::Operand), + Sha256(sha256::Operand), + Sha3(sha3::Operand), + Sha512(sha512::Operand), Floating(floating::Operand), MemoryRegisterOffset(memory::Operand), Immediate(immediates::Operand), @@ -111,6 +123,24 @@ pub enum Operand { /// Each reviewed family validates its reserved encodings; structures decline. #[allow(clippy::result_unit_err)] pub fn decode(word: u32) -> Option> { + if let Some(decoded) = aes::decode(word) { + return Some(decoded.map(Operand::Aes)); + } + if let Some(decoded) = i8mm::decode(word) { + return Some(decoded.map(Operand::I8mm)); + } + if let Some(decoded) = sha1::decode(word) { + return Some(Ok(Operand::Sha1(decoded))); + } + if let Some(decoded) = sha256::decode(word) { + return Some(Ok(Operand::Sha256(decoded))); + } + if let Some(decoded) = sha3::decode(word) { + return Some(decoded.map(Operand::Sha3)); + } + if let Some(decoded) = sha512::decode(word) { + return Some(decoded.map(Operand::Sha512)); + } if let Some(decoded) = memory::decode(word) { return Some(decoded.map(Operand::MemoryRegisterOffset)); } diff --git a/crates/stela-compiler/src/aarch64/simd/aes.rs b/crates/stela-compiler/src/aarch64/simd/aes.rs new file mode 100644 index 0000000000..5ecd0e5a0b --- /dev/null +++ b/crates/stela-compiler/src/aarch64/simd/aes.rs @@ -0,0 +1,77 @@ +//! Classic .16B AES forms from the pinned Arm A64 2026-06 reference. +//! Profile: FEAT_AES and FP/AdvSIMD enabled, non-streaming, 128-bit vector state. +//! V31 is ordinary vector data. These forms do not modify NZCV/FPCR/FPSR. + +const FORM_MASK: u32 = 0xffff_fc00; +const AESE: u32 = 0x4e28_4800; +const AESD: u32 = 0x4e28_5800; +const AESMC: u32 = 0x4e28_6800; +const AESIMC: u32 = 0x4e28_7800; +const REGISTER_MASK: u32 = 31; +const SOURCE_SHIFT: u32 = 5; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Encrypt, + Decrypt, + MixColumns, + InverseMixColumns, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operand { + pub kind: Kind, + pub destination: u8, + pub source: u8, +} + +/// 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> { + let kind = match word & FORM_MASK { + AESE => Kind::Encrypt, + AESD => Kind::Decrypt, + AESMC => Kind::MixColumns, + AESIMC => Kind::InverseMixColumns, + _ => return None, + }; + Some(Ok(Operand { + kind, + destination: (word & REGISTER_MASK) as u8, + source: ((word >> SOURCE_SHIFT) & REGISTER_MASK) as u8, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_register_pair_including_v31_and_aliases_is_ordinary_data() { + for (base, kind) in [ + (AESE, Kind::Encrypt), + (AESD, Kind::Decrypt), + (AESMC, Kind::MixColumns), + (AESIMC, Kind::InverseMixColumns), + ] { + for destination in 0..=REGISTER_MASK { + for source in 0..=REGISTER_MASK { + assert_eq!( + decode(base | (source << SOURCE_SHIFT) | destination), + Some(Ok(Operand { + kind, + destination: destination as u8, + source: source as u8, + })) + ); + } + } + for size in 1..4 { + assert!(decode(base | (size << 22)).is_none()); + } + assert!(decode(base & !(1 << 30)).is_none()); // No .8B form. + assert!(decode(base | (1 << 28)).is_none()); // No scalar form. + } + } +} diff --git a/crates/stela-compiler/src/aarch64/simd/i8mm.rs b/crates/stela-compiler/src/aarch64/simd/i8mm.rs new file mode 100644 index 0000000000..e3780fba44 --- /dev/null +++ b/crates/stela-compiler/src/aarch64/simd/i8mm.rs @@ -0,0 +1,214 @@ +//! Classic Arm A64 June 2026 FEAT_I8MM matrix and mixed-sign dot products. +use super::arithmetic::Shape; + +const REGISTER_MASK: u32 = 31; +const DESTINATION_SHIFT: u32 = 0; +const LEFT_SHIFT: u32 = 5; +const RIGHT_SHIFT: u32 = 16; +const VECTOR_Q: u32 = 1 << 30; +const INDEX_H_SHIFT: u32 = 11; +const INDEX_L_SHIFT: u32 = 21; +const INDEX_BIT_MASK: u32 = 1; +const INDEX_HIGH_SHIFT: u32 = 1; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MatrixKind { + Signed, + Unsigned, + UnsignedSigned, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DotKind { + UnsignedSigned, + SignedUnsigned, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Matrix(MatrixKind), + Dot(DotKind), +} + +impl Kind { + pub fn signedness(self) -> (bool, bool) { + match self { + Self::Matrix(MatrixKind::Signed) => (true, true), + Self::Matrix(MatrixKind::Unsigned) => (false, false), + Self::Matrix(MatrixKind::UnsignedSigned) | Self::Dot(DotKind::UnsignedSigned) => { + (false, true) + } + Self::Dot(DotKind::SignedUnsigned) => (true, false), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operand { + pub kind: Kind, + pub destination: u8, + pub left: u8, + pub right: u8, + pub shape: Shape, + pub index: Option, +} + +#[derive(Clone, Copy)] +enum Encoding { + Smmla, + Ummla, + Usmmla, + Usdot, + UsdotIndexed, + SudotIndexed, +} + +impl Encoding { + const ALL: &'static [Self] = &[ + Self::Smmla, + Self::Ummla, + Self::Usmmla, + Self::Usdot, + Self::UsdotIndexed, + Self::SudotIndexed, + ]; + + fn facts(self) -> (u32, u32, Kind, bool) { + match self { + Self::Smmla => ( + 0xffe0fc00, + 0x4e80a400, + Kind::Matrix(MatrixKind::Signed), + false, + ), + Self::Ummla => ( + 0xffe0fc00, + 0x6e80a400, + Kind::Matrix(MatrixKind::Unsigned), + false, + ), + Self::Usmmla => ( + 0xffe0fc00, + 0x4e80ac00, + Kind::Matrix(MatrixKind::UnsignedSigned), + false, + ), + Self::Usdot => ( + 0xbfe0fc00, + 0x0e809c00, + Kind::Dot(DotKind::UnsignedSigned), + false, + ), + Self::UsdotIndexed => ( + 0xbfc0f400, + 0x0f80f000, + Kind::Dot(DotKind::UnsignedSigned), + true, + ), + Self::SudotIndexed => ( + 0xbfc0f400, + 0x0f00f000, + Kind::Dot(DotKind::SignedUnsigned), + true, + ), + } + } +} + +#[allow(clippy::result_unit_err)] +pub fn decode(word: u32) -> Option> { + let (_, _, kind, indexed) = Encoding::ALL + .iter() + .map(|encoding| encoding.facts()) + .find(|(mask, value, _, _)| word & *mask == *value)?; + Some(Ok(Operand { + kind, + destination: register(word, DESTINATION_SHIFT), + left: register(word, LEFT_SHIFT), + // M is the high register bit; H:L alone selects the dword group. + right: register(word, RIGHT_SHIFT), + shape: if word & VECTOR_Q == 0 { + Shape::Vector64 + } else { + Shape::Vector128 + }, + index: indexed.then_some( + ((((word >> INDEX_H_SHIFT) & INDEX_BIT_MASK) << INDEX_HIGH_SHIFT) + | ((word >> INDEX_L_SHIFT) & INDEX_BIT_MASK)) as u8, + ), + })) +} + +fn register(word: u32, shift: u32) -> u8 { + ((word >> shift) & REGISTER_MASK) as u8 +} + +#[cfg(test)] +mod tests { + use super::*; + + const INDEX_COUNT: u32 = 4; + + #[test] + fn exact_forms_cover_every_register_width_and_index() { + for encoding in Encoding::ALL { + let (_, base, kind, indexed) = encoding.facts(); + let shapes: &[(u32, Shape)] = if matches!(kind, Kind::Matrix(_)) { + &[(VECTOR_Q, Shape::Vector128)] + } else { + &[(0, Shape::Vector64), (VECTOR_Q, Shape::Vector128)] + }; + for &(q, shape) in shapes { + for index in 0..if indexed { INDEX_COUNT } else { 1 } { + for register in 0..=REGISTER_MASK { + for (d, n, m) in [ + (register, 31, 16), + (31, register, 16), + (31, 16, register), + (register, register, register), + ] { + let word = base + | q + | d + | n << LEFT_SHIFT + | m << RIGHT_SHIFT + | (index & INDEX_BIT_MASK) << INDEX_L_SHIFT + | (index >> INDEX_HIGH_SHIFT) << INDEX_H_SHIFT; + assert_eq!( + decode(word), + Some(Ok(Operand { + kind, + destination: d as u8, + left: n as u8, + right: m as u8, + shape, + index: indexed.then_some(index as u8), + })) + ); + } + } + } + } + } + } + + #[test] + fn fixed_bits_never_accept_another_arrangement_or_scalar_form() { + for encoding in Encoding::ALL { + let (mask, base, _, _) = encoding.facts(); + for bit in 0..32 { + if mask & (1 << bit) != 0 { + let changed = base ^ (1 << bit); + if let Some(Ok(other)) = decode(changed) { + // A changed opcode can select another canonical I8MM form, + // but must not retain the original semantic kind. + assert_ne!(other.kind, decode(base).unwrap().unwrap().kind); + } + } + } + } + assert!(decode(0x0e80a400).is_none()); // Matrix Q=0 is unallocated. + assert!(decode(0x5f80f000).is_none()); // No scalar mixed dot form. + assert!(decode(0x0e009c00).is_none()); // No vector SUDOT canonical form. + } +} diff --git a/crates/stela-compiler/src/aarch64/simd/sha1.rs b/crates/stela-compiler/src/aarch64/simd/sha1.rs new file mode 100644 index 0000000000..e69a89e54c --- /dev/null +++ b/crates/stela-compiler/src/aarch64/simd/sha1.rs @@ -0,0 +1,94 @@ +//! Six exact SHA1 forms from Arm ISA_A64_xml_A_profile-2026-06. +//! FEAT_SHA1 and enabled non-streaming FP/AdvSIMD are execution requirements. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Choose, + Parity, + Majority, + Rotate, + Schedule0, + Schedule1, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operand { + pub kind: Kind, + /// Read/write except SHA1H, whose S result clears destination bits 127:32. + pub destination: u8, + pub left: u8, + /// Ignored for SHA1H/SHA1SU1. V31 is ordinary data in every role. + pub right: u8, +} + +const REGISTER_MASK: u32 = 31; +const LEFT_REGISTER_SHIFT: u8 = 5; +const RIGHT_REGISTER_SHIFT: u8 = 16; + +const THREE_REGISTER_MASK: u32 = 0xffe0fc00; +const TWO_REGISTER_MASK: u32 = 0xfffffc00; +const SHA1C: u32 = 0x5e000000; +const SHA1P: u32 = 0x5e001000; +const SHA1M: u32 = 0x5e002000; +const SHA1SU0: u32 = 0x5e003000; +const SHA1H: u32 = 0x5e280800; +const SHA1SU1: u32 = 0x5e281800; + +pub fn decode(word: u32) -> Option { + let kind = match word & THREE_REGISTER_MASK { + SHA1C => Kind::Choose, + SHA1P => Kind::Parity, + SHA1M => Kind::Majority, + SHA1SU0 => Kind::Schedule0, + _ => match word & TWO_REGISTER_MASK { + SHA1H => Kind::Rotate, + SHA1SU1 => Kind::Schedule1, + _ => return None, + }, + }; + Some(Operand { + kind, + destination: (word & REGISTER_MASK) as u8, + left: ((word >> LEFT_REGISTER_SHIFT) & REGISTER_MASK) as u8, + right: ((word >> RIGHT_REGISTER_SHIFT) & REGISTER_MASK) as u8, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exact_forms_accept_all_registers_and_decline_fixed_bit_mutations() { + for (base, mask, kind) in [ + (SHA1C, THREE_REGISTER_MASK, Kind::Choose), + (SHA1P, THREE_REGISTER_MASK, Kind::Parity), + (SHA1M, THREE_REGISTER_MASK, Kind::Majority), + (SHA1SU0, THREE_REGISTER_MASK, Kind::Schedule0), + (SHA1H, TWO_REGISTER_MASK, Kind::Rotate), + (SHA1SU1, TWO_REGISTER_MASK, Kind::Schedule1), + ] { + for destination in 0..32 { + for left in 0..32 { + for right in 0..if mask == THREE_REGISTER_MASK { 32 } else { 1 } { + let operand = decode( + base | destination + | (left << LEFT_REGISTER_SHIFT) + | (right << RIGHT_REGISTER_SHIFT), + ) + .unwrap(); + assert_eq!(operand.kind, kind); + assert_eq!(operand.destination, destination as u8); + assert_eq!(operand.left, left as u8); + if mask == THREE_REGISTER_MASK { + assert_eq!(operand.right, right as u8); + } + } + } + } + // The fixed size/Q/top-level bits must not broaden this family. + for bit in [22, 23, 24, 25, 26, 27, 28, 29, 30, 31] { + assert!(decode(base ^ (1 << bit)).is_none()); + } + } + } +} diff --git a/crates/stela-compiler/src/aarch64/simd/sha256.rs b/crates/stela-compiler/src/aarch64/simd/sha256.rs new file mode 100644 index 0000000000..152aac58a8 --- /dev/null +++ b/crates/stela-compiler/src/aarch64/simd/sha256.rs @@ -0,0 +1,82 @@ +//! Four exact SHA256 forms from Arm ISA_A64_xml_A_profile-2026-06. +//! FEAT_SHA256 and enabled non-streaming FP/AdvSIMD are execution requirements. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Hash, + Hash2, + Schedule0, + Schedule1, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operand { + pub kind: Kind, + pub destination: u8, + pub left: u8, + /// Ignored for SHA256SU0. V31 is ordinary vector data, never ZR/SP. + pub right: u8, +} + +const REGISTER_MASK: u32 = 31; +const LEFT_REGISTER_SHIFT: u8 = 5; +const RIGHT_REGISTER_SHIFT: u8 = 16; + +const THREE_REGISTER_MASK: u32 = 0xffe0fc00; +const TWO_REGISTER_MASK: u32 = 0xfffffc00; +const SHA256H: u32 = 0x5e004000; +const SHA256H2: u32 = 0x5e005000; +const SHA256SU1: u32 = 0x5e006000; +const SHA256SU0: u32 = 0x5e282800; + +pub fn decode(word: u32) -> Option { + let kind = match word & THREE_REGISTER_MASK { + SHA256H => Kind::Hash, + SHA256H2 => Kind::Hash2, + SHA256SU1 => Kind::Schedule1, + _ if word & TWO_REGISTER_MASK == SHA256SU0 => Kind::Schedule0, + _ => return None, + }; + Some(Operand { + kind, + destination: (word & REGISTER_MASK) as u8, + left: ((word >> LEFT_REGISTER_SHIFT) & REGISTER_MASK) as u8, + right: ((word >> RIGHT_REGISTER_SHIFT) & REGISTER_MASK) as u8, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exact_forms_accept_all_registers_and_keep_hash_parts_distinct() { + for (base, mask, kind) in [ + (SHA256H, THREE_REGISTER_MASK, Kind::Hash), + (SHA256H2, THREE_REGISTER_MASK, Kind::Hash2), + (SHA256SU0, TWO_REGISTER_MASK, Kind::Schedule0), + (SHA256SU1, THREE_REGISTER_MASK, Kind::Schedule1), + ] { + for destination in 0..32 { + for left in 0..32 { + for right in 0..if mask == THREE_REGISTER_MASK { 32 } else { 1 } { + let operand = decode( + base | destination + | (left << LEFT_REGISTER_SHIFT) + | (right << RIGHT_REGISTER_SHIFT), + ) + .unwrap(); + assert_eq!(operand.kind, kind); + assert_eq!(operand.destination, destination as u8); + assert_eq!(operand.left, left as u8); + if mask == THREE_REGISTER_MASK { + assert_eq!(operand.right, right as u8); + } + } + } + } + for bit in [22, 23, 24, 25, 26, 27, 28, 29, 30, 31] { + assert!(decode(base ^ (1 << bit)).is_none()); + } + } + } +} diff --git a/crates/stela-compiler/src/aarch64/simd/sha3.rs b/crates/stela-compiler/src/aarch64/simd/sha3.rs new file mode 100644 index 0000000000..3a9a35561e --- /dev/null +++ b/crates/stela-compiler/src/aarch64/simd/sha3.rs @@ -0,0 +1,213 @@ +//! Classic SHA3 logical forms from Arm A64 2026-06 {eor3,bcax,rax1,xar}_advsimd. +//! The enabled, nonstreaming FP/AdvSIMD profile writes all 128 destination bits. +//! These forms neither read nor update FPCR, FPSR or NZCV. V31 is ordinary data. +const REGISTER_MASK: u32 = 31; +const DESTINATION_SHIFT: u32 = 0; +const LEFT_SHIFT: u32 = 5; +const RIGHT_SHIFT: u32 = 16; +const THIRD_SHIFT: u32 = 10; +const XAR_ROTATION_SHIFT: u32 = 10; +const XAR_ROTATION_MASK: u32 = 63; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Eor3 { third: u8 }, + Bcax { third: u8 }, + Rax1, + Xar { rotation: u8 }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operand { + pub kind: Kind, + pub destination: u8, + pub left: u8, + pub right: u8, +} + +#[derive(Clone, Copy)] +enum Encoding { + Eor3, + Bcax, + Rax1, + Xar, +} + +impl Encoding { + const ALL: &'static [Self] = &[Self::Eor3, Self::Bcax, Self::Rax1, Self::Xar]; + + fn facts(self) -> (u32, u32) { + match self { + Self::Eor3 => (0xffe08000, 0xce000000), + Self::Bcax => (0xffe08000, 0xce200000), + Self::Rax1 => (0xffe0fc00, 0xce608c00), + Self::Xar => (0xffe00000, 0xce800000), + } + } + + fn kind(self, word: u32) -> Kind { + let third = register(word, THIRD_SHIFT); + match self { + Self::Eor3 => Kind::Eor3 { third }, + Self::Bcax => Kind::Bcax { third }, + Self::Rax1 => Kind::Rax1, + Self::Xar => Kind::Xar { + rotation: ((word >> XAR_ROTATION_SHIFT) & XAR_ROTATION_MASK) as u8, + }, + } + } +} + +/// 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> { + let encoding = Encoding::ALL.iter().copied().find(|encoding| { + let (mask, value) = encoding.facts(); + word & mask == value + })?; + Some(Ok(Operand { + kind: encoding.kind(word), + destination: register(word, DESTINATION_SHIFT), + left: register(word, LEFT_SHIFT), + right: register(word, RIGHT_SHIFT), + })) +} + +fn register(word: u32, shift: u32) -> u8 { + ((word >> shift) & REGISTER_MASK) as u8 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_register_role_preserves_v31_and_source_aliases() { + for encoding in Encoding::ALL { + let (_, base) = encoding.facts(); + for register in 0..32 { + let word = base | register | (register << LEFT_SHIFT) | (register << RIGHT_SHIFT); + let decoded = decode(word).unwrap().unwrap(); + assert_eq!(decoded.destination, register as u8); + assert_eq!(decoded.left, register as u8); + assert_eq!(decoded.right, register as u8); + } + } + // Independently sweep all four fields, including third sources and V31. + for base in [0xce000000, 0xce200000] { + for destination in 0..32 { + for source in 0..32 { + for (left, right, third) in [(source, 2, 3), (1, source, 3), (1, 2, source)] { + let operand = decode( + base | destination + | (left << LEFT_SHIFT) + | (right << RIGHT_SHIFT) + | (third << THIRD_SHIFT), + ) + .unwrap() + .unwrap(); + assert_eq!(operand.destination, destination as u8); + assert_eq!(operand.left, left as u8); + assert_eq!(operand.right, right as u8); + assert_eq!( + operand.kind, + if base == 0xce000000 { + Kind::Eor3 { third: third as u8 } + } else { + Kind::Bcax { third: third as u8 } + } + ); + } + } + } + } + } + + #[test] + fn known_words_decode_distinct_operand_roles_and_fourth_field() { + for (word, kind) in [ + (0xce020c20, Kind::Eor3 { third: 3 }), + (0xce220c20, Kind::Bcax { third: 3 }), + (0xce628c20, Kind::Rax1), + (0xce82fc20, Kind::Xar { rotation: 63 }), + ] { + assert_eq!( + decode(word), + Some(Ok(Operand { + kind, + destination: 0, + left: 1, + right: 2 + })) + ); + } + for encoding in Encoding::ALL { + let (_, base) = encoding.facts(); + for register in 0..32 { + for (destination, left, right) in + [(register, 1, 2), (0, register, 2), (0, 1, register)] + { + let operand = + decode(base | destination | (left << LEFT_SHIFT) | (right << RIGHT_SHIFT)) + .unwrap() + .unwrap(); + assert_eq!( + (operand.destination, operand.left, operand.right), + (destination as u8, left as u8, right as u8) + ); + } + } + } + } + + #[test] + fn xar_immediate_is_direct_zero_through_sixty_three() { + for rotation in 0..64 { + let operand = decode( + 0xce800000 + | (rotation << XAR_ROTATION_SHIFT) + | (31 << RIGHT_SHIFT) + | (31 << LEFT_SHIFT) + | 31, + ) + .unwrap() + .unwrap(); + assert_eq!( + operand.kind, + Kind::Xar { + rotation: rotation as u8 + } + ); + assert_eq!( + (operand.destination, operand.left, operand.right), + (31, 31, 31) + ); + } + } + + #[test] + fn fixed_bits_are_exact_and_sve_forms_are_not_classic_sha3() { + for word in [0x04203800, 0x04603800, 0x4520f400, 0x04203400, 0xce600000] { + assert!(decode(word).is_none(), "{word:08x}"); + } + for encoding in Encoding::ALL { + let (mask, base) = encoding.facts(); + for bit in 0..32 { + if mask & (1 << bit) == 0 { + continue; + } + let changed = base ^ (1 << bit); + let belongs_to_another_form = Encoding::ALL.iter().any(|other| { + let (other_mask, other_value) = other.facts(); + changed & other_mask == other_value + }); + assert_eq!( + decode(changed).is_some(), + belongs_to_another_form, + "{changed:08x}" + ); + } + } + } +} diff --git a/crates/stela-compiler/src/aarch64/simd/sha512.rs b/crates/stela-compiler/src/aarch64/simd/sha512.rs new file mode 100644 index 0000000000..d86877f9ed --- /dev/null +++ b/crates/stela-compiler/src/aarch64/simd/sha512.rs @@ -0,0 +1,130 @@ +//! Four classic SHA512 forms from the pinned Arm A64 2026-06 reference. +//! Profile: FEAT_SHA512, FP/AdvSIMD enabled, nonstreaming, 128-bit V state. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Hash, + Hash2, + Schedule0, + Schedule1, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operand { + pub kind: Kind, + /// Read/write V register; V31 is ordinary data in every role. + pub destination: u8, + pub left: u8, + /// SHA512SU0 has no third operand. + pub right: Option, +} + +const THREE_REGISTER_MASK: u32 = 0xffe0fc00; +const TWO_REGISTER_MASK: u32 = 0xfffffc00; +const HASH: u32 = 0xce608000; +const HASH2: u32 = 0xce608400; +const SCHEDULE0: u32 = 0xcec08000; +const SCHEDULE1: u32 = 0xce608800; +const REGISTER_MASK: u32 = 31; +const LEFT_SHIFT: u32 = 5; +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> { + let kind = if word & TWO_REGISTER_MASK == SCHEDULE0 { + Kind::Schedule0 + } else { + match word & THREE_REGISTER_MASK { + HASH => Kind::Hash, + HASH2 => Kind::Hash2, + SCHEDULE1 => Kind::Schedule1, + _ => return None, + } + }; + Some(Ok(Operand { + kind, + destination: (word & REGISTER_MASK) as u8, + left: ((word >> LEFT_SHIFT) & REGISTER_MASK) as u8, + right: if kind == Kind::Schedule0 { + None + } else { + Some(((word >> RIGHT_SHIFT) & REGISTER_MASK) as u8) + }, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_allocated_word_preserves_all_register_roles_and_aliases() { + let mut count = 0; + for (base, kind) in [ + (HASH, Kind::Hash), + (HASH2, Kind::Hash2), + (SCHEDULE1, Kind::Schedule1), + ] { + for destination in 0..32u8 { + for left in 0..32u8 { + for right in 0..32u8 { + let word = base + | u32::from(destination) + | (u32::from(left) << LEFT_SHIFT) + | (u32::from(right) << RIGHT_SHIFT); + assert_eq!( + decode(word), + Some(Ok(Operand { + kind, + destination, + left, + right: Some(right), + })) + ); + count += 1; + } + } + } + } + for destination in 0..32u8 { + for left in 0..32u8 { + assert_eq!( + decode(SCHEDULE0 | u32::from(destination) | (u32::from(left) << LEFT_SHIFT)), + Some(Ok(Operand { + kind: Kind::Schedule0, + destination, + left, + right: None, + })) + ); + count += 1; + } + } + assert_eq!(count, 99_328); + } + + #[test] + fn fixed_field_changes_do_not_create_widths_or_consume_other_crypto_forms() { + for (base, mask) in [ + (HASH, THREE_REGISTER_MASK), + (HASH2, THREE_REGISTER_MASK), + (SCHEDULE0, TWO_REGISTER_MASK), + (SCHEDULE1, THREE_REGISTER_MASK), + ] { + for bit in 0..32 { + if mask & (1 << bit) != 0 { + let changed = base ^ (1 << bit); + // One opcode-bit change can legitimately select a sibling. + if ![HASH, HASH2, SCHEDULE0, SCHEDULE1].contains(&changed) { + assert!(decode(changed).is_none(), "{changed:08x}"); + } + } + } + } + for other in [0xce608c00, 0xce60c000, 0xce60c400, 0xcec08400] { + assert!(decode(other).is_none()); // RAX1, SM3PARTW1/2, SM4E + } + } +} diff --git a/crates/stela-compiler/src/lib.rs b/crates/stela-compiler/src/lib.rs index 60eff53af1..8695c36cb3 100644 --- a/crates/stela-compiler/src/lib.rs +++ b/crates/stela-compiler/src/lib.rs @@ -3,13 +3,17 @@ pub mod aarch64; pub mod block; +mod target; pub mod x86_64; +pub use target::TargetCpu; + use serde::{Deserialize, Serialize}; /// Bind cached code and evidence to compiler implementation and dependencies. pub const SOURCE_FINGERPRINT_MATERIAL: &str = concat!( include_str!("lib.rs"), + include_str!("target.rs"), include_str!("aarch64.rs"), include_str!("x86_64.rs"), include_str!("block.rs"), @@ -41,6 +45,10 @@ pub const SOURCE_FINGERPRINT_MATERIAL: &str = concat!( include_str!("x86_64/fp_register.rs"), include_str!("aarch64/integer_math.rs"), include_str!("x86_64/integer_math.rs"), + include_str!("aarch64/integer_unary.rs"), + include_str!("x86_64/integer_unary.rs"), + include_str!("aarch64/integer_minmax.rs"), + include_str!("x86_64/integer_minmax.rs"), include_str!("aarch64/literal.rs"), include_str!("x86_64/literal.rs"), include_str!("aarch64/pc_relative.rs"), @@ -50,6 +58,20 @@ pub const SOURCE_FINGERPRINT_MATERIAL: &str = concat!( include_str!("x86_64/memory_store.rs"), include_str!("aarch64/simd.rs"), include_str!("x86_64/simd.rs"), + include_str!("aarch64/simd/aes.rs"), + include_str!("x86_64/simd/aes.rs"), + include_str!("x86_64/simd/aes/sbox.rs"), + include_str!("aarch64/simd/i8mm.rs"), + include_str!("x86_64/simd/i8mm.rs"), + include_str!("aarch64/simd/sha1.rs"), + include_str!("x86_64/simd/sha1.rs"), + include_str!("aarch64/simd/sha256.rs"), + include_str!("x86_64/simd/sha256.rs"), + include_str!("x86_64/simd/sha32.rs"), + include_str!("aarch64/simd/sha3.rs"), + include_str!("x86_64/simd/sha3.rs"), + include_str!("aarch64/simd/sha512.rs"), + include_str!("x86_64/simd/sha512.rs"), include_str!("aarch64/simd/memory.rs"), include_str!("x86_64/simd/memory.rs"), include_str!("aarch64/simd/floating.rs"), @@ -107,382 +129,6 @@ pub const SOURCE_FINGERPRINT_MATERIAL: &str = concat!( include_str!("../../../Cargo.lock"), ); -/// Explicit host requirements bind generated code and persistent cache identity. -/// SSE tiers are nested; PCLMULQDQ, usable AVX/FMA and F16C are independent. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct TargetCpu { - tier: SseTier, - pclmulqdq: bool, - fma: bool, - f16c: bool, -} - -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -enum SseTier { - #[default] - Baseline, - Ssse3, - Sse41, - Sse42, -} - -// Retain the established public tier names and their canonical cache identities. -#[allow(non_upper_case_globals)] -impl TargetCpu { - pub const Baseline: Self = Self { - tier: SseTier::Baseline, - pclmulqdq: false, - fma: false, - f16c: false, - }; - pub const Ssse3: Self = Self { - tier: SseTier::Ssse3, - pclmulqdq: false, - fma: false, - f16c: false, - }; - pub const Sse41: Self = Self { - tier: SseTier::Sse41, - pclmulqdq: false, - fma: false, - f16c: false, - }; - pub const Sse42: Self = Self { - tier: SseTier::Sse42, - pclmulqdq: false, - fma: false, - f16c: false, - }; - /// 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 fn with_pclmulqdq(self) -> Self { - Self { - pclmulqdq: true, - ..self - } - } - pub const fn with_fma(self) -> Self { - Self { fma: true, ..self } - } - pub const fn with_f16c(self) -> Self { - Self { f16c: true, ..self } - } - /// True only when every required feature is present in this target. - pub fn supports(self, required: Self) -> bool { - self.tier >= required.tier - && (!required.pclmulqdq || self.pclmulqdq) - && (!required.fma || self.fma) - && (!required.f16c || self.f16c) - } - pub fn detect() -> Self { - #[cfg(target_arch = "x86_64")] - { - 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"), - ) - } - #[cfg(not(target_arch = "x86_64"))] - { - Self::Baseline - } - } - #[cfg(any(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, - fma: false, - f16c: false, - } - } - #[cfg(any(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) - } - } - pub fn id(self) -> &'static str { - match (self.tier, self.pclmulqdq, self.fma, self.f16c) { - (SseTier::Baseline, false, false, false) => "x86_64-baseline", - (SseTier::Ssse3, false, false, false) => "x86_64-baseline+ssse3", - (SseTier::Sse41, false, false, false) => "x86_64-baseline+ssse3+sse4.1", - (SseTier::Sse42, false, false, false) => "x86_64-baseline+ssse3+sse4.1+sse4.2", - (SseTier::Baseline, true, false, false) => "x86_64-baseline+pclmulqdq", - (SseTier::Ssse3, true, false, false) => "x86_64-baseline+ssse3+pclmulqdq", - (SseTier::Sse41, true, false, false) => "x86_64-baseline+ssse3+sse4.1+pclmulqdq", - (SseTier::Sse42, true, false, false) => "x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq", - (SseTier::Baseline, false, true, false) => "x86_64-baseline+fma", - (SseTier::Ssse3, false, true, false) => "x86_64-baseline+ssse3+fma", - (SseTier::Sse41, false, true, false) => "x86_64-baseline+ssse3+sse4.1+fma", - (SseTier::Sse42, false, true, false) => "x86_64-baseline+ssse3+sse4.1+sse4.2+fma", - (SseTier::Baseline, true, true, false) => "x86_64-baseline+pclmulqdq+fma", - (SseTier::Ssse3, true, true, false) => "x86_64-baseline+ssse3+pclmulqdq+fma", - (SseTier::Sse41, true, true, false) => "x86_64-baseline+ssse3+sse4.1+pclmulqdq+fma", - (SseTier::Sse42, true, true, false) => { - "x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+fma" - } - (SseTier::Baseline, false, false, true) => "x86_64-baseline+f16c", - (SseTier::Ssse3, false, false, true) => "x86_64-baseline+ssse3+f16c", - (SseTier::Sse41, false, false, true) => "x86_64-baseline+ssse3+sse4.1+f16c", - (SseTier::Sse42, false, false, true) => "x86_64-baseline+ssse3+sse4.1+sse4.2+f16c", - (SseTier::Baseline, true, false, true) => "x86_64-baseline+pclmulqdq+f16c", - (SseTier::Ssse3, true, false, true) => "x86_64-baseline+ssse3+pclmulqdq+f16c", - (SseTier::Sse41, true, false, true) => "x86_64-baseline+ssse3+sse4.1+pclmulqdq+f16c", - (SseTier::Sse42, true, false, true) => { - "x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+f16c" - } - (SseTier::Baseline, false, true, true) => "x86_64-baseline+fma+f16c", - (SseTier::Ssse3, false, true, true) => "x86_64-baseline+ssse3+fma+f16c", - (SseTier::Sse41, false, true, true) => "x86_64-baseline+ssse3+sse4.1+fma+f16c", - (SseTier::Sse42, false, true, true) => "x86_64-baseline+ssse3+sse4.1+sse4.2+fma+f16c", - (SseTier::Baseline, true, true, true) => "x86_64-baseline+pclmulqdq+fma+f16c", - (SseTier::Ssse3, true, true, true) => "x86_64-baseline+ssse3+pclmulqdq+fma+f16c", - (SseTier::Sse41, true, true, true) => "x86_64-baseline+ssse3+sse4.1+pclmulqdq+fma+f16c", - (SseTier::Sse42, true, true, true) => { - "x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+fma+f16c" - } - } - } - pub fn supported(self) -> bool { - cfg!(target_arch = "x86_64") && Self::detect().supports(self) - } -} - -// Ordering means feature containment, not an arbitrary rank. -// Independent PCLMUL, FMA and F16C requirements can make targets incomparable. -impl PartialOrd for TargetCpu { - fn partial_cmp(&self, other: &Self) -> Option { - match (self.supports(*other), other.supports(*self)) { - (true, true) => Some(std::cmp::Ordering::Equal), - (true, false) => Some(std::cmp::Ordering::Greater), - (false, true) => Some(std::cmp::Ordering::Less), - (false, false) => None, - } - } -} - -impl std::str::FromStr for TargetCpu { - type Err = String; - fn from_str(value: &str) -> Result { - let (without_f16c, f16c) = match value.strip_suffix("+f16c") { - Some(target) => (target, true), - None => (value, false), - }; - let (without_fma, fma) = match without_f16c.strip_suffix("+fma") { - Some(target) => (target, true), - None => (without_f16c, false), - }; - let (tier_name, pclmulqdq) = match without_fma.strip_suffix("+pclmulqdq") { - Some(tier_name) => (tier_name, true), - None => (without_fma, false), - }; - let tier = [Self::Baseline, Self::Ssse3, Self::Sse41, Self::Sse42] - .into_iter() - .zip(["baseline", "ssse3", "sse4.1", "sse4.2"]) - .find(|(target, alias)| target.id() == tier_name || *alias == tier_name) - .map(|(target, _)| target) - .ok_or_else(|| format!("unknown x86-64 CPU target {value}"))?; - Ok(Self { - pclmulqdq, - fma, - f16c, - ..tier - }) - } -} - -#[cfg(test)] -mod target_tests { - use super::*; - - const TIERS: [TargetCpu; 4] = [ - TargetCpu::Baseline, - TargetCpu::Ssse3, - TargetCpu::Sse41, - TargetCpu::Sse42, - ]; - - fn targets() -> Vec { - TIERS - .into_iter() - .flat_map(|tier| { - [ - tier, - tier.with_pclmulqdq(), - tier.with_fma(), - tier.with_pclmulqdq().with_fma(), - tier.with_f16c(), - tier.with_pclmulqdq().with_f16c(), - tier.with_fma().with_f16c(), - tier.with_pclmulqdq().with_fma().with_f16c(), - ] - }) - .collect() - } - - #[test] - fn targets_require_every_feature_in_the_declared_tier() { - for bits in 0..16 { - let features = (bits & 1 != 0, bits & 2 != 0, bits & 4 != 0, bits & 8 != 0); - let target = TargetCpu::for_features(features.0, features.1, features.2, features.3); - assert_eq!(target >= TargetCpu::Ssse3, features.0); - assert_eq!(target >= TargetCpu::Sse41, features.0 && features.1); - assert_eq!( - target >= TargetCpu::Sse42, - features.0 && features.1 && features.2 - ); - assert_eq!(target.supports(TargetCpu::Pclmulqdq), features.3); - assert!(!target.supports(TargetCpu::Fma)); - assert!(!target.supports(TargetCpu::F16c)); - } - } - - #[test] - fn vex_detection_requires_avx_state_for_each_independent_feature() { - 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 target = - TargetCpu::for_features_with_vex(ssse3, sse41, sse42, pclmulqdq, avx, fma, f16c); - let previous = TargetCpu::for_features(ssse3, sse41, sse42, pclmulqdq); - let expected = TargetCpu { - fma: avx && fma, - f16c: avx && f16c, - ..previous - }; - assert_eq!(target, expected); - assert_eq!(target.supports(TargetCpu::Fma), avx && fma); - assert_eq!(target.supports(TargetCpu::F16c), avx && f16c); - assert_eq!(target.supports(TargetCpu::Pclmulqdq), pclmulqdq); - assert_eq!(target >= TargetCpu::Sse42, ssse3 && sse41 && sse42); - } - } - - #[test] - fn canonical_ids_and_aliases_round_trip_without_ambiguous_extensions() { - let mut ids = std::collections::BTreeSet::new(); - for target in targets() { - assert!(ids.insert(target.id())); - assert_eq!(target.id().parse::().unwrap(), target); - } - assert_eq!(ids.len(), 32); - for (tier, alias) in TIERS - .into_iter() - .zip(["baseline", "ssse3", "sse4.1", "sse4.2"]) - { - for (suffix, target) in [ - ("", tier), - ("+pclmulqdq", tier.with_pclmulqdq()), - ("+fma", tier.with_fma()), - ("+pclmulqdq+fma", tier.with_pclmulqdq().with_fma()), - ("+f16c", tier.with_f16c()), - ("+pclmulqdq+f16c", tier.with_pclmulqdq().with_f16c()), - ("+fma+f16c", tier.with_fma().with_f16c()), - ( - "+pclmulqdq+fma+f16c", - tier.with_pclmulqdq().with_fma().with_f16c(), - ), - ] { - assert_eq!( - format!("{alias}{suffix}").parse::().unwrap(), - target - ); - } - } - for invalid in [ - "", - "fma", - "f16c", - "avx", - "x86_64-baseline+avx2", - "baseline+avx+fma", - "sse4.2+pclmulqdq+pclmulqdq", - "baseline+fma+fma", - "baseline+pclmulqdq+fma+fma", - "baseline+fma+pclmulqdq", - "x86_64-baseline+sse4.2+fma", - "baseline+fma+unknown", - "baseline+f16c+f16c", - "baseline+f16c+fma", - "baseline+f16c+pclmulqdq", - "baseline+avx+f16c", - ] { - assert!(invalid.parse::().is_err(), "{invalid}"); - } - assert_eq!(TargetCpu::Fma.id(), "x86_64-baseline+fma"); - assert_eq!(TargetCpu::F16c.id(), "x86_64-baseline+f16c"); - assert_eq!( - TargetCpu::Sse42.with_pclmulqdq().with_fma().id(), - "x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+fma" - ); - } - - #[test] - fn independent_features_require_full_containment() { - for host in targets() { - for required in targets() { - let expected = host.tier >= required.tier - && (!required.pclmulqdq || host.pclmulqdq) - && (!required.fma || host.fma); - let expected = expected && (!required.f16c || host.f16c); - assert_eq!(host.supports(required), expected); - assert_eq!(host >= required, expected); - let reverse = required.supports(host); - let ordering = match (expected, reverse) { - (true, true) => Some(std::cmp::Ordering::Equal), - (true, false) => Some(std::cmp::Ordering::Greater), - (false, true) => Some(std::cmp::Ordering::Less), - (false, false) => None, - }; - assert_eq!(host.partial_cmp(&required), ordering); - } - } - assert_eq!(TargetCpu::Sse42.partial_cmp(&TargetCpu::Pclmulqdq), None); - assert_eq!(TargetCpu::Fma.partial_cmp(&TargetCpu::Pclmulqdq), None); - assert_eq!(TargetCpu::Sse42.partial_cmp(&TargetCpu::Fma), None); - assert_eq!(TargetCpu::Fma.partial_cmp(&TargetCpu::F16c), None); - assert!(!TargetCpu::Sse42.supports(TargetCpu::Pclmulqdq)); - assert!(!TargetCpu::Pclmulqdq.supports(TargetCpu::Ssse3)); - assert!(!TargetCpu::Sse42.with_pclmulqdq().supports(TargetCpu::Fma)); - assert!(!TargetCpu::Sse42.with_fma().supports(TargetCpu::F16c)); - assert!(!TargetCpu::F16c.supports(TargetCpu::Fma)); - } -} - #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub struct GuestAddress(pub u64); diff --git a/crates/stela-compiler/src/target.rs b/crates/stela-compiler/src/target.rs new file mode 100644 index 0000000000..801ad08c20 --- /dev/null +++ b/crates/stela-compiler/src/target.rs @@ -0,0 +1,473 @@ +//! Host requirements, detection and stable generated-code target identities. + +/// 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)] +pub struct TargetCpu { + tier: SseTier, + pclmulqdq: bool, + fma: bool, + f16c: bool, + popcnt: bool, + bmi1: bool, + aes: bool, + sha: bool, +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum SseTier { + #[default] + Baseline, + Ssse3, + Sse41, + Sse42, +} + +// Retain the established public tier names and their canonical 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, + }; + pub const Ssse3: Self = Self { + tier: SseTier::Ssse3, + ..Self::Baseline + }; + pub const Sse41: Self = Self { + tier: SseTier::Sse41, + ..Self::Baseline + }; + pub const Sse42: Self = Self { + 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(); + + pub const fn with_pclmulqdq(self) -> Self { + Self { + pclmulqdq: true, + ..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 } + } + /// True only when every required feature is present in this target. + 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) + } + pub fn detect() -> Self { + #[cfg(target_arch = "x86_64")] + { + 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"), + ..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"), + ) + } + } + #[cfg(not(target_arch = "x86_64"))] + { + Self::Baseline + } + } + #[cfg(any(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(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 { + SseTier::Baseline => "x86_64-baseline", + SseTier::Ssse3 => "x86_64-baseline+ssse3", + SseTier::Sse41 => "x86_64-baseline+ssse3+sse4.1", + 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"), + ] { + if enabled { + id.push_str(suffix); + } + } + id + } + pub fn supported(self) -> bool { + cfg!(target_arch = "x86_64") && Self::detect().supports(self) + } +} + +// Ordering means feature containment, not an arbitrary rank. +impl PartialOrd for TargetCpu { + fn partial_cmp(&self, other: &Self) -> Option { + match (self.supports(*other), other.supports(*self)) { + (true, true) => Some(std::cmp::Ordering::Equal), + (true, false) => Some(std::cmp::Ordering::Greater), + (false, true) => Some(std::cmp::Ordering::Less), + (false, false) => None, + } + } +} + +impl std::str::FromStr for TargetCpu { + type Err = String; + fn from_str(value: &str) -> Result { + let mut target = Self::Baseline; + let mut tier_name = value; + // Strip each optional suffix once, in reverse canonical order. Any + // duplicate, unknown or reordered suffix remains and fails tier parsing. + for (suffix, enabled) in [ + ("+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) { + tier_name = prefix; + *enabled = true; + } + } + target.tier = match tier_name { + "baseline" | "x86_64-baseline" => SseTier::Baseline, + "ssse3" | "x86_64-baseline+ssse3" => SseTier::Ssse3, + "sse4.1" | "x86_64-baseline+ssse3+sse4.1" => SseTier::Sse41, + "sse4.2" | "x86_64-baseline+ssse3+sse4.1+sse4.2" => SseTier::Sse42, + _ => return Err(format!("unknown x86-64 CPU target {value}")), + }; + Ok(target) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const TIERS: [(TargetCpu, &str, &str); 4] = [ + (TargetCpu::Baseline, "baseline", "x86_64-baseline"), + (TargetCpu::Ssse3, "ssse3", "x86_64-baseline+ssse3"), + (TargetCpu::Sse41, "sse4.1", "x86_64-baseline+ssse3+sse4.1"), + ( + TargetCpu::Sse42, + "sse4.2", + "x86_64-baseline+ssse3+sse4.1+sse4.2", + ), + ]; + const FEATURES: [TargetCpu; 7] = [ + TargetCpu::Pclmulqdq, + TargetCpu::Fma, + TargetCpu::F16c, + TargetCpu::Popcnt, + TargetCpu::Bmi1, + TargetCpu::Aes, + TargetCpu::Sha, + ]; + + fn profiles() -> impl Iterator { + TIERS.into_iter().flat_map(|(tier, _, _)| { + (0..128).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, + ..tier + }) + }) + } + + #[test] + fn old_canonical_ids_and_aliases_keep_exact_bytes() { + for (tier, alias, canonical) in TIERS { + for (suffix, target) in [ + ("", tier), + ("+pclmulqdq", tier.with_pclmulqdq()), + ("+fma", tier.with_fma()), + ("+pclmulqdq+fma", tier.with_pclmulqdq().with_fma()), + ("+f16c", tier.with_f16c()), + ("+pclmulqdq+f16c", tier.with_pclmulqdq().with_f16c()), + ("+fma+f16c", tier.with_fma().with_f16c()), + ( + "+pclmulqdq+fma+f16c", + tier.with_pclmulqdq().with_fma().with_f16c(), + ), + ] { + assert_eq!(target.id(), format!("{canonical}{suffix}")); + assert_eq!(format!("{alias}{suffix}").parse::(), Ok(target)); + } + } + } + + #[test] + fn every_profile_has_one_canonical_identity_and_alias() { + let mut ids = std::collections::BTreeSet::new(); + for target in profiles() { + let id = target.id(); + assert!(ids.insert(id.clone())); + assert_eq!(id.parse::(), Ok(target)); + let (_, alias, canonical) = TIERS + .into_iter() + .find(|(tier, _, _)| tier.tier == target.tier) + .unwrap(); + let suffix = id.strip_prefix(canonical).unwrap(); + assert_eq!(format!("{alias}{suffix}").parse::(), Ok(target)); + } + assert_eq!(ids.len(), 512); + 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 invalid_duplicate_and_reordered_suffixes_are_rejected() { + for invalid in [ + "", + "native", + "fma", + "f16c", + "popcnt", + "bmi1", + "aes", + "sha", + "avx", + "baseline+", + "baseline+avx+fma", + "baseline+avx+f16c", + "x86_64-baseline+avx2", + "x86_64-baseline+sse4.2+fma", + "baseline+fma+unknown", + "baseline+f16c+fma", + "baseline+sha+aes", + "baseline+aes+bmi1", + "baseline+bmi1+popcnt", + "baseline+popcnt+f16c", + "baseline+fma+pclmulqdq", + "baseline+sha+ssse3", + "baseline+POPCNT", + ] { + assert!(invalid.parse::().is_err(), "{invalid}"); + } + for suffix in ["pclmulqdq", "fma", "f16c", "popcnt", "bmi1", "aes", "sha"] { + for tier in ["baseline", "x86_64-baseline+ssse3+sse4.1+sse4.2"] { + let duplicate = format!("{tier}+{suffix}+{suffix}"); + assert!(duplicate.parse::().is_err(), "{duplicate}"); + } + } + } + + #[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, + ]) { + assert_eq!(host.supports(required), present); + assert_eq!(host >= required, present); + } + 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 { + assert!(!TargetCpu::Sse42.supports(feature)); + assert_eq!(TargetCpu::Sse42.partial_cmp(&feature), None); + for other in FEATURES { + assert_eq!(feature.supports(other), feature == other); + assert_eq!( + feature.partial_cmp(&other), + if feature == other { + Some(std::cmp::Ordering::Equal) + } else { + None + } + ); + } + } + let combined = TargetCpu::Ssse3.with_popcnt().with_aes(); + assert!(combined.supports(TargetCpu::Baseline.with_popcnt().with_aes())); + assert!(!combined.supports(TargetCpu::Ssse3.with_popcnt().with_sha())); + assert!(!combined.supports(TargetCpu::Sse41.with_popcnt().with_aes())); + assert_eq!( + combined.partial_cmp(&TargetCpu::Popcnt), + Some(std::cmp::Ordering::Greater) + ); + assert_eq!( + TargetCpu::Aes.partial_cmp(&combined), + Some(std::cmp::Ordering::Less) + ); + } + + #[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)); + } + } + } + + #[test] + fn native_detection_reads_independent_bits_without_tier_gating() { + let target = TargetCpu::detect(); + #[cfg(target_arch = "x86_64")] + { + for (required, detected) in [ + ( + TargetCpu::Pclmulqdq, + std::is_x86_feature_detected!("pclmulqdq"), + ), + ( + TargetCpu::Fma, + std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma"), + ), + ( + TargetCpu::F16c, + std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("f16c"), + ), + (TargetCpu::Popcnt, std::is_x86_feature_detected!("popcnt")), + (TargetCpu::Bmi1, std::is_x86_feature_detected!("bmi1")), + (TargetCpu::Aes, std::is_x86_feature_detected!("aes")), + (TargetCpu::Sha, std::is_x86_feature_detected!("sha")), + ] { + assert_eq!(target.supports(required), detected); + } + assert!(target.supported()); + } + #[cfg(not(target_arch = "x86_64"))] + { + assert_eq!(target, TargetCpu::Baseline); + assert!(!target.supported()); + } + } +} diff --git a/crates/stela-compiler/src/x86_64.rs b/crates/stela-compiler/src/x86_64.rs index f65d63edb5..6b356ca93f 100644 --- a/crates/stela-compiler/src/x86_64.rs +++ b/crates/stela-compiler/src/x86_64.rs @@ -15,6 +15,8 @@ mod crc; mod flags; mod fp_register; mod integer_math; +mod integer_minmax; +mod integer_unary; pub mod isa; mod literal; mod memory_store; @@ -298,6 +300,8 @@ fn emit_instruction( Operation::Crc(operand) => crc::emit(code, &operand, target), Operation::Flags(operand) => flags::emit(code, &operand), Operation::IntegerMath(operand) => integer_math::emit(code, &operand), + Operation::IntegerMinMax(operand) => integer_minmax::emit(code, &operand), + Operation::IntegerUnary(operand) => integer_unary::emit(code, &operand, target), Operation::Literal(operand) => literal::emit(code, &operand), Operation::MemoryPair { transfer, diff --git a/crates/stela-compiler/src/x86_64/integer_minmax.rs b/crates/stela-compiler/src/x86_64/integer_minmax.rs new file mode 100644 index 0000000000..ba35b21dad --- /dev/null +++ b/crates/stela-compiler/src/x86_64/integer_minmax.rs @@ -0,0 +1,171 @@ +//! Scalar min/max selection without guest condition-flag changes. +use super::{Register, Shift, Width, load, right_operand, store}; +use crate::aarch64::integer_minmax::{Kind, Operand, Right}; + +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) { + if operand.destination == Register::Zero { + code.push(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 + } 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.extend(immediate.to_le_bytes()); + } + } + // 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); + } + // 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, + ]); + store(code, operand.destination); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn signed_x_immediates_sign_extend_but_unsigned_do_not() { + for value in [0, 1, 0x7f, 0x80, 0xff] { + for width in [Width::W32, Width::X64] { + for kind in [ + Kind::SignedMinimum, + Kind::SignedMaximum, + Kind::UnsignedMinimum, + Kind::UnsignedMaximum, + ] { + let mut code = Vec::new(); + emit( + &mut code, + &Operand { + kind, + width, + destination: Register::X(0), + left: Register::X(1), + right: Right::Immediate(value), + }, + ); + let mut prefix = Vec::new(); + load(&mut prefix, Register::X(1)); + let signed_negative_x = width == Width::X64 && kind.signed() && value >= 0x80; + let materialization = if signed_negative_x { + MOV_RCX_IMM32 + } else { + &[MOV_ECX_IMM32] + }; + assert_eq!( + &code[prefix.len()..prefix.len() + materialization.len()], + materialization + ); + let immediate_start = prefix.len() + materialization.len(); + let expected = if kind.signed() { + i32::from(value as i8) as u32 + } else { + u32::from(value) + }; + assert_eq!( + &code[immediate_start..immediate_start + size_of::()], + &expected.to_le_bytes() + ); + } + } + } + } + + #[test] + fn every_predicate_follows_compare_directly_at_guest_width() { + for (kind, condition) in [ + (Kind::SignedMinimum, CMOVG), + (Kind::SignedMaximum, CMOVL), + (Kind::UnsignedMinimum, CMOVA), + (Kind::UnsignedMaximum, CMOVB), + ] { + for width in [Width::W32, Width::X64] { + let mut code = Vec::new(); + emit( + &mut code, + &Operand { + kind, + width, + destination: Register::X(1), + left: Register::X(1), + right: Right::Register(Register::Zero), + }, + ); + let mut prefix = Vec::new(); + load(&mut prefix, Register::X(1)); + right_operand(&mut prefix, Register::Zero, Width::X64, Shift::Lsl, 0); + let expected = if width == Width::X64 { + vec![ + REX_W, + 0x39, + 0xc8, + REX_W, + OPCODE_ESCAPE, + condition, + MODRM_EAX_ECX, + ] + } else { + vec![0x39, 0xc8, OPCODE_ESCAPE, condition, MODRM_EAX_ECX] + }; + let mut suffix = Vec::new(); + store(&mut suffix, Register::X(1)); + assert_eq!(code, [prefix, expected, suffix].concat()); + } + } + } + + #[test] + fn discarded_result_preserves_a_nonempty_interval() { + let mut code = Vec::new(); + emit( + &mut code, + &Operand { + kind: Kind::SignedMinimum, + width: Width::W32, + destination: Register::Zero, + left: Register::X(1), + right: Right::Register(Register::X(2)), + }, + ); + assert_eq!(code, [NOP]); + } +} diff --git a/crates/stela-compiler/src/x86_64/integer_unary.rs b/crates/stela-compiler/src/x86_64/integer_unary.rs new file mode 100644 index 0000000000..6106df6bd8 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/integer_unary.rs @@ -0,0 +1,260 @@ +//! Scalar CSSC recipes; host arithmetic flags never update guest NZCV. +use super::{Register, Width, load, offset, store}; +use crate::{ + TargetCpu, + aarch64::integer_unary::{Kind, Operand}, +}; + +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 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]; +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; +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) { + if operand.destination == Register::Zero { + code.push(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()); + } + } + store(code, 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); + } + Kind::PopulationCount if target.supports(TargetCpu::Popcnt) => { + memory_count(code, operand, POPCNT_EAX_RDI_DISP32, Some(PREFIX_F3)); + } + Kind::PopulationCount => { + load(code, operand.source); + population_count(code, operand.width); + } + Kind::TrailingZeros if target.supports(TargetCpu::Bmi1) => { + memory_count(code, operand, TZCNT_EAX_RDI_DISP32, Some(PREFIX_F3)); + } + Kind::TrailingZeros => { + memory_count(code, operand, BSF_EAX_RDI_DISP32, None); + // 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); + } + } + store(code, operand.destination); +} + +fn memory_count(code: &mut Vec, operand: &Operand, opcode: &[u8], prefix: Option) { + // 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); + let source = offset(operand.source).expect("nonzero scalar count source"); + code.extend(source.to_le_bytes()); +} + +// 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), + } +} + +fn population_count(code: &mut Vec, width: Width) { + // 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); + + 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); + + 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); + + 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); + } + } + instruction(code, width, SHR_EAX_IMM8); + code.push((bits(width) - u8::BITS) as u8); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn emitted(kind: Kind, width: Width, source: Register, target: TargetCpu) -> Vec { + let mut code = Vec::new(); + emit( + &mut code, + &Operand { + kind, + width, + destination: Register::X(0), + source, + }, + target, + ); + code + } + + #[test] + fn optional_count_features_are_independent() { + let baseline = TargetCpu::Baseline; + let source = Register::X(1); + for width in [Width::W32, Width::X64] { + for (kind, required, unrelated) in [ + (Kind::PopulationCount, TargetCpu::Popcnt, TargetCpu::Bmi1), + (Kind::TrailingZeros, TargetCpu::Bmi1, TargetCpu::Popcnt), + ] { + let ordinary = emitted(kind, width, source, baseline); + let checked = emitted(kind, width, source, required); + assert_eq!(emitted(kind, width, source, unrelated), ordinary); + assert_eq!( + emitted(kind, width, source, baseline.with_popcnt().with_bmi1()), + checked + ); + assert!(checked.len() < ordinary.len()); + } + } + } + + #[test] + fn known_zero_source_uses_the_same_short_path_for_every_target() { + for kind in [Kind::Absolute, Kind::PopulationCount, Kind::TrailingZeros] { + for width in [Width::W32, Width::X64] { + let constant = emitted(kind, width, Register::Zero, TargetCpu::Baseline); + assert!( + constant.len() + < emitted(kind, width, Register::X(1), TargetCpu::Baseline).len() + ); + for target in [ + TargetCpu::Popcnt, + TargetCpu::Bmi1, + TargetCpu::Baseline.with_popcnt().with_bmi1(), + ] { + assert_eq!(emitted(kind, width, Register::Zero, target), constant); + } + } + } + } + + #[test] + fn discard_is_a_nonempty_no_effect_interval_for_every_target() { + for kind in [Kind::Absolute, Kind::PopulationCount, Kind::TrailingZeros] { + for width in [Width::W32, Width::X64] { + for target in [ + TargetCpu::Baseline, + TargetCpu::Baseline.with_popcnt().with_bmi1(), + ] { + let mut code = Vec::new(); + emit( + &mut code, + &Operand { + kind, + width, + destination: Register::Zero, + source: Register::X(1), + }, + target, + ); + assert_eq!(code, [NOP]); + } + } + } + } +} diff --git a/crates/stela-compiler/src/x86_64/isa.rs b/crates/stela-compiler/src/x86_64/isa.rs index f029b69483..fd24749c79 100644 --- a/crates/stela-compiler/src/x86_64/isa.rs +++ b/crates/stela-compiler/src/x86_64/isa.rs @@ -16,6 +16,17 @@ macro_rules! catalog { }; } 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]), @@ -111,6 +122,7 @@ catalog! { StoreUnaligned => ("movdqu", Baseline, [0xf3,0x0f,0x7f]), MoveQword => ("movq", Baseline, [0xf3,0x0f,0x7e]), ByteShuffle => ("pshufb", Ssse3, [0x66,0x0f,0x38,0x00]), + AlignBytes => ("palignr", Ssse3, [0x66,0x0f,0x3a,0x0f]), } /// Packed immediate shifts use an opcode group, rather than a source ModRM field. diff --git a/crates/stela-compiler/src/x86_64/simd.rs b/crates/stela-compiler/src/x86_64/simd.rs index 55a2371185..a57549bb3b 100644 --- a/crates/stela-compiler/src/x86_64/simd.rs +++ b/crates/stela-compiler/src/x86_64/simd.rs @@ -4,6 +4,7 @@ use super::isa::SimdOpcode; use super::isa::SimdOpcode as Host; use super::{memory_address, memory_writeback}; use crate::aarch64::simd::{Comparison, IntegerOperation, Operand}; +mod aes; pub(super) mod arithmetic; mod bfloat16; mod comparison; @@ -13,6 +14,7 @@ mod floating; mod fused; mod half; mod halving; +mod i8mm; mod immediates; mod integer_conversion; pub(super) mod memory; @@ -25,6 +27,11 @@ mod reductions; mod refinement; mod rounding; mod saturating; +mod sha1; +mod sha256; +mod sha3; +mod sha32; +mod sha512; mod shifts; mod sqrt; mod widening; @@ -279,6 +286,12 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand) { } pub(super) fn emit_for_target(code: &mut Vec, operand: &Operand, target: crate::TargetCpu) { match *operand { + Operand::Aes(ref operand) => aes::emit(code, operand, target), + Operand::I8mm(ref operand) => i8mm::emit(code, operand, target), + Operand::Sha1(ref operand) => sha1::emit(code, operand, target), + Operand::Sha256(ref operand) => sha256::emit(code, operand, target), + Operand::Sha3(ref operand) => sha3::emit(code, operand), + Operand::Sha512(ref operand) => sha512::emit(code, operand, target), Operand::Floating(ref operand) => floating::emit(code, operand, target), Operand::MemoryRegisterOffset(ref operand) => memory::emit_register_offset(code, operand), Operand::Immediate(ref operand) => immediates::emit(code, operand, target), diff --git a/crates/stela-compiler/src/x86_64/simd/aes.rs b/crates/stela-compiler/src/x86_64/simd/aes.rs new file mode 100644 index 0000000000..b04e3ffa34 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/aes.rs @@ -0,0 +1,240 @@ +//! Fixed-work SSE2 AES transformations and independently gated legacy AES-NI. +//! All guest sources are read before the sole 128-bit destination commit. +//! There are no secret-indexed loads, host FP operations or guest memory effects. +mod sbox; + +use super::{Host, commit, packed, read_vector, rearrange::constant, shuffle}; +use crate::{ + TargetCpu, + aarch64::simd::aes::{Kind, Operand}, + x86_64::isa::ShiftOpcode as Shift, +}; + +const RCX: u8 = 1; +const RESULT: u8 = 0; +const OLD_DESTINATION: u8 = 1; +const MASK: u8 = 3; +const LEFT: u8 = 4; +const RIGHT: u8 = 5; +const TERM: u8 = 6; +const HIGH: u8 = 7; +const BYTE_BITS: u8 = 8; +const COLUMN_BITS: u8 = 32; +const COLUMN_REPLICATION: u64 = 0x0000_0001_0000_0001; +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. + 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) { + packed(code, Host::Xor, HIGH, HIGH); + packed(code, Host::GreaterByte, HIGH, value); + packed(code, Host::AddByte, value, value); + packed(code, Host::And, HIGH, MASK); + packed(code, Host::Xor, value, HIGH); +} + +fn shift_rows(code: &mut Vec, inverse: bool, target: TargetCpu) { + let selection = if inverse { + INVERSE_SHIFT_ROWS + } else { + SHIFT_ROWS + }; + if target.supports(TargetCpu::Ssse3) { + constant(code, MASK, selection); + Host::ByteShuffle.register(code, RESULT, MASK, target); + return; + } + // Each row rotates whole four-byte columns, then a fixed mask selects + // that row from every column. PSHUFD is baseline SSE2, not SSSE3. + let order = if inverse { + INVERSE_COLUMN_ORDER + } else { + FORWARD_COLUMN_ORDER + }; + 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()); + packed(code, Host::MoveGprQword, MASK, RCX); + packed(code, Host::UnpackLowQword, MASK, MASK); + if row == 0 { + packed(code, Host::MoveAligned, RIGHT, RESULT); + packed(code, Host::And, RIGHT, MASK); + } else { + shuffle(code, LEFT, RESULT, control); + packed(code, Host::And, LEFT, MASK); + packed(code, Host::Or, RIGHT, LEFT); + } + } + packed(code, Host::MoveAligned, RESULT, RIGHT); +} + +/// Rotate every four-byte AES column right, preserving the original input. +/// MASK/HIGH remain available for xtime; RESULT may also be the destination. +fn rotate_column(code: &mut Vec, 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); + Shift::RightDword.emit(code, destination, bits); + packed(code, Host::Or, destination, TERM); +} + +fn mix_columns(code: &mut Vec, inverse: bool) { + byte_constant(code, MASK, FIELD_REDUCTION); + if inverse { + rotate_column(code, RIGHT, RESULT, BYTE_BITS * 2); + packed(code, Host::Xor, RIGHT, RESULT); + xtime(code, RIGHT); + xtime(code, RIGHT); + packed(code, Host::Xor, RESULT, RIGHT); + } + packed(code, Host::MoveAligned, LEFT, RESULT); + rotate_column(code, RIGHT, LEFT, BYTE_BITS); + packed(code, Host::Xor, RESULT, RIGHT); + // RESULT = a XOR rot8(a), LEFT retains a. + xtime(code, RESULT); + packed(code, Host::Xor, RESULT, RIGHT); + rotate_column(code, RIGHT, LEFT, BYTE_BITS * 2); + packed(code, Host::Xor, RESULT, RIGHT); + rotate_column(code, RIGHT, LEFT, BYTE_BITS * 3); + packed(code, Host::Xor, RESULT, RIGHT); + // Above equals xtime(a XOR rot8(a)) XOR rot8(a) XOR rot16(a) XOR + // rot24(a): a XOR columnXor simplifies away the duplicate a. +} + +fn aes(code: &mut Vec, kind: Kind, target: TargetCpu) { + if kind == Kind::InverseMixColumns { + Host::AesInverseMixColumns.register(code, RESULT, RESULT, target); + return; + } + packed(code, Host::Xor, MASK, MASK); + match kind { + Kind::Encrypt => Host::AesEncryptLast.register(code, RESULT, MASK, target), + Kind::Decrypt => Host::AesDecryptLast.register(code, RESULT, MASK, target), + Kind::MixColumns => { + Host::AesDecryptLast.register(code, RESULT, MASK, target); + Host::AesEncryptRound.register(code, RESULT, MASK, target); + } + Kind::InverseMixColumns => unreachable!("handled before zero preparation"), + } +} + +pub(super) fn emit(code: &mut Vec, 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); + packed(code, Host::Xor, RESULT, OLD_DESTINATION); + } + if target.supports(TargetCpu::Aes) { + aes(code, operand.kind, target); + } else { + match operand.kind { + Kind::Encrypt => { + shift_rows(code, false, target); + sbox::emit(code, false); + } + Kind::Decrypt => { + shift_rows(code, true, target); + sbox::emit(code, true); + } + Kind::MixColumns => mix_columns(code, false), + Kind::InverseMixColumns => mix_columns(code, true), + } + } + commit(code, operand.destination, RESULT); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn occurrences(code: &[u8], opcode: Host) -> usize { + code.windows(opcode.encoding().len()) + .filter(|window| *window == opcode.encoding()) + .count() + } + + #[test] + fn independent_aes_target_uses_only_the_reviewed_legacy_recipes() { + for (kind, expected, bytes) in [ + (Kind::Encrypt, vec![Host::AesEncryptLast], 37), + (Kind::Decrypt, vec![Host::AesDecryptLast], 37), + ( + Kind::MixColumns, + vec![Host::AesDecryptLast, Host::AesEncryptRound], + 30, + ), + ( + Kind::InverseMixColumns, + vec![Host::AesInverseMixColumns], + 21, + ), + ] { + let operand = Operand { + kind, + destination: 31, + source: 31, + }; + let mut code = Vec::new(); + emit(&mut code, &operand, TargetCpu::Aes); + assert_eq!(code.len(), bytes); // Complete body, excludes harness RET. + for opcode in [ + Host::AesEncryptLast, + Host::AesDecryptLast, + Host::AesEncryptRound, + Host::AesDecryptRound, + Host::AesInverseMixColumns, + ] { + assert_eq!( + occurrences(&code, opcode), + usize::from(expected.contains(&opcode)) + ); + } + assert_eq!(occurrences(&code, Host::ByteShuffle), 0); + } + } + + #[test] + fn baseline_excludes_aes_and_ssse3_even_for_aliases() { + for kind in [ + Kind::Encrypt, + Kind::Decrypt, + Kind::MixColumns, + Kind::InverseMixColumns, + ] { + let mut code = Vec::new(); + emit( + &mut code, + &Operand { + kind, + destination: 31, + source: 31, + }, + TargetCpu::Baseline, + ); + for opcode in [ + Host::AesEncryptLast, + Host::AesDecryptLast, + Host::AesEncryptRound, + Host::AesDecryptRound, + Host::AesInverseMixColumns, + Host::ByteShuffle, + ] { + assert_eq!(occurrences(&code, opcode), 0); + } + } + } +} diff --git a/crates/stela-compiler/src/x86_64/simd/aes/sbox.rs b/crates/stela-compiler/src/x86_64/simd/aes/sbox.rs new file mode 100644 index 0000000000..bfc2d4abb9 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/aes/sbox.rs @@ -0,0 +1,321 @@ +//! Pinned mathematical AES S-box circuits and fixed stack-plane lowering. +//! SysV leaf/block ABI enters with RSP%16=8. The parent emits no prologue; +//! every other ordinary instruction restores its own temporary frame. Padding +//! the complete frame by eight bytes aligns each 16-byte plane for the legacy +//! PAND/PXOR memory operand. GuestState accesses stay unaligned in the parent. +//! There is one fallthrough path and the exact frame is restored before commit. +use super::{BYTE_BITS, Host, LEFT, MASK, RESULT, Shift, TargetCpu, byte_constant, packed}; + +const VECTOR_BYTES: u32 = 16; +const INPUT_PLANES: usize = 8; +const SYSV_ENTRY_STACK_MISALIGNMENT: u32 = 8; +const STACK_MODRM_DISP32: u8 = 0x84; +const STACK_SIB: u8 = 0x24; +const SUB_RSP_IMMEDIATE: [u8; 3] = [0x48, 0x81, 0xec]; +const ADD_RSP_IMMEDIATE: [u8; 3] = [0x48, 0x81, 0xc4]; + +// Peralta/Calik's 113-gate forward and 121-gate inverse mathematical circuits: +// https://www.cs.yale.edu/homes/peralta/CircuitStuff/{SLP_AES_113.txt,Sinv.txt}. +// Hash-pinned research receipts retain source identity and exhaustive checks +// against Arm's independent S-box tables. U0/S0 are the most significant bits. +// Every gate is evaluated on sixteen independent 0/1 byte planes. Fixed stack +// locations keep lowering simple; no secret-indexed access or allocation policy. +#[derive(Clone, Copy)] +enum Gate { + And(u8, u8), + Xor(u8, u8), + Xnor(u8, u8), +} + +const FORWARD_GATES: [Gate; 113] = [ + Gate::Xor(3, 5), + Gate::Xor(0, 6), + Gate::Xor(0, 3), + Gate::Xor(0, 5), + Gate::Xor(1, 2), + Gate::Xor(12, 7), + Gate::Xor(13, 3), + Gate::Xor(9, 8), + Gate::Xor(13, 0), + Gate::Xor(13, 6), + Gate::Xor(17, 11), + Gate::Xor(4, 15), + Gate::Xor(19, 5), + Gate::Xor(19, 1), + Gate::Xor(20, 7), + Gate::Xor(20, 12), + Gate::Xor(21, 10), + Gate::Xor(7, 24), + Gate::Xor(23, 24), + Gate::Xor(23, 11), + Gate::Xor(12, 24), + Gate::Xor(9, 28), + Gate::Xor(0, 28), + Gate::And(15, 20), + Gate::And(18, 22), + Gate::Xor(32, 31), + Gate::And(14, 7), + Gate::Xor(34, 31), + Gate::And(9, 28), + Gate::And(17, 13), + Gate::Xor(37, 36), + Gate::And(16, 25), + Gate::Xor(39, 36), + Gate::And(10, 24), + Gate::And(8, 26), + Gate::Xor(42, 41), + Gate::And(11, 23), + Gate::Xor(44, 41), + Gate::Xor(33, 21), + Gate::Xor(35, 45), + Gate::Xor(38, 43), + Gate::Xor(40, 45), + Gate::Xor(46, 43), + Gate::Xor(47, 27), + Gate::Xor(48, 29), + Gate::Xor(49, 30), + Gate::Xor(50, 51), + Gate::And(50, 52), + Gate::Xor(53, 55), + Gate::And(54, 56), + Gate::Xor(57, 51), + Gate::Xor(52, 53), + Gate::Xor(51, 55), + Gate::And(60, 59), + Gate::Xor(61, 53), + Gate::Xor(52, 62), + Gate::Xor(56, 62), + Gate::And(53, 64), + Gate::Xor(65, 63), + Gate::Xor(56, 65), + Gate::And(58, 67), + Gate::Xor(54, 68), + Gate::Xor(69, 66), + Gate::Xor(58, 62), + Gate::Xor(58, 69), + Gate::Xor(62, 66), + Gate::Xor(71, 70), + Gate::And(73, 20), + Gate::And(66, 22), + Gate::And(62, 7), + Gate::And(72, 28), + Gate::And(69, 13), + Gate::And(58, 25), + Gate::And(71, 24), + Gate::And(74, 26), + Gate::And(70, 23), + Gate::And(73, 15), + Gate::And(66, 18), + Gate::And(62, 14), + Gate::And(72, 9), + Gate::And(69, 17), + Gate::And(58, 16), + Gate::And(71, 10), + Gate::And(74, 8), + Gate::And(70, 11), + Gate::Xor(90, 91), + Gate::Xor(85, 93), + Gate::Xor(84, 94), + Gate::Xor(75, 77), + Gate::Xor(76, 75), + Gate::Xor(78, 79), + Gate::Xor(87, 96), + Gate::Xor(82, 98), + Gate::Xor(83, 99), + Gate::Xor(100, 101), + Gate::Xor(98, 97), + Gate::Xor(78, 80), + Gate::Xor(88, 93), + Gate::Xor(96, 104), + Gate::Xor(95, 103), + Gate::Xor(81, 100), + Gate::Xor(89, 102), + Gate::Xor(105, 106), + Gate::Xnor(87, 110), + Gate::Xor(90, 108), + Gate::Xor(94, 86), + Gate::Xor(95, 108), + Gate::Xnor(102, 110), + Gate::Xor(106, 107), + Gate::Xnor(107, 108), + Gate::Xor(109, 112), + Gate::Xnor(118, 92), + Gate::Xor(113, 109), +]; +const FORWARD_OUTPUTS: [u8; 8] = [114, 117, 119, 107, 116, 120, 115, 111]; + +const INVERSE_GATES: [Gate; 121] = [ + Gate::Xor(0, 3), + Gate::Xnor(1, 3), + Gate::Xor(0, 9), + Gate::Xor(6, 7), + Gate::Xor(9, 11), + Gate::Xnor(2, 12), + Gate::Xor(3, 4), + Gate::Xnor(7, 14), + Gate::Xor(12, 14), + Gate::Xnor(0, 2), + Gate::Xor(5, 17), + Gate::Xor(8, 9), + Gate::Xor(12, 16), + Gate::Xor(10, 15), + Gate::Xor(18, 13), + Gate::Xor(8, 12), + Gate::Xor(9, 16), + Gate::Xor(20, 19), + Gate::Xor(10, 18), + Gate::Xor(15, 13), + Gate::Xor(22, 21), + Gate::Xor(20, 22), + Gate::Xor(24, 27), + Gate::Xor(16, 13), + Gate::Xor(19, 21), + Gate::And(23, 26), + Gate::And(8, 10), + Gate::Xor(29, 33), + Gate::And(12, 18), + Gate::Xor(36, 33), + Gate::And(24, 27), + Gate::And(9, 15), + Gate::Xor(30, 38), + Gate::And(16, 13), + Gate::Xor(41, 38), + Gate::And(20, 22), + Gate::And(25, 28), + Gate::Xor(44, 43), + Gate::And(19, 21), + Gate::Xor(46, 43), + Gate::Xor(35, 34), + Gate::Xor(37, 32), + Gate::Xor(40, 39), + Gate::Xor(42, 47), + Gate::Xor(48, 45), + Gate::Xor(49, 47), + Gate::Xor(50, 45), + Gate::Xor(51, 31), + Gate::Xor(54, 55), + Gate::And(54, 52), + Gate::Xor(53, 57), + Gate::Xor(52, 53), + Gate::Xor(55, 57), + Gate::And(60, 59), + Gate::And(58, 56), + Gate::Xor(55, 62), + Gate::Xor(53, 61), + Gate::And(52, 55), + Gate::And(59, 65), + Gate::Xor(59, 57), + Gate::Xor(66, 67), + Gate::And(53, 54), + Gate::And(56, 69), + Gate::Xor(56, 57), + Gate::Xor(70, 71), + Gate::Xor(68, 72), + Gate::Xor(64, 63), + Gate::Xor(64, 68), + Gate::Xor(63, 72), + Gate::Xor(74, 73), + Gate::And(76, 26), + Gate::And(72, 10), + Gate::And(63, 18), + Gate::And(75, 27), + Gate::And(68, 15), + Gate::And(64, 13), + Gate::And(74, 22), + Gate::And(77, 28), + Gate::And(73, 21), + Gate::And(76, 23), + Gate::And(72, 8), + Gate::And(63, 12), + Gate::And(75, 24), + Gate::And(68, 9), + Gate::And(64, 16), + Gate::And(74, 20), + Gate::And(77, 25), + Gate::And(73, 19), + Gate::Xor(79, 78), + Gate::Xor(80, 78), + Gate::Xor(82, 81), + Gate::Xor(83, 81), + Gate::Xor(85, 84), + Gate::Xor(86, 84), + Gate::Xor(96, 100), + Gate::Xor(97, 101), + Gate::Xor(98, 100), + Gate::Xor(99, 101), + Gate::Xor(88, 87), + Gate::Xor(89, 87), + Gate::Xor(91, 90), + Gate::Xor(92, 90), + Gate::Xor(94, 93), + Gate::Xor(95, 93), + Gate::Xor(106, 110), + Gate::Xor(107, 111), + Gate::Xor(108, 110), + Gate::Xor(109, 111), + Gate::Xor(103, 114), + Gate::Xor(104, 114), + Gate::Xor(105, 114), + Gate::Xor(102, 104), + Gate::Xor(118, 119), + Gate::Xor(112, 115), + Gate::Xor(119, 121), + Gate::Xor(116, 122), + Gate::Xor(103, 113), + Gate::Xor(122, 124), + Gate::Xor(102, 112), + Gate::Xor(120, 124), + Gate::Xor(126, 127), +]; +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); + code.extend([STACK_MODRM_DISP32 | (register << 3), STACK_SIB]); + code.extend((plane as u32 * VECTOR_BYTES).to_le_bytes()); +} + +pub(super) fn emit(code: &mut Vec, inverse: bool) { + let (gates, outputs): (&[Gate], [u8; 8]) = if inverse { + (&INVERSE_GATES, INVERSE_OUTPUTS) + } else { + (&FORWARD_GATES, FORWARD_OUTPUTS) + }; + let frame = (INPUT_PLANES + gates.len()) as u32 * VECTOR_BYTES + SYSV_ENTRY_STACK_MISALIGNMENT; + code.extend(SUB_RSP_IMMEDIATE); + code.extend(frame.to_le_bytes()); + byte_constant(code, MASK, 1); + for input in 0..INPUT_PLANES { + packed(code, Host::MoveAligned, LEFT, RESULT); + let bit = BYTE_BITS - 1 - input as u8; + if bit != 0 { + Shift::RightWord.emit(code, LEFT, bit); + } + packed(code, Host::And, LEFT, MASK); + stack_plane(code, LEFT, input, Host::StoreUnaligned); + } + for (index, gate) in gates.iter().enumerate() { + let (left, right, opcode, invert) = match *gate { + Gate::And(left, right) => (left, right, Host::And, false), + Gate::Xor(left, right) => (left, right, Host::Xor, false), + Gate::Xnor(left, right) => (left, right, Host::Xor, true), + }; + stack_plane(code, LEFT, usize::from(left), Host::LoadUnaligned); + stack_plane(code, LEFT, usize::from(right), opcode); + if invert { + packed(code, Host::Xor, LEFT, MASK); + } + stack_plane(code, LEFT, INPUT_PLANES + index, Host::StoreUnaligned); + } + packed(code, Host::Xor, RESULT, RESULT); + for (output, plane) in outputs.into_iter().enumerate() { + stack_plane(code, LEFT, usize::from(plane), Host::LoadUnaligned); + let bit = BYTE_BITS - 1 - output as u8; + if bit != 0 { + Shift::LeftWord.emit(code, LEFT, bit); + } + packed(code, Host::Or, RESULT, LEFT); + } + code.extend(ADD_RSP_IMMEDIATE); + code.extend(frame.to_le_bytes()); +} diff --git a/crates/stela-compiler/src/x86_64/simd/i8mm.rs b/crates/stela-compiler/src/x86_64/simd/i8mm.rs new file mode 100644 index 0000000000..1b365eb637 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/i8mm.rs @@ -0,0 +1,190 @@ +//! Exact byte dot products and 2x8-by-8x2 matrix accumulation. +use super::{Host, commit, packed, read_vector, shuffle}; +use crate::{ + TargetCpu, + aarch64::simd::{ + arithmetic::Shape, + i8mm::{Kind, Operand}, + }, + x86_64::isa::ShiftOpcode as Shift, +}; + +const LEFT: u8 = 0; +const RIGHT: u8 = 1; +const LEFT_HIGH: u8 = 2; +const RIGHT_HIGH: u8 = 3; +const EXTENSION_MASK: u8 = 4; +const ORIGINAL_LEFT: u8 = 5; +const ORIGINAL_RIGHT: u8 = 6; +// The mask register is dead once operands are widened or the first dot is complete. +const FIRST_HALF_SUM: u8 = EXTENSION_MASK; +const ROW0_COLUMN1_PRODUCTS: u8 = EXTENSION_MASK; +const ROW1_COLUMN1_PRODUCTS: u8 = ORIGINAL_LEFT; +const RESULT: u8 = LEFT; +const OLD_DESTINATION: u8 = RIGHT; +const BYTE_BITS: u8 = 8; +const DOT_GROUP_BROADCAST: u8 = 0x55; +const MATRIX_LEFT_LOW: u8 = 0xa0; // Dwords [0, 0, 2, 2]. +const MATRIX_LEFT_HIGH: u8 = 0xf5; // Dwords [1, 1, 3, 3]. +const MATRIX_RIGHT_LOW: u8 = 0x88; // Dwords [0, 2, 0, 2]. +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) { + packed(code, Host::MoveAligned, LEFT_HIGH, LEFT); + packed(code, Host::MoveAligned, RIGHT_HIGH, RIGHT); + for (low, high, signed) in [ + (LEFT, LEFT_HIGH, left_signed), + (RIGHT, RIGHT_HIGH, right_signed), + ] { + Shift::LeftWord.emit(code, low, BYTE_BITS); + let right = if signed { + Shift::ArithmeticWord + } else { + Shift::RightWord + }; + right.emit(code, low, BYTE_BITS); + right.emit(code, high, BYTE_BITS); + } + packed(code, Host::MultiplyAddWords, LEFT, RIGHT); + packed(code, Host::MultiplyAddWords, LEFT_HIGH, RIGHT_HIGH); + packed(code, Host::AddDword, RESULT, LEFT_HIGH); +} + +fn matrix_sse2(code: &mut Vec, left_signed: bool, right_signed: bool) { + // XMM5/6 retain the original left/right inputs throughout both halves. + shuffle(code, LEFT, ORIGINAL_LEFT, MATRIX_LEFT_LOW); + shuffle(code, RIGHT, ORIGINAL_RIGHT, MATRIX_RIGHT_LOW); + dot_sum(code, left_signed, right_signed); + packed(code, Host::MoveAligned, FIRST_HALF_SUM, RESULT); + shuffle(code, LEFT, ORIGINAL_LEFT, MATRIX_LEFT_HIGH); + shuffle(code, RIGHT, ORIGINAL_RIGHT, MATRIX_RIGHT_HIGH); + dot_sum(code, left_signed, right_signed); + packed(code, Host::AddDword, RESULT, FIRST_HALF_SUM); +} + +fn matrix_ssse3(code: &mut Vec, 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); + for (low, high, signed) in [ + (LEFT, LEFT_HIGH, left_signed), + (RIGHT, RIGHT_HIGH, right_signed), + ] { + packed(code, Host::MoveAligned, high, low); + if signed { + packed(code, Host::GreaterByte, EXTENSION_MASK, low); + } + packed(code, Host::UnpackLowByte, low, EXTENSION_MASK); + packed(code, Host::UnpackHighByte, high, EXTENSION_MASK); + if low == LEFT && signed { + packed(code, Host::Xor, EXTENSION_MASK, EXTENSION_MASK); + } + } + packed(code, Host::MoveAligned, ROW0_COLUMN1_PRODUCTS, LEFT); + packed(code, Host::MoveAligned, ROW1_COLUMN1_PRODUCTS, LEFT_HIGH); + packed(code, Host::MultiplyAddWords, LEFT, RIGHT); // Row 0, column 0. + packed(code, Host::MultiplyAddWords, LEFT_HIGH, RIGHT); // Row 1, column 0. + packed( + code, + Host::MultiplyAddWords, + ROW0_COLUMN1_PRODUCTS, + RIGHT_HIGH, + ); + packed( + code, + Host::MultiplyAddWords, + ROW1_COLUMN1_PRODUCTS, + RIGHT_HIGH, + ); + // First reduce pairs for each row, then produce row-major [00,01,10,11]. + Host::HorizontalAddDword.register(code, LEFT, ROW0_COLUMN1_PRODUCTS, target); + Host::HorizontalAddDword.register(code, LEFT_HIGH, ROW1_COLUMN1_PRODUCTS, target); + Host::HorizontalAddDword.register(code, RESULT, LEFT_HIGH, target); +} + +pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { + let (left_signed, right_signed) = operand.kind.signedness(); + match operand.kind { + Kind::Matrix(_) if target.supports(TargetCpu::Ssse3) => { + read_vector(code, operand.left, LEFT); + read_vector(code, operand.right, RIGHT); + matrix_ssse3(code, left_signed, right_signed, target); + } + Kind::Matrix(_) => { + read_vector(code, operand.left, ORIGINAL_LEFT); + read_vector(code, operand.right, ORIGINAL_RIGHT); + matrix_sse2(code, left_signed, right_signed); + } + Kind::Dot(_) => { + read_vector(code, operand.left, LEFT); + read_vector(code, operand.right, RIGHT); + if let Some(index) = operand.index { + shuffle(code, RIGHT, RIGHT, index * DOT_GROUP_BROADCAST); + } + dot_sum(code, left_signed, right_signed); + } + } + read_vector(code, operand.destination, OLD_DESTINATION); + packed(code, Host::AddDword, RESULT, OLD_DESTINATION); + if operand.shape == Shape::Vector64 { + packed(code, Host::MoveQword, RESULT, RESULT); + } + commit(code, operand.destination, RESULT); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn emitted(word: u32, target: TargetCpu) -> Vec { + let operand = crate::aarch64::simd::i8mm::decode(word).unwrap().unwrap(); + let mut code = Vec::new(); + emit(&mut code, &operand, target); + code + } + + #[test] + fn only_checked_matrix_paths_use_horizontal_add() { + const PHADDD: &[u8] = &[0x66, 0x0f, 0x38, 0x02]; + for word in [0x4e80a400, 0x6e80a400, 0x4e80ac00] { + let baseline = emitted(word, TargetCpu::Baseline); + let checked = emitted(word, TargetCpu::Ssse3); + assert!(!baseline.windows(PHADDD.len()).any(|bytes| bytes == PHADDD)); + assert_eq!( + checked + .windows(PHADDD.len()) + .filter(|bytes| *bytes == PHADDD) + .count(), + 3 + ); + assert!(checked.len() < baseline.len()); + } + for word in [0x0e809c00, 0x0f80f000, 0x0f00f000] { + assert_eq!( + emitted(word, TargetCpu::Baseline), + emitted(word, TargetCpu::Ssse3) + ); + } + } + + #[test] + fn indexed_q0_uses_full_source_and_clears_upper_destination() { + const CLEAR_UPPER: &[u8] = &[0xf3, 0x0f, 0x7e, 0xc0]; + for base in [0x0f80f000, 0x0f00f000] { + for index in 0..4 { + let word = base | 31 << 16 | 31 << 5 | 31 | (index & 1) << 21 | (index >> 1) << 11; + let low = emitted(word, TargetCpu::Baseline); + let full = emitted(word | 1 << 30, TargetCpu::Baseline); + assert!( + low.windows(5).any(|bytes| bytes + == [0x66, 0x0f, 0x70, 0xc9, index as u8 * DOT_GROUP_BROADCAST]) + ); + assert!(low.windows(4).any(|bytes| bytes == CLEAR_UPPER)); + assert!(!full.windows(4).any(|bytes| bytes == CLEAR_UPPER)); + } + } + } +} diff --git a/crates/stela-compiler/src/x86_64/simd/sha1.rs b/crates/stela-compiler/src/x86_64/simd/sha1.rs new file mode 100644 index 0000000000..a70dcce8ce --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/sha1.rs @@ -0,0 +1,194 @@ +//! SHA1 instructions: scalar integer rounds, SSE2 schedule and checked Intel SHA. +//! All inputs are consumed before the single vector commit, including aliases. +use super::sha32::{ + HIGH_WORD_BYTE, RESULT, Rotate32, Scalar32, WORD_BITS, WORD_BYTES, WORDS_PER_VECTOR, + move_to_vector, pack_state, read_scalar_vector, +}; +use super::{Host, commit, packed, read_vector, shuffle}; +use crate::{ + TargetCpu, + aarch64::simd::sha1::{Kind, Operand}, + x86_64::isa::ShiftOpcode as Shift, +}; + +const EAX: u8 = 0; +const ECX: u8 = 1; +const EDX: u8 = 2; +const ESI: u8 = 6; +const R8D: u8 = 8; +const R9D: u8 = 9; +const R10D: u8 = 10; +const R11D: u8 = 11; +const LEFT: u8 = 1; +const RIGHT: u8 = 2; +const TEMPORARY: u8 = 3; +const LOW_WORD: u8 = 0; +const HASH_E_INDEX: usize = WORDS_PER_VECTOR; +const HASH_A_ROTATE: u8 = 5; +const HASH_B_ROTATE: u8 = 30; +const HASH_E_ROTATE_RIGHT: u8 = 2; +const SCHEDULE_ROTATE: u8 = 1; +const SCHEDULE_FEEDBACK_ROTATE: u8 = 2; +const CHOOSE_FUNCTION: u8 = 0; +const PARITY_FUNCTION: u8 = 1; +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) { + use Scalar32::*; + let mut state = [EAX, ECX, EDX, ESI, R8D]; + for (lane, register) in state[..WORDS_PER_VECTOR].iter().enumerate() { + Move.state(code, *register, operand.destination, lane as u8); + } + Move.state(code, state[HASH_E_INDEX], operand.left, LOW_WORD); + for lane in 0..WORDS_PER_VECTOR as u8 { + let [a, b, c, d, e] = state; + match operand.kind { + Kind::Choose => { + Move.register(code, R10D, c); + Xor.register(code, R10D, d); + And.register(code, R10D, b); + Xor.register(code, R10D, d); + } + Kind::Parity => { + Move.register(code, R10D, b); + Xor.register(code, R10D, c); + Xor.register(code, R10D, d); + } + Kind::Majority => { + Move.register(code, R10D, b); + And.register(code, R10D, c); + Move.register(code, R11D, b); + Or.register(code, R11D, c); + And.register(code, R11D, d); + Or.register(code, R10D, R11D); + } + _ => unreachable!("SHA1 hash update kind"), + } + Move.register(code, R9D, a); + Rotate32::Left.emit(code, R9D, HASH_A_ROTATE); + Add.register(code, e, R9D); + Add.register(code, e, R10D); + // No guest state is written until every original message lane is read. + Add.state(code, e, operand.right, lane); + Rotate32::Left.emit(code, b, HASH_B_ROTATE); + state = [e, a, b, c, d]; + } + pack_state(code, [state[0], state[1], state[2], state[3]]); +} + +fn rounds_sha(code: &mut Vec, operand: &Operand, target: TargetCpu) { + let (function, constant) = match operand.kind { + Kind::Choose => (CHOOSE_FUNCTION, CHOOSE_CONSTANT), + Kind::Parity => (PARITY_FUNCTION, PARITY_CONSTANT), + Kind::Majority => (MAJORITY_FUNCTION, MAJORITY_CONSTANT), + _ => unreachable!("SHA1 hash update kind"), + }; + read_vector(code, operand.destination, RESULT); + read_vector(code, operand.right, RIGHT); + // 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()); + 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); + shuffle(code, RESULT, RESULT, REVERSE_DWORDS); +} + +fn schedule0(code: &mut Vec, operand: &Operand) { + read_vector(code, operand.destination, RESULT); + read_vector(code, operand.left, LEFT); + read_vector(code, operand.right, RIGHT); + // [d2,d3,n0,n1] XOR d XOR m, low lane first. + shuffle(code, TEMPORARY, RESULT, SWAP_QWORDS); + packed(code, Host::UnpackLowQword, TEMPORARY, LEFT); + packed(code, Host::Xor, RESULT, TEMPORARY); + packed(code, Host::Xor, RESULT, RIGHT); +} +fn rotate_lanes(code: &mut Vec, 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) { + read_vector(code, operand.destination, RESULT); + read_vector(code, operand.left, LEFT); + if target.supports(TargetCpu::Sha) { + shuffle(code, RESULT, RESULT, REVERSE_DWORDS); + shuffle(code, LEFT, LEFT, REVERSE_DWORDS); + Host::Sha1Message2.register(code, RESULT, LEFT, target); + shuffle(code, RESULT, RESULT, REVERSE_DWORDS); + } else { + Shift::RightBytes.emit(code, LEFT, WORD_BYTES); + packed(code, Host::Xor, RESULT, LEFT); + packed(code, Host::MoveAligned, RIGHT, RESULT); + Shift::LeftBytes.emit(code, RIGHT, HIGH_WORD_BYTE); // T0 only, in the high result lane + rotate_lanes(code, RIGHT, TEMPORARY, SCHEDULE_FEEDBACK_ROTATE); + rotate_lanes(code, RESULT, LEFT, SCHEDULE_ROTATE); + packed(code, Host::Xor, RESULT, RIGHT); + } +} + +pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { + match operand.kind { + Kind::Choose | Kind::Parity | Kind::Majority => { + if target.supports(TargetCpu::Sha) { + rounds_sha(code, operand, target); + } else { + rounds_baseline(code, operand); + } + } + Kind::Rotate => { + Scalar32::Move.state(code, EAX, operand.left, LOW_WORD); + Rotate32::Right.emit(code, EAX, HASH_E_ROTATE_RIGHT); + move_to_vector(code, RESULT, EAX); // clears destination bits 127:32 + } + Kind::Schedule0 => schedule0(code, operand), + Kind::Schedule1 => schedule1(code, operand, target), + } + commit(code, operand.destination, RESULT); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn baseline_has_no_sha_and_checked_rounds_cancel_the_selected_constant() { + for (kind, constant) in [ + (Kind::Choose, CHOOSE_CONSTANT), + (Kind::Parity, PARITY_CONSTANT), + (Kind::Majority, MAJORITY_CONSTANT), + ] { + let operand = Operand { + kind, + destination: 31, + left: 31, + right: 31, + }; + let mut baseline = Vec::new(); + emit(&mut baseline, &operand, TargetCpu::Baseline); + assert!(!baseline.windows(3).any(|w| w == [0x0f, 0x3a, 0xcc])); + let mut checked = Vec::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())); + assert!(checked.windows(3).any(|w| w == Host::SubDword.encoding())); + } + } +} diff --git a/crates/stela-compiler/src/x86_64/simd/sha256.rs b/crates/stela-compiler/src/x86_64/simd/sha256.rs new file mode 100644 index 0000000000..815a91fafb --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/sha256.rs @@ -0,0 +1,298 @@ +//! SHA256 instructions: integer rounds, SSE2 schedule, checked Intel SHA. +//! H/H2 each execute all four rounds and commit only their own selected half. +use super::sha32::{ + DOUBLE_WORD_BYTES, HIGH_WORD_BYTE, RESULT, Rotate32, Scalar32, WORD_BITS, WORD_BYTES, + WORDS_PER_VECTOR, pack_state, +}; +use super::{Host, commit, packed, read_vector, shuffle}; +use crate::{ + TargetCpu, + aarch64::simd::sha256::{Kind, Operand}, + x86_64::isa::ShiftOpcode as Shift, +}; + +const EAX: u8 = 0; +const ECX: u8 = 1; +const EDX: u8 = 2; +const EBX: u8 = 3; +const EBP: u8 = 5; +const ESI: u8 = 6; +const R8D: u8 = 8; +const R9D: u8 = 9; +const R10D: u8 = 10; +const R11D: u8 = 11; +const R12D: u8 = 12; +const LEFT: u8 = 1; +const RIGHT: u8 = 2; +const TEMPORARY: u8 = 3; +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) { + // 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 + } else { + MOVQ_XMM_RM64 + }); + code.push(MODRM_REGISTER | (xmm << MODRM_REGISTER_SHIFT) | (register & LOW_REGISTER_MASK)); + } +} +fn big_sigma(code: &mut Vec, 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..] { + Scalar32::Move.register(code, temporary, input); + Rotate32::Right.emit(code, temporary, *amount); + Scalar32::Xor.register(code, result, temporary); + } +} +fn rounds_baseline(code: &mut Vec, operand: &Operand) { + use Scalar32::*; + preserve_scratch(code, false); + let (x, y) = if operand.kind == Kind::Hash { + (operand.destination, operand.left) + } else { + (operand.left, operand.destination) + }; + let mut state = [EAX, ECX, EDX, ESI, R8D, R9D, R10D, R11D]; + for (index, register) in state.iter().enumerate() { + Move.state( + code, + *register, + if index < WORDS_PER_VECTOR { x } else { y }, + (index % WORDS_PER_VECTOR) as u8, + ); + } + for lane in 0..WORDS_PER_VECTOR as u8 { + let [a, b, c, d, e, f, g, h] = state; + big_sigma(code, e, EBX, EBP, BIG_SIGMA1); + Move.register(code, EBP, f); + Xor.register(code, EBP, g); + And.register(code, EBP, e); + Xor.register(code, EBP, g); + Add.register(code, EBX, EBP); + Add.register(code, EBX, h); + Add.state(code, EBX, operand.right, lane); + Add.register(code, d, EBX); // new E; the original D is now consumed + big_sigma(code, a, EBP, R12D, BIG_SIGMA0); + Add.register(code, EBX, EBP); + Move.register(code, R12D, a); + And.register(code, R12D, b); + Move.register(code, EBP, a); + Or.register(code, EBP, b); + And.register(code, EBP, c); + Or.register(code, EBP, R12D); + Add.register(code, EBX, EBP); + Move.register(code, h, EBX); // new A; the original H is now consumed + state = [h, a, b, c, d, e, f, g]; + } + let part = if operand.kind == Kind::Hash { + &state[..WORDS_PER_VECTOR] + } else { + &state[WORDS_PER_VECTOR..] + }; + 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) { + let (x, y) = if operand.kind == Kind::Hash { + (operand.destination, operand.left) + } else { + (operand.left, operand.destination) + }; + read_vector(code, x, LEFT); + read_vector(code, y, RIGHT); + read_vector(code, operand.right, RESULT); // RNDS2's implicit WK input + shuffle(code, LEFT, LEFT, REVERSE_DWORDS); // [D,C,B,A] + shuffle(code, RIGHT, RIGHT, REVERSE_DWORDS); // [H,G,F,E] + packed(code, Host::MoveAligned, TEMPORARY, RIGHT); + packed(code, Host::UnpackHighQword, TEMPORARY, LEFT); // [F,E,B,A] + packed(code, Host::UnpackLowQword, RIGHT, LEFT); // [H,G,D,C] + Host::Sha256Rounds2.register(code, RIGHT, TEMPORARY, target); + Shift::RightBytes.emit(code, RESULT, DOUBLE_WORD_BYTES); + Host::Sha256Rounds2.register(code, TEMPORARY, RIGHT, target); + packed( + code, + if operand.kind == Kind::Hash { + Host::UnpackHighQword + } else { + Host::UnpackLowQword + }, + TEMPORARY, + RIGHT, + ); + shuffle(code, RESULT, TEMPORARY, REVERSE_DWORD_PAIRS); +} + +fn small_sigma(code: &mut Vec, 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); + Shift::RightDword.emit(code, result, amounts[0]); + packed(code, Host::MoveAligned, temporary, input); + Shift::LeftDword.emit(code, temporary, WORD_BITS - amounts[0]); + packed(code, Host::Xor, result, temporary); + for (shift, amount) in [ + (Shift::RightDword, amounts[1]), + (Shift::LeftDword, WORD_BITS - amounts[1]), + ] { + packed(code, Host::MoveAligned, temporary, input); + shift.emit(code, temporary, amount); + packed(code, Host::Xor, result, temporary); + } + Shift::RightDword.emit(code, input, amounts[2]); + packed(code, Host::Xor, result, input); +} +fn schedule0(code: &mut Vec, operand: &Operand, target: TargetCpu) { + read_vector(code, operand.destination, RESULT); + read_vector(code, operand.left, LEFT); + if target.supports(TargetCpu::Sha) { + Host::Sha256Message1.register(code, RESULT, LEFT, target); + } 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] + } else { + packed(code, Host::MoveAligned, RIGHT, RESULT); + Shift::RightBytes.emit(code, RIGHT, WORD_BYTES); + Shift::LeftBytes.emit(code, LEFT, HIGH_WORD_BYTE); + packed(code, Host::Or, RIGHT, LEFT); + } + small_sigma(code, RIGHT, TEMPORARY, SIGMA_TEMPORARY, SMALL_SIGMA0); + packed(code, Host::AddDword, RESULT, TEMPORARY); + } +} +fn schedule1(code: &mut Vec, 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 original 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] + packed(code, Host::AddDword, RESULT, TEMPORARY); + } else { + Shift::RightBytes.emit(code, LEFT, WORD_BYTES); + packed(code, Host::MoveAligned, TEMPORARY, RIGHT); + Shift::LeftBytes.emit(code, TEMPORARY, HIGH_WORD_BYTE); + packed(code, Host::Or, LEFT, TEMPORARY); + packed(code, Host::AddDword, RESULT, LEFT); + } + if target.supports(TargetCpu::Sha) { + Host::Sha256Message2.register(code, RESULT, RIGHT, target); + } else { + Shift::RightBytes.emit(code, RIGHT, DOUBLE_WORD_BYTES); + small_sigma(code, RIGHT, TEMPORARY, SIGMA_TEMPORARY, SMALL_SIGMA1); // [sigma1(m2),sigma1(m3),0,0] + packed(code, Host::AddDword, RESULT, TEMPORARY); + packed(code, Host::MoveAligned, RIGHT, RESULT); + Shift::LeftBytes.emit(code, RIGHT, DOUBLE_WORD_BYTES); // [0,0,result0,result1] + small_sigma(code, RIGHT, TEMPORARY, SIGMA_TEMPORARY, SMALL_SIGMA1); + packed(code, Host::AddDword, RESULT, TEMPORARY); + } +} + +pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { + match operand.kind { + Kind::Hash | Kind::Hash2 => { + if target.supports(TargetCpu::Sha) { + rounds_sha(code, operand, target); + } else { + rounds_baseline(code, operand); + } + } + Kind::Schedule0 => schedule0(code, operand, target), + Kind::Schedule1 => schedule1(code, operand, target), + } + commit(code, operand.destination, RESULT); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn schedule_gathers_require_ssse3_independently_of_sha() { + for target in [ + TargetCpu::Baseline, + TargetCpu::Ssse3, + TargetCpu::Sha, + TargetCpu::Ssse3.with_sha(), + ] { + for kind in [Kind::Schedule0, Kind::Schedule1] { + let operand = Operand { + kind, + destination: 31, + left: 31, + right: 31, + }; + let mut code = Vec::new(); + emit(&mut code, &operand, target); + let alignment = Host::AlignBytes.encoding(); + let used = code + .windows(alignment.len()) + .any(|bytes| bytes == alignment); + let expected = target.supports(TargetCpu::Ssse3) + && (kind == Kind::Schedule1 || !target.supports(TargetCpu::Sha)); + assert_eq!(used, expected); + } + } + } + + #[test] + fn checked_hash_uses_two_round_pairs_with_explicit_implicit_input_staging() { + for kind in [Kind::Hash, Kind::Hash2] { + let operand = Operand { + kind, + destination: 31, + left: 31, + right: 31, + }; + let mut code = Vec::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(); + 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)); + } + } + } + } +} diff --git a/crates/stela-compiler/src/x86_64/simd/sha3.rs b/crates/stela-compiler/src/x86_64/simd/sha3.rs new file mode 100644 index 0000000000..fb0b52b2db --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/sha3.rs @@ -0,0 +1,119 @@ +//! SSE2 lowering for classic SHA3 logical forms. Source state is read completely +//! before the single destination commit, including every legal operand alias. +use super::{Host, commit, packed, read_vector}; +use crate::{ + aarch64::simd::sha3::{Kind, Operand}, + x86_64::isa::ShiftOpcode, +}; + +const RESULT: u8 = 0; +const SECOND: u8 = 1; +const TEMPORARY: u8 = 2; +const WORD_BITS: u8 = 16; +const DWORD_BITS: u8 = 32; +const QWORD_BITS: u8 = 64; +const NO_ROTATION: u8 = 0; +const ROTATE_RIGHT_THREE_WORDS: u8 = 3 * WORD_BITS; +const ROTATE_LEFT_ONE: u8 = 1; +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) { + match rotation { + NO_ROTATION => {} + DWORD_BITS => { + packed(code, Host::ShuffleDword, RESULT, RESULT); + code.push(SWAP_DWORDS_IN_QWORDS); + } + WORD_BITS | ROTATE_RIGHT_THREE_WORDS => { + let selector = if rotation == WORD_BITS { + ROTATE_WORDS_RIGHT_ONE + } else { + ROTATE_WORDS_RIGHT_THREE + }; + for opcode in [Host::ShuffleLowWord, Host::ShuffleHighWord] { + packed(code, opcode, RESULT, RESULT); + code.push(selector); + } + } + _ => { + packed(code, Host::MoveAligned, TEMPORARY, RESULT); + ShiftOpcode::RightQword.emit(code, RESULT, rotation); + ShiftOpcode::LeftQword.emit(code, TEMPORARY, QWORD_BITS - rotation); + packed(code, Host::Or, RESULT, TEMPORARY); + } + } +} + +pub(super) fn emit(code: &mut Vec, operand: &Operand) { + match operand.kind { + Kind::Eor3 { third } => { + read_vector(code, operand.left, RESULT); + read_vector(code, operand.right, SECOND); + read_vector(code, third, TEMPORARY); + packed(code, Host::Xor, RESULT, SECOND); + packed(code, Host::Xor, RESULT, TEMPORARY); + } + Kind::Bcax { third } => { + // PANDN complements its destination: ~Va & Vm, then XOR Vn. + read_vector(code, third, RESULT); + read_vector(code, operand.right, SECOND); + read_vector(code, operand.left, TEMPORARY); + packed(code, Host::AndNot, RESULT, SECOND); + packed(code, Host::Xor, RESULT, TEMPORARY); + } + Kind::Rax1 => { + read_vector(code, operand.right, RESULT); + read_vector(code, operand.left, SECOND); + packed(code, Host::MoveAligned, TEMPORARY, RESULT); + ShiftOpcode::RightQword.emit(code, TEMPORARY, QWORD_BITS - ROTATE_LEFT_ONE); + // m+m is m<<1 modulo each64; the separately shifted top bit wraps. + packed(code, Host::AddQword, RESULT, RESULT); + packed(code, Host::Or, RESULT, TEMPORARY); + packed(code, Host::Xor, RESULT, SECOND); + } + Kind::Xar { rotation } => { + read_vector(code, operand.left, RESULT); + read_vector(code, operand.right, SECOND); + packed(code, Host::Xor, RESULT, SECOND); + rotate_right(code, rotation); + } + } + commit(code, operand.destination, RESULT); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn staging_cost_accounts_for_complete_state_access_and_immediate_specializations() { + for (kind, expected_bytes) in [ + (Kind::Eor3 { third: 31 }, 40), + (Kind::Bcax { third: 31 }, 40), + (Kind::Rax1, 45), + (Kind::Xar { rotation: 0 }, 28), + (Kind::Xar { rotation: 16 }, 38), + (Kind::Xar { rotation: 32 }, 33), + (Kind::Xar { rotation: 48 }, 38), + (Kind::Xar { rotation: 63 }, 46), + ] { + let mut code = Vec::new(); + emit( + &mut code, + &Operand { + kind, + destination: 31, + left: 31, + right: 31, + }, + ); + assert_eq!(code.len(), expected_bytes, "{kind:?}"); + // MOVDQU is the sole architectural commit and writes all V31 bits. + let mut expected_store = vec![0xf3, 0x0f, 0x7f, 0x87]; + expected_store.extend(super::super::vector_offset(31).to_le_bytes()); + assert!(code.ends_with(&expected_store), "{kind:?}"); + } + } +} diff --git a/crates/stela-compiler/src/x86_64/simd/sha32.rs b/crates/stela-compiler/src/x86_64/simd/sha32.rs new file mode 100644 index 0000000000..d274d92f84 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/sha32.rs @@ -0,0 +1,114 @@ +//! Exact 32-bit encoders shared by the classic SHA1/SHA256 recipes. +//! This is a fixed GuestState/legacy-XMM boundary, not a general assembler. +use super::{Host, packed, vector_offset}; + +pub(super) const WORD_BITS: u8 = 32; +pub(super) const WORD_BYTES: u8 = WORD_BITS / 8; +pub(super) const WORDS_PER_VECTOR: usize = 4; +pub(super) const DOUBLE_WORD_BYTES: u8 = WORD_BYTES * 2; +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 { + Move, + Add, + Xor, + And, + Or, +} +impl Scalar32 { + fn opcode(self) -> u8 { + match self { + Self::Move => 0x8b, + Self::Add => 0x03, + Self::Xor => 0x33, + Self::And => 0x23, + Self::Or => 0x0b, + } + } + 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 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) enum Rotate32 { + Left, + 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, + }; + code.extend([ + ROTATE_IMMEDIATE, + MODRM_REGISTER | (group << MODRM_REGISTER_SHIFT) | (register & LOW_REGISTER_MASK), + 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 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()); +} +/// 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]) { + move_to_vector(code, RESULT, words[0]); + move_to_vector(code, PACK_PAIR, words[1]); + packed(code, Host::UnpackLowDword, RESULT, PACK_PAIR); + move_to_vector(code, PACK_PAIR, words[2]); + move_to_vector(code, PACK_LAST, words[3]); + packed(code, Host::UnpackLowDword, PACK_PAIR, PACK_LAST); + packed(code, Host::UnpackLowQword, 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 new file mode 100644 index 0000000000..63bc0de522 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/sha512.rs @@ -0,0 +1,288 @@ +//! Individual SHA512 instructions: scalar large sigmas and packed small sigmas. +//! Integer-only recipes preserve guest NZCV/FPCR/FPSR and caller MXCSR. +use super::{Host, commit, packed, read_vector, shuffle, vector_offset}; +use crate::{ + TargetCpu, + aarch64::simd::sha512::{Kind, Operand}, + x86_64::isa::ShiftOpcode as Shift, +}; + +const QWORD_BITS: u8 = 64; +const QWORD_BYTES: u32 = 8; +const LOW: u32 = 0; +const HIGH: u32 = 1; +const SWAP_QWORDS: u8 = 0x4e; +const OLD_DESTINATION_XMM: u8 = 0; +const SECOND_SOURCE_XMM: u8 = 1; +const SIGMA_INPUT_XMM: u8 = 2; +const SIGMA_OUTPUT_XMM: u8 = 3; +const ROTATE_SCRATCH_XMM: u8 = 4; +const SECOND_ROTATE_XMM: u8 = 5; +const SMALL_SIGMA0_ROTATIONS: [u8; 2] = [1, 8]; +const SMALL_SIGMA0_SHIFT: u8 = 7; +const SMALL_SIGMA1_ROTATIONS: [u8; 2] = [19, 61]; +const SMALL_SIGMA1_SHIFT: u8 = 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; +const X1: Gpr = Gpr::Rsi; +const Y0: Gpr = Gpr::R8; +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. +#[derive(Clone, Copy)] +#[repr(u8)] +enum QwordOpcode { + Add = 0x01, + Or = 0x09, + And = 0x21, + Xor = 0x31, + Move = 0x89, +} + +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 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 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 large_sigma( + code: &mut Vec, + destination: Gpr, + source: Gpr, + scratch: [Gpr; 2], + rotations: [u8; 3], +) { + // Independent rotates expose parallel work. Callers reuse dead original + // inputs, keeping every state access and avoiding spills or extra features. + let [first, second] = scratch; + let [low, middle, high] = rotations; + QwordOpcode::Move.emit(code, destination, source); + QwordOpcode::Move.emit(code, first, source); + QwordOpcode::Move.emit(code, second, source); + rotate(code, destination, low); + rotate(code, first, middle); + rotate(code, second, high); + QwordOpcode::Xor.emit(code, destination, first); + QwordOpcode::Xor.emit(code, destination, second); +} + +fn choose(code: &mut Vec, 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) { + QwordOpcode::Move.emit(code, destination, x); + QwordOpcode::And.emit(code, destination, y); + QwordOpcode::Move.emit(code, scratch, x); + QwordOpcode::Or.emit(code, scratch, y); + QwordOpcode::And.emit(code, scratch, z); + QwordOpcode::Or.emit(code, destination, scratch); +} + +fn hash(code: &mut Vec, operand: &Operand, second: bool) { + let right = operand.right.expect("three-register SHA512 hash form"); + // Stage every required original qword before either destination store. + // The high result may then be stored before low-result computation, even + // when all three guest register names alias. No guest memory is accessed. + for (vector, lane, register) in [ + (operand.destination, LOW, W0), + (operand.destination, HIGH, W1), + (operand.left, LOW, X0), + (right, LOW, Y0), + (right, HIGH, Y1), + ] { + state_qword(code, vector, lane, register, true); + } + if second { + majority(code, VALUE, SIGMA, X0, Y1, Y0); + // X0 is dead after majority; X1 is unused by the guest H2 form. + large_sigma(code, SIGMA, Y0, [X0, X1], LARGE_SIGMA0_ROTATIONS); + } else { + state_qword(code, operand.left, HIGH, X1, true); + choose(code, VALUE, Y1, X0, X1); + // Consume old W1 before sigma so its register and dead X1 can hold + // independent rotations. Modular addition preserves the original sum. + QwordOpcode::Add.emit(code, VALUE, W1); + large_sigma(code, SIGMA, Y1, [X1, W1], LARGE_SIGMA1_ROTATIONS); + } + QwordOpcode::Add.emit(code, VALUE, SIGMA); + if second { + QwordOpcode::Add.emit(code, VALUE, W1); + } + state_qword(code, operand.destination, HIGH, VALUE, false); + + if second { + large_sigma(code, SIGMA, VALUE, [X0, X1], LARGE_SIGMA0_ROTATIONS); + // W1 and X0 are dead original inputs. Keep VALUE as the sigma source + // until sigma completes, then use it as the first majority operand. + majority(code, W1, X0, VALUE, Y0, Y1); + QwordOpcode::Add.emit(code, W1, SIGMA); + QwordOpcode::Add.emit(code, W1, W0); + state_qword(code, operand.destination, LOW, W1, false); + } else { + QwordOpcode::Add.emit(code, VALUE, Y0); + choose(code, SIGMA, VALUE, Y1, X0); + // Y0 is dead after forming VALUE, and X1 was consumed by the first Ch. + large_sigma(code, W1, VALUE, [X1, Y0], LARGE_SIGMA1_ROTATIONS); + QwordOpcode::Add.emit(code, SIGMA, W1); + QwordOpcode::Add.emit(code, SIGMA, W0); + state_qword(code, operand.destination, LOW, SIGMA, false); + } +} + +fn packed_rotate(code: &mut Vec, 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); + Shift::LeftQword.emit(code, scratch, QWORD_BITS - amount); + packed(code, Host::Or, destination, scratch); +} + +fn small_sigma(code: &mut Vec, rotations: [u8; 2], shift: u8) { + // XMM2 holds both independent sigma inputs. XMM0/1 retain old W/Y. + packed_rotate( + code, + SIGMA_OUTPUT_XMM, + ROTATE_SCRATCH_XMM, + SIGMA_INPUT_XMM, + rotations[0], + ); + packed_rotate( + code, + SECOND_ROTATE_XMM, + ROTATE_SCRATCH_XMM, + SIGMA_INPUT_XMM, + rotations[1], + ); + packed(code, Host::Xor, SIGMA_OUTPUT_XMM, SECOND_ROTATE_XMM); + Shift::RightQword.emit(code, SIGMA_INPUT_XMM, shift); + packed(code, Host::Xor, SIGMA_OUTPUT_XMM, SIGMA_INPUT_XMM); +} + +pub(super) fn emit(code: &mut Vec, operand: &Operand, _target: TargetCpu) { + match operand.kind { + Kind::Hash | Kind::Hash2 => hash(code, operand, operand.kind == Kind::Hash2), + Kind::Schedule0 => { + read_vector(code, operand.destination, OLD_DESTINATION_XMM); + read_vector(code, operand.left, SECOND_SOURCE_XMM); + shuffle(code, SIGMA_INPUT_XMM, OLD_DESTINATION_XMM, SWAP_QWORDS); + packed( + code, + Host::UnpackLowQword, + SIGMA_INPUT_XMM, + SECOND_SOURCE_XMM, + ); // [old W1, old X0] + small_sigma(code, SMALL_SIGMA0_ROTATIONS, SMALL_SIGMA0_SHIFT); + packed(code, Host::AddQword, OLD_DESTINATION_XMM, SIGMA_OUTPUT_XMM); + commit(code, operand.destination, OLD_DESTINATION_XMM); + } + Kind::Schedule1 => { + read_vector(code, operand.destination, OLD_DESTINATION_XMM); + read_vector( + code, + operand.right.expect("three-register SHA512SU1 form"), + SECOND_SOURCE_XMM, + ); + read_vector(code, operand.left, SIGMA_INPUT_XMM); + small_sigma(code, SMALL_SIGMA1_ROTATIONS, SMALL_SIGMA1_SHIFT); + packed(code, Host::AddQword, OLD_DESTINATION_XMM, SECOND_SOURCE_XMM); + packed(code, Host::AddQword, OLD_DESTINATION_XMM, SIGMA_OUTPUT_XMM); + commit(code, operand.destination, OLD_DESTINATION_XMM); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scoped_qword_encodings_keep_rex_operand_roles_and_state_base() { + let mut code = Vec::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); + state_qword(&mut code, 31, HIGH, Gpr::R9, true); + state_qword(&mut code, 31, LOW, Gpr::R10, false); + let high = (vector_offset(31) + QWORD_BYTES).to_le_bytes(); + let low = vector_offset(31).to_le_bytes(); + assert_eq!( + code, + [ + &[0x49, 0x89, 0xd2][..], // mov r10,rdx + &[0x4d, 0x21, 0xca], // and r10,r9 + &[0x49, 0xc1, 0xcb, 23], // ror r11,23 + &[0x4c, 0x8b, 0x8f], + &high, + &[0x4c, 0x89, 0x97], + &low, + ] + .concat() + ); + } +} diff --git a/crates/stela-runtime/src/lib.rs b/crates/stela-runtime/src/lib.rs index 83d096e1ca..25c58331b0 100644 --- a/crates/stela-runtime/src/lib.rs +++ b/crates/stela-runtime/src/lib.rs @@ -107,7 +107,7 @@ pub fn prepare_leaf_for_target( compiler_source_sha256: sha256(stela_compiler::SOURCE_FINGERPRINT_MATERIAL.as_bytes()), guest_base: base.0, abi: NATIVE_ABI.into(), - target_cpu: target.id().into(), + target_cpu: target.id(), }; prepare(identity, root, || { stela_compiler::compile_for_target(source, base, target) @@ -163,7 +163,7 @@ pub fn prepare_block_for_target( compiler_source_sha256: sha256(stela_compiler::SOURCE_FINGERPRINT_MATERIAL.as_bytes()), guest_base: base.0, abi: profile.abi().into(), - target_cpu: target.id().into(), + target_cpu: target.id(), }; let prepared = prepare(identity, root, || { block::compile_for_target(prefix, base, profile, target).map(|b| b.native) @@ -292,6 +292,49 @@ mod tests { Ok(()) } #[test] + fn independent_cpu_requirements_have_distinct_cache_identities() -> Result<()> { + use stela_compiler::TargetCpu; + let root = tempfile::tempdir()?; + let input = source(42); + let mut keys = std::collections::BTreeSet::new(); + for target in [ + TargetCpu::Baseline, + TargetCpu::Popcnt, + TargetCpu::Bmi1, + TargetCpu::Aes, + TargetCpu::Sha, + TargetCpu::Baseline.with_popcnt().with_bmi1(), + TargetCpu::Baseline.with_aes().with_sha(), + TargetCpu::Sse42 + .with_pclmulqdq() + .with_fma() + .with_f16c() + .with_popcnt() + .with_bmi1() + .with_aes() + .with_sha(), + ] { + let artifact = + prepare_leaf_for_target(&input, GuestAddress(0x1000), root.path(), target)?; + assert_eq!(artifact.manifest.identity.target_cpu, target.id()); + assert_eq!( + artifact + .manifest + .identity + .target_cpu + .parse::() + .unwrap(), + target + ); + assert!(keys.insert(artifact.key)); + assert!( + prepare_leaf_for_target(&input, GuestAddress(0x1000), root.path(), target)? + .cache_hit + ); + } + Ok(()) + } + #[test] fn clock_profile_cache_isolated_from_both_previous_profiles_and_exact_operands() -> Result<()> { use stela_compiler::block::BlockProfile; let root = tempfile::tempdir()?; diff --git a/dev/integer-math-differential.py b/dev/integer-math-differential.py index 329a979b83..bceba30620 100644 --- a/dev/integer-math-differential.py +++ b/dev/integer-math-differential.py @@ -442,7 +442,7 @@ def bounded_cases(compiled): receive.close() -def unary_blocks(cli, directory, forms=UNARY_FORMS, target='native'): +def unary_blocks(cli, directory, forms=UNARY_FORMS, target='native', fixtures=None): """Unchanged ARM RET and native shared block dispatch, with disk reuse.""" from differential import initialize_arm, capture_arm, seed_extended_state from unicorn import Uc, UC_ARCH_ARM64, UC_MODE_ARM @@ -450,26 +450,53 @@ def unary_blocks(cli, directory, forms=UNARY_FORMS, target='native'): base, stop = 0x100000, 0x100800 source, state_path = directory / 'unary.arm64', directory / 'unary-state.json' rows = [] - incoming = states(all_flags=True)[:16] + incoming = states(all_flags=True)[:16 if fixtures is None else 3] for form in forms: - words = [encoding(form, 0, 1, 2), RET] - code = struct.pack('<2I', *words) + operations = None if fixtures is None else fixtures[form] + words = ([encoding(form, 0, 1, 2)] if operations is None else + [operation['word'] for operation in operations]) + [RET] + code = struct.pack('<' + 'I' * len(words), *words) source.write_bytes(code) for flag, template in enumerate(incoming): initial = State.from_buffer_copy(template) - seed_extended_state(initial, (flag + FORMS[form]).to_bytes(8, 'little')) + seed_extended_state(initial, (flag + forms[form]).to_bytes(8, 'little')) initial.nzcv = flag << 28 initial.x[1] = (0, MASK, 1 << 63, 0x0123456789abcdef)[flag % 4] initial.x[30] = stop - expected = mathematical_reference(words, initial) + if operations is None: + expected = mathematical_reference(words, initial) + original_initial, original_code, original_start = initial, code, base + else: + initial.nzcv = (0, 7, 15)[flag] << 28 + initial.fpcr = (0, CSSC_READABLE_FPCR, CSSC_TRAP_ENABLES | CSSC_NEP)[flag] + expected = cssc_mathematical_reference(operations, initial) + # The primary QEMU capture proves CSSC separately. Unicorn can + # execute the unchanged RET from the model's post-CSSC state, + # under compatible controls; this is no joined-original claim. + original_initial = State.from_buffer_copy(initial) + original_initial.x[:] = expected['x'] + original_initial.fpcr &= CSSC_RET_COMPATIBLE_FPCR + original_code, original_start = struct.pack('> 28, 'target': target, + 'expected_integer_model': expected, 'native': native, + 'budget0_stop': budget_stop, 'original_ret_only': original_ret, + 'original_cssc_joined': False}) return rows @@ -767,15 +801,471 @@ def crc_mapping_benchmark(cli): print(json.dumps({'snapshot': str(snapshot), 'rows': len(rows), 'passed': True})) +# Add before main() in dev/integer-math-differential.py. Historical cases(), +# FORMS, mathematical_reference() and default execution stay byte-identical. +CSSC_BATCH_FUNCTIONS = 512 +CSSC_REGISTER_MASK = 31 +CSSC_SOURCE_SHIFT = 5 +CSSC_RIGHT_SHIFT = 16 +CSSC_IMMEDIATE_SHIFT = 10 +CSSC_WIDTH_BIT = 1 << 31 +CSSC_UNARY_MASK = 0xfffffc00 +CSSC_REGISTER_OPCODE_MASK = 0xffe0fc00 +CSSC_IMMEDIATE_OPCODE_MASK = 0xfffc0000 +CSSC_INPUT_STRIDE = 800 +CSSC_RECORD_BYTES = 1024 +CSSC_RETURN_EXIT = 4 +CSSC_STATUS_OFFSET = 248 +CSSC_EXCEPTION_OFFSET = 280 +CSSC_VECTOR_OFFSET = 320 +CSSC_READBACK_OFFSET = 832 +CSSC_TRAP_ENABLES = 0x9f00 +CSSC_NEP = 1 << 2 +CSSC_RET_COMPATIBLE_FPCR = 0x07c00000 +CSSC_READABLE_FPCR = 0x07c80007 +CSSC_FPSR_MASK = 0x0800009f +CSSC_ORACLE = ROOT / '.stela/research/cssc-implementation/original/receipt.json' +CSSC_FORMS = { + 'ABS32': (0x5ac02000, 'ABS_32_dp_1src', 'unary'), + 'ABS64': (0xdac02000, 'ABS_64_dp_1src', 'unary'), + 'CNT32': (0x5ac01c00, 'CNT_32_dp_1src', 'unary'), + 'CNT64': (0xdac01c00, 'CNT_64_dp_1src', 'unary'), + 'CTZ32': (0x5ac01800, 'CTZ_32_dp_1src', 'unary'), + 'CTZ64': (0xdac01800, 'CTZ_64_dp_1src', 'unary'), + 'SMAX32': (0x1ac06000, 'SMAX_32_dp_2src', 'register'), + 'SMAX32I': (0x11c00000, 'SMAX_32_minmax_imm', 'immediate'), + 'SMAX64': (0x9ac06000, 'SMAX_64_dp_2src', 'register'), + 'SMAX64I': (0x91c00000, 'SMAX_64_minmax_imm', 'immediate'), + 'SMIN32': (0x1ac06800, 'SMIN_32_dp_2src', 'register'), + 'SMIN32I': (0x11c80000, 'SMIN_32_minmax_imm', 'immediate'), + 'SMIN64': (0x9ac06800, 'SMIN_64_dp_2src', 'register'), + 'SMIN64I': (0x91c80000, 'SMIN_64_minmax_imm', 'immediate'), + 'UMAX32I': (0x11c40000, 'UMAX_32U_minmax_imm', 'immediate'), + 'UMAX32': (0x1ac06400, 'UMAX_32_dp_2src', 'register'), + 'UMAX64I': (0x91c40000, 'UMAX_64U_minmax_imm', 'immediate'), + 'UMAX64': (0x9ac06400, 'UMAX_64_dp_2src', 'register'), + 'UMIN32I': (0x11cc0000, 'UMIN_32U_minmax_imm', 'immediate'), + 'UMIN32': (0x1ac06c00, 'UMIN_32_dp_2src', 'register'), + 'UMIN64I': (0x91cc0000, 'UMIN_64U_minmax_imm', 'immediate'), + 'UMIN64': (0x9ac06c00, 'UMIN_64_dp_2src', 'register'), +} + + +def cssc_operation(form, d=0, n=1, m=2, immediate=0): + base, canonical, input_kind = CSSC_FORMS[form] + if any(not 0 <= register <= CSSC_REGISTER_MASK for register in (d, n, m)): + raise ValueError('Invalid CSSC register') + if not 0 <= immediate <= 255: + raise ValueError('Invalid CSSC immediate') + word = base | n << CSSC_SOURCE_SHIFT | d + if input_kind == 'register': + word |= m << CSSC_RIGHT_SHIFT + elif input_kind == 'immediate': + word |= immediate << CSSC_IMMEDIATE_SHIFT + return {'form': form, 'canonical_id': canonical, 'input_kind': input_kind, + 'width': 64 if base & CSSC_WIDTH_BIT else 32, + 'd': d, 'n': n, 'm': m if input_kind == 'register' else None, + 'raw_imm8': immediate if input_kind == 'immediate' else None, + 'word': word, 'name': form.rstrip('I').rstrip('0123456789').lower()} + + +def cssc_value(operation, first, second=0): + """Independent arbitrary-precision definition, not the native SWAR recipe.""" + width = operation['width'] + mask = (1 << width) - 1 + first &= mask + form = operation['form'] + if form.startswith('ABS'): + return abs(signed(first, width)) & mask + if form.startswith('CNT'): + return first.bit_count() + if form.startswith('CTZ'): + return width if first == 0 else (first & -first).bit_length() - 1 + is_signed = form.startswith('S') + if operation['input_kind'] == 'immediate': + second = signed(operation['raw_imm8'], 8) if is_signed else operation['raw_imm8'] + else: + second = signed(second, width) if is_signed else second & mask + first = signed(first, width) if is_signed else first + select = min if 'MIN' in form else max + return select(first, second) & mask + + +def cssc_mathematical_reference(operations, initial): + registers = list(initial.x) + for operation in operations: + first = registers[operation['n']] if operation['n'] != CSSC_REGISTER_MASK else 0 + right = operation['m'] + second = registers[right] if right not in (None, CSSC_REGISTER_MASK) else 0 + value = cssc_value(operation, first, second) + if operation['d'] != CSSC_REGISTER_MASK: + registers[operation['d']] = value + return {**complete_state(initial), 'x': registers} + + +def cssc_corpus(): + """Bounded original full-frame inputs; no host result guides generation.""" + from differential import seed_extended_state + functions, records, indexes = [], [], {} + rng = random.Random(0x43535343494e5447) + controls = (0, CSSC_READABLE_FPCR, *(1 << bit for bit in (8, 9, 10, 11, 12, 15)), + CSSC_TRAP_ENABLES, CSSC_READABLE_FPCR | CSSC_TRAP_ENABLES) + + def append(operation, label, first=None, second=None, control=None, flags=None): + word = operation['word'] + if word not in indexes: + indexes[word] = len(functions) + functions.append(operation) + function = indexes[word] + initial = State() + for register in range(31): + initial.x[register] = rng.getrandbits(64) + initial.sp = rng.getrandbits(64) & ~15 + initial.reserved = rng.getrandbits(32) + seed_extended_state(initial, len(records)) + initial.nzcv = (len(records) % 16 if flags is None else flags) << 28 + initial.fpcr = controls[len(records) % len(controls)] if control is None else control + initial.fpsr = (0, CSSC_FPSR_MASK, 1 << 27, 0x9f)[len(records) % 4] + poison = 0xdeadc0de00000000 if operation['width'] == 32 else 0 + if operation['n'] != CSSC_REGISTER_MASK and first is not None: + initial.x[operation['n']] = (first & ((1 << operation['width']) - 1)) | poison + right = operation['m'] + if right not in (None, CSSC_REGISTER_MASK, operation['n']) and second is not None: + initial.x[right] = (second & ((1 << operation['width']) - 1)) | poison + records.append({'case': len(records), 'function': function, 'function_index': function, + 'label': label, 'initial': bytes(initial), + 'initial_state_sha256': hashlib.sha256(bytes(initial)).hexdigest()}) + + # Decoder tests cover all 1024 combinations. Original execution spans each + # register field plus every in-place/ZR/discard position without a quadratic + # repeated native compilation sweep. + unary_roles = tuple(dict.fromkeys(( + *((d, (d + 5) % 32) for d in range(32)), + *((r, r) for r in range(32)), + *((d, 31) for d in range(32)), + *((31, n) for n in range(32))))) + binary_roles = ((0, 1, 2), (1, 1, 2), (2, 1, 2), (1, 1, 1), + (0, 1, 1), (31, 1, 2), (0, 31, 2), (0, 1, 31), + (0, 31, 31), (31, 31, 31), (30, 30, 30)) + for form, (_, _, input_kind) in CSSC_FORMS.items(): + operation = cssc_operation(form) + width = operation['width'] + sign, mask = 1 << (width - 1), (1 << width) - 1 + values = (0, 1, 2, sign - 1, sign, sign + 1, mask - 1, mask, + 0xaaaaaaaaaaaaaaaa & mask, 0x5555555555555555 & mask) + if input_kind == 'unary': + for d, n in unary_roles: + append(cssc_operation(form, d, n), 'all_register_roles') + directed = (*values, *(1 << bit for bit in range(width)), + *((1 << count) - 1 for count in range(width + 1))) + for value in dict.fromkeys(directed): + append(operation, 'bit_and_sign_boundaries', value) + elif input_kind == 'register': + roles = tuple(dict.fromkeys((*binary_roles, + *((d, (d + 5) % 32, (d + 13) % 32) for d in range(32))))) + for d, n, m in roles: + append(cssc_operation(form, d, n, m), 'register_aliases', sign, mask) + for first, second in itertools.product(values, values): + append(operation, 'ordering_and_overflow_boundaries', first, second) + else: + for immediate in range(256): + operation = cssc_operation(form, immediate=immediate) + decoded = signed(immediate, 8) if form.startswith('S') else immediate + for first in dict.fromkeys((decoded - 1, decoded, decoded + 1, *values)): + append(operation, 'all_immediate_ordering_boundaries', first) + for immediate in (0, 0x7f, 0x80, 0xff): + for d, n in ((1, 1), (31, 1), (0, 31), (31, 31), (30, 30)): + append(cssc_operation(form, d, n, immediate=immediate), 'immediate_aliases', sign) + operation = cssc_operation(form, immediate=0x80) + for flags in range(16): + append(operation, 'all_nzcv_and_extended_state', sign, mask, flags=flags) + for control in controls: + append(operation, 'integer_preserves_fp_controls', sign, mask, control=control) + if len(records) > 50000 or len({op['canonical_id'] for op in functions}) != 22: + raise AssertionError('CSSC corpus exceeded scope or omitted a canonical form') + return functions, records + + +def cssc_calibration_corpus(): + functions, records = [], [] + for form in CSSC_FORMS: + operation = cssc_operation(form, immediate=0x80) + function = len(functions) + functions.append(operation) + for control in (0, CSSC_READABLE_FPCR | CSSC_TRAP_ENABLES): + initial = State() + for register in range(31): + initial.x[register] = (0xdeadc0de00000000 | (1 << 31)) ^ register + initial.x[2] = MASK + initial.sp = 0x42008000 + initial.nzcv = (len(records) % 16) << 28 + initial.reserved = 0x43535343 + initial.fpcr = control + initial.fpsr = CSSC_FPSR_MASK + records.append({'case': len(records), 'function': function, 'function_index': function, + 'label': 'calibration', 'initial': bytes(initial), + 'initial_state_sha256': hashlib.sha256(bytes(initial)).hexdigest()}) + return functions, records + + +def prepare_cssc_oracle(directory, calibration=False): + functions, records = cssc_calibration_corpus() if calibration else cssc_corpus() + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + functions = [{**op, 'source_hex': struct.pack('> 26 != shared.FP_REGISTER_EC_SVC or current_el != 4 + or cpacr != shared.VECTOR_NUMERICAL_CPACR_FPEN or marker != shared.VECTOR_NUMERICAL_ORIGINAL_MARKER + or shared.fp_register_elf_word(artifacts['guest.elf'], elr - 8) != operation['word'] + or shared.fp_register_elf_word(artifacts['guest.elf'], elr - 4) != shared.FP_REGISTER_SVC + or original.fpcr != pre_fpcr or original.fpsr != pre_fpsr + or pre_fpsr != initial.fpsr + or pre_fpcr != initial.fpcr & ~CSSC_TRAP_ENABLES): + raise AssertionError(f'CSSC original source/exception/control evidence invalid: {index}') + observed_initial = State.from_buffer_copy(initial) + observed_initial.fpcr = pre_fpcr + if cssc_mathematical_reference([operation], observed_initial) != complete_state(original): + raise AssertionError(f'CSSC original differs from independent integer model: {index}') + records.append({**expected, 'operation': operation, 'original': bytes(original), + 'control_policy': pre_fpcr != initial.fpcr}) + return {'records': records, 'functions': expected_functions, 'receipt': receipt, + 'receipt_sha256': hashlib.sha256(receipt_bytes).hexdigest(), + 'control_policy_cases': sum(record['control_policy'] for record in records)} + + +def execute_cssc_cases(compiled, records): + counts = {'original_native_full_state': 0, 'requested_control_policy_full_state': 0, + 'native_integer_model_full_state': 0} + corpus = hashlib.sha256() + for target, binaries in compiled.items(): + for record in records: + initial = State.from_buffer_copy(record['initial']) + expected = cssc_mathematical_reference([record['operation']], initial) + actual = native_state(binaries[record['function']], initial) + if actual != expected: + raise AssertionError(json.dumps({'target': target, 'case': record['case'], + 'operation': record['operation'], 'expected': expected, 'actual': actual})) + counts['native_integer_model_full_state'] += 1 + if record['control_policy']: + # Original raw requested enables are RAZ/WI. Preserve that input + # and observation; count storage-policy equality separately. + adjusted = dict(actual, fpcr=complete_state(State.from_buffer_copy(record['original']))['fpcr']) + if adjusted != complete_state(State.from_buffer_copy(record['original'])): + raise AssertionError('CSSC requested-control policy changed a non-control effect') + counts['requested_control_policy_full_state'] += 1 + else: + if actual != complete_state(State.from_buffer_copy(record['original'])): + raise AssertionError('CSSC raw original/native full state differs') + counts['original_native_full_state'] += 1 + corpus.update(target.encode() + struct.pack('> 26 != engine.FP_REGISTER_EC_SVC or current_el != 4 + or cpacr != engine.VECTOR_NUMERICAL_CPACR_FPEN or marker != engine.VECTOR_NUMERICAL_ORIGINAL_MARKER + or engine.fp_register_elf_word(elf, elr - 8) != op['word'] + or engine.fp_register_elf_word(elf, elr - 4) != engine.FP_REGISTER_SVC + or fpcr != initial.fpcr & engine.FP_REGISTER_QEMU_MASKS['fpcr'] + or fpsr != initial.fpsr & engine.FP_REGISTER_QEMU_MASKS['fpsr']): + raise AssertionError('Original subject/access/control evidence differs') + mathematical = expected_state(family, op, initial) + observed_controls = State.from_buffer_copy(mathematical) + observed_controls.fpcr, observed_controls.fpsr = fpcr, fpsr + if bytes(original) != bytes(observed_controls): + raise AssertionError(json.dumps({'case':index, 'operation':op, 'primary':state_dict(original), + 'expected_observed_controls':state_dict(observed_controls), 'initial':state_dict(initial)})) + policy = (fpcr, fpsr) != (initial.fpcr, initial.fpsr) + initial.x[RETURN_REGISTER] = original.x[RETURN_REGISTER] = mathematical.x[RETURN_REGISTER] = engine.STOP + records.append({**case, 'initial':bytes(initial), 'expected':bytes(mathematical), 'primary_expected':bytes(original), + 'operation':op, 'equality_basis':'requested_storage_policy' if policy else 'direct_original'}) + readbacks[(case['initial'][-8:].hex(), fpcr, fpsr)] += 1 + return {'functions':operations, 'records':records, 'producer':producer, 'receipt_sha256':receipt_sha, + 'pointer_sha256':pointer_sha, 'control_readbacks':[{'requested_storage_hex':requested, 'fpcr':fpcr, 'fpsr':fpsr, 'cases':count} + for (requested, fpcr, fpsr), count in sorted(readbacks.items())]} + + +def execute_batches(engine, batches): + family = family_module(batches[0]['cohort']) + oracle = load_original(engine, family, batches[0]['oracle_path']) + counts, digest = Counter(), hashlib.sha256() + examples = {} + with ExitStack() as mappings: + functions = {} + for batch in batches: + address = mappings.enter_context(engine.executable(batch['native'])) + for local, offset in enumerate(batch['offsets']): + functions[batch['function_base'] + local] = address + offset + address = mappings.enter_context(engine.executable(engine.NUMERICAL_MXCSR_WRAPPER)) + wrapper = ctypes.CFUNCTYPE(None, ctypes.POINTER(State), ctypes.c_void_p, ctypes.c_uint32, + ctypes.POINTER(engine.NumericalNativeExit))(address) + guard = ctypes.create_string_buffer(engine.NUMERICAL_GUARD_BYTES * 2 + ctypes.sizeof(State)) + state_address = ctypes.addressof(guard) + engine.NUMERICAL_GUARD_BYTES + state_pointer = ctypes.cast(state_address, ctypes.POINTER(State)) + def invoke(record, mxcsr): + ctypes.memmove(guard, engine.NUMERICAL_GUARD + record['initial'] + engine.NUMERICAL_GUARD, len(guard)) + observed = engine.NumericalNativeExit() + wrapper(state_pointer, functions[record['function']], mxcsr, ctypes.byref(observed)) + # Leaf functions return void: BlockExit scratch is deliberately not interpreted. + if observed.mxcsr_before != mxcsr or observed.mxcsr_after != mxcsr: + raise AssertionError('Integer crypto changed caller MXCSR') + if guard.raw[:engine.NUMERICAL_GUARD_BYTES] != engine.NUMERICAL_GUARD or guard.raw[-engine.NUMERICAL_GUARD_BYTES:] != engine.NUMERICAL_GUARD: + raise AssertionError('Integer crypto changed owned RAM canaries') + actual = ctypes.string_at(state_address, ctypes.sizeof(State)) + if actual != record['expected']: + raise AssertionError(json.dumps({'case':record['case'], 'operation':record['operation'], + 'actual':state_dict(State.from_buffer_copy(actual)), 'expected':state_dict(State.from_buffer_copy(record['expected']))})) + for record in oracle['records']: + invoke(record, engine.NUMERICAL_MXCSR_ALL_MASKS) + counts[record['equality_basis']] += 1 + digest.update(struct.pack('>= 1 + return result + + +def rotate_byte(value, amount): + return ((value << amount) | (value >> (8 - amount))) & BYTE_MASK + + +def substitute_byte(value): + inverse = field_inverse(value) + result = inverse ^ 0x63 + for rotation in (1, 2, 3, 4): + result ^= rotate_byte(inverse, rotation) + return result + + +SBOX = tuple(substitute_byte(value) for value in range(256)) +_inverse = [0] * 256 +for _index, _value in enumerate(SBOX): + _inverse[_value] = _index +INVERSE_SBOX = tuple(_inverse) +del _inverse, _index, _value + + +def shift_rows(value, inverse=False): + direction = -1 if inverse else 1 + return bytes(value[4 * ((column + direction * row) % 4) + row] + for column in range(4) for row in range(4)) + + +def mix_columns(value, inverse=False): + matrix = INVERSE_MATRIX if inverse else FORWARD_MATRIX + result = bytearray(16) + for column in range(4): + for row in range(4): + output = 0 + for item in range(4): + output ^= field_multiply(matrix[row][item], value[4 * column + item]) + result[4 * column + row] = output + return bytes(result) + + +def operation(name, destination, source): + if name not in FORM_VALUES or not (0 <= destination < 32 and 0 <= source < 32): + raise ValueError('invalid classic AES form or vector register') + return {'kind': FOCUS, 'name': name, 'd': destination, 'n': source, 'm': source, + 'lane': 1, 'bytes': 16, 'scalar': False, 'output_kind': 'vector', + 'word': FORM_VALUES[name] | (source << 5) | destination, + 'canonical_id': name.upper() + '_B_cryptoaes'} + + +def functions(): + return [operation(name, destination, source) + for name in FORM_VALUES for destination in range(32) for source in range(32)] + + +def vector_bytes(state, register): + low, high = state.v[register] + return (low | (high << 64)).to_bytes(16, 'little') + + +def set_vector(state, register, value): + packed = int.from_bytes(value, 'little') + state.v[register][:] = [packed & LIMB_MASK, packed >> 64] + + +def expected(op, initial): + state = State.from_buffer_copy(initial) + value = vector_bytes(initial, op['n']) + if op['name'] in ('aese', 'aesd'): + old = vector_bytes(initial, op['d']) + value = bytes(left ^ right for left, right in zip(value, old)) + inverse = op['name'] == 'aesd' + table = INVERSE_SBOX if inverse else SBOX + value = bytes(table[item] for item in shift_rows(value, inverse)) + else: + value = mix_columns(value, op['name'] == 'aesimc') + set_vector(state, op['d'], value) + return state + + +def initial_state(index): + rng = random.Random(0xae500000 + index) + state = State() + state.x[:] = [rng.getrandbits(64) for _ in range(31)] + state.sp = 0x30000800 + state.nzcv = (index % 16) << 28 + state.reserved = rng.getrandbits(32) + seed_extended_state(state, 0xae510000 + index) + return state + + +def corpus(): + programs = functions() + records = [] + lookup = {(op['name'], op['d'], op['n']): index for index, op in enumerate(programs)} + + def record(index, state, label): + op = programs[index] + runtime = False + if label == 'all_register_pairs' and (op['d'], op['n']) in ( + (0, 1), (31, 31), (31, 0), (0, 31)): + runtime = True + state.fpcr = 0x07c00000 if op['d'] == 31 else 0 + state.fpsr = 0x0800001f if op['d'] == 31 else 0 + elif label == 'all_sbox_bytes_each_lane': + runtime = vector_bytes(state, 1)[0] in (0, 1, 0x53, 0x63, 0x80, 0xff) + elif label == 'column_basis': + bit = int.from_bytes(vector_bytes(state, 1), 'little').bit_length() - 1 + runtime = bit in (0, 7, 8, 15, 31, 63, 64, 127) + elif label == 'v31_alias_edges': + runtime = True + records.append({'function': index, 'initial': bytes(state), 'label': label, + 'runtime': runtime}) + + for index in range(len(programs)): + record(index, initial_state(index), 'all_register_pairs') + # Across 256 cyclic blocks, every byte value occurs in every one of 16 lanes. + for name in ('aese', 'aesd'): + index = lookup[name, 0, 1] + for value in range(256): + state = initial_state(len(records)) + set_vector(state, 0, bytes(16)) + set_vector(state, 1, bytes((value + lane) & BYTE_MASK for lane in range(16))) + record(index, state, 'all_sbox_bytes_each_lane') + # Linear column transforms: every basis bit, including all reduction bits. + for name in ('aesmc', 'aesimc'): + index = lookup[name, 0, 1] + for bit in range(128): + state = initial_state(len(records)) + set_vector(state, 0, bytes([BYTE_MASK] * 16)) # Stale destination. + set_vector(state, 1, (1 << bit).to_bytes(16, 'little')) + record(index, state, 'column_basis') + for name in FORM_VALUES: + index = lookup[name, 31, 31] + for value in (0, 1, 0x80, 0xff): + state = initial_state(len(records)) + set_vector(state, 31, bytes([value] * 16)) + record(index, state, 'v31_alias_edges') + return programs, records + + +def chains(): + """Optional shared-runner sequences; expected() applies each step in order.""" + return [ + [operation('aese', 0, 1), operation('aesmc', 0, 0), + operation('aesd', 31, 0), operation('aesimc', 31, 31)], + [operation('aesimc', 2, 31), operation('aesmc', 31, 2), + operation('aese', 31, 31), operation('aesd', 0, 31)], + ] + + +def optional_opcodes(target_id): + features = set(target_id.split('+')[1:]) + if 'aes' in features: + return {'aesenclast', 'aesdeclast', 'aesenc', 'aesimc'} + if 'ssse3' in features: + return {'pshufb'} + return set() diff --git a/dev/simd_fixtures/i8mm.py b/dev/simd_fixtures/i8mm.py new file mode 100644 index 0000000000..31e4214214 --- /dev/null +++ b/dev/simd_fixtures/i8mm.py @@ -0,0 +1,147 @@ +"""Pure classic I8MM fixtures: original words and independent integer semantics.""" +import struct + +from differential import State, seed_extended_state + +FOCUS = 'i8mm' +CANONICAL_FORMS = ( + 'SMMLA_asimdsame2_G', 'UMMLA_asimdsame2_G', 'USMMLA_asimdsame2_G', + 'USDOT_asimdsame2_D', 'USDOT_asimdelem_D', 'SUDOT_asimdelem_D', +) +MATRIX_BASES = {'smmla': 0x4e80a400, 'ummla': 0x6e80a400, 'usmmla': 0x4e80ac00} +DOT_BASES = {'usdot': 0x0e809c00} +INDEXED_BASES = {'usdot': 0x0f80f000, 'sudot': 0x0f00f000} +MASK64 = (1 << 64) - 1 +FPSR_QC = 1 << 27 +ALIAS_ROLES = ((0, 1, 2), (1, 1, 2), (2, 1, 2), (0, 1, 1), (31, 31, 31), (31, 29, 31)) + + +def operation(name, count=16, index=None, d=0, n=1, m=2): + matrix = name in MATRIX_BASES + if count not in (8, 16) or any(not 0 <= register < 32 for register in (d, n, m)): + raise ValueError('I8MM vector width/register outside allocated range') + if matrix: + if count != 16 or index is not None: + raise ValueError('I8MM matrices have only the full 128-bit unindexed form') + base, canonical = MATRIX_BASES[name], name.upper() + '_asimdsame2_G' + elif index is None: + if name not in DOT_BASES: + raise ValueError('Only USDOT has a mixed-sign vector encoding') + base, canonical = DOT_BASES[name], 'USDOT_asimdsame2_D' + else: + if name not in INDEXED_BASES or not 0 <= index < 4: + raise ValueError('I8MM indexed dots select one of four full-source dword groups') + base, canonical = INDEXED_BASES[name], name.upper() + '_asimdelem_D' + base |= (index & 1) << 21 | (index >> 1) << 11 + word = base | (count == 16) << 30 | m << 16 | n << 5 | d + return {'kind': FOCUS, 'name': name, 'word': word, 'canonical_id': canonical, + 'd': d, 'n': n, 'm': m, 'lane': 1, 'output_lane': 4, 'bytes': count, + 'scalar': False, 'upper': False, 'output_kind': 'vector', 'index': index, + 'matrix': matrix, 'left_signed': name in ('smmla', 'sudot'), + 'right_signed': name in ('smmla', 'usmmla', 'usdot')} + + +def functions(): + layouts = [(name, 16, None) for name in MATRIX_BASES] + layouts += [('usdot', count, None) for count in (8, 16)] + layouts += [(name, count, index) for name in INDEXED_BASES + for count in (8, 16) for index in range(4)] + result = [] + for name, count, index in layouts: + registers = [*ALIAS_ROLES, *((d, (d + 5) % 32, (d + 13) % 32) for d in range(32))] + result.extend(operation(name, count, index, d, n, m) for d, n, m in registers) + return result + + +def expected(op, initial): + """Read old operands before writing; preserve all other 784-byte state fields.""" + state = State.from_buffer_copy(initial) + left, right, previous = (initial.v[op[key]][0] | initial.v[op[key]][1] << 64 for key in ('n', 'm', 'd')) + + def byte(vector, position, signed): + value = vector >> (8 * position) & 255 + return value - 256 if signed and value >= 128 else value + + result = 0 + for element in range(op['bytes'] // 4): + if op['matrix']: + row, column = divmod(element, 2) + products = (byte(left, 8 * row + k, op['left_signed']) * byte(right, 8 * column + k, op['right_signed']) + for k in range(8)) + else: + group = element if op['index'] is None else op['index'] + products = (byte(left, 4 * element + k, op['left_signed']) * byte(right, 4 * group + k, op['right_signed']) + for k in range(4)) + value = ((previous >> (32 * element) & 0xffffffff) + sum(products)) & 0xffffffff + result |= value << (32 * element) + state.v[op['d']][:] = [result & MASK64, result >> 64] + return state + + +def initial_state(op, pattern, flags): + state = State() + for register in range(31): + state.x[register] = (0x9e3779b97f4a7c15 * (register + 1) + pattern) & MASK64 + state.sp = 0x000000007ffffff0 + state.nzcv = flags << 28 + state.reserved = 0x51ad1234 + seed_extended_state(state, pattern * 16 + flags) + # Every FP rounding mode and the standard AHP/DN/FZ controls must survive + # unchanged; this family performs no FP arithmetic or status update. + state.fpcr = (pattern % 4) << 22 | (0x07000000 if flags else 0) + boundary = (0, 255, 128, 127, 1, 254, 129, 126) + for register in range(32): + if pattern < 4: + values = bytes([boundary[pattern]]) * 16 + elif pattern == 7: + values = bytes(8) + bytes([255]) * 8 + else: + values = bytes(boundary[(register + byte + pattern) % len(boundary)] for byte in range(16)) + state.v[register][:] = struct.unpack('<2Q', values) + if len({op['d'], op['n'], op['m']}) == 3: + accumulators = (0, 0xffffffff, 0x7fffffff, 0x80000000) + state.v[op['d']][:] = struct.unpack('<2Q', struct.pack('<4I', + *(accumulators[(pattern + lane) % 4] for lane in range(4)))) + if pattern in (5, 6): + state.v[op['n']][:] = [MASK64, MASK64] + value = int.from_bytes(bytes([127 if pattern == 5 else 128]) * 8, 'little') + state.v[op['m']][:] = [value, value] + if op['name'] == 'sudot': + state.v[op['n']][:], state.v[op['m']][:] = state.v[op['m']][:], state.v[op['n']][:] + elif pattern >= 8: + left = bytearray(16) + left[pattern - 8] = 128 + state.v[op['n']][:] = struct.unpack('<2Q', left) + state.v[op['m']][:] = struct.unpack('<2Q', bytes(17 * byte + 3 & 255 for byte in range(16))) + state.fpsr = (state.fpsr & ~FPSR_QC) | (FPSR_QC if flags else 0) + return state + + +def corpus(): + ops, records = functions(), [] + for index, op in enumerate(ops): + # All register/alias roles get eight patterns; the distinct-register + # representative additionally isolates every original source byte. + patterns = range(24) if (op['d'], op['n'], op['m']) == ALIAS_ROLES[0] else range(8) + for pattern in patterns: + for flags in (0, 15): + registers = (op['d'], op['n'], op['m']) + runtime = ( + registers == ALIAS_ROLES[0] and (pattern, flags) in ((5, 15), (8, 0)) + or registers == ALIAS_ROLES[1] and (pattern, flags) == (4, 0) + or registers == ALIAS_ROLES[4] and (pattern, flags) == (6, 15) + or op['matrix'] and registers == ALIAS_ROLES[0] and (pattern, flags) == (3, 15) + or op['matrix'] and registers == ALIAS_ROLES[2] and (pattern, flags) == (2, 0) + or op['matrix'] and registers == ALIAS_ROLES[3] and (pattern, flags) == (3, 0) + or not op['matrix'] and op['name'] == 'usdot' and op['bytes'] == 8 + and op['index'] is None and registers == ALIAS_ROLES[2] and (pattern, flags) == (1, 0) + or not op['matrix'] and op['name'] == 'usdot' and op['bytes'] == 8 + and op['index'] is None and registers == ALIAS_ROLES[3] and (pattern, flags) == (3, 0) + ) + records.append({'function': index, 'label': f'pattern_{pattern}_flags_{flags}', + 'initial': bytes(initial_state(op, pattern, flags)), 'runtime': runtime}) + return ops, records + + +def optional_opcodes(target_id): + return {'phaddd'} if 'ssse3' in target_id.split('+') else set() diff --git a/dev/simd_fixtures/sha12.py b/dev/simd_fixtures/sha12.py new file mode 100644 index 0000000000..d598f12616 --- /dev/null +++ b/dev/simd_fixtures/sha12.py @@ -0,0 +1,168 @@ +"""Pinned classic SHA1/SHA256 fixtures for the consolidated SIMD engine. + +Pure encoding, full-state corpus and independent integer model only. The engine +owns original/native execution, exact source identities, feature profiles and +oracle limitations. No arithmetic instruction reads or changes FPCR/FPSR/NZCV. +""" +import random +from differential import State, seed_extended_state + +FOCUS = 'sha12' +MASK32 = (1 << 32) - 1 +MASK64 = (1 << 64) - 1 +FORMS = { + 'sha1c': ('SHA1C_QSV_cryptosha3', 0x5e000000), + 'sha1p': ('SHA1P_QSV_cryptosha3', 0x5e001000), + 'sha1m': ('SHA1M_QSV_cryptosha3', 0x5e002000), + 'sha1h': ('SHA1H_SS_cryptosha2', 0x5e280800), + 'sha1su0': ('SHA1SU0_VVV_cryptosha3', 0x5e003000), + 'sha1su1': ('SHA1SU1_VV_cryptosha2', 0x5e281800), + 'sha256h': ('SHA256H_QQV_cryptosha3', 0x5e004000), + 'sha256h2': ('SHA256H2_QQV_cryptosha3', 0x5e005000), + 'sha256su0': ('SHA256SU0_VV_cryptosha2', 0x5e282800), + 'sha256su1': ('SHA256SU1_VVV_cryptosha3', 0x5e006000), +} +CANONICAL_FORMS = tuple(value[0] for value in FORMS.values()) +TWO_REGISTER_FORMS = frozenset(('sha1h', 'sha1su1', 'sha256su0')) +TERNARY_ROLES = ((0, 1, 2), (1, 1, 2), (2, 1, 2), (0, 1, 1), + (31, 31, 31), (0, 31, 31), (31, 29, 31), (31, 31, 29), + (31, 29, 30), (0, 31, 30), (0, 30, 31)) +UNARY_ROLES = ((0, 1, 0), (1, 1, 0), (31, 31, 0), (0, 31, 0), + (31, 0, 0), (31, 29, 0), (0, 30, 0)) +PATTERN_COUNT = 16 + + +def operation(name, d=0, n=1, m=2): + if name not in FORMS or any(not 0 <= value < 32 for value in (d, n, m)): + raise ValueError('invalid classic SHA operation/register') + canonical_id, base = FORMS[name] + if name in TWO_REGISTER_FORMS: + m = 0 + return {'name': name, 'word': base | (n << 5) | d | (m << 16), + 'canonical_id': canonical_id, 'd': d, 'n': n, 'm': m, + 'lane': 4, 'bytes': 4 if name == 'sha1h' else 16, + 'scalar': name == 'sha1h', 'output_kind': 'vector'} + + +def functions(): + return [{**operation(name, d, n, m), 'role_index': role} for name in FORMS + for role, (d, n, m) in enumerate(UNARY_ROLES if name in TWO_REGISTER_FORMS else TERNARY_ROLES)] + + +def _rol(value, amount): + return ((value << amount) | (value >> (32 - amount))) & MASK32 + + +def _ror(value, amount): + return _rol(value, 32 - amount) + + +def _choose(a, b, c): + return (a & b) ^ ((~a & MASK32) & c) + + +def _majority(a, b, c): + return (a & b) ^ (a & c) ^ (b & c) + + +def _sigma0(value): + return _ror(value, 7) ^ _ror(value, 18) ^ (value >> 3) + + +def _sigma1(value): + return _ror(value, 17) ^ _ror(value, 19) ^ (value >> 10) + + +def expected(op, initial): + result = State.from_buffer_copy(initial) + words = [list((vector[0] | (vector[1] << 64)) >> (i * 32) & MASK32 for i in range(4)) + for vector in initial.v] + d, n, m = (words[op[key]][:] for key in ('d', 'n', 'm')) + name = op['name'] + if name == 'sha1h': + out = [_ror(n[0], 2), 0, 0, 0] + elif name in ('sha1c', 'sha1p', 'sha1m'): + a, b, c, d_word = d + e = n[0] + for word in m: + f = _choose(b, c, d_word) if name == 'sha1c' else _majority(b, c, d_word) if name == 'sha1m' else b ^ c ^ d_word + a, b, c, d_word, e = (_rol(a, 5) + f + e + word) & MASK32, a, _rol(b, 30), c, d_word + out = [a, b, c, d_word] + elif name == 'sha1su0': + shifted = d[2:] + n[:2] + out = [a ^ b ^ c for a, b, c in zip(d, shifted, m)] + elif name == 'sha1su1': + t = [a ^ b for a, b in zip(d, n[1:] + [0])] + out = [_rol(value, 1) for value in t] + out[3] ^= _rol(t[0], 2) + elif name == 'sha256su0': + out = [(a + _sigma0(b)) & MASK32 for a, b in zip(d, d[1:] + n[:1])] + elif name == 'sha256su1': + base = [(a + b) & MASK32 for a, b in zip(d, n[1:] + m[:1])] + out = [(base[0] + _sigma1(m[2])) & MASK32, (base[1] + _sigma1(m[3])) & MASK32] + out += [(base[2] + _sigma1(out[0])) & MASK32, (base[3] + _sigma1(out[1])) & MASK32] + elif name in ('sha256h', 'sha256h2'): + a, b, c, d_word = d if name == 'sha256h' else n + e, f, g, h = n if name == 'sha256h' else d + for word in m: + t1 = h + (_ror(e, 6) ^ _ror(e, 11) ^ _ror(e, 25)) + _choose(e, f, g) + word + t2 = (_ror(a, 2) ^ _ror(a, 13) ^ _ror(a, 22)) + _majority(a, b, c) + a, b, c, d_word, e, f, g, h = (t1 + t2) & MASK32, a, b, c, (d_word + t1) & MASK32, e, f, g + out = [a, b, c, d_word] if name == 'sha256h' else [e, f, g, h] + else: + raise ValueError('unsupported classic SHA model operation') + value = sum(word << (i * 32) for i, word in enumerate(out)) + result.v[op['d']][:] = [value & MASK64, value >> 64] + return result + + +def state(op, pattern, flags): + if not 0 <= pattern < PATTERN_COUNT or not 0 <= flags < 16: + raise ValueError('classic SHA corpus index outside bounded scope') + initial = State() + seed = 0x534841120000 | (pattern << 8) | flags + seed_extended_state(initial, seed) + rng = random.Random(seed) + initial.x[:] = [rng.getrandbits(64) for _ in initial.x] + initial.sp = 0x240000008000 + initial.nzcv = flags << 28 + initial.reserved = 0x53484112 + initial.fpcr = (0, 0x07c00000, 0x00080000, 0x07c80000)[pattern % 4] + initial.fpsr = (0, 0x0800009f, 0x08000000, 0x0000009f)[flags % 4] + directed = (0, MASK32, 1, 0x80000000, 0x7fffffff, 0xfffffffe, + 0xaaaaaaaa, 0x55555555, 0x01020304, 0x10204080, 0x89abcdef, 0x76543210) + for register in range(32): + if pattern < 8: + values = [directed[(register + lane + pattern) % len(directed)] for lane in range(4)] + elif pattern < 12: + values = [1 << ((register + 8 * (pattern - 8) + 2 * lane) % 32) for lane in range(4)] + else: + values = [rng.getrandbits(32) for _ in range(4)] + value = sum(word << (i * 32) for i, word in enumerate(values)) + initial.v[register][:] = [value & MASK64, value >> 64] + return initial + + +def optional_opcodes(target_id): + features = set(target_id.split('+')[1:]) + expected = set() + if 'sha' in features: + expected.update(('sha1rnds4', 'sha1msg2', 'sha256rnds2', 'sha256msg1', 'sha256msg2')) + if 'ssse3' in features: + expected.add('palignr') + return expected + + +def corpus(): + ops = functions() + records = [] + for index, op in enumerate(ops): + for pattern in range(PATTERN_COUNT): + for flags in range(16): + record = {'function': index, 'label': f'pattern_{pattern}_nzcv_{flags:x}', + 'initial': bytes(state(op, pattern, flags))} + if ((op['role_index'] == 0 and (pattern, flags) in ((0, 0), (9, 15), (10, 0), (15, 15))) + or (op['role_index'] in (1, 2, 3, 4, 6) and pattern == 12 and flags == 15)): + record['runtime'] = True + records.append(record) + return ops, records diff --git a/dev/simd_fixtures/sha3.py b/dev/simd_fixtures/sha3.py new file mode 100644 index 0000000000..02262d73ec --- /dev/null +++ b/dev/simd_fixtures/sha3.py @@ -0,0 +1,186 @@ +"""Pure classic SHA3 encoding/corpus/oracle fixtures for the shared SIMD engine.""" +import ctypes +import random +import struct + +from differential import State, seed_extended_state + +FOCUS = 'sha3' +FORMS = { + 'eor3': ('EOR3_VVV16_crypto4', 0xce000000), + 'bcax': ('BCAX_VVV16_crypto4', 0xce200000), + 'rax1': ('RAX1_VVV2_cryptosha512_3', 0xce608c00), + 'xar': ('XAR_VVV2_crypto3_imm6', 0xce800000), +} +CANONICAL_FORMS = tuple(value[0] for value in FORMS.values()) +MASK64 = (1 << 64) - 1 +STANDARD_CONTROLS = (0, 1 << 22, 2 << 22, 3 << 22, 1 << 24, 1 << 25, 1 << 26, 0x07c00000) +EXTENDED_CONTROLS = (1, 2, 4, 1 << 19, 0x9f00, 0x07c89f07) + + +def operation(name, d=0, n=1, m=2, a=31, amount=0): + if name not in FORMS or any(not isinstance(r, int) or not 0 <= r < 32 for r in (d, n, m, a)): + raise ValueError('invalid classic SHA3 operation/register') + if not isinstance(amount, int) or not 0 <= amount < 64 or (name != 'xar' and amount): + raise ValueError('XAR rotation must be an immediate0..63; other forms have no immediate') + canonical_id, base = FORMS[name] + word = base | d | (n << 5) | (m << 16) + result = {'kind': FOCUS, 'name': name, 'd': d, 'n': n, 'm': m, + 'lane': 8, 'bytes': 16, 'scalar': False, 'output_kind': 'vector', + 'canonical_id': canonical_id, 'word': word} + if name in ('eor3', 'bcax'): + result.update(a=a, word=word | (a << 10)) + elif name == 'xar': + result.update(amount=amount, word=word | (amount << 10)) + return result + + +def alias_partitions(roles): + """Restricted-growth strings enumerate each register equality partition once.""" + if not isinstance(roles, int) or not 1 <= roles <= 4: + raise ValueError('classic SHA3 has one through four register roles') + result = [(0,)] + for _ in range(roles - 1): + result = [prefix + (group,) for prefix in result for group in range(max(prefix) + 2)] + return result + + +def functions(): + result = {} + def add(op): + result.setdefault(op['word'], op) + for name in FORMS: + roles = 4 if name in ('eor3', 'bcax') else 3 + for amount in range(64) if name == 'xar' else (0,): + for partition in alias_partitions(roles): + registers = [(0, 1, 2, 31)[group] for group in partition] + options = dict(zip(('d', 'n', 'm', 'a'), registers)) + add(operation(name, **options, amount=amount)) + for register in range(32): + add(operation(name, d=register, n=(register + 1) % 32, + m=(register + 2) % 32, a=(register + 3) % 32, + amount=register if name == 'xar' else 0)) + for role in range(roles): + registers = [0, 1, 2, 3] + registers[role] = 31 + add(operation(name, **dict(zip(('d', 'n', 'm', 'a'), registers)), amount=63 if name == 'xar' else 0)) + return list(result.values()) + + +def chain(): + """One mixed alias chain for the shared engine's block/runtime checks.""" + return [operation('eor3', d=31, n=1, m=2, a=3), + operation('bcax', d=2, n=31, m=2, a=3), + operation('rax1', d=3, n=2, m=31), + operation('xar', d=31, n=3, m=2, amount=63)] + + +def expected(op, initial): + """Clone all architectural bytes; mathematical operations touch Vd only.""" + state = State.from_buffer_copy(initial) + left = int(initial.v[op['n']][0]) | (int(initial.v[op['n']][1]) << 64) + right = int(initial.v[op['m']][0]) | (int(initial.v[op['m']][1]) << 64) + if op['name'] in ('eor3', 'bcax'): + third = int(initial.v[op['a']][0]) | (int(initial.v[op['a']][1]) << 64) + value = left ^ right ^ third if op['name'] == 'eor3' else left ^ (right & ~third) + else: + value = 0 + for lane in range(2): + shift = lane * 64 + n, m = (left >> shift) & MASK64, (right >> shift) & MASK64 + if op['name'] == 'rax1': + output = n ^ (((m * 2) & MASK64) | (m // (1 << 63))) + elif op['name'] == 'xar': + # Bit-index construction is independent of host shift/OR lowering. + source = n ^ m + output = sum(((source >> ((bit + op['amount']) % 64)) & 1) << bit for bit in range(64)) + else: + raise ValueError('unknown classic SHA3 mathematical operation') + value |= output << shift + state.v[op['d']][:] = [value & MASK64, value >> 64] + return state + + +def seed(initial, op, pattern, source=None, bit=None): + sources = [op['n'], op['m']] + ([op['a']] if 'a' in op else []) + if source is not None: + if source not in sources or bit is None or not 0 <= bit < 128: + raise ValueError('one-hot SHA3 witness needs a source role and bit0..127') + for register in sources: + initial.v[register][:] = [0, 0] + initial.v[source][:] = [int(bit < 64) << (bit % 64), int(bit >= 64) << (bit % 64)] + elif pattern < 8: + # Exhaustive independent Boolean triples on distinct-source witnesses. + for role, register in enumerate(sources): + low = MASK64 if pattern & (1 << (2 - role)) else 0 + initial.v[register][:] = [low, low ^ MASK64] + elif pattern == 8: + for register in range(32): + initial.v[register][:] = struct.unpack('<2Q', bytes((index + 17 * register) % 256 for index in range(16))) + elif pattern == 9: + for register in range(32): + initial.v[register][:] = [0xaaaaaaaaaaaaaaaa ^ register, 0x5555555555555555 ^ (register << 32)] + elif pattern != 10: + raise ValueError('unknown SHA3 input pattern') + return initial + + +def representatives(ops): + result = [] + for name, amount in [('eor3', None), ('bcax', None), ('rax1', None), + *[('xar', value) for value in (0, 1, 8, 16, 31, 32, 48, 63)]]: + for index, op in enumerate(ops): + sources = [op['n'], op['m']] + ([op['a']] if 'a' in op else []) + if (op['name'] == name and (amount is None or op['amount'] == amount) + and len(set([op['d'], *sources])) == len(sources) + 1): + result.append(index) + break + else: + raise AssertionError(f'Missing distinct-source SHA3 representative: {name}/{amount}') + return result + + +def initial_state(index, witness): + state = State() + rng = random.Random(index * 4096 + witness) + for register in range(31): + state.x[register] = rng.getrandbits(64) + state.sp = 0xfeed000000001000 + state.reserved = 0x51ad1234 + state.nzcv = (witness % 16) << 28 + seed_extended_state(state, index * 4096 + witness) + state.fpcr = STANDARD_CONTROLS[witness % len(STANDARD_CONTROLS)] + state.fpsr = 0x0800009f if witness & 1 else 0 + return state + + +def corpus(): + ops = functions() + cases = [] + selected = set(representatives(ops)) + runtime_aliases = set() + for name in FORMS: + for predicate in ( + lambda op: len({op[role] for role in ('d', 'n', 'm') + (('a',) if 'a' in op else ())}) == 1, + lambda op: op['d'] == 31): + runtime_aliases.add(next(index for index, op in enumerate(ops) if op['name'] == name and predicate(op))) + for index, op in enumerate(ops): + witnesses = [(pattern, None, None) for pattern in range(11)] + if index in selected: + sources = [op['n'], op['m']] + ([op['a']] if 'a' in op else []) + witnesses.extend((10, source, bit) for source in sources for bit in range(128)) + for witness, (pattern, source, bit) in enumerate(witnesses): + state = seed(initial_state(index, witness), op, pattern, source, bit) + cases.append({'function': index, 'label': f'pattern_{pattern}' if source is None else f'one_hot_v{source}_bit{bit}', + 'initial': bytes(state), + 'runtime': (index in selected and pattern in (0, 8) and source is None) + or (index in runtime_aliases and pattern == 9 and source is None)}) + if index in selected: + for control in EXTENDED_CONTROLS: + state = initial_state(index, control) + state.fpcr, state.fpsr = control, 0x0800009f + cases.append({'function': index, 'label': f'extended_control_{control:08x}', + 'initial': bytes(state), 'runtime': True}) + assert sum(record['runtime'] for record in cases) <= 96 + assert ctypes.sizeof(State) == 784 + return ops, cases diff --git a/dev/simd_fixtures/sha512.py b/dev/simd_fixtures/sha512.py new file mode 100644 index 0000000000..fd5586fb84 --- /dev/null +++ b/dev/simd_fixtures/sha512.py @@ -0,0 +1,140 @@ +"""Independent four-form SHA512 fixtures for the consolidated SIMD runner. + +Only original instruction words and complete input states live here. The runner +owns original/native execution, source maps, artifacts, cache and evidence credit. +""" +import random + +from differential import State, seed_extended_state + +FOCUS = 'sha512' +MASK = (1 << 64) - 1 +FORMS = { + 'sha512h': (0xce608000, 'SHA512H_QQV_cryptosha512_3'), + 'sha512h2': (0xce608400, 'SHA512H2_QQV_cryptosha512_3'), + 'sha512su0': (0xcec08000, 'SHA512SU0_VV2_cryptosha512_2'), + 'sha512su1': (0xce608800, 'SHA512SU1_VVV2_cryptosha512_3'), +} +CANONICAL_FORMS = tuple(canonical for _, canonical in FORMS.values()) +PATTERNS = 72 +ALIAS_LAYOUTS = ((0, 1, 2), (1, 1, 2), (2, 1, 2), (0, 1, 1), + (31, 31, 31), (0, 31, 31), (31, 29, 31), (31, 0, 1)) +UNARY_LAYOUTS = ((0, 1, 0), (1, 1, 0), (31, 31, 0), (31, 0, 0), (0, 31, 0)) + + +def operation(name, d=0, n=1, m=2): + if name not in FORMS or any(not 0 <= register < 32 for register in (d, n, m)): + raise ValueError('Invalid SHA512 form or vector register') + base, canonical = FORMS[name] + third = name != 'sha512su0' + return {'name': name, 'kind': FOCUS, 'd': d, 'n': n, 'm': m if third else None, + 'lane': 8, 'bytes': 16, 'scalar': False, 'output_kind': 'vector', + 'canonical_id': canonical, 'word': base | d | (n << 5) | (m << 16 if third else 0)} + + +def functions(): + result = [] + for name in FORMS: + layouts = UNARY_LAYOUTS if name == 'sha512su0' else ALIAS_LAYOUTS + result.extend(dict(operation(name, d, n, m), layout='alias') for d, n, m in layouts) + result.extend(dict(operation(name, d, (d + 5) % 32, (d + 13) % 32), layout='all_registers') + for d in range(32)) + return result + + +def expected(op, initial): + """Bitvector math independent of the selected x86 scalar/SSE2 recipes.""" + result = State.from_buffer_copy(initial) + w0, w1 = initial.v[op['d']] + x0, x1 = initial.v[op['n']] + + def rotate(value, amount): + return ((value >> amount) | (value << (64 - amount))) & MASK + + def large(value, rotations): + return rotate(value, rotations[0]) ^ rotate(value, rotations[1]) ^ rotate(value, rotations[2]) + + def small(value, rotations, amount): + return rotate(value, rotations[0]) ^ rotate(value, rotations[1]) ^ (value >> amount) + + def choose(x, y, z): + return (x & y) ^ ((~x & MASK) & z) + + def majority(x, y, z): + return (x & y) ^ (x & z) ^ (y & z) + + name = op['name'] + if name == 'sha512su0': + low = w0 + small(w1, (1, 8), 7) + high = w1 + small(x0, (1, 8), 7) + else: + y0, y1 = initial.v[op['m']] + if name == 'sha512su1': + low = w0 + small(x0, (19, 61), 6) + y0 + high = w1 + small(x1, (19, 61), 6) + y1 + elif name == 'sha512h': + high = (choose(y1, x0, x1) + large(y1, (14, 18, 41)) + w1) & MASK + temporary = (high + y0) & MASK + low = choose(temporary, y1, x0) + large(temporary, (14, 18, 41)) + w0 + elif name == 'sha512h2': + high = (majority(x0, y1, y0) + large(y0, (28, 34, 39)) + w1) & MASK + low = majority(high, y0, y1) + large(high, (28, 34, 39)) + w0 + else: + raise ValueError('Unknown SHA512 mathematical operation') + result.v[op['d']][:] = (low & MASK, high & MASK) + return result + + +def initial_state(function_index, pattern, flags): + if not 0 <= pattern < PATTERNS or flags not in (0, 15): + raise ValueError('Invalid SHA512 pattern or flags') + state = State() + generator = random.Random(0x51200000 + function_index * 4096 + pattern * 16 + flags) + for register in range(31): + state.x[register] = generator.getrandbits(64) + state.sp = generator.getrandbits(64) + state.nzcv = flags << 28 + state.reserved = 0x512ad123 + seed_extended_state(state, generator.getrandbits(64)) + for register in range(32): + if pattern == 0: + lanes = (0, 0) + elif pattern == 1: + lanes = (MASK, MASK) + elif pattern == 2: + lanes = (0xaaaaaaaaaaaaaaaa, 0x5555555555555555) + elif pattern == 3: + lanes = (0x0123456789abcdef ^ register, 0xfedcba9876543210 ^ (register << 32)) + elif pattern == 4: + lanes = (1 << 63, 1) + elif pattern == 5: + lanes = (MASK - register, register + 1) + elif pattern < 70: + bit = (pattern - 6 + register) % 64 + lanes = (1 << bit, MASK ^ (1 << ((bit + 17) % 64))) + else: + continue # Independent seeded random low/high qwords. + state.v[register][:] = lanes + state.fpsr = (state.fpsr & ~(1 << 27)) | ((1 << 27) if flags else 0) + return state + + +def corpus(): + operations, records = functions(), [] + seen = set() + for index, op in enumerate(operations): + # Each form has exhaustive one-bit and boundary patterns; each alias has + # eight boundaries/random states, and all register positions have two. + representative = op['name'] not in seen + patterns = range(PATTERNS) if representative else (0, 1, 2, 3, 4, 5, 70, 71) + if op['layout'] == 'all_registers': + patterns = (70, 71) + seen.add(op['name']) + for pattern in patterns: + for flags in (0, 15): + initial = initial_state(index, pattern, flags) + runtime = op['layout'] == 'alias' and ( + pattern in (0, 1, 4, 70, 71) if representative else pattern == 3) + records.append({'function': index, 'runtime': runtime, 'label': f'{op["name"]}/{op["layout"]}/{pattern}/{flags}', + 'pattern': pattern, 'flags': flags, 'initial': bytes(initial)}) + return operations, records diff --git a/dev/simd_original.py b/dev/simd_original.py new file mode 100644 index 0000000000..7c27ac5b4a --- /dev/null +++ b/dev/simd_original.py @@ -0,0 +1,451 @@ +#!/usr/bin/env python3 +"""Original-only full-state EL0 observer for register-only SIMD fixtures.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import socket +import struct +import subprocess +import tempfile +import time + +from differential import ROOT +INPUT_ADDRESS = 0x41000000 +OUTPUT_ADDRESS = 0x49000000 +MARKER_ADDRESS = 0x40070000 +SCRATCH_ADDRESS = 0x40072000 +TEXT_ADDRESS = 0x40080000 +INPUT_STRIDE = 800 +STATE_BYTES = 784 +RECORD_BYTES = 1024 +HEADER_BYTES = 1024 +FP_ACCESS_ENABLED = 3 << 20 +PSTATE_EL0T_MASKED = 0x3c0 +PSTATE_EL1H_MASKED = 0x3c5 +NZCV_MASK = 0xf0000000 +QEMU_FPCR_MASK = 0x07ff2007 +QEMU_FPSR_MASK = 0xf800009f +FPCR_TRAP_MASK = 0x9f00 +CPU_MODEL = 'max' +FPSR_QC = 1 << 27 +FPCR_NEP = 1 << 2 +SVC_IMMEDIATE = 0x123 +SVC_WORD = 0xd4000001 | (SVC_IMMEDIATE << 5) +RET_WORD = 0xd65f03c0 +COMPLETED_MARKER = 0x1234 +CPU_REGISTERS = ('CurrentEL', 'MIDR_EL1', 'ID_AA64PFR0_EL1', 'ID_AA64ISAR1_EL1', + 'ID_AA64PFR1_EL1', 'ID_AA64ZFR0_EL1', 'ID_AA64MMFR1_EL1', 'ID_AA64ISAR2_EL1', 'ID_AA64ISAR0_EL1') +LAYOUT = {'x': 0, 'sp': 248, 'spsr': 256, 'fpcr': 264, 'fpsr': 272, + 'esr': 280, 'elr': 288, 'current_el': 296, 'cpacr': 304, + 'marker': 312, 'v': 320, 'pre_fpcr': 832, 'pre_fpsr': 840} + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def json_bytes(value): + return (json.dumps(value, indent=2) + '\n').encode() + + +def write_new(path, data): + if path.exists(): + if path.read_bytes() != data: + raise AssertionError(f'Immutable evidence file changed: {path}') + else: + with path.open('xb') as file: + file.write(data) + + +def integer(value): + return int(value, 0) if isinstance(value, str) else value + + +def operation(function): + if 'operations' in function: + assert len(function['operations']) == 1 + return function['operations'][0] + return function + + +def load_corpus(directory): + names = ('functions.json', 'cases.json', 'inputs.bin', 'input-plan.json') + files = {name: (directory / name).read_bytes() for name in names} + functions = json.loads(files['functions.json']) + cases = json.loads(files['cases.json']) + inputs = files['inputs.bin'] + plan = json.loads(files['input-plan.json']) + for name, identity in plan['files'].items(): + assert sha(files[name]) == identity['sha256'], name + assert len(files[name]) == identity['bytes'], name + assert plan['cases'] == len(cases) and plan['functions'] == len(functions) + assert 0 < len(cases) <= 50000 + assert len(inputs) == len(cases) * INPUT_STRIDE + assert len(functions) > 0 + words = [] + for function in functions: + word = integer(operation(function)['word']) + assert 0 <= word < 1 << 32 + canonical_source = struct.pack('> shift & 65535},lsl#{shift}' + for shift in (16, 32, 48) if value >> shift & 65535) + return lines + + +def assembly(words, count): + lines = ['.arch armv8.7-a+fp16+sve', '.text', '.global _start', '_start:', + 'adrp x0,vectors', 'add x0,x0,:lo12:vectors', 'msr vbar_el1,x0', 'isb'] + lines += mov('x0', FP_ACCESS_ENABLED) + ['msr cpacr_el1,x0', 'isb'] + lines += mov('x1', OUTPUT_ADDRESS - HEADER_BYTES) + for index, register in enumerate(CPU_REGISTERS): + lines += [f'mrs x0,{register}', f'str x0,[x1,#{index * 8}]'] + lines += mov('x0', SCRATCH_ADDRESS) + for offset, value in ((0, INPUT_ADDRESS), (8, OUTPUT_ADDRESS), (16, count)): + lines += mov('x1', value) + [f'str x1,[x0,#{offset}]'] + lines += ['again:'] + mov('x0', SCRATCH_ADDRESS) + lines += ['ldr x19,[x0]', 'ldr x20,[x0,#8]', 'mov sp,x20', + 'ldr w0,[x19,#784]', 'msr fpcr,x0', 'mrs x0,fpcr', 'str x0,[sp,#832]', + 'ldr w0,[x19,#788]', 'msr fpsr,x0', 'mrs x0,fpsr', 'str x0,[sp,#840]', + 'ldr x0,[x19,#256]', 'msr sp_el0,x0', + 'ldr w0,[x19,#264]', f'and x0,x0,#{NZCV_MASK:#x}', + f'orr x0,x0,#{PSTATE_EL0T_MASKED:#x}', 'msr spsr_el1,x0', + 'adrp x0,functions', 'add x0,x0,:lo12:functions', + 'ldr x1,[x19]', 'ldr x0,[x0,x1,lsl#3]', 'msr elr_el1,x0'] + lines += [f'ldr q{register},[x19,#{272 + register * 16}]' for register in range(32)] + lines += ['mov x30,x19'] + lines += [f'ldp x{register},x{register + 1},[x30,#{8 + register * 8}]' + for register in range(0, 30, 2)] + lines += ['ldr x30,[x30,#248]', 'eret'] + for index, word in enumerate(words): + lines += [f'subject_{index}:', f'.inst 0x{word:08x}', f'svc #{SVC_IMMEDIATE}'] + lines += ['.balign 2048', 'vectors:'] + for _ in range(16): + lines += ['b exception_entry', '.space 124'] + lines += ['exception_entry:'] + lines += [f'stp x{register},x{register + 1},[sp,#{register * 8}]' + for register in range(0, 30, 2)] + lines += ['str x30,[sp,#240]'] + for register, offset in (('sp_el0', 248), ('spsr_el1', 256), ('fpcr', 264), + ('fpsr', 272), ('esr_el1', 280), ('elr_el1', 288), + ('CurrentEL', 296), ('cpacr_el1', 304)): + lines += [f'mrs x0,{register}', f'str x0,[sp,#{offset}]'] + lines += [f'str q{register},[sp,#{320 + register * 16}]' for register in range(32)] + lines += mov('x0', COMPLETED_MARKER) + ['str x0,[sp,#312]'] + lines += mov('x0', SCRATCH_ADDRESS) + lines += ['ldp x1,x2,[x0]', f'add x1,x1,#{INPUT_STRIDE}', + f'add x2,x2,#{RECORD_BYTES}', 'stp x1,x2,[x0]', + 'ldr x1,[x0,#16]', 'subs x1,x1,#1', 'str x1,[x0,#16]', 'b.eq finished', + 'adr x0,again', 'msr elr_el1,x0'] + lines += mov('x0', PSTATE_EL1H_MASKED) + ['msr spsr_el1,x0', 'eret', 'finished:'] + lines += mov('x0', MARKER_ADDRESS) + mov('x1', COMPLETED_MARKER) + lines += ['str x1,[x0]', 'completed: b completed', + '.section .rodata', '.balign 8', 'functions:'] + lines += [f'.quad subject_{index}' for index in range(len(words))] + return '\n'.join(lines) + '\n' + + +def tools_and_bindings(): + qemu = ROOT / '.tools/qemu/bin/qemu-system-aarch64' + if not qemu.is_file(): + qemu = Path(shutil.which('qemu-system-aarch64') or '') + clang = Path(shutil.which('clang') or '') + if os.uname().sysname == 'Darwin': + clang = Path(subprocess.check_output(['/usr/bin/xcrun', '--find', 'clang'], text=True).strip()) + candidates = sorted((ROOT / '.tools/rust/rustup/toolchains').glob('*/lib/rustlib/*/bin/rust-lld')) + lld = Path(shutil.which('ld.lld')) if shutil.which('ld.lld') else candidates[0] + assert all(path.is_file() for path in (qemu, clang, lld)) + qemu_executables = sorted((ROOT / '.tools/qemu/Cellar/qemu').glob('*/bin/qemu-system-aarch64')) + tools = {str(path): {'sha256': sha(path.read_bytes()), 'resolved_path': str(path.resolve())} + for path in (qemu, qemu.resolve(), clang, clang.resolve(), lld, lld.resolve(), *qemu_executables)} + return qemu, clang, lld, {'tools': tools, + 'qemu_version': subprocess.check_output([str(qemu), '--version'], text=True).splitlines()[0], + 'clang_version': subprocess.check_output([str(clang), '--version'], text=True).splitlines()[0], + 'producer_sha256': sha(Path(__file__).read_bytes())} + + +def elf_subjects(path, words, functions): + """Read ELF64 symbols/sections directly; inspect the actual linked instruction bytes.""" + data = path.read_bytes() + assert data[:6] == b'\x7fELF\x02\x01' + header = struct.unpack_from('<16sHHIQQQIHHHHHH', data) + section_offset, section_stride, section_count = header[6], header[11], header[12] + assert section_stride == 64 + sections = [struct.unpack_from(' deadline: + raise AssertionError('QEMU failed before QMP connection') + time.sleep(0.02) + connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + connection.settimeout(10) + connection.connect(str(endpoint)) + stream = connection.makefile('rwb') + json.loads(stream.readline()) + + def request(name, arguments=None): + data = {'execute': name} + if arguments is not None: + data['arguments'] = arguments + stream.write(json.dumps(data).encode() + b'\n') + stream.flush() + while True: + reply = json.loads(stream.readline()) + if 'error' in reply: + raise AssertionError(reply) + if 'return' in reply: + return reply['return'] + + request('qmp_capabilities') + request('cont') + deadline = time.monotonic() + 60 + while True: + marker = request('human-monitor-command', {'command-line': f'xp /1gx {MARKER_ADDRESS:#x}'}) + if marker.strip().endswith(f'{COMPLETED_MARKER:#018x}'): + break + if process.poll() is not None or time.monotonic() > deadline: + raise AssertionError(f'Original oracle timeout/failure: {marker}') + time.sleep(0.02) + request('stop') + size = HEADER_BYTES + count * RECORD_BYTES + request('human-monitor-command', {'command-line': f'pmemsave {OUTPUT_ADDRESS - HEADER_BYTES:#x} {size} "{destination / "results.bin"}"'}) + request('quit') + process.wait(timeout=5) + finally: + if stream is not None: + stream.close() + if connection is not None: + connection.close() + if process.poll() is None: + process.kill() + process.wait(timeout=5) + + +def validate_results(destination, functions, cases, inputs, subjects): + results = (destination / 'results.bin').read_bytes() + assert len(results) == HEADER_BYTES + len(cases) * RECORD_BYTES + controls, trap_observations, status_deltas = {}, [], {} + for index in range(len(cases)): + input_offset = index * INPUT_STRIDE + function_index = struct.unpack_from('> 26 == 0x15 and observed['esr'] & 65535 == SVC_IMMEDIATE, (index, 'genuine_svc') + assert observed['elr'] == subjects[function_index]['expected_elr'], (index, 'elr') + assert observed['current_el'] == 4 and observed['cpacr'] == FP_ACCESS_ENABLED, (index, 'access') + assert observed['marker'] == COMPLETED_MARKER, (index, 'marker') + op = operation(functions[function_index]) + word = integer(op['word']) + destination_register = op['d'] + for register in range(32): + if op['output_kind'] != 'vector' or register != destination_register: + assert record[320 + register * 16:336 + register * 16] == initial[264 + register * 16:280 + register * 16], (index, 'non_destination_v', register) + if op['output_kind'] == 'vector': + destination_offset = LAYOUT['v'] + destination_register * 16 + if op['scalar']: + lane_bytes = op['lane'] + merge_register = op['n'] if op['merge'] == 'left_if_nep' else op['d'] + merge_offset = 264 + merge_register * 16 + expected_upper = (initial[merge_offset + lane_bytes:merge_offset + 16] + if pre_fpcr & FPCR_NEP and op['merge'] != 'none' else bytes(16 - lane_bytes)) + assert record[destination_offset + lane_bytes:destination_offset + 16] == expected_upper, (index, 'declared_scalar_merge_or_clear') + elif op['bytes'] == 8: + assert record[destination_offset + 8:destination_offset + 16] == bytes(8), (index, 'vector64_upper_zero') + controls.setdefault(str(requested_fpcr), set()).add(pre_fpcr) + delta = observed['fpsr'] & ~pre_fpsr + status_deltas[str(delta)] = status_deltas.get(str(delta), 0) + 1 + if requested_fpcr & FPCR_TRAP_MASK: + trap_observations.append({'case': index, 'function_index': function_index, + 'requested_fpcr': requested_fpcr, 'pre_fpcr': pre_fpcr, + 'post_fpcr': observed['fpcr'], 'classification': 'requested_trap_enables_raz_wi'}) + return {'cpu_registers': dict(zip(CPU_REGISTERS, map(hex, struct.unpack_from('<9Q', results)))), + 'fpcr_requested_readbacks': {key: sorted(value) for key, value in controls.items()}, + 'trap_enable_readback_cases': trap_observations, 'observed_new_fpsr_masks': status_deltas} + + +def capture(prepared, directory, focus): + directory = Path(directory).resolve() + destination, qemu, bindings, functions, cases, inputs, subjects = prepared + if destination.parent != directory or bindings['focus'] != focus: + raise AssertionError('Original observer preparation/capture configuration differs') + receipt_path = destination / 'receipt.json' + if receipt_path.exists(): + receipt = json.loads(receipt_path.read_bytes()) + for name, info in receipt['files'].items(): + assert sha((destination / name).read_bytes()) == info['sha256'], name + else: + if not (destination / 'results.bin').exists(): + execute(destination, qemu, len(cases)) + observations = validate_results(destination, functions, cases, inputs, subjects) + files = {path.name: {'sha256': sha(path.read_bytes()), 'bytes': path.stat().st_size} + for path in sorted(destination.iterdir()) if path.is_file() and path.name != 'receipt.json'} + receipt = {'kind': focus + '_original_el0_full_frame_qemu', + 'passed_transport_and_architectural_frame_checks': True, + 'cases': len(cases), 'functions': len(functions), 'cpu': CPU_MODEL, + 'directory': str(destination.relative_to(ROOT)), **bindings, **observations, + 'input_stride': INPUT_STRIDE, 'state_bytes': STATE_BYTES, + 'results_header_bytes': HEADER_BYTES, 'results_stride': RECORD_BYTES, + 'snapshot_layout': LAYOUT, 'files': files, + 'checks': ['Each exact original SIMD instruction runs at EL0t with all 31 GPRs, SP_EL0, 32 full vectors, NZCV, FPCR and FPSR restored from the retained input.', + 'A genuine SVC follows the subject; the EL1 handler snapshots all GPRs before transport clobbers and all vectors before transport resumes.', + 'All GPRs/SP, NZCV and non-destination vectors are unchanged. Scalars merge the declared original destination/left source under NEP or clear inactive bits; vector64 upper clears. QC and sticky flags preserve.', + 'Actual preinstruction FPCR/FPSR readbacks, genuine SVC ESR, exact linked subject/SVC bytes and ELR identify every execution.'], + 'limits': ['Original QEMU emulator observations only; no native execution, mathematical result-model validation, Apple hardware proof, or performance credit.', + 'Canonical function identity is original SIMD word plus RET through the unused per-function return register. This EL0 fixture executes the unchanged SIMD word followed by SVC; the original RET is not executed.', + 'QEMU trap enables are RAZ/WI. Exact requested and actual controls are retained; no FP trap-delivery credit is claimed.', + 'State.reserved is retained input metadata, not an architectural register; general guest RAM effects are not applicable to these register-only subjects.', + 'EL2/EL3/security, streaming modes and access-disabled execution are outside this fixture.']} + write_new(receipt_path, json_bytes(receipt)) + pointer = {'kind': focus + '_original_oracle_capture_pointer', + 'directory': str(destination.relative_to(ROOT)), + 'receipt': {'path': str(receipt_path.relative_to(ROOT)), + 'sha256': sha(receipt_path.read_bytes()), 'bytes': receipt_path.stat().st_size}, + 'files': receipt['files']} + pointer_path = directory / 'receipt.json' + if pointer_path.exists(): + history = directory / 'pointer-history' + history.mkdir(exist_ok=True) + previous = pointer_path.read_bytes() + write_new(history / f'{sha(previous)}.json', previous) + next_pointer = directory / 'receipt.next.json' + next_pointer.write_bytes(json_bytes(pointer)) + os.replace(next_pointer, pointer_path) + return receipt_path + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--directory', type=Path, required=True) + parser.add_argument('--focus', required=True) + parser.add_argument('--source-bindings', type=Path, required=True) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument('--prepare', action='store_true') + group.add_argument('--capture', action='store_true') + arguments = parser.parse_args() + source_bindings = json.loads(arguments.source_bindings.read_bytes()) + prepared = prepare(arguments.directory, arguments.focus, source_bindings) + if arguments.capture: + path = capture(prepared, arguments.directory, arguments.focus) + print(json.dumps({'receipt': str(path), 'sha256': sha(path.read_bytes())})) + else: + destination = prepared[0] + print(json.dumps({'prepared': str(destination), 'functions': len(prepared[3]), + 'cases': len(prepared[4]), 'guest_elf_sha256': sha((destination / 'guest.elf').read_bytes())})) diff --git a/dev/test_scalar_isa.py b/dev/test_scalar_isa.py index 70d8ad6f27..ed5d1df83d 100644 --- a/dev/test_scalar_isa.py +++ b/dev/test_scalar_isa.py @@ -694,5 +694,75 @@ OPERANDS: REG0:rw MEM0:r x86_mappings.safe_artifact(root, '../outside') +class CsscIntegerOracleTests(unittest.TestCase): + def test_abs_minimum_counts_zero_and_all_bit_positions(self): + for width in (32, 64): + sign, mask = 1 << (width - 1), (1 << width) - 1 + absolute = math.cssc_operation(f'ABS{width}') + count = math.cssc_operation(f'CNT{width}') + trailing = math.cssc_operation(f'CTZ{width}') + self.assertEqual(math.cssc_value(absolute, sign), sign) + self.assertEqual(math.cssc_value(absolute, mask), 1) + self.assertEqual(math.cssc_value(trailing, 0), width) + for bit in range(width): + self.assertEqual(math.cssc_value(trailing, 1 << bit), bit) + self.assertEqual(math.cssc_value(count, 1 << bit), 1) + for population in range(width + 1): + self.assertEqual(math.cssc_value(count, (1 << population) - 1), population) + if width == 32: + self.assertEqual(math.cssc_value(absolute, 0xdeadc0de80000000), sign) + self.assertEqual(math.cssc_value(trailing, 0xffffffff00000000), width) + self.assertEqual(math.cssc_value(count, 0xffffffff00000000), 0) + + def test_signed_immediate_and_overflow_ordering_are_distinct_from_unsigned(self): + for width in (32, 64): + sign, mask = 1 << (width - 1), (1 << width) - 1 + self.assertEqual(math.cssc_value(math.cssc_operation(f'SMIN{width}'), sign, sign - 1), sign) + self.assertEqual(math.cssc_value(math.cssc_operation(f'SMAX{width}'), sign, sign - 1), sign - 1) + self.assertEqual(math.cssc_value(math.cssc_operation(f'UMIN{width}'), sign, sign - 1), sign - 1) + self.assertEqual(math.cssc_value(math.cssc_operation(f'UMAX{width}'), sign, sign - 1), sign) + for raw in range(256): + signed = raw if raw < 128 else raw - 256 + signed_max = math.cssc_operation(f'SMAX{width}I', immediate=raw) + unsigned_max = math.cssc_operation(f'UMAX{width}I', immediate=raw) + self.assertEqual(math.cssc_value(signed_max, sign), signed & mask) + self.assertEqual(math.cssc_value(unsigned_max, 0), raw) + self.assertEqual(math.cssc_value(signed_max, signed & mask), signed & mask) + + def test_sequential_alias_zero_and_w_results_preserve_all_other_state(self): + initial = State() + initial.x[1] = 0xdeadc0deffffffff + initial.x[2] = 0xffffffffffffffff + initial.sp, initial.nzcv, initial.reserved = 0x1230, 0xf0000000, 0x43535343 + initial.fpcr, initial.fpsr = 0x07c89f07, 0x0800009f + operations = [math.cssc_operation('ABS32', 1, 1), + math.cssc_operation('CTZ64', 2, 1), + math.cssc_operation('CNT32', 0, 2), + math.cssc_operation('SMIN64I', 3, 0, immediate=0xff), + math.cssc_operation('ABS64', 31, 3), + math.cssc_operation('CTZ32', 4, 31)] + expected = complete_state(initial) + expected['x'][0:5] = [0, 1, 0, math.MASK, 32] + self.assertEqual(math.cssc_mathematical_reference(operations, initial), expected) + self.assertEqual(initial.x[1], 0xdeadc0deffffffff) + + def test_corpus_is_bounded_complete_and_keeps_all_raw_immediate_fields(self): + functions, records = math.cssc_corpus() + self.assertEqual(len({operation['canonical_id'] for operation in functions}), 22) + self.assertEqual(len({operation['word'] for operation in functions}), len(functions)) + self.assertLess(len(records), 50000) + for form, (_, _, kind) in math.CSSC_FORMS.items(): + selected = [operation for operation in functions if operation['form'] == form] + if kind == 'unary': + self.assertEqual({operation['d'] for operation in selected}, set(range(32))) + self.assertEqual({operation['n'] for operation in selected}, set(range(32))) + self.assertTrue(any(operation['d'] == operation['n'] == 31 for operation in selected)) + if kind == 'immediate': + self.assertEqual({operation['raw_imm8'] for operation in selected}, set(range(256))) + controls = {State.from_buffer_copy(record['initial']).fpcr for record in records} + for bit in (8, 9, 10, 11, 12, 15): + self.assertIn(1 << bit, controls) + + if __name__ == "__main__": unittest.main() diff --git a/dev/test_simd_fixtures.py b/dev/test_simd_fixtures.py new file mode 100644 index 0000000000..f6444553d9 --- /dev/null +++ b/dev/test_simd_fixtures.py @@ -0,0 +1,528 @@ +"""Pure family models and focused shared-runner infrastructure guards.""" +import ctypes +import importlib +import json +from pathlib import Path +import struct +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch +from contextlib import nullcontext + +from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM +from differential import ROOT, BASE, State, seed_extended_state +from simd_fixtures import aes, sha12, sha512, sha3, i8mm +import simd_fixture_runner as runner +import simd_original + +engine = importlib.import_module('simd-differential') + +class AesFixtureTests(unittest.TestCase): + def test_published_substitution_and_column_anchors(self): + self.assertEqual(aes.SBOX[0], 99) + self.assertEqual(aes.SBOX[83], 237) + self.assertEqual(aes.INVERSE_SBOX[99], 0) + self.assertEqual(aes.INVERSE_SBOX[237], 83) + original = bytes.fromhex('d4bf5d30') + bytes(12) + mixed = bytes.fromhex('046681e5') + bytes(12) + self.assertEqual(aes.mix_columns(original), mixed) + self.assertEqual(aes.mix_columns(mixed, True), original) + + def test_every_register_encoding_and_bounded_runtime_corpus(self): + (functions, records) = aes.corpus() + self.assertEqual(len(functions), 4096) + self.assertEqual(len(records), 4880) + self.assertEqual(len({op['word'] for op in functions}), 4096) + self.assertEqual({op['canonical_id'] for op in functions}, set(aes.CANONICAL_FORMS)) + for op in functions: + self.assertEqual(op['word'] & aes.FORM_MASK, aes.FORM_VALUES[op['name']]) + runtime = [record for record in records if record['runtime']] + self.assertEqual(len(runtime), 60) + self.assertEqual({functions[record['function']]['name'] for record in runtime}, set(aes.FORM_VALUES)) + self.assertTrue(all((len(record['initial']) == 784 for record in records))) + + def test_aliases_and_complete_unrelated_state_preservation(self): + for (name, byte) in [('aese', 99), ('aesd', 82)]: + initial = aes.initial_state(17) + result = aes.expected(aes.operation(name, 31, 31), initial) + self.assertEqual(aes.vector_bytes(result, 31), bytes([byte] * 16)) + self.assertEqual(bytes(result)[:aes.State.v.offset + 31 * 16], bytes(initial)[:aes.State.v.offset + 31 * 16]) + self.assertEqual(bytes(result)[aes.State.v.offset + 32 * 16:], bytes(initial)[aes.State.v.offset + 32 * 16:]) + for name in aes.FORM_VALUES: + initial = aes.initial_state(23) + result = aes.expected(aes.operation(name, 7, 31), initial) + start = aes.State.v.offset + 7 * 16 + self.assertEqual(bytes(result)[:start], bytes(initial)[:start]) + self.assertEqual(bytes(result)[start + 16:], bytes(initial)[start + 16:]) + + def test_linear_inverse_on_every_column_basis_bit(self): + for bit in range(128): + value = (1 << bit).to_bytes(16, 'little') + self.assertEqual(aes.mix_columns(aes.mix_columns(value), True), value) + + def test_independent_host_aes_feature_policy(self): + self.assertEqual(aes.optional_opcodes('x86_64-baseline'), set()) + self.assertEqual(aes.optional_opcodes('x86_64-baseline+ssse3'), {'pshufb'}) + expected = {'aesenclast', 'aesdeclast', 'aesenc', 'aesimc'} + self.assertEqual(aes.optional_opcodes('x86_64-baseline+aes'), expected) + self.assertEqual(aes.optional_opcodes('x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+aes'), expected) + + +class Sha12FixtureTests(unittest.TestCase): + def test_sha12_exact_source_forms_alias_roles_and_bounded_full_state_corpus(self): + (ops, records) = sha12.corpus() + facts = {row['id']: row for row in json.loads((ROOT / 'tests/isa/a64-documented-checklist.json').read_text())['forms']} + self.assertEqual((len(ops), len(records), len(sha12.CANONICAL_FORMS)), (98, 25088, 10)) + self.assertEqual({op['canonical_id'] for op in ops}, set(sha12.CANONICAL_FORMS)) + decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) + for op in ops: + fact = facts[op['canonical_id']] + self.assertEqual(op['word'] & int(fact['encoding_mask'], 0), int(fact['encoding_value'], 0)) + self.assertEqual([row.mnemonic for row in decoder.disasm(struct.pack('> 28 for row in records}, set(range(16))) + self.assertEqual({State.from_buffer_copy(row['initial']).fpcr for row in selected}, {0, 130023424, 524288, 130547712}) + for row in selected: + initial = State.from_buffer_copy(row['initial']) + op = ops[row['function']] + result = sha12.expected(op, initial) + result.v[op['d']][:] = initial.v[op['d']] + self.assertEqual(bytes(result), bytes(initial)) + + def test_sha12_h_scalar_clearing_and_independent_features(self): + op = sha12.operation('sha1h', d=31, n=31) + initial = State() + initial.v[31][:] = [18446744073709551615, 18446744073709551615] + initial.fpcr = 4294967295 + initial.fpsr = 4294967295 + initial.nzcv = 4026531840 + result = sha12.expected(op, initial) + self.assertEqual(list(result.v[31]), [4294967295, 0]) + self.assertEqual((result.fpcr, result.fpsr, result.nzcv), (initial.fpcr, initial.fpsr, initial.nzcv)) + for target in ('x86_64-baseline', 'x86_64-baseline+pclmulqdq+fma+f16c'): + self.assertEqual(sha12.optional_opcodes(target), set()) + self.assertEqual(sha12.optional_opcodes('x86_64-baseline+ssse3+sse4.1+sse4.2'), {'palignr'}) + self.assertEqual(sha12.optional_opcodes('x86_64-baseline+sha'), {'sha1rnds4', 'sha1msg2', 'sha256rnds2', 'sha256msg1', 'sha256msg2'}) + self.assertEqual(sha12.optional_opcodes('x86_64-baseline+ssse3+sha'), {'palignr', 'sha1rnds4', 'sha1msg2', 'sha256rnds2', 'sha256msg1', 'sha256msg2'}) + + +class Sha512FixtureTests(unittest.TestCase): + def test_sha512_fixtures_bind_four_exact_forms_aliases_and_complete_corpus(self): + (functions, records) = sha512.corpus() + self.assertEqual((len(functions), len(records)), (157, 1488)) + self.assertEqual(sum((record['runtime'] for record in records)), 90) + self.assertEqual(len({operation['word'] for operation in functions}), 157) + self.assertEqual({operation['canonical_id'] for operation in functions}, set(sha512.CANONICAL_FORMS)) + facts = {row['id']: row for row in json.loads((ROOT / 'tests/isa/a64-documented-checklist.json').read_bytes())['forms']} + decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) + for operation in functions: + fact = facts[operation['canonical_id']] + self.assertEqual(operation['word'] & int(fact['encoding_mask'], 0), int(fact['encoding_value'], 0)) + self.assertEqual([instruction.mnemonic for instruction in decoder.disasm(struct.pack('> (bit + amount) % 64 & 1) << bit for bit in range(64))) + + def rounds(state, words): + (a, b, c, d, e, f, g, h) = state + for word in words: + sigma1 = rotate(e, 14) ^ rotate(e, 18) ^ rotate(e, 41) + sigma0 = rotate(a, 28) ^ rotate(a, 34) ^ rotate(a, 39) + choose = (f ^ g) & e ^ g + majority = a & b | (a | b) & c + first = h + sigma1 + choose + word & mask + second = sigma0 + majority & mask + (a, b, c, d, e, f, g, h) = (first + second & mask, a, b, c, d + first & mask, e, f, g) + return (a, b, c, d, e, f, g, h) + for (index, operation) in enumerate(sha512.functions()): + if operation['name'] not in ('sha512h', 'sha512h2'): + continue + for pattern in (1, 3, 70): + initial = sha512.initial_state(index, pattern, 15) + (w0, w1) = initial.v[operation['d']] + (x0, x1) = initial.v[operation['n']] + (y0, y1) = initial.v[operation['m']] + if operation['name'] == 'sha512h': + synthetic = (0, 0, -x1 & mask, y0, y1, x0, x1, 0) + (a, b, c, d, e, f, g, h) = rounds(synthetic, (w1, w0)) + reference = [e, f - y0 & mask] + else: + synthetic = (y0, y1, x0, -w1 & mask, 0, 0, 0, 0) + (a, b, c, d, e, f, g, h) = rounds(synthetic, (w1, w0)) + reference = [a, b] + observed = sha512.expected(operation, initial) + self.assertEqual(list(observed.v[operation['d']]), reference) + observed.v[operation['d']][:] = initial.v[operation['d']] + self.assertEqual(bytes(observed), bytes(initial)) + + def test_sha512_schedule_lane_order_old_destination_and_unused_high_source(self): + mask = (1 << 64) - 1 + initial = sha512.initial_state(0, 0, 15) + initial.v[0][:] = [7, 11] + initial.v[1][:] = [13, 17] + initial.v[2][:] = [19, 23] + + def small(value, rotations, amount): + rotated = [sum(((value >> (bit + rotation) % 64 & 1) << bit for bit in range(64))) for rotation in rotations] + return rotated[0] ^ rotated[1] ^ value // (1 << amount) + expected = {'sha512su0': [7 + small(11, (1, 8), 7) & mask, 11 + small(13, (1, 8), 7) & mask], 'sha512su1': [7 + small(13, (19, 61), 6) + 19 & mask, 11 + small(17, (19, 61), 6) + 23 & mask]} + for name in expected: + operation = sha512.operation(name) + output = sha512.expected(operation, initial) + self.assertEqual(list(output.v[0]), expected[name]) + output.v[0][:] = initial.v[0] + self.assertEqual(bytes(output), bytes(initial)) + for name in ('sha512h2', 'sha512su0'): + operation = sha512.operation(name) + original = sha512.expected(operation, initial) + poisoned = State.from_buffer_copy(initial) + poisoned.v[1][1] ^= mask + output = sha512.expected(operation, poisoned) + self.assertEqual(list(output.v[0]), list(original.v[0])) + alias = sha512.operation('sha512su0', d=31, n=31) + initial.v[31][:] = [7, 11] + self.assertEqual(list(sha512.expected(alias, initial).v[31]), [7 + small(11, (1, 8), 7) & mask, 11 + small(7, (1, 8), 7) & mask]) + + +class Sha3FixtureTests(unittest.TestCase): + def test_sha3_inventory_all_immediates_equality_partitions_and_v31_roles(self): + functions = sha3.functions() + facts = {row['id']: row for row in json.loads((ROOT / 'tests/isa/a64-documented-checklist.json').read_bytes())['forms']} + self.assertEqual(len({operation['word'] for operation in functions}), len(functions)) + self.assertEqual({operation['canonical_id'] for operation in functions}, set(sha3.CANONICAL_FORMS)) + decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) + for operation in functions: + fact = facts[operation['canonical_id']] + self.assertEqual(operation['word'] & int(fact['encoding_mask'], 0), int(fact['encoding_value'], 0)) + self.assertEqual([instruction.mnemonic for instruction in decoder.disasm(struct.pack('> 63) for value in initial.v[31]] + self.assertEqual(bytes(actual), bytes(expected), name) + self.assertEqual(ctypes.sizeof(State), 784) + (functions, records) = sha3.corpus() + self.assertEqual({record['function'] for record in records}, set(range(len(functions)))) + self.assertTrue(all((len(record['initial']) == 784 for record in records))) + policy = [record for record in records if record['label'].startswith('extended_control_')] + self.assertEqual(len(policy), 11 * 6) + self.assertTrue(all(('original' not in record and 'oracle_limit' not in record for record in records))) + self.assertLessEqual(sum((record['runtime'] for record in records)), 96) + self.assertEqual({State.from_buffer_copy(record['initial']).fpcr for record in policy}, set(sha3.EXTENDED_CONTROLS)) + representatives = set(sha3.representatives(functions)) + for index in representatives: + matching = [record for record in records if record['function'] == index and (not record['label'].startswith('extended_control_'))] + self.assertEqual({State.from_buffer_copy(record['initial']).nzcv >> 28 for record in matching}, set(range(16))) + self.assertEqual({State.from_buffer_copy(record['initial']).fpcr for record in matching}, set(sha3.STANDARD_CONTROLS)) + original = bytes(initial) + for operation in sha3.chain(): + initial = sha3.expected(operation, initial) + self.assertNotEqual(bytes(initial), original) + + +class I8mmFixtureTests(unittest.TestCase): + def test_i8mm_canonical_layouts_register_roles_and_encoded_fields(self): + ops = i8mm.functions() + self.assertEqual((len(ops), len({op['word'] for op in ops})), (798, 798)) + layouts = {(op['name'], op['bytes'], op['index']) for op in ops} + self.assertEqual(len(layouts), 21) + facts = {row['id']: row for row in json.loads((ROOT / 'tests/isa/a64-documented-checklist.json').read_bytes())['forms']} + for op in ops: + fact = facts[op['canonical_id']] + self.assertEqual(op['word'] & int(fact['encoding_mask'], 0), int(fact['encoding_value'], 0)) + self.assertEqual((op['word'] & 31, op['word'] >> 5 & 31, op['word'] >> 16 & 31), (op['d'], op['n'], op['m'])) + if op['index'] is not None: + self.assertEqual((op['word'] >> 11 & 1) << 1 | op['word'] >> 21 & 1, op['index']) + self.assertEqual({op['canonical_id'] for op in ops}, set(i8mm.CANONICAL_FORMS)) + for layout in layouts: + selected = [op for op in ops if (op['name'], op['bytes'], op['index']) == layout] + for role in ('d', 'n', 'm'): + self.assertEqual({op[role] for op in selected}, set(range(32))) + for (args, options) in ((('smmla', 8), {}), (('ummla', 16, 0), {}), (('sudot', 16), {}), (('usdot', 16, 4), {}), (('usdot', 8), {'m': 32})): + with self.assertRaises(ValueError): + i8mm.operation(*args, **options) + + def test_i8mm_matrix_column_storage_row_order_and_wrapped_addend(self): + state = State() + state.v[1][:] = struct.unpack('<2Q', bytes([1] + [0] * 7 + [0, 2] + [0] * 6)) + state.v[2][:] = struct.unpack('<2Q', bytes([3] + [0] * 7 + [0, 4] + [0] * 6)) + state.v[0][:] = struct.unpack('<2Q', struct.pack('<4I', 4294967295, 2147483647, 2147483648, 4294967294)) + for name in i8mm.MATRIX_BASES: + actual = i8mm.expected(i8mm.operation(name), state) + self.assertEqual(struct.unpack('<4I', struct.pack('<2Q', *actual.v[0])), (2, 2147483647, 2147483648, 6)) + (state.v[1][:], state.v[2][:], state.v[0][:]) = ([9259542123273814144] * 2, [18446744073709551615] * 2, [0, 0]) + for (name, expected) in (('smmla', 1024), ('ummla', 261120), ('usmmla', -1024 & 4294967295)): + actual = i8mm.expected(i8mm.operation(name), state) + self.assertEqual(struct.unpack('<4I', struct.pack('<2Q', *actual.v[0])), (expected,) * 4) + + def test_i8mm_index_reads_all_vm_bits_and_writes_only_destination(self): + for name in ('usdot', 'sudot'): + op = i8mm.operation(name, 8, 3, m=31) + state = State() + seed_extended_state(state, 123) + state.v[0][:] = [0, 18446744073709551615] + (left, right) = (bytes([255]) * 8 + bytes([128]) * 8, bytes(12) + bytes([128]) * 4) + if name == 'sudot': + (left, right) = (bytes([128]) * 16, bytes(12) + bytes([255]) * 4) + (state.v[1][:], state.v[31][:]) = (struct.unpack('<2Q', left), struct.unpack('<2Q', right)) + before = bytes(state) + actual = i8mm.expected(op, state) + expected = State.from_buffer_copy(state) + value = -130560 & 4294967295 + expected.v[0][:] = [value | value << 32, 0] + self.assertEqual(bytes(actual), bytes(expected)) + self.assertEqual(bytes(state), before) + + def test_i8mm_all_aliases_use_snapshots_and_never_saturate(self): + state = State() + state.v[31][:] = [72340172838076673] * 2 + actual = i8mm.expected(i8mm.operation('smmla', d=31, n=31, m=31), state) + self.assertEqual(list(actual.v[31]), [72340207197815049] * 2) + for name in ('usdot', 'sudot'): + state.v[1][:] = [9187201950435737471] * 2 if name == 'sudot' else [18446744073709551615] * 2 + state.v[2][:] = [18446744073709551615] * 2 if name == 'sudot' else [9187201950435737471] * 2 + state.v[0][:] = [0, 0] + state.fpsr = 134217759 + op = i8mm.operation(name, 16, 0 if name == 'sudot' else None) + actual = i8mm.expected(op, state) + self.assertEqual(struct.unpack('<4I', struct.pack('<2Q', *actual.v[0])), (129540,) * 4) + self.assertEqual(actual.fpsr, state.fpsr) + + def test_i8mm_corpus_and_runtime_budget_cover_every_layout_and_control(self): + (ops, records) = i8mm.corpus() + self.assertEqual((len(ops), len(records)), (798, 13440)) + self.assertEqual({record['function'] for record in records}, set(range(798))) + runtime = [record for record in records if record['runtime']] + self.assertEqual(len(runtime), 95) + self.assertEqual({(ops[r['function']]['name'], ops[r['function']]['bytes'], ops[r['function']]['index']) for r in runtime}, {(op['name'], op['bytes'], op['index']) for op in ops}) + self.assertEqual({State.from_buffer_copy(r['initial']).fpcr >> 22 & 3 for r in runtime}, {0, 1, 2, 3}) + self.assertEqual({bool(State.from_buffer_copy(r['initial']).fpsr & i8mm.FPSR_QC) for r in runtime}, {False, True}) + self.assertEqual(i8mm.optional_opcodes('x86_64-baseline+fma'), set()) + self.assertEqual(i8mm.optional_opcodes('x86_64-baseline+ssse3+sse4.1'), {'phaddd'}) + + +class FixtureRunnerTests(unittest.TestCase): + def setUp(self): + self.op = sha3.operation('eor3', d=0, n=1, m=2, a=3) + initial = State() + seed_extended_state(initial, 1234) + initial.x[30] = engine.STOP + self.initial = initial + self.family = SimpleNamespace(FOCUS='sha3', CANONICAL_FORMS=(self.op['canonical_id'],), + functions=lambda:[self.op], corpus=lambda:([self.op], [{'function':0, 'label':'toy', 'initial':bytes(initial), 'runtime':True}]), + expected=sha3.expected) + + def test_interface_rejects_missing_form_runtime_and_short_state(self): + operations, records = runner.fixture_corpus(self.family) + self.assertEqual((len(operations), len(records)), (1, 1)) + self.assertEqual(operations[0]['merge'], 'none') + self.family.corpus = lambda:([self.op], [{'function':0, 'label':'toy', 'initial':bytes(self.initial), 'runtime':False}]) + with self.assertRaisesRegex(AssertionError, 'runtime selection'): + runner.fixture_corpus(self.family) + self.family.corpus = lambda:([self.op], [{'function':0, 'label':'toy', 'initial':bytes(7), 'runtime':True}]) + with self.assertRaisesRegex(AssertionError, 'framing'): + runner.fixture_corpus(self.family) + + def test_expected_model_cannot_modify_fp_status_or_input_state(self): + original = bytes(self.initial) + runner.expected_state(self.family, self.op, self.initial) + self.assertEqual(bytes(self.initial), original) + def bad_model(operation, initial): + initial.fpsr ^= 1 + return initial + self.family.expected = bad_model + with self.assertRaisesRegex(AssertionError, 'outside its destination'): + runner.expected_state(self.family, self.op, self.initial) + self.assertEqual(bytes(self.initial), original) + + def test_repeated_model_replays_accumulator_instead_of_reusing_first_result(self): + def accumulating(operation, initial): + state = State.from_buffer_copy(initial) + state.v[operation['d']][0] = (state.v[operation['d']][0] + 7) & ((1 << 64) - 1) + return state + self.family.expected = accumulating + one = runner.apply_operations(self.family, [self.op], self.initial) + three = runner.apply_operations(self.family, [self.op] * 3, self.initial) + self.assertEqual((three.v[0][0] - one.v[0][0]) & ((1 << 64) - 1), 14) + self.assertNotEqual(bytes(three), bytes(one)) + + def test_admission_uses_independent_decoder_before_mocked_compiler(self): + with tempfile.TemporaryDirectory() as temporary: + with patch.object(engine.subprocess, 'check_output', side_effect=RuntimeError('compiler reached')) as compile_call: + with self.assertRaisesRegex(RuntimeError, 'compiler reached'): + engine.compile_batch(Path('mock-stela'), Path(temporary), [{'operations':[self.op]}], 0, + allowed_mnemonics={'eor3'}) + self.assertEqual(compile_call.call_count, 1) + with self.assertRaisesRegex(AssertionError, 'Independent decoder'): + engine.compile_batch(Path('mock-stela'), Path(temporary), [{'operations':[self.op]}], 0, + allowed_mnemonics={'not-the-decoded-instruction'}) + self.assertEqual(compile_call.call_count, 1) + + def test_leaf_wrapper_does_not_treat_undefined_exit_scratch_as_block_exit(self): + expected = runner.expected_state(self.family, self.op, self.initial) + record = {'function':0, 'case':0, 'operation':self.op, 'initial':bytes(self.initial), + 'expected':bytes(expected), 'equality_basis':'direct_original'} + requested = [] + def wrapper(state, address, mxcsr, exit_pointer): + ctypes.memmove(state, bytes(expected), ctypes.sizeof(State)) + observed = ctypes.cast(exit_pointer, ctypes.POINTER(engine.NumericalNativeExit)).contents + observed.kind, observed.next_pc = 0xdead, 0xbeef + observed.mxcsr_before = observed.mxcsr_after = mxcsr + requested.append(mxcsr) + batches = [{'cohort':'sha3', 'oracle_path':'unit-only', 'native':b'', 'offsets':[0], 'function_base':0}] + with patch.object(runner, 'family_module', return_value=self.family), \ + patch.object(runner, 'load_original', return_value={'records':[record]}), \ + patch.object(engine, 'executable', side_effect=lambda _:nullcontext(0)), \ + patch.object(runner.ctypes, 'CFUNCTYPE', return_value=lambda _:wrapper): + result = runner.execute_batches(engine, batches) + self.assertEqual(result['complete_native_state_comparisons'], 1) + self.assertEqual(result['direct_original_math_native_comparisons'], 1) + self.assertEqual(result['caller_mxcsr_preservation_comparisons'], 16) + self.assertEqual(len(set(requested)), 16) + + def test_dependency_manifest_includes_fixture_adapter_package_and_shared_engine(self): + identities = runner.dependencies(engine, sha3) + for source in (Path(engine.__file__), Path(runner.__file__), Path(sha3.__file__), + Path(sha3.__file__).parent / '__init__.py', ROOT / 'dev/differential.py', ROOT / 'dev/evidence.py'): + self.assertEqual(identities[str(source.relative_to(ROOT))], engine.digest(source.read_bytes())) + + def test_original_storage_policy_preserves_raw_frames_and_never_credits_direct_equality(self): + with tempfile.TemporaryDirectory(dir=ROOT / '.stela/research/integer-crypto-harness') as temporary: + directory = Path(temporary) + self.initial.fpcr = 0x9f00 + operations, cases = runner.fixture_corpus(self.family) + expected = runner.expected_state(self.family, self.op, self.initial) + observed = State.from_buffer_copy(expected) + observed.fpcr = 0 + snapshot = bytearray(1024) + struct.pack_into('<31Q', snapshot, 0, *observed.x) + struct.pack_into('<4Q', snapshot, 248, observed.sp, observed.nzcv | 0x3c0, observed.fpcr, observed.fpsr) + struct.pack_into('<5Q', snapshot, engine.VECTOR_NUMERICAL_EXCEPTION_OFFSET, + engine.FP_REGISTER_EC_SVC << 26, BASE + 8, 4, engine.VECTOR_NUMERICAL_CPACR_FPEN, engine.VECTOR_NUMERICAL_ORIGINAL_MARKER) + struct.pack_into('<64Q', snapshot, engine.VECTOR_NUMERICAL_VECTORS_OFFSET, *[value for vector in observed.v for value in vector]) + struct.pack_into('<2Q', snapshot, engine.VECTOR_NUMERICAL_READBACK_OFFSET, 0, self.initial.fpsr) + files = {'functions.json':json.dumps([{**operations[0], 'source_hex':struct.pack('