diff --git a/CHANGELOG.md b/CHANGELOG.md index ac7ace8..ac5e919 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ remains unsupported. - Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status. ### Added +- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op. - The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review. - Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review. - `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged. diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 0d81ca6..5b67f2c 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -31,6 +31,20 @@ pub struct CompiledShader { pub msl: String, } +/// Optional translation passes applied after verification. +/// +/// Default options preserve the historical IR shape: constants from scalar +/// evaluation and immediates remain, but pure vector expressions between +/// constants are not rewritten. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CompileOptions { + /// Replace pure vector unary/binary ops whose operands are already + /// `const.u32` with a single constant. Floating-point ops fold only when + /// the existing exact positive-normal rules accept the result. Loads, + /// stores, lane masks, merges and branches are never folded. + pub fold_constants: bool, +} + #[derive(Debug)] pub enum CompileError { InvalidLength { @@ -475,10 +489,23 @@ fn exact_float_result(operator: Binary, left: KnownBits, right: KnownBits) -> Op /// Compiles explicitly tagged raw machine code to a synthetic Metal compute kernel. /// /// Bind equal-length disjoint input and output word buffers and dispatch one -/// invocation per word in a one-dimensional grid. +/// invocation per word in a one-dimensional grid. Equivalent to +/// [`compile_with`] using [`CompileOptions::default`]. pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result { + compile_with(architecture, bytes, CompileOptions::default()) +} + +/// Compiles like [`compile`], with optional IR passes selected by `options`. +pub fn compile_with( + architecture: Architecture, + bytes: &[u8], + options: CompileOptions, +) -> Result { let decoded = decode_fixture(architecture, bytes)?; - let operations = lift(&decoded, bytes.len())?; + let mut operations = lift(&decoded, bytes.len())?; + if options.fold_constants { + fold_constant_ops(&mut operations); + } let disassembly = decoded.iter().map(|line| format!("{line}\n")).collect(); let mut ir = String::new(); @@ -1462,6 +1489,118 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { + const_value(operations, source).and_then(|bits| eval_unary(operator, bits)) + } + Op::Binary(operator, left, right) => { + match ( + const_value(operations, left), + const_value(operations, right), + ) { + (Some(left), Some(right)) => eval_binary(operator, left, right), + _ => None, + } + } + _ => None, + }; + if let Some(bits) = folded { + operations[index].1 = Op::Constant(bits); + } + } +} + +fn const_value(operations: &[(usize, Op)], value: Value) -> Option { + match operations.get(value.0).map(|(_, operation)| *operation)? { + Op::Constant(bits) => Some(bits), + _ => None, + } +} + +fn concrete_bits(facts: KnownBits) -> Option { + if let Some([first, second]) = facts.values { + return (first == second).then_some(first); + } + if facts.zero | facts.one == u32::MAX { + Some(facts.one) + } else { + None + } +} + +fn eval_unary(operator: VectorUnary, source: u32) -> Option { + Some(match operator { + VectorUnary::Not => !source, + VectorUnary::ReverseBits => source.reverse_bits(), + VectorUnary::FindHighUnsigned => { + if source == 0 { + 0xffff_ffff + } else { + source.leading_zeros() + } + } + VectorUnary::FindLow => { + if source == 0 { + 0xffff_ffff + } else { + source.trailing_zeros() + } + } + VectorUnary::FindHighSigned => { + if source == 0 || source == 0xffff_ffff { + 0xffff_ffff + } else { + (source ^ (0u32.wrapping_sub(source >> 31))).leading_zeros() + } + } + }) +} + +fn eval_binary(operator: Binary, left: u32, right: u32) -> Option { + match operator { + Binary::FloatAdd | Binary::FloatMul => concrete_bits(exact_float_result( + operator, + KnownBits::constant(left), + KnownBits::constant(right), + )?), + Binary::Vector(operation) => Some(eval_vector_binary(operation, left, right)), + } +} + +fn eval_vector_binary(operation: VectorBinary, left: u32, right: u32) -> u32 { + let i24 = |value: u32| ((value as i32) << 8) >> 8; + let u24 = |value: u32| value & 0x00ff_ffff; + match operation { + VectorBinary::Add => left.wrapping_add(right), + VectorBinary::Sub => left.wrapping_sub(right), + VectorBinary::Xnor => !(left ^ right), + VectorBinary::MinSigned => (left as i32).min(right as i32) as u32, + VectorBinary::MinUnsigned => left.min(right), + VectorBinary::MaxSigned => (left as i32).max(right as i32) as u32, + VectorBinary::MaxUnsigned => left.max(right), + VectorBinary::Mul24Signed => (i24(left) as u32).wrapping_mul(i24(right) as u32), + VectorBinary::Mul24Unsigned => u24(left).wrapping_mul(u24(right)), + VectorBinary::MulHi24Signed => { + ((i64::from(i24(left)) * i64::from(i24(right))) >> 32) as u32 + } + VectorBinary::MulHi24Unsigned => { + ((u64::from(u24(left)) * u64::from(u24(right))) >> 32) as u32 + } + VectorBinary::And => left & right, + VectorBinary::Or => left | right, + VectorBinary::Xor => left ^ right, + VectorBinary::ShiftLeft => left << (right & 31), + VectorBinary::ShiftRight => left >> (right & 31), + VectorBinary::ArithmeticShiftRight => ((left as i32) >> (right & 31)) as u32, + } +} + /// A wave-uniform constant operand at `offset`. fn constant( operations: &mut Vec<(usize, Op)>, @@ -1510,7 +1649,58 @@ fn merge_lanes( #[cfg(test)] mod tests { - use super::{Binary, KnownBits, exact_float_result}; + use super::{ + Binary, KnownBits, Op, Value, VectorBinary, VectorUnary, eval_unary, eval_vector_binary, + exact_float_result, vector_expression, + }; + + /// Every foldable vector op must keep a matching MSL template and eval arm + /// so the fold table cannot drift from emission. Match arms in + /// `vector_expression` / `eval_vector_binary` / unary `expression` are + /// exhaustive; this test calls both sides for each variant. + #[test] + fn every_foldable_vector_op_has_matching_msl_template() { + for operation in [ + VectorBinary::Add, + VectorBinary::Sub, + VectorBinary::Xnor, + VectorBinary::MinSigned, + VectorBinary::MinUnsigned, + VectorBinary::MaxSigned, + VectorBinary::MaxUnsigned, + VectorBinary::Mul24Signed, + VectorBinary::Mul24Unsigned, + VectorBinary::MulHi24Signed, + VectorBinary::MulHi24Unsigned, + VectorBinary::And, + VectorBinary::Or, + VectorBinary::Xor, + VectorBinary::ShiftLeft, + VectorBinary::ShiftRight, + VectorBinary::ArithmeticShiftRight, + ] { + let expression = vector_expression(operation, "left", "right"); + assert!( + !expression.is_empty(), + "missing MSL template for {operation:?}" + ); + let _ = eval_vector_binary(operation, 0x11, 0x22); + } + for operation in [ + VectorUnary::Not, + VectorUnary::ReverseBits, + VectorUnary::FindHighUnsigned, + VectorUnary::FindLow, + VectorUnary::FindHighSigned, + ] { + let expression = Op::Unary(operation, Value(0)).expression(&|v| v.to_string(), "", ""); + assert!( + !expression.is_empty(), + "missing MSL template for {operation:?}" + ); + assert!(eval_unary(operation, 0x8000_0001).is_some()); + } + } #[test] fn propagates_known_bits_through_integer_operators() { diff --git a/crates/shader/tests/compiler.rs b/crates/shader/tests/compiler.rs index d70f1f5..3243728 100644 --- a/crates/shader/tests/compiler.rs +++ b/crates/shader/tests/compiler.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later -use xenora_shader::{Architecture, CompileError, compile}; +use xenora_shader::{Architecture, CompileError, CompileOptions, compile, compile_with}; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin"); @@ -551,3 +551,314 @@ fn vop1_integer_fixture_lowers_unary_and_masked_swap() { include_str!("../../../fixtures/golden/vector-unary.metal") ); } + +// --- Opt-in constant folding: hand-computed known-answer fixtures ------------- +// Instruction words are built by hand to match the existing RDNA2 fixture shape +// (load, wait, mov literals, op, store). Expected constants are derived from the +// RDNA2 guide / MSL templates in lib.rs, then checked against fold-on IR. Fold-off +// (and default compile) must leave the op mnemonic in the IR. + +fn words(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() +} + +fn mov_lit(dst: u32) -> u32 { + 0x7e00_0000 | (dst << 17) | (1 << 9) | 255 +} + +fn vop2(op: u32, dst: u32, src0_vgpr: u32, src1_vgpr: u32) -> u32 { + (op << 25) | (dst << 17) | (src1_vgpr << 9) | (0x100 + src0_vgpr) +} + +fn vop1(op: u32, dst: u32, src_vgpr: u32) -> u32 { + 0x7e00_0000 | (dst << 17) | (op << 9) | (0x100 + src_vgpr) +} + +/// load v1; mov v2,A; mov v3,B; VOP2 dst=v2 (or v4); store the result VGPR. +fn binary_const_fixture(op: u32, left: u32, right: u32, dst_is_v4: bool) -> Vec { + let (dst, store_hi) = if dst_is_v4 { + (4u32, 0x8001_0400u32) + } else { + (2, 0x8001_0200) + }; + // For shift-rev forms the ISA encodes count in SRC0 and value in SRC1; the + // caller passes (count, value) already swapped into (src0, src1) via left/right + // naming below when needed. Non-rev forms use SRC0=v2, SRC1=v3. + let op_word = if dst_is_v4 { + // Shift-rev: v_l*rev dst, v3(count), v2(value) → SRC0=v3, SRC1=v2. + vop2(op, dst, 3, 2) + } else { + vop2(op, dst, 2, 3) + }; + words(&[ + 0xe030_2000, + 0x8000_0100, // buffer_load_dword v1 + 0xbf8c_3f70, // s_waitcnt vmcnt(0) + mov_lit(2), + left, // v_mov_b32 v2, left + mov_lit(3), + right, // v_mov_b32 v3, right + op_word, + 0xe070_2000, + store_hi, // buffer_store_dword result + 0xbbfd_0000, // s_waitcnt_vscnt + 0xbf81_0000, // s_endpgm + ]) +} + +fn unary_const_fixture(op: u32, source: u32) -> Vec { + words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + mov_lit(2), + source, // v_mov_b32 v2, source + vop1(op, 3, 2), // v_* v3, v2 + 0xe070_2000, + 0x8001_0300, // buffer_store_dword v3 + 0xbbfd_0000, + 0xbf81_0000, + ]) +} + +/// load; mov v2,A; mov v3,B; and v2,v2,v3; xor v1,v1,v2; store. +/// Hand-computed: 0x12345678 & 0xff00ff00 == 0x12005600. +fn constant_and_fixture() -> Vec { + const A: u32 = 0x1234_5678; + const B: u32 = 0xff00_ff00; + words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + mov_lit(2), + A, + mov_lit(3), + B, + 0x3604_0702, // v_and_b32 v2, v2, v3 (OP=27) + 0x3a02_0501, // v_xor_b32 v1, v1, v2 + 0xe070_2000, + 0x8001_0100, + 0xbbfd_0000, + 0xbf81_0000, + ]) +} + +fn compile_fold_off(code: &[u8]) -> xenora_shader::CompiledShader { + compile_with( + Architecture::Gfx1030, + code, + CompileOptions { + fold_constants: false, + }, + ) + .unwrap() +} + +fn compile_fold_on(code: &[u8]) -> xenora_shader::CompiledShader { + compile_with( + Architecture::Gfx1030, + code, + CompileOptions { + fold_constants: true, + }, + ) + .unwrap() +} + +fn assert_folds_to(code: &[u8], mnemonic: &str, expected: u32) { + let plain = compile_fold_off(code); + let folded = compile_fold_on(code); + let default = compile(Architecture::Gfx1030, code).unwrap(); + assert_eq!( + default.ir, plain.ir, + "default compile must match fold_constants: false" + ); + assert!( + plain.ir.contains(mnemonic), + "fold-off IR must keep {mnemonic}: {}", + plain.ir + ); + assert!( + !folded.ir.contains(mnemonic), + "fold-on IR must drop {mnemonic}: {}", + folded.ir + ); + let const_ir = format!("const.u32 0x{expected:08x}"); + assert!( + folded.ir.contains(&const_ir), + "fold-on IR must contain {const_ir}: {}", + folded.ir + ); + let const_msl = format!("0x{expected:08x}u"); + assert!( + folded.msl.contains(&const_msl), + "fold-on MSL must contain {const_msl}: {}", + folded.msl + ); +} + +#[test] +fn default_compile_matches_fold_constants_off() { + let code = constant_and_fixture(); + let baseline = compile(Architecture::Gfx1030, &code).unwrap(); + let explicit = compile_fold_off(&code); + assert_eq!(baseline.ir, explicit.ir); + assert_eq!(baseline.msl, explicit.msl); + assert!(baseline.ir.contains("and.b32")); +} + +#[test] +fn folds_constant_and_b32_to_known_answer() { + // 0x12345678 & 0xff00ff00 = 0x12005600 (bitwise and of each bit). + assert_folds_to(&constant_and_fixture(), "and.b32", 0x1200_5600); +} + +#[test] +fn folding_is_noop_on_add_fixture() { + let folded = compile_fold_on(FIXTURE); + let plain = compile(Architecture::Gfx1030, FIXTURE).unwrap(); + // add.bin has no pure constant-constant vector op, so folding is a no-op. + assert_eq!(folded.ir, plain.ir); + assert_eq!(folded.msl, plain.msl); + assert_eq!(plain.ir, include_str!("../../../fixtures/golden/add.ir")); +} + +#[test] +fn folds_lshl_by_32_as_shift_by_0() { + // Guide / MSL: count masked with S0[4:0] → 32 & 31 == 0, so 0xf0 << 0 == 0xf0. + // v_lshlrev_b32 OP=26; fixture stores into v4 (rev encoding). + let code = binary_const_fixture(26, 0x0000_00f0, 32, true); + assert_folds_to(&code, "lshl.b32", 0x0000_00f0); +} + +#[test] +fn folds_lshl_by_33_as_shift_by_1() { + // 33 & 31 == 1, so 0xf0 << 1 == 0x1e0. + let code = binary_const_fixture(26, 0x0000_00f0, 33, true); + assert_folds_to(&code, "lshl.b32", 0x0000_01e0); +} + +#[test] +fn folds_lshr_by_32_as_shift_by_0() { + // 32 & 31 == 0, so 0xf0 >> 0 == 0xf0. v_lshrrev_b32 OP=22. + let code = binary_const_fixture(22, 0x0000_00f0, 32, true); + assert_folds_to(&code, "lshr.b32", 0x0000_00f0); +} + +#[test] +fn folds_lshr_by_33_as_shift_by_1() { + // 33 & 31 == 1, so 0xf0 >> 1 == 0x78. + let code = binary_const_fixture(22, 0x0000_00f0, 33, true); + assert_folds_to(&code, "lshr.b32", 0x0000_0078); +} + +#[test] +fn folds_ashr_of_negative_value() { + // (-16 as i32) >> 4 == -1 → 0xffffffff. v_ashrrev_i32 OP=24. + let code = binary_const_fixture(24, 0xffff_fff0, 4, true); + assert_folds_to(&code, "ashr.i32", 0xffff_ffff); +} + +#[test] +fn folds_min_i32_and_min_u32_differ_on_sign_bit() { + // min_i32(0x80000000, 1) = min(-2^31, 1) = 0x80000000. + // min_u32(0x80000000, 1) = min(2^31, 1) = 1. + // They must differ. OP MinI32=17, MinU32=19. + assert_folds_to( + &binary_const_fixture(17, 0x8000_0000, 1, false), + "min.i32", + 0x8000_0000, + ); + assert_folds_to( + &binary_const_fixture(19, 0x8000_0000, 1, false), + "min.u32", + 1, + ); +} + +#[test] +fn folds_mul_hi_i32_i24_with_negative_input() { + // i24(0x00ffffff) = ((0x00ffffff << 8) >> 8) = -1; i24(2) = 2; + // (-1 * 2) as i64 >> 32 = -1 → 0xffffffff. v_mul_hi_i32_i24 OP=10. + let code = binary_const_fixture(10, 0x00ff_ffff, 2, false); + assert_folds_to(&code, "mulhi24.i32", 0xffff_ffff); +} + +#[test] +fn folds_ffbh_i32_on_zero_all_ones_and_one() { + // RDNA2 / MSL: return 0xffffffff when every bit matches the sign bit (0 or -1); + // else clz(x ^ (0 - (x >> 31))). For 1: clz(1) = 31. v_ffbh_i32 OP=59. + assert_folds_to(&unary_const_fixture(59, 0), "ffbh.i32", 0xffff_ffff); + assert_folds_to( + &unary_const_fixture(59, 0xffff_ffff), + "ffbh.i32", + 0xffff_ffff, + ); + assert_folds_to(&unary_const_fixture(59, 1), "ffbh.i32", 31); +} + +#[test] +fn folds_exact_positive_normal_float_add() { + // 1.0 + 2.0 = 3.0 exactly (positive normals). Bits: 0x3f800000 + 0x40000000 + // → 0x40400000. VOP2 add_f32 OP=3. + let code = binary_const_fixture(3, 0x3f80_0000, 0x4000_0000, false); + assert_folds_to(&code, "add.f32", 0x4040_0000); +} + +#[test] +fn float_add_from_load_stays_unfolded_with_fold_on() { + // float-exact.bin feeds add.f32 from a load-derived value (not a pure + // constant), so the op must remain even with fold_constants. Constant + // denormal / NaN / negative / inexact float pairs are rejected at verify + // (see rejects_inexact_float_add_of_constants_at_verify) and never reach + // the folder as stay-unfolded ops. + let plain = compile_fold_off(FLOAT); + let folded = compile_fold_on(FLOAT); + assert!( + plain.ir.contains("add.f32"), + "fold-off must keep add.f32: {}", + plain.ir + ); + assert!( + folded.ir.contains("add.f32"), + "fold-on must not rewrite load-derived add.f32: {}", + folded.ir + ); + assert!( + folded.ir.contains("mul.f32"), + "fold-on must not rewrite load-derived mul.f32: {}", + folded.ir + ); +} + +#[test] +fn rejects_inexact_float_add_of_constants_at_verify() { + // Both operands are positive normals, but 1.0 + 2^-24 is not representable + // in f32 (ulp of 1.0 is 2^-23), so exact_float_result refuses. Lift/verify + // rejects before fold_constant_ops runs; the op cannot "stay unfolded". + // Probed: fold_off and fold_on both return Verify at the add_f32 word. + let code = binary_const_fixture(3, 0x3f80_0000, 0x3380_0000, false); + let off = compile_with( + Architecture::Gfx1030, + &code, + CompileOptions { + fold_constants: false, + }, + ); + let on = compile_with( + Architecture::Gfx1030, + &code, + CompileOptions { + fold_constants: true, + }, + ); + assert!( + matches!(off, Err(CompileError::Verify { .. })), + "fold-off must reject inexact constant add.f32 at verify: {off:?}" + ); + assert!( + matches!(on, Err(CompileError::Verify { .. })), + "fold-on must reject inexact constant add.f32 at verify: {on:?}" + ); + // Folder unchanged: no stay-unfolded path exists for this pair. +}