Skip to content
Draft
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
1 change: 1 addition & 0 deletions crates/xcl/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const TRANSLATOR_SOURCES: &[&str] = &[
"src/gpu/recomp/emit.rs",
"src/gpu/recomp/mesh_wave.rs",
"src/gpu/recomp/mod.rs",
"src/gpu/recomp/native_mesh.rs",
"src/gpu/recomp/upper_lanes.rs",
"src/gpu/recomp/x64_masks.rs",
"src/gpu/shader.rs",
Expand Down
60 changes: 47 additions & 13 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub(super) enum Flow {
}

pub(super) struct Em {
pub(super) native_mesh: bool,
/// whole-wave reductions (`graphics_reductions`)
pub reductions: super::Reductions,
opt: Options,
Expand Down Expand Up @@ -602,6 +603,7 @@ impl Em {
pub fn new(opt: Options) -> Self {
Em {
opt,
native_mesh: false,
reductions: Default::default(),
out: String::new(),
indent: 1,
Expand Down Expand Up @@ -1374,9 +1376,13 @@ impl Em {
// GS_ALLOC_REQ: M0 = primitives << 12 | vertices (scalar: whatever EXEC is)
if rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0) & 0xF == 9 {
let m0 = self.sreg(124);
self.line(&format!(
"if (lane_id == 0u) {{ res.Store(xcl_rec * 4u, {m0} & 0x3FFu); res.Store(xcl_rec * 4u + 4u, ({m0} >> 12) & 0x7FFu); }}"
));
if self.native_mesh {
self.line(&format!("if (lane_id == 0u) xcl_counts = {m0};"));
} else {
self.line(&format!(
"if (lane_id == 0u) {{ res.Store(xcl_rec * 4u, {m0} & 0x3FFu); res.Store(xcl_rec * 4u + 4u, ({m0} >> 12) & 0x7FFu); }}"
));
}
}
Flow::Next
}
Expand Down Expand Up @@ -2433,7 +2439,7 @@ impl Em {
(Mode::Mesh(_), 12) => {
for c in 0..4 {
if enabled(c) {
st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {c}u) * 4u, {});", Self::exp_comp(srcs, compr, c)));
st.push(self.mesh_vertex_store(c, &Self::exp_comp(srcs, compr, c)));
}
}
}
Expand All @@ -2450,12 +2456,16 @@ impl Em {
for j in at {
for c in 0..4 {
if enabled(c) {
st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {}u) * 4u, {});", 4 * (j + 1) + c, Self::exp_comp(srcs, compr, c)));
st.push(self.mesh_vertex_store(4 * (j + 1) + c, &Self::exp_comp(srcs, compr, c)));
}
}
}
}
(Mode::Mesh(_), 20) => st.push(format!("if (xcl_pok) res.Store(xcl_prm * 4u, {});", srcs[0])),
(Mode::Mesh(_), 20) => st.push(if self.native_mesh {
format!("xcl_primitive = {};", srcs[0])
} else {
format!("if (xcl_pok) res.Store(xcl_prm * 4u, {});", srcs[0])
}),
(Mode::Mesh(_), 9) => {}
_ => return Err("export target"),
}
Expand All @@ -2476,6 +2486,14 @@ impl Em {
Ok(())
}

fn mesh_vertex_store(&self, component: usize, value: &str) -> String {
if self.native_mesh {
format!("xcl_vertex[{component}] = {value};")
} else {
format!("if (xcl_vok) res.Store((xcl_vtx + {component}u) * 4u, {value});")
}
}

