victory-gta6: this fork's changes on top of VIctory main (ffe310e)
World rendering, lighting, frame-rate and memory work for Grand Theft Auto VI (Xbox Series X profile) on one Windows PC with an NVIDIA RTX 4070. The README describes the state, the changes and the credits. Based on VIctory by Marvisak and contributors (GPL-3.0-or-later); XCL by ivall and contributors was used as a reference. No game files are included. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
ffe310eb20
commit
578d459c34
61 files changed
+32259
-1274
No files matched your search
@@ -44,6 +44,7 @@ impl SigElement {
|
||||
18 => 68,
|
||||
19 => 67,
|
||||
20 => 69,
|
||||
28 => 23, // barycentrics
|
||||
30 => 25, // cull primitive
|
||||
_ => 0,
|
||||
}
|
||||
@@ -114,10 +115,27 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The most a mesh shader's outputs may take, in bytes (D3D12).
|
||||
pub(crate) const MESH_OUTPUT_LIMIT: u64 = 32 * 1024;
|
||||
|
||||
/// A mesh shader's output size as the DXIL validator measures it against
|
||||
/// [`MESH_OUTPUT_LIMIT`]: 4 bytes per component of every vertex element
|
||||
/// and primitive element, times the maxima rounded up to multiples of 32.
|
||||
pub(crate) fn mesh_output_bytes(
|
||||
vertex: &[SigElement],
|
||||
primitive: &[SigElement],
|
||||
max_vertices: u32,
|
||||
max_primitives: u32,
|
||||
) -> u64 {
|
||||
let scalars = |els: &[SigElement]| els.iter().map(|e| u64::from(e.cols)).sum::<u64>();
|
||||
let align = |n: u32| u64::from(n).next_multiple_of(32);
|
||||
4 * (scalars(vertex) * align(max_vertices) + scalars(primitive) * align(max_primitives))
|
||||
}
|
||||
|
||||
/// A resource bound by register, as `PSV0` lists it.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Binding {
|
||||
/// PSV resource type: 1 sampler, 2 CBV.
|
||||
/// PSV resource type: 1 sampler, 2 CBV, 4 raw SRV, 7 raw UAV.
|
||||
pub kind: u32,
|
||||
pub space: u32,
|
||||
pub register: u32,
|
||||
@@ -126,7 +144,7 @@ pub(crate) struct Binding {
|
||||
}
|
||||
|
||||
pub(crate) struct Psv<'a> {
|
||||
/// PSV shader kind: 0 pixel, 1 vertex, 5 compute.
|
||||
/// PSV shader kind: 0 pixel, 1 vertex, 2 geometry, 5 compute.
|
||||
pub stage: u8,
|
||||
/// Vertex: writes `SV_Position`. Pixel: writes depth.
|
||||
pub flag: bool,
|
||||
@@ -136,6 +154,9 @@ pub(crate) struct Psv<'a> {
|
||||
pub prims: &'a [SigElement],
|
||||
/// Mesh: its state and the group-shared bytes it declares.
|
||||
pub mesh: Option<(super::shader::Mesh, u32)>,
|
||||
/// Geometry (triangles in, triangle strips out on stream 0): its
|
||||
/// maximum vertex count. `flag`: writes `SV_Position`.
|
||||
pub geometry: Option<u32>,
|
||||
pub bindings: &'a [Binding],
|
||||
/// Compute: thread-group size and required wave size.
|
||||
pub threads: [u32; 3],
|
||||
@@ -189,6 +210,15 @@ pub(crate) fn psv(p: &Psv) -> Vec<u8> {
|
||||
info[27] = mesh.topology;
|
||||
info[30] = p.prims.len() as u8;
|
||||
}
|
||||
if let Some(max_vertices) = p.geometry {
|
||||
// Input primitive (3: triangles), output topology (5: triangle
|
||||
// strips), stream mask, position written; the vertex maximum.
|
||||
info[0..4].copy_from_slice(&3u32.to_le_bytes());
|
||||
info[4..8].copy_from_slice(&5u32.to_le_bytes());
|
||||
info[8..12].copy_from_slice(&1u32.to_le_bytes());
|
||||
info[12] = u8::from(p.flag);
|
||||
info[26..28].copy_from_slice(&(max_vertices as u16).to_le_bytes());
|
||||
}
|
||||
out.extend(info);
|
||||
u32s(&mut out, &[p.bindings.len() as u32]);
|
||||
if !p.bindings.is_empty() {
|
||||
|
||||
@@ -68,6 +68,16 @@ impl Host {
|
||||
let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1");
|
||||
// SAFETY: plain D3D12/DXGI calls with valid out pointers.
|
||||
unsafe {
|
||||
// `VICTORY_D3D12_DEBUG`: the debug layer, whose messages a
|
||||
// refused pipeline's error then carries.
|
||||
if std::env::var_os("VICTORY_D3D12_DEBUG").is_some() {
|
||||
let mut debug: Option<ID3D12Debug> = None;
|
||||
if D3D12GetDebugInterface(&mut debug).is_ok()
|
||||
&& let Some(debug) = debug
|
||||
{
|
||||
debug.EnableDebugLayer();
|
||||
}
|
||||
}
|
||||
let mut device: Option<ID3D12Device> = None;
|
||||
if warp {
|
||||
let factory: IDXGIFactory4 =
|
||||
@@ -132,21 +142,23 @@ impl Host {
|
||||
ShaderVisibility: vis,
|
||||
})
|
||||
.collect();
|
||||
let mut views: Vec<(u8, bool)> = stages
|
||||
// By slot, then kind: 0 CBV, 1 SRV, 2 UAV.
|
||||
let mut views: Vec<(u8, u8)> = stages
|
||||
.iter()
|
||||
.flat_map(|(s, _)| {
|
||||
let cbvs = s.root_cbvs.iter().map(|&r| (r, false));
|
||||
cbvs.chain(s.root_srvs.iter().map(|&r| (r, true)))
|
||||
let cbvs = s.root_cbvs.iter().map(|&r| (r, 0));
|
||||
let srvs = s.root_srvs.iter().map(|&r| (r, 1));
|
||||
cbvs.chain(srvs).chain(s.root_uavs.iter().map(|&r| (r, 2)))
|
||||
})
|
||||
.collect();
|
||||
views.sort_unstable();
|
||||
views.dedup();
|
||||
for (slot, srv) in views {
|
||||
for (slot, kind) in views {
|
||||
params.push(D3D12_ROOT_PARAMETER1 {
|
||||
ParameterType: if srv {
|
||||
D3D12_ROOT_PARAMETER_TYPE_SRV
|
||||
} else {
|
||||
D3D12_ROOT_PARAMETER_TYPE_CBV
|
||||
ParameterType: match kind {
|
||||
1 => D3D12_ROOT_PARAMETER_TYPE_SRV,
|
||||
2 => D3D12_ROOT_PARAMETER_TYPE_UAV,
|
||||
_ => D3D12_ROOT_PARAMETER_TYPE_CBV,
|
||||
},
|
||||
Anonymous: D3D12_ROOT_PARAMETER1_0 {
|
||||
Descriptor: D3D12_ROOT_DESCRIPTOR1 {
|
||||
@@ -233,7 +245,34 @@ impl Host {
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: the description points at live data.
|
||||
unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(err)
|
||||
unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(|e| self.explained(e))
|
||||
}
|
||||
|
||||
/// The error with the debug layer's messages since the last call, if
|
||||
/// the layer is on (`VICTORY_D3D12_DEBUG`).
|
||||
fn explained(&self, e: windows::core::Error) -> String {
|
||||
let mut text = err(e);
|
||||
let Ok(queue) = self.device.cast::<ID3D12InfoQueue>() else {
|
||||
return text;
|
||||
};
|
||||
// SAFETY: each message is read into a buffer of the size the queue
|
||||
// asks for, aligned for the message header.
|
||||
unsafe {
|
||||
for i in 0..queue.GetNumStoredMessages() {
|
||||
let mut len = 0usize;
|
||||
let _ = queue.GetMessage(i, None, &mut len);
|
||||
let mut buffer = vec![0u64; len.div_ceil(8)];
|
||||
let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
|
||||
if queue.GetMessage(i, Some(message), &mut len).is_ok() {
|
||||
let m = &*message;
|
||||
let bytes = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength.saturating_sub(1));
|
||||
text.push_str(" | ");
|
||||
text.push_str(&String::from_utf8_lossy(bytes));
|
||||
}
|
||||
}
|
||||
queue.ClearStoredMessages();
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// A graphics pipeline from a vertex and a pixel shader, with float or
|
||||
@@ -255,6 +294,18 @@ impl Host {
|
||||
root: &ID3D12RootSignature,
|
||||
vs: &[u8],
|
||||
ps: &[u8],
|
||||
) -> Result<ID3D12PipelineState, String> {
|
||||
self.pipeline_with_gs(root, vs, None, ps)
|
||||
}
|
||||
|
||||
/// As [`Host::pipeline_with`], with a geometry shader between the two
|
||||
/// (the rectangle stage, `rect_list_gs`).
|
||||
pub fn pipeline_with_gs(
|
||||
&self,
|
||||
root: &ID3D12RootSignature,
|
||||
vs: &[u8],
|
||||
gs: Option<&[u8]>,
|
||||
ps: &[u8],
|
||||
) -> Result<ID3D12PipelineState, String> {
|
||||
let inputs = sig(vs, FourCC::ISG1)?;
|
||||
let names: Vec<CString> = inputs
|
||||
@@ -287,6 +338,10 @@ impl Host {
|
||||
pShaderBytecode: ps.as_ptr().cast(),
|
||||
BytecodeLength: ps.len(),
|
||||
},
|
||||
GS: gs.map_or(D3D12_SHADER_BYTECODE::default(), |gs| D3D12_SHADER_BYTECODE {
|
||||
pShaderBytecode: gs.as_ptr().cast(),
|
||||
BytecodeLength: gs.len(),
|
||||
}),
|
||||
SampleMask: u32::MAX,
|
||||
RasterizerState: D3D12_RASTERIZER_DESC {
|
||||
FillMode: D3D12_FILL_MODE_SOLID,
|
||||
@@ -528,6 +583,8 @@ fn stub(pixel: bool, outputs: Vec<SigElement>) -> HostShader {
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
root_indexed_views: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,557 @@
|
||||
//! The console's ray-tracing node test, `image_bvh_intersect_ray` and
|
||||
//! `image_bvh64_intersect_ray`, as inline DXIL: the host has no instruction
|
||||
//! that tests one ray against one node of the title's own structures.
|
||||
//!
|
||||
//! [`crate::bvh`] says what the instruction computes and is the reference:
|
||||
//! the code made here does the same float operations in the same order
|
||||
//! (DXIL float operations carry no fast-math flags, so the host may not
|
||||
//! reorder or fuse them), and the tests in `intersect_tests.rs` run it on
|
||||
//! the card against the reference.
|
||||
//!
|
||||
//! The title's nodes are in title memory, named by address: they are read
|
||||
//! through the host's copies of title memory ([`Lower::memory`]), one look
|
||||
//! in its directory per node (two for a 128-byte box node).
|
||||
//!
|
||||
//! Shape of the code, under the instruction's lane guard:
|
||||
//!
|
||||
//! ```text
|
||||
//! kind = pointer & 7
|
||||
//! box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4);
|
||||
//! four slab tests; the sorting network
|
||||
//! triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test
|
||||
//! other (6, 7): a triangle miss
|
||||
//! ```
|
||||
//!
|
||||
//! Each lane reads only the dwords its node's kind needs: 28 for a 32-bit
|
||||
//! box node, 16 for a 16-bit one, 10 for a triangle.
|
||||
|
||||
use super::{Attr, Bin, Fields, Inst, Lower, Operand, Reg, Term, V, Why, flags, pred};
|
||||
use crate::bvh;
|
||||
use crate::resource::BvhNodes;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The tests' stand-in for title memory ([`Lower::bvh_memory`]): a
|
||||
/// heap slot holding a raw buffer, and the title address of its first
|
||||
/// byte. (The card tests have no host to keep copies of title memory
|
||||
/// and their directory.)
|
||||
pub(in crate::emit) static TEST_MEMORY: std::cell::Cell<Option<(u32, u64)>> =
|
||||
const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// Where the instruction's node is.
|
||||
#[derive(Clone, Copy)]
|
||||
enum NodeAt {
|
||||
/// At this byte of a raw buffer of the host.
|
||||
Buffer { handle: V, byte: V },
|
||||
/// In title memory: the raw view of the host copy holding the node's
|
||||
/// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]),
|
||||
/// and the node's address, for the second half of a 128-byte node.
|
||||
Memory { handle: V, byte: V, low: V, high: V },
|
||||
}
|
||||
|
||||
/// The ray operands, as floats.
|
||||
struct Ray {
|
||||
extent: V,
|
||||
origin: [V; 3],
|
||||
direction: [V; 3],
|
||||
inverse: [V; 3],
|
||||
}
|
||||
|
||||
impl<'a> Lower<'a> {
|
||||
/// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`.
|
||||
pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
|
||||
let Fields::Image {
|
||||
data,
|
||||
addr,
|
||||
rsrc,
|
||||
dmask,
|
||||
a16,
|
||||
d16,
|
||||
tfe,
|
||||
lwe,
|
||||
..
|
||||
} = &inst.fields
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
if *a16 || *d16 || *tfe || *lwe || *dmask != 0xf {
|
||||
return Err("a ray-tracing node test with 16-bit operands or a partial result");
|
||||
}
|
||||
let wide = inst.name() == "image_bvh64_intersect_ray";
|
||||
// Operand VGPRs in order: the node pointer (two dwords in the
|
||||
// 64-bit form), the ray's extent, origin, direction and inverse
|
||||
// direction.
|
||||
let mut regs = Vec::new();
|
||||
for a in addr {
|
||||
if let Operand::Vector { reg, dwords } = *a {
|
||||
regs.extend((0..dwords).map(|k| reg + k));
|
||||
}
|
||||
}
|
||||
if regs.len() != if wide { 12 } else { 11 } {
|
||||
return Err("a ray-tracing node test's operands");
|
||||
}
|
||||
let Operand::Vector { reg: dst, .. } = *data else {
|
||||
return Err("a ray-tracing node test's result");
|
||||
};
|
||||
let site = (b, i);
|
||||
let nodes = self
|
||||
.x
|
||||
.res
|
||||
.bvh
|
||||
.iter()
|
||||
.find(|n| n.0 == site)
|
||||
.map(|n| n.1)
|
||||
.ok_or("an untracked ray-tracing structure")?;
|
||||
let (sort, barycentrics) = match nodes {
|
||||
BvhNodes::Resource => (true, true),
|
||||
BvhNodes::Memory { word1, word3 } => (
|
||||
word1 & bvh::BOX_SORT != 0,
|
||||
word3 & bvh::RETURN_BARYCENTRICS != 0,
|
||||
),
|
||||
};
|
||||
if !barycentrics {
|
||||
// Mode 0 returns a triangle id and a hit status in the last two
|
||||
// dwords; no program of the title asks for it.
|
||||
return Err("a ray-tracing structure that returns triangle ids");
|
||||
}
|
||||
let guard = self.guard(b, i)?;
|
||||
let mut x = Vec::with_capacity(regs.len());
|
||||
for &r in ®s {
|
||||
let v = inst.read(Reg::V(r)).ok_or("an unread operand")?;
|
||||
x.push(self.i32_of(v)?);
|
||||
}
|
||||
let pointer = x[0];
|
||||
let pointer_high = wide.then(|| x[1]);
|
||||
let f: Vec<V> = x[1 + usize::from(wide)..]
|
||||
.iter()
|
||||
.map(|&v| self.as_float(v))
|
||||
.collect();
|
||||
let ray = Ray {
|
||||
extent: f[0],
|
||||
origin: [f[1], f[2], f[3]],
|
||||
direction: [f[4], f[5], f[6]],
|
||||
inverse: [f[7], f[8], f[9]],
|
||||
};
|
||||
let c = self.cur;
|
||||
let at = match nodes {
|
||||
BvhNodes::Resource => {
|
||||
let src = self
|
||||
.descriptors
|
||||
.get(&(site, false))
|
||||
.copied()
|
||||
.ok_or("an untracked ray-tracing structure")?;
|
||||
let handle = self.handle(site, src, false, (11, 0))?;
|
||||
// (pointer >> 3) << 6 from the buffer's start.
|
||||
let (kind_bits, k3) = (self.s.m.i32(!7), self.s.m.i32(3));
|
||||
let byte = self.s.m.bin(c, Bin::And, pointer, kind_bits);
|
||||
let byte = self.s.m.bin(c, Bin::Shl, byte, k3);
|
||||
NodeAt::Buffer { handle, byte }
|
||||
}
|
||||
BvhNodes::Memory { .. } => {
|
||||
let Operand::Scalar { code, .. } = *rsrc else {
|
||||
return Err("a ray-tracing structure descriptor not in SGPRs");
|
||||
};
|
||||
let mut words = [pointer; 2];
|
||||
for (k, w) in words.iter_mut().enumerate() {
|
||||
let v = inst
|
||||
.read(Reg::S(code + k as u8))
|
||||
.ok_or("an unread operand")?;
|
||||
*w = self.i32_of(v)?;
|
||||
}
|
||||
let (low, high) = self.bvh_address(words[0], words[1], pointer, pointer_high);
|
||||
// One look for the node's copy, before the branches: a
|
||||
// node is 64 bytes on 64, so its first half lies in one
|
||||
// 64 KiB page whatever its kind.
|
||||
let (handle, byte) = self.bvh_memory(low, high, guard);
|
||||
NodeAt::Memory {
|
||||
handle,
|
||||
byte,
|
||||
low,
|
||||
high,
|
||||
}
|
||||
}
|
||||
};
|
||||
let zero = self.s.m.i32(0);
|
||||
let gate = self.begin_guarded(guard);
|
||||
let head = self.cur;
|
||||
let (k4, k6, k7) = (self.s.m.i32(4), self.s.m.i32(6), self.s.m.i32(7));
|
||||
let kind = self.s.m.bin(head, Bin::And, pointer, k7);
|
||||
let pair = self.s.m.bin(head, Bin::And, pointer, k6);
|
||||
let is_box = self.s.m.cmp(head, pred::EQ, pair, k4);
|
||||
let is_triangle = self.s.m.cmp(head, pred::IULT, kind, k4);
|
||||
let (box_block, leaf_block) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
let (triangle_block, join) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
self.s
|
||||
.m
|
||||
.terminate(head, Term::CondBr(is_box, box_block, leaf_block));
|
||||
self.s
|
||||
.m
|
||||
.terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join));
|
||||
self.cur = box_block;
|
||||
let boxes = self.bvh_boxes(at, kind, &ray, sort);
|
||||
let box_end = self.cur;
|
||||
self.s.m.terminate(box_end, Term::Br(join));
|
||||
self.cur = triangle_block;
|
||||
let triangle = self.bvh_triangle(at, kind, &ray);
|
||||
let triangle_end = self.cur;
|
||||
self.s.m.terminate(triangle_end, Term::Br(join));
|
||||
self.cur = join;
|
||||
// Kinds 6 and 7 (an instance, a procedural primitive): not known
|
||||
// what the console returns; the title's programs do not read it.
|
||||
let other = bvh::MISS.map(|f| self.s.m.i32(f.to_bits()));
|
||||
let i32t = self.s.t.i32;
|
||||
let mut results = Vec::with_capacity(4);
|
||||
for k in 0..4 {
|
||||
let phi = self.s.m.phi(join, i32t);
|
||||
self.s.m.set_phi(
|
||||
phi,
|
||||
vec![
|
||||
(boxes[k], box_end),
|
||||
(triangle[k], triangle_end),
|
||||
(other[k], leaf_block),
|
||||
],
|
||||
);
|
||||
results.push((phi, zero));
|
||||
}
|
||||
let results = self.end_guarded(gate, &results);
|
||||
for (k, &r) in results.iter().enumerate() {
|
||||
self.write(inst, Reg::V(dst + k as u8), r, guard);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Title memory at `low`/`high` for a node's bytes: the raw view of the
|
||||
/// host copy holding the address and the byte in that view
|
||||
/// ([`Lower::memory`]: a page the host has no copy of reads zeros and
|
||||
/// is left for the host to fetch, for lanes that run).
|
||||
fn bvh_memory(&mut self, low: V, high: V, guard: Option<V>) -> (V, V) {
|
||||
#[cfg(test)]
|
||||
if let Some((slot, base)) = TEST_MEMORY.get() {
|
||||
// The buffer at heap slot `slot` holds the bytes from title
|
||||
// address `base` on; any other address reads past its end,
|
||||
// which is zeros.
|
||||
let c = self.cur;
|
||||
let slot = self.s.m.i32(slot);
|
||||
let handle = self.s.heap_handle(c, slot, false, false, (11, 0));
|
||||
let (base_low, base_high) =
|
||||
(self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32));
|
||||
let at = self.s.m.bin(c, Bin::Sub, low, base_low);
|
||||
let in_low = self.s.m.cmp(c, pred::IUGE, low, base_low);
|
||||
let in_high = self.s.m.cmp(c, pred::EQ, high, base_high);
|
||||
let inside = self.s.m.bin(c, Bin::And, in_low, in_high);
|
||||
let outside = self.s.m.i32(0xffff_ff00);
|
||||
let at = self.s.m.select(c, inside, at, outside);
|
||||
return (handle, at);
|
||||
}
|
||||
self.memory(low, high, guard)
|
||||
}
|
||||
|
||||
/// `count` dwords of the node from its byte `base` + `offset` (`base`
|
||||
/// computed, `offset` fixed; none of the node's bytes past 127), read
|
||||
/// four at a time.
|
||||
fn bvh_node_words(&mut self, at: NodeAt, base: Option<V>, offset: u32, count: u32) -> Vec<V> {
|
||||
let c = self.cur;
|
||||
let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
|
||||
// The second half of a 128-byte node may lie in the next 64 KiB
|
||||
// page, which may be in another copy: its own look, made once.
|
||||
let mut second = None;
|
||||
let mut out = Vec::with_capacity(count as usize);
|
||||
for start in (0..count).step_by(4) {
|
||||
let n = (count - start).min(4);
|
||||
let node_byte = offset + 4 * start;
|
||||
let (handle, mut byte) = match at {
|
||||
NodeAt::Buffer { handle, byte } => (handle, byte),
|
||||
NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte),
|
||||
NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| {
|
||||
let (low, high) = self.address_plus(low, high, 64);
|
||||
// Every lane in this block runs the instruction.
|
||||
let (handle, byte) = self.bvh_memory(low, high, None);
|
||||
let k64 = self.s.m.i32(64);
|
||||
(handle, self.s.m.bin(c, Bin::Sub, byte, k64))
|
||||
}),
|
||||
};
|
||||
if let Some(b) = base {
|
||||
byte = self.s.m.bin(c, Bin::Add, byte, b);
|
||||
}
|
||||
let k = self.s.m.i32(node_byte);
|
||||
let byte = self.s.m.bin(c, Bin::Add, byte, k);
|
||||
let mask = self.s.m.i8((1u8 << n) - 1);
|
||||
let r = self.s.op(
|
||||
c,
|
||||
"rawBufferLoad.f32",
|
||||
Attr::ReadOnly,
|
||||
self.s.t.res_ret,
|
||||
139,
|
||||
&[handle, byte, undef, mask, align],
|
||||
);
|
||||
for k in 0..n {
|
||||
let f = self.s.m.extract(c, r, k);
|
||||
out.push(self.as_int(f));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The node's title address, [`bvh::node_address`]: the descriptor's
|
||||
/// base (dword 0 and the low byte of dword 1, in 256-byte units) plus
|
||||
/// `(pointer >> 3) << 6`.
|
||||
fn bvh_address(&mut self, word0: V, word1: V, pointer: V, pointer_high: Option<V>) -> (V, V) {
|
||||
let c = self.cur;
|
||||
let i64t = self.s.m.int(64);
|
||||
let (zero, byte) = (self.s.m.i32(0), self.s.m.i32(0xff));
|
||||
let base_high = self.s.m.bin(c, Bin::And, word1, byte);
|
||||
let base = self.join64(word0, base_high);
|
||||
let k8 = self.s.m.int_const(i64t, 8);
|
||||
let base = self.s.m.bin(c, Bin::Shl, base, k8);
|
||||
let p = self.join64(pointer, pointer_high.unwrap_or(zero));
|
||||
let (k3, k6) = (self.s.m.int_const(i64t, 3), self.s.m.int_const(i64t, 6));
|
||||
let p = self.s.m.bin(c, Bin::LShr, p, k3);
|
||||
let p = self.s.m.bin(c, Bin::Shl, p, k6);
|
||||
let a = self.s.m.bin(c, Bin::Add, base, p);
|
||||
self.s.flags |= flags::INT64;
|
||||
self.split64(a)
|
||||
}
|
||||
|
||||
/// The box test ([`bvh::boxes`]): four result dwords. Starts in the
|
||||
/// current block and leaves `self.cur` at the block it ends in.
|
||||
fn bvh_boxes(&mut self, at: NodeAt, kind: V, ray: &Ray, sort: bool) -> [V; 4] {
|
||||
let head = self.cur;
|
||||
let children = self.bvh_node_words(at, None, 0, 4);
|
||||
let k5 = self.s.m.i32(5);
|
||||
let wide = self.s.m.cmp(head, pred::EQ, kind, k5);
|
||||
let (wide_block, half_block) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
let join = self.s.m.new_block();
|
||||
self.s
|
||||
.m
|
||||
.terminate(head, Term::CondBr(wide, wide_block, half_block));
|
||||
// 32-bit floats: 24 dwords from byte 16.
|
||||
self.cur = wide_block;
|
||||
let k16 = self.s.m.i32(16);
|
||||
let words = self.bvh_node_words(at, None, 16, 24);
|
||||
let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect();
|
||||
self.s.m.terminate(wide_block, Term::Br(join));
|
||||
// 16-bit floats: 24 halves in 12 dwords from byte 16, the low half
|
||||
// of a dword first.
|
||||
self.cur = half_block;
|
||||
let words = self.bvh_node_words(at, None, 16, 12);
|
||||
let f32t = self.s.t.f32;
|
||||
let mut halves = Vec::with_capacity(24);
|
||||
for n in 0..24 {
|
||||
let mut h = words[n / 2];
|
||||
if n % 2 == 1 {
|
||||
h = self.s.m.bin(half_block, Bin::LShr, h, k16);
|
||||
}
|
||||
// The conversion reads the low 16 bits.
|
||||
halves.push(self.s.op(
|
||||
half_block,
|
||||
"legacyF16ToF32",
|
||||
Attr::ReadNone,
|
||||
f32t,
|
||||
131,
|
||||
&[h],
|
||||
));
|
||||
}
|
||||
self.s.m.terminate(half_block, Term::Br(join));
|
||||
self.cur = join;
|
||||
let mut coords = Vec::with_capacity(24);
|
||||
for n in 0..24 {
|
||||
let phi = self.s.m.phi(join, f32t);
|
||||
self.s
|
||||
.m
|
||||
.set_phi(phi, vec![(floats[n], wide_block), (halves[n], half_block)]);
|
||||
coords.push(phi);
|
||||
}
|
||||
// The inverse direction held finite ([`bvh::boxes`]).
|
||||
let (most, least) = (
|
||||
self.s.m.f32(f32::MAX.to_bits()),
|
||||
self.s.m.f32((-f32::MAX).to_bits()),
|
||||
);
|
||||
let inverse = ray.inverse.map(|x| {
|
||||
let x = self.binary(35, x, least);
|
||||
self.binary(36, x, most)
|
||||
});
|
||||
let c = join;
|
||||
let (none, infinity, fzero) = (
|
||||
self.s.m.i32(bvh::NONE),
|
||||
self.s.m.f32(f32::INFINITY.to_bits()),
|
||||
self.s.m.f32(0),
|
||||
);
|
||||
let mut ids = [none; 4];
|
||||
let mut distances = [infinity; 4];
|
||||
for n in 0..4 {
|
||||
let bx = &coords[6 * n..6 * n + 6];
|
||||
let (mut near, mut far) = ([fzero; 3], [fzero; 3]);
|
||||
for a in 0..3 {
|
||||
let low = self.s.m.bin(c, Bin::Sub, bx[a], ray.origin[a]);
|
||||
let low = self.s.m.bin(c, Bin::Mul, low, inverse[a]);
|
||||
let high = self.s.m.bin(c, Bin::Sub, bx[3 + a], ray.origin[a]);
|
||||
let high = self.s.m.bin(c, Bin::Mul, high, inverse[a]);
|
||||
near[a] = self.binary(36, low, high);
|
||||
far[a] = self.binary(35, low, high);
|
||||
}
|
||||
let enter = self.binary(35, near[0], near[1]);
|
||||
let enter = self.binary(35, enter, near[2]);
|
||||
let leave = self.binary(36, far[0], far[1]);
|
||||
let leave = self.binary(36, leave, far[2]);
|
||||
let from = self.binary(35, enter, fzero);
|
||||
// Ordered compares: a NaN anywhere is a miss.
|
||||
let through = self.s.m.cmp(c, pred::OGE, leave, from);
|
||||
let before = self.s.m.cmp(c, pred::OLT, enter, ray.extent);
|
||||
let off = self.is_nan_f32(bx[0]);
|
||||
let on = self.s.m.bool(true);
|
||||
let on = self.s.m.bin(c, Bin::Xor, off, on);
|
||||
let hit = self.s.m.bin(c, Bin::And, through, before);
|
||||
let hit = self.s.m.bin(c, Bin::And, hit, on);
|
||||
ids[n] = self.s.m.select(c, hit, children[n], none);
|
||||
distances[n] = self.s.m.select(c, hit, enter, infinity);
|
||||
}
|
||||
if sort {
|
||||
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
|
||||
let swap = self.s.m.cmp(c, pred::OLT, distances[b], distances[a]);
|
||||
let (da, db) = (distances[a], distances[b]);
|
||||
distances[a] = self.s.m.select(c, swap, db, da);
|
||||
distances[b] = self.s.m.select(c, swap, da, db);
|
||||
let (ia, ib) = (ids[a], ids[b]);
|
||||
ids[a] = self.s.m.select(c, swap, ib, ia);
|
||||
ids[b] = self.s.m.select(c, swap, ia, ib);
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The triangle test ([`bvh::triangle`] of [`bvh::triangle_vertices`]):
|
||||
/// four result dwords, made in the current block.
|
||||
fn bvh_triangle(&mut self, at: NodeAt, kind: V, ray: &Ray) -> [V; 4] {
|
||||
let c = self.cur;
|
||||
let k = |l: &mut Self, v: u32| l.s.m.i32(v);
|
||||
// The triangle's byte of the dword at byte 60: which of its
|
||||
// vertices barycentric I and J weigh.
|
||||
let id = self.bvh_node_words(at, None, 60, 1)[0];
|
||||
let (k2, k3, k12, k15) = (k(self, 2), k(self, 3), k(self, 12), k(self, 15));
|
||||
let shift = self.s.m.bin(c, Bin::Shl, kind, k3);
|
||||
let id = self.s.m.bin(c, Bin::LShr, id, shift);
|
||||
let i = self.s.m.bin(c, Bin::And, id, k3);
|
||||
let j = self.s.m.bin(c, Bin::LShr, id, k2);
|
||||
let j = self.s.m.bin(c, Bin::And, j, k3);
|
||||
let first = self.s.m.bin(c, Bin::Sub, k3, i);
|
||||
let first = self.s.m.bin(c, Bin::Sub, first, j);
|
||||
let first = self.s.m.bin(c, Bin::And, first, k3);
|
||||
// The node's vertices the triangle is made of, four bits each.
|
||||
let (k0, k1) = (k(self, 0), k(self, 1));
|
||||
let maps: [V; 4] = std::array::from_fn(|n| k(self, bvh::vertex_map(n as u32)));
|
||||
let (is0, is1, is2) = (
|
||||
self.s.m.cmp(c, pred::EQ, kind, k0),
|
||||
self.s.m.cmp(c, pred::EQ, kind, k1),
|
||||
self.s.m.cmp(c, pred::EQ, kind, k2),
|
||||
);
|
||||
let map = self.s.m.select(c, is2, maps[2], maps[3]);
|
||||
let map = self.s.m.select(c, is1, maps[1], map);
|
||||
let map = self.s.m.select(c, is0, maps[0], map);
|
||||
let mut p = Vec::with_capacity(3);
|
||||
for n in [first, i, j] {
|
||||
let nibble = self.s.m.bin(c, Bin::Shl, n, k2);
|
||||
let vertex = self.s.m.bin(c, Bin::LShr, map, nibble);
|
||||
let vertex = self.s.m.bin(c, Bin::And, vertex, k15);
|
||||
let byte = self.s.m.bin(c, Bin::Mul, vertex, k12);
|
||||
let words = self.bvh_node_words(at, Some(byte), 0, 3);
|
||||
// Relative to the ray's origin.
|
||||
let r: Vec<V> = (0..3)
|
||||
.map(|a| {
|
||||
let f = self.as_float(words[a]);
|
||||
self.s.m.bin(c, Bin::Sub, f, ray.origin[a])
|
||||
})
|
||||
.collect();
|
||||
p.push([r[0], r[1], r[2]]);
|
||||
}
|
||||
// The ray's largest axis z, and x and y after it in an order that
|
||||
// keeps the winding.
|
||||
let fzero = self.s.m.f32(0);
|
||||
let size = ray.direction.map(|d| self.unary(6, d));
|
||||
let xy = self.s.m.cmp(c, pred::OGE, size[0], size[1]);
|
||||
let xz = self.s.m.cmp(c, pred::OGE, size[0], size[2]);
|
||||
let yz = self.s.m.cmp(c, pred::OGE, size[1], size[2]);
|
||||
let z0 = self.s.m.bin(c, Bin::And, xy, xz);
|
||||
let on = self.s.m.bool(true);
|
||||
let not_xy = self.s.m.bin(c, Bin::Xor, xy, on);
|
||||
let z1 = self.s.m.bin(c, Bin::And, not_xy, yz);
|
||||
// Component (kz + n) % 3 of `q`.
|
||||
let pick = |l: &mut Self, q: [V; 3], n: usize| {
|
||||
let rest = l.s.m.select(c, z1, q[(1 + n) % 3], q[(2 + n) % 3]);
|
||||
l.s.m.select(c, z0, q[n % 3], rest)
|
||||
};
|
||||
let dz = pick(self, ray.direction, 0);
|
||||
let backwards = self.s.m.cmp(c, pred::OLT, dz, fzero);
|
||||
// (x, y, z) of `q`: the two after the largest axis, swapped for a
|
||||
// ray that runs backwards along it.
|
||||
let axes = |l: &mut Self, q: [V; 3]| {
|
||||
let (x, y) = (pick(l, q, 1), pick(l, q, 2));
|
||||
[
|
||||
l.s.m.select(c, backwards, y, x),
|
||||
l.s.m.select(c, backwards, x, y),
|
||||
pick(l, q, 0),
|
||||
]
|
||||
};
|
||||
let d = axes(self, ray.direction);
|
||||
let sz = pick(self, ray.inverse, 0);
|
||||
let sx = self.s.m.bin(c, Bin::Mul, d[0], sz);
|
||||
let sy = self.s.m.bin(c, Bin::Mul, d[1], sz);
|
||||
let mut sheared = Vec::with_capacity(3);
|
||||
for r in p {
|
||||
let r = axes(self, r);
|
||||
let x = self.s.m.bin(c, Bin::Mul, sx, r[2]);
|
||||
let x = self.s.m.bin(c, Bin::Sub, r[0], x);
|
||||
let y = self.s.m.bin(c, Bin::Mul, sy, r[2]);
|
||||
let y = self.s.m.bin(c, Bin::Sub, r[1], y);
|
||||
let z = self.s.m.bin(c, Bin::Mul, sz, r[2]);
|
||||
sheared.push((x, y, z));
|
||||
}
|
||||
let [(ax, ay, az), (bx, by, bz), (cx, cy, cz)] = sheared[..] else {
|
||||
unreachable!()
|
||||
};
|
||||
// p * q - r * s.
|
||||
let cross = |l: &mut Self, p: V, q: V, r: V, s: V| {
|
||||
let a = l.s.m.bin(c, Bin::Mul, p, q);
|
||||
let b = l.s.m.bin(c, Bin::Mul, r, s);
|
||||
l.s.m.bin(c, Bin::Sub, a, b)
|
||||
};
|
||||
let u = cross(self, cx, by, cy, bx);
|
||||
let v = cross(self, ax, cy, ay, cx);
|
||||
let w = cross(self, bx, ay, by, ax);
|
||||
let any = |l: &mut Self, p: u8| {
|
||||
let a = l.s.m.cmp(c, p, u, fzero);
|
||||
let b = l.s.m.cmp(c, p, v, fzero);
|
||||
let d = l.s.m.cmp(c, p, w, fzero);
|
||||
let a = l.s.m.bin(c, Bin::Or, a, b);
|
||||
l.s.m.bin(c, Bin::Or, a, d)
|
||||
};
|
||||
let behind = any(self, pred::OLT);
|
||||
let before = any(self, pred::OGT);
|
||||
let outside = self.s.m.bin(c, Bin::And, behind, before);
|
||||
let inside = self.s.m.bin(c, Bin::Xor, outside, on);
|
||||
let det = self.s.m.bin(c, Bin::Add, v, w);
|
||||
let det = self.s.m.bin(c, Bin::Add, u, det);
|
||||
let t = self.s.m.bin(c, Bin::Mul, u, az);
|
||||
let t2 = self.s.m.bin(c, Bin::Mul, v, bz);
|
||||
let t = self.s.m.bin(c, Bin::Add, t, t2);
|
||||
let t2 = self.s.m.bin(c, Bin::Mul, w, cz);
|
||||
let t = self.s.m.bin(c, Bin::Add, t, t2);
|
||||
// The distance is not negative: the numerator has the
|
||||
// denominator's sign (or is 0). Ordered compares: a denominator
|
||||
// of 0 or a NaN is a miss.
|
||||
let front = self.s.m.cmp(c, pred::OGT, det, fzero);
|
||||
let front_ahead = self.s.m.cmp(c, pred::OGE, t, fzero);
|
||||
let front = self.s.m.bin(c, Bin::And, front, front_ahead);
|
||||
let back = self.s.m.cmp(c, pred::OLT, det, fzero);
|
||||
let back_ahead = self.s.m.cmp(c, pred::OLE, t, fzero);
|
||||
let back = self.s.m.bin(c, Bin::And, back, back_ahead);
|
||||
let ahead = self.s.m.bin(c, Bin::Or, front, back);
|
||||
let hit = self.s.m.bin(c, Bin::And, inside, ahead);
|
||||
let miss = bvh::MISS.map(|f| self.s.m.f32(f.to_bits()));
|
||||
let out = [t, det, v, w];
|
||||
std::array::from_fn(|n| {
|
||||
let f = self.s.m.select(c, hit, out[n], miss[n]);
|
||||
self.as_int(f)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
//! The ray-tracing node test end to end: a synthetic compute program that
|
||||
//! runs `image_bvh64_intersect_ray` (or the 32-bit form) once per thread,
|
||||
//! lowered to DXIL, validated by `dxil.dll` when present, run on the host
|
||||
//! GPU and WARP, and compared dword for dword with the CPU reference
|
||||
//! ([`crate::bvh`]).
|
||||
//!
|
||||
//! The nodes are in a raw buffer. Two ways to name it are run: the
|
||||
//! buffer's descriptor from the program's table (a resource of the host,
|
||||
//! [`crate::resource::BvhNodes::Resource`]), and the title's way, a
|
||||
//! descriptor of numbers over title memory with the structure's address in
|
||||
//! the node pointer or in the descriptor. These tests have no host that
|
||||
//! keeps copies of title memory and their directory, so for the second
|
||||
//! they put a stand-in under the node reader
|
||||
//! (`lower::intersect::TEST_MEMORY`); without it the same program reads
|
||||
//! through the directory, which is only checked to lower and validate.
|
||||
|
||||
use super::host::{Dispatch, Host, Root, Stride, View};
|
||||
use super::lower::intersect::TEST_MEMORY;
|
||||
use super::{HostShader, lower, validator};
|
||||
use crate::bvh::{self, Ray, tests as nodes};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use crate::resource::BvhNodes;
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
/// Threads of one group, each with its own record.
|
||||
const THREADS: u32 = 32;
|
||||
/// Bytes of a thread's record: the node pointer (two dwords), the ray's
|
||||
/// extent, origin, direction and inverse direction, and whether the
|
||||
/// thread runs the instruction.
|
||||
const RECORD: u32 = 64;
|
||||
/// Where the nodes start in the buffer.
|
||||
const NODES: u32 = THREADS * RECORD;
|
||||
/// What the result registers hold before the instruction.
|
||||
const BEFORE: [u32; 4] = [1, 2, 3, 4];
|
||||
|
||||
/// How the program names the nodes' memory.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Descriptor {
|
||||
/// The buffer's descriptor from the table.
|
||||
Table,
|
||||
/// Numbers, as the title builds it: dwords 0 and 1 (the base address
|
||||
/// in 256-byte units and the box sorting bit); the size and the rest of
|
||||
/// the flags as the title sets them.
|
||||
Numbers(u32, u32),
|
||||
}
|
||||
|
||||
/// The descriptor the title builds for the 64-bit form: the whole address
|
||||
/// space, sorted boxes, barycentrics returned.
|
||||
const WHOLE: Descriptor = Descriptor::Numbers(0, bvh::BOX_SORT);
|
||||
|
||||
/// The program: per thread, the record's twelve operand dwords in v1-v12,
|
||||
/// the instruction's result in v13-v16 (under a lane mask of the threads
|
||||
/// whose record says so), stored to the UAV at 16 bytes a thread.
|
||||
fn program(wide: bool, descriptor: Descriptor) -> Vec<u32> {
|
||||
let mut w = vec![
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0xF408_0202,
|
||||
0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
|
||||
0xF408_0302,
|
||||
0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
|
||||
0x3428_0086, // v_lshlrev_b32 v20, 6, v0
|
||||
0xE038_1000,
|
||||
0x8002_0114, // buffer_load_dwordx4 v[1:4], v20, s[8:11], 0 offen
|
||||
0xE038_1010,
|
||||
0x8002_0514, // buffer_load_dwordx4 v[5:8], v20, s[8:11], 0 offen offset:16
|
||||
0xE038_1020,
|
||||
0x8002_0914, // buffer_load_dwordx4 v[9:12], v20, s[8:11], 0 offen offset:32
|
||||
0xE030_1030,
|
||||
0x8002_1114, // buffer_load_dword v17, v20, s[8:11], 0 offen offset:48
|
||||
];
|
||||
for k in 0..4u32 {
|
||||
// v_mov_b32 v13+k, 1+k
|
||||
w.push(0x7E00_0200 | (13 + k) << 17 | (0x81 + k));
|
||||
}
|
||||
let rsrc = match descriptor {
|
||||
Descriptor::Table => 8,
|
||||
Descriptor::Numbers(word0, word1) => {
|
||||
// s_mov_b32 s24, word0
|
||||
w.extend([0xBE98_03FF, word0]);
|
||||
if word1 == bvh::BOX_SORT {
|
||||
// As the title makes it.
|
||||
w.push(0xBE99_0B81); // s_brev_b32 s25, 1
|
||||
} else {
|
||||
w.extend([0xBE99_03FF, word1]); // s_mov_b32 s25, word1
|
||||
}
|
||||
w.extend([
|
||||
0xBE9A_03C1, // s_mov_b32 s26, -1
|
||||
0xBE9B_03FF,
|
||||
0x8900_03FF, // s_mov_b32 s27, 0x890003ff
|
||||
]);
|
||||
24
|
||||
}
|
||||
};
|
||||
w.extend([
|
||||
0xBE94_037E, // s_mov_b32 s20, exec_lo
|
||||
0x7DAA_2280, // v_cmpx_ne_u32 exec_lo, 0, v17
|
||||
]);
|
||||
let first = 0x0000_0D01 | (rsrc >> 2) << 16;
|
||||
if wide {
|
||||
// image_bvh64_intersect_ray v[13:16], [v1 .. v12], s[rsrc:rsrc+3]
|
||||
w.extend([0xF19C_9F07, first, 0x0504_0302, 0x0908_0706, 0x000C_0B0A]);
|
||||
} else {
|
||||
// image_bvh_intersect_ray v[13:16], [v1, v3 .. v12], s[rsrc:rsrc+3]
|
||||
w.extend([0xF198_9F07, first, 0x0605_0403, 0x0A09_0807, 0x0000_0C0B]);
|
||||
}
|
||||
w.extend([
|
||||
0xBEFE_0314, // s_mov_b32 exec_lo, s20
|
||||
0x342A_0084, // v_lshlrev_b32 v21, 4, v0
|
||||
0xE078_1000,
|
||||
0x8003_0D15, // buffer_store_dwordx4 v[13:16], v21, s[12:15], 0 offen
|
||||
0xBF81_0000, // s_endpgm
|
||||
]);
|
||||
w
|
||||
}
|
||||
|
||||
fn native(words: &[u32]) -> NativeProgram {
|
||||
let table = |kind, at| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: at,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
};
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 22,
|
||||
layout: vec![
|
||||
RootParam {
|
||||
root: RootType::Constants,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 4,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
used: vec![table(ResourceType::Srv, 0), table(ResourceType::Uav, 8)],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 5 << 1,
|
||||
threads: [THREADS, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lowers the program; the DXIL is validated when the validator is there.
|
||||
fn build(
|
||||
wide: bool,
|
||||
descriptor: Descriptor,
|
||||
) -> Result<(HostShader, resource::Resources), ShaderError> {
|
||||
let native = native(&program(wide, descriptor));
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
|
||||
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,
|
||||
})?;
|
||||
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,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views.clone(),
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
Ok((shader, res))
|
||||
}
|
||||
|
||||
/// One thread's test: a node (by its index in the node list), the kind its
|
||||
/// pointer carries, and the ray; `None` leaves the thread masked out.
|
||||
type Case = Option<(usize, u32, Ray)>;
|
||||
|
||||
/// The scene: node dwords (a 32-bit box node takes 32, the others 16) and
|
||||
/// where each node starts, in dwords from the first node.
|
||||
struct Scene {
|
||||
words: Vec<u32>,
|
||||
starts: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
words: Vec::new(),
|
||||
starts: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a node of `dwords` (16 or 32) and returns its index.
|
||||
fn add(&mut self, node: [u32; 28], dwords: usize) -> usize {
|
||||
self.starts.push(self.words.len());
|
||||
let mut padded = [0u32; 32];
|
||||
padded[..28].copy_from_slice(&node);
|
||||
// Bytes the instruction must not read as part of the node: what
|
||||
// follows a 64-byte node, and a box node's last 16 bytes.
|
||||
for w in padded.iter_mut().skip(if dwords == 16 { 16 } else { 28 }) {
|
||||
*w = 0x7fc0_dead;
|
||||
}
|
||||
self.words.extend(&padded[..dwords]);
|
||||
self.starts.len() - 1
|
||||
}
|
||||
|
||||
/// The pointer of node `n` with `kind`, counted from the first node.
|
||||
fn pointer(&self, n: usize, kind: u32) -> u32 {
|
||||
(4 * self.starts[n] as u32) >> 3 | kind
|
||||
}
|
||||
|
||||
/// What the instruction reads of node `n`.
|
||||
fn node(&self, n: usize) -> [u32; 28] {
|
||||
std::array::from_fn(|k| self.words.get(self.starts[n] + k).copied().unwrap_or(0))
|
||||
}
|
||||
}
|
||||
|
||||
/// A small generator of repeatable numbers.
|
||||
struct Numbers(u64);
|
||||
|
||||
impl Numbers {
|
||||
fn next(&mut self) -> u32 {
|
||||
self.0 = self
|
||||
.0
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1442695040888963407);
|
||||
(self.0 >> 33) as u32
|
||||
}
|
||||
|
||||
/// A float in -1..1 in steps of 1/4096 (exactly representable).
|
||||
fn unit(&mut self) -> f32 {
|
||||
(self.next() % 8193) as f32 / 4096.0 - 1.0
|
||||
}
|
||||
|
||||
fn vector(&mut self, scale: f32) -> [f32; 3] {
|
||||
[
|
||||
self.unit() * scale,
|
||||
self.unit() * scale,
|
||||
self.unit() * scale,
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// The scene and batches of cases over it.
|
||||
fn scene() -> (Scene, Vec<Vec<Case>>) {
|
||||
let mut s = Scene::new();
|
||||
let mut g = Numbers(0x5eed);
|
||||
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
|
||||
let moved =
|
||||
|b: [f32; 6], by: [f32; 3]| -> [f32; 6] { std::array::from_fn(|k| b[k] + by[k % 3]) };
|
||||
let off = [f32::NAN; 6];
|
||||
let mut box_nodes = Vec::new();
|
||||
// The boxes of the reference's own tests, in both widths.
|
||||
let lined = [
|
||||
moved(UNIT, [30.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 5.0, 0.0]),
|
||||
moved(UNIT, [20.0, 0.0, 0.0]),
|
||||
];
|
||||
let ids = [0x105, 0x20c, 0x304, 0x400];
|
||||
box_nodes.push((s.add(nodes::box32(ids, lined), 32), 5));
|
||||
box_nodes.push((s.add(nodes::box16(ids, lined), 16), 4));
|
||||
// Boxes around the origin, one switched off, one child missing.
|
||||
let around = [
|
||||
UNIT,
|
||||
moved(UNIT, [0.5, 0.5, 0.5]),
|
||||
off,
|
||||
[-4.0, -0.25, -0.25, 4.0, 0.25, 0.25],
|
||||
];
|
||||
let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc];
|
||||
box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5));
|
||||
box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4));
|
||||
// Random boxes.
|
||||
for n in 0..6 {
|
||||
let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| {
|
||||
let (c, h) = (g.vector(8.0), g.vector(2.0).map(f32::abs));
|
||||
std::array::from_fn(|k| c[k % 3] + if k < 3 { -h[k] } else { h[k - 3] })
|
||||
});
|
||||
let ids: [u32; 4] = std::array::from_fn(|k| 0x1000 * (n + 1) + 8 * k as u32 + 5);
|
||||
if n % 2 == 0 {
|
||||
box_nodes.push((s.add(nodes::box32(ids, boxes), 32), 5));
|
||||
} else {
|
||||
box_nodes.push((s.add(nodes::box16(ids, boxes), 16), 4));
|
||||
}
|
||||
}
|
||||
// Triangles: one of the reference's tests, a pair as the title's
|
||||
// builder stores it, all four triangles of a full node with turned
|
||||
// ids, random ones.
|
||||
let mut triangle_nodes = Vec::new();
|
||||
let front = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
|
||||
triangle_nodes.push((s.add(nodes::triangles(&front, 9), 16), 0));
|
||||
let pair = s.add(
|
||||
nodes::triangles(
|
||||
&[front[0], front[1], front[2], [2.0, 2.0, 5.0]],
|
||||
9 | 0x80 | 6 << 8,
|
||||
),
|
||||
16,
|
||||
);
|
||||
triangle_nodes.extend([(pair, 0), (pair, 1)]);
|
||||
let five = [
|
||||
[-3.0, -1.0, 6.0],
|
||||
[-1.0, 2.0, 6.5],
|
||||
[1.0, -1.0, 6.0],
|
||||
[3.0, 2.0, 6.5],
|
||||
[5.0, -1.0, 7.0],
|
||||
];
|
||||
// I and J per triangle: (1, 2), (2, 0), (0, 1), (1, 2).
|
||||
let full = s.add(nodes::triangles(&five, 9 | 2 << 8 | 4 << 16 | 9 << 24), 16);
|
||||
triangle_nodes.extend((0..4).map(|k| (full, k)));
|
||||
for _ in 0..5 {
|
||||
let c = g.vector(6.0);
|
||||
let v: [[f32; 3]; 3] = std::array::from_fn(|_| {
|
||||
let d = g.vector(3.0);
|
||||
[c[0] + d[0], c[1] + d[1], c[2] + d[2]]
|
||||
});
|
||||
triangle_nodes.push((s.add(nodes::triangles(&v, 9), 16), 0));
|
||||
}
|
||||
let mut cases: Vec<Case> = Vec::new();
|
||||
// Rays of the reference's tests against the lined-up boxes.
|
||||
for &(n, kind) in &box_nodes[..2] {
|
||||
for (origin, direction, extent) in [
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 19.5),
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 19.0),
|
||||
([0.0; 3], [-1.0, 0.0, 0.0], 1000.0),
|
||||
([40.0, 0.0, 0.0], [-2.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, 0.5, 0.25], [1.0, -0.0, 0.0], 1000.0),
|
||||
([0.0; 3], [0.0; 3], 1000.0),
|
||||
] {
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
|
||||
}
|
||||
}
|
||||
// Random rays at every box node, half of them aimed at a box.
|
||||
for &(n, kind) in &box_nodes {
|
||||
let words = s.node(n);
|
||||
let boxes = if kind == 5 {
|
||||
bvh::boxes32(&words)
|
||||
} else {
|
||||
bvh::boxes16(&words)
|
||||
};
|
||||
for k in 0..12 {
|
||||
let origin = g.vector(12.0);
|
||||
let direction = if k % 2 == 0 {
|
||||
let b = boxes[(k / 2) % 4];
|
||||
if b[0].is_nan() {
|
||||
g.vector(1.0)
|
||||
} else {
|
||||
std::array::from_fn(|a| (b[a] + b[3 + a]) / 2.0 - origin[a] + g.unit() / 2.0)
|
||||
}
|
||||
} else {
|
||||
g.vector(1.0)
|
||||
};
|
||||
let extent = if k % 3 == 0 { 6.0 } else { 100.0 };
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
|
||||
}
|
||||
}
|
||||
// Rays at every triangle: aimed inside, at an edge, at a vertex, past
|
||||
// it, from both sides, along each axis.
|
||||
for &(n, kind) in &triangle_nodes {
|
||||
let p = bvh::triangle_vertices(&s.node(n), kind);
|
||||
let at = |w: [f32; 3]| -> [f32; 3] {
|
||||
std::array::from_fn(|a| w[0] * p[0][a] + w[1] * p[1][a] + w[2] * p[2][a])
|
||||
};
|
||||
for (k, w) in [
|
||||
[0.5, 0.25, 0.25],
|
||||
[0.125, 0.75, 0.125],
|
||||
[0.5, 0.5, 0.0],
|
||||
[0.0, 0.5, 0.5],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.75, 0.75, -0.5],
|
||||
[-0.25, 0.5, 0.75],
|
||||
[0.25, 0.25, 0.5],
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let target = at(w);
|
||||
let origin = if k % 2 == 0 { [0.0; 3] } else { g.vector(16.0) };
|
||||
let mut direction: [f32; 3] = std::array::from_fn(|a| target[a] - origin[a]);
|
||||
if k == 7 {
|
||||
// The triangle lies behind.
|
||||
direction = direction.map(|d| -d);
|
||||
}
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
|
||||
}
|
||||
for axis in 0..3 {
|
||||
for sign in [1.0f32, -1.0] {
|
||||
let target = at([0.25, 0.5, 0.25]);
|
||||
let mut origin = target;
|
||||
origin[axis] -= 8.0 * sign;
|
||||
let mut direction = [0.0; 3];
|
||||
direction[axis] = sign;
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Kinds the instruction does not read, and threads masked out.
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
cases.extend([
|
||||
Some((triangle_nodes[0].0, 6, ray)),
|
||||
Some((triangle_nodes[0].0, 7, ray)),
|
||||
None,
|
||||
Some((
|
||||
box_nodes[0].0,
|
||||
5,
|
||||
Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
|
||||
)),
|
||||
None,
|
||||
]);
|
||||
let batches = cases
|
||||
.chunks(THREADS as usize)
|
||||
.map(<[Case]>::to_vec)
|
||||
.collect();
|
||||
(s, batches)
|
||||
}
|
||||
|
||||
/// The buffer for one batch: the threads' records, then the nodes. Node
|
||||
/// pointers count from `base` before the first node, in bytes.
|
||||
fn buffer(scene: &Scene, batch: &[Case], base: u64) -> Vec<u32> {
|
||||
let mut data = vec![0u32; (NODES / 4) as usize];
|
||||
for (t, case) in batch.iter().enumerate() {
|
||||
let Some((n, kind, ray)) = case else { continue };
|
||||
let r = &mut data[t * (RECORD / 4) as usize..][..13];
|
||||
let pointer = (base >> 3) + u64::from(scene.pointer(*n, *kind));
|
||||
(r[0], r[1]) = (pointer as u32, (pointer >> 32) as u32);
|
||||
r[2] = ray.extent.to_bits();
|
||||
for a in 0..3 {
|
||||
r[3 + a] = ray.origin[a].to_bits();
|
||||
r[6 + a] = ray.direction[a].to_bits();
|
||||
r[9 + a] = ray.inverse[a].to_bits();
|
||||
}
|
||||
r[12] = 1;
|
||||
}
|
||||
data.extend(&scene.words);
|
||||
data
|
||||
}
|
||||
|
||||
fn expected(scene: &Scene, case: &Case, sort: bool) -> [u32; 4] {
|
||||
match case {
|
||||
Some((n, kind, ray)) => bvh::intersect(&scene.node(*n), *kind, ray, sort),
|
||||
None => BEFORE,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the tests' title memory for this thread until dropped.
|
||||
struct Memory;
|
||||
|
||||
impl Memory {
|
||||
fn at(base: u64) -> Self {
|
||||
// Heap slot 0: the buffer of records and nodes.
|
||||
TEST_MEMORY.set(Some((0, base)));
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Memory {
|
||||
fn drop(&mut self) {
|
||||
TEST_MEMORY.set(None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs every batch on the hardware adapter and WARP and compares with
|
||||
/// the reference. `pointers` is what node pointers count from, in bytes
|
||||
/// before the first node.
|
||||
fn run(wide: bool, descriptor: Descriptor, pointers: u64, sort: bool) {
|
||||
let (shader, res) = build(wide, descriptor).expect("the program lowers");
|
||||
assert_eq!(res.bvh.len(), 1);
|
||||
let (scene, batches) = scene();
|
||||
// The reference must see a bit of everything, or the comparison
|
||||
// proves little.
|
||||
let all: Vec<&Case> = batches.iter().flatten().collect();
|
||||
let results: Vec<[u32; 4]> = all.iter().map(|c| expected(&scene, c, sort)).collect();
|
||||
let boxes = |hits: usize| {
|
||||
all.iter()
|
||||
.zip(&results)
|
||||
.filter(|(c, r)| {
|
||||
matches!(c, Some((_, 4 | 5, _)))
|
||||
&& r.iter().filter(|&&x| x != bvh::NONE).count() == hits
|
||||
})
|
||||
.count()
|
||||
};
|
||||
let triangles = |hit: bool| {
|
||||
all.iter()
|
||||
.zip(&results)
|
||||
.filter(|(c, r)| {
|
||||
matches!(c, Some((_, 0..=3, _))) && (r[0] != f32::INFINITY.to_bits()) == hit
|
||||
})
|
||||
.count()
|
||||
};
|
||||
assert!(
|
||||
boxes(0) > 5 && boxes(1) > 5 && boxes(2) > 5 && boxes(3) > 0,
|
||||
"box cases"
|
||||
);
|
||||
assert!(
|
||||
triangles(true) > 30 && triangles(false) > 30,
|
||||
"triangle cases"
|
||||
);
|
||||
// Sorting must matter to some case, or the unsorted run proves nothing.
|
||||
assert!(
|
||||
all.iter()
|
||||
.any(|c| expected(&scene, c, true) != expected(&scene, c, false)),
|
||||
"no case tells sorted from unsorted"
|
||||
);
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let mut ran = 0;
|
||||
for (label, warp) in [("hardware", false), ("warp", true)] {
|
||||
let Ok(host) = Host::new(warp) else {
|
||||
eprintln!("no SM 6.6 {label} device; skipped");
|
||||
continue;
|
||||
};
|
||||
let (root, pso) = host
|
||||
.compute_pipeline(&shader)
|
||||
.unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
|
||||
for (b, batch) in batches.iter().enumerate() {
|
||||
let data = buffer(&scene, batch, pointers);
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(vec![0; 5]))],
|
||||
views: &[
|
||||
View::Buffer {
|
||||
data: &data,
|
||||
stride: Stride::Raw,
|
||||
},
|
||||
View::RawUav(4 * THREADS),
|
||||
],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
|
||||
for t in 0..THREADS as usize {
|
||||
let case = batch.get(t).copied().flatten();
|
||||
let want = match batch.get(t) {
|
||||
Some(c) => expected(&scene, c, sort),
|
||||
// A thread past the batch: its record is zeros, so it
|
||||
// is masked out.
|
||||
None => BEFORE,
|
||||
};
|
||||
let got = &out[0][4 * t..4 * t + 4];
|
||||
assert_eq!(
|
||||
got,
|
||||
want,
|
||||
"{label}, batch {b} thread {t}: {case:x?}\n got {:x?} = {:?}\nwant {:x?} = {:?}",
|
||||
got,
|
||||
got.iter().map(|&x| f32::from_bits(x)).collect::<Vec<_>>(),
|
||||
want,
|
||||
want.map(f32::from_bits),
|
||||
);
|
||||
}
|
||||
}
|
||||
ran += 1;
|
||||
}
|
||||
assert!(ran > 0, "no SM 6.6 device available");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
|
||||
// Pointers count from the buffer's start.
|
||||
run(true, Descriptor::Table, u64::from(NODES), true);
|
||||
assert_eq!(
|
||||
build(true, Descriptor::Table).unwrap().1.bvh[0].1,
|
||||
BvhNodes::Resource
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
|
||||
run(false, Descriptor::Table, u64::from(NODES), true);
|
||||
}
|
||||
|
||||
/// Where the tests' title memory puts the buffer: past 4 GiB, on 256 bytes.
|
||||
const BASE: u64 = 0x12_3456_7800;
|
||||
|
||||
#[test]
|
||||
fn the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
|
||||
// The title's way: one descriptor for all of memory, the structure's
|
||||
// address folded into a 64-bit pointer.
|
||||
let _memory = Memory::at(BASE);
|
||||
run(true, WHOLE, BASE + u64::from(NODES), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
|
||||
// The title's other way: the structure's address in the descriptor
|
||||
// (in 256-byte units, 40 bits), a 32-bit pointer from there. Here with
|
||||
// an address past 2^40 bytes, and without box sorting.
|
||||
let base = 0x312_3456_7800u64;
|
||||
let structure = base + u64::from(NODES);
|
||||
let _memory = Memory::at(base);
|
||||
let descriptor = Descriptor::Numbers((structure >> 8) as u32, (structure >> 40) as u32);
|
||||
run(false, descriptor, 0, false);
|
||||
// And sorted.
|
||||
let descriptor = Descriptor::Numbers(
|
||||
(structure >> 8) as u32,
|
||||
(structure >> 40) as u32 | bvh::BOX_SORT,
|
||||
);
|
||||
run(false, descriptor, 0, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_descriptor_of_numbers_is_title_memory_read_through_the_directory() {
|
||||
for wide in [true, false] {
|
||||
let native = native(&program(wide, WHOLE));
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
|
||||
// The flags the title sets: sorted boxes, barycentrics, a
|
||||
// ray-tracing structure. No resource is taken for it: the buffer
|
||||
// loads' and the store's descriptors are all there is.
|
||||
assert_eq!(res.bvh.len(), 1);
|
||||
assert_eq!(
|
||||
res.bvh[0].1,
|
||||
BvhNodes::Memory {
|
||||
word1: 0x8000_0000,
|
||||
word3: 0x8900_03ff
|
||||
}
|
||||
);
|
||||
assert_eq!(res.descriptors.len(), 5);
|
||||
// Without the tests' stand-in the nodes are read as the title's
|
||||
// programs will read them: through the host's directory of title
|
||||
// memory. The program lowers and validates, and asks the host for
|
||||
// the directory and for the list of pages it found no copy of.
|
||||
let (shader, _) = build(wide, WHOLE).expect("lowers through the directory");
|
||||
assert!(shader.root_srvs.contains(&super::SLOT_MEMORY));
|
||||
assert!(shader.root_uavs.contains(&super::SLOT_FAULTS));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_structure_that_returns_triangle_ids_is_refused_by_name() {
|
||||
// Triangle return mode 0 (bit 24 of dword 3 clear): the last two
|
||||
// result dwords would be a triangle id and a hit status.
|
||||
let mut words = program(true, WHOLE);
|
||||
let flags = words.iter().position(|&w| w == 0x8900_03FF).unwrap();
|
||||
words[flags] = 0x8800_03FF;
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let r = 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,
|
||||
});
|
||||
match r {
|
||||
Err(ShaderError::Unsupported { what, .. }) => {
|
||||
assert_eq!(what, "a ray-tracing structure that returns triangle ids");
|
||||
}
|
||||
other => panic!("{:?}", other.map(|_| ())),
|
||||
}
|
||||
}
|
||||
+3923
-405
File diff suppressed because it is too large.
Load diff
@@ -50,10 +50,9 @@
|
||||
//! descriptors (1,024 world compute programs, ray-tracing material
|
||||
//! resolves) read raw views this way.
|
||||
//!
|
||||
//! * **Texture atomics** (added 2026-11-23): a texture UAV the shader uses
|
||||
//! atomically is declared a 32-bit unsigned single-channel view; the
|
||||
//! host's view at that index must be an R32 integer view (64-bit atomics
|
||||
//! stop the translation). Global loads from a root SRV read it raw.
|
||||
//! * **Texture atomics** use a scalar integer UAV. The host binds R32_UINT
|
||||
//! for 32-bit operations and R32G32_UINT for 64-bit operations. The latter
|
||||
//! require SM 6.6 atomic support on typed and descriptor-heap resources.
|
||||
//!
|
||||
//! Entry points: [`translate`] (container bytes as the title passes them
|
||||
//! at pipeline creation → [`HostShader`]), [`emit`] (the same with the
|
||||
@@ -74,16 +73,26 @@
|
||||
//! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are
|
||||
//! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the
|
||||
//! console never exports them).
|
||||
//! * **Rectangle lists** ([`rect_list_gs`], `gs_6_6`): the console draws a
|
||||
//! rectangle from three vertices; the host has no such topology. A
|
||||
//! pipeline the title makes for rectangles (topology type 19) gets a
|
||||
//! geometry shader of ours between the translated vertex and pixel
|
||||
//! shaders and draws triangle lists with the title's own vertex counts.
|
||||
//! It binds nothing.
|
||||
|
||||
mod bitcode;
|
||||
mod container;
|
||||
#[cfg(all(test, windows))]
|
||||
mod diff_tests;
|
||||
#[cfg(all(test, windows))]
|
||||
mod intersect_tests;
|
||||
#[cfg(all(windows, any(test, feature = "host")))]
|
||||
pub mod host;
|
||||
mod lower;
|
||||
mod rect;
|
||||
mod sampler;
|
||||
mod shader;
|
||||
mod threading;
|
||||
#[cfg(windows)]
|
||||
pub mod validator;
|
||||
#[cfg(all(test, windows))]
|
||||
@@ -97,7 +106,13 @@ use crate::native::{HwStage, NativeProgram, RootType};
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
pub use sampler::StaticSampler;
|
||||
pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
|
||||
pub use lower::set_host_max_wave;
|
||||
pub use rect::rect_list_gs;
|
||||
pub use shader::{
|
||||
MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
|
||||
SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
|
||||
set_view_heap_limit,
|
||||
};
|
||||
|
||||
/// The loop limit without an override: 2^20.
|
||||
pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT;
|
||||
@@ -122,6 +137,33 @@ pub fn loop_limit() -> u32 {
|
||||
})
|
||||
}
|
||||
|
||||
/// Which of a translated program's group barriers wait for the whole
|
||||
/// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory
|
||||
/// fence and lose the wait. A wait that some thread of the group never
|
||||
/// reaches is undefined on the host, and NVIDIA's wait is for every
|
||||
/// thread: the group stands until Windows resets the card. (The console's
|
||||
/// barrier is the wave's, whatever lanes are live, and a wave that ended
|
||||
/// is not waited for.) `VICTORY_GROUP_SYNC`:
|
||||
/// - unset or `2`: every barrier waits, as before.
|
||||
/// - `1`: the title's `s_barrier` waits only in a block every lane runs,
|
||||
/// in a program no lane can be cut out of at the iteration limit.
|
||||
/// - `0`: no barrier waits, neither the title's nor the ones the
|
||||
/// translation adds (wave64 programs in two host waves exchange through
|
||||
/// them, so such programs compute wrong values). For one run that tells
|
||||
/// whether a barrier is what stops the card: with it no run can stand in
|
||||
/// a barrier.
|
||||
///
|
||||
/// Part of the translation: the shader cache keys on it (`victory-gpu`'s
|
||||
/// does).
|
||||
pub fn group_sync() -> u8 {
|
||||
static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
|
||||
*MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) {
|
||||
Some("0") => 0,
|
||||
Some("1") => 1,
|
||||
_ => 2,
|
||||
})
|
||||
}
|
||||
|
||||
/// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
|
||||
/// unreadable or 0. Pure, for testing.
|
||||
fn parse_loop_limit(value: Option<&str>) -> u32 {
|
||||
@@ -156,6 +198,11 @@ pub struct HostShader {
|
||||
/// Root SRVs (raw buffers) the shader reads: `t<index>` in
|
||||
/// [`ROOT_CBV_SPACE`].
|
||||
pub root_srvs: Vec<u8>,
|
||||
/// Root UAVs (raw buffers) the shader reads or writes: `u<index>` in
|
||||
/// [`ROOT_CBV_SPACE`].
|
||||
pub root_uavs: Vec<u8>,
|
||||
/// Heap descriptors that can be selected from root state at bind time.
|
||||
pub root_indexed_views: Vec<crate::resource::RootIndexedView>,
|
||||
}
|
||||
|
||||
impl HostShader {
|
||||
@@ -204,7 +251,7 @@ pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
|
||||
offset: 0,
|
||||
what: "a container without a vertex, pixel, compute or mesh program",
|
||||
})?;
|
||||
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
|
||||
let p = crate::spill::build(&native)?;
|
||||
// Structurisation first: tracing per-lane descriptors needs it (its
|
||||
// failure is reported after the earlier stages').
|
||||
let st = structure::structure(&p);
|
||||
@@ -223,6 +270,139 @@ pub fn emit(
|
||||
io: &io::Io,
|
||||
res: &resource::Resources,
|
||||
) -> Result<HostShader, ShaderError> {
|
||||
let original = emit_program(c, native, p, st, io, res);
|
||||
// A console wave64 compute program on a host of 32-lane waves that
|
||||
// still needs 64 lanes, or whose cross-lane code sits where not every
|
||||
// lane runs: once more with its early-outs left out
|
||||
// ([`ir::without_early_outs`]), which is what usually keeps the whole
|
||||
// body from being a block every lane runs.
|
||||
let stuck = match &original {
|
||||
Ok((_, wave)) => *wave == Some(64),
|
||||
Err(ShaderError::Unsupported { what, .. }) => what.ends_with("where not every lane runs"),
|
||||
Err(_) => false,
|
||||
};
|
||||
if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 {
|
||||
let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
|
||||
let report = |what: &str, r: &Result<(HostShader, Option<u32>), ShaderError>| {
|
||||
if why {
|
||||
match r {
|
||||
Ok((_, wave)) => eprintln!("WAVE64-RETRY {what}: wave {wave:?}"),
|
||||
Err(e) => eprintln!("WAVE64-RETRY {what}: {e}"),
|
||||
}
|
||||
}
|
||||
};
|
||||
let done = |r: &Result<(HostShader, Option<u32>), ShaderError>| matches!(r, Ok((_, wave)) if *wave != Some(64));
|
||||
// Each host wave as a wave of its own (`lower::with_local_waves`),
|
||||
// for programs still stopped where not every lane runs.
|
||||
let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0");
|
||||
// Where the wave operations are the allocation idiom
|
||||
// ([`lower::wave_local`]) that is exact. Other programs are taken
|
||||
// the same way last of all, each half-wave giving its own results
|
||||
// (approximate: a tile-wide result becomes two half-tile ones);
|
||||
// `VICTORY_WAVE_LOCAL=idiom` refuses those instead.
|
||||
let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom");
|
||||
let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) {
|
||||
Ok(()) => true,
|
||||
Err((offset, what)) => {
|
||||
if why {
|
||||
eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}");
|
||||
}
|
||||
false
|
||||
}
|
||||
};
|
||||
// The program in two other forms: without its early-outs, and
|
||||
// without any branch that only skips code no lane is left for.
|
||||
let form = |p: Option<ir::Program>| {
|
||||
p.and_then(|p| {
|
||||
let st = structure::structure(&p).ok()?;
|
||||
let io = io::raise(&p, native).ok()?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?;
|
||||
Some((p, st, io, res))
|
||||
})
|
||||
};
|
||||
let forms = [
|
||||
("without early-outs", form(ir::without_early_outs(p))),
|
||||
("without skips", form(ir::without_skips(p))),
|
||||
];
|
||||
for (name, f) in &forms {
|
||||
if let Some((p, st, io, res)) = f {
|
||||
let again = emit_program(c, native, p, st, io, res);
|
||||
report(name, &again);
|
||||
if done(&again) {
|
||||
return again.map(|(shader, _)| shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
if local_on {
|
||||
// exact first (every form), then approximate
|
||||
for exact in [true, false] {
|
||||
if !exact && strict {
|
||||
break;
|
||||
}
|
||||
for (name, f) in &forms {
|
||||
if let Some((p, st, io, res)) = f
|
||||
&& idiom(p, st) == exact
|
||||
{
|
||||
let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
|
||||
report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local);
|
||||
if done(&local) {
|
||||
return local.map(|(shader, _)| shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
if idiom(p, st) == exact {
|
||||
let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
|
||||
report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local);
|
||||
if done(&local) {
|
||||
return local.map(|(shader, _)| shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Last: every mask and lane read per host wave.
|
||||
if !strict {
|
||||
for (name, f) in &forms {
|
||||
if let Some((p, st, io, res)) = f {
|
||||
let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
|
||||
report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local);
|
||||
if done(&local) {
|
||||
return local.map(|(shader, _)| shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
|
||||
report("local waves (APPROXIMATE, any mask)", &local);
|
||||
if done(&local) {
|
||||
return local.map(|(shader, _)| shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let original = original.map(|(shader, _)| shader);
|
||||
// Retry unsupported programs only. Threading can separate an unknown
|
||||
// register value from its apparent use on a mutually exclusive path.
|
||||
if !matches!(original, Err(ShaderError::Unsupported { .. })) {
|
||||
return original;
|
||||
}
|
||||
let edges = threading::constant_edges(p, st);
|
||||
if edges.is_empty() {
|
||||
return original;
|
||||
}
|
||||
let p = ir::thread_edges(p, &edges)?;
|
||||
let st = structure::structure(&p)?;
|
||||
let io = io::raise(&p, native)?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
|
||||
emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader)
|
||||
}
|
||||
|
||||
/// The translated program, and the wave size it requires of the host.
|
||||
fn emit_program(
|
||||
c: &Container,
|
||||
native: &NativeProgram,
|
||||
p: &ir::Program,
|
||||
st: &structure::Structured,
|
||||
io: &io::Io,
|
||||
res: &resource::Resources,
|
||||
) -> Result<(HostShader, Option<u32>), ShaderError> {
|
||||
let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
|
||||
match c.part(fourcc) {
|
||||
Some(part) => signature(part.data),
|
||||
@@ -241,6 +421,8 @@ pub fn emit(
|
||||
// Constant, as DXC declares it (the AMD compiler crashed on a
|
||||
// front face without a mode).
|
||||
(13, _) => 1,
|
||||
// Until a read says which mode (`lower`).
|
||||
(28, _) => 2,
|
||||
(0 | 6 | 7, 9) => 2,
|
||||
(0, _) => 1,
|
||||
_ => 0,
|
||||
@@ -289,7 +471,8 @@ pub fn emit(
|
||||
prims,
|
||||
mesh_stride,
|
||||
})?;
|
||||
Ok(HostShader {
|
||||
let wave_size = l.wave_size;
|
||||
let shader = HostShader {
|
||||
stage: native.stage,
|
||||
dxil: l.dxil,
|
||||
user_data: l.user_data,
|
||||
@@ -308,7 +491,10 @@ pub fn emit(
|
||||
samplers: l.samplers,
|
||||
root_cbvs: l.root_cbvs,
|
||||
root_srvs: l.root_srvs,
|
||||
})
|
||||
root_uavs: l.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views.clone(),
|
||||
};
|
||||
Ok((shader, wave_size))
|
||||
}
|
||||
|
||||
/// The rows of an `ISG1`/`OSG1` part.
|
||||
@@ -358,6 +544,7 @@ fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
|
||||
68 => 18,
|
||||
69 => 20,
|
||||
70 => 15,
|
||||
23 => 28, // barycentrics
|
||||
25 => 30, // cull primitive
|
||||
_ => {
|
||||
return Err(ShaderError::Unsupported {
|
||||
@@ -486,11 +673,12 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A wave64 compute program that writes only EXEC's high dword
|
||||
/// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is
|
||||
/// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was
|
||||
/// opaque and keyed by the unchanged low dword, so building its lane bit
|
||||
/// needed the mask's own value: lowering recursed until the stack
|
||||
/// overflowed, which takes the whole process down (found by
|
||||
/// random-input testing). Now the instruction fails like any other that
|
||||
/// random-input testing). Now that low dword, seen with two high
|
||||
/// dwords, has no mask, and the instruction fails like any other that
|
||||
/// cannot be expressed: its result is missing, and only a side effect
|
||||
/// that uses it would stop the translation.
|
||||
#[test]
|
||||
@@ -520,6 +708,108 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A wave64 compute program: `body`, then a store of v1 to a UAV.
|
||||
fn stores_v1(body: &[u32]) -> Result<(), ShaderError> {
|
||||
use crate::native::RootParam;
|
||||
use crate::{ResourceType, RootType, UsedResource};
|
||||
// s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0
|
||||
let mut words = vec![0xBE81_0380, 0xF408_0200, 0xFA00_0000];
|
||||
words.extend_from_slice(body);
|
||||
// v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen;
|
||||
// s_endpgm
|
||||
words.extend_from_slice(&[0x3406_0082, 0xE070_1000, 0x8002_0103, 0xBF81_0000]);
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: true,
|
||||
vgprs: 4,
|
||||
layout: vec![RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
used: vec![UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 4,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 2,
|
||||
threads: [64, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
|
||||
let res = resource::track(&p, &native.layout, native.stage, None).unwrap();
|
||||
let io = io::raise(&p, &native).unwrap();
|
||||
let st = structure::structure(&p).unwrap();
|
||||
let container = crate::dxbc::build(&[]);
|
||||
let c = Container::parse(&container).unwrap();
|
||||
emit(&c, &native, &p, &st, &io, &res).map(|_| ())
|
||||
}
|
||||
|
||||
/// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi`
|
||||
/// or `exec_hi`): lanes 32-63 took the mask the low dword was first
|
||||
/// written with (the compare's, EXEC's on entry). Now the store refuses;
|
||||
/// without the write it translates.
|
||||
#[test]
|
||||
fn a_mask_whose_high_dword_is_rewritten_is_refused() {
|
||||
// v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc
|
||||
let select = [0x7D84_0080, 0x7E04_028B, 0x0202_0480];
|
||||
// The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc.
|
||||
let carry = [0x7D84_0080, 0x7E04_028B, 0x5002_0480];
|
||||
// v_mov_b32 v1, 7
|
||||
let mov = [0x7E02_0287];
|
||||
for body in [&select[..], &carry, &mov] {
|
||||
stores_v1(body).unwrap();
|
||||
}
|
||||
// s_mov_b32 vcc_hi, 0 after the compare.
|
||||
let select_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x0202_0480];
|
||||
let carry_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x5002_0480];
|
||||
// s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after
|
||||
// s_mov_b64 s[2:3], exec.
|
||||
let exec_hi = [0xBEFF_0380, 0x7E02_0287];
|
||||
let exec_hi_saved = [0xBE82_047E, 0xBEFF_0380, 0x7E02_0287];
|
||||
for body in [&select_hi[..], &carry_hi, &exec_hi, &exec_hi_saved] {
|
||||
assert!(stores_v1(body).is_err(), "{body:x?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `ds_bpermute_b32` stores nothing: each lane reads the lane its address
|
||||
/// names. It stopped as "LDS the program does not allocate" (sticky lips)
|
||||
/// or "an LDS operation" (the checkerboard shadow masks).
|
||||
#[test]
|
||||
fn a_backward_permute_reads_the_lane_its_address_names() {
|
||||
// v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2
|
||||
stores_v1(&[0x7E04_028B, 0xDACC_0000, 0x0100_0200]).unwrap();
|
||||
}
|
||||
|
||||
/// A carry-in reading a join of compares after a divergent branch. A
|
||||
/// lane that skipped the inner compare has VCC clear there (VOPC clears
|
||||
/// inactive lanes), not the first compare's bit, so the join is no
|
||||
/// per-lane phi: lowering refuses it.
|
||||
#[test]
|
||||
fn a_carry_in_from_a_divergent_join_is_refused() {
|
||||
let body = [
|
||||
0x7E04_028B, // v_mov_b32 v2, 11
|
||||
0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
|
||||
0xBE82_376A, // s_andn1_saveexec_b64 s[2:3], vcc
|
||||
0xBF88_0001, // s_cbranch_execz 1
|
||||
0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0
|
||||
0x88FE_027E, // s_or_b64 exec, exec, s[2:3]
|
||||
0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc
|
||||
];
|
||||
let e = stores_v1(&body).unwrap_err().to_string();
|
||||
assert!(e.contains("a carry-in from an untracked mask"), "{e}");
|
||||
}
|
||||
|
||||
/// A pixel shader writing a constant colour.
|
||||
#[cfg(windows)]
|
||||
fn constant_color() -> Vec<u8> {
|
||||
@@ -565,6 +855,8 @@ mod tests {
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
let file = |var: &str, stage| {
|
||||
std::env::var(var).ok().map(|p| super::HostShader {
|
||||
@@ -575,6 +867,8 @@ mod tests {
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
root_indexed_views: Vec::new(),
|
||||
})
|
||||
};
|
||||
let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
|
||||
@@ -746,4 +1040,528 @@ mod tests {
|
||||
// Translated or refused with a reason; it must not panic.
|
||||
let _ = super::emit(&c, &native, &p, &st, &io, &res);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valu_div_f32_sequence_executes_on_gpu() {
|
||||
let words: &[u32] = &[
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0xF408_0202,
|
||||
0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
|
||||
0xF408_0302,
|
||||
0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
|
||||
0x340E_0083, // v_lshlrev_b32 v7, 3, v0
|
||||
0xE034_1000,
|
||||
0x8002_0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen
|
||||
0xD56D_6A03,
|
||||
0x0406_0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1
|
||||
0xD56D_1008,
|
||||
0x0406_0501, // v_div_scale_f32 v8, s16, v1, v2, v1
|
||||
0x7E08_5503, // v_rcp_f32 v4, v3
|
||||
0xD54B_0005,
|
||||
0x23CA_0903, // v_fma_f32 v5, -v3, v4, 1.0
|
||||
0xD54B_0004,
|
||||
0x0412_0905, // v_fma_f32 v4, v5, v4, v4
|
||||
0x100A_0908, // v_mul_f32 v5, v8, v4
|
||||
0xD54B_0006,
|
||||
0x2422_0B03, // v_fma_f32 v6, -v3, v5, v8
|
||||
0xD56F_0004,
|
||||
0x0416_0906, // v_div_fmas_f32 v4, v6, v4, v5
|
||||
0xD55F_0001,
|
||||
0x0406_0504, // v_div_fixup_f32 v1, v4, v2, v1
|
||||
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
|
||||
0xE070_1000,
|
||||
0x8003_0107, // buffer_store_dword v1, v7, s[12:15], 0 offen
|
||||
0xBF81_0000, // s_endpgm
|
||||
];
|
||||
let native = super::NativeProgram {
|
||||
stage: super::HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 9,
|
||||
layout: vec![
|
||||
crate::RootParam {
|
||||
root: crate::RootType::Constants,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 4,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
crate::RootParam {
|
||||
root: crate::RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
used: vec![
|
||||
crate::UsedResource {
|
||||
kind: crate::ResourceType::Srv,
|
||||
root: crate::RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
crate::UsedResource {
|
||||
kind: crate::ResourceType::Uav,
|
||||
root: crate::RootType::Table,
|
||||
table_offset_dwords: 8,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
io: crate::native::StageIo::Cs(crate::native::ComputeIo {
|
||||
rsrc2: 5 << 1,
|
||||
threads: [7, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap();
|
||||
let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap();
|
||||
let io = crate::io::raise(&p, &native).unwrap();
|
||||
let st = crate::structure::structure(&p).unwrap();
|
||||
let l = super::lower::lower(&super::lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})
|
||||
.unwrap();
|
||||
let mut dxil = l.dxil;
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) = super::validator::Validator::load(
|
||||
super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut dxil).unwrap();
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if let Ok(host) = super::host::Host::new(false) {
|
||||
let cs = super::HostShader {
|
||||
stage: super::HwStage::Cs,
|
||||
dxil,
|
||||
user_data: l.user_data,
|
||||
samplers: Vec::new(),
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: l.root_cbvs,
|
||||
root_srvs: l.root_srvs,
|
||||
root_uavs: l.root_uavs,
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
let (root, pso) = host.compute_pipeline(&cs).unwrap();
|
||||
let inputs: Vec<u32> = [
|
||||
7.0f32, 3.0, -1.0, 1e-40, 1.0, 1e35, 1e-35, 1e-36, 0.0, 0.0, -1.0, 0.0, -1e35, 1e35,
|
||||
]
|
||||
.into_iter()
|
||||
.map(f32::to_bits)
|
||||
.collect();
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&super::host::Dispatch {
|
||||
roots: vec![(0, super::host::Root::Constants(vec![0, 0, 0, 0, 0]))],
|
||||
views: &[
|
||||
super::host::View::Buffer {
|
||||
data: &inputs,
|
||||
stride: super::host::Stride::Raw,
|
||||
},
|
||||
super::host::View::RawUav(64),
|
||||
],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let got: Vec<f32> = out[0][..7].iter().copied().map(f32::from_bits).collect();
|
||||
assert!((got[0] - (7.0f32 / 3.0)).abs() < 1e-6, "got {:?}", got);
|
||||
assert_eq!(out[0][1], (-1.0f32 / 1e-40).to_bits());
|
||||
assert!(
|
||||
(got[2] - 1e-35).abs() <= 1e-40,
|
||||
"lane 2 got {:?} ({:#x})",
|
||||
got[2],
|
||||
out[0][2]
|
||||
);
|
||||
assert!(
|
||||
(got[3] - 10.0).abs() < 1e-5,
|
||||
"lane 3 got {:?} ({:#x})",
|
||||
got[3],
|
||||
out[0][3]
|
||||
);
|
||||
assert_eq!(out[0][4], 0xFFC0_0000);
|
||||
assert_eq!(out[0][5], (-1.0f32 / 0.0).to_bits());
|
||||
assert!(
|
||||
(got[6] - (-1.0)).abs() < 1e-6,
|
||||
"lane 6 got {:?} ({:#x})",
|
||||
got[6],
|
||||
out[0][6]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod atomic_tests {
|
||||
use super::*;
|
||||
use crate::native::{ComputeIo, RootParam, StageIo};
|
||||
|
||||
#[test]
|
||||
fn heap_texture_atomic_widths() {
|
||||
// A synthetic compute shader loads a 2D UAV from a root table,
|
||||
// compares or adds at (0, 0), then uses the returned register(s).
|
||||
for (opcode, mask, wide) in [
|
||||
(16u32, 3, false),
|
||||
(16, 15, true),
|
||||
(17, 1, false),
|
||||
(17, 3, true),
|
||||
] {
|
||||
let words = [
|
||||
0xBE81_0380, // s_mov_b32 s1, 0 (table address high)
|
||||
0xF40C_0200,
|
||||
0xFA00_0000, // s_load_dwordx8 s[8:15], s[0:1], 0
|
||||
0x7E00_0280,
|
||||
0x7E02_0280, // v0, v1 = coordinates
|
||||
0x7E04_0281,
|
||||
0x7E06_0282,
|
||||
0x7E08_0283,
|
||||
0x7E0A_0284, // v2..v5 = 1..4
|
||||
0xF000_2008 | opcode << 18 | mask << 8,
|
||||
0x0002_0200,
|
||||
// Use the old value in a second atomic at the same location.
|
||||
0xF044_0008 | (if wide { 3 } else { 1 }) << 8,
|
||||
0x0002_0200,
|
||||
0xBF81_0000,
|
||||
];
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 6,
|
||||
layout: vec![RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
used: vec![],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 2,
|
||||
threads: [32, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let p = ir::build(&native.code, false, native.vgprs).unwrap();
|
||||
let bytes = crate::dxbc::build(&[]);
|
||||
let shader = emit(
|
||||
&Container::parse(&bytes).unwrap(),
|
||||
&native,
|
||||
&p,
|
||||
&structure::structure(&p).unwrap(),
|
||||
&io::raise(&p, &native).unwrap(),
|
||||
&resource::track(&p, &native.layout, native.stage, None).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let container = Container::parse(&shader.dxil).unwrap();
|
||||
let features = u64::from_le_bytes(
|
||||
container
|
||||
.part(FourCC::SFI0)
|
||||
.unwrap()
|
||||
.data
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
let required = 0x1040_8000; // heap atomics, typed atomics, Int64Ops
|
||||
assert_eq!(features & required, if wide { required } else { 0 });
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) =
|
||||
validator::Validator::load(validator::Validator::default_path().as_deref())
|
||||
{
|
||||
v.validate(&mut shader.dxil.clone()).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod barycentric_tests {
|
||||
use super::container::SigElement;
|
||||
use super::*;
|
||||
use crate::native::{PsInput, StageIo, Usage};
|
||||
|
||||
/// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER.
|
||||
const PERSP_CENTER: u32 = 1 << 1;
|
||||
const LINEAR_CENTER: u32 = 1 << 5;
|
||||
|
||||
/// `exp mrt0, v<r>, v<r>, v<r>, v<r> done vm`.
|
||||
fn exp_mrt0(r: u32) -> [u32; 2] {
|
||||
[0xF800_180F, r * 0x0101_0101]
|
||||
}
|
||||
|
||||
/// VOP2 `v_add_f32 v<dst>, v<a>, v<b>`.
|
||||
fn v_add_f32(dst: u32, a: u32, b: u32) -> u32 {
|
||||
3 << 25 | dst << 17 | b << 9 | (256 + a)
|
||||
}
|
||||
|
||||
fn element(name: &str, kind: u8, row: u32) -> SigElement {
|
||||
SigElement {
|
||||
name: name.into(),
|
||||
index: 0,
|
||||
kind,
|
||||
comp: 9,
|
||||
interp: 0,
|
||||
row: Some(row),
|
||||
col: 0,
|
||||
cols: 4,
|
||||
usage: 0,
|
||||
half: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates a pixel program with the input VGPRs `input_addr`
|
||||
/// enables and one float4 TEXCOORD0 attribute (attr 0, row 0).
|
||||
fn pixel(words: &[u32], input_addr: u32) -> Result<HostShader, ShaderError> {
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Ps,
|
||||
wave64: false,
|
||||
vgprs: 8,
|
||||
layout: vec![],
|
||||
used: vec![],
|
||||
io: StageIo::Ps {
|
||||
inputs: vec![PsInput {
|
||||
usage: Usage::Generic,
|
||||
row: 0,
|
||||
mask: 0b1111,
|
||||
attr: 0,
|
||||
flat: false,
|
||||
fp16: false,
|
||||
pack2: false,
|
||||
row2: 0,
|
||||
}],
|
||||
input_addr,
|
||||
db_shader_control: 0,
|
||||
patches: vec![],
|
||||
},
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let mut target = element("SV_Target", 16, 0);
|
||||
target.usage = 15;
|
||||
let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true);
|
||||
let osg1 = container::signature(&[target], false);
|
||||
let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]);
|
||||
let c = Container::parse(&bytes).unwrap();
|
||||
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, None)?;
|
||||
let io = io::raise(&p, &native)?;
|
||||
let st = structure::structure(&p)?;
|
||||
emit(&c, &native, &p, &st, &io, &res)
|
||||
}
|
||||
|
||||
/// The translation's `SFI0` features and `ISG1` rows.
|
||||
fn parts(shader: &HostShader) -> (u64, Vec<SigElement>) {
|
||||
let c = Container::parse(&shader.dxil).unwrap();
|
||||
let sfi0 = c.part(FourCC::SFI0).unwrap().data.try_into().unwrap();
|
||||
(
|
||||
u64::from_le_bytes(sfi0),
|
||||
signature(c.part(FourCC::ISG1).unwrap().data).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn validate(shader: &HostShader) {
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) =
|
||||
validator::Validator::load(validator::Validator::default_path().as_deref())
|
||||
{
|
||||
v.validate(&mut shader.dxil.clone()).unwrap();
|
||||
}
|
||||
let _ = shader;
|
||||
}
|
||||
|
||||
/// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as
|
||||
/// plain floats: they are channels y and z of `SV_Barycentrics`, the
|
||||
/// weights of vertices 1 and 2.
|
||||
#[test]
|
||||
fn barycentrics_read_as_values_are_sv_barycentrics() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (features, inputs) = parts(&shader);
|
||||
assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
|
||||
let bary: Vec<_> = inputs.iter().filter(|e| e.kind == 28).collect();
|
||||
assert_eq!(bary.len(), 1, "{inputs:?}");
|
||||
assert_eq!((bary[0].index, bary[0].col, bary[0].cols), (0, 0, 3));
|
||||
// Not packed: the validator wants packing location -1.
|
||||
assert_eq!(bary[0].row, None);
|
||||
// Only y and z (I and J) are read.
|
||||
let isg1 = Container::parse(&shader.dxil).unwrap();
|
||||
let isg1 = isg1.part(FourCC::ISG1).unwrap().data;
|
||||
let rw: Vec<u8> = (0..2).map(|k| isg1[8 + 32 * k + 25]).collect();
|
||||
assert!(rw.contains(&0b110), "{rw:?}");
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// Two kinds of barycentrics read directly: one element per mode.
|
||||
#[test]
|
||||
fn two_barycentric_modes_get_two_elements() {
|
||||
// v0-v1 perspective i, j; v2-v3 linear i, j.
|
||||
let [e0, e1] = exp_mrt0(4);
|
||||
let words = [v_add_f32(4, 0, 3), e0, e1, 0xBF81_0000];
|
||||
let shader = pixel(&words, PERSP_CENTER | LINEAR_CENTER).unwrap();
|
||||
let (_, inputs) = parts(&shader);
|
||||
let mut indices: Vec<u32> = inputs
|
||||
.iter()
|
||||
.filter(|e| e.kind == 28)
|
||||
.map(|e| e.index)
|
||||
.collect();
|
||||
indices.sort();
|
||||
assert_eq!(indices, [0, 1], "{inputs:?}");
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// I and J only fed to `v_interp_*` stay host interpolation: no
|
||||
/// barycentrics are declared.
|
||||
#[test]
|
||||
fn interpolation_alone_declares_no_barycentrics() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [
|
||||
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
e0,
|
||||
e1,
|
||||
0xBF81_0000,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (features, inputs) = parts(&shader);
|
||||
assert_eq!(features & 0x2_0000, 0);
|
||||
assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// Both: the attribute is interpolated and J is used as a value.
|
||||
#[test]
|
||||
fn interpolation_and_a_barycentric_value_together() {
|
||||
let [e0, e1] = exp_mrt0(3);
|
||||
let words = [
|
||||
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
v_add_f32(3, 2, 1), // v3 = attribute + j
|
||||
e0,
|
||||
e1,
|
||||
0xBF81_0000,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (features, inputs) = parts(&shader);
|
||||
assert_ne!(features & 0x2_0000, 0);
|
||||
assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
|
||||
validate(&shader);
|
||||
}
|
||||
/// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float).
|
||||
fn texcoord_mode(shader: &HostShader) -> u8 {
|
||||
let c = Container::parse(&shader.dxil).unwrap();
|
||||
let psv = c.part(FourCC::PSV0).unwrap().data;
|
||||
let row = [1, 0, 0x44, 0, 3];
|
||||
let at = psv.windows(5).position(|w| w == row).unwrap();
|
||||
psv[at + 5]
|
||||
}
|
||||
|
||||
const S_ENDPGM: u32 = 0xBF81_0000;
|
||||
|
||||
/// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads
|
||||
/// the attribute's vertices: TEXCOORD0 becomes constant, read with
|
||||
/// `attributeAtVertex`; i and j are `SV_Barycentrics` values.
|
||||
#[test]
|
||||
fn computed_barycentrics_read_the_vertices() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [
|
||||
0x1006_00F0, // v_mul_f32 v3, 0.5, v0
|
||||
0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
e0,
|
||||
e1,
|
||||
S_ENDPGM,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (features, inputs) = parts(&shader);
|
||||
assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
|
||||
assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
|
||||
assert_eq!(texcoord_mode(&shader), 1);
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// Weights from constants alone: the vertices, no `SV_Barycentrics`.
|
||||
#[test]
|
||||
fn constant_weights_need_no_barycentrics() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [
|
||||
0x7E06_02F0, // v_mov_b32 v3, 0.5
|
||||
0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
|
||||
0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
|
||||
e0,
|
||||
e1,
|
||||
S_ENDPGM,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (features, inputs) = parts(&shader);
|
||||
assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
|
||||
assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
|
||||
assert_eq!(texcoord_mode(&shader), 1);
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// The same attribute interpolated with the loaded i and j and with a
|
||||
/// computed j: both from its vertices, the first weighed with
|
||||
/// `SV_Barycentrics`.
|
||||
#[test]
|
||||
fn computed_and_loaded_barycentrics_on_one_attribute() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [
|
||||
0xC810_0100, // v_interp_p1_f32 v4, v0, attr0.y
|
||||
0xC811_0101, // v_interp_p2_f32 v4, v1, attr0.y
|
||||
0x1006_02F0, // v_mul_f32 v3, 0.5, v1
|
||||
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
|
||||
0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
|
||||
v_add_f32(2, 2, 4),
|
||||
e0,
|
||||
e1,
|
||||
S_ENDPGM,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (_, inputs) = parts(&shader);
|
||||
assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
|
||||
assert_eq!(texcoord_mode(&shader), 1);
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// P10 of an attribute the program interpolates is P1 - P0.
|
||||
#[test]
|
||||
fn p10_of_an_interpolated_attribute() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [
|
||||
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
0xC812_0000, // v_interp_mov_f32 v4, p10, attr0.x
|
||||
v_add_f32(2, 2, 4),
|
||||
e0,
|
||||
e1,
|
||||
S_ENDPGM,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
assert_eq!(texcoord_mode(&shader), 1);
|
||||
validate(&shader);
|
||||
// Alone, what the hardware holds is not known.
|
||||
let [e0, e1] = exp_mrt0(4);
|
||||
let words = [0xC812_0000, e0, e1, S_ENDPGM];
|
||||
assert!(pixel(&words, PERSP_CENTER).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
//! The geometry shader that completes the console's rectangle lists (list
|
||||
//! topology 17, pipeline topology type 19). A rectangle comes as three
|
||||
//! vertices, three corners of a screen-aligned rectangle; the hardware
|
||||
//! draws the whole rectangle and continues every vertex shader output
|
||||
//! linearly into the fourth corner. The host has no such topology: the
|
||||
//! draw goes out as a triangle list with this shader behind the translated
|
||||
//! vertex shader, so vertex counts, vertex numbers, indices and indirect
|
||||
//! arguments stay the title's, and each rectangle arrives here as one
|
||||
//! triangle.
|
||||
//!
|
||||
//! Which vertex is the corner between the other two varies: Grand Theft
|
||||
//! Auto VI's full-screen rectangles come as top left, bottom left, bottom
|
||||
//! right (the second), its tiled lighting as top left, bottom left, top
|
||||
//! right (the first). The corner is the vertex that shares x with one of
|
||||
//! the others and y with the other; the fourth vertex lies opposite it,
|
||||
//! `a + b - corner` for the position and every float output. That holds
|
||||
//! for three vertices with one positive w (then it is the same in clip
|
||||
//! space and on the screen, whatever the interpolation mode); three that
|
||||
//! differ in w, or are not such corners, stay the triangle they make.
|
||||
//!
|
||||
//! Flat values are the first vertex's: both triangles start with it (the
|
||||
//! halves on either side of the diagonal through it, turning as the three
|
||||
//! vertices do), which is the vertex the host takes a flat input from, and
|
||||
//! the fourth vertex's integer outputs are the first vertex's.
|
||||
//!
|
||||
//! shortcut: that the console takes a rectangle's flat values from its
|
||||
//! first vertex follows from the hardware's provoking-vertex setting for
|
||||
//! triangles; it is not measured on a rectangle.
|
||||
|
||||
use super::bitcode::{Attr, Bin, Term, V, pred};
|
||||
use super::container::SigElement;
|
||||
use super::shader::{Geometry, Shader};
|
||||
use crate::ShaderError;
|
||||
use crate::dxbc::{Container, FourCC};
|
||||
|
||||
/// Vertices emitted per rectangle: two triangles.
|
||||
const VERTICES: u32 = 6;
|
||||
|
||||
/// The scalars a geometry shader may emit per invocation (vertices times
|
||||
/// output components).
|
||||
const MAX_SCALARS: u32 = 1024;
|
||||
|
||||
/// The geometry shader (a DXIL container) for rectangle lists drawn with
|
||||
/// the translated vertex shader `vs` and, if the pipeline has one, the
|
||||
/// translated pixel shader `ps` (both as [`super::HostShader::dxil`]). Its
|
||||
/// inputs and outputs are the vertex shader's outputs, register for
|
||||
/// register, so it links with both. A pixel shader that declares a
|
||||
/// primitive id gets the rectangle's number, which the host leaves to the
|
||||
/// geometry stage when there is one.
|
||||
pub fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> {
|
||||
let sig = |dxil: &[u8], fourcc| -> Result<Vec<SigElement>, ShaderError> {
|
||||
let c = Container::parse(dxil)?;
|
||||
match c.part(fourcc) {
|
||||
Some(part) => super::signature(part.data),
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
};
|
||||
let outputs = sig(vs, FourCC::OSG1)?;
|
||||
let wanted = match ps {
|
||||
Some(ps) => sig(ps, FourCC::ISG1)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
build(outputs, &wanted)
|
||||
}
|
||||
|
||||
/// [`rect_list_gs`] from the vertex shader's outputs and the pixel
|
||||
/// shader's inputs.
|
||||
fn build(mut outputs: Vec<SigElement>, ps_inputs: &[SigElement]) -> Result<Vec<u8>, ShaderError> {
|
||||
let unsupported = |what| ShaderError::Unsupported { offset: 0, what };
|
||||
if outputs.iter().any(|e| e.row.is_none()) {
|
||||
return Err(unsupported("a rectangle list output without a register"));
|
||||
}
|
||||
let Some(position) = outputs
|
||||
.iter()
|
||||
.position(|e| e.kind == 3 && e.comp == 9 && e.cols == 4)
|
||||
else {
|
||||
return Err(unsupported("a rectangle list without a four-component position"));
|
||||
};
|
||||
for e in &mut outputs {
|
||||
// Interpolation as `emit_program` declares a vertex shader's
|
||||
// outputs; a geometry shader's inputs carry the same modes.
|
||||
e.interp = match (e.kind, e.comp) {
|
||||
(3, _) => 4,
|
||||
(0 | 6 | 7, 9) => 2,
|
||||
(0, _) => 1,
|
||||
_ => 0,
|
||||
};
|
||||
e.usage = (1 << e.cols) - 1;
|
||||
}
|
||||
let mut s = Shader::new(false);
|
||||
s.geometry = Some(Geometry {
|
||||
max_vertices: VERTICES,
|
||||
});
|
||||
s.inputs = outputs.clone();
|
||||
// The primitive id the pixel shader declares, as one more output.
|
||||
let wanted = ps_inputs
|
||||
.iter()
|
||||
.find(|e| e.kind == 10 && e.row.is_some())
|
||||
.filter(|_| !outputs.iter().any(|o| o.kind == 10));
|
||||
let primitive = match wanted {
|
||||
Some(e) => {
|
||||
// Alone in its columns, and in a row of constant elements.
|
||||
let clash = outputs.iter().any(|o| {
|
||||
let overlap = o.col < e.col + e.cols && e.col < o.col + o.cols;
|
||||
o.row == e.row && (o.interp != 1 || overlap)
|
||||
});
|
||||
if clash {
|
||||
return Err(unsupported(
|
||||
"a rectangle list whose primitive id shares a register with a vertex output",
|
||||
));
|
||||
}
|
||||
outputs.push(SigElement {
|
||||
interp: 1,
|
||||
usage: (1 << e.cols) - 1,
|
||||
..e.clone()
|
||||
});
|
||||
Some(outputs.len() - 1)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let scalars: u32 = outputs.iter().map(|e| u32::from(e.cols)).sum();
|
||||
if scalars * VERTICES > MAX_SCALARS {
|
||||
return Err(unsupported(
|
||||
"a rectangle list with more output components than a geometry shader emits",
|
||||
));
|
||||
}
|
||||
s.outputs = outputs;
|
||||
let b = s.entry;
|
||||
|
||||
// Every input of the three vertices: [element][column][vertex].
|
||||
let mut corners: Vec<Vec<[V; 3]>> = Vec::new();
|
||||
for id in 0..s.inputs.len() {
|
||||
let mut columns = Vec::new();
|
||||
for col in 0..s.inputs[id].cols {
|
||||
columns.push([0, 1, 2].map(|vertex| load(&mut s, id, col, vertex)));
|
||||
}
|
||||
corners.push(columns);
|
||||
}
|
||||
|
||||
// One positive w, and no two vertices in one place.
|
||||
let (x, y, w) = (
|
||||
corners[position][0],
|
||||
corners[position][1],
|
||||
corners[position][3],
|
||||
);
|
||||
let zero = s.m.f32(0);
|
||||
let mut plain = s.m.cmp(b, pred::OGT, w[0], zero);
|
||||
for &other in &w[1..] {
|
||||
let one_w = same(&mut s, other, w[0]);
|
||||
plain = both(&mut s, plain, one_w);
|
||||
}
|
||||
for (i, j) in [(0, 1), (0, 2), (1, 2)] {
|
||||
let (same_x, same_y) = (same(&mut s, x[i], x[j]), same(&mut s, y[i], y[j]));
|
||||
let together = both(&mut s, same_x, same_y);
|
||||
let apart = not(&mut s, together);
|
||||
plain = both(&mut s, plain, apart);
|
||||
}
|
||||
// corner[i]: vertex i is the corner between the other two (the first
|
||||
// that shares x with one of them and y with the other).
|
||||
let mut corner: Vec<V> = Vec::new();
|
||||
for i in 0..3 {
|
||||
let (a, c) = ((i + 1) % 3, (i + 2) % 3);
|
||||
let (xa, yc) = (same(&mut s, x[i], x[a]), same(&mut s, y[i], y[c]));
|
||||
let (xc, ya) = (same(&mut s, x[i], x[c]), same(&mut s, y[i], y[a]));
|
||||
let (one, other) = (both(&mut s, xa, yc), both(&mut s, xc, ya));
|
||||
let shares = either(&mut s, one, other);
|
||||
let mut here = both(&mut s, shares, plain);
|
||||
for &found in &corner {
|
||||
let earlier = not(&mut s, found);
|
||||
here = both(&mut s, here, earlier);
|
||||
}
|
||||
corner.push(here);
|
||||
}
|
||||
|
||||
// What the six emitted vertices carry: [element][column][vertex].
|
||||
let mut emitted: Vec<Vec<[V; 6]>> = Vec::new();
|
||||
for (id, columns) in corners.iter().enumerate() {
|
||||
let float = s.inputs[id].comp == 9;
|
||||
let mut out = Vec::new();
|
||||
for &[p0, p1, p2] in columns {
|
||||
// The fourth vertex: `a + b - corner`. Integers (flat), and
|
||||
// three vertices without a corner, keep the first vertex's
|
||||
// value; the second triangle of the latter is then empty.
|
||||
let mut fourth = p0;
|
||||
if float {
|
||||
for (k, (a, c, at)) in [(p1, p2, p0), (p2, p0, p1), (p0, p1, p2)]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let sum = s.m.bin(b, Bin::Add, a, c);
|
||||
let opposite = s.m.bin(b, Bin::Sub, sum, at);
|
||||
fourth = s.m.select(b, corner[k], opposite, fourth);
|
||||
}
|
||||
}
|
||||
// Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1,
|
||||
// v2), (v0, v2, v3). Third: (v0, v1, v2), (v0, v3, v1).
|
||||
let third = s.m.select(b, corner[0], fourth, p2);
|
||||
let fifth = s.m.select(b, corner[1], p2, fourth);
|
||||
let sixth = s.m.select(b, corner[0], p2, p1);
|
||||
let sixth = s.m.select(b, corner[1], fourth, sixth);
|
||||
out.push([p0, p1, third, p0, fifth, sixth]);
|
||||
}
|
||||
emitted.push(out);
|
||||
}
|
||||
|
||||
// The rectangle's number: the triangle's, three vertices a rectangle.
|
||||
let mut number = None;
|
||||
if let Some(id) = primitive {
|
||||
let n = s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[]);
|
||||
number = Some((id, n));
|
||||
}
|
||||
let stream = s.m.i8(0);
|
||||
for vertex in 0..VERTICES as usize {
|
||||
for (id, columns) in emitted.iter().enumerate() {
|
||||
let name = if s.outputs[id].comp == 9 {
|
||||
"storeOutput.f32"
|
||||
} else {
|
||||
"storeOutput.i32"
|
||||
};
|
||||
for (col, values) in columns.iter().enumerate() {
|
||||
let args = [
|
||||
s.m.i32(id as u32),
|
||||
s.m.i32(0),
|
||||
s.m.i8(col as u8),
|
||||
values[vertex],
|
||||
];
|
||||
s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
}
|
||||
if let Some((id, n)) = number {
|
||||
let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(0), n];
|
||||
s.op(b, "storeOutput.i32", Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]);
|
||||
// The strip ends after the first triangle.
|
||||
if vertex == 2 {
|
||||
s.op(b, "cutStream", Attr::NoUnwind, s.t.void, 98, &[stream]);
|
||||
}
|
||||
}
|
||||
s.m.terminate(b, Term::Ret);
|
||||
Ok(s.finish())
|
||||
}
|
||||
|
||||
/// Column `col` of input `id` at vertex `vertex` of the triangle.
|
||||
fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V {
|
||||
let (name, ty) = if s.inputs[id].comp == 9 {
|
||||
("loadInput.f32", s.t.f32)
|
||||
} else {
|
||||
("loadInput.i32", s.t.i32)
|
||||
};
|
||||
let args = [
|
||||
s.m.i32(id as u32),
|
||||
s.m.i32(0),
|
||||
s.m.i8(col),
|
||||
s.m.i32(vertex),
|
||||
];
|
||||
let entry = s.entry;
|
||||
s.op(entry, name, Attr::ReadNone, ty, 4, &args)
|
||||
}
|
||||
|
||||
/// Two floats are equal.
|
||||
fn same(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.cmp(entry, pred::OEQ, a, b)
|
||||
}
|
||||
|
||||
fn both(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.bin(entry, Bin::And, a, b)
|
||||
}
|
||||
|
||||
fn either(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.bin(entry, Bin::Or, a, b)
|
||||
}
|
||||
|
||||
fn not(s: &mut Shader, a: V) -> V {
|
||||
let (entry, on) = (s.entry, s.m.bool(true));
|
||||
s.m.bin(entry, Bin::Xor, a, on)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn element(name: &str, index: u32, kind: u8, comp: u8, row: u32, cols: u8) -> SigElement {
|
||||
SigElement {
|
||||
name: name.into(),
|
||||
index,
|
||||
kind,
|
||||
comp,
|
||||
interp: 0,
|
||||
row: Some(row),
|
||||
col: 0,
|
||||
cols,
|
||||
usage: 0,
|
||||
half: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A position, a float interpolant and an integer one.
|
||||
fn outputs() -> Vec<SigElement> {
|
||||
vec![
|
||||
element("SV_Position", 0, 3, 9, 0, 4),
|
||||
element("TEXCOORD", 0, 0, 9, 1, 4),
|
||||
element("TEXCOORD", 1, 0, 5, 2, 2),
|
||||
]
|
||||
}
|
||||
|
||||
/// The stage is a geometry shader of triangles in and six strip
|
||||
/// vertices out, with the vertex shader's outputs on both sides and
|
||||
/// the primitive id the pixel shader declares; the validator, where
|
||||
/// there is one, accepts it.
|
||||
#[test]
|
||||
fn the_rectangle_stage_is_a_geometry_shader() {
|
||||
let wanted = [element("SV_PrimitiveID", 0, 10, 5, 3, 1)];
|
||||
let gs = build(outputs(), &wanted).unwrap();
|
||||
let c = Container::parse(&gs).unwrap();
|
||||
// Program version: geometry (2), shader model 6.6.
|
||||
assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0]);
|
||||
let psv = c.part(FourCC::PSV0).unwrap().data;
|
||||
// Triangles in, triangle strips out, stream 0, a position.
|
||||
assert_eq!(psv[4..17], [3, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 1]);
|
||||
// Geometry stage, six vertices, three inputs, four outputs.
|
||||
assert_eq!(psv[28..34], [2, 0, 6, 0, 3, 4]);
|
||||
let sig = |fourcc| super::super::signature(c.part(fourcc).unwrap().data).unwrap();
|
||||
let (ins, outs) = (sig(FourCC::ISG1), sig(FourCC::OSG1));
|
||||
assert_eq!(ins.len(), 3);
|
||||
assert_eq!(outs.len(), 4);
|
||||
for (i, o) in ins.iter().zip(&outs) {
|
||||
assert_eq!((&i.name, i.index, i.row), (&o.name, o.index, o.row));
|
||||
assert_eq!((i.col, i.cols, i.comp), (o.col, o.cols, o.comp));
|
||||
}
|
||||
assert_eq!((outs[3].kind, outs[3].row), (10, Some(3)));
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) = super::super::validator::Validator::load(
|
||||
super::super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut gs.clone()).unwrap();
|
||||
let plain = build(outputs(), &[]).unwrap();
|
||||
v.validate(&mut plain.clone()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Refused with a reason: no position, a primitive id in a register a
|
||||
/// vertex output has, more components than six vertices may carry.
|
||||
#[test]
|
||||
fn rectangle_stages_that_cannot_be_made_are_refused() {
|
||||
assert!(build(outputs()[1..].to_vec(), &[]).is_err());
|
||||
let taken = [element("SV_PrimitiveID", 0, 10, 5, 1, 1)];
|
||||
assert!(build(outputs(), &taken).is_err());
|
||||
let mut many = vec![element("SV_Position", 0, 3, 9, 0, 4)];
|
||||
many.extend((1..=43).map(|row| element("TEXCOORD", row - 1, 0, 9, row, 4)));
|
||||
assert!(build(many, &[]).is_err());
|
||||
}
|
||||
|
||||
/// A vertex shader that passes a position and a float4 through, and a
|
||||
/// pixel shader that writes the float4.
|
||||
#[cfg(windows)]
|
||||
fn pass_through() -> (super::super::HostShader, super::super::HostShader) {
|
||||
let position = SigElement {
|
||||
interp: 4,
|
||||
usage: 15,
|
||||
..element("SV_Position", 0, 3, 9, 0, 4)
|
||||
};
|
||||
let coord = SigElement {
|
||||
interp: 2,
|
||||
usage: 15,
|
||||
..element("TEXCOORD", 0, 0, 9, 1, 4)
|
||||
};
|
||||
let mut vs = Shader::new(false);
|
||||
vs.inputs = vec![
|
||||
SigElement {
|
||||
usage: 15,
|
||||
..element("POSITION", 0, 0, 9, 0, 4)
|
||||
},
|
||||
SigElement {
|
||||
interp: 0,
|
||||
..coord.clone()
|
||||
},
|
||||
];
|
||||
vs.outputs = vec![position.clone(), coord.clone()];
|
||||
let mut ps = Shader::new(true);
|
||||
ps.inputs = vec![
|
||||
SigElement {
|
||||
usage: 0,
|
||||
..position
|
||||
},
|
||||
coord,
|
||||
];
|
||||
ps.outputs = vec![SigElement {
|
||||
usage: 15,
|
||||
..element("SV_Target", 0, 16, 9, 0, 4)
|
||||
}];
|
||||
// Vertex: output id from input id. Pixel: target 0 from input 1.
|
||||
for (s, copies) in [(&mut vs, &[(0, 0), (1, 1)][..]), (&mut ps, &[(1, 0)][..])] {
|
||||
let b = s.entry;
|
||||
for &(from, to) in copies {
|
||||
for col in 0..4 {
|
||||
let args = [s.m.i32(from), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)];
|
||||
let v = s.op(b, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args);
|
||||
let args = [s.m.i32(to), s.m.i32(0), s.m.i8(col), v];
|
||||
s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
}
|
||||
s.m.terminate(b, Term::Ret);
|
||||
}
|
||||
let host = |stage, s: Shader| super::super::HostShader {
|
||||
stage,
|
||||
dxil: s.finish(),
|
||||
user_data: Vec::new(),
|
||||
samplers: Vec::new(),
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
(
|
||||
host(crate::native::HwStage::Vs, vs),
|
||||
host(crate::native::HwStage::Ps, ps),
|
||||
)
|
||||
}
|
||||
|
||||
/// Three corners of the whole target, the corner between the other two
|
||||
/// first (as the tiled lighting sends its tiles), second (as
|
||||
/// full-screen rectangles come) or third: with the stage every texel
|
||||
/// is drawn and the interpolant continues into the fourth corner's
|
||||
/// half; without it part of the target is not drawn.
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn rectangles_are_drawn_whole() {
|
||||
use super::super::host::{Draw, Host};
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 device; skipped");
|
||||
return;
|
||||
};
|
||||
let (vs, ps) = pass_through();
|
||||
if let Ok(mut v) = super::super::validator::Validator::load(
|
||||
super::super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut vs.dxil.clone()).unwrap();
|
||||
v.validate(&mut ps.dxil.clone()).unwrap();
|
||||
}
|
||||
let gs = rect_list_gs(&vs.dxil, Some(&ps.dxil[..])).unwrap();
|
||||
let root = host.root_signature(&vs, &ps).unwrap();
|
||||
// Position (z 0.5, w 1) and an interpolant that is the position.
|
||||
let vertex = |(x, y): (f32, f32)| [x, y, 0.5, 1.0, x, y, 0.0, 1.0];
|
||||
for (name, corners) in [
|
||||
("corner first", [(-1.0, 1.0), (-1.0, -1.0), (1.0, 1.0)]),
|
||||
("corner second", [(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)]),
|
||||
("corner third", [(-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]),
|
||||
] {
|
||||
let vertices = corners.map(vertex).concat();
|
||||
let draw = |gs: Option<&[u8]>| {
|
||||
let pso = host
|
||||
.pipeline_with_gs(&root, &vs.dxil, gs, &ps.dxil)
|
||||
.unwrap();
|
||||
let d = Draw {
|
||||
roots: Vec::new(),
|
||||
textures: &[],
|
||||
samplers: &[],
|
||||
vertices: &vertices,
|
||||
stride: 32,
|
||||
size: (8, 8),
|
||||
mesh_groups: 0,
|
||||
};
|
||||
host.draw(&root, &pso, &d).unwrap()
|
||||
};
|
||||
let whole = draw(Some(&gs[..]));
|
||||
for (i, texel) in whole.iter().enumerate() {
|
||||
let (x, y) = ((i % 8) as f32, (i / 8) as f32);
|
||||
let want = [(x + 0.5) / 4.0 - 1.0, 1.0 - (y + 0.5) / 4.0, 0.0, 1.0];
|
||||
assert!(
|
||||
texel.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4),
|
||||
"{name}: texel {i} is {texel:?}, not {want:?}"
|
||||
);
|
||||
}
|
||||
let half = draw(None);
|
||||
let missing = half.iter().zip(&whole).filter(|(a, b)| a != b).count();
|
||||
assert!(missing >= 24, "{name}: only {missing} texels need the stage");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,13 +13,73 @@ pub const SAMPLER_SPACE: u32 = 0;
|
||||
/// `t<root parameter index>` in this space.
|
||||
pub const ROOT_CBV_SPACE: u32 = 1;
|
||||
|
||||
/// The root SRV `t<SLOT_STRIDES>` in [`ROOT_CBV_SPACE`] of a shader that
|
||||
/// reads buffers through descriptors it picks from the view heap at an
|
||||
/// index it computes (SM 6.6 dynamic resources): a raw buffer of
|
||||
/// [`SLOT_STRIDES_COUNT`] dwords the host keeps, dword `i` the bytes per
|
||||
/// element of the buffer view at heap slot `i` (0: none or not a buffer).
|
||||
/// The console's descriptor holds that stride and its hardware multiplies
|
||||
/// the element index by it; the program's code does not say it, and the
|
||||
/// used-resource list only names what tables hold. A shader that has this
|
||||
/// root SRV also tells the host that the buffer views of the whole heap
|
||||
/// must be ready when it runs, not only those its tables name.
|
||||
pub const SLOT_STRIDES: u8 = 255;
|
||||
/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it.
|
||||
pub const SLOT_STRIDES_COUNT: u32 = 1 << 21;
|
||||
|
||||
/// Title memory by address (`resource::MEMORY`): console code reads and
|
||||
/// writes through raw 40-bit addresses it takes from root constants,
|
||||
/// descriptors and other memory (the ray-tracing structure builder and the
|
||||
/// programs that walk its structures). The host keeps copies of the title
|
||||
/// memory shaders use; a shader with such an access finds the copy by the
|
||||
/// address:
|
||||
///
|
||||
/// - the root SRV `t<SLOT_MEMORY>` in [`ROOT_CBV_SPACE`] is a directory of
|
||||
/// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title
|
||||
/// address space: the number of the host copy holding that page (0: none
|
||||
/// yet) and the page's byte offset in that copy;
|
||||
/// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base`
|
||||
/// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself
|
||||
/// reads zeros and drops writes;
|
||||
/// - the root UAV `u<SLOT_FAULTS>` takes the page numbers of accesses that
|
||||
/// found no copy ([`MEMORY_FAULTS`] dwords, dword 0 a sink), which the
|
||||
/// host reads afterwards to make those copies for the frames to come.
|
||||
pub const SLOT_MEMORY: u8 = 254;
|
||||
/// See [`SLOT_MEMORY`].
|
||||
pub const SLOT_FAULTS: u8 = 253;
|
||||
/// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB.
|
||||
pub const MEMORY_PAGES: u32 = 1 << 21;
|
||||
/// Dwords of the [`SLOT_FAULTS`] buffer.
|
||||
pub const MEMORY_FAULTS: u32 = 4096;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the view
|
||||
/// heap slot of the memory copies' views ([`SLOT_MEMORY`]).
|
||||
pub const USER_MEMORY_BASE: u32 = 0x100;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the low
|
||||
/// 32 bits of the title address of the buffer view at dword `dword` of the
|
||||
/// descriptor table of root parameter `slot`; [`USER_VIEW_ADDRESS`] + 1:
|
||||
/// its bits from 32 up. (Console code reads the address out of a buffer
|
||||
/// descriptor and uses it as a pointer.)
|
||||
pub const USER_VIEW_ADDRESS: u32 = 0x101;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the
|
||||
/// bytes (0 to 15) by which the raw view the host binds for the root view
|
||||
/// of root parameter `slot` begins before the title's address. A raw view
|
||||
/// begins on 16 bytes of its host buffer; the console's root views begin
|
||||
/// anywhere (the structure builder's counters sit at addresses ending in
|
||||
/// 4 and c). The shader adds the dword to every byte offset through that
|
||||
/// view. Asked for every root UAV, and for the root SRVs of programs with
|
||||
/// a spilled user-data table.
|
||||
pub const USER_VIEW_BIAS: u32 = 0x103;
|
||||
|
||||
/// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
|
||||
pub(crate) mod flags {
|
||||
pub const RAW_BUFFERS: u64 = 1 << 4;
|
||||
pub const STENCIL_REF: u64 = 1 << 11;
|
||||
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
|
||||
pub const WAVE_OPS: u64 = 1 << 19;
|
||||
pub const BARYCENTRICS: u64 = 1 << 22;
|
||||
pub const INT64: u64 = 1 << 20;
|
||||
pub const ATOMIC_TYPED64: u64 = 1 << 27;
|
||||
pub const ATOMIC_HEAP64: u64 = 1 << 32;
|
||||
pub const RESOURCE_HEAP: u64 = 1 << 30;
|
||||
pub const SAMPLER_HEAP: u64 = 1 << 31;
|
||||
}
|
||||
@@ -45,6 +105,25 @@ pub(crate) struct Mesh {
|
||||
pub topology: u8,
|
||||
}
|
||||
|
||||
/// What a geometry shader declares: triangles in, triangle strips out on
|
||||
/// stream 0, one instance.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Geometry {
|
||||
pub max_vertices: u32,
|
||||
}
|
||||
|
||||
/// The null slot a host view heap keeps at its end when the title's heap did not fit in it
|
||||
/// (0: no limit). Shaders translated while it is set read that slot for any view index at or
|
||||
/// past it: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is
|
||||
/// larger) hung its GPU on reads past the end (GPU-based validation: "descriptor heap index
|
||||
/// out of bounds"), which AMD's driver forgives.
|
||||
static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
|
||||
/// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null.
|
||||
pub fn set_view_heap_limit(null_slot: u32) {
|
||||
VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) struct Shader {
|
||||
pub m: Module,
|
||||
pub t: Types,
|
||||
@@ -55,6 +134,8 @@ pub(crate) struct Shader {
|
||||
pub prims: Vec<SigElement>,
|
||||
/// A mesh shader (`threads` is its thread-group size).
|
||||
pub mesh: Option<Mesh>,
|
||||
/// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false.
|
||||
pub geometry: Option<Geometry>,
|
||||
/// Dwords of user data the shader reads (0: no user-data buffer).
|
||||
pub user_data: u32,
|
||||
/// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`].
|
||||
@@ -65,6 +146,8 @@ pub(crate) struct Shader {
|
||||
pub root_cbvs: Vec<(u8, V)>,
|
||||
/// Root SRVs (raw buffers) read, likewise.
|
||||
pub root_srvs: Vec<(u8, V)>,
|
||||
/// Root UAVs (raw buffers) read or written, likewise.
|
||||
pub root_uavs: Vec<(u8, V)>,
|
||||
pub flags: u64,
|
||||
/// Heap handles made with a non-uniform index.
|
||||
pub nonuniform_handles: u32,
|
||||
@@ -115,11 +198,13 @@ impl Shader {
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh: None,
|
||||
geometry: None,
|
||||
user_data: 0,
|
||||
samplers: 0,
|
||||
cmp_samplers: 0,
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
flags: 0,
|
||||
nonuniform_handles: 0,
|
||||
threads: None,
|
||||
@@ -236,6 +321,31 @@ impl Shader {
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of the root UAV (a raw buffer) of root parameter `slot`:
|
||||
/// `u<slot>` in [`ROOT_CBV_SPACE`].
|
||||
pub fn root_uav_handle(&mut self, slot: u8) -> V {
|
||||
if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) {
|
||||
return h;
|
||||
}
|
||||
let r = self.m.i32(u32::from(slot));
|
||||
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(1)];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let f = self.m.bool(false);
|
||||
let block = self.entry;
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, r, f],
|
||||
);
|
||||
let h = self.annotate(block, h, 11 | 0x1000, 0);
|
||||
self.flags |= flags::RAW_BUFFERS;
|
||||
self.root_uavs.push((slot, h));
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of immediate sampler `n` (a comparison sampler when its
|
||||
/// bit in `cmp_samplers` is set).
|
||||
pub fn sampler_handle(&mut self, block: usize, n: u32) -> V {
|
||||
@@ -286,6 +396,25 @@ impl Shader {
|
||||
nonuniform: bool,
|
||||
props: (u32, u32),
|
||||
) -> V {
|
||||
// a view index past the host heap (`set_view_heap_limit`) reads its null slot instead
|
||||
let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed);
|
||||
// (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid)
|
||||
let index = if !sampler && limit != 0 {
|
||||
let null = self.m.i32(limit);
|
||||
let i32t = self.t.i32;
|
||||
self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null])
|
||||
} else if sampler {
|
||||
// A sampler heap has at most 2,048 samplers on any host: an
|
||||
// index past that (a number read from memory the host has not
|
||||
// got yet) stays inside the largest heap there is.
|
||||
// shortcut: not the bound heap's own count, which a title
|
||||
// heap smaller than 2,048 would need.
|
||||
let last = self.m.i32(2047);
|
||||
let i32t = self.t.i32;
|
||||
self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last])
|
||||
} else {
|
||||
index
|
||||
};
|
||||
self.flags |= if sampler {
|
||||
flags::SAMPLER_HEAP
|
||||
} else {
|
||||
@@ -318,6 +447,7 @@ impl Shader {
|
||||
|| self.samplers > 0
|
||||
|| !self.root_cbvs.is_empty()
|
||||
|| !self.root_srvs.is_empty()
|
||||
|| !self.root_uavs.is_empty()
|
||||
{
|
||||
let empty = self.m.md_str("");
|
||||
let mut cbvs = None;
|
||||
@@ -401,6 +531,43 @@ impl Shader {
|
||||
}
|
||||
srvs = Some(self.m.md_node(list));
|
||||
}
|
||||
let mut uavs = None;
|
||||
if !self.root_uavs.is_empty() {
|
||||
let ty = self
|
||||
.m
|
||||
.named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let no = self.m.bool(false);
|
||||
let no = self.m.md_value(no);
|
||||
let mut list = Vec::new();
|
||||
for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() {
|
||||
// Id, variable, name, space, lower bound, range size,
|
||||
// shape (11: raw buffer), globally coherent, counter,
|
||||
// rasterizer ordered, no extra properties.
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, n as u32)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, ROOT_CBV_SPACE)),
|
||||
Some(i32c(&mut self, u32::from(slot))),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, 11)),
|
||||
Some(no),
|
||||
Some(no),
|
||||
Some(no),
|
||||
None,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 7,
|
||||
space: ROOT_CBV_SPACE,
|
||||
register: u32::from(slot),
|
||||
dxil_kind: 11,
|
||||
});
|
||||
}
|
||||
uavs = Some(self.m.md_node(list));
|
||||
}
|
||||
let mut samplers = None;
|
||||
if self.samplers > 0 {
|
||||
let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]);
|
||||
@@ -430,11 +597,12 @@ impl Shader {
|
||||
}
|
||||
samplers = Some(self.m.md_node(list));
|
||||
}
|
||||
resources = Some(self.m.md_node(vec![srvs, None, cbvs, samplers]));
|
||||
// PSV0 lists them as the module does: CBVs, samplers, SRVs.
|
||||
resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers]));
|
||||
// PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs.
|
||||
bindings.sort_by_key(|b| match b.kind {
|
||||
2 => 0,
|
||||
1 => 1,
|
||||
7 => 3,
|
||||
_ => 2,
|
||||
});
|
||||
}
|
||||
@@ -468,6 +636,11 @@ impl Shader {
|
||||
});
|
||||
}
|
||||
}
|
||||
// A geometry shader lists four streams: the other three have
|
||||
// no outputs.
|
||||
if self.geometry.is_some() {
|
||||
view.extend([0, 0, 0]);
|
||||
}
|
||||
let arr = self.m.array(view.len() as u32, self.t.i32);
|
||||
let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect();
|
||||
let arr = self.m.aggregate(arr, &elems);
|
||||
@@ -488,8 +661,8 @@ impl Shader {
|
||||
if self.pixel && self.outputs.iter().any(|o| o.kind == 20) {
|
||||
self.flags |= flags::STENCIL_REF;
|
||||
}
|
||||
// Entry properties: shader flags (tag 0), thread-group size (4),
|
||||
// wave size (11).
|
||||
// Entry properties: shader flags (tag 0), geometry state (1),
|
||||
// thread-group size (4), wave size (11).
|
||||
let mut props = Vec::new();
|
||||
if self.flags != 0 {
|
||||
props.push(i32c(&mut self, 0));
|
||||
@@ -497,6 +670,13 @@ impl Shader {
|
||||
let f = self.m.int_const(i64t, self.flags as i64);
|
||||
props.push(self.m.md_value(f));
|
||||
}
|
||||
if let Some(g) = self.geometry {
|
||||
// Input primitive (3: triangles), maximum vertices, stream
|
||||
// mask, output topology (5: triangle strips), instances.
|
||||
props.push(i32c(&mut self, 1));
|
||||
let state = [3, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n)));
|
||||
props.push(self.m.md_node(state.to_vec()));
|
||||
}
|
||||
if let Some(threads) = self.threads {
|
||||
let t = threads.map(|n| Some(i32c(&mut self, n)));
|
||||
let t = self.m.md_node(t.to_vec());
|
||||
@@ -543,9 +723,10 @@ impl Shader {
|
||||
let version = self.m.md_node(vec![Some(one), Some(six)]);
|
||||
self.m.named_md("dx.version", vec![version]);
|
||||
self.m.named_md("dx.valver", vec![version]);
|
||||
// Program kinds: 0 pixel, 1 vertex, 5 compute, 13 mesh.
|
||||
// Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh.
|
||||
let (name, kind) = match (self.threads, self.pixel) {
|
||||
_ if self.mesh.is_some() => ("ms", 13u32),
|
||||
_ if self.geometry.is_some() => ("gs", 2),
|
||||
(Some(_), _) => ("cs", 5u32),
|
||||
(None, true) => ("ps", 0),
|
||||
(None, false) => ("vs", 1),
|
||||
@@ -578,12 +759,21 @@ impl Shader {
|
||||
if self.flags & flags::INT64 != 0 {
|
||||
features |= 0x8000;
|
||||
}
|
||||
if self.flags & flags::BARYCENTRICS != 0 {
|
||||
features |= 0x2_0000;
|
||||
}
|
||||
if self.flags & flags::RESOURCE_HEAP != 0 {
|
||||
features |= 0x200_0000;
|
||||
}
|
||||
if self.flags & flags::SAMPLER_HEAP != 0 {
|
||||
features |= 0x400_0000;
|
||||
}
|
||||
if self.flags & flags::ATOMIC_TYPED64 != 0 {
|
||||
features |= 0x40_0000;
|
||||
}
|
||||
if self.flags & flags::ATOMIC_HEAP64 != 0 {
|
||||
features |= 0x1000_0000;
|
||||
}
|
||||
let sfi0 = features.to_le_bytes();
|
||||
let isg1 = container::signature(&self.inputs, true);
|
||||
let osg1 = container::signature(&self.outputs, false);
|
||||
@@ -599,6 +789,7 @@ impl Shader {
|
||||
outputs: &self.outputs,
|
||||
prims: &self.prims,
|
||||
mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)),
|
||||
geometry: self.geometry.map(|g| g.max_vertices),
|
||||
bindings: &bindings,
|
||||
threads: self.threads.unwrap_or_default(),
|
||||
wave_size: self.wave_size,
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Jump threading for uniform diamonds. One arm can set a flag that fixes
|
||||
//! the join's next branch. Registers recycled on that arm then never reach
|
||||
//! the other successor, even if an ordinary SSA phi joins their values.
|
||||
use crate::gfx10::{Fields, Operand, Valu};
|
||||
use crate::ir::{Exit, Program, Reg, Value};
|
||||
use crate::structure::{Atom, Bool, LaneExit, Structured};
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn plain(v: &Valu) -> bool {
|
||||
v.abs == 0
|
||||
&& v.neg == 0
|
||||
&& v.opsel == 0
|
||||
&& !v.clamp
|
||||
&& v.omod == 0
|
||||
&& v.sdwa.is_none()
|
||||
&& v.dpp.is_none()
|
||||
}
|
||||
|
||||
fn immediate(op: Operand) -> Option<u32> {
|
||||
match op {
|
||||
Operand::Const(c) => crate::resource::inline(c),
|
||||
Operand::Literal(n) => Some(n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn constant_edges(p: &Program, st: &Structured) -> Vec<(usize, usize, usize)> {
|
||||
let mut constants = HashMap::new();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
if inst.name() == "v_mov_b32"
|
||||
&& st.guards[b][i].is_none()
|
||||
&& let Fields::Valu(v) = &inst.fields
|
||||
&& plain(v)
|
||||
&& let [src] = v.src.as_slice()
|
||||
&& let Some(word) = immediate(*src)
|
||||
&& let [(_, dst)] = inst.writes.as_slice()
|
||||
{
|
||||
constants.insert(*dst, word);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut edges = Vec::new();
|
||||
for (join, block) in p.blocks.iter().enumerate() {
|
||||
let LaneExit::Branch {
|
||||
when,
|
||||
taken,
|
||||
not_taken,
|
||||
} = st.exits[join]
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if when == Bool::TRUE || when == Bool::FALSE {
|
||||
continue;
|
||||
}
|
||||
// Keep memory accesses and wave operations at their original
|
||||
// reconvergence point. Only duplicate scalar ALU and comparisons.
|
||||
if !block.insts.iter().all(|i| match &i.fields {
|
||||
Fields::Sop { .. } => true,
|
||||
Fields::Sopp { .. } => i.name().starts_with("s_cbranch_"),
|
||||
Fields::Valu(_) => i.name().starts_with("v_cmp_"),
|
||||
_ => false,
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
let [a, b] = block.preds.as_slice() else {
|
||||
continue;
|
||||
};
|
||||
// A triangle has a direct edge from the fork to the join. A full
|
||||
// diamond has an unconditional jump at the end of each arm.
|
||||
let arm_from = |arm: usize| match p.blocks[arm].preds.as_slice() {
|
||||
&[fork] if p.blocks[arm].exit == Exit::Jump(join) => Some(fork),
|
||||
_ => None,
|
||||
};
|
||||
let fork = match (arm_from(*a), arm_from(*b)) {
|
||||
(Some(f), Some(g)) if f == g => f,
|
||||
(_, Some(f)) if f == *a => f,
|
||||
(Some(f), _) if f == *b => f,
|
||||
_ => continue,
|
||||
};
|
||||
if fork == join || a == b {
|
||||
continue;
|
||||
}
|
||||
let LaneExit::Branch { when: entry, .. } = st.exits[fork] else {
|
||||
continue;
|
||||
};
|
||||
if !st
|
||||
.bools
|
||||
.support(entry)
|
||||
.iter()
|
||||
.all(|a| matches!(a, Atom::Uniform(_)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for (edge, &pred) in block.preds.iter().enumerate() {
|
||||
let value = |v: Value| {
|
||||
let input = block
|
||||
.phis
|
||||
.iter()
|
||||
.find(|p| p.value == v)
|
||||
.map_or(v, |p| p.args[edge]);
|
||||
constants.get(&input).copied()
|
||||
};
|
||||
// Restrict the branch's decision diagram to known comparisons.
|
||||
// Unknown tests stop the proof. Keep the original join for the
|
||||
// other arm, which may still go either way.
|
||||
let mut cond = when;
|
||||
while let Some((Atom::Lane(id), lo, hi)) = st.bools.node(cond) {
|
||||
let Some(inst) = block
|
||||
.insts
|
||||
.iter()
|
||||
.find(|i| i.writes.iter().any(|&(_, v)| v == id))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let Fields::Valu(v) = &inst.fields else { break };
|
||||
let [left, right] = v.src.as_slice() else {
|
||||
break;
|
||||
};
|
||||
let operand = |op| match op {
|
||||
Operand::Vector { reg, dwords: 1 } => value(inst.read(Reg::V(reg))?),
|
||||
_ => immediate(op),
|
||||
};
|
||||
let (Some(x), Some(y)) = (operand(*left), operand(*right)) else {
|
||||
break;
|
||||
};
|
||||
if !plain(v) {
|
||||
break;
|
||||
}
|
||||
let yes = match inst.name() {
|
||||
"v_cmp_eq_u32" | "v_cmp_eq_i32" => x == y,
|
||||
"v_cmp_ne_u32" | "v_cmp_ne_i32" => x != y,
|
||||
_ => break,
|
||||
};
|
||||
cond = if yes { hi } else { lo };
|
||||
}
|
||||
if cond == Bool::TRUE || cond == Bool::FALSE {
|
||||
edges.push((
|
||||
pred,
|
||||
join,
|
||||
if cond == Bool::TRUE { taken } else { not_taken },
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
edges
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ir;
|
||||
use crate::structure;
|
||||
|
||||
// s8 initially holds a descriptor address. One arm overwrites it with
|
||||
// a buffer load and sets v1. Only that arm can use s8 as the stored value.
|
||||
const WORDS: [u32; 19] = [
|
||||
0xbe810380, // s1 = 0 (table address high)
|
||||
0xf4080200, 0xfa000000, // load SRV into s[8:11]
|
||||
0xf4080300, 0xfa000020, // load UAV into s[12:15]
|
||||
0x7e020280, // v1 = 0
|
||||
0xbf068002, 0xbf850003, // if s2 == 0, jump to join
|
||||
0xf4200204, 0xfa00000c, // s8 = buffer.Load(12)
|
||||
0x7e020281, // v1 = 1
|
||||
0x7d840280, 0xbf870002, // join: if v1 == 0, jump to constant
|
||||
0x7e060208, 0xbf820001, // v3 = s8, jump to store
|
||||
0x7e060293, // constant: v3 = 19
|
||||
0xe0700000, 0x80030300, // store v3 at byte 0
|
||||
0xbf810000, // end
|
||||
];
|
||||
|
||||
fn program(words: &[u32]) -> Program {
|
||||
ir::build(
|
||||
&words
|
||||
.iter()
|
||||
.flat_map(|w| w.to_le_bytes())
|
||||
.collect::<Vec<_>>(),
|
||||
false,
|
||||
4,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_buffer_load_reaches_the_numeric_read() {
|
||||
let p = program(&WORDS);
|
||||
let st = structure::structure(&p).unwrap();
|
||||
let edges = constant_edges(&p, &st);
|
||||
assert_eq!(edges, [(0, 2, 4)]);
|
||||
let p = ir::thread_edges(&p, &edges).unwrap();
|
||||
let load = &p.blocks[1].insts[0];
|
||||
assert_eq!(p.blocks[3].insts[0].read(Reg::S(8)), load.write(Reg::S(8)));
|
||||
assert_eq!(
|
||||
p.blocks[0].exit,
|
||||
Exit::Branch {
|
||||
taken: 6,
|
||||
not_taken: 1
|
||||
}
|
||||
);
|
||||
assert_eq!(p.blocks[6].exit, Exit::Jump(4));
|
||||
assert_eq!(p.blocks[6].insts.len(), p.blocks[2].insts.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_unknown_flags_and_divergent_forks_alone() {
|
||||
let mut words = WORDS;
|
||||
words[5] = 0x7e020202; // v1 = s2
|
||||
words[10] = 0x7e020203; // v1 = s3
|
||||
let p = program(&words);
|
||||
assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
|
||||
let mut words = WORDS;
|
||||
words[6] = 0x7d840080; // compare 0 with lane-dependent v0
|
||||
words[7] = 0xbf870003; // branch on VCC
|
||||
let p = program(&words);
|
||||
assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
//!
|
||||
//! Covers RDNA2 hardware semantics that differ from naive DXIL lowering:
|
||||
//! `v_med3_f32`/`v_med3_f16` with NaN operands, `v_fract_f32`/`v_fract_f16`
|
||||
//! near `1.0`, and turn-range reduction for `v_sin_*`/`v_cos_*`.
|
||||
//! near `1.0`, turn-range reduction for `v_sin_*`/`v_cos_*`, and the LDS
|
||||
//! float atomics `ds_min_f32`/`ds_max_f32`.
|
||||
|
||||
use super::host::{Dispatch, Host, Root, View};
|
||||
use super::{HostShader, lower, validator};
|
||||
@@ -43,9 +44,33 @@ const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 {
|
||||
|
||||
/// VOP3 `op vdst, src0, src1, src2` (no modifiers).
|
||||
const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] {
|
||||
vop3_mod(op, vdst, src0, src1, src2, 0, 0, 0, false)
|
||||
}
|
||||
|
||||
/// VOP3 `op vdst, src0, src1, src2` with explicit `abs`, `neg`, `omod`, `clamp`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
const fn vop3_mod(
|
||||
op: u16,
|
||||
vdst: u8,
|
||||
src0: u16,
|
||||
src1: u16,
|
||||
src2: u16,
|
||||
abs: u8,
|
||||
neg: u8,
|
||||
omod: u8,
|
||||
clamp: bool,
|
||||
) -> [u32; 2] {
|
||||
[
|
||||
0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32,
|
||||
(src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18,
|
||||
0x35 << 26
|
||||
| (op as u32 & 0x3FF) << 16
|
||||
| (clamp as u32) << 15
|
||||
| (abs as u32 & 7) << 8
|
||||
| vdst as u32,
|
||||
(neg as u32 & 7) << 29
|
||||
| (omod as u32 & 3) << 27
|
||||
| (src0 as u32 & 0x1FF)
|
||||
| (src1 as u32 & 0x1FF) << 9
|
||||
| (src2 as u32 & 0x1FF) << 18,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -69,6 +94,12 @@ const fn vgpr(n: u8) -> u16 {
|
||||
/// 4 dwords of root constants in `s0..s3`, runs `body` (leaving its result in
|
||||
/// `v0`), and stores `v0` to dword 0 of the raw UAV at heap index 0.
|
||||
fn build_valu_cs(body: &[u32]) -> HostShader {
|
||||
build_cs(body, 1, 0)
|
||||
}
|
||||
|
||||
/// [`build_valu_cs`] with `threads` threads in x (thread index in `v0`
|
||||
/// on entry, before `body`) and `lds_bytes` of LDS (a multiple of 512).
|
||||
fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader {
|
||||
let mut words = Vec::new();
|
||||
// s[4:5] = descriptor table address (heap index 0 -> byte offset 0).
|
||||
words.push(s_mov_b32(5, 0x80)); // inline constant 0
|
||||
@@ -116,8 +147,8 @@ fn build_valu_cs(body: &[u32]) -> HostShader {
|
||||
slot: 1,
|
||||
}],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
|
||||
threads: [1, 1, 1],
|
||||
rsrc2: (5 << 1) | ((lds_bytes / 512) << 15), // 5 user SGPRs: s0..s4
|
||||
threads: [threads, 1, 1],
|
||||
}),
|
||||
code,
|
||||
};
|
||||
@@ -148,6 +179,8 @@ fn build_valu_cs(body: &[u32]) -> HostShader {
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views,
|
||||
};
|
||||
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
@@ -172,11 +205,20 @@ pub(super) static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()
|
||||
fn run_cases(
|
||||
shader: &HostShader,
|
||||
cases: &[[u32; 4]],
|
||||
check: impl FnMut(&str, usize, [u32; 4], u32),
|
||||
) {
|
||||
run_cases_on(shader, cases, &[("hardware", false), ("warp", true)], check);
|
||||
}
|
||||
|
||||
fn run_cases_on(
|
||||
shader: &HostShader,
|
||||
cases: &[[u32; 4]],
|
||||
devices: &[(&str, bool)],
|
||||
mut check: impl FnMut(&str, usize, [u32; 4], u32),
|
||||
) {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut ran = 0;
|
||||
for (label, warp) in [("hardware", false), ("warp", true)] {
|
||||
for &(label, warp) in devices {
|
||||
let Ok(host) = Host::new(warp) else {
|
||||
eprintln!("no SM 6.6 {label} device; skipped");
|
||||
continue;
|
||||
@@ -209,7 +251,7 @@ fn run_cases(
|
||||
}
|
||||
ran += 1;
|
||||
}
|
||||
assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available");
|
||||
assert!(ran > 0, "no SM 6.6 device available ({devices:?})");
|
||||
}
|
||||
|
||||
fn is_f16_nan(bits: u16) -> bool {
|
||||
@@ -868,6 +910,286 @@ fn bfe_signed_and_unsigned_match_rdna2() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f16_omod_applies_before_clamp() {
|
||||
// VOP3 v_add_f16 (0x132 = 0x100 + VOP2 0x32): v0 = (v1 + v2) * omod [clamp]
|
||||
let mul2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 1, false));
|
||||
let mul4 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 2, false));
|
||||
let div2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, false));
|
||||
let div2_clamp = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, true));
|
||||
|
||||
// f16 constants: 0.25=0x3400, 0.5=0x3800, 0.75=0x3A00, 1.0=0x3C00, 1.5=0x3E00, 2.0=0x4000, -0.5=0xB800
|
||||
run_cases(
|
||||
&mul2,
|
||||
&[[0x3400, 0x3800, 0, 0]], // (0.25 + 0.5) * 2 = 1.5 (0x3E00)
|
||||
|backend, _, _, got| {
|
||||
assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 mul:2");
|
||||
},
|
||||
);
|
||||
run_cases(
|
||||
&mul4,
|
||||
&[[0x3400, 0x3400, 0, 0]], // (0.25 + 0.25) * 4 = 2.0 (0x4000)
|
||||
|backend, _, _, got| {
|
||||
assert_eq!(got as u16, 0x4000, "{backend}: v_add_f16 mul:4");
|
||||
},
|
||||
);
|
||||
run_cases(
|
||||
&div2,
|
||||
&[[0x3E00, 0x3E00, 0, 0]], // (1.5 + 1.5) / 2 = 1.5 (0x3E00)
|
||||
|backend, _, _, got| {
|
||||
assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 div:2");
|
||||
},
|
||||
);
|
||||
// Ordering check: (0.75 + 0.75) = 1.5; div:2 before clamp gives 0.75 (0x3A00),
|
||||
// whereas clamp before div:2 would give 0.5 (0x3800).
|
||||
let clamp_cases: &[(u16, u16, u16)] = &[
|
||||
(0x3A00, 0x3A00, 0x3A00), // (0.75 + 0.75) / 2 = 0.75 -> 0.75
|
||||
(0x3E00, 0x3E00, 0x3C00), // (1.5 + 1.5) / 2 = 1.5 -> clamped to 1.0
|
||||
(0xB800, 0xB800, 0x0000), // (-0.5 + -0.5) / 2 = -0.5 -> clamped to 0.0
|
||||
];
|
||||
let inputs: Vec<[u32; 4]> = clamp_cases
|
||||
.iter()
|
||||
.map(|&(a, b, _)| [u32::from(a), u32::from(b), 0, 0])
|
||||
.collect();
|
||||
run_cases(&div2_clamp, &inputs, |backend, i, _, got| {
|
||||
let want = clamp_cases[i].2;
|
||||
assert_eq!(
|
||||
got as u16, want,
|
||||
"{backend}: v_add_f16 div:2 clamp case {i}: got {:#06x}, want {want:#06x}",
|
||||
got as u16,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() {
|
||||
// VOP3 v_cvt_u16_f16 = 0x1D2 (0x180 + VOP1 0x52)
|
||||
// VOP3 v_cvt_i16_f16 = 0x1D3 (0x180 + VOP1 0x53)
|
||||
let cvt_u16 = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 0, 0, 0, false));
|
||||
let cvt_u16_abs = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 1, 0, 0, false));
|
||||
let cvt_i16 = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 0, 0, false));
|
||||
let cvt_i16_neg = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 1, 0, false));
|
||||
|
||||
let u16_cases: &[(u16, u16)] = &[
|
||||
(0xBC00, 0), // -1.0 -> 0
|
||||
(0xFC00, 0), // -inf -> 0
|
||||
(0x7E00, 0), // NaN -> 0
|
||||
(0x57BC, 123), // 123.75 -> 123
|
||||
(0x7BFF, 65504), // 65504.0 (max finite f16) -> 65504
|
||||
(0x7C00, 0xFFFF), // +inf -> 65535 (saturated)
|
||||
];
|
||||
let u16_in: Vec<[u32; 4]> = u16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect();
|
||||
run_cases(&cvt_u16, &u16_in, |backend, i, inp, got| {
|
||||
let want = u16_cases[i].1;
|
||||
assert_eq!(
|
||||
got as u16, want,
|
||||
"{backend}: v_cvt_u16_f16({:#06x}) = {:#06x}, want {want:#06x}",
|
||||
inp[0], got as u16,
|
||||
);
|
||||
});
|
||||
run_cases(
|
||||
&cvt_u16_abs,
|
||||
&[[0xD7BC, 0, 0, 0]], // |-123.75| -> 123
|
||||
|backend, _, _, got| {
|
||||
assert_eq!(got as u16, 123, "{backend}: v_cvt_u16_f16 |src0|");
|
||||
},
|
||||
);
|
||||
|
||||
let i16_cases: &[(u16, u16)] = &[
|
||||
(0xFC00, 0x8000), // -inf -> -32768
|
||||
(0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped)
|
||||
(0xD7BC, (-123i16) as u16), // -123.75 -> -123
|
||||
(0x7E00, 0), // NaN -> 0
|
||||
(0x57BC, 123), // 123.75 -> 123
|
||||
(0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped)
|
||||
(0x7C00, 0x7FFF), // +inf -> 32767
|
||||
];
|
||||
let i16_in: Vec<[u32; 4]> = i16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect();
|
||||
run_cases(&cvt_i16, &i16_in, |backend, i, inp, got| {
|
||||
let want = i16_cases[i].1;
|
||||
assert_eq!(
|
||||
got as u16, want,
|
||||
"{backend}: v_cvt_i16_f16({:#06x}) = {:#06x}, want {want:#06x}",
|
||||
inp[0], got as u16,
|
||||
);
|
||||
});
|
||||
run_cases(
|
||||
&cvt_i16_neg,
|
||||
&[[0x57BC, 0, 0, 0], [0x78E2, 0, 0, 0]], // -(123.75) -> -123; -(40000.0) -> -32768
|
||||
|backend, i, _, got| {
|
||||
let want = [(-123i16) as u16, 0x8000][i];
|
||||
assert_eq!(got as u16, want, "{backend}: v_cvt_i16_f16 -src0 case {i}");
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const S_BARRIER: u32 = 0xBF8A_0000;
|
||||
|
||||
/// VOP2 `op vdst, src0, vsrc1`.
|
||||
const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 {
|
||||
(op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF)
|
||||
}
|
||||
|
||||
/// DS `op vdst, addr, data0` at offset 0.
|
||||
const fn ds(op: u8, vdst: u8, addr: u8, data0: u8) -> [u32; 2] {
|
||||
[
|
||||
0x36 << 26 | (op as u32) << 18,
|
||||
(vdst as u32) << 24 | (data0 as u32) << 8 | addr as u32,
|
||||
]
|
||||
}
|
||||
|
||||
const DS_WRITE_B32: u8 = 0x0D;
|
||||
const DS_MIN_F32: u8 = 0x12;
|
||||
const DS_MAX_F32: u8 = 0x13;
|
||||
const DS_MIN_RTN_F32: u8 = 0x32;
|
||||
const DS_MAX_RTN_F32: u8 = 0x33;
|
||||
const DS_READ_B32: u8 = 0x36;
|
||||
|
||||
/// What RDNA2 writes for `ds_max_f32` / `ds_min_f32` over a dword holding
|
||||
/// `old` with `data` (bits), as measured on gfx1036 with f32 denormals kept:
|
||||
/// an sNaN, data first, then memory, is written quieted; otherwise a NaN
|
||||
/// loses to a number (two quiet NaNs give the data); numbers compare as
|
||||
/// floats with -0 below +0.
|
||||
fn lds_min_max_ref(old: u32, data: u32, max: bool) -> u32 {
|
||||
let nan = |x: u32| x & 0x7FFF_FFFF > 0x7F80_0000;
|
||||
let snan = |x: u32| nan(x) && x & 0x40_0000 == 0;
|
||||
let key = |x: u32| {
|
||||
let b = x as i32;
|
||||
if b < 0 { b ^ 0x7FFF_FFFF } else { b }
|
||||
};
|
||||
if snan(data) {
|
||||
return data | 0x40_0000;
|
||||
}
|
||||
if snan(old) {
|
||||
return old | 0x40_0000;
|
||||
}
|
||||
match (nan(data), nan(old)) {
|
||||
(true, true) | (false, true) => return data,
|
||||
(true, false) => return old,
|
||||
(false, false) => {}
|
||||
}
|
||||
let take = if max {
|
||||
key(data) > key(old)
|
||||
} else {
|
||||
key(data) < key(old)
|
||||
};
|
||||
if take { data } else { old }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ds_min_max_f32_order_floats_and_return_the_old_value() {
|
||||
let values = [
|
||||
0.0f32,
|
||||
-0.0,
|
||||
1.0,
|
||||
-1.0,
|
||||
2.5,
|
||||
-2.5,
|
||||
1e-30,
|
||||
-1e-30,
|
||||
f32::from_bits(1), // denormal
|
||||
f32::from_bits(0x8000_0001),
|
||||
f32::INFINITY,
|
||||
f32::NEG_INFINITY,
|
||||
f32::MAX,
|
||||
f32::MIN,
|
||||
];
|
||||
// Quiet and signalling NaNs of both signs, in memory and as data.
|
||||
let nans = [
|
||||
0x7FC0_0000u32,
|
||||
0xFFC0_0000,
|
||||
0x7F80_0001,
|
||||
0xFFA0_0000,
|
||||
0x7FBF_FFFF,
|
||||
];
|
||||
let bits: Vec<u32> = values.iter().map(|v| v.to_bits()).chain(nans).collect();
|
||||
let mut cases: Vec<[u32; 4]> = Vec::new();
|
||||
for &old in &bits {
|
||||
for &data in &bits {
|
||||
cases.push([old, data, 0, 0]);
|
||||
}
|
||||
}
|
||||
for (rtn, plain, max, what) in [
|
||||
(DS_MAX_RTN_F32, DS_MAX_F32, true, "ds_max"),
|
||||
(DS_MIN_RTN_F32, DS_MIN_F32, false, "ds_min"),
|
||||
] {
|
||||
// v5 = 0; LDS[v5] = v1; the atomic with v2; v0 = the old value
|
||||
// (rtn) or the dword afterwards (read back).
|
||||
let mut returns_old = vec![vop1(0x001, 5, 0x80)];
|
||||
returns_old.extend(ds(DS_WRITE_B32, 0, 5, 1));
|
||||
returns_old.extend(ds(rtn, 0, 5, 2));
|
||||
let mut returns_new = vec![vop1(0x001, 5, 0x80)];
|
||||
returns_new.extend(ds(DS_WRITE_B32, 0, 5, 1));
|
||||
returns_new.extend(ds(plain, 0, 5, 2));
|
||||
returns_new.extend(ds(DS_READ_B32, 0, 5, 0));
|
||||
for (body, old_result) in [(returns_old, true), (returns_new, false)] {
|
||||
// One thread with LDS declares WaveSize(32), which WARP's
|
||||
// pipeline creation refuses: hardware only (the 64-thread test
|
||||
// below runs on WARP too).
|
||||
let shader = build_cs(&body, 1, 512);
|
||||
run_cases_on(
|
||||
&shader,
|
||||
&cases,
|
||||
&[("hardware", false)],
|
||||
|backend, _, inp, got| {
|
||||
let (old, data) = (f32::from_bits(inp[0]), f32::from_bits(inp[1]));
|
||||
let want = if old_result {
|
||||
inp[0]
|
||||
} else {
|
||||
lds_min_max_ref(inp[0], inp[1], max)
|
||||
};
|
||||
assert_eq!(
|
||||
got,
|
||||
want,
|
||||
"{backend}: {what}_f32 on {old:e} [{:#010x}] with {data:e} [{:#010x}] gave {got:#010x}, want {want:#010x} ({})",
|
||||
inp[0],
|
||||
inp[1],
|
||||
if old_result {
|
||||
"old value"
|
||||
} else {
|
||||
"dword after"
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ds_min_max_f32_are_atomic_across_waves() {
|
||||
// 64 threads (two host waves of 32 or one of 64): LDS[0] = v1, then
|
||||
// every thread applies (thread - 32) as a float; v0 = LDS[0].
|
||||
for (op, max, init, want) in [
|
||||
(DS_MAX_F32, true, f32::NEG_INFINITY, 31.0f32),
|
||||
(DS_MAX_F32, true, 100.0, 100.0),
|
||||
(DS_MIN_F32, false, f32::INFINITY, -32.0),
|
||||
(DS_MIN_F32, false, -0.0, -32.0),
|
||||
] {
|
||||
let mut body = vec![vop1(0x001, 5, 0x80)];
|
||||
body.extend(ds(DS_WRITE_B32, 0, 5, 1));
|
||||
body.push(S_BARRIER);
|
||||
body.push(vop2(0x26, 6, vgpr(0), 3)); // v_sub_nc_u32 v6, v0, v3
|
||||
body.push(vop1(0x005, 6, vgpr(6))); // v_cvt_f32_i32
|
||||
body.extend(ds(op, 0, 5, 6));
|
||||
body.push(S_BARRIER);
|
||||
body.extend(ds(DS_READ_B32, 0, 5, 0));
|
||||
let shader = build_cs(&body, 64, 512);
|
||||
run_cases(
|
||||
&shader,
|
||||
&[[init.to_bits(), 0, 32, 0]],
|
||||
|backend, _, _, got| {
|
||||
assert_eq!(
|
||||
f32::from_bits(got),
|
||||
want,
|
||||
"{backend}: {} from {init} over 64 threads",
|
||||
if max { "max" } else { "min" },
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v_cmp_class_f16_matches_rdna2() {
|
||||
// v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6
|
||||
|
||||
@@ -82,6 +82,8 @@ fn build(words: &[u32], buffers: bool) -> HostShader {
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
v.validate(&mut shader.dxil.clone())
|
||||
|
||||
@@ -35,7 +35,9 @@ pub(crate) enum Op {
|
||||
impl Op {
|
||||
fn of(name: &str) -> Option<Op> {
|
||||
Some(match name {
|
||||
"v_add_nc_u32" => Op::AddU,
|
||||
// the low dword of a 64-bit sum (`v_add_co_ci_u32` carries into
|
||||
// the high one) is the 32-bit sum of the low dwords
|
||||
"v_add_nc_u32" | "v_add_co_u32" => Op::AddU,
|
||||
"v_add_f32" => Op::AddF,
|
||||
"v_min_u32" => Op::MinU,
|
||||
"v_max_u32" => Op::MaxU,
|
||||
@@ -253,11 +255,11 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
let Some(k) = lo else {
|
||||
return shapes(vec, uni, wave);
|
||||
};
|
||||
exec = if name == "s_mov_b64" {
|
||||
exec = (if name == "s_mov_b64" {
|
||||
k
|
||||
} else {
|
||||
exec & !0xFFFF_FFFF | k & 0xFFFF_FFFF
|
||||
};
|
||||
(exec & !0xFFFF_FFFF) | (k & 0xFFFF_FFFF)
|
||||
}) & all;
|
||||
continue;
|
||||
}
|
||||
if inst.write(Reg::S(EXEC + 1)).is_some() {
|
||||
@@ -268,7 +270,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
else {
|
||||
return shapes(vec, uni, wave);
|
||||
};
|
||||
exec = exec & 0xFFFF_FFFF | k << 32;
|
||||
exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all;
|
||||
continue;
|
||||
}
|
||||
if let Fields::Sop { src, .. } = &inst.fields {
|
||||
@@ -494,15 +496,18 @@ fn constant(inst: &Inst) -> Option<u64> {
|
||||
let Fields::Sop { src, .. } = &inst.fields else {
|
||||
return None;
|
||||
};
|
||||
let wide = inst.name() == "s_mov_b64";
|
||||
match *src.first()? {
|
||||
Operand::Const(c) => {
|
||||
Operand::Scalar { code: NULL, .. } => Some(0),
|
||||
Operand::Const(c @ 128..=208) => {
|
||||
let x = crate::resource::inline(c)?;
|
||||
Some(if (x as i32) < 0 {
|
||||
u64::MAX
|
||||
Some(if wide {
|
||||
i64::from(x as i32) as u64
|
||||
} else {
|
||||
u64::from(x)
|
||||
})
|
||||
}
|
||||
Operand::Const(c) if !wide => crate::resource::inline(c).map(u64::from),
|
||||
Operand::Literal(x) => Some(u64::from(x)),
|
||||
_ => None,
|
||||
}
|
||||
@@ -577,7 +582,8 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> {
|
||||
};
|
||||
}
|
||||
// Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive).
|
||||
let mut found: Option<(Op, Value, Value, u32, bool)> = None;
|
||||
let mut meta: Option<(Value, Value, u32, bool)> = None;
|
||||
let mut op_found: Option<Op> = None;
|
||||
for (l, &s) in lanes.iter().enumerate() {
|
||||
let below = (1u64 << l) - 1;
|
||||
let (op, src, mask, ident, set) = match s {
|
||||
@@ -592,28 +598,40 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> {
|
||||
Sym::K(_) if l == 0 => continue,
|
||||
_ => return None,
|
||||
};
|
||||
let inclusive = set == below | 1 << l;
|
||||
let inclusive = set == below | (1u64 << l);
|
||||
if !inclusive && set != below {
|
||||
return None;
|
||||
}
|
||||
let op = match (op, found) {
|
||||
(Some(o), _) => o,
|
||||
(None, Some(f)) => f.0,
|
||||
(None, None) => continue,
|
||||
};
|
||||
let me = (op, src, mask, ident, inclusive);
|
||||
match found {
|
||||
None => found = Some(me),
|
||||
Some(f) if f == me => {}
|
||||
if l == 0 && !inclusive {
|
||||
return None;
|
||||
}
|
||||
if op.is_none() && set.count_ones() != 1 {
|
||||
return None;
|
||||
}
|
||||
let lane_meta = (src, mask, ident, inclusive);
|
||||
match meta {
|
||||
None => meta = Some(lane_meta),
|
||||
Some(prev) if prev == lane_meta => {}
|
||||
_ => return None,
|
||||
}
|
||||
if let Some(o) = op {
|
||||
match op_found {
|
||||
None => op_found = Some(o),
|
||||
Some(prev) if prev == o => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
let (op, src, mask, ident, inclusive) = found?;
|
||||
if let Sym::K(k) = lanes[0]
|
||||
&& (inclusive || k != ident)
|
||||
{
|
||||
let (src, mask, ident, inclusive) = meta?;
|
||||
let op = op_found?;
|
||||
if !op.identity(ident) {
|
||||
return None;
|
||||
}
|
||||
match lanes[0] {
|
||||
Sym::K(k) if !inclusive && k == ident => {}
|
||||
Sym::Red { .. } if inclusive => {}
|
||||
_ => return None,
|
||||
}
|
||||
Some(Shape::Prefix(op, src, mask, ident, inclusive))
|
||||
}
|
||||
|
||||
@@ -621,6 +639,45 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const S_ENDPGM: u32 = 0xBF81_0000;
|
||||
|
||||
const fn sop1(sdst: u8, op: u8, ssrc0: u8) -> u32 {
|
||||
0xBE80_0000 | (sdst as u32) << 16 | (op as u32) << 8 | ssrc0 as u32
|
||||
}
|
||||
|
||||
const fn vop1(vdst: u8, op: u8, src0: u16) -> u32 {
|
||||
(0x3F << 25) | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF)
|
||||
}
|
||||
|
||||
const fn vop2(vdst: u8, op: u8, src0: u16, vsrc1: u8) -> u32 {
|
||||
(op as u32) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF)
|
||||
}
|
||||
|
||||
const fn dpp16(vsrc0: u8, ctrl: u16, row_mask: u8, bank_mask: u8, bound_ctrl: bool) -> u32 {
|
||||
(row_mask as u32) << 28
|
||||
| (bank_mask as u32) << 24
|
||||
| (bound_ctrl as u32) << 19
|
||||
| (ctrl as u32) << 8
|
||||
| vsrc0 as u32
|
||||
}
|
||||
|
||||
const fn vop3(vdst: u8, op: u16, src0: u16, src1: u16, src2: u16) -> [u32; 2] {
|
||||
[
|
||||
0xD400_0000 | (op as u32) << 16 | vdst as u32,
|
||||
(src0 as u32 & 0x1FF) | ((src1 as u32 & 0x1FF) << 9) | ((src2 as u32 & 0x1FF) << 18),
|
||||
]
|
||||
}
|
||||
|
||||
fn build(words: &[u32], wave64: bool) -> Program {
|
||||
let code: Vec<u8> = words
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(std::iter::once(S_ENDPGM))
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
crate::ir::build(&code, wave64, 256).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dpp_lanes_follow_the_isa() {
|
||||
// row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16.
|
||||
@@ -676,4 +733,220 @@ mod tests {
|
||||
Some(Shape::Active(Op::AddU, x, m, 0))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_decodes_width_and_inline_kinds() {
|
||||
let b64 = 0x04;
|
||||
let b32 = 0x03;
|
||||
let check = |words: &[u32], wave64: bool| -> Option<u64> {
|
||||
let p = build(words, wave64);
|
||||
constant(&p.blocks[0].insts[0])
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
check(&[sop1(EXEC, b64, 194)], true),
|
||||
Some(0xFFFF_FFFF_FFFF_FFFE)
|
||||
);
|
||||
assert_eq!(
|
||||
check(&[sop1(EXEC, b64, 196)], true),
|
||||
Some(0xFFFF_FFFF_FFFF_FFFC)
|
||||
);
|
||||
assert_eq!(
|
||||
check(&[sop1(EXEC, b64, 208)], true),
|
||||
Some(0xFFFF_FFFF_FFFF_FFF0)
|
||||
);
|
||||
assert_eq!(check(&[sop1(EXEC, b64, 193)], true), Some(u64::MAX));
|
||||
assert_eq!(check(&[sop1(EXEC, b64, NULL)], true), Some(0));
|
||||
assert_eq!(check(&[sop1(EXEC, b64, 243)], true), None);
|
||||
assert_eq!(
|
||||
check(&[sop1(EXEC, b64, 255), 0x1234_5678], true),
|
||||
Some(0x1234_5678)
|
||||
);
|
||||
|
||||
assert_eq!(check(&[sop1(EXEC, b32, 194)], false), Some(0xFFFF_FFFE));
|
||||
assert_eq!(check(&[sop1(EXEC, b32, 243)], false), Some(0xBF80_0000));
|
||||
assert_eq!(check(&[sop1(EXEC, b32, NULL)], false), Some(0));
|
||||
assert_eq!(
|
||||
check(&[sop1(EXEC, b32, 255), 0x1234_5678], false),
|
||||
Some(0x1234_5678)
|
||||
);
|
||||
assert_eq!(check(&[sop1(EXEC, b32, 0)], false), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_minus_two_masks_lane_zero_and_enforces_dpp_guard() {
|
||||
for wave64 in [false, true] {
|
||||
let mut w = Vec::new();
|
||||
let save_op = if wave64 { 0x25 } else { 0x3D };
|
||||
let mov_exec = if wave64 { 0x04 } else { 0x03 };
|
||||
let push_exec = |w: &mut Vec<u32>, k: u8| w.push(sop1(EXEC, mov_exec, k));
|
||||
let push_exec_lit = |w: &mut Vec<u32>, lit: u32| {
|
||||
w.push(sop1(EXEC, mov_exec, 255));
|
||||
w.push(lit);
|
||||
};
|
||||
|
||||
w.push(sop1(0, save_op, 193));
|
||||
w.extend(vop3(1, 0x101, 128, 256, 0));
|
||||
for shift in [1u16, 2, 4, 8] {
|
||||
w.push(vop2(1, 0x25, 0xFA, 1));
|
||||
w.push(dpp16(1, 0x110 + shift, 0xF, 0xF, false));
|
||||
}
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 15, 0));
|
||||
push_exec_lit(&mut w, 0xFFFF_0000);
|
||||
w.push(vop2(1, 0x25, 2, 1));
|
||||
|
||||
if wave64 {
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 31, 0));
|
||||
w.push(sop1(EXEC, 0x03, 128));
|
||||
w.push(sop1(EXEC + 1, 0x03, 255));
|
||||
w.push(0x0000_FFFF);
|
||||
w.push(vop2(1, 0x25, 2, 1));
|
||||
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 47, 0));
|
||||
w.push(sop1(EXEC, 0x03, 128));
|
||||
w.push(sop1(EXEC + 1, 0x03, 255));
|
||||
w.push(0xFFFF_0000);
|
||||
w.push(vop2(1, 0x25, 2, 1));
|
||||
}
|
||||
|
||||
push_exec(&mut w, 193);
|
||||
w.push(vop1(3, 0x01, 257));
|
||||
w.push(vop1(3, 0x01, 0xFA));
|
||||
w.push(dpp16(1, 0x111, 0xF, 0xF, false));
|
||||
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 15, 0));
|
||||
push_exec_lit(&mut w, 0x0001_0000);
|
||||
w.push(vop1(3, 0x01, 2));
|
||||
|
||||
if wave64 {
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 31, 0));
|
||||
w.push(sop1(EXEC, 0x03, 128));
|
||||
w.push(sop1(EXEC + 1, 0x03, 129));
|
||||
w.push(vop1(3, 0x01, 2));
|
||||
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 47, 0));
|
||||
w.push(sop1(EXEC, 0x03, 128));
|
||||
w.push(sop1(EXEC + 1, 0x03, 255));
|
||||
w.push(0x0001_0000);
|
||||
w.push(vop1(3, 0x01, 2));
|
||||
}
|
||||
|
||||
push_exec(&mut w, 193);
|
||||
w.push(vop1(2, 0x01, 128));
|
||||
w.push(vop1(5, 0x01, 135));
|
||||
push_exec(&mut w, 194);
|
||||
w.push(vop1(2, 0x01, 259));
|
||||
w.push(vop1(4, 0x01, 0xFA));
|
||||
w.push(dpp16(5, 0xE4, 0xF, 0xF, false));
|
||||
w.push(sop1(EXEC, mov_exec, 0));
|
||||
|
||||
let p = build(&w, wave64);
|
||||
let insts = &p.blocks[0].insts;
|
||||
let saved = insts[0].write(Reg::S(0)).unwrap();
|
||||
let v0_in = p
|
||||
.inputs
|
||||
.iter()
|
||||
.find_map(|&(r, v)| (r == Reg::V(0)).then_some(v))
|
||||
.unwrap();
|
||||
let v2_val = insts[insts.len() - 4].write(Reg::V(2)).unwrap();
|
||||
let v4_val = insts[insts.len() - 3].write(Reg::V(4)).unwrap();
|
||||
let sec = §ions(&p, 0)[&0];
|
||||
assert_eq!(
|
||||
sec.shapes.get(&v2_val),
|
||||
Some(&Shape::Prefix(Op::AddU, v0_in, saved, 0, false))
|
||||
);
|
||||
assert_eq!(sec.shapes.get(&v4_val), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp() {
|
||||
let w = [
|
||||
sop1(0, 0x3D, 193),
|
||||
vop1(1, 0x01, 135),
|
||||
sop1(EXEC, 0x04, 193),
|
||||
vop1(2, 0x01, 0xFA),
|
||||
dpp16(1, 0xE4, 0xF, 0xF, false),
|
||||
sop1(EXEC + 1, 0x03, 193),
|
||||
vop1(3, 0x01, 0xFA),
|
||||
dpp16(1, 0xE4, 0xF, 0xF, false),
|
||||
sop1(EXEC, 0x03, 0),
|
||||
];
|
||||
let p = build(&w, false);
|
||||
let insts = &p.blocks[0].insts;
|
||||
let v2_val = insts[3].write(Reg::V(2)).unwrap();
|
||||
let v3_val = insts[5].write(Reg::V(3)).unwrap();
|
||||
let sec = §ions(&p, 0)[&0];
|
||||
assert_eq!(sec.shapes.get(&v2_val), Some(&Shape::K(7)));
|
||||
assert_eq!(sec.shapes.get(&v3_val), Some(&Shape::K(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_lane_prefix_soundness() {
|
||||
let (v0, v_other, m0, m_other) = (Value(1), Value(2), Value(3), Value(4));
|
||||
let red = |op: Option<Op>, src: Value, mask: Value, ident: u32, lanes: u64| Sym::Red {
|
||||
op,
|
||||
src,
|
||||
mask,
|
||||
ident,
|
||||
lanes,
|
||||
};
|
||||
|
||||
for (wave, all) in [(32usize, u64::from(u32::MAX)), (64usize, u64::MAX)] {
|
||||
let below_mask = |l: usize| if l == 0 { 0 } else { (1u64 << l) - 1 };
|
||||
|
||||
let mut valid_inc: Vec<Sym> = (0..wave)
|
||||
.map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l) | (1u64 << l)))
|
||||
.collect();
|
||||
valid_inc[0] = red(None, v0, m0, 0, 1);
|
||||
assert_eq!(
|
||||
per_lane(&valid_inc, all),
|
||||
Some(Shape::Prefix(Op::AddU, v0, m0, 0, true))
|
||||
);
|
||||
|
||||
let mut valid_exc: Vec<Sym> = (0..wave)
|
||||
.map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l)))
|
||||
.collect();
|
||||
valid_exc[0] = Sym::K(0);
|
||||
valid_exc[1] = red(None, v0, m0, 0, 1);
|
||||
assert_eq!(
|
||||
per_lane(&valid_exc, all),
|
||||
Some(Shape::Prefix(Op::AddU, v0, m0, 0, false))
|
||||
);
|
||||
|
||||
let mut mixed_other_src = valid_exc.clone();
|
||||
mixed_other_src[0] = red(None, v_other, m0, 0, 1);
|
||||
assert_eq!(per_lane(&mixed_other_src, all), None);
|
||||
|
||||
let mut mixed_same_src = valid_exc.clone();
|
||||
mixed_same_src[0] = red(None, v0, m0, 0, 1);
|
||||
assert_eq!(per_lane(&mixed_same_src, all), None);
|
||||
|
||||
let mut exc_bad_lane1_src = valid_exc.clone();
|
||||
exc_bad_lane1_src[1] = red(None, v_other, m0, 0, 1);
|
||||
assert_eq!(per_lane(&exc_bad_lane1_src, all), None);
|
||||
|
||||
let mut exc_bad_lane1_set = valid_exc.clone();
|
||||
exc_bad_lane1_set[1] = red(None, v0, m0, 0, 0b11);
|
||||
assert_eq!(per_lane(&exc_bad_lane1_set, all), None);
|
||||
|
||||
for bad0 in [
|
||||
red(None, v0, m0, 1, 1),
|
||||
red(None, v_other, m0, 0, 1),
|
||||
red(None, v0, m_other, 0, 1),
|
||||
red(None, v0, m0, 0, 0),
|
||||
Sym::K(0),
|
||||
] {
|
||||
let mut bad_inc = valid_inc.clone();
|
||||
bad_inc[0] = bad0;
|
||||
assert_eq!(per_lane(&bad_inc, all), None);
|
||||
}
|
||||
|
||||
let mut bad_ident: Vec<Sym> = (0..wave)
|
||||
.map(|l| red(Some(Op::AddU), v0, m0, 1, below_mask(l) | (1u64 << l)))
|
||||
.collect();
|
||||
bad_ident[0] = red(None, v0, m0, 1, 1);
|
||||
assert_eq!(per_lane(&bad_ident, all), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user