From 1661a3e0cfb31380ea71faad2f98c3c983d5cea6 Mon Sep 17 00:00:00 2001 From: Jason Vermaak <346274234+VermaakLabs@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:54:54 +0200 Subject: [PATCH 01/25] Shaders: lower image_atomic_inc, _dec, _fcmpswap, _fmin and _fmax DXIL has no operation for these five, so they stopped the program. Each is now a compare-and-swap loop on the dword: the new value is made from the old one by RDNA2's definition, starting from a guess of 0, until the exchange finds the value it was made from. A null view reads 0, so the loop leaves at once there. inc and dec wrap at the data as the ISA says; fcmpswap compares as floats (-0 matches +0, NaN matches nothing); fmin and fmax follow v_min_f32 and v_max_f32. Tests: synthetic GFX10 compute shaders for each, validated by dxil.dll and run on the host GPU and WARP, checking the returned old value and the texel left behind. --- .../src/emit/image_atomic_tests.rs | 269 ++++++++++++++++++ crates/victory-shader/src/emit/lower.rs | 77 ++++- crates/victory-shader/src/emit/mod.rs | 2 + 3 files changed, 344 insertions(+), 4 deletions(-) create mode 100644 crates/victory-shader/src/emit/image_atomic_tests.rs diff --git a/crates/victory-shader/src/emit/image_atomic_tests.rs b/crates/victory-shader/src/emit/image_atomic_tests.rs new file mode 100644 index 0000000..0be8ed7 --- /dev/null +++ b/crates/victory-shader/src/emit/image_atomic_tests.rs @@ -0,0 +1,269 @@ +//! End-to-end tests of the image atomics DXIL has no operation for +//! (`image_atomic_inc`, `_dec`, `_fcmpswap`, `_fmin`, `_fmax`): synthetic +//! GFX10 compute shaders lowered to DXIL, validated by `dxil.dll` when +//! present, and run on the host GPU and WARP against RDNA2's definitions. + +use super::host::{Dispatch, Host, Root, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// SOP1 `s_mov_b32 sdst, src0`. +const fn s_mov_b32(sdst: u8, src0: u8) -> u32 { + 0xBE80_0000 | (sdst as u32) << 16 | 0x03 << 8 | src0 as u32 +} + +/// SMEM `s_load_dwordx{4,8} s[dst:..], s[base:base+1], byte_off` (soffset = null). +const fn s_load(op: u8, dst: u8, base: u8, byte_off: u32) -> [u32; 2] { + [ + 0x3D << 26 | (op as u32) << 18 | (dst as u32) << 6 | (base as u32 >> 1), + 125 << 25 | byte_off, + ] +} + +/// VOP1 `v_mov_b32 vdst, src0` (`src0`: 0..105 = SGPR, 128 = 0, 256.. = VGPR). +const fn v_mov_b32(vdst: u8, src0: u16) -> u32 { + 0x7E00_0000 | (vdst as u32) << 17 | 0x001 << 9 | (src0 as u32 & 0x1FF) +} + +/// MIMG `op vdata, vaddr[2], s[srsrc:srsrc+7] dmask dim:2D [glc]`. +const fn mimg(op: u8, vdata: u8, vaddr: u8, srsrc: u8, dmask: u8, glc: bool) -> [u32; 2] { + [ + 0x3C << 26 | ((op as u32) & 0x7F) << 18 | (glc as u32) << 13 | (dmask as u32) << 8 | 1 << 3, + (srsrc as u32 >> 2) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] +} + +/// MUBUF `buffer_store_dword vdata, off, s[srsrc:srsrc+3], 0`. +const fn buffer_store_dword(vdata: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8, + ] +} + +const IMAGE_ATOMIC_SWAP: u8 = 0x0F; + +/// A one-thread compute shader: root constants `s0..s3` are (start, data, +/// compare, 0). It swaps `start` into texel (0, 0) of the R32_UINT texture +/// at heap index 1, runs `op` there with glc and the data (and compare, for +/// the two-dword forms), and stores the returned old value to dword 0 of +/// the raw UAV at heap index 0. +fn build(op: u8, pair: bool) -> HostShader { + let mut words = vec![s_mov_b32(5, 0x80)]; // s[4:5]: the table at 0 + words.extend(s_load(0x02, 8, 4, 0)); // the raw UAV + words.extend(s_load(0x03, 16, 4, 32)); // the texture + for i in 0..4u8 { + words.push(v_mov_b32(i + 1, u16::from(i))); // v1..v4 = s0..s3 + } + words.push(v_mov_b32(5, 128)); // x = 0 + words.push(v_mov_b32(6, 128)); // y = 0 + words.push(v_mov_b32(7, 256 + 1)); // the start value + words.extend(mimg(IMAGE_ATOMIC_SWAP, 7, 5, 16, 1, false)); + words.push(v_mov_b32(8, 256 + 2)); // data + words.push(v_mov_b32(9, 256 + 3)); // compare + words.extend(mimg(op, 8, 5, 16, if pair { 3 } else { 1 }, true)); + words.extend(buffer_store_dword(8, 8)); + words.push(S_ENDPGM); + + let used = |kind, table_offset_dwords, dwords| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: table_offset_dwords / 8, + stride: 0, + dwords, + user_data: 4, + slot: 1, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 12, + 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![used(ResourceType::Uav, 0, 4), used(ResourceType::Uav, 8, 8)], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + 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).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 lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + shader +} + +/// Runs `op` for each (start, data, compare) and checks the old value it +/// returns and the texel it leaves against `want(start, data, compare)`. +fn check(name: &str, op: u8, pair: bool, cases: &[[u32; 3]], want: impl Fn(u32, u32, u32) -> u32) { + let shader = build(op, pair); + 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}")); + for &[start, data, compare] in cases { + 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) => [start, data, compare, 0][u.dword as usize], + (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(1), View::UintTextureUav(1, 1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + let (old, texel) = (out[0][0], out[1][0]); + let expect = want(start, data, compare); + assert_eq!( + (old, texel), + (start, expect), + "{label}: {name}({start:#010x}, data {data:#010x}, compare {compare:#010x}) \ + returned {old:#010x} and left {texel:#010x}, want {start:#010x} and {expect:#010x}", + ); + } + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} + +#[test] +fn image_atomic_inc_wraps_at_the_data() { + let cases = [ + [0, 5, 0], + [4, 5, 0], + [5, 5, 0], + [9, 5, 0], + [7, 0, 0], + [u32::MAX - 1, u32::MAX, 0], + ]; + check("image_atomic_inc", 0x1B, false, &cases, |old, data, _| { + if old >= data { 0 } else { old + 1 } + }); +} + +#[test] +fn image_atomic_dec_reloads_at_zero_or_above_the_data() { + let cases = [ + [5, 9, 0], + [1, 9, 0], + [0, 9, 0], + [12, 9, 0], + [9, 9, 0], + [0, 0, 0], + ]; + check("image_atomic_dec", 0x1C, false, &cases, |old, data, _| { + if old == 0 || old > data { + data + } else { + old - 1 + } + }); +} + +#[test] +fn image_atomic_fcmpswap_compares_as_floats() { + let f = f32::to_bits; + let nan = 0x7FC0_0000; + let cases = [ + [f(1.5), f(7.0), f(1.5)], // equal: swapped + [f(1.5), f(7.0), f(2.5)], // unequal: kept + [0x8000_0000, f(3.0), 0], // -0 equals +0 + [nan, f(3.0), nan], // NaN equals nothing + ]; + check( + "image_atomic_fcmpswap", + 0x1D, + true, + &cases, + |old, data, compare| { + if f32::from_bits(old) == f32::from_bits(compare) { + data + } else { + old + } + }, + ); +} + +#[test] +fn image_atomic_fmin_and_fmax_keep_the_smaller_and_larger() { + let f = f32::to_bits; + let cases = [ + [f(2.0), f(-3.5), 0], + [f(-3.5), f(2.0), 0], + [f(1.0), f(1.0), 0], + [f(-0.5), f(-0.25), 0], + ]; + let pick = |min: bool| { + move |old: u32, data: u32, _| { + let (o, d) = (f32::from_bits(old), f32::from_bits(data)); + f32::to_bits(if min { d.min(o) } else { d.max(o) }) + } + }; + check("image_atomic_fmin", 0x1E, false, &cases, pick(true)); + check("image_atomic_fmax", 0x1F, false, &cases, pick(false)); +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 211da17..c0158a6 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -336,6 +336,10 @@ fn unsupported(offset: usize, what: Why) -> Stop { Stop::Fail(ShaderError::Unsupported { offset, what }) } +/// The image atomics made by [`Lower::atomic_loop`], in place of a DXIL +/// atomic operation code. +const ATOMIC_LOOP: u32 = u32::MAX - 1; + impl<'a> Lower<'a> { fn new(x: &'a Parts<'a>, bad: &'a HashMap) -> Self { let p = x.p; @@ -1849,6 +1853,66 @@ impl<'a> Lower<'a> { .collect() } + /// An image atomic DXIL has no operation for (`inc`, `dec`, `fcmpswap`, + /// `fmin`, `fmax`), on the dword at `coords` of the 32-bit integer view + /// `h`: a compare-and-swap loop from a first guess of 0, until the + /// exchange finds the value the new one was made from (a null view reads + /// 0, so it leaves at once). `vals`: the data (fcmpswap: new, compare). + /// Returns the old value. + fn atomic_loop(&mut self, h: V, coords: &[V], op: &str, vals: &[V]) -> V { + let i32t = self.s.t.i32; + let entry = self.cur; + let (head, done) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(entry, Term::Br(head)); + self.cur = head; + let old = self.s.m.phi(head, i32t); + let (data, zero, one) = (vals[0], self.s.m.i32(0), self.s.m.i32(1)); + let new = match op { + // old >= data ? 0 : old + 1 + "inc" => { + let up = self.s.m.bin(head, Bin::Add, old, one); + let wrap = self.s.m.cmp(head, pred::IUGE, old, data); + self.s.m.select(head, wrap, zero, up) + } + // old == 0 || old > data ? data : old - 1 + "dec" => { + let down = self.s.m.bin(head, Bin::Sub, old, one); + let empty = self.s.m.cmp(head, pred::EQ, old, zero); + let over = self.s.m.cmp(head, pred::IUGT, old, data); + let reload = self.s.m.bin(head, Bin::Or, empty, over); + self.s.m.select(head, reload, data, down) + } + // A float compare: -0 matches +0, NaN matches nothing. + "fcmpswap" => { + let (o, c) = (self.as_float(old), self.as_float(vals[1])); + let eq = self.s.m.cmp(head, pred::OEQ, o, c); + self.s.m.select(head, eq, data, old) + } + // As v_min_f32 and v_max_f32. + _ => { + let (d, o) = (self.as_float(data), self.as_float(old)); + let m = self.binary(if op == "fmax" { 35 } else { 36 }, d, o); + self.as_int(m) + } + }; + let mut args = vec![h]; + args.extend_from_slice(coords); + args.extend([old, new]); + let prev = self.s.op( + head, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &args, + ); + let found = self.s.m.cmp(head, pred::EQ, prev, old); + self.s.m.terminate(head, Term::CondBr(found, done, head)); + self.s.m.set_phi(old, vec![(zero, entry), (prev, head)]); + self.cur = done; + prev + } + /// Code that depends on the lane layout: wave operations, and in compute /// the console's wave size (lanes are thread ids in group order there). /// Pixel lanes match only within a quad. @@ -5499,6 +5563,8 @@ impl<'a> Lower<'a> { "umax" => 7, "swap" => 8, "cmpswap" => u32::MAX, + // No DXIL operation: a compare-and-swap loop (`atomic_loop`). + "inc" | "dec" | "fcmpswap" | "fmin" | "fmax" => ATOMIC_LOOP, _ => return Err(name), }; let Fields::Image { cache, .. } = &inst.fields else { @@ -5507,10 +5573,11 @@ impl<'a> Lower<'a> { if *d16 || *a16 { return Err("a 16-bit image atomic"); } - // dmask: the data dwords (cmpswap: twice the value's). + // dmask: the data dwords (the compare-and-swaps: twice the value's). // shortcut: 64-bit image atomics (two dwords, an R32G32 view) // need the host's 64-bit typed atomics; they stop the program. - if *dmask != if code == u32::MAX { 3 } else { 1 } { + let pair = matches!(op, "cmpswap" | "fcmpswap"); + if *dmask != if pair { 3 } else { 1 } { return Err("a 64-bit image atomic"); } let iu = self.s.m.undef(self.s.t.i32); @@ -5521,7 +5588,7 @@ impl<'a> Lower<'a> { let Operand::Vector { reg, .. } = *data else { return Err("image atomic data"); }; - let vals = self.vgprs(inst, data, if code == u32::MAX { 2 } else { 1 })?; + let vals = self.vgprs(inst, data, if pair { 2 } else { 1 })?; let mut value = vals[0]; if op == "sub" { let z = self.s.m.i32(0); @@ -5535,7 +5602,9 @@ impl<'a> Lower<'a> { let at = self.begin_guarded(guard); let i32t = self.s.t.i32; let mut args = vec![h]; - let r = if code == u32::MAX { + let r = if code == ATOMIC_LOOP { + self.atomic_loop(h, &cs, op, &vals) + } else if code == u32::MAX { // cmpswap: data is (new, compare). args.extend(cs); args.extend([vals[1], vals[0]]); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 6c668f3..f6a5e6a 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -81,6 +81,8 @@ mod container; mod diff_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; +#[cfg(all(test, windows))] +mod image_atomic_tests; mod lower; mod sampler; mod shader; From 95f5672a68d53fbd7220667c7941bd282d6dd027 Mon Sep 17 00:00:00 2001 From: THE-PRO-GAME <171867920+THE-PRO-GAME@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:21:38 +0100 Subject: [PATCH 02/25] Fix signed scalar overflow flags in compute shaders Set SCC for S_ADD_I32, S_SUB_I32, and S_ADDK_I32 from the signs of their inputs and wrapping result. Exercise branches that consume SCC and compare GPU readback against signed arithmetic. --- crates/victory-shader/src/emit/lower.rs | 35 +++++++---- crates/victory-shader/src/emit/valu_tests.rs | 64 ++++++++++++++++++++ 2 files changed, 88 insertions(+), 11 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..f8a8534 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2566,7 +2566,7 @@ impl<'a> Lower<'a> { } let m = &mut self.s.m; let _ = m; - let (r, carry): (V, Option) = match name { + let (r, scc_value): (V, Option) = match name { "s_mov_b32" => (src32(self, 0)?, None), "s_movk_i32" => (sext16(self), None), "s_cselect_b32" => { @@ -2594,18 +2594,22 @@ impl<'a> Lower<'a> { src32(self, 1)? }; let r = self.s.m.bin(c, Bin::Add, a, b); - let carry = if name == "s_add_u32" { - Some(self.s.m.cmp(c, pred::IULT, r, a)) + let flag = if name == "s_add_u32" { + self.s.m.cmp(c, pred::IULT, r, a) } else { - None + self.signed_overflow(c, a, b, r, false) }; - (r, carry) + (r, Some(flag)) } "s_sub_u32" | "s_sub_i32" => { let (a, b) = (src32(self, 0)?, src32(self, 1)?); let r = self.s.m.bin(c, Bin::Sub, a, b); - let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b)); - (r, carry) + let flag = if name == "s_sub_u32" { + self.s.m.cmp(c, pred::IULT, a, b) + } else { + self.signed_overflow(c, a, b, r, true) + }; + (r, Some(flag)) } "s_addc_u32" | "s_subb_u32" => { let (a, b) = (src32(self, 0)?, src32(self, 1)?); @@ -2735,7 +2739,7 @@ impl<'a> Lower<'a> { }; self.set(lo, Val::I32(r)); if let Some(scc) = scc { - let val = match carry { + let val = match scc_value { Some(k) => Val::Bit(k), None if matches!( name, @@ -2749,9 +2753,6 @@ impl<'a> Lower<'a> { { return Ok(()); } - None if name.starts_with("s_add") || name.starts_with("s_sub") => { - Val::Missing("the carry of a scalar operation") - } None => { let z = self.s.m.i32(0); Val::Bit(self.s.m.cmp(c, pred::NE, r, z)) @@ -2762,6 +2763,18 @@ impl<'a> Lower<'a> { Ok(()) } + /// RDNA2 sets SCC on signed overflow. The result changes the first + /// operand's sign when matching signs are added or opposite signs are + /// subtracted. Test the sign bit of both XORs without widening. + fn signed_overflow(&mut self, c: usize, a: V, b: V, result: V, subtract: bool) -> V { + let m = &mut self.s.m; + let sign_change = m.bin(c, Bin::Xor, a, result); + let sign_check = m.bin(c, Bin::Xor, if subtract { a } else { result }, b); + let overflow_bits = m.bin(c, Bin::And, sign_change, sign_check); + let zero = m.i32(0); + m.cmp(c, pred::SLT, overflow_bits, zero) + } + /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the /// scalar and vector add-with-carry instructions set it. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option) -> (V, V) { diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..4936376 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -212,6 +212,70 @@ fn run_cases( assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); } +fn run_signed_scc_cases( + name: &str, + body: &[u32], + operands: &[(i32, i32)], + reference: impl Fn(i32, i32) -> (i32, bool), +) { + let mut words = body.to_vec(); + words.extend([ + 0xBF85_0001, // s_cbranch_scc1 over the next instruction + s_mov_b32(2, 0x80), // s2 = 0 when SCC is clear + sop2(0x12, 7, 6, 2), // s_xor_b32 s7, s6, s2 + vop1(0x001, 0, sgpr(7)), // v_mov_b32 v0, s7 + ]); + let shader = build_valu_cs(&words); + // First read the arithmetic result unchanged, then toggle its high bit + // only when SCC is set. This checks both outputs with the single-dword UAV. + let inputs: Vec<_> = operands + .iter() + .flat_map(|&(a, b)| [[a as u32, b as u32, 0, 0], [a as u32, b as u32, 1 << 31, 0]]) + .collect(); + run_cases(&shader, &inputs, |backend, _, [a, b, mask, _], got| { + let (result, overflow) = reference(a as i32, b as i32); + let expected = result as u32 ^ if overflow { mask } else { 0 }; + assert_eq!( + got, expected, + "{backend}: {name}({:#010x}, {:#010x}), SCC mask {mask:#010x}", + a, b, + ); + }); +} + +#[test] +fn scalar_add_i32_scc_controls_branch() { + run_signed_scc_cases( + "s_add_i32", + &[sop2(0x02, 6, 0, 1)], + &[(i32::MAX, 1), (i32::MIN, -1), (-1, 1), (8, 5)], + i32::overflowing_add, + ); +} + +#[test] +fn scalar_sub_i32_scc_controls_branch() { + run_signed_scc_cases( + "s_sub_i32", + &[sop2(0x03, 6, 0, 1)], + &[(i32::MIN, 1), (i32::MAX, -1), (0, 1), (-8, -3)], + i32::overflowing_sub, + ); +} + +#[test] +fn scalar_addk_i32_scc_controls_branch() { + for imm in [-1i16, 1] { + let addk_s6 = 0xB000_0000 | 0x0F << 23 | 6 << 16 | u32::from(imm as u16); + run_signed_scc_cases( + "s_addk_i32", + &[s_mov_b32(6, 0), addk_s6], + &[(i32::MIN, 0), (i32::MAX, 0), (-1, 0), (8, 0)], + |a, _| a.overflowing_add(i32::from(imm)), + ); + } +} + fn is_f16_nan(bits: u16) -> bool { (bits & 0x7FFF) > 0x7C00 } From a793ad86a83bea3fc024df95ff4150d736e71896 Mon Sep 17 00:00:00 2001 From: bartikele Date: Tue, 24 Nov 2026 16:21:39 +0100 Subject: [PATCH 03/25] victory-shader: lower all-zero and all-one constant lane masks --- crates/victory-shader/src/emit/lower.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..425a370 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1634,6 +1634,10 @@ impl<'a> Lower<'a> { let hi = hi.map(word).transpose()?; Ok(self.lane_bit(at, lo, hi)) } + Atom::Constant(0) => Ok(self.s.m.bool(false)), + Atom::Constant(k) if k == u64::MAX || (!self.x.native.wave64 && k as u32 == u32::MAX) => { + Ok(self.s.m.bool(true)) + } Atom::Constant(k) if self.console_lanes => { let lo = self.s.m.i32(k as u32); let hi = self.s.m.i32((k >> 32) as u32); From 59ab6b736af3037780f46b706ddce67362c26448 Mon Sep 17 00:00:00 2001 From: THE-PRO-GAME <171867920+THE-PRO-GAME@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:21:43 +0100 Subject: [PATCH 04/25] Preserve DATA0 when paired LDS write offsets match Emit one store element for equal-offset DS_WRITE2 and DS_WRITE2ST64. Exercise 32-bit and 64-bit stores with equal and distinct offsets through compute dispatch and readback. --- crates/victory-shader/src/emit/lower.rs | 7 +- crates/victory-shader/src/emit/valu_tests.rs | 118 +++++++++++++++++-- 2 files changed, 117 insertions(+), 8 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index f8a8534..e3a5bb2 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2180,7 +2180,12 @@ impl<'a> Lower<'a> { } if let Some(rest) = name.strip_prefix("ds_write") { let elements = if rest.starts_with('2') { - pair(name) + let mut elements = pair(name); + // Equal offsets perform one write with DATA0 (RDNA 2 ISA §10.4.3). + if offset0 == offset1 { + elements.truncate(1); + } + elements } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { vec![(offset, width(name))] } else { diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 4936376..f97d796 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -69,6 +69,17 @@ const fn vgpr(n: u8) -> u16 { /// 4 dwords of root constants in `s0..s3`, runs `body` (leaving its result in /// `v0`), and stores `v0` to dword 0 of the raw UAV at heap index 0. fn build_valu_cs(body: &[u32]) -> HostShader { + build_test_cs( + body, + ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }, + &buffer_store_dword(0, 8, 0), + ) +} + +fn build_test_cs(body: &[u32], compute: ComputeIo, result_store: &[u32]) -> HostShader { 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 @@ -79,7 +90,7 @@ fn build_valu_cs(body: &[u32]) -> HostShader { 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.extend_from_slice(result_store); words.push(S_ENDPGM); let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); @@ -115,10 +126,7 @@ fn build_valu_cs(body: &[u32]) -> HostShader { user_data: 4, slot: 1, }], - io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 - threads: [1, 1, 1], - }), + io: StageIo::Cs(compute), code, }; @@ -173,6 +181,17 @@ fn run_cases( shader: &HostShader, cases: &[[u32; 4]], mut check: impl FnMut(&str, usize, [u32; 4], u32), +) { + run_output_cases(shader, cases, 1, |backend, i, inputs, out| { + check(backend, i, inputs, out[0]); + }); +} + +fn run_output_cases( + shader: &HostShader, + cases: &[[u32; 4]], + output_dwords: u32, + mut check: impl FnMut(&str, usize, [u32; 4], &[u32]), ) { let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; @@ -199,13 +218,13 @@ fn run_cases( &pso, &Dispatch { roots: vec![(0, Root::Constants(ud))], - views: &[View::RawUav(1)], + views: &[View::RawUav(output_dwords)], samplers: &[], groups: [1, 1, 1], }, ) .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - check(label, i, inputs, out[0][0]); + check(label, i, inputs, &out[0]); } ran += 1; } @@ -1001,3 +1020,88 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +fn check_lds_paired_write(name: &str, write_op: u32, width: usize, stride64: bool) { + const LANES: u32 = 64; + const DWORDS_PER_LANE: usize = 4; + const WAIT_LDS: u32 = 0xBF8C_C07F; // s_waitcnt lgkmcnt(0) + let inputs = [0x1234_5678, 0x9ABC_DEF0, 0x0BAD_F00D, 0xFEED_BEEF]; + let read_op = if width == 1 { 0x36 } else { 0x76 }; + let scale = 4 * width as u32 * if stride64 { 64 } else { 1 }; + let data1 = 1 + width as u32; + for same_offset in [false, true] { + // Each lane starts at its own aligned 16-byte offset. Use a + // separation of at least 1024 bytes for the st64 accesses. + let distinct_offset = if stride64 { 6 } else { 3 }; + let offsets = [2, if same_offset { 2 } else { distinct_offset }]; + let mut body = Vec::from(vop3(0x11A, 0, 132, vgpr(0), 0)); // v0 = thread id << 4 + body.extend([ + 0x36 << 26 | write_op << 18 | offsets[0] | offsets[1] << 8, + 1 << 8 | data1 << 16, // Address = v0, DATA0 = v1, DATA1 = v2 or v3. + WAIT_LDS, + ]); + for (element, &offset) in offsets.iter().enumerate() { + body.extend([ + 0x36 << 26 | read_op << 18 | (offset * scale), + 5 << 24, + WAIT_LDS, + ]); + let [mut store, operands] = buffer_store_dword(5, 8, 8 * element as u16); + store |= 1 << 12; // offen: v0 is the per-lane byte offset. + if width == 2 { + store |= 1 << 18; // buffer_store_dwordx2 + } + body.extend([store, operands]); + } + let shader = build_test_cs( + &body, + ComputeIo { + rsrc2: (5 << 1) | (8 << 15), // 5 user SGPRs, 4096 bytes of LDS. + threads: [LANES, 1, 1], + }, + &[], + ); + run_output_cases( + &shader, + &[inputs], + LANES * DWORDS_PER_LANE as u32, + |backend, _, _, out| { + let second = if same_offset { 0 } else { width }; + assert_eq!(out.len(), LANES as usize * DWORDS_PER_LANE); + let (lanes, _) = out.as_chunks::(); + for (lane, values) in lanes.iter().enumerate() { + assert_eq!( + &values[..width], + &inputs[..width], + "{backend}: {name}, offsets {offsets:?}, lane {lane}, DATA0" + ); + assert_eq!( + &values[2..2 + width], + &inputs[second..second + width], + "{backend}: {name}, offsets {offsets:?}, lane {lane}, second value" + ); + } + }, + ); + } +} + +#[test] +fn paired_lds_write2_b32() { + check_lds_paired_write("ds_write2_b32", 0x0E, 1, false); +} + +#[test] +fn paired_lds_write2st64_b32() { + check_lds_paired_write("ds_write2st64_b32", 0x0F, 1, true); +} + +#[test] +fn paired_lds_write2_b64() { + check_lds_paired_write("ds_write2_b64", 0x4E, 2, false); +} + +#[test] +fn paired_lds_write2st64_b64() { + check_lds_paired_write("ds_write2st64_b64", 0x4F, 2, true); +} From 0b7067fb6debaffd716d1676ac837b19503f6945 Mon Sep 17 00:00:00 2001 From: Tarcisio Date: Tue, 24 Nov 2026 12:39:28 -0300 Subject: [PATCH 05/25] Shaders: lower constant 64-bit integer compares without INT64 --- crates/victory-shader/src/emit/lower.rs | 59 +++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..5fa3b3f 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5366,6 +5366,10 @@ impl<'a> Lower<'a> { } } "u64" | "i64" => { + if matches!(op, "f" | "t") { + self.lane(inst, Some(op == "t")); + return Ok(()); + } let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?); let signed = ty == "i64"; let p = match op { @@ -7418,4 +7422,59 @@ mod tests { // A 16-bit float is a half already, sign included. assert_eq!(half(0xBC00 << half_shift(16)), -1.0); } + + #[test] + fn constant_64_bit_compares_lower_without_int64() { + for (vopc, branch) in [ + (0x7DC0_0080u32, 0xBF86_0001u32), // v_cmp_f_u64 vcc, ...; s_cbranch_vccnz + (0x7D4E_0080, 0xBF86_0001), // v_cmp_t_i64 vcc, ...; s_cbranch_vccnz + (0x7DE0_0080, 0xBF89_0001), // v_cmpx_f_u64 exec, ...; s_cbranch_execnz + (0x7D6E_0080, 0xBF89_0001), // v_cmpx_t_i64 exec, ...; s_cbranch_execnz + ] { + let words = [ + 0x7E00_0280u32, // v_mov_b32 v0, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + vopc, + branch, + 0xBE80_0380, // s_mov_b32 s0, 0 + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 2, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 2).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 emitted = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .unwrap(); + let sfi0 = crate::dxbc::Container::parse(&emitted.dxil) + .unwrap() + .part(crate::dxbc::FourCC::SFI0) + .unwrap() + .data; + let features = u64::from_le_bytes(sfi0.try_into().unwrap()); + assert_eq!(features & 0x8000, 0, "unexpected INT64 feature bit"); + } + } } From 0199cdb68ea418943e5ff5f7985d6a4da4a4a06c Mon Sep 17 00:00:00 2001 From: mgunes1311-lab Date: Tue, 24 Nov 2026 18:40:34 +0300 Subject: [PATCH 06/25] Shaders: track comparison flag per immediate sampler in Shader --- crates/victory-shader/src/emit/shader.rs | 31 ++++++++++-------------- 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index dd2eb75..c12b44f 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -57,10 +57,9 @@ pub(crate) struct Shader { pub mesh: Option, /// Dwords of user data the shader reads (0: no user-data buffer). pub user_data: u32, - /// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`]. - pub samplers: u32, - /// Bit n: immediate sampler n is a comparison sampler. - pub cmp_samplers: u64, + /// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`]: `true` when + /// the sampler is a comparison sampler. + pub samplers: Vec, /// Root CBVs read, by root parameter index, with their handles. pub root_cbvs: Vec<(u8, V)>, /// Root SRVs (raw buffers) read, likewise. @@ -116,8 +115,7 @@ impl Shader { prims: Vec::new(), mesh: None, user_data: 0, - samplers: 0, - cmp_samplers: 0, + samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), flags: 0, @@ -236,9 +234,9 @@ impl Shader { h } - /// The handle of immediate sampler `n` (a comparison sampler when its - /// bit in `cmp_samplers` is set). - pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { + /// The handle of immediate sampler `n` (a comparison sampler when + /// `comparison` is set). + pub fn sampler_handle(&mut self, block: usize, n: u32, comparison: bool) -> V { let bind = [ self.m.i32(n), self.m.i32(n), @@ -255,11 +253,7 @@ impl Shader { 217, &[bind, i, f], ); - let cmp = if self.cmp_samplers >> n & 1 != 0 { - 0x8000 - } else { - 0 - }; + let cmp = if comparison { 0x8000 } else { 0 }; self.annotate(block, h, 14 | cmp, 0) } @@ -315,7 +309,7 @@ impl Shader { s.m.md_value(c) }; if self.user_data > 0 - || self.samplers > 0 + || !self.samplers.is_empty() || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() { @@ -402,13 +396,14 @@ impl Shader { srvs = Some(self.m.md_node(list)); } let mut samplers = None; - if self.samplers > 0 { + if !self.samplers.is_empty() { let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]); let p = self.m.ptr(ty); let u = self.m.undef(p); let mut list = Vec::new(); - for n in 0..self.samplers { - let kind = (self.cmp_samplers >> n & 1) as u32; + for n in 0..self.samplers.len() { + let kind = u32::from(self.samplers[n]); + let n = n as u32; let ops = vec![ Some(i32c(&mut self, n)), Some(self.m.md_value(u)), From d25783b8d87dea346cccd4f8aff90d6dd75f9258 Mon Sep 17 00:00:00 2001 From: ESAT Date: Tue, 24 Nov 2026 18:41:31 +0300 Subject: [PATCH 07/25] Shaders: compute signed overflow SCC for s_add_i32, s_addk_i32, and s_sub_i32 AI-generated & verified with Gemini 4 Neon (not written by a human engineer). s_add_i32, s_addk_i32, and s_sub_i32 previously left SCC as Val::Missing("the carry of a scalar operation"), causing any shader that reads SCC after these instructions (e.g. via s_cselect_b32 or s_cbranch_scc*) to fail lowering. Compute 32-bit two's-complement signed overflow directly in i32 (no i64 capability required), matching the AMD RDNA2 ISA: - s_add_i32 / s_addk_i32: ((a ^ r) & (b ^ r)) --- crates/victory-shader/src/emit/lower.rs | 24 +++- crates/victory-shader/src/emit/valu_tests.rs | 113 +++++++++++++++++++ 2 files changed, 132 insertions(+), 5 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..c751db6 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2595,17 +2595,31 @@ impl<'a> Lower<'a> { }; let r = self.s.m.bin(c, Bin::Add, a, b); let carry = if name == "s_add_u32" { - Some(self.s.m.cmp(c, pred::IULT, r, a)) + self.s.m.cmp(c, pred::IULT, r, a) } else { - None + // Signed overflow: a and b share a sign bit that r flips. + let ar = self.s.m.bin(c, Bin::Xor, a, r); + let br = self.s.m.bin(c, Bin::Xor, b, r); + let ov = self.s.m.bin(c, Bin::And, ar, br); + let z = self.s.m.i32(0); + self.s.m.cmp(c, pred::SLT, ov, z) }; - (r, carry) + (r, Some(carry)) } "s_sub_u32" | "s_sub_i32" => { let (a, b) = (src32(self, 0)?, src32(self, 1)?); let r = self.s.m.bin(c, Bin::Sub, a, b); - let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b)); - (r, carry) + let carry = if name == "s_sub_u32" { + self.s.m.cmp(c, pred::IULT, a, b) + } else { + // Signed overflow: a and b have opposite signs and r flips a's sign. + let ab = self.s.m.bin(c, Bin::Xor, a, b); + let ar = self.s.m.bin(c, Bin::Xor, a, r); + let ov = self.s.m.bin(c, Bin::And, ab, ar); + let z = self.s.m.i32(0); + self.s.m.cmp(c, pred::SLT, ov, z) + }; + (r, Some(carry)) } "s_addc_u32" | "s_subb_u32" => { let (a, b) = (src32(self, 0)?, src32(self, 1)?); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..bca2793 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -937,3 +937,116 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +/// SOPK `op sdst, simm16`. +const fn sopk(op: u8, sdst: u8, simm16: i16) -> u32 { + 0xB000_0000 | (op as u32 & 0x1F) << 23 | (sdst as u32 & 0x7F) << 16 | (simm16 as u16) as u32 +} + +#[test] +fn signed_scalar_add_sub_scc_matches_rdna2() { + // s_add_i32 s6, s0, s1 (SOP2 0x02); s_cselect_b32 s7, 1, 0 (SOP2 0x0A); v_mov_b32 v0, s7 + let add_scc = build_valu_cs(&[ + sop2(0x02, 6, 0, 1), + sop2(0x0A, 7, 0x81, 0x80), + vop1(0x001, 0, sgpr(7)), + ]); + // s_sub_i32 s6, s0, s1 (SOP2 0x03); s_cselect_b32 s7, 1, 0; v_mov_b32 v0, s7 + let sub_scc = build_valu_cs(&[ + sop2(0x03, 6, 0, 1), + sop2(0x0A, 7, 0x81, 0x80), + vop1(0x001, 0, sgpr(7)), + ]); + // s_mov_b32 s6, s0; s_addk_i32 s6, +1 (SOPK 0x0F); s_cselect_b32 s7, 1, 0; v_mov_b32 v0, s7 + let addk_pos1 = build_valu_cs(&[ + s_mov_b32(6, 0), + sopk(0x0F, 6, 1), + sop2(0x0A, 7, 0x81, 0x80), + vop1(0x001, 0, sgpr(7)), + ]); + // s_mov_b32 s6, s0; s_addk_i32 s6, -32768 (SOPK 0x0F); s_cselect_b32 s7, 1, 0; v_mov_b32 v0, s7 + let addk_neg_min = build_valu_cs(&[ + s_mov_b32(6, 0), + sopk(0x0F, 6, i16::MIN), + sop2(0x0A, 7, 0x81, 0x80), + vop1(0x001, 0, sgpr(7)), + ]); + + let add_cases: &[(i32, i32)] = &[ + (0, 0), + (10, 20), + (-1, 1), // unsigned carry, no signed overflow + (i32::MAX, 0), + (i32::MAX, 1), // positive overflow + (i32::MAX, i32::MAX), // positive overflow + (i32::MIN, 0), + (i32::MIN, -1), // negative overflow + (i32::MIN, i32::MIN), // negative overflow (result 0) + (i32::MIN, i32::MAX), // -1, no overflow + ]; + let add_in: Vec<[u32; 4]> = add_cases + .iter() + .map(|&(a, b)| [a as u32, b as u32, 0, 0]) + .collect(); + run_cases(&add_scc, &add_in, |backend, i, _, got| { + let (a, b) = add_cases[i]; + let want = u32::from(a.overflowing_add(b).1); + assert_eq!( + got, want, + "{backend}: s_add_i32({a}, {b}) SCC = {got}, want {want}", + ); + }); + + let sub_cases: &[(i32, i32)] = &[ + (0, 0), + (0, 1), // unsigned borrow, no signed overflow + (0, i32::MIN), // 0 - (-2^31) overflows i32 + (i32::MIN, 0), + (i32::MIN, 1), // negative overflow + (i32::MIN, i32::MIN), // 0, no overflow + (i32::MAX, -1), // positive overflow + (i32::MAX, i32::MIN), // positive overflow + (-5, -3), // -2, no overflow + (-1, i32::MAX), // -2^31 (i32::MIN), no overflow + ]; + let sub_in: Vec<[u32; 4]> = sub_cases + .iter() + .map(|&(a, b)| [a as u32, b as u32, 0, 0]) + .collect(); + run_cases(&sub_scc, &sub_in, |backend, i, _, got| { + let (a, b) = sub_cases[i]; + let want = u32::from(a.overflowing_sub(b).1); + assert_eq!( + got, want, + "{backend}: s_sub_i32({a}, {b}) SCC = {got}, want {want}", + ); + }); + + let addk_pos_cases: &[i32] = &[0, -1, i32::MAX - 1, i32::MAX, i32::MIN]; + let addk_pos_in: Vec<[u32; 4]> = addk_pos_cases + .iter() + .map(|&a| [a as u32, 0, 0, 0]) + .collect(); + run_cases(&addk_pos1, &addk_pos_in, |backend, i, _, got| { + let a = addk_pos_cases[i]; + let want = u32::from(a.overflowing_add(1).1); + assert_eq!( + got, want, + "{backend}: s_addk_i32({a}, +1) SCC = {got}, want {want}", + ); + }); + + let addk_neg_cases: &[i32] = &[0, i32::MAX, i32::MIN + 32768, i32::MIN + 32767, i32::MIN]; + let addk_neg_in: Vec<[u32; 4]> = addk_neg_cases + .iter() + .map(|&a| [a as u32, 0, 0, 0]) + .collect(); + run_cases(&addk_neg_min, &addk_neg_in, |backend, i, _, got| { + let a = addk_neg_cases[i]; + let want = u32::from(a.overflowing_add(i32::from(i16::MIN)).1); + assert_eq!( + got, want, + "{backend}: s_addk_i32({a}, -32768) SCC = {got}, want {want}", + ); + }); +} From 6dbbf1d953eef94fd7e200f2b1fff3b9d3fa2627 Mon Sep 17 00:00:00 2001 From: mgunes1311-lab Date: Tue, 24 Nov 2026 18:42:45 +0300 Subject: [PATCH 08/25] Shaders: build comparison static samplers safely and add tests --- crates/victory-shader/src/emit/mod.rs | 250 ++++++++++++++++++++++++-- 1 file changed, 238 insertions(+), 12 deletions(-) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 89652da..326df71 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -293,24 +293,29 @@ pub fn emit( stage: native.stage, dxil: l.dxil, user_data: l.user_data, - static_samplers: l - .samplers - .iter() - .enumerate() - .map(|(n, &w)| { - let mut s = StaticSampler::from_words(w); - if l.cmp_samplers >> n & 1 != 0 { - s.filter |= 0x80; - } - s - }) - .collect(), + static_samplers: build_static_samplers(&l.samplers, &l.cmp_samplers), samplers: l.samplers, root_cbvs: l.root_cbvs, root_srvs: l.root_srvs, }) } +fn build_static_samplers(samplers: &[[u32; 4]], cmp_samplers: &[bool]) -> Vec { + samplers + .iter() + .zip(cmp_samplers) + .map(|(&w, &cmp)| { + let mut s = StaticSampler::from_words(w); + if cmp { + // Comparison overrides the 2-bit D3D12_FILTER_REDUCTION_TYPE + // field (bits 7..8), rather than ORing onto MINIMUM (0x100 -> MAXIMUM). + s.filter = (s.filter & !0x180) | 0x80; + } + s + }) + .collect() +} + /// The rows of an `ISG1`/`OSG1` part. fn signature(part: &[u8]) -> Result, ShaderError> { use crate::dxbc::u32_at; @@ -746,4 +751,225 @@ mod tests { // Translated or refused with a reason; it must not panic. let _ = super::emit(&c, &native, &p, &st, &io, &res); } + + fn lower_immediate_sampler_cs(words: &[u32]) -> super::HostShader { + let table = crate::native::RootParam { + root: crate::native::RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }; + let range = |kind, table_offset_dwords, dwords| crate::native::UsedResource { + kind, + root: crate::native::RootType::Table, + table_offset_dwords, + lower_bound: 0, + stride: 0, + dwords, + user_data: 0, + slot: 0, + }; + let native = super::NativeProgram { + stage: super::HwStage::Cs, + wave64: false, + vgprs: 32, + layout: vec![table], + used: vec![ + range(crate::native::ResourceType::Srv, 0, 8), + range(crate::native::ResourceType::Uav, 8, 4), + ], + io: crate::native::StageIo::Cs(crate::native::ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = crate::structure::structure(&p).expect("structure"); + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)) + .expect("resource::track"); + let io = crate::io::raise(&p, &native).expect("io::raise"); + let l = super::lower::lower(&super::lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + let shader = super::HostShader { + stage: native.stage, + dxil: l.dxil, + user_data: l.user_data, + static_samplers: super::build_static_samplers(&l.samplers, &l.cmp_samplers), + samplers: l.samplers, + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + }; + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + shader + } + + fn dual_use_sampler_program(sampler: [u32; 4], cmp_first: bool) -> Vec { + let mut words = vec![ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xF408_0A02, + 0xFA00_0020, // s_load_dwordx4 s[40:43], s[4:5], 0x20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + ]; + for (i, w) in sampler.into_iter().enumerate() { + words.push(0xBE88_03FF | ((i as u32) << 16)); // s_mov_b32 s(8+i), lit32 + words.push(w); + } + let v_mov_lit = |dst: u32, lit: f32, out: &mut Vec| { + out.push(0x7E00_02FF | (dst << 17)); + out.push(lit.to_bits()); + }; + v_mov_lit(1, 0.25, &mut words); // ref1 = 0.25 (<= 0.5 -> 1.0) + v_mov_lit(2, 0.5, &mut words); + v_mov_lit(3, 0.5, &mut words); + v_mov_lit(4, 0.75, &mut words); // ref2 = 0.75 (> 0.5 -> 0.0) + v_mov_lit(5, 0.5, &mut words); + v_mov_lit(6, 0.5, &mut words); + words.push(0x7E20_0280); // v_mov_b32 v16, 0 + + let std_sample = [0xF09C_0108, 0x0043_0C02]; // image_sample_lz v12, v[2:3], s[12:19], s[8:11] + let cmp_sample_1 = [0xF0BC_0108, 0x0043_0D01]; // image_sample_c_lz v13, v[1:3], s[12:19], s[8:11] + let cmp_sample_2 = [0xF0BC_0108, 0x0043_0E04]; // image_sample_c_lz v14, v[4:6], s[12:19], s[8:11] + if cmp_first { + words.extend(cmp_sample_1); + words.extend(cmp_sample_2); + words.extend(std_sample); + } else { + words.extend(std_sample); + words.extend(cmp_sample_1); + words.extend(cmp_sample_2); + } + words.extend([ + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xE070_1004, + 0x800A_0D10, // buffer_store_dword v13, v16, s[40:43], 0 offen offset:4 + 0xE070_1008, + 0x800A_0E10, // buffer_store_dword v14, v16, s[40:43], 0 offen offset:8 + 0xBF81_0000, // s_endpgm + ]); + words + } + + #[test] + fn constant_sampler_used_with_and_without_comparison_splits_into_two_static_samplers() { + // Point clamp, comparison LESS_EQUAL (4). + let sampler = [0x3092u32, 0x00FF_F000, 0x0000_0000, 0x0000_0000]; + for cmp_first in [false, true] { + let shader = lower_immediate_sampler_cs(&dual_use_sampler_program(sampler, cmp_first)); + assert_eq!(shader.samplers, vec![sampler, sampler]); + assert_eq!(shader.static_samplers.len(), 2); + let filters: Vec = shader.static_samplers.iter().map(|s| s.filter).collect(); + let expected = if cmp_first { + vec![0x80, 0x00] + } else { + vec![0x00, 0x80] + }; + assert_eq!(filters, expected, "cmp_first={cmp_first}"); + + #[cfg(all(windows, feature = "host"))] + { + use super::host::{Dispatch, Host, Root, View}; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + // D3D12 leaves `SHADER_SAMPLE_COMPARISON` optional for RGBA32F on + // hardware; WARP implements it everywhere. + if let Ok(host) = Host::new(true) { + let texel = [[0.5f32, 0.0, 0.0, 1.0]]; + let views = [View::Texture(1, 1, &texel), View::RawUav(3)]; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("warp: compute_pipeline: {e}")); + let words = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(vec![0]))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("warp: dispatch: {e}")); + let got: Vec = words[0].iter().copied().map(f32::from_bits).collect(); + assert_eq!(got, vec![0.5, 1.0, 0.0], "warp cmp_first={cmp_first}"); + } + } + } + + // A MINIMUM reduction sampler (0x100) also used with comparison must + // become COMPARISON (0x80), not MAXIMUM (0x180). + let min_sampler = [0x2000_3092u32, 0x00FF_F000, 0x0000_0000, 0x0000_0000]; + let shader = lower_immediate_sampler_cs(&dual_use_sampler_program(min_sampler, false)); + let filters: Vec = shader.static_samplers.iter().map(|s| s.filter).collect(); + assert_eq!(filters, vec![0x100, 0x80]); + } + + #[test] + fn more_than_64_immediate_samplers_do_not_overflow() { + let mut words = vec![ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xF408_0A02, + 0xFA00_0020, // s_load_dwordx4 s[40:43], s[4:5], 0x20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0280, // v_mov_b32 v2, 0 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0x7E20_0280, // v_mov_b32 v16, 0 + ]; + for i in 0..66u32 { + // Vary MaxLOD across bits 12..23 cleanly without colliding with 1-bits. + let sampler = [0x3092u32, (i + 1) << 12, 0x0000_0000, 0x0000_0000]; + for (j, w) in sampler.into_iter().enumerate() { + words.push(0xBE88_03FF | ((j as u32) << 16)); + words.push(w); + } + if !i.is_multiple_of(2) { + words.extend([0xF0BC_0108, 0x0043_0C01]); // image_sample_c_lz v12, v[1:3], s[12:19], s[8:11] + } else { + words.extend([0xF09C_0108, 0x0043_0C02]); // image_sample_lz v12, v[2:3], s[12:19], s[8:11] + } + words.extend([ + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_1000 | ((i * 4) & 0x0FFF), // buffer_store_dword v12, v16, s[40:43], 0 offen offset:... + 0x800A_0C10, + ]); + } + words.push(0xBF81_0000); // s_endpgm + + let shader = lower_immediate_sampler_cs(&words); + assert_eq!(shader.samplers.len(), 66); + assert_eq!(shader.static_samplers.len(), 66); + for (i, s) in shader.static_samplers.iter().enumerate() { + let expected = if !i.is_multiple_of(2) { 0x80 } else { 0x00 }; + assert_eq!(s.filter & 0x180, expected, "sampler {i}"); + } + } } From 69695bd132d42806c48c8fb579d15a61037c52fd Mon Sep 17 00:00:00 2001 From: bartikele Date: Tue, 24 Nov 2026 16:43:06 +0100 Subject: [PATCH 09/25] victory-shader: define 0 for first half of guarded interpolation --- crates/victory-shader/src/emit/lower.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..d400550 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5452,6 +5452,18 @@ impl<'a> Lower<'a> { fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Some(&interp) = self.interps.get(&site) else { + if inst.name().starts_with("v_interp_p1") { + let dst = match &inst.fields { + Fields::Vintrp { dst, .. } => *dst, + Fields::Valu(v) => v.dst.ok_or("an interpolation")?, + _ => unreachable!(), + }; + if let Operand::Vector { reg, .. } = dst { + let z = self.s.m.i32(0); + self.write(inst, Reg::V(reg), z, None); + } + return Ok(()); + } return Err("the first half of an interpolation"); }; let (attribute, mode) = match interp { From a0206d1ad34a3c6f33a3a46939c78400718100e3 Mon Sep 17 00:00:00 2001 From: mgunes1311-lab Date: Tue, 24 Nov 2026 18:46:53 +0300 Subject: [PATCH 10/25] Shaders: split comparison vs non-comparison immediate samplers in lowering --- crates/victory-shader/src/emit/lower.rs | 47 ++++++++++++------------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..59f40d6 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -31,8 +31,8 @@ enum Val { pub(crate) struct Lowered { pub dxil: Vec, - /// Bit n: immediate sampler n is used for comparisons. - pub cmp_samplers: u64, + /// Whether immediate sampler `n` is used for comparisons. + pub cmp_samplers: Vec, pub root_cbvs: Vec, pub root_srvs: Vec, pub user_data: Vec, @@ -168,7 +168,7 @@ struct Lower<'a> { params: HashMap, user_data: Option, user_reads: BTreeMap, - samplers: Vec<[u32; 4]>, + samplers: Vec<([u32; 4], bool)>, descriptors: HashMap<(Site, bool), &'a Source>, scalar: HashMap, exports: HashMap, @@ -898,10 +898,10 @@ impl<'a> Lower<'a> { } self.fill_phis()?; let user_data = self.user_reads.values().copied().collect(); - self.s.samplers = self.samplers.len() as u32; + let (samplers, cmp_samplers): (Vec<_>, Vec<_>) = self.samplers.into_iter().unzip(); + self.s.samplers = cmp_samplers.clone(); let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect(); - let cmp_samplers = self.s.cmp_samplers; Ok(Lowered { cmp_samplers, root_cbvs, @@ -912,7 +912,7 @@ impl<'a> Lower<'a> { wave_ops: self.s.flags & flags::WAVE_OPS != 0, dxil: self.s.finish(), user_data, - samplers: self.samplers, + samplers, }) } @@ -3327,19 +3327,16 @@ impl<'a> Lower<'a> { .get(..4) .and_then(|w| w.try_into().ok()) .ok_or("a sampler constant")?; - let n = match self.samplers.iter().position(|w| *w == words) { + let comparison = props.0 & 0x8000 != 0; + let key = (words, comparison); + let n = match self.samplers.iter().position(|s| *s == key) { Some(n) => n, None => { - self.samplers.push(words); + self.samplers.push(key); self.samplers.len() - 1 } }; - if props.0 & 0x8000 != 0 { - // shortcut: one sampler used with and without comparison - // would need two static samplers; it becomes a comparison one. - self.s.cmp_samplers |= 1 << n; - } - Ok(self.s.sampler_handle(self.cur, n as u32)) + Ok(self.s.sampler_handle(self.cur, n as u32, comparison)) } Source::Constant(_) => Err("a constant resource descriptor"), Source::Built { address, .. } => { @@ -7099,9 +7096,7 @@ mod tests { S_ENDPGM, ]; - let code: Vec = words.iter() - .flat_map(|w| w.to_le_bytes()) - .collect(); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, @@ -7118,9 +7113,12 @@ mod tests { let p = ir::build(&native.code, false, 256).unwrap(); - assert!(p.blocks.iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_perm_b32")); + assert!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32") + ); let st = structure::structure(&p).unwrap(); let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); @@ -7137,13 +7135,12 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, - }).unwrap(); + }) + .unwrap(); - let container = - crate::Container::parse(&emitted.dxil).unwrap(); + let container = crate::Container::parse(&emitted.dxil).unwrap(); - let features = - container.part(crate::FourCC::SFI0).unwrap(); + let features = container.part(crate::FourCC::SFI0).unwrap(); u64::from_le_bytes(features.data.try_into().unwrap()) } From cb9b4c9210dc63f33b156df1fba5020b3c1a615a Mon Sep 17 00:00:00 2001 From: bartikele Date: Tue, 24 Nov 2026 16:47:03 +0100 Subject: [PATCH 11/25] victory-shader: handle s_buffer_load_dword in descriptor_data --- crates/victory-shader/src/emit/lower.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..a8c47e5 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2995,6 +2995,12 @@ impl<'a> Lower<'a> { } (props, None) } + Fields::Smem { .. } if un.starts_with("s_buffer_load_dword") => { + if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + return Err("a constant buffer's descriptor read as data"); + } + ((11 | u, 0), None) + } _ => return Err("a scalar memory read as data"), }; let h = self.handle(site, &src, false, props)?; From 0dcf6d01adbb5d5a6dfcc120bcf8fefde4ed631a Mon Sep 17 00:00:00 2001 From: ESAT Date: Tue, 24 Nov 2026 19:07:04 +0300 Subject: [PATCH 12/25] Shaders: lower v_pk_fmac_f16 (VOP2 0x3c and VOP3 0x13c) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI-generated & verified with Gemini 4 Neon (High Mode) — not written by a human engineer. `v_pk_fmac_f16` (packed 2x f16 multiply-accumulate into the destination VGPR) is decoded by gfx10 (VOP2 0x3c / VOP3 0x13c) but previously routed into `packed16`, which rejected it with `Err("a packed 16-bit operation")`. Add `pk_fmac_f16` in `lower.rs` to compute both f16 halves (`lo` and `hi`) via `legacyF16ToF32` -> `fmad` -> `legacyF32ToF16`, honoring DPP (`self.src0`), GFX10 inline-constant expansion (low half = constant, high half = 0), and VOP3 `abs`/`neg`/`omod`/`clamp` modifiers across both halves. Verified with synthetic GPU + WARP + dxil.dll tests in `valu_tests.rs` on NVIDIA GeForce RTX 3060 Ti (Windows 11, Rust 1.98.1). No game data used. Co-Authored-By: Gemini 4 Neon (High Mode) --- crates/victory-shader/src/emit/lower.rs | 86 ++++++++++++++++++ crates/victory-shader/src/emit/valu_tests.rs | 91 ++++++++++++++++++++ 2 files changed, 177 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..74997f9 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3740,6 +3740,9 @@ impl<'a> Lower<'a> { if let Some(r) = self.valu16(inst, name, guard) { return r; } + if name == "v_pk_fmac_f16" { + return self.pk_fmac_f16(inst, guard); + } if let Some(op) = name.strip_prefix("v_pk_") { return self.packed16(inst, op, guard); } @@ -4771,6 +4774,89 @@ impl<'a> Lower<'a> { Ok(self.s.m.bin(c, Bin::And, x, m)) } + /// `v_pk_fmac_f16` (VOP2 `0x3c` / VOP3 `0x13c`): two packed f16 + /// multiply-accumulates (`d.lo = s0.lo * s1.lo + d.lo`, same for `hi`). + /// VOP3 `abs`/`neg`/`omod`/`clamp` apply to both halves. + fn pk_fmac_f16(&mut self, inst: &Inst, guard: Option) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.sdwa.is_some() { + return Err("SDWA on v_pk_fmac_f16"); + } + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a packed result outside a VGPR"); + }; + let c = self.cur; + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let old = match inst.read(Reg::V(reg)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), + }; + let s0_raw = match self.src0 { + Some(x) => x, + None => { + let op = *v.src.first().ok_or("a missing operand")?; + self.f16_operand(inst, &op)? + } + }; + let op1 = *v.src.get(1).ok_or("a missing operand")?; + let s1_raw = self.f16_operand(inst, &op1)?; + + let k16 = self.s.m.i32(16); + let m16 = self.s.m.i32(0xFFFF); + let mut halves = Vec::with_capacity(2); + for high in [false, true] { + let mut lane_f = |raw: V, k: usize| { + let h = if high { + self.s.m.bin(c, Bin::LShr, raw, k16) + } else { + raw + }; + let h = self.s.m.bin(c, Bin::And, h, m16); + let mut f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + if v.abs >> k & 1 != 0 { + f = self.unary(6, f); + } + if v.neg >> k & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + f = self.s.m.bin(c, Bin::Sub, z, f); + } + f + }; + let a = lane_f(s0_raw, 0); + let b = lane_f(s1_raw, 1); + let acc_h = if high { + self.s.m.bin(c, Bin::LShr, old, k16) + } else { + old + }; + let acc_h = self.s.m.bin(c, Bin::And, acc_h, m16); + let acc = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[acc_h]); + let mut f = self.fmad(a, b, acc); + if v.omod != 0 { + let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(v.omod)]; + let kf = self.s.m.f32(factor.to_bits()); + f = self.s.m.bin(c, Bin::Mul, f, kf); + } + if v.clamp { + f = self.unary(7, f); + } + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + halves.push(self.s.m.bin(c, Bin::And, h, m16)); + } + let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16); + let r = self.s.m.bin(c, Bin::Or, halves[0], hi); + self.write(inst, Reg::V(reg), r, guard); + Ok(()) + } + /// Packed 16-bit operations (`v_pk_*`): each half computed as the /// 16-bit operation does, f16 through f32 as in [`Self::valu16`]. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option) -> Result<(), Why> { diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..44a9bb1 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -937,3 +937,94 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +/// VOP2 `op vdst, src0, vsrc1`. +const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) +} + +#[test] +fn v_pk_fmac_f16_matches_rdna2() { + // VOP2 `v_pk_fmac_f16 v0, v1, v2` (opcode 0x3c), initialized from v3 (root constant s2). + let vop2_cs = build_valu_cs(&[ + vop1(0x001, 0, vgpr(3)), // v_mov_b32 v0, v3 (accumulator) + vop2(0x3c, 0, vgpr(1), 2), // v_pk_fmac_f16 v0, v1, v2 + ]); + // VOP2 with inline constant 1.0 (0xF2): GFX10 puts 1.0 in lo f16 and 0.0 in hi f16. + let vop2_inline_cs = build_valu_cs(&[ + vop1(0x001, 0, vgpr(3)), // v_mov_b32 v0, v3 + vop2(0x3c, 0, 0xF2, 2), // v_pk_fmac_f16 v0, 1.0, v2 + ]); + // VOP3 `v_pk_fmac_f16 v0, |v1|, -v2 clamp` (opcode 0x13c): abs[0], neg[1], clamp. + let [mut w0, mut w1] = vop3(0x13c, 0, vgpr(1), vgpr(2), 0); + w0 |= (1 << 8) | (1 << 15); // abs[0], clamp + w1 |= 1 << 30; // neg[1] + let vop3_mod_cs = build_valu_cs(&[ + vop1(0x001, 0, vgpr(3)), // v_mov_b32 v0, v3 + w0, + w1, + ]); + + let pack = |lo: u16, hi: u16| u32::from(lo) | (u32::from(hi) << 16); + // f16 constants: 0.0=0x0000, 0.5=0x3800, 1.0=0x3C00, 2.0=0x4000, 3.0=0x4200, + // 4.0=0x4400, 5.0=0x4500, 7.0=0x4700, 10.0=0x4900, -2.0=0xC000, -3.0=0xC200. + let vop2_cases: &[([u32; 4], u32)] = &[ + // lo: 2.0 * 3.0 + 1.0 = 7.0; hi: -2.0 * 4.0 + 10.0 = 2.0 + ( + [pack(0x4000, 0xC000), pack(0x4200, 0x4400), pack(0x3C00, 0x4900), 0], + pack(0x4700, 0x4000), + ), + // lo: 0.5 * 4.0 + 3.0 = 5.0; hi: 0.0 * 7.0 + (-3.0) = -3.0 + ( + [pack(0x3800, 0x0000), pack(0x4400, 0x4700), pack(0x4200, 0xC200), 0], + pack(0x4500, 0xC200), + ), + ]; + let vop2_in: Vec<[u32; 4]> = vop2_cases.iter().map(|c| c.0).collect(); + run_cases(&vop2_cs, &vop2_in, |backend, i, inp, got| { + let want = vop2_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_pk_fmac_f16({:#010x}, {:#010x}, acc={:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); + + // Inline 1.0: lo = 1.0 * 3.0 + 2.0 = 5.0; hi = 0.0 * 4.0 + 7.0 = 7.0 (unchanged). + run_cases( + &vop2_inline_cs, + &[[0, pack(0x4200, 0x4400), pack(0x4000, 0x4700), 0]], + |backend, _, _, got| { + let want = pack(0x4500, 0x4700); + assert_eq!( + got, want, + "{backend}: v_pk_fmac_f16(1.0, ...) = {got:#010x}, want {want:#010x}", + ); + }, + ); + + // VOP3 abs[0], neg[1], clamp: + // lo: |-2.0| * (-0.5) + 1.5(=0x3E00) = 0.5 (in [0, 1]) -> 0x3800 + // hi: |-2.0| * (-2.0) + 1.0 = -3.0 -> clamped to 0.0 (0x0000) + // case 2: lo: |-2.0| * (-(-1.0)) + 0.5 = 2.5 -> clamped to 1.0 (0x3C00) + // hi: |0.5| * (-(-0.5)) + 0.25(=0x3400) = 0.5 (0x3800) + let vop3_cases: &[([u32; 4], u32)] = &[ + ( + [pack(0xC000, 0xC000), pack(0x3800, 0x4000), pack(0x3E00, 0x3C00), 0], + pack(0x3800, 0x0000), + ), + ( + [pack(0xC000, 0x3800), pack(0xBC00, 0xB800), pack(0x3800, 0x3400), 0], + pack(0x3C00, 0x3800), + ), + ]; + let vop3_in: Vec<[u32; 4]> = vop3_cases.iter().map(|c| c.0).collect(); + run_cases(&vop3_mod_cs, &vop3_in, |backend, i, inp, got| { + let want = vop3_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_pk_fmac_f16_e64(|{:#010x}|, -{:#010x}, acc={:#010x}) clamp = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); +} From bf873ffd3b30ea77b18736e63a032cf33d2dc7e6 Mon Sep 17 00:00:00 2001 From: ESAT Date: Tue, 24 Nov 2026 19:10:16 +0300 Subject: [PATCH 13/25] Shaders: support saturating clamp on packed 16-bit integer ops (v_pk_{add,sub,mad}_{u16,i16}) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI-generated & verified with Gemini 4 Neon (High Mode) — not written by a human engineer. `packed16` in `lower.rs` previously rejected `v.clamp` on all packed 16-bit integer instructions with `Err("modifiers on a packed integer operation")`. Under the AMD RDNA2 ISA (VOP3P), `clamp` on `v_pk_add_u16`, `v_pk_sub_u16`, `v_pk_mad_u16`, `v_pk_add_i16`, `v_pk_sub_i16`, and `v_pk_mad_i16` saturates each 16-bit lane to `[0, 65535]` (unsigned) or `[-32768, 32767]` (signed). Because `packed16` computes each lane in 32 bits (`u16*u16+u16 <= u32::MAX`, `i16*i16+i16` fits in `i32`), saturation is exact in 32-bit integer compares before masking to 16 bits. Non-saturating packed integer ops keep rejecting `clamp`. Verified with synthetic GPU + WARP + dxil.dll tests in `valu_tests.rs` on NVIDIA GeForce RTX 3060 Ti (Windows 11, Rust 1.98.1). No game data used. Co-Authored-By: Gemini 4 Neon (High Mode) --- crates/victory-shader/src/emit/lower.rs | 36 +++++- crates/victory-shader/src/emit/valu_tests.rs | 115 +++++++++++++++++++ 2 files changed, 149 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..2c84fce 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4785,7 +4785,11 @@ impl<'a> Lower<'a> { | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2, _ => return Err("a packed 16-bit operation"), }; - if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) { + let saturates = matches!( + op, + "add_u16" | "sub_u16" | "mad_u16" | "add_i16" | "sub_i16" | "mad_i16" + ); + if v.omod != 0 || !float && ((v.clamp && !saturates) || v.neg != 0 || v.neg_hi != 0) { return Err("modifiers on a packed integer operation"); } let c = self.cur; @@ -4835,7 +4839,7 @@ impl<'a> Lower<'a> { } } let k15 = self.s.m.i32(15); - match op { + let r = match op { "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]), "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]), "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]), @@ -4867,6 +4871,34 @@ impl<'a> Lower<'a> { let t = self.s.m.cmp(c, p, xs[0], xs[1]); self.s.m.select(c, t, xs[0], xs[1]) } + }; + if v.clamp && saturates { + match op { + // Unsigned: add/mad fit in u32 (max 65535*65535+65535 <= u32::MAX); + // sub is in [-65535, 65535] so signed < 0 catches underflow. + "add_u16" | "mad_u16" => { + let hi = self.s.m.i32(0xFFFF); + let over = self.s.m.cmp(c, pred::IUGT, r, hi); + self.s.m.select(c, over, hi, r) + } + "sub_u16" => { + let z = self.s.m.i32(0); + let under = self.s.m.cmp(c, pred::SLT, r, z); + self.s.m.select(c, under, z, r) + } + // Signed: operands are sign-extended i16 in i32, so add/sub/mad + // never wrap i32 (|r| <= 32768*32768 + 32768 < 2^31). + _ => { + let lo = self.s.m.i32(i32::from(i16::MIN) as u32); + let hi = self.s.m.i32(i32::from(i16::MAX) as u32); + let under = self.s.m.cmp(c, pred::SLT, r, lo); + let t = self.s.m.select(c, under, lo, r); + let over = self.s.m.cmp(c, pred::SGT, t, hi); + self.s.m.select(c, over, hi, t) + } + } + } else { + r } }; let m = self.s.m.i32(0xFFFF); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..f855491 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -937,3 +937,118 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +/// VOP3P `op vdst, src0, src1, src2` with standard packed lane selects +/// (`opsel = 0b000`, `opsel_hi = 0b111`) and optional `clamp`. +const fn vop3p(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16, clamp: bool) -> [u32; 2] { + [ + 0x33 << 26 + | (op as u32 & 0x7F) << 16 + | (clamp as u32) << 15 + | (1 << 14) // opsel_hi[2] = 1 + | vdst as u32, + (0b11 << 27) // opsel_hi[1:0] = 0b11 + | (src0 as u32 & 0x1FF) + | (src1 as u32 & 0x1FF) << 9 + | (src2 as u32 & 0x1FF) << 18, + ] +} + +#[test] +fn v_pk_int16_clamp_saturates_as_rdna2() { + let pack_u = |lo: u16, hi: u16| u32::from(lo) | (u32::from(hi) << 16); + let pack_i = |lo: i16, hi: i16| pack_u(lo as u16, hi as u16); + + // VOP3P opcodes: 0x00=mad_i16, 0x02=add_i16, 0x03=sub_i16, 0x09=mad_u16, 0x0a=add_u16, 0x0b=sub_u16. + let add_u16 = build_valu_cs(&vop3p(0x0a, 0, vgpr(1), vgpr(2), 0, true)); + let sub_u16 = build_valu_cs(&vop3p(0x0b, 0, vgpr(1), vgpr(2), 0, true)); + let mad_u16 = build_valu_cs(&vop3p(0x09, 0, vgpr(1), vgpr(2), vgpr(3), true)); + let add_i16 = build_valu_cs(&vop3p(0x02, 0, vgpr(1), vgpr(2), 0, true)); + let sub_i16 = build_valu_cs(&vop3p(0x03, 0, vgpr(1), vgpr(2), 0, true)); + let mad_i16 = build_valu_cs(&vop3p(0x00, 0, vgpr(1), vgpr(2), vgpr(3), true)); + + // add_u16 clamp: lo overflows (60000+10000 -> 65535), hi fits (100+200 -> 300) + run_cases( + &add_u16, + &[ + [pack_u(60000, 100), pack_u(10000, 200), 0, 0], + [pack_u(u16::MAX, 0), pack_u(u16::MAX, 0), 0, 0], + ], + |backend, i, _, got| { + let want = [pack_u(u16::MAX, 300), pack_u(u16::MAX, 0)][i]; + assert_eq!(got, want, "{backend}: v_pk_add_u16 clamp case {i}"); + }, + ); + + // sub_u16 clamp: lo underflows (5-10 -> 0), hi fits (500-200 -> 300) + run_cases( + &sub_u16, + &[ + [pack_u(5, 500), pack_u(10, 200), 0, 0], + [pack_u(0, u16::MAX), pack_u(u16::MAX, 0), 0, 0], + ], + |backend, i, _, got| { + let want = [pack_u(0, 300), pack_u(0, u16::MAX)][i]; + assert_eq!(got, want, "{backend}: v_pk_sub_u16 clamp case {i}"); + }, + ); + + // mad_u16 clamp: lo max*max+max -> 65535 (tests no u32 wrap!), hi 20*30+40 -> 640 + run_cases( + &mad_u16, + &[[ + pack_u(u16::MAX, 20), + pack_u(u16::MAX, 30), + pack_u(u16::MAX, 40), + 0, + ]], + |backend, _, _, got| { + let want = pack_u(u16::MAX, 640); + assert_eq!(got, want, "{backend}: v_pk_mad_u16 clamp"); + }, + ); + + // add_i16 clamp: lo +overflow (30000+10000 -> 32767), hi -overflow (-30000-10000 -> -32768) + run_cases( + &add_i16, + &[ + [pack_i(30000, -30000), pack_i(10000, -10000), 0, 0], + [pack_i(100, -50), pack_i(-25, 20), 0, 0], + ], + |backend, i, _, got| { + let want = [pack_i(i16::MAX, i16::MIN), pack_i(75, -30)][i]; + assert_eq!(got, want, "{backend}: v_pk_add_i16 clamp case {i}"); + }, + ); + + // sub_i16 clamp: lo -overflow (-30000-10000 -> -32768), hi +overflow (30000-(-10000) -> 32767) + run_cases( + &sub_i16, + &[ + [pack_i(-30000, 30000), pack_i(10000, -10000), 0, 0], + [pack_i(0, -100), pack_i(i16::MIN, -200), 0, 0], + ], + |backend, i, _, got| { + let want = [pack_i(i16::MIN, i16::MAX), pack_i(i16::MAX, 100)][i]; + assert_eq!(got, want, "{backend}: v_pk_sub_i16 clamp case {i}"); + }, + ); + + // mad_i16 clamp: lo (-32768)*(-32768)+32767 -> 32767, hi (-32768)*(32767)-32768 -> -32768 + run_cases( + &mad_i16, + &[ + [ + pack_i(i16::MIN, i16::MIN), + pack_i(i16::MIN, i16::MAX), + pack_i(i16::MAX, i16::MIN), + 0, + ], + [pack_i(-10, 5), pack_i(20, -4), pack_i(50, -3), 0], + ], + |backend, i, _, got| { + let want = [pack_i(i16::MAX, i16::MIN), pack_i(-150, -23)][i]; + assert_eq!(got, want, "{backend}: v_pk_mad_i16 clamp case {i}"); + }, + ); +} From 4e35c96234d0d04941bb5b1ce9b0ded6abdf1aa0 Mon Sep 17 00:00:00 2001 From: DenRakEiw <89697885+DenRakEiw@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:14:20 +0100 Subject: [PATCH 14/25] Shaders: lower v_div_fixup_f32 and v_div_fixup_f16 with RDNA2 IEEE-754 special-case semantics --- crates/victory-shader/src/emit/lower.rs | 68 +++++++++++++- crates/victory-shader/src/emit/valu_tests.rs | 99 ++++++++++++++++++++ 2 files changed, 166 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..3576367 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1482,6 +1482,69 @@ impl<'a> Lower<'a> { self.s.m.select(c, nan, least, median) } + /// `v_div_fixup_f32` / `v_div_fixup_f16`: finalizes a division sequence's + /// quotient `quot` (`src0`) for `num / denom` (`src2 / src1`), resolving + /// IEEE-754 special cases (`NaN`, `0/0`, `inf/inf`, `x/0`, `x/inf`, + /// `0/x`, `inf/x`, and `quot == NaN` overflow) and applying `sign(denom) + /// ^ sign(num)` in pure integer bit operations. + fn div_fixup(&mut self, quot: V, denom: V, num: V) -> V { + let c = self.cur; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let q = self.as_int(quot); + let d = self.as_int(denom); + let n = self.as_int(num); + + let sign_mask = k(self, 0x8000_0000); + let abs_mask = k(self, 0x7FFF_FFFF); + let inf_bits = k(self, 0x7F80_0000); + let qnan_bits = k(self, 0x7FC0_0000); + let quiet_bit = k(self, 0x0040_0000); + let zero = k(self, 0); + + let sign_xor = self.s.m.bin(c, Bin::Xor, d, n); + let sign_out = self.s.m.bin(c, Bin::And, sign_xor, sign_mask); + + let q_mag = self.s.m.bin(c, Bin::And, q, abs_mask); + let d_mag = self.s.m.bin(c, Bin::And, d, abs_mask); + let n_mag = self.s.m.bin(c, Bin::And, n, abs_mask); + + let q_nan = self.s.m.cmp(c, pred::IUGT, q_mag, inf_bits); + let d_nan = self.s.m.cmp(c, pred::IUGT, d_mag, inf_bits); + let n_nan = self.s.m.cmp(c, pred::IUGT, n_mag, inf_bits); + + let d_inf = self.s.m.cmp(c, pred::EQ, d_mag, inf_bits); + let n_inf = self.s.m.cmp(c, pred::EQ, n_mag, inf_bits); + let d_zero = self.s.m.cmp(c, pred::EQ, d_mag, zero); + let n_zero = self.s.m.cmp(c, pred::EQ, n_mag, zero); + + let signed_inf = self.s.m.bin(c, Bin::Or, inf_bits, sign_out); + let signed_zero = sign_out; + let signed_q = self.s.m.bin(c, Bin::Or, q_mag, sign_out); + + // Priority (lowest to highest, built bottom-up via select): + // 6. Normal/inf quotient: copysign(quot, sign_out); NaN quotient -> ±inf. + let r = self.s.m.select(c, q_nan, signed_inf, signed_q); + // 5. denom == ±inf or num == ±0 -> ±0.0 with sign_out. + let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero); + let r = self.s.m.select(c, make_zero, signed_zero, r); + // 4. num == ±inf or denom == ±0 -> ±inf with sign_out. + let make_inf = self.s.m.bin(c, Bin::Or, n_inf, d_zero); + let r = self.s.m.select(c, make_inf, signed_inf, r); + // 3. (0 / 0) or (inf / inf) -> canonical qNaN. + let zero_over_zero = self.s.m.bin(c, Bin::And, d_zero, n_zero); + let inf_over_inf = self.s.m.bin(c, Bin::And, d_inf, n_inf); + let indet = self.s.m.bin(c, Bin::Or, zero_over_zero, inf_over_inf); + let r = self.s.m.select(c, indet, qnan_bits, r); + // 2. num is NaN -> quiet(num). + let n_quiet = self.s.m.bin(c, Bin::Or, n, quiet_bit); + let r = self.s.m.select(c, n_nan, n_quiet, r); + // 1. denom is NaN -> quiet(denom). + let d_quiet = self.s.m.bin(c, Bin::Or, d, quiet_bit); + let r = self.s.m.select(c, d_nan, d_quiet, r); + + self.as_float(r) + } + /// `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 @@ -3958,7 +4021,7 @@ impl<'a> Lower<'a> { let r = self.s.m.bin(c, Bin::Add, m, cc); float(self, r) } - "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => { + "v_max3_f32" | "v_min3_f32" | "v_med3_f32" | "v_div_fixup_f32" => { let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); let r = match name { "v_max3_f32" => { @@ -3969,6 +4032,7 @@ impl<'a> Lower<'a> { let t = self.max_min(false, a, bb); self.max_min(false, t, cc) } + "v_div_fixup_f32" => self.div_fixup(a, bb, cc), _ => self.med3(a, bb, cc), }; float(self, r) @@ -4424,6 +4488,7 @@ impl<'a> Lower<'a> { "v_max3_f16", "v_min3_f16", "v_med3_f16", + "v_div_fixup_f16", ]; const FLOAT1: &[&str] = &[ "v_rcp_f16", @@ -4547,6 +4612,7 @@ impl<'a> Lower<'a> { let t = self.max_min(false, a, b); self.max_min(false, t, acc) } + "v_div_fixup_f16" => self.div_fixup(a, b, acc), _ => self.med3(a, b, acc), }; return float_result(self, r); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..4003efa 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -937,3 +937,102 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +#[test] +fn v_div_fixup_f32_matches_rdna2() { + // VOP3 v_div_fixup_f32 v0, v1 (quot), v2 (denom), v3 (num) — opcode 0x15f + let shader = build_valu_cs(&vop3(0x15f, 0, vgpr(1), vgpr(2), vgpr(3))); + let p_zero = 0.0f32.to_bits(); + let n_zero = (-0.0f32).to_bits(); + let p_inf = f32::INFINITY.to_bits(); + let n_inf = f32::NEG_INFINITY.to_bits(); + let qnan = 0x7FC0_0000u32; + let snan1 = 0x7F80_0001u32; + let snan2 = 0x7F80_0002u32; + let f_pos = 3.5f32.to_bits(); + let f_neg = (-3.5f32).to_bits(); + let two = 2.0f32.to_bits(); + let m_two = (-2.0f32).to_bits(); + let seven = 7.0f32.to_bits(); + let m_seven = (-7.0f32).to_bits(); + + // (quot, denom, num) -> expected exact bits (None = any NaN) + let cases: &[([u32; 4], Option)] = &[ + // Normal quotients: sign = sign(denom) ^ sign(num). + ([f_pos, two, seven, 0], Some(f_pos)), + ([f_pos, m_two, seven, 0], Some(f_neg)), + ([f_neg, m_two, m_seven, 0], Some(f_pos)), + // NaN quotient with finite non-zero denom/num -> ±inf with sign_out. + ([qnan, two, seven, 0], Some(p_inf)), + ([qnan, m_two, seven, 0], Some(n_inf)), + // Division by ±0 -> ±inf with sign_out. + ([f_pos, p_zero, seven, 0], Some(p_inf)), + ([f_pos, n_zero, seven, 0], Some(n_inf)), + ([f_pos, n_zero, m_seven, 0], Some(p_inf)), + // ±inf / finite -> ±inf with sign_out. + ([f_pos, m_two, p_inf, 0], Some(n_inf)), + ([f_pos, m_two, n_inf, 0], Some(p_inf)), + // finite / ±inf and ±0 / finite -> ±0.0 with sign_out. + ([f_pos, n_inf, seven, 0], Some(n_zero)), + ([f_pos, n_inf, m_seven, 0], Some(p_zero)), + ([f_pos, m_two, p_zero, 0], Some(n_zero)), + ([f_pos, m_two, n_zero, 0], Some(p_zero)), + // Indeterminate forms: 0/0 and inf/inf -> qNaN. + ([f_pos, p_zero, p_zero, 0], None), + ([f_pos, n_zero, p_zero, 0], None), + ([f_pos, p_inf, n_inf, 0], None), + // NaN in denom or num propagates quieted NaN (denom takes priority). + ([f_pos, snan1, snan2, 0], Some(0x7FC0_0001)), + ([f_pos, two, snan2, 0], Some(0x7FC0_0002)), + ]; + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + match cases[i].1 { + Some(want) => assert_eq!( + got, want, + "{backend}: v_div_fixup_f32({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ), + None => assert!( + f32::from_bits(got).is_nan(), + "{backend}: v_div_fixup_f32({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want NaN", + inp[0], inp[1], inp[2], + ), + } + }); +} + +#[test] +fn v_div_fixup_f16_matches_rdna2() { + // VOP3 v_div_fixup_f16 v0, v1 (quot), v2 (denom), v3 (num) — opcode 0x35f + let shader = build_valu_cs(&vop3(0x35f, 0, vgpr(1), vgpr(2), vgpr(3))); + // f16 bit patterns: +0=0x0000, -0=0x8000, +1=0x3C00, -2=0xC000, +3.5=0x4300, -3.5=0xC300, + // +inf=0x7C00, -inf=0xFC00, qNaN=0x7E00 + let cases: &[([u32; 4], Option)] = &[ + ([0x4300, 0xC000, 0x3C00, 0], Some(0xC300)), // copysign(3.5, -2 ^ +1) = -3.5 + ([0xC300, 0xC000, 0xBC00, 0], Some(0x4300)), // copysign(-3.5, -2 ^ -1) = +3.5 + ([0x7E00, 0xC000, 0x3C00, 0], Some(0xFC00)), // NaN quot -> -inf + ([0x4300, 0x8000, 0x3C00, 0], Some(0xFC00)), // +1 / -0 -> -inf + ([0x4300, 0xFC00, 0x3C00, 0], Some(0x8000)), // +1 / -inf -> -0.0 + ([0x4300, 0xC000, 0x0000, 0], Some(0x8000)), // +0 / -2 -> -0.0 + ([0x4300, 0x0000, 0x0000, 0], None), // 0 / 0 -> NaN + ([0x4300, 0x7C00, 0xFC00, 0], None), // -inf / +inf -> NaN + ([0x4300, 0x7E00, 0x3C00, 0], None), // NaN denom -> NaN + ]; + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let got_h = got as u16; + match cases[i].1 { + Some(want) => assert_eq!( + got_h, want, + "{backend}: v_div_fixup_f16({:#06x}, {:#06x}, {:#06x}) = {got_h:#06x}, want {want:#06x}", + inp[0], inp[1], inp[2], + ), + None => assert!( + is_f16_nan(got_h), + "{backend}: v_div_fixup_f16({:#06x}, {:#06x}, {:#06x}) = {got_h:#06x}, want NaN", + inp[0], inp[1], inp[2], + ), + } + }); +} From bec4bfa28977aba7cb64ff3d1aebf31e2d8efdef Mon Sep 17 00:00:00 2001 From: Jordan Ouellette Date: Tue, 24 Nov 2026 11:17:12 -0500 Subject: [PATCH 15/25] Shaders: reads of uninitialized pixel SGPRs read as zero --- crates/victory-shader/src/emit/mod.rs | 83 +++++++++++++++++++++++++++ crates/victory-shader/src/io.rs | 10 ++-- crates/victory-shader/src/native.rs | 70 +++++++++++++++++++++- 3 files changed, 156 insertions(+), 7 deletions(-) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 89652da..d1b22d1 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -445,6 +445,7 @@ mod tests { used: vec![], io: StageIo::Ps { inputs: vec![], + rsrc2: 0, input_addr: 0, db_shader_control: 0, patches: vec![], @@ -646,6 +647,7 @@ mod tests { pack2: false, row2: 0, }], + rsrc2: 0, input_addr, db_shader_control: 0, patches: vec![], @@ -718,6 +720,7 @@ mod tests { pack2: false, row2: 0, }], + rsrc2: 0, input_addr: 0, db_shader_control: 0, patches: vec![], @@ -746,4 +749,84 @@ mod tests { // Translated or refused with a reason; it must not panic. let _ = super::emit(&c, &native, &p, &st, &io, &res); } + + #[test] + fn pixel_reads_of_uninitialized_sgprs_read_as_zero() { + let try_emit = |rsrc2: u32, sgpr: u32| { + // v_mov_b32 v0, s; exp mrt0, v0, v0, v0, v0 done vm; s_endpgm + let words = [0x7E00_0200u32 | sgpr, 0xF800_180F, 0x0000_0000, 0xBF81_0000]; + let native = super::NativeProgram { + stage: super::HwStage::Ps, + wave64: false, + vgprs: 2, + layout: vec![], + used: vec![], + io: crate::native::StageIo::Ps { + inputs: vec![], + rsrc2, + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let osg1 = super::container::signature( + &[SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }], + false, + ); + let bytes = crate::dxbc::build(&[(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 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(); + super::emit(&c, &native, &p, &st, &io, &res) + }; + + // 2 user SGPRs (s0..=s1) + prim_mask (s2) -> initialized_sgprs = 3. + let rsrc2 = 2 << 1; + // s2 is hardware-initialized (prim_mask) and must still be refused. + assert!(matches!( + try_emit(rsrc2, 2), + Err(crate::ShaderError::Unsupported { + what: "a hardware SGPR input", + .. + }) + )); + // s3 is uninitialized on entry and reads as zero, passing DXIL validation. + let out = try_emit(rsrc2, 3).unwrap(); + #[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(); + } + // Enabling SCRATCH_EN (bit 0) initializes s3 (scratch wave offset), so + // s3 is refused again while s4 reads as zero. + assert!(matches!( + try_emit(rsrc2 | 1, 3), + Err(crate::ShaderError::Unsupported { + what: "a hardware SGPR input", + .. + }) + )); + let out = try_emit(rsrc2 | 1, 4).unwrap(); + #[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(); + } + } } diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index e3cbd60..0a34ae5 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -182,8 +182,8 @@ 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)). + /// How many SGPRs the hardware initializes on entry + /// ([`StageIo::initialized_sgprs`](crate::native::StageIo::initialized_sgprs)). pub initialized_sgprs: Option, } @@ -290,10 +290,7 @@ 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, - }, + initialized_sgprs: native.io.initialized_sgprs(), ..Io::default() }; let defs: std::collections::HashMap = p @@ -558,6 +555,7 @@ mod tests { used: vec![], io: StageIo::Ps { inputs, + rsrc2: 0, input_addr, db_shader_control: 0, patches: Vec::::new(), diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 4bdd39b..2038bef 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -35,6 +35,7 @@ //! mask, u8 attribute (v_interp `attr`), u8 default, u8 second //! row (of a packed pair), u8 parameter slot, u8 flags (bit 0 //! flat, 1 linear, 3 fp16, 4 fp16 packed); E+0x124 u32 count +//! E+0x128 u32 SPI_SHADER_PGM_RSRC2_PS //! E+0x134 u32 SPI_PS_INPUT_ADDR, E+0x138 u32 DB_SHADER_CONTROL //! E+0x148 u32 export patch size (dwords), E+0x14c 8 patches, one per //! MRT: u32 code offset (dwords, -1 none), then the export code @@ -102,6 +103,7 @@ const ENTRY_SIZE: u64 = 20; const MAX_SEMANTICS: u32 = 32; const PS_INPUTS: usize = 0x24; const PS_INPUT_COUNT: usize = 0x124; +const PS_RSRC2: usize = 0x128; const PS_INPUT_ADDR: usize = 0x134; const PS_DB_SHADER_CONTROL: usize = 0x138; const PS_PATCH_SIZE: usize = 0x148; @@ -260,6 +262,8 @@ pub enum StageIo { }, Ps { inputs: Vec, + /// `SPI_SHADER_PGM_RSRC2_PS`: user SGPRs and enabled hardware SGPRs. + rsrc2: u32, /// `SPI_PS_INPUT_ADDR`: which system values arrive in VGPRs. input_addr: u32, /// `DB_SHADER_CONTROL`: depth export, kill. @@ -270,6 +274,33 @@ pub enum StageIo { Ms(MeshIo), } +impl StageIo { + /// How many general SGPRs (`s0..`) the hardware initializes on entry, when + /// the stage's `PGM_RSRC2` register is read. Registers at or above this + /// count hold whatever the previous wave left. + pub fn initialized_sgprs(&self) -> Option { + match self { + Self::Cs(cs) => Some(cs.initialized_sgprs()), + Self::Ps { rsrc2, .. } => Some(ps_initialized_sgprs(*rsrc2)), + _ => None, + } + } +} + +/// SGPRs the hardware initializes for a pixel shader from +/// `SPI_SHADER_PGM_RSRC2_PS`: user SGPRs (bits 1-5, plus bit 28 as MSB), +/// `prim_mask` (always present), `wave_cnt` (bit 7), POPS collision wave id +/// (bit 25), intrawave collisions (bit 26), and the scratch wave offset +/// (bit 0). +pub fn ps_initialized_sgprs(rsrc2: u32) -> u8 { + let user = ((rsrc2 >> 1) & 0x1F) | (((rsrc2 >> 28) & 1) << 5); + let scratch = rsrc2 & 1; + let wave_cnt = (rsrc2 >> 7) & 1; + let pops_collision = (rsrc2 >> 25) & 1; + let pops_intrawave = (rsrc2 >> 26) & 1; + (user + 1 + wave_cnt + pops_collision + pops_intrawave + scratch) as u8 +} + /// A mesh program's outputs and limits. It runs as one hardware NGG stage: /// lane n of the group (`threads` lanes) exports vertex n (`exp pos`, /// `exp param`) and primitive n (`exp prim`). @@ -605,6 +636,7 @@ fn ps_io(data: &[u8], code_len: usize) -> Result { } Ok(StageIo::Ps { inputs, + rsrc2: u32_at(data, PS_RSRC2)?, input_addr: u32_at(data, PS_INPUT_ADDR)?, db_shader_control: u32_at(data, PS_DB_SHADER_CONTROL)?, patches, @@ -785,6 +817,7 @@ mod tests { used: vec![], io: StageIo::Ps { inputs: vec![], + rsrc2: 0, input_addr: 0, db_shader_control: 0, patches: vec![], @@ -854,6 +887,7 @@ mod tests { // TEXCOORD in row 1 (xy), read as attr0, flat. blob[e + PS_INPUTS..][..8].copy_from_slice(&[6, 1, 3, 0, 0, 0, 1, 1]); blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&1u32.to_le_bytes()); + blob[e + PS_RSRC2..][..4].copy_from_slice(&0x14u32.to_le_bytes()); blob[e + PS_INPUT_ADDR..][..4].copy_from_slice(&2u32.to_le_bytes()); blob[e + PS_PATCH_SIZE..][..4].copy_from_slice(&2u32.to_le_bytes()); // MRT1 at dword 1: the 32_ABGR variant is `exp mrt1 v0-v3 done`. @@ -865,6 +899,7 @@ mod tests { let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; let StageIo::Ps { inputs, + rsrc2, input_addr, patches, .. @@ -882,7 +917,7 @@ mod tests { pack2: false, row2: 0, }; - assert_eq!((&inputs[..], *input_addr), (&[input][..], 2)); + assert_eq!((&inputs[..], *rsrc2, *input_addr), (&[input][..], 0x14, 2)); assert_eq!(patches.len(), 1); assert_eq!((patches[0].mrt, patches[0].offset), (1, 1)); let patched = p.patched_code(); @@ -979,6 +1014,39 @@ mod tests { assert_eq!(cs.initialized_sgprs(), 11); } + #[test] + fn ps_initialized_sgprs_covers_user_system_and_scratch() { + // 10 user SGPRs (s0..=s9) + prim_mask (s10): 11. + assert_eq!(ps_initialized_sgprs(10 << 1), 11); + // 17 user SGPRs (s0..=s16) + prim_mask (s17): 18. + assert_eq!(ps_initialized_sgprs(17 << 1), 18); + // USER_SGPR_MSB (bit 28) extends user SGPRs to 32 + prim_mask: 33. + assert_eq!(ps_initialized_sgprs(1 << 28), 33); + // Scratch (bit 0), wave_cnt (bit 7), POPS collision wave id (bit 25), + // and intrawave collisions (bit 26) each add one SGPR. + assert_eq!(ps_initialized_sgprs((10 << 1) | 1), 12); + assert_eq!(ps_initialized_sgprs((10 << 1) | (1 << 7)), 12); + assert_eq!( + ps_initialized_sgprs((10 << 1) | 1 | (1 << 7) | (1 << 25) | (1 << 26)), + 15 + ); + // TRAP_PRESENT (bit 6), EXTRA_LDS_SIZE (8..=15), and EXCP_EN (16..=24) + // do not allocate general SGPRs. + assert_eq!( + ps_initialized_sgprs((10 << 1) | (1 << 6) | (0xFF << 8) | (0x1FF << 16)), + 11 + ); + let ps = StageIo::Ps { + inputs: vec![], + rsrc2: 17 << 1, + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }; + assert_eq!(ps.initialized_sgprs(), Some(18)); + assert_eq!(StageIo::None.initialized_sgprs(), None); + } + #[test] fn reads_every_native_blob() { let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)])); From d160854be046f2d70a71ade4ba9836f0c6edcd15 Mon Sep 17 00:00:00 2001 From: ESAT Date: Tue, 24 Nov 2026 19:22:53 +0300 Subject: [PATCH 16/25] Shaders: lower v_frexp_mant_{f32,f16} and v_frexp_exp_i{32_f32,16_f16} MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI-generated & verified with Gemini 4 Neon (High Mode) — not written by a human engineer. Lower the four RDNA2 `frexp` instructions (`v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_frexp_mant_f16`, `v_frexp_exp_i16_f16`) via a shared 32-bit bitwise `frexp_f32` helper: - finite non-zero (normal and subnormal via DXIL `FirstbitHi` op 33): mantissa in `(-1, -0.5] U [0.5, 1)` and unbiased exponent `exp` where `a == mantissa * 2^exp`; - `±0`, `±inf`, `NaN`: mantissa preserves the input (sign/special value), exponent is `0`. - f16 variants widen through `half_fsrc` (exact even for all f16 subnormals), apply `frexp_f32`, and preserve the destination's untouched half via `write_half`. Verified with synthetic GPU + WARP + dxil.dll tests in `valu_tests.rs` on NVIDIA GeForce RTX 3060 Ti (Windows 11, Rust 1.98.1). No game data used. Co-Authored-By: Gemini 4 Neon (High Mode) --- crates/victory-shader/src/emit/lower.rs | 78 +++++++++++++ crates/victory-shader/src/emit/valu_tests.rs | 110 +++++++++++++++++++ 2 files changed, 188 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..773ad0d 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1548,6 +1548,60 @@ impl<'a> Lower<'a> { self.s.m.select(c, z, zero, m) } + /// Decomposes an f32 into `(mantissa, exponent)` per RDNA2 `v_frexp_*`: + /// - finite non-zero (normal or subnormal): `mantissa` in `(-1, -0.5] U [0.5, 1)` + /// and `exponent` such that `a == mantissa * 2^exponent`; + /// - `±0`, `±inf`, `NaN`: `mantissa = a` (preserving sign/special value), `exponent = 0`. + fn frexp_f32(&mut self, a: V) -> (V, V) { + let c = self.cur; + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let bits = self.as_int(a); + let sign_mask = k(self, 0x8000_0000); + let mag_mask = k(self, 0x7FFF_FFFF); + let mant_mask = k(self, 0x007F_FFFF); + let half_exp = k(self, 0x3F00_0000); + let (k0, k23, k255, k126) = (k(self, 0), k(self, 23), k(self, 255), k(self, 126)); + + let sign = self.s.m.bin(c, Bin::And, bits, sign_mask); + let mag = self.s.m.bin(c, Bin::And, bits, mag_mask); + let exp_raw = self.s.m.bin(c, Bin::LShr, mag, k23); + let mant_raw = self.s.m.bin(c, Bin::And, mag, mant_mask); + + // Normal path: biased exponent 1..=254 -> exponent = exp_raw - 126, mantissa exp = 126. + let norm_mant = self.s.m.bin(c, Bin::Or, sign, half_exp); + let norm_mant = self.s.m.bin(c, Bin::Or, norm_mant, mant_raw); + let norm_exp = self.s.m.bin(c, Bin::Sub, exp_raw, k126); + + // Subnormal path (exp_raw == 0, mant_raw != 0): shift top bit of mant_raw to bit 23. + // FirstbitHi (op 33) counts leading zeros from bit 31: bit k -> lz = 31 - k in [9..=31]. + let lz = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 33, &[mant_raw]); + let k8 = k(self, 8); + let sh = self.s.m.bin(c, Bin::Sub, lz, k8); + let k31 = k(self, 31); + let sh_safe = self.s.m.bin(c, Bin::And, sh, k31); + let sub_mant_bits = self.s.m.bin(c, Bin::Shl, mant_raw, sh_safe); + let sub_mant_bits = self.s.m.bin(c, Bin::And, sub_mant_bits, mant_mask); + let sub_mant = self.s.m.bin(c, Bin::Or, sign, half_exp); + let sub_mant = self.s.m.bin(c, Bin::Or, sub_mant, sub_mant_bits); + // Value = mant_raw * 2^-149 = (0.5..1) * 2^(-117 - lz). + let k_neg117 = k(self, (-117i32) as u32); + let sub_exp = self.s.m.bin(c, Bin::Sub, k_neg117, lz); + + let is_exp0 = self.s.m.cmp(c, pred::EQ, exp_raw, k0); + let is_zero = self.s.m.cmp(c, pred::EQ, mag, k0); + let is_inf_nan = self.s.m.cmp(c, pred::EQ, exp_raw, k255); + let is_special = self.s.m.bin(c, Bin::Or, is_zero, is_inf_nan); + + let mant_fin = self.s.m.select(c, is_exp0, sub_mant, norm_mant); + let exp_fin = self.s.m.select(c, is_exp0, sub_exp, norm_exp); + + let mant_bits = self.s.m.select(c, is_special, bits, mant_fin); + let exp = self.s.m.select(c, is_special, k0, exp_fin); + (self.as_float(mant_bits), exp) + } + // ---- lane booleans ---- fn boolean(&mut self, b: Bool, at: usize) -> Result { @@ -4004,6 +4058,16 @@ impl<'a> Lower<'a> { }; float(self, r) } + "v_frexp_mant_f32" => { + let a = f(self, 0)?; + let (mant, _) = self.frexp_f32(a); + float(self, mant) + } + "v_frexp_exp_i32_f32" => { + let a = f(self, 0)?; + let (_, exp) = self.frexp_f32(a); + int(self, exp) + } "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => { let mut a = f(self, 0)?; if name == "v_cvt_rpi_i32_f32" { @@ -4438,6 +4502,7 @@ impl<'a> Lower<'a> { "v_rndne_f16", "v_sin_f16", "v_cos_f16", + "v_frexp_mant_f16", "v_cvt_f16_u16", "v_cvt_f16_i16", ]; @@ -4457,6 +4522,7 @@ impl<'a> Lower<'a> { "v_cvt_i16_f16", "v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16", + "v_frexp_exp_i16_f16", ]; let all = [FLOAT1, FLOAT2, FLOAT3, INT]; if !all.iter().any(|l| l.contains(&name)) @@ -4570,6 +4636,10 @@ impl<'a> Lower<'a> { let one = self.s.m.f32(1.0f32.to_bits()); self.s.m.bin(c, Bin::SDiv, one, a) } + "v_frexp_mant_f16" => { + let a = self.half_fsrc(inst, 0)?; + self.frexp_f32(a).0 + } _ => { let a = self.half_fsrc(inst, 0)?; let op = match name { @@ -4602,6 +4672,14 @@ impl<'a> Lower<'a> { let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?; return self.write_half(inst, r, guard); } + if name == "v_frexp_exp_i16_f16" { + if v.clamp || v.omod != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + let a = self.half_fsrc(inst, 0)?; + let (_, exp) = self.frexp_f32(a); + return self.write_half(inst, exp, 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"); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..e4e5319 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -937,3 +937,113 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +#[test] +fn v_frexp_f32_and_f16_match_rdna2() { + // VOP1 opcodes: 0x3f=v_frexp_exp_i32_f32, 0x40=v_frexp_mant_f32, + // 0x59=v_frexp_mant_f16, 0x5a=v_frexp_exp_i16_f16. + let exp_f32 = build_valu_cs(&[vop1(0x3f, 0, vgpr(1))]); + let mant_f32 = build_valu_cs(&[vop1(0x40, 0, vgpr(1))]); + // For f16 tests, initialize v0 = 0xDEAD_0000 so we also verify high-half preservation. + let mant_f16 = build_valu_cs(&[ + vop1(0x001, 0, vgpr(2)), // v_mov_b32 v0, v2 (sentinel upper half) + vop1(0x59, 0, vgpr(1)), + ]); + let exp_f16 = build_valu_cs(&[ + vop1(0x001, 0, vgpr(2)), // v_mov_b32 v0, v2 (sentinel upper half) + vop1(0x5a, 0, vgpr(1)), + ]); + + // (input f32 bits, expected mantissa f32 bits, expected i32 exponent) + let f32_cases: &[(u32, u32, i32)] = &[ + (0.0f32.to_bits(), 0.0f32.to_bits(), 0), + ((-0.0f32).to_bits(), (-0.0f32).to_bits(), 0), + (0.5f32.to_bits(), 0.5f32.to_bits(), 0), + (1.0f32.to_bits(), 0.5f32.to_bits(), 1), + ((-6.0f32).to_bits(), (-0.75f32).to_bits(), 3), + (0.125f32.to_bits(), 0.5f32.to_bits(), -2), + (f32::INFINITY.to_bits(), f32::INFINITY.to_bits(), 0), + (f32::NEG_INFINITY.to_bits(), f32::NEG_INFINITY.to_bits(), 0), + // Subnormals: 2^-127 = 0.5 * 2^-126; 3 * 2^-149 = 0.75 * 2^-147; -2^-149 = -0.5 * 2^-148 + (0x0040_0000, 0.5f32.to_bits(), -126), + (0x0000_0003, 0.75f32.to_bits(), -147), + (0x8000_0001, (-0.5f32).to_bits(), -148), + ]; + let f32_in: Vec<[u32; 4]> = f32_cases.iter().map(|&(x, _, _)| [x, 0, 0, 0]).collect(); + run_cases(&mant_f32, &f32_in, |backend, i, inp, got| { + let want = f32_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_frexp_mant_f32({:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); + run_cases(&exp_f32, &f32_in, |backend, i, inp, got| { + let want = f32_cases[i].2 as u32; + assert_eq!( + got, want, + "{backend}: v_frexp_exp_i32_f32({:#010x}) = {} ({got:#010x}), want {}", + inp[0], got as i32, f32_cases[i].2, + ); + }); + + // NaN: mantissa stays NaN, exponent is 0. + let qnan = 0x7FC0_0000u32; + run_cases(&mant_f32, &[[qnan, 0, 0, 0]], |backend, _, _, got| { + assert!( + f32::from_bits(got).is_nan(), + "{backend}: v_frexp_mant_f32(NaN) = {got:#010x}, want NaN", + ); + }); + run_cases(&exp_f32, &[[qnan, 0, 0, 0]], |backend, _, _, got| { + assert_eq!(got, 0, "{backend}: v_frexp_exp_i32_f32(NaN) = {got}, want 0"); + }); + + // f16 cases: (input f16, expected mantissa f16, expected i16 exponent) + // 0x0000=+0, 0x8000=-0, 0x3800=0.5, 0x3C00=1.0, 0xC600=-6.0 (-0.75 * 2^3, -0.75=0xBA00), + // 0x7BFF=65504 (max f16 -> mant=0x3BFF, exp=16), 0x0001=2^-24 (min subnormal -> 0.5 * 2^-23), + // 0x8003=-3*2^-24 (-0.75 * 2^-22), 0x7C00=+inf, 0xFC00=-inf. + let sentinel = 0xDEAD_0000u32; + let f16_cases: &[(u16, u16, i16)] = &[ + (0x0000, 0x0000, 0), + (0x8000, 0x8000, 0), + (0x3800, 0x3800, 0), + (0x3C00, 0x3800, 1), + (0xC600, 0xBA00, 3), + (0x7BFF, 0x3BFF, 16), + (0x0001, 0x3800, -23), + (0x8003, 0xBA00, -22), + (0x7C00, 0x7C00, 0), + (0xFC00, 0xFC00, 0), + ]; + let f16_in: Vec<[u32; 4]> = f16_cases + .iter() + .map(|&(x, _, _)| [u32::from(x), sentinel, 0, 0]) + .collect(); + run_cases(&mant_f16, &f16_in, |backend, i, inp, got| { + let want = sentinel | u32::from(f16_cases[i].1); + assert_eq!( + got, want, + "{backend}: v_frexp_mant_f16({:#06x}) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); + run_cases(&exp_f16, &f16_in, |backend, i, inp, got| { + let want = sentinel | u32::from(f16_cases[i].2 as u16); + assert_eq!( + got, want, + "{backend}: v_frexp_exp_i16_f16({:#06x}) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); + + // f16 NaN: mantissa is f16 NaN (upper half preserved), exponent is 0. + run_cases(&mant_f16, &[[0x7E00, sentinel, 0, 0]], |backend, _, _, got| { + assert_eq!(got & 0xFFFF_0000, sentinel); + let lo = (got & 0x7FFF) as u16; + assert!(lo > 0x7C00, "{backend}: v_frexp_mant_f16(NaN) lo={lo:#06x}, want NaN"); + }); + run_cases(&exp_f16, &[[0x7E00, sentinel, 0, 0]], |backend, _, _, got| { + assert_eq!(got, sentinel, "{backend}: v_frexp_exp_i16_f16(NaN) = {got:#010x}, want 0"); + }); +} From 89670357c408980f314d52cd5a944b28a46666cd Mon Sep 17 00:00:00 2001 From: DenRakEiw <89697885+DenRakEiw@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:23:48 +0100 Subject: [PATCH 17/25] Shaders: lower v_sad_u8, v_msad_u8, v_sad_u16, and v_sad_u32 with clamp support --- crates/victory-shader/src/emit/lower.rs | 65 +++++++++++++++ crates/victory-shader/src/emit/valu_tests.rs | 87 ++++++++++++++++++++ 2 files changed, 152 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..2092d05 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4253,6 +4253,28 @@ impl<'a> Lower<'a> { ); int(self, r) } + "v_sad_u8" | "v_msad_u8" | "v_sad_u16" | "v_sad_u32" => { + if v.omod != 0 || v.abs != 0 || v.neg != 0 { + return Err("integer output modifiers"); + } + let (a, b, acc) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let delta = match name { + "v_sad_u8" | "v_msad_u8" => self.sad_lanes(a, b, 8, 4, name == "v_msad_u8"), + "v_sad_u16" => self.sad_lanes(a, b, 16, 2, false), + _ => self.abs_diff_u32(a, b), + }; + let mut r = self.s.m.bin(c, Bin::Add, acc, delta); + if v.clamp { + let over = self.s.m.cmp(c, pred::IULT, r, acc); + let max = self.s.m.i32(u32::MAX); + r = self.s.m.select(c, over, max, r); + } + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a result without a register"); + }; + self.write(inst, Reg::V(reg), r, guard); + Ok(()) + } _ => { let r = self.integer(inst, name)?; int(self, r) @@ -4260,6 +4282,49 @@ impl<'a> Lower<'a> { } } + /// `|a - b|` for unsigned 32-bit values. + fn abs_diff_u32(&mut self, a: V, b: V) -> V { + let c = self.cur; + let ab = self.s.m.bin(c, Bin::Sub, a, b); + let ba = self.s.m.bin(c, Bin::Sub, b, a); + let ge = self.s.m.cmp(c, pred::IUGE, a, b); + self.s.m.select(c, ge, ab, ba) + } + + /// Sum of unsigned absolute differences across `lanes` packed elements of + /// `bits` width (`8` or `16`). With `masked`, lanes where `a`'s element is + /// zero contribute 0 (`v_msad_u8`). + fn sad_lanes(&mut self, a: V, b: V, bits: u32, lanes: u32, masked: bool) -> V { + let c = self.cur; + let mask = self.s.m.i32((1u32 << bits) - 1); + let zero = self.s.m.i32(0); + let mut total = zero; + for lane in 0..lanes { + let (xa, xb) = if lane == 0 { + (a, b) + } else { + let sh = self.s.m.i32(lane * bits); + ( + self.s.m.bin(c, Bin::LShr, a, sh), + self.s.m.bin(c, Bin::LShr, b, sh), + ) + }; + let xa = self.s.m.bin(c, Bin::And, xa, mask); + let xb = self.s.m.bin(c, Bin::And, xb, mask); + let mut diff = self.abs_diff_u32(xa, xb); + if masked { + let is_zero = self.s.m.cmp(c, pred::EQ, xa, zero); + diff = self.s.m.select(c, is_zero, zero, diff); + } + total = if lane == 0 { + diff + } else { + self.s.m.bin(c, Bin::Add, total, diff) + }; + } + total + } + /// A 64-bit source (a register pair; inline constants sign-extend). fn src64(&mut self, inst: &Inst, k: usize) -> Result { let Fields::Valu(v) = &inst.fields else { diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..1a68b35 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -937,3 +937,90 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +#[test] +fn v_sad_family_matches_rdna2() { + let vop3_clamp = |op: u16| -> [u32; 2] { + let [mut w0, w1] = vop3(op, 0, vgpr(1), vgpr(2), vgpr(3)); + w0 |= 1 << 15; // clamp = 1 + [w0, w1] + }; + + // v_sad_u8 (0x15a) + let sad_u8 = build_valu_cs(&vop3(0x15a, 0, vgpr(1), vgpr(2), vgpr(3))); + let sad_u8_clamp = build_valu_cs(&vop3_clamp(0x15a)); + // Bytes: |0x10-0x20|=16, |0xFF-0x00|=255, |0x05-0x05|=0, |0x80-0x70|=16 -> sum = 287 + run_cases( + &sad_u8, + &[ + [0x8005_FF10, 0x7005_0020, 100, 0], + [0xFFFF_FFFF, 0x0000_0000, u32::MAX - 10, 0], // wraps: (2^32 - 11) + 1020 = 1009 + ], + |backend, i, _, got| { + let want = [387u32, 1009][i]; + assert_eq!(got, want, "{backend}: v_sad_u8 case {i}"); + }, + ); + run_cases( + &sad_u8_clamp, + &[[0xFFFF_FFFF, 0x0000_0000, u32::MAX - 10, 0]], // saturates to u32::MAX + |backend, _, _, got| { + assert_eq!(got, u32::MAX, "{backend}: v_sad_u8 clamp"); + }, + ); + + // v_msad_u8 (0x171): zero bytes in src0 contribute 0 regardless of src1. + let msad_u8 = build_valu_cs(&vop3(0x171, 0, vgpr(1), vgpr(2), vgpr(3))); + // Byte 0: src0=0x00 -> skipped (even though src1=0xFF) + // Byte 1: |0x10-0x00| = 16 (src1=0 is NOT skipped!) + // Byte 2: src0=0x00 -> skipped + // Byte 3: |0x80-0x70| = 16 -> sum = 32 + run_cases( + &msad_u8, + &[[0x8000_1000, 0x70AA_00FF, 5, 0]], + |backend, _, _, got| { + assert_eq!(got, 37, "{backend}: v_msad_u8"); + }, + ); + + // v_sad_u16 (0x15c) + let sad_u16 = build_valu_cs(&vop3(0x15c, 0, vgpr(1), vgpr(2), vgpr(3))); + let sad_u16_clamp = build_valu_cs(&vop3_clamp(0x15c)); + // Low: |0x0100 - 0x0300| = 0x200; High: |0xFFFF - 0x0001| = 0xFFFE -> sum = 0x101FE + run_cases( + &sad_u16, + &[[0xFFFF_0100, 0x0001_0300, 2, 0]], + |backend, _, _, got| { + assert_eq!(got, 0x10200, "{backend}: v_sad_u16"); + }, + ); + run_cases( + &sad_u16_clamp, + &[[0xFFFF_FFFF, 0x0000_0000, u32::MAX - 5, 0]], + |backend, _, _, got| { + assert_eq!(got, u32::MAX, "{backend}: v_sad_u16 clamp"); + }, + ); + + // v_sad_u32 (0x15d) + let sad_u32 = build_valu_cs(&vop3(0x15d, 0, vgpr(1), vgpr(2), vgpr(3))); + let sad_u32_clamp = build_valu_cs(&vop3_clamp(0x15d)); + run_cases( + &sad_u32, + &[ + [10, 30, 5, 0], + [0xFFFF_FFFF, 0, 10, 0], // wraps: (2^32 - 1) + 10 = 9 + ], + |backend, i, _, got| { + let want = [25u32, 9][i]; + assert_eq!(got, want, "{backend}: v_sad_u32 case {i}"); + }, + ); + run_cases( + &sad_u32_clamp, + &[[0xFFFF_FFFF, 0, 10, 0]], + |backend, _, _, got| { + assert_eq!(got, u32::MAX, "{backend}: v_sad_u32 clamp"); + }, + ); +} From 7dffb2a6c245c1ee68efd602be5cd0934e9ee0f9 Mon Sep 17 00:00:00 2001 From: ESAT Date: Tue, 24 Nov 2026 19:26:11 +0300 Subject: [PATCH 18/25] Shaders: lower v_mad_{u16,i16} and saturating clamp on 16-bit integer ops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI-generated & verified with Gemini 4 Neon (High Mode) — not written by a human engineer. - Add `v_mad_u16` (VOP3 0x340) and `v_mad_i16` (VOP3 0x35e) to `valu16` / `valu16_op` in `crates/victory-shader/src/emit/lower.rs`, preserving the untouched half of the destination VGPR via `write_half`. - Allow saturating `v.clamp` on `v_add_nc_u16`, `v_sub_nc_u16`, `v_subrev_nc_u16`, `v_mad_u16`, and `v_mad_i16` (clamping to `[0, 65535]` for unsigned and `[-32768, 32767]` for signed in 32-bit intermediate precision). Non-saturating 16-bit integer ops continue to reject `v.clamp`. Verified with synthetic GPU + WARP + dxil.dll tests in `valu_tests.rs` on NVIDIA GeForce RTX 3060 Ti (Windows 11, Rust 1.98.1). No game data used. Co-Authored-By: Gemini 4 Neon (High Mode) --- crates/victory-shader/src/emit/lower.rs | 42 ++++++++- crates/victory-shader/src/emit/valu_tests.rs | 92 ++++++++++++++++++++ 2 files changed, 132 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..35372e0 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4446,6 +4446,8 @@ impl<'a> Lower<'a> { "v_sub_nc_u16", "v_subrev_nc_u16", "v_mul_lo_u16", + "v_mad_u16", + "v_mad_i16", "v_lshlrev_b16", "v_lshrrev_b16", "v_ashrrev_i16", @@ -4603,7 +4605,11 @@ impl<'a> Lower<'a> { 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 { + let saturates = matches!( + name, + "v_add_nc_u16" | "v_sub_nc_u16" | "v_subrev_nc_u16" | "v_mad_u16" | "v_mad_i16" + ); + if (v.clamp && !saturates) || v.omod != 0 || v.abs != 0 || v.neg != 0 { return Err("modifiers on a 16-bit integer operation"); } let r = match name { @@ -4637,11 +4643,19 @@ impl<'a> Lower<'a> { b = sext(self, b); } let k15 = self.s.m.i32(15); - match name { + let r = 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_mad_u16" | "v_mad_i16" => { + let mut d = self.half_src(inst, 2)?; + if name == "v_mad_i16" { + d = sext(self, d); + } + let m = self.s.m.bin(c, Bin::Mul, a, b); + self.s.m.bin(c, Bin::Add, m, d) + } "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); @@ -4667,6 +4681,30 @@ impl<'a> Lower<'a> { let t = self.s.m.cmp(c, p, a, b); self.s.m.select(c, t, a, b) } + }; + if v.clamp && saturates { + match name { + "v_add_nc_u16" | "v_mad_u16" => { + let hi = self.s.m.i32(0xFFFF); + let over = self.s.m.cmp(c, pred::IUGT, r, hi); + self.s.m.select(c, over, hi, r) + } + "v_sub_nc_u16" | "v_subrev_nc_u16" => { + let z = self.s.m.i32(0); + let under = self.s.m.cmp(c, pred::SLT, r, z); + self.s.m.select(c, under, z, r) + } + _ => { + let lo = self.s.m.i32(i32::from(i16::MIN) as u32); + let hi = self.s.m.i32(i32::from(i16::MAX) as u32); + let under = self.s.m.cmp(c, pred::SLT, r, lo); + let t = self.s.m.select(c, under, lo, r); + let over = self.s.m.cmp(c, pred::SGT, t, hi); + self.s.m.select(c, over, hi, t) + } + } + } else { + r } } }; diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..a00a743 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -937,3 +937,95 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +#[test] +fn v_mad_16_and_int16_clamp_match_rdna2() { + let vop3_clamp = |op: u16, s0: u16, s1: u16, s2: u16, clamp: bool| { + let [mut w0, w1] = vop3(op, 0, s0, s1, s2); + if clamp { + w0 |= 1 << 15; + } + [w0, w1] + }; + let with_sentinel = |words: [u32; 2]| { + build_valu_cs(&[ + vop1(0x001, 0, vgpr(4)), // v_mov_b32 v0, v4 (sentinel upper half) + words[0], + words[1], + ]) + }; + + // VOP3 opcodes: 0x303=v_add_nc_u16, 0x304=v_sub_nc_u16, 0x340=v_mad_u16, 0x35e=v_mad_i16. + let mad_u16_wrap = with_sentinel(vop3_clamp(0x340, vgpr(1), vgpr(2), vgpr(3), false)); + let mad_u16_sat = with_sentinel(vop3_clamp(0x340, vgpr(1), vgpr(2), vgpr(3), true)); + let mad_i16_wrap = with_sentinel(vop3_clamp(0x35e, vgpr(1), vgpr(2), vgpr(3), false)); + let mad_i16_sat = with_sentinel(vop3_clamp(0x35e, vgpr(1), vgpr(2), vgpr(3), true)); + let add_u16_sat = with_sentinel(vop3_clamp(0x303, vgpr(1), vgpr(2), 0, true)); + let sub_u16_sat = with_sentinel(vop3_clamp(0x304, vgpr(1), vgpr(2), 0, true)); + + let sentinel = 0xBEEF_0000u32; + + // v_mad_u16 wrapping & saturating (including u16::MAX * u16::MAX + u16::MAX without u32 wrap) + let u_cases: &[(u16, u16, u16, u16, u16)] = &[ + (20, 30, 40, 640, 640), + (300, 300, 100, (90_100u32 & 0xFFFF) as u16, u16::MAX), + (u16::MAX, u16::MAX, u16::MAX, 0, u16::MAX), + ]; + let u_in: Vec<[u32; 4]> = u_cases + .iter() + .map(|&(a, b, c, _, _)| [u32::from(a), u32::from(b), u32::from(c), sentinel]) + .collect(); + run_cases(&mad_u16_wrap, &u_in, |backend, i, _, got| { + let want = sentinel | u32::from(u_cases[i].3); + assert_eq!(got, want, "{backend}: v_mad_u16 wrap case {i}"); + }); + run_cases(&mad_u16_sat, &u_in, |backend, i, _, got| { + let want = sentinel | u32::from(u_cases[i].4); + assert_eq!(got, want, "{backend}: v_mad_u16 clamp case {i}"); + }); + + // v_mad_i16 wrapping & saturating (positive & negative overflow extremes) + let i_cases: &[(i16, i16, i16, i16, i16)] = &[ + (-10, 20, 50, -150, -150), + (i16::MIN, i16::MIN, i16::MAX, i16::MAX, i16::MAX), + (i16::MIN, i16::MAX, i16::MIN, 0, i16::MIN), + (200, 200, 100, (40_100i32 as i16), i16::MAX), + (-200, 200, -100, (-40_100i32 as i16), i16::MIN), + ]; + let i_in: Vec<[u32; 4]> = i_cases + .iter() + .map(|&(a, b, c, _, _)| [u32::from(a as u16), u32::from(b as u16), u32::from(c as u16), sentinel]) + .collect(); + run_cases(&mad_i16_wrap, &i_in, |backend, i, _, got| { + let want = sentinel | u32::from(i_cases[i].3 as u16); + assert_eq!(got, want, "{backend}: v_mad_i16 wrap case {i}"); + }); + run_cases(&mad_i16_sat, &i_in, |backend, i, _, got| { + let want = sentinel | u32::from(i_cases[i].4 as u16); + assert_eq!(got, want, "{backend}: v_mad_i16 clamp case {i}"); + }); + + // v_add_nc_u16 clamp & v_sub_nc_u16 clamp + run_cases( + &add_u16_sat, + &[ + [60000, 10000, 0, sentinel], + [123, 456, 0, sentinel], + ], + |backend, i, _, got| { + let want = sentinel | [u32::from(u16::MAX), 579][i]; + assert_eq!(got, want, "{backend}: v_add_nc_u16 clamp case {i}"); + }, + ); + run_cases( + &sub_u16_sat, + &[ + [5, 10, 0, sentinel], + [500, 200, 0, sentinel], + ], + |backend, i, _, got| { + let want = sentinel | [0, 300][i]; + assert_eq!(got, want, "{backend}: v_sub_nc_u16 clamp case {i}"); + }, + ); +} From ba532339235f404ae6d60b6cb39152373422c1fc Mon Sep 17 00:00:00 2001 From: ESAT Date: Tue, 24 Nov 2026 19:31:45 +0300 Subject: [PATCH 19/25] Shaders: lower v_ldexp_f16 (VOP2 0x3b and VOP3 0x13b) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI-generated & verified with Gemini 4 Neon (High Mode) — not written by a human engineer. Lower `v_ldexp_f16` (`D.f16 = S0.f16 * 2^(S1.i16)`) in `valu16` / `valu16_op`: - Widens `S0` via `half_fsrc` (exact for all f16 normals and subnormals, honoring `opsel[0]`, `abs[0]`, `neg[0]`) and sign-extends `S1` from 16 bits via `half_src`. - Clamps the exponent to `[-64, 64]` and constructs `2^e` directly as a normal finite f32 (`(e + 127) << 23`), so `±0 * finite = ±0` (never `0 * inf = NaN`), `±inf * finite = ±inf` (never `inf * 0 = NaN`), and extreme exponents (`i16::MIN` / `i16::MAX`) overflow/underflow f16 cleanly without intermediate f32 faults. - Writes back via `float_result` (honoring `clamp`, `opsel[3]`, and preserving the untouched half of the destination VGPR). Verified with synthetic GPU + WARP + dxil.dll tests in `valu_tests.rs` on NVIDIA GeForce RTX 3060 Ti (Windows 11, Rust 1.98.1). No game data used. Co-Authored-By: Gemini 4 Neon (High Mode) --- crates/victory-shader/src/emit/lower.rs | 45 ++++++++++- crates/victory-shader/src/emit/valu_tests.rs | 78 ++++++++++++++++++++ 2 files changed, 122 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..1350749 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4460,7 +4460,7 @@ impl<'a> Lower<'a> { ]; let all = [FLOAT1, FLOAT2, FLOAT3, INT]; if !all.iter().any(|l| l.contains(&name)) - && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16") + && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16" | "v_ldexp_f16") { return None; } @@ -4502,6 +4502,49 @@ impl<'a> Lower<'a> { let f = self.fsrc(inst, 0)?; return float_result(self, f); } + if name == "v_ldexp_f16" { + // D.f16 = S0.f16 * 2^(S1.i16). S1 is a signed 16-bit integer exponent, + // so float abs/neg modifiers apply only to S0. + if (v.abs | v.neg) & 2 != 0 { + return Err("float modifier on v_ldexp_f16 exponent"); + } + let a = self.half_fsrc(inst, 0)?; + let raw_e = self.half_src(inst, 1)?; + let k16 = self.s.m.i32(16); + let e = self.s.m.bin(c, Bin::Shl, raw_e, k16); + let e = self.s.m.bin(c, Bin::AShr, e, k16); + // Clamp exponent to [-64, 64] so 2^e is always a normal finite f32: + // - +-0 * finite = +-0 (never 0 * inf = NaN), + // - +-inf * finite = +-inf (never inf * 0 = NaN), + // - min f16 (2^-24) * 2^64 overflows f16 to +-inf, + // - max f16 (~2^16) * 2^-64 underflows f16 to +-0. + let lo = self.s.m.i32((-64i32) as u32); + let hi = self.s.m.i32(64); + let under = self.s.m.cmp(c, pred::SLT, e, lo); + let e = self.s.m.select(c, under, lo, e); + let over = self.s.m.cmp(c, pred::SGT, e, hi); + let e = self.s.m.select(c, over, hi, e); + let bias = self.s.m.i32(127); + let k23 = self.s.m.i32(23); + let biased = self.s.m.bin(c, Bin::Add, e, bias); + let scale_bits = self.s.m.bin(c, Bin::Shl, biased, k23); + let scale = self.as_float(scale_bits); + let r = self.s.m.bin(c, Bin::Mul, a, scale); + // DXIL `legacyF32ToF16` rounds toward zero on NVIDIA/WARP and clamps finite + // values >= 65536 to 0x7BFF (max finite f16). Under RDNA2's default RTE mode, + // |r| >= 65520.0 (the f16 overflow threshold) overflows to signed infinity. + let abs_r = self.unary(6, r); + let ov_thresh = self.s.m.f32(65520.0f32.to_bits()); + let overflows = self.s.m.cmp(c, pred::OGE, abs_r, ov_thresh); + let r_bits = self.as_int(r); + let sign_mask = self.s.m.i32(0x8000_0000); + let inf_bits = self.s.m.i32(0x7F80_0000); + let r_sign = self.s.m.bin(c, Bin::And, r_bits, sign_mask); + let signed_inf_bits = self.s.m.bin(c, Bin::Or, r_sign, inf_bits); + let signed_inf = self.as_float(signed_inf_bits); + let r = self.s.m.select(c, overflows, signed_inf, r); + return float_result(self, r); + } if float2.contains(&name) { let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?); let r = match name { diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..5b777e0 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -937,3 +937,81 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +/// VOP2 `op vdst, src0, vsrc1`. +const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) +} + +#[test] +fn v_ldexp_f16_matches_rdna2() { + // VOP2 `v_ldexp_f16 v0, v1, v2` (opcode 0x3b), preserving upper half from v3. + let vop2_cs = build_valu_cs(&[ + vop1(0x001, 0, vgpr(3)), // v_mov_b32 v0, v3 (sentinel upper half) + vop2(0x3b, 0, vgpr(1), 2), // v_ldexp_f16 v0, v1, v2 + ]); + // VOP3 `v_ldexp_f16 v0, |v1|, v2 clamp` (opcode 0x13b) with op_sel:[1, 0, 0, 1] + // (reads high half of v1, low half of v2, writes high half of v0). + let [mut w0, w1] = vop3(0x13b, 0, vgpr(1), vgpr(2), 0); + w0 |= (1 << 8) | (1 << 11) | (1 << 14) | (1 << 15); // abs[0], opsel[0], opsel[3], clamp + let vop3_cs = build_valu_cs(&[ + vop1(0x001, 0, vgpr(3)), // v_mov_b32 v0, v3 (sentinel lower half) + w0, + w1, + ]); + + let sentinel = 0xCAFE_0000u32; + // (f16 input, i16 exponent, expected f16 output) + let cases: &[(u16, i16, u16)] = &[ + (0x3C00, 0, 0x3C00), // 1.0 * 2^0 = 1.0 + (0x3E00, 3, 0x4A00), // 1.5 * 2^3 = 12.0 + (0xC200, -2, 0xBA00), // -3.0 * 2^-2 = -0.75 + (0x3C00, -15, 0x0200), // 1.0 * 2^-15 = f16 subnormal 0x0200 + (0x0001, 24, 0x3C00), // min f16 subnormal (2^-24) * 2^24 = 1.0 + (0x7BFF, 0, 0x7BFF), // max finite f16 * 2^0 stays 65504 (no premature inf) + (0x3C00, 16, 0x7C00), // 1.0 * 2^16 = 65536 -> +inf (RTE overflow) + (0xBC00, 1000, 0xFC00), // -1.0 * 2^1000 -> -inf + (0x0001, i16::MAX, 0x7C00), // min subnormal * 2^32767 -> +inf + (0x7BFF, i16::MIN, 0x0000), // max finite * 2^-32768 -> +0.0 + (0xFBFF, i16::MIN, 0x8000), // -max finite * 2^-32768 -> -0.0 + (0x0000, i16::MAX, 0x0000), // +0.0 * 2^32767 = +0.0 (not NaN) + (0x8000, i16::MAX, 0x8000), // -0.0 * 2^32767 = -0.0 (not NaN) + (0x7C00, i16::MIN, 0x7C00), // +inf * 2^-32768 = +inf (not NaN) + (0xFC00, i16::MIN, 0xFC00), // -inf * 2^-32768 = -inf (not NaN) + ]; + let inputs: Vec<[u32; 4]> = cases + .iter() + .map(|&(a, e, _)| [u32::from(a), u32::from(e as u16), sentinel, 0]) + .collect(); + run_cases(&vop2_cs, &inputs, |backend, i, _, got| { + let (a, e, want_h) = cases[i]; + let want = sentinel | u32::from(want_h); + assert_eq!( + got, want, + "{backend}: v_ldexp_f16({a:#06x}, {e}) = {got:#010x}, want {want:#010x}", + ); + }); + + // NaN stays NaN (upper half preserved). + run_cases(&vop2_cs, &[[0x7E00, 4, sentinel, 0]], |backend, _, _, got| { + assert_eq!(got & 0xFFFF_0000, sentinel); + let lo = (got & 0x7FFF) as u16; + assert!(lo > 0x7C00, "{backend}: v_ldexp_f16(NaN, 4) lo={lo:#06x}, want NaN"); + }); + + // VOP3 abs[0] + opsel:[1,0,0,1] + clamp: + // |-0.25(=0xB400)| * 2^1 = 0.5 (0x3800) into high half; |-1.0(=0xBC00)| * 2^2 = 4.0 -> clamped 1.0 (0x3C00) + let lo_sentinel = 0x0000_1234u32; + let vop3_cases: &[([u32; 4], u32)] = &[ + ([0xB400_0000, 1, lo_sentinel, 0], (0x3800u32 << 16) | lo_sentinel), + ([0xBC00_0000, 2, lo_sentinel, 0], (0x3C00u32 << 16) | lo_sentinel), + ]; + let vop3_in: Vec<[u32; 4]> = vop3_cases.iter().map(|c| c.0).collect(); + run_cases(&vop3_cs, &vop3_in, |backend, i, _, got| { + let want = vop3_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_ldexp_f16_e64 case {i} = {got:#010x}, want {want:#010x}", + ); + }); +} From a3346f97d6f4dc762a97f7acf4882867c0bff99c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 17:41:15 +0100 Subject: [PATCH 20/25] Shaders: implicit-level samples in compute take their gradients from the quad A console compute program may sample with an implicit level of detail (image_sample, image_sample_b): the hardware takes the coordinates' coarse derivatives across each quad of lanes. As DXIL `sample` and `sampleBias`, these programs failed validation with "Function uses features incompatible with the shader stage (cs) of the entry function". The gradients are now read from the quad (lane 1 less lane 0, lane 2 less lane 0, through waveReadLaneAt) and passed to `sampleGrad`; a bias scales them by 2^bias. Pixel and mesh shaders are unchanged. `victory translate --validate` over the title's shaders on Windows (dxil.dll 10.0.26100), on top of #439: compute programs validated go from 1,658 to 2,193 of 2,193 emitted; no other count changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SDn5GupcrERtCYPyoztdtG --- crates/victory-shader/src/emit/lower.rs | 61 +++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..8b27e8d 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2028,6 +2028,32 @@ impl<'a> Lower<'a> { r } + /// The x then y gradients (three each, undefined past `coords`) of + /// float coordinates `coords` across this lane's quad: lane 1 less lane + /// 0, lane 2 less lane 0, as the hardware's coarse derivatives. + fn quad_gradients(&mut self, coords: &[V]) -> Vec { + self.s.flags |= flags::WAVE_OPS; + let c = self.cur; + let fu = self.s.m.undef(self.s.t.f32); + let lane = self.lane_index(); + let (not3, one, two) = (self.s.m.i32(!3), self.s.m.i32(1), self.s.m.i32(2)); + let base = self.s.m.bin(c, Bin::And, lane, not3); + let right = self.s.m.bin(c, Bin::Or, base, one); + let below = self.s.m.bin(c, Bin::Or, base, two); + 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 v = l.read_lane(xi, lane); + l.as_float(v) + }; + let (x0, x1, x2) = (at(self, base), at(self, right), at(self, below)); + g[k] = self.s.m.bin(c, Bin::Sub, x1, x0); + g[3 + k] = self.s.m.bin(c, Bin::Sub, x2, x0); + } + g + } + fn read_lane(&mut self, x: V, lane: V) -> V { self.s.op( self.cur, @@ -5923,7 +5949,42 @@ impl<'a> Lower<'a> { } let mut args = vec![h, sh]; args.extend(&cs); + // In compute shaders an implicit level of detail comes from + // the lanes' quads, as the hardware takes it: DXIL derivatives + // there need conditions the validator does not grant these + // programs, so the gradients are read from the quad and the + // sample takes them explicitly. + let quad_grads = matches!(op, 60 | 61) + && self.s.threads.is_some() + && self.s.mesh.is_none() + && kind != 5; match op { + 60 | 61 if quad_grads => { + let mut g = self.quad_gradients(&cs[..spatial]); + if op == 61 { + // A bias scales the footprint by 2^bias. + let bias = addr_val(self, 0)?; + let bias = self.as_float(bias); + let scale = self.unary(21, bias); + for x in g.iter_mut().filter(|x| **x != fu) { + *x = self.s.m.bin(c, Bin::Mul, *x, scale); + } + } + if offset_word { + return Err("a sample offset outside a pixel shader"); + } + args.extend(&os); + args.extend(g); + args.push(fu); + self.s.op( + c, + "sampleGrad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 63, + &args, + ) + } 60 => { if offset_word { // DXIL takes immediate offsets in -8..=7; the From 891f5b6bc4ed0301f651e5de47d7e2fad77481a9 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 17:52:39 +0000 Subject: [PATCH 21/25] Fix wave-3 test helpers for post-#1198 signatures Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../src/emit/image_atomic_tests.rs | 7 +- crates/victory-shader/src/emit/mod.rs | 2 + crates/victory-shader/src/emit/valu_tests.rs | 249 ++++++++++++++++++ 3 files changed, 256 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/image_atomic_tests.rs b/crates/victory-shader/src/emit/image_atomic_tests.rs index 0be8ed7..827f8ce 100644 --- a/crates/victory-shader/src/emit/image_atomic_tests.rs +++ b/crates/victory-shader/src/emit/image_atomic_tests.rs @@ -111,9 +111,10 @@ fn build(op: u8, pair: bool) -> 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, @@ -134,6 +135,8 @@ fn build(op: u8, pair: bool) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + address_map: false, + descriptor_words: false, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 3aa328f..30c5582 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -946,6 +946,8 @@ mod tests { samplers: l.samplers, root_cbvs: l.root_cbvs, root_srvs: l.root_srvs, + address_map: false, + descriptor_words: false, }; #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 95ae23c..53e0f0c 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1802,3 +1802,252 @@ fn paired_lds_write2_b64() { fn paired_lds_write2st64_b64() { check_lds_paired_write("ds_write2st64_b64", 0x4F, 2, true); } + +const fn vop3p(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16, clamp: bool) -> [u32; 2] { + [ + 0x33 << 26 + | (op as u32 & 0x7F) << 16 + | (clamp as u32) << 15 + | (1 << 14) // opsel_hi[2] = 1 + | vdst as u32, + (0b11 << 27) // opsel_hi[1:0] = 0b11 + | (src0 as u32 & 0x1FF) + | (src1 as u32 & 0x1FF) << 9 + | (src2 as u32 & 0x1FF) << 18, + ] +} + +const fn sopk(op: u8, sdst: u8, simm16: i16) -> u32 { + 0xB000_0000 | (op as u32 & 0x1F) << 23 | (sdst as u32 & 0x7F) << 16 | (simm16 as u16) as u32 +} + +fn run_signed_scc_cases( + name: &str, + body: &[u32], + operands: &[(i32, i32)], + reference: impl Fn(i32, i32) -> (i32, bool), +) { + let mut words = body.to_vec(); + words.extend([ + 0xBF85_0001, // s_cbranch_scc1 over the next instruction + s_mov_b32(2, 0x80), // s2 = 0 when SCC is clear + sop2(0x12, 7, 6, 2), // s_xor_b32 s7, s6, s2 + vop1(0x001, 0, sgpr(7)), // v_mov_b32 v0, s7 + ]); + let shader = build_valu_cs(&words); + // First read the arithmetic result unchanged, then toggle its high bit + // only when SCC is set. This checks both outputs with the single-dword UAV. + let inputs: Vec<_> = operands + .iter() + .flat_map(|&(a, b)| [[a as u32, b as u32, 0, 0], [a as u32, b as u32, 1 << 31, 0]]) + .collect(); + run_cases(&shader, &inputs, |backend, _, [a, b, mask, _], got| { + let (result, overflow) = reference(a as i32, b as i32); + let expected = result as u32 ^ if overflow { mask } else { 0 }; + assert_eq!( + got, expected, + "{backend}: {name}({:#010x}, {:#010x}), SCC mask {mask:#010x}", + a, b, + ); + }); +} + +fn check_lds_paired_write(name: &str, write_op: u32, width: usize, stride64: bool) { + const LANES: u32 = 64; + const DWORDS_PER_LANE: usize = 4; + const WAIT_LDS: u32 = 0xBF8C_C07F; // s_waitcnt lgkmcnt(0) + let inputs = [0x1234_5678, 0x9ABC_DEF0, 0x0BAD_F00D, 0xFEED_BEEF]; + let read_op = if width == 1 { 0x36 } else { 0x76 }; + let scale = 4 * width as u32 * if stride64 { 64 } else { 1 }; + let data1 = 1 + width as u32; + for same_offset in [false, true] { + // Each lane starts at its own aligned 16-byte offset. Use a + // separation of at least 1024 bytes for the st64 accesses. + let distinct_offset = if stride64 { 6 } else { 3 }; + let offsets = [2, if same_offset { 2 } else { distinct_offset }]; + let mut body = Vec::from(vop3(0x11A, 0, 132, vgpr(0), 0)); // v0 = thread id << 4 + body.extend([ + 0x36 << 26 | write_op << 18 | offsets[0] | offsets[1] << 8, + 1 << 8 | data1 << 16, // Address = v0, DATA0 = v1, DATA1 = v2 or v3. + WAIT_LDS, + ]); + for (element, &offset) in offsets.iter().enumerate() { + body.extend([ + 0x36 << 26 | read_op << 18 | (offset * scale), + 5 << 24, + WAIT_LDS, + ]); + let [mut store, operands] = buffer_store_dword(5, 8, 8 * element as u16); + store |= 1 << 12; // offen: v0 is the per-lane byte offset. + if width == 2 { + store |= 1 << 18; // buffer_store_dwordx2 + } + body.extend([store, operands]); + } + let shader = build_test_cs( + &body, + ComputeIo { + rsrc2: (5 << 1) | (8 << 15), // 5 user SGPRs, 4096 bytes of LDS. + threads: [LANES, 1, 1], + }, + &[], + ); + run_output_cases( + &shader, + &[inputs], + LANES * DWORDS_PER_LANE as u32, + |backend, _, _, out| { + let second = if same_offset { 0 } else { width }; + assert_eq!(out.len(), LANES as usize * DWORDS_PER_LANE); + let (lanes, _) = out.as_chunks::(); + for (lane, values) in lanes.iter().enumerate() { + assert_eq!( + &values[..width], + &inputs[..width], + "{backend}: {name}, offsets {offsets:?}, lane {lane}, DATA0" + ); + assert_eq!( + &values[2..2 + width], + &inputs[second..second + width], + "{backend}: {name}, offsets {offsets:?}, lane {lane}, second value" + ); + } + }, + ); + } +} + +fn build_test_cs(body: &[u32], compute: ComputeIo, result_store: &[u32]) -> HostShader { + 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(result_store); + 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(compute), + 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, + }) + .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, + address_map: false, + descriptor_words: false, + }; + + 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"); + } + + shader +} + +fn run_output_cases( + shader: &HostShader, + cases: &[[u32; 4]], + output_dwords: u32, + mut check: impl FnMut(&str, usize, [u32; 4], &[u32]), +) { + 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}")); + for (i, &inputs) in cases.iter().enumerate() { + 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 out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(output_dwords)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + check(label, i, inputs, &out[0]); + } + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} From 69428c844cc21b73c8150e0ec99e11fd18326adc Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 17:54:18 +0000 Subject: [PATCH 22/25] Prefix cfg(windows)-only bindings with underscore Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-shader/src/emit/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 30c5582..6926be7 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1165,12 +1165,12 @@ mod tests { }) )); // s3 is uninitialized on entry and reads as zero, passing DXIL validation. - let out = try_emit(rsrc2, 3).unwrap(); + let _out = try_emit(rsrc2, 3).unwrap(); #[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(); } // Enabling SCRATCH_EN (bit 0) initializes s3 (scratch wave offset), so // s3 is refused again while s4 reads as zero. @@ -1181,12 +1181,12 @@ mod tests { .. }) )); - let out = try_emit(rsrc2 | 1, 4).unwrap(); + let _out = try_emit(rsrc2 | 1, 4).unwrap(); #[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(); } } } From adc9d8ff866ede8bc4030864da674f140b87cb84 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 17:57:37 +0000 Subject: [PATCH 23/25] Build test HostShader from lowered fields (static samplers, address map, descriptor words) Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-shader/src/emit/image_atomic_tests.rs | 6 +++--- crates/victory-shader/src/emit/mod.rs | 4 ++-- crates/victory-shader/src/emit/valu_tests.rs | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/victory-shader/src/emit/image_atomic_tests.rs b/crates/victory-shader/src/emit/image_atomic_tests.rs index 827f8ce..d2d741e 100644 --- a/crates/victory-shader/src/emit/image_atomic_tests.rs +++ b/crates/victory-shader/src/emit/image_atomic_tests.rs @@ -131,12 +131,12 @@ fn build(op: u8, pair: bool) -> HostShader { stage: HwStage::Cs, dxil: lowered.dxil, user_data: lowered.user_data, + static_samplers: super::build_static_samplers(&lowered.samplers, &lowered.cmp_samplers), samplers: lowered.samplers, - static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, - address_map: false, - descriptor_words: false, + address_map: lowered.address_map, + descriptor_words: lowered.descriptor_words, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 6926be7..ac21619 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -946,8 +946,8 @@ mod tests { samplers: l.samplers, root_cbvs: l.root_cbvs, root_srvs: l.root_srvs, - address_map: false, - descriptor_words: false, + address_map: l.address_map, + descriptor_words: l.descriptor_words, }; #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 53e0f0c..ff5fafb 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -144,8 +144,8 @@ fn build_valu_cs(body: &[u32]) -> HostShader { stage: HwStage::Cs, dxil: lowered.dxil, user_data: lowered.user_data, + static_samplers: super::build_static_samplers(&lowered.samplers, &lowered.cmp_samplers), samplers: lowered.samplers, - static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, address_map: lowered.address_map, @@ -1990,12 +1990,12 @@ fn build_test_cs(body: &[u32], compute: ComputeIo, result_store: &[u32]) -> Host stage: HwStage::Cs, dxil: lowered.dxil, user_data: lowered.user_data, + static_samplers: super::build_static_samplers(&lowered.samplers, &lowered.cmp_samplers), samplers: lowered.samplers, - static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, - address_map: false, - descriptor_words: false, + address_map: lowered.address_map, + descriptor_words: lowered.descriptor_words, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { From 0880b8fc1ed80d8659e81bfe7c09778f34a9d34c Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 18:01:47 +0000 Subject: [PATCH 24/25] ci: retrigger check job Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> From 5c75cf28793f0c67c807c181abf8fb26df2c1df0 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 18:04:27 +0000 Subject: [PATCH 25/25] Serialize image-atomic host tests on ONE_AT_A_TIME Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-shader/src/emit/image_atomic_tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/victory-shader/src/emit/image_atomic_tests.rs b/crates/victory-shader/src/emit/image_atomic_tests.rs index d2d741e..a4ebdbf 100644 --- a/crates/victory-shader/src/emit/image_atomic_tests.rs +++ b/crates/victory-shader/src/emit/image_atomic_tests.rs @@ -149,6 +149,9 @@ fn build(op: u8, pair: bool) -> HostShader { /// returns and the texel it leaves against `want(start, data, compare)`. fn check(name: &str, op: u8, pair: bool, cases: &[[u32; 3]], want: impl Fn(u32, u32, u32) -> u32) { let shader = build(op, pair); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); let mut ran = 0; for (label, warp) in [("hardware", false), ("warp", true)] { let Ok(host) = Host::new(warp) else {