diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index faa68c1206..bdd940a713 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -520,10 +520,14 @@ fn translate( } return; } - let programs = match native_programs(dxil) { + let mut programs = match native_programs(dxil) { Ok(p) => p, Err(e) => return t.fail(e.to_string(), example), }; + // (the form a run translates: `victory_shader::emit::translate` does the same) + for program in &mut programs { + emit::host_form(&container, program); + } // `VICTORY_FAIL_DUMP=`: the first 3 containers of each failure reason, as the title // has them (`.cdxil`), to work on a translator gap offline let dump = std::env::var_os("VICTORY_FAIL_DUMP"); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index e835c2c557..9a4cc403d8 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -113,6 +113,7 @@ mod waterfall_tests; #[cfg(all(test, windows))] mod wave64_tests; mod wave; +mod water_tile_slots; use crate::dxbc::{Container, FourCC}; use crate::native::{HwStage, NativeProgram, RootType}; @@ -483,13 +484,24 @@ pub fn translate(container: &[u8]) -> Result { } } +/// Brings a console program into the form this host translates, where one differs from the +/// program as the title has it: on a host of 32-lane waves the water light's tile lists take +/// a slot a lane ([`water_tile_slots`]). [`translate`] does this itself; a caller that parses +/// the container and calls [`emit`] calls this first. Returns whether the program changed. +pub fn host_form(c: &Container, native: &mut NativeProgram) -> bool { + lower::host_max_wave() == 32 + && c.digest == water_tile_slots::CONTAINER + && water_tile_slots::on() + && water_tile_slots::rewrite(native) +} + fn translate_plain(container: &[u8]) -> Result { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) .or(c.part(FourCC::ACCC)) .ok_or(ShaderError::Malformed("no DXIL part"))?; - let native = crate::native_programs(dxil.data)? + let mut native = crate::native_programs(dxil.data)? .into_iter() .find(|p| { matches!( @@ -501,6 +513,9 @@ fn translate_plain(container: &[u8]) -> Result { offset: 0, what: "a container without a vertex, pixel, compute or mesh program", })?; + // The water light's tile lists on a host of 32-lane waves: a slot a lane + // ([`water_tile_slots`]), so no tile is lost between the two host waves of a group. + host_form(&c, &mut native); let p = crate::spill::build(&native)?; // Structurisation first: tracing per-lane descriptors needs it (its // failure is reported after the earlier stages'). @@ -605,7 +620,7 @@ pub fn emit( }; let forms = [ ("without early-outs", form("without early-outs", ir::without_early_outs(p))), - ("without skips", form("without skips", ir::without_skips(p, false))), + ("without skips", form("without skips", ir::without_skips(p, false, false))), ]; for (name, f) in &forms { if let Some((p, st, io, res)) = f { @@ -643,6 +658,9 @@ pub fn emit( | [0x24, 0x12, 0x6c, 0x14, 0xdc, 0x76, 0x19, 0xb0, 0x82, 0xef, 0x57, 0x12, 0x96, 0x03, 0x88, 0x90] | [0x70, 0x99, 0xa5, 0x7f, 0xde, 0xd1, 0x42, 0x61, 0x3b, 0x44, 0xf4, 0x10, 0x46, 0x3d, 0x6b, 0xe6] | [0xf1, 0xf1, 0x61, 0xe4, 0x7e, 0xef, 0xa3, 0x64, 0x69, 0x18, 0x39, 0xfd, 0x72, 0x06, 0xcc, 0xf6] + // `CS_TransmissionVolumetrics_VolumePortalsOnly` (a10179ab7eda0dc3): the same + // shape, 20 branches wave-wide. + | [0x4f, 0xa5, 0x83, 0x20, 0xd7, 0x61, 0xbf, 0x55, 0x81, 0x20, 0xf9, 0x2c, 0x19, 0xd3, 0x84, 0xaa] ) || matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() == 128) && c.digest == [0x50, 0xcf, 0x28, 0x32, 0x8b, 0x58, 0x05, 0x3d, 0xa8, 0x9a, 0x8d, 0xa0, 0x1a, 0xa1, 0x23, 0xc6]; @@ -665,7 +683,7 @@ pub fn emit( // lane runs, where the two host waves can exchange. // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.) let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0"); - let deep = if deep_on { form("without skips, scalars followed", ir::without_skips(p, true)) } else { None }; + let deep = if deep_on { form("without skips, scalars followed", ir::without_skips(p, true, false)) } else { None }; if let Some((p, st, io, res)) = &deep { let again = emit_program(c, native, p, st, io, res); report("without skips, scalars followed", &again); @@ -677,13 +695,24 @@ pub fn emit( // those places taken as the console takes them, by the whole wave at once // ([`widen`]), at two group barriers per such branch. if wide_on || driver_loop { + // For the programs taken wave-wide: first with the skips around loops that + // go round on a scalar test kept ([`ir::without_skips`], `loops_kept`), + // which the wave then takes together; the form of before if that one + // does not translate. (`VICTORY_WAVE_LOOP_SKIPS=0`: only the form of before.) + let loops_on = std::env::var_os("VICTORY_WAVE_LOOP_SKIPS").is_none_or(|v| v != "0"); + let kept = if wide_on && deep_on && loops_on { + form("without skips, loops kept", ir::without_skips(p, true, true)) + } else { + None + }; let bases = [ deep.as_ref().map(|f| &f.0), forms[1].1.as_ref().map(|f| &f.0), forms[0].1.as_ref().map(|f| &f.0), Some(p), ]; - if let Some(base) = bases.into_iter().flatten().next() { + let before = bases.into_iter().flatten().next(); + for base in [kept.as_ref().map(|f| &f.0), before].into_iter().flatten() { let again = widen(c, native, base, why, driver_loop, wide_on); report("wave-wide branches", &again); if done(&again) { diff --git a/crates/victory-shader/src/emit/water_tile_slots.rs b/crates/victory-shader/src/emit/water_tile_slots.rs new file mode 100644 index 0000000000..1207372aba --- /dev/null +++ b/crates/victory-shader/src/emit/water_tile_slots.rs @@ -0,0 +1,164 @@ +//! The water light's tile lists on a host of 32-lane waves: one list slot a lane. +//! +//! `water_shading:CS_TransmissionVolumetrics_GenerateTiles` (the title, 1.0.2.1) puts every water +//! tile into one of two lists: tiles without lamps from the front, tiles with lamps from the +//! back. The console takes the slots for a whole 64-lane wave at once: the wave's first lane +//! adds the wave's count to the list's counter, and every lane's slot is that lane's rank +//! among the wave's lanes on top of what the counter held. Run as two host waves, the rank of +//! a lane of the second half needs the first half's lane mask, exchanged through group memory. +//! On an RTX 4070 (run 421, frame 2822) the tiles the second half listed overwrote as many +//! slots of the first half, a few slots in: those tiles got no light that frame and the water +//! was dark there (blocks of 16 x 16 pixels around boats and piers). +//! +//! Here every lane of the list takes its own slot: it adds 1 to the counter and its slot is +//! what the counter held. Slots are still each given once and the counters end the same; only +//! the order within a list differs, which nothing reads. No lane mask, no first lane and no +//! exchange between the halves is left in the two appends. +//! +//! The change is made in the console program's own code, before translation: the instructions +//! kept are the program's (its atomic add, its waits, its load of the list's size), moved to +//! the front of each append, with the rest of the append made no-operations. Branch targets +//! and the code after the appends keep their places. +//! +//! After xss3009's "Fix transmission tile allocation on wave32 hosts" (Victory-NVIDIA forks, +//! 69e7e00), written again for this tree. `VICTORY_WATER_TILE_SLOTS=0`: the program as it is. + +use crate::native::{HwStage, NativeProgram}; + +/// The container's digest (bytes 4..20 of the container). +pub(super) const CONTAINER: [u8; 16] = [ + 0xf5, 0xd1, 0x0c, 0xde, 0x74, 0x33, 0x37, 0x82, 0xf3, 0x0f, 0x9b, 0xb5, 0x56, 0xc0, 0x73, 0xd4, +]; +/// The program's length and the FNV-1a hash of its bytes. +const BYTES: usize = 2112; +const CODE: u64 = 0x377a_8d97_4fb8_631f; + +/// `v_mov_b32 v5, 0` (its source becomes the constant 1) and a `s_nop`. +const MOVE_ZERO: usize = 0x6c4; +const NOP: usize = 0x6d8; + +/// An append: where it is, and the pieces of it that stay, in order. +struct Append { + body: std::ops::Range, + kept: &'static [std::ops::Range], +} + +/// Tiles without lamps: `buffer_atomic_add v5, .., 0 glc`, `s_waitcnt vmcnt(0)`. +const FRONT: Append = Append { body: 0x6a8..0x704, kept: &[0x6dc..0x6e4, 0x6f0..0x6f4] }; +/// Tiles with lamps: `buffer_atomic_add v5, .., offset:32 glc`, the load of the list's size, +/// `s_waitcnt vmcnt(0)`, `s_waitcnt lgkmcnt(0)`. The reversal of the slot that follows stays. +const BACK: Append = Append { + body: 0x70c..0x774, + kept: &[0x740..0x748, 0x74c..0x754, 0x75c..0x760, 0x770..0x774], +}; + +pub(super) fn on() -> bool { + std::env::var_os("VICTORY_WATER_TILE_SLOTS").is_none_or(|v| v != "0") +} + +fn fnv(bytes: &[u8]) -> u64 { + bytes + .iter() + .fold(0xcbf2_9ce4_8422_2325, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)) +} + +/// Whether `native` is the program this change knows byte for byte. +fn known(native: &NativeProgram) -> bool { + native.stage == HwStage::Cs && native.wave64 && native.code.len() == BYTES && fnv(&native.code) == CODE +} + +/// Rewrites the two appends of the known program; any other program is left as it is. +/// Returns whether it changed the program. +pub(super) fn rewrite(native: &mut NativeProgram) -> bool { + if !known(native) { + return false; + } + let before = native.code.clone(); + let mut one: [u8; 4] = before[MOVE_ZERO..MOVE_ZERO + 4].try_into().expect("four bytes"); + // The source operand's nine bits: 0x80 is the constant 0, 0x81 the constant 1. + one[0] |= 1; + let nop: [u8; 4] = before[NOP..NOP + 4].try_into().expect("four bytes"); + for append in [FRONT, BACK] { + let mut new = one.to_vec(); + for piece in append.kept { + new.extend_from_slice(&before[piece.clone()]); + } + let body = &mut native.code[append.body]; + debug_assert!(new.len() <= body.len() && body.len() % 4 == 0); + body[..new.len()].copy_from_slice(&new); + for word in body[new.len()..].chunks_exact_mut(4) { + word.copy_from_slice(&nop); + } + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A program of the known length with the two instructions the rewrite copies and marks + /// in the pieces it keeps, so the result can be read back piece by piece. + fn stand_in() -> Vec { + let mut code = vec![0xaa; BYTES]; + code[MOVE_ZERO..MOVE_ZERO + 4].copy_from_slice(&0x7e0a_0280u32.to_le_bytes()); + code[NOP..NOP + 4].copy_from_slice(&0xbf80_0000u32.to_le_bytes()); + for (n, piece) in FRONT.kept.iter().chain(BACK.kept).enumerate() { + code[piece.clone()].fill(n as u8 + 1); + } + code + } + + #[test] + fn another_program_is_left_as_it_is() { + let code = stand_in(); + let mut native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 32, + layout: Vec::new(), + used: Vec::new(), + io: crate::native::StageIo::Cs(crate::native::ComputeIo { rsrc2: 0, threads: [8, 8, 1] }), + code: code.clone(), + }; + assert!(!rewrite(&mut native)); + assert_eq!(native.code, code); + } + + #[test] + fn an_append_becomes_one_add_a_lane_and_keeps_its_length() { + let before = stand_in(); + let mut code = before.clone(); + let one = 0x7e0a_0281u32.to_le_bytes(); + let nop = 0xbf80_0000u32.to_le_bytes(); + // (the rewrite's body, without the identity test) + for append in [FRONT, BACK] { + let mut new = one.to_vec(); + for piece in append.kept { + new.extend_from_slice(&before[piece.clone()]); + } + let body = &mut code[append.body]; + body[..new.len()].copy_from_slice(&new); + for word in body[new.len()..].chunks_exact_mut(4) { + word.copy_from_slice(&nop); + } + } + assert_eq!(code.len(), before.len()); + // Front: the move of 1, the add (8 bytes of mark 1), the wait (4 bytes of mark 2). + assert_eq!(&code[0x6a8..0x6ac], &one); + assert_eq!(&code[0x6ac..0x6b4], &[1; 8]); + assert_eq!(&code[0x6b4..0x6b8], &[2; 4]); + assert!(code[0x6b8..0x704].chunks_exact(4).all(|w| w == nop)); + // Back: the move, the add (mark 3), the size (mark 4), the two waits (marks 5, 6). + assert_eq!(&code[0x70c..0x710], &one); + assert_eq!(&code[0x710..0x718], &[3; 8]); + assert_eq!(&code[0x718..0x720], &[4; 8]); + assert_eq!(&code[0x720..0x724], &[5; 4]); + assert_eq!(&code[0x724..0x728], &[6; 4]); + assert!(code[0x728..0x774].chunks_exact(4).all(|w| w == nop)); + // Nothing outside the two appends moved. + assert_eq!(&code[..0x6a8], &before[..0x6a8]); + assert_eq!(&code[0x704..0x70c], &before[0x704..0x70c]); + assert_eq!(&code[0x774..], &before[0x774..]); + } +} diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index cb79fb6684..33f5d14bcd 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -777,7 +777,16 @@ pub(crate) fn without_early_outs(p: &Program) -> Option { /// the join may have other ways in (an inner branch that ends together with an outer one). /// That leaves out most of the skips of the title's large lighting programs, whose bodies /// are then code every lane runs. -pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { +/// +/// `loops_kept` keeps a skip around a loop that goes round on a scalar test (`s_cmp_*`, not a +/// lane mask). With no lane left the console does not run such a loop; walked with EXEC +/// clear, its bounds are whatever a first-lane read found in the registers of lanes that +/// never wrote them, and it goes round until the iteration limit, where every thread of the +/// group leaves the program (the water's tiled light: the loop over a tile's slices, whose +/// ends the tile's farthest lane gives; a tile without that lane stored nothing at all, at +/// 4,096 rounds of group barriers). The kept skip is a branch the wave takes together +/// (`emit::widen`), as on the console. +pub(crate) fn without_skips(p: &Program, deep: bool, loops_kept: bool) -> Option { let n = p.blocks.len(); let ends = |b: usize| { p.blocks[b].exit == Exit::End @@ -860,6 +869,41 @@ pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { return None; } } + // a loop in the region that goes round on a scalar test + if loops_kept { + for x in (0..n).filter(|&x| inside[x]) { + let Some(last) = p.blocks[x].insts.last() else { + continue; + }; + if !matches!(last.name(), "s_cbranch_scc0" | "s_cbranch_scc1") { + continue; + } + let scalar = last.read(Reg::Scc).is_none_or(|scc| { + p.blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| i.writes.iter().any(|w| w.1 == scc)) + .is_none_or(|i| i.name().starts_with("s_cmp_") || i.name().starts_with("s_bitcmp")) + }); + // (round: the branch leads back to its own block inside the region) + let mut seen = vec![false; n]; + let mut stack = p.blocks[x].exit.successors(); + let mut round = false; + while let Some(y) = stack.pop() { + if y == x { + round = true; + break; + } + if y >= n || !inside[y] || std::mem::replace(&mut seen[y], true) { + continue; + } + stack.extend(p.blocks[y].exit.successors()); + } + if scalar && round { + return None; + } + } + } // the join sees no scalar the region changed let join = &p.blocks[target]; for phi in &join.phis { @@ -1746,22 +1790,22 @@ mod tests { // s6 is changed in the body and read after the join: the branch stays let kept = skip(&[SET, USE], &[READ]); assert_eq!(skips(&kept), 1); - assert!(without_skips(&kept, false).is_none()); - assert!(without_skips(&kept, true).is_none()); + assert!(without_skips(&kept, false, false).is_none()); + assert!(without_skips(&kept, true, false).is_none()); // ... put back by a copy of what it held (as a scalar parked in a VGPR lane comes // back): every lane may walk the body let back = skip(&[SET, USE, BACK], &[READ]); - assert!(without_skips(&back, false).is_none()); - assert_eq!(skips(&without_skips(&back, true).expect("left out")), 0); + assert!(without_skips(&back, false, false).is_none()); + assert_eq!(skips(&without_skips(&back, true, false).expect("left out")), 0); // ... or not read after the join at all let unread = skip(&[SET, USE], &[]); - assert_eq!(skips(&without_skips(&unread, false).expect("left out")), 0); - assert_eq!(skips(&without_skips(&unread, true).expect("left out")), 0); + assert_eq!(skips(&without_skips(&unread, false, false).expect("left out")), 0); + assert_eq!(skips(&without_skips(&unread, true, false).expect("left out")), 0); // ... or read only by a restore of EXEC that nothing uses before the next one // (s_mov_b64 exec, s[6:7]; s_mov_b64 exec, s[12:13]; v_mov_b32 v2, s0) let idle = skip(&[SET, USE], &[0xBEFE_0406, 0xBEFE_040C, 0x7E04_0200]); - assert!(without_skips(&idle, false).is_none()); - assert_eq!(skips(&without_skips(&idle, true).expect("left out")), 0); + assert!(without_skips(&idle, false, false).is_none()); + assert_eq!(skips(&without_skips(&idle, true, false).expect("left out")), 0); } #[test]