/// (vdst, I/J VGPR or interp_mov parameter, attribute, channel)
fn interp_fields(d: &Decoded) -> (u64, u64, u64, u64) {
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
Expand Down Expand Up @@ -5066,7 +5084,12 @@ impl Em {
// lane reads within a quad see helper lanes (`rla`)
h.push_str("#define XCL_PIXEL 1\n");
}
h.push_str("RWByteAddressBuffer io : register(u0);\nRWByteAddressBuffer res : register(u1);\n");
if self.native_mesh {
// The PS reads its own title arguments from u0. Native mesh uses the old record slot.
h.push_str("RWByteAddressBuffer io : register(u1);\n");
} else {
h.push_str("RWByteAddressBuffer io : register(u0);\nRWByteAddressBuffer res : register(u1);\n");
}
// compute work across workgroups (bottom-up BVH builds: atomics, then reading what
// other groups wrote) relies on GLC / cache invalidation on the console: keep the flat
// memory coherent across the GPU only when the program actually uses those; otherwise
Expand Down Expand Up @@ -5378,7 +5401,11 @@ static uint xcl_cap = 1u << 16;
}
self.safe_barrier_prelude(&mut h);
let t = ms.threads;
let _ = writeln!(h, "[WaveSize({native_lanes})]\n[numthreads({t}, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID)\n{{");
if self.native_mesh {
super::native_mesh::entry(&mut h, ms);
} else {
let _ = writeln!(h, "[WaveSize({native_lanes})]\n[numthreads({t}, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID)\n{{");
}
if self.safe_barrier {
h.push_str(" xcl_s_barrier_init(gi);\n");
}
Expand All @@ -5391,17 +5418,21 @@ static uint xcl_cap = 1u << 16;
}
// thread index in the group as the console numbers it: wave · lanes + lane
let _ = writeln!(h, " uint xcl_wave = gi / {lanes}u;\n uint xcl_slot = xcl_wave * {lanes}u + lane_id;");
let _ = writeln!(h, " uint xcl_rec = gid.x * {}u;", ms.record_dwords());
let _ = writeln!(h, " uint xcl_vtx = xcl_rec + {MESH_HEADER}u + xcl_slot * {}u;", ms.vert_dwords());
let _ = writeln!(h, " uint xcl_prm = xcl_rec + {}u + xcl_slot;", MESH_HEADER + ms.max_vertices as usize * ms.vert_dwords());
if !self.native_mesh {
let _ = writeln!(h, " uint xcl_rec = gid.x * {}u;", ms.record_dwords());
let _ = writeln!(h, " uint xcl_vtx = xcl_rec + {MESH_HEADER}u + xcl_slot * {}u;", ms.vert_dwords());
let _ = writeln!(h, " uint xcl_prm = xcl_rec + {}u + xcl_slot;", MESH_HEADER + ms.max_vertices as usize * ms.vert_dwords());
}
// A record has room for `max_vertices` vertices and `max_primitives` primitives; a
// thread past either exports nothing (the console's hardware drops an export past
// what the program asked room for). `res` is a root UAV: nothing bounds a store
// there, and one past the last record of the buffer is a store to an unmapped
// address (a retail title's first frames with mesh programs lost the device to a
// shader's access to unmapped memory on five shader units at once).
let _ = writeln!(h, " bool xcl_vok = xcl_slot < {}u;", ms.max_vertices);
let _ = writeln!(h, " bool xcl_pok = xcl_slot < {}u;", ms.max_primitives);
if !self.native_mesh {
let _ = writeln!(h, " bool xcl_vok = xcl_slot < {}u;", ms.max_vertices);
let _ = writeln!(h, " bool xcl_pok = xcl_slot < {}u;", ms.max_primitives);
}
load_sgprs(&mut h);
if sg.contains(&3) {
h.push_str(" s3 = (s3 & 0xF0FFFFFFu) | (xcl_wave << 24);\n");
Expand All @@ -5422,6 +5453,9 @@ static uint xcl_cap = 1u << 16;
if self.safe_barrier {
h.push_str(" xcl_s_barrier_exit();\n");
}
if self.native_mesh {
super::native_mesh::finish(&mut h, ms);
}
h.push_str("}\n");
}
Mode::Geometry(g) => {
Expand Down
14 changes: 11 additions & 3 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ pub mod partition;
pub mod ps_masks;
pub mod x64_masks;
pub mod pso;
mod native_mesh;
pub use emit::mesh_passthrough;
pub mod runner;
pub mod ssa;
Expand Down Expand Up @@ -1941,10 +1942,16 @@ pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool {
#[inline]
pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
let _stall = crate::stall::span(crate::stall::StallKind::ShaderTranslation);
translate_inner(code, opt)
translate_inner(code, opt, false)
}

fn translate_inner(code: &[u8], opt: &Options) -> Result<Translation, String> {
pub(super) fn translate_native_mesh(code: &[u8], opt: &Options) -> Result<Translation, String> {
let Mode::Mesh(ms) = &opt.mode else { return Err("not a mesh entry".into()) };
native_mesh::preflight(code, ms, opt.wave64)?;
translate_inner(code, opt, true)
}

fn translate_inner(code: &[u8], opt: &Options, native_mesh: bool) -> Result<Translation, String> {
let program = code;
let normalized;
let opt = if opt.mem_windows & HEAP_WINDOWS != 0 {
Expand Down Expand Up @@ -1997,6 +2004,7 @@ fn translate_inner(code: &[u8], opt: &Options) -> Result<Translation, String> {
}
}
let mut em = emit::Em::new(opt.clone());
em.native_mesh = native_mesh;
em.coherent_mem = matches!(opt.mode, Mode::Compute(_)) && needs_coherent_mem(&insts);
em.configure_round_modes(&insts, branches == 0);
em.writes_lds = emit::lds_order_wanted() && emit::writes_lds(&insts);
Expand Down Expand Up @@ -2069,7 +2077,7 @@ fn translate_inner(code: &[u8], opt: &Options) -> Result<Translation, String> {
// smaller for DXC and the driver on big programs)
emit_structured(&sctx, &mut em, &mut code, 0, u64::MAX, None, 0, &Conts::default(), &BTreeSet::new(), 1, &mut blocks, &mut flags);
if code.len() > STRUCTURED_BYTES_PER_CODE_BYTE * program.len() {
return translate_inner(program, &Options { structured: false, ..opt.clone() });
return translate_inner(program, &Options { structured: false, ..opt.clone() }, native_mesh);
}
} else {
if gs_jump.is_some() && opt.split_wave64 && opt.wave64 {
Expand Down
98 changes: 98 additions & 0 deletions crates/xcl/src/gpu/recomp/native_mesh.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//! Eligibility and output layout for the single-wave native mesh entry.

use std::fmt::Write;

use super::{ranked, MsInterface};
use crate::gpu::rdna2::{decode, field_value};

pub(super) fn preflight(code: &[u8], ms: &MsInterface, wave64: bool) -> Result<(), &'static str> {
if wave64 || ms.threads != 32 || !(1..=32).contains(&ms.max_vertices) || !(1..=32).contains(&ms.max_primitives) {
return Err("requires one wave32 and at most one vertex and primitive per lane");
}
let params = ranked(&ms.outputs, true);
if !ms.outputs.iter().any(|e| e.system_value == 1 && e.mask == 15)
|| params.iter().any(|e| e.component_type != 3 || e.system_value != 0)
|| !fits_output(ms.max_vertices, ms.max_primitives, params.len())
{
return Err("unsupported mesh output signature");
}
let mut offset = 0;
let mut counts = 0;
let mut position = false;
let mut primitive = false;
while offset < code.len() {
let d = decode(&code[offset..], offset as u64).map_err(|_| "cannot decode mesh program")?;
offset += d.len;
if d.inst.name.contains("_STORE")
|| d.inst.name.contains("_ATOMIC")
|| crate::gpu::dxil::kernel::real_lds_access(&d)
{
return Err("mesh program may write shared memory");
}
if crate::gpu::rdna2::vgpr_uses(&d).0.contains(&5) {
return Err("uses the two-pass linear group index");
}
let field = |name| field_value(d.enc, &d.words, name).unwrap_or_default();
if d.inst.name == "S_SENDMSG" && field("SIMM16") & 0xf == 9 {
counts += 1;
}
if d.enc.name == "ENC_EXP" {
match (field("TGT"), field("EN"), field("COMPR")) {
(9, _, 0) | (32..=63, _, 0) => {}
(12, 15, 0) => position = true,
(20, 1, 0) => primitive = true,
_ => return Err("unsupported mesh export"),
}
}
}
if counts != 1 || !position || !primitive {
return Err("requires one allocation request, position and primitive exports");
}
Ok(())
}

fn fits_output(max_vertices: u32, max_primitives: u32, params: usize) -> bool {
// D3D12 rounds the vertex count to a multiple of 32 for the 32 KiB output budget.
// Budget float4 attributes and, conservatively, the uint3 triangle index for each primitive.
const ROWS: usize = 32;
params < ROWS
&& (params + 1) * 16 * max_vertices.next_multiple_of(32) as usize + 12 * max_primitives as usize <= 32 * 1024
}

pub(super) fn entry(h: &mut String, ms: &MsInterface) {
h.push_str("struct XclVert { float4 pos : SV_Position;\n");
for (k, e) in ranked(&ms.outputs, true).into_iter().enumerate() {
let _ = writeln!(h, " float4 p{k} : {};", e.semantic());
}
let _ = writeln!(
h,
"}};\n[outputtopology(\"triangle\")]\n[numthreads(32, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID, out vertices XclVert verts[{}], out indices uint3 tris[{}])\n{{",
ms.max_vertices, ms.max_primitives,
);
let words = ms.vert_dwords();
let _ = writeln!(h, " uint xcl_vertex[{words}];\n [unroll] for (uint i = 0u; i < {words}u; ++i) xcl_vertex[i] = 0u;");
h.push_str(" uint xcl_primitive = 0x80000000u;\n uint xcl_counts = 0u;\n");
}

pub(super) fn finish(h: &mut String, ms: &MsInterface) {
h.push_str(" uint counts = WaveReadLaneAt(xcl_counts, 0u);\n");
let _ = writeln!(h, " uint nv = min(counts & 0x3ffu, {}u);", ms.max_vertices);
let _ = writeln!(h, " uint np = nv == 0u ? 0u : min((counts >> 12) & 0x7ffu, {}u);", ms.max_primitives);
h.push_str(" SetMeshOutputCounts(nv, np);\n if (xcl_slot < nv) {\n XclVert v;\n");
for (k, field) in std::iter::once("pos".to_string()).chain((0..ranked(&ms.outputs, true).len()).map(|k| format!("p{k}"))).enumerate() {
let i = 4 * k;
let _ = writeln!(h, " v.{field} = asfloat(uint4(xcl_vertex[{i}], xcl_vertex[{}], xcl_vertex[{}], xcl_vertex[{}]));", i + 1, i + 2, i + 3);
}
h.push_str(
" verts[xcl_slot] = v;\n }\n if (xcl_slot < np) {\n uint p = xcl_primitive;\n uint3 x = uint3(p & 0x1ffu, (p >> 10) & 0x1ffu, (p >> 20) & 0x1ffu);\n tris[xcl_slot] = select((p >> 31) != 0u || any(x >= nv), uint3(0u, 0u, 0u), x);\n }\n",
);
}

#[cfg(test)]
#[test]
fn native_mesh_output_budget_includes_alignment_and_row_limit() {
assert!(fits_output(32, 32, 31));
assert!(fits_output(33, 1, 30));
assert!(!fits_output(33, 1, 31));
assert!(!fits_output(1, 1, 32));
}
16 changes: 16 additions & 0 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1547,6 +1547,22 @@ pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Resul
})
}

pub(crate) fn console_native_mesh(blob: &[u8]) -> Result<Vec<u8>, String> {
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")?;
let mode = interface(blob, &sh, f).ok_or("unknown mesh interface")?;
let p = f.programs.first().ok_or("FSSM without a program")?;
let code = &f.data[p.offset..p.offset + p.len];
let t = super::translate_native_mesh(code, &Options {
mode, wave64: super::fssm_wave64(f, code), rodata: f.rodata(p),
mem_windows: windows_for_stage(mem_windows(), Stage::Mesh), ..Default::default()
})?;
if !t.complete() || !t.static_samplers.is_empty() {
return Err("native mesh translation or sampler layout unsupported".into());
}
Ok(dxc::compile_cached(&t.hlsl, "main", "ms_6_6")?.0)
}

/// Whether the adapter runs only 32-lane waves (its wave range lacks 64): wave64 compute,
/// mesh and geometry programs then need the split form.
pub fn wave32_only(wave_min: u32, wave_max: u32) -> bool {
Expand Down
Loading
Loading