From d04de8abebdc3da70e8fb49b79b13c3761999564 Mon Sep 17 00:00:00 2001 From: diego Date: Mon, 23 Nov 2026 21:32:30 -0300 Subject: [PATCH 1/3] Shaders: byte and halfword LDS reads and writes ds_read_{u,i}{8,16}, their _d16/_d16_hi forms, and ds_write_b{8,16} (and _d16_hi) went untranslated. Reads load the dword holding the data, shift it down and extend it; the d16 forms fill one half of the VGPR and keep the other, which the IR now records as a read of the destination. Writes clear the bytes and set them with two atomics, so lanes writing other bytes of the same dword at once keep theirs. Synthetic GFX10 compute programs check every form against a model of the console's LDS on the host GPU and WARP, including 64 lanes writing neighbouring bytes of shared dwords. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lds_tests.rs | 442 ++++++++++++++++++++ crates/victory-shader/src/emit/lower.rs | 170 +++++++- crates/victory-shader/src/emit/mod.rs | 2 + crates/victory-shader/src/ir.rs | 4 + 4 files changed, 617 insertions(+), 1 deletion(-) create mode 100644 crates/victory-shader/src/emit/lds_tests.rs diff --git a/crates/victory-shader/src/emit/lds_tests.rs b/crates/victory-shader/src/emit/lds_tests.rs new file mode 100644 index 0000000000..82cb181d86 --- /dev/null +++ b/crates/victory-shader/src/emit/lds_tests.rs @@ -0,0 +1,442 @@ +//! Byte and halfword LDS accesses: synthetic GFX10 compute programs lowered +//! to DXIL (validated by `dxil.dll` when present) and run on the host GPU and +//! WARP, against a model of the console's LDS. + +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; +/// `s_waitcnt` with every counter at 0. +const S_WAITCNT_0: u32 = 0xBF8C_0000; +const S_BARRIER: u32 = 0xBF8A_0000; + +/// Inline constants as source operands. +const fn int(n: i8) -> u16 { + if n >= 0 { + 128 + n as u16 + } else { + (192 - n as i16) as u16 + } +} + +const fn vgpr(n: u8) -> u16 { + 256 + n as u16 +} + +/// SOP1 `s_mov_b32 sdst, src0`. +const fn s_mov_b32(sdst: u8, src0: u16) -> u32 { + 0xBE80_0000 | (sdst as u32) << 16 | 0x03 << 8 | (src0 as u32 & 0xFF) +} + +/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], 0`. +const fn s_load_dwordx4(dst: u8, base: u8) -> [u32; 2] { + [ + 0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), + 125 << 25, + ] +} + +/// VOP1 `op vdst, src0`. +const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { + 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) +} + +/// VOP2 `op vdst, src0, vsrc1`. +const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) +} + +const fn v_mov_b32(vdst: u8, src0: u16) -> u32 { + vop1(0x001, vdst, src0) +} +const fn v_lshlrev_b32(vdst: u8, shift: u16, v: u8) -> u32 { + vop2(0x1A, vdst, shift, v) +} +const fn v_and_b32(vdst: u8, src0: u16, v: u8) -> u32 { + vop2(0x1B, vdst, src0, v) +} +const fn v_add_nc_u32(vdst: u8, src0: u16, v: u8) -> u32 { + vop2(0x25, vdst, src0, v) +} + +/// DS `op [vdst,] addr [, data0] offset:offset`. +const fn ds(op: u8, vdst: u8, addr: u8, data0: u8, offset: u16) -> [u32; 2] { + [ + 0x36 << 26 | (op as u32) << 18 | offset as u32, + (vdst as u32) << 24 | (data0 as u32) << 8 | addr as u32, + ] +} + +/// MUBUF `buffer_store_dword vdata, vaddr, s[srsrc:srsrc+3], 0 offen`. +const fn buffer_store_dword_offen(vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | 0x1C << 18 | 1 << 12, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] +} + +const DS_WRITE_B32: u8 = 0x0D; +const DS_READ_B32: u8 = 0x36; + +/// The byte and halfword opcodes: (name, opcode). +const READS: &[(&str, u8)] = &[ + ("ds_read_i8", 0x39), + ("ds_read_u8", 0x3A), + ("ds_read_i16", 0x3B), + ("ds_read_u16", 0x3C), + ("ds_read_u8_d16", 0xA2), + ("ds_read_u8_d16_hi", 0xA3), + ("ds_read_i8_d16", 0xA4), + ("ds_read_i8_d16_hi", 0xA5), + ("ds_read_u16_d16", 0xA6), + ("ds_read_u16_d16_hi", 0xA7), +]; +const WRITES: &[(&str, u8)] = &[ + ("ds_write_b8", 0x1E), + ("ds_write_b16", 0x1F), + ("ds_write_b8_d16_hi", 0xA0), + ("ds_write_b16_d16_hi", 0xA1), +]; + +/// A compute program of `threads` lanes (waves of 32) with 512 bytes of +/// LDS: the thread id in `v0`, the 4 root constants in `v1..v4`; `body` +/// leaves each lane's result in `v5`, stored to dword `thread id` of the +/// raw UAV at heap index 0. +fn build_cs(body: &[u32], threads: u32) -> HostShader { + let mut words = vec![s_mov_b32(5, int(0))]; + words.extend_from_slice(&s_load_dwordx4(8, 4)); + for i in 0..4u8 { + words.push(v_mov_b32(i + 1, u16::from(i))); + } + words.extend_from_slice(body); + words.push(v_lshlrev_b32(6, int(2), 0)); + words.extend_from_slice(&buffer_store_dword_offen(5, 6, 8)); + words.push(S_ENDPGM); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 16, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + // 5 user SGPRs, thread id x only, one 512-byte LDS granule. + rsrc2: 5 << 1 | 1 << 15, + threads: [threads, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = + resource::track(&p, &native.layout, native.stage, Some(&st)).expect("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, + }; + 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"); + assert_eq!(copy[4..20], ours[..], "container hash"); + } + shader +} + +/// Each available host (GPU, WARP), for running shaders on, with the lock +/// that keeps GPU tests from running at once; hold it while using them. +fn hosts() -> ( + std::sync::MutexGuard<'static, ()>, + Vec<(&'static str, Host)>, +) { + let one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let hosts: Vec<_> = [("hardware", false), ("warp", true)] + .into_iter() + .filter_map(|(label, warp)| match Host::new(warp) { + Ok(h) => Some((label, h)), + Err(_) => { + eprintln!("no SM 6.6 {label} device; skipped"); + None + } + }) + .collect(); + (one, hosts) +} + +/// Runs `shader` with root constants `k` and returns the first `threads` +/// dwords of its UAV. +fn run(label: &str, host: &Host, shader: &HostShader, k: [u32; 4], threads: u32) -> Vec { + let (root, pso) = host + .compute_pipeline(shader) + .unwrap_or_else(|e| panic!("{label}: pipeline: {e}")); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) => k[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(threads)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch: {e}")); + out[0][..threads as usize].to_vec() +} + +/// Accesses a halfword (else a byte); `_d16` names a VGPR half, not a width. +fn halfword(name: &str) -> bool { + ["u16", "i16", "b16"] + .iter() + .any(|t| name.split('_').any(|p| p == *t)) +} + +/// The console's result of a byte or halfword read of `lds` at `at`, into +/// a VGPR holding `old`. +fn model_read(name: &str, lds: &[u8], at: usize, old: u32) -> u32 { + let wide = halfword(name); + let x = if wide { + u32::from(u16::from_le_bytes([lds[at], lds[at + 1]])) + } else { + u32::from(lds[at]) + }; + let x = match (name.contains("_i"), wide) { + (true, true) => x as u16 as i16 as i32 as u32, + (true, false) => x as u8 as i8 as i32 as u32, + _ => x, + }; + if name.ends_with("_d16_hi") { + old & 0xFFFF | x << 16 + } else if name.ends_with("_d16") { + old & 0xFFFF_0000 | x & 0xFFFF + } else { + x + } +} + +fn model_write(name: &str, lds: &mut [u8], at: usize, data: u32) { + let d = if name.ends_with("_d16_hi") { + data >> 16 + } else { + data + }; + let n = if halfword(name) { 2 } else { 1 }; + lds[at..at + n].copy_from_slice(&d.to_le_bytes()[..n]); +} + +/// Two waves: no host wave size is asked for (WARP has no 32-lane waves), +/// and LDS is shared across waves. +const LANES: u32 = 64; + +const DWORD0: u32 = 0x8281_7F01; +const DWORD1: u32 = 0xFEDC_BA98; +const OLD: u32 = 0x1234_5678; + +fn initial_lds() -> Vec { + [DWORD0, DWORD1] + .iter() + .flat_map(|d| d.to_le_bytes()) + .collect() +} + +/// Byte addresses (before the instruction's offset of 2) for an access of +/// `name`'s width: every byte of two dwords, or every halfword. +fn addresses(name: &str) -> Vec { + let step = if halfword(name) { 2 } else { 1 }; + (0..6).step_by(step).collect() +} + +#[test] +fn byte_and_halfword_reads() { + let (_one, hosts) = hosts(); + for &(name, op) in READS { + // Two dwords of LDS from v1/v2, then the read at v3 + 2 into v5, + // which holds v4 first (the half a d16 read keeps). + let mut body = vec![v_mov_b32(7, int(0))]; + body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 1, 0)); + body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 2, 4)); + body.push(S_WAITCNT_0); + body.push(S_BARRIER); + body.push(v_mov_b32(5, vgpr(4))); + body.extend_from_slice(&ds(op, 5, 3, 0, 2)); + body.push(S_WAITCNT_0); + let shader = build_cs(&body, LANES); + let lds = initial_lds(); + for (label, host) in &hosts { + for at in addresses(name) { + let got = run(label, host, &shader, [DWORD0, DWORD1, at, OLD], LANES); + let want = model_read(name, &lds, at as usize + 2, OLD); + for (lane, g) in got.into_iter().enumerate() { + assert_eq!( + g, want, + "{label}: {name} at {at}+2, lane {lane}: {g:#010x}, want {want:#010x}" + ); + } + } + } + } +} + +#[test] +fn byte_and_halfword_writes() { + let (_one, hosts) = hosts(); + for &(name, op) in WRITES { + // Two dwords of LDS from v1/v2, the write of v4 at v3 + 2 (the same + // in every lane), then the dword holding it read back. + let mut body = vec![v_mov_b32(7, int(0))]; + body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 1, 0)); + body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 2, 4)); + body.push(S_WAITCNT_0); + body.push(S_BARRIER); + body.extend_from_slice(&ds(op, 0, 3, 4, 2)); + body.push(S_WAITCNT_0); + body.push(S_BARRIER); + body.push(v_add_nc_u32(9, int(2), 3)); + body.push(v_and_b32(9, int(-4), 9)); + body.extend_from_slice(&ds(DS_READ_B32, 5, 9, 0, 0)); + body.push(S_WAITCNT_0); + let shader = build_cs(&body, LANES); + for (label, host) in &hosts { + for at in addresses(name) { + let at = at as usize + 2; + let mut lds = initial_lds(); + model_write(name, &mut lds, at, OLD); + let d = at & !3; + let want = u32::from_le_bytes(lds[d..d + 4].try_into().unwrap()); + let k = [DWORD0, DWORD1, at as u32 - 2, OLD]; + for (lane, g) in run(label, host, &shader, k, LANES).into_iter().enumerate() { + assert_eq!( + g, want, + "{label}: {name} at {at}, lane {lane}: {g:#010x}, want {want:#010x}" + ); + } + } + } + } +} + +/// Every lane writes its own bytes of dwords the other lanes write too: +/// none of them is lost. +#[test] +fn lanes_share_dwords() { + let (_one, hosts) = hosts(); + for &(name, op) in WRITES { + let wide = halfword(name); + // v10 = thread id + v1 (in the high half for _d16_hi), written at + // thread id × width; then each lane reads back a dword of them. + let mut body = vec![v_add_nc_u32(10, vgpr(0), 1)]; + if name.ends_with("_d16_hi") { + body.push(v_lshlrev_b32(10, int(16), 10)); + } + body.push(if wide { + v_lshlrev_b32(11, int(1), 0) + } else { + v_mov_b32(11, vgpr(0)) + }); + body.extend_from_slice(&ds(op, 0, 11, 10, 0)); + body.push(S_WAITCNT_0); + body.push(S_BARRIER); + let dwords = LANES * if wide { 2 } else { 1 } / 4; + body.push(v_and_b32(9, int(dwords as i8 - 1), 0)); + body.push(v_lshlrev_b32(9, int(2), 9)); + body.extend_from_slice(&ds(DS_READ_B32, 5, 9, 0, 0)); + body.push(S_WAITCNT_0); + let shader = build_cs(&body, LANES); + let base = 0x0000_A0F0; + let mut lds = vec![0u8; LANES as usize * 2]; + for lane in 0..LANES { + let data = lane + base; + let data = if name.ends_with("_d16_hi") { + data << 16 + } else { + data + }; + let at = (lane * if wide { 2 } else { 1 }) as usize; + model_write(name, &mut lds, at, data); + } + for (label, host) in &hosts { + let got = run(label, host, &shader, [base, 0, 0, 0], LANES); + for (lane, &g) in got.iter().enumerate() { + let d = (lane % dwords as usize) * 4; + let want = u32::from_le_bytes(lds[d..d + 4].try_into().unwrap()); + assert_eq!( + g, want, + "{label}: {name}, lane {lane}: {g:#010x}, want {want:#010x}" + ); + } + } + } +} + +/// The opcodes above decode to their names. +#[test] +fn opcodes() { + let named = [("ds_write_b32", DS_WRITE_B32), ("ds_read_b32", DS_READ_B32)]; + for &(name, op) in READS.iter().chain(WRITES).chain(&named) { + let code: Vec = ds(op, 5, 3, 4, 2) + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let code = [&code[..], &S_ENDPGM.to_le_bytes()].concat(); + let inst = &crate::gfx10::decode(&code).expect("decode")[0]; + assert_eq!(inst.name(), Some(name)); + } +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd804b0..a64ed85483 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -342,6 +342,50 @@ fn unsupported(offset: usize, what: Why) -> Stop { Stop::Fail(ShaderError::Unsupported { offset, what }) } +/// A byte or halfword LDS access: `ds_read_{u,i}{8,16}[_d16[_hi]]` and +/// `ds_write_b{8,16}[_d16_hi]`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct SubDword { + write: bool, + bits: u32, + /// Reads: sign-extended. + signed: bool, + /// Reads: the result is 16 bits wide and goes into one half of the VGPR, + /// the other half kept (`Some(true)`: the high half). Writes: the data + /// comes from the high half (`Some(true)`). + d16: Option, +} + +impl SubDword { + fn of(name: &str) -> Option { + let (write, rest) = match name.strip_prefix("ds_read_") { + Some(r) => (false, r), + None => (true, name.strip_prefix("ds_write_")?), + }; + let (ty, d16) = match rest.split_once("_d16") { + None => (rest, None), + Some((t, "")) if !write => (t, Some(false)), + Some((t, "_hi")) => (t, Some(true)), + Some(_) => return None, + }; + let (signed, bits) = match (write, ty) { + (false, "u8") => (false, 8), + (false, "i8") => (true, 8), + (false, "u16") => (false, 16), + (false, "i16") => (true, 16), + (true, "b8") => (false, 8), + (true, "b16") => (false, 16), + _ => return None, + }; + Some(Self { + write, + bits, + signed, + d16, + }) + } +} + impl<'a> Lower<'a> { fn new(x: &'a Parts<'a>, bad: &'a HashMap) -> Self { let p = x.p; @@ -2061,6 +2105,90 @@ impl<'a> Lower<'a> { .collect() } + /// A byte or halfword LDS read or write at byte address `a + offset`, + /// through the dword holding it. + #[allow(clippy::too_many_arguments)] + fn ds_sub_dword( + &mut self, + inst: &Inst, + sub: SubDword, + a: V, + offset: u32, + dst_reg: Option, + data: &[Operand], + guard: Option, + ) -> Result<(), Why> { + use super::bitcode::Rmw; + let c = self.cur; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + // shortcut: as for dwords, in bounds; a halfword is taken as + // 2-aligned (the bytes never straddle two dwords). + let o = k(self, offset); + let at = self.s.m.bin(c, Bin::Add, a, o); + let two = k(self, 2); + let index = self.s.m.bin(c, Bin::LShr, at, two); + let lds = self.s.lds(); + let p = self.s.m.element(c, lds, index); + let three = k(self, 3); + let byte = self.s.m.bin(c, Bin::And, at, three); + let shift = self.s.m.bin(c, Bin::Shl, byte, three); + let mask = k(self, (1 << sub.bits) - 1); + if !sub.write { + let reg = dst_reg.ok_or("an LDS read result")?; + let x = self.s.m.load(c, p); + let x = self.s.m.bin(c, Bin::LShr, x, shift); + let x = if sub.signed { + let up = k(self, 32 - sub.bits); + let x = self.s.m.bin(c, Bin::Shl, x, up); + self.s.m.bin(c, Bin::AShr, x, up) + } else { + self.s.m.bin(c, Bin::And, x, mask) + }; + let x = match sub.d16 { + None => x, + Some(high) => { + let old = inst.read(Reg::V(reg)).ok_or("an unread operand")?; + let old = self.i32_of(old)?; + let low16 = k(self, 0xFFFF); + let half = self.s.m.bin(c, Bin::And, x, low16); + if high { + let keep = self.s.m.bin(c, Bin::And, old, low16); + let sixteen = k(self, 16); + let half = self.s.m.bin(c, Bin::Shl, half, sixteen); + self.s.m.bin(c, Bin::Or, keep, half) + } else { + let high16 = k(self, 0xFFFF_0000); + let keep = self.s.m.bin(c, Bin::And, old, high16); + self.s.m.bin(c, Bin::Or, keep, half) + } + } + }; + self.write(inst, Reg::V(reg), x, guard); + return Ok(()); + } + let d = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0]; + let d = if sub.d16 == Some(true) { + let sixteen = k(self, 16); + self.s.m.bin(c, Bin::LShr, d, sixteen) + } else { + d + }; + let d = self.s.m.bin(c, Bin::And, d, mask); + let set = self.s.m.bin(c, Bin::Shl, d, shift); + let bits = self.s.m.bin(c, Bin::Shl, mask, shift); + let ones = k(self, !0); + let clear = self.s.m.bin(c, Bin::Xor, bits, ones); + // Lanes write other bytes of the same dword at the same time, so + // the bytes go in atomically: cleared, then set. shortcut: lanes + // writing the same bytes at once leave both values or-ed together + // where the console keeps one of them. + let at = self.begin_guarded(guard); + self.s.m.atomic(self.cur, Rmw::And, p, clear); + self.s.m.atomic(self.cur, Rmw::Or, p, set); + self.end_guarded(at, &[]); + Ok(()) + } + /// LDS (thread-group shared memory) and `ds_swizzle`. fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { let Fields::Ds { @@ -2158,6 +2286,9 @@ impl<'a> Lower<'a> { (u32::from(*offset1) * scale, w), ] }; + if let Some(sub) = SubDword::of(name) { + return self.ds_sub_dword(inst, sub, a, offset, dst_reg, data, guard); + } if let Some(rest) = name.strip_prefix("ds_read") { let elements = if rest.starts_with('2') { pair(name) @@ -6947,7 +7078,7 @@ impl<'a> Lower<'a> { #[cfg(test)] mod tests { - use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; + use super::{Lowered, Numeric, Parts, SubDword, buffer_format, half_shift, lower}; use crate::native::{ ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, }; @@ -7326,6 +7457,43 @@ mod tests { lowers(&words, group_ids_xy).expect("dead timestamp"); } + #[test] + fn sub_dword_lds_names() { + let s = |write, bits, signed, d16| { + Some(SubDword { + write, + bits, + signed, + d16, + }) + }; + assert_eq!(SubDword::of("ds_read_i8"), s(false, 8, true, None)); + assert_eq!(SubDword::of("ds_read_u16"), s(false, 16, false, None)); + assert_eq!( + SubDword::of("ds_read_u8_d16"), + s(false, 8, false, Some(false)) + ); + assert_eq!( + SubDword::of("ds_read_i16_d16_hi"), + s(false, 16, true, Some(true)) + ); + assert_eq!(SubDword::of("ds_write_b8"), s(true, 8, false, None)); + assert_eq!( + SubDword::of("ds_write_b16_d16_hi"), + s(true, 16, false, Some(true)) + ); + for name in [ + "ds_read_b32", + "ds_read2_b32", + "ds_write_b64", + "ds_write_b8_d16", + "ds_read_u8_d32", + "ds_add_u32", + ] { + assert_eq!(SubDword::of(name), None, "{name}"); + } + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 89652da8f1..d20c2f7a8d 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 lds_tests; mod lower; mod sampler; mod shader; diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index cc73a49bb3..6597254789 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -840,6 +840,10 @@ fn effects( regs(o, &mut r)?; } if let Some(d) = dst { + // A 16-bit read keeps the other half of its VGPR. + if name.starts_with("ds_read") && name.contains("_d16") { + regs(d, &mut r)?; + } regs(d, &mut w)?; } if *gds From 8e39c10609e7b1399906280ac59dc7bd35fc5338 Mon Sep 17 00:00:00 2001 From: diego Date: Tue, 24 Nov 2026 14:34:29 -0300 Subject: [PATCH 2/3] Shaders: drop the extra d16 read of the LDS destination The IR already records every vector instruction's destination as a read (for the lanes it leaves alone), so a ds_read_*_d16* sees the half it keeps without a rule of its own. The d16 tests pass on the GPU and WARP without it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/ir.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 6597254789..cc73a49bb3 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -840,10 +840,6 @@ fn effects( regs(o, &mut r)?; } if let Some(d) = dst { - // A 16-bit read keeps the other half of its VGPR. - if name.starts_with("ds_read") && name.contains("_d16") { - regs(d, &mut r)?; - } regs(d, &mut w)?; } if *gds From c853a6ab38df8dbb1755e39ad3ed5903ed378cbc Mon Sep 17 00:00:00 2001 From: diego Date: Tue, 24 Nov 2026 15:47:18 -0300 Subject: [PATCH 3/3] Shaders: halfword LDS accesses straddling two dwords A halfword at byte 3 of a dword takes its high byte from byte 0 of the next one: an RDNA2 measurement on the PR showed the hardware reads (and writes) the two bytes at the address across the dword boundary, where the lowering took halfwords as 2-aligned. Reads now also load the next dword and writes clear and set its byte with two more atomics; neither adds a branch or loop. The tests run every form at every byte address from 2 to 7, odd and straddling halfwords included, over three dwords of LDS, and the write test reads back the next dword as well. They fail on the previous lowering and pass on the GPU and WARP. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lds_tests.rs | 47 ++++++++++++--------- crates/victory-shader/src/emit/lower.rs | 47 +++++++++++++++++++-- 2 files changed, 71 insertions(+), 23 deletions(-) diff --git a/crates/victory-shader/src/emit/lds_tests.rs b/crates/victory-shader/src/emit/lds_tests.rs index 82cb181d86..a0ae3effe1 100644 --- a/crates/victory-shader/src/emit/lds_tests.rs +++ b/crates/victory-shader/src/emit/lds_tests.rs @@ -290,31 +290,39 @@ const DWORD0: u32 = 0x8281_7F01; const DWORD1: u32 = 0xFEDC_BA98; const OLD: u32 = 0x1234_5678; +/// Three dwords: `DWORD0`, then `DWORD1` twice (the root constants hold +/// only two). fn initial_lds() -> Vec { - [DWORD0, DWORD1] + [DWORD0, DWORD1, DWORD1] .iter() .flat_map(|d| d.to_le_bytes()) .collect() } /// Byte addresses (before the instruction's offset of 2) for an access of -/// `name`'s width: every byte of two dwords, or every halfword. +/// `name`'s width: every byte from 2 to 7, odd and straddling halfwords too. fn addresses(name: &str) -> Vec { - let step = if halfword(name) { 2 } else { 1 }; - (0..6).step_by(step).collect() + (0..if halfword(name) { 5 } else { 6 }).collect() +} + +/// Writes the three dwords of `initial_lds` (`v7` = 0), then waits for them. +fn store_initial_lds(body: &mut Vec) { + body.push(v_mov_b32(7, int(0))); + body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 1, 0)); + body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 2, 4)); + body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 2, 8)); + body.push(S_WAITCNT_0); + body.push(S_BARRIER); } #[test] fn byte_and_halfword_reads() { let (_one, hosts) = hosts(); for &(name, op) in READS { - // Two dwords of LDS from v1/v2, then the read at v3 + 2 into v5, + // Three dwords of LDS from v1/v2, then the read at v3 + 2 into v5, // which holds v4 first (the half a d16 read keeps). - let mut body = vec![v_mov_b32(7, int(0))]; - body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 1, 0)); - body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 2, 4)); - body.push(S_WAITCNT_0); - body.push(S_BARRIER); + let mut body = vec![]; + store_initial_lds(&mut body); body.push(v_mov_b32(5, vgpr(4))); body.extend_from_slice(&ds(op, 5, 3, 0, 2)); body.push(S_WAITCNT_0); @@ -339,18 +347,19 @@ fn byte_and_halfword_reads() { fn byte_and_halfword_writes() { let (_one, hosts) = hosts(); for &(name, op) in WRITES { - // Two dwords of LDS from v1/v2, the write of v4 at v3 + 2 (the same - // in every lane), then the dword holding it read back. - let mut body = vec![v_mov_b32(7, int(0))]; - body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 1, 0)); - body.extend_from_slice(&ds(DS_WRITE_B32, 0, 7, 2, 4)); - body.push(S_WAITCNT_0); - body.push(S_BARRIER); + // Three dwords of LDS from v1/v2, the write of v4 at v3 + 2 (the + // same in every lane), then the dword holding it read back by even + // lanes and the next one by odd lanes. + let mut body = vec![]; + store_initial_lds(&mut body); body.extend_from_slice(&ds(op, 0, 3, 4, 2)); body.push(S_WAITCNT_0); body.push(S_BARRIER); body.push(v_add_nc_u32(9, int(2), 3)); body.push(v_and_b32(9, int(-4), 9)); + body.push(v_and_b32(12, int(1), 0)); + body.push(v_lshlrev_b32(12, int(2), 12)); + body.push(v_add_nc_u32(9, vgpr(12), 9)); body.extend_from_slice(&ds(DS_READ_B32, 5, 9, 0, 0)); body.push(S_WAITCNT_0); let shader = build_cs(&body, LANES); @@ -359,10 +368,10 @@ fn byte_and_halfword_writes() { let at = at as usize + 2; let mut lds = initial_lds(); model_write(name, &mut lds, at, OLD); - let d = at & !3; - let want = u32::from_le_bytes(lds[d..d + 4].try_into().unwrap()); let k = [DWORD0, DWORD1, at as u32 - 2, OLD]; for (lane, g) in run(label, host, &shader, k, LANES).into_iter().enumerate() { + let d = (at & !3) + 4 * (lane & 1); + let want = u32::from_le_bytes(lds[d..d + 4].try_into().unwrap()); assert_eq!( g, want, "{label}: {name} at {at}, lane {lane}: {g:#010x}, want {want:#010x}" diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index a64ed85483..a07562cf4a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2121,8 +2121,7 @@ impl<'a> Lower<'a> { use super::bitcode::Rmw; let c = self.cur; let k = |l: &mut Self, v: u32| l.s.m.i32(v); - // shortcut: as for dwords, in bounds; a halfword is taken as - // 2-aligned (the bytes never straddle two dwords). + // shortcut: as for dwords, in bounds. let o = k(self, offset); let at = self.s.m.bin(c, Bin::Add, a, o); let two = k(self, 2); @@ -2133,10 +2132,34 @@ impl<'a> Lower<'a> { let byte = self.s.m.bin(c, Bin::And, at, three); let shift = self.s.m.bin(c, Bin::Shl, byte, three); let mask = k(self, (1 << sub.bits) - 1); + // A halfword at byte 3 of a dword takes its high byte from byte 0 of + // the next, as the hardware reads and writes it (measured on RDNA2): + // `next` is that dword then, else the same one again, with nothing + // of it read or written. + let next = if sub.bits == 16 { + let straddle = self.s.m.cmp(c, pred::EQ, byte, three); + let one = k(self, 1); + let after = self.s.m.bin(c, Bin::Add, index, one); + let i = self.s.m.select(c, straddle, after, index); + Some((straddle, self.s.m.element(c, lds, i))) + } else { + None + }; + let zero = k(self, 0); + let eight = k(self, 8); if !sub.write { let reg = dst_reg.ok_or("an LDS read result")?; let x = self.s.m.load(c, p); let x = self.s.m.bin(c, Bin::LShr, x, shift); + let x = match next { + None => x, + Some((straddle, p2)) => { + let y = self.s.m.load(c, p2); + let y = self.s.m.bin(c, Bin::Shl, y, eight); + let y = self.s.m.select(c, straddle, y, zero); + self.s.m.bin(c, Bin::Or, x, y) + } + }; let x = if sub.signed { let up = k(self, 32 - sub.bits); let x = self.s.m.bin(c, Bin::Shl, x, up); @@ -2178,13 +2201,29 @@ impl<'a> Lower<'a> { let bits = self.s.m.bin(c, Bin::Shl, mask, shift); let ones = k(self, !0); let clear = self.s.m.bin(c, Bin::Xor, bits, ones); + // The high byte of a straddling halfword, for the next dword. + let high = match next { + None => None, + Some((straddle, p2)) => { + let byte_mask = k(self, 0xFF); + let bits2 = self.s.m.select(c, straddle, byte_mask, zero); + let clear2 = self.s.m.bin(c, Bin::Xor, bits2, ones); + let set2 = self.s.m.bin(c, Bin::LShr, d, eight); + let set2 = self.s.m.select(c, straddle, set2, zero); + Some((p2, clear2, set2)) + } + }; // Lanes write other bytes of the same dword at the same time, so // the bytes go in atomically: cleared, then set. shortcut: lanes - // writing the same bytes at once leave both values or-ed together - // where the console keeps one of them. + // writing the same bytes at once leave their values or-ed together + // where the hardware keeps the highest lane's (measured on RDNA2). let at = self.begin_guarded(guard); self.s.m.atomic(self.cur, Rmw::And, p, clear); self.s.m.atomic(self.cur, Rmw::Or, p, set); + if let Some((p2, clear2, set2)) = high { + self.s.m.atomic(self.cur, Rmw::And, p2, clear2); + self.s.m.atomic(self.cur, Rmw::Or, p2, set2); + } self.end_guarded(at, &[]); Ok(()) }