Integrate GTA renderer and GPU optimizations #2469

Open
github-bot wants to merge 246 commits from github-bot/gh-2469 into main AGit
Owner

@⁠danekbiglike on GitHub · 2026-11-20 18:57 UTC · original
danekbiglike:gta5-rt-integration-20261120 → main · +196686 −4196 · 327 files · 246 commits · open

Integrates the GTA renderer through 4c4eaac78 with upstream a1fc5ae, together with GPU transfer and ray-tracing changes. The final diff excludes launcher changes.

The integration carries original commit authorship and co-author credits. It includes substantial work by TheCruZ, chenxiao07, Senaxx, Jetsku and other contributors. The complete authorship is recorded in the commit history.

Reviewed simnJS/KytyPS5-GTA, Erlou93/KytyPS5-Erlou and Jetsku/KytyPS5. The reviewed simnJS engine changes and several GPU fixes were already present. Other experimental changes require independent compatibility and performance validation.

Validation on Windows, Ryzen 7 3700X and RTX 3090:

  • Release emulator built with the launcher disabled. The launcher was not built in this validation.
  • GTA V PS5 PPSA04263 v01.011.001 reached gameplay on the rebuilt executable. Fidelity averaged 27.2 FPS during a 30-second city sample. A 65-second Performance walking and camera test averaged 58.55 FPS, and a separate 40-second Fidelity roadside test averaged 25.37 FPS. Hardware ray queries were observed in a separate instrumented run. These samples do not establish stable 60 or 30 FPS across the game.
  • GPU tiler parity passed, including 513 cases. Five initially failing GPU tests passed when rerun serially. Windows test allocation and file-clock conversion were fixed.
  • The full serial CTest run passed 79 of 83 tests. On rerun, save_data_memory passed and common passed after the file-clock fix. kernel_file_system still fails in winpthread cancellation with 0xc0000028. shader_recompiler_compute independently fails in the embedded-fetch lane-spill case during SSA instruction use replacement. Both remain unresolved.

This is a large integration across 327 files. The unresolved failures and compatibility with other games require investigation before merging. Maintainer review of scope and whether to split the changes would be appreciated.

Submitted by Danek (@⁠danekbiglike).

**@⁠danekbiglike** on GitHub · 2026-11-20 18:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2469) `danekbiglike:gta5-rt-integration-20261120` → `main` · +196686 −4196 · 327 files · 246 commits · open Integrates the GTA renderer through 4c4eaac78 with upstream a1fc5ae, together with GPU transfer and ray-tracing changes. The final diff excludes launcher changes. The integration carries original commit authorship and co-author credits. It includes substantial work by TheCruZ, chenxiao07, Senaxx, Jetsku and other contributors. The complete authorship is recorded in the commit history. Reviewed simnJS/KytyPS5-GTA, Erlou93/KytyPS5-Erlou and Jetsku/KytyPS5. The reviewed simnJS engine changes and several GPU fixes were already present. Other experimental changes require independent compatibility and performance validation. Validation on Windows, Ryzen 7 3700X and RTX 3090: - Release emulator built with the launcher disabled. The launcher was not built in this validation. - GTA V PS5 PPSA04263 v01.011.001 reached gameplay on the rebuilt executable. Fidelity averaged 27.2 FPS during a 30-second city sample. A 65-second Performance walking and camera test averaged 58.55 FPS, and a separate 40-second Fidelity roadside test averaged 25.37 FPS. Hardware ray queries were observed in a separate instrumented run. These samples do not establish stable 60 or 30 FPS across the game. - GPU tiler parity passed, including 513 cases. Five initially failing GPU tests passed when rerun serially. Windows test allocation and file-clock conversion were fixed. - The full serial CTest run passed 79 of 83 tests. On rerun, save_data_memory passed and common passed after the file-clock fix. kernel_file_system still fails in winpthread cancellation with 0xc0000028. shader_recompiler_compute independently fails in the embedded-fetch lane-spill case during SSA instruction use replacement. Both remain unresolved. This is a large integration across 327 files. The unresolved failures and compatibility with other games require investigation before merging. Maintainer review of scope and whether to split the changes would be appreciated. Submitted by Danek (@⁠danekbiglike).
Since bd41e2f6 a texture view entirely past MAX_MIP is taken as a mip
chain of its own that starts at its base mip (PPSA02110 compresses mip 1
through a T# that declares one level), and the view is unsupported, a
fatal error, when that chain does not have the layout of the view's mips.
ASTRO BOT samples mip 6 of a 1920x1080 target whose T# declares mips 0-5:
mip 6 lies in the mip tail the declared chain already holds, the rebased
30x16 chain does not match it, and the game closed while it loaded
("unsupported texture mip view changes physical layout: base=6 last=6
max=5 extent=1920x1080x1 tile=27").

The rebased chain is still tried first; when it does not match, the view
is resolved against the declared chain, as before bd41e2f6. A view past
MAX_MIP that fits neither (a tail mip of a T# with one level) is still
unsupported.
Workarounds that change what a game computes should say so in the log,
without an environment variable, so that a session shows whether one was
applied. Common::HackNotice::Report() prints a "[HACK]" line the first
time each distinct (workaround, site, shader, where) key fires, then a
summary of the keys that kept firing every 10 seconds. The counters are
lock-free atomics, so hot paths can report without measurable cost.

The unit tests that compile the shader walkers do not link the logging
library; they build the notices with KYTY_HACK_NOTICE_STDOUT and print to
stdout.
GTA V's (PPSA04263) skinning compute shaders pick their output buffer per
wave: a waterfall loop reads a key with V_READFIRSTLANE, loads the store
V# with S_BUFFER_LOAD_DWORDX4 from a table of V#s at key * 16, and stores
through it. Resource tracking only accepted GPU-selected V#s for raw DWORD
loads, so the dispatch failed with "buffer descriptor is not a valid
runtime value". The shaders run in Fidelity mode and feed the ray-tracing
BVH.

Recognize a store V# whose DWORDs are consecutive reads of one table at
(key << 4) + offset, mark its memory IndirectBuffer and the table binding
as selecting written targets. The SPIR-V store resolves the V# per lane
with the same address and bounds rules as indirect loads and writes
through BDA, which only reaches memory that a cached buffer holds.
Graphics stages are not supported and keep failing.

Before the dispatch, IndirectWriteTables caches every target the table
names, so that no store is dropped. In GTA V the table is the game's
2 MiB descriptor heap (131072 entries, about 40000 buffer V#s over
600 MiB) and it is prepared about 150 times a second. Each table keeps a
snapshot and only rescans the pages the CPU wrote since the previous
preparation (MemoryTracker::ConsumeCpuWrites, fed by a per-page bit set
whenever a page becomes CPU dirty), so an unchanged table costs a few
microseconds. Targets that share a caching page are cached as one
buffer. Targets whose buffers the garbage collector released, or whose
memory was not mapped yet, are cached again later. T#s, S#s, V#s
without a data format (the shader drops those stores) and unmapped
targets are skipped. A table the GPU wrote is downloaded first. The
targets are prepared before PrepareBda, which uploads the CPU writes of
the new buffers.

Which bytes the stores wrote comes back from the GPU: each store sets the
bit of its caching page in a write bitmap in the second half of the fault
buffer (an atomic OR only when the bit is clear). Once the submission
completed, the bitmap is read back like the faults; the written bytes of
the targets become GPU modified, and images over them are invalidated as
for other buffer writes. Pages the CPU dirtied since keep the CPU's
bytes. The fault-buffer parser takes its record capacity from the area it is
given (the write bitmap's areas are not the size of the fault areas); like
upstream's since fd04c3fa, it leaves the pages past them in the bitmap for
its next pass.

A dispatch that prepared targets gets the shader write hazard barrier.

Tests: resource tracking of table-selected store V#s,
BufferStoresGpuSelectedDescriptors (stores and write bitmap,
--indirect-buffer-only), IndirectWriteTables
(--indirect-write-tables-only) and the memory tracker's CPU-write and
GPU-marking helpers.

An unreadable V# table prints a "[HACK] V# table of indirect writes is unreadable and ignored"
notice (src/common/hackNotice.h): the first application of each distinct case, then a summary every 10 s.
GTA V (PPSA04263) CS 0xc6c91cf1882cdc3b shades ray hits by sampling
material textures whose T#s it reads from a 65536-entry descriptor heap
at an index taken from GPU-written material records. Indirect images
could only probe host-readable material keys and bind at most 64
candidates through a switch, so the shader was unsupported.

When the key is not a probeable material word, resource tracking now
keeps the table itself (also through a masked table offset, and when
several image instructions share one T# load). Materialization reads
the table, deduplicates its valid T#s into slots (reusing them while
the table is unchanged) and appends an entry-to-slot mapping to the
flattened SRT. The slots follow the resources of the root's image
binding, sized to a power-of-two capacity; the shader computes entry
= key & mask, loads its slot and samples the element with NonUniform
indexing. The host resolves each slot through the texture cache and
binds T#s the root's view cannot read, or whose guest memory is gone,
as null images.

The table keeps the T#s of the textures the game has unmapped since, as
image heaps do. PS5 never samples them (the GPU would fault on the
unmapped pages), so an element whose guest memory cannot be read binds a
null image; in Fidelity mode 10 to 20 such textures (128-704 KiB) show up
per session. Table elements resolve through
TextureCache::FindImageSpeculative, which declines depth/color
recreations (a few heap T#s alias depth buffers the frame renders to, and
converting them cost two recreations per frame).

One root of c6c9 compares against its elements (depth T#s, D16 and D32):
the shadow maps it reads are R16 and R32 float colors the game writes
(256x256 cube faces, 512x2048 cascades, 512-1024 square maps), whose
bytes PS5 samples as depth. Vulkan compares only depth formats, so such an
element samples a depth copy of the color image
(TextureCache::FindDepthCopy): an unregistered image with the color
image's layout in the T#'s depth format, one per color image and format,
copied again when it is acquired after the color image was written, and
deleted with the color image. Image counts the transitions to a write
access, which every GPU and host write of an image takes. Declining these
elements bound about 65000 null images every 10 s in Fidelity mode.

The shader binds five roots of 4096 elements each; resolving all of them
on every dispatch took 17% of the GPU thread. RenderExecutor keeps each
element's resolution by T#, shared by roots with the same view, and
resolves it again only when an image overlapping its memory was
registered or unregistered (a per-page epoch in the texture cache, and a
global image-set epoch that skips the per-range check while no image
changed), when the guest backing changed (kernel BackingEpoch), or
always when it has DCC metadata. Elements declined by the texture cache
are revalidated against the guest range the lookup examined. The table
words are read into a reused buffer.

Upstream (cd066010) replaced the probing of material keys with a direct
image-table lookup that makes every distinct T# of a bounded table its own
specialized image. On GTA V's ray tracing heaps it took ~9800 table words
for candidate T#s and failed ("sampled image descriptor 9813 uses
unsupported format 60"). Scalar 32-byte T# tables that are not indexed by
the workgroup, including those whose key is a plain material word (the
four roots of c6c9 that used to probe their keys), take the table path
above; the direct lookup keeps the other tables.

Since upstream 892e70c8 a null T# binds as a native null descriptor with no
image id and no view, and so do the table elements the texture cache
cannot use. RebindImages() skips these elements instead of taking them for
stale and acquiring the view of the null image id, which closed Demon's
Souls (PPSA01342) with "!is_allocated(id)" in slotVector.h:41.

Elements the speculative lookup declines otherwise, and those whose image
cannot be viewed in the format their T# reads it as, bind null images
instead of the memory PS5 would read. Both are announced with a "[HACK]
bindless table texture bound as null image" notice in the normal log
(src/common/hackNotice.h): the first application of each case, then a
summary every 10 s. GTA V raises neither. Any other error of the
resolution is fatal, as for other textures.

Marvel's Wolverine (PPSA03671) ended about a minute after boot with
"image.table_capacity != 0u && inst.GetOpcode() != ImageSampleRaw && !=
ImageQueryDimensions" in ApplyResourceSpecialization: resource tracking
chose the bindless T# table for an image that the shader also reads or
gathers through another instruction, which the table binding does not
serve. Images that other instructions read keep the other lookups of
indirect images; only images the table path samples are bound to the
table.

Also: run GTA V's ray tracing dispatches.

With BVH intersections and GPU-selected scalar loads supported, GTA V
(PPSA04263) still could not run its ray tracing compute shaders:
0xfa8b1616fddc203b, 0x6db33a2bcb077bc3, 0xca313cf56ef25496 and
0x651da332bc4a3f98 in Fidelity mode and 0xedc5bdc9a5687671 in Performance
RT mode. Skipping them left Franklin's house with dark, wrong indirect
lighting in Fidelity.

- The any-hit alpha test samples a T# loaded from a material table
  (S_BUFFER_LOAD_DWORDX8 at (material >> 4) << 5). Its SGPRs are reused
  for other data, so the T# words also reach Phis of those other
  register lifetimes and the bindless table plan was rejected. A T# read
  whose other uses are only Phis now stays an ordinary scalar load for
  them while its image uses take the table path.
- 0xedc5bdc9a5687671 also queries the size of a material table texture
  (IMAGE_GET_RESINFO); ImageQueryDimensions now selects the table
  descriptor like sampling does.

Tests: ResourceTrackingTests (indirect scalar reads, GPU-dependent
address reads, bindless image table query and shared registers) and
ScalarLoadsGpuSelectedDescriptors (--indirect-buffer-only).

GTA V also exited with std::out_of_range in ResourceControlFlow when
switching to Fidelity, because the kept scalar reads were never given a
buffer; they are now collected as buffer accesses like the other reads.

Also: make bindless table bindings cost what changed, not every slot.

GTA V's (PPSA04263) ray tracing in Fidelity mode binds bindless texture
tables of ~16k slots naming 8.5-11k distinct textures (cs c6c91cf1882cdc3b
on the graphics queue, ca313cf56ef25496, fa8b1616fddc203b and
651da332bc4a3f98 on the compute queues), about four times per frame, and
almost nothing in them changes from frame to frame. Every binding copied
every distinct TextureBinding, looked every slot up by its T#, checked
every element's image, acquired its view, touched it in the texture cache's
LRU and recorded its transition, and every resolution ahead of execution
rebuilt its 64k-entry table from scratch: ~38 ms per frame of the
execution thread, plus 5-7 ms idle waiting for those resolutions.

- The prepared bindings point at the elements of the table resolution
  (elements a resolution drops stay alive until ResetBindings()), each slot
  remembers its element so an unchanged T# skips the lookup, an element is
  resolved once per binding, the fields every binding reads share a cache
  line, and an element keeps its view while its image keeps the state of
  the last acquisition, as ReuseTextureLookup() does for direct textures.
  Table resolutions and retired element maps live in deques:
  std::unordered_map has no noexcept move, so a growing vector copied the
  elements and left the prepared bindings and slot memos pointing at freed
  ones (a crash in RebindImages once c6c9 sampled nine tables).
- Each program keeps the state of its last table binding: the T# of every
  slot, the elements and their descriptors. While the slots are unchanged,
  a binding only revisits the elements that a change could affect: those
  over pages where the texture cache registered or unregistered an image
  since (a short history of those ranges is kept, as is one of guest
  backing changes), those whose resolution depends on any backing change or
  DCC metadata, and those whose image is no longer bound as recorded
  (removed, replaced, dirty, another view or layout, also bound otherwise by
  the operation). The elements' images are pinned in the texture cache
  instead of being touched on every binding: the garbage collector and
  overlap resolution keep them.
- The check of the reused elements only reads: it is split over three
  helper threads that the execution thread joins, each flagging the
  elements of the chunks it claims; the flagged elements are marked in
  order afterwards. The helpers spin briefly for the next job and then
  sleep.
- Only the slots of the elements a binding visited are rewritten (about a
  hundred elements per dispatch).
- Materializing a bindless image table reuses the last tables the thread
  built when their words are unchanged: resolutions ahead of execution
  materialize into a ring of snapshots, so the previous snapshot almost
  never held an equal table.

Fidelity mode, standing still, debug build, each part turned off in turn:
reusing unchanged tables saves ~12 ms per frame of the execution thread,
the helper threads ~5 ms (`rebind images` 7.8 -> 2.7 ms) and the
per-thread image tables ~9 ms of idle time.

Null elements (native null descriptors without image or view, see
892e70c8) are never stale and have nothing to acquire: a reused table sees
them as unchanged instead of revisiting them on every dispatch, and
RebindImages() leaves them bound as null descriptors (Demon's Souls closed
with "!is_allocated(id)" in slotVector.h:41, in FindTexture() called from
RebindImages()). A GPU test dispatches a material shader over a table of
null entries twice, so the second dispatch reuses the table bindings.

Later the game adds the textures it streams in to the tables (null slots name them now): a
single new T# resolved and bound all the slots again, 3-5 ms of the execution thread per RT
dispatch (fa8b1616, ca313cf5, 651da332, 6db33a2b) and up to 16 ms for c6c91cf1, several times
a second. When only a few slots changed (at most an eighth of them), ReuseTableBindings() binds
those slots to the elements of their new T#s (new elements join the state and are visited like
changed ones) and reuses the rest. The tables are resolved slot by slot again once many
elements are no longer named by any slot, so their images do not stay pinned.

Also: reuse bindless tables across draws and patch the slots whose T#s move.

GTA V (PPSA04263) binds programs with bindless image tables of 16384 T#s
about 90 times a second in Fidelity mode. To reuse the previous binding of
a program, every binding compared each slot's T# with the one recorded,
about 6 % of the execution thread's time in Fidelity.

The materialization already keeps a table's slots when the table's words
did not change. The slots now carry an id that follows them when they are
reused, and the binding state records the id of the slots its values were
taken from: with the same id there is nothing to compare. In Fidelity
(modeswitch save) 1491 of 2000 comparisons are skipped.

Also: check the elements of reused bindless tables by version.

GTA V (PPSA04263) binds programs with bindless image tables of ~16 000
distinct elements about 90 times a second in Fidelity mode. While the T#s
of a table stay the same, each binding still read every element's
resolution and image to find those whose binding changed (image removed,
replaced, dirty, another view or layout): ~550 us per binding, about 50 ms
of the execution thread per second, almost all of it cache misses on the
scattered images. About 40 elements change per binding.

The texture cache now keeps a counter per image slot that advances with
every change the check reads: CPU, GPU and buffer dirty marks, tracking,
registration, reuse of the slot, usage, stencil association, rebind
requests and layout or access transitions (Image::HeapChanged() counts
too). Each table element resolution has a counter that advances when its
texture, view or layout changes. A table binding state records both
counters for each element it last found unchanged: while they hold, and
the operation does not bind the element's image itself (the check reads
that binding state), the element is still unchanged, and the check only
compares counters held in dense arrays. Elements whose counters moved are
checked as before, on the helper threads when there are many. Depth
images are always checked: a depth copy also depends on its color image.

In Fidelity (modeswitch save, native RT) a binding now checks ~230
elements instead of ~16 000 and finds the same ~40 changed (a verification
of every skipped element against the full check found no difference in 133
million, switching to Performance and back and driving). The check takes
89 us instead of ~750 us per binding (the whole rebind 190 us instead of
870 us), and the game runs at 23.79 / 23.36 fps instead of 22.44 / 21.72
(+7 %). Performance mode reuses almost no tables: 55.36 / 54.18 fps
against 55.70 / 54.85, within the drift between the runs.

Also: copy reused bindless table descriptors from a set of their own.

GTA V's (PPSA04263) native ray tracing in Fidelity mode binds its
bindless texture tables once per frame in each of four dispatches: cs
b93ab2ec5c5caf00 (three tables of 16 384 slots, 49 175 sampled image
descriptors), 0b41af19bddf132c, 6aeb221de7ff018e and d645a5101b936ce7
(one table each, ~16 390 descriptors). Every binding allocated a new
descriptor set and wrote all ~98 000 descriptors into it, although the
tables are reused from the previous binding (only the ~900 elements a
binding visits can change, and their descriptors are almost always the
same): vkUpdateDescriptorSets took 13.4 ms per second of the execution
thread while driving with Trevor, and copying the slots into the write
array another 3.4 ms.

Each table binding state now keeps its slot descriptors in a descriptor
set that is never bound (DescriptorHeap::CommitPersistent(), a pool of its
own). A binding that reuses the state copies its table ranges from that
set into the new set with VkCopyDescriptorSet, writes only the slots
around the tables, and first writes into the state's set the slots whose
descriptors changed. A binding that wrote the tables (slot by slot, or
with push descriptors before) copies them into the state's set
afterwards, while the state stays valid. The state's set changes together
with its slot descriptors, so it holds the same descriptors the binding
would write.

Trevor driving (fidelity_trevor_vehicle_20261106, native ray tracing),
the two ways alternating every 2 s in one run: CommitBindings() of the
four dispatches took 1.19 ms per frame writing the tables and 0.51 ms
copying them (b93ab2ec 514 -> 252 us, 0b41af19 290 -> 108 us,
6aeb221d 228 -> 88 us, d645a510 162 -> 63 us), ~19 ms per second of the
execution thread.

Also: keep the view of a current depth copy in a bindless table.

GTA V's (PPSA04263) native ray tracing in Fidelity mode samples color
textures of its bindless tables with depth T#s: they are bound as depth
copies of the color images (TextureCache::FindDepthCopy()), which are
depth images and so visited by every binding. cs b93ab2ec5c5caf00
visits ~710 of them per dispatch. A depth copy has no guest memory, so
its acquired view was never kept (the view is kept only for images with
guest data), and every visit acquired it again (FindTexture(), which
refreshes the copy from its color image when needed).

The view of a depth copy is kept like any other while the copy is
current (TextureCache::DepthCopyCurrent()): it holds its color image's
contents (DepthCopyStale()) and the color image is clean and fully
tracked, so acquiring it again would neither copy nor refresh anything
(RefreshDepthCopy() only refreshes a color image that is dirty or no
longer tracked, and copies only after the color image was written).

Trevor driving (fidelity_trevor_vehicle_20261106, native ray tracing),
the two ways alternating every 2 s in one run: the median
RebindImages() of b93ab2ec took 290 -> 220 us (60-145 us less per
frame as the scene grows busier), with ~10 instead of ~710 FindTexture()
calls per dispatch.

Also: merge the spans of new bindless table elements at once.

GTA V's ray tracing dispatch b93ab2ec (Fidelity with native ray tracing)
binds three bindless tables with ~26 000-47 000 elements. While the game
streams textures in, a binding that reuses the tables takes in up to
hundreds of new elements (thousands in the "Franklin and Lamar"
mission), and each one inserted its page spans into the sorted span
list, moving every span after it: 5-9 ms of the execution thread in one
binding while driving fast, and up to 97 ms in a binding of that
mission.

The spans of the new elements are appended and merged into the list
once, in the order the insertions gave. In one pass of that mission,
alternating both every 2 s: bindings that add 65-512 spans take 55 us
instead of 360, more than 512 0.3 ms instead of 56 ms; up to 8, 23 us
instead of 14.

Also: patch bindless tables whose T#s move between slots.

In the "Franklin and Lamar" mission of GTA V (Fidelity with native ray
tracing), the ray tracing dispatches b93ab2ec, 0b41af19, 6aeb221d and
d645a510 bind a table that the game fills with ~15 000 T#s and in which
it moves thousands of T#s to other slots every frame, at times most of
them. When more than an eighth of the slots changed, a binding resolved
all the slots again (49 152 for b93ab2ec), wrote all their descriptors
and pinned all their images, and the elements left unused made the next
patch resolve everything again as well: the execution thread spent
~550 ms/s in these four dispatches and bound the game to 17-20 fps on
foot and in the car.

Reused tables are now patched however many slots change (binding a
changed slot costs a fraction of resolving a slot), and the elements
that no slot names any more are dropped from the state, their images
unpinned, instead of resolving the tables again.

In one pass of that mission alternating both every 2 s: 20.5 -> 22.1
fps on foot and 15.5 -> 20.4 in the car; b93ab2ec 8.5 -> 6.9 ms per
dispatch, 0b41af19 4.7 -> 3.3, 6aeb221d 2.2 -> 1.5, d645a510 2.2 ->
1.4; 2 bindings resolved slot by slot instead of 459.

Also: bind table slots whose T# moved to another element of the state without a visit.

In the "Franklin and Lamar" mission of GTA V (Fidelity with native ray
tracing), the bindless table of the ray tracing dispatches (b93ab2ec binds
it three times, 0b41af19, 6aeb221d and d645a510 once) changes in 3 000 to
15 000 of its 16 384 slots per binding while the car drives, and 97 to
99.9 % of those slots now name a T# that another slot of the table already
names: the game moves its textures between slots. Each changed slot was
resolved again, looked up by element pointer in a hash map of the table
binding state, and its element marked for a visit (bind the image, check
its view, transit it, write the descriptors of all its slots), even when
the element and its descriptor had not changed: about 6 ms of the
execution thread per frame, the thread that sets the frame rate here.

An element the state already has keeps a descriptor that holds for any
of its slots: whatever may change it (an image registered over its range,
a backing change, a stale view, a layout change) marks it for a visit by
the same checks as for its other slots. The changed slot now takes the
element's index and is written from the element's descriptor when the
bindings are committed; only elements new to the state are resolved and
visited. The state finds an element by its version slot (an index the
element keeps for its life, unique among the elements alive) in a vector
instead of by pointer in a hash map, and the slot memo of the table
resolution carries that index, so a moved slot reads neither the element
nor a hash map.

Measured in one pass, alternating the old and the new code every 2 s
(debug build, Franklin and Lamar):
- on foot: 20.9 -> 24.9 fps; in the car: 19.8 -> 23.4 fps;
- per dispatch: b93ab2ec 7.04 -> 5.37 ms, 0b41af19 5.67 -> 2.80 ms,
  6aeb221d 1.72 -> 1.00 ms, d645a510 1.56 -> 0.85 ms;
- the slot patch of b93ab2ec 1.95 -> 0.81 ms, its visits 0.87 -> 0.51 ms.
Upstream now converts float inline constants (240-248) read by 64-bit
operands to their f64 bits inside ReadU32Pair (the same change as our
earlier version of this fix). ReadMask also goes through ReadU32Pair, but
a wave32 lane mask is a 32-bit operand and must keep the single-precision
word, so ReadMask only uses ReadU32Pair for wave64 and reads the raw
32-bit value otherwise.

Test: --inline-f64-only now runs upstream's
ScalarVector64BitFloatInlineConstants.
Graphics pipelines declare stencil op, compare/write mask, reference and
depth bias as dynamic state, but the dynamic state cache only emitted
them while the stencil test or polygon offset was enabled. Vulkan
requires every dynamic state of the bound pipeline to be set in the
command buffer before the draw; the validation layer reported
VUID-vkCmdDraw-None-07848 and VUID-vkCmdDrawIndexed-None-07848 in GTA V
(PPSA04263). Emit them whenever they are dirty: Invalidate marks them at
the start of each command buffer, and the values are unused while the
test or bias is disabled.
HandleFault treated any fault outside the GPU-mapped ranges as a guest
access violation, even when cache tracking itself protected the page.
Ask the page manager whether the page is watched and resolve such
faults like mapped ones.
GTA V (PPSA04263) clears the DCC metadata of its render targets with a
uniform-fill compute shader every frame. Upstream's TryConsumeComputeFill
writes such fills to guest memory on the CPU, and FillBuffer wrote them
through the guest mapping so that write faults would invalidate the cached
buffers and images: one fault for every tracked page of the range. A CPU
buffer fill now invalidates the buffer and texture caches for its whole
range first and then writes it without faulting.

Device-address memory keeps this tree's epoch-based synchronization instead
of upstream's queue of ranges (QueueBdaSync/TakeBdaSync): PrepareBda does
nothing while no page became CPU dirty, no buffer was registered and no
range was mapped since the last pass, and otherwise visits only the
tracking regions whose CPU-dirty epoch moved. TextureCache gains
IsRegionGpuModified, which tells whether an image over a range holds GPU
writes.

The queue goes with what upstream built on it: the batched upload behind
one barrier pair (b510053e8; this tree batches the synchronization per
guest submission) and the DMA-accessed tag of the BDA page-table entries
with its get_bda_pointer changes (0ec2cd5d5), with their tests. Faults are
logged and cached by the fault-buffer handler again.

Since b54057942 upstream selects the clear of GPU-written DCC metadata on
the GPU with conditional rendering instead of draining it, so the noted
compute-fill values this commit used to keep for MaterializeColorClear are
gone: in play they answered none of ~3 M clears.

Also: synchronize CPU-dirty runs a few clean pages apart together.

GTA V in Fidelity mode with native ray tracing, driving: the full synchronization of the cached
buffers that device addresses may reach (PrepareBda, ~120 per second, most of it for cs
b93ab2ec5c5caf00) took 110-150 ms per second of the execution thread, 55 % of it in
VirtualProtect: ~23 000 calls per second protecting the uploaded pages again, 3.3-3.5 us each
for ~6 pages. A call costs ~2.3 us of its own (with other threads of the process running, the
TLB flush on the other processors) and ~0.1-0.2 us per page. The synchronization handled every
run of CPU-dirty pages on its own, so the page tracker protected each run with its own call,
even when the next run of the same buffer was a few clean pages away.

Runs at most 32 pages apart are now synchronized together. The uploads are the same, one per
dirty run, and the page tracker protects the runs with one call through the clean pages between
them, which keep their protection. Measured with the gap switched every 2 s within a run, so
that both settings see the same scene (three runs): per uploaded byte, the synchronization took
3.6-6.7 % less time and made ~24 % fewer protection calls. A 96-page gap took 1-3 % more time
(40 pages per call).

Also: synchronize only the BDA regions that hold buffers.

Before each dispatch that reads through device addresses, PrepareBda
walked every 4 MiB tracking region of every mapped range, looking each
one up in an unordered_map, and each new buffer or mapping cleared that
map and ran a full pass over all mapped memory. In Demon's Souls the
mapped ranges span thousands of regions and buffers are registered every
frame: the execution thread spent 80% of the title menu in
SynchronizeBuffersInRanges (hashing, heap allocation), and the menu ran
at 5-7 fps.

Keep per-region tables (buffer count, a bitmap of the regions that hold
buffers, the synced epoch) and walk only the regions with buffers. A
registered buffer, or a range mapped since the last pass, forces its
regions instead of a full pass.

Demon's Souls title menu (vblank 180): 5-7 -> 82 fps.
An SDL gamepad remap event aborted the emulator through
EXIT_NOT_IMPLEMENTED. A new mapping changes how SDL translates the
device, and SDL sends no release or neutral axis events for the old
mapping, so input held on the active controller would stay stuck. A remap
of the active controller now resets its input state instead.
Guest code follows the SysV ABI, which lets leaf code keep data in the
128 bytes below rsp. Windows writes exception frames there, and the
emulator raises exceptions constantly for memory tracking. GTA V
(PPSA04263) keeps inflate_fast locals in the red zone; when a tracked
page faulted during its loop, the "[RAGE] HDD Streamer" thread reloaded
a clobbered input pointer and crashed reading 0xffffffffffffffff, late
in the prologue.

Protect the red zone unless --no-redzone is given. The launcher passes
--no-redzone when its checkbox is off, and new configurations default to on.
Upstream writes the driver pipeline cache on the shader store thread
when a pipeline creation finds that a minute has passed since the last
write (1b7ea368). The pipelines created last waited for another
creation, or for a clean exit, to be written, and a crash or a closed
window lost them.

Marvel's Wolverine (PPSA03671) spends about three minutes in the driver
on each pipeline of its ray tracing shader cs 1a04c58a9fbc2052, so
closing the emulator before the next write threw the work away and the
next start compiled the pipeline again. A pipeline whose creation takes
five seconds or more now has the cache written soon after it, at most
every 20 s: with cold caches nearly every creation is slow (Demon's
Souls, PPSA01341, while its pipeline manifest is replayed during a
load), and writing the whole cache (over 200 MB) every second or two
held pipeline creation back for more than ten minutes. A timer thread
checks four times a second whether a changed cache is due, so the
pipelines created last are written without waiting for another
creation.
Profiling the emulated GPU thread in GTA V (PPSA04263, ~3500 draws per
frame) showed per-draw costs that did not depend on what changed. Shader stage
lookup keys are now built in a local buffer and copied once.

This commit also reset the 10 KiB vertex input info in place, and kept a
per-thread cache of the guest backing mappings used last (each guest
backing read took a global mutex and a std::map lookup; ~16000 small
buffers a frame in GTA V's city at night). Upstream dropped those resets,
as callers value-initialize the input info (8c1db95c), and reads guest
backing through a lock-free page table (1b59ee62), so those parts are
gone. The test that a lookup a thread repeats does not outlive the
mapping it resolved stays.

This commit also compiled each resource plan into a dense node graph that
replaced the interpretation of the shader IR on every draw (13-16 ms per
frame, 2.87 -> 0.75 us per evaluation). Upstream now walks every resource
plan with its x86 walker (d7856753), so that part is gone.
GTA V (PPSA04263) pixel shader 0xf6b18542ea0e938a, drawn at the car
dealership, builds S# word 3 from data resource tracking cannot follow
("GetSamplerResource dword 3 is not a valid runtime value") and the
emulator exited. Word 3 only holds the border color pointer and type, so
sampling inside the texture does not depend on it.

When only word 3 is untrackable, keep the runtime-valid operand of an OR
that mixes lane data into it (the user-data border fields), or use a
transparent black border, and print a warning. SampleAdjust scratch bits
ORed into the word are dropped the same way instead of failing.

The existing console warning becomes a "[HACK] sampler border color word changed" notice in the
normal log (shader hash and pc) (src/common/hackNotice.h): the first application of each distinct case, then a summary every 10 s.
GTA V (PPSA04263) draws 3200-5000 times per frame and the emulated GPU was
a single thread that parsed every PM4 packet, resolved every draw and
recorded and submitted every Vulkan command itself, about 15-17 us per
draw: 11-18 fps in Performance mode, with the host GPU mostly idle.

The emulated GPU now runs in stages on their own threads
(KYTY_GPU_PIPELINE=0 or --gpu-pipeline 0 runs everything inline):
- Command processor: parses PM4 and emits every guest-visible effect as an
  ordered GpuOperation (draws, dispatches, end-of-pipe labels and
  interrupts, flips, WRITE_DATA, COPY_DATA, DMA_DATA, occlusion, constant
  RAM and LOD dumps, barriers, flushes, GC). Draws carry copy-on-write
  snapshots of the context, user config and shader registers. Indirect
  arguments and NUM_INSTANCES are read when the operation executes.
- Execution: runs the operations in order and owns the renderer and its
  caches, so labels, interrupts and flips are published only after every
  earlier draw captured the guest memory it reads.
- Recording: the renderer records through a CommandRecorder into a
  CommandStream of 64 KiB chunks; a recording thread replays them into
  pooled command buffers and submits them. Ticks are still allocated in
  order at submit time, so every wait keeps its meaning.
- WAIT_REG_MEM, COND_EXEC, branches and predication are answered from a
  journal of the CP writes not executed yet, waiting only for the one
  operation whose value is unknown instead of draining the pipeline.
- A suspend point registers the completion that frees the next one as an
  operation, at its place in the stream: the command processor runs ahead
  of what the execution thread recorded.
- Handoffs are lock-free SPSC rings with cache-line separated indices;
  waiting spins with an exponential _mm_pause backoff and only sleeps after
  KYTY_GPU_SPIN_US (2 ms) without work, so no stage enters the kernel within
  a busy frame. Stage threads run at high priority on pinned cores
  (KYTY_GPU_THREAD_CPUS, default 4,6,8; KYTY_GPU_THREAD_PRIORITY=0).
- RELEASE_MEM labels without an interrupt no longer submit a command
  buffer each (~200 per frame); they submit only once 64 draws or
  dispatches were recorded. Draws reuse their render state instead of
  zeroing 36 KiB each, and the GPU timeline is queried only when a deferred
  operation may be due instead of ~3700 times per frame.

Measured on the Los Santos route: 25-26.5 fps against ~20 with the
pipeline off; screenshots identical. gpu_pipeline_tests covers stream
ordering, chunk crossing, cross-thread replay, the SPSC rings with both
sides sleeping and the progress counter.

Upstream's RELEASE_MEM decoding (bf5dd62e, dc40478e, 6aaa5332) runs as one
operation on the execution thread, which writes the label and defers the
interrupt; a label-only release still flushes only once a batch of work was
recorded. WAIT_UNTIL_SAFE_FOR_RENDERING waits, as upstream does since it reverted
a358b847 (1be1c6c4), until no flip of the display buffer is pending; the
wait runs on the execution thread, in operation order, because flips the
command processor ran ahead of can still make the buffer busy.
Upstream's occlusion counters are published on the execution thread, and a
Z-pass predication waits for that publication.
Upstream's --flush-draws (7d4e0d9b) counts the draws the execution thread
records into each command buffer and submits before the one that reaches
the count.
Upstream's DLSS and FSR upscale of PSSR (782a85c6, e35360fa) records the
upscaler's commands into a Vulkan command buffer, which the execution
thread does not have with a deferred recorder, so PS5 Pro mode with
--dlss scaled linearly. The execution thread now picks the context's
quality mode and reset as upstream does, and records a command that
creates the upscaler feature the first time and evaluates it where the
command buffer is recorded (at once with a direct recorder, on the
recording thread with a deferred one); it records the linear upscale
there instead if the upscaler refuses the feature or the evaluation
fails. Replaced features are released once the GPU finished the commands
recorded before, and the upscaler is called by one thread at a time.

Demon's Souls (PPSA01341): a ProgressCounter that several threads wait
on wakes all of them. HostCopyQueue::m_completed has two waiters, the
execution thread (Drain(), before a guest fault's urgent command) and
the Vulkan recording thread (WaitFor() before a submission). WaitFor()
kept one shared wait target and cleared it when it finished, so one
waiter erased the other's target and the copy thread's last Notify()
found nothing to wake: the execution thread slept for good, and a guest
thread faulting on a GPU-written page waited for its urgent command for
ever; the title screen froze at 0 fps right after "Continue Offline",
more often the faster the menu ran. WaitFor() now lowers the registered
target and registers again after a Notify() took it out; Notify() takes
out the target it found and wakes every sleeper.

Also: cut per-draw lookups and driver stalls of the emulated GPU.

Measured on GTA V (PPSA04263) in Performance mode in Los Santos (2500-5000
draws per frame). The execution thread of the emulated GPU is the
bottleneck: the game spends most of each frame waiting for it.

- Draws resolve their shader programs ahead of execution on a resolve
  thread between the command processor and the execution thread
  (GPU_PIPELINE_RESOLVE, pinned to its own core): program selection, SRT
  materialization and the vertex fetch tables, about a third of the
  execution thread's work. The resolve thread never compiles and logs the
  guest memory it reads: upstream's x86 SRT walker records the address and
  the value of every load, a load that faults there (a GPU-owned or an
  unmapped page) fails the walk instead of downloading GPU-written bytes,
  and strict and shader-state reads go through the backing store.
  Resolutions go through a ring with per-operation resource snapshots (a
  program keeps its modules in a deque so their addresses stay valid). The
  execution thread repeats the logged reads the way its own walk reads
  (plain loads, strict reads for specialization memory) and falls back to
  resolving the draw itself when a byte changed or the GPU owns it, so
  draws see guest memory as it is when they execute. Indirect draws whose
  records the GPU reads are resolved by the execution thread.
  Programs are resolved under a spinlock, which also keeps the walker's
  per-plan scratch to one thread at a time.
- Graphics programs the resolve thread misses are compiled by six worker
  threads (translation, SPIR-V and shader module), so the shaders of a new
  area compile in parallel instead of one after another on the execution
  thread, which waits for a worker compiling its program without holding
  the lock and compiles itself what the workers did not add (and reports
  unsupported shaders as before). While loading Los Santos the execution
  thread compiled 346 shaders in 1.4 s in one frame; now it compiles 107
  (0.4 s) and waits 16 ms for the rest.
- Tracking regions without GPU- or CPU-dirty pages answer GPU-dirty queries
  and read-only upload scans without walking their pages (an atomic flag
  derived from the dirty bits).
- Texture descriptions are derived once per T# and shader view, and each
  color slot remembers its last two descriptions per CB registers and
  slice offset: tiling sizes, mip layouts and validation were recomputed
  for every binding of every draw.
- Image lookups that found an image with the same backing are remembered
  until an image on the pages of the range is registered or unregistered
  (84% hits); overlaps and insertions still take the full path.
- Unmapping memory drains the GPU only when the range has GPU-owned pages
  or images, or a pending completion may write guest memory in that
  range (completions record the range they write). Completions that only
  touch host state (cache bookkeeping, releases, flips, interrupts, fault
  scans) are deferred as host operations and never count: they were
  pending almost always, and a streaming game drained the GPU about 12
  times per frame (5-8 ms). Completions that run after such an unmap no
  longer act on the unmapped range.
- Unmaps run on the execution thread before its next operation instead of
  after its whole backlog. The guest unmaps memory only after the labels of
  the work that used it, which the execution thread writes after executing
  that work. Each munmap waited about 3 ms for the backlog (up to 30 ms
  per frame) while GTA V's streaming job held a mutex; the graphics queue
  waits (WAIT_REG_MEM) on a counter that job increments after it flushes
  its sceKernelBatchMap2 batch, so frames took 80-280 ms.
- The completion that frees the next suspend point is deferred as a host
  operation, so it does not make unmaps drain the GPU.
- Nearly every draw renders to the targets of the draw before it with the same target
  registers (97% in downtown views). Draws reuse the targets the draw before acquired
  (image discovery, DCC/CMask clear checks, attachment views, HTile state) while only draws
  executed in between (any other operation, a submission or a WAIT_REG_MEM invalidates them),
  the registers are the same (operations that share a context snapshot skip the comparison;
  snapshots now carry a unique id), no image was registered or unregistered, every target image
  keeps the tracking, dirty and ownership state the acquisition left it in, no work wrote cached
  buffers and no page of the color/HTile metadata became CPU dirty. Draws with depth or stencil
  clears acquire their targets themselves; layouts, transitions and binding state are still set
  by every draw. Reusing draws use the remembered targets in place instead of copying them.
- Sampled textures reuse the image and view the last lookup of their description found while
  no image on the pages of its range was registered or unregistered and the image keeps its
  tracking, dirty and usage state; they are written into the binding in place. Textures with
  metadata (fast clears) or stencil are looked up every time.
- Read-only buffer bindings reuse the buffer the last lookup of the range found while no buffer
  was registered or unregistered and no page of the range became CPU dirty (the epoch is read
  before the dirty check).
- The guest data draws stream into the stream buffer (20 MB per frame, four or five small
  CPU-written buffers per draw) is copied by a host copy thread (KYTY_GPU_THREAD_CPUS fifth
  entry, logical CPU 2 by default) from the backing store, in batches handed over after each
  draw. Submissions wait for the copies queued before them; the execution thread drains them
  before any operation other than a draw (labels, interrupts, flips, host commands) and before
  unmaps, so the guest never overwrites memory a pending copy reads.
- Draws stream the same small CPU-written buffers (frame and pass constants) again and again:
  within a draw window (only draws executed since the last other operation) a range streamed
  before keeps its copy while the stream buffer did not wrap and no work wrote cached buffers.
  The guest cannot overwrite data still to be read before a label, interrupt or wait tells it
  the GPU consumed it, and every such operation ends the window.
- Depth target descriptions are remembered per register state, hw_check() runs once per context
  snapshot, samplers are remembered without the sampler cache lock, the pipeline of the draw
  before is compared before hashing the key, remembered image lookups skip validating the image
  information again, the guest read log of a resolution merges contiguous reads and compares
  small ones inline, and the region tracking lock caches the thread id.
- The execution thread resolves a tracked page before it writes a label or WRITE_DATA, as
  the write fault would, instead of raising the exception.
- Programs persist across sessions through upstream's shader store
  (--shader-cache): the workers record the modules they compile there too.
  This commit used to keep its own _PipelineCache/<title>.<build>.programs
  store; upstream's store replaces it.
- Draws whose targets differ from the draw before only in the depth/stencil test controls or
  the depth bounds reuse its targets and refresh that state: half of the target acquisitions
  (1.56 -> 0.70 million per 2-minute run).
- Draws check the pending completions without the lock and query the GPU timeline every eighth
  call instead of on every draw; the vertex buffer arrays of a draw are not zeroed.
- Texture description keys hash 64-bit lanes with independent multiplies.
- Image lookup memos take the current image set epoch after a successful region check, instead
  of scanning the pages of the range again on every later draw once any image was registered.
- CPU accesses to pages the GPU wrote read back as urgent commands, before the operations
  queued since (the guest reads them only after a label written once the work before it
  executed): entering an area, a game thread waited 206 ms for the whole backlog.
- A stage that binds the same program with the same T#s and S#s as the draw before (about half
  of them) skips the texture description lookups and the sampler hashing.
- Deleted Vulkan images are kept in a small pool (32 images, 256 MiB) and
  reused by images created with the same parameters. A 512x2048 target
  rendered as R32 float and sampled as D32 depth every frame recreated two
  images per frame, each with a dedicated allocation that occasionally
  blocked for hundreds of milliseconds. Image creation: 135 -> 3 us.

Execution thread per draw (debug build with profiling): standing
14.4 -> 7.4 us, walking 10.6 -> 9.1 us. Free fall over Los Santos
(clean build, 3 runs each): 27-31 -> 37-45 fps, seconds below 25 fps
18-35 -> 1-2 per run. With the draw-to-draw reuse above the execution
thread spends 5.4 us per draw instead of 7.3 (profiled build, 5100-5400
draws per frame), and looking at downtown in free fall six alternating
runs average 41 fps instead of 32. Randomized tests cover RangeSet; gpu_pipeline_tests covers the host copy queue. With the program store this commit
had (now upstream's), dynamic depth bounds (now upstream's), urgent readbacks and the other
cuts above, the execution thread spends 3.8-4.5 us per draw instead of 5.4,
and the worst stretches of a free fall over Los Santos go from 29-40 to
45-50 fps.

Programs that bind upstream's resident image heap (27dc7c28) are resolved by
the execution thread: their heap views are acquired in draw order, after
ImageHeap::BeginDraw.

TextureCache::IsRegionRegistered (upstream) decides whether an unmapped
range holds images.

Further per-draw cuts of the execution thread in GTA V:
- A copy of a draw window's constants made in the current window answers
  right after the lock-free GPU-dirty check, before the obtain memo's
  CPU-dirty epoch and the region lock. The per-draw constants stay CPU
  dirty (rewritten every frame), so ~16000 copies and ~19000 reuses a
  frame in the city at night went through those checks only to find the
  copy made earlier in the same window; GPU writes advance the write
  generation the reuse compares.
- Slots whose T# did not change between draws keep their texture
  description; only the changed ones are looked up (GTA V's draws change
  one or two textures of programs with many). Sandy Shores, Performance
  mode: 55.2 -> 56.7 fps (5 interleaved runs).
- Clean backing reads check the GPU-dirty pages with the lock-free page
  test before searching the set of GPU-written byte ranges
  (TryReadGpuCleanBacking(), used by the validation of every draw's
  scalar reads): bytes the GPU wrote lie on GPU-dirty pages, ~0.7 % of
  the execution thread in the city.

This commit also tested dirty page ranges in place (BitArray::AnyInRange;
the hottest function of the execution thread, 7.7%), let regions without
dirty pages answer dirty queries without their locks, and clamped bound
buffers with a lock-free bitmap of committed pages (the range lock was
taken thousands of times per frame, 15-35 ms). Upstream now queries dirty
bits without the region lock (e5c35553), clamps fully backed ranges
without the state lock (3bd22044) and reads guest backing through a
lock-free page table (1b59ee62), so those parts are gone;
FindBackingPointer() walks upstream's page table. The draw targets live
in upstream's DrawTargets (7ae328b3): a draw that reuses the targets of
the draw before uses the memo's DrawTargets in place.

Also: do not lose the wake-up of a command processor that finds a reached target registered.

ASTRO BOT (PPSA21564 01.019) hung on its start screen with cold caches, a little after the
pipelines began to compile: no more frames and every thread asleep. In the dump the command
processor thread slept in ProgressCounter::WaitFor() for a register snapshot slot (sequence
0x9ab349) while the execution counter was at 0x9ab943: every emitted operation had executed,
the resolve and execution threads waited for work, no target was registered and the value the
command processor slept on (0x9ab32b) was long gone.

WaitFor() did not register its target when it found a lower one registered, and that one may
be reached already: the command processor leaves its own behind when it registers again after
a wake-up and finds its target reached. The next Notify() takes it out and wakes the sleepers.
When that Notify() runs at the value the command processor read (right after the execution
thread published it, or again when an urgent command interrupts the execution thread's wait on
an empty queue), atomic::wait() sees the same value and sleeps on with no target registered,
and no later Notify() wakes it. Long resolves and pipeline creations with cold caches leave the
command processor waiting while the execution thread runs dry, which makes it likely.

Sleepers now wait on a count of the wake-ups, which Notify() bumps when it takes a registration
out and a waiter reads before it registers, instead of on the value: every such wake-up ends the
wait and the waiter registers its target again. The host copy queue uses the same counter.

TestProgressCounter replays the sequence: a waiter woken with its target reached, a wait for the
next target, a Notify() at the value it read and then the advance to its target.

Upstream's GPU BVH mirror (eb3e86d5, RayTracing::Prepare) records
through the recorder as well: its header upload and its acceleration
structure builds go in Custom() commands, the builds as plain records.

Also: erase the write-back that landed, not the oldest one.

The texture cache keeps a record of every storage-image write-back still
in flight, and the priority operation that lands one removes its record.
Upstream f47da249 removes the oldest record, since priority operations
run in queue order. A priority operation queued while the scheduler is
not open runs at once on the calling thread, ahead of the queued ones,
so the oldest record can belong to another write-back still in flight:
its pages would stop waiting for it.

Remove the record of the write-back that landed. The search uses
find_if with an equality predicate: WriteBack compares with a defaulted
operator==, so clang-cl reports it as trivially equality comparable and
the STL of Visual Studio 18 (MSVC 14.51) hands std::ranges::find to its
vectorized find, whose static_assert accepts only 1, 2, 4 and 8 byte
elements.
GTA V (PPSA04263) crashed about once every 100 sessions in "[RAGE] HDD
Streamer" with an unhandled access violation inside zlib inflate_fast
(read of the output window) or inflate (first store into next_out), on
64 KiB direct-memory pages at 0x10xxxxxxxx. The page was mapped again a
moment later: the crash report could read it, with the decompressed data
in place.

Two game threads commit the same page: AsyncCommitThread maps it with
MAP_FIXED, and one or two milliseconds later the main thread maps the same
physical page at the same address again with MAP_FIXED. On the console
that is an atomic no-op, and the streamer already decompresses into the
page. The emulator replaces a mapping by unmapping it and mapping it again
(ReplaceFixedRangeWithReserved), so for that moment the page is gone and
the streamer's access faults.

Windows has the same kind of gap on its own: a file view can only be
split by unmapping all of it, so unmapping part of a view briefly takes
the parts that stay mapped away too. Those parts also came back with the
view's protection, dropping guest mprotect and the page manager's write
and read tracking on them.

- Both replacements publish the affected range in a small lock-free table
  while the mapping is absent. The runtime linker's fault handler waits
  until the range is mapped again and retries the access (unless the GPU
  tracking resolves the fault); a page that keeps faulting after its
  range was mapped again is still reported.
- After a Windows view split upstream gives the survivors back their
  own page protections (59723ae1); faults there are retried until then.
- Tests: survivors keep their protections on Windows, and a thread keeps
  using memory while other parts of its view are unmapped and while its
  mapping is replaced with MAP_FIXED (hundreds of retried faults per run,
  an unhandled access violation without this change).

Each retry also prints a "[HACK] guest access retried while its mapping was being replaced"
notice (src/common/hackNotice.h): the first application of each distinct case, then a summary every 10 s, instead of only the first eight console lines.
GTA V (PPSA04263) keeps the deformation of each vehicle in a 128x128
R8G8B8A8_SNORM linear render target taken from a pool of reused memory.
The GPU clears it and renders the impacts into it, and the CPU reads the
same memory to place the wheels and to deform the physics bounds. The
emulator only wrote GPU-written linear images back to guest memory with
--readback-linear-images, so the CPU read whatever the pool memory held
before (leftover half-float data of another resource) as damage: after a
light crash the wheels ended up displaced and tilted outside the body,
the car could no longer drive, and it could later snap back to its
original shape.

Read back GPU-written linear images on submit unless
--no-readback-linear-images is given. Driving around Los Santos this
downloads about 110 images (30 MiB) per second and costs about 0.35 ms of
GPU-thread time per 10 s. The launcher passes
--no-readback-linear-images when its checkbox is off, and new
configurations default to on.

The storage readback cases of upstream's GpuCommandLane test assume
linear readback off, so they turn it off before they start.
GTA V (PPSA04263) issues about 16 occlusion queries per frame as
EVENT_WRITE ZPASS_DONE begin/end pairs and polls the counters on the CPU
until bit 63 is set; it never predicates on them. The emulator answered
every dump with a synthetic count of one sample per DB, so the game drew
the sun's lens flare as if hidden behind trees and light glows and
flares as if visible through walls.

Count real samples with Vulkan occlusion queries. Every dump ends a
segment of the draw stream; the value it publishes is the running total
of all earlier segments, so a query (begin at A, end at A + 8) reads the
samples between its dumps whatever the pairing, also nested queries.
Samples are only counted while a guest query is open (begins without an
end are dropped after 8 frames). Host queries are only active inside
render pass instances: they begin when rendering begins or at a dump
inside it and end when it ends, so no render pass is split. Slots come
from a 16384-entry pool reset from the host (hostQueryReset); a segment
that found no free slot reads visible.

The execution thread publishes a dump once the GPU is known to have
finished its command buffer: at later dumps without querying the GPU,
and once per flip after refreshing the timeline. DB 0 gets the total and
the other 15 DBs zero, all with bit 63, written DB 0 last. The labels and
flips that pace the guest are written before the GPU runs the work, so
before a frame's flip the execution thread waits for the GPU to finish
the dumps of earlier frames: the counters of a frame reach guest memory
by the next flip. Otherwise, when the GPU was a frame behind, a counter
came out a flip late and the game drew Michael's pool (mission
Father/Son) for single frames without reflections and waves (pixel
shader 0x8ff8e7390aa255cd instead of 0x78c46fbde1c31d8d). The GPU has
usually finished: about 5 waits in 6000 frames. Draws do not poll the
timeline; a ZPASS predication with
wait_op 0 that finds a result missing asks the execution thread once to
finish the GPU work and publish. Dumps into memory the guest unmaps are
dropped. occlusionQueryPrecise is enabled when available.

The two silent cases print "[HACK] occlusion segment without a free host query slot reads
visible" and "[HACK] occlusion query begin without end dropped after 8 frames" notices (src/common/hackNotice.h): the first application of each distinct case, then a summary every 10 s.

Upstream (246d5115) counts samples with a host query per draw behind an
opt-in --occlusion-queries and publishes the counters by waiting for the GPU
at the next flush, label or flip. This replaces that implementation (it would
wait for the GPU on the execution thread and miss the pipelined flips) and
keeps its option and launcher checkbox, now on by default:
--no-occlusion-queries reads the counters always visible, and the launcher
passes it when the checkbox is off. Pm4Flip no longer expects the counters
published at the flip itself, and upstream's OcclusionQueriesTests, which
covered its counter helper, are gone with it.

GTA San Andreas - The Definitive Edition (PPSA03525) hid CJ, cars,
pedestrians and the radar map for one to three frames at a time while
the camera moved; with --no-occlusion-queries they stayed. Each of its
occlusion queries is a 0x240-byte object: the ZPASS_DONE begin and end
dumps go to A and A + 8, and a RELEASE_MEM right after the end dump
writes 1 to A + 0x100, a label the game reads as "query done". The
execution thread wrote the label as soon as it ran the RELEASE_MEM,
before the GPU had started the work, so the game read counters that were
still zero and treated the object as occluded. On the console the
end-of-pipe label lands after the counters dumped before it.

A RELEASE_MEM label written while occlusion dumps are unpublished now
goes through the same priority completions, behind the counters; its
interrupt follows it. Later labels keep their order: while a deferred
label is not written yet, they are deferred too, and one that cannot be
(GPU-written memory, GDS) waits for the completions queued before it.
EOP interrupts always run in the priority completions, in order. Waiting
for the GPU at those labels instead also removed the flicker but cut San
Andreas from 25 to 15 fps; the deferred label keeps 25 fps. In 2070
frames of walking, running and turning the camera in a street, no object
and no radar map went missing with this change (196 and 83 frames
without it).

Also: write occlusion counters when the GPU finishes their dump.

Red Dead Redemption (PPSA30528) decides on the CPU whether to draw the
sky reflection of its water from a ZPASS_DONE occlusion counter of the
previous frame (two queries per frame, double buffered; no predication).
In the opening cutscene (the Morningstar steaming in) about one frame in
four showed the river dark, without the reflection, in bursts of one to
three frames.

The game paces itself with suspend points: the one of frame F+1 returns
once the host GPU finished frame F (a priority completion releases it).
The counters of F, however, only reached guest memory from the execution
thread, at a later dump that already knew the GPU tick was done or at the
next frame's flip. At about half of the suspend point releases two to four
dumps the GPU had finished were not in guest memory yet, so the game read
counters without their ready bit and dropped the reflection for the frame.
On the console a dump's counters are in memory once the GPU got past it,
before anything later in the stream.

Each dump now queues a priority completion that publishes the finished
dumps. Priority completions run in order after the GPU, so the counters
land before the suspend point release or any later completion; the range
is tracked, so an unmap of the counters waits for it. The execution
thread still publishes what it finds finished and keeps the flip wait
GTA V needs. A mutex guards the pending dumps, the running total and the
slots they release, now that publication runs on two threads.

RDR opening cutscene, boat shot, every presented frame dumped, 3
alternating pairs with the same binary: frames without the reflection
83/276, 100/278, 81/280 before; 0/292, 1/281 (the fade-in), 0/275 after.
Suspend point releases that found finished dumps unpublished: about 2100
of 4300 per run before, none after.

Also: write occlusion counters into the copies that later GPU work reads.

In ASTRO BOT (PPSA21564), Creamy Canyon's surfaces and colours flickered
from frame to frame. For each object the game clears 256 bytes with
WRITE_DATA, dumps ZPASS_DONE before and after its bounding box, and a
compute shader (cs 14150b8d91170bd2) later in the same stream reads the
whole array of query objects (up to 0xba900 bytes) through a V#. On the
console the dump's counters are in memory before later work runs. Here
they reached guest memory only when the GPU finished the command buffer,
so the shader's copy of the range held the zeroes of WRITE_DATA and the
game took visible objects for occluded ones, differently every frame.

When an operation binds a buffer over dumps the GPU may not have
finished, the command buffer now copies the host query results
(vkCmdCopyQueryPoolResults with WAIT), and a small compute pass sums
them into the running total after each dump and writes the counters,
in the layout a dump writes, into the copy the operation reads, right
before it. The completion still publishes the same values to guest
memory for CPU readers and labels. Query slots whose results a command
buffer copies are reset only after the GPU finishes it, so a reader
never waits for the GPU. A CP DMA copy from pending counters waits for
them.

Creamy Canyon stays still between frames (per-pixel temporal deviation
over 16 shots: 35 before, 2 after) and runs at 22-24 fps instead of
20-22.

Also: publish finished occlusion counter dumps in batches.

ASTRO BOT (PPSA21564) dumps the occlusion counters ~13,000 times a frame
in Go-Go Archipelago, two per object. Each dump was published on its
own: a vkGetQueryPoolResults and a vkResetQueryPool for its one or two
host query slots, and 16 WriteFromCompletion() calls, one per DB, each a
TryWriteBacking() that takes the address space lock twice. That is
~420,000 shared locks a frame. The completion thread spent ~9 ms a frame
publishing with the occlusion mutex held, which every dump on the
execution thread takes (2.2 ms a frame of waiting there), and the
execution thread published another 1.9 ms a frame itself.

The dumps the GPU finished are published together: the segments of
consecutive dumps are consecutive host query slots, so their results are
read with one vkGetQueryPoolResults (two when they wrap) and their slots
reset with one vkResetQueryPool. The 16 counters of a dump are written
with one lookup of the backing store (TryWriteBackingQwords(), DB 0
last as before); writes the caches watch are still reported per counter.

On the beach (alternating 8-second windows in one instrumented run):
publishing takes 3.4 ms a frame on the completion thread instead of 9.1,
the execution thread waits 0.8 ms instead of 2.2 for the mutex, its
draws take 2.2 ms less (less contention on the locks), and the frame
rate goes from 17.3 to 18.5.
GTA V's exhaled cigar smoke in the Father/Son cutscene (and small
particles over the sky) rendered as opaque black blobs with ragged
edges. The particle pixel shader also writes its view depth to an
R16_FLOAT MRT blended with MIN; GTA V clears that target to 65504
(CB_COLOR_CLEAR_WORD0 = 0x7bff7bff) with a DCC fast clear whose keys
are 0x10. Only the GFX10 0x20 key was treated as a clear-to-register,
so the clear was dropped and the target kept the zeros in guest memory.
MIN(0, depth) stays 0, and the depth-of-field pass then treats the smoke
as touching the camera and blends in its dark near-field blur.

Treat 0x10 DCC keys as clear-to-register (the 16-bit clear words decode
since 57c97ebd), both when the metadata is read on the CPU and when the
GPU selects the clear with conditional rendering: that check keyed its
predicate slots by key >> 5 and rejected keys with any of the low five
bits set, so 0x10 never matched. It now has 16 slots keyed by key >> 4.
Particle-depth metadata the GPU wrote takes that path, and the smoke
was black again.
GTA V (PPSA04263) tessellates the trunks of trees near the camera. With
patches skipped by default, a tree's trunk disappeared when walking up to
it and came back at a distance, where the game draws an untessellated
model. Its tessellation programs now translate, so draw patches unless
--no-tessellation is passed. The launcher passes --no-tessellation when its checkbox is
off and enables it in new configurations.
GTA V (PPSA04263) lost most of its frame time to reads of guest memory the
GPU had just written: each one waited for a readback of all GPU work queued
so far. Near the mountain in Performance mode the grass and foliage culling
cost ~34 such drains a frame (11-12 ms of a 31 ms frame), and the ray
tracing of Fidelity mode ~340 a frame. After a recompiler change the first
session also stalled 50-280 ms on every new Vulkan pipeline.

- Indirect draws that upstream's path leaves to the GPU (vkCmdDraw(Indexed)Indirect on the
  guest records) no longer read DRAW_INDIRECT_MULTI's draw count on the CPU first: the host GPU
  reads it too (vkCmdDraw(Indexed)IndirectCount, when drawIndirectCount is supported), and
  NUM_INSTANCES reads the last draw's instance count only when a later draw inherits it. Draws
  upstream's path cannot take still read the count and records on the CPU. Like every draw
  whose records the GPU reads, these use the indirect_draw shader variant (a833e1b7).
- DISPATCH_INDIRECT with USE_THREAD_DIMENSIONS converts its GPU-written
  thread counts on the GPU: a small compute pass writes the workgroup counts
  for vkCmdDispatchIndirect and the thread limit into the shader data
  buffer (ShaderComputeInputInfo::dispatch_indirect_threads).
- SRT walks and the validation of resolutions read bytes of GPU-owned pages
  from the backing store when the GPU did not write them (byte-precise GPU
  write ranges, texture cache), instead of faulting into a readback: a load
  of upstream's x86 walker that faults on such a page completes with the
  bytes of the backing store.
- WRITE_DATA packets on GPU-owned pages store their dwords to the backing
  store and, in command order, to the cached buffer through a stream copy,
  instead of reading the page back first. This also covers pages that a
  GPU-written image still holds (GTA V writes a label once per frame into
  memory a 4K render target uses; the readback cost ~20 ms per frame in
  Fidelity); the image becomes CPU-dirty as on the faulting path.
- Reads of GPU-written buffer bytes whose last writer was already submitted
  copy them on a transfer-only queue that waits for that submission only
  (each cached range remembers the tick of its last writer). The copy is
  submitted only once the recording thread submitted that tick: with
  deferred recording, a copy waiting for a tick not yet in vkQueueSubmit
  could block inside the driver while holding a lock the recording thread
  (or a present) needs, and the emulator deadlocked.
- The pages and device-address writes that readbacks had to wait for are
  remembered, and an operation that writes them is submitted right away, so
  the readback that follows waits for that submission only (the BVH builds
  of the ray tracing read headers the previous dispatch wrote: ~15 drains a
  frame, ~2.5 ms each, down to ~0.1).
- The buffer cache keeps a host-visible mirror of the 64-byte lines that
  the execution thread reads again and again (the BVH headers that the ray
  tracing shaders cs ddff3c6d72c4e994, b2966d3472aac545, 9df701ab41f8ed18
  and 0e7bdeda7768b057 read from buffers their predecessors write): the
  lines a command buffer wrote are copied there at its end, and a read whose
  copy is newer than the last write waits for that submission and takes the
  bytes from the mirror (~140 readbacks a frame down to ~2). Dispatches whose
  buffers are reached through memory offsets no longer count as
  device-address writers when every written buffer is bound with its V#'s
  exact range.
- Bindless tables (the ray tracing material table, 16384 slots, ~8 a frame)
  bind each distinct element once, and an element stays valid while its
  data and metadata ranges stay readable instead of being resolved again on
  every map or unmap anywhere.
- The resolve thread also resolves indirect and tessellated draws and the
  programs of DISPATCH_DIRECT and DISPATCH_INDIRECT (~800 a frame in the ray
  tracing; the program does not depend on the GPU-written arguments, and
  ahead resolutions get the workgroup counts so tables indexed by the
  workgroup id resolve ahead too); the tessellation analysis is remembered
  per program pair. Strict reads larger than the 64-byte check buffer (the
  2 MiB key arrays of the bindless tables of cs c6c91cf1882cdc3b,
  ca313cf56ef25496, fa8b1616fddc203b and 651da332bc4a3f98) are validated
  from a scratch buffer instead of always failing.
- Scalar reads are checked against the written images once per draw.

Performance mode, mountain scene standing still: 33.7 -> 60 fps (capped);
recorded skyfall route minimum 18 -> 40-52 fps. Fidelity mode: 5.0 ->
8.4-9.4 fps. With a cold driver cache, ~20 s of pipeline stalls -> none
(310 pipelines created in 5.7 s before the menu, with the pipeline store this commit had;
upstream's shader store replaces it). Fidelity mode, debug
build, each later part turned off in turn: the mirror is worth ~11 % of the
frame rate, the transfer queue 6-8 ms per frame of the execution thread,
resolving indirect dispatches ahead ~6 ms and the large strict reads ~3 ms.

Demon's Souls (PPSA01341): some sessions submitted a command buffer
after almost every dispatch (~2,000 a frame, ~9-10 us of the execution
thread each, mostly waking the recording thread, which then spent a
queue submit on each): its SRT walks read GPU-written dwords through the
readback mirror, and while mirror reads keep succeeding every operation
that may write through device addresses asks for a submission. The same
session ran at 8.2 or 9.2 fps depending on whether that state set in. A
requested submission now happens at most once per millisecond; the
request waits for a later operation, and is dropped when another
submission sent the work meanwhile, so a readback waits at most for the
work recorded in that time. Against 200 us, 1 ms gave 12.4 against 11.9
fps in Demon's Souls, and 11.4-11.5 against 10.0-11.5 fps in GTA V
Fidelity mode; not submitting for readbacks at all costs GTA V Fidelity
~5%.

Upstream's BVH mirror (RayTracing::Prepare) synchronizes device-address
memory as an operation that does not store through it.
The first time GTA V (PPSA04263) draws something new, the NVIDIA driver
compiles its Vulkan graphics pipeline for 100-550 ms on the execution
thread: a skyfall over Los Santos created 32 new pipelines (4.2 s in
total) and dropped to 18 fps, while the same route with every pipeline
cached kept 29 fps. Compute pipelines of new programs were also created
on the execution thread, at their first dispatch.

A draw whose pipeline does not exist yet now queues it to one of three
background threads and is skipped until the pipeline is there, so an
object may appear a few frames late the first time it is seen instead of
the game stalling. Only draws that change nothing but the picture are
skipped: draws whose shaders write memory, draws counted by a guest
occlusion query and draws to linear images (the CPU reads those back,
e.g. vehicle damage) still wait for their pipeline. Dispatches always
run, but the compile workers that translate a compute program ahead of
its dispatch now also create its pipeline.

The option is on by default; --no-async-pipelines (or the launcher's
"Compile new pipelines in the background") waits for every pipeline as
before.

Also: compile the pipelines of UI, layer and small draws without skipping them.

A draw whose new pipeline the driver is still compiling is skipped until a background thread
created it. That is invisible for a 3D scene drawn every frame, but a draw the game makes
once into a cached layer is lost for good. On a cold pipeline cache Marvel's Wolverine
(PPSA03671) drew its screen-reader notice without its black background (the 3D world showed
through), its main menu with only some letters, its title logo missing and its frosted panels
as dark boxes; with a warm cache all of them were right. As main-next does:
- pipelines of at most 12000 SPIR-V words (all stages) compile at once: a few milliseconds;
- draws without depth test or write whose vertex shaders total at most 8000 words compile at
  once, whatever the pixel shader's size: UI and 2D layer draws (stencil does not count, UI
  libraries clip with it);
- draws whose color targets are all at most 1024 pixels wide and high are never skipped:
  glyph atlases and cached layers;
- a draw that queues a pipeline waits for it up to 20 ms before it is skipped: a pipeline
  the driver has cached finishes within it.
3D draws of large pipelines still compile in the background (--no-async-pipelines turns that
off as before).

Split out of main-next's 2957b8303.

Co-authored-by: Senaxx <[email protected]>
GTA V (PPSA04263) slowed down the longer a session ran: a place drawn at
60 fps right after loading ran at 40-45 fps from the same camera after
15-25 minutes. The cost per draw did not change; what grew was the
device-address synchronization on the GPU thread (2.7 -> 5 ms per frame)
and the game's write faults on protected pages (~1900 -> ~2500 per frame,
10 -> 15 ms of CPU per frame on the game's threads, each fault a
VirtualProtect behind the address-space lock the GPU thread also takes).

- Buffers were only released under memory pressure (above ~17 GB on a
  24 GB card, so never), and the cache grew to 10000-14000 buffers. Many of
  them cover memory the game has since reused for other data, and each
  synchronization pass before a draw with device-address accesses uploads
  every CPU-dirty page of every cached buffer and protects it again. The
  buffers no lookup used for 2048 collection ticks (about half a minute)
  and that hold no GPU writes are now released a few at a time. FindBuffer
  counts as a use (device-address windows, readbacks, indirect tables),
  shaders mark the pages they reach through device addresses in a third
  bitmap of the fault buffer, and buffers created for a device-address
  fault stay pinned: the host cannot see those accesses coming, and a
  released one would read zeros once.
- The game streams its per-frame vertex and constant data upwards through
  a ~48 MB ring covered by one cached buffer, taking a fault per page. When
  the page below the faulting one is already writable, the pages up to the
  next 64 KB boundary are released with the same fault. Blocks with
  GPU-written pages keep to the faulting page, since those must be read
  back first; the released pages are uploaded again at their next
  synchronization even if the game did not write them.

Same scene, same build, minute 7 -> minute 25 of the session: before
5.4 -> 6.5 us of frame time per draw, after 5.5 -> 5.6. Performance mode in
the rain, 3 minutes in (debug build, 5 sessions each): write faults
3260 -> 2700 per frame and 5400 -> 5100 cached buffers.

Releasing buffers by age drops memory a shader may still reach through a device address. The
last released buffers are remembered, and a device-address fault inside one of them prints a
"[HACK] buffer released by age reached again by a device-address fault" notice (src/common/hackNotice.h): the first application of each distinct case, then a summary every 10 s.
The 64 KiB release of the pages ahead of a write fault only skips the faults of memory that is
uploaded again at its next synchronization, so it has no notice.
A user's Radeon RX 9060 XT exits with "depth attachment feedback loop is
not supported by the host" in GTA V (PPSA04263): a draw samples the depth
or stencil target it also writes, which Vulkan allows only through
VK_EXT_attachment_feedback_loop_layout and its dynamic-state extension,
and that driver does not provide both.

Without them, copy the sampled mips, layers and aspects of the depth image
into an image of its own outside the render pass and bind that copy to the
draw instead: the draw reads the depth from before it ran, as translators
without feedback loops do. The copy is kept until the depth image is
deleted and refreshed for every such draw. Hosts with feedback loops keep
sampling the attachment as before.

The first such draw logs once that the host does not support depth
attachment feedback loops and that draws sample a pre-draw copy. It is a
limitation of the host, not an emulation error, so it is not a [HACK]
notice.
GTA V (PPSA04263) in Fidelity mode runs ~1450 async compute dispatches a
frame, many of them with buffers reached through device addresses (the ray
tracing BVH builds). Before each of those dispatches the execution thread
uploaded every page the CPU had dirtied since the previous one; the game
threads keep writing (mostly for the next frame), so it ran 13-40 times a
frame at 0.5-0.9 ms each (VirtualProtect of the uploaded pages, walks), and
each cached buffer's upload recorded its own pair of full barriers around its
copy: ~750 uploads and ~1,500 barriers that each wait for all earlier GPU
work per frame.

- The CPU writes that the work of a submission may read through device
  addresses precede the submission, or a WAIT_REG_MEM the work waited for;
  on hardware later ones are only seen after such a wait. So the upload now
  runs at the first device-address operation of each guest submission,
  after each operation that follows a WAIT_REG_MEM, after any write of the
  execution thread itself to tracked guest memory (labels and CP writes made
  for the command stream), and whenever buffers or mappings change. Pages
  dirtied in between stay dirty for the next pass.
- The copies of one synchronization are gathered and recorded together
  between a single pair of global barriers.

Fidelity mode, standing still: 5-6 passes a frame instead of 11-40 (debug
build: `bda: sync` 13.1 -> 9.2 ms per frame of the execution thread).

Also: upload only the memory a shader's device-address reads can reach.

GTA V's vertex shader 0x68c1a23a80317efd (drawn 4-27 times a frame in the
city) reads its vertex fetch V#s with S_LOAD_DWORDX4 from a table at a
user-data address, at ((key << 4) & 0x1f0). Those scalar reads made it a
DMA program, and every operation with DMA uploaded the CPU writes of all
cached memory first: ~16 MB a frame (2-3 passes of ~1.1 ms on the
execution thread) and ~4000 pages protected again, which the game then
faulted on (~2700 write faults a frame on its threads).

Resource tracking now records what DMA can read when every DMA access is
a read at a user-data base pair plus an offset with known possible bits
(a window from that base), or an indirect buffer whose V# comes from such
a table entry (the host reads the entries and adds the buffers they
describe). Operations whose programs all have a known reach upload only
those spans; any other DMA (full addresses, address writes, BVH queries)
keeps the full synchronization.

Rain save in Los Santos, performance mode, ~5000 draws a frame: 41-42 ->
45-47 fps (debug build), guest write faults 2700 -> 80 a frame, uploads
16 MB -> 0.7 MB a frame.

The assumptions of the footprint announce themselves with "[HACK] DMA upload assumes V# indices
stay within 64 records" and "[HACK] DMA upload of a V# range clipped to 256 MiB" notices (src/common/hackNotice.h): the first application of each distinct case, then a summary every 10 s.

Also: scatter batched buffer uploads with one dispatch.

The buffer cache batches the uploads of a synchronization behind one
pair of barriers, but still recorded one copy command per destination
buffer. In GTA V's Fidelity mode a batch copies to about 200 buffers,
several batches a frame: some 780 copy commands, 2.2 ms of GPU per frame
(each one costs about as much as a small dispatch).

A batch that copies to several buffers now runs as one compute dispatch
that copies every range by device address, from a job list placed in the
staging buffer after the data. Batches with ranges that are not dword
multiples, or whose job list does not fit in the staging buffer without
a wait, keep the copy commands.
In GTA V's (PPSA04263) Fidelity mode the picture froze for 4-10 s two or
three times per session and three cores kept compiling pipelines during
play. Two sources of new compute permutations were behind it.

- The ray tracing shader (cs c6c91cf1882cdc3b) selects T#s by key through
  four indirect image roots. The number of keys and of distinct T#s follows
  guest data from frame to frame, and both were part of the shader
  permutation: the mapping's offset in the flattened SRT (which shifts with
  every earlier mapping), its binary-search step count and the number of
  child images. The program store held ~40 permutations of this shader, each
  new one a 3.5-5 s pipeline compile on the execution thread. Indirect
  descriptor mappings now reserve room for a power of two of keys (at least
  8) and search that many; the shader still searches the runtime count.
  Distinct T#s are padded with copies of the last one, which no key
  selects, so that with the root they are a power of two. The emulator
  enables these stable layouts when it creates its renderer (resource
  tests keep exact counts) and raises the floors for compute shaders to
  256 keys and 8 images, which keeps the shader on one layout.
- The resolve thread resolved compute dispatches whose SRTs read V#s from
  memory that earlier dispatches wrote on the GPU; the backing store still
  held stale bytes there, so it built specializations from garbage (V#s
  with random strides) and queued them for compilation. One session queued
  ~2500 permutations of cs d8f2a760e26e9f63 and hundreds of others; each
  was compiled, recorded in the program store, precompiled again in every
  later session and given a pipeline on the background threads, and
  dispatches that met a queued pipeline waited for it. The read log of a
  resolution now notes whether a read touched a tracking region that may
  hold GPU writes; such resolutions no longer queue compiles (the execution
  thread's own lookup compiles what it needs). Lookups of a permutation
  start with the one the thread found last, as a program can still carry
  thousands of permutations from older stores.

Fidelity mode: one new c6c9 permutation in the first session (5 s), none in
the following ones (before: 2-3 per session, 4-10 s of stalls); background
compute pipelines during a session 1208 -> 0, speculative compute compiles
~3900 -> 1.
Every compute dispatch recorded a barrier before it (when it writes) and one after it, each
waiting for all earlier work. On the guest's GPU, dispatches of a queue overlap unless the guest
orders them with a wait, a partial flush or an ACQUIRE_MEM. GTA V's ray tracing structure builds
in Fidelity mode run ~600 direct dispatches per frame back to back on one asynchronous compute
queue; serialized, they kept the GPU ~7 ms per frame longer on work the execution thread then
waits for (the CPU reads the structures' headers to bind the next dispatches).

Defer the barrier after a direct dispatch to the next operation. When that is a direct dispatch
of the same queue with no ACQUIRE_MEM or WAIT_REG_MEM in between, record neither barrier: the
one before the earlier dispatch already ordered everything recorded before it, and the
operations other than dispatches (partial flushes, labels, draws) record their own barriers.

Also: chain indirect dispatches the guest did not order, like direct ones.

Demon's Souls (PPSA01341) runs ~570 indirect dispatches a frame in Boletaria (the culling and light chains of its
async and graphics queues). Each one recorded a barrier from every graphics, compute and transfer stage to the
indirect-argument read before it and another after it, and BeginGuestOperation recorded the barrier a preceding
direct dispatch had deferred: every indirect dispatch was a point where the whole queue drained (~15 us each,
~8 ms of a 24 ms GPU frame; the indirect dispatches were 52% of the GPU time of the frame).

A direct dispatch the guest does not order after the previous dispatch of its queue (no ACQUIRE_MEM, wait or
partial flush since) already skips both barriers and defers its own: the two overlap on the guest's GPU. An indirect
dispatch is now the same: without a guest order since the previous dispatch of its queue, the barrier before that
dispatch already ordered everything before it, the arguments included, so it records neither barrier and defers
the one after it to the next operation that is not such a dispatch.

Demon's Souls, Boletaria (RTX 3090, 2560x1440 render, same exe with the change off/on, ABBA 2+2): standing
24.6 -> 28.2 fps (+15%), walking out 23.2 -> 26.2 (+13%), walking in 24.4 -> 27.3 (+12%), turning the camera
31.4 -> 33.8 (+8%); the GPU busy time a frame (NVML utilization over the window) 23.9 -> 19.2 ms. Same picture.

Other games, same exe with the change off/on (ABBA 2+2, native ray tracing, vblank 180): GTA V Performance
71.0 -> 69.9 fps (-1.5%), GTA V Fidelity 35.3 -> 35.0 (-0.9%), both inside the noise; ASTRO BOT gogo_walk 62.6 ->
62.3 in the passes that walk the same way (one B pass walked onto the open beach, 17-24 fps, healthy image).
Draws touch every image they bind, thousands of times a frame, and each
touch loaded the image's LRU entry (a cache miss) only to find it already
touched in this tick (~2 % of the execution thread in GTA V's city).

The image keeps the tick of its last touch, so repeated touches stop at
the image they already read.
FindBuffers() looked up (or created) the cached buffer of every storage
buffer a draw binds, ~29000 a frame in GTA V's city at night, although
most are small CPU-dirty constant ranges that ObtainBuffer() streams
without a cached buffer. Operations with device-address reads still find
theirs first, before the BDA synchronization; the others leave the
lookup to ObtainBuffer(), which makes it when it needs the buffer.
A player with an AMD GPU (Radeon RX 9070) reports that Fidelity and
Performance RT exit in DescriptorHeap::Commit because a descriptor set
does not fit even an empty pool. The heap asked a pool for 32 sets of a
layout at once and halved the request on failure. AMD's driver keeps the
room of the sets a failed allocation did create, so asking an empty
default pool (262144 sampled images) for 32 sets of GTA V's bindless ray
tracing table (cs c6c91cf1882cdc3b, 20494 to 41000 sampled images per
set) used up its room on the failed attempts and left it unable to hold
even one set. Growing the pool until 32 sets fit only hid this, at up to
2 million sampled images per pool, until creating the pools failed.

Layouts whose sets come from the heap record their descriptor counts per
type, and the heap tracks the descriptors and sets its current pool has
left: it asks only for the sets that fit (15 or 3 of the ray tracing
tables per default pool) and moves to another pool when none does. If
the driver still refuses an allocation, the pool takes no more sets. A
set with more descriptors of a type than a default pool holds gets a
pool with the default sizes raised to hold four such sets.
In GTA V's Sandy Shores at dusk (Performance mode, ~5850 draws per frame) the execution thread
of the emulated GPU limited the frame rate to ~48-52 fps. It streams ~19000 small constant
buffers per frame into the stream buffer and uploads the flattened SRT and shader data of every
draw there. The stream buffer is device-local host-visible memory, which the CPU writes
combined: copies under 256 bytes and every upload were written by the execution thread itself,
and the next fence or locked instruction on that thread (the queue handshakes fence on every
operation it takes) waited until those writes drained over the bus. Moving the same work to a
cached ring removed a stall per draw (+10 % frames per second in the scene).

The execution thread now hands every stream-buffer write to the host copy thread: guest data
of any size (it reads the backing store, as larger copies already did) and host data through
HostCopyQueue::CopyInline(), which first copies the bytes into a ring of cached memory the copy
thread copies from (the ring waits for the copy thread only if it fell a whole ring behind).
Other threads, and sources larger than a ring chunk, copy directly as before.
3ff6606f made pads that are not DualSenses rumble from the haptic audio
port by taking the block peak, doubling it and sending it straight to the
motors. GTA V feeds its vehicle engine through that port as a quiet but
continuous texture meant for the DualSense voice-coil actuators, so in
any vehicle an Xbox-style pad vibrated strongly and without pause. Before
that change those pads only rumbled through scePadSetVibration (crashes,
impacts), which is what the game intends for them.

Make the haptic-audio rumble opt-in: --pad-haptic-rumble <true|false>
(Config::PadHapticRumbleEnabled, default false). While it is off the
non-DualSense pads take the same path as before 3ff6606f and the
DualSense is unchanged. With it on, the rumble mapping is the one from
3ff6606f.
Demon's Souls (PPSA01342) closes after about 3.5 minutes of play with
"sampled image descriptor 18 uses unsupported format 67" (k16_16_16_16UScaled)
from MaterializeResources. gpu_format.cpp had no sampled-texture entry for
16_16_16_16 USCALED/SSCALED, so the stage was rejected as fatal.

Scaled texels are integers returned as floats (float(uint) / float(int)), a
format hosts rarely let you sample. Back the image with the UNorm/SNorm format
of the same width (RemapTextureFormat), so filtering still happens in float,
and have the SPIR-V image emitter multiply the result by 65535 (USCALED) or
32767 (SSCALED) through the existing conversion_format path. Texel fetches
round the product so they return the stored integer exactly; gathers scale
their raw texels the same way. Only the two new formats gain table entries,
so every other format keeps its numeric class, remap and byte size. The
existing 8 and 8_8 UScaled paths still remap to UNorm and scale by 255.

Tests: sample, gather and load of 16_16_16_16 U/SScaled against the host
(shader_recompiler_compute_tests), materialization of T# formats 67/68 plus
unchanged 16_16_16_16 UNorm/Float/UInt/SInt and 8-bit UScaled
(resource_materialization_tests, format table checks).
RecordBdaFault loaded the bitmap word, ORed the page's bit and stored it
back. When several lanes of a wave fault on pages of the same 32-page
word, each lane stores its own copy of the old word and the others' bits
are lost, so those pages are not reported to the host until a later
access faults again. It also cost two memory operations at
every inlined page lookup.

Use a single OpAtomicOr on the word instead, as RecordBdaPageBit already
does for its miss path.

Idea from https://github.com/fxpw/KytyPS5 commit ec83acf9
("BDA faults set their bitmap bit with one atomic OR"); reimplemented on
our emitter.
Wave64 lane-bit reads of ballots now project to the lane predicate, one
word per half: a wave64 mask selects its low or high ballot word by lane,
and each word projects only through ballot words holding the same lanes.
Masks of constant halves stay as they are. Before, only wave32 masks were
projected.

Split from "shader: run wave64 compute as two host subgroups on 32-wide
GPUs"; the split waves themselves left wrongly coloured squares in GTA V's
ray traced reflections and were dropped.
A guest vector write keeps an inactive lane's old value with
select(exec, new, old). A new pass replaces the select by its new value
when every consumer of the result is masked by the same condition again,
so the old value is never read.

With robustBufferAccess2, scalar constant buffer reads load directly
instead of branching on their bounds.

Guest float min/max keep upstream's class-based lowering, which preserves
the signed-zero selection of RDNA2 (defb2f11d), instead of NMin/NMax.
V_PK_ADD/MUL/FMA/FMAC/MIN/MAX_F16 evaluated each lane in F32 and repacked
it, about a dozen integer and conversion instructions per lane. They now
bitcast both lanes to an F16 vector and use one native two-lane operation,
which requires shaderFloat16. Output modifiers keep the per-lane F32 path,
and KYTY_NATIVE_F16=0 restores it everywhere.

Adds a --packed-f16-only test subset.

Also: run scalar F16 arithmetic natively.

F16 IR values are now native halves in SPIR-V. V_ADD/SUB/MUL/MIN/MAX/FMA/
FMAC_F16 read their lanes with a half extract, compute in F16 and merge the
result with one half insert, where each took about seven SASS instructions
through F32 (unpack both sources, op, pack, mask, insert). F32 results
written as F16 merge with the same insert, F16 lane reads converted to F32
use UnpackHalf2x16's selected half, and swapped packed lanes take a rotate.

Output modifiers keep the F32 path; KYTY_NATIVE_F16=0 restores it. Tests
no longer forbid the Float16 capability, and --packed-f16-only also runs
the F16 sin and cos cases.
Every guest buffer was a storage buffer, so each scalar constant read
computed an address, bounds-checked it and issued a global load (about five
SASS instructions). Buffers that are only read by ReadConstBuffer at
immediate offsets below 64 KiB, and never written, formatted, aliased or
reached through indirect tables, now also get a uniform buffer descriptor
(DescriptorBindingKind::UniformBuffers) that those reads use: the constant
cache, with the bounds check done by robustBufferAccess2.

Both views of such a buffer share the base alignment, so the shader-data
byte offset stays valid for both. Requires uniformBufferStandardLayout;
KYTY_UNIFORM_BUFFERS=0 keeps the storage buffer reads.
Only the TextureCache part of upstream pull request #1284: the texture cache counts the registered images of each page of its page table in atomics, and InvalidateMemory returns without the cache lock when the written pages have none (98% of the write faults in God of War Ragnarok). The shared ProtectTransient lock and the lock-free dirty queries are already in this tree.
ASTRO BOT's compute shaders (e.g. 503d7f066a496c3c, 56a15431999c5a2d, ff8ee744ffa4dcdc)
load a pointer from the SRT root and then read fields at +0x30, +0x34, +0x58 and
+0x5c through it, inside branches that depend on per-lane values. The SRT walk
cannot decide such a branch, follows both sides and reaches the null pointer of the
side the GPU never takes. Upstream's x86 walker reads zero there (d7856753, bdf48dcf),
but the resolution stage that runs ahead of the execution thread still asked the guest
backing for address 0x58 when it read shader state, failed, and dropped the whole
specialization, so the execution thread resolved the same draw again (about 12000 times
in 150 s of the desert).

Read below guest memory as zero in the ahead shader-state reads as well. Nothing is mapped
there, so the bytes cannot change and need no entry in the read log that the execution thread
validates. The loads of upstream's x86 walker below guest memory read zero ahead of execution
too (they neither fail the walk nor enter the log); the shader-state reads now do the same.
Strict reads keep failing: they decide specializations.

Reading zero on the side of a branch the shader does not take is what the speculative walk
means, so, like the walker's loads, these reads report no [HACK] notice.
A buffer binding whose V# has no records (or a null base) is bound to a
16-byte null buffer so shaders read zeros from it, but the buffer was
created without ever being written, so it held whatever memory the
allocator handed out. Upstream's ZeroStrideBufferBinding test (a
zero-stride fetch with NumRecords = 0, expected to read 0) read 0x1000
from it after the test cases that ran before. Clear the buffer when the
buffer cache is created.
KYTY_PGO_GENERATE builds an instrumented emulator (clang and clang-cl) and
KYTY_PGO_USE optimizes with the llvm-profdata output of its runs. An
instrumented build writes its counters every KYTY_PGO_DUMP_SECONDS (default
20) to KYTY_PGO_FILE, so run scripts that stop the emulator with
TerminateProcess still leave a profile. Only Kyty's own targets get the
flags: third-party code a training run does not exercise keeps its normal
optimization. Both are off by default.

Also: add KYTY_NATIVE_V3 and KYTY_THINLTO, tolerate a missing PGO profile.

KYTY_NATIVE_V3 compiles for x86-64-v3 (AVX2/BMI/FMA CPUs) and KYTY_THINLTO
links across translation units with ThinLTO (clang and clang-cl); both are
off by default, so no release or build script changes. KYTY_PGO_USE with a
file that does not exist (or whose functions changed since it was
recorded) builds without the profile instead of stopping the
configuration.

GTA V in Performance mode (a Performance-mode scene, 60 s, same executable pair alternated, three pairs, mean
fps): default /O2 38.3; x86-64-v3 39.9 (+2.8 %); x86-64-v3 + ThinLTO 40.6 (+6 %);
x86-64-v3 + ThinLTO + the profile of KYTY_PGO_GENERATE runs of GTA V Performance and Fidelity
45.6 (+19 %; +11.8 % over ThinLTO alone, 40.8 in the same alternation).

Also: add a GTA V PGO profile.

pgo/gtav.profdata is the merged profile of three sessions played by hand
with an instrumented build (KYTY_PGO_GENERATE) of this code, from the
start of each game, 6-7 minutes each, with native ray tracing on: GTA V,
Demon's Souls and ASTRO BOT. Each game weighs the same in the merge. It
was recorded with LLVM 22.1.8; an older compiler cannot read it.
KYTY_PGO=ON optimizes with it (off by default; KYTY_PGO_USE, when set,
takes precedence). Functions that change after the profile was recorded
are optimized without it, so an older profile stays usable until it is
recorded again for a release.

Co-authored-by: TheCruZ <[email protected]>
The Windows job configures with KYTY_NATIVE_V3 and with KYTY_PGO_USE set to
pgo/gtav.profdata; ThinLTO already comes from
CMAKE_INTERPROCEDURAL_OPTIMIZATION. The profile was recorded with LLVM
22.1.8 and an older compiler rejects it ("unsupported instrumentation
profile format version"), so the job installs that LLVM before configuring.
A profile that is missing or that llvm-profdata cannot read builds without
PGO and a warning instead of failing the release. macOS and Linux keep
their default code generation.
The LS and HS programs are analysed for their record strides and
per-patch range, and the LS/HS/TES stages are lowered to Vulkan
tessellation (quad and triangle domains, fractional spacing, patch inputs
and outputs) so that Wolverine's terrain draws.

This lifts the EXIT_NOT_IMPLEMENTED checks that limited tessellation to
triangle domains with integer or fractional-odd partitioning and clockwise
output, and those on the LS/HS memory operands (32-bit, unformatted).
Power-of-two partitioning is equal spacing over the factors the hull shader
writes rounded up to a power of two; a line output is accepted for the
isoline domain, which draws lines, and still ends the emulator for a
triangle or quad domain.

A program shape the analysis still does not model ends the emulator with a message that
names the shaders (the analysis returns false instead of exiting by itself).
InlineShaderFunctions() expands S_SWAPPC_B64 calls into the caller: calls through an
immutable pointer, and calls through bounded scalar-buffer tables, whose runtime selection is
kept as a branch over the captured targets (a target outside the captured set traps). The
callees are read from guest memory and must be leaf functions that return through the pair
the call wrote. ShaderFunctionExpander keeps the decoded shader while its code is unchanged,
and an expansion while the call targets and the callee code read the same, for a caller that
expands the same shaders on every dispatch.

Split out of main-next's 58921bcb6.

Also: give far branches of call expansions out of band instead of islands.

Marvel's Wolverine's ray-tracing compute 0xe6d76d24f59f8015 calls one of 20 hit-group
functions from a table; the expansion inlines them one after another, so the returns to
the caller lie beyond the 16-bit offset of S_BRANCH. RelocateBranches placed branch
islands in the middle of other callees' code (56 of them). The goto structurizer works on
the code layout and saw gotos into the middle of other bodies: it routed every callee
through the same blocks with route variables, the register Phi webs spanned all bodies
and the program grew to 6532 structured blocks (2424 native).

A branch beyond the reach of its encoding now keeps offset 0 and its target travels next
to the code as a long branch (Decoder::LongBranch): the expander reports them,
DecodeProgram takes them, and the linked program keeps them. The code no longer moves
once relocated, so the inlined call bodies' ranges are exact as well. e6d7: 2813
structured blocks, 21 K Phis after resource tracking (from 800 K with the previous
record-table keys), translation 7 s instead of 25 s.

Co-authored-by: TheCruZ <[email protected]>
Marvel's Wolverine ended the emulator about two minutes after boot with
"condition (definition && *definition != index)" in FindScalarDefinition:
CS 0xe6d76d24f59f8015 calls, from a waterfall loop, the function each lane
selects from a table, so the register that holds the call target is written
by different paths (and crosses earlier calls that may write it). Shaders
whose call target is GPU data (a ReadConstBuffer producer) had their
dispatches skipped, and the game's new-game opening waited for work that
never ran.

FindScalarDefinition now returns AmbiguousScalarDefinition for such a
register, and PrepareCallTargets marks the source expand_calls for it, as for
a target that is GPU data: RefreshShaderSource expands the calls with
ShaderFunctionExpander from the guest's call tables (the reads are captured
with the others), which keeps the runtime selection as a branch over the
captured targets. The linked program is the expansion, which the pipeline
cache compiles and distinguishes by its code like the linked leaf functions.
A table that does not expand (not mapped, a target that is not a leaf
function, a size past the expander's bounds) ends the emulator with the
reason. The shader_cfg expectations for the joined and repeated-call cases
follow.
The hit shaders that Marvel's Wolverine's CS 0xe6d76d24f59f8015 calls through
its hit-group table read vertex attributes with buffer_load_format_xyz through
a V# loaded from the hit-group record, a value only the GPU knows. Buffers
selected at runtime supported formatted loads of the X component only, and
the shader ended the emulator with "buffer descriptor is not a valid runtime
value" (pc 0x286c of the expanded program). Each component of a
multi-component load now goes through the same runtime format decode as X,
with its own DST_SEL from the V#. X loads emit the same SPIR-V as before.
An exception that no one catches on a worker thread (the program cache's, for one) ended the
process with 0xC0000409 and no message. A terminate handler now prints the exception's what()
and aborts. Builds without exceptions (Linux, macOS) only print that terminate was called.

Co-authored-by: rezesferi <[email protected]>
The error lists the descriptor and the declared resource but not the program that declared it, which
is what a draw that exits with it needs to be reproduced (Wolverine, 4 minutes into the game: a 3D
storage image written through a 2D T#).
The iterative dominator solver visited the blocks in index order, so a shader with thousands
of blocks (inlined function calls) took one pass per block to converge: tens of seconds per
shader. It now visits them in depth-first reverse postorder from the entry (predecessors
before successors, back edges aside), then the blocks the walk does not reach. The fixed
point does not depend on the order. Dominator sets stay sorted, so inserting a block and
Dominates() are a binary search instead of a sort and a linear scan.

Split out of main-next's 58921bcb6.

Co-authored-by: TheCruZ <[email protected]>
Small render targets (at most 1024x1024) are the layers a game draws once and samples from
then on: glyph atlases and cached UI. The texture cache evicted them under memory pressure
like any other image, and a lost one is lost text: Marvel's Wolverine's letters went missing.
They are no longer evicted; the guest freeing their memory is what drops them.

Split out of main-next's 2957b8303.

Co-authored-by: TheCruZ <[email protected]>
Marvel's Wolverine (PPSA03671) ended about 50 s after boot, as its title scene
started, with "sampling a writable depth/stencil attachment aspect": a draw
samples, through a bindless T# table, the depth target it writes.
AcquireRenderTargets() chose the attachment feedback loop layout (or a pre-draw
copy) from the draw's direct image bindings only, so the depth stayed in a
layout the table element could not sample.

The table elements a draw binds (or, for reused tables, visits) now count as
samplers of the depth target as well, and the depth elements of a table are
visited by every binding (as elements with volatile DCC already are), so their
descriptors follow the layout of the image whether a draw writes it or not.
Hosts without VK_EXT_attachment_feedback_loop_layout cannot redirect a shared
table element to a per-draw copy and still end there.

Also: check the depth elements of compute programs' tables instead of visiting them every binding.

In GTA V's Fidelity mode the operation that traces rays b93ab2ec binds
tables with ~800 depth copies. The depth elements of a table state are
visited by every binding, so that the descriptors of draws follow a depth
target's attachment layout: ~790 visits a frame (binding, view lookup,
transit) for b93ab2ec alone, which draws nothing. The check that would
have spared them failed for every depth copy anyway: it expected an image
without guest memory in the general layout, while a depth copy is sampled
in the read layout of depth.

The depth elements of the states of compute programs are now checked as
the others (a depth copy holds while DepthCopyCurrent()), and a depth
copy is ready in the read layout of depth. Visits 1 049 -> 317 a frame;
the preparation, rebinding and descriptor commits of the dispatches 82.2
-> 73.0 ms/s, dispatches 225 -> 212 ms/s (Fidelity in the city).
Marvel's Wolverine's CS 0xe6d76d24f59f8015 is 77,290 dwords once its calls are inlined, and its
resource tracking spent minutes in two searches (offline, with the descriptor plans the shader
needs, 4 min 37 s; the game stands at 0 fps meanwhile). MemoryIndexBelongsTo(), asked for every
scalar descriptor read, scanned the whole program each time; it now indexes the memory
operations of each metadata index once per pass (the planning passes add none).
NativeDescriptorSource() searched the Phis it had visited in a vector, and the register Phis of
40 inlined callees are thousands of nodes; it uses a set. The same tracking takes 20 s, with the
same results.
--readback-linear-images (on by default) enrolls every linear image the GPU
writes and, after each submission, copies it to guest memory: the guest
bytes are read into a staging buffer, the GPU copies the image over them
and the result is written back when the GPU is done. Red Dead Redemption
(PPSA30528) post-processes in compute through about ten 4K linear storage
images per frame (2 to 66 MB each) that no CPU code reads, yet each frame
moved 316 MB through that path: ProcessDownloadImages took 43 ms of the
62 ms the execution thread needed per frame (1.1 ms in the guest-memory
read and 1.8 ms in recording and publishing per image) and capped the
game at 16 fps, menu included.

Linear images of 256 KiB or more are now read back lazily. While the GPU
writes such an image its pages are read-protected through the PageManager's
access watchers, which count their owners since upstream 9678c59b (the
region trackers hold one on GPU-dirty pages as well).
The first CPU access of those pages, read or write, writes the image to
guest memory, waits for it and releases the watch; from then on the image
is read back after every submission like the smaller ones, so a game that
does read a GPU result (the vehicle damage of GTA V) pays one wait the
first time and nothing else. Games that never touch the image pay no
readback at all.

RDR in the cabin of the save, Performance defaults: 16 fps -> 56 fps; the
readback of 316 MB per frame is gone and the execution thread drops from
62 to about 19 ms per frame.
Red Dead Redemption (PPSA30528) scales its resolution every frame: the
render targets keep their addresses and change their extent (2449x1378,
2433x1369, 2336x1314, 2209x1243...), so every frame the texture cache
frees about ten GPU-written targets and creates their replacements. A new
image starts CPU dirty, so each replacement was initialized from guest
memory: a full-size copy of the stale bytes the guest memory still holds
into a staging buffer (ObtainBufferForImage) plus a detile pass. Per
frame that was 4 to 8 uploads, 70 MB, 4.5 ms of the 21 ms the execution
thread needs in the open world of the save, for pixels the first write of
the target replaces anyway; the GPU's own pixels were dropped with the
old image and never reach guest memory.

FreeImage() now notes the range of a GPU-written render or depth target
it frees, unless the image is read back to guest memory. A target created
within four frames over memory covered by such a range, with no write of
its own yet and no GPU-written source buffer, is not uploaded.
Everything else (textures, targets the CPU may have written) takes the
old path.

RDR walking around the ranch, defaults of the launcher: 43 fps -> 52 fps;
ObtainBufferForImage 4.5 -> 1.7 ms per frame (the rest are textures
created from CPU data), uploads of 70 MB to 37 MB per frame.
Freeing the memory of a large render target takes 0.2 to 0.4 ms in the
driver (vkDestroyImage plus the free of its allocation). Red Dead
Redemption (PPSA30528) scales its resolution every frame, so its
render targets keep changing extent, never match a recycled image and
about six per frame overflow the recycle list: 5.6 destroys of 300 us,
1.7 ms of the 19 ms the execution thread needs per frame, on the thread
that records the draws.

Images the recycle list does not keep now go to a worker thread that
destroys them in batches; creating an image that fails to allocate, and
the destruction of the allocator, wait for it first so no memory is
held back.

RDR walking around the ranch, defaults of the launcher, vblank 180, three
pairs alternated: 50.6 -> 51.9 fps.
Red Dead Redemption (PPSA30528) converts sceKernelReadTsc() ticks to
time with the console's rate (1/1594.02 per microsecond) instead of
sceKernelGetTscFrequency(), so on a 3.7 GHz host its frame time came out
2.3 times too long and the whole game ran up to 2.3 times too fast.
Demon's Souls (PPSA01341) reads the counter with its own RDTSC and
converts it with the reported frequency, which ran its character and
animations too fast in the same way.

Upstream's --guest-tsc presents the 1.6 GHz console counter and rewrites
guest RDTSC/RDTSCP to the same product, which covers both games, but it
is off by default. Turn it on by default; --no-guest-tsc (and the
launcher's checkbox) run the guest counter at the host rate.
GTA San Andreas - The Definitive Edition crashed at random on the main
thread in TSet<int32>::UnhashElements (0x900f9c2f0), called from
FAsyncPackage::Event_ProcessImportsAndExports when it resets
ExportsInThisBlock: a read at 0x20 = Data + 2 * 12 + 8 with Data == 0.
The function is a frame-pointer leaf ("push rbp; mov rbp, rsp; push
r15..rbx") that keeps the element pointer at [rbp-0x40], 0x18 bytes below
RSP, and reloads it on every iteration. The registers show the previous
iteration had read the same pointer successfully, so the slot was
overwritten between two loads: a host exception taken on the store to the
hash table makes Windows write its exception frame under the guest RSP.

The red-zone patcher only recognised [rsp - n] operands, so functions that
reach the red zone through RBP were never protected. Track RBP - RSP
through each function (mov rbp, rsp, pushes and pops, mov/lea rsp from rbp
and leave) and treat [rbp + d] operands that land below RSP like the
RSP-relative ones in the liveness analysis.
Demon's Souls ran at 0.6-1 fps in game with the execution and resolution
threads at 100%: each of its ~6,300 draws a frame spent ~160 us looking
its programs up, ~60 us of it in each walk of the shader resource table
(two or three walks per draw). Its descriptor tables share 4 KiB pages with
data the GPU writes, so those pages are read-protected, and every walker
load there (~30-37 per walk) faulted: the exception handler then read the
dword around the GPU writes from the backing store, ~2 us per exception.

A walker load now asks the emulator first: when the address lies in a
tracking region that may hold GPU writes, the execution thread reads it
around the GPU writes as the fault handler did, without the fault. Other
loads, bytes the GPU wrote and walks on other threads still load
directly and fault as before.

- Resolution ahead of execution: the resolution thread failed almost
  every draw ahead of execution (8,000 of 9,000 a frame) because an SRT
  walk gave up at the first load of a page shared with GPU-written data,
  and the execution thread then walked every draw again itself under the
  program lock the two threads contend for. A walk ahead of execution
  now takes the backing store's bytes for those loads. Every load is
  logged with the value it read, and before using the walk the execution
  thread checks the logged bytes against the GPU's
  (GuestReadLog::StillValid() reads around the GPU writes and loads the
  bytes the GPU wrote directly), so a stale value only costs the walk
  again on the execution thread. The execution thread takes the
  resolution for ~75% of the draws; in game 0.7 -> 7.4 fps, menu 32 -> 85
  fps (2560x1440, vblank 180), together with the fault-free walker loads.
- One lookup per walk: still ~45 ms a frame of the execution thread went
  to reading descriptor dwords around the GPU's writes (~31 loads per SRT
  walk and ~21 per StillValid() check, ~120,000 a frame), each asking
  again whether the GPU owns the page, whether a GPU-written image covers
  it (under the texture cache lock) and where its backing store is.
  FindAroundBackingPage() answers the per-page part once: the walker
  keeps the answers of the pages it read during a walk and the check
  keeps those of the last four pages; each load then only looks up
  whether the GPU wrote its bytes (TryReadAroundGpuWritesOnPage()). A
  walk on the execution thread drops from 5.8 to 3.9 us and a check from
  3.6 to 2.1 us (profiling build).

Also: answer GPU-write lookups from the last clean gap.

Reading descriptor memory around the GPU's writes asks for every few
bytes whether the GPU wrote them (BufferCache::HasGpuDirtyBytes(), a
search in the range set of GPU-written bytes). Demon's Souls does that
~120,000 times a frame in its SRT walks and in the checks of resolutions
made ahead of execution, mostly within the same gaps between GPU-written
ranges.

The range set now carries a version that advances with every change,
and a lookup that finds no GPU-written byte remembers the gap it falls
in; later lookups inside that gap are answered without searching until
the set changes. An SRT walk on the execution thread drops from 2.9 to
2.5 us (profiling build, A/B in the same build: 10.6 -> 10.9-11.1 fps).

The same lookups are further answered from a mask per page (~100,000
queries a frame in Demon's Souls, on pages that mix the game's
descriptors with GPU-written data; the clean-gap cache answers a quarter
of them): each page gets a mask of its GPU-written bytes on its first
query, dropped when the ranges change over the page, and a query within
a page tests the mask. RangeSet::Add() and Subtract() report whether the
set changed, so an Add() of a range already held (most written bindings)
drops no mask and no longer advances the version. Debug build, Demon's
Souls in game: StillValid 2.07 -> 1.91 us and RefreshFlatLoads 1.11 ->
0.95 us a call, about 2.6 ms a frame.

Also: make the reads around the GPU's writes cheaper.

Demon's Souls validates about 9,000 resolved draws and dispatches a
frame on the execution thread, its slowest stage: 11 logged reads and
10 flattened SRT loads each, two thirds of the loads on pages the GPU
also writes, and about 3,000 of them read through the mirror of the
GPU's writes. Three costs of that path went down:

- Every change of the GPU-modified ranges dropped the cached byte masks
  of its pages, and the next query rebuilt them, 6,200 times a frame
  (mirror reads publish the bytes they read, and every written binding
  adds its range). The ranges gain or lose exactly the changed bytes,
  so the cached masks now take the change.
- RefreshFlatLoads() decided again which pages the GPU owns right after
  StillValid() decided it for mostly the same pages; it now reuses those
  answers (eight pages instead of four). A page read back in between
  no longer faults and is read from the backing store, which holds the
  downloaded bytes.
- A mirror read looked up each of its lines in the line map twice.

Per frame on the execution thread (debug build, Demon's Souls in game):
StillValid() + RefreshFlatLoads() 25.6 -> 22.4 ms, mask rebuilds
6,224 -> 3,005, page lookups of the flat loads 15,800 -> 9,400. Release
build, three alternating runs each: 19.45 -> 20.55 fps (median, +5.7 %).

Also: let the SRT walker's guest loads on a page it already answered for skip the call.

Problem (Demon's Souls, Boletaria; GTA V too): the SRT walker the shaders' resource
resolution runs (resolve thread ahead of execution, execution thread for what it
cannot resolve ahead) called ProbeGuestLoad for every guest dword it loads, ~43 per
stage and ~16,000 stages a frame in DS, although the loads of a walk fall on a few
pages the walk had already asked the emulator about: the call (six register saves,
thread-local page answers, pending-write check) was most of a walk's cost.

The walker now keeps four page slots in its scratch (page number -> backing bytes of
the page, or null for a direct load), cleared when a walk starts. A load on a cached
page is a compare and a load; the call fills the slot for pages answered Direct or
Backing, but not while writes of earlier operations are pending (every load must ask
for those) and not for PerLoad pages (GPU-owned ones, read around the GPU's writes).
The load is still the walker's own `mov eax, [r10]`, so a fault still completes as
a zero read.

Measured with uProf, one pass each, same exe, before/after (cycles samples per frame):
- DS Boletaria (base before cx-buf's CBuffer pages): resolve thread 138.6 -> 121.2
  (-12.5 %), execution thread 193.9 -> 191.1, 23.35 -> 23.92 fps.
- GTA V Performance (perf save): execution thread 102.0 -> 92.4 (-9.4 %), resolve
  thread 63.6 -> 60.2, 50.1 -> 55.0 fps.
- GTA V Fidelity (trevor save): execution thread 174.8 -> 158.2 (-9.5 %), resolve
  thread 107.3 -> 101.0, 26.8 -> 28.6 fps.
Demon's Souls reads (and overwrites) GPU results page by page: of its
~105 read faults a frame on GPU-written pages, 100 hit the page right
after the previous one, and ~134 write faults behaved alike. Each page
was a fault, an urgent command and a readback: ~110 us on the execution
thread and ~400 us for the guest thread, every page.

A readback for a guest fault now also takes the GPU-written pages that
follow it in the same buffer, up to 256 KiB, while their writes were
already submitted (or all of them when the faulting bytes force the GPU
to drain anyway), and no GPU-written image covers them. Internal reads
keep reading exactly what they ask for. Urgent commands drop from ~197
to ~69 a frame, and fewer readbacks wait for operations still being
recorded, so the submissions made to shorten those waits drop from
~2,000 to ~340 a frame. In game 7.8 -> 9.0 fps.

A page whose GPU-written bytes were all read through the mirror stayed
GPU-dirty with nothing left to download, and a later guest write there
stopped the emulator ("CPU dirty state conflicts with GPU dirty state");
the readback releases such pages too.

Also: read ahead the GPU-written pages of a guest readback across pages without GPU writes.

GTA V in Fidelity mode (Trevor on a buggy in Sandy Shores, native ray tracing) reads back a
buffer of a few hundred pages a frame from its job threads, page by page in order. On many pages
the faulting bytes are fields the CPU wrote between GPU-written ones, so the read-ahead, which
looked at the faulting bytes only, read just the faulting page, and it stopped at the first
following page without GPU writes. That made ~60 readbacks a frame, each waiting for the whole
GPU backlog: ~35 ms a frame summed over the job threads, which then start the next frame late
and miss the 30 Hz flip.

Decide by the GPU writes of the faulting pages and skip the following pages without GPU writes
(they need no download), still stopping at pages an image owns, at writes not submitted yet and
after 256 KB.

Trevor standing still: 20.8 -> 22.8 fps; readbacks 1250 -> 205 a second.
Demon's Souls keeps about twelve job worker threads spinning at ~95% of
a core each while they wait for work. With 24 logical processors they
also ran on the SMT siblings of the processors the GPU stage threads are
pinned to (command processor, resolution, execution, recording, host
copies), and the execution thread, the one that bounds the frame rate,
ran correspondingly slower.

The first stage thread that configures itself now makes the physical
cores of the stage processors (with their SMT siblings) the ones the
other threads of the process do not get by default
(SetProcessDefaultCpuSets): threads that pick no processors themselves,
the guest's among them, run on the remaining cores, and the stage
threads keep their affinity. Processors that would keep fewer than six
other physical cores are left as they were, and so is the process with
KYTY_GPU_THREAD_CPUS=off, which unpins the stages.

In game 9.1 -> 11.2 fps with the same build (A/B by a switch), 12.2 fps
with all of tonight's changes; GTA V Performance mode 57 -> 59 fps.

Also: keep every other thread off the cores reserved for the GPU stages.

Since the GPU stage threads got whole physical cores, the other threads
of the process only had a default CPU set without those cores. Windows
still gave many of them an ideal processor on a reserved core, and a
thread made ready while every processor it may use was busy waited in
that processor's queue, where the stage thread pinned there runs at
highest priority and the CPU set keeps the waiting thread from running.
Nothing took it from there until the balance set manager boosted it
after about four seconds.

ASTRO BOT froze for 2-6 seconds at a time in Sky Garden, more often the
longer it ran (six freezes a minute after ten minutes), even standing
still. Each time a game thread handling a page fault held the lock of a
page tracking region inside a VirtualProtect of a single page that took
2.6-5.5 s: the thread was ready (priority 11, base 8, last waiting on a
push lock) with its ideal processor on a reserved core, next to ~25
other ready game threads. The execution thread spun on that region's
lock in SynchronizeBuffersInRange the whole time, so nothing reached the
GPU. The same wait made the 250-400 ms hitches of the execution thread.

When cores are reserved, the threads already running and every thread
that starts later (a TLS callback, so also those of other libraries and
of the graphics driver) now get a hard affinity to the other processors,
with an ideal processor among them; threads that chose their own
processors keep them, and the stage threads pin themselves afterwards.
The default CPU sets stay for any thread that starts without the
callback.
Marvel's Wolverine's ray-tracing compute 0xe6d76d24f59f8015 reads the
textures of each hit group through two pointers the GPU chooses: a call
table row names a record, the record holds the V# of a T# table, and the
T# or S# is read from that table. The translation stopped at pc 0x2fa0
with "GetImageResource dword 0 is not a valid runtime value".

Record tables (TryMakeRecordTableDescriptor): the handle's key is the
first word of the table V# the descriptor is read through (the value the
GPU itself uses, no Phi mirror) and the element travels in its second
word; the materialization maps each record table's first V# word to the
block [count, ordinals] of its elements, reading only the rows that name
the inlined callee's address. The unwritten lanes of an SGPR spill VGPR
are UndefU32 (kept in the Phi, no substitution), and
NativeDescriptorSource follows S_MOV and V_READLANE/V_WRITELANE copies in
every descriptor source.

e6d7 now translates, tracks and validates. Its first dispatch still reads
a BDA page the buffer cache does not hold yet and hangs the GPU.

The record tables of cs e6d76d24f59f8015 and cs 1a04c58a9fbc2052 then
needed hardening in the materialization of this branch:
- Candidates and table V#s were found with a linear search over the ones
  already seen: 88 thousand candidates from about 33 thousand distinct
  record tables, a quadratic cost (billions of comparisons) paid on every
  dispatch, so the title scene ran at 1-2 fps. They are now found through
  hash tables keyed by their descriptor words; the specialization is the
  same.
- The element table of a record is read in one read and has its own
  limit of 2M elements: a record names a scene-wide sampler table of 720
  thousand elements, above the 65536-candidate limit, which closed
  Wolverine on New Game.
- Two records may name V#s at one base (a scene-wide table and a range of
  it, same first word): for the keys both cover they give the same
  elements, so the longer table serves both. Tables with different bases
  whose first words match still fail ("two record tables share the first
  word of their V#").
- A record table whose first or last word is not in guest memory gives
  the shader no elements and its key reads the null descriptor: one row
  of the 360 thousand names a record whose V# words are floats (a base
  outside guest memory and a size of a gigabyte) that the GPU never
  selects.

Also: keep record-table candidates in the resident image heap.

Marvel's Wolverine (PPSA03671) closed on its second start with "pipeline
needs 2917028 sampled images" for its ray tracing shader cs
1a04c58a9fbc2052. The shader reads material T#s from tables that
GPU-chosen records name, once per inlined hit group. Every image root
materialized its own copy of all the candidates of those tables, padded
to a power of two, as descriptors of the pipeline layout. Their count
and order were part of the shader specialization, so cs e6d76d24f59f8015
(88 thousand candidates) got a new 3-minute pipeline compile whenever
streaming changed them, and the host resolved every candidate again on
each dispatch.

Sampled roots of such tables now keep their candidates in the resident
image heap. ImageHeap::AcquireList() interns a root's candidates in the
view of the root's profile, which roots of one profile share with their
elements and kinds, and keeps them in device slot words the root owns:
a null slot, one slot per candidate and a trailing null slot. The blocks
the records name hold slot numbers instead of ordinals of materialized
descriptors; the shader reads the entry from the root's slots, whose
count and address precede the record mapping, and selects the heap
kind, as for heap tables. When the image behind an element changes or
its memory is unmapped, the root's slots take a new element, as table
slots do, so no dispatch reads a descriptor of a replaced image. The
descriptor layout no longer depends on the candidates, and the host
resolves only new elements. Hosts without the heap keep the
materialized candidates.

RenderExecutor::DispatchIndirectThreads() neither began a heap draw nor
rebound the heap before writing descriptors, unlike the direct and
indirect dispatch paths, so a heap program dispatched with GPU thread
counts read elements whose descriptors were never written and Wolverine
lost the device ("BufferCache: readback queue submission failed") six
minutes into its first start. It now calls ImageHeap::BeginDraw() before
resolving the program and ImageHeap::Rebind() before rebinding its
images, as the other paths do.

Also: keep flattened SRT offsets across small table size changes.

Marvel's Wolverine (PPSA03671) compiled its ray tracing shader cs
1a04c58a9fbc2052 again on every start, and the driver pipeline cache
never matched it: a 1.4 million word module whose pipeline takes the
driver about three minutes, seven variants per start. Every start gave
it a different module, because flattened SRT offsets reach the shader
as constants and two variable-size regions moved them: the blocks of
its record-table roots, one word per candidate (14537 candidates on one
start, 14539 on the next), and the mapping of its bindless image table,
one word per entry (14535 entries on one start, 14547 on the next).

With stable indirect layouts both regions now round up to 4096 words,
as the key mappings and the descriptor children already have a stable
size, so the programs and their pipelines stay the same until a table
crosses a 4096-word step.

Record-table blocks also go after every other flattened SRT region, and
the key mappings name them by data, so their size moves no constant: the
blocks of one record-table root grew by three 4096-word steps between
two starts, which moved every later flattened SRT offset the shader
takes as a constant. Sampler roots pad their candidate children to a
power of two with stable indirect layouts, as image roots already do,
because the number of sampler candidates per root changed the size of
its sampler arrays.
SWAPPC preserves SCC and the decision tree that selects a call-table target overwrites
it, so the expansion kept two decision trees, each with a copy of every target, one per
incoming SCC value. Wolverine's 0xe6d76d24f59f8015 thus inlined its 20 hit-group
functions twice: 77 K dwords, a 1.58 M-word SPIR-V program even without the islands.

A liveness walk now decides whether the SCC of the call can be read: a target that reads
SCC (S_CSELECT, S_CMOV, S_ADDC, S_SUBB, S_CBRANCH_SCC*, an SCC operand) before writing it,
or that returns with it untouched to caller code that reads it, needs the two trees;
otherwise one tree serves both values and the targets are inlined once. Instructions not
known to write SCC count as preserving it. e6d7: 44 K dwords, 1619 structured blocks,
11.7 K Phis, translation 3.4 s.
Wolverine's ray-tracing compute 0xe6d76d24f59f8015 calls one of 20 hit-group functions
from its traversal loop. The expansion inlines them into one program, and in a single
SPIR-V function (1.6 M words) the NVIDIA compiler ran past 36 GB and several minutes
without finishing.

The emitter now gives each inlined call target its own DontInline function, which the
compiler builds separately. The region of a target is every block its entry block
dominates, leaving through edges to one block; the function receives in a struct the
values defined before the region that it reads (also through operands without a SPIR-V
value, such as resource handles) and returns the values the exit block's Phis take on
its edges and the values later code reads. Main calls it where the entry block was and
branches to the exit block, whose Phis take one operand per region. Values computed at
function entry (GDS length, buffer-backed LDS base, buffer offsets and sizes) are
recomputed in each function, and per-invocation memory (scratch, function LDS) becomes
Private when a program has such functions. Programs without inlined calls emit as
before. e6d7: main 245 K words and 20 functions of 8-107 K words.

The memory helpers (get_bda_pointer, the runtime-V# buffer loads and the
conversion that switches over every buffer format, 7.4 K words) are
inlined at each use. In Wolverine's 0xe6d76d24f59f8015 the inlined
hit-group functions use them from hundreds of sites (the largest
function: 234 BDA pointers, 35 buffer loads), and the NVIDIA compiler
inlining every copy took minutes and gigabytes per function: one 31 K
word target with main 217 s and 6.7 GB, and the whole program did not
finish in 10 minutes and 25 GB. Programs with inlined call targets now
keep one DontInline copy of each helper (other programs keep inlining
them): the whole program compiles in 166 s and 5.5 GB.

Also: pass the values an outlined call target leaves unchanged to its function.

Marvel's Wolverine's 0x1a04c58a9fbc2052 (a ray tracing compute program with call table hit groups)
did not compile once the native ray tracing patch changed its control flow: "CompositeExtractU32x4
is read by an outlined call target without being passed to it". The exit block of an outlined
call target takes a value from one of the target's edges that the target does not define (the
value comes unchanged through the target: here a result of the native traversal's selection), and
only the values the target's instructions and conditions read were collected as the function's
inputs, so the Phi's incoming value was defined inside the function out of nowhere.

The values the exit block's Phis take from the target's edges and that are defined outside it are
inputs of the function too.

Also: dispatch the indirect calls of a program with outlined targets with one switch.

The expansion of a call table (ShaderFunctions.cpp) tests, for each target, the two
words of its address against the register that holds the callee and calls the target
on the first match, trying the next target only when no call was made. Emitted as the
structured control flow of the program that is a nest as deep as there are targets:
each level an `if (vote(hi == K.hi)) { if (vote(lo == K.lo)) { call } }` followed by
two merge blocks that give every register of the program (90 of them) a Phi, plus a
merge per level that falls into the previous one. Marvel's Wolverine ray tracing
compute 0x1a04c58a9fbc2052 has up to 100 targets, and the compile of its nest costs the
NVIDIA driver 25 % of what is left after the two commits before it (230 s and 5.4 GB
for a module of 8.1 MB with the nest, 174 s and 5.0 GB with the switch).

The tests are about the whole wave (votes) and the first level that matches wins, so the
program now computes what every level tests first (the loads of the table are reads),
selects the index of the first match and branches on it with one OpSwitch, into the
calls of the outlined targets, to one merge with one Phi per register. The Phis of the
merge blocks of the levels are what the program had before the call until a level
matches, and the Phis of the join take, for each level, the value after the call of that
level (the outputs of its region, or what the levels after it add on the way out).
Programs whose call table has a different shape are emitted as before.

Verified: the 3-target call table of the compute tests runs on the GPU in wave32 and
wave64 with the switch, and the module of 1a04 validates.
ASTRO BOT crashed while it loaded a save or the map of a galaxy: a null
dereference at pc 0x90706b5be (ProductNextLoad_ATQT, OdxAsyncLoader,
LevelTask_ATQT) or an endless key search at pc 0x900387770 in an
animation resource whose property table is garbage. In every case one
read() or pread() of a whole level or texture file (data/prein/levels/
.../*.lvx, data/prein/bg/gfx/*.jxm) had returned 0 bytes, and the game
parsed the stale contents of its buffer.

The reads went straight from ReadFile into guest memory. The buffer had
held a texture the GPU used (skybox_nx_pd_space_title.jxm), and the GPU
threads keep the pages of the buffers and images they synchronize
write-protected; InvalidateMemory() releases them before the read, but
the execution thread protects them again whenever it synchronizes a
buffer over that memory (PrepareBda for an indirect dispatch). A write
by the host kernel does not raise the fault the tracking handler
resolves, so ReadFile failed with ERROR_NOACCESS or
ERROR_INVALID_USER_BUFFER and transferred nothing.

read, pread and preadv now read into a per-thread host buffer and copy
it into guest memory. A copy that meets a protected page faults into
the tracking handler, which releases the page as for any guest write.
ASTRO BOT froze two times in three when diving into Sky Garden: the
graphics queue and two compute queues all waited (WAIT_REG_MEM) on
handoff labels that read 0. The game builds frames in three slots and
resets the labels of a slot to 0 when it starts a new frame in it,
once the graphics queue signalled the end of the frame that last used
the slot. A compute queue that waited on a label of that frame had not
seen the graphics queue write it: the command processor kept running
the graphics submission until its end, past the end-of-frame
interrupt, and only then retried the blocked compute queue, which by
then read the reset label and waited forever (and so did every queue
waiting on that compute queue).

A real GPU runs its queues side by side, so the waiting queue sees the
label as soon as it lands. The command processor now notes the memory
each blocked queue waits on (WAIT_REG_MEM, MEM_SEMAPHORE), and a packet
that writes it ends the writing queue's slice after that packet; every
queue then retries its wait before the writer goes on.
ASTRO BOT stayed in the warp tunnel into Sky Garden forever in about
half of the runs (nearly every run on a loaded machine): the game kept
rendering the tunnel but never started the level, and its texture
streamer read the same normal maps (*_n.gnfp) again about every half
second.

The streamer reads the mip statistics of GET_LOD_STATS: a 64-byte
header whose first dword marks the report complete, then one 64-bit
entry per counter with the finest mip sampled (bits 56..59, 0xF when
unsampled) and the samples the T# MIN_LOD clamp raised (bits 0..23),
which it takes as "load this texture at full size". The command
processor wrote a complete report with every counter zero, which says
that every texture was sampled at its finest mip and clamped; the
streamer then wanted more texture memory than it has, evicted and
reloaded textures in turn without end, and the level start waits for
streaming to settle.

Pixel shaders that sample an image through a T# the draw supplies now
record, per mip-statistics counter (T# MipStatsCntEn, MipStatsCntId),
the finest level sampled (the unclamped LOD plus the shader bias and the
view's BASE_LEVEL) and whether a sample was finer than the T# MIN_LOD:
one load of the image's field from the shader data, and, only when the
T# has a counter, one LOD query and one atomic pair per subgroup into a
counter buffer. GET_LOD_STATS copies and resets the counters in command
order, and the report reaches guest memory when the GPU completes it,
before the completions of later work; the game skips a report slot
whose header is still zero. A packet without a buffer or a reset (the
game probes with one before each report) changes nothing.

Draws in which no image has a counter use the same pixel program
compiled without the recording: its storage buffer atomics alone make
the driver run the depth and stencil tests after a shader that can
discard. GTA V sets no counter, so all its draws use these programs.

Ported from Jetsku's fork (21450ca39, the mip-statistics part of
9983732d2, 6364a83c5, dd2c02f18, a4bc914d0, bd77aef10, be9a7bdbb and
f3e37ba2f), without its switches and diagnostics.

This replaces upstream's --lod-stats (84b1dfbb), which counts the bound
T#s at their BASE_LEVEL when a draw resolves them and otherwise reports
every counter unsampled: the command processor runs ahead of the draws
here, and the shaders measure what they actually sample.

Also: record GET_LOD_STATS mip statistics per lane, without subgroup operations.

ASTRO BOT (PPSA21567 01.018) ended at boot on GeForce RTX 50 GPUs with
cold caches: a null read inside nvgpucomp64.dll, NVIDIA's shader
compiler, while the emulator created a pipeline (driver 32.0.16.2114,
the same one that creates every pipeline on Ampere). Two players saw it;
one says v14 booted and v17 did not.

The SPIR-V of the boot shaders of v14 and of v17 differs in one
construct only: the GET_LOD_STATS recording that v17 added to the pixel
shaders that sample a T# the draw supplies (32 of the 108 shaders both
builds compile at boot, ps 0xa0a705033ca1a7b8 of the player's log among
them). It reduced the mip level and the clamp flag over the subgroup
(OpGroupNonUniformUMin/UMax) and one elected lane issued the atomics.
All of that SPIR-V passes spirv-val; the crash is in the RTX 50
compiler, which is not the one of the earlier generations.

Every lane now records its own level and count with the same atomics,
on every GPU. The counters hold the same values: the finest level is a
minimum and the game only tests the count for zero. A player's RTX 5070
boots ASTRO BOT with it and plays without a crash, and on an RTX 3090
Sky Garden runs at 33.3 fps against 33.9 with the subgroup form (two
passes each, within the passes' own spread).

Co-authored-by: TheCruZ <[email protected]>
Demon's Souls froze for good on the "Continue offline" loading screen (no
frame for minutes). The execution thread was in WaitForCompile for a
compute program a worker was compiling; the worker, decoding the shader
code, faulted on a page the GPU owns (the code shares the page with data
the GPU wrote) and its read-back waited in SendUrgentCommandSync for the
execution thread, which only runs urgent commands between operations.

The execution thread now runs the urgent commands queued so far while it
waits for the worker.
In Demon's Souls ~1,900 draws a frame resolved ahead of execution failed the
check of the guest memory they read, and the execution thread resolved them
again (~7 us each). The bytes that changed were not GPU writes: the game
rewrites per-frame constants (a camera matrix at a fixed address, times)
after it submits the draws that read them, so the resolution ahead read the
previous values. In 83 % of the failed draws the only bytes that changed
were dwords the shader reads from the flattened SRT and nothing else the
resolution depends on.

The SRT walker now reports, for each load whose value only fills one
flattened SRT dword (no other value, condition, descriptor word or EXEC mask
of the walk uses it), that dword. The resolution ahead does not check those
loads: the execution thread reads them again, as its own walk would, and
writes their values into the stage's flattened SRT.

The same applies to descriptors the game rewrites after it submits the
draws that read them (~330 draws a frame still failed the check, ~17 us
each to resolve again, 5.4 ms a frame in a debug build): the base of
some V#s, and the mip statistics fields of many T# (bit 25 of dword 5
and the counter id in dword 6, toggled every frame for texture
streaming). The host derives nothing from those bits: the specialization
of a buffer does not depend on its base, image validity and lookups
ignore the statistics, LOD warning and perf_mod fields, and the buffers
are bound at the address the descriptor holds when the operation
executes. A resource plan now marks the descriptor sources that only
become direct buffer or image bindings (no indirect descriptor reads a
table, candidate, selector, row count or mask through them, no sampler
uses them, and V# bases only in programs without selector reads), with
the bits of each word that may be refreshed. The SRT walker names a load
whose value is one such word (and at most one flattened SRT dword
besides); the check compares those bits apart, and when only they
changed the execution thread writes the new bits into the stage's
descriptors and the whole word into the flattened SRT dword, as its own
walk would read them. Debug build, Demon's Souls in game: 11.9-12.0 ->
13.3 fps, draws resolved again 315 -> 1 a frame, the refresh costs 0.37
ms a frame.

Also: copy GPU-written flattened SRT dwords on the GPU instead of reading them back.

GTA V (PPSA04263) resolves its compute dispatches ahead of execution, and
the execution thread then reads again the dwords that the shaders load
through flat loads (the flattened SRT). In Fidelity mode some of them are
written by the GPU in the same frame (cs 7666e058e4e43618 reads one at
0x29ca8f100 that an earlier dispatch writes): reading them waited for the
GPU to run everything recorded before, through the mirror of GPU writes or
a fault and a readback, about 5 ms once per frame.

The resolution does not depend on those dwords: only the shader reads
them, when it runs, after the work that writes them. When their bytes are
GPU-written in a cached buffer, revalidating a dispatch now leaves them to
a copy on the GPU: the bindings copy them from the cached buffer into the
uploaded flattened SRT right before the dispatch, in stream order. Draws
keep reading them (a copy would end their rendering).

Execution thread in Fidelity (modeswitch save, debug build): GPU waits
131-144 -> 94-108 ms/s, fault handling 104-116 -> 55-65 ms/s.
Demon's Souls closed in about one run out of three on entering the game
with "MaterializeResources ... is true" (pipelineCache.cpp FindModule),
after "indirect image table at pc 0x000000fc has incompatible
candidates": a bindless image table read while the game rewrites it has
candidates of incompatible types. The resolution ahead of execution
already fails and the execution thread resolves the draw again; there a
failure exited the emulator.

Until the cause is fixed, the execution thread skips that draw or
dispatch, as it does with programs it cannot compile, and reports it with
a [HACK] notice. The draw is not rendered.
Marvel's Wolverine (PPSA03671) closed on its second start, once its save
data made it load the title scene. The scene's ray tracing shader (cs
1a04c58a9fbc2052) calls its hit groups through one call table; inlining
them gives 187968 words of code with more than 64 sampler roots, and
resource tracking failed with "sampler resource limit exceeded" and the
call expansion with "expanded shader exceeds the bounded code size"
(131072 words).

Each inlined target brings its own image and sampler roots, and every
target becomes a SPIR-V function of its own, so the cost grows linearly
with the code. Image and sampler roots are now limited to 256 instead of
64 and 32 (nothing else is sized by these limits, and the descriptor
arrays follow the actual counts), and expansions to 524288 words. The
expansion error now says how large the shader got.
Marvel's Wolverine (PPSA03671) crashed in ApplyResourceSpecialization()
when it specialized its ray tracing shader cs 1a04c58a9fbc2052: an
out-of-bounds read of the specialized buffers.

The pass that folds scalar reads of empty constant buffers to zero looked
up every ReadConstBuffer of kind ScalarBuffer by its buffer index. Reads
that only plan resources (the descriptor words of indirect tables and the
SRT reads, marked planning_only) never get a buffer index: theirs is the
one decoding left, which may exceed the buffer count. Those reads are now
skipped.
Marvel's Wolverine (PPSA03671) compiled its ray tracing shader cs
1a04c58a9fbc2052 again on every start (about three minutes in the
driver per variant): the module differed even when its specialization
matched. The call expansion compares the target of each GPU-chosen call
against the addresses of its candidate functions, and moves return and
GETPC addresses into registers, all as literals. The game loads most of
its hit-group functions at a different address on each start, so the
expanded code, and with it the program and its pipeline, changed.

Addresses in the expansion are now runtime words: the code holds the
index of a word, the shader reads the word from the flattened SRT after
the walked SRT words (ReadCallWord, one load per use), and the pipeline
cache passes each refresh's words to the materialization. Call targets
follow their code instead of their addresses, so the expanded program
is the same wherever the functions are loaded, and moving them no longer
retranslates the shader.

Also: let call table targets with the same code share one body.

Gran Turismo 7's any-hit call table (shader 0x63bebca1b79e1d5c, V#
09776020 001000ec 00002976 00005204) has 10614 rows of 16 bytes naming
1695 distinct functions, the most used one in 1825 rows. The expansion
gave each address a body of its own and stopped at 256 addresses
("shader call table exceeds the bounded target count").

With runtime words the targets are grouped by their exact code (a
function that reads its own address keeps a body of its own); each
address compares both words and branches to its group's body, and the
256 bound counts bodies, with up to 4096 addresses. Without runtime
words every address still has its own body. InlinedCallBody::aliases
carries the other addresses of a body into PointerTable::functions, so
the descriptor tables read through the records of any of them are
materialized. GT7 still has 352 distinct bodies among the 569 targets
the call keeps, more than the bound.
Wolverine's ray tracing compute shader 1a04c58a9fbc2052 samples 3D and
2D-array lookup textures that are still null in the first frames and
bound later. A null image was specialized as a plain 2D view, so the
same shader came out as one more 1.4 M-word program and the driver
spent another two to four minutes on its pipeline during boot.

A null descriptor reads zero through a view of any type, so the
specialization now keeps the dimension the shader samples with and
the program is the same before and after the texture is bound.
The same storage image of Wolverine's ray tracing shader
1a04c58a9fbc2052 is an RGBA8 target written as (R, G, B, A) in some
frames and an RG16F target written as (R, G, 0, 1) in others. The
descriptor swizzle went into the specialization as is, so the two
targets compiled two programs of 1.4 M words each.

A storage image in its own format applies the swizzle only to stores,
and a store keeps just the channels the format has. A swizzle that
stores each of those channels from its own component now becomes the
identity, so both targets share one program; other swizzles are kept.
Wolverine's ray tracing compute shader 1a04c58a9fbc2052 reads one
constant buffer with a single scalar load, and the game leaves its V#
all zero in some dispatches. The specialization still recorded the
buffer's stride, its zero-stride bounds mode and the empty-buffer
fold, so the bound (stride 16) and unbound buffer gave two programs
of 1.4 M words and the driver spent minutes on each pipeline at boot.

Only vector accesses use the stride and bounds mode. An empty buffer
binds the zeroed null buffer, so its scalar reads already give the
zero the empty-buffer fold puts in; the fold only matters where those
reads build descriptors. The plan now records per buffer whether it
has vector accesses and whether its scalar reads feed a descriptor,
and the specialization leaves out what the program does not use.
A guest CPU access to buffer memory the GPU wrote ran the whole readback
as an urgent command on the execution thread: record the download,
submit, wait until the GPU got there and publish the bytes. The writer
is usually in the command buffer being recorded (the execution thread
writes labels when it executes their packet, before the GPU does), so
every such read stalled the execution thread for a GPU round trip.
ASTRO BOT reads a few pages that its GPU work writes about 20 times a
frame.

Now the execution thread only records the download, submits it and goes
on; the reading thread waits for the GPU and the publication itself, as
on hardware only the reading thread waits for the memory. A second
urgent command then releases the pages unless the GPU wrote them again
meanwhile, in which case the access faults again and reads the newer
bytes. Downloads in flight are recorded, so another access to their
pages, also by the execution thread, waits for their publication
instead of reading the stale backing. That includes the execution
thread's own reads around the GPU's writes (indirect arguments,
descriptors, labels), which read the backing wherever no dirty range
covers the bytes: a download in flight counts as dirty bytes until it
is published. Without that, GTA V in Fidelity lost the device about 50
seconds after loading the story. A CPU write retries the
invalidation until its whole range is CPU-modified, and garbage
collection accepts dirty pages whose bytes a download in flight
carries. The pages of these readbacks count as hot as before, so an
operation that writes them is submitted as soon as it is recorded.

Sky Garden, alternating both ways every 20 s in one run: 24.8 -> 25.2
and 24.9 -> 25.6 fps in a release build (+8 % in a debug build, whose
execution thread is the slower stage). The approach follows
BryanKAdams' "publish guest-thread buffer readbacks without draining
the GPU thread" (44f841c13), done here with this tree's readback paths.

Also: download guest-thread readbacks on the readback queue.

After the read-ahead, GTA V's job threads in Fidelity mode (Trevor on a buggy in Sandy Shores,
native ray tracing) still read back ~16 times a frame. Each readback was recorded into the
command buffer being built and the faulting thread waited for that submission, that is, for all
the GPU work queued before it (~2 ms each, ~14 ms a frame summed), although in most cases the
writes it needed had completed long before.

When the last writes of the pages (and the device-address writes) were already submitted, copy
them on the readback queue, waiting on the timeline for those submissions only, as the
execution thread's own reads do (DownloadOnReadbackQueue()), and do not submit the command
buffer being recorded for it. The faulting thread waits for the copy and publishes the bytes.
Until then the pages count as a download in flight, and a priority operation over them keeps
later readers, unmaps and asynchronous publications behind the publication; a buffer waits for
its copies before it is destroyed. With the four slots busy, or while the writes are still being
recorded, the readback goes through the command buffer as before.

Trevor standing still: 22.8 -> 26.5 fps (readback waits 16 -> 3 ms a frame summed, submissions
54 -> 46 a frame); driving 17.9 -> 21.0 fps with the read-ahead change.
Every backing-store write or read first checks that the range overlaps
no private mapping: a std::map lookup over all guest mappings. Labels,
occlusion counters and WRITE_DATA over GPU-owned pages go through the
backing store a few bytes at a time, tens of thousands of times a frame
in ASTRO BOT. In Wormy Passage the check took 2.9 % of the execution
thread (about 1.4 ms a frame at 12,400 draws a frame) and 41 % of the
priority completions thread.

Each thread now remembers the last shared mapping that held a whole
range, keyed by a generation that advances whenever the mappings
change, and answers from it while it is current. Wormy Passage, uProf
over 20 s: the check leaves the execution thread's profile (3390
samples before) and drops from 11665 to 1156 samples on the completions
thread.
A mesh-shader draw dispatches its instances as workgroup rows. ASTRO BOT's
Serpent Starway boss (boss_snake) issues a draw of 77,054 instances about
25 s into the fight, and the host takes at most 65,535 rows (NVIDIA): the
emulator stopped with "mesh draw exceeds host workgroup limits: 1x77054".

The mesh draw parameters gain the host draw's first instance, which the
shader adds to the workgroup row for the instance ID, and draws with more
instances than maxMeshWorkGroupCount[1] (or the total workgroup limit)
are split into several host draws that update only that push constant.

Tests: TestMeshDrawSplit (gpu_pipeline_tests) checks that the host draws cover
every instance once within the limits, and the mesh prolog test
(shader_cfg_tests) that the instance ID is the first instance plus the row.
Demon's Souls binds about 5,300 written buffer ranges a frame, many of them
tens of megabytes (2,300 as texel buffers), and each binding synchronized
the whole range again: the upload scan visits every tracking region the
range covers, 1.3 us a texel binding, although the pages were already GPU
dirty and nothing had written them.

The last synchronization of a written range is remembered with the buffer
set epoch and two global epochs: the CPU-dirty one, which advances whenever
pages of any region become CPU dirty, and a new GPU-clean one, which
advances whenever pages of any region stop being GPU dirty. While the range
stays in the same buffer and neither epoch moved, its pages are GPU dirty
and hold no CPU writes, so only the write itself is recorded.

Debug build, Demon's Souls in game: 84 % of the written bindings skip the
scan; ObtainBuffer for written ranges 1.10 -> 0.55 us a call, about 2.9 ms
a frame.
Demon's Souls fills tables every frame with a compute shader that
writes destination[i] = source[i % size] for i below a count, count and
size read from a scalar buffer (about 190 dispatches a frame, ~4 MB).
The draws that follow read V#s and constants from those tables in their
SRT walks, so the execution thread read the GPU's results back: about
3,000 mirror reads and a few faults a frame, each waiting for the GPU.

As upstream's pattern fills, the shader is recognized by the hash of
its code (verified to implement exactly that) and the dispatch's
result is computed where it is known: when neither the source nor the
destination holds GPU writes and both are 32-bit buffers of the same
format, the destination is written in guest memory, invalidated like a
CPU fill, and the dispatch is not recorded. Otherwise the GPU runs it as
before (about half the dispatches, whose sources the GPU writes).

Debug build in game: StillValid() + RefreshFlatLoads() 23 -> 10 ms per
frame, 15.1 -> 19.5 fps, same draws and dispatches per frame and the
same image. Release build, three alternating runs each: 19.55 -> 21.48
fps (median, +9.9 %).
GTA V on Windows exited with STATUS_GUARD_PAGE_VIOLATION (0x80000001)
and no "Fatal Error" now and then, far more often while a program
captured the emulator's window (OBS, Windows Graphics Capture, fast
PrintWindow loops): three of three sessions with a capture. The faulting
code was the CPU walk of a shader resource table (WalkSrt), reading a
pointer the game had not filled for it, 0x9bbd98, which landed on the
guard page of another host thread's stack. The walkers' loads of
unmapped memory are access violations that the emulator turns into
zeros, but Windows raises a different exception for a guard page that
is not the faulting thread's own (its own is handled by the kernel), so
the vectored handler passed it on and the process ended.

The handler now treats such a guard page violation as the access
violation it is, so the same rules apply (a walker's load reads zero),
and when the access is handled without touching the page it puts the
guard back, which the system removes when it raises the exception, so
the other thread's stack still grows.
In GTA V Fidelity the ray traced shadow and reflection passes walk the
game's BVHs node by node through device addresses. Each access looked up
the page table and then loaded the page-use bitmap word with an atomic
load, waiting for it before deciding whether to set the page's bit. That
load sat on the critical path of every node fetch: in the downtown scene
of the mode switch save the passes ran at 6.2-6.7 fps.

Shaders with BVH intersections now set the bit with one atomic OR whose
result nothing reads and with no branch. The bitmap ends up the same;
the access no longer waits for it. GTA V Fidelity runs at 8.1-8.5 fps in
the same scene, the image does not change. Performance mode is
unchanged (54-56 fps). Other shaders keep the check: an unconditional OR
on every access cost the Demon's Souls menu a third of its frame rate
(the same bitmap words from many lanes); its shaders have no BVH
intersections and stay as they were (menu 59-60 fps, game unchanged).
GTA V's Fidelity mode runs a compute pass (cs b93ab2ec5c5caf00) over a list
another dispatch writes on the GPU just before it: its threads stop at the
list's count (lane < count). The SRT walk reads that count only to know
whether it is 0 (then no lane runs and the blocks after it are not reached).
The walk ahead of execution read the backing bytes before the writer ran,
logged them, and the execution thread then waited for the GPU to catch up
(~15 submissions, ~12 ms per frame) to compare them, found them changed and
resolved the dispatch again.

A load whose only use is such a zero test is not read in a walk ahead of
execution when a dispatch or draw resolved lately writes its bytes: the test
stays unknown and reaches both sides, as any non-zero bound does, and nothing
is logged for the execution thread to check.

With the GPU copy of the flattened SRT dwords, the execution thread's GPU
waits in Fidelity go from ~100 to ~63 ms/s (modeswitch save, debug build)
and Fidelity runs at 25.2-25.6 fps instead of 23.4-23.6 (+7.8 %, release
build with native ray tracing, vblank 180); Performance mode stays within noise (55.5-59.1 against
57.6-58.8 fps).

Also: do not read ahead GPU-produced values that only decide control flow.

ASTRO BOT (PPSA21564) culls with cs c5ee521b8849cf83 (Sky Garden: ~10 indirect dispatches a frame).
When a flag the CPU writes is 0, the shader reads two dwords that cs d0335580eea5b0b8 writes just
before it ([s[8:11] + 0x18] and [+0x1c]): one only decides a branch (s_cmp_lg_u32 against 0) and
the other is the bound of `tid < n` through a phi with 64. The walk ahead of execution read them
from the backing store and logged them, so the execution thread waited for the GPU to mirror those
bytes before it could use the resolution: ~60 ms a second of waits, 0.5 s in the 10 s windows of
the hitches while an area streams in.

A load whose value only decides control flow (branch conditions and zero-tested bounds, through
the nodes that compute them; never a descriptor word, an output, a flattened SRT dword or an EXEC
mask) is now treated like the bounds of zero tests already were: when the GPU produces its bytes
the walk ahead does not read it, the decisions it feeds stay unknown and both sides stay
reachable, so the resolution covers either outcome and has nothing of the GPU's to validate.

Walks ask for many such loads (~5 a draw), nearly all outside the lately written ranges: a
counting filter of the 64 KB blocks those ranges cover answers them without scanning the 256
ranges.

Also: check bounds tested for zero only for being zero, and learn the GPU's.

GTA V's Fidelity mode with native ray tracing runs a shadow pass (cs
b93ab2ec5c5caf00) whose threads stop at two work-list counts at fixed
addresses (0x2adea0000, 0x2adf9f200), written on the GPU by an earlier
dispatch of the frame. The walk ahead of execution skips such a zero-tested
count only while a dispatch it resolved lately writes it, which misses this
writer: it read the previous frame's counts, the execution thread found them
changed on almost every dispatch (816 failed checks in a 90 s drive) and
resolved again, and each check read the counts around the GPU's writes,
waiting 2-4 ms for the GPU (~40 ms/s while driving).

The walker now reports a load whose only use is a bound tested for zero
(ZeroTestSlot). The read log checks it only for still being zero or nonzero,
as that is all the resolution depends on, and when the check finds it on a
page the GPU owns it remembers the address: later walks ahead of execution
leave it unread, as they do for the bounds a recently resolved dispatch
writes, and nothing is logged for the execution thread to read.
GTA V's Fidelity mode samples as depth, through a bindless table (cs
b93ab2ec5c5caf00), shadow maps it writes as R32 float colors: the texture
cache keeps a depth copy of each color image and refreshes it whenever the
game writes the color image, a dozen times per frame. Color and depth images
could only be copied through a buffer (image to buffer, then buffer to
image), ~2.1 ms of GPU per frame at 4K.

With VK_KHR_maintenance8, vkCmdCopyImage copies between a depth aspect and a
color aspect of the same texel size (D16 with R16, D32 with R32): depth
copies and other depth/color copies of such formats take one direct copy.

Also: copy the depth aspect of depth/stencil images to and from color images directly.

GTA V (PPSA04263) Fidelity binds its two 4K D32S8 depth targets as R32_UINT storage images in CS
0x24cbc249a5cf541a and as depth targets again right after, in most frames, so the texture cache
converts them between depth and color two or three times per frame. The direct depth/color copy
of VK_KHR_maintenance8 skipped images with a stencil aspect, so these conversions went through a
buffer (image to buffer, then buffer to image): 1.4 ms of GPU for each conversion from R32 to
depth and 2.1 ms for each one from depth to R32 (GPU timestamps around every copy, driving).

VK_KHR_maintenance8 also copies the depth aspect of D16S8 and D32S8 images to and from R16 and R32
colors, and the buffer path copied the depth aspect alone as well, so depth/stencil images now
take the direct copy too; their stencil aspect keeps its contents, as before. The conversions
take 0.9 and 1.4 ms, and the GPU time of all image copies while driving goes from 163 to 130 ms
per second.

Also: convert D32 depth images to and from R32 colors with shaders
.


GTA V (PPSA04263) Fidelity binds its two 4K D32S8 depth targets as R32_UINT storage images in CS
0x24cbc249a5cf541a and as depth targets again right after, in most frames, so the texture cache
converts a depth image to R32 and an R32 image back to depth once per frame each. vkCmdCopyImage
of the depth aspect of these images (VK_KHR_maintenance8) took 1.4 ms of GPU from depth to R32
and 1.8 ms from R32 to depth (GPU timestamps around every copy, driving).

Single-sample D32 and D32S8 images of one level and one layer now convert to and from R32 images
of the same extent with two small shaders: a compute shader that reads the depth aspect and stores
its bits into the color image, and a full-screen draw whose fragment shader writes the color texels
as depth, without a stencil attachment, so the stencil aspect keeps its contents. Depth values are
floats in [0, 1], which the depth write keeps as they are. The conversions take 0.1 ms each: the
GPU is busy ~35 ms per second less while driving, at 29.2 frames per second instead of 27.0.
A listener receives the hash and code of every shader the guest maps through
sceAgcCreateShader, on the mapping thread and while the code is still valid.
Installing it replays the shaders mapped before, so it can start after the
guest. The pipeline manifest uses it to compile the modules it lists as soon
as their code is there.
Background threads that compile ahead of time must not take processors from the
emulated machine's threads; on Windows they run below normal priority.
On a cold start every new pipeline is created when a draw first needs it:
Demon's Souls stalls for seconds while the driver compiles them, and draws
whose pipeline is still compiling are skipped. The shader store keeps the
compiled SPIR-V between boots, but only for the same build, and its code is
derived from the game, so it cannot be shared.

A pipeline manifest lists how the session's modules and pipelines were asked
for, in the guest's terms only: the hash of each shader's code (and of a GS
back half), the user data count and push data cursor, the stage input state
without guest addresses, dispatch sizes or host limits, the resource
specialization, and the state of each graphics pipeline, which names its
stages by the hash of their module's record; compute pipelines follow from
their modules. It is text, one record per line with named fields that leave
out their defaults and enums by name, so git keeps readable diffs of it and a
field that an older file lacks reads its default. Lines are sorted, so the
same contents give the same bytes on any build or host; a format number
changes only when a field changes meaning.

At boot the cache reads <TITLE_ID>_<APP_VER>.kpm from assets/pipelines next to
the executable and from _PipelineCache (another version's files when there is
none: their records name code by hash). Threads below normal priority
translate each listed module as soon as the guest maps its shaders, then
create its pipelines, which draws and dispatches take from the ready maps the
asynchronous pipeline threads use; a key every creating thread claims first
is never created twice. Lookups that come first take the usual path.
--no-pipeline-manifest turns it off.

--record-pipeline-manifest (a launcher checkbox, off by default) adds what
the session compiles to the manifest in _PipelineCache (written every 10 s
and at exit), which can then be copied into assets/pipelines. While recording
the shader store is not read, as it keeps no stage input.

Cold starts (no _PipelineCache, driver shader cache missed): GTA V reaches
the game 7-10 s sooner (46.6-49.6 s instead of 55.6-56.4 s), with no pipeline
created on the execution thread while loading (234-235 before, 4.9 s) and its
longest loading frame 0.3-0.37 s instead of 6.7 s; its fps in game do not
change. Demon's Souls reaches the game after 129-138 s instead of 213-225 s,
with 9-13 compute pipelines created on the execution thread while loading
instead of 238-260 (92-102 s), and with the manifest of two sessions runs its
first 30 s in game at 21 fps with an 84 ms longest frame instead of 10 fps and
6.8 s.

Also: leave out manifest pipelines that no draw creates from their modules.

Elden Ring Nightreign crashed at boot with an access violation in
CreatePipelineInternal() on a pipeline manifest thread. The shared
manifest, and from it this computer's recording and main's
PPSA25381_01.000.000.kpm, have the record
`P v=cb4ca39f854d p=d13d0f660c25 ... va=0.0,0.1,0.2,0.3,0.4,0.5`, whose
vertex stage is a tessellation evaluation module: once the guest mapped
its shaders the pipeline read the vertex formats of six attributes from a
module that has none (a null vector). Recordings that mixed up the places
of their modules wrote such records for several titles; the reader only
refused pixel or compute modules in the wrong slot, and records with more
vertex attributes than their vertex module read past its formats.

A pipeline record is kept only if a draw could create it from the modules
it names, as GetGraphicsPipeline() does: a VS or mesh stage, or an LS, HS
and TES, with an optional PS; as many vertex attributes as the VS or LS
reads (none for a mesh stage), each from a binding the pipeline has; and
the LS's patch size, or patches of 3 points for a rectangle list. The
others are left out and the log names how many there were and why, with
an example. Every record of the manifests in assets that a session
recorded from its own draws passes these checks.
Recorded with --record-pipeline-manifest, here and by the players through
the pipeline sharing server (tools/pipeline-share-server, without the
tessellation layouts, which only a local recording may provide), each
file the union of its sessions (modules and pipelines):
- PPSA04263_01.011.001.kpm (GTA V): 1970 modules, 1598 pipelines.
- PPSA01341_01.007.000.kpm (Demon's Souls): 10859 modules, 9212 pipelines.
- PPSA21564_01.007.000.kpm (ASTRO BOT): 1613 modules, 3470 pipelines.
- PPSA30528_01.002.000.kpm (Red Dead Redemption): 551 modules, 529 pipelines.
- PPSA03525_01.006.000.kpm (GTA: San Andreas - The Definitive Edition):
  884 modules, 826 pipelines.
- PPSA03530_01.003.000.kpm (GTA: Vice City - The Definitive Edition):
  845 modules, 697 pipelines.
- PPSA03527_01.003.000.kpm (GTA III - The Definitive Edition): 770 modules,
  702 pipelines.
- PPSA01317_01.680.000.kpm (Gran Turismo 7): 1498 modules, 1023 pipelines.
- PPSA03355_01.003.000.kpm (Hades): 29 modules, 19 pipelines.
- PPSA12544_01.000.010.kpm (Hollow Knight: Silksong): 80 modules, 57
  pipelines.
- PPSA01473_01.005.003.kpm (Ratchet & Clank: Rift Apart): 55 modules, 12
  pipelines.
- PPSA03524_01.007.000.kpm (GTA: San Andreas - The Definitive Edition):
  8 modules, 0 pipelines.
- PPSA03671_01.001.005.kpm (Marvel's Wolverine): 464 modules, 137
  pipelines.
- PPSA04263_01.010.002.kpm (GTA V): 2114 modules, 1850 pipelines.
- PPSA04264_01.000.000.kpm (GTA V): 1513 modules, 1339 pipelines.
- PPSA04264_01.005.000.kpm (GTA V): 2005 modules, 1698 pipelines.
- PPSA04264_01.011.001.kpm (GTA V): 1126 modules, 974 pipelines.
- PPSA21564_01.018.000.kpm (ASTRO BOT): 1765 modules, 3471 pipelines.
- PPSA21567_01.018.000.kpm (ASTRO BOT): 882 modules, 1706 pipelines.
- PPSA21567_01.019.000.kpm (ASTRO BOT): 519 modules, 624 pipelines.
- PPSA26344_01.008.000.kpm (Ghost of Yotei): 1750 modules, 330
  pipelines.
- PPSA01325_01.905.000.kpm (Astro's Playroom): 431 modules, 403 pipelines.
- PPSA01342_01.005.000.kpm (Demon's Souls): 847 modules, 242 pipelines.
- PPSA04264_01.010.002.kpm (GTA V): 1376 modules, 1200 pipelines.
- PPSA07631_01.005.002.kpm (SAROS): 1205 modules, 350 pipelines.
- PPSA09695_01.000.003.kpm (Daxter): 24 modules, 30 pipelines.
- PPSA10067_01.004.001.kpm (Prince of Persia: The Lost Crown): 26
  modules, 16 pipelines.
- PPSA10112_01.000.001.kpm (SILENT HILL: The Short Message): 1091
  modules, 819 pipelines.
- PPSA17191_01.004.000.kpm (Hi-Fi RUSH): 826 modules, 860 pipelines.
- PPSA17597_01.012.000.kpm (Sonic X Shadow Generations): 49 modules, 37
  pipelines.
- PPSA25381_01.000.000.kpm (Elden Ring Nightreign): 959 modules, 714
  pipelines.
- PPSA26344_02.002.000.kpm (Ghost of Yotei): 548 modules, 110 pipelines.
- PPSA28180_01.036.178.kpm (Days Gone): 3278 modules, 5089 pipelines.
- PPSA01951_01.000.003.kpm (Control Ultimate Edition): 322 modules, 166
  pipelines.
- PPSA02633_01.000.034.kpm (Street Fighter 6): 766 modules, 438
  pipelines.
- PPSA03743_01.002.000.kpm (Soul Hackers 2): 222 modules, 166 pipelines.
- PPSA21564_01.019.000.kpm (ASTRO BOT): 2290 modules, 5624 pipelines.
- PPSA01317_01.710.000.kpm (Gran Turismo 7): 3603 modules, 2228
  pipelines.
- PPSA25972_01.000.029.kpm: 78 modules, 45 pipelines.
- PPSA01288_01.014.000.kpm: 1827 modules, 1156 pipelines.
- PPSA01417_01.015.001.kpm: 38 modules, 17 pipelines.
- PPSA01556_01.002.000.kpm (Resident Evil Village): 580 modules, 310
  pipelines.
- PPSA02100_01.005.000.kpm: 9 modules, 0 pipelines.
- PPSA02929_01.000.000.kpm: 10 modules, 6 pipelines.
- PPSA11386_01.018.000.kpm: 432 modules, 180 pipelines.
- PPSA17221_01.008.000.kpm: 74 modules, 52 pipelines.
- PPSA17221_01.044.000.kpm: 5 modules, 3 pipelines.
- PPSA25427_02.000.001.kpm: 2102 modules, 1118 pipelines.
- PPSA25839_01.000.000.kpm: 6 modules, 2 pipelines.
- PPSA26344_01.512.000.kpm (Ghost of Yotei): 2077 modules, 352
  pipelines.
- PPSA28824_01.000.015.kpm: 8 modules, 1 pipelines.
- PPSA33626_01.000.000.kpm: 367 modules, 260 pipelines.
- PPSA34063_01.003.001.kpm: 1530 modules, 905 pipelines.

They are text, up to 3519 KB each, and .gitattributes keeps their line ends
the same on every platform.
GTA V (PPSA04263) in Fidelity mode writes small records with WRITE_DATA
into pages that dispatches also write (0x29caace8c, 0x70 bytes, read by
cs f85e944c4ed88b61). Such a write goes to the backing store and, in
stream order, to the cached buffer, but its bytes stayed in the GPU-written
ranges: the resolution of the next dispatch that reads them faulted and
waited for the GPU to run everything recorded before, to read back the
very bytes the command processor had just written (about 5 ms per frame).

From that point of the stream the bytes are the ones written, which the
backing store holds: they leave the GPU-written ranges, so reads around
the GPU's writes take them from the backing store. A later GPU write marks
them again. While a download over them is in flight they stay GPU-written:
publishing it writes the buffer's earlier bytes to the backing store.

Execution thread GPU waits in Fidelity (modeswitch save, debug build):
~63-77 -> ~38 ms/s.
In ASTRO BOT (PPSA21564) about 530 draws a frame write memory from their vertex shaders (Sky
Garden: pixel shaders e13d633c21320f31 and 4f45b2c2a944a546, ~245 and ~220 draws a frame). Each
one ended the rendering instance and recorded a full barrier before it (earlier accesses before
its writes) and another after it (its writes before later work), so every such draw ran alone in
a rendering instance of its own between two GPU-wide waits: ~1,100 barriers and as many rendering
restarts a frame on the execution thread and on the GPU.

On the guest's GPU nothing orders the draws of one queue but the guest's own sync: a wait or an
ACQUIRE_MEM. In Sky Garden 98 % of these draws come right after another one of them, with no such
sync and no other operation in between. The barrier after a writing draw is now left pending in
the command buffer; draws of the same queue the guest did not order after it go on in the same
rendering instance, and a writing draw that follows a pending barrier needs no barrier before it.
The next operation that is not such a draw records the barrier first, as does anything that ends
rendering (copies, readbacks, image transitions, dispatches, the end of the command buffer).

Sky Garden, standing in the garden, A/B within one run (windows of 20 s, debug build): +5.4 % and
+4.5 % fps. Skipping both barriers altogether measured +3 to +11 %.
ASTRO BOT (PPSA21564) registers an event queue for the end-of-pipe interrupts of its command
buffers (AgcDriverAddEqEvent, event 0) and requests ~45,000 of them a second in Sky Garden, but
reads far fewer: its threads wait on the queue for at most eight events with a 1 us timeout only
until a counter in memory reaches the value they expect, and never look at the events they get.
Every interrupt that came while the last one was still unread was queued as a separate pending
event (a 32-byte allocation each), so the process heap grew by ~130 MB a minute (1.4 GB of
pending interrupts after 15 minutes, found with a sampling heap profiler) and the queue the guest
drains grew with it.

An interrupt of a context that already has an unread interrupt now adds to it (its count in
fflags), as a kqueue event that triggers again before it is read does, so there is at most one
unread interrupt per context; a new pending interrupt starts its count at 1. The guest learns the
GPU's progress from the labels the interrupts follow.
The locks of the page tracking (the memory tracker's and the page
manager's per-region locks, the texture cache's lock) are spin locks the
GPU threads and the guest's threads share: a game thread handling a page
fault takes a tracker region's lock and, under it, the page manager
region's lock, and changes the pages' protection with VirtualProtect
inside both. Their waiters spun with _mm_pause until the lock was free.

ASTRO BOT froze for 2-6 s at a time in Sky Garden, more often the longer
it ran: the holder of a region's lock, inside a VirtualProtect of a
single page that took 2.6-5.6 s, was ready (priority 10-11, base 8) but
did not get a processor, while a dozen game threads and the execution
thread spun on the same lock, and every other game thread was busy too.
The execution thread recorded nothing the whole time.

A waiter now spins for about 50 us and then sleeps on the lock word
(WaitOnAddress, at most 1 ms at a time) until the holder releases it;
unlock releases it with a sequentially consistent store, so it sees a
sleeper that registered meanwhile, and wakes one only when there is one. The GPU stage threads alone on a reserved core keep
spinning: they take no processor from anyone, and the execution thread,
the critical path, does not pay for a wake-up. The page manager's region
lock is the same lock now.
ASTRO BOT (PPSA21559, PPSA21564, PPSA21567, PPSA21568) runs in slow motion when the emulator
presents fewer frames than its frame rate: at 30 fps the game moves at half speed. Its simulation
never reads a clock. At start-up it sets its frame rate (60) once and stores it in three globals of
its executable: the rate (a double), the frame in seconds (a float) and the frame in microseconds.
Every frame the main update takes 1 / rate as its time step and hands it down to the game, the
physics world steps by the float, and most objects turn the microseconds into their smoothing
factors; about 180 functions also step their own per-frame updates (timers, velocities, the targets
of keyframed physics bodies) by a 1/60 float constant of the executable. Scaling the guest clocks
does not help, and the emulated vblank already follows wall time.

While the game presents fewer frames than its rate, those four values now hold the time between
presented frames (averaged over about eight frames, at most 1/30 s, twice the game's own frame), as
if the game had set that frame rate; at its rate they keep the game's own values. The game also
paces its frames by sleeping until 90 % of 1 / rate has passed: that reader now loads the game's
own frame time from unused padding before the main frame function, so that the pacing does not hold
the game at the slower rate.

Longer steps are not safe: the game itself only sets 60 fps or more, and its simulation is not
stable with steps much longer than its own. With steps of up to 1/15 s ASTRO BOT (PPSA21564) closed
a few seconds into the arrival flight of Go-Go Archipelago (pirate_island, Tentacle System), where
the emulator presents about 14 fps: a character controller of the level gained speed on every
66.5 ms step until its position overflowed (1e17, then inf and NaN), and a Havok shape AABB query
(hknpShapeQueryInterface) in a "Havok Worker" thread then read the missing body of its contacts at
0x20. Below 30 fps the game slows down again instead of taking longer steps.

ASTRO's PLAYROOM (PPSA01325) runs on the same engine, with the same globals, getters and main
update, and about 50 readers of the 1/60 constant (47 in 01.905.000). It does not pace its frames
by 1 / rate: the rate is only read by the 1 / rate getter, and that getter only by its updates. It
gets the same treatment without the pacing redirect.

The disc, digital and Japanese releases and their updates place this code and data at different
addresses, so they are found in the loaded executable by their code: the three frame-rate getters
next to each other (with step = rate + 8 and period = rate + 16, and 1.0 as the dividend), the only
call of the 1 / rate getter followed by a multiplication by 1000.0 (the pacing; ASTRO's PLAYROOM
must have none), a call of it followed by a conversion to float (the main update), the closest 8
bytes of int3 padding before the pacing, and the 1/60 float that the code reads the most (218
reads in 01.007.000 of PPSA21564, none for any other). Nothing is written unless each one is found
exactly once; the other titles and versions are left alone.

[HACK] Title-specific and visible: "[HACK] ASTRO BOT frame time" (or "ASTRO's PLAYROOM") is printed
with the title, the version and the addresses found when the executable is patched (or why it is
not), and the notice summary shows while the frame time is stretched. It stays until these games
run at 60 fps in the emulator.

Also: keep ASTRO BOT's physics stable with frame times of up to 1/20 s.

The frame-time [HACK] gives ASTRO BOT the time between presented frames as its step, so that the
game does not run in slow motion below its 60 fps. Its simulation is built for its own step: at
1/15 s a character controller of Go-Go Archipelago (pirate_island) diverged to NaN and its next
world query read a body it does not have (a guest fault reading 0x20 at pc 0x9008743e2 in a
"Havok Worker" thread), so the step was limited to 1/30 s and the game ran in slow motion again
below 30 fps.

Based on the community ASTRO BOT delta-time patch shared on Discord (the "General stability and
physics fixes" option of its launcher cheat files for PPSA21567 01.018.000 and 01.019.000), the
hack now also changes the game code that fails with longer steps. The code is found by patterns
that match 01.007.000 and 01.019.000 of PPSA21564 and 01.019.000 of PPSA21567, and goes to a page
next to the executable:
- Havok's QueryPoint does not query the world for a contact without a body. Only a character at a
  NaN position gets there (the sphere of those contacts is infinite), and that query is the fault
  above.
- Three Havok tree traversals end when their 256-entry node stack in the frame is full, instead of
  writing past it (a diverged query box visits the whole tree).
- Three solvers that step their objects ten times per frame by a tenth of the frame, and the cloth
  update (ApCloth), take up to four times as many steps, so that each one stays about as long as
  at 60 fps (rope bridges, cloth and inflatables, per the community patch).
- While the bot-rescue update runs the game keeps its own frame time: the community patch found
  that the rescued bots and the controller do not show up with stretched frames.
The guards and the rescue report through [HACK] notices when they fire. With all of them the
longest stretched step is 1/20 s, as in the community patch; where they are not found it stays
at 1/30 s. A cheat file whose Decouple option rewrites the frame-rate getters or the pacing still
turns the hack off, and the log now says that a cheat file is in use.

Same save and scene, with native ray tracing (the arrival flight of Go-Go Archipelago at 14-19
fps): with steps of up to 1/20 s the flight, the landing and the first steps on the island play
without a fault, and no guard fires. With steps of up to 1/15 s it no longer faults either (the
QueryPoint guard skips about two queries per second), but that character still diverges and the
game drops to 2-3 fps, so the limit stays at 1/20 s.
In Fidelity mode GTA V (PPSA04263) traces its RT shadows in compute
shader fa8b1616fddc203b, which walks the game's AMD BVHs with
IMAGE_BVH_INTERSECT_RAY. Emulated node by node it takes ~20 ms of GPU
per frame.

Build host acceleration structures from the guest BVHs on the GPU and
replace the shader's two traversal loops with ray queries:

- rt_tlas_walk.comp walks the guest TLAS (header at [s[4:5] + 16]) and
  writes one VkAccelerationStructureInstanceKHR per instance leaf
  (inverse of the guest world-to-object matrix, mask, facing flags).
  Instances with unusable transforms are left inactive.
- rt_blas_walk.comp counts the triangles of new BLASes, writes them
  (opaque and alpha tested ones as two geometries, with a table back to
  the guest leaf entries) and checks the boxes of built ones each frame;
  changed BLASes are built again. Triangles with non-finite vertices or
  outside the box of their leaf (a node the game is rewriting) are
  inactive.
- NativeRayTracing keeps the slots, builds the BLASes and the TLAS
  before each tracing dispatch, and reads the walk results back with
  deferred host operations.
- RayTracingPatch rewrites the decoded traversal loops of fa8b1616 into
  RT_* pseudo-instructions; the SPIR-V backend emits them as ray queries
  that report the hit (t, primitive word, instance) where the guest loop
  left it. Alpha tested candidates are sorted per lane and run through
  the game's own instance setup and leaf code, one (instance, entry) key
  per wave round, 256 rounds at most.

The game's leaf code loops over the rest of the leaf list until an entry
marked last. The patched copy tests only the selected entry (the
hardware reports the other triangles as candidates of their own): an
entry of a list the game rebuilt meanwhile could otherwise run past the
end of the BLAS buffer, where the loads read zeros and no entry is the
last one (GPU hang after a few minutes).

Fidelity (still scene, interleaved runs): 10.1 -> 11.8 fps (+16%);
fa8b1616 goes from ~20 ms to ~6 ms of GPU per frame. Performance mode does not
run the shader (unchanged). Needs VK_KHR_acceleration_structure and
VK_KHR_ray_query, which the device enables with upstream's --native-rt;
without them the shader runs as before.

The GPU memory of the acceleration structures is bounded, so a long
Fidelity session no longer grows without limit (the first version went
from 8.7 to 18.7 GB of VRAM in about 7 minutes, and one BLAS the game was
rewriting asked for 8 GB at once). A grown slot retires its old structure
and buffers. A slot unused for 1800 frames is evicted (so what the camera turned
away from keeps its shadows when it turns back): its table entry
becomes a tombstone (rt_tlas_walk.comp probes past it and new keys reuse
it) and its memory is destroyed once the recorded work has completed. A
slot of more than 2M triangles or 256 MiB, or whose build scratch exceeds
the scratch buffer, is not allocated. The arena has a budget (a quarter
of the largest device local heap within 512 MiB to 4 GiB, or
KYTY_RT_ARENA_MB, 0: none) and evicts the least recently used slots above
7/8 of it. It uses chunks of 64 MiB, places each allocation best fit and
drains the least used chunk when it reserves much more than it uses.

The walks share one pool of queue memory per preparation, and a
streaming burst (loading a district, the first frames in a garage:
hundreds of new BLASes at once) used to starve it. Every build took a
queue as large as its header's node limit, so most of them found the
pool full and produced slots with no triangles that were marked built
(shadows missing for the objects, for good), and the counts that failed
8 times were given up forever (half of the instances of the TLAS stayed
without a BLAS for the rest of the session). Now a build asks for a queue
sized by the leaves counted for it (the node limit only for a BLAS whose
leaves are not known, or after it overflowed), the builds of a
preparation use at most half of the pool and the counts a quarter, a
build or check that finds no room is done again, and a BLAS that could
not be counted is reported again every 64 preparations instead of never.

The instance flags tell which face of its triangles the game accepts:
its leaf code compares the sign the triangle test returns with flags
bit 3 (and takes both faces with bit 2). With bit 3 clear it accepts the
faces whose sign is set, the host's back faces, so the TLAS flips the
facing of those instances. Without it the wrong face was culled for
every instance that is not double sided: the single sided geometry (a
ped, ceilings, roofs, walls) cast no shadow (Trevor, standing
next to his car, had none at his feet).

A triangle outside its leaf's box is not dropped any more for static
BLASes, only one outside the box of the whole BLAS. The game's boxes do not always hold
the triangles of their leaf lists (tens of triangles per frame in a
scene lie outside them although the game's own traversal finds them),
and dropping them left the roof of a garage without shadow: the sun lit
its inside, dark in the game's own traversal. Triangles of nodes the
game is rewriting, far outside the BLAS, still become inactive.

The leaf box stays for the BLASes the game refits or has just changed
(vehicles, peds): a walk can read their nodes while the game rewrites
them, and the box of the leaf is what keeps those half written triangles
out (checking only the box of the whole BLAS let them in as large
stretched blocks around moving vehicles).

The queue of BLAS builds is served oldest first (it was last in, first
out): with a hundred or more animated BLASes asking for a build every
frame the backlog reached hundreds and the slots deep in it, such as a
ped that has just got out of a vehicle, kept the shape of their last
build for up to ~100 frames (measured: slots whose host triangles
differed from the guest's for 60 or more consecutive preparations; with
the age order the longest lag is 6 frames).

The traversal is a closest hit, not a first hit. The shadows of traffic
vehicles passing by left trails (copies of the wheel and body shadows
along the vehicle's path): the shadow pass reads the hit instance's
record (+60, bit 31: a moving object) and its denoiser keeps no history
where the occluder moves, and the game's front to back traversal makes
its first hit the nearest occluder. Ending the ray queries at the first
opaque hit the hardware found (often static geometry farther along the
ray) kept the vehicle's shadow history. The queries trace without
TerminateOnFirstHit and alpha tested candidates in front of the committed
hit still run the game's leaf code.

The patched shader keeps the guest pc of every instruction. The patch
inserts the native traversals after each site's entry, which moves the
instructions after them, and at its end the shader reads a table of 16
tile offsets stored after s_endpgm through a buffer at s_getpc_b64 + 0x68.
Translated with the moved pc, the address pointed into whatever followed
the code and the tile flags went to the wrong tiles: bit 0x8 (the wide
penumbra filter) was set in ~650 tiles per frame instead of ~22,000, the
denoiser kept the history where the vehicle had been and left stepped
copies of its shadow. S_GETPC_B64 now translates with the original pc.

The second RT shadow pass, cs 6db33a2bcb077bc3, has the same two packet
traversals of the TLAS at [s[4:5] + 16] over other registers; its two
loops are patched the same way (its leaf code has no switch that turns the
alpha test off, so a site can name no such register). Fidelity, still
scene (debug build): 9.7 fps with both shaders emulated, 12.3 fps with
both native.

Short rays: cs 651da332bc4a3f98 traces rays of at most 0.2 units through
the TLAS at [s[4:5] + 112], per lane (a wave-wide walk of the TLAS, then
each lane walks the BLAS of an instance with its own stack and keeps the
nearest triangle of either facing, with no alpha test). It is patched as
a closest hit site: every triangle opaque, no facing cull, and the commit
writes what the game's leaf code writes (distance, primitive word,
instance record, triangle node, and the barycentrics as the guest
triangle test reports them, the weights of the node vertices its remap
bits select). The host BLAS entry table also keeps the triangle node and
its barycentric remap (16 bytes per entry), and the TLAS size of a
preparation follows the last walk of the same TLAS, as the shaders trace
different TLASes. Fidelity, still scene (debug build): 8.7 fps with every
traversal emulated, 12.0 fps with fa8b1616, 6db33a2b and 651da332 native.

[HACK] Two parts are cuts, not what the hardware does, and each reports
a [HACK] notice when it changes what is traced: a wave stops after 256
rounds of alpha tested candidates and drops the rest, because a lane
whose key the leaf code never retires would hang the GPU (the lanes that
drop candidates mark the entry of their shader hash in hack marks after
the bitmaps of the fault buffer, which the host reads back every 32
fault reads without waiting and reports with the hash and the count);
and the walk of a BLAS the game refits drops the triangles outside their
leaf's box, because half written nodes would trace as stretched blocks,
although the game's boxes do not always hold their triangles (the walk
counts the triangles it drops in its state, reported with the readback).

Also: find the RT traversal loops of GTA V's shaders by structure.

The native ray tracing patches replaced the BVH traversal loops of three
GTA V shaders described by hand, by shader hash: two tables of sites
(the pcs of the loop, the instance setup, the leaf code and the exit,
the ray, mask and result registers). GTA V 01.011.001 (the current PS5
update) recompiled the three shaders that trace the TLAS: the first
shadow pass (fa8b1616fddc203b is now 8b2cbb0a0c686402), the second one
(6db33a2bcb077bc3 is now d39726900d9532a5) and the short rays
(651da332bc4a3f98 is now 71445d3087ceb8e1). None of them matched, so on
that version Fidelity mode kept the emulated BVH traversal (about 16 fps
instead of 20 fps) and nothing of the native tracing was exercised; any
other build or game kept the emulated traversal as well, and each new
hash would have needed another table.

The loops come from a template of sce::Psr (kBase format: root node
0x25, node type in the low bits, a stack of node pointers in VGPR lanes
capped at 60 with S_MIN_U32, a BVH T# built with S_BFE_U64 addr,
0x280008). The compiler now finds them by that structure in any compute
shader (RayTracingPatch.cpp, SiteFinder), and the hash tables are gone:
the loop header of a wave-wide traversal (S_AND_B64 target of the loop's
backward branch, S_AND_SAVEEXEC_B64, the node type test) or of a per lane
one (S_MOV_B64 exec), the box test's ray registers and TLAS header, the
stack pointer, the instance mask test of the setup, the BLAS loop head,
leaf, latch and the hit the leaf code accepts, the alpha test switch,
the SGPR the setup spills, the exit; the TLAS source is the header's
64-bit load from a user data pointer and the root the node register's
first value. A shader whose loop does not match in every detail keeps
its traversal. The TLAS source travels in the program's ShaderInfo
(stored with cached modules) to the dispatch that prepares the host
structures, and compute programs compiled with patching on get their
own program keys.

On GTA V 01.011.001 the derived sites and sources of the three shaders
are identical to the tables, field by field, as are those of the
previous build's fa8b1616fddc203b and 6db33a2bcb077bc3 (checked
offline); the fourth shader with BVH reads (85616b0a1db9efd4) is not a
traversal of this template and stays emulated at this point. Astro Bot's
shaders use another variant and are not recognized yet.

Also: run GTA V's RT shadow alpha test per lane in native traversals.

The ray traced shadow pass of GTA V's Fidelity mode (cs 0b41af19bddf132c)
traverses as a packet: with native ray tracing, every lane collects the
alpha tested triangles its host ray query reports and the wave then runs
the guest leaf code for one (instance, leaf) at a time with the lanes
that reached it. Rays that cross foliage and decals without an opaque hit
serialize the wave over dozens of candidates: the pass took ~28-33 ms of
GPU per frame, 55 % of the frame, against ~2 ms with every triangle opaque.

The leaf code's alpha test is recognized by the dataflow of what it
computes (material record, index and vertex buffers through the V#s of
the game's tables, the alpha texture of its bindless table, the level of
detail of the ray cone and the threshold), and the native traversal runs
it per lane on each candidate the hardware reports, confirming the ones
it accepts: the query returns the nearest of the opaque and accepted
hits, and the leaf code no longer runs. A site whose leaf code does not
match, or a program without a single bindless table sample, keeps the
previous path.

Also: run every alpha tested candidate of native RT traversals.

With --native-raytracing, a packet traversal whose leaf code the per lane
alpha test does not replace runs the game's leaf code for one (instance,
leaf) key per wave round, the smallest key any lane has. In GTA V's
Fidelity mode that is the second RT shadow pass (cs 2f34bc2dfe6b04a3,
whose leaf code has no single bindless table sample). A wave stopped
after 256 rounds and dropped the candidates it had left, so rays that
cross many alpha tested triangles (foliage) missed the ones the game's
alpha test would have accepted: 2,752 lanes in one 30 s Fidelity run,
the [HACK] notice of the limit.

Every round retires the selected key in each lane that has it (the leaf
code's resolve drops it or ends the lane's traversal, a culled instance
drops it), and a query reports each alpha tested triangle once, so a
wave always ends, after as many rounds as its lanes have candidates.
With a limit of 2^20 instead, the waves of that run that went past 256
rounds ended by themselves after 301 to 683. The limit was added while
looking for a GPU hang of this path that it did not fix: the game's leaf
code looped over a leaf list the game had rewritten, fixed by testing
only the selected entry. The game's own traversal has no limit either.

It was also the last hack mark a shader emits, now that the loop exits for
uncached device addresses are gone (upstream 6030fde6 reads unbacked BDA
pages as all ones in BVH shaders, which ends ASTRO's PLAYROOM's leaf walk):
the mark emitters and their test go too.

Also: overlap the dependent reads of the native RT alpha tests.

A wave64 program runs on a 32-wide host subgroup with two guest lanes per
invocation, each with its own ray query. The native traversal refilled
the candidates of the first half's query to its end, then the second's:
two dependent loops, each waiting on its own traversal and on the reads
of its alpha tests.

Both queries now advance in the same loop: each iteration proceeds both
queries before handling either result, so the traversals and the alpha
tests of the two halves overlap.

The alpha test of GTA V's RT shadows (cs 0b41af19) and reflections
(cs 6aeb221d) reads, for every alpha tested candidate a ray hits, the
triangle's three vertex indices and then their texture coordinates: two
more links in a chain of dependent reads that took most of the 3.7 ms
of the shadow dispatch.

After its entry table, each host BLAS slot now has a 32-byte record per
alpha tested triangle: the coordinates and a check word over them and
over what selects them (the primitive word, the material's stride and
offset, the V#s of the index and vertex buffers, the layout). A
candidate whose record matches takes the coordinates from there; others
read them as before and write the record, coordinates first. A walk
build clears the records of its slot, and a record half written by
another lane fails the check. The shadow dispatch takes 2.5 ms instead
of 3.75 and the reflections 0.40 instead of 0.48; the per-ray
verification is unchanged.

Also: keep the triangles of GTA V's dynamic BLASes outside their leaf boxes.

The native RT walk makes a triangle of a guest BLAS inactive when it is
outside a box: the box of its leaf in the BLASes the game refits or
changed lately, the box of the whole BLAS in the others. In GTA V's
Fidelity mode three BLASes of alpha tested triangles that the game
changes every frame (foliage, built again before every use) lost a
quarter to almost half of their triangles in each build: 225,000 of the
227,000 triangles the walks dropped in a 30 s run, the [HACK] notice in
158 of 194 preparations. Their leaf boxes do not hold the triangles of
their lists: the game's builder splits triangles among leaves and each
leaf box holds its part, while the game's traversal tests the whole
triangle in any leaf a ray enters (the reason why the other BLASes use
the box of the whole BLAS: dropping them lit the inside of a garage).
The other 1,600 were degenerate triangles of a refit BLAS, which the
refit leaves out of its boxes and nothing hits.

Every walk now checks the box of the whole BLAS (the union of its root's
children): the game's BVH bounds every triangle a ray can hit, so only
nodes the game is rewriting fall outside it. A split triangle is in the
lists of several leaves (the same triangle node, two leaves on average
in GTA V): a build without a layout now writes it once, from the first
of its entries the walk reaches, and leaves the others inactive (a
layout build already places them at the same position). Written once
per entry, as the static BLASes had them, the copies were candidates
the ray queries tested again: 5.6 % fewer fps in Fidelity with RT
without the frame limit, and as many as before once they are gone.

Also: trace GTA V's RT reflections with host ray queries.

GTA V's RT reflections (cs 85616b0a1db9efd4, 3.3 ms of GPU per frame in
Fidelity) trace with a closest hit traversal that alpha tests the
triangles whose primitive word is not marked opaque: the wave walks the
TLAS, each lane walks the BLAS with a stack in memory, and the leaf code
reads the material, the indices and the texture coordinates of an alpha
tested triangle with vector loads and samples its texture. The patch did
not recognize that leaf code, so the shader kept its emulated traversal.

The closest hit derivation now also accepts that leaf code: the opaque
split on the primitive word, the alpha test (the packet sites' test with
structured buffer loads of the material, the vertices read at the base
address of their V#, a per lane reference and cone spread) and the moves
of the accepted hit. The native traversal takes every triangle as a
candidate (the guest ignores the instances' opacity flags), confirms the
opaque ones and runs the per lane alpha test on the others. Closest hit
sites also take the guest's constant instance mask (0x7f) instead of
tracing every instance.

Also: derive the BVH layout of native RT traversals from the guest shader.

The native ray tracing patch only recognized the traversal loops of GTA V
01.011 and 01.010, and the host passes read the instance records with
their layout. GTA V 01.005.000 (PPSA04264) traces with an older version
of its BVH library and none of its three traversals was patched (the
RT shadows, cs 77826b07, cost 6.7 ms per dispatch emulated): its
instance records are found at the offset at header +0x28 instead of
+0x30, hold the world to object matrix by columns at +0x08 instead of
by rows at +0x00, the BLAS address as it is at +0x00 instead of packed
at +0x30, the mask in bits 8-15 and the flags in bits 0-7 of +0x3c;
its alpha test reads the geometry table and the first triangle node at
BLAS +0x20 and +0x80 and forms the texture coordinate offsets with byte
masks.

The site finder now reads all of that from the traversal's own code:
the record address (header + the 64-bit offset at a header field +
(node >> 3) << 7), the affine forms of the object space ray (the record
dwords each world ray component is multiplied by, and the one added),
the pair the BLAS T# is built from (two dwords as they are, or packed),
the root moved into the BLAS walk or pushed on its stack, the instance
mask test, and in wave-wide traversals the instance flags of the
opacity test. The packed layout travels with the program's ShaderInfo
to the TLAS walk (LoadGuestInstance in rt_common.inc). A traversal
without a mask test traces every instance.

The facing rule is also each program's own: the shadows accept, with
flags bit 3 clear, the triangles the host sees from the back (the fixed
flip parity so far), while the second RT pass of 01.011 and 01.010
(cs d3972690 / d3c89254) and 01.005's c7795cb2 accept the opposite ones,
and cull only when a dispatch constant (d3972690) or a per lane option
(c7795cb2) asks for it. The leaf code's final lane mask is evaluated as
a truth table over the facing compare, the hit and the selector, and the
lanes that cull are passed to RT_INIT, which sets CullBackFacing only in
those lanes.

Other changes the 01.005 traversals needed: the TLAS header pair is
found from the S_BFE_U64 of the TLAS T# (the pair holds the root node
by the loop), the BLAS test is the one whose T# is built in the loop
(the BLAS address may be in the TLAS header's registers), the instance
mask test may be wave-wide (an SGPR mask) or a V_CMP that narrows EXEC,
and the per lane alpha test takes an SGPR cone spread and its field
offsets and vertex offset form from the code (RayQueryAlpha's format
argument).

Also: trace Astro Bot's wave-wide closest hit traversals natively.

Astro Bot traces its BVHs (the reflection and lighting rays of Sky
Garden, 13 programs) with another template of the BVH library: the TLAS
and the BLAS are walked wave-wide (scalar nodes, a stack in VGPR lanes),
the leaf code keeps the nearest hit per lane with V_CNDMASK_B32 (or
V_MOV_B32 under a narrowed EXEC) of the distance and the primitive
word, every triangle is opaque and the instance flags select the
facing. None of the programs was patched and their traversals were
emulated.

A closest hit site may now keep its hit that way: the reject mask of the
V_CNDMASK_B32s is evaluated as a truth table over EXEC, the facing
compare, the hit, the selector of the facing rule and the distance test
(t > t max), and the site traces with the hardware, every triangle
opaque, with the facing of the instance flags, committing the distance
and the word when nearer. The selected key goes to an SGPR pair the
program never uses. Its instance mask test is any bit of the record's
top byte (S_CMP_GT_U32 <dword>, 0xffffff), the BLAS root is the value of
the inner loop's node register before it, and a loop nested in another
site's loop is not a site of its own.

The TLAS leaves of node type 7 have their instance record at header +
0x80 and the BLAS root 0x25 (S_CMP_LG_U32 7, <node & 7> selecting
S_MOV_B64 of header + 0x80, and S_CSELECT_B32 of the root); the layout
carries them to the TLAS walk and to the committed instance of the
traced rays.

Nine of the 13 programs are patched; two walk wave32 (S_MOV_B32
exec_lo, the header interleaved) and are still emulated.

Also: recognize the guest BVH walks of 32-lane waves and of ASTRO's PLAYROOM.

ASTRO BOT traces its reflections with compute programs compiled for
waves of 32 lanes (cs bdd0bb9bd8852dd4 and seven more), and ASTRO's
PLAYROOM uses an older version of the guest BVH walk in 17 programs,
8 of them wave32 (cs 5abb94205ac37db3, 038b50296f0de118, ...). With
--native-raytracing none of them was patched: the site finder only knew
the 64-lane forms of the lane-mask instructions and the layout of
GTA V's walk, so these programs kept walking the BVH on the guest side.

The site finder now takes the wave size of the program: lane-mask
operations are matched in their 32-bit forms, scalar register writes
follow the wave size and the packet site stays wave64 only. It also
learns Playroom's walk: instance records of 160 bytes (index * 0xa0)
whose transform starts at dword 4, a BLAS address stored as is, a root
node set by s_mov_b32 when a branch skips its load, instance masks of
20 or 24 bits tested with s_and or s_cmp, the node count at
header + 0x50 instead of + 0x58, and two more leaf forms: the hit kept
with v_cndmask after t, and the far distance tested with v_cmpx_le_f32.

The layout words now also carry the record stride, the transform base,
the mask width, bit 2 of the inline record offset and where the node
count is; the layouts of GTA V and of ASTRO BOT's wave64 programs pack
the same words as before. The emitter and the host walks read the
instance record with its stride and transform base, apply a narrow mask
as all lanes or none, and take the node limit from header + 0x50 when
the layout says so.

shader_cfg_tests check a wave64 and a wave32 site of ASTRO BOT and a
reduced Playroom program. In Playroom's CPU Plaza 13 programs are
patched now, 4 of them wave32, at 56-60 fps without errors.

Also: patch no more traversals than the ray query state holds.

The native ray tracing patch accepted up to 8 traversal sites in a
program, but the translation keeps ray query state for
IR::MaxRayQuerySites (4) and exits with "ray tracing patch site 4 out
of range" on the fifth. Gran Turismo 7 has a shader with 8 BVH walks
(24 IMAGE_BVH_INTERSECT_RAY). A program with more sites than that is
now left to the guest traversal.

Also: trace Gran Turismo 7's BVH walks, whose leaf code calls any-hit functions.

Gran Turismo 7 (sce::Psr's newer generation, BVH version 10) runs its
BVH walks wave-wide: the loop header copies EXEC (s_mov_b64 s[4:5],
exec), the instance code walks the BLAS in a second loop of the same
form, and its leaf code tests one triangle, calls the any-hit function
of the triangle's material (s_swappc_b64 through a call table) and,
when that returns v7 != 0, keeps the hit itself: v_cmpx_ne_u32 0, v7;
s_cbranch_execz, then V_MOV_B32s of the distance into t max, the
primitive word, the instance record pair, the triangle node and the
barycentrics. The instance setup spills SGPRs into VGPR lanes, which
V_READLANE_B32s after the BLAS loop restore. None of this was
recognized, and the patch ran before the call expansion, which decodes
the original code again.

A ClosestLeaf site runs the native loop of the leaf walk kinds: the
setup from the loop header (its box branch goes to the cull), the leaf
code with EXEC as its lane mask (its branches into the rest of the BLAS
loop go to the tail), every lane searching on after an accepted hit
(RT_RESOLVE dmask 2), the restores, and at the exit the opaque hit the
hardware found only where nearer than the leaf code's (RT_COMMIT dmask
1, with the barycentrics and the node). Programs with calls are patched
after the expansion, in RefreshShaderSource, and ApplyRayTracingPatch
moves the expanded program's runtime literals and inlined call bodies
with their instructions (the copied leaf code gets its own bodies).
GT7's three walks of this form (05e0cbbc, 05e12ebc, 05e3f1bc in its
eboot) are recognized after their calls expand; the instance record
layout, the TLAS header offset and where the node count is are taken
from the code, so the version 10 headers need nothing of their own.

Also: recognize guest BVH walks whose rays start at the same point in every lane.

ASTRO's PLAYROOM's cs 29289be6a0202b6d and ASTRO BOT's cs 9833d01b08e21d08 trace
rays whose world origin is the same for every lane. They keep it in SGPRs
(s12-s14 and s20-s22), copy it into the TLAS box test's VGPRs with V_MOV_B32
right before each test, and compute an instance's object space origin from the
SGPRs (V_MAD_F32 v, <record dword>, <origin SGPR>, v). The site finder took the
origin from the box test's VGPRs, which the instance setup never reads, so the
object space ray had no affine form and both programs kept the guest traversal.
Both also write the user data pair of the TLAS header (s[0:1]) in the other
cases of a switch before the header load, which the TLAS source check rejected.

A box test origin VGPR whose last write before the test is a plain V_MOV_B32
from an SGPR the traversal loop never writes, with no branch in between, is now
that SGPR: RT_INIT reads the component from it ([9..11]) and the object space
form takes it as a world input. The TLAS source check only rejects writes of
the header's user data pair on a path that reaches the load.

Layouts: 29289be6 d951c840 4c25ea62 30482080 308f2511 (2020 records, as
ddd61c40); 9833d01b 76543210 1dc6ba98 000dbb8f 000f2510 (as 1fc43349). The
other RT programs of GTA V, ASTRO BOT and ASTRO's PLAYROOM derive the same
sites and layouts as before, and their SPIR-V is byte-identical.

Also: trace GTA V's performance ray tracing shadows natively.

In GTA V's "Performance RT" graphics mode the native ray tracing (--native-raytracing) did nothing:
the program that traces the ray traced shadows (cs 0x48d704640ab9fb40, waves of 64 lanes) kept
walking the guest BVH, about one dispatch per frame and ~4-6 ms of GPU time each (the [RT] summary
counted every dispatch as a program whose BVH walk the patch does not recognize).

Its two traversal loops walk the TLAS wave-wide like the packet sites of the Fidelity mode, but
each lane then walks the instance's BLAS on its own (a stack per lane in LDS that spills to
scratch, closed by S_CBRANCH_EXECNZ) and runs the leaf code for its own triangles; any accepted
hit ends the lane's search. The guest leaf code cannot run for one candidate at a time, so these
sites (RayTracingKind::PacketLane) trace like a closest hit site: the hardware finds the hit with
the opacity and facing of the instance flags, the per-lane alpha test of the leaf code confirms
the alpha tested candidates, and RT_COMMIT writes the hit's distance, primitive word and instance
record. Without the per-lane alpha test the site keeps the guest traversal. As in the Fidelity
mode the host gives the nearest hit and the guest the first one it finds; the code after the
loop only reads the distance, whether there is a hit and the instance's dynamic flag.

The derivation is by the code's structure, and checks what the native traversal relies on:
- the per lane BLAS walk (one IMAGE_BVH_INTERSECT_RAY of a VGPR node starting at the record's
  root, the leaf entries, the triangle lanes, t = num / den within the t max), the hit moves and
  the TLAS walk dropping the lanes with a hit;
- the opacity: the alpha test runs for the lanes neither opaque (instance flags bit 0 or the
  primitive word's bit 30, unless flags bit 1) nor switched off by an SGPR the traversal keeps;
- the facing: the leaf code accepts one sign or the other by a wave-wide value x (selectors of
  flags bit 2 clear and x == 0 / x != 0); the host culls the back faces, or the front ones when
  the second selector holds (RayFlagCullFrontFacing);
- the alpha test of the closest hit sites (Lane layout) with the reference the leaf code computes,
  threshold * (M0 bit 0 ? factor : 1), the tables' V#s the program loads before the loop (read
  from their SGPRs at the entry), an NSA sample, and a level of detail chosen by wave-wide flags
  (cb dword 0x1e8: bit 26 the usual level, else bit 25 a ray cone, else 0): the test is derived
  on the path of the usual level (the other branch replaced by S_NOP in a copy of the program)
  and the site keeps the guest traversal when that flag is clear;
- a loop header whose lane mask the compiler keeps in VGPR lanes (V_READLANE_B32s before it,
  V_WRITELANE_B32s in the node type test); such a header that does not match keeps its loop, as
  other loops do;
- the TLAS header pair holds other values at the sites' entry: the guest's load of the header
  address is run again into the free SGPR pair RT_SELECT uses.

Performance RT (Franklin by his car in Los Santos, 30 s): 51 -> 64 fps.

Also: load the TLAS header again for closest hit sites whose header pair holds the root.

In GTA V 01.005 (PPSA04264) in the Fidelity mode with --native-raytracing, every ray of the
short contact shadow rays (cs 0x84ed00053b3771da, a closest hit site) went back to the guest
traversal: the [RT] summary of --rt-stats counted ~190 million rays every 10 s, and the program
took more GPU time than without the patch (3.1 ms per frame instead of 2.5).

The compiler loads the TLAS header address into s[12:13], builds the TLAS T# from it and then
reuses s12 for the root node (S_MOV_B32 s12, 37) before the loop. RT_INIT read the header from
that pair at the site entry, so the address it compared with the one the host published was the
root node and the header's high dword: never the same, every lane took the guest walk.

A closest hit site whose header pair holds another value at the entry now runs the guest's load
of the header address (S_LOAD_DWORDX2 from its user data pointer, which nothing writes) again
into an SGPR pair the program does not use, as the PacketLane sites already did into RT_SELECT's
pair; without such a pair the site is not patched.

Also: trace GTA V 01.005's performance ray tracing shadows natively.

In GTA V 01.005 (PPSA04264) in the "Performance RT" graphics mode the native ray tracing
(--native-raytracing) did nothing: the shadow program (cs 0x30c93330da43fd54, waves of 64 lanes)
kept walking the guest BVH, and the [RT] summary of --rt-stats counted every dispatch as a
program whose BVH walk the patch does not recognize. Its two traversal loops are the PacketLane
sites of 01.011's 0x48d704640ab9fb40, compiled differently:
- the first loop header keeps its lane mask in SGPRs but spills the saved EXEC into VGPR lanes
  in the node type test; such a header is now a packet header too (and, as the headers with
  spills, keeps its loop when it is not a site);
- the instance mask test is wave-wide: S_AND_B32 (R15 >> 8), <ray mask>; S_CBRANCH_SCC0 <next
  node>, with no test before it that narrows EXEC. The ray mask (0x80 or 0x7f) and the alpha
  test switch are spilled into VGPR lanes before the loops and read back in them; when the lane
  keeps the value through the loop (no other write of it there) RT_INIT reads it back at the
  entry, with the same V_READLANE_B32, into a free SGPR;
- the alpha test compares V_CMP_LT_F32 <reference>, <sampled> with a reference the same for
  every lane (threshold * factor, computed before the loops into an SGPR the traversal keeps):
  RT_ALPHA takes it from that SGPR (dmask 4);
- the leaf code loads the BLAS address from the instance record a second time into another SGPR
  pair for the geometry load: the same record dwords as the BLAS T#'s pair, with the same record
  pointer, count as that pair;
- the compares of the opacity and alpha switch selectors are their I32 forms.
The patch also counted image loads as writing 8 VGPRs, which hid the spilled lanes behind an
IMAGE_LOAD of one dword; it now counts the dwords of the data (and the one of TFE or LWE).

Also: trace GTA V 01.005's Fidelity packet sites with their alpha test natively.

In GTA V 01.005 (PPSA04264) in the Fidelity mode with --native-raytracing, the [RT] summary of
--rt-stats counted ~130 dispatches every 10 s of cs 0xa31ec6a25be5e017 as a program whose BVH
walk the patch does not recognize: its two traversal loops are the packet sites of 01.011's
0x0b41af19bddf132c, compiled differently:
- the instance mask test is S_AND_B32 <record dword>, 0x7f00; S_CBRANCH_SCC0 <next node>: the
  ray's mask in the constant, shifted (as ConstantMaskTest reads it for closest hit sites);
- the facing selectors compare with S_CMP_LG_I32 / S_CMP_EQ_I32, the same as their U32 forms;
- the record address read the TLAS header pair through S_FF1_I32_B64 s11, which the patch counted
  as writing s11 and s12 (the 32-bit results of 64-bit sources write one SGPR).
The alpha test of their leaf code also differs:
- M2 is loaded at offset 0 of <record offset> + 8 (S_ADD_I32) instead of at offset 8;
- the BLAS address is loaded from the instance record again into other pairs (VCC among them)
  for the geometry word and the BLAS fields: the same record dwords as the BLAS T#'s pair, with
  the same record pointer, count as that pair;
- the reference is threshold * factor for every material, computed in the leaf code and read
  with V_READFIRSTLANE_B32 (V_CMP_LT_F32 <reference>, <sampled>), not threshold * (M0 bit 0 ?
  factor : 1): RT_ALPHA's dmask 8 multiplies them before the test;
- the vertex stride and uv offset are M0 & 0xff and M1 & 0xff, and the vertex offsets are aligned
  down to 4 bytes (S_AND_B32 -4), the format the Lane layout already reads.

Also: trace closest hit walks with a per lane BLAS walk natively.

Marvel's Wolverine (sce::Psr BVH version 10) traces its reflections and shadows in
0x1a04c58a9fbc2052, whose traversal the native ray tracing patch did not recognize: it walks the
TLAS wave-wide as a closest hit site does, but then each lane walks the instance's BLAS on its own
(a stack per lane in LDS and scratch) and runs the leaf code for its own triangles: the triangle
test, the facing and opacity tests, a per-ray budget of alpha tests and the alpha test itself,
which samples the material's texture in a waterfall loop, keeping the nearest accepted hit in
registers. The alpha test is the game's own (meshlet-compressed indices, two vertex formats, a
level of detail from the triangle's area), so the native traversal runs the guest's leaf code
instead of a copy of it:

- The new site kind ClosestLane (ClosestLaneWalk) is recognized after the TLAS loop header's node
  type test: the instance setup up to the BLAS walk (the target of its backward
  S_CBRANCH_EXECNZ, whose only IMAGE_BVH_INTERSECT_RAY has the node VGPR as its address), the leaf
  code up to the S_MOV exec that ends it after the accepted hit's V_MOV_B32s (distance into t max,
  primitive word, triangle node, instance record pair and barycentrics, ClosestLaneHit), and the
  load of the next leaf list entry (V_LSHRREV_B32 <x>, 3, <node>; BUFFER_LOAD_DWORDX2 <node>, <x>).
- Its native traversal is a ClosestLeaf one in which every triangle is a candidate (no facing
  culled, none opaque: RayQueryInitAllCandidates), the wave takes the smallest instance any lane
  has (RayQueryKeyLaneLeaf), runs the guest instance setup once, and each lane with a candidate of
  that instance takes its own smallest leaf list entry into the node VGPR, loads the entry as the
  guest walk does and runs the guest leaf code, until no lane has candidates left (no limit of
  rounds). The copy of the leaf code leaves out the per lane walk's box code (skipped by an
  S_CBRANCH_EXECZ when no lane has a box node): its stack stores, whose addresses are no longer
  provably local in the copy, made the program's resource tracking incomplete.
- The BLAS walk's box test takes its T# from an S_BFE_U64 of the TLAS header that the program does
  before the loop and keeps in VGPR lanes: the box test is recognized through it.
- The TLAS header address is read through a V#: S_LOAD_DWORDX4 of the V# from the user data
  pointer, then S_BUFFER_LOAD_DWORDX2 at an offset. The patch records the V#'s offset
  (header_vsharp, ShaderInfo::ray_query_header_vsharp) and the host reads the V# to find the
  pointer the header is at (NativeRayTracing::UserPointer()).

The patched programs of GTA V's ray tracing shaders are the same as before (the nine of the
dumped Fidelity, Performance RT and mode switch passes, with waves of 64 and 32 lanes), and the
new IR variants are only used by ClosestLane sites.

Also: trace shadow rays with a lane masked TLAS stack and a per lane BLAS walk natively.

Marvel's Wolverine's 0x1a04c58a9fbc2052 traces its reflections (a closest hit site, recognized by the
previous commit) and then its shadow rays with a second walk the native ray tracing patch did not
recognize, so every shadow ray still walked the guest BVH with 32 lanes: the TLAS loop keeps a stack of
(node, lane mask) pairs and drops the lanes that find an accepted hit, and past the instance setup each
lane walks the instance's BLAS on its own and runs the guest leaf code (the triangle test, facing and
opacity tests and the alpha test), clearing itself from the lane mask the setup copied from EXEC when it
accepts a hit. This is a packet header (S_AND_B32, S_AND_SAVEEXEC_B32, node type test), which was only
recognized in waves of 64 lanes.

- The new site kind AnyLane (DeriveAnyLane, reached from DerivePacket in waves of 32 lanes only, other
  loops of that form keep the guest walk as before) shares the form of ClosestLaneWalk's BLAS walk (the
  backward S_CBRANCH_EXECNZ, the node VGPR of its only IMAGE_BVH_INTERSECT_RAY, the load of the next
  leaf list entry, the box code the copy leaves out) and ends the leaf code after the lane leaves the
  lane mask. Its native traversal is a ClosestLane one (every triangle a candidate, the smallest
  instance, each lane its own leaf, the guest leaf code) with the Packet sites' mask handling: the
  guest's copy of EXEC into the lane mask runs after RT_LEAF and RT_RESOLVE terminates the query of a
  lane that left the mask. There is no RT_COMMIT: the guest leaf code writes the hit.
- The ray's direction is the same for every lane and the loop reads it from VGPR lanes every iteration
  (V_READLANE_B32 into an SGPR, V_MOV_B32 into the box test's VGPR) and its t max is a constant moved
  into a VGPR there. RT_INIT reads a direction component from a lane of a VGPR (image_nsa_addr[12..14],
  bit 31 set) and a constant t max from `secondary_offset`; the instance records' layout derivation follows a
  direction read that way (LaneInput) as the ray of the BLAS test.
- Two sites of one program may test the instance mask with constants that select other bits of the
  same record dword (0x68000000 and 0x30000000): the lower shift serves both with the constants moved
  up, so the program keeps one record layout.
- MaxImageNsaAddressComponents is 16 for the extra RT_INIT operands.

GTA V's ray tracing shaders give the same patched programs as before (the nine of the dumped Fidelity,
Performance RT and mode switch passes, waves of 64 lanes; none in waves of 32).

Also: trace Resident Evil Village's per lane BLAS walks natively.

Resident Evil Village (sce::Psr BVH version 1) traces its ray tracing in 0xbe0b848d2e06ec9b and
0xf969c192323c215b, closest hit walks with a per lane BLAS walk like Marvel's Wolverine's
0x1a04c58a9fbc2052, but the native ray tracing patch recognized none of them: their walks load the
next leaf list entry in another form, and their accepted hit is kept in other registers.

- The entry goes to another VGPR pair, which a V_MOV_B32 then copies into the node VGPR of the BLAS
  walk's IMAGE_BVH_INTERSECT_RAY, and the walk keeps the index of the entry after it:
    V_LSHRREV_B32 <x>, 3, <entry>; BUFFER_LOAD_DWORDX2 <entry>, <x> idxen
    V_ADD_NC_U32 <next>, 1, <x>; S_MOV_B64 exec, <lanes>; V_MOV_B32 <node>, <entry>
  ClosestLaneWalk now takes that form too (LaneEntryCopy): the lane's leaf list entry pointer goes to
  <entry>, and the native leaf runs the guest instructions up to the V_MOV_B32, except the S_MOV_B64
  exec that restores the guest walk's lanes (EXEC is the lanes the native traversal selected).
- The accepted hit (ClosestLaneIndexHit) moves the distance, the primitive word (the entry's second
  DWORD), the index of the next entry and the instance record pair into VGPRs that are not
  consecutive (low into v37, high into v36), and has no barycentrics: the site keeps the VGPR of the
  record's high DWORD (result_instance_hi; NoRegister keeps result_instance + 1). The native commit
  writes no node or barycentrics there: in these walks every triangle is a candidate of the guest
  leaf code, which writes them itself.

The leaf lists and the nodes of version 1 are those of GTA V (8-byte entries with the triangle node
pointer and the primitive word, AMD box and triangle nodes), so the host BLASes are built from them
as they are. The sites of GTA V and Wolverine derive as before.

Also: run Resident Evil Village's alpha test in the native ray tracing of its closest hit walks.

With native ray tracing, Resident Evil Village's per lane BLAS walks (cs
be0b848d2e06ec9b, f969c192323c215b) ran the guest's leaf code once per
candidate triangle and per round: the wave takes the smallest instance, sets
it up, and every lane with a candidate there runs the setup and the leaf code
for one of its own. About 93 % of the candidates are alpha tested, 5 per ray, so
the dispatches took 21.8 and 12.7 ms instead of the 9.1 and 2.6 ms of the
guest's own walk, and the house of the first level went from 25.5 to 16 fps.

The leaf code of these shaders is the compiler's output for one template of
the BVH library (sce::Psr version 1), so DeriveEntryAlphaTest() recognizes it
by its machine code (from the triangle test to the flag test of the accepted
hit) and checks the data flow it relies on: the instance flags (record dword
15, bit 0 opaque, bit 1 alpha tested anyway, the same meaning as the host's
instance flags), and the V#s of the material entry and buffer tables, which are
user data SGPRs of the program. Such a site (RayTracingAlphaLayout::Entry) runs
no guest code in its native traversal: the hardware finds the nearest opaque
hit, the per lane alpha test confirms or drops each non opaque candidate, and
RT_COMMIT writes the registers of the accepted hit like a PacketLane site's
(distance, primitive word, instance record, and the index of the entry after
the hit's as its node).

AlphaTestEntry() does what the guest leaf code does: the instance record's
material entry selects the index and vertex buffers (with their strides), the
triangle's three 16 bit indices select half float texture coordinates, which
the barycentrics of the guest's triangle test interpolate; the material's
first texture, when it has one, selects the scale of the coordinates by its x
and y channels, and the alpha is the x channel of the second one, which must
exceed 0.5. The two samples are the program's own (EmitImageSampleLodAtKey()
emits an image sample for another key of its heap or table), so the textures
are the ones the guest samples. The instance dependent reads are kept in the
lane's alpha cache. A program in which the two samples are not found keeps
the guest traversal, as before for PacketLane.

Measured in the house (Continue, 60 s of fps, same save): 33-35 fps with native
ray tracing against 24.7-25.8 without it (16 before); the frame matches the one
without native ray tracing as closely as before (mean pixel difference 1.7).
The patched programs of GTA V's nine shaders and Wolverine's 1a04 are identical.

Also: trace Marvel's Wolverine's second shadow ray compute natively.

Marvel's Wolverine's cs 0xb790bfb6f776e13a (a ray tracing compute, waves of
32 lanes) kept walking the guest's BVH with native ray tracing on ("RT derive
FAIL: 0 sites", the --rt-stats line "programs whose BVH walk the patch does
not recognize"). It is the same walk as the second site of 0x1a04c58a9fbc2052
(a TLAS loop with a stack of (node, lane mask) pairs in VGPR lanes, a per lane
BLAS walk, the guest's leaf code that takes any hit), compiled differently:

- the loop header has the node type's S_AND_B32 before the S_AND_SAVEEXEC;
- the ray direction is the same for every lane, kept negated: V_MOV_B32 <v>,
  -<s> before the loop, and the object space direction is built from the SGPRs
  with the negation (V_MAD_F32 ..., -s29, ...); a negated SGPR that a VGPR
  input copies with the negation is that input;
- the compiler duplicated the BLAS loop (two identical copies, the second
  after the first one's exit, with the same prologue); the instance setup
  jumps to the copy's prologue under one condition, which the native
  traversal sends to the leaf code, as both copies run the same code;
- the accepted hit restores EXEC from vcc_lo, and t max is V_CVT_F32_I32 64.

A site found this way patches 4851 instructions; the patched programs of GTA
V's nine shaders, Resident Evil Village's two and Wolverine's 0x1a04 hash the
same as before.

Also: trace the any hit walks with lane masks on the IR.

Marvel's Wolverine's shadow rays (cs b790bfb6f776e13a, and the second
traversal of cs 1a04c58a9fbc2052, waves of 32 lanes) walk the TLAS with a
wave-wide stack of (node, lane mask) pairs; each lane then walks the BLAS
and runs the leaf code, and a lane that accepts a hit leaves the live
lanes. The native ray tracing patch recognized this walk on the decoded
program and placed a native traversal with copies of the guest's instance
setup and leaf code before the loop.

The walk is now recognized on the SSA program before resource tracking
(TraceNativeTraversals, next to the ray query pass), and rewritten in
place: only phi arguments, selects and branch conditions change. With the
host's structures the stack pops the candidates of the lanes' ray queries
(the smallest instance any lane has, with the lanes that have it), each
BLAS walk starts at the lane's own leaf list entry of that instance and
ends after its leaf code, and the walk leaves when no lane has a
candidate; the first iteration runs without lanes and goes straight to the
pop. Without them the loop walks as before.

The TLAS source (user data pointer, V# offset, header offset, root) and
the instance record layout come from the IR as the patch derived them from
the decoded program (the same packed layout for cs b790bfb6f776e13a): the
record address, the world to object matrix from the BLAS box test's ray,
the BLAS address, the node count and the instance mask. The patch keeps
its other forms. A program with both (cs 1a04c58a9fbc2052) gets the IR's
site after the patch's, sharing its TLAS and layout: its walk's constant
ray mask (0x30000000) selects the instance mask's bits at a higher shift
of the record dword the patch's site reads (0x68000000), so it moves up
to the patch's shift, as the patch did with two sites; its lanes start as
the tracing lanes without the finished ones (S_ANDN2 of EXEC). The guest
BVH reach of a patched program counts once the patch and the IR cover
every node test (Program::ray_tracing_outside).

Also: trace Resident Evil Village's closest hit walks on the IR.

Resident Evil Village's shadow rays (cs be0b848d2e06ec9b, f969c192323c215b,
sce::Psr version 1) walk the TLAS for the lanes of a packet and each lane
walks its instance's BLAS, whose leaf code is the library's alpha test
template. The decoded patch recognized them (ClosestLane with the Entry alpha
test) and replaced the walk with a native traversal that runs no guest code.

They are now found on the IR, before resource tracking, next to the any hit
walks: the walk is the outermost loop around the TLAS node test (the guest's
two backward branches make two nested loops), its BLAS walk the loop's other
intersection, the template the machine code of the BLAS walk. Before the walk
the host traverses and alpha tests (RayQueryAlpha with the Entry layout, the
V#s of the template's first two constant buffers); the walk then takes the
shortest way to its exit (its branch conditions on that way fixed when a lane
traces natively), and the values the code after it reads of an accepted hit
(the primitive word, the index after the hit's leaf list entry and the
instance record address, found by their sources in the walk) take the host's
hit when it is nearer than the walk's t max. The RayQueryAlpha and
RayQueryInit operations are those of the patch (same arguments).

The layout derivation also takes the one bit instance mask test of this
version (BitFieldUExtract(flags, 10, 1) == 1) and its BLAS node count, the
64-bit count at +80 less one: the host now reads the BLAS sizes there, as the
guest does, instead of at +88. In the house of a saved game, the image with
native ray tracing differs from the guest's own traversal by 1.6 (mean pixel
difference; 12.2 before).

The ClosestLane walks that load the leaf list entry into another pair, the
Entry alpha test and its RT_ALPHA/RT_INIT variants leave the decoded patch.

Also: trace Marvel's Wolverine's closest hit walks on the IR.

Marvel's Wolverine's cs 1a04c58a9fbc2052 (wave32, sce::Psr version 10) has
two BVH walks: a closest hit walk whose TLAS node tests run for the lanes of a
packet, with a per lane BLAS walk that runs the game's own leaf code, and the
any hit walk with lane masks, already traced on the IR. The decoded patch
traced the first one (ClosestLane) by copying the instance setup and the leaf
code into a native loop next to the game's.

It is now found on the IR with Resident Evil Village's walks, whose shape it
shares (MatchPacketWalk: the two nested loops around the TLAS node test, the
way to the exit, the BLAS walk, the layout and the TLAS source), and runs the
game's loop itself, without copies: every triangle is a candidate of the
game's leaf code, which keeps the nearest hit (no lane leaves the walk).
Before the walk the queries start and take their first instance; each round
of the outer loop processes the smallest instance a lane has a candidate leaf
of (its node is that instance, its packet the lanes with a leaf of it, taken
before the inner loop), each lane's BLAS walk runs once from its own leaf as
the any hit walks do, and at the end of the round (the inner loop's merge,
before the pop of the packet's stack) the next instance continues the walk,
or the walk leaves when there is none. The instance setup runs for every
round instead of being reused for the next leaves of the same instance.

A program's walks now all trace natively, with one TLAS source: the any hit
walk's ray mask (0x30000000) moves to the closest hit walk's lower shift of
the same record dword (0x68000000), as the decoded patch did; an instance
mask whose bits are not contiguous is accepted. In game both walks of the
program are traced on the IR (sites=2) and the walks of the other forms
translate to the same SPIR-V as before.

The ClosestLane sites leave the decoded patch: ClosestLaneWalk,
ClosestLaneHit, the leaf list fields, the TLAS header read from a V# (only
those sites had it) and the lane leaf variants of RT_SELECT, RT_LEAF and
RT_INIT.

Also: trace GTA V's opaque closest hit walks on the IR.

GTA V's short rays (cs 84ed00053b3771da on 01.005, 71445d30/651da332 on
01.011) walk the TLAS with a packet stack and each lane walks the BLAS of
the instance on its own; the leaf code keeps the nearest triangle (every
one opaque, both facings) and the code after the walk reads the hit's
primitive word, triangle node, barycentrics and instance record address.
The decoded patch traced them (ClosestOpaque sites with HitMoves); this
moves them to the IR pass, next to Resident Evil Village's walks.

MatchClosestOpaqueWalk takes a packet walk with a per lane BLAS walk
without texture reads (no alpha test) and finds the values the code after
the walk reads of an accepted hit: those whose sources, through the leaf
code's write under its accept condition (the condition of its write of a
barycentric), are of one kind: the instance record address, the leaf list
entry's words, or a component of the triangle test times the reciprocal of
its denominator (distance and barycentrics). Other sources of the same
registers (the walk reuses them on other paths) do not count. The walk is
rewritten as Resident Evil Village's, without the alpha test: every
triangle opaque, the walk takes the shortest way to its exit and the
values take the host's hit when nearer than the walk's t max.

The walk need not test the instance mask (84ed00053b3771da does not: every
instance counts, as the patch took it), and its BVH node count rule is the
one the patch derived from the TLAS's T#, so that the program shares the
layout of the game's other programs that trace the same TLAS. The decoded
patch leaves these sites to the IR; the ones with an alpha test (GTA V's
reflections) and the wave-wide walks (ASTRO BOT) stay sites.

Also: trace ASTRO BOT's wave-wide closest hit walks on the IR.

ASTRO BOT (cs bdd0bb9bd8852dd4) and ASTRO's PLAYROOM (the 2020 template:
5abb94205ac37db3, 038b50296f0de118 and 15 more, wave32 and wave64) walk
the TLAS with a packet stack and the BLAS of each instance with the whole
wave: scalar box tests, then a triangle test of each entry of the leaf's
list (node and primitive word). The leaf code keeps the nearest hit with
lane masks (V_CNDMASK of t and the word, or moves under S_AND_SAVEEXEC)
and takes a triangle only when it faces the ray or the instance's flags
or the program's cull switch let it pass. The decoded patch traced them
(ClosestSelectHit); this moves them to the IR pass, next to GTA V's per
lane walks.

MatchPacketWalk takes a walk with two other BVH tests sharing a T# (the
box and triangle tests of the wave's BLAS walk) and finds the BLAS loop
and its root in the TLAS loop. The layout also covers what these programs
need: the inline instance records (node type 7 at the header's +0x80, root
37), masks wider than 8 bits (an unsigned compare against 2^k - 1) and
PLAYROOM's 160-byte record stride; the type tests can hide in a lane mask
or a logical and.

MatchClosestWaveWalk finds the leaf's accept condition (the select that
keeps t) and reads its truth table over the hit, the far test, the facing
bit of the triangle test against a bit of the instance flags, the
both-facings flag and the cull switch: the facing rule goes to the layout
(flags dword and shift, flip) and the switch to the ray query's cull
argument, so the host only culls back facing triangles where the walk
did. The values the code after the walk reads (t, the primitive word, the
node, the instance record) are classified by their sources through the
lane-masked selects. The walk is rewritten as GTA V's.

The reduced programs of these walks in the tests left the patch with
ClosestSelectHit: the IR pass cannot trace them (nothing after the walk
reads the hit), so their tests go; the native statistics test compiles
Gran Turismo 7's program instead.

Also: trace GTA V's alpha tested closest hit walks on the IR.

GTA V's reflections (cs 6aeb221de7ff018e and 85616b0a1db9efd4 on 01.011,
77826b07f891b9f5 on 01.005) walk the TLAS as its short rays do (a packet
stack, each lane walks the BLAS of the instance on its own, the leaf code
keeps the nearest triangle), but the leaf code alpha tests the triangles
not marked opaque: the W channel of T# M2 >> 4 of a bindless table at the
triangle's texture coordinates against a reference, at level
min(M2 & 15, log2(2 * (spread * t + lod)) + offset); M0..M2 are the
material table's elements m * 3 + k for the geometry entry of the
triangle's BLAS plus a field of the instance record, and the indices and
vertices are read through V#s M1 >> 8 and M0 >> 8 of the buffer table.
The hit's moves then run where the flag is set (1 for opaque triangles).
The decoded patch traced them (ClosestOpaque sites with ClosestAlphaHit and
DeriveLaneAlphaTest); this moves them to the IR pass.

DeriveLaneAlpha finds the same test in the BLAS walk's values: the one
sample and its comparison, the flag the comparison sets, the material
loads (through the T#'s waterfall key), the geometry entry (the BLAS of
the triangle test's descriptor, or the record dwords it is made of on
01.005, and the record the walk takes the BLAS from), the index loads
(the waterfall key M1 >> 8, the hit's primitive word), the six vertex
loads at the base of element M0 >> 8, and the level (the hit's distance).
MatchClosestOpaqueWalk takes a BLAS walk with that test, and its accept
condition is that of the hit's moves: the nearer test and a flag whose phi
has the alpha test's flag and the constant 1. The leaf code's distance and
barycentrics are also taken as the written values of its lane masked
writes (WrittenHitDistance: HitDistance's search through phis stops at 64
values, fewer than this leaf code has). The walk is rewritten as the short
rays' are, with RayQueryAlpha (Lane layout, the arguments the patch passed)
before RayQueryInit, which takes the opacity from the geometry.

The reflections' ray comes from before the walk and the packet's lanes do
not write it (only its inverse direction): MatchPacketWalk takes the lanes
of those writes then. The patch leaves these walks to the IR, and
ClosestAlphaHit goes; DeriveLaneAlphaTest stays for the PacketLane sites.

Also: trace GTA V's per lane any hit BVH walks on the IR.

GTA V's Performance RT (cs 48d704640ab9fb40 in 01.011, 30c93330da43fd54 in
01.005) walks the TLAS for the whole wave and each lane's BLAS on its own,
with leaf code that takes any hit of the triangle test that faces the ray,
is not farther than the t max and passes the alpha test of its material.
The decoder patch found this walk in the guest code (DerivePacketLane) and
replaced it with RT_INIT and RT_ALPHA; the IR traversal pass did not know
it, so it was the last shape of these programs left to the patch.

The pass now matches it on the packet walk (MatchPacketLaneWalk): the
opacity of the instance flags, every instance opaque where a value from
before the walk says so; the facing of the instance flags, flipped where a
wave-wide condition holds; the alpha test (DeriveLaneAlpha, which now also
takes a reference threshold * (M0 bit 0 ? factor : 1) and the level the
leaf code takes on the way of a wave-wide condition, and leaves out the
loads of the other way); and the instance mask when the leaf code ands it
with a value instead of a constant. It is rewritten as the other packet
walks, with RayQueryInit without leaf code and its flip and allow
arguments, and every hit the host finds is the walk's hit.

The sources, the layout and the arguments of the alpha test and of the
init are the ones the patch produced. The patch loses PacketLane:
DerivePacketLane, DeriveLaneAlphaTest and their helpers, the lane alpha
layout and the RT_INIT dmask 16 go away.

Also: trace GTA V's wave-wide any hit BVH walks with the alpha test on the IR.

GTA V's Fidelity mode (cs 0b41af19bddf132c in 01.011, a31ec6a25be5e017 in
01.005) walks the TLAS for the whole wave and then the BLAS of each
candidate instance for the whole wave too, with the BLAS node on a stack
kept in a lane (ReadLane/WriteLane) instead of a phi. Its leaf code takes
any hit of the triangle test that faces the ray, is not farther than the
t max and is opaque or passes the alpha test of its material; the alpha
test reads the material, the T#, the indices and the vertices with scalar
loads, so every value of it is wave-wide. The decoder patch found this
walk in the guest code (DeriveAlphaTest on the packet sites) and replaced
it with RT_INIT and RT_ALPHA; the IR traversal pass did not know it, so it
was the last user of the patch's alpha test.

The pass now matches it on the packet walk (MatchPacketWaveWalk): the root
of the wave BLAS from the lane stack when its header has no node phi; the
opacity of the instance flags (DeriveLeafOpacity, taken out of
MatchPacketLaneWalk, which now also takes an opaque bit tested with an
equality); the flag that leads to the alpha block, a select chain of
constants that has to give the same table as that opacity; and the alpha
test (DeriveLaneAlpha with scalar loads: the material element at
(m * 3) << 2 plus an immediate, the T#, index and vertex V#s read from the
user data inside the walk, which are loaded again before it, and the
reference threshold * factor when the factor is the same for every lane).
It is rewritten as the per lane any hit walks, with RayQueryAlpha in its
scalar variant, and every hit the host finds is the walk's hit.

The sources, the layout and the arguments of the alpha test and of the
init are the ones the patch produced. The patch loses its alpha test:
RT_ALPHA, DeriveAlphaTest and its helpers, the alpha layout and the alpha
off register of the closest hit sites go away; a packet site whose leaf
code samples an image is left to the IR.

Also: trace GTA V's wave-wide any hit BVH walks without the alpha test on the IR.

GTA V's Fidelity mode (cs 2f34bc2dfe6b04a3 in 01.011, c7795cb2906bd593 in
01.005) has the same wave-wide TLAS and BLAS walks as its alpha tested
ones, with leaf code the game compiled without the alpha test: it takes
any hit of the triangle test that faces the ray and is not farther than
the t max where the lane's alpha test is off, or where the triangle is
opaque and its instance is not alpha tested. The decoder patch took these
walks as Packet sites, ran the guest's leaf code for every candidate the
host found and resolved the hits per key (RT_SELECT, RT_LEAF, RT_RESOLVE);
they were the last packet walks left to the patch.

The pass now matches them on the packet walk (MatchPacketWaveWalk without
an alpha test): the accept condition of the lane masked write of the
distance, whose truth table over the off, opaque and alpha tested atoms
(DeriveLeafOpacity, which now also takes off as x == 0) has to be that
opacity, with the facing of the instance flags (LeafFacing, which may now
read conditions that are 0/1 values compared with 0, a condition from
before the walk as one atom, and the values a Select by the lanes the
BLAS walk starts from gives them; the lanes that cull are a per lane
condition in 01.005). It is rewritten as the other any hit walks, with
RayQueryInit's new OpaqueOnly variant: the triangles that are not opaque
are no hit (gl_RayFlagsCullNoOpaqueEXT) where the alpha test is not off,
and every hit the host finds is the walk's hit.

The sources and the layout are the ones the patch produced. The patch
loses its Packet sites: every packet walk is the IR's, DerivePacket and
the helpers only it used, the reads of the hit's instance record after a
packet walk in the BVH reach and the Packet check of CheckSite go away.

Also: recognize the native ray tracing walks with the ray query pass's recognizers.

The ray query pass (TraceTraversalsWithRayQueries) and the native ray tracing forms
(TraceNativeTraversals) recognized the same walks each on their own: the pass's nested walk
(MatchNested) takes GTA V 01.005's short ray and reflection walks (cs 84ed00053b3771da,
77826b07f891b9f5) and its walk over a stack the wave shares (MatchWalk) GTA V 01.005's wave-wide
walk (cs c7795cb2906bd593), which the forms ClosestOpaque and PacketWave also took with their own
BLAS walk recognizers (MatchBlasWalk, MatchWaveBlas).

The pass's recognizers now also run before resource tracking, where the native forms run (they
give resource tracking the TLAS source and the code that stays in the BVH): there the TLAS words
are the walk's values from before its loops instead of flattened SRT slots (TlasWord). Before
resource tracking they take GTA V 01.011's walks too, whose instance records hold the BLAS address
in units of 8 bytes at +48 (cs 6aeb221de7ff018e, 85616b0a1db9efd4, 2f34bc2dfe6b04a3,
0b41af19bddf132c: BlasWords), and the alpha tested wave-wide walk of 01.005, which reads the
instance flags again past the branch into the BLAS loop (cs a31ec6a25be5e017). What only the pass's
rewrite needs (the instance reads it swaps, NestedReads; the per-candidate code it copies,
WalkCopies) is split off the recognizers, so after resource tracking they take what they took
before. So is what its rewrite of nested walks needs of the loop: the extent (the committed t), which
any hit walks do not have (GTA V's Performance RT walks, cs 48d704640ab9fb40, 30c93330da43fd54;
Marvel's Wolverine's lane mask walks, cs b790bfb6f776e13a), and a world ray from before the
outermost loop around the TLAS walk (Wolverine's cs 1a04c58a9fbc2052 computes its rays in a loop
around both of its walks): MatchNested takes those walks, and NestedReads leaves them.

Every native form takes its per lane BLAS walk from MatchNested: Entry (Resident Evil Village),
ClosestOpaque, PacketLane and PacketWave (GTA V), ClosestLane and the lane mask walks (Wolverine);
MatchBlasWalk is gone. PacketWave takes its wave-wide BLAS walk from MatchWalk. The wave-wide BLAS
walk of ClosestWave (ASTRO BOT, ASTRO's PLAYROOM, cs bdd0bb9bd8852dd4) keeps its own recognizer
(MatchWaveBlas): those walks keep the closest hit, while MatchWalk takes walks whose first accepted
hit leaves, and they walk the BLAS in two nested loops and leave the TLAS loop by breaks besides its
latch. The ray query pass no longer leaves whole programs with native sites alone: the
intersections of the walks of native sites take BvhIntersectNative, and the pass leaves those
walks.

The SPIR-V of the native programs (86 of GTA V, ASTRO BOT, ASTRO's PLAYROOM, Resident Evil Village
and Marvel's Wolverine, and Wolverine's cs 1a04c58a9fbc2052) is unchanged, with and without the ray
query pass.

Also: trace Gran Turismo 7's closest hit BVH walks with any hit functions on the IR.

Gran Turismo 7 (cs 05e0cbbc, 05e12ebc, 05e3f1bc; the program of
TestRayTracingClosestLeafCalls) walks the TLAS with a packet stack and
the BLAS of each instance with the whole wave, like ASTRO BOT, but its
leaf code calls the game's any hit function (an inlined call of the
expanded program) for the triangles that are not opaque and keeps the
nearest hit it accepts in registers. The decoded patch traced it
(ClosestLeafWalk, the RT_SETUP/RT_REUSE/RT_LEAF/RT_EXIT_CHECK pseudo
instructions); this moves it to the IR pass and drops that part of the
patch.

MatchWaveBlas took the leaf list's triangle test for the box test (both
start at a phi of their loop): the triangle test now has to be inside
the box test's loop. LeafFacing may meet one more term of the accept
condition that the pass does not model (what the any hit function
returns): the facing rule is read as before with that term as one more
conjunct, and the walk becomes ClosestLeaf, whose guest leaf code
decides the triangles that are not opaque.

The host traverses with the opacity of the geometry and of the instance
flags and confirms the opaque triangles. The guest walk then runs once
per candidate the queries leave, the wave's smallest (instance, leaf)
key with the lanes that have it: its TLAS node is the key's instance and
its lanes those with the key, its BLAS walk starts at the key's leaf and
leaves the leaf list after that entry, and the leaf code keeps the
nearest hit (every lane goes on searching). At the round's end, before
the pop, the next key or the exit. After the walk the values read of
the hit are the host's where its opaque hit is nearer than the distance
the leaf code kept, and the walk's lanes are again those that started
it. Same TLAS source, record layout and query arguments as the patch.

Also: drop the native ray tracing patch of decoded programs.

Every BVH walk the native ray tracing patch recognized on the decoded program (RayTracingPatch: the
sce::Psr traversal loops of GTA V, ASTRO BOT, Astro's Playroom, Resident Evil Village, Marvel's
Wolverine and Gran Turismo 7) now traces natively on the IR (IR::TraceNativeTraversals), with the
ray query pass's recognizers for its BLAS walk: the patch derives no site in any of the 97 programs
with a BVH walk we have of those games.

Remove it: RayTracingPatch.{h,cpp}, its pseudo instructions (RT_INIT, RT_SELECT, RT_RESOLVE,
RT_COMMIT, RT_EXIT) and their translation, the guest pc of moved code that S_GETPC_B64 returned,
the node tests the patch left to the guest (Program::ray_tracing_outside, and the sites the IR
walks had to share), the patch of expanded programs, and the TLAS source it derived for programs
that walk their BVH themselves (the IR gives it, as it already did for the walks it recognizes).
The instance record layout (RayTracingLayout) and the alpha test fields move to ir/RayQuery.h;
the RayQueryFlag operation and the Enter, CullResolve and SetupBegin marks, which only the patch
emitted, go too. The "[RT]" summaries count the programs that trace natively and those whose walk
no form recognizes.

The SPIR-V of the reference programs (GTA V 01.005 and 01.011, ASTRO BOT, Astro's Playroom,
Resident Evil Village and Wolverine, cs 1a04c58a9fbc2052 expanded, and Gran Turismo 7's expanded
closest hit walk) is the same, byte for byte, with native ray tracing, with the ray query pass and
with both.

Also: drop the native ray tracing state only the decoded patch set.

With the patch of decoded programs gone, no lane of a native traversal enters guest leaf code or
runs an instance setup through the RayQuery* operations: the IR walks resolve every round with
RayQueryMark Resolve for all the lanes and read no reuse flag. The state behind those (the entered,
terminated and prepared bits, the instance whose setup ran last and the reuse flag RayQueryNext
computed with a subgroup reduction each round) only took constant values.

Remove it, and the argument of RayQueryMark: Resolve drops the selected key of the lanes that have
it, RayQueryNext's fourth component is 0 and RayQueryResult reports the hit the hardware found.
The SPIR-V of the native traversals loses that dead code; that of the other programs is the same.
In Fidelity mode GTA V (PPSA04263) builds the four TLASes of its ray
tracing passes every frame in its BVH compute queue: 18 shaders, each
dispatched once per TLAS (9df701ab41f8ed18 ... 54ec6ec2689fd4c4),
several of which wait for the GPU. 9df701ab41f8ed18 alone kept the
execution thread waiting about 13 ms per frame: it reads the BLAS
headers the refits just wrote on the GPU.

With native ray tracing, the stage is replaced by one native build per
TLAS (hle_tlas.comp): the command processor drops the stage's dispatches
(from the first instance list to the last build, per queue; other
shaders keep running), keeps the instance list of each build (the V# at
s[6:9] of 9df701ab41f8ed18, 96-byte records the game's CPU writes: BLAS
address, mask and flags, user data, object-to-world matrix) and the TLAS
address (s[0:1] of 54ec6ec2689fd4c4), and after the last one a host
command records the builds. Each build (one workgroup, up to 4096
instances, an empty list making an empty TLAS) writes the game's format
into guest memory: the header, a 4-wide box32 tree over the instances
sorted by Morton code (root at header + 256) and the 128-byte instance
records (world-to-object and object-to-world 3x4, BLAS address with the
flags the game derives from the instance and the BLAS header, mask, user
data). The header depends only on the instance count, so the host also
writes it to the backing: the RT shaders' resource tables read it
without a readback.

Checked in game against the game's own builds run side by side, standing
and driving (80k instances): the instance records are the same
(world-to-object within 2e-5) and every instance box holds the game's
leaf box but for one instance in a few frames, by 0.3 mm (a few ulps of
margin cover the different rounding of the transformed boxes). Shadows
and reflections match; no hang in 300 s runs standing and driving
through the city.

[HACK] Two parts are cuts, and each reports a [HACK] notice when it
happens: a list of more than 4096 instances builds a TLAS of its first
4096 (one workgroup builds it), and a build without a list or a TLAS
address, or with records shorter than 96 bytes, is skipped, so the TLAS
keeps what it held (the game's own build was dropped).

Also: let the game build the TLASes whose lists the native build cannot read.

With --native-raytracing the command processor drops the dispatches of
the game's TLAS builds (Psr_Gpu_TopLevelBvh_Build) and hle_tlas.comp
builds each TLAS in one workgroup, from instance records of 96 bytes, up
to 4096 of them. The list was checked only after the build's dispatches
had been dropped: a longer list made a TLAS of its first 4096 instances,
and one with shorter records or without an address made none, the TLAS
keeping what it held ([HACK] notices). GTA V's lists fit, so it never got
there.

The list (address, stride and count at s[6:8] of
psr_morton_compute_bounding_box_for_instances) is known at the build's
first dispatch: a list the native build cannot read now leaves the
game's own build running, from that dispatch to its last pass
(psr_collapse_to_qbvh_simple_top). Still a [HACK] notice: a build
without a TLAS address, and a list the native build cannot read that
comes while other builds of the stage are already native (their
dispatches were dropped).

Also: replace the TLAS builds of GTA V 01.005.

GTA V 01.005 (PPSA04264) links an older build of sce::Psr (generation Base252, build J02232310)
whose shaders the emulator recognizes by their code. With native ray tracing only its BLAS refits
were replaced: its three TLAS builds of every frame ran as the game dispatches them, about 25
dispatches per TLAS (sort, rotations, scans and compaction) that wait for the GPU, only for the
native traversal to walk the result.

Its top level stage runs the same passes as the newer build with fewer of them (no indirect
arguments, valid instance indices or vec2u scans), and its last pass, collapse_to_qbvh_simple,
also ends its BLAS builds. The TLAS has the same box32 nodes from header + 256, but another
header (version word 0xbbe6e938, 0x24 at +24, the records at header + [header + 40], the count
plus 4 at +80 and the count at +116) and another instance record: the BLAS address as is at +0,
the world-to-object 3x4 by columns at +8, the root at +56, the input's flags word with the flags
in its low byte at +60 and the object-to-world 3x4 by columns at +64.

The top level passes of Base252 are now listed, its list is taken from the V# at s[4:7] (count at
s6) of morton_compute_bounding_box_for_instances, and hle_tlas.comp writes either format. A pass
of the library the replacement does not know inside the stage still stops the replacement.

Also: recognize GTA V's sce::Psr BVH shaders by the name they register.

The native TLAS builds and BLAS refits replace dispatches of sce::Psr,
Sony's ray tracing BVH library that GTA V links statically, which they
recognized by the hash of the shader code: 18 hashes of the top level
build and 4 of the triangle fan refit of GTA V. Those hashes only hold
for GTA V's copy of the library: the shaders carry compiler metadata, so
no Psr shader of Astro Bot or Wolverine has the same bytes, although
Astro Bot's library is the same generation (its TLAS build and fan refit
shaders have identical instructions or the same user data layout).

The library registers every shader with the driver under its name:
sceAgcDriverRegisterOwner("sce::Psr") and, when it succeeds,
sceAgcDriverRegisterResource for each of its 460 compute shaders (code
address, size and name such as psr_qbvh_fan_refit_async). GTA V's
Agc::Toolkit does the same for its own shaders. Those driver functions
always failed, so the games skipped the registration. Owners and
resources are now registered, with handles, and can be unregistered one
by one or with their owner. The name of each resource is kept by address:
ShaderRegisteredName() returns the name of the shader whose code starts
at an address and ShaderNameRegistered() whether a name was registered.
The games only check that the calls succeed.

The command processor now looks the shader of a dispatch up by name
(psrShaders.h): psr_morton_compute_bounding_box_for_instances opens the
TLAS window and psr_collapse_to_qbvh_simple_top closes each build,
psr_qbvh_fan_refit_copy_dispatch_args opens the refit window and
psr_qbvh_refit_bottom_level closes each refit. The user data the HLE
reads (instance list V# and count, TLAS address, BLAS address, geometry
table, geometry index) has the layout of the generation of 460 shaders
that GTA V and Astro Bot link; the generation is told by the names the
library registered (shaders the next generation, Wolverine's, removed or
added), and a library of another generation keeps every dispatch
emulated. Two pairs of names have byte-identical code
(psr_morton_initialize_indirect_args_top and its _trinity copy, the
_uint32 and _float descriptor initializations of the scan), which the
hashes could not tell apart: both names belong to the stage.

Also: recognize the shaders of sce::Psr by their code when the game does not name them.

The BVH builds and refits of sce::Psr are replaced with native ray tracing only when the game
registers the library's shaders under their psr_ names (sceAgcDriverRegisterResource), as GTA V
01.011 does. Other titles do not: GTA V 01.005 registers them without the prefix and ASTRO BOT
registers none, so their passes were never recognized.

Without those names, a shader is now recognized by its code. Its fingerprint is the sorted
multiset of its instructions up to s_endpgm, each reduced to its opcode, operand kinds, constants
(not the ones added to the program counter), modifiers and memory offsets and formats; registers,
branch targets, order and waits are left out. It is looked up in a table of the fingerprints of
every shader of the builds of the library the emulator knows (generated from the shader tables
of the games' executables), for the build whose compiler revision is in the footer of the
binary: the same code can be another generation's pass (Gran Turismo 7's build shares 91
fingerprints with GTA V's), and a build that is known but not measured is logged and emulated
(ASTRO BOT's build of Base460: its 460 shaders are in the table, with the same passes, but not
enabled). Only the shaders of an accepted build are fingerprinted, once per address. An opcode
enters the fingerprint as its decoder enum value when the table was generated: an opcode the
decoder learned later (upstream's V_CMP_U_F16, inserted in the middle of the enum) counts as the
unknown instruction it was then, and the opcodes after it keep their earlier values.

By their code, the 460 shaders of GTA V 01.010/01.011's build get the same passes as by their
names except 11 copies under a _trinity name that have the code of a kBase pass (GTA V
dispatches none of them).

Also: stop replacing sce::Psr builds the native build does not know.

With native ray tracing, the command processor drops the top level
builds and the fan refits of the sce::Psr library (generation Base460:
GTA V 01.010/01.011, ASTRO BOT, Nightreign) and replaces them with its
own. It recognises them only by the first and last shader of their
windows, and drops every listed shader in between. A game that runs
another pass of the library inside a window (a build flow GTA V does
not use: rebraiding, refittable TLASes, kTrinity BVHs of the PS5
Pro...) would have half of its build dropped and the rest emulated, and
its TLAS would be garbage; a window that never sees its last shader
would drop the scans and sorts of every later build.

GTA V 01.011 in Fidelity runs nothing else of the library inside its
12 TLAS windows (4 builds each) and 12 refit windows of a 30 s run.
Nightreign builds a TLAS of one instance on its title screen, whose
build takes psr_morton_init_one_instance_root_node (the root node, in
the scratch memory) instead of the sort and the hierarchy passes: it is
now one of the stage's shaders. So:
- the first TLAS window of each queue runs as the game dispatches it,
  and only shows which passes it runs;
- another psr_ shader inside a TLAS or refit window, or any kTrinity
  shader (the _trinity copy of initialize_indirect_args_top is no
  longer taken for the kBase one), turns the replacement off for the
  rest of the session, with a line in the log: the window in progress
  is completed, later builds and refits are emulated as they are and
  the BLAS builds are no longer followed (the host finds those BLASes
  through the top level walk);
- psr_morton_capture_memory, the first pass of every build, closes a
  window still open: the builds and refits that ended are replaced.

Also: cache the guest memory HLE builds read through device addresses.

The native builds that replace the TLAS builds and BLAS refits of sce::Psr read their inputs
(the instance list the game's CPU writes, the BLASes, the refit's vertex buffers) through the BDA
page table, and PrepareBda() uploads nothing more before them: the command processor makes each
input reach a cached buffer first. It did so with ObtainBuffer(), which answers a read of up to
16 KiB of CPU-written memory from the stream buffer, without creating or updating the cached
buffer the page table reaches. Draws and dispatches bind the buffer ObtainBuffer() returns and
reach other memory through device addresses only after FindBuffers() and the BDA
synchronization, so only these builds read zeros (no cached buffer) or older data there: a TLAS
from a list under 16 KiB (GTA V 01.005 builds TLASes of 8 and 14 instances every frame) has every
instance inactive for the native traversal, and a small vertex buffer the CPU writes (ASTRO BOT
has BLASes the CPU writes) refits to stale or collapsed triangles.

BufferCache::PrepareDeviceAddressRead() caches a range in a buffer the page table reaches and
uploads the CPU writes it does not hold, as ObtainBuffer() does for larger reads. The HLE builds
take every input they read through it: the instance list, the header and root node of each BLAS
an instance references (its flags and bounds) unless the GPU wrote them, the vertex buffers and
the header of each refit BLAS.
In Fidelity mode GTA V (PPSA04263) refits the BLASes of its animated
geometry (people, vehicles, vegetation; about 170 BLASes and 850
geometries per frame) in its BVH compute queue, with four shaders per
BLAS: ddff3c6d72c4e994 (indirect arguments from the BLAS header),
8972763dd85dcf74 once per geometry (the five vertices of each triangle
node, loaded with the geometry's vertex buffer V# and transformed by its
object matrix), 8de8b6519a1fefe2 (more arguments) and b2966d3472aac545
(the box32 boxes, bottom up with atomic counters). About 1300 dispatches
that cost the execution thread some 13 ms per frame.

With native ray tracing they are replaced by hle_blas_refit.comp: the
command processor drops the dispatches, keeps each BLAS (s[0:1] of
ddff3c6d72c4e994) and each geometry (table V# at s[0:3], BLAS at s[4:5],
geometry index s8 of 8972763dd85dcf74), and after the last box pass a
host command records two dispatches: one workgroup per geometry rewrites
the vertices of its triangle nodes from the vertex buffer (formats of 8,
16 and 32-bit components) and matrix of the geometry entry the game's
CPU wrote, then one workgroup per BLAS lists its box nodes level by
level from the root and recomputes the child boxes from the deepest
level up (degenerate triangles skipped and non-finite boxes made empty,
as the game does). The BLAS nodes become GPU written; their headers
stay.

Checked in game against the game's own refits run side by side: no
mismatch in 800k triangle nodes and 900k boxes per sample over a minute;
images match, no hang in 300 s runs standing and driving.
With both stages replaced (this and the native TLAS builds) the BVH
queue goes from about 3650 to 900 dispatches per frame. Fidelity mode,
standing in the city, release builds, three interleaved runs: 12.0 ->
22.6 fps; Performance mode unchanged (59.2 / 58.6 fps).

The host BLAS of every guest BLAS that GTA V refits (its animated
vehicles and pedestrians, ~130 per frame in Fidelity mode) used to be
rebuilt before each frame's ray tracing: the BLAS walk traversed the
guest BVH again to write its triangles and the build preferred fast
tracing, ~3.7 ms per frame of GPU time (2.2 ms of it the walks, one
workgroup per BLAS level by level). A BLAS the HLE refit pass refit
since its last host build, with no other refit in between, keeps its
triangles and their order: the BLAS walk now rewrites its vertices
through the entry table of the slot in one parallel pass (walked again
every 30 builds). Slots the guest changed lately are built with a fast
build (they are rebuilt every frame anyway) and built once more for
tracing when they stop changing. GPU time of the BLAS builds: 3.7 -> 2.1
ms per frame, the ray traced shadows (fa8b1616) take the same time.

[HACK] One part is a cut and reports a [HACK] notice when it happens: a
refit pass whose jobs do not fit in the 4 MiB job buffer is skipped, so
its BLASes keep their last shape (the game's own refit dispatches were
dropped).

Also: refit GTA V's BLASes in batches when their jobs do not fit.

With --native-raytracing the command processor drops the dispatches of
the game's BLAS refits (Psr_Gpu_BottomLevelBvh_FanRefit) and
NativeRayTracing::RecordHleRefit() refits the BLASes, with one job per
geometry (96 bytes) and per BLAS (16 bytes) in a 4 MiB buffer. A refit
with more jobs than that returned without refitting anything, after the
game's dispatches had been dropped: those BLASes kept their last shape
(a [HACK] notice). GTA V refits about 170 BLASes of 850 geometries a
frame (80 KB of jobs), so it never got there, but nothing bounds them.

A refit whose jobs do not fit now runs in passes over the buffer: the
vertices of the geometries, as many as it holds at a time, then the
boxes of the BLASes the same way. A refit that fits records the same
commands as before.

Also: shorten the native RT passes that read GTA V's BVHs.

The host passes that read GTA V's BVHs (leaf walks, gathers of the
refit BLASes and the HLE refit of the BLASes the game animates) are
chains of dependent reads, and they looked up the page table for every
32-bit word: nine times per triangle, seven times per box node and six
times per stored box. A 64-byte node of a BVH never crosses a caching
page, so the passes now translate a node once and read or write its
words directly, and read a leaf entry with one 8-byte load.

The box refit computes the four child boxes of a node before storing
any of them, so the reads of the four children no longer wait for the
stores of the previous one, and runs 512 invocations per BLAS: its
levels are walked one after another, and the widest ones of a vehicle
or a ped had more nodes than 256 invocations take at once. A gather
takes a workgroup per 1024 triangles of the largest job instead of one
per job.

Also: replace the BLAS refits of GTA V 01.005.

GTA V 01.005 (PPSA04264) ships an older build of sce::Psr (J02232310, 252 shaders, generation
Base252 here). With native ray tracing its BLAS refits were emulated every frame.

Its refits run the same four passes as in Base460 (qbvh_fan_refit_copy_dispatch_args, then
qbvh_fan_refit_async per geometry, qbvh_fan_refit_recover_aabbs and qbvh_refit_bottom_level) on
the same triangle and box nodes, but the async pass takes the geometry index in s6 (s8 in
Base460), and the BLAS header keeps the fields the refit reads at other offsets: the vertex
index table at 0x38, the first triangle node of each geometry at 0x48, the geometry count at
0x70, the triangle node count at 0x7c, the first triangle node at 0x80 and the node limit at
0x50.

The shaders of that build are recognized by their code and the refit replacement takes the
generation's user data, and hle_blas_refit.comp the header layout. Its BLAS builds (other user
data) and top level builds (another instance record, header and sequence of passes) are still
emulated, as the log says.

Also: give the host BLASes of GTA V's sce::Psr builds a slot in the same frame.

The host BLASes mirror the game's BLASes from their leaf lists, but a
BLAS the host had not seen yet was only found by the walk of a TLAS that
referenced it, counted on the GPU and read back: it got a slot and a
build one to three frames later, so objects that streamed in, spawned or
were rebuilt cast no shadow for those frames (the flickering of the
native shadows).

The command processor now follows sce::Psr's BLAS builds (by shader
name, user data of generation Base460): psr_morton_compute_code_for_mesh_*
runs once per geometry with the build's geometry table (120-byte
srt_geometry_config entries the game's CPU writes: kind, flags with bit
0 = opaque, vertex and index buffer V#s, the index buffer's record count
being the triangle count) and psr_collapse_to_qbvh_simple_bottom(_with_refit)
writes the BLAS (its address and primitive count). After that dispatch,
NativeRayTracing gets the BLAS with the triangle count and opacity of
each geometry and gives it a slot laid out by primitive, sized exactly,
built at the next preparation and found by the walks through a table of
the host's (after the walk's own), so no readback is involved. A build
whose triangles do not add up to its primitive count (split triangles)
or with other kinds of geometry is left to the walks.

A layout build walks the guest BLAS as before and places each list entry
at its geometry's first host primitive plus its triangle index: the
geometry comes from the header's per triangle node table (+40, the one
the game's own leaf code reads), the index from bits 0-29 of the
primitive word. That the word holds the triangle index of the geometry
was a hypothesis; every entry is checked (a geometry of the layout, an
index below its triangle count, the opacity of the geometry), positions
no entry names stay inactive, and a slot whose build does not match, or
whose memory holds another BLAS by then (another header or geometry
count), is given up and found by the walks. In GTA V's Fidelity save,
6 000 layout builds matched in every entry; the 12 given up held another
BLAS by the time they were built. The walk of a layout slot takes a queue
for as many leaves as the build has triangles, and a build gathered from
its entry table (no walk) takes no queue from the pool: before, every
gathered refit counted against the half of the pool the builds share, few
builds fitted in a preparation and the backlog left slots outdated.
Traced both through the host structures and through the game's own BVH (a
local verification pass, about 700 000 rays aimed at triangles of the host
instances in the Fidelity save), the closest hits differ in distance for
0.06% of the rays, against 0.34% without this change.

GTA V builds most of its BLASes in batches: every pass of
Psr_Gpu_BottomLevelBvh_Build runs for each BLAS of the batch before the
next pass, so the Morton code passes of up to twenty builds come before
their psr_collapse_to_qbvh_simple_bottom dispatches. A single build in
progress lost all but the last one: in Fidelity only about 70 of some
1500 builds in three minutes got a host BLAS in the same frame, and the
rest waited for a TLAS walk to find them and for its readback (several
frames without their shadows, a pop-in that looked like flickering when
driving). The builds in progress are kept by their scratch memory, which
the Morton pass has at s[4:5] and the collapse at s[2:3]. Builds with
split triangles are followed too: the BLAS walk places a triangle that
several leaves name at its one layout position, and checks every list
entry against the layout.

GTA V streams part of its static geometry as compressed sce::Psr BLASes
and decompresses them on the GPU (psr_decompress_*) right before a TLAS
references them. Their host BLASes waited for a TLAS walk to report them
and for that readback: in a three minute Fidelity session they were about
650 of the 960 BLASes the walks still had to find. The command processor
remembers the memory size of each psr_morton_capture_memory and tells
NativeRayTracing about every BLAS a psr_decompress_compute_fan_node_* pass
writes (s6, with the high address bits at s1). Its triangle counts are
only on the GPU, so the slot holds as many triangles of each opacity as
that memory can (more than 32 bytes per triangle; GTA V uses 54 or more)
and is built by walking the guest BLAS at the next preparation. Builds
always read back their triangle counts, and a slot with far more room
than its BLAS needs gets its exact size, the way a slot that is too small
grows. A decompression into the memory of a BLAS that had a slot drops
that slot's layout and refits.

Also: follow the BLAS builds of GTA V 01.005.

With native ray tracing, the BLASes GTA V 01.005 (PPSA04264, sce::Psr generation Base252) builds
with sce::Psr were only found by the walks of the TLASes that reference them: counted on the GPU,
read back and built one to three frames later, so objects that stream in or are rebuilt (the
pool BLASes of the characters, rebuilt with another geometry table every few frames) cast no
shadow for those frames. The builds of generation Base460 (01.010/01.011) were already followed.

Its BLAS builds run the same passes with almost the same user data: the geometry index of
morton_compute_code_for_mesh_* is in bits 18-31 of s6 (s7 in Base460), and builds without refit
data end with collapse_to_qbvh_simple, the last pass of the TLAS builds too (outside the TLAS
stage it ends a BLAS build), with the primitive count minus one in s14. The geometry tables have
the same 120-byte entries. Its BLAS header holds the fields the layout build reads at other
offsets (the geometry of each triangle node at +32, the geometry count at +112, the first
triangle node at +128) and version 6 at +252: the layout of a followed build carries its header
layout to rt_blas_walk.comp.

In the prologue's bank (Fidelity) the host then builds about 2.7 BLASes per frame from the
layouts of the builds it followed, with one layout mismatch in a whole run; the walks build only
the 85 BLASes that already existed when ray tracing started.

Also: keep the host BLASes of GTA V's refit BLASes up to date within the frame.

GTA V refits the BLASes of its peds and vehicles at the end of a frame
for the next one, and the host rebuilds them (gathered builds) at the
first preparation of the next frame, the one of the shadow TLAS. In
Fidelity that preparation built only a few of them, and the rest traced
the shape of an earlier frame: about 40 of 220 builds in a vehicle, and
after getting out a queue of 270 that built 4-8 per preparation, four
frames late, with some slots waiting for hundreds of frames (shadows that
do not follow the animation, a ped's shadow still sitting after getting
out, vehicle shadows that freeze).
- A gathered build did not update the signature of the slot's boxes, so
  the check of the same preparation saw the refit boxes as a change and
  made the slot dynamic: walked again before every use for 120
  preparations, about 200 false changes per preparation. A gather now
  marks the slot and the check of the same preparation takes the new box
  signature; later checks compare as before. A slot that does change is
  rebuilt before every preparation, not once a frame: the guest can
  change it between the ray tracing passes of a frame.
- A walk that did not fit in the pool stopped the queue, gathers included
  (they take no pool). It is now put back and the queue goes on; the first
  walk always goes, or a BLAS with a large walk would wait behind the
  gathers forever, and the gathers of the last refit go first. Queue
  entries that no longer need a build no longer count in the pool, the
  pool is twice as large and a preparation takes up to 512 builds.
- A slot that grew, or whose walk overflowed its queue, kept a leaf count
  of 0 (the largest queue) for good: builds now read back the leaves they
  walked.
In a city drive in Fidelity, preparations of the shadow TLAS that starved
went from 49% to 1%, and changes the checks reported from 95 to 0 per
preparation.

The builds of BLASes the guest refits allow updates, and a gathered build
updates the last build in place
(VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR) instead of building
~95 BLASes from scratch per frame in Fidelity mode (~2.5 ms of GPU); a
walk now and then (every MaxGathers gathers) builds them anew. A refit
BLAS whose boxes the verification finds changing outside the refit pass
(dynamic) was walked again and given a fast build before every
preparation: about ten refit BLASes were walked and built three times a
frame, once for each TLAS traced after the first (3.3 ms of GPU per frame
with the reflections traced natively). Those builds now gather the
vertices through the entry table, like the first build after a refit
pass, and update the last build in place: the guest only refits them, so
their triangles keep their order. An update keeps the flags of the build
it updates.
Astro Bot dispatches its RT passes with DISPATCH_INDIRECT (thread
dimensions read from memory), and only DispatchDirect() prepared the
host acceleration structures of a program that traces through a guest
TLAS: the patched programs found no context and fell back to their own
traversal, slower than the original with the native code inside (cs
45f8ddf6, 0.71 -> 2.06 ms per dispatch). The three dispatch paths now
share PrepareNativeRayTracing().

Eight of those programs also load the TLAS header address with a scalar
load from their user data pointer, which the recompiler turns into a
read of the flattened SRT (the host reads the user data on the CPU and
copies in the dwords the GPU wrote). Through the BDA page table the TLAS
walk read a cache buffer over that memory, synchronized only when
something binds it, or no buffer at all: zero, every time. The shader
info now holds the flattened SRT dwords the sites read the header from
(the ReadConst slots of RayQueryInit's header operands), and Prepare()
copies them from the dispatch's flattened SRT into the state the walk
starts from. The walk also leaves the context invalid when a box node or
an instance record is in memory the host has not cached, so the guest
traverses the TLAS itself that time and its own reads cache the memory.
Astro Bot dispatches most of its ray tracing passes in Sky Garden with a
null TLAS header address (8 of the 9 patched programs, ~10 dispatches a
frame; the guest skips its traversal for them). The patched programs
then take their guest traversal, but the host runs them much slower than
the originals: cs 45f8ddf6 took 3.6 ms instead of 0.7 ms per dispatch,
and Sky Garden ran at 21.2 fps instead of 23.4.

GetComputeProgram() now looks at the header address the patched program
reads from its flattened SRT (ShaderInfo::ray_query_header_slots) and,
when it is null, looks up (or compiles) the program without the native
ray tracing patch, under the software program key. The resolution ahead
of the execution thread leaves those dispatches to it.
Native ray tracing traces the ray tracing passes the shader recompiler
recognizes (GTA V's shadows and reflections in Fidelity mode, ASTRO BOT)
with the host GPU's ray queries and acceleration structures. It is still
experimental, so it now follows upstream's --native-rt, off by default
(--native-raytracing stays as an alias, for older settings and scripts),
and upstream's "Native ray tracing (experimental)" box in the launcher's
graphics settings, whose tooltip now says what it does and which reads the
setting the fork's own box saved (native_ray_tracing_enabled) while a
configuration has no native_rt yet.

Upstream's ray query traversals over its GPU BVH mirror (RayTracing) take
the same option: they trace the BVH loops the patch leaves to the shader.
In GTA V's Fidelity mode they trace none: the BVH loops that remain stay
emulated, as before.

Off, the device enables neither VK_KHR_acceleration_structure nor
VK_KHR_ray_query, NativeRayTracing stays disabled (no shader is patched or
keyed differently, no sce::Psr dispatch is replaced, no host BLAS, TLAS or
refit work is recorded) and the AGC resource registration calls answer as
before instead of keeping the names the sce::Psr recognition needs. Program
keys and the pipeline manifests are those of the build without native ray
tracing; on, patched programs keep their own keys.
Sonic X Shadow Generations (PPSA17597) starts in a launcher program that
LoadExecs the game it starts (/app0/SonicBlueBlur.elf). On Windows,
LoadExec starts a new emulator process and then quits, but the new process
reserved the guest memory (about 13 GB in PS5 Pro mode, committed up front)
while the old one still had its own: with less than twice that free in the
paging file, the game closed on "could not reserve ... MB for guest direct
memory" as it started.

LoadExec now gives the new process an inherited handle to itself
(KYTY_LOAD_EXEC_PARENT), and the new process waits for the old one to exit
before anything else (at most 30 s).
Days Gone (PPSA28180) loses the device on NVIDIA 2-5 minutes after boot,
before the main menu, since upstream b64e430b9 binds the HTile depth
target of every DEPTH_COMPRESS_DISABLE pass whose depth and stencil tests
are off. The game runs many such passes a frame (no pixel shader, over
whole targets from 256x256 to 6912x2304), none of them with a pending
HTile fast clear, and the driver reports "3D WIDTH ZT Violation" graphics
exceptions right before the TDR (nvlddmkm events 13, then 153). With the
binding 7 of 10 runs lost the device at 114-315 s; without it every run
lasted the whole 451 s test.

The host attachment is never compressed, so such a pass only has work to
do when its HTile has a pending fast clear, the case upstream's change is
for (PPSA32236 fast-clears HTile each frame, runs this pass, then samples
the depth as raw memory). Bind it only then. The render target memo stays
valid: a fast clear is set by a dispatch or a DMA, which ends the memo.
GTA San Andreas - The Definitive Edition closed when CJ left his house and got into the
Grove Street car, and sometimes while loading a save with cold caches: "shader info collection
failed: buffer ADD_TID is only valid for compute shaders" or "shader binding resolution failed
during SPIR-V emit: hash=0x6ec55245116a00b2 (or 0xc472a5c9a3283ecb) stage=1 resource=2 reason=buffer
descriptor has reserved dst_sel".

Both vertex programs take buffer 2's V# from user data slots 4-7 on only one side of a branch
whose condition the guest reads from memory that a draw or dispatch resolved just before
writes. The walk ahead of execution does not read such a load (the writer may not have run
yet), so it reaches both sides, and the slots hold leftovers of other draws there, such as
00000000 20379d00 c3800000 01d8c347 (ADD_TID) or 80000000 00000001 00000000 11811c53 (ADD_TID
and reserved dst_sel). That specialization was still queued for a worker to compile, as only
reads of GPU-written pages kept it from that, and the compile exited. The execution thread,
which reads the condition, never asks for it: it ran those draws with its own programs.

A resolution whose walk left a GPU-produced load unread now leaves the compile to the
execution thread, like one that read GPU-written bytes. The ADD_TID error names the shader.
Demon's Souls (PPSA01341) closed in game after a few minutes of play
with "Unhandled host exception ... address=0xffffffffffffffff" on a
"BPE JobWorkerThread": its audio engine asserts (sample_player_1.cpp
line 1652, int 0x41) as soon as an AJM decode job reports any of
CODEC_ERROR, FATAL, INVALID_DATA, ... for a voice.

The voice was a DualSense haptic sound. The game's haptic banks
(sound/banks/vibration/*.bnk) hold 48 kHz dual-mono ATRAC9 streams with
192-byte superframes of one frame, and a few of their frames do not
unpack in LibAtrac9 (ERR_UNPACK_SCALE_FACTOR_MODE_INVALID or _OOB): 4 of
330 streams in levels_haptics.bnk and 13 of 1754 in
player_foley_haptics.bnk, one or two frames each, against none in the
6000+ streams of the ordinary banks checked. FFmpeg's decoder rejects
the same frames. PS5 decodes those streams without reporting an error,
or the game would assert there too, so a frame that does not unpack is
a lost frame and not the end of the stream.

The ATRAC9 decoder now plays such a frame (an ERR_UNPACK_* status, or a
frame that takes more bytes than its superframe holds) and the rest of
its superframe as silence, skips the superframe's bytes, and restarts
LibAtrac9's handles when the superframe has more than one frame, since
LibAtrac9 counts the frames of a superframe. Other decoder failures
still end the job with CODEC_ERROR.

[HACK] What the console produces for these frames is not known: its
system at9 decoder accepts them, and silence only keeps the job and the
stream going. The fix is to implement in LibAtrac9 what the system's at9
decoder does with these modes. Every replaced frame reports a [HACK]
notice, keyed by the decoder status and the stream's configuration.
Elden Ring Nightreign (PPSA25381) closes in game, a few minutes in, with
"Depth target fatal: unsupported depth register state", which did not
say which of its four checks failed. The draw binds a 480x96 or 576x96
target with an 8-bit stencil buffer and no Z buffer (DB_Z_INFO format
invalid, no Z address) while its stencil test is on, and stencil-only
targets are not supported.

Report a target without a Z buffer as such, with its stencil format,
addresses and extent, and give the failed checks and the depth
registers they read (format, samples, mip levels, slices, extent, HTile,
shading rate encoding and both Z addresses) in the other message.
GTA V closed when it entered the game in Fidelity with native RT, with
"Not implemented (result != vk::Result::eSuccess)" in shaders.cpp for
three compute pipelines in a row, which said neither what the driver
returned nor which shaders it refused. The error now names the
vk::Result and the shader hash of a compute pipeline, or the hashes of
the stages of a graphics pipeline:
"vkCreateComputePipelines failed: ErrorUnknown, cs 0x0b41af19bddf132c".
kyty_emulator and every test made with add_kyty_full_emulator_test
compiled the 202 translation units of the emulator again. A build of
the emulator, the launcher and the eight tests of our candidate builds
(two of them whole-emulator tests) compiled them three times: 4832 of
its 6374 s of compile time.

They are now compiled once, in the OBJECT library kyty_emulator_objects
(the emulator's include directories, the usage requirements of its
libraries, clang-tidy and include-what-you-use), and linked into
kyty_emulator, shader_cfg_tests, shader_recompiler_compute_tests,
http_uri_parse_tests, kernel_file_system_tests and net_resolver_tests.
virtual_memory_allocation_tests keeps its own copy (OWN_SOURCES): it
compiles them with KYTY_VIRTUAL_MEMORY_ALLOCATION_TESTS. On macOS x86_64
the library passes KYTY_LINKED_GUEST_ADDRESS_SPACE and the segment
addresses on to the executables that link it, which no longer add
macosGuestAddressSpace.cpp (and its .zerofill segments) a second time.

Every emulator source keeps the compile command kyty_emulator used,
apart from the object path (compile_commands.json compared with our
options, with ThinLTO, PGO and x86-64-v3, and with those of the Windows
release job); kernel_file_system_tests and net_resolver_tests compiled
their copies with one more include directory, which the emulator does
not use. The executables link the same objects and libraries, in the
same order, except that the objects of the library now come before the
executable's own (main.cpp, which has no dynamic initializers, or the
test).

clang-cl, 24 jobs on 12 cores, nothing else running:
- full build: 277.5 -> 179.3 s, 5815 -> 2867 s of CPU;
- after touching an emulator source: 3 -> 1 compilations, 35 -> 15 s
  of CPU;
- after touching vulkanCommon.h: 181 -> 63 compilations,
  130.6 -> 87.2 s, 2273 -> 790 s of CPU.
With the emulator compiled once, optimizing the 57 000 lines of
ShaderRecompilerComputeTests.cpp became the end of a full build: 46 s
of CPU on its own, and in the build it ran from 128 to 179 s. The code
it tests is in the emulator objects; the file only builds the cases and
checks their results. It is now compiled with /Od (-O0 with clang and
gcc): 21 s on its own. /O1 would still take 38 s.

Unoptimized, main() keeps a stack slot for every case it builds: its
frame grows from 285 KB to 752 KB, and the test overflowed the 1 MB
stack of the main thread on Windows (0xC00000FD after the first GPU
cases). There it now gets an 8 MB stack, the main thread stack Linux
and macOS give by default.

Full build: 179.3 -> 144.1 s; after touching vulkanCommon.h:
87.2 -> 53.0 s. The test runs in 34.6 s instead of 28.3 s (warm caches,
two runs each) and prints the same results.
Cold, Demon's Souls needs thousands of compute pipelines from its pipeline manifest, about 1 s of
NVIDIA's compiler each. In the emulator's process the threads that create them run off the cores of
the pinned GPU stages (the process's default CPU sets) and below the game's ~12 busy job threads,
which leave them about two cores. With empty caches and the same save, the game reached its world
after 821 s, and then stalled 53 times over 100 ms in 115 s of walking in circles (32 s in all, the
worst 12.9 s), mostly on compute pipelines.

The emulator now starts helper processes (this executable with --pipeline-helper) that create a
device like its own and, for each compute module of the manifest or that the game has just
compiled, the pipeline in an empty pipeline cache, whose data they send back through a pipe. The
emulator creates the pipeline from that data (~2 ms, with
VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT) and merges the data into the driver cache
file it saves. A module whose pipeline the driver cache (or NVIDIA's disk cache) already holds is
not sent. Helpers run at the priority of the emulator's threads on all of its processors, the idle
second threads of the reserved cores included, each with an NVIDIA disk cache of its own, and exit
after 100 pipelines or 20 s without work. Pipelines the game has just compiled go before the
manifest's; a dispatch takes back a pipeline no helper has started, and waits at most 2 s for one
a helper compiles. 10 helpers on 24 logical processors (KYTY_PIPELINE_HELPERS=<n>, 0 turns them
off); NVIDIA's driver on Windows only.

Demon's Souls, empty caches, same save and route: the world after 463 s instead of 821 s (helpers
compiled ~6 pipelines/s, 2508 in all, before it), and 9 frames over 100 ms (1.1 s, the worst
172 ms) instead of 53. Warm, no helper starts (every pipeline is in the saved driver cache): world
after 64 s (59 s without helpers), 10 frames over 100 ms (15). Measured apart from the game, NVIDIA's
driver creates compute pipelines from several threads of one process as fast as from as many
processes (64 large ones: 5.2/s with 16 threads, 3.7/s with 16 processes); in the game, the same
helpers as threads of the emulator reached the world after 414 s but stalled 132 times over 100 ms
there, and could not use the reserved cores. GTA V and ASTRO BOT start no helper (NVIDIA's disk
cache holds their pipelines): load time and fps unchanged (GTA V 47/50 s and 57.6/58.9 fps, ASTRO
BOT 84/83 s and 30/30 fps, without/with).
Gran Turismo 7 closed while loading its first race (the Music Rally)
with "shader 0x63bebca1b79e1d5c: its call tables do not expand: shader
call table descriptor is not statically readable". The shader is a BVH
walk whose leaf code calls the any-hit function of each triangle's
material: s_buffer_load_dwordx4 s[4:7], s[84:87], vcc_lo and
s_swappc_b64 s[14:15], s[14:15], where s[84:87] is the call table's V#,
loaded once before the traversal loops (s_load_dwordx4 s[84:87],
s[0:1], 0x140). ResolveCalls looked for the descriptor's definition
only in the call's own block. Other walks reuse those SGPRs after the
loop, or keep the pointer to the table of V#s spilled in VGPR lanes
(v_writelane_b32 v85, s4, 11 at the start, v_readlane_b32 s2, v85, 11
before the V# load).

When the scan of the call's block finds no definition, a register read
from memory is resolved from the write that reaches the read on every
path with no other write in between (a walk back from the read that
stops at the writers and fails at the entry), and a V_READLANE_B32 of a
constant lane from the V_WRITELANE_B32 of that lane that reaches it
(other writes of the VGPR on the way must be V_WRITELANE_B32s of other
constant lanes).

Each register the resolution went through is kept with the instruction
whose value of it was read, and the callee check follows them: a
register a callee leaves overwritten must not reach that instruction
from the return of the call (the shader's own writes on the way end
the path). The check was that no callee writes any register the
targets depend on. GT7's any-hit functions save the SGPRs they use and
restore them before returning (s_mov_b32 s<n>, s84 ... s_mov_b32 s84,
s<n>), which counts as leaving them, through SGPRs or VGPR lanes on
every path. Its table also names 1119 functions (of 1717) that load
their own descriptors over the caller's table V# (s_load_dwordx4
s[84:87], s[16:17], 8) and never restore it: after one of them the
next call would read its target through another V#, on the console
too, so they are not targets of this call. They are left out of the
expansion and their rows, if reached, end at the miss trap. A call
through an immutable pointer, or a table left without targets, still
fails.
With --native-rt nothing told whether a game's ray tracing really ran on
the host: a program whose BVH walk the patch does not recognize (as ASTRO's
PLAYROOM's cs 29289be6a0202b6d and ASTRO BOT's cs 9833d01b08e21d08 were) keeps
the game's traversal without a trace in the log, and so does a patched site
whose TLAS walk published no context.

The log now gets an "[RT]" summary every 10 s when something did not trace
natively (none otherwise), from counters that cost an increment on the CPU:
- dispatches traced through host TLASes, dispatches of programs whose BVH walk
  the patch does not recognize (with the last shader) and dispatches without a
  TLAS, which run the program without the patch (ShaderModule::guest_traversal);
- TLAS walks that published no context, so that their dispatches walk the
  guest BVH (a null header read through the user data pointer, a header that is
  not a TLAS the host knows, or TLAS memory not cached yet), with the last
  program, from the readbacks;
- the programs compiled so far: patched, with a guest BVH walk the patch does not
  recognize, and with sites that always take the guest traversal.

--rt-stats also counts on the GPU the rays the patched sites send back to the
guest traversal: one ballot per wave and, only when some lane goes back, one
atomic add in the shader's hack mark entry of the fault buffer
(HACK_MARK_GUEST_RAYS), read back with the hack marks. Its programs get their
own program keys; without it the SPIR-V of every program is unchanged.
ASTRO BOT (PPSA21564) draws broken ray traced shading during the arrival flight to Go-Go
Archipelago. Its pass cs 0x1fc433499277ce93 traces TLASes that the game writes with the CPU (three
that it rotates through, 101 instances each), and their last instance records lie on a caching
page that no buffer covered. The TLAS walk found that page missing, left the context invalid and
let the dispatch walk the guest BVH, counting on the guest's reads to get the page cached. They
never did (the rays reached only the records before it): every dispatch of the level walked the
guest BVH, read zeros there and ran into the loop exits of FinishBdaLoopExits. With 1.19 the age
collection also released buffers that only the walks read ("buffer released by age reached again
by a device-address fault").

The TLAS and BLAS walks now record the pages without a buffer that they read in the fault buffer,
as the device-address accesses of guest shaders do, so that the host caches them for the next
walks and pins them against the age collection. Pages with a buffer are not recorded as used: a
load of the use bitmap in each read cost GTA V's walks in Fidelity about 7 % more GPU time (40 us
of 630 per preparation); recording the faults costs nothing measurable. A walk that finds part of
the TLAS, its header included, in memory that is not cached yet publishes what it read: the rays
miss the rest for that dispatch instead of a guest traversal over zeros. The "[RT]" summary
reports those walks apart from the ones whose header is not a TLAS.

Also: cache a guest TLAS before the dispatch that reads it.

ASTRO BOT (PPSA21564) writes the TLASes of each level with the CPU into memory that no other GPU
work reads, so the first dispatches over a new one found no buffer there. In Go-Go Archipelago
(cs 0x1fc433499277ce93) the first walk of each of the three TLASes of the flight found no header,
and a pass of 64 dispatches in the first frame on the island, over a TLAS of 4242 instances, found
none in all of them; without native ray tracing, the guest's own traversal read zeros instead. A
BLAS that the CPU wrote too (before the level) was read as zeros the first time as well. That pass
also got a host TLAS of the size of the source's previous one, 1024 instances: the instance count
of a walk is only known after the frame.

As for the DMA bases of a dispatch, the memory of the TLAS of a program whose BVH walk the ray
tracing patch recognizes (now derived without native ray tracing too) gets cached buffers before
the device-address synchronization: the header address (from the flattened SRT, or read through
the user data pointer), the box nodes and instance records that the walk reaches, and the BLASes
those instances reference, read on the CPU as rt_tlas_walk.comp and rt_blas_walk.comp read them,
when the CPU wrote them last. The buffers are pinned, as the ones of device-address faults: the
walks do not record their use. Memory the GPU wrote (GTA V's TLASes) is left alone: about 0.7 us
per ray tracing dispatch there. The instance count read there sizes the host TLAS of the
dispatch, and the "[RT]" summary reports the walks that do not fit the host structures.
GTA V in Fidelity mode (Trevor driving, native ray tracing) froze for good in about one run in
six: no more flips, CPU at ~9 %. A game thread faulted ~290,000 times a second on the same
address, its own instruction pointer in the executable (0x901d63710), each fault an urgent
command on the execution thread that found nothing to download. The page held guest code and a
cache watched it for writes; the watchers' protection (read-only) carries no execute
permission, so the instruction fetch faulted, HandleFault() treated it as a read with nothing to
do, and the instruction ran again into the same fault.

An instruction fetch that faults on a page the guest mapped for execution now puts the page
back with its watchers' access plus execute. While read watchers keep the page inaccessible the
fault is resolved as before first, and the next fetch gets the permission. A later watcher
change drops it again and costs one more fault.
GTA V in Fidelity mode with native ray tracing: with the shader store cold (the first session
after a build), dispatches translated their compute programs and created their pipelines on the
execution thread although the pipeline manifest has them. cs b93ab2ec5c5caf00 (the shadow pass
that ray queries patch) took 55-80 ms a frame while driving (translation ~23 ms, module ~9 ms,
pipeline ~14 ms), and with the driver's cache cold too the first crash froze the game for ~5 s
(0b41af19 34.8 s, 6aeb221d 12.6 s, d645a510 7.4 s of pipeline creation in total). With the
patching on, dispatches look compute programs up under their own keys
(AppendNativeRayTracingKey()), which the manifest's modules did not carry: none served them.

The manifest builds compute modules with the patching and its key, and for the patched ones
also the unpatched guest-traversal variant that dispatches without a TLAS use.

A recording keeps the patched modules too, as the program they patch: the patch keeps the guest
walk and adds no resources (it reaches the ray tracing state through device addresses), so the
specialization a patched module was compiled with is the unpatched program's as well, and the
manifest builds the record patched or not as the host does. The three records of cs
0b41af19bddf132c, recorded without native ray tracing, serve its patched dispatches. Recordings
left them out before, so variants that only sessions with native ray tracing compile never
reached the manifest. A recorded module is named by the manifest's identity, without the marks
native ray tracing adds to the host's key, as the loaded and built records are.
Cold, the helpers took their jobs in the order the manifest's modules were
built, and the manifest's threads created the graphics pipelines in the
order their modules were. The driver's time follows the size of the SPIR-V,
from about a second to minutes (GTA V's cs 0b41af19), and a long one
started last keeps one helper busy alone while the others are done: in
Wolverine the precompilation notice stood 45 s at "152 of 154" for the last
two.

After the urgent jobs (a dispatch wants them soon), the helpers now take the
largest module first, and the manifest's threads the graphics pipeline with
the most SPIR-V first.

Demon's Souls, cold, the same build with the order before: in game after
371 s against 379 s, the game stopped for 286 s against 307 s, of which 22 s
against 33 s with fewer than 4 of the 20 helpers busy.

Also: compile first the pipelines of the shaders the game used in earlier sessions.

A game maps far more shaders than it uses soon, and its pipeline manifest lists them for every
place of the game. Demon's Souls (PPSA01341 01.007) maps 6731 shaders while it boots and loads, 2959
of them listed, and uses 1170 of them up to its first area (574 compute). With a cold driver
cache the helpers compiled the 2933 listed compute pipelines the largest first, ~6.5 a second, so
the ones the game needed were spread over a queue of minutes: without the precompilation pause
its GPU thread took 482 of them back and created them itself (110 s of stalls before the game
was playable, at 187 s).

The pipelines the GPU threads use for the first time in a session now note the programs of their
stages, in order, in <title>_<version>.use next to the recorded manifest. The next sessions build
the manifest's modules, create its graphics pipelines and queue the helpers' compute pipelines in
that order, the last session first, before everything else. A title without the file compiles as
before.

Demon's Souls, cold driver cache, without the pause: playable at 132 s instead of 187 s, 65
compute pipelines created on the GPU thread instead of 482 (57 s of pipeline waits instead of
114 s). With the pause the order only decides what is ready first for a player who plays at once.
GTA V's Fidelity mode with native ray tracing builds its BVHs with Sony's Psr
library every frame. Before each build pass (cs 5c02d7970bd792ec,
f85e944c4ed88b61 and others) the command processor writes the pass's
parameter block (68 dwords: the descriptors of its inputs and outputs) with
WRITE_DATA, over the previous pass's. The resolution thread walked the
pass's SRT before the execution thread had run that WRITE_DATA, so it read
the previous parameters; the execution thread found bits that are not
refreshed changed (output record counts, descriptor flags), walked the SRT
again itself, and its loads of those pages, which writable bindings of
earlier passes mark as written by the GPU, waited for the GPU to finish all
queued work (~11 ms each, 60-180 ms/s while driving).

A WRITE_DATA's bytes are in the command buffer when it is parsed. Its
operation now carries them, and the resolution thread, as it passes the
operation, keeps them until the execution thread ran it: its guest reads
(GuestReadLog::Read() and the SRT walker's loads) take them over the backing
store, so the walk ahead sees the parameters the pass will run with.
V_CMP_CLASS tested all ten classes against the mask bits: 86 instructions per test, and Demon's
Souls' compute programs test 0x38 (negative and finite) in many places, 7 % of their SPIR-V. A
constant mask, the usual operand, now builds only the classes it selects, the finite classes of
one sign as one exponent test: 6 instructions for 0x38. A mask read from a register keeps the
full test.

The 94 programs of a 196-program sample of Demon's Souls that change only by this: 9 % fewer
instructions, pipeline creation on one thread 537 -> 526 ms per pipeline (50.5 -> 49.4 s, each
module's old and new SPIR-V back to back); Demon's Souls' shader store 147 -> 141 MB.
The NVIDIA compiler inlines get_bda_pointer at every call, dozens per compute program in Demon's
Souls, and its pointer came from a Phi of a fault path and an available path. The fault path now
only records the fault, in an if without else, and the pointer is a select: one block and one Phi
fewer per copy. The faulted-read counter of the loop exits needs no Phi parent patched anymore.

Pipeline creation on one thread, each module's old and new SPIR-V back to back, a 196-program
sample of Demon's Souls' compute programs: 1059 -> 970 ms per pipeline (207.5 -> 190.1 s, with
the constant class masks of the previous commit, about 1 % of it). GTA V's trevor_still (Fidelity
with native ray tracing) and Demon's Souls' ingame30 keep their frame rate with this series.
A 16- or 32-bit read through a device address that is not dword aligned reads the next dword too,
and looked it up with a second get_bda_pointer: NVIDIA's compiler inlines a copy per call, and
these copies were about half of Demon's Souls' (without them its programs compiled in 0.8x the
time). The next dword is on the first one's page unless the first ends the 16 KB page, so its
pointer is the first one's + 4; only the last dword of a page takes a second pass of a loop around
the one get_bda_pointer. The loads are in the loop, which carries only the first dword into its
second pass: carrying both pointers out of the loop cost registers (fewer warps per SM in 207 of
Demon's Souls' 1959 compute programs and more in 65; 97 and 67 this way). Faults and use bits are
recorded as before; the zero reads counted for the loop exits count once per read on one page
instead of twice. In BVH traversal shaders a dword of a missing page still reads as all ones; the
next dword of a read that stays in its dword reads zero there too.

Pipeline creation on one thread (its CPU time), each module's SPIR-V before and after back to
back, a 196-program sample of Demon's Souls' compute programs: 811 -> 658 ms per pipeline; the
driver's binaries of its 1959 programs 246 -> 215 MB. Demon's Souls' ingame30 with warm caches:
22.42 -> 22.55 fps (ABBA, 3 and 2 passes).
Demon's Souls closed in some zones (Boletarian Palace, Shrine of Storms, Tower of Latria,
Stonefang Tunnel) with "Not implemented (desc.info.data.size == 0 || alignment == 0 || ...)" in
descriptors.cpp, and also with "unsupported texture mip view changes physical layout", "texture
base layer is out of bounds", "invalid color metadata" or "invalid data image range". In
Stonefang (m06_00) it closed after 2-6 minutes of walking. Pixel shader 3f7b19201073e188 picks
one of the eight T#s of its constant block by the top byte of a flat vertex attribute, in a loop
over the distinct values of the wave (s_ff1 over the OR of 1 << byte). The host materializes
every T# the shader could pick: one per bit of the 32-bit lane mask, 32 entries 32 bytes apart
from the block's +0x158, and past the eighth come the block's sampler (+0x258) and other
constants. The game reuses that memory for float data and leaves words 2-5 of older T#s in
place: such an entry passes the T# checks of the materialization, but its base is unaligned or
unmapped, and deriving its image description exited the emulator. In the Tower of Latria
(m04_01) shaders 14a2913be711acaf and b4e1b94988dff9ae get candidates like
02a31000,c4700000,001fc7ff,91b30fac,... (8192x128 with 1281 layers, a view of mips 0-3 of a
one-mip image), the "changes physical layout" closes.

Deriving the description of a T# now reports why the host cannot view it instead of exiting. A
candidate of a T# the shader selects at run time (one an indirect descriptor can name, a bindless
table element or an image heap element) that the host cannot view, or whose data or color
metadata range is outside guest memory, binds a null image: the shader never selects it. A T# the
shader reads directly still exits, with the same reason.

Also: bind a null image for T# candidates the texture cache cannot resolve.

Demon's Souls (PPSA01341) closed after 2-30 minutes of play with "TextureCache: unresolvable
equal-address image overlap" (a view of 4609 layers of one level over a texture array of 10
levels and 256 layers at 0x1003000000; 7265 layers over 8x256 at 0x1000000000) and with
"unsupported sampled depth image" (the T# of the scene depth at 0x276180000, 2560 pitch, with
words 6-7 90700000,00000004 and 02728000,c4700000, which are no metadata settings of it).
Pixel shaders 3f7b19201073e188, 14a2913be711acaf and b4e1b94988dff9ae pick one of the T#s of
their constant block at run time, the host resolves every T# they could pick (see "bind a null
image for T# candidates the host cannot view"), and those candidates hold the T#s of the game's
texture arrays and of the scene depth (02761800,c1600000,0167c27f,91800924,00000000,00700000,
00000000,00000000). Past the T#s the shader selects the game leaves the first words of older T#s
and other data: such a candidate starts like the T# of a real image and goes on with other
words. Its description passed the checks, and the texture cache's overlap resolution and the
sampled depth checks exited.

The lookup of a candidate (TextureCache::ImageDesc::candidate) now declines an overlap the cache
cannot resolve instead of exiting, and a candidate whose image is a depth image it cannot sample
as depth binds a null image, as bindless table elements already did. A T# the shader reads
directly still exits.
GTA V (PPSA04263) Fidelity binds two 4K depth targets as R32_UINT storage images in CS
0x24cbc249a5cf541a, in most frames, and their stencil planes as 8_UINT storage images in the
same dispatch. Vulkan has no storage depth or stencil images, so the texture cache converts: it
creates an R32_UINT image, copies the depth into it and deletes the D32S8 image, and the depth
target that follows converts back into yet another new D32S8 image. Deleting the depth image
deleted its stencil association too, so the stencil binding of the dispatch found no image: a
new R8_UINT image was created and uploaded from guest memory, 8.3 MB that hold no stencil (the
stencil is never written back), the stencil the game rendered was lost, and the stencil the
dispatch wrote never reached the new depth image. The dispatch cost the execution thread
~0.9 ms, and every conversion created two 4K images.

The image a depth/color conversion replaces is now kept, unregistered, instead of deleted, and
the conversion back reuses it; a depth image keeps its stencil aspect and stencil associations
meanwhile. A texture or storage image of the stencil plane of a kept depth image binds a
persistent copy of its stencil aspect, refreshed on the GPU when the depth image was written
since and written back into it when the depth image returns. Kept images are deleted after 2048
submissions, beyond eight, or when their memory is unmapped. The 512x2048 shadow map that GTA V
renders as R32_SFLOAT and samples as depth converts twice per frame as well and reuses its two
images the same way.

Keeping a depth image and taking it back change what a lookup of its stencil planes finds (the
depth image, or a copy of its stencil) while nothing is registered or deleted over the planes:
both count as changes of the image set over the planes, so the lookups remembered over them
(the texture cache's exact lookups, bindless table elements) are made again. SAROS (PPSA07631)
binds a stencil plane as a texture and, in the same dispatch, the depth bytes in a color format
after it: the conversion kept the depth image, and the stencil binding, looked up again, took
the remembered lookup of its plane back to the kept, unregistered depth image and ended the
emulator ("texture requires rediscovery before final acquisition").
A pipeline manifest record holds the resource specialization that the recording build derived
for its program: one element per buffer, image and sampler that build found, plus the variants
it added. When a later build finds other resources in the same code, the record no longer fits
and ApplyResourceSpecialization stops on one of its checks (more resources than elements, or an
added variant whose root does not exist): a fatal error while the manifest is replayed. The next
commit binds fewer buffers in GTA V's cs c421273ce118f4a5, whose records are in the shipped
manifests (PPSA04263 and PPSA04264), so the replay stopped there.

Such a record can never match a dispatch or a draw of this build, which looks a module up by the
specialization it derives, so the replay now skips it before compiling, as it skips programs
that call guest functions; it counts as a failed module in the summary.
GTA V in Fidelity mode with native ray tracing, driving: the execution thread waited 95-110 ms
per second for the GPU. The DispatchIndirect of cs c421273ce118f4a5 (a pass of Psr over the
nodes of a BVH) builds two V#s, s[48:51] and s[24:27], as {s6, s1 | stride 64, the dword at
s[6:7] + 0x58, format}: the record count is in a header of the buffer itself, which the BVH
build before (cs cab98b9b1a31a38e) writes on the GPU. Resolved ahead of execution, that dword
still held stale bytes; the execution thread read it again to bind the buffer's range, a load
from a GPU-owned page that waits for all queued GPU work (~11 ms), and it always differed.

Such a self-sized buffer (a V# whose base is user data and whose record count a scalar read
takes at a fixed offset of that same base) is now accessed through device addresses in compute
shaders, as the V#s a shader selects at runtime: its V# words stay in the shader, so the record
count is a flattened SRT dword (copied on the GPU when the GPU wrote it) and the shader checks
the V#'s own bounds, as the hardware does. The host never reads the header. Before the dispatch
it caches the first 64 KiB from the base (other pages are found through the buffers that hold
them, or fault and get cached, like any device-address access), and the pages the stores wrote
come back through the write bitmap. Only V#s whose every use is a raw load or a raw DWORD store
take this path; the others keep their binding.
GTA V in Fidelity mode, driving: the game unmaps ~120 ranges per second while it streams, and
every unmap of a range with a registered image made the execution thread finish all queued GPU
work first: ~5 drains per second of ~1 ms, up to 14 ms per second, with the GPU idle until the
execution thread submits again. None of those images was written by the GPU or read back: they
were streamed textures, copies of guest memory.

The drain protects GPU writes to the range and completions that write guest memory. An image
that only holds guest data has neither: freeing it is what the garbage collector does at any
time, its objects living until the queued work that uses them is done. Like the buffers, which
drain only for GPU-modified pages, the unmap now drains for images that are GPU-modified, armed
for a lazy readback or downloaded after each submission.

The partial image unmap of the texture cache test now expects no drain for an image that only
holds guest data, and a drain for an image the GPU wrote.
GTA V in Fidelity mode with native ray tracing, driving: before it uses a draw or dispatch that
the resolve stage prepared ahead, the execution thread checks that the guest memory the resolve
read is unchanged (GuestReadLog::StillValid()). The strict reads, specialization memory such as
the key arrays of bindless tables, came to ~240 MB per second, and each was copied from the
backing store into a scratch buffer before the comparison: 30.7 ms per second of the execution
thread, 0.126 ns per byte.

They are now compared where the backing store holds them, after the same check that the GPU
does not own the bytes (a range over several mappings still compares a copy): 14.2 ms per
second, 0.059 ns per byte, measured in one run with the two ways switched every 2 s.

Also: compare the large tables of the operations that trace rays on the execution helpers too.

In GTA V's Fidelity mode the four operations that trace rays with alpha
tests each compare a 2 MB bindless table before they run (the
revalidation of what the resolution read ahead), and their table states
check the versions of ~17 000 elements each. The execution thread did all
of it alone, at a few GB/s for memory that is not in its caches.

These comparisons are now split over the execution helpers, as the
checks of the elements already were. Revalidation 28.1 -> 21.4 ms/s, the
version checks 10.9 -> 7.9 (Fidelity in the city).
Demon's Souls draws most meshes with runs of DRAW_INDEX_INDIRECT packets
that differ only in their data offset: in Boletaria about 2,800 such
packets a frame, 1,700 of them in runs of 2 to 40. Each was an operation
of its own for the command processor, the resolution and the execution
threads (~4 us each on the execution thread, the one that limits the
frame rate there).

The parser draws a run of packets whose records follow each other as one
multi-draw, but the records of a run are not always consecutive: they
are 20 bytes apart, and sometimes 40, 60... (every second or third
record). Those runs now draw as one multi-draw of that stride too: any
constant stride of at least a record, dword aligned. Packets with the
predication bit, other registers or another stride end the run.

Boletaria with the user's save, two alternating runs each (with the
faster replicating fill), when the parser drew no runs: facing the
castle 16.4 -> 22.1 fps, walking 15.4 -> 20.1 and 16.4 -> 20.9, turning
the camera 25.7 -> 28.2 and 26.0 -> 28.0, title menu 78 -> 99. Same
picture.
Demon's Souls walks over a hundred thousand SRTs a second on the
resolution thread, which then takes as long per frame as the execution
thread. Each load of a walk reached the guest read log through an
indirect call to RecordLoad(), which inserted its dword at the end of
the byte vector and merged its entry: a fifth of the resolution thread.
Every load also asked through a second callback for the bytes of
pending WRITE_DATA packets, though none was pending.

WalkSrt now hands all the loads of a walk to an optional batch
recorder, which logs them as RecordLoad() did, with the bytes written
behind a cursor in room made once. The log is the same: checked
against the per-load path on 24 million walks in game. The pending
writes change only between operations on the resolution thread, so a
walk made while none is pending does not ask for them.

In Demon's Souls, logging the loads goes from 20 % to 11 % of the
resolution thread, and the execution thread waits for resolved
operations 7 % of the time instead of 12 %.
ASTRO BOT (PPSA21564) measures the visibility of each object of Go-Go
Archipelago with an occlusion query: a ZPASS_DONE dump, a proxy draw,
another dump and a WRITE_DATA. On the beach that is ~13,000 dumps and
~6,700 WRITE_DATAs a frame between ~11,000 draws, which stream ~9,000
small constant ranges (~6 MB) a frame into the stream buffer through the
host copy thread. Those copies read the guest's backing store when the
copy thread runs them, so every operation other than a draw waits for
them before it executes (HostCopyQueue::Drain()): ~6,500 waits and
3.5-4 ms a frame of the execution thread, which is the bottleneck.

Only the copies of the operation right before one that is not a draw are
still pending when it drains. The resolve thread, which runs behind the
command processor and so almost always has the next operation queued,
marks a draw or dispatch whose next operation is not a draw
(GpuOperation::stream_in_place), and the execution thread copies the
guest bytes such an operation streams into the copy queue's ring right
away (CopyInline()); the copy thread writes the stream buffer from there.
Drain() waits only for the copies that still read a source passed to
Copy(). Every other copy still runs on the copy thread: GTA V streams
~22 MB a frame between draws, and copying all of it on the execution
thread cost it 12% of its frame rate in Performance mode.

On the beach (alternating 8-second windows in one instrumented run) the
waits drop from 3.4 ms a frame to none, the draws take 0.7 ms more, and
the frame rate goes from 18.4 to 19.3; GTA V is unchanged.
A game started from the launcher runs with the printf log silent, so when it closes or crashes
nothing is left to tell why. Turning the printf log to a file is no way out: it traces every call
of the graphics libraries in each frame (about 3 MB a second in GTA V, 6 % fewer frames per second).

--session-log <file> keeps what reaches the console whatever the log direction (the [HACK] notices,
warnings and errors of Log::WriteToConsoleAndLog, and the fatal errors of DbgReport), plus the
reports of a fatal error that went only to stdout or stderr: the context of a guest fault, the
fatal errors of the page manager and of depth targets, and an uncaught exception. The printf log
stays off.

The file is buffered and written out after each message, as the console is; these messages are
rare, so no hot path pays for it, and a fatal report is on disk before the process exits. The
program a LoadExec starts continues the file; pipeline helpers do not open it.
ASTRO BOT's crash on GeForce RTX 50 reported a host fault with registers
and raw stack words only; finding that the faulting code was
nvgpucomp64.dll, NVIDIA's shader compiler, took matching the code bytes
by hand, and nothing said which pipeline the driver was creating.

The fault report now gives the module and offset of the faulting
instruction and of the stack words that point into a module, and the
guest pipeline (stage hashes) the faulting thread was creating in the
driver: the pipeline creation records it in a thread-local slot for the
duration of the vkCreate*Pipelines call.
Resident Evil Village hung the GPU (TDR, device lost) a few seconds after
starting a game. Its BVH builds compact their nodes with a single-pass scan
with decoupled look-back (cs af3a06c77cbc67e7): each workgroup publishes
{flag, value} with a GLC buffer_store_dwordx2, and the next workgroups spin
on that pair with a GLC buffer_load_dwordx2. The load has been one 64-bit
atomic read since d1fe1324c ("shader: keep coherent 64bit atomic"), but the
store was still two DWORD stores, so a reader could see the new flag with
the previous value. The scan then came out non-monotonic at block borders,
the collapse pass (cs 213dffe426b387dc) wrote several nodes into the same
slot, and box nodes ended up with float garbage as child pointers. The
traversal in cs be0b848d2e06ec9b followed one of them into a leaf list it
never left.

On the guest GPU such a store is a single 64-bit write. Store an aligned
GLC/DLC DWORD pair that lies inside its buffer with one 64-bit atomic store
through the same 64-bit alias the load uses (release semantics, device
scope); any other pair keeps the DWORD stores. This completes the 64-bit
atomic read of d1fe1324c; shaderBufferInt64Atomics is already a required
device feature.
Resident Evil Village crashed (a jump to address 0, or to a garbage address, in the thread
Renderer::DelayEndTask) or hung right after the intro video of a new game. It runs the jobs of
Psr::buildManyBottomLevelBvh on fibers whose contexts are 4 KB, placed right above their
SceFiber objects. Fibers ran on the guest's context, and host code runs on that stack too: on
Windows the dispatch of the exceptions the emulator handles in guest memory (the pages it
protects to track writes for the GPU; RenderContext::HandleFault) pushes the thread context with
its extended state and runs the handlers there. That overflowed the 4 KB context: the magic at
its base was overwritten, and so were the neighbouring fiber object (a later sceFiberSwitch to it
started a fiber with a garbage context) and the stack of a suspended fiber (whose resume returned
to address 0). The PS5 does not take such exceptions, so the guest's context is enough there.

On Windows a fiber now runs on a stack of the emulator in guest memory (the pthread stack area), the
size of its context plus 64 KB (the deepest use measured in Resident Evil Village, guest code and
fault dispatch together, was under 8 KB; it had about 80 such stacks), assigned to the fiber object
when it starts and released when it is initialized again, finalized or its entry returns. The fiber
object keeps the guest's context: sceFiberGetInfo reports it and the magic at its base is still
written there. Without room in the stack area a fiber runs on its own context, with a warning. Linux
and macOS take signals on an alternate stack and are unchanged.
Marvel's Wolverine (PPSA03671) links a newer build of sce::Psr (515 shaders, BVH version 10)
than GTA V. The emulator did not know its generation, so with native ray tracing nothing of it
was replaced: every frame of the first cutscenes after New Game refits some 550 BLASes with
psr_qbvh_fan_refit_copy_dispatch_args, psr_qbvh_fan_refit_async_shader_mesh_0 (once per
geometry), psr_qbvh_fan_refit_recover_aabbs and psr_qbvh_refit_bottom_level, about 2,200
dispatches a frame whose cost is the emulator's per-dispatch work (the box pass, fb3ca6c727da6121,
was also 44 % of the GPU time).

The refit has the same window as GTA V's (all the argument copies, then the vertex passes, then
the recoveries and the box passes) and its BLAS header keeps the fields at the offsets of
Base460. The vertex passes call functions of the game to compute the vertices, so they keep
running; the other three passes are replaced:
- psr_qbvh_fan_refit_copy_dispatch_args writes the indirect arguments of the vertex pass of each
  geometry over boxes of the BLAS's first box nodes, keeping the signs of the floats it
  overwrites: one host command writes them for every BLAS of the window before anything else
  the window runs.
- psr_qbvh_fan_refit_recover_aabbs makes those floats infinite again with their signs, and
  psr_qbvh_refit_bottom_level refits the boxes bottom up and writes the bounds of the BLAS (the
  root's boxes) in its header: with the last box pass, the box refit of hle_blas_refit.comp does
  all three for every BLAS of the window.

The generation is recognized by the shader names the library registers (the nested BVH counts
and flattening it added, the shaders of Base460 it removed), and the replaced shaders by their
code as well (CodeFingerprint() and the compiler revision of Wolverine's build): the other
shaders of the generation are Other, so no other replacement applies to it. GTA V's generations
take the same paths as before.

In the first cutscene the box pass is gone and the GPU is busy 13 % of the time instead of 19 %;
the dumped BLASes have the boxes the game's own refit computes from their leaves.
The root's four boxes, and so the bounds in the header, grow by 1/256 of their size: in large
animated BLASes they were seen about 1e-3 of their size behind their children, and no ray may
miss geometry at their edges.
Marvel's Wolverine builds its TLAS on the GPU within the frame, so NativeRayTracing never
reads an instance count for it (NoteTlasInstances() stays 0) and sized each host TLAS from
the previous walk of the source (at least 1024). The scene changes the count by thousands
at once (224, 1546, 2811, 2868 instances while the forest loads), the first walk after
each change overflowed the host instances and logged "TLAS walks found more box nodes or
instances than the host structures hold" while its rays missed the rest.

A source the CPU has never counted now starts at 4096 instances, and a source that still
overflows keeps the count the GPU found as its floor from then on. Sources whose TLAS the
CPU counts (GTA V, ASTRO BOT) size their host TLAS exactly as before.
Marvel's Wolverine (PPSA03671) lost the device right after New Game on
NVIDIA ("Illegal Instruction Parameter", nvlddmkm 153): the ray tracing
compute 0x1a04c58a9fbc2052 runs its hit groups through a call table, and
the first dispatch that executes them with real data dies. Shader Instruction
Error sits at the WARPSYNC after the BSYNC of a branch inside a helper
function (the switch of indirect_buffer_format_geometry inlined into
load_indirect_buffer_*_formatted, or the page table lookup of
get_bda_pointer): the driver gives a function called from a lane guard
(`if (exec)`) a software convergence mask, and the lanes of a call target
that execute reach the helper with masks that do not match. With the loads
returning zero, or with get_bda_pointer inlined at every site (which the
driver cannot compile: 40 GB), every lane takes the same path and nothing
fails; maximal reconvergence, subgroup uniform control flow, a switch-free
format geometry, a branch-free get_bda_pointer and arrays without branches
alone did not help.

In a compute program with outlined call targets, no call of the memory
accesses sits under a lane guard any more. LoadBuffer calls
load_indirect_buffer_* from every lane (a lane that is not executing passes
a V# without format, which loads nothing, and takes the zero result with a
Select); the helpers and the other guest memory loads and stores take the
pointer from get_bda_pointer_masked(address, active), a new function in
which an inactive lane looks up page 0, records nothing and gets no pointer,
and only the load or store itself stays under its guard. The per invocation
arrays (LDS and scratch, Private variables in these programs) are read at a
clamped index and written back unchanged where the lane does not store, so
their accesses have no branch either. Other programs emit the same SPIR-V
as before.

Also: read guest memory through bda_load_u32 functions instead of a diamond at each site.

Every read of guest memory through its device address (s_load and s_buffer_load
of V#s, T# and SRT tables, runtime-V# buffer loads) was a call of
get_bda_pointer followed, at the site, by a compare, a branch around the
ConvertUToPtr and Load, and a Phi, and the guard of the access (bounds, EXEC) as
one more diamond around all of it. Marvel's Wolverine ray tracing compute
0x1a04c58a9fbc2052 has about 4000 such sites: three blocks and about fourteen
instructions each, a third of its instructions, and the NVIDIA compiler takes
minutes and gigabytes for it (232 s and 7.4 GB for the 20-target module; 362 s
and 13.8 GB for its largest variant without call targets).

The access is now a call of bda_load_u32(address), or of bda_load_u32_g(guard,
address) where the site has a guard: one function (DontInline in programs of
outlined call targets, as the other shared helpers) that looks the page up,
records its use or fault and loads, with the guard inside. The loads of
runtime-V# buffers (load_indirect_buffer_*) take whether the lane executes as an
argument in the same way, and every lane calls them. This is what the commit
before it did for programs of outlined call targets with get_bda_pointer_masked:
no call sits under a lane guard any more in any program, and loads no longer
need that function, which only the stores use. Only the variants a program calls
(coherent or not, guarded or not) are defined, after its other functions, so the
programs that do not read memory by address are unchanged.

GTA V Fidelity with native ray tracing is unchanged: the compile time of its
largest compute programs is the same within the noise (14.0 s and 13.9 s,
6.7 s and 6.8 s, 24.8 s and 22.8 s), and the Franklin and Lamar scene runs at 26.6 fps
before and 27.4 fps after (3 passes each).
"shader function needs nested calls or unsupported instructions" closed
Marvel's Wolverine's 0x1a04c58a9fbc2052 (a ray tracing compute whose hit groups
are called through a table) once its hit groups stopped being skipped, without
saying which of the call targets or which instruction made the expansion fail.
The reason now carries the instruction word, the target's address, the offset
in the function and what it is (a call, S_ENDPGM, an instruction the decoder
does not support, or a write to the return address).
Marvel's Wolverine's 0x1a04c58a9fbc2052 closed the emulator ("its call tables do
not expand: shader function needs nested calls or unsupported instructions")
some 15 to 20 minutes after New Game, once its hit groups were no longer
skipped. The call table of that compute lists, besides the hit groups, the
address of the code of a pixel shader (746 words ending in `exp null ... done`
and S_ENDPGM), which no lane calls but ReadFunction() rejects for the
S_ENDPGM, and one such candidate failed the whole expansion.

Of a call through a table, a candidate that cannot be read as a function
(unmapped, not DWORD aligned, a call, S_ENDPGM, an instruction the decoder
does not support) is now left out of the expansion, as a function that
overwrites a dependency of the call already is: if a lane did reach its row it
would end at the miss trap. A call through an immutable pointer, and a table
with no readable target, still fail with the reason of the first one (which
names the address); how many were left out, and the first, is logged.

A pass of 1500 s after New Game with the first candidate of every table
forced out ran without a problem.
With --trinity --dlss every game closed at start with "vkCreateDevice
failed: ErrorInitializationFailed" (Ghost of Yotei 02.002 here): NGX
needs VK_NVX_binary_import, for which the NVIDIA driver reserves the
address space of its CUDA runtime below 1 TiB. The guest regions take
all of it up to 0xfc00000000, and the writable alias of guest direct
memory (13.6 GB in Pro mode), mapped at no particular address, went to
the lowest free range that fit: the 16 GB left below 1 TiB, so the
driver found no room.

The alias now asks for an address at or above 1 TiB (MapViewOfFile3 with
address requirements) and falls back to any address as before. The
driver then reserves its range in that gap, and GT7 (PPSA01317 01.680)
upscales its PSSR with DLSS.
The scalar branches of a program (S_CBRANCH on EXEC, VCC, SCC or on the result of
a scalar compare) are emitted as OpGroupNonUniformAny/All over the lanes of the
wave. The NVIDIA driver spends about 45 ms compiling each one and almost nothing
on a ballot: the dispatch loop of Marvel's Wolverine ray tracing compute
0x1a04c58a9fbc2052, which has hundreds of such guards (one pair per call target),
went from 17.8 s to 7.3 s with the guards as ballots in the compile benchmark of
its main function alone. The module of 20 call targets does not change (82.0 s
and 82.2 s): the cost moves to the targets, so the gain is for programs where
the votes dominate, such as compute programs of wave32 with hundreds of uniform
guards.

Any(p) is now Ballot(p) != 0 and All(p) is Ballot(!p) == 0; the invocations that
do not execute the instruction are in neither form. A wave of 64 lanes on a
subgroup of 64 has its upper half in the second word, which is ORed in; a wave
of 64 split over two subgroups of 32 already has the predicate of both halves
combined and takes the first word. The programs no longer need the vote
capability, only the ballot one (ShaderInfo::subgroup_vote is gone).
The window title's frame and fps came from the presenter's own count, which
also includes the frames the emulator draws by itself when the game does not
present: the "Compiling pipelines" / "Waiting for pipelines" notice, trophy
notifications and the like. While GTA V sat stopped compiling pipelines the
title still said 60 fps, unlike the F2 overlay, which counts guest flips.

Count the main-bus guest flips in PerformanceOverlayRecordFlip with one
relaxed atomic increment (whether or not the overlay is shown) and use that
for "frame" and "fps" in the title, as the overlay does. The host presentation
count stays in the title as "presented: N", so tools can still tell that the
emulator is alive while the game is stopped.
Before drawing an object Demon's Souls culls its triangles in a compute
pass of its own (xprindexculling). At Boletaria, standing at the start
of 1-1, that is ~2,770 of the ~4,400 dispatches the execution thread
runs each frame, ~11 ms of its ~54 ms a frame. The engine has a switch
for the pass, doIndexBufferCulling, and runs every "+name=value" line of
$/packagecmdlineargs.txt at boot.

A read-only open of that file now gets a copy with lines added (the
game's files stay as they are): doIndexBufferCulling=false by default
for Demon's Souls, and those of KYTY_GAME_CONVARS="name=value;..."
(a name given there replaces the default's value, "0" adds none). A
stat of the file gives the copy's size. The host GPU draws the
triangles the pass would have culled; the image is the same.

Boletaria, same spot, ABBA (3-4 passes a side): standing 20.0 -> 21.3
fps, walking 18.8 -> 19.9, turning the camera 23.7 -> 25.1; dispatches
4,400 -> 1,640 a frame.
Demon's Souls' job workers wait for work by polling the job queues in a
loop that pauses, reads the TSC and goes round again for two seconds of
idleness before blocking. Work comes every frame, so the workers never
block: standing at Boletaria a stack sampler shows 13 of the game's
threads at 94-99% of a CPU each, in the same few instructions of that
loop (eboot+0x83b9xx). With the emulator's own threads that is every
core of a 12-core host busy, and the game threads that do work share
cores with spinning ones.

Find the idle loop's call of the poll and the wait's call of its TSC
helper by their code (the same in 01.005.000 and 01.007.000) and route
both through thunks that sleep 50 us first (the poll's only when it
found no work). The TSC thunk then jumps to the game's helper, which the
guest instruction patches already give the guest's TSC rate, so the
two-second idle test still compares times of one clock. Other games are
left untouched; the patch reports itself as a [HACK] notice.

Demon's Souls, Boletaria, same build with and without the patch
(gamepilot, fps): standing 23.2 -> 23.6, walking 21.6/22.3 ->
22.1/23.1, turning 27.8/28.1 -> 29.9/30.1, title menu 81 -> 118.

Ported from chenxiao07's fork (fa1182847), adapted: the TSC thunk calls
the game's helper instead of reading the TSC itself, the code search
lives in loader/guestCode.
A program whose device-address reads have no bounds synchronizes every
mapped range before it runs (RenderContext::PrepareBda()). Demon's Souls
does that ~15 times a frame at Boletaria, for ~1,200-1,700 buffers a
frame, ~400 of them with pages to upload. Each buffer went through the
page tracker on its own: its CPU-dirty pages were taken and protected
again with one protection call per buffer (~410 a frame, ~2.3 us each
on the execution thread), although the buffers of a span lie side by
side in the same regions.

The buffers of a CPU-dirty span now go through the tracker together
(MemoryTracker::ForEachUploadRanges()): in each region the dirty pages
of all their ranges are taken with one protection update, so the page
manager protects runs of pages across buffers with one call. The copies
of each buffer are staged and recorded as before. A span with a single
buffer keeps the old path.

Demon's Souls, standing at Boletaria, same build with and without the
change: protection calls in the full synchronizations 410 -> 328 a
frame, page tracking and protection 3.05 -> 2.7 ms a frame, the full
synchronizations 4.8 -> 4.5 ms a frame of the execution thread (the
frame rate does not show 0.3 ms). GTA V's full synchronizations (ray
tracing in Fidelity) take the same path: the bytes uploaded and the
pages protected afterwards are the same, only the number of protection
calls changes.
The emitter keeps every guest register as a uint and masks each vector write
with select(exec, new, old), bitcasting around every float operation. A read
that is itself masked by a condition implying the select's condition only ever
sees the new value, but the module still carries the select, the bitcasts and
the old value's chain. In Demon's Souls the big compute programs are 35 % bitcasts and 19 %
selects, and the NVIDIA driver spends 3-6 s compiling each of them.

Run a pass over the finished module (function bodies of at least 30000 words
only): cancel Bitcast(T, Bitcast(U, x)) when x is a T, forward reads of a
select to its new value when every use ends in a select or a logical and whose
condition implies the select's condition (structural implication through
LogicalAnd), skip an inner select under an outer one it implies, and drop the
instructions and decorations left without uses. Operands are rewritten only at
positions known to be ids.

Driver compile time, same module before/after: DS cs 6b3ba597ada1908f 5.88 s
-> 4.50 s (709k -> 437k words), 7df3cbd56e0417f3 3.24 -> 2.12 s, 162cd57d995c138c
3.21 -> 2.29 s, f2d2a73f22800e83 6.14 -> 5.03 s, 432842b0fdad9d18 6.55 -> 6.20 s.
The pass takes about 100 ms on the largest module. All 60 largest DS and
Wolverine modules still validate; Wolverine 1a04 shrinks only 10 %. DS ingame
fps unchanged (31.4 vs 32.6, ABBA, inside the noise) and the image is the same.
Gran Turismo 7 01.680 closed in PS5 Pro mode while loading a race: its cs f0ff5e4576313e72 stores
DWORDs at pc 0xe38 (buffer_store_dword ... idxen) through s[4:7] = {base, stride 4, count, format}
that it builds itself. The base is user data s[4:5] + 0x100 plus an offset it reads at
s[4:5] + 0x6c, and the record count is the 32-aligned sum of two counters it loads from a buffer
the GPU writes: a list whose length only the GPU knows. Resource tracking took GPU-selected V#s
only for loads, and for stores through V#s read from a descriptor table, so it failed with
"buffer descriptor is not a valid runtime value".

Such a raw DWORD store becomes an indirect buffer store, which the SPIR-V emitter already writes
by device address with the V#'s own bounds checked on the GPU. Like a FLAT store, it marks the
program as one with address writes, so the pages it wrote come back through the write bitmap,
and it records its user-data base, so the host caches that memory before the shader runs.
Gran Turismo 7 in PS5 Pro mode closed while loading a race with "shader CFG build failed: branch at
pc 0x00000bdc targets invalid pc 0x000012d4". Its ray tracing pass cs d73e95c5c9fcba1a has an
S_ENDPGM at 0x12a4, then a debug block (the target of S_CBRANCH_CDBGSYS_OR_USER at 0x10, which is
never taken), then code from 0x12d4 that S_CBRANCH_SCC0 at 0xbdc reaches; that code ends with an
S_BRANCH back to 0xbf8 and a padding word. DecodeProgram stopped at an S_ENDPGM unless a branch
targets the word right after it, so the program ended at 0x12a4.

Past an S_ENDPGM, decoding now goes on while a branch decoded so far targets code farther on, and
from there a path can also end with S_BRANCH. A target past the code is still left to the CFG,
which reports it. A program that decoded before decodes the same: none of its branches targets
code past the S_ENDPGM where decoding stopped, or the CFG would have rejected it.
Ghost of Yotei 02.002 crashed at boot in PS5 Pro mode, writing at 0x900dddf88 to 0xae309dd78. It
allocates the blocks that Psml_mfsr2's GetSharedRequirements asks for with
sceKernelAllocateMainDirectMemory and keeps each in a fixed list of 67 entries followed by their
count. GetSharedRequirements always asked for 123 blocks, enough for a 7680x4320 maximum, so the
68th entry overwrote the count and the next one was written past the game's object.

The count now scales with max_width * max_height: 123 blocks for 7680x4320, 31 for 3840x2160.
CreateSharedResources expects the same count.
The emitter recomputes the same address arithmetic, descriptor decoding and
read-only loads at every buffer access, and calls the same guest-memory helper
with the same arguments again and again. Wolverine's 1a04 call-target program
(1.75M words in its smallest variant) is 37 % redundant: the NVIDIA driver
needs 131 s to create its pipeline.

Add dominator-scoped value numbering to the pass that runs over the finished
module (function bodies of at least 30000 words). It merges instructions with
the same opcode, type, operands and decorations (NoContraction included), GLSL
math calls, loads of push constants, uniform and uniform-constant memory, loads
of storage buffers and device pointers in functions that never write memory
(fault-buffer atomics, which only set idempotent bits, do not count), and calls
of helpers that are provably pure: scalar and vector arguments, no stores
outside their own variables, no subgroup operations, reads of read-only memory
only, atomics only on the fault buffer, and callees that are pure too. Operands
are replaced only at positions known to be ids; a value with a user the pass
cannot rewrite is kept.

Driver pipeline creation time, same module before/after (forwarding only ->
with value numbering): Wolverine 1a04 131.4 s -> 101.8 s (-22 %, peak memory
4.3 -> 3.4 GB); DS cs 6b3ba597ada1908f 4.50 -> 4.37 s, 432842b0fdad9d18
6.20 -> 5.90 s, f2d2a73f22800e83 5.03 -> 4.88 s, 162cd57d995c138c 2.29 ->
2.24 s, 7df3cbd56e0417f3 2.12 -> 2.09 s. Merging plain arithmetic alone does
nothing for the driver; the loads (-13 %) and the helper calls (-11 %) are what
pay. The pass takes about 175 ms on the 1.75M-word module. Both sets validate
with spirv-val. DS ingame warm A/B (ABBA, 2 passes per side): 36.34 -> 36.49 fps
(+0.4 %, noise), same image. Lowering the 30000-word threshold does not pay: on
the 14 largest 8000-30000-word compute modules of DS forwarding saves 7 ms of a
209 ms compile, about what the pass costs.
Gran Turismo 7 in PS5 Pro mode closed while loading a race: "shader 0xd73e95c5c9fcba1a: its call
tables do not expand: shader call table exceeds the bounded body count (1380 bodies for 1704
targets)". Its ray tracing passes (d73e95c5c9fcba1a, cd7934db7cfc2c25 and some 30 more) call the
hit functions of its materials through one table (s_swappc_b64 through 16-byte rows); an expansion
holds at most 256 distinct bodies, and inlining the others is not viable (the pipeline of a pass
with some 120 bodies already takes about a minute to create). Past them, the start of the race
closed it with cs 4ee6a568a66fcc24: "shader loop may overwrite a call-target dependency s8 at pc
1932".

Until those calls run, a dispatch whose call tables do not expand is skipped with a [HACK] notice
that gives the reason, and what it computes is missing, instead of closing the emulator; its
program is remembered as skipped.
PPSA01341 sometimes crashes while loading: a job worker follows a
free-list pointer that reads 0x7ffdfff and faults at 0x7ffe007.

The game streams a 2048x2048 BC texture with 12 mips (0x2b0000 bytes)
and later reuses its memory. Compute shaders c56a64833c5492b8 and
ef9b071345addec8 write mip 0 again through a 512x512 two-dword storage
descriptor (0x200000 bytes), while the game keeps a heap in the bytes of
the old mips 1-11. A CPU write had marked the cached BC image dirty, so
ResolveOverlap skipped the BC alias resolution and returned the stale
12-mip image as a view of its mip 0. The storage binding then marked the
whole image GPU-written, the next raw lookup published all 12 mips to
the buffer cache, and a guest read later wrote the image's mips 1-11
over the heap.

A BC image the CPU wrote after its upload is never written back (it is
not safe to download), so retire it as BcAlias::Resolve does a clean
one: the raw request gets its own image, and only its bytes become
GPU-written. An image that may only be CPU-dirty can still hold GPU
writes and keeps the current path.
The launcher saves its configuration with QSettings, which writes when the object is destroyed and
drops any error. When Kyty.ini sits in a folder the user cannot write to (for example %ProgramData%
on Windows, where the file is created when there is no Kyty.ini next to the launcher), every
change to the game list, the global settings or the window state was lost without any warning.

WriteSettings now calls sync() and checks status(). On failure it explains that the configuration
could not be saved and where. On Windows it offers to save it with administrator rights: the
settings (including what the launcher kept from the existing file) go to a temporary file and the
launcher starts itself again with the runas verb and the argument --copy-settings <source>
<destination>. That elevated process only copies the file, accepts no destination other than a file
named Kyty.ini, and exits. No elevation is requested when the write works. After a refusal the
question is not repeated during the session. On Linux and macOS only the message is shown.
Demon's Souls with a cold driver cache: the manifest's pipelines, and in the helper processes the
compute pipelines the driver cache misses, are compiled while the game runs. The game competes
with them for the processors and stalls on those it needs first: its loading screen stands still
for minutes (436 s with ~570 frames in one pass) and nothing tells the player why.

When what is left for the driver would take long (30 s with --pipeline-precompile ask, the default;
20 s with wait, or once the player waits), a thread of the pipeline cache stops the game and shows
a small notice in the bottom right corner, drawn by the system overlay: how many pipelines are
compiled of those known, the shaders still to translate, and, once a session, the choice. No time
left is shown: the game keeps mapping shaders that add to the work. Esc or Circle plays at once, as
before, with the rest compiled in the background, and the game is not stopped again in the session.
Enter or Cross, or no answer, waits: the game goes on by itself once they are compiled, and stops
again for the pipelines it maps later, with the progress alone. Demon's Souls maps its shaders in
batches while it boots and loads: after a stop the notice stays 15 s, and a batch of 5 s or more in
that time stops the game again under it, so that one notice shows the boot and another the loading,
not one per batch. Without the question, Enter and Cross are the game's while the notice shows.
--pipeline-precompile play never stops the game.

The estimate counts a helper's job that has run t seconds as at least t more, and takes the
longest job when it is longer than the jobs shared out among the helpers: a few pipelines that
take minutes stop the game too (Wolverine stood minutes at 0 fps before its menu, with no notice,
waiting for 1 to 5 of them). And when the guest GPU has waited more than 3 s for a pipeline, from
a helper or created on the execution thread, the notice says the game waits for it and for how
long, in every mode, also after playing at once; it goes 1 s after the game goes on. While the game
waits so, it is stopped as soon as 5 s are left for the driver: it stands still anyway, and the
helpers get the processors.

It is one notice, under one title, whatever brings it: what the game does decides its text (asked,
paused, waiting for a pipeline, or going on again while the notice stays), and its progress counts
the pipelines compiled since it appeared. GTA V in Fidelity mode with native ray tracing, cold,
showed two: "Waiting for pipelines" with every pending job as the pipelines the game waited for
("60"), then "Precompiling pipelines" counting the same jobs again from 0 of 60, and, the game going
on, "The game is paused" for 15 s more; it looked as if the work were done twice. Nothing is
compiled twice: in that pass no pipeline was created twice and no module built twice.

The game's threads are suspended only while they run the game's own code (instruction pointer in
an executable segment of its programs, taken before any is suspended), where they hold no lock of
the emulator; one inside the emulator is resumed at once and tried again every 50 ms. Presentation,
the helpers and the manifest's threads go on, and while the game is stopped the helpers get the
processors it leaves: all but four, up to twice as many as while it runs, as many as half the free
memory holds.

Warm caches leave nothing for the driver: no notice, and the thread reads a few counters four
times a second. No path per draw or dispatch changes.

Demon's Souls, cold, the same save: playing at once at the first notice, the game is reached
after 490 s (488 to 519 s in three passes with play); unanswered, after 386 s, with 2 notices (the
boot and intro, 162 s; the level's loading, 213 s; the game's menu between them) and 24 stops,
instead of a still loading screen. In the game, the compile stalls left are of variants the
manifest does not list, either way. Warm, with ask: no notice, and GTA V is in the game after
51.0 to 52.0 s (52.0 s with play), ASTRO BOT in the garden after 80.4 s (89.3 s), Red Dead
Redemption in the game after 22.1 s (22.6 s).

Also: show the pipeline notice while any pipeline takes long to compile.

The notice of the pipelines the driver compiles ahead of the game came up only while the game
was stopped for them or once its GPU work had waited 3 s for one. Pipelines the driver creates on
other threads (background and manifest threads, the helper processes) and shorter waits left the
game stuttering with nothing on screen to say why.

Count the driver's pipeline creations in progress on every thread of the process (the scope that
already names the pipeline of a driver fault) and the helpers' running jobs. Whenever one has
taken 0.5 s, or the game's GPU work has waited that long, show the notice in a new Compiling state:
it takes no input, says the game keeps running but may stutter, and stays 3 s after the last slow
compilation. The notice after the game goes on stays 3 s instead of 15 s, longer while another
slow compilation comes; the watch looks every 100 ms instead of 250 ms, and the log says when the
notice shows and hides and why.

Also: estimate the helpers' pipelines by their size.

The precompilation stops the game when what the driver has left would take long, and took every
helper job for the mean of the latest ones. A title's largest pipelines take a hundred times the
mean (GTA V's ray tracing programs, 20-40 s each against ~0.3 s), and the helpers compile them
after the ones the game used before: with the code of GTA V's shaders known from the start (second
session, cold driver cache), 217 of its 304 compute pipelines were compiled before the game ran,
the 86 left counted for 3 s, and the game was only stopped at 36 s, while it loaded the save and
already waited for them.

The helpers now report what their jobs take by their size, from the time and size of their
latest pipelines, for the jobs that wait and for the ones that run, and the estimate takes the
larger of the two.
On a host with 32-wide subgroups (NVIDIA, Intel, AMD RDNA2) a wave64 compute program ran two GCN lanes per
Vulkan invocation (lanes i and i+32): every value twice, the heavy shaders at the 255-register cap. Demon's
Souls (PPSA01341) has ~790 wave64 compute programs in Boletaria alone, including its light loops and culling
shaders.

A program whose lanes' results depend on no lane outside their 32-lane half now runs one lane per
invocation, each subgroup a half wave with its own copy of the scalar state. IsWaveLaneLocal (LaneLocal.cpp)
proves it conservatively on the program's own branches:
- refused: lane reads and writes, lane counts, LDS, cross-row DPP, IMAGE_GET_LOD, lane masks used as data, SCC
  made from a lane mask (also from an EXEC save), a DPP row mask that treats the halves apart;
- lane masks (EXEC, selects, carries) come from compares and EXEC or are 0 / -1: other scalar bits hold the
  wave's layout;
- V_READFIRSTLANE needs an active lane in the half and a uniform value or a waterfall loop;
- a branch on VCC needs a VCC holding EXEC's lanes;
- after a branch on EXEC or VCC (another way for a half only when none of its lanes is active), both ways keep
  that half's lanes inactive, pass no barrier, and leave every scalar register the merge reads the same.
Buffers with ADD_TID take the GCN lane from the invocation index in such a program.

76% of the 789 wave64 compute programs Boletaria runs qualify (603).

Demon's Souls, Boletaria (RTX 3090, 2560x1440 render, same exe with the proof off/on, ABBA 2+2): standing
22.9 -> 24.5 fps (+6.8%), walking out 21.5 -> 23.0 (+6.9%), walking in 22.3 -> 23.9 (+7.1%), turning the
camera 27.6 -> 30.8-31.0 (+12%).

lane_local_tests: 23 hand-assembled programs with the expected verdict; with files, the verdicts of dumped
shaders.
Demon's Souls streams textures through two big arrays, 0x1009000000 (352 MB, 256 layers,
11 mips) and the depth pool 0x102a400000 (320 MB, 80 layers), and maps, unmaps and fills one
layer's memory at a time. TextureCache::UnmapMemory freed every image that touched the
unmapped range, so each layer remap deleted the whole array: the next lookup created a new
352 MB Vulkan image and uploaded all of it again (copy of the whole range to the staging ring,
detile, copy), 45-110 ms on the execution thread at a time and a wait for room in the staging
ring behind it. In one 160 s walk after the load, 25 creations of the first array and 19 slow
uploads of the second: 58 uploads over 8 ms, 2.6 s of the execution thread, 26 of them over
50 ms, and the command processor waiting behind each.

Layered tiled images of 8 MiB or more (no metadata, not render or video-out targets, depth only
with one level and no D16 promotion) now take partial CPU writes. A write fault, a partial unmap
or a map inside them records the granule (256 KiB for writes, a page for maps and unmaps) as
dirty and stops watching just those pages, instead of marking the image dirty and unwatching
all of it; an unmap that does not cover the whole image no longer frees it. The refresh uploads
only the layers over the dirty ranges: the source is the guest bytes of those layers alone, a new
TileManager::DetileLayers pass detiles them into a packed linear layout
(ImageInfo::LayerRunLinearLayout) and ImageInfo::BufferCopiesLayers copies them to their layers.
Any other invalidation, images the GPU or a buffer wrote, or dirty layers covering more than half
of the image take the whole-image path as before. Memory mapped under such an image is reported by
a new TextureCache::MapMemory, run on the GPU thread only while some candidate image exists, as
the pages it maps are not protected whatever the tracking counts say.

Same walk after the change: 19 slow uploads, 0.7 s (7 over 50 ms); the first array no longer
appears, the pool uploads only the first time in full.
Demon's Souls binds about 48,000 buffer ranges a frame through
BufferCache::ObtainBuffer (a 10 % share of the execution thread).
Two things in it cost more than they had to:

- The sets of GPU-modified and checked ranges were std::map nodes, one
  per interval, tens of thousands of them: every Add, Contains and
  Intersects walked pointers that miss the cache (RangeSet::Add alone
  was 3.1 units a frame of the execution thread).
- 21 % of the calls are reads of texel buffers, which the read memo
  left out: each one went through SynchronizeBuffer and
  SynchronizeBufferFromImage, whose FindImageFromRange takes the
  texture cache lock and only matches an image that starts at the
  buffer's address, although no image is registered on that page.

RangeSet now keeps sorted blocks of up to 128 intervals with each
block's first address in a second array, so a lookup searches two short
arrays and a change moves one block's tail; its answers are those of the
map version (a differential run of 4 million operations on 50,000
intervals found no difference in results, gaps, final set or clamped
parts, and 211 ns an operation became 89 ns). The read memo now covers
texel buffers too, and SynchronizeBuffer skips the image lookup, while
no image is registered on the page where the range starts
(RegisteredPageCounts, checked again on every memo hit).

Demon's Souls Boletaria (uProf, 25 s a side, execution thread, units
a frame): RangeSet::Add 3.05 -> 0.95, Contains 1.79 -> 0.55,
Intersects 0.39 -> 0.18, FindImageFromRange 1.18 -> 0.06, ObtainBuffer
9.22 -> 8.22, SynchronizeBuffer 5.42 -> 4.02, SynchronizeBuffersInRange
3.45 -> 2.64: 7.9 units, 3.8 % of the thread; four ABBA passes a side
gave +4 to +10 % per stretch (each pass varies by up to 10 %). GTA V
Performance: execution thread 127,602 -> 127,538 cycles (uProf, 25 s),
ObtainBuffer -9 %; two ABBA runs gave 62.7 -> 54.7 and 60.2 -> 66.3 fps
(mean 61.5 -> 60.5: the machine's noise, with the uProf cost not up);
GTA V Fidelity 33.12 -> 33.39; ASTRO BOT gogo_walk 62.3 -> 62.3.
Demon's Souls (PPSA01341): the table draws and the scout thread of chenxiao07's fork read the game's tables (SRT slots,
V#s, T#s) from threads that must not enter the guest's fault handler, and prove them later against what read watchers
and mappings did meanwhile. This tree had none of the primitives for that:

- Common::GuardedCopy: a copy that stops at the first byte it cannot read (rep movsb; the access violation is resumed
  after the copy by the host exception filter, never reaching the guest's fault handler). The asm is a function-level
  statement, as the module-level one of his tree only assembles with -flto.
- PageManager::HasReadWatchers / ReadGranules / READ_GRANULE_BITS: a bit per 64 KiB granule (set before a page's read
  hint, cleared after the granule's last) that answers "no read watchers" with one load for most ranges.
- RenderContext::MappingEpoch / HasReadWatchers / ReadGranules (the names his GpuResourceManager has): the mapped ranges'
  version without the lock.
- Memory::IsFullyMapped, TryReadBackingToHost and TryReadGpuCleanBackingToHost (his names for the backing reads of host
  destinations).

Nothing calls them yet on the draw path; the read hints add one byte store per page of a read-watcher update. Boletaria
(uProf, one pass each, same scenario): execution thread 235.8 -> 227.3 units a frame, all threads 595.1 -> 583.9 (noise
level), GPU 18-21 ms a frame in both (19.3 / 20.8 / 19.5 / 18.3 / 19.4 -> 19.3 / 20.5 / 19.8 / 18.6 / 18.3), 21.2 / 19.7 /
20.9 / 28.6 / 28.2 -> 21.0 / 19.5 / 21.1 / 28.1 / 27.7 fps. GTA V Performance 43.5 -> 42.4 fps (GPU 8.7 -> 8.8 ms), Fidelity
(Trevor) 25.3 -> 24.9 (24.2 -> 24.9 ms), ASTRO BOT Go-Go 60 -> 60 (11.8 -> 12.6 ms); no fatal error or device loss.
Demon's Souls packs many CBuffers into the same 4 KiB pages, so a CPU write to one marks every neighbour dirty and the
tracker re-uploads all of them. The reference tree patches the two CBuffer allocation calls and the render-context call
of eboot 01.007.000 (cave plus 5-byte call redirection, checked by function fingerprints) so each CBuffer gets its own
pages.

Ported with KYTY_GPU_BUFFER_PAGES (his default is on; here 1 turns it on). Boletaria, uProf of the execution thread: hot
thread work 197.8 -> 186.3 (-5.8 %) with it on, GPU 19.2 vs 19.0 ms/frame, fps 26.4 / 24.9 / 26.4 / 31.3 / 31.1 against
26.4 / 24.7 / 25.5 / 31.4 / 31.3 (menu, still, walk out, walk in, spin): no visible change in the frame rate, so it
stays opt-in.
Demon's Souls moves 20-26 GiB per 300 frames in large memmoves, 73 % of those bytes equal to what the destination already
holds, and writing them marks the pages CPU-dirty (re-uploads, re-validation of every read log that watches them). The
reference tree replaces libc.prx's memmove (01.007.000, verified by fingerprint) with one that compares and writes only
the differing pages, going through the tracker's TryPrepareHostWrite / Overwrite / ImageWrite so GPU-written ranges are
brought back first.

Ported with KYTY_GUEST_MOVE_COMPARE (his default is on; here 1 turns it on). Boletaria: with the comparison hot thread
work 190.0 -> 183.1 (-3.6 %, GuestReadLog::StillValid 7.35 -> 5.54), but the frame rate is the same or 3 % lower
(26.1 / 23.9 / 24.7 / 30.0 / 29.8 fps against 26.9 / 24.5 / 26.3 / 31.1 / 30.8 with the hook installed and no
comparison). Opt-in.
The European 01.005.000 TouchManager unlinks a touch interval node from its swept list without checking its prev
pointer; a job worker's loop crashed on a node with prev and next 0 (eboot+0xd8c1f5, a write to 0x50 in "BPE
JobWorkerThread" after about 10 minutes of play). 01.007.000 checks prev first and goes on with the next entry. The same
check is patched into 01.005.000's loop (35 bytes from the load of next). Build-checked by pattern; a no-op on 01.007.000
(the Boletaria passes of this branch run it and see no change).

Ported from the chenxiao07 fork.
ResourceFactory's loading thread reads its priority lists without the lock of a request's removal: a node read between
the two steps of the removal (request cleared, then unlinked) went to the request handling with no request and crashed
(01.005.000 eboot+0x895822, within minutes of play for two European players). A node without a request makes the loader
wait until it is unlinked, or has a request again, for a second at most, then scan its lists again; a node that stays
linked to itself at the head of a list (nothing would move it while the loader holds the lock) makes the list rebuilt
from its last node backwards, as the 268 million scans of King Allant's fog (frozen game) needed.

Ported from the chenxiao07 fork.
Job workers crashed on null children in the scene tree while areas streamed in (01.007.000 eboot+0x8daff8, +0xb9d1e1,
+0xc5cabf, +0xc5a3be at "save and quit", +0x8db185), on a null object an event dispatch calls its listeners on
(eboot+0xc5845a at Latria) and on a physics job with no object to step (eboot+0x1ab6047). What writes the nulls is not
known. Each traversal here treats the null as an empty node (a find returns nothing, a visit visits nothing, a
collector returns its vector's count unchanged) and the first skips are printed with the registers that locate the
parent. Brings the host platform layer it samples threads with (src/local/local-platform, a plain copy of the
chenxiao07 fork's) and Loader::DescribeGuestAddressForDiagnostics.

Ported from the chenxiao07 fork.
Days Gone Remastered (PPSA28180) flickered in its main menu on an emulator whose execution
thread ran right behind the command processor: a frame or two of the scene doubled or squashed,
and the TAA history carried it for 10-45 frames. It never happened with the whole GPU inline
(upstream, KYTY_GPU_PIPELINE=0) or with the execution held back from the command processor.
Holding back only the callbacks of the COPY_DATA reference-clock packets (about eight a frame
into one page) cured it; holding back WRITE_DATA, DMA_DATA, the labels, the flips or the draws
did not.

WriteReferenceClock wrote the clock when the execution thread ran the packet, long before the
host GPU reaches that point, so the game read the CPU's recording times as the timings of its
GPU passes: short and uneven when the execution follows the command processor closely, long and
steady when it lags.

The clock is now read when the host GPU finishes the work before the packet. The write goes
through the priority completions, the way the labels of occlusion dumps do, and counts as a
deferred label so that the labels the game waits on follow it. The buffer is submitted after
each timestamp so that every timestamp has a tick of its own: the differences between them are
host GPU time. A destination that GPU work writes keeps the immediate write.
An unmap deleted no buffer: RenderContext::UnmapMemory only invalidated the cache, so the buffers over unmapped memory stayed in
video memory for good (the collector waits for a frame without BDA shaders, which this game never has): at 1-1, 151 buffers of
2.5 GiB after 12 minutes. Demon's Souls' page allocator is worse: it keeps the pages of a block it takes back mapped and hands
them to the next pool, so a buffer over a freed block stayed and joins grew the next ones over it (its GPU heap moves three of
its 120 MiB blocks at every world load; an 8 GB card with reduced texture streaming went from ~2 GiB of buffers to 3.1-3.4 in 40
loads, past the video memory budget).

BufferCache::DeleteUnmappedBuffers deletes the buffers an unmapped range holds whole; SplitUnmappedBuffers cuts a buffer mapped
in no more than half of its bytes to its mapped runs (new buffers with the bytes copied on the GPU); DropFreedRange does both for
a block the game freed and keeps mapped, reading back (or dropping, KYTY_ENGINE_FREE_BUFFERS=2) its GPU-written bytes first, with
the allocator's free block lists (FreeBlocksIn) deciding for buffers over several free blocks. Loader::DemonsSoulsPageFree
hooks the allocator's free (01.007.000 eboot+0x80f550, known builds by pattern) to tell the GPU caches (NoteGameFree ->
RenderContext::FreedByGame, queued for the GPU thread) and, with 16 GiB of RAM or less, walks the free lists every 2 s to give
blocks free for ~30 s back to the system (KYTY_ENGINE_FREE=giveback|walk|count|0). Brings the backing store helpers it needs
(TryGetBackingPieces, DiscardBacking on Linux, GuestRangeWatched, HostMemoryRangeIsReadable), src/local/slow-log.h and a
DropHotReadsBacking that has nothing to drop until the read-guard hot reads are ported.

Boletaria, one uProf pass and one NVML pass each (before: the commit before this one): 297 MiB of buffers over 5 freed blocks
let go in the pass, 24.8 ms of the GPU thread in all. Execution thread 201.3 -> 192.2 units/frame (-4.5 %), game-side threads
62.4 -> 58.5 ms/frame, GPU 19.3 / 20.7 / 19.8 / 19.3 / 19.0 -> 19.5 / 20.1 / 19.7 / 19.1 / 18.2 ms/frame (still, walking out,
walking in, spinning right, left): the time is the same; what changes is the video memory a long session keeps.

Other games (a counter in the unmap path, one pass of GTA V Rendimiento, GTA V Fidelidad with Trevor and ASTRO BOT gogo_walk
each; before = the commit before this one): GTA unmaps 6,600-8,600 times per 30 s and none of those ranges holds a registered
buffer, so no buffer is deleted or split (0 in 30 s windows of both modes) and the unmap path costs 0.2-0.3 ms of the GPU thread
per 30 s (ASTRO: 134 and 11 unmaps per 30 s, none with buffers, 0.02 ms); no DeviceLost, no validation message, no new warning in
the logs. Process CPU per frame and GPU per frame: GTA Fidelidad 224.3 -> 204.7 ms and 23.9 -> 24.0 ms (29.8 -> 32.9 fps), ASTRO
181.4 -> 183.3 ms and 11.6 -> 12.5 ms (60 -> 60 fps). GTA Rendimiento, six passes each alternated: 60.3 / 60.4 / 64.3 / 64.9 /
64.9 fps before, 52.0 / 59.3 / 57.6 / 65.8 / 62.7 / 63.1 after (process CPU 123.6 / 121.3 / 117.1 / 116.1 / 114.1 against 136.1 /
120.6 / 127.0 / 112.8 / 117.6 / 117.0 ms per frame, GPU 8.7-9.0 ms both): the machine's load moved the passes as much as the
change (the three latest pairs, 64.3 / 64.9 / 64.9 against 65.8 / 62.7 / 63.1), and the code that runs there is one lookup of
the registered buffers per unmap. src/local/slow-log.h's KYTY_HITCH_LOG_MS defaults to off.

Ported from the chenxiao07 fork.
Upstream's BVH mirror (RayTracing, gpu_bvh_mirror.comp) reads guest BVHs through the BDA page
table as they are at each call. This fork keeps its own BDA synchronization, which uploads the CPU
writes since the last synchronization only once a device-address reader comes after them
(RenderContext::NoteOperation()), so the mirror read the old bytes: BvhMirror failed at "relink".

RayTracing::Prepare counts as a device-address reader after the guest's writes (NoteOperation) and
synchronizes the page table itself (PrepareBda), as the dispatches that call it only do so for
programs that use DMA.
The pipeline manifest says how every module and pipeline of a title was asked for, but holds no
code: a module can only be built once the guest maps its shader. So the precompilation pause only
compiled what the game had mapped so far. Demon's Souls maps 3683 shaders before its menu, 2499
more when it loads its first area and the rest of the 7341 the manifest lists as other areas load:
the game stopped again for each batch (or, played at once, stalled on them).

A shader binary ends with a footer that sizes its program, whatever file holds it. A thread now
searches the game's files (its folder or archive) for such binaries and gives the manifest the
code of the listed shaders, by the hash the manifest names them with. To leave textures, audio and
video unread, a kind of file (an extension) is given up after 32 files or 256 MB without a shader;
large files are read in overlapping pieces. What the search finds and what the guest maps (shaders
inside compressed packages are only seen then) is kept in <title>_<version>.code, on this computer
only, so that later sessions have all of it from the start without searching; the files are
searched again only for listed code the last search did not look for.

With the code, the manifest builds all its modules and pipelines from the start, and the pause
that --pipeline-precompile already makes (the notice shows its progress) lasts until all of them
are compiled: while the store is read and the files are searched the work does not count as
done, and the game is not stopped before its first thread runs. Where nothing stops the game, the
shaders the guest has mapped go before those only its files hold.

Demon's Souls, first session with nothing cached (--pipeline-precompile wait): one pause of
266 s before the splash screen
(7341 shaders found in 1.5 GB of 14,347 files, 10,765 modules, 15,355 pipelines), and after it no
pipeline is created and no shader translated on the path of a draw or dispatch, in the menu or in
Boletaria; the frame rate there is that of a warm start. GTA V (shaders inside its RPF packages,
95 in the executable): the search takes 0.4 s, the pause is the one it had (46 s for 101
pipelines, 52 s for 85 before), in game after 99 s (106 s before).

Also: probe for the manifest's shaders the files that a sample of their kind left out.

GTA V (PPSA04263 01.011.001), first session: 1451 of the 1480 shader codes
the manifest lists are in the game's files, unencrypted, in update/update2.rpf
(540 MB, binaries between 3.4 and 47 MB), but the scan of the game's files
found 95, those of the eboot: the encrypted .rpf packages of the root use up
the sample of the kind, and update/update.rpf (3 GB, no shaders) comes before
update2.rpf. Resident Evil Village keeps its 501 listed codes uncompressed in
its .pak packages, 12.8 GB into one of 18 GB and 20 GB into one of 28 GB; the
scan read 256 MB of the first, gave the kind up and found 44.

While listed code is still missing, the files the sampling left out or cut
short are probed with a 1 MB window every 32 MB, and the stretch around a
window with shaders is read until 16 MB hold none. The scan ends as soon as
nothing listed is missing, and the log says what it found:

  [ShaderScan] game files: N shaders found (M of K listed by the manifest,
  X new), T s (F files, B MB read)

The record of what the last scan did not find carries the version of the
scan, so that the code an older scan missed is searched for again.

Also: leave a kind of file and a file out of the scan after a stretch without shaders.

SAROS (PPSA07631), first session: the scan of the game's files read its nine
.ucas packages whole, 145 GB, because the first one holds 17 shader binaries
and a kind of file that held one was read to the end; it found 44 of the 1032
codes the manifest lists. Ghost of Yotei (PPSA26344): the probes read 55 GB,
because its 46 000 .sps files and 10 000 .xpps shader packages are small and
each probe window took a whole file; the manifest's code was in the first
.xpps packages. In the emulator that is minutes of reading on the thread that
serves the game's own reads from a .zar, and the precompilation pause waits
for the scan.

A kind of file is now left out after 32 files or 256 MB in a row without a
shader, not only before the first one, and a file after 256 MB in a row
without one; what is left out goes to the probes. The probes leave a kind
after 256 files in a row that gave no missing code (Wolverine needs 120,
GTA V 24). Offline, SAROS reads 6.3 GB and finds the same 44; Ghost of Yotei
reads 2.5 GB in 22 s instead of 55 GB in 41 min and finds 350 of 370 codes
instead of 353; GTA V (three dumps), Resident Evil Village and Wolverine find
the same codes in the same bytes, and nothing changes in the other dumps
scanned whole (Demon's Souls, Control, ASTRO's PLAYROOM, the GTA trilogy).
The store was read one record after another on the main thread before the game starts: each
record's zstd frame, its resource plan and its Vulkan module. With the modules of a whole title
in it (Demon's Souls with its manifest built ahead: 13,625 modules, 324 MB) that took 6.2 s of a
warm start.

The records are now read on every thread and added to the cache in the store's order; a damaged
record still ends the store, and the modules read after it are destroyed.
A title is only compiled ahead of the game from what a manifest lists, and a manifest only exists
for the titles someone recorded with --record-pipeline-manifest. A title without one compiled
everything on the path of its draws and dispatches in every cold session: Demon's Souls without
its manifest, cold, spends 104-112 s there before and in its first area (179 compute pipelines
created by the GPU thread for 45 s and 126 waits for one for 41 s, 950 graphics pipelines created
or awaited for 22 s, 444 translations for 2.8 s; 2300 draws skipped), and the same again after
every emulator update.

A session that uses manifests now records its own too, into the same file a recording session
writes, which the next sessions load: what a session creates that no manifest lists is compiled
ahead from then on. Unlike with --record-pipeline-manifest the shader store stays in use: the
modules it loads were recorded when they were compiled, or are listed already.

Demon's Souls without its manifest, second cold session: one pause of 21 s at boot for the 1264
pipelines of the first session, in its first area after 79 s instead of 154-158 s, and 3.1 s of
compilation on the path of draws and dispatches instead of 104-112 s (20 modules and 31 pipelines
the first session had not used).
The execution thread copied every CPU-dirty page it uploads into the
staging ring itself. With shaders that read through device addresses most
of those uploads come from the synchronization of all cached buffers
(RenderContext::PrepareBda()): GTA V (PPSA04263) in Performance RT at a
downtown crossing uploads ~3,300 pages (13 MB) a frame there, for the ray
traced shadows of cs 48d704640ab9fb40 and three more compute shaders, and
the copies took ~50 ms/s of an execution thread that is the bottleneck
(~930 ms/s busy at 55-60 fps).

Hand them to the host copy thread, as the data draws stream already goes
(BufferCache::StreamGuestData()). The tracker protects the pages before
the upload is copied, so a later guest write still faults and marks them
dirty; the copies read the backing store; every submission waits for the
copies queued before it, and guest-visible effects and unmaps drain them.
Transfers that do not fit in the ring keep being copied in place.

Measured with both paths switched every 5 s in one run (execution thread,
ms/s): GTA V Performance RT, parked downtown: device-address
synchronization 288 -> 263, waits for the copy thread 0.4; Fidelity:
206 -> 190. The protection calls of the synchronization get slower with
the copy thread busy (+10 to +30 ms/s), which is why the gain is half of
the copy time. Performance mode has no such synchronization: unchanged.
The synchronization of everything device addresses may read
(RenderContext::PrepareBda()) uploads every CPU write under a cached
buffer and cleans the page, which protects it again. The guest rewrites
its per-frame data every frame, so each of those pages costs a protection
call on the execution thread and a write fault on a guest thread, frame
after frame. GTA V (PPSA04263) in Performance RT at a downtown crossing,
where four compute shaders with unbounded device-address reads (the ray
traced shadows of cs 48d704640ab9fb40 among them) run every frame: ~570
protection calls and ~2,300 write faults a frame; with the copies on the
copy thread the synchronization is ~240 ms/s of the execution thread and
~200 of them are VirtualProtect.

A page that faults again within three synchronizations of its last visit,
three times in a row, now stays CPU dirty: the synchronization uploads it
every time and does not protect it. That is the state of a page the guest
wrote right after a synchronization, so nothing else changes: draws that
bind it still upload and clean it, and so do the synchronizations of
declared ranges. Every twelve synchronizations the page is cleaned once and
stays dirty again only if the guest faults on it soon after. Only faults
count as writes (a fault also releases the pages up to the next 64 KiB
boundary, which are dirty without having been written). Pages the GPU ever
wrote are left out: uploading them would overwrite what the GPU stored
there, which guest memory only receives when a fault reads it back. A
synchronization runs for a new submission while pages are kept dirty even
if no page faulted since the last one.

Measured with both behaviours switched every 5 s in one run (execution
thread): GTA V Performance RT, parked downtown: synchronization
253 -> 202 ms/s, protection calls 605 -> 381 a frame, guest write faults
2,340 -> 1,557 a frame, uploads 15.8 -> 20.7 MB a frame, 60.7 -> 63.1 fps;
Fidelity: 171 -> 166 ms/s, 37.8 -> 39.4 fps. Longer windows keep more
pages dirty and upload several times more than they save.
BufferCache::SynchronizeBuffer() asks the tracker for the CPU-dirty pages
of the range a draw or dispatch reads. The tracker skips a region that has
no dirty page at all; for any other region it takes the region's lock, the
one the guest's page-fault handlers hold while they release a page. With
the guest faulting all over its memory that is nearly every region.

GTA V (PPSA04263) in Performance RT at a downtown crossing: of ~26,000
read-only buffer lookups a frame, ~10,400 miss the memo of
BufferCache::ObtainBuffer() (ranges that differ from draw to draw) and
come here; almost all of them read pages that are clean, and the calls
took 65 ms/s of an execution thread that is the bottleneck, part of it
spinning on locks held by fault handlers (~2,000 write faults a frame in
this mode).

Check the range's pages first, without the lock, as the lookups already do
to choose between a streamed copy and the cached buffer: a range without
CPU-dirty pages has nothing to upload.

Measured with both paths switched every 5 s in one run (execution thread):
the calls 65 -> 38 ms/s (0.11 -> 0.06 us each), the slow path of the
lookups 102 -> 76 ms/s.
A module had the stride of each of its buffers compiled in, so a shader that is given records of
several sizes, or records in one dispatch and a single element in another, needed a module and a
pipeline for each combination. In Demon's Souls' manifest 77 % of the extra variants of its
compute shaders (1821 of 2344, in 1675 of its 4035 compute shaders) differ in a stride only, and
within one session 80 % (163 of 203): its particle programs read their records from V#s whose
stride is the record size. Each is ~1 s of the driver, on the path of a dispatch when no
manifest lists it.

A buffer's stride can now be RuntimeBufferStride: the module reads the stride of the bound V#
from its shader data (a dword per buffer binding after the mip statistics fields, filled where
the bound ranges are), and one module serves the buffers of every stride, 0 included. Only the
plain strides of the buffers a program names itself and reads by element are read so; swizzled
strides, the candidates of indirect descriptors and zero-stride buffers with the bounds mode of
zero_stride_oob stay compiled in.

Only the compute programs that no manifest lists read them at run time: nothing says they are
given one stride only, and each stride would cost a pipeline on the path of a dispatch. Their
modules are recorded as they are, and the sessions that list those records build the same
modules. The programs a manifest lists with their strides keep them compiled in, with the SPIR-V
they had (GTA V with its manifest: every compute pipeline comes from the driver cache as before).

Demon's Souls without a manifest, first session, cold: 605 compute modules instead of 777 for
the same shaders, 82 s of compilation on the path of draws and dispatches instead of 112 s (57
compute pipelines created by the GPU thread instead of 179), in its first area after 130 s
instead of 158 s.
GTA V (PPSA04263) in Performance RT binds ~32,000 read-only buffer ranges
a frame in the city centre. The lookup memo is keyed by the exact range,
and ~11,300 of them a frame are ranges no draw bound before (each draw
binds its own piece of the vertex and index data and its constants, next
to those of the draws before it), so they took the slow path: the page
table walk for the buffer, the CPU-dirty query of the range and a memo
entry nobody reads again.

A read-only range that lies within one caching page is now answered by a
memo of that page: its buffer and which of its tracker pages had nothing
to upload when a lookup last checked (or uploaded) them, valid while no
buffer is registered or unregistered and no page of its tracking region
becomes CPU dirty, as the entries of the exact memo. The first lookup of
a page checks the whole page once. Ranges that cross a caching page keep
the exact memo.

Measured with both paths switched every 5 s in one run (execution thread):
lookups on the slow path 11,327 -> 2,012 a frame, read-only lookups
116.7 -> 93.0 ms/s.
GTA V (PPSA04263) skins its meshes on the GPU in Performance RT and
Fidelity: cs e777d90ed493bd6c, ad33aa3c0aae1311 and abb185d80e19fb9a, ~16
dispatches a frame. Each thread looks for the record whose thread range
holds it, reads its vertex through a device address (the base of a V# in
a table, picked by a field of the record, plus an attribute offset and
stride * vertex from other fields) and stores the result through another
V# of the table. Such addresses are neither a user-data base plus an
offset nor a V# table the host derives, so the programs were not DMA
bounded and each of their dispatches uploaded the CPU writes of all
cached memory: two full synchronizations a frame instead of the one of
the ray-traced shadows.

The decoder now recognizes such a program by its code
(Decoder::RecordReach): it matches the record search instruction by
instruction and follows the rest with symbolic register values, per EXEC
state, requiring every device-address read to be "table entry of the
record's pointer field + ((attribute + stride * vertex) & ~3) + n" and
noting the table entries its stores go through. Resource tracking keeps
the reach when it covers every access that left the program unbounded.
At the dispatch the host reads the header, the records and the table
from guest memory (only while the CPU wrote them last) and synchronizes
the vertex range of each record and the buffers its stores write. A
program, or a dispatch, that does not fit keeps the full synchronization.

Checked against the device-address use bitmap, read before and after
each bounded dispatch: 31,000 scans, 2.1 million pages used, none outside
the reach. With the reach switched every 5 s in one run: full
synchronizations 2.0 -> 1.0 a frame, their time 188 -> 165 ms/s of the
execution thread plus 10 ms/s for the reach.
Demon's Souls' deferred decals at Boletaria (~750 a frame) alternate a stencil
mark with a decal that samples depth, both with the depth target in the
depth-read-only, stencil-attachment layout. The target's tracked access went
attachment <-> attachment + shader read at every draw: ~1,500 image barriers a
frame, each of which ends the render pass (1,484 of the frame's 1,678), and
the GPU work the next frame's culling readbacks wait behind.

In a layout that keeps every aspect shaders can read read-only, the shader
reads and the attachment writes are of different aspects: Image::GetBarriers
records no barrier for that change and the image keeps both accesses (after
chenxiao07's 397112a04, decided by the layout instead of the sampled aspects).
The barrier between two decals that read and write the same storage image
stays.

Boletaria, with the next commit: standing 28.9 -> 31.2 fps, turning the camera
34.3 -> 40.4 fps; GTA V Performance 70.9 fps (70.2-72.2 before).
A guest thread that reads GPU results back takes a fault a page, and each fault
is two commands of the execution thread and a copy on the readback queue the
thread waits for. Demon's Souls reads the destinations of its engine's GPU
copies (cs 22e0328668b00aa3, ~1 KB each, with GPU-written sources) one after
another from one thread, ~60 of its ~100 readbacks a frame at Boletaria: 5 ms
of a 21 ms frame in which the execution thread waits for the game's next
submission, and 3.6 ms a frame of urgent commands on the execution thread.

The buffer cache keeps the pages guest threads read back by fault lately (up
to 512, for 16384 guest readbacks after their last fault). A readback on the readback
queue downloads those whose GPU writes are done with the faulting pages, as
their own faults would, in the same copy: they are published and leave GPU
ownership together and fault no more. A page whose writes are not done yet, or
that an image holds, keeps its own fault.

Boletaria, same pass with it off / on: standing 35.3 -> 38.1 fps, turning the
camera 36.0 -> 40.4 fps; guest readback faults 97 -> 24 a frame, urgent
commands of the execution thread 3.6 -> 1.4 ms a frame.
A pixel program instrumented for GET_LOD_STATS has a plain variant, for the draws
in which no image has a mip statistics counter, and a pipeline holds one of the
two. A game's draws use both: of the 1158 graphics pipelines of a first session
of Demon's Souls with no manifest, 522 were the other variant of a pipeline a
draw had asked for before, and each was compiled when its first draw came, which
was skipped meanwhile or waited for it.

When a draw asks for a pipeline that is not there and whose pixel program has
both variants, the pipeline with the other one is queued too, behind those that
draws wait for; a draw that asks for it while it is queued moves it among them.

Demon's Souls without a manifest, a first session with cold caches, up to 50 s
in Boletaria: of 632 such pipelines, 494 were ready when their first draw came,
31 were asked for while queued and 107 were not used. Draws skipped 2440 -> 1512;
graphics pipelines the draws created or waited for 958 (21.7 s) -> 577 (13.6 s);
in the level after 119 s instead of 130 s.
GTA V's Performance RT mode traces its shadows in cs 48d704640ab9fb40, once a frame. Its
device-address reads follow pointers (the TLAS, the instance records, each BLAS, the tables of
the alpha test), so its reach was unknown and the dispatch synchronized all cached memory. With
the skinning programs bounded it was the last full synchronization of the frame: ~170 ms/s of the
execution thread at 67 fps at a crossroads of the city (2,400 pages protected again per frame)
and ~350 ms/s of protection faults in the game's threads, for pages no device address reads.

The reach of such a program is known when the host built its TLAS:
- The patch gives the instructions whose accesses stay in the guest BVH: the traversal loop of
  each site (nodes, instance records, BLAS headers, tables and lists, and the indices and
  vertices of the leaf's alpha test) and, after the loop of a site that accepts any hit, the reads
  of the instance record of the hit. ResourceTracking counts them as covered, with the node tests
  and the ray query; the material table and the buffer table of each alpha test are buffers of
  the program (ShaderInfo::ray_query_reach).
- The native TLAS build tells the render context the memory of the TLAS and the BLASes of its
  instance list. sce::Psr's capture pass gives the memory of the BLASes the GPU builds or
  decompresses; the size of one the CPU wrote is in its header.
- A dispatch then synchronizes the TLAS, its BLASes, the BLASes its preparation may build (the
  preparation builds no other), the material table, the buffer table and the buffers its V#s
  describe. The table has 131,072 entries in GTA V (40,000 in use, 680 MB): its ranges are
  decoded again only when its bytes change, and synchronized by tracking region as a pass of the
  device-address synchronization over that set, which leaves the pages the guest rewrites every
  frame CPU dirty as a pass over everything does (a region with such pages is visited again by
  the next pass over everything or over the set, whichever passes ran between).
A TLAS the game built itself, a BLAS of unknown extent or a table the host cannot read leave the
dispatch with the full synchronization. So do the sites that keep the closest hit: cs
2f34bc2dfe6b04a3 (Fidelity) reads other memory through the registers of the result when it
traces natively.

Checked against the device-address use bitmap in a debug build: 447,623 pages used by the
bounded dispatches while driving through the city, none outside the reach; 2,990,796 in Fidelity
with the guest's own traversal forced, none outside.

Parked at the crossroads, with the reach switched every 5 s in one run: full synchronizations
1.0 -> 0 per frame, device-address synchronization 180 -> 90 ms/s of the execution thread, its
protection calls 325 -> 137 per frame (150 -> 55 ms/s), those of the game's threads 352 -> 23
ms/s, 66.6 -> 77.3 fps.

Also: bound the reads after the traversal loops of programs that trace rays natively.

In GTA V's Fidelity mode the closest hit programs cs 6aeb221de7ff018e and d645a5101b936ce7
shade their hit after the traversal loop: they read the instance record of the hit (its BLAS,
transform and material base), the BLAS header and the entry of its geometry table, the
vertices of the hit triangle, and its indices, texture coordinates and colors through the base
of V#s from the buffer table. Only reads within the loops (and, for sites that accept any hit,
the reads right at the registers of the hit) counted as within the reach of a program that
traces rays, so both programs, one dispatch a frame each, kept the synchronization of
everything by device address in every frame.

A device-address read of such a program is now within its reach when the high DWORD of its
address derives only from the hit of a site, from the TLAS header the sites trace, from what
other covered reads return, or from the base of V#s the program reads from a table of 16-byte
records (the host enumerates the buffers of that table as it does an alpha test's buffer table);
the low DWORD may add any offset, as the leaf code does. Where paths merge, a value takes the
base of the paths that have one: the registers of a site's result hold the hit only in the lanes
that have one, and the reads after the loop are those lanes' (or ignore what the others load).
The derivation is a fixed point over the program's values, so the loops that carry values
around are followed.

The buffer table of cs 6aeb221de7ff018e's alpha test is no buffer of the program (it reads the
table through device addresses): its V# comes from four slots of the flattened SRT
(ShaderInfo::RayQuerySrtVsharp).
The BLAS builds of sce::Psr read the vertices of a geometry through the V# at +8 of its record
in the geometry table (120 bytes each): GTA V's cs 2adee3faed27c152 loads it with
s_buffer_load_dwordx4 at index * 0x78 + 8 and reads the vertex buffer through it. The V# is not
at a base in user data, so the reach of the program was unknown and each of its dispatches (0.75
a frame while driving through the city in Performance RT, as BLASes stream in) synchronized all
cached memory.

A V# whose DWORDs are scalar reads of one record of a buffer of the program, at index * stride +
immediate, is a field of a table of records (ShaderInfo::dma_record_tables): the host
synchronizes the buffer of every record, from the table as the guest's CPU wrote it. The accesses
check the bounds of the V#.

Checked against the device-address use bitmap in a debug build, with the two other reaches of
the series: 447,623 pages used by the bounded dispatches, none outside.

Also: bound reads through V#s a program selects from a table of records by a shift.

GTA V's Fidelity mode runs cs b93ab2ec5c5caf00 every frame. It reads its index and vertex
buffers through V#s it takes from the game's buffer table, a bound buffer of 131 072 16-byte
entries, at (word >> 8) << 4, and on one path it picks one of two such entries, so the V#
DWORDs reach the reads through Phis. A table of records was only recognized with a multiply
by the record size and a single read per DWORD, so each of its 33 accesses left the program
without a known reach and every dispatch of it synchronized everything by device address.

A record offset may now also be index << log2(stride), and the three DWORDs may be Phis of one
block whose operands from each predecessor read one record of the same table. The host decodes
a table of 16-byte records with the V# at their start through the cached buffer table of the
alpha tests (its copy is compared, and its V#s decoded again, only when its bytes change),
instead of reading all of its records at every dispatch.
A buffer that takes its record count from a header the GPU writes (the nodes of a BVH in the
passes of sce::Psr, GTA V's cs c421273ce118f4a5) left the device-address reach of its program
unknown: the host does not know the count, and every dispatch synchronized all cached memory (in
bursts while BLASes stream in, in Performance RT and in Fidelity).

The buffer lies in the memory the library captured for the BVH at its base
(psr_morton_capture_memory, which the command processor follows): the dispatch synchronizes that
memory, and everything when the base is in no captured memory. The program is then bounded by
its windows and tables as any other, which the test of self-sized buffers no longer denies.
EA SPORTS UFC 6 (PPSA23566) loses the device on NVIDIA in the intro video
after the first-boot settings, with "3D WIDTH ZT Violation" graphics
exceptions (nvlddmkm event 13) right before the TDR. The game renders with
dynamic resolution: it keeps one depth allocation and programs DB_DEPTH_SIZE
with the extent of the moment (3240x1824, then 3248x1824: same address,
pitch and height). The wider target matches the cached 3240-wide image as an
equal-address overlap, and ResolveDepthOverlap returned that image as it
was, since its format, stencil and resources fit. The render area follows
the requested extent, so the draws wrote 8 pixels past the edge of the depth
attachment (the exception's x, in pixel pairs, is 1620 = 3240 / 2).

A depth target wider or taller than the cached image now gets a new image,
as a growing color view already does (ExpandImage), with the old contents
copied over. The outgrown image is freed instead of parked: a parked image
only comes back for its exact layout, and the larger image serves the
smaller extents, so it is recreated only when the extent reaches a new
maximum.
SAROS (PPSA07631) closed while booting with a write past the end of a mapping in its
"Foreground Worker" threads (pc 0x1ff0e1 of its eboot): a leaf function keeps its loop
count at [rbp-0x40], in the red zone under RSP, while it writes 28-byte records to a
buffer whose pages the emulator tracks. Each fault the emulator resolves there makes
Windows write the exception context below RSP, the count turns into garbage and the loop
runs off the end of the buffer (0x4000 records in 0x70000 bytes). The patcher moves such
accesses below the red zone, but it only analyzed the functions .eh_frame lists, and
SAROS lists 17617 of them for 111 MiB of code; this function is not one of them.

Find the others before patching: the code addresses that relative relocations store
(virtual tables, tables of function pointers) and, following the branches of every
known function, the targets of its direct calls and RIP-relative LEAs. Executable
segments hold no data, so all of them are function entries. SAROS's eboot goes from
17617 analyzed functions to 418991, 1006 of which use the red zone (123010 memory
accesses moved, 2.9 MB of trampolines).

The analysis only reads the original code, so it runs on up to 16 threads, in batches
of 256 functions, and only notes which functions have instructions to rewrite; the
trampolines and patches are then written on one thread in the same order as before, so
the result is the same byte for byte. Patching SAROS's eboot takes 2.7 s instead of 16 s.
SAROS (PPSA07631) closed on the screens after its first boot with "buffer descriptor is not
a valid runtime value" in cs bbd2706c785082e8. At pc 0x3d4 it stores records with
buffer_store_dwordx4 ... idxen through s[16:19] = {s3, s0 | stride 32, count, format} that
it builds itself, and at pc 0x3f0 through {s6 + 0x100, s1 | stride, count, format}: the low
dword of each base comes from one user-data register and the high 16 bits from another one
that is not the next register. Raw stores through V#s the GPU completes (Gran Turismo 7's
cs f0ff5e4576313e72) only took bases whose high dword is in the next register.

Record DMA bases as {low, high} register pairs and, when the low and the high dword of a
base each come from a single user-data register that is not the next one, take that pair
too. The host builds the base from the low dword and the low 16 bits of the high one: guest
addresses have 48 bits, and a V#'s dword 1 holds the stride above them.
Demon's Souls (PPSA01341): the table draws of chenxiao07's fork keep a draw's V#s, slot words and ring copies across draws
and prove them by "no byte of this range can have changed since". This tree's tracker epochs only moved when pages became
CPU dirty or GPU-written pages stopped being GPU dirty, so a proof by them missed what the emulator itself writes into
CPU-dirty pages (labels, WRITE_DATA, DMA copies, fills, completions, readbacks): stale tables and black flashes with the
table draws on.

- RegionManager::CpuModificationEpoch: the sum of the region's CPU-dirty, GPU-clean and host-write epochs;
  RegionManager::NoteHostWrite moves the last.
- MemoryTracker::CpuModificationEpoch (a range inside one region; 0 where nothing is provable) and NoteHostWrite.
- BufferCache::CpuModificationEpoch (up to 64 regions, 0 if any is untracked), NoteHostWrite, IsRegionCpuDirty and
  RegisteredBuffer (the registered buffer over a range, none registered: not FindBuffer, which makes one).
- Memory::NoteEmulatorWrite: every place the emulator writes guest memory (the scout's host-write sites) tells the tracker
  and the scout together.

Nothing here reads the epoch yet (the table draws do); the writes cost an atomic add per tracker region they touch.
Demon's Souls (PPSA01341) at Boletaria makes ~6,300 draws and ~1,500 dispatches a
frame, and the execution thread spends ~2.7 us on each draw of the normal path
(bindings prepared, buffers obtained, push descriptors, the resolve stage's
plan checked again): it is busy the whole frame and sets the frame rate.

chenxiao07's table mode, ported whole from his fork (952cbd9ca): a shader pair
that the normal path drew is compiled once more as a table program
(ir/passes/TableMode, the SPIR-V emitter's table block), which reads its user
data slots, flat SRT loads and V#s from a block in a ring buffer and its
images and samplers from one descriptor set per distinct T#/S# word set. A
later draw of the pair evaluates the slots into the block (TableEvaluate,
TableGather, TableBlocks), finds or makes the image set (TableSet, validated by
the texture cache's epochs and registrations), puts the targets and the set's
images in their layouts (NativeXprEmitTargets, TableTransit) and draws with
the block's address in the push constants: no bindings, no resolution ahead
and no descriptor writes. Runs of draws of one pair continue without looking
the pair up again; indirect draws read their records on the GPU; the pair's
state (targets, dynamic state) is captured from the normal path's draw
(DrawStateObserver, NativeXprCaptureState). TableDispatch does the same for
plain dispatches (KYTY_TABLE_DISPATCH, off: it saves nothing here). The scout
thread (scout.cpp) that evaluates draws ahead of a render thread that also
processes the command buffers is ported too, off by default (KYTY_SCOUT=1/2):
with this tree's pipelined GPU only a third of the draws got a ticket.

Adapted to this tree:
- buffers whose V# changes format between draws of a pair are specialized for
  no format and decode it at run time with upstream's indirect-buffer format
  functions (the V#'s fourth dword in the block), where his module decodes his
  BufferWord;
- table programs and their pipelines are made by the shader and pipeline
  workers (TableProgram::waiting, PipelineCache's asynchronous native variant)
  and the pair waits for them (his pair.waiting): creating them on the
  execution thread stalled 4.8 s when the camera turned;
- the resolve stage skips the draws of pairs that the table drew (TableHint),
  and keeps resolving for 120 frames those of a pair whose try was refused
  after one that drew (those cost 12 us without their resolution);
- this texture cache keeps a DCC fast clear in the metadata's bytes, not in
  the surface metadata his IsMetaCleared reads: a table draw whose color target
  or DCC texture has a fast clear pending (ColorClearSettled) takes the normal
  path, whose lookup applies it. The texture cache keeps the metadata ranges it
  found settled until an emulator write, a GPU write or a download reaches
  them (a color clear epoch, and a memo per target and texture). Without it
  the character at Boletaria lost his rim light: a DCC target cleared once a
  frame took ~200 table draws over the last frame's contents;
- a draw a table program cannot make, known before the try (stages other than
  a vertex program in the ES stage and a pixel program, or a pair refused for
  good under the shader map generation), takes the normal path without the
  try's preamble (pending operations, the context lock, the native XPR state
  and its key's hash, the pair's lookup). GTA V makes ~5,250 indexed draws a
  frame and none by table (~4,800 with other stages, ~470 of refused pairs):
  with the whole try on each of them its execution thread did 8 % more work
  (uProf: 113.5 -> 123.4 units a frame) and Performance went 44.7 -> 41.1 fps.
Not ported: his image serials (KYTY_TABLE_SERIALS, 0 here: the epochs decide),
the sweep of old draw states (NativeXprSweepStates), learning a portable
buffer from a refused set (KYTY_TABLE_LEARN_PORTABLE), the speculation
(KYTY_SPECULATE). His native XPR records by registers are in (nativeXpr.inc)
but off (KYTY_NATIVE_XPR=1): they draw the scene black or darken the walls
here. His counters and census (Spec::Refuse, LiveCounters, LiveCensus) are
empty functions.

Measured with the next commit (tickets) under uProf, the same script before
(without this series) and after, warm caches: Boletaria standing 23.2 -> 27.3
fps (execution thread 196.2 -> 171.7 units a frame, resolve stage 127.3 ->
94.0, GPU 17.3 -> 17.8 ms), turning 31.8 -> 31.4 (no gain), same image;
GTA V ingame30: Performance 44.7 -> 44.3 fps (execution thread 113.5 ->
114.0), Fidelity 28.0 -> 28.9.

The table mode is on for every game (KYTY_TABLE_XPR=2; 0 turns it off).

Also: evaluate table draws and dispatches ahead on the resolve thread.

Demon's Souls (PPSA01341) at Boletaria: with the table mode the execution thread
still evaluates each table draw's slots and V#s itself (TableEvaluate,
TableGather: ~13 units a frame of its ~150 in the uProf pass), ~1.8-2.0 us a
draw. chenxiao07's scout thread evaluates draws ahead of his render thread from
the command stream; with this tree's pipelined GPU (command processor, resolve
stage, execution thread) it got a ticket for only a third of the draws.

The resolve stage already sees every operation with its exact registers, ahead
of the execution thread. For a draw whose pair the table drew last
(TableHint), and for a plain dispatch whose compute stage the table dispatched
last (TableDispatchHint), it evaluates the pair's published view
(Scout::EvaluateAhead, the scout's own Evaluate) and the operation carries the
ticket (a ring of 1024). The execution thread applies it when it holds, with
the scout's proofs (the same user data and mapping epoch, no write by the
emulator or the GPU since to the pages it read, no read watchers on them), and
evaluates itself otherwise. KYTY_SCOUT=3 is the default (0 off; 1 and 2 are
chenxiao07's scout thread and its verifier).

Boletaria standing: tickets used for ~5,250 of ~6,300 table draws a frame
(845 lost to emulator writes on their pages, 202 without one), TableEvaluate
13.2 -> 1.9 units a frame, TableGather 2.9 -> 0, table draws 11.8 -> 11.0
ms a frame. Dispatch tickets (with KYTY_TABLE_DISPATCH=1): ~780 of ~900 table
dispatches a frame. The verifier compared ~4 M draw tickets standing and turning
and ~780 dispatch tickets a frame with the execution thread's own evaluation:
no difference. Table dispatches with their tickets (uProf, the same pass with
KYTY_TABLE_DISPATCH 1 and 0): standing 27.1 / 27.0 fps, execution thread 170.1
/ 171.9 units a frame, turning 31.2 / 30.5: nothing measurable, so table
dispatches stay off. GTA V draws none by table: its tickets cost nothing there
(KYTY_SCOUT=0: 41.2 fps, with them 41.1).

Also: let the draw states no draw used for a minute leave.

The native XPR cache keeps a draw state per key of every graphics register,
render target addresses included, and never erased one: entering an area of
Demon's Souls (PPSA01341) makes ~1,500 that are never used again (~2.8 KB
each plus their targets), so long play grows the heap with every area.

Ported from chenxiao07's fork (510b9d5d4, the half the table mode's port did
not bring: TableSweepPairs is in): a state no draw used for 3,600 frames
leaves, in a sweep every 600 frames once there are more than 2,048. What holds
one by its address forgets it then: the last emission, the last lookup, the
table's last draw and its image sets' transits (TableForgetStates). Not while
a speculation holds the catalog (none runs in this tree).

Also: address a table program's unswizzled buffers with the stride of their V#.

Demon's Souls (PPSA01341) at Boletaria 1-1: the cobbled walkway at the top of
the stairs past the first gate drew pure black, without fog or light, under
the debris on it (vs 014091f0494f85c9 ps 94a9d6370adf6400, a G-buffer material
that blends ten 2048x2048 layers; the user's save shows it at every load).
TableBufferSpecialized lets a pair's program take the unswizzled V#s of other
strides (KYTY_TABLE_STRIDES) and the renderer writes each V#'s stride into the
block, but the port's emitter left that word unread and indexed the buffer with
the stride the program was specialized for: the pair's draws whose V#s had
another stride read their records at the wrong offsets. As his emitter does, a
table program loads each buffer's stride from the block at entry and indexes
its unswizzled buffers with it. (Bisected by table pair: with only this pair
by table the walkway is black; with KYTY_TABLE_STRIDES=0 it is drawn.)

Co-authored-by: TheCruZ <[email protected]>
Demon's Souls, first session with cold caches: the scan of the game's files
found the code of the 7341 shaders the manifest lists in 1463 MB of files, but
it took 134 s, against 2-3 s for the same scan when it finds nothing: the code
store flushed its file to disk after each record (FlushFileBuffers, ~18 ms
each), and the precompilation pause waits for the scan.

A record that a crash cuts short does not read back and ends the file, so the
flush is not needed: records are written without it.
Silent Hill: The Short Message (PPSA10112) and Hi-Fi RUSH (PPSA17191), first
session: the scan of the game's files found none of the 763 and 612 codes the
manifest lists. Unreal Engine 4 keeps a game's shaders in shader archives
(ShaderArchive-*.ushaderbytecode) inside its package (.pak), stored there as
they are, but each shader in the archive is compressed with LZ4, so the
search for shader binaries sees none.

For each package (versions 10 and 11, with an index that is not encrypted),
the scan reads the index, finds the shader archives stored as they are,
decompresses each shader (LZ4 block format) and searches it; a loose
.ushaderbytecode file is read the same way. Silent Hill: 763 of 763 in 1.0 s;
Hi-Fi RUSH: 612 of 612 in 1.7 s. Packages whose entries are compressed (the
GTA trilogy, zlib) and the IoStore containers of Unreal Engine 5 (SAROS,
Code Violet, each shader group compressed with Oodle) are not read. GTA V and
Demon's Souls have no such packages.

Also: search the assets of Unreal Engine packages for the manifest's compressed shaders.

GTA III, Vice City and San Andreas (Definitive Edition, Unreal Engine 4.26):
the scan of the game's files found none of the shaders their manifests list
(0 of 598, 632 and 650). Their package (pakchunk0-ps5.pak) has no shader
archive: each material keeps its shaders in its asset (.uexp), each one an
array with its code compressed with LZ4, then its size and its stage, and
most assets are compressed with zlib in the package.

The package reader now also reads the assets (.uexp, .uasset, .umap, .bin)
stored as they are or compressed with zlib (inflated with stb_image's zlib
decoder, already linked), and finds those arrays in them: the footer's magic
survives the compression among the literals near the end of the code, so for
each magic that is not a footer in place the array that ends 44 to 112 bytes
after it, followed by a plausible size and stage, is decompressed and
searched. Only the assets of packages are searched this way, not every file.

Also: read older Unreal Engine packages through their index when searching for shaders.

Days Gone (PPSA28180): the scan of the game's files found 1567 of the 2345
shaders its manifest lists in 43.6 s, reading 11.7 GB. All of them are in
the clear in chunk1.pak (28 GB, package version 3, nothing compressed), in
the materials' packages (.uasset, up to a few hundred KB, which keep their
shaders inline) and in the global shader cache (.bin), but the samples of a
file that size reach only part of it.

The package reader now also reads versions 3 to 7 (the older index, with the
names and entries together; block offsets from the package's start before
version 5), and from any package it reads the global shaders (.bin) and the
assets stored as they are up to 512 KB (the materials, not the textures or
meshes; the assets compressed with zlib are read whole, as before, since GTA
III's keep their shaders in larger .uexp files). A package read through its
index is no longer sampled as well.

Days Gone: 2333 of 2345 listed shaders in 18.6 s, reading 10.0 GB. The other
packages read through their index are sampled no longer either: GTA III 505
of 598 in 8.1 s (876 MB read instead of 1269 MB), Hi-Fi RUSH 612 of 612 in
1.4 s (621 MB instead of 877 MB), Silent Hill: The Short Message 763 of 763
in 1.0 s. GTA V and Demon's Souls have no such packages.

Also: read the maps of Unreal Engine packages whole when searching for shaders.

Days Gone (PPSA28180): the scan of the game's files found 2333 of the 2345
shaders its manifest lists, reading 10.0 GB in 18.6 s; with 12 missing it
read every package to the end. Those 12 are in the clear in chunk1.pak too:
11 in one level (Cascade_AlwaysLoaded.umap, 13.7 MB, which keeps the
materials of its level and their shaders inline, 2.9 to 3.5 MB into it) and
one in a material instance of 555 KB, past the 512 KB the package reader
read of an asset stored as it is.

Maps stored as they are are now read whole, and other assets up to 1 MB
(chunk1.pak: 466 MB of maps, 1.9 GB more of assets); every listed shader is
then found within chunk1.pak, and the scan stops there.

Days Gone: 2345 of 2345 listed shaders in 18.2 s, reading 6.6 GB. Silent
Hill: The Short Message 763 of 763 in 0.8 s, reading 375 MB (before 1.0 s);
Hi-Fi RUSH (612 of 612, 1.2 s) and GTA III (505 of 598, 8.2 s) read the same
as before. GTA V and Demon's Souls have no such packages.
Red Dead Redemption (PPSA30528), first session: the scan of the game's files
found 32 of the 494 codes the manifest lists, those in eboot.bin. The other
shaders are in game/shaders.rpf, whose entries are compressed with zstd, so
the search for shader binaries sees none.

Every zstd frame that begins and ends in what the scan reads (frames are
recognised by their magic, whatever holds them) is decompressed, up to 64 MB,
and searched. Red Dead Redemption: 493 of 494 in 1.3 s, reading the same
1085 MB (738 MB decompressed offline). GTA V and Demon's Souls have no zstd
frames in their files and find the same.
Demon's Souls (PPSA01341) copies ~60 small results a frame (500 B to 30 KB) with the engine's cs_memset32 program
(a Replicate fill whose period covers its count) from memory the GPU wrote, and a game thread then reads each
of them back: a fault, an urgent command on the execution thread, a copy on the readback queue that the
faulting thread waits for and a second urgent command, ~55-80 us each, one after another from the thread
that submits the frame. With the followers of the readback queue ~24 such faults a frame are left.

chenxiao07's copy feedback, ported from his fork (fbe29c51f, 57231d9ed, in their 952cbd9ca form): after an
identified small GPU copy into guest memory (BufferCache::ScheduleCopyFeedback, up to 64 KiB) the destination
is copied into one of 512 slots of a download buffer behind it. A guest access to bytes a snapshot holds,
once the copy completed, is served from it in the first urgent command (TryGuestReadFromFeedback): the
GPU-written bytes of the pages are published from the snapshots, all of them or nothing, and the pages
leave GPU ownership as a readback's do; the whole snapshot goes with it, whose other pages would fault one
by one. Any later GPU write over the range (BufferCache::NoteWrite), upload (NoteUpload), image download into
the range or the buffer's removal invalidates the snapshot; a snapshot of memory unmapped since is never used;
a readback in flight over the pages keeps the normal path.

Adapted to this tree: his trigger is his Demon's Souls copy-shader replacement (DemonsSouls::TryLinearCopy by
shader hash); here the generic Replicate fill recognition does it: when the CPU cannot replicate (the source
holds GPU writes) and the period covers the count, the program is a plain copy of count dwords, which
BufferCache::CopyBuffer makes on the GPU without the dispatch, and the snapshot follows it. The slot's host
read gets its own barrier (DownloadBufferMemory's), where his Buffer::CopyFrom took access masks.
Not ported: the batched snapshot copies of KYTY_FEEDBACK_BATCH (his note: it fires only under KYTY_SPECULATE=4)
and the verify of the eager write-back (KYTY_EAGER_FEEDBACK_VERIFY).

KYTY_COPY_FEEDBACK=0 turns it off.
Turning the camera in Demon's Souls (PPSA01341) at Boletaria, a stack sampler puts ~17 % of the execution
thread in NtProtectVirtualMemory (uProf's user-mode cycles do not see it), most of it the write protection
MemoryTracker::ForEachUploadRange(s) gives back to the pages each upload of CPU-written buffer bytes marks
clean, one call per run of pages, on the thread every draw waits for.

chenxiao07's async reprotect, ported from his fork (476ae208b): while an upload consumes CPU-dirty pages
(BufferCache::SynchronizeBuffer(s), MemoryTracker::UploadScope) the pages take their tracking state but the
host protection of the ranges is recorded (PageManager::SetDeferredWriteProtectSink) instead of applied.
BufferCache::UploadCopies queues it on the host copy thread ahead of the copies, which read the backing store:
a guest write before it lands in the copy, a write after it faults as before. Until it is applied the region
proves nothing (RegionManager::CpuModificationEpoch is 0, BufferCache::DeferredProtectionPending is true for
the table draws' clean-range proofs); applied (PageManager::ReapplyProtection: the watched pages' state at
that time), it moves the region's epoch.

Adapted to this tree: his upload worker is our HostCopyQueue (a call job in order with its copies). When not
every copy of the upload reads the backing store (or the staging is not in the ring the copy thread fills),
the protection is applied on the calling thread before the copies; a copy made on the calling thread of a
later upload in the same synchronization waits for the protections queued before it.

KYTY_ASYNC_REPROTECT=0 turns it off.
Nearly every draw repeats the programs, T#s and S#s of an earlier draw: in
GTA V's Performance mode about 93 % of the ~5,900 draws a frame bind what an
earlier draw of their kind committed, in Demon's Souls about 80 %. Each still
looked every T# up again (the description map, ReuseTextureLookup() reading the
image), acquired the views again in RebindImages() and transited the images in
CommitBindings(): about half a microsecond of the 2.5 us the execution thread
spends on a draw.

With KYTY_DRAW_TEMPLATES=1 (off by default) the resolution ahead keys each draw
by the programs, T#s, S#s and bindless tables of its stages; the execution
thread adds the pipeline and the target images and keeps, per key, the image
and sampler bindings as the draw committed them: the views in their read
layouts, the samplers and the version of each image. A later draw of the key
takes them without reading any image. Once its buffers are found, an image
whose version moved, or over whose range an image was registered or
unregistered, is looked up and acquired again, and the template is stored
again. Only images the commit left in their read layouts, that the draw does
not render to or write, and that are not depth images, their copies or their
color twins take part; stages with bindless tables, the image heap, storage
images or views by mip keep the current path.

Per draw on the execution thread, GTA V Performance: 2.25 -> 2.16 us (66.9 ->
68.2 fps). PrepareBindings goes from 0.36 to 0.19 us and CommitBindings from
0.38 to 0.29 us, partly given back to the template lookups and checks; the key
costs the resolution thread 0.1 us more per draw. Demon's Souls (Boletaria):
RebindImages 0.45 -> 0.13 us.

Also: key draw templates by the draw's registers and take its pipeline and targets from them.

With KYTY_DRAW_TEMPLATES=2 the resolve thread extends a draw's resource key
with the registers its pipeline, targets and bindings derive from: the
context registers but those only dynamic state reads (viewports, scissors,
blend color, depth bounds, depth bias values, stencil masks and references,
user clip planes), the user configuration registers but the index offset
and object id, the shader stage registers but the user data addresses, and
the vertex input layout. The context and user configuration keys are hashed
once per register snapshot id. In GTA V Performance mode 93 % of the
template lookups hit with this key.

The execution thread finds the template by the state key, the target
images, topology, primitive restart and pixel program variant. A template
keeps the draw's pipeline, so a hit skips GetGraphicsPipeline(). While the
draw reuses the render target memo's targets and every target image keeps
the version (layout and access) the template recorded, the draw takes the
rendering state, feedback aspects and attachment states the template
recorded instead of acquiring its targets again.

Draw templates off (default) and KYTY_DRAW_TEMPLATES=1 are unchanged.

Also: share read-only buffer views between the stages of a draw.

With state templates (KYTY_DRAW_TEMPLATES=2), RebindBuffers() reuses the
storage buffer view an earlier stage of the same draw obtained for the same
read-only range, alignment and view kind instead of looking the buffer up
again: nothing that runs between the lookups of a draw's stages changes what
one finds. The vertex and pixel stages of GTA V's draws often read the same
constant ranges (about 7,500 shared views per frame in Performance mode).

Also: push the descriptors of template draws with update templates.

With state templates (KYTY_DRAW_TEMPLATES=2), the first draw of a template
whose stages bind the template's images records its push descriptor writes
as the data of a descriptor update template: images and samplers in place,
and a slot for each buffer binding kind of each stage. Later draws of the
template copy that data, put their own buffer views in the slots and push
it with vkCmdPushDescriptorSetWithTemplateKHR instead of building the
descriptor writes again. Update templates are shared by pipeline layout and
entries. Draws that bind GDS or table state, need descriptor copies or slot
set writes, or run without push descriptors keep CommitBindings().

The deferred command recorder copies the data into its stream. It passes
the copy as a const void*: vulkan.hpp also takes the data by reference to a
value of any type, which recorded the address of the pointer and crashed
the driver.

GTA V Performance mode, 30 s in game, KYTY_DRAW_TEMPLATES=2 with the two
commits before against =1: the execution thread goes from 2.24 to 2.02 us
per draw and from 65.5 to 72.3 fps; 94 % of the template hits push the
template's descriptors and 66 % take the template's targets. Demon's Souls
(Boletaria) stays the same within noise: few of its draws are resolved
ahead.
Demon's Souls (PPSA01341) at Boletaria: its ~10 job threads fault ~80 times a frame on memory the GPU wrote
(the results of cs 78ba7ec89e620596, 9c63c492870cd001 and the engine's copies), and each fault sends one or two
urgent commands to the execution thread. GuestGpu::RunUrgentCommands() drained the host copy queue before every
batch of them, so a faulting thread also waited for the copies (and, with the async reprotect, the page
protections) queued since the last guest-visible effect: 2.9 % of the execution thread's samples while turning
the camera, on the path of the threads that build the next frame.

Only maps and unmaps need the drain: they change memory that queued copies may still read. A readback fault
does not: those copies read CPU-dirty pages, not the GPU-written ones the read releases, and the GPU work the
read waits for was submitted after them (every submission waits for the copies queued before it).
SendUrgentCommandSync() takes `drain_copies` (default true); the readbacks of the buffer cache and the lazy image
flush pass false, and RunUrgentCommands() drains only when a command it took asks for it (deciding after it took
them, so a command queued after the drain no longer runs without it).

Stack samples of the same scene before and after (the job threads summed; sampler running): standing still
33.3 -> 33.9 fps, the job threads' waits for urgent commands 16.5 -> 15.5 %; turning 34.7 -> 36.1 fps, 25.8 ->
20.6 %; the drain left the urgent commands (2.9 % -> 0 of the execution thread) and part of it moved to the
next guest-visible effect. GTA V (PPSA04263, uProf): Performance 48.6 -> 49.1 fps, execution thread 105.2 ->
102.6 units a frame; Fidelity 32.5 -> 32.2 fps, GPU 23.7 -> 22.7 ms a frame.
Hollow Knight: Silksong (Unity): the scan of the game's files found 7 of the
72 shaders its manifest lists. A Unity Shader object (2021.3 and later) keeps
each platform's code in a blob compressed with LZ4, in chunks whose offsets,
compressed sizes and sizes come just before it, so no footer is seen in the
files.

Files that may be Unity's (.bundle, .unity3d, .assets) are now read as such:
a serialized file whose types include Shader (class 48), or each one in a
bundle (UnityFS) whose blocks are stored as they are, is searched for those
blobs, and each chunk is decompressed and searched. Silksong: 7 -> 68 of 72
listed shaders, in 3.5 s instead of 0.7 s (2603 MB read instead of 546 MB);
games without those files do not change (GTA V 1451 of 1480 in 1.8 s, Demon's
Souls 7341 of 7341 in 4.2-4.3 s).
In GTA V's Fidelity mode four dispatches a frame that trace rays (cs 0b41af19bddf132c,
2f34bc2dfe6b04a3, 6aeb221de7ff018e, d645a5101b936ce7) and cs b93ab2ec5c5caf00 take the reach of
the game's buffer table: the table is compared with its copy (its pages checked for CPU writes and
uploads) six times a frame, and the buffers its 131 072 V#s describe are synchronized four times a
frame, about 0.45 ms of the execution thread each.

The full synchronization by device address already relies on what the guest's CPU writes after a
synchronization waiting for the next submission or wait (a new BDA generation), unless buffers are
registered or ranges mapped in between. The comparison of a buffer table and the synchronization
of the buffers it describes now follow the same rule: once in a generation and layout, until the
table changes. Half of the set synchronizations and two thirds of the comparisons go away: the
execution thread spends 37 ms/s less (722 -> 685 ms/s of operations; the reach of the dispatches
96 -> 76 ms/s), and the guest's threads 44 ms/s less protecting pages.

Also: compare only the pages of a buffer table that the CPU wrote.

In GTA V the operations that trace rays with alpha tests read the vertex
and index buffers of their geometry through a buffer table (2 MB, 131 072
V#s). Its copy was compared with the guest's whole, once a BDA generation,
when any of its pages was CPU dirty or had been uploaded since the last
comparison, which was almost always (other buffers share its pages, and
the game writes a page of it now and then): 4 MB read a frame in
Fidelity, 14 ms/s of the execution thread.

The page tracker now keeps a record of the written pages for each of its
users (the indirect write tables had the only one), and the comparison
takes only the pages written since the last one: a few hundred bytes a
frame. Tables that share pages pass the pages they take to each other.
The buffer table takes 1.8 ms/s in Fidelity in the city.
In GTA V Performance mode the resolve thread is the next limit after the
execution thread: it spends ~1.95 us per draw choosing programs and walking
the SRT of ~5,700 draws a frame, ~785 ms/s at 68 fps. With the execution
thread's work ablated (draws skipped after resolution), the resolve thread
saturates at 912 ms/s and the frame rate stops at 81.5 fps.

KYTY_RESOLVE_HELPER=1 starts a helper thread (pinned to core 0, the last
free core of the first CCD) that resolves some of the draws. The resolve
thread still takes every operation in order: it reserves the draw's slot of
the resolution ring (ReserveResolvedDraw(), state Pending), hands the draw
over while the helper has fewer than two pending, and the helper resolves
into it (ResolveDrawInto(), Ready or Failed). The execution thread waits for
a Pending resolution before it uses or releases it (WaitResolvedDraw()).

Walks ahead could not run on two threads:
- GetAhead() held the program lock for the whole walk. Programs are added
  under the lock and never removed and a program found ahead keeps its
  resource plan, so a thread that resolves ahead with scratch of its own
  (BeginAheadThread()) now takes the lock only for the cache lookups.
- The resource plan's walk and materialization scratch (srt_scratch,
  material_keys, selector_keys) is mutable state of the plan: two walks of
  the same plan overwrote each other's captures, and a draw read a texture
  range from the other walk's V# ("unsupported texture data range" at boot).
  Each such thread gets scratch slots of its own (PlanScratch()).
- The buffer ranges earlier resolutions write, which later walks do not
  read control flow from, were thread-local to the resolve thread. The helper
  takes only draws of programs the resolve thread saw write no buffers, and
  copies the resolve thread's ranges as of the draw it was handed under a
  sequence count (SyncAheadWrites()). Draws resolve on the resolve thread
  while WRITE_DATA bytes that walks ahead must read are pending.

GTA V Performance mode, the same save, one pass each: with the execution
thread ablated, 81.5 -> 128.5 fps (the helper resolves 45-70% of the draws).
Unablated the frame rate is the execution thread's (68.1 and 67.1 fps), with
the image unchanged. Off by default: without the variable the resolve thread
holds the program lock for the whole resolution as before.
Demon's Souls (Boletaria) issues ~6,600 DRAW_INDEX_INDIRECT packets a frame, mostly runs of packets with the same
registers and draw initiator whose data offsets jump between records. The command processor merged only packets whose
offsets step a constant stride, so the runs became ~3,460 operations a frame, and each one that a shader pair's table
programs draw (tableXpr.inc) costs the execution thread a table try: its pending operations, the context lock, the
native XPR state and the evaluation of the pair's table.

Following chenxiao07's native XPR runs (TryNativeXprDraws: up to 64 following packets with the same other words, any
data offsets), a pair whose last table try drew it (TableHint) now takes such a run as one operation, ~2,700 a frame.
The operation keeps the packets (GpuDrawIndirectArgs::run_offsets: read when it executes, as WRITE_DATA's data), the
table try takes each record at its packet's offset and groups the records that follow one another into multi-draws as
before, and a run the table refuses draws its records one by one (or on the CPU). Other pairs, all of GTA V's, keep
the constant stride. The CP asks the table only once a table try drew a draw, and the operation keeps its size (the
index type is a byte).

Demon's Souls, Boletaria standing still: frame 27.8 -> 25.7 ms in the GPU pipeline timeline (execution thread idle
4.1 -> 3.1 ms, GPU busy unchanged), 36.7 -> 38.9 fps; spinning, about the same.
In GTA V's Fidelity mode the operations that trace rays synchronize the
buffers their device addresses reach: the buffers of the buffer table's
set (the vertex and index buffers its 131 072 V#s describe: ~5 000
pieces, in a pass twice a frame) and ~150 spans each (the BLASes of the
TLAS). Each piece and span went through the page tracker on its own. Only
~550 pieces a frame have CPU-dirty pages, and each of those took its
region's lock, built its copies and protected its pages alone (~1 us
each): the set took 38 ms/s of the execution thread.

The CPU-dirty pages of a region are now read once, only the pieces of the
set (and the spans, sorted and merged) over them are visited, and the
buffers found go through one pass of the tracker together, which protects
the pages of each region with one call per run. Three in four of the
~1 800 runs of CPU-dirty pages a frame in the regions of the set lie
outside it: the pages of each region under the set are kept with it, and
only the dirty ones among them are looked up. The execution helpers visit
regions too: their dirty pages, which the guest's threads write, are
mostly cache misses.

The set takes ~21 ms/s instead of 38 (one batch 38.1 -> 30.6, the pages
under the set 32.8 -> 29.2, the helpers 28.2 -> 20.9), the spans 9.6
instead of 10.6 (Fidelity in the city).
In GTA V Performance mode an AMD uProf profile of the execution thread
put ~2% of its samples in the standard library's vectorized minimum
search (__std_min_8u): std::min over an initializer list of 64-bit values
calls it out of line for every uniform view of a draw's buffers
(RebindBuffers) and for the sizes of sentinel buffer descriptors
(FindBuffers). Native XPR draws (Demon's Souls) take the same out-of-line
maximum for the alignment of their dynamic offsets.

Nested two-operand minimums and maximums give the same values inline.
In GTA V a draw binds ~4.3 distinct small read-only buffer ranges (frame, pass and object
constants), and each binding went through BufferCache::ObtainBuffer(): ~37,600 calls a frame
in Performance mode, most of them stream uploads of a few hundred bytes (each with its GPU and
CPU dirty checks, a stream buffer map and commit) or memo lookups, all dominated by cache misses
on the tracker and memo tables. The ranges of one draw mostly sit next to each other.

With KYTY_DRAW_BUFFERS=1 (off by default), before the stages bind their buffers, the draw
gathers its read-only ranges of up to 16 KiB (not written by a stage of the draw, not under
pending occlusion counter dumps, not formatted reads that may take an image's data). Those an
earlier draw of the draw window copied to the stream buffer (the stream memo of ObtainBuffer())
bind to that copy; the others are sorted and each cluster of them (gaps up to 4 KiB, spans up to
64 KiB) is copied from the backing store to the stream buffer with one copy, from the 256-byte
boundary below it so the offsets keep the alignment of the addresses, and noted in the stream
memo. A cluster the GPU modified, or without one backing run, binds as before.

GTA V Performance (same build, resolve helper on): ObtainBuffer calls drop from ~37,600 to
~12,400 a frame and the storage buffer bindings from 0.56 to 0.15 us a draw, for ~0.17 us a draw
of gathering and copies; half the ranges are already in the stream buffer, and the copies take
~7 MB a frame (17 MB without the memo). Without the fine accounting, draws take 1.99 us instead
of 2.08 on the execution thread, which is busy 13.49 ms a frame instead of 13.86, and the game
runs at 72.6 fps instead of 70.8. ASTRO BOT (PPSA21564, Sky Garden): ObtainBuffer calls drop
from ~45,000 to ~14,900 a frame and the buffer bindings of a draw from 0.95 to 0.68 us.
SAROS (PPSA07631): the scan of the game's files found 44 of the 1032
shaders its manifest lists, reading 6.3 GB in 11.3 s. Unreal Engine 5 keeps
its shaders in the shader libraries of its IoStore containers (.utoc and
.ucas): a library chunk lists groups of shaders, each another chunk
compressed as a whole with Oodle (Mermaid), and every group of SAROS is
compressed. The emulator carries no Oodle decoder, but the game links one in
its own code (Oodle 2.9, statically in eboot.bin; no module of its own).

The scan now reads an IoStore container through its table of contents
(versions 3 to 8, not encrypted; blocks stored as they are, or compressed
with Oodle, zlib or LZ4; partitions _s1.ucas...): each library chunk, then
each of its groups, decompressed, instead of sampling the .ucas. Oodle
streams go to the game's OodleLZ_Decompress, found in the programs loaded
at start as the one function (by .eh_frame) that refers to two of its
messages ("asked for len 0", "decoder memory given, but too small"), with
no title or build in the code. It is called on the scan's thread once the
programs are relocated, with fuzz safety, the exact size, no dictionary and
2 MB of decoder memory, so that it neither allocates nor logs through the
game; the thread first commits 256 KB of its stack, as guest code has no
Windows stack probes. SAROS, Code Violet and NHL 27 have the same decoder.

SAROS: 1031 of 1032 listed shaders in 9.5 s, reading 1.4 GB. GTA V (1451 of
1480, 2.0 s) and Demon's Souls (7341 of 7341, 4.3 s) have no IoStore
containers and do not change.
ASTRO BOT (PPSA21564 01.019.000): three of the shaders its manifest lists
that the scan of the game's files did not find, taken from the code a
session mapped, are in eboot.bin byte for byte. A shader binary is its
program (the code, aligned, and the literal buffer), then a section and the
footer; the section begins 16 bytes aligned, so a program whose literal
buffer leaves it unaligned is followed by 4 to 12 bytes of padding. The
search placed the program right before the section, without the padding,
and hashed bytes 4 to 12 bytes off.

The program now begins the aligned size of the program and of the section
before the footer. In the files measured every unaligned program had its
padding, and the aligned span finds every program the old one found.

ASTRO BOT: 647 of 993 listed shaders found (before 641); GTA V: 1453 of
1480 (before 1451); Demon's Souls: 7341 of 7341, as before.
NHL 27 keeps the shaders of one bundle in a group at 635-638 MB of a 1 GB
.cas file, 23 MB before the next group (661-744 MB). The probe windows at
608 and 640 MB fall outside it; the one at 672 MB hits the second group
and its run begins where the window before it ended, at 641 MB, so the
13 listed shaders of the first group were never read.

When a run finds code the manifest lists, read back from where it began,
in pieces, until as many bytes as a run needs to stop hold no shader (or
up to what the file had been read to). A run that finds nothing listed
does not do it, so complete games and runs over unrelated data cost the
same as before.

Scan line of the first session (listed found, MB read):
- NHL 27: 1079 -> 1096 of 1172, 9645 -> 9945 MB.
- UFC 6: 552 -> 557 of 698, 6126 -> 6198 MB.
- GTA V: 1453 of 1480, 3783 MB, unchanged.
- Demon's Souls: 7341 of 7341, ~1490 MB, unchanged.
ScatterUploadBatch() built its job list in a local std::vector grown by push_back and then
copied it into the staging buffer. A batch holds up to 65,535 jobs of 32 bytes, so each flush
reallocated megabytes on the heap: in ASTRO BOT (PPSA21564, Sky Garden) the BDA
synchronization of its indirect dispatches spent ~5 % of the execution thread in the heap's
search for large free blocks (RtlpFindEntry, RtlpInsertFreeBlock), with ~0.1 instructions per
cycle.

The jobs are now counted first (with the same checks) and written straight into the mapped
staging buffer: the same jobs in the same order, without the list. ASTRO BOT, Sky Garden (one
pass before and one after): indirect dispatches take 414 us instead of 431 and the execution
thread is busy 29.5 ms a frame instead of 30.3.
NHL 27 and UFC 6 keep their data in .cas files of up to 1 GB (205 GB in NHL 27). The scan of the
game's files found their shaders by probing a window every 32 MB of each file: the shaders a patch
updated go in groups of 4-7 MB in the patch's .cas files that no window hits, so NHL 27 had 1096 of
the 1172 shaders its manifest lists after reading 9.9 GB in 20 s.

Frostbite indexes its .cas files: Data/layout.toc (and Patch/layout.toc) lists the superbundles and
the install chunks, the folders of the .cas files, by a persistent index; each superbundle's table
of contents (.toc) lists its bundles, and each bundle the place in the .cas files of its metadata and
of each of its entries. The metadata gives the types of the bundle's res entries; the shaders are the
res entries of the type whose entries are named shaders/bytecode/, each one block stored as it is.

When the game has a layout.toc, its tables of contents are read, the bundles with most entries
first; of each bundle, the header and the res types of its metadata, and then its shader entries,
those one after the other in a .cas file in one read, until 256 bundles in a row gave no listed
code. The .cas and .toc files are not searched otherwise.

First session, the scan's line: NHL 27 1161 of 1172 listed (was 1096), 2.5 s (was 20.2 s), 761 MB
read (was 9945 MB); UFC 6 565 of 698 (was 557), 1.6 s (was 13.4 s), 656 MB (was 6198 MB). GTA V
(1453 of 1480, 2.1 s) and Demon's Souls (7341 of 7341, 4.3 s) have no layout.toc and do not change.
The execution thread waited for the host copy thread before every operation other than a draw, so that the guest
could not overwrite the sources of queued copies once it saw a label, an interrupt or a flip. A dispatch is no such
effect: the submission that carries it waits for the copies on the recording thread anyway. Since the uploads of the
full device-address synchronization go through the copy thread (~1 MB each in Demon's Souls at Boletaria, ~15 a
frame), the dispatch after one waited ~230 us for them, ~6 times a frame: 1.4 ms of the execution thread standing
still and 1.1 ms while turning.

Only callbacks drain the copies now. The guest memory a dispatch may write on the CPU in place of the GPU (fills,
replicated patterns and copies of BufferCache) waits for the queued copies right before the write, as those copies
may read it.

Demon's Souls, Boletaria (execution thread, ms per frame, before -> after): standing still 22.4 -> 21.4, turning
19.9 -> 18.1; the waits left move to the callbacks (0.05 -> 1.16 standing still).
Experiment launches the emulator with the draw templates (KYTY_DRAW_TEMPLATES=2), the second resolve thread
(KYTY_RESOLVE_HELPER=1) and the per-draw block of small read-only buffers (KYTY_DRAW_BUFFERS=1), which are off by
default while they are tested. Original clears the three, also when the launcher's own environment has them.
Two classes mirrored guest BVHs into host acceleration structures:
RayTracing, whose pair mirror serves the traversals the ray query pass
rewrites, and NativeRayTracing, which serves the traversals the native
ray tracing patch recognizes (GTA V, ASTRO BOT, ASTRO's PLAYROOM, Gran
Turismo 7, Marvel's Wolverine, Resident Evil Village) and the command
processor's sce::Psr replacements (TLAS builds, BLAS refits and builds).

They are one class now, RayTracing, owned by the render context. The
code of the slots, the arena, the walks and the sce::Psr replacements
moves to rayTracingSlots.cpp as members of RayTracing; nothing it does
changes. The render context constructs the class on every device, as
it did NativeRayTracing (it reads guest TLASes on the CPU to cache their
memory even without native ray tracing), so the pair mirror creates its
pipelines at its first Prepare(), which only programs rewritten by the
ray query pass call.

Also: trace the ray query pass's traversals through the native ray tracing slots.

There were two host mirrors of guest BVHs behind --native-rt: the (BLAS, subtree root)
pair mirror of RayTracing::Prepare(uint64_t) (gpu_bvh_mirror.comp), for the loops the
ray query pass rewrites, and the slots of the native ray tracing patch (rt_tlas_walk.comp,
rt_blas_walk.comp), which GTA V's ray tracing passes trace through. Both kept host BLASes,
TLASes, readbacks and an eviction policy of their own for the same guest BVHs.

The ray query pass's traversals now trace the slots too, and the pair mirror is gone:

- Prepare(tlas, frame) records a walk of the slots with the "PSR_BVHL" header at `tlas`
  (TlasSource::header, layout word 3 bit 30, RayTracing::PsrHeaderLayout). The TLAS walk
  then takes the instance records in order (format 1, 3, 6 or 10 as the header says;
  record i is instance i) instead of walking box nodes, keeps each record's
  object-to-world matrix, and skips the instances the guest never hits (no BLAS, an empty
  root or mask) and those without a host BLAS (AABB instances, BLASes not 64-byte
  aligned).
- The context stays exact for these traversals: it is valid only once every visible
  instance has a built host BLAS that the verification found unchanged, otherwise the
  program's own loop walks the guest BVH. Their BLAS signatures also cover the list entries
  and vertices of the leaves (a refit may keep every box), the verification clears the
  context when it finds a change, a changed BLAS is walked again instead of gathered, and
  the root box check that drops triangles of nodes being rewritten does not apply (the
  rewritten loop tests every candidate itself). The patch's traversals keep publishing at
  once as before (GTA V: a new or changed BLAS a frame late).
- The emitters of the pass read the patch's context entry (valid at +36, TLAS at +8, slot
  infos at +24, instance array at +40): a candidate's prim record and the barycentric remap
  of its triangle come from the entry table of its slot, the instance record from the
  instance index. TriangleEntry() and GuestBarycentrics() take the query, so the patched
  programs' SPIR-V does not change.
- Unused host BLASes go after RayTracing::EvictFrames frames, as the patch's do.
- The patch's walks keep the guest's loop for when the host has no structures for their
  TLAS. The ray query pass leaves the programs with patch sites (RayQueryInit) alone, so
  that one program reads one context: its walks over 32-bit nodes nested under a TLAS
  walk took the loops GTA V's update 01.005 keeps under its closest hit sites.

BvhMirror's GPU test traces the slots: build, refit (only a vertex moves: the first call
must find it), relink and eviction in header formats 1, 3 and 10, a Trinity format 10 TLAS
left alone; RayQueryTraversal is unchanged and passes over them.

Also: name the native ray tracing hooks after the native walks.

The host hooks of native ray tracing still spoke of the patch of decoded programs, which the IR
walks replaced: RayTracing::PatchShaders() is now NativeTraversals(), and the pipeline cache, the
pipeline manifest, the buffer cache's ray counts and the TLAS walk speak of native programs and of
the programs with the guest's walks (the variant of a dispatch without a TLAS).

PrepareNativeRayTracing() stays apart from the ray query pass's PrepareRayQuery(), and says why: that
one writes its context address into the shader data that RebindBuffers() uploads, so it runs before
it; this one reads the TLAS header address from the flattened SRT that RebindBuffers() uploads, with
the dwords GPU work wrote, so it runs after it.
The native ray tracing forms of the IR pass (IR::TraceNativeTraversals)
had tests with real programs only for ASTRO's PLAYROOM's wave-wide
closest hit walk and Gran Turismo 7's walk with any hit functions. A
change of RayQueryTraversal.cpp, which follows upstream's pass, could
leave a walk of the other forms to the guest's traversal with every test
passing; in the game it only shows as an "[RT] ... no form recognizes"
line and the cost of the guest's walk.

TestRayTracingNativeWalks compiles one real program of each of those
forms as the game does with --native-rt and checks the number of sites,
the TLAS source, the instance record layout, the ranges of guest code
that stay in the BVH and the ray queries in the SPIR-V, which validates:

- GTA V's Fidelity, cs 2f34bc2dfe6b04a3 (wave-wide any hit walks without
  the alpha test) and cs 0b41af19bddf132c (with the material's alpha
  test), 01.011;
- its Performance RT, cs 48d704640ab9fb40 (per lane BLAS walks), 01.011;
- its short rays, cs 84ed00053b3771da (01.005), and reflections, cs
  6aeb221de7ff018e (01.011): closest hit walks, opaque and alpha tested;
- Resident Evil Village's cs be0b848d2e06ec9b (alpha test of the entry
  tables);
- Marvel's Wolverine's cs b790bfb6f776e13a (any hit walk over a stack of
  node and lane mask pairs, wave32).

The expected values are those the decoded patch derived for these
programs, with Resident Evil Village's node count at the TLAS header's
+0x80. The programs, 892 to 7128 dwords, are in
ShaderRayTracingPrograms.inc.
ASTRO BOT's ps 9833d01b08e21d08 and ASTRO's PLAYROOM's ps 29289be6a0202b6d
walk the TLAS for a packet of lanes and each BLAS with the whole wave, as
the other wave-wide closest hit walks, with rays whose origin is the same
in every lane. The decoded patch traced them ("recognize guest BVH walks
whose rays start at the same point in every lane"); the IR pass left them
to the guest's traversal, for two reasons:

- The loop restores the exec mask in each round and copies the origin
  from SGPRs into the box test's VGPRs in those lanes before each test,
  so the lanes and the origin of the box test are values of the loop
  (Select(lanes, origin, -1)), not of before it. MatchPacketWalk now
  takes the lanes of the first round (EntryLanes: PathEntry through the
  selects whose condition it decides and the ands of the same lanes) and
  the copied values.
- A switch before the walk sets the TLAS header's user data pair s[0:1]
  to other user data pairs in the cases that sample a texture and leave
  the program. The structurizer joins those cases with flags, so the
  address of the header load is a tree of phis of four pairs.
  DeriveHeaderSource now takes, for an address that is not a user data
  pair, the one value of each word that reaches the load (ReachingValue:
  the incoming values of the phis whose edges the branches into the load
  and into each edge do not rule out): s[0:1], as the patch did.

Both derive the patch's site, TLAS source (s[0:1] + 0x28, root 0x25),
layouts (9833d01b: 76543210 1dc6ba98 000dbb8f 000f2510; 29289be6:
d951c840 4c25ea62 30482080 308f2511) and reach. The other 102 programs
with BVH tests of the dumps (GTA V, ASTRO BOT, ASTRO's PLAYROOM,
Wolverine, RE Village, Nightreign, Ghost of Yotei; wave32 and wave64),
Wolverine's 1a04c58a9fbc2052 and Gran Turismo 7's expanded program keep
their sites, TLAS sources and byte-identical SPIR-V, with and without
native ray tracing.

Both programs are pixel shaders, and the walks are traced only in compute
programs, so the game does not use this yet. TestRayTracingNativeWalks
checks them compiled as compute programs, without validating the SPIR-V
(a compute stage has no exports).
In ASTRO BOT (PPSA21564 01.019), Downsize Surprise, the ceiling of the
secret room that the mouse form reaches flickered with occlusion queries
on; with --no-occlusion-queries it stayed.

The game draws a bounding box for each object between two ZPASS_DONE
dumps, with the depth test on and depth writes off, and draws the object
only when its box counted samples. The boxes of that room lie on the
surfaces already in the depth buffer: the host's exact depth test failed
every sample of the ceiling's box, its query read zero and the ceiling
was left out, until a later frame passed it again. The console's depth
block counts ZPASS samples conservatively unless DB_COUNT_CONTROL sets
DISABLE_CONSERVATIVE_ZPASS_COUNTS, which the game never does (it writes
0x11000100 and 0x11000102), and such a box still counts there.

While a guest query counts, a draw that tests depth without writing it
and has no depth bias of its own is now moved toward the viewer by 64
units of the depth format and one unit of its depth slope, on the normal
path and on table draws. The state a table draw captures stays the
guest's: table draws take the bias when they are emitted while a query
counts.

Checked with the user at the spot, with switches that are not in this
commit: reading every query as visible, turning off the depth test of
those boxes or biasing them removed the flicker; turning off their
stencil test, depth bounds test or culling, scaling the counts, the
table mode, and the ordering changes (readers and command-processor
writes waiting for the GPU, dumps dropped under later writes, the flip
waiting for every dump) did not.
Demon's Souls, cold: while the game boots and loads, the threads of the pipeline manifest and the
helper processes translate its shaders and have the driver create its pipelines ("Pipeline
manifest: 655/2508 modules, 1282/5778 pipelines (813 modules wait for their shaders) at 2.0 s")
side by side with the game, which runs slower until they are done: for minutes in Demon's Souls,
less in ASTRO BOT. Nothing on screen said so: the pipeline notice only comes up when the game is
stopped for them, when its GPU work waits for one, or when one takes long.

Show a small bar in the bottom-right corner, over the notice when both are up: "Preparing
pipelines: performance may drop until they are ready.", the share done, and the pipelines and
shaders left. Its work counts shaders translated and pipelines created alike, from when the work
began, against what is left now (queued modules and pipelines, helper jobs, what the manifest's
threads run); not against the manifest's totals, which list pipelines whose shaders the game has
not mapped yet, or never maps, so the bar would never fill. As in the notice, the total grows
when the game maps more shaders. The bar comes up once there has been work for 1 s and goes after
2 s without any (Demon's Souls maps its shaders in batches: one bar for the batches that follow
each other closely); not while the game is stopped for the pipelines, whose notice shows that
progress, and only with a manifest.

The precompilation thread, which already reads the manifest's backlog and the helpers' counts
every 100 ms, decides it; the present thread reads three atomics. The bar does not keep the
overlay refreshing on every vblank as the notice does (for a game that may be stopped): it is
drawn on the frames the game presents, and the overlay is repainted once when it shows and once
when it hides. No path per draw or dispatch changes.
SAROS (PPSA07631) in PS5 Pro mode closed at boot with "buffer descriptor is not a valid
runtime value" in cs 12070dfbb803ca3b at pc 0x2d8: buffer_atomic_or ... idxen through
s[24:27], which a uniform branch on user data s2 builds either from {s6 + offset, s1 |
stride 4} or from {s3 + offset, s0 | stride 4}, with a record count it loads. The shader
also adds into counters through such V#s. Accesses through V#s the GPU completes only took
loads, and raw DWORD stores whose base is in user data (Gran Turismo 7's cs
f0ff5e4576313e72); atomics went to the failure.

Take raw 32-bit integer atomics wherever such V#s take raw stores (bases in user data, V#
table stores, self-sized buffers): the atomic runs on the guest memory through its device
address, marks the page written and returns the old value, or zero where no cached buffer
backs the page, as the indirect loads read it.

Two cases the base search did not see in this shader: a V# whose dwords are Phis of one
block now takes the base of each incoming edge, and the low dword of a 64-bit sum,
difference, AND or left shift only follows the low dwords of its operands. Compiled for
wave32, the shader offsets {s3, s0} by the low dword of S_LSHL_B64 {loaded dword, VCC_HI},
and VCC_HI (the initial s15) was taken for part of the base.

Only a V# with a dword that derives from memory the shader reads counts as one the GPU
computes: this shader and Gran Turismo 7's load their record counts. A V# built from user
data alone, such as the merge of two user-data V#s a loop carries, stays the host's to bind,
and fails when no single buffer is carried (TestLoopExitAtomicBindsCarriedBuffer).
Demon's Souls (Boletaria, after ~20 min of play): the stone floor under
the player turned black while debris and grass kept drawing. Its pixel
shader 3f7b19201073e188 picks one of the eight T#s of its material block
by a byte of a vertex attribute. The host cannot see the attribute and
reads all 32 T#s the selector can reach; past the eighth come the
block's sampler, its constants and leftovers of older T#s. One of them
read as a 1D T# next to the 2D arrays of the real ones,
BuildResourceSpecialization() failed with "indirect image table at pc
0x000000fc has incompatible candidates" and the floor draw was skipped
every frame ("[HACK] draw or dispatch with unresolvable resources
skipped") while that material block lived.

In the last zone of Boletaria (m02_03) a second form skipped six more
shaders (0d4527aa959ca0d1, e733fb1c7474ac30, 503037057cade3df,
f2d2a73f22800e83, 0789276a30486bf4, 4758f30aeb525d2d...) about 110
times a second each: their 32-key domain wraps to key 0xffffffff, whose
T# the shader's U32 arithmetic places 0x1000020c0 bytes past the table,
in memory nothing maps, and the failed read failed the whole draw.

The shader selects neither: the GPU would fault on the second, and the
first cannot take the coordinates of the instruction's 2D array. A table
offset past 4 GiB is no longer read and reads as null, as out-of-range
byte keys already do. A candidate read from guest memory for a T# that
is only sampled, whose dimension cannot take the coordinates of the
first typed candidate, reads as null when that candidate has the
dimension of the instruction and it reads fewer address components than
the instruction supplies (a 2D T# under a 1D sample would read one the
sample does not), as the slots of another dimension of a
bounded table already do. Explicitly selected T#s, other accesses,
candidates of another conversion format or swizzle, and reachable
candidates of an unsupported format still fail the draw.
SAROS (PPSA07631) walks a sce::Psr TLAS whose header address is a user data pair itself, its
high word cut to 16 bits (cs 0697eb9d76b3160b: s_pack_ll_b32_b16 of the pair, no load). The TLAS
source of the native ray tracing forms only took header addresses the program loads from memory
at the user data pointer, so with --native-rt none of its walks traced on the host: "[RT]" counted
896 dispatches that walked the guest BVH and none through host TLASes.

The source now says so (ShaderInfo::UserDataRayQueryHeader as the header offset), resource
tracking no longer looks for a read of the header there, and the host takes the low 48 bits of
the pair as the header when it prepares the TLAS, caches its memory before the dispatch and
checks the guest header. The ClosestLane walks of cs 0697eb9d76b3160b now trace natively;
TestRayTracingNativeWalks checks the program.
SAROS (PPSA07631) traces its visibility rays with a flat walk (cs 0035a11651ca7301 and
050c80c3de19f034, wave32): one loop and one intersection take the TLAS and, from the instance
records, the BLASes, each lane on its own stack in LDS and scratch; the first triangle a lane hits
within a fixed t max ends its walk, which keeps the hit's distance and primitive word. The code
after the walk reads only those. With --native-rt none of it traced on the host ("[RT]": the walk
the patch does not recognize, last cs 0035a11651ca7301).

That is the form the ray query pass's recognizer of flat walks (Match) takes, after resource
tracking, for records of format 1 and 3 and a closest hit extent. Before resource tracking it now
also takes the loop carrying the TLAS header >> 3 in its phis, records of format 10 (the BLAS >> 3
in 54 bits at +48, the instance mask in bits 24..31 of the flags) and a fixed t max (an any hit
walk), and asks only for the phi of the primitive word; after resource tracking nothing changes. A
native form of such any hit walks (Flat) derives the instance record layout from the walk's code
(the world to object matrix from the object space ray its instance nodes give the ray phis), runs
the guest loop on no lane whose host query traces, and gives the code after the walk the host's
hit: every triangle opaque, both facings. TestRayTracingNativeWalks checks cs 0035a11651ca7301.

SAROS's closest hit flat walk (cs 192d8cd7fb8773d8, with the facing of the instance flags) and its
wave-wide walks with two copies of the leaf list loop (cs 2fa6b5a3b15e54d4) still walk the guest
BVH.
SAROS (PPSA07631) traces rays that keep the closest hit with the flat walk of its visibility rays
(cs 192d8cd7fb8773d8, wave32), whose t max shrinks to each nearer hit: one loop and one
intersection take the TLAS and the BLASes of sce::Psr format 10, and the code after the walk reads
the hit's distance, its primitive word, its triangle node and the address of the instance record.
A triangle counts when its distance is finite and nearer and, on the lanes that cull, when its
facing (the sign of the intersection's numerator) is the one bit 3 of the instance flags selects,
unless bit 2 takes both; the walk sets those flags at an instance node to dword 13 of the record
>> 22, the bits above the BLAS. With --native-rt the walk ran on the guest BVH ("[RT]": programs
whose BVH walk no form recognizes).

The native form of flat walks (Flat) now also takes closest hit walks. Before resource tracking
the recognizer of flat walks keeps the phis of the node and of the instance record where one phi
alone carries each, and the leaf's accept condition gives the facing test: the instance flags of
the layout (the record dword and the shift the flags phi takes), whether the test flips the
facing, and the lanes that cull. The host query keeps the closest hit and gives the code after the
walk its node and instance record too. TestRayTracingNativeWalks checks cs 192d8cd7fb8773d8.
SAROS (PPSA07631) shades its Nanite geometry (the floor of the first area)
with dispatches it builds on the GPU, Unreal's shader bundles: after the
visible pixels are binned by material (cs e77d6586fff358d3,
ffa9920cc930b822, da869f9de8f33148), cs 7c991e9d4e6cbb3c (ordered append)
compacts the dispatch packets of the non-empty bins into a command buffer
the CPU fills with one-dword NOPs; the guest then waits for it
(CS_PARTIAL_FLUSH, PFP_SYNC_ME) and calls the buffer. The pipelined
command processor parsed the call long before the execution thread had
recorded the compaction: it read only the NOPs, no shading dispatch ran
and the floor stayed black, its depth (EmitDepthTargets) hiding the meshes
behind it. With KYTY_GPU_PIPELINE=0 it was drawn.

As the prefetch parser does after PFP_SYNC_ME, an indirect buffer (or a
branch's) fetched after one now waits until the operations emitted before
it executed, and the bytes of the buffer the GPU wrote are read back before
it is parsed. Without a PFP_SYNC_ME before the fetch nothing changes.
SAROS, waking up in the first area: the floor is textured and lit again
(24 fps; 25-27 before, without that shading).
SAROS (PPSA07631) runs three wave-wide walks in one program (cs 2fa6b5a3b15e54d4, wave32): a TLAS
walk and a BLAS walk of scalar nodes over sce::Psr format 10, whose leaf code keeps the closest hit.
A branch on the instance flags before the leaf list takes one of two copies of its loop, each with
its own triangle test: one keeps the nearest hit of both facings (bit 24 of record dword 13 set),
the other the nearest hit of the facing bit 25 selects. Each copy writes the distance as
min(t, T) where the hit is finite (and of that facing), and the primitive word where it is also
nearer. With --native-rt the walks ran on the guest BVH ("[RT]": 252 dispatches every 10 s of
programs whose BVH walk no form recognizes, last cs 2fa6b5a3b15e54d4).

The recognizer of wave-wide BLAS walks (MatchWaveBlas) now also takes a box test with two triangle
tests in two loops, and ClosestWave reads the facing of such a walk from its two copies
(LeafFacingCopies). The branch's record bit is "both facings", and the other copy's test gives the
facing bit and whether it flips. Each copy's writes must hold exactly where the hit is finite,
nearer and of the facing (min(t, T) counts as written where T is nearer). The values read after the
walk are those the copies write (HitResults with their conditions). LeafFacing's test of a record
bit moved out of it (RecordBitTest) to serve both. TestRayTracingNativeWalks checks
cs 2fa6b5a3b15e54d4.
SAROS (PPSA07631) traces the same TLAS, whose header is the user data pair, in four to five
programs a frame (cs 0697eb9d76b3160b, 0035a11651ca7301, 192d8cd7fb8773d8, 2fa6b5a3b15e54d4 and,
every other frame, 050c80c3de19f034). Each preparation of the host TLAS lists the built BLASes the
TLAS uses and checks them against the guest's (ModeVerify), walking all their boxes again: 0.64 ms
of the GPU per preparation, 2.9 of the 3.0 ms a frame the preparations took. With --native-rt the
game ran slower than with its own walks (24.9 against 26.4 fps in the first area).

A TLAS whose header is the user data pair is known on the CPU: its BLASes are now checked at its
first preparation of a frame, and in a preparation that gathered slots (the check takes their
boxes). A BLAS the guest changes later in the frame is found in the next one, and then built before
every preparation as before. The TLAS walk lists the slots the TLAS uses in every preparation (their
last use), and the check takes them only when the push constant asks for it. In the same scene the
preparations take 0.94 ms of the GPU a frame instead of 3.0.
SAROS (PPSA07631) in PS5 Pro mode lost the device ~20 s after boot (~80 s with the intro
videos): the GPU hung in cs 4a2181e0b7db95a7, the refit pass of its kTrinity BVHs (one
dispatch per BVH, 770 at load), in its loop over the primitive records of a leaf. The
earlier passes of each BVH (cs bbd2706c785082e8, 5d9d0b6be7ee2238, 12070dfbb803ca3b) write
lists and counters into scratch memory at user data {s3, s0} through V#s they compute from
offsets in the BVH header: ~140 KiB past the base for most BVHs, up to ~10 MiB for the
largest ones, whose scratch the guest maps on its own. CacheDmaBases() cached 16 KiB after
each base: past it the stores recorded faults and were dropped, and the next passes (cs
ba6fc85f77dc1520, 4234bd3f182d2b20) took zeros from those lists for primitive indices.

Keep the user-data bases of raw stores and atomics through V#s the GPU computes apart from
the DMA bases of FLAT accesses (ShaderInfo::vsharp_base_registers) and cache the mapped
memory that follows them without a gap, up to 32 MiB: the scratch of one BVH. A fixed window
falls short: 1 MiB still lost the stores of four BVHs (up to 3 MiB past their base) and 8 MiB
those of one (10 MiB). The scratch pages no longer fault and the refit ends. FLAT bases keep
their 16 KiB window, gaps included.

Only programs with such V#s change; GTA V has none (its shader corpus translates to the same
programs).
SAROS (PPSA07631) in PS5 Pro mode lost the device when it loaded its first level: the GPU
hung in cs 97b4ff9a6c61e171, a persistent work queue (1440 groups take items until a count of
pending items, in a 52-byte buffer the dispatches before it set, reaches zero), every wave
waiting at its barriers or for queue entries. The game keeps those counters in memory that
also holds the HTile of a 256x256 depth target, and the dispatches that set them (cs
35572da77b0da985, 0x34 bytes; fc7df1c43a90ec63, 4 or 8 bytes; b598b1f93bb1a8df and
4c3981a5cf2d2292) or zero 4 KiB there (cs 64027fcc947425e5) write a buffer that starts at
that HTile. TryConsumeComputeMetaClear() took any dispatch with a written buffer at a
metadata address for a clear of the whole metadata and dropped all of its stores: the
counters kept stale values and the queue never ran dry. Normal mode lays out its memory
differently and hit none of them.

Replace a dispatch by a metadata clear only when every buffer it writes is metadata and each
covers a whole slice of it (the metadata size of the image that owns it over its layers, when
that image is known), and then clear them all. The HTile clears of SAROS (cs
64027fcc947425e5 and 6561730ac5dd9232 over the 32 KiB or 384 KiB of a target) are still
consumed.

What changes for every game: a dispatch that was consumed and now runs is one that writes
less than a slice of the metadata at its address, or also writes a buffer that is not
metadata (in SAROS, an append in cs dde1af5f1e2a7dab whose 128 KiB list starts at an HTile
while its counter is elsewhere). Before, its stores were dropped and the whole metadata
marked clear; now they reach memory and the metadata keeps its state. Dispatches that only
read metadata, or that it consumes as a clear, behave as before. ComputeMetaClearClassification
checks that a dispatch that writes metadata and another buffer runs.
PrepareBda synchronized every cached buffer over all the mapped ranges whenever an epoch moved (a CPU-dirty page
anywhere, a buffer registered, a range mapped), and the first program of a submission whose device-address reach is
not bounded paid for it all. Demon's Souls (PPSA01341) runs 14 such compute programs a frame at Boletaria
(cs a6c5ba75568fdc37 and a8ae237bf9b2f438 pay for most of it): 11-16 full synchronizations a frame, 3.3-4.3 ms of the
execution thread, half of what its ~1,600 direct dispatches cost, in the part of the frame the game waits for before
it can send its draws.

chenxiao07's tree keeps BDA region requests instead: a tracker region's mapped, registered ranges with the proof (the
region's CPU modification epoch and its registration epoch) that they were synchronized, so a preparation skips every
request whose region did not change, and a dirty bit per region (bdaDirtyRegions.h) that a guest thread's write sets
and the execution thread sees from the next submission or met WAIT_REG_MEM on (BdaDirtyRegions::Publish, where
RenderContext::NoteOperation starts a new BDA generation; the execution thread's own writes are visible at once). A
program's BdaReadPlan (the memory its loads through device addresses can reach, from the user data and the flattened
SRT, built from its IR) lets a preparation visit only the regions of the ranges it reads.

Ported: BdaReadPlan.{h,cpp} (CompiledShaderInfo::bda_read_plan, serialized with it), BufferCache::
SynchronizeRegionRequest / RegionRegistrationEpoch / TakeRegistrationSpans / CollectMappedRegisteredRanges /
EnsureBdaReadable, RenderContext::PrepareBdaReadRanges and the region request lists. The plans are tried only for
stages whose windows upstream's analysis could not bound: a bounded stage's windows cost less than a plan's ranges
(with the plans first, the ~6,200 draws of the frame paid ~0.4 us each: 28.9 -> 26.1 fps). Not ported: the
speculation's use of the requests. (The write protection an upload worker applies later is this tree's asynchronous
reprotection: a request its uploads left unproven while that protection is queued is not marked dirty again, as in
his tree.)

On in Demon's Souls, where it was measured; KYTY_BDA_REGIONS=0/1 forces it off or on in any game (GTA V's Performance
RT has the same full synchronizations), KYTY_BDA_DIRTY_REGIONS=0 turns the dirty bits off.

Demon's Souls, Boletaria, the same debug exe with the execution thread's time by phase, one pass each with
KYTY_BDA_REGIONS=0 and unset (table dispatches off in both; standing 30 s, then turning 24 s): the full
synchronizations 2.0 ms a frame -> none, direct dispatches 6.2 -> 4.3 ms a frame, execution thread busy 21.8 -> 19.5
ms a frame; standing 35.4 -> 39.9 fps (frame 28.3 -> 25.0 ms), turning 37.2 -> 41.1 fps (26.9 -> 24.1 ms). The image is
the same (grass and fire, which the port without Publish lost). GTA V Performance mode, 30 s in game, on an earlier
base: 70.3 fps, no DeviceLost (the requests are off there).

Ported from the chenxiao07 fork.
Demon's Souls (PPSA01341) at Boletaria makes ~1,600 direct and ~460 indirect dispatches a frame, which cost the
execution thread ~7 ms a frame (with the BDA region requests), against ~1.1 ms in chenxiao07's tree, where they go
through the table (TableDispatch, ~0.5 us each). This tree's TableDispatch served plain direct dispatches only, was
off, and when on it saved ~0.4 ms a frame: it reset the draws' table state after each dispatch (the targets' and
sets' transits again, no TableContinue, the graphics state bound again), and indirect dispatches never went through it.

His TableDispatch whole (952cbd9ca, table-xpr.inc):
- indirect dispatches of thread groups: their arguments' buffer obtained as the normal path's DispatchIndirect obtains
  it, the barrier for the indirect read unless the dispatch is chained, dispatchIndirect;
- direct dispatches of thread counts: the groups that cover them, and the counts pushed where the program bounds its
  threads by them (dispatch_thread_dword, as the normal path pushes them). Indirect dispatches of thread counts stay on
  the normal path (it reads the counts the GPU wrote), as in his tree;
- the draws' table state is left as it is: a dispatch binds nothing of the graphics bind point, and an image its set
  moves to another layout moves TextureCache::ImagesEpoch;
- a shader the normal path took as a metadata clear or a fill stays there for good (his TableDispatchSeen with a
  special path);
- a pair whose buffer V#s changed format is learned again with that buffer's format decoded at run time (before, the
  pair was refused for good: TableDispatchLearn never learned a pair with a program again);
- the dispatches collect retired sets and sweep pairs as the draws do, and the resolve thread evaluates ahead the
  table dispatches of the new kinds too (KYTY_SCOUT=3);
- table programs check their raw loads and stores against their V#s' ranges, as their formatted loads did
  (EmitStorageElementInBounds skipped it under robustBufferAccess2, which does not bound their device addresses).
  Demon's Souls' skinning shaders (cs 0x25f790e00, hash b0d4eda3907099d1, and cs 0x25f791700, hash 102f0d4c553811c9),
  which the relearning above brings to the table, run whole groups of 64 threads past their vertex count; those threads
  read past the vertex streams, which the table copies into its ring (their pages are CPU-written), so they read the
  ring's other copies: black shapes came out of the character and the whole screen flashed black as soon as the camera
  turned at the user's save on the Boletaria stairs. On the guest's GPU those loads give zero and the stores are dropped.
His DemonsSouls::ComputeChains is this tree's chained dispatches (7228ff8cc8). Adapted: the pair still learns its
table program from the program the normal path chose (TableDispatchLearn; this tree's program cache) instead of asking
for it in TableDispatch; and the resolve thread resolves ahead, for 120 frames, the dispatches of a compute stage one of
whose dispatches took the normal path after one the table served, as it does for draws (TableMixedFrames): Boletaria
alternates ~15 indirect dispatches a frame between the two (the table refuses their blocks or sets now and then), and
each one without its resolution chose its program on the execution thread, ~220 us (3.3 ms a frame).

Demon's Souls, Boletaria, the same debug exe with the execution thread's time by phase, one pass each with
KYTY_TABLE_DISPATCH=0 and unset (the BDA region requests on in both; standing 30 s, then turning 24 s): ~960 direct and
~345 indirect dispatches a frame go through the table (2.4 and 5.3 us each, TableBlocks 1.5 us of it), ~530 direct
ones are consumed as fills or metadata clears and ~120 indirect ones take the normal path. The execution thread's
dispatches cost about the same (7.0 -> 6.9 ms a frame standing, 7.5 -> 7.8 turning: his ~0.5 us a dispatch is not
reached here), but it is busy less (19.5 -> 18.9 ms a frame standing) and the resolve thread no longer resolves the
dispatches the table serves: standing 39.9 -> 40.8 fps (frame 25.0 -> 24.5 ms), turning 41.1 -> 43.1 fps (24.1 ->
23.1 ms). The same image.

With the bounds checks (the last point of the list), the user played on from the save on the Boletaria stairs without
the black shapes. In image passes turning the camera there, one of ~340 screenshots shows a dark shape at the left of
the screen (the camera also comes close to the walls there with table dispatches off), against 2-4 of the 26 of each
pass before. Their cost was not measured (the figures above are from before them).

Ported from the chenxiao07 fork.

Co-authored-by: TheCruZ <[email protected]>
SAROS (PPSA07631) closed in PS5 Pro mode (--trinity) with "TextureCache:
unresolvable equal-address image overlap, address=0x3205ac0000
requested=1x1 cached=1x1 requested_size=0x800000 cached_size=0x600000
type=10/10 tile=27/27": two 3D images at one address with the same pitch,
height, tile mode, format and mip layout, the new one with more depth
slices (8 MiB over 6 MiB, 128 over 96 slices). Its Pro settings take its
volumes from 96 to 128 slices while loading (the volumetric fog grid at
0x3105b80000 goes from 288x162x96 to 288x162x128), and the dynamic
resolution changes their width within the pitch: this one changed both at
once. A volume that gains slices was only expanded with the same width and
height, so the overlap fell through to the fatal error.

Equal levels have equal mip layouts at this point, so the block slices are
the same whatever the width within the pitch, as volumes of the same size
already assume (they are expanded whatever their extents): a larger depth
expands the image with another width too. The copy into the expanded image
takes the smaller extent of each axis.
SAROS (PPSA07631) crashed twice in a Background Worker that builds its navigation mesh (Recast's
rcAddSpan, eboot 0x900ff8048): a bucket of the span grid held 0xffffffffffffffff, which it read as
a span pointer. A trace of the emulator's writes into guest memory named the writer: the page of
that bucket had been filled with 0xff five times in the 2 s before by MaterializeColorClear, and
zeroed by the game in between. When every byte of a color metadata slice is one key that clears,
MaterializeColorClear clears the image and fills the slice with 0xff in guest memory (the expanded
keys). Every lookup does it, also the lookups of T# candidates: the elements of bindless tables and
image heaps, and the T#s an indirect descriptor can name, that the host binds in case the shader
selects them (ResolveTexture). A table keeps the T#s of textures the game has freed, and their
metadata's memory then holds other data: a guard page put on each slice after it was filled caught
the game's own threads writing the slices of candidates of the bindless pixel shader
7464a9b4435b277e (RenderThread, a BackgroundThread, and IoDispatcher reading a file into one),
while the slices of the textures and targets SAROS binds directly were only rewritten by its DMA
fills and AMPR commands. Zeroed memory there reads as a cleared slice, so its next lookup filled the
game's data with 0xff.

PS5 reads a candidate's metadata only when the shader selects it, and never writes the keys of a
texture it samples. A candidate's lookup still clears its image, but leaves the keys in memory and
keeps a hash of them and of the image's write count: the next lookup applies the clears again only
if the keys or the image changed.

What changes for every game: a candidate's lookup writes no guest memory. A candidate whose keys
still clear and whose image something wrote since is cleared again at its next lookup (the keys
decide what PS5 samples), and a direct lookup after a candidate's clear repeats it (the same color
on an image nothing wrote since). A direct binding that writes the image publishes its keys as
before.
Demon's Souls (PPSA01341) at Boletaria dispatches its copy shader (the engine's cs_memset32) ~520 times a frame. Each
dispatch took the shader's program and the evaluation of its resources (the resolution ahead, or a lookup on the
execution thread) before it was consumed as a replicating fill: ~0.4 us a dispatch on the execution thread for a
program it never runs.

chenxiao07's register fast path (DemonsSouls::LinearCopyOf with m_linear_copy_shader, 952cbd9ca): once a dispatch of
the shader was consumed as a replicating fill whose V#s, count and pattern its registers give (s[0:3] the source V#,
s[4:7] the destination's, s[8:11] a buffer whose first two dwords are the count and the pattern size), the dispatches
of that code address are copied from the registers alone while the shader map generation stands; every 64th takes the
normal path again. Adapted: the copy is this tree's (ConsumeReplicate, taken out of TryConsumeComputeFill: written on
the CPU, or a GPU copy with its snapshot when the source holds GPU writes; his always copies on the GPU), its pattern
may be shorter than the count, as the normal path's, and parameters the GPU wrote take the normal path. Not ported:
the resolve thread still resolves these dispatches ahead (his tree has no such thread).

Learned only in Demon's Souls (Loader::DemonsSoulsTitle).

Demon's Souls, Boletaria, the same debug instrumentation before and after (one pass each; standing 30 s, then turning
24 s): direct dispatches 1.96 -> 1.76 ms a frame standing, 2.10 -> 1.88 turning; a copy from the registers 2.15 us,
the CPU replication most of it. 39.8 -> 40.7 fps standing, 41.8 -> 43.6 turning (more than the dispatches account
for: part of it is the passes' spread). The same image.

Ported from the chenxiao07 fork.

Co-authored-by: TheCruZ <[email protected]>
In GTA V's Performance RT mode the operation that traces rays 48d704640ab9fb40
synchronizes the buffers its alpha tests read through the V#s of a 2 MB table
(131 072 V#s). Whenever the CPU wrote a page of the table, the table was decoded
again whole: 2.5-3.1 ms each time, up to 6 times a second while driving (up to
16 ms/s of the execution thread), though only a few V#s change at a time (~8 a
frame while driving).

Only the V#s that differ from the copy are decoded now, and their ranges added
to the set; the ranges of the V#s they replace stay in it (synchronizing more
buffers is harmless) until an eighth of the table was replaced, and the table is
decoded again. BufferCache::AddToSet() adds a range to a set and keeps what
SynchronizeBuffersInSet() derived from it: its next pass visits the regions of
the range, and the pages the set covers are updated in place. Performance RT at
a downtown crossing, driving: an update 2.5-3.1 ms -> 7-13 us; the reach of
48d704640ab9fb40 218 -> 63 us a frame, the dispatch 1054 -> 856 us.
Before an operation that traces rays executes in GTA V, the check of its programs' resolution
compared the T# array of its bindless table that the resolution read: 2 MB, ~110 us each with the
helpers, four operations a frame in Fidelity mode (19 ms/s of the execution thread) and one in
Performance RT mode. The guest changes a page of it about once a second, but its pages stay CPU
dirty (no buffer covers them), so the memory tracker cannot tell which.

StrictWatch write-watches the pages of the strict reads of at least 256 KiB before the read, as
the image heap watches its tables: a write fault, a write of the emulator through the backing
store, an invalidation or an unmap takes the watch of its pages, and the next read or check
watches them again with a new version. The read keeps the version of its bytes, and its check
compares only the pages watched again since (all of them for a read that the guest's writes ahead
change, or when the range is not watched). In Fidelity mode the check of the four operations goes
from 112 to 3.5 us each; the guest's writes take ~3 page faults a second.
In GTA V's Fidelity mode each of the four operations that trace rays commits ~82 000 image
descriptors (bindless tables of 16 384 slots), and the draws between them a few dozen. Resizing
the array from a few dozen elements back to 82 000 cleared ~2 MB every time: 30 us of each such
commit (5.3 ms/s of the execution thread in Fidelity mode).

The array only grows now. A commit assigns every element it refers to (the image bindings are
allocated densely: each image's mips, then the slots of its tables, which are copied from the
table state's set or assigned), so the cleared elements were never read.
The operations that trace rays in GTA V bind bindless tables of 16 384 slots, kept in the
table state's slot set. Each binding took a new set from the descriptor heap and copied the
tables into it: 24 576 descriptors per operation in Fidelity mode (35 us of its
updateDescriptorSets), and sets that large (~82 000 descriptors) made the heap retire its pools
every few sets.

A table state now keeps a few whole sets of its layout (a ring). A binding whose tables all come
from one state's slot set binds a ring set that no pending GPU work uses: the other descriptors
are written as before, and its table slots take only the slots changed since it was last bound
(the state logs each changed slot with a version), or copy the tables from the slot set when it
is older than the log (a new set, or one after a binding that wrote the tables whole).

CommitBindings() of the four ray tracing operations in Fidelity mode (PPSA04263, native ray
tracing): 97 -> 23 us each (heap Commit 41 -> 0.1 us, updateDescriptorSets 35 -> 2.4 us; 98 000 ->
133 descriptors copied a frame), 17.0 -> 4.0 ms/s of the execution thread. In Performance RT,
with the commits before it, the operation's CommitBindings() takes 110 -> 24 us.
GTA V (PPSA04263) in Fidelity with native ray tracing rebinds a bindless
table state of ~17 000 elements in each of its 4 ray tracing dispatches
per frame. The helper threads flag the elements whose versions moved (a
few hundred), and the execution thread then read the ~17 000 flags one
byte at a time to collect them: 13.8 us per dispatch.

The flags are now read a word at a time, skipping the zero words:
2.5 us per dispatch (-11 us, ~-45 us per frame).
A table state marked every element with DCC metadata in every binding,
which resolved it again from scratch and visited it: their lookup
materializes the fast clears the guest left in the metadata. GTA V
(PPSA04263) in Fidelity with native ray tracing has ~35 such elements in
the tables of each of its 4 ray tracing dispatches per frame, each
resolved again for ~1.2 us.

An element whose metadata holds no clear to apply
(TextureCache::ColorClearSettled(), with its memo) now binds as the
others do: image registrations and backing changes over its ranges mark
it, and its image's version decides whether it is visited. About three
of four are settled in each binding. Per ray tracing dispatch, resolving
the marked elements takes 38.9 -> 15.2 us and checking the DCC elements
2.1 -> 9.7 us (~-16 us, ~-64 us per frame).
Demon's Souls (PPSA01341) streams textures while the camera turns: at Boletaria ~9 uploads a frame of CPU-written
textures (2.8-5.6 MiB each; each pool slot again ~1.4 s later), whose guest bytes ObtainBufferForImage copied into the
staging ring on the execution thread, ~165 us each (1.5 ms a frame, the execution thread being the critical stage);
most come from its texture pool, where it released pages (read as zeros).

The copy into the staging ring goes to the host copy thread, as buffer uploads' copies already do (UploadCopies):
RefreshImage watched the image's pages again before the upload, so a guest write after it faults and leaves the image
CPU dirty; the copy reads the backing store; every submission waits for the copies and so does any guest-visible
effect or unmap (HostCopyQueue::Drain). Images over several guest mappings are copied a piece at a time and the parts
without backing are zeroed on that thread (Memory::TryGetSparseBackingPieces: what TryReadSparseBacking reads, as
pieces); one larger than the ring is still copied on the execution thread. An image's copies are handed over at once.
The idea is chenxiao07's (KYTY_ASYNC_UPLOAD=2 in his fork, with an upload worker of its own).

On by default in Demon's Souls (Loader::DemonsSoulsTitle); KYTY_ASYNC_IMAGE_STAGING=0/1 forces it.

Demon's Souls, Boletaria, the same debug instrumentation before and after (one pass before, two after; standing 30 s,
then turning 24 s). Turning: the image staging copies on the execution thread 1.51 -> 0.02 ms a frame (9 uploads a
frame), the draws' graphics bindings 1.85 -> 0.58-0.60 ms, waiting for the copy thread at submissions 0.67 -> 1.10 ms,
the execution thread 16.93 -> 16.12-16.41 ms a frame, the frame 23.56 -> 23.16-23.36 ms (42.5 -> 43.5-43.9 fps).
Standing (no image uploads): unchanged, 38.8 -> 39.2-39.5 fps.

Co-authored-by: chenxiao07 <[email protected]>
A stage that takes its images from a draw template binds them with only the
type of their descriptions (PrepareBindingsFromTemplate() does not copy the
rest, which the commit does not need). When another stage of the draw no
longer matched the template, the draw stored the template again, and the
stages that still held it stored the descriptions left in their bindings by
whatever draw used those slots before. The next draws of the key then checked
the image set epoch over the wrong guest range (CheckTemplateImages()) and
the read-ready check of the stored image looked at the wrong subresources.
In GTA V Performance RT ~100 drawauto draws per frame store their template
again this way.

The stages that still hold their template keep its descriptions, and the
read-ready check uses the stored binding.
Draw templates refused every depth image, so a key whose draws sample a depth
buffer was stored and refused once per tick and its draws looked up, acquired
and committed their bindings every time. In GTA V Performance RT (city route,
Experiment draw mode) 166 drawauto draws per frame (~7 per refused key, the
deferred passes that read the scene depth) and 21 indexed ones went that way:
3.7 us per drawauto draw against 2.6 us for a held one.

A depth image the draw does not render to is held like a color image: its
version moves with its layout, contents and tracking, and the image set epoch
of its range with its identity. Stencil views of a depth image are still
refused, as their lookup refreshes the stencil association, and so are stencil
copies, which are refreshed from their depth image when acquired like depth
copies are from their color images.

GTA V Performance RT, one instrumented pass with both modes in alternate 5 s
windows (KYTY_PACCT): refused drawauto draws 166 -> 0 per frame, drawauto
4.14 -> 3.81 us per draw (~9 ms per second of the execution thread's 913).
Demon's Souls (PPSA01341) writes ~3,500 buffers a frame at Boletaria, most of them the same ranges by operation after
operation of one command buffer. After each operation CommitWriteTicks assigns the current tick to every range it wrote,
a lookup and update in the map of write ticks, which holds every range ever written: WriteTicks::Assign took 0.6 ms a
frame of the execution thread, at an IPC of 0.84.

Assign remembers the last ranges it assigned (256, by a hash of the range) with their tick, and returns at once for one
assigned in this tick: the map still holds that tick over the range, as the ticks assigned only grow.

Demon's Souls, Boletaria, the same debug instrumentation, the skip off and on (one pass each; standing 30 s, then
turning 24 s): 2,369 of ~4,070 ranges a frame skipped standing (2,347 of ~3,840 turning); CommitWriteTicks' assigns
0.80 -> 0.57 ms a frame of the execution thread standing, 0.67 -> 0.52 turning (0.20 -> 0.14 us a range). The image is
the same.
The game's Ziva shaders (CS_ZivaRBFInterpolate, KernelFunctions, EigenSkinning,
TensorSkinning) reduce across a wave64 through LDS with no barrier, relying on
GCN lockstep. Run as halves (LocalSize 32), our SPIR-V had no barrier between one
invocation's LDS write and another's read: a data race under the Vulkan memory
model. Players on RTX 30/40 see torn character meshes that go away with Ziva
muscles off; our RTX 50 never tore.

KYTY76_LDS_SYNC (on unless 0) emits OpControlBarrier(Subgroup, Workgroup,
AcquireRelease|WorkgroupMemory) before every LDS load and store in wave64-halves
compute modules (like __syncwarp). Halves keep control flow subgroup-uniform.
Modules with the BVH stack op are left out (per-lane slots; ray tracing is
skipped). In the precompile Origin. bt.sh: 99/99 tests.

KYTY76_LDS_SYNC=0 turns it off.

Adapted to this tree: the switch is part of the SPIR-V profile (Spirv::Profile::lds_lane_sync, read once in
SpirvProfile), which the shader store's header holds, in place of his precompile Origin(): a store written
with the other setting is not reused.
Only compute programs get it: in this tree mesh shaders run in halves too, and the barrier there flashed
white lines over ASTRO BOT's and SAROS's title screens.

Ported from the Senaxx fork (86151b7251).
This reverts commit e5e70a635d.
(cherry picked from commit f2fca83b4e05b60bf21f605aee12aeacc16f616f)
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:21:04 +00:00
This pull request has changes conflicting with the target branch.
  • CMakeLists.txt
  • src/common/emulatorConfig.h
  • src/common/threads.cpp
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
  • src/graphics/host_gpu/renderer/cache/streamBuffer.h
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/graphics/host_gpu/renderer/colorRenderTarget.cpp
  • src/graphics/host_gpu/renderer/commandScheduler.cpp
  • src/graphics/host_gpu/renderer/depthRenderTarget.cpp
  • src/graphics/host_gpu/renderer/image/image.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptorHeap.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptors.h
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/pipelineSerialization.cpp
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderContext.cpp
  • src/graphics/host_gpu/renderer/renderContext.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/presentation/systemOverlay.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translate.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translator.h
  • src/graphics/shader/recompiler/ir/Program.cpp
  • src/graphics/shader/recompiler/ir/Serialize.h
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/shader.cpp
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/loader/runtimeLinker.cpp
  • src/loader/x64InstructionEmulator.cpp
  • src/loader/x64InstructionEmulator.h
  • tests/ResourceMaterializationTests.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/VdecswTests.cpp
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2469/head:github-bot/gh-2469'
git switch 'github-bot/gh-2469'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2469'
git switch 'github-bot/gh-2469'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2469'
git switch 'github-bot/gh-2469'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2469'
git switch 'main'
git merge --squash 'github-bot/gh-2469'
git switch 'main'
git merge --ff-only 'github-bot/gh-2469'
git switch 'main'
git merge 'github-bot/gh-2469'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.