feat: translate CSSC, crypto and I8MM instructions
This commit is contained in:
1 parent
3bee5618b8
commit
eca3110a3c
45 files changed
+9592
-461
No files matched your search
@@ -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) {
|
||||
|
||||
@@ -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<Operand> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Operand> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Result<Operand, ()>> {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -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<Result<Operand, ()>> {
|
||||
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.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8>,
|
||||
}
|
||||
|
||||
#[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<Result<Operand, ()>> {
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -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<Operand> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Operand> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Result<Operand, ()>> {
|
||||
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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8>,
|
||||
}
|
||||
|
||||
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<Result<Operand, ()>> {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<std::cmp::Ordering> {
|
||||
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<Self, Self::Err> {
|
||||
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<TargetCpu> {
|
||||
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::<TargetCpu>().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::<TargetCpu>().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::<TargetCpu>().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);
|
||||
|
||||
|
||||
@@ -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<std::cmp::Ordering> {
|
||||
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<Self, Self::Err> {
|
||||
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<Item = TargetCpu> {
|
||||
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::<TargetCpu>(), 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::<TargetCpu>(), 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::<TargetCpu>(), 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::<TargetCpu>().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::<TargetCpu>().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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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<u8>, 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::<u32>()],
|
||||
&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]);
|
||||
}
|
||||
}
|
||||
@@ -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<u8>, 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<u8>, operand: &Operand, opcode: &[u8], prefix: Option<u8>) {
|
||||
// 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8> {
|
||||
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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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<u8>, operand: &Operand) {
|
||||
}
|
||||
pub(super) fn emit_for_target(code: &mut Vec<u8>, 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),
|
||||
|
||||
@@ -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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8>, 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<u8>, 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());
|
||||
}
|
||||
@@ -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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8>, 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<u8>, 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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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);
|
||||
}
|
||||
@@ -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<u8>, 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<u8>, 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<u8>, 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<u8>,
|
||||
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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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<u8>, 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()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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::<TargetCpu>()
|
||||
.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()?;
|
||||
|
||||
@@ -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('<I', RET), base
|
||||
machine = Uc(UC_ARCH_ARM64, UC_MODE_ARM)
|
||||
machine.mem_map(base, 4096); machine.mem_write(base, code)
|
||||
machine.mem_map(base, 4096); machine.mem_write(base, original_code)
|
||||
machine.reg_write(arm.UC_ARM64_REG_PSTATE, 0)
|
||||
initialize_arm(machine, initial)
|
||||
machine.emu_start(base, stop, count=4)
|
||||
initialize_arm(machine, original_initial)
|
||||
machine.emu_start(original_start, stop, count=4)
|
||||
assert machine.reg_read(arm.UC_ARM64_REG_PC) == stop
|
||||
assert complete_state(capture_arm(machine, initial)) == expected
|
||||
original_ret = complete_state(capture_arm(machine, original_initial))
|
||||
assert original_ret == (expected if operations is None else complete_state(original_initial))
|
||||
state_path.write_text(json.dumps(complete_state(initial)))
|
||||
if operations is not None and flag == 0:
|
||||
budget_stop = json.loads(subprocess.check_output([str(cli), 'run-blocks', str(source),
|
||||
'--state', str(state_path), '--guest-base', hex(base), '--stop-pc', hex(stop),
|
||||
'--block-budget', '0', '--cpu-target', target,
|
||||
'--cache-dir', str(directory / ('unary-cache-' + target))], timeout=15))
|
||||
assert budget_stop['state'] == complete_state(initial) and budget_stop['pc'] == base
|
||||
assert budget_stop['outcome']['reason'] == {'kind': 'budget_exhausted'}
|
||||
assert budget_stop['outcome']['blocks_executed'] == 0
|
||||
assert budget_stop['outcome']['compiled_blocks'] == 0
|
||||
else:
|
||||
budget_stop = None
|
||||
native = json.loads(subprocess.check_output([str(cli), 'run-blocks', str(source),
|
||||
'--state', str(state_path), '--guest-base', hex(base), '--stop-pc', hex(stop),
|
||||
'--block-budget', '1', '--cpu-target', target,
|
||||
@@ -481,7 +508,14 @@ def unary_blocks(cli, directory, forms=UNARY_FORMS, target='native'):
|
||||
outcome = native['outcome']
|
||||
assert outcome['reason'] == {'kind': 'stop_address'} and outcome['blocks_executed'] == 1
|
||||
assert outcome['compiled_blocks'] == int(flag == 0) and outcome['disk_cache_hits'] == int(flag != 0)
|
||||
rows.append({'form': form, 'flags': flag, 'target': target, 'original': expected, 'native': native})
|
||||
if operations is None:
|
||||
rows.append({'form': form, 'flags': flag, 'target': target, 'original': expected, 'native': native})
|
||||
else:
|
||||
assert outcome['last_exit'] == [stop, CSSC_RETURN_EXIT]
|
||||
rows.append({'form': form, 'flags': initial.nzcv >> 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('<II', op['word'], RET).hex()} for op in functions]
|
||||
metadata = [{key: value for key, value in record.items() if key != 'initial'} for record in records]
|
||||
inputs = b''.join(struct.pack('<Q', record['function']) + record['initial'] + bytes(8) for record in records)
|
||||
files = {'functions.json': (json.dumps(functions, indent=2) + '\n').encode(),
|
||||
'cases.json': (json.dumps(metadata, indent=2) + '\n').encode(), 'inputs.bin': inputs}
|
||||
plan = {'kind': 'cssc_original_input_plan', 'cases': len(records), 'functions': len(functions),
|
||||
'harness_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
||||
'files': {name: {'sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data)} for name, data in files.items()}}
|
||||
files['input-plan.json'] = (json.dumps(plan, indent=2) + '\n').encode()
|
||||
for name, data in files.items():
|
||||
path = directory / name
|
||||
if path.exists():
|
||||
if path.read_bytes() != data:
|
||||
raise AssertionError(f'Immutable CSSC original input changed: {name}')
|
||||
else:
|
||||
with path.open('xb') as output:
|
||||
output.write(data)
|
||||
return plan
|
||||
|
||||
|
||||
def load_cssc_oracle(path):
|
||||
"""Validate unchanged producer framing before admitting original results."""
|
||||
import importlib.util
|
||||
path = Path(path)
|
||||
receipt_bytes = path.read_bytes()
|
||||
receipt = json.loads(receipt_bytes)
|
||||
if 'receipt' in receipt:
|
||||
pointer = receipt['receipt']
|
||||
receipt_bytes = (ROOT / pointer['path']).read_bytes()
|
||||
if hashlib.sha256(receipt_bytes).hexdigest() != pointer['sha256']:
|
||||
raise AssertionError('CSSC original receipt pointer changed')
|
||||
receipt = json.loads(receipt_bytes)
|
||||
if (receipt.get('passed_transport_and_architectural_frame_checks') is not True
|
||||
or receipt.get('capability_and_execution_supported') is not True):
|
||||
raise AssertionError('Passing CSSC original transport receipt required')
|
||||
directory = ROOT / receipt['directory']
|
||||
artifacts = {}
|
||||
for name, identity in receipt['files'].items():
|
||||
if Path(name).name != name:
|
||||
raise AssertionError('Original artifact is not one path component')
|
||||
data = (directory / name).read_bytes()
|
||||
if hashlib.sha256(data).hexdigest() != identity['sha256'] or len(data) != identity['bytes']:
|
||||
raise AssertionError(f'Original CSSC artifact changed: {name}')
|
||||
artifacts[name] = data
|
||||
expected_functions, expected_records = cssc_corpus()
|
||||
functions = json.loads(artifacts['functions.json'])
|
||||
cases = json.loads(artifacts['cases.json'])
|
||||
if len(functions) != len(expected_functions) or len(cases) != len(expected_records):
|
||||
raise AssertionError('CSSC original corpus/function counts changed')
|
||||
spec = importlib.util.spec_from_file_location('cssc_shared_full_frame', ROOT / 'dev/simd-differential.py')
|
||||
shared = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(shared)
|
||||
inputs, results = artifacts['inputs.bin'], artifacts['results.bin']
|
||||
if len(inputs) != len(cases) * CSSC_INPUT_STRIDE or len(results) != (len(cases) + 1) * CSSC_RECORD_BYTES:
|
||||
raise AssertionError('CSSC original input/output framing changed')
|
||||
for actual, expected in zip(functions, expected_functions):
|
||||
if actual != {**expected, 'source_hex': struct.pack('<II', expected['word'], RET).hex()}:
|
||||
raise AssertionError('CSSC original instruction metadata changed')
|
||||
records = []
|
||||
for index, (case, expected) in enumerate(zip(cases, expected_records)):
|
||||
raw = inputs[index * CSSC_INPUT_STRIDE:(index + 1) * CSSC_INPUT_STRIDE]
|
||||
if raw != struct.pack('<Q', expected['function']) + expected['initial'] + bytes(8):
|
||||
raise AssertionError('CSSC input state differs from independent generation')
|
||||
if case != {key: value for key, value in expected.items() if key != 'initial'}:
|
||||
raise AssertionError('CSSC original case metadata changed')
|
||||
operation = expected_functions[expected['function']]
|
||||
initial = State.from_buffer_copy(expected['initial'])
|
||||
snapshot = results[(index + 1) * CSSC_RECORD_BYTES:(index + 2) * CSSC_RECORD_BYTES]
|
||||
original = shared.full_frame_numerical_original_state(initial, snapshot)
|
||||
esr, elr, current_el, cpacr, marker = struct.unpack_from('<5Q', snapshot, CSSC_EXCEPTION_OFFSET)
|
||||
pre_fpcr, pre_fpsr = struct.unpack_from('<2Q', snapshot, CSSC_READBACK_OFFSET)
|
||||
if (esr >> 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('<Q', record['case']) + record['initial'])
|
||||
return {**counts, 'state_corpus_sha256': corpus.hexdigest(), 'targets': list(compiled)}
|
||||
|
||||
|
||||
def cssc_blocks(cli, directory, target='baseline'):
|
||||
fixtures = {form: [cssc_operation(form, immediate=0x80)] for form in CSSC_FORMS}
|
||||
fixtures['abs_count_alias_chain'] = [cssc_operation('ABS32', 1, 1),
|
||||
cssc_operation('CNT64', 2, 1), cssc_operation('CTZ32', 0, 2)]
|
||||
fixtures['signed_unsigned_immediate_chain'] = [cssc_operation('SMIN64I', 1, 1, immediate=0xff),
|
||||
cssc_operation('UMAX32I', 1, 1, immediate=0x80), cssc_operation('SMAX64', 0, 1, 1)]
|
||||
fixtures['zero_discard_chain'] = [cssc_operation('CTZ64', 1, 31),
|
||||
cssc_operation('ABS32', 31, 1), cssc_operation('UMIN32', 0, 31, 1)]
|
||||
forms = {name: operations[0]['word'] for name, operations in fixtures.items()}
|
||||
return unary_blocks(cli, directory, forms, target, fixtures=fixtures)
|
||||
|
||||
|
||||
def cssc_worker(pipe, compiled, records):
|
||||
try:
|
||||
pipe.send(execute_cssc_cases(compiled, records))
|
||||
except BaseException as error:
|
||||
pipe.send({'error': repr(error)})
|
||||
finally:
|
||||
pipe.close()
|
||||
|
||||
|
||||
def run_cssc_cohort(cli, oracle_path):
|
||||
import importlib.util
|
||||
oracle = load_cssc_oracle(oracle_path)
|
||||
spec = importlib.util.spec_from_file_location('cssc_shared_batch', ROOT / 'dev/simd-differential.py')
|
||||
shared = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(shared)
|
||||
shared_hashes = {name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest()
|
||||
for name in ('dev/simd-differential.py', 'dev/differential.py', 'dev/evidence.py')}
|
||||
# Reuse the established CLI native-target probe rather than assuming feature
|
||||
# availability from the host OS or an SSE tier.
|
||||
with tempfile.TemporaryDirectory(prefix='stela-cssc-capability-') as temporary:
|
||||
directory = Path(temporary)
|
||||
source = directory / 'probe.arm64'
|
||||
source.write_bytes(struct.pack('<II', CSSC_FORMS['ABS32'][0], RET))
|
||||
manifest = json.loads(subprocess.check_output([str(cli), 'compile-leaf', str(source),
|
||||
'--cpu-target', 'native', '--output-dir', str(directory / 'output')]))
|
||||
native_target = manifest['target_cpu']
|
||||
features = set(native_target.split('+'))
|
||||
targets = ['baseline']
|
||||
for target, required in (('baseline+popcnt', {'popcnt'}), ('baseline+bmi1', {'bmi1'}),
|
||||
('baseline+popcnt+bmi1', {'popcnt', 'bmi1'})):
|
||||
if required <= features:
|
||||
targets.append(target)
|
||||
host = {'native_target': native_target, 'checked_targets': targets}
|
||||
compiled, compiler = {}, None
|
||||
cli_hash = hashlib.sha256(cli.read_bytes()).hexdigest()
|
||||
with tempfile.TemporaryDirectory(prefix='stela-cssc-') as temporary:
|
||||
directory = Path(temporary)
|
||||
for target in targets:
|
||||
binaries = []
|
||||
for start in range(0, len(oracle['functions']), CSSC_BATCH_FUNCTIONS):
|
||||
functions = oracle['functions'][start:start + CSSC_BATCH_FUNCTIONS]
|
||||
# Capstone lacks CSSC. The original reader has already checked
|
||||
# every word against the pinned forms and immutable capture.
|
||||
source_bytes = b''.join(struct.pack('<II', operation['word'], RET) for operation in functions)
|
||||
source = directory / f'{target}-{start}.arm64'
|
||||
source.write_bytes(source_bytes)
|
||||
output = directory / f'{target}-{start}'
|
||||
manifest = json.loads(subprocess.check_output([str(cli), 'compile-leaf', str(source),
|
||||
'--guest-base', hex(shared.BASE), '--output-dir', str(output), '--cpu-target', target], timeout=60))
|
||||
native = (output / 'native.bin').read_bytes()
|
||||
offsets = shared.validate_manifest(manifest, source_bytes, native, False, f'x86_64-{target}')
|
||||
identity = manifest['compiler_source_sha256']
|
||||
if compiler is not None and compiler != identity:
|
||||
raise AssertionError('Compiler changed during CSSC compilation')
|
||||
compiler = identity
|
||||
for index in range(len(functions)):
|
||||
end = offsets[2 * index + 2] if index + 1 < len(functions) else len(native)
|
||||
if native[offsets[2 * index + 1]:end] != b'\xc3':
|
||||
raise AssertionError('CSSC function has no exact host RET boundary')
|
||||
binaries.append(native[offsets[2 * index]:end])
|
||||
compiled[target] = binaries
|
||||
context = multiprocessing.get_context('spawn')
|
||||
receive, send = context.Pipe(duplex=False)
|
||||
process = context.Process(target=cssc_worker, args=(send, compiled, oracle['records']))
|
||||
process.start()
|
||||
send.close()
|
||||
try:
|
||||
if not receive.poll(600):
|
||||
raise AssertionError('CSSC native isolated worker timed out')
|
||||
result = receive.recv()
|
||||
process.join(timeout=2)
|
||||
if process.exitcode != 0 or 'error' in result:
|
||||
raise AssertionError(f'CSSC native isolated worker failed: {result}; exit={process.exitcode}')
|
||||
finally:
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join()
|
||||
receive.close()
|
||||
runtime_targets = list(dict.fromkeys(('baseline', targets[-1])))
|
||||
block_cases = [row for target in runtime_targets for row in cssc_blocks(cli, directory, target)]
|
||||
if hashlib.sha256(cli.read_bytes()).hexdigest() != cli_hash:
|
||||
raise AssertionError('Compiler executable changed during CSSC cohort')
|
||||
if any(hashlib.sha256((ROOT / name).read_bytes()).hexdigest() != identity
|
||||
for name, identity in shared_hashes.items()):
|
||||
raise AssertionError('Shared harness sources changed during CSSC cohort')
|
||||
report = {'kind': 'cssc_original_vs_native_integer', 'passed': True, **result,
|
||||
'forms': 22, 'original_cases': len(oracle['records']),
|
||||
'original_receipt_sha256': oracle['receipt_sha256'], 'original_producer': oracle['receipt'],
|
||||
'compiler_source_sha256': compiler, 'compiler_executable_sha256': cli_hash,
|
||||
'harness_source_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
||||
'shared_sources_sha256': shared_hashes,
|
||||
'source_decode_basis': 'Pinned CSSC forms/masks and exact immutable original source/frame validation; shared manifest hash/map/target and exact host RET checks.',
|
||||
'capstone_cssc_decode_supported': False,
|
||||
'host_capabilities': host,
|
||||
'runtime_block_cases': block_cases, 'runtime_model_full_state_comparisons': len(block_cases),
|
||||
'runtime_budget0_stops': sum(row['budget0_stop'] is not None for row in block_cases),
|
||||
'runtime_original_ret_only_comparisons': len(block_cases),
|
||||
'runtime_joined_original_cssc_comparisons': 0,
|
||||
'limits': 'Enabled FEAT_CSSC integer results and complete GuestState only. Requested FP enable storage policy is counted separately where original controls are RAZ/WI. Original full frames execute each source word before SVC; native leaf executes the word plus compiled RET. No full PSTATE/DIT timing guarantee, disabled-feature exception, Apple hardware, guest memory or OS/application claim. Bounded native model/RET, cold/warm disk-cache and budget0-stop/budget1-one-block checks are separate from primary single-word original captures. Original RET-only composition has zero joined-original CSSC equality credit.'}
|
||||
write_evidence(ROOT / '.stela/cssc-differential-report.json', report)
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--no-build', action='store_true', help='Use the already built CLI')
|
||||
parser.add_argument('--crc-mapping-benchmark', action='store_true',
|
||||
help='Compare actual CRC output with baseline candidates using shared native timer')
|
||||
parser.add_argument('--cssc', action='store_true', help='Run the separate 22-form scalar CSSC cohort')
|
||||
parser.add_argument('--cssc-oracle', type=Path, default=CSSC_ORACLE)
|
||||
parser.add_argument('--prepare-cssc-oracle', type=Path, help='Write immutable original-only CSSC inputs')
|
||||
parser.add_argument('--cssc-calibration', action='store_true', help='Prepare the bounded 44-frame original calibration')
|
||||
arguments = parser.parse_args()
|
||||
if arguments.prepare_cssc_oracle is not None:
|
||||
print(json.dumps(prepare_cssc_oracle(arguments.prepare_cssc_oracle, arguments.cssc_calibration), indent=2))
|
||||
return
|
||||
if arguments.cssc_calibration:
|
||||
parser.error('--cssc-calibration requires --prepare-cssc-oracle')
|
||||
if not arguments.no_build:
|
||||
subprocess.run([str(ROOT / 'dev/cargo'), 'build', '--locked', '-p', 'stela-cli'], check=True)
|
||||
cli = ROOT / 'target/debug/stela'
|
||||
if arguments.cssc:
|
||||
run_cssc_cohort(cli, arguments.cssc_oracle)
|
||||
return
|
||||
if arguments.crc_mapping_benchmark:
|
||||
crc_mapping_benchmark(cli)
|
||||
return
|
||||
|
||||
@@ -25,6 +25,7 @@ import socket
|
||||
from pathlib import Path
|
||||
import random
|
||||
import signal
|
||||
import sys
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
@@ -38,6 +39,8 @@ from unicorn import __version__ as unicorn_version
|
||||
from differential import (ROOT, BASE, MASK, State, states, executable, initialize_arm,
|
||||
capture_arm, state_dict, seed_extended_state, parse_fault_record, move)
|
||||
from evidence import retain_native_evidence, write_evidence
|
||||
from simd_fixtures import FAMILIES as FIXTURE_FAMILIES
|
||||
import simd_fixture_runner
|
||||
|
||||
RET = 0xd65f03c0
|
||||
STOP = 0x220000100000
|
||||
@@ -242,7 +245,7 @@ def validate_manifest(manifest, source, native, block, target_cpu=None, guest_ba
|
||||
return [row[1] for row in mapping]
|
||||
|
||||
|
||||
def compile_batch(cli, directory, functions, index, block=False, cpu_target="baseline", target_id="x86_64-baseline", guest_base=BASE):
|
||||
def compile_batch(cli, directory, functions, index, block=False, cpu_target="baseline", target_id="x86_64-baseline", guest_base=BASE, allowed_mnemonics=None):
|
||||
if block and len(functions) != 1:
|
||||
raise ValueError('A block compilation batch must have exactly one entry')
|
||||
words, entries = [], []
|
||||
@@ -252,7 +255,7 @@ def compile_batch(cli, directory, functions, index, block=False, cpu_target="bas
|
||||
words.append(numerical_return_word(function['operations'][0]) if len(function['operations']) == 1 else RET)
|
||||
source = struct.pack('<' + 'I' * len(words), *words)
|
||||
disassembly = list(Cs(CS_ARCH_ARM64, CS_MODE_ARM).disasm(source, BASE))
|
||||
if len(disassembly) != len(words) or any(i.mnemonic not in {'ldr', 'str', 'ldur', 'stur', 'ldp', 'stp', 'movi', 'ret', 'and', 'bic', 'orr', 'orn', 'eor', 'bsl', 'bit', 'bif', 'add', 'sub', 'abs', 'neg', 'mov', 'cmeq', 'cmgt', 'cmge', 'cmhi', 'cmhs', 'cmlt', 'cmle', 'cmtst', 'dup', 'ins', 'smov', 'umov', 'ext', 'rev16', 'rev32', 'rev64', 'zip1', 'zip2', 'uzp1', 'uzp2', 'trn1', 'trn2', 'tbl', 'tbx', 'shl', 'sshr', 'ushr', 'srshr', 'urshr', 'ssra', 'usra', 'srsra', 'ursra', 'sli', 'sri', 'shrn', 'shrn2', 'rshrn', 'rshrn2', 'sshll', 'sshll2', 'ushll', 'ushll2', 'sxtl', 'sxtl2', 'uxtl', 'uxtl2', 'smin', 'smax', 'umin', 'umax', 'sminp', 'smaxp', 'uminp', 'umaxp', 'sminv', 'smaxv', 'uminv', 'umaxv', 'addv', 'addp', 'saddlv', 'uaddlv', 'cnt', 'clz', 'cls', 'rbit', 'mvn', 'not', 'sqadd', 'uqadd', 'sqsub', 'uqsub', 'sqabs', 'sqneg', 'suqadd', 'usqadd', 'sqxtn', 'sqxtn2', 'uqxtn', 'uqxtn2', 'sqxtun', 'sqxtun2', 'mul', 'mla', 'mls', 'smull', 'smull2', 'umull', 'umull2', 'smlal', 'smlal2', 'umlal', 'umlal2', 'smlsl', 'smlsl2', 'umlsl', 'umlsl2', 'saddl', 'saddl2', 'uaddl', 'uaddl2', 'ssubl', 'ssubl2', 'usubl', 'usubl2', 'saddw', 'saddw2', 'uaddw', 'uaddw2', 'ssubw', 'ssubw2', 'usubw', 'usubw2', 'sabd', 'uabd', 'saba', 'uaba', 'sabdl', 'sabdl2', 'uabdl', 'uabdl2', 'sabal', 'sabal2', 'uabal', 'uabal2', 'shadd', 'uhadd', 'srhadd', 'urhadd', 'shsub', 'uhsub', 'addhn', 'addhn2', 'raddhn', 'raddhn2', 'subhn', 'subhn2', 'rsubhn', 'rsubhn2', 'saddlp', 'uaddlp', 'sadalp', 'uadalp', 'xtn', 'xtn2', 'shll', 'shll2', 'mvni', 'fmov', 'pmul', 'pmull', 'pmull2', 'sqdmulh', 'sqrdmulh', 'sqdmull', 'sqdmull2', 'sqdmlal', 'sqdmlal2', 'sqdmlsl', 'sqdmlsl2', 'sshl', 'ushl', 'srshl', 'urshl', 'sqshl', 'uqshl', 'sqrshl', 'uqrshl', 'sqshlu', 'fcsel', 'fabs', 'fneg', 'sqshrn', 'sqshrn2', 'sqrshrn', 'sqrshrn2', 'uqshrn', 'uqshrn2', 'uqrshrn', 'uqrshrn2', 'sqshrun', 'sqshrun2', 'sqrshrun', 'sqrshrun2', 'sdot', 'udot', 'sqrdmlah', 'sqrdmlsh', 'fadd', 'fsub', 'fmul', 'fdiv', 'mrs', 'msr', 'fmadd', 'fmsub', 'fnmadd', 'fnmsub', 'fmla', 'fmls', 'fcvt', 'fcvtl', 'fcvtl2', 'fcvtn', 'fcvtn2', 'fcvtxn', 'fcvtxn2', 'fcvtns', 'fcvtnu', 'fcvtps', 'fcvtpu', 'fcvtms', 'fcvtmu', 'fcvtzs', 'fcvtzu', 'fcvtas', 'fcvtau', 'scvtf', 'ucvtf', 'fjcvtzs', 'fcmp', 'fcmpe', 'fccmp', 'fccmpe', 'facge', 'facgt', 'fcmeq', 'fcmge', 'fcmgt', 'fcmle', 'fcmlt', 'fmax', 'fmin', 'fmaxnm', 'fminnm', 'fmaxp', 'fminp', 'fmaxnmp', 'fminnmp', 'fmaxv', 'fminv', 'fmaxnmv', 'fminnmv', 'frintn', 'frintp', 'frintm', 'frintz', 'frinta', 'frintx', 'frinti', 'frint32z', 'frint32x', 'frint64z', 'frint64x', 'fsqrt', 'frecpe', 'frsqrte', 'frecpx', 'urecpe', 'ursqrte', 'frecps', 'frsqrts', 'fnmul', 'fabd', 'faddp', 'fmulx', 'fmlal', 'fmlal2', 'fmlsl', 'fmlsl2', 'bfcvt', 'bfcvtn', 'bfcvtn2', 'bfdot', 'bfmlalb', 'bfmlalt', 'bfmmla', 'fcadd', 'fcmla'} for i in disassembly):
|
||||
if len(disassembly) != len(words) or any(i.mnemonic not in ({'ldr', 'str', 'ldur', 'stur', 'ldp', 'stp', 'movi', 'ret', 'and', 'bic', 'orr', 'orn', 'eor', 'bsl', 'bit', 'bif', 'add', 'sub', 'abs', 'neg', 'mov', 'cmeq', 'cmgt', 'cmge', 'cmhi', 'cmhs', 'cmlt', 'cmle', 'cmtst', 'dup', 'ins', 'smov', 'umov', 'ext', 'rev16', 'rev32', 'rev64', 'zip1', 'zip2', 'uzp1', 'uzp2', 'trn1', 'trn2', 'tbl', 'tbx', 'shl', 'sshr', 'ushr', 'srshr', 'urshr', 'ssra', 'usra', 'srsra', 'ursra', 'sli', 'sri', 'shrn', 'shrn2', 'rshrn', 'rshrn2', 'sshll', 'sshll2', 'ushll', 'ushll2', 'sxtl', 'sxtl2', 'uxtl', 'uxtl2', 'smin', 'smax', 'umin', 'umax', 'sminp', 'smaxp', 'uminp', 'umaxp', 'sminv', 'smaxv', 'uminv', 'umaxv', 'addv', 'addp', 'saddlv', 'uaddlv', 'cnt', 'clz', 'cls', 'rbit', 'mvn', 'not', 'sqadd', 'uqadd', 'sqsub', 'uqsub', 'sqabs', 'sqneg', 'suqadd', 'usqadd', 'sqxtn', 'sqxtn2', 'uqxtn', 'uqxtn2', 'sqxtun', 'sqxtun2', 'mul', 'mla', 'mls', 'smull', 'smull2', 'umull', 'umull2', 'smlal', 'smlal2', 'umlal', 'umlal2', 'smlsl', 'smlsl2', 'umlsl', 'umlsl2', 'saddl', 'saddl2', 'uaddl', 'uaddl2', 'ssubl', 'ssubl2', 'usubl', 'usubl2', 'saddw', 'saddw2', 'uaddw', 'uaddw2', 'ssubw', 'ssubw2', 'usubw', 'usubw2', 'sabd', 'uabd', 'saba', 'uaba', 'sabdl', 'sabdl2', 'uabdl', 'uabdl2', 'sabal', 'sabal2', 'uabal', 'uabal2', 'shadd', 'uhadd', 'srhadd', 'urhadd', 'shsub', 'uhsub', 'addhn', 'addhn2', 'raddhn', 'raddhn2', 'subhn', 'subhn2', 'rsubhn', 'rsubhn2', 'saddlp', 'uaddlp', 'sadalp', 'uadalp', 'xtn', 'xtn2', 'shll', 'shll2', 'mvni', 'fmov', 'pmul', 'pmull', 'pmull2', 'sqdmulh', 'sqrdmulh', 'sqdmull', 'sqdmull2', 'sqdmlal', 'sqdmlal2', 'sqdmlsl', 'sqdmlsl2', 'sshl', 'ushl', 'srshl', 'urshl', 'sqshl', 'uqshl', 'sqrshl', 'uqrshl', 'sqshlu', 'fcsel', 'fabs', 'fneg', 'sqshrn', 'sqshrn2', 'sqrshrn', 'sqrshrn2', 'uqshrn', 'uqshrn2', 'uqrshrn', 'uqrshrn2', 'sqshrun', 'sqshrun2', 'sqrshrun', 'sqrshrun2', 'sdot', 'udot', 'sqrdmlah', 'sqrdmlsh', 'fadd', 'fsub', 'fmul', 'fdiv', 'mrs', 'msr', 'fmadd', 'fmsub', 'fnmadd', 'fnmsub', 'fmla', 'fmls', 'fcvt', 'fcvtl', 'fcvtl2', 'fcvtn', 'fcvtn2', 'fcvtxn', 'fcvtxn2', 'fcvtns', 'fcvtnu', 'fcvtps', 'fcvtpu', 'fcvtms', 'fcvtmu', 'fcvtzs', 'fcvtzu', 'fcvtas', 'fcvtau', 'scvtf', 'ucvtf', 'fjcvtzs', 'fcmp', 'fcmpe', 'fccmp', 'fccmpe', 'facge', 'facgt', 'fcmeq', 'fcmge', 'fcmgt', 'fcmle', 'fcmlt', 'fmax', 'fmin', 'fmaxnm', 'fminnm', 'fmaxp', 'fminp', 'fmaxnmp', 'fminnmp', 'fmaxv', 'fminv', 'fmaxnmv', 'fminnmv', 'frintn', 'frintp', 'frintm', 'frintz', 'frinta', 'frintx', 'frinti', 'frint32z', 'frint32x', 'frint64z', 'frint64x', 'fsqrt', 'frecpe', 'frsqrte', 'frecpx', 'urecpe', 'ursqrte', 'frecps', 'frsqrts', 'fnmul', 'fabd', 'faddp', 'fmulx', 'fmlal', 'fmlal2', 'fmlsl', 'fmlsl2', 'bfcvt', 'bfcvtn', 'bfcvtn2', 'bfdot', 'bfmlalb', 'bfmlalt', 'bfmmla', 'fcadd', 'fcmla'} if allowed_mnemonics is None else set(allowed_mnemonics) | {'ret'}) for i in disassembly):
|
||||
raise AssertionError('Independent decoder declined SIMD fixture')
|
||||
path = directory / f'program-{index}.arm64'
|
||||
path.write_bytes(source)
|
||||
@@ -406,7 +409,9 @@ def execute_batches(batches, pipe):
|
||||
|
||||
def worker(pipe, batches):
|
||||
try:
|
||||
if batches[0].get('cohort') == 'scalar_numerical':
|
||||
if batches[0].get('cohort') in FIXTURE_FAMILIES:
|
||||
result = simd_fixture_runner.execute_batches(sys.modules[__name__], batches)
|
||||
elif batches[0].get('cohort') == 'scalar_numerical':
|
||||
result = execute_numerical_batches(batches)
|
||||
elif batches[0].get('cohort') == 'fp_registers':
|
||||
result = execute_fp_register_batches(batches)
|
||||
@@ -7414,7 +7419,9 @@ def run_register_cohort(cli, focus):
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--no-build', action='store_true')
|
||||
parser.add_argument('--focus', choices=[*REGISTER_COHORTS, NUMERICAL_FOCUS, FP_REGISTER_FOCUS, VECTOR_NUMERICAL_FOCUS, FUSED_NUMERICAL_FOCUS, CONVERSION_NUMERICAL_FOCUS, COMPARISON_MINMAX_FOCUS, ROUND_INTEGRAL_FOCUS, SQRT_NUMERICAL_FOCUS, ESTIMATE_NUMERICAL_FOCUS, REFINEMENT_NUMERICAL_FOCUS, BINARY_REMAINING_FOCUS, WIDENING_NUMERICAL_FOCUS, BFLOAT16_NUMERICAL_FOCUS, COMPLEX_NUMERICAL_FOCUS], help='Only the focused SIMD implementation cohort')
|
||||
parser.add_argument('--focus', choices=[*REGISTER_COHORTS, *FIXTURE_FAMILIES, NUMERICAL_FOCUS, FP_REGISTER_FOCUS, VECTOR_NUMERICAL_FOCUS, FUSED_NUMERICAL_FOCUS, CONVERSION_NUMERICAL_FOCUS, COMPARISON_MINMAX_FOCUS, ROUND_INTEGRAL_FOCUS, SQRT_NUMERICAL_FOCUS, ESTIMATE_NUMERICAL_FOCUS, REFINEMENT_NUMERICAL_FOCUS, BINARY_REMAINING_FOCUS, WIDENING_NUMERICAL_FOCUS, BFLOAT16_NUMERICAL_FOCUS, COMPLEX_NUMERICAL_FOCUS], help='Only the focused SIMD implementation cohort')
|
||||
parser.add_argument('--fixture-oracle', type=Path, help='Full-frame primary original pointer for an integer/crypto fixture family')
|
||||
parser.add_argument('--prepare-fixture-oracle', type=Path, help='Freeze original-only fixture inputs in this directory')
|
||||
parser.add_argument('--numerical-oracle', type=Path, default=NUMERICAL_FOUNDATION,
|
||||
help='Pinned numerical foundation receipt for scalar_numerical')
|
||||
parser.add_argument('--vector-oracle', type=Path, default=VECTOR_NUMERICAL_ORACLE,
|
||||
@@ -7436,9 +7443,20 @@ def main():
|
||||
parser.add_argument('--estimate-oracle', type=Path, default=ESTIMATE_NUMERICAL_ORACLE)
|
||||
parser.add_argument('--refinement-oracle', type=Path, default=REFINEMENT_NUMERICAL_ORACLE)
|
||||
arguments = parser.parse_args()
|
||||
if arguments.prepare_fixture_oracle:
|
||||
if arguments.focus not in FIXTURE_FAMILIES:
|
||||
parser.error('--prepare-fixture-oracle requires an integer/crypto fixture focus')
|
||||
prepared = simd_fixture_runner.prepare_original(sys.modules[__name__],
|
||||
simd_fixture_runner.family_module(arguments.focus), arguments.prepare_fixture_oracle)
|
||||
print(json.dumps(prepared, indent=2))
|
||||
return
|
||||
if not arguments.no_build:
|
||||
subprocess.run([str(ROOT / 'dev/cargo'), 'build', '--locked', '-p', 'stela-cli'], check=True)
|
||||
cli = ROOT / 'target/debug/stela'
|
||||
if arguments.focus in FIXTURE_FAMILIES:
|
||||
_, report = simd_fixture_runner.run(sys.modules[__name__], cli, arguments.focus, arguments.fixture_oracle)
|
||||
print(json.dumps(report, indent=2))
|
||||
return
|
||||
if arguments.focus == NUMERICAL_FOCUS:
|
||||
run_scalar_numerical_cohort(cli, arguments.numerical_oracle)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
"""Shared full-state adapter for pure integer and crypto SIMD fixtures.
|
||||
|
||||
The CLI supplies its existing compiler, original snapshot reader, artifact/map
|
||||
checks and MXCSR wrapper explicitly. Family modules own only words, inputs and
|
||||
independent integer models. Historical cohort engines remain unchanged.
|
||||
"""
|
||||
from collections import Counter
|
||||
from contextlib import ExitStack
|
||||
import ctypes
|
||||
import importlib
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from differential import ROOT, BASE, State, state_dict
|
||||
from evidence import write_evidence
|
||||
from simd_fixtures import FAMILIES
|
||||
import simd_original
|
||||
|
||||
BATCH_FUNCTIONS = 512
|
||||
MAXIMUM_RUNTIME_CASES = 96
|
||||
CACHE_LOOP_ITERATIONS = 3
|
||||
BRANCH_NEXT_INSTRUCTION = 0x14000001
|
||||
MAXIMUM_MIXED_OPERATIONS = 8
|
||||
ORIGINAL_INPUT_HEADER = 8
|
||||
ORIGINAL_INPUT_STRIDE = 800
|
||||
ORIGINAL_RECORD_BYTES = 1024
|
||||
ORIGINAL_STATE_BYTES = 784
|
||||
RETURN_REGISTER = 30
|
||||
VECTOR_REGISTER_BITS = 5
|
||||
VECTOR_LEFT_SHIFT = 5
|
||||
VECTOR_LEFT_MASK = ((1 << VECTOR_REGISTER_BITS) - 1) << VECTOR_LEFT_SHIFT
|
||||
|
||||
|
||||
def family_module(focus):
|
||||
if focus not in FAMILIES:
|
||||
raise ValueError('Unknown SIMD fixture family')
|
||||
return importlib.import_module('simd_fixtures.' + focus)
|
||||
|
||||
|
||||
def fixture_corpus(family):
|
||||
operations, cases = family.corpus()
|
||||
if operations != family.functions() or not operations or not cases:
|
||||
raise AssertionError('Fixture functions/corpus disagree or are empty')
|
||||
if len({op['word'] for op in operations}) != len(operations):
|
||||
raise AssertionError('Each original word needs one fixture function')
|
||||
if {op['canonical_id'] for op in operations} != set(family.CANONICAL_FORMS):
|
||||
raise AssertionError('Fixture canonical form inventory differs')
|
||||
operations = [dict(op, merge=op.get('merge', 'none')) for op in operations]
|
||||
records = []
|
||||
for index, case in enumerate(cases):
|
||||
initial = case['initial']
|
||||
if len(initial) != ORIGINAL_STATE_BYTES or not 0 <= case['function'] < len(operations):
|
||||
raise AssertionError('Fixture input/state framing differs')
|
||||
records.append({**case, 'case': index, 'function_index': case['function']})
|
||||
runtime = [case for case in records if case.get('runtime')]
|
||||
if not 0 < len(runtime) <= MAXIMUM_RUNTIME_CASES:
|
||||
raise AssertionError('Fixture runtime selection exceeds its bounded budget')
|
||||
if {operations[case['function']]['canonical_id'] for case in runtime} != set(family.CANONICAL_FORMS):
|
||||
raise AssertionError('Runtime selection omits a canonical form')
|
||||
return operations, records
|
||||
|
||||
|
||||
def dependencies(engine, family):
|
||||
paths = [Path(engine.__file__), Path(__file__), Path(family.__file__),
|
||||
Path(family.__file__).parent / '__init__.py', Path(simd_original.__file__), ROOT / 'dev/differential.py', ROOT / 'dev/evidence.py']
|
||||
guards = Path(__file__).parent / 'test_simd_fixtures.py'
|
||||
if guards.exists():
|
||||
paths.append(guards)
|
||||
return {str(path.relative_to(ROOT)): engine.digest(path.read_bytes()) for path in paths}
|
||||
|
||||
|
||||
def oracle_path(focus):
|
||||
return ROOT / '.stela/research/integer-crypto-harness' / focus / 'oracle/receipt.json'
|
||||
|
||||
|
||||
def prepare_original(engine, family, directory):
|
||||
"""Freeze input/source bindings for the separately invoked shared observer."""
|
||||
operations, records = fixture_corpus(family)
|
||||
directory = Path(directory)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
sources = dependencies(engine, family)
|
||||
binding_path = directory / 'source-bindings.json'
|
||||
data = (json.dumps(sources, indent=2) + '\n').encode()
|
||||
if binding_path.exists() and binding_path.read_bytes() != data:
|
||||
raise AssertionError('Frozen original source bindings changed')
|
||||
if not binding_path.exists():
|
||||
binding_path.write_bytes(data)
|
||||
plan = engine.prepare_full_frame_numerical_oracle(directory, operations, records, family.FOCUS)
|
||||
return {**plan, 'observer_sha256': engine.digest(Path(simd_original.__file__).read_bytes()),
|
||||
'fixture_sources_sha256':sources, 'capture_command':[sys.executable, str(Path(simd_original.__file__)),
|
||||
'--directory', str(directory), '--focus', family.FOCUS, '--source-bindings', str(binding_path), '--capture']}
|
||||
|
||||
|
||||
def expected_state(family, operation, initial):
|
||||
expected = family.expected(operation, State.from_buffer_copy(initial))
|
||||
if not isinstance(expected, State):
|
||||
raise AssertionError('Fixture model must return a complete State')
|
||||
untouched = State.from_buffer_copy(expected)
|
||||
untouched.v[operation['d']][:] = initial.v[operation['d']]
|
||||
if bytes(untouched) != bytes(initial):
|
||||
raise AssertionError('Integer crypto model changed fields outside its destination')
|
||||
return expected
|
||||
|
||||
|
||||
def load_original(engine, family, pointer_path):
|
||||
pointer, pointer_sha = engine.numerical_json(pointer_path)
|
||||
producer, receipt_sha = engine.numerical_json(ROOT / pointer['receipt']['path'], pointer['receipt']['sha256'])
|
||||
operations, cases = fixture_corpus(family)
|
||||
if (not producer.get('passed_transport_and_architectural_frame_checks') or producer['cases'] != len(cases)
|
||||
or pointer['directory'] != producer['directory']):
|
||||
raise AssertionError('Passing complete original capture required')
|
||||
directory = ROOT / producer['directory']
|
||||
for name, identity in producer['files'].items():
|
||||
if Path(name).name != name:
|
||||
raise AssertionError('Original evidence name escapes capture directory')
|
||||
data = (directory / name).read_bytes()
|
||||
if engine.digest(data) != identity['sha256'] or len(data) != identity['bytes']:
|
||||
raise AssertionError('Original capture file changed: ' + name)
|
||||
functions = json.loads((directory / 'functions.json').read_bytes())
|
||||
expected_functions = [{**op, 'source_hex':struct.pack('<II', op['word'], engine.RET).hex()} for op in operations]
|
||||
if functions != expected_functions:
|
||||
raise AssertionError('Captured words differ from frozen fixture encodings')
|
||||
metadata = json.loads((directory / 'cases.json').read_bytes())
|
||||
if metadata != [{key:value for key, value in case.items() if key != 'initial'} for case in cases]:
|
||||
raise AssertionError('Captured case metadata differs from the frozen fixture corpus')
|
||||
inputs, results, elf = ((directory / name).read_bytes() for name in ('inputs.bin', 'results.bin', 'guest.elf'))
|
||||
expected_inputs = b''.join(struct.pack('<Q', case['function']) + case['initial'] + bytes(8) for case in cases)
|
||||
if inputs != expected_inputs or len(results) != (len(cases) + 1) * ORIGINAL_RECORD_BYTES:
|
||||
raise AssertionError('Captured inputs/frame count differ from fixture corpus')
|
||||
records, readbacks = [], Counter()
|
||||
for index, case in enumerate(cases):
|
||||
op = operations[case['function']]
|
||||
initial = State.from_buffer_copy(case['initial'])
|
||||
snapshot = results[(index + 1) * ORIGINAL_RECORD_BYTES:(index + 2) * ORIGINAL_RECORD_BYTES]
|
||||
original = engine.full_frame_numerical_original_state(initial, snapshot)
|
||||
esr, elr, current_el, cpacr, marker = struct.unpack_from('<5Q', snapshot, engine.VECTOR_NUMERICAL_EXCEPTION_OFFSET)
|
||||
fpcr, fpsr = struct.unpack_from('<2Q', snapshot, engine.VECTOR_NUMERICAL_READBACK_OFFSET)
|
||||
if (esr >> 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('<I', record['operation']['word']))
|
||||
digest.update(record['initial'])
|
||||
op = record['operation']
|
||||
examples.setdefault((op['canonical_id'], op['lane'], op['bytes'], op['scalar'], op.get('index')), record)
|
||||
for record in examples.values():
|
||||
for masks in (0, engine.NUMERICAL_MXCSR_ALL_MASKS):
|
||||
for status in (0, engine.NUMERICAL_MXCSR_ALL_STATUS):
|
||||
for mode in range(4):
|
||||
invoke(record, masks | status | mode << engine.NUMERICAL_MXCSR_ROUND_SHIFT)
|
||||
counts['mxcsr_checks'] += 1
|
||||
return {'complete_native_state_comparisons':len(oracle['records']), 'direct_original_math_native_comparisons':counts['direct_original'],
|
||||
'requested_storage_native_policy_comparisons':counts['requested_storage_policy'], 'caller_mxcsr_preservation_comparisons':counts['mxcsr_checks'],
|
||||
'state_corpus_sha256':digest.hexdigest(), 'architectural_state_bytes':ctypes.sizeof(State),
|
||||
'limits':'All native/model bytes compare. Direct original equality excludes requested storage absent from captured FPCR/FPSR readbacks; those raw originals stay unchanged. Leaf RET is harness-owned. No numerical helper/refusal or supplementary Unicorn success is inferred.'}
|
||||
|
||||
|
||||
def apply_operations(family, operations, initial):
|
||||
state = State.from_buffer_copy(initial)
|
||||
for op in operations:
|
||||
state = expected_state(family, op, state)
|
||||
return state
|
||||
|
||||
|
||||
def runtime_checks(engine, family, oracle, cli, directory, compiler, target, target_id):
|
||||
selected = [record for record in oracle['records'] if record.get('runtime')]
|
||||
if not 0 < len(selected) <= MAXIMUM_RUNTIME_CASES:
|
||||
raise AssertionError('Invalid runtime fixture selection')
|
||||
memory_address, memory = 0x240000000000, engine.NUMERICAL_GUARD * 16
|
||||
memory_path = directory / 'runtime-memory.json'
|
||||
memory_path.write_text(json.dumps({'regions':[{'guest_address':memory_address, 'virtual_bytes':len(memory),
|
||||
'initial_bytes':list(memory), 'readable':True, 'writable':True}]}))
|
||||
counts, transcripts = Counter(), []
|
||||
def invoke(code, initial, entry=BASE, budget=16, cache=None):
|
||||
source_path, state_path = directory / 'runtime.arm64', directory / 'runtime-state.json'
|
||||
source_path.write_bytes(code)
|
||||
state_path.write_text(json.dumps(state_dict(initial)))
|
||||
cache = cache or directory / 'runtime-cache'
|
||||
report = json.loads(subprocess.check_output([str(cli), 'run-blocks', str(source_path), '--guest-base', hex(BASE),
|
||||
'--entry', hex(entry), '--stop-pc', hex(engine.STOP), '--cpu-target', target, '--state', str(state_path),
|
||||
'--block-budget', str(budget), '--cache-dir', str(cache), '--memory', str(memory_path),
|
||||
'--read-memory', f'{hex(memory_address)}:{len(memory)}'], timeout=30))
|
||||
if report['compiler_source_sha256'] != compiler or report['target_cpu'] != target_id or report['source_sha256'] != engine.digest(code):
|
||||
raise AssertionError('Runtime compiler/source/target identity differs')
|
||||
ram = report['memory']
|
||||
if ram['memory_before'] != ram['memory_after'] or ram['memory_reads'][0]['hex'] != memory.hex():
|
||||
raise AssertionError('Register-only crypto changed owned guest RAM')
|
||||
if report['outcome']['floating_point_helpers']:
|
||||
raise AssertionError('Integer crypto entered a floating-point helper')
|
||||
counts['invocations'] += 1
|
||||
transcripts.append({'source_hex':code.hex(), 'initial_state_hex':bytes(initial).hex(), 'report':report})
|
||||
return report, engine.numerical_report_state(report['state'])
|
||||
def require(report, actual, expected, pc=None, reason='stop_address'):
|
||||
pc = engine.STOP if pc is None else pc
|
||||
if report['pc'] != pc or report['outcome']['reason']['kind'] != reason or bytes(actual) != bytes(expected):
|
||||
write_evidence(ROOT / f'.stela/simd-{family.FOCUS}-runtime-failure.json', {'kind':'simd_fixture_runtime_failure',
|
||||
'transcripts':transcripts, 'expected_state_hex':bytes(expected).hex(), 'expected_pc':pc, 'expected_reason':reason})
|
||||
raise AssertionError('Integer crypto runtime complete-state mismatch')
|
||||
counts['complete_state_comparisons'] += 1
|
||||
for record in selected:
|
||||
initial = State.from_buffer_copy(record['initial'])
|
||||
source = struct.pack('<II', record['operation']['word'], engine.RET)
|
||||
report, actual = invoke(source, initial)
|
||||
require(report, actual, State.from_buffer_copy(record['expected']))
|
||||
counts[record['equality_basis']] += 1
|
||||
representatives = {}
|
||||
for record in selected:
|
||||
representatives.setdefault(record['operation']['canonical_id'], record)
|
||||
for record in representatives.values():
|
||||
op, initial = record['operation'], State.from_buffer_copy(record['initial'])
|
||||
# B+4 forces a real dispatcher boundary after the subject; RET is the next block.
|
||||
source = struct.pack('<3I', op['word'], BRANCH_NEXT_INSTRUCTION, engine.RET)
|
||||
intermediate = expected_state(family, op, initial)
|
||||
cache = directory / ('resume-' + str(record['function']))
|
||||
first, actual = invoke(source, initial, budget=1, cache=cache)
|
||||
require(first, actual, intermediate, BASE + 8, 'budget_exhausted')
|
||||
final, actual = invoke(source, actual, entry=BASE + 8, budget=1, cache=cache)
|
||||
require(final, actual, intermediate)
|
||||
counts['budget_resume_checks'] += 1
|
||||
warm, actual = invoke(source, initial, cache=cache)
|
||||
require(warm, actual, intermediate)
|
||||
if not warm['outcome']['disk_cache_hits']:
|
||||
raise AssertionError('Fresh runtime did not reuse persistent code')
|
||||
counts['disk_cache_checks'] += 1
|
||||
source = struct.pack('<4I', op['word'], engine.NUMERICAL_SUBS_X10_ONE, engine.NUMERICAL_CBNZ_X10_BACK_TWO, engine.RET)
|
||||
loop_initial = State.from_buffer_copy(initial)
|
||||
loop_initial.x[10] = CACHE_LOOP_ITERATIONS
|
||||
expected = apply_operations(family, [op] * CACHE_LOOP_ITERATIONS, loop_initial)
|
||||
expected.x[10], expected.nzcv = 0, engine.NUMERICAL_ZERO_CARRY_FLAGS
|
||||
repeated, actual = invoke(source, loop_initial)
|
||||
require(repeated, actual, expected)
|
||||
if repeated['outcome']['memory_cache_hits'] < CACHE_LOOP_ITERATIONS - 1:
|
||||
raise AssertionError('Repeated accumulating instructions missed live cache reuse')
|
||||
counts['memory_cache_loop_checks'] += 1
|
||||
mixed = list(representatives.values())[:MAXIMUM_MIXED_OPERATIONS]
|
||||
operations = [dict(record['operation']) for record in mixed]
|
||||
for previous, operation in zip(operations, operations[1:]):
|
||||
operation['n'] = previous['d']
|
||||
operation['word'] = operation['word'] & ~VECTOR_LEFT_MASK | operation['n'] << VECTOR_LEFT_SHIFT
|
||||
initial = State.from_buffer_copy(mixed[0]['initial'])
|
||||
source = struct.pack('<' + 'I' * (len(operations) + 1), *[op['word'] for op in operations], engine.RET)
|
||||
report, actual = invoke(source, initial)
|
||||
require(report, actual, apply_operations(family, operations, initial))
|
||||
counts['mixed_dependency_chain_checks'] += 1
|
||||
snapshot = write_evidence(ROOT / f'.stela/simd-{family.FOCUS}-{target_id}-runtime-records.json', transcripts)
|
||||
return {**dict(counts), 'transcript':{'path':str(snapshot.relative_to(ROOT)), 'sha256':engine.digest(snapshot.read_bytes())},
|
||||
'limits':'Actual runtime full state, budget, disk/live cache and guest RAM checks use sequential integer models grounded in primary single-instruction originals. No joined-original, helper, enabled trap or performance credit.'}
|
||||
|
||||
|
||||
def run(engine, cli, focus, pointer=None):
|
||||
family = family_module(focus)
|
||||
pointer = Path(pointer) if pointer else oracle_path(focus)
|
||||
oracle = load_original(engine, family, pointer)
|
||||
shared = dependencies(engine, family)
|
||||
cli_sha, started = engine.digest(cli.read_bytes()), time.monotonic()
|
||||
cpu = json.loads(subprocess.check_output([str(cli), 'cpu-info']))
|
||||
selections = [('baseline', 'x86_64-baseline')]
|
||||
if cpu['detected_target'] != 'x86_64-baseline':
|
||||
selections.append(('native', cpu['detected_target']))
|
||||
profiles, compiler = [], None
|
||||
with tempfile.TemporaryDirectory(prefix='stela-' + focus + '-') as temporary:
|
||||
for target, target_id in selections:
|
||||
directory = Path(temporary) / target_id
|
||||
directory.mkdir()
|
||||
batches, artifacts = [], []
|
||||
for start in range(0, len(oracle['functions']), BATCH_FUNCTIONS):
|
||||
operations = oracle['functions'][start:start + BATCH_FUNCTIONS]
|
||||
programs = [{'operations':[op]} for op in operations]
|
||||
batch = engine.compile_batch(cli, directory, programs, start, cpu_target=target, target_id=target_id,
|
||||
guest_base=BASE + start * 8, allowed_mnemonics={op['name'] for op in operations})
|
||||
batch.update(cohort=focus, function_base=start, oracle_path=str(pointer))
|
||||
if compiler is not None and batch['compiler'] != compiler:
|
||||
raise AssertionError('Compiler changed during fixture preparation')
|
||||
compiler = batch['compiler']
|
||||
accounting = engine.native_binary_accounting(batch)
|
||||
retained = engine.retain_native_binary_evidence(batch, accounting, [])
|
||||
artifacts.append({'function_base':start, 'functions':len(operations), 'files':retained, 'accounting':accounting})
|
||||
batches.append(batch)
|
||||
raw = engine.bounded_cases(batches)
|
||||
runtime = runtime_checks(engine, family, oracle, cli, directory, compiler, target, target_id)
|
||||
used = set()
|
||||
optional = {row['mnemonic'] for row in cpu['simd_opcodes'] if row['minimum_target'] != 'x86_64-baseline'}
|
||||
for batch in batches:
|
||||
used.update(optional & {engine.native_mnemonic(op.mnemonic) for op in engine.decode_native_stream(batch['native'])})
|
||||
if hasattr(family, 'optional_opcodes') and used != set(family.optional_opcodes(target_id)):
|
||||
raise AssertionError((target_id, sorted(used), sorted(family.optional_opcodes(target_id))))
|
||||
profiles.append({'target_cpu':target_id, 'raw_native':raw, 'runtime':runtime, 'native_artifacts':artifacts,
|
||||
'optional_opcodes_used':sorted(used)})
|
||||
if engine.digest(cli.read_bytes()) != cli_sha or dependencies(engine, family) != shared:
|
||||
raise AssertionError('Executable/harness/fixture dependencies changed during verification')
|
||||
report = {'kind':f'simd_{focus}_arm_vs_native_x86', 'passed':True, 'canonical_forms':len(family.CANONICAL_FORMS),
|
||||
'functions':len(oracle['functions']), 'original_full_frame_captures':len(oracle['records']),
|
||||
'compiler_source_sha256':compiler, 'compiler_executable_sha256':cli_sha,
|
||||
'harness_source_sha256':shared[str(Path(engine.__file__).relative_to(ROOT))], 'shared_sources_sha256':shared,
|
||||
'original_oracle_receipt_sha256':oracle['receipt_sha256'], 'original_producer':oracle['producer'],
|
||||
'input_derivation':'Only X30 becomes STOP for actual runtime guest RET; original inputs/capture frames remain immutable. Leaf native RET is harness-owned. All other imported state bytes remain unchanged.',
|
||||
'control_readbacks':oracle['control_readbacks'], 'profiles':profiles, 'verification_wall_seconds':time.monotonic() - started,
|
||||
'complete_native_state_comparisons':sum(profile['raw_native']['complete_native_state_comparisons'] for profile in profiles),
|
||||
'direct_original_math_native_comparisons':sum(profile['raw_native']['direct_original_math_native_comparisons'] for profile in profiles),
|
||||
'requested_storage_native_policy_comparisons':sum(profile['raw_native']['requested_storage_native_policy_comparisons'] for profile in profiles),
|
||||
'native_mxcsr_preservation_comparisons':sum(profile['raw_native']['caller_mxcsr_preservation_comparisons'] for profile in profiles),
|
||||
'runtime_complete_state_comparisons':sum(profile['runtime']['complete_state_comparisons'] for profile in profiles),
|
||||
'limits':'Enabled nonstreaming integer/crypto SIMD only. Full784B primary/model/native equality is distinct from requested FP storage unavailable in original readbacks. No numerical FP-enable refusals, model-only originals, joined-original, disabled-feature/access, Apple-hardware, process/OS or performance claim.'}
|
||||
path = write_evidence(ROOT / f'.stela/simd-{focus}-differential-report.json', report)
|
||||
return path, report
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Pure instruction fixtures; execution belongs to the shared SIMD adapter."""
|
||||
|
||||
FAMILIES = ('aes', 'sha12', 'sha512', 'sha3', 'i8mm')
|
||||
@@ -0,0 +1,206 @@
|
||||
"""Classic .16B AES fixtures: independent polynomial model, complete state.
|
||||
|
||||
Scope: FEAT_AES, FP/AdvSIMD enabled and non-streaming; no upper scalable
|
||||
register, disabled-access, physical timing or PSTATE.DIT verification claim.
|
||||
The shared engine owns original/native execution, binaries and evidence.
|
||||
"""
|
||||
import random
|
||||
|
||||
from differential import State, seed_extended_state
|
||||
|
||||
FOCUS = 'aes'
|
||||
CANONICAL_FORMS = (
|
||||
'AESE_B_cryptoaes', 'AESD_B_cryptoaes',
|
||||
'AESMC_B_cryptoaes', 'AESIMC_B_cryptoaes',
|
||||
)
|
||||
FORM_VALUES = {'aese': 0x4e284800, 'aesd': 0x4e285800,
|
||||
'aesmc': 0x4e286800, 'aesimc': 0x4e287800}
|
||||
FORM_MASK = 0xfffffc00
|
||||
FIELD_POLYNOMIAL = 0x11b
|
||||
BYTE_MASK = 0xff
|
||||
LIMB_MASK = (1 << 64) - 1
|
||||
FORWARD_MATRIX = ((2, 3, 1, 1), (1, 2, 3, 1),
|
||||
(1, 1, 2, 3), (3, 1, 1, 2))
|
||||
INVERSE_MATRIX = ((14, 11, 13, 9), (9, 14, 11, 13),
|
||||
(13, 9, 14, 11), (11, 13, 9, 14))
|
||||
|
||||
|
||||
def field_multiply(left, right):
|
||||
"""Schoolbook carryless polynomial product, then independent reduction."""
|
||||
product = 0
|
||||
for bit in range(8):
|
||||
if right & (1 << bit):
|
||||
product ^= left << bit
|
||||
for degree in range(14, 7, -1):
|
||||
if product & (1 << degree):
|
||||
product ^= FIELD_POLYNOMIAL << (degree - 8)
|
||||
return product
|
||||
|
||||
|
||||
def field_inverse(value):
|
||||
result = 1
|
||||
factor = value
|
||||
power = 254
|
||||
while power:
|
||||
if power & 1:
|
||||
result = field_multiply(result, factor)
|
||||
factor = field_multiply(factor, factor)
|
||||
power >>= 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()
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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('<II', word, 0xd65f0000 | operation(function).get('return_register', 30) << 5)
|
||||
if 'source_hex' in function:
|
||||
assert bytes.fromhex(function['source_hex']) == canonical_source
|
||||
words.append(word)
|
||||
assert len(set(words)) == len(words), 'Each exact subject word must have one function'
|
||||
for index, case in enumerate(cases):
|
||||
offset = index * INPUT_STRIDE
|
||||
function_index = struct.unpack_from('<Q', inputs, offset)[0]
|
||||
assert function_index < len(functions), index
|
||||
for field in ('function', 'function_index'):
|
||||
if field in case:
|
||||
assert case[field] == function_index, (index, field)
|
||||
if 'initial_state_sha256' in case:
|
||||
assert case['initial_state_sha256'] == sha(inputs[offset + 8:offset + 8 + STATE_BYTES]), index
|
||||
assert inputs[offset + 8 + STATE_BYTES:offset + INPUT_STRIDE] == bytes(8), index
|
||||
return files, functions, cases, inputs, words
|
||||
|
||||
|
||||
def mov(register, value):
|
||||
lines = [f'movz {register},#{value & 65535}']
|
||||
lines.extend(f'movk {register},#{value >> 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('<IIQQQQIIQQ', data, section_offset + index * section_stride)
|
||||
for index in range(section_count)]
|
||||
symbols = {}
|
||||
for section in sections:
|
||||
if section[1] != 2:
|
||||
continue
|
||||
strings = sections[section[6]]
|
||||
string_data = data[strings[4]:strings[4] + strings[5]]
|
||||
assert section[9] == 24
|
||||
for offset in range(section[4], section[4] + section[5], section[9]):
|
||||
name, _, _, section_index, value, size = struct.unpack_from('<IBBHQQ', data, offset)
|
||||
end = string_data.find(b'\0', name)
|
||||
symbols[string_data[name:end].decode()] = (section_index, value, size)
|
||||
subjects = []
|
||||
for index, word in enumerate(words):
|
||||
section_index, pc, _ = symbols[f'subject_{index}']
|
||||
section = sections[section_index]
|
||||
offset = section[4] + pc - section[3]
|
||||
actual = data[offset:offset + 8]
|
||||
assert actual == struct.pack('<II', word, SVC_WORD), (index, actual.hex())
|
||||
canonical = bytes.fromhex(functions[index]['source_hex'])
|
||||
subjects.append({'function_index': index, 'instruction_pc': pc, 'svc_pc': pc + 4,
|
||||
'expected_elr': pc + 8, 'executed_source_hex': actual.hex(),
|
||||
'executed_source_sha256': sha(actual), 'canonical_source_hex': canonical.hex(),
|
||||
'canonical_source_sha256': sha(canonical), 'elf_offset': offset})
|
||||
assert symbols['_start'][1] == TEXT_ADDRESS
|
||||
assert symbols['vectors'][1] % 2048 == 0
|
||||
return subjects
|
||||
|
||||
|
||||
def prepare(directory, focus, source_bindings):
|
||||
directory = Path(directory).resolve()
|
||||
directory.relative_to(ROOT)
|
||||
if not focus or any(character not in "abcdefghijklmnopqrstuvwxyz0123456789_" for character in focus):
|
||||
raise ValueError("Invalid original observer focus")
|
||||
for name, identity in source_bindings.items():
|
||||
if sha((ROOT / name).read_bytes()) != identity:
|
||||
raise AssertionError("Frozen original source binding changed: " + name)
|
||||
files, functions, cases, inputs, words = load_corpus(directory)
|
||||
source = assembly(words, len(cases)).encode()
|
||||
qemu, clang, lld, bindings = tools_and_bindings()
|
||||
bindings['focus'] = focus
|
||||
bindings['source_receipts'] = source_bindings
|
||||
bindings['observer_dependencies'] = {'dev/differential.py': sha((ROOT / 'dev/differential.py').read_bytes())}
|
||||
bindings['inputs'] = {name: {'sha256': sha(data), 'bytes': len(data)} for name, data in files.items()}
|
||||
key = sha(source + json_bytes(bindings))
|
||||
destination = directory / key
|
||||
destination.mkdir(exist_ok=True)
|
||||
for name, data in files.items():
|
||||
write_new(destination / name, data)
|
||||
write_new(destination / 'guest.S', source)
|
||||
write_new(destination / 'original.py', Path(__file__).read_bytes())
|
||||
write_new(destination / 'bindings.json', json_bytes(bindings))
|
||||
if not (destination / 'guest.elf').exists():
|
||||
command = [str(clang), '--target=aarch64-unknown-none-elf', '-c', str(destination / 'guest.S'), '-o', str(destination / 'guest.o')]
|
||||
write_new(destination / 'assemble-command.json', json_bytes(command))
|
||||
subprocess.run(command, check=True)
|
||||
env = os.environ.copy()
|
||||
if lld.name == 'rust-lld' and os.uname().sysname == 'Darwin':
|
||||
env['DYLD_LIBRARY_PATH'] = str(lld.resolve().parents[3])
|
||||
command = [str(lld), *(['-flavor', 'gnu'] if lld.name == 'rust-lld' else []),
|
||||
'-m', 'aarch64elf', '-Ttext', hex(TEXT_ADDRESS), '-e', '_start',
|
||||
str(destination / 'guest.o'), '-o', str(destination / 'guest.elf')]
|
||||
write_new(destination / 'link-command.json', json_bytes(command))
|
||||
subprocess.run(command, check=True, env=env)
|
||||
subjects = elf_subjects(destination / 'guest.elf', words, functions)
|
||||
write_new(destination / 'subjects.json', json_bytes(subjects))
|
||||
return destination, qemu, bindings, functions, cases, inputs, subjects
|
||||
|
||||
|
||||
def execute(destination, qemu, count):
|
||||
with tempfile.TemporaryDirectory(prefix='stela-simd-original-el0-') as temporary:
|
||||
endpoint = Path(temporary) / 'qmp'
|
||||
command = [str(qemu), '-machine', 'virt,secure=off,virtualization=off', '-cpu', CPU_MODEL,
|
||||
'-accel', 'tcg', '-m', '512M', '-display', 'none', '-serial', 'none',
|
||||
'-monitor', 'none', '-nic', 'none', '-kernel', str(destination / 'guest.elf'),
|
||||
'-device', f'loader,file={destination / "inputs.bin"},addr={INPUT_ADDRESS:#x},force-raw=on',
|
||||
'-qmp', f'unix:{endpoint},server=on,wait=off', '-S']
|
||||
write_new(destination / 'qemu-command.json', json_bytes(command))
|
||||
with (destination / 'stderr.log').open('xb') as log:
|
||||
process = subprocess.Popen(command, stdout=log, stderr=log)
|
||||
stream = connection = None
|
||||
try:
|
||||
deadline = time.monotonic() + 15
|
||||
while not endpoint.exists():
|
||||
if process.poll() is not None or time.monotonic() > 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('<Q', inputs, input_offset)[0]
|
||||
initial = inputs[input_offset + 8:input_offset + 8 + STATE_BYTES]
|
||||
record = results[HEADER_BYTES + index * RECORD_BYTES:HEADER_BYTES + (index + 1) * RECORD_BYTES]
|
||||
requested_fpcr, requested_fpsr = struct.unpack_from('<II', initial, 776)
|
||||
pre_fpcr, pre_fpsr = struct.unpack_from('<QQ', record, LAYOUT['pre_fpcr'])
|
||||
observed = {name: struct.unpack_from('<Q', record, offset)[0]
|
||||
for name, offset in LAYOUT.items() if name not in ('x', 'v')}
|
||||
assert pre_fpcr == requested_fpcr & QEMU_FPCR_MASK, (index, 'pre_fpcr')
|
||||
assert pre_fpsr == requested_fpsr & QEMU_FPSR_MASK, (index, 'pre_fpsr')
|
||||
op = operation(functions[function_index])
|
||||
assert record[:248] == initial[:248], (index, 'all_gprs_unchanged')
|
||||
assert observed['sp'] == struct.unpack_from('<Q', initial, 248)[0], (index, 'sp')
|
||||
initial_nzcv = struct.unpack_from('<I', initial, 256)[0]
|
||||
assert observed['spsr'] == (initial_nzcv & NZCV_MASK) | PSTATE_EL0T_MASKED, (index, 'spsr_unchanged')
|
||||
assert observed['fpcr'] == pre_fpcr, (index, 'fpcr_unchanged')
|
||||
assert observed['fpsr'] & pre_fpsr == pre_fpsr, (index, 'sticky_fpsr')
|
||||
assert observed['fpsr'] & FPSR_QC == pre_fpsr & FPSR_QC, (index, 'qc_unchanged')
|
||||
assert observed['fpsr'] & ~QEMU_FPSR_MASK == 0, (index, 'reserved_fpsr')
|
||||
assert observed['esr'] >> 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())}))
|
||||
@@ -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()
|
||||
@@ -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('<I', op['word']), 0)], [op['name']])
|
||||
selected = [row for row in records if row.get('runtime')]
|
||||
self.assertEqual(len(selected), 90)
|
||||
self.assertEqual({ops[row['function']]['canonical_id'] for row in selected}, set(sha12.CANONICAL_FORMS))
|
||||
self.assertEqual({State.from_buffer_copy(row['initial']).nzcv >> 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('<I', operation['word']), 0)], [operation['name']])
|
||||
self.assertFalse(operation['scalar'])
|
||||
self.assertEqual((operation['lane'], operation['bytes'], operation['output_kind']), (8, 16, 'vector'))
|
||||
for name in sha512.FORMS:
|
||||
positions = [operation for operation in functions if operation['name'] == name and operation['layout'] == 'all_registers']
|
||||
self.assertEqual({operation['d'] for operation in positions}, set(range(32)))
|
||||
self.assertEqual({operation['n'] for operation in positions}, set(range(32)))
|
||||
if name != 'sha512su0':
|
||||
self.assertEqual({operation['m'] for operation in positions}, set(range(32)))
|
||||
self.assertEqual({record['function'] for record in records}, set(range(157)))
|
||||
for record in records:
|
||||
self.assertEqual(len(record['initial']), ctypes.sizeof(State))
|
||||
for name in sha512.FORMS:
|
||||
first = next((index for (index, operation) in enumerate(functions) if operation['name'] == name))
|
||||
self.assertEqual({record['pattern'] for record in records if record['function'] == first}, set(range(72)))
|
||||
with self.assertRaises(ValueError):
|
||||
sha512.operation('sha512h', d=32)
|
||||
with self.assertRaises(ValueError):
|
||||
sha512.operation('sha512su2')
|
||||
|
||||
def test_sha512_hash_oracle_matches_independent_two_round_recurrence(self):
|
||||
mask = (1 << 64) - 1
|
||||
|
||||
def rotate(value, amount):
|
||||
return sum(((value >> (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('<I', operation['word']), 0)], [operation['name']])
|
||||
self.assertEqual((operation['bytes'], operation['scalar'], operation['output_kind']), (16, False, 'vector'))
|
||||
for name in sha3.FORMS:
|
||||
matching = [operation for operation in functions if operation['name'] == name]
|
||||
self.assertEqual({operation['d'] for operation in matching}, set(range(32)))
|
||||
roles = ('d', 'n', 'm', 'a') if name in ('eor3', 'bcax') else ('d', 'n', 'm')
|
||||
for role in roles:
|
||||
self.assertTrue(any((operation[role] == 31 for operation in matching)), (name, role))
|
||||
partitions = set(sha3.alias_partitions(len(roles)))
|
||||
self.assertEqual(len(partitions), 15 if len(roles) == 4 else 5)
|
||||
for amount in range(64) if name == 'xar' else (None,):
|
||||
observed = set()
|
||||
for operation in matching:
|
||||
if amount is not None and operation['amount'] != amount:
|
||||
continue
|
||||
groups = {}
|
||||
observed.add(tuple((groups.setdefault(operation[role], len(groups)) for role in roles)))
|
||||
self.assertEqual(observed, partitions, (name, amount))
|
||||
self.assertEqual(len(sha3.representatives(functions)), 11)
|
||||
self.assertEqual({operation['name'] for operation in sha3.chain()}, set(sha3.FORMS))
|
||||
for (name, options) in [('sha512', {}), ('xar', {'amount': -1}), ('xar', {'amount': 64}), ('rax1', {'amount': 1}), ('bcax', {'a': 32}), ('eor3', {'n': -1})]:
|
||||
with self.assertRaises(ValueError):
|
||||
sha3.operation(name, **options)
|
||||
|
||||
def test_sha3_truth_table_and_complement_operand_order(self):
|
||||
initial = State()
|
||||
for (name, truth) in [('eor3', (0, 1, 1, 0, 1, 0, 0, 1)), ('bcax', (0, 0, 1, 0, 1, 1, 0, 1))]:
|
||||
operation = sha3.operation(name)
|
||||
for (row, output) in enumerate(truth):
|
||||
sha3.seed(initial, operation, row)
|
||||
result = sha3.expected(operation, initial)
|
||||
self.assertEqual(list(result.v[0]), [sha3.MASK64 if output else 0, sha3.MASK64 if truth[row ^ 7] else 0])
|
||||
initial.v[1][:] = [0, 0]
|
||||
initial.v[2][:] = [17361641481138401520, 12297829382473034410]
|
||||
initial.v[31][:] = [1085102592571150095, 6148914691236517205]
|
||||
result = sha3.expected(sha3.operation('bcax'), initial)
|
||||
self.assertEqual(list(result.v[0]), list(initial.v[2]))
|
||||
|
||||
def test_sha3_bit_index_rotates_keep_lanes_independent_for_all_immediates(self):
|
||||
initial = State()
|
||||
initial.v[1][:] = [81985529216486895, 9223372036854775809]
|
||||
initial.v[2][:] = [0, 0]
|
||||
for rotation in range(64):
|
||||
result = sha3.expected(sha3.operation('xar', amount=rotation), initial)
|
||||
expected = []
|
||||
for value in initial.v[1]:
|
||||
bits = f'{value:064b}'
|
||||
expected.append(int(bits[-rotation:] + bits[:-rotation], 2) if rotation else value)
|
||||
self.assertEqual(list(result.v[0]), expected, rotation)
|
||||
initial.v[2][:] = [9223372036854775809, 1]
|
||||
result = sha3.expected(sha3.operation('rax1'), initial)
|
||||
self.assertEqual(list(result.v[0]), [initial.v[1][0] ^ 3, initial.v[1][1] ^ 2])
|
||||
|
||||
def test_sha3_source_snapshot_and_preservation_are_complete_784_byte_states(self):
|
||||
initial = State()
|
||||
seed_extended_state(initial, 1443)
|
||||
(initial.x[0], initial.sp, initial.reserved) = (4660, 22136, 2882400001)
|
||||
(initial.nzcv, initial.fpcr, initial.fpsr) = (4026531840, 130588423, 134217887)
|
||||
for name in sha3.FORMS:
|
||||
operation = sha3.operation(name, d=31, n=31, m=31, a=31, amount=63 if name == 'xar' else 0)
|
||||
actual = sha3.expected(operation, initial)
|
||||
expected = State.from_buffer_copy(initial)
|
||||
if name == 'xar':
|
||||
expected.v[31][:] = [0, 0]
|
||||
elif name == 'rax1':
|
||||
expected.v[31][:] = [value ^ (value << 1 & sha3.MASK64 | value >> 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('<II', self.op['word'], engine.RET).hex()}]).encode(),
|
||||
'cases.json':json.dumps([{key:value for key, value in cases[0].items() if key != 'initial'}]).encode(),
|
||||
'inputs.bin':struct.pack('<Q', 0) + bytes(self.initial) + bytes(8),
|
||||
'results.bin':bytes(1024) + bytes(snapshot), 'guest.elf':b'unit-test-elf'}
|
||||
for name, data in files.items():
|
||||
(directory / name).write_bytes(data)
|
||||
producer = {'directory':str(directory.relative_to(ROOT)), 'cases':1,
|
||||
'passed_transport_and_architectural_frame_checks':True,
|
||||
'files':{name:{'sha256':engine.digest(data), 'bytes':len(data)} for name, data in files.items()}}
|
||||
receipt = directory / 'receipt.json'
|
||||
receipt.write_text(json.dumps(producer))
|
||||
pointer = directory / 'pointer.json'
|
||||
pointer.write_text(json.dumps({'directory':producer['directory'],
|
||||
'receipt':{'path':str(receipt.relative_to(ROOT)), 'sha256':engine.digest(receipt.read_bytes())}}))
|
||||
word_at = {BASE:self.op['word'], BASE + 4:engine.FP_REGISTER_SVC}
|
||||
with patch.object(engine, 'fp_register_elf_word', side_effect=lambda elf, pc:word_at[pc]):
|
||||
loaded = runner.load_original(engine, self.family, pointer)
|
||||
record = loaded['records'][0]
|
||||
self.assertEqual(record['equality_basis'], 'requested_storage_policy')
|
||||
self.assertEqual(State.from_buffer_copy(record['primary_expected']).fpcr, 0)
|
||||
self.assertEqual(State.from_buffer_copy(record['expected']).fpcr, 0x9f00)
|
||||
self.assertEqual(State.from_buffer_copy(record['initial']).fpcr, 0x9f00)
|
||||
self.assertEqual((directory / 'results.bin').read_bytes(), files['results.bin'])
|
||||
|
||||
def test_promoted_observer_takes_explicit_focus_and_frozen_source_bindings(self):
|
||||
with tempfile.TemporaryDirectory(dir=ROOT / '.stela/research/integer-crypto-harness') as temporary:
|
||||
directory = Path(temporary)
|
||||
operations, records = runner.fixture_corpus(self.family)
|
||||
engine.prepare_full_frame_numerical_oracle(directory, operations, records, 'sha3')
|
||||
with patch.object(simd_original, 'tools_and_bindings', side_effect=RuntimeError('tools reached')) as tools:
|
||||
with self.assertRaisesRegex(AssertionError, 'Frozen original source binding changed'):
|
||||
simd_original.prepare(directory, 'sha3', {'dev/differential.py':'incorrect'})
|
||||
tools.assert_not_called()
|
||||
with self.assertRaisesRegex(ValueError, 'Invalid original observer focus'):
|
||||
simd_original.prepare(directory, '../not-a-focus', {})
|
||||
tools.assert_not_called()
|
||||
with self.assertRaisesRegex(RuntimeError, 'tools reached'):
|
||||
simd_original.prepare(directory, 'sha3',
|
||||
{'dev/differential.py':engine.digest((ROOT / 'dev/differential.py').read_bytes())})
|
||||
self.assertEqual(tools.call_count, 1)
|
||||
@@ -41,6 +41,32 @@ def fixtures():
|
||||
|
||||
|
||||
class IsaProgressTests(unittest.TestCase):
|
||||
def test_cssc_fixed_encoding_alternative_is_explicit_and_canonical(self):
|
||||
catalog = json.loads((progress.ROOT / 'tests/isa/a64-documented-checklist.json').read_bytes())
|
||||
facts = progress.a64_checklist.validate(catalog)
|
||||
cssc = [row for row in facts.values()
|
||||
if any(feature['feature'] == 'FEAT_CSSC' for feature in row['features'])]
|
||||
self.assertEqual(len(cssc), 22)
|
||||
decoder = type('UnavailableDecoder', (), {'disasm': lambda self, data, address: iter(())})()
|
||||
for row in cssc:
|
||||
word = int(row['encoding_value'], 16) | 0x3ff
|
||||
mnemonic, assembly, basis = progress.smoke_decoding(decoder, word, row['id'], facts)
|
||||
self.assertEqual((mnemonic, assembly), (row['mnemonic'].lower(), row['mnemonic'].lower()))
|
||||
self.assertEqual(basis, 'pinned_arm_cssc_fixed_encoding')
|
||||
with self.assertRaises(ValueError):
|
||||
progress.smoke_decoding(decoder, word ^ (1 << 31), row['id'], facts)
|
||||
|
||||
def test_fixed_encoding_alternative_does_not_cover_other_families_or_missing_facts(self):
|
||||
catalog = json.loads((progress.ROOT / 'tests/isa/a64-documented-checklist.json').read_bytes())
|
||||
facts = progress.a64_checklist.validate(catalog)
|
||||
decoder = type('UnavailableDecoder', (), {'disasm': lambda self, data, address: iter(())})()
|
||||
for identity in ('ABS_32_dp_1src', 'RET_64R_branch_reg'):
|
||||
row = facts[identity]
|
||||
with self.assertRaises(ValueError):
|
||||
progress.smoke_decoding(decoder, int(row['encoding_value'], 16), identity)
|
||||
with self.assertRaises(ValueError):
|
||||
progress.smoke_decoding(decoder, progress.RET, 'RET_64R_branch_reg', facts)
|
||||
|
||||
def test_implementation_refresh_preserves_archived_verification_checkpoint(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
@@ -407,7 +433,7 @@ class BlockProgressTests(unittest.TestCase):
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
leaf = progress.validate_registry(json.loads((root / 'tests/isa/apple-silicon-reviewed-forms.json').read_text()))
|
||||
block = progress.validate_registry(json.loads((root / 'tests/isa/apple-silicon-block-forms.json').read_text()))
|
||||
self.assertEqual(progress.summarize(leaf)['reviewed']['implemented'], 585)
|
||||
self.assertEqual(progress.summarize(leaf)['reviewed']['implemented'], 635)
|
||||
self.assertEqual(progress.summarize(leaf)['reviewed']['partial'], 20)
|
||||
self.assertEqual(progress.summarize(block)['reviewed']['implemented'], 434)
|
||||
self.assertEqual(progress.summarize(block)['reviewed']['partial'], 2)
|
||||
@@ -420,7 +446,7 @@ class BlockProgressTests(unittest.TestCase):
|
||||
'traps': {'native_comparisons': 320,
|
||||
'comparison_field': 'trap_state_exit_comparisons'}}}}
|
||||
text = progress.markdown(report)
|
||||
self.assertIn('| Leaf-profile instruction forms implemented | 585 |', text)
|
||||
self.assertIn('| Leaf-profile instruction forms implemented | 635 |', text)
|
||||
self.assertIn('| Block-profile instruction forms implemented | 434 |', text)
|
||||
self.assertIn('| Native block state/exit comparisons | 28,704 |', text)
|
||||
self.assertIn('| Block-profile forms partially implemented | 2 |', text)
|
||||
|
||||
@@ -171,7 +171,22 @@ def compile_probe(cli, word, directory, expect_failure=None, run=subprocess.run,
|
||||
**({'abi': manifest['abi'], 'source_bytes': consumed, 'compiler_mode': mode} if mode != 'leaf' else {})}
|
||||
|
||||
|
||||
def smoke_forms(cli, forms, overrides, directory, mode='leaf'):
|
||||
def smoke_decoding(decoder, word, identity, canonical_facts=None):
|
||||
instruction = next(decoder.disasm(struct.pack('<I', word), 0), None)
|
||||
if instruction is not None:
|
||||
return instruction.mnemonic, f'{instruction.mnemonic} {instruction.op_str}', 'capstone'
|
||||
# CSSC has no reserved operand combinations beyond its fixed encoding bits.
|
||||
# This limited alternative uses independently hash-validated Arm facts;
|
||||
# it does not claim that the installed Capstone decoded the instruction.
|
||||
fact = (canonical_facts or {}).get(identity)
|
||||
if (fact is not None and any(feature['feature'] == 'FEAT_CSSC' for feature in fact['features'])
|
||||
and word & int(fact['encoding_mask'], 16) == int(fact['encoding_value'], 16)):
|
||||
mnemonic = fact['mnemonic'].lower()
|
||||
return mnemonic, mnemonic, 'pinned_arm_cssc_fixed_encoding'
|
||||
raise ValueError(f'Independent decoder declined {identity}: {word:#x}')
|
||||
|
||||
|
||||
def smoke_forms(cli, forms, overrides, directory, mode='leaf', canonical_facts=None):
|
||||
decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
|
||||
fingerprint = None
|
||||
results = []
|
||||
@@ -180,8 +195,8 @@ def smoke_forms(cli, forms, overrides, directory, mode='leaf'):
|
||||
continue
|
||||
for index, sample in enumerate(row['smoke_samples']):
|
||||
word = validate_sample(forms[identity], sample)
|
||||
instruction = next(decoder.disasm(struct.pack('<I', word), 0), None)
|
||||
if instruction is None or instruction.mnemonic not in sample['expected_mnemonics']:
|
||||
mnemonic, assembly, basis = smoke_decoding(decoder, word, identity, canonical_facts)
|
||||
if mnemonic not in sample['expected_mnemonics']:
|
||||
raise ValueError(f'Independent decoder differs for {identity}: {word:#x}')
|
||||
location = directory / f'{len(results)}-supported'
|
||||
location.mkdir()
|
||||
@@ -192,7 +207,8 @@ def smoke_forms(cli, forms, overrides, directory, mode='leaf'):
|
||||
if fingerprint is not None and fingerprint != probe['compiler_source_sha256']:
|
||||
raise ValueError('Compiler changed during ISA progress probes')
|
||||
fingerprint = probe['compiler_source_sha256']
|
||||
results.append({'id': identity, 'sample': index, 'assembly': f'{instruction.mnemonic} {instruction.op_str}', **probe})
|
||||
results.append({'id': identity, 'sample': index, 'assembly': assembly,
|
||||
'independent_decode_basis': basis, **probe})
|
||||
for index, sample in enumerate(row.get('rejected_samples', [])):
|
||||
location = directory / f'{len(results)}-rejected'
|
||||
location.mkdir()
|
||||
@@ -450,6 +466,7 @@ def main():
|
||||
service_rows = validate_registry(service_registry)
|
||||
catalog_data = args.checklist.read_bytes()
|
||||
catalog = json.loads(catalog_data)
|
||||
canonical_facts = a64_checklist.validate(catalog)
|
||||
apple_profiles_data = args.apple_profiles.read_bytes()
|
||||
apple_profiles = json.loads(apple_profiles_data)
|
||||
apple = json.loads((ROOT / 'tests/isa/apple-specific-extensions.json').read_bytes())
|
||||
@@ -462,13 +479,15 @@ def main():
|
||||
raise ValueError('Block registry must declare the native block-exit compiler ABI')
|
||||
executable_hash = sha256(args.cli)
|
||||
with tempfile.TemporaryDirectory(prefix='stela-apple-progress-') as temporary:
|
||||
compiler, probes = smoke_forms(args.cli, rows, rows, Path(temporary))
|
||||
compiler, probes = smoke_forms(args.cli, rows, rows, Path(temporary), canonical_facts=canonical_facts)
|
||||
block_directory = Path(temporary) / 'blocks'
|
||||
block_directory.mkdir()
|
||||
block_compiler, block_probes = smoke_forms(args.cli, block_rows, block_rows, block_directory, mode='block')
|
||||
block_compiler, block_probes = smoke_forms(args.cli, block_rows, block_rows, block_directory,
|
||||
mode='block', canonical_facts=canonical_facts)
|
||||
service_directory = Path(temporary) / 'services'
|
||||
service_directory.mkdir()
|
||||
service_compiler, service_probes = smoke_forms(args.cli, service_rows, service_rows, service_directory, mode='service')
|
||||
service_compiler, service_probes = smoke_forms(args.cli, service_rows, service_rows, service_directory,
|
||||
mode='service', canonical_facts=canonical_facts)
|
||||
if block_compiler != compiler or service_compiler != compiler:
|
||||
raise ValueError('Leaf and block compiler identities differ')
|
||||
if args.implementation_only:
|
||||
|
||||
+22
@@ -2519,3 +2519,25 @@ mod clock_cli_tests {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cpu_target_cli_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cpu_selectors_keep_native_and_explicit_capabilities_distinct() {
|
||||
use stela_compiler::TargetCpu;
|
||||
assert_eq!(parse_cpu_target("native"), Ok(TargetCpu::detect()));
|
||||
assert_eq!(
|
||||
parse_cpu_target("baseline+popcnt+bmi1+aes+sha"),
|
||||
Ok(TargetCpu::Baseline
|
||||
.with_popcnt()
|
||||
.with_bmi1()
|
||||
.with_aes()
|
||||
.with_sha())
|
||||
);
|
||||
for invalid in ["native+aes", "baseline+sha+aes", "baseline+bmi1+bmi1"] {
|
||||
assert!(parse_cpu_target(invalid).is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2138,20 +2138,20 @@
|
||||
},
|
||||
"facts_sha256": "fff5ee6ca3eb54bc4c9d52f749373725a0261175d843ab23cebfaa5dd87d0db3",
|
||||
"assessment": {
|
||||
"implemented": 1060,
|
||||
"implemented": 1110,
|
||||
"partial": 14,
|
||||
"unsupported": 3258,
|
||||
"unsupported": 3208,
|
||||
"total": 4332,
|
||||
"implementation_percentage": 24.469067405355496,
|
||||
"implementation_percentage": 25.62326869806094,
|
||||
"categories": {
|
||||
"base_integer_system": {
|
||||
"unsupported": 673,
|
||||
"implemented": 276,
|
||||
"implemented": 298,
|
||||
"unsupported": 651,
|
||||
"partial": 5
|
||||
},
|
||||
"fp_simd": {
|
||||
"implemented": 784,
|
||||
"unsupported": 419,
|
||||
"implemented": 812,
|
||||
"unsupported": 391,
|
||||
"partial": 9
|
||||
},
|
||||
"sme": {
|
||||
@@ -2162,7 +2162,7 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"compiler_source_sha256": "abe8a8be65ad81a1e7b13d4d283cea5de5789ba5f10a4b6b86232cdc3df73312",
|
||||
"compiler_source_sha256": "79ed2cf496d8e93d8c694f037a6268ee84a2a88e191e27cfcf996ca9b015f4b1",
|
||||
"evidence_reports": [],
|
||||
"assessment_basis": "reviewed_implementation_and_emission_smoke",
|
||||
"last_verified_checkpoint": {
|
||||
@@ -2173,8 +2173,8 @@
|
||||
"report_sha256": "e6673aaad69c8712258d7cc62215913ef2721a9972063ff041aab6f5591bf141"
|
||||
},
|
||||
"forms": [
|
||||
{"id":"ABS_32_dp_1src","instruction_id":"ABS","mnemonic":"ABS","category":"base_integer_system","source_file":"abs.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5ac02000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"ABS_64_dp_1src","instruction_id":"ABS","mnemonic":"ABS","category":"base_integer_system","source_file":"abs.xml","encoding_mask":"0xfffffc00","encoding_value":"0xdac02000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"ABS_32_dp_1src","instruction_id":"ABS","mnemonic":"ABS","category":"base_integer_system","source_file":"abs.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5ac02000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"ABS_64_dp_1src","instruction_id":"ABS","mnemonic":"ABS","category":"base_integer_system","source_file":"abs.xml","encoding_mask":"0xfffffc00","encoding_value":"0xdac02000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"ABS_asimdmisc_R","instruction_id":"ABS_advsimd","mnemonic":"ABS","category":"fp_simd","source_file":"abs_advsimd.xml","encoding_mask":"0xbf3ffc00","encoding_value":"0x0e20b800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"FP/AdvSIMD enabled. All allocated scalar/vector lane sizes and Q widths, ordinary V31 data, all source/destination overlaps, modulo integer results and Q=0/scalar upper-half clearing. NZCV/FPCR/FPSR unchanged."}]},
|
||||
{"id":"ABS_asisdmisc_R","instruction_id":"ABS_advsimd","mnemonic":"ABS","category":"fp_simd","source_file":"abs_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5ee0b800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"FP/AdvSIMD enabled. All allocated scalar/vector lane sizes and Q widths, ordinary V31 data, all source/destination overlaps, modulo integer results and Q=0/scalar upper-half clearing. NZCV/FPCR/FPSR unchanged."}]},
|
||||
{"id":"ADCS_32_addsub_carry","instruction_id":"ADCS","mnemonic":"ADCS","category":"base_integer_system","source_file":"adcs.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x3a000000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined operands and width for this canonical encoding form in the declared leaf profile; full PSTATE/system integration outside profile."}]},
|
||||
@@ -2203,10 +2203,10 @@
|
||||
{"id":"ADD_asisdsame_only","instruction_id":"ADD_advsimd","mnemonic":"ADD","category":"fp_simd","source_file":"add_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5ee08400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"FP/AdvSIMD enabled. All allocated scalar/vector lane sizes and Q widths, ordinary V31 data, all source/destination overlaps, modulo integer results and Q=0/scalar upper-half clearing. NZCV/FPCR/FPSR unchanged."}]},
|
||||
{"id":"ADRP_only_pcreladdr","instruction_id":"ADRP","mnemonic":"ADRP","category":"base_integer_system","source_file":"adrp.xml","encoding_mask":"0x9f000000","encoding_value":"0x90000000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All signed 21-bit immhi:immlo values and Xd destinations including discarded XZR; guest per-instruction PC, modulo-64-bit address formation, architectural 4 KiB ADRP granule regardless of mapping page size, and SP/NZCV/reserved-word preservation. Native output maintains ordered nonempty source-map intervals. No address dereference or platform ABI support is implied."}]},
|
||||
{"id":"ADR_only_pcreladdr","instruction_id":"ADR","mnemonic":"ADR","category":"base_integer_system","source_file":"adr.xml","encoding_mask":"0x9f000000","encoding_value":"0x10000000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All signed 21-bit immhi:immlo values and Xd destinations including discarded XZR; guest per-instruction PC, modulo-64-bit address formation, architectural 4 KiB ADRP granule regardless of mapping page size, and SP/NZCV/reserved-word preservation. Native output maintains ordered nonempty source-map intervals. No address dereference or platform ABI support is implied."}]},
|
||||
{"id":"AESD_B_cryptoaes","instruction_id":"AESD_advsimd","mnemonic":"AESD","category":"fp_simd","source_file":"aesd_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x4e285800","features":[{"feature":"FEAT_AES","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"AESE_B_cryptoaes","instruction_id":"AESE_advsimd","mnemonic":"AESE","category":"fp_simd","source_file":"aese_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x4e284800","features":[{"feature":"FEAT_AES","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"AESIMC_B_cryptoaes","instruction_id":"AESIMC_advsimd","mnemonic":"AESIMC","category":"fp_simd","source_file":"aesimc_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x4e287800","features":[{"feature":"FEAT_AES","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"AESMC_B_cryptoaes","instruction_id":"AESMC_advsimd","mnemonic":"AESMC","category":"fp_simd","source_file":"aesmc_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x4e286800","features":[{"feature":"FEAT_AES","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"AESD_B_cryptoaes","instruction_id":"AESD_advsimd","mnemonic":"AESD","category":"fp_simd","source_file":"aesd_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x4e285800","features":[{"feature":"FEAT_AES","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and AES. All register roles and aliases; pre-XOR rounds and column transformations write 128 bits. Fixed-work baseline, independent SSSE3 staging and checked AES-NI preserve NZCV, FPCR/FPSR and guest RAM. Disabled access, streaming, hardware timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"AESE_B_cryptoaes","instruction_id":"AESE_advsimd","mnemonic":"AESE","category":"fp_simd","source_file":"aese_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x4e284800","features":[{"feature":"FEAT_AES","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and AES. All register roles and aliases; pre-XOR rounds and column transformations write 128 bits. Fixed-work baseline, independent SSSE3 staging and checked AES-NI preserve NZCV, FPCR/FPSR and guest RAM. Disabled access, streaming, hardware timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"AESIMC_B_cryptoaes","instruction_id":"AESIMC_advsimd","mnemonic":"AESIMC","category":"fp_simd","source_file":"aesimc_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x4e287800","features":[{"feature":"FEAT_AES","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and AES. All register roles and aliases; pre-XOR rounds and column transformations write 128 bits. Fixed-work baseline, independent SSSE3 staging and checked AES-NI preserve NZCV, FPCR/FPSR and guest RAM. Disabled access, streaming, hardware timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"AESMC_B_cryptoaes","instruction_id":"AESMC_advsimd","mnemonic":"AESMC","category":"fp_simd","source_file":"aesmc_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x4e286800","features":[{"feature":"FEAT_AES","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and AES. All register roles and aliases; pre-XOR rounds and column transformations write 128 bits. Fixed-work baseline, independent SSSE3 staging and checked AES-NI preserve NZCV, FPCR/FPSR and guest RAM. Disabled access, streaming, hardware timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"ANDS_32S_log_imm","instruction_id":"ANDS_log_imm","mnemonic":"ANDS","category":"base_integer_system","source_file":"ands_log_imm.xml","encoding_mask":"0xffc00000","encoding_value":"0x72000000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined operands and width for this canonical encoding form in the declared leaf profile; full PSTATE/system integration outside profile."}]},
|
||||
{"id":"ANDS_32_log_shift","instruction_id":"ANDS_log_shift","mnemonic":"ANDS","category":"base_integer_system","source_file":"ands_log_shift.xml","encoding_mask":"0xff200000","encoding_value":"0x6a000000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined operands and width for this canonical encoding form in the declared leaf profile; full PSTATE/system integration outside profile."}]},
|
||||
{"id":"ANDS_64S_log_imm","instruction_id":"ANDS_log_imm","mnemonic":"ANDS","category":"base_integer_system","source_file":"ands_log_imm.xml","encoding_mask":"0xff800000","encoding_value":"0xf2000000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined operands and width for this canonical encoding form in the declared leaf profile; full PSTATE/system integration outside profile."}]},
|
||||
@@ -2239,7 +2239,7 @@
|
||||
{"id":"AUTIZA_64Z_dp_1src","instruction_id":"AUTIA","mnemonic":"AUTIZA","category":"base_integer_system","source_file":"autia.xml","encoding_mask":"0xffffffe0","encoding_value":"0xdac133e0","features":[{"feature":"FEAT_PAuth","name":"v8Ap3"}],"status":"implemented","profiles":[{"profile":"apple-arm64e-software-pauth-clock-v1","status":"implemented","scope":"Complete form in explicit classic software PAuth1 execution profile; GCS/BTI and PAuth_LR/FPAC disabled, exact immutable-source helper boundary."}]},
|
||||
{"id":"AUTIZB_64Z_dp_1src","instruction_id":"AUTIB","mnemonic":"AUTIZB","category":"base_integer_system","source_file":"autib.xml","encoding_mask":"0xffffffe0","encoding_value":"0xdac137e0","features":[{"feature":"FEAT_PAuth","name":"v8Ap3"}],"status":"implemented","profiles":[{"profile":"apple-arm64e-software-pauth-clock-v1","status":"implemented","scope":"Complete form in explicit classic software PAuth1 execution profile; GCS/BTI and PAuth_LR/FPAC disabled, exact immutable-source helper boundary."}]},
|
||||
{"id":"AXFLAG_M_pstate","instruction_id":"AXFLAG","mnemonic":"AXFLAG","category":"base_integer_system","source_file":"axflag.xml","encoding_mask":"0xfffff0ff","encoding_value":"0xd500405f","features":[{"feature":"FEAT_FlagM2","name":"v8Ap5"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FlagM/FlagM2 register-only profile with architectural NZCV. CFINV toggles C; RMIF selectively copies rotated Xn bits; SETF8/16 sets NZV from Wn and preserves C; AXFLAG/XAFLAG perform declared Boolean transforms. Register31 is ZR; ignored CRm bits follow pinned decode. All unrelated state and ordinary guest RAM are preserved. No complete PSTATE/DIT, disabled-feature guest exception delivery, application or OS compatibility claim."}]},
|
||||
{"id":"BCAX_VVV16_crypto4","instruction_id":"BCAX_advsimd","mnemonic":"BCAX","category":"fp_simd","source_file":"bcax_advsimd.xml","encoding_mask":"0xffe08000","encoding_value":"0xce200000","features":[{"feature":"FEAT_SHA3","name":"v8Ap2"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"BCAX_VVV16_crypto4","instruction_id":"BCAX_advsimd","mnemonic":"BCAX","category":"fp_simd","source_file":"bcax_advsimd.xml","encoding_mask":"0xffe08000","encoding_value":"0xce200000","features":[{"feature":"FEAT_SHA3","name":"v8Ap2"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA3. EOR3/BCAX three-source logic, qword RAX1 and every XAR immediate 0..63; all register roles and aliases. Full 128-bit destination, NZCV/FPCR/FPSR and guest RAM preserved. Disabled access, streaming/SVE spellings and Apple hardware remain outside scope."}]},
|
||||
{"id":"BC_only_condbranch","instruction_id":"BC_cond","mnemonic":"BC","category":"base_integer_system","source_file":"bc_cond.xml","encoding_mask":"0xff000010","encoding_value":"0x54000010","features":[{"feature":"FEAT_HBC","name":"v8Ap8"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"BF1CVTL_asimdmisc_V","instruction_id":"BF12CVTL_advsimd","mnemonic":"BF1CVTL","category":"fp_simd","source_file":"bf12cvtl_advsimd.xml","encoding_mask":"0xbffffc00","encoding_value":"0x2ea17800","features":[{"feature":"FEAT_FP8","name":"v9Ap5"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"BF2CVTL_asimdmisc_V","instruction_id":"BF12CVTL_advsimd","mnemonic":"BF2CVTL","category":"fp_simd","source_file":"bf12cvtl_advsimd.xml","encoding_mask":"0xbffffc00","encoding_value":"0x2ee17800","features":[{"feature":"FEAT_FP8","name":"v9Ap5"}],"status":"unsupported","profiles":[]},
|
||||
@@ -2389,8 +2389,8 @@
|
||||
{"id":"CMLT_asisdmisc_Z","instruction_id":"CMLT_advsimd","mnemonic":"CMLT","category":"fp_simd","source_file":"cmlt_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5ee0a800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"FP/AdvSIMD enabled. Every allocated integer lane size and vector/scalar arrangement, all overlaps and V31 data; per-lane all-ones/zero result masks, scalar/Q=0 upper-half clearing; NZCV/FPCR/FPSR preserved."}]},
|
||||
{"id":"CMTST_asimdsame_only","instruction_id":"CMTST_advsimd","mnemonic":"CMTST","category":"fp_simd","source_file":"cmtst_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x0e208c00","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"FP/AdvSIMD enabled. Every allocated integer lane size and vector/scalar arrangement, all overlaps and V31 data; per-lane all-ones/zero result masks, scalar/Q=0 upper-half clearing; NZCV/FPCR/FPSR preserved."}]},
|
||||
{"id":"CMTST_asisdsame_only","instruction_id":"CMTST_advsimd","mnemonic":"CMTST","category":"fp_simd","source_file":"cmtst_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5ee08c00","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"FP/AdvSIMD enabled. Every allocated integer lane size and vector/scalar arrangement, all overlaps and V31 data; per-lane all-ones/zero result masks, scalar/Q=0 upper-half clearing; NZCV/FPCR/FPSR preserved."}]},
|
||||
{"id":"CNT_32_dp_1src","instruction_id":"CNT","mnemonic":"CNT","category":"base_integer_system","source_file":"cnt.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5ac01c00","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"CNT_64_dp_1src","instruction_id":"CNT","mnemonic":"CNT","category":"base_integer_system","source_file":"cnt.xml","encoding_mask":"0xfffffc00","encoding_value":"0xdac01c00","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"CNT_32_dp_1src","instruction_id":"CNT","mnemonic":"CNT","category":"base_integer_system","source_file":"cnt.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5ac01c00","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"CNT_64_dp_1src","instruction_id":"CNT","mnemonic":"CNT","category":"base_integer_system","source_file":"cnt.xml","encoding_mask":"0xfffffc00","encoding_value":"0xdac01c00","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"CNT_asimdmisc_R","instruction_id":"CNT_advsimd","mnemonic":"CNT","category":"fp_simd","source_file":"cnt_advsimd.xml","encoding_mask":"0xbf3ffc00","encoding_value":"0x0e205800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"CPYEN_CPY_memcms","instruction_id":"CPYPN","mnemonic":"CPYEN","category":"base_integer_system","source_file":"cpypn.xml","encoding_mask":"0x3fe0fc00","encoding_value":"0x1d80c400","features":[{"feature":"FEAT_MOPS","name":"v8Ap8"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"CPYERN_CPY_memcms","instruction_id":"CPYPRN","mnemonic":"CPYERN","category":"base_integer_system","source_file":"cpyprn.xml","encoding_mask":"0x3fe0fc00","encoding_value":"0x1d808400","features":[{"feature":"FEAT_MOPS","name":"v8Ap8"}],"status":"unsupported","profiles":[]},
|
||||
@@ -2505,8 +2505,8 @@
|
||||
{"id":"CSINV_64_condsel","instruction_id":"CSINV","mnemonic":"CSINV","category":"base_integer_system","source_file":"csinv.xml","encoding_mask":"0xffe00c00","encoding_value":"0xda800000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined registers, overlaps, W32/X64 widths and 16 condition encodings including always-true AL/NV; false-arm transform at operand width, W32 zero extension, ZR operands and guest NZCV preservation in the declared leaf profile. Complete PSTATE/DIT and platform integration remain outside profile."}]},
|
||||
{"id":"CSNEG_32_condsel","instruction_id":"CSNEG","mnemonic":"CSNEG","category":"base_integer_system","source_file":"csneg.xml","encoding_mask":"0xffe00c00","encoding_value":"0x5a800400","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined registers, overlaps, W32/X64 widths and 16 condition encodings including always-true AL/NV; false-arm transform at operand width, W32 zero extension, ZR operands and guest NZCV preservation in the declared leaf profile. Complete PSTATE/DIT and platform integration remain outside profile."}]},
|
||||
{"id":"CSNEG_64_condsel","instruction_id":"CSNEG","mnemonic":"CSNEG","category":"base_integer_system","source_file":"csneg.xml","encoding_mask":"0xffe00c00","encoding_value":"0xda800400","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined registers, overlaps, W32/X64 widths and 16 condition encodings including always-true AL/NV; false-arm transform at operand width, W32 zero extension, ZR operands and guest NZCV preservation in the declared leaf profile. Complete PSTATE/DIT and platform integration remain outside profile."}]},
|
||||
{"id":"CTZ_32_dp_1src","instruction_id":"CTZ","mnemonic":"CTZ","category":"base_integer_system","source_file":"ctz.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5ac01800","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"CTZ_64_dp_1src","instruction_id":"CTZ","mnemonic":"CTZ","category":"base_integer_system","source_file":"ctz.xml","encoding_mask":"0xfffffc00","encoding_value":"0xdac01800","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"CTZ_32_dp_1src","instruction_id":"CTZ","mnemonic":"CTZ","category":"base_integer_system","source_file":"ctz.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5ac01800","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"CTZ_64_dp_1src","instruction_id":"CTZ","mnemonic":"CTZ","category":"base_integer_system","source_file":"ctz.xml","encoding_mask":"0xfffffc00","encoding_value":"0xdac01800","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"DCPS1_DC_exception","instruction_id":"DCPS1","mnemonic":"DCPS1","category":"base_integer_system","source_file":"dcps1.xml","encoding_mask":"0xffe0001f","encoding_value":"0xd4a00001","features":[],"status":"unsupported","profiles":[]},
|
||||
{"id":"DCPS2_DC_exception","instruction_id":"DCPS2","mnemonic":"DCPS2","category":"base_integer_system","source_file":"dcps2.xml","encoding_mask":"0xffe0001f","encoding_value":"0xd4a00002","features":[],"status":"unsupported","profiles":[]},
|
||||
{"id":"DCPS3_DC_exception","instruction_id":"DCPS3","mnemonic":"DCPS3","category":"base_integer_system","source_file":"dcps3.xml","encoding_mask":"0xffe0001f","encoding_value":"0xd4a00003","features":[],"status":"unsupported","profiles":[]},
|
||||
@@ -2520,7 +2520,7 @@
|
||||
{"id":"DUP_asisdone_only","instruction_id":"DUP_advsimd_elt","mnemonic":"DUP","category":"fp_simd","source_file":"dup_advsimd_elt.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e000400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated vector widths, lane sizes, indices and source-spec ignored bits; GPR31 is ZR and V31 ordinary data. Scalar/Q=0 upper clearing, INS unselected lanes, signed/unsigned GPR transfer width, all aliases, table register modulo-32 wrapping and unsigned OOB zero/preservation. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-FP traps, SME streaming or application execution claim."}]},
|
||||
{"id":"EON_32_log_shift","instruction_id":"EON","mnemonic":"EON","category":"base_integer_system","source_file":"eon.xml","encoding_mask":"0xff200000","encoding_value":"0x4a200000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined operands and width for this canonical encoding form in the declared leaf profile; full PSTATE/system integration outside profile."}]},
|
||||
{"id":"EON_64_log_shift","instruction_id":"EON","mnemonic":"EON","category":"base_integer_system","source_file":"eon.xml","encoding_mask":"0xff200000","encoding_value":"0xca200000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined operands and width for this canonical encoding form in the declared leaf profile; full PSTATE/system integration outside profile."}]},
|
||||
{"id":"EOR3_VVV16_crypto4","instruction_id":"EOR3_advsimd","mnemonic":"EOR3","category":"fp_simd","source_file":"eor3_advsimd.xml","encoding_mask":"0xffe08000","encoding_value":"0xce000000","features":[{"feature":"FEAT_SHA3","name":"v8Ap2"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"EOR3_VVV16_crypto4","instruction_id":"EOR3_advsimd","mnemonic":"EOR3","category":"fp_simd","source_file":"eor3_advsimd.xml","encoding_mask":"0xffe08000","encoding_value":"0xce000000","features":[{"feature":"FEAT_SHA3","name":"v8Ap2"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA3. EOR3/BCAX three-source logic, qword RAX1 and every XAR immediate 0..63; all register roles and aliases. Full 128-bit destination, NZCV/FPCR/FPSR and guest RAM preserved. Disabled access, streaming/SVE spellings and Apple hardware remain outside scope."}]},
|
||||
{"id":"EOR_32_log_imm","instruction_id":"EOR_log_imm","mnemonic":"EOR","category":"base_integer_system","source_file":"eor_log_imm.xml","encoding_mask":"0xffc00000","encoding_value":"0x52000000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined operands and width for this canonical encoding form in the declared leaf profile; full PSTATE/system integration outside profile."}]},
|
||||
{"id":"EOR_32_log_shift","instruction_id":"EOR_log_shift","mnemonic":"EOR","category":"base_integer_system","source_file":"eor_log_shift.xml","encoding_mask":"0xff200000","encoding_value":"0x4a000000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined operands and width for this canonical encoding form in the declared leaf profile; full PSTATE/system integration outside profile."}]},
|
||||
{"id":"EOR_64_log_imm","instruction_id":"EOR_log_imm","mnemonic":"EOR","category":"base_integer_system","source_file":"eor_log_imm.xml","encoding_mask":"0xff800000","encoding_value":"0xd2000000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined operands and width for this canonical encoding form in the declared leaf profile; full PSTATE/system integration outside profile."}]},
|
||||
@@ -3609,7 +3609,7 @@
|
||||
{"id":"PRFUM_P_ldst_unscaled","instruction_id":"PRFUM","mnemonic":"PRFUM","category":"base_integer_system","source_file":"prfum.xml","encoding_mask":"0xffe00c00","encoding_value":"0xf8800000","features":[],"status":"unsupported","profiles":[]},
|
||||
{"id":"PSB_HC_hints","instruction_id":"PSB","mnemonic":"PSB","category":"base_integer_system","source_file":"psb.xml","encoding_mask":"0xffffffff","encoding_value":"0xd503223f","features":[{"feature":"FEAT_SPE","name":"v8Ap2 && PROFILE_A"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"RADDHN_asimddiff_N","instruction_id":"RADDHN_advsimd","mnemonic":"RADDHN","category":"fp_simd","source_file":"raddhn_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x2e204000","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated 8/16/32-bit lane, width and Q half variant; ordinary V31 and all source/old-destination aliases. Signed/unsigned halving uses mathematical carry/borrow and round bias before truncation. High-half narrowing and XTN preserve low halves for 2 forms and clear upper halves for lower forms. Pairwise widening extends before summation/optional modular accumulation; SHLL shifts selected input halves by full original lane width. NZCV/FPCR/FPSR and RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or full application claim."}]},
|
||||
{"id":"RAX1_VVV2_cryptosha512_3","instruction_id":"RAX1_advsimd","mnemonic":"RAX1","category":"fp_simd","source_file":"rax1_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0xce608c00","features":[{"feature":"FEAT_SHA3","name":"v8Ap2"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"RAX1_VVV2_cryptosha512_3","instruction_id":"RAX1_advsimd","mnemonic":"RAX1","category":"fp_simd","source_file":"rax1_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0xce608c00","features":[{"feature":"FEAT_SHA3","name":"v8Ap2"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA3. EOR3/BCAX three-source logic, qword RAX1 and every XAR immediate 0..63; all register roles and aliases. Full 128-bit destination, NZCV/FPCR/FPSR and guest RAM preserved. Disabled access, streaming/SVE spellings and Apple hardware remain outside scope."}]},
|
||||
{"id":"RBIT_32_dp_1src","instruction_id":"RBIT_int","mnemonic":"RBIT","category":"base_integer_system","source_file":"rbit_int.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5ac00000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Complete scalar selected-width bit reversal, leading-sign count or byte-container reversal in declared private-RAM profile. Rn/Rd31 are ZR, aliases preserve inputs, W writes zero-extend; NZCV/V/FP and other state preserved. Full PSTATE/DIT remains outside profile."}]},
|
||||
{"id":"RBIT_64_dp_1src","instruction_id":"RBIT_int","mnemonic":"RBIT","category":"base_integer_system","source_file":"rbit_int.xml","encoding_mask":"0xfffffc00","encoding_value":"0xdac00000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Complete scalar selected-width bit reversal, leading-sign count or byte-container reversal in declared private-RAM profile. Rn/Rd31 are ZR, aliases preserve inputs, W writes zero-extend; NZCV/V/FP and other state preserved. Full PSTATE/DIT remains outside profile."}]},
|
||||
{"id":"RBIT_asimdmisc_R","instruction_id":"RBIT_advsimd","mnemonic":"RBIT","category":"fp_simd","source_file":"rbit_advsimd.xml","encoding_mask":"0xbffffc00","encoding_value":"0x2e605800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
@@ -3768,20 +3768,20 @@
|
||||
{"id":"SETP_SET_memcms","instruction_id":"SETP","mnemonic":"SETP","category":"base_integer_system","source_file":"setp.xml","encoding_mask":"0x3fe0fc00","encoding_value":"0x19c00400","features":[{"feature":"FEAT_MOPS","name":"v8Ap8"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SEVL_HI_hints","instruction_id":"SEVL","mnemonic":"SEVL","category":"base_integer_system","source_file":"sevl.xml","encoding_mask":"0xffffffff","encoding_value":"0xd50320bf","features":[],"status":"unsupported","profiles":[]},
|
||||
{"id":"SEV_HI_hints","instruction_id":"SEV","mnemonic":"SEV","category":"base_integer_system","source_file":"sev.xml","encoding_mask":"0xffffffff","encoding_value":"0xd503209f","features":[],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA1C_QSV_cryptosha3","instruction_id":"SHA1C_advsimd","mnemonic":"SHA1C","category":"fp_simd","source_file":"sha1c_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e000000","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA1H_SS_cryptosha2","instruction_id":"SHA1H_advsimd","mnemonic":"SHA1H","category":"fp_simd","source_file":"sha1h_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5e280800","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA1M_QSV_cryptosha3","instruction_id":"SHA1M_advsimd","mnemonic":"SHA1M","category":"fp_simd","source_file":"sha1m_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e002000","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA1P_QSV_cryptosha3","instruction_id":"SHA1P_advsimd","mnemonic":"SHA1P","category":"fp_simd","source_file":"sha1p_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e001000","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA1SU0_VVV_cryptosha3","instruction_id":"SHA1SU0_advsimd","mnemonic":"SHA1SU0","category":"fp_simd","source_file":"sha1su0_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e003000","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA1SU1_VV_cryptosha2","instruction_id":"SHA1SU1_advsimd","mnemonic":"SHA1SU1","category":"fp_simd","source_file":"sha1su1_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5e281800","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA256H2_QQV_cryptosha3","instruction_id":"SHA256H2_advsimd","mnemonic":"SHA256H2","category":"fp_simd","source_file":"sha256h2_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e005000","features":[{"feature":"FEAT_SHA256","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA256H_QQV_cryptosha3","instruction_id":"SHA256H_advsimd","mnemonic":"SHA256H","category":"fp_simd","source_file":"sha256h_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e004000","features":[{"feature":"FEAT_SHA256","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA256SU0_VV_cryptosha2","instruction_id":"SHA256SU0_advsimd","mnemonic":"SHA256SU0","category":"fp_simd","source_file":"sha256su0_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5e282800","features":[{"feature":"FEAT_SHA256","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA256SU1_VVV_cryptosha3","instruction_id":"SHA256SU1_advsimd","mnemonic":"SHA256SU1","category":"fp_simd","source_file":"sha256su1_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e006000","features":[{"feature":"FEAT_SHA256","name":"v8Ap0"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA512H2_QQV_cryptosha512_3","instruction_id":"SHA512H2_advsimd","mnemonic":"SHA512H2","category":"fp_simd","source_file":"sha512h2_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0xce608400","features":[{"feature":"FEAT_SHA512","name":"v8Ap2"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA512H_QQV_cryptosha512_3","instruction_id":"SHA512H_advsimd","mnemonic":"SHA512H","category":"fp_simd","source_file":"sha512h_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0xce608000","features":[{"feature":"FEAT_SHA512","name":"v8Ap2"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA512SU0_VV2_cryptosha512_2","instruction_id":"SHA512SU0_advsimd","mnemonic":"SHA512SU0","category":"fp_simd","source_file":"sha512su0_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0xcec08000","features":[{"feature":"FEAT_SHA512","name":"v8Ap2"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA512SU1_VVV2_cryptosha512_3","instruction_id":"SHA512SU1_advsimd","mnemonic":"SHA512SU1","category":"fp_simd","source_file":"sha512su1_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0xce608800","features":[{"feature":"FEAT_SHA512","name":"v8Ap2"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SHA1C_QSV_cryptosha3","instruction_id":"SHA1C_advsimd","mnemonic":"SHA1C","category":"fp_simd","source_file":"sha1c_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e000000","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA1/SHA256. All register roles and aliases; four-round updates and ordered schedules preserve original operand snapshots. SHA1H writes only the rotated low word and clears other destination bits. Independent SHA/SSSE3 mappings preserve NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA1H_SS_cryptosha2","instruction_id":"SHA1H_advsimd","mnemonic":"SHA1H","category":"fp_simd","source_file":"sha1h_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5e280800","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA1/SHA256. All register roles and aliases; four-round updates and ordered schedules preserve original operand snapshots. SHA1H writes only the rotated low word and clears other destination bits. Independent SHA/SSSE3 mappings preserve NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA1M_QSV_cryptosha3","instruction_id":"SHA1M_advsimd","mnemonic":"SHA1M","category":"fp_simd","source_file":"sha1m_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e002000","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA1/SHA256. All register roles and aliases; four-round updates and ordered schedules preserve original operand snapshots. SHA1H writes only the rotated low word and clears other destination bits. Independent SHA/SSSE3 mappings preserve NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA1P_QSV_cryptosha3","instruction_id":"SHA1P_advsimd","mnemonic":"SHA1P","category":"fp_simd","source_file":"sha1p_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e001000","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA1/SHA256. All register roles and aliases; four-round updates and ordered schedules preserve original operand snapshots. SHA1H writes only the rotated low word and clears other destination bits. Independent SHA/SSSE3 mappings preserve NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA1SU0_VVV_cryptosha3","instruction_id":"SHA1SU0_advsimd","mnemonic":"SHA1SU0","category":"fp_simd","source_file":"sha1su0_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e003000","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA1/SHA256. All register roles and aliases; four-round updates and ordered schedules preserve original operand snapshots. SHA1H writes only the rotated low word and clears other destination bits. Independent SHA/SSSE3 mappings preserve NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA1SU1_VV_cryptosha2","instruction_id":"SHA1SU1_advsimd","mnemonic":"SHA1SU1","category":"fp_simd","source_file":"sha1su1_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5e281800","features":[{"feature":"FEAT_SHA1","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA1/SHA256. All register roles and aliases; four-round updates and ordered schedules preserve original operand snapshots. SHA1H writes only the rotated low word and clears other destination bits. Independent SHA/SSSE3 mappings preserve NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA256H2_QQV_cryptosha3","instruction_id":"SHA256H2_advsimd","mnemonic":"SHA256H2","category":"fp_simd","source_file":"sha256h2_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e005000","features":[{"feature":"FEAT_SHA256","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA1/SHA256. All register roles and aliases; four-round updates and ordered schedules preserve original operand snapshots. SHA1H writes only the rotated low word and clears other destination bits. Independent SHA/SSSE3 mappings preserve NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA256H_QQV_cryptosha3","instruction_id":"SHA256H_advsimd","mnemonic":"SHA256H","category":"fp_simd","source_file":"sha256h_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e004000","features":[{"feature":"FEAT_SHA256","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA1/SHA256. All register roles and aliases; four-round updates and ordered schedules preserve original operand snapshots. SHA1H writes only the rotated low word and clears other destination bits. Independent SHA/SSSE3 mappings preserve NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA256SU0_VV_cryptosha2","instruction_id":"SHA256SU0_advsimd","mnemonic":"SHA256SU0","category":"fp_simd","source_file":"sha256su0_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0x5e282800","features":[{"feature":"FEAT_SHA256","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA1/SHA256. All register roles and aliases; four-round updates and ordered schedules preserve original operand snapshots. SHA1H writes only the rotated low word and clears other destination bits. Independent SHA/SSSE3 mappings preserve NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA256SU1_VVV_cryptosha3","instruction_id":"SHA256SU1_advsimd","mnemonic":"SHA256SU1","category":"fp_simd","source_file":"sha256su1_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x5e006000","features":[{"feature":"FEAT_SHA256","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA1/SHA256. All register roles and aliases; four-round updates and ordered schedules preserve original operand snapshots. SHA1H writes only the rotated low word and clears other destination bits. Independent SHA/SSSE3 mappings preserve NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA512H2_QQV_cryptosha512_3","instruction_id":"SHA512H2_advsimd","mnemonic":"SHA512H2","category":"fp_simd","source_file":"sha512h2_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0xce608400","features":[{"feature":"FEAT_SHA512","name":"v8Ap2"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA512. All register roles and aliases, exact sequential two-qword hash and schedule dependencies, full 128-bit destination. Baseline integer/SSE2 preserves NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA512H_QQV_cryptosha512_3","instruction_id":"SHA512H_advsimd","mnemonic":"SHA512H","category":"fp_simd","source_file":"sha512h_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0xce608000","features":[{"feature":"FEAT_SHA512","name":"v8Ap2"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA512. All register roles and aliases, exact sequential two-qword hash and schedule dependencies, full 128-bit destination. Baseline integer/SSE2 preserves NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA512SU0_VV2_cryptosha512_2","instruction_id":"SHA512SU0_advsimd","mnemonic":"SHA512SU0","category":"fp_simd","source_file":"sha512su0_advsimd.xml","encoding_mask":"0xfffffc00","encoding_value":"0xcec08000","features":[{"feature":"FEAT_SHA512","name":"v8Ap2"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA512. All register roles and aliases, exact sequential two-qword hash and schedule dependencies, full 128-bit destination. Baseline integer/SSE2 preserves NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHA512SU1_VVV2_cryptosha512_3","instruction_id":"SHA512SU1_advsimd","mnemonic":"SHA512SU1","category":"fp_simd","source_file":"sha512su1_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0xce608800","features":[{"feature":"FEAT_SHA512","name":"v8Ap2"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA512. All register roles and aliases, exact sequential two-qword hash and schedule dependencies, full 128-bit destination. Baseline integer/SSE2 preserves NZCV, FPCR/FPSR and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SHADD_asimdsame_only","instruction_id":"SHADD_advsimd","mnemonic":"SHADD","category":"fp_simd","source_file":"shadd_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x0e200400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated 8/16/32-bit lane, width and Q half variant; ordinary V31 and all source/old-destination aliases. Signed/unsigned halving uses mathematical carry/borrow and round bias before truncation. High-half narrowing and XTN preserve low halves for 2 forms and clear upper halves for lower forms. Pairwise widening extends before summation/optional modular accumulation; SHLL shifts selected input halves by full original lane width. NZCV/FPCR/FPSR and RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or full application claim."}]},
|
||||
{"id":"SHLL_asimdmisc_S","instruction_id":"SHLL_advsimd","mnemonic":"SHLL","category":"fp_simd","source_file":"shll_advsimd.xml","encoding_mask":"0xbf3ffc00","encoding_value":"0x2e213800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated 8/16/32-bit lane, width and Q half variant; ordinary V31 and all source/old-destination aliases. Signed/unsigned halving uses mathematical carry/borrow and round bias before truncation. High-half narrowing and XTN preserve low halves for 2 forms and clear upper halves for lower forms. Pairwise widening extends before summation/optional modular accumulation; SHLL shifts selected input halves by full original lane width. NZCV/FPCR/FPSR and RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or full application claim."}]},
|
||||
{"id":"SHL_asimdshf_R","instruction_id":"SHL_advsimd","mnemonic":"SHL","category":"fp_simd","source_file":"shl_advsimd.xml","encoding_mask":"0xbf80fc00","encoding_value":"0x0f005400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar D/vector width, immediate lane size and shift count; V31 and overlapping source/destination. Right shift by full lane width, integer rounding without overflow, modular accumulation and insertion preserve masks. Narrowing truncation and lower/upper-half writes, signed/unsigned widening source-half selection. Scalar/Q=0 upper clearing. Guest NZCV/FPCR/FPSR and RAM unchanged. No saturation/QC, disabled-FP exceptions, SME streaming or full application claim."}]},
|
||||
@@ -3803,24 +3803,24 @@
|
||||
{"id":"SMADDL_64WA_dp_3src","instruction_id":"SMADDL","mnemonic":"SMADDL","category":"base_integer_system","source_file":"smaddl.xml","encoding_mask":"0xffe08000","encoding_value":"0x9b200000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined W32 multiplicands and X64 addend/destination registers and overlaps, signed/unsigned source extension, modular X64 add/sub result, ZR operands and guest NZCV preservation in the declared leaf profile; complete PSTATE/DIT and platform integration remain outside profile."}]},
|
||||
{"id":"SMAXP_asimdsame_only","instruction_id":"SMAXP_advsimd","mnemonic":"SMAXP","category":"fp_simd","source_file":"smaxp_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x0e20a400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"SMAXV_asimdall_only","instruction_id":"SMAXV_advsimd","mnemonic":"SMAXV","category":"fp_simd","source_file":"smaxv_advsimd.xml","encoding_mask":"0xbf3ffc00","encoding_value":"0x0e30a800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"SMAX_32_dp_2src","instruction_id":"SMAX_reg","mnemonic":"SMAX","category":"base_integer_system","source_file":"smax_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x1ac06000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SMAX_32_minmax_imm","instruction_id":"SMAX_imm","mnemonic":"SMAX","category":"base_integer_system","source_file":"smax_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x11c00000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SMAX_64_dp_2src","instruction_id":"SMAX_reg","mnemonic":"SMAX","category":"base_integer_system","source_file":"smax_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x9ac06000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SMAX_64_minmax_imm","instruction_id":"SMAX_imm","mnemonic":"SMAX","category":"base_integer_system","source_file":"smax_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x91c00000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SMAX_32_dp_2src","instruction_id":"SMAX_reg","mnemonic":"SMAX","category":"base_integer_system","source_file":"smax_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x1ac06000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"SMAX_32_minmax_imm","instruction_id":"SMAX_imm","mnemonic":"SMAX","category":"base_integer_system","source_file":"smax_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x11c00000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"SMAX_64_dp_2src","instruction_id":"SMAX_reg","mnemonic":"SMAX","category":"base_integer_system","source_file":"smax_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x9ac06000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"SMAX_64_minmax_imm","instruction_id":"SMAX_imm","mnemonic":"SMAX","category":"base_integer_system","source_file":"smax_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x91c00000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"SMAX_asimdsame_only","instruction_id":"SMAX_advsimd","mnemonic":"SMAX","category":"fp_simd","source_file":"smax_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x0e206400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"SMC_EX_exception","instruction_id":"SMC","mnemonic":"SMC","category":"base_integer_system","source_file":"smc.xml","encoding_mask":"0xffe0001f","encoding_value":"0xd4000003","features":[],"status":"unsupported","profiles":[]},
|
||||
{"id":"SMINP_asimdsame_only","instruction_id":"SMINP_advsimd","mnemonic":"SMINP","category":"fp_simd","source_file":"sminp_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x0e20ac00","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"SMINV_asimdall_only","instruction_id":"SMINV_advsimd","mnemonic":"SMINV","category":"fp_simd","source_file":"sminv_advsimd.xml","encoding_mask":"0xbf3ffc00","encoding_value":"0x0e31a800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"SMIN_32_dp_2src","instruction_id":"SMIN_reg","mnemonic":"SMIN","category":"base_integer_system","source_file":"smin_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x1ac06800","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SMIN_32_minmax_imm","instruction_id":"SMIN_imm","mnemonic":"SMIN","category":"base_integer_system","source_file":"smin_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x11c80000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SMIN_64_dp_2src","instruction_id":"SMIN_reg","mnemonic":"SMIN","category":"base_integer_system","source_file":"smin_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x9ac06800","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SMIN_64_minmax_imm","instruction_id":"SMIN_imm","mnemonic":"SMIN","category":"base_integer_system","source_file":"smin_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x91c80000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SMIN_32_dp_2src","instruction_id":"SMIN_reg","mnemonic":"SMIN","category":"base_integer_system","source_file":"smin_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x1ac06800","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"SMIN_32_minmax_imm","instruction_id":"SMIN_imm","mnemonic":"SMIN","category":"base_integer_system","source_file":"smin_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x11c80000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"SMIN_64_dp_2src","instruction_id":"SMIN_reg","mnemonic":"SMIN","category":"base_integer_system","source_file":"smin_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x9ac06800","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"SMIN_64_minmax_imm","instruction_id":"SMIN_imm","mnemonic":"SMIN","category":"base_integer_system","source_file":"smin_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x91c80000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"SMIN_asimdsame_only","instruction_id":"SMIN_advsimd","mnemonic":"SMIN","category":"fp_simd","source_file":"smin_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x0e206c00","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"SMLAL_asimddiff_L","instruction_id":"SMLAL_advsimd_vec","mnemonic":"SMLAL","category":"fp_simd","source_file":"smlal_advsimd_vec.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x0e208000","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated 8/16/32-bit lanes and vector widths; normal Q=0 upper clearing and long/wide source-half selection. Full signed/unsigned doubled-width products, modular add/sub accumulation, widening ADD/SUB with full-width left operands for W forms, and mathematical signed/unsigned absolute differences before truncation. V31 and source/destination overlaps, including old accumulator values. Guest NZCV/FPCR/FPSR and RAM unchanged. Polynomial, high/saturating and indexed-element variants are separate forms; no disabled-feature traps, SME streaming or application execution claim."}]},
|
||||
{"id":"SMLAL_asimdelem_L","instruction_id":"SMLAL_advsimd_elt","mnemonic":"SMLAL","category":"fp_simd","source_file":"smlal_advsimd_elt.xml","encoding_mask":"0xbf00f400","encoding_value":"0x0f002000","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD, ordinary non-streaming execution. All allocated 16/32-bit indexed MUL/MLA/MLS and signed/unsigned long multiply/add/sub forms, vector widths, indices and source halves. Halfword indexed sources use V0..V15 and H:L:M; word sources use V0..V31 and H:L. Widening Q selects only the left source half. Full modular products/accumulation, all source/destination aliases, V31 and Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature traps, SME streaming or full application claim."}]},
|
||||
{"id":"SMLSL_asimddiff_L","instruction_id":"SMLSL_advsimd_vec","mnemonic":"SMLSL","category":"fp_simd","source_file":"smlsl_advsimd_vec.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x0e20a000","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated 8/16/32-bit lanes and vector widths; normal Q=0 upper clearing and long/wide source-half selection. Full signed/unsigned doubled-width products, modular add/sub accumulation, widening ADD/SUB with full-width left operands for W forms, and mathematical signed/unsigned absolute differences before truncation. V31 and source/destination overlaps, including old accumulator values. Guest NZCV/FPCR/FPSR and RAM unchanged. Polynomial, high/saturating and indexed-element variants are separate forms; no disabled-feature traps, SME streaming or application execution claim."}]},
|
||||
{"id":"SMLSL_asimdelem_L","instruction_id":"SMLSL_advsimd_elt","mnemonic":"SMLSL","category":"fp_simd","source_file":"smlsl_advsimd_elt.xml","encoding_mask":"0xbf00f400","encoding_value":"0x0f006000","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD, ordinary non-streaming execution. All allocated 16/32-bit indexed MUL/MLA/MLS and signed/unsigned long multiply/add/sub forms, vector widths, indices and source halves. Halfword indexed sources use V0..V15 and H:L:M; word sources use V0..V31 and H:L. Widening Q selects only the left source half. Full modular products/accumulation, all source/destination aliases, V31 and Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature traps, SME streaming or full application claim."}]},
|
||||
{"id":"SMMLA_asimdsame2_G","instruction_id":"SMMLA_advsimd_vec","mnemonic":"SMMLA","category":"fp_simd","source_file":"smmla_advsimd_vec.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x4e80a400","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SMMLA_asimdsame2_G","instruction_id":"SMMLA_advsimd_vec","mnemonic":"SMMLA","category":"fp_simd","source_file":"smmla_advsimd_vec.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x4e80a400","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and I8MM. Signed/unsigned/mixed 2x8-by-8x2 matrix accumulation, mixed dot vector/indexed forms, Q0/Q1 and all allocated Vm/index roles. Accumulation wraps modulo32; Q0 clears upper64. Baseline/checked SSSE3 preserve NZCV, FPCR/FPSR including QC and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SMOV_asimdins_W_w","instruction_id":"SMOV_advsimd","mnemonic":"SMOV","category":"fp_simd","source_file":"smov_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x0e002c00","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated vector widths, lane sizes, indices and source-spec ignored bits; GPR31 is ZR and V31 ordinary data. Scalar/Q=0 upper clearing, INS unselected lanes, signed/unsigned GPR transfer width, all aliases, table register modulo-32 wrapping and unsigned OOB zero/preservation. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-FP traps, SME streaming or application execution claim."}]},
|
||||
{"id":"SMOV_asimdins_X_x","instruction_id":"SMOV_advsimd","mnemonic":"SMOV","category":"fp_simd","source_file":"smov_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x4e002c00","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated vector widths, lane sizes, indices and source-spec ignored bits; GPR31 is ZR and V31 ordinary data. Scalar/Q=0 upper clearing, INS unselected lanes, signed/unsigned GPR transfer width, all aliases, table register modulo-32 wrapping and unsigned OOB zero/preservation. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-FP traps, SME streaming or application execution claim."}]},
|
||||
{"id":"SMSUBL_64WA_dp_3src","instruction_id":"SMSUBL","mnemonic":"SMSUBL","category":"base_integer_system","source_file":"smsubl.xml","encoding_mask":"0xffe08000","encoding_value":"0x9b208000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined W32 multiplicands and X64 addend/destination registers and overlaps, signed/unsigned source extension, modular X64 add/sub result, ZR operands and guest NZCV preservation in the declared leaf profile; complete PSTATE/DIT and platform integration remain outside profile."}]},
|
||||
@@ -4171,7 +4171,7 @@
|
||||
{"id":"SUB_64_addsub_shift","instruction_id":"SUB_addsub_shift","mnemonic":"SUB","category":"base_integer_system","source_file":"sub_addsub_shift.xml","encoding_mask":"0xff200000","encoding_value":"0xcb000000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined operands and width for this canonical encoding form in the declared leaf profile; full PSTATE/system integration outside profile."}]},
|
||||
{"id":"SUB_asimdsame_only","instruction_id":"SUB_advsimd","mnemonic":"SUB","category":"fp_simd","source_file":"sub_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x2e208400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"FP/AdvSIMD enabled. All allocated scalar/vector lane sizes and Q widths, ordinary V31 data, all source/destination overlaps, modulo integer results and Q=0/scalar upper-half clearing. NZCV/FPCR/FPSR unchanged."}]},
|
||||
{"id":"SUB_asisdsame_only","instruction_id":"SUB_advsimd","mnemonic":"SUB","category":"fp_simd","source_file":"sub_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x7ee08400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"FP/AdvSIMD enabled. All allocated scalar/vector lane sizes and Q widths, ordinary V31 data, all source/destination overlaps, modulo integer results and Q=0/scalar upper-half clearing. NZCV/FPCR/FPSR unchanged."}]},
|
||||
{"id":"SUDOT_asimdelem_D","instruction_id":"SUDOT_advsimd_elt","mnemonic":"SUDOT","category":"fp_simd","source_file":"sudot_advsimd_elt.xml","encoding_mask":"0xbfc0f400","encoding_value":"0x0f00f000","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"SUDOT_asimdelem_D","instruction_id":"SUDOT_advsimd_elt","mnemonic":"SUDOT","category":"fp_simd","source_file":"sudot_advsimd_elt.xml","encoding_mask":"0xbfc0f400","encoding_value":"0x0f00f000","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and I8MM. Signed/unsigned/mixed 2x8-by-8x2 matrix accumulation, mixed dot vector/indexed forms, Q0/Q1 and all allocated Vm/index roles. Accumulation wraps modulo32; Q0 clears upper64. Baseline/checked SSSE3 preserve NZCV, FPCR/FPSR including QC and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"SUQADD_asimdmisc_R","instruction_id":"SUQADD_advsimd","mnemonic":"SUQADD","category":"fp_simd","source_file":"suqadd_advsimd.xml","encoding_mask":"0xbf3ffc00","encoding_value":"0x0e203800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar B/H/S/D and vector arrangement, V31 ordinary data and all source/destination aliases. Signed/unsigned saturation, MIN ABS/NEG clamping, mixed-signedness accumulation including mathematical overflow beyond 64 bits, and signed/unsigned narrowing with scalar clearing/upper-half preservation. Active-lane saturation sets sticky FPSR.QC; inactive lanes cannot set it. Other FPSR bits, FPCR, NZCV and guest RAM unchanged. No disabled-feature traps, SME streaming, floating-point arithmetic/exception handling or complete process claim."}]},
|
||||
{"id":"SUQADD_asisdmisc_R","instruction_id":"SUQADD_advsimd","mnemonic":"SUQADD","category":"fp_simd","source_file":"suqadd_advsimd.xml","encoding_mask":"0xff3ffc00","encoding_value":"0x5e203800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar B/H/S/D and vector arrangement, V31 ordinary data and all source/destination aliases. Signed/unsigned saturation, MIN ABS/NEG clamping, mixed-signedness accumulation including mathematical overflow beyond 64 bits, and signed/unsigned narrowing with scalar clearing/upper-half preservation. Active-lane saturation sets sticky FPSR.QC; inactive lanes cannot set it. Other FPSR bits, FPCR, NZCV and guest RAM unchanged. No disabled-feature traps, SME streaming, floating-point arithmetic/exception handling or complete process claim."}]},
|
||||
{"id":"SVC_EX_exception","instruction_id":"SVC","mnemonic":"SVC","category":"base_integer_system","source_file":"svc.xml","encoding_mask":"0xffe0001f","encoding_value":"0xd4000001","features":[],"status":"partial","profiles":[{"profile":"direct-private-ram-block-v1","status":"partial","scope":"Partial: stop at the original instruction PC with preserved modeled GPR/SP/NZCV/reserved state, class and imm16. Preferred exception return is PC+4 for SVC and PC for BRK. No EL/PSTATE transition, vector dispatch, ESR/SPSR/ELR register update, syscall service or host trap is implemented. Input code extents remain nonwrapping; leaf compilation declines."}]},
|
||||
@@ -4262,23 +4262,23 @@
|
||||
{"id":"UMADDL_64WA_dp_3src","instruction_id":"UMADDL","mnemonic":"UMADDL","category":"base_integer_system","source_file":"umaddl.xml","encoding_mask":"0xffe08000","encoding_value":"0x9ba00000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined W32 multiplicands and X64 addend/destination registers and overlaps, signed/unsigned source extension, modular X64 add/sub result, ZR operands and guest NZCV preservation in the declared leaf profile; complete PSTATE/DIT and platform integration remain outside profile."}]},
|
||||
{"id":"UMAXP_asimdsame_only","instruction_id":"UMAXP_advsimd","mnemonic":"UMAXP","category":"fp_simd","source_file":"umaxp_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x2e20a400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"UMAXV_asimdall_only","instruction_id":"UMAXV_advsimd","mnemonic":"UMAXV","category":"fp_simd","source_file":"umaxv_advsimd.xml","encoding_mask":"0xbf3ffc00","encoding_value":"0x2e30a800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"UMAX_32U_minmax_imm","instruction_id":"UMAX_imm","mnemonic":"UMAX","category":"base_integer_system","source_file":"umax_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x11c40000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"UMAX_32_dp_2src","instruction_id":"UMAX_reg","mnemonic":"UMAX","category":"base_integer_system","source_file":"umax_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x1ac06400","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"UMAX_64U_minmax_imm","instruction_id":"UMAX_imm","mnemonic":"UMAX","category":"base_integer_system","source_file":"umax_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x91c40000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"UMAX_64_dp_2src","instruction_id":"UMAX_reg","mnemonic":"UMAX","category":"base_integer_system","source_file":"umax_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x9ac06400","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"UMAX_32U_minmax_imm","instruction_id":"UMAX_imm","mnemonic":"UMAX","category":"base_integer_system","source_file":"umax_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x11c40000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"UMAX_32_dp_2src","instruction_id":"UMAX_reg","mnemonic":"UMAX","category":"base_integer_system","source_file":"umax_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x1ac06400","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"UMAX_64U_minmax_imm","instruction_id":"UMAX_imm","mnemonic":"UMAX","category":"base_integer_system","source_file":"umax_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x91c40000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"UMAX_64_dp_2src","instruction_id":"UMAX_reg","mnemonic":"UMAX","category":"base_integer_system","source_file":"umax_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x9ac06400","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"UMAX_asimdsame_only","instruction_id":"UMAX_advsimd","mnemonic":"UMAX","category":"fp_simd","source_file":"umax_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x2e206400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"UMINP_asimdsame_only","instruction_id":"UMINP_advsimd","mnemonic":"UMINP","category":"fp_simd","source_file":"uminp_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x2e20ac00","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"UMINV_asimdall_only","instruction_id":"UMINV_advsimd","mnemonic":"UMINV","category":"fp_simd","source_file":"uminv_advsimd.xml","encoding_mask":"0xbf3ffc00","encoding_value":"0x2e31a800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"UMIN_32U_minmax_imm","instruction_id":"UMIN_imm","mnemonic":"UMIN","category":"base_integer_system","source_file":"umin_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x11cc0000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"UMIN_32_dp_2src","instruction_id":"UMIN_reg","mnemonic":"UMIN","category":"base_integer_system","source_file":"umin_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x1ac06c00","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"UMIN_64U_minmax_imm","instruction_id":"UMIN_imm","mnemonic":"UMIN","category":"base_integer_system","source_file":"umin_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x91cc0000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"UMIN_64_dp_2src","instruction_id":"UMIN_reg","mnemonic":"UMIN","category":"base_integer_system","source_file":"umin_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x9ac06c00","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"UMIN_32U_minmax_imm","instruction_id":"UMIN_imm","mnemonic":"UMIN","category":"base_integer_system","source_file":"umin_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x11cc0000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"UMIN_32_dp_2src","instruction_id":"UMIN_reg","mnemonic":"UMIN","category":"base_integer_system","source_file":"umin_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x1ac06c00","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"UMIN_64U_minmax_imm","instruction_id":"UMIN_imm","mnemonic":"UMIN","category":"base_integer_system","source_file":"umin_imm.xml","encoding_mask":"0xfffc0000","encoding_value":"0x91cc0000","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"UMIN_64_dp_2src","instruction_id":"UMIN_reg","mnemonic":"UMIN","category":"base_integer_system","source_file":"umin_reg.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x9ac06c00","features":[{"feature":"FEAT_CSSC","name":"v8Ap9"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FEAT_CSSC, all W32/X64 registers and allocated imm8 values. ZR, aliases, width truncation, zero extension and signed immediate extension preserve NZCV, SIMD/FP state and RAM. Disabled-feature traps, DIT timing guarantees and Apple hardware conformance remain outside scope."}]},
|
||||
{"id":"UMIN_asimdsame_only","instruction_id":"UMIN_advsimd","mnemonic":"UMIN","category":"fp_simd","source_file":"umin_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x2e206c00","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated vector width and integer lane size; V31 ordinary data and all aliases. Signed/unsigned lane, pairwise and across min/max; modular sums, signed/unsigned widening sums and scalar ADDP D source pair. Across results clear all upper vector bits. Independent byte CNT/RBIT/NOT and 8/16/32-bit CLZ/CLS, including zero/all-one and all leading counts. Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature exceptions, SME streaming, FP arithmetic or complete application claim."}]},
|
||||
{"id":"UMLAL_asimddiff_L","instruction_id":"UMLAL_advsimd_vec","mnemonic":"UMLAL","category":"fp_simd","source_file":"umlal_advsimd_vec.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x2e208000","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated 8/16/32-bit lanes and vector widths; normal Q=0 upper clearing and long/wide source-half selection. Full signed/unsigned doubled-width products, modular add/sub accumulation, widening ADD/SUB with full-width left operands for W forms, and mathematical signed/unsigned absolute differences before truncation. V31 and source/destination overlaps, including old accumulator values. Guest NZCV/FPCR/FPSR and RAM unchanged. Polynomial, high/saturating and indexed-element variants are separate forms; no disabled-feature traps, SME streaming or application execution claim."}]},
|
||||
{"id":"UMLAL_asimdelem_L","instruction_id":"UMLAL_advsimd_elt","mnemonic":"UMLAL","category":"fp_simd","source_file":"umlal_advsimd_elt.xml","encoding_mask":"0xbf00f400","encoding_value":"0x2f002000","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD, ordinary non-streaming execution. All allocated 16/32-bit indexed MUL/MLA/MLS and signed/unsigned long multiply/add/sub forms, vector widths, indices and source halves. Halfword indexed sources use V0..V15 and H:L:M; word sources use V0..V31 and H:L. Widening Q selects only the left source half. Full modular products/accumulation, all source/destination aliases, V31 and Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature traps, SME streaming or full application claim."}]},
|
||||
{"id":"UMLSL_asimddiff_L","instruction_id":"UMLSL_advsimd_vec","mnemonic":"UMLSL","category":"fp_simd","source_file":"umlsl_advsimd_vec.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x2e20a000","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated 8/16/32-bit lanes and vector widths; normal Q=0 upper clearing and long/wide source-half selection. Full signed/unsigned doubled-width products, modular add/sub accumulation, widening ADD/SUB with full-width left operands for W forms, and mathematical signed/unsigned absolute differences before truncation. V31 and source/destination overlaps, including old accumulator values. Guest NZCV/FPCR/FPSR and RAM unchanged. Polynomial, high/saturating and indexed-element variants are separate forms; no disabled-feature traps, SME streaming or application execution claim."}]},
|
||||
{"id":"UMLSL_asimdelem_L","instruction_id":"UMLSL_advsimd_elt","mnemonic":"UMLSL","category":"fp_simd","source_file":"umlsl_advsimd_elt.xml","encoding_mask":"0xbf00f400","encoding_value":"0x2f006000","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD, ordinary non-streaming execution. All allocated 16/32-bit indexed MUL/MLA/MLS and signed/unsigned long multiply/add/sub forms, vector widths, indices and source halves. Halfword indexed sources use V0..V15 and H:L:M; word sources use V0..V31 and H:L. Widening Q selects only the left source half. Full modular products/accumulation, all source/destination aliases, V31 and Q=0 upper clearing. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-feature traps, SME streaming or full application claim."}]},
|
||||
{"id":"UMMLA_asimdsame2_G","instruction_id":"UMMLA_advsimd_vec","mnemonic":"UMMLA","category":"fp_simd","source_file":"ummla_advsimd_vec.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x6e80a400","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"UMMLA_asimdsame2_G","instruction_id":"UMMLA_advsimd_vec","mnemonic":"UMMLA","category":"fp_simd","source_file":"ummla_advsimd_vec.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x6e80a400","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and I8MM. Signed/unsigned/mixed 2x8-by-8x2 matrix accumulation, mixed dot vector/indexed forms, Q0/Q1 and all allocated Vm/index roles. Accumulation wraps modulo32; Q0 clears upper64. Baseline/checked SSSE3 preserve NZCV, FPCR/FPSR including QC and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"UMOV_asimdins_W_w","instruction_id":"UMOV_advsimd","mnemonic":"UMOV","category":"fp_simd","source_file":"umov_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x0e003c00","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated vector widths, lane sizes, indices and source-spec ignored bits; GPR31 is ZR and V31 ordinary data. Scalar/Q=0 upper clearing, INS unselected lanes, signed/unsigned GPR transfer width, all aliases, table register modulo-32 wrapping and unsigned OOB zero/preservation. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-FP traps, SME streaming or application execution claim."}]},
|
||||
{"id":"UMOV_asimdins_X_x","instruction_id":"UMOV_advsimd","mnemonic":"UMOV","category":"fp_simd","source_file":"umov_advsimd.xml","encoding_mask":"0xffeffc00","encoding_value":"0x4e083c00","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated vector widths, lane sizes, indices and source-spec ignored bits; GPR31 is ZR and V31 ordinary data. Scalar/Q=0 upper clearing, INS unselected lanes, signed/unsigned GPR transfer width, all aliases, table register modulo-32 wrapping and unsigned OOB zero/preservation. NZCV/FPCR/FPSR and guest RAM unchanged. No disabled-FP traps, SME streaming or application execution claim."}]},
|
||||
{"id":"UMSUBL_64WA_dp_3src","instruction_id":"UMSUBL","mnemonic":"UMSUBL","category":"base_integer_system","source_file":"umsubl.xml","encoding_mask":"0xffe08000","encoding_value":"0x9ba08000","features":[],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"All defined W32 multiplicands and X64 addend/destination registers and overlaps, signed/unsigned source extension, modular X64 add/sub result, ZR operands and guest NZCV preservation in the declared leaf profile; complete PSTATE/DIT and platform integration remain outside profile."}]},
|
||||
@@ -4310,14 +4310,14 @@
|
||||
{"id":"URSQRTE_asimdmisc_R","instruction_id":"URSQRTE_advsimd","mnemonic":"URSQRTE","category":"fp_simd","source_file":"ursqrte_advsimd.xml","encoding_mask":"0xbfbffc00","encoding_value":"0x2ea1c800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-block-v1","status":"implemented","scope":"Unsigned 32-bit deterministic estimates in 2S/4S layouts follow the architectural domain/table rules, including out-of-domain all-ones saturation. Every FPCR field and retained enable is ignored, and all FPSR bits remain unchanged. The enabled AArch64 non-streaming FP/AdvSIMD/FP16/AFP profile declares FEAT_RPRES absent. Every AH=1 Single FRECPE/FRSQRTE original observation from a QEMU RPRES-enabled profile is classified as model scope, even when outputs coincide; it receives no direct original-equality credit. V0\u2013V31 are ordinary data and aliases are legal. Vectors ignore scalar NEP, evaluate active lanes only and clear Q=0 upper bits. Sources and old merge state are captured before transactional destination/sticky-status commit, preserving NZCV, unrelated registers and RAM. Baseline packed estimates form bounded keys and use private nearest-even DIV/SQRT plus integer conversion; scalar FRECPE uses exact integer division. Checked SSE4.1 H/S vector FRECPE and URECPE use RCPPS with exact integer threshold correction, clamped invalid unsigned keys and checked Half packing; Double vectors retain DIV. Conditional interior helpers validate immutable source at the original instruction; caller MXCSR is restored before every helper exit or guest commit. No numerical leaf ABI, enabled trap delivery, disabled-FP access, streaming SME, complete Apple hardware specification, application or OS execution is established."}]},
|
||||
{"id":"URSRA_asimdshf_R","instruction_id":"URSRA_advsimd","mnemonic":"URSRA","category":"fp_simd","source_file":"ursra_advsimd.xml","encoding_mask":"0xbf80fc00","encoding_value":"0x2f003400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar D/vector width, immediate lane size and shift count; V31 and overlapping source/destination. Right shift by full lane width, integer rounding without overflow, modular accumulation and insertion preserve masks. Narrowing truncation and lower/upper-half writes, signed/unsigned widening source-half selection. Scalar/Q=0 upper clearing. Guest NZCV/FPCR/FPSR and RAM unchanged. No saturation/QC, disabled-FP exceptions, SME streaming or full application claim."}]},
|
||||
{"id":"URSRA_asisdshf_R","instruction_id":"URSRA_advsimd","mnemonic":"URSRA","category":"fp_simd","source_file":"ursra_advsimd.xml","encoding_mask":"0xffc0fc00","encoding_value":"0x7f403400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar D/vector width, immediate lane size and shift count; V31 and overlapping source/destination. Right shift by full lane width, integer rounding without overflow, modular accumulation and insertion preserve masks. Narrowing truncation and lower/upper-half writes, signed/unsigned widening source-half selection. Scalar/Q=0 upper clearing. Guest NZCV/FPCR/FPSR and RAM unchanged. No saturation/QC, disabled-FP exceptions, SME streaming or full application claim."}]},
|
||||
{"id":"USDOT_asimdelem_D","instruction_id":"USDOT_advsimd_elt","mnemonic":"USDOT","category":"fp_simd","source_file":"usdot_advsimd_elt.xml","encoding_mask":"0xbfc0f400","encoding_value":"0x0f80f000","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"USDOT_asimdsame2_D","instruction_id":"USDOT_advsimd_vec","mnemonic":"USDOT","category":"fp_simd","source_file":"usdot_advsimd_vec.xml","encoding_mask":"0xbfe0fc00","encoding_value":"0x0e809c00","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"USDOT_asimdelem_D","instruction_id":"USDOT_advsimd_elt","mnemonic":"USDOT","category":"fp_simd","source_file":"usdot_advsimd_elt.xml","encoding_mask":"0xbfc0f400","encoding_value":"0x0f80f000","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and I8MM. Signed/unsigned/mixed 2x8-by-8x2 matrix accumulation, mixed dot vector/indexed forms, Q0/Q1 and all allocated Vm/index roles. Accumulation wraps modulo32; Q0 clears upper64. Baseline/checked SSSE3 preserve NZCV, FPCR/FPSR including QC and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"USDOT_asimdsame2_D","instruction_id":"USDOT_advsimd_vec","mnemonic":"USDOT","category":"fp_simd","source_file":"usdot_advsimd_vec.xml","encoding_mask":"0xbfe0fc00","encoding_value":"0x0e809c00","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and I8MM. Signed/unsigned/mixed 2x8-by-8x2 matrix accumulation, mixed dot vector/indexed forms, Q0/Q1 and all allocated Vm/index roles. Accumulation wraps modulo32; Q0 clears upper64. Baseline/checked SSSE3 preserve NZCV, FPCR/FPSR including QC and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"USHLL_asimdshf_L","instruction_id":"USHLL_advsimd","mnemonic":"USHLL","category":"fp_simd","source_file":"ushll_advsimd.xml","encoding_mask":"0xbf80fc00","encoding_value":"0x2f00a400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar D/vector width, immediate lane size and shift count; V31 and overlapping source/destination. Right shift by full lane width, integer rounding without overflow, modular accumulation and insertion preserve masks. Narrowing truncation and lower/upper-half writes, signed/unsigned widening source-half selection. Scalar/Q=0 upper clearing. Guest NZCV/FPCR/FPSR and RAM unchanged. No saturation/QC, disabled-FP exceptions, SME streaming or full application claim."}]},
|
||||
{"id":"USHL_asimdsame_only","instruction_id":"USHL_advsimd","mnemonic":"USHL","category":"fp_simd","source_file":"ushl_advsimd.xml","encoding_mask":"0xbf20fc00","encoding_value":"0x2e204400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated scalar/vector register-controlled SSHL/USHL/SRSHL/URSHL and SQSHL/UQSHL/SQRSHL/UQRSHL forms, plus immediate SQSHL/UQSHL/SQSHLU. Counts use only the signed low byte, with mathematical out-of-width and rounded-right behavior. Active-lane saturation sets sticky FPSR.QC; other status/control bits and RAM are unchanged. Source/count/destination aliases, V31, scalar/Q=0 upper clearing and all legal immediate counts are supported. Disabled-feature traps, streaming SME, guest exception delivery and full processes remain separate."}]},
|
||||
{"id":"USHL_asisdsame_only","instruction_id":"USHL_advsimd","mnemonic":"USHL","category":"fp_simd","source_file":"ushl_advsimd.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x7ee04400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. All allocated scalar/vector register-controlled SSHL/USHL/SRSHL/URSHL and SQSHL/UQSHL/SQRSHL/UQRSHL forms, plus immediate SQSHL/UQSHL/SQSHLU. Counts use only the signed low byte, with mathematical out-of-width and rounded-right behavior. Active-lane saturation sets sticky FPSR.QC; other status/control bits and RAM are unchanged. Source/count/destination aliases, V31, scalar/Q=0 upper clearing and all legal immediate counts are supported. Disabled-feature traps, streaming SME, guest exception delivery and full processes remain separate."}]},
|
||||
{"id":"USHR_asimdshf_R","instruction_id":"USHR_advsimd","mnemonic":"USHR","category":"fp_simd","source_file":"ushr_advsimd.xml","encoding_mask":"0xbf80fc00","encoding_value":"0x2f000400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar D/vector width, immediate lane size and shift count; V31 and overlapping source/destination. Right shift by full lane width, integer rounding without overflow, modular accumulation and insertion preserve masks. Narrowing truncation and lower/upper-half writes, signed/unsigned widening source-half selection. Scalar/Q=0 upper clearing. Guest NZCV/FPCR/FPSR and RAM unchanged. No saturation/QC, disabled-FP exceptions, SME streaming or full application claim."}]},
|
||||
{"id":"USHR_asisdshf_R","instruction_id":"USHR_advsimd","mnemonic":"USHR","category":"fp_simd","source_file":"ushr_advsimd.xml","encoding_mask":"0xffc0fc00","encoding_value":"0x7f400400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar D/vector width, immediate lane size and shift count; V31 and overlapping source/destination. Right shift by full lane width, integer rounding without overflow, modular accumulation and insertion preserve masks. Narrowing truncation and lower/upper-half writes, signed/unsigned widening source-half selection. Scalar/Q=0 upper clearing. Guest NZCV/FPCR/FPSR and RAM unchanged. No saturation/QC, disabled-FP exceptions, SME streaming or full application claim."}]},
|
||||
{"id":"USMMLA_asimdsame2_G","instruction_id":"USMMLA_advsimd_vec","mnemonic":"USMMLA","category":"fp_simd","source_file":"usmmla_advsimd_vec.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x4e80ac00","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"USMMLA_asimdsame2_G","instruction_id":"USMMLA_advsimd_vec","mnemonic":"USMMLA","category":"fp_simd","source_file":"usmmla_advsimd_vec.xml","encoding_mask":"0xffe0fc00","encoding_value":"0x4e80ac00","features":[{"feature":"FEAT_I8MM","name":"v8Ap2 && PROFILE_A"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and I8MM. Signed/unsigned/mixed 2x8-by-8x2 matrix accumulation, mixed dot vector/indexed forms, Q0/Q1 and all allocated Vm/index roles. Accumulation wraps modulo32; Q0 clears upper64. Baseline/checked SSSE3 preserve NZCV, FPCR/FPSR including QC and RAM. Disabled access, streaming and Apple hardware remain outside scope."}]},
|
||||
{"id":"USQADD_asimdmisc_R","instruction_id":"USQADD_advsimd","mnemonic":"USQADD","category":"fp_simd","source_file":"usqadd_advsimd.xml","encoding_mask":"0xbf3ffc00","encoding_value":"0x2e203800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar B/H/S/D and vector arrangement, V31 ordinary data and all source/destination aliases. Signed/unsigned saturation, MIN ABS/NEG clamping, mixed-signedness accumulation including mathematical overflow beyond 64 bits, and signed/unsigned narrowing with scalar clearing/upper-half preservation. Active-lane saturation sets sticky FPSR.QC; inactive lanes cannot set it. Other FPSR bits, FPCR, NZCV and guest RAM unchanged. No disabled-feature traps, SME streaming, floating-point arithmetic/exception handling or complete process claim."}]},
|
||||
{"id":"USQADD_asisdmisc_R","instruction_id":"USQADD_advsimd","mnemonic":"USQADD","category":"fp_simd","source_file":"usqadd_advsimd.xml","encoding_mask":"0xff3ffc00","encoding_value":"0x7e203800","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar B/H/S/D and vector arrangement, V31 ordinary data and all source/destination aliases. Signed/unsigned saturation, MIN ABS/NEG clamping, mixed-signedness accumulation including mathematical overflow beyond 64 bits, and signed/unsigned narrowing with scalar clearing/upper-half preservation. Active-lane saturation sets sticky FPSR.QC; inactive lanes cannot set it. Other FPSR bits, FPCR, NZCV and guest RAM unchanged. No disabled-feature traps, SME streaming, floating-point arithmetic/exception handling or complete process claim."}]},
|
||||
{"id":"USRA_asimdshf_R","instruction_id":"USRA_advsimd","mnemonic":"USRA","category":"fp_simd","source_file":"usra_advsimd.xml","encoding_mask":"0xbf80fc00","encoding_value":"0x2f001400","features":[{"feature":"FEAT_AdvSIMD","name":"v8Ap0"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FP/AdvSIMD. Every allocated scalar D/vector width, immediate lane size and shift count; V31 and overlapping source/destination. Right shift by full lane width, integer rounding without overflow, modular accumulation and insertion preserve masks. Narrowing truncation and lower/upper-half writes, signed/unsigned widening source-half selection. Scalar/Q=0 upper clearing. Guest NZCV/FPCR/FPSR and RAM unchanged. No saturation/QC, disabled-FP exceptions, SME streaming or full application claim."}]},
|
||||
@@ -4331,7 +4331,7 @@
|
||||
{"id":"WFIT_only_systeminstrswithreg","instruction_id":"WFIT","mnemonic":"WFIT","category":"base_integer_system","source_file":"wfit.xml","encoding_mask":"0xffffffe0","encoding_value":"0xd5031020","features":[{"feature":"FEAT_WFxT","name":"v8Ap7"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"WFI_HI_hints","instruction_id":"WFI","mnemonic":"WFI","category":"base_integer_system","source_file":"wfi.xml","encoding_mask":"0xffffffff","encoding_value":"0xd503207f","features":[],"status":"unsupported","profiles":[]},
|
||||
{"id":"XAFLAG_M_pstate","instruction_id":"XAFLAG","mnemonic":"XAFLAG","category":"base_integer_system","source_file":"xaflag.xml","encoding_mask":"0xfffff0ff","encoding_value":"0xd500403f","features":[{"feature":"FEAT_FlagM2","name":"v8Ap5"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled FlagM/FlagM2 register-only profile with architectural NZCV. CFINV toggles C; RMIF selectively copies rotated Xn bits; SETF8/16 sets NZV from Wn and preserves C; AXFLAG/XAFLAG perform declared Boolean transforms. Register31 is ZR; ignored CRm bits follow pinned decode. All unrelated state and ordinary guest RAM are preserved. No complete PSTATE/DIT, disabled-feature guest exception delivery, application or OS compatibility claim."}]},
|
||||
{"id":"XAR_VVV2_crypto3_imm6","instruction_id":"XAR_advsimd","mnemonic":"XAR","category":"fp_simd","source_file":"xar_advsimd.xml","encoding_mask":"0xffe00000","encoding_value":"0xce800000","features":[{"feature":"FEAT_SHA3","name":"v8Ap2"}],"status":"unsupported","profiles":[]},
|
||||
{"id":"XAR_VVV2_crypto3_imm6","instruction_id":"XAR_advsimd","mnemonic":"XAR","category":"fp_simd","source_file":"xar_advsimd.xml","encoding_mask":"0xffe00000","encoding_value":"0xce800000","features":[{"feature":"FEAT_SHA3","name":"v8Ap2"}],"status":"implemented","profiles":[{"profile":"direct-private-ram-leaf-v2","status":"implemented","scope":"Enabled nonstreaming FP/AdvSIMD and SHA3. EOR3/BCAX three-source logic, qword RAX1 and every XAR immediate 0..63; all register roles and aliases. Full 128-bit destination, NZCV/FPCR/FPSR and guest RAM preserved. Disabled access, streaming/SVE spellings and Apple hardware remain outside scope."}]},
|
||||
{"id":"XPACD_64Z_dp_1src","instruction_id":"XPAC","mnemonic":"XPACD","category":"base_integer_system","source_file":"xpac.xml","encoding_mask":"0xffffffe0","encoding_value":"0xdac147e0","features":[{"feature":"FEAT_PAuth","name":"v8Ap3"}],"status":"implemented","profiles":[{"profile":"apple-arm64e-software-pauth-clock-v1","status":"implemented","scope":"Complete form in explicit classic software PAuth1 execution profile; GCS/BTI and PAuth_LR/FPAC disabled, exact immutable-source helper boundary."}]},
|
||||
{"id":"XPACI_64Z_dp_1src","instruction_id":"XPAC","mnemonic":"XPACI","category":"base_integer_system","source_file":"xpac.xml","encoding_mask":"0xffffffe0","encoding_value":"0xdac143e0","features":[{"feature":"FEAT_PAuth","name":"v8Ap3"}],"status":"implemented","profiles":[{"profile":"apple-arm64e-software-pauth-clock-v1","status":"implemented","scope":"Complete form in explicit classic software PAuth1 execution profile; GCS/BTI and PAuth_LR/FPAC disabled, exact immutable-source helper boundary."}]},
|
||||
{"id":"XPACLRI_HI_hints","instruction_id":"XPAC","mnemonic":"XPACLRI","category":"base_integer_system","source_file":"xpac.xml","encoding_mask":"0xffffffff","encoding_value":"0xd50320ff","features":[{"feature":"FEAT_PAuth","name":"v8Ap3"}],"status":"implemented","profiles":[{"profile":"apple-arm64e-software-pauth-clock-v1","status":"implemented","scope":"Complete form in explicit classic software PAuth1 execution profile; GCS/BTI and PAuth_LR/FPAC disabled, exact immutable-source helper boundary."}]},
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
],
|
||||
"compiler_fingerprint_sources": [
|
||||
"crates/stela-compiler/src/lib.rs",
|
||||
"crates/stela-compiler/src/target.rs",
|
||||
"crates/stela-compiler/src/aarch64.rs",
|
||||
"crates/stela-compiler/src/x86_64.rs",
|
||||
"crates/stela-compiler/src/block.rs",
|
||||
@@ -62,6 +63,10 @@
|
||||
"crates/stela-compiler/src/x86_64/fp_register.rs",
|
||||
"crates/stela-compiler/src/aarch64/integer_math.rs",
|
||||
"crates/stela-compiler/src/x86_64/integer_math.rs",
|
||||
"crates/stela-compiler/src/aarch64/integer_unary.rs",
|
||||
"crates/stela-compiler/src/x86_64/integer_unary.rs",
|
||||
"crates/stela-compiler/src/aarch64/integer_minmax.rs",
|
||||
"crates/stela-compiler/src/x86_64/integer_minmax.rs",
|
||||
"crates/stela-compiler/src/aarch64/literal.rs",
|
||||
"crates/stela-compiler/src/x86_64/literal.rs",
|
||||
"crates/stela-compiler/src/aarch64/pc_relative.rs",
|
||||
@@ -71,6 +76,20 @@
|
||||
"crates/stela-compiler/src/x86_64/memory_store.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/aes.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/aes.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/aes/sbox.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/i8mm.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/i8mm.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/sha1.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/sha1.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/sha256.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/sha256.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/sha32.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/sha3.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/sha3.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/sha512.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/sha512.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/memory.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/memory.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/floating.rs",
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
],
|
||||
"compiler_fingerprint_sources": [
|
||||
"crates/stela-compiler/src/lib.rs",
|
||||
"crates/stela-compiler/src/target.rs",
|
||||
"crates/stela-compiler/src/aarch64.rs",
|
||||
"crates/stela-compiler/src/x86_64.rs",
|
||||
"crates/stela-compiler/src/block.rs",
|
||||
@@ -62,6 +63,10 @@
|
||||
"crates/stela-compiler/src/x86_64/fp_register.rs",
|
||||
"crates/stela-compiler/src/aarch64/integer_math.rs",
|
||||
"crates/stela-compiler/src/x86_64/integer_math.rs",
|
||||
"crates/stela-compiler/src/aarch64/integer_unary.rs",
|
||||
"crates/stela-compiler/src/x86_64/integer_unary.rs",
|
||||
"crates/stela-compiler/src/aarch64/integer_minmax.rs",
|
||||
"crates/stela-compiler/src/x86_64/integer_minmax.rs",
|
||||
"crates/stela-compiler/src/aarch64/literal.rs",
|
||||
"crates/stela-compiler/src/x86_64/literal.rs",
|
||||
"crates/stela-compiler/src/aarch64/pc_relative.rs",
|
||||
@@ -71,6 +76,20 @@
|
||||
"crates/stela-compiler/src/x86_64/memory_store.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/aes.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/aes.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/aes/sbox.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/i8mm.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/i8mm.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/sha1.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/sha1.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/sha256.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/sha256.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/sha32.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/sha3.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/sha3.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/sha512.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/sha512.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/memory.rs",
|
||||
"crates/stela-compiler/src/x86_64/simd/memory.rs",
|
||||
"crates/stela-compiler/src/aarch64/simd/floating.rs",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user