From 54643d89643ec397c98eada60c7321e02f7aa973 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Lu=C3=ADs=20da=20Silva?= Date: Tue, 24 Nov 2026 20:15:09 -0300 Subject: [PATCH 1/3] GPU: indirect clamp at 2^16 groups, budget by the program's threads, reductions logged Two world runs on an RTX 5070 hung (device removed) in the same indirect dispatch of a loop-free culling program whose arguments another pass writes (meshlet culling; DRED stops at it). The clamp let a dispatch of 2^20 groups through, and the list budget counted every group as 64 threads. - A dispatch now runs at most 2^16 groups (mesh dispatches likewise). - The budget counts each program's own threads per group (numthreads, or a mesh program's lanes), read from its native program once. - Each record the clamp reduces is written to the list's budget buffer (up to 31 a run); before the list's next submission the host logs them at info, "indirect arguments clamped", with the program's hash, the kind and the arguments read and left (the first three per program and kind, then every hundredth, at most 300 lines). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 626b328bd449aa5baff87520a512a6d8de204a67) (cherry picked from commit bface5a143aeb5a50b9e6ed58e72d22ae4e8c3a4) --- crates/victory-gpu/src/draw.rs | 10 ++- crates/victory-gpu/src/host.rs | 16 ++-- crates/victory-gpu/src/indirect.rs | 130 +++++++++++++++++++++++++---- crates/victory-gpu/src/pipeline.rs | 45 ++++++++++ 4 files changed, 178 insertions(+), 23 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b9c352e48d..3704aafde6 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1621,7 +1621,15 @@ impl State { s.refresh(list, *at, 4); } // Bounded first: the clamp binds a compute pipeline of its own. - if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { + let (threads, hash) = crate::pipeline::group_of(self.pipeline as This); + let tag = crate::indirect::tag(&hash); + if !crate::indirect::bound( + list, + &args.buffer, + args.gpu(arguments), + (kind, stride, max), + (threads, tag), + ) { why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 698f87b2de..945e4166ae 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1921,7 +1921,8 @@ impl HostList { let (buffer, data) = self .budget .get_or_init(|| { - let (b, d) = host()?.shared_buffer(256)?; + // The budget, then the log of reduced records (`crate::indirect`). + let (b, d) = host()?.shared_buffer(1024)?; Some((b, d as usize)) }) .as_ref()?; @@ -1929,10 +1930,15 @@ impl HostList { if !deferred.budget_zeroed { deferred.budget_zeroed = true; let at = *data; - // SAFETY: the list's own mapped word, written before it runs. - deferred - .copies - .push(Step::Host(Box::new(move || unsafe { (at as *mut u32).write_volatile(0) }))); + // SAFETY: the list's own mapped words, read (what its last run + // logged) and zeroed before it runs. + deferred.copies.push(Step::Host(Box::new(move || unsafe { + let words = std::slice::from_raw_parts(at as *const u32, 256); + let read: Vec = words.iter().map(|w| std::ptr::read_volatile(w)).collect(); + crate::indirect::take_log(&read); + (at as *mut u32).write_volatile(0); + (at as *mut u32).add(1).write_volatile(0); + }))); } // SAFETY: a live buffer. Some(unsafe { buffer.GetGPUVirtualAddress() }) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 050dd867fc..e6dd86b487 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -12,9 +12,13 @@ //! either. //! //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 -//! groups per dimension and 2^20 per dispatch, one-dimensional mesh +//! groups per dimension and 2^16 per dispatch, one-dimensional mesh //! dispatches, the budget) cut legitimate work beyond them; raise them if -//! the title needs more. +//! the title needs more. A world run on an RTX 5070 hung in an indirect +//! dispatch of a loop-free culling program whose arguments another pass +//! writes: 2^20 groups of a heavy program outlast the host's timeout in +//! one dispatch. The budget counts each program's own threads per group, +//! and records the clamp reduces are logged (`take_log`). use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::ID3DBlob; @@ -24,40 +28,63 @@ use windows::core::s; use crate::host::{HostList, host, transition}; const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)" -cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; +#define RS "RootConstants(num32BitConstants=8, b0), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { + uint kind; uint stride; uint records; uint threads; uint tag; uint3 unused; +}; RWByteAddressBuffer args : register(u0); -// The list's work so far (vertex instances, threads): past the budget, -// records run empty. +// The list's work so far (vertex instances, threads), at byte 0: past the +// budget, records run empty. At byte 4 the records this list's clamps +// reduced, the first LOGGED of them from byte 16 on (8 words each: tag, +// kind, the arguments read, those left), read back by the host. RWByteAddressBuffer budget : register(u1); static const uint BUDGET = 1u << 27; // Groups of one dispatch; more run empty. -static const uint GROUPS = 1u << 20; +static const uint GROUPS = 1u << 16; +static const uint LOGGED = 31; +void note(uint3 raw, uint3 left) { + if (all(raw == left)) return; + uint n; + budget.InterlockedAdd(4, 1, n); + if (n < LOGGED) { + uint at = 16 + n * 32; + budget.Store4(at, uint4(tag, kind, raw.x, raw.y)); + budget.Store4(at + 16, uint4(raw.z, left.x, left.y, left.z)); + } +} [RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { if (id.x >= records) return; uint at = id.x * stride; uint cost; + uint3 raw; + uint3 left; if (kind <= 1) { // Draws: vertex or index count, then instances. - uint count = min(args.Load(at), 1u << 24); - uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); + raw = uint3(args.Load2(at), 0); + uint count = min(raw.x, 1u << 24); + uint instances = min(raw.y, (1u << 26) / max(count, 1u)); cost = count * instances; - args.Store2(at, uint2(count, instances)); + left = uint3(count, instances, 0); + args.Store2(at, left.xy); } else if (kind == 2) { - uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); + raw = args.Load3(at); + uint3 g = min(raw, uint3(65535, 65535, 65535)); // x * y fits 32 bits; the whole count may not. if (g.z != 0 && g.x * g.y > GROUPS / g.z) { g = uint3(0, 0, 0); } - cost = g.x * g.y * g.z * 64; + // Threads per group as the program has them. + cost = g.x * g.y * g.z * max(threads, 1u); + left = g; args.Store3(at, g); } else { // Mesh dispatches: the console's are one-dimensional. - uint3 g = args.Load3(at); - g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); - cost = g.x * g.y * g.z * 128; + raw = args.Load3(at); + uint3 g = uint3(min(raw.x, GROUPS), min(raw.y, 1u), min(raw.z, 1u)); + cost = g.x * g.y * g.z * max(threads, 1u); + left = g; args.Store3(at, g); } uint before; @@ -65,7 +92,9 @@ void main(uint3 id : SV_DispatchThreadID) { if (before >= BUDGET || before + cost > BUDGET) { // Draws keep their layout with no vertices; groups become zero. args.Store(at, 0); + left.x = 0; } + note(raw, left); } "#; @@ -149,6 +178,7 @@ pub(crate) fn bound( buffer: &ID3D12Resource, gpu: u64, (kind, stride, records): (u32, u32, u32), + (threads, tag): (u32, u32), ) -> bool { let (Some(c), Some(budget)) = (clamp(), list.budget()) else { return false; @@ -157,7 +187,14 @@ pub(crate) fn bound( return false; } let l = &list.list; - let constants = [kind, stride, records, 0]; + // Groups of an unknown size count as the console's wave (64) or a + // mesh group (128). + let threads = match (threads, kind) { + (0, 2) => 64, + (0, _) => 128, + (n, _) => n, + }; + let constants = [kind, stride, records, threads, tag, 0, 0, 0]; // SAFETY: an open list; our root signature, pipeline and a live buffer // the caller's list holds. unsafe { @@ -165,7 +202,7 @@ pub(crate) fn bound( l.ResourceBarrier(&[uav_barrier()]); l.SetComputeRootSignature(&c.root); l.SetPipelineState(&c.pso); - l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + l.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); l.SetComputeRootUnorderedAccessView(1, gpu); l.SetComputeRootUnorderedAccessView(2, budget); l.Dispatch(records.div_ceil(64), 1, 1); @@ -207,6 +244,65 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { } } +/// Program hashes by the tag the clamp logs them under. +static TAGS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// The tag of the program `hash` (its index among those seen). +pub(crate) fn tag(hash: &str) -> u32 { + let mut tags = TAGS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(i) = tags.iter().position(|h| h == hash) { + return i as u32; + } + tags.push(hash.to_owned()); + tags.len() as u32 - 1 +} + +/// Logs the records a list's clamps reduced in its last run, from its +/// budget buffer's words (`words`, read before they are zeroed): the first +/// three per program and kind, then every hundredth, at most 300 lines. +pub(crate) fn take_log(words: &[u32]) { + use std::sync::atomic::{AtomicU32, Ordering}; + static LINES: AtomicU32 = AtomicU32::new(0); + static SEEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let Some(&reduced) = words.get(1) else { return }; + if reduced == 0 { + return; + } + let tags = TAGS.lock().unwrap_or_else(|e| e.into_inner()).clone(); + for n in 0..(reduced as usize).min(31) { + let Some(r) = words.get(4 + n * 8..4 + n * 8 + 8) else { + break; + }; + let (tag, kind) = (r[0], r[1]); + { + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let i = match seen.iter().position(|e| e.0 == tag && e.1 == kind) { + Some(i) => i, + None => { + seen.push((tag, kind, 0)); + seen.len() - 1 + } + }; + seen[i].2 += 1; + let count = seen[i].2; + if count > 3 && !count.is_multiple_of(100) { + continue; + } + } + if LINES.fetch_add(1, Ordering::Relaxed) >= 300 { + return; + } + tracing::info!( + shader = tags.get(tag as usize).map_or("?", String::as_str), + kind, + read = ?[r[2], r[3], r[4]], + left = ?[r[5], r[6], r[7]], + reduced_in_list = reduced, + "indirect arguments clamped" + ); + } +} + #[cfg(test)] mod tests { /// The clamp compiles with the system's compiler and the host takes it. diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 6b47927b02..fad958d355 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -67,6 +67,9 @@ pub(crate) struct Shader { /// (diagnostics: `VICTORY_SKIP_WAVE64`). #[cfg(all(windows, feature = "diagnostics"))] wave64: OnceLock, + /// Its native program's thread-group size in threads (0: unknown). + #[cfg(windows)] + group: OnceLock, } impl std::fmt::Debug for Shader { @@ -99,6 +102,8 @@ impl Shader { translated: OnceLock::new(), #[cfg(all(windows, feature = "diagnostics"))] wave64: OnceLock::new(), + #[cfg(windows)] + group: OnceLock::new(), } } } @@ -215,6 +220,46 @@ fn with_resources( Ok(Translated { host, used }) } +#[cfg(windows)] +impl Shader { + /// Its native program's thread-group size in threads: `numthreads` of a + /// compute program, the lanes of a mesh program's group; 0 if neither. + fn group(&self) -> u32 { + *self.group.get_or_init(|| { + use victory_shader::native::StageIo; + victory_shader::Container::parse(&self.container) + .ok() + .and_then(|c| { + c.part(victory_shader::FourCC::DXIL) + .map(|p| p.data.to_vec()) + }) + .and_then(|d| victory_shader::native::native_programs(&d).ok()) + .and_then(|ps| { + ps.iter().find_map(|p| match &p.io { + StageIo::Cs(cs) => Some(cs.threads.iter().product::()), + StageIo::Ms(ms) => Some(ms.threads), + _ => None, + }) + }) + .unwrap_or(0) + }) + } +} + +/// The thread-group size in threads of the compute or mesh program of the +/// pipeline `this` (0 if unknown), and that program's hash. +#[cfg(windows)] +pub(crate) fn group_of(this: This) -> (u32, String) { + if this.is_null() { + return (0, String::new()); + } + pipeline(this) + .shaders + .iter() + .find(|s| matches!(s.stage, "compute" | "mesh")) + .map_or((0, String::new()), |s| (s.group(), s.hash.clone())) +} + #[repr(C)] struct Pipeline { object: Object, From 4c3c59209dede0cbdb19bafb41b6e843db6949e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Lu=C3=ADs=20da=20Silva?= Date: Tue, 24 Nov 2026 21:08:46 -0300 Subject: [PATCH 2/3] Shaders, GPU: one-dimensional dispatches of more than 65,535 groups run folded The console runs more than 65,535 groups along x; the host does not, and the indirect clamp cut such dispatches to 65,535 (in the world on an RTX 5070: the indirect diffuse lighting's final gather asks for about 115,000, so 43% of it never ran). Such a dispatch (y and z of 1) now runs folded: rows of 65,535 groups along z, and a second dispatch for the rest. A compute shader that reads its group id reads a fold root constant (b1 in the user-data space, one dword; every compute root signature has it, 0 unless folded): non-zero, it is the first group the dispatch runs plus one, the group is that plus x plus z rows, and z reads 0 (`GROUP_FOLD_ROW`). - Direct dispatches fold on the CPU (two Dispatch calls with the constant). - Indirect ones (one uncounted record) fold in the argument clamp: it writes the count and the records (constant, then x, y, z) to a region of the list's fold buffer, executed with a command signature of the constant and a dispatch. Up to 2^22 groups fold; the budget still bounds the work. - The test host's compute root signatures have the constant too (set to 0 unless a dispatch's roots set it). Test: emit::fold_tests on the RTX 5070 and WARP (groups as given, a folded remainder from group 100, and two rows: groups 0, 1, 65535, 65536). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 365802a8f25bdc45cb1a8eb523d8e9b6fdf6cba4) --- crates/victory-gpu/src/draw.rs | 120 ++++++++++- crates/victory-gpu/src/host.rs | 31 +++ crates/victory-gpu/src/indirect.rs | 57 +++++- crates/victory-gpu/src/pipeline/host.rs | 18 ++ crates/victory-shader/src/emit/fold_tests.rs | 205 +++++++++++++++++++ crates/victory-shader/src/emit/host.rs | 43 +++- crates/victory-shader/src/emit/lower.rs | 42 +++- crates/victory-shader/src/emit/mod.rs | 6 +- crates/victory-shader/src/emit/shader.rs | 63 ++++++ 9 files changed, 567 insertions(+), 18 deletions(-) create mode 100644 crates/victory-shader/src/emit/fold_tests.rs diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 3704aafde6..3fd95f674a 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -677,6 +677,11 @@ impl State { } } } + // Not folded unless the dispatch says so. + if let Some(param) = stage.fold { + // SAFETY: an open list; the parameter is one root constant. + unsafe { l.SetComputeRoot32BitConstant(param, 0, 0) }; + } for (views, kind) in [(&stage.root_cbvs, 0), (&stage.root_srvs, 1), (&stage.root_uavs, 2)] { for &(slot, param) in views { if kind == 1 && slot == victory_shader::emit::VIEW_STRIDES { @@ -951,8 +956,27 @@ impl State { list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); #[cfg(feature = "diagnostics")] self.probe_small(list, true); - // SAFETY: an open list with everything set. - unsafe { list.list.Dispatch(x, y, z) }; + let row = victory_shader::emit::GROUP_FOLD_ROW; + match p.stages.first().and_then(|s| s.fold) { + // More groups than the host runs along x: in rows along z, + // then the rest (`GROUP_FOLD_ROW`). + Some(param) if x > row && y == 1 && z == 1 => { + let (rows, rest) = (x / row, x % row); + // SAFETY: an open list with everything set; the parameter + // is one root constant. + unsafe { + list.list.SetComputeRoot32BitConstant(param, 1, 0); + list.list.Dispatch(row, 1, rows); + if rest != 0 { + list.list.SetComputeRoot32BitConstant(param, rows * row + 1, 0); + list.list.Dispatch(rest, 1, 1); + } + list.list.SetComputeRoot32BitConstant(param, 0, 0); + } + } + // SAFETY: an open list with everything set. + _ => unsafe { list.list.Dispatch(x, y, z) }, + } #[cfg(feature = "diagnostics")] self.probe_written(list); DISPATCHED.fetch_add(1, Ordering::Relaxed); @@ -1620,6 +1644,18 @@ impl State { if let Some((s, at)) = &counter { s.refresh(list, *at, 4); } + // One uncounted dispatch of a compute program may run folded + // (`GROUP_FOLD_ROW`): the clamp writes its records to a region of + // the list's fold buffer, with the fold root constant. + let folded = (kind == DISPATCH && count.is_none() && max == 1) + .then(|| crate::pipeline::host_pipeline(self.pipeline as This)) + .flatten() + .filter(|p| p.compute) + .and_then(|p| { + let param = p.stages.first()?.fold?; + let signature = fold_signature(&p.root, param)?; + Some((list.fold_region()?, signature)) + }); // Bounded first: the clamp binds a compute pipeline of its own. let (threads, hash) = crate::pipeline::group_of(self.pipeline as This); let tag = crate::indirect::tag(&hash); @@ -1629,6 +1665,7 @@ impl State { args.gpu(arguments), (kind, stride, max), (threads, tag), + folded.as_ref().map(|((buffer, gpu, _), _)| (buffer, *gpu)), ) { why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; @@ -1651,6 +1688,9 @@ impl State { }; if !ran { crate::indirect::done(list, &args.buffer); + if let Some(((buffer, ..), _)) = &folded { + crate::indirect::done_fold(list, buffer); + } #[cfg(feature = "diagnostics")] match crate::pipeline::host_pipeline(self.pipeline as This) { None => { @@ -1674,17 +1714,26 @@ impl State { ) }); // SAFETY: an open list with everything set; the buffers are host - // copies the list keeps alive (refresh), the signature is cached. + // copies the list keeps alive (refresh) or its own fold buffer, the + // signatures are cached. unsafe { - list.list.ExecuteIndirect( - &signature, - max, - &args.buffer, - args.offset(arguments), - counter.as_ref().map(|(s, _)| &s.buffer), - counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), - ) + match &folded { + Some(((buffer, _, offset), signature)) => { + list.list.ExecuteIndirect(signature, 2, buffer, offset + 16, buffer, *offset) + } + None => list.list.ExecuteIndirect( + &signature, + max, + &args.buffer, + args.offset(arguments), + counter.as_ref().map(|(s, _)| &s.buffer), + counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), + ), + } }; + if let Some(((buffer, ..), _)) = &folded { + crate::indirect::done_fold(list, buffer); + } // A listed frame: what the records held (after the clamp). #[cfg(feature = "diagnostics")] if crate::capture::dump_on() { @@ -1702,6 +1751,55 @@ impl State { } } +/// The host command signature of folded dispatches for the root signature +/// `root`, whose root parameter `param` is the fold constant: records of +/// that constant and a dispatch, 16 bytes apart. Made once per root +/// signature (kept alive here). +fn fold_signature(root: &ID3D12RootSignature, param: u32) -> Option { + static MADE: std::sync::Mutex> = + std::sync::Mutex::new(Vec::new()); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((.., s)) = made.iter().find(|(r, p, _)| r == root && *p == param) { + return Some(s.clone()); + } + let arguments = [ + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, + Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { + Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { + RootParameterIndex: param, + DestOffsetIn32BitValues: 0, + Num32BitValuesToSet: 1, + }, + }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + ..Default::default() + }, + ]; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 16, + NumArgumentDescs: 2, + pArgumentDescs: arguments.as_ptr(), + NodeMask: 0, + }; + let mut signature: Option = None; + // SAFETY: a description of two arguments for a live root signature. + let result = unsafe { + crate::host::host()? + .device + .CreateCommandSignature(&desc, root, &mut signature) + }; + if let Err(e) = result { + once!(error = %e, param, "host command signature for folded dispatches refused"); + return None; + } + let signature = signature?; + made.push((root.clone(), param, signature.clone())); + Some(signature) +} + /// The host command signature for one argument of `kind` with records /// `stride` bytes apart (no root arguments, so no root signature), made /// once. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 945e4166ae..1b839e4d55 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -610,6 +610,12 @@ mod tests { } } +/// Bytes of a list's fold buffer per indirect execution: the record count, +/// then up to two records of a root constant and three group counts. +pub(crate) const FOLD_REGION: u32 = 64; +/// Fold regions per list (folded indirect dispatches between resets). +const FOLD_REGIONS: u32 = 1024; + /// A host command list and its allocator, always used together. pub(crate) struct HostList { allocator: ID3D12CommandAllocator, @@ -643,6 +649,9 @@ pub(crate) struct HostList { /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted. budget: OnceLock>, + /// Where the argument clamp writes the records of folded dispatches + /// (`crate::indirect`), [`FOLD_REGION`] bytes per execution. + fold: OnceLock>, /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] @@ -836,6 +845,8 @@ struct Deferred { writes: Vec<(usize, crate::queue::Written, usize)>, /// Whether a step zeroes the indirect-work budget. budget_zeroed: bool, + /// Fold regions taken since the reset ([`HostList::fold_region`]). + fold_regions: u32, /// Work done once the list has run, before the bottom-of-pipe writes /// (title memory shaders wrote at addresses they computed goes back). after: Vec>, @@ -951,6 +962,7 @@ impl Host { pipelines: Mutex::default(), id, budget: OnceLock::new(), + fold: OnceLock::new(), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] @@ -1944,6 +1956,25 @@ impl HostList { Some(unsafe { buffer.GetGPUVirtualAddress() }) } + /// A region of the list's fold buffer for one indirect execution until + /// the list is reset: the buffer, the region's host address and its + /// offset; none when the list has used them all. + pub(crate) fn fold_region(&self) -> Option<(ID3D12Resource, u64, u64)> { + let buffer = self + .fold + .get_or_init(|| Some(host()?.shared_buffer(u64::from(FOLD_REGION * FOLD_REGIONS))?.0)) + .as_ref()?; + let mut deferred = self.deferred(); + if deferred.fold_regions >= FOLD_REGIONS { + return None; + } + let offset = u64::from(deferred.fold_regions * FOLD_REGION); + deferred.fold_regions += 1; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + offset; + Some((buffer.clone(), gpu, offset)) + } + /// Keeps `object` alive until the list is reset. pub(crate) fn keep(&self, object: &impl Interface) { if let Ok(object) = object.cast::() { diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index e6dd86b487..7881b6c65e 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -28,9 +28,9 @@ use windows::core::s; use crate::host::{HostList, host, transition}; const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=8, b0), UAV(u0), UAV(u1)" +#define RS "RootConstants(num32BitConstants=8, b0), UAV(u0), UAV(u1), UAV(u2)" cbuffer Record : register(b0) { - uint kind; uint stride; uint records; uint threads; uint tag; uint3 unused; + uint kind; uint stride; uint records; uint threads; uint tag; uint folding; uint2 unused; }; RWByteAddressBuffer args : register(u0); // The list's work so far (vertex instances, threads), at byte 0: past the @@ -41,6 +41,14 @@ RWByteAddressBuffer budget : register(u1); static const uint BUDGET = 1u << 27; // Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 16; +// A one-record dispatch run folded (`folding`): the record count at byte 0 +// of `fold`, then up to two records (the fold root constant, then x, y, z) +// from byte 16 on. Up to FOLDED groups of a one-dimensional dispatch run, +// as rows of ROW groups along z and one more dispatch for the rest (the +// translated shader's group is the constant minus one plus x plus z rows). +RWByteAddressBuffer fold : register(u2); +static const uint ROW = 65535; +static const uint FOLDED = 1u << 22; static const uint LOGGED = 31; void note(uint3 raw, uint3 left) { if (all(raw == left)) return; @@ -68,6 +76,34 @@ void main(uint3 id : SV_DispatchThreadID) { cost = count * instances; left = uint3(count, instances, 0); args.Store2(at, left.xy); + } else if (kind == 2 && folding != 0) { + raw = args.Load3(at); + uint count = 1; + if (raw.y == 1 && raw.z == 1 && raw.x > ROW && raw.x <= FOLDED) { + uint rows = raw.x / ROW; + uint rest = raw.x - rows * ROW; + fold.Store4(16, uint4(1, ROW, 1, rows)); + fold.Store4(32, uint4(rows * ROW + 1, rest, 1, 1)); + count = rest != 0 ? 2 : 1; + left = raw; + } else { + uint3 g = min(raw, uint3(65535, 65535, 65535)); + if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + g = uint3(0, 0, 0); + } + fold.Store4(16, uint4(0, g)); + left = g; + } + cost = left.x * left.y * left.z * max(threads, 1u); + uint before; + budget.InterlockedAdd(0, cost, before); + if (before >= BUDGET || before + cost > BUDGET) { + count = 0; + left.x = 0; + } + fold.Store(0, count); + note(raw, left); + return; } else if (kind == 2) { raw = args.Load3(at); uint3 g = min(raw, uint3(65535, 65535, 65535)); @@ -179,6 +215,7 @@ pub(crate) fn bound( gpu: u64, (kind, stride, records): (u32, u32, u32), (threads, tag): (u32, u32), + fold: Option<(&ID3D12Resource, u64)>, ) -> bool { let (Some(c), Some(budget)) = (clamp(), list.budget()) else { return false; @@ -194,7 +231,7 @@ pub(crate) fn bound( (0, _) => 128, (n, _) => n, }; - let constants = [kind, stride, records, threads, tag, 0, 0, 0]; + let constants = [kind, stride, records, threads, tag, u32::from(fold.is_some()), 0, 0]; // SAFETY: an open list; our root signature, pipeline and a live buffer // the caller's list holds. unsafe { @@ -205,6 +242,8 @@ pub(crate) fn bound( l.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); l.SetComputeRootUnorderedAccessView(1, gpu); l.SetComputeRootUnorderedAccessView(2, budget); + // Unused unless folding: the budget word stands in. + l.SetComputeRootUnorderedAccessView(3, fold.map_or(budget, |f| f.1)); l.Dispatch(records.div_ceil(64), 1, 1); l.ResourceBarrier(&[ uav_barrier(), @@ -214,6 +253,13 @@ pub(crate) fn bound( D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, ), ]); + if let Some((f, _)) = fold { + l.ResourceBarrier(&[transition( + f, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + )]); + } } true } @@ -244,6 +290,11 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { } } +/// [`done`] for a fold buffer [`bound`] wrote records to. +pub(crate) fn done_fold(list: &HostList, buffer: &ID3D12Resource) { + done(list, buffer); +} + /// Program hashes by the tag the clamp logs them under. static TAGS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 877c1ebaa0..494326afa5 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -263,6 +263,9 @@ pub(crate) struct Stage { pub(crate) memory_dirty: Option, /// Our root parameter of the heap's view addresses (`crate::memory`). pub(crate) view_addresses: Option, + /// Our root parameter of a compute stage's group fold (one root + /// constant, `GROUP_FOLD_ROW`): 0 unless a dispatch runs folded. + pub(crate) fold: Option, } impl Stage { @@ -405,7 +408,22 @@ impl HostPipeline { memory: None, memory_dirty: None, view_addresses: None, + fold: None, }; + if compute.is_some() { + stage.fold = Some(params.len() as u32); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 1, + RegisterSpace: USER_DATA_SPACE, + Num32BitValues: 1, + }, + }, + ShaderVisibility: visibility, + }); + } let dwords = t.user_data_dwords(); if dwords > 0 { stage.user_data = Some((params.len() as u32, dwords)); diff --git a/crates/victory-shader/src/emit/fold_tests.rs b/crates/victory-shader/src/emit/fold_tests.rs new file mode 100644 index 0000000000..2a7521d022 --- /dev/null +++ b/crates/victory-shader/src/emit/fold_tests.rs @@ -0,0 +1,205 @@ +//! End-to-end test of folded dispatches (`GROUP_FOLD_ROW`): a synthetic +//! GFX10 compute program that stores its group id, lowered to DXIL, +//! validated by `dxil.dll` when present, and run on the host GPU and WARP +//! with the fold root constant the host sets. + +use super::host::{Dispatch, Host, Root, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +/// One thread per group, the table of views at s0 (a raw UAV at entry 0), +/// group x in s1 and group z in s2. Each group stores its x and z at +/// entry `(x + (x >> 16) * 2) & 7` (two dwords): distinct for the groups +/// the cases below run. +const STORE_GROUP_ID: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0000, // s_load_dwordx4 s[40:43], s[4:5], 0x0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x7E02_0201, // v_mov_b32 v1, s1 + 0x7E04_0202, // v_mov_b32 v2, s2 + 0x2C08_0290, // v_lshrrev_b32 v4, 16, v1 + 0xD746_0003, + 0x0405_0304, // v_lshl_add_u32 v3, v4, 1, v1 + 0x3606_0687, // v_and_b32 v3, 7, v3 + 0x3406_0683, // v_lshlrev_b32 v3, 3, v3 + 0xE070_1000, + 0x800A_0103, // buffer_store_dword v1, v3, s[40:43], 0 offen + 0xE070_1004, + 0x800A_0203, // buffer_store_dword v2, v3, s[40:43], 0 offen offset:4 + 0xBF81_0000, // s_endpgm +]; + +fn build() -> HostShader { + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }], + // One user SGPR, then group x (bit 7) and group z (bit 9). + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 1 | 1 << 7 | 1 << 9, + threads: [1, 1, 1], + }), + code: STORE_GROUP_ID + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + memory: lowered.memory, + memory_writes: lowered.memory_writes, + view_addresses: lowered.view_addresses, + heap: lowered.heap, + heap_writes: lowered.heap_writes, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } else { + eprintln!("no dxil.dll; validation skipped"); + } + shader +} + +/// Groups dispatched, the fold constant, and the (x, z) each entry holds +/// after. +type Case = ([u32; 3], u32, [(u32, u32); 8]); + +#[test] +fn folded_dispatches_number_groups_as_the_console() { + let shader = build(); + // (groups, fold) and what each entry holds after: (x, z) per entry. + let cases: [Case; 3] = [ + // As given: groups 0..3. + ( + [4, 1, 1], + 0, + [ + (0, 0), + (1, 0), + (2, 0), + (3, 0), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + ], + ), + // The rest of a folded dispatch from group 100 on: groups 100..103. + ( + [4, 1, 1], + 101, + [ + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (100, 0), + (101, 0), + (102, 0), + (103, 0), + ], + ), + // Two rows: groups 0, 1, 65535 and 65536, z read as 0. + ( + [2, 1, 2], + 1, + [ + (0, 0), + (1, 0), + (65536, 0), + (0, 0), + (0, 0), + (0, 0), + (0, 0), + (65535, 0), + ], + ), + ]; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + let fold = Host::fold_param(&root).expect("a compute root signature has the fold"); + for (groups, value, want) in cases { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + assert_eq!(u.root, RootType::Table, "{u:?}"); + ud[u.index as usize] = 0; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + (fold, Root::Constants(vec![value])), + ], + views: &[View::RawUav(16)], + samplers: &[], + groups, + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + let got: Vec<(u32, u32)> = out[0].chunks(2).map(|c| (c[0], c[1])).collect(); + assert_eq!(got, want, "{label}: groups {groups:?}, fold {value}"); + } + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index b0d2bf3885..f48d0b85b1 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -131,6 +131,8 @@ fn default_adapter_is_warp() -> bool { /// Serializes WARP (`d3d10warp.dll`) operations across threads: concurrent /// WARP pipeline compiles / dispatches crash with `0xC0000005` on Windows 11. static WARP_LOCK: Mutex<()> = Mutex::new(()); +/// Root signatures made with a group fold parameter, and its index. +static FOLDS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); impl Host { fn lock_warp(&self) -> Option> { @@ -248,6 +250,21 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } + // A compute stage's group fold (`GROUP_FOLD_ROW`), last. + let fold = stages.iter().any(|(s, _)| s.stage == crate::native::HwStage::Cs).then(|| { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 1, + RegisterSpace: super::USER_DATA_SPACE, + Num32BitValues: 1, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + params.len() as u32 - 1 + }); let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { @@ -295,7 +312,14 @@ impl Host { let bytes = unsafe { std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()) }; - self.root_signature_bytes(bytes) + let made = self.root_signature_bytes(bytes)?; + if let Some(param) = fold { + FOLDS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((made.as_raw() as usize, param)); + } + Ok(made) } /// Creates a root signature from serialized root signature bytes (or a @@ -306,6 +330,20 @@ impl Host { unsafe { self.device.CreateRootSignature(0, bytes) }.map_err(err) } + /// The root parameter of the group fold in a root signature + /// [`Host::root_signature_for`] made for a compute stage: 0 unless a + /// dispatch's roots set it. + pub fn fold_param(root: &ID3D12RootSignature) -> Option { + let key = root.as_raw() as usize; + FOLDS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .rev() + .find(|f| f.0 == key) + .map(|f| f.1) + } + /// A compute pipeline; user data is root parameter 0. pub fn compute_pipeline( &self, @@ -1808,6 +1846,9 @@ impl Host { } list.SetDescriptorHeaps(&[Some(views.clone()), Some(samplers.clone())]); list.SetComputeRootSignature(root); + if let Some(param) = Host::fold_param(root) { + list.SetComputeRoot32BitConstant(param, 0, 0); + } for (param, arg) in &d.roots { match arg { Root::Constants(data) => list.SetComputeRoot32BitConstants( diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 68e78c47bd..2c82613873 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1456,7 +1456,7 @@ impl<'a> Lower<'a> { // host's value can be. Input::FrontFace => (13, 0), Input::ThreadIdInGroup(c) => return self.thread_id(c), - Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c), + Input::GroupId(c) => return self.group_id(c), Input::GroupInfo => return Val::Missing("the thread-group info SGPR"), Input::MeshGroup => { let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else { @@ -1521,6 +1521,46 @@ impl<'a> Lower<'a> { self.load_input(id, col) } + /// Component `c` of a compute program's group id, read in the entry + /// block, as the console numbers it in a folded dispatch too + /// ([`super::shader::GROUP_FOLD_ROW`]). + fn group_id(&mut self, c: u8) -> Val { + let Val::I32(g) = self.compute_id("groupId.i32", 94, c) else { + unreachable!() + }; + if c == 1 || self.s.threads.is_none() || self.s.mesh.is_some() { + return Val::I32(g); + } + let e = self.s.entry; + let h = self.s.fold_handle(); + let row = self.s.m.i32(0); + let r = self.s.op( + e, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, row], + ); + let fold = self.s.m.extract(e, r, 0); + let zero = self.s.m.i32(0); + let folded = self.s.m.cmp(e, pred::NE, fold, zero); + if c == 2 { + return Val::I32(self.s.m.select(e, folded, zero, g)); + } + // First group plus x plus z rows. + let Val::I32(z) = self.compute_id("groupId.i32", 94, 2) else { + unreachable!() + }; + let one = self.s.m.i32(1); + let first = self.s.m.bin(e, Bin::Sub, fold, one); + let row = self.s.m.i32(super::shader::GROUP_FOLD_ROW); + let rows = self.s.m.bin(e, Bin::Mul, z, row); + let x = self.s.m.bin(e, Bin::Add, first, g); + let x = self.s.m.bin(e, Bin::Add, x, rows); + Val::I32(self.s.m.select(e, folded, x, g)) + } + /// A component of a compute thread or group id, read in the entry block. fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val { let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c))); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index acd1740952..e63e24e3da 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -194,6 +194,8 @@ pub mod validator; #[cfg(all(test, windows))] mod valu_tests; #[cfg(all(test, windows))] +mod fold_tests; +#[cfg(all(test, windows))] mod waterfall_tests; mod wave; @@ -203,8 +205,8 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; pub use shader::{ - HEAP_SAMPLERS, HEAP_VIEWS, MEMORY_SPACE, NULL_BUFFER_VIEW, ROOT_CBV_SPACE, SAMPLER_SPACE, - USER_DATA_SPACE, VIEW_STRIDES, + GROUP_FOLD_ROW, HEAP_SAMPLERS, HEAP_VIEWS, MEMORY_SPACE, NULL_BUFFER_VIEW, ROOT_CBV_SPACE, + SAMPLER_SPACE, USER_DATA_SPACE, VIEW_STRIDES, }; /// The loop limit without an override: 2^20. diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 51e170c21c..b448e20fc4 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -7,6 +7,17 @@ use super::container::{self, Binding, Psv, SigElement}; /// Where the shader reads its user data: `b0` in this space. pub const USER_DATA_SPACE: u32 = 0; +/// Groups per row of a folded dispatch. The host runs at most 65,535 +/// groups per dimension, the console more: a one-dimensional dispatch of +/// more groups runs folded, as rows of this many groups along z, the +/// groups past the last full row in a second dispatch. Compute shaders +/// that read their group id read the fold from `b1` in +/// [`USER_DATA_SPACE`] (one dword; every compute root signature has it): 0 +/// for a dispatch as given, else the first group the dispatch runs plus +/// one; their group is then that first group plus x plus z times this, +/// and z is 0. +pub const GROUP_FOLD_ROW: u32 = 65535; + /// Where immediate samplers are bound: `s` in this space. pub const SAMPLER_SPACE: u32 = 0; /// Where root CBVs and SRVs are bound: `b` and @@ -94,6 +105,9 @@ pub(crate) struct Shader { pub root_srvs: Vec<(u8, V)>, /// Root UAVs (raw buffers) read or written, likewise. pub root_uavs: Vec<(u8, V)>, + /// The group fold's handle (`b1` in [`USER_DATA_SPACE`]), once read: + /// see [`GROUP_FOLD_ROW`]. + pub fold: Option, /// The title-memory page table's handle, once read. pub memory: Option, /// The written-pages bitmap's handle, once title memory is written. @@ -158,6 +172,7 @@ impl Shader { root_cbvs: Vec::new(), root_srvs: Vec::new(), root_uavs: Vec::new(), + fold: None, memory: None, memory_dirty: None, view_addresses: None, @@ -250,6 +265,30 @@ impl Shader { self.annotate(block, h, 13, u32::MAX) } + /// The handle of the group fold constant (`b1` in [`USER_DATA_SPACE`], + /// one dword), made in the entry block. + pub fn fold_handle(&mut self) -> V { + if let Some(h) = self.fold { + return h; + } + let one = self.m.i32(1); + let bind = [one, one, self.m.i32(USER_DATA_SPACE), self.m.i8(2)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let block = self.entry; + let (i, f) = (self.m.i32(1), self.m.bool(false)); + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, i, f], + ); + let h = self.annotate(block, h, 13, 16); + self.fold = Some(h); + h + } + /// The handle of the root CBV of root parameter `slot`, made in the /// entry block. pub fn root_cbv_handle(&mut self, slot: u8) -> V { @@ -482,6 +521,7 @@ impl Shader { s.m.md_value(c) }; if self.user_data > 0 + || self.fold.is_some() || self.samplers > 0 || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() @@ -516,6 +556,29 @@ impl Shader { dxil_kind: 13, }); } + if self.fold.is_some() { + let arr = self.m.array(4, self.t.i32); + let ty = self.m.named_struct("GroupFold", vec![arr]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let ops = vec![ + Some(i32c(&mut self, cbv_list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, USER_DATA_SPACE)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 16)), + None, + ]; + cbv_list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 2, + space: USER_DATA_SPACE, + register: 1, + dxil_kind: 13, + }); + } let blob = self.m.array(16384, self.t.i32); let ty = self.m.named_struct("RootCbv", vec![blob]); let p = self.m.ptr(ty); From 1c558d9b19faedd6a776a839e83dd448bbc45e76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Lu=C3=ADs=20da=20Silva?= Date: Tue, 24 Nov 2026 21:23:55 -0300 Subject: [PATCH 3/3] Test host: blank line before the fold table Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/host.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index f48d0b85b1..b1e597b556 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -131,6 +131,7 @@ fn default_adapter_is_warp() -> bool { /// Serializes WARP (`d3d10warp.dll`) operations across threads: concurrent /// WARP pipeline compiles / dispatches crash with `0xC0000005` on Windows 11. static WARP_LOCK: Mutex<()> = Mutex::new(()); + /// Root signatures made with a group fold parameter, and its index. static FOLDS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new());