mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 03:39:52 +00:00
Merge task/382-crt-startup into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
This commit is contained in:
commit
417b19c859
4 files changed
+1120
-5
No files matched your search
@@ -23,6 +23,7 @@ remains unsupported.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
|
||||
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
|
||||
- Avoided resolver allocations for permitted guest data reads and writes contained in one mapping, preserving checked fallback for split spans and faults (#105).
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
@@ -31,6 +32,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=<path>` 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.
|
||||
|
||||
+613
-1
@@ -5,7 +5,7 @@
|
||||
//! Provides isolated, page-aligned guest virtual memory with permission checking
|
||||
//! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks.
|
||||
|
||||
use std::fmt;
|
||||
use std::{fmt, ops::Range};
|
||||
|
||||
pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536;
|
||||
|
||||
@@ -520,14 +520,39 @@ impl GuestMemory {
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
if let Some((index, range)) = self.contiguous_region(address, src.len())
|
||||
&& self.regions[index].permissions.write
|
||||
{
|
||||
self.regions[index].data[range].copy_from_slice(src);
|
||||
return Ok(());
|
||||
}
|
||||
self.write_checked(address, src, Some("write"))
|
||||
}
|
||||
|
||||
/// Read raw bytes from guest memory at the specified address, checking permissions.
|
||||
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
|
||||
if let Some((index, range)) = self.contiguous_region(address, dst.len())
|
||||
&& self.regions[index].permissions.read
|
||||
{
|
||||
dst.copy_from_slice(&self.regions[index].data[range]);
|
||||
return Ok(());
|
||||
}
|
||||
self.read_checked(address, dst, Some("read"))
|
||||
}
|
||||
|
||||
// Only the first eligible mapping may supply the whole span. Otherwise
|
||||
// the checked resolver must preserve split-access and overlap priority.
|
||||
fn contiguous_region(&self, address: u64, len: usize) -> Option<(usize, Range<usize>)> {
|
||||
let (index, region) = self
|
||||
.regions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, region)| region.base + region.data.len() as u64 > address)?;
|
||||
let offset = usize::try_from(address.checked_sub(region.base)?).ok()?;
|
||||
let end = offset.checked_add(len)?;
|
||||
(end <= region.data.len()).then_some((index, offset..end))
|
||||
}
|
||||
|
||||
/// Read an instruction byte from guest memory, verifying execute permission.
|
||||
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
address.checked_add(1).ok_or(MemoryError::Overflow)?;
|
||||
@@ -869,3 +894,590 @@ mod instruction_fetch_tests {
|
||||
assert_eq!(m.fetch_instruction_byte(BASE + 3), Ok(0x44));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod data_access_contract_tests {
|
||||
use super::{MemoryPermissions as P, *};
|
||||
const A: u64 = 0x10_0000;
|
||||
|
||||
#[test]
|
||||
fn data_permissions_are_independent_and_failed_reads_leave_output_untouched() {
|
||||
for bits in 0..8 {
|
||||
let p = P {
|
||||
read: bits & 1 != 0,
|
||||
write: bits & 2 != 0,
|
||||
execute: bits & 4 != 0,
|
||||
};
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 4, p, &[1, 2, 3, 4]).unwrap();
|
||||
let mut out = [0xee; 2];
|
||||
let read = m.read_bytes(A + 1, &mut out);
|
||||
assert_eq!(
|
||||
read,
|
||||
if p.read {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 1,
|
||||
required: "read",
|
||||
})
|
||||
}
|
||||
);
|
||||
assert_eq!(out, if p.read { [2, 3] } else { [0xee; 2] });
|
||||
let write = m.write_bytes(A + 1, &[0x55, 0x66]);
|
||||
assert_eq!(
|
||||
write,
|
||||
if p.write {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 1,
|
||||
required: "write",
|
||||
})
|
||||
}
|
||||
);
|
||||
let mut stored = [0; 4];
|
||||
m.read_checked(A, &mut stored, None).unwrap();
|
||||
assert_eq!(
|
||||
stored,
|
||||
if p.write {
|
||||
[1, 0x55, 0x66, 4]
|
||||
} else {
|
||||
[1, 2, 3, 4]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_data_spans_keep_inclusive_ends_and_ignore_permissions() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0, P::NO_ACCESS).unwrap();
|
||||
m.map_region(A + 16, 3, P::NO_ACCESS).unwrap();
|
||||
m.map_region(u64::MAX, 0, P::NO_ACCESS).unwrap();
|
||||
for at in [A, A + 16, A + 17, A + 19, u64::MAX] {
|
||||
assert_eq!(m.read_bytes(at, &mut []), Ok(()));
|
||||
assert_eq!(m.write_bytes(at, &[]), Ok(()));
|
||||
}
|
||||
for at in [A - 1, A + 1, A + 15, A + 20] {
|
||||
assert_eq!(
|
||||
m.read_bytes(at, &mut []),
|
||||
Err(MemoryError::UnmappedAddress(at))
|
||||
);
|
||||
assert_eq!(
|
||||
m.write_bytes(at, &[]),
|
||||
Err(MemoryError::UnmappedAddress(at))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_address_overflow_precedes_permissions_and_preserves_output() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX - 3, 3, P::NO_ACCESS).unwrap();
|
||||
let mut out = [0xee; 2];
|
||||
assert_eq!(
|
||||
m.read_bytes(u64::MAX - 1, &mut out),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(out, [0xee; 2]);
|
||||
assert_eq!(
|
||||
m.write_bytes(u64::MAX - 1, &[1, 2]),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(
|
||||
m.read_bytes(u64::MAX, &mut out[..1]),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(m.write_bytes(u64::MAX, &[1]), Err(MemoryError::Overflow));
|
||||
assert_eq!(m.read_u16(u64::MAX - 1), Err(MemoryError::Overflow));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_data_accesses_keep_exact_fallback_errors_and_atomicity() {
|
||||
for (gap, right) in [
|
||||
(0, P::READ_WRITE),
|
||||
(0, P::READ_ONLY),
|
||||
(0, P::NO_ACCESS),
|
||||
(
|
||||
0,
|
||||
P {
|
||||
read: false,
|
||||
write: true,
|
||||
execute: false,
|
||||
},
|
||||
),
|
||||
(1, P::READ_WRITE),
|
||||
] {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 8, P::READ_WRITE, &[0, 1, 2, 3, 4, 5, 6, 7])
|
||||
.unwrap();
|
||||
let b = A + 8 + gap;
|
||||
m.map_region_with_data(b, 8, right, &[8, 9, 10, 11, 12, 13, 14, 15])
|
||||
.unwrap();
|
||||
let mut expected = m.clone();
|
||||
let mut actual_out = [0xee; 4];
|
||||
let mut expected_out = [0xee; 4];
|
||||
assert_eq!(
|
||||
m.read_bytes(A + 6, &mut actual_out),
|
||||
expected.read_checked(A + 6, &mut expected_out, Some("read"))
|
||||
);
|
||||
assert_eq!(actual_out, expected_out);
|
||||
assert_eq!(
|
||||
actual_out,
|
||||
if gap == 0 && right.read {
|
||||
[6, 7, 8, 9]
|
||||
} else {
|
||||
[0xee; 4]
|
||||
}
|
||||
);
|
||||
let bytes = [0xa0, 0xa1, 0xa2, 0xa3];
|
||||
assert_eq!(
|
||||
m.write_bytes(A + 6, &bytes),
|
||||
expected.write_checked(A + 6, &bytes, Some("write"))
|
||||
);
|
||||
let written = gap == 0 && right.write;
|
||||
assert_eq!(
|
||||
m.read_u64_bypass(A).unwrap().to_le_bytes(),
|
||||
if written {
|
||||
[0, 1, 2, 3, 4, 5, 0xa0, 0xa1]
|
||||
} else {
|
||||
[0, 1, 2, 3, 4, 5, 6, 7]
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
m.read_u64_bypass(b).unwrap().to_le_bytes(),
|
||||
if written {
|
||||
[0xa2, 0xa3, 10, 11, 12, 13, 14, 15]
|
||||
} else {
|
||||
[8, 9, 10, 11, 12, 13, 14, 15]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_accesses_keep_first_mapping_priority_for_partial_overlaps() {
|
||||
const BASE: u64 = 0x0000_0003_0000_0000;
|
||||
for first in [P::READ_WRITE, P::READ_ONLY] {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(0x1000, 1, P::NO_ACCESS).unwrap();
|
||||
m.map_region_with_data(BASE, 4, first, &[1, 2, 3, 4])
|
||||
.unwrap();
|
||||
let empty = m.map_heap_allocation(PROCESS_HEAP, 0).unwrap();
|
||||
assert_eq!(empty, BASE);
|
||||
assert_eq!(
|
||||
m.resize_heap_allocation(PROCESS_HEAP, empty, 8, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
let mut out = [0xee; 8];
|
||||
assert_eq!(m.read_bytes(BASE, &mut out), Ok(()));
|
||||
assert_eq!(out, [1, 2, 3, 4, 0, 0, 0, 0]);
|
||||
assert_eq!(m.read_u16(BASE), Ok(0x0201));
|
||||
let bytes = [0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7];
|
||||
let mut expected = m.clone();
|
||||
assert_eq!(
|
||||
m.write_bytes(BASE, &bytes),
|
||||
expected.write_checked(BASE, &bytes, Some("write"))
|
||||
);
|
||||
m.read_bytes(BASE, &mut out).unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
if first.write {
|
||||
bytes
|
||||
} else {
|
||||
[1, 2, 3, 4, 0, 0, 0, 0]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_accesses_observe_writes_clones_release_and_remap() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 8, P::READ_WRITE, &[1; 8])
|
||||
.unwrap();
|
||||
let mut clone = m.clone();
|
||||
m.write_u64(A, 0x1122_3344_5566_7788).unwrap();
|
||||
clone.write_u32(A, 0xaabb_ccdd).unwrap();
|
||||
assert_eq!(m.read_u64(A), Ok(0x1122_3344_5566_7788));
|
||||
assert_eq!(clone.read_u64(A), Ok(0x0101_0101_aabb_ccdd));
|
||||
let b = m.map_virtual_allocation(0x4000, 2, P::READ_WRITE).unwrap();
|
||||
m.write_u16(b, 0x1234).unwrap();
|
||||
assert_eq!(m.read_u16(b), Ok(0x1234));
|
||||
assert!(m.release_virtual_allocation(b));
|
||||
assert_eq!(m.read_u16(b), Err(MemoryError::UnmappedAddress(b)));
|
||||
m.map_region_with_data(b, 2, P::READ_ONLY, &[0x56, 0x78])
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u16(b), Ok(0x7856));
|
||||
assert_eq!(
|
||||
m.write_u8(b, 0),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: b,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
assert_eq!(clone.read_u16(b), Err(MemoryError::UnmappedAddress(b)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod data_memory_bench {
|
||||
use super::{MemoryPermissions as P, *};
|
||||
use crate::{CpuState, DbtEngine, ExitReason, Register};
|
||||
use std::{hint::black_box, time::Instant};
|
||||
|
||||
const CODE: u64 = 0x1000;
|
||||
const VALUE: u64 = 0xffff_ff00;
|
||||
#[derive(Clone, Copy)]
|
||||
enum Kind {
|
||||
Registers,
|
||||
Counter,
|
||||
Sequential,
|
||||
Split,
|
||||
}
|
||||
|
||||
fn setting(name: &str, default: usize, maximum: usize) -> usize {
|
||||
let value = std::env::var(name).map_or(default, |s| s.parse().expect(name));
|
||||
assert!((1..=maximum).contains(&value), "invalid {name}");
|
||||
value
|
||||
}
|
||||
fn quantile(sorted: &[f64], fraction: f64) -> f64 {
|
||||
let rank = (sorted.len() - 1) as f64 * fraction;
|
||||
let lo = rank.floor() as usize;
|
||||
sorted[lo] + (sorted[rank.ceil() as usize] - sorted[lo]) * rank.fract()
|
||||
}
|
||||
fn guest(kind: Kind, iterations: usize, data: u64) -> (Vec<u8>, usize) {
|
||||
// MOV RCX, iterations; MOV RDX, VALUE (control) or RSI, data; XOR EAX,EAX.
|
||||
let registers = matches!(kind, Kind::Registers);
|
||||
let sequential = matches!(kind, Kind::Sequential);
|
||||
let mut code = vec![0x48, 0xb9];
|
||||
code.extend_from_slice(&(iterations as u64).to_le_bytes());
|
||||
code.extend_from_slice(&[0x48, if registers { 0xba } else { 0xbe }]);
|
||||
let target = if registers { VALUE } else { data };
|
||||
code.extend_from_slice(&target.to_le_bytes());
|
||||
code.extend_from_slice(&[0x31, 0xc0]);
|
||||
let per_iteration = if registers {
|
||||
// ADD RAX,RDX; ADD RDX,1; DEC RCX; JNZ -12.
|
||||
code.extend_from_slice(&[
|
||||
0x48, 0x01, 0xd0, 0x48, 0x83, 0xc2, 0x01, 0x48, 0xff, 0xc9, 0x75, 0xf4,
|
||||
]);
|
||||
4
|
||||
} else {
|
||||
// MOV RDX,[RSI]; ADD RAX,RDX; ADD RDX,1; MOV [RSI],RDX.
|
||||
code.extend_from_slice(&[
|
||||
0x48, 0x8b, 0x16, 0x48, 0x01, 0xd0, 0x48, 0x83, 0xc2, 0x01, 0x48, 0x89, 0x16,
|
||||
]);
|
||||
if sequential {
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xc6, 0x08]); // ADD RSI,8.
|
||||
}
|
||||
// DEC RCX; JNZ -22 (sequential) or -18 (counter).
|
||||
let back = if sequential { 0xea } else { 0xee };
|
||||
code.extend_from_slice(&[0x48, 0xff, 0xc9, 0x75, back]);
|
||||
6 + usize::from(sequential)
|
||||
};
|
||||
code.push(0xf4); // HLT; three setup instructions and one halt.
|
||||
(code, iterations * per_iteration + 4)
|
||||
}
|
||||
|
||||
// Run identical source on the baseline and candidate with the same release profile.
|
||||
// Allocation counting is deliberately separate: instrumentation distorts these timings.
|
||||
#[test]
|
||||
#[ignore = "manual, correctness-gated warm DBT data-memory timing"]
|
||||
fn warm_data_memory_benchmark() {
|
||||
let samples = setting("XENORA_DATA_BENCH_SAMPLES", 31, 1001);
|
||||
let counter = setting("XENORA_DATA_BENCH_ITERS", 32768, 65536);
|
||||
let sequential = setting("XENORA_DATA_BENCH_STREAM_ITERS", 16384, 65536);
|
||||
for (label, kind, regions, last) in [
|
||||
("register-control", Kind::Registers, 4, false),
|
||||
("counter-front", Kind::Counter, 4, false),
|
||||
("counter-front-many", Kind::Counter, 64, false),
|
||||
("counter-first", Kind::Counter, 4, false),
|
||||
("counter-first-many", Kind::Counter, 64, false),
|
||||
("counter-third-many", Kind::Counter, 64, false),
|
||||
("counter-middle", Kind::Counter, 64, false),
|
||||
("counter-last", Kind::Counter, 64, true),
|
||||
("sequential-front", Kind::Sequential, 4, false),
|
||||
("sequential-front-many", Kind::Sequential, 64, false),
|
||||
("sequential-first", Kind::Sequential, 4, false),
|
||||
("sequential-first-many", Kind::Sequential, 64, false),
|
||||
("sequential-last", Kind::Sequential, 64, true),
|
||||
("split-counter-control", Kind::Split, 4, false),
|
||||
] {
|
||||
let iterations = if matches!(kind, Kind::Sequential) {
|
||||
sequential
|
||||
} else {
|
||||
counter
|
||||
};
|
||||
let code_address = if label.contains("-first") {
|
||||
0x8000_0000
|
||||
} else {
|
||||
CODE
|
||||
};
|
||||
let data = if last {
|
||||
0x4000_0000
|
||||
} else if label.contains("-third") {
|
||||
0x20_1000
|
||||
} else if label.contains("-middle") {
|
||||
0x23_f000
|
||||
} else {
|
||||
0x1_0000
|
||||
};
|
||||
let (code, expected_instructions) = guest(kind, iterations, data);
|
||||
let words = if matches!(kind, Kind::Sequential) {
|
||||
iterations
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let initial: Vec<u8> = (0..words)
|
||||
.flat_map(|i| (VALUE + i as u64).to_le_bytes())
|
||||
.collect();
|
||||
let increment = match kind {
|
||||
Kind::Registers => 0,
|
||||
Kind::Sequential => 1,
|
||||
_ => iterations as u64,
|
||||
};
|
||||
let expected: Vec<u8> = (0..words)
|
||||
.flat_map(|i| (VALUE + i as u64 + increment).to_le_bytes())
|
||||
.collect();
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(code_address, 4096, P::READ_EXECUTE, &code)
|
||||
.unwrap();
|
||||
let pieces = if matches!(kind, Kind::Split) {
|
||||
memory
|
||||
.map_region_with_data(data, 4, P::READ_WRITE, &initial[..4])
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(data + 4, 4, P::READ_WRITE, &initial[4..])
|
||||
.unwrap();
|
||||
2
|
||||
} else {
|
||||
memory
|
||||
.map_region_with_data(data, initial.len(), P::READ_WRITE, &initial)
|
||||
.unwrap();
|
||||
1
|
||||
};
|
||||
for i in 0..regions - pieces - 1 {
|
||||
memory
|
||||
.map_region(0x20_0000 + i as u64 * 8192, 4096, P::READ_ONLY)
|
||||
.unwrap();
|
||||
}
|
||||
let initial_cpu = CpuState::new(code_address, 0x8000_0000); // No stack instructions.
|
||||
let mut dbt = DbtEngine::new(1024 * 1024).unwrap();
|
||||
let mut readback = vec![0; initial.len()];
|
||||
let n = iterations as u64;
|
||||
let sum = n * VALUE + n * (n - 1) / 2;
|
||||
let mut timings = Vec::with_capacity(samples);
|
||||
let warmups = 5;
|
||||
for sample in 0..samples + warmups {
|
||||
memory.write_bytes(data, &initial).unwrap();
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let before = dbt.metrics;
|
||||
let started = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut memory, expected_instructions + 16));
|
||||
let elapsed = started.elapsed();
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt, "{label}");
|
||||
assert_eq!(
|
||||
result.instructions_executed, expected_instructions,
|
||||
"{label}"
|
||||
);
|
||||
let state = (
|
||||
cpu.get(Register::Rax),
|
||||
cpu.get(Register::Rdx),
|
||||
cpu.get(Register::Rcx),
|
||||
);
|
||||
assert_eq!(state, (sum, VALUE + n, 0), "{label}");
|
||||
memory.read_bytes(data, &mut readback).unwrap();
|
||||
assert_eq!(readback, expected, "{label}");
|
||||
assert_eq!(dbt.metrics.interpreter_fallbacks, 0, "{label}");
|
||||
if sample > 0 {
|
||||
let compiled = |m: crate::DbtMetrics| {
|
||||
(m.blocks_compiled, m.native_bytes_emitted, m.cache_misses)
|
||||
};
|
||||
assert_eq!(compiled(dbt.metrics), compiled(before), "{label}");
|
||||
if sample >= warmups {
|
||||
timings.push(elapsed.as_nanos() as f64 / n as f64);
|
||||
}
|
||||
} else {
|
||||
assert!(dbt.metrics.blocks_compiled > 0, "{label}");
|
||||
}
|
||||
}
|
||||
timings.sort_by(f64::total_cmp);
|
||||
println!(
|
||||
"warm-data label={label} regions={regions} iterations={iterations} samples={samples} warmups={warmups} instructions={expected_instructions} median_ns_per_iteration={:.3} p10={:.3} p90={:.3}",
|
||||
quantile(&timings, 0.5),
|
||||
quantile(&timings, 0.1),
|
||||
quantile(&timings, 0.9)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod mapping_group_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn aliases_preserve_bytes_across_resize_relocation_and_release() {
|
||||
const BASE: u64 = 0x0000_0003_0000_0000;
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(BASE - 16, 8, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(BASE, 4, MemoryPermissions::READ_ONLY, &[1, 2, 3, 4])
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(BASE + 16, 8, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
let heap = memory.create_private_heap(0).unwrap();
|
||||
assert_eq!(memory.map_heap_allocation(PROCESS_HEAP, 0), Ok(BASE));
|
||||
assert_eq!(memory.map_heap_allocation(heap, 0), Ok(BASE));
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 8, true),
|
||||
Err(MemoryError::AllocationFailed)
|
||||
);
|
||||
assert_eq!(memory.resize_heap_allocation(heap, BASE, 8, true), Ok(BASE));
|
||||
memory.write_bytes(BASE + 4, &[5, 6, 7, 8]).unwrap();
|
||||
assert_eq!(memory.read_u64(BASE), Ok(0x0807_0605_0403_0201));
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(heap, BASE, 32, true),
|
||||
Err(MemoryError::AllocationFailed)
|
||||
);
|
||||
let moved = memory
|
||||
.resize_heap_allocation(heap, BASE, 32, false)
|
||||
.unwrap();
|
||||
assert_ne!(moved, BASE);
|
||||
let mut bytes = [0xff; 32];
|
||||
memory.read_bytes(moved, &mut bytes).unwrap();
|
||||
let mut expected = [0; 32];
|
||||
expected[4..8].copy_from_slice(&[5, 6, 7, 8]);
|
||||
assert_eq!(bytes, expected);
|
||||
let mut failed = [0xff; 8];
|
||||
assert_eq!(
|
||||
memory.read_bytes(BASE, &mut failed),
|
||||
Err(MemoryError::UnmappedAddress(BASE + 4))
|
||||
);
|
||||
assert_eq!(failed, [0xff; 8]);
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 8, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
assert_eq!(memory.read_u64(BASE), Ok(0x0403_0201));
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 2, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
assert_eq!(memory.read_u16(BASE + 2), Ok(0x0403));
|
||||
assert!(memory.release_heap_allocation(PROCESS_HEAP, BASE));
|
||||
assert_eq!(memory.read_u32(BASE), Ok(0x0403_0201));
|
||||
assert_eq!(memory.read_u64(BASE - 16), Ok(0));
|
||||
assert_eq!(memory.read_u64(BASE + 16), Ok(0));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod bounds_access_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn permitted_empty_spans_and_high_addresses_keep_exact_bounds() {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
u64::MAX - 8,
|
||||
8,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&[1, 2, 3, 4, 5, 6, 7, 8],
|
||||
)
|
||||
.unwrap();
|
||||
for at in [u64::MAX - 8, u64::MAX - 4, u64::MAX - 1, u64::MAX] {
|
||||
assert_eq!(memory.read_bytes(at, &mut []), Ok(()));
|
||||
assert_eq!(memory.write_bytes(at, &[]), Ok(()));
|
||||
}
|
||||
assert_eq!(memory.read_u64(u64::MAX - 8), Ok(0x0807_0605_0403_0201));
|
||||
assert_eq!(memory.read_u8(u64::MAX - 1), Ok(8));
|
||||
let mut failed = [0xee; 2];
|
||||
assert_eq!(
|
||||
memory.read_bytes(u64::MAX - 1, &mut failed),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(failed, [0xee; 2]);
|
||||
assert_eq!(
|
||||
memory.write_u16(u64::MAX - 1, 0xffff),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(memory.read_u64(u64::MAX - 7), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
memory.write_u64(u64::MAX - 7, u64::MAX),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
memory.write_u8(u64::MAX - 1, 0x99).unwrap();
|
||||
let mut actual = [0; 8];
|
||||
memory.read_bytes(u64::MAX - 8, &mut actual).unwrap();
|
||||
assert_eq!(actual, [1, 2, 3, 4, 5, 6, 7, 0x99]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod mapping_search_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_mapping_and_gap_keeps_its_bytes_across_table_sizes() {
|
||||
const BASE: u64 = 0x40_0000;
|
||||
for count in [0usize, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 32, 33] {
|
||||
let mut memory = GuestMemory::new();
|
||||
for index in (0..count).rev() {
|
||||
memory
|
||||
.map_region_with_data(
|
||||
BASE + index as u64 * 0x100,
|
||||
8,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&[(index + 1) as u8; 8],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
memory.read_u8(BASE - 1),
|
||||
Err(MemoryError::UnmappedAddress(BASE - 1))
|
||||
);
|
||||
if count == 0 {
|
||||
assert_eq!(
|
||||
memory.read_u8(BASE),
|
||||
Err(MemoryError::UnmappedAddress(BASE))
|
||||
);
|
||||
assert_eq!(
|
||||
memory.write_u8(BASE, 1),
|
||||
Err(MemoryError::UnmappedAddress(BASE))
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_bytes(BASE, &mut []),
|
||||
Err(MemoryError::UnmappedAddress(BASE))
|
||||
);
|
||||
}
|
||||
for index in 0..count {
|
||||
let address = BASE + index as u64 * 0x100;
|
||||
let mut actual = [0; 8];
|
||||
memory.read_bytes(address, &mut actual).unwrap();
|
||||
assert_eq!(actual, [(index + 1) as u8; 8]);
|
||||
let replacement = [0x80 + index as u8; 8];
|
||||
memory.write_bytes(address, &replacement).unwrap();
|
||||
memory.read_bytes(address, &mut actual).unwrap();
|
||||
assert_eq!(actual, replacement);
|
||||
assert_eq!(memory.read_bytes(address + 8, &mut []), Ok(()));
|
||||
assert_eq!(
|
||||
memory.read_u8(address + 8),
|
||||
Err(MemoryError::UnmappedAddress(address + 8))
|
||||
);
|
||||
let mut failed = [0xee; 2];
|
||||
assert_eq!(
|
||||
memory.read_bytes(address + 7, &mut failed),
|
||||
Err(MemoryError::UnmappedAddress(address + 8))
|
||||
);
|
||||
assert_eq!(failed, [0xee; 2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+193
-3
@@ -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<CompiledShader, CompileError> {
|
||||
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<CompiledShader, CompileError> {
|
||||
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<Vec<(usize, O
|
||||
})
|
||||
}
|
||||
|
||||
/// Replace pure constant expressions with `Op::Constant` in place.
|
||||
///
|
||||
/// Operands stay addressable by their original `Value` indices so later uses
|
||||
/// need no rewrite. Side-effecting and mask-dependent ops are left unchanged.
|
||||
fn fold_constant_ops(operations: &mut [(usize, Op)]) {
|
||||
for index in 0..operations.len() {
|
||||
let folded = match operations[index].1 {
|
||||
Op::Unary(operator, source) => {
|
||||
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<u32> {
|
||||
match operations.get(value.0).map(|(_, operation)| *operation)? {
|
||||
Op::Constant(bits) => Some(bits),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn concrete_bits(facts: KnownBits) -> Option<u32> {
|
||||
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<u32> {
|
||||
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<u32> {
|
||||
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() {
|
||||
|
||||
@@ -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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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.
|
||||
}
|
||||
Reference in new issue
Block a user