diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 3c2ed783c5f..ca1f63b3255 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -204,6 +204,22 @@ fn create() -> windows::core::Result { ) .is_ok() && options.DepthBoundsTestSupported.as_bool(); + let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_7, + }; + let sm67 = device + .CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut model).cast(), + size_of_val(&model) as u32, + ) + .is_ok() + && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_7.0; + victory_shader::emit::set_helper_lane_waves(sm67); + tracing::info!( + sm67, + "host shader model 6.7 (wave operations over helper lanes)" + ); let messages = debug .then(|| device.cast::().ok()) .flatten(); diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index fd09daa1561..c4e9fbeafba 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -68,6 +68,21 @@ fn build() -> &'static [u8; 32] { }) } +/// [`build`], and whether pixel wave operations include helper lanes +/// (shader model 6.7): the host's device decides that, and it exists only +/// after the cache is opened, so it keys each entry rather than the folder. +/// Unchanged where they do not. +fn entry_build() -> [u8; 32] { + if victory_shader::emit::helper_lane_waves() { + let mut h = blake3::Hasher::new(); + h.update(build()); + h.update(b"helper lanes"); + *h.finalize().as_bytes() + } else { + *build() + } +} + /// This file, whose `encode` and `decode` define the entries. const ENCODING: &[u8] = include_bytes!("shader_cache.rs"); @@ -87,7 +102,7 @@ pub fn host_shader(container: &[u8]) -> (Result, bool) { let options = victory_shader::emit::Options { view_marks: true }; let translate = |c: &[u8]| victory_shader::emit::translate_with(c, options).map_err(|e| e.to_string()); match CACHE.get() { - Some(cache) => cached(cache, build(), container, translate), + Some(cache) => cached(cache, &entry_build(), container, translate), None => (translate(container), false), } } diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index ad1772b1cbe..0003a49d597 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -176,8 +176,15 @@ pub(crate) enum Attr { ReadOnly = 3, /// Barriers. NoDuplicate = 4, + /// `main` of a pixel shader whose wave operations include helper lanes + /// (shader model 6.7). + HelperLaneWaves = 5, } +/// The string attribute DXC gives an entry point with +/// `[WaveOpsIncludeHelperLanes]`. +const HELPER_LANE_WAVES: &str = "waveops-include-helper-lanes"; + struct Func { name: String, ty: Ty, @@ -327,6 +334,12 @@ impl Module { } /// A function declaration (or `main` with `body`), found by name. + /// Sets the attributes of function `f`. + pub fn set_function_attr(&mut self, f: V, attr: Attr) { + let V::Func(i) = f else { panic!("not a function") }; + self.funcs[i as usize].attr = Some(attr); + } + pub fn function(&mut self, name: &str, ty: Ty, attr: Option, body: bool) -> V { if let Some(&i) = self.func_ids.get(name) { return V::Func(i); @@ -745,9 +758,25 @@ impl Module { } w.record(3, &r); } + // Group 5 only when a function has it, so other modules' bytes + // stay as they were: a string attribute without a value (kind 3, + // its bytes, then 0). + let groups = if self + .funcs + .iter() + .any(|f| f.attr == Some(Attr::HelperLaneWaves)) + { + let mut r = vec![5, 0xFFFF_FFFF, 3]; + r.extend(HELPER_LANE_WAVES.bytes().map(u64::from)); + r.push(0); + w.record(3, &r); + 5 + } else { + 4 + }; w.exit(); w.enter(PARAMATTR_BLOCK, 3); - for id in 1..=4 { + for id in 1..=groups { w.record(2, &[id]); } w.exit(); diff --git a/crates/victory-shader/src/emit/helper_lane_tests.rs b/crates/victory-shader/src/emit/helper_lane_tests.rs new file mode 100644 index 00000000000..88118954d7a --- /dev/null +++ b/crates/victory-shader/src/emit/helper_lane_tests.rs @@ -0,0 +1,255 @@ +//! A pixel program's lane-mask loop at a triangle edge: on the console the +//! helper lanes of whole-quad mode are in EXEC and are served like the +//! others, so quad reads of their results give the neighbour's value. On +//! the host, wave operations leave helper lanes out unless the program asks +//! for them (shader model 6.7's `WaveOpsIncludeHelperLanes`). + +use super::container::{SigElement, signature}; +use super::host::{Draw, Host}; +use super::{HostShader, emit}; +use crate::native::{HwStage, NativeProgram, StageIo, Usage, VsInput}; +use crate::{Container, FourCC, io, ir, resource, structure}; + +const EXEC_LO: u32 = 0x7E; +const S_ENDPGM: u32 = 0xBF81_0000; +const fn sop1(op: u32, d: u32, s: u32) -> u32 { + 0xBE80_0000 | d << 16 | op << 8 | s +} +const fn sop2(op: u32, d: u32, a: u32, b: u32) -> u32 { + 0x8000_0000 | op << 23 | d << 16 | b << 8 | a +} +const fn vop1(op: u32, d: u32, s: u32) -> u32 { + 0x7E00_0000 | d << 17 | op << 9 | s +} +const fn vop2(op: u32, d: u32, s0: u32, v1: u32) -> u32 { + op << 25 | d << 17 | v1 << 9 | s0 +} +const fn v(n: u32) -> u32 { + 256 + n +} + +/// Each pixel's key, `3x + 5y + 1`: distinct within a quad. +fn key(x: u32, y: u32) -> u32 { + 3 * x + 5 * y + 1 +} + +/// Serves one key per pass (`s_ff1` of EXEC, `v_readlane`, `v_cmpx`), +/// as a waterfall over a per-lane value does, then reads the x neighbour's +/// result with DPP `quad_perm:[1,0,3,2]`. Exports (own result, neighbour's +/// result, own result, key) as floats. +fn pixel_program(wave64: bool) -> Vec { + // s_mov, s_ff1_i32, s_andn2 on EXEC's 32 or 64 bits. + let (mov, ff1, andn2) = if wave64 { + (0x04, 0x14, 0x15) + } else { + (0x03, 0x13, 0x14) + }; + let mut w = vec![ + vop1(0x07, 2, v(0)), // v_cvt_u32_f32 v2, v0 (x) + vop1(0x07, 3, v(1)), // v_cvt_u32_f32 v3, v1 (y) + vop2(0x0B, 4, 128 + 3, 2), // v_mul_u32_u24 v4, 3, v2 + vop2(0x0B, 5, 128 + 5, 3), // v_mul_u32_u24 v5, 5, v3 + vop2(0x25, 4, v(4), 5), // v_add_nc_u32 v4, v4, v5 + vop2(0x25, 4, 128 + 1, 4), // v_add_nc_u32 v4, 1, v4 + vop1(0x01, 5, 128), // v_mov_b32 v5, 0 + sop1(mov, 12, EXEC_LO), // s_mov s12, exec (the whole quads) + sop1(mov, 10, EXEC_LO), // s_mov s10, exec (lanes left) + sop1(ff1, 0, EXEC_LO), // s_ff1_i32 s0, exec + 0xD760_0001, // v_readlane_b32 s1, v4, s0 + 0x0000_0104, + 0x7C00_0000 | 0xD2 << 17 | 4 << 9 | 1, // v_cmpx_eq_u32 s1, v4 + vop1(0x01, 5, 1), // v_mov_b32 v5, s1 + sop2(andn2, 10, 10, EXEC_LO), // s_andn2 s10, s10, exec + sop1(mov, EXEC_LO, 10), // s_mov exec, s10 + ]; + w.push(0xBF80_0000 | 0x09 << 16 | (-8i32 as u32 & 0xFFFF)); // s_cbranch_execnz (s_ff1) + w.extend([ + sop1(mov, EXEC_LO, 12), // s_mov exec, s12 + // v_mov_b32 v6, v5 quad_perm:[1,0,3,2] bound_ctrl:1 + 0x7E00_0000 | 6 << 17 | 0x01 << 9 | 0xFA, + 0xF << 28 | 0xF << 24 | 1 << 19 | 0xB1 << 8 | 5, + vop1(0x06, 5, v(5)), // v_cvt_f32_u32 v5, v5 + vop1(0x06, 6, v(6)), // v_cvt_f32_u32 v6, v6 + vop1(0x06, 4, v(4)), // v_cvt_f32_u32 v4, v4 + 0xF800_180F, // exp mrt0 v5, v6, v5, v4 done vm + 0x0405_0605, + S_ENDPGM, + ]); + w +} + +fn sig(name: &str, kind: u8, interp: u8) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + } +} + +fn translate(native: &NativeProgram, inputs: &[SigElement], outputs: &[SigElement]) -> HostShader { + let isg = signature(inputs, true); + let osg = signature(outputs, false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg), (FourCC::OSG1, &osg)]); + let c = Container::parse(&bytes).expect("container"); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).expect("ir"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource"); + let io = io::raise(&p, native).expect("io"); + let h = emit(&c, native, &p, &st, &io, &res).expect("emit"); + if let Ok(mut val) = + super::validator::Validator::load(super::validator::Validator::default_path().as_deref()) + { + val.validate(&mut h.dxil.clone()) + .expect("DXIL validation failed"); + } + h +} + +/// The keys a lane-mask loop serves reach the helper lanes at a triangle +/// edge, so a quad read of a helper's result gives its key, as on the +/// console. Needs a host with shader model 6.7 (wave operations over helper +/// lanes). Was a defect: the host's ballots left helpers out, so a helper +/// was never served and its neighbour read 0 (8 of 136 pixels on a Radeon +/// 780M, RDNA3, and 18 on WARP). +#[test] +fn lane_mask_loops_serve_helper_lanes_at_a_triangle_edge() { + // A host first: translation may depend on what the device supports. + let _ = Host::new(false); + let vs_code = [0xF800_08CF, 0x0706_0504, S_ENDPGM]; // exp pos0 v4..v7 done + let vs_native = NativeProgram { + stage: HwStage::Vs, + wave64: true, + vgprs: 8, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Vs { + inputs: vec![VsInput { + usage: Usage::Generic, + row: 0, + mask: 0xF, + vgpr: 4, + }], + outputs: Vec::new(), + }, + code: vs_code.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let vs = translate( + &vs_native, + &[sig("POSITION", 0, 0)], + &[sig("SV_Position", 3, 4)], + ); + // A triangle whose diagonal crosses quads of a 16x16 target. + let vertices = [ + -1.0, -1.0, 0.5, 1.0, // + -1.0, 1.1, 0.5, 1.0, // + 1.1, -1.0, 0.5, 1.0, + ]; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut failures = Vec::new(); + let mut ran = false; + { + let wave64 = true; + let ps_native = NativeProgram { + stage: HwStage::Ps, + wave64, + vgprs: 8, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Ps { + inputs: Vec::new(), + input_addr: 0x300, // SV_Position.x in v0, .y in v1 + db_shader_control: 0, + patches: Vec::new(), + }, + code: pixel_program(wave64) + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(), + }; + let ps = translate( + &ps_native, + &[sig("SV_Position", 3, 4)], + &[sig("SV_Target", 16, 0)], + ); + for (adapter, warp) in [("hardware", false), ("warp", true)] { + let label = format!("wave{} {adapter}", if wave64 { 64 } else { 32 }); + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + ran = true; + let (root, pso) = host + .pipeline(&vs, &ps) + .unwrap_or_else(|e| panic!("{label}: pipeline: {e}")); + let pixels = host + .draw( + &root, + &pso, + &Draw { + roots: Vec::new(), + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 16, + size: (16, 16), + mesh_groups: 0, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + let (mut covered, mut own, mut neighbour) = (0, 0, 0); + let (mut first, mut first_own) = (None, None); + for (i, px) in pixels.iter().enumerate() { + let (x, y) = (i as u32 % 16, i as u32 / 16); + if px[3] != key(x, y) as f32 { + continue; // not covered + } + covered += 1; + let want = [key(x, y) as f32, key(x ^ 1, y) as f32]; + if px[0] != want[0] { + own += 1; + if first_own.is_none() { + first_own = + Some(format!("({x}, {y}): own {} instead of {}", px[0], want[0])); + } + } + if px[1] != want[1] { + neighbour += 1; + if first.is_none() { + first = Some(format!( + "({x}, {y}): neighbour {} instead of {}", + px[1], want[1] + )); + } + } + } + eprintln!( + "{label}: {covered} pixels, own result wrong {own}, neighbour's wrong {neighbour}{}{}", + first_own + .as_deref() + .map(|f| format!(", first {f}")) + .unwrap_or_default(), + first + .as_deref() + .map(|f| format!(", first {f}")) + .unwrap_or_default() + ); + assert!(covered > 100, "{label}: only {covered} pixels covered"); + if own + neighbour > 0 { + failures.push(format!( + "{label}: own {own}, neighbour {neighbour} of {covered}" + )); + } + } + } + assert!(ran, "no SM 6.6 device"); + assert!(failures.is_empty(), "{}", failures.join("; ")); +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index da16ad7d2cf..5b5a37859e3 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -103,6 +103,19 @@ fn create_device(warp: bool) -> Result { sm.HighestShaderModel.0 )); } + let mut sm67 = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_7, + }; + super::set_helper_lane_waves( + device + .CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut sm67).cast(), + size_of_val(&sm67) as u32, + ) + .is_ok() + && sm67.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_7.0, + ); Ok(device) } } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c96f522ec82..362ddfb6bbc 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3080,7 +3080,8 @@ impl<'a> Lower<'a> { /// the first pass and leaves; what a helper lane computes only feeds /// derivatives, and its stores are dropped. fn helper_reads_own(&mut self, own: V, first: V) -> V { - if !self.s.pixel { + // Shader model 6.7: the wave operations include helper lanes. + if !self.s.pixel || super::helper_lane_waves() { return first; } let c = self.cur; diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 91a5e64b985..568a5feb1d2 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -207,6 +207,8 @@ mod crosslane_tests; mod diff_tests; #[cfg(all(test, windows))] mod flow_tests; +#[cfg(all(test, windows))] +mod helper_lane_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; mod lower; @@ -241,6 +243,23 @@ pub use shader::{ VIEW_STRIDES, VIEW_WRITE_BITS, VIEW_WRITES, }; +static HELPER_LANE_WAVES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Tells translation that the host runs shader model 6.7: pixel shaders +/// with wave operations then include helper lanes in them, as the +/// console's do. Without it a loop that serves one lane's value per pass +/// (sampling with a per-lane descriptor) never serves a helper lane and +/// runs to the loop limit, which hangs NVIDIA GPUs. Part of the +/// translation, so the shader cache must key on it (`victory-gpu`'s does). +pub fn set_helper_lane_waves(on: bool) { + HELPER_LANE_WAVES.store(on, std::sync::atomic::Ordering::Relaxed); +} + +/// See [`set_helper_lane_waves`]. +pub fn helper_lane_waves() -> bool { + HELPER_LANE_WAVES.load(std::sync::atomic::Ordering::Relaxed) +} + /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 441dae74353..f60cadab9bf 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -898,11 +898,23 @@ impl Shader { let ident = self.m.md_str("victory"); let ident = self.m.md_node(vec![Some(ident)]); self.m.named_md("llvm.ident", vec![ident]); + // Pixel shaders with wave operations run them over helper lanes + // too, as the console does (shader model 6.7), where the host can. + let helper_lanes = + self.pixel && self.flags & flags::WAVE_OPS != 0 && super::helper_lane_waves(); + if helper_lanes { + self.m.set_function_attr(self.main, Attr::HelperLaneWaves); + } + let minor = if helper_lanes { 7 } else { 6 }; let one = i32c(&mut self, 1); let six = i32c(&mut self, 6); - let version = self.m.md_node(vec![Some(one), Some(six)]); + let minor_c = i32c(&mut self, minor); + let version = self.m.md_node(vec![Some(one), Some(minor_c)]); self.m.named_md("dx.version", vec![version]); - self.m.named_md("dx.valver", vec![version]); + // The container's parts are written as validator 1.6 does (see + // `container::signature`), whatever the shader model. + let valver = self.m.md_node(vec![Some(one), Some(six)]); + self.m.named_md("dx.valver", vec![valver]); // Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh. let (name, kind) = match (self.threads, self.pixel) { _ if self.mesh.is_some() => ("ms", 13u32), @@ -912,16 +924,16 @@ impl Shader { (None, false) => ("vs", 1), }; let name = self.m.md_str(name); - let sm = self.m.md_node(vec![Some(name), Some(six), Some(six)]); + let sm = self.m.md_node(vec![Some(name), Some(six), Some(minor_c)]); self.m.named_md("dx.shaderModel", vec![sm]); self.m.named_md("dx.entryPoints", vec![entry]); let bitcode = self.m.write(); let mut dxil = Vec::with_capacity(24 + bitcode.len()); - dxil.extend((kind << 16 | 0x66).to_le_bytes()); + dxil.extend((kind << 16 | 0x60 | minor).to_le_bytes()); dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes()); dxil.extend(b"DXIL"); - dxil.extend(0x106u32.to_le_bytes()); + dxil.extend((0x100 | minor).to_le_bytes()); dxil.extend(16u32.to_le_bytes()); dxil.extend((bitcode.len() as u32).to_le_bytes()); dxil.extend(&bitcode);