From 98a629a32933862efe2bb756c1ef4182dd433805 Mon Sep 17 00:00:00 2001 From: MacieGx Date: Thu, 26 Nov 2026 01:11:05 +0100 Subject: [PATCH] Recompiler: loads through s_getpc_b64 read the constant data after the program Console programs keep constant tables after s_endpgm and read them PC-relative (s_getpc_b64 + s_load_dword* / global_load_dword*). The translation gave s_getpc_b64 the program offset with high dword 0, so in a title these loads read memory window 0 at a low offset: zeros. 676 of the 26503 shader records of a retail title use this, among them all postfx_aces LUT bakes, whose 64-cube output LUT came out as one constant texel, so the presented image was flat. The data blocks after the program (xbox::Fssm::rodata, the new Options::rodata) now go with the translation: - HLSL: emit.rs embeds them as `static const uint xcl_rodata[]`, and s_load and FLAT / GLOBAL dword loads whose address may be a code address take the dwords at that address inside a block from the table (xcl_cload* / xcl_gload*). - Direct DXIL: the same, as an internal constant array of the module (Lw::rodata_loads in lower_window.rs); s_buffer_load through a V# built from s_getpc_b64 reads it too. kernel::translate_entry_rodata carries the data. The per-lane form (XCL_PER_LANE) has no table and leaves such programs to the per-instruction form. TRANSLATOR_VERSION 9 -> 10. - pso.rs passes the data on the compute, VS / PS and mesh paths (HLSL and direct), and `xcl shaders` (precompile, direct sweep) does too. Loads are sorted at translation by whether their address comes from s_getpc_b64, by a forward dataflow over the CFG (gpu/recomp/code_loads.rs: s_getpc_b64 and offsets added to it give a code address, merges join, loads give data). A load whose address never comes from it stays a plain memory load with no table test; one whose address comes from it on every path reads only the table (xcl_cload*, 0 outside the blocks, no memory access); a mixed one reads the memory and selects the table's dwords, with no branch, when the raw high dword is CODE_ADDRESS_HI (0xC0DE, above any user-space address). s_getpc_b64 gives that high dword in a program with a mixed load, and 0 otherwise. Why: the first form tested the window index in a branch around every such load, and the NVIDIA Linux driver (vkd3d-proton) crashed compiling it (pr1sm-dev on #2229). The tag is given with one memory window too: memory loads there take the low dword only, and without it the title's memory at the table's low offset was read as the table (thehollowedone on #2229). The dataflow follows every source of an instruction: a constant source of a select (inline or literal) is data, so a select between a code address and a constant is decided at run time, not read from the table only; an SDWA source with S0 / S1 set is the SGPR it names, which rdna2::sgpr_uses leaves out and rdna2::vgpr_uses takes for a VGPR. code_loads.rs and the recompiler's cfg.rs it runs on are in build.rs's TRANSLATOR_SOURCES, so a change to them gives the translated cache another identity for both paths. Not covered: byte / short global loads, MUBUF buffer_load, the legacy GS path and the per-lane form still read memory at such addresses. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/build.rs | 2 + crates/xcl/src/gpu/dxil/core_tests.rs | 123 +++++++++++- crates/xcl/src/gpu/dxil/coverage.rs | 17 +- crates/xcl/src/gpu/dxil/kernel.rs | 40 +++- crates/xcl/src/gpu/dxil/lower.rs | 16 +- crates/xcl/src/gpu/dxil/lower_mem.rs | 19 +- crates/xcl/src/gpu/dxil/lower_window.rs | 91 +++++++++ crates/xcl/src/gpu/recomp/code_loads.rs | 253 ++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/emit.rs | 88 ++++++++- crates/xcl/src/gpu/recomp/mod.rs | 19 +- crates/xcl/src/gpu/recomp/pso.rs | 61 ++++-- crates/xcl/src/gpu/recomp/tests.rs | 116 +++++++++++ crates/xcl/src/gpu/xbox.rs | 13 ++ crates/xcl/src/shaders.rs | 8 +- 14 files changed, 826 insertions(+), 40 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/code_loads.rs diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 22b136da8e..afbccc02fc 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -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", diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 7492f54b9c..a85a18ce9d 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -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 = (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)]| { + 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, space1`, shared with a sample of /// the same S#, and validates. @@ -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)])); } } diff --git a/crates/xcl/src/gpu/dxil/coverage.rs b/crates/xcl/src/gpu/dxil/coverage.rs index 4ac26cb707..b0fbac1700 100644 --- a/crates/xcl/src/gpu/dxil/coverage.rs +++ b/crates/xcl/src/gpu/dxil/coverage.rs @@ -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, 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)]) -> Result, 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 { @@ -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)); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..30dbad0178 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -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; @@ -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. @@ -155,6 +155,32 @@ fn translate_entry( compact: Option, nest: Option, tables: usize, +) -> Result { + 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)]) -> Result { + 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, + nest: Option, + tables: usize, + rodata: Vec<(u32, Vec)>, ) -> Result { // 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 @@ -162,7 +188,7 @@ fn translate_entry( 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| { @@ -193,6 +219,7 @@ fn translate_on_this_thread( compact: Option, nest: Option, tables: usize, + rodata: Vec<(u32, Vec)>, ) -> Result { let geo = match &entry { Entry::Geometry(g) => Some(g.clone()), @@ -209,6 +236,10 @@ fn translate_on_this_thread( let split = o.wave64 && o.split && !gfx; let leaders: BTreeSet = 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"); @@ -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, diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5034d31903..efd9e1f540 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -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}; @@ -190,6 +190,13 @@ pub struct Lw { pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, + /// 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)>, + pub rodata_table: Option, + /// the loads that may read the constant data, by pc (`recomp::code_loads`) + pub code_loads: BTreeMap, /// cached decoded format descriptors hoisted to `d3`'s defining block pub fmt_desc_cache: HashMap<(Value, Option), super::lower_mem::FmtDesc>, /// cached single-component format decode parameters hoisted to `d3`'s defining block @@ -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(()); } diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index cc7cd0116a..005e931150 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -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| { @@ -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 { @@ -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]); } diff --git a/crates/xcl/src/gpu/dxil/lower_window.rs b/crates/xcl/src/gpu/dxil/lower_window.rs index 1f41e5817d..193203b2e6 100644 --- a/crates/xcl/src/gpu/dxil/lower_window.rs +++ b/crates/xcl/src/gpu/dxil/lower_window.rs @@ -151,6 +151,83 @@ impl Lw { self.wr(VAR_WIN, w); } + /// `Lw::rodata` (the HLSL kernel's `xcl_cload` / `xcl_gload`): the dwords `vals` the load + /// at `pc` read from memory at `a`, `a + 4`.. (`a` dword-aligned), with those at a code + /// address inside one of the program's constant data blocks replaced by the block's dword + /// (`Lw::code_loads`). A load whose address comes from `s_getpc_b64` on every path takes + /// the block's dwords (0 outside the blocks); one whose address may come from it tells a + /// code address by the high dword `CODE_ADDRESS_HI`: with several windows by the window of + /// the access, just selected (`VAR_WIN`), with one by `hi`, the raw high dword of the + /// address (the memory at the same low dword is read otherwise). `vals` as they are for the + /// other loads and without data. + pub(crate) fn rodata_loads(&mut self, pc: u64, hi: Value, a: Value, vals: Vec) -> Vec { + let total: usize = self.rodata.iter().map(|b| b.1.len()).sum(); + let Some(&kind) = self.code_loads.get(&pc) else { return vals }; + if total == 0 { + return vals; + } + let only_code = kind == crate::gpu::recomp::code_loads::CodeLoad::Code; + let table = match self.rodata_table { + Some(g) => g, + None => { + let words: Vec = self.rodata.iter().flat_map(|b| b.1.iter().copied()).collect(); + let words: Vec = words.into_iter().map(|w| self.s.m.i32c(w)).collect(); + let i32 = self.s.m.i32(); + let at = self.s.m.array(total as u64, i32); + let init = self.s.m.aggregate(at, &words); + let g = self.s.m.global("xcl_rodata", at, 0, Some(init), true, 4); + self.rodata_table = Some(g); + g + } + }; + let code = if only_code { + None + } else if self.windowed() { + let w = self.rd(VAR_WIN); + let base = self.uma_base(); + let hi = self.c(crate::gpu::recomp::CODE_ADDRESS_HI); + let cw = self.sub(hi, base); + Some(self.cmp(Pred::Eq, w, cw)) + } else { + Some(self.cmpc(Pred::Eq, hi, crate::gpu::recomp::CODE_ADDRESS_HI)) + }; + // per block: `a`'s offset in it, its dword's index in the table, the block's bytes + let mut first = 0u32; + let mut blocks = Vec::new(); + for (at, len) in self.rodata.iter().map(|b| (b.0, b.1.len() as u32)).filter(|b| b.1 > 0).collect::>() { + let k = self.c(at); + let off = self.sub(a, k); + let q = self.lshrc(off, 2); + let q = self.addc(q, first); + blocks.push((off, q, 4 * len)); + first += len; + } + let z = self.c(0); + vals.into_iter() + .enumerate() + .map(|(i, v)| { + let i = i as u32; + let (mut inside, mut idx) = (None, z); + for &(off, q, bytes) in &blocks { + let (o, q) = if i == 0 { (off, q) } else { (self.addc(off, 4 * i), self.addc(q, i)) }; + let c = self.cmpc(Pred::ULt, o, bytes); + idx = self.sel(c, q, idx); + inside = Some(match inside { + Some(x) => self.or(x, c), + None => c, + }); + } + let mut inside = inside.expect("a block"); + if let Some(cw) = code { + inside = self.and(inside, cw); + } + let p = self.s.m.gep(table, &[z, idx]); + let t = self.s.m.load(p, 4); + self.sel(inside, t, if only_code { z } else { v }) + }) + .collect() + } + /// The window of a buffer access: V# base `d1[15:0]:d0` plus `adds` (the stride bits /// `d1[29:16]` are not part of the address). pub fn buffer_window(&mut self, d0: Value, d1: Value, adds: &[Ea], write: bool) { @@ -160,6 +237,20 @@ impl Lw { } } + /// The raw high dword of a FLAT / global access's address (`flat_window`, `addtid_window`): + /// SADDR's, the VGPR pair's or 0. + pub fn flat_hi(&mut self, d: &Decoded, addtid: bool) -> Value { + let global = d.enc.name == "ENC_FLAT_GLBL"; + let saddr = Self::fv(d, "SADDR"); + if (addtid || global) && saddr != 0x7D && saddr != 0x7F { + self.sreg(saddr + 1) + } else if addtid { + self.c(0) + } else { + self.vreg(Self::fv(d, "ADDR") + 1) + } + } + /// The window of a FLAT / global access: SADDR pair + VGPR offset, or the 64-bit VGPR /// address, plus the instruction offset (signed for global). pub fn flat_window(&mut self, d: &Decoded, write: bool) { diff --git a/crates/xcl/src/gpu/recomp/code_loads.rs b/crates/xcl/src/gpu/recomp/code_loads.rs new file mode 100644 index 0000000000..1764fa672d --- /dev/null +++ b/crates/xcl/src/gpu/recomp/code_loads.rs @@ -0,0 +1,253 @@ +//! Which loads of a program read at a code address: the constant data the console compiler puts +//! after the program (`Options::rodata`), which the program finds with `s_getpc_b64` plus an +//! offset. A load whose address does not come from `s_getpc_b64` needs no look at the table, +//! and one whose address comes only from it needs no memory access. + +use std::collections::BTreeMap; + +use super::cfg::Cfg; +use crate::gpu::rdna2::{self, Decoded}; + +/// `code_loads`: how a load's address relates to the code region. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum CodeLoad { + /// on every path the address's high dword comes from `s_getpc_b64` (with offsets added): + /// the dwords are the table's + Code, + /// it may or may not: the address decides at run time + Maybe, +} + +/// What a register dword holds, as far as the code region goes. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum K { + Data, + Code, + Maybe, +} + +fn join(a: K, b: K) -> K { + if a == b { a } else { K::Maybe } +} + +/// s0..s127, then v0..v255 +const REGS: usize = 128 + 256; + +/// The loads (`s_load*` / `s_buffer_load*`, FLAT / GLOBAL) whose address may be a code address, +/// by pc; the others read the memory. A program whose control flow is not known (an indirect +/// jump) has every such load `Maybe`. +pub fn code_loads(insts: &[Decoded]) -> BTreeMap { + let mut out = BTreeMap::new(); + let Some(cfg) = Cfg::new(insts) else { + for d in insts.iter().filter(|d| address(d).is_some()) { + out.insert(d.pc, CodeLoad::Maybe); + } + return out; + }; + // forward dataflow over the blocks: the registers' kinds at each block's start + let nb = cfg.start.len(); + let mut at: Vec>> = vec![None; nb]; + if nb == 0 { + return out; + } + at[0] = Some(vec![K::Data; REGS]); + let mut work = vec![0usize]; + while let Some(b) = work.pop() { + let mut st = at[b].clone().expect("a reached block"); + for d in &insts[cfg.range(b)] { + step(&mut st, d); + } + for &s in &cfg.succ[b] { + let changed = match &mut at[s] { + Some(t) => { + let mut c = false; + for (x, y) in t.iter_mut().zip(&st) { + let j = join(*x, *y); + c |= j != *x; + *x = j; + } + c + } + None => { + at[s] = Some(st.clone()); + true + } + }; + if changed && !work.contains(&s) { + work.push(s); + } + } + } + for b in 0..nb { + let Some(mut st) = at[b].clone() else { continue }; + for d in &insts[cfg.range(b)] { + if let Some((hi, lo)) = address(d) { + let kind = match st[hi] { + K::Code => Some(CodeLoad::Code), + K::Maybe => Some(CodeLoad::Maybe), + K::Data => lo.iter().any(|&r| st[r] != K::Data).then_some(CodeLoad::Maybe), + }; + if let Some(k) = kind { + out.insert(d.pc, k); + } + } + step(&mut st, d); + } + } + out +} + +/// The registers of a load's address: (the high dword's, the low dword's). +fn address(d: &Decoded) -> Option<(usize, Vec)> { + let f = |n: &str| rdna2::field_value(d.enc, &d.words, n); + let name = d.inst.name; + match d.enc.name { + "ENC_SMEM" if name.starts_with("S_LOAD_") || name.starts_with("S_BUFFER_LOAD_") => { + let b = (f("SBASE")? * rdna2::register_scale("SBASE")) as usize; + Some((b + 1, vec![b])) + } + "ENC_FLAT" | "ENC_FLAT_GLBL" if name.contains("_LOAD_") => { + let (v, s) = (128 + f("ADDR").unwrap_or(0) as usize, f("SADDR").unwrap_or(0x7F) as usize); + if d.enc.name == "ENC_FLAT_GLBL" && s != 0x7D && s != 0x7F { + Some((s + 1, vec![s, v])) + } else { + Some((v + 1, vec![v])) + } + } + _ => None, + } +} + +/// The registers `d` reads (s0..s127, then v0..v255), and whether one of its sources is a +/// constant (inline or literal). An SDWA source with S0 / S1 set is an SGPR, which +/// `rdna2::sgpr_uses` leaves out (SRC0) and `rdna2::vgpr_uses` takes for a VGPR (VSRC1). +fn reads(d: &Decoded) -> (Vec, bool) { + let (sr, _) = rdna2::sgpr_uses(d); + let (vr, _) = rdna2::vgpr_uses(d); + let mut regs: Vec = sr.iter().map(|&r| r as usize).chain(vr.iter().map(|&r| 128 + r as usize)).collect(); + let mut constant = d.ienc.operands.iter().filter(|o| !o.output && !o.implicit).any(|o| { + o.field.is_some_and(|f| { + matches!(f, "SRC0" | "SRC1" | "SRC2" | "SSRC0" | "SSRC1") + && !(f == "SRC0" && d.variant != rdna2::Variant::Plain) + && rdna2::field_value(d.enc, &d.words, f).is_some_and(|v| (128..=255).contains(&v)) + }) + }); + // an SDWA source with S0 / S1 set: an SGPR or a constant (0..=255) + let mut scalar = |regs: &mut Vec, v: u64| match v { + 0..=127 if v != 125 => regs.push(v as usize), + 128..=255 => constant = true, + _ => {} + }; + if d.variant == rdna2::Variant::Sdwa { + let ext = d.words.get(1).copied().unwrap_or(0) as u64; + if ext >> 23 & 1 == 1 { + scalar(&mut regs, ext & 0xff); + } + if let Some(v) = rdna2::field_value(d.enc, &d.words, "VSRC1").filter(|_| ext >> 31 & 1 == 1) { + regs.retain(|&r| r != 128 + v as usize); + scalar(&mut regs, v); + } + } + regs.retain(|&r| r < REGS); + (regs, constant) +} + +/// The kinds after `d`: `s_getpc_b64` gives code addresses, a load gives data, a select joins +/// what it selects from (a constant: data), and any other instruction gives a code address when +/// it computes with one (an offset added to it). +fn step(st: &mut [K], d: &Decoded) { + let (_, sw) = rdna2::sgpr_uses(d); + let (_, vw) = rdna2::vgpr_uses(d); + let (regs, constant) = reads(d); + let reads = regs.into_iter(); + let k = if d.inst.name == "S_GETPC_B64" { + K::Code + } else if matches!(d.enc.name, "ENC_SMEM" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_DS" | "ENC_MIMG") { + K::Data + } else if matches!(d.inst.name, "V_CNDMASK_B32" | "S_CSELECT_B32" | "S_CSELECT_B64") { + reads.map(|r| st[r]).chain(constant.then_some(K::Data)).reduce(join).unwrap_or(K::Data) + } else { + let mut k = K::Data; + for r in reads { + match st[r] { + K::Maybe => k = K::Maybe, + K::Code if k == K::Data => k = K::Code, + _ => {} + } + } + k + }; + for w in sw.iter().map(|&r| r as usize).chain(vw.iter().map(|&r| 128 + r as usize)).filter(|&r| r < REGS) { + st[w] = k; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn insts(prog: &[(&str, &str, &[(&str, u64)], Option)]) -> Vec { + let mut code = Vec::new(); + for (inst, enc, fields, lit) in prog { + code.extend(rdna2::encode(inst, enc, fields, *lit).unwrap()); + } + let mut out = Vec::new(); + let mut off = 0; + while off < code.len() { + let d = rdna2::decode(&code[off..], off as u64).unwrap(); + off += d.len; + out.push(d); + } + out + } + + /// The pattern of a retail LUT bake: the code address plus a scaled index in VGPRs, read + /// with a GLOBAL load; a descriptor table pointer from the user SGPRs reads memory, and a + /// pointer that is a code address on one path only is decided at run time. + #[test] + fn loads_from_s_getpc_read_the_code_and_the_others_memory() { + let p = insts(&[ + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 255)], Some(0x293C)), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)], None), + ("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 5), ("SDST", 106), ("SRC0", 256 + 5), ("SRC1", 0)], None), + ("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 1), ("VSRC1", 6)], None), + ("GLOBAL_LOAD_DWORDX3", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 5), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 5), ("OFFSET", 0x40), ("SOFFSET", 125)], None), + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 0), ("OFFSET", 4), ("SOFFSET", 125)], None), + // s[0:1] is data after the load, a code address again on one path of the branch + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 0), ("SBASE", 5), ("OFFSET", 0), ("SOFFSET", 125)], None), + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 1)], None), + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)], None), + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 21), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)], None), + ("S_ENDPGM", "ENC_SOPP", &[], None), + ]); + let m = code_loads(&p); + assert_eq!(m, BTreeMap::from([(p[5].pc, CodeLoad::Code), (p[7].pc, CodeLoad::Code), (p[11].pc, CodeLoad::Maybe)])); + } + + /// A select between a code address and a constant gives either (the load is decided at run + /// time); an SDWA form that takes the code address from an SGPR (S0 / S1) computes with it. + #[test] + fn constant_and_sdwa_sources_count() { + let sdwa: &[(&str, u64)] = &[("SRC0", 0xF9), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6)]; + let p = insts(&[ + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)], None), + // s[2:3]: the code address, or 0 for its high dword + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 0)], None), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 1), ("SSRC1", 128)], None), + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 1), ("OFFSET", 0), ("SOFFSET", 125)], None), + // v[10:11]: the code address, its high dword moved from s1 by SRC0 (S0) + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 0)], None), + ("V_MOV_B32", "VOP1_VOP_SDWA", &[sdwa, &[("VDST", 11), ("VSRC0", 1), ("S0", 1)]].concat(), None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 20), ("ADDR", 10), ("SADDR", 0x7D), ("OFFSET", 0)], None), + // v13: v12 plus s1 as VSRC1 (S1) + ("V_ADD_NC_U32", "VOP2_VOP_SDWA", &[sdwa, &[("VDST", 13), ("VSRC0", 12), ("VSRC1", 1), ("S1", 1)]].concat(), None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 21), ("ADDR", 12), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("S_ENDPGM", "ENC_SOPP", &[], None), + ]); + assert_eq!(p[5].variant, rdna2::Variant::Sdwa); + let m = code_loads(&p); + assert_eq!(m, BTreeMap::from([(p[3].pc, CodeLoad::Maybe), (p[6].pc, CodeLoad::Code), (p[8].pc, CodeLoad::Code)])); + } +} diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 2f817a809f..f436ce8f09 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -57,6 +57,9 @@ pub(super) struct Em { cur_pc: u64, /// MIMG instruction address → its sampler's S# when the code builds it from constants pub static_ss: BTreeMap, + /// with constant data in the code (`Options::rodata`): the loads that may read it, by pc + /// (`code_loads`); the others read the memory only + pub code_loads: BTreeMap, /// the static samplers sampled with: (S#, comparison), in register order pub static_used: Vec<([u32; 4], bool)>, /// highest VGPR the program references (v_movrel* ranges) @@ -617,6 +620,7 @@ impl Em { upper: None, cur_pc: 0, static_ss: BTreeMap::new(), + code_loads: BTreeMap::new(), static_used: Vec::new(), max_vgpr: 0, has_f16_round_op: false, @@ -1597,9 +1601,13 @@ impl Em { return Err("indirect branch"); } if name == "s_getpc_b64" { - // the code region is addressed from 0 in this model + // the code region is addressed from 0 in this model – with a load that may or may + // not read the constant data after the program, above every memory address + // (`rodata_loader`) let pc = d.pc + d.len as u64; - self.write64(&dst, &hex(pc as u32), "0u"); + let maybe = self.code_loads.values().any(|k| *k == super::code_loads::CodeLoad::Maybe); + let hi = if !maybe { "0u".to_string() } else { hex(super::CODE_ADDRESS_HI) }; + self.write64(&dst, &hex(pc as u32), &hi); return Ok(()); } if matches!(name, "s_bitset0_b64" | "s_bitset1_b64") { @@ -1963,18 +1971,21 @@ impl Em { } else { self.line(&format!("uint {t}_a = ({b} + {} + {soff}) & ~3u;", hex(imm))); } + // (with constant data in the code, which `s_load` reads too: `rodata_loader`) + let hi = if self.opt.mem_windows > 1 { format!("(uint)({t}_ea >> 32), ") } else { format!("{hi}, ") }; + let (load, hi) = self.code_load(d, &hi); match count { 1 => { - self.line(&format!("uint {t}_0 = mem.Load({t}_a);")); + self.line(&format!("uint {t}_0 = {load}({hi}{t}_a);")); vals.push(format!("{t}_0")); } 2 => { - self.line(&format!("uint2 {t}_g0 = mem.Load2({t}_a);")); + self.line(&format!("uint2 {t}_g0 = {load}2({hi}{t}_a);")); vals.extend([format!("{t}_g0.x"), format!("{t}_g0.y")]); } _ => { for g in 0..count / 4 { - self.line(&format!("uint4 {t}_g{g} = mem.Load4({t}_a + {}u);", 16 * g)); + self.line(&format!("uint4 {t}_g{g} = {load}4({hi}{t}_a + {}u);", 16 * g)); vals.extend(["x", "y", "z", "w"].iter().map(|c| format!("{t}_g{g}.{c}"))); } } @@ -1998,6 +2009,18 @@ impl Em { Ok(()) } + /// The dword load of `s_load` / FLAT / GLOBAL instruction `d` (`rodata_loader`) and the + /// high-dword argument (`hi`: `", "`) it takes: the memory's for an address that is not + /// from `s_getpc_b64`, the constant data's for one that is on every path, both for one that + /// may be either. + fn code_load(&self, d: &Decoded, hi: &str) -> (&'static str, String) { + match self.code_loads.get(&d.pc) { + None => ("mem.Load", String::new()), + Some(super::code_loads::CodeLoad::Code) => ("xcl_cload", String::new()), + Some(super::code_loads::CodeLoad::Maybe) => ("xcl_gload", hi.to_string()), + } + } + /// Several memory windows: select the window for a READ whose high dword (bits 32..63) is /// `hi`. 32-bit console descriptor table pointers pass `hi == 0` (window 0); any other `hi` /// outside `[xcl_uma_base, xcl_uma_base + mem_windows)` falls into the `default` arm of the @@ -4415,6 +4438,20 @@ impl Em { let t = self.t(); self.emit_flat_addr(global, op.ends_with("_addtid"), saddr, f("ADDR"), off, 0, store, &t); let act = self.act(); + // (with constant data in the code: `rodata_loader`; with one window the address is the + // low dword, and the high dword only tells a code address) + let hi = if self.code_loads.get(&d.pc) != Some(&super::code_loads::CodeLoad::Maybe) { + String::new() + } else if self.opt.mem_windows > 1 { + format!("(uint)({t}_ea >> 32), ") + } else if (op.ends_with("_addtid") || global) && saddr != 0x7D && saddr != 0x7F { + format!("{}, ", self.sreg(saddr + 1)) + } else if op.ends_with("_addtid") { + "0u, ".into() + } else { + format!("{}, ", self.vreg(f("ADDR") + 1)) + }; + let (load, hi) = self.code_load(d, &hi); let mut st = Vec::new(); for i in 0..count { if store { @@ -4422,7 +4459,7 @@ impl Em { st.push(format!("mem.Store(({t}_a + {}u) & ~3u, {v});", 4 * i)); } else { let v = self.vreg(f("VDST") + i); - st.push(format!("{v} = mem.Load(({t}_a + {}u) & ~3u);", 4 * i)); + st.push(format!("{v} = {load}({hi}({t}_a + {}u) & ~3u);", 4 * i)); } } self.line(&format!("if ({act}) {{ {} }}", st.join(" "))); @@ -4845,6 +4882,7 @@ impl Em { } else { h.push_str(LOADX4_ONE_WINDOW); } + h.push_str(&rodata_loader(&self.opt.rodata)); for (i, (_, cmp)) in self.static_used.iter().enumerate() { let k = self.opt.static_sampler_base as usize + i; let ty = if *cmp { "SamplerComparisonState" } else { "SamplerState" }; @@ -5733,6 +5771,44 @@ fn float_minmax_mem(min: bool, x2: bool, a: &str, v: &str, old: &str, t: &str) - /// Placeholder where the memory window accessors go (after the `mem` declarations). const MEM_ACCESSORS_HERE: &str = "//XCL_MEM_ACCESSORS\n"; +/// `Options::rodata`: the program's constant data as an array of the shader, and the dword +/// loads of `s_load` and FLAT / GLOBAL instructions that read it (`code_loads`): +/// - `xcl_cload*(a)`: the address comes from `s_getpc_b64` on every path – the dwords at code +/// address `a` (0 outside the blocks), no memory access; +/// - `xcl_gload*(hi, a)`: it may – the memory is read, and a code address inside a block (high +/// dword `CODE_ADDRESS_HI`, also with one memory window, where the title's memory at the same +/// low dword is read otherwise) selects the block's dwords instead, with no branch (a test of +/// the window index in a branch around the load made the NVIDIA Linux driver fault while +/// compiling). +/// +/// Nothing without data. +fn rodata_loader(rodata: &[(u32, Vec)]) -> String { + let total: usize = rodata.iter().map(|b| b.1.len()).sum(); + if total == 0 { + return String::new(); + } + let words: Vec = rodata.iter().flat_map(|b| b.1.iter()).map(|w| format!("0x{w:08X}u")).collect(); + let mut s = format!("static const uint xcl_rodata[{total}] = {{ {} }};\nuint xcl_cload(uint a) {{\n uint r = 0u;\n", words.join(", ")); + let mut first = 0usize; + let mut inside = Vec::new(); + for (at, block) in rodata.iter().filter(|b| !b.1.is_empty()) { + let bytes = 4 * block.len(); + let _ = writeln!(s, " r = select(a - {at}u < {bytes}u, xcl_rodata[min({first}u + ((a - {at}u) >> 2), {}u)], r);", total - 1); + inside.push(format!("a - {at}u < {bytes}u")); + first += block.len(); + } + s.push_str(" return r;\n}\n"); + s.push_str("uint2 xcl_cload2(uint a) { return uint2(xcl_cload(a), xcl_cload(a + 4u)); }\n"); + s.push_str("uint4 xcl_cload4(uint a) { return uint4(xcl_cload(a), xcl_cload(a + 4u), xcl_cload(a + 8u), xcl_cload(a + 12u)); }\n"); + let inside = inside.into_iter().reduce(|x, y| format!("or({x}, {y})")).expect("a block"); + let _ = writeln!(s, "bool xcl_code(uint hi, uint a) {{ return and(hi == {:#X}u, {inside}); }}", super::CODE_ADDRESS_HI); + for (n, ty) in [("", "uint"), ("2", "uint2"), ("4", "uint4")] { + let c = if n.is_empty() { "c".to_string() } else { format!("(bool{n})c") }; + let _ = writeln!(s, "{ty} xcl_gload{n}(uint hi, uint a) {{ {ty} m = mem.Load{n}(a); bool c = xcl_code(hi, a); return select({c}, xcl_cload{n}(a), m); }}"); + } + s +} + /// Four dwords at four addresses (scalar buffer loads with their bounds checks); with several /// windows `mem_accessors` defines it, with one switch for all four. const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); }\n"; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 528493d6e5..9f2fd209ad 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -52,6 +52,7 @@ //! `ByteAddressBuffer` (`mem`); initial SGPRs (user data) come from `io`. Textures come next. pub mod cfg; +pub mod code_loads; pub mod dxc; pub mod dxil; pub mod lane_masks; @@ -204,6 +205,13 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21; pub const IO_GS_PRIMS: usize = 110; pub const IO_GS_VERTICES: usize = 111; pub const IO_UMA_BASE_HI: usize = 112; +/// High dword `s_getpc_b64` gives a program that has constant data in its code region +/// (`Options::rodata`) and a load that may or may not read it (`code_loads::CodeLoad::Maybe`), +/// with any number of memory windows: its code addresses are then above every +/// address a title can have (user space ends at 0x7FFF_FFFF_FFFF), so a load from the data is +/// told from a load of the title's memory at the same low dword (descriptor tables in window 0, +/// any memory with one window, which ignores the high dword). +pub const CODE_ADDRESS_HI: u32 = 0xC0DE; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) @@ -528,11 +536,17 @@ pub struct Options { /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, + /// constant data the console compiler put in the code region after the program + /// (`xbox::Fssm::rodata`): (address from the program's start, dwords). The program finds + /// it with `s_getpc_b64` and reads it with `s_load` / `global_load`; the title's memory does + /// not hold the code, so a load at a code address in one of these ranges takes the dwords + /// from the shader (`CODE_ADDRESS_HI`) + pub rodata: Vec<(u32, Vec)>, } impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true } + Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true, rodata: Vec::new() } } } @@ -1550,6 +1564,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { em.coherent_mem = matches!(opt.mode, Mode::Compute(_)) && needs_coherent_mem(&insts); em.configure_round_modes(&insts, branches == 0); em.static_ss = constant_samplers(&insts, &leaders); + if !opt.rodata.is_empty() { + em.code_loads = code_loads::code_loads(&insts); + } // split wave64: masks only read lane by lane skip the halves' exchange (geometry mode // continues from the ES into the GS through s_setpc: left as it is); pixel shaders: they // skip the quad reads that give the helper lanes' bits diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5d000775ef..4d4a68ebf6 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -948,6 +948,21 @@ fn direct_fallback(stage: &str, err: &str) { crate::xlog_info!("[SHADER] direct DXIL fallback stage={stage} reason=\"{reason}\" detail=\"{}\" – HLSL path", err.lines().next().unwrap_or("")); } +/// Whether the program takes an address in its code region for something else than a far jump +/// (`rdna2::resolve_far_jumps`): an `s_getpc_b64` the compiler emits to reach the constant +/// data after the program. +fn takes_code_address(code: &[u8]) -> bool { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let Ok(d) = crate::gpu::rdna2::decode(&code[off..], off as u64) else { return false }; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + (0..insts.len()).any(|i| insts[i].inst.name == "S_GETPC_B64" && !insts.get(i + 3).is_some_and(|s| s.far_target.is_some())) +} + /// A console compute shader through the direct DXIL translator (`gpu::dxil::kernel`). /// FSPX (driver) containers are left to the HLSL path. fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result { @@ -956,10 +971,13 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; + // the constant data the program reads from its own code region (`Options::rodata`) + let rodata = f.rodata(p); let wave64 = super::fssm_wave64(f, code); let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base }; // `XCL_PER_LANE=1`: the per-lane form first, #1426's per-instruction form where it refuses - if super::lower_dxil::enabled() { + // (and for a program that reads constant data in its code: the per-lane form has no table) + if super::lower_dxil::enabled() && !(!rodata.is_empty() && takes_code_address(code)) { match super::lower_dxil::compute_with(code, &cs, o) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("CS per-lane"); @@ -972,7 +990,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } } } - let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64)?; + let k = crate::gpu::dxil::kernel::translate_entry_rodata(code, o, crate::gpu::dxil::kernel::Entry::Compute(cs), split_wave64, &rodata)?; dump_direct(blob, &k.dxil); Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) } @@ -1003,11 +1021,12 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; let o = crate::gpu::dxil::kernel::KernelOptions { wave64: super::fssm_wave64(f, code), split: false, mem_windows: windows, sampler_base }; - let k = match (&mode, stage) { - (Mode::Vertex(vs), Stage::Vertex) => crate::gpu::dxil::kernel::translate_vertex(code, o, vs)?, - (Mode::Pixel(ps), Stage::Pixel) => crate::gpu::dxil::kernel::translate_pixel(code, o, ps)?, + let entry = match (&mode, stage) { + (Mode::Vertex(vs), Stage::Vertex) => crate::gpu::dxil::kernel::Entry::Vertex(vs.clone()), + (Mode::Pixel(ps), Stage::Pixel) => crate::gpu::dxil::kernel::Entry::Pixel(ps.clone()), _ => return Err("the shader stage does not match its slot in the PSO".into()), }; + let k = crate::gpu::dxil::kernel::translate_entry_rodata(code, o, entry, false, &f.rodata(p))?; dump_direct(blob, &k.dxil); Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }) } @@ -1047,7 +1066,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, rodata: f.rodata(p), ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1090,6 +1109,7 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option fn compile_console_mesh( blob: &[u8], code: &[u8], + rodata: Vec<(u32, Vec)>, ms: &super::MsInterface, wave64: bool, windows: u32, @@ -1106,7 +1126,7 @@ fn compile_console_mesh( mem_windows: windows, sampler_base: 0, }; - match crate::gpu::dxil::kernel::translate_mesh(code, o, ms) { + match crate::gpu::dxil::kernel::translate_entry_rodata(code, o, crate::gpu::dxil::kernel::Entry::Mesh(ms.clone()), false, &rodata) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("MS"); dump_direct(blob, &k.dxil); @@ -1115,7 +1135,7 @@ fn compile_console_mesh( Err(e) => direct_fallback("MS", &e), } } - let t = super::translate_mesh(code, ms.clone(), wave64, split_wave64, windows)?; + let t = translate(code, &Options { mode: Mode::Mesh(ms.clone()), wave64, split_wave64, mem_windows: windows, rodata, ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1131,7 +1151,7 @@ fn console_mesh_with( windows: u32, cache_dir: &std::path::Path, cache: &Mutex, - compile: impl FnOnce(&[u8], &super::MsInterface, bool) -> Result, + compile: impl FnOnce(&[u8], Vec<(u32, Vec)>, &super::MsInterface, bool) -> Result, ) -> Result { let sh = xbox::parse(blob).ok_or("not a console shader container")?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 7)).ok_or("no NGG hardware variant")?; @@ -1142,7 +1162,7 @@ fn console_mesh_with( let code = &f.data[p.offset..p.offset + p.len]; let wave64 = super::fssm_wave64(f, code); let split = wave64 && split_wave64; - let compile_one = || compile(code, ms, wave64); + let compile_one = || compile(code, f.rodata(p), ms, wave64); // Cache the mesh compute pass in RAM (`ShaderCache` + in-flight coalescing) and on disk // (`translated/v2`, namespaced by backend) across all `(MS, PS)` pipelines that share it. let cs = if cache_allowed(Stage::Mesh, |name| std::env::var_os(name).is_some()) { @@ -1167,8 +1187,8 @@ fn console_mesh_with( pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { let windows = mem_windows(); let dir = dxc::cache_dir(); - console_mesh_with(blob, ps, split_wave64, windows, &dir, shader_cache(), |code, ms, wave64| { - compile_console_mesh(blob, code, ms, wave64, windows, split_wave64) + console_mesh_with(blob, ps, split_wave64, windows, &dir, shader_cache(), |code, rodata, ms, wave64| { + compile_console_mesh(blob, code, rodata, ms, wave64, windows, split_wave64) }) } @@ -1428,6 +1448,19 @@ mod shader_cache_tests { assert_ne!(a, translated::identity_for("source-a", "dxc-b")); } + /// Which loads read the constant data in the code (`code_loads`, over `cfg::Cfg`) decides + /// the HLSL and the direct translations alike: both files are in the translator's source + /// hash, so a change to them is another identity. + #[test] + fn translated_identity_tracks_the_code_load_analysis() { + let build = include_str!("../../../build.rs"); + let list = &build[build.find("const TRANSLATOR_SOURCES").unwrap()..]; + let list = &list[..list.find("];").unwrap()]; + for f in ["src/gpu/recomp/code_loads.rs", "src/gpu/recomp/cfg.rs"] { + assert!(list.contains(&format!("\"{f}\"")), "{f} is not in build.rs TRANSLATOR_SOURCES"); + } + } + #[test] fn translated_namespace_tracks_every_request_input() { let dir = PathBuf::from("cache"); @@ -1950,9 +1983,9 @@ mod shader_cache_tests { let compiles = AtomicUsize::new(0); let run = |c: &Mutex| { - console_mesh_with(&blob, None, false, 1, &dir, c, |code, ms, wave64| { + console_mesh_with(&blob, None, false, 1, &dir, c, |code, rodata, ms, wave64| { compiles.fetch_add(1, Ordering::SeqCst); - compile_console_mesh(&blob, code, ms, wave64, 1, false) + compile_console_mesh(&blob, code, rodata, ms, wave64, 1, false) }) }; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018edc36..87dcb7fce4 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4510,6 +4510,122 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() { } } +/// Constant data after the program (`Options::rodata`): `s_getpc_b64` plus the compiler's +/// offset is its address, and `s_load` / `global_load` read it from the shader. The memory +/// does not hold the code (a retail tone-map LUT bake read zeros for its spline coefficients +/// there and wrote one colour to every texel); any other address still reads the memory. +#[test] +fn gpu_loads_read_the_constant_data_after_the_program() { + loads_read_the_constant_data(false); +} + +/// As `gpu_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_loads_read_the_constant_data_after_the_program_not_the_memory_at_its_offset() { + 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 loads_read_the_constant_data(at_the_table: bool) { + 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), + // 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 = (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)]; + assert!(!translate(&code, &Options::default()).unwrap().hlsl.contains("xcl_gload"), "no data, no loader"); + if !gpu_ready() { + return; + } + let check = |r: &runner::KernelResult, 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"); + 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 = KernelState::default(); + st.sgpr[2] = if at_the_table { block + 4 } else { 0x900 }; + 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 + 2].copy_from_slice(&[4242, 4343]); + for l in 0..64 { + mem[0x200 + l] = 7000 + l as u32; + } + let t = translate(&code, &Options { rodata: rodata.clone(), ..runner::options(Mode::Kernel) }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + check(&runner::run(&dxil, &st, &mem).unwrap(), "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 heap in [false, true] { + let t = translate(&code, &on_gpu(Options { mem_windows: 2, heap_windows: heap, rodata: rodata.clone(), ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported); + // loads from s_getpc_b64 read the table only, the others the memory only; the load that + // may be either tells by the address's high dword, with no branch + let h = &t.hlsl; + assert_eq!(h.matches("= xcl_cload(").count(), 4, "s_load_dword and global_load_dwordx3 of the table:\n{h}"); + assert!(h.contains("= xcl_cload4(") && h.contains("v8 = xcl_mLoad(("), "{h}"); + assert_eq!(h.matches("= xcl_gload(").count(), 2, "the two loads through s[8:9]:\n{h}"); + assert!(h.contains(&format!("bool xcl_code(uint hi, uint a) {{ return and(hi == 0xC0DEu, a - {block}u < 40u); }}")), "{h}"); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + check(&runner::run_in_arena(&dxil, &st, &arena).unwrap(), if heap { "heap windows" } else { "two windows" }); + } +} + /// Experiment: does OpenExistingHeapFromAddress accept a reservation with only part committed? #[test] #[ignore] diff --git a/crates/xcl/src/gpu/xbox.rs b/crates/xcl/src/gpu/xbox.rs index c268bf9bbf..63b9a0849c 100644 --- a/crates/xcl/src/gpu/xbox.rs +++ b/crates/xcl/src/gpu/xbox.rs @@ -151,6 +151,19 @@ impl Fssm { self.version == 0x101 && rd32(&self.data, 0xD4).is_some_and(|w| w != 0xDEAD_BEEF && w & 0x20 != 0) } + /// The constant data blocks that follow program `p` in the code region, as the program + /// addresses them (`s_getpc_b64`: from its own start): (address, dwords of the block). + pub fn rodata(&self, p: &Program) -> Vec<(u32, Vec)> { + self.data_blocks + .iter() + .filter(|b| b.offset >= p.offset + p.len) + .filter_map(|b| { + let bytes = self.data.get(b.offset..b.offset + b.len)?; + Some(((b.offset - p.offset) as u32, bytes.chunks_exact(4).map(|w| u32::from_le_bytes(w.try_into().unwrap())).collect())) + }) + .collect() + } + pub fn stage_label(&self) -> String { if self.stages.is_empty() { return "?".into(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 4c5a014974..b554383cdd 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1765,7 +1765,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // as `pso` translates: with the title's memory windows (`console_translation`, // `translate_mesh`) let split = if matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { graphics_split } else { split }; - let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, ..Default::default() }; + let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, rodata: f.rodata(p), ..Default::default() }; let t = match recomp::translate(code, &opt) { Ok(t) if t.complete() => t, Ok(_) => { @@ -2437,9 +2437,9 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> let t = std::time::Instant::now(); let r = { let (tx, rx) = std::sync::mpsc::channel(); - let (c, m) = (code.to_vec(), mode.clone()); + let (c, m, rodata) = (code.to_vec(), mode.clone(), f.rodata(p)); std::thread::spawn(move || { - let _ = tx.send(coverage::translate_mode(&c, &m, o, validate)); + let _ = tx.send(coverage::translate_mode(&c, &m, o, validate, &rodata)); }); rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))) }; @@ -2481,7 +2481,7 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> recomp::Mode::Pixel(_) => "ps_6_6", _ => "cs_6_6", }; - let opt = recomp::Options { mode: mode.clone(), wave64, split_wave64: wave64 && split, mem_windows: windows, ..Default::default() }; + let opt = recomp::Options { mode: mode.clone(), wave64, split_wave64: wave64 && split, mem_windows: windows, rodata: f.rodata(p), ..Default::default() }; let t = recomp::translate(code, &opt).ok().filter(|t| t.complete())?; dump("hlsl", t.hlsl.as_bytes()); let d = recomp::dxc::compile(&t.hlsl, "main", profile, &[]).ok()?;