diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 135ba57e27..c77ab1ee17 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6960,6 +6960,72 @@ mod tests { } } + #[test] + fn joined_descriptor_compares_must_gate_the_access() { + use crate::resource::tests::WATERFALL_JOINED_WAVE32; + + let (layout, used) = texture_and_uav_tables(); + let lowered = lower_wave(WATERFALL_JOINED_WAVE32, layout, used, false).unwrap(); + assert_eq!(lowered.nonuniform_handles, 1); + assert!(!lowered.wave_ops); + + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let select = words.iter_mut().find(|w| **w == 0xBE95_3C15).unwrap(); + // Save EXEC without narrowing it to lanes with matching descriptors. + *select = 0xBE95_037E; // s_mov_b32 s21, exec_lo + let (layout, used) = texture_and_uav_tables(); + match lower_wave(&words, layout, used, false) { + Err(crate::ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + }) => {} + Err(err) => panic!("unexpected refusal: {err:?}"), + Ok(lowered) => panic!( + "accepted the unused compares and emitted {} nonuniform handle(s)", + lowered.nonuniform_handles + ), + } + } + + #[test] + fn joined_descriptor_loop_must_retry_nonmatching_lanes() { + use crate::resource::tests::WATERFALL_JOINED_WAVE32; + + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let retry = words.iter_mut().find(|w| **w == 0x897E_157E).unwrap(); + // Keep the descriptor comparisons and the CFG back edge, but + // terminate the loop after the first descriptor has been used. + *retry = 0xBEFE_0380; // s_mov_b32 exec_lo, 0 + let (layout, used) = texture_and_uav_tables(); + match lower_wave(&words, layout, used, false) { + Err(crate::ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + }) => {} + Err(err) => panic!("unexpected refusal: {err:?}"), + Ok(lowered) => panic!( + "accepted a dead retry and emitted {} nonuniform handle(s)", + lowered.nonuniform_handles + ), + } + } + + #[test] + fn waterfall_retry_can_cross_blocks() { + use crate::resource::tests::WATERFALL_FETCHED_WAVE32; + + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + let select = words.iter().position(|&w| w == 0xBE95_3C15).unwrap(); + assert_eq!(words[select + 1], 0xBF80_0000); + // Split the loop between the mask computation and the texture + // access, leaving every instruction and the back edge in place. + words[select + 1] = 0xBF82_0000; // s_branch to the next instruction + let (layout, used) = texture_tables(); + let lowered = lower_wave(&words, layout, used, false).unwrap(); + assert_eq!(lowered.nonuniform_handles, 1); + assert!(!lowered.wave_ops); + } + #[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/resource.rs b/crates/victory-shader/src/resource.rs index ecd1b23c42..11ccd3e77c 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -14,7 +14,7 @@ use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; -use crate::ir::{Inst, Program, Reg, Value}; +use crate::ir::{Block, EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, RootParam, RootType}; use crate::structure::{Bool, LaneExit, Structured}; @@ -159,10 +159,6 @@ pub fn track( .collect(), ..Resources::default() }; - // `v_readfirstlane_b32` results descriptors are read from. - let mut first_lane: Vec = Vec::new(); - // Per descriptor read from the first lane: where, and those results. - let mut first_lane_at: Vec<(usize, Vec)> = Vec::new(); for (b, block) in p.blocks.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); @@ -174,9 +170,23 @@ pub fn track( let source = t.descriptor(inst, op, b).map_err(fail)?; let words = t.first_lane_words(inst, op).unwrap_or_default(); if !words.is_empty() { - first_lane_at.push((inst.machine.offset, words.clone())); + let waterfall = t.waterfall(site, &words); + if words.iter().any(|w| !waterfall.reads.contains(w)) { + return Err(fail( + "a descriptor read from the first lane outside a waterfall loop", + )); + } + for cmp in waterfall.compares { + if !out.waterfall.compares.contains(&cmp) { + out.waterfall.compares.push(cmp); + } + } + for read in waterfall.reads { + if !out.waterfall.reads.contains(&read) { + out.waterfall.reads.push(read); + } + } } - first_lane.extend(words); out.descriptors.push(Descriptor { site, role, source }); Ok(()) }; @@ -215,18 +225,6 @@ pub fn track( } } } - out.waterfall = t.waterfall(&first_lane); - // Taking the first lane's descriptor as each lane's own holds only in - // a waterfall loop: one whose compare of the first lane's dwords with - // the lane's own repeats the access until every lane has had its turn. - for (offset, words) in first_lane_at { - if words.iter().any(|w| !out.waterfall.reads.contains(w)) { - return Err(ShaderError::Unsupported { - offset, - what: "a descriptor read from the first lane outside a waterfall loop", - }); - } - } Ok(out) } @@ -1319,7 +1317,7 @@ impl<'a> Tracer<'a> { if let Term::Value(v) = *w && phi_of(w).is_none() && let Some((d, _)) = self.defs[v.0 as usize] - && (d == block || self.reaches(block, d)) + && (d == block || self.reaches(block, d, |b| b.exit.successors())) { return Err("a descriptor partly joined by control flow"); } @@ -1369,9 +1367,9 @@ impl<'a> Tracer<'a> { /// Whether a path leads from block `from` to block `to` (to `from` /// itself only through a back edge). - fn reaches(&self, from: usize, to: usize) -> bool { + fn reaches(&self, from: usize, to: usize, successors: impl Fn(&Block) -> Vec) -> bool { let mut seen = vec![false; self.p.blocks.len()]; - let mut stack = self.p.blocks[from].exit.successors(); + let mut stack = successors(&self.p.blocks[from]); while let Some(x) = stack.pop() { if x == to { return true; @@ -1379,71 +1377,125 @@ impl<'a> Tracer<'a> { if std::mem::replace(&mut seen[x], true) { continue; } - stack.extend(self.p.blocks[x].exit.successors()); + stack.extend(successors(&self.p.blocks[x])); } false } - /// The waterfall loops over descriptors read from the first lane (the - /// `v_readfirstlane_b32` results `reads`): the `v_cmp_eq` of those - /// results with the dwords they read. - fn waterfall(&self, reads: &[Value]) -> Waterfall { - let mut out = Waterfall::default(); - if reads.is_empty() { - return out; + /// Definitions that necessarily contribute a positive condition to + /// EXEC at the access. Stop at masks we cannot prove are conjunctions. + fn exec_conditions(&self, access: &Inst, word: u8) -> Vec { + let (and, save) = if self.p.wave64 { + ("s_and_b64", "s_and_saveexec_b64") + } else { + ("s_and_b32", "s_and_saveexec_b32") + }; + let exec = Reg::S(EXEC + word); + let mut pending: Vec = access.read(exec).into_iter().collect(); + let mut seen = std::collections::HashSet::new(); + let mut sites = Vec::new(); + while let Some(v) = pending.pop() { + let Term::Value(v) = self.origin(v) else { + continue; + }; + if !seen.insert(v) { + continue; + } + let Some(site) = self.defs[v.0 as usize] else { + continue; + }; + let inst = self.inst(site); + let name = inst.name(); + if name.starts_with("v_cmp") { + // A copy of the low mask into the high half does not + // establish the comparison for the upper 32 lanes. + if inst.writes.get(usize::from(word)).is_some_and(|w| w.1 == v) { + sites.push(site); + } + continue; + } + let Fields::Sop { dst, src, .. } = &inst.fields else { + continue; + }; + if name == save && inst.write(exec) == Some(v) { + pending.extend(inst.read(exec)); + } else if name != and + || !matches!(dst, Some(Operand::Scalar { code, .. }) + if inst.write(Reg::S(code + word)) == Some(v)) + { + continue; + } + pending.extend(src.iter().filter_map(|op| match *op { + Operand::Scalar { code, .. } => inst.read(Reg::S(code + word)), + _ => None, + })); } - for (b, block) in self.p.blocks.iter().enumerate() { - for (i, inst) in block.insts.iter().enumerate() { - let Fields::Valu(f) = &inst.fields else { - continue; - }; - let Some(ty) = inst - .name() - .strip_prefix("v_cmp_eq_") - .or(inst.name().strip_prefix("v_cmpx_eq_")) + sites + } + + /// A descriptor read is a waterfall candidate only when its equality + /// compares actually gate the access in the loop. + fn waterfall(&self, site: Site, reads: &[Value]) -> Waterfall { + let mut out = Waterfall::default(); + let access = self.inst(site); + let mut conditions = self.exec_conditions(access, 0); + if self.p.wave64 { + let high = self.exec_conditions(access, 1); + conditions.retain(|cmp| high.contains(cmp)); + } + for (b, i) in conditions { + let inst = self.inst((b, i)); + if !self.same_loop(site.0, b) { + continue; + } + let Fields::Valu(f) = &inst.fields else { + continue; + }; + let Some(ty) = inst + .name() + .strip_prefix("v_cmp_eq_") + .or(inst.name().strip_prefix("v_cmpx_eq_")) + else { + continue; + }; + let dwords = match ty { + "u32" | "i32" => 1, + "u64" | "i64" => 2, + _ => continue, + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + continue; + } + // The first lane's dwords on one side, the lane's own on the + // other. + let pair = |first: &Operand, own: &Operand| -> Option> { + let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = (first, own) else { - continue; - }; - let dwords = match ty { - "u32" | "i32" => 1, - "u64" | "i64" => 2, - _ => continue, + return None; }; - if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { - continue; - } - // The first lane's dwords on one side, the lane's own on the - // other. - let pair = |first: &Operand, own: &Operand| -> Option> { - let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = - (first, own) - else { - return None; - }; - (0..dwords) - .map(|k| { - let Term::Value(x) = self.origin(inst.read(Reg::S(code + k))?) else { - return None; - }; - let lane = inst.read(Reg::V(reg + k))?; - let (d, _) = self.defs[x.0 as usize]?; - let same = reads.contains(&x) - && self.same_loop(b, d) - && self.lane_term(Term::Value(self.first_lane_source(x)?)) - == self.lane_term(Term::Value(lane)); - same.then_some(x) - }) - .collect() - }; - let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { - continue; - }; - if let Some(xs) = pair(a, c).or_else(|| pair(c, a)) { - out.compares.push((b, i)); - for x in xs { - if !out.reads.contains(&x) { - out.reads.push(x); - } + (0..dwords) + .map(|k| { + let Term::Value(x) = self.origin(inst.read(Reg::S(code + k))?) else { + return None; + }; + let lane = inst.read(Reg::V(reg + k))?; + let (d, _) = self.defs[x.0 as usize]?; + let same = reads.contains(&x) + && self.same_loop(b, d) + && self.lane_term(Term::Value(self.first_lane_source(x)?)) + == self.lane_term(Term::Value(lane)); + same.then_some(x) + }) + .collect() + }; + let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { + continue; + }; + if let Some(xs) = pair(a, c).or_else(|| pair(c, a)) { + out.compares.push((b, i)); + for x in xs { + if !out.reads.contains(&x) { + out.reads.push(x); } } } @@ -1454,7 +1506,24 @@ impl<'a> Tracer<'a> { /// Whether blocks `a` and `b` are in one loop: each reaches the other /// (a block reaches itself only through a back edge). fn same_loop(&self, a: usize, b: usize) -> bool { - self.reaches(a, b) && self.reaches(b, a) + let successors = |block: &Block| { + if let Exit::Branch { taken, not_taken } = block.exit + && let Some(branch) = block.insts.last() + && matches!(branch.name(), "s_cbranch_execz" | "s_cbranch_execnz") + && (0..=u8::from(self.p.wave64)).all(|word| { + branch.read(Reg::S(EXEC + word)).map(|v| self.origin(v)) == Some(Term::Const(0)) + }) + { + // An empty EXEC has no lane that can repeat the access. + return vec![if branch.name() == "s_cbranch_execz" { + taken + } else { + not_taken + }]; + } + block.exit.successors() + }; + self.reaches(a, b, successors) && self.reaches(b, a, successors) } /// Consecutive dwords of one scalar load. @@ -2449,6 +2518,23 @@ pub(crate) mod tests { ); } + #[test] + fn a_wave64_access_needs_both_exec_halves_gated() { + waterfall(WATERFALL_FETCHED_WAVE64, true).unwrap(); + let mut words = WATERFALL_FETCHED_WAVE64.to_vec(); + let save = words.iter().position(|&w| w == 0xBE96_2416).unwrap(); + assert_eq!(words[save + 1], 0xBF80_0000); + // Reenable the previous upper lanes while leaving EXEC_LO gated. + words[save + 1] = 0xBEFF_0317; // s_mov_b32 exec_hi, s23 + assert!(matches!( + waterfall(&words, true), + Err(ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + }) + )); + } + #[test] fn a_first_lane_read_without_its_compare_is_no_waterfall() { // The loop without the compare of dwords 0 and 1: nothing makes