CGBJ's renderer, DLSS, an F1 settings menu, frame generation, ray tracing switch

The default of scripts\play-nvidia.ps1 changes: the game renders its own
720p and DLSS takes it to 1080p (Series S), in place of the half render
scale and the title's upscaler. -Resolution still reaches the older path.

- Renderer: codec-d/cool_fox f4b48ad (GPL-3.0) with this fork's NVIDIA
  fixes on top (residency.rs, stretch.rs, the ffx upscale dispatch).
- DLSS for the title's upscale, from avatarmanz/VIctory-7900XTX pull
  request 203 (feature `dlss`, VICTORY_UPSCALE=dlss), with
  VICTORY_DLSS_PRESET and a live sharpness setting.
- F1 settings menu in the game (host/menu.rs): saved to
  victory-settings.txt, applied by the launcher at the next start,
  "save and restart" from the menu. F3: the panel, now with the
  generated frame rate beside the real one.
- DLSS frame generation through NVIDIA Streamline (streamline.rs, fg.rs),
  2x to 6x, the amount changed while playing. Constants and the depth and
  motion vector tags are handed over at each present.
- VICTORY_FPS_CAP: the title's own 30 frames a second can be lifted
  (60, 120, none), live from the menu.
- Real ray tracing as an option (-RayTracing, VICTORY_BVH_BUILDER=1): on
  this renderer the structure builder runs on NVIDIA. Frame generation is
  left off with it: the two together run at about 0.1 fps, cause not found.
- VICTORY_HEAP_RECHECK_EVERY: textures picked by index looked at again
  for the whole run (a test against the posterized look).
- Get-NVIDIA-DLSS.cmd / scripts\get-nvidia-sdks.ps1: fetch the few NVIDIA
  files DLSS and frame generation need (about 70 MB) from NVIDIA's GitHub
  into nvidia-sdk\ (git-ignored). They are NVIDIA's, under NVIDIA's
  licences, and are not part of this repository. Without them the picture
  is stretched and there is no frame generation.
- scripts\build-nvidia.ps1; the launcher builds the layer when it is not
  built, and again with DLSS once those files are there.

Measured on an RTX 5070 (Series S, DLSS, opening rooms): about 15-17 fps
without ray tracing, 13-15 with it, before generated frames. What is known
to be wrong is in the README's new section.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
trustno1-coderandClaude Fable 5.2 committed 2026-11-26 17:56:14 -08:00
1 parent 9e7ab9d9a2
commit 63957271cd
55 files changed
+8030 -1313

No files matched your search

