Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/xcl/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const TRANSLATOR_SOURCES: &[&str] = &[
"src/gpu/rdna2.rs",
"src/gpu/rdna2_spec.rs",
"src/gpu/rdna2_xbox.rs",
"src/gpu/recomp/cfg.rs",
"src/gpu/recomp/code_loads.rs",
"src/gpu/recomp/dxc.rs",
"src/gpu/recomp/emit.rs",
"src/gpu/recomp/mesh_wave.rs",
Expand Down
123 changes: 122 additions & 1 deletion crates/xcl/src/gpu/dxil/core_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,127 @@ fn multi_window_mem_format_and_bvh_validate() {
}
}

/// Constant data after the program (`kernel::translate_entry_rodata`), as the HLSL kernel's
/// `gpu_loads_read_the_constant_data_after_the_program`: `s_getpc_b64` plus the compiler's
/// offset is its address, and `s_load` / `global_load` (with windows `s_buffer_load` too) read
/// it from the module's table – with one window, two windows (switch) and heap windows, where
/// window 0 holds other bytes at the table's offset. Any other address still reads the memory.
#[test]
fn gpu_direct_loads_read_the_constant_data_after_the_program() {
direct_loads_read_the_constant_data(false);
}

/// As `gpu_direct_loads_read_the_constant_data_after_the_program`, with the memory a load
/// through the same register pair reads at the table's low offset: with one window only the
/// high dword of a code address tells them apart (thehollowedone on #2229).
#[test]
fn gpu_direct_loads_read_the_constant_data_after_the_program_not_the_memory_at_its_offset() {
direct_loads_read_the_constant_data(true);
}

