diff --git a/Cargo.lock b/Cargo.lock index bab4a7e..aaee366 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -226,6 +226,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "indexmap" version = "2.14.2" @@ -723,6 +729,7 @@ version = "0.1.0" dependencies = [ "anyhow", "blake3", + "hex", "tempfile", "thiserror", "tracing", diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 7ac09a1..5daa839 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -616,6 +616,54 @@ impl Layout { ) } + /// The byte ranges of tiled memory that [`Layout::detile`] reads for + /// mip `mip` of array slice `slice` (3D: every depth slice of the mip, + /// `slice` 0): sorted, disjoint, one per depth slice or slab at most. + /// A mip in the tail gets the part of the tail block its elements span, + /// which other tail mips may share; a write outside every range leaves + /// the subresource's detiled contents as they were. + pub fn extents(&self, mip: u32, slice: u32) -> Result>, Error> { + let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; + let bytes = m.width as usize * self.desc.element_bytes as usize; + let depth_pitch = bytes * m.height as usize; + let mut spans: Vec> = Vec::new(); + let z_of = |linear: usize| linear / depth_pitch; + let mut current: Option<(usize, std::ops::Range)> = None; + self.walk( + self.size as usize, + mip, + slice, + usize::MAX, + bytes, + depth_pitch, + |tiled, linear, len| { + let z = z_of(linear); + let run = tiled as u64..(tiled + len) as u64; + match &mut current { + Some((at, r)) if *at == z => { + r.start = r.start.min(run.start); + r.end = r.end.max(run.end); + } + _ => { + if let Some((_, r)) = current.replace((z, run)) { + spans.push(r); + } + } + } + }, + )?; + spans.extend(current.map(|(_, r)| r)); + spans.sort_by_key(|r| r.start); + let mut merged: Vec> = Vec::with_capacity(spans.len()); + for r in spans { + match merged.last_mut() { + Some(last) if r.start <= last.end => last.end = last.end.max(r.end), + _ => merged.push(r), + } + } + Ok(merged) + } + /// The reverse of [`Layout::detile`]: linear rows into tiled memory. pub fn tile( &self, @@ -984,6 +1032,85 @@ mod tests { } } + /// A subresource's extents hold every element it detiles, and bytes + /// outside them do not change what it detiles to. + #[test] + fn extents_hold_what_a_subresource_detiles() { + let cases = [ + desc(64, 64, 7, 16, Swizzle::SW_64KB_D), + desc(100, 60, 7, 4, Swizzle::SW_64KB_D), + desc(250, 175, 8, 8, Swizzle::SW_4KB_S), + desc(33, 17, 6, 1, Swizzle::SW_4KB_D), + desc(30, 20, 5, 4, Swizzle::LINEAR), + desc(83, 31, 6, 1, Swizzle::SW_256B_S), + Desc { + depth: 3, + ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S) + }, + Desc { + depth: 4, + ..desc(30, 20, 3, 4, Swizzle::LINEAR) + }, + Desc { + dimension: Dimension::Tex3d, + depth: 16, + ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S) + }, + ]; + for d in cases { + let l = Layout::new(&d).unwrap(); + let size = l.size as usize; + let tiled: Vec = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + let slices = if d.dimension == Dimension::Tex3d { + 1 + } else { + d.depth + }; + for slice in 0..slices { + for mip in 0..d.mips { + let e = l.extents(mip, slice).unwrap(); + assert!(!e.is_empty(), "{d:?} mip {mip} slice {slice}"); + for w in e.windows(2) { + assert!(w[0].end < w[1].start, "{d:?} mip {mip}: {e:?}"); + } + assert!(e.iter().all(|r| r.start < r.end && r.end <= l.size)); + let inside = |at: u64| e.iter().any(|r| r.contains(&at)); + let m = l.mips[mip as usize]; + let n = u64::from(d.element_bytes); + // Outside the tail a 2D mip's extent is its own blocks. + if m.tail.is_none() && d.dimension != Dimension::Tex3d { + let total: u64 = e.iter().map(|r| r.end - r.start).sum(); + let own = u64::from(m.pitch) * u64::from(m.rows) * n; + assert!(total <= own, "{d:?} mip {mip}: {total} > {own}"); + } + for z in 0..m.depth { + for y in 0..m.height { + for x in 0..m.width { + let at = l.offset(mip, x, y, slice + z).unwrap(); + assert!(inside(at) && inside(at + n - 1), "{d:?} mip {mip}"); + } + } + } + let row = m.width as usize * n as usize; + let plane = row * m.height as usize; + let mut before = vec![0; plane * m.depth as usize]; + l.detile(&tiled, mip, slice, &mut before, row, plane) + .unwrap(); + let mut changed = tiled.clone(); + for (i, b) in changed.iter_mut().enumerate() { + if !inside(i as u64) { + *b = !*b; + } + } + let mut after = vec![0; before.len()]; + l.detile(&changed, mip, slice, &mut after, row, plane) + .unwrap(); + assert_eq!(before, after, "{d:?} mip {mip} slice {slice}"); + } + } + } + } + /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12, /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first. diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 1182eb7..e3c4176 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -723,6 +723,9 @@ static FUNCTIONS: Table<24> = { Table(f) }; +#[cfg(all(test, windows))] +pub(crate) use tests::test_view_heap; + #[cfg(test)] mod tests { use super::*; @@ -738,6 +741,28 @@ mod tests { create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out) } + #[cfg(windows)] + pub(crate) fn test_view_heap(count: u32) -> This { + let mut heap = std::ptr::null(); + assert_eq!( + create( + HeapDesc { + kind: VIEWS_KIND, + count, + flags: SHADER_VISIBLE, + nodes: 0, + }, + Placement { + address: 0, + size: 0, + }, + &mut heap, + ), + S_OK + ); + heap + } + #[test] fn heaps_hold_count_descriptors_from_their_start() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 16c6151..f436fd7 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -74,23 +74,26 @@ pub(crate) struct State { /// Tables made afresh in this list: (table, what it holds) → first /// dynamic slot. fresh_tables: std::collections::HashMap<(u64, u64), u32>, + /// Dynamic slots held by the recording, plus their cache keys so a + /// rejected bind can give back only the tables it reserved. + dynamic: Vec, /// Root SRV views made in this list: (title heap, title address) → /// dynamic slot (see [`State::bind_root_srv`]). root_srv_slots: std::collections::HashMap<(usize, u64), u32>, - /// The dynamic slots the list holds: title heap, first, count; given - /// back when the list is reset or released. - dynamic: Vec<(usize, u32, u32)>, - /// A fresh table of the stage being bound could not be made. - table_failed: bool, /// Address maps made in this list: title view heap, host GPU address. maps: Vec<(usize, u64)>, } -impl Drop for State { +struct FreshTable { + key: (u64, u64), + heap: usize, + first: u32, + count: u32, +} + +impl Drop for FreshTable { fn drop(&mut self) { - for &(heap, first, n) in &self.dynamic { - crate::descriptor::release_dynamic(heap, first, n); - } + crate::descriptor::release_dynamic(self.heap, self.first, self.count); } } @@ -282,10 +285,13 @@ impl State { let Some(texture) = crate::resource::host_resource(record.resource) else { continue; }; + let Some(rtv) = host.rtv(texture, record.desc().as_ref()) else { + continue; + }; self.targets.push(record.resource as usize); #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); - rtvs.push(host.rtv(texture, record.desc().as_ref())); + rtvs.push(rtv); } self.depth = 0; let dsv = crate::descriptor::dsv_record(depth).and_then(|record| { @@ -469,11 +475,11 @@ impl State { list.keep(&p.pso); list.keep(&p.root); } + let reserved_before_bind = self.dynamic.len(); for stage in &p.stages { let t = stage.translated(); - self.table_failed = false; - let made = self.tables(list, &t.used, compute); - if self.table_failed { + let Some(made) = self.tables(list, &t.used, compute) else { + self.release_rejected_tables(reserved_before_bind); static DROPPED_TABLES: AtomicU64 = AtomicU64::new(0); let n = DROPPED_TABLES.fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() { @@ -483,7 +489,7 @@ impl State { ); } return false; - } + }; if let Some((param, dwords)) = stage.user_data { let mut values = vec![0u32; dwords as usize]; for u in &t.host.user_data { @@ -517,7 +523,12 @@ impl State { (None, Some(h)) => { crate::address_map::make(list, h).map(|(gpu, (first, n))| { if n > 0 { - self.dynamic.push((self.heaps[0], first, n)); + self.dynamic.push(FreshTable { + key: (0, 0), + heap: self.heaps[0], + first, + count: n, + }); } self.maps.push((self.heaps[0], gpu)); gpu @@ -622,7 +633,12 @@ impl State { once!("no free dynamic slot for a root SRV: left unset"); return; }; - self.dynamic.push((heap, index, 1)); + self.dynamic.push(FreshTable { + key: (0, 0), + heap, + first: index, + count: 1, + }); self.root_srv_slots.insert((heap, address), index); match shadow { Some((shadow, address)) => { @@ -773,13 +789,19 @@ impl State { /// the constant data copied to upload memory when the list is /// submitted: the host wants constant buffers 256-byte aligned, the /// console only 16. Returns those tables' new byte offsets by root - /// parameter; the other tables' slots are made from the title's. + /// parameter; the other tables' slots are made from the title's. If + /// the heap cannot fit a fresh table, the bind must release its reservations. /// /// Within a list, the same table holding the same descriptors is made /// once: its constant data is copied at submission either way, and the /// big tables the world binds would otherwise take hundreds of slots per /// draw, wrapping the dynamic slots onto lists not yet submitted. - fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> { + fn tables( + &mut self, + list: &HostList, + used: &[UsedResource], + compute: bool, + ) -> Option> { let tables = |u: &&UsedResource| u.root == RootType::Table; let mut fresh: Vec = used .iter() @@ -863,12 +885,15 @@ impl State { // view: a texture or null descriptor read as a buffer gives // a wild address on AMD and the device is removed (#59). // The draw or dispatch is dropped instead. - self.table_failed = true; - continue; + return None; }; self.fresh_tables.insert(key, first); - self.dynamic - .push((std::ptr::from_ref(heap) as usize, first, n)); + self.dynamic.push(FreshTable { + key, + heap: std::ptr::from_ref(heap) as usize, + first, + count: n, + }); // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { @@ -899,7 +924,13 @@ impl State { } made.push((slot, first * 32)); } - made + Some(made) + } + + fn release_rejected_tables(&mut self, reserved_before_bind: usize) { + for table in self.dynamic.drain(reserved_before_bind..) { + self.fresh_tables.remove(&table.key); + } } /// The first draws, at debug level: what they bind and read @@ -1358,3 +1389,114 @@ pub(crate) fn stencil_ref(list: &HostList, reference: u32) { // SAFETY: an open list. unsafe { list.list.OMSetStencilRef(reference) }; } + +#[cfg(test)] +mod tests { + use super::*; + use crate::descriptor::{heap, test_view_heap}; + use crate::pipeline::{Shader, Translated}; + use victory_shader::{HwStage, emit::HostShader}; + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + use windows::core::s; + + #[test] + fn rejected_bind_releases_only_its_new_tables() { + let Some(host) = crate::host::host() else { + return; + }; + let list = host.new_list().unwrap(); + let source = b"[numthreads(1,1,1)] void main() {}"; + let mut code: Option = None; + // SAFETY: the source is live and the out pointer is valid. + unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + s!("test"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + None, + ) + } + .unwrap(); + let code = code.unwrap(); + // SAFETY: the blob owns the returned byte range. + let dxil = unsafe { + std::slice::from_raw_parts(code.GetBufferPointer().cast(), code.GetBufferSize()) + } + .to_vec(); + let used = [2, 4, 3] + .into_iter() + .enumerate() + .map(|(slot, size)| UsedResource { + kind: ResourceType::Cbv, + root: RootType::Table, + table_offset_dwords: (size - 1) * 8, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: slot as u8, + }) + .collect(); + let shader = Shader::test_compute(Translated { + host: HostShader { + stage: HwStage::Cs, + dxil, + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + address_map: false, + descriptor_words: false, + }, + used, + }); + let pipeline = HostPipeline::new(&[shader], None).unwrap(); + let title_heap = test_view_heap(9); + let guest = heap(title_heap); + let view_heap = guest.host().unwrap(); + // SAFETY: a live heap. + let capacity = unsafe { view_heap.heap.GetDesc() }.NumDescriptors - view_heap.count(); + + let mut state = State::default(); + state.heaps[0] = title_heap as usize; + state.set_table(true, 0, guest.start); + assert!(state.bind(&list, &pipeline, true)); + assert_eq!(state.dynamic.len(), 1); + let (&accepted_key, &accepted_first) = state.fresh_tables.iter().next().unwrap(); + + // Leave six slots after the accepted two-slot table. A four-slot + // table fits but the following three-slot table cannot fit. + let blocker = view_heap.dynamic(capacity - 8).unwrap(); + state.set_table(true, 1, guest.start + 2 * 32); + state.set_table(true, 2, guest.start + 6 * 32); + assert!(!state.bind(&list, &pipeline, true)); + assert_eq!(state.dynamic.len(), 1); + assert_eq!(state.fresh_tables.len(), 1); + assert_eq!(state.fresh_tables[&accepted_key], accepted_first); + + // Check both free ranges independently because the upstream scan + // splits a run at its cursor (issue #871). + let tail = view_heap.dynamic(2).unwrap(); + let returned = view_heap.dynamic(4).unwrap(); + assert_eq!(returned + 4, tail); + assert!(view_heap.dynamic(1).is_none()); + view_heap.release(tail, 2); + view_heap.release(returned, 4); + view_heap.release(blocker, capacity - 8); + + assert!(state.bind(&list, &pipeline, true)); + assert_eq!(state.dynamic.len(), 3); + assert_eq!(state.fresh_tables[&accepted_key], accepted_first); + drop(state); + crate::object::slot:: u32>(title_heap, 0x10)(title_heap); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d5214fe..7f9246c 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -782,12 +782,18 @@ impl Host { first_error } - /// A host render target view of `resource`, valid until it is recorded. + /// A host render target view of `resource`, valid until it is recorded, + /// or `None` if the host resource lacks `ALLOW_RENDER_TARGET`. pub(crate) fn rtv( &self, resource: &ID3D12Resource, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>, - ) -> D3D12_CPU_DESCRIPTOR_HANDLE { + ) -> Option { + // SAFETY: a live resource. + let flags = unsafe { resource.GetDesc() }.Flags; + if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 == 0 { + return None; + } let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING; // SAFETY: a slot of our heap and a live resource. unsafe { @@ -795,7 +801,7 @@ impl Host { handle.ptr += (slot * self.rtv_size) as usize; self.device .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle); - handle + Some(handle) } } diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 778011d..37bd405 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -708,7 +708,9 @@ extern "system" fn clear_rtv( unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } }); const RENDER_TARGET: u32 = 0x4; - let rtv = host.rtv(texture, record.desc().as_ref()); + let Some(rtv) = host.rtv(texture, record.desc().as_ref()) else { + return; + }; // SAFETY: an open list, a fresh view of a live texture. unsafe { if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) { @@ -878,11 +880,31 @@ extern "system" fn set_pipeline(this: This, pipeline: This) { let _ = this; } +/// Records a global UAV barrier on `this`'s host list so earlier shader +/// writes finish before later GPU work starts. +fn wait_for_shader_writes(this: This) { + #[cfg(windows)] + if let Some(list) = host_list(this) { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + // SAFETY: `Barrier` matches `D3D12_RESOURCE_BARRIER` in layout, and + // `UAV_BARRIER` names no resource (`first` is null). + let barrier = + unsafe { std::mem::transmute::(UAV_BARRIER) }; + // SAFETY: `list.list` is an open host command list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } + #[cfg(not(windows))] + let _ = this; +} + /// Pipeline syncs: waits for earlier work and cache flushes, at the top or -/// bottom of the pipe `(flags, control, address, size)`. Host lists order -/// their own work and every submission is waited for, so there is nothing -/// to do. -extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {} +/// bottom of the pipe `(flags, control, address, size)`. Within a single +/// command list, earlier shader writes must finish before later dispatches +/// or draws read or write the same resources, so record a UAV barrier on +/// the host list. +extern "system" fn sync(this: This, _flags: u32, _control: u32, _address: u64, _size: u64) { + wait_for_shader_writes(this); +} /// Reset with console flags `(allocator, pipeline, flags)`; the flags only /// tune the console's command memory. @@ -1262,19 +1284,9 @@ extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _referen /// first, so only their ordering matters: one barrier on every shader /// write (the title's buffer barriers order compute passes). extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { - #[cfg(windows)] - if count > 0 - && let Some(list) = host_list(this) - { - use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; - // SAFETY: the same layout; no resource named. - let barrier = - unsafe { std::mem::transmute::(UAV_BARRIER) }; - // SAFETY: an open list. - unsafe { list.list.ResourceBarrier(&[barrier]) }; + if count > 0 { + wait_for_shader_writes(this); } - #[cfg(not(windows))] - let _ = (this, count); } /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and @@ -1482,4 +1494,285 @@ mod tests { assert_eq!(release(list), 0); assert_eq!(release(allocator), 0); } + + fn non_host_list(newer: bool) -> This { + let table = if newer { + &NEWER_LIST_FUNCTIONS + } else { + &LIST_FUNCTIONS + }; + Box::into_raw(Box::new(List { + object: Object::new(table), + kind: 0, + put: [0; 5], + reserved: [0; 64], + graphics_root_headers: [0; 128], + compute_root_headers: [0; 128], + pipeline_shadow: [0; 8], + newer: [0; 256], + uploads: Default::default(), + #[cfg(windows)] + host: None, + #[cfg(windows)] + state: Default::default(), + })) + .cast() + } + + #[test] + fn sync_is_safe_on_null_and_non_host_lists() { + type SyncFn = extern "system" fn(This, u32, u32, u64, u64); + type BarrierGroupsFn = extern "system" fn(This, u32, *const u8); + + let base = list_table(false); + assert_eq!(base[129], sync as *const ()); + assert_eq!(base[130], sync as *const ()); + let newer = list_table(true); + assert_eq!(newer[131], sync as *const ()); + assert_eq!(newer[132], sync as *const ()); + assert_eq!(newer[146], barrier_groups as *const ()); + + sync(std::ptr::null(), 1, 2, 0x1000, 64); + barrier_groups(std::ptr::null(), 1, std::ptr::null()); + + for (is_newer, slots) in [(false, [129usize, 130]), (true, [131usize, 132])] { + let list = non_host_list(is_newer); + for slot_index in slots { + let offset = slot_index * size_of::<*const ()>(); + slot::(list, offset)(list, 0, 0, 0, 0); + slot::(list, offset)(list, 0x3, 0x1, 0xdead_beef, 256); + } + if is_newer { + let offset = 146 * size_of::<*const ()>(); + slot::(list, offset)(list, 0, std::ptr::null()); + slot::(list, offset)(list, 2, std::ptr::null()); + } + assert_eq!(slot:: u32>(list, 0x10)(list), 0); + } + } + + #[cfg(windows)] + #[test] + fn sync_orders_dependent_compute_uav_dispatches() { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_COMPUTE_PIPELINE_STATE_DESC, D3D12_SHADER_BYTECODE, ID3D12PipelineState, + ID3D12RootSignature, + }; + use windows::core::s; + + let Some(host) = crate::host::host() else { + return; + }; + + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=2, b0), UAV(u0), UAV(u1)" +cbuffer Params : register(b0) { uint count; uint stage; }; +RWByteAddressBuffer buf_a : register(u0); +RWByteAddressBuffer buf_b : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= count) return; + if (stage == 0u) { + uint v = id.x ^ 0xA5A50001u; + for (uint k = 0u; k < 32u; ++k) { + v = v * 1664525u + 1013904223u; + } + buf_a.Store(id.x * 4u, v); + } else if (stage == 1u) { + uint rev = count - 1u - id.x; + uint v = buf_a.Load(rev * 4u); + buf_b.Store(id.x * 4u, v + 1u); + } else if (stage == 2u) { + uint rev = count - 1u - id.x; + uint v = buf_b.Load(rev * 4u); + buf_a.Store(id.x * 4u, v * 3u); + } else { + uint rev = count - 1u - id.x; + uint v = buf_a.Load(rev * 4u); + buf_b.Store(id.x * 4u, v ^ 0x55AA55AAu); + } +} +"#; + + let mut code: Option = None; + let mut errors: Option = None; + // SAFETY: valid static HLSL source and entry-point/target names. + let compiled = unsafe { + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + s!("sync_ordering_test"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(e) = compiled { + let msg = errors + .map(|b| { + // SAFETY: the compiler error blob owns its bytes. + let slice = unsafe { + std::slice::from_raw_parts( + b.GetBufferPointer().cast::(), + b.GetBufferSize(), + ) + }; + String::from_utf8_lossy(slice).into_owned() + }) + .unwrap_or_default(); + panic!("D3DCompile failed ({e}): {msg}"); + } + let code = code.expect("compiled shader blob"); + // SAFETY: `code` owns valid DXBC bytes containing an embedded root signature. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let bytes = std::slice::from_raw_parts( + code.GetBufferPointer().cast::(), + code.GetBufferSize(), + ); + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, bytes).unwrap(); + let pso = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + }) + .unwrap(); + (root, pso) + }; + + const COUNT: u32 = 65_536; + const GROUPS: u32 = COUNT / 64; + let bytes = u64::from(COUNT) * 4; + let (buf_a, ptr_a) = host.shared_buffer(bytes).expect("shared buffer A"); + let (buf_b, ptr_b) = host.shared_buffer(bytes).expect("shared buffer B"); + // SAFETY: `ptr_a` and `ptr_b` point to `bytes` mapped bytes each. + unsafe { + ptr_a.write_bytes(0, bytes as usize); + ptr_b.write_bytes(0, bytes as usize); + } + // SAFETY: live D3D12 buffer resources. + let (gpu_a, gpu_b) = + unsafe { (buf_a.GetGPUVirtualAddress(), buf_b.GetGPUVirtualAddress()) }; + + let null = std::ptr::null(); + let mut allocator = null; + assert_eq!( + create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), + S_OK + ); + let mut list = null; + assert_eq!( + create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), + S_OK + ); + let hl = host_list(list).expect("host list present when host GPU exists"); + + // `device::tests::newer_device_levels_are_the_same_device` may flip + // `device::newer()` in parallel, so inspect this list's own vtable. + // SAFETY: `list` starts with `Object` whose first pointer is its vtable. + let is_newer = unsafe { + std::ptr::eq( + *list.cast::<*const *const ()>(), + NEWER_LIST_FUNCTIONS.0.as_ptr(), + ) + }; + let (top_slot, bottom_slot) = if is_newer { + (newer_slot(129), newer_slot(130)) + } else { + (129, 130) + }; + + type SyncFn = extern "system" fn(This, u32, u32, u64, u64); + let sync_top = slot::(list, top_slot * size_of::<*const ()>()); + let sync_bottom = slot::(list, bottom_slot * size_of::<*const ()>()); + + // SAFETY: `hl.list` is an open list and `root`, `pso`, `buf_a`, `buf_b` outlive execution. + unsafe { + hl.list.SetComputeRootSignature(&root); + hl.list.SetPipelineState(&pso); + hl.list.SetComputeRootUnorderedAccessView(1, gpu_a); + hl.list.SetComputeRootUnorderedAccessView(2, gpu_b); + + let p0 = [COUNT, 0u32]; + hl.list + .SetComputeRoot32BitConstants(0, 2, p0.as_ptr().cast(), 0); + hl.list.Dispatch(GROUPS, 1, 1); + + sync_top(list, 0, 0, 0, 0); + + let p1 = [COUNT, 1u32]; + hl.list + .SetComputeRoot32BitConstants(0, 2, p1.as_ptr().cast(), 0); + hl.list.Dispatch(GROUPS, 1, 1); + + sync_bottom(list, 0x1, 0x2, 0x1000, 64); + + let p2 = [COUNT, 2u32]; + hl.list + .SetComputeRoot32BitConstants(0, 2, p2.as_ptr().cast(), 0); + hl.list.Dispatch(GROUPS, 1, 1); + + // `count == 0` is a no-op; `count > 0` orders pass 3 after pass 2. + barrier_groups(list, 0, std::ptr::null()); + barrier_groups(list, 1, std::ptr::null()); + + let p3 = [COUNT, 3u32]; + hl.list + .SetComputeRoot32BitConstants(0, 2, p3.as_ptr().cast(), 0); + hl.list.Dispatch(GROUPS, 1, 1); + } + + assert_eq!( + slot:: HRESULT>(list, 0x48)(list), + S_OK + ); + host.execute(&[hl]); + + // SAFETY: `host.execute` waited for GPU completion; both mappings cover `COUNT` u32s. + let (out_a, out_b) = unsafe { + ( + std::slice::from_raw_parts(ptr_a.cast::(), COUNT as usize), + std::slice::from_raw_parts(ptr_b.cast::(), COUNT as usize), + ) + }; + for i in 0..COUNT { + let mut v = i ^ 0xA5A5_0001; + for _ in 0..32 { + v = v.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + } + let expected_a = v.wrapping_add(1).wrapping_mul(3); + assert_eq!( + out_a[i as usize], expected_a, + "ordering mismatch in buf_a at {i}" + ); + + let rev = COUNT - 1 - i; + let mut v_rev = rev ^ 0xA5A5_0001; + for _ in 0..32 { + v_rev = v_rev.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + } + let expected_b = v_rev.wrapping_add(1).wrapping_mul(3) ^ 0x55AA_55AA; + assert_eq!( + out_b[i as usize], expected_b, + "ordering mismatch in buf_b at {i}" + ); + } + + assert_eq!(reset(list, allocator, null), S_OK); + let release = |o: This| slot:: u32>(o, 0x10)(o); + assert_eq!(release(list), 0); + assert_eq!(release(allocator), 0); + } } diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index dcf0a3a..08a17ac 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -104,6 +104,16 @@ pub(crate) struct Translated { #[cfg(windows)] impl Shader { + #[cfg(test)] + pub(crate) fn test_compute(translated: Translated) -> Arc { + Arc::new(Self { + stage: "compute", + hash: "test-compute".into(), + container: Vec::new(), + translated: OnceLock::from(Some(translated)), + }) + } + /// The translation, made on first use; a shader that does not /// translate is logged once. pub(crate) fn translated(&self) -> Option<&Translated> { diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 60bb05c..ae6baa7 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -100,6 +100,65 @@ impl Default for GraphicsState { } } +/// Integer render target formats: D3D12 cannot blend into them. +fn integer_format(f: DXGI_FORMAT) -> bool { + matches!( + f, + DXGI_FORMAT_R32G32B32A32_UINT + | DXGI_FORMAT_R32G32B32A32_SINT + | DXGI_FORMAT_R32G32B32_UINT + | DXGI_FORMAT_R32G32B32_SINT + | DXGI_FORMAT_R16G16B16A16_UINT + | DXGI_FORMAT_R16G16B16A16_SINT + | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R32G32_SINT + | DXGI_FORMAT_R10G10B10A2_UINT + | DXGI_FORMAT_R8G8B8A8_UINT + | DXGI_FORMAT_R8G8B8A8_SINT + | DXGI_FORMAT_R16G16_UINT + | DXGI_FORMAT_R16G16_SINT + | DXGI_FORMAT_R32_UINT + | DXGI_FORMAT_R32_SINT + | DXGI_FORMAT_R8G8_UINT + | DXGI_FORMAT_R8G8_SINT + | DXGI_FORMAT_R16_UINT + | DXGI_FORMAT_R16_SINT + | DXGI_FORMAT_R8_UINT + | DXGI_FORMAT_R8_SINT + ) +} + +/// The title's blend state as the host takes it: blending off on integer +/// render targets. The console ignores blending there, and titles leave it +/// on (the world sets it on an `R8_UINT` target), but D3D12 does not allow +/// it: vkd3d-proton refuses such a pipeline with `E_INVALIDARG` ("using +/// integer format is not supported"), and its draws are lost. With one +/// description for every target, each target gets its own copy so the +/// others keep theirs. +fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D12_BLEND_DESC { + let count = (targets.NumRenderTargets as usize).min(8); + let per_target = blend.IndependentBlendEnable.as_bool(); + let blends = |i: usize| { + blend.RenderTarget[if per_target { i } else { 0 }] + .BlendEnable + .as_bool() + }; + if !(0..count).any(|i| integer_format(targets.RTFormats[i]) && blends(i)) { + return *blend; + } + let mut host = *blend; + if !per_target { + host.IndependentBlendEnable = true.into(); + host.RenderTarget = [blend.RenderTarget[0]; 8]; + } + for i in 0..count { + if integer_format(targets.RTFormats[i]) { + host.RenderTarget[i].BlendEnable = false.into(); + } + } + host +} + impl GraphicsState { /// Takes in one subobject of a stream: its type, then its data at +4 /// (+8 for those holding pointers). @@ -111,16 +170,22 @@ impl GraphicsState { unsafe { let data = at.add(4); match kind { - 8 => self.blend = data.cast::().read_unaligned(), + 8 => self.blend = clean_blend(data.cast::().read_unaligned()), 9 => self.sample_mask = data.cast::().read_unaligned(), - 10 => self.rasterizer = data.cast::().read_unaligned(), - 11 => self.depth = data.cast::().read_unaligned(), + 10 => { + self.rasterizer = + clean_rasterizer(data.cast::().read_unaligned()) + } + 11 => { + self.depth = + clean_depth(data.cast::().read_unaligned()) + } 21 => { // shortcut: the depth bounds test is dropped (the host // pipeline uses the plain description); bring it back // with a stream if a title enables it. let d = data.cast::().read_unaligned(); - self.depth = D3D12_DEPTH_STENCIL_DESC { + self.depth = clean_depth(D3D12_DEPTH_STENCIL_DESC { DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, DepthFunc: d.DepthFunc, @@ -129,7 +194,7 @@ impl GraphicsState { StencilWriteMask: d.StencilWriteMask, FrontFace: d.FrontFace, BackFace: d.BackFace, - }; + }); } 12 => { let layout = at.add(8).cast::().read_unaligned(); @@ -147,12 +212,18 @@ impl GraphicsState { self.inputs = elements .iter() .zip(&self.names) - .map(|(e, name)| D3D12_INPUT_ELEMENT_DESC { - SemanticName: PCSTR(name.as_ptr().cast()), - Format: DXGI_FORMAT( - crate::resource::pc_format(e.Format.0 as u32) as i32 - ), - ..*e + .map(|(e, name)| { + // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. + let mut out: D3D12_INPUT_ELEMENT_DESC = std::mem::zeroed(); + out.SemanticName = PCSTR(name.as_ptr().cast()); + out.SemanticIndex = e.SemanticIndex; + out.Format = + DXGI_FORMAT(crate::resource::pc_format(e.Format.0 as u32) as i32); + out.InputSlot = e.InputSlot; + out.AlignedByteOffset = e.AlignedByteOffset; + out.InputSlotClass = e.InputSlotClass; + out.InstanceDataStepRate = e.InstanceDataStepRate; + out }) .collect(); } @@ -165,10 +236,14 @@ impl GraphicsState { D3D12_PRIMITIVE_TOPOLOGY_TYPE(data.cast::().read_unaligned()) } 15 => { - self.targets = data.cast::().read_unaligned(); - for f in &mut self.targets.RTFormats { - f.0 = crate::resource::pc_format(f.0 as u32) as i32; + let raw = data.cast::().read_unaligned(); + // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. + let mut out: D3D12_RT_FORMAT_ARRAY = std::mem::zeroed(); + out.NumRenderTargets = raw.NumRenderTargets; + for (dst, src) in out.RTFormats.iter_mut().zip(raw.RTFormats) { + dst.0 = crate::resource::pc_format(src.0 as u32) as i32; } + self.targets = out; } 16 => { let f = data.cast::().read_unaligned(); @@ -646,7 +721,7 @@ impl HostPipeline { pRootSignature: unsafe { std::mem::transmute_copy(&root) }, VS: code(0), PS: code(1), - BlendState: g.blend, + BlendState: host_blend(&g.blend, &g.targets), SampleMask: g.sample_mask, RasterizerState: g.rasterizer, DepthStencilState: g.depth, @@ -739,30 +814,34 @@ fn mesh_pipeline( dsv: Sub, samples: Sub, } - let mut stream = Stream { - root: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, - root.as_raw(), - ), - ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), - ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), - blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), - mask: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, - g.sample_mask, - ), - raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), - depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth), - targets: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, - g.targets, - ), - dsv: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, - g.depth_format, - ), - samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), - }; + // SAFETY: `Stream` is plain-old-data; zeroing clears padding inside + // `Sub` so D3D12's pipeline library desc comparison is deterministic. + let mut stream: Stream = unsafe { std::mem::zeroed() }; + stream.root = Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + root.as_raw(), + ); + stream.ms = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms); + stream.ps = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps); + stream.blend = Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, + host_blend(&g.blend, &g.targets), + ); + stream.mask = Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, + g.sample_mask, + ); + stream.raster = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer); + stream.depth = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth); + stream.targets = Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + g.targets, + ); + stream.dsv = Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + g.depth_format, + ); + stream.samples = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples); let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: size_of::(), pPipelineStateSubobjectStream: (&raw mut stream).cast(), @@ -833,3 +912,171 @@ fn root_signature( Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec())) } } + +/// Copies a blend description field-by-field into zeroed memory so +/// uninitialized padding bytes from the title's stream cannot cause +/// `ID3D12PipelineLibrary` description mismatches. +fn clean_blend(b: D3D12_BLEND_DESC) -> D3D12_BLEND_DESC { + // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. + let mut out: D3D12_BLEND_DESC = unsafe { std::mem::zeroed() }; + out.AlphaToCoverageEnable = b.AlphaToCoverageEnable; + out.IndependentBlendEnable = b.IndependentBlendEnable; + for (dst, src) in out.RenderTarget.iter_mut().zip(b.RenderTarget) { + // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. + let mut rt: D3D12_RENDER_TARGET_BLEND_DESC = unsafe { std::mem::zeroed() }; + rt.BlendEnable = src.BlendEnable; + rt.LogicOpEnable = src.LogicOpEnable; + rt.SrcBlend = src.SrcBlend; + rt.DestBlend = src.DestBlend; + rt.BlendOp = src.BlendOp; + rt.SrcBlendAlpha = src.SrcBlendAlpha; + rt.DestBlendAlpha = src.DestBlendAlpha; + rt.BlendOpAlpha = src.BlendOpAlpha; + rt.LogicOp = src.LogicOp; + rt.RenderTargetWriteMask = src.RenderTargetWriteMask; + *dst = rt; + } + out +} + +/// Copies a rasterizer description field-by-field into zeroed memory. +fn clean_rasterizer(r: D3D12_RASTERIZER_DESC) -> D3D12_RASTERIZER_DESC { + // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. + let mut out: D3D12_RASTERIZER_DESC = unsafe { std::mem::zeroed() }; + out.FillMode = r.FillMode; + out.CullMode = r.CullMode; + out.FrontCounterClockwise = r.FrontCounterClockwise; + out.DepthBias = r.DepthBias; + out.DepthBiasClamp = r.DepthBiasClamp; + out.SlopeScaledDepthBias = r.SlopeScaledDepthBias; + out.DepthClipEnable = r.DepthClipEnable; + out.MultisampleEnable = r.MultisampleEnable; + out.AntialiasedLineEnable = r.AntialiasedLineEnable; + out.ForcedSampleCount = r.ForcedSampleCount; + out.ConservativeRaster = r.ConservativeRaster; + out +} + +/// Copies a depth-stencil description field-by-field into zeroed memory. +fn clean_depth(d: D3D12_DEPTH_STENCIL_DESC) -> D3D12_DEPTH_STENCIL_DESC { + // SAFETY: plain-old-data D3D12 struct; zeroed to clear padding. + let mut out: D3D12_DEPTH_STENCIL_DESC = unsafe { std::mem::zeroed() }; + out.DepthEnable = d.DepthEnable; + out.DepthWriteMask = d.DepthWriteMask; + out.DepthFunc = d.DepthFunc; + out.StencilEnable = d.StencilEnable; + out.StencilReadMask = d.StencilReadMask; + out.StencilWriteMask = d.StencilWriteMask; + out.FrontFace = d.FrontFace; + out.BackFace = d.BackFace; + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn targets(formats: &[DXGI_FORMAT]) -> D3D12_RT_FORMAT_ARRAY { + let mut t = D3D12_RT_FORMAT_ARRAY { + NumRenderTargets: formats.len() as u32, + ..Default::default() + }; + t.RTFormats[..formats.len()].copy_from_slice(formats); + t + } + + fn blending(independent: bool) -> D3D12_BLEND_DESC { + let mut b = GraphicsState::default().blend; + b.IndependentBlendEnable = independent.into(); + for t in &mut b.RenderTarget { + t.BlendEnable = true.into(); + t.SrcBlend = D3D12_BLEND_SRC_ALPHA; + t.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + } + b + } + + #[test] + fn integer_targets_do_not_blend() { + let t = targets(&[ + DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16B16A16_FLOAT, + DXGI_FORMAT_R8_UINT, + ]); + for independent in [false, true] { + let host = host_blend(&blending(independent), &t); + assert!(host.IndependentBlendEnable.as_bool()); + assert!(host.RenderTarget[0].BlendEnable.as_bool()); + assert!(host.RenderTarget[1].BlendEnable.as_bool()); + assert!(!host.RenderTarget[2].BlendEnable.as_bool()); + // The rest of the target's state is the title's. + assert_eq!(host.RenderTarget[2].SrcBlend, D3D12_BLEND_SRC_ALPHA); + assert_eq!(host.RenderTarget[0].DestBlend, D3D12_BLEND_INV_SRC_ALPHA); + } + } + + #[test] + fn blend_states_without_integer_blending_are_kept() { + // No integer target. + let b = blending(false); + let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R11G11B10_FLOAT]); + assert_eq!(host_blend(&b, &t), b); + // An integer target that does not blend. + let mut b = blending(true); + b.RenderTarget[1].BlendEnable = false.into(); + let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT]); + assert_eq!(host_blend(&b, &t), b); + // Integer formats past the targets in use. + let mut t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM]); + t.RTFormats[1] = DXGI_FORMAT_R8_UINT; + assert_eq!(host_blend(&blending(false), &t), blending(false)); + } + + /// Padding bytes after `u8` fields in title PSO streams (such as + /// `RenderTargetWriteMask` or `StencilWriteMask`) must be zeroed so + /// identical logical states produce byte-identical D3D12 structs. + #[test] + fn cleaned_graphics_descs_zero_padding_bytes() { + let mut raw_depth = [0xAAu8; size_of::()]; + let base = D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_LESS, + StencilEnable: false.into(), + StencilReadMask: 0xff, + StencilWriteMask: 0xff, + FrontFace: D3D12_DEPTH_STENCILOP_DESC::default(), + BackFace: D3D12_DEPTH_STENCILOP_DESC::default(), + }; + // Write valid fields over 0xAA garbage so only padding stays 0xAA. + // SAFETY: `raw_depth` has the exact size of `D3D12_DEPTH_STENCIL_DESC`. + let dirty: D3D12_DEPTH_STENCIL_DESC = unsafe { + let p = raw_depth.as_mut_ptr().cast::(); + std::ptr::addr_of_mut!((*p).DepthEnable).write_unaligned(base.DepthEnable); + std::ptr::addr_of_mut!((*p).DepthWriteMask).write_unaligned(base.DepthWriteMask); + std::ptr::addr_of_mut!((*p).DepthFunc).write_unaligned(base.DepthFunc); + std::ptr::addr_of_mut!((*p).StencilEnable).write_unaligned(base.StencilEnable); + std::ptr::addr_of_mut!((*p).StencilReadMask).write_unaligned(base.StencilReadMask); + std::ptr::addr_of_mut!((*p).StencilWriteMask).write_unaligned(base.StencilWriteMask); + std::ptr::addr_of_mut!((*p).FrontFace).write_unaligned(base.FrontFace); + std::ptr::addr_of_mut!((*p).BackFace).write_unaligned(base.BackFace); + p.read_unaligned() + }; + let a = clean_depth(dirty); + let b = clean_depth(base); + // SAFETY: inspecting raw bytes of plain-old-data structs. + let (ba, bb) = unsafe { + ( + std::slice::from_raw_parts( + (&raw const a).cast::(), + size_of::(), + ), + std::slice::from_raw_parts( + (&raw const b).cast::(), + size_of::(), + ), + ) + }; + assert_eq!(ba, bb); + } +} diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 5c9fabc..f688c56 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -42,6 +42,9 @@ struct Library { _blob: Vec, /// Pipelines stored since the last save. added: u64, + /// Names already stored during this run (avoids duplicate `StorePipeline` + /// calls when two worker threads compile the same pipeline concurrently). + stored: HashSet, } // SAFETY: D3D12 objects are free-threaded; every call is made under the @@ -105,6 +108,7 @@ fn open(device: &ID3D12Device1, blob: Vec) -> Option { library, _blob: blob, added: 0, + stored: HashSet::new(), }); } Err(e) => { @@ -119,6 +123,7 @@ fn open(device: &ID3D12Device1, blob: Vec) -> Option { library, _blob: Vec::new(), added: 0, + stored: HashSet::new(), }) } @@ -160,10 +165,12 @@ pub(crate) fn pipeline( let pso = create()?; MADE.fetch_add(1, Ordering::Relaxed); let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); - // SAFETY: a live pipeline; a name already stored (a description that - // differs) is refused, which leaves the library as it was. - if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { - l.added += 1; + if l.stored.insert(name.to_owned()) { + // SAFETY: a live pipeline; a name already stored in an earlier run + // is refused, which leaves the library as it was. + if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { + l.added += 1; + } } Ok(pso) } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index f626a23..d01b35f 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -840,9 +840,42 @@ fn host_texture( if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) { d.format = family(d.format); } + // Some console formats (such as B5G5R5A1_UNORM) allow unordered access + // or render-target flags on the console that PC GPUs refuse; drop + // unsupported flags on typed formats so the host copy is still created. + const RENDER_TARGET: u32 = 1; + let typeless = family(d.format) == d.format && family(d.format + 1) == d.format; + if !typeless && d.flags & (RENDER_TARGET | UNORDERED) != 0 { + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(d.format as i32), + ..Default::default() + }; + // SAFETY: plain feature query into our struct. + let ok = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_FORMAT_SUPPORT, + (&raw mut support).cast(), + size_of::() as u32, + ) + } + .is_ok(); + if ok { + if d.flags & UNORDERED != 0 + && support.Support1.0 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0 == 0 + { + d.flags &= !UNORDERED; + } + if d.flags & RENDER_TARGET != 0 + && support.Support1.0 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 == 0 + { + d.flags &= !RENDER_TARGET; + } + } + } // The clear value names the format too: format, then color or depth - // and stencil (5 words). - let clear_value = (!clear.is_null()).then(|| { + // and stencil (5 words). D3D12 requires a null optimized clear value + // when neither render-target nor depth-stencil is set (id=815). + let clear_value = (!clear.is_null() && d.flags & (RENDER_TARGET | DEPTH) != 0).then(|| { // SAFETY: the title passes a whole clear value. let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() }; value[0] = pc_format(value[0]); @@ -1851,4 +1884,95 @@ mod tests { assert_eq!(slot::(heap, 0x10)(heap), 1); assert_eq!(slot::(placed, 0x10)(placed), 0); } + + #[cfg(windows)] + #[test] + fn host_texture_drops_unsupported_uav_flag_for_b5g5r5a1() { + use windows::Win32::Graphics::Direct3D12::*; + if crate::host::host().is_none() { + return; // no host GPU here + } + let make = |format: u32, flags: u32| ResourceDesc { + dimension: 3, // TEXTURE2D + alignment: 0, + width: 64, + height: 64, + depth_or_array_size: 1, + mip_levels: 1, + format, + sample_count: 1, + sample_quality: 0, + layout: 0, + flags, + }; + // B5G5R5A1_UNORM (86) with ALLOW_RENDER_TARGET | ALLOW_UNORDERED_ACCESS (5): + // the flag must survive exactly when the host reports typed-UAV + // support for the format and be dropped otherwise. + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(86), + ..Default::default() + }; + let host = crate::host::host().unwrap(); + // SAFETY: plain feature query into our struct. + let typed_uav = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_FORMAT_SUPPORT, + (&raw mut support).cast(), + size_of::() as u32, + ) + } + .is_ok() + && support.Support1.0 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0 != 0; + let b5g5r5a1 = host_texture(&make(86, 5), 0, std::ptr::null()) + .expect("B5G5R5A1_UNORM texture should be created"); + // SAFETY: live D3D12 resource. + let d = unsafe { b5g5r5a1.GetDesc() }; + assert_eq!( + d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0, + if typed_uav { + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 + } else { + 0 + } + ); + assert_ne!(d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0, 0); + + // B4G4R4A4_UNORM (115) with ALLOW_RENDER_TARGET (1) and a non-null + // clear value: the flag must survive exactly when the host reports + // render-target support for the format and be dropped otherwise. + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(115), + ..Default::default() + }; + // SAFETY: plain feature query into our struct. + let render_target = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_FORMAT_SUPPORT, + (&raw mut support).cast(), + size_of::() as u32, + ) + } + .is_ok() + && support.Support1.0 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 != 0; + let clear = [115u32, 0, 0, 0, 0]; + let b4g4r4a4 = host_texture(&make(115, 1), 0, clear.as_ptr().cast()) + .expect("B4G4R4A4_UNORM texture should succeed"); + // SAFETY: live D3D12 resource. + let bd = unsafe { b4g4r4a4.GetDesc() }; + assert_eq!( + bd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0, + if render_target { + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 + } else { + 0 + } + ); + + // R8G8B8A8_TYPELESS (27) with flags=5 must keep ALLOW_UNORDERED_ACCESS. + let typeless = host_texture(&make(27, 5), 0, std::ptr::null()) + .expect("R8G8B8A8_TYPELESS texture should succeed"); + // SAFETY: live D3D12 resource. + let td = unsafe { typeless.GetDesc() }; + assert_ne!(td.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0, 0); + } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 60eab0c..6b462cb 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -7,15 +7,19 @@ //! //! "Changed" means a page of the memory was written since the last detiling //! ([`crate::watch`]), in write-watched memory; in physical-page views, -//! which cannot be watched, a content hash of the whole memory at every -//! submission that samples it. +//! which cannot be watched, a content hash of each page at every +//! submission that samples it. Only the subresources whose memory holds a +//! changed page are detiled again (and, when watched, only the changed +//! pages read again). //! -//! shortcut: a change detiles the whole texture, not the pages written. -//! Only textures read through descriptor tables are brought up to date +//! shortcut: a changed subresource is detiled whole, not just its blocks in +//! the pages written, and every subresource is still copied into the host +//! texture. Only textures read through descriptor tables are brought up to date //! (directly indexed views are not known per draw); plane 0 is uploaded //! (every mip and array slice), depth and stencil planes are not. use std::collections::HashMap; +use std::ops::Range; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::*; @@ -43,20 +47,72 @@ pub(crate) struct Staging { layout: victory_formats::texture::Layout, /// Mips per array slice. mips: u32, + /// Per subresource, the byte ranges of the memory it is detiled from. + extents: Vec>>, memory: *const u8, last: Mutex, } -/// What a texture's staging buffer holds: the hash of the memory detiled -/// (memory not watched), or the write-watch asking it was detiled after, -/// with room to read the memory into. +/// What a texture's staging buffer holds: the hash of each page of the +/// memory detiled (memory not watched), or the write-watch asking it was +/// detiled after, with the memory as then read. #[derive(Default)] struct Last { - hash: Option, + hashes: Vec, asked: u64, read: Vec, } +/// Whether any of `changed` overlaps any of `extents` (both sorted). +fn overlaps(extents: &[Range], changed: &[Range]) -> bool { + let (mut i, mut j) = (0, 0); + while i < extents.len() && j < changed.len() { + let (e, c) = (&extents[i], &changed[j]); + if e.start < c.end && c.start < e.end { + return true; + } + if e.end <= c.end { + i += 1; + } else { + j += 1; + } + } + false +} + +/// The parts of `[0, len)` in which `a` and `b`, hashes of its `page`-byte +/// parts, differ; `None` when they do not hash the same parts. +fn changed_pages( + a: &[blake3::Hash], + b: &[blake3::Hash], + page: usize, + len: usize, +) -> Option>> { + (a.len() == b.len()).then(|| { + (0..a.len()) + .filter(|&i| a[i] != b[i]) + .map(|i| i * page..((i + 1) * page).min(len)) + .collect() + }) +} + +/// `[start, start + len)`'s byte ranges, relative to `start`, of the +/// `page`-byte pages numbered `pages` (in order). +fn page_ranges( + pages: impl Iterator, + page: usize, + start: usize, + len: usize, +) -> Vec> { + pages + .map(|p| { + let end = ((p + 1) * page).min(start + len); + (p * page).max(start) - start..end.saturating_sub(start) + }) + .filter(|r| r.start < r.end) + .collect() +} + // SAFETY: the staging mapping is written only at submission, under // `last`'s lock; the title memory is only read. unsafe impl Send for Staging {} @@ -188,18 +244,45 @@ impl Staging { let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); let last = &mut *last; if let Some((now, written)) = crate::watch::writes(start, start + size, false) { - if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { + let before = last.asked; + if before != 0 && written.iter().all(|&(_, w)| w <= before) { return 0; } last.asked = now; // Read through the copy, which stands unmapped pages: memory of // big pools is too slow to ask page by page. - last.read.resize(size, 0); - crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); - self.detile(&last.read); + if before == 0 || last.read.len() != size { + last.read.resize(size, 0); + crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); + self.detile(&last.read, None); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexWatched, size as u64); + return size; + } + // The rest of the memory is as last read: read again only the + // pages written since, and detile what they hold. + let pages = written + .iter() + .filter(|&&(_, w)| w > before) + .map(|&(p, _)| p); + let changed = page_ranges(pages, crate::watch::PAGE, start, size); + let mut read = 0; + for r in &changed { + // SAFETY: `r` lies inside both the read copy and the + // texture's memory, each `size` bytes. + let (to, from) = unsafe { + ( + last.read.as_mut_ptr().add(r.start), + self.memory.add(r.start), + ) + }; + crate::host::copy_mapped(to, from, r.len(), false); + read += r.len(); + } + self.detile(&last.read, Some(&changed)); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::TexWatched, size as u64); - return size; + crate::copystat::add(crate::copystat::C::TexWatched, read as u64); + return read; } if !committed(self.memory, size) { #[cfg(feature = "diagnostics")] @@ -213,21 +296,25 @@ impl Staging { } // SAFETY: committed memory of the texture's layout size. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; - let hash = blake3::hash(tiled); + let page = crate::watch::PAGE; + let hashes: Vec = tiled.chunks(page).map(blake3::hash).collect(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); - if last.hash == Some(hash) { + if last.hashes == hashes { return size; } - last.hash = Some(hash); - self.detile(tiled); + let changed = changed_pages(&last.hashes, &hashes, page, size); + self.detile(tiled, changed.as_deref()); + last.hashes = hashes; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); size } - /// Detiles `tiled` (the texture's memory) into the staging buffer. - fn detile(&self, tiled: &[u8]) { + /// Detiles `tiled` (the texture's memory) into the staging buffer: the + /// subresources whose memory overlaps `changed` (sorted byte ranges), + /// or all of them. + fn detile(&self, tiled: &[u8], changed: Option<&[Range]>) { #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { tracing::debug!( @@ -237,6 +324,9 @@ impl Staging { ); } for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { + if changed.is_some_and(|c| !overlaps(&self.extents[i], c)) { + continue; + } let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); let f = footprint.Footprint; let pitch = f.RowPitch as usize; @@ -327,6 +417,18 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { ) }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); + let mips = u32::from(d.MipLevels).max(1); + let whole: Vec<_> = std::iter::once(0..layout.size as usize).collect(); + let extents = (0..count) + .map(|i| match layout.extents(i % mips, i / mips) { + Ok(e) => e + .into_iter() + .map(|r| r.start as usize..r.end as usize) + .collect(), + // Detiling it fails too; any change "touches" it. + Err(_) => whole.clone(), + }) + .collect(); let s = Arc::new(Staging { buffer, #[cfg(feature = "diagnostics")] @@ -336,9 +438,56 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { rows, layout, mips: u32::from(d.MipLevels), + extents, memory, last: Mutex::default(), }); map.insert(resource as usize, s.clone()); Some(s) } + +#[cfg(test)] +// Single ranges in brackets are meant: lists of one range. +#[allow(clippy::single_range_in_vec_init)] +mod tests { + use super::{changed_pages, overlaps, page_ranges}; + + #[test] + fn ranges_overlap_only_when_they_share_a_byte() { + let extents = [10..20, 40..50]; + assert!(overlaps(&extents, &[15..16])); + assert!(overlaps(&extents, &[0..5, 49..60])); + assert!(overlaps(&extents, &[0..11])); + // Touching ends share no byte. + assert!(!overlaps(&extents, &[20..40])); + assert!(!overlaps(&extents, &[0..10, 20..40, 50..90])); + assert!(!overlaps(&extents, &[])); + assert!(!overlaps(&[], &[0..100])); + // A long change across several extents, and the reverse. + assert!(overlaps(&[10..20, 40..50], &[0..100])); + assert!(overlaps(&[0..100], &[10..20, 40..50])); + } + + #[test] + fn hashed_pages_that_differ_are_the_change() { + let h = |b: u8| blake3::hash(&[b]); + let (a, b) = ([h(1), h(2), h(3)], [h(1), h(9), h(9)]); + // The last page is short: the memory ends inside it. + assert_eq!( + changed_pages(&a, &b, 64, 150), + Some(vec![64..128, 128..150]) + ); + assert_eq!(changed_pages(&a, &a, 64, 150), Some(vec![])); + // Nothing hashed before: no part known to be unchanged. + assert_eq!(changed_pages(&[], &b, 64, 150), None); + } + + #[test] + fn written_pages_become_ranges_of_the_memory() { + // Memory from 100 for 250 bytes, in 64-byte pages 1..=5. + let r = page_ranges([1, 3, 5].into_iter(), 64, 100, 250); + assert_eq!(r, vec![0..28, 92..156, 220..250]); + // Pages outside the memory give nothing. + assert!(page_ranges([0, 6].into_iter(), 64, 100, 250).is_empty()); + } +} diff --git a/crates/victory-loader/Cargo.toml b/crates/victory-loader/Cargo.toml index 637253a..4b0e098 100644 --- a/crates/victory-loader/Cargo.toml +++ b/crates/victory-loader/Cargo.toml @@ -14,6 +14,7 @@ anyhow.workspace = true thiserror.workspace = true tracing.workspace = true blake3.workspace = true +hex = "0.4" [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = [ diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs index c3f8c90..cd5d574 100644 --- a/crates/victory-loader/src/prepare.rs +++ b/crates/victory-loader/src/prepare.rs @@ -1,6 +1,7 @@ //! Turns a title's image into something the Windows loader maps but does //! not run. Pure byte manipulation, so it is testable on any host. +use tracing; use victory_pe::layout::{self, dir, dll_flags, file_flags}; use victory_pe::{ImageInfo, PeError}; @@ -106,6 +107,15 @@ pub fn prepare(original: &[u8]) -> Result { } } + // Apply VICTORY_PATCH if set + if let Some(patch_env) = std::env::var_os("VICTORY_PATCH") { + let patch_env = patch_env.to_string_lossy().into_owned(); + let patches = parse_victory_patch(&patch_env); + if let Err(e) = apply_victory_patches(&mut bytes, &patches) { + tracing::warn!(target: "victory-loader", "VICTORY_PATCH application failed: {e}"); + } + } + Ok(PreparedImage { info, bytes, @@ -173,6 +183,59 @@ fn write(bytes: &mut [u8], at: usize, v: &[u8]) -> Result<(), PrepareError> { Ok(()) } +/// Simple hex decoder for VICTORY_PATCH bytes (no external `hex` crate needed). +/// Parses a VICTORY_PATCH environment variable value. +/// Format: `::` +/// Multiple patches can be specified by setting the env var multiple times +/// or using a separator (here we support space-separated multiple entries). +fn parse_victory_patch(env_val: &str) -> Vec<(String, u32, Vec)> { + let mut patches = Vec::new(); + for part in env_val.split_whitespace() { + let parts: Vec<&str> = part.split(':').collect(); + if parts.len() != 3 { + tracing::warn!(target: "victory-loader", "invalid VICTORY_PATCH format: {part}"); + continue; + } + let module = parts[0].to_string(); + let rva = u32::from_str_radix(parts[1], 16).unwrap_or(0); + let bytes = hex::decode(parts[2].trim()).unwrap_or_else(|_| Vec::new()); + patches.push((module, rva, bytes)); + } + patches +} + +/// Applies a list of VICTORY_PATCH entries to the image bytes. +/// Each patch is logged via `tracing::info!` with module, rva, old bytes, new bytes. +fn apply_victory_patches( + bytes: &mut [u8], + patches: &[(String, u32, Vec)], +) -> Result<(), PrepareError> { + for (module, rva, new_bytes) in patches { + // Verify the RVA is within the file bounds + if *rva as usize >= bytes.len() { + tracing::warn!(target: "victory-loader", "VICTORY_PATCH rva {:#x} outside file size {}", rva, bytes.len()); + continue; + } + // Save the old bytes for logging + let old_bytes = bytes[*rva as usize..*rva as usize + new_bytes.len()].to_vec(); + // Apply the patch + bytes[*rva as usize..*rva as usize + new_bytes.len()].copy_from_slice(new_bytes); + // Log the patch application + let old_hex = old_bytes + .iter() + .map(|b| format!("{:02x}", b)) + .collect::>() + .join(""); + let new_hex = new_bytes + .iter() + .map(|b| format!("{:02x}", b)) + .collect::>() + .join(""); + tracing::info!(target: "victory-loader", "VICTORY_PATCH: module={}, rva={:#x}, old_bytes=[{}], new_bytes=[{}]", module, rva, old_hex, new_hex); + } + Ok(()) +} + #[cfg(test)] mod tests { #[cfg(windows)] diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 13b54af..0be6ef3 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -5,7 +5,7 @@ //! it is written: functions, then constants (all at module level), then the //! instructions of `main` in block order. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub(crate) struct Ty(u32); @@ -308,6 +308,10 @@ impl Module { /// Gives constant `old` the content of `new` (both stay valid). pub fn replace_const(&mut self, old: V, new: V) { if let (V::Const(o), V::Const(n)) = (old, new) { + if self.const_ids.get(&self.consts[o as usize]) == Some(&o) { + let prev = self.consts[o as usize].clone(); + self.const_ids.remove(&prev); + } self.consts[o as usize] = self.consts[n as usize].clone(); } } @@ -486,12 +490,38 @@ impl Module { self.named.push((name.into(), nodes)); } - /// The module as bitcode. - /// Which instructions are written: every body instruction, the branch - /// conditions, and whatever they read, transitively (a phi nothing reads + /// Blocks reachable from entry (index 0) and their reverse postorder. + fn reachable(&self) -> (Vec, Vec) { + let succs = |b: usize| successors(self.blocks[b].term); + let mut seen = vec![false; self.blocks.len()]; + let mut post = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, k) = *top; + top.1 += 1; + match succs(b).get(k) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + (seen, post) + } + + /// Which instructions are written: every body instruction in reachable + /// blocks, the branch conditions, and whatever they read, transitively + /// (a phi nothing reads, or an incoming edge from an unreachable block, /// is dropped). A worklist visits each instruction once, so a long chain /// of merges costs one pass, not one pass per merge. - fn live(&self) -> Vec { + fn live(&self, reachable: &[bool]) -> Vec { let mut live = vec![false; self.insts.len()]; let mut work: Vec = Vec::new(); let mark = |live: &mut [bool], work: &mut Vec, v: V| { @@ -502,7 +532,10 @@ impl Module { work.push(i); } }; - for b in &self.blocks { + for (b_idx, b) in self.blocks.iter().enumerate() { + if !reachable[b_idx] { + continue; + } for &i in &b.body { mark(&mut live, &mut work, V::Inst(i)); } @@ -511,9 +544,16 @@ impl Module { } } while let Some(i) = work.pop() { - for_each_operand(&self.insts[i as usize].op, |v| { - mark(&mut live, &mut work, v) - }); + match &self.insts[i as usize].op { + Op::Phi(inc) => { + for &(v, pred) in inc { + if reachable[pred] { + mark(&mut live, &mut work, v); + } + } + } + op => for_each_operand(op, |v| mark(&mut live, &mut work, v)), + } } live } @@ -650,33 +690,13 @@ impl Module { } w.exit(); - // Phis nothing reads are left out (one register per phi makes many). - let live = self.live(); - // Blocks are laid out in reverse postorder, so every block follows // its forward predecessors (drivers take a branch to an earlier // block for a loop's back edge). + let (seen, post) = self.reachable(); + // Phis nothing reads (and operands from unreachable edges) are left out. + let live = self.live(&seen); let succs = |b: usize| successors(self.blocks[b].term); - let mut seen = vec![false; self.blocks.len()]; - let mut post = Vec::new(); - let mut stack = vec![(0usize, 0usize)]; - seen[0] = true; - while let Some(top) = stack.last_mut() { - let (b, k) = *top; - top.1 += 1; - match succs(b).get(k) { - Some(&s) if !seen[s] => { - seen[s] = true; - stack.push((s, 0)); - } - Some(_) => {} - None => { - post.push(b); - stack.pop(); - } - } - } - post.reverse(); let mut pos = vec![u64::MAX; self.blocks.len()]; for (n, &b) in post.iter().enumerate() { pos[b] = n as u64; @@ -690,15 +710,19 @@ impl Module { preds[s].push(b); } } - let mut fold = vec![None; self.blocks.len()]; + let mut fold: Vec> = vec![None; self.blocks.len()]; + let mut folded_edges: HashSet<(usize, usize)> = HashSet::new(); for &b in &post { let blk = &self.blocks[b]; if let (Some(Term::Br(h)), true, [p]) = ( blk.term, blk.phis.is_empty() && blk.body.is_empty(), &preds[b][..], - ) && pos[h] < pos[b] + ) && fold[*p].is_none() + && fold[h].is_none() + && pos[h] < pos[b] && !succs(*p).contains(&h) + && folded_edges.insert((*p, h)) { fold[b] = Some((*p, h)); } @@ -823,6 +847,9 @@ impl Module { r.clear(); r.push(u64::from(inst.ty.0)); for &(v, b) in incoming { + if !seen[b] { + continue; + } r.push(signed(i64::from(inst_id) - i64::from(abs(v)))); r.push(from(b)); } @@ -1131,7 +1158,8 @@ mod tests { fn worklist_liveness_matches_passes() { for (regs, stages, read) in [(1, 0, 1), (1, 1, 1), (4, 3, 1), (8, 17, 3), (16, 40, 16)] { let m = synthetic(regs, stages, read); - let live = m.live(); + let (reach, _) = m.reachable(); + let live = m.live(&reach); assert_eq!(live, live_by_passes(&m), "{regs} regs x {stages} stages"); } } @@ -1158,12 +1186,25 @@ mod tests { V::Inst(i) => i as usize, _ => unreachable!(), }; - let live = m.live(); + let (reach, _) = m.reachable(); + let live = m.live(&reach); assert!(live[ids(read)] && live[ids(sum)]); assert!(!live[ids(unread)] && !live[ids(cyc_a)] && !live[ids(cyc_b)]); assert_eq!(live, live_by_passes(&m)); } + #[test] + fn replace_const_evicts_old_cache_key() { + let mut m = Module::default(); + let c42 = m.i32(42); + let c99 = m.i32(99); + m.replace_const(c42, c99); + let fresh_42 = m.i32(42); + assert_ne!(fresh_42, c42); + assert_eq!(m.int_value(c42), Some(99)); + assert_eq!(m.int_value(fresh_42), Some(42)); + } + #[test] fn successors_of_each_terminator() { assert!(successors(None).is_empty()); diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 8b05b12..7feb2f2 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -25,6 +25,32 @@ pub(crate) struct SigElement { } impl SigElement { + /// Canonical DXIL semantic name for system values (`kind != 0`), matching + /// what `dxil.dll` writes when regenerating `ISG1`/`OSG1` during validation. + fn canonical_name(&self) -> &str { + match self.kind { + 1 => "SV_VertexID", + 2 => "SV_InstanceID", + 3 => "SV_Position", + 4 => "SV_RenderTargetArrayIndex", + 5 => "SV_ViewportArrayIndex", + 6 => "SV_ClipDistance", + 7 => "SV_CullDistance", + 10 => "SV_PrimitiveID", + 12 => "SV_SampleIndex", + 13 => "SV_IsFrontFace", + 14 => "SV_Coverage", + 15 => "SV_InnerCoverage", + 16 => "SV_Target", + 17 => "SV_Depth", + 18 => "SV_DepthLessEqual", + 19 => "SV_DepthGreaterEqual", + 20 => "SV_StencilRef", + 30 => "SV_CullPrimitive", + _ => &self.name, + } + } + fn system_value(&self) -> u32 { match self.kind { 1 => 6, // vertex id @@ -82,9 +108,10 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { match shared { Some(j) => offsets.push(offsets[j]), None => { + let name = e.canonical_name(); offsets.push(next); - next += e.name.len() as u32 + 1; - names.push(&e.name); + next += name.len() as u32 + 1; + names.push(name); } } } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index e3c8834..fb3e9fc 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -18,10 +18,12 @@ use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource}; use crate::resource::{Address, CODE, Resources, Role, Site, Source}; -use crate::structure::{Atom, Bool, LaneExit, Structured}; +use crate::structure::{Atom, Bool, BoolSet, LaneExit, Structured}; type Why = &'static str; +type HandleKey = (usize, Site, u8, bool, u32, u32); + mod bvh; mod global; @@ -65,28 +67,40 @@ pub(crate) struct Parts<'a> { pub mesh_stride: u32, } -enum Stop { - /// A phi whose incoming value has no DXIL form was read: redo with it missing. - Retry(Value, Why), - Fail(ShaderError), +pub(crate) fn lower(parts: &Parts) -> Result { + Lower::new(parts).run() } -pub(crate) fn lower(parts: &Parts) -> Result { - let mut bad = HashMap::new(); - loop { - match Lower::new(parts, &bad).run() { - Ok(l) => return Ok(l), - Err(Stop::Retry(v, why)) => { - if bad.insert(v, why).is_some() { - return Err(ShaderError::Unsupported { - offset: 0, - what: "a phi that does not settle", - }); - } - } - Err(Stop::Fail(e)) => return Err(e), - } - } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ReadDep { + Value(Value), + Edge { + from: usize, + to: usize, + value: Value, + }, +} + +struct ValueDeps { + block: usize, + guard: Option, + invert_guard: bool, + ignore_why: Option, + deps: Vec, +} + +struct OldDep { + value: Option, + direct_why: Option, + invert_guard: bool, + ignore_why: Option, +} + +struct SinkRead { + block: usize, + guard: Option, + offset: usize, + deps: Vec, } const TWO_PI: f32 = std::f32::consts::TAU; @@ -157,7 +171,6 @@ fn half_shift(width: u32) -> u32 { struct Lower<'a> { s: Shader, x: &'a Parts<'a>, - bad: &'a HashMap, lane_fail: HashMap, vals: HashMap, floats: HashMap, @@ -165,13 +178,21 @@ struct Lower<'a> { block: Vec>, cur: usize, bools: HashMap<(usize, Bool), V>, + bool_deps: HashMap<(usize, Bool), Vec>, lane_bits: HashMap, /// IR phi location by value. phi_at: HashMap, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, - read_phis: HashSet, + taint_candidates: HashSet, + cur_reads: Vec, + cur_old_deps: Vec, + cur_edge: Option<(usize, usize)>, + deps: HashMap>, + deps_order: Vec, + direct_missing: Vec<(Value, Why, usize, Option, bool)>, + sinks: Vec, params: HashMap, user_data: Option, user_reads: BTreeMap, @@ -180,7 +201,8 @@ struct Lower<'a> { scalar: HashMap, exports: HashMap, interps: HashMap, - handles: HashMap<(usize, Site, u8, bool, u32, u32), V>, + handles: HashMap, + handle_deps: HashMap>, /// Blocks splitting the edge from one IR block to another. edges: HashMap<(usize, usize), usize>, /// Per IR block: a `done` export is behind every lane entering it. @@ -209,6 +231,7 @@ struct Lower<'a> { mask_ok: bool, /// Ballots of masks read as data, by low dword: (low, high). ballots: HashMap, + ballot_deps: HashMap>, /// Masks whose ballot is being built: a mask whose lane bit needs its /// own value as a number (an opaque mask keyed by a dword it shares /// with another) would otherwise recurse until the stack overflows. @@ -349,8 +372,8 @@ fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap Stop { - Stop::Fail(ShaderError::Unsupported { offset, what }) +fn unsupported(offset: usize, what: Why) -> ShaderError { + ShaderError::Unsupported { offset, what } } /// The image atomics made by [`Lower::atomic_loop`], in place of a DXIL @@ -358,7 +381,7 @@ fn unsupported(offset: usize, what: Why) -> Stop { const ATOMIC_LOOP: u32 = u32::MAX - 1; impl<'a> Lower<'a> { - fn new(x: &'a Parts<'a>, bad: &'a HashMap) -> Self { + fn new(x: &'a Parts<'a>) -> Self { let p = x.p; let mut phi_at = HashMap::new(); for (b, block) in p.blocks.iter().enumerate() { @@ -469,19 +492,26 @@ impl<'a> Lower<'a> { Lower { s, x, - bad, lane_fail: HashMap::new(), vals: HashMap::new(), floats: HashMap::new(), block: vec![None; p.blocks.len()], cur: 0, bools: HashMap::new(), + bool_deps: HashMap::new(), lane_bits: HashMap::new(), phi_at, mask_phis: HashMap::new(), pending_masks: Vec::new(), data_phis: Vec::new(), - read_phis: HashSet::new(), + taint_candidates: HashSet::new(), + cur_reads: Vec::new(), + cur_old_deps: Vec::new(), + cur_edge: None, + deps: HashMap::new(), + deps_order: Vec::new(), + direct_missing: Vec::new(), + sinks: Vec::new(), params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), user_data: None, user_reads: BTreeMap::new(), @@ -496,6 +526,7 @@ impl<'a> Lower<'a> { exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(), handles: HashMap::new(), + handle_deps: HashMap::new(), edges: HashMap::new(), exported: vec![false; p.blocks.len()], rpo: vec![usize::MAX; p.blocks.len()], @@ -513,6 +544,7 @@ impl<'a> Lower<'a> { }, mask_ok: false, ballots: HashMap::new(), + ballot_deps: HashMap::new(), balloting: HashSet::new(), def_block: p .blocks @@ -740,10 +772,18 @@ impl<'a> Lower<'a> { const UNKNOWN: Why = "a whole-wave section step the simulation does not follow"; let inst = &self.x.p.blocks[b].insts[i]; for &(_, w) in &inst.writes { + self.cur_reads.clear(); + self.cur_edge = None; let val = if self.section_out.contains(&w) { let shape = self.sections[&b][&start].shapes.get(&w).copied(); match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh)) { - Ok(x) => Val::I32(x), + Ok(x) => { + let reads = std::mem::take(&mut self.cur_reads); + if !reads.is_empty() { + self.record_write_deps(w, b, None, false, None, reads); + } + Val::I32(x) + } Err(why) => Val::Missing(why), } } else { @@ -850,7 +890,7 @@ impl<'a> Lower<'a> { Ok(if float { self.as_int(r) } else { r }) } - fn run(mut self) -> Result { + fn run(mut self) -> Result { let p = self.x.p; let order = crate::ir::reverse_postorder(&p.blocks); for (n, &b) in order.iter().enumerate() { @@ -895,15 +935,16 @@ impl<'a> Lower<'a> { for (i, phi) in p.blocks[b].phis.iter().enumerate() { let val = match phi.reg { Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"), - _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]), Reg::Scc => { let v = self.s.m.phi(self.cur, self.s.t.i1); self.data_phis.push((v, b, i)); + self.taint_candidates.insert(phi.value); Val::Bit(v) } _ => { let v = self.s.m.phi(self.cur, self.s.t.i32); self.data_phis.push((v, b, i)); + self.taint_candidates.insert(phi.value); Val::I32(v) } }; @@ -960,7 +1001,7 @@ impl<'a> Lower<'a> { } /// Values of the program's input registers. - fn inputs(&mut self) -> Result<(), Stop> { + fn inputs(&mut self) -> Result<(), ShaderError> { let io_inputs: HashMap = self.x.io.inputs.iter().copied().collect(); for &(reg, v) in &self.x.p.inputs { let val = match reg { @@ -1144,18 +1185,60 @@ impl<'a> Lower<'a> { } } + fn record_read(&mut self, v: Value) { + if !self.taint_candidates.contains(&v) { + return; + } + let dep = match self.cur_edge { + Some((from, to)) => ReadDep::Edge { from, to, value: v }, + None => ReadDep::Value(v), + }; + if !self.cur_reads.contains(&dep) { + self.cur_reads.push(dep); + } + } + + fn record_write_deps( + &mut self, + w: Value, + block: usize, + guard: Option, + invert_guard: bool, + ignore_why: Option, + deps: Vec, + ) { + self.taint_candidates.insert(w); + let list = self.deps.entry(w).or_insert_with(|| { + self.deps_order.push(w); + Vec::new() + }); + list.push(ValueDeps { + block, + guard, + invert_guard, + ignore_why, + deps, + }); + } + /// The DXIL form of an IR value. fn get(&mut self, v: Value) -> Result { - if self.phi_at.contains_key(&v) { - self.read_phis.insert(v); - } + self.get_inner(v, true) + } + + fn get_inner(&mut self, v: Value, track: bool) -> Result { let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v); match self.vals.get(&v) { Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => { return self.mask_dword(v).map(Val::I32); } Some(&Val::Missing(w)) => return Err(w), - Some(&val) => return Ok(val), + Some(&val) => { + if track { + self.record_read(v); + } + return Ok(val); + } None => {} } if let Some(&(param, dword)) = self.params.get(&v) { @@ -1166,6 +1249,50 @@ impl<'a> Lower<'a> { Err("a value defined after its use") } + /// Reads an overwritten register's previous value, recording its lane + /// dependency (`invert_guard` for `!guard`, active lanes otherwise) so + /// direct missing values and tainted phis still propagate where kept. + fn old_i32_of(&mut self, v: Option, invert_guard: bool, ignore_why: Option) -> V { + let Some(v) = v else { + return self.s.m.i32(0); + }; + match self.get_inner(v, false) { + Ok(Val::I32(x)) => { + if self.taint_candidates.contains(&v) { + self.cur_old_deps.push(OldDep { + value: Some(v), + direct_why: None, + invert_guard, + ignore_why, + }); + } + x + } + Ok(Val::Bit(x)) => { + if self.taint_candidates.contains(&v) { + self.cur_old_deps.push(OldDep { + value: Some(v), + direct_why: None, + invert_guard, + ignore_why, + }); + } + self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32) + } + Ok(Val::Missing(why)) | Err(why) => { + if ignore_why != Some(why) { + self.cur_old_deps.push(OldDep { + value: None, + direct_why: Some(why), + invert_guard, + ignore_why, + }); + } + self.s.m.i32(0) + } + } + } + fn i32_of(&mut self, v: Value) -> Result { match self.get(v)? { Val::I32(x) => Ok(x), @@ -1214,6 +1341,14 @@ impl<'a> Lower<'a> { Val::I32(self.s.m.extract(entry, r, index % 4)) } + fn extend_cur_reads(&mut self, extra: &[ReadDep]) { + for &dep in extra { + if !self.cur_reads.contains(&dep) { + self.cur_reads.push(dep); + } + } + } + /// A dword of a lane mask as a number: the ballot of the lanes' bits, /// taken in the block that writes the mask (see [`MaskData`]). fn mask_dword(&mut self, v: Value) -> Result { @@ -1226,7 +1361,13 @@ impl<'a> Lower<'a> { return Err("a lane mask holding lanes elsewhere read as data"); } let (x, y) = match self.ballots.get(&lo) { - Some(&xy) => xy, + Some(&xy) => { + if let Some(deps) = self.ballot_deps.get(&lo) { + let deps = deps.clone(); + self.extend_cur_reads(&deps); + } + xy + } None => { let at = match self.def_block.get(&lo) { // Program inputs (EXEC on entry). @@ -1237,9 +1378,15 @@ impl<'a> Lower<'a> { if !self.balloting.insert(lo) { return Err("a lane mask whose lanes depend on its own value"); } + let saved = std::mem::take(&mut self.cur_reads); let bit = self.boolean(m, at); self.balloting.remove(&lo); + let sub = std::mem::replace(&mut self.cur_reads, saved); let bit = bit?; + self.extend_cur_reads(&sub); + if !sub.is_empty() { + self.ballot_deps.insert(lo, sub); + } let i32t = self.s.t.i32; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); let r = self @@ -1350,13 +1497,7 @@ impl<'a> Lower<'a> { Reg::S(reg) }; let val = inst.read(r).ok_or("an unread operand")?; - match self.floats.get(&val) { - Some(&f) => f, - None => { - let x = self.i32_of(val)?; - self.as_float(x) - } - } + self.float_of(val)? } _ => { let x = self.operand(inst, &op)?; @@ -1711,8 +1852,25 @@ impl<'a> Lower<'a> { return Ok(self.s.m.bool(b == Bool::TRUE)); } if let Some(&v) = self.bools.get(&(at, b)) { + if let Some(deps) = self.bool_deps.get(&(at, b)) { + let deps = deps.clone(); + self.extend_cur_reads(&deps); + } return Ok(v); } + let saved = std::mem::take(&mut self.cur_reads); + let r = self.boolean_uncached(b, at); + let sub = std::mem::replace(&mut self.cur_reads, saved); + let v = r?; + self.extend_cur_reads(&sub); + if !sub.is_empty() { + self.bool_deps.insert((at, b), sub); + } + self.bools.insert((at, b), v); + Ok(v) + } + + fn boolean_uncached(&mut self, b: Bool, at: usize) -> Result { let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant"); let a = self.atom(atom, at)?; let m = &mut self.s.m; @@ -1736,18 +1894,21 @@ impl<'a> Lower<'a> { self.s.m.select(at, a, h, l) } }; - self.bools.insert((at, b), v); Ok(v) } fn atom(&mut self, atom: Atom, at: usize) -> Result { match atom { - Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| { - self.lane_fail - .get(&v) - .copied() - .unwrap_or("a lane mask from a carry") - }), + Atom::Lane(v) => { + let r = self.lane_bits.get(&v).copied().ok_or_else(|| { + self.lane_fail + .get(&v) + .copied() + .unwrap_or("a lane mask from a carry") + })?; + self.record_read(v); + Ok(r) + } Atom::Uniform(v) => match self.get(v)? { Val::Bit(x) => Ok(x), Val::I32(x) => { @@ -1896,11 +2057,7 @@ impl<'a> Lower<'a> { let Some(new) = inst.write(reg) else { return }; let x = match (guard, reg) { (Some(g), Reg::V(_)) => { - let old = match inst.read(reg).map(|o| self.i32_of(o)) { - Some(Ok(o)) => o, - // The validator refuses reads of undef. - _ => self.s.m.i32(0), - }; + let old = self.old_i32_of(inst.read(reg), true, None); self.s.m.select(self.cur, g, x, old) } _ => x, @@ -1937,10 +2094,7 @@ impl<'a> Lower<'a> { if unused != 2 { return field; } - let old = match inst.read(reg).map(|o| self.i32_of(o)) { - Some(Ok(o)) => o, - _ => self.s.m.i32(0), - }; + let old = self.old_i32_of(inst.read(reg), false, None); let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at)); let old = self.s.m.bin(c, Bin::And, old, keep); self.s.m.bin(c, Bin::Or, old, field) @@ -2290,6 +2444,7 @@ impl<'a> Lower<'a> { /// The float value of a register value. fn float_of(&mut self, v: Value) -> Result { if let Some(&f) = self.floats.get(&v) { + self.record_read(v); return Ok(f); } let x = self.i32_of(v)?; @@ -2479,10 +2634,9 @@ impl<'a> Lower<'a> { Some(d) => Some(self.vgprs(inst, d, 1)?[0]), None => None, }; - let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v))); - let outside = match old_reg { - Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)), - None => self.s.m.i32(0), + let outside = match (guard, dst_reg.and_then(|r| inst.read(Reg::V(r)))) { + (Some(_), Some(v)) => self.old_i32_of(Some(v), true, None), + _ => self.s.m.i32(0), }; let p = dword(self, offset); let at = self.begin_guarded(guard); @@ -2503,10 +2657,13 @@ impl<'a> Lower<'a> { // ---- instructions ---- - fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> { + fn inst(&mut self, b: usize, i: usize) -> Result<(), ShaderError> { let inst: &'a Inst = &self.x.p.blocks[b].insts[i]; let offset = inst.machine.offset; let name = inst.name(); + self.cur_reads.clear(); + self.cur_old_deps.clear(); + self.cur_edge = None; self.mask_ok = match self.mask_data { MaskData::Console => true, MaskData::Host => { @@ -2556,8 +2713,66 @@ impl<'a> Lower<'a> { Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i), Fields::Flat { .. } => Err("flat memory"), }; + let reads = std::mem::take(&mut self.cur_reads); + let old_deps = std::mem::take(&mut self.cur_old_deps); match r { - Ok(()) => Ok(()), + Ok(()) => { + let guard = self.x.st.guards[b][i]; + if !reads.is_empty() { + if effect { + self.sinks.push(SinkRead { + block: b, + guard, + offset, + deps: reads, + }); + } else { + let use_guard = matches!( + &inst.fields, + Fields::Valu(v) + if v.dpp.is_none() + && !matches!( + name, + "v_readfirstlane_b32" + | "v_readlane_b32" + | "v_writelane_b32" + ) + ) + .then_some(guard) + .flatten(); + for &(_, w) in &inst.writes { + if matches!(self.vals.get(&w), Some(Val::I32(_) | Val::Bit(_))) + || self.lane_bits.contains_key(&w) + { + self.record_write_deps(w, b, use_guard, false, None, reads.clone()); + } + } + } + } + for old in old_deps { + for &(_, w) in &inst.writes { + if !matches!(self.vals.get(&w), Some(Val::I32(_) | Val::Bit(_))) { + continue; + } + if let Some(why) = old.direct_why { + self.taint_candidates.insert(w); + self.direct_missing + .push((w, why, b, guard, old.invert_guard)); + } + if let Some(u) = old.value { + self.record_write_deps( + w, + b, + guard, + old.invert_guard, + old.ignore_why, + vec![ReadDep::Value(u)], + ); + } + } + } + Ok(()) + } Err(why) if effect => Err(unsupported(offset, why)), Err(why) => { for &(_, v) in &inst.writes { @@ -3080,6 +3295,17 @@ impl<'a> Lower<'a> { return self.global_smem(inst); } let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { + if let Some(a) = self.scalar.get(&site).copied() + && self + .x + .native + .layout + .get(a.param) + .is_some_and(|p| p.root == RootType::Descriptor) + && !self.loads_descriptor(site) + { + return self.root_view_smem(inst, a, site); + } return self.descriptor_data(inst, site); }; let count = match rest { @@ -3120,8 +3346,15 @@ impl<'a> Lower<'a> { } return Ok(()); } - if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { - let h = self.handle(site, src, false, (11, 0))?; + // A raw view, read only or not; a constant buffer otherwise. (A + // UAV read through a constant buffer handle removes the device.) + let raw = match kind.map(|u| u.kind) { + Some(ResourceType::Srv) => Some(11), + Some(ResourceType::Uav) => Some(11 | 0x1000), + _ => None, + }; + if let Some(props) = raw { + let h = self.handle(site, src, false, (props, 0))?; for k in 0..count { let off = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, addr, off); @@ -3226,7 +3459,9 @@ impl<'a> Lower<'a> { _ => None, }) }); - let Some((at, first)) = use_at else { + // A load read only for its numbers (sizes for a mip level, say): + // another load of the same entry, used as a resource, tells its kind. + let Some((at, first)) = use_at.or_else(|| self.same_entry_use(site)) else { // No access names it: the console words are all there is. let words = self.descriptor_words(site, count)?; for (k, x) in words.into_iter().enumerate() { @@ -3331,8 +3566,14 @@ impl<'a> Lower<'a> { None => vec![(2, field(self, 0))], }; // Fields the host view gives are rebuilt from it; the console's - // other words (addresses, formats) come from the descriptor words. - let console = self.descriptor_words(site, count).ok(); + // other words (addresses, formats) come from the descriptor words, + // when those are already bound for this program. + let console = self + .s + .descriptor_words + .is_some() + .then(|| self.descriptor_words(site, count).ok()) + .flatten(); for k in 0..count { let rel = k.wrapping_sub(u32::from(first)); match (words.iter().find(|w| w.0 == rel), &console) { @@ -3348,6 +3589,127 @@ impl<'a> Lower<'a> { Ok(()) } + /// The use site and first dword of a resource descriptor loaded from + /// the same heap entry as the scalar load at `site`: the same parameter + /// and offset, and the same computed term (or the first lane's value of + /// the same VGPR, in another pass of a waterfall loop). + fn same_entry_use(&self, site: Site) -> Option<(Site, u8)> { + let a = self.scalar.get(&site)?; + let lane = |v: Value| -> Value { + self.x + .p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| i.writes.iter().any(|w| w.1 == v)) + .filter(|i| i.name() == "v_readfirstlane_b32") + .and_then(|i| i.reads.iter().find(|r| matches!(r.0, Reg::V(_)))) + .map_or(v, |r| r.1) + }; + let same = |b: &Address| { + b.param == a.param + && b.offset == a.offset + && match (a.dynamic, b.dynamic) { + (None, None) => true, + (Some(x), Some(y)) => x == y || lane(x) == lane(y), + _ => false, + } + }; + self.x + .res + .descriptors + .iter() + .filter(|d| d.role == Role::Resource) + .find_map(|d| { + d.source.leaves().into_iter().find_map(|l| match *l { + Source::Loaded { load, first } + if load != site && self.scalar.get(&load).is_some_and(same) => + { + Some((d.site, first)) + } + _ => None, + }) + }) + } + + /// Whether a descriptor the program uses comes from the scalar load at + /// `site` (a descriptor in memory, not data). + fn loads_descriptor(&self, site: Site) -> bool { + self.x.res.descriptors.iter().any(|d| { + d.source.leaves().into_iter().any(|l| { + matches!(*l, Source::Loaded { load, .. } | Source::Fetched { load, .. } + if load == site) + }) + }) + } + + /// `s_load_dword*` from a root view's address: that buffer's memory, as + /// global loads from it read it (a root SRV raw, a root CBV as a + /// constant buffer). + fn root_view_smem(&mut self, inst: &Inst, a: Address, site: Site) -> Result<(), Why> { + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return Err("a scalar memory read as data"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u32, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar memory read as data"), + }; + let c = self.cur; + let mut off = self.s.m.i32(a.offset); + if let Some(d) = a.dynamic { + let d = self.i32_of(d)?; + off = self.s.m.bin(c, Bin::Add, off, d); + } + let src = Source::Built { + address: a, + bits: 0, + words: [0, 0], + }; + let raw = match self.used_kind(&src).map(|u| u.kind) { + Some(ResourceType::Srv) => true, + Some(ResourceType::Cbv) | None => false, + _ => return Err("a root UAV read with scalar loads"), + }; + let h = if raw { + self.handle(site, &src, false, (11, 0))? + } else { + self.handle(site, &src, false, (13, 0x1_0000))? + }; + for k in 0..count { + let four = self.s.m.i32(4 * k); + let at = self.s.m.bin(c, Bin::Add, off, four); + let x = if raw { + let (u, mask, al) = ( + self.s.m.undef(self.s.t.i32), + self.s.m.i8(1), + self.s.m.i32(4), + ); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, at, u, mask, al], + ); + let x = self.s.m.extract(c, r, 0); + self.as_int(x) + } else { + self.cbuffer_dword(h, at) + }; + self.write(inst, Reg::S(code + k as u8), x, None); + } + Ok(()) + } + /// `s_load_dword*` from the program's constant table. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { let Fields::Smem { @@ -3595,9 +3957,20 @@ impl<'a> Lower<'a> { Source::Loaded { load, first } => { let key = (self.cur, *load, *first, sampler, props.0, props.1); if let Some(&h) = self.handles.get(&key) { + if let Some(deps) = self.handle_deps.get(&key) { + let deps = deps.clone(); + self.extend_cur_reads(&deps); + } return Ok(h); } - let index = self.heap_index(*load, *first, sampler)?; + let saved = std::mem::take(&mut self.cur_reads); + let index = self.heap_index(*load, *first, sampler); + let sub = std::mem::replace(&mut self.cur_reads, saved); + let index = index?; + self.extend_cur_reads(&sub); + if !sub.is_empty() { + self.handle_deps.insert(key, sub); + } // A waterfall loop's load at the first lane's offset reads // each lane's own entry (see `resource::Waterfall`). let per_lane = self.x.res.waterfall.loads.contains(load); @@ -3662,7 +4035,9 @@ impl<'a> Lower<'a> { }; let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); let here = std::mem::replace(&mut self.cur, at); + let prev_edge = self.cur_edge.replace((q, *block)); let index = self.heap_index(*load, *first, sampler); + self.cur_edge = prev_edge; self.cur = here; incoming.push((index?, at)); } @@ -3746,7 +4121,9 @@ impl<'a> Lower<'a> { let index = match arg { Some(arg) => { let here = std::mem::replace(&mut self.cur, at); + let prev_edge = self.cur_edge.replace((q, *block)); let index = self.lane_heap_index(arg, sampler); + self.cur_edge = prev_edge; self.cur = here; index? } @@ -4213,13 +4590,7 @@ impl<'a> Lower<'a> { return Err("an accumulator"); }; let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?; - let acc = match self.floats.get(&acc) { - Some(&x) => x, - None => { - let x = self.i32_of(acc)?; - self.as_float(x) - } - }; + let acc = self.float_of(acc)?; let r = match name { "v_fmac_f32" => self.fmad(a, bb, acc), "v_mac_f32" => { @@ -4448,14 +4819,38 @@ impl<'a> Lower<'a> { float(self, r) } "v_cndmask_b32" => { - let mask = match v.src.get(2) { - Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), - _ => None, + let cond = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => { + let m = inst + .read(Reg::S(code)) + .and_then(|m| { + self.x + .st + .masks + .get(&m) + .or_else(|| self.x.st.other.get(&m)) + .copied() + }) + .ok_or("a select on an untracked mask")?; + self.boolean(m, c)? + } + Some(&Operand::Const(k)) => { + let x = + crate::resource::inline(k).ok_or("a select on an untracked mask")?; + if x == 0 { + self.s.m.bool(false) + } else if x == u32::MAX { + self.s.m.bool(true) + } else if self.console_lanes { + let lo = self.s.m.i32(x); + let hi = self.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }); + self.lane_bit(c, lo, Some(hi)) + } else { + return Err("a constant lane mask"); + } + } + _ => return Err("a select on an untracked mask"), }; - let m = mask - .and_then(|m| self.x.st.masks.get(&m).copied()) - .ok_or("a select on an untracked mask")?; - let cond = self.boolean(m, c)?; if v.abs != 0 || v.neg != 0 { let (a, bb) = (f(self, 0)?, f(self, 1)?); let r = self.s.m.select(c, cond, bb, a); @@ -4674,11 +5069,22 @@ impl<'a> Lower<'a> { /// op_sel (or an SDWA word select) picks the high half; inline float /// constants are f16 values here. fn half_src(&mut self, inst: &Inst, k: usize) -> Result { + self.half_src_with(inst, k, true) + } + + /// [`Self::half_src`] for a 16-bit compare: RDNA2 ignores VOP3 `op_sel` + /// on `v_cmp_*`/`v_cmpx_*` over f16, u16 and i16, and reads the low half; + /// an SDWA word select still picks the half it names. + fn half_cmp_src(&mut self, inst: &Inst, k: usize) -> Result { + self.half_src_with(inst, k, false) + } + + fn half_src_with(&mut self, inst: &Inst, k: usize, opsel: bool) -> Result { let Fields::Valu(v) = &inst.fields else { unreachable!() }; let op = *v.src.get(k).ok_or("a missing operand")?; - let mut high = v.opsel >> k & 1 != 0; + let mut high = opsel && v.opsel >> k & 1 != 0; if let Some(sd) = v.sdwa { match sd.src_sel.get(k).copied().unwrap_or(6) { 4 => {} @@ -4704,10 +5110,19 @@ impl<'a> Lower<'a> { /// An f16 source as an f32 (exact), with its abs/neg modifiers. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result { + self.half_fsrc_with(inst, k, true) + } + + /// [`Self::half_fsrc`] for a 16-bit compare, which ignores `op_sel`. + fn half_cmp_fsrc(&mut self, inst: &Inst, k: usize) -> Result { + self.half_fsrc_with(inst, k, false) + } + + fn half_fsrc_with(&mut self, inst: &Inst, k: usize, opsel: bool) -> Result { let Fields::Valu(v) = &inst.fields else { unreachable!() }; - let h = self.half_src(inst, k)?; + let h = self.half_src_with(inst, k, opsel)?; let f32t = self.s.t.f32; let mut f = self .s @@ -4746,9 +5161,10 @@ impl<'a> Lower<'a> { } } let c = self.cur; - let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { - Some(Ok(o)) if keep => o, - _ => self.s.m.i32(0), + let old = if keep { + self.old_i32_of(inst.read(Reg::V(reg)), false, None) + } else { + self.s.m.i32(0) }; let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF)); let x = self.s.m.bin(c, Bin::And, x, low); @@ -5904,7 +6320,7 @@ impl<'a> Lower<'a> { } "f32" | "f16" => { let (a, b) = if ty == "f16" { - (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?) + (self.half_cmp_fsrc(inst, 0)?, self.half_cmp_fsrc(inst, 1)?) } else { (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?) }; @@ -5962,7 +6378,7 @@ impl<'a> Lower<'a> { } "u32" | "i32" | "u16" | "i16" => { let (a, b) = if ty.ends_with("16") { - let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); + let (mut a, mut b) = (self.half_cmp_src(inst, 0)?, self.half_cmp_src(inst, 1)?); if ty == "i16" { let k16 = self.s.m.i32(16); for x in [&mut a, &mut b] { @@ -6029,18 +6445,6 @@ impl<'a> Lower<'a> { fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Some(&interp) = self.interps.get(&site) else { - if inst.name().starts_with("v_interp_p1") { - let dst = match &inst.fields { - Fields::Vintrp { dst, .. } => *dst, - Fields::Valu(v) => v.dst.ok_or("an interpolation")?, - _ => unreachable!(), - }; - if let Operand::Vector { reg, .. } = dst { - let z = self.s.m.i32(0); - self.write(inst, Reg::V(reg), z, None); - } - return Ok(()); - } return Err("the first half of an interpolation"); }; let (attribute, mode) = match interp { @@ -6153,10 +6557,11 @@ impl<'a> Lower<'a> { /// results keep the register's high half (GFX10). fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V { let c = self.cur; - let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { - Some(Ok(o)) => o, - _ => self.s.m.i32(0), - }; + let old = self.old_i32_of( + inst.read(Reg::V(reg)), + false, + Some("the first half of an interpolation"), + ); let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF)); let old = self.s.m.bin(c, Bin::And, old, high); let x = self.s.m.bin(c, Bin::And, x, low); @@ -7435,11 +7840,14 @@ impl<'a> Lower<'a> { } } - fn exit(&mut self, b: usize) -> Result<(), Stop> { + fn exit(&mut self, b: usize) -> Result<(), ShaderError> { let offset = self.x.p.blocks[b] .insts .last() .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset); + self.cur_reads.clear(); + self.cur_old_deps.clear(); + self.cur_edge = None; let term = match self.x.st.exits[b] { LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => { let ok = self.count_iteration(t, pred::IULT); @@ -7470,6 +7878,15 @@ impl<'a> Lower<'a> { (c, taken, not_taken) } }; + let reads = std::mem::take(&mut self.cur_reads); + if !reads.is_empty() { + self.sinks.push(SinkRead { + block: b, + guard: None, + offset, + deps: reads, + }); + } // A back edge is taken only below the iteration limit. let back = |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b]; @@ -7588,23 +8005,11 @@ impl<'a> Lower<'a> { e } - fn fill_phis(&mut self) -> Result<(), Stop> { + fn fill_phis(&mut self) -> Result<(), ShaderError> { let p = self.x.p; - // A phi that only another read phi consumes is live too. Without this, a value with no DXIL form that - // reaches a read through two joins is taken for dead at the first join and replaced by zero below, and the - // lowering accepts what it refuses when the same value is read directly. - let mut work: Vec = self.read_phis.iter().copied().collect(); - while let Some(v) = work.pop() { - let Some(&(b, i)) = self.phi_at.get(&v) else { - continue; - }; - for &arg in &p.blocks[b].phis[i].args { - if self.phi_at.contains_key(&arg) && self.read_phis.insert(arg) { - work.push(arg); - } - } - } - for (v, b, i) in std::mem::take(&mut self.data_phis) { + let data_phis = std::mem::take(&mut self.data_phis); + let mut has_missing = false; + for &(v, b, i) in &data_phis { let phi = &p.blocks[b].phis[i]; let bit = phi.reg == Reg::Scc; let mut incoming = Vec::new(); @@ -7614,17 +8019,14 @@ impl<'a> Lower<'a> { let arg = phi.args[n]; let x = match (self.vals.get(&arg).copied(), bit) { (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, - (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { - return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); - } - (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => { - return Err(Stop::Retry(phi.value, why)); - } - _ if self.read_phis.contains(&phi.value) => { - return Err(Stop::Retry(phi.value, "a join of mismatched values")); + _ => { + has_missing = true; + if bit { + self.s.m.bool(false) + } else { + self.s.m.i32(0) + } } - _ if bit => self.s.m.bool(false), - _ => self.s.m.i32(0), }; incoming.push((x, qb)); } @@ -7644,11 +8046,215 @@ impl<'a> Lower<'a> { *self.x.st.masks.get(&phi.args[n]).ok_or_else(|| { unsupported(offset, "a lane-mask join of an untracked mask") })?; + self.cur_reads.clear(); + self.cur_edge = None; let x = self.boolean(m, qb).map_err(|w| unsupported(offset, w))?; + let reads = std::mem::take(&mut self.cur_reads); + if !reads.is_empty() { + let deps = reads + .into_iter() + .map(|dep| match dep { + ReadDep::Value(value) => ReadDep::Edge { + from: q, + to: b, + value, + }, + other => other, + }) + .collect(); + self.sinks.push(SinkRead { + block: q, + guard: None, + offset, + deps, + }); + } incoming.push((x, qb)); } self.s.m.set_phi(v, incoming); } + if (!has_missing && self.direct_missing.is_empty()) || self.sinks.is_empty() { + return Ok(()); + } + self.check_missing_reach(&data_phis) + } + + /// Rejects the program if any missing or mismatched phi incoming edge (or + /// direct missing value surviving via a partial/guarded overwrite) can + /// reach an observable sink along a feasible path in [`Structured`]. + fn check_missing_reach(&self, data_phis: &[(V, usize, usize)]) -> Result<(), ShaderError> { + const MAX_TAINT_ROUNDS: usize = 256; + let p = self.x.p; + let st = self.x.st; + let mut bools = BoolSet::new(&st.bools); + let mut taint: HashMap> = HashMap::new(); + + let site_cond = + |bools: &mut BoolSet, block: usize, guard: Option, invert: bool| -> Bool { + match guard { + Some(g) => { + let g = if invert { bools.not(g) } else { g }; + bools.and(st.reach[block], g) + } + None => st.reach[block], + } + }; + let dep_cond = |bools: &mut BoolSet, base: Bool, dep: ReadDep| -> (Value, Bool) { + match dep { + ReadDep::Value(u) => (u, base), + ReadDep::Edge { from, to, value: u } => { + let ec = bools.edge(st, from, to); + (u, bools.and(base, ec)) + } + } + }; + let merge = |taint: &mut HashMap>, + dst: Value, + why: Why, + cond: Bool, + bools: &mut BoolSet| + -> bool { + if cond == Bool::FALSE { + return false; + } + let list = taint.entry(dst).or_default(); + if let Some((_, existing)) = list.iter_mut().find(|(w, _)| *w == why) { + let next = bools.or(*existing, cond); + if next != *existing { + *existing = next; + return true; + } + false + } else { + list.push((why, cond)); + true + } + }; + + for &(dst, why, block, guard, invert) in &self.direct_missing { + let c = site_cond(&mut bools, block, guard, invert); + merge(&mut taint, dst, why, c, &mut bools); + } + + for &(_, b, i) in data_phis { + let phi = &p.blocks[b].phis[i]; + let bit = phi.reg == Reg::Scc; + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + if self.tail[q].is_none() { + continue; + } + let arg = phi.args[n]; + let why = match (self.vals.get(&arg).copied(), bit) { + (Some(Val::I32(_)), false) | (Some(Val::Bit(_)), true) => continue, + (Some(Val::Bit(_)), false) => "an SCC joined with SGPR values", + (Some(Val::Missing(why)), _) => why, + _ => "a join of mismatched values", + }; + let mut c = bools.edge(st, q, b); + if self.rpo[b] <= self.rpo[q] { + c = bools.forget(c, self.rpo[b]); + } + merge(&mut taint, phi.value, why, c, &mut bools); + } + } + + let propagate_step = + |taint: &mut HashMap>, bools: &mut BoolSet, precise: bool| { + let mut changed = false; + for &(_, b, i) in data_phis { + let phi = &p.blocks[b].phis[i]; + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + if self.tail[q].is_none() { + continue; + } + let Some(list) = taint.get(&phi.args[n]).cloned() else { + continue; + }; + let ec = if precise { + bools.edge(st, q, b) + } else { + Bool::TRUE + }; + for (why, c) in list { + let tc = if precise { + let mut tc = bools.and(c, ec); + if self.rpo[b] <= self.rpo[q] { + tc = bools.forget(tc, self.rpo[b]); + } + tc + } else { + Bool::TRUE + }; + changed |= merge(taint, phi.value, why, tc, bools); + } + } + } + for &w in &self.deps_order { + for info in &self.deps[&w] { + let use_c = if precise { + site_cond(bools, info.block, info.guard, info.invert_guard) + } else { + Bool::TRUE + }; + for &dep in &info.deps { + let (val, dc) = if precise { + dep_cond(bools, use_c, dep) + } else { + let u = match dep { + ReadDep::Value(u) | ReadDep::Edge { value: u, .. } => u, + }; + (u, Bool::TRUE) + }; + let Some(list) = taint.get(&val).cloned() else { + continue; + }; + for (why, c) in list { + if info.ignore_why == Some(why) { + continue; + } + let tc = if precise { + bools.and(c, dc) + } else { + Bool::TRUE + }; + changed |= merge(taint, w, why, tc, bools); + } + } + } + } + changed + }; + + let mut settled = false; + for _ in 0..MAX_TAINT_ROUNDS { + if !propagate_step(&mut taint, &mut bools, true) { + settled = true; + break; + } + } + if !settled { + // Conservative widening when cyclic propagation exceeds the round cap. + for list in taint.values_mut() { + for (_, c) in list.iter_mut() { + *c = Bool::TRUE; + } + } + while propagate_step(&mut taint, &mut bools, false) {} + } + + for sink in &self.sinks { + let sink_c = site_cond(&mut bools, sink.block, sink.guard, false); + for &dep in &sink.deps { + let (val, dc) = dep_cond(&mut bools, sink_c, dep); + if let Some(list) = taint.get(&val) { + for &(why, c) in list { + if bools.sat(c, dc) { + return Err(unsupported(sink.offset, why)); + } + } + } + } + } Ok(()) } } @@ -7790,6 +8396,24 @@ mod tests { } } + #[test] + fn v_cndmask_accepts_uniform_and_constant_masks() { + // Uniform select (`s_cselect_b32`) and inline constant masks in `v_cndmask_b32` + // (resolved in `Structured::other` or directly as constants). + let words = [ + 0xBF06_8000u32, // s_cmp_eq_u32 s0, 0 + 0x8500_80C1, // s_cselect_b32 s0, -1, 0 + 0xD501_0001, + 0x0001_0080, // v_cndmask_b32 v1, 0, 1, s0 + 0xD501_0002, + 0x0201_02C1, // v_cndmask_b32 v2, 1, v1, -1 + 0xD834_0000, + 0x0000_0200, // ds_write_b32 v0, v2 + S_ENDPGM, + ]; + lowers(&words, 0x8001).unwrap(); + } + fn perm_features(selector: u32) -> u64 { // Synthetic compute shader: // v0 is the thread ID and can supply a dynamic selector. @@ -7999,6 +8623,42 @@ mod tests { } } + #[test] + fn a_descriptor_read_only_as_data_takes_the_kind_of_its_entrys_use() { + // The table entry at s0 loaded twice: the second load's descriptor + // reads a structured buffer, the first's record count (dword 2) is + // only read as a number, as the console compiler does for a size. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408_0302, + 0xFA00_0000, // s_load_dwordx4 s[12:15], s[4:5], null + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE030_2000, + 0x8003_0100, // buffer_load_dword v1, v0, s[12:15], 0 idxen + 0x7E04_020A, // v_mov_b32 v2, s10 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + 0xD834_0000, + 0x0000_0200, // ds_write_b32 v0, v2 + S_ENDPGM, + ]; + let layout = vec![root(RootType::Table, 0, 0)]; + let used = vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }]; + lower_with(&words, layout, used).unwrap(); + } + /// Tables of 2D textures at s0 and samplers at s1. fn texture_tables() -> (Vec, Vec) { let range = |kind, user_data, slot| UsedResource { @@ -8125,6 +8785,511 @@ mod tests { lowers(&words, group_ids_xy).expect("dead timestamp"); } + #[cfg(windows)] + fn validate_dxil(dxil: &[u8]) { + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + let mut copy = dxil.to_vec(); + let ours = copy[4..20].to_vec(); + v.validate(&mut copy).expect("DXIL validation failed"); + assert_eq!(copy[4..20], ours[..], "container hash mismatch"); + } + } + + #[cfg(not(windows))] + fn validate_dxil(_dxil: &[u8]) {} + + #[test] + fn a_live_descriptor_word_stays_missing_through_two_joins() { + let mut words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 (table) + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 (root constant) + 0xBF85_0002, // take the descriptor arm when SCC is set + 0xBE89_0391, // s_mov_b32 s9, 17 + 0xBF82_0006, // skip the descriptor arm + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xE030_2000, + 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + 0xBF85_0001, // if SCC is set, keep the descriptor word live + 0xBE89_039D, // s_mov_b32 s9, 29 + 0x7E04_0209, // v_mov_b32 v2, s9 + 0xD834_0000, + 0x0000_0200, // ds_write_b32 v0, v2 + S_ENDPGM, + ]; + let run = |words: &[u32]| { + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let used = vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }]; + lower_wave(words, layout, used, false) + }; + let reason = |words: &[u32]| match run(words) { + Ok(_) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let through_two_joins = reason(&words); + assert_eq!( + through_two_joins, + Some("a descriptor's address or format read as data") + ); + words[13] = 0xBF82_0001; // skip the overwrite unconditionally: one join + assert_eq!(through_two_joins, reason(&words)); + + // Correlated overwrite: when SCC is set, always overwrite s9 = 29 before reading it. + words[13] = 0xBF84_0001; // s_cbranch_scc0 +1 (skip overwrite only when SCC is clear) + let lowered = run(&words).expect("overwritten descriptor word must lower"); + validate_dxil(&lowered.dxil); + } + + #[test] + fn unknown_stride_load_stays_missing_when_live_and_lowers_when_overwritten() { + let mut words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 (table) + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 (root constant) + 0xBF85_0002, // take the unknown-stride load arm when SCC is set + 0x7E02_0291, // v_mov_b32 v1, 17 + 0xBF82_0004, // skip the load arm + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xE030_2000, + 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen (unknown stride -> Missing) + 0xBF85_0001, // if SCC is set, keep the missing load live + 0x7E02_029D, // v_mov_b32 v1, 29 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let run = |words: &[u32]| { + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let used = vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, // unknown stride + dwords: 4, + user_data: 0, + slot: 0, + }]; + lower_wave(words, layout, used, false) + }; + let reason = |words: &[u32]| match run(words) { + Ok(_) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let two_joins = reason(&words); + assert_eq!(two_joins, Some("a structured buffer of unknown stride")); + words[11] = 0xBF82_0001; // s_branch +1: one join + assert_eq!(two_joins, reason(&words)); + + // Correlated overwrite: when SCC is set, always overwrite v1 = 29. + words[11] = 0xBF84_0001; // s_cbranch_scc0 +1 + let lowered = run(&words).expect("overwritten unknown-stride load must lower"); + validate_dxil(&lowered.dxil); + } + + #[test] + fn first_half_of_interpolation_stays_missing_when_live_and_lowers_when_overwritten() { + let mut words = [ + 0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x (Missing) + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF84_0001, // s_cbranch_scc0 +1 (skip p2 when s0 != 0) + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xBF85_0001, // s_cbranch_scc1 +1 (skip overwrite when s0 == 0) + 0x7E04_0280, // v_mov_b32 v2, 0 + 0xF800_180F, + 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm + S_ENDPGM, + ]; + let run = |words: &[u32]| { + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![root(RootType::Constants, 0, 0)], + used: vec![], + io: StageIo::Ps { + rsrc2: 0, + inputs: vec![crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: 0, + mask: 0b1111, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr: 1 << 1, // PERSP_CENTER + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, false, 4).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(); + let outputs = vec![super::SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0, + half: false, + }]; + let inputs = vec![super::SigElement { + name: "TEXCOORD".into(), + index: 0, + kind: 0, + comp: 9, + interp: 2, + row: Some(0), + col: 0, + cols: 4, + usage: 0, + half: false, + }]; + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs, + outputs, + prims: vec![], + mesh_stride: 0, + }) + }; + // Overwritten on the s0 != 0 branch: p1 never reaches exp. + let lowered = run(&words).expect("overwritten interp half must lower"); + validate_dxil(&lowered.dxil); + + // Flip word 4 to s_cbranch_scc0 +1: when s0 != 0, p1 reaches exp live. + words[4] = 0xBF84_0001; + let Err(crate::ShaderError::Unsupported { what, .. }) = run(&words) else { + panic!("live p1 must refuse"); + }; + assert_eq!(what, "the first half of an interpolation"); + + // Unconditional skip (1 join): also refuses identically. + words[4] = 0xBF82_0001; + let Err(crate::ShaderError::Unsupported { what, .. }) = run(&words) else { + panic!("1-join live p1 must refuse"); + }; + assert_eq!(what, "the first half of an interpolation"); + } + + #[test] + fn guarded_write_and_exec_mask_phi_lower_soundly() { + // 1. EXEC phi fed by a scalar SGPR in one branch, then read via s_bcnt1_i32_b32. + let exec_phi_words = [ + 0xBE84_03BF, // s_mov_b32 s4, 0x3F + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF84_0001, // s_cbranch_scc0 +1 + 0xBEFE_0304, // s_mov_b32 exec_lo, s4 + 0xBE82_0F7E, // s_bcnt1_i32_b32 s2, exec_lo + 0x7E00_0202, // v_mov_b32 v0, s2 + 0xD834_0000, + 0x0000_0000, // ds_write_b32 v0, v0 + S_ENDPGM, + ]; + let lowered = lower_wave( + &exec_phi_words, + vec![root(RootType::Constants, 0, 0)], + vec![], + false, + ) + .expect("EXEC phi read via mask_ok must lower"); + validate_dxil(&lowered.dxil); + + // 2. Guarded write (`write_placed`) preserving `17` on `!guard` lanes where `guard` + // lanes held an unknown-stride load (and overwriting `guard` lanes with `29`). + let guarded_words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 (table) + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0291, // v_mov_b32 v1, 17 + 0x7D84_0080, // v_cmp_eq_u32 vcc_lo, 0, v0 + 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo + 0xBF88_0004, // s_cbranch_execz +4 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xE030_2000, + 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen (unknown stride) + 0xBEFE_0306, // s_mov_b32 exec_lo, s6 + 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo + 0x7E02_029D, // v_mov_b32 v1, 29 (guarded by v0 == 0, keeps v1 = 17 on v0 != 0) + 0xBEFE_0306, // s_mov_b32 exec_lo, s6 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let lowered = lower_wave( + &guarded_words, + vec![root(RootType::Table, 0, 0)], + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }], + false, + ) + .expect("guarded overwrite over unknown-stride arm must lower"); + validate_dxil(&lowered.dxil); + } + + #[test] + fn loop_missing_value_refuses_on_back_edge_and_lowers_when_infeasible() { + // Loop header (word 4): s2 starts at 17, v7 = 0. Inside loop: if s0 == 0, s_memtime -> s2. + // Latch uses VCC so loop-invariant scc (s0 == 0) survives across iterations. + // After loop: if s0 == 0, overwrite s2 = 29, else read P_s2. + let mut words = [ + 0x7E00_0280, // 0: v_mov_b32 v0, 0 + 0xBE82_0391, // 1: s_mov_b32 s2, 17 + 0x7E0E_0280, // 2: v_mov_b32 v7, 0 + 0xBF06_8000, // 3: s_cmp_eq_u32 s0, 0 (loop-invariant, preserved in SCC) + // loop header (word 4): + 0xBF84_0003, // 4: s_cbranch_scc0 +3 (skip s_memtime when s0 != 0) + 0xF490_0180, + 0, // 5-6: s_memtime s[6:7] + 0xBE82_0306, // 7: s_mov_b32 s2, s6 + // latch (word 8): + 0x4A0E_0E81, // 8: v_add_nc_u32 v7, 1, v7 + 0x7D88_0E82, // 9: v_cmp_gt_u32 vcc_lo, 2, v7 + 0xBF87_FFF9, // 10: s_cbranch_vccnz -7 (back to word 4) + // after loop (word 11): + 0xBF84_0001, // 11: s_cbranch_scc0 +1 (skip overwrite when s0 != 0) + 0xBE82_039D, // 12: s_mov_b32 s2, 29 + 0x7E02_0202, // 13: v_mov_b32 v1, s2 + 0xD834_0000, + 0x0000_0100, // 14-15: ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let run = + |words: &[u32]| lower_wave(words, vec![root(RootType::Constants, 0, 0)], vec![], false); + let lowered = run(&words).expect("loop-invariant infeasible missing edge must lower"); + validate_dxil(&lowered.dxil); + + // Flip word 11 to s_cbranch_scc1 +1: s_memtime from back-edge reaches ds_write when s0 == 0. + words[11] = 0xBF85_0001; + let Err(crate::ShaderError::Unsupported { what, .. }) = run(&words) else { + panic!("live loop back-edge missing value must refuse"); + }; + assert_eq!(what, "a scalar memory read as data"); + } + + #[test] + fn old_register_missing_values_and_cached_floats_stay_refused() { + let srv_used = || { + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + let expect_unsupported = |res: Result, want: &str| match res { + Ok(_) => panic!("expected refusal `{want}`, but lowered"), + Err(crate::ShaderError::Unsupported { what, .. }) => assert_eq!(what, want), + Err(error) => panic!("{error}"), + }; + + // 1a. Direct Val::Missing on `old` surviving into `!guard` of `write_placed`. + let direct_old_guard = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xE030_2000, + 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen (unknown stride) + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 (v0 < 16) + 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo + 0x7E02_029D, // v_mov_b32 v1, 29 (v0 >= 16 keeps old unknown-stride v1) + 0xBEFE_0306, // s_mov_b32 exec_lo, s6 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + expect_unsupported( + lower_wave( + &direct_old_guard, + vec![root(RootType::Table, 0, 0)], + srv_used(), + false, + ), + "a structured buffer of unknown stride", + ); + + // 1b. Phi Val::Missing on `old` surviving into `!guard` of `write_placed`. + let phi_old_guard = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0291, // v_mov_b32 v1, 17 + 0x7D84_0080, // v_cmp_eq_u32 vcc_lo, 0, v0 (v0 == 0) + 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo + 0xBF88_0004, // s_cbranch_execz +4 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xE030_2000, + 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen + 0xBEFE_0306, // s_mov_b32 exec_lo, s6 + 0x7D8A_0080, // v_cmp_ne_u32 vcc_lo, 0, v0 (v0 != 0 -> !guard keeps v0 == 0!) + 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo + 0x7E02_029D, // v_mov_b32 v1, 29 + 0xBEFE_0306, // s_mov_b32 exec_lo, s6 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + expect_unsupported( + lower_wave( + &phi_old_guard, + vec![root(RootType::Table, 0, 0)], + srv_used(), + false, + ), + "a structured buffer of unknown stride", + ); + + // 1c. Live Val::Missing on `old` kept by `write_16` (`keep == true`). + let write16_old = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xE030_2000, + 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen + 0x6402_00F2, // v_add_f16 v1, 1.0, v0 (keeps high 16 bits of v1) + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + expect_unsupported( + lower_wave( + &write16_old, + vec![root(RootType::Table, 0, 0)], + srv_used(), + false, + ), + "a structured buffer of unknown stride", + ); + + // 1d. Live Val::Missing on `old` kept by `place_bits` (SDWA `dst_unused: UNUSED_PRESERVE`). + let sdwa_old = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xE030_2000, + 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen + 0x7E02_02F9, + 0x0006_1400, // v_mov_b32_sdwa v1, v0 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + expect_unsupported( + lower_wave( + &sdwa_old, + vec![root(RootType::Table, 0, 0)], + srv_used(), + false, + ), + "a structured buffer of unknown stride", + ); + + // 1e. Direct Val::Missing on `outside` surviving `!guard` of `ds_add_rtn_u32`. + let ds_rtn_outside = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xE030_2000, + 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 (v0 < 16) + 0xBE86_3C6A, // s_and_saveexec_b32 s6, vcc_lo + 0xD880_0000, + 0x0100_0000, // ds_add_rtn_u32 v1, v0, v0 (v0 >= 16 keeps outside = unknown-stride v1) + 0xBEFE_0306, // s_mov_b32 exec_lo, s6 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + expect_unsupported( + lower_wave( + &ds_rtn_outside, + vec![root(RootType::Table, 0, 0)], + srv_used(), + false, + ), + "a structured buffer of unknown stride", + ); + + // 2. Live missing phi flowing through chained float ops (`self.floats` cache hit) to `ds_write`. + let chained_float_phi = [ + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0002, // take s_memtime arm when s0 == 0 + 0xBE82_0391, // s_mov_b32 s2, 17 + 0xBF82_0003, // skip s_memtime + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBE82_0306, // s_mov_b32 s2, s6 + 0x0604_0002, // v_add_f32 v2, s2, v0 (inserts v2 into self.floats) + 0x0A06_04F4, // v_mul_f32 v3, 2.0, v2 (hits self.floats[&v2], inserts v3 into self.floats) + 0xD834_0000, + 0x0000_0300, // ds_write_b32 v0, v3 + S_ENDPGM, + ]; + expect_unsupported( + lower_wave( + &chained_float_phi, + vec![root(RootType::Constants, 0, 0)], + vec![], + false, + ), + "a scalar memory read as data", + ); + } + #[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/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index ac21619..6c8594d 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -87,6 +87,8 @@ pub mod host; #[cfg(all(test, windows))] mod image_atomic_tests; mod lower; +#[cfg(all(test, windows))] +mod root_view_tests; mod sampler; mod shader; #[cfg(windows)] @@ -831,6 +833,49 @@ mod tests { assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency"); } + /// A system value whose console signature used non-canonical casing (such + /// as `SV_TARGET`) must be written with DXIL's canonical name (`SV_Target`) + /// in `ISG1`/`OSG1` so `dxil.dll` validation accepts the container part. + #[test] + #[cfg(windows)] + fn non_canonical_system_value_name_validates() { + let mut s = super::shader::Shader::new(true); + s.outputs.push(SigElement { + name: "SV_TARGET".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xf, + half: false, + }); + let zero = s.m.f32(0); + let id = s.m.i32(0); + let row = s.m.i32(0); + let void = s.t.void; + for ch in 0..4u8 { + let c = s.m.i8(ch); + s.op( + s.entry, + "storeOutput.f32", + super::bitcode::Attr::NoUnwind, + void, + 5, + &[id, row, c, zero], + ); + } + s.m.terminate(s.entry, super::bitcode::Term::Ret); + let mut c = s.finish(); + let path = super::validator::Validator::default_path(); + let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else { + return; + }; + v.validate(&mut c).unwrap(); + } + /// A pixel shader reading channel z of an input whose element starts at /// w. Looking the channel up subtracted the element's first channel /// before checking the channel lies in it, so in a build with overflow diff --git a/crates/victory-shader/src/emit/root_view_tests.rs b/crates/victory-shader/src/emit/root_view_tests.rs new file mode 100644 index 0000000..351a169 --- /dev/null +++ b/crates/victory-shader/src/emit/root_view_tests.rs @@ -0,0 +1,186 @@ +//! End-to-end tests of scalar loads (`s_load_dword*`) from a root view's +//! address: synthetic GFX10 programs lowered to DXIL, validated by +//! `dxil.dll` when present, and run on the hardware GPU and on WARP. + +use super::host::{Dispatch, Host, Root, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// A root view in user SGPRs 0-1 (root parameter 0) and a table in user +/// SGPR 2 (root parameter 1) whose entry 0 is a raw UAV: dwords 2 and 3 +/// of the view's memory go to dwords 0 and 1 of the UAV. +const READ_DWORDS_2_AND_3: &[u32] = &[ + 0xF404_0100, + 0xFA00_0008, // s_load_dwordx2 s[4:5], s[0:1], 0x8 + 0xBE86_0302, // s_mov_b32 s6, s2 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], null + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x7E02_0204, // v_mov_b32 v1, s4 + 0x7E04_0205, // v_mov_b32 v2, s5 + 0xE070_0000, + 0x8002_0100, // buffer_store_dword v1, off, s[8:11], 0 + 0xE070_0004, + 0x8002_0200, // buffer_store_dword v2, off, s[8:11], 0 offset:4 + S_ENDPGM, +]; + +/// [`READ_DWORDS_2_AND_3`] lowered with the root view of `kind`. +fn build(kind: ResourceType) -> HostShader { + let param = |root, sgprs, user_data, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + let used = |kind, root, user_data, slot| UsedResource { + kind, + root, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data, + slot, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + param(RootType::Descriptor, 2, 0, 0), + param(RootType::Table, 1, 2, 1), + ], + used: vec![ + used(kind, RootType::Descriptor, 0, 0), + used(ResourceType::Uav, RootType::Table, 2, 1), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 3 << 1, + threads: [1, 1, 1], + }), + code: READ_DWORDS_2_AND_3 + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let names: Vec<_> = p + .blocks + .iter() + .flat_map(|b| b.insts.iter().map(|i| i.name())) + .collect(); + assert_eq!( + names, + [ + "s_load_dwordx2", + "s_mov_b32", + "s_mov_b32", + "s_load_dwordx4", + "v_mov_b32", + "v_mov_b32", + "buffer_store_dword", + "buffer_store_dword", + "s_endpgm", + ] + ); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + address_map: lowered.address_map, + descriptor_words: lowered.descriptor_words, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } else { + eprintln!("no dxil.dll; validation skipped"); + } + shader +} + +#[test] +fn scalar_loads_read_a_root_srv_and_a_root_cbv() { + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let data: Vec = (0..64).map(|i| 0x2000 + i).collect(); + for (kind, srv) in [(ResourceType::Srv, true), (ResourceType::Cbv, false)] { + let shader = build(kind); + assert_eq!( + (shader.root_srvs.len(), shader.root_cbvs.len()), + if srv { (1, 0) } else { (0, 1) }, + "{kind:?}: the root view the shader declares" + ); + for warp in [false, true] { + let host = match Host::new(warp) { + Ok(h) => h, + Err(e) if warp => { + eprintln!("no SM 6.6 WARP device ({e}); skipped"); + continue; + } + Err(e) => panic!("no SM 6.6 hardware device: {e}"), + }; + let label = if warp { "WARP" } else { "hardware" }; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + assert_eq!(u.root, RootType::Table, "{u:?}"); + ud[u.index as usize] = 0; + } + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label} {kind:?}: {e}")); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + ( + 1, + Root::View { + srv, + data: data.clone(), + }, + ), + ], + views: &[View::RawUav(2)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label} {kind:?}: {e}")); + assert_eq!(out[0], [0x2002, 0x2003], "{label} {kind:?}"); + eprintln!("{label}: scalar loads from a root {kind:?} exact"); + } + } +} diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 58826c6..2eea61b 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -736,3 +736,101 @@ impl Shader { Some(self.m.md_node(list)) } } + +#[cfg(all(test, windows))] +mod tests { + use super::super::HostShader; + use super::super::bitcode::{Bin, Term, pred}; + use super::super::host::Host; + use super::super::validator; + use super::*; + use crate::native::HwStage; + + fn validate_and_create_cs_pso(mut dxil: Vec) { + let path = validator::Validator::default_path(); + if let Ok(mut validator) = validator::Validator::load(path.as_deref()) { + validator.validate(&mut dxil).unwrap(); + } + let hs = HostShader { + stage: HwStage::Cs, + dxil, + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + address_map: false, + descriptor_words: false, + }; + if let Ok(host) = Host::new(false) { + host.compute_pipeline(&hs).unwrap(); + } + if let Ok(warp) = Host::new(true) { + warp.compute_pipeline(&hs).unwrap(); + } + } + + #[test] + fn two_empty_latches_to_same_header_validate() { + let mut s = Shader::new(false); + s.threads = Some([1, 1, 1]); + let entry = s.entry; + let head = s.m.new_block(); + let body = s.m.new_block(); + let latch_a = s.m.new_block(); + let latch_b = s.m.new_block(); + let exit = s.m.new_block(); + + let i32t = s.t.i32; + let zero = s.m.i32(0); + let one = s.m.i32(1); + let two = s.m.i32(2); + let ten = s.m.i32(10); + s.m.terminate(entry, Term::Br(head)); + + let acc = s.m.phi(head, i32t); + let go = s.m.cmp(head, pred::IULT, acc, ten); + s.m.terminate(head, Term::CondBr(go, body, exit)); + + let bit = s.m.bin(body, Bin::And, acc, one); + let pick = s.m.cmp(body, pred::EQ, bit, zero); + s.m.terminate(body, Term::CondBr(pick, latch_a, latch_b)); + + // Two distinct empty back-edge latches from `body` to `head` carry + // distinct incoming values; only one may fold into `body`. + s.m.terminate(latch_a, Term::Br(head)); + s.m.terminate(latch_b, Term::Br(head)); + let next_a = s.m.bin(body, Bin::Add, acc, one); + let next_b = s.m.bin(body, Bin::Add, acc, two); + s.m.set_phi( + acc, + vec![(zero, entry), (next_a, latch_a), (next_b, latch_b)], + ); + + s.m.terminate(exit, Term::Ret); + validate_and_create_cs_pso(s.finish()); + } + + #[test] + fn phi_with_unreachable_predecessor_validates() { + let mut s = Shader::new(false); + s.threads = Some([1, 1, 1]); + let entry = s.entry; + let dead = s.m.new_block(); + let join = s.m.new_block(); + + let i32t = s.t.i32; + let one = s.m.i32(1); + let live_val = s.m.bin(entry, Bin::Add, one, one); + s.m.terminate(entry, Term::Br(join)); + + let dead_val = s.m.bin(dead, Bin::Add, one, one); + s.m.terminate(dead, Term::Br(join)); + + let merged = s.m.phi(join, i32t); + s.m.set_phi(merged, vec![(live_val, entry), (dead_val, dead)]); + let _used = s.m.bin(join, Bin::Add, merged, one); + s.m.terminate(join, Term::Ret); + validate_and_create_cs_pso(s.finish()); + } +} diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index ff5fafb..cacd0a7 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -2051,3 +2051,153 @@ fn run_output_cases( } assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); } +#[test] +fn reachability_overwritten_missing_phis_match_on_host_and_warp() { + // 1. Correlated overwrite of a missing descriptor word (`s13`) across two joins: + // when s0 == 0: load s[12:15], read UAV via raw buffer_load_dword, then overwrite s13 = 29; + // when s0 != 0: set s13 = 17, skip overwrite. Result v0 = s13. + let desc_word_shader = build_valu_cs(&[ + 0x7E0C_0280, // v_mov_b32 v6, 0 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0002, // s_cbranch_scc1 +2 + 0xBE8D_0391, // s_mov_b32 s13, 17 + 0xBF82_0004, // s_branch +4 + s_load_dwordx4(12, 4)[0], + s_load_dwordx4(12, 4)[1], + 0xE030_0000, + 0x8003_0506, // buffer_load_dword v5, v6, s[12:15], 0 + 0xBF84_0001, // s_cbranch_scc0 +1 (skip overwrite only when s0 != 0) + 0xBE8D_039D, // s_mov_b32 s13, 29 + vop1(0x001, 0, sgpr(13)), + ]); + // 2. Correlated overwrite of an unknown-stride buffer_load_dword (`v5` -> Missing) across two joins: + // when s0 == 0: load with idxen (stride = 0 in build_valu_cs -> unknown stride), then overwrite v5 = 29; + // when s0 != 0: v5 = 17, skip overwrite. Result v0 = v5. + let unknown_stride_shader = build_valu_cs(&[ + 0x7E0C_0280, // v_mov_b32 v6, 0 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0002, // s_cbranch_scc1 +2 + 0x7E0A_0291, // v_mov_b32 v5, 17 + 0xBF82_0004, // s_branch +4 + s_load_dwordx4(12, 4)[0], + s_load_dwordx4(12, 4)[1], + 0xE030_2000, + 0x8003_0506, // buffer_load_dword v5, v6, s[12:15], 0 idxen (unknown stride) + 0xBF84_0001, // s_cbranch_scc0 +1 (skip overwrite only when s0 != 0) + 0x7E0A_029D, // v_mov_b32 v5, 29 + vop1(0x001, 0, vgpr(5)), + ]); + // 3. Loop-invariant infeasible s_memtime phi (latch uses VCC to preserve SCC): + // when s0 == 0: loop runs s_memtime -> s13, then overwrites s13 = 29 after loop; + // when s0 != 0: loop keeps s13 = 17, skips overwrite after loop. + let loop_shader = build_valu_cs(&[ + 0xBE8D_0391, // s_mov_b32 s13, 17 + 0x7E0E_0280, // v_mov_b32 v7, 0 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF84_0003, // s_cbranch_scc0 +3 + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBE8D_0306, // s_mov_b32 s13, s6 + 0x4A0E_0E81, // v_add_nc_u32 v7, 1, v7 + 0x7D88_0E82, // v_cmp_gt_u32 vcc_lo, 2, v7 + 0xBF87_FFF9, // s_cbranch_vccnz -7 + 0xBF84_0001, // s_cbranch_scc0 +1 + 0xBE8D_039D, // s_mov_b32 s13, 29 + vop1(0x001, 0, sgpr(13)), + ]); + + let cases = [([0, 0, 0, 0], 29u32), ([1, 0, 0, 0], 17u32)]; + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + for (name, shader) in [ + ("desc_word", &desc_word_shader), + ("unknown_stride", &unknown_stride_shader), + ("loop_memtime", &loop_shader), + ] { + run_cases(shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend} {name} s0={}: got {got}, want {want}", + inp[0] + ); + }); + } +} +#[test] +fn scalar_buffer_loads_read_a_uav_through_its_table() { + // The UAV is the one `build_valu_cs` stores to: write root constant 0 + // to its dword 0, read it back with a scalar buffer load, and store + // that. + let body = [ + 0xE070_0000, + 0x8002_0100, // buffer_store_dword v1, off, s[8:11], 0 + 0xF420_0304, + 0xFA00_0000, // s_buffer_load_dword s12, s[8:11], null + 0x7E00_020C, // v_mov_b32 v0, s12 + ]; + let shader = build_valu_cs(&body); + let cases = [[0x1234_5678, 0, 0, 0], [0xDEAD_BEEF, 0, 0, 0]]; + run_cases(&shader, &cases, |backend, _, inp, got| { + assert_eq!(got, inp[0], "{backend}: read back {got:#010x}"); + }); +} + +#[test] +fn v_cmp_16bit_ignores_vop3_op_sel() { + // v_cmp_lt_f16_e64 s6, v1, v2 (VOP3 encoding of VOPC 0x0c9), op_sel:[1,0]; + // then v_cndmask_b32_e64 v0, 0, 1, s6. + let [mut hi0, hi1] = vop3(0x0c9, 6, vgpr(1), vgpr(2), 0); + hi0 |= 1 << 11; // op_sel[0] = high half, which RDNA2 ignores here + let f16_hi = build_valu_cs(&[ + hi0, + hi1, + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + // The same compare with op_sel clear, as a control. + let f16_lo = build_valu_cs(&[ + vop3(0x0c9, 6, vgpr(1), vgpr(2), 0)[0], + vop3(0x0c9, 6, vgpr(1), vgpr(2), 0)[1], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + // v_cmp_lt_u16_e64 with op_sel:[1,0] (VOPC 0x0a9). + let [mut hi0, hi1] = vop3(0x0a9, 6, vgpr(1), vgpr(2), 0); + hi0 |= 1 << 11; + let u16_hi = build_valu_cs(&[ + hi0, + hi1, + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + + // Low halves decide: 1.0 < 1.5 true; 2.0 < 1.5 false. In the second + // case honouring op_sel (high half 1.0) would wrongly say true. + let f16_inputs = [ + [0x4000_3C00, 0x0000_3E00, 0, 0], + [0x3C00_4000, 0x0000_3E00, 0, 0], + ]; + let f16_wants = [1u32, 0u32]; + for (name, shader) in [("op_sel high", &f16_hi), ("op_sel low", &f16_lo)] { + run_cases(shader, &f16_inputs, |backend, i, inp, got| { + let want = f16_wants[i]; + assert_eq!( + got, want, + "{backend}: v_cmp_lt_f16({name}) ({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + } + + // u16: low 9 < 5 is false; honouring op_sel (high half 1) would say true. + let u16_inputs = [[0x0001_0009, 0x0000_0005, 0, 0]]; + let u16_wants = [0u32]; + run_cases(&u16_hi, &u16_inputs, |backend, i, inp, got| { + let want = u16_wants[i]; + assert_eq!( + got, want, + "{backend}: v_cmp_lt_u16(op_sel high) ({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); +} diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index c9c5ce2..1710489 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -94,19 +94,15 @@ fn build(words: &[u32], buffers: bool) -> HostShader { shader } -/// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the -/// hardware GPU and on WARP (each skipped without a device) and returns, -/// per one that ran, the UAV's 32 dwords. -fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { - let samplers = [D3D12_SAMPLER_DESC { - Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, - AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - MaxAnisotropy: 1, - MaxLOD: f32::MAX, - ..Default::default() - }]; +/// Runs `shader` with `views` at heap indices 0.. (the UAV last) and +/// `samplers` at sampler-heap indices 0.. on the hardware GPU and on WARP (each +/// skipped without a device) and returns, per one that ran, the UAV's 32 +/// dwords. +fn run_with_samplers( + shader: &HostShader, + views: &[View], + samplers: &[D3D12_SAMPLER_DESC], +) -> Vec<(&'static str, Vec)> { let mut out = Vec::new(); // One GPU test at a time, with the VALU tests: in parallel on the // hardware adapter and WARP the test process sometimes died of an @@ -136,7 +132,7 @@ fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { &Dispatch { roots: vec![(0, Root::Constants(ud))], views, - samplers: &samplers, + samplers, groups: [1, 1, 1], }, ) @@ -146,6 +142,19 @@ fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { out } +fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { + let samplers = [D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }]; + run_with_samplers(shader, views, &samplers) +} + /// The red channel each lane sampled from two 1x1 textures, red 1.0 at /// heap index 0 and 2.0 at 1. fn sampled(shader: &HostShader) -> Vec<(&'static str, Vec)> { @@ -249,3 +258,79 @@ fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() { } } } + +#[test] +fn lanes_sample_texture_after_redundant_partial_write() { + use crate::resource::tests::joined_with_redundant_write; + let shader = build(&joined_with_redundant_write(), false); + let results = sampled(&shader); + assert!(!results.is_empty()); + let want: Vec = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); + for (label, red) in results { + assert_eq!(red, want, "{label}"); + } +} + +#[test] +fn lanes_sample_joined_sampler_after_redundant_partial_write() { + use crate::resource::tests::joined_sampler_shader; + let shader = build(&joined_sampler_shader(Some(0x7E08_0218)), false); + let tex = [[1.0f32, 0.0, 0.0, 1.0], [2.0f32, 0.0, 0.0, 1.0]]; + let views = [ + View::Texture(2, 1, &tex), + View::Texture(2, 1, &tex), + View::RawUav(32), + ]; + let sampler = |addr| D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: addr, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }; + let wrap = sampler(D3D12_TEXTURE_ADDRESS_MODE_WRAP); + let clamp = sampler(D3D12_TEXTURE_ADDRESS_MODE_CLAMP); + + for (swapped, samplers) in [(false, [wrap, clamp]), (true, [clamp, wrap])] { + let results = run_with_samplers(&shader, &views, &samplers); + assert!(!results.is_empty()); + let want: Vec = (0..32) + .map(|l| if (l < 16) ^ swapped { 1.0 } else { 2.0 }) + .collect(); + for (label, words) in results { + let red: Vec = words.into_iter().map(f32::from_bits).collect(); + assert_eq!(red, want, "{label}, swapped {swapped}"); + } + } +} + +#[test] +fn lanes_sample_after_vgpr_swap_and_word_extract() { + use crate::resource::tests::WATERFALL_JOINED_WAVE32; + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let at = words.iter().position(|&w| w == 0x887E_147E).unwrap() + 1; + words.splice( + at..at, + [ + 0x7E08_CB05, // v_swap_b32 v4, v5 + 0x7E0A_CB04, // v_swap_b32 v5, v4 + 0x3808_0880, // v_or_b32 v4, 0, v4 + 0xD700_0014, + 0x0002_0CA0, // v_lshrrev_b64 v[20:21], 32, v[6:7] + 0x7E0E_0314, // v_mov_b32 v7, v20 + 0xD744_0016, + 0x03FE_1308, + 0x0706_0504, // v_perm_b32 v22, v8, v9, 0x07060504 + 0x7E10_0316, // v_mov_b32 v8, v22 + ], + ); + let shader = build(&words, false); + let results = sampled(&shader); + assert!(!results.is_empty()); + let want: Vec = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); + for (label, red) in results { + assert_eq!(red, want, "{label}"); + } +} diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 1b2bf98..3e8a2c9 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -12,11 +12,15 @@ //! memory address is traced through the SSA values back to those //! parameters, by data flow: copies, phis that agree, and additions. +use std::collections::HashMap; + use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, RootParam, RootType}; -use crate::structure::{Bool, LaneExit, Structured}; +use crate::structure::{Atom, Bool, LaneExit, Structured}; + +mod uniform; /// An instruction: block and index in [`crate::ir::Block::insts`]. pub type Site = (usize, usize); @@ -312,7 +316,7 @@ pub fn track( } /// A dword after copy propagation. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] enum Term { Const(u32), Value(Value), @@ -340,8 +344,35 @@ struct Tracer<'a> { lanes: Option<&'a Structured>, /// Reverse-postorder index per block. rpo: Vec, + /// Memo of [`Tracer::uniform`] per value. + uniform_memo: std::cell::RefCell>>, + /// Per value: whether a phi is uniform, settled on first use + /// ([`uniform`] module). + phi_ok: std::cell::RefCell>>, + regions: std::cell::OnceCell, } +/// VALU operations whose result is uniform when their operands are: the +/// address arithmetic a compiler moves into VGPRs and then reads back with +/// `v_readfirstlane_b32`. +const UNIFORM_VALU: &[&str] = &[ + "v_mov_b32", + "v_add_co_u32", + "v_add_nc_u32", + "v_add_co_ci_u32", + "v_sub_co_u32", + "v_sub_nc_u32", + "v_lshlrev_b32", + "v_lshlrev_b64", + "v_lshl_add_u32", + "v_add3_u32", + "v_ashrrev_i32", + "v_med3_i32", + "v_and_b32", + "v_or_b32", + "v_mul_lo_u32", +]; + /// What lanes are known to satisfy: each [`Bool`] where its flag is set, /// its negation where not. type Known = Vec<(Bool, bool)>; @@ -401,6 +432,9 @@ impl<'a> Tracer<'a> { origin: Vec::new(), lanes, rpo, + uniform_memo: std::cell::RefCell::new(vec![None; n]), + phi_ok: std::cell::RefCell::new(None), + regions: std::cell::OnceCell::new(), }; t.origin = t.propagate_copies(n)?; Ok(t) @@ -545,6 +579,9 @@ impl<'a> Tracer<'a> { dynamic: None, }; } + if let Some(src) = self.uniform_first_lane(v) { + return self.sum(self.vorigin(src)); + } let Some([a, b]) = self .sop2(v, &["s_add_u32", "s_add_i32"]) .map(|(_, t)| t) @@ -611,6 +648,8 @@ impl<'a> Tracer<'a> { && let Fields::Valu(f) = &inst.fields && f.abs == 0 && f.neg == 0 + && !f.clamp + && f.omod == 0 && f.sdwa.is_none() && f.dpp.is_none() && let Some(t) = f.src.first().and_then(|s| self.vterm(inst, s)) @@ -668,6 +707,7 @@ impl<'a> Tracer<'a> { /// The address `lo` and `hi` hold, plus `extra` (an instruction's /// immediate and offset register). fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result { + let (lo, hi) = (self.unlaned(lo), self.unlaned(hi)); let s = self.sum(lo); if s.dynamic.is_some() && extra.dynamic.is_some() { return Err("an address with two computed terms"); @@ -727,7 +767,9 @@ impl<'a> Tracer<'a> { /// `hi` adds something (with carry) to `high`: `s_addc_u32` or /// `v_add_co_ci_u32` with `high` as an operand. fn carried(&self, hi: Term, high: Value) -> bool { - let Term::Value(v) = hi else { return false }; + let Term::Value(v) = self.unlaned(hi) else { + return false; + }; if v == high { return true; } @@ -760,6 +802,9 @@ impl<'a> Tracer<'a> { return "an address relative to the program counter"; } match self.def(v).map(|i| i.name()) { + Some("v_readfirstlane_b32") => { + "an address read from the first lane of a per-lane value" + } Some(n) if n.starts_with("s_load_") => "an address loaded from memory", None => "an address from a phi", _ => "an address not from a root parameter", @@ -1062,6 +1107,65 @@ impl<'a> Tracer<'a> { inst.read(Reg::V(reg)) } + /// The VGPR a `v_readfirstlane_b32` writing `v` reads, when that value + /// is uniform: the first lane's is then every lane's. + fn uniform_first_lane(&self, v: Value) -> Option { + self.first_lane_source(v).filter(|&s| self.uniform(s)) + } + + /// `t`, with a first-lane read of a uniform value replaced by its source. + fn unlaned(&self, t: Term) -> Term { + match t { + Term::Value(v) => self + .uniform_first_lane(v) + .map_or(t, |src| self.vorigin(src)), + Term::Const(_) => t, + } + } + + /// Whether every lane holds the same value of `v`: built from scalars, + /// constants and first-lane reads, through [`UNIFORM_VALU`]. + fn uniform(&self, v: Value) -> bool { + let memo = self.uniform_memo.borrow()[v.0 as usize]; + if let Some(known) = memo { + return known; + } + let known = self.uniform_now(v); + self.uniform_memo.borrow_mut()[v.0 as usize] = Some(known); + known + } + + fn uniform_now(&self, v: Value) -> bool { + if let Some(reg) = self.inputs[v.0 as usize] { + return matches!(reg, Reg::S(_)); + } + if self.phis[v.0 as usize].is_some() { + return self.phi_uniform(v); + } + let Some(inst) = self.def(v) else { + return false; + }; + if matches!(inst.name(), "v_readfirstlane_b32" | "v_readlane_b32") { + return true; + } + let uniform_op = |op: &Operand| match *op { + Operand::Vector { reg, dwords } => { + (0..dwords).all(|k| inst.read(Reg::V(reg + k)).is_some_and(|x| self.uniform(x))) + } + Operand::Scalar { code, dwords } if code != NULL => { + (0..dwords).all(|k| inst.read(Reg::S(code + k)).is_some_and(|x| self.uniform(x))) + } + _ => true, + }; + match &inst.fields { + Fields::Sop { src, .. } => src.iter().all(uniform_op), + Fields::Valu(f) if UNIFORM_VALU.contains(&inst.name()) => { + f.src.iter().all(uniform_op) && self.valu_reads_uniform(inst, self.guarded(v)) + } + _ => false, + } + } + /// The `v_readfirstlane_b32` results the descriptor operand `op` of /// `inst` is, when every dword is one. fn first_lane_words(&self, inst: &Inst, op: &Operand) -> Option> { @@ -1076,19 +1180,6 @@ impl<'a> Tracer<'a> { .collect() } - /// `t` through VGPR copies (of VGPRs or of scalars) and copies. - fn lane_term(&self, mut t: Term) -> Term { - for _ in 0..MAX_JOINS * 2 { - let Term::Value(v) = t else { break }; - let next = self.vorigin(v); - if next == t { - break; - } - t = next; - } - t - } - /// Whether `t` is a value each lane holds its own of (one in VGPRs). fn varies(&self, t: Term) -> bool { let Term::Value(v) = t else { return false }; @@ -1103,40 +1194,263 @@ impl<'a> Tracer<'a> { matches!(reg, Some(Reg::V(_))) } - /// [`Self::lane_term`], where every lane in `known` runs each VGPR copy - /// it follows. - fn lane_value(&self, mut t: Term, known: &Known) -> Result { + /// `t` through VGPR copies and lane-preserving moves/extracts where + /// every lane in `known` sees the same result (including guarded writes + /// that provably rewrite what active lanes already held). + fn lane_value(&self, t: Term, known: &[(Bool, bool)]) -> Result { + self.lane_value_in(t, known, 0) + } + + fn lane_value_in( + &self, + mut t: Term, + known: &[(Bool, bool)], + depth: usize, + ) -> Result { for _ in 0..MAX_JOINS * 2 { let Term::Value(v) = t else { break }; - let next = self.vstep(v); - if next == t { - break; + if !self.varies(t) { + let next = self.origin(v); + if next == t { + break; + } + t = next; + continue; } - if self.varies(t) - && let Some(site) = self.defs[v.0 as usize] + let Some(site) = self.defs[v.0 as usize] else { + break; + }; + if let Some((dst_reg, next)) = self.lane_copy(v) { + match self.runs(site, known) { + Ok(()) => { + if next == t { + break; + } + t = next; + } + Err(err) => { + t = self + .redundant_write(site, dst_reg, next, known, depth) + .ok_or(err)? + } + } + } else if let Some((dst_reg, _, _, _)) = self.lane_picked_with_reg(v) + && let Err(err) = self.runs(site, known) { - self.runs(site, known)?; + // A guarded v_cndmask_b32 whose active lanes already hold the + // selected value is also a no-op across all lanes in `known`. + t = self + .redundant_write(site, dst_reg, Term::Value(v), known, depth) + .ok_or(err)?; + } else { + break; } - t = next; } Ok(t) } - /// One copy of [`Self::vorigin`]: what the `v_mov_b32` writing `v` - /// reads, or `v`'s origin. - fn vstep(&self, v: Value) -> Term { - if let Some(inst) = self.def(v) - && inst.name() == "v_mov_b32" - && let Fields::Valu(f) = &inst.fields - && f.abs == 0 - && f.neg == 0 - && f.sdwa.is_none() - && f.dpp.is_none() - && let Some(t) = f.src.first().and_then(|s| self.raw(inst, s)) - { - return t; + /// When a guarded write to `dst_reg` at `site` writes `rhs` equal to the + /// prior value on every active lane in `known`, returns the prior value. + fn redundant_write( + &self, + site: Site, + dst_reg: Reg, + rhs: Term, + known: &[(Bool, bool)], + depth: usize, + ) -> Option { + if depth >= MAX_JOINS { + return None; + } + let old = self.inst(site).read(dst_reg)?; + let lanes = self.lanes?; + let guard = lanes.guards[site.0][site.1]?; + let mut active = known.to_vec(); + active.extend([(lanes.reach[site.0], true), (guard, true)]); + self.lane_value_equals(Term::Value(old), rhs, &active, depth + 1) + .then_some(Term::Value(old)) + } + + /// A single lane-preserving VGPR copy, identity ALU operation, or + /// 32-bit word extract writing `v`: its destination register and the + /// value written when active. + fn lane_copy(&self, v: Value) -> Option<(Reg, Term)> { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if f.abs != 0 || f.neg != 0 || f.clamp || f.omod != 0 || f.dpp.is_some() { + return None; + } + let name = inst.name(); + if name == "v_mov_b32" { + let Some(Operand::Vector { reg, .. }) = f.dst else { + return None; + }; + if inst.write(Reg::V(reg)) != Some(v) { + return None; + } + if !f + .sdwa + .is_none_or(|s| s.dst_sel == 6 && s.src_sel[0] == 6 && s.sext & 1 == 0) + { + return None; + } + return Some((Reg::V(reg), self.raw(inst, f.src.first()?)?)); + } + if f.sdwa.is_some() { + return None; + } + if name == "v_swap_b32" { + let (Some(Operand::Vector { reg: dreg, .. }), Some(&Operand::Vector { reg: sreg, .. })) = + (f.dst, f.src.first()) + else { + return None; + }; + if inst.write(Reg::V(dreg)) == Some(v) { + return Some((Reg::V(dreg), Term::Value(inst.read(Reg::V(sreg))?))); + } + if inst.write(Reg::V(sreg)) == Some(v) { + return Some((Reg::V(sreg), Term::Value(inst.read(Reg::V(dreg))?))); + } + return None; + } + let Some(Operand::Vector { reg: dreg, dwords }) = f.dst else { + return None; + }; + if dwords == 2 && matches!(name, "v_lshrrev_b64" | "v_ashrrev_i64" | "v_lshlrev_b64") { + let [sh_op, src_op] = &f.src[..] else { + return None; + }; + let Term::Const(sh) = self.raw(inst, sh_op)? else { + return None; + }; + let words = self.raw64(inst, src_op)?; + let sh = sh & 63; + let k = inst + .writes + .iter() + .filter(|w| matches!(w.0, Reg::V(_))) + .position(|w| w.1 == v)?; + let reg = Reg::V(dreg + k as u8); + return match (name, sh, k) { + (_, 0, 0) => Some((reg, words[0])), + (_, 0, 1) => Some((reg, words[1])), + ("v_lshrrev_b64" | "v_ashrrev_i64", 32, 0) => Some((reg, words[1])), + ("v_lshrrev_b64", 32, 1) => Some((reg, Term::Const(0))), + ("v_lshlrev_b64", 32, 0) => Some((reg, Term::Const(0))), + ("v_lshlrev_b64", 32, 1) => Some((reg, words[0])), + _ => None, + }; + } + if inst.write(Reg::V(dreg)) != Some(v) { + return None; + } + let dst_reg = Reg::V(dreg); + let op = |k: usize| self.raw(inst, f.src.get(k)?); + let term = match name { + "v_or_b32" => match (op(0)?, op(1)?) { + (a, Term::Const(0)) | (Term::Const(0), a) => Some(a), + (a, b) if a == b => Some(a), + _ => None, + }, + "v_and_b32" => match (op(0)?, op(1)?) { + (a, Term::Const(u32::MAX)) | (Term::Const(u32::MAX), a) => Some(a), + (a, b) if a == b => Some(a), + _ => None, + }, + "v_xor_b32" => match (op(0)?, op(1)?) { + (a, Term::Const(0)) | (Term::Const(0), a) => Some(a), + _ => None, + }, + "v_add_nc_u32" | "v_add_co_u32" => match (op(0)?, op(1)?) { + (a, Term::Const(0)) | (Term::Const(0), a) => Some(a), + _ => None, + }, + "v_sub_nc_u32" | "v_sub_co_u32" => match (op(0)?, op(1)?) { + (a, Term::Const(0)) => Some(a), + _ => None, + }, + "v_subrev_nc_u32" | "v_subrev_co_u32" => match (op(0)?, op(1)?) { + (Term::Const(0), a) => Some(a), + _ => None, + }, + "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => match (op(0)?, op(1)?) { + (Term::Const(sh), a) if sh & 31 == 0 => Some(a), + _ => None, + }, + "v_mul_lo_u32" => match (op(0)?, op(1)?) { + (a, Term::Const(1)) | (Term::Const(1), a) => Some(a), + _ => None, + }, + "v_min_u32" => match (op(0)?, op(1)?) { + (a, Term::Const(u32::MAX)) | (Term::Const(u32::MAX), a) => Some(a), + (a, b) if a == b => Some(a), + _ => None, + }, + "v_max_u32" => match (op(0)?, op(1)?) { + (a, Term::Const(0)) | (Term::Const(0), a) => Some(a), + (a, b) if a == b => Some(a), + _ => None, + }, + "v_min_i32" | "v_max_i32" => match (op(0)?, op(1)?) { + (a, b) if a == b => Some(a), + _ => None, + }, + "v_bfi_b32" => match (op(0)?, op(1)?, op(2)?) { + (Term::Const(u32::MAX), a, _) | (Term::Const(0), _, a) => Some(a), + (_, a, b) if a == b => Some(a), + _ => None, + }, + "v_perm_b32" => match (op(0)?, op(1)?, op(2)?) { + (_, src1, Term::Const(0x0302_0100)) => Some(src1), + (src0, _, Term::Const(0x0706_0504)) => Some(src0), + _ => None, + }, + "v_alignbit_b32" => match (op(1)?, op(2)?) { + (src1, Term::Const(sh)) if sh & 31 == 0 => Some(src1), + _ => None, + }, + "v_alignbyte_b32" => match (op(1)?, op(2)?) { + (src1, Term::Const(sh)) if sh & 3 == 0 => Some(src1), + _ => None, + }, + "v_cndmask_b32" => { + let (clear, set, mask) = (op(0)?, op(1)?, f.src.get(2)?); + match *mask { + Operand::Scalar { code: NULL, .. } + | Operand::Const(128) + | Operand::Literal(0) => Some(clear), + Operand::Const(193) => Some(set), + Operand::Literal(u32::MAX) if !self.p.wave64 => Some(set), + _ if clear == set => Some(clear), + _ => None, + } + } + _ => None, + }?; + Some((dst_reg, term)) + } + + /// Resolves a 64-bit VALU operand to its `[low, high]` dwords. + fn raw64(&self, inst: &Inst, op: &Operand) -> Option<[Term; 2]> { + match *op { + Operand::Vector { reg, .. } => Some([ + Term::Value(inst.read(Reg::V(reg))?), + Term::Value(inst.read(Reg::V(reg + 1))?), + ]), + Operand::Scalar { code: NULL, .. } => Some([Term::Const(0), Term::Const(0)]), + Operand::Scalar { code, .. } => Some([ + self.origin(inst.read(Reg::S(code))?), + self.origin(inst.read(Reg::S(code + 1))?), + ]), + Operand::Const(c @ 128..=208) => { + let low = inline(c)?; + Some([Term::Const(low), Term::Const(((low as i32) >> 31) as u32)]) + } + Operand::Literal(x) => Some([Term::Const(x), Term::Const(0)]), + _ => None, } - self.origin(v) } /// A VALU operand as `inst` reads it: a VGPR's value itself, other @@ -1148,19 +1462,473 @@ impl<'a> Tracer<'a> { } } + /// Proves that `a` and `b` evaluate to the same 32-bit word in every lane + /// satisfying `known`. + fn lane_value_equals(&self, a: Term, b: Term, known: &[(Bool, bool)], depth: usize) -> bool { + if !self.feasible(known) { + return true; + } + if depth > MAX_JOINS { + return false; + } + let Ok(a) = self.lane_value_in(a, known, depth) else { + return false; + }; + let Ok(b) = self.lane_value_in(b, known, depth) else { + return false; + }; + if a == b { + return true; + } + if depth == MAX_JOINS { + return false; + } + if let Some(branches) = self.split_term(a, known) { + let mut next_known = known.to_vec(); + return branches.into_iter().all(|(ext, arg)| { + let n = next_known.len(); + next_known.extend(ext); + let ok = self.lane_value_equals(arg, b, &next_known, depth + 1); + next_known.truncate(n); + ok + }); + } + if let Some(branches) = self.split_term(b, known) { + let mut next_known = known.to_vec(); + return branches.into_iter().all(|(ext, arg)| { + let n = next_known.len(); + next_known.extend(ext); + let ok = self.lane_value_equals(a, arg, &next_known, depth + 1); + next_known.truncate(n); + ok + }); + } + false + } + + /// Splits a forward phi or select `t` into `(edge_conditions, branch_term)` + /// cases under `known`. + fn split_term(&self, t: Term, known: &[(Bool, bool)]) -> Option> { + let Term::Value(v) = t else { return None }; + if let Some((block, phi_idx)) = self.phis[v.0 as usize] { + let preds = &self.p.blocks[block].preds; + if preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) { + return None; + } + let lanes = self.lanes?; + let args = &self.p.blocks[block].phis[phi_idx].args; + return Some( + preds + .iter() + .enumerate() + .map(|(j, &q)| { + let mut ext = vec![(lanes.reach[q], true)]; + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + ext.push((when, taken == block)); + } + (ext, Term::Value(args[j])) + }) + .collect(), + ); + } + if let Some((_, mask, set_val, clear_val)) = self.lane_picked_with_reg(v) { + let site = self.defs[v.0 as usize]?; + self.runs(site, known).ok()?; + let bit = self.lanes?.masks.get(&mask).copied()?; + return Some(vec![ + (vec![(bit, true)], set_val), + (vec![(bit, false)], clear_val), + ]); + } + if let Some((scc, set_val, clear_val)) = self.picked(v) { + if let Some(lanes) = self.lanes + && let Some(ub) = lanes.bools.var_bool(Atom::Uniform(scc)) + { + return Some(vec![ + (vec![(ub, true)], set_val), + (vec![(ub, false)], clear_val), + ]); + } + return Some(vec![(vec![], set_val), (vec![], clear_val)]); + } + None + } + + /// Whether some lane can satisfy all conditions in `all`, taking into + /// account equivalent/opposite `v_cmp` lane atoms and 1D integer bounds. + fn feasible(&self, all: &[(Bool, bool)]) -> bool { + let Some(lanes) = self.lanes else { + return true; + }; + if !lanes.bools.meet(all) { + return false; + } + let mut lane_atoms = Vec::new(); + for &(b, _) in all { + for atom in lanes.bools.support(b) { + if matches!(atom, Atom::Lane(_)) && !lane_atoms.contains(&atom) { + lane_atoms.push(atom); + } + } + } + if lane_atoms.len() < 2 { + return true; + } + let mut groups: HashMap = HashMap::new(); + let mut equiv = Vec::new(); + for &atom in &lane_atoms { + let Atom::Lane(v) = atom else { continue }; + if let Some((key, inv)) = self.canon_cmp(v) { + let next_id = groups.len(); + let group = *groups.entry(key).or_insert(next_id); + equiv.push((atom, group, inv)); + } + } + if equiv.is_empty() { + return true; + } + let groups_len = groups.len(); + lanes + .bools + .meet_with_facts(all, &equiv, groups_len, |assigned| { + self.cmp_leaf_ok(assigned) + }) + } + + fn feasible_with(&self, known: &[(Bool, bool)], extra: &[(Bool, bool)]) -> bool { + let mut conds = Vec::with_capacity(known.len() + extra.len()); + conds.extend_from_slice(known); + conds.extend_from_slice(extra); + self.feasible(&conds) + } + + /// Whether two mask values evaluate to the same boolean on every lane in + /// `known` (and both are tracked in `lanes.masks` when `lanes` is present). + fn same_mask(&self, a: Value, b: Value, known: &[(Bool, bool)]) -> bool { + if a == b { + return true; + } + let Some(lanes) = self.lanes else { + return false; + }; + let (Some(&ma), Some(&mb)) = (lanes.masks.get(&a), lanes.masks.get(&b)) else { + return false; + }; + ma == mb + || (!self.feasible_with(known, &[(ma, true), (mb, false)]) + && !self.feasible_with(known, &[(ma, false), (mb, true)])) + } + + /// Canonicalizes a pure `v_cmp_*` / `v_cmpx_*` instruction defining `v` + /// into `(canonical_key, inverted)` so equivalent or negated compares + /// share the same key. + fn canon_cmp(&self, v: Value) -> Option<(CanonKey, bool)> { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if f.dpp.is_some() || f.clamp || f.omod != 0 { + return None; + } + let rest = inst + .name() + .strip_prefix("v_cmp_") + .or_else(|| inst.name().strip_prefix("v_cmpx_"))?; + let (op, ty_str) = rest.rsplit_once('_')?; + let ty = match ty_str { + "u16" => CmpType::U16, + "i16" => CmpType::I16, + "f16" => CmpType::F16, + "u32" => CmpType::U32, + "i32" => CmpType::I32, + "f32" => CmpType::F32, + "u64" => CmpType::U64, + "i64" => CmpType::I64, + "f64" => CmpType::F64, + _ => return None, + }; + let a = self.cmp_operand(inst, f, 0, ty)?; + let b = self.cmp_operand(inst, f, 1, ty)?; + let ordered = |x: CmpOperand, y: CmpOperand| if x <= y { (x, y) } else { (y, x) }; + let (pred, inv) = match ty { + CmpType::U16 + | CmpType::I16 + | CmpType::U32 + | CmpType::I32 + | CmpType::U64 + | CmpType::I64 => match op { + "f" => (CanonPred::Const(false), false), + "t" => (CanonPred::Const(true), false), + "lt" => (CanonPred::IntLt(a, b), false), + "ge" => (CanonPred::IntLt(a, b), true), + "gt" => (CanonPred::IntLt(b, a), false), + "le" => (CanonPred::IntLt(b, a), true), + "eq" => { + let (lo, hi) = ordered(a, b); + (CanonPred::IntEq(lo, hi), false) + } + "ne" | "lg" => { + let (lo, hi) = ordered(a, b); + (CanonPred::IntEq(lo, hi), true) + } + _ => return None, + }, + CmpType::F16 | CmpType::F32 | CmpType::F64 => match op { + "f" => (CanonPred::Const(false), false), + "tru" => (CanonPred::Const(true), false), + "lt" => (CanonPred::FloatLt(a, b), false), + "nlt" => (CanonPred::FloatLt(a, b), true), + "gt" => (CanonPred::FloatLt(b, a), false), + "ngt" => (CanonPred::FloatLt(b, a), true), + "le" => (CanonPred::FloatLe(a, b), false), + "nle" => (CanonPred::FloatLe(a, b), true), + "ge" => (CanonPred::FloatLe(b, a), false), + "nge" => (CanonPred::FloatLe(b, a), true), + "eq" => { + let (lo, hi) = ordered(a, b); + (CanonPred::FloatEq(lo, hi), false) + } + "neq" => { + let (lo, hi) = ordered(a, b); + (CanonPred::FloatEq(lo, hi), true) + } + "lg" => { + let (lo, hi) = ordered(a, b); + (CanonPred::FloatLg(lo, hi), false) + } + "nlg" => { + let (lo, hi) = ordered(a, b); + (CanonPred::FloatLg(lo, hi), true) + } + "o" => { + let (lo, hi) = ordered(a, b); + (CanonPred::FloatOrd(lo, hi), false) + } + "u" => { + let (lo, hi) = ordered(a, b); + (CanonPred::FloatOrd(lo, hi), true) + } + "class" => (CanonPred::FloatClass(a, b), false), + _ => return None, + }, + }; + Some((CanonKey { ty, pred }, inv)) + } + + fn cmp_operand( + &self, + inst: &Inst, + f: &crate::gfx10::Valu, + k: usize, + ty: CmpType, + ) -> Option { + let op = *f.src.get(k)?; + let words = match ty { + CmpType::U64 | CmpType::I64 | CmpType::F64 => match op { + Operand::Vector { reg, .. } => [ + self.lane_unconditional(inst.read(Reg::V(reg))?), + self.lane_unconditional(inst.read(Reg::V(reg + 1))?), + ], + Operand::Scalar { code: NULL, .. } => [Term::Const(0), Term::Const(0)], + Operand::Scalar { code, .. } => [ + self.origin(inst.read(Reg::S(code))?), + self.origin(inst.read(Reg::S(code + 1))?), + ], + Operand::Const(c @ 128..=208) => { + let low = inline(c)?; + [Term::Const(low), Term::Const(((low as i32) >> 31) as u32)] + } + Operand::Literal(x) => [Term::Const(x), Term::Const(0)], + _ => return None, + }, + _ => { + let w = match op { + Operand::Vector { reg, .. } => self.lane_unconditional(inst.read(Reg::V(reg))?), + Operand::Const(c) if ty == CmpType::F16 && c >= 240 => return None, + _ => self.term(inst, &op)?, + }; + [w, Term::Const(0)] + } + }; + let is16 = matches!(ty, CmpType::U16 | CmpType::I16 | CmpType::F16); + Some(CmpOperand { + words, + abs: (f.abs >> k) & 1 != 0, + neg: (f.neg >> k) & 1 != 0, + opsel: is16 && ((f.opsel >> k) & 1 != 0), + sdwa: f.sdwa.map(|s| (s.src_sel[k], (s.sext >> k) & 1 != 0)), + }) + } + + /// Follows unconditional lane-preserving copies (those with no guard) + /// from `v`. + fn lane_unconditional(&self, mut v: Value) -> Term { + for _ in 0..MAX_JOINS * 2 { + let Some(site) = self.defs[v.0 as usize] else { + return Term::Value(v); + }; + if self + .lanes + .is_some_and(|l| l.guards[site.0][site.1].is_some()) + { + return Term::Value(v); + } + let Some((_, next)) = self.lane_copy(v) else { + return Term::Value(v); + }; + match next { + Term::Value(u) if u != v => v = u, + other => return other, + } + } + Term::Value(v) + } + + /// Checks whether a leaf assignment of `Atom::Lane` compares is consistent + /// with 1D integer constant bounds (e.g., `(x < 8) && !(x < 16)` is false). + fn cmp_leaf_ok(&self, assigned: &[(Atom, bool)]) -> bool { + struct Bounds { + lo: i128, + hi: i128, + neq: Vec, + } + fn entry_for( + map: &mut HashMap<(CmpType, CmpOperand), Bounds>, + ty: CmpType, + op: CmpOperand, + ) -> &mut Bounds { + let (min, max) = match ty { + CmpType::U16 => (0i128, i128::from(u16::MAX)), + CmpType::I16 => (i128::from(i16::MIN), i128::from(i16::MAX)), + CmpType::U32 => (0i128, i128::from(u32::MAX)), + CmpType::I32 => (i128::from(i32::MIN), i128::from(i32::MAX)), + CmpType::U64 => (0i128, i128::from(u64::MAX)), + CmpType::I64 => (i128::from(i64::MIN), i128::from(i64::MAX)), + _ => (0, 0), + }; + map.entry((ty, op)).or_insert(Bounds { + lo: min, + hi: max, + neq: Vec::new(), + }) + } + let mut bounds: HashMap<(CmpType, CmpOperand), Bounds> = HashMap::new(); + let int_const = |ty: CmpType, op: CmpOperand| -> Option { + if op.abs || op.neg || op.opsel || op.sdwa.is_some() { + return None; + } + let (Term::Const(w0), Term::Const(w1)) = (op.words[0], op.words[1]) else { + return None; + }; + Some(match ty { + CmpType::U16 => i128::from(w0 as u16), + CmpType::I16 => i128::from(w0 as u16 as i16), + CmpType::U32 => i128::from(w0), + CmpType::I32 => i128::from(w0 as i32), + CmpType::U64 => i128::from(u64::from(w0) | (u64::from(w1) << 32)), + CmpType::I64 => i128::from((u64::from(w0) | (u64::from(w1) << 32)) as i64), + _ => return None, + }) + }; + for &(atom, truth) in assigned { + let Atom::Lane(v) = atom else { continue }; + let Some((CanonKey { ty, pred }, inv)) = self.canon_cmp(v) else { + continue; + }; + let holds = truth ^ inv; + match pred { + CanonPred::Const(c) => { + if c != holds { + return false; + } + } + CanonPred::IntLt(a, b) => { + if a == b { + if holds { + return false; + } + continue; + } + if let (Some(ka), Some(kb)) = (int_const(ty, a), int_const(ty, b)) { + if (ka < kb) != holds { + return false; + } + continue; + } + if let Some(k) = int_const(ty, b) { + let e = entry_for(&mut bounds, ty, a); + if holds { + e.hi = e.hi.min(k - 1); + } else { + e.lo = e.lo.max(k); + } + } else if let Some(k) = int_const(ty, a) { + let e = entry_for(&mut bounds, ty, b); + if holds { + e.lo = e.lo.max(k + 1); + } else { + e.hi = e.hi.min(k); + } + } + } + CanonPred::IntEq(a, b) => { + if a == b { + if !holds { + return false; + } + continue; + } + if let (Some(ka), Some(kb)) = (int_const(ty, a), int_const(ty, b)) { + if (ka == kb) != holds { + return false; + } + continue; + } + if let Some(k) = int_const(ty, b) { + let e = entry_for(&mut bounds, ty, a); + if holds { + e.lo = e.lo.max(k); + e.hi = e.hi.min(k); + } else { + e.neq.push(k); + } + } else if let Some(k) = int_const(ty, a) { + let e = entry_for(&mut bounds, ty, b); + if holds { + e.lo = e.lo.max(k); + e.hi = e.hi.min(k); + } else { + e.neq.push(k); + } + } + } + _ => {} + } + } + bounds + .values() + .all(|b| b.lo <= b.hi && (b.lo != b.hi || !b.neq.contains(&b.lo))) + } + /// Fails unless every lane in `known` that reaches the vector /// instruction at `site` runs it: one with its EXEC bit clear there /// keeps what the registers held before. - fn runs(&self, site: Site, known: &Known) -> Result<(), &'static str> { + fn runs(&self, site: Site, known: &[(Bool, bool)]) -> Result<(), &'static str> { let Some(lanes) = self.lanes else { return Ok(()); }; let Some(&Some(guard)) = lanes.guards.get(site.0).and_then(|g| g.get(site.1)) else { return Ok(()); }; - let mut skips = known.clone(); + let mut skips = known.to_vec(); skips.extend([(lanes.reach[site.0], true), (guard, false)]); - if lanes.bools.meet(&skips) { + if self.feasible(&skips) { return Err("a per-lane descriptor written where some lanes may keep the old one"); } Ok(()) @@ -1284,7 +2052,11 @@ impl<'a> Tracer<'a> { let Some(mask) = picks.iter().flatten().map(|p| p.0).next() else { return Ok(None); }; - if picks.iter().flatten().any(|p| p.0 != mask) { + if picks + .iter() + .flatten() + .any(|p| !self.same_mask(p.0, mask, known)) + { return Err("a descriptor chosen per lane by several masks"); } for (w, p) in words.iter().zip(&picks) { @@ -1294,11 +2066,6 @@ impl<'a> Tracer<'a> { self.runs(site, known)?; } } - if joins.len() >= MAX_JOINS { - return Err("a descriptor joined too often"); - } - joins.push(usize::MAX); - // Each side holds where the lane's bit of the mask is set, or clear. let bit = self.lanes.and_then(|l| l.masks.get(&mask).copied()); let side = |set: bool| -> Vec { words @@ -1316,6 +2083,18 @@ impl<'a> Tracer<'a> { }) .collect() }; + if let Some(b) = bit { + let t_ok = self.feasible_with(known, &[(b, true)]); + let f_ok = self.feasible_with(known, &[(b, false)]); + if t_ok != f_ok { + return self.per_lane(&side(t_ok), joins, known).map(Some); + } + } + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(usize::MAX); + // Each side holds where the lane's bit of the mask is set, or clear. let args = [true, false] .into_iter() .map(|set| { @@ -1334,6 +2113,11 @@ impl<'a> Tracer<'a> { /// lane mask it reads, and the dword it is where the lane's bit is set /// (src1), then clear (src0). fn lane_picked(&self, v: Value) -> Option<(Value, Term, Term)> { + let (_, mask, set, clear) = self.lane_picked_with_reg(v)?; + Some((mask, set, clear)) + } + + fn lane_picked_with_reg(&self, v: Value) -> Option<(Reg, Value, Term, Term)> { let inst = self.def(v)?; let Fields::Valu(f) = &inst.fields else { return None; @@ -1356,7 +2140,12 @@ impl<'a> Tracer<'a> { return None; }; let mask = inst.read(Reg::S(code))?; - Some((mask, self.raw(inst, &set)?, self.raw(inst, &clear)?)) + Some(( + Reg::V(reg), + mask, + self.raw(inst, &set)?, + self.raw(inst, &clear)?, + )) } /// Per-lane words that phis of one block join, as an if/else on a @@ -1423,7 +2212,7 @@ impl<'a> Tracer<'a> { { known.push((when, taken == block)); } - let arg = if lanes.bools.meet(known) { + let arg = if self.feasible(known) { let edge: Vec = words .iter() .map(|w| match phi_of(w) { @@ -1524,7 +2313,8 @@ impl<'a> Tracer<'a> { return Err(SELECT); } let reach = (lanes.reach[b], true); - let meet = |conditions: &[(Bool, bool)]| lanes.bools.meet(conditions); + let loop_known = [reach, (remaining, true)]; + let meet = |conditions: &[(Bool, bool)]| self.feasible(conditions); let mut out = Waterfall::default(); let mut required = vec![(remaining, true)]; for (i, inst) in block.insts[..access].iter().enumerate() { @@ -1562,8 +2352,16 @@ impl<'a> Tracer<'a> { let (_, read) = self.defs[x.0 as usize]?; let same = reads.contains(&x) && read < i - && self.lane_term(Term::Value(self.first_lane_source(x)?)) - == self.lane_term(Term::Value(lane)); + && match ( + self.lane_value( + Term::Value(self.first_lane_source(x)?), + &loop_known, + ), + self.lane_value(Term::Value(lane), &loop_known), + ) { + (Ok(lhs), Ok(rhs)) => lhs == rhs, + _ => false, + }; same.then_some(x) }) .collect() @@ -1639,6 +2437,47 @@ impl<'a> Tracer<'a> { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum CmpType { + U16, + I16, + F16, + U32, + I32, + F32, + U64, + I64, + F64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +struct CmpOperand { + words: [Term; 2], + abs: bool, + neg: bool, + opsel: bool, + sdwa: Option<(u8, bool)>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum CanonPred { + Const(bool), + IntLt(CmpOperand, CmpOperand), + IntEq(CmpOperand, CmpOperand), + FloatLt(CmpOperand, CmpOperand), + FloatLe(CmpOperand, CmpOperand), + FloatEq(CmpOperand, CmpOperand), + FloatLg(CmpOperand, CmpOperand), + FloatOrd(CmpOperand, CmpOperand), + FloatClass(CmpOperand, CmpOperand), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +struct CanonKey { + ty: CmpType, + pred: CanonPred, +} + #[derive(Clone, Copy, PartialEq, Eq)] enum Moved { Const(u32), @@ -2059,6 +2898,132 @@ pub(crate) mod tests { ); } + /// A scalar load of a table in the code, at an address a VGPR sum builds + /// from `s_getpc_b64` and a uniform index, read back to SGPRs with + /// `v_readfirstlane_b32` (the console compiler's form). Assembled with + /// llvm-mc for gfx1030, wave32. + const CODE_TABLE_FIRST_LANE: &[u32] = &[ + 0xBE80_1F00, // s_getpc_b64 s[0:1] + 0x8000_FF00, + 0x0000_0DDC, // s_add_u32 s0, s0, 0xddc + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x7E00_0283, // v_mov_b32 v0, 3 + 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 + 0xD70F_6A01, + 0x0000_0101, // v_add_co_u32 v1, vcc_lo, v1, s0 + 0xD528_6A02, + 0x01A9_0001, // v_add_co_ci_u32 v2, vcc_lo, s1, 0, vcc_lo + 0x7E04_0501, // v_readfirstlane_b32 s2, v1 + 0x7E06_0502, // v_readfirstlane_b32 s3, v2 + 0xF400_0181, + 0xFA00_0000, // s_load_dword s6, s[2:3], null + S_ENDPGM, + ]; + + #[test] + fn a_first_lane_read_of_a_uniform_code_table_address_is_traced() { + let r = track_words(CODE_TABLE_FIRST_LANE, &[], HwStage::Cs); + let (_, a) = r + .scalar + .iter() + .find(|s| s.1.param == CODE) + .expect("the code table load is traced"); + // s_getpc_b64 is the first instruction: its next one is at 4. + assert_eq!(a.offset, 4 + 0xDDC); + assert!(a.dynamic.is_some(), "the index stays a computed term"); + } + + #[test] + fn a_first_lane_read_of_a_per_lane_code_table_address_is_refused_by_name() { + // Same, but the index is lane 0's own input (v0 is never set). + let words = [ + 0xBE80_1F00, // s_getpc_b64 s[0:1] + 0x8000_FF00, + 0x0000_0DDC, // s_add_u32 s0, s0, 0xddc + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 + 0xD70F_6A01, + 0x0000_0101, // v_add_co_u32 v1, vcc_lo, v1, s0 + 0xD528_6A02, + 0x01A9_0001, // v_add_co_ci_u32 v2, vcc_lo, s1, 0, vcc_lo + 0x7E04_0501, // v_readfirstlane_b32 s2, v1 + 0x7E06_0502, // v_readfirstlane_b32 s3, v2 + 0xF400_0181, + 0xFA00_0000, // s_load_dword s6, s[2:3], null + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[], HwStage::Cs, lanes(&p).as_ref()).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + // the s_load_dword, at byte 44 + offset: 44, + what: "an address read from the first lane of a per-lane value" + } + ); + } + + /// A table in the code read in a loop whose counter (v7) the exit test + /// compares with `limit`: the console compiler's form for a lookup table + /// walked at a uniform index. Assembled with llvm-mc for gfx1030, wave32. + fn code_table_loop(compare: u32) -> Vec { + vec![ + 0xBE80_1F00, // s_getpc_b64 s[0:1] + 0x8000_FF00, + 0x0000_0DDC, // s_add_u32 s0, s0, 0xddc + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x7E0E_0280, // v_mov_b32 v7, 0 + 0x3402_0E82, // loop: v_lshlrev_b32 v1, 2, v7 + 0xD70F_6A01, + 0x0000_0101, // v_add_co_u32 v1, vcc_lo, v1, s0 + 0xD528_6A02, + 0x01A9_0001, // v_add_co_ci_u32 v2, vcc_lo, s1, 0, vcc_lo + 0x7E04_0501, // v_readfirstlane_b32 s2, v1 + 0x7E06_0502, // v_readfirstlane_b32 s3, v2 + 0xF400_0181, + 0xFA00_0000, // s_load_dword s6, s[2:3], null + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x4A0E_0E81, // v_add_nc_u32 v7, 1, v7 + compare, + 0xBF87_FFF3, // s_cbranch_vccnz loop + S_ENDPGM, + ] + } + + #[test] + fn a_loop_counter_with_a_uniform_exit_indexes_a_code_table() { + // v_cmp_gt_i32 vcc_lo, 5, v7 + let r = track_words(&code_table_loop(0x7D08_0E85), &[], HwStage::Cs); + let (_, a) = r + .scalar + .iter() + .find(|s| s.1.param == CODE) + .expect("the code table load is traced"); + assert_eq!(a.offset, 4 + 0xDDC); + assert!(a.dynamic.is_some(), "the counter stays a computed term"); + } + + #[test] + fn a_loop_counter_with_a_per_lane_exit_is_refused_by_name() { + // v_cmp_gt_u32 vcc_lo, v0, v7: lanes leave at their own count. + let code: Vec = code_table_loop(0x7D88_0F00) + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[], HwStage::Cs, lanes(&p).as_ref()).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + // the s_load_dword, at byte 48 + offset: 48, + what: "an address read from the first lane of a per-lane value" + } + ); + } + /// A waterfall loop over an image descriptor each lane loads from the /// table at s0 (wave32, assembled with llvm-mc for gfx1030): lane i /// reads entry i with two `global_load_dwordx4`, the loop reads the @@ -3092,4 +4057,360 @@ pub(crate) mod tests { assert_eq!(r.waterfall.compares.len(), 2); assert_eq!(r.waterfall.reads.len(), 4); } + + pub(crate) fn joined_with_redundant_write() -> Vec { + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let at = word_at(&words, 0x887E_147E) + 1; + words.splice( + at..at, + [ + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo + 0x7E08_0218, // v_mov_b32 v4, s24 (then arm's word 0) + 0xBEFE_0312, // s_mov_b32 exec_lo, s18 + ], + ); + words + } + + /// 32-thread synthetic compute shader joining two 4-dword sampler + /// descriptors across an if/else (`lane < 16` takes entry 0, else entry 1) + /// and sampling a 2x1 texture at U=2.0. + pub(crate) fn joined_sampler_shader(redundant_write: Option) -> Vec { + let mut words = vec![ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0202, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0x0 + 0xF408_0603, + 0xFA00_0000, // s_load_dwordx4 s[24:27], s[6:7], 0x0 + 0xF408_0703, + 0xFA00_0010, // s_load_dwordx4 s[28:31], s[6:7], 0x10 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_02F4, // v_mov_b32 v2, 2.0 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0004, // s_cbranch_execz -> +4 (else flow) + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0xBE94_3D14, // s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0004, // s_cbranch_execz -> +4 (join) + 0x7E08_021C, // v_mov_b32 v4, s28 + 0x7E0A_021D, // v_mov_b32 v5, s29 + 0x7E0C_021E, // v_mov_b32 v6, s30 + 0x7E0E_021F, // v_mov_b32 v7, s31 + 0x887E_147E, // s_or_b32 exec_lo, exec_lo, s20 + ]; + if let Some(mov) = redundant_write { + words.extend([ + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo + mov, + 0xBEFE_0312, // s_mov_b32 exec_lo, s18 + ]); + } + words.extend([ + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E20_0504, // loop: v_readfirstlane_b32 s16, v4 + 0x7E22_0505, // v_readfirstlane_b32 s17, v5 + 0x7E24_0506, // v_readfirstlane_b32 s18, v6 + 0x7E26_0507, // v_readfirstlane_b32 s19, v7 + 0xD4E2_0015, + 0x0002_0810, // v_cmp_eq_u64_e64 s21, s[16:17], v[4:5] + 0xD4E2_0016, + 0x0002_0C12, // v_cmp_eq_u64_e64 s22, s[18:19], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0082_0C02, // image_sample_lz v[12:15], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFF0, // s_cbranch_execnz -> loop (-16 dwords) + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]); + words + } + + #[test] + fn joined_descriptor_redundant_partial_write() { + let r = waterfall(&joined_with_redundant_write(), false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + let Source::LanePhi { args, .. } = &image.source else { + unreachable!() + }; + let [Some(Source::LanePhi { args: flow, .. }), Some(other)] = &args[..] else { + panic!("{args:?}") + }; + assert_eq!(table_offset(&r, other), 0x20); + let [None, Some(then)] = &flow[..] else { + panic!("{flow:?}") + }; + assert_eq!(table_offset(&r, then), 0); + assert_eq!(r.waterfall.compares.len(), 4); + assert_eq!(r.waterfall.reads.len(), 8); + } + + #[test] + fn joined_descriptor_redundant_partial_write_subset_and_swapped_cmp() { + // Strict subset mask (lane < 8) writing v4 = s24. + let mut subset = joined_with_redundant_write(); + let cmp = word_at(&subset, 0x7D88_0090); + let second_cmp = cmp + + 1 + + subset[cmp + 1..] + .iter() + .position(|&w| w == 0x7D88_0090) + .unwrap(); + subset[second_cmp] = 0x7D88_0088; // v_cmp_gt_u32 vcc_lo, 8, v0 + assert!(waterfall(&subset, false).is_ok()); + + // Swapped VOP3 comparison: v_cmp_lt_u32 vcc_lo, v0, 16. + let mut swapped = WATERFALL_JOINED_WAVE32.to_vec(); + let at = word_at(&swapped, 0x887E_147E) + 1; + swapped.splice( + at..at, + [ + 0xD4C1_006A, + 0x0001_2100, // v_cmp_lt_u32 vcc_lo, v0, 16 + 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo + 0x7E08_0218, // v_mov_b32 v4, s24 + 0xBEFE_0312, // s_mov_b32 exec_lo, s18 + ], + ); + assert!(waterfall(&swapped, false).is_ok()); + + // Independent sampler control (#750): redundant v4 = s24 passes, non-identity v4 = s28 fails. + assert!(waterfall(&joined_sampler_shader(Some(0x7E08_0218)), false).is_ok()); + assert_eq!( + refusal(&joined_sampler_shader(Some(0x7E08_021C)), false), + "a per-lane descriptor written where some lanes may keep the old one" + ); + } + + #[test] + fn joined_descriptor_non_identity_or_overlapping_partial_writes_are_refused() { + // Non-identity masked write: v4 = s32 on lanes < 16 corrupts the then-arm descriptor. + let mut wrong_val = joined_with_redundant_write(); + let mov = word_at(&wrong_val, 0xBE92_3C6A) + 1; + wrong_val[mov] = 0x7E08_0220; // v_mov_b32 v4, s32 + assert_eq!( + refusal(&wrong_val, false), + "a per-lane descriptor written where some lanes may keep the old one" + ); + + // Overlapping masked write: widen mask to lane < 24 so lanes 16..23 overwrite else-arm word 0. + let mut widened = joined_with_redundant_write(); + let cmp = word_at(&widened, 0xBE92_3C6A) - 1; + widened[cmp] = 0x7D88_0098; // v_cmp_gt_u32 vcc_lo, 24, v0 + assert_eq!( + refusal(&widened, false), + "a per-lane descriptor written where some lanes may keep the old one" + ); + + // Opposite-arm non-matching write: v_cmp_le_u32 16, v0 (lanes >= 16) writing s24. + let mut flipped = WATERFALL_JOINED_WAVE32.to_vec(); + let at = word_at(&flipped, 0x887E_147E) + 1; + flipped.splice( + at..at, + [ + 0x7D86_0090, // v_cmp_le_u32 vcc_lo, 16, v0 + 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo + 0x7E08_0218, // v_mov_b32 v4, s24 + 0xBEFE_0312, // s_mov_b32 exec_lo, s18 + ], + ); + assert_eq!( + refusal(&flipped, false), + "a per-lane descriptor written where some lanes may keep the old one" + ); + } + + pub(crate) fn fetched_with_lane_preserving_transforms() -> Vec { + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + // After global_load_dwordx4 v[4:7], v[8:11] and s_waitcnt (0xBF8C_0070), + // shuffle/identity-move/extract the loaded descriptor dwords before the waterfall loop. + let at = word_at(&words, 0xBF8C_0070) + 1; + words.splice( + at..at, + [ + // v_swap_b32 v4, v5; v_swap_b32 v5, v4 (back to original order via swaps) + 0x7E08_CB05, + 0x7E0A_CB04, + // Identity bitwise/shift moves: v4 = 0 | v4, v5 = -1 & v5, v6 = v6 << 0 + 0x3808_0880, + 0x360A_0AC1, + 0x340C_0C80, + // 64-bit word extract: v_lshrrev_b64 v[20:21], 32, v[6:7] -> v20 = v7 + 0xD700_0014, + 0x0002_0CA0, + // v_mov_b32 v7, v20 + 0x7E0E_0314, + // Byte-preserving v_perm_b32 v22, v8, v9, 0x07060504 -> v22 = v8 + 0xD744_0016, + 0x03FE_1308, + 0x0706_0504, + // v_mov_b32 v8, v22 + 0x7E10_0316, + // v_alignbit_b32 v23, v8, v9, 0 -> v23 = v9 + 0xD54E_0017, + 0x0202_1308, + // v_mov_b32 v9, v23 + 0x7E12_0317, + // v_cndmask_b32 v10, v10, v10, vcc_lo (same operand on both sides) + 0x0214_150A, + ], + ); + // Adjust s_cbranch_execnz backward offset in loop by +16 dwords (-0x1a - 16 = -0x2a) — + // wait: the loop starts AFTER `at`, so its own backward offset is unchanged! + words + } + + #[test] + fn first_lane_of_lane_preserving_moves_and_extracts_is_traced() { + let r = waterfall(&fetched_with_lane_preserving_transforms(), false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + assert!(matches!(image.source, Source::Fetched { first: 0, .. })); + assert_eq!(r.waterfall.compares.len(), 4); + assert_eq!(r.waterfall.reads.len(), 8); + } + + #[test] + fn first_lane_of_non_identity_computed_vgprs_still_fails() { + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + let at = word_at(&words, 0xBF8C_0070) + 1; + // Non-identity computed VGPR: v_or_b32 v4, 1, v4 + words.insert(at, 0x3808_0881); + assert_eq!( + refusal(&words, false), + "a descriptor read from the first lane of computed VGPRs" + ); + + // Non-dword 64-bit shift: v_lshrrev_b64 v[20:21], 16, v[6:7]; v_mov_b32 v4, v20 + let mut bad_shift = WATERFALL_FETCHED_WAVE32.to_vec(); + bad_shift.splice( + at..at, + [ + 0xD700_0014, + 0x0002_0C90, // shift by 16 + 0x7E08_0314, // v4 = v20 + ], + ); + assert_eq!( + refusal(&bad_shift, false), + "a descriptor read from the first lane of computed VGPRs" + ); + + // Non-identity permute selector: 0x07060405 into v4 + let mut bad_perm = WATERFALL_FETCHED_WAVE32.to_vec(); + bad_perm.splice( + at..at, + [ + 0xD744_0016, + 0x03FE_1308, + 0x0706_0405, + 0x7E08_0316, // v4 = v22 + ], + ); + assert_eq!( + refusal(&bad_perm, false), + "a descriptor read from the first lane of computed VGPRs" + ); + + // Guarded v_swap_b32 under partial EXEC (not redundant since v4 != v5) must fail. + let mut guarded_swap = WATERFALL_FETCHED_WAVE32.to_vec(); + guarded_swap.splice( + at..at, + [ + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBE92_3C6A, // s_and_saveexec_b32 s18, vcc_lo + 0x7E08_CB05, // v_swap_b32 v4, v5 + 0xBEFE_0312, // s_mov_b32 exec_lo, s18 + ], + ); + assert_eq!( + refusal(&guarded_swap, false), + "a per-lane descriptor written where some lanes may keep the old one" + ); + } + + #[test] + fn lane_select_accepts_equivalent_masks_and_refuses_different_ones() { + // Recompute an equivalent mask in s18 for the high word of WATERFALL_PICKED_WAVE32 + // and verify it still traces, while a narrower mask (lane < 8) is refused. + let mut eq_mask = WATERFALL_PICKED_WAVE32.to_vec(); + let at = word_at(&eq_mask, 0x0216_1627); + eq_mask.splice( + at..at, + [ + 0xD4C1_0012, + 0x0001_2100, // v_cmp_lt_u32_e64 s18, v0, 16 + ], + ); + let cnd = at + 2; + // Replace v_cndmask_b32 v11, s39, v11, vcc_lo with VOP3 using s18. + eq_mask[cnd] = 0xD501_000B; + eq_mask.insert(cnd + 1, (18 << 18) | ((256 + 11) << 9) | 39); + assert!(waterfall(&eq_mask, false).is_ok()); + + let mut diff_mask = eq_mask; + diff_mask[at + 1] = 0x0001_1100; // v_cmp_lt_u32_e64 s18, v0, 8 + assert_eq!( + refusal(&diff_mask, false), + "a descriptor chosen per lane by several masks" + ); + } + + #[test] + fn v_cndmask_literal_all_ones_mask_is_refused_in_wave64() { + // v_cndmask_b32_e64 v4, v20, v4, 0xFFFF_FFFF: in wave32 all 32 lanes + // take v4 (set), whereas in wave64 the literal zero-extends to + // 0x0000_0000_FFFF_FFFF so lanes 32..63 take v20 (clear). + let lit_mask = [ + 0xD501_0004, + (255 << 18) | ((256 + 4) << 9) | (256 + 20), + u32::MAX, + ]; + let mut w32 = WATERFALL_FETCHED_WAVE32.to_vec(); + let at32 = word_at(&w32, 0xBF8C_0070) + 1; + w32.splice(at32..at32, lit_mask); + assert!(waterfall(&w32, false).is_ok()); + + let mut w64_lit = WATERFALL_FETCHED_WAVE64.to_vec(); + let at64 = word_at(&w64_lit, 0xBF8C_0070) + 1; + w64_lit.splice(at64..at64, lit_mask); + assert_eq!( + refusal(&w64_lit, true), + "a descriptor read from the first lane of computed VGPRs" + ); + + // Inline -1 (Const(193)) sign-extends to all 64 lanes in wave64. + let mut w64_inline = WATERFALL_FETCHED_WAVE64.to_vec(); + w64_inline.splice( + at64..at64, + [0xD501_0004, (193 << 18) | ((256 + 4) << 9) | (256 + 20)], + ); + assert!(waterfall(&w64_inline, true).is_ok()); + } } diff --git a/crates/victory-shader/src/resource/uniform.rs b/crates/victory-shader/src/resource/uniform.rs new file mode 100644 index 0000000..a531c8b --- /dev/null +++ b/crates/victory-shader/src/resource/uniform.rs @@ -0,0 +1,289 @@ +//! Wave uniformity through phis: a loop counter or a value joined by a +//! uniform branch holds the same value in every lane that runs, so an +//! address computed from it and read back with `v_readfirstlane_b32` is the +//! address of every lane (the console compiler's table loops). +//! +//! A phi is uniform when all its arguments are, and no branch whose lanes +//! may part ways can send lanes to it along different edges: not a join of +//! the two arms of such a branch, nor a block of a loop it can leave or +//! stay in lane by lane. The set of uniform phis is the greatest fixed +//! point (a loop counter's own increment feeds its exit test). + +use super::{MAX_ROUNDS, Tracer}; +use crate::ir::{EXEC, Exit, Inst, Reg, VCC, Value, reverse_postorder}; + +/// Operations that combine lane masks bit by bit (or copy one). +const MASK_OPS: &[&str] = &[ + "s_and_b32", + "s_or_b32", + "s_xor_b32", + "s_andn2_b32", + "s_orn2_b32", + "s_nand_b32", + "s_nor_b32", + "s_xnor_b32", + "s_and_b64", + "s_or_b64", + "s_xor_b64", + "s_andn2_b64", + "s_orn2_b64", + "s_mov_b32", + "s_mov_b64", + "s_not_b32", + "s_not_b64", +]; + +/// Per block: the blocks a lane-divergent branch there taints. +pub(super) type Regions = Vec>>; + +fn is_exec(reg: Reg) -> bool { + matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) +} + +impl Tracer<'_> { + /// Whether the phi `v` is the same in every lane that reads it. + pub(super) fn phi_uniform(&self, v: Value) -> bool { + if self.lanes.is_none() { + return false; + } + if self.phi_ok.borrow().is_none() { + self.settle_phis(); + } + self.phi_ok + .borrow() + .as_ref() + .is_some_and(|ok| ok[v.0 as usize]) + } + + /// Greatest fixed point: every phi uniform until an argument or a + /// divergent branch says otherwise. + fn settle_phis(&self) { + let mut ok: Vec = self.phis.iter().map(Option::is_some).collect(); + *self.phi_ok.borrow_mut() = Some(ok.clone()); + let regions = self.regions(); + let mut settled = false; + for _ in 0..MAX_ROUNDS { + self.uniform_memo.borrow_mut().fill(None); + let mut tainted = vec![false; self.p.blocks.len()]; + for (b, region) in regions.iter().enumerate() { + if let Some(region) = region + && !self.branch_uniform(b) + { + for &x in region { + tainted[x] = true; + } + } + } + let mut changed = false; + for (b, block) in self.p.blocks.iter().enumerate() { + for phi in &block.phis { + let i = phi.value.0 as usize; + if ok[i] && (tainted[b] || !phi.args.iter().all(|&a| self.uniform(a))) { + ok[i] = false; + changed = true; + } + } + } + *self.phi_ok.borrow_mut() = Some(ok.clone()); + if !changed { + settled = true; + break; + } + } + if !settled { + *self.phi_ok.borrow_mut() = Some(vec![false; ok.len()]); + } + self.uniform_memo.borrow_mut().fill(None); + } + + /// Whether every lane that reaches the closing branch of block `b` + /// takes it the same way. + fn branch_uniform(&self, b: usize) -> bool { + let Some(inst) = self.p.blocks[b].insts.last() else { + return false; + }; + match inst.name() { + "s_cbranch_execz" | "s_cbranch_execnz" => true, + "s_cbranch_scc0" | "s_cbranch_scc1" => { + inst.read(Reg::Scc).is_some_and(|v| self.uniform(v)) + } + "s_cbranch_vccz" | "s_cbranch_vccnz" => { + let mut vcc = inst + .reads + .iter() + .filter(|(r, _)| matches!(r, Reg::S(c) if (VCC..VCC + 2).contains(c))) + .peekable(); + vcc.peek().is_some() && vcc.all(|&(_, v)| self.mask_uniform(v)) + } + _ => false, + } + } + + /// Whether a lane mask holds the same bit in every lane it covers: a + /// comparison of uniform values, combined with EXEC and other such masks. + fn mask_uniform(&self, v: Value) -> bool { + let Some(inst) = self.def(v) else { + return false; + }; + let name = inst.name(); + if name.starts_with("v_cmp") && !name.starts_with("v_cmpx") { + return self.valu_reads_uniform(inst, false); + } + MASK_OPS.contains(&name) + && inst.reads.iter().all(|&(reg, x)| { + is_exec(reg) || (reg != Reg::Scc && (self.mask_uniform(x) || self.uniform(x))) + }) + } + + /// Whether every register a VALU instruction reads is uniform, but EXEC + /// and, unless `guarded`, the old value of the VGPRs it writes (which + /// only the lanes it skips keep). + pub(super) fn valu_reads_uniform(&self, inst: &Inst, guarded: bool) -> bool { + inst.reads.iter().all(|&(reg, x)| { + is_exec(reg) + || (!guarded && matches!(reg, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == reg)) + || self.uniform(x) + }) + } + + /// Whether lanes run the instruction defining `v` under a condition + /// beyond reaching it. + pub(super) fn guarded(&self, v: Value) -> bool { + match (self.lanes, self.defs[v.0 as usize]) { + (Some(st), Some((b, i))) => st.guards[b][i].is_some(), + _ => true, + } + } + + /// The blocks tainted by the branch closing each block, were it divergent. + fn regions(&self) -> &Regions { + self.regions.get_or_init(|| { + let blocks = &self.p.blocks; + let n = blocks.len(); + let mut fwd = vec![false; n]; + for b in reverse_postorder(blocks) { + fwd[b] = true; + } + let succs: Vec> = blocks + .iter() + .map(|b| match b.exit { + Exit::Jump(t) => vec![t], + Exit::Branch { taken, not_taken } => vec![taken, not_taken], + Exit::End => vec![n], + Exit::Indirect => Vec::new(), + }) + .collect(); + let (_, ipdom) = compute_postdoms(n, &succs, &fwd); + let walk = |from: usize, stop: usize, next: &dyn Fn(usize) -> Vec| { + let mut seen = vec![false; n]; + let mut stack = vec![from]; + while let Some(x) = stack.pop() { + if x >= n || seen[x] { + continue; + } + seen[x] = true; + if x != stop { + stack.extend(next(x)); + } + } + seen + }; + let forward = |x: usize| succs[x].clone(); + let backward = |x: usize| blocks[x].preds.clone(); + (0..n) + .map(|b| { + let Exit::Branch { taken, not_taken } = blocks[b].exit else { + return None; + }; + if !fwd[b] || taken == not_taken { + return None; + } + let stop = ipdom[b]; + let (r1, r2) = (walk(taken, stop, &forward), walk(not_taken, stop, &forward)); + // Its loop: the blocks it reaches that reach it back. + let (d1, d2) = ( + walk(taken, usize::MAX, &forward), + walk(not_taken, usize::MAX, &forward), + ); + let up = walk(b, usize::MAX, &backward); + Some( + (0..n) + .filter(|&x| (r1[x] && r2[x]) || ((d1[x] || d2[x]) && up[x])) + .collect(), + ) + }) + .collect() + }) + } +} + +/// Immediate post-dominator per block (or virtual exit `n`) using Cooper-Harvey-Kennedy. +/// Unreachable or never-exiting blocks have `rev_idx == usize::MAX`. +fn compute_postdoms(n: usize, succs: &[Vec], fwd: &[bool]) -> (Vec, Vec) { + let mut rev_succs = vec![Vec::new(); n + 1]; + for b in 0..n { + if !fwd[b] { + continue; + } + for &s in &succs[b] { + rev_succs[s].push(b); + } + } + let mut post = Vec::with_capacity(n + 1); + let mut seen = vec![false; n + 1]; + let mut stack = vec![(n, 0usize)]; + seen[n] = true; + while let Some((node, idx)) = stack.last_mut() { + let u = *node; + if *idx < rev_succs[u].len() { + let v = rev_succs[u][*idx]; + *idx += 1; + if !seen[v] { + seen[v] = true; + stack.push((v, 0)); + } + } else { + post.push(u); + stack.pop(); + } + } + post.reverse(); + let mut rev_idx = vec![usize::MAX; n + 1]; + for (idx, &b) in post.iter().enumerate() { + rev_idx[b] = idx; + } + let mut ipdom = vec![usize::MAX; n + 1]; + ipdom[n] = n; + let intersect = |mut a: usize, mut b: usize, ipdom: &[usize]| -> usize { + while a != b { + while rev_idx[a] > rev_idx[b] { + a = ipdom[a]; + } + while rev_idx[b] > rev_idx[a] { + b = ipdom[b]; + } + } + a + }; + let mut changed = true; + while changed { + changed = false; + for &b in &post[1..] { + let mut new = usize::MAX; + for &s in &succs[b] { + if ipdom[s] != usize::MAX { + new = if new == usize::MAX { + s + } else { + intersect(s, new, &ipdom) + }; + } + } + if new != usize::MAX && ipdom[b] != new { + ipdom[b] = new; + changed = true; + } + } + } + (rev_idx, ipdom) +} diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index 962909d..37e4290 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -255,6 +255,107 @@ impl Bools { }) } + /// The `Bool` representing `atom` if it exists in this table. + pub(crate) fn var_bool(&self, atom: Atom) -> Option { + let &v = self.ids.get(&atom)?; + self.unique.get(&(v, Bool::FALSE, Bool::TRUE)).copied() + } + + /// Whether some lane can satisfy every `(b, holds)` of `all` at once, + /// enforcing equivalence groups over atoms (`(atom, group, inverted)`) + /// and checking `leaf_ok` on any surviving leaf assignment. + pub(crate) fn meet_with_facts( + &self, + all: &[(Bool, bool)], + equiv: &[(Atom, usize, bool)], + groups_len: usize, + leaf_ok: impl Fn(&[(Atom, bool)]) -> bool, + ) -> bool { + let mut var_equiv = Map::default(); + for &(atom, group, inv) in equiv { + if let Some(&v) = self.ids.get(&atom) { + var_equiv.insert(v, (group, inv)); + } + } + let mut budget = MAX_MEET; + let mut groups = vec![None; groups_len]; + let mut assigned = Vec::new(); + self.meet_facts_in( + all.to_vec(), + &mut budget, + &var_equiv, + &mut groups, + &mut assigned, + &leaf_ok, + ) + } + + fn meet_facts_in bool>( + &self, + mut all: Vec<(Bool, bool)>, + budget: &mut usize, + var_equiv: &Map, + groups: &mut [Option], + assigned: &mut Vec<(Atom, bool)>, + leaf_ok: &F, + ) -> bool { + let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE }; + if all.iter().any(fails) { + return false; + } + all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE); + if *budget == 0 { + return true; + } + if all.is_empty() { + return leaf_ok(assigned); + } + *budget -= 1; + let top = |b: Bool| self.nodes[b.0 as usize].0; + let v = all.iter().map(|&(b, _)| top(b)).min().expect("not empty"); + let atom = self.atoms[v as usize]; + let track_atom = matches!(atom, Atom::Lane(_)); + + let values = match var_equiv.get(&v).copied() { + Some((g, inv)) => match groups[g] { + Some(gval) => [Some(gval ^ inv), None], + None => [Some(false), Some(true)], + }, + None => [Some(false), Some(true)], + }; + + for value in values.into_iter().flatten() { + let set_group = match var_equiv.get(&v).copied() { + Some((g, inv)) if groups[g].is_none() => { + groups[g] = Some(value ^ inv); + Some(g) + } + _ => None, + }; + let next = all + .iter() + .map(|&(b, holds)| { + let (lo, hi) = self.split(b, v); + (if value { hi } else { lo }, holds) + }) + .collect(); + if track_atom { + assigned.push((atom, value)); + } + let ok = self.meet_facts_in(next, budget, var_equiv, groups, assigned, leaf_ok); + if track_atom { + assigned.pop(); + } + if let Some(g) = set_group { + groups[g] = None; + } + if ok { + return true; + } + } + false + } + fn implies(&mut self, a: Bool, b: Bool) -> bool { let nb = self.not(b); self.and(a, nb) == Bool::FALSE @@ -314,6 +415,162 @@ impl Bools { } } +/// Non-mutating overlay over [`Bools`] for building path conditions in +/// lowering without mutating [`Structured`]. Caps extra nodes and falls back +/// to `Bool::TRUE` (conservatively reachable) on overflow. +pub(crate) struct BoolSet<'a> { + base: &'a Bools, + extra: Vec<(u32, Bool, Bool)>, + unique: Map<(u32, Bool, Bool), Bool>, + memo: Map<(Bool, Bool, Bool), Bool>, + forget_memo: Map<(Bool, usize), Bool>, + overflow: bool, +} + +const MAX_OVERLAY_NODES: usize = 1 << 16; + +impl<'a> BoolSet<'a> { + pub(crate) fn new(base: &'a Bools) -> Self { + BoolSet { + base, + extra: Vec::new(), + unique: Map::default(), + memo: Map::default(), + forget_memo: Map::default(), + overflow: false, + } + } + + fn node(&self, b: Bool) -> (u32, Bool, Bool) { + let base_len = self.base.nodes.len(); + let idx = b.0 as usize; + if idx < base_len { + self.base.nodes[idx] + } else { + self.extra[idx - base_len] + } + } + + fn mk(&mut self, v: u32, lo: Bool, hi: Bool) -> Bool { + if self.overflow { + return Bool::TRUE; + } + if lo == hi { + return lo; + } + let base_len = self.base.nodes.len(); + if (lo.0 as usize) < base_len + && (hi.0 as usize) < base_len + && let Some(&b) = self.base.unique.get(&(v, lo, hi)) + { + return b; + } + if let Some(&b) = self.unique.get(&(v, lo, hi)) { + return b; + } + if self.extra.len() >= MAX_OVERLAY_NODES { + self.overflow = true; + return Bool::TRUE; + } + let b = Bool((base_len + self.extra.len()) as u32); + self.extra.push((v, lo, hi)); + self.unique.insert((v, lo, hi), b); + b + } + + fn split(&self, b: Bool, v: u32) -> (Bool, Bool) { + match self.node(b) { + (bv, lo, hi) if bv == v => (lo, hi), + _ => (b, b), + } + } + + fn ite(&mut self, f: Bool, g: Bool, h: Bool) -> Bool { + if self.overflow { + return Bool::TRUE; + } + if f == Bool::TRUE || g == h { + return g; + } + if f == Bool::FALSE { + return h; + } + if (g, h) == (Bool::TRUE, Bool::FALSE) { + return f; + } + if let Some(&r) = self.memo.get(&(f, g, h)) { + return r; + } + let top = |b: Bool| self.node(b).0; + let v = top(f).min(top(g)).min(top(h)); + let ((f0, f1), (g0, g1), (h0, h1)) = (self.split(f, v), self.split(g, v), self.split(h, v)); + let lo = self.ite(f0, g0, h0); + let hi = self.ite(f1, g1, h1); + let r = self.mk(v, lo, hi); + self.memo.insert((f, g, h), r); + r + } + + pub(crate) fn and(&mut self, a: Bool, b: Bool) -> Bool { + self.ite(a, b, Bool::FALSE) + } + + pub(crate) fn or(&mut self, a: Bool, b: Bool) -> Bool { + self.ite(a, Bool::TRUE, b) + } + + pub(crate) fn not(&mut self, a: Bool) -> Bool { + match a { + Bool::FALSE if !self.overflow => Bool::TRUE, + Bool::TRUE if !self.overflow => Bool::FALSE, + _ => self.ite(a, Bool::FALSE, Bool::TRUE), + } + } + + /// Existentially quantifies atoms born at `from` or later (loop back edges). + pub(crate) fn forget(&mut self, b: Bool, from: usize) -> Bool { + if self.overflow { + return Bool::TRUE; + } + let (v, lo, hi) = self.node(b); + if v == TERMINAL { + return b; + } + if let Some(&r) = self.forget_memo.get(&(b, from)) { + return r; + } + let lo = self.forget(lo, from); + let hi = self.forget(hi, from); + let r = if self.base.born[v as usize] >= from { + self.or(lo, hi) + } else { + self.mk(v, lo, hi) + }; + self.forget_memo.insert((b, from), r); + r + } + + /// Condition under which a lane takes edge `q -> b`. + pub(crate) fn edge(&mut self, st: &Structured, q: usize, b: usize) -> Bool { + let mut c = st.reach[q]; + if let LaneExit::Branch { + when, + taken, + not_taken, + } = st.exits[q] + && taken != not_taken + { + let branch = if b == taken { when } else { self.not(when) }; + c = self.and(c, branch); + } + c + } + + pub(crate) fn sat(&mut self, a: Bool, b: Bool) -> bool { + self.overflow || self.and(a, b) != Bool::FALSE + } +} + /// How a lane leaves a block. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LaneExit { @@ -345,6 +602,9 @@ pub struct Structured { pub reach: Vec, /// The lane's bit of each lane-mask value, by its low dword's value. pub masks: HashMap, + /// Lane masks not derived from EXEC or VALU results (constants, opaque + /// values, uniform selects) resolved at uses such as `v_cndmask_b32`. + pub other: HashMap, /// Exact Wave64 pairs for checking masks at their uses. paired_masks: Map, /// Wave64 masks: low dword's value by the high dword's. @@ -626,6 +886,7 @@ impl<'a> Lanes<'a> { } Ok(Structured { masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), + other: self.other.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), highs: self .masks .keys()