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:
fxcelessandClaude Fable 5.2 committed 2026-11-24 13:02:18 -05:00
1 parent 45c6e80601
commit 6fa814fba5
61 files changed
+32259 -1274

No files matched your search

+76
View File
@@ -1,3 +1,79 @@
# victory-gta6
A work-in-progress fork of [VIctory](https://github.com/Marvisak/VIctory), the
compatibility layer that runs the Xbox Series build of Grand Theft Auto VI
natively on Windows from files the user supplies. This fork follows upstream
`main` and adds fixes aimed at one goal: getting the game's world to render
correctly and playably on one particular PC.
**This repository contains no game files, code or assets.** You need your own
copy of the game. It is not affiliated with or endorsed by Rockstar Games or
Take-Two Interactive.
## Credits
- **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its
contributors is the base of everything here: the loader, the runtime
services, the Direct3D 12 back end and the shader recompiler. Licensed
GPL-3.0-or-later; so is this fork. Upstream's history is kept intact below
the single commit that carries this fork's changes.
- **[XCL](https://github.com/ivall/xcl)** by ivall and its contributors
(GPL-2.0-only) was used as a reference for how the same title behaves under
another layer. Fixes inspired by it were written anew in VIctory's code.
- This fork's changes were developed with [Claude Code](https://claude.com/claude-code).
## Status of this fork (2026-11-25)
**Not playable yet: about 3 frames per second, and shadowed areas are black.**
Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB,
32 GB RAM. The Series X profile is used throughout.
| Stage | State in this fork |
|-------|--------------------|
| Boot, menus, start screen | works, 30 fps (as upstream) |
| Opening cutscene | plays from start to finish, in order, lit: title cards, credits cards, night and dusk shots |
| Saves | the game autosaves a checkpoint and loads it again |
| First gameplay scene (the prologue) | renders: characters, textures, sky, sunlit exterior; HUD, pause menu and pad input work |
| Light in shadow | missing: the game's ray-traced bounce light and ray-traced lamp and sun shadows do not run yet, so anything the sun does not hit directly is black |
| Frame rate in the world | 2-3.5 fps (270-450 ms per frame), from 3-6 seconds per frame at the start |
| Stability | no driver hang or device loss in normal runs |
### What this fork changed (summary)
Rendering:
- Meshlet culling read its scene buffers as the wrong kind of view, so the world drew almost nothing; fixed.
- Per-draw descriptor tables could run out, after which draws used slots never made for them and the card hung; fixed.
- Light packed by the game's compute shaders was read back through empty copies (sky, probes, fog); fixed for every mip level and layer.
- The fog reconstruction, shadow-mask, hair, blend-shape skinning, fire and several material programs did not translate; fixed.
- Gathers at a named mip level (with and without an offset) read level 0; fixed.
- Implicit-level samples outside pixel shaders produced invalid DXIL in 730 compute programs; fixed.
- Rectangle lists, depth and stencil twins for depth textures written by compute, texture read-backs.
- Ray tracing, in progress and off by default: the game's own structure-builder programs translate, title memory can be read by raw address from shaders, and the hardware ray/box and ray/triangle test is emulated in DXIL (checked against a reference on the GPU).
Speed and memory:
- Waits for memory values, write-watch queries and page queries no longer walk page tables per call.
- Large title buffers get a copy in card memory, with shader writes found by hashing on the card.
- Submissions can be sent ahead of the wait for the card (`VICTORY_LATE_WAIT`), with a relay thread that lands results as the card finishes (`VICTORY_RELAY`, new and untested in the game).
- The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory.
- An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed.
Most of the newer speed changes sit behind environment switches that are off
by default (`VICTORY_LATE_WAIT`, `VICTORY_RELAY`, `VICTORY_WIDE_BACK`,
`VICTORY_CARD_BUFFERS_MIN_MB`, `VICTORY_INPLACE`, `VICTORY_BVH_BUILDER`, ...).
Each is described in a comment where it is read.
### Known problems
- Everything in shadow is black (see above).
- The interior of the first gameplay room is sometimes not drawn after the cutscene hands over to gameplay.
- Around 24 GB of memory is in use during play.
- Many changes here are specific to this title and this GPU, and some are marked `shortcut:` in the code where they approximate what the console does.
Everything below this line is upstream VIctory's own README, unchanged; its
status section describes upstream, not this fork.
---
# VIctory
Runs Grand Theft Auto VI (Xbox Series X|S) natively on Windows, from files
+11 -1
View File
@@ -152,7 +152,17 @@ fn main() -> Result<()> {
pipelines,
list,
jobs,
} => translate::run(paths, validate, pipelines, list, jobs),
} => {
// `VICTORY_VIEW_LIMIT=<null slot>`: translate as on a host whose view heap is capped
if let Some(n) = std::env::var("VICTORY_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) {
victory_shader::emit::set_view_heap_limit(n);
}
// `VICTORY_HOST_WAVE=32`: translate as for a GPU whose waves are at most 32 lanes
if let Some(n) = std::env::var("VICTORY_HOST_WAVE").ok().and_then(|v| v.parse().ok()) {
victory_shader::emit::set_host_max_wave(n);
}
translate::run(paths, validate, pipelines, list, jobs)
}
Command::Run {
exe,
unimplemented,
+6
View File
@@ -30,6 +30,12 @@ pub fn run(
let images = cfg.cache_subdir("images")?;
victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
let image = victory_loader::load(&prepared, &images)?;
// The program is mapped from the copy `load` wrote: the file's bytes
// and their patched copy are not read again, and were held for the
// whole run (two blocks of 114.7 MB each for Grand Theft Auto VI, in
// physical memory: run 65's memory map).
drop(prepared);
drop(original);
victory_hle::runtime::set_main_image(image.base());
victory_hle::runtime::set_image_path(image.base(), exe);
println!(
+52 -3
View File
@@ -312,6 +312,10 @@ fn translate(
let Some(bytes) = source.bytes() else {
return t.fail("corrupt record".into(), example);
};
// The hash a run's log names the shader by (`hash=` in "first bind",
// "shader does not translate", "host pipeline refused").
let hash = blake3::hash(&bytes).to_hex()[..16].to_owned();
let example = || format!("{}{} #{hash}", path.display(), source.label());
t.containers += 1;
let Ok(container) = Container::parse(&bytes) else {
return t.fail("no DXIL part (SM5 or older)".into(), example);
@@ -319,17 +323,61 @@ fn translate(
let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else {
return t.fail("no DXIL part (SM5 or older)".into(), example);
};
if !lock(seen).insert(blake3::hash(dxil)) {
// `~`: the hash of the code alone; containers that differ only around
// it are translated once, the others listed as duplicates of it.
let code = blake3::hash(dxil);
let code8 = code.to_hex()[..8].to_owned();
let example = || format!("{} ~{code8}", example());
// `VICTORY_DUMP_MATCH=<dir>;<text>|<text>...`: the containers whose
// line holds one of the texts (a name, `#hash`), as the title has them.
if let Ok(spec) = std::env::var("VICTORY_DUMP_MATCH")
&& let Some((dir, texts)) = spec.split_once(';')
{
let line = example();
if texts.split('|').any(|text| !text.is_empty() && line.contains(text)) {
let name: String = source
.label()
.chars()
.skip_while(|c| *c != ' ')
.filter(|c| c.is_ascii_alphanumeric() || *c == '_')
.take(70)
.collect();
let _ = std::fs::create_dir_all(dir);
let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]);
}
}
if !lock(seen).insert(code) {
t.duplicates += 1;
if t.list {
t.lines.push(format!("{} duplicate", example()));
}
return;
}
let programs = match native_programs(dxil) {
Ok(p) => p,
Err(e) => return t.fail(e.to_string(), example),
};
// `VICTORY_FAIL_DUMP=<dir>`: the first 3 containers of each failure reason, as the title
// has them (`.cdxil`), to work on a translator gap offline
let dump = std::env::var_os("VICTORY_FAIL_DUMP");
let before: Option<BTreeMap<String, usize>> = dump.as_ref().map(|_| t.failed.iter().map(|(k, v)| (k.clone(), v.0)).collect());
translate_programs(&container, programs, &example, t, checks);
if let (Some(dir), Some(before)) = (dump, before) {
for (reason, (n, _)) in &t.failed {
let was = before.get(reason).copied().unwrap_or(0);
if *n > was && was < 3 {
let stem: String = reason.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).take(60).collect();
let _ = std::fs::create_dir_all(&dir);
let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{stem}_{was}.cdxil")), &bytes[..]);
}
}
}
}
fn translate_programs(container: &Container, programs: Vec<NativeProgram>, example: &dyn Fn() -> String, t: &mut Tally, checks: &mut Checks) {
for p in programs {
t.programs += 1;
match ir::build(&p.patched_code(), p.wave64, p.vgprs) {
match victory_shader::spill::build(&p) {
Ok(program) => {
t.translated += 1;
t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::<usize>();
@@ -390,7 +438,7 @@ fn translate(
if let (Some(r), Some(i), Some(s)) = (res, raised, structured) {
let label = || format!("{} {:?}", example(), p.stage);
*counter(t, p.stage, 0) += 1;
match emit::emit(&container, &p, &program, &s, &i, &r) {
match emit::emit(container, &p, &program, &s, &i, &r) {
Ok(shader) => {
*counter(t, p.stage, 1) += 1;
check(shader, t, checks, label);
@@ -525,6 +573,7 @@ fn tally_io(r: &io::Io, t: &mut Tally) {
match i {
io::Interp::Interpolated { .. } => t.interpolated += 1,
io::Interp::Vertex { .. } => t.vertex_values += 1,
io::Interp::Weighted { .. } => t.interpolated += 1,
}
}
for e in &r.exports {
+18 -3
View File
@@ -129,8 +129,8 @@ impl Tables {
/// alpha 64 B and colour 256 B, BC4 64 B, BC5 64 B), 512 u16 BC7 control
/// words, then 255 dictionary entries per format in format order: BC1
/// 6 + 16 B, BC3 8 + 32 B, BC4 2 + 16 B, BC5 4 + 32 B, BC6H (u8 mode,
/// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 32 i16).
/// Little-endian, no padding. Every model must tile 65536.
/// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 2 B,
/// 16 + 15 i16). Little-endian, no padding. Every model must tile 65536.
pub fn parse(bytes: &[u8]) -> Result<Tables, Error> {
if bytes.len() != TABLES_SIZE {
return Err(Error("table file has the wrong size"));
@@ -222,7 +222,10 @@ impl Tables {
bits: [r.u8(), r.u8()],
..Default::default()
};
for v in ix.ix.as_flattened_mut() {
// Unused: the widths again in all entries but the first.
r.u16();
// Only 15 slots for set 1, which no entry uses (0 bits).
for v in &mut ix.ix.as_flattened_mut()[..31] {
*v = r.u16() as i16;
}
(ep, ix)
@@ -1590,4 +1593,16 @@ mod tests {
}
assert!(n > 0);
}
/// A dictionary entry stands in for a block the decoder made: a set with
/// 0 index bits holds no indices, and pixel 0 is the anchor (top bit clear).
#[test]
fn bc7_dictionary_indices_line_up() {
let t = Tables::builtin().unwrap();
for (k, (_, ix)) in t.bc7.iter().enumerate() {
let anchor = 0..1 << (ix.bits[0] - 1);
let ok = (ix.bits[1] != 0 || ix.ix[1] == [0; 16]) && anchor.contains(&ix.ix[0][0]);
assert!(ok, "entry {k}: {:?}", ix.ix);
}
}
}
+26 -2
View File
@@ -671,6 +671,13 @@ impl Layout {
}
runs.push((first_tiled, first_linear, bytes - first_linear));
}
// A mip can end partway through the last run. Check the other runs
// once so each row can copy them with a compile-time length.
let (body, last) = runs.split_at(runs.len().saturating_sub(1));
let run_len = body
.first()
.map(|run| run.2)
.filter(|&len| body.iter().all(|run| run.2 == len));
for z in 0..depth {
let (s, inner) = self.split(first + z);
let base = u64::from(s) * self.slice_size + m.offset;
@@ -681,9 +688,13 @@ impl Layout {
copy(tiled_row as usize, linear_row, bytes);
} else {
let tiled_row = (base + self.row(m, y, inner)) as usize;
for &(tiled, linear, len) in &runs {
copy(tiled_row + tiled, linear_row + linear, len);
match run_len {
Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy),
Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy),
Some(32) => copy_runs::<32>(body, tiled_row, linear_row, &mut copy),
_ => copy_runs::<0>(body, tiled_row, linear_row, &mut copy),
}
copy_runs::<0>(last, tiled_row, linear_row, &mut copy);
}
}
}
@@ -691,6 +702,19 @@ impl Layout {
}
}
/// Copy micro-tile runs inline at a known width, or use each run's length for N = 0.
fn copy_runs<const N: usize>(
runs: &[(usize, usize, usize)],
tiled_row: usize,
linear_row: usize,
copy: &mut impl FnMut(usize, usize, usize),
) {
for &(tiled, linear, len) in runs {
let len = if N == 0 { len } else { N };
copy(tiled_row + tiled, linear_row + linear, len);
}
}
/// What a DXGI format stores per element: bytes, texels per element side
/// (4 for block compression), and whether its stencil is a second plane
/// (the GPU keeps depth and stencil apart).
+193 -7
View File
@@ -20,18 +20,139 @@ pub(crate) fn folder() -> Option<&'static PathBuf> {
/// too, and their draws traced at debug level.
pub(crate) fn listed(n: u64) -> bool {
static LIST: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new();
LIST.get_or_init(|| {
let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default();
let named = LIST
.get_or_init(|| {
let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default();
list.split(',')
.filter_map(|f| f.trim().parse().ok())
.collect()
})
.contains(&n);
// `VICTORY_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first
// one that ran 500 draws or more (a title's first 3D frames: their
// numbers depend on how long the menus were shown), and the 30th and
// the 80th (Grand Theft Auto VI opens with a cutscene made in the
// engine: later shots of it, in case the first is dark by design).
//
// `VICTORY_CAPTURE_WORLD_ALSO` (comma-separated): more frames counted
// from that first one (Grand Theft Auto VI's blue patches show from
// about the 118th frame on, when the window's model has arrived and
// the reflections hold values: none of the four above has them).
static ALSO: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new();
let also = ALSO.get_or_init(|| {
let list = std::env::var("VICTORY_CAPTURE_WORLD_ALSO").unwrap_or_default();
list.split(',')
.filter_map(|f| f.trim().parse().ok())
.collect()
})
.contains(&n)
});
let first = WORLD.load(std::sync::atomic::Ordering::Relaxed);
let after = n.wrapping_sub(first);
named || first != u64::MAX && ([2, 6, 30, 80].contains(&after) || also.contains(&after))
}
/// With a capture folder, for the frames [`listed`]: `what` is added to
/// the frame's `frame-<n>-ops.txt`, one line per draw, dispatch, copy or
/// drop in the order recorded (the title records on several threads, so
/// lines of different lists interleave; each names its list). The file
/// says which pass writes which target, to find the pass whose output
/// stays empty.
#[cfg(feature = "diagnostics")]
pub(crate) fn op(list: usize, what: impl FnOnce() -> String) {
use std::io::Write;
let frame = crate::queue::presented() + 1;
if !listed(frame) {
// Before the world: the last lines are kept, and written out when
// it starts (`before-world-ops.txt`): what the title drew just
// before (Grand Theft Auto VI shows a title card there, whose text
// did not show).
if world_on() && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX {
// At most 300 lines of a frame: the world's first frame alone
// (thousands of operations, recorded before it is known to be
// the world's) pushed everything before it out.
static IN_FRAME: std::sync::Mutex<(u64, u32)> = std::sync::Mutex::new((0, 0));
{
let mut in_frame = IN_FRAME.lock().unwrap_or_else(|e| e.into_inner());
if in_frame.0 != frame {
*in_frame = (frame, 0);
}
in_frame.1 += 1;
if in_frame.1 > 300 {
return;
}
}
let what = what();
let mut ring = RING.lock().unwrap_or_else(|e| e.into_inner());
if ring.len() >= RING_LINES {
ring.pop_front();
}
ring.push_back(format!("frame {frame} list {list:#x} {what}"));
}
return;
}
let Some(folder) = folder() else {
return;
};
static FILE: std::sync::Mutex<Option<(u64, u64, std::fs::File)>> = std::sync::Mutex::new(None);
let what = what();
let mut file = FILE.lock().unwrap_or_else(|e| e.into_inner());
if file.as_ref().is_none_or(|f| f.0 != frame) {
let Ok(made) = std::fs::File::create(folder.join(format!("frame-{frame}-ops.txt"))) else {
return;
};
*file = Some((frame, 0, made));
}
if let Some((_, n, f)) = file.as_mut() {
*n += 1;
let _ = writeln!(f, "{n} list {list:#x} {what}");
}
}
/// The last lines of [`op`] before the world.
#[cfg(feature = "diagnostics")]
static RING: std::sync::Mutex<std::collections::VecDeque<String>> =
std::sync::Mutex::new(std::collections::VecDeque::new());
#[cfg(feature = "diagnostics")]
const RING_LINES: usize = 6000;
/// Whether `VICTORY_CAPTURE_WORLD` is set.
fn world_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_CAPTURE_WORLD").is_some())
}
/// The first frame that ran 500 draws or more (`VICTORY_CAPTURE_WORLD`).
static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
/// At the present of `frame`: the draws run on the host so far.
pub(crate) fn frame_drew(frame: u64, drawn: u64) {
use std::sync::atomic::Ordering::Relaxed;
static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let before = LAST.swap(drawn, Relaxed);
if world_on()
&& drawn.saturating_sub(before) >= 500
&& WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed).is_ok()
{
tracing::info!(frame, "the first frame of 500 draws or more: frames {} and {} are captured", frame + 2, frame + 6);
#[cfg(feature = "diagnostics")]
if let Some(folder) = folder() {
let lines: Vec<String> = std::mem::take(&mut *RING.lock().unwrap_or_else(|e| e.into_inner())).into();
let _ = std::fs::write(folder.join("before-world-ops.txt"), lines.join("
"));
}
}
}
/// Whether frame `n` is saved.
pub(crate) fn wanted(n: u64) -> bool {
folder().is_some() && (n.is_power_of_two() || listed(n))
// Before the world, with `VICTORY_CAPTURE_WORLD`: every 16th frame too
// (small pictures of menus, loading screens and title cards).
let before_world = world_on() && n % 16 == 0 && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX;
// In the world: every 8th frame's picture, a timeline of the opening
// cutscene (its shots do not fall on the same frame numbers from run to
// run, so single frames cannot be compared between runs).
let first = WORLD.load(std::sync::atomic::Ordering::Relaxed);
let in_world = world_on() && first != u64::MAX && n > first && (n - first) % 8 == 0;
folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world)
}
/// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`.
@@ -281,6 +402,26 @@ fn dump_one(
}
let pitch = f.RowPitch as usize;
let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * f.Height as usize);
// A 24-bit depth plane comes back as 32-bit words: which depth values
// (low 24 bits) and which top bytes it holds, the most common first.
if matches!(d.Format.0, 44..=47) {
let mut depths = std::collections::HashMap::<u32, u32>::new();
let mut tops = std::collections::HashMap::<u32, u32>::new();
for y in 0..f.Height as usize {
for x in 0..f.Width as usize {
let at = y * pitch + x * 4;
let w = u32::from_le_bytes(rows[at..at + 4].try_into().unwrap_or([0; 4]));
*depths.entry(w & 0xff_ffff).or_default() += 1;
*tops.entry(w >> 24).or_default() += 1;
}
}
let most = |m: std::collections::HashMap<u32, u32>| {
let mut v: Vec<(u32, u32)> = m.into_iter().collect();
v.sort_by_key(|e| std::cmp::Reverse(e.1));
(v.len(), v.into_iter().take(12).collect::<Vec<_>>())
};
tracing::info!(?resource, depths = ?most(depths), top_bytes = ?most(tops), "24-bit depth plane values (value, texels)");
}
if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) {
let name = format!(
"frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}",
@@ -384,9 +525,54 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
(0.0, finite.fold(0.0f32, f32::max))
};
let range = (high - low).max(1e-20);
tracing::info!(format, low, high, "target values");
// How much of the target holds anything: a lit scene and one bright
// lamp on black have the same highest value.
let above = values.iter().filter(|v| v.iter().any(|c| c.is_finite() && *c > low)).count();
let nonzero_percent = above as f32 * 100.0 / values.len().max(1) as f32;
tracing::info!(format, low, high, nonzero_percent, "target values");
// Small float colour targets (the 1x1 luminance and exposure targets):
// every texel's four channels as numbers. The picture has no alpha and
// eight bits a channel.
if matches!(format, 1..=2 | 9..=10) && w * h <= 16 {
for y in 0..h {
for x in 0..w {
let b = px(x, y, n);
let texel: [f32; 4] = if n == 16 {
[0, 1, 2, 3].map(|i| f32::from_bits(u32_at(b, i)))
} else {
[0, 1, 2, 3].map(|i| half(u16_at(b, i)))
};
tracing::info!(format, x, y, ?texel, "target texel");
}
}
}
// R32_UINT targets hold packed light (the title reads them back as
// R9G9B9E5): as floats their low, high and share above the lowest say
// nothing. How many texels hold any bit, and the highest channel value
// of the packed reading.
if format == 42 {
let (mut set, mut packed_high) = (0usize, 0f32);
for y in 0..h {
for x in 0..w {
let v = u32_at(px(x, y, 4), 0);
set += usize::from(v != 0);
let scale = 2f32.powi((v >> 27) as i32 - 24);
for k in 0..3 {
packed_high = packed_high.max((v >> (9 * k) & 0x1ff) as f32 * scale);
}
}
}
let nonzero_bits_percent = set as f32 * 100.0 / (w * h).max(1) as f32;
tracing::info!(format, nonzero_bits_percent, packed_high, "target values as packed light");
}
// Float colours (scene light) go through a cube root: scaled linearly,
// a night scene under one lamp of 50 units came out all black.
let curved = matches!(format, 1..=2 | 9..=10 | 26);
for v in values {
let c = v.map(|c| (((c - low) / range).clamp(0.0, 1.0) * 255.0) as u8);
let c = v.map(|c| {
let t = ((c - low) / range).clamp(0.0, 1.0);
((if curved { t.cbrt() } else { t }) * 255.0) as u8
});
out.extend([c[0], c[1], c[2], 255]);
}
Some(out)
File diff suppressed because it is too large. Load diff
+433 -36
View File
@@ -99,6 +99,13 @@ impl Heap {
.as_ref()
}
/// The handle of descriptor `index` of this heap.
#[cfg(windows)]
pub(crate) fn handle(&self, index: u32) -> Option<u64> {
let step = u64::from(increment(self.desc.kind)?);
(index < self.desc.count).then(|| self.start + u64::from(index) * step)
}
/// The descriptor index of `handle` in this heap, if it lies in it.
pub(crate) fn index(&self, handle: u64) -> Option<u32> {
let step = u64::from(increment(self.desc.kind)?);
@@ -231,7 +238,8 @@ impl RtvRecord {
0,
]
};
words[0] = crate::resource::pc_format(words[0]);
// A target or depth view: of a target, in its stand-in format.
words[0] = crate::resource::target_format(crate::resource::pc_format(words[0]));
// SAFETY: both host view descriptions are 24 bytes in this layout.
Some(unsafe { (&raw const words).cast::<T>().read_unaligned() })
}
@@ -318,9 +326,21 @@ impl View {
/// generation, so descriptors (and host slots made from them) naming the
/// old one go stale instead of naming whatever is made at the same address
/// next.
/// shortcut: views without a resource object (constant buffers, memory
/// views, samplers) are kept for the run; they are bounded by the title's
/// memory and sampler states.
///
/// Views without a resource object have nothing that releases them, and a
/// title copies descriptors as bytes, so nothing says when the last
/// descriptor naming an entry is gone: such entries were kept for the run.
/// Grand Theft Auto VI writes some 14,000 constant buffer views a frame,
/// each at the address its constants have that frame: 2,450,139 entries
/// after four minutes of play, 1,047 MB with the index, and 11,000 more
/// every second (run 65). So the two kinds that carry an address are not
/// entries any more: their records name them whole ([`constant_words`],
/// [`placed_words`]), and the table holds only what is bounded: views of
/// resource objects (freed with the resource), samplers (as many as there
/// are sampler states), and the shapes of placed views (their descriptions
/// without the address: as many as the title has kinds of textures and
/// buffers, however often it moves them).
/// `VICTORY_VIEW_INLINE=0`: every view is an entry, as before.
struct Views {
/// Each entry's view and generation.
list: Vec<(View, u32)>,
@@ -328,6 +348,9 @@ struct Views {
/// Entries naming each resource.
by_resource: std::collections::BTreeMap<usize, Vec<u32>>,
free: Vec<u32>,
/// The shapes of views of placed memory, and where each is.
shapes: Vec<Shape>,
shape_index: std::collections::BTreeMap<Shape, u32>,
}
static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views {
@@ -335,9 +358,220 @@ static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views {
index: std::collections::BTreeMap::new(),
by_resource: std::collections::BTreeMap::new(),
free: Vec::new(),
shapes: Vec::new(),
shape_index: std::collections::BTreeMap::new(),
});
const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE");
/// A record is the tag and two words, `i` and `generation` (the host keeps
/// them as one 64-bit key per slot). The top two bits of `generation` say
/// what the other 62 bits are: 0, entry `i` of the table at that
/// generation; [`CONSTANT`], a constant buffer view, whole; [`PLACED`], a
/// view of placed memory: its address and the number of its shape.
const KIND_SHIFT: u32 = 30;
/// Table generations stay below the kind bits (and above 0).
const GENERATIONS: u32 = (1 << KIND_SHIFT) - 1;
const CONSTANT: u32 = 1;
const PLACED: u32 = 2;
/// Bits of a constant buffer view's address in its record: any address a
/// program can have. The 15 bits above them are its size.
const CONSTANT_ADDRESS_BITS: u32 = 47;
/// Bits of a placed view's address in its record: placed memory is title
/// memory, which lies below 1 TiB. The 22 bits above them number its shape.
const PLACED_ADDRESS_BITS: u32 = 40;
const SHAPES: usize = 1 << (62 - PLACED_ADDRESS_BITS);
/// A view of placed memory without its address: whether it is unordered
/// access, the resource description, and the view's words but the two that
/// hold the address (10 and 11).
type Shape = (bool, [u32; 14], [u32; 14]);
/// Whether constant buffer views and views of placed memory are named whole
/// in their records ([`Views`]). On by default; `VICTORY_VIEW_INLINE=0`
/// makes every view a table entry, as before.
fn inline() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_INLINE").is_none_or(|v| v != "0"))
}
/// Views named whole in their records since the start: constant buffer
/// views, views of placed memory (for the memory line).
static NAMED_WHOLE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
/// The two record words of the 62 bits `payload` of kind `kind`.
fn kind_words(kind: u32, payload: u64) -> [u32; 2] {
[payload as u32, kind << KIND_SHIFT | (payload >> 32) as u32]
}
/// The 62 bits two record words carry beside their kind.
fn payload(i: u32, generation: u32) -> u64 {
u64::from(generation & GENERATIONS) << 32 | u64::from(i)
}
/// The record words that name the constant buffer view of `size` bytes at
/// `address` whole; `None` if they cannot: an address past 47 bits, or a
/// size of 16 KiB or more that is no multiple of 256 or reaches 4 MiB (the
/// size has 15 bits: bytes below 16 KiB, else units of 256 bytes). Such a
/// view is a table entry.
fn constant_words(address: u64, size: u32) -> Option<[u32; 2]> {
if address >> CONSTANT_ADDRESS_BITS != 0 {
return None;
}
let code = if size < 1 << 14 {
u64::from(size)
} else if size.is_multiple_of(256) && size >> 8 < 1 << 14 {
1 << 14 | u64::from(size >> 8)
} else {
return None;
};
Some(kind_words(CONSTANT, code << CONSTANT_ADDRESS_BITS | address))
}
/// The constant buffer view [`constant_words`] named.
fn constant_of(i: u32, generation: u32) -> View {
let payload = payload(i, generation);
let code = (payload >> CONSTANT_ADDRESS_BITS) as u32;
let size = if code >> 14 == 0 { code } else { (code & 0x3fff) << 8 };
View::Constant(payload & ((1 << CONSTANT_ADDRESS_BITS) - 1), size)
}
/// A placed view's shape and its address.
fn shape_of(unordered: bool, resource: &[u32; 14], desc: &[u32; 16]) -> (Shape, u64) {
let mut rest = [0u32; 14];
rest[..10].copy_from_slice(&desc[..10]);
rest[10..].copy_from_slice(&desc[12..]);
(
(unordered, *resource, rest),
u64::from(desc[10]) | u64::from(desc[11]) << 32,
)
}
/// The record words that name the view of placed memory at `address` with
/// shape number `shape`.
fn placed_words(shape: u32, address: u64) -> [u32; 2] {
kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address)
}
impl Views {
/// The number of `shape`, a new one if it is not there yet; `None` when
/// the shapes are full (the view is then a table entry).
fn shape(&mut self, shape: Shape) -> Option<u32> {
if let Some(&at) = self.shape_index.get(&shape) {
return Some(at);
}
if self.shapes.len() >= SHAPES {
return None;
}
let at = self.shapes.len() as u32;
self.shapes.push(shape);
self.shape_index.insert(shape, at);
Some(at)
}
/// The view of placed memory [`placed_words`] named.
fn placed_of(&self, i: u32, generation: u32) -> Option<View> {
let payload = payload(i, generation);
let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1);
let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?;
let mut desc = [0u32; 16];
desc[..10].copy_from_slice(&rest[..10]);
(desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
desc[12..].copy_from_slice(&rest[10..]);
Some(View::Placed(unordered, resource, desc))
}
/// The record words of `view` as a table entry: its entry (a new or a
/// freed one if the view is not there yet) and that entry's generation.
fn entry(&mut self, view: View) -> [u32; 2] {
let i = match self.index.get(&view) {
Some(&i) => i,
None => {
let i = match self.free.pop() {
Some(i) => {
self.list[i as usize].0 = view.clone();
i
}
None => {
self.list.push((view.clone(), 1));
self.list.len() as u32 - 1
}
};
for r in view.resources().into_iter().filter(|&r| r != 0) {
self.by_resource.entry(r).or_default().push(i);
}
self.index.insert(view, i);
i
}
};
[i, self.list[i as usize].1]
}
}
/// The two words that name `view` in a record: the view itself where its
/// kind allows ([`Views`]), else its table entry.
fn words_for(view: View) -> [u32; 2] {
use std::sync::atomic::Ordering::Relaxed;
if inline() {
match &view {
View::Constant(address, size) => {
if let Some(words) = constant_words(*address, *size) {
NAMED_WHOLE[0].fetch_add(1, Relaxed);
return words;
}
}
View::Placed(unordered, resource, desc) => {
let (shape, address) = shape_of(*unordered, resource, desc);
if address >> PLACED_ADDRESS_BITS == 0 {
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
if let Some(shape) = views.shape(shape) {
NAMED_WHOLE[1].fetch_add(1, Relaxed);
return placed_words(shape, address);
}
}
}
_ => {}
}
}
VIEWS.lock().unwrap_or_else(|e| e.into_inner()).entry(view)
}
/// For the memory line: the distinct views kept ([`Views`]), those of them
/// free for reuse, and the bytes the table and its index hold for them (an
/// estimate: an entry of the table, and one of the index with its share of
/// a tree node; the shapes likewise); then the entries that are constant
/// buffer views and views of placed memory (those that did not fit a
/// record, or all of them with `VICTORY_VIEW_INLINE=0`), the shapes of
/// placed views kept, and the views named whole in their records since the
/// start: constant buffer views, views of placed memory.
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn views_kept() -> [u64; 8] {
use std::sync::atomic::Ordering::Relaxed;
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let each = size_of::<(View, u32)>() as u64;
let shape = size_of::<Shape>() as u64;
let (mut constants, mut placed) = (0, 0);
for (view, _) in &views.list {
match view {
View::Constant(..) => constants += 1,
View::Placed(..) => placed += 1,
_ => {}
}
}
[
views.list.len() as u64,
views.free.len() as u64,
views.list.capacity() as u64 * each
+ views.index.len() as u64 * each * 3 / 2
+ views.shapes.capacity() as u64 * shape
+ views.shape_index.len() as u64 * shape * 3 / 2,
constants,
placed,
views.shapes.len() as u64,
NAMED_WHOLE[0].load(Relaxed),
NAMED_WHOLE[1].load(Relaxed),
]
}
impl View {
/// The resource objects the view names.
fn resources(&self) -> [usize; 2] {
@@ -347,43 +581,122 @@ impl View {
_ => [0, 0],
}
}
/// The texture object the view is of, if that texture has no host copy
/// yet (`crate::resource::host_waits`): a slot written with such a
/// view is left null until the texture is first used.
#[cfg(windows)]
fn waiting_texture(&self) -> Option<usize> {
match *self {
View::Shader(r, _) | View::Unordered(r, _, _)
if crate::resource::host_waits(r as This) =>
{
Some(r)
}
_ => None,
}
}
}
/// Title slots (their handles) written with a view of a texture object
/// that had no host copy then, by texture. A title texture gets its host
/// copy on first use (`resource.rs` `Hosted`), and Grand Theft Auto VI
/// writes each texture's views into its view heap when it creates the
/// texture: making those host slots would make every host copy at once.
/// They are made when the texture is: translated shaders index the heap
/// directly, so a slot is not always made again by the draw that reads it.
#[cfg(windows)]
static WAITING: std::sync::Mutex<std::collections::BTreeMap<usize, Vec<u64>>> =
std::sync::Mutex::new(std::collections::BTreeMap::new());
/// Textures given their host copy since [`make_waiting`] last ran.
#[cfg(windows)]
static MADE_LATE: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
/// Title texture `resource` was given its host copy (called under that
/// texture's own lock: nothing else is locked here).
#[cfg(windows)]
pub(crate) fn texture_made(resource: usize) {
MADE_LATE
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(resource);
}
/// The slot at `handle` was written with a view of texture `resource`,
/// which has no host copy: it waits for one.
#[cfg(windows)]
fn wait_for(resource: usize, handle: u64) {
/// A texture with more slots waiting than this is in use for all we
/// know (its views are being copied about): its host copy is made.
const MOST: usize = 64;
let many = {
let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner());
let slots = waiting.entry(resource).or_default();
if !slots.contains(&handle) {
slots.push(handle);
}
slots.len() > MOST
};
if many {
// Makes it, and notes it made.
let _ = crate::resource::host_copy(resource as This);
} else if !crate::resource::host_waits(resource as This) {
// Made by another thread since the slot was looked at: that making
// may have been taken by `make_waiting` before this slot was noted.
texture_made(resource);
}
}
/// Makes the host slots that waited for a texture's host copy, for the
/// textures made since the last call. Called before a submission runs, by
/// the thread that submits: a slot is read when a list runs.
#[cfg(windows)]
pub(crate) fn make_waiting() {
let made = std::mem::take(&mut *MADE_LATE.lock().unwrap_or_else(|e| e.into_inner()));
for resource in made {
let handles = WAITING
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&resource);
for handle in handles.into_iter().flatten() {
// Only if the slot still holds a view of that texture: the
// title may have written it since (and a view of another
// texture without a host copy must go on waiting).
// (Looked up first: the handle is read only while its heap is
// there.)
let Some((heap, index)) = shader_slot(handle) else {
continue;
};
let same = match view(handle) {
Some(View::Shader(r, _) | View::Unordered(r, _, _)) => r == resource,
_ => false,
};
if same && let Some(Some(host)) = heap.host.get() {
host.mirror(index, handle, true);
}
}
}
}
fn record(handle: u64, view: View) {
if handle == 0 {
return;
}
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let i = match views.index.get(&view) {
Some(&i) => i,
None => {
let i = match views.free.pop() {
Some(i) => {
views.list[i as usize].0 = view.clone();
i
}
None => {
views.list.push((view.clone(), 1));
views.list.len() as u32 - 1
}
};
for r in view.resources().into_iter().filter(|&r| r != 0) {
views.by_resource.entry(r).or_default().push(i);
}
views.index.insert(view, i);
i
}
};
let generation = views.list[i as usize].1;
let [i, generation] = words_for(view);
// SAFETY: the handle is a descriptor slot, at least 16 bytes.
unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) };
drop(views);
#[cfg(windows)]
mirror(handle);
}
/// The title released `resource`: the views naming it go stale.
pub(crate) fn forget(resource: usize) {
#[cfg(windows)]
WAITING
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&resource);
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let Some(entries) = views.by_resource.remove(&resource) else {
return;
@@ -396,19 +709,27 @@ pub(crate) fn forget(resource: usize) {
continue;
}
views.index.remove(&view);
views.list[i as usize].1 = generation.wrapping_add(1).max(1);
// (Below the bits that say a record is no table entry.)
views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1);
// The view's other resource (a counter) keeps a stale entry, which
// `forget` of that resource skips.
views.free.push(i);
}
}
/// The view of entry `i` if `generation` is still its own.
#[cfg(windows)]
/// The view the record words `i` and `generation` name: the one they hold
/// whole, or the view of entry `i` if `generation` is still its own.
fn view_at(i: u32, generation: u32) -> Option<View> {
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let (view, current) = views.list.get(i as usize)?;
(*current == generation).then(|| view.clone())
match generation >> KIND_SHIFT {
0 => {
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let (view, current) = views.list.get(i as usize)?;
(*current == generation).then(|| view.clone())
}
CONSTANT => Some(constant_of(i, generation)),
PLACED => VIEWS.lock().unwrap_or_else(|e| e.into_inner()).placed_of(i, generation),
_ => None,
}
}
/// The view recorded at `handle`, if one is (and its resource is alive).
@@ -418,9 +739,10 @@ pub(crate) fn view(handle: u64) -> Option<View> {
}
// SAFETY: the handle is a descriptor slot the title passes back.
let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let (view, current) = views.list.get(i as usize)?;
(tag == VIEW_TAG && *current == generation).then(|| view.clone())
if tag != VIEW_TAG {
return None;
}
view_at(i, generation)
}
/// A description of `N` words, if the title passes one.
@@ -741,6 +1063,81 @@ mod tests {
heap[0] = 0;
}
/// Constant buffer views are named whole in their records: any address
/// a program can have, any size below 16 KiB, multiples of 256 bytes
/// up to 4 MiB; what does not fit says so.
#[test]
fn constant_views_fit_their_records() {
let top = (1u64 << CONSTANT_ADDRESS_BITS) - 1;
for address in [0u64, 0x100, 0x2602_0000, 0xd_6b60_0000, 0x7ffd_a34f_0000, top] {
for size in [0u32, 1, 255, 256, 4000, (1 << 14) - 1, 1 << 14, 65536, (1 << 22) - 256] {
let [i, generation] = constant_words(address, size).expect("fits");
assert_eq!(generation >> KIND_SHIFT, CONSTANT);
assert_eq!(view_at(i, generation), Some(View::Constant(address, size)), "{address:#x} {size}");
}
}
assert_eq!(constant_words(top + 1, 256), None, "an address past 47 bits");
assert_eq!(constant_words(0x1000, (1 << 14) + 1), None, "16 KiB or more, no multiple of 256");
assert_eq!(constant_words(0x1000, 1 << 22), None, "4 MiB");
// Different views never share their words.
assert_ne!(constant_words(0x1000, 256), constant_words(0x1000, 512));
assert_ne!(constant_words(0x1000, 256), constant_words(0x1100, 256));
assert_ne!(constant_words(0x1000, 1 << 14), constant_words(0x1000, 64));
}
/// The leak of run 65: a title that writes constant buffer views and
/// views of placed memory at ever new addresses adds nothing to the
/// table; one shape stands for all the placed views alike.
#[test]
fn views_at_new_addresses_add_no_entries() {
if !inline() {
return;
}
let null = std::ptr::null();
let slots = [0u64; 4];
let at = slots.as_ptr() as u64;
// A resource description and a view no other test uses.
let resource: [u32; 14] = std::array::from_fn(|k| 0x5ee0_0000 + k as u32);
let mut desc: [u32; 16] = std::array::from_fn(|k| 0x7a70_0000 + k as u32);
let mine = |v: &View| match v {
View::Constant(address, _) => (0x6_0000_0000..0x6_1000_0000).contains(address),
View::Placed(_, r, _) => *r == resource,
_ => false,
};
let entries = || VIEWS.lock().unwrap().list.iter().filter(|(v, _)| mine(v)).count();
let shapes = || VIEWS.lock().unwrap().shapes.iter().filter(|s| s.1 == resource).count();
for n in 0..20_000u64 {
let address = 0x6_0000_0000 + n * 0x100;
create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at);
assert_eq!(view(at), Some(View::Constant(address, 512)));
let placed = 0xd_4940_0000 + n * 0x1_0000;
(desc[10], desc[11]) = (placed as u32, (placed >> 32) as u32);
create_placed_srv(null, &resource, &desc, at);
assert_eq!(view(at), Some(View::Placed(false, resource, desc)));
}
assert_eq!(entries(), 0, "no table entries");
assert_eq!(shapes(), 1, "one shape for 20,000 placed views");
// The same shape, unordered: another shape.
create_placed_uav(null, &resource, &desc, at);
assert_eq!(view(at), Some(View::Placed(true, resource, desc)));
assert_eq!(shapes(), 2);
// Placed memory past 1 TiB (not title memory) is a table entry.
(desc[10], desc[11]) = (0, 0x100);
create_placed_srv(null, &resource, &desc, at);
assert_eq!(view(at), Some(View::Placed(false, resource, desc)));
assert_eq!(entries(), 1);
// A record's words are the same for the same view (the host knows
// a slot's view by them), and differ with the address.
// SAFETY: both handles are slots of 32 bytes above.
let words = |handle: u64| unsafe { *(handle as *const [u32; 3]) };
let other = [0u64; 4];
create_cbv(null, &[0x40, 6, 512, 0], at);
create_cbv(null, &[0x40, 6, 512, 0], other.as_ptr() as u64);
assert_eq!(words(at), words(other.as_ptr() as u64));
create_cbv(null, &[0x140, 6, 512, 0], other.as_ptr() as u64);
assert_ne!(words(at), words(other.as_ptr() as u64));
}
/// A released resource's views go stale; the same view of a new
/// resource at the same address is a new record.
#[test]
File diff suppressed because it is too large. Load diff
+55
View File
@@ -346,6 +346,59 @@ fn feature_levels(data: *mut c_void) -> HRESULT {
}
}
/// Device methods 0x1c8 and 0x218 (`SLOT`). Grand Theft Auto VI calls both
/// (title+0x2477578 and title+0x24800d5) as `(this, description, interface
/// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the
/// object `out` names and draws with it; on failure it goes without that
/// pipeline, silently. What the descriptions hold is not known: the calls
/// fail as they always did, with `out` null, and the first ones log the
/// description's words and what its first word points at, so that the two
/// methods can be written.
/// shortcut: not implemented. Answering `S_OK` here without making the
/// pipeline would hand the title whatever its stack held as an object.
extern "system" fn unknown_pipeline<const SLOT: usize>(
_: This,
desc: *const u8,
_iid: *const Iid,
out: *mut This,
) -> HRESULT {
use std::sync::atomic::{AtomicU32, Ordering};
static CALLS: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2];
let calls = CALLS[usize::from(SLOT == 0x218)].fetch_add(1, Ordering::Relaxed) + 1;
if !out.is_null() {
// SAFETY: the title's out pointer (a local of its own).
unsafe { *out = std::ptr::null() };
}
if calls <= 4 || calls.is_power_of_two() {
// Sixteen 64-bit words at `at`, read through the kernel: neither
// pointer is known to be mapped.
#[cfg(windows)]
let words = |at: usize| -> Option<Vec<u64>> {
let mut bytes = [0u8; 128];
(at != 0 && crate::host::read_into(at as *const u8, &mut bytes)).then(|| {
bytes
.chunks_exact(8)
.map(|c| c.iter().rev().fold(0u64, |v, &b| v << 8 | u64::from(b)))
.collect()
})
};
#[cfg(not(windows))]
let words = |_: usize| None::<Vec<u64>>;
let description = words(desc as usize);
let first = description
.as_ref()
.and_then(|w| words(w[0] as usize));
tracing::warn!(
slot = format_args!("{:#x}", SLOT),
calls,
description = format_args!("{description:x?}"),
first_points_at = format_args!("{first:x?}"),
"a pipeline creation method that is not implemented: the title goes without this pipeline"
);
}
E_NOTIMPL
}
/// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the
/// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9,
/// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of
@@ -382,8 +435,10 @@ static FUNCTIONS: Table<160> = {
f[39] = query::create as *const (); // 0x138
f[41] = signature::create as *const (); // 0x148
f[48] = queue::create_x as *const (); // 0x180
f[57] = unknown_pipeline::<0x1c8> as *const (); // 0x1c8
f[61] = descriptor::create_sampler_x as *const (); // 0x1e8
f[62] = pipeline::create_compute_x as *const (); // 0x1f0
f[67] = unknown_pipeline::<0x218> as *const (); // 0x218
f[69] = object::ignore as *const (); // 0x228 debug error filter
f[70] = descriptor::create_placed_srv as *const (); // 0x230
f[71] = descriptor::create_placed_uav as *const (); // 0x238
File diff suppressed because it is too large. Load diff
+24 -2
View File
@@ -219,6 +219,27 @@ struct Mode {
}
const _: () = assert!(size_of::<Mode>() == 32);
/// The size of the display the console reports: `VICTORY_DISPLAY_MODE=WxH`
/// if set (as a console reports the television it is plugged into: a
/// Series X on a 1080p set lists a 1080p mode), else 3840x2160.
/// shortcut: not yet the host display's own size by default; make it so
/// once a title is seen to render for the mode it is given.
fn display_size() -> (u32, u32) {
static SIZE: std::sync::OnceLock<(u32, u32)> = std::sync::OnceLock::new();
*SIZE.get_or_init(|| {
let asked = std::env::var("VICTORY_DISPLAY_MODE").ok().and_then(|v| {
let (w, h) = v.trim().split_once(['x', 'X'])?;
Some((w.trim().parse::<u32>().ok()?, h.trim().parse::<u32>().ok()?))
});
let size = match asked {
Some((w, h)) if (640..=7680).contains(&w) && (360..=4320).contains(&h) => (w, h),
_ => (3840, 2160),
};
tracing::info!(width = size.0, height = size.1, "display mode reported to the title");
size
})
}
/// The console's mode list: one 4K mode at 60 Hz (Grand Theft Auto VI looks
/// for a 120 Hz one to allow 120 Hz frame intervals).
/// shortcut: fixed mode, not the host display's; report the host's rates if
@@ -242,9 +263,10 @@ extern "system" fn modes(
return MORE_DATA;
}
*count = 1;
let (width, height) = display_size();
let mode = Mode {
width: 3840,
height: 2160,
width,
height,
refresh: [60, 1],
format: 0,
scanlines: 1, // progressive
+22 -2
View File
@@ -75,7 +75,7 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT
extern "system" fn release(this: This) -> u32 {
object::release_boxed::<Fence>(this)
}
extern "system" fn completed(this: This) -> u64 {
pub(crate) extern "system" fn completed(this: This) -> u64 {
fence(this).value.load(Ordering::Acquire)
}
extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT {
@@ -88,6 +88,19 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c
return S_OK;
}
if event.is_null() {
// With submissions sent to the card and not waited for
// (`crate::host::late`) the signal may be behind them: they are
// settled, which sets it.
#[cfg(windows)]
if crate::host::late() {
drop(waiters);
crate::host::settle_for_fence();
if fence.value.load(Ordering::Acquire) >= value {
return S_OK;
}
tracing::warn!(value, "blocking fence wait not implemented");
return E_NOTIMPL;
}
// shortcut: a null event means "block until reached"; nothing can
// reach it while no GPU work runs, so fail instead of hanging.
tracing::warn!(value, "blocking fence wait not implemented");
@@ -96,7 +109,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c
waiters.push((value, event as usize));
S_OK
}
pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
/// Moves the fence to `value` and sets the events that waited for it.
pub(crate) fn set(this: This, value: u64) {
let fence = fence(this);
let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
fence.value.store(value, Ordering::Release);
@@ -107,6 +121,12 @@ pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
}
!reached
});
}
pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
set(this, value);
// A queue may have waited for it: what it held runs now.
#[cfg(windows)]
crate::queue::release_held(false);
S_OK
}
+21 -1
View File
@@ -126,8 +126,22 @@ pub(crate) extern "system" fn wait(
token: *mut u64,
) -> HRESULT {
let origin = kind == ORIGIN;
let (tick, wait) = next_tick(kind);
let (mut tick, mut wait) = next_tick(kind);
let limit = Duration::from_millis(u64::from(timeout_ms));
// A blocking wait for an event that has happened since the last wait
// for it ended (a frame took longer than a tick) ends at once, on the
// tick that passed: sleeping on to the next one cost 17 ms of every
// 730 ms frame (run 58: "2.0 frame waits sleeping 16.8 ms"). Polls (a
// time-out shorter than a tick) answer as before.
// `VICTORY_LATE_WAITS=1` sleeps to the next tick, as before.
static SLEEP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*SLEEP.get_or_init(|| std::env::var_os("VICTORY_LATE_WAITS").is_some_and(|v| v == "1"))
&& limit >= wait
&& tick > last(kind).load(Ordering::Relaxed) + 1
{
tick -= 1;
wait = Duration::ZERO;
}
let hr = if wait > limit {
std::thread::sleep(limit);
TIMEOUT
@@ -136,6 +150,12 @@ pub(crate) extern "system" fn wait(
last(kind).fetch_max(tick, Ordering::Relaxed);
S_OK
};
#[cfg(all(windows, feature = "diagnostics"))]
{
use crate::copystat::{C, add};
add(C::PaceWaits, 1);
add(C::PaceUs, wait.min(limit).as_micros() as u64);
}
// A frame begun on a time-out takes no tick: its flip still does.
if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) {
// Tokens count frames (consecutive), not ticks.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+9 -1
View File
@@ -31,6 +31,8 @@ pub mod frame;
mod host;
#[cfg(windows)]
mod indirect;
#[cfg(windows)]
mod inplace;
pub mod list;
pub mod object;
pub mod pipeline;
@@ -45,6 +47,8 @@ mod sampler;
#[cfg(windows)]
pub mod shader_cache;
#[cfg(windows)]
mod memory;
#[cfg(windows)]
mod shadow;
pub mod signature;
#[cfg(windows)]
@@ -55,4 +59,8 @@ mod watch;
#[cfg(windows)]
pub use host::on_failure;
#[cfg(windows)]
pub use watch::{title_memory_remapped, writing as kernel_will_write};
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view};
#[cfg(windows)]
pub use watch::{
title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write,
};
File diff suppressed because it is too large. Load diff
+319
View File
@@ -0,0 +1,319 @@
//! Title memory by address, for translated shaders that read and write
//! through raw 40-bit addresses (`victory_shader::emit::SLOT_MEMORY`: the
//! console's ray-tracing structure builder and the programs that walk its
//! structures; the structures themselves lie in plain title memory, in no
//! buffer object).
//!
//! The copies are the ones every other access uses ([`crate::shadow`]: a
//! title buffer's copy, or the 4 MiB window of memory outside buffers), so
//! a root view and a raw address reach the same host bytes. This module
//! keeps what a shader needs to find them:
//!
//! - the **directory**: per 64 KiB page of title address space the number
//! of the copy that holds the page (0: none) and the page's byte offset
//! in it; one buffer for all lists, entries only ever go from empty to
//! filled;
//! - per view heap a run of slots with a raw unordered access view of each
//! numbered copy (slot 0 of the run: a null view, for pages without a
//! copy);
//! - the **faults**: the page numbers shaders found empty, read back here
//! once a frame, so the copies exist from the next frame on. A pointer a
//! shader takes out of memory cannot be known before it runs; the
//! addresses a dispatch is given as root views are made ready before it.
//!
//! **A page that is not there when a shader touches it is a lost access**:
//! the read gives 0, the store is dropped, and the fault note only helps
//! the next frame. For the structure builder that is the same as a dropped
//! stage, so before a dispatch the host makes ready everything it can see
//! the dispatch name: the whole copy around each root view, around each
//! pair of root constants that is a title address and around each root
//! constant that is one in 256-byte units (the builder passes structures
//! all three ways), and the 4 MiB after each (a structure may cross a
//! window's end).
//! shortcut: what a stage reaches only through pointers it reads out of
//! memory (InitHeaders' table of structure addresses, LoadInstances'
//! instance records) is not made ready unless something else named it;
//! the fault count in the log says whether that happens. The whole answer
//! is the extent of the title's allocation around an address, which the
//! memory module of the layer knows and this one does not ask yet.
//!
//! shortcut: a copy that is numbered is kept for the rest of the run, and
//! there are at most [`COPIES`] of them (4 MiB windows mostly: 4 GiB at
//! most). Every dispatch of such a shader brings all numbered copies up to
//! date and, if it can store, declares all of them written (the bytes are
//! compared on the CPU afterwards, as for any unordered access view): a
//! dirty-page mask written by the shader would bound both.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES};
use windows::Win32::Graphics::Direct3D12::*;
use crate::descriptor::host::HostHeap;
use crate::host::{HostList, host};
use crate::shadow::Shadow;
/// Copies that can be numbered (the run of heap slots is one longer). A
/// listed frame of the opening cutscene names about 50 windows.
const COPIES: u32 = 1023;
/// A window of memory outside buffers (`shadow.rs`).
const CELL: u64 = 4 << 20;
/// A directory page.
const PAGE: u64 = 1 << 16;
struct Memory {
/// Buffer, its mapping, its GPU address.
directory: (ID3D12Resource, *mut u32, u64),
faults: (ID3D12Resource, *mut u32, u64),
/// Copy `n` is `copies[n - 1]`.
copies: Vec<Arc<Shadow>>,
/// Per host view heap (by address): the first slot of its run, and how
/// many copies have their view there.
heaps: HashMap<usize, (u32, u32)>,
/// The frame the faults were last read in.
frame: u64,
/// Pages asked for this frame that are not the title's memory.
refused: std::collections::HashSet<u64>,
}
// SAFETY: the mappings are of buffers the struct owns; all access is under
// the mutex.
unsafe impl Send for Memory {}
static MEMORY: Mutex<Option<Memory>> = Mutex::new(None);
/// What a draw binds.
pub(crate) struct Ready {
pub(crate) directory: u64,
pub(crate) faults: u64,
/// The view heap slot of the null view; copy `n`'s view is `n` further.
pub(crate) base: u32,
}
impl Memory {
fn new() -> Option<Memory> {
let host = host()?;
let make = |dwords: u64, what: &str| {
let (buffer, data) = host.shared_buffer(dwords * 4)?;
crate::host::name(&buffer, || format!("title memory by address: {what}"));
// SAFETY: a fresh mapping of at least that many bytes.
unsafe { std::ptr::write_bytes(data, 0, (dwords * 4) as usize) };
// SAFETY: a live buffer.
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
Some((buffer, data.cast::<u32>(), gpu))
};
tracing::info!("title memory by address: a shader reads or writes through raw addresses");
Some(Memory {
directory: make(u64::from(MEMORY_PAGES) * 2, "directory")?,
faults: make(u64::from(MEMORY_FAULTS), "faults")?,
copies: Vec::new(),
heaps: HashMap::new(),
frame: u64::MAX,
refused: Default::default(),
})
}
/// Gives the page of `address` its copy, if it has none and the memory
/// is the title's.
fn map(&mut self, address: u64) {
let page = address / PAGE;
// The last entry stays empty: addresses past the directory read it.
if page >= u64::from(MEMORY_PAGES) - 1 {
return;
}
// SAFETY: inside the directory's mapping.
let entry = unsafe { self.directory.1.add(page as usize * 2) };
// SAFETY: as above.
if unsafe { entry.read() } != 0 {
return;
}
let start = page * PAGE;
// A shader's pointer, or a constant taken for an address, may be
// anything: only memory the title has.
if self.refused.contains(&page) {
return;
}
if !crate::texture::committed(start as *const u8, PAGE as usize) {
self.refused.insert(page);
return;
}
// The copy a root view at that address would get; a buffer that
// ends inside the page is passed over for what holds all of it.
let whole = |s: &Arc<Shadow>| s.offset_in(start).is_some_and(|_| s.left(start) >= PAGE);
let Some(shadow) = crate::shadow::find(start, 1)
.filter(whole)
.or_else(|| crate::shadow::find(start, PAGE).filter(whole))
else {
return;
};
// SAFETY: a live buffer.
let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
return;
}
let n = match self.copies.iter().position(|c| Arc::ptr_eq(c, &shadow)) {
Some(n) => n,
None if self.copies.len() < COPIES as usize => {
self.copies.push(shadow.clone());
let n = self.copies.len() - 1;
// Every page the copy holds whole, not only the one asked
// for: a structure is more than 64 KiB.
// shortcut: a page of a title buffer inside this one that
// has a copy of its own is given this copy too.
let (first, len) = shadow.span();
let mut at = first.next_multiple_of(PAGE);
while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 {
// SAFETY: inside the directory's mapping.
let other = unsafe { self.directory.1.add((at / PAGE) as usize * 2) };
// SAFETY: as above; the offset first, as below.
unsafe {
if other.read() == 0 {
other.add(1).write_volatile((at - first) as u32);
other.write_volatile(n as u32 + 1);
}
}
at += PAGE;
}
n
}
None => {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros")
});
return;
}
};
let offset = shadow.offset_in(start).unwrap_or(0);
// The offset first: a shader that sees the number sees it too.
// SAFETY: inside the directory's mapping.
unsafe {
entry.add(1).write_volatile(offset as u32);
entry.write_volatile(n as u32 + 1);
}
}
/// The pages shaders found empty since the last frame.
fn take_faults(&mut self) {
let mut pages = Vec::new();
for i in 1..MEMORY_FAULTS as usize {
// SAFETY: inside the faults' mapping; the GPU may be writing,
// a number missed now is written again next frame.
let at = unsafe { self.faults.1.add(i) };
// SAFETY: as above.
let page = unsafe { at.read_volatile() };
if page != 0 {
pages.push(page);
// SAFETY: as above.
unsafe { at.write_volatile(0) };
}
}
if !pages.is_empty() {
// Each is an access that read 0 or was dropped.
static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 50 {
tracing::warn!(
pages = pages.len(),
first = format_args!("{:#x}", u64::from(pages[0]) * PAGE),
"title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now"
);
}
}
for page in pages {
self.map(u64::from(page) * PAGE);
}
}
/// What a dispatch names: the copy around `address` and the 4 MiB
/// after it.
fn name(&mut self, address: u64) {
self.map(address);
self.map((address & !(CELL - 1)) + CELL);
}
}
/// Before a draw whose shader reads title memory by address: what its
/// root arguments name gets its copies (`addresses`: its root views;
/// `constants`: its root constants, see the module), every numbered copy
/// has its view in `heap`'s run and is brought up to date when `list` is
/// submitted (and, with `writes`, copied back after). None if the host
/// cannot hold it; the draw is then dropped.
pub(crate) fn ready(
list: &HostList,
heap: &HostHeap,
addresses: &[u64],
constants: &[u32],
writes: bool,
) -> Option<Ready> {
let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner());
if guard.is_none() {
*guard = Memory::new();
}
let m = guard.as_mut()?;
let frame = crate::frame::current();
if m.frame != frame {
m.frame = frame;
m.refused.clear();
m.take_faults();
}
let numbered = m.copies.len();
for &address in addresses {
m.name(address);
}
// A title address in two constants (low dword, then bits 32 to 39), or
// in one in 256-byte units. A constant that only looks like one names
// memory nothing reads; one that is not the title's memory is refused.
for (i, &c) in constants.iter().enumerate() {
if let Some(&high) = constants.get(i + 1)
&& (1..=0xFF).contains(&high)
&& c >= 0x1_0000
{
m.name(u64::from(c) | u64::from(high) << 32);
}
if c >= 0x0100_0000 {
m.name(u64::from(c) << 8);
}
}
let key = std::ptr::from_ref(heap) as usize;
let (base, made) = match m.heaps.get(&key) {
Some(&run) => run,
None => {
// Held for the heap's life: not given back with a list's slots.
let base = heap.dynamic(COPIES + 1)?;
heap.null_raw_uav_at(base);
(base, 0)
}
};
for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) {
let (_, len) = shadow.span();
heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len);
}
m.heaps.insert(key, (base, m.copies.len() as u32));
// Once per list, and for copies numbered since: the builder alone
// dispatches hundreds of times a frame.
// shortcut: a copy another list numbers meanwhile is brought up to date
// by that list's submission, which may run after this one's.
const READ: usize = usize::MAX - 0x6d;
const WRITE: usize = usize::MAX - 0x6e;
let first_read = list.first_use(READ);
let first_write = writes && list.first_use(WRITE);
for (n, shadow) in m.copies.iter().enumerate() {
let (start, len) = shadow.span();
if first_read || n >= numbered {
shadow.refresh(list, start, len);
}
if writes && (first_write || n >= numbered) {
shadow.gpu_writes(list, start, len);
}
}
if first_read {
list.keep(&m.directory.0);
list.keep(&m.faults.0);
}
Some(Ready {
directory: m.directory.2,
faults: m.faults.2,
base,
})
}
+232 -14
View File
@@ -74,6 +74,28 @@ impl std::fmt::Debug for Shader {
/// Every container seen, by full content hash.
static SHADERS: Mutex<Option<HashMap<[u8; 32], Arc<Shader>>>> = Mutex::new(None);
/// For the memory lines: containers kept and their bytes, translations
/// kept and the bytes of their host code. None of them is ever let go.
static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// What the shader table and the pipeline library keep in memory:
/// containers and their bytes, translations and their bytes, the bytes of
/// the library's file (kept whole while the library lives) and what its
/// last save wrote.
#[cfg(windows)]
pub(crate) fn kept() -> [u64; 7] {
use std::sync::atomic::Ordering::Relaxed;
[
KEPT[0].load(Relaxed),
KEPT[1].load(Relaxed),
KEPT[2].load(Relaxed),
KEPT[3].load(Relaxed),
library::BLOB.load(Relaxed),
library::SAVED.load(Relaxed),
library::TRIMMED_BYTES.load(Relaxed),
]
}
/// The shared container for `bytes`.
fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
let full = blake3::hash(bytes);
@@ -82,6 +104,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
.get_or_insert_with(HashMap::new)
.entry(*full.as_bytes())
.or_insert_with(|| {
KEPT[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
KEPT[1].fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed);
Arc::new(Shader {
stage,
hash: full.to_hex()[..16].to_owned(),
@@ -98,6 +122,9 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
pub(crate) struct Translated {
pub(crate) host: victory_shader::emit::HostShader,
pub(crate) used: Vec<victory_shader::UsedResource>,
/// Whether the shader's code can store to buffer memory ([`stores`]);
/// true when its code is not known.
pub(crate) stores: bool,
}
#[cfg(windows)]
@@ -108,6 +135,21 @@ impl Shader {
self.translated
.get_or_init(|| {
let done = translate(&self.container);
// `VICTORY_SHADER_SAVE=<dir>`: each shader as the title gave it (`.cdxil`) and as
// translated (`.dxil`), by the hash crash reports name it with
if let Some(dir) = std::env::var_os("VICTORY_SHADER_SAVE") {
let dir = std::path::PathBuf::from(dir);
let _ = std::fs::create_dir_all(&dir);
let stem = format!("{}.{}", self.hash, self.stage);
let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &self.container);
if let Ok(t) = &done {
let _ = std::fs::write(dir.join(format!("{stem}.dxil")), &t.host.dxil);
}
}
if let Ok(t) = &done {
KEPT[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
KEPT[3].fetch_add(t.host.dxil.len() as u64, std::sync::atomic::Ordering::Relaxed);
}
match &done {
Ok(t) => tracing::info!(
stage = self.stage,
@@ -132,23 +174,170 @@ impl Shader {
#[cfg(windows)]
fn translate(container: &[u8]) -> Result<Translated, String> {
use victory_shader::{Container, FourCC, HwStage};
let host = crate::shader_cache::host_shader(container)?;
// The translation depends on it (a view index past a capped heap).
crate::descriptor::host::probe_view_limit();
let c = Container::parse(container).map_err(|e| e.to_string())?;
let used = match c.part(FourCC::DXIL) {
Some(part) => victory_shader::native_programs(part.data)
.map_err(|e| e.to_string())?
.into_iter()
.find(|p| {
matches!(
p.stage,
HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs
)
})
.map(|p| p.used)
.unwrap_or_default(),
let programs = match c.part(FourCC::DXIL) {
Some(part) => victory_shader::native_programs(part.data).map_err(|e| e.to_string())?,
None => Vec::new(),
};
Ok(Translated { host, used })
let host = crate::shader_cache::host_shader(container)?;
let stores = programs.is_empty() || programs.iter().any(stores);
let used = programs
.into_iter()
.find(|p| {
matches!(
p.stage,
HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs
)
})
.map(|p| p.used)
.unwrap_or_default();
Ok(Translated { host, used, stores })
}
/// The compute pipelines of the console's ray-tracing structure builder
/// (`XboxBvhBuilder.dll`; its programs are the ones with a spilled
/// user-data table) run **all or none**. Its stages feed each other
/// through memory: a stage that runs on what a dropped stage never wrote
/// computes its store offsets from garbage. The structures lie in plain
/// title memory, between the title's own objects, and a root view has no
/// size, so those stores land on the neighbours (run 98, with 14 of 35
/// stages translated: the title died within a second of the first builder
/// submission, on pointers that had become bounding-box bit patterns).
///
/// So a builder dispatch runs only while every builder pipeline the title
/// has created has a host pipeline; the first builder dispatch makes them
/// all on the spot instead of over the next frames (a stage "still being
/// made" would be a dropped stage). One that cannot be made turns the
/// builder off for the rest of the run.
///
/// shortcut: and only with `VICTORY_BVH_BUILDER=1`, until a run has shown
/// the whole builder and the host side of title memory by address
/// (`memory.rs`) working on a card; nothing reads the structures before
/// the programs that walk them translate.
#[cfg(windows)]
struct Builder {
pipelines: Vec<Arc<make::Pending>>,
/// Every one of `pipelines` has a host pipeline.
whole: bool,
/// One could not be made.
off: bool,
}
#[cfg(windows)]
static BUILDER: Mutex<Builder> = Mutex::new(Builder {
pipelines: Vec::new(),
whole: false,
off: false,
});
/// Whether `shaders` are a pipeline of the structure builder.
#[cfg(windows)]
fn of_builder(shaders: &[Arc<Shader>]) -> bool {
use victory_shader::{Container, FourCC};
let [shader] = shaders else { return false };
if shader.stage != "compute" {
return false;
}
let Ok(c) = Container::parse(&shader.container) else {
return false;
};
c.part(FourCC::DXIL)
.and_then(|part| victory_shader::native_programs(part.data).ok())
.is_some_and(|programs| programs.iter().any(victory_shader::spill::is_spilled))
}
/// `VICTORY_BVH_QUARANTINE=1`: what the structure builder's stages store
/// stays in the host's copies and is not copied back into title memory. A
/// check for a first run of the whole builder: a stage that stores where
/// it should not can then not reach the title's own objects (run 98), and
/// the programs that walk the structures read the host's copies anyway.
/// shortcut: not a way to run: the title also reads results back (sizes,
/// counters) and gets none, and a copy's pages are overwritten from title
/// memory when the title writes them.
#[cfg(windows)]
pub(crate) fn builder_quarantined(this: This) -> bool {
static ON: OnceLock<bool> = OnceLock::new();
is_builder(this) && *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_QUARANTINE").is_some_and(|v| v == "1"))
}
/// Whether the title's pipeline `this` is one of the structure builder's.
#[cfg(windows)]
pub(crate) fn is_builder(this: This) -> bool {
!this.is_null() && pipeline(this).builder
}
/// A stage of the builder was dropped after all: none runs from here on.
#[cfg(windows)]
pub(crate) fn builder_off(why: &'static str) {
let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
if !b.off {
b.off = true;
tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none");
}
}
/// At a dispatch of a builder pipeline: whether the builder runs (see
/// [`Builder`]).
#[cfg(windows)]
pub(crate) fn builder_runs() -> bool {
static ALLOWED: OnceLock<bool> = OnceLock::new();
if !*ALLOWED.get_or_init(|| std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1")) {
return false;
}
let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
if b.off {
return false;
}
if b.whole {
return true;
}
let missing = b.pipelines.iter().filter(|p| !make::now(p)).count();
if missing > 0 {
b.off = true;
tracing::warn!(
missing,
of = b.pipelines.len(),
"the ray-tracing structure builder stays off: not all of its programs have a host pipeline, and its stages run all or none"
);
return false;
}
tracing::info!(
pipelines = b.pipelines.len(),
"the ray-tracing structure builder runs: all of its programs have host pipelines"
);
b.whole = true;
true
}
/// Whether a console program can store to buffer memory: it has a buffer,
/// typed-buffer, scalar-memory, flat or global store or atomic, or code
/// that is not all known (an instruction of those kinds outside our table,
/// an indirect jump, code that does not decode). Stores to textures
/// (image instructions) and to the program's own scratch memory do not
/// count: neither reaches a buffer's host copy. After upstream #413,
/// which leaves scalar-memory stores out and counts image stores.
#[cfg(windows)]
fn stores(program: &victory_shader::NativeProgram) -> bool {
use victory_shader::gfx10::{Encoding, decode};
let Ok(code) = decode(&program.code) else {
return true;
};
code.iter().any(|i| {
let name = i.name();
match i.encoding {
Encoding::Mubuf
| Encoding::Mtbuf
| Encoding::Smem
| Encoding::Flat
| Encoding::Global => name.is_none_or(|n| {
(n.contains("store") || n.contains("atomic")) && !n.contains("scratch")
}),
Encoding::Sop1 => name.is_none_or(|n| matches!(n, "s_setpc_b64" | "s_swappc_b64")),
_ => false,
}
})
}
#[repr(C)]
@@ -163,6 +352,9 @@ struct Pipeline {
/// (by a worker: the title may release the pipeline meanwhile).
#[cfg(windows)]
host: Arc<make::Pending>,
/// One of the ray-tracing structure builder's ([`Builder`]).
#[cfg(windows)]
builder: bool,
}
const _: () = assert!(offset_of!(Pipeline, packet) == 0x10);
@@ -274,6 +466,7 @@ pub(crate) fn note_drop(this: This) {
/// Counts a draw or dispatch dropped for `why` (diagnostics).
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn note_why(why: String) {
crate::capture::op(0, || format!("DROPPED {why}"));
let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner());
*drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1;
}
@@ -311,11 +504,22 @@ fn hand_out(
let host = Arc::new(make::Pending::new(shaders.clone(), graphics));
#[cfg(windows)]
make::early(&host);
#[cfg(windows)]
let builder = of_builder(&shaders);
#[cfg(windows)]
if builder {
// Another stage: the group is looked at again at its next dispatch.
let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
b.pipelines.push(host.clone());
b.whole = false;
}
let pipeline = Box::new(Pipeline {
object: Object::new(&FUNCTIONS),
packet: [0; 8],
#[cfg(windows)]
host,
#[cfg(windows)]
builder,
shaders,
bound: std::sync::atomic::AtomicBool::new(false),
});
@@ -490,6 +694,20 @@ mod library;
#[cfg(windows)]
mod make;
/// Lets the pipeline library's mapped file go from memory when no pipeline
/// has loaded for a while (`library::trim`); called by the host's sweep.
#[cfg(windows)]
pub(crate) fn trim_library() {
library::trim();
}
/// The pipeline library's part of the report when the host device is
/// removed (`library::removal_note`).
#[cfg(windows)]
pub(crate) fn library_removal_note() -> String {
library::removal_note()
}
/// Keeps compiled host pipelines, and the list of title pipelines to start
/// early, in `dir` (a folder of the cache) across runs.
#[cfg(windows)]
+274 -17
View File
@@ -109,6 +109,15 @@ impl GraphicsState {
// pipeline uses the plain description); bring it back
// with a stream if a title enables it.
let d = data.cast::<D3D12_DEPTH_STENCIL_DESC1>().read_unaligned();
if d.DepthBoundsTestEnable.as_bool() {
static SEEN: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(0);
if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
tracing::warn!(
"a pipeline enables the depth bounds test, which its host pipeline leaves out: its draws pass at every depth"
);
}
}
self.depth = D3D12_DEPTH_STENCIL_DESC {
DepthEnable: d.DepthEnable,
DepthWriteMask: d.DepthWriteMask,
@@ -156,7 +165,9 @@ impl GraphicsState {
15 => {
self.targets = data.cast::<D3D12_RT_FORMAT_ARRAY>().read_unaligned();
for f in &mut self.targets.RTFormats {
f.0 = crate::resource::pc_format(f.0 as u32) as i32;
f.0 = crate::resource::target_format(crate::resource::pc_format(
f.0 as u32,
)) as i32;
}
}
16 => {
@@ -243,6 +254,17 @@ pub(crate) struct Input {
const RECTANGLES: i32 = 19;
const QUADS: i32 = 32;
/// Whether the title's root SRVs are bound as one-view tables of the
/// buffer's host copy, whose reads past its end return zeros, rather than
/// as root descriptors, which have no size: a mesh shader's vertex fetch
/// has no record limit, and a read past the copy reaches whatever the host
/// placed after it (memory it has freed: the device is removed, upstream
/// PR #493). `VICTORY_ROOT_SRV_DIRECT=1` goes back to root descriptors.
pub(crate) fn bounded_root_srvs() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_ROOT_SRV_DIRECT").is_none())
}
/// One stage of a host pipeline and where its bindings go.
pub(crate) struct Stage {
pub(crate) shader: Arc<Shader>,
@@ -251,6 +273,9 @@ pub(crate) struct Stage {
/// Root parameters of its root views: (title root parameter, ours).
pub(crate) root_cbvs: Vec<(u8, u32)>,
pub(crate) root_srvs: Vec<(u8, u32)>,
/// Root UAVs: one-view tables like the SRVs (or root descriptors with
/// `VICTORY_ROOT_SRV_DIRECT=1`).
pub(crate) root_uavs: Vec<(u8, u32)>,
}
impl Stage {
@@ -273,8 +298,15 @@ pub(crate) struct HostPipeline {
/// The vertex buffer slots it reads (bit per slot).
pub(crate) slots: u32,
pub(crate) inputs: Vec<Input>,
/// Has the geometry stage that completes the console's rectangles
/// (`victory_shader::emit::rect_list_gs`): its rectangle draws go out
/// as the title gives them, three vertices a rectangle.
pub(crate) rects: bool,
/// Its shaders, for reports of slow submissions.
pub(crate) name: String,
/// Its depth, stencil, cull and blend state in short, for the frame
/// listing (empty for compute).
pub(crate) state: String,
}
/// Logs a pipeline that gets no host pipeline, once per reason.
@@ -292,6 +324,9 @@ impl HostPipeline {
/// A host pipeline for vertex and pixel shaders with the graphics
/// state `g`, or for one compute shader.
pub(crate) fn new(shaders: &[Arc<Shader>], g: Option<&GraphicsState>) -> Option<HostPipeline> {
// For the report when the host device is removed: what this thread
// has in the library from here on.
super::library::label(format!("{shaders:?}"));
let find = |stage| shaders.iter().find(|s| s.stage == stage);
let compute = match shaders {
[cs] if cs.stage == "compute" => Some(cs),
@@ -330,6 +365,9 @@ impl HostPipeline {
// The root signature the translated shaders' bindings define.
let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new();
// The ranges table parameters point at, alive until the root
// signature is made.
let mut ranges: Vec<Box<D3D12_DESCRIPTOR_RANGE1>> = Vec::new();
let mut samplers = Vec::new();
let mut bound = Vec::new();
for &(shader, visibility) in &stages {
@@ -339,6 +377,7 @@ impl HostPipeline {
user_data: None,
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
root_uavs: Vec::new(),
};
let dwords = t.user_data_dwords();
if dwords > 0 {
@@ -366,8 +405,55 @@ impl HostPipeline {
D3D12_ROOT_PARAMETER_TYPE_SRV,
&mut stage.root_srvs,
),
(
&t.root_uavs,
D3D12_ROOT_PARAMETER_TYPE_UAV,
&mut stage.root_uavs,
),
] {
for &slot in slots {
let uav = kind == D3D12_ROOT_PARAMETER_TYPE_UAV;
// Ours, not the title's, stay root descriptors: the
// table of strides, the directory of title memory by
// address and its fault notes.
let ours = if uav {
slot == victory_shader::emit::SLOT_FAULTS
} else {
slot == victory_shader::emit::SLOT_STRIDES
|| slot == victory_shader::emit::SLOT_MEMORY
};
if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() {
// A one-view table: the view's size bounds the
// reads (and a root UAV's writes), which a root
// descriptor leaves unbounded.
// (Our own table of strides stays a descriptor.)
ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 {
RangeType: if uav {
D3D12_DESCRIPTOR_RANGE_TYPE_UAV
} else {
D3D12_DESCRIPTOR_RANGE_TYPE_SRV
},
NumDescriptors: 1,
BaseShaderRegister: u32::from(slot),
RegisterSpace: ROOT_CBV_SPACE,
Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE
| D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE,
OffsetInDescriptorsFromTableStart: 0,
}));
let range: *const D3D12_DESCRIPTOR_RANGE1 = &**ranges.last()?;
out.push((slot, params.len() as u32));
params.push(D3D12_ROOT_PARAMETER1 {
ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE,
Anonymous: D3D12_ROOT_PARAMETER1_0 {
DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 {
NumDescriptorRanges: 1,
pDescriptorRanges: range,
},
},
ShaderVisibility: visibility,
});
continue;
}
out.push((slot, params.len() as u32));
params.push(D3D12_ROOT_PARAMETER1 {
ParameterType: kind,
@@ -451,6 +537,8 @@ impl HostPipeline {
name: format!("{shaders:?}"),
slots: 0,
inputs: Vec::new(),
rects: false,
state: String::new(),
});
}
let Some(g) = g else {
@@ -458,8 +546,12 @@ impl HostPipeline {
};
let state = g.describe();
if mesh.is_some() {
// "triangles": the stream names its topology since it did not
// load from the library without one (see `mesh_pipeline`); a
// new name keeps such entries, stored before, from being
// looked up again.
let name = super::library::name(
"mesh",
"mesh triangles",
&root_blob,
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
&state,
@@ -483,14 +575,35 @@ impl HostPipeline {
name: format!("{shaders:?}"),
slots: 0,
inputs: Vec::new(),
rects: false,
state: String::new(),
});
}
let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
// A pipeline the title makes for rectangles gets a geometry stage
// that completes each one from the three vertices the vertex
// shader made. Without it (refused here or by the host) the draws
// fall back on what `draw` does for rectangles.
let mut rect_gs = None;
if g.topology.0 == RECTANGLES {
let ps = stages.get(1).and_then(|(s, _)| s.translated());
let vs = &stages[0].0.translated()?.host.dxil;
match victory_shader::emit::rect_list_gs(vs, ps.map(|t| &t.host.dxil[..])) {
Ok(gs) => rect_gs = Some(gs),
Err(e) => tracing::warn!(error = %e, ?shaders, "no rectangle geometry stage"),
}
}
let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
// SAFETY: a borrowed pointer the description never releases.
pRootSignature: unsafe { std::mem::transmute_copy(&root) },
VS: code(0),
PS: code(1),
GS: rect_gs.as_ref().map_or(D3D12_SHADER_BYTECODE::default(), |gs| {
D3D12_SHADER_BYTECODE {
pShaderBytecode: gs.as_ptr().cast(),
BytecodeLength: gs.len(),
}
}),
BlendState: g.blend,
SampleMask: g.sample_mask,
RasterizerState: g.rasterizer,
@@ -512,19 +625,40 @@ impl HostPipeline {
SampleDesc: g.samples,
..Default::default()
};
let name = super::library::name(
"graphics",
&root_blob,
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
&state,
);
let made = super::library::pipeline(
&name,
// SAFETY: the description points at live data.
|library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) },
// SAFETY: as above.
|| unsafe { host.device.CreateGraphicsPipelineState(&desc) },
);
// A pipeline with the geometry stage has a name of its own in the
// library; the others keep theirs.
let name = |gs: Option<&Vec<u8>>| match gs {
Some(gs) => super::library::name(
"graphics rectangles",
&root_blob,
&[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs[..]],
&state,
),
None => super::library::name(
"graphics",
&root_blob,
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
&state,
),
};
let make = |desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, name: &str| {
super::library::pipeline(
name,
// SAFETY: the description points at live data.
|library, name| unsafe { library.LoadGraphicsPipeline(name, desc) },
// SAFETY: as above.
|| unsafe { host.device.CreateGraphicsPipelineState(desc) },
)
};
let mut made = make(&desc, &name(rect_gs.as_ref()));
if made.is_err() && rect_gs.is_some() {
// The host refused the geometry stage: once more without it.
tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage");
host.log_messages();
desc.GS = D3D12_SHADER_BYTECODE::default();
rect_gs = None;
made = make(&desc, &name(None));
}
let pso = match made {
Ok(pso) => pso,
Err(e) => {
@@ -553,12 +687,49 @@ impl HostPipeline {
name: format!("{shaders:?}"),
slots: g.slots(),
inputs: g.elements(),
rects: rect_gs.is_some(),
state: {
let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]);
let face = |f: &D3D12_DEPTH_STENCILOP_DESC| {
format!(
"fail {} depth-fail {} pass {} func {}",
f.StencilFailOp.0, f.StencilDepthFailOp.0, f.StencilPassOp.0, f.StencilFunc.0
)
};
format!(
"depth {} write {} func {}; stencil {} read {:#x} write {:#x} front [{}] back [{}]; cull {} front-ccw {}; blend {} src {} dst {} op {} mask {:#x}",
d.DepthEnable.as_bool(),
d.DepthWriteMask.0,
d.DepthFunc.0,
d.StencilEnable.as_bool(),
d.StencilReadMask,
d.StencilWriteMask,
face(&d.FrontFace),
face(&d.BackFace),
r.CullMode.0,
r.FrontCounterClockwise.as_bool(),
b.BlendEnable.as_bool(),
b.SrcBlend.0,
b.DestBlend.0,
b.BlendOp.0,
b.RenderTargetWriteMask
)
},
})
}
}
/// A mesh pipeline from the title's graphics state: the pipeline-state
/// stream form (no input layout or topology).
/// stream form (no input layout).
///
/// The stream names a triangle topology, which D3D12 does not need for a
/// mesh shader: without it the pipeline library refuses to load a stored
/// pipeline with the very stream it was made from (`E_INVALIDARG`; debug
/// layer message 972, "does not match the one used to create the PSO"), so
/// every mesh pipeline was compiled again, and its store then refused (970,
/// "already exists"). The translation makes triangle mesh shaders only
/// (`mesh_prologue` refuses others), and the debug layer wants the two to
/// agree (1323).
fn mesh_pipeline(
device: &ID3D12Device,
root: &ID3D12RootSignature,
@@ -583,6 +754,7 @@ fn mesh_pipeline(
targets: Sub<D3D12_RT_FORMAT_ARRAY>,
dsv: Sub<DXGI_FORMAT>,
samples: Sub<DXGI_SAMPLE_DESC>,
topology: Sub<D3D12_PRIMITIVE_TOPOLOGY_TYPE>,
}
let mut stream = Stream {
root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()),
@@ -595,6 +767,10 @@ fn mesh_pipeline(
targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets),
dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format),
samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples),
topology: Sub(
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
),
};
let desc = D3D12_PIPELINE_STATE_STREAM_DESC {
SizeInBytes: size_of::<Stream>(),
@@ -665,3 +841,84 @@ fn root_signature(
Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec()))
}
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use super::*;
/// A triangle mesh shader of our own and a pixel shader for it.
const MS: &str = "struct V { float4 p : SV_Position; };
[outputtopology(\"triangle\")] [numthreads(1, 1, 1)]
void main(out vertices V v[3], out indices uint3 t[1]) {
SetMeshOutputCounts(3, 1);
v[0].p = float4(0, 0, 0, 1);
v[1].p = float4(1, 0, 0, 1);
v[2].p = float4(0, 1, 0, 1);
t[0] = uint3(0, 1, 2);
}";
const PS: &str = "float4 main() : SV_Target { return 1; }";
/// The PC `dxc.exe` (`VICTORY_PC_DXC`, else the newest Windows SDK's).
fn dxc() -> Option<PathBuf> {
let dxc = match std::env::var_os("VICTORY_PC_DXC") {
Some(p) => PathBuf::from(p),
None => victory_shader::emit::validator::Validator::default_path()?
.with_file_name("dxc.exe"),
};
dxc.exists().then_some(dxc)
}
fn compile(dxc: &Path, dir: &Path, src: &str, profile: &str) -> Vec<u8> {
let (hlsl, out) = (
dir.join(format!("{profile}.hlsl")),
dir.join(format!("{profile}.dxil")),
);
std::fs::write(&hlsl, src).unwrap();
let status = std::process::Command::new(dxc)
.args(["-nologo", "-T", profile, "-E", "main", "-Fo"])
.arg(&out)
.arg(&hlsl)
.status()
.unwrap();
assert!(status.success(), "dxc failed for {profile}");
std::fs::read(out).unwrap()
}
fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE {
D3D12_SHADER_BYTECODE {
pShaderBytecode: bytes.as_ptr().cast(),
BytecodeLength: bytes.len(),
}
}
/// A mesh pipeline made once is loaded from the library the next time,
/// not compiled again (a stream without a topology never loads).
#[test]
fn a_mesh_pipeline_loads_from_the_library() {
let Some(host) = host() else {
return; // no host GPU here
};
let Some(dxc) = dxc() else {
eprintln!("no PC dxc.exe; skipped");
return;
};
let dir = tempfile::tempdir().unwrap();
let ms = compile(&dxc, dir.path(), MS, "ms_6_5");
let ps = compile(&dxc, dir.path(), PS, "ps_6_5");
let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap();
let mut g = GraphicsState::default();
g.targets.NumRenderTargets = 1;
g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe());
mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &name).expect("made");
let loaded = super::super::library::LOADED.load(Ordering::Relaxed);
mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &name).expect("made again");
assert!(
super::super::library::LOADED.load(Ordering::Relaxed) > loaded,
"the mesh pipeline was compiled again instead of loaded from the library"
);
}
}
+632 -48
View File
@@ -12,13 +12,45 @@
//! graphics state); the next run hands those to the workers at
//! creation, during loading.
//!
//! All library calls are serialised: the interface does not promise that
//! stores, loads and serialising may overlap.
//! Library calls overlap: the host documents the library as safe to use
//! from several threads ("The pipeline library is thread-safe to use, and
//! will internally synchronize as necessary", `CreatePipelineLibrary`,
//! Thread Safety), with one exception kept here: two loads of the same
//! pipeline are made one after the other ([`same_name`]). Under one lock of
//! ours for every call, the eight workers made pipelines one at a time:
//! 87 to 96 of 110 looks at each worker found it waiting for that lock
//! (run 49), and an earlier run's 2,300 pipelines, all in the library, were
//! still being loaded 46 s into the opening cutscene.
//! `VICTORY_LIBRARY_LOCK=1`: one call at a time, as before.
//!
//! The library's file is mapped, not read into memory ([`Blob`]): the host
//! keeps pointing into the bytes it was made from for as long as it lives,
//! and read into a buffer they were 1,352 MB of the process's own memory
//! for the whole run (run 60), all of it in physical memory. Mapped, the
//! pages are the file's: only those the host reads are in memory, and the
//! system can drop them without writing them anywhere. A save writes the
//! new library through a mapping of the new file in the same way (a buffer
//! of the library's size was made, filled and written out at each save).
//! `VICTORY_LIBRARY_MAP=0`: read and written through buffers, as before.
//!
//! The mapped file's handle stays open for as long as the mapping lives
//! ([`holds`]). A save renames the new library over the file this run has
//! mapped, and with the handle closed Windows then gives up the old file's
//! contents: every page of the mapping that is not in memory at that
//! moment, or leaves memory later (the trim below, or Windows taking pages
//! back), reads as zeros from then on. The host's library reads such pages
//! as stored pipelines; the driver, handed a pipeline of zeros, removes the
//! device with DXGI_ERROR_DRIVER_INTERNAL_ERROR (runs 72, 73 and 82, each
//! within 5 ms of the first library call after a save and a trim; and the
//! library run 77 saved from such pages was refused by run 78). Measured
//! with a 64 MB file written past the system's cache, mapped and replaced:
//! 16,352 of 16,384 pages read zeros with the handle closed, none with it
//! open (the test below). `VICTORY_LIBRARY_HANDLE=0`: closed, as before.
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::sync::{Mutex, MutexGuard, OnceLock, RwLock};
use windows::Win32::Graphics::Direct3D12::*;
use windows::core::{HSTRING, Interface, PCWSTR};
@@ -35,64 +67,430 @@ pub fn use_pipeline_cache(dir: PathBuf) {
pub(crate) static MADE: AtomicU64 = AtomicU64::new(0);
pub(crate) static LOADED: AtomicU64 = AtomicU64::new(0);
pub(crate) static EARLY: AtomicU64 = AtomicU64::new(0);
/// For the memory lines: the bytes of the library's file, kept in memory
/// while the library lives, and the bytes the last save wrote (a buffer of
/// that size is made, filled and written every time pipelines were added,
/// at most every 20 s).
pub(crate) static BLOB: AtomicU64 = AtomicU64::new(0);
pub(crate) static SAVED: AtomicU64 = AtomicU64::new(0);
/// Whether the library's file is mapped ([`Blob`]) and saved through a
/// mapping. On by default; `VICTORY_LIBRARY_MAP=0` uses buffers, as before.
fn mapped() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_MAP").is_none_or(|v| v != "0"))
}
/// Whether the mapped library file's handle is kept open while it is
/// mapped (see the module's notes: without it a save in the same run turns
/// the mapping's pages into zeros as they leave memory). On by default;
/// `VICTORY_LIBRARY_HANDLE=0` closes it after mapping, as before.
fn holds() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_HANDLE").is_none_or(|v| v != "0"))
}
/// A whole file mapped into memory: read-only (the library's file) or
/// writable (the file a save fills). Unmapped when dropped.
struct Mapped {
at: windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS,
len: usize,
/// The file, for a mapping made by [`Mapped::open`] ([`holds`]): open
/// until after the view is unmapped, so that the file a rename took
/// the name from keeps its contents for the view.
_file: Option<std::fs::File>,
}
impl Mapped {
/// Maps `file` (`len` bytes, not zero) for reading, or for reading and
/// writing.
fn map(file: &std::fs::File, len: usize, write: bool) -> Option<Mapped> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MapViewOfFile, PAGE_READONLY, PAGE_READWRITE,
};
if len == 0 {
return None;
}
// SAFETY: a file we hold open; the view keeps the file's pages
// after the mapping object and the file are closed.
let at = unsafe {
let mapping = CreateFileMappingW(
file.as_raw_handle(),
std::ptr::null(),
if write { PAGE_READWRITE } else { PAGE_READONLY },
0,
0,
std::ptr::null(),
);
if mapping.is_null() {
return None;
}
let at = MapViewOfFile(mapping, if write { FILE_MAP_WRITE } else { FILE_MAP_READ }, 0, 0, 0);
CloseHandle(mapping);
at
};
(!at.Value.is_null()).then_some(Mapped { at, len, _file: None })
}
/// The file at `path`, mapped for reading; `None` if it is not there,
/// is empty or cannot be mapped.
fn open(path: &std::path::Path) -> Option<Mapped> {
Mapped::open_holding(path, holds())
}
/// As [`Mapped::open`]; `hold` says whether the file stays open with
/// the mapping.
fn open_holding(path: &std::path::Path, hold: bool) -> Option<Mapped> {
// Opened as the standard library opens a file to read: others may
// read, write, rename and delete it meanwhile, so a save still
// renames the new library over this one.
let file = std::fs::File::open(path).ok()?;
let len = usize::try_from(file.metadata().ok()?.len()).ok()?;
let mut mapped = Mapped::map(&file, len, false)?;
if hold {
mapped._file = Some(file);
}
Some(mapped)
}
/// A new file of `len` bytes at `path` (replacing what is there),
/// mapped for writing.
fn create(path: &std::path::Path, len: usize) -> Option<Mapped> {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(path)
.ok()?;
file.set_len(len as u64).ok()?;
Mapped::map(&file, len, true)
}
fn bytes(&self) -> &[u8] {
// SAFETY: the view holds `len` readable bytes until dropped.
unsafe { std::slice::from_raw_parts(self.at.Value.cast(), self.len) }
}
/// Only for a view made by [`Mapped::create`].
fn bytes_mut(&mut self) -> &mut [u8] {
// SAFETY: a writable view of `len` bytes, ours alone.
unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) }
}
}
impl Drop for Mapped {
fn drop(&mut self) {
// SAFETY: our view.
unsafe { windows_sys::Win32::System::Memory::UnmapViewOfFile(self.at) };
}
}
/// The bytes a library is made from: the host reads them for as long as
/// the library lives, so they are kept beside it.
enum Blob {
/// No file (an empty library).
None,
/// The file read into memory (`VICTORY_LIBRARY_MAP=0`, tests, or a file
/// that could not be mapped).
Held(Vec<u8>),
/// The file itself, mapped.
Mapped(Mapped),
}
impl Blob {
/// The library file in `dir`: a library a save left beside it
/// ([`NEXT_FILE`]) takes its place first.
fn of(dir: &std::path::Path) -> Blob {
let path = dir.join(LIBRARY_FILE);
let next = dir.join(NEXT_FILE);
if next.exists() && std::fs::rename(&next, &path).is_err() {
tracing::warn!("the host pipeline library saved last could not take the old one's place");
}
if mapped()
&& let Some(file) = Mapped::open(&path)
{
return Blob::Mapped(file);
}
match std::fs::read(&path) {
Ok(bytes) if !bytes.is_empty() => Blob::Held(bytes),
_ => Blob::None,
}
}
fn bytes(&self) -> &[u8] {
match self {
Blob::None => &[],
Blob::Held(bytes) => bytes,
Blob::Mapped(file) => file.bytes(),
}
}
}
/// The mapped library file's view (address, bytes; 0: not mapped), when a
/// pipeline was last loaded from the library (`crate::host::now_ms`), and
/// whether the view's pages were let go since ([`trim`]).
static VIEW: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
static LOADED_AT: AtomicU64 = AtomicU64::new(0);
static TRIMMED: AtomicBool = AtomicBool::new(false);
/// The bytes of the view let go so far, for the memory line.
pub(crate) static TRIMMED_BYTES: AtomicU64 = AtomicU64::new(0);
/// When the view's pages were last let go (`crate::host::now_ms`), and how
/// often and when a save of this run last renamed a new library over the
/// mapped file: for [`removal_note`].
static TRIMMED_AT: AtomicU64 = AtomicU64::new(0);
static REPLACED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
/// The library calls running now: thread, what (load, make, store,
/// serialise), the pipeline, and since when (`crate::host::now_us`).
static CALLS: Mutex<Vec<(u32, &'static str, String, u64)>> = Mutex::new(Vec::new());
thread_local! {
/// The pipeline this thread is making (its shaders), for [`CALLS`].
static LABEL: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) };
}
/// Names the pipeline this thread makes next.
pub(crate) fn label(text: String) {
LABEL.with(|l| *l.borrow_mut() = text);
}
/// A library call of this thread, listed in [`CALLS`] until dropped.
struct Call(u32, u64);
fn call(what: &'static str, name: &str) -> Call {
let (thread, since) = (crate::host::thread_id(), crate::host::now_us());
let label = LABEL.with(|l| l.borrow().clone());
CALLS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((thread, what, format!("{name} {label}"), since));
Call(thread, since)
}
impl Drop for Call {
fn drop(&mut self) {
CALLS
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|c| (c.0, c.3) != (self.0, self.1));
}
}
/// For the report when the host device is removed: the library calls
/// running at that moment, whether this run replaced the mapped file and
/// let its pages go, and how many pages of the mapping read as zeros now.
/// A library holds no page of zeros (the 259 MB one of run 83 has no run of
/// 2,048 zero bytes): each such page is one whose contents were lost (see
/// the module's notes), and a pipeline stored there is what the driver was
/// handed.
pub(crate) fn removal_note() -> String {
use std::fmt::Write;
let now = crate::host::now_us();
let mut text = String::from("pipeline library: ");
{
let calls = CALLS.lock().unwrap_or_else(|e| e.into_inner());
if calls.is_empty() {
text.push_str("no call running");
}
for (i, (thread, what, name, since)) in calls.iter().enumerate() {
let _ = write!(
text,
"{}{what} of {name} running for {:.1} ms on thread {thread}",
if i == 0 { "" } else { ", " },
now.saturating_sub(*since) as f64 / 1000.0
);
}
}
let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed));
if at == 0 {
text.push_str("; its file is not mapped");
return text;
}
let ago = |ms: u64| crate::host::now_ms().saturating_sub(ms) as f64 / 1000.0;
let _ = write!(
text,
"; its file is mapped ({len} bytes), the handle {}",
if holds() { "kept open" } else { "closed (VICTORY_LIBRARY_HANDLE=0)" }
);
match REPLACED[0].load(Ordering::Relaxed) {
0 => text.push_str("; this run has not replaced the file"),
n => {
let _ = write!(
text,
"; this run replaced the file under the mapping {n} times, last {:.1} s ago",
ago(REPLACED[1].load(Ordering::Relaxed))
);
}
}
if TRIMMED_BYTES.load(Ordering::Relaxed) > 0 {
let _ = write!(text, "; its pages were last let go {:.1} s ago", ago(TRIMMED_AT.load(Ordering::Relaxed)));
}
// Within two seconds: pages not in memory come from the disk.
let started = std::time::Instant::now();
// SAFETY: the view lives as long as the library, which is never dropped.
let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, len) };
let (mut zero, mut looked, mut first) = (0u64, 0u64, None);
for (n, page) in bytes.chunks(4096).enumerate() {
if n % 4096 == 0 && started.elapsed() > std::time::Duration::from_secs(2) {
break;
}
looked += 1;
if page.iter().all(|&b| b == 0) {
zero += 1;
if first.is_none() {
first = Some(n);
}
}
}
let _ = write!(text, "; {zero} of the {looked} pages looked at read as zeros now");
if let Some(first) = first {
let _ = write!(text, " (the first is page {first}): the library's contents were lost there");
}
text
}
/// Lets the mapped library file's pages go from the process's memory once
/// no pipeline has been loaded for ten seconds. The host reads nearly the
/// whole file while the early pipelines load (run 65: all 1,490 MB of it
/// were in the process's memory a minute in, and 1,300 MB still at the
/// end, on a PC with 2 GB free); after that it reads the file again only
/// when a new pipeline loads. Pages let go stay in Windows' file cache
/// while nothing else wants the memory, and come back on the next read.
/// Called once a second by the sweep; does its work on a thread of its own
/// (hundreds of thousands of pages), once after each burst of loads.
/// `VICTORY_LIBRARY_TRIM=0`: the pages stay until Windows takes them.
pub(crate) fn trim() {
const QUIET_MS: u64 = 10_000;
static ON: OnceLock<bool> = OnceLock::new();
let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed));
if at == 0
|| TRIMMED.load(Ordering::Relaxed)
|| crate::host::now_ms() < LOADED_AT.load(Ordering::Relaxed) + QUIET_MS
|| !*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_TRIM").is_none_or(|v| v != "0"))
|| TRIMMED.swap(true, Ordering::Relaxed)
{
return;
}
let work = move || {
// SAFETY: the view lives as long as the library, which is never
// dropped. Unlocking pages that are not locked fails, as expected,
// and takes them out of the working set: the documented way to let
// pages of a mapped file go.
unsafe { windows_sys::Win32::System::Memory::VirtualUnlock(at as *const _, len) };
TRIMMED_BYTES.fetch_add(len as u64, Ordering::Relaxed);
TRIMMED_AT.store(crate::host::now_ms(), Ordering::Relaxed);
crate::host::trail(|| format!("pipeline library: the mapped file's pages let go from memory ({len} bytes)"));
};
if std::thread::Builder::new().name("victory-library-trim".into()).spawn(work).is_err() {
TRIMMED.store(false, Ordering::Relaxed);
}
}
struct Library {
library: ID3D12PipelineLibrary1,
/// The blob the library was made from: it must outlive the library.
_blob: Vec<u8>,
_blob: Blob,
/// Pipelines stored since the last save.
added: u64,
added: AtomicU64,
/// Stores share it and a save takes it alone: the size the library
/// asks for must still be its size when it is written out.
saving: RwLock<()>,
}
// SAFETY: D3D12 objects are free-threaded; every call is made under the
// mutex that holds the library.
// SAFETY: D3D12 objects are free-threaded, and the library synchronises
// its own calls (see the module's notes); what it does not, two loads of
// one name, is serialised by `same_name`.
unsafe impl Send for Library {}
// SAFETY: as above; the other fields are an atomic and a lock.
unsafe impl Sync for Library {}
/// Held by a load of the pipeline named `name`: loads of the same name
/// wait for each other (the host's one exception to the library's thread
/// safety: such a load may change that pipeline's entry). Names share 64
/// locks, so two different names seldom wait.
fn same_name(name: &str) -> MutexGuard<'static, ()> {
static LOADING: [Mutex<()>; 64] = [const { Mutex::new(()) }; 64];
let at = name.bytes().fold(0usize, |h, b| h.wrapping_mul(31).wrapping_add(usize::from(b)));
LOADING[at % LOADING.len()].lock().unwrap_or_else(|e| e.into_inner())
}
/// With `VICTORY_LIBRARY_LOCK=1`: held by every library call, as before.
fn one_call() -> Option<MutexGuard<'static, ()>> {
static ON: OnceLock<bool> = OnceLock::new();
static CALLING: Mutex<()> = Mutex::new(());
ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_LOCK").is_some_and(|v| v == "1"))
.then(|| CALLING.lock().unwrap_or_else(|e| e.into_inner()))
}
const LIBRARY_FILE: &str = "host-pipelines.bin";
/// A saved library that could not replace [`LIBRARY_FILE`] while this run
/// had it mapped (a system that refuses to replace a mapped file): the next
/// start renames it over the library first ([`Blob::of`]).
const NEXT_FILE: &str = "host-pipelines.next";
const EARLY_FILE: &str = "early-pipelines.txt";
/// Title pipelines listed for an early start, at most.
const EARLY_MAX: usize = 8192;
fn library() -> Option<&'static Mutex<Library>> {
static LIBRARY: OnceLock<Option<Mutex<Library>>> = OnceLock::new();
fn library() -> Option<&'static Library> {
static LIBRARY: OnceLock<Option<Library>> = OnceLock::new();
LIBRARY
.get_or_init(|| {
let device = crate::host::host()?.device.cast::<ID3D12Device1>().ok()?;
let blob = DIR
.get()
.and_then(|d| std::fs::read(d.join(LIBRARY_FILE)).ok())
.unwrap_or_default();
let blob = DIR.get().map_or(Blob::None, |d| Blob::of(d));
let library = open(&device, blob);
if library.is_none() {
tracing::warn!("no host pipeline library: pipelines are not kept");
}
library.map(Mutex::new)
library
})
.as_ref()
}
/// The library in `blob`, or an empty one if the host rejects the blob (an
/// adapter or driver change, damage).
fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> {
fn open(device: &ID3D12Device1, blob: Blob) -> Option<Library> {
let make = |bytes: &[u8]| -> windows::core::Result<ID3D12PipelineLibrary1> {
// SAFETY: the bytes outlive the library (kept beside it).
unsafe {
device.CreatePipelineLibrary::<ID3D12PipelineLibrary>(bytes)?.cast()
}
};
if !blob.is_empty() {
match make(&blob) {
if !blob.bytes().is_empty() {
match make(blob.bytes()) {
Ok(library) => {
tracing::info!(bytes = blob.len(), "host pipeline library loaded");
return Some(Library { library, _blob: blob, added: 0 });
let bytes = blob.bytes().len();
BLOB.store(bytes as u64, Ordering::Relaxed);
tracing::info!(bytes, mapped = matches!(blob, Blob::Mapped(_)), "host pipeline library loaded");
if let Blob::Mapped(file) = &blob {
VIEW[1].store(file.len, Ordering::Relaxed);
VIEW[0].store(file.at.Value as usize, Ordering::Relaxed);
LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed);
}
return Some(Library {
library,
_blob: blob,
added: AtomicU64::new(0),
saving: RwLock::new(()),
});
}
Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"),
}
} else {
tracing::info!("no host pipeline library yet; starting an empty one");
}
// The rejected bytes are let go (a mapped file is unmapped) before the
// empty library is made: nothing reads them any more.
drop(blob);
let library = make(&[]).ok()?;
Some(Library { library, _blob: Vec::new(), added: 0 })
Some(Library {
library,
_blob: Blob::None,
added: AtomicU64::new(0),
saving: RwLock::new(()),
})
}
/// A pipeline's name in the library: the hash of what its host
@@ -118,18 +516,47 @@ pub(crate) fn pipeline(
MADE.fetch_add(1, Ordering::Relaxed);
return create();
};
if let Ok(pso) = load(&library.lock().unwrap_or_else(|e| e.into_inner()).library, PCWSTR(wide.as_ptr())) {
LOADED.fetch_add(1, Ordering::Relaxed);
return Ok(pso);
}
// Compiled outside the lock: compiles take up to seconds.
let pso = create()?;
let began = std::time::Instant::now();
let loaded = {
let _all = one_call();
let _one = same_name(name);
let _call = call("load", name);
load(&library.library, PCWSTR(wide.as_ptr()))
};
// The load read the library's file (see `trim`).
LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed);
TRIMMED.store(false, Ordering::Relaxed);
let refused = match loaded {
Ok(pso) => {
LOADED.fetch_add(1, Ordering::Relaxed);
crate::host::trail(|| {
let label = LABEL.with(|l| l.borrow().clone());
format!("pipeline library: loaded {label} in {:.1} ms", began.elapsed().as_secs_f64() * 1e3)
});
return Ok(pso);
}
Err(e) => e,
};
// Compiled outside any lock: compiles take up to seconds.
let pso = {
let _call = call("make", name);
create()?
};
MADE.fetch_add(1, Ordering::Relaxed);
let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
crate::host::trail(|| {
let label = LABEL.with(|l| l.borrow().clone());
format!(
"pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})",
began.elapsed().as_secs_f64() * 1e3
)
});
let _all = one_call();
let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner());
let _call = call("store", name);
// SAFETY: a live pipeline; a name already stored (a description that
// differs) is refused, which leaves the library as it was.
if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() {
l.added += 1;
if unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() {
library.added.fetch_add(1, Ordering::Relaxed);
}
Ok(pso)
}
@@ -147,34 +574,60 @@ pub(crate) fn save(now: bool) {
}
*last = Some(std::time::Instant::now());
}
let blob = {
let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
if l.added == 0 && !USED_CHANGED.swap(false, Ordering::Relaxed) {
if let Err(e) = std::fs::create_dir_all(dir) {
tracing::warn!(error = %e, "host pipeline library not saved");
return;
}
let tmp = dir.join(LIBRARY_FILE).with_extension("tmp");
// The bytes of the library written to `tmp`; 0 when no pipeline was
// added: the library on disk is then what it was, and only the early
// list is written (a title pipeline first drawn with wrote all 1,352 MB
// of the library again: run 60's second save).
let bytes = {
let _all = one_call();
// No store between asking the size and writing; loads go on.
let _alone = library.saving.write().unwrap_or_else(|e| e.into_inner());
let added = library.added.load(Ordering::Relaxed);
if !USED_CHANGED.swap(false, Ordering::Relaxed) && added == 0 {
return;
}
// SAFETY: a buffer of the size the library asks for.
let bytes = unsafe {
let mut bytes = vec![0u8; l.library.GetSerializedSize()];
l.library.Serialize(&mut bytes).map(|()| bytes)
};
match bytes {
Ok(bytes) => {
l.added = 0;
bytes
}
Err(e) => {
if added == 0 {
0
} else {
// SAFETY: a plain query.
let size = unsafe { library.library.GetSerializedSize() };
let _call = call("serialise", "the whole library");
if let Err(e) = serialise(&library.library, &tmp, size) {
tracing::warn!(error = %e, "host pipeline library not serialised");
let _ = std::fs::remove_file(&tmp);
return;
}
library.added.store(0, Ordering::Relaxed);
SAVED.store(size as u64, Ordering::Relaxed);
size
}
};
let used: Vec<String> = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect();
let written = std::fs::create_dir_all(dir)
.and_then(|()| write_atomically(&dir.join(LIBRARY_FILE), &blob))
let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) };
if bytes > 0 && library_written.is_ok() {
// In place unless the system refused and the new one waits beside it.
let in_place = !dir.join(NEXT_FILE).exists();
if in_place && VIEW[0].load(Ordering::Relaxed) != 0 {
REPLACED[1].store(crate::host::now_ms(), Ordering::Relaxed);
REPLACED[0].fetch_add(1, Ordering::Relaxed);
}
crate::host::trail(|| {
format!(
"pipeline library: saved {bytes} bytes, {}",
if in_place { "renamed over the library's file" } else { "left beside the library's file for the next start" }
)
});
}
let written = library_written
.and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes()));
match written {
Ok(()) => tracing::info!(
bytes = blob.len(),
bytes,
early = used.len(),
made = MADE.load(Ordering::Relaxed),
loaded = LOADED.load(Ordering::Relaxed),
@@ -185,6 +638,35 @@ pub(crate) fn save(now: bool) {
}
}
/// Writes the library's `size` serialised bytes to the file `tmp`: through
/// a mapping of that file, so that the bytes are the file's pages and not
/// 1.3 GB more of the process's own memory for the seconds a save takes;
/// through a buffer where the file cannot be mapped (and with
/// `VICTORY_LIBRARY_MAP=0`).
fn serialise(library: &ID3D12PipelineLibrary1, tmp: &std::path::Path, size: usize) -> std::io::Result<()> {
let failed = |e: windows::core::Error| std::io::Error::other(e.to_string());
if mapped()
&& let Some(mut file) = Mapped::create(tmp, size)
{
// SAFETY: a buffer of the size the library asks for.
return unsafe { library.Serialize(file.bytes_mut()) }.map_err(failed);
}
let mut bytes = vec![0u8; size];
// SAFETY: a buffer of the size the library asks for.
unsafe { library.Serialize(&mut bytes) }.map_err(failed)?;
std::fs::write(tmp, &bytes)
}
/// Renames the written library `tmp` over the library's file in `dir`. This
/// run may have that file mapped: Windows 11 replaces a mapped file, and
/// the mapping goes on reading the old one for as long as a handle on it
/// is open ([`holds`]; with none, only the pages in memory at that moment
/// stay: the rest read as zeros). Where a system refuses, the new library
/// is left beside it as [`NEXT_FILE`] for the next start.
fn replace_library(dir: &std::path::Path, tmp: &std::path::Path) -> std::io::Result<()> {
std::fs::rename(tmp, dir.join(LIBRARY_FILE)).or_else(|_| std::fs::rename(tmp, dir.join(NEXT_FILE)))
}
/// Writes `bytes` to a temporary file beside `path`, then renames it over
/// `path`: a reader never sees a part.
fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
@@ -246,9 +728,111 @@ mod tests {
let Some(device) = crate::host::host().and_then(|h| h.device.cast::<ID3D12Device1>().ok()) else {
return; // no host GPU here
};
let library = open(&device, b"not a pipeline library".repeat(16)).expect("an empty library");
let library = open(&device, Blob::Held(b"not a pipeline library".repeat(16))).expect("an empty library");
// SAFETY: a plain query on a live library.
assert!(unsafe { library.library.GetSerializedSize() } > 0);
assert!(library._blob.is_empty());
assert!(matches!(library._blob, Blob::None));
}
/// A mapped file reads as the file's bytes, a file written through a
/// mapping holds what was written, and the library's file can be
/// replaced while it is mapped (or the new one waits as the next).
#[test]
fn the_library_file_is_mapped_and_replaced() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(LIBRARY_FILE);
assert!(matches!(Blob::of(dir.path()), Blob::None), "no file yet");
std::fs::write(&path, b"").unwrap();
assert!(matches!(Blob::of(dir.path()), Blob::None), "an empty file");
let old: Vec<u8> = (0..200_000u32).map(|i| i as u8).collect();
std::fs::write(&path, &old).unwrap();
let blob = Blob::of(dir.path());
assert!(matches!(blob, Blob::Mapped(_)) || !mapped());
assert_eq!(blob.bytes(), &old[..]);
// A save while the old file is mapped.
let tmp = path.with_extension("tmp");
let new: Vec<u8> = (0..300_000u32).map(|i| (i * 7) as u8).collect();
{
let mut file = Mapped::create(&tmp, new.len()).expect("a new file, mapped");
file.bytes_mut().copy_from_slice(&new);
}
assert_eq!(std::fs::read(&tmp).unwrap(), new);
replace_library(dir.path(), &tmp).unwrap();
assert!(!tmp.exists());
// The mapping still reads the old library.
assert_eq!(blob.bytes(), &old[..]);
drop(blob);
// The next start reads the new one, wherever the save left it.
assert_eq!(Blob::of(dir.path()).bytes(), &new[..]);
assert!(!dir.path().join(NEXT_FILE).exists());
}
/// The bytes at `at` of the pattern the test below writes.
fn pattern(at: usize, out: &mut [u8]) {
for (i, word) in out.chunks_exact_mut(4).enumerate() {
let v = ((at / 4 + i) as u32).wrapping_mul(2_654_435_761).wrapping_add(1);
word.copy_from_slice(&v.to_le_bytes());
}
}
/// A file of `len` bytes (whole MiB) of [`pattern`], written past the
/// system's cache: none of its pages is in memory afterwards. False
/// where the folder's file system does not take such writes.
fn write_uncached(path: &std::path::Path, len: usize) -> bool {
use std::io::Write;
use std::os::windows::fs::OpenOptionsExt;
// FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH
const UNCACHED: u32 = 0x2000_0000 | 0x8000_0000;
const CHUNK: usize = 1 << 20;
let Ok(mut file) = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.custom_flags(UNCACHED)
.open(path)
else {
return false;
};
// Such writes want a buffer on a sector boundary.
let mut store = vec![0u8; CHUNK + 4096];
let start = store.as_ptr().align_offset(4096);
for at in (0..len).step_by(CHUNK) {
let chunk = &mut store[start..start + CHUNK];
pattern(at, chunk);
if file.write_all(chunk).is_err() {
return false;
}
}
true
}
/// The device loss of runs 72, 73 and 82: the library's file is
/// replaced while it is mapped, and pages of the mapping that were not
/// in memory then are read afterwards (in the runs: pages the trim let
/// go and Windows gave to something else). With the file's handle kept
/// open they still read as the old file. (With it closed, as before,
/// all but the first few read as zeros on the PC this was found on.)
#[test]
fn a_replaced_library_file_still_reads_from_the_disk() {
const LEN: usize = 8 << 20;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(LIBRARY_FILE);
if !write_uncached(&path, LEN) {
return; // no uncached writes here: nothing to show
}
let mapped = Mapped::open_holding(&path, true).expect("the file, mapped");
// A save: the new library, renamed over the mapped one.
let tmp = path.with_extension("tmp");
{
let mut file = Mapped::create(&tmp, LEN).expect("a new file, mapped");
file.bytes_mut().fill(0xEE);
}
replace_library(dir.path(), &tmp).unwrap();
// Every page of the old mapping, read for the first time now.
let mut expected = vec![0u8; 4096];
for (page, bytes) in mapped.bytes().chunks(4096).enumerate() {
pattern(page * 4096, &mut expected);
assert!(bytes == &expected[..], "page {page} of the replaced library no longer reads as the old file");
}
}
}
+175 -38
View File
@@ -16,7 +16,8 @@
//! guess; a pass the title runs only once and whose pipeline takes longer
//! is lost.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
@@ -27,7 +28,7 @@ use super::host::{GraphicsState, HostPipeline};
pub(crate) struct Pending {
shaders: Vec<Arc<Shader>>,
pub(crate) graphics: Option<Box<GraphicsState>>,
queued: AtomicBool,
queue_state: AtomicU8,
made: OnceLock<Option<HostPipeline>>,
/// What identifies it across runs (shader containers and state), and
/// whether a draw has used it yet.
@@ -52,7 +53,7 @@ impl Pending {
Pending {
shaders,
graphics,
queued: AtomicBool::new(false),
queue_state: AtomicU8::new(NOT_QUEUED),
made: OnceLock::new(),
key: key.finalize().to_hex()[..32].to_owned(),
used: AtomicBool::new(false),
@@ -109,22 +110,25 @@ pub(crate) fn waiting() -> u64 {
/// queues it on first use.
pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
if p.made.get().is_none() {
start(p);
start(p, REQUESTED);
wait(p, crate::frame::current());
}
let made = p.made.get()?.as_ref();
if made.is_some() && !p.used.swap(true, Ordering::Relaxed) {
// Also one that could not be made (a shader that does not translate):
// the next run then finds that out while loading, like the others,
// instead of in the world's frames, where each first use of such a
// pipeline waits on the frame's budget for nothing.
if !p.used.swap(true, Ordering::Relaxed) {
super::library::note_used(&p.key);
}
made
}
/// Queues `p` for the workers, once.
fn start(p: &Arc<Pending>) {
if !p.queued.swap(true, Ordering::Relaxed) {
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
queue(p.clone());
}
/// Makes `p` on this thread if it is not made yet (waiting for a worker
/// that is making it); whether it has a host pipeline.
pub(crate) fn now(p: &Arc<Pending>) -> bool {
p.make();
p.made.get().is_some_and(|made| made.is_some())
}
/// At the title's creation of a pipeline: starts it at once if an earlier
@@ -132,18 +136,43 @@ fn start(p: &Arc<Pending>) {
pub(crate) fn early(p: &Arc<Pending>) {
if !p.shaders.is_empty() && super::library::wanted_early(&p.key) {
super::library::EARLY.fetch_add(1, Ordering::Relaxed);
start(p);
start(p, EARLY);
}
}
/// Whether the frame's budget is one for all threads together: a thread
/// that waits takes what is left of it and gives back what it did not
/// use. Counted only when a wait had ended, the budget was one per thread:
/// each of the title's five recording threads began its first wait of a
/// frame with nothing counted yet and waited the whole half second, 2.5 s
/// of waiting in every frame in which pipelines were being made (runs
/// 34-49: "2504 ms waiting for pipelines" in each such frame).
/// On by default; `VICTORY_PIPELINE_WAIT_SHARED=0` counts as before.
fn shared_budget() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0"))
}
/// Waits for `p` while frame `frame` has budget left.
fn wait(p: &Pending, frame: u64) {
static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
static WAITED_US: AtomicU64 = AtomicU64::new(0);
if FRAME.swap(frame, Ordering::Relaxed) != frame {
WAITED_US.store(0, Ordering::Relaxed);
// The frame the budget belongs to, and what was waited of it (or is
// taken by a thread waiting now).
static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO));
let shared = shared_budget();
let left = {
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
if spent.0 != frame {
*spent = (frame, Duration::ZERO);
}
let left = BUDGET.saturating_sub(spent.1);
if shared {
spent.1 += left;
}
left
};
if left.is_zero() {
return;
}
let left = BUDGET.saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed)));
let started = Instant::now();
let (lock, done) = &DONE;
let mut held = lock.lock().unwrap_or_else(|e| e.into_inner());
@@ -154,22 +183,115 @@ fn wait(p: &Pending, frame: u64) {
}
held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0;
}
WAITED_US.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
drop(held);
let waited = started.elapsed().min(left);
{
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
// A frame that began meanwhile has its own budget.
if spent.0 == frame {
if shared {
spent.1 = spent.1.saturating_sub(left - waited);
} else {
spent.1 += waited;
}
}
}
#[cfg(feature = "diagnostics")]
crate::copystat::add(
crate::copystat::C::PipelineWaitUs,
started.elapsed().as_micros() as u64,
);
}
/// Hands `p` to the workers (half the logical processors, 2 to 8), started
/// on first use.
fn queue(p: Arc<Pending>) {
static SENDER: OnceLock<std::sync::mpsc::Sender<Arc<Pending>>> = OnceLock::new();
let sender = SENDER.get_or_init(|| {
let (sender, receiver) = std::sync::mpsc::channel::<Arc<Pending>>();
let receiver = Arc::new(Mutex::new(receiver));
const NOT_QUEUED: u8 = 0;
const EARLY: u8 = 1;
const REQUESTED: u8 = 2;
const MAKING: u8 = 3;
struct Queue {
early: VecDeque<Arc<Pending>>,
requested: VecDeque<Arc<Pending>>,
}
impl Queue {
const fn new() -> Self {
Self {
early: VecDeque::new(),
requested: VecDeque::new(),
}
}
/// Queues an unrequested pipeline or promotes one queued at creation.
/// Returns whether it is new to the queue, or `None` if nothing changed.
fn push(&mut self, p: &Arc<Pending>, priority: u8) -> Option<bool> {
let prev = p.queue_state.load(Ordering::Relaxed);
if prev >= priority {
return None;
}
p.queue_state.store(priority, Ordering::Relaxed);
if priority == REQUESTED {
self.requested.push_back(p.clone());
} else {
self.early.push_back(p.clone());
}
Some(prev == NOT_QUEUED)
}
fn pop(&mut self) -> Option<Arc<Pending>> {
let p = self.requested.pop_front().or_else(|| {
// An early entry can have been promoted and claimed already.
std::iter::from_fn(|| self.early.pop_front())
.find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
})?;
p.queue_state.store(MAKING, Ordering::Relaxed);
Some(p)
}
}
static QUEUE: Mutex<Queue> = Mutex::new(Queue::new());
static AVAILABLE: Condvar = Condvar::new();
/// Start or promote work for a draw without waiting behind the entire early
/// list. Queue changes and worker claims happen under the same lock.
fn start(p: &Arc<Pending>, priority: u8) {
if p.queue_state.load(Ordering::Relaxed) >= priority {
return;
}
if !workers() {
if p.queue_state.swap(MAKING, Ordering::Relaxed) == NOT_QUEUED {
p.make();
}
return;
}
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
if let Some(new) = queue.push(p, priority) {
if new {
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
}
AVAILABLE.notify_one();
}
}
fn next() -> Arc<Pending> {
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(p) = queue.pop() {
return p;
}
queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner());
}
}
/// Starts the workers (half the logical processors, 2 to 8) on first use.
fn workers() -> bool {
static RUNNING: OnceLock<bool> = OnceLock::new();
*RUNNING.get_or_init(|| {
let mut running = false;
let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8));
for i in 0..workers {
let receiver = receiver.clone();
let spawned = std::thread::Builder::new()
.name(format!("victory-pipelines-{i}"))
.spawn(move || {
.spawn(|| {
// Below the title's own threads (loading, recording).
// SAFETY: a plain call on our own thread.
unsafe {
@@ -177,9 +299,7 @@ fn queue(p: Arc<Pending>) {
let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
}
loop {
let next = receiver.lock().unwrap_or_else(|e| e.into_inner()).recv();
let Ok(p) = next else { return };
p.make();
next().make();
if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
drained();
} else {
@@ -189,15 +309,12 @@ fn queue(p: Arc<Pending>) {
});
if let Err(e) = spawned {
tracing::warn!(error = %e, "no pipeline worker");
} else {
running = true;
}
}
sender
});
if let Err(e) = sender.send(p) {
// No worker: made here instead.
e.0.make();
WAITING.fetch_sub(1, Ordering::Relaxed);
}
running
})
}
/// The most pipelines waiting at once since the workers last ran out.
@@ -228,11 +345,31 @@ mod tests {
fn first_use_is_made_by_a_worker() {
let p = Arc::new(Pending::new(Vec::new(), None));
assert!(ready(&p).is_none());
assert!(p.queued.load(Ordering::Relaxed));
assert_ne!(p.queue_state.load(Ordering::Relaxed), NOT_QUEUED);
let started = Instant::now();
while p.made.get().is_none() && started.elapsed() < Duration::from_secs(10) {
std::thread::yield_now();
}
assert!(matches!(p.made.get(), Some(None)));
}
#[test]
fn draws_promote_early_pipelines_without_claiming_them_twice() {
let earlier = Arc::new(Pending::new(Vec::new(), None));
let promoted = Arc::new(Pending::new(Vec::new(), None));
let requested = Arc::new(Pending::new(Vec::new(), None));
let mut queue = Queue::new();
assert_eq!(queue.push(&earlier, EARLY), Some(true));
assert_eq!(queue.push(&promoted, EARLY), Some(true));
assert_eq!(queue.push(&requested, REQUESTED), Some(true));
assert_eq!(queue.push(&promoted, REQUESTED), Some(false));
assert_eq!(queue.push(&promoted, REQUESTED), None);
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &requested));
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &promoted));
assert_eq!(queue.push(&promoted, REQUESTED), None);
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier));
assert!(queue.pop().is_none());
}
}
+6
View File
@@ -11,6 +11,12 @@
//! [`components`] does not know keep the first vertex's value, and so do
//! components past the end of the vertex (an element that reaches into the
//! next one, which the layout allows).
//!
//! A pipeline the title makes for rectangles completes them on the GPU
//! instead, in a geometry stage (`victory_shader::emit::rect_list_gs`):
//! from the vertex shader's outputs, whichever vertex the corner is, for
//! direct, indexed and indirect draws alike. This expansion is what is
//! left for a pipeline that could not get that stage.
/// Expands `rects` rectangles of `stride`-byte vertices from `src` into six
/// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both
+548 -9
View File
@@ -34,9 +34,403 @@ struct Queue {
object: Object,
kind: u32,
desc: QueueDesc,
/// What the queue was given after a wait for a fence that had not been
/// reached, in order; it runs when the fence gets there.
#[cfg(windows)]
held: std::sync::Mutex<Vec<Held>>,
}
const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10);
/// One thing a waiting queue holds back.
#[cfg(windows)]
enum Held {
/// The queue waits for the fence (its address) to reach the value.
Wait(usize, u64),
/// A list of the next submission waits for a memory value.
Value(crate::list::ValueWait),
/// A submission: the lists' host sides, taken from the title's lists
/// (which it may reset meanwhile), and the order they run in.
Run(Vec<crate::list::Detached>, Vec<usize>),
/// A signal of the queue's, due after what it holds before it.
Signal(usize, u64),
}
/// The queues that hold something (their addresses).
#[cfg(windows)]
static WAITING: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
#[cfg(windows)]
fn lock<T>(mutex: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(|e| e.into_inner())
}
/// Whether queues wait for fences. `VICTORY_QUEUE_WAIT=0`: they do not,
/// and every submission runs when it is made (as before).
#[cfg(windows)]
fn waits() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_WAIT").is_none_or(|v| v != "0"))
}
/// Whether a submission is held list by list: the lists before the first
/// one whose wait for a memory value is not met run at once, and each list
/// that waits is held with the lists after it, behind its own waits.
/// Holding a submission whole made the title's queues wait for each other:
/// a graphics submission was held for a value a compute list writes, and
/// that compute list for a value an earlier list of the same graphics
/// submission writes. Nothing moved until the present forced it, and the
/// title reached its present only after waiting about 2.5 s, every frame
/// (runs 27-30: 2.4-2.9 s from the last submission to the present call,
/// 13-32 ms before waits were honoured; the frame's main graphics
/// submissions, 88 lists, ran forced, the compute lists before them).
/// On by default; `VICTORY_SPLIT_WAITS=0` holds whole submissions, as
/// before.
#[cfg(windows)]
fn split() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_SPLIT_WAITS").is_none_or(|v| v != "0"))
}
/// Whether a list is cut into host lists at its waits for memory values
/// (`crate::list::cut`), and a queue runs a submission part by part: it
/// stands at each wait until the value is in memory, with everything
/// recorded before the wait run and its bottom-of-pipe writes done, as on
/// the console. Held list by list ([`split`]) a wait still held its whole
/// list: the title's lists are chains of jobs, each behind a wait for a
/// value another queue's list writes in the middle of its own chain
/// (frame 858 of run 33: a compute list of 433 commands with 13 waits;
/// graphics lists of the form "341 dispatches, wait, draws"), so two lists
/// each waited for a write behind the other's wait and only the present
/// moved them, in the wrong order.
/// On by default where waits are honoured list by list;
/// `VICTORY_CUT_WAITS=0` holds whole lists, as before.
#[cfg(windows)]
pub(crate) fn cuts() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
waits() && split() && *ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WAITS").is_none_or(|v| v != "0"))
}
/// Whether a present runs what queues still hold (on by default: a wait
/// is not kept across frames). `VICTORY_WAIT_FORCE=0` keeps it held: for
/// finding out whether the title's waits reach across its presents; a
/// wait nothing ever meets then stops the title for good.
#[cfg(windows)]
fn forces() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_FORCE").is_none_or(|v| v != "0"))
}
/// A submission to a queue whose lists are cut at their waits ([`cuts`]).
/// The lists before the first one that waits run at once if the queue
/// holds nothing; the rest goes behind what the queue holds, part by part
/// (`crate::list::detach_parts`): the waits of a part, then its host
/// lists. [`release_held`] runs the queue's line as far as the values are
/// there, now and whenever a submission has run.
#[cfg(windows)]
fn submit_cut(this: This, lists: &[This]) {
let Some(host) = crate::host::host() else {
return;
};
let first = if lock(&queue(this).held).is_empty() {
lists
.iter()
.position(|&l| crate::list::cut_list(l))
.unwrap_or(lists.len())
} else {
0
};
#[cfg(feature = "diagnostics")]
crate::capture::op(this as usize, || {
let named: Vec<String> = lists
.iter()
.map(|&l| match crate::list::host_list(l) {
Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize),
None => format!("title {l:?}"),
})
.collect();
format!(
"SUBMIT queue kind {:?} held {} lists {named:?} (the first {first} run at once, the rest part by part)",
Some(queue(this).kind),
first < lists.len()
)
});
if first > 0 && crate::host::late() {
// Sent to the card and not waited for: their host sides are taken
// from the title's lists (which it may reset before they have run)
// and come back, with their tables' slots, when they are settled.
let (taken, order) = crate::list::detach(&lists[..first]);
host.execute_late(taken, order);
} else if first > 0 {
let now: Vec<_> = lists[..first]
.iter()
.filter_map(|&l| crate::list::host_list(l))
.collect();
host.execute(&now);
// They have run: their descriptor tables' slots are free again, as
// on the path without cuts ([`execute`]). This path replaced that
// one without the call, so the lists that run at once kept their
// slots until the title's reset and the ring ran out as before
// (run 45: 3,143 of 15,942 tables refused in one frame).
crate::list::tables_done(&lists[..first]);
}
if first < lists.len() {
let parts = crate::list::detach_parts(&lists[first..]);
static SEEN: AtomicU64 = AtomicU64::new(0);
if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
tracing::info!(
kind = queue(this).kind,
lists = lists.len(),
run_at_once = first,
parts = parts.len(),
waits = parts.iter().map(|p| p.0.len()).sum::<usize>(),
"a submission is given to its queue part by part (its lists wait for memory values)"
);
}
{
let mut held = lock(&queue(this).held);
for (waits, taken, order) in parts {
held.extend(waits.into_iter().map(Held::Value));
held.push(Held::Run(taken, order));
}
}
let mut waiting = lock(&WAITING);
if !waiting.contains(&(this as usize)) {
waiting.push(this as usize);
}
}
// What ran may be what another queue waits for, and what was just
// given to the queue may be free to run already.
release_held(false);
}
/// A submission to a queue that honours waits, list by list ([`split`]).
/// shortcut: a wait still holds its whole list, not only the commands
/// after it; and lists named twice among those held stay in one piece.
#[cfg(windows)]
fn submit_split(this: This, lists: &[This]) {
let Some(host) = crate::host::host() else {
return;
};
let by = crate::list::waits_by_list(lists);
// Behind what the queue already holds, nothing runs now.
let cut = if lock(&queue(this).held).is_empty() {
(0..lists.len())
.find(|&i| by[i].iter().any(|w| !w.met()))
.unwrap_or(lists.len())
} else {
0
};
#[cfg(feature = "diagnostics")]
crate::capture::op(this as usize, || {
let named: Vec<String> = lists
.iter()
.map(|&l| match crate::list::host_list(l) {
Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize),
None => format!("title {l:?}"),
})
.collect();
format!(
"SUBMIT queue kind {:?} held {} lists {named:?} (the first {cut} run at once)",
Some(queue(this).kind),
cut < lists.len()
)
});
if cut > 0 {
let now: Vec<_> = lists[..cut]
.iter()
.filter_map(|&l| crate::list::host_list(l))
.collect();
host.execute(&now);
}
if cut < lists.len() {
static SEEN: AtomicU64 = AtomicU64::new(0);
if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
tracing::info!(
kind = queue(this).kind,
lists = lists.len(),
run_at_once = cut,
waits = ?by[cut],
"lists of a submission are held for a memory value"
);
}
let rest = &lists[cut..];
// A list's host side can be taken once.
let twice = rest.iter().enumerate().any(|(i, l)| rest[..i].contains(l));
let mut pieces: Vec<Held> = Vec::new();
let mut from = cut;
while from < lists.len() {
// Up to the next list that waits for anything (met or not: it
// is looked at again when its turn comes).
let to = if twice {
lists.len()
} else {
(from + 1..lists.len())
.find(|&i| !by[i].is_empty())
.unwrap_or(lists.len())
};
let waits: Vec<crate::list::ValueWait> = by[from..to].concat();
pieces.extend(waits.into_iter().map(Held::Value));
let (taken, order) = crate::list::detach(&lists[from..to]);
pieces.push(Held::Run(taken, order));
from = to;
}
lock(&queue(this).held).extend(pieces);
let mut waiting = lock(&WAITING);
if !waiting.contains(&(this as usize)) {
waiting.push(this as usize);
}
}
// What ran may be what another queue waits for, and what was just held
// may be free to run already.
release_held(false);
}
/// Adds `what()` to what the queue holds, if it holds anything (it waits
/// for a fence): whether it was added.
#[cfg(windows)]
fn hold(this: This, what: impl FnOnce() -> Held) -> bool {
if this.is_null() {
return false;
}
let mut held = lock(&queue(this).held);
if held.is_empty() {
return false;
}
held.push(what());
true
}
/// Runs what waiting queues hold as far as their fences have been reached
/// (`all`: all of it), each queue's in the order it was given. Called
/// where a fence may have moved: after a signal and after a submission (a
/// list's bottom-of-pipe write may be into a fence), never from inside
/// one.
#[cfg(windows)]
pub(crate) fn release_held(all: bool) {
// One caller at a time, so a queue's submissions keep their order.
static RELEASING: std::sync::Mutex<()> = std::sync::Mutex::new(());
if lock(&WAITING).is_empty() {
return;
}
let _one = lock(&RELEASING);
loop {
let queues = lock(&WAITING).clone();
let mut moved = false;
for q in queues {
// SAFETY: a live queue: one released is taken off the list.
let held = unsafe { &(*(q as *const Queue)).held };
let mut held = lock(held);
loop {
match held.first() {
None => break,
Some(&Held::Wait(fence, value))
if !all && crate::fence::completed(fence as This) < value =>
{
break;
}
Some(Held::Value(wait)) if !all && !value_met(wait) => break,
Some(_) => {}
}
match held.remove(0) {
Held::Wait(..) => {}
Held::Value(wait) => {
// Passed at a present without being met: what the
// queue stood at.
if all && !value_met(&wait) {
static SEEN: AtomicU64 = AtomicU64::new(0);
if SEEN.fetch_add(1, Ordering::Relaxed) < 16 {
tracing::warn!(
queue = format_args!("{q:#x}"),
?wait,
"a wait for a memory value was not met at a present: the queue runs on"
);
}
}
}
Held::Run(lists, order) => {
#[cfg(feature = "diagnostics")]
crate::capture::op(q, || {
format!(
"RUN held submission of {} lists (forced {all})",
order.len()
)
});
// Diagnostics: the part behind this one stands at
// waits that are met already, so the two could have
// been one host submission (one wait for the card,
// each range shaders write compared once).
#[cfg(feature = "diagnostics")]
{
let waits = held.iter().take_while(|h| matches!(h, Held::Value(_))).count();
if waits > 0
&& matches!(held.get(waits), Some(Held::Run(..)))
&& held[..waits].iter().all(|h| matches!(h, Held::Value(w) if w.met()))
{
crate::copystat::add(crate::copystat::C::PartsTogether, 1);
}
}
if crate::host::late()
&& let Some(host) = crate::host::host()
{
// Not waited for: the host keeps the lists
// until they are settled.
host.execute_late(lists, order);
} else {
let ran = {
let runs: Vec<&crate::host::HostList> =
order.iter().map(|&i| lists[i].host()).collect();
match crate::host::host() {
Some(host) => {
host.execute(&runs);
true
}
None => false,
}
};
// They have run: their host lists are used again.
if ran {
crate::list::recycle(lists, &order);
}
}
if all {
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::Forced, 1);
static ONCE: AtomicBool = AtomicBool::new(false);
if !ONCE.swap(true, Ordering::Relaxed) {
tracing::warn!(
"a queue still held a submission at a present: its fence was not reached"
);
}
}
}
// Behind what was sent to the card and not waited
// for, if anything was.
Held::Signal(fence, value) => {
if !crate::host::late_signal(fence, value) {
crate::fence::set(fence as This, value);
}
}
}
moved = true;
}
if held.is_empty() {
lock(&WAITING).retain(|&w| w != q);
}
}
if !moved {
break;
}
}
}
/// Whether a queue may pass `wait`: memory holds the value, or, with
/// submissions sent to the card without a wait (`crate::host::late`), it
/// will once those in the air have run.
#[cfg(windows)]
fn value_met(wait: &crate::list::ValueWait) -> bool {
wait.met() || (crate::host::late() && crate::host::late_met(wait))
}
fn queue<'a>(this: This) -> &'a Queue {
// SAFETY: called from queue methods only.
unsafe { &*this.cast::<Queue>() }
@@ -61,6 +455,8 @@ pub(crate) extern "system" fn create(
},
kind: desc.kind,
desc,
#[cfg(windows)]
held: Default::default(),
});
object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out)
}
@@ -107,11 +503,17 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT
)
}
extern "system" fn release(this: This) -> u32 {
object::release_boxed::<Queue>(this)
let left = object::release_boxed::<Queue>(this);
#[cfg(windows)]
if left == 0 {
lock(&WAITING).retain(|&q| q != this as usize);
}
left
}
/// Runs the lists' host lists and waits for them (decision 0007).
extern "system" fn execute(_: This, count: u32, lists: *const This) {
/// Runs the lists' host lists and waits for them (decision 0007). A queue
/// that waits for a fence keeps them until the fence is reached.
extern "system" fn execute(this: This, count: u32, lists: *const This) {
if lists.is_null() {
return;
}
@@ -119,13 +521,64 @@ extern "system" fn execute(_: This, count: u32, lists: *const This) {
if let Some(host) = crate::host::host() {
// SAFETY: the title passes `count` lists.
let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) };
if cuts() && !this.is_null() {
submit_cut(this, lists);
return;
}
if waits() && split() && !this.is_null() {
submit_split(this, lists);
return;
}
// A list that waits for a memory value not there yet: the queue
// holds the submission, as it does behind a fence.
if waits() && !this.is_null() {
let unmet = crate::list::unmet_waits(lists);
if !unmet.is_empty() {
static SEEN: AtomicU64 = AtomicU64::new(0);
if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value");
}
lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value));
let mut waiting = lock(&WAITING);
if !waiting.contains(&(this as usize)) {
waiting.push(this as usize);
}
}
}
let kept = hold(this, || {
let (taken, order) = crate::list::detach(lists);
Held::Run(taken, order)
});
// Diagnostics: the order submissions are made in, next to the
// commands of the frame's `ops` file (which are in recording order).
#[cfg(feature = "diagnostics")]
crate::capture::op(this as usize, || {
let kind = (!this.is_null()).then(|| queue(this).kind);
// The lists as the frame's other lines name them (their host sides).
let named: Vec<String> = lists
.iter()
.map(|&l| match crate::list::host_list(l) {
Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize),
None => format!("title {l:?}"),
})
.collect();
format!("SUBMIT queue kind {kind:?} held {kept} lists {named:?}")
});
if kept {
return;
}
let host_lists: Vec<_> = lists
.iter()
.filter_map(|&l| crate::list::host_list(l))
.collect();
host.execute(&host_lists);
crate::list::tables_done(lists);
// What the lists wrote at the bottom of the pipe may be a fence
// another queue waits for.
release_held(false);
return;
}
let _ = this;
static ONCE: AtomicBool = AtomicBool::new(false);
if !ONCE.swap(true, Ordering::Relaxed) {
tracing::warn!(count, "command lists submitted; no host GPU runs them");
@@ -157,15 +610,80 @@ extern "system" fn signal2_x(
}
/// Markers and events only matter to profilers.
extern "system" fn marker(_: This) {}
extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT {
extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT {
if fence.is_null() {
return E_INVALIDARG;
}
// A queue that waits signals after what it holds.
#[cfg(windows)]
if hold(this, || Held::Signal(fence as usize, value)) {
return S_OK;
}
// Behind the submissions sent to the card and not waited for: the
// fence is set when they are settled.
#[cfg(windows)]
if crate::host::late_signal(fence as usize, value) {
return S_OK;
}
let _ = this;
crate::fence::signal(fence, value)
}
/// Nothing runs on the queue, so waiting for a fence never blocks it.
extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT {
if fence.is_null() { E_INVALIDARG } else { S_OK }
/// From here on the queue runs nothing it is given until `fence` reaches
/// `value`: how the console orders work between queues (the title's
/// compute queue waits for the depth the graphics queue draws). Our
/// submissions run when they are made, so a wait for a value already
/// reached is nothing; otherwise what the queue is given next is held
/// ([`Held`]) until a signal or a list's bottom-of-pipe write gets the
/// fence there.
extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT {
if fence.is_null() {
return E_INVALIDARG;
}
#[cfg(windows)]
if !this.is_null() {
let now = crate::fence::completed(fence);
// Whether the title uses this at all (the first calls).
{
static CALLS: AtomicU64 = AtomicU64::new(0);
if CALLS.fetch_add(1, Ordering::Relaxed) < 8 {
tracing::info!(kind = queue(this).kind, now, value, "a queue is told to wait for a fence");
}
}
#[cfg(feature = "diagnostics")]
crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind));
let behind = {
let mut held = lock(&queue(this).held);
let behind = !held.is_empty() || now < value;
if behind && waits() {
held.push(Held::Wait(fence as usize, value));
}
behind
};
if behind {
static SEEN: AtomicU64 = AtomicU64::new(0);
if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
tracing::info!(
kind = queue(this).kind,
now,
value,
held = waits(),
"a queue waits for a fence not reached yet"
);
}
}
if behind && waits() {
{
let mut waiting = lock(&WAITING);
if !waiting.contains(&(this as usize)) {
waiting.push(this as usize);
}
}
// The fence may have got there meanwhile.
release_held(false);
}
}
let _ = (this, value);
S_OK
}
/// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]).
extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT {
@@ -242,6 +760,24 @@ extern "system" fn present(
plane_parameters: *const Plane,
_parameters: *const u8,
) -> HRESULT {
#[cfg(all(windows, feature = "diagnostics"))]
crate::copystat::present_begins();
// Submissions sent to the card and not waited for are settled first,
// and what that frees runs in its own order, before anything is forced.
#[cfg(windows)]
if crate::host::late() && !crate::host::late_free_present() {
crate::host::settle_for_present();
release_held(false);
crate::host::settle_for_present();
} else if crate::host::late() {
// The present is sent ahead too: what waits for a value a flight
// will write runs behind that flight, and nothing is settled here.
release_held(false);
}
// shortcut: what a queue still holds at a present runs now, whatever
// its fence: a wait is not kept across frames.
#[cfg(windows)]
release_held(forces());
let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
if frame.is_power_of_two() {
let (draws, dispatches) = crate::list::take_counts();
@@ -272,8 +808,11 @@ extern "system" fn present(
}
}
#[cfg(all(windows, feature = "diagnostics"))]
if crate::capture::listed(frame) {
crate::capture::dump_targets(frame);
{
crate::capture::frame_drew(frame, crate::draw::drawn());
if crate::capture::listed(frame) {
crate::capture::dump_targets(frame);
}
}
#[cfg(windows)]
if planes > 0
File diff suppressed because it is too large. Load diff
+38 -1
View File
@@ -15,6 +15,7 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use victory_pipeline::{Cache, Converter};
use victory_shader::emit::{HostShader, StaticSampler, UserData};
use victory_shader::resource::RootIndexedView;
use victory_shader::{HwStage, RootType};
static CACHE: OnceLock<Cache> = OnceLock::new();
@@ -53,6 +54,8 @@ fn build() -> &'static [u8; 32] {
match exe {
Ok(mut bytes) => {
bytes.extend_from_slice(&limit.to_le_bytes());
// Which group barriers wait is part of the translation too.
bytes.push(victory_shader::emit::group_sync());
*blake3::hash(&bytes).as_bytes()
}
Err(e) => {
@@ -206,10 +209,22 @@ fn encode(s: &HostShader) -> Vec<u8> {
word(&mut out, v);
}
}
for slots in [&s.root_cbvs, &s.root_srvs] {
for slots in [&s.root_cbvs, &s.root_srvs, &s.root_uavs] {
word(&mut out, slots.len() as u32);
out.extend(slots);
}
word(&mut out, s.root_indexed_views.len() as u32);
for view in &s.root_indexed_views {
for value in [
u32::from(view.table_slot),
u32::from(view.constant_slot),
view.constant_dword,
view.byte_offset,
u32::from(view.shift),
] {
word(&mut out, value);
}
}
out
}
@@ -266,6 +281,18 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
}
let root_cbvs = r.list()?;
let root_srvs = r.list()?;
let root_uavs = r.list()?;
let n = r.word()? as usize;
let mut root_indexed_views = Vec::with_capacity(n.min(256));
for _ in 0..n {
root_indexed_views.push(RootIndexedView {
table_slot: u8::try_from(r.word()?).ok()?,
constant_slot: u8::try_from(r.word()?).ok()?,
constant_dword: r.word()?,
byte_offset: r.word()?,
shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?,
});
}
r.0.is_empty().then_some(HostShader {
stage,
dxil,
@@ -274,6 +301,8 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
static_samplers,
root_cbvs,
root_srvs,
root_uavs,
root_indexed_views,
})
}
@@ -300,6 +329,14 @@ mod tests {
])],
root_cbvs: vec![2],
root_srvs: vec![0, 3],
root_uavs: vec![1],
root_indexed_views: vec![RootIndexedView {
table_slot: 1,
constant_slot: 2,
constant_dword: 3,
byte_offset: 32,
shift: 5,
}],
}
}
File diff suppressed because it is too large. Load diff
+841 -18
View File
@@ -43,18 +43,29 @@ pub(crate) struct Staging {
layout: victory_formats::texture::Layout,
/// Mips per array slice.
mips: u32,
/// The staging buffer's bytes (counted in `STAGED` while it lives).
bytes: u64,
memory: *const u8,
last: Mutex<Last>,
/// Whether the staging buffer was detiled since a submitted list last
/// uploaded it, and whether one has uploaded it at all: a list records
/// the upload only then. (Every list that sampled a title texture
/// uploaded all of it again, changed or not: 5,411 subresource copies
/// of 1,120 textures in one frame of run 18.)
dirty: std::sync::atomic::AtomicBool,
uploaded: std::sync::atomic::AtomicBool,
/// When a list last recorded a use of it (`crate::host::moment`).
used: std::sync::atomic::AtomicU64,
}
/// What a texture's staging buffer holds: the hash of the memory detiled
/// (memory not watched), or the write-watch asking it was detiled after,
/// with room to read the memory into.
/// (memory not watched), or the write-watch asking it was detiled after.
#[derive(Default)]
struct Last {
hash: Option<blake3::Hash>,
asked: u64,
read: Vec<u8>,
/// The frame a partly mapped texture was last read in.
partial: Option<u64>,
}
// SAFETY: the staging mapping is written only at submission, under
@@ -65,6 +76,378 @@ unsafe impl Sync for Staging {}
static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None);
/// The buffer a texture the host writes is copied through into the texture
/// of a view the title placed in its memory in another format
/// ([`alias`]): every level of every layer as each of the two formats lays
/// it out for a copy (the same bytes: the texels are as wide), the written
/// texture's layout first.
struct Through {
buffer: ID3D12Resource,
parts: Vec<(
D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
)>,
}
/// The most levels times layers [`alias`] copies (a cube of nine levels).
const ALIAS_PARTS: u32 = 54;
// SAFETY: a device-local buffer only lists record copies with.
unsafe impl Send for Through {}
// SAFETY: as above.
unsafe impl Sync for Through {}
/// The copy buffers of [`alias`], by the placed view's texture.
static THROUGH: Mutex<Option<HashMap<usize, Arc<Through>>>> = Mutex::new(None);
/// Brings `placed`, the texture of a view the title placed in the memory
/// of `source` in another format (`crate::resource::alias_of`), up to date
/// with what the host wrote to `source`: the texels of every level and
/// layer are copied as they are, through a buffer (the host copies between
/// two formats of one texel width in no other way). Recorded the first time
/// the list reads the view
/// and again whenever the list used `source` in another way since (wrote
/// it, or read it itself). Leaves `placed` in the copy destination state,
/// as [`upload`] does. False if the copy cannot be made: the caller fills
/// the texture from title memory, as before.
pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool {
const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8;
const COPY_DEST: u32 = 0x400;
const COPY_SOURCE: u32 = 0x800;
let (Some(to), Some(from)) = (
crate::resource::host_resource(placed),
crate::resource::host_resource(source),
) else {
return false;
};
let Some(host) = host() else { return false };
let through = {
let mut map = THROUGH.lock().unwrap_or_else(|e| e.into_inner());
let map = map.get_or_insert_with(HashMap::new);
match map.get(&(placed as usize)) {
Some(through) => through.clone(),
None => {
// SAFETY: live textures.
let (of_from, of_to) = unsafe { (from.GetDesc(), to.GetDesc()) };
// Levels times layers (a volume's slices are one part).
let count = |d: &D3D12_RESOURCE_DESC| {
let layers = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
1
} else {
u32::from(d.DepthOrArraySize)
};
u32::from(d.MipLevels) * layers
};
let parts = count(&of_from);
if parts == 0 || parts > ALIAS_PARTS || parts != count(&of_to) {
return false;
}
let mut rows = [(); 2]
.map(|()| vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); parts as usize]);
let mut bytes = [0u64; 2];
// SAFETY: plain queries; the out pointers are ours and
// hold `parts` layouts each.
unsafe {
host.device.GetCopyableFootprints(
&of_from,
0,
parts,
0,
Some(rows[0].as_mut_ptr()),
None,
None,
Some(&mut bytes[0]),
);
host.device.GetCopyableFootprints(
&of_to,
0,
parts,
0,
Some(rows[1].as_mut_ptr()),
None,
None,
Some(&mut bytes[1]),
);
}
let alike = rows[0].iter().zip(&rows[1]).all(|(a, b)| {
let (fa, fb) = (a.Footprint, b.Footprint);
a.Offset == b.Offset
&& (fa.Width, fa.Height, fa.Depth, fa.RowPitch)
== (fb.Width, fb.Height, fb.Depth, fb.RowPitch)
});
if bytes[0] == 0 || bytes[0] != bytes[1] || !alike {
return false;
}
let Some(buffer) = host.uav_buffer(bytes[0]) else {
return false;
};
crate::host::name(&buffer, || {
format!(
"alias copy {}x{} f{} to f{}",
of_from.Width, of_from.Height, of_from.Format.0, of_to.Format.0
)
});
tracing::info!(
view = ?placed,
texture = ?source,
width = of_from.Width,
height = of_from.Height,
parts,
written_as = of_from.Format.0,
read_as = of_to.Format.0,
"a view placed in the memory of a texture the host writes, in another format: read from that texture by a copy on the host"
);
let [of_written, of_read] = rows;
let through = Arc::new(Through {
buffer,
parts: of_written.into_iter().zip(of_read).collect(),
});
map.insert(placed as usize, through.clone());
through
}
}
};
let first = list.first_use(placed as usize);
// The source's first use in the list records nothing (its prelude
// brings it to the state); a use in another way since the last copy
// shows as a change of state.
let before = list.transition(source, COPY_SOURCE).map(|(texture, before)| {
let state = crate::host::legal_state(texture, COPY_SOURCE);
let barrier = crate::host::transition(
texture,
D3D12_RESOURCE_STATES(before as i32),
D3D12_RESOURCE_STATES(state as i32),
);
// SAFETY: an open list and a live texture.
unsafe { list.list.ResourceBarrier(&[barrier]) };
before
});
if !first && before.is_none() {
return true;
}
crate::list::ensure_state(list, placed, COPY_DEST);
let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: index as u32,
},
};
let rows = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(&through.buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: *row,
},
};
let (common, read, written) = (
D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATE_COPY_DEST,
);
#[cfg(feature = "diagnostics")]
list.note_op(|| format!("alias copy of {source:?} into {placed:?}"));
// SAFETY: an open list and live resources; the buffer is as big as
// the footprints and rests in the common state between copies.
unsafe {
list.list
.ResourceBarrier(&[crate::host::transition(&through.buffer, common, written)]);
for (index, (of_written, _)) in through.parts.iter().enumerate() {
list.list
.CopyTextureRegion(&rows(of_written), 0, 0, 0, &part(from, index), None);
}
list.list
.ResourceBarrier(&[crate::host::transition(&through.buffer, written, read)]);
for (index, (_, of_read)) in through.parts.iter().enumerate() {
list.list
.CopyTextureRegion(&part(to, index), 0, 0, 0, &rows(of_read), None);
}
list.list
.ResourceBarrier(&[crate::host::transition(&through.buffer, read, common)]);
}
list.keep(&through.buffer);
// A draw that also writes the source (a view of it handled before
// this one) needs it in that state again; the next read of the alias
// then copies once more, as it must after a write.
if let Some(before) = before
&& before & TARGET_OR_UNORDERED != 0
{
crate::list::ensure_state(list, source, before);
}
true
}
/// Whether a texture refresh that finds the runtime remapping title memory
/// goes on without waiting for it (`VICTORY_TEXTURE_NO_WAIT=1`; off by
/// default).
///
/// A texture whose memory is all mapped is read in place, under a lock
/// the runtime takes alone while it changes a mapping
/// (`crate::watch::title_memory_reading`), so that no page goes away under
/// the read. While the world streams in the runtime remaps all the time,
/// and each of the frame's 150-360 refreshes waited for it: runs 99-101
/// have 4, 15 and 16 frame lines with over 300 ms of "textures", up to
/// 3,708 ms, and on every one of them the wait for this lock is the whole
/// of it (1,345 of 1,381 ms; 3,630 of 3,708; the write-watch askings 3-12
/// ms, the texture's own lock 0).
///
/// With the switch the refresh asks for the lock without waiting. If the
/// runtime has it, the texture is read through the kernel instead, which
/// needs no lock: it fails if a page is not there, and then the texture is
/// left as it is and read at its next refresh, a frame later. A read
/// through the kernel costs about 0.6 ms a megabyte against 0.3 in place.
///
/// What changes for the picture: a texture that arrives while the runtime
/// is remapping may show a frame later. It never shows partly read.
fn no_wait() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_NO_WAIT").is_some_and(|v| v == "1"))
}
/// Since the last frame-rate line, with [`no_wait`]: refreshes that read
/// through the kernel because title memory was being remapped, and those
/// left for the next refresh because a page was not there.
pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
/// Since the last frame-rate line, of texture refreshes on every thread, in
/// microseconds: waiting for the texture's own lock (another thread is
/// refreshing the same texture), asking the write watch and the guards,
/// waiting for title memory to hold still (the lock the runtime takes
/// alone while it remaps, `crate::watch::title_memory_reading`), and the
/// refreshes in all.
///
/// While the world streams in, the frame line's "textures" is seconds a
/// frame in some runs and tenths in others for the same megabytes (2,566
/// ms for 110 MB in run 93, 314 ms for 132 MB in run 91; before these
/// counters, runs 81, 83, 85 and 94 each had lines of 1.5-2.9 s), and the
/// submitting thread is not running while it lasts (run 93: 240-310 ms of
/// its own time a frame beside 1,100-1,800 ms of "textures"): it waits.
/// These say for what.
pub(crate) static REFRESH_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// `f`'s result, its time added to [`REFRESH_WAITS`]' place `slot`.
fn waited<T>(slot: usize, f: impl FnOnce() -> T) -> T {
let started = std::time::Instant::now();
let out = f();
REFRESH_WAITS[slot].fetch_add(started.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed);
out
}
thread_local! {
/// Room to read a texture's memory into: one buffer per submitting
/// thread. Each texture kept its own, a second copy in memory of every
/// write-watched or partly mapped texture ever sampled, for the run.
static READ: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Calls `f` with `size` bytes of this thread's read buffer (their
/// contents are whatever the last texture left).
fn with_read<R>(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R {
READ.with(|read| {
let mut read = read.borrow_mut();
if read.len() < size {
read.resize(size, 0);
}
f(&mut read[..size])
})
}
/// Whether a texture all of whose memory is mapped is read through the
/// kernel's copy instead of in place (`VICTORY_TEXTURE_COPY=1`; off by
/// default). Round 3 of the memory work read every such texture that way
/// to be safe from pages taken away under the read; it cost 0.6 ms per MB
/// against 0.3 in place (90-105 ms a frame while the world streams in, runs
/// 72 and 73, against 20-40), and both runs with it lost the graphics
/// device, for a reason not found. The read in place is safe now for
/// another reason (`crate::watch::title_memory_reading`); this switch is
/// left to tell whether the copy was what lost the device.
fn through_copy() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_COPY").is_some_and(|v| v == "1"))
}
/// Calls `f` with the `size` bytes of title memory at `memory`, read
/// through the kernel into this thread's read buffer; pages that are not
/// there read as zeros. The bytes are those a read in place would see.
fn with_title<R>(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> R {
with_read(size, |read| {
crate::host::copy_mapped(read.as_mut_ptr(), memory, size, false);
f(read)
})
}
/// Staging buffers alive (also those only a list still holds) and their
/// bytes.
static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
impl Drop for Staging {
fn drop(&mut self) {
use std::sync::atomic::Ordering::Relaxed;
STAGED[0].fetch_sub(1, Relaxed);
STAGED[1].fetch_sub(self.bytes, Relaxed);
}
}
/// For the memory line: staging buffers alive, their bytes, and how many
/// of them their texture still has (the others wait for a list's reset).
#[cfg(feature = "diagnostics")]
pub(crate) fn memory() -> [u64; 3] {
use std::sync::atomic::Ordering::Relaxed;
let kept = STAGING
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.map_or(0, |map| map.len() as u64);
[STAGED[0].load(Relaxed), STAGED[1].load(Relaxed), kept]
}
/// Staging buffers let go as idle since the start, and their bytes.
static LET_GO: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
/// For the memory line: staging buffers let go as idle, and their bytes.
#[cfg(feature = "diagnostics")]
pub(crate) fn let_go() -> [u64; 2] {
use std::sync::atomic::Ordering::Relaxed;
[LET_GO[0].load(Relaxed), LET_GO[1].load(Relaxed)]
}
/// Lets go of the staging buffers no list recorded a use of for `IDLE_MS`
/// and `IDLE_FRAMES` frames and no list holds: a staging buffer is system memory the size of its
/// texture, kept so that an unchanged texture is not uploaded again, and
/// those of textures no longer sampled were kept for the run (2,246 of
/// them, 2.1 GB, at the end of run 24). The next list that samples such a
/// texture makes a staging buffer anew, detiles and uploads once more.
/// Called before a submission starts, by the thread that submits.
pub(crate) fn let_go_idle() {
use std::sync::atomic::Ordering::Relaxed;
const IDLE_MS: u64 = 10_000;
const IDLE_FRAMES: u64 = 4;
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
let Some(map) = map.as_mut() else {
return;
};
// A list that recorded an upload or a check holds the staging until it
// is reset: one only the table holds is named by no list, recorded or
// running.
let (mut went, mut bytes) = (0u64, 0u64);
map.retain(|_, s| {
let keep = Arc::strong_count(s) > 1
|| !crate::host::long_ago(s.used.load(Relaxed), IDLE_MS, IDLE_FRAMES);
if !keep {
LET_GO[0].fetch_add(1, Relaxed);
LET_GO[1].fetch_add(s.bytes, Relaxed);
went += 1;
bytes += s.bytes;
}
keep
});
if went > 0 {
crate::host::trail(|| format!("sweep: {went} staging buffers of textures let go ({} KiB), held by no list", bytes >> 10));
}
}
/// Textures the host GPU wrote by a copy or resolve: their contents are on
/// the host, not in title memory, which stays as it was.
static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None);
@@ -76,6 +459,17 @@ pub(crate) fn host_written(resource: This) {
.insert(resource as usize);
}
/// Whether the host GPU wrote `resource` by a copy or resolve
/// ([`host_written`]): its host copy cannot be made again from title
/// memory.
pub(crate) fn host_wrote(resource: usize) -> bool {
HOST_WRITTEN
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.is_some_and(|set| set.contains(&resource))
}
/// The title released a resource.
pub(crate) fn forget(resource: usize) {
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
@@ -86,6 +480,10 @@ pub(crate) fn forget(resource: usize) {
if let Some(set) = set.as_mut() {
set.remove(&resource);
}
let mut through = THROUGH.lock().unwrap_or_else(|e| e.into_inner());
if let Some(through) = through.as_mut() {
through.remove(&resource);
}
}
/// Whether `resource`'s host copy takes its contents from title memory:
@@ -114,6 +512,20 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
let Some(staging) = staging(resource, texture) else {
return;
};
use std::sync::atomic::Ordering::Relaxed;
staging.used.store(crate::host::moment(), Relaxed);
// The host texture has the staging buffer's contents: only the check
// at submission is left, and what it finds changed the next list that
// samples the texture uploads (a frame late where every list of the
// frame was recorded before that check).
if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexSkipped, 1);
list.defer_texture(staging);
return;
}
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexUploads, 1);
const COPY_DEST: u32 = 0x400;
crate::list::ensure_state(list, resource, COPY_DEST);
// The staging buffer lives as long as `staging`, which the deferred
@@ -165,11 +577,26 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
// SAFETY: an open list; both locations name live resources.
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
// When the list is submitted, its copy takes what the staging buffer
// holds by then: noted before the check below, which sets `dirty`
// again if it detiles (the next list then uploads once more).
{
let staging = staging.clone();
list.defer_host(move || {
staging.uploaded.store(true, Relaxed);
staging.dirty.store(false, Relaxed);
});
}
// Once per submission however many of its lists sample the texture.
list.defer_texture(staging);
}
impl Staging {
/// The title memory the texture is read from: address and bytes.
pub(crate) fn memory(&self) -> (usize, usize) {
(self.memory as usize, self.layout.size as usize)
}
/// Detiles the texture memory into the staging buffer if it changed
/// since the last time (and is mapped at all).
pub(crate) fn refresh(&self) {
@@ -183,35 +610,123 @@ impl Staging {
/// Returns the bytes of title memory read.
fn refresh_now(&self) -> usize {
let whole = std::time::Instant::now();
let read = self.refresh_timed();
REFRESH_WAITS[3].fetch_add(whole.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed);
read
}
fn refresh_timed(&self) -> usize {
let size = self.layout.size as usize;
let start = self.memory as usize;
let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner()));
let last = &mut *last;
if let Some((now, written)) = crate::watch::writes(start, start + size, false) {
if let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) {
if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
return 0;
}
last.asked = now;
// Read through the copy, which stands unmapped pages: memory of
// big pools is too slow to ask page by page.
last.read.resize(size, 0);
crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false);
self.detile(&last.read);
with_read(size, |read| {
crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false);
self.detile(read);
});
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
return size;
}
if !committed(self.memory, size) {
#[cfg(feature = "diagnostics")]
tracing::debug!(
memory = ?self.memory,
size,
desc = ?self.layout.desc,
"a sampled texture's memory is not committed"
);
return 0;
// View memory has no write-watch, and a texture there was hashed
// whole at every check: 229 MB and 51 ms a frame in a gameplay view
// where two textures change (run 58). It is guarded now, as buffers
// in view memory are: a write of the title's to it faults once and
// is noted, a mapping is announced by the runtime. While neither
// happened the texture is as it was. What the guard cannot see (a
// write to the same pages through another view) is still found by
// the hash, which is taken every eighth frame only, by the
// texture's address, so the textures take turns.
// `VICTORY_TEXTURE_GUARD=0` hashes at every check, as before.
static GUARD: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0"))
&& let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true))
{
const HASH_EVERY: u64 = 8;
let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked);
last.asked = now;
let turn = crate::frame::current().wrapping_add((start >> 16) as u64) % HASH_EVERY == 0;
if unwritten && !turn {
return 0;
}
}
// SAFETY: committed memory of the texture's layout size.
// From here on the texture's memory may be read in place. Held until
// that read is done: the runtime changes what title memory shows
// only with this taken alone, so what `committed` finds mapped
// stays mapped (see `crate::watch::title_memory_reading`; without
// it a page went between the asking and the read in runs 71 and
// 74).
let _mapped = if no_wait() {
// Not waited for: while the runtime remaps title memory the
// texture is read through the kernel instead, whole or not at
// all (`no_wait`).
let Some(mapped) = crate::watch::title_memory_reading_now() else {
return self.refresh_unlocked(last, size);
};
mapped
} else {
waited(2, crate::watch::title_memory_reading)
};
if !committed(self.memory, size) {
// Partly mapped: a streamed texture with only some mips' pages
// there, the usual state while it streams in. Read through the
// copy, which stands unmapped pages (zeros), and upload what
// is there; nothing at all mapped changes nothing.
// shortcut: read again at most every 30 frames (reading around
// unmapped pages is slow, and nothing tells us when pages
// arrive): a mip that streams in shows up to 30 frames late.
let frame = crate::frame::current();
if last.partial.is_some_and(|at| frame < at + 30) {
return 0;
}
last.partial = Some(frame);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
let changed = with_read(size, |read| {
crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false);
let hash = blake3::hash(read);
if last.hash == Some(hash) {
return false;
}
last.hash = Some(hash);
if read.iter().all(|&b| b == 0) {
return false;
}
self.detile(read);
true
});
#[cfg(feature = "diagnostics")]
if changed {
crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
}
let _ = changed;
return size;
}
if through_copy() {
return with_title(self.memory, size, |tiled| {
let hash = blake3::hash(tiled);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
if last.hash == Some(hash) {
return size;
}
last.hash = Some(hash);
self.detile(tiled);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
size
});
}
// SAFETY: committed memory of the texture's layout size, and it
// stays committed while `_mapped` is held.
let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) };
let hash = blake3::hash(tiled);
#[cfg(feature = "diagnostics")]
@@ -226,8 +741,38 @@ impl Staging {
size
}
/// A refresh while the runtime is remapping title memory ([`no_wait`]):
/// the texture is read through the kernel, which fails if a page of it
/// is not there at this moment. Then nothing is taken and the texture
/// is looked at again at its next refresh (what was learnt about writes
/// to it is forgotten, so that it is not passed over as unwritten).
/// Returns the bytes read.
fn refresh_unlocked(&self, last: &mut Last, size: usize) -> usize {
use std::sync::atomic::Ordering::Relaxed;
let read = with_read(size, |read| {
if !crate::host::read_into(self.memory, read) {
return false;
}
let hash = blake3::hash(read);
if last.hash != Some(hash) {
last.hash = Some(hash);
self.detile(read);
}
true
});
if read {
UNLOCKED[0].fetch_add(1, Relaxed);
size
} else {
UNLOCKED[1].fetch_add(1, Relaxed);
last.asked = 0;
0
}
}
/// Detiles `tiled` (the texture's memory) into the staging buffer.
fn detile(&self, tiled: &[u8]) {
self.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
if tiled.iter().all(|&b| b == 0) {
tracing::debug!(
@@ -256,9 +801,109 @@ impl Staging {
}
}
/// Lets go of a title texture's staging buffer (lists that recorded an
/// upload from it hold it until they have run); the next upload makes one
/// anew.
pub(crate) fn unstage(resource: This) {
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
if let Some(map) = map.as_mut() {
map.remove(&(resource as usize));
}
}
/// Whether a title texture has a staging buffer: a list recorded its
/// upload, and the lists that sample it check it at submission.
pub(crate) fn is_staged(resource: This) -> bool {
let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize)))
}
/// The bytes of a title texture's memory, and whether all of it is mapped,
/// if the texture has been staged for upload.
pub(crate) fn staged(resource: This) -> Option<(u64, bool)> {
let s = {
let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
map.as_ref()?.get(&(resource as usize))?.clone()
};
let size = s.layout.size as usize;
Some((size as u64, committed(s.memory, size)))
}
/// Whether `[at, at + len)` is committed memory (streamed textures may be
/// unmapped until their pages arrive).
pub(crate) fn committed(at: *const u8, len: usize) -> bool {
if by_query() {
return committed_by_query(at, len);
}
if len == 0 {
return true;
}
let (there, of) = readable(at as usize, len, true);
there == of
}
/// Whether the two questions above and below are put to `VirtualQuery`, as
/// they were (`VICTORY_COMMITTED_QUERY=1`). `VirtualQuery` answers with the
/// length of the run of pages in the same state, which it finds by walking
/// the page tables to the run's end: 8.8 ms for one question in the title's
/// 1.1 GB block (round 6). The pass over the heap's views asks three or
/// more of them for every texture slot that is due, 3,000 slots a frame
/// when the card has no room (run 75): that pass then ran 208-264 ms, and
/// while it ran the submitting thread's write-watch askings waited behind
/// the walks (run 76: 8-22 askings a frame of 6-21 ms each, 46-172 ms).
fn by_query() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_COMMITTED_QUERY").is_some_and(|v| v == "1"))
}
/// Of the kernel's pages that hold `[at, at + len)` (`len > 0`): how many
/// can be read, and how many there are; with `all`, it stops at the first
/// that cannot. One question to the kernel for up to 256 pages at once
/// (`QueryWorkingSetEx`: the state of each page asked about, no walk); a
/// page not in the working set may still be there (never touched, or
/// trimmed), and a one-byte read through the kernel says.
/// A page that is committed and may not be read counts as not there, which
/// is what the callers ask for: they read or write the memory next.
fn readable(at: usize, len: usize, all: bool) -> (usize, usize) {
use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
const KERNEL_PAGE: usize = 4096;
let (first, last) = (at / KERNEL_PAGE, at.saturating_add(len - 1) / KERNEL_PAGE);
let of = last - first + 1;
let mut there = 0;
// SAFETY: plain data.
let mut info: [PSAPI_WORKING_SET_EX_INFORMATION; 256] = unsafe { std::mem::zeroed() };
let mut page = first;
while page <= last {
let n = (last - page + 1).min(info.len());
for (i, entry) in info[..n].iter_mut().enumerate() {
entry.VirtualAddress = ((page + i) * KERNEL_PAGE) as *mut _;
}
// SAFETY: `n` entries of the size given; our own process.
let asked = unsafe {
K32QueryWorkingSetEx(
GetCurrentProcess(),
info.as_mut_ptr().cast(),
(n * size_of::<PSAPI_WORKING_SET_EX_INFORMATION>()) as u32,
)
} != 0;
for (i, entry) in info[..n].iter().enumerate() {
// Bit 0 of the answer: the page is in the working set.
// SAFETY: plain data the query filled in.
let valid = asked && unsafe { entry.VirtualAttributes.Flags } & 1 != 0;
let mut byte = [0u8];
if valid || crate::host::read_into(((page + i) * KERNEL_PAGE) as *const u8, &mut byte) {
there += 1;
} else if all {
return (there, of);
}
}
page += n;
}
(there, of)
}
fn committed_by_query(at: *const u8, len: usize) -> bool {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery};
let mut p = at as usize;
let end = p + len;
@@ -275,6 +920,67 @@ pub(crate) fn committed(at: *const u8, len: usize) -> bool {
true
}
/// How many bytes of `[at, at + len)` are committed memory: all of a
/// texture that is there, some of one streaming in (its smaller mips lie
/// at the start of its memory, and their pages are mapped first), none of
/// one not there. With neither the first nor the last page committed the
/// answer is none without a look at the pages between (two queries for the
/// slots whose texture is away, which are asked again and again).
pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery};
if len == 0 {
return 0;
}
let start = at as usize;
let end = start.saturating_add(len);
if !committed(at, 1) && !committed((end - 1) as *const u8, 1) {
return 0;
}
if !by_query() {
static BY_PAGE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if *BY_PAGE.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_PAGE").is_some_and(|v| v == "1")) {
// By page, without the walk: whole pages, cut to the range.
let (there, _) = readable(start, len, false);
return (there as u64 * 4096).min(len as u64);
}
// By 64 KiB block, one page asked of each: the title's memory is
// mapped in blocks of that size (the console's page), and the
// answer is a measure of how much of a texture has arrived, not a
// promise that every byte can be read (the upload reads through the
// kernel). By page, a texture half there cost a failed kernel read
// for each of its missing pages, every frame it stayed due: 1,663
// textures "uploaded in part" kept the pass over the heap's views at
// 90-160 ms a frame (run 81). `VICTORY_MAPPED_BY_PAGE=1`: by page.
const BLOCK: usize = 64 << 10;
let mut there = 0u64;
let mut block = start & !(BLOCK - 1);
while block < end {
let (lo, hi) = (block.max(start), block.saturating_add(BLOCK).min(end));
if readable(lo, 1, true).0 == 1 {
there += (hi - lo) as u64;
}
block = block.saturating_add(BLOCK);
}
return there;
}
let (mut p, mut there) = (start, 0u64);
while p < end {
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) };
let next = (info.BaseAddress as usize).saturating_add(info.RegionSize).min(end);
if n == 0 || next <= p {
break;
}
if info.State == MEM_COMMIT {
there += (next - p) as u64;
}
p = next;
}
there
}
/// The staging state of a title texture, made on first use.
fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
@@ -327,6 +1033,8 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
)
});
tracing::debug!(?desc, total, "texture contents uploaded from title memory");
STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed);
let s = Arc::new(Staging {
buffer,
#[cfg(feature = "diagnostics")]
@@ -336,9 +1044,124 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
rows,
layout,
mips: u32::from(d.MipLevels),
bytes: total,
memory,
last: Mutex::default(),
dirty: std::sync::atomic::AtomicBool::new(true),
uploaded: std::sync::atomic::AtomicBool::new(false),
used: std::sync::atomic::AtomicU64::new(crate::host::moment()),
});
map.insert(resource as usize, s.clone());
Some(s)
}
#[cfg(test)]
mod title_memory_tests {
use super::with_title;
/// Title memory whose tail is reserved and not committed reads through
/// the copy as its bytes and then zeros, without a fault; so does
/// memory a page of which is taken away between two reads, and the
/// zeros are zeros whatever the read buffer held before.
#[test]
fn an_uncommitted_tail_reads_as_zeros() {
use windows_sys::Win32::System::Memory::*;
const HEAD: usize = 0xb_0000;
const SIZE: usize = 0x20_0000;
// SAFETY: a private reservation of our own; only committed pages
// are written in place, and nothing else reads them in place.
unsafe {
// The read buffer holds something else first.
let other = vec![0x77u8; SIZE];
with_title(other.as_ptr(), SIZE, |bytes| assert!(bytes.iter().all(|&b| b == 0x77)));
let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
assert!(!base.is_null());
assert_eq!(VirtualAlloc(base.cast(), HEAD, MEM_COMMIT, PAGE_READWRITE), base.cast());
base.write_bytes(0x5a, HEAD);
with_title(base, SIZE, |bytes| {
assert!(bytes[..HEAD].iter().all(|&b| b == 0x5a), "what is mapped");
assert!(bytes[HEAD..].iter().all(|&b| b == 0), "what is not: zeros");
});
// The title takes a page in the middle away: zeros from then
// on, the rest as before.
assert_ne!(VirtualFree(base.add(0x4_0000).cast(), 0x1_0000, MEM_DECOMMIT), 0);
with_title(base, SIZE, |bytes| {
assert!(bytes[..0x4_0000].iter().all(|&b| b == 0x5a));
assert!(bytes[0x4_0000..0x5_0000].iter().all(|&b| b == 0));
assert!(bytes[0x5_0000..HEAD].iter().all(|&b| b == 0x5a));
assert!(bytes[HEAD..].iter().all(|&b| b == 0));
});
assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
}
}
/// The texture both device-loss runs named last (16 texels wide, 4 or 8
/// high, format 10, layout 0x100, console flags 0x300000; its memory
/// began 0x300 into a page in run 73 and 0x700 in run 72, and here also
/// 0xf00, so that a page line runs through it): what the detiling is
/// given and what it writes are the same read in place and read through
/// the copy, and the rows it writes end where the staging buffer the
/// host sizes for it ends (896 bytes for 4 rows of 128 bytes 256 apart,
/// 1,920 for 8).
#[test]
fn the_small_texture_of_runs_72_and_73_detiles_the_same_both_ways() {
use windows_sys::Win32::System::Memory::*;
for (height, within) in [(4u32, 0x300usize), (8, 0x700), (4, 0xf00), (8, 0xf00)] {
// The description as the log printed it, word for word.
let words: [u32; 14] = [3, 0, 0, 0, 16, 0, height, 65537, 10, 1, 0, 256, 3_145_728, 0];
// SAFETY: fourteen words are a resource description (56 bytes,
// plain numbers).
let desc: crate::resource::ResourceDesc = unsafe { std::mem::transmute(words) };
let layout = crate::resource::texture_layout(&desc)
.expect("a console layout")
.planes[0]
.layout
.clone();
let size = layout.size as usize;
let (row, pitch) = (16 * 8, 256usize);
assert!(size >= row * height as usize, "the layout holds every texel");
// Committed pages and a reserved one after them; the texture
// begins `within` bytes into the first, as the title placed it.
// SAFETY: our own reservation; the committed part is written
// and read in place, by this thread alone.
unsafe {
let pages = size.div_ceil(4096) + 1;
let base = VirtualAlloc(std::ptr::null(), (pages + 1) * 4096, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
assert!(!base.is_null());
assert_eq!(VirtualAlloc(base.cast(), pages * 4096, MEM_COMMIT, PAGE_READWRITE), base.cast());
for i in 0..pages * 4096 {
base.add(i).write((i * 7 + i / 251) as u8);
}
let memory = base.add(within);
let in_place = std::slice::from_raw_parts(memory, size);
// The bytes: the same in place and through the copy.
with_title(memory, size, |copied| assert_eq!(copied, in_place));
// What the detiling writes: the same, and inside the bytes
// the host's staging buffer for this texture has.
let staged = (height as usize - 1) * pitch + row;
assert_eq!(staged, if height == 4 { 896 } else { 1920 });
let detile = |tiled: &[u8]| {
// The slice `Staging::detile` hands over: whole rows.
let mut linear = vec![0xeeu8; pitch * height as usize];
layout
.detile(tiled, 0, 0, &mut linear, pitch, pitch * height as usize)
.expect("detiled");
linear
};
let direct = detile(in_place);
let through = with_title(memory, size, |copied| detile(copied));
assert_eq!(direct, through);
for y in 0..height as usize {
assert!(direct[y * pitch..][..row].iter().any(|&b| b != 0xee), "row {y} written");
assert!(direct[y * pitch + row..(y + 1) * pitch].iter().all(|&b| b == 0xee), "nothing past row {y}");
}
// A buffer of exactly the staged bytes is enough.
let mut exact = vec![0u8; staged];
layout
.detile(in_place, 0, 0, &mut exact, pitch, pitch * height as usize)
.expect("the staging buffer's bytes are enough");
assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
}
}
}
}
+747 -20
View File
@@ -10,7 +10,9 @@
//! copy leaves each 64 KiB block it took read-only, and our vectored handler
//! takes the first write to it: it notes the block as written and gives the
//! write access back. The runtime tells us when it maps or unmaps views
//! ([`title_memory_remapped`]), which resets their protection.
//! ([`title_memory_remapped`]), which resets their protection. Blocks found
//! wholly uncommitted are skipped while they remain so; one query can
//! confirm a whole region, including ordinary reservations between views.
//!
//! shortcut: writes into physical pages through another view (xmem's
//! `write_physical`, DirectStorage's page destinations) are not seen at
@@ -35,14 +37,264 @@ struct Journal {
written: BTreeMap<usize, u64>,
/// Room for the kernel's answer.
found: Vec<usize>,
/// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`])
/// and the asking that did: `writes` answers for a range inside one
/// from the journal, without another kernel call.
ahead: Vec<(usize, usize)>,
ahead_asked: u64,
/// The ahead asking stands for a whole submission ([`ask_once`]): no
/// other ahead asking is made, and `ahead` stays, until
/// [`ask_once_end`].
kept: bool,
}
static JOURNAL: Mutex<Journal> = Mutex::new(Journal {
asked: 0,
written: BTreeMap::new(),
found: Vec::new(),
ahead: Vec::new(),
ahead_asked: 0,
kept: false,
});
/// Ranges of one submission closer than this are asked about together:
/// walking the pages between them costs less than another kernel call (a
/// call that resets written pages costs 30-70 microseconds whatever the
/// range).
const AHEAD_GAP: usize = (8 << 20) / PAGE;
/// The most one asking covers (its answer needs 8 bytes per 4 KiB page).
const AHEAD_MAX: usize = (1 << 30) / PAGE;
/// Asks the kernel about many ranges `(start, end)` at once, before the
/// [`writes`] of each: ranges close together are one asking, and `writes`
/// then answers from the journal until [`ask_ahead_done`]. The world's
/// submissions refresh thousands of host copies (6,664 askings a frame,
/// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are
/// left to `writes`.
pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
let mut pieces: Vec<(usize, usize)> = ranges
.iter()
.filter(|r| r.0 < r.1)
.map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE)))
.collect();
if pieces.len() < 2 {
return;
}
pieces.sort_unstable();
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = &mut *j;
// The submission's one asking stands ([`ask_once`]): what it does not
// hold is left to `writes`.
if j.kept {
return;
}
j.asked += 1;
j.ahead_asked = j.asked;
j.ahead.clear();
let mut i = 0;
while i < pieces.len() {
let first = pieces[i].0;
let mut last = pieces[i].1;
let mut k = i + 1;
while k < pieces.len()
&& pieces[k].0 <= last + AHEAD_GAP
&& last.max(pieces[k].1) - first <= AHEAD_MAX
{
last = last.max(pieces[k].1);
k += 1;
}
ask_run(j, &pieces[i..k]);
i = k;
}
}
/// Since the last frame line: the kernel askings that took a millisecond
/// or more, their microseconds, and the longest asking's. An asking walks
/// page tables, some ten microseconds for most ranges; in run 75 the 2,644
/// askings of a frame took 219 ms in the lines where the pass over the
/// heap's views ran long, 25-50 ms in the others. These numbers say
/// whether a few askings wait for something or all of them are slow.
#[cfg(feature = "diagnostics")]
static SLOW: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
#[cfg(feature = "diagnostics")]
fn slow(us: u64) {
use std::sync::atomic::Ordering::Relaxed;
if us >= 1000 {
SLOW[0].fetch_add(1, Relaxed);
SLOW[1].fetch_add(us, Relaxed);
}
SLOW[2].fetch_max(us, Relaxed);
}
/// [`SLOW`], taken.
#[cfg(feature = "diagnostics")]
pub(crate) fn slow_asks() -> [u64; 3] {
[0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed))
}
/// The submission's refreshes are done: `writes` asks the kernel again.
pub(crate) fn ask_ahead_done() {
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
if !j.kept {
j.ahead.clear();
}
}
/// Whether a submission asks the kernel once, before its first refresh,
/// about every range its lists refresh (`VICTORY_ASK_ONCE=1`; off by
/// default).
///
/// A submission's refreshes are done in groups, between the title's own
/// buffer copies (each copy flushes the refreshes recorded before it), and
/// every group asked the kernel again: 2,644 askings a frame, 70 a
/// submission. With the switch the journal answers all of them from one
/// asking made when the submission starts.
///
/// What changes: memory the title's other threads write while the
/// submission is being prepared is seen by the next submission's asking,
/// not by this one's later groups. What this submission's lists read was
/// written before they were submitted, so before the asking. Our own
/// writes into title memory while preparing are told to the journal
/// ([`wrote`]) or end the asking ([`ask_once_end`]).
pub(crate) fn once() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
// On by default since run 81 (with card buffers: 375-450 ms a frame
// against 573-647, the picture unchanged over four minutes);
// `VICTORY_ASK_ONCE=0` asks per range, as before.
*ON.get_or_init(|| std::env::var_os("VICTORY_ASK_ONCE").is_none_or(|v| v != "0"))
}
/// With [`once`]: asks about `ranges` (everything a submission's lists
/// refresh) as [`ask_ahead`] does, and lets that asking stand until
/// [`ask_once_end`].
pub(crate) fn ask_once(ranges: &[(usize, usize)]) {
if !once() {
return;
}
ask_once_end();
ask_ahead(ranges);
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = &mut *j;
if j.ahead.is_empty() {
// `ask_ahead` asked nothing (fewer than two ranges).
j.asked += 1;
j.ahead_asked = j.asked;
}
// `ask_ahead` leaves a range that lies alone to `writes`, which asks
// once per flush: with one asking for the submission that was every
// such range asked again at each of its 70 flushes (run 76: 2,300
// askings a frame with the switch on, as without it). They are asked
// here, once; what is not write-watched stays with `writes`.
for &(start, end) in ranges {
if start >= end {
continue;
}
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
if !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) && ask_kernel(j, first, last) {
j.ahead.push((first, last));
}
}
j.kept = !j.ahead.is_empty();
}
/// The submission's one asking stands no longer: its refreshes are done,
/// or title memory was written in a way the journal was not told.
pub(crate) fn ask_once_end() {
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
if j.kept {
j.kept = false;
j.ahead.clear();
}
}
/// We wrote title memory `[at, at + len)` while a submission's one asking
/// stands (the title's buffer copies, done at submission): its pages count
/// as written after that asking, so the refreshes that follow copy them.
pub(crate) fn wrote(at: usize, len: usize) {
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
if !j.kept || len == 0 {
return;
}
j.asked += 1;
let now = j.asked;
for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) {
j.written.insert(page, now);
}
}
/// One kernel asking for `pieces` (page ranges in order); by halves if it
/// fails, as a run across two reservations or into memory that is not
/// write-watched does. A piece alone is left to [`writes`].
fn ask_run(j: &mut Journal, pieces: &[(usize, usize)]) {
if pieces.len() < 2 {
return;
}
let first = pieces[0].0;
let last = pieces.iter().map(|p| p.1).max().unwrap_or(first);
if ask_kernel(j, first, last) {
j.ahead.push((first, last));
return;
}
let (a, b) = pieces.split_at(pieces.len() / 2);
ask_run(j, a);
ask_run(j, b);
}
/// Asks the kernel for the written pages of pages `[first, last)` and notes
/// them in the journal under the ahead asking; false (and nothing changed)
/// if the range is not write-watched memory of one reservation.
fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool {
use windows_sys::Win32::System::Memory::GetWriteWatch;
const WRITE_WATCH_FLAG_RESET: u32 = 1;
let mut count = (last - first) * PAGE / KERNEL_PAGE;
j.found.resize(count.max(j.found.len()), 0);
let mut granularity = 0;
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
// SAFETY: the answer buffer holds `count` entries.
let failed = unsafe {
GetWriteWatch(
WRITE_WATCH_FLAG_RESET,
(first * PAGE) as *const _,
(last - first) * PAGE,
j.found.as_mut_ptr().cast(),
&mut count,
&mut granularity,
)
} != 0;
if failed {
return false;
}
#[cfg(feature = "diagnostics")]
{
use crate::copystat::{C, add};
add(C::Watches, 1);
add(C::WatchUs, started.elapsed().as_micros() as u64);
slow(started.elapsed().as_micros() as u64);
}
let now = j.ahead_asked;
for k in 0..count {
let page = j.found[k] / PAGE;
j.written.insert(page, now);
}
true
}
/// What [`writes`] would say of `[start, end)` from the journal alone, if
/// the range lies in one asked ahead ([`ask_ahead`], [`ask_once`]): the
/// pages written since tracking began and the asking that last found each
/// written, with the number of the asking that stands (as [`writes`] gives
/// it). `None` if the kernel would have to be asked.
pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> {
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
j.ahead
.iter()
.any(|&(a, b)| a <= first && last <= b)
.then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect()))
}
/// The pages of `[start, end)` (whole pages) as last written, for pages
/// written since tracking began: `(page number, asking)` in page order, and
/// this asking's number, which is higher than any in the list but those the
@@ -54,6 +306,16 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = &mut *j;
// Asked ahead with the submission's other ranges: the journal has it.
if j.ahead.iter().any(|&(a, b)| a <= first && last <= b) {
return Some((
j.ahead_asked,
j.written
.range(first..last)
.map(|(&p, &w)| (p, w))
.collect(),
));
}
let mut count = (last - first) * PAGE / KERNEL_PAGE;
j.found.resize(count.max(j.found.len()), 0);
let mut granularity = 0;
@@ -75,7 +337,12 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
if !guarded {
return None;
}
guard(first * PAGE, last * PAGE)?
#[cfg(feature = "diagnostics")]
let guarding = std::time::Instant::now();
let written = guard(first * PAGE, last * PAGE);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64);
written?
} else {
Vec::new()
};
@@ -84,6 +351,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
use crate::copystat::{C, add};
add(C::Watches, 1);
add(C::WatchUs, started.elapsed().as_micros() as u64);
slow(started.elapsed().as_micros() as u64);
}
j.asked += 1;
let now = j.asked;
@@ -108,11 +376,15 @@ struct Guards {
protected: BTreeSet<usize>,
/// Of those, the ones not written since a copy took them.
clean: BTreeSet<usize>,
/// Blocks already copied as zeros. While they remain wholly uncommitted,
/// the copy can skip hundreds of MB of failing kernel reads per world frame.
absent: BTreeSet<usize>,
}
static GUARDS: Mutex<Guards> = Mutex::new(Guards {
protected: BTreeSet::new(),
clean: BTreeSet::new(),
absent: BTreeSet::new(),
});
fn guards() -> std::sync::MutexGuard<'static, Guards> {
@@ -123,12 +395,20 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> {
/// they were last guarded (all of a block's pages), guarding them again
/// before the caller copies them. `None` if the memory is not a view.
fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery};
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) };
if n == 0 || info.Type != MEM_MAPPED {
// A range whose first block the guards hold already (read-only by our
// hand, or noted absent) is a view: no question to Windows. The
// question walks the page tables to the end of the pages that share the
// first one's state, and a guarded view is one long run of read-only
// pages: 0.6 ms for the title's 174 MB heap, 16 times a frame, and most
// of the 68 ms a frame of "guards" (run 58).
// `VICTORY_GUARD_ASK=1` asks every time, as before.
static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && {
let g = guards();
let first = start / BLOCK;
g.protected.contains(&first) || g.absent.contains(&first)
};
if !known && !is_view(start, end) {
return None;
}
install();
@@ -136,8 +416,35 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
let mut written = Vec::new();
let mut run: Option<usize> = None;
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
// The range's clean blocks, in order: read off the set in one pass,
// not looked up one block at a time. A frame asks about some 10 GB of
// view memory, 150,000 blocks, nearly all clean: the lookups were most
// of the 60-90 ms a frame of "guards" (run 54). What the loop adds to
// the set meanwhile is the block it stands at or ones before it.
let clean: Vec<usize> = g.clean.range(first..last).copied().collect();
if clean.len() == last - first {
// Nothing written, mapped or new since the range was last taken.
return Some(written);
}
let mut next_clean = 0;
let mut uncommitted_until = first;
for block in first..=last {
let open = block < last && !g.clean.contains(&block);
while next_clean < clean.len() && clean[next_clean] < block {
next_clean += 1;
}
let is_clean = next_clean < clean.len() && clean[next_clean] == block;
let mut open = block < last && !is_clean;
if open && g.absent.contains(&block) {
// Ordinary commits need no runtime mapping notification. Reuse
// this asking's query for the following blocks in the same region.
if block >= uncommitted_until {
uncommitted_until = uncommitted_end(block);
}
open = block >= uncommitted_until;
if open {
g.absent.remove(&block);
}
}
if open {
written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE);
if g.protected.contains(&block) {
@@ -155,8 +462,53 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
Some(written)
}
/// Whether `[start, end)` is view memory. The title's views lie in
/// placeholders, mapped and unmapped block by block as it streams, so a
/// range can begin in a block that is not mapped right now: the first
/// pages of the range that are there decide. A range with nothing there
/// counts as a view (its blocks are noted absent, and looked at again when
/// the runtime maps them).
///
/// Looking at the first address only took such a range for "not a view":
/// its copy was marked not watched for good and copied whole at every
/// refresh, around its unmapped pages (run 54: 300 such ranges, 570 MB
/// copied a frame for them, 255 copies a frame reading around holes).
/// `VICTORY_GUARD_HOLES=0` looks at the first address only, as before.
fn is_view(start: usize, end: usize) -> bool {
use windows_sys::Win32::System::Memory::{
MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery,
};
static HOLES: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let holes = *HOLES.get_or_init(|| std::env::var_os("VICTORY_GUARD_HOLES").is_none_or(|v| v != "0"));
let mut at = start;
loop {
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
if n == 0 {
return false;
}
if info.Type == MEM_MAPPED {
return true;
}
// Committed memory that is no view (the title's heaps, ours), or
// the answer as it was before.
if info.State == MEM_COMMIT || !holes {
return false;
}
// A hole (a placeholder, or free): on to what follows it.
let next = (info.BaseAddress as usize).saturating_add(info.RegionSize);
if next <= at || next >= end {
return true;
}
at = next;
}
}
/// Makes blocks `[from, to)` read-only and notes them guarded and clean;
/// block by block if they span views, leaving out any that fail (unmapped).
/// block by block if they span views, leaving out any that fail, and
/// noting those not committed (unmapped) absent.
fn protect(g: &mut Guards, from: usize, to: usize) {
use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
let set = |from: usize, to: usize| {
@@ -182,10 +534,28 @@ fn protect(g: &mut Guards, from: usize, to: usize) {
for block in from..to {
if set(block, block + 1) {
note(g, block, block + 1);
} else if block < uncommitted_end(block) {
g.absent.insert(block);
}
}
}
/// The end (exclusive) of the whole uncommitted blocks starting at `block`.
fn uncommitted_end(block: usize) -> usize {
use windows_sys::Win32::System::Memory::{
MEM_FREE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, VirtualQuery,
};
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery((block * BLOCK) as *const _, &mut info, size_of_val(&info)) };
if n != 0 && matches!(info.State, MEM_RESERVE | MEM_FREE) {
(info.BaseAddress as usize).saturating_add(info.RegionSize) / BLOCK
} else {
block
}
}
/// Gives write access back to the guarded blocks of `[start, end)` and
/// notes them written; true if any was guarded.
fn open(g: &mut Guards, start: usize, end: usize) -> bool {
@@ -212,17 +582,77 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
pub fn writing(at: usize, len: usize) {
// The length is the title's (`fread`'s size times count, saturated).
open(&mut guards(), at, at.saturating_add(len));
// A placed texture there changes with no descriptor written.
crate::descriptor::host::remapped(at, len);
}
/// Held shared by a read of title memory in place, and alone by the runtime
/// while it changes what title memory shows.
///
/// The runtime does not change a mapping in one step. To unmap one page of
/// a view it unmaps the whole view and maps what stays again
/// (`xmem.rs` `unmap`), and a view it maps is a reservation until the next
/// call commits it (`map`, then `commit`). For that moment pages the title
/// never gave up are "reserved, never committed", and a thread reading
/// them in place takes an access violation: run 71 in `Layout::detile`,
/// run 74 in the hash before it, both under `Staging::refresh_now`, which
/// had asked whether the texture was all mapped and been told yes. Asking
/// cannot help; not changing the mapping while such a read is under way
/// does.
static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(());
/// What the runtime holds while it changes what title memory shows
/// ([`title_memory_remapping`]).
pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>);
/// The runtime is about to map, unmap or move physical pages of title
/// memory: until what it returns is dropped, no read of title memory in
/// place is under way and none begins ([`title_memory_reading`]). Taken
/// around the whole change, the unmapping and the mapping again.
pub fn title_memory_remapping() -> Remapping {
Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner()))
}
/// What a read of title memory in place holds ([`title_memory_reading`]).
pub struct Reading(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>);
/// For reading title memory in place: until what it returns is dropped,
/// the runtime changes no mapping, so memory found mapped stays mapped.
/// Not to be taken twice by one thread, nor held across anything that
/// maps title memory.
pub fn title_memory_reading() -> Reading {
Reading(MAPPING.read().unwrap_or_else(|e| e.into_inner()))
}
/// [`title_memory_reading`] if it can be had at once: `None` while the
/// runtime changes a mapping (or waits to), for a caller that has another
/// way to read and would rather not wait.
pub fn title_memory_reading_now() -> Option<Reading> {
match MAPPING.try_read() {
Ok(guard) => Some(Reading(guard)),
Err(std::sync::TryLockError::Poisoned(e)) => Some(Reading(e.into_inner())),
Err(std::sync::TryLockError::WouldBlock) => None,
}
}
/// The runtime mapped or unmapped title memory `[at, at + len)`: what it
/// shows is new and read-write, so it is no longer guarded.
/// shows is new and read-write, so it is no longer guarded (nor known
/// unmapped).
pub fn title_memory_remapped(at: usize, len: usize) {
// A placed texture there arrives, goes or changes with no descriptor
// written.
crate::descriptor::host::remapped(at, len);
// The views the runtime told us of there are no longer what it shows.
crate::inplace::views_gone(at, len);
// And nothing stays in place over it.
crate::inplace::title_memory_freeing(at, len);
let mut g = guards();
let blocks: Vec<usize> = g
.protected
.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK))
.copied()
.collect();
let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK);
let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect();
for block in absent {
g.absent.remove(&block);
}
let blocks: Vec<usize> = g.protected.range(range).copied().collect();
for block in blocks {
g.protected.remove(&block);
g.clean.remove(&block);
@@ -358,17 +788,264 @@ mod tests {
let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) };
file.read(into).is_ok_and(|n| n == 13)
};
assert!(!read(&mut file), "the kernel does not fault into our handler");
assert!(
!read(&mut file),
"the kernel does not fault into our handler"
);
writing(view + 100, 13);
assert!(read(&mut file));
// SAFETY: the bytes just read.
assert_eq!(unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, b"from the disk");
assert_eq!(guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()));
let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) };
assert_eq!(landed, b"from the disk");
assert_eq!(
guard(view, view + 2 * BLOCK),
Some((view / PAGE..view / PAGE + 1).collect())
);
// SAFETY: our view.
unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) };
unsafe {
UnmapViewOfFile(
windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS {
Value: view as *mut _,
},
)
};
title_memory_remapped(view, 2 * BLOCK);
}
#[test]
fn writes_in_partly_committed_view_blocks_are_reported() {
use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile,
SEC_RESERVE, UnmapViewOfFile,
};
const SIZE: usize = 3 * BLOCK;
struct View(MEMORY_MAPPED_VIEW_ADDRESS);
impl Drop for View {
fn drop(&mut self) {
title_memory_remapped(self.0.Value as usize, SIZE);
// SAFETY: our view is still mapped.
unsafe { UnmapViewOfFile(self.0) };
}
}
// SAFETY: a new reserved pagefile section. The view holds its own
// reference after we close the handle, including on assertion failure.
let view = unsafe {
let section = CreateFileMappingW(
INVALID_HANDLE_VALUE,
std::ptr::null(),
PAGE_READWRITE | SEC_RESERVE,
0,
SIZE as u32,
std::ptr::null(),
);
assert!(!section.is_null());
let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, SIZE);
CloseHandle(section);
assert!(!view.Value.is_null());
View(view)
};
let start = view.0.Value as usize;
let commit = |at: usize, len| {
// SAFETY: these pages belong to our reserved view.
let committed = unsafe { VirtualAlloc(at as _, len, MEM_COMMIT, PAGE_READWRITE) };
assert_eq!(committed as usize, at);
};
let early = start + BLOCK + 3 * KERNEL_PAGE;
let late = start + 2 * BLOCK + 3 * KERNEL_PAGE;
commit(start, BLOCK);
commit(early, KERNEL_PAGE);
let refresh = || guard(start, start + SIZE).unwrap();
assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]);
// The last block is still entirely reserved.
assert!(!refresh().contains(&(late / PAGE)));
commit(late, KERNEL_PAGE); // Ordinary commit, without a runtime mapping notification.
for at in [early, late] {
assert!(writable(at));
// SAFETY: each address is inside its committed read-write page.
unsafe { (at as *mut u8).write_volatile(1) };
}
assert_eq!(refresh(), [early / PAGE, late / PAGE]);
}
/// A range of view memory whose first block is not mapped is a view
/// all the same: its blocks are reported once, then the ones written
/// or mapped since.
#[test]
fn a_range_that_begins_in_an_unmapped_block_is_guarded() {
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER,
MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2,
VirtualAlloc2,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
// SAFETY: a fresh placeholder of three blocks and a pagefile
// section of three; the middle block is mapped first.
let (p, section) = unsafe {
let p = VirtualAlloc2(
GetCurrentProcess(),
std::ptr::null(),
3 * BLOCK,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
std::ptr::null_mut(),
0,
) as usize;
assert_ne!(p, 0);
let section = CreateFileMappingW(
-1isize as _,
std::ptr::null(),
PAGE_READWRITE,
0,
(3 * BLOCK) as u32,
std::ptr::null(),
);
assert!(!section.is_null());
(p, section)
};
let map = |block: usize| {
// SAFETY: splits the placeholder at the block and maps the
// section's block there.
let view = unsafe {
VirtualFree(
(p + block * BLOCK) as *mut _,
BLOCK,
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
);
MapViewOfFile3(
section,
GetCurrentProcess(),
(p + block * BLOCK) as *const _,
(block * BLOCK) as u64,
BLOCK,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
)
};
assert_eq!(view.Value as usize, p + block * BLOCK);
view
};
let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE;
let all: Vec<usize> = (0..3).flat_map(pages).collect();
// Nothing mapped at all: a view with every block absent.
assert!(is_view(p, p + 3 * BLOCK));
let middle = map(1);
title_memory_remapped(p + BLOCK, BLOCK);
// The range begins in the placeholder, its middle block is a view.
assert!(is_view(p, p + 3 * BLOCK));
assert_eq!(guard(p, p + 3 * BLOCK), Some(all));
assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since");
// SAFETY: inside the mapped middle block.
unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) };
assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
let first = map(0);
title_memory_remapped(p, BLOCK);
assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect()));
assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
// Memory of ours that is no view stays none.
let mut local = [0u8; 16];
let at = local.as_mut_ptr() as usize;
assert!(!is_view(at, at + local.len()));
// SAFETY: our views and placeholder.
unsafe {
UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
UnmapViewOfFile2(GetCurrentProcess(), middle, MEM_PRESERVE_PLACEHOLDER);
for block in 0..3 {
VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
}
windows_sys::Win32::Foundation::CloseHandle(section);
}
title_memory_remapped(p, 3 * BLOCK);
}
/// Blocks of a placeholder between views are reported once, then not
/// again (they cannot be guarded) until the runtime maps them.
#[test]
fn unmapped_blocks_are_reported_once_until_mapped() {
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER,
MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2,
VirtualAlloc2,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
// SAFETY: a fresh placeholder of three blocks and a pagefile
// section of two; block 0 shows the section's first block, as the
// runtime maps physical pages.
let (p, section) = unsafe {
let p = VirtualAlloc2(
GetCurrentProcess(),
std::ptr::null(),
3 * BLOCK,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
std::ptr::null_mut(),
0,
) as usize;
assert_ne!(p, 0);
let section = CreateFileMappingW(
-1isize as _,
std::ptr::null(),
PAGE_READWRITE,
0,
(2 * BLOCK) as u32,
std::ptr::null(),
);
assert!(!section.is_null());
(p, section)
};
let map = |block: usize| {
// SAFETY: splits the placeholder at the block and maps the
// section's block there.
let view = unsafe {
VirtualFree(
(p + block * BLOCK) as *mut _,
BLOCK,
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
);
MapViewOfFile3(
section,
GetCurrentProcess(),
(p + block * BLOCK) as *const _,
(block * BLOCK) as u64,
BLOCK,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
)
};
assert_eq!(view.Value as usize, p + block * BLOCK);
view
};
let first = map(0);
let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE;
let all: Vec<usize> = (0..3).flat_map(pages).collect();
assert_eq!(guard(p, p + 3 * BLOCK), Some(all));
assert_eq!(
guard(p, p + 3 * BLOCK),
Some(Vec::new()),
"nothing written since"
);
let second = map(1);
title_memory_remapped(p + BLOCK, BLOCK);
assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
// SAFETY: our views and placeholder.
unsafe {
UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
UnmapViewOfFile2(GetCurrentProcess(), second, MEM_PRESERVE_PLACEHOLDER);
for block in 0..3 {
VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
}
windows_sys::Win32::Foundation::CloseHandle(section);
}
title_memory_remapped(p, 3 * BLOCK);
}
/// A write or mapping that runs past the end of the address space (a
/// title's `fread` with a huge count) covers up to the end; the sum used
/// to overflow. Up there no test has guarded blocks.
@@ -379,3 +1056,53 @@ mod tests {
title_memory_remapped(top, usize::MAX);
}
}
#[cfg(test)]
mod mapping_tests {
use super::{title_memory_reading, title_memory_remapping};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, mpsc};
use std::time::Duration;
/// A change of mapping waits for a read in place that is under way, and
/// a read in place waits for a change of mapping.
#[test]
fn reads_in_place_and_remappings_wait_for_each_other() {
// A reader holds; the change does not begin until it lets go.
let changed = Arc::new(AtomicBool::new(false));
let reading = title_memory_reading();
let (began, wait) = mpsc::channel();
let change = {
let changed = changed.clone();
std::thread::spawn(move || {
began.send(()).unwrap();
let _changing = title_memory_remapping();
changed.store(true, Ordering::SeqCst);
})
};
wait.recv().unwrap();
std::thread::sleep(Duration::from_millis(100));
assert!(!changed.load(Ordering::SeqCst), "the mapping changed under a read in place");
drop(reading);
change.join().unwrap();
assert!(changed.load(Ordering::SeqCst));
// A change holds; the read does not begin until it is done.
let read = Arc::new(AtomicBool::new(false));
let changing = title_memory_remapping();
let (began, wait) = mpsc::channel();
let reader = {
let read = read.clone();
std::thread::spawn(move || {
began.send(()).unwrap();
let _reading = title_memory_reading();
read.store(true, Ordering::SeqCst);
})
};
wait.recv().unwrap();
std::thread::sleep(Duration::from_millis(100));
assert!(!read.load(Ordering::SeqCst), "a read in place began during a change of mapping");
drop(changing);
reader.join().unwrap();
assert!(read.load(Ordering::SeqCst));
}
}
+5
View File
@@ -114,6 +114,11 @@ fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> {
heap.blocks
.insert(ptr as usize, Block { size, apu, layout });
heap.by_apu.insert(apu, ptr as usize);
// The big ones are named in the log: they are the title's audio memory
// given out of our allocator, which the memory line counts as ours.
if size >= 32 << 20 {
tracing::info!(mb = size >> 20, at = ?ptr, "audio memory for the title from our allocator");
}
Some((ptr, apu))
}
@@ -976,6 +976,16 @@ fn into_destination(
if super::xmem::write_physical(pages, offset, &data[..n]) {
Ok(())
} else {
// Said aloud: Grand Theft Auto VI never reads a request's result
// (it only polls for completion), so a destination left unwritten
// is a model or texture that silently holds whatever its pages
// held before.
tracing::warn!(
offset,
len,
pages = pages.len(),
"dstorage: a destination's physical pages could not be written (unknown page or a host failure); its request fails"
);
Err(E_INVALIDARG)
}
}
+15 -1
View File
@@ -1144,7 +1144,21 @@ mod host {
return None;
}
self.empty_until[slot] = None;
Some(convert(&state.Gamepad))
#[allow(unused_mut)]
let mut pad = convert(&state.Gamepad);
// The scripted keys (`VICTORY_KEYS`) also press the first
// pad's buttons, by the stand-in pad's table: with a real pad
// connected the stand-in is not there, and a title that listens
// to the pad (Grand Theft Auto VI's start screen) saw nothing.
#[cfg(feature = "diagnostics")]
if slot == 0 {
for vk in scripted() {
if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) {
pad.buttons |= button;
}
}
}
Some(pad)
}
fn keys(&mut self) -> Vec<KeyState> {
+82
View File
@@ -428,6 +428,9 @@ pub extern "system" fn XMemAllocatePhysicalPages(
flags = format_args!("{flags:#x}"),
"XMemAllocatePhysicalPages"
);
// For the GPU side's in-place census: only a committed section can be
// opened as a host heap.
victory_gpu::title_memory_section(handle as usize, size as u64, on_wine());
let section = Arc::new(Section(handle));
let mut physical = physical();
let first = physical.next_page;
@@ -596,6 +599,11 @@ pub extern "system" fn XMemMapPhysicalPages(
) -> *mut c_void {
let base = address as usize;
let mut physical = physical();
// Until the pages are mapped again: `unmap` takes whole views away and
// maps what stays of them again, and a mapped view is a reservation
// until it is committed. A read of title memory in place must not fall
// into that gap (`victory_gpu::title_memory_remapping`).
let _changing = victory_gpu::title_memory_remapping();
unmap(&mut physical, base, n * PAGE);
if pages.is_null() {
return address;
@@ -663,6 +671,8 @@ pub extern "system" fn XMemMapPhysicalPagesScatter(
pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
let (to, from, len) = (to as usize, from as usize, len as usize);
let mut physical = physical();
// As in `XMemMapPhysicalPages`: no read in place meets the gap.
let _changing = victory_gpu::title_memory_remapping();
unmap(&mut physical, to, len);
for k in (0..len).step_by(PAGE) {
if from == 0 {
@@ -728,6 +738,8 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
}
// New contents, read-write: the GPU side's copies no longer guard it.
victory_gpu::title_memory_remapped(base, len);
// What the range shows now, for the GPU side's in-place census.
victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64);
physical.views.insert(base, (len, slice));
true
}
@@ -868,6 +880,25 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin
gpu_optimal_limit: gpu_optimal,
..Default::default()
};
// What the title is told, logged at the first asking and at every
// 1,024th: "used" is all the process has committed, the layer's own
// memory and the card's included (27 GB in run 60's gameplay against a
// limit of 13.5 GB). A title that budgets its streaming from these two
// figures believes it is far over its limit.
// shortcut: the figure is not yet the title's own memory alone (its
// heaps and the pages it mapped); count those if this line shows the
// title asking.
static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let asked = ASKED.fetch_add(1, Ordering::Relaxed);
if asked % 1024 == 0 {
tracing::info!(
asked = asked + 1,
which = _which,
limit_mb = stats.title_limit >> 20,
used_mb = stats.title_used >> 20,
"the title asks how much memory it uses"
);
}
// SAFETY: checked non-null; the title passes room for the structure.
unsafe { out.write(stats) };
1
@@ -1112,6 +1143,57 @@ mod tests {
assert_eq!(XMemIsToolsMemAvailable(), 0);
}
/// A thread that reads a mapped page in place, as the GPU side reads a
/// texture, never meets the moment in which the runtime has taken the
/// page's view away to map it again: mapping the same pages at the same
/// address unmaps the view and maps a new one, and without the lock the
/// reader faults on a page "reserved, never committed" (the crashes of
/// runs 71 and 74).
#[test]
fn a_read_in_place_never_meets_the_gap_of_a_remapping() {
use std::sync::atomic::{AtomicBool, Ordering};
let mut pages = [0usize; 3];
let mut n = 3;
assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
let a = XMemVirtualAlloc(
std::ptr::null_mut(),
3 * PAGE,
MEM_RESERVE | PAGES_64K,
0,
PAGE_READWRITE,
);
assert!(!a.is_null());
assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
// SAFETY: mapped read-write.
unsafe { a.cast::<u8>().write(1) };
let first = a as usize;
let stop = std::sync::Arc::new(AtomicBool::new(false));
let reader = {
let stop = stop.clone();
std::thread::spawn(move || {
let mut reads = 0u64;
while !stop.load(Ordering::Relaxed) {
let _reading = victory_gpu::title_memory_reading();
// SAFETY: the page is mapped whenever no change of
// mapping is under way, and none is while `_reading`
// is held.
assert_eq!(unsafe { (first as *const u8).read_volatile() }, 1);
reads += 1;
}
reads
})
};
for _ in 0..2000 {
// The same pages at the same address: the view goes and comes
// back, with the same bytes.
assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
}
stop.store(true, Ordering::Relaxed);
assert!(reader.join().expect("the reader never faulted") > 0);
assert_eq!(XMemMapPhysicalPages(a, 3, std::ptr::null()), a);
assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
}
#[test]
fn mapping_no_pages_changes_nothing() {
let pages = allocate(2);
+1
View File
@@ -24,6 +24,7 @@ windows-sys = { workspace = true, features = [
"Win32_System_Kernel",
"Win32_System_LibraryLoader",
"Win32_System_Memory",
"Win32_System_Performance",
"Win32_System_Threading",
] }
+249
View File
@@ -0,0 +1,249 @@
//! Instructions the console's CPU (Zen 2) has and an Intel PC's lacks, emulated: the title's
//! code raises STATUS_ILLEGAL_INSTRUCTION on them (GTA VI zeroes memory with a `clzero` loop at
//! its first frames), and the vectored handler steps over them here.
//!
//! Ported from XCL (github.com/ivall/xcl, GPL-2.0-only): `insn.rs` (decoder, as
//! `console_insn_decode.rs`, unchanged) and `eh.rs` `emulate_console_only`.
#[path = "console_insn_decode.rs"]
mod decode;
use decode::ConsoleOnly;
use std::cell::Cell;
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT;
const CONTINUE_EXECUTION: i32 = -1;
/// Whether what Windows said about memory is remembered per thread (the regions it found
/// writable, the code bytes it found readable) and not asked again at every emulated
/// instruction. A query walks the pages of the region it answers for: asked from outside, it
/// took 2-9 ms in the title's heaps of 0.6-2.2 GB and 89 ms in its 6.2 GB page pool (run 30),
/// and the title zeroes blocks of them with `clzero` loops all through a frame: six of its
/// threads spent 25-78 % of their time inside that query (runs 29 and 30), about 27 s of
/// processor time in Windows per 9 s frame. On by default; `VICTORY_CLZERO_ASK=1` asks every
/// time, as before.
fn remembers() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_CLZERO_ASK").is_none_or(|v| v != "1"))
}
/// Answers a remembered region gives before Windows is asked about it again: one freed or
/// protected meanwhile is forgotten then.
const ANSWERS: u32 = 4096;
thread_local! {
/// The regions Windows last said are committed and writable (start, end), newest first,
/// and the answers they gave since they were emptied.
static WRITABLE: Cell<([(usize, usize); 4], u32)> = const { Cell::new(([(0, 0); 4], 0)) };
/// Faulting addresses and the code bytes found readable there, newest first.
static CODE: Cell<[(usize, usize); 8]> = const { Cell::new([(0, 0); 8]) };
}
/// Instructions emulated, the times Windows was asked about memory for them, and the bytes
/// `clzero` loops zeroed, since the start.
static EMULATED: AtomicU64 = AtomicU64::new(0);
static ASKED: AtomicU64 = AtomicU64::new(0);
static ZEROED: AtomicU64 = AtomicU64::new(0);
fn readable(va: usize, bytes: usize) -> bool {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery};
// SAFETY: plain data filled in by the query.
let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0;
ASKED.fetch_add(1, Relaxed);
found && m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.BaseAddress as usize + m.RegionSize >= va + bytes
}
fn writable(va: usize, bytes: usize) -> bool {
writable_to(va, va + bytes) == Some(va + bytes)
}
/// Where the committed, writable memory that `va` lies in ends, at most `end`; None if `va`
/// is not in such memory. A region found is remembered ([`remembers`]).
/// shortcut: a remembered region that was freed or protected since is written all the same
/// for up to [`ANSWERS`] answers: the write then faults inside the handler, which the guard
/// on view memory opens as it does any write, and which is a crash otherwise (as the
/// unchecked single-line emulation behind this one already is).
fn writable_to(va: usize, end: usize) -> Option<usize> {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualQuery};
let remember = remembers();
if remember {
let (regions, answers) = WRITABLE.with(Cell::get);
if let Some(&(_, to)) = regions.iter().find(|&&(from, to)| from <= va && va < to) {
let next = if answers >= ANSWERS { ([(0, 0); 4], 0) } else { (regions, answers + 1) };
WRITABLE.with(|w| w.set(next));
return Some(to.min(end));
}
}
// SAFETY: plain data filled in by the query.
let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0;
ASKED.fetch_add(1, Relaxed);
if !found || m.State != MEM_COMMIT || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 {
return None;
}
let (from, to) = (m.BaseAddress as usize, m.BaseAddress as usize + m.RegionSize);
if remember {
WRITABLE.with(|w| {
let (mut regions, answers) = w.get();
regions.rotate_right(1);
regions[0] = (from, to);
w.set((regions, answers));
});
}
Some(to.min(end))
}
/// An illegal instruction at `ctx.Rip`: a console-only one is emulated and stepped over
/// (`CONTINUE_EXECUTION`); anything else returns 0 (the crash report and the title's handlers
/// see it).
///
/// # Safety
/// `ctx` is the faulting thread's context, from the exception being dispatched.
pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 {
let rip = ctx.Rip as usize;
// The same few instructions fault again and again: their bytes are asked about once.
let known = if remembers() { CODE.with(Cell::get) } else { [(0, 0); 8] };
let n = match known.iter().find(|&&(at, n)| at == rip && n > 0) {
Some(&(_, n)) => n,
None => {
if !readable(rip, 1) {
return 0;
}
let n = (1..=16).rev().find(|&n| readable(rip, n)).unwrap_or(0);
if remembers() {
let mut known = known;
known.rotate_right(1);
known[0] = (rip, n);
CODE.with(|c| c.set(known));
}
n
}
};
// SAFETY: `n` bytes at `rip` are readable.
let code = unsafe { std::slice::from_raw_parts(rip as *const u8, n) };
let Some((what, len)) = decode::decode(code) else { return 0 };
static SEEN: std::sync::Mutex<Vec<std::mem::Discriminant<ConsoleOnly>>> = std::sync::Mutex::new(Vec::new());
if let Ok(mut seen) = SEEN.lock()
&& !seen.contains(&std::mem::discriminant(&what))
{
seen.push(std::mem::discriminant(&what));
if what != ConsoleOnly::Ud2 {
tracing::warn!(instruction = ?what, at = format_args!("{rip:#x}"), "a console CPU instruction this CPU lacks: emulated (logged once)");
}
}
match what {
ConsoleOnly::Ud2 => return 0,
ConsoleOnly::Clwb => {
// nothing to write back on the PC: patched to NOPs, no exception next time
use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect};
let mut old = 0u32;
// SAFETY: the instruction's own bytes, made writable for the patch and restored.
unsafe {
if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 {
std::slice::from_raw_parts_mut(rip as *mut u8, len).fill(0x90);
VirtualProtect(rip as *const _, len, old, &mut old);
}
}
}
ConsoleOnly::Monitorx => {}
ConsoleOnly::Mwaitx => std::hint::spin_loop(),
ConsoleOnly::Clzero => {
// with an address-size prefix (0x67) the line is at EAX, zero-extended
let a32 = code[..len - 3].contains(&0x67);
let line = (if a32 { ctx.Rax & 0xFFFF_FFFF } else { ctx.Rax } as usize) & !63;
if !writable(line, 64) {
return 0; // the real instruction faults there too
}
// SAFETY: the 64-byte line is committed and writable.
unsafe { std::ptr::write_bytes(line as *mut u8, 0, 64) };
}
ConsoleOnly::ClzeroLoop { end_reg } => {
// the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once
let regs: [u64; 16] = [
ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15,
];
let end = regs[end_reg as usize & 15] as usize;
let start = ctx.Rax as usize;
if end > start && end - start < 2 << 30 {
// Region by region: a block may lie across several (the title's pages are
// mapped one view each), and one answer for all of it was a refusal, after
// which every 64-byte line took an exception of its own.
let mut at = start;
while at < end {
let Some(to) = writable_to(at, end) else { break };
// SAFETY: committed and writable from `at` to `to`.
unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) };
at = to;
}
if at == start {
return 0;
}
ZEROED.fetch_add((at - start) as u64, Relaxed);
if at < end {
// What follows is not writable: the loop goes on there (the same
// instruction again), where the real one faults too.
ctx.Rax = at as u64;
return CONTINUE_EXECUTION;
}
}
ctx.Rax = end as u64;
}
ConsoleOnly::Rdpru => {
let mut v = 0i64;
// SAFETY: a valid out pointer.
unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut v) };
let v = if ctx.Rcx as u32 <= 1 { v as u64 } else { 0 };
ctx.Rax = v & 0xFFFF_FFFF;
ctx.Rdx = v >> 32;
}
ConsoleOnly::Rdpid(r) => {
// SAFETY: no preconditions.
let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u64;
let regs: [&mut u64; 16] = [
&mut ctx.Rax, &mut ctx.Rcx, &mut ctx.Rdx, &mut ctx.Rbx, &mut ctx.Rsp, &mut ctx.Rbp, &mut ctx.Rsi, &mut ctx.Rdi, &mut ctx.R8, &mut ctx.R9, &mut ctx.R10, &mut ctx.R11, &mut ctx.R12, &mut ctx.R13,
&mut ctx.R14, &mut ctx.R15,
];
*regs[r as usize & 15] = cpu;
}
// the low quadword changes; the high one is zeroed, as a Zen 5 does
ConsoleOnly::Extrq { dst, src, len, idx } => {
// SAFETY: the context's XMM registers (CONTEXT_FLOATING_POINT is captured for exceptions).
let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters };
let (len, idx) = match src {
Some(s) => {
let c = x[s as usize & 15].Low;
(c as u8, (c >> 8) as u8)
}
None => (len, idx),
};
let d = &mut x[dst as usize & 15];
d.Low = decode::extrq(d.Low, len, idx);
d.High = 0;
}
ConsoleOnly::Insertq { dst, src, reg, len, idx } => {
// SAFETY: as above.
let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters };
let s = x[src as usize & 15];
let (len, idx) = if reg { (s.High as u8, (s.High >> 8) as u8) } else { (len, idx) };
let d = &mut x[dst as usize & 15];
d.Low = decode::insertq(d.Low, s.Low, len, idx);
d.High = 0;
}
}
ctx.Rip += len as u64;
// How often this runs at all (each one is an exception: a trip into Windows and back).
let emulated = EMULATED.fetch_add(1, Relaxed) + 1;
if emulated >= 1 << 16 && emulated.is_power_of_two() {
tracing::info!(
emulated,
asked = ASKED.load(Relaxed),
zeroed_mb = ZEROED.load(Relaxed) >> 20,
"console CPU instructions emulated so far, the times Windows was asked about memory for them, and what clzero loops zeroed"
);
}
CONTINUE_EXECUTION
}
@@ -0,0 +1,237 @@
//! Instructions the console's CPU (Zen 2) has and a PC's may lack – a title raises
//! STATUS_ILLEGAL_INSTRUCTION on them on an Intel CPU before Ice Lake / Alder Lake (CLWB,
//! SHA) or on any Intel CPU (CLZERO, RDPRU, MONITORX / MWAITX and SSE4a's EXTRQ / INSERTQ,
//! which are AMD's). The exception handler (`eh`) emulates the ones decoded here and steps over
//! them.
/// A console-only instruction at the faulting address.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsoleOnly {
/// `clwb m8`: write a cache line back – nothing to do, the PC's memory is coherent
Clwb,
/// `clzero`: zero the 64-byte cache line at rAX
Clzero,
/// `clzero` loop: `clzero; add rax, 0x40; cmp rax, <reg>; jb -12` – zero `[rax..reg)`
ClzeroLoop { end_reg: u8 },
/// `rdpru`: ecx = 0 MPERF / 1 APERF → edx:eax (a counter)
Rdpru,
/// `monitorx` / `mwaitx`: a wait the emulation skips
Monitorx,
Mwaitx,
/// `rdpid r64`: TSC_AUX (the processor number) into the register (CONTEXT order: rax, rcx,
/// rdx, rbx, rsp, rbp, rsi, rdi, r8..r15)
Rdpid(u8),
/// SSE4a `extrq xmm, imm8 (length), imm8 (index)` / `extrq xmm1, xmm2` (`src` Some: the
/// length and index in xmm2's bits 5:0 and 13:8): a bit field of the low quadword, moved
/// down and zero-extended (the high quadword zeroed). Registers are XMM numbers 0..15.
Extrq { dst: u8, src: Option<u8>, len: u8, idx: u8 },
/// SSE4a `insertq xmm1, xmm2, imm8 (length), imm8 (index)` / `insertq xmm1, xmm2` (`reg`:
/// the length and index in xmm2's bits 69:64 and 77:72): the low bits of xmm2 put into a
/// bit field of xmm1's low quadword.
Insertq { dst: u8, src: u8, reg: bool, len: u8, idx: u8 },
/// `ud2`: the title's own trap (not emulated)
Ud2,
}
/// A field length of SSE4a's six bits: 0 is 64.
fn field_len(len: u8) -> u32 {
match len & 63 {
0 => 64,
n => n as u32,
}
}
/// EXTRQ on a low quadword: `len` bits from bit `idx`, zero-extended (a field past bit 63 is
/// undefined on the console; here it is what a shift gives).
pub fn extrq(v: u64, len: u8, idx: u8) -> u64 {
let (len, idx) = (field_len(len), (idx & 63) as u32);
let field = v.checked_shr(idx).unwrap_or(0);
if len >= 64 {
field
} else {
field & ((1u64 << len) - 1)
}
}
/// INSERTQ on a low quadword: the low `len` bits of `src` put at bit `idx` of `dst`.
pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 {
let (len, idx) = (field_len(len), (idx & 63) as u32);
let ones = if len >= 64 { u64::MAX } else { (1u64 << len) - 1 };
let mask = ones.checked_shl(idx).unwrap_or(0);
(dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask)
}
/// The length of a ModRM-encoded operand (ModRM, SIB and displacement) at `b[0]`, None when the
/// bytes run out.
fn modrm_len(b: &[u8]) -> Option<usize> {
let modrm = *b.first()?;
let (md, rm) = (modrm >> 6, modrm & 7);
if md == 3 {
return Some(1);
}
let mut len = 1;
let mut base = rm;
if rm == 4 {
base = *b.get(1)? & 7;
len += 1;
}
len += match md {
0 if base == 5 => 4, // disp32 (rip-relative, or a SIB without a base)
0 => 0,
1 => 1,
_ => 4,
};
(b.len() >= len).then_some(len)
}
/// The console-only instruction at the start of `code` and its length.
pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> {
let mut i = 0;
// `rep`: the last of F2 / F3, which decides between them (and over 66) for SSE4a
let (mut p66, mut pf3, mut rep, mut rex) = (false, false, 0u8, 0u8);
while let Some(&b) = code.get(i) {
match b {
0x66 => p66 = true,
0xF2 => rep = 0xF2,
0xF3 => {
pf3 = true;
rep = 0xF3;
}
0x2E | 0x3E | 0x26 | 0x36 | 0x64 | 0x65 | 0x67 => {}
// REX counts only right before the opcode: one before a legacy prefix is ignored
0x40..=0x4F => {
rex = b;
i += 1;
continue;
}
_ => break,
}
rex = 0;
i += 1;
}
if *code.get(i)? != 0x0F {
return None;
}
match (*code.get(i + 1)?, code.get(i + 2).copied()) {
(0x01, Some(0xFC)) => {
// clzero (0F 01 FC); add rax, 0x40 (48 83 C0 40); cmp rax, <reg> ([48|4C] 39 modrm); jb -12 (72 F4)
// (not after an 0x67: that CLZERO is at EAX, and the jb goes back to the 0F, past the
// prefix – it is stepped alone, the loop is taken from the next one)
if code.len() >= i + 12
&& !code[..i].contains(&0x67)
&& code[i + 3..i + 7] == [0x48, 0x83, 0xC0, 0x40]
&& (code[i + 7] == 0x48 || code[i + 7] == 0x4C)
&& code[i + 8] == 0x39
&& code[i + 10..i + 12] == [0x72, 0xF4]
{
let rex_r = code[i + 7] == 0x4C;
let modrm = code[i + 9];
let reg_idx = ((modrm >> 3) & 7) | if rex_r { 8 } else { 0 };
Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12))
} else {
Some((ConsoleOnly::Clzero, i + 3))
}
}
(0x01, Some(0xFD)) => Some((ConsoleOnly::Rdpru, i + 3)),
(0x01, Some(0xFA)) => Some((ConsoleOnly::Monitorx, i + 3)),
(0x01, Some(0xFB)) => Some((ConsoleOnly::Mwaitx, i + 3)),
(0x0B, _) => Some((ConsoleOnly::Ud2, i + 2)),
// SSE4a: register operands only (ModRM mod 3); REX.R extends reg, REX.B rm
// (the last of F2 / F3 decides: F2 INSERTQ, F3 #UD; neither with 66: EXTRQ)
(0x78 | 0x79, Some(m)) if (rep == 0xF2 || (rep == 0 && p66)) && m >> 6 == 3 => {
let reg = ((m >> 3) & 7) | (rex & 4) << 1;
let rm = (m & 7) | (rex & 1) << 3;
let imm = |k: usize| code.get(i + 3 + k).copied();
match (code[i + 1], rep == 0xF2) {
// extrq xmm(rm), imm8, imm8 – the ModRM reg field is /0
(0x78, false) if (m >> 3) & 7 == 0 => Some((ConsoleOnly::Extrq { dst: rm, src: None, len: imm(0)?, idx: imm(1)? }, i + 5)),
(0x79, false) => Some((ConsoleOnly::Extrq { dst: reg, src: Some(rm), len: 0, idx: 0 }, i + 3)),
(0x78, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: false, len: imm(0)?, idx: imm(1)? }, i + 5)),
(0x79, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: true, len: 0, idx: 0 }, i + 3)),
_ => None,
}
}
// 66 0F AE /6 with a memory operand (without 66 it is xsaveopt)
(0xAE, Some(m)) if p66 && (m >> 3) & 7 == 6 && m >> 6 != 3 => Some((ConsoleOnly::Clwb, i + 2 + modrm_len(&code[i + 2..])?)),
// F3 0F C7 /7 with a register operand
(0xC7, Some(m)) if pf3 && (m >> 3) & 7 == 7 && m >> 6 == 3 => Some((ConsoleOnly::Rdpid((m & 7) | (rex & 1) << 3), i + 3)),
_ => None,
}
}
/// `code` as hex, for a log line.
pub fn hex(code: &[u8]) -> String {
code.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
/// EXTRQ / INSERTQ as AMD's manual gives them: a length of 0 is 64.
#[test]
fn sse4a_bit_fields() {
assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 8, 16), 0xBC);
assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 0, 0), 0x1234_5678_9ABC_DEF0);
assert_eq!(extrq(0x8000_0000_0000_0000, 1, 63), 1);
assert_eq!(insertq(0xFFFF_FFFF_FFFF_FFFF, 0xAB, 8, 8), 0xFFFF_FFFF_FFFF_ABFF);
assert_eq!(insertq(0, 0x1FF, 4, 60), 0xF000_0000_0000_0000);
assert_eq!(insertq(0x1111, 0xDEAD_BEEF_0000_0000, 0, 0), 0xDEAD_BEEF_0000_0000);
for (v, len, idx) in [(0x0123_4567_89AB_CDEFu64, 12u8, 20u8), (u64::MAX, 63, 1), (0x55, 3, 0)] {
assert_eq!(extrq(insertq(0, v, len, idx), len, idx), extrq(v, len, 0));
}
}
#[test]
fn decodes_the_console_only_instructions() {
assert_eq!(decode(&[0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 3)));
// clzero loop against r10 (4C 39 D0 = cmp rax, r10)
assert_eq!(
decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4]),
Some((ConsoleOnly::ClzeroLoop { end_reg: 10 }, 12))
);
// clzero loop against rdx (48 39 D0 = cmp rax, rdx)
assert_eq!(
decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]),
Some((ConsoleOnly::ClzeroLoop { end_reg: 2 }, 12))
);
// the same loop after an address-size prefix: that one CLZERO alone
assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 4)));
assert_eq!(decode(&[0x0F, 0x01, 0xFD]), Some((ConsoleOnly::Rdpru, 3)));
assert_eq!(decode(&[0x0F, 0x01, 0xFA]), Some((ConsoleOnly::Monitorx, 3)));
assert_eq!(decode(&[0x0F, 0x01, 0xFB]), Some((ConsoleOnly::Mwaitx, 3)));
assert_eq!(decode(&[0x0F, 0x0B]), Some((ConsoleOnly::Ud2, 2)));
// clwb [rax]; clwb [rcx+0x40]; clwb [rsp+8]; clwb [rip+disp32]; clwb [r8]
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 4)));
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x71, 0x40]), Some((ConsoleOnly::Clwb, 5)));
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24, 0x08]), Some((ConsoleOnly::Clwb, 6)));
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x35, 1, 2, 3, 4]), Some((ConsoleOnly::Clwb, 8)));
assert_eq!(decode(&[0x66, 0x41, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 5)));
// rdpid rax; rdpid r9
assert_eq!(decode(&[0xF3, 0x0F, 0xC7, 0xF8]), Some((ConsoleOnly::Rdpid(0), 4)));
assert_eq!(decode(&[0xF3, 0x41, 0x0F, 0xC7, 0xF9]), Some((ConsoleOnly::Rdpid(9), 5)));
// not console-only: clflushopt (/7), xsaveopt (no 66), a plain mov, truncated bytes
// SSE4a, as a retail game has it (#216: insertq xmm0, xmm1 with length / index bytes)
assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10]), Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 8, idx: 16 }, 6)));
assert_eq!(decode(&[0xF2, 0x45, 0x0F, 0x79, 0xC1]), Some((ConsoleOnly::Insertq { dst: 8, src: 9, reg: true, len: 0, idx: 0 }, 5)));
assert_eq!(decode(&[0x66, 0x0F, 0x78, 0xC2, 0x04, 0x08]), Some((ConsoleOnly::Extrq { dst: 2, src: None, len: 4, idx: 8 }, 6)));
assert_eq!(decode(&[0x66, 0x0F, 0x79, 0xCA]), Some((ConsoleOnly::Extrq { dst: 1, src: Some(2), len: 0, idx: 0 }, 4)));
assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08]), None, "an immediate missing");
assert_eq!(decode(&[0x0F, 0x78, 0xC1, 0x08, 0x10]), None, "VMREAD without a prefix is not SSE4a");
// prefixes as a Zen 5 runs them (Kalmarv on #209): the last of F2 / F3 decides, 66 next
// to them does not; 0x67 and a REX before a legacy prefix are ignored
let insertq = Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 16, idx: 16 }, 7));
for code in [[0x66, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF2, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x67, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10]] {
assert_eq!(decode(&code), insertq, "{code:02x?}");
}
for code in [[0xF2, 0xF3, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x66, 0xF3, 0x0F, 0x78, 0xC0, 0x10, 0x10]] {
assert_eq!(decode(&code), None, "#UD on the CPU: {code:02x?}");
}
assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 4)));
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x38]), None);
assert_eq!(decode(&[0x0F, 0xAE, 0x30]), None);
assert_eq!(decode(&[0x48, 0x8B, 0x01]), None);
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24]), None);
assert_eq!(decode(&[0x0F]), None);
}
}
+9
View File
@@ -357,6 +357,15 @@ unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option<usize> {
}
unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
// an instruction of the console's CPU this one lacks: emulated, the title goes on
// SAFETY: the system passes valid exception pointers.
if unsafe { (*(*info).ExceptionRecord).ExceptionCode } == EXCEPTION_ILLEGAL_INSTRUCTION {
// SAFETY: the faulting thread's context, for the exception being dispatched.
let r = unsafe { crate::console_insn::emulate(&mut *(*info).ContextRecord) };
if r != 0 {
return r;
}
}
// SAFETY: the system passes valid exception pointers.
if unsafe { emulate_amd_only(info) } {
return -1; // EXCEPTION_CONTINUE_EXECUTION
+1
View File
@@ -22,6 +22,7 @@
//! on, pass every thread start and end on to the attached images.
#[cfg(windows)]
mod console_insn;
mod crash;
pub mod prepare;
pub mod resolve;
+696
View File
@@ -0,0 +1,696 @@
//! The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and
//! `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the
//! instruction returns for one ray and one node. The emitter lowers the
//! instruction to the same arithmetic in the same order
//! (`emit/intersect.rs`), so its code can be compared against this dword
//! for dword.
//!
//! The instruction tests one ray against one 64-byte node of a bounding
//! volume hierarchy and returns four dwords. Traversal (the stack, instance
//! transforms, culling, the hit distance `numerator / denominator`) is the
//! program's own code.
//!
//! # Node pointers
//!
//! A node pointer's low three bits are the node's kind, the rest its byte
//! offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the
//! base address of the descriptor (40 bits in dword 0 and the low byte of
//! dword 1, in 256-byte units). The 32-bit form takes a 32-bit pointer;
//! the 64-bit form a 64-bit one, with which a program uses one descriptor
//! with base 0 for every structure and adds `address >> 3` itself.
//!
//! | kind | node |
//! |---|---|
//! | 0-3 | triangle 0-3 of a triangle node |
//! | 4 | box node, 16-bit floats (64 bytes) |
//! | 5 | box node, 32-bit floats (128 bytes) |
//! | 6 | instance: not read by the instruction |
//! | 7 | procedural primitive: not read by the instruction |
//!
//! # Box nodes
//!
//! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four
//! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16
//! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes
//! 112-127 are not read). The result is the pointers of the children whose
//! box the ray enters before its extent, nearest entry first when the
//! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest.
//!
//! # Triangle nodes
//!
//! Five vertices of three 32-bit floats at bytes 0-59 and a dword at byte
//! 60 with one byte per triangle: bits 1:0 name the triangle's vertex that
//! barycentric I weighs, bits 3:2 the one J weighs (the builder stores an
//! input triangle's second vertex at the former, its third at the latter
//! and its first at the remaining one, so I and J are the weights of the
//! input triangle's second and third vertices). Triangle `k` of the node
//! uses the node's vertices [`TRIANGLE_VERTICES`]`[k]`. A program that
//! keeps fewer triangles in a node uses the bytes of the unused vertices
//! for its own data.
//!
//! With the descriptor's triangle return mode set (bit 120) the result is
//! the hit distance's numerator, its denominator, and the numerators of I
//! and J over the same denominator, as floats. The denominator is positive
//! for a triangle whose vertices run clockwise seen from the ray's origin
//! in a left-handed coordinate system. A miss returns +infinity, 1.0, 0, 0.
//! The ray's extent is not tested for triangles.
//!
//! # Where this comes from
//!
//! The node formats, the descriptor bits and the tests are those of the
//! public software emulation of this instruction in the open-source Vulkan
//! driver for this GPU family (box test and sorting network as there; the
//! triangle test is the watertight one it uses, Woop, Benthin and Wald,
//! JCGT 2013), and agree with what Grand Theft Auto VI's own structure
//! builder writes and its trace programs read. Not known from either: how
//! the console rounds, which of two boxes entered at the same distance it
//! returns first, and what it returns for a ray exactly through an edge
//! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here:
//! a triangle miss; the title's programs do not read it).
/// The result dword for a box the ray misses, or a child that is not there.
pub const NONE: u32 = 0xffff_ffff;
/// The node's vertices that make triangle 0-3, by the triangle's own
/// vertex numbers 0-2.
pub const TRIANGLE_VERTICES: [[u32; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]];
/// Descriptor dword 1: boxes are returned nearest first.
pub const BOX_SORT: u32 = 1 << 31;
/// Descriptor dword 3: triangles return the numerators of I and J (clear:
/// a triangle id and a hit status, which nothing here produces).
pub const RETURN_BARYCENTRICS: u32 = 1 << 24;
/// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing
/// structure.
pub const DESCRIPTOR_TYPE: u32 = 8;
/// The ray as the instruction takes it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ray {
pub extent: f32,
pub origin: [f32; 3],
pub direction: [f32; 3],
/// What the program computed as `1 / direction`.
pub inverse: [f32; 3],
}
impl Ray {
/// A ray with the inverse direction a program computes by division.
pub fn new(origin: [f32; 3], direction: [f32; 3], extent: f32) -> Self {
Self {
extent,
origin,
direction,
inverse: direction.map(|d| 1.0 / d),
}
}
}
/// The kind of the node a pointer names.
pub fn kind(pointer: u64) -> u32 {
(pointer & 7) as u32
}
/// The byte address of the node `pointer` names, for a descriptor whose
/// first two dwords are `word0` and `word1`.
pub fn node_address(word0: u32, word1: u32, pointer: u64) -> u64 {
let base = (u64::from(word1 & 0xff) << 32 | u64::from(word0)) << 8;
base.wrapping_add((pointer >> 3) << 6)
}
/// What the instruction returns for the node at `words` (its first 28
/// dwords; a 64-byte node's dwords 16-27 are not read) named by a pointer
/// of this `kind`, with box sorting as `sort` says and the triangle return
/// mode set.
pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4] {
match kind & 7 {
4 => boxes(&children(words), &boxes16(words), ray, sort),
5 => boxes(&children(words), &boxes32(words), ray, sort),
k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits),
_ => MISS.map(f32::to_bits),
}
}
/// A box node's four child pointers.
pub fn children(words: &[u32; 28]) -> [u32; 4] {
[words[0], words[1], words[2], words[3]]
}
/// The four boxes of a 16-bit box node: minimum x y z, maximum x y z.
pub fn boxes16(words: &[u32; 28]) -> [[f32; 6]; 4] {
std::array::from_fn(|b| {
std::array::from_fn(|k| {
let half = 6 * b + k;
half_to_f32((words[4 + half / 2] >> (16 * (half % 2))) as u16)
})
})
}
/// The four boxes of a 32-bit box node.
pub fn boxes32(words: &[u32; 28]) -> [[f32; 6]; 4] {
std::array::from_fn(|b| std::array::from_fn(|k| f32::from_bits(words[4 + 6 * b + k])))
}
/// [`TRIANGLE_VERTICES`] of triangle `k` in four bits each, vertex 0 lowest
/// (as the public descriptions of the format give it: 0x210, 0x231, 0x432,
/// 0x042).
pub fn vertex_map(k: u32) -> u32 {
let v = TRIANGLE_VERTICES[(k & 3) as usize];
v[0] | v[1] << 4 | v[2] << 8
}
/// The vertices of triangle `k` (0-3) of a triangle node, the first being
/// the one neither barycentric weighs, then I's, then J's.
pub fn triangle_vertices(words: &[u32; 28], k: u32) -> [[f32; 3]; 3] {
let id = words[15] >> (8 * k);
let (i, j) = (id & 3, id >> 2 & 3);
// An id naming one vertex twice, or a vertex 3, is malformed; it reads
// what this arithmetic lands on (a vertex of the node), as the emitted
// code does.
let first = 3u32.wrapping_sub(i).wrapping_sub(j) & 3;
[first, i, j].map(|n| {
let vertex = (vertex_map(k) >> (4 * n) & 0xf) as usize;
std::array::from_fn(|c| f32::from_bits(words[3 * vertex + c]))
})
}
/// The box test: child pointers of the boxes the ray enters, `NONE` for
/// the others; sorted by entry distance when `sort`, in child order
/// otherwise.
pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) -> [u32; 4] {
// An infinite inverse (a direction component of 0) would turn an
// origin exactly on a box's face into a NaN. (Maximum then minimum, as
// the emitted code: a NaN becomes the lower bound, where `clamp` would
// keep it.)
#[allow(clippy::manual_clamp)]
let inverse = ray.inverse.map(|x| x.max(-f32::MAX).min(f32::MAX));
let mut ids = [NONE; 4];
let mut distances = [f32::INFINITY; 4];
for (n, b) in boxes.iter().enumerate() {
let (mut near, mut far) = ([0f32; 3], [0f32; 3]);
for a in 0..3 {
let low = (b[a] - ray.origin[a]) * inverse[a];
let high = (b[3 + a] - ray.origin[a]) * inverse[a];
near[a] = low.min(high);
far[a] = low.max(high);
}
let enter = near[0].max(near[1]).max(near[2]);
let leave = far[0].min(far[1]).min(far[2]);
// A box whose minimum x is NaN is switched off.
if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent {
ids[n] = children[n];
distances[n] = enter;
}
}
if sort {
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
if distances[b] < distances[a] {
distances.swap(a, b);
ids.swap(a, b);
}
}
}
ids
}
/// What a triangle the ray misses returns.
pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0];
/// The triangle test: the hit distance's numerator, the denominator, and
/// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise.
/// Watertight: the vertices are sheared so the ray runs along its largest
/// axis, and the signs of the three edge functions decide, so a ray
/// between two triangles that share an edge cannot miss both. Any NaN
/// misses, and so does a triangle seen edge-on.
pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] {
let d = ray.direction;
let size = d.map(f32::abs);
// The largest axis, and the other two in an order that keeps the
// triangle's winding.
let kz = if size[0] >= size[1] {
if size[0] >= size[2] { 0 } else { 2 }
} else if size[1] >= size[2] {
1
} else {
2
};
let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3);
if d[kz] < 0.0 {
std::mem::swap(&mut kx, &mut ky);
}
let sz = ray.inverse[kz];
let (sx, sy) = (d[kx] * sz, d[ky] * sz);
let sheared = |v: &[f32; 3]| {
let r = [
v[0] - ray.origin[0],
v[1] - ray.origin[1],
v[2] - ray.origin[2],
];
(r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz])
};
let (ax, ay, az) = sheared(&p[0]);
let (bx, by, bz) = sheared(&p[1]);
let (cx, cy, cz) = sheared(&p[2]);
let u = cx * by - cy * bx;
let v = ax * cy - ay * cx;
let w = bx * ay - by * ax;
let behind = u < 0.0 || v < 0.0 || w < 0.0;
let before = u > 0.0 || v > 0.0 || w > 0.0;
let det = u + (v + w);
let t = (u * az + v * bz) + w * cz;
let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0;
if !(behind && before) && ahead {
[t, det, v, w]
} else {
MISS
}
}
/// A 16-bit float as a 32-bit one (exact).
pub fn half_to_f32(h: u16) -> f32 {
let sign = u32::from(h >> 15) << 31;
let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff));
let bits = match exponent {
0 if mantissa == 0 => sign,
0 => {
// Subnormal: normalise.
let shift = mantissa.leading_zeros() - 21;
sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13
}
0x1f => sign | 0xff << 23 | mantissa << 13,
e => sign | (e + 112) << 23 | mantissa << 13,
};
f32::from_bits(bits)
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
/// The smallest 16-bit float not below `x` (`up`) or not above it.
pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 {
let mut best: Option<u16> = None;
for h in 0..=0xffffu16 {
let f = half_to_f32(h);
if f.is_nan() || if up { f < x } else { f > x } {
continue;
}
best = match best {
Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b),
_ => Some(h),
};
}
best.expect("a half")
}
/// A 32-bit box node.
pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
let mut w = [0u32; 28];
w[..4].copy_from_slice(&children);
for (b, bx) in boxes.iter().enumerate() {
for (k, x) in bx.iter().enumerate() {
w[4 + 6 * b + k] = x.to_bits();
}
}
w
}
/// A 16-bit box node holding `boxes` rounded outward.
pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
let mut w = [0u32; 28];
w[..4].copy_from_slice(&children);
for (b, bx) in boxes.iter().enumerate() {
for (k, x) in bx.iter().enumerate() {
let half = 6 * b + k;
let h = if x.is_nan() {
0x7e00
} else {
f32_to_half(*x, k >= 3)
};
w[4 + half / 2] |= u32::from(h) << (16 * (half % 2));
}
}
w
}
/// A triangle node: up to five vertices, and the dword at byte 60.
pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] {
let mut w = [0u32; 28];
for (n, v) in vertices.iter().enumerate() {
for (c, x) in v.iter().enumerate() {
w[3 * n + c] = x.to_bits();
}
}
w[15] = id;
w
}
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] {
std::array::from_fn(|k| b[k] + by[k % 3])
}
const OFF: [f32; 6] = [f32::NAN; 6];
#[test]
fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() {
// The 64-bit form as the title uses it: base 0, the structure's
// address folded into the pointer.
let structure = 0x12_3456_7800u64;
let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5);
assert_eq!(kind(pointer), 5);
assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40);
// The 32-bit form: the base in the descriptor.
let word0 = (structure >> 8) as u32;
let word1 = (structure >> 40) as u32 | BOX_SORT;
assert_eq!(
node_address(word0, word1, 0x1000 >> 3 | 4),
structure + 0x1000
);
// A base past 4 GiB of 256-byte units.
assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64);
}
#[test]
fn halves_convert_exactly() {
assert_eq!(half_to_f32(0x3c00), 1.0);
assert_eq!(half_to_f32(0xc000), -2.0);
assert_eq!(half_to_f32(0x7c00), f32::INFINITY);
assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24));
assert_eq!(half_to_f32(0x7bff), 65504.0);
assert!(half_to_f32(0x7e00).is_nan());
assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000);
// Outward rounding of the test helper.
assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1);
assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1);
}
#[test]
fn boxes_are_returned_nearest_first_and_misses_last() {
let children = [0x105, 0x20c, 0x304, 0x400];
// Along +x from the origin: boxes at x = 30, 10, (off axis), 20.
let node = box32(
children,
[
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 ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]);
// Without sorting: child order, the miss in its place.
assert_eq!(
intersect(&node, 5, &ray, false),
[0x105, 0x20c, NONE, 0x400]
);
// The extent cuts the far ones off (entered at 9, 19, 29).
let short = Ray {
extent: 19.5,
..ray
};
assert_eq!(
intersect(&node, 5, &short, true),
[0x20c, 0x400, NONE, NONE]
);
// An entry exactly at the extent is no hit.
let exact = Ray {
extent: 19.0,
..ray
};
assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]);
// Backwards: nothing.
let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0);
assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]);
}
#[test]
fn a_ray_starting_inside_a_box_enters_it_at_its_origin() {
let node = box32(
[8, 16, NONE, NONE],
[UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF],
);
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0);
// Box 0 is entered at -1 (behind the origin), box 1 at 2.
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]);
// Even with a tiny extent the box around the origin is a hit.
let tiny = Ray {
extent: 1e-6,
..ray
};
assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]);
}
#[test]
fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() {
let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]);
// Direction components of 0: the inverse is infinite.
let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
assert!(ray.inverse[1].is_infinite());
// The origin lies in the plane of the box's -y face: (-1 - -1) x inf
// would be a NaN; with the inverse held finite it is 0, and the ray
// running along the face is inside.
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
// Along the +y face it is outside: the face's plane is left at 0
// and the box is entered at 4 (as the public emulation has it).
let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]);
let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]);
// -0 gives -infinity.
let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0);
assert_eq!(minus.inverse[1], f32::NEG_INFINITY);
assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]);
}
#[test]
fn a_box_switched_off_and_a_missing_child_return_none() {
let node = box32(
[8, NONE, 24, 32],
[UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF],
);
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
// Child 1 is hit but is not there: its pointer is what "none" is.
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
}
#[test]
fn equal_distances_keep_child_order() {
let node = box32([8, 16, 24, 32], [UNIT; 4]);
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]);
}
#[test]
fn half_float_boxes_test_like_their_widened_values() {
let boxes = [
moved(UNIT, [30.0, 0.1, 0.0]),
moved(UNIT, [10.0, 0.0, 0.3]),
moved(UNIT, [10.0, 5.0, 0.0]),
moved(UNIT, [20.7, 0.0, 0.0]),
];
let children = [0x105, 0x20c, 0x304, 0x400];
let node = box16(children, boxes);
let wide = boxes16(&node);
for (w, b) in wide.iter().zip(&boxes) {
for k in 0..3 {
assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward");
}
}
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]);
assert_eq!(
intersect(&node, 4, &ray, true),
intersect(&box32(children, wide), 5, &ray, true)
);
}
/// The hit a result describes: distance, I, J, front face.
fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> {
let [t, det, i, j] = r.map(f32::from_bits);
(t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0))
}
/// Clockwise seen from the origin looking down +z in a left-handed
/// system (x right, y up): the front face.
const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
#[test]
fn a_triangle_returns_distance_and_weights_over_one_denominator() {
let node = triangles(&TRIANGLE, 9);
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
assert_eq!(t, 5.0);
// (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2.
assert_eq!((i, j), (0.25, 0.25));
assert!(front);
// Near vertex 1: I near 1.
let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0);
let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
assert!(i > 0.85 && j < 0.1, "{i} {j}");
// From behind: the same weights, the back face.
let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0);
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false));
// An unnormalised direction: the distance is in its units.
let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0);
assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25);
}
#[test]
fn a_triangle_is_missed_beside_behind_and_edge_on() {
let node = triangles(&TRIANGLE, 9);
let miss = MISS.map(f32::to_bits);
// Beside it.
let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&node, 0, &ray, true), miss);
// It lies behind the origin.
let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&node, 0, &ray, true), miss);
// In its plane.
let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 0, &ray, true), miss);
// A triangle with no area.
let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9);
let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&flat, 0, &ray, true), miss);
// A vertex that is not a number, a direction of zero.
let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9);
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&nan, 0, &ray, true), miss);
let still = Ray::new([0.0; 3], [0.0; 3], 100.0);
assert_eq!(intersect(&node, 0, &still, true), miss);
// The extent is the program's to test: a far triangle is a hit.
let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0);
assert!(hit(intersect(&node, 0, &short, true)).is_some());
}
#[test]
fn a_ray_through_a_shared_edge_misses_neither_triangle() {
// Two triangles of a quad sharing the diagonal, wound alike.
let quad = [
[-1.0, -1.0, 4.0],
[-1.0, 1.0, 4.0],
[1.0, 1.0, 4.0],
[1.0, -1.0, 4.0],
];
let first = triangles(&[quad[0], quad[1], quad[2]], 9);
let second = triangles(&[quad[0], quad[2], quad[3]], 9);
// A fan of rays crossing the diagonal, some exactly on it.
for n in -40..=40 {
let x = n as f32 / 64.0;
for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] {
for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] {
// Aim at (ox, oy, 4).
let s = 4.0 / d[2];
let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0);
let a = hit(intersect(&first, 0, &ray, true));
let b = hit(intersect(&second, 0, &ray, true));
assert!(
a.is_some() || b.is_some(),
"a hole at {ox} {oy} along {d:?}"
);
for h in [a, b].into_iter().flatten() {
assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}");
}
}
}
}
}
#[test]
fn the_id_dword_says_which_vertices_the_weights_belong_to() {
// What the title's builder does with an input triangle (a, b, c)
// and an id byte: a at the vertex neither field names, b at I's,
// c at J's.
let [a, b, c] = TRIANGLE;
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] {
let mut stored = [[0f32; 3]; 3];
stored[(3 - i - j) as usize] = a;
stored[i as usize] = b;
stored[j as usize] = c;
let node = triangles(&stored, i | j << 2);
assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}");
}
// The higher bits of the byte (opaque and the like) change nothing.
let node = triangles(&[a, b, c], 9 | 0x80);
assert_eq!(intersect(&node, 0, &ray, true), plain);
}
#[test]
fn triangles_one_to_three_take_their_vertices_and_their_id_byte() {
let [a, b, c] = TRIANGLE;
let far = [50.0, 50.0, 50.0];
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
for k in 1..4u32 {
// Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`.
let mut vertices = [far; 5];
let at = TRIANGLE_VERTICES[k as usize];
vertices[at[0] as usize] = a;
vertices[at[1] as usize] = b;
vertices[at[2] as usize] = c;
// Triangle 0's byte would be malformed here; only byte k counts.
let node = triangles(&vertices, 9 << (8 * k));
assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}");
}
// A pair as the title's builder stores it: the second triangle's
// own vertex at node vertex 3, named by I.
let d = [2.0, 2.0, 5.0];
// Input triangles (a, b, c) and (a, d, b): they share a and b.
let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8);
// Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2.
let got = triangle_vertices(&node, 1);
assert_eq!(got, [b, d, c]);
}
#[test]
fn instances_and_procedural_nodes_return_a_triangle_miss() {
let node = triangles(&TRIANGLE, 9);
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
for k in [6, 7] {
assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits));
}
}
#[test]
fn the_largest_axis_and_its_sign_do_not_change_the_answer() {
// The same triangle and ray turned so the ray's largest axis is each
// of the three, forwards and backwards. Both turns are rotations,
// so the facing stays.
let turn = |v: [f32; 3], axis: usize, flip: bool| {
let mut r = v;
for _ in 0..axis {
r = [r[2], r[0], r[1]];
}
if flip {
// Half a turn about the axis after the largest one's next.
let largest = (2 + axis) % 3;
r[largest] = -r[largest];
r[(largest + 1) % 3] = -r[(largest + 1) % 3];
}
r
};
let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0);
let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit");
for axis in 0..3 {
for flip in [false, true] {
let p = TRIANGLE.map(|v| turn(v, axis, flip));
let r = Ray::new(
turn(ray.origin, axis, flip),
turn(ray.direction, axis, flip),
100.0,
);
let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit");
assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}");
assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5);
assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}");
}
}
}
}
+32 -2
View File
@@ -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() {
+66 -9
View File
@@ -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(),
}
}
+557
View File
@@ -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 &regs {
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(|_| ())),
}
}
File diff suppressed because it is too large. Load diff
+828 -10
View File
@@ -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());
}
}
+484
View File
@@ -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");
}
}
}
+196 -5
View File
@@ -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,
+218
View File
@@ -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());
}
}
+329 -7
View File
@@ -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())
+296 -23
View File
@@ -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 = &sections(&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 = &sections(&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);
}
}
}
+3 -1
View File
@@ -11,7 +11,9 @@ use super::{Encoding, Instruction};
pub enum Operand {
/// Scalar registers by operand code: 0-105 `s0`-`s105`, 106/107
/// `vcc_lo`/`vcc_hi`, 108-123 `ttmp0`-`ttmp15`, 124 `m0`, 125 `null`,
/// 126/127 `exec_lo`/`exec_hi`.
/// 126/127 `exec_lo`/`exec_hi`. The decoder gives no code above 127; the
/// IR names scalars parked in VGPR lanes by the codes from 128 up
/// (`crate::ir::PARKED`).
Scalar {
code: u8,
dwords: u8,
+144 -18
View File
@@ -33,7 +33,7 @@
use crate::ShaderError;
use crate::gfx10::{Fields, Operand};
use crate::ir::{Inst, Program, Reg, Value};
use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads};
use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage};
use crate::resource::Site;
@@ -138,6 +138,11 @@ pub enum Interp {
/// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10,
/// 1 for P20, 2 for P0 (the provoking vertex).
Vertex { attribute: Attribute, vertex: u8 },
/// A half of an interpolation whose i or j is computed rather than
/// loaded: each half evaluates as the hardware does, from the
/// attribute's vertex values (`v_interp_p1*`: P0 + i P10, with P10 =
/// P1 - P0; `v_interp_p2*`: its old dst + j P20, with P20 = P2 - P0).
Weighted { attribute: Attribute },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -238,13 +243,52 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
(loaded, &[][..], &[][..])
}
(StageIo::Ms(ms), HwStage::Ms) => {
let group = p.inputs.iter().find(|i| i.0 == Reg::V(5)).map(|i| i.1);
// The group input, and the phis that may carry it past a join.
let mut group: Vec<Value> = p
.inputs
.iter()
.filter(|i| i.0 == Reg::V(5))
.map(|i| i.1)
.collect();
// No lane is active over the EXEC-zero edge of s_cbranch_execz or
// _execnz, the same case as a partial-EXEC write below.
let no_lanes = |q: usize, b: usize| match (
p.blocks[q].insts.last().map(Inst::name),
p.blocks[q].exit,
) {
(Some("s_cbranch_execz"), Exit::Branch { taken, not_taken }) => {
taken == b && not_taken != b
}
(Some("s_cbranch_execnz"), Exit::Branch { taken, not_taken }) => {
not_taken == b && taken != b
}
_ => false,
};
while let Some(v) = p
.blocks
.iter()
.enumerate()
.flat_map(|(b, k)| k.phis.iter().map(move |f| (b, f)))
.find_map(|(b, f)| {
let mut args = f.args.iter().zip(&p.blocks[b].preds);
let carried = args.any(|(a, &q)| group.contains(a) && !no_lanes(q, b));
(carried && !group.contains(&f.value)).then_some(f.value)
})
{
group.push(v);
}
// The group input holds the same value in every lane only as the
// first lane reads it; a VGPR write reads its old value too.
// first lane reads it. A write to v5 reads its old value too, which
// only lanes outside EXEC keep.
// shortcut: writes that may keep the old v5 in active lanes
// (v_fmac_f32's accumulator, a 16-bit half or d16 load,
// v_writelane_b32, v_movreld_b32, DPP that skips lanes) and
// partial-EXEC writes pass; check those too if a mesh program
// writes v5 that way.
let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| {
group.is_some_and(|g| i.reads.contains(&(Reg::V(5), g)))
i.read(Reg::V(5)).is_some_and(|v| group.contains(&v))
&& i.name() != "v_readfirstlane_b32"
&& i.write(Reg::V(5)).is_none()
&& (i.write(Reg::V(5)).is_none() || operand_reads(p, i).contains(&Reg::V(5)))
});
if let Some(i) = per_lane {
return Err(unsupported(
@@ -352,7 +396,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
&barycentric,
)
.map_err(|what| unsupported(at, what))?;
io.interps.push((site, interp.with(attribute)));
push_pair(&mut io, site, interp, attribute);
}
_ => return Err(unsupported(at, "an interpolation form")),
}
@@ -368,7 +412,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
let interp = halves
.pair(&v.src[0], read(2), read(1), &barycentric)
.map_err(|what| unsupported(at, what))?;
io.interps.push((site, interp.with(attribute)));
push_pair(&mut io, site, interp, attribute);
}
_ => return Err(unsupported(at, "an interpolation form")),
},
@@ -439,22 +483,39 @@ fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> {
out
}
/// An interpolation before its attribute is known.
/// An interpolation before its attribute is known: `barycentric` none
/// when i or j is computed.
struct Pair {
barycentric: Barycentric,
barycentric: Option<Barycentric>,
first: Vec<Site>,
}
impl Pair {
fn with(self, attribute: Attribute) -> Interp {
Interp::Interpolated {
attribute,
barycentric: self.barycentric,
first: self.first,
match self.barycentric {
Some(barycentric) => Interp::Interpolated {
attribute,
barycentric,
first: self.first,
},
None => Interp::Weighted { attribute },
}
}
}
/// Records interpolation `pair` at `site`, and its first halves too when
/// they evaluate on their own (computed barycentrics).
fn push_pair(io: &mut Io, site: Site, pair: Pair, attribute: Attribute) {
if pair.barycentric.is_none() {
for &f in &pair.first {
if !io.interps.iter().any(|(s, _)| *s == f) {
io.interps.push((f, Interp::Weighted { attribute }));
}
}
}
io.interps.push((site, pair.with(attribute)));
}
/// Finds the first halves of interpolations.
struct Halves<'a> {
p: &'a Program,
@@ -465,7 +526,9 @@ struct Halves<'a> {
impl Halves<'_> {
/// The interpolation whose second half reads the first half's result
/// `acc`, the barycentric `j`, and attribute `attr`: every first half
/// must read the same attribute channel and the same kind's i.
/// must read the same attribute channel. With j and every first half's
/// i loaded as one kind's, the pair interpolates with that kind;
/// otherwise each half evaluates on its own (`Interp::Weighted`).
fn pair(
&self,
attr: &Operand,
@@ -479,8 +542,9 @@ impl Halves<'_> {
&mut Vec::new(),
&mut first,
)?;
let Some((kind, 1)) = barycentric(j) else {
return Err("an interpolation with computed barycentrics");
let mut kind = match barycentric(j) {
Some((kind, 1)) => Some(kind),
_ => None,
};
for &(b, i) in &first {
let inst = &self.p.blocks[b].insts[i];
@@ -499,8 +563,8 @@ impl Halves<'_> {
if a != *attr {
return Err("interpolation halves of different attributes");
}
if barycentric(i) != Some((kind, 0)) {
return Err("an interpolation with computed barycentrics");
if kind.is_some_and(|k| barycentric(i) != Some((k, 0))) {
kind = None;
}
}
Ok(Pair {
@@ -634,6 +698,33 @@ mod tests {
assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err());
}
#[test]
fn computed_barycentrics_evaluate_each_half() {
// i scaled before the first half: both halves stand on their own.
let p = program(&[
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
S_ENDPGM,
]);
let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
let attribute = Attribute {
usage: Usage::Generic,
row: 1,
channel: 0,
high: false,
};
let mut interps = io.interps.clone();
interps.sort_by_key(|i| i.0);
assert_eq!(
interps,
[
((0, 1), Interp::Weighted { attribute }),
((0, 2), Interp::Weighted { attribute }),
]
);
}
#[test]
fn mesh_inputs_and_primitive_export() {
let mesh = |words: &[u32]| {
@@ -669,6 +760,41 @@ mod tests {
assert_eq!(io.exports[0].target, Target::Primitive);
// The group input is uniform only as the first lane reads it.
assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5
// Also as an operand of a write to v5, or after a join.
let per_lane: [&[u32]; 5] = [
&[0x4A0A_0305, S_ENDPGM], // v_add_nc_u32 v5, v5, v1
&[0x7E0A_0D05, S_ENDPGM], // v_cvt_f32_u32 v5, v5
&[0xDC30_8000, 0x0500_0005, S_ENDPGM], // global_load_dword v5, v5, s[0:1]
&[0x7E0A_CB01, S_ENDPGM], // v_swap_b32 v5, v1
&[
0xBF06_8001, // s_cmp_eq_u32 s1, 0
0xBF85_0001, // s_cbranch_scc1 -> 0xc
0x7E0A_0280, // v_mov_b32 v5, 0
0x7E02_0305, // 0xc: v_mov_b32 v1, v5
S_ENDPGM,
],
];
let accepted: Vec<_> = per_lane.iter().filter(|w| mesh(w).is_ok()).collect();
assert!(accepted.is_empty(), "accepted: {accepted:08X?}");
// Overwriting v5 reads the group input only for lanes outside EXEC:
// v_mov_b32 v5, 0; v_mov_b32 v1, v5.
assert!(mesh(&[0x7E0A_0280, 0x7E02_0305, S_ENDPGM]).is_ok());
// Skipping that write with s_cbranch_execz is the same case: under the
// same mask, the read sees only the 0.
let reuse = [
0x7E04_0505, // v_readfirstlane_b32 s2, v5
0x7D88_0084, // v_cmp_gt_u32 vcc, 4, v0
0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
0xBF88_0001, // s_cbranch_execz -> 0x14
0x7E0A_0280, // v_mov_b32 v5, 0
0x88FE_067E, // 0x14: s_or_b64 exec, exec, s[6:7]
0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
0xBF88_0001, // s_cbranch_execz -> 0x24
0x7E02_0305, // v_mov_b32 v1, v5
0x88FE_067E, // 0x24: s_or_b64 exec, exec, s[6:7]
S_ENDPGM,
];
assert_eq!(mesh(&reuse).map(|_| ()), Ok(()));
}
#[test]
+433 -18
View File
@@ -19,7 +19,9 @@ use crate::ShaderError;
use crate::gfx10::{self, Fields, Flow, Instruction, Operand};
/// One register dword. Scalar codes as in [`Operand::Scalar`]: 0-105 SGPRs,
/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC.
/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. Codes from
/// [`PARKED`] up are scalars the compiler parked in VGPR lanes (`unspill`):
/// no machine instruction names them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Reg {
S(u8),
@@ -30,6 +32,8 @@ pub enum Reg {
pub const VCC: u8 = 106;
pub const M0: u8 = 124;
pub const EXEC: u8 = 126;
/// The first scalar code past the machine's (0-127): see [`Reg`].
pub const PARKED: u8 = 128;
/// An SSA value: the content of one register dword (SCC: one bit).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -123,7 +127,7 @@ impl Inst {
/// count. Fails on instructions the IR cannot express yet
/// ([`ShaderError::Unsupported`]).
pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderError> {
let list = gfx10::decode(code)?;
let mut list = gfx10::decode(code)?;
let lanes = 1 + u8::from(wave64);
let isa = |offset, reason| ShaderError::Isa { offset, reason };
@@ -145,6 +149,7 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
}
leaders.sort_unstable();
leaders.dedup();
let parked = unspill(&mut list, &leaders, wave64, lanes, vgprs);
let block_at = |offset: usize| {
leaders
.binary_search(&offset)
@@ -164,13 +169,21 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
let next_offsets: Vec<Option<usize>> = (0..list.len())
.map(|i| list.get(i + 1).map(|n| n.offset))
.collect();
for ((machine, flow), next) in list.into_iter().zip(flows).zip(next_offsets) {
for (n, ((machine, flow), next)) in list.into_iter().zip(flows).zip(next_offsets).enumerate() {
let b = leaders.partition_point(|&l| l <= machine.offset) - 1;
let name = machine.name().ok_or(ShaderError::Unsupported {
offset: machine.offset,
what: "unknown opcode",
})?;
let fields = machine.fields(wave64);
let mut fields = machine.fields(wave64);
// A move to or from a scalar parked in a VGPR lane (`unspill`): its register
// codes may be ones the machine word cannot hold.
if let Ok(k) = parked.binary_search_by_key(&n, |m| m.0)
&& let Fields::Sop { dst: Some(Operand::Scalar { code: to, .. }), src, .. } = &mut fields
&& let Some(Operand::Scalar { code: from, .. }) = src.first_mut()
{
(*to, *from) = (parked[k].1, parked[k].2);
}
let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?);
let ends = flow != Flow::Next || next.is_none_or(|n| leaders.binary_search(&n).is_ok());
if ends {
@@ -185,7 +198,13 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
Flow::Stop => Exit::End,
};
}
if let Some((reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? {
if let Some((mut reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? {
// Lanes disabled in EXEC keep the old value.
for w in writes.iter().filter(|w| matches!(w, Reg::V(_))) {
if !reads.contains(w) {
reads.push(*w);
}
}
let unset = |regs: Vec<Reg>| regs.into_iter().map(|r| (r, NONE)).collect();
blocks[b].insts.push(Inst {
machine,
@@ -204,6 +223,230 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
}
split_irreducible(&mut blocks)?;
Ok(rename(blocks, wave64, vgprs))
}
/// Scalar registers the compiler parked in lanes of a VGPR, as scalar moves.
///
/// When it runs out of SGPRs the console compiler saves one in a lane of a
/// spare VGPR (`v_writelane_b32 vN, sX, K`) and takes it back later
/// (`v_readlane_b32 sX, vN, K`). A VGPR whose every use in the program is one
/// of those two forms with a constant lane is such a store: lane K of it is a
/// scalar register by another name. Each (VGPR, lane) gets a register code
/// the program does not use (the trap temporaries first, then SGPRs it never
/// names, then codes from [`PARKED`] up, which no machine word can hold), and
/// the save and the restore become `s_mov_b32` to and from it. Returns those
/// moves (index in `list`, destination code, source code) in order, for
/// `build` to put the codes into the decoded fields. They are then copies for
/// every later stage: a parked descriptor is traced to its load, and nothing
/// is left of a cross-lane operation, which a console wave run as two host
/// waves could not do where not every lane runs (the lane may be in the other
/// wave, or not running).
/// A register pair parked in two neighbouring lanes (a lane mask, a 64-bit
/// address) moves as a pair (`s_mov_b64`) when every save and every restore
/// of the two lanes come together, so a parked lane mask comes back as the
/// mask it is; otherwise its halves come back as two scalars.
fn unspill(
list: &mut [gfx10::Instruction],
leaders: &[usize],
wave64: bool,
lanes: u8,
vgprs: u16,
) -> Vec<(usize, u8, u8)> {
/// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`: (save, N, X, K).
fn parked(inst: &gfx10::Instruction, fields: &Fields) -> Option<(bool, u8, u8, u32)> {
let Fields::Valu(v) = fields else { return None };
if v.abs != 0 || v.neg != 0 || v.opsel != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some() || v.dpp.is_some() {
return None;
}
let lane = |op: &Operand| match *op {
Operand::Const(c @ 128..=191) => Some(u32::from(c) - 128),
_ => None,
};
match (inst.name()?, v.dst?, v.src.as_slice()) {
("v_writelane_b32", Operand::Vector { reg, .. }, [Operand::Scalar { code, .. }, k]) if *code < 105 => {
Some((true, reg, *code, lane(k)?))
}
("v_readlane_b32", Operand::Scalar { code, .. }, [Operand::Vector { reg, .. }, k]) if code < 105 => {
Some((false, *reg, code, lane(k)?))
}
_ => None,
}
}
// VGPRs used by parking alone, the scalar codes the program uses, and
// per instruction the scalar codes it writes.
let mut stores = [false; 256];
let mut other = [false; 256];
let mut used = [false; 128];
let mut parks: Vec<Option<(bool, u8, u8, u32)>> = Vec::with_capacity(list.len());
let mut written: Vec<Vec<u8>> = Vec::with_capacity(list.len());
for inst in list.iter() {
let Some(name) = inst.name() else { return Vec::new() };
let fields = inst.fields(wave64);
let park = parked(inst, &fields);
let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else {
return Vec::new();
};
let mut codes = Vec::new();
if let Some((reads, writes)) = effects {
for &reg in &writes {
if let Reg::S(c) = reg {
codes.push(c);
}
}
for reg in reads.into_iter().chain(writes) {
match reg {
Reg::S(c) => used[usize::from(c)] = true,
Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true,
Reg::V(r) => other[usize::from(r)] = true,
Reg::Scc => {}
}
}
}
parks.push(park);
written.push(codes);
}
for (i, park) in parks.iter_mut().enumerate() {
if park.is_some_and(|p| other[usize::from(p.1)]) {
*park = None;
}
let _ = i;
}
if parks.iter().all(Option::is_none) {
return Vec::new();
}
let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok();
// Lane pairs (register, lower lane) that always move together: each
// save of the lower lane is followed, in the same block and before its
// register changes, by the save of the next register into the next
// lane; each restore of the lower lane is followed at once by the
// restore of the next lane into the next register.
// The second save may come any number of instructions after the first (the
// compiler puts loads and constants between the two: five instructions later
// in the ped mesh programs). Only wave64 programs have pairs: a wave32 mask
// is one dword, and a pair move of it with its neighbour would hide it.
let mut slots: Vec<(u8, u32)> = parks.iter().flatten().map(|p| (p.1, p.3)).collect();
slots.sort_unstable();
slots.dedup();
// instruction -> the instruction that completes its pair
let partner = |i: usize| -> Option<usize> {
let (save, reg, code, lane) = parks[i]?;
if save {
let mut j = i + 1;
while j < list.len() && !leader(j) {
if parks[j] == Some((true, reg, code + 1, lane + 1)) {
return Some(j);
}
if parks[j].is_some_and(|p| p.1 == reg && (p.3 == lane || p.3 == lane + 1))
|| written[j].contains(&code)
|| written[j].contains(&(code + 1))
{
return None;
}
j += 1;
}
None
} else {
let j = i + 1;
(j < list.len() && !leader(j) && parks[j] == Some((false, reg, code + 1, lane + 1))).then_some(j)
}
};
let mut pairs: Vec<(u8, u32)> = Vec::new();
for &(reg, lane) in &slots {
if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) {
continue;
}
let lower: Vec<usize> = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect();
let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count();
let partners: Vec<Option<usize>> = lower.iter().map(|&i| partner(i)).collect();
let mut distinct: Vec<usize> = partners.iter().flatten().copied().collect();
distinct.sort_unstable();
distinct.dedup();
if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() {
pairs.push((reg, lane));
}
}
// Codes for the parked scalars: the trap temporaries (108..=123), then
// user SGPRs the program never names, from the top, then the codes past
// the machine's (`PARKED`..=254; 255 stays unused so that the code after a
// parked one always exists). A material resolve program parks up to 63
// scalars and leaves about 20 machine codes unused.
let past = usize::from(PARKED);
let mut free = [false; 256];
for c in (0..105).chain(108..=123) {
free[c] = !used[c];
}
free[past..255].fill(true);
let mut codes: Vec<((u8, u32), u8)> = Vec::new();
for &(reg, lane) in &pairs {
let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]);
// Not enough spare codes: leave the program as it is.
let Some(c) = at else { return Vec::new() };
(free[c], free[c + 1]) = (false, false);
codes.push(((reg, lane), c as u8));
codes.push(((reg, lane + 1), c as u8 + 1));
}
for &slot in &slots {
if codes.iter().any(|c| c.0 == slot) {
continue;
}
let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else {
return Vec::new();
};
free[c] = false;
codes.push((slot, c as u8));
}
let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1);
let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| {
list[i] = gfx10::Instruction {
offset: list[i].offset,
encoding,
opcode,
words: vec![word],
};
};
// `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code
// from `PARKED` up does not fit the word: s0 stands in for it there.
let field = |code: u8| if code < PARKED { u32::from(code) } else { 0 };
let mov = |wide: bool, dst: u8, src: u8| 0xBE80_0000 | field(dst) << 16 | (3 + u32::from(wide)) << 8 | field(src);
const NOP: u32 = 0xBF80_0000;
let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new();
for i in 0..list.len() {
let Some((save, reg, code, lane)) = parks[i] else {
continue;
};
let Some(slot) = code_of(reg, lane) else { return Vec::new() };
if pairs.contains(&(reg, lane)) {
let Some(j) = partner(i) else { return Vec::new() };
// A save moves the pair where its second half is saved; a
// restore where its first half is restored.
let (at, gone) = if save { (j, i) } else { (i, j) };
let (dst, src) = if save { (slot, code) } else { (code, slot) };
edits.push((at, Some((true, dst, src))));
edits.push((gone, None));
} else if lane > 0 && pairs.contains(&(reg, lane - 1)) {
// the upper half of a pair: moved with the lower
} else {
let (dst, src) = if save { (slot, code) } else { (code, slot) };
edits.push((i, Some((false, dst, src))));
}
}
let mut moves = Vec::new();
for (i, edit) in edits {
match edit {
Some((wide, dst, src)) => {
put(list, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src));
moves.push((i, dst, src));
}
None => put(list, i, gfx10::Encoding::Sopp, 0, NOP),
}
}
moves.sort_unstable();
moves
}
/// Rename register reads and writes after changing edges in a reducible graph.
fn rename(mut blocks: Vec<Block>, wave64: bool, vgprs: u16) -> Program {
let order = reverse_postorder(&blocks);
let (live_in, live_out) = liveness(&blocks, &order);
let mut values = 0u32;
@@ -262,33 +505,193 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
}
}
remove_trivial_phis(&mut blocks, values);
Ok(Program {
Program {
wave64,
vgprs,
blocks,
inputs,
})
}
}
/// Duplicate a join for each proven (predecessor, join, destination) edge.
/// The instructions still execute on that path and define fresh SSA values.
pub(crate) fn thread_edges(
p: &Program,
edges: &[(usize, usize, usize)],
) -> Result<Program, ShaderError> {
let mut blocks = p.blocks.clone();
for block in &mut blocks {
block.phis.clear();
}
for &(pred, join, dest) in edges {
let mut copy = blocks[join].clone();
copy.exit = Exit::Jump(dest);
let target = blocks.len();
match &mut blocks[pred].exit {
Exit::Jump(t) => *t = target,
Exit::Branch { taken, not_taken } => {
if *taken == join {
*taken = target;
}
if *not_taken == join {
*not_taken = target;
}
}
_ => unreachable!("threading an incoming edge"),
}
blocks.push(copy);
}
link(&mut blocks);
split_irreducible(&mut blocks)?;
Ok(rename(blocks, p.wave64, p.vgprs))
}
/// The program without its early-outs: an `s_cbranch_execz` to a block that
/// only ends the program (`if (!inBounds) return;`, the outermost branch of
/// most compute programs) is left out, so the lanes that would have left
/// walk the body with EXEC clear. Vector instructions and every effect are
/// masked by EXEC already, as on the console, where the branch is taken
/// only when no lane of the wave is left; scalar code has no effects. The
/// body is then code every lane runs, which a console wave run as two host
/// waves needs for the barriers of its exchanges and LDS accesses.
/// `None` if the program has no such branch.
pub(crate) fn without_early_outs(p: &Program) -> Option<Program> {
let ends = |b: usize| {
p.blocks[b].exit == Exit::End
&& p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. }))
};
let mut blocks = p.blocks.clone();
let mut any = false;
for block in &mut blocks {
let Exit::Branch { taken, not_taken } = block.exit else {
continue;
};
if ends(taken) && block.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") {
block.insts.pop();
block.exit = Exit::Jump(not_taken);
any = true;
}
}
if !any {
return None;
}
for block in &mut blocks {
block.phis.clear();
}
link(&mut blocks);
split_irreducible(&mut blocks).ok()?;
Some(rename(blocks, p.wave64, p.vgprs))
}
/// As [`without_early_outs`], and also without the branches that only skip a
/// region when no lane is left for it: an `s_cbranch_execz` whose target is
/// where the skipped code ends up anyway (`if (c) { ... }` with nothing
/// else leaving the region). Every lane then walks the region with EXEC
/// clear for those that would have skipped it, and LDS accesses and
/// exchanges inside it are in code every lane runs.
/// The console takes such a branch only when no lane of the wave is left,
/// and then its scalar code does not run: a branch is kept if the code
/// after it could see that (a scalar register or SCC that the region
/// changes and the join merges with the value from before; EXEC aside,
/// which is empty either way). `None` if nothing changes.
pub(crate) fn without_skips(p: &Program) -> Option<Program> {
let n = p.blocks.len();
let ends = |b: usize| {
p.blocks[b].exit == Exit::End
&& p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. }))
};
// The region a skip of `b` to `target` leaves out, if it is a pure skip.
let skipped = |b: usize, target: usize, first: usize| -> Option<Vec<bool>> {
let mut inside = vec![false; n];
let mut stack = vec![first];
while let Some(x) = stack.pop() {
if x == target || inside[x] {
continue;
}
if x == b {
return None; // a loop back to the branch
}
inside[x] = true;
match p.blocks[x].exit {
Exit::End | Exit::Indirect => return None,
exit => stack.extend(exit.successors()),
}
}
// entered only through the branch
for x in (0..n).filter(|&x| inside[x]) {
if p.blocks[x].preds.iter().any(|&q| q != b && !inside[q]) {
return None;
}
}
// the join sees no scalar the region changed
let join = &p.blocks[target];
for phi in &join.phis {
let scalar = match phi.reg {
Reg::S(c) => c != 126 && c != 127,
Reg::Scc => true,
Reg::V(_) => false,
};
if !scalar {
continue;
}
let before: Vec<Value> =
join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| *a).collect();
let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| *a);
if within.into_iter().any(|a| !before.contains(&a)) {
return None;
}
}
// other ways into the join than the branch and the region: not a plain `if`
if join.preds.iter().any(|&q| q != b && !inside[q]) {
return None;
}
Some(inside)
};
let mut blocks = p.blocks.clone();
let mut any = false;
for b in 0..n {
let Exit::Branch { taken, not_taken } = p.blocks[b].exit else {
continue;
};
if !p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") {
continue;
}
if ends(taken) || skipped(b, taken, not_taken).is_some() {
blocks[b].insts.pop();
blocks[b].exit = Exit::Jump(not_taken);
any = true;
}
}
if !any {
return None;
}
for block in &mut blocks {
block.phis.clear();
}
link(&mut blocks);
split_irreducible(&mut blocks).ok()?;
Some(rename(blocks, p.wave64, p.vgprs))
}
/// Placeholder before renaming.
const NONE: Value = Value(u32::MAX);
/// SGPR codes 0-127, SCC, VGPRs 0-255.
const REGS: usize = 128 + 1 + 256;
/// Scalar codes 0-255 (from [`PARKED`] up: parked scalars), SCC, VGPRs 0-255.
const REGS: usize = 256 + 1 + 256;
type RegSet = [u64; REGS.div_ceil(64)];
fn index(reg: Reg) -> usize {
match reg {
Reg::S(c) => usize::from(c),
Reg::Scc => 128,
Reg::V(r) => 129 + usize::from(r),
Reg::Scc => 256,
Reg::V(r) => 257 + usize::from(r),
}
}
fn reg_at(i: usize) -> Reg {
match i {
0..128 => Reg::S(i as u8),
128 => Reg::Scc,
_ => Reg::V((i - 129) as u8),
0..256 => Reg::S(i as u8),
256 => Reg::Scc,
_ => Reg::V((i - 257) as u8),
}
}
@@ -662,6 +1065,16 @@ const DROPPED: &[&str] = &[
/// Registers read, registers written.
type Effects = (Vec<Reg>, Vec<Reg>);
/// The registers `inst` of `p` reads as operands: its reads without the old
/// value of a VGPR it only writes.
pub(crate) fn operand_reads(p: &Program, inst: &Inst) -> Vec<Reg> {
let lanes = 1 + u8::from(p.wave64);
effects(&inst.machine, &inst.fields, inst.name(), lanes, p.vgprs)
.ok()
.flatten()
.map_or_else(Vec::new, |e| e.0)
}
/// Registers an instruction reads and writes, one per dword, or `None` if
/// the IR drops it.
fn effects(
@@ -818,6 +1231,7 @@ fn effects(
indexed(d, &mut r)?;
}
}
"v_div_fmas_f32" | "v_div_fmas_f64" => r.extend(mask(VCC)),
_ => {}
}
if name.starts_with("v_interp_") || src_indexed || dst_indexed {
@@ -930,8 +1344,6 @@ fn effects(
}
if vector {
r.extend(mask(EXEC));
// Lanes disabled in EXEC keep the old value.
r.extend(w.iter().filter(|w| matches!(w, Reg::V(_))));
}
let mut seen = Vec::with_capacity(r.len());
r.retain(|reg| {
@@ -1008,10 +1420,13 @@ fn add_regs(op: &Operand, lanes: u8, out: &mut Vec<Reg>) -> Result<(), ()> {
Operand::Scalar { code, .. } if code == gfx10::NULL => {}
Operand::Scalar { code, dwords } => {
let end = u16::from(code) + u16::from(dwords);
if end > 128 {
// A machine operand ends within the machine's codes, a parked
// scalar (`unspill`) within those past them.
let limit = if code < PARKED { 128 } else { 256 };
if end > limit {
return Err(());
}
out.extend((code..end as u8).map(Reg::S));
out.extend((u16::from(code)..end).map(|c| Reg::S(c as u8)));
}
Operand::Vector { reg, dwords } => {
if u16::from(reg) + u16::from(dwords) > 256 {
+2
View File
@@ -6,6 +6,7 @@
//! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use
//! console-only intrinsics, so the GFX10 code is translated in general.
pub mod bvh;
pub mod dxbc;
pub mod dxil;
pub mod emit;
@@ -14,6 +15,7 @@ pub mod io;
pub mod ir;
pub mod native;
pub mod resource;
pub mod spill;
pub mod structure;
pub use dxbc::{Container, FourCC, Part};
File diff suppressed because it is too large. Load diff
+380
View File
@@ -0,0 +1,380 @@
//! The spilled user-data table of a compute program.
//!
//! A compute program has as many user SGPRs as `COMPUTE_PGM_RSRC2` says. A
//! root signature that needs more dwords than that keeps none of its
//! parameters in registers: user-data dwords 0 and 1 then hold the 40-bit
//! address of a table in memory (`s0`, and `s1 & 0xff` as bits 32-39), and
//! the parameter the layout declares at user-data index N (16 or above) is
//! at byte `4 * (N - 16)` of that table. The code reads it with
//! `s_load_dword*` through that pointer. (Every compute program of the
//! console's ray-tracing structure builder, `XboxBvhBuilder.dll`, is of this
//! kind; measured there: 118 of 118 such loads land on a declared parameter.)
//!
//! [`user_data`] rewrites those loads away: each dword they read becomes the
//! entry value of the SGPR its user-data index names, as if the parameter
//! had arrived in a register. Resource tracking and lowering then treat a
//! spilled parameter like any other (the host binds user data by root slot
//! and dword, not by register).
use crate::ShaderError;
use crate::gfx10::{Fields, NULL, Operand};
use crate::ir::{self, Program, Reg, Value};
use crate::native::{HwStage, NativeProgram, StageIo};
/// The user-data index of the table's first dword.
const FIRST: u32 = 16;
/// [`ir::build`] of `native`'s code as the hardware runs it, with the loads
/// of a spilled user-data table rewritten ([`user_data`]).
pub fn build(native: &NativeProgram) -> Result<Program, ShaderError> {
let mut p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
user_data(&mut p, native);
Ok(p)
}
/// Whether `native` is a compute program that keeps its root parameters in
/// a spilled user-data table (see the module): the entries no register
/// holds, as (first user-data index, dwords), if the table starts at index
/// 16 and the program has the two registers of its address.
fn spilled(native: &NativeProgram) -> Option<Vec<(u32, u32)>> {
let StageIo::Cs(cs) = &native.io else {
return None;
};
if native.stage != HwStage::Cs {
return None;
}
let registers = u32::from(cs.user_sgprs());
let spilled: Vec<(u32, u32)> = native
.layout
.iter()
.filter(|e| e.sgprs > 0 && u32::from(e.user_data) >= registers)
.map(|e| (u32::from(e.user_data), e.sgprs))
.collect();
// Only the one arrangement seen: the table starts at index 16.
(spilled.iter().map(|e| e.0).min() == Some(FIRST) && registers >= 2).then_some(spilled)
}
/// Whether `native` reads its root parameters from a spilled user-data
/// table. (In Grand Theft Auto VI exactly the compute programs of the
/// console's ray-tracing structure builder do.)
pub fn is_spilled(native: &NativeProgram) -> bool {
spilled(native).is_some()
}
/// Rewrites the loads of `native`'s spilled user-data table in `p`; returns
/// how many loads it replaced. Nothing changes unless the program is a
/// compute program whose layout has entries past its user SGPRs, the first
/// at index 16. A load is left alone (and resource tracking then refuses it
/// as before) when its offset is not a constant on a dword, or when a dword
/// it reads and the program uses is in no layout entry.
pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize {
let Some(spilled) = spilled(native) else {
return 0;
};
let entry = |reg: Reg, p: &Program| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1);
let (Some(low), Some(high)) = (entry(Reg::S(0), p), entry(Reg::S(1), p)) else {
return 0;
};
// The pointer's halves: `s0` and its copies, `s1 & 0xff` and its copies.
let mut lows = vec![low];
let mut highs: Vec<Value> = Vec::new();
let mut raw_highs = vec![high];
// Instructions that only form the pointer: dropped when nothing reads
// them any more.
let mut forming: Vec<(usize, usize)> = Vec::new();
loop {
let mut changed = false;
for (b, block) in p.blocks.iter().enumerate() {
for (i, inst) in block.insts.iter().enumerate() {
let Fields::Sop { dst, src, .. } = &inst.fields else {
continue;
};
let Some(Operand::Scalar { code: d, .. }) = *dst else {
continue;
};
let Some(out) = inst.write(Reg::S(d)) else {
continue;
};
let read = |op: &Operand| match *op {
Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
_ => None,
};
let found = match (inst.name(), &src[..]) {
("s_mov_b32", [s]) => match read(s) {
Some(v) if lows.contains(&v) => Some(&mut lows),
Some(v) if highs.contains(&v) => Some(&mut highs),
Some(v) if raw_highs.contains(&v) => Some(&mut raw_highs),
_ => None,
},
("s_and_b32", [x, y]) => {
let masked = |a: &Operand, m: &Operand| {
matches!(*m, Operand::Literal(0xff))
&& read(a).is_some_and(|v| raw_highs.contains(&v))
};
(masked(x, y) || masked(y, x)).then_some(&mut highs)
}
_ => None,
};
if let Some(set) = found
&& !set.contains(&out)
{
set.push(out);
forming.push((b, i));
changed = true;
}
}
}
if !changed {
break;
}
}
if highs.is_empty() {
return 0;
}
// Values some instruction or phi reads.
let mut read_somewhere = std::collections::HashSet::new();
for block in &p.blocks {
read_somewhere.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
read_somewhere.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
}
let mut next = p
.inputs
.iter()
.map(|i| i.1)
.chain(p.blocks.iter().flat_map(|b| {
b.phis
.iter()
.map(|phi| phi.value)
.chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1)))
}))
.map(|v| v.0 + 1)
.max()
.unwrap_or(0);
// Each load through the pointer: its dwords become entry values.
let mut replaced: std::collections::HashMap<Value, Value> = Default::default();
let mut gone: Vec<(usize, usize)> = Vec::new();
let mut inputs = p.inputs.clone();
for (b, block) in p.blocks.iter().enumerate() {
'insts: for (i, inst) in block.insts.iter().enumerate() {
let Fields::Smem {
data: Some(Operand::Scalar { code: first, .. }),
base: Operand::Scalar { code: base, .. },
offset,
soffset,
..
} = inst.fields
else {
continue;
};
if !inst.name().starts_with("s_load_dword")
|| !matches!(soffset, Operand::Scalar { code: NULL, .. } | Operand::Const(128))
|| offset < 0
|| offset % 4 != 0
|| !inst.read(Reg::S(base)).is_some_and(|v| lows.contains(&v))
|| !inst.read(Reg::S(base + 1)).is_some_and(|v| highs.contains(&v))
{
continue;
}
let mut dwords = Vec::new();
for &(reg, v) in &inst.writes {
let Reg::S(code) = reg else {
continue 'insts;
};
let Some(k) = code.checked_sub(first) else {
continue 'insts;
};
let index = FIRST + offset as u32 / 4 + u32::from(k);
let declared = spilled.iter().any(|&(at, n)| index >= at && index < at + n);
if !declared {
if read_somewhere.contains(&v) {
continue 'insts;
}
continue;
}
// SGPR codes end at 105; no root signature reaches there.
let Ok(code) = u8::try_from(index) else {
continue 'insts;
};
if code > 105 {
continue 'insts;
}
dwords.push((Reg::S(code), v));
}
for (reg, v) in dwords {
let value = match inputs.iter().find(|e| e.0 == reg) {
Some(e) => e.1,
None => {
let value = Value(next);
next += 1;
inputs.push((reg, value));
value
}
};
replaced.insert(v, value);
}
gone.push((b, i));
}
}
if gone.is_empty() {
return 0;
}
p.inputs = inputs;
let renamed = |v: &mut Value| {
if let Some(&to) = replaced.get(v) {
*v = to;
}
};
for block in &mut p.blocks {
for phi in &mut block.phis {
phi.args.iter_mut().for_each(renamed);
}
for inst in &mut block.insts {
inst.reads.iter_mut().for_each(|r| renamed(&mut r.1));
}
}
// The loads go, then what only formed the pointer (last first, so a
// copy goes before what it copied).
let mut drop = gone.clone();
loop {
let read_somewhere = {
let mut used = std::collections::HashSet::new();
for (b, block) in p.blocks.iter().enumerate() {
used.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
for (i, inst) in block.insts.iter().enumerate() {
if !drop.contains(&(b, i)) {
used.extend(inst.reads.iter().map(|r| r.1));
}
}
}
used
};
let before = drop.len();
for &site in &forming {
let inst = &p.blocks[site.0].insts[site.1];
if !drop.contains(&site) && inst.writes.iter().all(|w| !read_somewhere.contains(&w.1)) {
drop.push(site);
}
}
if drop.len() == before {
break;
}
}
for (b, block) in p.blocks.iter_mut().enumerate() {
let mut i = 0;
block.insts.retain(|_| {
i += 1;
!drop.contains(&(b, i - 1))
});
}
// The pointer's registers are no inputs once nothing reads them.
let mut read = std::collections::HashSet::new();
for block in &p.blocks {
read.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
read.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
}
p.inputs
.retain(|&(reg, v)| !matches!(reg, Reg::S(0 | 1)) || read.contains(&v));
gone.len()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::native::{ComputeIo, RootParam, RootType};
fn param(root: RootType, user_data: u8, sgprs: u32, slot: u8) -> RootParam {
RootParam {
root,
table_offset_dwords: 0,
sgprs,
base_register: 0,
user_data,
slot,
}
}
/// A compute program with `registers` user SGPRs and the group id after
/// them.
fn native(words: &[u32], registers: u32, layout: Vec<RootParam>) -> NativeProgram {
NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 256,
layout,
used: vec![],
io: StageIo::Cs(ComputeIo {
rsrc2: registers << 1 | 1 << 7,
threads: [1, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
}
}
// s_and_b32 s3, s1, 0xff; s_mov_b32 s2, s0; s_load_dword s5, s[2:3],
// 0x10; s_load_dwordx2 s[0:1], s[2:3], 0; s_endpgm.
const TABLE: [u32; 8] = [
0x8703_FF01,
0x0000_00FF,
0xBE82_0300,
0xF400_0141,
0xFA00_0010,
0xF404_0001,
0xFA00_0000,
0xBF81_0000,
];
#[test]
fn loads_of_the_spilled_table_become_entry_registers() {
let n = native(
&TABLE,
4,
vec![
param(RootType::Descriptor, 16, 2, 0),
param(RootType::Descriptor, 18, 2, 1),
param(RootType::Constants, 20, 16, 2),
],
);
let mut p = ir::build(&n.code, false, 256).unwrap();
assert_eq!(user_data(&mut p, &n), 2);
let names: Vec<&str> = p.blocks.iter().flat_map(|b| &b.insts).map(|i| i.name()).collect();
assert!(!names.iter().any(|n| n.starts_with("s_load_")), "{names:?}");
// The pointer is gone with the loads; byte 0x10 is index 20, the
// first root constant, and bytes 0-7 are the first root view.
let mut regs: Vec<Reg> = p.inputs.iter().map(|i| i.0).collect();
regs.sort();
assert_eq!(regs, [Reg::S(16), Reg::S(17), Reg::S(20)]);
}
#[test]
fn parameters_in_registers_are_left_alone() {
// The same code where s0 and s1 are a root view the layout declares.
let n = native(&TABLE, 6, vec![param(RootType::Descriptor, 0, 2, 0)]);
let mut p = ir::build(&n.code, false, 256).unwrap();
let before = p.clone();
assert_eq!(user_data(&mut p, &n), 0);
assert_eq!(p, before);
}
#[test]
fn a_used_dword_no_parameter_declares_keeps_its_load() {
// As above with `s_mov_b32 s6, s5` before the end: the dword at
// byte 0x10 (index 20) is read, and here nothing declares it.
let mut words = TABLE.to_vec();
words.insert(7, 0xBE86_0305);
let n = native(&words, 4, vec![param(RootType::Descriptor, 16, 2, 0)]);
let mut p = ir::build(&n.code, false, 256).unwrap();
assert_eq!(user_data(&mut p, &n), 1);
let loads = p
.blocks
.iter()
.flat_map(|b| &b.insts)
.filter(|i| i.name().starts_with("s_load_"))
.count();
assert_eq!(loads, 1);
// The pointer is still read, by the load that stays.
assert!(p.inputs.iter().any(|i| i.0 == Reg::S(0)));
}
}
+588 -45
View File
@@ -101,6 +101,16 @@ const TERMINAL: u32 = u32::MAX;
const MAX_NODES: usize = 1 << 21;
/// Case splits [`Bools::meet`] makes before it gives up.
const MAX_MEET: usize = 1 << 16;
/// Conditions [`Meets`] keeps; past that, they are searched anew.
const MAX_MEETS: usize = 1 << 18;
/// What [`Bools::meet`] found out about one [`Bools`], for its later calls:
/// the conditions no lane satisfies, and the case splits it took to find
/// that out of each.
#[derive(Debug, Default)]
pub struct Meets {
none: Map<Box<[u32]>, usize>,
}
impl Bools {
fn new() -> Self {
@@ -227,32 +237,99 @@ impl Bools {
/// `b` where `holds`, its negation where not. Yes when the search grows
/// too large to finish.
pub fn meet(&self, all: &[(Bool, bool)]) -> bool {
let mut budget = MAX_MEET;
self.meet_in(all.to_vec(), &mut budget)
self.meet_seen(all, &mut Meets::default())
}
fn meet_in(&self, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool {
let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE };
if all.iter().any(fails) {
return false;
/// [`Self::meet`], which looks up in `seen` what earlier calls on these
/// `Bools` found out and adds what it finds. The answer is the one
/// `meet` gives.
pub fn meet_seen(&self, all: &[(Bool, bool)], seen: &mut Meets) -> bool {
self.meet_within(all, MAX_MEET, seen)
}
/// [`Self::meet_seen`] with `budget` case splits.
fn meet_within(&self, all: &[(Bool, bool)], mut budget: usize, seen: &mut Meets) -> bool {
let mut work = all
.iter()
.map(|&(b, holds)| b.0 << 1 | u32::from(holds))
.collect();
self.meet_in(0, &mut work, &mut budget, seen)
}
/// The search of [`Self::meet`] for the conditions `work[at..]` (a node
/// doubled, plus one where it must hold), which it takes off `work`.
///
/// The search is a case split on the top variable, and the cofactors of
/// a few large functions come down to the same conditions over and over
/// (a block's reach under a mask and under its negation share most of
/// their nodes), so splitting each anew is exponential where the
/// distinct conditions are few. `seen` keeps the conditions that no lane
/// satisfies with the case splits it took to find that out: meeting
/// them again takes those splits off the budget at once. A search
/// therefore gives up exactly where one that split everything anew
/// would (nothing below such conditions ends it early, so it either
/// makes all those splits or runs out among them), and gives the same
/// answer.
fn meet_in(
&self,
at: usize,
work: &mut Vec<u32>,
budget: &mut usize,
seen: &mut Meets,
) -> bool {
// Constants either fail or say nothing.
let mut kept = at;
for i in at..work.len() {
let (b, holds) = (work[i] >> 1, work[i] & 1 != 0);
if b > Bool::TRUE.0 {
work[kept] = work[i];
kept += 1;
} else if (b == Bool::TRUE.0) != holds {
work.truncate(at);
return false;
}
}
all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE);
if all.is_empty() || *budget == 0 {
work.truncate(kept);
if kept == at || *budget == 0 {
work.truncate(at);
return true;
}
// As a set: neither order nor repeats change the search.
work[at..].sort_unstable();
let mut end = at + 1;
for i in at + 1..kept {
if work[i] != work[end - 1] {
work[end] = work[i];
end += 1;
}
}
work.truncate(end);
if let Some(&splits) = seen.none.get(&work[at..]) {
let within = splits <= *budget;
*budget = budget.saturating_sub(splits);
work.truncate(at);
return !within;
}
let before = *budget;
*budget -= 1;
let top = |b: Bool| self.nodes[b.0 as usize].0;
let v = all.iter().map(|&(b, _)| top(b)).min().expect("not empty");
[false, true].into_iter().any(|value| {
let next = all
.iter()
.map(|&(b, holds)| {
let (lo, hi) = self.split(b, v);
(if value { hi } else { lo }, holds)
})
.collect();
self.meet_in(next, budget)
})
let top = |code: u32| self.nodes[(code >> 1) as usize].0;
let v = work[at..].iter().map(|&c| top(c)).min().expect("not empty");
let mut found = false;
for value in [false, true] {
for i in at..end {
let (lo, hi) = self.split(Bool(work[i] >> 1), v);
work.push((if value { hi } else { lo }).0 << 1 | work[i] & 1);
}
if self.meet_in(end, work, budget, seen) {
found = true;
break;
}
}
if !found && seen.none.len() < MAX_MEETS {
seen.none.insert(work[at..end].into(), before - *budget);
}
work.truncate(at);
found
}
fn implies(&mut self, a: Bool, b: Bool) -> bool {
@@ -351,8 +428,12 @@ pub struct Structured {
pub highs: HashMap<Value, Value>,
/// Masks (low dwords) set only in lanes whose EXEC bit is set where
/// they are written: every such lane reaches the writing block, so a
/// ballot there gives the mask as data.
/// ballot there gives the mask as data. No split low dword, as in
/// `masks`.
pub active: HashSet<Value>,
/// Incoming lane boolean per predecessor edge (in block predecessor order)
/// for each [`Atom::Phi`] id.
pub phi_masks: HashMap<Value, Vec<Bool>>,
}
impl Structured {
@@ -371,11 +452,15 @@ pub fn structure(program: &Program) -> Result<Structured, ShaderError> {
loop {
let execs = l.masks_in_order();
let cond = l.paths()?;
let wrong = l.wrong_joins(&cond);
if wrong.is_empty() {
let (wrong, new_derived) = l.check_joins(&cond);
if l.b.overflow {
return Err(TOO_LARGE);
}
if wrong.is_empty() && new_derived.is_empty() {
return l.finish(&execs, &cond);
}
l.unresolved.extend(wrong);
l.derived_phis.extend(new_derived);
l.reset();
}
}
@@ -397,16 +482,26 @@ struct Lanes<'a> {
phis: Map<Value, (usize, usize)>,
/// Mask joins found wrong when resolved to a constant: atoms instead.
unresolved: HashSet<Value>,
/// Phi ids whose joins depend on EXEC or VALU results (including along
/// back edges), carried across resets so their joins stay in `masks`.
derived_phis: HashSet<Value>,
b: Bools,
/// Masks derived from EXEC and VALU results.
masks: Map<Key, Bool>,
/// Other values read as masks: constants, uniform selects, opaque ones.
other: Map<Key, Bool>,
/// Pairs read as masks that `mask` does not see: carry-ins, and pairs
/// joins take over back edges.
seen: Vec<Key>,
/// For branches: SCC of a mask operation ("some lane is set") as the
/// lane's own bit.
scc_lane: Map<Value, Bool>,
/// Joins resolved to a constant, to check once all edges are known.
joins: Vec<Join>,
/// [`Atom::Phi`] joins created in the current pass, resolved in
/// `check_joins` and exported in `finish`.
phi_joins: Vec<PhiJoin>,
phi_join_ids: HashSet<Value>,
/// Per block: what a lane knows on entry, over forward edges only.
first: Vec<Bool>,
/// Per block ending in a branch: when a lane takes it.
@@ -422,6 +517,16 @@ struct Join {
/// The phi value naming the join.
id: Value,
value: bool,
derived: bool,
args: Vec<Key>,
}
/// A mask join represented as [`Atom::Phi`], whose incoming edge masks are
/// resolved once every block (including loop back edges) has been visited.
struct PhiJoin {
block: usize,
id: Value,
derived: bool,
args: Vec<Key>,
}
@@ -468,11 +573,15 @@ impl<'a> Lanes<'a> {
defs,
phis,
unresolved: HashSet::new(),
derived_phis: HashSet::new(),
b: Bools::new(),
masks: Map::default(),
other: Map::default(),
seen: Vec::new(),
scc_lane: Map::default(),
joins: Vec::new(),
phi_joins: Vec::new(),
phi_join_ids: HashSet::new(),
first: vec![Bool::FALSE; blocks.len()],
when: vec![None; blocks.len()],
active: HashSet::new(),
@@ -483,8 +592,11 @@ impl<'a> Lanes<'a> {
self.b = Bools::new();
self.masks.clear();
self.other.clear();
self.seen.clear();
self.scc_lane.clear();
self.joins.clear();
self.phi_joins.clear();
self.phi_join_ids.clear();
self.first.fill(Bool::FALSE);
self.when.fill(None);
self.active.clear();
@@ -557,28 +669,61 @@ impl<'a> Lanes<'a> {
}
}
/// Joins whose constant fails on some edge, given what lanes know.
fn wrong_joins(&mut self, cond: &[Bool]) -> Vec<Value> {
/// Joins whose constant fails on some edge, and joins that need another
/// pass because a later edge turned out to derive from EXEC or VALU.
fn check_joins(&mut self, cond: &[Bool]) -> (Vec<Value>, Vec<Value>) {
let mut wrong = Vec::new();
let mut new_derived = Vec::new();
let mut seen_derived = HashSet::new();
let mut j = 0;
let mut p = 0;
// Checking an argument can resolve another join; it is checked too.
while j < self.joins.len() {
let (block, id, value) = (self.joins[j].block, self.joins[j].id, self.joins[j].value);
for (n, a) in self.joins[j].args.clone().into_iter().enumerate() {
let (q, taken) = self.incoming[block][n];
let e = self.edge(cond[q], q, taken);
let mut m = self.mask(a).0;
if !value {
m = self.b.not(m);
}
if !self.b.implies(e, m) {
wrong.push(id);
break;
while j < self.joins.len() || p < self.phi_joins.len() {
while j < self.joins.len() {
let (block, id, value, was_derived) = (
self.joins[j].block,
self.joins[j].id,
self.joins[j].value,
self.joins[j].derived,
);
let mut failed = false;
for (n, a) in self.joins[j].args.clone().into_iter().enumerate() {
let (q, taken) = self.incoming[block][n];
let e = self.edge(cond[q], q, taken);
let (mut m, d) = self.mask(a);
if !was_derived
&& d
&& !self.derived_phis.contains(&id)
&& seen_derived.insert(id)
{
new_derived.push(id);
}
if !value {
m = self.b.not(m);
}
if !failed && !self.b.implies(e, m) {
wrong.push(id);
failed = true;
}
}
j += 1;
}
while p < self.phi_joins.len() {
let (id, was_derived) = (self.phi_joins[p].id, self.phi_joins[p].derived);
for a in self.phi_joins[p].args.clone() {
let (_, d) = self.mask(a);
if !was_derived
&& d
&& !self.derived_phis.contains(&id)
&& seen_derived.insert(id)
{
new_derived.push(id);
}
}
p += 1;
}
j += 1;
}
wrong
(wrong, new_derived)
}
fn finish(
@@ -586,6 +731,22 @@ impl<'a> Lanes<'a> {
execs: &[Vec<Option<Bool>>],
cond: &[Bool],
) -> Result<Structured, ShaderError> {
let phi_joins = std::mem::take(&mut self.phi_joins);
let mut phi_masks = HashMap::with_capacity(phi_joins.len());
for pj in phi_joins {
let incoming: Vec<Bool> = pj
.args
.into_iter()
.enumerate()
.map(|(n, a)| {
let (q, taken) = self.incoming[pj.block][n];
let e = self.edge(cond[q], q, taken);
let m = self.mask(a).0;
self.b.given(m, e)
})
.collect();
phi_masks.insert(pj.id, incoming);
}
let blocks = &self.p.blocks;
let b = &mut self.b;
let guards = blocks
@@ -624,6 +785,20 @@ impl<'a> Lanes<'a> {
if self.b.overflow {
return Err(TOO_LARGE);
}
// Exports go by low dword. A low dword read with two high dwords
// (one rewritten alone) names no one mask: it is left out, so
// lowering refuses what reads it instead of taking the other
// pair's lanes 32-63. Not where the low dword holds a number: see
// the shortcut in `mask`.
let (mut high, mut split) = (Map::default(), HashSet::new());
let keys = self.masks.keys().chain(self.other.keys());
for &(lo, hi) in keys.chain(&self.seen) {
if *high.entry(lo).or_insert(hi) != hi {
split.insert(lo);
}
}
self.masks.retain(|k, _| !split.contains(&k.0));
self.active.retain(|lo| !split.contains(lo));
Ok(Structured {
masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(),
highs: self
@@ -634,6 +809,7 @@ impl<'a> Lanes<'a> {
.collect(),
paired_masks: if self.p.wave64 { self.masks } else { Map::default() },
active: self.active,
phi_masks,
bools: self.b,
exits,
guards,
@@ -694,6 +870,12 @@ impl<'a> Lanes<'a> {
})
};
let derived = exec_write(lo, k.0) || exec_write(hi, k.1);
// shortcut: the atom names the pair by its low dword, and
// lowering takes the high dword written beside it. For halves
// written apart (two `s_mov_b32`) lanes 32-63 are wrong unless
// lowering has no value for the low dword (EXEC, compares)
// and refuses. Give the atom both dwords when such code
// turns up.
let m = m.unwrap_or_else(|| {
let born = self.born(k.0);
self.b.atom(Atom::Opaque(k.0), born)
@@ -730,7 +912,7 @@ impl<'a> Lanes<'a> {
.map(|n| (arg(lo, k.0, n), arg(hi, k.1, n)))
.collect();
let id = lo.map_or(k.1, |_| k.0);
let mut derived = false;
let mut derived = self.derived_phis.contains(&id);
// (edge condition, mask) per forward edge; back edges come later.
let mut forward = Vec::new();
for (n, &a) in args.iter().enumerate() {
@@ -740,6 +922,8 @@ impl<'a> Lanes<'a> {
derived |= d;
let e = self.edge(self.first[q], q, taken);
forward.push((e, m));
} else {
self.seen.push(a);
}
}
if forward.len() == args.len()
@@ -760,6 +944,7 @@ impl<'a> Lanes<'a> {
block,
id,
value,
derived,
args,
});
let m = if value { Bool::TRUE } else { Bool::FALSE };
@@ -767,6 +952,14 @@ impl<'a> Lanes<'a> {
}
}
}
if self.phi_join_ids.insert(id) {
self.phi_joins.push(PhiJoin {
block,
id,
derived,
args,
});
}
let born = self.index[block];
Some((self.b.atom(Atom::Phi(id), born), derived))
}
@@ -854,9 +1047,13 @@ impl<'a> Lanes<'a> {
"cselect" => {
let (a, c) = (arg(0, self)?, arg(1, self)?);
let scc = inst.read(Reg::Scc)?;
let born = self.born(scc);
let u = self.b.atom(Atom::Uniform(scc), born);
(self.b.ite(u, a, c), None)
if self.clear_after_loop(scc) {
(c, None)
} else {
let born = self.born(scc);
let u = self.b.atom(Atom::Uniform(scc), born);
(self.b.ite(u, a, c), None)
}
}
_ => {
let (a, c) = (arg(0, self)?, arg(1, self)?);
@@ -872,6 +1069,31 @@ impl<'a> Lanes<'a> {
})
}
/// Whether SCC value `scc` is clear wherever it is read: the instruction before an
/// `s_cbranch_execnz` that closes a loop wrote it as "the EXEC it leaves is not
/// empty" (`s_andn2_wrexec`, say), and the wave leaves `do { .. } while (EXEC)`
/// with EXEC empty. A read inside the loop or behind another way out of it sees a
/// join of this value, not the value itself.
fn clear_after_loop(&self, scc: Value) -> bool {
let Some(&(b, i)) = self.defs.get(&scc) else {
return false;
};
let block = &self.p.blocks[b];
let (Some(writer), Some(last)) = (block.insts.get(i), block.insts.last()) else {
return false;
};
let exec = writer.write(Reg::S(EXEC));
let back = match block.exit {
Exit::Branch { taken, .. } => self.index[taken] <= self.index[b],
_ => false,
};
back && i + 2 == block.insts.len()
&& exec.is_some()
&& last.name() == "s_cbranch_execnz"
&& last.read(Reg::S(EXEC)) == exec
&& (!self.p.wave64 || last.read(Reg::S(EXEC + 1)) == writer.write(Reg::S(EXEC + 1)))
}
fn combine(&mut self, f: &str, a: Bool, c: Bool) -> Option<Bool> {
let b = &mut self.b;
Some(match f {
@@ -963,6 +1185,23 @@ impl<'a> Lanes<'a> {
};
self.scc_lane.insert(scc, m);
}
// `s_bcnt1` of a mask every running lane sees alike (EXEC under a scalar
// condition, or EXEC itself): its SCC, "some lane is set", is each lane's own
// bit. A branch on it then reads no ballot.
if takes_mask
&& name.starts_with("s_bcnt1_i32_b")
&& let Some(scc) = inst.write(Reg::Scc)
&& let [a] = &src[..]
&& let Some((m, true)) = self.operand(inst, a)
{
let e = exec.unwrap_or(Bool::TRUE);
let own = self.b.given(m, e);
if self.b.implies(m, e)
&& self.b.support(own).iter().all(|a| matches!(a, Atom::Uniform(_)))
{
self.scc_lane.insert(scc, own);
}
}
}
Fields::Valu(v) => {
let exec = self.exec(inst);
@@ -974,11 +1213,22 @@ impl<'a> Lanes<'a> {
l.active.insert(k.0);
};
// A select reads a mask nothing else may: a join of compare
// results is resolved here, as for EXEC.
if name == "v_cndmask_b32"
// results is resolved here, as for EXEC. A carry-in is only
// recorded for `finish`: resolving its join would turn a
// refusal into a per-lane phi, wrong after a divergent branch.
if (name == "v_cndmask_b32" || name.contains("_co_ci_"))
&& let Some(&Operand::Scalar { code, .. }) = v.src.get(2)
&& code != NULL
&& let Some(k) = self.key(|r| inst.read(r), code)
{
if name == "v_cndmask_b32" {
self.mask(k);
} else {
self.seen.push(k);
}
}
if matches!(name, "v_div_fmas_f32" | "v_div_fmas_f64")
&& let Some(k) = self.key(|r| inst.read(r), VCC)
{
self.mask(k);
}
@@ -1112,6 +1362,102 @@ mod tests {
s.guards.iter().flatten().filter(|g| g.is_some()).count()
}
/// The search of [`Bools::meet`] with every case split made anew, as it
/// was before [`Meets`].
fn meet_anew(b: &Bools, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool {
let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE };
if all.iter().any(fails) {
return false;
}
all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE);
if all.is_empty() || *budget == 0 {
return true;
}
*budget -= 1;
let top = |x: Bool| b.nodes[x.0 as usize].0;
let v = all.iter().map(|&(x, _)| top(x)).min().expect("not empty");
[false, true].into_iter().any(|value| {
let next = all
.iter()
.map(|&(x, holds)| {
let (lo, hi) = b.split(x, v);
(if value { hi } else { lo }, holds)
})
.collect();
meet_anew(b, next, budget)
})
}
#[test]
fn a_search_that_remembers_answers_as_one_made_anew() {
// Functions of 12 variables put together at random, and conditions
// of two to five of them (repeats and constants among them), under
// budgets that run out early, late and never: the answer, and where
// no lane is found the budget left, are those of the search that
// remembers nothing; with what one `Meets` gathered over all of
// them, and with an empty one.
let mut b = Bools::new();
let mut state = 0x9E37_79B9_7F4A_7C15_u64;
let mut random = move |n: usize| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state % n as u64) as usize
};
let mut f: Vec<Bool> = (0..12).map(|i| b.atom(Atom::Constant(i + 2), 0)).collect();
f.extend([Bool::FALSE, Bool::TRUE]);
for _ in 0..120 {
let (x, y) = (f[random(f.len())], f[random(f.len())]);
let made = match random(4) {
0 => b.and(x, y),
1 => b.or(x, y),
2 => b.xor(x, y),
_ => b.not(x),
};
f.push(made);
}
let mut seen = Meets::default();
let (mut none, mut some, mut gave_up) = (0, 0, 0);
for _ in 0..1500 {
let all: Vec<(Bool, bool)> = (0..2 + random(4))
.map(|_| (f[random(f.len())], random(2) == 0))
.collect();
for budget in [0, 1, 2, 3, 5, 9, 20, 60, 250, 1000, MAX_MEET] {
let mut left = budget;
let anew = meet_anew(&b, all.clone(), &mut left);
for fresh in [false, true] {
let mut empty = Meets::default();
let seen = if fresh { &mut empty } else { &mut seen };
let mut work = all
.iter()
.map(|&(x, holds)| x.0 << 1 | u32::from(holds))
.collect();
let mut mine = budget;
let found = b.meet_in(0, &mut work, &mut mine, seen);
assert_eq!(found, anew, "{all:?} within {budget}");
assert!(work.is_empty());
if !found {
assert_eq!(mine, left, "{all:?} within {budget}");
}
}
assert_eq!(b.meet_within(&all, budget, &mut seen), anew);
if !anew {
none += 1;
} else if meet_anew(&b, all.clone(), &mut usize::MAX.clone()) {
some += 1;
} else {
gave_up += 1;
}
}
}
// All three outcomes came up, and searches were remembered.
assert!(
none > 100 && some > 100 && gave_up > 100,
"{none} {some} {gave_up}"
);
assert!(seen.none.len() > 100);
}
#[test]
fn divergent_if_becomes_a_lane_branch() {
let p = build(
@@ -1193,6 +1539,39 @@ mod tests {
));
}
/// `s_cselect` on the SCC a lane loop ended with (the blend-shape skinning
/// programs): the loop is left when no lane remains, so the select takes
/// its second operand; it was a uniform atom whose value no lane has.
#[test]
fn a_select_on_the_condition_a_lane_loop_ended_with_takes_its_second_operand() {
let cnd = 256 | (256 << 9) | (3 << 18);
let p = build(
&[
0xBE83_037E, // 0: s_mov_b32 s3, exec_lo
0xBE9C_037E, // s_mov_b32 s28, exec_lo
0x7E3A_0507, // 8: v_readfirstlane_b32 s29, v7
0x7DA4_0E1D, // v_cmpx_eq_u32 exec_lo, s29, v7
0xBE9C_471C, // s_andn2_wrexec_b32 s28, s28
0xBF89_FFFC, // s_cbranch_execnz -> 8
0xBEFE_0303, // s_mov_b32 exec_lo, s3
0x8503_807E, // s_cselect_b32 s3, exec_lo, 0
0xD501_0001,
cnd, // v_cndmask_b32 v1, v0, v0, s3
S_ENDPGM,
],
false,
);
let s = structure(&p).unwrap();
let select = p
.blocks
.iter()
.flat_map(|b| &b.insts)
.find(|i| i.name() == "s_cselect_b32")
.expect("the select");
let mask = select.write(Reg::S(3)).unwrap();
assert_eq!(s.masks.get(&mask), Some(&Bool::FALSE));
}
#[test]
fn scalar_branches_stay_uniform() {
let p = build(
@@ -1212,6 +1591,57 @@ mod tests {
assert_eq!(guarded(&s), 0);
}
#[test]
fn a_mask_whose_high_dword_is_rewritten_is_not_the_compare() {
for reader in [
0x0202_0480, // v_cndmask_b32 v1, 0, v2, vcc
0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc
] {
let p = build(
&[
0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
0xBEEB_0380, // s_mov_b32 vcc_hi, 0
reader,
S_ENDPGM,
],
true,
);
let s = structure(&p).unwrap();
let lo = p.blocks[0].insts[2].read(Reg::S(VCC)).unwrap();
assert_eq!(p.blocks[0].insts[0].write(Reg::S(VCC)), Some(lo));
// The reader sees (compare low dword, 0): lanes 32-63 are clear.
// The mask exported for that low dword must not be the compare.
assert_ne!(
s.masks.get(&lo).and_then(|&m| s.bools.node(m)),
Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)),
"{reader:#x}: vcc_hi was zeroed after the compare"
);
}
}
#[test]
fn a_mask_joined_over_a_back_edge_with_a_rewritten_high_dword_is_not_the_compare() {
let p = build(
&[
0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
0x0202_0480, // 4: v_cndmask_b32 v1, 0, v2, vcc
0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1
0xBEEB_0380, // s_mov_b32 vcc_hi, 0
0xBF85_FFFC, // s_cbranch_scc1 -> 4
S_ENDPGM,
],
true,
);
let s = structure(&p).unwrap();
// The select reads the loop header's join; over the back edge it
// takes (compare low dword, 0), which only the join sees.
let lo = p.blocks[1].insts[1].write(Reg::S(VCC)).unwrap();
assert_ne!(
s.masks.get(&lo).and_then(|&m| s.bools.node(m)),
Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE))
);
}
#[test]
fn irreducible_loops_are_split() {
let p = build(
@@ -1231,4 +1661,117 @@ mod tests {
assert_eq!(p.blocks[1].preds, [2]);
assert!(structure(&p).is_ok());
}
#[test]
fn mask_phi_joining_constant_and_compare_records_edge_bools() {
let cnd = 258 | (259 << 9) | (2 << 18);
let p = build(
&[
0xBF06_8000, // 0: s_cmp_eq_u32 s0, 0
0xBF85_0002, // 4: s_cbranch_scc1 -> 16
0xBE82_0380, // 8: s_mov_b32 s2, 0
0xBF82_0002, // 12: s_branch -> 24
0xD4C2_0002,
0x0002_0080, // 16: v_cmp_eq_u32 s2, 0, v0
0xD501_0001,
cnd, // 24: v_cndmask_b32 v1, v2, v3, s2
S_ENDPGM,
],
false,
);
let s = structure(&p).unwrap();
let phi = p
.blocks
.iter()
.flat_map(|b| &b.phis)
.find(|phi| phi.reg == Reg::S(2))
.expect("mask phi for s2");
assert_eq!(
s.masks.get(&phi.value).and_then(|&m| s.bools.node(m)),
Some((Atom::Phi(phi.value), Bool::FALSE, Bool::TRUE))
);
let edges = &s.phi_masks[&phi.value];
assert_eq!(edges.len(), 2);
assert!(edges.contains(&Bool::FALSE), "{edges:?}");
assert!(
edges
.iter()
.any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])),
"{edges:?}"
);
}
#[test]
fn loop_mask_accumulator_from_zero_tracks_phi_and_edges() {
let cnd = 258 | (259 << 9) | (2 << 18);
let p = build(
&[
0xBE82_0480, // 0: s_mov_b64 s[2:3], 0
0xBE84_0380, // 4: s_mov_b32 s4, 0
0xD501_0001,
cnd, // 8: v_cndmask_b32 v1, v2, v3, s[2:3]
0x7D84_0080, // 16: v_cmp_eq_u32 vcc, 0, v0
0x8882_026A, // 20: s_or_b64 s[2:3], vcc, s[2:3]
0x8004_8104, // 24: s_add_u32 s4, s4, 1
0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4
0xBF85_FFF9, // 32: s_cbranch_scc1 -> 8
0xD501_0004,
cnd, // 36: v_cndmask_b32 v4, v2, v3, s[2:3]
S_ENDPGM,
],
true,
);
let s = structure(&p).unwrap();
let phi = p
.blocks
.iter()
.flat_map(|b| &b.phis)
.find(|phi| phi.reg == Reg::S(2))
.expect("loop mask phi for s[2:3]");
assert!(s.masks.contains_key(&phi.value));
let edges = &s.phi_masks[&phi.value];
assert_eq!(edges.len(), 2);
assert!(edges.contains(&Bool::FALSE), "{edges:?}");
assert!(edges.iter().any(|&e| {
let sup = s.bools.support(e);
sup.contains(&Atom::Phi(phi.value)) && sup.iter().any(|a| matches!(a, Atom::Lane(_)))
}));
}
#[test]
fn loop_mask_phi_reset_to_constant_on_back_edge() {
let cnd = 258 | (259 << 9) | (2 << 18);
let p = build(
&[
0xD4C2_0002,
0x0002_0080, // 0: v_cmp_eq_u32 s2, 0, v0
0xBE84_0380, // 8: s_mov_b32 s4, 0
0xD501_0001,
cnd, // 12: v_cndmask_b32 v1, v2, v3, s2
0xBE82_0380, // 20: s_mov_b32 s2, 0
0x8004_8104, // 24: s_add_u32 s4, s4, 1
0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4
0xBF85_FFFA, // 32: s_cbranch_scc1 -> 12
S_ENDPGM,
],
false,
);
let s = structure(&p).unwrap();
let phi = p
.blocks
.iter()
.flat_map(|b| &b.phis)
.find(|phi| phi.reg == Reg::S(2))
.expect("loop mask phi for s2");
assert!(s.masks.contains_key(&phi.value));
let edges = &s.phi_masks[&phi.value];
assert_eq!(edges.len(), 2);
assert!(edges.contains(&Bool::FALSE), "{edges:?}");
assert!(
edges
.iter()
.any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])),
"{edges:?}"
);
}
}