/// `at_the_table`: the memory s[2:3] points to has the table's low offset (one window only).
fn direct_loads_read_the_constant_data(at_the_table: bool) {
use super::kernel::{translate_entry_rodata, Entry};
use crate::gpu::recomp::{runner, HEAP_WINDOWS};
let body = |table: u32| {
prog(&[
("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)], None), // s[0:1] = 4
("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 255)], Some(table.wrapping_sub(4))),
("S_ADDC_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)], None),
("GLOBAL_LOAD_DWORDX3", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 10), ("SADDR", 0), ("OFFSET", 0)], None),
("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 0), ("OFFSET", 4), ("SOFFSET", 125)], None),
("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)], None),
// memory, not the data: v[12:13] and s[2:3]
("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 8), ("ADDR", 12), ("SADDR", 0x7D), ("OFFSET", 0)], None),
("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 28), ("SBASE", 1), ("OFFSET", 0), ("SOFFSET", 125)], None),
// the V# s[4:7] on the table
("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 0)], None),
("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 1)], None),
("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 30), ("SBASE", 2), ("OFFSET", 4), ("SOFFSET", 125)], None),
// s[8:9]: the code address on one path, memory on the other – told at run time
("S_MOV_B64", "ENC_SOP1", &[("SDST", 8), ("SSRC0", 0)], None),
("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 128)], None),
("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None),
("S_MOV_B64", "ENC_SOP1", &[("SDST", 8), ("SSRC0", 2)], None),
("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 21), ("SBASE", 4), ("OFFSET", 12), ("SOFFSET", 125)], None),
("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 129)], None),
("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None),
("S_MOV_B64", "ENC_SOP1", &[("SDST", 8), ("SSRC0", 2)], None),
("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 22), ("SBASE", 4), ("OFFSET", 4), ("SOFFSET", 125)], None),
])
};
// as in retail data: program, guard s_endpgm, block (u32 N, N dwords, s_endpgm)
let block = body(0).len() as u32 + 4;
let code = body(block + 4);
let table: Vec<u32> = (0..8).map(|i| 0x7AB1_E000 + i).collect();
let mut data = vec![table.len() as u32];
data.extend(&table);
data.push(0xBF81_0000);
let rodata = vec![(block, data)];
let split = runner::split_wave64();
let direct = |windows: u32, rodata: &[(u32, Vec<u32>)]| {
let o = KernelOptions { wave64: true, split, mem_windows: windows, sampler_base: 0 };
translate_entry_rodata(&code, o, Entry::Kernel, true, rodata).unwrap_or_else(|e| panic!("windows {windows:#x}: {}", &e[..e.len().min(800)]))
};
// (translations are validated in test builds)
let one = direct(1, &rodata).dxil;
assert_eq!(direct(1, &[]).dxil, translate(&code, KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }).unwrap(), "no data, no table");
assert_ne!(one, direct(1, &[]).dxil);
match (runner::adapter(), runner::wave64_programs_supported()) {
(Ok(_), Ok(true)) => {}
(a, w) => return runner::skip_test(if a.is_err() || w.is_err() { "no GPU" } else { "no wave64" }),
}
let check = |r: &runner::KernelResult, buffer: [u32; 2], what: &str| {
assert_eq!(r.sgpr[20], table[1], "{what}: s_load_dword of the table");
assert_eq!(r.sgpr[24..28], table[2..6], "{what}: s_load_dwordx4 of the table");
assert_eq!(r.sgpr[28..30], [4242, 4343], "{what}: s_load from memory");
assert_eq!(r.sgpr[21..23], [table[3], 4343], "{what}: s_load of the table, then of memory, through one register pair");
assert_eq!(r.sgpr[30..32], buffer, "{what}: s_buffer_load");
for l in 0..64usize {
let k = l % 6;
assert_eq!(r.vgpr[l][5..8], table[k..k + 3], "{what}, lane {l}: three dwords of the table from {k}");
assert_eq!(r.vgpr[l][8], 7000 + l as u32, "{what}, lane {l}: memory outside the data");
}
};
// one window: nothing of the code is in the memory
let mut st = runner::KernelState::default();
st.sgpr[2] = if at_the_table { block + 4 } else { 0x900 };
st.sgpr[6] = 64;
for (l, r) in st.vgpr.iter_mut().enumerate() {
r[10] = 4 * (l as u32 % 6);
r[12] = 0x800 + 4 * l as u32;
}
let mut mem = vec![0u32; 1024];
let m = (st.sgpr[2] / 4) as usize;
mem[m..m + 3].copy_from_slice(&[4242, 4343, 4444]);
for l in 0..64 {
mem[0x200 + l] = 7000 + l as u32;
}
check(&runner::run(&one, &st, &mem).unwrap(), [table[1], table[2]], "one window");
if at_the_table {
return;
}
// several windows: a code address is in none of them, and window 0 holds other bytes at
// the table's offset
let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap();
let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64);
let word = |a: u64| unsafe { &mut *(a as *mut u32) };
for k in 0..16u64 {
*word(w0 + block as u64 + 4 * k) = 0xBAD0_0000 + k as u32;
}
*word(w1 + 0x900) = 4242;
*word(w1 + 0x904) = 4343;
st.sgpr[2..4].copy_from_slice(&[(w1 + 0x900) as u32, (w1 >> 32) as u32]);
for (l, r) in st.vgpr.iter_mut().enumerate() {
*word(w1 + 0x800 + 4 * l as u64) = 7000 + l as u32;
r[12] = (w1 + 0x800 + 4 * l as u64) as u32;
r[13] = (w1 >> 32) as u32;
}
for (windows, what) in [(2, "two windows"), (2 | HEAP_WINDOWS, "heap windows")] {
check(&runner::run_in_arena(&direct(windows, &rodata).dxil, &st, &arena).unwrap(), [table[1], table[2]], what);
}
}

/// `image_get_lod` with a static sampler (an S# built from constants in the code) translates
/// to `CalculateLevelOfDetail` on the sampler bound at `s<i>, space1`, shared with a sample of
/// the same S#, and validates.
Expand All @@ -434,7 +555,7 @@ fn ps_get_lod_with_a_static_sampler() {
let k = super::kernel::translate_pixel(&code, ko, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)]));
assert_eq!(k.static_samplers, vec![(linear, false)], "one static sampler, shared by get_lod and sample");
if crate::gpu::recomp::dxc::location().is_ok() {
super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)]));
super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true, &[]).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)]));
}
}

