shader: track GPU-selected buffer stores through a bounded descriptor table (GTA V crash) #2501
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!2501
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2501"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@taklaciwiz-maker on GitHub · 2026-11-21 21:05 UTC · original
taklaciwiz-maker:gta-v-shader-fix→main· +164 −18 · 3 files · 1 commits · openFixes #2277. That report has the same exit, on PPSA04263.
Problem
GTA V (PPSA04264, 01.011.001) exits during the first mission with:
The compute shader runs a waterfall loop:
v_readfirstlanepicks a key from a per-lane value. That value comes from an unbounded buffer load(
BUFFER_LOAD_DWORD v0, v31, s12 ... idxen offset:52).S_BUFFER_LOAD_DWORDX4 s0, s8, key << 4loads a V# from a 16-byte-stride table.BUFFER_STORE_DWORD ... offenwrites through that V#.TryMakeIndirectBufferaccepts this store pattern only through the legacy-store path. That path needs thekey to be a loop-bounded material index (
BoundedSelectedIndex). Here the key has no bound, so trackingfails.
The load path already handles this shape with
table_scalar: the table V# bounds every reachabledescriptor.
Changes (3 files, +164/-18, against main
39936ff, clang-format 22 applied to the changed lines)ResourceTracking.cpp,TryMakeIndirectBuffer:UniformizedMaterialValue/IndexedMaterialRead/BoundedSelectedIndex), it falls back totable_scalar, as the load path does.ReadFirstLaneresult is still rejected.ResourceMaterialization.cpp/ShaderIR.h, row limit:MaxIndirectScalarTableRows = 262144, used only fortable_scalarscans.MaxIndirectDescriptorProbesis unchanged; index proofs also use it.NormalizeIndirectBuffer:offenonly), unswizzled and unformatted, withOOB_SELECT = 0. Example:66ec0000,00040002,00017bb0,00014204, stride 4, 97200 records.[base, base + stride * records).OOB_SELECT = 0with stride 4 for raw offsets, sothis may be more permissive than hardware.
MaterializeResourcesruns on everyFindModule, so the 131072-row scan ran on every dispatch:~26–30 ms each, ~500 scans/min, about 2 FPS.
ReadScalarTablecall instead of one call per row.ResourcePlan::scan_cache(ScanCacheEntry, buffer resources only) stores the candidates andmapping of each scan.
of the table bytes. When all of them match, the stored result is replayed.
Results
RTX 5070 / Ryzen 5 7600X.
not touch; see my comment in #2277.
a21fd80, then rebased it onto39936ffwith no conflicts.39936ff, on a build that also has a separate HTile fix andnative_rt=true:about 7 minutes with no crash.
0xe777d90ed493bd6cis translated several times with no tracking error.Caveats
table_scalar, every distinct descriptor in the table is bound as a written storage buffer on everydispatch. This scene has 7 of them, up to 41 MB each. All of them are marked GPU-modified in full,
although each waterfall iteration writes only one. This is correct but coarse.
OOB_SELECT = 0normalization (item 3) should be checked against hardware.ResourceTracking.cppandResourceMaterialization.cpp.I did not check whether it fixes this crash in a different way.
🤖 Generated with Claude Code
@coderabbitai[bot] on GitHub · 2026-11-21 21:17 UTC · original
Walkthrough
The changes add a row limit and scan-result cache for indirect scalar descriptor tables. Materialization normalizes eligible indirect buffers and can bulk-read descriptor tables, reuse cached scan results, and store results after a cache miss. Resource tracking now falls back to scalar-table selection in specified cases where indirect-buffer matching or bounded-index proof is unavailable.
Suggested reviewers:
nmzik,claxten10Change: Bug fix · Severity of issue fixed: Medium
Merge Risk:
Moderate · up to
0c2d9This change lets GTA V shaders that select buffer descriptors through a table compile instead of failing. As written, the descriptor normalization can permit out-of-range stores that the original buffer bounds would drop. The new bulk table read can also cause the renderer to exit for certain buffer layouts that previously worked, and cold scans of very large tables may be slow. Resolve the bounds and read-capture issues before merging, or explicitly accept them.
Pre-merge checks:
4
#2277is the only active direct target. Its requirement is that GTA V (PPSA04263) boots past shader resource tracking and does not stop with the error for hash 0xe777d90ed493bd6c, stage=compute,…Full details: Title check
Explanation
The title names the main change: GPU-selected buffer stores are tracked through a bounded descriptor table (table_scalar fallback), with the GTA V crash as context. The raw summary and objectives describe the same fallback in ResourceTracking.cpp, plus the row limit, normalization, and scan cache, which the title does not mention. The title is specific and matches the primary change.
Full details: Description check
Explanation
The description is detailed and on-topic. It explains the GTA V crash, the waterfall-loop store pattern, and the TryMakeIndirectBuffer fallback. It also covers the row limit, the NormalizeIndirectBuffer change, the XXH3-keyed scan cache, test results, and caveats. These match the raw summary and PR objectives.
Full details: Linked Issues check
Explanation
Issue
#2277is the only active direct target. Its requirement is that GTA V (PPSA04263) boots past shader resource tracking and does not stop with the error for hash 0xe777d90ed493bd6c, stage=compute, pc=0x0000093c. The PR changes TryMakeIndirectBuffer in ResourceTracking.cpp. The diff confirms that when material-key matching fails, the legacy store path now calls scalar_table() and sets indirect.table_scalar = true instead of returning false. The ReadFirstLane check still rejects keys that are not ReadFirstLane results. The hash and pc in the issue match the failure the PR addresses. The PR author reports that the crash is gone and that the prologue ran for about 7 minutes on PPSA04264 with the same shader hash. That is the same title and shader, but not the PPSA04263 serial named in the issue. The check is therefore satisfied by code and reported runtime evidence. No test was added in the diff. The evidence is the author's report, not a test in this PR.Full details: Out of Scope Changes check
Explanation
The changes fall into four groups. (1) ResourceTracking.cpp: the table_scalar fallback. This is the direct fix for the reported error. (2) ResourceMaterialization.cpp and ShaderIR.h: MaxIndirectScalarTableRows (262144) applies only to table_scalar scans. The fallback needs this limit because the reported table has 131072 rows. This is connected to the fix. (3) NormalizeIndirectBuffer: rewrites non-indexed, unswizzled, unformatted raw candidates with OOB_SELECT = 0 to byte bounds. It applies to all matching buffers, not only this shader. The connection to the crash is indirect. The PR states that the RDNA2 behavior was not verified and may be more permissive than hardware. (4) Scan cache (ScanCacheEntry, ResourcePlan::scan_cache, XXH3 hashing, bulk ReadScalarTable). This addresses the cost of the new scan that runs on every FindModule call after the fix. The issue does not request a performance change. The cache is connected to the fix, so it is not shown to be unrelated. The PR objectives list all four groups as intended work. Group (3) carries an unverified hardware risk that the author discloses. It is not a demonstrated unrelated change.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Share
@ -231,0 +242,4 @@}value.dwords[1] = (value.dwords[1] & ~(0x3fffu << 16u)) | (1u << 16u);value.dwords[2] = static_cast<uint32_t>(bytes);value.dwords[3] |= 3u << 28u;@coderabbitai[bot] on GitHub · 2026-11-21 21:17 UTC · original
Preserve the original structured-buffer bounds.
For stride=16, NumRecords=4 and OOB_SELECT=0, a non-indexed store at byte offset 32 must be dropped. RDNA2 checks offset against stride. This rewrite instead creates a 64-byte raw range with OOB_SELECT=3, which admits that store. Preserve the original bounds when normalizing the descriptor. In-bounds stores must remain valid. (amd.com)
@ -732,0 +747,4 @@const uint64_t row_limit =indirect.table_scalar ? MaxIndirectScalarTableRows : MaxIndirectDescriptorProbes;if (child_count == 0u || (!image_heap && count * child_count > row_limit))return failed("candidate count", fmt::format("rows={} limit={}", count, row_limit));@coderabbitai[bot] on GitHub · 2026-11-21 21:17 UTC · original
Replace the linear child search in
intern_candidatewith a keyed ordinal lookup.intern_candidatesearches all existing children withstd::findfor each candidate. A cold scan of distinct descriptors therefore costs n(n-1)/2 comparisons. The raisedtable_scalarrow limit allows n up to 262144, which gives 34,359,607,296 comparisons. A content change also misses the scan cache and repeats the full scan.Add an ordinal map keyed by the same equality used for the root check. Assign ordinals in first-seen order, and keep the existing root-descriptor check and the
specializationspush for new children. Lookups then become amortized constant time per candidate.@ -740,0 +761,4 @@if (!image_heap && pointer == nullptr && count > 16u && table_size >= 4u &&table_size <= (uint64_t {64} << 20u)) {heap_words.resize(table_size / 4u);bulk_table = ReadScalarTable(table_base, table_size, 0u, runtime, heap_words);@coderabbitai[bot] on GitHub · 2026-11-21 21:17 UTC · original
Do not capture unused table bytes as descriptor dependencies.
With a 4096-byte table and 17 selected 16-byte rows, this read captures the unused tail too.
SrtReadCapturerecords the full span. If a separate sentinel write buffer starts at table_base+1024,RenderExecutor::FindBuffersnow exits with"scalar resource reads overlap a shader buffer write". The previous row reads did not overlap that writer. Keep dependency capture limited to the descriptor words, or retain row reads when bulk capture would change alias checks. (raw.githubusercontent.com)@coderabbitai[bot] on GitHub · 2026-11-21 21:17 UTC · original · reviewed
Actionable comments posted: 3
f250f814-6abf-487e-90a8-b605f4026311Reviewing files that changed from the base of the PR and between
39936ffa39and0c2d9d7e91.src/graphics/shader/recompiler/ir/ShaderIR.hsrc/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cppsrc/graphics/shader/recompiler/ir/passes/ResourceTracking.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@theantipopau on GitHub · 2026-11-23 01:20 UTC · original
Review: scan cache and GPU-modified range handling
Read against
39936ffa. The scan cache is correct for this shape — I traced the replay path and could not break it — but the invalidation story is weaker than the description implies, one key component is dead, and most of the 41 MB cost is paid by code this PR does not touch, on every dispatch, including the dispatches the cache is supposed to make cheap.What holds
table_base/table_size/first/step/count/read_dwords/dword_count/source_index/resource_indexcover every input that changeschildren.normalizecloses over plan-static state only:NormalizeIndirectBufferreadsresource.formatted/read/written/max_byte_extent, andApplyResourceSpecializationdoes not rewrite those.affineneeds no separate field because a non-affine scan is exactlyfirst=0, step=4.intern_candidate's dedup over[children_begin, end), so replaying them without dedup yields the same ordinals.mappingis a relative slice re-inserted at the newmapping_offset. The no-children case stores a 2-word mapping and then hitsresize(mapping_offset)on both paths, soflattened_srtends the same length either way.count * child_count <= 262144makesstatic_cast<uint32_t>(count)safe.ReadTablezero-fillswords.subspan(count), and the bulk branch reproduces that withstd::min<size_t>(read_dwords, available).Four fixes
1.
content_hashhashes the CPU backing, not what the GPU sees.ReadShaderGuestMemoryisTryReadBufferBacking— no GPU-dirty download. "The table bytes did not change" therefore only means "the CPU copy did not change". Not a new bug (the scan reads the same backing, so cache and scan agree), but the hash cannot invalidate on a GPU write to the table — the exact case theScanCacheEntrycomment claims to cover. Harmless here only because the store targets the children.2.
cache_key.rootis always{0,0,0,0}.descriptors[resource_index] = {.dword_count = dword_count}(line 721) zeroes it before the key is built (line 784), so the root contributes nothing androot_dword_countis the constantdword_countalready in the key. Capture the root dwords before line 721, or drop both fields and fix the comment — as written, "the root descriptor ... is part of the key" is a false safety signal.3.
MaxIndirectScalarTableRowsis not scoped to the new fallback.row_limitkeys offindirect.table_scalar, which pre-existing load-path sites also set (ResourceTracking.cpp:3205, 3301, 3306, 3553). Those go from 65,536 rows to 262,144 — 4x more descriptors and specializations on shaders unrelated to this crash. Use a separate flag (store_table_scalar) set only inscalar_table()and gate the bigger budget on it.4. The
OOB_SELECT = 0rewrite is the only semantic change, and it is narrower than the caveat suggests. For a raw V#,GetSize() == stride * NumRecords, sostride=4/records=97200andstride=1/bytes=388800describe the same extent. The rewrite only changes OOB_SELECT 0 -> 3. That is defensible (0 means no bounds check at all) but it does drop accesses paststride * recordsthat hardware would have allowed. Worth a differential dump rather than a code reading.Minor:
cache_eligiblerequiresdescriptors.size() == children_begin, so only the first indirect buffer source materialized in a call is ever cached. Fine, but the comment does not say so.The hit still copies and hashes the whole table
bulk_table = ReadScalarTable(...)andXXH3_64bits(...)both run unconditionally, before the cache lookup. The 0.22 ms hit is 2 MiB of guest-backed copy plus 2 MiB of hashing, every dispatch — all of it spent proving the table is unchanged rather than scanning it.The bulk read is also sized from the V# size, not the scanned extent. With
table_maximumset,countcan be far belowtable_size: the read then covers up to 64 MiB, and if any of it is uncommittedReadScalarTablefails andbulk_tablegoes false — silently back to the per-row path and the 26-30 ms this change exists to remove. Clamping tofirst + (count - 1) * step + read_dwords * 4fixes both the waste and the cliff.The 41 MB is a per-dispatch full-range mark, not a write
Every dispatch,
RebindBuffers->NativeStorageBuffer->ObtainBuffer(is_written = resource.written)once per child, and each one:ForEachUploadRange(is_written=true)->ChangeState<Gpu, true>over the whole[base, base+41MB): 11 tracker regions,RegionBits(~bits, start, end)+SetRange+changed.None()each. The first mark does the real watcher work; every later dispatch redoes the bit work and the region locks for nothing, becausechangedis empty andUpdateProtectionis skipped.m_gpu_modified_ranges.Add(41 MB).InvalidateMemoryFromGPU(address, 41 MB), which takes the texture-cache lock and walks the images in that range. Seven children means a 287 MB range query over the image table per dispatch, under a global lock, at roughly 500 dispatches/min. That is the part I would expect to matter most, and it is invisible in the FPS attribution.Second order: because the whole range is GPU-dirty, any guest write anywhere in those 41 MB takes the
InvalidateRegionflush path, and any read downloads the full range.Concrete fixes, cheapest first
ForEachUploadRange, ifIsRegionGpuModified(vaddr, size)is already true, skip theIterateGPU-mark pass. Semantics are identical (changedis empty) and it removes the per-dispatch page walk and region locks for every repeatedly-bound written buffer in the emulator, not just this shader.BufferCache::MappedMemoryWritealready invalidates on the exact written range.epochtoRegionManager, bumped onChangeState<Cpu, true>and on the GPU-dirty mark, and key the cache on the epoch of the region(s) covering the table instead ofcontent_hash. A 2 MiB table is one region, so validity becomes an O(1) compare — no 2 MiB copy, no hash, no collision risk, and it actually invalidates when the GPU writes the table. That is roughly 20 lines on top of this change.If the epoch is too invasive here, 1-3 are small and local and recover most of the cost.
One more:
scan_cacheismutableand written throughconst ResourcePlan&. The class comment says the owning renderer serializes access, so it is safe today, but it is now persisted state rather than per-call scratch likematerial_keys/selector_keys. Worth a comment, or taking the plan by non-const reference so the mutation is visible at the call site.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.Merge
Merge the changes and update on Forgejo.