diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 8a3d6d15..ec8c8016 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -334,6 +334,51 @@ impl Module { V::Func(i) } + /// The names of the module's declared functions. + #[cfg(test)] + pub fn func_names(&self) -> impl Iterator { + self.funcs.iter().map(|f| f.name.as_str()) + } + + /// A line per instruction: its op and operands — `i7` an instruction, + /// `f2` a function, `k8` an integer constant, `c1` another constant, + /// `g3` a global. + #[cfg(test)] + pub fn inst_lines(&self) -> Vec { + let v = |m: &Self, x: V| -> String { + match x { + V::Inst(i) => format!("i{i}"), + V::Func(i) => format!("f{i}"), + V::Global(i) => format!("g{i}"), + V::Const(i) => match &m.consts[i as usize].1 { + Const::Int(n) => format!("k{n}"), + _ => format!("c{i}"), + }, + } + }; + self.insts + .iter() + .map(|i| match &i.op { + Op::Bin(op, a, b) => format!("bin:{op:?} {} {}", v(self, *a), v(self, *b)), + Op::Cast(op, a) => format!("cast:{op:?} {}", v(self, *a)), + Op::Cmp(p, a, b) => format!("cmp:{p} {} {}", v(self, *a), v(self, *b)), + Op::Select(c, t, f) => { + format!("select {} {} {}", v(self, *c), v(self, *t), v(self, *f)) + } + Op::Extract(a, i) => format!("extract {} {i}", v(self, *a)), + Op::Call(f, args) => { + let args = args + .iter() + .map(|&a| v(self, a)) + .collect::>() + .join(", "); + format!("call f{f} [{args}]") + } + op => format!("{op:?}"), + }) + .collect() + } + /// An external global of type `ty` in address space `space` (DXIL /// declares thread-group shared memory this way). pub fn global(&mut self, name: &str, ty: Ty, space: u32) -> V { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 0dfe8d80..55c2d7dd 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -62,6 +62,15 @@ pub(crate) struct Lowered { /// Test builds: the property words of each handle annotation, in order. #[cfg(test)] pub annotations: Vec<(u32, u32)>, + /// The names of the emitted functions (which dx.ops ran); tests only, + /// kept from #599 for tests of lane ops (none reads them here yet). + #[cfg(test)] + #[allow(dead_code)] + pub op_names: Vec, + /// The emitted instructions, one line each; tests only (see above). + #[cfg(test)] + #[allow(dead_code)] + pub insts: Vec, /// Test builds: typed loads assembled from a dword-aligned pair. #[cfg(test)] pub unaligned_typed_loads: u32, @@ -1400,6 +1409,10 @@ impl<'a> Lower<'a> { let stride_table = self.s.stride_table.is_some(); let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect(); let cmp_samplers = self.s.cmp_samplers; + #[cfg(test)] + let op_names = self.s.m.func_names().map(str::to_owned).collect(); + #[cfg(test)] + let insts = self.s.m.inst_lines(); Ok(Lowered { #[cfg(test)] annotations: std::mem::take(&mut self.s.annotations), @@ -1417,6 +1430,10 @@ impl<'a> Lower<'a> { dxil: self.s.finish(), user_data, samplers: self.samplers, + #[cfg(test)] + op_names, + #[cfg(test)] + insts, }) } @@ -1839,7 +1856,21 @@ impl<'a> Lower<'a> { xy } }; - Ok(if high { y } else { x }) + Ok(if high { + y + } else if self.mask_data == MaskData::Host && !self.x.native.wave64 { + // A wave32 program's host wave may still have 64 lanes, whose + // upper half is a second console wave: its bits are the ballot's + // second dword. + let lane = self.lane_index(); + let c = self.cur; + let k32 = self.s.m.i32(32); + let upper = self.s.m.cmp(c, pred::IUGE, lane, k32); + self.s.flags |= flags::WAVE_OPS; + self.s.m.select(c, upper, y, x) + } else { + x + }) } // ---- operands ---- @@ -2560,6 +2591,55 @@ impl<'a> Lower<'a> { .collect() } + /// The lane's own console wave's 32-lane base on a 64-lane host wave + /// (0 or 32): the renumbering a console lane number takes to stay a + /// host lane. + fn lane_base(&mut self) -> V { + let lane = self.lane_index(); + let k32 = self.s.m.i32(32); + self.s.m.bin(self.cur, Bin::And, lane, k32) + } + + /// A lane operand of a graphics program: a constant one is the console's, + /// so on a host wave wider than the program's each half is a console wave + /// and console lane `k` of the lane's own wave is `k | (lane & 32)`. A + /// computed one is refused: nothing marks whether it is a host lane + /// (`v_mbcnt`'s rank is) or an index within a 32-lane dword (a bit scan + /// of a mask read as data is), and lowering the wrong one reads another + /// lane. Compute keeps its own rule (console lanes relabel the wave). + fn console_lane_operand(&mut self, lane: V) -> Result { + if self.s.threads.is_none() && !matches!(lane, V::Const(_)) { + return Err("a computed lane in a pixel or vertex program"); + } + Ok(self.console_lane_operand_const(lane)) + } + + /// [`console_lane_operand`](Self::console_lane_operand)'s mapping, for a + /// lane already known to be the console's. + fn console_lane_operand_const(&mut self, lane: V) -> V { + if matches!(lane, V::Const(_)) && !self.x.native.wave64 { + let base = self.lane_base(); + self.s.m.bin(self.cur, Bin::Or, lane, base) + } else { + lane + } + } + + /// Refuses a constant lane that a host wave narrower than the program's + /// does not hold (a wave64 program's lane 40 on a 32-lane host): a + /// `WaveReadLaneAt` of a lane the wave does not have is undefined. No + /// emulation exists for those lanes yet (compute exchanges halves; + /// graphics stages have no such path). + fn lane_operand_checked(&self, lane: V) -> Result<(), Why> { + if self.s.threads.is_none() + && self.x.native.wave64 + && matches!(lane, V::Const(k) if k >= self.x.target.lanes_max) + { + return Err("a wave64 lane on a host wave narrower than the program's"); + } + Ok(()) + } + /// 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. @@ -2570,9 +2650,16 @@ impl<'a> Lower<'a> { // memory if mesh programs turn out to need these. return Err("a cross-lane operation in a mesh shader"); } - if self.s.threads.is_none() && !(quad && self.s.pixel) { - return Err("a cross-lane operation outside compute"); - } + // Compute, pixel and vertex programs all have the console's lanes on + // the host: a compute lane is relabelled to its console lane, and a + // pixel or vertex wave is lane for lane the console's when the host + // wave is the program's (the target is 32-64 lanes). `quad` marks the + // operations whose lanes all lie in one quad; the host has quads in + // every stage they are used in. A pixel shader's helper lanes are host + // lanes too: they take part in quads and in wave operations, so a read + // of one is what the host makes it, and what they compute is never + // written. + let _ = quad; debug_assert!(self.s.threads.is_none() || self.console_lanes); self.s.flags |= flags::WAVE_OPS; Ok(()) @@ -2916,6 +3003,15 @@ impl<'a> Lower<'a> { // console's, so quad-local swizzles read through quad operations. let mesh_quad = self.s.mesh.is_some() && quad; if !mesh_quad { + // A pixel shader has helper lanes at a primitive's edge, and a + // wave operation leaves them out: a swizzle that reads another + // quad can name one, and `WaveReadLaneAt` of a helper lane is + // undefined in SM 6.6 (helper participation is 6.7). Only the + // quad-local patterns are taken; `ds_bpermute` is safe because + // it zeroes a lane its ballot does not hold. + if self.s.pixel && !quad { + return Err("a swizzle across quads in a pixel shader"); + } self.cross_lane(quad)?; } // The source sits in the address field. @@ -4828,11 +4924,17 @@ impl<'a> Lower<'a> { self.rel_offset(sv, base, local)? } else if !self.split && self.runs_in_every_lane(v) { // The definition ran in every lane, so the lane it - // read was lane 0: the load's EXEC (possibly - // narrower, and not the definition's) does not - // change which lane that was. + // read was the wave's first: lane 0, or on a host + // wave wider than a graphics program's the base of + // the lane's own console wave. The load's EXEC + // (possibly narrower, and not the definition's) + // does not change which lane that was. let a = self.rel_offset_op(inst, op0, base, local)?; - let z = self.s.m.i32(0); + let z = if self.s.threads.is_none() && !self.x.native.wave64 { + self.lane_base() + } else { + self.s.m.i32(0) + }; self.read_lane(a, z) } else if self.console_cf { // The console wave's first lane, as `valu_op` @@ -4867,11 +4969,16 @@ impl<'a> Lower<'a> { } else { let a = self.rel_offset_op(inst, op0, base, local)?; let lane = self.operand(inst, op1)?; - if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) { + // The lane space is the main arm's: a computed + // one is a host lane, a constant one the console's + // of the lane's own wave. + let lane = if self.mask_data == MaskData::Host { self.s.flags |= flags::WAVE_OPS; + self.console_lane_operand(lane)? } else { self.cross_lane(false)?; - } + lane + }; if self.console_cf { self.console_read_lane(a, lane) } else { @@ -6166,11 +6273,16 @@ impl<'a> Lower<'a> { let (a, lane) = (s(self, 0)?, s(self, 1)?); // A computed lane in a pixel or vertex program is a host lane // (from a mask or `v_mbcnt`); a constant one is the console's. - if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) { + self.lane_operand_checked(lane)?; + let lane = if self.mask_data == MaskData::Host { self.s.flags |= flags::WAVE_OPS; + self.console_lane_operand(lane)? } else { self.cross_lane(false)?; - } + // A constant lane is the console's own, and the console's + // lane layout is the host's outside compute: no refusal. + lane + }; let r = if self.console_cf { self.console_read_lane(a, lane) } else { @@ -6188,7 +6300,16 @@ impl<'a> Lower<'a> { Some(o) => self.i32_of(o)?, None => self.s.m.i32(0), }; - self.cross_lane(false)?; + // The lane space is `v_readlane`'s: a host lane, or a + // console's constant lane of the lane's own wave. + self.lane_operand_checked(lane)?; + let lane = if self.mask_data == MaskData::Host { + self.s.flags |= flags::WAVE_OPS; + self.console_lane_operand(lane)? + } else { + lane + }; + self.s.flags |= flags::WAVE_OPS; let me = if self.console_cf { self.console_lane().0 } else { @@ -6218,14 +6339,28 @@ impl<'a> Lower<'a> { "v_readfirstlane_b32" => { let a = s(self, 0)?; self.s.flags |= flags::WAVE_OPS; - let r = self.s.op( - c, - "waveReadLaneFirst.i32", - Attr::NoUnwind, - self.s.t.i32, - 118, - &[a], - ); + let r = if self.mask_data == MaskData::Host && !self.x.native.wave64 { + // The first lane of the lane's own console wave: the low + // set bit of its half of the exec ballot, renumbered to + // a host lane. + let exec = inst.read(Reg::S(EXEC)).ok_or(LANE_MASK)?; + let d = self.mask_dword(exec)?; + let f = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[d]); + let base = self.lane_base(); + let first = self.s.m.bin(c, Bin::Or, f, base); + self.read_lane(a, first) + } else { + self.s.op( + c, + "waveReadLaneFirst.i32", + Attr::NoUnwind, + self.s.t.i32, + 118, + &[a], + ) + }; int(self, r) } _ => { @@ -7216,13 +7351,25 @@ impl<'a> Lower<'a> { } else if self.s.mesh.is_none() { self.cross_lane(false)?; } + // On a host wave wider than the console's the upper half is a + // second console wave: `lo` counts bits of the lane's own + // half's mask below its lane in it, and a wave32 mask's high + // half is empty. The count is a lane number, and lane numbers + // stay host lanes: a second wave's rank takes its 32-lane + // base, so `v_mbcnt_lo(-1)` is still the lane index. + let host_halves = self.mask_data == MaskData::Host && !self.x.native.wave64; let lane = if self.console_cf { self.console_lane().0 } else { self.lane_index() }; let below = if name == "v_mbcnt_lo_u32_b32" { - lane + if host_halves { + let k31 = k(self, 31); + self.s.m.bin(c, Bin::And, lane, k31) + } else { + lane + } } else { let (k32, z) = (k(self, 32), k(self, 0)); let t = self.s.m.bin(c, Bin::Sub, lane, k32); @@ -7236,10 +7383,20 @@ impl<'a> Lower<'a> { let m = self.s.m.bin(c, Bin::Sub, m, one); let full = self.s.m.cmp(c, pred::IUGE, below, k32); let m = self.s.m.select(c, full, ones, m); - let x = self.s.m.bin(c, Bin::And, a, m); + let x = if host_halves && name == "v_mbcnt_hi_u32_b32" { + k(self, 0) + } else { + self.s.m.bin(c, Bin::And, a, m) + }; let n = self .s .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]); + let n = if host_halves && name == "v_mbcnt_lo_u32_b32" { + let base = self.s.m.bin(c, Bin::And, lane, k32); + self.s.m.bin(c, Bin::Add, n, base) + } else { + n + }; self.s.m.bin(c, Bin::Add, n, b) } _ => return Err(name), diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 36bf2144..05f2f43d 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -2169,17 +2169,155 @@ mod barycentric_tests { let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); - let mut host = emit(&c, &native, &p, &st, &io, &res, Target::ANY).unwrap(); + let host = emit(&c, &native, &p, &st, &io, &res, Target::ANY).unwrap(); #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( super::validator::Validator::default_path().as_deref(), ) { - v.validate(&mut host.dxil).unwrap(); + let mut copy = host.dxil.clone(); + v.validate(&mut copy).unwrap(); } + // Off Windows there is no dxil.dll: the DXIL is what is checked. + #[cfg(not(windows))] + assert!(!host.dxil.is_empty()); } for opcode in [0xCC21_000B, 0xCC22_000B] { translate(opcode); } } + /// Cross-lane operations outside compute: a pixel program's lane-indexed + /// reads and writes, its mask bit count, its byte permute and its + /// swizzle all lower. They were refused with "a cross-lane operation + /// outside compute", which dropped every draw of the program. + #[test] + fn cross_lane_operations_lower_in_a_pixel_program() { + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let sig = super::container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &sig)]); + let c = Container::parse(&bytes).unwrap(); + let pixel = |words: &[u32]| -> Result { + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + emit(&c, &native, &p, &st, &io, &res, Target::ANY) + }; + // exp mrt0 of v, done vm, then s_endpgm. + let export = |reg: u32| [0xF800_180F, reg << 24 | reg << 16 | reg << 8 | reg, S_ENDPGM]; + let cases: [(&str, Vec); 5] = [ + ( + // v_readlane_b32 s4, v2, 5; v_mov_b32 v4, s4 + "v_readlane_b32 of a constant lane", + [ + vec![0x7E04_02F2, 0xD760_0004, 0x0001_0B02, 0x7E08_0204], + export(4).to_vec(), + ] + .concat(), + ), + ( + // v_writelane_b32 v5, 7, 5 + "v_writelane_b32 of a constant lane", + [vec![0x7E04_02F2, 0xD761_0005, 0x0001_0A87], export(5).to_vec()].concat(), + ), + ( + // v_mbcnt_lo_u32_b32 v5, -1, 0: the lane index + "v_mbcnt_lo_u32_b32 of an all-ones mask", + [vec![0xD765_0005, 0x0001_00C1], export(5).to_vec()].concat(), + ), + ( + // ds_bpermute_b32 v3, v2, v1 offset:12 + "ds_bpermute_b32", + [vec![0xDACC_000C, 0x0300_0102], export(3).to_vec()].concat(), + ), + ( + // ds_swizzle_b32 v3, v2 offset:0x8000 (a quad pattern) + "ds_swizzle_b32 of a quad", + [vec![0xD8D4_8000, 0x0300_0102], export(3).to_vec()].concat(), + ), + ]; + for (name, words) in cases { + let shader = match pixel(&words) { + Ok(shader) => shader, + Err(e) => panic!("{name}: refused: {e:?}"), + }; + assert!(!shader.dxil.is_empty(), "{name}: no DXIL"); + } + } + /// A swizzle across quads stays refused in a pixel shader: a helper lane + /// at a primitive's edge can be its source, and wave operations leave + /// those out in SM 6.6. (`lane_operand_checked`'s wave64 refusal has no + /// test: a synthetic wave64 pixel program needs the console's EXEC + /// conventions first, which no test builds yet.) + #[test] + fn a_pixel_swizzle_across_quads_is_refused() { + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let sig = super::container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &sig)]); + let c = Container::parse(&bytes).unwrap(); + let lower = |words: &[u32], wave64: bool, lanes: Target| -> Result { + let native = NativeProgram { + stage: HwStage::Ps, + wave64, + vgprs: 8, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + emit(&c, &native, &p, &st, &io, &res, lanes) + }; + // ds_swizzle_b32 v3, v2 offset:0x7C00 (xor 31: lanes of other quads). + let swizzle = [0xD8D4_7C00, 0x0300_0102, 0xF800_180F, 0x0303_0303, S_ENDPGM]; + let why = lower(&swizzle, false, Target::ANY).expect_err("a cross-quad swizzle"); + assert!( + format!("{why:?}").contains("a swizzle across quads in a pixel shader"), + "{why:?}" + ); + } }