Expand Down
17 changes: 9 additions & 8 deletions crates/xcl/src/gpu/dxil/coverage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,14 +246,15 @@ pub fn percentiles(v: &[u64]) -> (u64, u64, u64) {

/// One program through the direct translator for `mode`. Panics (outside the translator's
/// own thread) come back as `"panic: …"`; `validate` runs DXC's validator on the result
/// (the translator itself only validates in debug / test builds).
pub fn translate_mode(code: &[u8], mode: &Mode, o: KernelOptions, validate: bool) -> Result<Vec<u8>, String> {
/// (the translator itself only validates in debug / test builds). `rodata`: the constant data
/// after the program (`xbox::Fssm::rodata`).
pub fn translate_mode(code: &[u8], mode: &Mode, o: KernelOptions, validate: bool, rodata: &[(u32, Vec<u32>)]) -> Result<Vec<u8>, String> {
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match mode {
Mode::Kernel => kernel::translate_full(code, o),
Mode::Compute(cs) => kernel::translate_compute(code, o, cs),
Mode::Vertex(vs) => kernel::translate_vertex(code, KernelOptions { split: false, ..o }, vs),
Mode::Pixel(ps) => kernel::translate_pixel(code, KernelOptions { split: false, ..o }, ps),
Mode::Mesh(ms) => kernel::translate_mesh(code, o, ms),
Mode::Kernel => kernel::translate_entry_rodata(code, o, kernel::Entry::Kernel, true, rodata),
Mode::Compute(cs) => kernel::translate_entry_rodata(code, o, kernel::Entry::Compute(cs.clone()), true, rodata),
Mode::Vertex(vs) => kernel::translate_entry_rodata(code, KernelOptions { split: false, ..o }, kernel::Entry::Vertex(vs.clone()), true, rodata),
Mode::Pixel(ps) => kernel::translate_entry_rodata(code, KernelOptions { split: false, ..o }, kernel::Entry::Pixel(ps.clone()), true, rodata),
Mode::Mesh(ms) => kernel::translate_entry_rodata(code, o, kernel::Entry::Mesh(ms.clone()), true, rodata),
Mode::Geometry(g) => kernel::translate_geometry(code, o, g),
}));
let k = match r {
Expand Down Expand Up @@ -405,7 +406,7 @@ mod tests {
let mut r = Report::default();
for (name, code, mode) in [("ok", ok.clone(), Mode::Kernel), ("gs", ok, Mode::Geometry(Default::default()))] {
let t0 = std::time::Instant::now();
let res = translate_mode(&code, &mode, o, false).map(|d| d.len());
let res = translate_mode(&code, &mode, o, false, &[]).map(|d| d.len());
r.add(name, &Sample { stage: stage_name(&mode), result: res, time: t0.elapsed(), hlsl_size: None });
}
assert_eq!(r.stages["kernel"].translated, 1, "{}", r.text(5));
Expand Down
40 changes: 37 additions & 3 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//! `recomp::CsInterface`): user SGPRs from `io`, then the enabled group ids
//! and TG_SIZE; v0..v2 = thread id in the group; results only through memory.
use std::collections::{BTreeSet, HashMap};
use std::collections::{BTreeMap, BTreeSet, HashMap};

use super::cfg::{Cfg, Term};
use super::container::Stage;
Expand Down Expand Up @@ -38,7 +38,7 @@ pub struct KernelOptions {
/// identity (`recomp::pso`): bump it when `pso::direct_compute` / `direct_graphics` change the
/// containers. An edit of `gpu/dxil` needs no bump, `XCL_DIRECT_DXIL_SOURCE_ID` is its hash
/// (the `gpu/dxil` sources are not in build.rs's translator source hash).
pub const TRANSLATOR_VERSION: u32 = 9;
pub const TRANSLATOR_VERSION: u32 = 10;

/// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this
/// translator, with the HLSL path as the fallback for what it cannot translate yet.
Expand Down Expand Up @@ -155,14 +155,40 @@ fn translate_entry(
compact: Option<bool>,
nest: Option<super::compact::Nest>,
tables: usize,
) -> Result<Kernel, String> {
translate_entry_with(code, o, entry, compact, nest, tables, Vec::new())
}

/// A program at `entry` with the constant data the console compiler put after it in the code
/// region (`xbox::Fssm::rodata`, the recompiler's `Options::rodata`): `s_getpc_b64` plus the
/// compiler's offset is its address, and dword loads at such an address read the table the
/// module carries (`Lw::rodata_loads`). `wave32_only`: as `translate_compute_on` (compute only).
pub fn translate_entry_rodata(code: &[u8], o: KernelOptions, entry: Entry, wave32_only: bool, rodata: &[(u32, Vec<u32>)]) -> Result<Kernel, String> {
let compact = if matches!(entry, Entry::Kernel | Entry::Compute(_)) { compact_mode() } else { None };
let tables = match entry {
Entry::Compute(_) if !wave32_only => super::compact::TABLE_WORDS,
Entry::Kernel | Entry::Compute(_) => super::compact::TABLE_WORDS_WAVE32,
_ => 0,
};
translate_entry_with(code, o, entry, compact, None, tables, rodata.to_vec())
}

fn translate_entry_with(
code: &[u8],
o: KernelOptions,
entry: Entry,
compact: Option<bool>,
nest: Option<super::compact::Nest>,
tables: usize,
rodata: Vec<(u32, Vec<u32>)>,
) -> Result<Kernel, String> {
// SSA construction recurses along the CFG (one level per guarded memory access between
// a register's definition and its use): a thread with a large stack for big programs
let code = code.to_vec();
std::thread::Builder::new()
.name("xcl-dxil-translate".into())
.stack_size(256 << 20)
.spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables))
.spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables, rodata))
.map_err(|e| format!("translator thread: {e}"))?
.join()
.map_err(|e| {
Expand Down Expand Up @@ -193,6 +219,7 @@ fn translate_on_this_thread(
compact: Option<bool>,
nest: Option<super::compact::Nest>,
tables: usize,
rodata: Vec<(u32, Vec<u32>)>,
) -> Result<Kernel, String> {
let geo = match &entry {
Entry::Geometry(g) => Some(g.clone()),
Expand All @@ -209,6 +236,10 @@ fn translate_on_this_thread(
let split = o.wave64 && o.split && !gfx;
let leaders: BTreeSet<u64> = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect();
let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry);
if !rodata.is_empty() {
lw.code_loads = crate::gpu::recomp::code_loads::code_loads(&cfg.insts);
}
lw.rodata = rodata;
let uses_lds = lw.lds.is_some();
let res = lw.res;
let io = lw.init.io.expect("the I/O buffer");
Expand Down Expand Up @@ -519,6 +550,9 @@ impl Lw {
heap_mem,
res,
fmt_table: None,
rodata: Vec::new(),
rodata_table: None,
code_loads: BTreeMap::new(),
fmt_desc_cache: HashMap::new(),
fmt_comp1_cache: HashMap::new(),
reload: None,
Expand Down
16 changes: 14 additions & 2 deletions crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
//! Variables: SGPR code `c` (0..=127; slot 125 = SCC, as in the kernel ABI),
//! VGPR `v` = 128 + v, the loop budget = [`VAR_BUDGET`].
use std::collections::{BTreeSet, HashMap};
use std::collections::{BTreeMap, BTreeSet, HashMap};

use super::module::{BinOp, Block, CastOp, Pred, Value};
use super::ops::{BitCount, Binary, FClass, FUnary, Tertiary};
Expand Down Expand Up @@ -190,6 +190,13 @@ pub struct Lw {
pub res: Option<RawUav>,
/// the buffer format table (`FMT_INFO`), created on first use
pub fmt_table: Option<Value>,
/// constant data after the program in the code region (`recomp::Options::rodata`:
/// (address from the program's start, dwords)) and its table, created on first use
/// (`rodata_loads`)
pub rodata: Vec<(u32, Vec<u32>)>,
pub rodata_table: Option<Value>,
/// the loads that may read the constant data, by pc (`recomp::code_loads`)
pub code_loads: BTreeMap<u64, crate::gpu::recomp::code_loads::CodeLoad>,
/// cached decoded format descriptors hoisted to `d3`'s defining block
pub fmt_desc_cache: HashMap<(Value, Option<u32>), super::lower_mem::FmtDesc>,
/// cached single-component format decode parameters hoisted to `d3`'s defining block
Expand Down Expand Up @@ -1305,8 +1312,13 @@ impl Lw {
return err(d, "indirect branch");
}
if name == "s_getpc_b64" {
// the code region is addressed from 0 – with a load that may or may not read the
// constant data after the program, above every memory address (`rodata_loads`), as
// the HLSL kernel
let pc = d.pc + d.len as u64;
let (lo, hi) = (self.c(pc as u32), self.c(0));
let maybe = self.code_loads.values().any(|k| *k == crate::gpu::recomp::code_loads::CodeLoad::Maybe);
let code_hi = if !maybe { 0 } else { crate::gpu::recomp::CODE_ADDRESS_HI };
let (lo, hi) = (self.c(pc as u32), self.c(code_hi));
self.write64(&dst, lo, hi);
return Ok(());
}
Expand Down
19 changes: 18 additions & 1 deletion crates/xcl/src/gpu/dxil/lower_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1167,6 +1167,13 @@ impl Lw {
let base = self.add(d0, off);
let base_aligned = self.andc(base, !3);
let raw = self.mem_ld_chunks(base_aligned, count);
// (a V# on the constant data in the code)
let raw = if self.code_loads.contains_key(&d.pc) {
let hi = self.andc(d1, 0xFFFF);
self.rodata_loads(d.pc, hi, base_aligned, raw)
} else {
raw
};
let z = self.c(0);
(0..count)
.map(|i| {
Expand All @@ -1193,7 +1200,9 @@ impl Lw {
let a = self.add(b, k);
let a = self.add(a, soff);
let base_aligned = self.andc(a, !3);
self.mem_ld_chunks(base_aligned, count)
let raw = self.mem_ld_chunks(base_aligned, count);
// (constant data in the code)
self.rodata_loads(d.pc, hi, base_aligned, raw)
};
let coherent = ["GLC", "DLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1));
if self.split && coherent {
Expand Down Expand Up @@ -2025,6 +2034,14 @@ impl Lw {
} else {
let vd = Self::fv(d, "VDST");
let loaded = self.mem_ld_n(Some(act), a, count as u32);
// (constant data in the code)
let loaded = if !self.code_loads.contains_key(&d.pc) {
loaded
} else {
let hi = self.flat_hi(d, op.ends_with("_addtid"));
let a = self.andc(a, !3);
self.rodata_loads(d.pc, hi, a, loaded)
};
for i in 0..count {
self.write32(&Dst::V(vd + i), loaded[i as usize]);
}
Expand Down
Loading
Loading