+35 -4
View File
@@ -1228,12 +1228,43 @@ fn translated_compute_matches_pc() {
let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect();
root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true)));
root_views.sort_unstable();
let view_strides: Vec<u32> = views
.iter()
.map(|v| match *v {
View::RawUav(_) => 1,
View::HalfUav(_) => 8,
View::Buffer { stride, .. } => match stride {
Stride::Raw => 1,
Stride::Typed => 16,
Stride::Structured(s) => s,
Stride::Format(f, bytes) => {
let kind = match f.0 as u32 {
3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => {
super::VIEW_INTEGER
}
4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => {
super::VIEW_INTEGER | super::VIEW_SIGNED
}
_ => 0,
};
bytes | kind
}
},
_ => 0,
})
.collect();
for (n, (slot, srv)) in root_views.into_iter().enumerate() {
assert_eq!(slot, 4 + u8::from(srv), "{name}: root view");
let data = if srv {
root_srv.clone()
let data = if srv
&& (slot == super::SLOT_STRIDES || slot == super::SLOT_TABLE_STRIDES)
{
view_strides.clone()
} else {
root_cbv.clone()
assert_eq!(slot, 4 + u8::from(srv), "{name}: root view");
if srv {
root_srv.clone()
} else {
root_cbv.clone()
}
};
roots.push((1 + n as u32, Root::View { srv, data }));
}
+46
View File
@@ -1006,6 +1006,12 @@ pub enum View<'a> {
UintTextureUav(u32, u32),
/// A typed RGBA16F buffer UAV of this many elements, zeroed.
HalfUav(u32),
/// A typed buffer UAV pre-filled with `data` (`format`, bytes per element).
TypedUav {
data: &'a [u32],
format: DXGI_FORMAT,
elem_bytes: u32,
},
/// The same buffer viewed as R16G16B16A16_UINT: what a translated
/// program that moves halves is shown ([`super::HostShader::half_views`]).
HalfUintUav(u32),
@@ -1290,6 +1296,46 @@ impl Host {
)?;
uavs.push((b, None, n, rb));
}
View::TypedUav {
data,
format,
elem_bytes,
} => {
let n = data.len() as u32;
let bytes = u64::from(n) * 4;
let elements = (bytes / u64::from(elem_bytes)) as u32;
let b = make(
D3D12_HEAP_TYPE_DEFAULT,
&buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
D3D12_RESOURCE_STATE_COPY_DEST,
)?;
let up = upload(data)?;
list.CopyBufferRegion(&b, 0, &up, 0, bytes);
list.ResourceBarrier(&[transition(
&b,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
)]);
keep.push(up);
let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: format,
ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_UAV {
NumElements: elements,
Flags: D3D12_BUFFER_UAV_FLAG_NONE,
..Default::default()
},
},
};
dev.CreateUnorderedAccessView(&b, None, Some(&desc), at);
let rb = make(
D3D12_HEAP_TYPE_READBACK,
&buffer(bytes, D3D12_RESOURCE_FLAG_NONE),
D3D12_RESOURCE_STATE_COPY_DEST,
)?;
uavs.push((b, None, n, rb));
}
View::TextureUav(w, h) => {
let t = make(
D3D12_HEAP_TYPE_DEFAULT,
+2 -21
View File
@@ -59,14 +59,6 @@ struct Ray {
inverse: [V; 3],
}
/// LOCAL (from our wt5): `VICTORY_BVH_MISS=1` (off by default): the node test
/// misses every node. While the structure builder is off the structures are
/// never built, and a walk of what lies in their memory is not the console's.
fn bvh_miss() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_MISS").is_some_and(|v| v == "1"))
}
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> {
@@ -199,22 +191,11 @@ impl<'a> Lower<'a> {
.m
.terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join));
self.cur = box_block;
// LOCAL (from our wt5): with `VICTORY_BVH_MISS=1` every node is missed
// without being read: a box returns no child and a triangle the
// triangle miss, so a walk ends at its first node.
let boxes = if bvh_miss() {
[self.s.m.i32(bvh::NONE); 4]
} else {
self.bvh_boxes(at, kind, &ray, sort)
};
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 = if bvh_miss() {
bvh::MISS.map(|f| self.s.m.i32(f.to_bits()))
} else {
self.bvh_triangle(at, kind, &ray)
};
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;
+66 -24
View File
@@ -441,6 +441,7 @@ enum MaskData {
/// What a value holding a lane mask read as a number stops with.
pub(super) const LANE_MASK: Why = "a lane mask read as data";
pub(super) const DIVERGENT_MASK_EXCHANGE: Why = "a lane mask exchanged where not every lane runs";
/// A mask with lanes outside EXEC where it is written, read as a number where the lanes that
/// run that block are not all of the wave.
pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data";
@@ -564,7 +565,7 @@ fn need(block: usize) {
/// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`.
/// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes
/// run (no lane branch can have split the arriving lanes); loop-carried values never do.
fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
fn lane_uniform(p: &Program, st: &Structured, all: &[bool], ordered_lds: bool) -> HashSet<Value> {
let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
let mut same: HashSet<Value> = HashSet::new();
for b in crate::ir::reverse_postorder(&p.blocks) {
@@ -577,6 +578,9 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
}
for (i, inst) in block.insts.iter().enumerate() {
let name = inst.name();
if st.guards[b][i].is_some() {
continue; // lanes outside EXEC keep another value
}
let ops: Vec<Operand> = match &inst.fields {
Fields::Valu(v)
if v.dpp.is_none()
@@ -587,11 +591,18 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
{
v.src.clone()
}
Fields::Ds {
addr: Some(Operand::Vector { reg, dwords: 1 }),
gds: false,
..
} if ordered_lds && name == "ds_read_b32" => {
if inst.read(Reg::V(*reg)).is_some_and(|a| same.contains(&a)) {
same.extend(inst.writes.iter().map(|w| w.1));
}
continue;
}
_ => continue,
};
if st.guards[b][i].is_some() {
continue; // lanes outside EXEC keep another value
}
let alike = ops.iter().all(|op| match *op {
Operand::Vector { reg, .. } => {
// every dword of the operand the instruction reads from that register on
@@ -1193,6 +1204,13 @@ thread_local! {
}
pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
// A scalar select uses the condition of the whole guest wave, even
// when the preceding mask operation has no scalar-dword consumers.
if matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_))
&& i.read(Reg::Scc).is_some_and(|s| st.scc_some.contains_key(&s))
{
return true;
}
let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
let ops: Vec<&Operand> = match &i.fields {
// A mask operation (its result a mask) is no data use.
@@ -1698,7 +1716,9 @@ impl<'a> Lower<'a> {
local_ok: false,
local_any: LOCAL_ANY.get(),
uniform: match &exchange {
Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all),
Some((_, false, all)) if !LOCAL_WAVES.get() => {
lane_uniform(p, x.st, all, split_lds && super::group_sync() != 0)
}
_ => HashSet::new(),
},
own_bits: match &exchange {
@@ -3549,7 +3569,7 @@ impl<'a> Lower<'a> {
} else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) {
// (a group of 32 or fewer has no other half to exchange with)
need(b.unwrap_or(0));
return Err("a lane mask exchanged where not every lane runs");
return Err(DIVERGENT_MASK_EXCHANGE);
}
xy = self.exchange_halves(at, xy.0);
}
@@ -4250,7 +4270,7 @@ impl<'a> Lower<'a> {
}
if !made.is_none_or(|b| self.all_lanes(b)) {
need(made.unwrap_or(0));
return Err("a lane mask exchanged where not every lane runs");
return Err(DIVERGENT_MASK_EXCHANGE);
}
let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
let (lo, hi) = self.exchange_halves(at, some);
@@ -6049,6 +6069,13 @@ impl<'a> Lower<'a> {
fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
if self.x.st.scc_some.contains_key(&v)
&& matches!(self.vals.get(&v), None | Some(Val::Missing(_)))
{
let x = self.scc_some(v)?;
self.vals.insert(v, Val::Bit(x));
return Ok(x);
}
match self.get(v) {
Ok(Val::Bit(x)) => Ok(x),
Ok(_) => Err("SCC without a value"),
@@ -7526,7 +7553,7 @@ impl<'a> Lower<'a> {
/// `ResourceHeap`): read from the host's table by heap slot in the
/// current block.
fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
let word = self.slot_word(src)?;
let word = self.slot_word(src, false)?;
Ok(word.map(|word| {
let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS);
let stride = self.s.m.bin(self.cur, Bin::And, word, bits);
@@ -7549,18 +7576,17 @@ impl<'a> Lower<'a> {
if !super::shader::constant_marks() {
return Ok(None);
}
let Some(word) = self.slot_word(src)? else {
let Some(word) = self.slot_word(src, false)? else {
return Ok(None);
};
let mark = self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT);
let mark =self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT);
Ok(Some(self.s.m.cmp(self.cur, pred::EQ, word, mark)))
}
/// Whether the typed buffer view `src` names is one of an integer format,
/// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the
/// program does not pick from the heap).
/// and whether a signed one (`ResourceHeap` or `Table`).
fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> {
let Some(word) = self.slot_word(src)? else {
let Some(word) = self.slot_word(src, true)? else {
return Ok(None);
};
let c = self.cur;
@@ -7574,19 +7600,22 @@ impl<'a> Lower<'a> {
}
/// The host's word for the buffer view `src` names: its stride and
/// format kind ([`super::shader::SLOT_STRIDES`]).
fn slot_word(&mut self, src: &Source) -> Result<Option<V>, Why> {
/// format kind ([`super::shader::SLOT_STRIDES`] for `ResourceHeap`,
/// [`super::shader::SLOT_TABLE_STRIDES`] for `Table` when `allow_table`).
fn slot_word(&mut self, src: &Source, allow_table: bool) -> Result<Option<V>, Why> {
let Source::Loaded { load, first } = src else {
return Ok(None);
};
let heap = self
let srv_slot = match self
.scalar
.get(load)
.and_then(|a| self.x.native.layout.get(a.param))
.is_some_and(|p| p.root == RootType::ResourceHeap);
if !heap {
return Ok(None);
}
.map(|p| p.root)
{
Some(RootType::ResourceHeap) => super::shader::SLOT_STRIDES,
Some(RootType::Table) if allow_table => super::shader::SLOT_TABLE_STRIDES,
_ => return Ok(None),
};
let key = (self.cur, *load, *first);
if let Some(&v) = self.strides.get(&key) {
return Ok(Some(v));
@@ -7601,7 +7630,7 @@ impl<'a> Lower<'a> {
self.s.m.tag(slot, Tag::Clamp);
let two = self.s.m.i32(2);
let byte = self.s.m.bin(c, Bin::Shl, slot, two);
let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
let h = self.s.root_srv_handle(srv_slot);
let iu = self.s.m.undef(self.s.t.i32);
let mask = self.s.m.i8(1);
let align = self.s.m.i32(4);
@@ -7769,6 +7798,15 @@ impl<'a> Lower<'a> {
unreachable!()
};
let name = inst.name();
if let Some(&source) = self.x.res.restored_lanes.get(&(b, i)) {
// This lane was overwritten by a uniform scalar. The previous
// contents of other lanes can be unknown (a reduction scratch).
let word = match source {
crate::resource::Moved::Value(v) => self.i32_of(v)?,
crate::resource::Moved::Const(k) => self.s.m.i32(k),
};
return self.write_i(inst, word, None);
}
if self.x.res.waterfall.compares.contains(&(b, i)) {
// The first lane's dwords of a waterfall loop are each lane's
// own (see `resource::Waterfall`).
@@ -11963,9 +12001,13 @@ impl<'a> Lower<'a> {
// through a view of an integer format it is a 16-bit
// integer, zero- or sign-extended (VIctory 4243a96a: the face
// network keeps its halves in UINT views; its output was
// noise). shortcut: that is known of the views a program
// picks from the heap; and the handle stays a float one,
// whose bits the drivers pass.
// noise). Both `ResourceHeap` (`SLOT_STRIDES`) and `Table`
// (`SLOT_TABLE_STRIDES`, dynamic table snapshots included)
// populate the view-kind bits, while the handle stays a float
// one (`0x409`), whose raw bits RTX and WARP pass bit-exact
// without extra CFG blocks or touching non-d16 shaders.
// LOCAL (faces): not where the program moves halves as
// integers (`halves`): those views are shown as UINT already.
let integer = if typed && !halves { self.integer_view(src)? } else { None };
let mut wide = Vec::new();
for k in 0..count {
+113 -18
View File
@@ -122,7 +122,7 @@ pub use lower::{host_settings, set_host_max_wave, set_host_rdna};
pub use rect::rect_list_gs;
pub use shader::{
MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
SLOT_STRIDE_CONSTANT, SLOT_STRIDES_COUNT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
SLOT_STRIDE_CONSTANT, SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
constant_marks, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
};
@@ -500,17 +500,45 @@ pub fn emit(
};
// 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 form = |label: &str, p: Option<ir::Program>| {
let Some(p) = p else {
if why {
eprintln!("WAVE64-FORM {label}: ir returned None");
}
return None;
};
let st = match structure::structure(&p) {
Ok(st) => st,
Err(e) => {
if why {
eprintln!("WAVE64-FORM {label}: structure failed: {e}");
}
return None;
}
};
let io = match io::raise(&p, native) {
Ok(io) => io,
Err(e) => {
if why {
eprintln!("WAVE64-FORM {label}: io::raise failed: {e}");
}
return None;
}
};
let res = match resource::track(&p, &native.layout, native.stage, Some(&st)) {
Ok(res) => res,
Err(e) => {
if why {
eprintln!("WAVE64-FORM {label}: resource::track failed: {e}");
}
return None;
}
};
Some((p, st, io, res))
};
let forms = [
("without early-outs", form(ir::without_early_outs(p))),
("without skips", form(ir::without_skips(p, false))),
("without early-outs", form("without early-outs", ir::without_early_outs(p))),
("without skips", form("without skips", ir::without_skips(p, false))),
];
for (name, f) in &forms {
if let Some((p, st, io, res)) = f {
@@ -526,7 +554,24 @@ pub fn emit(
// lost the card in a submission of two programs that had just moved to it
// (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which
// has no barrier, stays on.
let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1");
let wide_option = std::env::var_os("VICTORY_WAVE_WIDE");
// Both archived kernels use one logical wave per group and have
// validated wave32 PSOs on RTX. Explicit policy wins.
let scene_kernel = matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64)
&& matches!(
c.digest,
[0x58, 0x1d, 0xab, 0x2c, 0xd8, 0xbc, 0xf2, 0x2e, 0x5c, 0x96, 0x4b, 0x98, 0xe9, 0x03, 0x48, 0xd1]
| [0x24, 0x31, 0xbb, 0xe7, 0xdc, 0x15, 0x4a, 0xd7, 0x59, 0xd2, 0x0b, 0xc9, 0x54, 0x82, 0x9c, 0x1c]
);
let wide_on = wide_option.as_ref().map_or(scene_kernel, |v| v == "1");
// A single guest wave can iterate an active-lane loop until both host
// halves have finished. The precise latch and convergence conditions
// for the driver compute route are checked by widen().
let driver_loop = wide_option.is_none()
&& c.part(FourCC::DXIL).is_none()
&& c.part(FourCC::ACCC).is_some()
&& matches!(&original, Err(ShaderError::Unsupported { what, .. })
if *what == lower::DIVERGENT_MASK_EXCHANGE);
// exact first: each host wave on its own where that is exact (the idiom, every
// form; no barriers), then the other exact forms; then approximate
for exact in [true, false] {
@@ -537,7 +582,7 @@ pub fn emit(
// lane runs, where the two host waves can exchange.
// (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.)
let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0");
let deep = if deep_on { form(ir::without_skips(p, true)) } else { None };
let deep = if deep_on { form("without skips, scalars followed", ir::without_skips(p, true)) } else { None };
if let Some((p, st, io, res)) = &deep {
let again = emit_program(c, native, p, st, io, res);
report("without skips, scalars followed", &again);
@@ -548,7 +593,7 @@ pub fn emit(
// Still stopped where not every lane runs: the per-lane branches around
// those places taken as the console takes them, by the whole wave at once
// ([`widen`]), at two group barriers per such branch.
if wide_on {
if wide_on || driver_loop {
let bases = [
deep.as_ref().map(|f| &f.0),
forms[1].1.as_ref().map(|f| &f.0),
@@ -556,7 +601,7 @@ pub fn emit(
Some(p),
];
if let Some(base) = bases.into_iter().flatten().next() {
let again = widen(c, native, base, why);
let again = widen(c, native, base, why, driver_loop);
report("wave-wide branches", &again);
if done(&again) {
return again.map(|(shader, _)| shader);
@@ -618,7 +663,7 @@ pub fn emit(
&& what == lower::LANE_MASK
&& std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") =>
{
let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some());
let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some(), false);
match again {
Ok(_) => again,
Err(_) => emit_program(c, native, p, st, io, res),
@@ -626,7 +671,17 @@ pub fn emit(
}
other => other,
};
let original = original.map(|(shader, _)| shader);
let supported = |(shader, wave): (HostShader, Option<u32>)| {
if wave == Some(64) && lower::host_max_wave() == 32 {
Err(ShaderError::Unsupported {
offset: 0,
what: "no wave32 lowering for this wave64 program",
})
} else {
Ok(shader)
}
};
let original = original.and_then(supported);
// 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 { .. })) {
@@ -640,7 +695,7 @@ pub fn emit(
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)
emit_program(c, native, &p, &st, &io, &res).and_then(supported)
}
/// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane
@@ -655,6 +710,7 @@ fn widen(
native: &NativeProgram,
p: &ir::Program,
why: bool,
active_loop_only: bool,
) -> Result<(HostShader, Option<u32>), ShaderError> {
const NOT: ShaderError = ShaderError::Unsupported {
offset: 0,
@@ -687,7 +743,22 @@ fn widen(
|| matches!(&r, Ok((_, Some(64)))) && !needs.is_empty();
if !stuck {
if why {
eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len());
let order = ir::reverse_postorder(&p.blocks);
let mut rpo = vec![0usize; p.blocks.len()];
for (i, &b) in order.iter().enumerate() {
rpo[b] = i;
}
let mut sorted: Vec<usize> = wide.iter().copied().collect();
sorted.sort_unstable();
let desc: Vec<String> = sorted
.iter()
.map(|&b| {
let back = matches!(p.blocks[b].exit, ir::Exit::Branch { taken, not_taken } if rpo[taken] <= rpo[b] || rpo[not_taken] <= rpo[b]);
let nm = p.blocks[b].insts.last().map_or("?", |i| i.name());
format!("B{b}({nm}{})", if back { ",BACK" } else { "" })
})
.collect();
eprintln!("WAVE64-WIDE {} branches taken wave-wide: [{}]", wide.len(), desc.join(", "));
}
return r;
}
@@ -702,6 +773,30 @@ fn widen(
}
return r;
}
if active_loop_only {
// Only a single backward branch on the SCC just set by
// s_andn2_wrexec_b64. This instruction restricts EXEC to the
// unfinished lanes. The guest repeats the loop if *either*
// half still has work, while individual vector writes retain
// their EXEC predicates.
let [latch] = more.as_slice() else {
return r;
};
let block = &p.blocks[*latch];
let [.., update, branch] = block.insts.as_slice() else {
return r;
};
if !wide.is_empty()
|| update.name() != "s_andn2_wrexec_b64"
|| branch.name() != "s_cbranch_scc1"
|| !matches!(
block.exit,
ir::Exit::Branch { taken, not_taken } if taken <= *latch && not_taken > *latch
)
{
return r;
}
}
wide.extend(more);
}
}
+5
View File
@@ -24,6 +24,11 @@ pub const ROOT_CBV_SPACE: u32 = 1;
/// 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;
/// The same table of strides and format kinds as [`SLOT_STRIDES`], bound for
/// shaders that only inspect views from descriptor tables (`RootType::Table`).
/// Kept distinct from [`SLOT_STRIDES`] so the host binds the table without
/// running the full bindless heap buffer sweep.
pub const SLOT_TABLE_STRIDES: u8 = 252;
/// The bits of a [`SLOT_STRIDES`] dword that hold the stride.
pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1;
/// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format
+270 -423
View File
@@ -181,7 +181,6 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
@@ -1919,7 +1918,6 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: Vec::new(),
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
@@ -2060,76 +2058,48 @@ fn rdna_forms_give_what_the_spelled_out_ones_give() {
}
}
/// A program that moves a typed buffer's 16-bit channels
/// (`buffer_load_format_d16_xyzw` from the table's first view,
/// `buffer_store_format_d16_xyzw` to its second) names both places for the
/// host (`HostShader::half_views`) and moves every pattern as it is through
/// unsigned views: half floats, the not-a-number ones among them, and
/// plain 16-bit integers (the title keeps both in such buffers; the
/// network that moves its faces reads indices this way). A program that
/// moves no halves names nothing.
#[test]
fn halves_go_through_a_table_as_they_are_and_name_their_views() {
use super::host::Stride;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_UINT;
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | op << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
const LOAD_D16_XYZW: u32 = 0x83;
const STORE_D16_XYZW: u32 = 0x87;
const THREADS: u32 = 32;
// The table's second descriptor, 0x20 bytes on.
let mut second = s_load_dwordx4(12, 4);
second[1] |= 0x20;
let mut words = vec![s_mov_b32(5, 0x80)];
words.extend_from_slice(&s_load_dwordx4(8, 4));
words.extend_from_slice(&second);
// v[1:2] = first[thread] (four halves), second[thread] = v[1:2].
words.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8));
words.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12));
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u8, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | (op as u32) << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null).
const fn s_load_dwordx4_off(dst: u8, base: u8, byte_offset: u32) -> [u32; 2] {
[
0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1),
(125 << 25) | (byte_offset & 0x1F_FFFF),
]
}
/// Builds a compute shader whose descriptors live in a `RootType::Table` at
/// `s4` (like `compute_graph_ops` and `ped_standard_head_cs`).
fn build_table_typed_cs(body: &[u32], used: Vec<UsedResource>) -> HostShader {
let mut words = Vec::new();
words.push(s_mov_b32(5, 0x80)); // s5 = 0
words.extend_from_slice(body);
words.push(S_ENDPGM);
let view = |kind: ResourceType, table_offset_dwords: u32| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords,
lower_bound: table_offset_dwords / 8,
stride: 4,
dwords: 4,
user_data: 4,
slot: 1,
};
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
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![view(ResourceType::Srv, 0), view(ResourceType::Uav, 8)],
layout: vec![RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 0,
}],
used,
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1,
threads: [THREADS, 1, 1],
rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
threads: [4, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
code,
};
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
@@ -2148,7 +2118,6 @@ fn halves_go_through_a_table_as_they_are_and_name_their_views() {
mesh_stride: 0,
})
.expect("lower");
assert_eq!(lowered.half_views, [(1, 0), (1, 8)]);
let shader = HostShader {
stage: HwStage::Cs,
dxil: lowered.dxil,
@@ -2159,362 +2128,252 @@ fn halves_go_through_a_table_as_they_are_and_name_their_views() {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut dxil = shader.dxil.clone();
v.validate(&mut dxil).expect("DXIL validation failed");
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
// A raw store through the same table: no halves, nothing named.
assert!(build_valu_cs(&[]).half_views.is_empty());
// Four halves a thread: numbers, both zeros, subnormals, infinities,
// not-a-numbers of both signs, and integers past the largest number's
// pattern, as indices are.
const SPECIAL: [u16; 16] = [
0x0000, 0x0001, 0x03ff, 0x0400, 0x3c00, 0x7bff, 0x7c00, 0x7c01, 0x7e00, 0x7fff, 0x8000,
0x8001, 0xbc00, 0xfc00, 0xfc01, 0xffff,
];
let halves: Vec<u16> = (0..4 * THREADS as usize)
.map(|i| match i {
0..16 => SPECIAL[i],
_ => (i as u16).wrapping_mul(0x0203).wrapping_add(0x7b00),
})
.collect();
let data: Vec<u32> = halves
.chunks(2)
.map(|pair| u32::from(pair[0]) | u32::from(pair[1]) << 16)
.collect();
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)] {
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}"));
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
ud[u.index as usize] = match (u.root, u.slot) {
(RootType::Table, 1) => 0,
other => panic!("unexpected user data {other:?}"),
};
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[
View::Buffer {
data: &data,
stride: Stride::Format(DXGI_FORMAT_R16G16B16A16_UINT, 8),
},
View::HalfUintUav(THREADS),
],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
assert_eq!(
out[0], data,
"{label}: the halves stored are the halves loaded"
);
ran += 1;
}
assert!(ran > 0, "no SM 6.6 device available");
shader
}
/// The places a program that moves halves names are the descriptors it
/// loads, not the start of the range their used-resource entry describes:
/// with one entry for a range from dword 0, a load at byte 0x20 names
/// dword 8 (a host view there in a 16-bit float format is the one shown
/// as its unsigned twin). A descriptor picked at run time (the load's
/// offset in an SGPR) names nothing and keeps the float path: which slot
/// it reads, and in which format, is known only then.
/// `compute_graph_ops` (facial lip-sync & wrapped submesh solver) binds
/// `R16G16B16A16_UINT` / `R16_UINT` UAVs via `RootType::Table` (which on NVIDIA
/// are snapshotted into dynamic descriptor slots) and reads/writes FP16 bit
/// patterns with `buffer_load_format_d16_xyzw` and `buffer_store_format_d16_xyzw`.
/// Verify bit-exact round-trips for UINT, SINT, and FLOAT views (including
/// non-zero table offsets matching dynamic descriptor snapshots) on hardware
/// GPU and WARP.
#[test]
fn half_places_are_the_descriptors_the_program_loads() {
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | op << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
const LOAD_D16_XYZW: u32 = 0x83;
const STORE_D16_XYZW: u32 = 0x87;
let lowered = |words: &[u32]| {
let range = |kind: ResourceType, table_offset_dwords: u32| UsedResource {
kind,
fn typed_d16_table_uav_roundtrip_uint_sint_and_float() {
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_SINT,
DXGI_FORMAT_R16G16B16A16_UINT,
};
let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut body = Vec::new();
// s[8:11] = table[0] (src typed UAV), s[12:15] = table[1] (dst typed UAV),
// s[16:19] = table[2] (raw UAV dump of loaded v[2:3]).
body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0));
body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32));
body.extend_from_slice(&s_load_dwordx4_off(16, 4, 64));
// buffer_load_format_d16_xyzw v[2:3], v0, s[8:11], 0 idxen (op 0x83)
body.extend_from_slice(&mubuf_idxen(0x83, 2, 0, 8));
// buffer_store_format_d16_xyzw v[2:3], v0, s[12:15], 0 idxen (op 0x87)
body.extend_from_slice(&mubuf_idxen(0x87, 2, 0, 12));
// Also dump thread 0's loaded v[2:3] into raw UAV (table[2]) to verify the load itself.
// v4 = v0 << 3 (byte offset = thread * 8)
body.push(0x3408_0083); // v_lshlrev_b32 v4, 3, v0
// buffer_store_dwordx2 v[2:3], v4, s[16:19], 0 offen (op 0x1D, offen bit 12)
body.extend_from_slice(&[
0x38 << 26 | 0x1D << 18 | 1 << 12,
0x80 << 24 | (16u32 >> 2) << 16 | (2u32 << 8) | 4u32,
]);
let used = (0..3u32)
.map(|k| UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords,
lower_bound: table_offset_dwords / 8,
table_offset_dwords: k * 8,
lower_bound: k,
stride: 4,
dwords: 4,
user_data: 4,
slot: 1,
};
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
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,
},
],
// One entry for a range of views from dword 0, one at 16.
used: vec![range(ResourceType::Srv, 0), range(ResourceType::Uav, 16)],
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1,
threads: [32, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
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("resource::track");
let io = io::raise(&p, &native).expect("io::raise");
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,
slot: 0,
})
.expect("lower")
};
// `s_load_dwordx4 s[dst:dst+3], s[4:5], offset` (soffset null), or with
// the offset in `soffset` instead.
let at = |dst: u8, offset: u32| {
let mut w = s_load_dwordx4(dst, 4);
w[1] |= offset;
w
};
let picked = |dst: u8, soffset: u8| {
let mut w = s_load_dwordx4(dst, 4);
w[1] = u32::from(soffset) << 25;
w
};
let mut fixed = vec![s_mov_b32(5, 0x80)];
fixed.extend_from_slice(&at(8, 0x20));
fixed.extend_from_slice(&at(12, 0x40));
fixed.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8));
fixed.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12));
fixed.push(S_ENDPGM);
assert_eq!(lowered(&fixed).half_views, [(1, 8), (1, 16)]);
// The load's offset in s20, from the first lane's thread index
// (`v_readfirstlane_b32 s20, v0`): picked at run time. The pick may land
// on the store's place too, so no place of that table is named: the d16
// accesses there take the float path, as before half views.
let mut runtime = vec![s_mov_b32(5, 0x80), vop1(0x02, 20, vgpr(0))];
runtime.extend_from_slice(&picked(8, 20));
runtime.extend_from_slice(&at(12, 0x40));
runtime.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8));
runtime.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12));
runtime.push(S_ENDPGM);
assert!(lowered(&runtime).half_views.is_empty());
}
/// A format load of whole dwords (`buffer_load_format_x`, not d16) whose
/// result the program only reads one half of as a half float
/// (`v_cvt_f32_f16`) is moving 16-bit integers: the head program reads the
/// face network's output so, from an `R16_UINT` view. It names its view for
/// the host and loads the integer: 0x3c00 comes through as 1.0. Used as a
/// whole float instead (`v_add_f32`), the load stays a float load and names
/// nothing; so does a load of halves beside a load of the same view read as
/// a whole float (a view of numbers the program also picks one half float
/// out of, as hundreds of the title's pixel programs do).
#[test]
fn a_format_load_read_as_halves_loads_the_integer() {
use super::host::Stride;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT;
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | op << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
const LOAD_FORMAT_X: u32 = 0x00;
const V_CVT_F32_F16: u16 = 0x0B;
const V_ADD_F32: u8 = 0x03;
let lowered = |body: &[u32]| {
let view = |kind: ResourceType, table_offset_dwords: u32, stride: u32| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords,
lower_bound: table_offset_dwords / 8,
stride,
dwords: 4,
user_data: 4,
slot: 1,
};
let mut second = s_load_dwordx4(12, 4);
second[1] |= 0x20;
let mut words = vec![s_mov_b32(5, 0x80)];
words.extend_from_slice(&s_load_dwordx4(8, 4));
words.extend_from_slice(&second);
// `body` leaves v2, stored raw.
words.extend_from_slice(body);
words.extend_from_slice(&buffer_store_dword(2, 12, 0));
words.push(S_ENDPGM);
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
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![view(ResourceType::Srv, 0, 4), view(ResourceType::Uav, 8, 0)],
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1,
threads: [1, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
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("resource::track");
let io = io::raise(&p, &native).expect("io::raise");
let l = lower::lower(&lower::Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
})
.expect("lower");
HostShader {
stage: HwStage::Cs,
dxil: l.dxil,
user_data: l.user_data,
samplers: l.samplers,
static_samplers: Vec::new(),
root_cbvs: l.root_cbvs,
root_srvs: l.root_srvs,
root_uavs: l.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: l.half_views,
}
};
// v1 = first[v0] (one channel).
let load = mubuf_idxen(LOAD_FORMAT_X, 1, 0, 8);
let half = vop1(V_CVT_F32_F16, 2, vgpr(1));
let as_halves = lowered(&[&load[..], &[half]].concat());
assert_eq!(as_halves.half_views, [(1, 0)]);
let as_float = lowered(&[&load[..], &[vop2(V_ADD_F32, 2, vgpr(1), 1)]].concat());
assert!(as_float.half_views.is_empty());
// v3 = first[v0] too, read as a whole float: v2 = half(v1) + v3.
let mut beside = load.to_vec();
beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8));
beside.push(half);
beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2));
assert!(lowered(&beside).half_views.is_empty());
// Behind a branch, as the head program has it: where the lanes meet
// again the loaded value goes on through a phi, and a later write of
// v1 under EXEC reads it only to keep it in the lanes it leaves alone.
const SAVE_EXEC: u32 = 0xBE90_037E; // s_mov_b32 s16, exec_lo
const ONLY_LANE_0: u32 = 0x7DA4_0080; // v_cmpx_eq_u32 exec_lo, 0, v0
const SKIP_3: u32 = 0xBF88_0003; // s_cbranch_execz over the next 3 words
const RESTORE_EXEC: u32 = 0xBEFE_0310; // s_mov_b32 exec_lo, s16
let zero = vop1(0x01, 2, 128); // v_mov_b32 v2, 0
let rewrite = vop1(0x01, 1, 128); // v_mov_b32 v1, 0
let branched = lowered(
&[
&[zero, SAVE_EXEC, ONLY_LANE_0, SKIP_3][..],
&load,
&[
half,
RESTORE_EXEC,
SAVE_EXEC,
ONLY_LANE_0,
rewrite,
RESTORE_EXEC,
],
]
.concat(),
.collect();
let shader = build_table_typed_cs(&body, used);
assert!(
shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES),
"table typed d16 shader should request SLOT_TABLE_STRIDES"
);
assert_eq!(branched.half_views, [(1, 0)]);
// A d16 load names its place where it is the only access there...
const LOAD_FORMAT_D16_X: u32 = 0x80;
let d16 = mubuf_idxen(LOAD_FORMAT_D16_X, 1, 0, 8);
let d16_alone = lowered(&[&d16[..], &[half]].concat());
assert_eq!(d16_alone.half_views, [(1, 0)]);
// ...and not beside a whole float read through the same place, which
// would see the unsigned twin: v2 = half(d16 v1) + v3.
let mut d16_beside = d16.to_vec();
d16_beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8));
d16_beside.push(half);
d16_beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2));
assert!(lowered(&d16_beside).half_views.is_empty());
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
for shader in [&as_halves, &branched, &d16_alone] {
let mut dxil = shader.dxil.clone();
v.validate(&mut dxil).expect("DXIL validation failed");
}
}
// Element 0 of an R16_UINT buffer holds the half 1.0 (0x3c00).
let data = [0x0000_3c00u32, 0];
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)] {
let Ok(host) = Host::new(warp) else {
eprintln!("no SM 6.6 {label} device; skipped");
continue;
};
for (name, shader) in [("straight", &as_halves), ("branched", &branched)] {
let (root, pso) = host
.compute_pipeline(shader)
.unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
assert!(
!shader.root_srvs.contains(&super::SLOT_STRIDES),
"table-only shader must not trigger the bindless SLOT_STRIDES sweep"
);
// 4 elements x 4 u16 channels = 8 u32 dwords.
// Includes FP16 subnormal (0x0001), -0.0 (0x8000), 1.0 (0x3C00), -1.0 (0xBC00),
// NaN (0x7E00), max u16 (0xFFFF), and arbitrary patterns.
let uint_bits: [u32; 8] = [
0x3C00_0001, 0x7E00_BC00,
0xFFFF_8000, 0xABCD_1234,
0x0002_0000, 0x7BFF_FBFF,
0xDEAD_BEEF, 0xCAFE_BABE,
];
let sint_bits: [u32; 8] = [
0xFFFF_8000, 0x7FFF_0001,
0xC000_0000, 0x8001_7FFE,
0xFFFF_FFFF, 0x0000_0000,
0xFEDC_BA98, 0x7654_3210,
];
// Normal finite FP16 values that round-trip cleanly through f32.
let float_bits: [u32; 8] = [
0x4000_3C00, 0x3800_BC00, // 1.0, 2.0, -1.0, 0.5
0xC200_3400, 0x4500_0000, // 0.25, -3.0, 0.0, 5.0
0x3E00_BE00, 0x4400_C400, // -1.5, 1.5, -4.0, 4.0
0x3C00_0000, 0x4200_C000, // 0.0, 1.0, -2.0, 3.0
];
let zeros = [0u32; 8];
let cases = [
("R16G16B16A16_UINT @0", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 0u32),
("R16G16B16A16_UINT @3 (dynamic offset)", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 3u32),
("R16G16B16A16_SINT @0", DXGI_FORMAT_R16G16B16A16_SINT, 8 | super::VIEW_INTEGER | super::VIEW_SIGNED, &sint_bits, 0u32),
("R16G16B16A16_FLOAT @0", DXGI_FORMAT_R16G16B16A16_FLOAT, 8, &float_bits, 0u32),
];
for (backend, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else { continue };
let (root, pso) = host
.compute_pipeline(&shader)
.unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}"));
for &(label, format, stride_word, input, base_slot) in &cases {
let mut views = Vec::new();
let mut strides = Vec::new();
for _ in 0..base_slot {
views.push(View::RawUav(1));
strides.push(0u32);
}
let uav_base = base_slot as usize;
views.push(View::TypedUav { data: input, format, elem_bytes: 8 });
strides.push(stride_word);
views.push(View::TypedUav { data: &zeros, format, elem_bytes: 8 });
strides.push(stride_word);
views.push(View::RawUav(8));
strides.push(1);
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
ud[u.index as usize] = match (u.root, u.slot) {
(RootType::Table, 1) => 0,
other => panic!("unexpected user data {other:?}"),
};
if u.root == RootType::Table && u.slot == 0 {
ud[u.index as usize] = base_slot * 32;
}
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![
(0, Root::Constants(ud)),
(1, Root::View { srv: true, data: strides }),
],
views: &views,
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}"));
assert_eq!(
out[uav_base + 2],
input,
"{backend} {label}: buffer_load_format_d16_xyzw mismatch"
);
assert_eq!(
out[uav_base + 1],
input,
"{backend} {label}: buffer_store_format_d16_xyzw mismatch"
);
}
}
}
/// Non-`d16` typed loads (`buffer_load_format_x`) are used by
/// `CS_BlendshapeTranslationsHSSGraphOutputExtract` (reading `HSSGraphOut`
/// `R16_UINT`) and `CS_PedStandardSkinning_*` (reading bone indices). Verify
/// exact integer bits for `R16_UINT`, `R16_SINT`, and `R32_UINT`.
#[test]
fn typed_non_d16_table_load_preserves_integer_bits() {
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R32_UINT,
};
let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut body = Vec::new();
// s[8:11] = table[0] (src typed SRV), s[12:15] = table[1] (raw UAV out)
body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0));
body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32));
// buffer_load_format_x v2, v0, s[8:11], 0 idxen (op 0x00)
body.extend_from_slice(&mubuf_idxen(0x00, 2, 0, 8));
// v4 = v0 << 2 (byte offset = thread * 4)
body.push(0x3408_0082); // v_lshlrev_b32 v4, 2, v0
// buffer_store_dword v2, v4, s[12:15], 0 offen (op 0x1C, offen bit 12)
body.extend_from_slice(&[
0x38 << 26 | 0x1C << 18 | 1 << 12,
0x80 << 24 | (12u32 >> 2) << 16 | (2u32 << 8) | 4u32,
]);
let used = vec![
UsedResource {
kind: ResourceType::Srv,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 4,
dwords: 4,
user_data: 4,
slot: 0,
},
UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 8,
lower_bound: 1,
stride: 4,
dwords: 4,
user_data: 4,
slot: 0,
},
];
let shader = build_table_typed_cs(&body, used);
// Non-d16 typed loads stay untouched (no SLOT_TABLE_STRIDES root SRV, no
// CFG branches) so non-d16 pixel/mesh/particle/skinning shaders keep
// identical DXIL and pipeline cache keys while still preserving raw bits.
assert!(
!shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES),
"non-d16 typed load should not add SLOT_TABLE_STRIDES"
);
let r16_data = [0x3C00_0001u32, 0xFFFF_BC00u32];
let r32_data = [0xDEAD_BEEFu32, 0x0000_0001, 0x8000_0000, 0x7FFF_FFFF];
let cases: [(&str, _, u32, &[u32], [u32; 4]); 3] = [
(
"R16_UINT",
DXGI_FORMAT_R16_UINT,
2,
&r16_data,
[0x0001, 0x3C00, 0xBC00, 0xFFFF],
),
(
"R16_SINT",
DXGI_FORMAT_R16_SINT,
2,
&r16_data,
[0x0001, 0x3C00, 0xFFFF_BC00, 0xFFFF_FFFF],
),
(
"R32_UINT",
DXGI_FORMAT_R32_UINT,
4,
&r32_data,
r32_data,
),
];
for (backend, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else { continue };
let (root, pso) = host
.compute_pipeline(&shader)
.unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}"));
for &(label, format, elem_bytes, input, want) in &cases {
let views = [
View::Buffer {
data: input,
stride: super::host::Stride::Format(format, elem_bytes),
},
View::RawUav(4),
];
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
if u.root == RootType::Table && u.slot == 0 {
ud[u.index as usize] = 0;
}
}
let out = host
.dispatch(
@@ -2522,25 +2381,13 @@ fn a_format_load_read_as_halves_loads_the_integer() {
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[
View::Buffer {
data: &data,
stride: Stride::Format(DXGI_FORMAT_R16_UINT, 2),
},
View::RawUav(1),
],
views: &views,
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
assert_eq!(
out[0][0],
1.0f32.to_bits(),
"{label}, {name}: the half read as an integer's bits"
);
.unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}"));
assert_eq!(out[0], want, "{backend} {label}: buffer_load_format_x mismatch");
}
ran += 1;
}
assert!(ran > 0, "no SM 6.6 device available");
}
+108 -21
View File
@@ -138,6 +138,9 @@ pub struct RootIndexedView {
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Resources {
/// Scalar values saved to a constant VGPR lane and restored within one
/// block, even if that VGPR is also used in ordinary vector operations.
pub(crate) restored_lanes: std::collections::HashMap<Site, Moved>,
/// Every scalar memory access by address (`s_load_*`, `s_store_*`), and
/// every global memory access (`global_*`, the dynamic term per lane).
pub scalar: Vec<(Site, Address)>,
@@ -224,9 +227,12 @@ pub fn track(
let mut offset_at =
std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new();
for (b, block) in p.blocks.iter().enumerate() {
t.at.set(Some(b));
for (i, inst) in block.insts.iter().enumerate() {
let site = (b, i);
t.at.set(Some(site));
if let Some(value) = t.restored(inst, Some(b)) {
out.restored_lanes.insert(site, value);
}
let fail = |what| ShaderError::Unsupported {
offset: inst.machine.offset,
what,
@@ -234,7 +240,7 @@ pub fn track(
let mut first_lane = Vec::new();
let mut offset = Vec::new();
let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> {
let source = t.descriptor(inst, op, b).map_err(fail)?;
let source = t.descriptor(inst, op, site).map_err(fail)?;
// A descriptor the code keeps per lane ([`Tracer::lane_copies`])
// is the same in every lane: its loop is lowered as it stands
// and needs no proof.
@@ -411,8 +417,8 @@ struct Tracer<'a> {
meets: std::cell::RefCell<Meets>,
/// Reverse-postorder index per block.
rpo: Vec<usize>,
/// The block of the access being traced ([`Self::live`]).
at: std::cell::Cell<Option<usize>>,
/// The instruction site of the access being traced ([`Self::live`]).
at: std::cell::Cell<Option<Site>>,
}
/// What lanes are known to satisfy: each [`Bool`] where its flag is set,
@@ -514,7 +520,7 @@ impl<'a> Tracer<'a> {
}
for inst in &block.insts {
for (k, &(_, v)) in inst.writes.iter().enumerate() {
let new = match copy_source(inst, k).or_else(|| self.restored(inst)) {
let new = match copy_source(inst, k).or_else(|| self.restored(inst, None)) {
Some(Moved::Const(c)) => Some(Term::Const(c)),
Some(Moved::Value(s)) => o[s.0 as usize],
None => Some(Term::Value(v)),
@@ -1113,8 +1119,8 @@ impl<'a> Tracer<'a> {
self.address(lo, hi, extra)
}
/// The source of the descriptor operand `op` of `inst`, in block `at`.
fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result<Source, &'static str> {
/// The source of the descriptor operand `op` of `inst`, at `at`.
fn descriptor(&self, inst: &Inst, op: &Operand, at: Site) -> Result<Source, &'static str> {
let Operand::Scalar { code, dwords } = *op else {
return Err("a descriptor not in SGPRs");
};
@@ -1129,8 +1135,14 @@ impl<'a> Tracer<'a> {
{
words = raw.to_vec();
}
// Only the lanes that reach the access read the descriptor.
let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true)));
// Only the lanes that reach and run the access read the descriptor.
let mut known = Vec::new();
if let Some(l) = self.lanes {
known.push((l.reach[at.0], true));
if let Some(guard) = l.guards[at.0][at.1] {
known.push((guard, true));
}
}
self.classify(&words, &mut Vec::new(), &mut known)
}
@@ -1282,7 +1294,10 @@ impl<'a> Tracer<'a> {
let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else {
return t;
};
let mut known = vec![(lanes.reach[at], true)];
let mut known = vec![(lanes.reach[at.0], true)];
if let Some(guard) = lanes.guards[at.0][at.1] {
known.push((guard, true));
}
for _ in 0..MAX_JOINS {
let Term::Value(v) = t else { break };
let Some((block, i)) = self.phis[v.0 as usize] else {
@@ -2292,41 +2307,64 @@ impl<'a> Tracer<'a> {
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Moved {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Moved {
Const(u32),
Value(Value),
}
fn plain_lane(v: &crate::gfx10::Valu) -> bool {
v.abs == 0
&& v.neg == 0
&& v.opsel == 0
&& !v.clamp
&& v.omod == 0
&& v.sdwa.is_none()
&& v.dpp.is_none()
}
impl Tracer<'_> {
/// For `v_readlane_b32` of a constant lane: the SGPR spilled to that
/// lane, found by following the VGPR's `v_writelane_b32` writes.
fn restored(&self, inst: &Inst) -> Option<Moved> {
fn restored(&self, inst: &Inst, block: Option<usize>) -> Option<Moved> {
let Fields::Valu(v) = &inst.fields else {
return None;
};
if inst.name() != "v_readlane_b32" {
if inst.name() != "v_readlane_b32" || !plain_lane(v) {
return None;
}
let [Operand::Vector { reg, .. }, lane] = v.src[..] else {
return None;
};
self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new())
let lane = lane_of(lane)?;
if lane >= if self.p.wave64 { 64 } else { 32 } {
return None;
}
self.spilled(inst.read(Reg::V(reg))?, lane, block, &mut Vec::new())
.ok()
.flatten()
}
/// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in
/// `seen` (already being resolved), `Err` if not a spilled SGPR.
fn spilled(&self, v: Value, lane: u32, seen: &mut Vec<Value>) -> Result<Option<Moved>, ()> {
fn spilled(
&self,
v: Value,
lane: u32,
block: Option<usize>,
seen: &mut Vec<Value>,
) -> Result<Option<Moved>, ()> {
if let Some((b, i)) = self.phis[v.0 as usize] {
if block.is_some() {
return Err(());
}
if seen.contains(&v) {
return Ok(None);
}
seen.push(v);
let mut found = None;
for &a in &self.p.blocks[b].phis[i].args {
if let Some(m) = self.spilled(a, lane, seen)? {
if let Some(m) = self.spilled(a, lane, block, seen)? {
if found.is_some_and(|f| f != m) {
return Err(());
}
@@ -2335,18 +2373,26 @@ impl Tracer<'_> {
}
return Ok(found);
}
let inst = self.def(v).ok_or(())?;
let site = self.defs[v.0 as usize].ok_or(())?;
if block.is_some_and(|b| site.0 != b) {
return Err(());
}
let inst = self.inst(site);
let Fields::Valu(w) = &inst.fields else {
return Err(());
};
let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else {
return Err(());
};
if inst.name() != "v_writelane_b32" {
if inst.name() != "v_writelane_b32" || !plain_lane(w) {
return Err(());
}
if lane_of(*at).ok_or(())? != lane {
return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen);
let written = lane_of(*at).ok_or(())?;
if written >= if self.p.wave64 { 64 } else { 32 } {
return Err(());
}
if written != lane {
return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, block, seen);
}
match *value {
Operand::Scalar { code, .. } if code != NULL => {
@@ -4061,4 +4107,45 @@ pub(crate) mod tests {
assert_eq!(r.waterfall.compares.len(), 2);
assert_eq!(r.waterfall.reads.len(), 4);
}
#[test]
fn a_guarded_access_excludes_dead_lane_edges_at_a_join() {
// Lanes failing `v_cmp_gt_u32` clear EXEC and take `s_cbranch_execz`
// directly to the join block without initializing the immediate
// sampler `s[8:11]`. The join's `image_sample_lz` is guarded by EXEC,
// so only the arm where `s[8:11]` was built can execute it.
let code: Vec<u8> = [
0xBE84_0300u32, // s_mov_b32 s4, s0
0xBE85_0380, // s_mov_b32 s5, 0
0xF40C_0302,
0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0
0x7E04_0D00, // v_cvt_f32_u32 v2, v0
0x7E06_0302, // v_mov_b32 v3, v2
0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
0x877E_6A7E, // s_and_b32 exec_lo, exec_lo, vcc_lo
0xBF88_0004, // s_cbranch_execz -> join (skips 4 dwords)
0xBE88_0380, // s_mov_b32 s8, 0
0xBE89_0380, // s_mov_b32 s9, 0
0xBE8A_0380, // s_mov_b32 s10, 0
0xBE8B_0380, // s_mov_b32 s11, 0
0xF09C_0F08,
0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11]
S_ENDPGM,
]
.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
let p = crate::ir::build(&code, false, 256).unwrap();
let structured = lanes(&p).expect("structured form");
assert!(structured.guards[2][0].is_some(), "join access must carry an EXEC guard");
let r = track(&p, &[param(Table, 0, 1)], HwStage::Cs, Some(&structured)).unwrap();
assert!(
r.descriptors
.iter()
.any(|d| d.role == Role::Sampler && d.source == Source::Constant(vec![0; 4])),
"guarded join should resolve the immediate sampler from the live arm: {:?}",
r.descriptors
);
}
}