From f1fa9d585cbda5c85256652dd0ce488807b6f28f Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:26:19 +0000 Subject: [PATCH 001/123] Shaders: a value with no DXIL form stays missing through a join only another join reads `Lower::get` marks the phi a value is read from, and `fill_phis` used that mark to decide whether a missing incoming value fails the program or is silently replaced by zero (or false). A join that only feeds another join is never read through `get`, so it counted as unread: a timestamp read (`s_memtime`, which has no DXIL form) that reaches a branch through two joins translated, while the same read with no join in between was refused with `a scalar memory read as data`. Follow the incoming values of a read phi, so a phi an actually read phi takes a value from is treated as read too. The refusal then reaches the reader, as it does without a join, and a value that is genuinely dead (the group id is read instead) still translates. Found and reported by Dathinel in #604; the test is theirs. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 86 +++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 0c10171fc9..de6a097e9b 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -7235,7 +7235,31 @@ impl<'a> Lower<'a> { }) } + /// Adds to `read_phis` every phi an incoming value of a read phi. A + /// read only marks the phi it takes the value from, so a join feeding + /// another join looked unread: a value with no DXIL form then quietly + /// became zero (or false) on that edge, and the program translated with + /// a different answer. Following the joins makes the reader refuse it, + /// as it does for a value read without a join in between. + fn follow_phi_reads(&mut self) { + let p = self.x.p; + let mut queue: Vec = self.read_phis.iter().copied().collect(); + while let Some(v) = queue.pop() { + let Some(&(b, i)) = self.phi_at.get(&v) else { + continue; + }; + for &arg in &p.blocks[b].phis[i].args { + if self.phi_at.contains_key(&arg) && self.read_phis.insert(arg) { + queue.push(arg); + } + } + } + } + fn fill_phis(&mut self) -> Result<(), Stop> { + // A phi read only through another phi is as live as its reader, so + // a missing incoming value stays missing (see `follow_phi_reads`). + self.follow_phi_reads(); let p = self.x.p; for (v, b, i) in std::mem::take(&mut self.data_phis) { let phi = &p.blocks[b].phis[i]; @@ -7364,6 +7388,68 @@ mod tests { ); } + #[test] + fn a_missing_value_stays_missing_through_two_live_joins() { + /// Whether the compute program translates with the group-id SGPRs + /// enabled (`rsrc2 = 3 << 7`). + fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .map(|_| ()) + } + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a read with no joins, so the two agree. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); + } + #[test] fn buffer_cache_invalidations_lower_as_no_ops() { // MUBUF opcode 0x071/0x072 with no data operand: the title asks the From d185b556cc7d65a3b05e83479030c8096330741c Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:26:29 +0000 Subject: [PATCH 002/123] GPU: VICTORY_D3D12_WARP=0 picks the hardware adapter again The switch was read as "is the variable set", so `VICTORY_D3D12_WARP=0` still created the host device on the software adapter: a `0` left in the shell, or set for one command in a batch file, had to be removed instead of turned off. `0` now counts as unset; `1`, an empty value and every other value still select WARP. Reported in #610. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- README.md | 2 +- crates/victory-gpu/src/host.rs | 31 ++++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 92c106cb5a..4cdc6b0d0f 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,7 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | | `VICTORY_SKIP_PIPELINES=,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | | `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | -| `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | +| `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver); `=0` turns it back off, so one shell variable can stay set between runs | | `VICTORY_ADAPTER=` | select a D3D12 adapter by case-insensitive substring (default: high-performance GPU) | | `VICTORY_SHADER_LOOP_LIMIT=` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | | `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) | diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b1c6e4d2c9..b998f93698 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -235,7 +235,7 @@ fn create() -> windows::core::Result { // Diagnostics: the software adapter, on which a shader's wild access // is an access violation in this process (a crash report with the // address and instruction) instead of a GPU fault and driver reset. - if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() { + if warp_on() { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); @@ -411,6 +411,21 @@ pub(crate) fn dred_on() -> bool { }) } +/// Whether the host device is the software adapter (`VICTORY_D3D12_WARP`, +/// diagnostics builds). The variable is set to `1` to compare a run with +/// WARP, so `0` has to turn it off again: a `0` left in the shell (or in a +/// `.bat` that sets it for one command) used to pick WARP as well. +fn warp_on() -> bool { + cfg!(feature = "diagnostics") && warp_switch(std::env::var_os("VICTORY_D3D12_WARP").as_deref()) +} + +/// The `VICTORY_D3D12_WARP` switch, by its value: on when the variable is +/// set to anything but `0`. An empty value counts as on, like every other +/// switch in the README's table. +fn warp_switch(value: Option<&std::ffi::OsStr>) -> bool { + value.is_some_and(|value| value != "0") +} + /// Whether each list of a submission runs and is timed on its own, slow /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics /// builds; the commands are noted with `VICTORY_D3D12_DRED` on). @@ -2763,6 +2778,20 @@ mod tests { assert_eq!(adapter_name(&[b'X' as u16, b'e' as u16]), "Xe"); } + #[test] + fn warp_switch_takes_zero_as_off() { + use std::ffi::OsStr; + // Unset, `0`, `1`, empty, and a value the README does not name. + assert!(!warp_switch(None), "unset"); + assert!(!warp_switch(Some(OsStr::new("0"))), "`0` turns it off"); + assert!(warp_switch(Some(OsStr::new("1")))); + assert!(warp_switch(Some(OsStr::new(""))), "empty is set"); + assert!( + warp_switch(Some(OsStr::new("yes"))), + "any other value is on" + ); + } + #[test] fn adapter_filter_matches_case_insensitively() { assert!(adapter_matches("NVIDIA GeForce RTX 3070 Ti", "rtx 3070")); From c60710a21b47ab224d564e35eae09d93bdafc2d1 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:01:17 +0000 Subject: [PATCH 003/123] Shaders: test that a built program is SSA and every read is dominated `ir::build` hands the emitter one value per register dword and a block graph, and the emitter relies on two things it never checked: that a value is written once, and that the block a read is in is dominated by the block that writes it (a phi's argument by its predecessor). A program that broke either would lower a read to a value that does not exist yet, or to the wrong one. The test builds programs at random from every instruction word the decoder accepts (every opcode of every encoding), and checks those invariants against a dominator set computed by the naive iterative algorithm, so the check does not share code with what it checks. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/ir.rs | 193 ++++++++++++++++++++++++++++++++ 1 file changed, 193 insertions(+) diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 878487b3bb..5b77e77068 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -1232,6 +1232,199 @@ fn add_regs(op: &Operand, lanes: u8, out: &mut Vec) -> Result<(), ()> { #[cfg(test)] mod tests { use super::*; + use std::collections::{HashMap, HashSet}; + + /// Dominators of every block, by the naive iterative algorithm: for each + /// block, the intersection of its predecessors' sets plus itself, until + /// nothing changes. Slow, but independent of the code under test. + fn reference_dominators(blocks: &[Block]) -> Vec> { + let n = blocks.len(); + let mut dom: Vec> = vec![(0..n).collect(); n]; + let mut reachable = vec![false; n]; + reachable[0] = true; + let mut work = vec![0]; + while let Some(b) = work.pop() { + for s in blocks[b].exit.successors() { + if !reachable[s] { + reachable[s] = true; + work.push(s); + } + } + } + let mut changed = true; + while changed { + changed = false; + for b in 1..n { + if !reachable[b] { + continue; + } + let mut d: Option> = None; + for &q in &blocks[b].preds { + if !reachable[q] { + continue; + } + d = Some(match d { + None => dom[q].clone(), + Some(acc) => acc.iter().copied().filter(|x| dom[q].contains(x)).collect(), + }); + } + let mut d = d.unwrap_or_default(); + d.push(b); + d.sort_unstable(); + if d != dom[b] { + dom[b] = d; + changed = true; + } + } + } + dom + } + + /// One word per instruction the decoder accepts, for programs built at + /// random: every opcode of every encoding, with a few operand patterns. + fn decodable_words() -> Vec { + let mut out = Vec::new(); + let mut push = |w: u32, second: u32| { + let code: Vec = [w, second, 0xBF81_0000] + .iter() + .flat_map(|x| x.to_le_bytes()) + .collect(); + if crate::gfx10::decode(&code).is_ok() { + out.push(w); + } + }; + for op in 0..128u32 { + for rest in [0, 0x1FF, 0x3FFFF, 0xFFFF] { + push(op << 25 | rest, 0); // VOP2 + push(0x7E00_0000 | (op << 9) | rest, 0); // VOP1 + push(0x7C00_0000 | (op << 17) | rest, 0); // VOPC + } + } + for op in 0..128u32 { + for rest in [0, 0xFF, 0xFFFF] { + push(0x8000_0000 | (op << 23) | rest, 0); // SOP2 + push(0xB000_0000 | (op << 23) | rest, 0); // SOPK + push(0xBF00_0000 | (op << 16) | rest, 0); // SOPC + push(0xBF80_0000 | (op << 16) | rest, 0); // SOPP + } + push(0xBE80_0000 | (op << 8) | 0xFF, 0); // SOP1 + } + for op in 0..1024u32 { + push(0xD000_0000 | (op << 16), 0x0000_01FF); // VOP3 + } + for op in 0..256u32 { + push(0xD800_0000 | (op << 18), 0); // DS + push(0xF400_0000 | (op << 18), 0); // SMEM + push(0xDC00_0000 | (op << 18), 0); // FLAT + } + for op in 0..128u32 { + push(0xCC00_0000 | (op << 16), 0x0000_01FF); // VOP3P + push(0xE000_0000 | (op << 18), 0); // MUBUF + push(0xF000_0000 | (op << 18), 0); // MIMG + } + for op in 0..16u32 { + push(0xC800_0000 | (op << 16), 0); // VINTRP + push(0xE800_0000 | (op << 16), 0); // MTBUF + } + push(0xF800_0000, 0); // EXP + out.sort_unstable(); + out.dedup(); + out + } + + /// Every value is written once, and every read of it is in a block its + /// definition dominates (a phi's argument in that predecessor), so the + /// emitter can hand each read a value that already exists. + #[test] + fn built_programs_are_ssa_and_dominated() { + let words = decodable_words(); + assert!(words.len() > 1000, "only {} words decode", words.len()); + // xorshift, so the corpus is the same on every run and host. + let mut rng = 0x9E37_79B9_7F4A_7C15u64; + let mut next = || { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + rng + }; + let mut built = 0usize; + for _ in 0..20_000 { + let n = (next() % 12) as usize + 1; + let mut code: Vec = (0..n) + .map(|_| words[(next() as usize) % words.len()]) + .collect(); + code.push(0xBF81_0000); + let bytes: Vec = code.iter().flat_map(|w| w.to_le_bytes()).collect(); + let wave64 = next() % 2 == 0; + let Ok(p) = build(&bytes, wave64, 256) else { + continue; + }; + built += 1; + let dom = reference_dominators(&p.blocks); + let mut defined: HashMap = HashMap::new(); + for (b, block) in p.blocks.iter().enumerate() { + for phi in &block.phis { + assert_eq!( + phi.args.len(), + block.preds.len(), + "block {b}: phi {:?} has {} arguments for {} predecessors", + phi.value, + phi.args.len(), + block.preds.len() + ); + assert!( + defined.insert(phi.value, (b, phi.reg)).is_none(), + "phi {:?} defined twice", + phi.value + ); + } + for inst in &block.insts { + for &(reg, v) in &inst.writes { + let old = defined.insert(v, (b, reg)); + assert!( + old.is_none(), + "{v:?} written twice: {old:?} and ({b}, {reg:?})" + ); + } + } + } + let inputs: HashSet = p.inputs.iter().map(|i| i.1).collect(); + for (b, block) in p.blocks.iter().enumerate() { + for phi in &block.phis { + for (n, &arg) in phi.args.iter().enumerate() { + if inputs.contains(&arg) { + continue; + } + let Some(&(d, _)) = defined.get(&arg) else { + panic!("phi {:?} takes {arg:?}, which nothing defines", phi.value); + }; + assert!( + dom[block.preds[n]].contains(&d), + "phi {:?} takes {arg:?} from block {d}, which does not dominate \ + predecessor {}", + phi.value, + block.preds[n] + ); + } + } + for inst in &block.insts { + for &(_, v) in &inst.reads { + if inputs.contains(&v) { + continue; + } + let Some(&(d, _)) = defined.get(&v) else { + panic!("{v:?} is read in block {b} but never written"); + }; + assert!( + dom[b].contains(&d), + "{v:?} is written in block {d}, which does not dominate block {b}" + ); + } + } + } + } + assert!(built > 500, "only {built} programs built"); + } fn reference_postorder(blocks: &[Block]) -> Vec { let mut seen = vec![false; blocks.len()]; From 61cece302ee7956c1517a6f1a1635cbb9e4f6584 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:14:05 +0000 Subject: [PATCH 004/123] Shaders: a heap view written anywhere is a UAV in every access, and glc makes it globally coherent A descriptor from the SM 6.6 resource heap was annotated SRV or UAV per instruction: the load of a view the program also stores to got an SRV handle ((0xB, 0)) and the store a UAV one ((0x100B, 0)), for one and the same descriptor; a scalar read of it became a constant buffer. Every access now takes IsUAV from all uses of the descriptor (twin loads of the same dwords included) when the root signature says nothing: a store or atomic through any of them makes it a UAV. A known kind still wins. Scalar reads of a UAV are raw UAV loads. A UAV with a plain glc access (skip the per-CU cache, how GFX10 code sees another group's writes) also sets IsGloballyCoherent (0x4000) on all of its handles. glc on an atomic only returns the old value and does not count; glc on a view nothing writes leaves it an SRV. Upstream issues Marvisak/VIctory#724 and #725. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 175 ++++++++++++++++++++++-- 1 file changed, 161 insertions(+), 14 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index de6a097e9b..776554966e 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -41,6 +41,9 @@ pub(crate) struct Lowered { pub has_isnan_op: bool, #[cfg(test)] pub has_fcmp_uno: bool, + /// The props of each heap handle, in creation order. + #[cfg(test)] + pub handle_props: Vec<(u32, u32)>, } pub(crate) struct Parts<'a> { @@ -943,6 +946,12 @@ impl<'a> Lower<'a> { let has_isnan_op = self.s.m.has_dx_op("dx.op.isSpecialFloat.f32", 8); #[cfg(test)] let has_fcmp_uno = self.s.m.has_cmp(pred::UNO); + #[cfg(test)] + let handle_props = { + let mut h: Vec<_> = self.handles.iter().map(|(k, v)| (*v, k.4)).collect(); + h.sort_unstable(); + h.into_iter().map(|(_, p)| p).collect() + }; Ok(Lowered { cmp_samplers, root_cbvs, @@ -954,6 +963,8 @@ impl<'a> Lower<'a> { has_isnan_op, #[cfg(test)] has_fcmp_uno, + #[cfg(test)] + handle_props, }) } @@ -3120,8 +3131,11 @@ impl<'a> Lower<'a> { } return Ok(()); } - if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { - let h = self.handle(site, src, false, (11, 0))?; + // A buffer view read as scalars: raw loads (constant buffers are the + // rest). A UAV, known as one or written elsewhere, keeps its kind. + let u = self.uav_bits(src, kind); + if u != 0 || matches!(kind, Some(k) if k.kind == ResourceType::Srv) { + let h = self.handle(site, src, false, (11 | u, 0))?; for k in 0..count { let off = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, addr, off); @@ -3303,10 +3317,9 @@ impl<'a> Lower<'a> { let used = self.used_kind(&src); let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; let un = ui.name(); - let uav = un.contains("store") - || un.contains("atomic") - || used.is_some_and(|u| u.kind == ResourceType::Uav); - let u = if uav { 0x1000 } else { 0 }; + let written = un.contains("store") || un.contains("atomic"); + let u = self.uav_bits(&src, used) | if written { 0x1000 } else { 0 }; + let uav = u & 0x1000 != 0; let (props, image) = match &ui.fields { Fields::Image { dim, .. } => { let kind = match dim { @@ -3679,6 +3692,58 @@ impl<'a> Lower<'a> { .max_by_key(|u| u.table_offset_dwords) } + /// The `IsUAV` and `IsGloballyCoherent` bits of every handle of the + /// resource descriptor `src`, from all of its uses in the program, not + /// only the access at hand: one descriptor read by a load and written by + /// a store is one UAV, and both handles must say so. `used` is what the + /// root signature says of it (heap descriptors: nothing). + /// + /// A UAV is globally coherent when some plain access through it has + /// `glc` (it skips the per-CU cache, as LLVM's GFX10 memory model lowers + /// a device-scope atomic load, to see other groups' writes). On atomics + /// `glc` only asks for the old value. + fn uav_bits(&self, src: &Source, used: Option<&UsedResource>) -> u32 { + let leaves: Vec<(Site, u8)> = src + .leaves() + .into_iter() + .filter_map(|l| match *l { + Source::Loaded { load, first } => Some((load, first)), + _ => None, + }) + .collect(); + let same = |other: &Source| { + other.leaves().into_iter().any(|l| match *l { + Source::Loaded { load, first } => leaves + .iter() + .any(|&(at, f)| f == first && (at == load || self.twin_loads(at, load))), + _ => false, + }) || other == src + }; + let (mut written, mut coherent) = (false, false); + for d in &self.x.res.descriptors { + if d.role != Role::Resource || !same(&d.source) { + continue; + } + let i: &Inst = &self.x.p.blocks[d.site.0].insts[d.site.1]; + let (Fields::Buffer { cache, .. } + | Fields::Image { cache, .. } + | Fields::Smem { cache, .. }) = &i.fields + else { + continue; + }; + let n = i.name(); + let atomic = n.contains("atomic"); + written |= atomic || n.contains("store"); + coherent |= cache.glc && !atomic; + } + let uav = used.map_or(written, |u| u.kind == ResourceType::Uav); + match (uav, coherent) { + (false, _) => 0, + (true, false) => 0x1000, + (true, true) => 0x1000 | 0x4000, + } + } + /// A handle for the descriptor `src` read at `site`. fn handle( &mut self, @@ -5914,11 +5979,9 @@ impl<'a> Lower<'a> { .copied() .ok_or("an untracked image")?; let store = name.starts_with("image_store"); - let uav = store - || self - .used_kind(src) - .is_some_and(|u| u.kind == ResourceType::Uav); - let props = (kind | if uav { 0x1000 } else { 0 }, 0x409); + let u = self.uav_bits(src, self.used_kind(src)) | if store { 0x1000 } else { 0 }; + let uav = u & 0x1000 != 0; + let props = (kind | u, 0x409); if let Some(op) = name.strip_prefix("image_atomic_") { // GLC returns the old value. DXIL implements subtraction by adding // the two's complement of the operand at the same width. @@ -5975,7 +6038,7 @@ impl<'a> Lower<'a> { } else { original }; - let h = self.handle(site, src, false, (kind | 0x1000, component))?; + let h = self.handle(site, src, false, (kind | 0x1000 | u, component))?; let mut args = vec![h]; let (intrinsic, opcode) = if compare { let comparand = if wide { @@ -6600,8 +6663,8 @@ impl<'a> Lower<'a> { } return Ok(()); } - let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); - let u = if uav { 0x1000 } else { 0 }; + let u = self.uav_bits(src, used) | if store || atomic.is_some() { 0x1000 } else { 0 }; + let uav = u & 0x1000 != 0; let iu = self.s.m.undef(self.s.t.i32); if let Some(op) = atomic { let d = data.as_ref().ok_or("buffer atomic data")?; @@ -7450,6 +7513,90 @@ mod tests { lowers(&words, group_ids_xy).expect("dead timestamp"); } + /// The props of the heap handles of a compute program whose s4 holds + /// the resource heap's address. + fn heap_props(words: &[u32]) -> Vec<(u32, u32)> { + use crate::native::{RootParam, RootType}; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![RootParam { + root: RootType::ResourceHeap, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 0, + }], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let lowered = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .unwrap(); + lowered.handle_props + } + + #[test] + fn a_heap_descriptor_written_anywhere_is_a_uav_in_every_access() { + const HEAP: [u32; 4] = [ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 (the heap's first view) + 0x7E00_0280, // v_mov_b32 v0, 0 + ]; + const LOAD: [u32; 2] = [0xE030_1000, 0x8002_0100]; // buffer_load_dword v1, v0, s[8:11], 0 offen + const LOAD_GLC: [u32; 2] = [0xE030_5000, 0x8002_0100]; // ... glc + const STORE: [u32; 2] = [0xE070_1004, 0x8002_0100]; // buffer_store_dword v1, ... offset:4 + let program = |body: &[&[u32]]| { + let mut w = HEAP.to_vec(); + body.iter().for_each(|b| w.extend_from_slice(b)); + w.push(S_ENDPGM); + heap_props(&w) + }; + // Read only: a raw SRV, as before. + assert_eq!(program(&[&LOAD]), [(0xB, 0)]); + // Read and written: one raw UAV, the load's handle included (it was + // an SRV handle of the UAV descriptor). + assert_eq!(program(&[&LOAD, &STORE]), [(0x100B, 0)]); + assert_eq!(program(&[&STORE, &LOAD]), [(0x100B, 0)]); + // A glc load of it: globally coherent, in every handle. + assert_eq!(program(&[&LOAD_GLC, &STORE]), [(0x500B, 0)]); + assert_eq!(program(&[&LOAD, &LOAD_GLC, &STORE]), [(0x500B, 0)]); + // glc alone does not make an SRV a UAV. + assert_eq!(program(&[&LOAD_GLC]), [(0xB, 0)]); + // Scalar reads of a written view: a raw UAV, not a constant buffer. + let scalar: [u32; 3] = [ + 0xF420_0304, + 0xFA00_0000, // s_buffer_load_dword s12, s[8:11], 0 + 0x7E04_020C, // v_mov_b32 v2, s12 + ]; + let store_v2: [u32; 2] = [0xE070_1008, 0x8002_0200]; // buffer_store_dword v2, ... offset:8 + assert_eq!(program(&[&scalar, &store_v2]), [(0x100B, 0)]); + // Never written: a constant buffer, as before. + let props = program(&[&scalar]); + assert_eq!(props, [(13, 0x1_0000)]); + } + #[test] fn buffer_cache_invalidations_lower_as_no_ops() { // MUBUF opcode 0x071/0x072 with no data operand: the title asks the From a53a5a5b64a3ab0d45d25a0d004be74588794def Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:29:18 +0000 Subject: [PATCH 005/123] Shaders: cube-map arrays sample their slice and face, not layer 0's +X face MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For a cube array the console takes the face operand of image_sample* and image_gather4* (dim CUBE) as 8 × slice + face; GFX10 MIMG has no array bit. The lowering always declared a TextureCube and matched the operand against faces 0-5 only, so any slice above 0 sampled slice 0's +X face, silently. A cube descriptor is now a TextureCubeArray (kind 9) when some sample or gather through it builds its face operand that way: a multiply-add by 8.0 (v_fma/v_fmac/v_fmamk/v_fmaak/v_mad/v_mac/v_madmk/v_madak, as Mesa's prepare_cube_coords emits it), an add of a product by 8.0, or a constant of 8 or more (a constant slice folded in). Every access through the descriptor takes that kind, as the view is one. The slice, floor(face / 8), becomes the fourth coordinate and face - 8 × slice the face (both exact in f32). A size query of a cube array reports its layers in faces (6 × cubes), as the hardware does (Mesa divides them by 6 for txs). A bare face id stays a cube, as before. Upstream issue Marvisak/VIctory#720. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 287 ++++++++++++++++++++++-- 1 file changed, 264 insertions(+), 23 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 776554966e..0c17a61fb9 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3692,17 +3692,11 @@ impl<'a> Lower<'a> { .max_by_key(|u| u.table_offset_dwords) } - /// The `IsUAV` and `IsGloballyCoherent` bits of every handle of the - /// resource descriptor `src`, from all of its uses in the program, not - /// only the access at hand: one descriptor read by a load and written by - /// a store is one UAV, and both handles must say so. `used` is what the - /// root signature says of it (heap descriptors: nothing). - /// - /// A UAV is globally coherent when some plain access through it has - /// `glc` (it skips the per-CU cache, as LLVM's GFX10 memory model lowers - /// a device-scope atomic load, to see other groups' writes). On atomics - /// `glc` only asks for the old value. - fn uav_bits(&self, src: &Source, used: Option<&UsedResource>) -> u32 { + /// Every instruction that reads or writes through the resource + /// descriptor `src`: the same dwords of the same scalar load, or of a + /// twin load of them. + fn accesses(&self, src: &Source) -> Vec<&'a Inst> { + let p: &'a Program = self.x.p; let leaves: Vec<(Site, u8)> = src .leaves() .into_iter() @@ -3719,12 +3713,160 @@ impl<'a> Lower<'a> { _ => false, }) || other == src }; - let (mut written, mut coherent) = (false, false); - for d in &self.x.res.descriptors { - if d.role != Role::Resource || !same(&d.source) { - continue; + self.x + .res + .descriptors + .iter() + .filter(|d| d.role == Role::Resource && same(&d.source)) + .map(|d| &p.blocks[d.site.0].insts[d.site.1]) + .collect() + } + + /// Whether the cube image `src` is a cube array: some sample or gather + /// through it passes a slice in its face operand. The console has no + /// array bit in the instruction; it takes the face operand as + /// `8 × slice + face` (Mesa's `prepare_cube_coords` builds it with one + /// multiply-add by 8.0), so a face operand built that way, or a + /// constant of 8 or more, names a slice. Every access through the + /// descriptor then takes the array's kind, as the view is one. + // shortcut: a cube array only ever sampled at slice 0 (or with the slice + // multiplied in some other way, or 16-bit coordinates) stays a cube. + fn cube_array(&self, src: &Source) -> bool { + self.accesses(src).into_iter().any(|i| { + let Fields::Image { + addr, + dim: 3, + a16: false, + .. + } = &i.fields + else { + return false; + }; + let n = i.name(); + if !n.starts_with("image_sample") && !n.starts_with("image_gather") { + return false; + } + // s, t, face after the offset, bias and reference words (cube + // samples take no gradients). + let first = usize::from(n.ends_with("_o")) + + usize::from(n.starts_with("image_sample_b")) + + usize::from(n.starts_with("image_sample_c")); + let regs: Vec = addr + .iter() + .filter_map(|a| match *a { + Operand::Vector { reg, dwords } => Some((0..dwords).map(move |k| reg + k)), + _ => None, + }) + .flatten() + .collect(); + regs.get(first + 2) + .and_then(|&r| i.read(Reg::V(r))) + .is_some_and(|face| self.slice_in_face(face, 8)) + }) + } + + /// The instruction writing `v` (none for a phi or an input). + fn writer(&self, v: Value) -> Option<&'a Inst> { + let p: &'a Program = self.x.p; + let b = *self.def_block.get(&v)?; + p.blocks[b] + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == v)) + } + + /// The bits of `op` as `inst` reads it, if a constant: inline, literal, + /// or moved into the register from one (at most `depth` moves back). + fn constant_bits(&self, inst: &Inst, op: &Operand, depth: u8) -> Option { + let moved = |reg: Reg, mov: &str| { + let w = self.writer(inst.read(reg)?)?; + if depth == 0 || w.name() != mov { + return None; + } + let src = match &w.fields { + Fields::Sop { src, .. } => src.first()?, + Fields::Valu(v) if v.sdwa.is_none() && v.dpp.is_none() => v.src.first()?, + _ => return None, + }; + self.constant_bits(w, src, depth - 1) + }; + match *op { + Operand::Literal(x) => Some(x), + Operand::Const(code) => crate::resource::inline(code), + Operand::Scalar { code, .. } => moved(Reg::S(code), "s_mov_b32"), + Operand::Vector { reg, .. } => moved(Reg::V(reg), "v_mov_b32"), + Operand::Attr { .. } => None, + } + } + + /// Whether the cube face operand `face` carries a slice (`8 × slice + + /// face`, see [`Self::cube_array`]), following at most `depth` moves. + fn slice_in_face(&self, face: Value, depth: u8) -> bool { + let Some(w) = self.writer(face) else { + return false; + }; + let Fields::Valu(v) = &w.fields else { + return false; + }; + let eight = 8.0f32.to_bits(); + let bits = |n: usize| { + v.src + .get(n) + .and_then(|o| self.constant_bits(w, o, 4)) + .filter(|_| v.neg >> n & 1 == 0 && v.abs >> n & 1 == 0) + }; + let at_least_eight = |x: Option| x.is_some_and(|x| f32::from_bits(x) >= 8.0); + match w.name() { + "v_mov_b32" if depth > 0 && v.sdwa.is_none() && v.dpp.is_none() => { + match v.src.first() { + Some(&Operand::Vector { reg, .. }) => w + .read(Reg::V(reg)) + .is_some_and(|x| self.slice_in_face(x, depth - 1)), + _ => at_least_eight(bits(0)), + } } - let i: &Inst = &self.x.p.blocks[d.site.0].insts[d.site.1]; + // slice × 8.0 + face (the multiplied operands come first). + "v_fma_f32" | "v_fmac_f32" | "v_fmamk_f32" | "v_fmaak_f32" | "v_mad_f32" + | "v_mac_f32" | "v_madmk_f32" | "v_madak_f32" => { + bits(0) == Some(eight) || bits(1) == Some(eight) + } + // face + (slice × 8.0), or face plus a constant slice folded in. + "v_add_f32" => (0..2).any(|n| { + let product = match v.src.get(n) { + Some(&Operand::Vector { reg, .. }) => w + .read(Reg::V(reg)) + .and_then(|x| self.writer(x)) + .is_some_and(|m| { + let Fields::Valu(mv) = &m.fields else { + return false; + }; + m.name() == "v_mul_f32" + && (0..2).any(|k| { + mv.src.get(k).and_then(|o| self.constant_bits(m, o, 4)) + == Some(eight) + }) + }), + _ => false, + }; + product || at_least_eight(bits(n)) + }), + _ => false, + } + } + + /// The `IsUAV` and `IsGloballyCoherent` bits of every handle of the + /// resource descriptor `src`, from all of its uses in the program, not + /// only the access at hand: one descriptor read by a load and written by + /// a store is one UAV, and both handles must say so. `used` is what the + /// root signature says of it (heap descriptors: nothing). + /// + /// A UAV is globally coherent when some plain access through it has + /// `glc` (it skips the per-CU cache, as LLVM's GFX10 memory model lowers + /// a device-scope atomic load, to see other groups' writes). On atomics + /// `glc` only asks for the old value. + fn uav_bits(&self, src: &Source, used: Option<&UsedResource>) -> u32 { + let (mut written, mut coherent) = (false, false); + for i in self.accesses(src) { let (Fields::Buffer { cache, .. } | Fields::Image { cache, .. } | Fields::Smem { cache, .. }) = &i.fields @@ -5978,6 +6120,13 @@ impl<'a> Lower<'a> { .get(&(site, false)) .copied() .ok_or("an untracked image")?; + // A cube array: its slice is in the face operand. + let kind = if kind == 5 && self.cube_array(src) { + 9 + } else { + kind + }; + let cube = matches!(kind, 5 | 9); let store = name.starts_with("image_store"); let u = self.uav_bits(src, self.used_kind(src)) | if store { 0x1000 } else { 0 }; let uav = u & 0x1000 != 0; @@ -6173,12 +6322,21 @@ impl<'a> Lower<'a> { 2 | 5 | 6 => [true, true, false, true], _ => [true, true, true, true], }; + // The console counts a cube array's layers in faces (Mesa + // lowers a cube array's size query to divide them by 6). + let layers = (kind == 9).then(|| { + let z = self.s.m.extract(c, d, 2); + let six = self.s.m.i32(6); + self.s.m.bin(c, Bin::Mul, z, six) + }); let Operand::Vector { reg, .. } = *data else { return Err("an image result"); }; for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() { let x = if ch == 3 && uav || !present[ch as usize] { one + } else if let (2, Some(layers)) = (ch, layers) { + layers } else { self.s.m.extract(c, d, ch) }; @@ -6227,15 +6385,29 @@ impl<'a> Lower<'a> { l.as_float(x) } }; - if kind == 5 && (*unorm || op == 63 || op == 81) { + if cube && (*unorm || op == 63 || op == 81) { return Err("a cube sample with texel coordinates, gradients or a level query"); } for (k, slot) in cs.iter_mut().enumerate().take(coords) { let x = addr_packed(self, coord_base, k)?; *slot = to_float(self, x); } - if kind == 5 { - let dir = self.cube_direction(cs[0], cs[1], cs[2]); + if cube { + let face = if kind == 9 { + // 8 × slice + face: the slice is the fourth coordinate. + let (eighth, eight) = ( + self.s.m.f32(0.125f32.to_bits()), + self.s.m.f32(8.0f32.to_bits()), + ); + let x = self.s.m.bin(c, Bin::Mul, cs[2], eighth); + let slice = self.unary(27, x); + let whole = self.s.m.bin(c, Bin::Mul, slice, eight); + cs[3] = slice; + self.s.m.bin(c, Bin::Sub, cs[2], whole) + } else { + cs[2] + }; + let dir = self.cube_direction(cs[0], cs[1], face); cs[..3].copy_from_slice(&dir); } if *unorm { @@ -6273,7 +6445,7 @@ impl<'a> Lower<'a> { } return Ok(()); } - let offsets = if kind == 5 { + let offsets = if cube { 0 } else { (coords - usize::from(kind == 6 || kind == 7)).min(3) @@ -6497,9 +6669,8 @@ impl<'a> Lower<'a> { /// The direction a cube sample's face coordinates stand for: the /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the - /// host's cube sampling turns back into the same texel. - // shortcut: the view is taken as a cube, not a cube array (whose face - // operand adds 8 × the slice). + /// host's cube sampling turns back into the same texel. A cube array's + /// slice is taken out of `face` first (see [`Self::cube_array`]). fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] { let c = self.cur; let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits()); @@ -7597,6 +7768,76 @@ mod tests { assert_eq!(props, [(13, 0x1_0000)]); } + #[test] + fn a_cube_sample_whose_face_operand_holds_a_slice_is_a_cube_array() { + // An image (heap view 0), a buffer (view 1), an immediate sampler, + // s = t = 1.5; then the face operand in v3, a cube sample of it + // and a store of the result (the reproducer of upstream #720). + let head: [u32; 14] = [ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0202, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0 + 0xF408_0502, + 0xFA00_0020, // s_load_dwordx4 s[20:23], s[4:5], 32 + 0xBE90_0380, // s_mov_b32 s16, 0 + 0xBE91_0380, // s_mov_b32 s17, 0 + 0xBE92_0380, // s_mov_b32 s18, 0 + 0xBE93_0380, // s_mov_b32 s19, 0 + 0x7E02_02FF, + 0x3FC0_0000, // v_mov_b32 v1, 1.5 + 0x7E04_02FF, + 0x3FC0_0000, // v_mov_b32 v2, 1.5 + 0x7E0A_02F2, // v_mov_b32 v5, 1.0 (the slice) + ]; + let tail: [u32; 4] = [ + 0xF09C_0118, + 0x0082_0401, // image_sample_lz v4, v[1:3], s[8:15], s[16:19] dmask:1 dim:CUBE + 0xE070_0000, + 0x8005_0400, // buffer_store_dword v4, off, s[20:23] + ]; + let image_kind = |face: &[u32], extra: &[u32]| { + let words = [&head[..], face, &tail[..], extra, &[S_ENDPGM]].concat(); + let props = heap_props(&words); + let images: Vec = props + .iter() + .filter(|p| p.1 == 0x409) + .map(|p| p.0 & 0xFF) + .collect(); + assert_eq!(images.len(), 1, "{props:x?}"); + images[0] + }; + // A bare face id: a cube, as before. + assert_eq!(image_kind(&[0x7E06_02F4], &[]), 5); // v_mov_b32 v3, 2.0 + // 8 × slice + face, as the console compiler builds it. + let fmac = [ + 0x7E06_02F4, // v_mov_b32 v3, 2.0 + 0x5606_0AFF, + 0x4100_0000, // v_fmac_f32 v3, 8.0, v5 + ]; + assert_eq!(image_kind(&fmac, &[]), 9); + // The product and the sum apart. + let mul_add = [ + 0x7E12_02F4, // v_mov_b32 v9, 2.0 + 0x100C_0AFF, + 0x4100_0000, // v_mul_f32 v6, 8.0, v5 + 0x0606_1306, // v_add_f32 v3, v6, v9 + ]; + assert_eq!(image_kind(&mul_add, &[]), 9); + // A constant slice folded in: 10.0 is slice 1, face 2. + assert_eq!(image_kind(&[0x7E06_02FF, 0x4120_0000], &[]), 9); + // A multiply-add by something else is no slice. + let fmac_four = [0x7E06_02F4, 0x5606_0AF6]; // v_fmac_f32 v3, 4.0, v5 + assert_eq!(image_kind(&fmac_four, &[]), 5); + // A size query of the same view takes the array's kind too. + let resinfo = [ + 0x7E0E_0280, // v_mov_b32 v7, 0 + 0xF038_0718, + 0x0002_0607, // image_get_resinfo v[6:8], v7, s[8:15] dmask:0x7 dim:CUBE + ]; + assert_eq!(image_kind(&fmac, &resinfo), 9); + assert_eq!(image_kind(&[0x7E06_02F4], &resinfo), 5); + } + #[test] fn buffer_cache_invalidations_lower_as_no_ops() { // MUBUF opcode 0x071/0x072 with no data operand: the title asks the From f427da3e04de41b0206b7326bfff36a22934c204 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:42:43 +0000 Subject: [PATCH 006/123] Shaders: only a timestamp stays missing through joins, not every value The #604 fix (f1fa9d5) marked every phi a read phi takes a value from as read, so any missing incoming value of such a join refused the program. Upstream merged the same change as #612 and measured it (#736): 323 programs that translated and validated before stopped, mostly on descriptor dwords, lane masks and interpolation halves that only joins carry after their last use, where the zero never reaches a reader. Phis read only through other joins are now kept apart from the ones an instruction reads. A missing incoming value refuses such a phi only when zero would silently misrepresent it: an s_memtime or s_memrealtime timestamp, the #604 case. Every other value becomes zero on that edge, as before the fix. The test keeps the timestamp case and adds an s_getpc_b64 carried through the same two joins: refused when read directly, translated when only joins carry it. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 50 +++++++++++++++++++------ 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 0c17a61fb9..7a4a971951 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -7469,31 +7469,45 @@ impl<'a> Lower<'a> { }) } - /// Adds to `read_phis` every phi an incoming value of a read phi. A - /// read only marks the phi it takes the value from, so a join feeding - /// another join looked unread: a value with no DXIL form then quietly - /// became zero (or false) on that edge, and the program translated with - /// a different answer. Following the joins makes the reader refuse it, - /// as it does for a value read without a join in between. - fn follow_phi_reads(&mut self) { + /// The phis a read phi takes a value from, through any number of joins, + /// that no instruction reads directly. A read only marks the phi it + /// takes the value from, so a join feeding another join looks unread. + fn phis_read_through_joins(&self) -> HashSet { let p = self.x.p; + let mut through = HashSet::new(); let mut queue: Vec = self.read_phis.iter().copied().collect(); while let Some(v) = queue.pop() { let Some(&(b, i)) = self.phi_at.get(&v) else { continue; }; for &arg in &p.blocks[b].phis[i].args { - if self.phi_at.contains_key(&arg) && self.read_phis.insert(arg) { + if self.phi_at.contains_key(&arg) + && !self.read_phis.contains(&arg) + && through.insert(arg) + { queue.push(arg); } } } + through + } + + /// Whether `v` is a value zero would silently misrepresent if it + /// reached a read through joins: a timestamp, which counts up and + /// which titles compare and subtract. Other missing values that only + /// joins carry (descriptor dwords, lane masks, interpolation halves...) + /// are mostly registers reused after their last use, and keep becoming + /// zero there: refusing them stopped hundreds of programs that + /// translated and validated before (upstream #736). + fn zero_is_wrong(&self, v: Value) -> bool { + self.writer(v) + .is_some_and(|i| matches!(i.name(), "s_memtime" | "s_memrealtime")) } fn fill_phis(&mut self) -> Result<(), Stop> { - // A phi read only through another phi is as live as its reader, so - // a missing incoming value stays missing (see `follow_phi_reads`). - self.follow_phi_reads(); + // A phi read only through another phi is as live as its reader: a + // timestamp it carries stays missing (see `zero_is_wrong`). + let through = self.phis_read_through_joins(); let p = self.x.p; for (v, b, i) in std::mem::take(&mut self.data_phis) { let phi = &p.blocks[b].phis[i]; @@ -7519,7 +7533,10 @@ impl<'a> Lower<'a> { self.s.m.undef(self.s.t.i32) } } - (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => { + (Some(Val::Missing(why)), _) + if self.read_phis.contains(&phi.value) + || through.contains(&phi.value) && self.zero_is_wrong(arg) => + { return Err(Stop::Retry(phi.value, why)); } _ if self.read_phis.contains(&phi.value) => { @@ -7682,6 +7699,15 @@ mod tests { assert_eq!(refusal(&words), refusal(&direct)); words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead lowers(&words, group_ids_xy).expect("dead timestamp"); + // Other values with no DXIL form that only joins carry still become + // zero there, as before (refusing them stopped hundreds of programs + // that translated, upstream #736): only a direct read refuses. + let mut words = words; + words[8] = 0xBF07_8006; // read s6 again + words[0..2].copy_from_slice(&[0xBE86_1F00, 0xBF80_0000]); // s_getpc_b64 s[6:7]; s_nop + let direct = [&words[..2], &words[8..]].concat(); + assert!(refusal(&direct).is_some(), "s_getpc_b64 read as data"); + assert_eq!(refusal(&words), None); } /// The props of the heap handles of a compute program whose s4 holds From f45400c24cf49e4a0ea65ea03b3f403e3ab515cd Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:43:05 +0000 Subject: [PATCH 007/123] docs: victory-formats decodes BCPack; it is no longer planned Upstream issue Marvisak/VIctory#761. The Portuguese translation had the same line. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- docs/architecture.md | 2 +- docs/pt-BR/architecture.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index a4a95f23e4..a4ed32a50f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -35,7 +35,7 @@ Converting them ahead of time from files is only a warm-up. | `victory-hle` | console API implementations, host pass-through policy | | `victory-gpu` | D3D12.X objects, command lists and GPU memory → host D3D12 | | `victory-shader` | Xbox shader containers → host shaders | -| `victory-formats` | the GPU's texture layouts (sizes, tiling, detiling), audio codecs; planned: BCPack | +| `victory-formats` | the GPU's texture layouts (sizes, tiling, detiling), BCPack decoding, audio codecs | | `victory-pipeline` | converter trait, content-addressed cache | | `victory-game` | Grand Theft Auto VI-specific formats, build identities, hooks | | `apps/victory` | command-line front end | diff --git a/docs/pt-BR/architecture.md b/docs/pt-BR/architecture.md index 05d536c192..42800542ac 100644 --- a/docs/pt-BR/architecture.md +++ b/docs/pt-BR/architecture.md @@ -39,7 +39,7 @@ só como aquecimento. | `victory-hle` | implementações das APIs do console, política de repasse ao host | | `victory-gpu` | objetos D3D12.X, command lists e memória de GPU → D3D12 do host | | `victory-shader` | containers de shader do Xbox → shaders do host | -| `victory-formats` | layouts de textura da GPU (tamanhos, tiling, detiling), codecs de áudio; planejado: BCPack | +| `victory-formats` | layouts de textura da GPU (tamanhos, tiling, detiling), decodificação BCPack, codecs de áudio | | `victory-pipeline` | trait de conversor, cache endereçado por conteúdo | | `victory-game` | formatos, identidades de build e hooks específicos de Grand Theft Auto VI | | `apps/victory` | interface de linha de comando | From 5b93bd01422be9876f737a07292611c6b9a0748f Mon Sep 17 00:00:00 2001 From: Louis Faust Date: Mon, 23 Nov 2026 22:59:38 -0800 Subject: [PATCH 008/123] Docs: drop the private intra-doc link to MICRO in texture.rs rustdoc warns that the module docs link to the private const MICRO (rustdoc::private_intra_doc_links). Plain code formatting keeps the reference without the broken link. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit 0f0c872a8f55b356c166c9c6d4185a6bda578e88) --- crates/victory-formats/src/texture.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index e3d5bbb234..87f6edd816 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -13,7 +13,7 @@ //! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`, //! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`, //! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile -//! patterns in [`MICRO`] from `gfx10SwizzlePattern.h` (the RB+ tables, as on +//! patterns in `MICRO` from `gfx10SwizzlePattern.h` (the RB+ tables, as on //! RDNA2). addrlib carries this notice: //! //! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. From d56d40812fc84e8a55b1ea433c8176fe8fc10d32 Mon Sep 17 00:00:00 2001 From: Louis Faust Date: Mon, 23 Nov 2026 22:49:58 -0800 Subject: [PATCH 009/123] Shaders: gate the constant_color test helper to Windows Its only callers (stub_pipeline_is_created, constant_color_validates) are #[cfg(windows)], so on macOS/Linux the helper is dead code and cargo check --all-targets warns 'function constant_color is never used'. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit ab3eb92941e9039b1e9bd90f6c51c64572fc425f) --- crates/victory-shader/src/emit/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index c88dd3f0ab..5feabae1a3 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -542,6 +542,7 @@ mod tests { } /// A pixel shader writing a constant colour. + #[cfg(windows)] fn constant_color() -> Vec { let mut s = Shader::new(true); s.outputs.push(SigElement { From 8cd5f1048a8c895be7e4db22f231c18a497825d7 Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 15:42:18 +0900 Subject: [PATCH 010/123] GPU: unbind vertex buffer slots for null view arrays (cherry picked from commit 31ce30f16954ffdf22758c6f24757a0d8ae79c62) --- crates/victory-gpu/src/draw.rs | 6 ++++++ crates/victory-gpu/src/list.rs | 6 +++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 346e22c17f..598e0fbd0f 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -267,6 +267,12 @@ impl State { } } + pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { + for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) { + *slot = VertexView::default(); + } + } + pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) { self.index = view.copied().unwrap_or_default(); } diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 81df65c558..9bb088f67d 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1187,7 +1187,11 @@ mod state { views: *const VertexView, ) { with_state(this, |_, s| { - s.set_vertex_buffers(start, items(views, count)) + if views.is_null() { + s.clear_vertex_buffers(start, count); + } else { + s.set_vertex_buffers(start, items(views, count)); + } }); } /// `(count, handles, one range, depth)`: with one range, the handles From 1169a3b2c294a951c21f58bec228be6e3eccb9bd Mon Sep 17 00:00:00 2001 From: EatCodeSleep2 <52021568+EatCodeSleep2@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:34:34 -0800 Subject: [PATCH 011/123] GPU: use the host upload path for texture staging copies Queue the list-owned D3D12 staging upload as a host fill so Wine does not skip it based on the title-memory VirtualQuery check. (cherry picked from commit af22e5d3a12c49a3fccc6812b06260715edcab70) --- crates/victory-gpu/src/list.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 9bb088f67d..3ddc5ea698 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -694,7 +694,9 @@ extern "system" fn copy_texture_region( let Some((buffer, staging)) = list.upload(host, bytes) else { return; }; - list.defer_copy(staging, data, bytes as usize); + // The list owns this mapped D3D12 upload buffer. Wine can report + // its address as MEM_FREE, so use the host-upload path. + list.defer_fill(staging, data, bytes as usize); from.resource = buffer.as_raw().cast_const().cast(); from.footprint.offset = 0; #[cfg(feature = "diagnostics")] From d45ef2eda6724a7656f18d8a5a1e2f388da93239 Mon Sep 17 00:00:00 2001 From: lameloball2813-ui <293005050+lameloball2813-ui@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:39:42 -0700 Subject: [PATCH 012/123] Docs: rustdoc builds the loader, GPU and shader crates without warnings (cherry picked from commit 5864aaba28f2ef88d3e32c5710d43ce2b8ef5268) --- crates/victory-gpu/src/list.rs | 2 +- crates/victory-gpu/src/shader_cache.rs | 2 +- crates/victory-loader/src/lib.rs | 2 +- crates/victory-shader/src/emit/validator.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 3ddc5ea698..57986fa247 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -6,7 +6,7 @@ //! the table as a call. //! //! Each list records onto a host command list as its methods are called -//! (decision 0007); draw state lives in [`crate::draw`]. Methods not +//! (decision 0007); draw state lives in `crate::draw`. Methods not //! written yet log once with their caller, so a run lists what to do next. #![allow(clippy::not_unsafe_ptr_arg_deref)] diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index aea2d2beb3..f25e62518a 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -6,7 +6,7 @@ //! atomically; an entry that does not read back is translated again. //! //! The entry is our own encoding of [`HostShader`]: a field added to it -//! must be added to [`encode`] and [`decode`] too (entries of older builds +//! must be added to `encode` and `decode` too (entries of older builds //! are ignored anyway). use std::path::PathBuf; diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 086ae97009..cb51af552a 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -4,7 +4,7 @@ //! CPU, so the machine code needs no translation. What differs is the //! platform underneath, so the loader's job is to: //! -//! 1. [`prepare`] a lightly patched copy of the image (pure, portable): mark +//! 1. [`prepare()`] a lightly patched copy of the image (pure, portable): mark //! it as a DLL, remove its entry point and import directory, and detach //! its TLS callbacks, so the Windows loader maps it, relocates it, //! allocates its static TLS and registers its unwind tables, but runs diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs index a0da0800a1..8cfd3ca9bd 100644 --- a/crates/victory-shader/src/emit/validator.rs +++ b/crates/victory-shader/src/emit/validator.rs @@ -1,6 +1,6 @@ //! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the //! offline batch. Translated shaders do not need it: they carry the -//! container hash we compute ([`super::container::hash`]). +//! container hash we compute (`container::hash`). //! //! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's //! `bin\\x64\dxil.dll`, else wherever `LoadLibrary` finds it. From b197a34da48b875f3a63f00e459375565172a3fd Mon Sep 17 00:00:00 2001 From: Carlos Sant'Anna Date: Tue, 24 Nov 2026 03:14:58 -0300 Subject: [PATCH 013/123] GPU diagnostics: describe a buffer UAV by its range, not as uav None describe looked only for a host texture, so every UAV over a buffer printed 'uav None' in device-removed reports and drop traces, though the view is made. It now prints the buffer's title range, as a buffer shader view does. (cherry picked from commit d74558c4fc715d1be6731013e9644cbc43d70565) --- crates/victory-gpu/src/draw.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 598e0fbd0f..cb2dc7b78d 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1322,7 +1322,11 @@ fn describe(view: Option<&View>) -> String { None => "no view".into(), Some(v @ View::Shader(r, _)) => texture(*r as This) .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))), - Some(View::Unordered(r, ..)) => format!("uav {:?}", texture(*r as This)), + // A buffer has no host texture: its title range, as for a shader view. + Some(v @ View::Unordered(r, ..)) => texture(*r as This).map_or_else( + || format!("uav buffer {:?}", crate::descriptor::host::buffer_range(v)), + |t| format!("uav {t}"), + ), Some(View::Placed(u, r, d)) => format!( "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}", r[0], From 9ba912def0f2ff33e02dd74b1e1fe4da5f43d49f Mon Sep 17 00:00:00 2001 From: AlanQiang0418 Date: Tue, 24 Nov 2026 01:01:55 -0500 Subject: [PATCH 014/123] Shaders: decode GFX10 packed inline constants by operand type (cherry picked from commit a0efd2d37709f9e7c3774b64a3a06ab616a643ba) --- crates/victory-shader/src/emit/lower.rs | 45 +++++++++++--------- crates/victory-shader/src/emit/valu_tests.rs | 21 +++++++++ 2 files changed, 45 insertions(+), 21 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 7a4a971951..c565e6ca88 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1285,6 +1285,19 @@ impl<'a> Lower<'a> { } } + /// GFX10 puts an inline f16 constant in the low half of the operand. + fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result { + match *op { + Operand::Const(c @ 240..=248) => { + let h = [ + 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, + ][usize::from(c - 240)]; + Ok(self.s.m.i32(h)) + } + _ => self.operand(inst, op), + } + } + fn as_float(&mut self, x: V) -> V { self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32) } @@ -4797,15 +4810,9 @@ impl<'a> Lower<'a> { _ => return Err("a byte select on a 16-bit operation"), } } - let x = match (op, self.src0) { - (_, Some(x)) if k == 0 => x, - (Operand::Const(c @ 240..=248), _) => { - let h = [ - 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, - ][usize::from(c - 240)]; - self.s.m.i32(h) - } - _ => self.operand(inst, &op)?, + let x = match self.src0 { + Some(x) if k == 0 => x, + _ => self.f16_operand(inst, &op)?, }; let c = self.cur; let x = if high { @@ -5223,22 +5230,18 @@ impl<'a> Lower<'a> { /// Half `high` of source `k` of a packed (VOP3P) operation, in the low /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the - /// half the high result reads. Inline float constants are f16 values. - fn packed_src(&mut self, inst: &Inst, k: usize, high: bool) -> Result { + /// half the high result reads. Packed integer instructions see the f32 + /// bits of an inline float constant. + fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result { let Fields::Valu(v) = &inst.fields else { unreachable!() }; let op = *v.src.get(k).ok_or("a missing operand")?; let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0; - let x = match op { - Operand::Const(c @ 240..=248) => { - let h = [ - 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, - ][usize::from(c - 240)]; - // shortcut: taken to fill both halves. - self.s.m.i32(h | h << 16) - } - _ => self.operand(inst, &op)?, + let x = if float { + self.f16_operand(inst, &op)? + } else { + self.operand(inst, &op)? }; let c = self.cur; let x = if sel { @@ -5274,7 +5277,7 @@ impl<'a> Lower<'a> { for high in [false, true] { let mut xs = Vec::new(); for k in 0..n { - let h = self.packed_src(inst, k, high)?; + let h = self.packed_src(inst, k, high, float)?; if float { let mut f = self .s diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 79d857ad33..ab8102d752 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -236,6 +236,27 @@ fn f16_to_f32(bits: u16) -> f32 { f32::from_bits(f32_bits) } +#[test] +fn packed_add_selects_halves_of_inline_constants() { + // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves. + // The same GFX10 source field (248) has a different bit pattern for a + // packed floating-point and a packed integer instruction. + let cases = [ + // v_pk_add_f16 v0, 0x3118, v1 + ([0xcc0f4000, 0x1a0202f8], 0x0000_3118), + // v_pk_add_f16 v0, 0x3118, v1 op_sel_hi:[0,1] (use low twice) + ([0xcc0f4000, 0x120202f8], 0x3118_3118), + // v_pk_add_u16 v0, 0x3e22f983, v1 + ([0xcc0a4000, 0x1a0202f8], 0x3e22_f983), + ]; + for (words, expected) in cases { + let shader = build_valu_cs(&words); + run_cases(&shader, &[[0; 4]], |backend, _, _, got| { + assert_eq!(got, expected, "{backend}: {words:08x?}"); + }); + } +} + #[test] fn v_med3_f32_matches_rdna2_with_nan() { // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) From e488762750116d783322458177c2d8c6116d93f3 Mon Sep 17 00:00:00 2001 From: Saitken91 <98485913+SAitken91@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:01:02 -0600 Subject: [PATCH 015/123] Shaders: centroid position with conservative depth Pixel programs that write SV_DepthLessEqual or SV_DepthGreaterEqual failed validation: "Interpolation mode for PS input position must be linear_noperspective_centroid or linear_noperspective_sample when outputting oDepthGE or oDepthLE". The position is now declared linear_noperspective_centroid in those programs, as DXC declares it; without multisampling the value is the same. translate --validate on shaders.rpf: vertex/pixel 12172 -> 12186 validated; the error is gone from the list. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit c249f02dd5d933537195c668d8082d82a9e50efa) --- crates/victory-shader/src/emit/mod.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 5feabae1a3..d3c6e16ddc 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -274,6 +274,13 @@ fn emit_program( _ => 0, }; } + // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL + // wants the position centroid (or per sample), as DXC declares it then. + if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) { + for e in inputs.iter_mut().filter(|e| e.kind == 3) { + e.interp = 5; + } + } // Per-primitive outputs are constant. The console never exports a // primitive id or cull flag a mesh shader writes (it culls with the // primitive export), so those rows are left out. From 510d880c8cfec3f282e12d9781bb562fdd5794a3 Mon Sep 17 00:00:00 2001 From: Lyrnc <98659851+Lyrnc@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:44:03 +0000 Subject: [PATCH 016/123] Shaders: v_cmp_lg is ordered on AMD hosts too (olt | ogt, not fcmp one) v_cmp_lg_{f32,f16} ("less or greater") is ordered and not equal: false when either operand is a NaN, on RDNA2 hardware as in the ISA. It was lowered to `fcmp one`, which says the same, but the AMD D3D12 driver runs `fcmp one` as unordered and returns true for a NaN. NVIDIA and WARP get it right. It now lowers as `olt | ogt`, which all three run alike. New GPU test v_cmp_lg_is_false_for_nan covers both widths: NaN on either side, both NaN, a signalling NaN, +0 against -0, inf against inf and against -inf, and junk in the unread high halves for f16. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 51f1627, upstream Marvisak/VIctory#706) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/bitcode.rs | 3 ++ crates/victory-shader/src/emit/lower.rs | 49 ++++++++++-------- crates/victory-shader/src/emit/valu_tests.rs | 52 ++++++++++++++++++++ 3 files changed, 84 insertions(+), 20 deletions(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index bb8182f9e2..bb35e1e0f3 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -103,6 +103,9 @@ pub(crate) mod pred { pub const OGE: u8 = 3; pub const OLT: u8 = 4; pub const OLE: u8 = 5; + // Not emitted: the AMD D3D12 driver treats it as UNE, so `v_cmp_lg` + // lowers as OLT | OGT instead. + #[allow(dead_code)] pub const ONE: u8 = 6; pub const ORD: u8 = 7; pub const UNO: u8 = 8; diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c565e6ca88..cef0957b8c 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5817,26 +5817,35 @@ impl<'a> Lower<'a> { } else { (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?) }; - let p = match op { - "f" => pred::FALSE, - "lt" => pred::OLT, - "eq" => pred::OEQ, - "le" => pred::OLE, - "gt" => pred::OGT, - "lg" => pred::ONE, - "ge" => pred::OGE, - "o" => pred::ORD, - "u" => pred::UNO, - "nge" => pred::ULT, - "nlg" => pred::UEQ, - "ngt" => pred::ULE, - "nle" => pred::UGT, - "neq" => pred::UNE, - "nlt" => pred::UGE, - "tru" => pred::TRUE, - _ => return Err(inst.name()), - }; - self.s.m.cmp(c, p, a, b) + if op == "lg" { + // Ordered and not equal, false for a NaN, as `olt | ogt`. + // `fcmp one` means the same, but the AMD D3D12 driver + // runs it as unordered (true for a NaN) where NVIDIA + // and WARP do not; olt and ogt agree on all three. + let lt = self.s.m.cmp(c, pred::OLT, a, b); + let gt = self.s.m.cmp(c, pred::OGT, a, b); + self.s.m.bin(c, Bin::Or, lt, gt) + } else { + let p = match op { + "f" => pred::FALSE, + "lt" => pred::OLT, + "eq" => pred::OEQ, + "le" => pred::OLE, + "gt" => pred::OGT, + "ge" => pred::OGE, + "o" => pred::ORD, + "u" => pred::UNO, + "nge" => pred::ULT, + "nlg" => pred::UEQ, + "ngt" => pred::ULE, + "nle" => pred::UGT, + "neq" => pred::UNE, + "nlt" => pred::UGE, + "tru" => pred::TRUE, + _ => return Err(inst.name()), + }; + self.s.m.cmp(c, p, a, b) + } } "u64" | "i64" => { let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index ab8102d752..811ecab6d6 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -513,6 +513,58 @@ fn v_fma_legacy_f32_follows_the_d3d9_zero_rule() { }); } +/// `v_cmp_lg_*` is "less or greater": ordered and not equal, so false when +/// either operand is a NaN (RDNA2 ISA; the same on gfx1036 hardware). +#[test] +fn v_cmp_lg_is_false_for_nan() { + // v_cmp_lg_{f32,f16}_e64 s20, v1, v2 (VOPC 0x005 / 0x0cd in VOP3); + // v_cndmask_b32_e64 v0, 0, 1, s20 (VOP3 0x101) + let nan = f32::NAN.to_bits(); + let (inf, ninf) = (f32::INFINITY.to_bits(), f32::NEG_INFINITY.to_bits()); + let f = f32::to_bits; + let f32_cases: &[([u32; 4], u32)] = &[ + ([f(1.0), f(2.0), 0, 0], 1), + ([f(2.0), f(1.0), 0, 0], 1), + ([f(1.0), f(1.0), 0, 0], 0), + ([f(0.0), f(-0.0), 0, 0], 0), + ([inf, ninf, 0, 0], 1), + ([inf, inf, 0, 0], 0), + ([nan, f(1.0), 0, 0], 0), + ([f(1.0), nan, 0, 0], 0), + ([nan, nan, 0, 0], 0), + ([0x7F80_0001, f(0.0), 0, 0], 0), // a signalling NaN + ]; + let f16_cases: &[([u32; 4], u32)] = &[ + ([0x3C00, 0x4000, 0, 0], 1), + ([0x4000, 0x3C00, 0, 0], 1), + ([0x3C00, 0x3C00, 0, 0], 0), + ([0x0000, 0x8000, 0, 0], 0), + ([0x7C00, 0xFC00, 0, 0], 1), + ([0x7E00, 0x3C00, 0, 0], 0), + ([0x3C00, 0x7E00, 0, 0], 0), + ([0x7E00, 0x7E00, 0, 0], 0), + ([0x7C01, 0x0000, 0, 0], 0), // a signalling NaN + ([0xABCD_3C00, 0x1234_7E00, 0, 0], 0), // only the low halves are read + ]; + for (op, what, cases) in [ + (0x005u16, "v_cmp_lg_f32", f32_cases), + (0x0cd, "v_cmp_lg_f16", f16_cases), + ] { + let mut body = vop3(op, 20, vgpr(1), vgpr(2), 0x80).to_vec(); + body.extend_from_slice(&vop3(0x101, 0, 0x80, 0x81, sgpr(20))); + let shader = build_valu_cs(&body); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: {what}({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + } +} + #[test] fn v_fract_f32_never_returns_one() { // v_fract_f32 v0, v1 (VOP1 opcode 0x020) From 713793200997bccd0993954ce3a33f7cfe227706 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:45:11 +0000 Subject: [PATCH 017/123] Shaders: the test module builds without warnings off Windows constant_color became Windows-only (upstream #685), which left its two imports unused on Linux; the DXIL of the descriptor-data test is only read by the validator and the host, so its binding is unused there too. Gate the imports and allow the binding off Windows, so `cargo clippy --all-targets -- -D warnings` (the CI gate) passes for victory-shader on Linux. Also drops a redundant rebinding in the #604 test. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 1 - crates/victory-shader/src/emit/mod.rs | 4 ++++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index cef0957b8c..fe6995fef5 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -7714,7 +7714,6 @@ mod tests { // Other values with no DXIL form that only joins carry still become // zero there, as before (refusing them stopped hundreds of programs // that translated, upstream #736): only a direct read refuses. - let mut words = words; words[8] = 0xBF07_8006; // read s6 again words[0..2].copy_from_slice(&[0xBE86_1F00, 0xBF80_0000]); // s_getpc_b64 s[6:7]; s_nop let direct = [&words[..2], &words[8..]].concat(); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index d3c6e16ddc..c02472ccf5 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -432,6 +432,7 @@ fn signature(part: &[u8]) -> Result, ShaderError> { #[cfg(test)] mod tests { + #[cfg(windows)] use super::bitcode::Attr; use super::lower::LOOP_LIMIT; use super::parse_loop_limit; @@ -447,6 +448,7 @@ mod tests { } } use super::container::SigElement; + #[cfg(windows)] use super::shader::Shader; use super::*; use crate::native::{ComputeIo, StageIo}; @@ -865,6 +867,8 @@ mod tests { mesh_stride: 0, }) .unwrap(); + // Only the validator and the host (Windows) read the DXIL. + #[cfg_attr(not(windows), allow(unused_mut, unused_variables))] let mut dxil = l.dxil; #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( From be15b448aba43b0a2c81f93f814674db6db4eba1 Mon Sep 17 00:00:00 2001 From: Enzo Souza Duarte Date: Tue, 24 Nov 2026 09:46:39 +0000 Subject: [PATCH 018/123] GPU: write half subnormals from f32 rectangle outputs (cherry picked from commit eb30a0d, upstream Marvisak/VIctory#418; the subnormal path checked against exact ties-to-even rounding for every f32 below 2^-14, both signs) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/primitive.rs | 31 ++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index e8fef10a54..5b01f7b35e 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -191,7 +191,19 @@ fn f32_to_half(v: f32) -> u16 { return sign | 0x7c00; // too large: infinity } if exp <= 0 { - return sign; // too small: zero + if exp < -10 { + return sign; // below half the smallest subnormal: zero + } + // Half subnormals are `m * 2^-24`. An f32 in this range is still + // normal (exponent field >= 1), so its significand has the implicit + // leading 1; shift it into the half mantissa, rounding to even. + let sig = (1u32 << 23) | man; + let shift = (14 - exp) as u32; + let halfway = 1u32 << (shift - 1); + let q = sig >> shift; + let r = sig & ((1u32 << shift) - 1); + let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0)); + return sign | m as u16; } // Rounded to nearest: a carry out of the mantissa is added into the // exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00. @@ -372,4 +384,21 @@ mod tests { } src } + + /// `half_to_f32` reads subnormals, so an f16 rectangle output must be + /// able to write them back instead of flushing every one to zero. + #[test] + fn half_subnormals_convert_in_both_directions() { + assert_eq!(f32_to_half(2f32.powi(-24)), 0x0001); + assert_eq!(f32_to_half(-2f32.powi(-24)), 0x8001); + assert_eq!(f32_to_half(2f32.powi(-23)), 0x0002); + assert_eq!(f32_to_half(1023.0 * 2f32.powi(-24)), 0x03ff); + // Ties go to an even mantissa: 0/1 and 1/2. + assert_eq!(f32_to_half(2f32.powi(-25)), 0x0000); + assert_eq!(f32_to_half(3.0 * 2f32.powi(-25)), 0x0002); + // Below half the smallest subnormal, and normal values, are unchanged. + assert_eq!(f32_to_half(2f32.powi(-26)), 0x0000); + assert_eq!(f32_to_half(1.5), 0x3e00); + assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); + } } From c48acf01b422eea5df33364611daebf577893b00 Mon Sep 17 00:00:00 2001 From: Proudnoob4 Date: Tue, 24 Nov 2026 09:47:12 +0000 Subject: [PATCH 019/123] Shaders: reads of uninitialized SGPRs read as zero, as VGPRs do Compute programs read SGPRs the hardware does not initialize when two branches make the paths look like they allow a read before a write, even though the branch that skips the write does not reach the read. That stops translation with 'a hardware SGPR input is not supported' and drops the program's dispatches. ComputeIo::initialized_sgprs() counts the user SGPRs, the enabled system ones and the scratch wave offset. A read of a general SGPR (0..=105) at or above that count holds whatever the previous wave left, so no program can depend on its value: read it as zero, as unset VGPRs already are. Reserved registers (VCC, trap temporaries, M0, EXEC) keep their current handling. (cherry picked from commit f4438b3, upstream Marvisak/VIctory#432 by Proudnoob4) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 10 +++++++- crates/victory-shader/src/io.rs | 7 ++++++ crates/victory-shader/src/native.rs | 31 +++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index fe6995fef5..55262f0c39 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -983,8 +983,16 @@ impl<'a> Lower<'a> { for &(reg, v) in &self.x.p.inputs { let val = match reg { Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use - Reg::S(_) => match io_inputs.get(&v) { + Reg::S(n) => match io_inputs.get(&v) { Some(&input) => self.input(input), + // Above the SGPRs the hardware initializes, a register + // holds what the last wave left, so no program depends + // on it: a read the paths only seem to allow (a branch + // past the write, taken only with one past the read) + // reads zero, as VGPRs do. + None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => { + Val::I32(self.s.m.i32(0)) + } None => Val::Missing("a hardware SGPR input"), }, Reg::Scc => Val::Missing("SCC on entry"), diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index f075dba44b..f535132a0d 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -184,6 +184,9 @@ pub struct Io { pub inputs: Vec<(Value, Input)>, pub interps: Vec<(Site, Interp)>, pub exports: Vec, + /// Compute: how many SGPRs the hardware initializes + /// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)). + pub initialized_sgprs: Option, } /// Raises the I/O of `p`, built from `native`'s patched code. Fails for @@ -289,6 +292,10 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { let mut io = Io { inputs: inputs.clone(), + initialized_sgprs: match &native.io { + StageIo::Cs(cs) => Some(cs.initialized_sgprs()), + _ => None, + }, ..Io::default() }; // Only a second interpolation half needs to trace SSA definitions. diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 76b307ade8..036cb768e0 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -331,6 +331,15 @@ impl ComputeIo { (ids, take(10)) } + /// SGPRs the hardware initializes: the user SGPRs, the enabled system + /// ones, then the scratch wave offset when scratch is enabled (bit 0). + /// The ones above hold whatever the previous wave left. + pub fn initialized_sgprs(&self) -> u8 { + let (ids, info) = self.system_sgprs(); + let end = ids.into_iter().chain([info]).flatten().map(|s| s + 1).max(); + end.unwrap_or(0).max(self.user_sgprs()) + (self.rsrc2 & 1) as u8 + } + /// Thread id components in v0, v1, v2 (1 to 3). `TIDIG_COMP_CNT` is a /// 2-bit field, but a group id has only three components: 3 loads x, y /// and z like 2 does. @@ -1464,6 +1473,28 @@ mod tests { assert_eq!(cs.thread_id_vgprs(), 3); } + #[test] + fn initialized_sgprs_covers_user_system_and_scratch() { + // 5 user SGPRs, group ids x and y (s5, s6), no scratch: s0..=s6. + let cs = ComputeIo { + rsrc2: 0x1098A, + threads: [16, 16, 1], + }; + assert_eq!(cs.initialized_sgprs(), 7); + // All three group ids after 6 user SGPRs, plus the info SGPR: s0..=s9. + let cs = ComputeIo { + rsrc2: 0x78C, + threads: [8, 8, 1], + }; + assert_eq!(cs.initialized_sgprs(), 10); + // The same with scratch enabled adds the wave offset: s0..=s10. + let cs = ComputeIo { + rsrc2: 0x78D, + threads: [8, 8, 1], + }; + assert_eq!(cs.initialized_sgprs(), 11); + } + #[test] fn reads_every_native_blob() { let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)])); From 17ef0d2098de71b033437ecd15c66fb06123d2e3 Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 09:47:50 +0000 Subject: [PATCH 020/123] GPU: upload CPU-written textures before CopyResource and region copies A texture the title fills through memory has its contents in the staging copy until an upload records them; a copy out of it before any draw read it copied the stale host texture. (cherry picked from commits 0064c08 and 4f53d6f, upstream Marvisak/VIctory#671; adapted to this tree's `&list` handle) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/list.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 57986fa247..a7e5031a1b 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -512,6 +512,11 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::host_resource(dst), crate::resource::host_resource(src), ) { + // A texture the title fills through memory has its contents in + // the staging copy until an upload records them. + if crate::texture::title_written(from) { + crate::texture::upload(&list, src, from); + } ensure_state(&list, dst, COPY_DEST); ensure_state(&list, src, COPY_SOURCE); crate::texture::host_written(dst); @@ -709,6 +714,9 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; + if crate::texture::title_written(texture) { + crate::texture::upload(&list, src.resource, texture); + } ensure_state(&list, src.resource, COPY_SOURCE); from.resource = texture.as_raw().cast_const().cast(); } From 600e362160b944b17705980451db0aa4b874667c Mon Sep 17 00:00:00 2001 From: lameloball2813-ui <293005050+lameloball2813-ui@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:48:04 +0000 Subject: [PATCH 021/123] Loader tests: build the probe fixture under CARGO_TARGET_TMPDIR (cherry picked from commit 764fa19, upstream Marvisak/VIctory#666; this tree's VICTORY_HLE_PROBE override for Proton is kept) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-loader/tests/load_probe.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs index bc3734bb17..6f78f7674b 100644 --- a/crates/victory-loader/tests/load_probe.rs +++ b/crates/victory-loader/tests/load_probe.rs @@ -20,15 +20,16 @@ fn workspace_root() -> PathBuf { } /// Builds the fixture into its own target dir (the outer cargo holds the -/// lock on the main one while tests run). +/// lock on the main one while tests run), in the outer one's scratch folder +/// for tests, so that it follows `CARGO_TARGET_DIR` like the rest of the +/// build. fn build_probe() -> PathBuf { // Under Proton the Windows test process cannot invoke the Linux Cargo. if let Some(path) = std::env::var_os("VICTORY_HLE_PROBE") { return PathBuf::from(path); } - let root = workspace_root(); - let manifest = root.join("tests/fixtures/hle-probe/Cargo.toml"); - let target = root.join("target/fixtures"); + let manifest = workspace_root().join("tests/fixtures/hle-probe/Cargo.toml"); + let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("hle-probe"); let status = Command::new(env!("CARGO")) .args(["build", "--quiet", "--manifest-path"]) .arg(&manifest) From 005497e19f9c2a3c5fce063994fd9bc75002ad24 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:51:53 +0000 Subject: [PATCH 022/123] Shaders: compute samples clamped by _cl keep the console's lanes image_sample_cl and image_sample_b_cl lower like image_sample(_b): outside pixel shaders, as explicit gradients from each quad of lanes. They were missing from implicit_derivatives, so a compute program using only them did not get the console's lane order, and the gradients came from whichever host lanes shared a quad (a debug assertion in tests). Also moves reads_mask_as_data's doc comment back onto it. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 59 ++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 6 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 55262f0c39..0ecb78638c 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -277,13 +277,16 @@ enum MaskData { /// What a value holding a lane mask read as a number stops with. const LANE_MASK: Why = "a lane mask read as data"; -/// Instructions that read a lane mask (not EXEC implicitly, not a lane's -/// bit) as a number. /// Samples whose level comes from derivatives across each quad of lanes. fn implicit_derivatives(name: &str) -> bool { - matches!(name, "image_sample" | "image_sample_b") + matches!( + name, + "image_sample" | "image_sample_cl" | "image_sample_b" | "image_sample_b_cl" + ) } +/// Instructions that read a lane mask (not EXEC implicitly, not a lane's +/// bit) as a number. fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); let ops: Vec<&Operand> = match &i.fields { @@ -7732,6 +7735,11 @@ mod tests { /// The props of the heap handles of a compute program whose s4 holds /// the resource heap's address. fn heap_props(words: &[u32]) -> Vec<(u32, u32)> { + heap_lower(words).unwrap().handle_props + } + + /// Lowers a compute program with a resource heap at s4. + fn heap_lower(words: &[u32]) -> Result { use crate::native::{RootParam, RootType}; let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { @@ -7757,7 +7765,7 @@ mod tests { let res = resource::track(&p, &native.layout, native.stage).unwrap(); let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); - let lowered = lower(&Parts { + lower(&Parts { native: &native, p: &p, st: &st, @@ -7768,8 +7776,47 @@ mod tests { prims: vec![], mesh_stride: 0, }) - .unwrap(); - lowered.handle_props + } + + #[test] + fn compute_samples_with_implicit_levels_keep_console_lanes() { + // Outside pixel shaders these take their level from each quad of + // console lanes (`quad_gradients`), whatever the clamp. + let head: [u32; 11] = [ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0202, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0 + 0xF408_0502, + 0xFA00_0020, // s_load_dwordx4 s[20:23], s[4:5], 32 + 0xBE90_0380, // s_mov_b32 s16, 0 + 0xBE91_0380, // s_mov_b32 s17, 0 + 0xBE92_0380, // s_mov_b32 s18, 0 + 0xBE93_0380, // s_mov_b32 s19, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0280, // v_mov_b32 v2, 0 + ]; + let regs: [u32; 2] = [ + 0x7E06_0280, // v_mov_b32 v3, 0 + 0x7E08_0280, // v_mov_b32 v4, 0 + ]; + for (name, word) in [ + ("image_sample", 0xF080_0108), + ("image_sample_cl", 0xF084_0108), + ("image_sample_b", 0xF094_0108), + ("image_sample_b_cl", 0xF098_0108), + ] { + let tail: [u32; 5] = [ + word, + 0x0082_0501, // v5, v[1:], s[8:15], s[16:19] dmask:1 dim:2D + 0xE070_0000, + 0x8005_0500, // buffer_store_dword v5, off, s[20:23] + S_ENDPGM, + ]; + let words = [&head[..], ®s[..], &tail[..]].concat(); + if let Err(e) = heap_lower(&words) { + panic!("{name}: {e}"); + } + } } #[test] From 244cd0258fb550ec166f1b6a3a824fb31658b506 Mon Sep 17 00:00:00 2001 From: Saitken91 <98485913+SAitken91@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:51:59 +0000 Subject: [PATCH 023/123] Shaders: image_sample_o with constant offsets DXIL takes immediate texel offsets in -8..=7; the console's are 6-bit fields a byte apart in the first address VGPR and may be computed. A constant word in range becomes the immediates; anything else is refused. Outside pixel shaders the sample takes its level from each quad, so it needs the console's lanes like image_sample. (cherry picked from commit 260611a, upstream Marvisak/VIctory#634; adapted: the offsets also reach this tree's quad-gradient path, plus a regression test) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/bitcode.rs | 11 +++ crates/victory-shader/src/emit/lower.rs | 82 ++++++++++++++++++++++- 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index bb35e1e0f3..5fea10144e 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -294,6 +294,17 @@ impl Module { self.constant(ty, Const::Aggregate(ids)) } + /// The value of an integer constant; `None` for anything else. + pub fn int_value(&self, v: V) -> Option { + match v { + V::Const(i) => match self.consts[i as usize].1 { + Const::Int(x) => Some(x), + _ => None, + }, + _ => None, + } + } + /// Gives constant `old` the content of `new` (both stay valid). pub fn replace_const(&mut self, old: V, new: V) { if let (V::Const(o), V::Const(n)) = (old, new) { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 0ecb78638c..c648405070 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -281,7 +281,11 @@ const LANE_MASK: Why = "a lane mask read as data"; fn implicit_derivatives(name: &str) -> bool { matches!( name, - "image_sample" | "image_sample_cl" | "image_sample_b" | "image_sample_b_cl" + "image_sample" + | "image_sample_cl" + | "image_sample_o" + | "image_sample_b" + | "image_sample_b_cl" ) } @@ -6311,7 +6315,7 @@ impl<'a> Lower<'a> { return Ok(()); } let (op, sample) = match name { - "image_sample" | "image_sample_cl" => (60, true), + "image_sample" | "image_sample_cl" | "image_sample_o" => (60, true), "image_sample_lz" | "image_sample_l" => (62, true), "image_sample_b" | "image_sample_b_cl" => (61, true), "image_sample_c_lz" => (65, true), @@ -6478,6 +6482,24 @@ impl<'a> Lower<'a> { for o in os.iter_mut().take(offsets) { *o = zero; } + if offset_word && op != 73 { + // DXIL takes immediate offsets in -8..=7; the console's are + // 6-bit fields (x, y, z a byte apart) and may be computed. + let w = addr_val(self, 0)?; + let w = self + .s + .m + .int_value(w) + .ok_or("a sample offset that is not constant")? as u32; + for (k, o) in os.iter_mut().enumerate().take(offsets) { + let x = (w >> (8 * k) & 0x3F) as i32; + let x = if x >= 32 { x - 64 } else { x }; + if !(-8..=7).contains(&x) { + return Err("a sample offset past -8..7"); + } + *o = self.s.m.i32(x as u32); + } + } let mut args = vec![h, sh]; args.extend(&cs); let clamp = if has_cl { @@ -7781,7 +7803,7 @@ mod tests { #[test] fn compute_samples_with_implicit_levels_keep_console_lanes() { // Outside pixel shaders these take their level from each quad of - // console lanes (`quad_gradients`), whatever the clamp. + // console lanes (`quad_gradients`), whatever the clamp or offset. let head: [u32; 11] = [ 0xBE85_0380, // s_mov_b32 s5, 0 0xF40C_0202, @@ -7804,6 +7826,7 @@ mod tests { ("image_sample_cl", 0xF084_0108), ("image_sample_b", 0xF094_0108), ("image_sample_b_cl", 0xF098_0108), + ("image_sample_o", 0xF0C0_0108), ] { let tail: [u32; 5] = [ word, @@ -7819,6 +7842,59 @@ mod tests { } } + #[test] + fn a_sample_with_constant_offsets_takes_them_as_immediates() { + // An image (heap view 0), a buffer (view 1), an immediate sampler, + // s = t = 1.5; then the offsets in v1, an image_sample_o of them and + // a store of the result (upstream #634). + let head: [u32; 13] = [ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0202, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0 + 0xF408_0502, + 0xFA00_0020, // s_load_dwordx4 s[20:23], s[4:5], 32 + 0xBE90_0380, // s_mov_b32 s16, 0 + 0xBE91_0380, // s_mov_b32 s17, 0 + 0xBE92_0380, // s_mov_b32 s18, 0 + 0xBE93_0380, // s_mov_b32 s19, 0 + 0x7E04_02FF, + 0x3FC0_0000, // v_mov_b32 v2, 1.5 + 0x7E06_02FF, + 0x3FC0_0000, // v_mov_b32 v3, 1.5 + ]; + let tail: [u32; 5] = [ + 0xF0C0_0108, + 0x0082_0401, // image_sample_o v4, v[1:3], s[8:15], s[16:19] dmask:1 dim:2D + 0xE070_0000, + 0x8005_0400, // buffer_store_dword v4, off, s[20:23] + S_ENDPGM, + ]; + let sample = |offsets: &[u32]| heap_lower(&[&head[..], offsets, &tail[..]].concat()); + let refused = |offsets: &[u32]| match sample(offsets) { + Err(crate::ShaderError::Unsupported { what, .. }) => what, + other => panic!("{:?}", other.map(|_| ())), + }; + // x = 1, y = -1 (6-bit fields a byte apart; the rest ignored). + sample(&[0x7E02_02FF, 0xC0C0_3F01]).unwrap(); + // x = -8, y = 7: the ends of DXIL's range. + sample(&[0x7E02_02FF, 0x0000_0738]).unwrap(); + // x = 8 is past it. + assert_eq!( + refused(&[0x7E02_02FF, 0x0000_0008]), + "a sample offset past -8..7" + ); + // y = -9 too. + assert_eq!( + refused(&[0x7E02_02FF, 0x0000_3700]), + "a sample offset past -8..7" + ); + // Offsets computed per lane (v0, the thread id) cannot be immediates. + assert_eq!( + refused(&[0x7E02_0300]), // v_mov_b32 v1, v0 + "a sample offset that is not constant" + ); + } + #[test] fn a_heap_descriptor_written_anywhere_is_a_uav_in_every_access() { const HEAP: [u32; 4] = [ From 0c8ec3952fee6e319f98cc7fc1dedc84084b53a5 Mon Sep 17 00:00:00 2001 From: julio Date: Tue, 24 Nov 2026 09:53:05 +0000 Subject: [PATCH 024/123] GPU: give null texture UAVs the title's view dimension When the host cannot make an unordered-access view (no host texture, a format the host does not allow, a placed texture not mirrored), null_for() wrote a 2D null UAV whatever the title asked for. A shader that writes a 3D texture through it then has a dimension mismatch, which GPU-based validation reports for the world's wind field update. Shader views already get a null view of the title's dimension (null_like); unordered views did not. Null texture UAVs now keep the title's dimension: 1D, 1D and 2D arrays, 3D (WSize -1). Multisampled and unnamed dimensions stay 2D. (cherry picked from commit cbb50b8, upstream Marvisak/VIctory#205; the title's shader name is left out of the comment and message per the asset policy) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/descriptor/host.rs | 105 +++++++++++++++++++--- 1 file changed, 92 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index dd223654f2..48aa25073b 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -889,14 +889,18 @@ pub(crate) fn placed_texture(view: &View) -> Option { } /// A null view of the kind `view` is, for a slot whose view the host -/// cannot make: unordered access (to a buffer or a 2D texture) or a shader -/// view. Writes to it are dropped, reads give zeros. +/// cannot make: unordered access (to a buffer or a texture of the title's +/// dimension) or a shader view. Writes to it are dropped, reads give zeros. fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some(); - let buffer = match view { - View::Unordered(r, _, desc) => is_buffer(r) || desc.is_some_and(|d| d[1] == 1), - View::Placed(true, resource, _) => resource[0] == 1, + // Unordered views: whether a buffer, and the title's view dimension. + let (buffer, dimension) = match view { + View::Unordered(r, _, desc) => ( + is_buffer(r) || desc.is_some_and(|d| d[1] == 1), + desc.map(|d| d[1]), + ), + View::Placed(true, resource, desc) => (resource[0] == 1, Some(desc[1])), // Shader views of buffers read nothing through a null buffer view: // a null 2D view where the shader expects a buffer is a mismatch // the hardware does not survive in general (GPU-based validation @@ -918,14 +922,14 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { } _ => return null_view(at), }; - let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { - Format: DXGI_FORMAT_R32_UINT, - ViewDimension: if buffer { - D3D12_UAV_DIMENSION_BUFFER - } else { - D3D12_UAV_DIMENSION_TEXTURE2D - }, - ..Default::default() + let desc = if buffer { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + } + } else { + null_uav_desc(dimension) }; // SAFETY: a slot of our heap; a null resource is allowed with a desc. unsafe { @@ -938,6 +942,46 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { }; } +/// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays, +/// 3D), 2D if it names none: a 2D null view where the shader writes a 3D +/// texture is a mismatch GPU-based validation reports (the world's wind +/// field update, 2026-11-24). +fn null_uav_desc(dimension: Option) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + match dimension.map(|d| D3D12_UAV_DIMENSION(d as i32)) { + Some(D3D12_UAV_DIMENSION_TEXTURE1D) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + } + Some(D3D12_UAV_DIMENSION_TEXTURE1DARRAY) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; + desc.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV { + ArraySize: 1, + ..Default::default() + }; + } + Some(D3D12_UAV_DIMENSION_TEXTURE2DARRAY) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + desc.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { + ArraySize: 1, + ..Default::default() + }; + } + Some(D3D12_UAV_DIMENSION_TEXTURE3D) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + desc.Anonymous.Texture3D = D3D12_TEX3D_UAV { + WSize: u32::MAX, + ..Default::default() + }; + } + _ => {} + } + desc +} + /// A buffer view that reads zeros (raw, as translated shaders mostly read /// buffers). fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { @@ -1016,6 +1060,41 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// A null texture UAV keeps the title's dimension (3D for the world's + /// wind field), and is 2D when the title names none. + #[test] + fn null_uavs_keep_the_titles_dimension() { + let d = null_uav_desc(Some(8)); + assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE3D); + // SAFETY: the member the dimension names. + assert_eq!(unsafe { d.Anonymous.Texture3D.WSize }, u32::MAX); + let d = null_uav_desc(Some(5)); + assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY); + // SAFETY: the member the dimension names. + assert_eq!(unsafe { d.Anonymous.Texture2DArray.ArraySize }, 1); + let dimension = |d| null_uav_desc(d).ViewDimension; + assert_eq!(dimension(Some(2)), D3D12_UAV_DIMENSION_TEXTURE1D); + assert_eq!(dimension(Some(4)), D3D12_UAV_DIMENSION_TEXTURE2D); + assert_eq!(dimension(None), D3D12_UAV_DIMENSION_TEXTURE2D); + // Multisampled UAVs need a cap; they stay 2D. + assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D); + } + + /// A null 3D UAV made on the real device leaves it alive. + #[test] + fn null_3d_uav_is_accepted_by_the_device() { + let Some(host) = host() else { + return; // no host GPU + }; + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + let view = View::Unordered(0, 0, Some([28, 8, 0, 0, 0, 0, 0, 0, 0, 0])); + null_for(&view, heap.cpu(0)); + // SAFETY: a plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + } + /// The CPU-side block used to initialize null samplers must fit the /// same portable sampler limit as the shader-visible heap. #[test] From bc188e3038d886f70c81b88d7c7dd4e46b76f86d Mon Sep 17 00:00:00 2001 From: hophaver <86059649+hophaver@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:54:12 +0000 Subject: [PATCH 025/123] GPU: the larger dynamic range only where the heap still fits Command lists take per-draw table slots from a view heap's dynamic range; 2^16 of them ran out seconds into the world (every world run on an RX 9070 XT, each a device removal shortly after; upstream #59). View heaps now get 2^18 dynamic slots where the host takes them on top of every title slot, else 2^16 as before (a capped heap, NVIDIA), then the portable cap. (cherry picked from commit e8d3b64, upstream Marvisak/VIctory#336; heap sizing only: this tree already falls back to the title's slots when a table does not fit, instead of dropping the draw) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/descriptor/host.rs | 48 +++++++++++++++++------ 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 48aa25073b..98eae48935 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -19,7 +19,8 @@ pub(crate) struct HostHeap { step: u32, /// Slots mirroring the title's; `spare` more follow them. count: u32, - /// Dynamic slots past the title's: [`DYNAMIC`] in a view heap, + /// Dynamic slots past the title's: [`DYNAMIC`] in a view heap (or + /// [`MIN_DYNAMIC`] where the host will not take that many more), /// [`SAMPLER_DYNAMIC`] in a capped sampler heap, none in another. spare: u32, sampler: bool, @@ -69,7 +70,13 @@ const PORTABLE_VIEWS: u32 = 1_000_000; /// Slots past the title's in a view heap, for tables a draw needs made /// afresh (constant buffers copied per draw). A list holds the slots it /// took until it is reset (its submissions have run) or released. -const DYNAMIC: u32 = 1 << 16; +/// 2^16 ran out seconds into the world (every world run on an RX 9070 XT, +/// each a device removal shortly after; upstream #59). +const DYNAMIC: u32 = 1 << 18; + +/// The dynamic slots of a view heap whose host would not take [`DYNAMIC`] +/// more (a capped heap, NVIDIA): the title's slots keep their room first. +const MIN_DYNAMIC: u32 = 1 << 16; /// The host's limit for shader-visible sampler heaps, on every binding /// tier. @@ -118,15 +125,28 @@ impl HostHeap { SAMPLER_DYNAMIC, ); } - let extra = if sampler { 0 } else { DYNAMIC }; - let (heap, count) = match make(count + extra) { - Ok(heap) => (heap, count), - Err(e) if !sampler && count + extra > PORTABLE_VIEWS => { - // shortcut: descriptors past the host's limit are left out; - // a title that reaches them needs remapping. - tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); - (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra) + // View heaps: the larger dynamic range only where the host takes it + // on top of every title slot; else the smaller one, and the cap + // after that. + let made = if sampler { + make(count).map(|heap| (heap, count, 0)) + } else if let Ok(heap) = make(count.saturating_add(DYNAMIC)) { + Ok((heap, count, DYNAMIC)) + } else { + match make(count.saturating_add(MIN_DYNAMIC)) { + Ok(heap) => Ok((heap, count, MIN_DYNAMIC)), + Err(e) if count.saturating_add(MIN_DYNAMIC) > PORTABLE_VIEWS => { + // shortcut: descriptors past the host's limit are left + // out; a title that reaches them needs remapping. + tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); + make(PORTABLE_VIEWS) + .map(|heap| (heap, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC)) + } + Err(e) => Err(e), } + }; + let (heap, count, extra) = match made { + Ok(made) => made, Err(e) => { tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); return None; @@ -1119,14 +1139,16 @@ mod tests { let Some(heap) = HostHeap::new(false, 4) else { return; // no host GPU }; - let a = heap.dynamic(DYNAMIC - 100).unwrap(); + let spare = heap.spare; + assert!(spare == DYNAMIC || spare == MIN_DYNAMIC, "{spare}"); + let a = heap.dynamic(spare - 100).unwrap(); let b = heap.dynamic(60).unwrap(); - assert_eq!((a, b), (4, 4 + DYNAMIC - 100)); + assert_eq!((a, b), (4, 4 + spare - 100)); // 40 left at the end: 50 do not fit until something is given back. assert_eq!(heap.dynamic(50), None); heap.release(a, 50); assert_eq!(heap.dynamic(50), Some(4)); - assert_eq!(heap.dynamic(40), Some(4 + DYNAMIC - 40)); + assert_eq!(heap.dynamic(40), Some(4 + spare - 40)); } /// A sampler heap past the host's limit is capped, not lost, and keeps From 626937d7a347c8a89d56f03d974b43d52efac7b4 Mon Sep 17 00:00:00 2001 From: Advait Palve Date: Tue, 24 Nov 2026 09:54:41 +0000 Subject: [PATCH 026/123] core: test that a data_dir inside the repo is refused The test from upstream Marvisak/VIctory#611 (commit 9a8908c); the rest of that change is already here in a newer form (show_config prints data_dir with its origin). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-core/src/config.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index 0104f91476..6abd162a89 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -1598,6 +1598,16 @@ mod tests { assert!(cfg.cache_subdir("x").is_err()); } + #[test] + fn data_inside_repo_is_refused() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("data"); + let cfg = Config { + data_dir: inside, + ..Default::default() + }; + assert!(cfg.data_subdir("x").is_err()); + } + /// A path that is absolute on the host (`/x` is not absolute on Windows). #[test] fn folder_overlap_folds_case_only_when_asked() { From 872361ee8fa26fcd5d419252d9cecef7fddc79fd Mon Sep 17 00:00:00 2001 From: r4 <192970269+r4tedx@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:02:33 +0000 Subject: [PATCH 027/123] Shaders: per-lane descriptors and the console's waterfall loops Ports upstream Marvisak/VIctory#566 and the follow-up ffe310e. The console compiler handles a descriptor that differs per lane with a "waterfall" loop: read the first active lane's descriptor (v_readfirstlane), run the access for the lanes that match, drop them, and repeat. Before this, the resource tracker refused every such program ("descriptor-as-data" was the largest refusal class upstream measured in #736). - resource.rs: descriptors chosen by s_cselect / s_cmov are traced per SCC outcome. Per-lane loads, per-lane choices and if/else joins are traced per lane. A waterfall loop is accepted only when EXEC selection is proven (the loop really narrows to the matching lanes), and it is lowered as one non-uniform access. - lower.rs: a waterfall's first-lane read becomes the lane's own dword, and the heap index comes from each lane's descriptor. - track() takes the structured program (Option<&Structured>), so structurisation now runs before resource tracking. - New tests: 26 resource/lowering tests plus the GPU-run waterfall_tests.rs (Windows). Merged into this fork by three-way file merge: the tracker keeps its memo of address sums (now in a RefCell, since the tracker is &self upstream), structure keeps select_masks next to paired_masks, and the threading retry path in emit passes the structured program too. (upstream commits a3d3bc9 ffa6635 077ec8b 6285e19 6638098 b1c8306 6c63dea 74a9d33 ffe310e) Co-authored-by: fuzeofficial Co-authored-by: Marvis Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- apps/victory/src/translate.rs | 17 +- crates/victory-shader/src/emit/lower.rs | 368 ++- crates/victory-shader/src/emit/mod.rs | 31 +- crates/victory-shader/src/emit/shader.rs | 18 +- crates/victory-shader/src/emit/valu_tests.rs | 16 +- .../src/emit/waterfall_tests.rs | 249 ++ crates/victory-shader/src/resource.rs | 2006 ++++++++++++++++- crates/victory-shader/src/structure.rs | 55 + .../victory-shader/tests/resource_tracking.rs | 16 +- docs/architecture.md | 7 +- 10 files changed, 2695 insertions(+), 88 deletions(-) create mode 100644 crates/victory-shader/src/emit/waterfall_tests.rs diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index e3c7d94a9f..7b5a032c60 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -344,7 +344,11 @@ fn translate( Ok(program) => { t.translated += 1; t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::(); - let res = match resource::track(&program, &p.layout, p.stage) { + // Per-lane descriptors are traced on the per-lane form; its + // failure is listed after the resources' and I/O's. + let structured = structure::structure(&program); + let lanes = structured.as_ref().ok(); + let res = match resource::track(&program, &p.layout, p.stage, lanes) { Ok(r) => { tally_resources(&p, &r, t); Some(r) @@ -379,7 +383,7 @@ fn translate( Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)), } } - let structured = match structure::structure(&program) { + let structured = match structured { Ok(s) => { tally_structured(&program, &s, t); Some(s) @@ -558,7 +562,7 @@ fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) { let mut traced = HashSet::new(); for leaf in r.descriptors.iter().flat_map(|d| d.source.leaves()) { let a = match *leaf { - resource::Source::Loaded { load, .. } => { + resource::Source::Loaded { load, .. } | resource::Source::Fetched { load, .. } => { t.loaded += 1; address(load) } @@ -571,7 +575,12 @@ fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) { t.constant += 1; None } - resource::Source::Phi { .. } => unreachable!("leaves are no phis"), + resource::Source::Phi { .. } + | resource::Source::Select { .. } + | resource::Source::Lanes { .. } + | resource::Source::LanePhi { .. } => { + unreachable!("leaves are no phis, selects or per-lane choices") + } }; // Heaps hold dynamic resources, which no used entry lists; code // tables are no root parameter. diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c648405070..d9f25e0927 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -44,6 +44,12 @@ pub(crate) struct Lowered { /// The props of each heap handle, in creation order. #[cfg(test)] pub handle_props: Vec<(u32, u32)>, + /// Heap handles made with a non-uniform index. + #[cfg(test)] + pub nonuniform_handles: u32, + /// Whether the program uses wave operations. + #[cfg(test)] + pub wave_ops: bool, } pub(crate) struct Parts<'a> { @@ -963,6 +969,10 @@ impl<'a> Lower<'a> { cmp_samplers, root_cbvs, root_srvs, + #[cfg(test)] + nonuniform_handles: self.s.nonuniform_handles, + #[cfg(test)] + wave_ops: self.s.flags & flags::WAVE_OPS != 0, dxil: self.s.finish(), user_data, samplers: self.samplers, @@ -3687,9 +3697,14 @@ impl<'a> Lower<'a> { /// The used-resource entry a descriptor loaded from a table falls in. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { - if let Source::Phi { args, .. } = src { + if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } = + src + { return self.used_kind(args.first()?); } + if let Source::LanePhi { args, .. } = src { + return args.iter().flatten().find_map(|a| self.used_kind(a)); + } if let Source::Built { address, .. } = src { let rp = self.x.native.layout.get(address.param)?; return self @@ -3699,7 +3714,7 @@ impl<'a> Lower<'a> { .iter() .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data); } - let Source::Loaded { load, first } = src else { + let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else { return None; }; let a = self.scalar.get(load)?; @@ -3929,7 +3944,12 @@ impl<'a> Lower<'a> { return Ok(h); } let index = self.heap_index(*load, *first, sampler)?; - let h = self.s.heap_handle(self.cur, index, sampler, props); + // A waterfall loop's load at the first lane's offset reads + // each lane's own entry (see `resource::Waterfall`). + let per_lane = self.x.res.waterfall.loads.contains(load); + let h = self + .s + .heap_handle(self.cur, index, sampler, per_lane, props); self.handles.insert(key, h); Ok(h) } @@ -3998,11 +4018,141 @@ impl<'a> Lower<'a> { let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; let phi = self.s.m.phi(join, self.s.t.i32); self.s.m.set_phi(phi, incoming); - Ok(self.s.heap_handle(self.cur, phi, sampler, props)) + Ok(self.s.heap_handle(self.cur, phi, sampler, false, props)) + } + Source::Select { scc, args } => { + // The heap index of each choice, picked by SCC (uniform). + let [ + Source::Loaded { load: a, first: fa }, + Source::Loaded { load: b, first: fb }, + ] = args[..] + else { + return Err("a descriptor chosen by a condition"); + }; + let cond = match self.get(*scc)? { + Val::Bit(x) => x, + _ => return Err("SCC without a value"), + }; + let set = self.heap_index(a, fa, sampler)?; + let clear = self.heap_index(b, fb, sampler)?; + let index = self.s.m.select(self.cur, cond, set, clear); + Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) + } + Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => { + // A descriptor each lane has its own of (a waterfall loop + // reads it from the first active lane): each lane's heap + // index, non-uniform. + let index = self.lane_heap_index(src, sampler)?; + Ok(self.s.heap_handle(self.cur, index, sampler, true, props)) + } + } + } + + /// The heap index of a descriptor that may differ between lanes, + /// computed in the current block (or, chosen by control flow, at the + /// join). + fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result { + match src { + Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), + Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler), + Source::Lanes { mask, args } | Source::Select { scc: mask, args } => { + let [a, b] = &args[..] else { + return Err("a descriptor chosen per lane"); + }; + let cond = if matches!(src, Source::Lanes { .. }) { + let &m = self + .x + .st + .masks + .get(mask) + .ok_or("a descriptor chosen per lane by an untracked mask")?; + self.boolean(m, self.cur)? + } else { + match self.get(*mask)? { + Val::Bit(x) => x, + _ => return Err("SCC without a value"), + } + }; + let set = self.lane_heap_index(a, sampler)?; + let clear = self.lane_heap_index(b, sampler)?; + Ok(self.s.m.select(self.cur, cond, set, clear)) + } + Source::LanePhi { block, args } => { + // Each predecessor computes its heap index at its end (what + // it reads is there: the dwords are, on that edge); the join + // picks the one of the edge the lane came by. An edge no + // lane reading it takes gives index 0. + let join = + self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?; + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = + self.tail[q].ok_or("a per-lane descriptor joined from a later block")?; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + let index = match arg { + Some(arg) => { + let here = std::mem::replace(&mut self.cur, at); + let index = self.lane_heap_index(arg, sampler); + self.cur = here; + index? + } + None => self.s.m.i32(0), + }; + incoming.push((index, at)); + } + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) } + _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"), } } + /// The heap index of the descriptor at dword `first` of what the global + /// load at `load` reads, in each lane: its address (base plus offsets) + /// over the descriptor size. + fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result { + const WHY: Why = "a per-lane descriptor load"; + let a = *self + .scalar + .get(&load) + .ok_or("an untracked descriptor load")?; + match self.x.native.layout.get(a.param).map(|p| p.root) { + Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {} + _ => return Err("a descriptor outside the heaps"), + } + let li: &Inst = &self.x.p.blocks[load.0].insts[load.1]; + let Fields::Flat { + addr: Some(Operand::Vector { reg, .. }), + saddr, + offset, + .. + } = li.fields + else { + return Err(WHY); + }; + let c = self.cur; + // The low dword of the address: SGPR base plus VGPR offset, or the + // VGPR pair's low half (heap addresses fit in 32 bits). + let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?; + if let Some(Operand::Scalar { code, .. }) = saddr + && code != NULL + { + let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?; + at = self.s.m.bin(c, Bin::Add, base, at); + } + let k = self + .s + .m + .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first))); + at = self.s.m.bin(c, Bin::Add, at, k); + let shift = self.s.m.i32(if sampler { 4 } else { 5 }); + Ok(self.s.m.bin(c, Bin::LShr, at, shift)) + } + /// The heap index of the descriptor at dword `first` of what the scalar /// load at `load` reads, computed in the current block. fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result { @@ -4048,6 +4198,12 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if self.x.res.waterfall.compares.contains(&(b, i)) { + // The first lane's dwords of a waterfall loop are each lane's + // own (see `resource::Waterfall`). + self.lane(inst, Some(true)); + return Ok(()); + } if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) { let r = if v.dpp.is_some() { Err("a compare with DPP") @@ -4727,6 +4883,16 @@ impl<'a> Lower<'a> { let val = self.read_lane(a, idx); int(self, val) } + "v_readfirstlane_b32" + if inst + .writes + .first() + .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) => + { + // A waterfall loop's read of a descriptor dword: the lane's own. + let a = s(self, 0)?; + int(self, a) + } "v_readfirstlane_b32" => { let a = s(self, 0)?; self.s.flags |= flags::WAVE_OPS; @@ -7619,8 +7785,10 @@ impl<'a> Lower<'a> { #[cfg(test)] mod tests { - use super::{Numeric, Parts, buffer_format, half_shift, lower}; - use crate::native::{ComputeIo, HwStage, NativeProgram, StageIo}; + use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; + use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, + }; use crate::{io, ir, resource, structure}; const S_ENDPGM: u32 = 0xBF81_0000; @@ -7641,7 +7809,7 @@ mod tests { code, }; let p = ir::build(&native.code, false, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); lower(&Parts { @@ -7703,7 +7871,7 @@ mod tests { code, }; let p = ir::build(&native.code, false, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); lower(&Parts { @@ -7784,9 +7952,9 @@ mod tests { code, }; let p = ir::build(&native.code, false, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); - let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); lower(&Parts { native: &native, p: &p, @@ -8038,7 +8206,7 @@ mod tests { code, }; let p = ir::build(&native.code, false, 4).unwrap(); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); let target = crate::emit::container::SigElement { @@ -8084,7 +8252,7 @@ mod tests { code, }; let p = ir::build(&native.code, false, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); lower(&Parts { @@ -8138,6 +8306,67 @@ mod tests { lowers_ps(&words).unwrap(); } + /// Lowers a compute program with the root parameters `layout` (in user + /// SGPRs from s0 on) and the used resources `used`. + fn lower_with( + words: &[u32], + layout: Vec, + used: Vec, + ) -> Result { + lower_wave(words, layout, used, false) + } + + /// [`lower_with`] in wave64 if `wave64`. + fn lower_wave( + words: &[u32], + layout: Vec, + used: Vec, + wave64: bool, + ) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 256, + layout, + used, + io: StageIo::Cs(ComputeIo { + // The layout's user SGPRs (at least two), 512 bytes of LDS. + rsrc2: 1 << 15 | sgprs.max(2) << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, wave64, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + } + + /// Root parameter `slot` in user SGPRs from `user_data` on. + fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: if root == RootType::Descriptor { 2 } else { 1 }, + base_register: 0, + user_data, + slot, + } + } + #[test] fn a_scalar_carry_chain_reaches_the_select() { // The high dword of a 64-bit add or subtract, then a select on the @@ -8165,6 +8394,7 @@ mod tests { 0xBE83_0380, // s_mov_b32 s3, 0 S_ENDPGM, ]; + for words in [add, sub] { lowers(&words).unwrap(); } @@ -8211,10 +8441,10 @@ mod tests { .any(|i| i.name() == "v_perm_b32") ); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); let io = io::raise(&p, &native).unwrap(); - let st = structure::structure(&p).unwrap(); let emitted = lower(&Parts { native: &native, @@ -8299,7 +8529,7 @@ mod tests { code, }; let p = ir::build(&native.code, false, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); lower(&Parts { @@ -8408,6 +8638,112 @@ mod tests { // A 16-bit float is a half already, sign included. assert_eq!(half(0xBC00 << half_shift(16)), -1.0); } + + #[test] + fn a_descriptor_selected_by_scc_picks_its_heap_index() { + // Two buffer descriptors loaded from the table at s0, one picked by + // a root constant (s1) with s_cselect_b64 per half, and loaded + // through by index and stored to LDS so the load is needed. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408_0302, + 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] + 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] + 0xE030_2000, + 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + // Both are structured buffers of dwords in the table's range. + let used = || { + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + lower_with(&words, layout(), used()).unwrap(); + } + + /// Tables of 2D textures at s0 and samplers at s1. + fn texture_tables() -> (Vec, Vec) { + let range = |kind, user_data, slot| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, + user_data, + slot, + }; + ( + vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], + vec![ + range(ResourceType::Srv, 0, 0), + range(ResourceType::Sampler, 1, 1), + ], + ) + } + + #[test] + fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { + use crate::resource::tests::{ + WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, + }; + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + (WATERFALL_PICKED_WAVE32, false), + ] { + let (layout, used) = texture_tables(); + let l = lower_wave(words, layout, used, wave64).unwrap(); + // The loop's reads of the first lane became each lane's own + // dwords: no wave operation is left. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } + } + + /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. + pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { + let (layout, mut used) = texture_tables(); + used.push(UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }); + (layout, used) + } + + #[test] + fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { + use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; + for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { + let (layout, used) = texture_and_uav_tables(); + let l = lower_wave(words, layout, used, false).unwrap(); + // One image handle, from the join's per-lane heap index. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } + } } #[cfg(test)] @@ -8472,7 +8808,7 @@ mod select_tests { let p = crate::ir::build(&native.code, wave64, native.vgprs).unwrap(); let st = crate::structure::structure(&p).unwrap(); let io = crate::io::raise(&p, &native).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); let shader = emit(&c, &native, &p, &st, &io, &res).unwrap(); let emitted = Container::parse(&shader.dxil).unwrap(); let features = emitted.part(FourCC::SFI0).unwrap(); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index c02472ccf5..4121fde063 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -88,6 +88,8 @@ mod threading; pub mod validator; #[cfg(all(test, windows))] mod valu_tests; +#[cfg(all(test, windows))] +mod waterfall_tests; mod wave; use crate::dxbc::{Container, FourCC}; @@ -211,9 +213,12 @@ pub fn translate(container: &[u8]) -> Result { .iter() .all(|r| native.stage.user_sgpr(r.user_data) >= 16); let p = ir::build_with(&native.patched_code(), native.wave64, native.vgprs, spilled)?; - let res = resource::track(&p, &native.layout, native.stage)?; + // Structurisation first: tracing per-lane descriptors needs it (its + // failure is reported after the earlier stages'). + let st = structure::structure(&p); + let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?; let io = io::raise(&p, &native)?; - let st = structure::structure(&p)?; + let st = st?; emit(&c, &native, &p, &st, &io, &res) } @@ -239,7 +244,7 @@ pub fn emit( let p = ir::thread_edges(p, &edges)?; let st = structure::structure(&p)?; let io = io::raise(&p, native)?; - let res = resource::track(&p, &native.layout, native.stage)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; emit_program(c, native, &p, &st, &io, &res) } @@ -498,9 +503,9 @@ mod tests { let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); let c = Container::parse(&bytes).unwrap(); let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); - let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); // dxil.dll, where there is one, checks the flags against the module. #[cfg(windows)] @@ -540,9 +545,9 @@ mod tests { code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), }; let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); - let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); let container = crate::dxbc::build(&[]); let c = Container::parse(&container).unwrap(); if let Err(e) = emit(&c, &native, &p, &st, &io, &res) { @@ -700,9 +705,9 @@ mod tests { crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]); let c = super::Container::parse(&bytes).unwrap(); let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage).unwrap(); - let io = crate::io::raise(&p, &native).unwrap(); let st = crate::structure::structure(&p).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); // dxil.dll, where there is one, checks PSV0 against the module. #[cfg(windows)] @@ -769,9 +774,9 @@ mod tests { let bytes = crate::dxbc::build(&[(super::FourCC::ISG1, &isg1)]); let c = super::Container::parse(&bytes).unwrap(); let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage).unwrap(); - let io = crate::io::raise(&p, &native).unwrap(); let st = crate::structure::structure(&p).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); // Translated or refused with a reason; it must not panic. let _ = super::emit(&c, &native, &p, &st, &io, &res); } @@ -852,7 +857,7 @@ mod tests { code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), }; let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); let io = crate::io::raise(&p, &native).unwrap(); let st = crate::structure::structure(&p).unwrap(); let l = super::lower::lower(&super::lower::Parts { @@ -976,7 +981,7 @@ mod atomic_tests { &p, &structure::structure(&p).unwrap(), &io::raise(&p, &native).unwrap(), - &resource::track(&p, &native.layout, native.stage).unwrap(), + &resource::track(&p, &native.layout, native.stage, None).unwrap(), ) .unwrap(); let container = Container::parse(&shader.dxil).unwrap(); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 9eb9272639..042ff2218e 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -68,6 +68,8 @@ pub(crate) struct Shader { /// Root SRVs (raw buffers) read, likewise. pub root_srvs: Vec<(u8, V)>, pub flags: u64, + /// Heap handles made with a non-uniform index. + pub nonuniform_handles: u32, /// A compute shader with this thread-group size. pub threads: Option<[u32; 3]>, /// The wave size a compute shader requires (`WaveSize`). @@ -121,6 +123,7 @@ impl Shader { root_cbvs: Vec::new(), root_srvs: Vec::new(), flags: 0, + nonuniform_handles: 0, threads: None, wave_size: None, lds_dwords: 0, @@ -275,14 +278,23 @@ impl Shader { ) } - /// A descriptor heap handle, annotated with `props`. - pub fn heap_handle(&mut self, block: usize, index: V, sampler: bool, props: (u32, u32)) -> V { + /// A descriptor heap handle, annotated with `props`; `nonuniform` when + /// the index may differ between lanes (`NonUniformResourceIndex`). + pub fn heap_handle( + &mut self, + block: usize, + index: V, + sampler: bool, + nonuniform: bool, + props: (u32, u32), + ) -> V { self.flags |= if sampler { flags::SAMPLER_HEAP } else { flags::RESOURCE_HEAP }; - let (s, n) = (self.m.bool(sampler), self.m.bool(false)); + self.nonuniform_handles += u32::from(nonuniform); + let (s, n) = (self.m.bool(sampler), self.m.bool(nonuniform)); let h = self.op( block, "createHandleFromHeap", diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 811ecab6d6..a23533cd10 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -123,9 +123,10 @@ fn build_valu_cs(body: &[u32]) -> HostShader { }; let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - let res = resource::track(&p, &native.layout, native.stage).expect("resource::track"); - let io = io::raise(&p, &native).expect("io::raise"); let st = structure::structure(&p).expect("structure"); + let res = + resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); let lowered = lower::lower(&lower::Parts { native: &native, p: &p, @@ -159,6 +160,13 @@ fn build_valu_cs(body: &[u32]) -> HostShader { shader } +/// One GPU test at a time. With these tests on the hardware adapter and WARP +/// from several test threads at once, now and then none of their dispatches +/// ever completes and the test binary hangs; and two GPU tests at once on +/// WARP can end the test process with an access violation. Other GPU test +/// modules take this lock too. +pub(super) static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// Runs `shader` on every available SM 6.6 host (hardware GPU and WARP) for /// each 4-dword input set and invokes `check(backend, case_index, inputs, result_dword)`. fn run_cases( @@ -166,10 +174,6 @@ fn run_cases( cases: &[[u32; 4]], mut check: impl FnMut(&str, usize, [u32; 4], u32), ) { - // One test at a time: with these tests on the hardware adapter and WARP - // from several test threads at once, now and then none of their - // dispatches ever completes and the test binary hangs. - static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; for (label, warp) in [("hardware", false), ("warp", true)] { diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs new file mode 100644 index 0000000000..104fc6d0c0 --- /dev/null +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -0,0 +1,249 @@ +//! End-to-end tests of waterfall loops over per-lane descriptors: the +//! synthetic GFX10 programs of `resource::tests` lowered to DXIL, validated +//! by `dxil.dll` when present, and run on the host GPU and WARP, each lane +//! reading the resource its own descriptor names. + +use windows::Win32::Graphics::Direct3D12::*; + +use super::host::{Dispatch, Host, Root, Stride, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +/// Lowers a wave32 compute program of 32 threads with the table of views at +/// s0 (textures, or with `buffers` structured buffers of dwords, at entries +/// 0 and 1, a raw UAV at entry 2) and the table of samplers at s1. +fn build(words: &[u32], buffers: bool) -> HostShader { + let table = |user_data: u8| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot: user_data, + }; + let range = |kind, table_offset_dwords, dwords, stride, user_data| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: 0, + stride, + dwords, + user_data, + slot: user_data, + }; + let views = if buffers { + range(ResourceType::Srv, 0, 4, 4, 0) + } else { + range(ResourceType::Srv, 0, 8, 0, 0) + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 32, + layout: vec![table(0), table(1)], + used: vec![ + views, + range(ResourceType::Uav, 16, 4, 0, 0), + range(ResourceType::Sampler, 0, 4, 0, 1), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [32, 1, 1], + }), + code: words.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"); + // One access with each lane's own heap index, no wave operation. + assert_eq!(lowered.nonuniform_handles, 1); + assert!(!lowered.wave_ops); + 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, + }; + 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 +} + +/// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the +/// hardware GPU and on WARP (each skipped without a device) and returns, +/// per one that ran, the UAV's 32 dwords. +fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { + let samplers = [D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }]; + let mut out = Vec::new(); + // One GPU test at a time, with the VALU tests: in parallel on the + // hardware adapter and WARP the test process sometimes died of an + // access violation (7 of 24 runs of these four tests). + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + 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) = match host.compute_pipeline(shader) { + Ok(p) => p, + Err(e) => panic!("{label}: compute_pipeline failed: {e}"), + }; + // Both tables start at heap index 0. + 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 words = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views, + samplers: &samplers, + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + out.push((label, words[0].clone())); + } + out +} + +/// The red channel each lane sampled from two 1x1 textures, red 1.0 at +/// heap index 0 and 2.0 at 1. +fn sampled(shader: &HostShader) -> Vec<(&'static str, Vec)> { + let first = [[1.0f32, 0.0, 0.0, 1.0]]; + let second = [[2.0f32, 0.0, 0.0, 1.0]]; + let views = [ + View::Texture(1, 1, &first), + View::Texture(1, 1, &second), + View::RawUav(32), + ]; + run(shader, &views) + .into_iter() + .map(|(label, words)| (label, words.into_iter().map(f32::from_bits).collect())) + .collect() +} + +#[test] +fn lanes_sample_the_texture_their_if_else_arm_chose() { + use crate::resource::tests::WATERFALL_JOINED_WAVE32; + let shader = build(WATERFALL_JOINED_WAVE32, false); + for (label, red) in sampled(&shader) { + // Lanes below 16 took the first texture, the others the second. + let want: Vec = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); + assert_eq!(red, want, "{label}"); + } +} + +#[test] +fn lanes_sample_the_texture_their_arm_loaded_or_picked() { + use crate::resource::tests::WATERFALL_JOINED_MIXED_WAVE32; + let shader = build(WATERFALL_JOINED_MIXED_WAVE32, false); + for (label, red) in sampled(&shader) { + // Lanes below 16 loaded entry (lane & 1); of the others, lanes + // below 24 picked the first, the rest the second. + let want: Vec = (0..32) + .map(|l| match l { + 0..16 => [1.0, 2.0][l & 1], + 16..24 => 1.0, + _ => 2.0, + }) + .collect(); + assert_eq!(red, want, "{label}"); + } +} + +#[test] +fn lanes_load_from_the_buffer_their_nested_arms_chose() { + use crate::resource::tests::WATERFALL_JOINED_BUFFER_WAVE32; + let shader = build(WATERFALL_JOINED_BUFFER_WAVE32, true); + let first: Vec = (0..32).map(|i| 100 + i).collect(); + let second: Vec = (0..32).map(|i| 200 + i).collect(); + let views = [ + View::Buffer { + data: &first, + stride: Stride::Structured(4), + }, + View::Buffer { + data: &second, + stride: Stride::Structured(4), + }, + View::RawUav(32), + ]; + for (label, got) in run(&shader, &views) { + // Dword `lane` of the first buffer below 16, of the second from 16 + // to 23; lanes from 24 on load and store nothing. + let want: Vec = (0..32) + .map(|l| match l { + 0..16 => 100 + l, + 16..24 => 200 + l, + _ => 0, + }) + .collect(); + assert_eq!(got, want, "{label}"); + } +} + +#[test] +fn lanes_sample_the_entry_their_offset_names_in_the_console_waterfall() { + use crate::resource::tests::WATERFALL_INDEXED_WAVE32; + let shader = build(WATERFALL_INDEXED_WAVE32, false); + let results = sampled(&shader); + assert!(!results.is_empty()); + for (label, red) in results { + // Even lanes hold entry 0's offset, odd lanes entry 1's. + let want: Vec = (0..32).map(|l| [1.0, 2.0][l & 1]).collect(); + assert_eq!(red, want, "{label}"); + } +} + +#[test] +fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() { + use crate::resource::tests::cmpx_waterfall; + // Lanes below 16 hold the first descriptor, the others the second. + let want: Vec = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); + for folded in [false, true] { + let shader = build(&cmpx_waterfall(false, folded), false); + let results = sampled(&shader); + assert!(!results.is_empty()); + for (label, red) in results { + assert_eq!(red, want, "{label}, folded {folded}"); + } + } +} diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index ec8a06798e..c496a0602e 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -14,8 +14,9 @@ use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; -use crate::ir::{Inst, Program, Reg, Value}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, RootParam, RootType}; +use crate::structure::{Bool, LaneExit, Structured}; /// An instruction: block and index in [`crate::ir::Block::insts`]. pub type Site = (usize, usize); @@ -54,13 +55,39 @@ pub enum Source { /// Chosen by control flow: one source per predecessor of `block`, in /// [`crate::ir::Block::preds`] order. Phi { block: usize, args: Vec }, + /// Chosen by SCC (`scc`, the value an `s_cselect` or `s_cmov` of each + /// dword reads): the source when it is set, then when it is clear. + Select { scc: Value, args: Vec }, + /// Dwords `first..` of what the vector load at `load` (`global_load_*`) + /// reads, each lane at its own address (see [`Resources::scalar`]); the + /// dwords past that load come from loads of the bytes that follow. A + /// descriptor that differs between lanes. + Fetched { load: Site, first: u8 }, + /// Picked per lane by `v_cndmask_b32` reading the lane mask whose low + /// dword is `mask`: the source where the lane's bit is set, then where it + /// is clear. + Lanes { mask: Value, args: Vec }, + /// Per-lane dwords chosen by control flow (VGPRs joined where lanes + /// that took different paths meet): one source per predecessor of + /// `block`, in [`crate::ir::Block::preds`] order, `None` on an edge no + /// lane that accesses the descriptor takes. A descriptor that differs + /// between lanes. + LanePhi { + block: usize, + args: Vec>, + }, } impl Source { /// The sources this one picks from (itself unless a phi). pub fn leaves(&self) -> Vec<&Source> { match self { - Source::Phi { args, .. } => args.iter().flat_map(Source::leaves).collect(), + Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } => { + args.iter().flat_map(Source::leaves).collect() + } + Source::LanePhi { args, .. } => { + args.iter().flatten().flat_map(Source::leaves).collect() + } s => vec![s], } } @@ -89,13 +116,41 @@ pub struct Resources { /// User SGPRs holding root parameters: value on entry, layout index, /// dword within the parameter. pub params: Vec<(Value, usize, u32)>, + pub waterfall: Waterfall, +} + +/// Waterfall loops over descriptors that differ between lanes: each pass +/// reads the first active lane's descriptor with `v_readfirstlane_b32`, +/// compares it with every lane's own (`v_cmp_eq`), and runs the access with +/// the lanes that match. Their accesses take each lane's own descriptor +/// ([`Source::Fetched`], [`Source::Lanes`]), so the first lane's dwords are +/// each lane's own too: the compares hold in every lane and one pass serves +/// all lanes. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Waterfall { + /// The compares, true in every lane. + pub compares: Vec, + /// The `v_readfirstlane_b32` results they compare, each the lane's own + /// source dword. + pub reads: Vec, + /// Descriptor loads at a table offset among `reads` (the console + /// compiler's form): each lane loads its own entry. + pub loads: Vec, } /// Traces every descriptor and scalar address of `p`, which runs as /// `stage`, to the root parameters in `layout`. Fails on the first one it -/// cannot trace. -pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result { - let mut t = Tracer::new(p, layout, stage)?; +/// cannot trace. `lanes`, `p` as one lane runs it, tells which paths the +/// lanes that access a per-lane descriptor took and which writes they ran; +/// without it, per-lane descriptors chosen by control flow are refused and +/// per-lane writes are taken to run in every lane. +pub fn track( + p: &Program, + layout: &[RootParam], + stage: HwStage, + lanes: Option<&Structured>, +) -> Result { + let t = Tracer::new(p, layout, stage, lanes)?; let mut out = Resources { params: p .inputs @@ -107,6 +162,13 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result, Vec)>::new(); + // The console compiler's waterfall reads the first lane's table offset + // and loads that entry: accesses, offset reads and loads by block. + let mut offset_at = + std::collections::BTreeMap::, Vec, Vec)>::new(); for (b, block) in p.blocks.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); @@ -114,8 +176,18 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result Result<(), ShaderError> { - let source = t.descriptor(inst, op).map_err(fail)?; + let source = t.descriptor(inst, op, b).map_err(fail)?; + first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); + if let Source::Loaded { load, .. } = source + && let Some((_, a)) = out.scalar.iter().find(|s| s.0 == load) + && let Some(Term::Value(v)) = a.dynamic.map(|d| t.origin(d)) + && t.first_lane_source(v).is_some() + { + offset.push((v, load)); + } out.descriptors.push(Descriptor { site, role, source }); Ok(()) }; @@ -159,6 +231,47 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result {} } + if !first_lane.is_empty() { + let (accesses, reads) = first_lane_at.entry(b).or_default(); + accesses.push(i); + reads.extend(first_lane); + } + if !offset.is_empty() { + let (accesses, reads, loads) = offset_at.entry(b).or_default(); + accesses.push(i); + for (v, load) in offset { + reads.push(v); + loads.push(load); + } + } + } + } + // The proof needs the per-lane form. Without it nothing is emitted, and + // its failure is the one to report, so the reads stay unproven here. + if t.lanes.is_none() { + return Ok(out); + } + for (block, (accesses, mut reads)) in first_lane_at { + reads.sort_unstable(); + reads.dedup(); + let proof = + t.waterfall(block, &accesses, &reads) + .map_err(|what| ShaderError::Unsupported { + offset: t.inst((block, accesses[0])).machine.offset, + what, + })?; + out.waterfall.compares.extend(proof.compares); + out.waterfall.reads.extend(proof.reads); + } + // Unproven, an offset read stays the first lane's (one uniform entry), + // which is what the hardware reads outside a waterfall loop. + for (block, (accesses, mut reads, loads)) in offset_at { + reads.sort_unstable(); + reads.dedup(); + if let Ok(proof) = t.waterfall(block, &accesses, &reads) { + out.waterfall.compares.extend(proof.compares); + out.waterfall.reads.extend(proof.reads); + out.waterfall.loads.extend(loads); } } Ok(out) @@ -192,14 +305,26 @@ struct Tracer<'a> { inputs: Vec>, origin: Vec, /// Address sums already traced, indexed by SSA value. - sums: Vec>, + sums: std::cell::RefCell>>, + lanes: Option<&'a Structured>, + /// Reverse-postorder index per block. + rpo: Vec, } +/// What lanes are known to satisfy: each [`Bool`] where its flag is set, +/// its negation where not. +type Known = Vec<(Bool, bool)>; + const MAX_ROUNDS: usize = 64; const MAX_JOINS: usize = 8; impl<'a> Tracer<'a> { - fn new(p: &'a Program, layout: &'a [RootParam], stage: HwStage) -> Result { + fn new( + p: &'a Program, + layout: &'a [RootParam], + stage: HwStage, + lanes: Option<&'a Structured>, + ) -> Result { let all = || { p.inputs .iter() @@ -228,6 +353,13 @@ impl<'a> Tracer<'a> { } } } + let mut rpo = vec![usize::MAX; p.blocks.len()]; + for (n, b) in crate::ir::reverse_postorder(&p.blocks) + .into_iter() + .enumerate() + { + rpo[b] = n; + } let mut t = Tracer { p, layout, @@ -236,7 +368,9 @@ impl<'a> Tracer<'a> { phis, inputs, origin: Vec::new(), - sums: Vec::new(), + sums: Default::default(), + lanes, + rpo, }; t.origin = t.propagate_copies(n)?; Ok(t) @@ -348,7 +482,7 @@ impl<'a> Tracer<'a> { )) } - fn sum(&mut self, t: Term) -> Sum { + fn sum(&self, t: Term) -> Sum { let v = match t { Term::Const(c) => { return Sum { @@ -360,7 +494,7 @@ impl<'a> Tracer<'a> { Term::Value(v) => v, }; let index = v.0 as usize; - if let Some(&Some(sum)) = self.sums.get(index) { + if let Some(&Some(sum)) = self.sums.borrow().get(index) { return sum; } let dynamic = Sum { @@ -405,10 +539,11 @@ impl<'a> Tracer<'a> { }; // The operands' origins are settled before tracing starts. Every // use of this value can reuse its sum, including an opaque result. - if index >= self.sums.len() { - self.sums.resize(index + 1, None); + let mut sums = self.sums.borrow_mut(); + if index >= sums.len() { + sums.resize(index + 1, None); } - self.sums[index] = Some(sum); + sums[index] = Some(sum); sum } @@ -472,7 +607,7 @@ impl<'a> Tracer<'a> { /// A global memory address: an SGPR pair plus a VGPR offset, or a VGPR /// pair. fn flat_address( - &mut self, + &self, inst: &Inst, addr: Option<&Operand>, saddr: Option<&Operand>, @@ -516,7 +651,7 @@ impl<'a> Tracer<'a> { /// The address `lo` and `hi` hold, plus `extra` (an instruction's /// immediate and offset register). - fn address(&mut self, lo: Term, hi: Term, extra: Sum) -> Result { + fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result { let s = self.sum(lo); if s.dynamic.is_some() && extra.dynamic.is_some() { return Err("an address with two computed terms"); @@ -627,7 +762,7 @@ impl<'a> Tracer<'a> { } fn smem_address( - &mut self, + &self, inst: &Inst, base: &Operand, offset: i32, @@ -651,7 +786,8 @@ impl<'a> Tracer<'a> { self.address(lo, hi, extra) } - fn descriptor(&mut self, inst: &Inst, op: &Operand) -> Result { + /// The source of the descriptor operand `op` of `inst`, in block `at`. + fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result { let Operand::Scalar { code, dwords } = *op else { return Err("a descriptor not in SGPRs"); }; @@ -659,15 +795,38 @@ impl<'a> Tracer<'a> { .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) .collect::>>() .ok_or("a descriptor not in SGPRs")?; - self.classify(&words, &mut Vec::new()) + // Only the lanes that reach the access read the descriptor. + let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); + self.classify(&words, &mut Vec::new(), &mut known) } /// The source of a descriptor's words; `joins` are the phi blocks - /// being resolved. - fn classify(&mut self, words: &[Term], joins: &mut Vec) -> Result { - if let Some(source) = self.phi(words, joins)? { + /// being resolved, `known` holds in every lane that reads them. + fn classify( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result { + if let Some(source) = self.phi(words, joins, known)? { + return Ok(source); + } + if let Some(source) = self.select(words, joins, known)? { return Ok(source); } + let read = |w: &Term| match *w { + Term::Value(v) => self.first_lane_source(v), + Term::Const(_) => None, + }; + if let Some(sources) = words.iter().map(read).collect::>>() { + // Read from the first active lane, as a waterfall loop does: the + // dwords each lane holds. + let lanes: Vec = sources.into_iter().map(Term::Value).collect(); + return self.per_lane(&lanes, joins, known); + } + if words.iter().any(|w| read(w).is_some()) { + return Err("a descriptor partly read from the first lane"); + } if let Some(consts) = words .iter() .map(|w| match *w { @@ -717,18 +876,19 @@ impl<'a> Tracer<'a> { /// Words that phis of one block join, traced per predecessor (words /// defined before the join hold on every edge). fn phi( - &mut self, + &self, words: &[Term], joins: &mut Vec, + known: &mut Known, ) -> Result, &'static str> { - let Some((block, _)) = words.iter().find_map(|&w| self.phi_site(w)) else { + let phi_of = |w: &Term| match *w { + Term::Value(v) => self.phis[v.0 as usize], + Term::Const(_) => None, + }; + let Some((block, _)) = words.iter().find_map(phi_of) else { return Ok(None); }; - if words - .iter() - .filter_map(|&w| self.phi_site(w)) - .any(|(b, _)| b != block) - { + if words.iter().filter_map(phi_of).any(|(b, _)| b != block) { return Err("a descriptor joined in several blocks"); } if joins.contains(&block) { @@ -744,23 +904,107 @@ impl<'a> Tracer<'a> { .map(|j| { let edge: Vec = words .iter() - .map(|&w| match self.phi_site(w) { + .map(|w| match phi_of(w) { Some((_, i)) => self.origin(phis[i].args[j]), - None => w, + None => *w, }) .collect(); - self.classify(&edge, joins) + self.classify(&edge, joins, known) }) .collect::>(); joins.pop(); Ok(Some(Source::Phi { block, args: args? })) } - fn phi_site(&self, word: Term) -> Option { - match word { - Term::Value(v) => self.phis[v.0 as usize], - Term::Const(_) => None, + /// Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced + /// per outcome (other words are the same for both). + fn select( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result, &'static str> { + let picks: Vec<_> = words + .iter() + .map(|w| match *w { + Term::Value(v) => self.picked(v), + Term::Const(_) => None, + }) + .collect(); + let Some(scc) = picks.iter().flatten().map(|p| p.0).next() else { + return Ok(None); + }; + if picks.iter().flatten().any(|p| p.0 != scc) { + return Err("a descriptor chosen by several conditions"); } + // Each level doubles the sources; selects count like joins (a + // marker no block index reaches). + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(usize::MAX); + let side = |set: bool| -> Vec { + words + .iter() + .zip(&picks) + .map(|(w, p)| match p { + Some((_, t, f)) => { + if set { + *t + } else { + *f + } + } + None => *w, + }) + .collect() + }; + let args = [true, false] + .into_iter() + .map(|set| self.classify(&side(set), joins, known)) + .collect::>(); + joins.pop(); + Ok(Some(Source::Select { scc, args: args? })) + } + + /// For `v` written by `s_cselect_b32`/`_b64` or `s_cmov_b32`/`_b64`: + /// the SCC it reads and the dword it is when SCC is set, then clear. + fn picked(&self, v: Value) -> Option<(Value, Term, Term)> { + let inst = self.def(v)?; + let Fields::Sop { dst, src, .. } = &inst.fields else { + return None; + }; + let k = inst.writes.iter().position(|w| w.1 == v)? as u8; + let wide = match inst.name() { + "s_cselect_b32" | "s_cmov_b32" => false, + "s_cselect_b64" | "s_cmov_b64" => true, + _ => return None, + }; + // A dword of a 32- or 64-bit operand: 64-bit inline integers are + // sign-extended; 64-bit literals and float constants are not + // followed. + let dword = |op: &Operand| match *op { + Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)), + Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code + k))?)), + Operand::Const(c) if !wide => inline(c).map(Term::Const), + Operand::Const(c @ 128..=208) => { + let low = inline(c)?; + Some(Term::Const(if k == 0 { + low + } else { + ((low as i32) >> 31) as u32 + })) + } + Operand::Literal(x) if !wide => Some(Term::Const(x)), + _ => None, + }; + let set = dword(src.first()?)?; + let clear = if inst.name().starts_with("s_cmov") { + dword(dst.as_ref()?)? + } else { + dword(src.get(1)?)? + }; + Some((inst.read(Reg::Scc)?, set, clear)) } /// `v` as some other dword with constant bits set. @@ -787,6 +1031,575 @@ impl<'a> Tracer<'a> { } } + /// For a `v_readfirstlane_b32` result: the VGPR value it reads. + fn first_lane_source(&self, v: Value) -> Option { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if inst.name() != "v_readfirstlane_b32" || f.sdwa.is_some() || f.dpp.is_some() { + return None; + } + let Some(&Operand::Vector { reg, .. }) = f.src.first() else { + return None; + }; + inst.read(Reg::V(reg)) + } + + /// The `v_readfirstlane_b32` results the descriptor operand `op` of + /// `inst` is, when every dword is one. + fn first_lane_words(&self, inst: &Inst, op: &Operand) -> Option> { + let Operand::Scalar { code, dwords } = *op else { + return None; + }; + (0..dwords) + .map(|k| match self.origin(inst.read(Reg::S(code + k))?) { + Term::Value(v) => self.first_lane_source(v).map(|_| v), + Term::Const(_) => None, + }) + .collect() + } + + /// `t` through VGPR copies (of VGPRs or of scalars) and copies. + fn lane_term(&self, mut t: Term) -> Term { + for _ in 0..MAX_JOINS * 2 { + let Term::Value(v) = t else { break }; + let next = self.vorigin(v); + if next == t { + break; + } + t = next; + } + t + } + + /// Whether `t` is a value each lane holds its own of (one in VGPRs). + fn varies(&self, t: Term) -> bool { + let Term::Value(v) = t else { return false }; + let reg = match (self.inputs[v.0 as usize], self.phis[v.0 as usize]) { + (Some(reg), _) => Some(reg), + (None, Some((b, i))) => Some(self.p.blocks[b].phis[i].reg), + (None, None) => self + .def(v) + .and_then(|i| i.writes.iter().find(|w| w.1 == v)) + .map(|w| w.0), + }; + matches!(reg, Some(Reg::V(_))) + } + + /// [`Self::lane_term`], where every lane in `known` runs each VGPR copy + /// it follows. + fn lane_value(&self, mut t: Term, known: &Known) -> Result { + for _ in 0..MAX_JOINS * 2 { + let Term::Value(v) = t else { break }; + let next = self.vstep(v); + if next == t { + break; + } + if self.varies(t) + && let Some(site) = self.defs[v.0 as usize] + { + self.runs(site, known)?; + } + t = next; + } + Ok(t) + } + + /// One copy of [`Self::vorigin`]: what the `v_mov_b32` writing `v` + /// reads, or `v`'s origin. + fn vstep(&self, v: Value) -> Term { + if let Some(inst) = self.def(v) + && inst.name() == "v_mov_b32" + && let Fields::Valu(f) = &inst.fields + && f.abs == 0 + && f.neg == 0 + && f.sdwa.is_none() + && f.dpp.is_none() + && let Some(t) = f.src.first().and_then(|s| self.raw(inst, s)) + { + return t; + } + self.origin(v) + } + + /// A VALU operand as `inst` reads it: a VGPR's value itself, other + /// operands' origins. + fn raw(&self, inst: &Inst, op: &Operand) -> Option { + match *op { + Operand::Vector { reg, .. } => Some(Term::Value(inst.read(Reg::V(reg))?)), + op => self.term(inst, &op), + } + } + + /// Fails unless every lane in `known` that reaches the vector + /// instruction at `site` runs it: one with its EXEC bit clear there + /// keeps what the registers held before. + fn runs(&self, site: Site, known: &Known) -> Result<(), &'static str> { + let Some(lanes) = self.lanes else { + return Ok(()); + }; + let Some(&Some(guard)) = lanes.guards.get(site.0).and_then(|g| g.get(site.1)) else { + return Ok(()); + }; + let mut skips = known.clone(); + skips.extend([(lanes.reach[site.0], true), (guard, false)]); + if lanes.bools.meet(&skips) { + return Err("a per-lane descriptor written where some lanes may keep the old one"); + } + Ok(()) + } + + /// The source of descriptor dwords each lane holds its own of (a + /// waterfall loop reads them from the first active lane): the same in + /// every lane, loaded per lane from memory a heap address points to, or + /// picked per lane between such sources, by a lane mask or by the path + /// the lane took. `known` holds in every lane that accesses them. + fn per_lane( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result { + let words = words + .iter() + .map(|&w| self.lane_value(w, known)) + .collect::, _>>()?; + let words = &words[..]; + let Some(&lane) = words.iter().find(|&&w| self.varies(w)) else { + return self.classify(words, joins, known); + }; + if let Some(source) = self.fetched(words, known)? { + return Ok(source); + } + if let Some(source) = self.lane_select(words, joins, known)? { + return Ok(source); + } + if let Some(source) = self.lane_phi(words, joins, known)? { + return Ok(source); + } + let Term::Value(v) = lane else { unreachable!() }; + let name = self.def(v).map(|i| i.name()); + Err(match name { + _ if self.inputs[v.0 as usize].is_some() => { + "a descriptor read from the first lane of an input VGPR" + } + None => "a descriptor read from the first lane of a phi", + Some(n) if n.starts_with("ds_read") => { + "a descriptor read from the first lane of an LDS read" + } + Some(n) if n.starts_with("buffer_load") => { + "a descriptor read from the first lane of a buffer load" + } + Some(n) if n.starts_with("global_load") || n.starts_with("flat_load") => { + "a descriptor read from the first lane of a partial or mixed load" + } + Some(_) => "a descriptor read from the first lane of computed VGPRs", + }) + } + + /// Dwords of `global_load_dword*` that line up: `first..` of one load, + /// then the bytes that follow (an image descriptor takes two + /// `global_load_dwordx4`). + fn fetched(&self, words: &[Term], known: &Known) -> Result, &'static str> { + let at = |w: &Term| -> Option<(Site, usize)> { + let Term::Value(v) = *w else { return None }; + let site = self.defs[v.0 as usize]?; + let inst = self.inst(site); + if !inst.name().starts_with("global_load_dword") { + return None; + } + let k = inst + .writes + .iter() + .filter(|w| matches!(w.0, Reg::V(_))) + .position(|w| w.1 == v)?; + Some((site, k)) + }; + let Some(sites) = words.iter().map(at).collect::>>() else { + return Ok(None); + }; + let address = |site: Site| { + let inst = self.inst(site); + let Fields::Flat { + addr, + saddr, + offset, + .. + } = &inst.fields + else { + return Err("a global load"); + }; + self.flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset) + }; + let (load, first) = sites[0]; + let a0 = address(load)?; + for (k, &(site, dword)) in sites.iter().enumerate() { + self.runs(site, known)?; + let a = address(site)?; + let want = a0.offset.wrapping_add(4 * (first + k) as u32); + if (a.param, a.dynamic) != (a0.param, a0.dynamic) + || a.offset.wrapping_add(4 * dword as u32) != want + { + return Err("a descriptor read from the first lane of loads that do not line up"); + } + } + Ok(Some(Source::Fetched { + load, + first: first as u8, + })) + } + + /// Words that `v_cndmask_b32` picks by one lane mask, traced per outcome + /// (other words are the same for both). + fn lane_select( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result, &'static str> { + let picks: Vec<_> = words + .iter() + .map(|w| match *w { + Term::Value(v) => self.lane_picked(v), + Term::Const(_) => None, + }) + .collect(); + let Some(mask) = picks.iter().flatten().map(|p| p.0).next() else { + return Ok(None); + }; + if picks.iter().flatten().any(|p| p.0 != mask) { + return Err("a descriptor chosen per lane by several masks"); + } + for (w, p) in words.iter().zip(&picks) { + if let (Term::Value(v), Some(_)) = (*w, p) + && let Some(site) = self.defs[v.0 as usize] + { + self.runs(site, known)?; + } + } + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(usize::MAX); + // Each side holds where the lane's bit of the mask is set, or clear. + let bit = self.lanes.and_then(|l| l.masks.get(&mask).copied()); + let side = |set: bool| -> Vec { + words + .iter() + .zip(&picks) + .map(|(w, p)| match p { + Some((_, t, f)) => { + if set { + *t + } else { + *f + } + } + None => *w, + }) + .collect() + }; + let args = [true, false] + .into_iter() + .map(|set| { + let n = known.len(); + known.extend(bit.map(|b| (b, set))); + let arg = self.per_lane(&side(set), joins, known); + known.truncate(n); + arg + }) + .collect::>(); + joins.pop(); + Ok(Some(Source::Lanes { mask, args: args? })) + } + + /// For `v` written by a plain `v_cndmask_b32`: the low dword of the + /// lane mask it reads, and the dword it is where the lane's bit is set + /// (src1), then clear (src0). + fn lane_picked(&self, v: Value) -> Option<(Value, Term, Term)> { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + let Some(Operand::Vector { reg, .. }) = f.dst else { + return None; + }; + if inst.name() != "v_cndmask_b32" + || inst.write(Reg::V(reg)) != Some(v) + || f.abs != 0 + || f.neg != 0 + || f.clamp + || f.omod != 0 + || f.sdwa.is_some() + || f.dpp.is_some() + { + return None; + } + let [clear, set, Operand::Scalar { code, .. }] = f.src[..] else { + return None; + }; + let mask = inst.read(Reg::S(code))?; + Some((mask, self.raw(inst, &set)?, self.raw(inst, &clear)?)) + } + + /// Per-lane words that phis of one block join, as an if/else on a + /// per-lane condition leaves them: traced on each edge into the block + /// that lanes in `known` can take (other words hold on every edge). + /// Lanes take their own paths ([`Structured`]), so each gets the value + /// of the edge it came by; an edge they cannot take is `None` (a flow + /// block's phi joins an arm's dwords with what lanes that skipped the + /// arm held before, which only they read). + fn lane_phi( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result, &'static str> { + let phi_of = |w: &Term| match *w { + Term::Value(v) => self.phis[v.0 as usize], + Term::Const(_) => None, + }; + let Some((block, _)) = words.iter().find_map(phi_of) else { + return Ok(None); + }; + if words.iter().filter_map(phi_of).any(|(b, _)| b != block) { + return Err("a descriptor joined in several blocks"); + } + if joins.contains(&block) { + return Err("a descriptor that changes in a loop"); + } + let preds = &self.p.blocks[block].preds; + if preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) { + // shortcut: what a lane holds after some passes is not traced. + return Err("a descriptor read from the first lane of a phi at a loop header"); + } + let Some(lanes) = self.lanes else { + return Err("a descriptor read from the first lane of a phi, without the lanes' paths"); + }; + // The other words must be there before the join: defined in a + // block that dominates it, which (both dominating the access) is + // one the join does not reach. + for w in words { + if let Term::Value(v) = *w + && phi_of(w).is_none() + && let Some((d, _)) = self.defs[v.0 as usize] + && (d == block || self.reaches(block, d)) + { + return Err("a descriptor partly joined by control flow"); + } + } + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(block); + let phis = &self.p.blocks[block].phis; + let mut args = Vec::new(); + for (j, &q) in preds.iter().enumerate() { + let n = known.len(); + known.push((lanes.reach[q], true)); + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + known.push((when, taken == block)); + } + let arg = if lanes.bools.meet(known) { + let edge: Vec = words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => Term::Value(phis[i].args[j]), + None => *w, + }) + .collect(); + self.per_lane(&edge, joins, known).map(Some) + } else { + Ok(None) + }; + known.truncate(n); + match arg { + Ok(a) => args.push(a), + Err(e) => { + joins.pop(); + return Err(e); + } + } + } + joins.pop(); + Ok(Some(Source::LanePhi { block, args })) + } + + /// Whether a path leads from block `from` to block `to` (to `from` + /// itself only through a back edge). + fn reaches(&self, from: usize, to: usize) -> bool { + let mut seen = vec![false; self.p.blocks.len()]; + let mut stack = self.p.blocks[from].exit.successors(); + while let Some(x) = stack.pop() { + if x == to { + return true; + } + if std::mem::replace(&mut seen[x], true) { + continue; + } + stack.extend(self.p.blocks[x].exit.successors()); + } + false + } + + /// Prove a single-block waterfall at the descriptor access. In each + /// iteration the access serves exactly the matching lanes, and the + /// back edge keeps exactly the other lanes active. Otherwise, why not. + /// + // shortcut: only the accesses are proven. Any other per-lane work in the + // loop is taken to run once for each lane, as the access does; a body + // whose effect adds up over the passes a lane waits through (a counter + // before the mask is narrowed) would differ. Compilers put nothing but + // the reads, the compares and the access in these loops. + fn waterfall( + &self, + b: usize, + accesses: &[usize], + reads: &[Value], + ) -> Result { + const LOOP: &str = "a descriptor read from the first lane outside a waterfall loop"; + const SPLIT: &str = "a waterfall loop nested in another or split over blocks"; + const SELECT: &str = "a waterfall loop whose compares do not select the access's lanes"; + const RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting"; + let access = accesses[0]; + let block = &self.p.blocks[b]; + let lanes = self.lanes.ok_or(LOOP)?; + let exit = block.insts.last().ok_or(LOOP)?; + if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b) + || exit.name() != "s_cbranch_execnz" + { + return Err(LOOP); + } + let mask = |low: Option, high: Option| { + let high = if self.p.wave64 { Some(high?) } else { None }; + lanes.mask_bits(low?, high) + }; + let exec = |inst: &Inst| mask(inst.read(Reg::S(EXEC)), inst.read(Reg::S(EXEC + 1))); + // The reads belong to this loop's own block: a loop around this one + // (one per operand, as LLVM nests them for a per-lane image and + // sampler) is not followed. + if reads + .iter() + .any(|v| self.defs[v.0 as usize].is_none_or(|at| at.0 != b)) + { + return Err(SPLIT); + } + let selected = exec(&block.insts[access]).ok_or(SELECT)?; + if accesses + .iter() + .any(|&i| exec(&block.insts[i]) != Some(selected)) + { + return Err(SELECT); + } + let retry = exec(exit).ok_or(RETRY)?; + let first = self.defs[reads[0].0 as usize].ok_or(LOOP)?; + let remaining = exec(self.inst(first)).ok_or(SELECT)?; + if reads.iter().any(|v| { + self.defs[v.0 as usize] + .is_none_or(|at| at.1 >= access || exec(self.inst(at)) != Some(remaining)) + }) { + return Err(SELECT); + } + let reach = (lanes.reach[b], true); + let meet = |conditions: &[(Bool, bool)]| lanes.bools.meet(conditions); + let mut out = Waterfall::default(); + let mut required = vec![(remaining, true)]; + for (i, inst) in block.insts[..access].iter().enumerate() { + let Fields::Valu(f) = &inst.fields else { + continue; + }; + let Some(ty) = inst + .name() + .strip_prefix("v_cmp_eq_") + .or(inst.name().strip_prefix("v_cmpx_eq_")) + else { + continue; + }; + let dwords = match ty { + "u32" | "i32" => 1, + "u64" | "i64" => 2, + _ => continue, + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + continue; + } + // The first lane's dwords on one side, the lane's own on the + // other. + let pair = |first: &Operand, own: &Operand| -> Option> { + let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = (first, own) + else { + return None; + }; + (0..dwords) + .map(|k| { + let Term::Value(x) = self.origin(inst.read(Reg::S(code + k))?) else { + return None; + }; + let lane = inst.read(Reg::V(reg + k))?; + let (_, read) = self.defs[x.0 as usize]?; + let same = reads.contains(&x) + && read < i + && self.lane_term(Term::Value(self.first_lane_source(x)?)) + == self.lane_term(Term::Value(lane)); + same.then_some(x) + }) + .collect() + }; + let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { + continue; + }; + if let Some(xs) = pair(a, c).or_else(|| pair(c, a)) { + let code = if inst.name().starts_with("v_cmpx_") { + EXEC + } else if let Some(Operand::Scalar { code, .. }) = f.dst { + code + } else { + continue; + }; + let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) + else { + continue; + }; + if meet(&[reach, (selected, true), (matched, false)]) { + continue; + } + required.push((matched, true)); + out.compares.push((b, i)); + for x in xs { + if !out.reads.contains(&x) { + out.reads.push(x); + } + } + } + } + if reads.iter().any(|v| !out.reads.contains(v)) + || meet(&[reach, (selected, true), (remaining, false)]) + { + return Err(SELECT); + } + // The access must take every match. + required.extend([reach, (selected, false)]); + if meet(&required) { + return Err(SELECT); + } + // The retry must keep exactly the lanes that were eligible but did + // not perform the access. + if meet(&[reach, (retry, true), (remaining, false)]) + || meet(&[reach, (retry, true), (selected, true)]) + || meet(&[reach, (remaining, true), (selected, false), (retry, false)]) + { + return Err(RETRY); + } + Ok(out) + } + /// Consecutive dwords of one scalar load. fn loaded(&self, words: &[Term]) -> Option { let Term::Value(v0) = words[0] else { @@ -941,7 +1754,7 @@ pub(crate) fn inline(code: u8) -> Option { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use crate::native::RootType::*; @@ -949,7 +1762,13 @@ mod tests { fn track_words(words: &[u32], layout: &[RootParam], stage: HwStage) -> Resources { let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - track(&crate::ir::build(&code, false, 256).unwrap(), layout, stage).unwrap() + let p = crate::ir::build(&code, false, 256).unwrap(); + track(&p, layout, stage, lanes(&p).as_ref()).unwrap() + } + + /// `p` as one lane runs it, if it structures. + fn lanes(p: &Program) -> Option { + crate::structure::structure(p).ok() } fn param(root: RootType, user_data: u8, sgprs: u32) -> RootParam { @@ -1132,6 +1951,81 @@ mod tests { ); } + #[test] + fn descriptors_selected_by_scc_are_traced_per_outcome() { + // Two buffer descriptors loaded from the table at s9 and one + // picked with s_cselect_b64 per half, as the compiler makes a + // conditional choice of resources without a branch. + let r = track_words( + &[ + 0xBE8C_0309, // s_mov_b32 s12, s9 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0xF408_0006, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null + 0xF408_0106, + 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10 + 0xBF06_800E, // s_cmp_eq_u32 s14, 0 + 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5] + 0x858A_0602, // s_cselect_b64 s[10:11], s[2:3], s[6:7] + 0xF420_0404, + 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let Source::Select { args, .. } = &r.descriptors[0].source else { + panic!("{:?}", r.descriptors) + }; + // SCC set picks the first operand. + assert_eq!( + args[..], + [ + Source::Loaded { + load: (0, 2), + first: 0 + }, + Source::Loaded { + load: (0, 3), + first: 0 + }, + ] + ); + assert_eq!(r.scalar, [((0, 2), at(0, 0)), ((0, 3), at(0, 0x10))]); + } + + #[test] + fn a_selection_that_mixes_two_descriptors_fails() { + // The high half picked from the first load whatever SCC is: when + // clear, the descriptor is half of one load and half of the other. + let code: Vec = [ + 0xBE8C_0309, // s_mov_b32 s12, s9 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0xF408_0006, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null + 0xF408_0106, + 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10 + 0xBF06_800E, // s_cmp_eq_u32 s14, 0 + 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5] + 0x858A_0202, // s_cselect_b64 s[10:11], s[2:3], s[2:3] + 0xF420_0404, + 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null + S_ENDPGM, + ] + .iter() + .flat_map(|w: &u32| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + offset: 36, + what: "a descriptor changed after loading" + } + ); + } + #[test] fn untraceable_addresses_fail_with_a_reason() { let code: Vec = [0xF408_0001, 0xFA00_0000, S_ENDPGM] // s_load_dwordx4 s[0:3], s[2:3] @@ -1139,7 +2033,7 @@ mod tests { .flat_map(|w: &u32| w.to_le_bytes()) .collect(); let p = crate::ir::build(&code, false, 256).unwrap(); - let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps).unwrap_err(); + let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err(); assert_eq!( err, ShaderError::Unsupported { @@ -1148,4 +2042,1038 @@ mod tests { } ); } + + /// A waterfall loop over an image descriptor each lane loads from the + /// table at s0 (wave32, assembled with llvm-mc for gfx1030): lane i + /// reads entry i with two `global_load_dwordx4`, the loop reads the + /// first active lane's descriptor into s[12:19], samples with the lanes + /// whose descriptor it is, and repeats for the others. The sampler comes + /// from the table at s1; the result goes to LDS so the sample is needed. + pub(crate) const WATERFALL_FETCHED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0x3402_0085, // v_lshlrev_b32 v1, 5, v0 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// [`WATERFALL_FETCHED_WAVE32`] in wave64: 64-bit lane masks. + pub(crate) const WATERFALL_FETCHED_WAVE64: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0x3402_0085, // v_lshlrev_b32 v1, 5, v0 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_047E, // s_mov_b64 s[20:21], exec + 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0016, + 0x0002_080C, // v_cmp_eq_u64_e64 s[22:23], s[12:13], v[4:5] + 0xD4E2_0018, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s[24:25], s[14:15], v[6:7] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xD4E2_0018, + 0x0002_1010, // v_cmp_eq_u64_e64 s[24:25], s[16:17], v[8:9] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xD4E2_0018, + 0x0002_1412, // v_cmp_eq_u64_e64 s[24:25], s[18:19], v[10:11] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xBE96_2416, // s_and_saveexec_b64 s[22:23], s[22:23] + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x89FE_167E, // s_xor_b64 exec, exec, s[22:23] + 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c + 0xBEFE_0414, // s_mov_b64 exec, s[20:21] + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// The same waterfall over one of two image descriptors loaded from the + /// table at s0, picked per lane by `v_cndmask_b32` (lanes below 16 take + /// the first). + pub(crate) const WATERFALL_PICKED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo + 0x7E16_021F, // v_mov_b32 v11, s31 + 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7E18_0504, // 0x7c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0x7c + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// The waterfall loop of [`WATERFALL_PICKED_WAVE32`] over one of two + /// image descriptors loaded from the table at s0, chosen by control flow + /// as the compiler lowers an if/else on a per-lane condition: lanes below + /// 16 move the first into v[4:11], the others the second, each arm + /// skipped when no lane takes it. The sample goes to the buffer at dword + /// 16 of the table, at lane * 4. + pub(crate) const WATERFALL_JOINED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0008, // s_cbranch_execz -> 0x70 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x7E16_021F, // v_mov_b32 v11, s31 + 0xBE94_3D14, // 0x70: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0008, // s_cbranch_execz -> 0x9c + 0x7E08_0220, // v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x7E10_0224, // v_mov_b32 v8, s36 + 0x7E12_0225, // v_mov_b32 v9, s37 + 0x7E14_0226, // v_mov_b32 v10, s38 + 0x7E16_0227, // v_mov_b32 v11, s39 + 0x887E_147E, // 0x9c: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E18_0504, // 0xa4: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0xa4 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + /// The console compiler's waterfall (Grand Theft Auto VI's ray-tracing + /// resolve and others): each lane holds its entry's byte offset in the + /// table at s0 (v7 = (lane & 1) * 32); the loop reads the first active + /// lane's offset, narrows EXEC to the lanes with the same one + /// (`v_cmpx_eq_u32`), loads that entry with `s_load_dwordx8` and samples, + /// then drops those lanes (`s_andn2_wrexec_b32`). The sample goes to the + /// buffer at dword 16 of the table, at lane * 4. + pub(crate) const WATERFALL_INDEXED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x360E_0081, // v_and_b32 v7, 1, v0 + 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBE95_037E, // s_mov_b32 s21, exec_lo + 0x7E28_0507, // 0x40: v_readfirstlane_b32 s20, v7 + 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 + 0xF40C_0302, + 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 + 0xBF89_FFF6, // s_cbranch_execnz -> 0x40 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + #[test] + fn the_console_waterfall_over_a_first_lane_offset_is_one() { + let r = waterfall(WATERFALL_INDEXED_WAVE32, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Loaded { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + let (_, address) = r.scalar.iter().find(|s| s.0 == load).unwrap(); + assert!(address.dynamic.is_some(), "{address:?}"); + assert_eq!(r.waterfall.compares.len(), 1); + assert_eq!(r.waterfall.reads.len(), 1); + assert_eq!(r.waterfall.loads, [load]); + } + + /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes + /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`, + /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the + /// first entry, the rest the second). + pub(crate) const WATERFALL_JOINED_MIXED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x3602_0081, // v_and_b32 v1, 1, v0 + 0x3402_0285, // v_lshlrev_b32 v1, 5, v1 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0004, // s_cbranch_execz -> 0x68 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xBE94_3D14, // 0x68: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0011, // s_cbranch_execz -> 0xb8 + 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo + 0x7E16_021F, // v_mov_b32 v11, s31 + 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo + 0x887E_147E, // 0xb8: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x7E18_0504, // 0xc4: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0xc4 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + /// A waterfall loop whose descriptor changes on each pass: v[4:11] holds + /// the first table entry on entry and the second after every pass, so + /// the first lane's dwords are phis of the loop header. + pub(crate) const WATERFALL_LOOPED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x7E16_021F, // v_mov_b32 v11, s31 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E18_0504, // 0x64: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0x7E08_0220, // v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x7E10_0224, // v_mov_b32 v8, s36 + 0x7E12_0225, // v_mov_b32 v9, s37 + 0x7E14_0226, // v_mov_b32 v10, s38 + 0x7E16_0227, // v_mov_b32 v11, s39 + 0xBF89_FFDE, // s_cbranch_execnz -> 0x64 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + /// A waterfall loop over one of two buffer descriptors (four dwords) + /// loaded from the table at s0, chosen by nested if/else: lanes below 16 + /// move the first into v[4:7], lanes from 16 to 23 the second, and the + /// others keep what v[4:7] held. Only lanes below 24 (the same mask) + /// run the loop, which loads dword `lane` of the chosen buffer, and + /// store it to the buffer at dword 16 of the table. + pub(crate) const WATERFALL_JOINED_BUFFER_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0602, + 0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0 + 0xF408_0802, + 0xFA00_0020, // s_load_dwordx4 s[32:35], s[4:5], 0x20 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xD4C4_001E, + 0x0002_0098, // v_cmp_gt_u32_e64 s30, 24, v0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0004, // s_cbranch_execz -> 0x50 + 0x7E08_0218, // 0x40: v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0xBE94_3D14, // 0x50: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0007, // s_cbranch_execz -> 0x78 + 0xBE9F_3C1E, // s_and_saveexec_b32 s31, s30 + 0xBF88_0004, // s_cbranch_execz -> 0x74 + 0x7E08_0220, // 0x64: v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x887E_1F7E, // 0x74: s_or_b32 exec_lo, exec_lo, s31 + 0x887E_147E, // 0x78: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_3C1E, // s_and_saveexec_b32 s23, s30 + 0xBF88_0013, // s_cbranch_execz -> 0xd0 + 0xBE9D_037E, // s_mov_b32 s29, exec_lo + 0x7E18_0504, // 0x88: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xE030_1000, + 0x8003_0C10, // buffer_load_dword v12, v16, s[12:15], 0 offen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFF1, // s_cbranch_execnz -> 0x88 + 0xBEFE_031D, // s_mov_b32 exec_lo, s29 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0x887E_177E, // 0xd0: s_or_b32 exec_lo, exec_lo, s23 + 0xBF81_0000, // s_endpgm + ]; + + fn waterfall(words: &[u32], wave64: bool) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, wave64, 256).unwrap(); + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + track(&p, &layout, HwStage::Cs, lanes(&p).as_ref()) + } + + #[test] + fn descriptors_read_from_the_first_lane_of_per_lane_loads_are_traced_to_them() { + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + ] { + let r = waterfall(words, wave64).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Fetched { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + // The first of the two loads: entry v0 * 32 of the table at s0. + let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1; + assert_eq!((a.param, a.offset), (0, 0)); + assert!(a.dynamic.is_some()); + // The sampler is the same for every lane. + let sampler = r.descriptors.iter().find(|d| d.role == Role::Sampler); + assert!(matches!( + sampler.unwrap().source, + Source::Loaded { first: 0, .. } + )); + // Four 64-bit compares of the first lane's dwords with the lane's + // own; the eight reads become the lane's own dwords. + assert_eq!(r.waterfall.compares.len(), 4); + assert_eq!(r.waterfall.reads.len(), 8); + } + } + + #[test] + fn descriptors_read_from_the_first_lane_of_a_per_lane_choice_are_traced_per_lane() { + let r = waterfall(WATERFALL_PICKED_WAVE32, false).unwrap(); + let image = &r.descriptors[0]; + let Source::Lanes { args, .. } = &image.source else { + panic!("{:?}", image.source) + }; + // Lanes with their bit set take the first load (offset 0), the + // others the second (0x20). + let offsets: Vec = args + .iter() + .map(|a| match *a { + Source::Loaded { load, first: 0 } => { + r.scalar.iter().find(|s| s.0 == load).unwrap().1.offset + } + ref a => panic!("{a:?}"), + }) + .collect(); + assert_eq!(offsets, [0, 0x20]); + assert_eq!(r.waterfall.compares.len(), 4); + } + + #[test] + fn a_first_lane_read_outside_a_loop_is_no_waterfall() { + // The waterfall without its back edge: the s_cbranch_execnz is an + // s_nop, so lanes the first one does not match never get a pass. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + let back = words.iter().position(|&w| w == 0xBF89_FFE6).unwrap(); + words[back] = 0xBF80_0000; + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + } + ), + "{err:?}" + ); + } + + /// Why resource tracking refuses `words`. + fn refusal(words: &[u32], wave64: bool) -> &'static str { + match waterfall(words, wave64) { + Err(ShaderError::Unsupported { what, .. }) => what, + other => panic!("not refused: {other:?}"), + } + } + + const NO_LOOP: &str = "a descriptor read from the first lane outside a waterfall loop"; + const NOT_SELECTED: &str = "a waterfall loop whose compares do not select the access's lanes"; + const BAD_RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting"; + const SPLIT: &str = "a waterfall loop nested in another or split over blocks"; + + /// The index of `word` in `words`. + fn word_at(words: &[u32], word: u32) -> usize { + words.iter().position(|&w| w == word).unwrap() + } + + #[test] + fn a_first_lane_read_without_its_compare_is_no_waterfall() { + // The loop without the compare of dwords 0 and 1: nothing makes + // the first lane's dwords the lane's own there. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + let cmp = word_at(&words, 0x0002_080C); + words[cmp - 1..=cmp].copy_from_slice(&[0xBF80_0000, 0xBF80_0000]); + assert_eq!(refusal(&words, false), NOT_SELECTED); + } + + #[test] + fn a_compare_that_does_not_mask_the_access_is_no_waterfall() { + // The compares are all there, but their result never narrows EXEC: + // every lane samples with the first lane's descriptor (reported by + // ifBars on upstream PR #566). + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let save = word_at(&words, 0xBE95_3C15); + words[save] = 0xBE95_037E; // s_mov_b32 s21, exec_lo + assert_eq!(refusal(&words, false), NOT_SELECTED); + } + + #[test] + fn an_access_under_a_further_mask_is_no_waterfall() { + // The access runs for the matching lanes that VCC also holds, yet + // the retry removes every matching lane. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let nop = word_at(&words, 0xBE95_3C15) + 1; + assert_eq!(words[nop], 0xBF80_0000); + words[nop] = 0x877E_6A7E; // s_and_b32 exec_lo, exec_lo, vcc_lo + assert_eq!(refusal(&words, false), NOT_SELECTED); + } + + #[test] + fn a_loop_that_drops_unmatched_lanes_is_no_waterfall() { + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let retry = word_at(&words, 0x897E_157E); + words[retry] = 0xBEFE_0380; // s_mov_b32 exec_lo, 0 + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_retry_that_keeps_other_lanes_than_those_waiting_is_no_waterfall() { + // The retry keeps the lanes of VCC that did not just sample, not + // the waiting ones: lanes 16 and up never sample on the console. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let retry = word_at(&words, 0x897E_157E); + words[retry] = 0x8A7E_7E6A; // s_andn2_b32 exec_lo, vcc_lo, exec_lo + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_wave64_retry_of_one_half_is_no_waterfall() { + // Only the low half of EXEC loses the lanes just served. + let mut words = WATERFALL_FETCHED_WAVE64.to_vec(); + let retry = word_at(&words, 0x89FE_167E); + words[retry] = 0x897E_167E; // s_xor_b32 exec_lo, exec_lo, s22 + assert_eq!(refusal(&words, true), BAD_RETRY); + } + + #[test] + fn a_descriptor_used_after_exec_is_restored_is_no_waterfall() { + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let sample = word_at(&words, 0xF09C_0F08); + let restore = word_at(&words, 0xBEFE_0317); + let image = [words[sample], words[sample + 1]]; + words[sample..sample + 2].fill(0xBF80_0000); // Keep the branch offsets. + words.splice(restore + 1..restore + 1, image); + assert_eq!(refusal(&words, false), NO_LOOP); + } + + #[test] + fn a_wave64_access_with_exec_hi_overwritten_is_no_waterfall() { + let mut words = WATERFALL_FETCHED_WAVE64.to_vec(); + let save = word_at(&words, 0xBE96_2416); + words[save + 1] = 0xBEFF_03C1; // s_mov_b32 exec_hi, -1 + assert_eq!(refusal(&words, true), NOT_SELECTED); + } + + /// The waterfall with `v_cmpx_eq` narrowing EXEC itself, and the retry + /// as `todo & !EXEC` (`folded`: in one `s_andn2_wrexec`), as LLVM's + /// AMDGPU backend writes it for GFX10 and later. + pub(crate) fn cmpx_waterfall(wave64: bool, folded: bool) -> Vec { + let (base, todo, restore): (&[u32], u32, u32) = if wave64 { + (WATERFALL_FETCHED_WAVE64, 0xBE94_047E, 0xBEFE_0414) + } else { + (WATERFALL_JOINED_WAVE32, 0xBE97_037E, 0xBEFE_0317) + }; + let reads = word_at(base, 0x7E18_0504); + let sample = word_at(base, 0xF09C_0F08); + let mut w = base[..=word_at(base, todo)].to_vec(); + // s_mov_b32 s21, exec_lo / s_mov_b64 s[22:23], exec + w.push(if wave64 { 0xBE96_047E } else { 0xBE95_037E }); + w.extend(&base[reads..reads + 8]); // v_readfirstlane_b32 s12..s19 + w.extend([ + 0x7DE4_080C, // v_cmpx_eq_u64 s[12:13], v[4:5] + 0x7DE4_0C0E, // v_cmpx_eq_u64 s[14:15], v[6:7] + 0x7DE4_1010, // v_cmpx_eq_u64 s[16:17], v[8:9] + 0x7DE4_1412, // v_cmpx_eq_u64 s[18:19], v[10:11] + ]); + w.extend(&base[sample..sample + 2]); // image_sample_lz + match (wave64, folded) { + // s_andn2_wrexec_b32 s21, s21; s_cbranch_execnz + (false, true) => w.extend([0xBE95_4715, 0xBF89_FFF0]), + // s_andn2_b32 s21, s21, exec_lo; s_mov_b32 exec_lo, s21 + (false, false) => w.extend([0x8A15_7E15, 0xBEFE_0315, 0xBF89_FFEF]), + // s_andn2_wrexec_b64 s[22:23], s[22:23] + (true, true) => w.extend([0xBE96_3A16, 0xBF89_FFF0]), + // s_andn2_b64 s[22:23], s[22:23], exec; s_mov_b64 exec, s[22:23] + (true, false) => w.extend([0x8A96_7E16, 0xBEFE_0416, 0xBF89_FFEF]), + } + w.extend(&base[word_at(base, restore)..]); + w + } + + #[test] + fn a_waterfall_narrowed_by_v_cmpx_is_one() { + for wave64 in [false, true] { + for folded in [false, true] { + let r = waterfall(&cmpx_waterfall(wave64, folded), wave64) + .unwrap_or_else(|e| panic!("wave64 {wave64} folded {folded}: {e:?}")); + assert_eq!(r.waterfall.compares.len(), 4, "{wave64} {folded}"); + assert_eq!(r.waterfall.reads.len(), 8, "{wave64} {folded}"); + } + } + } + + #[test] + fn a_v_cmpx_waterfall_whose_retry_drops_lanes_is_none() { + let mut words = cmpx_waterfall(false, false); + let retry = word_at(&words, 0x8A15_7E15); + words[retry] = 0x8A15_7E6A; // s_andn2_b32 s21, vcc_lo, exec_lo + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_waterfall_nested_in_another_is_refused_by_name() { + // An image whose resource and sampler are both per lane, with one + // loop per operand, the one for the sampler inside the one for the + // resource (what the SelectionDAG legalisation in LLVM would give). + // The console gives each lane its own pair. Refused for now: the + // access of the inner loop reads the first-lane dwords of the outer + // loop, which another block holds. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x3602_0081, // v_and_b32 v1, 1, v0 + 0x3402_0285, // v_lshlrev_b32 v1, 5, v1 + 0x3622_0080, // v_and_b32 v17, 0, v0 + 0x3422_2284, // v_lshlrev_b32 v17, 4, v17 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xDC38_8000, + 0x1406_0011, // global_load_dwordx4 v[20:23], v17, s[6:7] + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_037E, // s_mov_b32 s20, exec_lo + // L1, the loop over the resource: + 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, + 0x7E1C_0506, + 0x7E1E_0507, + 0x7E20_0508, + 0x7E22_0509, + 0x7E24_050A, + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBE9A_037E, // s_mov_b32 s26, exec_lo + // L2, the loop over the sampler: + 0x7E10_0514, // v_readfirstlane_b32 s8, v20 + 0x7E12_0515, // v_readfirstlane_b32 s9, v21 + 0x7E14_0516, // v_readfirstlane_b32 s10, v22 + 0x7E16_0517, // v_readfirstlane_b32 s11, v23 + 0xD4E2_0018, + 0x0002_2808, // v_cmp_eq_u64_e64 s24, s[8:9], v[20:21] + 0xD4E2_0019, + 0x0002_2C0A, // v_cmp_eq_u64_e64 s25, s[10:11], v[22:23] + 0x8718_1918, // s_and_b32 s24, s24, s25 + 0xBE98_3C18, // s_and_saveexec_b32 s24, s24 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + 0x897E_187E, // s_xor_b32 exec_lo, exec_lo, s24 + 0xBF89_FFF2, // s_cbranch_execnz L2 + 0xBEFE_031A, // s_mov_b32 exec_lo, s26 + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFDA, // s_cbranch_execnz L1 + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + assert_eq!(refusal(&words, false), SPLIT); + } + + #[test] + fn descriptors_read_from_the_first_lane_of_lds_fail_naming_it() { + // The waterfall over descriptors each lane read from LDS: + // ds_read_b128 v[4:7], v1 and ds_read_b128 v[8:11], v1 offset:16 + // in place of the global loads. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + words[5..9].copy_from_slice(&[0xDBFC_0000, 0x0400_0001, 0xDBFC_0010, 0x0800_0001]); + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of an LDS read", + .. + } + ), + "{err:?}" + ); + } + + /// The block of `p` at byte `offset`. + fn block_at(words: &[u32], offset: usize) -> usize { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + p.blocks.iter().position(|b| b.offset == offset).unwrap() + } + + /// The table offset of what the scalar load of `s` reads. + fn table_offset(r: &Resources, s: &Source) -> u32 { + match *s { + Source::Loaded { load, first: 0 } => { + r.scalar.iter().find(|x| x.0 == load).unwrap().1.offset + } + ref s => panic!("{s:?}"), + } + } + + #[test] + fn descriptors_read_from_the_first_lane_of_an_if_else_join_are_traced_per_path() { + let words = WATERFALL_JOINED_WAVE32; + let r = waterfall(words, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + // The join after the else arm: lanes that ran it (lanes from 16 on) + // take the second entry (0x20); the others come through the flow + // block, whose join gives lanes that ran the then arm the first one + // (0). No lane that skipped the then arm comes that way, so the + // dwords they held before (the inputs) are not traced. + let Source::LanePhi { block, args } = &image.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0x9c)); + let [Some(flow), Some(other)] = &args[..] else { + panic!("{args:?}") + }; + assert_eq!(table_offset(&r, other), 0x20); + let Source::LanePhi { block, args } = flow else { + panic!("{flow:?}") + }; + assert_eq!(*block, block_at(words, 0x70)); + let [None, Some(then)] = &args[..] else { + panic!("{args:?}") + }; + assert_eq!(table_offset(&r, then), 0); + // The loop's compares are of the joined dwords; still recognised. + assert_eq!(r.waterfall.compares.len(), 4); + assert_eq!(r.waterfall.reads.len(), 8); + // Without the lanes' paths the join is refused. + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + let err = track(&p, &layout, HwStage::Cs, None).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of a phi, without the lanes' paths", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn descriptors_joined_from_a_per_lane_load_and_a_per_lane_choice_are_traced_per_path() { + let words = WATERFALL_JOINED_MIXED_WAVE32; + let r = waterfall(words, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + let Source::LanePhi { block, args } = &image.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0xb8)); + let [ + Some(Source::LanePhi { args: flow, .. }), + Some(Source::Lanes { args: picked, .. }), + ] = &args[..] + else { + panic!("{args:?}") + }; + // The then arm loads each lane's entry from the table at s0. + let [None, Some(Source::Fetched { load, first: 0 })] = flow[..] else { + panic!("{flow:?}") + }; + let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1; + assert_eq!((a.param, a.offset), (0, 0)); + assert!(a.dynamic.is_some()); + // The else arm picks the first entry where vcc is set. + let offsets: Vec = picked.iter().map(|s| table_offset(&r, s)).collect(); + assert_eq!(offsets, [0, 0x20]); + assert_eq!(r.waterfall.compares.len(), 4); + } + + #[test] + fn a_descriptor_read_from_the_first_lane_of_a_loop_phi_fails_naming_it() { + let err = waterfall(WATERFALL_LOOPED_WAVE32, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of a phi at a loop header", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn a_per_lane_descriptor_some_lanes_do_not_write_fails() { + // The else arm of WATERFALL_JOINED_WAVE32 not skipped (its + // s_cbranch_execz an s_nop): it runs with EXEC clear in the lanes + // of the then arm, which keep the first entry; the second is not + // every lane's. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let skip = words.iter().rposition(|&w| w == 0xBF88_0008).unwrap(); + words[skip] = 0xBF80_0000; + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a per-lane descriptor written where some lanes may keep the old one", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn a_buffer_descriptor_joined_per_lane_is_traced_on_the_paths_of_lanes_that_load() { + let words = WATERFALL_JOINED_BUFFER_WAVE32; + let r = waterfall(words, false).unwrap(); + let buffer = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + // The outer join: lanes from the else arm's inner join, or (below + // 16) through the flow block. + let Source::LanePhi { block, args } = &buffer.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0x78)); + let [ + Some(Source::LanePhi { args: flow, .. }), + Some(Source::LanePhi { + block: inner, + args: nested, + }), + ] = &args[..] + else { + panic!("{args:?}") + }; + let [None, Some(then)] = &flow[..] else { + panic!("{flow:?}") + }; + assert_eq!(table_offset(&r, then), 0); + // Lanes from 24 on skip the inner arm and keep the inputs, but do + // not load: that edge is not traced. + assert_eq!(*inner, block_at(words, 0x74)); + let [None, Some(other)] = &nested[..] else { + panic!("{nested:?}") + }; + assert_eq!(table_offset(&r, other), 0x20); + assert_eq!(r.waterfall.compares.len(), 2); + assert_eq!(r.waterfall.reads.len(), 4); + } } diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index 013e5458e9..e1dc04dfe5 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -138,6 +138,8 @@ const MAX_NODES: usize = 1 << 21; /// Cap the `ite` memo table so complex shaders cannot trigger multi-tens-of-MB /// HashMap resizes (e.g. 35 MB at 2^21 buckets) under concurrent compilation. const MAX_MEMO: usize = 1 << 18; +/// Case splits [`Bools::meet`] makes before it gives up. +const MAX_MEET: usize = 1 << 16; impl Bools { fn new() -> Self { @@ -271,6 +273,38 @@ impl Bools { self.ite(a, nb, b) } + /// Whether some lane can satisfy every `(b, holds)` of `all` at once: + /// `b` where `holds`, its negation where not. Yes when the search grows + /// too large to finish. + pub fn meet(&self, all: &[(Bool, bool)]) -> bool { + let mut budget = MAX_MEET; + self.meet_in(all.to_vec(), &mut budget) + } + + fn meet_in(&self, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool { + let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE }; + if all.iter().any(fails) { + return false; + } + all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE); + if all.is_empty() || *budget == 0 { + return true; + } + *budget -= 1; + let top = |b: Bool| self.nodes[b.0 as usize].0; + let v = all.iter().map(|&(b, _)| top(b)).min().expect("not empty"); + [false, true].into_iter().any(|value| { + let next = all + .iter() + .map(|&(b, holds)| { + let (lo, hi) = self.split(b, v); + (if value { hi } else { lo }, holds) + }) + .collect(); + self.meet_in(next, budget) + }) + } + fn implies(&mut self, a: Bool, b: Bool) -> bool { let nb = self.not(b); self.and(a, nb) == Bool::FALSE @@ -377,11 +411,16 @@ pub struct Structured { /// enough (lanes outside EXEC then never get there, so a VGPR write /// needs no old value). Always `None` for scalar instructions. pub guards: Vec>>, + /// Per block: what holds in every lane that enters it (over forward + /// edges; a loop header forgets what its loop redefines). + pub reach: Vec, /// The lane's bit of each lane-mask value, by its low dword's value. pub masks: HashMap, /// Symbolic select conditions, keyed by the destination SSA value. /// A wave64 condition belongs to the exact pair read by the select. pub(crate) select_masks: HashMap, + /// Exact Wave64 pairs for checking masks at their uses. + paired_masks: Map, /// Wave64 masks: low dword's value by the high dword's. pub highs: HashMap, /// Masks (low dwords) set only in lanes whose EXEC bit is set where @@ -390,6 +429,16 @@ pub struct Structured { pub active: HashSet, } +impl Structured { + pub(crate) fn mask_bits(&self, low: Value, high: Option) -> Option { + match high { + Some(high) => self.paired_masks.get(&(low, high)), + None => self.masks.get(&low), + } + .copied() + } +} + /// Builds the per-lane form of `program`. pub fn structure(program: &Program) -> Result { let mut l = Lanes::new(program)?; @@ -661,10 +710,16 @@ impl<'a> Lanes<'a> { .map(|&(lo, hi)| (hi, lo)) .collect(), select_masks: self.select_masks, + paired_masks: if self.p.wave64 { + self.masks + } else { + Map::default() + }, active: self.active, bools: self.b, exits, guards, + reach: cond.to_vec(), }) } diff --git a/crates/victory-shader/tests/resource_tracking.rs b/crates/victory-shader/tests/resource_tracking.rs index ea205dd8aa..ddf9e2ce60 100644 --- a/crates/victory-shader/tests/resource_tracking.rs +++ b/crates/victory-shader/tests/resource_tracking.rs @@ -41,7 +41,7 @@ fn unrolled_loads(steps: u32, loads_per_step: u32) -> Program { #[test] fn tracks_every_offset_in_a_shared_address_chain() { let program = unrolled_loads(32, 4); - let tracked = track(&program, &[TABLE], HwStage::Ps).unwrap(); + let tracked = track(&program, &[TABLE], HwStage::Ps, None).unwrap(); let expected: Vec<_> = (1..=32) .flat_map(|step| (0..4).map(move |field| (16 * step + 4 * field, None))) .collect(); @@ -75,7 +75,7 @@ fn shared_address_keeps_its_dynamic_term_and_wraps_offsets() { .find(|(r, _)| *r == Reg::S(9)) .unwrap() .1; - let tracked = track(&program, &[TABLE], HwStage::Ps).unwrap(); + let tracked = track(&program, &[TABLE], HwStage::Ps, None).unwrap(); assert_eq!( tracked.scalar, [ @@ -112,7 +112,7 @@ fn shared_sum_with_two_dynamic_terms_stays_opaque() { END, ]); let dynamic = program.blocks[0].insts[1].write(Reg::S(4)).unwrap(); - let tracked = track(&program, &[TABLE], HwStage::Ps).unwrap(); + let tracked = track(&program, &[TABLE], HwStage::Ps, None).unwrap(); assert_eq!( tracked.scalar, [ @@ -135,7 +135,7 @@ fn shared_sum_with_two_dynamic_terms_stays_opaque() { ] ); assert_eq!( - track(&program, &[], HwStage::Ps).unwrap_err(), + track(&program, &[], HwStage::Ps, None).unwrap_err(), ShaderError::Unsupported { offset: 12, what: "an address not from a root parameter", @@ -152,14 +152,18 @@ fn bench_unrolled_loads() { let program = unrolled_loads(steps, loads); let layout = [TABLE]; assert_eq!( - track(&program, &layout, HwStage::Ps).unwrap().scalar.len(), + track(&program, &layout, HwStage::Ps, None) + .unwrap() + .scalar + .len(), (steps * loads) as usize ); let mut samples = [0.0; 7]; for sample in &mut samples { let start = Instant::now(); for _ in 0..iterations { - let tracked = track(black_box(&program), black_box(&layout), HwStage::Ps).unwrap(); + let tracked = + track(black_box(&program), black_box(&layout), HwStage::Ps, None).unwrap(); black_box(tracked); } *sample = start.elapsed().as_secs_f64() * 1e6 / f64::from(iterations); diff --git a/docs/architecture.md b/docs/architecture.md index a4ed32a50f..56acf4cfd5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -89,6 +89,11 @@ removes EXEC: lane masks become per-lane booleans, wave-wide mask tests become per-lane branches, and vector instructions keep a guard only where a lane can reach them with its EXEC bit clear. `victory_shader::resource` traces each descriptor and scalar memory address to the root parameter it -comes from (table, heap, root descriptor or constant). `victory translate` +comes from (table, heap, root descriptor or constant). A descriptor a +waterfall loop reads from the first lane (`v_readfirstlane_b32`) is traced +to the per-lane load or choice that gives each lane its own (a mask's +`v_cndmask_b32`, or an if/else whose arms each set it: traced on the paths +the lanes take, from structurisation), and accessed with a non-uniform heap +index in one pass. `victory translate` runs every shader it finds (containers, SGD5 files) through these and lists what they cannot handle yet. From ac62f72d6d40b4c3831f0b8826c2604e4123c5e8 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:06:50 +0000 Subject: [PATCH 028/123] GPU: view heaps stay within the device's descriptor limit A title heap of 2^20 descriptors plus the 2^18 dynamic range asked for a 1,310,720-view shader-visible heap. NVIDIA creates it without an error, but the runtime refuses it (debug layer #645, CREATE_DESCRIPTOR_HEAP_INVALID) and the device is removed once it is used (upstream Marvisak/VIctory#735, RTX 4060 Laptop). The sizing only fell back when creation failed, so it never did there. Heap sizes are now planned against the device's limit: what D3D12_OPTIONS19 reports as MaxViewDescriptorHeapSize (Agility runtimes), else the spec's 1,000,000. The larger dynamic range where it fits on top of every title slot, else the smaller one, else the title's slots are cut so the smaller one still fits, as the old cap did. The diagnosis is LAKSHYA-cmd-tech's (fork branch fix/gpu-resource-format-flags-and-heap-limit); this takes the limit from the device instead of a constant. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/descriptor/host.rs | 107 ++++++++++++++++++---- 1 file changed, 91 insertions(+), 16 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 98eae48935..3cd416788b 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -63,10 +63,51 @@ pub(crate) fn near_heaps(va: u64) -> String { text } -/// The host's limit for shader-visible view heaps on resource binding -/// tiers 1 and 2; tier 3 hardware may take more. +/// The host's limit for shader-visible view heaps on every resource +/// binding tier, unless the device reports a larger one +/// ([`max_view_heap`]). NVIDIA creates a larger heap without an error, +/// but the runtime refuses it (debug layer #645) and the device is removed +/// once it is used (upstream #735). const PORTABLE_VIEWS: u32 = 1_000_000; +/// The largest shader-visible view heap the device takes: what +/// `D3D12_OPTIONS19` reports (Agility runtimes), else [`PORTABLE_VIEWS`]. +fn max_view_heap(host: &Host) -> u32 { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + // SAFETY: the query writes its own structure of the given size. + let asked = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS19, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + match asked { + Ok(()) => options.MaxViewDescriptorHeapSize.max(PORTABLE_VIEWS), + Err(_) => PORTABLE_VIEWS, + } +} + +/// The view heaps to try for `count` title slots on a device that takes +/// `limit` views, in order: (heap size, title slots, dynamic slots). The +/// larger dynamic range where it fits on top of every title slot, else the +/// smaller one, else the title's slots are cut so that the smaller one +/// still fits (shortcut: descriptors past the host's limit are left out; a +/// title that reaches them needs remapping). None is over `limit`. +fn view_heap_sizes(count: u32, limit: u32) -> Vec<(u32, u32, u32)> { + let mut sizes: Vec<(u32, u32, u32)> = [DYNAMIC, MIN_DYNAMIC] + .into_iter() + .filter_map(|extra| { + let size = count.checked_add(extra)?; + (size <= limit).then_some((size, count, extra)) + }) + .collect(); + if count.saturating_add(MIN_DYNAMIC) > limit { + sizes.push((limit, limit.saturating_sub(MIN_DYNAMIC), MIN_DYNAMIC)); + } + sizes +} + /// Slots past the title's in a view heap, for tables a draw needs made /// afresh (constant buffers copied per draw). A list holds the slots it /// took until it is reset (its submissions have run) or released. @@ -125,25 +166,26 @@ impl HostHeap { SAMPLER_DYNAMIC, ); } - // View heaps: the larger dynamic range only where the host takes it - // on top of every title slot; else the smaller one, and the cap - // after that. let made = if sampler { make(count).map(|heap| (heap, count, 0)) - } else if let Ok(heap) = make(count.saturating_add(DYNAMIC)) { - Ok((heap, count, DYNAMIC)) } else { - match make(count.saturating_add(MIN_DYNAMIC)) { - Ok(heap) => Ok((heap, count, MIN_DYNAMIC)), - Err(e) if count.saturating_add(MIN_DYNAMIC) > PORTABLE_VIEWS => { - // shortcut: descriptors past the host's limit are left - // out; a title that reaches them needs remapping. - tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); - make(PORTABLE_VIEWS) - .map(|heap| (heap, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC)) + let limit = max_view_heap(host); + let mut tried = view_heap_sizes(count, limit).into_iter(); + // Never empty: the last size fits `limit` by construction. + let (size, titles, extra) = tried.next()?; + let mut made = make(size).map(|heap| (heap, titles, extra)); + for (size, titles, extra) in tried { + if made.is_ok() { + break; } - Err(e) => Err(e), + made = make(size).map(|heap| (heap, titles, extra)); + } + if let Ok((_, titles, extra)) = &made + && *titles < count + { + tracing::warn!(count, limit, "host view heap capped at {}", titles + extra); } + made }; let (heap, count, extra) = match made { Ok(made) => made, @@ -1133,6 +1175,39 @@ mod tests { ); } + /// A view heap is never sized past what the device takes: 2^20 title + /// slots plus the dynamic range asked for 1,310,720 views on a device + /// that takes 1,000,000 (upstream #735). + #[test] + fn view_heaps_stay_within_the_device_limit() { + let capped = view_heap_sizes(1 << 20, PORTABLE_VIEWS); + assert_eq!( + capped, + [(PORTABLE_VIEWS, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC)] + ); + assert_eq!( + view_heap_sizes(4, PORTABLE_VIEWS), + [(4 + DYNAMIC, 4, DYNAMIC), (4 + MIN_DYNAMIC, 4, MIN_DYNAMIC)] + ); + let only_small = PORTABLE_VIEWS - DYNAMIC + 1; + assert_eq!( + view_heap_sizes(only_small, PORTABLE_VIEWS), + [(only_small + MIN_DYNAMIC, only_small, MIN_DYNAMIC)] + ); + // A device that reports a larger limit gets the larger range. + assert_eq!( + view_heap_sizes(1 << 20, 1 << 21)[0], + ((1 << 20) + DYNAMIC, 1 << 20, DYNAMIC) + ); + for count in [0, 1, 999_999, 1_000_000, u32::MAX] { + let sizes = view_heap_sizes(count, PORTABLE_VIEWS); + assert!(!sizes.is_empty()); + for (size, titles, extra) in sizes { + assert!(size <= PORTABLE_VIEWS && titles + extra == size && titles <= count); + } + } + } + /// Dynamic slots stay taken until given back, and runs do not wrap. #[test] fn dynamic_slots_are_held_until_released() { From f32ed7405235a99de435e097e76b98481d2732d9 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:08:58 +0000 Subject: [PATCH 029/123] GPU: B5G5R5A1 and B4G4R4A4 targets are made as RGBA8 PC D3D12 has no unordered access on B5G5R5A1_UNORM (86) and no render target on B4G4R4A4_UNORM (115). Titles create both (upstream Marvisak/VIctory#735, the debug layer refuses them; #741 sees 86 at 2560x1440 with flags 5), and the refused texture left the title with a null resource. Render target and unordered-access textures of either are now made in R8G8B8A8_UNORM, the same channels with more bits, through resource::target_format like R9G9B9E5 -> RGBA16F already was, so their views, render target views and pipelines' target formats follow. Sampled-only textures keep their format, so title uploads are unchanged. A copy between a substituted target and a texture in the title's own format would be a cross-family copy the runtime refuses: CopyResource, texture region copies and readbacks now skip those with a one-time warning. The format list is LAKSHYA-cmd-tech's diagnosis (fork branch fix/gpu-resource-format-flags-and-heap-limit), which clears the flags; this keeps the title's render and UAV use working instead. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/list.rs | 58 ++++++++++++++++++++++++++++++ crates/victory-gpu/src/resource.rs | 57 +++++++++++++++++++++-------- 2 files changed, 100 insertions(+), 15 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index a7e5031a1b..728decc6cf 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -502,6 +502,38 @@ extern "system" fn copy_buffer_region( let _ = (this, dst, dst_offset, src, src_offset, len); } +/// Whether host formats `a` and `b` can meet in one copy: the same family. +/// A render target or UAV texture whose console format PC forbids is made +/// in another format (`resource::target_format`); a copy between it and a +/// texture of the title's own format would be refused by the runtime, so it +/// is skipped. +#[cfg(any(windows, test))] +fn same_family(a: u32, b: u32) -> bool { + let ok = a == b || crate::resource::family(a) == crate::resource::family(b); + if !ok { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!( + a, + b, + "texture copy between formats of different families skipped (a substituted target)", + ); + }); + } + ok +} + +/// [`same_family`] for two host resources. +#[cfg(windows)] +fn copyable( + to: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, + from: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, +) -> bool { + // SAFETY: live resources. + let (a, b) = unsafe { (to.GetDesc().Format.0, from.GetDesc().Format.0) }; + same_family(a as u32, b as u32) +} + extern "system" fn copy_resource(this: This, dst: This, src: This) { #[cfg(windows)] { @@ -512,6 +544,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::host_resource(dst), crate::resource::host_resource(src), ) { + if !copyable(to, from) { + return; + } // A texture the title fills through memory has its contents in // the staging copy until an upload records them. if crate::texture::title_written(from) { @@ -607,6 +642,11 @@ extern "system" fn copy_texture_region( }); return; } + // SAFETY: a live texture. + let from_format = unsafe { from_tex.GetDesc() }.Format.0 as u32; + if !same_family(from_format, host_format) { + return; + } if total == 0 || lines == 0 || row_bytes == 0 { return; } @@ -714,6 +754,9 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; + if !copyable(to, texture) { + return; + } if crate::texture::title_written(texture) { crate::texture::upload(&list, src.resource, texture); } @@ -1592,6 +1635,21 @@ mod tests { use super::*; use crate::object::slot; + /// A texture made in a substituted target format meets only its own + /// family in a copy (upstream #735): RGBA8 and its typeless and sRGB + /// twins copy, the title's B5G5R5A1 or R9G9B9E5 textures do not. + #[test] + fn copies_stay_within_a_format_family() { + use crate::resource::target_format; + assert!(same_family(28, 28)); + assert!(same_family(27, 29)); + assert!(same_family(10, 2 + 8)); + assert!(!same_family(target_format(86), 86)); + assert!(!same_family(target_format(115), 115)); + assert!(!same_family(target_format(67), 67)); + assert!(same_family(86, 86)); + } + #[cfg(windows)] #[test] fn command_list_creation_keeps_the_initial_pipeline() { diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index eebd4b74a9..1d89c498d1 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -238,18 +238,24 @@ pub(crate) fn pc_format(format: u32) -> u32 { } /// The format a render target or unordered-access texture of `format` is -/// made in on the host, and that render target views and pipelines name: -/// `R16G16B16A16_FLOAT` (10) for `R9G9B9E5_SHAREDEXP` (67), which PC D3D12 -/// forbids as a render target or unordered-access resource; else -/// [`pc_format`]. Textures only sampled keep `R9G9B9E5_SHAREDEXP`. +/// made in on the host, and that render target views and pipelines name, +/// for formats PC D3D12 forbids as one or the other: `R16G16B16A16_FLOAT` +/// (10) for `R9G9B9E5_SHAREDEXP` (67), and `R8G8B8A8_UNORM` (28), the same +/// channels with more bits, for `B5G5R5A1_UNORM` (86, no unordered access) +/// and `B4G4R4A4_UNORM` (115, no render target); else [`pc_format`]. +/// Textures only sampled keep their format. The host refused these +/// textures outright before (upstream #735, #741): the title's resource was +/// null. pub(crate) fn target_format(format: u32) -> u32 { const R9G9B9E5_SHAREDEXP: u32 = 67; const RGBA16_FLOAT: u32 = 10; - let format = pc_format(format); - if format == R9G9B9E5_SHAREDEXP { - RGBA16_FLOAT - } else { - format + const B5G5R5A1_UNORM: u32 = 86; + const B4G4R4A4_UNORM: u32 = 115; + const RGBA8_UNORM: u32 = 28; + match pc_format(format) { + R9G9B9E5_SHAREDEXP => RGBA16_FLOAT, + B5G5R5A1_UNORM | B4G4R4A4_UNORM => RGBA8_UNORM, + format => format, } } @@ -2525,9 +2531,18 @@ void main() { assert_eq!(target_format(118), 45); } + #[test] + fn small_unorm_targets_substitute_rgba8() { + assert_eq!(target_format(86), 28); + assert_eq!(target_format(115), 28); + // Sampled copies keep their format; B5G6R5 renders on PC. + assert_eq!(pc_format(86), 86); + assert_eq!(target_format(85), 85); + } + #[cfg(windows)] #[test] - fn r9g9b9e5_render_target_and_uav_textures_create_on_host() { + fn substituted_render_target_and_uav_textures_create_on_host() { if crate::host::host().is_none() { return; } @@ -2544,8 +2559,20 @@ void main() { layout: 0, flags, }; - for (flags, expected_host_format) in [(0, 67), (4, 10), (5, 10)] { - let d = tex_desc(flags); + for (format, flags, expected_host_format) in [ + (67, 0, 67), + (67, 4, 10), + (67, 5, 10), + // B5G5R5A1 has no unordered access on PC, B4G4R4A4 no render + // target (upstream #735). + (86, 0, 86), + (86, 5, 28), + (115, 1, 28), + ] { + let d = ResourceDesc { + format, + ..tex_desc(flags) + }; let mut out = std::ptr::null(); let hr = create_committed( std::ptr::null(), @@ -2557,12 +2584,12 @@ void main() { &RESOURCE_IIDS[0], &mut out, ); - assert_eq!(hr, S_OK, "flags {flags}"); + assert_eq!(hr, S_OK, "format {format} flags {flags}"); let host = host_resource(out).expect("host texture created"); // SAFETY: a live host texture. let got = unsafe { host.GetDesc() }.Format.0 as u32; - assert_eq!(got, expected_host_format, "flags {flags}"); - assert_eq!(view_format(out), None, "flags {flags}"); + assert_eq!(got, expected_host_format, "format {format} flags {flags}"); + assert_eq!(view_format(out), None, "format {format} flags {flags}"); assert_eq!(slot::(out, 0x10)(out), 0); } } From 73b2ae60f3533a38c98a42825e00949cb1378454 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:10:17 +0000 Subject: [PATCH 030/123] GPU: a copied texture uploads again once the title rewrites its memory Once a copy or resolve wrote a texture, upload() skipped it for good, so a texture copied into once kept its old contents when the title later streamed new mips into its memory (upstream Marvisak/VIctory#758). The copy now records the write-watch asking it happened at. A later upload asks the watch again: if a watch page wholly inside the texture was written after the copy, the texture goes back to taking its contents from title memory. Pages shared with a neighbour do not count, so a neighbour's writes cannot send stale memory over the copy; memory that is not watched keeps the copy, as before. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/texture.rs | 100 +++++++++++++++++++++++++----- 1 file changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 41805dfecd..318d72d180 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -71,14 +71,70 @@ thread_local! { } /// Textures the host GPU wrote by a copy or resolve: their contents are on -/// the host, not in title memory, which stays as it was. -static HOST_WRITTEN: Mutex>> = Mutex::new(None); +/// the host, not in title memory, which stays as it was. Each with the +/// write-watch asking at the copy (0: its memory is not watched). +static HOST_WRITTEN: Mutex>> = Mutex::new(None); + +/// A texture's title memory, `[start, end)`. +fn memory_range(resource: This) -> Option<(usize, usize)> { + let (memory, desc) = crate::resource::texture_memory(resource)?; + let size = crate::resource::texture_layout(&desc)?.planes[0] + .layout + .size; + let start = memory as usize; + Some((start, start.checked_add(usize::try_from(size).ok()?)?)) +} /// A host copy or resolve writes `resource`. pub(crate) fn host_written(resource: This) { - let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - set.get_or_insert_with(Default::default) - .insert(resource as usize); + let asked = memory_range(resource) + .and_then(|(start, end)| crate::watch::writes(start, end, false)) + .map_or(0, |(now, _)| now); + let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + map.get_or_insert_with(Default::default) + .insert(resource as usize, asked); +} + +/// Whether the title wrote a texture's memory `[start, end)` again after +/// the host copied into it at write-watch asking `copied`, given the +/// watch's `(page, asking)` answer. Only watch pages wholly inside the +/// texture count: a neighbour written in a shared page must not send stale +/// memory over the copy. A texture never watched (`copied` 0) keeps the +/// copy. +fn rewritten_since(start: usize, end: usize, copied: u64, written: &[(usize, u64)]) -> bool { + use crate::watch::PAGE; + let (first, last) = (start.div_ceil(PAGE), end / PAGE); + copied != 0 + && written + .iter() + .any(|&(page, asking)| (first..last).contains(&page) && asking > copied) +} + +/// Whether `resource`'s host copy keeps what the host GPU wrote into it: +/// a copy or resolve did, and the title has not written its memory since +/// (upstream #758: a texture copied into once ignored later streaming). +fn keeps_host_contents(resource: This) -> bool { + let copied = { + let map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + match map.as_ref().and_then(|map| map.get(&(resource as usize))) { + Some(&copied) => copied, + None => return false, + } + }; + if copied == 0 { + return true; + } + let rewritten = memory_range(resource).is_some_and(|(start, end)| { + crate::watch::writes(start, end, false) + .is_some_and(|(_, written)| rewritten_since(start, end, copied, &written)) + }); + if rewritten { + let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&(resource as usize)); + } + } + !rewritten } /// The title released a resource. @@ -87,9 +143,9 @@ pub(crate) fn forget(resource: usize) { if let Some(map) = map.as_mut() { map.remove(&resource); } - let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(set) = set.as_mut() { - set.remove(&resource); + let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&resource); } } @@ -106,14 +162,9 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { /// submission if the memory changed. Leaves the texture in the copy /// destination state. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { - let host_written = HOST_WRITTEN - .lock() - .unwrap_or_else(|e| e.into_inner()) - .as_ref() - .is_some_and(|set| set.contains(&(resource as usize))); - // shortcut: a texture the host copied into keeps the host's contents - // even if the title later writes its memory too. - if host_written || !list.first_use(resource as usize) { + // A texture the host copied into keeps the host's contents until the + // title writes its memory again (only noticed where it is watched). + if !list.first_use(resource as usize) || keeps_host_contents(resource) { return; } let Some(staging) = staging(resource, texture) else { @@ -376,6 +427,23 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { mod tests { use super::*; + /// A copied texture uploads again only once the title writes a watch + /// page wholly its own after the copy (upstream #758). + #[test] + fn copied_texture_uploads_again_after_the_title_rewrites_it() { + use crate::watch::PAGE; + let (start, end) = (4 * PAGE, 8 * PAGE); + assert!(!rewritten_since(start, end, 7, &[(4, 6), (5, 7)])); + assert!(rewritten_since(start, end, 7, &[(4, 6), (6, 8)])); + // Never watched: the copy is kept. + assert!(!rewritten_since(start, end, 0, &[(5, 9)])); + // Pages shared with neighbours do not count. + let (start, end) = (4 * PAGE + 256, 6 * PAGE + 256); + assert!(!rewritten_since(start, end, 7, &[(4, 9), (6, 9)])); + assert!(rewritten_since(start, end, 7, &[(5, 9)])); + assert!(!rewritten_since(PAGE + 16, PAGE + 4096, 1, &[(1, 9)])); + } + #[test] fn watched_texture_reads_reuse_space_and_expose_only_current_bytes() { #[cfg(feature = "diagnostics")] From 079e387d6e2ae7edf7a11156a79d24f3628dc2cc Mon Sep 17 00:00:00 2001 From: artor410 <62668404+artor410@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:11:57 +0000 Subject: [PATCH 031/123] GPU: run indirect mesh dispatches through indirect execution DispatchMeshX with an indirect address was dropped, so GPU-driven mesh dispatches (the world's) drew nothing (upstream Marvisak/VIctory#756). They now run through State::execute_indirect as one mesh dispatch (kind 10, stride 12) with its argument clamp; ones the host cannot run are counted with the other dropped indirect work. A direct mesh dispatch with an empty dimension runs nothing. (ported from upstream Marvisak/VIctory#24, commit d5f41f54; the test module conflict with the copy-family test was resolved by keeping both) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/list.rs | 87 +++++++++++++++++++++++++++++----- 1 file changed, 74 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 728decc6cf..b77ef688c2 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1283,19 +1283,33 @@ mod state { super::count_dispatch(); with_state(this, |list, s| s.dispatch(list, x, y, z)); } - /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh - /// programs take `x` groups only. - pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) { - super::count_draw(); - if y * z != 1 { + /// The groups a mesh dispatch of `x` × `y` × `z` groups runs: the + /// title's mesh programs read only the x group id, so `x` (y and z + /// other than 1 are logged once); none if any dimension is empty. + pub(super) fn mesh_groups(x: u32, y: u32, z: u32) -> Option { + if x == 0 || y == 0 || z == 0 { + return None; + } + if y != 1 || z != 1 { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups")); } - with_state(this, |list, s| s.dispatch_mesh(list, x)); + Some(x) } - /// `DispatchMeshX(x, flags, indirect arguments, payload)`. - /// shortcut: dispatches whose group count is in GPU memory (indirect) - /// are dropped; make them ExecuteIndirect when the title uses them. + /// `DispatchMesh(x, y, z)` (the PC method of List6). + pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) { + super::count_draw(); + if let Some(x) = mesh_groups(x, y, z) { + with_state(this, |list, s| s.dispatch_mesh(list, x)); + } + } + /// `DispatchMeshX(x, flags, indirect arguments, payload)`. With an + /// indirect address the group counts are in GPU memory there, run as + /// indirect execution of one mesh dispatch. + /// Inferred, not documented: the arguments are those of a PC indirect + /// mesh dispatch (D3D12_DISPATCH_MESH_ARGUMENTS, three 32-bit group + /// counts, as the title's mesh dispatch signatures have) and `x` is then + /// unused; `flags` and `payload` are unknown. pub(super) extern "system" fn dispatch_mesh_x( this: This, x: u32, @@ -1303,13 +1317,22 @@ mod state { indirect: u64, _payload: u64, ) { + const MESH: u32 = 10; + const STRIDE: u32 = 12; super::count_draw(); - if indirect != 0 { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped")); + if indirect == 0 { + if x != 0 { + with_state(this, |list, s| s.dispatch_mesh(list, x)); + } return; } - with_state(this, |list, s| s.dispatch_mesh(list, x)); + let mut ran = false; + with_state(this, |list, s| { + ran = s.execute_indirect(list, (MESH, STRIDE, 1), indirect, None); + }); + if !ran { + super::INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } } pub(super) extern "system" fn draw_indexed( this: This, @@ -1715,6 +1738,44 @@ mod tests { ); } + /// Mesh programs read only the x group id, so a mesh dispatch runs its + /// x groups; one with no groups in any dimension runs nothing. + #[cfg(windows)] + #[test] + fn mesh_dispatches_run_x_groups_unless_empty() { + use state::mesh_groups; + assert_eq!(mesh_groups(5, 1, 1), Some(5)); + assert_eq!(mesh_groups(0, 1, 1), None); + assert_eq!(mesh_groups(5, 0, 1), None); + assert_eq!(mesh_groups(5, 1, 0), None); + assert_eq!(mesh_groups(5, 2, 3), Some(5)); + assert_eq!(mesh_groups(5, u32::MAX, u32::MAX), Some(5)); + } + + /// An indirect mesh dispatch the host does not run (no host device, as + /// in tests) is counted with the other indirect work dropped. + #[cfg(windows)] + #[test] + fn indirect_mesh_dispatches_not_run_are_counted() { + let null = std::ptr::null(); + let mut allocator = null; + assert_eq!( + create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), + S_OK + ); + let mut list = null; + let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list); + assert_eq!(hr, S_OK); + let arguments = [7u32, 1, 1]; + let before = INDIRECT.load(std::sync::atomic::Ordering::Relaxed); + state::dispatch_mesh_x(list, 0, 0, arguments.as_ptr() as u64, 0); + assert!(INDIRECT.load(std::sync::atomic::Ordering::Relaxed) > before); + assert_eq!(close(list), S_OK); + let release = |o: This| slot:: u32>(o, 0x10)(o); + assert_eq!(release(list), 0); + assert_eq!(release(allocator), 0); + } + #[test] fn every_inline_command_falls_back_to_the_table() { let null = std::ptr::null(); From 4ab908f57576ad484c94f3fb993e16e5809fd0a3 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:13:31 +0000 Subject: [PATCH 032/123] GPU: a capped view heap keeps 2^18 dynamic slots On a heap capped at the device's limit (1,000,000 views on NVIDIA) the title's slots kept their room first and the dynamic range fell to 2^16. The world's fresh tables need far more per submission: most indirect draws and mesh dispatches were dropped as "a descriptor table without dynamic slots" and the G-buffer stayed nearly empty. Testers measured 2^18 on the capped heap at zero such drops, about twice the draws run and most of the G-buffer covered (upstream Marvisak/VIctory#747: RTX 4070 Ti, 5060 Ti, 5070 Ti). A capped heap now takes the full 2^18 dynamic range and cuts the title's mirrored slots to fit (737,856 at a 1,000,000 limit); 2^16 stays only as the fallback for a heap the host refuses. Measurements are Vaximous's, FADZIII's and YouKnowWh's in #747; the same constant change is on LAKSHYA-cmd-tech's branch fix/gpu-descriptor-heaps-caps-and-dynamic-expansion. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/descriptor/host.rs | 55 ++++++++++++----------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 3cd416788b..236e7fd9ee 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -20,7 +20,7 @@ pub(crate) struct HostHeap { /// Slots mirroring the title's; `spare` more follow them. count: u32, /// Dynamic slots past the title's: [`DYNAMIC`] in a view heap (or - /// [`MIN_DYNAMIC`] where the host will not take that many more), + /// [`MIN_DYNAMIC`] where the host refused that heap), /// [`SAMPLER_DYNAMIC`] in a capped sampler heap, none in another. spare: u32, sampler: bool, @@ -90,22 +90,19 @@ fn max_view_heap(host: &Host) -> u32 { /// The view heaps to try for `count` title slots on a device that takes /// `limit` views, in order: (heap size, title slots, dynamic slots). The -/// larger dynamic range where it fits on top of every title slot, else the -/// smaller one, else the title's slots are cut so that the smaller one -/// still fits (shortcut: descriptors past the host's limit are left out; a -/// title that reaches them needs remapping). None is over `limit`. +/// full dynamic range always: on top of every title slot where that fits, +/// else the title's slots are cut to make room for it (shortcut: +/// descriptors past the host's limit are left out; a title that reaches +/// them needs remapping). A capped heap with 2^16 dynamic slots ran dry in +/// every world submission and dropped most indirect draws, where 2^18 +/// dropped none (upstream #747: RTX 4070 Ti, 5060 Ti, 5070 Ti). Then, if +/// the host refuses that, the smaller range. None is over `limit`. fn view_heap_sizes(count: u32, limit: u32) -> Vec<(u32, u32, u32)> { - let mut sizes: Vec<(u32, u32, u32)> = [DYNAMIC, MIN_DYNAMIC] - .into_iter() - .filter_map(|extra| { - let size = count.checked_add(extra)?; - (size <= limit).then_some((size, count, extra)) - }) - .collect(); - if count.saturating_add(MIN_DYNAMIC) > limit { - sizes.push((limit, limit.saturating_sub(MIN_DYNAMIC), MIN_DYNAMIC)); - } - sizes + let planned = |extra: u32| match count.checked_add(extra) { + Some(size) if size <= limit => (size, count, extra), + _ => (limit, limit.saturating_sub(extra), extra), + }; + vec![planned(DYNAMIC), planned(MIN_DYNAMIC)] } /// Slots past the title's in a view heap, for tables a draw needs made @@ -115,8 +112,8 @@ fn view_heap_sizes(count: u32, limit: u32) -> Vec<(u32, u32, u32)> { /// each a device removal shortly after; upstream #59). const DYNAMIC: u32 = 1 << 18; -/// The dynamic slots of a view heap whose host would not take [`DYNAMIC`] -/// more (a capped heap, NVIDIA): the title's slots keep their room first. +/// The dynamic slots of a view heap the host refused with [`DYNAMIC`]: a +/// last resort, too few for the world (upstream #747). const MIN_DYNAMIC: u32 = 1 << 16; /// The host's limit for shader-visible sampler heaps, on every binding @@ -1180,28 +1177,34 @@ mod tests { /// that takes 1,000,000 (upstream #735). #[test] fn view_heaps_stay_within_the_device_limit() { - let capped = view_heap_sizes(1 << 20, PORTABLE_VIEWS); + // 2^20 title slots on a 1M device: the full dynamic range, the + // title's slots cut (upstream #735, #747). assert_eq!( - capped, - [(PORTABLE_VIEWS, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC)] + view_heap_sizes(1 << 20, PORTABLE_VIEWS), + [ + (PORTABLE_VIEWS, PORTABLE_VIEWS - DYNAMIC, DYNAMIC), + (PORTABLE_VIEWS, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC), + ] ); assert_eq!( view_heap_sizes(4, PORTABLE_VIEWS), [(4 + DYNAMIC, 4, DYNAMIC), (4 + MIN_DYNAMIC, 4, MIN_DYNAMIC)] ); - let only_small = PORTABLE_VIEWS - DYNAMIC + 1; assert_eq!( - view_heap_sizes(only_small, PORTABLE_VIEWS), - [(only_small + MIN_DYNAMIC, only_small, MIN_DYNAMIC)] + view_heap_sizes(800_000, PORTABLE_VIEWS), + [ + (PORTABLE_VIEWS, PORTABLE_VIEWS - DYNAMIC, DYNAMIC), + (800_000 + MIN_DYNAMIC, 800_000, MIN_DYNAMIC), + ] ); - // A device that reports a larger limit gets the larger range. + // A device that reports a larger limit keeps every title slot. assert_eq!( view_heap_sizes(1 << 20, 1 << 21)[0], ((1 << 20) + DYNAMIC, 1 << 20, DYNAMIC) ); for count in [0, 1, 999_999, 1_000_000, u32::MAX] { let sizes = view_heap_sizes(count, PORTABLE_VIEWS); - assert!(!sizes.is_empty()); + assert_eq!(sizes[0].2, DYNAMIC); for (size, titles, extra) in sizes { assert!(size <= PORTABLE_VIEWS && titles + extra == size && titles <= count); } From 2fae4dbdc74808b38ec869099d19b18731b9f9c4 Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 10:15:07 +0000 Subject: [PATCH 033/123] GPU: record resource-backed texture UAV clears The title's command list left ClearUnorderedAccessViewUint and ClearUnorderedAccessViewFloat (slots 0x1a8, 0x1b0) on the missing-method stub, so textures it clears through a UAV kept stale contents (upstream Marvisak/VIctory#771). Both now record a host clear for resource-backed textures: the title's CPU and shader-visible views must name the same texture; the host makes a matching pair (a CPU-only slot per list and a dynamic slot in the bound heap, held until the list is reset) and moves the texture to UAV state through the state tracker. Heap binding is split out of bind() as bind_heaps() so a clear can bind the heap outside a draw. Buffer UAV clears are not covered. Verified by the author on an RTX 5090 and WARP: a whole clear then a 2x2 clear of R32_UINT and R32_FLOAT 4x4 textures read back all 32 values, with no debug-layer errors. (ported from fuzeofficlal/VIctory commit d3594990, on upstream ffe310e; conflicts with this branch's depth-state tracking and rectangle scratch resolved by keeping both, bind() keeps this branch's signature; slot and null-value tests added) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/descriptor/host.rs | 44 ++++++++++ crates/victory-gpu/src/draw.rs | 91 +++++++++++++++++++-- crates/victory-gpu/src/host.rs | 27 +++++++ crates/victory-gpu/src/list.rs | 97 ++++++++++++++++++++++- 4 files changed, 250 insertions(+), 9 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 236e7fd9ee..92e839e11a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -388,6 +388,50 @@ impl HostHeap { } } + /// Makes a matched native UAV pair from the CPU view. The GPU slot is + /// held until list reset like the descriptors in a fresh table. + pub(crate) fn clear_texture_uav( + &self, + list: &crate::host::HostList, + texture: &ID3D12Resource, + words: Option<&[u32; 10]>, + ) -> Option<( + u32, + D3D12_GPU_DESCRIPTOR_HANDLE, + D3D12_CPU_DESCRIPTOR_HANDLE, + )> { + let mut desc = words.map(uav_desc); + if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { + return None; + } + let device = &host()?.device; + let cpu = list.clear_uav_cpu()?; + let slot = self.dynamic(1)?; + // SAFETY: both handles name live heap slots. Copy from the + // CPU-only heap to the shader-visible heap. + let gpu = unsafe { + device.CreateUnorderedAccessView( + texture, + None::<&ID3D12Resource>, + desc.as_ref().map(std::ptr::from_ref), + cpu, + ); + device.CopyDescriptorsSimple( + 1, + self.cpu(slot), + cpu, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); + D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: self.heap.GetGPUDescriptorHandleForHeapStart().ptr + + u64::from(slot) * u64::from(self.step), + } + }; + // The list's texture state retains the resource through execution. + self.keep(slot, None); + Some((slot, gpu, cpu)) + } + /// Makes slot `index` (a dynamic one) from `view`; a null view if the /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index cb2dc7b78d..335f05aaea 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -63,6 +63,12 @@ struct DepthTarget { state: u32, } +/// A UAV clear's value, as the title's call gives it. +pub(crate) enum UavClear { + Uint([u32; 4]), + Float([f32; 4]), +} + /// What one title list has set, and what its host list was last given. #[derive(Default)] pub(crate) struct State { @@ -268,7 +274,12 @@ impl State { } pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { - for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) { + for slot in self + .vertex + .iter_mut() + .skip(start as usize) + .take(count as usize) + { *slot = VertexView::default(); } } @@ -459,13 +470,8 @@ impl State { .map(|depth| depth.resource) } - /// A descriptor a shader reads through a table: its host slot made if - /// it changed, constant data copied, textures made readable. - /// What draws and dispatches share: heaps, our root signature, the - /// pipeline, and per stage the user data, root views and the - /// descriptors its tables hold. - fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) { - self.depth_sampled = false; + /// Binds the title's shader-visible heaps when they change. + fn bind_heaps(&mut self, list: &HostList) { let l = &list.list; // Heaps first: a root signature with directly indexed heaps must be // set after them. @@ -483,6 +489,75 @@ impl State { self.host_heaps = self.heaps; self.host_roots = [0; 2]; } + } + + /// Records a clear of a resource-backed texture UAV in the bound heap. + pub(crate) fn clear_texture_uav( + &mut self, + list: &HostList, + gpu: u64, + cpu: u64, + resource: This, + value: UavClear, + rects: &[RECT], + ) { + let heap_id = self.heaps[0]; + if heap_id == 0 { + return; + } + let heap = crate::descriptor::heap(heap_id as This); + if heap.index(gpu).is_none() { + return; + } + let ( + Some(View::Unordered(cpu_resource, _, words)), + Some(View::Unordered(gpu_resource, _, _)), + ) = (crate::descriptor::view(cpu), crate::descriptor::view(gpu)) + else { + return; + }; + if cpu_resource != resource as usize || gpu_resource != cpu_resource { + return; + } + let (Some(texture), Some(native_heap)) = + (crate::resource::host_resource(resource), heap.host()) + else { + return; + }; + let Some((slot, gpu, cpu)) = native_heap.clear_texture_uav(list, texture, words.as_ref()) + else { + return; + }; + self.dynamic.push((heap_id, slot, 1)); + self.bind_heaps(list); + crate::list::ensure_state( + list, + resource, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32, + ); + // SAFETY: matched views, a live texture in UAV state, and the + // shader-visible descriptor's heap is bound on this list. + unsafe { + match value { + UavClear::Uint(values) => { + list.list + .ClearUnorderedAccessViewUint(gpu, cpu, texture, &values, rects); + } + UavClear::Float(values) => { + list.list + .ClearUnorderedAccessViewFloat(gpu, cpu, texture, &values, rects); + } + } + } + } + + /// What draws and dispatches share: heaps, our root signature, the + /// pipeline, and per stage the user data, root views and the + /// descriptors its tables hold. + fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) { + self.depth_sampled = false; + let l = &list.list; + self.bind_heaps(list); let root = p.root.as_raw() as usize; if self.host_roots[usize::from(compute)] != root { // SAFETY: an open list and a live root signature. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b998f93698..1cd846deca 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -367,6 +367,9 @@ pub(crate) struct HostList { /// expanded vertices, rewritten draw arguments and per-draw atomic /// counters, reused across draws and across resets. rect_scratch: Mutex, + /// A CPU-only heap of one UAV slot, for the CPU descriptor of a UAV + /// clear, made on first use. + clear_uav_cpu: 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")] @@ -647,6 +650,7 @@ impl Host { pipelines: Mutex::default(), budget: OnceLock::new(), rect_scratch: Mutex::default(), + clear_uav_cpu: OnceLock::new(), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] @@ -1411,6 +1415,29 @@ impl HostList { Some((gpu + at, (data + at as usize) as *mut u8)) } + /// The CPU-only UAV slot used when recording a clear. D3D12 uses + /// this descriptor during recording, so the next clear may reuse it. + pub(crate) fn clear_uav_cpu(&self) -> Option { + let heap = self + .clear_uav_cpu + .get_or_init(|| { + // SAFETY: plain allocation of a CPU-only view heap. + unsafe { + host()? + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + ..Default::default() + }) + } + .ok() + }) + .as_ref()?; + // SAFETY: the list owns this heap until it is dropped. + Some(unsafe { heap.GetCPUDescriptorHandleForHeapStart() }) + } + /// The host address of the list's indirect-work budget, zeroed at each /// submission of the list from the first use after a reset on. pub(crate) fn budget(&self) -> Option { diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index b77ef688c2..9122a574f7 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -981,6 +981,80 @@ extern "system" fn clear_dsv( let _ = (this, handle, flags, depth, stencil, count, rects); } +/// Clear a resource-backed texture with a matching bound GPU UAV and CPU UAV. +#[cfg(windows)] +fn clear_uav( + this: This, + gpu: u64, + cpu: u64, + resource: This, + value: crate::draw::UavClear, + count: u32, + rects: *const Rect, +) { + let rects = if count == 0 || rects.is_null() { + &[] + } else { + // SAFETY: the title passes count rectangles in the host's layout. + unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } + }; + with_state(this, |list, state| { + state.clear_texture_uav(list, gpu, cpu, resource, value, rects) + }); +} + +extern "system" fn clear_uav_uint( + this: This, + gpu: u64, + cpu: u64, + resource: This, + values: *const [u32; 4], + count: u32, + rects: *const Rect, +) { + #[cfg(windows)] + // SAFETY: the title passes four values; null is tolerated. + if let Some(values) = unsafe { values.as_ref() } { + clear_uav( + this, + gpu, + cpu, + resource, + crate::draw::UavClear::Uint(*values), + count, + rects, + ); + } + #[cfg(not(windows))] + let _ = (this, gpu, cpu, resource, values, count, rects); +} + +extern "system" fn clear_uav_float( + this: This, + gpu: u64, + cpu: u64, + resource: This, + values: *const [f32; 4], + count: u32, + rects: *const Rect, +) { + #[cfg(windows)] + // SAFETY: the title passes four values; null is tolerated. + if let Some(values) = unsafe { values.as_ref() } { + clear_uav( + this, + gpu, + cpu, + resource, + crate::draw::UavClear::Float(*values), + count, + rects, + ); + } + #[cfg(not(windows))] + let _ = (this, gpu, cpu, resource, values, count, rects); +} + /// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses /// are title memory, copied at submission like buffer copies (if mapped). extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) { @@ -1537,7 +1611,7 @@ fn defer_write(this: This, address: u64, what: Written, bytes: usize) { /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96 /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 /// + 13): 140 slots. -const METHODS: [(usize, *const ()); 52] = [ +const METHODS: [(usize, *const ()); 54] = [ (0, list_query as *const ()), (2, list_release as *const ()), (7, object::parent_device as *const ()), // 0x38 @@ -1578,6 +1652,8 @@ const METHODS: [(usize, *const ()); 52] = [ (50, state::targets as *const ()), // 0x190 (51, clear_dsv as *const ()), // 0x198 (52, clear_rtv as *const ()), // 0x1a0 + (53, clear_uav_uint as *const ()), // 0x1a8 + (54, clear_uav_float as *const ()), // 0x1b0 (59, execute_indirect as *const ()), // 0x1d8 indirect (60, copy_memory as *const ()), // 0x1e0 (68, ignored_state as *const ()), // 0x220 depth bounds @@ -1776,6 +1852,25 @@ mod tests { assert_eq!(release(allocator), 0); } + /// The UAV clears sit in their slots (0x1a8, 0x1b0), not the + /// missing-method stub (upstream #771), and the table stays in slot + /// order without duplicates. + #[test] + fn uav_clears_fill_their_slots() { + let has = |i: usize, f: *const ()| METHODS.iter().any(|&(j, g)| j == i && g == f); + assert!(has(53, clear_uav_uint as *const ())); + assert!(has(54, clear_uav_float as *const ())); + assert!(METHODS.windows(2).all(|w| w[0].0 < w[1].0)); + } + + /// A clear with no values does nothing, host or not. + #[test] + fn uav_clears_tolerate_null_values() { + let null = std::ptr::null(); + clear_uav_uint(null, 0, 0, null, std::ptr::null(), 0, std::ptr::null()); + clear_uav_float(null, 0, 0, null, std::ptr::null(), 0, std::ptr::null()); + } + #[test] fn every_inline_command_falls_back_to_the_table() { let null = std::ptr::null(); From 92fde68aba9501ac1f8d1d35d5844916226bcb5a Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:43:36 +0000 Subject: [PATCH 034/123] Pilot: a Windows test machine that reports crashes and picks up fixes by itself scripts/pilot/VIctoryPilot.cmd is the one file a tester downloads and starts. It fetches pilot.ps1 from the branch and runs it (Windows PowerShell 5.1, nothing else needed). Pilot then: - installs what is missing on the first start (winget: Git, Rust, the GitHub CLI, the C++ build tools) and signs in to GitHub; - builds every new commit of the branch and runs the Windows-only tests (victory-gpu, victory-hle, victory-loader), reporting build errors and failing tests; - once the tester chooses the game, runs it and watches for crashes, new crashes.log entries, device removal and hangs (no output for N minutes), reporting each as a [Pilot] issue with the machine, commit, new crash entries, most frequent warnings and the output tail; - polls the branch every minute: a new commit is built, tested and run, and a crash report the new commit runs past is closed with a note; - keeps a [Pilot] status issue up to date, serves a dashboard on localhost:8765 (choose game, run, stop, rebuild, test, send a note), and replaces itself when the branch has a newer pilot.ps1. remote.json on the branch sets the next run (profile, VICTORY_* variables, allowed title arguments, test crates and filter, hang and survive times, pause), every value checked against an allowlist. Reports are logs only, with the user name, profile folder and game folder replaced. watch.sh is the developer's side: it waits for a new or updated [Pilot] report. Not run here (no PowerShell in this environment): checked for ASCII, balanced structure and the asset policy's limits; the dashboard script passes node --check. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- scripts/pilot/README.md | 84 +++ scripts/pilot/VIctoryPilot.cmd | 19 + scripts/pilot/pilot.ps1 | 1061 ++++++++++++++++++++++++++++++++ scripts/pilot/remote.json | 11 + scripts/pilot/watch.sh | 37 ++ 5 files changed, 1212 insertions(+) create mode 100644 scripts/pilot/README.md create mode 100644 scripts/pilot/VIctoryPilot.cmd create mode 100644 scripts/pilot/pilot.ps1 create mode 100644 scripts/pilot/remote.json create mode 100755 scripts/pilot/watch.sh diff --git a/scripts/pilot/README.md b/scripts/pilot/README.md new file mode 100644 index 0000000000..86de1a70bf --- /dev/null +++ b/scripts/pilot/README.md @@ -0,0 +1,84 @@ +# VIctory Pilot + +Pilot turns a Windows PC into a test machine that works with the developer +by itself. You start it once and leave it running. It then keeps doing four +things: + +1. **Builds and tests every new commit** on the branch, including the + Windows-only crates (`victory-gpu`, `victory-hle`, `victory-loader`) that + cannot be compiled where the fixes are written. +2. **Runs the game**, once you have chosen it, and watches for crashes, hangs + (no output for a few minutes) and GPU device removal. +3. **Reports what breaks** as issues on + [MfDev0/victory](https://github.com/MfDev0/victory/issues), titled + `[Pilot] ...`. Each report has the machine, the commit, the new + `crashes.log` entries, the most frequent warnings and the end of the + output. It also keeps a `[Pilot] status` issue up to date. +4. **Picks up fixes**: when a new commit lands on the branch, Pilot updates, + rebuilds, retests and reruns the game. If a crash does not come back, + Pilot closes its report with a note. + +A dashboard at `http://localhost:8765/` shows all of it live: what Pilot is +doing, the game's output, the reports, and buttons to choose the game, run, +stop, rebuild, test, or send a note ("the screen went black after the +logo"). + +## Start + +1. Download [`VIctoryPilot.cmd`](https://github.com/MfDev0/victory/raw/refs/heads/arena/59fabb00-victory/scripts/pilot/VIctoryPilot.cmd) + (right-click, *Save link as...*). +2. Double-click it. If Windows SmartScreen warns about it, choose + *More info*, then *Run anyway*. +3. The first start installs what is missing with `winget`: Git, Rust, the + GitHub CLI and the Visual Studio C++ build tools. Windows asks for + permission. The build tools are a large download. +4. Sign in to GitHub when asked. Press Enter, then paste the code shown in + the window into the browser page. Reports are sent from your account. +5. The dashboard opens. Keep the Pilot window open; closing it stops Pilot. + +You do not need the game for the first part: Pilot builds and tests on its +own. When you have the game, click **Choose game...** and pick the title's +executable. Testing the game starts then. + +The game must be your own copy. Keep it outside Pilot's folder. + +## What it runs, and what the developer can change + +Pilot only runs `git`, `cargo build` and `cargo test` for this repository, +`gh` (for issues on the fork) and the built `victory.exe`. Building runs the +repository's code, so only run Pilot on a branch you trust. + +The branch's [`remote.json`](remote.json) sets the next run. The developer +uses it to switch on more logging or another setting without asking you. +Pilot checks every value against an allowlist and ignores anything else: + +| Key | Allowed | +|---|---| +| `pause` | `true` stops Pilot from building and running until it is `false` again | +| `profile` | `release`, or `diag` (the diagnostics build) | +| `env` | variables named `VICTORY_*`, and `RUST_BACKTRACE` | +| `args` | `--console series-s` or `series-x`, `--unimplemented trap` or `zero`, `--strict` | +| `test_crates` | crates of this workspace | +| `test_filter` | a test name filter (letters, digits, `_`, `:`) | +| `hang_minutes` | minutes without output before a run counts as hung (2-120) | +| `survive_minutes` | minutes a run must last before an old crash report is closed (2-120) | + +When the branch has a newer `pilot.ps1`, Pilot replaces itself and restarts. +It waits until nothing is running. + +## Privacy + +Reports contain logs only: no game files, shaders, screenshots or memory, +per [docs/asset-policy.md](../../docs/asset-policy.md). Pilot replaces your +user name, your profile folder and the game's folder with placeholders +before sending anything. The issues are public. + +Pilot keeps its files under `%LOCALAPPDATA%\VIctoryPilot`: the source, +build output, `logs\` (every build, test and game run) and its settings. To +remove Pilot, delete that folder. + +## The developer's side + +`scripts/pilot/watch.sh [seconds]` waits until a `[Pilot]` report is new or +updated, prints it with its comments, and exits. A fix is pushed to the +branch, which Pilot picks up by itself. diff --git a/scripts/pilot/VIctoryPilot.cmd b/scripts/pilot/VIctoryPilot.cmd new file mode 100644 index 0000000000..ccbfe165f5 --- /dev/null +++ b/scripts/pilot/VIctoryPilot.cmd @@ -0,0 +1,19 @@ +@echo off +rem VIctory Pilot: double-click to start. Gets the latest Pilot from the +rem branch and runs it; the first start installs what is missing. +setlocal +set "PILOT_HOME=%LOCALAPPDATA%\VIctoryPilot" +set "PILOT_URL=https://raw.githubusercontent.com/MfDev0/victory/refs/heads/arena/59fabb00-victory/scripts/pilot/pilot.ps1" +if not exist "%PILOT_HOME%" mkdir "%PILOT_HOME%" +title VIctory Pilot +echo Getting the latest VIctory Pilot... +powershell -NoProfile -ExecutionPolicy Bypass -Command "try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $new = Join-Path $env:PILOT_HOME 'pilot.new.ps1'; Invoke-WebRequest -UseBasicParsing -Uri $env:PILOT_URL -OutFile $new; Move-Item -Force $new (Join-Path $env:PILOT_HOME 'pilot.ps1') } catch { Write-Host ('Download failed, using the last copy: ' + $_) }" +if not exist "%PILOT_HOME%\pilot.ps1" ( + echo Could not download Pilot. Check the internet connection and try again. + pause + exit /b 1 +) +powershell -NoProfile -ExecutionPolicy Bypass -Command "do { & powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $env:PILOT_HOME 'pilot.ps1'); $code = $LASTEXITCODE } while ($code -eq 3); exit $code" +echo. +echo VIctory Pilot stopped. Start it again with this file. +pause diff --git a/scripts/pilot/pilot.ps1 b/scripts/pilot/pilot.ps1 new file mode 100644 index 0000000000..86fe077bd2 --- /dev/null +++ b/scripts/pilot/pilot.ps1 @@ -0,0 +1,1061 @@ +# VIctory Pilot: builds, tests and runs VIctory on this PC, sends what +# breaks to GitHub as issues, and picks up fixes from the branch by itself. +# Started by VIctoryPilot.cmd; see scripts/pilot/README.md. +# +# Pilot only runs git, cargo (build and test of this repository), gh (issues +# on the fork) and victory.exe. The branch's scripts/pilot/remote.json can +# change the next run's settings, but only through the allowlists below: no +# command from the branch is run as such. +# +# ASCII only: Windows PowerShell 5.1 reads a script without a BOM as ANSI. + +$ErrorActionPreference = 'Continue' +$PilotVersion = '1.0' +$Repo = 'MfDev0/victory' +$Branch = 'arena/59fabb00-victory' +$PilotHome = Join-Path $env:LOCALAPPDATA 'VIctoryPilot' +$RepoDir = Join-Path $PilotHome 'victory' +$LogDir = Join-Path $PilotHome 'logs' +$ConfigPath = Join-Path $PilotHome 'config.json' +$StatePath = Join-Path $PilotHome 'state.json' +New-Item -ItemType Directory -Force -Path $PilotHome, $LogDir | Out-Null +try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch {} +try { $Host.UI.RawUI.WindowTitle = 'VIctory Pilot' } catch {} + +# ---------------------------------------------------------------- basics + +$script:Activity = New-Object System.Collections.Generic.List[string] +function Say([string]$msg) { + $line = (Get-Date -Format 'HH:mm:ss') + ' ' + $msg + Write-Host $line + $script:Activity.Add($line) + while ($script:Activity.Count -gt 300) { $script:Activity.RemoveAt(0) } + try { Add-Content -Path (Join-Path $LogDir 'pilot.log') -Value $line -Encoding UTF8 } catch {} +} + +function ConvertTo-Hash($obj) { + if ($null -eq $obj) { return $null } + if ($obj -is [System.Collections.IDictionary]) { return $obj } + if ($obj -is [System.Management.Automation.PSCustomObject]) { + $h = @{} + foreach ($p in $obj.PSObject.Properties) { $h[$p.Name] = ConvertTo-Hash $p.Value } + return $h + } + if (($obj -is [System.Collections.IEnumerable]) -and ($obj -isnot [string])) { + $list = New-Object System.Collections.ArrayList + foreach ($item in $obj) { [void]$list.Add((ConvertTo-Hash $item)) } + return , $list.ToArray() + } + return $obj +} + +function Load-Json([string]$path) { + if (Test-Path $path) { + try { return ConvertTo-Hash (Get-Content -Path $path -Raw -Encoding UTF8 | ConvertFrom-Json) } + catch { Say "could not read $path, starting fresh" } + } + return @{} +} + +function Save-Json([string]$path, $obj) { + try { ($obj | ConvertTo-Json -Depth 10) | Set-Content -Path $path -Encoding UTF8 } catch { Say "could not save $path" } +} + +function Find-Exe([string]$name) { + $c = Get-Command $name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($c) { return $c.Source } + return $null +} + +function Refresh-Path { + $machine = [Environment]::GetEnvironmentVariable('Path', 'Machine') + $user = [Environment]::GetEnvironmentVariable('Path', 'User') + $env:Path = "$machine;$user" + $cargoBin = Join-Path $env:USERPROFILE '.cargo\bin' + if ((Test-Path $cargoBin) -and ($env:Path -notlike "*$cargoBin*")) { $env:Path += ";$cargoBin" } + $ghDir = Join-Path $env:ProgramFiles 'GitHub CLI' + if ((Test-Path $ghDir) -and ($env:Path -notlike "*$ghDir*")) { $env:Path += ";$ghDir" } +} + +function Quote-Arg([string]$a) { + if ($a -eq '') { return '""' } + if ($a -notmatch '[\s"]') { return $a } + $escaped = ($a -replace '(\\*)"', '$1$1\"') -replace '(\\+)$', '$1$1' + return '"' + $escaped + '"' +} + +function Join-Args([string[]]$argv) { return (($argv | ForEach-Object { Quote-Arg $_ }) -join ' ') } + +# Runs a program to the end and returns its exit code and output. +function Run-Sync([string]$exe, [string[]]$argv, [string]$cwd = $PilotHome, [int]$timeout = 600) { + $path = $exe + if (-not [IO.Path]::IsPathRooted($exe)) { $path = Find-Exe $exe } + if (-not $path) { return @{ Code = -1; Out = "$exe is not installed" } } + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = $path + $psi.Arguments = Join-Args $argv + $psi.WorkingDirectory = $cwd + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + try { $p = [System.Diagnostics.Process]::Start($psi) } + catch { return @{ Code = -1; Out = "$exe could not start: $_" } } + $errTask = $p.StandardError.ReadToEndAsync() + $outTask = $p.StandardOutput.ReadToEndAsync() + if (-not $p.WaitForExit($timeout * 1000)) { + Kill-Tree $p.Id + return @{ Code = -2; Out = "$exe timed out after $timeout s" } + } + $p.WaitForExit() + return @{ Code = $p.ExitCode; Out = ($outTask.Result + "`n" + $errTask.Result).Trim() } +} + +function Kill-Tree([int]$id) { + try { & taskkill.exe /PID $id /T /F 2>&1 | Out-Null } catch {} +} + +function File-Size([string]$path) { + try { return (Get-Item -LiteralPath $path -ErrorAction Stop).Length } catch { return 0 } +} + +# The last lines of a file another process may still be writing. +function Read-Tail([string]$path, [int]$maxBytes = 262144, [long]$from = -1) { + if (-not (Test-Path -LiteralPath $path)) { return } + try { + $fs = [System.IO.File]::Open($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]'ReadWrite, Delete') + try { + $len = $fs.Length + $start = [Math]::Max([long]0, $len - $maxBytes) + if ($from -ge 0) { $start = [Math]::Max($from, $start) } + [void]$fs.Seek($start, [System.IO.SeekOrigin]::Begin) + $buf = New-Object byte[] ([int]($len - $start)) + $n = $fs.Read($buf, 0, $buf.Length) + $text = [System.Text.Encoding]::UTF8.GetString($buf, 0, $n) + } finally { $fs.Close() } + $text = $text -replace "\x1b\[[0-9;?]*[A-Za-z]", '' + return ($text -split "`r?`n") + } catch { return } +} + +# Hides this PC's user name and game folder in anything sent out. +function Scrub([string]$text) { + if (-not $text) { return '' } + $out = $text + if ($script:Config -and $script:Config.game_exe) { + $gameDir = Split-Path -Parent $script:Config.game_exe + if ($gameDir) { $out = $out.Replace($gameDir, '') } + } + if ($env:USERPROFILE) { $out = $out.Replace($env:USERPROFILE, '%USERPROFILE%') } + if ($env:USERNAME -and $env:USERNAME.Length -ge 3) { $out = $out.Replace($env:USERNAME, '') } + return $out +} + +function Short([string]$sha) { if ($sha -and $sha.Length -ge 7) { return $sha.Substring(0, 7) }; return '?' } + +# ---------------------------------------------------------------- state + +$script:Config = Load-Json $ConfigPath +foreach ($pair in @(@('game_exe', ''), @('auto_run', $true), @('run_tests', $true), @('extra_args', ''))) { + if (-not $script:Config.ContainsKey($pair[0])) { $script:Config[$pair[0]] = $pair[1] } +} +$script:State = Load-Json $StatePath +if (-not $script:State.ContainsKey('issues') -or $null -eq $script:State.issues) { $script:State.issues = @() } +$script:State.issues = @($script:State.issues | Where-Object { $_ -is [System.Collections.IDictionary] }) +foreach ($k in @('built', 'tested', 'ran')) { if (-not $script:State.ContainsKey($k)) { $script:State[$k] = '' } } + +function Save-State { Save-Json $StatePath $script:State } +function Save-Config { Save-Json $ConfigPath $script:Config } + +$script:Phase = 'starting' +$script:Detail = '' +$script:LocalSha = '' +$script:Subject = '' +$script:RemoteSha = '' +$script:Job = $null +$script:LastJob = $null +$script:PendingUpdate = $false +$script:SelfUpdate = $null +$script:Login = '' +$script:CanReport = $false +$script:IssuesOn = $false +$script:LastRemoteCheck = [DateTime]::MinValue +$script:LastHeartbeat = [DateTime]::MinValue +$script:Machine = @{} +$script:Remote = @{} + +# ---------------------------------------------------------------- setup + +function Has-MsvcTools { + $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' + if (-not (Test-Path $vswhere)) { return $false } + $found = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2>$null + return [bool]$found +} + +function Winget-Install([string]$id, [string]$override = '') { + Say "installing $id (Windows may ask for permission; this can take a while)" + $wargs = @('install', '--id', $id, '-e', '--source', 'winget', '--accept-source-agreements', '--accept-package-agreements') + if ($override) { $wargs += @('--override', $override) } else { $wargs += '--silent' } + & winget @wargs + Refresh-Path +} + +function Ensure-Tools { + $script:Phase = 'setting up' + Refresh-Path + $need = @() + if (-not (Find-Exe 'git')) { $need += 'Git.Git' } + if (-not (Find-Exe 'cargo')) { $need += 'Rustlang.Rustup' } + if (-not (Find-Exe 'gh')) { $need += 'GitHub.cli' } + $msvc = Has-MsvcTools + if (($need.Count -eq 0) -and $msvc) { Say 'tools: git, Rust, GitHub CLI and the C++ build tools are installed'; return $true } + if (-not (Find-Exe 'winget')) { + Say 'winget is missing. Install "App Installer" from the Microsoft Store (opening it now), then start Pilot again.' + Start-Process 'ms-windows-store://pdp/?ProductId=9NBLGGH4NNS1' + return $false + } + $listed = @($need) + if (-not $msvc) { $listed += 'C++ build tools' } + Say ('first start: installing what is missing: ' + ($listed -join ', ')) + foreach ($id in $need) { Winget-Install $id } + if (-not $msvc) { + Winget-Install 'Microsoft.VisualStudio.2022.BuildTools' '--passive --wait --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended' + } + Refresh-Path + $missing = @() + if (-not (Find-Exe 'git')) { $missing += 'git' } + if (-not (Find-Exe 'cargo')) { $missing += 'Rust (cargo)' } + if (-not (Find-Exe 'gh')) { $missing += 'GitHub CLI' } + if (-not (Has-MsvcTools)) { $missing += 'C++ build tools' } + if ($missing.Count -gt 0) { + Say ('still missing: ' + ($missing -join ', ') + '. Close this window and start Pilot again (a restart of Windows may be needed).') + return $false + } + return $true +} + +function Ensure-GitHub { + $r = Run-Sync 'gh' @('auth', 'status', '--hostname', 'github.com') + if ($r.Code -ne 0) { + Say 'Sign in to GitHub so Pilot can send reports: press Enter below, then paste the code in the browser page.' + & gh auth login --hostname github.com --git-protocol https --web + $r = Run-Sync 'gh' @('auth', 'status', '--hostname', 'github.com') + } + if ($r.Code -ne 0) { Say 'not signed in to GitHub: Pilot keeps working but cannot send reports'; return $false } + $who = Run-Sync 'gh' @('api', 'user', '--jq', '.login') + if ($who.Code -eq 0) { $script:Login = $who.Out.Trim() } + Say "GitHub: signed in as $($script:Login), reports go to $Repo" + return $true +} + +# Reports need issues on the fork (forks start with them off) and labels. +function Ensure-Issues { + $r = Run-Sync 'gh' @('api', "repos/$Repo", '--jq', '.has_issues') + if (($r.Code -eq 0) -and ($r.Out.Trim() -eq 'false')) { + Say "issues are off on ${Repo}: switching them on" + [void](Run-Sync 'gh' @('api', '-X', 'PATCH', "repos/$Repo", '-F', 'has_issues=true')) + $r = Run-Sync 'gh' @('api', "repos/$Repo", '--jq', '.has_issues') + } + if (($r.Code -ne 0) -or ($r.Out.Trim() -ne 'true')) { + Say "issues are off on $Repo and Pilot cannot switch them on: the owner can, under Settings > General > Features > Issues" + return $false + } + $labels = @( + @('crash-report', 'b60205', 'Pilot: a crash, hang or player report'), + @('build-failure', 'd93f0b', 'Pilot: the branch does not build on Windows'), + @('test-failure', 'fbca04', 'Pilot: Windows tests fail'), + @('pilot-status', '0e8a16', 'Pilot: the status of a Pilot PC') + ) + foreach ($l in $labels) { [void](Run-Sync 'gh' @('label', 'create', $l[0], '-R', $Repo, '--color', $l[1], '--description', $l[2], '--force')) } + return $true +} + +function Read-Machine { + $m = @{ gpu = '?'; driver = '?'; windows = '?'; cpu = '?'; ram_gb = '?' } + try { + $gpus = @(Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic Display|Remote' }) + if ($gpus.Count -gt 0) { + $m.gpu = ($gpus | ForEach-Object { $_.Name }) -join ' / ' + $m.driver = ($gpus | ForEach-Object { $_.DriverVersion }) -join ' / ' + } + $os = Get-CimInstance Win32_OperatingSystem + $m.windows = "$($os.Caption) build $($os.BuildNumber)" + $m.ram_gb = [Math]::Round($os.TotalVisibleMemorySize / 1MB, 1) + $m.cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name.Trim() + } catch {} + try { + $smi = Find-Exe 'nvidia-smi' + if ($smi) { + $v = (& $smi --query-gpu=driver_version --format=csv,noheader 2>$null | Select-Object -First 1) + if ($v) { $m.driver = "$($m.driver) (GeForce $($v.Trim()))" } + } + } catch {} + return $m +} + +# ---------------------------------------------------------------- the branch + +function Remote-Sha { + $r = Run-Sync 'git' @('ls-remote', "https://github.com/$Repo.git", "refs/heads/$Branch") $PilotHome 60 + if (($r.Code -eq 0) -and ($r.Out -match '([0-9a-f]{40})')) { return $Matches[1] } + return $null +} + +function Update-Repo { + $script:Phase = 'updating' + if (-not (Test-Path (Join-Path $RepoDir '.git'))) { + Say 'downloading the VIctory source (first time only)' + $r = Run-Sync 'git' @('clone', '--branch', $Branch, "https://github.com/$Repo.git", $RepoDir) $PilotHome 3600 + if ($r.Code -ne 0) { Say ('download failed: ' + $r.Out); return $false } + } + $r = Run-Sync 'git' @('fetch', '--quiet', 'origin', $Branch) $RepoDir 900 + if ($r.Code -ne 0) { Say ('update failed: ' + $r.Out); return $false } + $r = Run-Sync 'git' @('reset', '--hard', '--quiet', 'FETCH_HEAD') $RepoDir 300 + if ($r.Code -ne 0) { Say ('update failed: ' + $r.Out); return $false } + $old = $script:LocalSha + $script:LocalSha = (Run-Sync 'git' @('rev-parse', 'HEAD') $RepoDir).Out.Trim() + $script:Subject = (Run-Sync 'git' @('log', '-1', '--format=%s') $RepoDir).Out.Trim() + $script:RemoteSha = $script:LocalSha + $script:PendingUpdate = $false + if ($old -ne $script:LocalSha) { Say "source at $(Short $script:LocalSha): $($script:Subject)" } + Load-Remote + Check-SelfUpdate + return $true +} + +function Check-SelfUpdate { + $new = Join-Path $RepoDir 'scripts\pilot\pilot.ps1' + if (-not $PSCommandPath -or -not (Test-Path $new)) { return } + if ((Get-FileHash $new).Hash -ne (Get-FileHash $PSCommandPath).Hash) { + $script:SelfUpdate = $new + Say 'a newer Pilot is on the branch: it takes over once nothing is running' + } +} + +# The branch's run settings, every value checked. +function Load-Remote { + $r = @{ pause = $false; profile = 'release'; env = @{}; args = @(); test_crates = @('victory-gpu', 'victory-hle', 'victory-loader'); test_filter = ''; hang_minutes = 5; survive_minutes = 10 } + $path = Join-Path $RepoDir 'scripts\pilot\remote.json' + $raw = Load-Json $path + if ($raw.ContainsKey('pause')) { $r.pause = [bool]$raw.pause } + if ($raw.profile -in @('release', 'diag')) { $r.profile = $raw.profile } + if ($raw.env -is [System.Collections.IDictionary]) { + foreach ($k in $raw.env.Keys) { + $v = [string]$raw.env[$k] + if ((($k -match '^VICTORY_[A-Z0-9_]{1,40}$') -or ($k -in @('RUST_BACKTRACE'))) -and ($v.Length -le 300) -and ($v -notmatch '[\r\n]')) { $r.env[$k] = $v } + else { Say "remote.json: env $k ignored" } + } + } + $allowedArgs = @('--console', 'series-s', 'series-x', '--unimplemented', 'trap', 'zero', '--strict') + foreach ($a in @($raw.args)) { + if ($null -eq $a) { continue } + if ($a -in $allowedArgs) { $r.args += $a } else { Say "remote.json: argument $a ignored" } + } + $allowedCrates = @('victory', 'victory-gpu', 'victory-hle', 'victory-loader', 'victory-shader', 'victory-formats', 'victory-core', 'victory-game', 'xmem') + if ($raw.ContainsKey('test_crates')) { $r.test_crates = @(@($raw.test_crates) | Where-Object { $_ -in $allowedCrates }) } + if (($raw.test_filter -is [string]) -and ($raw.test_filter -match '^[A-Za-z0-9_:]{0,120}$')) { $r.test_filter = $raw.test_filter } + foreach ($k in @('hang_minutes', 'survive_minutes')) { + if ($raw.ContainsKey($k)) { $n = 0; if ([int]::TryParse([string]$raw[$k], [ref]$n) -and $n -ge 2 -and $n -le 120) { $r[$k] = $n } } + } + $script:Remote = $r +} + +function Victory-Exe { + $dir = 'release'; if ($script:Remote.profile -eq 'diag') { $dir = 'diag' } + return Join-Path $RepoDir "target\$dir\victory.exe" +} + +# ---------------------------------------------------------------- jobs + +function Start-LongJob([string]$kind, [string]$exe, [string[]]$argv, [hashtable]$envVars) { + $stamp = Get-Date -Format 'yyyyMMdd-HHmmss' + $out = Join-Path $LogDir "$kind-$stamp.out.txt" + $err = Join-Path $LogDir "$kind-$stamp.err.txt" + $saved = @{} + $envVars['CARGO_TERM_COLOR'] = 'never' + foreach ($k in $envVars.Keys) { $saved[$k] = [Environment]::GetEnvironmentVariable($k); [Environment]::SetEnvironmentVariable($k, $envVars[$k]) } + $p = $null + try { + $p = Start-Process -FilePath $exe -ArgumentList (Join-Args $argv) -WorkingDirectory $RepoDir -RedirectStandardOutput $out -RedirectStandardError $err -NoNewWindow -PassThru + $null = $p.Handle + } catch { Say "$kind could not start: $_" } + finally { foreach ($k in $saved.Keys) { [Environment]::SetEnvironmentVariable($k, $saved[$k]) } } + if (-not $p) { return $false } + $script:Job = @{ + Kind = $kind; Proc = $p; Out = $out; Err = $err; Started = Get-Date; LastActivity = Get-Date; LastSize = 0 + Sha = $script:LocalSha; Hung = $false; UserStopped = $false; Env = $envVars; Args = $argv; CrashBefore = @{} + } + return $true +} + +function Start-Build { + $cargo = Find-Exe 'cargo' + $script:Phase = 'building' + $script:Detail = 'compiling VIctory (the first build takes a long time)' + Say "building $(Short $script:LocalSha) ($($script:Remote.profile))" + $bargs = @('build', '--locked', '-p', 'victory') + if ($script:Remote.profile -eq 'diag') { $bargs += @('--profile', 'diag', '--features', 'diagnostics') } else { $bargs += '--release' } + return Start-LongJob 'build' $cargo $bargs @{} +} + +function Start-Tests { + $crates = @($script:Remote.test_crates) + if ($crates.Count -eq 0) { return $false } + $cargo = Find-Exe 'cargo' + $script:Phase = 'testing' + $script:Detail = 'running the Windows-only tests: ' + ($crates -join ', ') + Say "testing $(Short $script:LocalSha): $($crates -join ', ')" + $targs = @('test', '--locked') + foreach ($c in $crates) { $targs += @('-p', $c) } + $targs += '--no-fail-fast' + if ($script:Remote.test_filter) { $targs += @('--', $script:Remote.test_filter) } + return Start-LongJob 'test' $cargo $targs @{} +} + +function Crash-Logs { + $h = @{} + foreach ($root in @((Join-Path $env:LOCALAPPDATA 'victory'))) { + if ($root -and (Test-Path $root)) { + Get-ChildItem -Path $root -Recurse -Filter 'crashes.log' -ErrorAction SilentlyContinue -Depth 4 | ForEach-Object { $h[$_.FullName] = $_.Length } + } + } + return $h +} + +function Start-Game { + $exe = Victory-Exe + if (-not (Test-Path $exe)) { Say 'no build to run yet'; return $false } + if (-not $script:Config.game_exe -or -not (Test-Path -LiteralPath $script:Config.game_exe)) { Say 'choose the game first (Choose game on the dashboard)'; return $false } + $script:Phase = 'running the game' + $script:Detail = 'watching for crashes, hangs and device removal' + $gargs = @('run', $script:Config.game_exe, '--execute') + @($script:Remote.args) + $envVars = @{ RUST_BACKTRACE = '1' } + foreach ($k in $script:Remote.env.Keys) { $envVars[$k] = $script:Remote.env[$k] } + $before = Crash-Logs + Say "starting the game on $(Short $script:LocalSha)" + if (-not (Start-LongJob 'game' $exe $gargs $envVars)) { return $false } + $script:Job.CrashBefore = $before + return $true +} + +function Stop-Job([string]$why) { + if ($script:Job) { + $script:Job.UserStopped = $true + Say "stopping $($script:Job.Kind): $why" + Kill-Tree $script:Job.Proc.Id + } +} + +function Job-Lines($j, [int]$maxBytes = 262144) { + $a = @(Read-Tail $j.Out $maxBytes) + $b = @(Read-Tail $j.Err $maxBytes) + return (($a + $b) | Where-Object { $_ -ne '' }) +} + +function Tick-Job { + $j = $script:Job + if (-not $j) { return } + $size = (File-Size $j.Out) + (File-Size $j.Err) + if ($size -ne $j.LastSize) { $j.LastSize = $size; $j.LastActivity = Get-Date } + if (($j.Kind -eq 'game') -and -not $j.Proc.HasExited) { + $quiet = ((Get-Date) - $j.LastActivity).TotalMinutes + if ($quiet -ge $script:Remote.hang_minutes) { + Say "no output for $([int]$quiet) minutes: treating it as a hang" + $j.Hung = $true + Kill-Tree $j.Proc.Id + } + } + if ($j.Proc.HasExited) { + $script:Job = $null + $script:LastJob = $j + $code = 0 + try { $code = $j.Proc.ExitCode } catch {} + $j.Code = $code + $j.Minutes = [Math]::Round(((Get-Date) - $j.Started).TotalMinutes, 1) + switch ($j.Kind) { + 'build' { Finish-Build $j } + 'test' { Finish-Tests $j } + 'game' { Finish-Game $j } + } + } +} + +# ---------------------------------------------------------------- reports + +function Issue-Url([int]$n) { return "https://github.com/$Repo/issues/$n" } + +function Gh-Body([string]$text) { + $text = Scrub $text + if ($text.Length -gt 60000) { $text = $text.Substring(0, 60000) + "`n... (cut)" } + $file = Join-Path $LogDir 'issue-body.md' + [IO.File]::WriteAllText($file, $text, (New-Object System.Text.UTF8Encoding $false)) + return $file +} + +function New-Issue([string]$kind, [string]$title, [string]$body, [string]$label) { + if (-not $script:CanReport) { Say "not reported (not signed in): $title"; return 0 } + $file = Gh-Body $body + $r = Run-Sync 'gh' @('issue', 'create', '-R', $Repo, '--title', $title, '--body-file', $file, '--label', $label) + if ($r.Code -ne 0) { $r = Run-Sync 'gh' @('issue', 'create', '-R', $Repo, '--title', $title, '--body-file', $file) } + if (($r.Code -eq 0) -and ($r.Out -match '/issues/(\d+)')) { + $n = [int]$Matches[1] + Say "reported: $title -> $(Issue-Url $n)" + return $n + } + Say ('could not send the report: ' + $r.Out) + return 0 +} + +function Comment-Issue([int]$n, [string]$body) { + if (-not $script:CanReport -or $n -le 0) { return } + $file = Gh-Body $body + $r = Run-Sync 'gh' @('issue', 'comment', "$n", '-R', $Repo, '--body-file', $file) + if ($r.Code -ne 0) { Say ('could not comment: ' + $r.Out) } +} + +function Close-Issue($issue, [string]$why) { + Comment-Issue $issue.number $why + if ($script:CanReport) { [void](Run-Sync 'gh' @('issue', 'close', "$($issue.number)", '-R', $Repo)) } + $issue.closed = $true + Save-State + Say "closed #$($issue.number): $why" +} + +function Open-Issues([string]$kind) { $script:State.issues | Where-Object { $_.kind -eq $kind -and -not $_.closed } } + +function Add-Issue([int]$n, [string]$kind, [string]$title, [string]$signature, [double]$atMinutes) { + if ($n -le 0) { return } + $script:State.issues = @($script:State.issues) + @(@{ number = $n; kind = $kind; title = $title; signature = $signature; sha = $script:LocalSha; at_minutes = $atMinutes; closed = $false; seen = @($script:LocalSha) }) + Save-State +} + +function Machine-Table { + $m = $script:Machine + $lines = @( + '| | |', '|---|---|', + "| Commit | ``$($script:LocalSha)`` $($script:Subject) |", + "| GPU | $($m.gpu) |", + "| Driver | $($m.driver) |", + "| Windows | $($m.windows) |", + "| CPU / RAM | $($m.cpu) / $($m.ram_gb) GB |", + "| Profile | $($script:Remote.profile) |", + "| Pilot | $PilotVersion |" + ) + return ($lines -join "`n") +} + +function Fence([string[]]$lines, [int]$max) { + $l = @($lines) + if ($l.Count -gt $max) { $l = $l[($l.Count - $max)..($l.Count - 1)] } + return "``````text`n" + (($l -join "`n") -replace '```', "'''") + "`n``````" +} + +# ---------------------------------------------------------------- results + +function Finish-Build($j) { + $lines = @(Job-Lines $j) + if ($j.UserStopped) { $script:Phase = 'idle'; $script:Detail = 'build stopped'; return } + if ($j.Code -eq 0) { + Say "build OK in $($j.Minutes) min" + $script:State.built = $j.Sha + Save-State + foreach ($i in @(Open-Issues 'build')) { Close-Issue $i "Builds on ``$($j.Sha)`` (Pilot on $($script:Machine.gpu))." } + Next-Step + return + } + $errors = New-Object System.Collections.Generic.List[string] + $take = 0 + foreach ($l in $lines) { + if ($l -match '^(error|warning: unused)') { $take = 18 } + if ($take -gt 0) { $errors.Add($l); $take-- } + if ($errors.Count -gt 400) { break } + } + if ($errors.Count -eq 0) { $errors.AddRange([string[]]@($lines | Select-Object -Last 80)) } + $first = ($errors | Where-Object { $_ -match '^error' } | Select-Object -First 1) + if (-not $first) { $first = "exit code $($j.Code)" } + Say "build FAILED: $first" + $body = "Pilot could not build ``victory`` on Windows.`n`n" + (Machine-Table) + "`n`n### Errors`n" + (Fence $errors.ToArray() 400) + $open = @(Open-Issues 'build') + if ($open.Count -gt 0) { + if ($open[0].seen -notcontains $j.Sha) { + Comment-Issue $open[0].number ("Still fails on ``$($j.Sha)``.`n`n" + (Fence $errors.ToArray() 300)) + $open[0].seen = @($open[0].seen) + @($j.Sha); Save-State + } + } else { + $n = New-Issue 'build' "[Pilot] build fails on Windows: $first" $body 'build-failure' + Add-Issue $n 'build' $first $first 0 + } + $script:Phase = 'waiting for a fix' + $script:Detail = 'the build failed; reported, waiting for a new commit' +} + +function Finish-Tests($j) { + if ($j.UserStopped) { $script:Phase = 'idle'; return } + $lines = @(Job-Lines $j 4194304) + $failed = @($lines | Where-Object { $_ -match '^test (\S+) \.\.\. FAILED' } | ForEach-Object { ($_ -split ' ')[1] } | Select-Object -Unique) + $results = @($lines | Where-Object { $_ -match '^test result:' }) + $script:State.tested = $j.Sha + Save-State + $open = @(Open-Issues 'test') + if (($j.Code -eq 0) -or (($failed.Count -eq 0) -and ($results.Count -gt 0) -and -not ($results -match 'FAILED'))) { + Say "tests OK in $($j.Minutes) min ($($results.Count) suites)" + foreach ($i in $open) { Close-Issue $i "All tests pass on ``$($j.Sha)`` (Pilot on $($script:Machine.gpu))." } + Next-Step + return + } + if ($failed.Count -eq 0) { + # The tests did not run: a compile error in a test target. + Finish-Build $j + return + } + $details = New-Object System.Collections.Generic.List[string] + $inside = $false + foreach ($l in $lines) { + if ($l -match '^---- .* stdout ----') { $inside = $true } + elseif ($l -match '^(failures:|test result:)') { $inside = $false } + if ($inside) { $details.Add($l) } + if ($details.Count -gt 600) { break } + } + Say ("tests FAILED: " + ($failed -join ', ')) + $sig = ($failed | Sort-Object) -join ',' + $body = "Windows-only tests fail under Pilot.`n`n" + (Machine-Table) + "`n`n### Failed`n" + (($failed | ForEach-Object { "- ``$_``" }) -join "`n") + "`n`n### Output`n" + (Fence $details.ToArray() 600) + "`n`n### Summary`n" + (Fence $results 40) + if ($open.Count -gt 0) { + if (($open[0].signature -ne $sig) -or ($open[0].seen -notcontains $j.Sha)) { + Comment-Issue $open[0].number ("On ``$($j.Sha)`` these fail:`n" + (($failed | ForEach-Object { "- ``$_``" }) -join "`n") + "`n`n" + (Fence $details.ToArray() 400)) + $open[0].signature = $sig; $open[0].seen = @($open[0].seen) + @($j.Sha); Save-State + } + } else { + $n = New-Issue 'test' "[Pilot] $($failed.Count) Windows test(s) fail: $($failed[0])" $body 'test-failure' + Add-Issue $n 'test' $failed[0] $sig 0 + } + Next-Step +} + +function Crash-Signature([string[]]$crashLines, [string[]]$outLines, $j) { + $first = $crashLines | Where-Object { $_ -match '^VIctory: ' } | Select-Object -First 1 + if (-not $first) { + $first = @($outLines | Where-Object { $_ -match 'panicked at|DEVICE_REMOVED|DEVICE_HUNG|device removed|device hung|DXGI_ERROR|unhandled exception|access violation' }) | Select-Object -Last 1 + } + if (-not $first) { + if ($j.Hung) { return "hang: no output for $($script:Remote.hang_minutes) minutes" } + return ('exit code 0x{0:x8}' -f $j.Code) + } + $s = $first -replace '^\S*\s*\d{4}-\d\d-\d\d\S*\s*', '' + $s = $s -replace '\s\(.*$', '' + $s = $s -replace '0x[0-9a-fA-F]{9,}', '0x...' + $s = $s -replace 'thread \S+', 'thread' + if ($s.Length -gt 140) { $s = $s.Substring(0, 140) } + return $s.Trim() +} + +function Warning-Summary([string[]]$lines) { + $counts = @{} + foreach ($l in $lines) { + if ($l -match '\b(WARN|ERROR)\b') { + $k = $l -replace '^\S+\s+', '' -replace '0x[0-9a-fA-F]+', '0x_' -replace '\b\d+\b', 'N' + if ($k.Length -gt 160) { $k = $k.Substring(0, 160) } + if ($counts.ContainsKey($k)) { $counts[$k]++ } else { $counts[$k] = 1 } + } + } + $top = $counts.GetEnumerator() | Sort-Object Value -Descending | Select-Object -First 25 | ForEach-Object { '{0,6}x {1}' -f $_.Value, $_.Key } + return $top +} + +function Finish-Game($j) { + $outLines = @(Job-Lines $j 1048576) + $after = Crash-Logs + $crashLines = @() + foreach ($f in $after.Keys) { + $was = 0; if ($j.CrashBefore.ContainsKey($f)) { $was = $j.CrashBefore[$f] } + if ($after[$f] -gt $was) { $crashLines += @(Read-Tail $f 262144 $was) } + } + $crashLines = @($crashLines | Where-Object { $_ -ne '' }) + $script:State.ran = $j.Sha + Save-State + $crashed = $j.Hung -or ($crashLines.Count -gt 0) -or (($j.Code -ne 0) -and -not $j.UserStopped) + # Fixes that held: open crash reports from older commits this run got past. + foreach ($i in @(Open-Issues 'crash')) { + if ($i.sha -eq $j.Sha) { continue } + $need = [Math]::Max([double]$script:Remote.survive_minutes, 1.5 * [double]$i.at_minutes + 2) + $sig = '' + if ($crashed) { $sig = Crash-Signature $crashLines $outLines $j } + if (($sig -ne $i.signature) -and ($j.Minutes -ge $need)) { + Close-Issue $i "Not seen on ``$($j.Sha)``: the run lasted $($j.Minutes) min (this crash came at $($i.at_minutes) min). Closing; Pilot reopens a new report if it comes back." + } + } + if (-not $crashed) { + Say "the game ended normally after $($j.Minutes) min" + $script:Phase = 'idle' + $script:Detail = 'last run ended without a crash' + return + } + $sig = Crash-Signature $crashLines $outLines $j + $kind = 'crash'; if ($j.Hung) { $kind = 'hang' } + Say "$kind after $($j.Minutes) min: $sig" + $runArgs = (@($j.Args) | Select-Object -Skip 2) -join ' ' + $runEnv = @() + foreach ($k in $j.Env.Keys) { if ($k -ne 'CARGO_TERM_COLOR') { $runEnv += "$k=$($j.Env[$k])" } } + $settings = 'args: `' + $runArgs + '`, env: `' + ($runEnv -join ' ') + '`' + $existing = @(Open-Issues 'crash') | Where-Object { $_.signature -eq $sig } | Select-Object -First 1 + if ($existing) { + if ($existing.seen -notcontains $j.Sha) { + Comment-Issue $existing.number ("Happened again on ``$($j.Sha)`` after $($j.Minutes) min.`n`n" + (Fence $crashLines 120) + "`n`n
Output tail`n`n" + (Fence $outLines 150) + "`n
") + $existing.seen = @($existing.seen) + @($j.Sha); Save-State + } else { Say "same crash as #$($existing.number) on the same commit: not reported again" } + } else { + $body = @( + "Pilot saw a **$kind** after **$($j.Minutes) min** (exit code ``$('0x{0:x8}' -f $j.Code)``).", + '', (Machine-Table), '', "Run: $settings", '', + '### New crashes.log entries', (Fence $crashLines 200), '', + '### Most frequent warnings', (Fence @(Warning-Summary $outLines) 25), '', + '
Output tail (last 250 lines)', '', (Fence $outLines 250), '
', + '', '_Sent by VIctory Pilot. Logs only: no game data._' + ) -join "`n" + $n = New-Issue 'crash' "[Pilot] $($kind): $sig" $body 'crash-report' + Add-Issue $n 'crash' $sig $sig $j.Minutes + } + $script:Phase = 'waiting for a fix' + $script:Detail = "$kind reported; the next commit is built, tested and run by itself" +} + +# What to do next for the current commit. +function Next-Step { + if ($script:Job) { return } + if ($script:Remote.pause) { $script:Phase = 'paused'; $script:Detail = 'paused by remote.json on the branch'; return } + if ($script:State.built -ne $script:LocalSha) { [void](Start-Build); return } + if ($script:Config.run_tests -and ($script:State.tested -ne $script:LocalSha) -and (@($script:Remote.test_crates).Count -gt 0)) { if (Start-Tests) { return } } + if ($script:Config.auto_run -and ($script:State.ran -ne $script:LocalSha) -and $script:Config.game_exe) { if (Start-Game) { return } } + if (-not $script:Config.game_exe) { $script:Phase = 'idle'; $script:Detail = 'built and tested; choose the game when you have it' } + elseif ($script:Phase -ne 'waiting for a fix') { $script:Phase = 'idle'; $script:Detail = 'up to date' } +} + +function Check-Remote([bool]$force = $false) { + $script:LastRemoteCheck = Get-Date + $sha = Remote-Sha + if (-not $sha) { return } + $script:RemoteSha = $sha + if ($sha -eq $script:LocalSha) { return } + if ($script:Job) { + if (-not $script:PendingUpdate) { Say "new commit $(Short $sha) on the branch: applied when the current $($script:Job.Kind) ends" } + $script:PendingUpdate = $true + if ($script:Job.Kind -ne 'game') { Stop-Job 'a newer commit arrived' } + return + } + Say "new commit $(Short $sha): updating" + if (Update-Repo) { Next-Step } +} + +# A status issue the developer can read at a glance, edited in place. +function Heartbeat { + $script:LastHeartbeat = Get-Date + if (-not $script:CanReport) { return } + $job = 'none' + if ($script:Job) { $job = "$($script:Job.Kind), $([Math]::Round(((Get-Date) - $script:Job.Started).TotalMinutes, 1)) min" } + $open = @($script:State.issues | Where-Object { -not $_.closed } | ForEach-Object { "- #$($_.number) ($($_.kind)) $($_.title)" }) + $body = @( + "Pilot status, updated $(Get-Date -Format 'yyyy-MM-dd HH:mm') (local time).", '', + (Machine-Table), '', + "| Phase | $($script:Phase): $($script:Detail) |", '|---|---|', + "| Job | $job |", + "| Game chosen | $([bool]$script:Config.game_exe) |", + "| Built / tested / ran | $(Short $script:State.built) / $(Short $script:State.tested) / $(Short $script:State.ran) |", '', + '### Open reports', $(if ($open.Count) { $open -join "`n" } else { 'none' }), '', + '### Recent activity', (Fence ($script:Activity | Select-Object -Last 30) 30) + ) -join "`n" + $n = 0 + if ($script:State.ContainsKey('status_issue')) { $n = [int]$script:State.status_issue } + if ($n -gt 0) { + $file = Gh-Body $body + $r = Run-Sync 'gh' @('issue', 'edit', "$n", '-R', $Repo, '--body-file', $file) + if ($r.Code -eq 0) { return } + } + $n = New-Issue 'status' "[Pilot] status of $($script:Login)'s PC" $body 'pilot-status' + if ($n -gt 0) { $script:State.status_issue = $n; Save-State } +} + +# ---------------------------------------------------------------- dashboard + +function Choose-Game { + try { + Add-Type -AssemblyName System.Windows.Forms + $d = New-Object System.Windows.Forms.OpenFileDialog + $d.Title = "Choose the game's executable" + $d.Filter = 'Game executable (*.exe)|*.exe' + $owner = New-Object System.Windows.Forms.Form + $owner.TopMost = $true + if ($d.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { return $d.FileName } + } catch { Say "file dialog failed: $_" } + return $null +} + +function Set-Game([string]$path) { + $path = $path.Trim().Trim('"') + if (-not $path) { return 'no path given' } + if (-not (Test-Path -LiteralPath $path)) { return "not found: $path" } + if ($path.StartsWith($RepoDir, [StringComparison]::OrdinalIgnoreCase)) { return 'the game must not be inside the source folder' } + $script:Config.game_exe = $path + Save-Config + Say "game set: $path" + $script:State.ran = '' + Save-State + Next-Step + return 'game set' +} + +function Do-Action([string]$name, [string]$body) { + switch ($name) { + 'run' { if ($script:Job) { return "busy: $($script:Job.Kind)" }; $script:State.ran = ''; if (Start-Game) { return 'game started' } else { return 'could not start the game (see activity)' } } + 'stop' { Stop-Job 'stopped from the dashboard'; return 'stopping' } + 'rebuild' { if ($script:Job) { return "busy: $($script:Job.Kind)" }; $script:State.built = ''; $script:State.tested = ''; Save-State; Next-Step; return 'rebuilding' } + 'test' { if ($script:Job) { return "busy: $($script:Job.Kind)" }; if (Start-Tests) { return 'testing' } else { return 'no tests configured' } } + 'check' { Check-Remote $true; return "checked: branch at $(Short $script:RemoteSha)" } + 'browse' { $p = Choose-Game; if ($p) { return (Set-Game $p) } else { return 'nothing chosen' } } + 'setgame' { return (Set-Game $body) } + 'toggle_run' { $script:Config.auto_run = -not $script:Config.auto_run; Save-Config; return "auto-run: $($script:Config.auto_run)" } + 'toggle_tests' { $script:Config.run_tests = -not $script:Config.run_tests; Save-Config; return "tests: $($script:Config.run_tests)" } + 'report' { + $note = $body.Trim(); if (-not $note) { $note = 'Something looked wrong.' } + if ($note.Length -gt 2000) { $note = $note.Substring(0, 2000) } + $lines = @(); if ($script:Job) { $lines = @(Job-Lines $script:Job) } elseif ($script:LastJob) { $lines = @(Job-Lines $script:LastJob) } + $text = "Report from the player: $note`n`n" + (Machine-Table) + "`n`n### Output tail`n" + (Fence $lines 250) + $n = New-Issue 'note' "[Pilot] player report: $($note.Split("`n")[0])" $text 'crash-report' + Add-Issue $n 'note' $note $note 0 + if ($n -gt 0) { return "sent as #$n" } else { return 'could not send' } + } + 'logs' { Start-Process explorer.exe $LogDir; return 'opened' } + default { return "unknown action $name" } + } +} + +function Status-Json { + $tail = @() + $j = $script:Job; if (-not $j) { $j = $script:LastJob } + if ($j) { $tail = @(@(Job-Lines $j 65536) | Select-Object -Last 120) } + $job = $null + if ($script:Job) { + $job = @{ kind = $script:Job.Kind; minutes = [Math]::Round(((Get-Date) - $script:Job.Started).TotalMinutes, 1); quiet = [Math]::Round(((Get-Date) - $script:Job.LastActivity).TotalMinutes, 1) } + } + $issues = @($script:State.issues | Select-Object -Last 30 | ForEach-Object { @{ number = $_.number; kind = $_.kind; title = $_.title; closed = $_.closed; url = (Issue-Url $_.number) } }) + [array]::Reverse($issues) + $s = @{ + version = $PilotVersion; phase = $script:Phase; detail = $script:Detail + local = $script:LocalSha; subject = $script:Subject; remote = $script:RemoteSha; pending = $script:PendingUpdate + game = $script:Config.game_exe; auto_run = $script:Config.auto_run; run_tests = $script:Config.run_tests + login = $script:Login; can_report = $script:CanReport; repo = $Repo; branch = $Branch + machine = $script:Machine; job = $job; tail = $tail; activity = @($script:Activity | Select-Object -Last 80) + issues = $issues; paused = $script:Remote.pause; profile = $script:Remote.profile + status_issue = $script:State.status_issue; issues_on = $script:IssuesOn + } + return ($s | ConvertTo-Json -Depth 6 -Compress) +} + +function Send-Text($ctx, [string]$text, [string]$type, [int]$code = 200) { + $bytes = [Text.Encoding]::UTF8.GetBytes($text) + $ctx.Response.StatusCode = $code + $ctx.Response.ContentType = $type + $ctx.Response.Headers['Cache-Control'] = 'no-store' + $ctx.Response.OutputStream.Write($bytes, 0, $bytes.Length) +} + +function Serve($ctx) { + $req = $ctx.Request + if ($req.Headers['Host'] -notmatch '^(localhost|127\.0\.0\.1)(:\d+)?$') { Send-Text $ctx 'forbidden' 'text/plain' 403; return } + $path = $req.Url.AbsolutePath + if (($req.HttpMethod -eq 'GET') -and ($path -eq '/')) { Send-Text $ctx $DashboardHtml 'text/html; charset=utf-8'; return } + if (($req.HttpMethod -eq 'GET') -and ($path -eq '/api/status')) { Send-Text $ctx (Status-Json) 'application/json'; return } + if (($req.HttpMethod -eq 'POST') -and $path.StartsWith('/api/')) { + # A custom header: other web pages cannot send it without asking first. + if ($req.Headers['X-Pilot'] -ne '1') { Send-Text $ctx 'forbidden' 'text/plain' 403; return } + $reader = New-Object IO.StreamReader($req.InputStream, [Text.Encoding]::UTF8) + $body = $reader.ReadToEnd() + $msg = Do-Action $path.Substring(5) $body + Send-Text $ctx (@{ message = "$msg" } | ConvertTo-Json -Compress) 'application/json' + return + } + Send-Text $ctx 'not found' 'text/plain' 404 +} + +function Handle-Http { + while ($script:CtxTask -and $script:CtxTask.IsCompleted) { + $ctx = $null + try { $ctx = $script:CtxTask.Result } catch {} + $script:CtxTask = $script:Listener.GetContextAsync() + if (-not $ctx) { continue } + try { Serve $ctx } catch { Say "dashboard error: $_" } + finally { try { $ctx.Response.Close() } catch {} } + } +} + +$DashboardHtml = @' + +VIctory Pilot + + + +

VIctory Pilot

...
+
+
+

Connection

+
GitHub
+
Reports go to
+
Status issue
+
Branch
+
Running commit
+
Latest on branch
+
+

This PC

+
GPU
+
Driver
+
Windows
+
CPU / RAM
+
+

Game

+
Executable
+ + + +
+
+

Controls

+ + + +
+ + +
+
+

Something looked wrong?

+ + +
+
+
+ +

Output

+

Reports

none yet
+

Pilot activity

+
+
+ + +'@ + +# ---------------------------------------------------------------- main + +Say "VIctory Pilot $PilotVersion" +if (-not (Ensure-Tools)) { Read-Host 'Press Enter to close'; exit 1 } +$script:CanReport = Ensure-GitHub +$script:IssuesOn = $false +if ($script:CanReport) { $script:IssuesOn = Ensure-Issues; $script:CanReport = $script:IssuesOn } +$script:Machine = Read-Machine +Say "this PC: $($script:Machine.gpu), driver $($script:Machine.driver), $($script:Machine.windows)" + +$script:Listener = $null +$Port = 0 +foreach ($p in 8765..8775) { + try { + $l = New-Object System.Net.HttpListener + $l.Prefixes.Add("http://localhost:$p/") + $l.Start() + $script:Listener = $l + $Port = $p + break + } catch {} +} +if ($script:Listener) { + $script:CtxTask = $script:Listener.GetContextAsync() + Say "dashboard: http://localhost:$Port/ (keep this window open)" + Start-Process "http://localhost:$Port/" +} else { Say 'could not open the dashboard port: Pilot keeps working in this window' } + +if (Update-Repo) { Next-Step } +Heartbeat + +while ($true) { + Handle-Http + Tick-Job + $now = Get-Date + if (-not $script:Job -and $script:SelfUpdate) { + Say 'restarting into the newer Pilot' + try { Copy-Item -LiteralPath $script:SelfUpdate -Destination $PSCommandPath -Force } catch { Say "could not update Pilot: $_" } + if ($script:Listener) { $script:Listener.Stop() } + exit 3 + } + if (-not $script:Job -and $script:PendingUpdate) { if (Update-Repo) { Next-Step } } + if (($now - $script:LastRemoteCheck).TotalSeconds -ge 60) { Check-Remote } + if (($now - $script:LastHeartbeat).TotalMinutes -ge 10) { Heartbeat } + Start-Sleep -Milliseconds 250 +} diff --git a/scripts/pilot/remote.json b/scripts/pilot/remote.json new file mode 100644 index 0000000000..8dfc4d95c5 --- /dev/null +++ b/scripts/pilot/remote.json @@ -0,0 +1,11 @@ +{ + "note": "Settings for the next Pilot run, set by the developer on the branch. Pilot checks every value against an allowlist and ignores anything else.", + "pause": false, + "profile": "release", + "env": {}, + "args": [], + "test_crates": ["victory-gpu", "victory-hle", "victory-loader"], + "test_filter": "", + "hang_minutes": 5, + "survive_minutes": 10 +} diff --git a/scripts/pilot/watch.sh b/scripts/pilot/watch.sh new file mode 100755 index 0000000000..b75398dd60 --- /dev/null +++ b/scripts/pilot/watch.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# The developer's side of Pilot: waits until a [Pilot] report on the fork is +# new or updated, prints it, and exits 0; exits 2 when none came in time. +# Usage: scripts/pilot/watch.sh [seconds, default 1500] +# PILOT_STATUS=1 also wakes on the status issue (it is edited every 10 min). +set -euo pipefail +repo=${PILOT_REPO:-MfDev0/victory} +seen=${PILOT_SEEN:-${TMPDIR:-/tmp}/pilot-seen.txt} +limit=${1:-1500} +touch "$seen" +filter='.[] | select((.title | startswith("[Pilot] status")) | not)' +if [ "${PILOT_STATUS:-0}" = 1 ]; then filter='.[]'; fi +list() { + gh issue list -R "$repo" --state all --limit 100 --search '"[Pilot]" in:title' \ + --json number,updatedAt,title --jq "$filter"' | "\(.number) \(.updatedAt) \(.title)"' +} +end=$((SECONDS + limit)) +while :; do + now=$(list) + changed=$(grep -vxF -f "$seen" <<<"$now" || true) + if [ -n "$changed" ]; then + echo "== changed Pilot reports" + echo "$changed" + while read -r n _; do + echo + echo "================ #$n" + gh issue view "$n" -R "$repo" --comments | head -c 30000 + done <<<"$changed" + printf '%s\n' "$now" >"$seen" + exit 0 + fi + if [ "$SECONDS" -ge "$end" ]; then + echo "no new Pilot reports in ${limit}s" + exit 2 + fi + sleep 30 +done From d9198edcfd2b2259c240c0aaed0c4142420544da Mon Sep 17 00:00:00 2001 From: Kebap11 Date: Tue, 24 Nov 2026 10:51:15 +0000 Subject: [PATCH 035/123] Shaders: med3 tests its operands for NaN on their bits v_med3_f32 with a NaN operand gives the least operand on the hardware. The NaN test was a float compare: first fcmp uno, which Intel folded to false, then dx.op.isSpecialFloat (IsNaN), but NVIDIA still returned the plain median (upstream Marvisak/VIctory#745: v_med3_f32(1.0, 2.0, NaN) = 2 on an RTX 3050 Ti; #726). Under default shader fast-math a driver may assume no NaNs in either. The operands are now tested as |bits| > +inf, an unsigned integer compare that is true exactly for NaNs, quiet or signalling, of either sign. v_med3_f16 widens its operands first, so it is covered too. The lowering test now asserts the integer compare and neither float form. (ported from raphael-riesner/VIctory commit c7963773, branch shader/med3-nan-bits, tested by its author on the RTX 3050 Ti; the conflict with this fork's IsNaN form was resolved for the bit test) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 51 ++++++++++++++++--------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d9f25e0927..394c656933 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -41,6 +41,9 @@ pub(crate) struct Lowered { pub has_isnan_op: bool, #[cfg(test)] pub has_fcmp_uno: bool, + /// Whether an unsigned integer `>` compare was emitted. + #[cfg(test)] + pub has_iugt: bool, /// The props of each heap handle, in creation order. #[cfg(test)] pub handle_props: Vec<(u32, u32)>, @@ -960,6 +963,8 @@ impl<'a> Lower<'a> { #[cfg(test)] let has_fcmp_uno = self.s.m.has_cmp(pred::UNO); #[cfg(test)] + let has_iugt = self.s.m.has_cmp(pred::IUGT); + #[cfg(test)] let handle_props = { let mut h: Vec<_> = self.handles.iter().map(|(k, v)| (*v, k.4)).collect(); h.sort_unstable(); @@ -981,6 +986,8 @@ impl<'a> Lower<'a> { #[cfg(test)] has_fcmp_uno, #[cfg(test)] + has_iugt, + #[cfg(test)] handle_props, }) } @@ -1607,10 +1614,11 @@ impl<'a> Lower<'a> { /// minimum of the three instead (the host's minimum skips NaNs, so that /// is the smallest number among them). /// - /// Uses `dx.op.isSpecialFloat.f32` (`IsNaN`) instead of `fcmp uno`: some - /// D3D12 drivers (observed on Intel Iris Xe) fold `fcmp uno x, x` to false - /// under default shader fast-math, returning the wrong operand when the - /// third input is NaN. + /// The NaN test is on the operands' bits ([`Self::is_nan_bits`]), not a + /// float compare: drivers fold `fcmp uno x, x` to false under default + /// shader fast-math (observed on Intel Iris Xe and NVIDIA, upstream + /// #726, #745), returning the median where the hardware gives the + /// least operand. An integer compare leaves them nothing to assume. fn med3(&mut self, a: V, b: V, third: V) -> V { let c = self.cur; let lo = self.binary(36, a, b); @@ -1618,17 +1626,26 @@ impl<'a> Lower<'a> { let t = self.binary(36, hi, third); let median = self.binary(35, lo, t); let least = self.binary(36, lo, third); - let is_nan = |l: &mut Self, x: V| { - l.s.op(c, "isSpecialFloat.f32", Attr::ReadNone, l.s.t.i1, 8, &[x]) - }; - let nan_a = is_nan(self, a); - let nan_b = is_nan(self, b); - let nan_c = is_nan(self, third); - let ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b); - let nan = self.s.m.bin(c, Bin::Or, ab, nan_c); + let na = self.is_nan_bits(a); + let nb = self.is_nan_bits(b); + let n3 = self.is_nan_bits(third); + let ab = self.s.m.bin(c, Bin::Or, na, nb); + let nan = self.s.m.bin(c, Bin::Or, ab, n3); self.s.m.select(c, nan, least, median) } + /// Whether `f` is a NaN, tested on its bits (`|f| > +inf` as integers). + /// A float `fcmp uno` is not used: drivers (observed on NVIDIA) assume + /// no NaNs there and fold it to false, so the NaN case was lost. + fn is_nan_bits(&mut self, f: V) -> V { + let c = self.cur; + let bits = self.as_int(f); + let abs = self.s.m.i32(0x7FFF_FFFF); + let inf = self.s.m.i32(0x7F80_0000); + let mag = self.s.m.bin(c, Bin::And, bits, abs); + self.s.m.cmp(c, pred::IUGT, mag, inf) + } + /// `a - floor(a)`, which on the hardware never reaches 1.0: where it /// would round to it (a tiny negative `a`), the result is `below_one`, /// the largest value under 1.0 in the operation's width. Hosts differ @@ -7831,7 +7848,7 @@ mod tests { } #[test] - fn med3_f32_emits_dxil_isnan_instead_of_fcmp_uno() { + fn med3_f32_tests_nan_on_bits_not_a_float_compare() { // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) let src0 = 256 + 1u32; let src1 = 256 + 2u32; @@ -7843,12 +7860,12 @@ mod tests { ]; let lowered = lower_words(&words).unwrap(); assert!( - lowered.has_isnan_op, - "v_med3_f32 must emit dx.op.isSpecialFloat.f32 (IsNaN)" + lowered.has_iugt, + "v_med3_f32 must test NaN as |bits| > +inf, unsigned" ); assert!( - !lowered.has_fcmp_uno, - "v_med3_f32 must not emit fcmp uno (folded away by some drivers)" + !lowered.has_fcmp_uno && !lowered.has_isnan_op, + "v_med3_f32 must not test NaN with floats (folded away by drivers, #726, #745)" ); } From 7c60b9305585b0ef340fc02c98076fb4a3d42b49 Mon Sep 17 00:00:00 2001 From: Peppacodes <360593343+Peppacodes@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:51:40 +0000 Subject: [PATCH 036/123] HLE: a null or empty subkey under our OEM key opens the key itself RegOpenKeyW and RegOpenKeyExW returned ERROR_FILE_NOT_FOUND for any path below our stand-in for HKLM\...\CurrentVersion\OEM, including a null or empty one. The documented behaviour, and the host's: RegOpenKeyW gives back the key it was passed, RegOpenKeyExW a handle to the same key. Other paths below it still are not found (it has no subkeys). Test: both functions with a null and an empty subkey, on our key and on a host key for comparison. Co-Authored-By: Claude Opus 5.5 (ported from Peppacodes/VIctory commit 8e9f9b3, upstream Marvisak/VIctory#765; tested by the author on Windows 11) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-hle/src/modules/xsystem.rs | 43 +++++++++++++++++++++-- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/victory-hle/src/modules/xsystem.rs b/crates/victory-hle/src/modules/xsystem.rs index b40762bd47..625102b2a7 100644 --- a/crates/victory-hle/src/modules/xsystem.rs +++ b/crates/victory-hle/src/modules/xsystem.rs @@ -183,11 +183,20 @@ mod device_type { text.eq_ignore_ascii_case(expected) } - /// Opens our key for its path; the key has no subkeys. `None`: not - /// ours, ask the host. + /// Opens our key for its path; the key has no subkeys, and a null or + /// empty path below it opens the key itself, as the host's do. `None`: + /// not ours, ask the host. fn open(root: Key, sub: *const u16, out: *mut Key) -> Option { if root == oem() { - return Some(FILE_NOT_FOUND); + if !(sub.is_null() || is(sub, "")) { + return Some(FILE_NOT_FOUND); + } + if out.is_null() { + return Some(INVALID_PARAMETER); + } + // SAFETY: checked non-null; the title passes room for a key. + unsafe { out.write(oem()) }; + return Some(SUCCESS); } if root == LOCAL_MACHINE && is(sub, KEY) && !out.is_null() { // SAFETY: checked non-null; the title passes room for a key. @@ -342,6 +351,34 @@ mod device_type { assert_eq!(again, oem()); } + #[test] + fn a_null_or_empty_path_opens_the_key_itself() { + const KEY_READ: u32 = 0x2_0019; + let empty = w(""); + let host_key = w(r"Software\Microsoft\Windows NT\CurrentVersion"); + for (root, path) in [(oem(), w(KEY)), (std::ptr::null_mut(), host_key)] { + // Ours, then the host's for comparison. + let mut key = std::ptr::null_mut(); + assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS); + assert!(root.is_null() || key == root); + for sub in [std::ptr::null(), empty.as_ptr()] { + // `RegOpenKeyW` gives back the key it was passed. + let mut same = std::ptr::null_mut(); + assert_eq!(RegOpenKeyW(key, sub, &mut same), SUCCESS, "{sub:?}"); + assert_eq!(same, key); + // `RegOpenKeyExW` a handle to the same key. + let mut again = std::ptr::null_mut(); + assert_eq!( + RegOpenKeyExW(key, sub, 0, KEY_READ, &mut again), + SUCCESS, + "{sub:?}" + ); + assert_eq!(RegCloseKey(again), SUCCESS); + } + assert_eq!(RegCloseKey(key), SUCCESS); + } + } + #[test] fn other_keys_reach_the_host() { let mut key = std::ptr::null_mut(); From 98f0fcfaf1751705fe8378cffa6da4f38a695ef7 Mon Sep 17 00:00:00 2001 From: Peppacodes <360593343+Peppacodes@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:52:04 +0000 Subject: [PATCH 037/123] HLE: GetProcAddress on our modules sets the last error on a miss GetProcAddress on one of our pseudo modules returned NULL for a name it does not export, or for any ordinal, without setting the last error. The host sets ERROR_PROC_NOT_FOUND (127), and a caller that builds its failure from GetLastError() got 0, HRESULT_FROM_WIN32(0) being S_OK. Test: a missing name on kernel32 (the host's, for comparison), and a missing name and an ordinal on xgameruntime.dll, each after clearing the last error. Co-Authored-By: Claude Opus 5.5 (ported from Peppacodes/VIctory commit d0662f4, upstream Marvisak/VIctory#764; tested by the author on Windows 11. This fork already resolves ordinals on our modules (upstream #512): the last error is set where an ordinal is not exported) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-hle/src/modules/kernel.rs | 28 +++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 1bd037ef21..428fdeaeda 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -165,13 +165,15 @@ pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> * return host_override(module, name).unwrap_or_else(|| host::get_proc_address(module, name)); }; // Values below 0x10000 are ordinals. Our export table names ordinal - // exports `#n`, the same form the import binder looks up. + // exports `#n`, the same form the import binder looks up. A miss fails + // as the host's does, with the last error set. if (name as usize) < 0x1_0000 { let ordinal = format!("#{}", name as usize); return match m.exports.iter().find(|e| e.name == ordinal) { Some(e) => e.address as *mut c_void, None => { tracing::warn!(module = m.name, %ordinal, "GetProcAddress: not implemented"); + host::set_last_error(ERROR_PROC_NOT_FOUND); std::ptr::null_mut() } }; @@ -182,6 +184,7 @@ pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> * Some(e) => e.address as *mut c_void, None => { tracing::warn!(module = m.name, %name, "GetProcAddress: not implemented"); + host::set_last_error(ERROR_PROC_NOT_FOUND); std::ptr::null_mut() } } @@ -363,6 +366,7 @@ fn refuse(file: &str) { } const ERROR_MOD_NOT_FOUND: u32 = 126; +const ERROR_PROC_NOT_FOUND: u32 = 127; pub(crate) fn module() -> HleModule { HleModule { @@ -778,4 +782,26 @@ mod tests { assert_eq!(last, ERROR_INSUFFICIENT_BUFFER); } } + + #[cfg(windows)] + #[test] + fn a_missing_export_of_our_modules_sets_the_last_error() { + use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; + // SAFETY: sets and reads this thread's last error. + let clear = || unsafe { SetLastError(0) }; + // SAFETY: as above. + let last = || unsafe { GetLastError() }; + // The host's own modules, for comparison. + let kernel32 = GetModuleHandleW(w("kernel32.dll").as_ptr()); + clear(); + assert!(GetProcAddress(kernel32, c"NotAnExport".as_ptr().cast()).is_null()); + assert_eq!(last(), ERROR_PROC_NOT_FOUND); + // Ours, by name and by ordinal. + let runtime = LoadLibraryA(c"xgameruntime.dll".as_ptr().cast()); + for name in [c"NotAnExport".as_ptr().cast(), 9999 as *const u8] { + clear(); + assert!(GetProcAddress(runtime, name).is_null()); + assert_eq!(last(), ERROR_PROC_NOT_FOUND, "{name:?}"); + } + } } From a513e7700cf02c799f51e791fbc16443bb94c9a0 Mon Sep 17 00:00:00 2001 From: Peppacodes <360593343+Peppacodes@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:52:09 +0000 Subject: [PATCH 038/123] Loader: find a title DLL whatever its name's case map_dll lowercased the DLL's name and joined that to the title folder. On a case-sensitive folder (WSL creates them so, and new subfolders inherit the flag) GameLib.dll is not gamelib.dll: is_file() was false and the DLL was skipped without an error, so its imports went to stubs and a title's own LoadLibrary saw "not a title image". The lowercased name stays the key (seen, wanted, the returned list). The file is the name as written or, failing that, the folder's entry that matches it ignoring ASCII case, as the Windows loader ignores case. Test: a case-sensitive temp folder (fsutil setCaseSensitiveInfo, no admin) holding Late.dll, loaded as Late.dll, LATE.DLL and late.dll. Skipped where Windows cannot make such a folder. Co-Authored-By: Claude Opus 5.5 (ported from Peppacodes/VIctory commit 1e24f34, upstream Marvisak/VIctory#762; tested by the author on Windows 11) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-loader/src/windows.rs | 30 ++++++++++++++--- crates/victory-loader/tests/title_dlls.rs | 40 ++++++++++++++++++++++- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index 77e5881a58..bdcede78d3 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -156,19 +156,41 @@ fn map_dll( seen: &mut HashSet, loaded: &mut Vec<(String, LoadedImage)>, ) -> Result<()> { - let name = name.to_ascii_lowercase(); - let path = dirs.0.join(&name); - if !seen.insert(name.clone()) || !wanted(&name) || !path.is_file() { + let key = name.to_ascii_lowercase(); + if !seen.insert(key.clone()) || !wanted(&key) { return Ok(()); } + let Some(path) = file_in(dirs.0, name) else { + return Ok(()); + }; let original = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?; let prepared = prepare(&original).with_context(|| format!("preparing {}", path.display()))?; let image = load(&prepared, dirs.1).with_context(|| format!("loading {}", path.display()))?; map_imports(&image.info, dirs, wanted, seen, loaded)?; - loaded.push((name, image)); + loaded.push((key, image)); Ok(()) } +/// The file `name` in `dir`, its case ignored as the Windows loader ignores +/// it. A folder can be case-sensitive (WSL makes the folders it creates +/// so), where joining the name finds only that exact spelling. +fn file_in(dir: &Path, name: &str) -> Option { + let exact = dir.join(name); + if exact.is_file() { + return Some(exact); + } + std::fs::read_dir(dir) + .ok()? + .filter_map(Result::ok) + .find(|e| { + e.file_name() + .to_str() + .is_some_and(|n| n.eq_ignore_ascii_case(name)) + }) + .map(|e| e.path()) + .filter(|p| p.is_file()) +} + /// Resolves through `inner`, then through the exports of the title's DLLs. pub struct WithTitleDlls<'a> { pub inner: &'a dyn ImportResolver, diff --git a/crates/victory-loader/tests/title_dlls.rs b/crates/victory-loader/tests/title_dlls.rs index 49101bf8cc..d3cf3dde2e 100644 --- a/crates/victory-loader/tests/title_dlls.rs +++ b/crates/victory-loader/tests/title_dlls.rs @@ -1,4 +1,5 @@ -//! A title DLL that cannot be loaded is named in the error. +//! Finding the title's DLLs: one that cannot be loaded is named in the +//! error, and a folder's case sensitivity does not hide one. #![cfg(windows)] #[test] @@ -14,3 +15,40 @@ fn a_title_dll_that_does_not_prepare_is_named() { let text = format!("{error:#}"); assert!(text.contains("broken.dll"), "{text}"); } + +/// An empty folder whose names are case-sensitive, as folders WSL creates +/// are (`fsutil file setCaseSensitiveInfo`); `None` where Windows cannot +/// make one. +fn case_sensitive_dir() -> Option { + let dir = tempfile::tempdir().unwrap(); + let made = std::process::Command::new("fsutil.exe") + .args(["file", "setCaseSensitiveInfo"]) + .arg(dir.path()) + .arg("enable") + .output() + .is_ok_and(|o| o.status.success()); + made.then_some(dir) +} + +#[test] +fn a_title_dll_in_a_case_sensitive_folder_is_found_by_any_spelling() { + let Some(title) = case_sensitive_dir() else { + eprintln!("no case-sensitive folders on this machine; skipped"); + return; + }; + // Any real DLL will do; it imports only host DLLs, which are not in the folder. + std::fs::copy( + r"C:\Windows\System32\version.dll", + title.path().join("Late.dll"), + ) + .unwrap(); + let wanted = |_: &str| true; + // As written on disk, and as an import or `LoadLibrary` may spell it. + for name in ["Late.dll", "LATE.DLL", "late.dll"] { + let cache = tempfile::tempdir().unwrap(); + let dlls = + victory_loader::load_title_dll(name, title.path(), cache.path(), &wanted).unwrap(); + let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["late.dll"], "loading {name}"); + } +} From 4012fe905df02fd141d6b7ddcb81a7933ccbc258 Mon Sep 17 00:00:00 2001 From: DrTardis1963 <37927122+DrTardis1963@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:52:47 +0000 Subject: [PATCH 039/123] loader: ensure stack headroom before RtlCaptureStackBackTrace on Windows 10 On Windows 10 10.0.19045, fresh test threads often start with Rsp - TEB.StackLimit in 0x260..0x6c0, causing RtlWalkFrameChain inside RtlCaptureStackBackTrace to hit the stack PAGE_GUARD mid-walk and abort returning 0 frames. Touching one stack page in ensure_stack_headroom() before the walk keeps the full system-walk parity assertion intact without skipping it on Windows 10. (ported from DrTardis1963/VIctory commit 559756c5, upstream Marvisak/VIctory#742: crash::tests::unwinds_like_the_system_walk failed in about half the runs on Windows 10) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-loader/src/crash.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index ae3dab0607..c74ab5cade 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -860,9 +860,19 @@ mod tests { EXCEPTION_RECORD, RtlCaptureContext, RtlCaptureStackBackTrace, }; + /// Advances the thread stack's guard page if `Rsp` sits close enough to + /// `TEB.StackLimit` that Windows 10's `RtlCaptureStackBackTrace` crosses + /// the guard page mid-walk and aborts with zero frames. + #[inline(never)] + fn ensure_stack_headroom() { + let mut page = [0u8; 4096]; + std::hint::black_box(&mut page); + } + #[test] #[inline(never)] fn unwinds_like_the_system_walk() { + ensure_stack_headroom(); // SAFETY: zeroed CONTEXT is valid; both calls write our buffers. let (frames, walked) = unsafe { // `RtlCaptureContext` wants it 16-byte aligned too. From 162b70b8fe864dca9a7535bae081ad254a6f83ce Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:53:46 +0000 Subject: [PATCH 040/123] HLE: a display deferral stands where the system has no display power (#727) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PowerSetRequest(DisplayRequired) answers ERROR_NOT_SUPPORTED on a system with no display power to hold (headless, Remote Desktop, some laptops), and the title's deferral acquire failed with 0x80070032. The deferral is a power hint, so that one refusal now succeeds with the request handed out as usual; close still clears and closes it. Every other refusal keeps its error. Idea and diagnosis from geiyiliyabumo/VIctory commit 5c375286 (upstream Marvisak/VIctory#727), re-done against the current display.rs. Co-authored-by: 给伊莉雅补魔 <98532177+geiyiliyabumo@users.noreply.github.com> Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-hle/src/modules/display.rs | 37 ++++++++++++++++++++--- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/victory-hle/src/modules/display.rs b/crates/victory-hle/src/modules/display.rs index 25c395a869..510c3e52c7 100644 --- a/crates/victory-hle/src/modules/display.rs +++ b/crates/victory-hle/src/modules/display.rs @@ -127,14 +127,30 @@ extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT { } // SAFETY: the request we just created. if unsafe { PowerSetRequest(request, PowerRequestDisplayRequired) } == 0 { - let hr = last_error(); - // SAFETY: as above; not handed out. - unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; - return hr; + // SAFETY: no preconditions. + let code = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + if let Some(hr) = refused_request(code) { + // SAFETY: as above; not handed out. + unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; + return hr; + } + tracing::info!("display deferral: the system holds no display power here (no-op)"); } put(out, request) } +/// What a refused display-required request means for the title: `None` +/// where the deferral still stands, else its error. A system with no +/// display power to hold (headless, Remote Desktop, some laptops without an +/// active display route) answers `ERROR_NOT_SUPPORTED`; the deferral is a +/// power hint, so it succeeds there (upstream #727: the title's acquire +/// failed with 0x80070032). Closing the request is unchanged. +#[cfg(windows)] +fn refused_request(code: u32) -> Option { + const ERROR_NOT_SUPPORTED: u32 = 50; + (code != ERROR_NOT_SUPPORTED).then(|| hresult_from_win32(code)) +} + #[cfg(windows)] extern "system" fn close_deferral(_: This, handle: *mut c_void) { use windows_sys::Win32::Foundation::CloseHandle; @@ -151,7 +167,11 @@ extern "system" fn close_deferral(_: This, handle: *mut c_void) { #[cfg(windows)] fn last_error() -> HRESULT { // SAFETY: no preconditions. - let code = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + hresult_from_win32(unsafe { windows_sys::Win32::Foundation::GetLastError() }) +} + +#[cfg(windows)] +fn hresult_from_win32(code: u32) -> HRESULT { (0x8007_0000 | (code & 0xffff)) as i32 } @@ -231,6 +251,13 @@ mod tests { method::(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, handle); } + #[test] + fn a_system_without_display_power_keeps_the_deferral() { + assert_eq!(refused_request(50), None); + assert_eq!(refused_request(5), Some(0x8007_0005_u32 as HRESULT)); + assert_eq!(refused_request(87), Some(0x8007_0057_u32 as HRESULT)); + } + #[test] fn acquire_deferral_rejects_null_out() { type Acquire = extern "system" fn(This, *mut *mut c_void) -> HRESULT; From 565af2dee20cb7bd0384c251c112e3dfbf1fb2cb Mon Sep 17 00:00:00 2001 From: 9hvn9yt2vk-netizen <360448330+9hvn9yt2vk-netizen@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:13:35 +0100 Subject: [PATCH 041/123] shader: lower v_mad_u64_u32 and v_mad_i64_i32 D.64 = S0.32 * S1.32 + S2.64, written to both dwords of the destination pair. The 32 x 32-bit product always fits in 64 bits, so only the addition wraps. The unsigned form's carry out (VOP3B sdst) is the lane mask of that addition's carry; the signed form's carry is left untracked, so a program that reads it is refused with a reason instead of getting a guess. Both forms were refused as unsupported before ("v_mad_u64_u32 is not supported"), which drops any draw or dispatch whose shader uses them for 64-bit address or index arithmetic. Tests: emit::tests::mad_64_of_32_bit_operands_translates (any OS) checks that both halves and the unsigned carry translate and that reading the signed carry is refused; valu_tests::v_mad_u64_u32_and_v_mad_i64_i32_match_rdna2 (Windows, host GPU and WARP) checks results against 64-bit reference arithmetic, including wrapping products and addends and the carry. Co-Authored-By: Claude Opus 5.5 (ported from 9hvn9yt2vk-netizen/VIctory commit 7e5ab6a1, upstream Marvisak/VIctory#734; the test helper adapted to resource::track taking the structure) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 38 +++++++++ crates/victory-shader/src/emit/mod.rs | 83 ++++++++++++++++++++ crates/victory-shader/src/emit/valu_tests.rs | 70 +++++++++++++++++ 3 files changed, 191 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 394c656933..525c00b6df 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4837,6 +4837,44 @@ impl<'a> Lower<'a> { } Ok(()) } + "v_mad_u64_u32" | "v_mad_i64_i32" => { + // D.64 = S0.32 * S1.32 + S2.64. The 32 × 32-bit product + // always fits in 64 bits, so only the addition wraps. + let signed = name == "v_mad_i64_i32"; + let (a, bb) = (s(self, 0)?, s(self, 1)?); + let addend = self.src64(inst, 2)?; + let i64t = self.s.m.int(64); + let ext = if signed { Cast::SExt } else { Cast::ZExt }; + let a = self.s.m.cast(c, ext, a, i64t); + let bb = self.s.m.cast(c, ext, bb, i64t); + let product = self.s.m.bin(c, Bin::Mul, a, bb); + let r = self.s.m.bin(c, Bin::Add, product, addend); + if v.clamp { + return Err("a clamped 64-bit multiply-add"); + } + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 64-bit result"); + }; + let (lo, hi) = self.split64(r); + self.write(inst, Reg::V(reg), lo, guard); + self.write(inst, Reg::V(reg + 1), hi, guard); + // The carry out of the unsigned addition, a lane mask: this + // lane's bit. Left untracked for the signed form, whose + // carry nothing documents. + if !signed + && let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + let carry = self.s.m.cmp(c, pred::IULT, r, addend); + self.lane_bits.insert(w, carry); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } "v_readlane_b32" => { let (a, lane) = (s(self, 0)?, s(self, 1)?); // A computed lane in a pixel or vertex program is a host lane diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 4121fde063..3d3f8392b9 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -920,6 +920,89 @@ mod tests { ); } } + + /// Translates a one-lane compute program that copies root constants + /// s0..s3 to v1..v4, runs `body` and stores v0 to a raw UAV (the frame + /// of the GPU tests in `valu_tests`), so a value `body` cannot produce + /// stops the translation. + fn translate_stored(body: &[u32]) -> Result { + use crate::native::{ResourceType, RootParam, UsedResource}; + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + ]; + for i in 0..4 { + words.push(0x7E00_0200 | (i + 1) << 17 | i); // v_mov_b32 v(i+1), s(i) + } + words.extend_from_slice(body); + // buffer_store_dword v0, off, s[8:11], 0; s_endpgm + words.extend_from_slice(&[0xE070_0000, 0x8002_0000, 0xBF81_0000]); + let param = |root, sgprs, user_data, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + param(RootType::Constants, 4, 0, 0), + param(RootType::Table, 1, 4, 1), + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native)?; + let container = crate::dxbc::build(&[]); + let c = Container::parse(&container).unwrap(); + emit(&c, &native, &p, &st, &io, &res) + } + + /// The 64-bit multiply-adds of 32-bit operands translate, both halves + /// of the result and the unsigned form's carry; reading the signed + /// form's carry, which is not modelled, is refused with a reason. + #[test] + fn mad_64_of_32_bit_operands_translates() { + for op in [0x176u32, 0x177] { + // v_mad_{u64_u32,i64_i32} v[5:6], vcc_lo, v1, v2, v[3:4] + let mad = [0xD400_6A05 | op << 16, 0x040E_0501]; + for mov in [0x7E00_0305, 0x7E00_0306] { + // v_mov_b32 v0, v5 / v6 + translate_stored(&[mad[0], mad[1], mov]).unwrap(); + } + // v_cndmask_b32 v0, 0, 1, vcc_lo + let carry = translate_stored(&[mad[0], mad[1], 0xD501_0000, 0x01A9_0280]); + if op == 0x176 { + carry.unwrap(); + } else { + assert!( + matches!(carry, Err(ShaderError::Unsupported { .. })), + "{carry:?}" + ); + } + } + } } #[cfg(test)] diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index a23533cd10..aa6a93c16c 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1110,3 +1110,73 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +/// VOP3B `op vdst, sdst, src0, src1, src2` (no modifiers). +const fn vop3b(op: u16, vdst: u8, sdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + let [w0, w1] = vop3(op, vdst, src0, src1, src2); + [w0 | (sdst as u32 & 0x7F) << 8, w1] +} + +/// 32 × 32-bit inputs where the product or the 64-bit addend reach their +/// extremes, so both the multiply and the add wrap. +const MAD64_CASES: &[[u32; 4]] = &[ + [0, 0, 0, 0], + [1, 1, 0, 0], + [0xffff_ffff, 0xffff_ffff, 0, 0], + [0xffff_ffff, 0xffff_ffff, 0xffff_ffff, 0xffff_ffff], + [0xffff_ffff, 0xffff_ffff, 0x0000_0002, 0], + [0x8000_0000, 0x8000_0000, 0, 0x8000_0000], + [0x8000_0000, 0x7fff_ffff, 0x1234_5678, 0x9abc_def0], + [0x7fff_ffff, 0x7fff_ffff, 0xffff_ffff, 0x7fff_ffff], + [0xffff_fffe, 3, 1, 0], + [0x0001_0000, 0x0001_0000, 0xffff_ffff, 0xffff_ffff], + [0xdead_beef, 0x1337_c0de, 0x0bad_f00d, 0xfeed_face], +]; + +/// The 64-bit result and the carry out of the addition (unsigned form). +fn mad64(inp: [u32; 4], signed: bool) -> (u64, bool) { + let addend = u64::from(inp[2]) | u64::from(inp[3]) << 32; + let product = if signed { + (i64::from(inp[0] as i32) * i64::from(inp[1] as i32)) as u64 + } else { + u64::from(inp[0]) * u64::from(inp[1]) + }; + product.overflowing_add(addend) +} + +#[test] +fn v_mad_u64_u32_and_v_mad_i64_i32_match_rdna2() { + // v_mad_{u64_u32,i64_i32} v[5:6], vcc_lo, v1, v2, v[3:4] (VOP3B 0x176, + // 0x177), then v_mov_b32 v0, v5 (low dword) or v6 (high dword). + for (op, signed, form) in [ + (0x176, false, "v_mad_u64_u32"), + (0x177, true, "v_mad_i64_i32"), + ] { + let mad = vop3b(op, 5, 106, vgpr(1), vgpr(2), vgpr(3)); + for (half, reg) in [("low", 5), ("high", 6)] { + let shader = build_valu_cs(&[mad[0], mad[1], vop1(0x001, 0, vgpr(reg))]); + run_cases(&shader, MAD64_CASES, |backend, _, inp, got| { + let r = mad64(inp, signed).0; + let want = if reg == 5 { r as u32 } else { (r >> 32) as u32 }; + assert_eq!( + got, want, + "{backend}: {form}({:#x}, {:#x}, {:#x}{:08x}) {half} = {got:#010x}, \ + want {want:#010x}", + inp[0], inp[1], inp[3], inp[2], + ); + }); + } + } + // The unsigned form's carry out: v_cndmask_b32 v0, 0, 1, vcc_lo. + let mad = vop3b(0x176, 5, 106, vgpr(1), vgpr(2), vgpr(3)); + let pick = vop3(0x101, 0, 128, 129, 106); + let shader = build_valu_cs(&[mad[0], mad[1], pick[0], pick[1]]); + run_cases(&shader, MAD64_CASES, |backend, _, inp, got| { + let want = u32::from(mad64(inp, false).1); + assert_eq!( + got, want, + "{backend}: v_mad_u64_u32({:#x}, {:#x}, {:#x}{:08x}) carry = {got}, want {want}", + inp[0], inp[1], inp[3], inp[2], + ); + }); +} From 6cd5aab5199284d7e899590d98d863823be507e7 Mon Sep 17 00:00:00 2001 From: 9hvn9yt2vk-netizen <360448330+9hvn9yt2vk-netizen@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:16:44 +0100 Subject: [PATCH 042/123] shader: lower v_ldexp_f32, v_frexp_mant_f32 and v_frexp_exp_i32_f32 v_ldexp_f32: DXIL has no ldexp, so x is multiplied by three powers of two that are each a normal float (q, q and e - 2q for q = e / 3). The exponent is clamped to [-375, 378] first: past that any finite nonzero x is already at zero or infinity, and inside it each factor's exponent stays in [-126, 127]. Zeros, infinities and NaN pass through the multiplies unchanged. v_frexp_mant_f32 and v_frexp_exp_i32_f32 work on the bits, so denormals are normalized whatever the host's float mode: the significand keeps the sign with a magnitude in [0.5, 1), and x = significand * 2^exponent. Zero, infinity and NaN return themselves and exponent 0. All three were refused as unsupported before ("v_ldexp_f32 is not supported"), which drops any draw or dispatch whose shader uses them. Tests: emit::tests::ldexp_and_frexp_translate (any OS) checks that the VOP1/VOP3 forms, with abs and neg, translate. On Windows (host GPU and WARP), valu_tests::v_frexp_mant_and_exp_f32_match_rdna2 covers zeros, infinities, NaNs, both ends of the normal range and denormals, and valu_tests::v_ldexp_f32_scales_by_any_exponent covers exponents a single factor cannot hold, i32::MIN and i32::MAX, overflow, underflow and the special values (normal inputs and results only, so the host's denormal mode cannot change them). Co-Authored-By: Claude Opus 5.5 (ported from 9hvn9yt2vk-netizen/VIctory commit a0d66526, upstream Marvisak/VIctory#734) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 95 +++++++++++++++ crates/victory-shader/src/emit/mod.rs | 13 +++ crates/victory-shader/src/emit/valu_tests.rs | 115 +++++++++++++++++++ 3 files changed, 223 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 525c00b6df..741842e153 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1687,6 +1687,85 @@ impl<'a> Lower<'a> { self.s.m.select(c, exact, zero, r) } + /// `x * 2^e` for any i32 `e`, rounded once unless the result is a + /// denormal. DXIL has no ldexp: `x` is multiplied by three powers of + /// two that are each a normal float. Past ±375 any finite nonzero `x` + /// is already at zero or infinity, so `e` is clamped to [-375, 378], + /// which keeps each of q, q and e - 2q (q = e / 3) inside [-126, 127]. + fn ldexp(&mut self, x: V, e: V) -> V { + let c = self.cur; + let (lo, hi) = (self.s.m.i32(-375i32 as u32), self.s.m.i32(378)); + let below = self.s.m.cmp(c, pred::SLT, e, lo); + let e = self.s.m.select(c, below, lo, e); + let above = self.s.m.cmp(c, pred::SGT, e, hi); + let e = self.s.m.select(c, above, hi, e); + let three = self.s.m.i32(3); + let q = self.s.m.bin(c, Bin::SDiv, e, three); + let two_q = self.s.m.bin(c, Bin::Add, q, q); + let rest = self.s.m.bin(c, Bin::Sub, e, two_q); + let mut r = x; + for k in [q, q, rest] { + // 2^k for k in [-126, 127]: the biased exponent alone. + let (bias, at) = (self.s.m.i32(127), self.s.m.i32(23)); + let biased = self.s.m.bin(c, Bin::Add, k, bias); + let bits = self.s.m.bin(c, Bin::Shl, biased, at); + let factor = self.as_float(bits); + r = self.s.m.bin(c, Bin::Mul, r, factor); + } + r + } + + /// The significand (bits of a float with magnitude in [0.5, 1), the + /// sign kept) and the exponent of the f32 with bits `x`, so that + /// x = significand * 2^exponent, worked on the bits so that denormals + /// are normalized whatever the host's float mode. Zero gives itself and + /// 0; infinity and NaN give themselves and 0. + fn frexp(&mut self, x: V) -> (V, V) { + let c = self.cur; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (at, ff) = (k(self, 23), k(self, 0xFF)); + let field = self.s.m.bin(c, Bin::LShr, x, at); + let field = self.s.m.bin(c, Bin::And, field, ff); + let frac_mask = k(self, 0x7F_FFFF); + let frac = self.s.m.bin(c, Bin::And, x, frac_mask); + let sign_mask = k(self, 0x8000_0000); + let sign = self.s.m.bin(c, Bin::And, x, sign_mask); + // A denormal's leading one at bit 31 - lz moves to bit 23. + let lz = self.s.op( + c, + "unaryBits.i32", + Attr::ReadNone, + self.s.t.i32, + 33, + &[frac], + ); + let (eight, k31) = (k(self, 8), k(self, 31)); + let sh = self.s.m.bin(c, Bin::Sub, lz, eight); + let sh = self.s.m.bin(c, Bin::And, sh, k31); + let normalized = self.s.m.bin(c, Bin::Shl, frac, sh); + let normalized = self.s.m.bin(c, Bin::And, normalized, frac_mask); + let zero = k(self, 0); + let denormal = self.s.m.cmp(c, pred::EQ, field, zero); + let frac = self.s.m.select(c, denormal, normalized, frac); + let half = k(self, 0x3F00_0000); + let m = self.s.m.bin(c, Bin::Or, sign, half); + let m = self.s.m.bin(c, Bin::Or, m, frac); + // Exponents: field - 126, or -117 - lz for a denormal. + let (k126, k117) = (k(self, 126), k(self, -117i32 as u32)); + let e_normal = self.s.m.bin(c, Bin::Sub, field, k126); + let e_denormal = self.s.m.bin(c, Bin::Sub, k117, lz); + let e = self.s.m.select(c, denormal, e_denormal, e_normal); + // Zero, infinity and NaN. + let magnitude = k(self, 0x7FFF_FFFF); + let magnitude = self.s.m.bin(c, Bin::And, x, magnitude); + let is_zero = self.s.m.cmp(c, pred::EQ, magnitude, zero); + let special = self.s.m.cmp(c, pred::EQ, field, ff); + let keep = self.s.m.bin(c, Bin::Or, is_zero, special); + let m = self.s.m.select(c, keep, x, m); + let e = self.s.m.select(c, keep, zero, e); + (m, e) + } + /// The high dword of a 32 × 32-bit product. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V { let c = self.cur; @@ -4533,6 +4612,22 @@ impl<'a> Lower<'a> { } Ok(()) } + "v_ldexp_f32" => { + let (x, e) = (f(self, 0)?, s(self, 1)?); + let r = self.ldexp(x, e); + float(self, r) + } + "v_frexp_mant_f32" | "v_frexp_exp_i32_f32" => { + let x = f(self, 0)?; + let x = self.as_int(x); + let (m, e) = self.frexp(x); + if name == "v_frexp_mant_f32" { + let m = self.as_float(m); + float(self, m) + } else { + int(self, e) + } + } "v_ffbh_u32" | "v_ffbh_i32" => { // Counted from the top bit, -1 when none (DXIL's too). let a = s(self, 0)?; diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 3d3f8392b9..0ae1ced27f 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1003,6 +1003,19 @@ mod tests { } } } + + /// v_ldexp_f32, v_frexp_mant_f32 and v_frexp_exp_i32_f32 translate. + #[test] + fn ldexp_and_frexp_translate() { + // v_ldexp_f32 v0, v1, v2 + translate_stored(&[0xD762_0000, 0x0002_0501]).unwrap(); + // v_frexp_mant_f32 v0, v1; v_frexp_exp_i32_f32 v0, v1 + translate_stored(&[0x7E00_8101]).unwrap(); + translate_stored(&[0x7E00_7F01]).unwrap(); + // VOP3 forms with |v1| and -v1. + translate_stored(&[0xD5C0_0100, 0x0000_0101]).unwrap(); + translate_stored(&[0xD5BF_0000, 0x2000_0101]).unwrap(); + } } #[cfg(test)] diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index aa6a93c16c..3b9485a912 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1180,3 +1180,118 @@ fn v_mad_u64_u32_and_v_mad_i64_i32_match_rdna2() { ); }); } + +/// f32 bits of values whose significand and exponent RDNA2 returns exactly: +/// zeros, infinities, NaNs, normals at both ends of the range and +/// denormals (normalized: v_frexp works on the bits). +const FREXP_CASES: &[u32] = &[ + 0x0000_0000, // +0 + 0x8000_0000, // -0 + 0x7f80_0000, // +inf + 0xff80_0000, // -inf + 0x7fc0_0000, // NaN + 0xffc0_0001, // NaN with a payload + 0x3f80_0000, // 1.0 + 0xbf80_0000, // -1.0 + 0x3eff_ffff, // just below 0.5 + 0x4049_0fdb, // pi + 0x0080_0000, // smallest normal + 0x7f7f_ffff, // largest finite + 0xff7f_ffff, + 0x0000_0001, // smallest denormal + 0x8000_0001, + 0x007f_ffff, // largest denormal + 0x0040_0000, + 0x0000_ffff, +]; + +/// (significand bits, exponent) as RDNA2's v_frexp_mant_f32 and +/// v_frexp_exp_i32_f32 give them. +fn frexp_ref(x: u32) -> (u32, i32) { + let field = (x >> 23 & 0xFF) as i32; + let frac = x & 0x7F_FFFF; + if x & 0x7FFF_FFFF == 0 || field == 0xFF { + return (x, 0); + } + let (frac, e) = if field == 0 { + let lz = frac.leading_zeros(); + ((frac << (lz - 8)) & 0x7F_FFFF, -117 - lz as i32) + } else { + (frac, field - 126) + }; + (x & 0x8000_0000 | 0x3F00_0000 | frac, e) +} + +#[test] +fn v_frexp_mant_and_exp_f32_match_rdna2() { + let cases: Vec<[u32; 4]> = FREXP_CASES.iter().map(|&x| [x, 0, 0, 0]).collect(); + // Every case: the significand times 2^exponent gives the input back. + for &x in FREXP_CASES { + let (m, e) = frexp_ref(x); + let back = f64::from(f32::from_bits(m)) * 2f64.powi(e); + let want = f64::from(f32::from_bits(x)); + assert!(back == want || want.is_nan(), "{x:#010x}"); + } + // v_frexp_mant_f32 v0, v1 (VOP1 0x40) + let mant = build_valu_cs(&[vop1(0x040, 0, vgpr(1))]); + run_cases(&mant, &cases, |backend, _, inp, got| { + let want = frexp_ref(inp[0]).0; + assert_eq!( + got, want, + "{backend}: v_frexp_mant_f32({:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); + // v_frexp_exp_i32_f32 v0, v1 (VOP1 0x3f) + let exp = build_valu_cs(&[vop1(0x03f, 0, vgpr(1))]); + run_cases(&exp, &cases, |backend, _, inp, got| { + let want = frexp_ref(inp[0]).1; + assert_eq!( + got as i32, want, + "{backend}: v_frexp_exp_i32_f32({:#010x}) = {}, want {want}", + inp[0], got as i32, + ); + }); +} + +#[test] +fn v_ldexp_f32_scales_by_any_exponent() { + // v_ldexp_f32 v0, v1, v2 (VOP3 0x362). Results stay normal (or zero, + // or infinity) so the host's denormal mode cannot change them. + let shader = build_valu_cs(&vop3(0x362, 0, vgpr(1), vgpr(2), 0)); + let inf = f32::INFINITY.to_bits(); + let cases: &[(u32, i32, u32)] = &[ + (1.0f32.to_bits(), 0, 1.0f32.to_bits()), + (1.0f32.to_bits(), 127, 0x7f00_0000), + (1.0f32.to_bits(), 128, inf), + (1.0f32.to_bits(), -126, 0x0080_0000), + (1.5f32.to_bits(), -1, 0.75f32.to_bits()), + ((-3.0f32).to_bits(), 4, (-48.0f32).to_bits()), + // Exponents past what one power-of-two factor holds. + (0x0080_0000, 253, 0x7f00_0000), + (0x7f00_0000, -253, 0x0080_0000), + (0x0080_0000, 254, inf), + (0x7f7f_ffff, -253, 0x00ff_ffff), + // Overflow and underflow from any finite nonzero input. + (0x0080_0000, i32::MAX, inf), + ((-1.0e-30f32).to_bits(), 1000, 0xff80_0000), + (0x7f7f_ffff, i32::MIN, 0), + ((-0.5f32).to_bits(), -400, 0x8000_0000), + // Zeros, infinities and NaN keep their value. + (0x8000_0000, 1000, 0x8000_0000), + (inf, -1000, inf), + (0xff80_0000, 0, 0xff80_0000), + ]; + let inputs: Vec<[u32; 4]> = cases.iter().map(|&(x, e, _)| [x, e as u32, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].2; + assert_eq!( + got, want, + "{backend}: v_ldexp_f32({:#010x}, {}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1] as i32, + ); + }); + run_cases(&shader, &[[0x7fc0_0000, 10, 0, 0]], |backend, _, _, got| { + assert!(f32::from_bits(got).is_nan(), "{backend}: {got:#010x}"); + }); +} From 11f3dd866e654c8fb8c352881941195fa47ae831 Mon Sep 17 00:00:00 2001 From: 9hvn9yt2vk-netizen <360448330+9hvn9yt2vk-netizen@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:06:46 +0100 Subject: [PATCH 043/123] shader: run the console's 64-lane waves on hosts without them (NVIDIA) A compute program whose lanes read each other (lane reads, DPP, swizzles, ballots, v_mbcnt, wave reductions) or share LDS within one wave without barriers declares the console's wave size. With a wave64 program that is WaveSize(64), which only AMD's GPUs run: NVIDIA's (32 lanes) and Intel's refuse the pipeline, so every such dispatch was dropped there. victory-gpu now reads the host's lane counts (D3D12 OPTIONS1) at device creation and tells the translation (emit::set_host_wave64; the shader cache keys on it). Without 64-lane waves, a group that is one console wave (at most 64 threads) declares no wave size and runs its cross-lane steps through 64 group-shared slots between two group barriers: console lane n is the thread with flattened id n; a lane read stores, syncs and loads the source lane's slot; a ballot and a wave reduction or prefix sum gather every lane's slot; v_readfirstlane reads lane 0; each LDS access gets a barrier before it, which gives the console's lockstep order. A barrier must be reached by every thread, so these steps are allowed only in blocks every lane reaches (no per-lane branch reaches them unless they post-dominate it) and outside guarded code. Elsewhere, and in groups of several 64-lane waves, the program is refused with a reason instead of producing a pipeline the host rejects. Scalar branches stay uniform since every scalar value made from vector data comes through these steps. Hosts with 64-lane waves (AMD) translate exactly as before. Tests: emit::wave64_fixtures (any OS) checks that one-wave programs with lane reads, a ballot, v_mbcnt, LDS, DPP, v_readfirstlane and ds_swizzle translate both ways, and that a lane read under a per-lane branch and a two-wave group are refused without 64-lane waves. Two GPU tests in valu_tests (Windows) run those programs as 64 threads translated for a host without 64-lane waves and compare every lane's results. Co-Authored-By: Claude Opus 5.5 Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> (ported from 9hvn9yt2vk-netizen/VIctory commit 61b04f70, upstream Marvisak/VIctory#734. Adapted to this tree: read_lane's new callers here, the quad gradients of implicit-LOD sampling and v_permlane16, pass on its refusal; resource::track takes the structure; test Parts gain host_wave64. A retail run on an RTX 4080 by Xeltax: 114 compute pipelines the host refused on main, none with this; the rest are refused by the translator with a reason.) --- crates/victory-gpu/src/host.rs | 21 + crates/victory-gpu/src/shader_cache.rs | 4 +- crates/victory-shader/src/emit/lower.rs | 389 ++++++++++++++++-- crates/victory-shader/src/emit/mod.rs | 26 ++ crates/victory-shader/src/emit/valu_tests.rs | 77 ++++ .../src/emit/waterfall_tests.rs | 1 + .../src/emit/wave64_fixtures.rs | 199 +++++++++ 7 files changed, 689 insertions(+), 28 deletions(-) create mode 100644 crates/victory-shader/src/emit/wave64_fixtures.rs diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 1cd846deca..058be0f5ec 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -255,6 +255,27 @@ fn create() -> windows::core::Result { } } let device = device.ok_or_else(windows::core::Error::empty)?; + // Lane counts: without 64-lane waves (NVIDIA, Intel) the translation + // runs the console's 64-lane waves through group-shared memory where + // it can (victory_shader::emit::host_wave64). Set before the first + // translation, which the shader cache's key includes. + let mut lanes = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + if device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS1, + (&raw mut lanes).cast(), + size_of_val(&lanes) as u32, + ) + .is_ok() + { + victory_shader::emit::set_host_wave64(lanes.WaveLaneCountMin, lanes.WaveLaneCountMax); + tracing::info!( + min = lanes.WaveLaneCountMin, + max = lanes.WaveLaneCountMax, + wave64 = victory_shader::emit::host_wave64(), + "host wave lanes" + ); + } let messages = debug .then(|| device.cast::().ok()) .flatten(); diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index f25e62518a..a7ee403073 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -38,7 +38,8 @@ pub(crate) fn counts() -> (u64, u64) { /// What identifies this build: the BLAKE3 of our executable file and of /// the translation settings it runs with (the loop limit, which a -/// diagnostics build can change at run time). +/// diagnostics build can change at run time, and whether the host device +/// runs 64-lane waves, known once it is created). fn build() -> &'static [u8; 32] { static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); BUILD.get_or_init(|| { @@ -53,6 +54,7 @@ fn build() -> &'static [u8; 32] { match exe { Ok(mut bytes) => { bytes.extend_from_slice(&limit.to_le_bytes()); + bytes.push(u8::from(victory_shader::emit::host_wave64())); *blake3::hash(&bytes).as_bytes() } Err(e) => { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 741842e153..2e56eb394a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -66,6 +66,8 @@ pub(crate) struct Parts<'a> { pub prims: Vec, /// Mesh: what the group id arrives multiplied by. pub mesh_stride: u32, + /// The host runs 64-lane waves ([`super::host_wave64`]). + pub host_wave64: bool, } enum Stop { @@ -251,6 +253,127 @@ struct Lower<'a> { counters: HashMap)>, /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. abort: Option, + /// Compute needing the console's 64-lane wave on a host without one, + /// in a group that is that one wave: cross-lane steps go through + /// group-shared memory ([`Emulated`]). + emulated: Option, + /// Compute needing the console's 64-lane waves on a host without them, + /// in a group of several waves: refused. + wave64_refused: bool, + /// Guarded code being lowered ([`Lower::begin_guarded`] depth). + guard_depth: u32, +} + +/// The console's 64-lane wave as one thread group on a host whose waves +/// are narrower (NVIDIA's 32). Console lane n is the thread with flattened +/// id n; a step that reads other lanes (a lane read, a ballot, a wave +/// reduction) stores each lane's value in group-shared slots and reads +/// them back between two group barriers, and LDS accesses, which the +/// console's lanes make in lockstep, get a barrier before each. A barrier +/// must be reached by every thread of the group, so these steps are only +/// allowed where every lane runs: blocks no lane-dependent branch decides +/// on ([`uniform_blocks`]), outside guarded code; elsewhere the program +/// is refused with a reason. Scalar branches stay uniform because every +/// scalar value made from vector data comes through these same steps. +struct Emulated { + /// Threads in the group (at most 64): the console lanes that exist. + lanes: u32, + /// Per IR block: every lane that runs the program runs it. + uniform: Vec, + /// The exchange slots, `[64 x i32]` in group-shared memory. + slots: Option, +} + +/// Per IR block of `st`: whether every lane that runs the program reaches +/// it when any does. A block is not uniform when a branch on a per-lane +/// condition reaches it without strictly post-dominating that branch +/// (lanes reconverge only there), or when it cannot reach the end of the +/// program (no post-dominance to rely on). +fn uniform_blocks(st: &Structured) -> Vec { + let n = st.exits.len(); + let words = n.div_ceil(64); + let succs: Vec> = st + .exits + .iter() + .map(|e| match *e { + LaneExit::Jump(t) => vec![t], + LaneExit::Branch { + taken, not_taken, .. + } => vec![taken, not_taken], + LaneExit::End | LaneExit::Indirect => Vec::new(), + }) + .collect(); + // Post-dominators as bit sets: pd(b) = {b} + the meet over successors. + let mut pd: Vec> = (0..n) + .map(|b| { + if succs[b].is_empty() { + let mut v = vec![0u64; words]; + v[b / 64] |= 1 << (b % 64); + v + } else { + vec![u64::MAX; words] + } + }) + .collect(); + let mut changed = true; + while changed { + changed = false; + for b in (0..n).rev() { + if succs[b].is_empty() { + continue; + } + let mut v = vec![u64::MAX; words]; + for &t in &succs[b] { + for (w, x) in v.iter_mut().zip(&pd[t]) { + *w &= x; + } + } + v[b / 64] |= 1 << (b % 64); + if v != pd[b] { + pd[b] = v; + changed = true; + } + } + } + let mut preds = vec![Vec::new(); n]; + for (b, ss) in succs.iter().enumerate() { + for &t in ss { + preds[t].push(b); + } + } + let mut ends = vec![false; n]; + let mut stack: Vec = (0..n).filter(|&b| succs[b].is_empty()).collect(); + while let Some(b) = stack.pop() { + if !std::mem::replace(&mut ends[b], true) { + stack.extend(preds[b].iter().copied()); + } + } + let mut uniform = ends; + for (d, e) in st.exits.iter().enumerate() { + let LaneExit::Branch { when, .. } = *e else { + continue; + }; + if st + .bools + .support(when) + .iter() + .all(|a| matches!(a, Atom::Uniform(_))) + { + continue; + } + let mut seen = vec![false; n]; + let mut stack = succs[d].clone(); + while let Some(x) = stack.pop() { + if std::mem::replace(&mut seen[x], true) { + continue; + } + if x == d || pd[d][x / 64] >> (x % 64) & 1 == 0 { + uniform[x] = false; + } + stack.extend(succs[x].iter().copied()); + } + } + uniform } /// Iterations after which a loop is left (per entry into it), unless @@ -412,6 +535,7 @@ impl<'a> Lower<'a> { && (i.name().contains("store") || i.name().contains("atomic")) }); let mut console_lanes = false; + let (mut emulated, mut wave64_refused) = (None, false); if let StageIo::Cs(cs) = x.native.io { s.threads = Some(cs.threads); s.lds_dwords = cs.lds_bytes() / 4; @@ -454,9 +578,22 @@ impl<'a> Lower<'a> { }) }; let wave = if x.native.wave64 { 64 } else { 32 }; - let one_wave = cs.threads.iter().product::() <= wave; + let lanes = cs.threads.iter().product::(); + let one_wave = lanes <= wave; if console_lanes || one_wave && s.lds_dwords > 0 { - s.wave_size = Some(wave); + if wave == 64 && !x.host_wave64 { + if one_wave { + emulated = Some(Emulated { + lanes, + uniform: uniform_blocks(x.st), + slots: None, + }); + } else { + wave64_refused = true; + } + } else { + s.wave_size = Some(wave); + } } } let mut no_barrier = HashSet::new(); @@ -571,6 +708,9 @@ impl<'a> Lower<'a> { code_table: None, counters: HashMap::new(), abort: None, + emulated, + wave64_refused, + guard_depth: 0, } } @@ -821,6 +961,9 @@ impl<'a> Lower<'a> { let x = self.i32_of(src)?; let id = self.s.m.i32(ident); let x = self.s.m.select(c, on, x, id); + if self.emulated.is_some() { + return self.emulated_shape(op, x, prefix); + } self.s.flags |= flags::WAVE_OPS; let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF); let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); @@ -877,7 +1020,76 @@ impl<'a> Lower<'a> { Ok(if float { self.as_int(r) } else { r }) } + /// [`Emulated`]: the reduction (or, with `prefix` set to whether it is + /// inclusive, the prefix sum) of `x` over the console lanes; lanes + /// outside the operation's mask already hold its identity. + fn emulated_shape( + &mut self, + op: super::wave::Op, + x: V, + prefix: Option, + ) -> Result { + use super::wave::Op; + let c = self.cur; + self.emulated_here(self.cur_ir, c)?; + if prefix.is_some() && !matches!(op, Op::AddU | Op::AddF) { + return Err("a wave prefix of an operation other than a sum"); + } + let vals = self.gather(c, x); + let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF); + let me = self.mesh_thread(); + let mut acc: Option = None; + for (n, v) in vals.into_iter().enumerate() { + let v = if float { self.as_float(v) } else { v }; + let v = match prefix { + Some(inclusive) => { + // Lanes below this one (and this one when inclusive). + let k = self.s.m.i32(n as u32); + let p = if inclusive { pred::IULE } else { pred::IULT }; + let below = self.s.m.cmp(c, p, k, me); + let zero = if float { + self.s.m.f32(0) + } else { + self.s.m.i32(0) + }; + self.s.m.select(c, below, v, zero) + } + None => v, + }; + acc = Some(match acc { + None => v, + Some(a) => match op { + Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, a, v), + Op::Or => self.s.m.bin(c, Bin::Or, a, v), + Op::And => self.s.m.bin(c, Bin::And, a, v), + Op::Xor => self.s.m.bin(c, Bin::Xor, a, v), + Op::MaxF => self.binary(35, a, v), + Op::MinF => self.binary(36, a, v), + Op::MinU | Op::MaxU | Op::MinI | Op::MaxI => { + let p = match op { + Op::MinU => pred::IULT, + Op::MaxU => pred::IUGT, + Op::MinI => pred::SLT, + _ => pred::SGT, + }; + let keep = self.s.m.cmp(c, p, a, v); + self.s.m.select(c, keep, a, v) + } + }, + }); + } + let r = acc.ok_or("a wave reduction over no lanes")?; + Ok(if float { self.as_int(r) } else { r }) + } + fn run(mut self) -> Result { + if self.wave64_refused { + return Err(unsupported( + 0, + "a compute group of several 64-lane waves that reads across lanes \ + on a host without 64-lane waves", + )); + } let p = self.x.p; let order = crate::ir::reverse_postorder(&p.blocks); for (n, &b) in order.iter().enumerate() { @@ -1282,6 +1494,25 @@ impl<'a> Lower<'a> { let bit = self.boolean(m, at); self.balloting.remove(&lo); let bit = bit?; + if self.emulated.is_some() { + let ir = self.def_block.get(&lo).copied().unwrap_or(0); + self.emulated_here(ir, at)?; + let i32t = self.s.t.i32; + let one = self.s.m.cast(at, Cast::ZExt, bit, i32t); + let bits = self.gather(at, one); + let (mut x, mut y) = (self.s.m.i32(0), self.s.m.i32(0)); + for (n, b) in bits.into_iter().enumerate() { + let sh = self.s.m.i32(n as u32 % 32); + let b = self.s.m.bin(at, Bin::Shl, b, sh); + if n < 32 { + x = self.s.m.bin(at, Bin::Or, x, b); + } else { + y = self.s.m.bin(at, Bin::Or, y, b); + } + } + self.ballots.insert(lo, (x, y)); + return Ok(if high { y } else { x }); + } let i32t = self.s.t.i32; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); let r = self @@ -1903,14 +2134,18 @@ impl<'a> Lower<'a> { /// This lane's bit of the mask `lo`, `hi` (wave64). fn lane_bit(&mut self, at: usize, lo: V, hi: Option) -> V { - let lane = self.s.op( - at, - "waveGetLaneIndex", - Attr::ReadOnly, - self.s.t.i32, - 111, - &[], - ); + let lane = if self.emulated.is_some() { + self.mesh_thread() + } else { + self.s.op( + at, + "waveGetLaneIndex", + Attr::ReadOnly, + self.s.t.i32, + 111, + &[], + ) + }; let (k31, k32, one, z) = ( self.s.m.i32(31), self.s.m.i32(32), @@ -2119,6 +2354,7 @@ impl<'a> Lower<'a> { /// lane guard): returns where it started and the join block. fn begin_guarded(&mut self, guard: Option) -> Option<(usize, usize)> { let g = guard?; + self.guard_depth += 1; let (then, join) = (self.s.m.new_block(), self.s.m.new_block()); self.s.m.terminate(self.cur, Term::CondBr(g, then, join)); let head = self.cur; @@ -2131,6 +2367,7 @@ impl<'a> Lower<'a> { let Some((head, join)) = at else { return values.iter().map(|v| v.0).collect(); }; + self.guard_depth -= 1; let then = self.cur; self.s.m.terminate(then, Term::Br(join)); self.cur = join; @@ -2159,7 +2396,9 @@ impl<'a> Lower<'a> { return Err("a cross-lane operation outside compute"); } debug_assert!(self.s.threads.is_none() || self.console_lanes); - self.s.flags |= flags::WAVE_OPS; + if self.emulated.is_none() { + self.s.flags |= flags::WAVE_OPS; + } Ok(()) } @@ -2169,7 +2408,7 @@ impl<'a> Lower<'a> { /// plus the lane index. (A bijection while each host wave holds a /// wave-aligned run of flat ids, as the console's waves do.) fn thread_id(&mut self, c: u8) -> Val { - if !self.console_lanes { + if !self.console_lanes || self.emulated.is_some() { return self.compute_id("threadIdInGroup.i32", 95, c); } let [x, y, _] = self.s.threads.expect("compute"); @@ -2273,6 +2512,10 @@ impl<'a> Lower<'a> { } fn lane_index(&mut self) -> V { + if self.emulated.is_some() { + // Console lane n is the thread with flattened id n. + return self.mesh_thread(); + } if self.s.mesh.is_some() { // The console's lane: mesh code reads no other lanes, so host // waves need not match the console's. @@ -2314,21 +2557,87 @@ impl<'a> Lower<'a> { r } - fn read_lane(&mut self, x: V, lane: V) -> V { - self.s.op( + fn read_lane(&mut self, x: V, lane: V) -> Result { + if self.emulated.is_some() { + let at = self.cur; + self.emulated_here(self.cur_ir, at)?; + let me = self.mesh_thread(); + let p = self.slot(at, me); + self.s.m.store(at, p, x); + self.group_sync(at); + let q = self.slot(at, lane); + let r = self.s.m.load(at, q); + self.group_sync(at); + return Ok(r); + } + Ok(self.s.op( self.cur, "waveReadLaneAt.i32", Attr::NoUnwind, self.s.t.i32, 117, &[x, lane], - ) + )) + } + + /// [`Emulated`]: whether a step reading other lanes may run in DXIL + /// block `at`, which IR block `ir` lowers to (every lane must get there). + fn emulated_here(&self, ir: usize, at: usize) -> Result<(), Why> { + let em = self.emulated.as_ref().expect("emulated"); + if !em.uniform[ir] || at == self.cur && self.guard_depth > 0 { + return Err("a step across lanes in lane-dependent code on a host \ + without 64-lane waves"); + } + Ok(()) + } + + /// [`Emulated`]: the exchange slot of console lane `lane` (modulo 64), + /// addressed in `at`. + fn slot(&mut self, at: usize, lane: V) -> V { + let g = match self.emulated.as_ref().and_then(|e| e.slots) { + Some(g) => g, + None => { + let arr = self.s.m.array(64, self.s.t.i32); + let g = self.s.m.global("xlane", arr, 3); + self.emulated.as_mut().expect("emulated").slots = Some(g); + g + } + }; + let k63 = self.s.m.i32(63); + let i = self.s.m.bin(at, Bin::And, lane, k63); + self.s.m.element(at, g, i) + } + + /// A group barrier with a group-shared memory fence, in `at`. + fn group_sync(&mut self, at: usize) { + let mode = self.s.m.i32(1 | 8); + let void = self.s.t.void; + self.s + .op(at, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + + /// [`Emulated`]: every console lane's `x`, lane 0 first, in `at`. + fn gather(&mut self, at: usize, x: V) -> Vec { + let me = self.mesh_thread(); + let p = self.slot(at, me); + self.s.m.store(at, p, x); + self.group_sync(at); + let lanes = self.emulated.as_ref().expect("emulated").lanes; + let out = (0..lanes) + .map(|n| { + let k = self.s.m.i32(n); + let q = self.slot(at, k); + self.s.m.load(at, q) + }) + .collect(); + self.group_sync(at); + out } /// Coarse derivatives of `coords` across this lane's quad, as DXIL /// gradients (x for up to three coordinates, then y), each times /// `scale` if given. - fn quad_gradients(&mut self, coords: &[V], scale: Option) -> Vec { + fn quad_gradients(&mut self, coords: &[V], scale: Option) -> Result, Why> { let c = self.cur; let lane = self.lane_index(); let top = self.s.m.i32(!3); @@ -2343,13 +2652,13 @@ impl<'a> Lower<'a> { let mut g = vec![fu; 6]; for (k, &x) in coords.iter().enumerate().take(3) { let xi = self.as_int(x); - let at = |l: &mut Self, lane: V| { - let r = l.read_lane(xi, lane); - l.as_float(r) + let at = |l: &mut Self, lane: V| -> Result { + let r = l.read_lane(xi, lane)?; + Ok(l.as_float(r)) }; - let origin = at(self, base); + let origin = at(self, base)?; for (d, &lane) in lanes.iter().enumerate() { - let there = at(self, lane); + let there = at(self, lane)?; let mut diff = self.s.m.bin(c, Bin::Sub, there, origin); if let Some(s) = scale { diff = self.s.m.bin(c, Bin::Mul, diff, s); @@ -2357,7 +2666,7 @@ impl<'a> Lower<'a> { g[3 * d + k] = diff; } } - g + Ok(g) } /// The float value of a register value. @@ -2442,7 +2751,7 @@ impl<'a> Lower<'a> { let r = if mesh_quad { self.quad_pick(x, src) } else { - self.read_lane(x, src) + self.read_lane(x, src)? }; let reg = dst_reg.ok_or("a swizzle result")?; self.write(inst, Reg::V(reg), r, guard); @@ -2451,6 +2760,13 @@ impl<'a> Lower<'a> { if self.s.lds_dwords == 0 { return Err("LDS the program does not allocate"); } + if self.emulated.is_some() { + // The console's lanes reach each LDS access together; the + // host's two waves wait for each other before one. + let at = self.cur; + self.emulated_here(self.cur_ir, at)?; + self.group_sync(at); + } let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0]; // shortcut: LDS addresses are taken as aligned and in bounds // (out-of-bounds console accesses read 0 and drop writes). @@ -4421,7 +4737,7 @@ impl<'a> Lower<'a> { let mut r = if mesh_quad { self.quad_pick(x, src) } else { - self.read_lane(x, src) + self.read_lane(x, src)? }; let mut enable = None; if let Some(inside) = inside { @@ -4979,7 +5295,7 @@ impl<'a> Lower<'a> { } else { self.cross_lane(false)?; } - let r = self.read_lane(a, lane); + let r = self.read_lane(a, lane)?; int(self, r) } "v_writelane_b32" => { @@ -5030,7 +5346,7 @@ impl<'a> Lower<'a> { let row = self.s.m.bin(c, Bin::Xor, row, k16); let base = self.s.m.bin(c, Bin::Or, half, row); let idx = self.s.m.bin(c, Bin::Or, base, pick); - let val = self.read_lane(a, idx); + let val = self.read_lane(a, idx)?; int(self, val) } "v_readfirstlane_b32" @@ -5045,6 +5361,17 @@ impl<'a> Lower<'a> { } "v_readfirstlane_b32" => { let a = s(self, 0)?; + if self.emulated.is_some() { + // Unguarded in a uniform block every lane is active, so + // the first is lane 0. + if guard.is_some() { + return Err("v_readfirstlane under a lane guard on a host \ + without 64-lane waves"); + } + let zero = self.s.m.i32(0); + let r = self.read_lane(a, zero)?; + return int(self, r); + } self.s.flags |= flags::WAVE_OPS; let r = self.s.op( c, @@ -6840,7 +7167,7 @@ impl<'a> Lower<'a> { } else { None }; - let g = self.quad_gradients(&cs[..spatial], scale); + let g = self.quad_gradients(&cs[..spatial], scale)?; args.extend(&os); args.extend(g); args.push(fu); @@ -7972,6 +8299,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + host_wave64: true, }) } @@ -8034,6 +8362,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + host_wave64: true, }) .map(|_| ()) } @@ -8115,6 +8444,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + host_wave64: true, }) } @@ -8381,6 +8711,7 @@ mod tests { outputs: vec![target], prims: vec![], mesh_stride: 0, + host_wave64: true, }) .map(|_| ()) } @@ -8415,6 +8746,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + host_wave64: true, }) .map(|_| ()) } @@ -8502,6 +8834,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + host_wave64: true, }) } @@ -8606,6 +8939,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + host_wave64: true, }) .unwrap(); @@ -8692,6 +9026,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + host_wave64: true, }) .unwrap(); } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0ae1ced27f..53387f8191 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -91,6 +91,8 @@ mod valu_tests; #[cfg(all(test, windows))] mod waterfall_tests; mod wave; +#[cfg(test)] +mod wave64_fixtures; use crate::dxbc::{Container, FourCC}; use crate::native::{HwStage, NativeProgram, RootType}; @@ -137,6 +139,28 @@ fn parse_loop_limit(value: Option<&str>) -> u32 { } } +/// Whether the host device runs 64-lane waves (`WaveSize(64)`): set once, +/// before the first translation, by whoever creates the host device +/// ([`set_host_wave64`]); true until then. AMD's RDNA GPUs do; NVIDIA's +/// and Intel's have 32 lanes (or fewer) and refuse a pipeline that +/// declares 64. Without them a compute program that needs the console's +/// 64 lanes runs its cross-lane steps through group-shared memory when its +/// group is that one wave, and is refused with a reason otherwise. The +/// value is part of the translation, so the shader cache must key on it +/// (`victory-gpu`'s does). +pub fn host_wave64() -> bool { + HOST_WAVE64.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Sets [`host_wave64`] from the host device's lane counts +/// (`D3D12_FEATURE_DATA_D3D12_OPTIONS1::WaveLaneCountMin/Max`). +pub fn set_host_wave64(min_lanes: u32, max_lanes: u32) { + let yes = (min_lanes..=max_lanes).contains(&64); + HOST_WAVE64.store(yes, std::sync::atomic::Ordering::Relaxed); +} + +static HOST_WAVE64: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + /// A translated shader and what the host binds for it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HostShader { @@ -321,6 +345,7 @@ fn emit_program( outputs, prims, mesh_stride, + host_wave64: host_wave64(), })?; Ok(HostShader { stage: native.stage, @@ -870,6 +895,7 @@ mod tests { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + host_wave64: true, }) .unwrap(); // Only the validator and the host (Windows) read the DXIL. diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 3b9485a912..2884e1eca6 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -137,6 +137,7 @@ fn build_valu_cs(body: &[u32]) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + host_wave64: true, }) .expect("lower"); @@ -1295,3 +1296,79 @@ fn v_ldexp_f32_scales_by_any_exponent() { assert!(f32::from_bits(got).is_nan(), "{backend}: {got:#010x}"); }); } + +/// Translates a 64-thread wave64 program from `wave64_fixtures` for a host +/// without 64-lane waves (lane exchanges through group-shared memory) and +/// checks what its group stores on every available SM 6.6 host. The +/// translation declares no wave size, so it runs on any GPU: on NVIDIA's +/// 32-lane waves this is the only way these programs run at all. +fn run_wave64_group(body: &[u32], lds_bytes: u32, expected: &[u32]) { + use super::wave64_fixtures::{lower_for, program}; + let lowered = lower_for(&program(body, 64, lds_bytes), false).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, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = 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 mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) | (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(256)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + for (n, (&got, &want)) in out[0].iter().zip(expected).enumerate() { + assert_eq!( + got, + want, + "{label}: dword {n} (lane {}, result {}) = {got:#x}, want {want:#x}", + n % 64, + n / 64, + ); + } + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} + +#[test] +fn wave64_lane_reads_ballots_and_lds_run_without_64_lane_waves() { + use super::wave64_fixtures::{CROSS_LANE, cross_lane_expected}; + run_wave64_group(CROSS_LANE, 512, &cross_lane_expected()); +} + +#[test] +fn wave64_dpp_first_lane_and_swizzle_run_without_64_lane_waves() { + use super::wave64_fixtures::{DPP_FIRST_SWIZZLE, dpp_first_swizzle_expected}; + run_wave64_group(DPP_FIRST_SWIZZLE, 0, &dpp_first_swizzle_expected()); +} diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 104fc6d0c0..fa2d38cb40 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -69,6 +69,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + host_wave64: true, }) .expect("lower"); // One access with each lane's own heap index, no wave operation. diff --git a/crates/victory-shader/src/emit/wave64_fixtures.rs b/crates/victory-shader/src/emit/wave64_fixtures.rs new file mode 100644 index 0000000000..cebba3b869 --- /dev/null +++ b/crates/victory-shader/src/emit/wave64_fixtures.rs @@ -0,0 +1,199 @@ +//! Synthetic wave64 compute programs (assembled with LLVM's `llvm-mc +//! -mcpu=gfx1010 -mattr=+wavefrontsize64`) for the emulation of 64-lane +//! waves on hosts without them ([`super::host_wave64`]). +//! +//! Each runs as one group of 64 threads (one console wave). The frame puts a +//! raw buffer UAV descriptor in `s[8:11]`; thread n stores its results at +//! dwords n, 64 + n, 128 + n and 192 + n. + +use super::lower::{Lowered, Parts, lower}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{ShaderError, io, ir, resource, structure}; + +/// Lane reads, a ballot and LDS shared within the wave without a barrier. +/// Per lane n: lane 37's v0 (37), the count of lanes below 40 (40), the +/// lane's own index from `v_mbcnt` (n), and lane (n + 1) % 64's v0 through +/// LDS (written by every lane just before). +pub(super) const CROSS_LANE: &[u32] = &[ + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x340E_0082, // v_lshlrev_b32_e32 v7, 2, v0 + 0xD760_000C, + 0x0001_4B00, // v_readlane_b32 s12, v0, 37 + 0x7E02_020C, // v_mov_b32_e32 v1, s12 + 0xE070_1000, + 0x8002_0107, // buffer_store_dword v1, v7, s[8:11], 0 offen + 0x7D88_00A8, // v_cmp_gt_u32_e32 vcc, 40, v0 + 0xBE8D_106A, // s_bcnt1_i32_b64 s13, vcc + 0x7E04_020D, // v_mov_b32_e32 v2, s13 + 0xE070_1100, + 0x8002_0207, // buffer_store_dword v2, v7, s[8:11], 0 offen offset:256 + 0xD765_0003, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v3, -1, 0 + 0xD766_0003, + 0x0002_06C1, // v_mbcnt_hi_u32_b32 v3, -1, v3 + 0xE070_1200, + 0x8002_0307, // buffer_store_dword v3, v7, s[8:11], 0 offen offset:512 + 0x4A0C_0081, // v_add_nc_u32_e32 v6, 1, v0 + 0x360C_0CBF, // v_and_b32_e32 v6, 63, v6 + 0x340C_0C82, // v_lshlrev_b32_e32 v6, 2, v6 + 0xD834_0000, + 0x0000_0007, // ds_write_b32 v7, v0 + 0xD8D8_0000, + 0x0500_0006, // ds_read_b32 v5, v6 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE070_1300, + 0x8002_0507, // buffer_store_dword v5, v7, s[8:11], 0 offen offset:768 +]; + +/// What [`CROSS_LANE`] stores, by dword. +#[cfg_attr(not(windows), allow(dead_code))] +pub(super) fn cross_lane_expected() -> Vec { + let mut out = vec![37; 64]; + out.extend([40; 64]); + out.extend(0..64); + out.extend((0..64).map(|n| (n + 1) % 64)); + out +} + +/// DPP, `v_readfirstlane` and `ds_swizzle`. Per lane n: lane n - 1's v0 +/// within its row of 16 (0 for a row's first lane, `bound_ctrl`), lane 0's +/// v0 + 100 (100), and lane n ^ 1's v0 (`ds_swizzle` SWAP 1). +pub(super) const DPP_FIRST_SWIZZLE: &[u32] = &[ + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x340E_0082, // v_lshlrev_b32_e32 v7, 2, v0 + 0x7E10_02FA, + 0xFF09_1100, // v_mov_b32_dpp v8, v0 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1 + 0xE070_1000, + 0x8002_0807, // buffer_store_dword v8, v7, s[8:11], 0 offen + 0x4A12_00FF, + 0x0000_0064, // v_add_nc_u32_e32 v9, 0x64, v0 + 0x7E1C_0509, // v_readfirstlane_b32 s14, v9 + 0x7E14_020E, // v_mov_b32_e32 v10, s14 + 0xE070_1100, + 0x8002_0A07, // buffer_store_dword v10, v7, s[8:11], 0 offen offset:256 + 0xD8D4_041F, + 0x0B00_0000, // ds_swizzle_b32 v11, v0 offset:swizzle(SWAP,1) + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE070_1200, + 0x8002_0B07, // buffer_store_dword v11, v7, s[8:11], 0 offen offset:512 +]; + +/// What [`DPP_FIRST_SWIZZLE`] stores, by dword (192 dwords). +#[cfg_attr(not(windows), allow(dead_code))] +pub(super) fn dpp_first_swizzle_expected() -> Vec { + let mut out: Vec = (0..64) + .map(|n| if n % 16 == 0 { 0 } else { n - 1 }) + .collect(); + out.extend([100; 64]); + out.extend((0..64).map(|n| n ^ 1)); + out +} + +/// A lane read inside `if (lane < 10)`: only those lanes reach it, so a +/// group barrier there could never complete. +pub(super) const DIVERGENT_READLANE: &[u32] = &[ + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x340E_0082, // v_lshlrev_b32_e32 v7, 2, v0 + 0x7E02_0280, // v_mov_b32_e32 v1, 0 + 0x7D88_008A, // v_cmp_gt_u32_e32 vcc, 10, v0 + 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc + 0xBF88_0003, // s_cbranch_execz 3 + 0xD760_000C, + 0x0001_0B00, // v_readlane_b32 s12, v0, 5 + 0x7E02_020C, // v_mov_b32_e32 v1, s12 + 0x88FE_147E, // s_or_b64 exec, exec, s[20:21] + 0xE070_1000, + 0x8002_0107, // buffer_store_dword v1, v7, s[8:11], 0 offen +]; + +/// `body` as a wave64 compute program of `threads` threads with +/// `lds_bytes` of LDS, root constants in s0-s3 and a UAV table in s4. +pub(super) fn program(body: &[u32], threads: u32, lds_bytes: u32) -> NativeProgram { + // s_mov_b32 s5, 0; s_load_dwordx4 s[8:11], s[4:5], null + let mut words = vec![0xBE85_0380, 0xF408_0202, 0xFA00_0000]; + words.extend_from_slice(body); + words.push(0xBF81_0000); // s_endpgm + let param = |root, sgprs, user_data, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 32, + layout: vec![ + param(RootType::Constants, 4, 0, 0), + param(RootType::Table, 1, 4, 1), + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + // 5 user SGPRs; LDS in 512-byte units. + rsrc2: 5 << 1 | lds_bytes.div_ceil(512) << 15, + threads: [threads, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// Lowers `native` for a host with (or without) 64-lane waves. +pub(super) fn lower_for(native: &NativeProgram, host_wave64: bool) -> Result { + let p = ir::build(&native.code, native.wave64, native.vgprs)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, native)?; + lower(&Parts { + native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + host_wave64, + }) +} + +#[test] +fn one_wave_groups_translate_without_64_lane_waves() { + for body in [CROSS_LANE, DPP_FIRST_SWIZZLE] { + let native = program(body, 64, 512); + lower_for(&native, true).unwrap(); + lower_for(&native, false).unwrap(); + } +} + +#[test] +fn what_cannot_be_emulated_is_refused_with_a_reason() { + // Several console waves in one group: their lanes cannot be exchanged + // through one group's barriers. + let several = program(CROSS_LANE, 128, 512); + lower_for(&several, true).unwrap(); + let Err(e) = lower_for(&several, false) else { + panic!("translated"); + }; + assert!(e.to_string().contains("several 64-lane waves"), "{e}"); + // A lane read only some lanes reach. + let divergent = program(DIVERGENT_READLANE, 64, 0); + lower_for(&divergent, true).unwrap(); + let Err(e) = lower_for(&divergent, false) else { + panic!("translated"); + }; + assert!(e.to_string().contains("lane-dependent code"), "{e}"); +} From 90720f1ccd92d59e2b005b32281329c4459335f3 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:07:48 +0000 Subject: [PATCH 044/123] scripts: VIctory Try, a one-exe way to build this fork and run a game with it VIctoryTry.exe (built by scripts/try/build-exe.sh with Zig, never committed) holds try.ps1 and runs it: it asks for the game folder and exe, installs Rust and the C++ build tools if missing, downloads this branch's source as a zip, builds victory.exe and runs the game, with a run again / update / change paths menu after. No sign-in and nothing reported anywhere. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- scripts/try/README.md | 60 +++++++++ scripts/try/build-exe.sh | 173 ++++++++++++++++++++++++++ scripts/try/try.ps1 | 260 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 493 insertions(+) create mode 100644 scripts/try/README.md create mode 100755 scripts/try/build-exe.sh create mode 100644 scripts/try/try.ps1 diff --git a/scripts/try/README.md b/scripts/try/README.md new file mode 100644 index 0000000000..2a924b1c13 --- /dev/null +++ b/scripts/try/README.md @@ -0,0 +1,60 @@ +# VIctory Try + +A simple way to try this fork's VIctory on your own PC. Download +**VIctoryTry.exe** from the fork's Releases page, double-click it, and type +two paths: the game files folder and the game's exe. That's all. + +It doesn't sign in to anything and doesn't send anything anywhere. It only +downloads things anonymously: +- this fork's source code, as a zip; +- the first time only, the two tools building needs: Rust and Microsoft's + C++ Build Tools (a few GB; Windows asks for permission once). + +## What it does + +1. Asks for the game folder and the game exe, and remembers them. If the + folder holds several exe files, it lists them so you can pick one by number. +2. Installs Rust and the C++ Build Tools if they are missing. +3. Downloads the newest source and builds `victory.exe`. The first build takes + a while; after that it only rebuilds when the source changed. +4. Runs `victory.exe run --execute` and shows the output. +5. When the game stops, you choose what's next: + - **Enter**: run again; + - **U**: update to the newest version and run; + - **G**: change the game paths; + - **Q**: quit. + +## Requirements + +VIctory's own requirements apply: +- Windows 10 or 11 (x64); +- a CPU with AVX2; +- a D3D12 GPU with Shader Model 6.6 and mesh shaders; +- your own copy of the game. + +Keep the game outside the `%LOCALAPPDATA%\VIctoryTry` folder. + +## Where things go + +Everything lives in `%LOCALAPPDATA%\VIctoryTry`: +- `victory\`: the source; +- `target\`: the build; +- `logs\`: the build output and every game run; +- `config.json`: your two paths. + +VIctory writes crash details to `%LOCALAPPDATA%\victory\data\crashes.log`. To +remove everything, delete those two folders. + +## Windows warnings + +The exe isn't signed, so Windows SmartScreen may say "Windows protected your +PC". Click **More info**, then **Run anyway**. The exe is small: it holds +[`try.ps1`](try.ps1), writes it to `%LOCALAPPDATA%\VIctoryTry` and runs it +with Windows PowerShell. You can read the script, and the exe's C source is in +[`build-exe.sh`](build-exe.sh). + +## Building the exe + +On any OS with Zig (`pip install ziglang` works), run +`scripts/try/build-exe.sh`. The exe lands in `target/try/`. It's a release +download only: never commit it. diff --git a/scripts/try/build-exe.sh b/scripts/try/build-exe.sh new file mode 100755 index 0000000000..42b064a050 --- /dev/null +++ b/scripts/try/build-exe.sh @@ -0,0 +1,173 @@ +#!/usr/bin/env bash +# Builds VIctoryTry.exe, a double-click launcher for try.ps1, on any OS with +# Zig (https://ziglang.org, or `pip install ziglang`), which cross-compiles C +# for Windows. The exe is a release download only: never commit it. +# +# scripts/try/build-exe.sh [out-dir] (default: target/try) +# +# The exe holds the try.ps1 it was built with. It writes it to +# %LOCALAPPDATA%\VIctoryTry\try.ps1, runs it with Windows PowerShell in its +# console and waits for Enter before the window closes. The C source is +# below, in full. +set -euo pipefail + +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../.." && pwd)" +out="${1:-$root/target/try}" +mkdir -p "$out" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +if command -v zig >/dev/null 2>&1; then + zig=(zig) +elif python3 -c 'import ziglang' >/dev/null 2>&1; then + zig=(python3 -m ziglang) +elif [ -x /tmp/venv/bin/python ] && /tmp/venv/bin/python -c 'import ziglang' >/dev/null 2>&1; then + zig=(/tmp/venv/bin/python -m ziglang) +else + echo "needs Zig: install it, or: pip install ziglang" >&2 + exit 1 +fi + +version="$(sed -n "s/^\$TryVersion = '\([0-9.]*\)'.*/\1/p" "$here/try.ps1" | tr -d '\r')" +[ -n "$version" ] || { echo "no \$TryVersion in try.ps1" >&2; exit 1; } +IFS=. read -r v1 v2 <<<"$version" +v2="${v2:-0}" + +# try.ps1 as a C byte array (generated here, never stored in the repo). +{ + echo 'static const unsigned char TRY_PS1[] = {' + od -An -v -tu1 "$here/try.ps1" | sed 's/ */ /g; s/^ //; s/ $//; s/ /,/g; s/$/,/' | grep -v '^,$' + echo '};' +} >"$work/try_ps1.h" + +cat >"$work/launcher.c" <<'EOF' +/* VIctory Try launcher: see scripts/try/build-exe.sh. */ +#define WIN32_LEAN_AND_MEAN +#define UNICODE +#define _UNICODE +#include +#include +#include + +#include "try_ps1.h" + +static void wait_enter(void) { + wprintf(L"\nPress Enter to close this window."); + fflush(stdout); + HANDLE in = GetStdHandle(STD_INPUT_HANDLE); + FlushConsoleInputBuffer(in); + wchar_t buf[8]; + DWORD n = 0; + ReadConsoleW(in, buf, 8, &n, NULL); +} + +static int fail(const wchar_t *what) { + wprintf(L"VIctory Try: %ls (error %lu)\n", what, GetLastError()); + wait_enter(); + return 1; +} + +int main(void) { + SetConsoleTitleW(L"VIctory Try"); + /* Ctrl+C stops PowerShell (the child), not this window's last message. */ + SetConsoleCtrlHandler(NULL, TRUE); + + wchar_t home[MAX_PATH], script[MAX_PATH], ps[MAX_PATH]; + DWORD len = ExpandEnvironmentStringsW(L"%LOCALAPPDATA%\\VIctoryTry", home, + MAX_PATH); + if (len == 0 || len > MAX_PATH || wcschr(home, L'%')) + return fail(L"LOCALAPPDATA is not set"); + CreateDirectoryW(home, NULL); + swprintf(script, MAX_PATH, L"%ls\\try.ps1", home); + + HANDLE f = CreateFileW(script, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); + if (f == INVALID_HANDLE_VALUE) + return fail(L"cannot write try.ps1"); + DWORD wrote = 0; + BOOL ok = WriteFile(f, TRY_PS1, (DWORD)sizeof TRY_PS1, &wrote, NULL); + CloseHandle(f); + if (!ok || wrote != sizeof TRY_PS1) + return fail(L"cannot write try.ps1"); + + len = ExpandEnvironmentStringsW( + L"%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", ps, + MAX_PATH); + if (len == 0 || len > MAX_PATH || + GetFileAttributesW(ps) == INVALID_FILE_ATTRIBUTES) + wcscpy(ps, L"powershell.exe"); + + static wchar_t cmd[2048]; + swprintf(cmd, 2048, + L"\"%ls\" -NoProfile -ExecutionPolicy Bypass -File \"%ls\"", ps, + script); + + STARTUPINFOW si = {sizeof si}; + PROCESS_INFORMATION pi; + if (!CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL, home, &si, &pi)) + return fail(L"cannot start Windows PowerShell"); + WaitForSingleObject(pi.hProcess, INFINITE); + DWORD code = 0; + GetExitCodeProcess(pi.hProcess, &code); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + + wprintf(L"\nVIctory Try closed. Start it again with VIctoryTry.exe.\n"); + wait_enter(); + return (int)code; +} +EOF + +cat >"$work/VIctoryTry.manifest" <<'EOF' + + + + + + + + + + + + + + +EOF + +cat >"$work/VIctoryTry.rc" < +1 RT_MANIFEST "VIctoryTry.manifest" +VS_VERSION_INFO VERSIONINFO +FILEVERSION $v1,$v2,0,0 +PRODUCTVERSION $v1,$v2,0,0 +FILEOS VOS_NT_WINDOWS32 +FILETYPE VFT_APP +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "VIctory contributors" + VALUE "FileDescription", "VIctory Try" + VALUE "FileVersion", "$version" + VALUE "InternalName", "VIctoryTry" + VALUE "LegalCopyright", "GPL-3.0-or-later" + VALUE "OriginalFilename", "VIctoryTry.exe" + VALUE "ProductName", "VIctory Try" + VALUE "ProductVersion", "$version" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END +EOF + +(cd "$work" && "${zig[@]}" build-exe launcher.c VIctoryTry.rc -lc \ + -target x86_64-windows-gnu -O ReleaseSmall -fstrip \ + --name VIctoryTry -femit-bin="$out/VIctoryTry.exe") +rm -f "$out"/*.pdb "$out"/*.lib +echo "built $out/VIctoryTry.exe (VIctory Try $version, $(wc -c <"$out/VIctoryTry.exe") bytes)" diff --git a/scripts/try/try.ps1 b/scripts/try/try.ps1 new file mode 100644 index 0000000000..6a4571f649 --- /dev/null +++ b/scripts/try/try.ps1 @@ -0,0 +1,260 @@ +# VIctory Try: builds this fork's VIctory on your PC and runs your game with +# it. Started by VIctoryTry.exe (see scripts/try/README.md). +# +# Nothing is sent anywhere: no sign-in, no reports, no accounts. It only +# downloads (anonymously) the fork's source as a zip and, the first time, Rust +# and Microsoft's C++ build tools, which building needs. +# +# ASCII only: Windows PowerShell 5.1 reads a script without a BOM as ANSI. + +$ErrorActionPreference = 'Continue' +$ProgressPreference = 'SilentlyContinue' +$TryVersion = '1.0' +$SourceZip = 'https://codeload.github.com/MfDev0/victory/zip/refs/heads/arena/59fabb00-victory' +$TryHome = Join-Path $env:LOCALAPPDATA 'VIctoryTry' +$Src = Join-Path $TryHome 'victory' +$Target = Join-Path $TryHome 'target' +$ConfigPath = Join-Path $TryHome 'config.json' +$LogDir = Join-Path $TryHome 'logs' +New-Item -ItemType Directory -Force -Path $TryHome, $LogDir | Out-Null +try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch {} +try { $Host.UI.RawUI.WindowTitle = 'VIctory Try' } catch {} + +function Say([string]$msg) { Write-Host (' ' + $msg) } +function Step([string]$msg) { Write-Host ''; Write-Host ('== ' + $msg) -ForegroundColor Cyan } +function Bad([string]$msg) { Write-Host (' ' + $msg) -ForegroundColor Red } + +function Load-Config { + $c = @{ game_dir = ''; game_exe = ''; source_hash = '' } + if (Test-Path $ConfigPath) { + try { + $j = Get-Content -Path $ConfigPath -Raw | ConvertFrom-Json + foreach ($k in @('game_dir', 'game_exe', 'source_hash')) { if ($j.$k) { $c[$k] = [string]$j.$k } } + } catch {} + } + return $c +} +function Save-Config { try { ($script:Config | ConvertTo-Json) | Set-Content -Path $ConfigPath -Encoding ASCII } catch {} } + +function Refresh-Path { + $env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [Environment]::GetEnvironmentVariable('Path', 'User') + $cargoBin = Join-Path $env:USERPROFILE '.cargo\bin' + if ((Test-Path $cargoBin) -and ($env:Path -notlike "*$cargoBin*")) { $env:Path += ";$cargoBin" } +} + +function Find-Exe([string]$name) { + $c = Get-Command $name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($c) { return $c.Source } + return $null +} + +function Download([string]$url, [string]$file) { + try { Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $file; return $true } + catch { Bad "download failed: $url ($_)"; return $false } +} + +# ------------------------------------------------------------- the game + +function Read-Path([string]$prompt) { + $in = Read-Host $prompt + if ($null -eq $in) { return '' } + return $in.Trim().Trim('"').Trim("'").Trim() +} + +function Ask-Game([bool]$force) { + $c = $script:Config + if (-not $force -and $c.game_exe -and (Test-Path -LiteralPath $c.game_exe -PathType Leaf)) { + Say "game: $($c.game_exe)" + return $true + } + Step 'Where is the game?' + Say 'Paste each path and press Enter (right-click pastes in this window).' + $dir = ''; $exe = '' + while ($true) { + $dir = Read-Path ' 1) Game files folder' + if (-not $dir) { continue } + if (Test-Path -LiteralPath $dir -PathType Leaf) { $exe = $dir; $dir = Split-Path -Parent $dir; break } + if (Test-Path -LiteralPath $dir -PathType Container) { break } + Bad "not found: $dir" + } + $dir = (Resolve-Path -LiteralPath $dir).ProviderPath.TrimEnd('\') + if ($dir.StartsWith($TryHome, [StringComparison]::OrdinalIgnoreCase)) { + Bad "keep the game outside $TryHome" + return $false + } + while (-not $exe) { + $found = @(Get-ChildItem -LiteralPath $dir -Filter '*.exe' -File -ErrorAction SilentlyContinue | Select-Object -First 9) + if ($found.Count -gt 1) { + Say 'exe files in that folder:' + for ($i = 0; $i -lt $found.Count; $i++) { Say (" {0}) {1}" -f ($i + 1), $found[$i].Name) } + } + $hint = '' + if ($found.Count -eq 1) { $hint = " [Enter = $($found[0].Name)]" } + elseif ($found.Count -gt 1) { $hint = ' (a number above, or the path)' } + $in = Read-Path " 2) Game exe file$hint" + if (-not $in) { + if ($found.Count -eq 1) { $exe = $found[0].FullName } + continue + } + $n = 0 + if ([int]::TryParse($in, [ref]$n) -and $n -ge 1 -and $n -le $found.Count) { $exe = $found[$n - 1].FullName; continue } + if (-not [IO.Path]::IsPathRooted($in)) { $in = Join-Path $dir $in } + if (Test-Path -LiteralPath $in -PathType Leaf) { $exe = (Resolve-Path -LiteralPath $in).ProviderPath } + else { Bad "not found: $in" } + } + $c.game_dir = $dir + $c.game_exe = $exe + Save-Config + Say "game folder: $dir" + Say "game exe: $exe" + return $true +} + +# ------------------------------------------------------------- tools + +function Has-Msvc { + $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' + if (-not (Test-Path $vswhere)) { return $false } + $found = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2>$null + return [bool]$found +} + +function Ensure-Tools { + Refresh-Path + if (-not (Has-Msvc)) { + Step 'Installing Microsoft C++ Build Tools (first time only, a few GB)' + Say 'Windows will ask for permission. A progress window opens; wait for it to finish.' + $vs = Join-Path $TryHome 'vs_BuildTools.exe' + if (Download 'https://aka.ms/vs/17/release/vs_BuildTools.exe' $vs) { + $p = Start-Process -FilePath $vs -ArgumentList '--passive --wait --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended' -Wait -PassThru + Say "build tools installer finished (code $($p.ExitCode))" + } + if (-not (Has-Msvc)) { + Bad 'the C++ build tools are still missing. Restart Windows and start VIctory Try again.' + return $false + } + } + if (-not (Find-Exe 'rustup')) { + Step 'Installing Rust (first time only)' + $ri = Join-Path $TryHome 'rustup-init.exe' + if (Download 'https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe' $ri) { + & $ri -y --profile minimal --default-toolchain none + } + Refresh-Path + if (-not (Find-Exe 'rustup')) { + Bad 'Rust did not install. Start VIctory Try again; if it keeps failing, install it from https://rustup.rs' + return $false + } + } + return $true +} + +# ------------------------------------------------------------- build + +# Downloads the newest source; returns $true when it changed (or is new). +function Update-Source { + Step 'Getting the newest VIctory source' + $zip = Join-Path $TryHome 'source.zip' + if (-not (Download $SourceZip $zip)) { + if (Test-Path (Join-Path $Src 'Cargo.toml')) { Say 'using the source downloaded last time'; return $false } + return $null + } + $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $zip).Hash + if (($hash -eq $script:Config.source_hash) -and (Test-Path (Join-Path $Src 'Cargo.toml'))) { + Say 'no changes since last time' + return $false + } + $tmp = Join-Path $TryHome 'unpack' + if (Test-Path $tmp) { Remove-Item -Recurse -Force $tmp } + try { Expand-Archive -LiteralPath $zip -DestinationPath $tmp -Force } + catch { Bad "could not unpack the source: $_"; return $null } + $top = Get-ChildItem -LiteralPath $tmp -Directory | Select-Object -First 1 + if (-not $top) { Bad 'the source zip is empty'; return $null } + if (Test-Path $Src) { Remove-Item -Recurse -Force $Src } + Move-Item -LiteralPath $top.FullName -Destination $Src + Remove-Item -Recurse -Force $tmp + $script:Config.source_hash = $hash + Save-Config + Say 'new source unpacked' + return $true +} + +function Victory-Exe { return Join-Path $Target 'release\victory.exe' } + +function Build { + Step 'Building VIctory (the first build takes a while; later ones are quicker)' + $channel = '' + $tc = Join-Path $Src 'rust-toolchain.toml' + if (Test-Path $tc) { + $m = Select-String -LiteralPath $tc -Pattern '^\s*channel\s*=\s*"([^"]+)"' | Select-Object -First 1 + if ($m) { $channel = $m.Matches[0].Groups[1].Value } + } + if ($channel) { + Say "Rust $channel" + & rustup toolchain install $channel --profile minimal --target x86_64-pc-windows-msvc + } + $env:CARGO_TARGET_DIR = $Target + $log = Join-Path $LogDir 'build.log' + Push-Location $Src + try { + & cargo build --release -p victory 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $log + $code = $LASTEXITCODE + } finally { Pop-Location } + if ($code -ne 0 -or -not (Test-Path (Victory-Exe))) { + Bad "the build failed (code $code). The full output is in $log" + return $false + } + Say 'build finished' + return $true +} + +# ------------------------------------------------------------- run + +function Run-Game { + $c = $script:Config + Step 'Running the game with VIctory' + Say "game: $($c.game_exe)" + Say 'To stop: close the game window. (Ctrl+C closes VIctory Try too.)' + $env:VICTORY_GAME_DIR = $c.game_dir + $env:RUST_BACKTRACE = '1' + $stamp = Get-Date -Format 'yyyyMMdd-HHmmss' + $log = Join-Path $LogDir "game-$stamp.log" + Push-Location $TryHome + try { + & (Victory-Exe) run $c.game_exe --execute 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $log + $code = $LASTEXITCODE + } finally { Pop-Location } + Write-Host '' + Say "the game stopped (exit code $code)" + Say "its output: $log" + $crashes = Join-Path $env:LOCALAPPDATA 'victory\data\crashes.log' + if (Test-Path $crashes) { Say "crash details, if it crashed: $crashes" } +} + +# ------------------------------------------------------------- main + +Write-Host '' +Write-Host " VIctory Try $TryVersion" -ForegroundColor Green +Say 'Builds the newest VIctory from MfDev0/victory on this PC and runs your game.' +Say 'Nothing is uploaded or reported anywhere.' + +$script:Config = Load-Config +while (-not (Ask-Game $false)) {} +if (-not (Ensure-Tools)) { exit 1 } +$changed = Update-Source +if ($null -eq $changed) { Bad 'no source to build: check the internet connection'; exit 1 } +if ($changed -or -not (Test-Path (Victory-Exe))) { if (-not (Build)) { exit 1 } } + +while ($true) { + Run-Game + Write-Host '' + Say 'Enter = run again U = update to the newest version and run' + Say 'G = change the game paths Q = quit' + $k = (Read-Host ' Choice').Trim().ToUpper() + if ($k -eq 'Q') { exit 0 } + if ($k -eq 'G') { while (-not (Ask-Game $true)) {} } + if ($k -eq 'U') { + $changed = Update-Source + if ($changed -or -not (Test-Path (Victory-Exe))) { if (-not (Build)) { Say 'keeping the last working build' } } + } +} From 4e0c2980b7f392a5affc5b6b3c0b2c2dea4b123a Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:53:54 +0000 Subject: [PATCH 045/123] scripts: VIctory Try adds upstream VIctory's new fixes by itself scripts/try/upstream.txt names the last upstream commit this branch has (ffe310e). Each later upstream commit is cherry-picked on top of the fork in VIctory Try's local copy, oldest first; ones already here (empty) or conflicting are skipped, and a failed build falls back to the fork alone. Git comes from the PC or a portable MinGit. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- scripts/try/README.md | 22 +++++- scripts/try/try.ps1 | 157 +++++++++++++++++++++++++++++++-------- scripts/try/upstream.txt | 12 +++ 3 files changed, 158 insertions(+), 33 deletions(-) create mode 100644 scripts/try/upstream.txt diff --git a/scripts/try/README.md b/scripts/try/README.md index 2a924b1c13..b8db440ff9 100644 --- a/scripts/try/README.md +++ b/scripts/try/README.md @@ -6,16 +6,30 @@ two paths: the game files folder and the game's exe. That's all. It doesn't sign in to anything and doesn't send anything anywhere. It only downloads things anonymously: -- this fork's source code, as a zip; -- the first time only, the two tools building needs: Rust and Microsoft's - C++ Build Tools (a few GB; Windows asks for permission once). +- this fork's source code, and upstream VIctory's new commits; +- the first time only, the tools building needs: Git (a portable copy if you + have none), Rust and Microsoft's C++ Build Tools (a few GB; Windows asks + for permission once). + +## Upstream's new fixes, added by themselves + +Each time it updates, VIctory Try also fetches upstream VIctory +(Marvisak/VIctory). [`upstream.txt`](upstream.txt) names the last upstream +commit this fork already has. Every later upstream commit is applied on top +of the fork, oldest first: +- a fix the fork already has applies as an empty change and is skipped; +- a fix that clashes with the fork's changes is skipped; +- if the build fails with the new fixes added, the fork is built alone, so + you always get a working build. + +The window lists what was added and what was skipped. ## What it does 1. Asks for the game folder and the game exe, and remembers them. If the folder holds several exe files, it lists them so you can pick one by number. 2. Installs Rust and the C++ Build Tools if they are missing. -3. Downloads the newest source and builds `victory.exe`. The first build takes +3. Downloads the newest source, adds upstream's new fixes, and builds `victory.exe`. The first build takes a while; after that it only rebuilds when the source changed. 4. Runs `victory.exe run --execute` and shows the output. 5. When the game stops, you choose what's next: diff --git a/scripts/try/try.ps1 b/scripts/try/try.ps1 index 6a4571f649..8838034308 100644 --- a/scripts/try/try.ps1 +++ b/scripts/try/try.ps1 @@ -2,15 +2,24 @@ # it. Started by VIctoryTry.exe (see scripts/try/README.md). # # Nothing is sent anywhere: no sign-in, no reports, no accounts. It only -# downloads (anonymously) the fork's source as a zip and, the first time, Rust -# and Microsoft's C++ build tools, which building needs. +# downloads (anonymously) the fork's source, upstream VIctory's new commits +# and, the first time, Git, Rust and Microsoft's C++ build tools. +# +# Upstream's new fixes are added by themselves: the branch's +# scripts/try/upstream.txt names the last upstream commit the fork already +# has; each later one is applied on top, oldest first. Ones already in the +# fork (empty) or conflicting are skipped, and if the build fails with them +# the fork is built alone. # # ASCII only: Windows PowerShell 5.1 reads a script without a BOM as ANSI. $ErrorActionPreference = 'Continue' $ProgressPreference = 'SilentlyContinue' -$TryVersion = '1.0' -$SourceZip = 'https://codeload.github.com/MfDev0/victory/zip/refs/heads/arena/59fabb00-victory' +$TryVersion = '1.1' +$ForkUrl = 'https://github.com/MfDev0/victory.git' +$Branch = 'arena/59fabb00-victory' +$UpstreamUrl = 'https://github.com/Marvisak/VIctory.git' +$MinGitUrl = 'https://github.com/git-for-windows/git/releases/download/v2.56.1.windows.1/MinGit-2.56.1-64-bit.zip' $TryHome = Join-Path $env:LOCALAPPDATA 'VIctoryTry' $Src = Join-Path $TryHome 'victory' $Target = Join-Path $TryHome 'target' @@ -25,11 +34,11 @@ function Step([string]$msg) { Write-Host ''; Write-Host ('== ' + $msg) -Foregrou function Bad([string]$msg) { Write-Host (' ' + $msg) -ForegroundColor Red } function Load-Config { - $c = @{ game_dir = ''; game_exe = ''; source_hash = '' } + $c = @{ game_dir = ''; game_exe = ''; built_key = ''; added = '' } if (Test-Path $ConfigPath) { try { $j = Get-Content -Path $ConfigPath -Raw | ConvertFrom-Json - foreach ($k in @('game_dir', 'game_exe', 'source_hash')) { if ($j.$k) { $c[$k] = [string]$j.$k } } + foreach ($k in @('game_dir', 'game_exe', 'built_key', 'added')) { if ($j.$k) { $c[$k] = [string]$j.$k } } } catch {} } return $c @@ -119,6 +128,32 @@ function Has-Msvc { return [bool]$found } +# Git, to fetch the fork and upstream and apply upstream's new commits: the +# installed one, else a portable MinGit kept in our folder. +function Ensure-Git { + $sys = Find-Exe 'git' + if ($sys) { $script:Git = $sys; return $true } + $mine = Join-Path $TryHome 'mingit\cmd\git.exe' + if (-not (Test-Path $mine)) { + Step 'Getting a portable Git (first time only, about 40 MB)' + $zip = Join-Path $TryHome 'mingit.zip' + if (Download $MinGitUrl $zip) { + try { Expand-Archive -LiteralPath $zip -DestinationPath (Join-Path $TryHome 'mingit') -Force } catch { Bad "could not unpack Git: $_" } + Remove-Item -Force $zip -ErrorAction SilentlyContinue + } + } + if (Test-Path $mine) { $script:Git = $mine; return $true } + Bad 'Git is missing and could not be downloaded. Check the internet connection and start again.' + return $false +} + +# Runs git in the source folder; the exit code lands in $script:GCode. +function G { + $out = @(& $script:Git -C $Src -c core.autocrlf=false -c advice.detachedHead=false @args 2>&1 | ForEach-Object { "$_" }) + $script:GCode = $LASTEXITCODE + return $out +} + function Ensure-Tools { Refresh-Path if (-not (Has-Msvc)) { @@ -134,6 +169,7 @@ function Ensure-Tools { return $false } } + if (-not (Ensure-Git)) { return $false } if (-not (Find-Exe 'rustup')) { Step 'Installing Rust (first time only)' $ri = Join-Path $TryHome 'rustup-init.exe' @@ -151,34 +187,74 @@ function Ensure-Tools { # ------------------------------------------------------------- build -# Downloads the newest source; returns $true when it changed (or is new). +# Fetches the fork and upstream; returns $true when there is something new to +# build, $false when not, $null when there is no source at all. function Update-Source { - Step 'Getting the newest VIctory source' - $zip = Join-Path $TryHome 'source.zip' - if (-not (Download $SourceZip $zip)) { - if (Test-Path (Join-Path $Src 'Cargo.toml')) { Say 'using the source downloaded last time'; return $false } - return $null + Step 'Getting the newest VIctory (this fork, plus upstream''s new fixes)' + if ((Test-Path $Src) -and -not (Test-Path (Join-Path $Src '.git'))) { Remove-Item -Recurse -Force $Src } + if (-not (Test-Path $Src)) { + & $script:Git -c core.autocrlf=false clone -q --single-branch --branch $Branch $ForkUrl $Src + if ($LASTEXITCODE -ne 0) { Bad 'could not download the source: check the internet connection'; return $null } } - $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $zip).Hash - if (($hash -eq $script:Config.source_hash) -and (Test-Path (Join-Path $Src 'Cargo.toml'))) { + $null = G fetch -q origin "+refs/heads/${Branch}:refs/remotes/origin/fork" + if ($script:GCode -ne 0) { Say 'could not reach the fork: using what was downloaded before' } + $null = G fetch -q $UpstreamUrl '+refs/heads/main:refs/remotes/upstream/main' + if ($script:GCode -ne 0) { Say 'could not reach upstream VIctory: building the fork without its new fixes' } + $fork = (G rev-parse -q --verify refs/remotes/origin/fork) | Select-Object -First 1 + if (-not $fork) { Bad "the source download is broken: delete the victory folder in $TryHome and start again"; return $null } + $up = (G rev-parse -q --verify refs/remotes/upstream/main) | Select-Object -First 1 + $key = "$fork+$up" + if (($key -eq $script:Config.built_key) -and (Test-Path (Victory-Exe))) { Say 'no changes since last time' return $false } - $tmp = Join-Path $TryHome 'unpack' - if (Test-Path $tmp) { Remove-Item -Recurse -Force $tmp } - try { Expand-Archive -LiteralPath $zip -DestinationPath $tmp -Force } - catch { Bad "could not unpack the source: $_"; return $null } - $top = Get-ChildItem -LiteralPath $tmp -Directory | Select-Object -First 1 - if (-not $top) { Bad 'the source zip is empty'; return $null } - if (Test-Path $Src) { Remove-Item -Recurse -Force $Src } - Move-Item -LiteralPath $top.FullName -Destination $Src - Remove-Item -Recurse -Force $tmp - $script:Config.source_hash = $hash - Save-Config - Say 'new source unpacked' + $script:Key = $key return $true } +# Puts the fork in the source folder, then upstream's commits that came after +# what the fork has (scripts/try/upstream.txt). Returns the added subjects. +function Prepare-Source([bool]$withUpstream) { + $null = G cherry-pick --abort + $null = G checkout -q -f -B try refs/remotes/origin/fork + $null = G clean -fdq + $added = @() + if (-not $withUpstream) { return , $added } + $up = (G rev-parse -q --verify refs/remotes/upstream/main) | Select-Object -First 1 + if (-not $up) { return , $added } + $marker = Join-Path $Src 'scripts\try\upstream.txt' + $synced = ''; $have = @{} + if (Test-Path $marker) { + foreach ($line in Get-Content -LiteralPath $marker) { + if ($line -match '^\s*synced\s+([0-9a-f]{7,40})') { $synced = $Matches[1] } + elseif ($line -match '^\s*have\s+([0-9a-f]{7,40})') { $have[$Matches[1]] = $true } + } + } + if (-not $synced) { Say 'the fork does not say which upstream commits it has: not adding any'; return , $added } + $null = G merge-base --is-ancestor $synced $up + if ($script:GCode -ne 0) { Say 'upstream history changed: not adding its commits this time'; return , $added } + $new = @(G rev-list --reverse --first-parent "$synced..$up") + if ($new.Count -eq 0) { Say 'upstream VIctory has nothing new beyond this fork'; return , $added } + Say "upstream VIctory has $($new.Count) new commit(s) beyond this fork" + foreach ($sha in $new) { + $known = $false + foreach ($h in $have.Keys) { if ($sha.StartsWith($h)) { $known = $true } } + $subject = (G log -1 --format=%s $sha) | Select-Object -First 1 + if ($known) { Say " have already: $subject"; continue } + $parents = @(((G rev-list --parents -n 1 $sha) | Select-Object -First 1) -split ' ').Count - 1 + $pick = @('-c', 'user.name=VIctory Try', '-c', 'user.email=try@localhost', 'cherry-pick', '-x') + if ($parents -gt 1) { $pick += @('-m', '1') } + $null = G @pick $sha + if ($script:GCode -eq 0) { Say " added: $subject"; $added += $subject; continue } + $conflict = @(G diff --name-only --diff-filter=U).Count -gt 0 + $null = G cherry-pick --abort + $null = G reset -q --hard + if ($conflict) { Say " skipped (clashes with this fork's changes): $subject" } + else { Say " have already: $subject" } + } + return , $added +} + function Victory-Exe { return Join-Path $Target 'release\victory.exe' } function Build { @@ -208,12 +284,34 @@ function Build { return $true } +# The fork with upstream's new fixes; if that does not build, the fork alone. +function Build-All { + $added = @(Prepare-Source $true) + $ok = Build + if (-not $ok -and $added.Count -gt 0) { + Bad "the build failed with upstream's new fixes added: building this fork without them" + $added = @() + $null = Prepare-Source $false + $ok = Build + } + if ($ok) { + $script:Config.built_key = $script:Key + $script:Config.added = ($added -join "`n") + Save-Config + if ($added.Count -gt 0) { Say "this build includes $($added.Count) new upstream fix(es)" } + } + return $ok +} + # ------------------------------------------------------------- run function Run-Game { $c = $script:Config Step 'Running the game with VIctory' Say "game: $($c.game_exe)" + $build = (G log -1 --format='%h %s' refs/remotes/origin/fork) | Select-Object -First 1 + if ($build) { Say "VIctory: fork at $build" } + if ($c.added) { Say "plus upstream: $(@($c.added -split "`n").Count) new fix(es) on top" } Say 'To stop: close the game window. (Ctrl+C closes VIctory Try too.)' $env:VICTORY_GAME_DIR = $c.game_dir $env:RUST_BACKTRACE = '1' @@ -235,7 +333,8 @@ function Run-Game { Write-Host '' Write-Host " VIctory Try $TryVersion" -ForegroundColor Green -Say 'Builds the newest VIctory from MfDev0/victory on this PC and runs your game.' +Say 'Builds the newest VIctory from MfDev0/victory, with upstream VIctory''s new' +Say 'fixes added by themselves, on this PC and runs your game.' Say 'Nothing is uploaded or reported anywhere.' $script:Config = Load-Config @@ -243,7 +342,7 @@ while (-not (Ask-Game $false)) {} if (-not (Ensure-Tools)) { exit 1 } $changed = Update-Source if ($null -eq $changed) { Bad 'no source to build: check the internet connection'; exit 1 } -if ($changed -or -not (Test-Path (Victory-Exe))) { if (-not (Build)) { exit 1 } } +if ($changed -or -not (Test-Path (Victory-Exe))) { if (-not (Build-All)) { exit 1 } } while ($true) { Run-Game @@ -255,6 +354,6 @@ while ($true) { if ($k -eq 'G') { while (-not (Ask-Game $true)) {} } if ($k -eq 'U') { $changed = Update-Source - if ($changed -or -not (Test-Path (Victory-Exe))) { if (-not (Build)) { Say 'keeping the last working build' } } + if ($changed -or -not (Test-Path (Victory-Exe))) { if (-not (Build-All)) { Say 'keeping the last working build' } } } } diff --git a/scripts/try/upstream.txt b/scripts/try/upstream.txt new file mode 100644 index 0000000000..f0a7bc64f8 --- /dev/null +++ b/scripts/try/upstream.txt @@ -0,0 +1,12 @@ +# Upstream VIctory (Marvisak/VIctory, main) as this branch has it. VIctory Try +# reads this to add only upstream's NEW fixes to what it builds: +# +# synced everything on upstream main up to this commit is in +# this branch already (merged, cherry-picked or ported); +# have a later upstream commit that is in this branch already. +# +# Each upstream commit after "synced" that is not a "have" is applied on top +# of this branch, oldest first. One already here applies as an empty change +# and is skipped; one that conflicts is skipped too. Update this file when +# upstream work is brought into the branch. +synced ffe310eb2098e52169f4c44db5ffdabf43a72622 From 58bc72feb89fd8a6094526e53ae0b0302e546a16 Mon Sep 17 00:00:00 2001 From: Peppacodes <360593343+Peppacodes@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:04:15 +1100 Subject: [PATCH 046/123] Shaders: always-false and always-true float compares lower as constants v_cmp_f_{f32,f16} and v_cmp_tru_{f32,f16} lowered to fcmp false and fcmp true (predicates 0 and 15). DXC folds those away, so drivers never see them from it, and WARP removes its device at the first dispatch of a pipeline that has one ("The GPU device instance has been suspended"). The hardware adapter (RTX 5080) runs them. A removed WARP device stays removed for the process, so everything after it fails too. They are false and true whatever the operands, NaNs included (RDNA2 ISA), so they now lower as constants, as the integer v_cmp_f/v_cmp_t already do. FALSE and TRUE stay in the predicate table, unused. Found with a sweep of every 32-bit VALU instruction on the hardware adapter against WARP: all 62 compares now run and agree on both. Test: float_compares_that_are_always_false_or_true, f32 and f16 with ordinary and NaN operands, on the hardware adapter and WARP. On main WARP's dispatch fails with the device suspended. (cherry picked from commit e04929d9d0c4815fc054f8793986894794b350dc) --- crates/victory-shader/src/emit/bitcode.rs | 4 ++ crates/victory-shader/src/emit/lower.rs | 9 ++++- crates/victory-shader/src/emit/valu_tests.rs | 39 ++++++++++++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 5fea10144e..c7b23a19cd 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -97,6 +97,9 @@ pub(crate) enum Cast { /// Compare predicates: floats 0-15, integers 32-41. pub(crate) mod pred { + // FALSE and TRUE are not emitted: WARP removes its device on them (and + // DXC folds them away), so constant compares lower as constants. + #[allow(dead_code)] pub const FALSE: u8 = 0; pub const OEQ: u8 = 1; pub const OGT: u8 = 2; @@ -115,6 +118,7 @@ pub(crate) mod pred { pub const ULT: u8 = 12; pub const ULE: u8 = 13; pub const UNE: u8 = 14; + #[allow(dead_code)] pub const TRUE: u8 = 15; pub const EQ: u8 = 32; pub const NE: u8 = 33; diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 2e56eb394a..9d6407e544 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6470,6 +6470,13 @@ impl<'a> Lower<'a> { self.s.m.cmp(c, pred::NE, bit, zero) } "f32" | "f16" => { + // Always false or true, NaNs included: constants, as for the + // integer compares. As `fcmp false`/`fcmp true`, which DXC + // never emits, WARP removes its device at the first dispatch. + if op == "f" || op == "tru" { + self.lane(inst, Some(op == "tru")); + return Ok(()); + } let (a, b) = if ty == "f16" { (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?) } else { @@ -6485,7 +6492,6 @@ impl<'a> Lower<'a> { self.s.m.bin(c, Bin::Or, lt, gt) } else { let p = match op { - "f" => pred::FALSE, "lt" => pred::OLT, "eq" => pred::OEQ, "le" => pred::OLE, @@ -6499,7 +6505,6 @@ impl<'a> Lower<'a> { "nle" => pred::UGT, "neq" => pred::UNE, "nlt" => pred::UGE, - "tru" => pred::TRUE, _ => return Err(inst.name()), }; self.s.m.cmp(c, p, a, b) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 2884e1eca6..53c3ca7e2b 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -570,6 +570,45 @@ fn v_cmp_lg_is_false_for_nan() { } } +/// `v_cmp_f_*` is false and `v_cmp_tru_*` true whatever the operands, NaNs +/// included (RDNA2 ISA). As `fcmp false`/`fcmp true` WARP removed its device +/// at the first dispatch. +#[test] +fn float_compares_that_are_always_false_or_true() { + let nan = f32::NAN.to_bits(); + let f = f32::to_bits; + let f32_inputs = [ + [f(1.0), f(2.0), 0, 0], + [f(1.0), f(1.0), 0, 0], + [nan, f(1.0), 0, 0], + [nan, nan, 0, 0], + ]; + let f16_inputs = [ + [0x3C00, 0x4000, 0, 0], + [0x3C00, 0x3C00, 0, 0], + [0x7E00, 0x3C00, 0, 0], + [0x7E00, 0x7E00, 0, 0], + ]; + // v_cmp_*_e64 s20, v1, v2; v_cndmask_b32_e64 v0, 0, 1, s20 + for (op, what, inputs, want) in [ + (0x000u16, "v_cmp_f_f32", f32_inputs, 0), + (0x00f, "v_cmp_tru_f32", f32_inputs, 1), + (0x0c8, "v_cmp_f_f16", f16_inputs, 0), + (0x0ef, "v_cmp_tru_f16", f16_inputs, 1), + ] { + let mut body = vop3(op, 20, vgpr(1), vgpr(2), 0x80).to_vec(); + body.extend_from_slice(&vop3(0x101, 0, 0x80, 0x81, sgpr(20))); + let shader = build_valu_cs(&body); + run_cases(&shader, &inputs, |backend, _, inp, got| { + assert_eq!( + got, want, + "{backend}: {what}({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + } +} + #[test] fn v_fract_f32_never_returns_one() { // v_fract_f32 v0, v1 (VOP1 opcode 0x020) From 94714620bd1c6cc61d395eac88e11484390c027c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 12:46:49 +0100 Subject: [PATCH 047/123] Shaders: apply v_cmp_class_f32 abs/neg modifiers bitwise (cherry picked from commit e08e6f46641ff8ced92b94313f1e143a3ac9fe42) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 38 ++++--- crates/victory-shader/src/emit/valu_tests.rs | 112 +++++++++++++++++++ 2 files changed, 134 insertions(+), 16 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 9d6407e544..272eb0c798 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6405,24 +6405,30 @@ impl<'a> Lower<'a> { // Bit k of src1 tests class k: signalling NaN, quiet NaN, // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf. let f16 = ty == "f16"; - let x = if f16 { - let Fields::Valu(v) = &inst.fields else { - unreachable!() - }; - let mut h = self.half_src(inst, 0)?; - if v.abs & 1 != 0 { - let m = self.s.m.i32(0x7FFF); - h = self.s.m.bin(c, Bin::And, h, m); - } - if v.neg & 1 != 0 { - let s = self.s.m.i32(0x8000); - h = self.s.m.bin(c, Bin::Xor, h, s); - } - h + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + // Apply abs/neg bitwise so sNaNs are not quieted and denormals + // are not flushed to zero before classification. + let (mut x, abs_mask, sign_bit) = if f16 { + (self.half_src(inst, 0)?, 0x7FFF, 0x8000) } else { - let x = self.fsrc(inst, 0)?; - self.as_int(x) + let op = *v.src.first().ok_or("a missing operand")?; + let raw = self.operand(inst, &op)?; + let x = match Self::sdwa_src(inst, 0) { + Some((sel, sext)) => self.select_bits(raw, sel, sext), + None => raw, + }; + (x, 0x7FFF_FFFF, 0x8000_0000) }; + if v.abs & 1 != 0 { + let m = self.s.m.i32(abs_mask); + x = self.s.m.bin(c, Bin::And, x, m); + } + if v.neg & 1 != 0 { + let s = self.s.m.i32(sign_bit); + x = self.s.m.bin(c, Bin::Xor, x, s); + } let mask = self.src(inst, 1)?; let k = |l: &mut Self, v: u32| l.s.m.i32(v); let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 { diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 53c3ca7e2b..8942a55e0d 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1411,3 +1411,115 @@ fn wave64_dpp_first_lane_and_swizzle_run_without_64_lane_waves() { use super::wave64_fixtures::{DPP_FIRST_SWIZZLE, dpp_first_swizzle_expected}; run_wave64_group(DPP_FIRST_SWIZZLE, 0, &dpp_first_swizzle_expected()); } + +#[test] +fn v_cmp_class_f32_matches_rdna2() { + let build = |abs0: bool, neg0: bool| { + let [mut w0, mut w1] = vop3(0x088, 6, vgpr(1), vgpr(2), 0); + if abs0 { + w0 |= 1 << 8; // abs[0] = 1 + } + if neg0 { + w1 |= 1 << 29; // neg[0] = 1 + } + let sel = vop3(0x101, 0, 0x80, 0x81, sgpr(6)); + build_valu_cs(&[w0, w1, sel[0], sel[1]]) + }; + + // All 10 IEEE-754 binary32 classes: bit k corresponds to class k. + let classes: &[(u32, u32)] = &[ + (0x7F80_0001, 0), // +sNaN (quiet bit 0x40_0000 clear) + (0xFF80_0001, 0), // -sNaN + (0x7FC0_0000, 1), // +qNaN (quiet bit set) + (0xFFC0_0001, 1), // -qNaN + (0xFF80_0000, 2), // -inf + (0xBF80_0000, 3), // -normal (-1.0) + (0x8000_0001, 4), // -denormal + (0x8000_0000, 5), // -0.0 + (0x0000_0000, 6), // +0.0 + (0x0000_0001, 7), // +denormal + (0x3F80_0000, 8), // +normal (+1.0) + (0x7F80_0000, 9), // +inf + ]; + let mut plain_cases = Vec::new(); + for &(bits, cls) in classes { + plain_cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); + plain_cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); + } + let cmp_plain = build(false, false); + let plain_in: Vec<[u32; 4]> = plain_cases.iter().map(|c| c.0).collect(); + run_cases(&cmp_plain, &plain_in, |backend, i, inp, got| { + let want = plain_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmp_class_f32({:#010x}, {:#05x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + + // RDNA2 input modifiers on v_cmp_class_f32 manipulate the sign bit bitwise: + // they must not quiet sNaNs or flush denormals to zero. + struct ModCases { + label: &'static str, + abs: bool, + neg: bool, + items: &'static [(u32, u32)], + } + let mod_sets = [ + ModCases { + label: "neg", + abs: false, + neg: true, + items: &[ + (0x3F80_0000, 3), // -(+1.0) -> -normal + (0x0000_0000, 5), // -(+0.0) -> -0.0 + (0x8000_0000, 6), // -(-0.0) -> +0.0 + (0x0000_0001, 4), // -(+denormal) -> -denormal (not flushed to -0.0) + (0x8000_0001, 7), // -(-denormal) -> +denormal (not flushed to +0.0) + (0x7F80_0001, 0), // -(+sNaN) -> sNaN (not quieted to qNaN) + (0xFF80_0001, 0), // -(-sNaN) -> sNaN (not quieted to qNaN) + ], + }, + ModCases { + label: "abs", + abs: true, + neg: false, + items: &[ + (0xBF80_0000, 8), // |-1.0| -> +normal + (0x8000_0000, 6), // |-0.0| -> +0.0 + (0xFF80_0000, 9), // |-inf| -> +inf + (0x8000_0001, 7), // |-denormal| -> +denormal + (0xFF80_0001, 0), // |-sNaN| -> sNaN + ], + }, + ModCases { + label: "abs+neg", + abs: true, + neg: true, + items: &[ + (0x3F80_0000, 3), // -|+1.0| -> -normal + (0xBF80_0000, 3), // -|-1.0| -> -normal + (0x0000_0001, 4), // -|+denormal| -> -denormal + (0x8000_0001, 4), // -|-denormal| -> -denormal + (0x7F80_0001, 0), // -|+sNaN| -> sNaN + ], + }, + ]; + for set in mod_sets { + let shader = build(set.abs, set.neg); + let mut cases = Vec::new(); + for &(bits, cls) in set.items { + cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); + cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); + } + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmp_class_f32[{}]({:#010x}, {:#05x}) = {got}, want {want}", + set.label, inp[0], inp[1], + ); + }); + } +} From 3a7a75e5722278ae487af4310f42977d2a759a68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 12:38:28 +0100 Subject: [PATCH 048/123] Shaders: sign-extend SDWA WORD_0 results with UNUSED_SEXT on 16-bit ops (cherry picked from commit 24011cf1d2c4e002920df6362a80a35f7133e685) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 67 +++++++--- crates/victory-shader/src/emit/valu_tests.rs | 127 +++++++++++++++++++ 2 files changed, 178 insertions(+), 16 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 272eb0c798..f7490fe038 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5514,33 +5514,41 @@ impl<'a> Lower<'a> { return Err("a 16-bit result outside a VGPR"); }; let mut high = v.opsel >> 3 & 1 != 0; - // SDWA: the word written, the other one kept (preserve) or zero - // (pad; a sign extension above the high word adds nothing). + // SDWA: the word written, the other one kept (preserve), sign-extended + // above the low word (sext), or zero (pad; a sign extension above the + // high word adds nothing, and bits below it pad with zero). let mut keep = true; + let mut sext = false; if let Some(sd) = v.sdwa { match (sd.dst_sel, sd.dst_unused) { (4, 2) => {} (5, 2) => high = true, - (4 | 6, _) => keep = false, - (5, _) => (high, keep) = (true, false), + (4, 1) => (keep, sext) = (false, true), + (4, 0) | (6, _) => keep = false, + (5, 0 | 1) => (high, keep) = (true, false), _ => return Err("an SDWA destination of a 16-bit operation"), } } let c = self.cur; - let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { - Some(Ok(o)) if keep => o, - _ => self.s.m.i32(0), - }; let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF)); - let x = self.s.m.bin(c, Bin::And, x, low); - let r = if high { - let o = self.s.m.bin(c, Bin::And, old, low); - let x = self.s.m.bin(c, Bin::Shl, x, k16); - self.s.m.bin(c, Bin::Or, o, x) + let r = if sext { + let t = self.s.m.bin(c, Bin::Shl, x, k16); + self.s.m.bin(c, Bin::AShr, t, k16) } else { - let keep = self.s.m.i32(0xFFFF_0000); - let o = self.s.m.bin(c, Bin::And, old, keep); - self.s.m.bin(c, Bin::Or, o, x) + let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { + Some(Ok(o)) if keep => o, + _ => self.s.m.i32(0), + }; + let x = self.s.m.bin(c, Bin::And, x, low); + if high { + let o = self.s.m.bin(c, Bin::And, old, low); + let x = self.s.m.bin(c, Bin::Shl, x, k16); + self.s.m.bin(c, Bin::Or, o, x) + } else { + let keep = self.s.m.i32(0xFFFF_0000); + let o = self.s.m.bin(c, Bin::And, old, keep); + self.s.m.bin(c, Bin::Or, o, x) + } }; self.write_placed(inst, Reg::V(reg), r, guard); Ok(()) @@ -9135,6 +9143,33 @@ mod tests { assert_eq!(half(0xBC00 << half_shift(16)), -1.0); } + #[test] + fn sdwa_16bit_reserved_dst_unused_is_refused() { + for dst_sel in [4u32, 5] { + // v_cvt_i16_f16_sdwa v1, v0 dst_sel:{WORD_0,WORD_1} dst_unused:3 (reserved); + // ds_write_b32 v0, v1 to keep v1 live. + let sdwa_ext = (dst_sel << 8) | (3 << 11) | (4 << 16); + let words = [ + 0x7E02_A6F9, // v_cvt_i16_f16 v1, sdwa + sdwa_ext, + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let err = lowers_lds(&words).expect_err("reserved dst_unused must fail"); + assert!( + matches!( + err, + crate::ShaderError::Unsupported { + what: "an SDWA destination of a 16-bit operation", + .. + } + ), + "unexpected error for dst_sel={dst_sel}: {err}" + ); + } + } + #[test] fn a_descriptor_selected_by_scc_picks_its_heap_index() { // Two buffer descriptors loaded from the table at s0, one picked by diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 8942a55e0d..c1b849864e 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -40,6 +40,43 @@ const fn s_load_dwordx4(dst: u8, base: u8) -> [u32; 2] { const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) } +/// VOP1 SDWA `op_sdwa vdst, vsrc0 dst_sel dst_unused src0_sel`. +const fn vop1_sdwa( + op: u16, + vdst: u8, + vsrc0: u8, + dst_sel: u8, + dst_unused: u8, + src0_sel: u8, +) -> [u32; 2] { + [ + vop1(op, vdst, 0xF9), + vsrc0 as u32 + | (dst_sel as u32 & 7) << 8 + | (dst_unused as u32 & 3) << 11 + | (src0_sel as u32 & 7) << 16, + ] +} + +/// VOP2 SDWA `op_sdwa vdst, vsrc0, vsrc1 dst_sel dst_unused src0_sel src1_sel`. +const fn vop2_sdwa( + op: u8, + vdst: u8, + vsrc0: u8, + vsrc1: u8, + dst: (u8, u8), + src_sel: [u8; 2], +) -> [u32; 2] { + [ + (op as u32) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | 0xF9, + vsrc0 as u32 + | (dst.0 as u32 & 7) << 8 + | (dst.1 as u32 & 3) << 11 + | (src_sel[0] as u32 & 7) << 16 + | (src_sel[1] as u32 & 7) << 24, + ] +} + /// VOP3 `op vdst, src0, src1, src2` (no modifiers). const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { @@ -1523,3 +1560,93 @@ fn v_cmp_class_f32_matches_rdna2() { }); } } + +#[test] +fn sdwa_16bit_dst_unused_sext_sign_extends_word0() { + // SDWA dst_sel: 4 = WORD_0, 5 = WORD_1. + // SDWA dst_unused: 0 = UNUSED_PAD, 1 = UNUSED_SEXT, 2 = UNUSED_PRESERVE. + // Pre-seed v0 from v4 (0xABCD_1234) so UNUSED_SEXT/UNUSED_PAD/UNUSED_PRESERVE + // are distinguishable from each other. + let seed = 0xABCD_1234u32; + + // v_cvt_i16_f16_sdwa v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0 + let mut body = vec![vop1(0x001, 0, vgpr(4))]; + body.extend_from_slice(&vop1_sdwa(0x053, 0, 1, 4, 1, 4)); + let cvt_sext = build_valu_cs(&body); + let cvt_cases: &[(u32, u32)] = &[ + (0xBC00, 0xFFFF_FFFF), // -1.0 -> -1i16 sign-extended to -1i32 + (0xF800, 0xFFFF_8000), // -32768.0 -> -32768i16 sign-extended + (0x3C00, 0x0000_0001), // +1.0 -> +1i16 zero-extended (old v0 upper bits cleared) + (0x7BFF, 0x0000_7FFF), // +65504.0 -> saturated +32767i16 + (0x0000, 0x0000_0000), // 0.0 -> 0 + ]; + let cvt_in: Vec<[u32; 4]> = cvt_cases.iter().map(|&(x, _)| [x, 0, 0, seed]).collect(); + run_cases(&cvt_sext, &cvt_in, |backend, i, inp, got| { + let want = cvt_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cvt_i16_f16_sdwa({:#06x}, WORD_0, UNUSED_SEXT) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); + + // v_cvt_norm_i16_f16_sdwa v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_1 + let mut body = vec![vop1(0x001, 0, vgpr(4))]; + body.extend_from_slice(&vop1_sdwa(0x063, 0, 1, 4, 1, 5)); + let norm_sext = build_valu_cs(&body); + let norm_cases: &[(u32, u32)] = &[ + (0xBC00_3C00, 0xFFFF_8001), // high half -1.0 -> -32767i16 sign-extended + (0x3C00_BC00, 0x0000_7FFF), // high half +1.0 -> +32767i16 + ]; + let norm_in: Vec<[u32; 4]> = norm_cases.iter().map(|&(x, _)| [x, 0, 0, seed]).collect(); + run_cases(&norm_sext, &norm_in, |backend, i, inp, got| { + let want = norm_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cvt_norm_i16_f16_sdwa({:#010x}, WORD_0, UNUSED_SEXT) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); + + // v_add_f16_sdwa v0, v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0 src1_sel:WORD_0 + let mut body = vec![vop1(0x001, 0, vgpr(4))]; + body.extend_from_slice(&vop2_sdwa(0x32, 0, 1, 2, (4, 1), [4, 4])); + let add_sext = build_valu_cs(&body); + let add_cases: &[(u32, u32, u32)] = &[ + (0xBC00, 0xC000, 0xFFFF_C200), // -1.0 + -2.0 = -3.0 (0xC200, bit 15 set -> sign-extended) + (0x3C00, 0x4000, 0x0000_4200), // +1.0 + +2.0 = +3.0 (0x4200, bit 15 clear) + ]; + let add_in: Vec<[u32; 4]> = add_cases.iter().map(|&(a, b, _)| [a, b, 0, seed]).collect(); + run_cases(&add_sext, &add_in, |backend, i, inp, got| { + let want = add_cases[i].2; + assert_eq!( + got, want, + "{backend}: v_add_f16_sdwa({:#06x}, {:#06x}, WORD_0, UNUSED_SEXT) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], + ); + }); + + // Regression check for the other dst_sel / dst_unused modes on v_cvt_i16_f16_sdwa(-1.0): + // WORD_0 + UNUSED_PAD -> 0x0000_FFFF, WORD_0 + UNUSED_PRESERVE -> 0xABCD_FFFF, + // WORD_1 + UNUSED_PAD / UNUSED_SEXT -> 0xFFFF_0000 (bits below WORD_1 pad with 0), + // WORD_1 + UNUSED_PRESERVE -> 0xFFFF_1234, DWORD -> 0x0000_FFFF. + let modes: &[(u8, u8, u32)] = &[ + (4, 0, 0x0000_FFFF), + (4, 2, 0xABCD_FFFF), + (5, 0, 0xFFFF_0000), + (5, 1, 0xFFFF_0000), + (5, 2, 0xFFFF_1234), + (6, 0, 0x0000_FFFF), + ]; + for &(dst_sel, dst_unused, want) in modes { + let mut body = vec![vop1(0x001, 0, vgpr(4))]; + body.extend_from_slice(&vop1_sdwa(0x053, 0, 1, dst_sel, dst_unused, 4)); + let shader = build_valu_cs(&body); + run_cases(&shader, &[[0xBC00, 0, 0, seed]], |backend, _, _, got| { + assert_eq!( + got, want, + "{backend}: v_cvt_i16_f16_sdwa(-1.0, dst_sel={dst_sel}, dst_unused={dst_unused}) = {got:#010x}, want {want:#010x}", + ); + }); + } +} From 5d048cc0e1a1713bf626e8f0b2666c30af3bb958 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 13:07:36 +0100 Subject: [PATCH 049/123] GPU: preserve NaN and round normals to nearest even in f32_to_half (cherry picked from commit 63111deb4d007dd0830864f4e22cd5264bd01275) --- crates/victory-gpu/src/primitive.rs | 63 +++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index 5b01f7b35e..976be2d208 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -185,10 +185,16 @@ fn half_to_f32(h: u16) -> f32 { fn f32_to_half(v: f32) -> u16 { let bits = v.to_bits(); let sign = ((bits >> 16) & 0x8000) as u16; - let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15; + let raw_exp = (bits >> 23) & 0xff; let man = bits & 0x7f_ffff; + if raw_exp == 0xff && man != 0 { + // Quiet NaN, preserving sign and upper payload bits (set bit 9 so a + // signalling NaN with payload below bit 13 never turns into infinity). + return sign | 0x7e00 | (man >> 13) as u16; + } + let exp = raw_exp as i32 - 127 + 15; if exp >= 31 { - return sign | 0x7c00; // too large: infinity + return sign | 0x7c00; // infinity or overflow } if exp <= 0 { if exp < -10 { @@ -205,10 +211,11 @@ fn f32_to_half(v: f32) -> u16 { let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0)); return sign | m as u16; } - // Rounded to nearest: a carry out of the mantissa is added into the + // Round to nearest even: a carry out of the mantissa is added into the // exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00. let half = (exp as u32) << 10; - sign | (half + ((man + 0x1000) >> 13)) as u16 + let lsb = (man >> 13) & 1; + sign | (half + ((man + 0x0fff + lsb) >> 13)) as u16 } #[cfg(test)] @@ -401,4 +408,52 @@ mod tests { assert_eq!(f32_to_half(1.5), 0x3e00); assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); } + + #[test] + fn f32_to_half_preserves_nan_and_rounds_normals_to_nearest_even() { + // Quiet and signalling NaNs (both signs) must produce quiet f16 NaNs, + // never infinities (0x7c00 / 0xfc00). + for (bits, want) in [ + (f32::NAN.to_bits(), 0x7e00u16), + ((-f32::NAN).to_bits(), 0xfe00), + (0x7fc0_4000, 0x7e02), // qNaN with payload bits + (0x7f80_0001, 0x7e00), // +sNaN with payload below bit 13 + (0xff80_0001, 0xfe00), // -sNaN with payload below bit 13 + ] { + let h = f32_to_half(f32::from_bits(bits)); + assert_eq!( + h, want, + "f32_to_half({bits:#010x}) = {h:#06x}, want {want:#06x}" + ); + assert!(half_to_f32(h).is_nan()); + } + assert_eq!(f32_to_half(f32::INFINITY), 0x7c00); + assert_eq!(f32_to_half(f32::NEG_INFINITY), 0xfc00); + + // Normal rounding must tie to even (matching subnormals): + // 1.0 + 2^-11 is midway between even 0x3c00 and odd 0x3c01 -> 0x3c00. + assert_eq!(f32_to_half(f32::from_bits(0x3f80_1000)), 0x3c00); + assert_eq!(f32_to_half(f32::from_bits(0xbf80_1000)), 0xbc00); + // 1.0 + 3*2^-11 is midway between odd 0x3c01 and even 0x3c02 -> 0x3c02. + assert_eq!(f32_to_half(f32::from_bits(0x3f80_3000)), 0x3c02); + // Strictly above the tie rounds up. + assert_eq!(f32_to_half(f32::from_bits(0x3f80_1001)), 0x3c01); + // Overflow boundary: just below 65520 stays finite (0x7bff); 65520 ties to even (+inf). + assert_eq!(f32_to_half(f32::from_bits(0x477f_efff)), 0x7bff); + assert_eq!(f32_to_half(f32::from_bits(0x477f_f000)), 0x7c00); + + // Every finite/infinite f16 bit pattern round-trips identically; NaNs stay NaN. + for h in 0..=u16::MAX { + let f = half_to_f32(h); + let back = f32_to_half(f); + if f.is_nan() { + assert!( + (back & 0x7fff) > 0x7c00 && (back & 0x8000) == (h & 0x8000), + "NaN {h:#06x} became {back:#06x}" + ); + } else { + assert_eq!(back, h, "f16 {h:#06x} failed round-trip"); + } + } + } } From 3fb0864a58ea9e072e977c77799a5c84183b7b3b Mon Sep 17 00:00:00 2001 From: Nicolai Van der Storm Date: Tue, 24 Nov 2026 13:17:21 +0100 Subject: [PATCH 050/123] Shaders: an image atomic gets its own u32 handle, not a cached f32 one Heap handles were cached per block by the first property word only (kind and UAV flag), not the second (component type and count). A size query (f32 x4) and then an atomic (u32 x1) on the same image UAV in one block shared the query's handle, so dxil-spirv declared a float image and emitted OpAtomicUMax %float. NVIDIA's compiler faults on that (0xc0000005 in vkCreate*Pipelines under vkd3d-proton). The key now holds both words; structured buffers read with two strides get their own handles too. Offline check (translate --pipelines over shaders.rpf, NVIDIA RTX 5070 Ti, vkd3d-proton master): 21,566 pipelines, no driver fault, every dumped SPIR-V module passes spirv-val. In the title, the world loads without the driver faults. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit ae7e0bef6a9bc834358d48f39902c284f3d9218e) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 44 ++++++++++++++++++++++++ crates/victory-shader/src/emit/shader.rs | 7 ++++ 2 files changed, 51 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index f7490fe038..366d10e3e1 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -50,6 +50,9 @@ pub(crate) struct Lowered { /// Heap handles made with a non-uniform index. #[cfg(test)] pub nonuniform_handles: u32, + /// Each heap handle's resource properties, in creation order. + #[cfg(test)] + pub heap_props: Vec<(u32, u32)>, /// Whether the program uses wave operations. #[cfg(test)] pub wave_ops: bool, @@ -1189,6 +1192,8 @@ impl<'a> Lower<'a> { #[cfg(test)] nonuniform_handles: self.s.nonuniform_handles, #[cfg(test)] + heap_props: std::mem::take(&mut self.s.heap_props), + #[cfg(test)] wave_ops: self.s.flags & flags::WAVE_OPS != 0, dxil: self.s.finish(), user_data, @@ -4351,6 +4356,8 @@ impl<'a> Lower<'a> { ) -> Result { match src { Source::Loaded { load, first } => { + // Keyed by both property words: one descriptor can be read + // as f32 x4 (a size query) and as u32 (an atomic). let key = (self.cur, *load, *first, sampler, props); if let Some(&h) = self.handles.get(&key) { return Ok(h); @@ -9248,6 +9255,43 @@ mod tests { } } + #[test] + fn an_image_atomic_after_a_size_query_gets_an_integer_handle() { + // A size query, then an atomic on the same image UAV: the float + // handle of the query must not be reused for the u32 atomic + // (dxil-spirv then declares a float image: OpAtomicUMax %float). + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0202, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], null + 0x7E02_0300, // v_mov_b32 v1, v0 + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xF038_0308, + 0x0002_0200, // image_get_resinfo v[2:3], v0, s[8:15] dmask:0x3 dim:2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xF05C_0108, + 0x0002_0200, // image_atomic_umax v2, v[0:1], s[8:15] dmask:0x1 dim:2D + S_ENDPGM, + ]; + let used = vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }]; + let l = lower_with(&words, vec![root(RootType::Table, 0, 0)], used).unwrap(); + // The query's f32 x4 handle and the atomic's own u32 x1 one. + assert_eq!( + l.heap_props.iter().map(|p| p.1).collect::>(), + [0x409, 0x105] + ); + } + /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { let (layout, mut used) = texture_tables(); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 042ff2218e..9c9a6b022c 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -70,6 +70,9 @@ pub(crate) struct Shader { pub flags: u64, /// Heap handles made with a non-uniform index. pub nonuniform_handles: u32, + /// Each heap handle's resource properties, in creation order. + #[cfg(test)] + pub heap_props: Vec<(u32, u32)>, /// A compute shader with this thread-group size. pub threads: Option<[u32; 3]>, /// The wave size a compute shader requires (`WaveSize`). @@ -124,6 +127,8 @@ impl Shader { root_srvs: Vec::new(), flags: 0, nonuniform_handles: 0, + #[cfg(test)] + heap_props: Vec::new(), threads: None, wave_size: None, lds_dwords: 0, @@ -294,6 +299,8 @@ impl Shader { flags::RESOURCE_HEAP }; self.nonuniform_handles += u32::from(nonuniform); + #[cfg(test)] + self.heap_props.push(props); let (s, n) = (self.m.bool(sampler), self.m.bool(nonuniform)); let h = self.op( block, From e208b061c89334d2fa0623cafc9acf3eaa93ebf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 12:56:18 +0100 Subject: [PATCH 051/123] GPU: validate sub-16 alignments and use fallible allocation in allocate_upload (cherry picked from commit 57c61f2d8218fbf67d0beb22845edb4787168cd8) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/list.rs | 87 ++++++++++++++++++++++++++++++++-- 1 file changed, 82 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 9122a574f7..e1a5d8362f 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1179,20 +1179,34 @@ extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: /// its instance descriptions there (and wrote through our old /// `E_NOTIMPL` as a pointer). extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 { - let align = usize::try_from(alignment).unwrap_or(0).max(16); + if this.is_null() { + return std::ptr::null_mut(); + } + let Ok(raw_align) = usize::try_from(alignment) else { + return std::ptr::null_mut(); + }; + if raw_align != 0 && !raw_align.is_power_of_two() { + return std::ptr::null_mut(); + } + let align = raw_align.max(16); let Some(len) = usize::try_from(size) .ok() .and_then(|s| s.checked_add(align)) else { return std::ptr::null_mut(); }; - if this.is_null() || !align.is_power_of_two() { + let mut block = Vec::new(); + if block.try_reserve_exact(len).is_err() { return std::ptr::null_mut(); } - let mut block = vec![0u8; len]; + block.resize(len, 0); let start = block.as_mut_ptr(); - // SAFETY: the offset is below `align`, so `size` bytes fit after it. - let at = unsafe { start.add(start.align_offset(align)) }; + let offset = start.align_offset(align); + if offset >= align { + return std::ptr::null_mut(); + } + // SAFETY: `offset < align` and `len == size + align`, so `size` bytes fit at `start + offset`. + let at = unsafe { start.add(offset) }; // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::()).uploads }; // Moving the vector keeps its heap block where it is. @@ -2024,4 +2038,67 @@ mod tests { assert_eq!(release(object), 0); } } + + #[test] + fn allocate_upload_rejects_bad_alignments_and_oversized_requests() { + let null = std::ptr::null(); + let mut allocator = null; + assert_eq!( + create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), + S_OK + ); + let mut list = null; + assert_eq!( + create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), + S_OK + ); + + assert!(allocate_upload(null, 16, 16).is_null(), "null list"); + for bad in [3u64, 5, 6, 7, 9, 10, 12, 15, 0x30] { + assert!( + allocate_upload(list, 8, bad).is_null(), + "non-power-of-two alignment {bad} must fail" + ); + } + // Oversized alignments and sizes must return null rather than panicking + // or aborting across the FFI boundary. + assert!( + allocate_upload(list, 16, 1u64 << 63).is_null(), + "alignment > isize::MAX must return null" + ); + assert!( + allocate_upload(list, isize::MAX as u64, 16).is_null(), + "size + align > isize::MAX must return null" + ); + assert!( + allocate_upload(list, u64::MAX, 16).is_null(), + "wrapping size must return null" + ); + assert!( + allocate_upload(list, 1u64 << 50, 16).is_null(), + "unallocatable size must return null" + ); + // SAFETY: `list` is ours and stays live until released below. + let uploads = unsafe { &(*list.cast::()).uploads }; + assert!(uploads.lock().unwrap().is_empty()); + + // Default alignment (0) and valid sub-16 powers of two still succeed + // with at least 16-byte alignment. + for align in [0u64, 1, 2, 4, 8, 16, 64] { + let p = allocate_upload(list, 24, align); + let want = align.max(16) as usize; + assert!( + !p.is_null() && (p as usize).is_multiple_of(want), + "valid alignment {align} failed" + ); + // SAFETY: 24 bytes were allocated at `p`. + unsafe { p.write_bytes(0x5a, 24) }; + } + assert_eq!(close(list), S_OK); + assert_eq!(reset(list, allocator, null), S_OK); + assert!(uploads.lock().unwrap().is_empty()); + let release = |o: This| slot:: u32>(o, 0x10)(o); + assert_eq!(release(list), 0); + assert_eq!(release(allocator), 0); + } } From b90cf8803a7b73fa0c3502311ba4dd15b010d1c1 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:12:22 +0000 Subject: [PATCH 052/123] HLE: XApu writes samples to the title's output as bytes, never as [f32] The title's output pointer is a *mut u8 with no alignment promise; viewing it as &mut [f32] is undefined behaviour when it is not 4-byte aligned. All three output paths (plain decode, converted interleaved, converted deinterleaved) now write little-endian bytes. A result event that cannot be created frees the connection memory and fails with E_OUTOFMEMORY instead of handing back a null event. Idea from AndyLatimer's 13df0dad (upstream #839), hand-ported: our XApu also converts and resamples, so the patch did not apply. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-hle/src/modules/apu.rs | 61 ++++++++++++++++++--------- 1 file changed, 41 insertions(+), 20 deletions(-) diff --git a/crates/victory-hle/src/modules/apu.rs b/crates/victory-hle/src/modules/apu.rs index 4eb9056083..51c3daa387 100644 --- a/crates/victory-hle/src/modules/apu.rs +++ b/crates/victory-hle/src/modules/apu.rs @@ -212,7 +212,13 @@ pub extern "system" fn XApuConnect( } let event = if input.options & RESULT_EVENT != 0 { // SAFETY: plain auto-reset event, no name. - unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) } + let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; + if event.is_null() { + // SAFETY: allocated above with `layout`. + unsafe { std::alloc::dealloc(memory, layout) }; + return E_OUTOFMEMORY; + } + event } else { std::ptr::null_mut() }; @@ -431,19 +437,29 @@ fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: & .min(command.frame_count as usize) .min(output_length as usize / (4 * channels)); let kept = &pcm[first * channels..(first + frames) * channels]; - // SAFETY: the title's output buffer holds `output_length` bytes. - let out = unsafe { std::slice::from_raw_parts_mut(output.cast::(), frames * channels) }; + // SAFETY: the title's output buffer holds `output_length` bytes, at + // least `frames * channels` samples. + let out = unsafe { std::slice::from_raw_parts_mut(output, frames * channels * 4) }; if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 { - for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() { - (out[i], out[frames + i]) = (frame[0], frame[1]); - } + let (left, right) = out.split_at_mut(frames * 4); + let pairs = kept.as_chunks::<2>().0; + put_samples(left, pairs.iter().map(|f| f[0])); + put_samples(right, pairs.iter().map(|f| f[1])); } else { - out.copy_from_slice(kept); + put_samples(out, kept.iter().copied()); } result.frames = frames as u32; result.output_length = (frames * channels * 4) as u32; } +/// Writes float samples to the title's output bytes. The title's buffer is a +/// `*mut u8` with no alignment promise, so it is never viewed as `[f32]`. +fn put_samples(out: &mut [u8], samples: impl Iterator) { + for (dst, sample) in out.as_chunks_mut::<4>().0.iter_mut().zip(samples) { + *dst = sample.to_le_bytes(); + } +} + /// Decodes (when the connection decodes) and resamples one command's input /// into float PCM at the pitch the title asked for. fn process_convert( @@ -535,21 +551,15 @@ fn process_convert( return; } // SAFETY: the title's output buffer holds `output_length` bytes. - let out = unsafe { std::slice::from_raw_parts_mut(output.cast::(), len) }; - for (i, frame) in converted[..frames * 2] - .as_chunks::<2>() - .0 - .iter() - .enumerate() - { - out[i] = frame[0]; - out[midpoint + i] = frame[1]; - } + let out = unsafe { std::slice::from_raw_parts_mut(output, len * 4) }; + let (left, right) = out.split_at_mut(midpoint * 4); + let pairs = converted[..frames * 2].as_chunks::<2>().0; + put_samples(left, pairs.iter().map(|f| f[0])); + put_samples(right, pairs.iter().map(|f| f[1])); } else { // SAFETY: the title's output buffer holds `output_length` bytes. - let out = - unsafe { std::slice::from_raw_parts_mut(output.cast::(), frames * channels) }; - out.copy_from_slice(&converted[..frames * channels]); + let out = unsafe { std::slice::from_raw_parts_mut(output, frames * channels * 4) }; + put_samples(out, converted[..frames * channels].iter().copied()); } result.frames = frames as u32; result.output_length = (frames * channels * 4) as u32; @@ -960,4 +970,15 @@ mod tests { assert!(energy > 0.01, "converted a tone, energy {energy}"); assert_eq!(XApuDisconnect(handle), S_OK); } + + #[test] + fn samples_go_to_an_unaligned_output_as_bytes() { + // One byte past a 4-byte boundary: a `[f32]` view there is UB. + let mut buf = [0u8; 13]; + put_samples(&mut buf[1..], [1.0f32, -2.0, 0.5].into_iter()); + assert_eq!(buf[0], 0); + assert_eq!(buf[1..5], 1.0f32.to_le_bytes()); + assert_eq!(buf[5..9], (-2.0f32).to_le_bytes()); + assert_eq!(buf[9..13], 0.5f32.to_le_bytes()); + } } From 10648ae0797bfa6e703c8b398a023c6994acb525 Mon Sep 17 00:00:00 2001 From: THE-PRO-GAME <171867920+THE-PRO-GAME@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:39:54 +0100 Subject: [PATCH 053/123] XGameSave: ignore noncanonical save version names Version cleanup reconstructs directory names from parsed numbers. A leftover v01 directory must not represent the same version as v1 or cleanup will remove the actual saved data. Only accept the decimal names written by commit. Cover a read with both directories present. (cherry picked from commit 27491af5b8b2b53f24b4e97f608f80a314113f6b) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-hle/src/modules/xgamesave.rs | 25 +++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index 68ebe8e788..2dd57cf29a 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -186,8 +186,12 @@ fn current(dir: &Path) -> std::io::Result> { let file = file.to_string_lossy(); if file.ends_with(".new") { std::fs::remove_dir_all(entry.path())?; - } else if let Some(n) = file.strip_prefix('v').and_then(|n| n.parse::().ok()) { - committed.push(n); + } else if let Some(digits) = file.strip_prefix('v') + && let Ok(number) = digits.parse::() + && digits == number.to_string() + { + // Only consider names that `commit` writes and cleanup can reconstruct. + committed.push(number); } } committed.sort_unstable(); @@ -1232,6 +1236,23 @@ mod tests { assert_eq!((v.number, v.display.as_str()), (1, "Chapter 1")); } + #[test] + fn a_noncanonical_directory_does_not_remove_a_committed_save() { + let root = tempfile::tempdir().unwrap(); + let c = Provider { + root: root.path().to_owned(), + } + .container("Slot"); + commit(&c.dir, 1, "Slot", "", &[("blob", Source::Data(b"data"))]).unwrap(); + let backup = c.dir.join("v01"); + std::fs::create_dir(&backup).unwrap(); + + let blobs = read(&c, None); + assert!(c.dir.join("v1").is_dir(), "the committed save was removed"); + assert!(backup.is_dir()); + assert_eq!(blobs.unwrap(), [("blob".into(), b"data".to_vec())]); + } + /// An empty configuration id names none. As a folder name it would be /// the folder every configuration lives in, whose folders then look /// like containers of the old layout and are converted away. From b5abd827e0a58fba8461c62b1c25bd1abaa7062a Mon Sep 17 00:00:00 2001 From: Numbers-iwnl <62726053+Numbers-iwnl@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:13:38 -0300 Subject: [PATCH 054/123] gameinput: a host slot that never reported input is not a pad A wireless receiver answers for its pad while the pad is switched off: the slot reads connected with an all-zero report. That counted as a pad, so the keyboard's stand-in pad was never connected and keyboard input went nowhere with no controller in hand. Treat a slot as a pad only after it has reported something other than rest. Once it has, it stays a pad at rest, so a played-with pad does not connect and disconnect on every button release. The callback test seeds an all-zero pad and waits for its connect callback; it presses a button now. (cherry picked from commit 517f2775796f7e797c209fd74db6951b9f6b7634) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-hle/src/modules/gameinput.rs | 84 ++++++++++++++++++++- 1 file changed, 80 insertions(+), 4 deletions(-) diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 1c2feeecfe..61eeca18e4 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -340,6 +340,10 @@ struct State { pending: Vec, /// Device callbacks running now: token and thread. running: Vec<(u64, ThreadId)>, + /// Host slots that have reported input at least once. A wireless receiver + /// answers for its pad while the pad is off, with an all-zero report; that + /// slot is not a pad until something is actually pressed. + seen_input: [bool; PADS], } pub struct Hub { @@ -384,6 +388,7 @@ impl Hub { callbacks: Vec::new(), pending: Vec::new(), running: Vec::new(), + seen_input: [false; PADS], }), returned: Condvar::new(), })); @@ -469,6 +474,16 @@ impl State { ) -> Vec { let now = now(); let mut events = std::mem::take(&mut self.pending); + // A slot that has never reported input is not a pad: a wireless receiver keeps + // answering for a pad that is switched off, and its all-zero report used to hide the + // keyboard's stand-in, leaving the keyboard dead with no pad in hand. + let pads: [Option; PADS] = std::array::from_fn(|slot| { + let pad = pads[slot]?; + if pad != PadState::default() { + self.seen_input[slot] = true; + } + self.seen_input[slot].then_some(pad) + }); let any_pad = pads.iter().any(Option::is_some); for (slot, pad) in pads.into_iter().enumerate() { self.update(devices, slot, pad.map(Value::Pad), now, &mut events); @@ -1541,7 +1556,11 @@ mod tests { let stand_in = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); let no_keys = current(hub, KEYBOARD_KIND, KEYBOARD).unwrap(); tick(); - host.lock().unwrap().pads[1] = Some(PadState::default()); + // A slot that has never reported input is not a pad: press A. + host.lock().unwrap().pads[1] = Some(PadState { + buttons: A, + ..Default::default() + }); hub.poll(); let pad_a = current(hub, GAMEPAD_KIND, 1).unwrap(); tick(); @@ -1571,6 +1590,50 @@ mod tests { } } + #[test] + fn a_receiver_with_a_switched_off_pad_does_not_hide_the_keyboard_stand_in() { + let (hub, host) = fake(); + let log = Log::default(); + register(hub, GAMEPAD_KIND, 2, &log); + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); + + // A wireless receiver answers for a pad that is switched off: the slot reads + // connected with an all-zero report. That is not a pad, and it must not take the + // stand-in away - the keyboard would be dead with nothing in the player's hands. + host.lock().unwrap().pads[0] = Some(PadState::default()); + hub.poll(); + assert_eq!( + *log.lock().unwrap(), + [(FALLBACK, STATUS_CONNECTED, 0)], + "an all-zero slot is not a pad" + ); + assert_eq!(current(hub, GAMEPAD_KIND, 0), Err(DEVICE_DISCONNECTED)); + + // The first real press turns the slot into a pad, and the stand-in steps aside. + host.lock().unwrap().pads[0] = Some(PadState { + buttons: A, + ..Default::default() + }); + hub.poll(); + assert_eq!( + log.lock().unwrap()[1..], + [(0, STATUS_CONNECTED, 0), (FALLBACK, 0, STATUS_CONNECTED)] + ); + let pressed = current(hub, GAMEPAD_KIND, 0).unwrap(); + assert_eq!(pad(pressed).buttons, A); + release(pressed); + + // Back at rest it stays a pad: a pad that has been used does not connect and + // disconnect on every button release. + host.lock().unwrap().pads[0] = Some(PadState::default()); + hub.poll(); + assert_eq!(log.lock().unwrap().len(), 3, "no churn while the pad rests"); + let rest = current(hub, GAMEPAD_KIND, 0).unwrap(); + assert_eq!(pad(rest), PadState::default()); + release(rest); + assert_eq!(current(hub, GAMEPAD_KIND, FALLBACK), Err(DEVICE_DISCONNECTED)); + } + #[test] fn keys_feed_the_keyboard_and_the_stand_in_pad() { let (hub, host) = fake(); @@ -1674,7 +1737,12 @@ mod tests { ), S_OK ); - host.lock().unwrap().pads[1] = Some(PadState::default()); + // A slot that has never reported input is not a pad, so the callback test + // presses a button to make this one appear. + host.lock().unwrap().pads[1] = Some(PadState { + buttons: A, + ..Default::default() + }); let poller = std::thread::spawn(|| hub.poll()); while !INSIDE.load(Ordering::SeqCst) { std::thread::sleep(Duration::from_millis(1)); @@ -1699,7 +1767,11 @@ mod tests { #[test] fn devices_are_found_by_id_and_rumble_reaches_the_host() { let (hub, host) = fake(); - host.lock().unwrap().pads[2] = Some(PadState::default()); + // A slot is a pad once it has reported input. + host.lock().unwrap().pads[2] = Some(PadState { + buttons: A, + ..Default::default() + }); hub.poll(); let device = &hub.devices[2] as *const Device; let info = slot:: *const u8, _>(device, 0x18); @@ -1735,7 +1807,11 @@ mod tests { #[test] fn trigger_rumble_reaches_the_host() { let (hub, host) = fake(); - host.lock().unwrap().pads[1] = Some(PadState::default()); + // A slot is a pad once it has reported input. + host.lock().unwrap().pads[1] = Some(PadState { + buttons: A, + ..Default::default() + }); hub.poll(); let device = &hub.devices[1] as *const Device; type Rumble = extern "system" fn(*const Device, *const [f32; 4]); From 5c78110b8537e72cdb4311e56f53af0e40ac9ebb Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:15:09 +0000 Subject: [PATCH 055/123] GPU: ID3D12GraphicsCommandList::ClearState (slot 0x58) The slot was empty: a title calling ClearState jumped through a null method. The host list's state goes back to its defaults and so do our bindings (heaps, roots, views, targets, what the host list has bound), with the given pipeline set for the next draw or dispatch. The list keeps its dynamic descriptor slots, which draws recorded before the clear still read. From geiyiliyabumo's 458e0b6a (upstream #848), adapted to our State. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 45 ++++++++++++++++++++++++++++++++++ crates/victory-gpu/src/list.rs | 18 +++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 335f05aaea..e62161a1eb 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -195,6 +195,16 @@ impl State { self.pipeline = pipeline as usize; } + /// `ClearState`: every binding back to its default as at a reset, with + /// `pipeline` set. The list keeps its dynamic descriptor slots: draws + /// recorded before the clear still read them. + pub(crate) fn clear(&mut self, pipeline: This) { + let dynamic = std::mem::take(&mut self.dynamic); + *self = State::default(); + self.dynamic = dynamic; + self.pipeline = pipeline as usize; + } + /// Takes the dynamic descriptor slots held by this recording, so a /// pending host list can keep them alive until its submission finishes. pub(crate) fn take_dynamic(&mut self) -> Vec<(usize, u32, u32)> { @@ -1608,6 +1618,41 @@ mod depth_tests { } } +#[cfg(test)] +mod clear_state_tests { + use super::*; + + #[test] + fn clear_resets_bindings_but_keeps_dynamic_slots() { + // A synthetic slot record: no registered heap, so giving it back + // does nothing. + let dynamic = (0, 64, 3); + let mut state = State::default(); + state.pipeline = 1; + state.heaps = [2, 3]; + state.targets = vec![8]; + state.topology = 4; + state.host_pipeline = 10; + state.host_roots = [11, 12]; + state.host_heaps = [13, 14]; + state.fresh_tables = [((4, 15), dynamic.1)].into(); + state.dynamic = vec![dynamic]; + let pipeline: This = std::ptr::dangling(); + state.clear(pipeline); + assert_eq!(state.pipeline, pipeline as usize); + assert_eq!(state.heaps, [0; 2]); + assert!(state.targets.is_empty()); + assert_eq!(state.topology, 0); + assert_eq!(state.host_pipeline, 0); + assert_eq!(state.host_roots, [0; 2]); + assert_eq!(state.host_heaps, [0; 2]); + assert!(state.fresh_tables.is_empty()); + assert_eq!(state.dynamic, [dynamic]); + state.reset(std::ptr::null()); + assert!(state.dynamic.is_empty()); + } +} + #[cfg(all(test, feature = "diagnostics"))] mod tests { use super::*; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index e1a5d8362f..147e858149 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1169,6 +1169,21 @@ extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _siz /// Reset with console flags `(allocator, pipeline, flags)`; the flags only /// tune the console's command memory. +/// `ClearState` (0x58): the host list's state and ours back to their +/// defaults, `pipeline` bound at the next draw or dispatch. +extern "system" fn clear_state(this: This, pipeline: This) { + #[cfg(windows)] + with_state(this, |host, state| { + // SAFETY: an open list; the translated pipeline is bound later. + unsafe { host.list.ClearState(None) }; + state.clear(pipeline); + #[cfg(feature = "diagnostics")] + host.note_op(|| format!("clear state {pipeline:?}")); + }); + #[cfg(not(windows))] + let _ = (this, pipeline); +} + extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT { reset(this, allocator, pipeline) } @@ -1625,13 +1640,14 @@ fn defer_write(this: This, address: u64, what: Written, bytes: usize) { /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96 /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 /// + 13): 140 slots. -const METHODS: [(usize, *const ()); 54] = [ +const METHODS: [(usize, *const ()); 55] = [ (0, list_query as *const ()), (2, list_release as *const ()), (7, object::parent_device as *const ()), // 0x38 (8, list_type as *const ()), // 0x40 (9, close as *const ()), // 0x48 (10, reset as *const ()), // 0x50 + (11, clear_state as *const ()), // 0x58 (12, state::draw as *const ()), // 0x60 instanced (13, state::draw_indexed as *const ()), // 0x68 indexed (14, state::dispatch as *const ()), // 0x70 From 7d285fd5177a686d0c254edf8ecae072dc01a4c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:53:29 +0800 Subject: [PATCH 056/123] GPU: implement DiscardResource on command lists with region and state checks (cherry picked from commit 735f3af7cb95574337408f1cf63ff6fad697f64b) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/host.rs | 13 + crates/victory-gpu/src/list.rs | 432 ++++++++++++++++++++++++++++++++- 2 files changed, 444 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 058be0f5ec..051f3d41ef 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1218,6 +1218,19 @@ impl HostList { } } + /// The current state established by this list. A texture the list has + /// never used can arrive in a different state at submission. + pub(crate) fn tracked_texture_state( + &self, + copy: &std::sync::Arc, + ) -> Option { + self.states + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(&(std::sync::Arc::as_ptr(copy) as usize)) + .map(|&(_, last, _)| last) + } + /// At submission: the list that moves each texture this list uses from /// its real state to the one the list starts with; the textures' real /// states become those the list ends with. diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 147e858149..d23c5cd446 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -889,6 +889,154 @@ pub(crate) struct Rect { bottom: i32, } +#[repr(C)] +#[derive(Clone, Copy)] +struct DiscardRegion { + num_rects: u32, + rects: *const Rect, + first_subresource: u32, + num_subresources: u32, +} + +#[cfg(windows)] +const _: () = { + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D12::D3D12_DISCARD_REGION; + assert!(size_of::() == size_of::()); + assert!(align_of::() == align_of::()); + assert!(size_of::() == size_of::()); + assert!(align_of::() == align_of::()); +}; + +/// A non-null, aligned rectangle pointer must cover `num_rects` rectangles. +#[cfg(any(windows, test))] +unsafe fn valid_discard_region( + region: Option<&DiscardRegion>, + dimension: u32, + mip_levels: u16, + depth_or_array_size: u16, + planes: u8, + extent: [u64; 2], +) -> bool { + const TEXTURE_2D: u32 = 3; + const TEXTURE_3D: u32 = 4; + let Some(region) = region else { return true }; + let mips = u64::from(mip_levels.max(1)); + let slices = if dimension == TEXTURE_3D { + 1 + } else { + u64::from(depth_or_array_size.max(1)) + }; + let first = u64::from(region.first_subresource); + let count = u64::from(region.num_subresources); + if count == 0 || first + count > mips * slices * u64::from(planes) { + return false; + } + if region.num_rects == 0 { + return true; + } + let rects = region.num_rects as usize; + // Rectangles apply to 2D subresources of the same dimensions. In a + // contiguous range with multiple mips, adjacent subresources differ. + if dimension != TEXTURE_2D + || (mips > 1 && count > 1) + || region.rects.is_null() + || !region.rects.is_aligned() + || rects > isize::MAX as usize / size_of::() + { + return false; + } + let [width, height] = + extent.map(|size| size.checked_shr((first % mips) as u32).unwrap_or(0).max(1)); + // SAFETY: the caller supplies the array, and its pointer and size were checked. + unsafe { std::slice::from_raw_parts(region.rects, rects) } + .iter() + .all(|r| { + r.left >= 0 + && r.top >= 0 + && r.left < r.right + && r.top < r.bottom + && r.right as u64 <= width + && r.bottom as u64 <= height + }) +} + +#[cfg(any(windows, test))] +fn discard_state_allowed(state: u32, flags: u32) -> bool { + let required_flag = match state { + 0x4 => 0x1, // RENDER_TARGET + 0x10 => 0x2, // DEPTH_WRITE / ALLOW_DEPTH_STENCIL + 0x8 => 0x4, // UNORDERED_ACCESS + _ => return false, + }; + flags & required_flag != 0 +} + +extern "system" fn discard_resource(this: This, resource: This, region: *const DiscardRegion) { + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::*; + let (Some(list), Some(copy)) = (host_list(this), crate::resource::host_copy(resource)) + else { + return; + }; + let Some(state) = list.tracked_texture_state(©) else { + return; + }; + // SAFETY: a live host texture. + let desc = unsafe { copy.texture.GetDesc() }; + if !discard_state_allowed(state, desc.Flags.0 as u32) || !region.is_aligned() { + return; + } + // SAFETY: the title passes a discard region or null. + let region = unsafe { region.as_ref() }; + if let Some(region) = region { + let Some(host) = crate::host::host() else { + return; + }; + let mut format = D3D12_FEATURE_DATA_FORMAT_INFO { + Format: desc.Format, + PlaneCount: 0, + }; + // SAFETY: the feature data matches the requested query. + if unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_FORMAT_INFO, + (&raw mut format).cast(), + size_of::() as u32, + ) + } + .is_err() + { + return; + } + // SAFETY: the title supplies the rectangles described by the region. + if !unsafe { + valid_discard_region( + Some(region), + desc.Dimension.0 as u32, + desc.MipLevels, + desc.DepthOrArraySize, + format.PlaneCount, + [desc.Width, u64::from(desc.Height)], + ) + } { + return; + } + } + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("discard resource {resource:?}")); + // SAFETY: the list holds the texture in a compatible state. The + // checked region and its rectangles have the host layout. + unsafe { + list.list + .DiscardResource(©.texture, region.map(|r| std::ptr::from_ref(r).cast())) + }; + } + #[cfg(not(windows))] + let _ = (this, resource, region); +} + extern "system" fn clear_rtv( this: This, handle: u64, @@ -1640,7 +1788,7 @@ fn defer_write(this: This, address: u64, what: Written, bytes: usize) { /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96 /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 /// + 13): 140 slots. -const METHODS: [(usize, *const ()); 55] = [ +const METHODS: [(usize, *const ()); 56] = [ (0, list_query as *const ()), (2, list_release as *const ()), (7, object::parent_device as *const ()), // 0x38 @@ -1684,6 +1832,7 @@ const METHODS: [(usize, *const ()); 55] = [ (52, clear_rtv as *const ()), // 0x1a0 (53, clear_uav_uint as *const ()), // 0x1a8 (54, clear_uav_float as *const ()), // 0x1b0 + (55, discard_resource as *const ()), // 0x1b8 (59, execute_indirect as *const ()), // 0x1d8 indirect (60, copy_memory as *const ()), // 0x1e0 (68, ignored_state as *const ()), // 0x220 depth bounds @@ -1901,6 +2050,287 @@ mod tests { clear_uav_float(null, 0, 0, null, std::ptr::null(), 0, std::ptr::null()); } + #[test] + fn discard_resource_slot_is_stable() { + assert_eq!(LIST_FUNCTIONS.0[55], discard_resource as *const ()); + assert_eq!(NEWER_LIST_FUNCTIONS.0[55], discard_resource as *const ()); + } + + #[test] + fn discard_region_validation() { + let rect = Rect { + left: 1, + top: 1, + right: 4, + bottom: 4, + }; + let valid = DiscardRegion { + num_rects: 1, + rects: &rect, + first_subresource: 1, + num_subresources: 1, + }; + let whole_subresource = DiscardRegion { + num_rects: 0, + rects: std::ptr::null(), + ..valid + }; + let check = |region: Option<&DiscardRegion>, dimension, mips, slices, planes| { + // SAFETY: each non-null rectangle pointer names one live rectangle. + unsafe { valid_discard_region(region, dimension, mips, slices, planes, [8, 8]) } + }; + assert!(check(None, 3, 2, 3, 1)); + assert!(check(Some(&valid), 3, 2, 3, 1)); + assert!(!check(Some(&valid), 2, 2, 3, 1)); // 1D subresources + assert!(!check(Some(&valid), 4, 2, 3, 1)); // 3D subresources + assert!(check(Some(&whole_subresource), 4, 2, 3, 1)); + assert!(check(Some(&whole_subresource), 3, 1, 1, 2)); // stencil plane + assert!(!check(Some(&whole_subresource), 3, 1, 1, 1)); + + for (first, count) in [(5, 2), (6, 1), (u32::MAX, 2), (1, u32::MAX), (1, 0)] { + let bad_range = DiscardRegion { + first_subresource: first, + num_subresources: count, + ..whole_subresource + }; + assert!(!check(Some(&bad_range), 3, 2, 3, 1)); + } + let last_slice = DiscardRegion { + first_subresource: 5, + ..whole_subresource + }; + assert!(check(Some(&last_slice), 3, 2, 3, 1)); + assert!(!check(Some(&last_slice), 4, 2, 3, 1)); // depth is not an array size + + let null_rects = DiscardRegion { + rects: std::ptr::null(), + ..valid + }; + assert!(!check(Some(&null_rects), 3, 2, 3, 1)); + let different_mips = DiscardRegion { + num_subresources: 2, + ..valid + }; + assert!(!check(Some(&different_mips), 3, 2, 3, 1)); + assert!(check(Some(&different_mips), 3, 1, 3, 1)); + for right in [0, 1, 5] { + let rect = Rect { right, ..rect }; + let bad_rect = DiscardRegion { + rects: &rect, + ..valid + }; + assert!(!check(Some(&bad_rect), 3, 2, 3, 1)); + } + } + + #[test] + fn discard_requires_matching_state_and_flags() { + for (state, flag) in [(0x4, 1), (0x10, 2), (0x8, 4)] { + assert!(discard_state_allowed(state, flag)); + assert!(discard_state_allowed(state, flag | 0x20)); // simultaneous access + assert!(!discard_state_allowed(state, 0x7 ^ flag)); + assert!(!discard_state_allowed(state | 0x80, flag)); + } + for state in [0, 0x400, 0x80] { + assert!(!discard_state_allowed(state, 0x7)); + } + } + + #[cfg(windows)] + #[test] + fn discard_resource_executes_on_guest_queue() { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::{ + CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4, + }; + + let Some(host) = crate::host::host() else { + eprintln!("skipped live discard: no host D3D12 device"); + return; + }; + // SAFETY: plain DXGI queries for the device the guest queue uses. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); + let adapter: IDXGIAdapter1 = factory + .EnumAdapterByLuid(host.device.GetAdapterLuid()) + .unwrap(); + let desc = adapter.GetDesc1().unwrap(); + let name = String::from_utf16_lossy(&desc.Description); + eprintln!("live discard adapter: {}", name.trim_end_matches('\0')); + } + + let null = std::ptr::null(); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let resource_iid = guid( + 0x696442be, + 0xa72e, + 0x4059, + [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad], + ); + let make_resource = |desc: D3D12_RESOURCE_DESC| { + let mut resource = null; + assert_eq!( + crate::resource::create_committed( + null, + (&raw const heap).cast(), + 0, + (&raw const desc).cast(), + 0, + null.cast(), + &resource_iid, + &mut resource, + ), + S_OK + ); + resource + }; + let make_texture = |format, flags| { + let resource = make_resource(D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: flags, + ..Default::default() + }); + assert!( + crate::resource::host_resource(resource).is_some(), + "missing host texture for {format:?}" + ); + resource + }; + let rt = make_texture( + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ); + let ds = make_texture( + DXGI_FORMAT_D24_UNORM_S8_UINT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ); + let uav = make_texture( + DXGI_FORMAT_R32_UINT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ); + let srv = make_texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE); + let buffer = make_resource(D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }); + assert!(crate::resource::buffer_bytes(buffer).is_some()); + + let (mut queue, mut allocator, mut list) = (null, null, null); + let queue_iid = guid( + 0x0ec870a6, + 0x5d7e, + 0x4c22, + [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], + ); + let queue_desc = [0_u32; 4]; + assert_eq!( + crate::queue::create(null, queue_desc.as_ptr().cast(), &queue_iid, &mut queue), + S_OK + ); + assert_eq!( + create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), + S_OK + ); + assert_eq!( + create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), + S_OK + ); + let host_list = host_list(list).unwrap(); + let discard = slot::(list, 0x1b8); + discard(list, null, null.cast()); + discard(list, buffer, null.cast()); + ensure_state( + host_list, + srv, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 as u32, + ); + discard(list, srv, null.cast()); + discard(list, rt, null.cast()); // no state established by this list yet + + ensure_state(host_list, rt, D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32); + discard(list, rt, null.cast()); + let rect = Rect { + left: 1, + top: 2, + right: 5, + bottom: 6, + }; + discard( + list, + rt, + &DiscardRegion { + num_rects: 1, + rects: &rect, + first_subresource: 0, + num_subresources: 1, + }, + ); + let mut descriptor = [0_u64; 14]; + let handle = descriptor.as_mut_ptr() as u64; + crate::descriptor::create_rtv(null, rt, std::ptr::null(), handle); + let clear = + slot::(list, 0x1a0); + clear(list, handle, &[0.25, 0.5, 0.75, 1.0], 0, std::ptr::null()); + + ensure_state(host_list, ds, D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32); + for first_subresource in [0, 1] { + discard( + list, + ds, + &DiscardRegion { + num_rects: 0, + rects: std::ptr::null(), + first_subresource, + num_subresources: 1, + }, + ); + } + ensure_state( + host_list, + uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32, + ); + discard(list, uav, null.cast()); + + assert_eq!( + slot:: HRESULT>(list, 0x48)(list), + S_OK + ); + assert_eq!(host.log_messages(), None); + slot::(queue, 0x50)(queue, 1, &list); + // SAFETY: the guest queue waits for submission and the device is live. + unsafe { host.device.GetDeviceRemovedReason().unwrap() }; + + for object in [list, allocator, queue, rt, ds, uav, srv, buffer] { + assert_eq!( + slot:: u32>(object, 0x10)(object), + 0 + ); + } + } + #[test] fn every_inline_command_falls_back_to_the_table() { let null = std::ptr::null(); From 38bc82e38563b8a884f1f81141d91816b94bf972 Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 21:09:45 +0900 Subject: [PATCH 057/123] GPU: establish state for first-use render target and depth discard (cherry picked from commit 17cd278321852d098e298fa8d5afdde2e9576a0e) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/list.rs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index d23c5cd446..f4fd2da889 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -980,11 +980,22 @@ extern "system" fn discard_resource(this: This, resource: This, region: *const D else { return; }; - let Some(state) = list.tracked_texture_state(©) else { - return; - }; // SAFETY: a live host texture. let desc = unsafe { copy.texture.GetDesc() }; + let tracked = list.tracked_texture_state(©); + let state = match tracked { + Some(state) => state, + None if list_type(this) == D3D12_COMMAND_LIST_TYPE_DIRECT.0 as u32 => { + if desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { + D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32 + } else if desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) { + D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32 + } else { + return; + } + } + None => return, + }; if !discard_state_allowed(state, desc.Flags.0 as u32) || !region.is_aligned() { return; } @@ -1024,6 +1035,11 @@ extern "system" fn discard_resource(this: This, resource: This, region: *const D return; } } + // When discard is the first use, the normal submission prelude + // establishes its state before the list executes. + if tracked.is_none() { + ensure_state(&list, resource, state); + } #[cfg(feature = "diagnostics")] list.note_op(|| format!("discard resource {resource:?}")); // SAFETY: the list holds the texture in a compatible state. The @@ -2257,7 +2273,7 @@ mod tests { create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), S_OK ); - let host_list = host_list(list).unwrap(); + let host_list = &*host_list(list).unwrap(); let discard = slot::(list, 0x1b8); discard(list, null, null.cast()); discard(list, buffer, null.cast()); From a15a7244a8b72d2da30b35a5442272ff7ef39ce6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:48:18 +0800 Subject: [PATCH 058/123] GPU: implement SetPredication, SetMarker, BeginEvent, and EndEvent on command lists (cherry picked from commit a74fe6bc3b1569a8248b72301d4038cb85cef255) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/list.rs | 369 ++++++++++++++++++++++++++++++++- 1 file changed, 366 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index f4fd2da889..080e45239e 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -10,7 +10,7 @@ //! written yet log once with their caller, so a run lists what to do next. #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::mem::offset_of; +use std::{ffi::c_void, mem::offset_of}; use crate::object::{ self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid, @@ -1306,6 +1306,107 @@ extern "system" fn resolve_queries( } } +extern "system" fn set_predication(this: This, buffer: This, offset: u64, operation: u32) { + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::*; + + let Some(host) = host_list(this) else { + return; + }; + if buffer.is_null() { + #[cfg(feature = "diagnostics")] + host.note_op(|| "disable predication".into()); + // SAFETY: an open list; a null buffer disables predication. + unsafe { + host.list + .SetPredication(None, 0, D3D12_PREDICATION_OP_EQUAL_ZERO) + }; + return; + } + let operation = match operation { + 0 => D3D12_PREDICATION_OP_EQUAL_ZERO, + 1 => D3D12_PREDICATION_OP_NOT_EQUAL_ZERO, + _ => { + tracing::debug!(operation, "invalid predication operation"); + return; + } + }; + if !offset.is_multiple_of(8) { + tracing::debug!(offset, "unaligned predication offset"); + return; + } + let Some(data) = buffer_range(buffer, offset, 8) else { + return; + }; + #[cfg(feature = "diagnostics")] + host.note_op(|| format!("set predication {buffer:?}+{offset:#x} {operation:?}")); + if let Some(resource) = crate::resource::host_resource(buffer) { + ensure_state(&host, buffer, D3D12_RESOURCE_STATE_PREDICATION.0 as u32); + // SAFETY: an open list and a live buffer with an aligned predicate. + unsafe { host.list.SetPredication(Some(resource), offset, operation) }; + } else if let Some(device) = crate::host::host() + && let Some((upload, mapped)) = host.upload(device, 8) + { + // Title buffers live in CPU memory. Take each predicate at its place + // among deferred title writes. The list owns the upload, whose + // GENERIC_READ state includes PREDICATION. + host.defer_fill(mapped, data, 8); + // SAFETY: the list retains the upload through execution. + unsafe { host.list.SetPredication(Some(&upload), 0, operation) }; + } + } + #[cfg(not(windows))] + let _ = (this, buffer, offset, operation); +} + +#[cfg(windows)] +fn event_payload(data: *const c_void, size: u32) -> (Option<*const c_void>, u32) { + if data.is_null() || size == 0 { + (None, 0) + } else { + (Some(data), size) + } +} + +extern "system" fn set_marker(this: This, metadata: u32, data: *const c_void, size: u32) { + #[cfg(windows)] + if let Some(host) = host_list(this) { + let (data, size) = event_payload(data, size); + #[cfg(feature = "diagnostics")] + host.note_op(|| format!("set marker metadata={metadata:#x} size={size}")); + // SAFETY: an open list; the caller provides `size` bytes for this call. + unsafe { host.list.SetMarker(metadata, data, size) }; + } + #[cfg(not(windows))] + let _ = (this, metadata, data, size); +} + +extern "system" fn begin_event(this: This, metadata: u32, data: *const c_void, size: u32) { + #[cfg(windows)] + if let Some(host) = host_list(this) { + let (data, size) = event_payload(data, size); + #[cfg(feature = "diagnostics")] + host.note_op(|| format!("begin event metadata={metadata:#x} size={size}")); + // SAFETY: an open list; the caller provides `size` bytes for this call. + unsafe { host.list.BeginEvent(metadata, data, size) }; + } + #[cfg(not(windows))] + let _ = (this, metadata, data, size); +} + +extern "system" fn end_event(this: This) { + #[cfg(windows)] + if let Some(host) = host_list(this) { + #[cfg(feature = "diagnostics")] + host.note_op(|| "end event".into()); + // SAFETY: an open list; the caller pairs this with BeginEvent. + unsafe { host.list.EndEvent() }; + } + #[cfg(not(windows))] + let _ = this; +} + /// IUnknown 3, object 4, device child 1, allocator 2. static ALLOCATOR_FUNCTIONS: Table<24> = { let mut f = object::d3d12_object(object::missing_table::()); @@ -1804,7 +1905,7 @@ fn defer_write(this: This, address: u64, what: Written, bytes: usize) { /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96 /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 /// + 13): 140 slots. -const METHODS: [(usize, *const ()); 56] = [ +const METHODS: [(usize, *const ()); 59] = [ (0, list_query as *const ()), (2, list_release as *const ()), (7, object::parent_device as *const ()), // 0x38 @@ -1849,6 +1950,9 @@ const METHODS: [(usize, *const ()); 56] = [ (53, clear_uav_uint as *const ()), // 0x1a8 (54, clear_uav_float as *const ()), // 0x1b0 (55, discard_resource as *const ()), // 0x1b8 + (56, set_marker as *const ()), // 0x1c0 + (57, begin_event as *const ()), // 0x1c8 + (58, end_event as *const ()), // 0x1d0 (59, execute_indirect as *const ()), // 0x1d8 indirect (60, copy_memory as *const ()), // 0x1e0 (68, ignored_state as *const ()), // 0x220 depth bounds @@ -1863,10 +1967,11 @@ const METHODS: [(usize, *const ()); 56] = [ (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch ]; /// The rest of [`METHODS`], kept apart only to stay readable. -const MORE_METHODS: [(usize, *const ()); 9] = [ +const MORE_METHODS: [(usize, *const ()); 10] = [ (28, query_mark as *const ()), // 0xe0 BeginQuery (29, query_mark as *const ()), // 0xe8 EndQuery (30, resolve_queries as *const ()), // 0xf0 + (31, set_predication as *const ()), // 0xf8 (78, dispatch_x as *const ()), // 0x270 (98, state::dispatch_mesh_x as *const ()), // 0x310 (99, driver_hint as *const ()), // 0x318 @@ -2563,4 +2668,262 @@ mod tests { assert_eq!(release(list), 0); assert_eq!(release(allocator), 0); } + + type SetPredication = extern "system" fn(This, This, u64, u32); + type Marker = extern "system" fn(This, u32, *const c_void, u32); + type EndEvent = extern "system" fn(This); + + #[test] + fn predication_and_marker_slots_are_stable() { + let predication: SetPredication = set_predication; + let marker: Marker = set_marker; + let begin: Marker = begin_event; + let end: EndEvent = end_event; + for table in [&LIST_FUNCTIONS, &NEWER_LIST_FUNCTIONS] { + let object = Object::new(table); + assert_eq!( + slot::(&object, 0xf8) as *const (), + predication as *const () + ); + assert_eq!( + slot::(&object, 0x1c0) as *const (), + marker as *const () + ); + assert_eq!( + slot::(&object, 0x1c8) as *const (), + begin as *const () + ); + assert_eq!( + slot::(&object, 0x1d0) as *const (), + end as *const () + ); + } + } + + #[cfg(windows)] + #[test] + fn set_predication_and_markers_execute_on_gpu() { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC, + }; + use windows::core::{IUnknown, Interface}; + + let Some(device) = crate::host::host() else { + assert!( + std::env::var_os("VICTORY_D3D12_WARP").is_none(), + "WARP unavailable" + ); + eprintln!("skipping predication readback: no host D3D12 device"); + return; + }; + let null = std::ptr::null(); + let (mut allocator, mut list, mut predicate) = (null, null, null); + assert_eq!( + create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), + S_OK + ); + assert_eq!( + create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), + S_OK + ); + let host = host_list(list).unwrap(); + let native = &host.list; + let buf = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let default_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + assert_eq!( + crate::resource::create_committed( + null, + (&raw const default_heap).cast(), + 0, + (&raw const buf).cast(), + 0, + null.cast(), + &PAGEABLE_IIDS[0], + &mut predicate, + ), + S_OK + ); + let (predicate_data, _) = crate::resource::buffer_bytes(predicate).unwrap(); + + let create = |heap, desc: &D3D12_RESOURCE_DESC, state| -> ID3D12Resource { + let properties = D3D12_HEAP_PROPERTIES { + Type: heap, + ..Default::default() + }; + let mut resource = None; + // SAFETY: valid resource and heap descriptions and an initialized out pointer. + unsafe { + device + .device + .CreateCommittedResource( + &properties, + D3D12_HEAP_FLAG_NONE, + desc, + state, + None, + &mut resource, + ) + .unwrap(); + } + resource.unwrap() + }; + let target_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..buf + }; + let target = create( + D3D12_HEAP_TYPE_DEFAULT, + &target_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + ); + let dest = create( + D3D12_HEAP_TYPE_DEFAULT, + &D3D12_RESOURCE_DESC { Width: 48, ..buf }, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let readback = create( + D3D12_HEAP_TYPE_READBACK, + &D3D12_RESOURCE_DESC { Width: 512, ..buf }, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let (upload, upload_data) = device.upload_buffer(80).unwrap(); + // SAFETY: the mapped upload has room for all three byte patterns. + unsafe { + upload_data.write_bytes(0x11, 48); + upload_data.add(48).write_bytes(0x22, 16); + upload_data.add(64).write_bytes(0x33, 16); + } + + let begin = slot::(list, 0x1c8); + let mark = slot::(list, 0x1c0); + let end = slot::(list, 0x1d0); + let predicate_at = slot::(list, 0xf8); + let label = b"predication test\0"; + begin(list, 1, label.as_ptr().cast(), label.len() as u32); + mark(list, 1, label.as_ptr().cast(), label.len() as u32); + end(list); + begin(list, 0, null.cast(), 1); + mark(list, 0, label.as_ptr().cast(), 0); + mark(list, 0, null.cast(), 0); + end(list); + + let rtv = device.rtv(Some(&target), None); + // SAFETY: the list is open and all resources outlive its execution. + // The texture copy locations borrow those resources without adding refs. + unsafe { + native.ClearRenderTargetView(rtv, &[1.0, 0.0, 0.0, 1.0], None); + native.CopyBufferRegion(&dest, 0, &upload, 0, 48); + + predicate_at(list, predicate, 0, 0); + predicate_at(list, predicate, 8, u32::MAX); + predicate_at(list, predicate, 1, 0); + native.CopyBufferRegion(&dest, 0, &upload, 48, 16); + predicate_at(list, predicate, 8, 0); + native.CopyBufferRegion(&dest, 16, &upload, 48, 16); + predicate_at(list, predicate, 8, 1); + predicate_at(list, null, 0, 0); + native.CopyBufferRegion(&dest, 32, &upload, 64, 16); + + native.ResourceBarrier(&[ + crate::host::transition( + &dest, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + ), + crate::host::transition( + &target, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + ), + ]); + native.CopyBufferRegion(&readback, 256, &dest, 0, 48); + native.CopyTextureRegion( + &D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Width: 1, + Height: 1, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }, + 0, + 0, + 0, + &D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&target), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }, + None, + ); + } + + // SAFETY: these two predicate values fit in the guest buffer. Write + // after recording so only a submission-time fill observes them. + unsafe { predicate_data.cast::<[u64; 2]>().write_unaligned([0, 1]) }; + host.close(); + device.execute(&[&host]); + // SAFETY: execution has finished and the readback contains 512 bytes. + unsafe { + device.device.GetDeviceRemovedReason().unwrap(); + let mut mapped = std::ptr::null_mut(); + readback + .Map( + 0, + Some(&D3D12_RANGE { Begin: 0, End: 304 }), + Some(&mut mapped), + ) + .unwrap(); + let bytes = std::slice::from_raw_parts(mapped.cast::(), 304); + assert_eq!(&bytes[..4], &[255, 0, 0, 255]); + assert_eq!(&bytes[256..272], &[0x11; 16], "zero skips the copy"); + assert_eq!(&bytes[272..288], &[0x22; 16], "one allows the copy"); + assert_eq!(&bytes[288..304], &[0x33; 16], "disabling allows the copy"); + readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + } + + fn release_native(object: impl Interface) -> u32 { + // SAFETY: all COM vtables begin with IUnknown. Release consumes the owned reference. + unsafe { (object.assume_vtable::().Release)(object.into_raw()) } + } + let native = native.clone(); + let release = |o: This| slot:: u32>(o, 0x10)(o); + assert_eq!(release(list), 0); + assert_eq!(release(allocator), 0); + assert_eq!(release(predicate), 0); + assert_eq!(release_native(native), 0); + for resource in [target, dest, readback, upload] { + assert_eq!(release_native(resource), 0); + } + } } From 0b8deb65e4b2aa61bba468f6a49422b563b4853e Mon Sep 17 00:00:00 2001 From: swarm Date: Tue, 24 Nov 2026 07:57:20 -0500 Subject: [PATCH 059/123] Saturate indirect workload budget with a shared reject path (cherry picked from commit 27f7e570d15216f59c5027bdd4ee5e40a237d3bc) --- crates/victory-gpu/src/indirect.rs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 357bb0341f..3af15e10bf 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -62,12 +62,26 @@ void main(uint3 id : SV_DispatchThreadID) { cost = g.x * g.y * g.z * 128; args.Store3(at, g); } + // Saturate the shared budget instead of allowing uint wraparound. + // All accesses to the counter are atomic; a rejected record must + // never reopen the budget for later records. uint before; - budget.InterlockedAdd(0, cost, before); - if (before >= BUDGET || before + cost > BUDGET) { - // Draws keep their layout with no vertices; groups become zero. - args.Store(at, 0); + budget.InterlockedAdd(0, 0u, before); + [allow_uav_condition] + while (true) { + if (before >= BUDGET) break; + uint remaining = BUDGET - before; + uint next = before + min(cost, remaining); + uint observed; + budget.InterlockedCompareExchange(0, before, next, observed); + if (observed == before) { + if (cost <= remaining) return; + break; + } + before = observed; } + // Draws keep their layout with no vertices; groups become zero. + args.Store(at, 0); } "#; From 824ab278a0abd7a0bdcca3ccc9857451ab7842b7 Mon Sep 17 00:00:00 2001 From: slaktarn Date: Tue, 24 Nov 2026 13:06:40 +0100 Subject: [PATCH 060/123] HLE: fail WSAConnectByList and GetAddrInfoExA where the host lacks them Wine's ws2_32 exports neither; a title calling them panicked in the host! lookup and aborted. The overrides now fail the call (WSAEOPNOTSUPP, or the name is not found), and the export test skips them where they are missing. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit d469fe9df918d5a058b1c919a361e3c43bcd4ab9) --- crates/victory-hle/src/modules/net.rs | 33 +++++++++++++++++++++------ 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/crates/victory-hle/src/modules/net.rs b/crates/victory-hle/src/modules/net.rs index 857b351c7e..deb80ccd8e 100644 --- a/crates/victory-hle/src/modules/net.rs +++ b/crates/victory-hle/src/modules/net.rs @@ -320,9 +320,18 @@ pub extern "system" fn WSAConnectByList( return 0; } } - host!("ws2_32.dll", "WSAConnectByList": extern "system" fn(Socket, *const u8, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( - s, list, local_len, local, remote_len, remote, timeout, reserved, - ) + type ConnectByList = extern "system" fn(Socket, *const u8, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32; + static ADDRESS: std::sync::OnceLock> = std::sync::OnceLock::new(); + // Wine's ws2_32 has no WSAConnectByList: fail the call as unsupported. + let Some(address) = *ADDRESS.get_or_init(|| crate::host::function("ws2_32.dll", "WSAConnectByList")) + else { + const WSAEOPNOTSUPP: i32 = 10045; + host!("ws2_32.dll", "WSASetLastError": extern "system" fn(i32))(WSAEOPNOTSUPP); + return 0; + }; + // SAFETY: the host exports this function with this signature. + let connect = unsafe { std::mem::transmute::(address) }; + connect(s, list, local_len, local, remote_len, remote, timeout, reserved) } pub extern "system" fn WSAJoinLeaf( @@ -580,9 +589,16 @@ pub extern "system" fn GetAddrInfoExA( if !resolvable(narrow(name)) { return WSAHOST_NOT_FOUND; } - host!("ws2_32.dll", "GetAddrInfoExA": extern "system" fn(*const c_char, *const c_char, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)( - name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle, - ) + type Resolve = extern "system" fn(*const c_char, *const c_char, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32; + static ADDRESS: std::sync::OnceLock> = std::sync::OnceLock::new(); + // Wine's ws2_32 has no GetAddrInfoExA: the name is not found. + let Some(address) = *ADDRESS.get_or_init(|| crate::host::function("ws2_32.dll", "GetAddrInfoExA")) + else { + return WSAHOST_NOT_FOUND; + }; + // SAFETY: the host exports this function with this signature. + let resolve = unsafe { std::mem::transmute::(address) }; + resolve(name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle) } pub extern "system" fn GetAddrInfoExW( @@ -1053,6 +1069,9 @@ mod tests { // Windows 10's winhttp.dll); the HLE supplies those itself, so skip // them only when the host really lacks them. const NEWER_WINDOWS_ONLY: &[&str] = &["WinHttpGetProxySettingsEx"]; + // Wine's ws2_32 lacks these; their overrides fail the call instead + // of forwarding it. + const MISSING_ON_WINE: &[&str] = &["WSAConnectByList", "GetAddrInfoExA"]; for e in m.exports.iter().filter(|e| !e.name.starts_with('#')) { let dll = if e.name.starts_with("WinHttp") { "winhttp.dll" @@ -1060,7 +1079,7 @@ mod tests { "ws2_32.dll" }; let present = crate::host::function(dll, e.name).is_some(); - if !present && NEWER_WINDOWS_ONLY.contains(&e.name) { + if !present && (NEWER_WINDOWS_ONLY.contains(&e.name) || MISSING_ON_WINE.contains(&e.name)) { continue; } assert!(present, "{dll} lacks {}", e.name); From 83d578aa087685193913a9371d8134565bc70923 Mon Sep 17 00:00:00 2001 From: slaktarn Date: Tue, 24 Nov 2026 13:06:40 +0100 Subject: [PATCH 061/123] Shaders: one returning block per program Every s_endpgm (and the loop-limit abort) now branches to one shared ret block, as DXC's output always has. A loop left by both a break and a return could not be structured by dxil-spirv (vkd3d-proton): it emitted invalid SPIR-V ("exits the loop ... but not via a structured exit"), on which RADV segfaulted in vkCreateGraphicsPipelines (exit code 3). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 45aceea178d5ad325effa16765f3965801ab7c3e) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 366d10e3e1..cb23599a82 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -265,6 +265,10 @@ struct Lower<'a> { wave64_refused: bool, /// Guarded code being lowered ([`Lower::begin_guarded`] depth). guard_depth: u32, + /// The one block that returns: every end of the program branches to it, + /// so the function has a single exit as DXC emits it (dxil-spirv, under + /// Proton, cannot structure a loop left by both a break and a return). + ret: Option, } /// The console's 64-lane wave as one thread group on a host whose waves @@ -714,6 +718,7 @@ impl<'a> Lower<'a> { emulated, wave64_refused, guard_depth: 0, + ret: None, } } @@ -8091,7 +8096,7 @@ impl<'a> Lower<'a> { self.s .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); } - Term::Ret + Term::Br(self.ret_block()) } LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")), }; @@ -8137,11 +8142,23 @@ impl<'a> Lower<'a> { self.s .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); } - self.s.m.terminate(a, Term::Ret); + let r = self.ret_block(); + self.s.m.terminate(a, Term::Br(r)); self.abort = Some(a); a } + /// The function's single returning block (see `ret`). + fn ret_block(&mut self) -> usize { + if let Some(r) = self.ret { + return r; + } + let r = self.s.m.new_block(); + self.s.m.terminate(r, Term::Ret); + self.ret = Some(r); + r + } + /// The DXIL block a branch from IR block `from` to `to` goes to. fn edge(&mut self, from: usize, to: usize) -> usize { let target = self.block[to].expect("reachable"); From 5785b6df6b19858ed0a3994ed7b79d9659aee36f Mon Sep 17 00:00:00 2001 From: slaktarn Date: Tue, 24 Nov 2026 13:06:58 +0100 Subject: [PATCH 062/123] GPU: mirror heap slots the title writes into its own memory Grand Theft Auto VI places its descriptor heaps in its own memory and copies whole slots there itself; no create or copy call reports those writes, so the host slot kept what it was mirrored from before. Slots a shader reads directly by index (not through a table) are only made from what was mirrored: in the world a mesh shader read a slot as a constant buffer while the host slot still held a texture view, whose upper half it took for a buffer at address 0 (a GPU page fault and a lost device; likely the "world's low-address page faults" noted at null_view). Before each submission, the 64 KiB blocks of every shader-visible heap written since the last one (watch::writes) are mirrored again; mirror() skips slots whose record did not change. Found with umr wave dumps under Proton (RX 9070 XT): the faulting waves held s[8:11] = {0, 0x00400000, 0x00248000, 0}, the second half of an image descriptor, loaded from heap slot ~1,061,522. Before, the world lost the device after 5-90 s; with this, 90 s, then a different fault (next commit). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 6f732b6c1cbc66ffef44897c6db12a7af9aac867) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/descriptor.rs | 50 ++++++++++++++++++++++++++++ crates/victory-gpu/src/queue.rs | 1 + 2 files changed, 51 insertions(+) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index a922864331..039dab596b 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -59,6 +59,11 @@ pub(crate) struct Heap { host: std::sync::OnceLock>, #[cfg(windows)] pending: std::sync::Mutex>, + /// The write-watch asking (see [`crate::watch::writes`]) up to which + /// the host heap has caught up with what the title wrote into its + /// memory itself (see [`resync_title_writes`]). + #[cfg(windows)] + synced: std::sync::atomic::AtomicU64, } pub(crate) fn heap<'a>(this: This) -> &'a Heap { @@ -148,6 +153,49 @@ fn mirror(handle: u64) { } } +/// Brings the host heaps up to date with descriptors the title wrote into +/// heap memory itself (copies of whole slots, which no create or copy call +/// reports), before a submission runs: slots read directly by index (not +/// through a table) are made only from what was mirrored, so a slot the +/// title turned from a texture into a constant buffer kept the texture, +/// whose upper half the shader read as a buffer at address 0: a GPU page +/// fault and a lost device in the world. Only the 64 KiB blocks written +/// since the last call are looked at; heaps in memory the kernel does not +/// watch (ours, not the title's) are left as they are. +#[cfg(windows)] +pub(crate) fn resync_title_writes() { + use std::sync::atomic::Ordering::Relaxed; + // Held throughout: registered heaps stay alive while it is. + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + for &(start, end, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + let (Some(Some(host)), Some(step)) = (heap.host.get(), increment(heap.desc.kind)) else { + continue; // no host heap yet: its first use mirrors everything + }; + let page = crate::watch::PAGE as u64; + let (first, last) = (start / page * page, end.div_ceil(page) * page); + let Some((now, written)) = crate::watch::writes(first as usize, last as usize, true) else { + continue; + }; + let before = heap.synced.swap(now, Relaxed); + let step = u64::from(step); + for (p, asked) in written { + if asked <= before { + continue; + } + let from = (p as u64 * page).max(start); + let to = ((p as u64 + 1) * page).min(end); + for i in (from - start) / step..(to - start).div_ceil(step) { + let i = i as u32; + if i < heap.desc.count { + host.mirror(i, start + u64::from(i) * step, false); + } + } + } + } +} + /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] @@ -624,6 +672,8 @@ pub(crate) extern "system" fn create_heap( host: std::sync::OnceLock::new(), #[cfg(windows)] pending: Default::default(), + #[cfg(windows)] + synced: std::sync::atomic::AtomicU64::new(0), }); #[cfg(windows)] if visible { diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 1d3d2b5b17..76820b07ba 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -126,6 +126,7 @@ extern "system" fn execute(this: This, count: u32, lists: *const This) { } #[cfg(windows)] if crate::host::host().is_some() { + crate::descriptor::resync_title_writes(); // SAFETY: the title passes `count` lists. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; // Held until they run: the title may reset its lists before. From 1b03a428ad2b66bd5718610cb020a108edeb91ec Mon Sep 17 00:00:00 2001 From: slaktarn Date: Tue, 24 Nov 2026 13:06:58 +0100 Subject: [PATCH 063/123] GPU: bind root SRVs as bounded one-view tables A root SRV is a raw address the GPU reads without bounds. The console's reads past the title buffer land in other title memory; ours past its host copy land in unmapped memory: in the world a compute shader read 32 MB past a root SRV's copy (umr: TCP fault at s[10:11] + 0x1f0e000) and the device was lost. Root SRVs (ByteAddressBuffer t in ROOT_CBV_SPACE) are now a table of one raw view sized to the rest of the host copy, in a dynamic slot of the bound view heap, reused within a list for the same address. Reads past the copy return zeros. The shaders' bindings do not change. With this and the previous commit, the world runs without a device loss for as long as tested (8 minutes, twice, under Proton). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit c69bd9af0c14bd694e1a23113d3a6e6214a7f4da) --- crates/victory-gpu/src/descriptor/host.rs | 33 ++++++++++ crates/victory-gpu/src/draw.rs | 73 +++++++++++++++++++++++ crates/victory-gpu/src/pipeline/host.rs | 33 ++++++++++ 3 files changed, 139 insertions(+) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 92e839e11a..6edf927ae0 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -468,6 +468,39 @@ impl HostHeap { } } + /// The shader-visible handle of slot `index`. + pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE { + // SAFETY: a live shader-visible heap. + let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr }; + D3D12_GPU_DESCRIPTOR_HANDLE { ptr: start + u64::from(index) * u64::from(self.step) } + } + + /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes + /// of `buffer` from byte `offset` (4-byte units, rounded down), holding + /// the buffer while the slot does. + pub(crate) fn raw_srv_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { + let Some(host) = host() else { return }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: offset / 4, + NumElements: (len / 4).clamp(1, u64::from(u32::MAX)) as u32, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + // SAFETY: a live buffer and a slot of our heap; the range lies in it. + unsafe { + host.device + .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index)) + }; + self.keep(index, Some(buffer.clone())); + } + /// Makes slot `index` (a dynamic one) a constant buffer view of host /// memory (the list's own, which it holds). pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e62161a1eb..3740473d34 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -94,6 +94,9 @@ pub(crate) struct State { /// Tables made afresh in this list: (table, what it holds) → first /// dynamic slot. fresh_tables: std::collections::HashMap<(u64, u64), u32>, + /// Root SRV views made in this list: (title heap, title address) → + /// dynamic slot (see [`State::bind_root_srv`]). + root_srv_slots: std::collections::HashMap<(usize, u64), u32>, /// The dynamic slots the list holds: title heap, first, count; given /// back when the list is reset or released. dynamic: Vec<(usize, u32, u32)>, @@ -616,6 +619,12 @@ impl State { } for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { for &(slot, param) in views { + // Root SRVs are bounded one-view tables (see the host + // root signature). + if srv { + self.bind_root_srv(list, compute, slot, param); + continue; + } let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { once!(slot, "a shader reads a root view the title did not set"); @@ -638,6 +647,70 @@ impl State { } } + /// Binds the title's root SRV `slot` as the one-view table `param` (see + /// the host root signature): a raw view of the rest of the title + /// buffer's host copy, in a dynamic slot of the bound view heap, so + /// reads past the copy return zeros rather than fault. Zeros (our null + /// buffer) if the title set none or it lies outside every buffer. + fn bind_root_srv(&mut self, list: &HostList, compute: bool, slot: u8, param: u32) { + let l = &list.list; + let heap = self.heaps[0]; + if heap == 0 { + once!("a root SRV with no view heap bound: left unset"); + return; + } + let title_heap = crate::descriptor::heap(heap as This); + let Some(host) = title_heap.host() else { return }; + let address = match self.roots_ref(compute).get(usize::from(slot)) { + Some(Root::View(address)) => *address, + _ => 0, + }; + let shadow = crate::shadow::find(address, 1).filter(|_| address != 0).map(|s| (s, address)); + // The same buffer again in this list: its slot, refreshed again. + if let Some(&index) = self.root_srv_slots.get(&(heap, address)) { + if let Some((shadow, address)) = &shadow { + shadow.refresh(list, *address, shadow.left(*address).min(1 << 20)); + } + let table = host.gpu_handle(index); + // SAFETY: an open list; the slot is held by this list. + unsafe { + if compute { + l.SetComputeRootDescriptorTable(param, table); + } else { + l.SetGraphicsRootDescriptorTable(param, table); + } + } + return; + } + let Some(index) = host.dynamic(1) else { + once!("no free dynamic slot for a root SRV: left unset"); + return; + }; + self.dynamic.push((heap, index, 1)); + self.root_srv_slots.insert((heap, address), index); + match shadow { + Some((shadow, address)) => { + let len = shadow.left(address); + shadow.refresh(list, address, len.min(1 << 20)); + host.raw_srv_at(index, &shadow.buffer, shadow.offset(address), len); + } + None => { + once!(slot, "a root SRV the title did not set, or outside every buffer: reads zeros"); + host.make_null(index); + } + } + let table = host.gpu_handle(index); + // SAFETY: an open list; the slot is in the bound heap and held by + // this list until it is reset. + unsafe { + if compute { + l.SetComputeRootDescriptorTable(param, table); + } else { + l.SetGraphicsRootDescriptorTable(param, table); + } + } + } + /// Runs a dispatch on the host. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 88fb2a7bdf..a1c01d4c2c 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -338,6 +338,9 @@ impl HostPipeline { // The root signature the translated shaders' bindings define. let mut params: Vec = Vec::new(); + // Root SRVs are bound as one-view tables (see below); their ranges + // must outlive the serialisation, so each is boxed here. + let mut ranges: Vec> = Vec::new(); let mut samplers = Vec::new(); let mut bound = Vec::new(); for &(shader, visibility) in &stages { @@ -377,6 +380,36 @@ impl HostPipeline { ] { for &slot in slots { out.push((slot, params.len() as u32)); + // A root SRV is a raw address the GPU reads without + // bounds: the console's reads past the title buffer + // land in other title memory, ours past its host copy + // in unmapped memory (a GPU page fault and a lost + // device in the world). A table of one raw view sized + // to the copy reads zeros there instead; the shader's + // binding (`t`, a ByteAddressBuffer) is the same. + if kind == D3D12_ROOT_PARAMETER_TYPE_SRV { + ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE + | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, + OffsetInDescriptorsFromTableStart: 0, + })); + let range: &D3D12_DESCRIPTOR_RANGE1 = ranges.last().expect("just pushed"); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { + NumDescriptorRanges: 1, + pDescriptorRanges: range, + }, + }, + ShaderVisibility: visibility, + }); + continue; + } params.push(D3D12_ROOT_PARAMETER1 { ParameterType: kind, Anonymous: D3D12_ROOT_PARAMETER1_0 { From 17fe4d53ca9a99a6e10c681ace95a467d767a8d6 Mon Sep 17 00:00:00 2001 From: slaktarn Date: Tue, 24 Nov 2026 13:06:58 +0100 Subject: [PATCH 064/123] Watch: ask the kernel once per range per submission under Wine Wine emulates write watching page by page under one lock (about 1 ms an asking), and the world's copies ask about the same big buffers dozens of times per submission: 3,500 askings and 17 GB checked per frame, 3 s of a frame. Under Wine, a range the kernel already answered for in this submission is now answered from the journal; a write in between keeps its dirty bit and shows in the next submission. Windows is unchanged. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 4f9aa10c88a867e1cfd80fb55438ce839d1c1cfb) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/queue.rs | 1 + crates/victory-gpu/src/watch.rs | 68 +++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 76820b07ba..392620d94f 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -126,6 +126,7 @@ extern "system" fn execute(this: This, count: u32, lists: *const This) { } #[cfg(windows)] if crate::host::host().is_some() { + crate::watch::new_submission(); crate::descriptor::resync_title_writes(); // SAFETY: the title passes `count` lists. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 19ee5daf1e..b44d0e7e74 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -35,14 +35,44 @@ struct Journal { written: BTreeMap, /// Room for the kernel's answer. found: Vec, + /// Page ranges the kernel was asked about since the submission began + /// (see [`new_submission`]); under Wine only. + asked_now: Vec<(usize, usize)>, } static JOURNAL: Mutex = Mutex::new(Journal { asked: 0, written: BTreeMap::new(), found: Vec::new(), + asked_now: Vec::new(), }); +/// Whether we run under Wine (its ntdll exports `wine_get_version`). +fn on_wine() -> bool { + static WINE: std::sync::LazyLock = std::sync::LazyLock::new(|| { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + // SAFETY: plain lookups in ntdll, always loaded. + unsafe { + let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); + !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() + } + }); + *WINE +} + +/// A submission begins: memory asked about from now on is asked of the +/// kernel again. Within one submission, a range the kernel already +/// answered for is answered from the journal: Wine emulates write watching +/// page by page under one lock (about 1 ms an asking), and the world's +/// copies ask about the same big buffers dozens of times per submission +/// (17 GB checked per frame, 3 s of a frame). A write between two askings +/// in one submission keeps its dirty bit, so the next submission sees it. +pub(crate) fn new_submission() { + if on_wine() { + JOURNAL.lock().unwrap_or_else(|e| e.into_inner()).asked_now.clear(); + } +} + /// The pages of `[start, end)` (whole pages) as last written, for pages /// written since tracking began: `(page number, asking)` in page order, and /// this asking's number, which is higher than any in the list but those the @@ -54,6 +84,13 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let (first, last) = (start / PAGE, end.div_ceil(PAGE)); let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); let j = &mut *j; + if on_wine() && j.asked_now.iter().any(|&(f, l)| f <= first && last <= l) { + j.asked += 1; + return Some(( + j.asked, + j.written.range(first..last).map(|(&p, &w)| (p, w)).collect(), + )); + } let mut count = (last - first) * PAGE / KERNEL_PAGE; j.found.resize(count.max(j.found.len()), 0); let mut granularity = 0; @@ -78,6 +115,9 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve None => guard(first * PAGE, last * PAGE)?, } } else { + if on_wine() && j.asked_now.len() < 4096 { + j.asked_now.push((first, last)); + } Vec::new() }; #[cfg(feature = "diagnostics")] @@ -444,6 +484,8 @@ mod tests { assert!(before.is_empty()); // SAFETY: committed pages of ours. unsafe { ((p + PAGE + 8) as *mut u8).write(1) }; + // Under Wine a range is asked of the kernel once per submission. + new_submission(); let (now, after) = writes(start, end, false).expect("watched"); assert_eq!(after, [(p / PAGE + 1, now)]); // Another asker after the kernel's bit was cleared still sees it. @@ -537,6 +579,32 @@ mod tests { // the same addresses would find them written. } + /// Under Wine, a write after a range was asked about in a submission + /// is reported in the next one, not lost. + #[test] + fn writes_within_a_submission_show_in_the_next() { + if !on_wine() { + return; + } + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert_ne!(p, 0); + // Kept, not freed: another test given this address would see the + // journal's entries for it. The journal may already hold some (a + // freed allocation of another test here), so compare with them. + new_submission(); + let (_, before) = writes(p, p + 2 * PAGE, false).expect("watched"); + // SAFETY: committed pages of ours. + unsafe { ((p + 8) as *mut u8).write(1) }; + let (_, same) = writes(p, p + 2 * PAGE, false).expect("watched"); + assert_eq!(same, before, "answered from the journal within the submission"); + new_submission(); + let (now, next) = writes(p, p + 2 * PAGE, false).expect("watched"); + assert!(next.contains(&(p / PAGE, now)), "the write shows in the next submission"); + } + /// A kernel read into a guarded view block fails; opened first, it /// lands and the block counts as written. #[test] From a9eeebac0dfb4baea44ca7f8d2c3053cce770d4b Mon Sep 17 00:00:00 2001 From: slaktarn Date: Tue, 24 Nov 2026 13:06:40 +0100 Subject: [PATCH 065/123] Shader tests: skip the DXIL hash refusal check under Wine vkd3d-proton does not check DXIL container hashes, so pipelines with a zero or wrong digest are accepted there; the rest of the test still runs. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 4782660af613c779988b6b5aa7cb092598c2d715) --- crates/victory-shader/src/emit/mod.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 53387f8191..2b4f522e08 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -646,6 +646,16 @@ mod tests { v.validate(&mut vs.dxil.clone()).unwrap(); } host.pipeline(&vs, &ps).unwrap(); + // vkd3d-proton (Wine, Proton) does not check the container hash. + // SAFETY: plain lookups in ntdll, always loaded. + let wine = unsafe { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); + !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() + }; + if wine { + return; + } // The runtime checks the container hash: no hash or a wrong one is // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass // value; ours works with older ones too.) From d11c2499d9a188b6849c39cced0d1167a6b5d6e4 Mon Sep 17 00:00:00 2001 From: Victory Dev Date: Tue, 24 Nov 2026 00:58:32 -0400 Subject: [PATCH 066/123] shader: give unwritten VGPR/SGPR reads a zero-valued input ir::build assigns SSA values in reverse-postorder; a register with no reaching definition could leak NONE (Value(u32::MAX)) into the emitter as 'a value defined after its use'. Leonida keeps all registers in zero- initialized Function arrays, so an unwritten register reads zero. When a read has no reaching definition, mint a zero-valued entry input for it. Same semantics VIctory already uses for program inputs (lower.rs:917,924), applied at the source so all IR consumers see a real Value. (cherry picked from commit 8d811770e7c5081e0380ed832c4cd34c4f755d38) --- crates/victory-shader/src/ir.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 5b77e77068..9d3e65ded1 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -407,8 +407,17 @@ fn rename(mut blocks: Vec, wave64: bool, vgprs: u16) -> Program { } for inst in &mut block.insts { for (reg, v) in &mut inst.reads { - *v = current[index(*reg)]; - debug_assert_ne!(*v, NONE, "{reg:?} read at {:#x}", inst.machine.offset); + let mut value = current[index(*reg)]; + if value == NONE { + // No reaching definition: the hardware's registers start + // at zero (Leonida tools/rdna2spirv.py:15973). Give the + // read a zero-valued entry input instead of leaking NONE + // into the emitter as "a value defined after its use". + value = new_value(); + inputs.push((*reg, value)); + current[index(*reg)] = value; + } + *v = value; } for (reg, v) in &mut inst.writes { *v = new_value(); From 1aad9e58c38a57dc79a4b186f53006c96f6d45c7 Mon Sep 17 00:00:00 2001 From: Victory Dev Date: Tue, 24 Nov 2026 07:40:15 -0400 Subject: [PATCH 067/123] gpu: VICTORY_DUMP_SHADERS writes each translated shader's DXIL to a directory Diagnostics builds only. Without it the emitted DXIL of a shader named in a device-removal or slow-list report (for example the mesh shaders that exceed the ~2 s TDR on NVIDIA) could only be reproduced with the offline translate command and a cache lookup by an unrelated key. The files are named - with the same hash the logs use, and read with 'dxc -dumpbin'. No behaviour change when the variable is unset. Co-Authored-By: Claude Sonnet 5.5 (cherry picked from commit 84a0127f8d4ae992c2e9d9f99414b6b9a6d56a67) --- crates/victory-gpu/src/pipeline.rs | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index bb7b4956ba..7ca4dd9988 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -109,13 +109,25 @@ impl Shader { .get_or_init(|| { let done = translate(&self.container); match &done { - Ok(t) => tracing::info!( - stage = self.stage, - hash = %self.hash, - user_data = t.host.user_data.len(), - samplers = t.host.samplers.len(), - "shader translated" - ), + Ok(t) => { + // `VICTORY_DUMP_SHADERS=`: the emitted DXIL, to read + // with a disassembler (`dxc -dumpbin`). + #[cfg(feature = "diagnostics")] + if let Some(dir) = std::env::var_os("VICTORY_DUMP_SHADERS") { + let file = std::path::Path::new(&dir) + .join(format!("{}-{}.dxil", self.stage, self.hash)); + if let Err(e) = std::fs::write(&file, &t.host.dxil) { + tracing::warn!(error = %e, file = %file.display(), "shader not dumped"); + } + } + tracing::info!( + stage = self.stage, + hash = %self.hash, + user_data = t.host.user_data.len(), + samplers = t.host.samplers.len(), + "shader translated" + ) + } Err(e) => tracing::warn!( stage = self.stage, hash = %self.hash, From 5737773f5a87a53133a3ae3aa89888e705cffcc0 Mon Sep 17 00:00:00 2001 From: lucaseddd <217490109+lucaseddd@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:41:44 -0300 Subject: [PATCH 068/123] GPU diagnostics: identify shader stages and direct root arguments in draw traces (cherry picked from commit b70fa03e02f6860a4f5dd2f026a73b3f358ca99d) --- crates/victory-gpu/src/draw.rs | 43 ++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 3740473d34..6e838e179f 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1023,11 +1023,12 @@ impl State { let handle = table + u64::from(u.table_offset_dwords) * 4; describe(crate::descriptor::view(handle).as_ref()) } + (RootType::Descriptor, bound) => describe_root_view(bound), (root, _) => format!("{root:?}"), }; out.push(format!( - "{} {:?} s{}+{}: {what}", - stage.shader.hash, u.kind, u.slot, u.table_offset_dwords + "{} {} {:?} s{}+{}: {what}", + stage.shader.stage, stage.shader.hash, u.kind, u.slot, u.table_offset_dwords )); } } @@ -1506,6 +1507,44 @@ fn describe(view: Option<&View>) -> String { } } +/// Reports the guest argument before host binding. +#[cfg(feature = "diagnostics")] +fn describe_root_view(bound: Option<&Root>) -> String { + match bound { + Some(Root::View(address)) => format!("Descriptor(guest address {address:#x})"), + Some(Root::Table(_)) => "Descriptor(table supplied)".into(), + Some(Root::Constants(_)) => "Descriptor(constants supplied)".into(), + Some(Root::None) | None => "Descriptor(unset)".into(), + } +} + +#[cfg(all(test, feature = "diagnostics"))] +mod trace_tests { + use super::*; + + #[test] + fn root_view_trace_distinguishes_zero_unset_and_wrong_argument_kinds() { + assert_eq!(describe_root_view(None), "Descriptor(unset)"); + assert_eq!(describe_root_view(Some(&Root::None)), "Descriptor(unset)"); + assert_eq!( + describe_root_view(Some(&Root::View(0))), + "Descriptor(guest address 0x0)" + ); + assert_eq!( + describe_root_view(Some(&Root::View(42))), + "Descriptor(guest address 0x2a)" + ); + assert_eq!( + describe_root_view(Some(&Root::Table(42))), + "Descriptor(table supplied)" + ); + assert_eq!( + describe_root_view(Some(&Root::Constants(vec![42]))), + "Descriptor(constants supplied)" + ); + } +} + /// The console's own primitive topologies. const TRIANGLE_FAN: u32 = 6; const RECTANGLES: u32 = 17; From e62e645696235292d1025bfa27928681200b5ddc Mon Sep 17 00:00:00 2001 From: Xvania7 <281555600+Xvania7@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:37:48 +0200 Subject: [PATCH 069/123] gpu: normalize mip levels for auto-sized textures in GetDesc (fixes #773) (cherry picked from commit 3eafeafe11ec929eb61842e618afa39b312ac4ec) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/resource.rs | 103 ++++++++++++++++++++++++++++- 1 file changed, 101 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 1d89c498d1..5f3a300b5e 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1029,7 +1029,7 @@ fn resource<'a>(this: This) -> &'a Resource { // The creation methods' own arguments, passed on. #[allow(clippy::too_many_arguments)] fn hand_out_resource( - desc: ResourceDesc, + mut desc: ResourceDesc, heap: HeapProperties, heap_flags: u32, backing: Backing, @@ -1038,6 +1038,9 @@ fn hand_out_resource( iid: *const Iid, out: *mut This, ) -> HRESULT { + if desc.dimension != BUFFER && desc.mip_levels == 0 { + desc.mip_levels = mip_count(&desc) as u16; + } #[cfg(not(windows))] let _ = (state, clear); // The clear value is the caller's only during the call. @@ -1367,8 +1370,12 @@ extern "system" fn map(this: This, _sub: u32, _read: *const c_void, out: *mut *m extern "system" fn unmap(_: This, _sub: u32, _written: *const c_void) {} extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) { if !out.is_null() { + let mut desc = resource(this).desc; + if desc.dimension != BUFFER && desc.mip_levels == 0 { + desc.mip_levels = mip_count(&desc) as u16; + } // SAFETY: checked non-null; the title passes room for a description. - unsafe { out.write(resource(this).desc) }; + unsafe { out.write(desc) }; } } /// Device method `GetCustomHeapProperties`, returning its struct through a @@ -2593,4 +2600,96 @@ void main() { assert_eq!(slot::(out, 0x10)(out), 0); } } + + #[test] + fn auto_size_textures_normalize_mip_levels_in_get_desc() { + let null = std::ptr::null(); + let get_desc = |desc: &ResourceDesc| -> ResourceDesc { + let mut res = null; + let hr = create_committed( + null, + &PROPERTIES, + 0, + desc, + 0, + null.cast(), + &RESOURCE_IIDS[0], + &mut res, + ); + assert_eq!(hr, S_OK); + let mut out = std::mem::MaybeUninit::::uninit(); + slot::(res, 0x50)(res, out.as_mut_ptr()); + assert_eq!(slot::(res, 0x10)(res), 0); + // SAFETY: initialized by resource_desc. + unsafe { out.assume_init() } + }; + + // 4x4 2D texture with auto mips (0) -> 3 mips (4x4, 2x2, 1x1) + let t2d = ResourceDesc { + dimension: 3, + width: 4, + height: 4, + depth_or_array_size: 1, + mip_levels: 0, + format: 28, // DXGI_FORMAT_R8G8B8A8_UNORM + layout: 0, + ..buffer(0) + }; + assert_eq!(get_desc(&t2d).mip_levels, 3); + + // 2D texture array (e.g. 6 slices) with auto mips (0) -> array size does not inflate mips + let t2d_array = ResourceDesc { + dimension: 3, + width: 4, + height: 4, + depth_or_array_size: 6, + mip_levels: 0, + format: 28, + layout: 0, + ..buffer(0) + }; + assert_eq!(get_desc(&t2d_array).mip_levels, 3); + + // Explicit 2-mip control -> stays 2 + let t2d_explicit = ResourceDesc { + dimension: 3, + width: 4, + height: 4, + depth_or_array_size: 1, + mip_levels: 2, + format: 28, + layout: 0, + ..buffer(0) + }; + assert_eq!(get_desc(&t2d_explicit).mip_levels, 2); + + // 1D texture with auto mips (0) -> 256 gives 9 mips + let t1d = ResourceDesc { + dimension: 2, + width: 256, + height: 1, + depth_or_array_size: 1, + mip_levels: 0, + format: 28, + layout: 0, + ..buffer(0) + }; + assert_eq!(get_desc(&t1d).mip_levels, 9); + + // 3D volume texture with auto mips (0) -> 16x8x32 gives 6 mips (max dimension 32) + let t3d = ResourceDesc { + dimension: 4, + width: 16, + height: 8, + depth_or_array_size: 32, + mip_levels: 0, + format: 28, + layout: 0, + ..buffer(0) + }; + assert_eq!(get_desc(&t3d).mip_levels, 6); + + // Ordinary buffer -> stays 1 mip + assert_eq!(get_desc(&buffer(256)).mip_levels, 1); + } } From 09f6f3f43cf2870a5f5114a9c4e15771d056bd48 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:23:22 +0000 Subject: [PATCH 070/123] GPU: say once when a present has several planes PresentX can put a UI plane over a scene plane (a fork reports Series S presenting a 1080p scene under a 4K UI); we show the first plane only. A warning, once, tells from a log whether a title needs the planes composited (MichaelSmithAI's 24a387d7 composites them; not ported until a log shows the need). Only the count is read: the plane stride is not confirmed, so later planes are not looked at. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/queue.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 392620d94f..6a1868eb79 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -291,6 +291,15 @@ extern "system" fn present( ) -> HRESULT { // Read now: the parameters are the title's, maybe on its stack. The // frame is shown in the queue's order, after the work before it. + if planes > 1 { + // A console can put a UI plane over a scene plane (Series S: a + // 1080p scene under a 4K UI); only the first is shown here. Once, + // so a run shows whether a title needs the planes composited. + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(planes, "a present with several planes: only the first is shown"); + }); + } let plane = if planes > 0 { // SAFETY: the title passes `planes` plane descriptions. unsafe { plane_parameters.as_ref() } From 89b72102dba6e64e14f903eda0984897b921564f Mon Sep 17 00:00:00 2001 From: LF2000 Builder Date: Tue, 24 Nov 2026 00:37:23 -0500 Subject: [PATCH 071/123] BCPack: read BC7 dictionary indices from the right offset Each BC7 dictionary entry has two more bytes after the two index widths. They repeat the widths in all entries but the first. The parser read them as pixel 0 of set 0, so every index was off by one: pixel 0 was 4 in 253 of 255 entries, and set 0's last pixel landed in set 1, which no entry uses. Any BC7 block whose index reference points into the dictionary was built on the wrong indices. Skip the two bytes and read 16 indices for set 0 and 15 for set 1. The table size does not change. The new test checks the shipped table: a set with 0 bits holds no indices, and pixel 0 is a valid anchor. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 0ecaa8cb92ac86e9721f9a0870788fe326b645bd) --- crates/victory-formats/src/bcpack.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs index 360dce12d5..c8d35378df 100644 --- a/crates/victory-formats/src/bcpack.rs +++ b/crates/victory-formats/src/bcpack.rs @@ -129,8 +129,8 @@ impl Tables { /// alpha 64 B and colour 256 B, BC4 64 B, BC5 64 B), 512 u16 BC7 control /// words, then 255 dictionary entries per format in format order: BC1 /// 6 + 16 B, BC3 8 + 32 B, BC4 2 + 16 B, BC5 4 + 32 B, BC6H (u8 mode, - /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 32 i16). - /// Little-endian, no padding. Every model must tile 65536. + /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 2 B, + /// 16 + 15 i16). Little-endian, no padding. Every model must tile 65536. pub fn parse(bytes: &[u8]) -> Result { if bytes.len() != TABLES_SIZE { return Err(Error("table file has the wrong size")); @@ -222,7 +222,10 @@ impl Tables { bits: [r.u8(), r.u8()], ..Default::default() }; - for v in ix.ix.as_flattened_mut() { + // Unused: the widths again in all entries but the first. + r.u16(); + // Only 15 slots for set 1, which no entry uses (0 bits). + for v in &mut ix.ix.as_flattened_mut()[..31] { *v = r.u16() as i16; } (ep, ix) @@ -1590,4 +1593,16 @@ mod tests { } assert!(n > 0); } + + /// A dictionary entry stands in for a block the decoder made: a set with + /// 0 index bits holds no indices, and pixel 0 is the anchor (top bit clear). + #[test] + fn bc7_dictionary_indices_line_up() { + let t = Tables::builtin().unwrap(); + for (k, (_, ix)) in t.bc7.iter().enumerate() { + let anchor = 0..1 << (ix.bits[0] - 1); + let ok = (ix.bits[1] != 0 || ix.ix[1] == [0; 16]) && anchor.contains(&ix.ix[0][0]); + assert!(ok, "entry {k}: {:?}", ix.ix); + } + } } From f4325b412461d8ad2cca7b03b26ecf0d761cef9c Mon Sep 17 00:00:00 2001 From: LF2000 Builder Date: Tue, 24 Nov 2026 00:40:54 -0500 Subject: [PATCH 072/123] Shaders: refuse per-lane reads of mesh v5 in v5 writes and after joins The mesh guard let any instruction that writes v5 read the group input, because a VGPR write also reads its old value. That also let through instructions that take v5 as a real operand, such as v_add_nc_u32 v5, v5, v1 or global_load_dword v5, v5, s[0:1]. It also only checked the input value itself, so v_mov_b32 v1, v5 after a join where one path kept v5 passed. Lowering then gave every lane the first lane's value. The IR now adds the old-value read in build, so ir::operand_reads can return an instruction's operand reads. The guard exempts a write to v5 only when v5 is not one of its operands, and follows the group input through phis. It skips phi arguments from the EXEC-zero edge of s_cbranch_execz or s_cbranch_execnz. No lane runs there, so that is the same case as a partial-EXEC write, and a divergent if that reuses v5 after v_readfirstlane_b32 stays accepted. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 98fe8fe840bab7ad086c8126ea9d5dd856fb2e89) --- crates/victory-shader/src/io.rs | 84 +++++++++++++++++++++++++++++++-- crates/victory-shader/src/ir.rs | 20 ++++++-- 2 files changed, 96 insertions(+), 8 deletions(-) diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index f535132a0d..9ed00ce969 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -35,7 +35,7 @@ use std::collections::HashMap; use crate::ShaderError; use crate::gfx10::{Fields, Operand}; -use crate::ir::{Inst, Program, Reg, Value}; +use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads}; use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage}; use crate::resource::Site; @@ -240,13 +240,52 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { (loaded, &[][..], &[][..]) } (StageIo::Ms(ms), HwStage::Ms) => { - let group = p.inputs.iter().find(|i| i.0 == Reg::V(5)).map(|i| i.1); + // The group input, and the phis that may carry it past a join. + let mut group: Vec = p + .inputs + .iter() + .filter(|i| i.0 == Reg::V(5)) + .map(|i| i.1) + .collect(); + // No lane is active over the EXEC-zero edge of s_cbranch_execz or + // _execnz, the same case as a partial-EXEC write below. + let no_lanes = |q: usize, b: usize| match ( + p.blocks[q].insts.last().map(Inst::name), + p.blocks[q].exit, + ) { + (Some("s_cbranch_execz"), Exit::Branch { taken, not_taken }) => { + taken == b && not_taken != b + } + (Some("s_cbranch_execnz"), Exit::Branch { taken, not_taken }) => { + not_taken == b && taken != b + } + _ => false, + }; + while let Some(v) = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, k)| k.phis.iter().map(move |f| (b, f))) + .find_map(|(b, f)| { + let mut args = f.args.iter().zip(&p.blocks[b].preds); + let carried = args.any(|(a, &q)| group.contains(a) && !no_lanes(q, b)); + (carried && !group.contains(&f.value)).then_some(f.value) + }) + { + group.push(v); + } // The group input holds the same value in every lane only as the - // first lane reads it; a VGPR write reads its old value too. + // first lane reads it. A write to v5 reads its old value too, which + // only lanes outside EXEC keep. + // shortcut: writes that may keep the old v5 in active lanes + // (v_fmac_f32's accumulator, a 16-bit half or d16 load, + // v_writelane_b32, v_movreld_b32, DPP that skips lanes) and + // partial-EXEC writes pass; check those too if a mesh program + // writes v5 that way. let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| { - group.is_some_and(|g| i.reads.contains(&(Reg::V(5), g))) + i.read(Reg::V(5)).is_some_and(|v| group.contains(&v)) && i.name() != "v_readfirstlane_b32" - && i.write(Reg::V(5)).is_none() + && (i.write(Reg::V(5)).is_none() || operand_reads(p, i).contains(&Reg::V(5))) }); if let Some(i) = per_lane { return Err(unsupported( @@ -759,6 +798,41 @@ mod tests { assert_eq!(io.exports[0].target, Target::Primitive); // The group input is uniform only as the first lane reads it. assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5 + // Also as an operand of a write to v5, or after a join. + let per_lane: [&[u32]; 5] = [ + &[0x4A0A_0305, S_ENDPGM], // v_add_nc_u32 v5, v5, v1 + &[0x7E0A_0D05, S_ENDPGM], // v_cvt_f32_u32 v5, v5 + &[0xDC30_8000, 0x0500_0005, S_ENDPGM], // global_load_dword v5, v5, s[0:1] + &[0x7E0A_CB01, S_ENDPGM], // v_swap_b32 v5, v1 + &[ + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0001, // s_cbranch_scc1 -> 0xc + 0x7E0A_0280, // v_mov_b32 v5, 0 + 0x7E02_0305, // 0xc: v_mov_b32 v1, v5 + S_ENDPGM, + ], + ]; + let accepted: Vec<_> = per_lane.iter().filter(|w| mesh(w).is_ok()).collect(); + assert!(accepted.is_empty(), "accepted: {accepted:08X?}"); + // Overwriting v5 reads the group input only for lanes outside EXEC: + // v_mov_b32 v5, 0; v_mov_b32 v1, v5. + assert!(mesh(&[0x7E0A_0280, 0x7E02_0305, S_ENDPGM]).is_ok()); + // Skipping that write with s_cbranch_execz is the same case: under the + // same mask, the read sees only the 0. + let reuse = [ + 0x7E04_0505, // v_readfirstlane_b32 s2, v5 + 0x7D88_0084, // v_cmp_gt_u32 vcc, 4, v0 + 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBF88_0001, // s_cbranch_execz -> 0x14 + 0x7E0A_0280, // v_mov_b32 v5, 0 + 0x88FE_067E, // 0x14: s_or_b64 exec, exec, s[6:7] + 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBF88_0001, // s_cbranch_execz -> 0x24 + 0x7E02_0305, // v_mov_b32 v1, v5 + 0x88FE_067E, // 0x24: s_or_b64 exec, exec, s[6:7] + S_ENDPGM, + ]; + assert_eq!(mesh(&reuse).map(|_| ()), Ok(())); } #[test] diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 9d3e65ded1..8f17c81528 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -354,7 +354,13 @@ pub fn build_with( Flow::Stop => Exit::End, }; } - if let Some((reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? { + if let Some((mut reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? { + // Lanes disabled in EXEC keep the old value. + for w in writes.iter().filter(|w| matches!(w, Reg::V(_))) { + if !reads.contains(w) { + reads.push(*w); + } + } let unset = |regs: Vec| regs.into_iter().map(|r| (r, NONE)).collect(); blocks[b].insts.push(Inst { machine, @@ -872,6 +878,16 @@ const DROPPED: &[&str] = &[ /// Registers read, registers written. type Effects = (Vec, Vec); +/// The registers `inst` of `p` reads as operands: its reads without the old +/// value of a VGPR it only writes. +pub(crate) fn operand_reads(p: &Program, inst: &Inst) -> Vec { + let lanes = 1 + u8::from(p.wave64); + effects(&inst.machine, &inst.fields, inst.name(), lanes, p.vgprs) + .ok() + .flatten() + .map_or_else(Vec::new, |e| e.0) +} + /// Registers an instruction reads and writes, one per dword, or `None` if /// the IR drops it. fn effects( @@ -1140,8 +1156,6 @@ fn effects( } if vector { r.extend(mask(EXEC)); - // Lanes disabled in EXEC keep the old value. - r.extend(w.iter().filter(|w| matches!(w, Reg::V(_)))); } let mut seen = Vec::with_capacity(r.len()); r.retain(|reg| { From 73dcab39b61a3a03af2677adb3c7d45f8dd29ede Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 15:14:06 +0900 Subject: [PATCH 073/123] GPU: use selected mip extents for MSAA resolves (cherry picked from commit ea09cb04bc0cf14ee4caae7d71f3bf51ae787115) --- crates/victory-gpu/src/list.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 080e45239e..42b222fa59 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -837,7 +837,7 @@ extern "system" fn resolve( { use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D12::{ - D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1, + D3D12_RESOLVE_MODE_AVERAGE, D3D12_RESOURCE_DESC, ID3D12GraphicsCommandList1, }; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; use windows::core::Interface; @@ -848,11 +848,17 @@ extern "system" fn resolve( crate::texture::host_written(dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}")); + let extent = |d: D3D12_RESOURCE_DESC, subresource: u32| { + // Mips are the low-order component of an array or plane subresource index. + let mip = subresource % u32::from(d.MipLevels); + ((d.Width >> mip).max(1), (d.Height >> mip).max(1)) + }; // SAFETY: an open list and live textures; the region is inside both. unsafe { - let (a, b) = (to.GetDesc(), from.GetDesc()); + let (dst_width, dst_height) = extent(to.GetDesc(), dst_sub); + let (src_width, src_height) = extent(from.GetDesc(), src_sub); let format = DXGI_FORMAT(format as i32); - if (a.Width, a.Height) == (b.Width, b.Height) { + if (dst_width, dst_height) == (src_width, src_height) { list.list .ResolveSubresource(to, dst_sub, from, src_sub, format); } else if let Ok(list1) = list.list.cast::() { @@ -860,8 +866,8 @@ extern "system" fn resolve( let rect = RECT { left: 0, top: 0, - right: a.Width.min(b.Width) as i32, - bottom: a.Height.min(b.Height) as i32, + right: dst_width.min(src_width) as i32, + bottom: dst_height.min(src_height) as i32, }; list1.ResolveSubresourceRegion( to, From 778fe017d1f68b447cc3fcd7d7debcc0a399ecac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Lu=C3=ADs=20da=20Silva?= Date: Tue, 24 Nov 2026 04:08:25 -0300 Subject: [PATCH 074/123] Shaders: lower tbuffer_store_format_* that need no conversion Typed-format stores whose format is in the instruction (MTBUF) were refused by name. They now lower as raw stores of the element's dwords when no conversion is involved: formats of 32-bit channels (uint, sint, float; 32 to 32_32_32_32) store the data's bits, and the _d16_ forms of the 16-bit float formats (16_16, 16_16_16_16) store their halves as they are. The instruction must supply every channel of the format, as the typed loads' layout gives it. Everything else stays refused with a reason: norm, scaled and narrow integer formats (conversions), elements under a dword (a read-modify-write lanes would race on), and f32 data for half formats, because DXIL's f32-to-f16 op rounds toward zero (measured below) where the console rounds to nearest even; #422 addresses that. GPU tests store each lowered layout on the host GPU and WARP and read the dwords back; another test checks the refusals. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 837bb40516d988ec7c2dfa7eb38e44aeb786b828) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 69 +++++- crates/victory-shader/src/emit/valu_tests.rs | 247 +++++++++++++++++++ 2 files changed, 314 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index cb23599a82..cd60e72236 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4102,6 +4102,42 @@ impl<'a> Lower<'a> { Ok(out) } + /// The dwords a `tbuffer_store_format_*` writes: its `channels` data + /// channels in buffer format `format`, as RDNA2 lays them out (see + /// [`buffer_format`]). Formats of 32-bit channels store the data's bits; + /// the `_d16_` forms of the 16-bit float formats store their halves as + /// they are. + // shortcut: only stores that need no conversion, with every channel of + // the format supplied, are lowered. Others need conversions (norm, + // scaled, narrow integers; f32 to f16, whose DXIL op rounds toward zero + // where the console rounds to nearest even, see #422) or elements under + // a dword (a read-modify-write lanes would race on); refused until a + // program needs them. + fn format_store_words( + &mut self, + inst: &Inst, + data: Option<&Operand>, + format: u8, + channels: u32, + ) -> Result, Why> { + let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?; + if bits.len() != channels as usize { + return Err("a typed-format store of some of its format's channels"); + } + if !bits.iter().sum::().is_multiple_of(32) { + return Err("a typed-format store of an element under a dword"); + } + let d16 = inst.name().contains("_d16_"); + let data = data.ok_or("buffer store data")?; + match (bits[0], numeric, d16) { + (32, Numeric::Uint | Numeric::Sint | Numeric::Float, false) => { + self.vgprs(inst, data, channels as u8) + } + (16, Numeric::Float, true) => self.vgprs(inst, data, channels.div_ceil(2) as u8), + _ => Err("a typed-format store of a converted or narrow format"), + } + } + /// The byte offset a buffer descriptor built around a root descriptor adds /// (constant and computed parts); none for other descriptors. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option), Why> { @@ -7453,13 +7489,16 @@ impl<'a> Lower<'a> { if *lds || *tfe { return Err("a buffer access to LDS or with tfe"); } - if format.is_some() && !name.starts_with("tbuffer_load_format_") { + if format.is_some() + && !name.starts_with("tbuffer_load_format_") + && !name.starts_with("tbuffer_store_format_") + { return Err(name); } let site = (b, i); let guard = self.guard(b, i)?; let c = self.cur; - let store = name.starts_with("buffer_store_"); + let store = name.starts_with("buffer_store_") || name.starts_with("tbuffer_store_"); // DXIL atomic operations: add, and, or, xor, signed and unsigned // min and max, exchange; compare-exchange apart. let atomic = match name.strip_prefix("buffer_atomic_") { @@ -7483,6 +7522,7 @@ impl<'a> Lower<'a> { .strip_prefix("buffer_load_") .or(plain.strip_prefix("buffer_store_")) .or(plain.strip_prefix("tbuffer_load_")) + .or(plain.strip_prefix("tbuffer_store_")) { _ if atomic.is_some() => (false, 1), Some("dword") => (false, 1), @@ -7606,6 +7646,31 @@ impl<'a> Lower<'a> { } return Ok(()); } + if let (true, Some(f)) = (store, *format) { + if index.is_some() { + return Err("a typed-format store by index"); + } + let words = self.format_store_words(inst, data.as_ref(), f, count)?; + let iu = self.s.m.undef(self.s.t.i32); + let mut args = vec![self.handle(site, src, false, (11 | u, 0))?, off, iu]; + let n = words.len(); + args.extend(words); + args.resize(3 + 4, iu); + args.push(self.s.m.i8((1u8 << n) - 1)); + args.push(self.s.m.i32(4)); + let at = self.begin_guarded(guard); + let void = self.s.t.void; + self.s.op( + self.cur, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &args, + ); + self.end_guarded(at, &[]); + return Ok(()); + } if store { let regs = if d16 { count.div_ceil(2) } else { count }; let mut vals = diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index c1b849864e..2c1e4b27bd 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1650,3 +1650,250 @@ fn sdwa_16bit_dst_unused_sext_sign_extends_word0() { }); } } + +/// [`build_valu_cs`], with the lowering's refusal as an error. +fn try_build_valu_cs(body: &[u32]) -> Result { + let mut words = Vec::new(); + // s[4:5] = descriptor table address (heap index 0 -> byte offset 0). + words.push(s_mov_b32(5, 0x80)); // inline constant 0 + words.extend_from_slice(&s_load_dwordx4(8, 4)); + // Copy root constants s0..s3 into v1..v4 so VALU instructions operate on + // VGPRs just as they do in real shaders. + for i in 0..4u8 { + words.push(vop1(0x001, i + 1, sgpr(i))); // v_mov_b32 + } + words.extend_from_slice(body); + words.extend_from_slice(&buffer_store_dword(0, 8, 0)); + words.push(S_ENDPGM); + + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + threads: [1, 1, 1], + }), + code, + }; + + 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("resource::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, + host_wave64: true, + }) + .map_err(|e| format!("{e:?}"))?; + + 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, + }; + + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + let ours = copy[4..20].to_vec(); + v.validate(&mut copy).expect("DXIL validation failed"); + assert_eq!(copy[4..20], ours[..], "container hash mismatch"); + } + + Ok(shader) +} + +/// MTBUF `op vdata, v5, s[8:11], 0 format:fmt offset:16` (no offen/idxen; +/// `op` 4..7 stores x..xyzw, 12..15 their d16 forms). +const fn mtbuf_store(op: u8, fmt: u8, vdata: u8) -> [u32; 2] { + [ + 0x3A << 26 | (fmt as u32) << 19 | (op as u32 & 7) << 16 | 16, + 0x80 << 24 | (op as u32 >> 3 & 1) << 21 | (8 >> 2) << 16 | (vdata as u32) << 8 | 5, + ] +} + +/// Runs `shader` once with root constants `inputs` on every available +/// SM 6.6 host and returns the first `dwords` of its raw UAV, per device. +fn run_dwords(shader: &HostShader, inputs: [u32; 4], dwords: u32) -> Vec<(&'static str, Vec)> { + let mut out = Vec::new(); + 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 mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) => inputs[u.dword as usize], + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let r = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(dwords)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + out.push((label, r[0].clone())); + } + assert!( + !out.is_empty(), + "neither hardware nor WARP SM 6.6 device available" + ); + out +} + +#[test] +fn tbuffer_store_format_writes_the_formats_layout() { + let f = |x: f32| x.to_bits(); + // (what, op, format, data in v1..v4, dwords 4..8 afterwards) + type Case = (&'static str, u8, u8, [u32; 4], [u32; 4]); + let cases: &[Case] = &[ + ( + "32_32_32_32 float xyzw", + 7, + 77, + [f(1.5), f(-0.0), 0x7FC0_1234, 0x0000_0001], + [f(1.5), f(-0.0), 0x7FC0_1234, 0x0000_0001], + ), + ( + "32_32_32_32 sint xyzw", + 7, + 76, + [u32::MAX, 0x8000_0000, 7, 0x1234_5678], + [u32::MAX, 0x8000_0000, 7, 0x1234_5678], + ), + ( + "32_32_32 float xyz", + 6, + 74, + [f(2.0), f(3.0), f(4.0), 0xDEAD_BEEF], + [f(2.0), f(3.0), f(4.0), 0], + ), + ( + "32_32 uint xy", + 5, + 63, + [0xAABB_CCDD, 9, 0xDEAD_BEEF, 0xDEAD_BEEF], + [0xAABB_CCDD, 9, 0, 0], + ), + ( + "32 float x", + 4, + 22, + [f(-7.25), 1, 2, 3], + [f(-7.25), 0, 0, 0], + ), + ( + // d16: the halves are stored as they are. + "16_16 float d16_xy", + 13, + 29, + [0xBC00_3555, 0xDEAD_BEEF, 0, 0], + [0xBC00_3555, 0, 0, 0], + ), + ( + "16_16_16_16 float d16_xyzw", + 15, + 71, + [0x1234_5678, 0x7C00_FC00, 0, 0], + [0x1234_5678, 0x7C00_FC00, 0, 0], + ), + ]; + for &(what, op, fmt, inputs, want) in cases { + let mut body = vec![vop1(0x001, 5, 0x80)]; // v_mov_b32 v5, 0 + body.extend(mtbuf_store(op, fmt, 1)); + let shader = build_valu_cs(&body); + for (backend, out) in run_dwords(&shader, inputs, 8) { + assert_eq!( + out[4..8], + want, + "{backend}: tbuffer_store {what}: wrote {:#010x?}, want {want:#010x?}", + &out[4..8], + ); + } + } +} + +#[test] +fn tbuffer_store_format_refuses_what_it_does_not_convert() { + for (what, op, fmt, reason) in [ + ("8_8_8_8 unorm", 7, 56, "a converted or narrow format"), + ("16_16 uint", 5, 27, "a converted or narrow format"), + ("16 float", 4, 13, "an element under a dword"), + ( + "32_32_32_32 float, xy only", + 5, + 77, + "some of its format's channels", + ), + ("32 float d16_x", 12, 22, "a converted or narrow format"), + // f32 to f16 waits for nearest-even narrowing (#422). + ("16_16 float xy", 5, 29, "a converted or narrow format"), + ( + "16_16_16_16 float xyzw", + 7, + 71, + "a converted or narrow format", + ), + ] { + let mut body = vec![vop1(0x001, 5, 0x80)]; + body.extend(mtbuf_store(op, fmt, 1)); + match try_build_valu_cs(&body) { + Ok(_) => panic!("tbuffer_store {what} lowered; it should be refused"), + Err(e) => assert!(e.contains(reason), "tbuffer_store {what}: refused with {e}"), + } + } +} From 1cda09ff52589a9d6b3374c80aee1f14c2a3188e Mon Sep 17 00:00:00 2001 From: senchsus Date: Tue, 24 Nov 2026 06:41:39 +0000 Subject: [PATCH 075/123] Shaders: v_mul_legacy_f32 treats denormal operands as zero RDNA2 flushes denormal operands of the legacy multiplies to zero, so 0 x anything = 0 also holds for them. The lowering only tested for an exact float zero, whose result also depends on the host's denormal mode. Test the exponent bits instead. Follow-up to #2. (cherry picked from commit 3d73ea92879b2ba102ebe3055374eda875782475) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 17 +++++++--- crates/victory-shader/src/emit/valu_tests.rs | 33 ++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index cd60e72236..60fccdebff 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2021,14 +2021,23 @@ impl<'a> Lower<'a> { self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32) } - /// `0 × anything = 0`, as in D3D9. + /// `0 × anything = 0`, as in D3D9. As on RDNA2, a denormal operand counts + /// as zero, so the test is on the exponent bits rather than a float + /// compare (whose result would depend on the host's denormal mode). fn legacy_mul(&mut self, a: V, b: V) -> V { let c = self.cur; let m = self.s.m.bin(c, Bin::Mul, a, b); - let zero = self.s.m.f32(0); - let az = self.s.m.cmp(c, pred::OEQ, a, zero); - let bz = self.s.m.cmp(c, pred::OEQ, b, zero); + let exp = self.s.m.i32(0x7F80_0000); + let izero = self.s.m.i32(0); + let is_zero = |l: &mut Self, v: V| { + let bits = l.as_int(v); + let e = l.s.m.bin(c, Bin::And, bits, exp); + l.s.m.cmp(c, pred::EQ, e, izero) + }; + let az = is_zero(self, a); + let bz = is_zero(self, b); let z = self.s.m.bin(c, Bin::Or, az, bz); + let zero = self.s.m.f32(0); self.s.m.select(c, z, zero, m) } diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 2c1e4b27bd..a90969e306 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1897,3 +1897,36 @@ fn tbuffer_store_format_refuses_what_it_does_not_convert() { } } } + +#[test] +fn v_mul_legacy_f32_treats_denormals_as_zero() { + // v_mul_legacy_f32 v0, v1, v2 (VOP2 opcode 0x007 in its VOP3 encoding) + let shader = build_valu_cs(&vop3(0x107, 0, vgpr(1), vgpr(2), vgpr(0))); + let f = f32::to_bits; + let (denorm, neg_denorm, min_normal) = (0x0000_0001u32, 0x8040_0000u32, 0x0080_0000u32); + + let cases: &[(u32, u32, u32)] = &[ + // Zero or denormal times anything, non-finite included, is +0. + (f(0.0), f(f32::INFINITY), f(0.0)), + (f(-0.0), f(f32::NAN), f(0.0)), + (f(f32::NAN), f(0.0), f(0.0)), + (denorm, f(f32::INFINITY), f(0.0)), + (f(f32::NAN), neg_denorm, f(0.0)), + (denorm, f(2.0f32.powi(100)), f(0.0)), + // The smallest normal is not zero. + (min_normal, f(2.0), f(f32::MIN_POSITIVE * 2.0)), + // Ordinary products. + (f(1.5), f(-4.0), f(-6.0)), + (f(3.0), f(0.5), f(1.5)), + ]; + + let inputs: Vec<[u32; 4]> = cases.iter().map(|&(a, b, _)| [a, b, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].2; + assert_eq!( + got, want, + "{backend}: v_mul_legacy_f32({:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], + ); + }); +} From 2ef80b4ca79103bb1f95b61513171e876525e138 Mon Sep 17 00:00:00 2001 From: DenRakEiw <89697885+DenRakEiw@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:26:38 +0100 Subject: [PATCH 076/123] shader: support f16 omod and saturate/apply modifiers in v_cvt_{u16,i16}_f16 (cherry picked from commit 5e9d60d134e2130f140d18a65a5461c9265d7f24) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 131 +++++++++-------- crates/victory-shader/src/emit/valu_tests.rs | 140 +++++++++++++++++++ 2 files changed, 209 insertions(+), 62 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 60fccdebff..9e93836977 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5695,8 +5695,13 @@ impl<'a> Lower<'a> { return self.write_f(inst, f, guard); } let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> { - if v.omod != 0 { - return Err("an output modifier on a 16-bit operation"); + match v.omod { + 0 => {} + k => { + let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)]; + let k = l.s.m.f32(factor.to_bits()); + f = l.s.m.bin(l.cur, Bin::Mul, f, k); + } } if v.clamp { f = l.unary(7, f); @@ -5808,71 +5813,73 @@ impl<'a> Lower<'a> { let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?; return self.write_half(inst, r, guard); } + if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") { + if v.clamp || v.omod != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + // Toward zero, saturating at the 16-bit range (infinities + // included); NaN gives 0. Clamped in f32 first, where every + // f16 is exact, so the conversion never leaves i32's range. + let a = self.half_fsrc(inst, 0)?; + let (lo, hi) = if name == "v_cvt_u16_f16" { + (0.0f32, 65535.0f32) + } else { + (-32768.0, 32767.0) + }; + let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits())); + let t = self.binary(35, a, lo); + let t = self.binary(36, t, hi); + let r = self.s.m.cast(c, Cast::FpToSi, t, i32t); + let nan = self.s.m.cmp(c, pred::UNO, a, a); + let z = self.s.m.i32(0); + let r = self.s.m.select(c, nan, z, r); + return self.write_half(inst, r, guard); + } // 16-bit integers: computed on the low halves, the low 16 bits kept. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 { return Err("modifiers on a 16-bit integer operation"); } - let r = match name { - "v_cvt_u16_f16" | "v_cvt_i16_f16" => { - // Toward zero, saturating at the 16-bit range (infinities - // included); NaN gives 0. Clamped in f32 first, where every - // f16 is exact, so the conversion never leaves i32's range. - let a = self.half_fsrc(inst, 0)?; - let (lo, hi) = if name == "v_cvt_u16_f16" { - (0.0f32, 65535.0f32) - } else { - (-32768.0, 32767.0) - }; - let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits())); - let t = self.binary(35, a, lo); - let t = self.binary(36, t, hi); - let r = self.s.m.cast(c, Cast::FpToSi, t, i32t); - let nan = self.s.m.cmp(c, pred::UNO, a, a); - let z = self.s.m.i32(0); - self.s.m.select(c, nan, z, r) - } - _ => { - let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); - let k16 = self.s.m.i32(16); - let sext = |l: &mut Self, x: V| { - let t = l.s.m.bin(c, Bin::Shl, x, k16); - l.s.m.bin(c, Bin::AShr, t, k16) - }; - if name.ends_with("_i16") { - a = sext(self, a); - b = sext(self, b); + let r = { + let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); + let k16 = self.s.m.i32(16); + let sext = |l: &mut Self, x: V| { + let t = l.s.m.bin(c, Bin::Shl, x, k16); + l.s.m.bin(c, Bin::AShr, t, k16) + }; + if name.ends_with("_i16") { + a = sext(self, a); + b = sext(self, b); + } + let k15 = self.s.m.i32(15); + match name { + "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b), + "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b), + "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a), + "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b), + "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => { + // src0 is the shift (4 bits), src1 the value. + let sh = self.s.m.bin(c, Bin::And, a, k15); + let x = if name == "v_ashrrev_i16" { + sext(self, b) + } else { + b + }; + let op = match name { + "v_lshlrev_b16" => Bin::Shl, + "v_lshrrev_b16" => Bin::LShr, + _ => Bin::AShr, + }; + self.s.m.bin(c, op, x, sh) } - let k15 = self.s.m.i32(15); - match name { - "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b), - "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b), - "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a), - "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b), - "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => { - // src0 is the shift (4 bits), src1 the value. - let sh = self.s.m.bin(c, Bin::And, a, k15); - let x = if name == "v_ashrrev_i16" { - sext(self, b) - } else { - b - }; - let op = match name { - "v_lshlrev_b16" => Bin::Shl, - "v_lshrrev_b16" => Bin::LShr, - _ => Bin::AShr, - }; - self.s.m.bin(c, op, x, sh) - } - _ => { - let p = match name { - "v_max_u16" => pred::IUGT, - "v_min_u16" => pred::IULT, - "v_max_i16" => pred::SGT, - _ => pred::SLT, - }; - let t = self.s.m.cmp(c, p, a, b); - self.s.m.select(c, t, a, b) - } + _ => { + let p = match name { + "v_max_u16" => pred::IUGT, + "v_min_u16" => pred::IULT, + "v_max_i16" => pred::SGT, + _ => pred::SLT, + }; + let t = self.s.m.cmp(c, p, a, b); + self.s.m.select(c, t, a, b) } } }; diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index a90969e306..73d358ce1c 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1930,3 +1930,143 @@ fn v_mul_legacy_f32_treats_denormals_as_zero() { ); }); } + +/// VOP3 `op vdst, src0, src1, src2` with explicit `abs`, `neg`, `omod`, `clamp`. +#[allow(clippy::too_many_arguments)] +const fn vop3_mod( + op: u16, + vdst: u8, + src0: u16, + src1: u16, + src2: u16, + abs: u8, + neg: u8, + omod: u8, + clamp: bool, +) -> [u32; 2] { + [ + 0x35 << 26 + | (op as u32 & 0x3FF) << 16 + | (clamp as u32) << 15 + | (abs as u32 & 7) << 8 + | vdst as u32, + (neg as u32 & 7) << 29 + | (omod as u32 & 3) << 27 + | (src0 as u32 & 0x1FF) + | (src1 as u32 & 0x1FF) << 9 + | (src2 as u32 & 0x1FF) << 18, + ] +} + +#[test] +fn f16_omod_applies_before_clamp() { + // VOP3 v_add_f16 (0x132 = 0x100 + VOP2 0x32): v0 = (v1 + v2) * omod [clamp] + let mul2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 1, false)); + let mul4 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 2, false)); + let div2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, false)); + let div2_clamp = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, true)); + + // f16 constants: 0.25=0x3400, 0.5=0x3800, 0.75=0x3A00, 1.0=0x3C00, 1.5=0x3E00, 2.0=0x4000, -0.5=0xB800 + run_cases( + &mul2, + &[[0x3400, 0x3800, 0, 0]], // (0.25 + 0.5) * 2 = 1.5 (0x3E00) + |backend, _, _, got| { + assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 mul:2"); + }, + ); + run_cases( + &mul4, + &[[0x3400, 0x3400, 0, 0]], // (0.25 + 0.25) * 4 = 2.0 (0x4000) + |backend, _, _, got| { + assert_eq!(got as u16, 0x4000, "{backend}: v_add_f16 mul:4"); + }, + ); + run_cases( + &div2, + &[[0x3E00, 0x3E00, 0, 0]], // (1.5 + 1.5) / 2 = 1.5 (0x3E00) + |backend, _, _, got| { + assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 div:2"); + }, + ); + // Ordering check: (0.75 + 0.75) = 1.5; div:2 before clamp gives 0.75 (0x3A00), + // whereas clamp before div:2 would give 0.5 (0x3800). + let clamp_cases: &[(u16, u16, u16)] = &[ + (0x3A00, 0x3A00, 0x3A00), // (0.75 + 0.75) / 2 = 0.75 -> 0.75 + (0x3E00, 0x3E00, 0x3C00), // (1.5 + 1.5) / 2 = 1.5 -> clamped to 1.0 + (0xB800, 0xB800, 0x0000), // (-0.5 + -0.5) / 2 = -0.5 -> clamped to 0.0 + ]; + let inputs: Vec<[u32; 4]> = clamp_cases + .iter() + .map(|&(a, b, _)| [u32::from(a), u32::from(b), 0, 0]) + .collect(); + run_cases(&div2_clamp, &inputs, |backend, i, _, got| { + let want = clamp_cases[i].2; + assert_eq!( + got as u16, want, + "{backend}: v_add_f16 div:2 clamp case {i}: got {:#06x}, want {want:#06x}", + got as u16, + ); + }); +} + +#[test] +fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() { + // VOP3 v_cvt_u16_f16 = 0x1D2 (0x180 + VOP1 0x52) + // VOP3 v_cvt_i16_f16 = 0x1D3 (0x180 + VOP1 0x53) + let cvt_u16 = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + let cvt_u16_abs = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 1, 0, 0, false)); + let cvt_i16 = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + let cvt_i16_neg = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 1, 0, false)); + + let u16_cases: &[(u16, u16)] = &[ + (0xBC00, 0), // -1.0 -> 0 + (0xFC00, 0), // -inf -> 0 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x7BFF, 65504), // 65504.0 (max finite f16) -> 65504 + (0x7C00, 0xFFFF), // +inf -> 65535 (saturated) + ]; + let u16_in: Vec<[u32; 4]> = u16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + run_cases(&cvt_u16, &u16_in, |backend, i, inp, got| { + let want = u16_cases[i].1; + assert_eq!( + got as u16, want, + "{backend}: v_cvt_u16_f16({:#06x}) = {:#06x}, want {want:#06x}", + inp[0], got as u16, + ); + }); + run_cases( + &cvt_u16_abs, + &[[0xD7BC, 0, 0, 0]], // |-123.75| -> 123 + |backend, _, _, got| { + assert_eq!(got as u16, 123, "{backend}: v_cvt_u16_f16 |src0|"); + }, + ); + + let i16_cases: &[(u16, u16)] = &[ + (0xFC00, 0x8000), // -inf -> -32768 + (0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped) + (0xD7BC, (-123i16) as u16), // -123.75 -> -123 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped) + (0x7C00, 0x7FFF), // +inf -> 32767 + ]; + let i16_in: Vec<[u32; 4]> = i16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + run_cases(&cvt_i16, &i16_in, |backend, i, inp, got| { + let want = i16_cases[i].1; + assert_eq!( + got as u16, want, + "{backend}: v_cvt_i16_f16({:#06x}) = {:#06x}, want {want:#06x}", + inp[0], got as u16, + ); + }); + run_cases( + &cvt_i16_neg, + &[[0x57BC, 0, 0, 0], [0x78E2, 0, 0, 0]], // -(123.75) -> -123; -(40000.0) -> -32768 + |backend, i, _, got| { + let want = [(-123i16) as u16, 0x8000][i]; + assert_eq!(got as u16, want, "{backend}: v_cvt_i16_f16 -src0 case {i}"); + }, + ); +} From 6415628cfda0016a20f9537c50d1f6f0364b8745 Mon Sep 17 00:00:00 2001 From: wrothgaril <211408787+wrothgaril@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:11:57 +0100 Subject: [PATCH 077/123] Shaders: bound root view accesses by the size the host binds A root SRV or CBV has no bounds on the host: a shader access past the memory the host mapped there is a GPU page fault. The console's buffer views of the same memory have record counts, and the offsets come from title data the host may not have mirrored (zeros, stale memory), so such accesses happen. Some hosts' GPUs stall on the fault until the driver resets the device as hung: a mesh dispatch of a program that reads its vertex streams through a root view with a formatted load hangs an RTX 5090 and the device is removed. The host now passes each root view's byte size in the user-data dword of its address (which the shader never reads, the view being bound as a root argument), and every raw, formatted and constant access through a root view checks the bytes it touches against it: reads past it give 0, writes are dropped, as for a console view past its records. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 06657a8bebe86f562cf1d55796de565b9a9d329b) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 31 +++- crates/victory-shader/src/emit/diff_tests.rs | 3 + crates/victory-shader/src/emit/lower.rs | 157 ++++++++++++++++++- crates/victory-shader/src/emit/valu_tests.rs | 153 ++++++++++++++++++ 4 files changed, 338 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 6e838e179f..d01255e54d 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -159,9 +159,7 @@ pub(crate) fn dispatched() -> u64 { /// other views as 1 MiB (both cut at their buffer's end). fn root_view(list: &HostList, address: u64, srv: bool) -> Option { let shadow = crate::shadow::find(address, 1)?; - let len = shadow - .left(address) - .min(if srv { 1 << 20 } else { 1 << 16 }); + let len = root_view_len(&shadow, address, srv); let gpu = shadow.gpu(address); if srv || gpu % 256 == 0 { shadow.refresh(list, address, len); @@ -172,6 +170,14 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option { Some(gpu) } +/// The bytes of title memory at `address` a root view binds (and shaders +/// may read: see [`State::root_view_bytes`]). +fn root_view_len(shadow: &crate::shadow::Shadow, address: u64, srv: bool) -> u64 { + shadow + .left(address) + .min(if srv { 1 << 20 } else { 1 << 16 }) +} + macro_rules! once { ($($arg:tt)*) => {{ static ONCE: std::sync::Once = std::sync::Once::new(); @@ -383,6 +389,21 @@ impl State { } } + /// The bytes root view `slot` holds from its start, as [`root_view`] + /// binds it. Shaders check their accesses against it: a root view has + /// no bounds on the host, and an access past the memory it maps is a + /// GPU page fault, which some hosts stall on until the driver resets + /// the device. 0 for a root view the title did not set. + fn root_view_bytes(&self, compute: bool, slot: u8, srv: bool) -> u32 { + let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { + return 0; + }; + let Some(shadow) = crate::shadow::find(address, 1) else { + return 0; + }; + u32::try_from(root_view_len(&shadow, address, srv)).unwrap_or(u32::MAX) + } + /// The bound heap holding `handle`. fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> { self.heaps @@ -605,6 +626,10 @@ impl State { .find(|m| m.0 == u.slot && u.root == RootType::Table); values[u.index as usize] = match fresh { Some(&(_, offset)) => offset, + None if u.root == RootType::Descriptor => { + let srv = stage.root_srvs.iter().any(|r| r.0 == u.slot); + self.root_view_bytes(compute, u.slot, srv) + } None => self.user_value(compute, u.slot, u.root, u.dword), }; } diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index fdc02aa119..633a4f5075 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -706,6 +706,9 @@ fn user_data(s: &HostShader, k: &[u32; 4]) -> Vec { (RootType::Table, 3) => 5 * 32, // The typed views of `raw` (compute) from 9. (RootType::Table, 6) => 9 * 32, + // The bytes of the root CBV (slot 4) and SRV (slot 5) bound. + (RootType::Descriptor, 4) => 64 * 4, + (RootType::Descriptor, 5) => 32 * 4, other => panic!("unexpected user data {other:?}"), }; } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 9e93836977..6aaba94de6 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -199,6 +199,8 @@ struct Lower<'a> { params: HashMap, user_data: Option, user_reads: BTreeMap, + /// Bytes each root view holds, by root parameter (see [`Self::root_view_size`]). + root_sizes: HashMap, samplers: Vec<[u32; 4]>, descriptors: HashMap<(Site, bool), &'a Source>, scalar: HashMap, @@ -667,6 +669,7 @@ impl<'a> Lower<'a> { params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), user_data: None, user_reads: BTreeMap::new(), + root_sizes: HashMap::new(), samplers: Vec::new(), descriptors: x .res @@ -826,6 +829,27 @@ impl<'a> Lower<'a> { }; Some(self.handle((b, i), &src, false, (11, 0))?) }; + // Root views: the dwords read checked against the view's size. + let root = if a.param == CODE { + None + } else { + self.root_view_size(&Source::Built { + address: a, + bits: 0, + words: [0, 0], + }) + }; + let (off, ok) = match root { + Some(size) => { + let bytes = if sub.is_some() { 4 } else { 4 * n }; + let not3 = self.s.m.i32(!3); + let at = self.s.m.bin(c, Bin::And, off, not3); + let (ok, _) = self.in_root_view(size, at, bytes); + let zero = self.s.m.i32(0); + (self.s.m.select(c, ok, off, zero), Some(ok)) + } + None => (off, None), + }; let dword = |l: &mut Self, byte: V| -> Result { match h { None => l.code_dword(byte), @@ -867,6 +891,7 @@ impl<'a> Lower<'a> { .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left) } }; + let x = self.zero_unless(ok, x); self.write(inst, Reg::V(reg + k as u8), x, guard); } Ok(()) @@ -1478,6 +1503,93 @@ impl<'a> Lower<'a> { Val::I32(self.s.m.extract(entry, r, index % 4)) } + /// For a root view (a root CBV, SRV or UAV), the bytes the host's view + /// holds from its start, which the host passes in the user-data dword of + /// the view's address. A root view has no bounds on the host: an access + /// past what the host mapped (an offset from data the host has not + /// mirrored) is a GPU page fault, which some hosts' GPUs stall on until + /// the driver resets the device. Accesses are checked against this size + /// as the console's bounded buffer views are. + fn root_view_size(&mut self, src: &Source) -> Option { + let Source::Built { address, .. } = src else { + return None; + }; + if address.param == CODE { + return None; + } + let rp = *self.x.native.layout.get(address.param)?; + if rp.root != RootType::Descriptor { + return None; + } + if let Some(&v) = self.root_sizes.get(&address.param) { + return Some(v); + } + let index = u32::from(rp.user_data); + self.user_reads.insert( + index, + UserData { + index, + slot: rp.slot, + root: RootType::Descriptor, + dword: 0, + }, + ); + self.s.user_data = self.s.user_data.max(index + 1); + let h = match self.user_data { + Some(h) => h, + None => { + let h = self.s.user_data_handle(); + self.user_data = Some(h); + h + } + }; + let entry = self.s.entry; + let row = self.s.m.i32(index / 4); + let r = self.s.op( + entry, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, row], + ); + let v = self.s.m.extract(entry, r, index % 4); + self.root_sizes.insert(address.param, v); + Some(v) + } + + /// Whether `bytes` bytes at byte `off` lie in a root view of `size` + /// bytes, and the offset to access instead (0 when they do not). + fn in_root_view(&mut self, size: V, off: V, bytes: u32) -> (V, V) { + let c = self.cur; + let below = self.s.m.cmp(c, pred::IULT, off, size); + let left = self.s.m.bin(c, Bin::Sub, size, off); + let n = self.s.m.i32(bytes); + let fits = self.s.m.cmp(c, pred::IUGE, left, n); + let ok = self.s.m.bin(c, Bin::And, below, fits); + let zero = self.s.m.i32(0); + (ok, self.s.m.select(c, ok, off, zero)) + } + + /// `guard` (lanes that run an access) narrowed to `ok`. + fn narrow(&mut self, guard: Option, ok: Option) -> Option { + match (guard, ok) { + (Some(g), Some(k)) => Some(self.s.m.bin(self.cur, Bin::And, g, k)), + (g, k) => g.or(k), + } + } + + /// `x` where `ok` holds, else 0 (`ok` none: always `x`). + fn zero_unless(&mut self, ok: Option, x: V) -> V { + match ok { + Some(k) => { + let zero = self.s.m.i32(0); + self.s.m.select(self.cur, k, x, zero) + } + None => x, + } + } + /// A dword of a lane mask as a number: the ballot of the lanes' bits, /// taken in the block that writes the mask (see [`MaskData`]). fn mask_dword(&mut self, v: Value) -> Result { @@ -3579,6 +3691,7 @@ impl<'a> Lower<'a> { .copied() .ok_or("an untracked descriptor")?; let kind = self.used_kind(src); + let size = self.root_view_size(src); let c = self.cur; let (base, extra) = self.built_offset(src)?; let offset = &((*offset as u32).wrapping_add(base) as i32); @@ -3608,6 +3721,13 @@ impl<'a> Lower<'a> { for k in 0..count { let off = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, addr, off); + let (a, ok) = match size { + Some(size) => { + let (ok, a) = self.in_root_view(size, a, 4); + (a, Some(ok)) + } + None => (a, None), + }; let mask = self.s.m.i8(1); let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); let r = self.s.op( @@ -3620,6 +3740,7 @@ impl<'a> Lower<'a> { ); let x = self.s.m.extract(c, r, 0); let x = self.as_int(x); + let x = self.zero_unless(ok, x); self.write(inst, Reg::S(code + k as u8), x, None); } return Ok(()); @@ -3659,7 +3780,14 @@ impl<'a> Lower<'a> { None => { let off = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, addr, off); - self.cbuffer_dword(h, a) + match size { + Some(size) => { + let (ok, a) = self.in_root_view(size, a, 4); + let x = self.cbuffer_dword(h, a); + self.zero_unless(Some(ok), x) + } + None => self.cbuffer_dword(h, a), + } } }; self.write(inst, Reg::S(code + k as u8), x, None); @@ -7601,10 +7729,19 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = *data else { return Err("a buffer result"); }; + let size = self.root_view_size(src); for k in 0..count { let four = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, byte, four); + let (a, ok) = match size { + Some(size) => { + let (ok, a) = self.in_root_view(size, a, 4); + (a, Some(ok)) + } + None => (a, None), + }; let x = self.cbuffer_dword(h, a); + let x = self.zero_unless(ok, x); self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); @@ -7612,6 +7749,16 @@ impl<'a> Lower<'a> { let u = self.uav_bits(src, used) | if store || atomic.is_some() { 0x1000 } else { 0 }; let uav = u & 0x1000 != 0; let iu = self.s.m.undef(self.s.t.i32); + // Root views: the bytes accessed checked against the view's size + // (raw accesses, and the raw loads formatted ones make). + let (off, root_ok) = match self.root_view_size(src) { + Some(size) if !typed || format.is_some() => { + let bytes = if format.is_some() { 16 } else { 4 * count }; + let (ok, at) = self.in_root_view(size, off, bytes); + (at, Some(ok)) + } + _ => (off, None), + }; if let Some(op) = atomic { let d = data.as_ref().ok_or("buffer atomic data")?; let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?; @@ -7634,7 +7781,8 @@ impl<'a> Lower<'a> { Some(v) if returns => self.i32_of(v)?, _ => self.s.m.i32(0), }; - let at = self.begin_guarded(guard); + let access = self.narrow(guard, root_ok); + let at = self.begin_guarded(access); let i32t = self.s.t.i32; let r = if op == u32::MAX { // cmpswap: data is (new, compare). @@ -7745,7 +7893,8 @@ impl<'a> Lower<'a> { if !typed { args.push(self.s.m.i32(4)); } - let at = self.begin_guarded(guard); + let access = self.narrow(guard, root_ok); + let at = self.begin_guarded(access); let void = self.s.t.void; self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args); self.end_guarded(at, &[]); @@ -7760,6 +7909,7 @@ impl<'a> Lower<'a> { return Err("a buffer result"); }; for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() { + let x = self.zero_unless(root_ok, x); self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); @@ -7839,6 +7989,7 @@ impl<'a> Lower<'a> { for k in 0..count { let x = self.s.m.extract(c, r, k); let x = self.as_int(x); + let x = self.zero_unless(root_ok, x); self.write(inst, Reg::V(reg + k as u8), x, guard); } Ok(()) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 73d358ce1c..d9a631f123 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -2070,3 +2070,156 @@ fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() { }, ); } + +/// MUBUF `buffer_load_dword vdata, vaddr, s[srsrc:srsrc+3], 0 offen`. +const fn buffer_load_dword_offen(vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | 0x0C << 18 | 1 << 12, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] +} + +/// A root SRV has no bounds on the host: a read past what the host bound +/// reads 0, as a console buffer view past its records does, instead of +/// memory after it (or an unmapped page, which some GPUs stall on). +#[test] +fn root_view_reads_stop_at_the_bound_size() { + // s0..s3 root constants, s4 the UAV table, s[8:9] the root SRV's address. + let mut words = vec![s_mov_b32(5, 0x80)]; + words.extend_from_slice(&s_load_dwordx4(12, 4)); + // The buffer descriptor built around the root address: all records. + words.push(s_mov_b32(10, 0xC1)); + words.push(s_mov_b32(11, 0x80)); + words.push(vop1(0x001, 1, sgpr(0))); // v_mov_b32 v1, s0: the byte offset + words.extend_from_slice(&buffer_load_dword_offen(0, 1, 8)); + words.extend_from_slice(&buffer_store_dword(0, 12, 0)); + words.push(S_ENDPGM); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let root = |root, sgprs, user_data, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + let used = |kind, root, user_data, slot| UsedResource { + kind, + root, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data, + slot, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + root(RootType::Constants, 4, 0, 0), + root(RootType::Table, 1, 4, 1), + root(RootType::Descriptor, 2, 8, 2), + ], + used: vec![ + used(ResourceType::Uav, RootType::Table, 4, 1), + used(ResourceType::Srv, RootType::Descriptor, 8, 2), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 10 << 1, // 10 user SGPRs: s0..s9 + threads: [1, 1, 1], + }), + code, + }; + 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("resource::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, + host_wave64: true, + }) + .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, + }; + assert_eq!(shader.root_srvs, [2]); + assert!( + shader + .user_data + .iter() + .any(|u| u.root == RootType::Descriptor && u.slot == 2 && u.index == 8), + "the root view's size is user data: {:?}", + shader.user_data + ); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + // 64 dwords bound, of which the host says 16 (64 bytes) are the view's. + let data: Vec = (0..64).map(|i| 0x100 + i).collect(); + 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).expect("pipeline"); + for (offset, want) in [ + (0, 0x100), + (60, 0x10F), + (64, 0), + (128, 0), + (u32::MAX - 3, 0), + ] { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match u.root { + RootType::Constants => offset, + RootType::Descriptor => 64, + _ => 0, + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + ( + 1, + Root::View { + srv: true, + data: data.clone(), + }, + ), + ], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!(out[0][0], want, "{label}: offset {offset:#x}"); + } + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} From 960fbb597bf9e1063a0112809d61c3c7867814d9 Mon Sep 17 00:00:00 2001 From: Peter Bonanni Date: Tue, 24 Nov 2026 13:28:51 +0000 Subject: [PATCH 078/123] GPU: select the readable format and plane for depth/stencil SRVs A shader view of a typeless depth texture names its depth or stencil aspect; D3D12 wants the readable format (R32_FLOAT, R24_UNORM_X8, ...) and, for 2D and 2D-array views, the plane that format lives in. A view in the depth format itself (D32_FLOAT, D24S8) or with no format is refused by the host, so passes sampling the depth buffer (lighting, fog, SSAO) read nothing. Hand-ported from Raxstreams' d615ee0f (upstream #651): our fits() keeps its cast handling and texture argument; the new texture_srv_desc() runs before it. (cherry picked from commit d615ee0fe0f90750320575e2501726486a0454ca) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/descriptor/host.rs | 115 +++++++++++++++++++++- 1 file changed, 114 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 6edf927ae0..4eac2c24bf 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -891,6 +891,50 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere true } +/// A shader view of a typeless depth texture names the readable aspect. +/// For a 2D view D3D12 also requires the plane index to match that format. +fn texture_srv_desc( + resource: &D3D12_RESOURCE_DESC, + words: &[u32; 10], +) -> D3D12_SHADER_RESOURCE_VIEW_DESC { + let mut view = srv_desc(words); + if !resource + .Flags + .contains(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) + { + return view; + } + let (dsv, depth, stencil) = match resource.Format { + DXGI_FORMAT_R32G8X24_TYPELESS => ( + DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, + Some(DXGI_FORMAT_X32_TYPELESS_G8X24_UINT), + ), + DXGI_FORMAT_R24G8_TYPELESS => ( + DXGI_FORMAT_D24_UNORM_S8_UINT, + DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + Some(DXGI_FORMAT_X24_TYPELESS_G8_UINT), + ), + DXGI_FORMAT_R32_TYPELESS => (DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R32_FLOAT, None), + DXGI_FORMAT_R16_TYPELESS => (DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM, None), + _ => return view, + }; + let plane = if Some(view.Format) == stencil { + 1 + } else if [DXGI_FORMAT_UNKNOWN, resource.Format, dsv, depth].contains(&view.Format) { + view.Format = depth; + 0 + } else { + return view; + }; + match view.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE2D => view.Anonymous.Texture2D.PlaneSlice = plane, + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => view.Anonymous.Texture2DArray.PlaneSlice = plane, + _ => {} + } + view +} + /// Makes the host descriptor for `view` at `at`: the host resource it /// views, or `None` if it cannot. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { @@ -918,7 +962,9 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { View::Shader(resource, desc) => { let resource = *resource as crate::object::This; if let Some(texture) = crate::resource::host_resource(resource) { - let mut desc = desc.as_ref().map(srv_desc); + // SAFETY: a live host texture. + let info = unsafe { texture.GetDesc() }; + let mut desc = desc.as_ref().map(|words| texture_srv_desc(&info, words)); if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { return None; } @@ -1333,4 +1379,71 @@ mod tests { assert_eq!(heap.count(), 16); assert_eq!(heap.dynamic(1), None); } + + #[test] + fn depth_srv_uses_the_requested_aspect() { + for (own, request, expected, plane) in [ + (19, 20, 21, 0), + (19, 22, 22, 1), + (44, 45, 46, 0), + (44, 47, 47, 1), + (44, 120, 47, 1), + (44, 119, 46, 0), + (39, 40, 41, 0), + (53, 55, 56, 0), + (19, 0, 21, 0), + (44, 44, 46, 0), + ] { + let resource = D3D12_RESOURCE_DESC { + Format: DXGI_FORMAT(own), + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + for dim in [ + D3D12_SRV_DIMENSION_TEXTURE2D, + D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + ] { + let mut words = [0; 10]; + words[0] = request; + words[1] = dim.0 as u32; + words[2] = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + words[4] = 2; // MostDetailedMip + words[5] = 3; // MipLevels + if dim == D3D12_SRV_DIMENSION_TEXTURE2DARRAY { + words[6] = 1; // FirstArraySlice + words[7] = 2; // ArraySize + } + let plane_word = if dim == D3D12_SRV_DIMENSION_TEXTURE2DARRAY { + 8 + } else { + 6 + }; + words[plane_word] = 1 - plane; + let view = texture_srv_desc(&resource, &words); + assert_eq!(view.Format.0, expected); + // SAFETY: read the member selected by the input view dimension. + unsafe { + if dim == D3D12_SRV_DIMENSION_TEXTURE2DARRAY { + let a = view.Anonymous.Texture2DArray; + assert_eq!( + ( + a.MostDetailedMip, + a.MipLevels, + a.FirstArraySlice, + a.ArraySize, + a.PlaneSlice + ), + (2, 3, 1, 2, plane) + ); + } else { + let a = view.Anonymous.Texture2D; + assert_eq!( + (a.MostDetailedMip, a.MipLevels, a.PlaneSlice), + (2, 3, plane) + ); + } + } + } + } + } } From 80314c3c1e99cbdbb79aa79e93bed2338f54e590 Mon Sep 17 00:00:00 2001 From: nathanbzrr Date: Tue, 24 Nov 2026 13:30:38 +0000 Subject: [PATCH 079/123] GPU: upload partially-resident streamed textures A streamed texture's pool maps the mips it has loaded and leaves the rest unmapped, like a tiled resource on the console. We only uploaded a texture whose every page was committed, so such textures stayed as they were made (black) until all their mips were resident: much of the world's material set never reached the host while you stood in it. Now a texture with any committed page is read: committed regions through the kernel (a page unmapped since the query reads as zeros), the others as zeros, one VirtualQuery per region rather than a failed read per page. A texture with nothing committed still keeps what it had. Idea from upstream #641 (f887f6a3, read_resident); written for our kernel-copy staging path, which that patch predates. (cherry picked from commit f887f6a3f7bcd083c072871fedc8a66d2a5b9fa8) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/texture.rs | 100 +++++++++++++++++++++++++++++- 1 file changed, 97 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 318d72d180..ea76b691a8 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -255,7 +255,14 @@ impl Staging { crate::copystat::add(crate::copystat::C::TexWatched, size as u64); return size; } - if !committed(self.memory, size) { + // A streamed texture can be partly resident: its pool maps the mips + // it has loaded and leaves the others unmapped, as tiled resources + // on the console (reads of an unmapped tile give zero, and titles + // clamp their level of detail to what is resident). Uploading only a + // fully committed texture left such textures as they were made, + // black, until every mip was in. A texture with nothing committed + // keeps what it had. + if !any_committed(self.memory, size) { #[cfg(feature = "diagnostics")] tracing::debug!( memory = ?self.memory, @@ -267,10 +274,13 @@ impl Staging { } // Read through the kernel, as above: the title may unmap the pages // (evicting a texture a big table lists) while we read them, and a - // direct read would fault. The copy is reused, not kept per texture. + // direct read would fault; unmapped pages read as zeros. The copy is + // reused, not kept per texture. SCRATCH.with_borrow_mut(|tiled| { tiled.resize(size, 0); - crate::host::copy_mapped(tiled.as_mut_ptr(), self.memory, size, false); + if !crate::host::read_into(self.memory, &mut tiled[..size]) { + read_resident(self.memory, &mut tiled[..size]); + } self.changed(last, tiled) }) } @@ -355,6 +365,59 @@ pub(crate) fn committed(at: *const u8, len: usize) -> bool { true } +/// Reads the committed regions of `[src, src + dst.len())` into `dst`, +/// zeros elsewhere: one query per region, not a failed read per page, for +/// a streamed texture most of which is not resident. +fn read_resident(src: *const u8, dst: &mut [u8]) { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + let base = src as usize; + let end = base.saturating_add(dst.len()); + let mut p = base; + while p < end { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + let stop = if n == 0 { + end + } else { + (info.BaseAddress as usize) + .saturating_add(info.RegionSize) + .clamp(p + 1, end) + }; + let piece = &mut dst[p - base..stop - base]; + if n != 0 && info.State == MEM_COMMIT { + // Through the kernel: a page unmapped since the query reads as + // zeros instead of faulting. + crate::host::copy_mapped(piece.as_mut_ptr(), p as *const u8, piece.len(), false); + } else { + piece.fill(0); + } + p = stop; + } +} + +/// Whether any page of `[at, at + len)` is committed. +fn any_committed(at: *const u8, len: usize) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + let mut p = at as usize; + let end = p.saturating_add(len); + while p < end { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + if n == 0 { + return false; + } + if info.State == MEM_COMMIT { + return true; + } + p = info.BaseAddress as usize + info.RegionSize; + } + false +} + /// The staging state of a title texture, made on first use. fn staging(resource: This, texture: &ID3D12Resource) -> Option> { let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); @@ -425,6 +488,37 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { #[cfg(test)] mod tests { + + /// A texture half of whose pages are committed reads those pages and + /// zeros for the rest; one with none committed is not read at all. + #[cfg(windows)] + #[test] + fn partly_resident_textures_read_what_is_mapped() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const PAGE: usize = 64 << 10; + // SAFETY: a fresh reservation, released below. + let base = unsafe { VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE, PAGE_READWRITE) }; + assert!(!base.is_null()); + let base = base.cast::(); + assert!(!any_committed(base, 4 * PAGE)); + // SAFETY: inside the reservation. + let second = unsafe { base.add(PAGE) }; + // SAFETY: inside the reservation. + assert!(!unsafe { VirtualAlloc(second.cast(), PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + // SAFETY: committed above. + unsafe { second.write_bytes(0xAB, PAGE) }; + assert!(any_committed(base, 4 * PAGE)); + assert!(!committed(base, 4 * PAGE)); + let mut out = vec![0x55; 4 * PAGE]; + read_resident(base, &mut out); + assert!(out[..PAGE].iter().all(|&b| b == 0)); + assert!(out[PAGE..2 * PAGE].iter().all(|&b| b == 0xAB)); + assert!(out[2 * PAGE..].iter().all(|&b| b == 0)); + // SAFETY: the reservation made above. + unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }; + } use super::*; /// A copied texture uploads again only once the title writes a watch From 4d3c4e6af2a1f978e9336d9fcfbf2a0bf482cc5f Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:33:48 +0000 Subject: [PATCH 080/123] GPU: spill oversized root signatures' user data to root CBVs A host root signature costs at most 64 dwords. Every stage's user data is root constants (one dword each) beside its root views (two each), so a pipeline whose vertex and pixel shaders read a lot of user data was refused ("host root signature refused") and every draw with it dropped. Over 64 dwords, the largest user data block now becomes a root CBV of the list's upload memory (two dwords) until the signature fits; the shader reads b0 the same either way. Nothing changes under the limit. Idea from upstream #644 (6fa53a51); its second phase (merging root views across stages) is not needed for our one-table root SRVs. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 31 ++++++-- crates/victory-gpu/src/pipeline/host.rs | 101 ++++++++++++++++++++++++ 2 files changed, 127 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d01255e54d..4e37534667 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -633,12 +633,33 @@ impl State { None => self.user_value(compute, u.slot, u.root, u.dword), }; } - // SAFETY: an open list; `values` covers the parameter. - unsafe { - if compute { - l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + if stage.user_data_cbv { + // Spilled (see the host root signature): the values in + // upload memory the list keeps until it is reset. + if let Some((gpu, to)) = list.scratch(u64::from(dwords) * 4) { + // SAFETY: `to` is at least `dwords` mapped dwords. + unsafe { + std::ptr::copy_nonoverlapping(values.as_ptr(), to.cast(), values.len()) + }; + // SAFETY: an open list; a 256-byte aligned live address. + unsafe { + if compute { + l.SetComputeRootConstantBufferView(param, gpu); + } else { + l.SetGraphicsRootConstantBufferView(param, gpu); + } + } } else { - l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + once!("no upload memory for user data: left unset"); + } + } else { + // SAFETY: an open list; `values` covers the parameter. + unsafe { + if compute { + l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + } else { + l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + } } } } diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index a1c01d4c2c..36d387406d 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -253,6 +253,10 @@ pub(crate) struct Stage { pub(crate) shader: Arc, /// The root parameter of its user data, and its size in dwords. pub(crate) user_data: Option<(u32, u32)>, + /// Its user data is a root CBV of upload memory, not root constants: + /// the signature would cost more than the host's 64 dwords otherwise + /// (see [`fit_root_signature`]). + pub(crate) user_data_cbv: bool, /// Root parameters of its root views: (title root parameter, ours). pub(crate) root_cbvs: Vec<(u8, u32)>, pub(crate) root_srvs: Vec<(u8, u32)>, @@ -348,6 +352,7 @@ impl HostPipeline { let mut stage = Stage { shader: shader.clone(), user_data: None, + user_data_cbv: false, root_cbvs: Vec::new(), root_srvs: Vec::new(), }; @@ -442,6 +447,7 @@ impl HostPipeline { } bound.push(stage); } + fit_root_signature(&mut params, &mut bound); let (root, root_blob) = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { Ok(root) => root, @@ -692,6 +698,66 @@ fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec { .to_vec() } +/// The most a host root signature may cost, in dwords. +const MAX_ROOT_COST: u32 = 64; + +/// What a root parameter costs in the host's 64 dwords. +fn root_param_cost(p: &D3D12_ROOT_PARAMETER1) -> u32 { + match p.ParameterType { + // SAFETY: the member the type names. + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS => unsafe { p.Anonymous.Constants.Num32BitValues }, + D3D12_ROOT_PARAMETER_TYPE_CBV + | D3D12_ROOT_PARAMETER_TYPE_SRV + | D3D12_ROOT_PARAMETER_TYPE_UAV => 2, + _ => 1, + } +} + +/// Fits the signature in the host's 64 dwords: a pipeline whose stages' +/// user data and root views cost more (a pixel shader with 40 dwords of +/// user data after a vertex shader with 20, say) was refused, and every +/// draw with it dropped. The largest user data block moves to a root CBV +/// (2 dwords; the shader reads `b0` the same either way) until it fits. +/// Idea from upstream #644 (6fa53a51). +fn fit_root_signature(params: &mut [D3D12_ROOT_PARAMETER1], stages: &mut [Stage]) { + let user: Vec<_> = stages.iter().map(|s| s.user_data).collect(); + for i in spill_user_data(params, &user) { + stages[i].user_data_cbv = true; + } +} + +/// The stages (indices into `user`, each stage's user data parameter and +/// dwords) whose user data [`fit_root_signature`] moves to a root CBV, +/// changing their parameters in `params`. +fn spill_user_data(params: &mut [D3D12_ROOT_PARAMETER1], user: &[Option<(u32, u32)>]) -> Vec { + let mut spilled = Vec::new(); + while params.iter().map(root_param_cost).sum::() > MAX_ROOT_COST { + let Some((i, param)) = user + .iter() + .enumerate() + .filter(|(i, u)| !spilled.contains(i) && u.is_some_and(|(_, n)| n > 2)) + .max_by_key(|(i, u)| (u.map_or(0, |(_, n)| n), std::cmp::Reverse(*i))) + .and_then(|(i, u)| Some((i, u.as_ref()?.0))) + else { + break; + }; + let visibility = params[param as usize].ShaderVisibility; + params[param as usize] = D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_CBV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC, + }, + }, + ShaderVisibility: visibility, + }; + spilled.push(i); + } + spilled +} + fn root_signature( device: &ID3D12Device, params: &[D3D12_ROOT_PARAMETER1], @@ -741,6 +807,41 @@ fn root_signature( #[cfg(test)] mod tests { + + /// Over 64 dwords, the largest user data blocks become root CBVs until + /// the signature fits; under it nothing changes. + #[test] + fn oversized_root_signatures_spill_user_data() { + let constants = |n| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Num32BitValues: n, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let cbv = D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_CBV, + ..Default::default() + }; + let cost = |p: &[D3D12_ROOT_PARAMETER1]| p.iter().map(root_param_cost).sum::(); + // VS 20 + 2 root CBVs, PS 40: 64 + 4. + let mut params = vec![constants(20), cbv, cbv, constants(40)]; + assert_eq!(cost(¶ms), 64); + assert!(spill_user_data(&mut params, &[Some((0, 20)), Some((3, 40))]).is_empty()); + params.push(cbv); + assert_eq!(spill_user_data(&mut params, &[Some((0, 20)), Some((3, 40))]), [1]); + assert_eq!(params[3].ParameterType, D3D12_ROOT_PARAMETER_TYPE_CBV); + assert_eq!(params[0].ParameterType, D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS); + assert_eq!(cost(¶ms), 28); + // Both, when one is not enough. + let mut params = vec![constants(63), constants(63)]; + assert_eq!(spill_user_data(&mut params, &[Some((0, 63)), Some((1, 63))]), [0, 1]); + assert_eq!(cost(¶ms), 4); + } use std::path::{Path, PathBuf}; use std::sync::atomic::Ordering; From e217770e04f27d6fc815082cf90c5370b85bf37d Mon Sep 17 00:00:00 2001 From: Halfect <265824964+Halfect@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:14:15 +0800 Subject: [PATCH 081/123] Shaders: guard conditional exports (cherry picked from commit 1bd52dcc9e4d2f863123f32a944c7ee4412c6852) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 9 ++-- crates/victory-shader/src/emit/mod.rs | 71 +++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 6aaba94de6..c7216ce80b 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -8007,13 +8007,12 @@ impl<'a> Lower<'a> { } let guard = self.guard(b, i)?; let mesh = self.s.mesh.is_some(); + let pixel_done = self.s.pixel && e.done; let c = self.cur; if let Some(g) = guard && !mesh + && pixel_done { - if !(e.done && self.s.pixel) { - return Err("a conditional export"); - } let t = self.s.m.bool(true); let kill = self.s.m.bin(c, Bin::Xor, g, t); self.s @@ -8147,7 +8146,9 @@ impl<'a> Lower<'a> { return Err("a 16-bit output the stage data does not mark"); } // A mesh lane writes its own vertex or primitive, where it exports. - let at = if mesh { + // Other conditional exports also run only for their enabled lanes; + // a pixel's final `done` export instead discards the other lanes. + let at = if mesh || !pixel_done { self.begin_guarded(guard) } else { None diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 2b4f522e08..48d276d084 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1052,6 +1052,77 @@ mod tests { translate_stored(&[0xD5C0_0100, 0x0000_0101]).unwrap(); translate_stored(&[0xD5BF_0000, 0x2000_0101]).unwrap(); } + + #[test] + fn a_conditional_pixel_export_is_guarded() { + // Only lanes for which v0 is zero export a colour. This is not the + // final `done` export, so inactive lanes must keep their old output. + let words: [u32; 6] = [ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE80_3C6A, // s_and_saveexec_b32 s0, vcc_lo + 0xF800_000F, + 0x0302_0102, // exp mrt0, v2, v1, v2, v3 + 0x887E_007E, // s_or_b32 exec_lo, exec_lo, s0 + 0xBF81_0000, // s_endpgm + ]; + let native = super::NativeProgram { + stage: super::HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: crate::native::StageIo::Ps { + inputs: vec![], + input_addr: 1 << 8, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let position = SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(0), + col: 0, + cols: 4, + usage: 1, + half: false, + }; + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + let isg1 = super::container::signature(&[position], true); + let osg1 = super::container::signature(&[target], false); + let bytes = + crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]); + let c = super::Container::parse(&bytes).unwrap(); + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let emitted = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); + + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut emitted.dxil.clone()).unwrap(); + } + #[cfg(not(windows))] + drop(emitted); + } } #[cfg(test)] From 3e602fe6509f30e6c5eaf7890f2ed2fb62e3d60d Mon Sep 17 00:00:00 2001 From: Halfect <265824964+Halfect@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:45:56 +0800 Subject: [PATCH 082/123] Shaders: zero unavailable mixed-precision FMA halves (cherry picked from commit 81fb96eb74be475edd872fd4f040b0b076c29455) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 8 ++- crates/victory-shader/src/emit/mod.rs | 92 +++++++++++++++++++++++++ 2 files changed, 97 insertions(+), 3 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c7216ce80b..9110c3fab0 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5321,9 +5321,11 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = v.dst else { return Err("a mixed-precision result"); }; - let old = match inst.read(Reg::V(reg)) { - Some(o) => self.i32_of(o)?, - None => self.s.m.i32(0), + // An unavailable old value is zero, as for other partial + // writes; never resurrect bits from before a full write. + let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + _ => self.s.m.i32(0), }; let h = self.f16_nearest(r); let (keep, h) = if name == "v_fma_mixhi_f16" { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 48d276d084..46b22af41a 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1123,6 +1123,98 @@ mod tests { #[cfg(not(windows))] drop(emitted); } + + /// `v_interp_p1ll_f16` writes all 32 bits; it does not preserve the old + /// high half. When a paired p2 represents the interpolation, a following + /// mixed-precision FMA must therefore zero an unavailable preserved half, + /// not resurrect bits from before p1ll. Cover both result halves. + #[test] + fn mixed_precision_fmas_accept_an_unavailable_interpolation_half() { + fn translate(opcode: u32) { + let words = [ + 0x7E10_0280u32, // v_mov_b32 v8, 0 + 0x7E20_0280, // v_mov_b32 v16, 0 + 0x7E16_02FF, + 0xFFFF_0000, // v_mov_b32 v11, 0xffff0000 + 0xD742_000B, + 0x0002_0102, // v_interp_p1ll_f16 v11, v0, attr2.x high + 0xD75A_000F, + 0x042E_0302, // v_interp_p2_f16 v15, v1, attr2.x, v11 high + opcode, + 0x0A02_2108, // v_fma_mix{lo,hi}_f16 v11, sel_lo(v8), v16, 0 + 0xF800_1801, + 0x0000_000B, // exp mrt0, v11, off, off, off done vm + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 17, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: 2, + mask: 3, + attr: 2, + flat: false, + fp16: true, + pack2: true, + row2: 2, + }], + input_addr: 2, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let input = SigElement { + name: "TEXCOORD".into(), + index: 0, + kind: 0, + comp: 9, + interp: 0, + row: Some(2), + col: 0, + cols: 2, + usage: 0, + half: false, + }; + let output = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let isg1 = super::container::signature(&[input], true); + let osg1 = super::container::signature(&[output], false); + let bytes = + crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let mut host = emit(&c, &native, &p, &st, &io, &res).unwrap(); + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut host.dxil).unwrap(); + } + } + + for opcode in [0xCC21_000B, 0xCC22_000B] { + translate(opcode); + } + } } #[cfg(test)] From ad5ecc313ad7d71579f87c3e5cffae67122a4046 Mon Sep 17 00:00:00 2001 From: nathanbzrr Date: Tue, 24 Nov 2026 03:04:47 -0300 Subject: [PATCH 083/123] Shaders: fix whole-wave EXEC inline constant sign-extension and prefix lane validation (cherry picked from commit 12eba495039d8018eb6959be95fcc10e387b7e33) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/wave.rs | 315 +++++++++++++++++++++++-- 1 file changed, 293 insertions(+), 22 deletions(-) diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index 011ca22705..ca9b6e3489 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -253,11 +253,11 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { let Some(k) = lo else { return shapes(vec, uni, wave); }; - exec = if name == "s_mov_b64" { + exec = (if name == "s_mov_b64" { k } else { - exec & !0xFFFF_FFFF | k & 0xFFFF_FFFF - }; + (exec & !0xFFFF_FFFF) | (k & 0xFFFF_FFFF) + }) & all; continue; } if inst.write(Reg::S(EXEC + 1)).is_some() { @@ -268,7 +268,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { else { return shapes(vec, uni, wave); }; - exec = exec & 0xFFFF_FFFF | k << 32; + exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all; continue; } if let Fields::Sop { src, .. } = &inst.fields { @@ -501,15 +501,18 @@ fn constant(inst: &Inst) -> Option { let Fields::Sop { src, .. } = &inst.fields else { return None; }; + let wide = inst.name() == "s_mov_b64"; match *src.first()? { - Operand::Const(c) => { + Operand::Scalar { code: NULL, .. } => Some(0), + Operand::Const(c @ 128..=208) => { let x = crate::resource::inline(c)?; - Some(if (x as i32) < 0 { - u64::MAX + Some(if wide { + i64::from(x as i32) as u64 } else { u64::from(x) }) } + Operand::Const(c) if !wide => crate::resource::inline(c).map(u64::from), Operand::Literal(x) => Some(u64::from(x)), _ => None, } @@ -584,7 +587,8 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { }; } // Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive). - let mut found: Option<(Op, Value, Value, u32, bool)> = None; + let mut meta: Option<(Value, Value, u32, bool)> = None; + let mut op_found: Option = None; for (l, &s) in lanes.iter().enumerate() { let below = (1u64 << l) - 1; let (op, src, mask, ident, set) = match s { @@ -599,28 +603,40 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { Sym::K(_) if l == 0 => continue, _ => return None, }; - let inclusive = set == below | 1 << l; + let inclusive = set == below | (1u64 << l); if !inclusive && set != below { return None; } - let op = match (op, found) { - (Some(o), _) => o, - (None, Some(f)) => f.0, - (None, None) => continue, - }; - let me = (op, src, mask, ident, inclusive); - match found { - None => found = Some(me), - Some(f) if f == me => {} + if l == 0 && !inclusive { + return None; + } + if op.is_none() && set.count_ones() != 1 { + return None; + } + let lane_meta = (src, mask, ident, inclusive); + match meta { + None => meta = Some(lane_meta), + Some(prev) if prev == lane_meta => {} _ => return None, } + if let Some(o) = op { + match op_found { + None => op_found = Some(o), + Some(prev) if prev == o => {} + _ => return None, + } + } } - let (op, src, mask, ident, inclusive) = found?; - if let Sym::K(k) = lanes[0] - && (inclusive || k != ident) - { + let (src, mask, ident, inclusive) = meta?; + let op = op_found?; + if !op.identity(ident) { return None; } + match lanes[0] { + Sym::K(k) if !inclusive && k == ident => {} + Sym::Red { .. } if inclusive => {} + _ => return None, + } Some(Shape::Prefix(op, src, mask, ident, inclusive)) } @@ -628,6 +644,45 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { mod tests { use super::*; + const S_ENDPGM: u32 = 0xBF81_0000; + + const fn sop1(sdst: u8, op: u8, ssrc0: u8) -> u32 { + 0xBE80_0000 | (sdst as u32) << 16 | (op as u32) << 8 | ssrc0 as u32 + } + + const fn vop1(vdst: u8, op: u8, src0: u16) -> u32 { + (0x3F << 25) | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn vop2(vdst: u8, op: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn dpp16(vsrc0: u8, ctrl: u16, row_mask: u8, bank_mask: u8, bound_ctrl: bool) -> u32 { + (row_mask as u32) << 28 + | (bank_mask as u32) << 24 + | (bound_ctrl as u32) << 19 + | (ctrl as u32) << 8 + | vsrc0 as u32 + } + + const fn vop3(vdst: u8, op: u16, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + [ + 0xD400_0000 | (op as u32) << 16 | vdst as u32, + (src0 as u32 & 0x1FF) | ((src1 as u32 & 0x1FF) << 9) | ((src2 as u32 & 0x1FF) << 18), + ] + } + + fn build(words: &[u32], wave64: bool) -> Program { + let code: Vec = words + .iter() + .copied() + .chain(std::iter::once(S_ENDPGM)) + .flat_map(u32::to_le_bytes) + .collect(); + crate::ir::build(&code, wave64, 256).unwrap() + } + #[test] fn dpp_lanes_follow_the_isa() { // row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16. @@ -727,4 +782,220 @@ mod tests { Some(&Shape::Active(Op::AddU, x, saved, 0)) ); } + + #[test] + fn constant_decodes_width_and_inline_kinds() { + let b64 = 0x04; + let b32 = 0x03; + let check = |words: &[u32], wave64: bool| -> Option { + let p = build(words, wave64); + constant(&p.blocks[0].insts[0]) + }; + + assert_eq!( + check(&[sop1(EXEC, b64, 194)], true), + Some(0xFFFF_FFFF_FFFF_FFFE) + ); + assert_eq!( + check(&[sop1(EXEC, b64, 196)], true), + Some(0xFFFF_FFFF_FFFF_FFFC) + ); + assert_eq!( + check(&[sop1(EXEC, b64, 208)], true), + Some(0xFFFF_FFFF_FFFF_FFF0) + ); + assert_eq!(check(&[sop1(EXEC, b64, 193)], true), Some(u64::MAX)); + assert_eq!(check(&[sop1(EXEC, b64, NULL)], true), Some(0)); + assert_eq!(check(&[sop1(EXEC, b64, 243)], true), None); + assert_eq!( + check(&[sop1(EXEC, b64, 255), 0x1234_5678], true), + Some(0x1234_5678) + ); + + assert_eq!(check(&[sop1(EXEC, b32, 194)], false), Some(0xFFFF_FFFE)); + assert_eq!(check(&[sop1(EXEC, b32, 243)], false), Some(0xBF80_0000)); + assert_eq!(check(&[sop1(EXEC, b32, NULL)], false), Some(0)); + assert_eq!( + check(&[sop1(EXEC, b32, 255), 0x1234_5678], false), + Some(0x1234_5678) + ); + assert_eq!(check(&[sop1(EXEC, b32, 0)], false), None); + } + + #[test] + fn exec_minus_two_masks_lane_zero_and_enforces_dpp_guard() { + for wave64 in [false, true] { + let mut w = Vec::new(); + let save_op = if wave64 { 0x25 } else { 0x3D }; + let mov_exec = if wave64 { 0x04 } else { 0x03 }; + let push_exec = |w: &mut Vec, k: u8| w.push(sop1(EXEC, mov_exec, k)); + let push_exec_lit = |w: &mut Vec, lit: u32| { + w.push(sop1(EXEC, mov_exec, 255)); + w.push(lit); + }; + + w.push(sop1(0, save_op, 193)); + w.extend(vop3(1, 0x101, 128, 256, 0)); + for shift in [1u16, 2, 4, 8] { + w.push(vop2(1, 0x25, 0xFA, 1)); + w.push(dpp16(1, 0x110 + shift, 0xF, 0xF, false)); + } + w.extend(vop3(2, 0x360, 257, 128 + 15, 0)); + push_exec_lit(&mut w, 0xFFFF_0000); + w.push(vop2(1, 0x25, 2, 1)); + + if wave64 { + w.extend(vop3(2, 0x360, 257, 128 + 31, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0x0000_FFFF); + w.push(vop2(1, 0x25, 2, 1)); + + w.extend(vop3(2, 0x360, 257, 128 + 47, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0xFFFF_0000); + w.push(vop2(1, 0x25, 2, 1)); + } + + push_exec(&mut w, 193); + w.push(vop1(3, 0x01, 257)); + w.push(vop1(3, 0x01, 0xFA)); + w.push(dpp16(1, 0x111, 0xF, 0xF, false)); + + w.extend(vop3(2, 0x360, 257, 128 + 15, 0)); + push_exec_lit(&mut w, 0x0001_0000); + w.push(vop1(3, 0x01, 2)); + + if wave64 { + w.extend(vop3(2, 0x360, 257, 128 + 31, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 129)); + w.push(vop1(3, 0x01, 2)); + + w.extend(vop3(2, 0x360, 257, 128 + 47, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0x0001_0000); + w.push(vop1(3, 0x01, 2)); + } + + push_exec(&mut w, 193); + w.push(vop1(2, 0x01, 128)); + w.push(vop1(5, 0x01, 135)); + push_exec(&mut w, 194); + w.push(vop1(2, 0x01, 259)); + w.push(vop1(4, 0x01, 0xFA)); + w.push(dpp16(5, 0xE4, 0xF, 0xF, false)); + w.push(sop1(EXEC, mov_exec, 0)); + + let p = build(&w, wave64); + let insts = &p.blocks[0].insts; + let saved = insts[0].write(Reg::S(0)).unwrap(); + let v0_in = p + .inputs + .iter() + .find_map(|&(r, v)| (r == Reg::V(0)).then_some(v)) + .unwrap(); + let v2_val = insts[insts.len() - 4].write(Reg::V(2)).unwrap(); + let v4_val = insts[insts.len() - 3].write(Reg::V(4)).unwrap(); + let sec = §ions(&p, 0)[&0]; + assert_eq!( + sec.shapes.get(&v2_val), + Some(&Shape::Prefix(Op::AddU, v0_in, saved, 0, false)) + ); + assert_eq!(sec.shapes.get(&v4_val), None); + } + } + + #[test] + fn wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp() { + let w = [ + sop1(0, 0x3D, 193), + vop1(1, 0x01, 135), + sop1(EXEC, 0x04, 193), + vop1(2, 0x01, 0xFA), + dpp16(1, 0xE4, 0xF, 0xF, false), + sop1(EXEC + 1, 0x03, 193), + vop1(3, 0x01, 0xFA), + dpp16(1, 0xE4, 0xF, 0xF, false), + sop1(EXEC, 0x03, 0), + ]; + let p = build(&w, false); + let insts = &p.blocks[0].insts; + let v2_val = insts[3].write(Reg::V(2)).unwrap(); + let v3_val = insts[5].write(Reg::V(3)).unwrap(); + let sec = §ions(&p, 0)[&0]; + assert_eq!(sec.shapes.get(&v2_val), Some(&Shape::K(7))); + assert_eq!(sec.shapes.get(&v3_val), Some(&Shape::K(7))); + } + + #[test] + fn per_lane_prefix_soundness() { + let (v0, v_other, m0, m_other) = (Value(1), Value(2), Value(3), Value(4)); + let red = |op: Option, src: Value, mask: Value, ident: u32, lanes: u64| Sym::Red { + op, + src, + mask, + ident, + lanes, + }; + + for (wave, all) in [(32usize, u64::from(u32::MAX)), (64usize, u64::MAX)] { + let below_mask = |l: usize| if l == 0 { 0 } else { (1u64 << l) - 1 }; + + let mut valid_inc: Vec = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l) | (1u64 << l))) + .collect(); + valid_inc[0] = red(None, v0, m0, 0, 1); + assert_eq!( + per_lane(&valid_inc, all), + Some(Shape::Prefix(Op::AddU, v0, m0, 0, true)) + ); + + let mut valid_exc: Vec = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l))) + .collect(); + valid_exc[0] = Sym::K(0); + valid_exc[1] = red(None, v0, m0, 0, 1); + assert_eq!( + per_lane(&valid_exc, all), + Some(Shape::Prefix(Op::AddU, v0, m0, 0, false)) + ); + + let mut mixed_other_src = valid_exc.clone(); + mixed_other_src[0] = red(None, v_other, m0, 0, 1); + assert_eq!(per_lane(&mixed_other_src, all), None); + + let mut mixed_same_src = valid_exc.clone(); + mixed_same_src[0] = red(None, v0, m0, 0, 1); + assert_eq!(per_lane(&mixed_same_src, all), None); + + let mut exc_bad_lane1_src = valid_exc.clone(); + exc_bad_lane1_src[1] = red(None, v_other, m0, 0, 1); + assert_eq!(per_lane(&exc_bad_lane1_src, all), None); + + let mut exc_bad_lane1_set = valid_exc.clone(); + exc_bad_lane1_set[1] = red(None, v0, m0, 0, 0b11); + assert_eq!(per_lane(&exc_bad_lane1_set, all), None); + + for bad0 in [ + red(None, v0, m0, 1, 1), + red(None, v_other, m0, 0, 1), + red(None, v0, m_other, 0, 1), + red(None, v0, m0, 0, 0), + Sym::K(0), + ] { + let mut bad_inc = valid_inc.clone(); + bad_inc[0] = bad0; + assert_eq!(per_lane(&bad_inc, all), None); + } + + let mut bad_ident: Vec = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 1, below_mask(l) | (1u64 << l))) + .collect(); + bad_ident[0] = red(None, v0, m0, 1, 1); + assert_eq!(per_lane(&bad_ident, all), None); + } + } } From 0782abbc17d6fb13338ddb8a79fc1ec4d7ebb05b Mon Sep 17 00:00:00 2001 From: LAKSHYA-cmd-tech <218701667+LAKSHYA-cmd-tech@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:36:22 +0000 Subject: [PATCH 084/123] Shaders: lower image_gather4_l and image_gather4_l_o The LOD form of a gather stopped its program. DXIL gathers from level 0 and has no LOD operand, so the console's LOD is not read: exact for the level-0 gathers titles make of shadow maps and G-buffers. From upstream #694 (0beec4d6, #293, #653); its image_sample_cl / image_sample_b_cl / image_sample_d_cl halves are already in this tree. The test also covers image_sample_d_cl. (cherry picked from commit 0beec4d64361a698b7550b30232df8e9c4114984) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 68 ++++++++++++++++++++++++- crates/victory-shader/src/emit/mod.rs | 1 + 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 9110c3fab0..05ed11e8be 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -7179,7 +7179,11 @@ impl<'a> Lower<'a> { "image_get_lod" if self.s.pixel => (81, true), // Implicit derivatives: pixel shaders only. "image_sample_c" | "image_sample_c_cl" if self.s.pixel => (64, true), - "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" => (73, true), + // The LOD of `_l` is not read: DXIL gathers from level 0, the + // one a title's gathers of shadow maps and G-buffers name. + // shortcut: a gather of a lower level reads level 0. + "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" + | "image_gather4_l_o" => (73, true), "image_load" | "image_load_mip" => (66, false), "image_get_resinfo" => (72, false), _ => return Err(name), @@ -8586,6 +8590,68 @@ mod tests { lower_words(words).map(|_| ()) } + /// image_sample_d_cl and image_gather4_l translate (upstream #694: + /// #293, #653), with the image table in user data 8, the sampler's in 9. + #[test] + fn image_sample_d_cl_and_gather4_l_translate() { + use crate::native::{RootParam, RootType}; + let param = |user_data: u8| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot: 0, + }; + let run = |image: [u32; 2]| { + let words = [ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF408_0204, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[8:9], null + 0xF40C_0001, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + image[0], + image[1], + S_ENDPGM, + ]; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![param(8), param(9)], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + host_wave64: true, + }) + .map(|_| ()) + }; + // image_sample_d_cl v[0:3], v[2:8], s[0:7], s[8:11] + run([0xF08C_0F08, 0x0040_0002]).unwrap(); + // image_gather4_l v[0:3], v[2:4], s[0:7], s[8:11] + run([0xF110_0108, 0x0040_0002]).unwrap(); + } + #[test] fn med3_f32_tests_nan_on_bits_not_a_float_compare() { // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 46b22af41a..2f59c7e95f 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1202,6 +1202,7 @@ mod tests { let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); + #[cfg_attr(not(windows), allow(unused_mut, unused_variables))] let mut host = emit(&c, &native, &p, &st, &io, &res).unwrap(); #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( From 9afaf1216d601c5a1da52759225dc55ccae0c1a4 Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:00:07 +0000 Subject: [PATCH 085/123] GPU: the depth bounds test (pipeline streams and OMSetDepthBounds) A title's DEPTH_STENCIL1 subobject lost its depth bounds test (the host pipeline took the plain description) and OMSetDepthBounds was ignored, so lights and fog volumes that rely on the test to skip pixels outside their depth range shaded the sky and everything behind them. Now a vertex or mesh pipeline whose stream enables the test is made as a stream with DEPTH_STENCIL1 (vertex pipelines kept the plain description otherwise, so their library entries stay valid; the name of one with the test says so), and OMSetDepthBounds reaches the host list, clamped to 0..=1 and in order. A host without the test (DepthBoundsTestSupported) says so once and draws as before. Ideas from upstream #849 (Xvania7 c47632fc, Raxstreams 520d629e), written for our stream builder and list table. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 31 +++ crates/victory-gpu/src/list.rs | 10 +- crates/victory-gpu/src/pipeline/host.rs | 251 +++++++++++++++++++++--- 3 files changed, 262 insertions(+), 30 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 4e37534667..9aee5d7dd7 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1813,6 +1813,15 @@ mod clear_state_tests { #[cfg(all(test, feature = "diagnostics"))] mod tests { + + /// Depth bounds reach the host in 0..=1 and in order. + #[test] + fn depth_bounds_are_clamped_and_ordered() { + assert_eq!(depth_range(0.25, 0.75), (0.25, 0.75)); + assert_eq!(depth_range(-1.0, 2.0), (0.0, 1.0)); + assert_eq!(depth_range(f32::NAN, f32::NAN), (0.0, 1.0)); + assert_eq!(depth_range(0.9, 0.1), (0.1, 0.1)); + } use super::*; #[test] @@ -2020,3 +2029,25 @@ mod tests { assert_eq!(pixels, [[0, 255, 0, 255]; (SIDE * SIDE) as usize]); } } + +/// `OMSetDepthBounds`, if the host has the test: bounds in 0..=1, the low +/// one first, as the host requires (its debug layer refuses others). +pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) { + if !crate::pipeline::host::depth_bounds_supported() { + return; + } + let (min, max) = depth_range(min, max); + if let Ok(list1) = list.list.cast::() { + // SAFETY: an open list. + unsafe { list1.OMSetDepthBounds(min, max) }; + } +} + +/// Depth bounds the host takes: NaN as the full range, each in 0..=1, in +/// order. +fn depth_range(min: f32, max: f32) -> (f32, f32) { + let unit = |x: f32, nan: f32| if x.is_nan() { nan } else { x.clamp(0.0, 1.0) }; + let (min, max) = (unit(min, 0.0), unit(max, 1.0)); + (min.min(max), max) +} + diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 42b222fa59..eeae581606 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1554,6 +1554,13 @@ mod state { crate::draw::stencil_ref(&list, reference); } } + /// `OMSetDepthBounds`: for pipelines with the depth bounds test (see + /// the host pipeline); lists start at 0..1, as the host's do. + pub(super) extern "system" fn depth_bounds(this: This, min: f32, max: f32) { + if let Some(list) = host_list(this) { + crate::draw::depth_bounds(&list, min, max); + } + } pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { with_state(this, |_, s| s.set_heaps(items(heaps, count))); } @@ -1732,6 +1739,7 @@ mod state { pub(super) use super::draw as dispatch_mesh; pub(super) use super::draw as dispatch_mesh_x; pub(super) use super::ignored_state as blend_factor; + pub(super) use super::ignored_state as depth_bounds; pub(super) use super::ignored_state as compute_constant; pub(super) use super::ignored_state as compute_constants; pub(super) use super::ignored_state as compute_table; @@ -1961,7 +1969,7 @@ const METHODS: [(usize, *const ()); 59] = [ (58, end_event as *const ()), // 0x1d0 (59, execute_indirect as *const ()), // 0x1d8 indirect (60, copy_memory as *const ()), // 0x1e0 - (68, ignored_state as *const ()), // 0x220 depth bounds + (68, state::depth_bounds as *const ()), // 0x220 depth bounds (69, write32 as *const ()), // 0x228 (70, write64 as *const ()), // 0x230 (71, wait_value as *const ()), // 0x238, 32 bits diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 36d387406d..04ad420ada 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -24,6 +24,9 @@ pub(crate) struct GraphicsState { sample_mask: u32, rasterizer: D3D12_RASTERIZER_DESC, depth: D3D12_DEPTH_STENCIL_DESC, + /// The depth bounds test (`DEPTH_STENCIL1`): pixels whose depth buffer + /// value lies outside the list's bounds are dropped. + depth_bounds: bool, /// Input elements, their names pointing into `names`. inputs: Vec, names: Vec, @@ -75,6 +78,7 @@ impl Default for GraphicsState { BackFace: keep, ..Default::default() }, + depth_bounds: false, inputs: Vec::new(), names: Vec::new(), strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, @@ -103,12 +107,13 @@ impl GraphicsState { 8 => self.blend = data.cast::().read_unaligned(), 9 => self.sample_mask = data.cast::().read_unaligned(), 10 => self.rasterizer = data.cast::().read_unaligned(), - 11 => self.depth = data.cast::().read_unaligned(), + 11 => { + self.depth = data.cast::().read_unaligned(); + self.depth_bounds = false; + } 21 => { - // shortcut: the depth bounds test is dropped (the host - // pipeline uses the plain description); bring it back - // with a stream if a title enables it. let d = data.cast::().read_unaligned(); + self.depth_bounds = d.DepthBoundsTestEnable.as_bool(); self.depth = D3D12_DEPTH_STENCIL_DESC { DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, @@ -199,7 +204,30 @@ impl GraphicsState { self.targets, self.depth_format.0, self.samples - ) + ) + if self.bounds() { " depth bounds" } else { "" } + } + + /// Whether the host pipeline tests depth bounds: the title's stream + /// enables the test and the host has it (else it is left out, as + /// before: pixels the test would drop are drawn). + pub(crate) fn bounds(&self) -> bool { + self.depth_bounds && depth_bounds_supported() + } + + /// The depth description with the depth bounds test on. + fn depth1(&self) -> D3D12_DEPTH_STENCIL_DESC1 { + let d = self.depth; + D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: d.DepthEnable, + DepthWriteMask: d.DepthWriteMask, + DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, + StencilReadMask: d.StencilReadMask, + StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, + BackFace: d.BackFace, + DepthBoundsTestEnable: true.into(), + } } /// The vertex buffer slots the input layout reads. @@ -570,13 +598,17 @@ impl HostPipeline { &[&code_bytes(&code(0)), &code_bytes(&code(1))], &state, ); - let made = super::library::pipeline( - &name, - // SAFETY: the description points at live data. - |library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) }, - // SAFETY: as above. - || unsafe { host.device.CreateGraphicsPipelineState(&desc) }, - ); + let made = if g.bounds() { + bounds_pipeline(&host.device, &desc, &root, g, &name) + } else { + super::library::pipeline( + &name, + // SAFETY: the description points at live data. + |library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { host.device.CreateGraphicsPipelineState(&desc) }, + ) + }; let pso = match made { Ok(pso) => pso, Err(e) => { @@ -627,20 +659,63 @@ fn mesh_pipeline( ps: D3D12_SHADER_BYTECODE, g: &GraphicsState, name: &str, +) -> windows::core::Result { + if g.bounds() { + let depth = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, g.depth1()); + mesh_stream(device, root, ms, ps, g, name, depth) + } else { + let depth = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth); + mesh_stream(device, root, ms, ps, g, name, depth) + } +} + +/// A stream subobject: its type, then its description, pointer-aligned. +#[repr(C, align(8))] +struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + +/// Makes the pipeline of a whole `stream`, or loads it from the library +/// under `name`. +fn stream_pipeline( + device: &ID3D12Device, + stream: &mut S, + name: &str, +) -> windows::core::Result { + use windows::core::Interface; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: std::ptr::from_mut(stream).cast(), + }; + let device = device.cast::()?; + super::library::pipeline( + name, + // SAFETY: the stream holds whole subobjects pointing at live data. + |library, name| unsafe { library.LoadPipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { device.CreatePipelineState(&desc) }, + ) +} + +/// [`mesh_pipeline`] with the depth subobject `depth` (with or without +/// the depth bounds test). +fn mesh_stream( + device: &ID3D12Device, + root: &ID3D12RootSignature, + ms: D3D12_SHADER_BYTECODE, + ps: D3D12_SHADER_BYTECODE, + g: &GraphicsState, + name: &str, + depth: Sub, ) -> windows::core::Result { use windows::core::Interface; - /// A stream subobject: its type, then its description, pointer-aligned. - #[repr(C, align(8))] - struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); #[repr(C)] - struct Stream { + struct Stream { root: Sub<*mut std::ffi::c_void>, ms: Sub, ps: Sub, blend: Sub, mask: Sub, raster: Sub, - depth: Sub, + depth: Sub, targets: Sub, dsv: Sub, samples: Sub, @@ -659,7 +734,7 @@ fn mesh_pipeline( g.sample_mask, ), raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), - depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth), + depth, targets: Sub( D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets, @@ -674,18 +749,106 @@ fn mesh_pipeline( D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, ), }; - let desc = D3D12_PIPELINE_STATE_STREAM_DESC { - SizeInBytes: size_of::(), - pPipelineStateSubobjectStream: (&raw mut stream).cast(), + stream_pipeline(device, &mut stream, name) +} + +/// A vertex pipeline with the depth bounds test, which the plain +/// description cannot name: the same state as a stream, its depth +/// subobject `DEPTH_STENCIL1`. +fn bounds_pipeline( + device: &ID3D12Device, + desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + root: &ID3D12RootSignature, + g: &GraphicsState, + name: &str, +) -> windows::core::Result { + use windows::core::Interface; + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + vs: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + inputs: Sub, + strip_cut: Sub, + topology: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + } + let mut targets = D3D12_RT_FORMAT_ARRAY { + NumRenderTargets: desc.NumRenderTargets, + ..Default::default() }; - let device = device.cast::()?; - super::library::pipeline( - name, - // SAFETY: the stream holds whole subobjects pointing at live data. - |library, name| unsafe { library.LoadPipeline(name, &desc) }, - // SAFETY: as above. - || unsafe { device.CreatePipelineState(&desc) }, - ) + targets.RTFormats = desc.RTVFormats; + let mut stream = Stream { + root: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + root.as_raw(), + ), + vs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, desc.VS), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, desc.PS), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, desc.BlendState), + mask: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, + desc.SampleMask, + ), + raster: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + desc.RasterizerState, + ), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, g.depth1()), + inputs: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, + desc.InputLayout, + ), + strip_cut: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, + desc.IBStripCutValue, + ), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + desc.PrimitiveTopologyType, + ), + targets: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + targets, + ), + dsv: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + desc.DSVFormat, + ), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, desc.SampleDesc), + }; + stream_pipeline(device, &mut stream, name) +} + +/// Whether the host has the depth bounds test (`DepthBoundsTestSupported`); +/// said once when a title wants it and the host has not. +pub(crate) fn depth_bounds_supported() -> bool { + static SUPPORTED: std::sync::OnceLock = std::sync::OnceLock::new(); + *SUPPORTED.get_or_init(|| { + let Some(host) = host() else { return false }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default(); + // SAFETY: the query writes its own structure of the given size. + let asked = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS2, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + let supported = asked.is_ok() && options.DepthBoundsTestSupported.as_bool(); + if !supported { + tracing::warn!( + "the host has no depth bounds test: pixels outside a title's depth bounds are drawn" + ); + } + supported + }) } /// The bytes of shader code (none for an absent stage). @@ -808,6 +971,36 @@ fn root_signature( #[cfg(test)] mod tests { + /// A stream's `DEPTH_STENCIL1` keeps its depth bounds test; a plain + /// `DEPTH_STENCIL` after it turns the test off again. + #[test] + fn depth_stencil1_keeps_the_depth_bounds_test() { + #[repr(C, align(8))] + struct Sub1(u32, D3D12_DEPTH_STENCIL_DESC1); + let mut g = GraphicsState::default(); + let d = D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: true.into(), + DepthFunc: D3D12_COMPARISON_FUNC_GREATER_EQUAL, + DepthBoundsTestEnable: true.into(), + ..Default::default() + }; + let sub = Sub1(21, d); + // SAFETY: a whole subobject of type 21. + unsafe { g.read(21, std::ptr::from_ref(&sub).cast()) }; + assert!(g.depth_bounds); + assert_eq!(g.depth.DepthFunc, D3D12_COMPARISON_FUNC_GREATER_EQUAL); + let one = g.depth1(); + assert!(one.DepthBoundsTestEnable.as_bool()); + assert_eq!(one.DepthFunc, D3D12_COMPARISON_FUNC_GREATER_EQUAL); + #[repr(C, align(8))] + struct Sub0(u32, D3D12_DEPTH_STENCIL_DESC); + let sub = Sub0(11, D3D12_DEPTH_STENCIL_DESC::default()); + // SAFETY: a whole subobject of type 11. + unsafe { g.read(11, std::ptr::from_ref(&sub).cast()) }; + assert!(!g.depth_bounds); + assert!(!g.bounds()); + } + /// Over 64 dwords, the largest user data blocks become root CBVs until /// the signature fits; under it nothing changes. #[test] From d6bc25461ef9a605af3152e9f8a631f07cb45b85 Mon Sep 17 00:00:00 2001 From: iurysf Date: Tue, 24 Nov 2026 03:52:15 -0300 Subject: [PATCH 086/123] GPU: let the frame-wait test tolerate a loaded scheduler waits_end_on_ticks_and_count_frames failed intermittently under CPU load (15 of 20 runs failed on main, exit 101; 20 of 20 pass after this change). Two assertions depended on the OS scheduler, not on the frame clock: - The wall-clock bound on the second wait was 50 ms. A 2 ms tick can take longer than that when the scheduler is busy. It is now 500 ms, still well below the 1 s time-out, so a wait that stalls for the full time-out is still caught. - The flip ticks had to be exactly consecutive. A late wake can skip ticks (the next tick comes from the clock), so the check is now strictly rising: it still rejects a tick that repeats or goes backwards. No production code changed. Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> (cherry picked from commit e1c3557bdc67f31e13d04a00d2d9ad1ebc65c7e3) --- crates/victory-gpu/src/frame.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index b55b53f039..d172d5b8d0 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -201,7 +201,9 @@ mod tests { let mut second = 0; assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK); assert!(second > first); - assert!(before.elapsed() <= Duration::from_millis(50)); + // Loose on purpose: a 2 ms tick can take over 50 ms on a loaded + // scheduler. 500 ms still fails well before the 1 s time-out. + assert!(before.elapsed() <= Duration::from_millis(500)); assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT); // Tokens count frames, a frame started early on a time-out too. let mut early = 0; @@ -217,7 +219,7 @@ mod tests { // The title's loop (the clock is global, so in the same test): an // origin poll that times out (and starts the frame), then a - // blocking flip wait. Each flip takes its own tick. + // blocking flip wait. Each flip ends on a tick of its own. const FLIP: u32 = 2; assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); let mut token = 0; @@ -231,7 +233,8 @@ mod tests { LAST[2].load(Ordering::Relaxed) }) .collect(); - assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}"); + // Strictly rising: a late wake may skip ticks, but never repeats one. + assert!(flips.windows(2).all(|w| w[1] > w[0]), "{flips:?}"); // Even when a flip wait begins on the tick another just ended on. let (tick, _) = next_tick(FLIP, Duration::ZERO); assert!(tick > flips[3]); From d79c35e2f36b061f60fc876ddee07f4d71cc94d1 Mon Sep 17 00:00:00 2001 From: Dathinel <221246794+Dathinel@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:47:32 -0500 Subject: [PATCH 087/123] Shaders: find the PC test compiler independently of the validator (cherry picked from commit 9c2a364dde5dd53ffd790725851f6cdcfed83360) --- Cargo.lock | 1 + crates/victory-shader/Cargo.toml | 1 + crates/victory-shader/src/emit/diff_tests.rs | 51 +++++++++++++++++--- crates/victory-shader/src/emit/validator.rs | 28 ++++++----- 4 files changed, 61 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7f110189d4..d83321cd0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -779,6 +779,7 @@ version = "0.1.0" dependencies = [ "memchr", "miniz_oxide", + "tempfile", "thiserror", "windows", "windows-sys", diff --git a/crates/victory-shader/Cargo.toml b/crates/victory-shader/Cargo.toml index 5915737f0e..80a9b0c5af 100644 --- a/crates/victory-shader/Cargo.toml +++ b/crates/victory-shader/Cargo.toml @@ -29,6 +29,7 @@ windows = { workspace = true, optional = true, features = [ ] } [target.'cfg(windows)'.dev-dependencies] +tempfile.workspace = true windows = { workspace = true, features = [ "Win32_Foundation", "Win32_Graphics_Direct3D", diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 633a4f5075..1676c75015 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -3,8 +3,9 @@ //! dispatched) on the host GPU with the same inputs. //! //! Needs `VICTORY_CONSOLE_DXC` (the console SDK's `dxc.exe`) and a PC -//! `dxc.exe` (`VICTORY_PC_DXC`, else the newest Windows SDK's); skipped -//! without them. Set `VICTORY_WARP=1` to draw on WARP. +//! `dxc.exe` (`VICTORY_PC_DXC`, then the newest Windows SDK's, then the +//! sibling of `VICTORY_DXIL` for standalone DXC). Skipped without both +//! compilers. Set `VICTORY_WARP=1` to draw on WARP. use std::path::{Path, PathBuf}; @@ -652,14 +653,50 @@ const MS_CASES: &[(&str, u32, &str)] = &[ ]; fn tools() -> Option<(PathBuf, PathBuf)> { - let console = PathBuf::from(std::env::var_os("VICTORY_CONSOLE_DXC")?); - let pc = match std::env::var_os("VICTORY_PC_DXC") { - Some(p) => PathBuf::from(p), - None => super::validator::Validator::default_path()?.with_file_name("dxc.exe"), - }; + tools_in(Path::new(super::validator::SDK_BIN), |key| { + std::env::var_os(key).map(PathBuf::from) + }) +} + +fn tools_in(kits: &Path, env_path: impl Fn(&str) -> Option) -> Option<(PathBuf, PathBuf)> { + let console = env_path("VICTORY_CONSOLE_DXC")?; + let pc = env_path("VICTORY_PC_DXC") + .or_else(|| super::validator::sdk_tool(kits, "dxc.exe")) + .or_else(|| env_path("VICTORY_DXIL").map(|dll| dll.with_file_name("dxc.exe")))?; (console.exists() && pc.exists()).then_some((console, pc)) } +#[test] +fn pc_compiler_prefers_sdk_and_supports_standalone_dxc() { + let dir = tempfile::tempdir().unwrap(); + let kits = dir.path().join("bin"); + let sdk = kits.join("10.0.26100.0").join("x64"); + std::fs::create_dir_all(&sdk).unwrap(); + let console = dir.path().join("console.exe"); + let validator = dir.path().join("dxil.dll"); + let explicit_pc = dir.path().join("dxc.exe"); + let sdk_pc = sdk.join("dxc.exe"); + for path in [&console, &validator, &explicit_pc, &sdk_pc] { + std::fs::write(path, []).unwrap(); + } + let locate = |pc: Option<&PathBuf>| { + tools_in(&kits, |key| match key { + "VICTORY_CONSOLE_DXC" => Some(console.clone()), + "VICTORY_DXIL" => Some(validator.clone()), + "VICTORY_PC_DXC" => pc.cloned(), + _ => None, + }) + }; + assert_eq!(locate(None), Some((console.clone(), sdk_pc.clone()))); + assert_eq!(locate(Some(&dir.path().join("missing.exe"))), None); + assert_eq!( + locate(Some(&explicit_pc)), + Some((console.clone(), explicit_pc.clone())) + ); + std::fs::remove_file(sdk_pc).unwrap(); + assert_eq!(locate(None), Some((console, explicit_pc))); +} + fn compile(dxc: &Path, dir: &Path, src: &str, entry: &str, profile: &str) -> Vec { let input = dir.join("t.hlsl"); let output = dir.join(format!("{entry}.bin")); diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs index 8cfd3ca9bd..c464d5ea6c 100644 --- a/crates/victory-shader/src/emit/validator.rs +++ b/crates/victory-shader/src/emit/validator.rs @@ -6,7 +6,7 @@ //! `bin\\x64\dxil.dll`, else wherever `LoadLibrary` finds it. use std::ffi::c_void; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE}; use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; @@ -114,6 +114,17 @@ pub struct Validator { module: HMODULE, } +pub(super) const SDK_BIN: &str = r"C:\Program Files (x86)\Windows Kits\10\bin"; + +pub(super) fn sdk_tool(kits: &Path, name: &str) -> Option { + std::fs::read_dir(kits) + .ok()? + .filter_map(Result::ok) + .map(|entry| entry.path().join("x64").join(name)) + .filter(|path| path.exists()) + .max() +} + // SAFETY: the validator object is free-threaded (DXC's validator has no // thread affinity) and the module handle is process-wide; calls are // serialised by `&mut self`. @@ -122,18 +133,9 @@ unsafe impl Send for Validator {} impl Validator { /// Where `dxil.dll` is looked for. pub fn default_path() -> Option { - if let Some(p) = std::env::var_os("VICTORY_DXIL") { - return Some(p.into()); - } - let kits = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin"); - let mut versions: Vec = std::fs::read_dir(&kits) - .ok()? - .filter_map(Result::ok) - .map(|e| e.path().join(r"x64\dxil.dll")) - .filter(|p| p.exists()) - .collect(); - versions.sort(); - versions.pop() + std::env::var_os("VICTORY_DXIL") + .map(PathBuf::from) + .or_else(|| sdk_tool(Path::new(SDK_BIN), "dxil.dll")) } /// Loads `path`'s validator (or `dxil.dll` from the DLL search path). From 0489fcefb2e602777dc472e03273d2f47b94214c Mon Sep 17 00:00:00 2001 From: DenRakEiw <89697885+DenRakEiw@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:37:27 +0100 Subject: [PATCH 088/123] xg: validate null tiling output, slice bounds, and checked copy spans (cherry picked from commit b9e5f2e9ff3d03c1cc3f89402aacbb63eb4c559e) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-hle/src/modules/xg.rs | 126 ++++++++++++++++++++++++--- 1 file changed, 113 insertions(+), 13 deletions(-) diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs index 0f9903b805..98e43bb32a 100644 --- a/crates/victory-hle/src/modules/xg.rs +++ b/crates/victory-hle/src/modules/xg.rs @@ -355,12 +355,13 @@ extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { } /// The plane, its mip and array slice for a subresource index, and the -/// tiled bytes and the linear bytes the copy touches. +/// tiled byte range and linear byte count the copy touches. struct CopyArgs<'a> { layout: &'a Layout, mip: u32, slice: u32, - tiled: usize, + tiled_offset: usize, + tiled_len: usize, linear: usize, } @@ -374,15 +375,37 @@ fn copy_args( let p = c.texture.planes.get(plane as usize)?; let l = &p.layout; let (mip, slice) = (subresource % c.mips, subresource / c.mips); + if slice >= l.slices { + return None; + } let m = l.mips.get(mip as usize)?; - let bytes = m.width as usize * l.desc.element_bytes as usize; - let depths = l.subresource_depth(mip) as usize; - let linear = (depths - 1) * depth as usize + (m.height as usize - 1) * row as usize + bytes; + let bytes = usize::try_from(m.width) + .ok()? + .checked_mul(usize::try_from(l.desc.element_bytes).ok()?)?; + let depths = usize::try_from(l.subresource_depth(mip)).ok()?; + let depth_span = depths + .checked_sub(1)? + .checked_mul(usize::try_from(depth).ok()?)?; + let row_span = usize::try_from(m.height) + .ok()? + .checked_sub(1)? + .checked_mul(usize::try_from(row).ok()?)?; + let linear = depth_span.checked_add(row_span)?.checked_add(bytes)?; + if linear > isize::MAX as usize { + return None; + } + let tiled_end = p.offset.checked_add(l.size)?; + if usize::try_from(tiled_end).ok()? > isize::MAX as usize { + return None; + } + let tiled_offset = usize::try_from(p.offset).ok()?; + let tiled_len = usize::try_from(l.size).ok()?; Some(CopyArgs { layout: l, mip, slice, - tiled: (p.offset + l.size) as usize, + tiled_offset, + tiled_len, linear, }) } @@ -412,11 +435,10 @@ extern "system" fn copy_into( if tiled.is_null() || linear.is_null() { return E_INVALIDARG; } - let offset = c.texture.planes[plane as usize].offset as usize; // SAFETY: the title's memory holds the whole texture and its rows. let (tiled, linear) = unsafe { ( - std::slice::from_raw_parts_mut(tiled.add(offset), a.tiled - offset), + std::slice::from_raw_parts_mut(tiled.add(a.tiled_offset), a.tiled_len), std::slice::from_raw_parts(linear, a.linear), ) }; @@ -449,11 +471,10 @@ extern "system" fn copy_from( if tiled.is_null() || linear.is_null() { return E_INVALIDARG; } - let offset = c.texture.planes[plane as usize].offset as usize; // SAFETY: the title's memory holds the whole texture and its rows. let (tiled, linear) = unsafe { ( - std::slice::from_raw_parts(tiled.add(offset), a.tiled - offset), + std::slice::from_raw_parts(tiled.add(a.tiled_offset), a.tiled_len), std::slice::from_raw_parts_mut(linear, a.linear), ) }; @@ -508,6 +529,10 @@ extern "system" fn tiling( if l.thick { return E_NOTIMPL; } + // SAFETY: `count` is null or a valid pointer to the caller's capacity. + if unsafe { count.as_ref().is_some_and(|&n| n > 0) } && out.is_null() { + return E_INVALIDARG; + } let standard = l.first_tail_mip; let tail = standard < c.mips; let tail_tiles = match standard { @@ -516,8 +541,8 @@ extern "system" fn tiling( _ => 0, }; let block = l.desc.block; - // SAFETY: each output is null or room for its value; `out` has room - // for `*count` entries. + // SAFETY: each output is null or room for its value; `out` is non-null + // whenever `*count > 0` and has room for `*count` entries. unsafe { if let Some(t) = tiles.as_mut() { *t = (l.size / TILE) as u32; @@ -535,7 +560,7 @@ extern "system" fn tiling( } if let Some(n) = count.as_mut() { let slices = if tail { l.slices.min(2) } else { l.slices }; - let wanted = (standard * slices).saturating_sub(first).min(*n); + let wanted = standard.saturating_mul(slices).saturating_sub(first).min(*n); for i in 0..wanted { let (slice, mip) = ((first + i) / standard, (first + i) % standard); let m = &l.mips[mip as usize]; @@ -844,4 +869,79 @@ mod tests { // `release`. drop(unsafe { Box::from_raw(c) }); } + + #[test] + fn tiling_rejects_null_out_when_count_nonzero() { + type Tiling = extern "system" fn( + This, + *mut u32, + *mut PackedMips, + *mut [u32; 3], + *mut u32, + u32, + *mut SubresourceTiling, + ) -> HRESULT; + let c = create(&desc(256, 256, 0, 98, 0x10a)); + let tiling: Tiling = slot(c, 10); + + let mut tiles = 99; + let mut count = 2; + assert_eq!( + tiling( + c, + &mut tiles, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut count, + 0, + std::ptr::null_mut(), + ), + E_INVALIDARG + ); + // Failed call leaves caller's outputs untouched. + assert_eq!((tiles, count), (99, 2)); + + // Zero capacity with null `out` is allowed and fills the summary fields. + count = 0; + assert_eq!( + tiling( + c, + &mut tiles, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut count, + 0, + std::ptr::null_mut(), + ), + S_OK + ); + assert_eq!((tiles, count), (2, 0)); + assert_eq!(release(c), 0); + } + + #[test] + fn copy_rejects_out_of_range_slice_and_plane() { + type Into = extern "system" fn(This, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT; + type From = + extern "system" fn(This, *mut u8, u32, u32, u32, *const u8, u32, u32) -> HRESULT; + let c = create(&desc(64, 64, 2, 98, 0x10a)); + let (into, from): (Into, From) = (slot(c, 8), slot(c, 9)); + + // 1 slice, 2 mips -> subresource 2 is slice 1 (out of range). + // Must fail in `copy_args` before touching `tiled` or `linear`. + let mut dummy = [0u8; 16]; + assert_eq!( + into(c, dummy.as_mut_ptr(), 0, 2, dummy.as_ptr(), 256, 0), + E_INVALIDARG + ); + assert_eq!( + from(c, dummy.as_mut_ptr(), 0, 2, 0, dummy.as_ptr(), 256, 0), + E_INVALIDARG + ); + assert_eq!( + into(c, dummy.as_mut_ptr(), 1, 0, dummy.as_ptr(), 256, 0), + E_INVALIDARG + ); + assert_eq!(release(c), 0); + } } From 68238736fbdc46e0823b3eb80f67d9676b96a9e3 Mon Sep 17 00:00:00 2001 From: LF2000 Builder Date: Tue, 24 Nov 2026 00:37:00 -0500 Subject: [PATCH 089/123] DSP: return XDSP_E_NO_DEVICE_RESOURCES past the stream limit XDspActivate returned E_OUTOFMEMORY when a connection already had as many streams as the title asked for at connect time. The GDK documents XDSP_E_NO_DEVICE_RESOURCES (0x8AC810A2) for this case, and XDspActivate's return list has no E_OUTOFMEMORY. A title that compares against the documented code saw something else. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit a1b8b85921b1be373115ab5d82e6910240c16423) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-hle/src/modules/dsp.rs | 41 +++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/dsp.rs b/crates/victory-hle/src/modules/dsp.rs index fcaa4e4caa..701a47239f 100644 --- a/crates/victory-hle/src/modules/dsp.rs +++ b/crates/victory-hle/src/modules/dsp.rs @@ -25,7 +25,8 @@ use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleModule, hle_export}; const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; -const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +/// XDSP_E_NO_DEVICE_RESOURCES: the connection's stream limit is used up. +const NO_DEVICE_RESOURCES: HRESULT = 0x8AC8_10A2_u32 as i32; const CONVOLUTION: u32 = 1; /// XDspActivationOptions: a per-channel IR and deinterleaved blocks both @@ -192,7 +193,7 @@ pub extern "system" fn XDspActivate( let dsp = unsafe { &*dsp }; let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner()); if *active >= dsp.max_streams { - return E_OUTOFMEMORY; + return NO_DEVICE_RESOURCES; } *active += 1; } @@ -476,4 +477,40 @@ mod tests { assert_eq!(XDspDeactivate(stream), S_OK); assert_eq!(XDspDisconnect(dsp), S_OK); } + + /// XDspConnectWithMaximumStreamLimit: "XDspActivate returns + /// XDSP_E_NO_DEVICE_RESOURCES if this count is exceeded." + #[test] + fn activations_past_the_stream_limit_have_no_device_resources() { + let mut base = vec![0u8; 0x1_0000]; + let mut dsp = std::ptr::null_mut(); + assert_eq!( + XDspConnectWithMaximumStreamLimit( + base.as_mut_ptr().cast(), + 0x1_0000, + 0, + 1, + 1, + &mut dsp + ), + S_OK + ); + let transform = StreamDesc { + kind: 2, + options: 0, + frames: 0x400, + channels: 1, + ir_floats: 0, + ir: std::ptr::null(), + }; + let (mut status, mut first, mut second) = + (std::ptr::null(), std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(XDspActivate(dsp, &transform, &mut status, &mut first), S_OK); + assert_eq!( + XDspActivate(dsp, &transform, &mut status, &mut second), + NO_DEVICE_RESOURCES + ); + assert_eq!(XDspDeactivate(first), S_OK); + assert_eq!(XDspDisconnect(dsp), S_OK); + } } From bda19ffa973ffe1405d488d187aa1723177e5bd7 Mon Sep 17 00:00:00 2001 From: LF2000 Builder Date: Tue, 24 Nov 2026 00:37:48 -0500 Subject: [PATCH 090/123] DSP: refuse XDspDisconnect while streams are still active XDspDisconnect freed the connection every time and returned S_OK. Each active stream keeps a pointer to the connection, and XDspDeactivate decrements the active count through it. So a title that disconnected before deactivating wrote into freed heap memory on the next deactivate. The GDK says XDspDisconnect fails with XDSP_E_NOT_ALL_HANDLES_DEACTIVATED (0x8AC810A4) in this case. Do the same, and keep the client, since an error return should leave it alone. The title can then deactivate its streams and disconnect again. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 37d52cb78ddc09cc5f8c967e190ebc9a51e79fe8) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-hle/src/modules/dsp.rs | 55 +++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/crates/victory-hle/src/modules/dsp.rs b/crates/victory-hle/src/modules/dsp.rs index 701a47239f..2e6737f5cb 100644 --- a/crates/victory-hle/src/modules/dsp.rs +++ b/crates/victory-hle/src/modules/dsp.rs @@ -27,6 +27,8 @@ use crate::{HleModule, hle_export}; const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; /// XDSP_E_NO_DEVICE_RESOURCES: the connection's stream limit is used up. const NO_DEVICE_RESOURCES: HRESULT = 0x8AC8_10A2_u32 as i32; +/// XDSP_E_NOT_ALL_HANDLES_DEACTIVATED: disconnect with streams still active. +const NOT_ALL_HANDLES_DEACTIVATED: HRESULT = 0x8AC8_10A4_u32 as i32; const CONVOLUTION: u32 = 1; /// XDspActivationOptions: a per-channel IR and deinterleaved blocks both @@ -115,12 +117,21 @@ pub extern "system" fn XDspConnectWithMaximumStreamLimit( S_OK } +/// Refuses while streams are active, as the GDK documents, since each one +/// points at the connection. The client is kept, so the title can +/// deactivate them and disconnect again. pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT { if dsp.is_null() { return E_INVALIDARG; } - // SAFETY: made by `XDspConnectWithMaximumStreamLimit`; disconnected - // once, after its streams. + // SAFETY: made by `XDspConnectWithMaximumStreamLimit`, not disconnected. + let connection = unsafe { &*dsp }; + if *connection.active.lock().unwrap_or_else(|e| e.into_inner()) != 0 { + return NOT_ALL_HANDLES_DEACTIVATED; + } + // Checked under the lock but freed after it: the title finishes its + // XDspActivate and XDspDeactivate calls on this connection before this. + // SAFETY: as above, and no stream points at it any more; disconnected once. drop(unsafe { Box::from_raw(dsp) }); S_OK } @@ -224,7 +235,7 @@ pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT { } // SAFETY: made by `XDspActivate`; deactivated once. let stream = unsafe { Box::from_raw(stream) }; - // SAFETY: the connection outlives its streams. + // SAFETY: `XDspDisconnect` keeps the connection while this is active. let dsp = unsafe { &*stream.dsp }; *dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1; S_OK @@ -513,4 +524,42 @@ mod tests { assert_eq!(XDspDeactivate(first), S_OK); assert_eq!(XDspDisconnect(dsp), S_OK); } + + /// XDspDisconnect: "All XDSP streams must be deactivated successfully + /// before calling this function"; otherwise it fails with + /// XDSP_E_NOT_ALL_HANDLES_DEACTIVATED. We take the error to leave the + /// client usable. + #[test] + fn disconnect_with_an_active_stream_is_refused() { + let mut base = vec![0u8; 0x1_0000]; + let mut dsp = std::ptr::null_mut(); + assert_eq!( + XDspConnectWithMaximumStreamLimit( + base.as_mut_ptr().cast(), + 0x1_0000, + 0, + 1, + 1, + &mut dsp + ), + S_OK + ); + let transform = StreamDesc { + kind: 2, + options: 0, + frames: 0x400, + channels: 1, + ir_floats: 0, + ir: std::ptr::null(), + }; + let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut()); + assert_eq!( + XDspActivate(dsp, &transform, &mut status, &mut stream), + S_OK + ); + assert_eq!(XDspDisconnect(dsp), NOT_ALL_HANDLES_DEACTIVATED); + // The client is still there for its stream. + assert_eq!(XDspDeactivate(stream), S_OK); + assert_eq!(XDspDisconnect(dsp), S_OK); + } } From c88bc0c4fd8f93764792571dde6c226755f2ed96 Mon Sep 17 00:00:00 2001 From: LF2000 Builder Date: Tue, 24 Nov 2026 00:37:37 -0500 Subject: [PATCH 091/123] Shaders: print only the operands an instruction has in SP3 text The disassembly text showed operands that some instructions lack, and dropped VOP3P negation that applies to one half only: - s_memtime, s_memrealtime and s_get_waveid_in_workgroup printed the unused SMEM base and offset. - A global or scratch access with no SGPR base printed `null`, not `off`. - A MUBUF load with lds printed the unused vdata as a destination. - VOP1 SDWA printed src1_sel, though VOP1 has no second source. - VOP3P ops other than v_fma_mix with only neg_lo or only neg_hi set on a source printed as if the source were not negated. These now get LLVM's neg_lo:[..] and neg_hi:[..] suffixes; a source negated in both halves keeps `-src`. Expected operands come from llvm-mc -mcpu=gfx1030 (gfx1010 for s_get_waveid_in_workgroup). Only the text changes; translation reads Fields and is unaffected. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 6325df752c5638365c3e5a2b2f827ba0f3f145cb) --- crates/victory-shader/src/gfx10/sp3.rs | 76 ++++++++++++++++++++++++-- 1 file changed, 72 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/gfx10/sp3.rs b/crates/victory-shader/src/gfx10/sp3.rs index 0ca5ab414d..4254c112db 100644 --- a/crates/victory-shader/src/gfx10/sp3.rs +++ b/crates/victory-shader/src/gfx10/sp3.rs @@ -145,7 +145,11 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { (_, 0) => soffset.to_string(), _ => format!("{soffset} offset:0x{:06x}", offset & 0x1F_FFFF), }; - out = format!("{data}, {base}, {off}"); + out = match name { + // The data is a counter or the wave ID; these have no address. + "s_memtime" | "s_memrealtime" | "s_get_waveid_in_workgroup" => data.to_string(), + _ => format!("{data}, {base}, {off}"), + }; } flags(&mut out, cache, false); } @@ -199,7 +203,12 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { cache, } => { if let Some(data) = data { - out = format!("{data}, {addr}, {rsrc}, {soffset}"); + // An LDS load returns its data to LDS, so vdata is unused. + out = if *lds && name.contains("_load_") { + format!("{addr}, {rsrc}, {soffset}") + } else { + format!("{data}, {addr}, {rsrc}, {soffset}") + }; if *idxen { out.push_str(" idxen"); } @@ -293,7 +302,11 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { dst.iter() .map(|o| o.to_string()) .chain([addr]) - .chain(data.iter().chain(saddr).map(|o| o.to_string())), + .chain(data.iter().map(|o| o.to_string())) + .chain(saddr.map(|o| match o { + Operand::Scalar { code: NULL, .. } => "off".into(), + o => o.to_string(), + })), ); if *offset != 0 { let _ = write!(out, " inst_offset:{offset}"); @@ -575,6 +588,18 @@ fn valu(name: &str, v: &Valu, encoding: Encoding) -> String { suffix("bound_ctrl:1"); } } + if encoding == Encoding::Vop3p && !mix { + // `-src` above covers a source negated in both halves; LLVM syntax + // for the one-sided rest. + let n = v.src.len(); + for (field, only) in [("neg_lo", v.neg & !v.neg_hi), ("neg_hi", v.neg_hi & !v.neg)] { + if (0..n).any(|i| bit(only, i)) { + let bits: Vec = + (0..n).map(|i| u8::from(bit(only, i)).to_string()).collect(); + suffix(&format!("{field}:[{}]", bits.join(","))); + } + } + } if let Some(sdwa) = v.sdwa { if v.clamp { suffix("clamp"); @@ -595,7 +620,7 @@ fn valu(name: &str, v: &Valu, encoding: Encoding) -> String { unused[usize::from(sdwa.dst_unused & 3)] )); } - for (i, s) in sdwa.src_sel.iter().enumerate() { + for (i, s) in sdwa.src_sel.iter().take(v.src.len()).enumerate() { if *s != 6 { suffix(&format!("src{i}_sel:{}", sel[usize::from(s & 7)])); } @@ -762,6 +787,49 @@ mod tests { ); } + #[test] + fn one_sided_packed_negation_is_printed() { + // Encodings from llvm-mc -mcpu=gfx1030. A source negated in both + // halves keeps the `-` prefix; one-sided bits get LLVM's suffixes. + let got = [ + one(&[0xCC0F_4001, 0x1A02_0702], true), + one(&[0xCC0F_4001, 0x3A02_0702], true), + one(&[0xCC0F_4201, 0x1A02_0702], true), + one(&[0xCC0F_4101, 0x7A02_0702], true), + ]; + assert_eq!( + got, + [ + "v_pk_add_f16 v1, v2, v3", + "v_pk_add_f16 v1, v2, v3 neg_lo:[1,0]", + "v_pk_add_f16 v1, v2, v3 neg_hi:[0,1]", + "v_pk_add_f16 v1, -v2, v3 neg_lo:[0,1]", + ] + ); + } + + #[test] + fn fields_the_instruction_lacks_are_not_printed() { + // Encodings from llvm-mc -mcpu=gfx1030; s_get_waveid_in_workgroup is gfx1010 only. + let got = [ + one(&[0xF490_0500, 0], true), + one(&[0xF4A8_0140, 0], true), + one(&[0xDC30_8000, 0x007D_0002], true), + one(&[0xE031_1000, 0x0001_0001], true), + one(&[0x7E02_02F9, 0x0005_0602], true), + ]; + assert_eq!( + got, + [ + "s_memtime s[20:21]", + "s_get_waveid_in_workgroup s5", + "global_load_dword v0, v[2:3], off", + "buffer_load_dword v1, s[4:7], s0 offen lds", + "v_mov_b32 v1, v2 src0_sel:WORD_1", + ] + ); + } + #[test] fn image_d16_data_is_packed() { // Three f16 channels occupy two VGPRs; NSA lists the addresses. From ab5ead9c38ace70e79f532ff84d2aa834ac257c0 Mon Sep 17 00:00:00 2001 From: lameloball2813-ui <293005050+lameloball2813-ui@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:21:11 -0700 Subject: [PATCH 092/123] Input: report the character each held key types (cherry picked from commit 3b001ed80c97a9da158696ae06c4961548953a53) --- crates/victory-hle/src/modules/gameinput.rs | 124 ++++++++++++++++++-- 1 file changed, 116 insertions(+), 8 deletions(-) diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 61eeca18e4..b5d77b305a 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1120,7 +1120,8 @@ mod host { use windows_sys::Win32::System::Threading::GetCurrentProcessId; use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ - GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, + GetAsyncKeyState, GetKeyState, GetKeyboardLayout, HKL, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, + ToUnicodeEx, }; use windows_sys::Win32::UI::Input::XboxController::{ XINPUT_GAMEPAD, XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_BACK, @@ -1223,14 +1224,19 @@ mod host { .collect(); down.extend(held); } - down.into_iter() - .map(|vk| KeyState { + let state = keyboard_state(&down, caps_lock()); + let layout = layout(); + down.iter() + .map(|&vk| { // SAFETY: plain query. - scan_code: unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) }, - virtual_key: vk, - // shortcut: no characters (code point 0); Grand Theft - // Auto VI reads scan codes and virtual keys only. - ..Default::default() + let scan_code = unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) }; + let (code_point, dead_key) = character(vk, scan_code, &state, layout); + KeyState { + scan_code, + code_point, + virtual_key: vk, + dead_key, + } }) .collect() } @@ -1288,6 +1294,82 @@ mod host { .collect() } + /// The keyboard state `ToUnicodeEx` reads with the keys `held` down: + /// each held key, the generic Shift, Ctrl and Alt from either side's key + /// (devices report sides only), and Caps Lock's toggle. + fn keyboard_state(held: &[u8], caps_lock: bool) -> [u8; 256] { + const DOWN: u8 = 0x80; + const TOGGLED: u8 = 1; + let mut state = [0u8; 256]; + for &vk in held { + state[usize::from(vk)] = DOWN; + let generic = match vk { + 0xA0 | 0xA1 => Some(0x10), // shift + 0xA2 | 0xA3 => Some(0x11), // control + 0xA4 | 0xA5 => Some(0x12), // alt + _ => None, + }; + if let Some(g) = generic { + state[g] = DOWN; + } + } + if caps_lock { + state[0x14] |= TOGGLED; + } + state + } + + fn caps_lock() -> bool { + // SAFETY: plain query. + let state = unsafe { GetKeyState(0x14) }; + state & 1 != 0 + } + + /// The foreground window's keyboard layout (the title's while it has + /// focus; this thread's when there is no foreground window). + fn layout() -> HKL { + // SAFETY: plain queries; a null window gives thread 0, this thread. + unsafe { + GetKeyboardLayout(GetWindowThreadProcessId( + GetForegroundWindow(), + std::ptr::null_mut(), + )) + } + } + + /// The character key `vk` types in `layout` with `state`: its code point + /// (0 when it types none, or several at once), and whether it is a dead + /// key, whose code point is then the accent's spacing form. Pending dead + /// keys are not combined: the thread's keyboard state is left alone. + fn character(vk: u8, scan_code: u32, state: &[u8; 256], layout: HKL) -> (u32, bool) { + /// `ToUnicodeEx` flag: keep the keyboard state (Windows 10 1607 on). + const KEEP_STATE: u32 = 4; + let mut text = [0u16; 8]; + // SAFETY: the state is the 256 bytes the call reads; the buffer's + // length is passed with it. + let n = unsafe { + ToUnicodeEx( + u32::from(vk), + scan_code & 0xFF, + state.as_ptr(), + text.as_mut_ptr(), + text.len() as i32, + KEEP_STATE, + layout, + ) + }; + let units = match n { + 0 => return (0, false), + ..0 => &text[..1], + n => &text[..(n as usize).min(text.len())], + }; + let mut chars = char::decode_utf16(units.iter().copied()); + match (chars.next(), chars.next()) { + (Some(Ok(c)), None) => (u32::from(c), n < 0), + _ => (0, false), + } + } + /// The foreground window is one of ours (the title's or our fallback). fn focused() -> bool { let mut process = 0; @@ -1319,6 +1401,32 @@ mod host { (1.0, -1.0, 1.0, 0.0) ); } + + #[test] + fn either_sides_modifier_holds_the_generic_one() { + let state = keyboard_state(&[0xA1, 0xA2, 0x41], false); + for vk in [0xA1, 0x10, 0xA2, 0x11, 0x41] { + assert_eq!(state[vk], 0x80, "{vk:#x}"); + } + for vk in [0xA0, 0xA3, 0x12, 0x14] { + assert_eq!(state[vk], 0, "{vk:#x}"); + } + assert_eq!(keyboard_state(&[], true)[0x14], 1); + } + + #[test] + fn keys_type_their_characters() { + // Space and Enter type the same in every layout; F1 types nothing. + let layout = layout(); + let typed = |vk: u8, held: &[u8]| { + // SAFETY: plain query. + let scan = unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) }; + character(vk, scan, &keyboard_state(held, false), layout) + }; + assert_eq!(typed(0x20, &[0x20]), (0x20, false)); + assert_eq!(typed(0x0D, &[0x0D]), (0x0D, false)); + assert_eq!(typed(0x70, &[0x70]), (0, false)); + } } #[cfg(test)] From 1277a3ec873c6e93db4a143e9e7d933a0cea9c03 Mon Sep 17 00:00:00 2001 From: LAKSHYA-cmd-tech <218701667+LAKSHYA-cmd-tech@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:38:58 +0530 Subject: [PATCH 093/123] HLE: implement XUser maximum-users slot 0x30 (#348, #622) (cherry picked from commit 241b08f4943973800de7c867d332b32d14436cf5) --- crates/victory-hle/src/modules/xuser.rs | 35 +++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/xuser.rs b/crates/victory-hle/src/modules/xuser.rs index 8b48dfc0d3..dafcfba771 100644 --- a/crates/victory-hle/src/modules/xuser.rs +++ b/crates/victory-hle/src/modules/xuser.rs @@ -267,8 +267,17 @@ extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Hand USER_NOT_FOUND } -// Unset slots (no title seen calls them): maximum users, gamer pictures, +// Unset slots (no title seen calls them): gamer pictures, // the UTF-16 token calls, issue resolution. +/// 1: one offline local user can be signed in at a time. +/// +/// Slot 0x30: maximum users (`IXUserProvider::GetMaxUsers`). The title calls it +/// during its account init right after `XUserAddAsync` and dereferences the output +/// (issue #348, #622, #630). +extern "system" fn get_max_users(_: This, _: Handle, out: *mut u32) -> HRESULT { + put(out, 1) +} + static VTABLE: Methods<35> = Methods([ missing::<0> as *const (), // 0x00 QueryInterface add_ref as *const (), // 0x08 AddRef @@ -276,7 +285,7 @@ static VTABLE: Methods<35> = Methods([ duplicate as *const (), // 0x18 close as *const (), // 0x20 compare as *const (), // 0x28 - missing::<6> as *const (), // 0x30 maximum users + get_max_users as *const (), // 0x30 maximum users add_async as *const (), // 0x38 add_result as *const (), // 0x40 get_local_id as *const (), // 0x48 @@ -422,4 +431,26 @@ mod tests { FAILED_TO_GET_TOKEN ); } + + #[test] + fn get_max_users_reports_one_user() { + type GetMaxUsers = extern "system" fn(This, Handle, *mut u32) -> HRESULT; + let this: This = &OBJECT; + let mut max = 0; + assert_eq!( + slot::(&OBJECT, 0x30)(this, user(), &mut max), + S_OK + ); + assert_eq!(max, 1); + max = 0; + assert_eq!( + slot::(&OBJECT, 0x30)(this, std::ptr::null(), &mut max), + S_OK + ); + assert_eq!(max, 1); + assert_eq!( + slot::(&OBJECT, 0x30)(this, user(), std::ptr::null_mut()), + crate::modules::xasync::E_INVALIDARG + ); + } } From bebf1a4b57b5adf7647447f3da3954bbe9dd5c85 Mon Sep 17 00:00:00 2001 From: wrothgaril <211408787+wrothgaril@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:51:03 +0100 Subject: [PATCH 094/123] gpu: expand console primitive topologies into host list index buffers - Add ExpandedTopology (TRIANGLE_FAN, LINE_LOOP, QUADS, QUAD_STRIP) in primitive.rs with 16-bit and 32-bit non-indexed and indexed expansion, strip-cut/primitive-restart handling, and degenerate tail padding. - Map LINE_LOOP to D3D_PRIMITIVE_TOPOLOGY_LINELIST and TRIANGLE_FAN/QUADS/QUAD_STRIP to TRIANGLELIST in draw::State::set_topology. - Expand non-indexed and indexed console topology draws via HostList scratch upload index buffers while honoring base_vertex, start_index, R16_UINT/R32_UINT index format, and HostPipeline::strip_cut. - Add unit and live D3D12 hardware/WARP rendering tests covering winding order, backface culling, strip cuts, and LINE_LOOP closing edges. (cherry picked from commit 79a476f57cb2934352a10273bcec6cce9919c4b8) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 258 +++++++-- crates/victory-gpu/src/pipeline/host.rs | 5 + crates/victory-gpu/src/primitive.rs | 675 ++++++++++++++++++++++++ 3 files changed, 898 insertions(+), 40 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9aee5d7dd7..46e571d178 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -226,11 +226,8 @@ impl State { self.topology = topology; let host = match topology { RECTANGLES => 4, - TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => { - once!(topology, "console topology drawn as a triangle list"); - 4 - } - t => t, + t => crate::primitive::ExpandedTopology::from_console(t) + .map_or(t, crate::primitive::ExpandedTopology::host_topology), }; // SAFETY: an open list. unsafe { @@ -1092,28 +1089,195 @@ impl State { #[cfg(feature = "diagnostics")] self.trace("draw", vertices, first); let rects = self.topology == RECTANGLES; + let expanded = crate::primitive::ExpandedTopology::from_console(self.topology); let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first)); if ran { - // Rectangles were expanded into their own vertex buffers. - let (count, from) = if rects { - (vertices / 3 * 6, 0) + if let Some(kind) = expanded { + if let Some((count, base)) = self.expand_non_indexed(list, kind, vertices, first) { + if count > 0 { + #[cfg(feature = "diagnostics")] + list.note_op(|| { + self.op_text(format!("draw {kind:?} {count}x{instances}"), false) + }); + // SAFETY: an open list with expanded scratch index buffer bound. + unsafe { + list.list + .DrawIndexedInstanced(count, instances, 0, base, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + } + return; + } } else { - (vertices, first) - }; - #[cfg(feature = "diagnostics")] - list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false)); - // SAFETY: an open list with everything set. - unsafe { - list.list - .DrawInstanced(count, instances, from, first_instance) + // Rectangles were expanded into their own vertex buffers. + let (count, from) = if rects { + (vertices / 3 * 6, 0) + } else { + (vertices, first) + }; + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false)); + // SAFETY: an open list with everything set. + unsafe { + list.list + .DrawInstanced(count, instances, from, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + return; + } + } + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); + } + + /// Binds a synthesized scratch index buffer expanding a non-indexed + /// console-only topology draw into a host triangle or line list. + fn expand_non_indexed( + &self, + list: &HostList, + kind: crate::primitive::ExpandedTopology, + vertices: u32, + first: u32, + ) -> Option<(u32, i32)> { + let out_count = kind.max_output_indices(vertices); + if out_count == 0 { + return Some((0, 0)); + } + let strip_cut = crate::pipeline::host_pipeline(self.pipeline as This) + .map_or(D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, |p| p.strip_cut); + let use_u16 = strip_cut == D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF; + if use_u16 { + if vertices > u32::from(u16::MAX) { + once!( + vertices, + "non-indexed console topology exceeds 16-bit strip-cut index range" + ); + return None; + } + let base = i32::try_from(first).ok()?; + let bytes = u64::from(out_count).checked_mul(2)?; + let size_bytes = u32::try_from(bytes).ok()?; + let (gpu, to) = list.scratch(bytes)?; + // SAFETY: `to` points to `out_count` writable `u16` elements in scratch upload memory. + let dst = unsafe { std::slice::from_raw_parts_mut(to.cast::(), out_count as usize) }; + kind.expand_non_indexed_u16(vertices, 0, dst); + let view = D3D12_INDEX_BUFFER_VIEW { + BufferLocation: gpu, + SizeInBytes: size_bytes, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT, }; - DRAWN.fetch_add(1, Ordering::Relaxed); + // SAFETY: an open list; the view names live scratch upload memory. + unsafe { list.list.IASetIndexBuffer(Some(&view)) }; + return Some((out_count, base)); } - if !ran { - DROPPED.fetch_add(1, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] - dropped(self.pipeline); + let (start, base) = match i32::try_from(first) { + Ok(base) => (0u32, base), + Err(_) => { + first.checked_add(vertices)?; + (first, 0) + } + }; + let bytes = u64::from(out_count).checked_mul(4)?; + let size_bytes = u32::try_from(bytes).ok()?; + let (gpu, to) = list.scratch(bytes)?; + // SAFETY: `to` points to `out_count` writable `u32` elements in scratch upload memory. + let dst = unsafe { std::slice::from_raw_parts_mut(to.cast::(), out_count as usize) }; + kind.expand_non_indexed_u32(vertices, start, dst); + let view = D3D12_INDEX_BUFFER_VIEW { + BufferLocation: gpu, + SizeInBytes: size_bytes, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, + }; + // SAFETY: an open list; the view names live scratch upload memory. + unsafe { list.list.IASetIndexBuffer(Some(&view)) }; + Some((out_count, base)) + } + + /// Binds a submission-filled scratch index buffer expanding an indexed + /// console-only topology draw into a host triangle or line list, preserving + /// index format (`R16_UINT`/`R32_UINT`) and strip-cut semantics. + fn expand_indexed( + &self, + list: &HostList, + kind: crate::primitive::ExpandedTopology, + indices: u32, + first: u32, + base: i32, + ) -> Option { + const R32_UINT: u32 = 42; + const R16_UINT: u32 = 57; + let v = self.index; + let is_u16 = match v.format { + R16_UINT => true, + R32_UINT => false, + _ => { + once!(format = v.format, "unsupported index format for console topology"); + return None; + } + }; + if v.address == 0 || v.size == 0 { + return None; + } + let elem_bytes: u64 = if is_u16 { 2 } else { 4 }; + let avail = (u64::from(v.size) / elem_bytes).saturating_sub(u64::from(first)); + let count = u64::from(indices).min(avail) as u32; + let max_out = kind.max_output_indices(count); + if max_out == 0 { + return Some(0); + } + let src_addr = v.address.checked_add(u64::from(first).checked_mul(elem_bytes)?)?; + let src_bytes = usize::try_from(u64::from(count).checked_mul(elem_bytes)?).ok()?; + let out_bytes = u64::from(max_out).checked_mul(elem_bytes)?; + let out_bytes_u32 = u32::try_from(out_bytes).ok()?; + let (gpu, to) = list.scratch(out_bytes)?; + let strip_cut = crate::pipeline::host_pipeline(self.pipeline as This) + .map_or(D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, |p| p.strip_cut); + let to_addr = to as usize; + let fallback_pad = (-i64::from(base)).max(0) as u32; + if is_u16 { + let cut = (strip_cut == D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF).then_some(u16::MAX); + let pad = fallback_pad.min(u32::from(u16::MAX)) as u16; + list.defer_host(move || { + let mut src = vec![0u16; count as usize]; + crate::host::copy_mapped( + src.as_mut_ptr().cast::(), + src_addr as *const u8, + src_bytes, + false, + ); + // SAFETY: `to_addr` points to `max_out` writable `u16` slots owned by this list. + let dst = unsafe { + std::slice::from_raw_parts_mut(to_addr as *mut u16, max_out as usize) + }; + kind.expand_indexed_u16(&src, cut, pad, dst); + }); + } else { + let cut = + (strip_cut == D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF).then_some(u32::MAX); + list.defer_host(move || { + let mut src = vec![0u32; count as usize]; + crate::host::copy_mapped( + src.as_mut_ptr().cast::(), + src_addr as *const u8, + src_bytes, + false, + ); + // SAFETY: `to_addr` points to `max_out` writable `u32` slots owned by this list. + let dst = unsafe { + std::slice::from_raw_parts_mut(to_addr as *mut u32, max_out as usize) + }; + kind.expand_indexed_u32(&src, cut, fallback_pad, dst); + }); } + let view = D3D12_INDEX_BUFFER_VIEW { + BufferLocation: gpu, + SizeInBytes: out_bytes_u32, + Format: DXGI_FORMAT(v.format as i32), + }; + // SAFETY: an open list; the view names live scratch upload memory. + unsafe { list.list.IASetIndexBuffer(Some(&view)) }; + Some(max_out) } /// Binds vertex buffers holding the rectangles of vertices `first..first @@ -1185,22 +1349,40 @@ impl State { if self.topology == RECTANGLES { once!("indexed rectangles not drawn"); } - let ran = self.topology != RECTANGLES && self.prepare(list, true); + let expanded = crate::primitive::ExpandedTopology::from_console(self.topology); + let ran = self.topology != RECTANGLES && self.prepare(list, expanded.is_none()); if ran { - #[cfg(feature = "diagnostics")] - list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); - // SAFETY: an open list with everything set. - unsafe { - list.list - .DrawIndexedInstanced(indices, instances, first, base, first_instance) - }; - DRAWN.fetch_add(1, Ordering::Relaxed); - } - if !ran { - DROPPED.fetch_add(1, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] - dropped(self.pipeline); + if let Some(kind) = expanded { + if let Some(count) = self.expand_indexed(list, kind, indices, first, base) { + if count > 0 { + #[cfg(feature = "diagnostics")] + list.note_op(|| { + self.op_text(format!("indexed {kind:?} {count}x{instances}"), false) + }); + // SAFETY: an open list with expanded scratch index buffer bound. + unsafe { + list.list + .DrawIndexedInstanced(count, instances, 0, base, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + } + return; + } + } else { + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); + // SAFETY: an open list with everything set. + unsafe { + list.list + .DrawIndexedInstanced(indices, instances, first, base, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + return; + } } + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); } } @@ -1591,12 +1773,8 @@ mod trace_tests { } } -/// The console's own primitive topologies. -const TRIANGLE_FAN: u32 = 6; +/// Console rectangle list topology (expanded on vertex inputs in [`crate::primitive`]). const RECTANGLES: u32 = 17; -const LINE_LOOP: u32 = 18; -const QUADS: u32 = 19; -const QUAD_STRIP: u32 = 20; /// Fixed-function state, straight onto the host list. pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) { diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 04ad420ada..20f6a1b335 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -310,6 +310,8 @@ pub(crate) struct HostPipeline { /// The vertex buffer slots it reads (bit per slot). pub(crate) slots: u32, pub(crate) inputs: Vec, + /// Index buffer strip-cut value for graphics pipelines. + pub(crate) strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, /// Its shaders, for reports of slow submissions. pub(crate) name: String, } @@ -527,6 +529,7 @@ impl HostPipeline { name: format!("{shaders:?}"), slots: 0, inputs: Vec::new(), + strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, }); } let Some(g) = g else { @@ -563,6 +566,7 @@ impl HostPipeline { name: format!("{shaders:?}"), slots: 0, inputs: Vec::new(), + strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, }); } @@ -637,6 +641,7 @@ impl HostPipeline { name: format!("{shaders:?}"), slots: g.slots(), inputs: g.elements(), + strip_cut: g.strip_cut, }) } } diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index 976be2d208..e2fba782e4 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -13,6 +13,224 @@ //! components past the end of the vertex (an element that reaches into the //! next one, which the layout allows). +/// Console-only primitive topologies expanded into standard D3D12 triangle or +/// line list index buffers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ExpandedTopology { + TriangleFan, + LineLoop, + Quads, + QuadStrip, +} + +impl ExpandedTopology { + const TRIANGLE_FAN: u32 = 6; + const LINE_LOOP: u32 = 18; + const QUADS: u32 = 19; + const QUAD_STRIP: u32 = 20; + + /// Returns the expanded console topology kind, or `None` for standard PC + /// topologies and `RECTANGLES` (handled via vertex expansion). + pub(crate) fn from_console(topology: u32) -> Option { + match topology { + Self::TRIANGLE_FAN => Some(Self::TriangleFan), + Self::LINE_LOOP => Some(Self::LineLoop), + Self::QUADS => Some(Self::Quads), + Self::QUAD_STRIP => Some(Self::QuadStrip), + _ => None, + } + } + + /// Standard D3D12 primitive topology value (`LINELIST = 2`, `TRIANGLELIST = 4`). + pub(crate) fn host_topology(self) -> u32 { + match self { + Self::LineLoop => 2, + Self::TriangleFan | Self::Quads | Self::QuadStrip => 4, + } + } + + /// Maximum number of indices emitted for `count` input vertices or indices. + pub(crate) fn max_output_indices(self, count: u32) -> u32 { + match self { + Self::TriangleFan => count.saturating_sub(2).saturating_mul(3), + Self::LineLoop => { + if count >= 2 { + count.saturating_mul(2) + } else { + 0 + } + } + Self::Quads => (count / 4).saturating_mul(6), + Self::QuadStrip => { + if count >= 4 { + ((count - 2) / 2).saturating_mul(6) + } else { + 0 + } + } + } + } + + /// Expands `count` sequential 16-bit vertex indices starting at `start`. + pub(crate) fn expand_non_indexed_u16(self, count: u32, start: u16, dst: &mut [u16]) -> usize { + expand_indices( + self, + (0..count).map(|i| start.wrapping_add(i as u16)), + None, + start, + dst, + ) + } + + /// Expands `count` sequential 32-bit vertex indices starting at `start`. + pub(crate) fn expand_non_indexed_u32(self, count: u32, start: u32, dst: &mut [u32]) -> usize { + expand_indices( + self, + (0..count).map(|i| start.wrapping_add(i)), + None, + start, + dst, + ) + } + + /// Expands 16-bit indices from `src`, honoring optional strip-cut `cut` and + /// padding unused tail slots with degenerate primitives. + pub(crate) fn expand_indexed_u16( + self, + src: &[u16], + cut: Option, + fallback_pad: u16, + dst: &mut [u16], + ) -> usize { + expand_indices(self, src.iter().copied(), cut, fallback_pad, dst) + } + + /// Expands 32-bit indices from `src`, honoring optional strip-cut `cut` and + /// padding unused tail slots with degenerate primitives. + pub(crate) fn expand_indexed_u32( + self, + src: &[u32], + cut: Option, + fallback_pad: u32, + dst: &mut [u32], + ) -> usize { + expand_indices(self, src.iter().copied(), cut, fallback_pad, dst) + } +} + +fn expand_indices( + kind: ExpandedTopology, + indices: impl IntoIterator, + cut: Option, + fallback_pad: T, + dst: &mut [T], +) -> usize { + let mut written = 0usize; + let mut emit = |slice: &[T]| { + if written + slice.len() <= dst.len() { + dst[written..written + slice.len()].copy_from_slice(slice); + written += slice.len(); + } + }; + match kind { + ExpandedTopology::TriangleFan => { + let mut pivot = None; + let mut prev = None; + for v in indices { + if cut == Some(v) { + pivot = None; + prev = None; + continue; + } + match (pivot, prev) { + (None, _) => pivot = Some(v), + (Some(_), None) => prev = Some(v), + (Some(p), Some(q)) => { + emit(&[p, q, v]); + prev = Some(v); + } + } + } + } + ExpandedTopology::LineLoop => { + let mut first = None; + let mut prev = None; + let mut run_len = 0usize; + for v in indices { + if cut == Some(v) { + if run_len >= 2 + && let (Some(f), Some(p)) = (first, prev) + { + emit(&[p, f]); + } + first = None; + prev = None; + run_len = 0; + continue; + } + if let Some(p) = prev { + emit(&[p, v]); + } else { + first = Some(v); + } + prev = Some(v); + run_len += 1; + } + if run_len >= 2 + && let (Some(f), Some(p)) = (first, prev) + { + emit(&[p, f]); + } + } + ExpandedTopology::Quads => { + let mut q = [None; 3]; + let mut len = 0usize; + for v in indices { + if cut == Some(v) { + len = 0; + continue; + } + if len < 3 { + q[len] = Some(v); + len += 1; + } else if let [Some(v0), Some(v1), Some(v2)] = q { + emit(&[v0, v1, v2, v0, v2, v]); + len = 0; + } + } + } + ExpandedTopology::QuadStrip => { + let mut a = None; + let mut b = None; + let mut c = None; + for v in indices { + if cut == Some(v) { + a = None; + b = None; + c = None; + continue; + } + match (a, b, c) { + (None, _, _) => a = Some(v), + (Some(_), None, _) => b = Some(v), + (Some(_), Some(_), None) => c = Some(v), + (Some(v0), Some(v1), Some(v2)) => { + emit(&[v0, v1, v, v0, v, v2]); + a = Some(v2); + b = Some(v); + c = None; + } + } + } + } + } + if written < dst.len() { + let pad = if written > 0 { dst[0] } else { fallback_pad }; + dst[written..].fill(pad); + } + written +} + /// Expands `rects` rectangles of `stride`-byte vertices from `src` into six /// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both /// triangles turn the same way. `elements` are (byte offset, format). @@ -456,4 +674,461 @@ mod tests { } } } + + #[test] + fn expand_non_indexed_topologies() { + // QUADS: 2 quads + 1 trailing vertex ignored. + let mut out = vec![0u32; ExpandedTopology::Quads.max_output_indices(9) as usize]; + assert_eq!(out.len(), 12); + let n = ExpandedTopology::Quads.expand_non_indexed_u32(9, 10, &mut out); + assert_eq!(n, 12); + assert_eq!(out, [10, 11, 12, 10, 12, 13, 14, 15, 16, 14, 16, 17]); + + // QUAD_STRIP: 6 vertices -> 2 quads with consistent winding, 7th ignored. + let mut out = vec![0u16; ExpandedTopology::QuadStrip.max_output_indices(7) as usize]; + assert_eq!(out.len(), 12); + let n = ExpandedTopology::QuadStrip.expand_non_indexed_u16(7, 0, &mut out); + assert_eq!(n, 12); + assert_eq!(out, [0, 1, 3, 0, 3, 2, 2, 3, 5, 2, 5, 4]); + + // TRIANGLE_FAN: 5 vertices -> 3 triangles sharing pivot 0. + let mut out = vec![0u32; ExpandedTopology::TriangleFan.max_output_indices(5) as usize]; + assert_eq!(out.len(), 9); + assert_eq!( + ExpandedTopology::TriangleFan.expand_non_indexed_u32(5, 0, &mut out), + 9 + ); + assert_eq!(out, [0, 1, 2, 0, 2, 3, 0, 3, 4]); + assert_eq!(ExpandedTopology::TriangleFan.max_output_indices(2), 0); + + // LINE_LOOP: 4 vertices -> 4 segments closing 3 -> 0. + let mut out = vec![0u16; ExpandedTopology::LineLoop.max_output_indices(4) as usize]; + assert_eq!(out.len(), 8); + assert_eq!( + ExpandedTopology::LineLoop.expand_non_indexed_u16(4, 1, &mut out), + 8 + ); + assert_eq!(out, [1, 2, 2, 3, 3, 4, 4, 1]); + assert_eq!(ExpandedTopology::LineLoop.max_output_indices(1), 0); + } + + #[test] + fn expand_indexed_topologies_with_strip_cuts() { + // TRIANGLE_FAN (16-bit, 0xFFFF cut): two fans separated by cut + incomplete tail. + let src: [u16; 10] = [0, 1, 2, 3, u16::MAX, 10, 11, 12, u16::MAX, 20]; + let mut out = vec![0u16; ExpandedTopology::TriangleFan.max_output_indices(10) as usize]; + let n = ExpandedTopology::TriangleFan.expand_indexed_u16(&src, Some(u16::MAX), 0, &mut out); + assert_eq!(n, 9); + assert_eq!(&out[..9], [0, 1, 2, 0, 2, 3, 10, 11, 12]); + assert!(out[9..].iter().all(|&i| i == 0), "degenerate tail padding"); + + // QUAD_STRIP (32-bit, 0xFFFFFFFF cut): two 4-vertex strips separated by cut. + let src32: [u32; 9] = [0, 1, 2, 3, u32::MAX, 4, 5, 6, 7]; + let mut out32 = vec![0u32; ExpandedTopology::QuadStrip.max_output_indices(9) as usize]; + let n = + ExpandedTopology::QuadStrip.expand_indexed_u32(&src32, Some(u32::MAX), 0, &mut out32); + assert_eq!(n, 12); + assert_eq!(&out32[..12], [0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6]); + assert!(out32[12..].iter().all(|&i| i == 0)); + + // QUADS (16-bit cut discards incomplete 2-vertex quad before cut). + let qsrc: [u16; 7] = [0, 1, u16::MAX, 2, 3, 4, 5]; + let mut qout = vec![0u16; ExpandedTopology::Quads.max_output_indices(7) as usize]; + let n = ExpandedTopology::Quads.expand_indexed_u16(&qsrc, Some(u16::MAX), 0, &mut qout); + assert_eq!(n, 6); + assert_eq!(qout, [2, 3, 4, 2, 4, 5]); + + // LINE_LOOP (16-bit cut closes first loop before starting second). + let lsrc: [u16; 7] = [0, 1, 2, u16::MAX, 5, 6, 7]; + let mut lout = vec![0u16; ExpandedTopology::LineLoop.max_output_indices(7) as usize]; + let n = ExpandedTopology::LineLoop.expand_indexed_u16(&lsrc, Some(u16::MAX), 0, &mut lout); + assert_eq!(n, 12); + assert_eq!(&lout[..12], [0, 1, 1, 2, 2, 0, 5, 6, 6, 7, 7, 5]); + assert_eq!(&lout[12..], [0, 0]); + } + + #[cfg(windows)] + fn render_topology_test( + topology_type: windows::Win32::Graphics::Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE, + host_topology: u32, + strip_cut: windows::Win32::Graphics::Direct3D12::D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, + vertices: &[[f32; 2]], + draw_calls: &[(&[u16], i32)], + ) -> Option> { + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::{D3D_PRIMITIVE_TOPOLOGY, ID3DBlob}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::core::s; + + let host = crate::host::host()?; + const HLSL: &str = r#" +float4 vs_main(float2 pos : POSITION) : SV_Position { return float4(pos, 0.0, 1.0); } +float4 ps_main() : SV_Target { return float4(1.0, 1.0, 1.0, 1.0); } +"#; + let compile = |entry: windows::core::PCSTR, target: windows::core::PCSTR| -> Vec { + let mut blob: Option = None; + // SAFETY: static shader source and entry point strings. + unsafe { + D3DCompile( + HLSL.as_ptr().cast(), + HLSL.len(), + s!("topology_test"), + None, + None, + entry, + target, + 0, + 0, + &mut blob, + None, + ) + .unwrap(); + let blob = blob.unwrap(); + std::slice::from_raw_parts( + blob.GetBufferPointer().cast::(), + blob.GetBufferSize(), + ) + .to_vec() + } + }; + let vs = compile(s!("vs_main"), s!("vs_5_0")); + let ps = compile(s!("ps_main"), s!("ps_5_0")); + + let rs_desc = D3D12_ROOT_SIGNATURE_DESC { + Flags: D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, + ..Default::default() + }; + let mut rs_blob: Option = None; + // SAFETY: plain root signature, PSO, RT, and readback creation. + let (root, pso, rt, readback, vb, vb_gpu) = unsafe { + D3D12SerializeRootSignature(&rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut rs_blob, None) + .unwrap(); + let rs_blob = rs_blob.unwrap(); + let rs_bytes = std::slice::from_raw_parts( + rs_blob.GetBufferPointer().cast::(), + rs_blob.GetBufferSize(), + ); + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, rs_bytes).unwrap(); + let elem = D3D12_INPUT_ELEMENT_DESC { + SemanticName: s!("POSITION"), + Format: DXGI_FORMAT_R32G32_FLOAT, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + ..Default::default() + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + let mut rast = D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_BACK, + DepthClipEnable: true.into(), + ..Default::default() + }; + if topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE { + rast.CullMode = D3D12_CULL_MODE_NONE; + } + let mut pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: vs.as_ptr().cast(), + BytecodeLength: vs.len(), + }, + PS: D3D12_SHADER_BYTECODE { + pShaderBytecode: ps.as_ptr().cast(), + BytecodeLength: ps.len(), + }, + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: rast, + InputLayout: D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: &elem, + NumElements: 1, + }, + IBStripCutValue: strip_cut, + PrimitiveTopologyType: topology_type, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso: ID3D12PipelineState = + host.device.CreateGraphicsPipelineState(&pso_desc).unwrap(); + + let rt_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let def_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut rt: Option = None; + host.device + .CreateCommittedResource( + &def_heap, + D3D12_HEAP_FLAG_NONE, + &rt_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut rt, + ) + .unwrap(); + let rt = rt.unwrap(); + + let rb_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256 * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let rb_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let mut readback: Option = None; + host.device + .CreateCommittedResource( + &rb_heap, + D3D12_HEAP_FLAG_NONE, + &rb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + let readback = readback.unwrap(); + + let vb_bytes = std::mem::size_of_val(vertices) as u64; + let (vb, vb_ptr) = host.upload_buffer(vb_bytes).unwrap(); + std::ptr::copy_nonoverlapping( + vertices.as_ptr().cast::(), + vb_ptr, + vb_bytes as usize, + ); + let vb_gpu = vb.GetGPUVirtualAddress(); + (root, pso, rt, readback, vb, vb_gpu) + }; + + let list = host.new_list().unwrap(); + let rtv = host.rtv(Some(&rt), None); + // SAFETY: open command list, live resources, valid scratch index views. + unsafe { + let l = &list.list; + l.ClearRenderTargetView(rtv, &[0.0, 0.0, 0.0, 1.0], None); + l.OMSetRenderTargets(1, Some(&rtv), false, None); + l.RSSetViewports(&[D3D12_VIEWPORT { + Width: 8.0, + Height: 8.0, + MaxDepth: 1.0, + ..Default::default() + }]); + l.RSSetScissorRects(&[RECT { + right: 8, + bottom: 8, + ..Default::default() + }]); + l.SetGraphicsRootSignature(&root); + l.SetPipelineState(&pso); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host_topology as i32)); + l.IASetVertexBuffers( + 0, + Some(&[D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: vb_gpu, + SizeInBytes: std::mem::size_of_val(vertices) as u32, + StrideInBytes: 8, + }]), + ); + for &(indices, base) in draw_calls { + let bytes = (indices.len() * 2) as u64; + let (ib_gpu, ib_ptr) = list.scratch(bytes).unwrap(); + std::ptr::copy_nonoverlapping( + indices.as_ptr().cast::(), + ib_ptr, + bytes as usize, + ); + l.IASetIndexBuffer(Some(&D3D12_INDEX_BUFFER_VIEW { + BufferLocation: ib_gpu, + SizeInBytes: bytes as u32, + Format: DXGI_FORMAT_R16_UINT, + })); + l.DrawIndexedInstanced(indices.len() as u32, 1, 0, base, 0); + } + l.ResourceBarrier(&[crate::host::transition( + &rt, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Width: 8, + Height: 8, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&rt), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + } + list.close(); + host.execute(&[&list]); + drop(vb); + + let mut data = std::ptr::null_mut(); + // SAFETY: `host.execute` waited for the GPU copy into `readback`. + let pixels = unsafe { + readback.Map(0, None, Some(&mut data)).unwrap(); + let mut out = Vec::with_capacity(64); + for y in 0..8usize { + let row = std::slice::from_raw_parts(data.cast::().add(y * 256), 32); + for x in 0..8usize { + out.push([row[x * 4], row[x * 4 + 1], row[x * 4 + 2], row[x * 4 + 3]]); + } + } + readback.Unmap(0, None); + out + }; + Some(pixels) + } + + #[cfg(windows)] + #[test] + fn quads_and_strip_cut_triangle_fan_render_with_backface_culling() { + use windows::Win32::Graphics::Direct3D12::*; + // Vertices in clockwise NDC order (front-facing under D3D12_CULL_MODE_BACK): + // 0..4: non-indexed QUADS covering left half (x: -1..0, y: -1..1). + // 4..8: indexed TRIANGLE_FAN #1 covering top-right (x: 0.25..1, y: 0.25..1). + // 8..11: indexed TRIANGLE_FAN #2 covering bottom-right (x: 0.25..1, y: -1..-0.25). + let vertices: [[f32; 2]; 11] = [ + [-1.0, 1.0], + [0.0, 1.0], + [0.0, -1.0], + [-1.0, -1.0], + [0.25, 1.0], + [1.0, 1.0], + [1.0, 0.25], + [0.25, 0.25], + [0.25, -0.25], + [1.0, -0.25], + [1.0, -1.0], + ]; + let mut quad_ib = vec![0u16; ExpandedTopology::Quads.max_output_indices(4) as usize]; + ExpandedTopology::Quads.expand_non_indexed_u16(4, 0, &mut quad_ib); + + let fan_src: [u16; 8] = [4, 5, 6, 7, u16::MAX, 8, 9, 10]; + let mut fan_ib = vec![0u16; ExpandedTopology::TriangleFan.max_output_indices(8) as usize]; + ExpandedTopology::TriangleFan.expand_indexed_u16(&fan_src, Some(u16::MAX), 0, &mut fan_ib); + + let Some(px) = render_topology_test( + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ExpandedTopology::Quads.host_topology(), + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF, + &vertices, + &[(&quad_ib, 0), (&fan_ib, 0)], + ) else { + return; + }; + let at = |x: usize, y: usize| px[y * 8 + x][0]; + // Both triangles of the left-half quad must rasterize (not backface-culled). + assert_eq!(at(1, 1), 255, "quad first triangle"); + assert_eq!(at(1, 6), 255, "quad second triangle"); + // Both strip-cut-separated triangle fans on the right half must rasterize. + assert_eq!(at(6, 1), 255, "first triangle fan"); + assert_eq!(at(7, 6), 255, "second triangle fan after strip cut"); + // Middle gap between the two fans must stay black (strip cut did not bridge). + assert_eq!(at(6, 4), 0, "gap between strip-cut fans stays black"); + } + + #[cfg(windows)] + #[test] + fn quad_strip_and_line_loop_render_on_gpu() { + use windows::Win32::Graphics::Direct3D12::*; + // Indexed QUAD_STRIP with 6 vertices (2 quads, CW front-facing under CULL_MODE_BACK) + // covering the entire 8x8 target. + let strip_verts: [[f32; 2]; 6] = [ + [-1.0, -1.0], + [-1.0, 1.0], + [0.0, -1.0], + [0.0, 1.0], + [1.0, -1.0], + [1.0, 1.0], + ]; + let strip_src: [u16; 6] = [0, 1, 2, 3, 4, 5]; + let mut strip_ib = vec![0u16; ExpandedTopology::QuadStrip.max_output_indices(6) as usize]; + ExpandedTopology::QuadStrip.expand_indexed_u16(&strip_src, None, 0, &mut strip_ib); + + let Some(px) = render_topology_test( + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ExpandedTopology::QuadStrip.host_topology(), + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, + &strip_verts, + &[(&strip_ib, 0)], + ) else { + return; + }; + let pat = |x: usize, y: usize| px[y * 8 + x][0]; + assert_eq!(pat(1, 1), 255, "quad strip quad 0"); + assert_eq!(pat(6, 6), 255, "quad strip quad 1"); + + // LINE_LOOP drawing the perimeter of pixel centers (1,1)->(6,1)->(6,6)->(1,6)->(1,1). + let to_ndc = |p: f32| (p + 0.5) / 8.0 * 2.0 - 1.0; + let loop_verts: [[f32; 2]; 4] = [ + [to_ndc(1.0), -to_ndc(1.0)], + [to_ndc(6.0), -to_ndc(1.0)], + [to_ndc(6.0), -to_ndc(6.0)], + [to_ndc(1.0), -to_ndc(6.0)], + ]; + let mut loop_ib = vec![0u16; ExpandedTopology::LineLoop.max_output_indices(4) as usize]; + ExpandedTopology::LineLoop.expand_non_indexed_u16(4, 0, &mut loop_ib); + + let Some(lpx) = render_topology_test( + D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, + ExpandedTopology::LineLoop.host_topology(), + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, + &loop_verts, + &[(&loop_ib, 0)], + ) else { + return; + }; + let lat = |x: usize, y: usize| lpx[y * 8 + x][0]; + assert_eq!(lat(3, 1), 255, "top edge"); + assert_eq!(lat(6, 3), 255, "right edge"); + assert_eq!(lat(3, 6), 255, "bottom edge"); + assert_eq!(lat(1, 3), 255, "closing edge v3 -> v0"); + assert_eq!(lat(3, 3), 0, "interior stays black"); + } } From 46a825e89a7a88be5b03ead58150f9a22a2c8aaa Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:04:20 +0000 Subject: [PATCH 095/123] GPU: build the Linux tests again (view_format is Windows-only) view_format reads the host copy, which only Windows has; its only callers and test are Windows-only already, so the crate's portable tests (50) failed to compile off Windows. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/resource.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 5f3a300b5e..c99a445796 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -310,6 +310,7 @@ pub(crate) const SRGB: [(u32, u32); 7] = [ /// The format a view of a title texture must name when its host copy is /// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if /// the host copy is typed. +#[cfg(windows)] pub(crate) fn view_format(this: This) -> Option { let host = host_resource(this)?; let own = pc_format(resource(this).desc.format); From 33cd521df0c17aa60613d7054269f83c16179ed4 Mon Sep 17 00:00:00 2001 From: slaktarn Date: Tue, 24 Nov 2026 14:17:00 +0000 Subject: [PATCH 096/123] GPU: build the indirect argument clamp with Wine's compiler too Under Wine, D3DCompile is vkd3d-shader's HLSL compiler, which has no RWByteAddressBuffer methods and embeds no [RootSignature]. The clamp did not build there, and DXC (our fallback) is rarely installed beside a Proton prefix, so every indirect execution was dropped under Proton. The clamp now uses structured buffers of words (a root UAV takes either) and its root signature is built in code; both compilers take it. Same behaviour on Windows. GPU tests check the clamped values, also with descriptor heaps bound. Kept: the budget's compare-exchange loop (#863) and the DXC fallback. Hand-ported from Slaktarn700 48287165 (proton-fixes). (cherry picked from commit 48287165fb) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/indirect.rs | 170 +++++++++++++++++++++++++---- 1 file changed, 148 insertions(+), 22 deletions(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 3af15e10bf..39cb47ee76 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -4,7 +4,8 @@ //! billion vertices or a dispatch past the host's limits runs until the //! host resets the display driver. So every record is clamped on the GPU, //! just before its execution, by a compute shader of ours (HLSL compiled by -//! the system's compiler; a 5.1 shader with its root signature inside). +//! the system's compiler as a 5.1 shader, or by DXC; its root signature is +//! built here, since Wine's compiler does not embed one). //! Non-indexed rectangle-list draws follow the clamp with GPU-side //! rectangle expansion in [`crate::rectangles`]. //! @@ -25,55 +26,62 @@ use windows::core::s; use crate::host::{HostList, host, transition}; +// Written for both compilers `D3DCompile` may be: Microsoft's and, under +// Wine, vkd3d-shader's, which has no `RWByteAddressBuffer` methods and +// embeds no root signature. So the buffers are structured buffers of words +// (a root UAV takes either) and the root signature is built in code +// ([`root_signature`]). 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; }; -RWByteAddressBuffer args : register(u0); +RWStructuredBuffer args : register(u0); // The list's work so far (vertex instances, threads): past the budget, // records run empty. -RWByteAddressBuffer budget : register(u1); +RWStructuredBuffer budget : register(u1); static const uint BUDGET = 1u << 27; // Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; -[RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { if (id.x >= records) return; - uint at = id.x * stride; + uint at = id.x * (stride / 4); uint cost; 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)); + uint count = min(args[at], 1u << 24); + uint instances = min(args[at + 1], (1u << 26) / max(count, 1u)); cost = count * instances; - args.Store2(at, uint2(count, instances)); + args[at] = count; + args[at + 1] = instances; } else if (kind == 2) { - uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); + uint3 g = min(uint3(args[at], args[at + 1], args[at + 2]), 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; - args.Store3(at, g); + args[at] = g.x; + args[at + 1] = g.y; + args[at + 2] = g.z; } 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)); + uint3 g = uint3(min(args[at], 65535u), min(args[at + 1], 1u), min(args[at + 2], 1u)); cost = g.x * g.y * g.z * 128; - args.Store3(at, g); + args[at] = g.x; + args[at + 1] = g.y; + args[at + 2] = g.z; } // Saturate the shared budget instead of allowing uint wraparound. // All accesses to the counter are atomic; a rejected record must // never reopen the budget for later records. uint before; - budget.InterlockedAdd(0, 0u, before); + InterlockedAdd(budget[0], 0u, before); [allow_uav_condition] while (true) { if (before >= BUDGET) break; uint remaining = BUDGET - before; uint next = before + min(cost, remaining); uint observed; - budget.InterlockedCompareExchange(0, before, next, observed); + InterlockedCompareExchange(budget[0], before, next, observed); if (observed == before) { if (cost <= remaining) return; break; @@ -81,10 +89,56 @@ void main(uint3 id : SV_DispatchThreadID) { before = observed; } // Draws keep their layout with no vertices; groups become zero. - args.Store(at, 0); + args[at] = 0; } "#; +/// The clamp's root signature: the record's four constants (b0), the +/// arguments (u0) and the budget (u1) as root UAVs. +fn root_signature(device: &ID3D12Device) -> windows::core::Result { + let uav = |register| D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { + ShaderRegister: register, + RegisterSpace: 0, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: 4, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + uav(0), + uav(1), + ]; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + ..Default::default() + }; + let mut blob: Option = None; + let mut errors: Option = None; + // SAFETY: the description and its parameters live through the call. + unsafe { + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, Some(&mut errors))?; + let blob = blob.ok_or_else(windows::core::Error::empty)?; + device.CreateRootSignature( + 0, + std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()), + ) + } +} + /// Where `dxcompiler.dll` is looked for: `VICTORY_DXC` (the DLL or its /// folder), beside the `dxil.dll` shader validation uses (the SDK ships them /// together), then the executable's folder and System32. @@ -221,9 +275,9 @@ fn make() -> windows::core::Result { Some(&mut errors), ) }; - // Wine's d3dcompiler_47 (vkd3d-shader) rejects RWByteAddressBuffer loads: - // then DXC (dxcompiler.dll; see `dxc_library` for where it is looked for) compiles - // the same source as cs_6_0, root signature inside. + // Should the system compiler still refuse it, DXC (dxcompiler.dll; see + // `dxc_library` for where it is looked for) compiles the same source as + // cs_6_0. let fallback; if let Err(e) = &compiled { if let Some(errors) = &errors { @@ -241,7 +295,8 @@ fn make() -> windows::core::Result { } else { fallback = Vec::new(); } - // SAFETY: the blob's own bytes; the root signature is inside the shader. + let root = root_signature(device)?; + // SAFETY: the blob's own bytes. unsafe { let bytes = match (&compiled, &code) { (Ok(()), Some(code)) => std::slice::from_raw_parts( @@ -250,7 +305,6 @@ fn make() -> windows::core::Result { ), _ => &fallback[..], }; - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { @@ -351,6 +405,78 @@ pub(crate) fn uav_barrier() -> D3D12_RESOURCE_BARRIER { #[cfg(test)] mod tests { + + /// The clamp bounds a draw, a dispatch and a mesh dispatch on the GPU. + #[test] + fn arguments_are_clamped_on_the_gpu() { + clamp_on_the_gpu(false); + } + + /// The same in a list with the title's kind of descriptor heaps bound + /// (under vkd3d-proton the clamp then faulted on address 0). + #[test] + fn arguments_are_clamped_with_heaps_bound() { + clamp_on_the_gpu(true); + } + + fn clamp_on_the_gpu(heaps: bool) { + use super::*; + let Some(host) = host() else { + return; // no host GPU here + }; + let (buffer, data) = host.shared_buffer(256).unwrap(); + let words = data.cast::(); + let records: [(usize, [u32; 4]); 3] = [ + (0, [u32::MAX, 5, 0, 0]), // draw: vertices, instances + (16, [70_000, 2, 3, 0]), // dispatch + (32, [100_000, 7, 9, 0]), // mesh dispatch + ]; + for (at, w) in records { + // SAFETY: inside the mapped 256 bytes. + unsafe { std::ptr::copy_nonoverlapping(w.as_ptr(), words.add(at / 4), 4) }; + } + let list = host.new_list().unwrap(); + if heaps { + let heap = |kind, count| -> ID3D12DescriptorHeap { + // SAFETY: plain heap creation. + unsafe { + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + } + .unwrap() + }; + let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1024); + let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 16); + // SAFETY: an open list and shader-visible heaps it keeps alive. + unsafe { list.list.SetDescriptorHeaps(&[Some(views.clone()), Some(samplers.clone())]) }; + list.keep(&views); + list.keep(&samplers); + } + // SAFETY: a live buffer and an open list. + let gpu = unsafe { + list.list.ResourceBarrier(&[transition( + &buffer, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + buffer.GetGPUVirtualAddress() + }; + for (kind, at, stride) in [(0, 0, 16), (2, 16, 12), (3, 32, 12)] { + assert!(bound(&list, &buffer, gpu + at, (kind, stride, 1))); + done(&list, &buffer); + } + list.close(); + host.execute(&[&list]); + // SAFETY: the list ran (execute waits); inside the mapped bytes. + let read = |at: usize| unsafe { std::slice::from_raw_parts(words.add(at / 4), 3).to_vec() }; + assert_eq!(read(0)[..2], [1 << 24, 4]); + assert_eq!(read(16), [65_535, 2, 3]); + assert_eq!(read(32), [65_535, 1, 1]); + } /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { From fcd5c56efb81c818f8c37477fb816afad0a2cd2f Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:18:19 +0000 Subject: [PATCH 097/123] GPU: build the indirect rectangle passes with Wine's compiler too Like the argument clamp: vkd3d-shader's HLSL compiler (D3DCompile under Wine) has no RWByteAddressBuffer methods and embeds no root signature, so the rectangle expander never built under Proton and indirect rectangle-list draws were dropped. Both passes now read structured buffers of words (byte offsets become word indices; the 64-bit and wider loads and stores split into words) and take root signatures built in code, the same eight constants and root views as before. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/rectangles.rs | 147 +++++++++++++++++---------- 1 file changed, 94 insertions(+), 53 deletions(-) diff --git a/crates/victory-gpu/src/rectangles.rs b/crates/victory-gpu/src/rectangles.rs index 4dc8cbae9d..441d5eb8b3 100644 --- a/crates/victory-gpu/src/rectangles.rs +++ b/crates/victory-gpu/src/rectangles.rs @@ -17,6 +17,10 @@ //! `v3 = v0 + v2 - v1` for the formats and in-stride components that //! [`crate::primitive::expand_rects`] computes. //! +//! Both passes read structured buffers of words and take root signatures +//! built here, so Wine's HLSL compiler (vkd3d-shader, no raw buffer +//! methods or embedded root signatures) builds them too. +//! //! `ExecuteIndirect` then reads our arguments (with the title's count, if //! any) and the expanded vertices; transitions afterwards return the scratch //! buffers to unordered access, so the next indirect rectangle draw of the @@ -215,7 +219,6 @@ pub(crate) fn dispatch_grid(records: u32) -> (u32, u32) { } const REWRITE_SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=8, b0), UAV(u0), UAV(u1), UAV(u2), UAV(u3)" cbuffer Params : register(b0) { uint records; uint src_stride; @@ -226,25 +229,24 @@ cbuffer Params : register(b0) { uint pad0; uint pad1; }; -RWByteAddressBuffer src_args : register(u0); -RWByteAddressBuffer count_buf : register(u1); -RWByteAddressBuffer alloc : register(u2); -RWByteAddressBuffer dst_args : register(u3); +RWStructuredBuffer src_args : register(u0); +RWStructuredBuffer count_buf : register(u1); +RWStructuredBuffer alloc : register(u2); +RWStructuredBuffer dst_args : register(u3); -[RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { uint r = id.x; if (r >= records) return; uint dst_at = r * 16u; if (has_count != 0u) { - uint live = count_buf.Load(0u); + uint live = count_buf[(0u) >> 2]; if (r >= live) { - dst_args.Store4(dst_at, uint4(0u, 0u, 0u, 0u)); + { uint4 _v = uint4(0u, 0u, 0u, 0u); dst_args[(dst_at) >> 2] = _v.x; dst_args[((dst_at) >> 2) + 1u] = _v.y; dst_args[((dst_at) >> 2) + 2u] = _v.z; dst_args[((dst_at) >> 2) + 3u] = _v.w; } return; } } - uint4 rec = src_args.Load4(r * src_stride); + uint4 rec = uint4(src_args[(r * src_stride) >> 2], src_args[((r * src_stride) >> 2) + 1u], src_args[((r * src_stride) >> 2) + 2u], src_args[((r * src_stride) >> 2) + 3u]); // The clamp's bounds again: 2^24 vertices, 2^26 vertex instances. rec.x = min(rec.x, 1u << 24); rec.y = min(rec.y, (1u << 26) / max(rec.x, 1u)); @@ -259,7 +261,7 @@ void main(uint3 id : SV_DispatchThreadID) { out_verts = 0u; } else { uint before; - alloc.InterlockedAdd(0u, out_verts, before); + InterlockedAdd(alloc[(0u) >> 2], out_verts, before); if (before >= vert_capacity || out_verts > vert_capacity - before) { out_verts = 0u; } else { @@ -267,12 +269,11 @@ void main(uint3 id : SV_DispatchThreadID) { } } } - dst_args.Store4(dst_at, uint4(out_verts, rec.y, out_start, rec.w)); + { uint4 _v = uint4(out_verts, rec.y, out_start, rec.w); dst_args[(dst_at) >> 2] = _v.x; dst_args[((dst_at) >> 2) + 1u] = _v.y; dst_args[((dst_at) >> 2) + 2u] = _v.z; dst_args[((dst_at) >> 2) + 3u] = _v.w; } } "#; const EXPAND_SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=8, b0), SRV(t0), UAV(u0), UAV(u1), UAV(u2), UAV(u3)" cbuffer Params : register(b0) { uint records; uint src_stride; @@ -283,43 +284,43 @@ cbuffer Params : register(b0) { uint elem_count; uint pad0; }; -ByteAddressBuffer elems : register(t0); -RWByteAddressBuffer src_args : register(u0); -RWByteAddressBuffer dst_args : register(u1); -RWByteAddressBuffer src_vb : register(u2); -RWByteAddressBuffer dst_vb : register(u3); +StructuredBuffer elems : register(t0); +RWStructuredBuffer src_args : register(u0); +RWStructuredBuffer dst_args : register(u1); +RWStructuredBuffer src_vb : register(u2); +RWStructuredBuffer dst_vb : register(u3); uint load_u8(uint pos) { - uint w = src_vb.Load(pos & ~3u); + uint w = src_vb[(pos & ~3u) >> 2]; return (w >> ((pos & 3u) * 8u)) & 0xffu; } uint load_u16(uint pos) { uint rem = pos & 3u; - uint w0 = src_vb.Load(pos & ~3u); + uint w0 = src_vb[(pos & ~3u) >> 2]; if (rem <= 2u) { return (w0 >> (rem * 8u)) & 0xffffu; } - uint w1 = src_vb.Load((pos & ~3u) + 4u); + uint w1 = src_vb[((pos & ~3u) + 4u) >> 2]; return ((w0 >> 24u) | (w1 << 8u)) & 0xffffu; } uint load_u32(uint pos) { uint rem = pos & 3u; - uint w0 = src_vb.Load(pos & ~3u); + uint w0 = src_vb[(pos & ~3u) >> 2]; if (rem == 0u) { return w0; } - uint w1 = src_vb.Load((pos & ~3u) + 4u); + uint w1 = src_vb[((pos & ~3u) + 4u) >> 2]; return (w0 >> (rem * 8u)) | (w1 << ((4u - rem) * 8u)); } void store_u8(uint pos, uint val) { uint aligned = pos & ~3u; uint shift = (pos & 3u) * 8u; - uint w = dst_vb.Load(aligned); + uint w = dst_vb[(aligned) >> 2]; w = (w & ~(0xffu << shift)) | ((val & 0xffu) << shift); - dst_vb.Store(aligned, w); + dst_vb[(aligned) >> 2] = w; } void store_u16(uint pos, uint val) { @@ -327,9 +328,9 @@ void store_u16(uint pos, uint val) { if (rem <= 2u) { uint aligned = pos & ~3u; uint shift = rem * 8u; - uint w = dst_vb.Load(aligned); + uint w = dst_vb[(aligned) >> 2]; w = (w & ~(0xffffu << shift)) | ((val & 0xffffu) << shift); - dst_vb.Store(aligned, w); + dst_vb[(aligned) >> 2] = w; } else { store_u8(pos, val & 0xffu); store_u8(pos + 1u, (val >> 8u) & 0xffu); @@ -339,25 +340,25 @@ void store_u16(uint pos, uint val) { void store_u32(uint pos, uint val) { uint rem = pos & 3u; if (rem == 0u) { - dst_vb.Store(pos, val); + dst_vb[(pos) >> 2] = val; } else { uint aligned = pos & ~3u; uint shift = rem * 8u; uint inv = (4u - rem) * 8u; uint mask = (1u << shift) - 1u; - uint w0 = dst_vb.Load(aligned); + uint w0 = dst_vb[(aligned) >> 2]; w0 = (w0 & mask) | (val << shift); - dst_vb.Store(aligned, w0); - uint w1 = dst_vb.Load(aligned + 4u); + dst_vb[(aligned) >> 2] = w0; + uint w1 = dst_vb[(aligned + 4u) >> 2]; w1 = (w1 & ~mask) | (val >> inv); - dst_vb.Store(aligned + 4u, w1); + dst_vb[(aligned + 4u) >> 2] = w1; } } void copy_vertex(uint src_off, uint dst_off) { uint full = vb_src_stride & ~3u; for (uint b = 0u; b < full; b += 4u) { - dst_vb.Store(dst_off + b, load_u32(src_off + b)); + dst_vb[(dst_off + b) >> 2] = load_u32(src_off + b); } uint rem = vb_src_stride & 3u; if (rem != 0u) { @@ -365,7 +366,7 @@ void copy_vertex(uint src_off, uint dst_off) { for (uint k = 0u; k < rem; k++) { w |= load_u8(src_off + full + k) << (k * 8u); } - dst_vb.Store(dst_off + full, w); + dst_vb[(dst_off + full) >> 2] = w; } } @@ -415,16 +416,15 @@ void write_comp(uint kind, uint pos, float v) { } } -[RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { uint r = gid.y * grid_x + gid.x; if (r >= records) return; - uint out_verts = dst_args.Load(r * 16u); + uint out_verts = dst_args[(r * 16u) >> 2]; uint rects = out_verts / 6u; if (rects == 0u) return; - uint dst_start = dst_args.Load(r * 16u + 8u); - uint src_start = src_args.Load(r * src_stride + 8u); + uint dst_start = dst_args[(r * 16u + 8u) >> 2]; + uint src_start = src_args[(r * src_stride + 8u) >> 2]; for (uint rect = gtid.x; rect < rects; rect += 64u) { uint v0_src = vb_src_bias + (src_start + rect * 3u) * vb_src_stride; @@ -441,7 +441,7 @@ void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { copy_vertex(v0_src, v3_dst); for (uint e = 0u; e < elem_count; e++) { - uint2 desc = elems.Load2(e * 8u); + uint2 desc = uint2(elems[(e * 8u) >> 2], elems[((e * 8u) >> 2) + 1u]); uint offset = desc.x; uint kind = desc.y & 0xffu; uint comp_count = desc.y >> 8u; @@ -526,17 +526,67 @@ fn compile_blob( code.ok_or_else(|| (windows::core::Error::empty(), String::new())) } +/// A pass's root signature: eight constants (b0), then `srvs` root SRVs +/// (t0...) and `uavs` root UAVs (u0...), in that order. Built here since +/// Wine's compiler (vkd3d-shader) embeds none in the shader; for the same +/// compiler the passes read structured buffers of words, not raw buffers. +fn root_signature( + device: &ID3D12Device, + srvs: u32, + uavs: u32, +) -> windows::core::Result { + let view = |kind, register| D3D12_ROOT_PARAMETER { + ParameterType: kind, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { + ShaderRegister: register, + RegisterSpace: 0, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let mut params = vec![D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: 8, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }]; + params.extend((0..srvs).map(|r| view(D3D12_ROOT_PARAMETER_TYPE_SRV, r))); + params.extend((0..uavs).map(|r| view(D3D12_ROOT_PARAMETER_TYPE_UAV, r))); + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + ..Default::default() + }; + let mut blob: Option = None; + // SAFETY: the description and its parameters live through the calls. + unsafe { + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None)?; + let blob = blob.ok_or_else(windows::core::Error::empty)?; + device.CreateRootSignature( + 0, + std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()), + ) + } +} + fn compile_pass( device: &ID3D12Device, name: windows::core::PCSTR, source: &str, + (srvs, uavs): (u32, u32), ) -> windows::core::Result { let code = compile_blob(name, source).map_err(|(e, _)| e)?; - // SAFETY: the blob's own bytes; the root signature is inside the shader. + let root = root_signature(device, srvs, uavs)?; + // SAFETY: the blob's own bytes. unsafe { let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { @@ -551,8 +601,8 @@ fn compile_pass( fn make() -> windows::core::Result { let device = &host().ok_or_else(windows::core::Error::empty)?.device; - let rewrite = compile_pass(device, s!("rect_rewrite"), REWRITE_SOURCE)?; - let expand = compile_pass(device, s!("rect_expand"), EXPAND_SOURCE)?; + let rewrite = compile_pass(device, s!("rect_rewrite"), REWRITE_SOURCE, (0, 4))?; + let expand = compile_pass(device, s!("rect_expand"), EXPAND_SOURCE, (1, 4))?; Ok(Shaders { rewrite, expand }) } @@ -942,19 +992,10 @@ mod tests { assert!(shaders().is_some()); } - /// Both HLSL shaders compile with `D3DCompile` when the host compiler - /// supports `cs_5_1` raw buffers (`RWByteAddressBuffer::Load`). + /// Both HLSL shaders compile with `D3DCompile`, Wine's (vkd3d-shader) + /// too: structured buffers of words, no embedded root signature. #[test] fn hlsl_compiles() { - let probe = r#" - RWByteAddressBuffer b : register(u0); - [RootSignature("UAV(u0)")] - [numthreads(1, 1, 1)] - void main() { b.Store(0, b.Load(0)); } - "#; - if compile_blob(s!("probe"), probe).is_err() { - return; // compiler here (e.g. Wine's vkd3d-shader) lacks RWByteAddressBuffer::Load - } if let Err((e, msg)) = compile_blob(s!("rect_rewrite"), REWRITE_SOURCE) { panic!("rect_rewrite HLSL failed ({e}): {msg}"); } From 22869c80e46128ad194b46693fbedec5c2095093 Mon Sep 17 00:00:00 2001 From: pgm1207 <104554896+pgm1207@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:20:32 +0000 Subject: [PATCH 098/123] GPU: no blending on integer render targets in host pipelines The console ignores blending on integer render targets and the title leaves it on (the world has a mesh pipeline blending into an R8_UINT target). D3D12 does not allow it: vkd3d-proton refuses such a pipeline with E_INVALIDARG and its draws are lost. The host pipeline now turns blending off on integer targets; with one description for all targets, each target gets its own copy so the others keep theirs. Hand-ported from pablogonz12 ceaf80693b. (cherry picked from commit ceaf80693be2bc1ac971c3e40df2fef0d036ccfc) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/pipeline/host.rs | 122 +++++++++++++++++++++++- 1 file changed, 120 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 20f6a1b335..ddbf9cd1a2 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -93,6 +93,65 @@ impl Default for GraphicsState { } } +/// Integer render target formats: D3D12 cannot blend into them. +fn integer_format(f: DXGI_FORMAT) -> bool { + matches!( + f, + DXGI_FORMAT_R32G32B32A32_UINT + | DXGI_FORMAT_R32G32B32A32_SINT + | DXGI_FORMAT_R32G32B32_UINT + | DXGI_FORMAT_R32G32B32_SINT + | DXGI_FORMAT_R16G16B16A16_UINT + | DXGI_FORMAT_R16G16B16A16_SINT + | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R32G32_SINT + | DXGI_FORMAT_R10G10B10A2_UINT + | DXGI_FORMAT_R8G8B8A8_UINT + | DXGI_FORMAT_R8G8B8A8_SINT + | DXGI_FORMAT_R16G16_UINT + | DXGI_FORMAT_R16G16_SINT + | DXGI_FORMAT_R32_UINT + | DXGI_FORMAT_R32_SINT + | DXGI_FORMAT_R8G8_UINT + | DXGI_FORMAT_R8G8_SINT + | DXGI_FORMAT_R16_UINT + | DXGI_FORMAT_R16_SINT + | DXGI_FORMAT_R8_UINT + | DXGI_FORMAT_R8_SINT + ) +} + +/// The title's blend state as the host takes it: blending off on integer +/// render targets. The console ignores blending there, and titles leave it +/// on (the world sets it on an `R8_UINT` target), but D3D12 does not allow +/// it: vkd3d-proton refuses such a pipeline with `E_INVALIDARG` ("using +/// integer format is not supported"), and its draws are lost. With one +/// description for every target, each target gets its own copy so the +/// others keep theirs. +fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D12_BLEND_DESC { + let count = (targets.NumRenderTargets as usize).min(8); + let per_target = blend.IndependentBlendEnable.as_bool(); + let blends = |i: usize| { + blend.RenderTarget[if per_target { i } else { 0 }] + .BlendEnable + .as_bool() + }; + if !(0..count).any(|i| integer_format(targets.RTFormats[i]) && blends(i)) { + return *blend; + } + let mut host = *blend; + if !per_target { + host.IndependentBlendEnable = true.into(); + host.RenderTarget = [blend.RenderTarget[0]; 8]; + } + for i in 0..count { + if integer_format(targets.RTFormats[i]) { + host.RenderTarget[i].BlendEnable = false.into(); + } + } + host +} + impl GraphicsState { /// Takes in one subobject of a stream: its type, then its data at +4 /// (+8 for those holding pointers). @@ -575,7 +634,7 @@ impl HostPipeline { pRootSignature: unsafe { std::mem::transmute_copy(&root) }, VS: code(0), PS: code(1), - BlendState: g.blend, + BlendState: host_blend(&g.blend, &g.targets), SampleMask: g.sample_mask, RasterizerState: g.rasterizer, DepthStencilState: g.depth, @@ -733,7 +792,10 @@ fn mesh_stream( ), ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), - blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + blend: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, + host_blend(&g.blend, &g.targets), + ), mask: Sub( D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask, @@ -976,6 +1038,62 @@ fn root_signature( #[cfg(test)] mod tests { + fn targets(formats: &[DXGI_FORMAT]) -> D3D12_RT_FORMAT_ARRAY { + let mut t = D3D12_RT_FORMAT_ARRAY { + NumRenderTargets: formats.len() as u32, + ..Default::default() + }; + t.RTFormats[..formats.len()].copy_from_slice(formats); + t + } + + fn blending(independent: bool) -> D3D12_BLEND_DESC { + let mut b = GraphicsState::default().blend; + b.IndependentBlendEnable = independent.into(); + for t in &mut b.RenderTarget { + t.BlendEnable = true.into(); + t.SrcBlend = D3D12_BLEND_SRC_ALPHA; + t.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + } + b + } + + #[test] + fn integer_targets_do_not_blend() { + let t = targets(&[ + DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16B16A16_FLOAT, + DXGI_FORMAT_R8_UINT, + ]); + for independent in [false, true] { + let host = host_blend(&blending(independent), &t); + assert!(host.IndependentBlendEnable.as_bool()); + assert!(host.RenderTarget[0].BlendEnable.as_bool()); + assert!(host.RenderTarget[1].BlendEnable.as_bool()); + assert!(!host.RenderTarget[2].BlendEnable.as_bool()); + // The rest of the target's state is the title's. + assert_eq!(host.RenderTarget[2].SrcBlend, D3D12_BLEND_SRC_ALPHA); + assert_eq!(host.RenderTarget[0].DestBlend, D3D12_BLEND_INV_SRC_ALPHA); + } + } + + #[test] + fn blend_states_without_integer_blending_are_kept() { + // No integer target. + let b = blending(false); + let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R11G11B10_FLOAT]); + assert_eq!(host_blend(&b, &t), b); + // An integer target that does not blend. + let mut b = blending(true); + b.RenderTarget[1].BlendEnable = false.into(); + let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT]); + assert_eq!(host_blend(&b, &t), b); + // Integer formats past the targets in use. + let mut t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM]); + t.RTFormats[1] = DXGI_FORMAT_R8_UINT; + assert_eq!(host_blend(&blending(false), &t), blending(false)); + } + /// A stream's `DEPTH_STENCIL1` keeps its depth bounds test; a plain /// `DEPTH_STENCIL` after it turns the test off again. #[test] From 7dfeb979e8fc8f60e42fd0f842f80b943a62c7df Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:22:36 +0000 Subject: [PATCH 099/123] Shaders: carry-ins on untracked masks, inline 0 and -1 select masks v_*_co_ci_u32 refused when its carry-in mask was not one structure followed (a plain SGPR number), and v_cndmask_b32 refused inline 0 and -1 masks. A carry-in now fails as an untracked select does, so compute retries it with console lanes and the lane tests its own bit of the register (pair in wave64); inline 0 and -1 masks are constants. Ported from undeadhuman37 fda0c774ef (from upstream PR #585, the mask part); our selects had the console-lane fallback already. New test runs on Linux: fails before, passes after. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 50 +++++++++++++++++++------ crates/victory-shader/src/emit/mod.rs | 19 ++++++++++ 2 files changed, 57 insertions(+), 12 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 05ed11e8be..4d8aa86262 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -457,15 +457,28 @@ fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { }) } -/// A select that needs the actual scalar mask words and console lane index. +/// A select or carry-in that needs the actual scalar mask words and console +/// lane index. fn numeric_select(st: &Structured, inst: &Inst) -> bool { - inst.name() == "v_cndmask_b32" - && matches!(&inst.fields, Fields::Valu(v) - if matches!(v.src.get(2), Some(Operand::Scalar { code, .. }) if *code != NULL)) - && inst + let Fields::Valu(v) = &inst.fields else { + return false; + }; + let Some(&Operand::Scalar { code, .. }) = v.src.get(2) else { + return false; + }; + if code == NULL { + return false; + } + match inst.name() { + "v_cndmask_b32" => inst .writes .first() - .is_some_and(|&(_, v)| !st.select_masks.contains_key(&v)) + .is_some_and(|&(_, v)| !st.select_masks.contains_key(&v)), + "v_add_co_ci_u32" | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => inst + .read(Reg::S(code)) + .is_none_or(|m| !st.masks.contains_key(&m)), + _ => false, + } } /// Where half `h` (dword h / 2, the high half when odd) of a parameter @@ -2304,8 +2317,19 @@ impl<'a> Lower<'a> { { return self.boolean(m, self.cur); } - let Some(&Operand::Scalar { code, .. }) = mask else { - return Err(UNTRACKED_SELECT); + self.numeric_mask(inst, mask) + } + + /// This lane's bit of a select or carry-in mask `structure` did not + /// follow: inline 0 and -1 are constants; a scalar register (pair in + /// wave64) is tested by the console lane, in compute programs run with + /// console lanes (the retry after [`UNTRACKED_SELECT`]). + fn numeric_mask(&mut self, inst: &Inst, mask: Option<&Operand>) -> Result { + let code = match mask { + Some(&Operand::Scalar { code, .. }) => code, + Some(&Operand::Const(128)) => return Ok(self.s.m.bool(false)), + Some(&Operand::Const(193)) => return Ok(self.s.m.bool(true)), + _ => return Err(UNTRACKED_SELECT), }; if code == NULL { return Ok(self.s.m.bool(false)); @@ -5414,10 +5438,12 @@ impl<'a> Lower<'a> { Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), _ => None, }; - let m = m - .and_then(|m| self.x.st.masks.get(&m).copied()) - .ok_or("a carry-in from an untracked mask")?; - Some(self.boolean(m, c)?) + // An untracked carry-in fails as an untracked select + // does, so compute retries it with console lanes. + match m.and_then(|m| self.x.st.masks.get(&m).copied()) { + Some(m) => Some(self.boolean(m, c)?), + None => Some(self.numeric_mask(inst, v.src.get(2))?), + } } else { None }; diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 2f59c7e95f..dbdb4ca2f3 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1015,6 +1015,25 @@ mod tests { emit(&c, &native, &p, &st, &io, &res) } + /// Selects and carry-ins whose mask `structure` does not follow (a plain + /// SGPR, here a root constant) translate: compute tests this lane's bit + /// of the number. Inline 0 and -1 masks are constants. + #[test] + fn untracked_select_and_carry_masks_translate() { + let vop3 = |op: u32, sdst: u32, s0: u32, s1: u32, s2: u32| { + [0xD400_0000 | op << 16 | sdst << 8, s0 | s1 << 9 | s2 << 18] + }; + let (v1, v2, s3) = (257, 258, 3); + for mask in [s3, 128, 193] { + // v_cndmask_b32_e64 v0, v1, v2, mask + translate_stored(&vop3(0x101, 0, v1, v2, mask)).unwrap(); + // v_add_co_ci_u32_e64 v0, null, v1, v2, mask (and sub, subrev) + for op in [0x128, 0x129, 0x12A] { + translate_stored(&vop3(op, 125, v1, v2, mask)).unwrap(); + } + } + } + /// The 64-bit multiply-adds of 32-bit operands translate, both halves /// of the result and the unsigned form's carry; reading the signed /// form's carry, which is not modelled, is refused with a reason. From be98ae6e853f4bf2e395a8695d31f12383b7ee5b Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:24:18 +0000 Subject: [PATCH 100/123] Shaders: a view only read as data takes its kind from its table's range A descriptor whose dwords the code reads as numbers (a size) but never uses was taken only when eight dwords with no range or an SRV range: a 2D texture. Now the range the entry falls in says what it is: a storage image's or a buffer's size (raw, or structured by the range's stride) translates too. Four dwords no range names stay refused. The fork measured "a descriptor read only as data" 395 -> 18 over its corpus with this change (compute emitted 1441 -> 1743). New Linux test: fails before, passes after. Ported from undeadhuman37 9d8df9040f. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 33 +++++++++++++------- crates/victory-shader/src/emit/mod.rs | 40 +++++++++++++++++++++++-- 2 files changed, 61 insertions(+), 12 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 4d8aa86262..84fe7b0545 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3974,22 +3974,35 @@ impl<'a> Lower<'a> { }; (first, src, props, image, uav) } else { - // An image the program only measures (it reads the size bits and - // samples the image in other programs): eight dwords are an image - // descriptor, taken here as a 2D texture. + // A view the program only measures (it reads the size bits and + // uses the view in other programs). The table's range, when one + // names the entry, says what it is; else the dwords read do: + // eight are an image descriptor, taken here as a 2D texture, and + // four a buffer only when a range gives its kind. // shortcut: a 3D or array image would report depth or layers 1. + const NONE: Why = "a descriptor read only as data"; let src = Source::Loaded { load: site, first: 0, }; - if count != 8 - || self - .used_kind(&src) - .is_some_and(|u| u.kind != ResourceType::Srv) - { - return Err("a descriptor read only as data"); + let used = self.used_kind(&src); + let (dwords, stride) = match used { + Some(u) if matches!(u.kind, ResourceType::Srv | ResourceType::Uav) => { + (u32::from(u.dwords), u.stride) + } + None => (count, 0), + Some(_) => return Err(NONE), + }; + let u = self.uav_bits(&src, used); + let uav = u & 0x1000 != 0; + match dwords { + 8 => (0, src, (2 | u, 0x409), Some(2), uav), + 4 if stride >= 4 && stride.is_multiple_of(4) => { + (0, src, (12 | u, stride), None, uav) + } + 4 if used.is_some() => (0, src, (11 | u, 0), None, uav), + _ => return Err(NONE), } - (0, src, (2, 0x409), Some(2), false) }; let h = self.handle(site, &src, false, props)?; let c = self.cur; diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index dbdb4ca2f3..441e7b074b 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -962,6 +962,14 @@ mod tests { /// of the GPU tests in `valu_tests`), so a value `body` cannot produce /// stops the translation. fn translate_stored(body: &[u32]) -> Result { + translate_stored_with(body, &[]) + } + + /// [`translate_stored`] with more resources of the table declared. + fn translate_stored_with( + body: &[u32], + more: &[crate::native::UsedResource], + ) -> Result { use crate::native::{ResourceType, RootParam, UsedResource}; let mut words = vec![ 0xBE85_0380, // s_mov_b32 s5, 0 @@ -990,7 +998,7 @@ mod tests { param(RootType::Constants, 4, 0, 0), param(RootType::Table, 1, 4, 1), ], - used: vec![UsedResource { + used: [UsedResource { kind: ResourceType::Uav, root: RootType::Table, table_offset_dwords: 0, @@ -999,7 +1007,10 @@ mod tests { dwords: 4, user_data: 4, slot: 1, - }], + }] + .into_iter() + .chain(more.iter().cloned()) + .collect(), io: StageIo::Cs(ComputeIo { rsrc2: 5 << 1, threads: [1, 1, 1], @@ -1015,6 +1026,31 @@ mod tests { emit(&c, &native, &p, &st, &io, &res) } + /// A view the program only measures takes its kind from the table's + /// range: a structured buffer's or a storage image's size, read as + /// data and never used here, translates. + #[test] + fn descriptor_read_only_as_data_takes_its_kind_from_the_range() { + use crate::native::{ResourceType, UsedResource}; + let range = |kind, dwords, stride| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 4, + lower_bound: 1, + stride, + dwords, + user_data: 4, + slot: 1, + }; + // s_load_dwordx4 s[12:15], s[4:5], 16; v_mov_b32 v0, s14 (records) + let buffer = [0xF408_0302, 0xFA00_0010, 0x7E00_020E]; + translate_stored_with(&buffer, &[range(ResourceType::Srv, 4, 16)]).unwrap(); + translate_stored_with(&buffer, &[range(ResourceType::Uav, 4, 0)]).unwrap(); + // s_load_dwordx8 s[12:19], s[4:5], 16; v_mov_b32 v0, s14 (height) + let image = [0xF40C_0302, 0xFA00_0010, 0x7E00_020E]; + translate_stored_with(&image, &[range(ResourceType::Uav, 8, 0)]).unwrap(); + } + /// Selects and carry-ins whose mask `structure` does not follow (a plain /// SGPR, here a root constant) translate: compute tests this lane's bit /// of the number. Inline 0 and -1 masks are constants. From 90a182d61eda08392f1efbafc49d24cfbe131673 Mon Sep 17 00:00:00 2001 From: undeadhuman37 <343031842+undeadhuman37@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:25:21 +0000 Subject: [PATCH 101/123] Shaders: a lane mask spilled to a VGPR lane is still that mask The console compiler spills scalars, lane-mask pairs among them, with v_writelane_b32 into constant lanes of a VGPR and restores them with v_readlane_b32 of the same lane. The restored pair was an opaque mask, so the selects, EXEC writes and joins that used it refused ("a select on an untracked mask", "an opaque lane mask", "a lane-mask join of an untracked mask"). structure now follows a constant-lane readlane back through a plain chain of writelanes to the scalar written to that lane, and gives the restored pair that scalar pair's mask. A chain with a phi or another write of the VGPR stays opaque (shortcut noted in code). The fork measured vertex/pixel programs emitted 12250 -> 12269 and compute 1443 -> 1452. The test runs on Linux: fails before, passes after. (cherry picked from commit fec0486061b5483afa0151ca6611cd63128cbafb) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/mod.rs | 69 ++++++++++++++++++++++++++ crates/victory-shader/src/structure.rs | 51 ++++++++++++++++++- 2 files changed, 119 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 441e7b074b..39257ddfc3 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -483,6 +483,75 @@ mod tests { use super::*; use crate::native::{ComputeIo, StageIo}; + /// Emits a pixel program that writes depth and stencil from `v0` and `v1`. + fn emit_depth_stencil_ps(words: &[u32], wave64: bool) -> Result<(), crate::ShaderError> { + let native = NativeProgram { + stage: HwStage::Ps, + wave64, + vgprs: 2, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let el = |name: &str, kind, comp| SigElement { + name: name.into(), + index: 0, + kind, + comp, + interp: 0, + row: None, + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let osg1 = + container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let out = emit(&c, &native, &p, &st, &io, &res)?; + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + Ok(()) + } + + /// A lane mask spilled into a VGPR lane (`v_writelane_b32`) and restored + /// into another SGPR (`v_readlane_b32`, same constant lane) is the same + /// mask: the select below followed it as an untracked one and refused. + #[test] + fn a_lane_mask_spilled_to_a_vgpr_lane_stays_a_mask() { + let words = [ + 0x7E00_02F2u32, // v_mov_b32 v0, 1.0 + 0xD405_000A, // v_cmp_lg_f32_e64 s10, v0, 0 + 0x0001_0100, + 0xD761_0001, // v_writelane_b32 v1, s10, 0 + 0x0001_000A, + 0xD760_000C, // v_readlane_b32 s12, v1, 0 + 0x0001_0101, + 0xD501_0002, // v_cndmask_b32_e64 v2, 0, 1, s12 + 0x0031_0280, + 0x7E02_0302, // v_mov_b32 v1, v2 + 0xF800_1883, // exp mrtz v0, v1, off, off done vm + 0x0000_0100, + 0xBF81_0000, // s_endpgm + ]; + emit_depth_stencil_ps(&words, false).unwrap(); + } + /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`). /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose /// output signature has SV_StencilRef, and the feature bit diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index e1dc04dfe5..0b4e23c9aa 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -747,6 +747,51 @@ impl<'a> Lanes<'a> { } } + /// The scalar a `v_readlane_b32` of a constant lane gives back: the one + /// a `v_writelane_b32` of the same lane put into that VGPR (the console + /// compiler spills scalars, lane masks among them, into VGPR lanes). + fn spilled(&self, v: Value) -> Option { + let at = |v: Value| { + let &(b, i) = self.defs.get(&v)?; + Some(&self.p.blocks[b].insts[i]) + }; + let lane = |op: Option<&Operand>| match op { + Some(&Operand::Const(c @ 128..=192)) => Some(c - 128), + _ => None, + }; + let read = at(v)?; + let Fields::Valu(r) = &read.fields else { + return None; + }; + let k = lane(r.src.get(1)).filter(|_| read.name() == "v_readlane_b32")?; + let Some(&Operand::Vector { reg, .. }) = r.src.first() else { + return None; + }; + let mut vgpr = read.read(Reg::V(reg))?; + // shortcut: only a straight chain of lane writes; a phi or any other + // write of the VGPR ends the search (the mask stays opaque). + for _ in 0..64 { + let w = at(vgpr)?; + let Fields::Valu(w) = &w.fields else { + return None; + }; + if at(vgpr)?.name() != "v_writelane_b32" { + return None; + } + let (Some(&Operand::Scalar { code, .. }), Some(&Operand::Vector { reg, .. })) = + (w.src.first(), w.dst.as_ref()) + else { + return None; + }; + let inst = at(vgpr)?; + if lane(w.src.get(1))? == k { + return inst.read(Reg::S(code)); + } + vgpr = inst.read(Reg::V(reg))?; + } + None + } + /// The mask a value pair holds, and whether it derives from EXEC or a /// VALU result. fn mask(&mut self, k: Key) -> (Bool, bool) { @@ -757,7 +802,11 @@ impl<'a> Lanes<'a> { return (m, false); } let p = self.p; - let (m, derived) = match self.join(k) { + let spilled = self + .spilled(k.0) + .zip(self.spilled(k.1)) + .filter(|&(a, b)| (a, b) != k); + let (m, derived) = match spilled.map(|s| self.mask(s)).or_else(|| self.join(k)) { Some(join) => join, None => { let (lo, hi) = (self.defs.get(&k.0).copied(), self.defs.get(&k.1).copied()); From e1b2e42b80d68917419703aad3192ed4ddef2fb6 Mon Sep 17 00:00:00 2001 From: undeadhuman37 <343031842+undeadhuman37@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:26:50 +0000 Subject: [PATCH 102/123] Shaders: a scalar joining a lane mask and a number lowers in pixel and vertex programs A register can hold a compare result's high dword on one path and a loaded number on another; the compiler only reads it where the number is live. The join's mask side was "a lane mask read as data", which refused the program. A pixel or vertex program now takes the mask's ballot as that incoming value (counts and zero tests mean the same on any wave size). shortcut: the ballot is the host wave's, so a join read some other way would differ from the console. The fork measured "a lane mask read as data" 250 -> 212. Hand-ported (the ballot is only taken where the incoming value is missing); the test runs on Linux and fails before. (cherry picked from commit 3e662eb84e0e6b7127633bfc768ed66250f72c70) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 72 ++++++++++++++++--------- crates/victory-shader/src/emit/mod.rs | 25 +++++++++ 2 files changed, 72 insertions(+), 25 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 84fe7b0545..4de6c64c7b 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -8526,33 +8526,55 @@ impl<'a> Lower<'a> { let Some(qb) = self.tail[q] else { continue }; let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); let arg = phi.args[n]; - let x = match (self.vals.get(&arg).copied(), bit) { - (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, - (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { - return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); - } - // A descriptor's dwords reaching a join that also takes - // data (the registers are reused after the last access). - // shortcut: undefined on that edge, assuming the program - // reads the joined value only after the data edge. - (Some(Val::Missing(_)), _) if self.descriptor_dword(arg) => { - if bit { - self.s.m.undef(self.s.t.i1) - } else { - self.s.m.undef(self.s.t.i32) + // A mask dword the other path left in the register: its + // ballot (a pixel or vertex program reads such a join only + // through a zero test or a count, the same on any wave size). + // shortcut: the ballot is the host wave's, so a join read + // some other way would differ from the console. + let val = self.vals.get(&arg).copied(); + let lo = self.x.st.highs.get(&arg).copied().unwrap_or(arg); + let ballot = if self.mask_data == MaskData::Host + && !bit + && matches!(val, None | Some(Val::Missing(_))) + && self.read_phis.contains(&phi.value) + && self.x.st.masks.contains_key(&lo) + && self.def_block.get(&lo).is_some_and(|&d| d != self.cur_ir) + { + self.mask_dword(arg).ok() + } else { + None + }; + let x = if let Some(x) = ballot { + x + } else { + match (val, bit) { + (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, + (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); } + // A descriptor's dwords reaching a join that also takes + // data (the registers are reused after the last access). + // shortcut: undefined on that edge, assuming the program + // reads the joined value only after the data edge. + (Some(Val::Missing(_)), _) if self.descriptor_dword(arg) => { + if bit { + self.s.m.undef(self.s.t.i1) + } else { + self.s.m.undef(self.s.t.i32) + } + } + (Some(Val::Missing(why)), _) + if self.read_phis.contains(&phi.value) + || through.contains(&phi.value) && self.zero_is_wrong(arg) => + { + return Err(Stop::Retry(phi.value, why)); + } + _ if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, "a join of mismatched values")); + } + _ if bit => self.s.m.bool(false), + _ => self.s.m.i32(0), } - (Some(Val::Missing(why)), _) - if self.read_phis.contains(&phi.value) - || through.contains(&phi.value) && self.zero_is_wrong(arg) => - { - return Err(Stop::Retry(phi.value, why)); - } - _ if self.read_phis.contains(&phi.value) => { - return Err(Stop::Retry(phi.value, "a join of mismatched values")); - } - _ if bit => self.s.m.bool(false), - _ => self.s.m.i32(0), }; incoming.push((x, qb)); } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 39257ddfc3..132ccf7d76 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -529,6 +529,31 @@ mod tests { Ok(()) } + /// A wave64 pixel program whose SGPR holds a lane mask's high dword (a compare result) on one + /// path and a number on the other, then compares it with zero: the + /// join's mask side was a lane mask read as data, which refused the + /// whole program. The ballot stands in for it (wave-size independent for + /// the zero test the console compiler emits). + #[test] + fn a_scalar_joining_a_lane_mask_and_a_number_lowers_in_pixel_programs() { + let words = [ + 0x7E00_02F2u32, // v_mov_b32 v0, 1.0 + 0xD405_000A, // v_cmp_lg_f32_e64 s[10:11], v0, 0 + 0x0001_0100, + 0xBE8C_0383, // s_mov_b32 s12, 3 + 0xBF02_850C, // s_cmp_gt_i32 s12, 5 + 0xBF85_0001, // s_cbranch_scc1 +1 (past the next word) + 0xBE8B_0385, // s_mov_b32 s11, 5 + 0xBF06_800B, // s_cmp_eq_u32 s11, 0 + 0x850D_8081, // s_cselect_b32 s13, 1, 0 + 0x7E02_020D, // v_mov_b32 v1, s13 + 0xF800_1883, // exp mrtz v0, v1, off, off done vm + 0x0000_0100, + 0xBF81_0000, // s_endpgm + ]; + emit_depth_stencil_ps(&words, true).unwrap(); + } + /// A lane mask spilled into a VGPR lane (`v_writelane_b32`) and restored /// into another SGPR (`v_readlane_b32`, same constant lane) is the same /// mask: the select below followed it as an untracked one and refused. From b096277676ffe2b5a0bcb6fe4c5926961bd78bbd Mon Sep 17 00:00:00 2001 From: kaoxyd Date: Tue, 24 Nov 2026 14:28:37 +0000 Subject: [PATCH 103/123] Shaders: mesh primitives with indices past the vertex count are culled The console packs a primitive's three vertex indices in 10-bit fields (up to 1023), while the host mesh shader declares max_vertices outputs. EmitIndices with an index at or past that count is undefined; on an RTX 5080 a shadow mesh program hung the GPU on such a draw. A primitive with any index out of range is now culled like bit 31 does (all indices 0, no area). Likewise a console group can have more lanes than the mesh declares vertices or primitives: a lane past the declared count no longer writes a vertex, primitive output or primitive (undefined on the host). From kaoxyd 4f5ffe35e2 (jlefebure's fork) and Mic0Lee 48fea7bae0, 2389344c78, ff658795d4, hand-ported. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 106 ++++++++++++++++++++++- crates/victory-shader/src/emit/shader.rs | 6 ++ 2 files changed, 108 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 4de6c64c7b..3bcfb2e0ba 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -56,6 +56,9 @@ pub(crate) struct Lowered { /// Whether the program uses wave operations. #[cfg(test)] pub wave_ops: bool, + /// Mesh primitive exports bounded by the declared vertex count. + #[cfg(test)] + pub bounded_prims: u32, } pub(crate) struct Parts<'a> { @@ -1238,6 +1241,8 @@ impl<'a> Lower<'a> { heap_props: std::mem::take(&mut self.s.heap_props), #[cfg(test)] wave_ops: self.s.flags & flags::WAVE_OPS != 0, + #[cfg(test)] + bounded_prims: self.s.bounded_prims, dxil: self.s.finish(), user_data, samplers: self.samplers, @@ -8050,7 +8055,7 @@ impl<'a> Lower<'a> { if e.compressed && !matches!(e.target, Target::Color(_) | Target::Depth) { return Err("a compressed export"); } - let guard = self.guard(b, i)?; + let mut guard = self.guard(b, i)?; let mesh = self.s.mesh.is_some(); let pixel_done = self.s.pixel && e.done; let c = self.cur; @@ -8063,6 +8068,15 @@ impl<'a> Lower<'a> { self.s .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]); } + // A console group can have more lanes than the mesh declares + // outputs; a host write past the declared count is undefined. + if let Some(m) = self.s.mesh { + let max = match e.target { + Target::Primitive | Target::PrimitiveParam { .. } => m.max_primitives, + _ => m.max_vertices, + }; + guard = self.mesh_output_guard(guard, max); + } if mesh && e.target == Target::Primitive { return self.emit_indices(e, guard); } @@ -8254,20 +8268,55 @@ impl<'a> Lower<'a> { Ok(()) } + /// Keeps a mesh lane from writing past the output count the host + /// shader declares (`max`), when the console group has more lanes. + fn mesh_output_guard(&mut self, guard: Option, max: u32) -> Option { + let lanes = self.s.threads.map_or(u32::MAX, |t| t[0]); + if lanes <= max { + return guard; + } + let lane = self.mesh_thread(); + let limit = self.s.m.i32(max); + let within = self.s.m.cmp(self.cur, pred::IULT, lane, limit); + Some(match guard { + Some(guard) => self.s.m.bin(self.cur, Bin::And, guard, within), + None => within, + }) + } + /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all - /// indices 0: no area). + /// indices 0: no area), and so does an index at or past the declared + /// vertex count: the console's 10-bit fields reach 1023, and an index + /// outside the mesh outputs is undefined on the host (an NVIDIA driver + /// was seen to hang on such a draw). fn emit_indices(&mut self, e: &Export, guard: Option) -> Result<(), Why> { let v = e.values[0].ok_or("a primitive export without its indices")?; let x = self.i32_of(v)?; + let max_vertices = self + .s + .mesh + .ok_or("a primitive export outside a mesh shader")? + .max_vertices; let at = self.begin_guarded(guard); let c = self.cur; let z = self.s.m.i32(0); - let culled = self.s.m.cmp(c, pred::SLT, x, z); - let mut args = vec![self.mesh_thread()]; + let limit = self.s.m.i32(max_vertices); + let mut culled = self.s.m.cmp(c, pred::SLT, x, z); + let mut indices = Vec::with_capacity(3); for k in 0..3 { let (shift, mask) = (self.s.m.i32(10 * k), self.s.m.i32(0x3FF)); let i = self.s.m.bin(c, Bin::LShr, x, shift); let i = self.s.m.bin(c, Bin::And, i, mask); + let outside = self.s.m.cmp(c, pred::IUGE, i, limit); + culled = self.s.m.bin(c, Bin::Or, culled, outside); + indices.push(i); + } + #[cfg(test)] + { + self.s.bounded_prims += 1; + } + let mut args = vec![self.mesh_thread()]; + for i in indices { args.push(self.s.m.select(c, culled, z, i)); } let void = self.s.t.void; @@ -9243,6 +9292,55 @@ mod tests { }) } + /// A primitive export is bounded by the declared vertex count (the + /// console's 10-bit fields reach 1023), and a group with more lanes + /// than outputs translates with its writes guarded. + #[test] + fn mesh_primitive_indices_are_bounded_by_the_vertex_count() { + let words = [ + 0x7E04_0505u32, // v_readfirstlane_b32 s2, v5 (the group input) + 0xF800_0941, + 0x0000_0009, // exp prim, v9, off, off, off done + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Ms, + wave64: true, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Ms(crate::native::MeshIo { + outputs: vec![], + clip_cntl: 0, + threads: 128, + max_vertices: 64, + max_primitives: 96, + topology: 2, + lds_bytes: 0, + }), + code, + }; + let p = ir::build(&native.code, true, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let l = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + host_wave64: true, + }) + .unwrap(); + assert_eq!(l.bounded_prims, 1); + } + /// Root parameter `slot` in user SGPRs from `user_data` on. fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { RootParam { diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 9c9a6b022c..3ca41bec05 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -70,6 +70,10 @@ pub(crate) struct Shader { pub flags: u64, /// Heap handles made with a non-uniform index. pub nonuniform_handles: u32, + /// Mesh primitive exports whose indices are checked against the + /// declared vertex count. + #[cfg(test)] + pub bounded_prims: u32, /// Each heap handle's resource properties, in creation order. #[cfg(test)] pub heap_props: Vec<(u32, u32)>, @@ -128,6 +132,8 @@ impl Shader { flags: 0, nonuniform_handles: 0, #[cfg(test)] + bounded_prims: 0, + #[cfg(test)] heap_props: Vec::new(), threads: None, wave_size: None, From b7e8d83cc3c8e4a7cea951860beb38bba0021f37 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 14:31:20 +0000 Subject: [PATCH 104/123] Shaders: spin-wait loops stop after 4096 iterations, not 2^20 A loop that only rereads one address until another workgroup, queue or the command processor changes it (decoupled look-back, persistent-thread queues, locks) waits microseconds on the console. On the host the write may never come: the writer's view can be another host resource, null or not yet mirrored, and the host compiler may hoist a load out of a loop that writes nothing (bufferLoad is readonly). The loop then runs to the 2^20 limit in every lane: about a second per wave of uncached reads, the order of the 650-930 ms world submissions spend on an RX 7600. Such loops are found in the IR (emit/spin.rs): no stores, exports, LDS writes, barriers or messages; every memory read and atomic at an address the loop does not change; and nothing loop-carried made by arithmetic, only lane masks, compares and what was read. They stop at VICTORY_SHADER_SPIN_LIMIT (default 4096, never above the loop limit); the shader cache keys on it. VICTORY_SHADER_LOOP_LIMIT now works in release builds too (PastiiJay e5b117a16f). Ported from PastiiJay/klbf-lab 1fcaf13243 and e5b117a16f. (cherry picked from commit 1fcaf13243cdd646bec6efeaf16b0c6c01d848d7) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- README.md | 3 +- crates/victory-gpu/src/shader_cache.rs | 15 +- crates/victory-shader/src/emit/lower.rs | 103 ++++- crates/victory-shader/src/emit/mod.rs | 52 ++- crates/victory-shader/src/emit/spin.rs | 478 ++++++++++++++++++++++++ 5 files changed, 635 insertions(+), 16 deletions(-) create mode 100644 crates/victory-shader/src/emit/spin.rs diff --git a/README.md b/README.md index 4cdc6b0d0f..d68e87efdd 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,8 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic | `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver); `=0` turns it back off, so one shell variable can stay set between runs | | `VICTORY_ADAPTER=` | select a D3D12 adapter by case-insensitive substring (default: high-performance GPU) | -| `VICTORY_SHADER_LOOP_LIMIT=` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | +| `VICTORY_SHADER_LOOP_LIMIT=` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries; works in release builds too); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | +| `VICTORY_SHADER_SPIN_LIMIT=` | loops that only reread memory until another workgroup or queue changes it (spin waits) stop after `n` iterations per lane instead of 4096 (own shader cache entries); `1048576` restores the general limit for them | | `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) | | `VICTORY_XMA_DUMP=` | saves the first 32 XMA voices' context and input | diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index a7ee403073..16dbd7e899 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -37,9 +37,10 @@ pub(crate) fn counts() -> (u64, u64) { } /// What identifies this build: the BLAKE3 of our executable file and of -/// the translation settings it runs with (the loop limit, which a -/// diagnostics build can change at run time, and whether the host device -/// runs 64-lane waves, known once it is created). +/// the translation settings it runs with (the loop and spin-wait limits, +/// which `VICTORY_SHADER_LOOP_LIMIT` and `VICTORY_SHADER_SPIN_LIMIT` change +/// at run time, and whether the host device runs 64-lane waves, known once +/// it is created). fn build() -> &'static [u8; 32] { static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); BUILD.get_or_init(|| { @@ -51,9 +52,17 @@ fn build() -> &'static [u8; 32] { "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner" ); } + let spin = victory_shader::emit::spin_limit(); + if spin != victory_shader::emit::DEFAULT_SPIN_LIMIT { + tracing::warn!( + spin, + "VICTORY_SHADER_SPIN_LIMIT: spin-wait loops stop at this count" + ); + } match exe { Ok(mut bytes) => { bytes.extend_from_slice(&limit.to_le_bytes()); + bytes.extend_from_slice(&spin.to_le_bytes()); bytes.push(u8::from(victory_shader::emit::host_wave64())); *blake3::hash(&bytes).as_bytes() } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 3bcfb2e0ba..a0fa970902 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -59,6 +59,9 @@ pub(crate) struct Lowered { /// Mesh primitive exports bounded by the declared vertex count. #[cfg(test)] pub bounded_prims: u32, + /// Back edges that count against the spin-wait limit. + #[cfg(test)] + pub spin_loops: usize, } pub(crate) struct Parts<'a> { @@ -261,6 +264,12 @@ struct Lower<'a> { counters: HashMap)>, /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. abort: Option, + /// Headers of loops that only wait for memory to change: they stop + /// at [`super::spin_limit`] instead. + spin: HashSet, + /// Back edges given the spin-wait limit. + #[cfg(test)] + spun: usize, /// Compute needing the console's 64-lane wave on a host without one, /// in a group that is that one wave: cross-lane steps go through /// group-shared memory ([`Emulated`]). @@ -734,6 +743,9 @@ impl<'a> Lower<'a> { code_table: None, counters: HashMap::new(), abort: None, + spin: HashSet::new(), + #[cfg(test)] + spun: 0, emulated, wave64_refused, guard_depth: 0, @@ -1151,7 +1163,8 @@ impl<'a> Lower<'a> { self.s.m.new_block() }); } - // Loop headers count iterations (`LOOP_LIMIT`). + // Loop headers count iterations (`LOOP_LIMIT`; spin waits less). + self.spin = super::spin::spin_loops(p); for &b in &order { let header = p.blocks[b] .preds @@ -1243,6 +1256,8 @@ impl<'a> Lower<'a> { wave_ops: self.s.flags & flags::WAVE_OPS != 0, #[cfg(test)] bounded_prims: self.s.bounded_prims, + #[cfg(test)] + spin_loops: self.spun, dxil: self.s.finish(), user_data, samplers: self.samplers, @@ -8449,7 +8464,16 @@ impl<'a> Lower<'a> { let (phi, _) = self.counters[&to]; let one = self.s.m.i32(1); let next = self.s.m.bin(c, Bin::Add, phi, one); - let limit = self.s.m.i32(super::loop_limit()); + let limit = if self.spin.contains(&to) { + #[cfg(test)] + { + self.spun += 1; + } + super::spin_limit() + } else { + super::loop_limit() + }; + let limit = self.s.m.i32(limit); self.counters .get_mut(&to) .expect("header") @@ -9242,6 +9266,81 @@ mod tests { lowers_ps(&words).unwrap(); } + /// A table at s0 holding structured buffers of dwords. + fn dword_buffers() -> (Vec, Vec) { + let root = RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }; + let used = UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }; + (vec![root], vec![used]) + } + + #[test] + fn a_spin_wait_on_a_table_buffer_gets_the_spin_limit() { + // Each lane rereads its flag in a buffer loaded from the table at + // s0 until it is no longer 0, then copies it to LDS. + let spin = [ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xBE82_0380, // s_mov_b32 s2, 0 + 0xE030_6000, + 0x8002_0100, // 0x14: buffer_load_dword v1, v0, s[8:11], 0 idxen glc + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 + 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 + 0xBF89_FFFA, // s_cbranch_execnz -> 0x14 + 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let (layout, used) = dword_buffers(); + let l = lower_with(&spin, layout, used).unwrap(); + assert_eq!(l.spin_loops, 1); + } + + #[test] + fn a_loop_that_writes_lds_keeps_the_loop_limit() { + // The same loop with the LDS write inside it: it has an effect each + // round, so it is no spin wait. + let writes = [ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xBE82_0380, // s_mov_b32 s2, 0 + 0xE030_6000, + 0x8002_0100, // 0x14: buffer_load_dword v1, v0, s[8:11], 0 idxen glc + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 + 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 + 0xBF89_FFF8, // s_cbranch_execnz -> 0x14 + 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 + S_ENDPGM, + ]; + let (layout, used) = dword_buffers(); + let l = lower_with(&writes, layout, used).unwrap(); + assert_eq!(l.spin_loops, 0); + } + /// Lowers a compute program with the root parameters `layout` (in user /// SGPRs from s0 on) and the used resources `used`. fn lower_with( diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 132ccf7d76..8c40ad54d7 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -83,6 +83,7 @@ pub mod host; mod lower; mod sampler; mod shader; +mod spin; mod threading; #[cfg(windows)] pub mod validator; @@ -107,8 +108,8 @@ pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; /// The iteration count after which a translated loop is left, per lane and /// per entry into the loop: [`DEFAULT_LOOP_LIMIT`]. /// -/// With the `diagnostics` feature, `VICTORY_SHADER_LOOP_LIMIT` (decimal or -/// `0x` hex, at least 1) sets it instead. A loop that hits the limit in +/// `VICTORY_SHADER_LOOP_LIMIT` (decimal or `0x` hex, at least 1) sets it +/// instead, in release builds too. A loop that hits the limit in /// every lane of a full-screen pass still runs for seconds (2^20 times a /// 4K screen is about 10^13 iterations); a much lower limit shows whether /// such loops are what makes a frame slow. The value is part of the @@ -116,17 +117,39 @@ pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; pub fn loop_limit() -> u32 { static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); *LIMIT.get_or_init(|| { - if cfg!(feature = "diagnostics") { - parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref()) - } else { - lower::LOOP_LIMIT - } + parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref()) + }) +} + +/// The spin-wait limit without an override: 4096. +pub const DEFAULT_SPIN_LIMIT: u32 = 1 << 12; + +/// The iteration count after which a loop that only waits for memory to +/// change (a spin wait, see `spin.rs`) is left: [`DEFAULT_SPIN_LIMIT`], or +/// `VICTORY_SHADER_SPIN_LIMIT` (decimal or `0x` hex, at least 1), never +/// more than [`loop_limit`]. On the console the write such a loop waits +/// for comes within microseconds; on the host, when it never comes (the +/// writer's view is another host resource, null, or the load was hoisted), +/// 2^20 uncached reads per lane cost about a second per wave, which is +/// what world frames spent per host submission. 4096 reads are a few +/// milliseconds. Part of the translation: the shader cache keys on it. +pub fn spin_limit() -> u32 { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| { + let v = std::env::var("VICTORY_SHADER_SPIN_LIMIT").ok(); + parse_limit(v.as_deref(), DEFAULT_SPIN_LIMIT).min(loop_limit()) }) } /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset, /// unreadable or 0. Pure, for testing. fn parse_loop_limit(value: Option<&str>) -> u32 { + parse_limit(value, lower::LOOP_LIMIT) +} + +/// A limit's value from its variable; `default` when it is unset, +/// unreadable or 0. +fn parse_limit(value: Option<&str>, default: u32) -> u32 { let parsed = value .map(str::trim) .and_then(|v| match v.strip_prefix("0x") { @@ -135,7 +158,7 @@ fn parse_loop_limit(value: Option<&str>) -> u32 { }); match parsed { Some(n) if n > 0 => n, - _ => lower::LOOP_LIMIT, + _ => default, } } @@ -477,6 +500,15 @@ mod tests { assert_eq!(parse_loop_limit(Some(bad)), LOOP_LIMIT, "{bad:?}"); } } + + #[test] + fn the_spin_limit_parses_with_its_own_default() { + use super::{DEFAULT_SPIN_LIMIT, parse_limit}; + assert_eq!(parse_limit(None, DEFAULT_SPIN_LIMIT), 4096); + assert_eq!(parse_limit(Some("0x40"), DEFAULT_SPIN_LIMIT), 64); + assert_eq!(parse_limit(Some("0"), DEFAULT_SPIN_LIMIT), 4096); + } + use super::container::SigElement; #[cfg(windows)] use super::shader::Shader; @@ -519,12 +551,12 @@ mod tests { let st = structure::structure(&p).unwrap(); let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); let io = io::raise(&p, &native).unwrap(); - let out = emit(&c, &native, &p, &st, &io, &res)?; + let _out = emit(&c, &native, &p, &st, &io, &res)?; #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( super::validator::Validator::default_path().as_deref(), ) { - v.validate(&mut out.dxil.clone()).unwrap(); + v.validate(&mut _out.dxil.clone()).unwrap(); } Ok(()) } diff --git a/crates/victory-shader/src/emit/spin.rs b/crates/victory-shader/src/emit/spin.rs new file mode 100644 index 0000000000..63de5bea4a --- /dev/null +++ b/crates/victory-shader/src/emit/spin.rs @@ -0,0 +1,478 @@ +//! Loops that only wait for memory to change (spin waits). +//! +//! A spin wait reads the same address again and again until another +//! workgroup, queue or the command processor writes it: decoupled +//! look-back prefix sums, persistent-thread queues, locks. On the console +//! the write comes within microseconds. On the host it may never come: the +//! writer's view can be another host resource than the reader's, null +//! (reads zeros) or not mirrored yet, and the host compiler may hoist a +//! load out of a loop that writes nothing. Such a loop then runs to the +//! iteration limit in every lane, 2^20 uncached reads: about a second per +//! wave. These loops get a much smaller limit ([`super::spin_limit`]). +//! +//! A loop counts as one only when nothing in it can have an effect the +//! limit would cut short: no stores, exports, LDS writes, barriers or +//! messages; every memory read and atomic at an address the loop does not +//! change; and no loop-carried value made by arithmetic (a counter means +//! the loop does work per iteration). What it carries are lane masks, +//! compare results and what it read. + +use std::collections::{HashMap, HashSet}; + +use crate::gfx10::{Fields, Operand}; +use crate::ir::{EXEC, Program, Reg, Value}; + +/// Headers (IR block indices) of the loops that only wait for memory. +pub(super) fn spin_loops(p: &Program) -> HashSet { + let order = crate::ir::reverse_postorder(&p.blocks); + let mut rpo = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + rpo[b] = n; + } + let mut found = HashSet::new(); + for &h in &order { + let latches: Vec = p.blocks[h] + .preds + .iter() + .copied() + .filter(|&q| rpo[q] != usize::MAX && rpo[h] <= rpo[q]) + .collect(); + if latches.is_empty() { + continue; + } + if Loop::new(p, h, &latches, &rpo).waits_only() { + found.insert(h); + } + } + found +} + +#[derive(Clone, Copy)] +enum Def { + Phi(usize, usize), + Inst(usize, usize), +} + +/// What an instruction does to memory, for the spin test. +#[derive(PartialEq)] +enum Access { + /// Reads (or an atomic): fine at an address the loop keeps. + Read, + /// Writes or synchronises: the loop does work. + Effect, + /// Registers only. + None, +} + +struct Loop<'a> { + p: &'a Program, + header: usize, + body: HashSet, + defs: HashMap, + /// Phis that merge one value with themselves, by that value. + alias: HashMap, +} + +impl<'a> Loop<'a> { + fn new(p: &'a Program, header: usize, latches: &[usize], rpo: &[usize]) -> Self { + let mut body = HashSet::from([header]); + let mut work = latches.to_vec(); + while let Some(b) = work.pop() { + if body.insert(b) { + work.extend(p.blocks[b].preds.iter().filter(|&&q| rpo[q] != usize::MAX)); + } + } + let mut defs = HashMap::new(); + for &b in &body { + for (i, phi) in p.blocks[b].phis.iter().enumerate() { + defs.insert(phi.value, Def::Phi(b, i)); + } + for (i, inst) in p.blocks[b].insts.iter().enumerate() { + for &(_, v) in &inst.writes { + defs.insert(v, Def::Inst(b, i)); + } + } + } + let mut l = Loop { + p, + header, + body, + defs, + alias: HashMap::new(), + }; + // Registers the loop does not write still get phis at its header: + // each merges one value with itself. + loop { + let mut changed = false; + for &b in &l.body { + for phi in &p.blocks[b].phis { + if l.alias.contains_key(&phi.value) { + continue; + } + let mut other = None; + let trivial = phi.args.iter().all(|&a| { + let a = l.resolve(a); + a == phi.value || *other.get_or_insert(a) == a + }); + if trivial && let Some(o) = other { + l.alias.insert(phi.value, o); + changed = true; + } + } + } + if !changed { + break; + } + } + l + } + + fn resolve(&self, mut v: Value) -> Value { + // Aliases form no cycle: each points at a value made earlier. + for _ in 0..64 { + match self.alias.get(&v) { + Some(&a) => v = a, + None => break, + } + } + v + } + + fn waits_only(&self) -> bool { + let mut reads = 0; + let mut memo = HashMap::new(); + for &b in &self.body { + for inst in &self.p.blocks[b].insts { + match access(inst) { + Access::Effect => return false, + Access::None => {} + Access::Read => { + reads += 1; + let kept = address(inst) + .into_iter() + .filter_map(|r| inst.read(r)) + .all(|v| self.invariant(v, &mut memo)); + if !kept { + return false; + } + } + } + } + } + if reads == 0 { + return false; + } + // What goes round the loop: no counter. + let mut seen = HashSet::new(); + self.p.blocks[self.header] + .phis + .iter() + .filter(|phi| !self.alias.contains_key(&phi.value)) + .all(|phi| self.carried_ok(phi.value, &mut seen)) + } + + /// Whether `v` is the same in every iteration. + fn invariant(&self, v: Value, memo: &mut HashMap) -> bool { + let v = self.resolve(v); + let Some(&def) = self.defs.get(&v) else { + return true; + }; + if let Some(&known) = memo.get(&v) { + return known; + } + let r = match def { + Def::Phi(..) => false, + Def::Inst(b, i) => { + let inst = &self.p.blocks[b].insts[i]; + let valu = matches!(inst.fields, Fields::Valu(_)); + let name = inst.name(); + let lane_wise = valu + && !name.starts_with("v_readfirstlane") + && !name.starts_with("v_readlane") + && !name.starts_with("v_cmp"); + matches!(inst.fields, Fields::Sop { .. } | Fields::Valu(_)) + && inst + .reads + .iter() + .filter(|(r, _)| !(lane_wise && is_exec(*r))) + .all(|&(_, x)| self.invariant(x, memo)) + } + }; + memo.insert(v, r); + r + } + + /// Whether loop-carried `v` holds what the loop read, lane masks or + /// compare results, and nothing computed by arithmetic. + fn carried_ok(&self, v: Value, seen: &mut HashSet) -> bool { + let v = self.resolve(v); + if !seen.insert(v) { + return true; + } + match self.defs.get(&v) { + None => true, + Some(&Def::Phi(b, i)) => self.p.blocks[b].phis[i] + .args + .iter() + .all(|&a| self.carried_ok(a, seen)), + Some(&Def::Inst(b, i)) => { + let inst = &self.p.blocks[b].insts[i]; + let name = inst.name(); + if access(inst) == Access::Read || mask_op(name) { + return true; + } + if copy_op(name) { + let valu = matches!(inst.fields, Fields::Valu(_)); + return inst + .reads + .iter() + .filter(|(r, _)| !(valu && is_exec(*r))) + .all(|&(_, x)| self.carried_ok(x, seen)); + } + false + } + } + } +} + +fn is_exec(r: Reg) -> bool { + matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) +} + +/// Lane-mask bookkeeping and compares: what every divergent loop carries. +fn mask_op(name: &str) -> bool { + [ + "s_and_", "s_or_", "s_xor_", "s_andn2_", "s_orn2_", "s_nand_", "s_nor_", "s_xnor_", + "s_not_", "s_cmp_", "s_cmpk_", "s_bitcmp", "v_cmp_", "v_cmpx_", + ] + .iter() + .any(|p| name.starts_with(p)) +} + +/// Moves and selects: carry what they copy. +fn copy_op(name: &str) -> bool { + name.starts_with("s_mov_") + || name.starts_with("s_cmov_") + || name.starts_with("s_cselect_") + || name.starts_with("v_mov_b32") + || name.starts_with("v_cndmask_b32") + || name.starts_with("v_readfirstlane_b32") + || name.starts_with("v_readlane_b32") +} + +fn access(inst: &crate::ir::Inst) -> Access { + let name = inst.name(); + match &inst.fields { + Fields::Exp { .. } => Access::Effect, + Fields::Sopp { .. } => { + if name == "s_barrier" || name.starts_with("s_sendmsg") || name.starts_with("s_trap") { + Access::Effect + } else { + Access::None + } + } + Fields::Sop { .. } | Fields::Valu(_) | Fields::Vintrp { .. } => Access::None, + Fields::Smem { data, .. } => { + if name.contains("store") || name.contains("atomic") { + Access::Effect + } else if data.is_some() { + Access::Read + } else { + Access::None + } + } + Fields::Buffer { lds, .. } => { + if *lds || name.contains("store") { + Access::Effect + } else if name.contains("load") || name.contains("atomic") { + Access::Read + } else { + // Cache invalidations. + Access::None + } + } + Fields::Image { .. } => { + if name.contains("store") { + Access::Effect + } else { + Access::Read + } + } + Fields::Ds { gds, .. } => { + if *gds { + Access::Effect + } else if name.starts_with("ds_read") { + Access::Read + } else if name.starts_with("ds_swizzle") || name.contains("permute") { + Access::None + } else { + Access::Effect + } + } + Fields::Flat { .. } => { + if name.starts_with("global_load_") { + Access::Read + } else { + Access::Effect + } + } + } +} + +/// The registers that make up a memory access's address. +fn address(inst: &crate::ir::Inst) -> Vec { + let mut regs = Vec::new(); + let mut add = |o: &Operand| match *o { + Operand::Scalar { code, dwords } => { + regs.extend((0..dwords).map(|k| Reg::S(code.wrapping_add(k)))); + } + Operand::Vector { reg, dwords } => { + regs.extend((0..dwords).map(|k| Reg::V(reg.wrapping_add(k)))); + } + _ => {} + }; + match &inst.fields { + Fields::Smem { base, soffset, .. } => { + add(base); + add(soffset); + } + Fields::Buffer { + addr, + rsrc, + soffset, + offen, + idxen, + .. + } => { + add(rsrc); + add(soffset); + if *offen || *idxen { + add(addr); + } + } + Fields::Image { + addr, + rsrc, + sampler, + .. + } => { + add(rsrc); + if let Some(s) = sampler { + add(s); + } + addr.iter().for_each(&mut add); + } + Fields::Ds { addr: Some(a), .. } => add(a), + Fields::Flat { addr, saddr, .. } => { + if let Some(a) = addr { + add(a); + } + if let Some(s) = saddr { + add(s); + } + } + _ => {} + } + regs +} + +#[cfg(test)] +mod tests { + use super::spin_loops; + use crate::ir; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn spins(words: &[u32]) -> Vec { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = ir::build(&code, false, 256).unwrap(); + let mut h: Vec = spin_loops(&p).into_iter().collect(); + h.sort_unstable(); + h + } + + #[test] + fn a_loop_rereading_one_flag_is_a_spin_wait() { + // Each lane waits until its flag (at v0 in the buffer at s[8:11]) + // is no longer 0. + let words = [ + 0xBE82_0380, // s_mov_b32 s2, 0 + 0xE030_6000, + 0x8002_0100, // 4: buffer_load_dword v1, v0, s[8:11], 0 idxen glc + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 + 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 + 0xBF89_FFF9, // s_cbranch_execnz -> 4 + 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 + S_ENDPGM, + ]; + assert_eq!(spins(&words).len(), 1); + } + + #[test] + fn a_loop_that_stores_or_counts_is_not() { + // The same with a store of the flag back: work per iteration. + let stores = [ + 0xBE82_0380, // s_mov_b32 s2, 0 + 0xE030_6000, + 0x8002_0100, // 4: buffer_load_dword v1, v0, s[8:11], 0 idxen glc + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_2000, + 0x8002_0100, // buffer_store_dword v1, v0, s[8:11], 0 idxen + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 + 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 + 0xBF89_FFF7, // s_cbranch_execnz -> 4 + 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 + S_ENDPGM, + ]; + assert_eq!(spins(&stores), Vec::::new()); + // A loop walking the buffer: the address moves. + let walks = [ + 0xBE82_0380, // s_mov_b32 s2, 0 + 0xE030_6000, + 0x8002_0100, // 4: buffer_load_dword v1, v0, s[8:11], 0 idxen glc + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x4A00_0081, // v_add_nc_u32 v0, 1, v0 + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 + 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 + 0xBF89_FFF8, // s_cbranch_execnz -> 4 + 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 + S_ENDPGM, + ]; + assert_eq!(spins(&walks), Vec::::new()); + // Rereading one address while counting: a loop with work to do. + let counts = [ + 0xBE82_0380, // s_mov_b32 s2, 0 + 0xE030_6000, + 0x8002_0100, // 4: buffer_load_dword v1, v0, s[8:11], 0 idxen glc + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x4A04_0481, // v_add_nc_u32 v2, 1, v2 + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 + 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 + 0xBF89_FFF8, // s_cbranch_execnz -> 4 + 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 + S_ENDPGM, + ]; + assert_eq!(spins(&counts), Vec::::new()); + } + + #[test] + fn a_loop_without_memory_reads_is_not() { + // The divergent counting loop of the structure tests (wave32). + let words = [ + 0xBE82_0380, // s_mov_b32 s2, 0 + 0x4A00_0081, // 4: v_add_nc_u32 v0, 1, v0 + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 + 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 + 0xBF89_FFFB, // s_cbranch_execnz -> 4 + 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 + S_ENDPGM, + ]; + assert_eq!(spins(&words), Vec::::new()); + } +} From d8476f889b37fc159e245b1cce32ab14ce5dc23c Mon Sep 17 00:00:00 2001 From: IgorRend Date: Tue, 24 Nov 2026 08:29:48 -0300 Subject: [PATCH 105/123] GPU: refuse pipelines whose mandatory stage has no DXIL Check that the mandatory shader stage produced DXIL before calling CreateComputePipelineState / CreateGraphicsPipelineState. On hardware a null bytecode can be accepted, the GPU then runs empty code and removes the device (0x887A0006); on WARP it surfaces as E_INVALIDARG. Refusing early avoids the spurious creation calls and the device removal. From IgorRend 17a35d98fb, the pipeline part only: its raw-buffer change took a range with no declared stride for a raw buffer and dropped the index, which would read structured buffers of unknown stride at the wrong addresses instead of refusing them. (cherry picked from commit 17a35d98fb006b1158462c0ab4d5ced5e31aa44d) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/pipeline/host.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index ddbf9cd1a2..56a52fe25e 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -555,6 +555,12 @@ impl HostPipeline { ) }; if compute.is_some() { + // D3D12 rejects empty mandatory stages with E_INVALIDARG; on + // hardware that arrives as a GPU device removal instead of a + // clean refusal, so bail before CreateComputePipelineState. + if code(0).BytecodeLength == 0 { + return refuse("compute shader did not translate", shaders); + } let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { // SAFETY: a borrowed pointer the description never releases. pRootSignature: unsafe { std::mem::transmute_copy(&root) }, @@ -629,6 +635,11 @@ impl HostPipeline { }); } + // VS is mandatory; an empty bytecode causes GPU device removal on + // hardware (E_INVALIDARG on WARP). PS may be absent (depth-only). + if code(0).BytecodeLength == 0 { + return refuse("vertex shader did not translate", shaders); + } let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { // SAFETY: a borrowed pointer the description never releases. pRootSignature: unsafe { std::mem::transmute_copy(&root) }, From 817be662bed643295d049d4e072e1cedc0c766f2 Mon Sep 17 00:00:00 2001 From: arthercz <125757106+arthercz@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:34:59 +0000 Subject: [PATCH 106/123] GPU: bound indirect mesh work and submit each list on its own A mesh record is now clamped to 4,096 groups (captured direct mesh work peaks at 260) and mesh groups have their own per-list budget of 2^15: allowing D3D12's 65,535 let one corrupt indirect record hold an RX 6700 XT until Windows reset it. The budget buffer's two words are zeroed together. Each title list now goes to the queue in its own ExecuteCommandLists: the OS resets a device whose submission runs for about 2 s, and world submissions of every list took 0.5 to 1.8 s, while each list is well under that. The lists are still waited for once, after the last (each on its own with diagnostics timing), so no wait bubble is added per list. From arthercz bba82d4c5e, hand-ported onto the structured-buffer clamp; its per-list waits are left out. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/host.rs | 51 ++++++++++++++++------------- crates/victory-gpu/src/indirect.rs | 52 ++++++++++++++++++++---------- 2 files changed, 63 insertions(+), 40 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 051f3d41ef..4a23d32bfb 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -703,38 +703,42 @@ impl Host { } batch.flush(); let prepared = std::time::Instant::now(); - // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`). + // Each run's lists go to the queue on their own, one submission + // each. The host resets a device whose submission runs for about + // 2 s (TDR); with the world streaming, one submission of every list + // comes close to that (0.5 to 1.8 s seen), while the lists are each + // well under it. They are waited for once, after the last; with + // diagnostics timing (`VICTORY_GPU_TIMING`) each on its own. + let groups: Vec<&[Option]> = firsts + .iter() + .zip(firsts.iter().skip(1).chain([&lists.len()])) + .map(|(&a, &b)| &lists[a..b]) + .collect(); #[cfg(feature = "diagnostics")] - let groups: Vec<&[Option]> = if timing() { - firsts - .iter() - .zip(firsts.iter().skip(1).chain([&lists.len()])) - .map(|(&a, &b)| &lists[a..b]) - .collect() - } else { - vec![&lists[..]] - }; + let wait_each = timing(); #[cfg(not(feature = "diagnostics"))] - let groups = [&lists[..]]; + let wait_each = false; for (i, group) in groups.iter().enumerate() { - *submitted += 1; let started = std::time::Instant::now(); // SAFETY: closed lists; the fence and event are ours. unsafe { self.queue.ExecuteCommandLists(group); - let waited = self - .queue - .Signal(&self.fence, *submitted) - .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); - match waited { - Ok(()) => { - WaitForSingleObject(self.event, INFINITE); + if wait_each || i + 1 == groups.len() { + *submitted += 1; + let waited = self + .queue + .Signal(&self.fence, *submitted) + .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); + match waited { + Ok(()) => { + WaitForSingleObject(self.event, INFINITE); + } + Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } - Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } } #[cfg(feature = "diagnostics")] - if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) { + if wait_each && started.elapsed() > std::time::Duration::from_millis(50) { // SAFETY: a plain query. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); let commands = runs[i] @@ -1486,9 +1490,10 @@ impl HostList { if !deferred.budget_zeroed { deferred.budget_zeroed = true; let at = *data; - // SAFETY: the list's own mapped word, written before it runs. + // SAFETY: the list's own mapped budget words (work, mesh + // groups), written before it runs. deferred.copies.push(Step::Host(Box::new(move || unsafe { - (at as *mut u32).write_volatile(0) + (at as *mut u64).write_volatile(0) }))); } // SAFETY: a live buffer. diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 39cb47ee76..f3fb07dc20 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -9,15 +9,17 @@ //! Non-indexed rectangle-list draws follow the clamp with GPU-side //! rectangle expansion in [`crate::rectangles`]. //! -//! Each list also has a budget (2^27 vertex instances or threads, groups -//! counted as 64 threads, mesh groups as 128): records past it run empty, -//! so a list of thousands of garbage records cannot run for seconds -//! either. +//! Each list also has budgets (2^27 vertex instances or threads, groups +//! counted as 64 threads; and 2^15 mesh groups): records past them run +//! empty, so a list of thousands of garbage records cannot run for seconds +//! either. A mesh record is limited to 4,096 groups: captured direct mesh +//! work peaks at 260 groups, and allowing D3D12's 65,535 let one corrupt +//! indirect record keep an RX 6700 XT busy until the driver was reset. //! //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 -//! groups per dimension and 2^20 per dispatch, one-dimensional mesh -//! dispatches, the budget) cut legitimate work beyond them; raise them if -//! the title needs more. +//! compute groups per dimension and 2^20 per dispatch, 4,096 groups per +//! one-dimensional mesh dispatch, the budgets) cut legitimate work beyond +//! them; raise them if the title needs more. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::ID3DBlob; @@ -34,17 +36,21 @@ use crate::host::{HostList, host, transition}; const SOURCE: &str = r#" cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; RWStructuredBuffer args : register(u0); -// The list's work so far (vertex instances, threads): past the budget, -// records run empty. +// The list's work so far (word 0: vertex instances, threads; word 1: mesh +// groups): past the budget, records run empty. RWStructuredBuffer budget : register(u1); static const uint BUDGET = 1u << 27; -// Groups of one dispatch; more run empty. +static const uint MESH_BUDGET = 1u << 15; +// Groups of one dispatch (one mesh dispatch); more run empty. static const uint GROUPS = 1u << 20; +static const uint MESH_GROUPS = 1u << 12; [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { if (id.x >= records) return; uint at = id.x * (stride / 4); uint cost; + uint counter = 0; + uint limit = BUDGET; if (kind <= 1) { // Draws: vertex or index count, then instances. uint count = min(args[at], 1u << 24); @@ -64,8 +70,10 @@ void main(uint3 id : SV_DispatchThreadID) { args[at + 2] = g.z; } else { // Mesh dispatches: the console's are one-dimensional. - uint3 g = uint3(min(args[at], 65535u), min(args[at + 1], 1u), min(args[at + 2], 1u)); - cost = g.x * g.y * g.z * 128; + uint3 g = uint3(min(args[at], MESH_GROUPS), min(args[at + 1], 1u), min(args[at + 2], 1u)); + cost = g.x * g.y * g.z; + counter = 1; + limit = MESH_BUDGET; args[at] = g.x; args[at + 1] = g.y; args[at + 2] = g.z; @@ -74,14 +82,14 @@ void main(uint3 id : SV_DispatchThreadID) { // All accesses to the counter are atomic; a rejected record must // never reopen the budget for later records. uint before; - InterlockedAdd(budget[0], 0u, before); + InterlockedAdd(budget[counter], 0u, before); [allow_uav_condition] while (true) { - if (before >= BUDGET) break; - uint remaining = BUDGET - before; + if (before >= limit) break; + uint remaining = limit - before; uint next = before + min(cost, remaining); uint observed; - InterlockedCompareExchange(budget[0], before, next, observed); + InterlockedCompareExchange(budget[counter], before, next, observed); if (observed == before) { if (cost <= remaining) return; break; @@ -405,6 +413,16 @@ pub(crate) fn uav_barrier() -> D3D12_RESOURCE_BARRIER { #[cfg(test)] mod tests { + /// A corrupt mesh record must not regain D3D12's 65,535-group maximum: + /// one such record ran until the driver reset an RX 6700 XT. + #[test] + fn mesh_indirect_work_is_bounded() { + assert!(super::SOURCE.contains("MESH_GROUPS = 1u << 12")); + assert!(super::SOURCE.contains("min(args[at], MESH_GROUPS)")); + assert!(super::SOURCE.contains("MESH_BUDGET = 1u << 15")); + assert!(super::SOURCE.contains("budget[counter]")); + } + /// The clamp bounds a draw, a dispatch and a mesh dispatch on the GPU. #[test] @@ -475,7 +493,7 @@ mod tests { let read = |at: usize| unsafe { std::slice::from_raw_parts(words.add(at / 4), 3).to_vec() }; assert_eq!(read(0)[..2], [1 << 24, 4]); assert_eq!(read(16), [65_535, 2, 3]); - assert_eq!(read(32), [65_535, 1, 1]); + assert_eq!(read(32), [4_096, 1, 1]); } /// The clamp compiles with the system's compiler and the host takes it. #[test] From 7cf728b68fa5527737709b8e90de1b245dc2860d Mon Sep 17 00:00:00 2001 From: Enzo Souza Duarte Date: Tue, 24 Nov 2026 11:33:04 -0300 Subject: [PATCH 107/123] PE: read long-format import descriptors (cherry picked from commit adeb9ff49dbfe33cbd52a0246dc5f9ba22015f8d) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-pe/src/implib.rs | 284 +++++++++++++++++++++++++++++--- 1 file changed, 263 insertions(+), 21 deletions(-) diff --git a/crates/victory-pe/src/implib.rs b/crates/victory-pe/src/implib.rs index ad1d912301..24b07d565c 100644 --- a/crates/victory-pe/src/implib.rs +++ b/crates/victory-pe/src/implib.rs @@ -4,8 +4,10 @@ //! console title may link against. That is the map the runtime needs to //! decide which of our implementations answers which import. +use object::Object; +use object::ObjectSymbol; use object::read::archive::ArchiveFile; -use object::read::coff::{ImportFile, ImportName, ImportType}; +use object::read::coff::{CoffFile, ImportFile, ImportName, ImportType}; use crate::{ImportSymbol, PeError}; @@ -28,34 +30,167 @@ pub enum LibImportKind { #[derive(Debug, Default)] pub struct ImportLibrary { pub imports: Vec, - /// Members that are not short-format import objects (regular objects, - /// long-format import descriptors). Reported so nothing is silently lost. + /// Members that are not short-format imports (regular objects, long + /// import descriptors and their null thunks). Reported so nothing is + /// silently lost. pub other_members: usize, } +// Values from the COFF import-object header. They are kept as plain integers +// here because the `object` crate exposes them as newtypes whose constants +// cannot be compared with bytes read from an archive. +const SIG1: u16 = 0; // IMAGE_FILE_MACHINE_UNKNOWN +const SIG2: u16 = 0xffff; // IMPORT_OBJECT_HDR_SIG2 +#[cfg(test)] +const TYPE_CODE: u16 = 0; +const TYPE_DATA: u16 = 1; +const TYPE_CONST: u16 = 2; +const NAME_ORDINAL: u16 = 0; +const NAME: u16 = 1; +const NAME_NO_PREFIX: u16 = 2; +const NAME_UNDECORATE: u16 = 3; +const NAME_EXPORTAS: u16 = 4; + +/// A long import descriptor has the same 20-byte prefix as a short import +/// object but carries no inline string data. The names live in the COFF +/// object that follows the null descriptor and null thunk members. +fn import_header(bytes: &[u8]) -> Option<(u16, u32, u16, u16)> { + if bytes.len() < 20 { + return None; + } + let sig1 = u16::from_le_bytes(bytes[0..2].try_into().ok()?); + let sig2 = u16::from_le_bytes(bytes[2..4].try_into().ok()?); + if sig1 != SIG1 || sig2 != SIG2 { + return None; + } + Some(( + u16::from_le_bytes(bytes[8..10].try_into().ok()?), // machine + u32::from_le_bytes(bytes[12..16].try_into().ok()?), // size_of_data + u16::from_le_bytes(bytes[16..18].try_into().ok()?), // ordinal/hint + u16::from_le_bytes(bytes[18..20].try_into().ok()?), // type/name type + )) +} + +fn import_kind(flags: u16) -> LibImportKind { + match flags & 0b11 { + TYPE_DATA => LibImportKind::Data, + TYPE_CONST => LibImportKind::Const, + _ => LibImportKind::Code, + } +} + +/// Names defined by the COFF object that belongs to a long descriptor. +fn coff_symbols(bytes: &[u8]) -> Vec { + let Ok(file) = CoffFile::<_, object::pe::ImageFileHeader>::parse(bytes) else { + return Vec::new(); + }; + file.symbols() + .filter_map(|symbol| symbol.name().ok().map(str::to_owned)) + .collect() +} + +fn strip_decoration(name: &str, name_type: u16) -> String { + // `IMPORT_OBJECT_NAME` is passed through as-is; only the no-prefix and + // undecorate forms ask us to remove a leading decoration. + if name_type == NAME { + return name.to_owned(); + } + let stripped = if matches!(name_type, NAME_NO_PREFIX | NAME_UNDECORATE) { + name.strip_prefix(['?', '@', '_']).unwrap_or(name) + } else { + name + }; + if name_type == NAME_UNDECORATE { + stripped.split('@').next().unwrap_or(stripped).to_owned() + } else { + stripped.to_owned() + } +} + impl ImportLibrary { pub fn parse(data: &[u8]) -> Result { let archive = ArchiveFile::parse(data)?; let mut lib = ImportLibrary::default(); - for member in archive.members() { - let member = member?; - let bytes = member.data(data)?; - match ImportFile::parse(bytes) { - Ok(import) => lib.imports.push(LibImport { - dll: String::from_utf8_lossy(import.dll()).into_owned(), - export: match import.import() { - ImportName::Name(name) => ImportSymbol::Name { - hint: 0, - name: String::from_utf8_lossy(name).into_owned(), + let members: Vec<_> = archive.members().collect::, _>>()?; + let contents: Vec> = members + .iter() + .map(|member| member.data(data).map(<[u8]>::to_vec)) + .collect::>()?; + let mut consumed = vec![false; contents.len()]; + + for (index, member) in contents.iter().enumerate() { + if consumed[index] { + continue; + } + if let Some((_, size, ordinal, flags)) = import_header(member) { + if size == 0 { + // Long-format descriptor. Its DLL and export names live + // in the COFF object(s) that follow the null members. + consumed[index] = true; + lib.other_members += 1; + let kind = import_kind(flags); + let name_type = flags >> 2 & 0b111; + let mut dll = None; + let mut names = Vec::new(); + for (next, object) in contents.iter().enumerate().skip(index + 1) { + if consumed[next] || import_header(object).is_some() { + break; + } + let symbols = coff_symbols(object); + if symbols.is_empty() { + continue; + } + consumed[next] = true; + lib.other_members += 1; + for symbol in symbols { + if let Some(d) = symbol.strip_prefix("__IMPORT_DESCRIPTOR_") { + dll = Some(d.to_owned()); + } else if let Some(export) = symbol.strip_prefix("__imp_") { + names.push(export.to_owned()); + } + } + } + let Some(dll) = dll else { + continue; + }; + for name in names { + let export = if name_type == NAME_ORDINAL { + ImportSymbol::Ordinal(ordinal) + } else if name_type == NAME_EXPORTAS { + ImportSymbol::Name { hint: 0, name } + } else { + ImportSymbol::Name { + hint: 0, + name: strip_decoration(&name, name_type), + } + }; + lib.imports.push(LibImport { + dll: dll.clone(), + export, + kind, + }); + } + continue; + } + } + match ImportFile::parse(&member[..]) { + Ok(import) => { + lib.imports.push(LibImport { + dll: String::from_utf8_lossy(import.dll()).into_owned(), + export: match import.import() { + ImportName::Name(name) => ImportSymbol::Name { + hint: 0, + name: String::from_utf8_lossy(name).into_owned(), + }, + ImportName::Ordinal(o) => ImportSymbol::Ordinal(o), + }, + kind: match import.import_type() { + ImportType::Code => LibImportKind::Code, + ImportType::Data => LibImportKind::Data, + ImportType::Const => LibImportKind::Const, }, - ImportName::Ordinal(o) => ImportSymbol::Ordinal(o), - }, - kind: match import.import_type() { - ImportType::Code => LibImportKind::Code, - ImportType::Data => LibImportKind::Data, - ImportType::Const => LibImportKind::Const, - }, - }), + }); + } Err(_) => lib.other_members += 1, } } @@ -555,4 +690,111 @@ mod tests { assert_eq!(lib.imports, [name("a.dll", "", LibImportKind::Code)]); assert_eq!(lib.other_members, 0); } + + fn long_descriptor(ordinal: u16, flags: u16) -> Vec { + let mut out = vec![0u8; 20]; + out[2..4].copy_from_slice(&SIG2.to_le_bytes()); + out[8..10].copy_from_slice(&0x8664u16.to_le_bytes()); + out[16..18].copy_from_slice(&ordinal.to_le_bytes()); + out[18..20].copy_from_slice(&flags.to_le_bytes()); + out + } + + /// A minimal COFF object with undefined external symbols. + fn coff_object(names: &[&str]) -> Vec { + let mut strings = Vec::new(); + let mut offsets = Vec::new(); + for name in names { + offsets.push(strings.len() as u32 + 4); + strings.extend_from_slice(name.as_bytes()); + strings.push(0); + } + let mut out = Vec::new(); + out.extend_from_slice(&0x8664u16.to_le_bytes()); // machine + out.extend_from_slice(&0u16.to_le_bytes()); // sections + out.extend_from_slice(&0u32.to_le_bytes()); // timestamp + out.extend_from_slice(&20u32.to_le_bytes()); // symbol table offset + out.extend_from_slice(&(names.len() as u32).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); // optional header + out.extend_from_slice(&0u16.to_le_bytes()); // characteristics + for offset in offsets { + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&offset.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); // value + out.extend_from_slice(&0i16.to_le_bytes()); // undefined section + out.extend_from_slice(&0u16.to_le_bytes()); // type + out.push(2); // external + out.push(0); // no aux records + } + out.extend_from_slice(&(strings.len() as u32 + 4).to_le_bytes()); + out.extend_from_slice(&strings); + out + } + + #[test] + fn short_imports_are_read() { + let bytes = archive(&[short_import( + "xsystem.dll", + "XSystemGetDeviceType", + 0, + TYPE_CODE, + NAME, + )]); + let lib = ImportLibrary::parse(&bytes).unwrap(); + assert_eq!(lib.imports.len(), 1); + assert_eq!(lib.imports[0].dll, "xsystem.dll"); + assert_eq!( + lib.imports[0].export, + ImportSymbol::Name { + hint: 0, + name: "XSystemGetDeviceType".into() + } + ); + assert_eq!(lib.other_members, 0); + } + + #[test] + fn long_imports_take_their_names_from_the_coff_object() { + let object = coff_object(&[ + "__IMPORT_DESCRIPTOR_xsystem.dll", + "__imp_XSystemGetDeviceType", + "__imp_XSystemSetDeviceType", + ]); + let bytes = archive(&[ + long_descriptor(0, TYPE_CODE | NAME << 2), + vec![0u8; 20], + vec![0u8; 8], + object, + ]); + let lib = ImportLibrary::parse(&bytes).unwrap(); + let exports: Vec<_> = lib + .imports + .iter() + .filter(|i| i.dll == "xsystem.dll") + .map(|i| i.export.to_string()) + .collect(); + assert_eq!(exports, ["XSystemGetDeviceType", "XSystemSetDeviceType"]); + // Descriptor, null descriptor, null thunk and the symbols object. + assert_eq!(lib.other_members, 4); + } + + #[test] + fn long_import_by_ordinal_uses_the_header_value() { + let object = coff_object(&[ + "__IMPORT_DESCRIPTOR_xsystem.dll", + "__imp_XSystemGetDeviceType", + ]); + let bytes = archive(&[long_descriptor(42, NAME_ORDINAL), object]); + let lib = ImportLibrary::parse(&bytes).unwrap(); + assert_eq!(lib.imports.len(), 1); + assert_eq!(lib.imports[0].export, ImportSymbol::Ordinal(42)); + } + + #[test] + fn unknown_members_are_reported_not_silently_dropped() { + let bytes = archive(&[vec![1, 2, 3]]); + let lib = ImportLibrary::parse(&bytes).unwrap(); + assert!(lib.imports.is_empty()); + assert_eq!(lib.other_members, 1); + } } From a582598bee6669e61d61b6999a830800cd8e9381 Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 24 Nov 2026 11:27:10 -0300 Subject: [PATCH 108/123] GPU: unit tests for the OPTIONS, ARCHITECTURE and MULTISAMPLE feature queries (cherry picked from commit 7d0302b2d85eef8e8b088ae46191adbde7655903) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/device.rs | 50 ++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index e768c95e18..7336724d24 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -590,4 +590,54 @@ mod tests { assert_eq!(info[1], 48); assert_eq!(check(device(), 6, (&raw mut info).cast(), 4), E_INVALIDARG); } + + #[test] + fn feature_options_report_the_rdna2_tiers() { + type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; + let device = device(); + let check = slot::(device, 0x68); + let mut options = [0u32; 16]; + assert_eq!(check(device, 0, options.as_mut_ptr().cast(), 64), S_OK); + assert_eq!(options, OPTIONS); + assert_eq!( + (options[3], options[4], options[8], options[9], options[15]), + (3, 3, 3, 40, 2) + ); + assert_eq!( + check(device, 0, options.as_mut_ptr().cast(), 60), + E_INVALIDARG + ); + assert_eq!(check(device, 0, std::ptr::null_mut(), 64), E_INVALIDARG); + } + + #[test] + fn feature_architecture_is_unified_and_coherent() { + type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; + let device = device(); + let check = slot::(device, 0x68); + let mut arch = [0u32; 4]; + assert_eq!(check(device, 1, arch.as_mut_ptr().cast(), 16), S_OK); + assert_eq!(arch, [0, 0, 1, 1]); + arch[0] = 1; + assert_eq!(check(device, 1, arch.as_mut_ptr().cast(), 16), E_INVALIDARG); + } + + #[test] + fn feature_multisample_has_one_level_for_the_hardware_counts() { + type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; + let device = device(); + let check = slot::(device, 0x68); + let levels = |samples: u32| { + // Format, sample count, flags in; quality levels out. + let mut query = [28, samples, 0, 99]; + assert_eq!(check(device, 4, query.as_mut_ptr().cast(), 16), S_OK); + query[3] + }; + for samples in [1, 2, 4, 8] { + assert_eq!(levels(samples), 1, "{samples} samples"); + } + for samples in [0, 3, 16] { + assert_eq!(levels(samples), 0, "{samples} samples"); + } + } } From 471a670f0925b69dafb8c38f98b25d4c5948e7ac Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 24 Nov 2026 11:27:21 -0300 Subject: [PATCH 109/123] HLE: test that XGSuggestSwizzleMode picks linear for a 1D texture (cherry picked from commit 246ecea9631acfe1b694421c6c600e3981a1f752) --- crates/victory-hle/src/modules/xg.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs index 98e43bb32a..f5cbeebd66 100644 --- a/crates/victory-hle/src/modules/xg.rs +++ b/crates/victory-hle/src/modules/xg.rs @@ -714,6 +714,10 @@ mod tests { d.flags = ALLOW_DEPTH_STENCIL; XGSuggestSwizzleMode(&d, 0, &mut out); assert_eq!(out, 0x118); + // A 1D texture has no tiled layout, whatever its use. + d.dimension = TEXTURE_1D; + XGSuggestSwizzleMode(&d, 0, &mut out); + assert_eq!(out, 0x100); } #[test] From c57338d53550324476d587a98d1b4feff7dc1114 Mon Sep 17 00:00:00 2001 From: Sakura-Byte <42319937+Sakura-Byte@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:16:03 -0500 Subject: [PATCH 110/123] victory-shader: add forced-var propagation and UNSAT memoization to Bools::meet (cherry picked from commit 80a235e0368e10301eea75181b70eda7dc5d24e4) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/structure.rs | 418 +++++++++++++++++++++++-- 1 file changed, 392 insertions(+), 26 deletions(-) diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index 0b4e23c9aa..0f7b016425 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -277,32 +277,7 @@ impl Bools { /// `b` where `holds`, its negation where not. Yes when the search grows /// too large to finish. pub fn meet(&self, all: &[(Bool, bool)]) -> bool { - let mut budget = MAX_MEET; - self.meet_in(all.to_vec(), &mut budget) - } - - fn meet_in(&self, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool { - let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE }; - if all.iter().any(fails) { - return false; - } - all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE); - if all.is_empty() || *budget == 0 { - return true; - } - *budget -= 1; - let top = |b: Bool| self.nodes[b.0 as usize].0; - let v = all.iter().map(|&(b, _)| top(b)).min().expect("not empty"); - [false, true].into_iter().any(|value| { - let next = all - .iter() - .map(|&(b, holds)| { - let (lo, hi) = self.split(b, v); - (if value { hi } else { lo }, holds) - }) - .collect(); - self.meet_in(next, budget) - }) + Meet::new(self).solve(all.to_vec()) } fn implies(&mut self, a: Bool, b: Bool) -> bool { @@ -385,6 +360,222 @@ impl Bools { } } +/// Ephemeral SAT solver for [`Bools::meet`] over immutable BDD nodes. +struct Meet<'a> { + bools: &'a Bools, + extra: Vec<(u32, Bool, Bool)>, + extra_unique: Map<(u32, Bool, Bool), Bool>, + restrict_memo: Map, + forced: Map, + failed: HashSet, BuildHasherDefault>, + budget: usize, + overflow: bool, +} + +impl<'a> Meet<'a> { + fn new(bools: &'a Bools) -> Self { + Self { + bools, + extra: Vec::new(), + extra_unique: Map::default(), + restrict_memo: Map::default(), + forced: Map::default(), + failed: HashSet::with_hasher(BuildHasherDefault::default()), + budget: MAX_MEET, + overflow: false, + } + } + + fn node(&self, b: Bool) -> (u32, Bool, Bool) { + let idx = b.0 as usize; + if idx < self.bools.nodes.len() { + self.bools.nodes[idx] + } else { + self.extra[idx - self.bools.nodes.len()] + } + } + + fn split(&self, b: Bool, v: u32) -> (Bool, Bool) { + match self.node(b) { + (bv, lo, hi) if bv == v => (lo, hi), + _ => (b, b), + } + } + + fn mk(&mut self, v: u32, lo: Bool, hi: Bool) -> Bool { + if lo == hi { + return lo; + } + if let Some(&b) = self.bools.unique.get(&(v, lo, hi)) { + return b; + } + if let Some(&b) = self.extra_unique.get(&(v, lo, hi)) { + return b; + } + if self.extra.len() >= MAX_NODES + || self.bools.nodes.len() + self.extra.len() >= u32::MAX as usize + { + self.overflow = true; + return Bool::FALSE; + } + let b = Bool((self.bools.nodes.len() + self.extra.len()) as u32); + self.extra.push((v, lo, hi)); + self.extra_unique.insert((v, lo, hi), b); + b + } + + fn restrict(&mut self, b: Bool, forced: &Map, max_v: u32) -> Bool { + let (bv, lo, hi) = self.node(b); + if bv == TERMINAL || bv > max_v || self.overflow { + return b; + } + if let Some(&r) = self.restrict_memo.get(&b) { + return r; + } + let r = if let Some(&value) = forced.get(&bv) { + self.restrict(if value { hi } else { lo }, forced, max_v) + } else { + let l = self.restrict(lo, forced, max_v); + let h = self.restrict(hi, forced, max_v); + if self.overflow { + return Bool::FALSE; + } + if l == lo && h == hi { + b + } else { + self.mk(bv, l, h) + } + }; + self.restrict_memo.insert(b, r); + r + } + + /// Canonicalizes constraints and propagates forced top-variable assignments to + /// a fixed point before branching into larger BDDs. + fn propagate(&mut self, all: &mut Vec<(Bool, bool)>) -> Option { + loop { + let mut i = 0; + while i < all.len() { + let (b, holds) = all[i]; + if b == if holds { Bool::FALSE } else { Bool::TRUE } { + return Some(false); + } + if b == Bool::FALSE || b == Bool::TRUE { + all.swap_remove(i); + } else { + i += 1; + } + } + all.sort_unstable(); + all.dedup(); + if all.windows(2).any(|w| w[0].0 == w[1].0 && w[0].1 != w[1].1) { + return Some(false); + } + if all.len() <= 1 { + // Any single non-constant reduced ROBDD node attains both `false` and `true`. + return Some(true); + } + + let mut forced = std::mem::take(&mut self.forced); + forced.clear(); + let mut max_v = 0u32; + let mut conflict = false; + for &(b, holds) in all.iter() { + let (v, lo, hi) = self.node(b); + debug_assert_ne!(v, TERMINAL); + let bad = if holds { Bool::FALSE } else { Bool::TRUE }; + let req = if lo == bad { + Some(true) + } else if hi == bad { + Some(false) + } else { + None + }; + if let Some(val) = req { + if let Some(prev) = forced.insert(v, val) { + if prev != val { + conflict = true; + break; + } + } else { + max_v = max_v.max(v); + } + } + } + if conflict { + self.forced = forced; + return Some(false); + } + if forced.is_empty() { + self.forced = forced; + return None; + } + self.restrict_memo.clear(); + for (b, _) in all.iter_mut() { + *b = self.restrict(*b, &forced, max_v); + } + self.forced = forced; + if self.overflow { + return Some(true); + } + } + } + + fn solve(&mut self, mut all: Vec<(Bool, bool)>) -> bool { + if self.bools.overflow { + return true; + } + if let Some(res) = self.propagate(&mut all) { + return res; + } + if self.failed.contains(&all) { + return false; + } + if self.budget == 0 { + return true; + } + self.budget -= 1; + let v = all + .iter() + .map(|&(b, _)| self.node(b).0) + .min() + .expect("not empty"); + let mut score = [0usize; 2]; + for &(b, holds) in &all { + let (bv, lo, hi) = self.node(b); + if bv == v { + let good = if holds { Bool::TRUE } else { Bool::FALSE }; + if lo == good { + score[0] += 1; + } + if hi == good { + score[1] += 1; + } + } + } + let order = if score[1] > score[0] { + [true, false] + } else { + [false, true] + }; + for value in order { + let next = all + .iter() + .map(|&(b, holds)| { + let (lo, hi) = self.split(b, v); + (if value { hi } else { lo }, holds) + }) + .collect(); + if self.solve(next) { + return true; + } + } + // Both branches returned false cleanly, so `all` is genuinely UNSAT. + self.failed.insert(all); + false + } +} + /// How a lane leaves a block. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LaneExit { @@ -1573,4 +1764,179 @@ mod tests { ); } } + + #[test] + fn meet_pins_forced_variables_across_deep_diamond_chain() { + let mut b = Bools::new(); + let val = Value; + let mut reach = Bool::TRUE; + for i in 0..24u32 { + let x = b.atom(Atom::Lane(val(2 * i + 1)), i as usize); + let y = b.atom(Atom::Lane(val(2 * i + 2)), i as usize); + let clause = b.or(x, y); + reach = b.and(reach, clause); + } + let tail = b.atom(Atom::Lane(val(100)), 30); + let not_tail = b.not(tail); + let guarded = b.and(reach, not_tail); + // Without bottom-up forced-var restriction, branching on the 24 (x | y) diamonds + // explores 3^24 paths and hits MAX_MEET, falsely returning `true`. + assert!(!b.meet(&[(guarded, true), (tail, true)])); + assert!(b.meet(&[(guarded, true), (tail, false)])); + + // Cascading unit propagation through a forced chain at the bottom. + let gate = b.atom(Atom::Uniform(val(101)), 31); + let cascade = b.ite(tail, gate, Bool::FALSE); + assert!(!b.meet(&[(guarded, true), (cascade, true)])); + assert!(b.meet(&[(reach, true), (cascade, true)])); + } + + #[test] + fn meet_memoizes_diamonds_without_forced_root_vars() { + let mut b = Bools::new(); + let val = Value; + let mut reach = Bool::TRUE; + for i in 0..22u32 { + let x = b.atom(Atom::Lane(val(2 * i + 1)), i as usize); + let y = b.atom(Atom::Lane(val(2 * i + 2)), i as usize); + let clause = b.or(x, y); + reach = b.and(reach, clause); + } + // Keep the conflict (z0 & !z0) below all 22 diamonds so no variable is + // forced at the root; failed-state memoization collapses the DAG. + let z0 = b.atom(Atom::Lane(val(200)), 30); + let z1 = b.atom(Atom::Lane(val(201)), 30); + let eq = b.xor(z0, z1); + let c1 = b.and(reach, z0); + let nz0 = b.not(z0); + let c2 = b.and(reach, nz0); + assert!(!b.meet(&[(c1, true), (c2, true)])); + + let same_side = b.and(reach, eq); + assert!(b.meet(&[(c1, true), (same_side, true)])); + assert!(!b.meet(&[(c1, true), (c1, false)])); + } + + #[test] + fn meet_handles_canonical_dedup_and_trivial_constraints() { + let mut b = Bools::new(); + let x = b.atom(Atom::Lane(Value(1)), 0); + let nx = b.not(x); + assert!(b.meet(&[])); + assert!(b.meet(&[(Bool::TRUE, true), (Bool::FALSE, false)])); + assert!(!b.meet(&[(Bool::FALSE, true)])); + assert!(!b.meet(&[(Bool::TRUE, false)])); + assert!(b.meet(&[(x, true), (x, true)])); + assert!(!b.meet(&[(x, true), (x, false)])); + assert!(!b.meet(&[(x, false), (nx, false)])); + } + + #[test] + fn resource_lane_phi_prunes_dead_arm_behind_diamond_chain() { + use crate::native::{HwStage, RootParam, RootType::Table}; + + let mut words = vec![ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0602, + 0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0 + 0xF408_0802, + 0xFA00_0020, // s_load_dwordx4 s[32:35], s[4:5], 0x20 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + ]; + // Prepend 20 (a_i | b_i) early-cull diamonds so `reach` carries 3^20 paths into + // the `lane_phi` + waterfall below; each cbranch targets the shared final s_endpgm. + const DIAMONDS: usize = 20; + let mut cbranch_sites = Vec::with_capacity(DIAMONDS); + for _ in 0..DIAMONDS { + words.extend_from_slice(&[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE8A_036A, // s_mov_b32 s10, vcc_lo + 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0 + 0x886A_6A0A, // s_or_b32 vcc_lo, s10, vcc_lo + 0xBE8A_3C6A, // s_and_saveexec_b32 s10, vcc_lo + 0xBF88_0000, // s_cbranch_execz -> patched to final s_endpgm + ]); + cbranch_sites.push(words.len() - 1); + } + // Waterfall descriptor join guarded by `s30` (`24 > v0`); the `!s30` arm never runs + // inside the waterfall loop and must be proven dead despite the 20 diamonds above. + words.extend_from_slice(&[ + 0xD4C4_001E, + 0x0002_0098, // v_cmp_gt_u32_e64 s30, 24, v0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0004, // s_cbranch_execz -> +4 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0xBE94_3D14, // s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0007, // s_cbranch_execz -> +7 + 0xBE9F_3C1E, // s_and_saveexec_b32 s31, s30 + 0xBF88_0004, // s_cbranch_execz -> +4 + 0x7E08_0220, // v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x887E_1F7E, // s_or_b32 exec_lo, exec_lo, s31 + 0x887E_147E, // s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_3C1E, // s_and_saveexec_b32 s23, s30 + 0xBF88_0013, // s_cbranch_execz -> +19 + 0xBE9D_037E, // s_mov_b32 s29, exec_lo + 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xE030_1000, + 0x8003_0C10, // buffer_load_dword v12, v16, s[12:15], 0 offen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFF1, // s_cbranch_execnz -> loop + 0xBEFE_031D, // s_mov_b32 exec_lo, s29 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0x887E_177E, // s_or_b32 exec_lo, exec_lo, s23 + S_ENDPGM, + ]); + let end_idx = words.len() - 1; + for site in cbranch_sites { + let rel = (end_idx - site - 1) as u16; + words[site] = 0xBF88_0000 | u32::from(rel); + } + let p = build(&words, false); + let s = structure(&p).unwrap(); + let layout = [ + RootParam { + root: Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 1, + slot: 0, + }, + ]; + let r = crate::resource::track(&p, &layout, HwStage::Cs, Some(&s)).unwrap(); + assert_eq!(r.waterfall.reads.len(), 4, "{r:?}"); + assert!(!r.descriptors.is_empty(), "{r:?}"); + } } From b0cbac8e74255a4c49e8bf77c8a40543aba53f47 Mon Sep 17 00:00:00 2001 From: BastienRdz <58186763+BastienRodz@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:20:53 +0000 Subject: [PATCH 111/123] Loader: a clwb in the last bytes of a page is emulated instead of faulting emulate_amd_only copies only the bytes left in the faulting page and gated clwb_len on n >= 15 because clwb_len took a fixed [u8; 15]. A 4- to 10-byte clwb starting in the last 14 bytes of a page (or falling back from a clwb_loop that straddles the page end) was therefore skipped, leaving pre-Ice Lake Intel CPUs with an unhandled STATUS_ILLEGAL_INSTRUCTION. Change clwb_len to take &[u8], bounds-checking each byte read and returning Some(len) only when len <= code.len(), and drop the n >= 15 guard in emulate_amd_only. Fixes #924. Co-Authored-By: Gemini 4 Neon Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 60d2cf9cbcf5a2abc773d5de10c3c892e77d3340) --- crates/victory-loader/src/crash.rs | 96 +++++++++++++++++++++--------- 1 file changed, 68 insertions(+), 28 deletions(-) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index c74ab5cade..c27235c914 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -264,9 +264,7 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { context.Rip += pass.len as u64; return true; } - if n >= 15 - && let Some(len) = clwb_len(bytes[..15].try_into().unwrap_or([0; 15])) - { + if let Some(len) = clwb_len(&bytes[..n]) { // A write-back hint: the PC's memory is coherent, so it has nothing to do. context.Rip += len as u64; return true; @@ -285,12 +283,12 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { /// `clwb m8` (`66 [rex] 0f ae /6`, a memory operand), which Intel CPUs before /// Ice Lake lack: its length, or `None` for any other instruction. -fn clwb_len(code: [u8; 15]) -> Option { - let at = if code[1] & 0xf0 == 0x40 { 2 } else { 1 }; - if code[0] != 0x66 || code[at] != 0x0f || code[at + 1] != 0xae { +fn clwb_len(code: &[u8]) -> Option { + let at = if *code.get(1)? & 0xf0 == 0x40 { 2 } else { 1 }; + if *code.first()? != 0x66 || code.get(at..at + 2)? != [0x0f, 0xae] { return None; } - let modrm = code[at + 2]; + let modrm = *code.get(at + 2)?; let (mode, rm) = (modrm >> 6, modrm & 7); if mode == 3 || (modrm >> 3) & 7 != 6 { return None; @@ -298,7 +296,7 @@ fn clwb_len(code: [u8; 15]) -> Option { let mut len = at + 3; let mut base = rm; if rm == 4 { - base = code[len] & 7; + base = *code.get(len)? & 7; len += 1; } len += match mode { @@ -307,7 +305,7 @@ fn clwb_len(code: [u8; 15]) -> Option { 2 => 4, _ => 0, }; - Some(len) + (len <= code.len()).then_some(len) } /// A `clwb` write-back loop as the title's compilers build it, one cache line a @@ -965,26 +963,68 @@ mod tests { #[test] fn clwb_lengths() { - let pad = |b: &[u8]| { - let mut c = [0u8; 15]; - c[..b.len()].copy_from_slice(b); - c + assert_eq!(clwb_len(&[0x66, 0x41, 0x0f, 0xae, 0x31]), Some(5)); // clwb [r9] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x30]), Some(4)); // clwb [rax] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x70, 0x40]), Some(5)); // clwb [rax+0x40] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0]), Some(8)); // [rax+disp32] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x34, 0x24]), Some(5)); // clwb [rsp] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0]), Some(8)); // [rip+disp32] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x38]), None); // clflushopt, /7 + assert_eq!(clwb_len(&[0x0f, 0xae, 0x30]), None); // xsaveopt, no 66 + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0xf0]), None); // register form + } + + #[test] + fn a_clwb_at_the_end_of_a_page_is_decoded() { + // Exact-length slices, as at the end of a page. + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x30]), Some(4)); + assert_eq!(clwb_len(&[0x66, 0x41, 0x0f, 0xae, 0x31]), Some(5)); + // Cut short by the slice: returns None without panicking. + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0xb0, 0, 1]), None); // disp32, 6 of 8 bytes + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x70]), None); // disp8, 4 of 5 bytes + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x34]), None); // SIB missing + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x34, 0x25, 0, 0]), None); // SIB disp32 cut short + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae]), None); // ModRM missing + assert_eq!(clwb_len(&[0x66]), None); + assert_eq!(clwb_len(&[]), None); + + // Emulation at the last 4 and 5 bytes of a page with an unreadable page after it. + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, + VirtualFree, VirtualProtect, }; - assert_eq!(clwb_len(pad(&[0x66, 0x41, 0x0f, 0xae, 0x31])), Some(5)); // clwb [r9] - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x30])), Some(4)); // clwb [rax] - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x70, 0x40])), Some(5)); // clwb [rax+0x40] - assert_eq!( - clwb_len(pad(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0])), - Some(8) - ); // [rax+disp32] - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x34, 0x24])), Some(5)); // clwb [rsp] - assert_eq!( - clwb_len(pad(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0])), - Some(8) - ); // [rip+disp32] - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x38])), None); // clflushopt, /7 - assert_eq!(clwb_len(pad(&[0x0f, 0xae, 0x30])), None); // xsaveopt, no 66 - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xf0])), None); // register form + // SAFETY: two pages of ours, the second unreadable so reading past the first faults. + unsafe { + let page = VirtualAlloc( + std::ptr::null(), + 0x2000, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ) + .cast::(); + assert!(!page.is_null()); + let mut old = 0; + let guard = page.add(0x1000).cast(); + assert_ne!(VirtualProtect(guard, 0x1000, PAGE_NOACCESS, &mut old), 0); + for insn in [ + &[0x66, 0x0f, 0xae, 0x30][..], + &[0x66, 0x41, 0x0f, 0xae, 0x31][..], + ] { + let end = page.add(0x1000 - insn.len()); + end.copy_from_nonoverlapping(insn.as_ptr(), insn.len()); + let mut record: EXCEPTION_RECORD = std::mem::zeroed(); + record.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION; + let mut context: CONTEXT = std::mem::zeroed(); + context.Rip = end as u64; + let mut pointers = EXCEPTION_POINTERS { + ExceptionRecord: &mut record, + ContextRecord: &mut context, + }; + assert!(emulate_amd_only(&mut pointers)); + assert_eq!(context.Rip, end as u64 + insn.len() as u64); + } + VirtualFree(page.cast(), 0, MEM_RELEASE); + } } #[test] From d4bdd4c399e63d604c64989a7aeb5de44405781d Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 24 Nov 2026 10:15:52 -0300 Subject: [PATCH 112/123] HLE: XSystemGetXboxLiveSandboxId refuses a buffer under 16 bytes (cherry picked from commit d4306f4753fd28841402d39f09d72da253086c44) --- crates/victory-hle/src/modules/xsystem.rs | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/victory-hle/src/modules/xsystem.rs b/crates/victory-hle/src/modules/xsystem.rs index 625102b2a7..f94d546146 100644 --- a/crates/victory-hle/src/modules/xsystem.rs +++ b/crates/victory-hle/src/modules/xsystem.rs @@ -3,6 +3,7 @@ //! chose ([`victory_gpu::console`]). #![allow(clippy::not_unsafe_ptr_arg_deref)] +use super::xasync::E_NOT_SUFFICIENT_BUFFER; use super::xgameruntime::{ Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put_string, }; @@ -35,6 +36,9 @@ pub const ANALYTICS: Guid = Guid::new( const CONSOLE_ID: &str = "00000000000000000000000000000000000001"; /// The retail sandbox. const SANDBOX: &str = "RETAIL"; +/// `XSystemXboxLiveSandboxIdMaxBytes`: the least the runtime accepts for the +/// sandbox id, whatever the sandbox's own length. +const SANDBOX_ID_MAX_BYTES: usize = 16; /// Base64 of 32 bytes: 44 characters (45 bytes with the NUL). const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE="; @@ -62,6 +66,9 @@ extern "system" fn console_id(_: This, size: usize, buffer: *mut u8, used: *mut put_string(CONSOLE_ID, size, buffer, used) } extern "system" fn sandbox_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + if size < SANDBOX_ID_MAX_BYTES { + return E_NOT_SUFFICIENT_BUFFER; + } put_string(SANDBOX, size, buffer, used) } /// The device id this title sees (titles see different ones). @@ -424,6 +431,24 @@ mod tests { assert_eq!(&buffer[..7], b"VkljdG9"); } + #[test] + fn a_sandbox_id_buffer_under_the_documented_minimum_is_refused() { + type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT; + let get = method::(&OBJECT, 0x20); + let mut buffer = [0xAAu8; 16]; + let mut used = 0; + for size in [7, 15] { + assert_eq!( + get(&OBJECT, size, buffer.as_mut_ptr(), &mut used), + E_NOT_SUFFICIENT_BUFFER, + "size {size}" + ); + assert_eq!((used, buffer), (0, [0xAA; 16])); + } + assert_eq!(get(&OBJECT, 16, buffer.as_mut_ptr(), &mut used), S_OK); + assert_eq!((used, &buffer[..7]), (7, &b"RETAIL\0"[..])); + } + #[test] fn analytics_info_comes_back_through_the_buffer() { type Get = extern "system" fn(This, *mut AnalyticsInfo) -> *mut AnalyticsInfo; From 02ec4792c4f99bf936fc6615fb3c870e9bc57330 Mon Sep 17 00:00:00 2001 From: nino-exe <173394600+nino-exe@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:20:37 +0200 Subject: [PATCH 113/123] policy: resolve a `..` in the not-yet-existing part of a path `resolve` canonicalizes the longest existing prefix and re-appends the rest, but it walks up with `Path::file_name()`, which is None for a trailing `..`. A path such as `/a/../b` (nothing exists yet) hit the `_` arm and returned PolicyError::Io, so a cache_dir or data_dir with a `..` in a directory that does not exist yet was rejected, and `normalize`'s `..` handling for the missing tail was never reached. A trailing `..` is now kept in `rest` so `normalize` resolves it lexically. Test: resolves_dot_dot_in_a_path_that_does_not_exist_yet (fails before, passes after). cargo test -p victory-core, cargo fmt --check and cargo clippy --tests are clean. (cherry picked from commit 52f0a099ede8aa4d5bde61a0c46963a77a4378ba) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-core/src/policy.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/victory-core/src/policy.rs b/crates/victory-core/src/policy.rs index 43df38be16..cd86e2d794 100644 --- a/crates/victory-core/src/policy.rs +++ b/crates/victory-core/src/policy.rs @@ -118,6 +118,11 @@ fn resolve( rest.push(name.to_os_string()); existing = parent; } + // `file_name()` is None for a trailing `..`; keep it so `normalize` resolves it. + (Some(parent), None) if existing.ends_with("..") => { + rest.push("..".into()); + existing = parent; + } _ => { return Err(PolicyError::Io { path: path.to_path_buf(), @@ -240,4 +245,16 @@ mod tests { Err(PolicyError::InsideRepo { .. }) )); } + + #[test] + fn resolves_dot_dot_in_a_path_that_does_not_exist_yet() { + let base = std::env::temp_dir().join("victory-policy-no-such"); + let path = base.join("a").join("..").join("b"); + let resolved = resolve(&path, |p: &Path| std::fs::canonicalize(p)) + .expect("a `..` in the missing tail must resolve lexically"); + assert_eq!( + resolved, + resolve(&base.join("b"), |p: &Path| std::fs::canonicalize(p)).unwrap() + ); + } } From 9e9ecf43d934fd1092b8ff947671bdc7b8468fc6 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 14:11:20 +0300 Subject: [PATCH 114/123] Isolate the write-watch fixture from reused virtual addresses (cherry picked from commit 95cefdaca5f4d5ad1f01e97d7bac09b39f3c5c0d) --- crates/victory-gpu/src/watch.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index b44d0e7e74..f85b88b84e 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -480,6 +480,12 @@ mod tests { } as usize; assert_ne!(p, 0); let (start, end) = (p, p + 4 * PAGE); + // A previous test may have used these virtual addresses. + let mut journal = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + for page in start / PAGE..end / PAGE { + journal.written.remove(&page); + } + drop(journal); let (_, before) = writes(start, end, false).expect("watched"); assert!(before.is_empty()); // SAFETY: committed pages of ours. From 0f1d438f9db1d7da5f3eaee0886c7541ecddfb72 Mon Sep 17 00:00:00 2001 From: BastienRdz <58186763+BastienRodz@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:43:45 +0000 Subject: [PATCH 115/123] GPU: GetDeviceRemovedReason reports the host device's state instead of E_NOTIMPL ID3D12Device::GetDeviceRemovedReason "gets the reason that the device was removed, or S_OK if the device isn't removed" (Microsoft D3D12 reference). Slot 37 (0x128) in the device function table was left on the default handler, returning E_NOTIMPL (0x80004001) on a healthy device, which a title checking FAILED(GetDeviceRemovedReason()) takes as a lost device. Wire slot 37 to removed_reason, which queries the host device's GetDeviceRemovedReason() and returns S_OK on Ok (or when there is no host device) and the error's HRESULT otherwise. Add a unit test verifying slot 0x128 returns S_OK on a healthy device. Co-Authored-By: Gemini 4 Neon Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 033598be34e7d0bbbe06269ae93018c5ac2b17ab) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/device.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index 7336724d24..0e8dd27213 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -373,6 +373,18 @@ fn feature_levels(data: *mut c_void) -> HRESULT { } } +/// The host device's state: the console's device is removed when the host's is. +extern "system" fn removed_reason(_: This) -> HRESULT { + #[cfg(windows)] + if let Some(host) = crate::host::host() { + // SAFETY: a plain query. + if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } { + return e.code().0; + } + } + S_OK +} + /// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the /// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9, /// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of @@ -405,6 +417,7 @@ static FUNCTIONS: Table<160> = { f[28] = resource::create_heap as *const (); // 0xe0 f[29] = resource::create_placed as *const (); // 0xe8 f[36] = fence::create as *const (); // 0x120 + f[37] = removed_reason as *const (); // 0x128 f[38] = resource::copyable_footprints as *const (); // 0x130 f[39] = query::create as *const (); // 0x138 f[41] = signature::create as *const (); // 0x148 @@ -640,4 +653,11 @@ mod tests { assert_eq!(levels(samples), 0, "{samples} samples"); } } + + #[test] + fn a_healthy_device_reports_no_removal() { + let device = device(); + let reason = slot:: HRESULT>(device, 0x128); + assert_eq!(reason(device), S_OK); + } } From ddfb86830782e8cb6cdcbb9ffccc7ac43254aa11 Mon Sep 17 00:00:00 2001 From: BastienRdz <58186763+BastienRodz@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:59:29 +0000 Subject: [PATCH 116/123] Shaders: 16-bit compares read the low halves whatever op_sel says, as RDNA2 does Previously `half_src` applied VOP3 `op_sel` bits to every 16-bit operation, causing 16-bit compares (`v_cmp_*` and `v_cmpx_*` on f16, u16, and i16) to read the high half when `op_sel` was set. As measured on gfx1036 (RDNA2) across 146 cases in #833 (VGPR, SGPR, literal, inline-constant sources, wave32/wave64, and `v_cmpx_*_e64`), RDNA2 hardware ignores VOP3 `op_sel` on 16-bit compares and always compares the low halves, while non-compare 16-bit ops such as `v_add_nc_u16` still honour `op_sel`. Ignore VOP3 `op_sel` in `half_src` (which `half_fsrc` calls as well) for `v_cmp*` instructions except `v_cmp_class*` (not measured), while keeping SDWA word selects intact, and add an end-to-end VALU test covering f16/u16/i16 compares, `v_cmpx_lt_f16`, and `v_add_nc_u16` as a control. Co-Authored-By: Gemini 4 Neon (cherry picked from commit a8aa1d1cb376ed9fc82ce9cc30d25c47c0b3e9c4) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 5 +- crates/victory-shader/src/emit/valu_tests.rs | 91 ++++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index a0fa970902..9d84268753 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5705,7 +5705,10 @@ impl<'a> Lower<'a> { unreachable!() }; let op = *v.src.get(k).ok_or("a missing operand")?; - let mut high = v.opsel >> k & 1 != 0; + // RDNA2 ignores VOP3 op_sel on 16-bit compares (v_cmp_class not measured). + let name = inst.name(); + let compare = name.starts_with("v_cmp") && !name.contains("class"); + let mut high = !compare && v.opsel >> k & 1 != 0; if let Some(sd) = v.sdwa { match sd.src_sel.get(k).copied().unwrap_or(6) { 4 => {} diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index d9a631f123..a7cf104a5e 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -2223,3 +2223,94 @@ fn root_view_reads_stop_at_the_bound_size() { } assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); } + +/// RDNA2 ignores VOP3 `op_sel` on 16-bit compares (reading the low halves +/// regardless), while non-compare 16-bit ops such as `v_add_nc_u16` honour it. +#[test] +fn cmp16_ignores_op_sel_as_rdna2_does() { + let vop3_opsel = |op: u16, dst: u8, s0: u16, s1: u16, opsel: u8| -> [u32; 2] { + let [w0, w1] = vop3(op, dst, s0, s1, 0); + [w0 | (u32::from(opsel) << 11), w1] + }; + + // High and low halves give opposite outcomes for every non-zero source op_sel. + let f16_cases: &[([u32; 4], u32)] = &[ + // hi 2.0 vs 1.0, lo 1.0 < 1.5 -> true only when both read the low half + ([0x4000_3C00, 0x3C00_3E00, 0, 0], 1), + // hi 1.0 vs 3.0, lo 2.0 < 1.5 -> false only when both read the low half + ([0x3C00_4000, 0x4200_3E00, 0, 0], 0), + ]; + let u16_cases: &[([u32; 4], u32)] = &[ + // hi 10 vs 1, lo 1 < 2 -> true + ([0x000A_0001, 0x0001_0002, 0, 0], 1), + // hi 1 vs 20, lo 10 < 2 -> false + ([0x0001_000A, 0x0014_0002, 0, 0], 0), + ]; + let i16_cases: &[([u32; 4], u32)] = &[ + // hi 1 vs -2, lo -1 < 0 -> true + ([0x0001_FFFF, 0xFFFE_0000, 0, 0], 1), + // hi -2 vs 2, lo 1 < -1 -> false + ([0xFFFE_0001, 0x0002_FFFF, 0, 0], 0), + ]; + + let mut cmp_shaders = Vec::new(); + for (op, what, cases) in [ + (0x0c9u16, "v_cmp_lt_f16", f16_cases), + (0x0a9, "v_cmp_lt_u16", u16_cases), + (0x089, "v_cmp_lt_i16", i16_cases), + ] { + for opsel in [0b0001u8, 0b0010, 0b0011] { + let mut body = vop3_opsel(op, 6, vgpr(1), vgpr(2), opsel).to_vec(); + body.extend_from_slice(&vop3(0x101, 0, 0x80, 0x81, sgpr(6))); + cmp_shaders.push((what, opsel, build_valu_cs(&body), cases)); + } + } + + // v_cmpx_lt_f16_e64 (0x0d9) writing EXEC directly also ignores op_sel. + let [w0, w1] = vop3_opsel(0x0d9, 126, vgpr(1), vgpr(2), 0b0001); + let cmpx = build_valu_cs(&[ + s_mov_b32(6, 126), // save exec_lo + vop1(0x001, 0, 0x80), // v0 = 0 + w0, + w1, // v_cmpx_lt_f16_e64 exec_lo, v1, v2 op_sel:[1,0] + vop1(0x001, 0, 0x81), // v0 = 1 if active + s_mov_b32(126, 6), // restore exec_lo + ]); + + // Control: v_add_nc_u16 (0x303) still honours op_sel. + let [w0, w1] = vop3_opsel(0x303, 0, vgpr(1), vgpr(2), 0b0001); + let add_hi = build_valu_cs(&[vop1(0x001, 0, 0x80), w0, w1]); + + for (what, opsel, shader, cases) in &cmp_shaders { + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: {what} opsel={opsel:#b} ({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + } + + let f16_in: Vec<[u32; 4]> = f16_cases.iter().map(|c| c.0).collect(); + run_cases(&cmpx, &f16_in, |backend, i, inp, got| { + let want = f16_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmpx_lt_f16 opsel=0b1 ({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + + run_cases( + &add_hi, + &[[0x000A_0001, 0x0014_0002, 0, 0]], + |backend, _, _, got| { + assert_eq!( + got, 12, + "{backend}: v_add_nc_u16 op_sel:[1,0] = {got}, want 12" + ); + }, + ); +} From 1288b014288e3ebb84993b12cbc0343367a413a0 Mon Sep 17 00:00:00 2001 From: swarm Date: Tue, 24 Nov 2026 09:23:02 -0500 Subject: [PATCH 117/123] Check that SDWA half-word selection survives the VOP3 compare fix (cherry picked from commit f45973553c09202da84d1160a2ddec1eb7b959b5) --- crates/victory-shader/src/emit/valu_tests.rs | 23 ++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index a7cf104a5e..d8a0e8a71c 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -2314,3 +2314,26 @@ fn cmp16_ignores_op_sel_as_rdna2_does() { }, ); } + +#[test] +fn cmp16_sdwa_preserves_word_selects() { + // llvm-mc -mcpu=gfx1030: v_cmp_lt_{f16,i16,u16}_sdwa vcc_lo, v1, v2. + let instructions = [ + (0x7d92_04f9, [0x4000_3c00, 0x3800_3e00, 0, 0]), + (0x7d12_04f9, [0x0003_ffff, 0xfffe_0000, 0, 0]), + (0x7d52_04f9, [0x0003_0001, 0x0000_0002, 0, 0]), + ]; + let select = vop3(0x101, 0, 0x80, 0x81, sgpr(106)); + for (instruction, input) in instructions { + // Low/low gives true. Selecting either high word gives false. + for (extension, expected) in [(0x0404_0001, 1), (0x0405_0001, 0), (0x0504_0001, 0)] { + let shader = build_valu_cs(&[instruction, extension, select[0], select[1]]); + run_cases(&shader, &[input], |backend, _, _, actual| { + assert_eq!( + actual, expected, + "{backend}: {instruction:#x} {extension:#x}" + ); + }); + } + } +} From 0805408257f2d68f3ff1344ff24ba7d741e96779 Mon Sep 17 00:00:00 2001 From: BastienRdz <58186763+BastienRodz@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:28:28 +0000 Subject: [PATCH 118/123] Shaders: half_src's comment says 16-bit compares ignore op_sel Co-Authored-By: Claude Opus 5.5 (cherry picked from commit e477c4bb64cb72e67e81db772e5969ae04e722e0) --- crates/victory-shader/src/emit/lower.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 9d84268753..2d90b3313a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5698,7 +5698,8 @@ impl<'a> Lower<'a> { } /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0): - /// op_sel (or an SDWA word select) picks the high half; inline float + /// op_sel (or an SDWA word select) picks the high half, except that + /// 16-bit compares other than `v_cmp_class` ignore op_sel; inline float /// constants are f16 values here. fn half_src(&mut self, inst: &Inst, k: usize) -> Result { let Fields::Valu(v) = &inst.fields else { From 8308c185a96cf9843b2667709816b3d9579a6922 Mon Sep 17 00:00:00 2001 From: Enzo Souza Duarte Date: Tue, 24 Nov 2026 11:10:55 -0300 Subject: [PATCH 119/123] Pipeline: delimit converter id in cache keys (cherry picked from commit f7bce85fcce3103f049dd6229eb00839a6e4778d) --- crates/victory-pipeline/src/cache.rs | 33 ++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/victory-pipeline/src/cache.rs b/crates/victory-pipeline/src/cache.rs index 81e57de2dc..ea88f7cc09 100644 --- a/crates/victory-pipeline/src/cache.rs +++ b/crates/victory-pipeline/src/cache.rs @@ -11,9 +11,12 @@ pub struct CacheKey(blake3::Hash); impl CacheKey { pub fn new(converter: &dyn Converter, input: &[u8]) -> Self { + let id = converter.id(); let mut h = blake3::Hasher::new(); - h.update(converter.id().as_bytes()); - h.update(&[0]); + // Length-prefix the id so a NUL inside it cannot be mistaken for the + // old separator and collide with a different id/version pair. + h.update(&(id.len() as u64).to_le_bytes()); + h.update(id.as_bytes()); h.update(&converter.version().to_le_bytes()); h.update(input); CacheKey(h.finalize()) @@ -151,6 +154,32 @@ mod tests { assert_ne!(CacheKey::new(&v1, b"x"), CacheKey::new(&v2, b"x")); } + struct Keyed(&'static str, u32); + + impl Converter for Keyed { + fn id(&self) -> &'static str { + self.0 + } + fn version(&self) -> u32 { + self.1 + } + fn convert(&self, _: &[u8]) -> Result> { + Ok(Vec::new()) + } + } + + #[test] + fn id_and_version_are_delimited() { + assert_ne!( + CacheKey::new(&Keyed("a\0", 1), b""), + CacheKey::new(&Keyed("a", 256), b"") + ); + assert_ne!( + CacheKey::new(&Keyed("a", 1), b"b"), + CacheKey::new(&Keyed("a", 1), b"") + ); + } + #[test] fn refuses_cache_inside_repo() { let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache"); From 8a334f6d224ed741e975c028e90e0124d264fbee Mon Sep 17 00:00:00 2001 From: Noname0202 Date: Tue, 24 Nov 2026 14:39:53 +0000 Subject: [PATCH 120/123] Shaders: handle s_buffer_load SMEM uses in descriptor_data (#798) A descriptor whose only use is an s_buffer_load is a raw buffer to the host; descriptor_data fell through to "a scalar memory read as data". Upstream reports 771 -> 0 such failures and +231 programs translated. From upstream PR #953 (c42cbb0737), hand-ported. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 50 +++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 2d90b3313a..5a3e270316 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3990,6 +3990,16 @@ impl<'a> Lower<'a> { } (props, None) } + // A descriptor that `s_buffer_load` reads is a raw buffer + // to the host when the load is a raw one (#798): a UAV or a + // known SRV. Else the load is a constant buffer, whose size + // no handle of the same slot can query. + Fields::Smem { .. } if un.starts_with("s_buffer_load") => { + if u == 0 && !used.is_some_and(|u| u.kind == ResourceType::Srv) { + return Err("a constant buffer's descriptor read as data"); + } + ((11 | u, 0), None) + } _ => return Err("a scalar memory read as data"), }; (first, src, props, image, uav) @@ -9795,6 +9805,46 @@ mod tests { lower_with(&words, layout(), used()).unwrap(); } + #[test] + fn s_buffer_load_descriptor_size_reads_as_data() { + // Buffer descriptor loaded from the table at s0, used by an SMEM + // `s_buffer_load_dword` (Fields::Smem) and also read as data via + // dword 2 (`s10`, num_records), then written to LDS. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF420_0304, + 0xFA00_0000, // s_buffer_load_dword s12, s[8:11], null + 0x800D_0A0C, // s_add_u32 s13, s12, s10 + 0x7E02_020D, // v_mov_b32 v1, s13 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let used = |kind| { + vec![UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + lower_with(&words, vec![root(RootType::Table, 0, 0)], used(ResourceType::Srv)).unwrap(); + let err = lower_with(&words, vec![root(RootType::Table, 0, 0)], used(ResourceType::Cbv)) + .err() + .expect("CBV descriptor read as data must be refused"); + assert!( + err.to_string().contains("constant buffer's descriptor read as data"), + "unexpected error: {err}" + ); + } + /// Tables of 2D textures at s0 and samplers at s1. fn texture_tables() -> (Vec, Vec) { let range = |kind, user_data, slot| UsedResource { From e6379def55745b8c65426002e95e9b609c50980c Mon Sep 17 00:00:00 2001 From: Sakura-Byte <42319937+Sakura-Byte@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:42:36 +0000 Subject: [PATCH 121/123] Shaders: helper lanes keep their own value in pixel v_readfirstlane DXIL waveReadLaneFirst reads the first active non-helper lane, while the console's WQM keeps helper lanes in EXEC. In a pixel waterfall loop a helper lane never matches the value it reads and spins to the loop limit. In pixel shaders, select the lane's own value when isHelperLane (SM 6.6, opcode 221) holds. From upstream PR #946 (c1596049), hand-ported. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-shader/src/emit/bitcode.rs | 6 +++ crates/victory-shader/src/emit/lower.rs | 60 ++++++++++++++++++++++- 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index c7b23a19cd..2a0ba3cb59 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -215,6 +215,12 @@ pub(crate) struct Module { } impl Module { + /// The names of the declared and defined functions. + #[cfg(test)] + pub fn func_names(&self) -> Vec { + self.funcs.iter().map(|f| f.name.clone()).collect() + } + fn ty(&mut self, def: TypeDef) -> Ty { if let Some(&t) = self.type_ids.get(&def) { return Ty(t); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 5a3e270316..ae6df472f3 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -56,6 +56,9 @@ pub(crate) struct Lowered { /// Whether the program uses wave operations. #[cfg(test)] pub wave_ops: bool, + /// The functions the module declares. + #[cfg(test)] + pub funcs: Vec, /// Mesh primitive exports bounded by the declared vertex count. #[cfg(test)] pub bounded_prims: u32, @@ -1255,6 +1258,8 @@ impl<'a> Lower<'a> { #[cfg(test)] wave_ops: self.s.flags & flags::WAVE_OPS != 0, #[cfg(test)] + funcs: self.s.m.func_names(), + #[cfg(test)] bounded_prims: self.s.bounded_prims, #[cfg(test)] spin_loops: self.spun, @@ -5629,7 +5634,7 @@ impl<'a> Lower<'a> { return int(self, r); } self.s.flags |= flags::WAVE_OPS; - let r = self.s.op( + let first = self.s.op( c, "waveReadLaneFirst.i32", Attr::NoUnwind, @@ -5637,6 +5642,23 @@ impl<'a> Lower<'a> { 118, &[a], ); + let r = if self.s.pixel { + // The host's waveReadLaneFirst skips helper lanes, which + // the console's WQM keeps in EXEC: a waterfall loop on a + // helper lane would never match the value it reads and + // spin to the loop limit. A helper lane takes its own. + let helper = self.s.op( + c, + "isHelperLane.i1", + Attr::ReadOnly, + self.s.t.i1, + 221, + &[], + ); + self.s.m.select(c, helper, a, first) + } else { + first + }; int(self, r) } _ => { @@ -9162,6 +9184,11 @@ mod tests { /// Lowers a pixel program with one target: whether it translates. fn lowers_ps(words: &[u32]) -> Result<(), crate::ShaderError> { + lower_ps(words).map(|_| ()) + } + + /// Lowers a pixel program with one target. + fn lower_ps(words: &[u32]) -> Result { let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Ps, @@ -9205,7 +9232,36 @@ mod tests { mesh_stride: 0, host_wave64: true, }) - .map(|_| ()) + } + + /// A pixel waterfall loop: each pass reads the first lane's v0 and + /// retires the lanes holding the same value. The host's + /// waveReadLaneFirst skips helper lanes, so a helper lane takes its own + /// value instead (else it never matches and spins to the loop limit). + #[test] + fn pixel_read_first_lane_gives_helper_lanes_their_own_value() { + let waterfall = [ + 0xD765_0000, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v0, -1, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E18_0500, // v_readfirstlane_b32 s12, v0 + 0x7D84_000C, // v_cmp_eq_u32 vcc, s12, v0 + 0xBE95_3C6A, // s_and_saveexec_b32 s21, vcc_lo + 0xBF80_0000, // s_nop 0 + 0x7E02_02FF, + 0x3F80_0000, // v_mov_b32 v1, 1.0f + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFF8, // s_cbranch_execnz -> loop + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xF800_180F, + 0x0101_0101, // exp mrt0, v1, v1, v1, v1 done vm + S_ENDPGM, + ]; + let l = lower_ps(&waterfall).unwrap(); + let has = |name: &str| l.funcs.iter().any(|f| f == name); + assert!(has("dx.op.waveReadLaneFirst.i32"), "{:?}", l.funcs); + assert!(has("dx.op.isHelperLane.i1"), "{:?}", l.funcs); } /// Lowers a compute program of constants that allocates 512 bytes of LDS From e50bf48202e082219ec94521f0c2c505d0b2374a Mon Sep 17 00:00:00 2001 From: Noname0202 Date: Tue, 24 Nov 2026 14:47:45 +0000 Subject: [PATCH 122/123] GPU: run ExecuteIndirect signatures that set root constants (#757) A command signature with root-constant arguments before its draw or dispatch was dropped. Map each title constant argument onto the host root parameter carrying the user data of the stage that reads it (or an unused range when none does), build a host signature bound to the pipeline's root signature (cached on the pipeline), and clamp the draw/dispatch argument at its offset in each record. The planner is pure and tested on every platform. Not mapped yet: root view arguments, a constant two stages read, a spilled (root CBV) user-data stage, rectangle lists. From upstream PR #956 (71967c10), hand-ported. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 104 ++++++++- crates/victory-gpu/src/indirect.rs | 29 +++ crates/victory-gpu/src/indirect_plan.rs | 280 ++++++++++++++++++++++++ crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/list.rs | 13 +- crates/victory-gpu/src/pipeline/host.rs | 12 + 6 files changed, 421 insertions(+), 19 deletions(-) create mode 100644 crates/victory-gpu/src/indirect_plan.rs diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 46e571d178..57cd226b26 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1387,8 +1387,9 @@ impl State { } impl State { - /// Indirect execution of a one-argument signature of `kind` (PC - /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with + /// Indirect execution of the title command signature `title_args` + /// (PC numbering of the last argument: 0 draw, 1 indexed draw, 2 + /// dispatch, 10 mesh dispatch; root constants may come before it) with /// records `stride` bytes apart at title address `arguments`, and the /// record count at `count` if the title gives one: the GPU reads them /// from the buffer's host copy, where earlier dispatches may have @@ -1396,7 +1397,9 @@ impl State { pub(crate) fn execute_indirect( &mut self, list: &HostList, - (kind, stride, max): (u32, u32, u32), + stride: u32, + title_args: &[[u32; 4]], + max: u32, arguments: u64, count: Option, ) -> bool { @@ -1410,6 +1413,33 @@ impl State { const INDEXED: u32 = 1; const DISPATCH: u32 = 2; const MESH: u32 = 10; + let pipeline = crate::pipeline::host_pipeline(self.pipeline as This); + // Root constants land in the user data of the stage that reads + // them; a spilled stage's user data is a root view (no dwords). + let stages: Vec> = pipeline + .map(|p| { + p.stages + .iter() + .filter_map(|s| { + let (param, dwords) = s.user_data?; + Some(crate::indirect_plan::StageUserData { + param, + dwords: if s.user_data_cbv { 0 } else { dwords }, + entries: &s.translated().host.user_data, + }) + }) + .collect() + }) + .unwrap_or_default(); + let Some(plan) = crate::indirect_plan::plan_indirect(stride, title_args, &stages) else { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_why(format!( + "indirect signature {title_args:?}: cannot map onto the host pipeline" + )); + return false; + }; + let kind = plan.kind; + let multi = plan.args.len() > 1; #[cfg(feature = "diagnostics")] let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); #[cfg(not(feature = "diagnostics"))] @@ -1429,6 +1459,11 @@ impl State { }, None => None, }; + if multi && self.topology == RECTANGLES { + once!("indirect rectangles with root constants not drawn"); + why("rectangles with root constants not supported"); + return false; + } if kind == INDEXED && self.topology == RECTANGLES { once!("indirect indexed rectangles not drawn"); why("indexed rectangles not supported"); @@ -1498,10 +1533,14 @@ impl State { DRAWN.fetch_add(1, Ordering::Relaxed); return true; } - let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH) - .then(|| host_signature(kind, stride)) - .flatten() - else { + let signature = if multi { + pipeline.and_then(|p| pipeline_signature(p, &plan.args, stride)) + } else { + matches!(kind, DRAW | INDEXED | DISPATCH | MESH) + .then(|| host_signature(kind, stride)) + .flatten() + }; + let Some(signature) = signature else { why("no host signature"); return false; }; @@ -1510,7 +1549,10 @@ 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)) { + // The clamp's view starts at the draw or dispatch argument of the + // first record (a root view has no bounds to shift). + let at = args.gpu(arguments) + u64::from(plan.arg_offset); + if !crate::indirect::bound(list, &args.buffer, at, (kind, stride, max)) { why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; } @@ -1519,7 +1561,7 @@ impl State { let ran = match kind { DRAW | INDEXED => self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), - DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) { + DISPATCH => match pipeline { Some(p) if p.compute => { self.bind(list, p, true); true @@ -1528,6 +1570,13 @@ impl State { }, _ => false, }; + // A signature with root arguments needs the root signature it was + // made for bound. + let ran = ran + && (!multi + || pipeline.is_some_and(|p| { + self.host_roots[usize::from(kind == DISPATCH)] == p.root.as_raw() as usize + })); if !ran { crate::indirect::done(list, &args.buffer); #[cfg(feature = "diagnostics")] @@ -1540,6 +1589,9 @@ impl State { } return false; } + if multi { + list.keep(&signature); + } #[cfg(feature = "diagnostics")] list.note_op(|| { self.op_text( @@ -1569,6 +1621,40 @@ impl State { } } +/// A multi-argument host command signature for `p`'s root signature, +/// made once per argument layout and stride. +fn pipeline_signature( + p: &HostPipeline, + args: &[crate::indirect_plan::HostIndirectArg], + stride: u32, +) -> Option { + let mut cache = p.signatures.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, _, s)) = cache.iter().find(|(a, st, _)| *st == stride && a == args) { + return Some(s.clone()); + } + let descs = crate::indirect::to_d3d12_descs(args); + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: descs.len() as u32, + pArgumentDescs: descs.as_ptr(), + NodeMask: 0, + }; + let mut signature: Option = None; + // SAFETY: `descs` lives through the call; `p.root` is a live root signature. + let result = unsafe { + crate::host::host()? + .device + .CreateCommandSignature(&desc, Some(&p.root), &mut signature) + }; + if let Err(e) = result { + once!(error = %e, ?args, stride, "host multi-argument command signature refused"); + return None; + } + let signature = signature?; + cache.push((args.to_vec(), stride, 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/indirect.rs b/crates/victory-gpu/src/indirect.rs index f3fb07dc20..2d2e2c3f6f 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -386,6 +386,35 @@ pub(crate) fn bound( true } +/// The D3D12 argument descriptions of a planned host signature. +pub(crate) fn to_d3d12_descs( + args: &[crate::indirect_plan::HostIndirectArg], +) -> Vec { + use crate::indirect_plan::HostIndirectArg; + args.iter() + .map(|&arg| match arg { + HostIndirectArg::Constant { + param, + offset, + count, + } => 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: offset, + Num32BitValuesToSet: count, + }, + }, + }, + HostIndirectArg::Execute(kind) => D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), + ..Default::default() + }, + }) + .collect() +} + /// After the execution: the buffer back to unordered access, where the /// title's passes keep using it. pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) { diff --git a/crates/victory-gpu/src/indirect_plan.rs b/crates/victory-gpu/src/indirect_plan.rs new file mode 100644 index 0000000000..0eceeb580f --- /dev/null +++ b/crates/victory-gpu/src/indirect_plan.rs @@ -0,0 +1,280 @@ +//! Indirect execution of multi-argument command signatures (#757): the +//! title's root-constant arguments before a draw or dispatch, mapped onto +//! the host root parameters that carry each stage's user data. Pure +//! planning, so it is tested everywhere; [`crate::indirect`] builds the host +//! signature. +//! +//! shortcut: only root constants are mapped; a root view argument, or a +//! constant two stages read, still drops the execution. +//! +//! From upstream PR #956 (Noname0202, 71967c10), hand-ported. + +/// One argument of a host command signature. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum HostIndirectArg { + Constant { param: u32, offset: u32, count: u32 }, + Execute(u32), +} + +/// One stage's user-data root-constant parameter, for mapping title indirect +/// root constants onto our host root signature. +pub(crate) struct StageUserData<'a> { + pub(crate) param: u32, + pub(crate) dwords: u32, + pub(crate) entries: &'a [victory_shader::emit::UserData], +} + +/// Host command-signature layout and trailing draw/dispatch offset for an +/// indirect execution. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct IndirectPlan { + /// Final execution kind (PC numbering: 0 draw, 1 indexed, 2 dispatch, 10 mesh). + pub(crate) kind: u32, + /// Byte offset of the final draw/dispatch argument inside each record. + pub(crate) arg_offset: u32, + /// Host arguments in record order (0 or more `Constant`s, then `Execute(kind)`). + pub(crate) args: Vec, +} + +/// Maps a title command signature (`stride`, `title_args`) onto `stages`'s +/// host user-data parameters. Supports single-argument draw/dispatch/mesh +/// signatures and multi-argument signatures whose prefix arguments are root +/// constants (`D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT`). +pub(crate) fn plan_indirect( + stride: u32, + title_args: &[[u32; 4]], + stages: &[StageUserData<'_>], +) -> Option { + const DRAW: u32 = 0; + const INDEXED: u32 = 1; + const DISPATCH: u32 = 2; + const CONSTANT: u32 = 5; + const MESH: u32 = 10; + const DISPATCH_SINGLE: u32 = 105; + + let (last, prefix) = title_args.split_last()?; + let kind = if last[0] == DISPATCH_SINGLE { + DISPATCH + } else { + last[0] + }; + let exec_bytes = match kind { + DRAW => 16, + INDEXED => 20, + DISPATCH | MESH => 12, + _ => return None, + }; + if prefix.is_empty() { + return Some(IndirectPlan { + kind, + arg_offset: 0, + args: vec![HostIndirectArg::Execute(kind)], + }); + } + + let mut host_args = Vec::with_capacity(title_args.len()); + let mut arg_offset = 0u32; + for arg in prefix { + if arg[0] != CONSTANT { + return None; + } + let title_slot = u8::try_from(arg[1]).ok()?; + let dest_off = arg[2]; + let num = arg[3]; + if num == 0 { + return None; + } + let end_dword = dest_off.checked_add(num)?; + + // Find every stage/index reading any dword in [dest_off, dest_off + num). + let mut target_stage: Option = None; + let mut base_index: Option = None; + for (si, stage) in stages.iter().enumerate() { + for u in stage.entries { + if u.root == victory_shader::RootType::Constants + && u.slot == title_slot + && u.dword >= dest_off + && u.dword < end_dword + { + let k = u.dword - dest_off; + let candidate = u.index.checked_sub(k)?; + match (target_stage, base_index) { + (None, None) => { + target_stage = Some(si); + base_index = Some(candidate); + } + (Some(s), Some(b)) if s == si && b == candidate => {} + _ => return None, + } + } + } + } + + let mapped = if let (Some(si), Some(base)) = (target_stage, base_index) { + let stage = &stages[si]; + let end_idx = base.checked_add(num)?; + if end_idx > stage.dwords { + return None; + } + // No other user-data entry may live in [base, base + num). + let collides = stage.entries.iter().any(|u| { + u.index >= base + && u.index < end_idx + && !(u.root == victory_shader::RootType::Constants + && u.slot == title_slot + && u.dword == dest_off + (u.index - base)) + }); + if collides { + return None; + } + HostIndirectArg::Constant { + param: stage.param, + offset: base, + count: num, + } + } else { + // No stage reads these constants; keep record alignment by landing + // them in an unused contiguous range of some stage's user data. + let mut free = None; + 'find: for stage in stages { + if num > stage.dwords { + continue; + } + for base in 0..=stage.dwords - num { + let end_idx = base + num; + let used_by_shader = stage + .entries + .iter() + .any(|u| u.index >= base && u.index < end_idx); + let used_by_prev = host_args.iter().any(|a| match *a { + HostIndirectArg::Constant { + param, + offset, + count, + } => param == stage.param && offset < end_idx && offset + count > base, + HostIndirectArg::Execute(_) => false, + }); + if !used_by_shader && !used_by_prev { + free = Some(HostIndirectArg::Constant { + param: stage.param, + offset: base, + count: num, + }); + break 'find; + } + } + } + free? + }; + + host_args.push(mapped); + arg_offset = arg_offset.checked_add(num.checked_mul(4)?)?; + } + if arg_offset.checked_add(exec_bytes)? > stride { + return None; + } + host_args.push(HostIndirectArg::Execute(kind)); + Some(IndirectPlan { + kind, + arg_offset, + args: host_args, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use victory_shader::RootType; + use victory_shader::emit::UserData; + + #[test] + fn plan_indirect_maps_root_constants_and_rejects_unsupported() { + let entries = [ + UserData { + index: 2, + slot: 1, + root: RootType::Constants, + dword: 0, + }, + UserData { + index: 3, + slot: 1, + root: RootType::Constants, + dword: 1, + }, + UserData { + index: 4, + slot: 0, + root: RootType::Table, + dword: 0, + }, + ]; + let stages = [StageUserData { + param: 0, + dwords: 8, + entries: &entries, + }]; + + // Single-argument dispatch stays at offset 0. + let single = plan_indirect(12, &[[2, 0, 0, 0]], &stages).unwrap(); + assert_eq!(single.kind, 2); + assert_eq!(single.arg_offset, 0); + assert_eq!(single.args, vec![HostIndirectArg::Execute(2)]); + + // Console DISPATCH_SINGLE (105) normalizes to DISPATCH (2). + let single_console = plan_indirect(12, &[[105, 0, 0, 0]], &stages).unwrap(); + assert_eq!(single_console.kind, 2); + + // Two root constants followed by Dispatch (stride 20 = 8 + 12). + let multi = plan_indirect(20, &[[5, 1, 0, 2], [2, 0, 0, 0]], &stages).unwrap(); + assert_eq!(multi.kind, 2); + assert_eq!(multi.arg_offset, 8); + assert_eq!( + multi.args, + vec![ + HostIndirectArg::Constant { + param: 0, + offset: 2, + count: 2, + }, + HostIndirectArg::Execute(2), + ] + ); + + // Unused constant lands in an unoccupied slot (0..1) without colliding with entries. + let unused = plan_indirect(16, &[[5, 7, 0, 1], [2, 0, 0, 0]], &stages).unwrap(); + assert_eq!(unused.arg_offset, 4); + assert_eq!( + unused.args[0], + HostIndirectArg::Constant { + param: 0, + offset: 0, + count: 1, + } + ); + + // Collision with an occupied table slot at index 4 is rejected. + assert!(plan_indirect(24, &[[5, 1, 0, 3], [2, 0, 0, 0]], &stages).is_none()); + + // Stride smaller than arg_offset + exec_bytes is rejected. + assert!(plan_indirect(16, &[[5, 1, 0, 2], [2, 0, 0, 0]], &stages).is_none()); + + // Non-constant prefix argument (e.g. CBV = 6) is rejected. + assert!(plan_indirect(20, &[[6, 0, 0, 0], [2, 0, 0, 0]], &stages).is_none()); + + // Same constant read by two different stages cannot map to one host parameter. + let stage2 = [ + StageUserData { + param: 0, + dwords: 4, + entries: &entries[..1], + }, + StageUserData { + param: 1, + dwords: 4, + entries: &entries[..1], + }, + ]; + assert!(plan_indirect(16, &[[5, 1, 0, 1], [2, 0, 0, 0]], &stage2).is_none()); + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index cb01b0666b..99a986053e 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -31,6 +31,8 @@ pub mod frame; mod host; #[cfg(windows)] mod indirect; +#[cfg_attr(not(windows), allow(dead_code))] +mod indirect_plan; pub mod list; pub mod object; pub mod pipeline; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index eeae581606..c46adfa51b 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1709,7 +1709,7 @@ mod state { } let mut ran = false; with_state(this, |list, s| { - ran = s.execute_indirect(list, (MESH, STRIDE, 1), indirect, None); + ran = s.execute_indirect(list, STRIDE, &[[MESH, 0, 0, 0]], 1, indirect, None); }); if !ran { super::INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -1796,18 +1796,11 @@ extern "system" fn execute_indirect( let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset); let mut ran = false; #[cfg(windows)] - if let ([[kind, ..]], Some(address)) = (args, address) + if let (false, Some(address)) = (args.is_empty(), address) && (count.is_null() || counter.is_some()) { - const DISPATCH: u32 = 2; - const DISPATCH_SINGLE: u32 = 105; - let kind = if *kind == DISPATCH_SINGLE { - DISPATCH - } else { - *kind - }; with_state(this, |list, s| { - ran = s.execute_indirect(list, (kind, stride, max), address, counter); + ran = s.execute_indirect(list, stride, args, max, address, counter); }); } else { #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 56a52fe25e..a78366e042 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -373,6 +373,15 @@ pub(crate) struct HostPipeline { pub(crate) strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, /// Its shaders, for reports of slow submissions. pub(crate) name: String, + /// Multi-argument host command signatures bound to `root`, by argument + /// layout and record stride. + pub(crate) signatures: std::sync::Mutex< + Vec<( + Vec, + u32, + ID3D12CommandSignature, + )>, + >, } /// Logs a pipeline that gets no host pipeline, once per reason. @@ -592,6 +601,7 @@ impl HostPipeline { root, stages: bound, name: format!("{shaders:?}"), + signatures: std::sync::Mutex::new(Vec::new()), slots: 0, inputs: Vec::new(), strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, @@ -629,6 +639,7 @@ impl HostPipeline { root, stages: bound, name: format!("{shaders:?}"), + signatures: std::sync::Mutex::new(Vec::new()), slots: 0, inputs: Vec::new(), strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, @@ -709,6 +720,7 @@ impl HostPipeline { root, stages: bound, name: format!("{shaders:?}"), + signatures: std::sync::Mutex::new(Vec::new()), slots: g.slots(), inputs: g.elements(), strip_cut: g.strip_cut, From 90e0f8d03ce965f637cdf9ff3a6508bf837e26ec Mon Sep 17 00:00:00 2001 From: MfDev0 <253415739+MfDev0@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:48:00 +0000 Subject: [PATCH 123/123] VIctory Try 1.2 Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- scripts/try/try.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/try/try.ps1 b/scripts/try/try.ps1 index 8838034308..772dbce61d 100644 --- a/scripts/try/try.ps1 +++ b/scripts/try/try.ps1 @@ -15,7 +15,7 @@ $ErrorActionPreference = 'Continue' $ProgressPreference = 'SilentlyContinue' -$TryVersion = '1.1' +$TryVersion = '1.2' $ForkUrl = 'https://github.com/MfDev0/victory.git' $Branch = 'arena/59fabb00-victory' $UpstreamUrl = 'https://github.com/Marvisak/VIctory.git'