Compare commits

...
Author SHA1 Message Date
izdat-sl4w 7c88e5d655 cpu: pin the unsigned Jcc conditions at their boundaries
The native DBT had no test for the 0x70..=0x7F or the 0F 80..=8F block
at all. These four conditions are the ones an ARM64 condition code
cannot provide directly: SUBS sets C when a subtraction does not
borrow, so x86 CF is its inverse, and ARM64's HI and LS are defined on
that same inverted carry.

Three tests derive CF and ZF from the operands (Intel SDM Volume 1,
3.4.3.1), then check JB, JAE, JBE and JA in the short and the near
encoding at both ends of the 32-bit and 64-bit ranges, with SUB as well
as CMP, and with the compare and the branch in separate translated
blocks. Inverting the borrow polarity in the lowering makes all three
fail.

Closes #64

Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 20:43:54 +01:00
Zach Doxsee 0730f4dbbf Merge pull request #353 from sahib453/task/69-rex-before-prefix
loader: ignore a REX prefix that is followed by a legacy prefix (#69)
2026-11-24 20:39:22 +01:00
Zach Doxsee 6f27da3ccc Merge pull request #354 from 1Bartosz/perf/92-imm-materialization
loader: load ARM64 constants with the fewest wide moves (#92)
2026-11-24 20:39:00 +01:00
zachdoxsee 6236996f41 Merge upstream main into perf/92-imm-materialization
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:32:35 +01:00
Zach Doxsee 05f2526d27 Merge pull request #345 from katherinebytes/codex/dbt-benchmark-percentiles
Report p95, p99 and IQR in the DBT benchmark
2026-11-24 20:31:23 +01:00
Zach Doxsee 5131de9cd6 Merge pull request #350 from katherinebytes/codex/bc1-tile-row-linearization
Copy tiled BC1 data by tile row
2026-11-24 20:27:49 +01:00
katherinebytes 68503a674c Explain DBT benchmark medians and test invocation
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:23:26 +00:00
katherinebytes 82cb66e80f Document the BC1 tile row bounds
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:23:26 +00:00
katherinebytes 06dbe2946d Merge upstream main for the DBT benchmark
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:22:23 +00:00
zachdoxsee 14d5083f0f Merge upstream main into codex/bc1-tile-row-linearization
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:20:44 +01:00
Bartosz Szczepański 710a2e1e73 loader: load ARM64 constants with the fewest wide moves (#92)
load_imm_64 emitted MOVZ for halfword 0 and then MOVK for zero
halfwords it could skip, and never used MOVN, so a small negative
constant took four instructions. It now starts from MOVZ or MOVN,
whichever leaves more halfwords already correct, at the first halfword
that differs, and adds MOVK only for the remaining differing halfwords.

On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native
bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture
instructions 128,724 instead of 145,732 (-11.7%). Benchmark run times
did not change measurably.

Tests check the sequences against llvm-mc encodings and execute the
edge values plus 512 seeded values, in X0 and X9, on the host through
the JIT, checking both the loaded value and the instruction count.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 19:31:02 +01:00
sahib453 de92766b29 loader: ignore a REX prefix that is followed by a legacy prefix (#69)
A REX prefix takes effect only immediately before the opcode (Intel SDM
Vol. 2A, 2.2.1). The decoder took the byte after the first REX as the
opcode, so `48 66 01 D8` was refused as an illegal instruction where it
should run as `add ax, bx`.

- x86_decode.rs: a REX byte followed by an operand-size, address-size,
  segment, LOCK or repeat prefix is dropped and prefix reading goes on.
  The dropped byte still counts toward the instruction length.
- cpu_known_answers.rs: the SDM-derived case moves from refused to
  verified, with three more for an ignored REX.B, an ignored REX.W
  before a segment prefix, and a later REX that does apply.

Two REX bytes in a row and the address-size prefix stay rejected.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:00:15 +05:30
katherinebytes 6de750b152 Copy tiled BC1 data by tile row
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 18:22:19 +00:00
katherinebytes 4e4a6b36be Report DBT benchmark percentiles and warmup
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 17:55:12 +00:00
7 changed files with 495 additions and 40 deletions

No files matched your search

+3
View File
@@ -10,6 +10,8 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
@@ -190,6 +192,7 @@ remains unsupported.
### Fixed
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
- Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state.
+80 -11
View File
@@ -1,5 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Synthetic interpreter and DBT timings.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
//! and run the executable named by the benchmark's compiler-artifact message.
use std::hint::black_box;
use std::time::{Duration, Instant};
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
@@ -88,14 +95,25 @@ fn check(result: ExecutionResult) {
assert_eq!(result.final_state.get(Register::Rax), ADDS as u64);
}
fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
// Interpolate between adjacent values at rank (n - 1) * fraction.
let rank = (sorted.len() - 1) as f64 * fraction;
let lower = sorted[rank.floor() as usize];
let upper = sorted[rank.ceil() as usize];
lower + (upper - lower).mul_f64(rank.fract())
}
fn report(label: &str, samples: &mut [Duration]) {
samples.sort_unstable();
let median = samples[samples.len() / 2];
let median = percentile(samples, 0.50);
let p95 = percentile(samples, 0.95);
let p99 = percentile(samples, 0.99);
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
let min = samples[0];
let max = samples[samples.len() - 1];
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
println!(
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, median {mips:.2} MIPS",
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
samples.len()
);
}
@@ -104,6 +122,8 @@ fn main() {
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
assert!(sample_count > 0);
let warmup_count = std::env::var("XENORA_DBT_BENCH_WARMUP")
.map_or(10, |value| value.parse::<usize>().expect("warmup count"));
let mut code = vec![0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]; // mov rax, 0
for _ in 0..ADDS {
@@ -124,38 +144,52 @@ fn main() {
let mut warm = Vec::with_capacity(sample_count);
let mut cold_metrics = None;
for _ in 0..sample_count {
for record in
std::iter::repeat_n(false, warmup_count).chain(std::iter::repeat_n(true, sample_count))
{
let mut interp = Interpreter::new(initial_cpu.clone(), &mut loaded.memory, BUDGET);
let start = Instant::now();
let result = black_box(interp.run());
interpreter.push(start.elapsed());
let interpreter_time = start.elapsed();
check(result);
let mut dbt = DbtEngine::new(4 * 1024 * 1024).unwrap();
let mut cpu = initial_cpu.clone();
let start = Instant::now();
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
cold.push(start.elapsed());
let cold_time = start.elapsed();
check(result);
assert!(dbt.metrics.blocks_compiled > 0);
assert_eq!(dbt.metrics.cache_hits, 0);
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
cold_metrics = Some(dbt.metrics);
let metrics = dbt.metrics;
let mut cpu = initial_cpu.clone();
let start = Instant::now();
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
warm.push(start.elapsed());
let warm_time = start.elapsed();
check(result);
assert_eq!(
Some(dbt.metrics.blocks_compiled),
cold_metrics.map(|m| m.blocks_compiled)
);
assert_eq!(dbt.metrics.blocks_compiled, metrics.blocks_compiled);
assert_eq!(dbt.metrics.cache_hits, dbt.metrics.blocks_compiled);
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
if record {
interpreter.push(interpreter_time);
cold.push(cold_time);
warm.push(warm_time);
cold_metrics = Some(metrics);
}
}
println!("{INSTRUCTIONS} guest instructions per sample, final RAX={ADDS}");
println!("{warmup_count} warmup rounds excluded (XENORA_DBT_BENCH_WARMUP, default 10)");
println!(
"Cold DBT includes translation with a fresh engine; warm DBT reuses that engine's cache."
);
println!(
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
);
println!("Even sample counts use the midpoint of the two middle values for the median.");
report("Interpreter", &mut interpreter);
report("Cold DBT", &mut cold);
report("Warm DBT", &mut warm);
@@ -165,3 +199,38 @@ fn main() {
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
);
}
#[cfg(test)]
mod tests {
#[test]
fn single_sample_has_no_spread() {
use super::{Duration, percentile};
let samples = [Duration::from_micros(50)];
for fraction in [0.25, 0.50, 0.75, 0.95, 0.99] {
assert_eq!(percentile(&samples, fraction), samples[0]);
}
}
#[test]
fn percentiles_interpolate_across_even_samples() {
use super::{Duration, percentile};
let samples = [10, 20, 30, 100].map(Duration::from_micros);
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(25));
assert_eq!(percentile(&samples, 0.95), Duration::from_nanos(89_500));
assert_eq!(percentile(&samples, 0.99), Duration::from_nanos(97_900));
assert_eq!(
percentile(&samples, 0.75) - percentile(&samples, 0.25),
Duration::from_nanos(30_000)
);
}
#[test]
fn median_uses_the_middle_of_odd_samples() {
use super::{Duration, percentile};
let samples = [10, 20, 100].map(Duration::from_micros);
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
}
}
+128 -14
View File
@@ -582,22 +582,35 @@ impl Arm64Assembler {
self.emit(0xf2800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
}
/// Load a full 64-bit constant into register Xd.
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
let w0 = (val & 0xffff) as u16;
let w1 = ((val >> 16) & 0xffff) as u16;
let w2 = ((val >> 32) & 0xffff) as u16;
let w3 = ((val >> 48) & 0xffff) as u16;
/// MOVN (64-bit with shift): MOVN Xd, #imm16, LSL #shift writes
/// NOT (imm16 << shift), so every other halfword becomes 0xFFFF.
pub fn movn_64(&mut self, xd: u8, imm16: u16, shift_idx: u8) {
let hw = (shift_idx & 3) as u32;
self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
}
self.movz_64(xd, w0, 0);
if w1 != 0 || (w2 == 0 && w3 == 0) {
self.movk_64(xd, w1, 1);
/// Load a full 64-bit constant into register Xd with the fewest MOVZ or
/// MOVN plus MOVK instructions: one for each halfword that differs from
/// the background the first instruction leaves, and always at least one.
/// MOVZ leaves zero halfwords and MOVN leaves 0xFFFF ones, so MOVN is used
/// when more halfwords are 0xFFFF than zero.
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
let halves: [u16; 4] = std::array::from_fn(|i| (val >> (16 * i)) as u16);
let zeros = halves.iter().filter(|&&h| h == 0).count();
let ones = halves.iter().filter(|&&h| h == 0xffff).count();
let background = if ones > zeros { 0xffff } else { 0 };
// The first halfword that differs from the background, or halfword 0
// when none does (val is 0 or all ones).
let first = halves.iter().position(|&h| h != background).unwrap_or(0);
if background == 0 {
self.movz_64(xd, halves[first], first as u8);
} else {
self.movn_64(xd, !halves[first], first as u8);
}
if w2 != 0 || w3 != 0 {
self.movk_64(xd, w2, 2);
}
if w3 != 0 {
self.movk_64(xd, w3, 3);
for (index, &half) in halves.iter().enumerate().skip(first + 1) {
if half != background {
self.movk_64(xd, half, index as u8);
}
}
}
@@ -786,4 +799,105 @@ mod tests {
asm.str_uoff_32(X0, X19, 136);
assert_eq!(asm.instructions(), &[0xf90013f5, 0xf9404269, 0xb9008a60]);
}
/// Constants at the halfword boundaries the MOVZ/MOVN choice depends on.
const IMMEDIATE_EDGES: [u64; 16] = [
0,
1,
0xffff,
0x1_0000,
0x8000_0000,
0xffff_ffff,
0x1_0000_0000,
0x1234_0000_0000_0000,
0x0000_0001_0000_0005,
0x1234_5678_9abc_def0,
0x7fff_ffff_ffff_ffff,
0x8000_0000_0000_0000,
0xffff_0000_ffff_ffff,
0xffff_ffff_edcc_5678,
0xffff_ffff_ffff_1234,
u64::MAX,
];
#[test]
fn immediate_sequences_match_llvm_encodings() {
// llvm-mc -triple=aarch64-apple-macos -show-encoding.
let cases: &[(u64, &[u32])] = &[
(0, &[0xd2800000]), // movz x0, #0
(u64::MAX, &[0x92800000]), // movn x0, #0
(0xffff_ffff_ffff_1234, &[0x929db960]), // movn x0, #0xedcb
(0x1234_0000_0000_0000, &[0xd2e24680]), // movz x0, #0x1234, lsl #48
(0xffff_0000_ffff_ffff, &[0x92dfffe0]), // movn x0, #0xffff, lsl #32
(0x0000_0001_0000_0005, &[0xd28000a0, 0xf2c00020]), // movz #5; movk #1, lsl #32
// movn x0, #0xa987; movk x0, #0xedcc, lsl #16
(0xffff_ffff_edcc_5678, &[0x929530e0, 0xf2bdb980]),
];
for &(value, expected) in cases {
let mut asm = Arm64Assembler::new();
asm.load_imm_64(X0, value);
assert_eq!(asm.instructions(), expected, "{value:#x}");
}
// movz x9, #0xdef0; movk x9, #0x9abc, lsl #16; #0x5678, lsl #32;
// #0x1234, lsl #48
let mut asm = Arm64Assembler::new();
asm.load_imm_64(X9, 0x1234_5678_9abc_def0);
assert_eq!(
asm.instructions(),
&[0xd29bde09, 0xf2b35789, 0xf2cacf09, 0xf2e24689]
);
}
/// Fewest MOVZ/MOVN/MOVK instructions for `value`: every halfword that is
/// neither zero (after MOVZ) nor 0xFFFF (after MOVN), and at least one.
fn shortest_wide_move(value: u64) -> usize {
let halves = (0..4).map(|i| (value >> (16 * i)) & 0xffff);
let not_zero = halves.clone().filter(|&h| h != 0).count();
let not_ones = halves.filter(|&h| h != 0xffff).count();
not_zero.min(not_ones).max(1)
}
#[test]
fn immediates_run_on_the_host_and_use_the_fewest_wide_moves() {
let mut values = IMMEDIATE_EDGES.to_vec();
let mut state = 0x9e37_79b9_7f4a_7c15u64;
for _ in 0..512 {
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
let raw = state.wrapping_mul(0x2545_f491_4f6c_dd1d);
// Force some halfwords to zero or all ones so both MOVZ and MOVN
// sequences of every length occur.
let mut value = raw;
for half in 0..4 {
match (raw >> (60 - 2 * half)) & 3 {
0 => value &= !(0xffff << (16 * half)),
1 => value |= 0xffff << (16 * half),
_ => {}
}
}
values.push(value);
}
let mut jit = crate::jit::JitMemory::new(64 * 1024).unwrap();
for value in values {
for register in [X0, X9] {
let mut asm = Arm64Assembler::new();
asm.load_imm_64(register, value);
assert_eq!(
asm.instructions().len(),
shortest_wide_move(value),
"{value:#x}"
);
if register != X0 {
asm.mov_reg_64(X0, register);
}
asm.ret();
let entry = jit.emit_block(asm.instructions()).unwrap();
// SAFETY: the block is a complete AAPCS64 leaf function that
// writes only X0 (and X9, a caller-saved register) and returns.
let function: extern "C" fn() -> u64 = unsafe { std::mem::transmute(entry) };
assert_eq!(function(), value, "{value:#x} in x{register}");
}
}
}
}
+203
View File
@@ -2267,4 +2267,207 @@ mod tests {
ExitReason::MemoryFault(MemoryError::UnmappedAddress(FS_BASE + 8))
);
}
/// Intel SDM Volume 1, section 3.4.3.1: for `SUB` and `CMP`, `CF` is the
/// borrow out of the most significant bit. `JB` is `CF = 1`, `JAE` is
/// `CF = 0`, `JBE` is `CF = 1 or ZF = 1` and `JA` is `CF = 0 and ZF = 0`.
///
/// ARM64 reports the inverse: `SUBS` sets `C` when the subtraction does
/// *not* borrow, and its `HI`/`LS` conditions are defined on that same
/// inverted carry. These four x86 conditions therefore cannot be taken
/// from an ARM64 condition code without translating the borrow first,
/// which makes them the ones to pin at the boundaries.
/// One unsigned condition: the low nibble pair as encoded in the `0x70`
/// block, and the rule that decides it from CF and ZF.
type UnsignedCondition = (u8, fn(bool, bool) -> bool);
const UNSIGNED_CONDITIONS: [UnsignedCondition; 4] = [
(0x72, |cf, _zf| cf), // JB, JC, JNAE
(0x73, |cf, _zf| !cf), // JAE, JNB, JNC
(0x76, |cf, zf| cf || zf), // JBE, JNA
(0x77, |cf, zf| !cf && !zf), // JA, JNBE
];
/// Build `<op> eax, ebx` (or `rax, rbx`) followed by the short or near form
/// of `condition`. The not-taken path writes 1 to `ECX` and halts, the
/// taken path writes 2. A near branch targets offset 140, which a `disp8`
/// cannot reach, so the two encodings are exercised separately.
fn unsigned_branch_program(op: [u8; 2], condition: u8, wide: bool, near: bool) -> Vec<u8> {
let mut code = Vec::new();
if wide {
code.push(0x48); // REX.W
}
code.extend_from_slice(&op); // cmp/sub eax, ebx
let jcc = code.len();
if near {
// The near form is `0F 8x`, where x is the low nibble of the
// short form's opcode.
code.extend_from_slice(&[0x0F, 0x80 | (condition & 0x0F), 0, 0, 0, 0]);
} else {
code.extend_from_slice(&[condition, 0]);
}
code.extend_from_slice(&[0xB9, 1, 0, 0, 0]); // mov ecx, 1
code.push(0xF4); // hlt
let target = if near { 140 } else { code.len() };
while code.len() < target {
code.push(0x90); // nop
}
code.extend_from_slice(&[0xB9, 2, 0, 0, 0]); // mov ecx, 2
code.push(0xF4); // hlt
let next = jcc + if near { 6 } else { 2 };
let displacement = target as i64 - next as i64;
if near {
code[jcc + 2..jcc + 6].copy_from_slice(&(displacement as i32).to_le_bytes());
} else {
code[jcc + 1] = displacement as i8 as u8;
}
code
}
/// Run one branch program and return `(ecx, cf, zf)`.
fn run_unsigned_branch(code: &[u8], left: u64, right: u64) -> (u64, bool, bool) {
let (mut engine, mut cpu, mut memory) = fixture(code);
cpu.set(Register::Rax, left);
cpu.set(Register::Rbx, right);
let result = engine.run(&mut cpu, &mut memory, 32);
assert_eq!(result.exit_reason, ExitReason::Halt);
// Either the two-instruction taken path or the two-instruction
// not-taken path runs after the compare and the branch.
assert_eq!(result.instructions_executed, 4);
// The compare, the branch and the halting move all run as translated
// ARM64, not through the shared interpreter.
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
(cpu.get(Register::Rcx), cpu.flags.cf, cpu.flags.zf)
}
/// The four unsigned conditions, at both ends of the 32-bit and 64-bit
/// ranges, in the short and the near encoding. Expected flags and
/// outcomes come from the SDM rules above, not from the lowering.
#[test]
fn unsigned_branch_conditions_follow_the_borrow_at_every_boundary() {
const CMP: [u8; 2] = [0x39, 0xD8];
let cases: &[(bool, u64, u64)] = &[
// 32-bit: zero, one, equal operands, both ends of the range, and
// the pair where the sign bit flips but the unsigned order holds.
(false, 0, 0),
(false, 0, 1),
(false, 1, 0),
(false, 0xFFFF_FFFF, 0xFFFF_FFFF),
(false, 0xFFFF_FFFF, 0),
(false, 0, 0xFFFF_FFFF),
(false, 0x7FFF_FFFF, 0x8000_0000),
(false, 0x8000_0000, 0x7FFF_FFFF),
// The same boundaries at 64 bits, plus a subtraction that clears
// the sign bit without borrowing.
(true, 0, 0),
(true, 0, 1),
(true, 1, 0),
(true, u64::MAX, u64::MAX),
(true, u64::MAX, 0),
(true, 0, u64::MAX),
(true, 0x7FFF_FFFF_FFFF_FFFF, 0x8000_0000_0000_0000),
(true, 0x8000_0000_0000_0000, 0x7FFF_FFFF_FFFF_FFFF),
(true, 0x8000_0000_0000_0000, 1),
];
for &(wide, left, right) in cases {
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
let (left, right) = (left & mask, right & mask);
// SDM: CF is the borrow out of the most significant bit, ZF is a
// zero result. Both follow from the operands alone.
let (cf, zf) = (left < right, left == right);
for &(condition, holds) in &UNSIGNED_CONDITIONS {
let taken = holds(cf, zf);
for &near in &[false, true] {
let code = unsigned_branch_program(CMP, condition, wide, near);
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
let case = format!(
"{condition:#04x} {:#x} {:#x} {}",
left,
right,
if near { "near" } else { "short" }
);
assert_eq!(got_cf, cf, "{case}: CF");
assert_eq!(got_zf, zf, "{case}: ZF");
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
}
}
}
}
/// `SUB` is the other producer of the carry these conditions read, and the
/// one where the ARM64 carry is inverted: `0 - 1` borrows, while
/// `0x8000_0000_0000_0000 - 1` does not borrow even though it clears the
/// sign bit.
#[test]
fn subtract_borrow_into_and_out_of_the_high_bit_feeds_the_unsigned_branches() {
const SUB: [u8; 2] = [0x29, 0xD8];
let cases: &[(bool, u64, u64)] = &[
(false, 0, 1),
(false, 0x8000_0000, 1),
(true, 0, 1),
(true, 0x8000_0000_0000_0000, 1),
];
for &(wide, left, right) in cases {
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
let (left, right) = (left & mask, right & mask);
let (cf, zf) = (left < right, left == right);
for &(condition, holds) in &UNSIGNED_CONDITIONS {
let taken = holds(cf, zf);
for &near in &[false, true] {
let code = unsigned_branch_program(SUB, condition, wide, near);
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
let case = format!(
"{condition:#04x} {:#x} {:#x} {}",
left,
right,
if near { "near" } else { "short" }
);
assert_eq!(got_cf, cf, "{case}: CF");
assert_eq!(got_zf, zf, "{case}: ZF");
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
}
}
}
}
/// The carry these conditions read is produced in one translated block and
/// consumed in the next. A lowering that left it in the host's condition
/// flags would pass the single-block cases above and fail here.
#[test]
fn unsigned_branch_reads_flags_stored_by_a_previous_block() {
const CMP: [u8; 2] = [0x39, 0xD8];
let cases: &[(bool, u64, u64)] = &[
(false, 0, 0), // CF = 0, ZF = 1
(false, 0, 1), // CF = 1, ZF = 0
(false, 0xFFFF_FFFF, 0), // CF = 0, ZF = 0
(true, 0x8000_0000_0000_0000, 1), // CF = 0 although the sign bit clears
];
for &(wide, left, right) in cases {
let (cf, zf) = (left < right, left == right);
for &(condition, holds) in &UNSIGNED_CONDITIONS {
let taken = holds(cf, zf);
let code = unsigned_branch_program(CMP, condition, wide, false);
let (mut engine, mut cpu, mut memory) = fixture(&code);
cpu.set(Register::Rax, left);
cpu.set(Register::Rbx, right);
// One instruction per run: the compare is translated as a
// one-instruction block, so the branch is compiled separately
// and can only read the flags the first block stored.
let first = engine.run(&mut cpu, &mut memory, 1);
assert_eq!(first.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(cpu.rip, ENTRY + if wide { 3 } else { 2 });
assert_eq!((cpu.flags.cf, cpu.flags.zf), (cf, zf));
let second = engine.run(&mut cpu, &mut memory, 8);
assert_eq!(second.exit_reason, ExitReason::Halt);
assert_eq!(second.instructions_executed, 3);
assert_eq!(cpu.get(Register::Rcx), if taken { 2 } else { 1 });
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
}
}
}
}
+22 -4
View File
@@ -237,6 +237,15 @@ impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
}
}
/// Whether `byte` is a legacy prefix: an operand-size, address-size, segment,
/// LOCK or repeat prefix (Intel SDM Vol. 2A, 2.1.1).
fn is_legacy_prefix(byte: u8) -> bool {
matches!(
byte,
0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 | 0x66 | 0x67 | 0xF0 | 0xF2 | 0xF3
)
}
/// Decode one instruction at `rip`. `fetch` supplies the byte at an address and
/// is called only for bytes that belong to the instruction, in order.
///
@@ -258,9 +267,22 @@ pub fn decode<E>(
let mut repne = false;
let mut lock = false;
let mut segment = None;
let mut rex = 0;
let mut byte = cursor.u8()?;
loop {
let selected = match byte {
// REX applies only immediately before the opcode. One that is
// followed by a legacy prefix is ignored (Intel SDM Vol. 2A, 2.2.1).
0x40..=0x4F => {
let next = cursor.u8()?;
if !is_legacy_prefix(next) {
rex = byte;
byte = next;
break;
}
byte = next;
continue;
}
0x64 => Segment::Fs,
0x65 => Segment::Gs,
0x66 => {
@@ -299,10 +321,6 @@ pub fn decode<E>(
byte = cursor.u8()?;
}
let rex = if byte & 0xF0 == 0x40 { byte } else { 0 };
if rex != 0 {
byte = cursor.u8()?;
}
let (rex_w, rex_r, rex_x, rex_b) =
(rex & 8 != 0, (rex & 4) << 1, (rex & 2) << 2, (rex & 1) << 3);
+12 -1
View File
@@ -1307,6 +1307,18 @@ addr32_sum_wraps_at_32_bits: rbx=ffff0000 rcx=10000+D rax=0 m0=44332211 => rax=1
486601d8
SDM 2A 2.2.1
rex_not_adjacent_to_opcode_is_ignored: rax=112233445566ffff rbx=1 => rax=1122334455660000 f=CPAZso
@ .byte 0x41,0x66,0x01,0xd8
416601d8
SDM 2A 2.2.1
ignored_rex_b_does_not_select_r8: rax=112233445566ffff rbx=1 r8=5 => rax=1122334455660000 f=CPAZso
@ .byte 0x48,0x64,0x8b,0x03
48648b03
SDM 2A 2.2.1; 1 3.4.1.1
ignored_rex_w_before_segment_prefix_loads_32_bits: rax=ffffffffffffffff rbx=8 fs8=1122334455667788 => rax=44332211 f=*
@ .byte 0x41,0x66,0x41,0x01,0xd8
41664101d8
SDM 2A 2.2.1
rex_after_ignored_rex_applies: rax=7 rbx=1 r8=112233445566ffff => r8=1122334455660000 f=CPAZso
@ .byte 0x66,0x48,0x01,0xd8
664801d8
SDM 2A 2.2.1.2
@@ -2746,7 +2758,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("repne_scasb_finds_byte", 1),
("repne_scasb_finds_byte_df_clear", 0),
("repne_scasd_exhausts_count", 1),
("rex_not_adjacent_to_opcode_is_ignored", 0),
("roundps_uses_mxcsr_rc", 0),
("roundsd_suppress_precision", 0),
("roundss_imm_modes", 0),
+47 -10
View File
@@ -27,6 +27,8 @@ pub use upload::{
const BLOCK_BYTES: usize = 8;
const TILE_BLOCKS: usize = 2;
const TILE_ROW_BYTES: usize = TILE_BLOCKS * BLOCK_BYTES;
const TILE_BYTES: usize = TILE_BLOCKS * TILE_ROW_BYTES;
#[derive(Debug, PartialEq, Eq)]
pub enum TextureError {
@@ -91,19 +93,30 @@ impl<'a> TiledBc1<'a> {
/// Copies one subresource as tightly packed row-major BC1 block rows.
/// Padded tile slots are excluded, including at partial texel blocks.
pub fn linearize(&self, layer: usize, mip: u32) -> Result<Vec<u8>, TextureError> {
if layer >= self.layers {
if layer >= self.layers || mip >= self.mips {
return Err(TextureError::OutOfBounds);
}
self.mip_extent(mip)?;
let (width, height) = mip_blocks(self.width, self.height, mip);
let base = self.mip_base(layer, mip)?;
let tile_row_stride = width.div_ceil(TILE_BLOCKS) * TILE_BYTES;
let full_tiles = width / TILE_BLOCKS;
let edge_bytes = (width % TILE_BLOCKS) * BLOCK_BYTES;
let mut blocks = Vec::new();
// Construction checked the larger, padded byte count.
blocks
.try_reserve_exact(width * height * BLOCK_BYTES)
.map_err(|_| TextureError::AllocationFailed)?;
// Construction requires the exact padded length, so each selected tile row is in bounds.
for y in 0..height {
for x in 0..width {
blocks.extend_from_slice(&self.block(layer, mip, x, y)?);
let row_start =
base + (y / TILE_BLOCKS) * tile_row_stride + (y % TILE_BLOCKS) * TILE_ROW_BYTES;
for tile in 0..full_tiles {
let start = row_start + tile * TILE_BYTES;
blocks.extend_from_slice(&self.bytes[start..start + TILE_ROW_BYTES]);
}
if edge_bytes != 0 {
let start = row_start + full_tiles * TILE_BYTES;
blocks.extend_from_slice(&self.bytes[start..start + edge_bytes]);
}
}
Ok(blocks)
@@ -124,19 +137,24 @@ impl<'a> TiledBc1<'a> {
if x >= width || y >= height {
return Err(TextureError::OutOfBounds);
}
let mut base = layer * self.layer_bytes;
for prior in 0..mip {
base += mip_bytes(self.width, self.height, prior)?;
}
let base = self.mip_base(layer, mip)?;
// Construction checked the full padded size for every level and layer.
let tile = (y / TILE_BLOCKS) * width.div_ceil(TILE_BLOCKS) + x / TILE_BLOCKS;
let within_tile = (y % TILE_BLOCKS) * TILE_BLOCKS + x % TILE_BLOCKS;
let offset = base + (tile * TILE_BLOCKS.pow(2) + within_tile) * BLOCK_BYTES;
let offset = base + tile * TILE_BYTES + within_tile * BLOCK_BYTES;
self.bytes
.get(offset..offset + BLOCK_BYTES)
.and_then(|bytes| bytes.try_into().ok())
.ok_or(TextureError::InvalidByteLength)
}
fn mip_base(&self, layer: usize, mip: u32) -> Result<usize, TextureError> {
let mut base = layer * self.layer_bytes;
for prior in 0..mip {
base += mip_bytes(self.width, self.height, prior)?;
}
Ok(base)
}
}
fn mip_blocks(width: usize, height: usize, mip: u32) -> (usize, usize) {
@@ -151,7 +169,7 @@ fn mip_bytes(width: usize, height: usize, mip: u32) -> Result<usize, TextureErro
width
.div_ceil(TILE_BLOCKS)
.checked_mul(height.div_ceil(TILE_BLOCKS))
.and_then(|tiles| tiles.checked_mul(TILE_BLOCKS.pow(2) * BLOCK_BYTES))
.and_then(|tiles| tiles.checked_mul(TILE_BYTES))
.ok_or(TextureError::SizeOverflow)
}
@@ -216,6 +234,7 @@ mod tests {
assert_eq!(tex.linearize(1, 0).unwrap(), logical_blocks.as_flattened());
assert_eq!(tex.linearize(1, 1).unwrap(), [20; 8]);
assert_eq!(tex.linearize(2, 0), Err(TextureError::OutOfBounds));
assert_eq!(tex.linearize(0, 2), Err(TextureError::OutOfBounds));
}
#[test]
@@ -242,6 +261,24 @@ mod tests {
assert_eq!(texture.block(0, 0, 2, 2), Ok([12; 8]));
}
#[test]
fn linearizes_odd_tile_edges_in_each_layer() {
// A 21×21 texture uses 9, 4 and 1 tiles across the three mips.
// Mip 1 is 10×10 texels, so only nine of its sixteen slots are logical.
let block = |slot: u8| [slot, 1, 2, 3, 4, 5, 6, !slot];
let bytes: Vec<_> = (0..112).flat_map(block).collect();
let texture = TiledBc1::new(&bytes, 21, 21, 3, 2).unwrap();
for (layer, first_slot) in [(0, 36), (1, 92)] {
let expected: Vec<_> = [0, 1, 4, 2, 3, 6, 8, 9, 12]
.into_iter()
.flat_map(|slot| block(first_slot + slot))
.collect();
assert_eq!(texture.linearize(layer, 1).unwrap(), expected);
let last_mip: Vec<_> = (16..20).flat_map(|slot| block(first_slot + slot)).collect();
assert_eq!(texture.linearize(layer, 2).unwrap(), last_mip);
}
}
#[test]
fn decodes_opaque_and_transparent_bc1_palettes() {
let opaque = decode_bc1([0, 0xf8, 31, 0, 0xe4, 0xe4, 0xe4, 0xe4]);