Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions crates/victory-shader/src/emit/bitcode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,19 @@ pub(crate) struct Module {
}

impl Module {
/// Barrier flags emitted before cleanup, for translation regression tests.
#[cfg(test)]
pub(crate) fn barrier_modes(&self) -> Vec<u32> {
self.insts.iter()
.filter_map(|inst| match &inst.op {
Op::Call(f, args) if self.funcs[*f as usize].name == "dx.op.barrier" => {
Some(self.int_value(args[1]).expect("constant barrier flags") as u32)
}
_ => None,
})
.collect()
}

fn ty(&mut self, def: TypeDef) -> Ty {
if let Some(&t) = self.type_ids.get(&def) {
return Ty(t);
Expand Down
131 changes: 119 additions & 12 deletions crates/victory-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ pub(crate) struct Lowered {
/// Heap handles made with a non-uniform index.
#[cfg(test)]
pub nonuniform_handles: u32,
#[cfg(test)]
pub barrier_modes: Vec<u32>,
/// Whether the program uses wave operations.
#[cfg(test)]
pub wave_ops: bool,
Expand Down Expand Up @@ -1036,7 +1038,8 @@ pub(super) fn with_first_half_pairs<R>(translate: impl FnOnce() -> R) -> R {
result
}

pub(super) fn host_max_wave() -> u32 {
/// The host's widest wave, or zero before the device reports it.
pub fn host_max_wave() -> u32 {
#[cfg(test)]
if let Some(lanes) = TEST_HOST_WAVE.get() {
return lanes;
Expand Down Expand Up @@ -1241,6 +1244,30 @@ fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap<u8, u8> {
partners
}

/// The title's barrier retains its memory fences even when group sync
/// would wait for a host wave that never visits it. Explicit overrides
/// keep their old meanings; automatic mode is a targeted compatibility
/// workaround for narrow-wave hosts and is restricted to single-console-wave
/// groups (`group_threads <= console_wave`), so multi-console-wave groups
/// never lose cross-wave synchronization.
fn barrier_mode(
setting: u8,
host_wave: u32,
console_wave: u32,
group_threads: Option<u32>,
divergent: bool,
writes_uavs: bool,
) -> u32 {
let single_console_wave = group_threads.is_some_and(|t| t <= console_wave);
let waits = match setting {
0 => false,
1 => !divergent,
2 => true,
_ => !(host_wave != 0 && host_wave < console_wave && single_console_wave && divergent),
};
8 | if writes_uavs { 2 } else { 0 } | u32::from(waits)
}

fn unsupported(offset: usize, what: Why) -> Stop {
Stop::Fail(ShaderError::Unsupported { offset, what })
}
Expand Down Expand Up @@ -2288,6 +2315,8 @@ impl<'a> Lower<'a> {
#[cfg(test)]
nonuniform_handles: self.s.nonuniform_handles,
#[cfg(test)]
barrier_modes: self.s.m.barrier_modes(),
#[cfg(test)]
wave_ops: self.s.flags & flags::WAVE_OPS != 0,
dxil: self.s.finish(),
user_data,
Expand Down Expand Up @@ -4801,17 +4830,17 @@ impl<'a> Lower<'a> {
// Thread-group sync with a shared-memory fence, and a UAV
// fence when the program writes UAVs (the waits before an
// s_barrier make those writes visible on the console).
let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 };
// Without the wait for the group (bit 0) where not every
// lane arrives, or where the switch says so.
let waits = match super::group_sync() {
0 => false,
1 => !self.fence_only.contains(&b),
_ => true,
};
if !waits {
mode &= !1;
}
let setting = super::group_sync();
let divergent = self.fence_only.contains(&b);
let group_threads = self.s.threads.map(|t| t.iter().product());
let mode = barrier_mode(
setting,
host_max_wave(),
self.wave(),
group_threads,
divergent,
self.writes_uavs,
);
let mode = self.s.m.i32(mode);
let void = self.s.t.void;
self.s
Expand Down Expand Up @@ -11299,6 +11328,84 @@ mod tests {

const S_ENDPGM: u32 = 0xBF81_0000;

#[test]
fn automatic_barriers_keep_fences_and_only_drop_unsafe_sync() {
for writes in [false, true] {
let fence = 8 | if writes { 2 } else { 0 };
for (host, console, threads, divergent, waits) in [
(32, 64, Some(64), true, false),
(32, 64, Some(64), false, true),
(32, 64, Some(128), true, true),
(32, 64, None, true, true),
(64, 64, Some(64), true, true),
(32, 32, Some(32), true, true),
(0, 64, Some(64), true, true),
] {
assert_eq!(
super::barrier_mode(3, host, console, threads, divergent, writes),
fence | u32::from(waits),
);
}
assert_eq!(super::barrier_mode(0, 32, 64, Some(64), false, writes), fence);
assert_eq!(super::barrier_mode(1, 64, 64, Some(64), true, writes), fence);
assert_eq!(super::barrier_mode(1, 32, 64, Some(64), false, writes), fence | 1);
assert_eq!(super::barrier_mode(2, 32, 64, Some(64), true, writes), fence | 1);
}
}

#[test]
fn automatic_barrier_flags_reach_the_emitted_shader() {
let divergent = [
0x7D88_0090, // v_cmp_gt_u32 vcc, 16, v0
0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc
0xBF88_0001, // s_cbranch_execz past the barrier
0xBF8A_0000, // s_barrier
0xBEFE_040C, // s_mov_b64 exec, s[12:13]
];
let mut divergent32 = divergent;
divergent32[1] = 0xBE8C_3C6A; // s_and_saveexec_b32 s12, vcc_lo
divergent32[4] = 0xBEFE_030C; // s_mov_b32 exec_lo, s12
for (body, wave64, threads, host, expected) in [
(&divergent[..], true, 64, 32, 8),
(&divergent[..], true, 128, 32, 9),
(&divergent[..], true, 64, 64, 9),
(&divergent32[..], false, 64, 32, 9),
(&[0xBF8A_0000][..], true, 64, 32, 9),
] {
let native = NativeProgram {
stage: HwStage::Cs,
wave64,
vgprs: 16,
layout: vec![],
used: vec![],
io: StageIo::Cs(ComputeIo { rsrc2: 0, threads: [threads, 1, 1] }),
code: body.iter().copied().chain([S_ENDPGM])
.flat_map(u32::to_le_bytes).collect(),
};
let p = ir::build(&native.code, wave64, native.vgprs).expect("IR");
let st = structure::structure(&p).expect("structure");
let res = resource::track(&p, &[], native.stage, Some(&st)).expect("resources");
let io = io::raise(&p, &native).expect("IO");
let old_wave = super::TEST_HOST_WAVE.replace(Some(host));
let old_mode = super::super::TEST_GROUP_SYNC.replace(Some(3));
let shader = lower(&Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: vec![],
outputs: vec![],
prims: vec![],
mesh_stride: 0,
});
super::TEST_HOST_WAVE.set(old_wave);
super::super::TEST_GROUP_SYNC.set(old_mode);
let shader = shader.unwrap_or_else(|e| panic!("wave64={wave64}, host={host}: {e:?}"));
assert_eq!(shader.barrier_modes, vec![expected]);
}
}

#[test]
fn packed_pixel_inputs_find_their_second_row() {
use super::super::container::SigElement;
Expand Down
37 changes: 32 additions & 5 deletions crates/victory-shader/src/emit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ use crate::{ShaderError, io, ir, resource, structure};

pub use bitcode::census;
pub use sampler::StaticSampler;
pub use lower::set_host_max_wave;
pub use lower::{host_max_wave, set_host_max_wave};
pub use rect::rect_list_gs;
pub use shader::{
MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
Expand Down Expand Up @@ -148,7 +148,10 @@ pub fn loop_limit() -> u32 {
/// thread: the group stands until Windows resets the card. (The console's
/// barrier is the wave's, whatever lanes are live, and a wave that ended
/// is not waited for.) `VICTORY_GROUP_SYNC`:
/// - unset or `2`: every barrier waits, as before.
/// - unset or `auto`: on hosts narrower than the console wave, the title's
/// divergent barriers retain their memory fences but do not wait. Other
/// hosts and uniform barriers keep their group sync.
/// - `2`: every barrier waits, as before.
/// - `1`: the title's `s_barrier` waits only in a block every lane runs,
/// in a program no lane can be cut out of at the iteration limit.
/// - `0`: no barrier waits, neither the title's nor the ones the
Expand All @@ -160,12 +163,26 @@ pub fn loop_limit() -> u32 {
/// Part of the translation: the shader cache keys on it (`victory-gpu`'s
/// does).
pub fn group_sync() -> u8 {
#[cfg(test)]
if let Some(mode) = TEST_GROUP_SYNC.get() {
return mode;
}
static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) {
*MODE.get_or_init(|| parse_group_sync(std::env::var("VICTORY_GROUP_SYNC").ok().as_deref()))
}

#[cfg(test)]
thread_local! {
static TEST_GROUP_SYNC: std::cell::Cell<Option<u8>> = const { std::cell::Cell::new(None) };
}

fn parse_group_sync(value: Option<&str>) -> u8 {
match value.map(str::trim) {
Some("0") => 0,
Some("1") => 1,
_ => 2,
})
Some("2") => 2,
_ => 3,
}
}

/// The clean-up passes that run over a translated program before it is
Expand Down Expand Up @@ -803,6 +820,16 @@ mod tests {
use super::lower::LOOP_LIMIT;
use super::parse_loop_limit;

#[test]
fn group_sync_defaults_to_auto_and_keeps_explicit_overrides() {
for value in [None, Some("auto"), Some(""), Some("invalid")] {
assert_eq!(super::parse_group_sync(value), 3);
}
for (value, mode) in [("0", 0), (" 1 ", 1), ("2", 2)] {
assert_eq!(super::parse_group_sync(Some(value)), mode);
}
}

#[test]
fn the_clean_up_switch_parses_or_runs_every_pass() {
let all = super::bitcode::opt::ALL;
Expand Down
58 changes: 58 additions & 0 deletions crates/victory-shader/src/emit/wave64_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,3 +530,61 @@ fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide()
}
eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside");
}

/// A barrier entered by only part of a console wave must complete on a
/// wave32 GPU without disabling uniform barriers or translation-added sync.
#[test]
fn an_automatic_barrier_inside_a_lane_branch_runs_on_narrow_hardware() {
let words = [
0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0
0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc
0xBF88_0001, // s_cbranch_execz over the barrier
0xBF8A_0000, // s_barrier
0xBEFE_040C, // s_mov_b64 exec, s[12:13]
0x7E00_0293, // v_mov_b32 v0, 19
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
];
let native = native(&words);
let p = ir::build(&native.code, true, native.vgprs).expect("ir::build");
let old_mode = super::TEST_GROUP_SYNC.replace(Some(3));
let shader = lowered(&native, &p, &HashSet::new());
super::TEST_GROUP_SYNC.set(old_mode);
let shader = shader.expect("lower divergent barrier");
if let Ok(mut validator) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut dxil = shader.dxil.clone();
validator.validate(&mut dxil).expect("DXIL validation");
}
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let Ok(host) = Host::new(false) else {
eprintln!("no SM 6.6 hardware device; not run");
return;
};
let mut waves = windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
// SAFETY: a plain feature query on the live device.
unsafe {
host.device.CheckFeatureSupport(
windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_D3D12_OPTIONS1,
(&raw mut waves).cast(), size_of_val(&waves) as u32,
).expect("host wave capabilities");
}
if waves.WaveLaneCountMax >= 64 || waves.WaveLaneCountMax == 0 {
eprintln!("no narrow-wave hardware device; not run");
return;
}
let (root, pso) = host.compute_pipeline(&shader).expect("pipeline on narrow-wave hardware");
for below in [1, 10, 32, 33, 64] {
let mut ud = vec![0; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
if let (RootType::Constants, 0, 0) = (u.root, u.slot, u.dword) {
ud[u.index as usize] = below;
}
}
let out = host.dispatch(&root, &pso, &Dispatch {
roots: vec![(0, Root::Constants(ud))], views: &[View::RawUav(1)],
samplers: &[], groups: [1, 1, 1],
}).expect("divergent barrier dispatch completes");
assert_eq!(out[0][0], 19, "{below} lanes enter the barrier");
}
eprintln!("ran automatic divergent barriers on hardware (max wave {}): 1, 10, 32, 33 and 64 active lanes", waves.WaveLaneCountMax);
}