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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,25 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
- With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`.
XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with
those on which the GPU completed at least one operation.
- `XCL_HOST_DXR=1` enables an experimental shadow-build capture of XboxBvhBuilder
build, rehydrate and copy calls on DXR 1.1 devices. It snapshots triangle inputs from
mapped UMA windows and rewrites readable CPU instance arrays to native BLAS addresses.
Compressed rehydration, command-buffer replay, procedural geometry and GPU-generated
instance arrays are not supported. Rehydration invalidates earlier shadow mappings.
Native buffers are retained until exit with a 256 MiB allocation budget
per device. Translated shaders still use the console BVH, so this diagnostic mode
adds GPU work and does not accelerate rendering yet. It is disabled by default.
- `XCL_HOST_RAYQUERY=1` additionally enables an experimental native consumer for one
verified full-resolution shadow compute shader. One compatible native TLAS is bound
directly per dispatch; mismatched addresses retain the original traversal. Only opaque
triangle BLASes without geometry transforms and translation-only instances with mask
`0xff` and no flags are eligible. A native hit tightens the maximum distance of the original
traversal; the guest still checks nearer intersections, including zero-distance hits, before merging the native
endpoint. A native miss leaves the original traversal unchanged. Freed or
remapped UMA ranges invalidate captured bindings. Producers and consumers must share the
same current command-list recording; Reset invalidates the bindings. Cross-list and
cross-queue publication is not supported. This is disabled by default; retail
scene coverage and a rendering performance improvement have not been established.
- `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib
requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget
(`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order.
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const TRANSLATOR_SOURCES: &[&str] = &[
"src/gpu/recomp/emit.rs",
"src/gpu/recomp/mesh_wave.rs",
"src/gpu/recomp/mod.rs",
"src/gpu/recomp/rayquery.rs",
"src/gpu/recomp/upper_lanes.rs",
"src/gpu/recomp/x64_masks.rs",
"src/gpu/shader.rs",
Expand Down
52 changes: 52 additions & 0 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ pub(super) enum Flow {
}

pub(super) struct Em {
pub rayquery_region: Option<super::rayquery::Region>,
uses_rayquery: bool,
opt: Options,
out: String,
pub indent: usize,
Expand Down Expand Up @@ -567,6 +569,8 @@ fn to_f16_rounded_expr(dynamic_rm: bool, e: &str) -> String {
impl Em {
pub fn new(opt: Options) -> Self {
Em {
rayquery_region: None,
uses_rayquery: false,
opt,
out: String::new(),
indent: 1,
Expand Down Expand Up @@ -975,6 +979,51 @@ impl Em {

// ---------------------------------------------------------------- one instruction

/// Use a native hit as an upper bound, retaining the guest's boundary intersections.
pub fn emit_rayquery_branch(&mut self) {
self.uses_rayquery = true;
let active = self.act();
self.line("bool xcl_q_ready = xcl_query_matches(s4, s5), xcl_q_hit = false;");
self.line("uint xcl_q_t = 0u;");
self.line("if (xcl_q_ready) {");
self.indent += 1;
self.line(&format!("bool xcl_q_bad = and({active}, !and(and(all(isfinite(asfloat(uint3(v47,v48,v49)))), all(isfinite(asfloat(uint3(v50,v51,v5))))), and(isfinite(asfloat(v8)), and(asfloat(v8) > 0.0f, any(asfloat(uint3(v50,v51,v5)) != 0.0f)))));"));
if self.x64() {
self.line("uint2 xcl_q_invalid = xcl_x_ballot(xcl_q_bad);");
self.line("xcl_q_ready = (xcl_q_invalid.x | xcl_q_invalid.y) == 0u;");
} else {
self.line("xcl_q_ready = !WaveActiveAnyTrue(xcl_q_bad);");
}
self.indent -= 1;
self.line("}");
self.line(&format!("if (and(xcl_q_ready, {active})) {{"));
self.indent += 1;
self.line("RayDesc xcl_q_ray; xcl_q_ray.Origin = asfloat(uint3(v47,v48,v49)); xcl_q_ray.Direction = asfloat(uint3(v50,v51,v5));");
self.line("xcl_q_ray.TMin = 0.0f; xcl_q_ray.TMax = asfloat(v8);");
self.line("RayQuery<RAY_FLAG_CULL_BACK_FACING_TRIANGLES> xcl_q;");
self.line("xcl_q.TraceRayInline(xcl_q_scene, RAY_FLAG_NONE, 0xffu, xcl_q_ray);");
self.line("while (xcl_q.Proceed()) {}");
self.line("xcl_q_hit = xcl_q.CommittedStatus() == COMMITTED_TRIANGLE_HIT;");
self.line("xcl_q_t = xcl_q_hit ? asuint(xcl_q.CommittedRayT()) : 0u;");
self.line("xcl_q_hit = and(xcl_q_hit, asfloat(xcl_q_t) < asfloat(v8));");
#[cfg(test)]
if matches!(self.opt.mode, Mode::Kernel) {
self.line(&format!("res.InterlockedAdd({}u, 1u);", super::KERNEL_RES_DWORDS * 4));
self.line(&format!("if (xcl_q_hit) res.InterlockedAdd({}u, 1u);", (super::KERNEL_RES_DWORDS + 1) * 4));
}
self.indent -= 1;
self.line("}");
self.line("v8 = xcl_q_hit ? xcl_q_t : v8;");
// The guest can accept a t=0 intersection that native traversal omits. Search the
// shorter interval too, then merge the native endpoint only if it found no nearer hit.
self.line("{");
}

pub fn emit_rayquery_merge(&mut self) {
self.line("bool xcl_q_use = and(xcl_q_hit, v28 == 0xc47a0000u);");
self.line("v8 = xcl_q_use ? xcl_q_t : v8; v28 = xcl_q_use ? xcl_q_t : v28; v31 = xcl_q_use ? 0u : v31;");
}

/// Emit one basic block's instructions in order; stops at the first non-fallthrough flow.
/// In split-wave64 mode, folds cross-half reduction tails (`v_readlane(v, L)` -> `v_op(v, s, v)`
/// -> `v_readlane(v, L^32)`, 32-bit and 64-bit `v_add_f64`) into a single `xcl_x_meet()`.
Expand Down Expand Up @@ -4694,6 +4743,9 @@ impl Em {
let infos: Vec<String> = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect();
let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", "));
h.push_str(PRELUDE_MEM);
if self.uses_rayquery {
h.push_str(super::rayquery::LOOKUP);
}
if self.uses_scratch {
h.push_str(PRELUDE_SCRATCH);
}
Expand Down
30 changes: 29 additions & 1 deletion crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ pub(crate) mod emit;
pub mod mesh_dispatch;
pub mod mesh_wave;
pub mod partition;
pub(crate) mod rayquery;
pub mod x64_masks;
pub mod pso;
pub use emit::mesh_passthrough;
Expand Down Expand Up @@ -202,6 +203,9 @@ 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;
pub const IO_HOST_AS_LO: usize = 113;
pub const IO_HOST_AS_HI: usize = 114;
pub const IO_HOST_AS_MAGIC: usize = 115;

impl GsInterface {
/// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register)
Expand Down Expand Up @@ -497,6 +501,8 @@ pub fn interface(blob: &[u8], sh: &super::xbox::XboxShader, f: &super::xbox::Fss

#[derive(Debug, Clone)]
pub struct Options {
/// Opt-in whole-region inline RayQuery for the verified shadow traversal program.
pub host_rayquery: bool,
pub mode: Mode,
/// wave64 (64-bit EXEC/VCC) or wave32 program
pub wave64: bool,
Expand Down Expand Up @@ -530,7 +536,7 @@ pub struct Options {

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 { host_rayquery: false, mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true }
}
}

Expand Down Expand Up @@ -1017,6 +1023,23 @@ fn emit_structured(
}
let d = depth + guard.is_some() as usize;
let ipad = " ".repeat(d);
if let Some(region) = em.rayquery_region.filter(|r| r.start == s && r.end <= hi) {
em.rayquery_region = None;
em.indent = d;
em.emit_rayquery_branch();
body.push_str(&em.take());
let raised = emit_structured(c, em, body, region.start, region.end, Some(region.end), nest + 1,
cont, &none, d + 1, blocks, flags);
body.push_str(&format!("{ipad}}}\n"));
em.indent = d;
em.emit_rayquery_merge();
body.push_str(&em.take());
em.rayquery_region = Some(region);
pending.extend(raised);
queued = None;
i = c.leaders.partition_point(|&l| l < region.end);
continue;
}
if resolved {
body.push_str(&format!("{ipad}{} = false;\n", skip_flag(s)));
}
Expand Down Expand Up @@ -1403,8 +1426,12 @@ pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
insts.push(d);
}
rdna2::resolve_far_jumps(&mut insts);
let query = rayquery::identify(program, opt, &insts);
let starts: BTreeSet<u64> = insts.iter().map(|d| d.pc).collect();
let mut leaders: BTreeSet<u64> = BTreeSet::from([0]);
if let Some(region) = query {
leaders.extend([region.start, region.end]);
}
let mut branches = 0usize;
// geometry mode: the ES's s_setpc_b64 continues into the GS code (or ends the ES alone)
let gs_jump = match &opt.mode {
Expand Down Expand Up @@ -1433,6 +1460,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
}
}
let mut em = emit::Em::new(opt.clone());
em.rayquery_region = query;
em.configure_round_modes(&insts, branches == 0);
em.static_ss = constant_samplers(&insts, &leaders);
// split wave64: masks only read lane by lane skip the halves' exchange (geometry mode
Expand Down
54 changes: 46 additions & 8 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,15 @@ pub struct Compiled {
/// Translate a console shader for `stage` to signed DXIL (DXC, disk-cached); its static
/// samplers take registers from `sampler_base` (space 1).
/// Fails when the blob is not a console shader or the program is not fully translated.
pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result<Compiled, String> {
pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result<Arc<Compiled>, String> {
console_to_dxil_for(blob, stage, sampler_base, false)
}

/// `console_to_dxil` for a GPU that runs only 32-lane waves when `split_wave64`
/// (`wave32_only_for_device`): a wave64 compute program gets the split form
/// (`Options::split_wave64`) instead of `[WaveSize(64)]`, which such a driver rejects.
/// Finished shaders are also kept in memory (`ShaderCache`): pipelines share their shaders.
pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result<Compiled, String> {
pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result<Arc<Compiled>, String> {
console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows())
}

Expand All @@ -148,10 +148,15 @@ fn shader_cache() -> &'static Mutex<ShaderCache> {

/// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile`
/// fills the caches without a title: the same keys as at its run).
pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result<Compiled, String> {
pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result<Arc<Compiled>, String> {
let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64);
// Keep the opt-in variant out of the legacy translation caches. DXC still caches by
// the generated HLSL, and only this one verified record takes this path.
if native_query_blob(blob, stage) {
return compile_one().map(Arc::new);
}
if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) {
return compile_one();
return compile_one().map(Arc::new);
}
let key = ShaderKey {
hash: crate::gpu::shader::fnv64(blob),
Expand All @@ -164,7 +169,7 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa
// with `XCL_DIRECT_DXIL` the disk entries live under their own identity (backend tag,
// direct translator version, routing mode): never mixed with the HLSL path's entries
let from_disk = || translated::cached(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one);
cached_shader(shader_cache(), key, blob, from_disk).map(|shader| shader.as_ref().clone())
cached_shader(shader_cache(), key, blob, from_disk)
}

/// Translations on disk: a console program's (DXIL, static samplers) by its bytes, so a run
Expand Down Expand Up @@ -365,7 +370,7 @@ mod translated {
fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<Compiled, String> {
// `XCL_DIRECT_DXIL=1`: compute shaders through the direct DXIL translator, the HLSL path
// for what it cannot translate yet
if stage == Stage::Compute && crate::gpu::dxil::kernel::enabled() {
if stage == Stage::Compute && crate::gpu::dxil::kernel::enabled() && !native_query_blob(blob, stage) {
if dxc::defer() {
return Err("DXIL not compiled yet".into());
}
Expand Down Expand Up @@ -809,14 +814,23 @@ 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::detect_wave64(code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?;
let t = translate(code, &Options { host_rayquery: native_query_blob(blob, stage), mode, wave64: super::detect_wave64(code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?;
if t.hlsl.contains("TraceRayInline") {
crate::xlog_info!("Host RayQuery: verified shadow traversal translated (record {:016x})", super::rayquery::SHADOW_RECORD);
}
if !t.complete() {
let missing: Vec<&String> = t.unsupported.keys().collect();
return Err(format!("incomplete translation, missing: {missing:?}"));
}
Ok((t, profile))
}

fn native_query_blob(blob: &[u8], stage: Stage) -> bool {
stage == Stage::Compute && crate::hle::d3d12x::host_bvh::query_requested()
&& crate::gpu::shader::fnv64(blob) == super::rayquery::SHADOW_RECORD
&& crate::hle::d3d12x::host_bvh::query_supported()
}

/// A console geometry stage as XCL runs it, in two passes: the console program as a compute
/// shader writes one record per thread group (vertices + primitives, `record`) into `res`,
/// then a pass-through mesh shader rasterises the records with the pixel shader.
Expand Down Expand Up @@ -1047,7 +1061,7 @@ pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[S
let statics: Vec<D3D12_STATIC_SAMPLER_DESC> = samplers.iter().enumerate().map(|(k, s)| static_sampler_desc(k as u32, s)).collect();
unsafe {
// u0 io, u1 res, u2..u5 the memory windows (`gpu::uma`; unused ones need no binding)
let params: Vec<D3D12_ROOT_PARAMETER1> = (0..6)
let mut params: Vec<D3D12_ROOT_PARAMETER1> = (0..6)
.map(|i| D3D12_ROOT_PARAMETER1 {
ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV,
Anonymous: D3D12_ROOT_PARAMETER1_0 {
Expand All @@ -1056,6 +1070,15 @@ pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[S
ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
})
.collect();
if crate::hle::d3d12x::host_bvh::query_requested() {
params.push(D3D12_ROOT_PARAMETER1 {
ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV,
Anonymous: D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 {
ShaderRegister: 0, RegisterSpace: 2, Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE,
} },
ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
});
}
let mut flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
if graphics {
flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
Expand Down Expand Up @@ -1566,6 +1589,21 @@ mod shader_cache_tests {
mod compile_time_bench {
use super::*;

#[test]
fn repeated_console_shader_requests_share_dxil() {
use crate::gpu::xbox::tests::{fssm, sample, CODE};
let mut f = fssm(&CODE, &[(6, 0)]);
for offset in [0x13C, 0x140, 0x144] {
f[offset..offset + 4].copy_from_slice(&1u32.to_le_bytes());
}
let blob = sample(5, &[f]);
let first = console_to_dxil(&blob, Stage::Compute, 0).unwrap();
let second = console_to_dxil(&blob, Stage::Compute, 0).unwrap();
assert_eq!(first.dxil, second.dxil);
assert_eq!(first.samplers, second.samplers);
assert_eq!(first.dxil.as_ptr(), second.dxil.as_ptr(), "a cache hit shares its compiled storage");
}

#[test]
#[ignore]
fn repeated_pso_shader_compile() {
Expand Down
Loading
Loading