shader: plan more indirect image table shapes #1118

Open
github-bot wants to merge 2 commits from github-bot/gh-1118 into main AGit
Owner

@⁠NeySlim on GitHub · 2026-10-06 19:45 UTC · original
NeySlim:feat/indirect-table-shapes → main · +299 −4 · 5 files · 2 commits · open

God of War Ragnarök (PPSA08332) selects light and material textures through descriptor tables indexed by waterfall loops (s_ff1 over a lane mask), bounded loops and loaded selectors. Several of these shapes were refused by resource tracking (GetImageResource dword 0 is not a valid runtime value).

Most of the original PR is now on main: wider records (a287a54f2), the guard proofs (a287a54f2, 25e1cc7ec, d70cbd418, ed1195d1, 9a3aca96), shared descriptor reads (7e884f55), masked keys and pointer-backed selector tables (1fa79d5c). What is left:

  • A bit scan key (ff1(mask)) whose ff1(mask) != -1 test is carried by the image's own EXEC predicate, rather than by a branch, is bounded like the branch-guarded form.
  • A key loaded through a scalar pointer at index * stride + offset, with index a zero-based loop counter bounded by a signed compare (s_cmp_lt_i32), becomes a pointer-backed selector read; a negative count runs no iteration.
  • Every key reads the record at the address the shader computes (key * stride + offset, 32-bit), negative keys included. When every path from the key's load to the image crosses a uniform key >= 0 test, a negative key never reaches the image and its record is not a candidate.

Tests

TestLaneGuardedBitScanTable and TestLoopSelectedSignedKey in resource_tracking_tests (guarded, unguarded, unrelated, inverted and key >= -1 tests, a second unguarded sample, a negative count). Each fails when the rule it covers is removed.

Validation

Linux, AMD Radeon 8060S, Mesa RADV 26.2.3, rebased on 9e41d832. CPU suites pass; shader_recompiler_compute_tests one case per process gives the same results as main (627 of 637; the same 10 fail on main on this setup). The game was checked with the earlier version of this PR; the planner accepted all of the compute and pixel shaders it compiles up to its first setup screen.

Related work: #811 and #852 generalize the same planner for Horizon Forbidden West, and #1255 touches the same code; whichever lands second, I will rebase it.

Not tested on Windows or macOS; the change is platform-independent recompiler code.

AI use

The investigation, the code, the tests and this description were produced with Claude Code (AI agent) on my machine. I reviewed the diff and the results before submitting.

**@⁠NeySlim** on GitHub · 2026-10-06 19:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118) `NeySlim:feat/indirect-table-shapes` → `main` · +299 −4 · 5 files · 2 commits · open God of War Ragnarök (PPSA08332) selects light and material textures through descriptor tables indexed by waterfall loops (`s_ff1` over a lane mask), bounded loops and loaded selectors. Several of these shapes were refused by resource tracking (`GetImageResource dword 0 is not a valid runtime value`). Most of the original PR is now on main: wider records (a287a54f2), the guard proofs (a287a54f2, 25e1cc7ec, d70cbd418, ed1195d1, 9a3aca96), shared descriptor reads (7e884f55), masked keys and pointer-backed selector tables (1fa79d5c). What is left: - A bit scan key (`ff1(mask)`) whose `ff1(mask) != -1` test is carried by the image's own EXEC predicate, rather than by a branch, is bounded like the branch-guarded form. - A key loaded through a scalar pointer at `index * stride + offset`, with `index` a zero-based loop counter bounded by a signed compare (`s_cmp_lt_i32`), becomes a pointer-backed selector read; a negative count runs no iteration. - Every key reads the record at the address the shader computes (`key * stride + offset`, 32-bit), negative keys included. When every path from the key's load to the image crosses a uniform `key >= 0` test, a negative key never reaches the image and its record is not a candidate. ## Tests `TestLaneGuardedBitScanTable` and `TestLoopSelectedSignedKey` in `resource_tracking_tests` (guarded, unguarded, unrelated, inverted and `key >= -1` tests, a second unguarded sample, a negative count). Each fails when the rule it covers is removed. ## Validation Linux, AMD Radeon 8060S, Mesa RADV 26.2.3, rebased on 9e41d832. CPU suites pass; `shader_recompiler_compute_tests` one case per process gives the same results as main (627 of 637; the same 10 fail on main on this setup). The game was checked with the earlier version of this PR; the planner accepted all of the compute and pixel shaders it compiles up to its first setup screen. Related work: #811 and #852 generalize the same planner for Horizon Forbidden West, and #1255 touches the same code; whichever lands second, I will rebase it. Not tested on Windows or macOS; the change is platform-independent recompiler code. ## AI use The investigation, the code, the tests and this description were produced with Claude Code (AI agent) on my machine. I reviewed the diff and the results before submitting.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:43:51 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 20:04 UTC · original · edited 2026-10-19 04:56 UTC

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

  • Last reviewed commit: 65660f8d4c018fe182d0be6ab243377e401d55f9
  • Latest commit, not reviewed: 3086624c91

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4c52e2ff-356f-4478-8b7c-14bb21eb0859
📥 Commits

Reviewing files that changed from the base of the PR and between d615e4ec43c2e525b3359aa792420a92d05325a9 and 65660f8d4c018fe182d0be6ab243377e401d55f9.

📒 Files selected for processing (3)
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • tests/ResourceTrackingTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 2 remain after this review.

📝 Walkthrough
📝 Walkthrough

Walkthrough

Resource tracking adds nonzero proofs across predecessor paths, lane-aware guard analysis, masked shifted-key matching, and bounded scalar-address selector recognition. It accepts qualifying reads that dominate handles, supports additional indirect image selector bounds, and reuses matching descriptor plans. Tests cover accepted and rejected lane-guard cases. Resource materialization reads scalar-pointer selector keys with probe and offset checks. Keys with the high bit set leave the candidate descriptor null without a descriptor-table read.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Feature

Merge Risk: ⚪ Minimal · up to 65660

The described selector changes have no established outstanding issue in this review. They are mergeable after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 34.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description directly explains the indirect image-table planning changes, supported shader access patterns, tests, validation, and related work.
Title check Passed The title clearly and concisely identifies the main change: expanding support for indirect image table shapes.
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 20:04 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#issuecomment-6024448660) · edited 2026-10-19 04:56 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1118?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > - Last reviewed commit: 65660f8d4c018fe182d0be6ab243377e401d55f9 > - Latest commit, not reviewed: 3086624c9102b2dcb209363ebde31ef7307c7a31 > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> ▶️ Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `4c52e2ff-356f-4478-8b7c-14bb21eb0859` </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between d615e4ec43c2e525b3359aa792420a92d05325a9 and 65660f8d4c018fe182d0be6ab243377e401d55f9. </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing (3)</strong></summary> <dl> <dd> * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `tests/ResourceTrackingTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 2 remain after this review. </dd> </dl> </details> <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> ## Walkthrough Resource tracking adds nonzero proofs across predecessor paths, lane-aware guard analysis, masked shifted-key matching, and bounded scalar-address selector recognition. It accepts qualifying reads that dominate handles, supports additional indirect image selector bounds, and reuses matching descriptor plans. Tests cover accepted and rejected lane-guard cases. Resource materialization reads scalar-pointer selector keys with probe and offset checks. Keys with the high bit set leave the candidate descriptor null without a descriptor-table read. **Suggested reviewers:** `nmzik` </dd> </dl> </details> </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"65660f8d4c018fe182d0be6ab243377e401d55f9" --> **Change:** Feature <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>⚪ Minimal</strong> · up to <code>65660</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **⚪ Minimal** · up to `65660` --> <!-- final_review_risk_coverage:{"sourceCommitId":"65660f8d4c018fe182d0be6ab243377e401d55f9","coveredCommitId":"65660f8d4c018fe182d0be6ab243377e401d55f9","kind":"reviewed"} --> The described selector changes have no established outstanding issue in this review. They are mergeable after normal checks. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 warning</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 34.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 3 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------- | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the indirect image-table planning changes, supported shader access patterns, tests, validation, and related work. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely identifies the main change: expanding support for indirect image table shapes. | </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1118)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 20:04 UTC · original · edited 2026-10-06 21:18 UTC
On src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp line 374 (outdated):

@@ -367,6 +367,22 @@ bool MaterializeIndirectDescriptor(const ResourcePlan&                         p
 			}
 			keys.resize(key_count);
 			std::iota(keys.begin(), keys.end(), 0u);
+		} else if (!indirect.selector_first.IsEmpty() && material_value.dword_count == 2u) {
+			// Selector words behind a scalar pointer: no buffer bounds to honour.
+			uint32_t first = 0, count = 0;
+			if (!clean.Evaluate(indirect.selector_first, first) ||
+			    !clean.Evaluate(indirect.key_count, count) || count > MaxIndirectDescriptorProbes)

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '345,405p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
rg -n 'key_count|MaxIndirectDescriptorProbes' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | head -100

Repository: KytyPS5/KytyPS5

Length of output: 7390


🏁 Script executed:

rg -n -C 12 'indirect\\.key_count\\s*=' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
rg -n -C 8 'clean\\.Evaluate\\(|bool Evaluate|Evaluate\\(Value' src/graphics/shader/recompiler/ir
rg -n 'class .*Clean|struct .*Clean|Clean.*Evaluate|Value.*Evaluate' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp src/graphics/shader/recompiler/ir

Repository: KytyPS5/KytyPS5

Length of output: 542


🏁 Script executed:

rg -n 'key_count[[:space:]]*=' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
sed -n '1550,1620p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
sed -n '1735,1765p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
sed -n '1880,1920p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
rg -n 'Evaluate\(' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
sed -n '520,580p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
rg -n 'class.*Clean|struct.*Clean|CleanValue|clean\\.' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp

Repository: KytyPS5/KytyPS5

Length of output: 12254


🏁 Script executed:

sed -n '1608,1745p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
sed -n '320,365p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
rg -n 'MatchUniformizedMaterialKey|key_count = bound->Arg' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Repository: KytyPS5/KytyPS5

Length of output: 8936


🏁 Script executed:

rg -n 'ValidateRuntimeValue|MaterializeIndirectDescriptor' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
sed -n '300,345p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
sed -n '315,355p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
sed -n '420,490p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp

Repository: KytyPS5/KytyPS5

Length of output: 8356


🏁 Script executed:

rg -n 'bool ValidateRuntimeValue|ValidateRuntimeValue\\(' src/graphics/shader/recompiler
sed -n '1125,1225p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
rg -n 'SLessThan32|ULessThan32' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | head -40

Repository: KytyPS5/KytyPS5

Length of output: 4999


🏁 Script executed:

rg -n -F 'ValidateRuntimeValue(' src
rg -n -F 'bool ValidateRuntimeValue' src
rg -n -F 'enum class RuntimeValueType' src
rg -n -F 'RuntimeValueType::Integer' src/graphics/shader/recompiler

Repository: KytyPS5/KytyPS5

Length of output: 4056


🏁 Script executed:

sed -n '135,270p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
sed -n '975,1005p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
sed -n '15,35p' src/graphics/shader/recompiler/ir/passes/SrtWalker.h

Repository: KytyPS5/KytyPS5

Length of output: 6424


🏁 Script executed:

rg -n -F 'struct IndirectDescriptor' src/graphics/shader/recompiler
rg -n -F 'key_count' src/graphics/shader/recompiler/ir
rg -n -F 'IndirectDescriptor' src/graphics/shader/recompiler/ir/passes/ResourceTracking.h src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.h src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Repository: KytyPS5/KytyPS5

Length of output: 7982


🏁 Script executed:

sed -n '480,515p' src/graphics/shader/recompiler/ir/ShaderIR.h
sed -n '912,940p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
sed -n '990,1015p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp

Repository: KytyPS5/KytyPS5

Length of output: 3601


🏁 Script executed:

sed -n '1588,1608p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
sed -n '1690,1760p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
sed -n '1868,1910p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Repository: KytyPS5/KytyPS5

Length of output: 6660


🏁 Script executed:

nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1595,1606p;1628,1656p;1745,1755p;915,936p'
nl -ba src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp | sed -n '330,342p;145,215p;980,990p'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '370,382p;1200,1215p'
nl -ba src/graphics/shader/recompiler/ir/ShaderIR.h | sed -n '486,507p'

Repository: KytyPS5/KytyPS5

Length of output: 10713


🏁 Script executed:

nl -ba src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp | sed -n '215,250p'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1207,1224p'

Repository: KytyPS5/KytyPS5

Length of output: 2610


🏁 Script executed:

rg -n -F 'LoopBoundProof' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
sed -n '380,520p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Repository: KytyPS5/KytyPS5

Length of output: 6051


🏁 Script executed:

nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '130,270p'

Repository: KytyPS5/KytyPS5

Length of output: 7314


Normalize negative signed bounds before applying the probe limit.

BoundedLoop accepts SLessThan32 bounds and stores the bound as key_count. Evaluation preserves its U32 bit pattern, so a negative signed bound can exceed the probe limit before the later conversion to zero. This can make indirect-image materialization fail even though the zero-based loop has no iterations. Track the bound’s signedness and normalize only signed nonpositive counts; keep large unsigned bounds subject to the limit.

🐛 Suggested fix
--- a/src/graphics/shader/recompiler/ir/ShaderIR.h
+++ b/src/graphics/shader/recompiler/ir/ShaderIR.h
@@
 		uint32_t workgroup_axis  = UINT32_MAX;
 		Value    key_count;
+		bool     key_count_signed = false;
 		Value                 selector_first;
--- a/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
+++ b/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
@@
 				    a.table_stride != b.table_stride ||
 				    a.workgroup_axis != b.workgroup_axis || a.sources != b.sources ||
+				    a.key_count_signed != b.key_count_signed ||
 				    !EquivalentValue(m_program, a.key_count, b.key_count) ||
@@
 		indirect.selector_first = Value(0u);
 		indirect.key_count      = bound->Arg(1);
+		indirect.key_count_signed = bound->GetOpcode() == ValueOpcode::SLessThan32;
@@
 					indirect.selector_first = first;
 					indirect.key_count = bound->Arg(1);
+					indirect.key_count_signed = bound->GetOpcode() == ValueOpcode::SLessThan32;
--- a/src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
+++ b/src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
@@
 			uint32_t first = 0, count = 0;
 			if (!clean.Evaluate(indirect.selector_first, first) ||
-			    !clean.Evaluate(indirect.key_count, count) || count > MaxIndirectDescriptorProbes)
+			    !clean.Evaluate(indirect.key_count, count))
 				return false;
-			if (std::bit_cast<int32_t>(count) <= 0) count = 0;
+			if (indirect.key_count_signed && std::bit_cast<int32_t>(count) <= 0) count = 0;
+			if (count > MaxIndirectDescriptorProbes) return false;

✅ Addressed in commit 4721ac4

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 20:04 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#discussion_r4199907404) · edited 2026-10-06 21:18 UTC On `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` line 374 (outdated): ```diff @@ -367,6 +367,22 @@ bool MaterializeIndirectDescriptor(const ResourcePlan& p } keys.resize(key_count); std::iota(keys.begin(), keys.end(), 0u); + } else if (!indirect.selector_first.IsEmpty() && material_value.dword_count == 2u) { + // Selector words behind a scalar pointer: no buffer bounds to honour. + uint32_t first = 0, count = 0; + if (!clean.Evaluate(indirect.selector_first, first) || + !clean.Evaluate(indirect.key_count, count) || count > MaxIndirectDescriptorProbes) ``` **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '345,405p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp rg -n 'key_count|MaxIndirectDescriptorProbes' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | head -100 ``` Repository: KytyPS5/KytyPS5 Length of output: 7390 --- 🏁 Script executed: ```bash rg -n -C 12 'indirect\\.key_count\\s*=' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp rg -n -C 8 'clean\\.Evaluate\\(|bool Evaluate|Evaluate\\(Value' src/graphics/shader/recompiler/ir rg -n 'class .*Clean|struct .*Clean|Clean.*Evaluate|Value.*Evaluate' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp src/graphics/shader/recompiler/ir ``` Repository: KytyPS5/KytyPS5 Length of output: 542 --- 🏁 Script executed: ```bash rg -n 'key_count[[:space:]]*=' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp sed -n '1550,1620p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp sed -n '1735,1765p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp sed -n '1880,1920p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp rg -n 'Evaluate\(' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp sed -n '520,580p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp rg -n 'class.*Clean|struct.*Clean|CleanValue|clean\\.' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 12254 --- 🏁 Script executed: ```bash sed -n '1608,1745p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp sed -n '320,365p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp rg -n 'MatchUniformizedMaterialKey|key_count = bound->Arg' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 8936 --- 🏁 Script executed: ```bash rg -n 'ValidateRuntimeValue|MaterializeIndirectDescriptor' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp sed -n '300,345p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp sed -n '315,355p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp sed -n '420,490p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 8356 --- 🏁 Script executed: ```bash rg -n 'bool ValidateRuntimeValue|ValidateRuntimeValue\\(' src/graphics/shader/recompiler sed -n '1125,1225p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp rg -n 'SLessThan32|ULessThan32' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | head -40 ``` Repository: KytyPS5/KytyPS5 Length of output: 4999 --- 🏁 Script executed: ```bash rg -n -F 'ValidateRuntimeValue(' src rg -n -F 'bool ValidateRuntimeValue' src rg -n -F 'enum class RuntimeValueType' src rg -n -F 'RuntimeValueType::Integer' src/graphics/shader/recompiler ``` Repository: KytyPS5/KytyPS5 Length of output: 4056 --- 🏁 Script executed: ```bash sed -n '135,270p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp sed -n '975,1005p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp sed -n '15,35p' src/graphics/shader/recompiler/ir/passes/SrtWalker.h ``` Repository: KytyPS5/KytyPS5 Length of output: 6424 --- 🏁 Script executed: ```bash rg -n -F 'struct IndirectDescriptor' src/graphics/shader/recompiler rg -n -F 'key_count' src/graphics/shader/recompiler/ir rg -n -F 'IndirectDescriptor' src/graphics/shader/recompiler/ir/passes/ResourceTracking.h src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.h src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 7982 --- 🏁 Script executed: ```bash sed -n '480,515p' src/graphics/shader/recompiler/ir/ShaderIR.h sed -n '912,940p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp sed -n '990,1015p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 3601 --- 🏁 Script executed: ```bash sed -n '1588,1608p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp sed -n '1690,1760p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp sed -n '1868,1910p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 6660 --- 🏁 Script executed: ```bash nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1595,1606p;1628,1656p;1745,1755p;915,936p' nl -ba src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp | sed -n '330,342p;145,215p;980,990p' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '370,382p;1200,1215p' nl -ba src/graphics/shader/recompiler/ir/ShaderIR.h | sed -n '486,507p' ``` Repository: KytyPS5/KytyPS5 Length of output: 10713 --- 🏁 Script executed: ```bash nl -ba src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp | sed -n '215,250p' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1207,1224p' ``` Repository: KytyPS5/KytyPS5 Length of output: 2610 --- 🏁 Script executed: ```bash rg -n -F 'LoopBoundProof' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp sed -n '380,520p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 6051 --- 🏁 Script executed: ```bash nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '130,270p' ``` Repository: KytyPS5/KytyPS5 Length of output: 7314 --- </details> **Normalize negative signed bounds before applying the probe limit.** `BoundedLoop` accepts `SLessThan32` bounds and stores the bound as `key_count`. Evaluation preserves its U32 bit pattern, so a negative signed bound can exceed the probe limit before the later conversion to zero. This can make indirect-image materialization fail even though the zero-based loop has no iterations. Track the bound’s signedness and normalize only signed nonpositive counts; keep large unsigned bounds subject to the limit. <details> <summary>🐛 Suggested fix</summary> ```diff --- a/src/graphics/shader/recompiler/ir/ShaderIR.h +++ b/src/graphics/shader/recompiler/ir/ShaderIR.h @@ uint32_t workgroup_axis = UINT32_MAX; Value key_count; + bool key_count_signed = false; Value selector_first; --- a/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp +++ b/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp @@ a.table_stride != b.table_stride || a.workgroup_axis != b.workgroup_axis || a.sources != b.sources || + a.key_count_signed != b.key_count_signed || !EquivalentValue(m_program, a.key_count, b.key_count) || @@ indirect.selector_first = Value(0u); indirect.key_count = bound->Arg(1); + indirect.key_count_signed = bound->GetOpcode() == ValueOpcode::SLessThan32; @@ indirect.selector_first = first; indirect.key_count = bound->Arg(1); + indirect.key_count_signed = bound->GetOpcode() == ValueOpcode::SLessThan32; --- a/src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp +++ b/src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp @@ uint32_t first = 0, count = 0; if (!clean.Evaluate(indirect.selector_first, first) || - !clean.Evaluate(indirect.key_count, count) || count > MaxIndirectDescriptorProbes) + !clean.Evaluate(indirect.key_count, count)) return false; - if (std::bit_cast<int32_t>(count) <= 0) count = 0; + if (indirect.key_count_signed && std::bit_cast<int32_t>(count) <= 0) count = 0; + if (count > MaxIndirectDescriptorProbes) return false; ``` </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:aa363a43f2281c82d8cb83b2 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 4721ac4
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 20:04 UTC · original · edited 2026-10-06 21:18 UTC
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 1148 (outdated):

@@ -1062,14 +1131,48 @@ class Tracker {
 		return axis;
 	}
 
-	bool MatchTableOffset(Value value, Value& key, uint32_t& offset, uint32_t& stride) const {
+	// key & low, created once after key's definition so it dominates every table read.
+	Value MaskedKey(Value key, uint32_t low) {
+		for (const auto& [cached_key, cached_mask, value]: m_masked_keys)
+			if (cached_key == key && cached_mask == low) return value;
+		const auto* definition = key.TryInstruction();
+		if (definition == nullptr || definition->Parent() == nullptr) return {};
+		auto* block = definition->Parent();
+		auto where = std::ranges::find_if(block->Instructions(),
+		    [&](const Inst& inst) { return &inst == definition; });
+		if (where == block->Instructions().end()) return {};
+		++where;
+		const Value value(&*block->PrependNewInst(where, ValueOpcode::BitwiseAnd32, {key, Value(low)}));
+		m_masked_keys.emplace_back(key, low, value);
+		return value;
+	}

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1125,1185p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
rg -n 'ValueOpcode::Phi|OpPhi|case .*Phi|PrependNewInst' src/graphics/shader/recompiler/backend/spirv src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | head -85

Repository: KytyPS5/KytyPS5

Length of output: 8812


🏁 Script executed:

printf '%s\n' '--- MatchTableOffset consumers and surrounding logic ---'
rg -n -F -- 'MatchTableOffset(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
sed -n '1128,1265p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
printf '%s\n' '--- relevant plan call sites ---'
rg -n -F -- 'MatchTableOffset' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
rg -n -F -- 'PrependNewInst' src/graphics/shader/recompiler/ir
printf '%s\n' '--- insertion declaration/implementation ---'
rg -n -F -- 'PrependNewInst' src/graphics/shader/recompiler/ir
printf '%s\n' '--- SPIR-V block emission ---'
sed -n '610,690p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
printf '%s\n' '--- Phi handling at emitter entry ---'
sed -n '45,90p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
sed -n '245,325p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp

Repository: KytyPS5/KytyPS5

Length of output: 21649


🏁 Script executed:

printf '%s\n' '--- Block insertion implementation ---'
nl -ba src/graphics/shader/recompiler/ir/Block.cpp | sed -n '1,55p'
nl -ba src/graphics/shader/recompiler/ir/Block.h | sed -n '1,60p'

printf '%s\n' '--- first MatchTableOffset caller ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1540,1665p'

printf '%s\n' '--- second MatchTableOffset caller ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1765,1885p'

printf '%s\n' '--- plan and cleanup ordering ---'
rg -n -F -- 'EliminateDeadCode' src/graphics/shader/recompiler/ir src/graphics/shader/recompiler
rg -n -F -- 'ResourceTracking' src/graphics/shader/recompiler/ir

Repository: KytyPS5/KytyPS5

Length of output: 19816


🏁 Script executed:

printf '%s\n' '--- ResourceTracking initialization and DCE order ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '340,410p'
printf '%s\n' '--- SPIR-V emitter failure handling ---'
rg -n -F -- 'void Fail(' src/graphics/shader/recompiler/backend/spirv
rg -n -F -- 'ctx.Fail(inst' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp | sed -n '285,325p'

Repository: KytyPS5/KytyPS5

Length of output: 5597


🏁 Script executed:

nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '350,385p'
rg -n -F -- 'void Fail(' src/graphics/shader/recompiler/backend/spirv
rg -n -F -- 'ctx.Fail(inst' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp | sed -n '285,325p'

Repository: KytyPS5/KytyPS5

Length of output: 3975


🏁 Script executed:

printf '%s\n' '--- MatchLoopSelectedKey call site ---'
rg -n -F -- 'MatchLoopSelectedKey(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
printf '%s\n' '--- PlanIndirectDescriptors call path ---'
rg -n -F -- 'PlanIndirectDescriptors()' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1880,1965p'
printf '%s\n' '--- SPIR-V failure binding ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp | sed -n '1,35p'
rg -n -F -- 'void Fail' src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp

Repository: KytyPS5/KytyPS5

Length of output: 6744


🏁 Script executed:

printf '%s\n' '--- shader compilation pass order ---'
nl -ba src/graphics/shader/recompiler/ShaderRecompiler.cpp | sed -n '575,685p'
printf '%s\n' '--- resource tracking entry points and calls ---'
rg -n 'Track.*Resource|Resource.*Track|Tracker\\(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp src/graphics/shader/recompiler/ir/passes/ResourceTracking.h src/graphics/shader/recompiler/ShaderRecompiler.cpp

Repository: KytyPS5/KytyPS5

Length of output: 5795


🏁 Script executed:

printf '%s\n' '--- Tracker instruction generation ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '390,520p'
printf '%s\n' '--- plan key consumers ---'
rg -n -F -- 'plan.key' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
printf '%s\n' '--- resource specialization implementation ---'
rg -n -F -- 'ApplyResourceSpecialization' src/graphics/shader/recompiler

Repository: KytyPS5/KytyPS5

Length of output: 7283


🏁 Script executed:

printf '%s\n' '--- resource specialization implementation ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1240,1355p'
printf '%s\n' '--- compile pipeline after post-tracking DCE ---'
nl -ba src/graphics/shader/recompiler/ShaderRecompiler.cpp | sed -n '629,725p'

Repository: KytyPS5/KytyPS5

Length of output: 10299


🏁 Script executed:

nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1945,2015p'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '2200,2285p'

Repository: KytyPS5/KytyPS5

Length of output: 8532


🏁 Script executed:

rg -n -F -- 'SelectorMaximum(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Repository: KytyPS5/KytyPS5

Length of output: 679


🏁 Script executed:

nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '2025,2075p'

Repository: KytyPS5/KytyPS5

Length of output: 2809


Insert masked keys after the block’s final Phi.

A masked key can be accepted in an indirect-image plan when its mask bound is below 64. If that key is a Phi with later Phis, MaskedKey inserts a live BitwiseAnd32 between them. The SPIR-V emitter calls its failure path when it reaches a Phi after a non-Phi instruction. Insert after the complete Phi group.

A failed match does not roll back the insertion, but the claim that nothing later removes it is too strong: CompileProgram runs another dead-code elimination after resource tracking. The accepted-plan path can keep the masked key live, so that cleanup does not prevent the ordering failure.

Proposed fix
 		++where;
+		while (where != block->Instructions().end() && where->GetOpcode() == ValueOpcode::Phi)
+			++where;
 		const Value value(&*block->PrependNewInst(where, ValueOpcode::BitwiseAnd32, {key, Value(low)}));

✅ Addressed in commit 4721ac4

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 20:04 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#discussion_r4199907421) · edited 2026-10-06 21:18 UTC On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 1148 (outdated): ```diff @@ -1062,14 +1131,48 @@ class Tracker { return axis; } - bool MatchTableOffset(Value value, Value& key, uint32_t& offset, uint32_t& stride) const { + // key & low, created once after key's definition so it dominates every table read. + Value MaskedKey(Value key, uint32_t low) { + for (const auto& [cached_key, cached_mask, value]: m_masked_keys) + if (cached_key == key && cached_mask == low) return value; + const auto* definition = key.TryInstruction(); + if (definition == nullptr || definition->Parent() == nullptr) return {}; + auto* block = definition->Parent(); + auto where = std::ranges::find_if(block->Instructions(), + [&](const Inst& inst) { return &inst == definition; }); + if (where == block->Instructions().end()) return {}; + ++where; + const Value value(&*block->PrependNewInst(where, ValueOpcode::BitwiseAnd32, {key, Value(low)})); + m_masked_keys.emplace_back(key, low, value); + return value; + } ``` **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '1125,1185p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp rg -n 'ValueOpcode::Phi|OpPhi|case .*Phi|PrependNewInst' src/graphics/shader/recompiler/backend/spirv src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | head -85 ``` Repository: KytyPS5/KytyPS5 Length of output: 8812 --- 🏁 Script executed: ```bash printf '%s\n' '--- MatchTableOffset consumers and surrounding logic ---' rg -n -F -- 'MatchTableOffset(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp sed -n '1128,1265p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp printf '%s\n' '--- relevant plan call sites ---' rg -n -F -- 'MatchTableOffset' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp rg -n -F -- 'PrependNewInst' src/graphics/shader/recompiler/ir printf '%s\n' '--- insertion declaration/implementation ---' rg -n -F -- 'PrependNewInst' src/graphics/shader/recompiler/ir printf '%s\n' '--- SPIR-V block emission ---' sed -n '610,690p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp printf '%s\n' '--- Phi handling at emitter entry ---' sed -n '45,90p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp sed -n '245,325p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 21649 --- 🏁 Script executed: ```bash printf '%s\n' '--- Block insertion implementation ---' nl -ba src/graphics/shader/recompiler/ir/Block.cpp | sed -n '1,55p' nl -ba src/graphics/shader/recompiler/ir/Block.h | sed -n '1,60p' printf '%s\n' '--- first MatchTableOffset caller ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1540,1665p' printf '%s\n' '--- second MatchTableOffset caller ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1765,1885p' printf '%s\n' '--- plan and cleanup ordering ---' rg -n -F -- 'EliminateDeadCode' src/graphics/shader/recompiler/ir src/graphics/shader/recompiler rg -n -F -- 'ResourceTracking' src/graphics/shader/recompiler/ir ``` Repository: KytyPS5/KytyPS5 Length of output: 19816 --- 🏁 Script executed: ```bash printf '%s\n' '--- ResourceTracking initialization and DCE order ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '340,410p' printf '%s\n' '--- SPIR-V emitter failure handling ---' rg -n -F -- 'void Fail(' src/graphics/shader/recompiler/backend/spirv rg -n -F -- 'ctx.Fail(inst' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp | sed -n '285,325p' ``` Repository: KytyPS5/KytyPS5 Length of output: 5597 --- 🏁 Script executed: ```bash nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '350,385p' rg -n -F -- 'void Fail(' src/graphics/shader/recompiler/backend/spirv rg -n -F -- 'ctx.Fail(inst' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp | sed -n '285,325p' ``` Repository: KytyPS5/KytyPS5 Length of output: 3975 --- 🏁 Script executed: ```bash printf '%s\n' '--- MatchLoopSelectedKey call site ---' rg -n -F -- 'MatchLoopSelectedKey(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp printf '%s\n' '--- PlanIndirectDescriptors call path ---' rg -n -F -- 'PlanIndirectDescriptors()' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1880,1965p' printf '%s\n' '--- SPIR-V failure binding ---' nl -ba src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp | sed -n '1,35p' rg -n -F -- 'void Fail' src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 6744 --- 🏁 Script executed: ```bash printf '%s\n' '--- shader compilation pass order ---' nl -ba src/graphics/shader/recompiler/ShaderRecompiler.cpp | sed -n '575,685p' printf '%s\n' '--- resource tracking entry points and calls ---' rg -n 'Track.*Resource|Resource.*Track|Tracker\\(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp src/graphics/shader/recompiler/ir/passes/ResourceTracking.h src/graphics/shader/recompiler/ShaderRecompiler.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 5795 --- 🏁 Script executed: ```bash printf '%s\n' '--- Tracker instruction generation ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '390,520p' printf '%s\n' '--- plan key consumers ---' rg -n -F -- 'plan.key' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp printf '%s\n' '--- resource specialization implementation ---' rg -n -F -- 'ApplyResourceSpecialization' src/graphics/shader/recompiler ``` Repository: KytyPS5/KytyPS5 Length of output: 7283 --- 🏁 Script executed: ```bash printf '%s\n' '--- resource specialization implementation ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1240,1355p' printf '%s\n' '--- compile pipeline after post-tracking DCE ---' nl -ba src/graphics/shader/recompiler/ShaderRecompiler.cpp | sed -n '629,725p' ``` Repository: KytyPS5/KytyPS5 Length of output: 10299 --- 🏁 Script executed: ```bash nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1945,2015p' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '2200,2285p' ``` Repository: KytyPS5/KytyPS5 Length of output: 8532 --- 🏁 Script executed: ```bash rg -n -F -- 'SelectorMaximum(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 679 --- 🏁 Script executed: ```bash nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '2025,2075p' ``` Repository: KytyPS5/KytyPS5 Length of output: 2809 --- </details> **Insert masked keys after the block’s final Phi.** A masked key can be accepted in an indirect-image plan when its mask bound is below 64. If that key is a Phi with later Phis, `MaskedKey` inserts a live `BitwiseAnd32` between them. The SPIR-V emitter calls its failure path when it reaches a Phi after a non-Phi instruction. Insert after the complete Phi group. A failed match does not roll back the insertion, but the claim that nothing later removes it is too strong: `CompileProgram` runs another dead-code elimination after resource tracking. The accepted-plan path can keep the masked key live, so that cleanup does not prevent the ordering failure. <details> <summary>Proposed fix</summary> ```diff ++where; + while (where != block->Instructions().end() && where->GetOpcode() == ValueOpcode::Phi) + ++where; const Value value(&*block->PrependNewInst(where, ValueOpcode::BitwiseAnd32, {key, Value(low)})); ``` </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:5596c554202adf13db56143d --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 4721ac4
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 20:04 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d43c5aac-3bd4-4aa3-ba36-cb1cf1979fab
📥 Commits

Reviewing files that changed from the base of the PR and between 199d0a9d92 and c5bc56e17bbb5cc6577ae0365bc2e22e1ac2fb24.

📒 Files selected for processing (2)
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 20:04 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#pullrequestreview-5433960317) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `d43c5aac-3bd4-4aa3-ba36-cb1cf1979fab` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 199d0a9d9225e560432301e39439296d57fa0e34 and c5bc56e17bbb5cc6577ae0365bc2e22e1ac2fb24. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=7a3b8e45-daff-4a8c-a46e-ff4e456a44d8 attempt=372a4e9d-2518-4659-87cf-6b76a640e3df batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 20:27 UTC · original · reviewed

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Reject negative SMEM displacements in this matcher. · ResourceTracking.cpp:1585-1604

src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp:1585-1604
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject negative SMEM displacements in this matcher.

When a bounded image selector uses S_LOAD_DWORD with displacement -4, the matcher accepts the aligned displacement and stores 0xfffffffc as an unsigned selector offset. The shader uses signed address arithmetic, but materialization adds this offset to the scalar base. The host can read a different key and materialize a different descriptor, or return false if the computed address cannot be read.

Reject negative displacements here unless the selector representation and materializer preserve signed addressing.

Suggested fix
 		if (memory == nullptr || memory->kind != ResourceKind::ScalarAddress ||
-		    memory->data_dwords != 1u || (memory->offset & 3u) != 0u ||
+		    memory->data_dwords != 1u || (memory->offset & 0x80000000u) != 0u ||
+		    (memory->offset & 3u) != 0u ||
 		    !MemoryIndexBelongsTo(memory_index, *read)) return false;

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f649e13a-517e-43f0-af40-e1d37e84c0c3
📥 Commits

Reviewing files that changed from the base of the PR and between c5bc56e17bbb5cc6577ae0365bc2e22e1ac2fb24 and 39dfea39cd511664eadf4a889e2f553958de7152.

📒 Files selected for processing (2)
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 1 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 20:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#pullrequestreview-5434197260) · **reviewed** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><strong>🟡 Minor</strong> · Reject negative SMEM displacements in this matcher. · <code>ResourceTracking.cpp:1585-1604</code></summary><blockquote> > > `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp:1585-1604` > **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** > > **Reject negative SMEM displacements in this matcher.** > > When a bounded image selector uses `S_LOAD_DWORD` with displacement `-4`, the matcher accepts the aligned displacement and stores `0xfffffffc` as an unsigned selector offset. The shader uses signed address arithmetic, but materialization adds this offset to the scalar base. The host can read a different key and materialize a different descriptor, or return false if the computed address cannot be read. > > Reject negative displacements here unless the selector representation and materializer preserve signed addressing. > > <details> > <summary>Suggested fix</summary> > > ```diff > if (memory == nullptr || memory->kind != ResourceKind::ScalarAddress || > - memory->data_dwords != 1u || (memory->offset & 3u) != 0u || > + memory->data_dwords != 1u || (memory->offset & 0x80000000u) != 0u || > + (memory->offset & 3u) != 0u || > !MemoryIndexBelongsTo(memory_index, *read)) return false; > ``` > > </details> > > <!-- cr-comment:v1:cf2348ec053571b363574c5e --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `f649e13a-517e-43f0-af40-e1d37e84c0c3` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between c5bc56e17bbb5cc6577ae0365bc2e22e1ac2fb24 and 39dfea39cd511664eadf4a889e2f553958de7152. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 1 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=a47338d3-5739-463c-b7a6-6e1b37960284 attempt=53d56ded-b67e-4e21-b040-bbda627d24e8 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 20:36 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: daa12953-4ccc-4343-909b-d12a5c29f91c
📥 Commits

Reviewing files that changed from the base of the PR and between 39dfea39cd511664eadf4a889e2f553958de7152 and d645fdbc954bf8f7f2f91ee5a59766809b877d64.

📒 Files selected for processing (1)
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 0 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 20:36 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#pullrequestreview-5434286045) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `daa12953-4ccc-4343-909b-d12a5c29f91c` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 39dfea39cd511664eadf4a889e2f553958de7152 and d645fdbc954bf8f7f2f91ee5a59766809b877d64. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 0 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=24d14d60-c770-4603-ba64-9b1767bad815 attempt=3cd6ea90-9566-410e-856a-5881fdf1d56d batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 20:36 UTC · original · edited 2026-10-06 21:18 UTC
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 1589 (outdated):

@@ -1468,6 +1573,39 @@ class Tracker {
 		return true;
 	}
 
+	// key = S_LOAD_DWORD(ptr + index * stride + offset) with index a zero-based loop counter
+	// bounded by a runtime value: the host reads the first `bound` selector words.
+	bool MatchLoopSelectedKey(Value key, const Inst& image,
+	                          DescriptorSource::IndirectDescriptor& indirect,
+	                          DescriptorSource& material_source) {
+		if (m_shader_buffer_writes) return false;
+		const auto* read = key.Resolve().TryInstruction();
+		if (read == nullptr || read->GetOpcode() != ValueOpcode::LoadAddressU32) return false;
+		uint32_t memory_index = 0;
+		const auto* memory = ScalarReadMemory(*read, memory_index);
+		// The selector offset is added unsigned at materialization: no negative displacement.
+		if (memory == nullptr || memory->kind != ResourceKind::ScalarAddress ||
+		    memory->data_dwords != 1u || (memory->offset & 0x80000000u) != 0u ||
+		    (memory->offset & 3u) != 0u || !MemoryIndexBelongsTo(memory_index, *read)) return false;

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reject negative displacement in the matched selector offset.

If read->Arg(1) adds -4 and memory->offset is zero, MatchTableOffset records offset as 0xfffffffc. The new check accepts the zero memory offset, and the combined offset passes the later UINT32_MAX check. Materialization then reads a large positive offset instead of rejecting this selector plan. Check the sign of the matched immediate displacement before recording the selector.

✅ Addressed in commit 54ee0da

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 20:36 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#discussion_r4200189275) · edited 2026-10-06 21:18 UTC On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 1589 (outdated): ```diff @@ -1468,6 +1573,39 @@ class Tracker { return true; } + // key = S_LOAD_DWORD(ptr + index * stride + offset) with index a zero-based loop counter + // bounded by a runtime value: the host reads the first `bound` selector words. + bool MatchLoopSelectedKey(Value key, const Inst& image, + DescriptorSource::IndirectDescriptor& indirect, + DescriptorSource& material_source) { + if (m_shader_buffer_writes) return false; + const auto* read = key.Resolve().TryInstruction(); + if (read == nullptr || read->GetOpcode() != ValueOpcode::LoadAddressU32) return false; + uint32_t memory_index = 0; + const auto* memory = ScalarReadMemory(*read, memory_index); + // The selector offset is added unsigned at materialization: no negative displacement. + if (memory == nullptr || memory->kind != ResourceKind::ScalarAddress || + memory->data_dwords != 1u || (memory->offset & 0x80000000u) != 0u || + (memory->offset & 3u) != 0u || !MemoryIndexBelongsTo(memory_index, *read)) return false; ``` **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** **Reject negative displacement in the matched selector offset.** If `read->Arg(1)` adds `-4` and `memory->offset` is zero, `MatchTableOffset` records `offset` as `0xfffffffc`. The new check accepts the zero memory offset, and the combined offset passes the later `UINT32_MAX` check. Materialization then reads a large positive offset instead of rejecting this selector plan. Check the sign of the matched immediate displacement before recording the selector. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f61c0ab0335e9740ef99be1c --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 54ee0da
Author
Owner

@⁠NeySlim on GitHub · 2026-10-06 21:18 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 1148 (outdated):

@@ -1062,14 +1131,48 @@ class Tracker {
 		return axis;
 	}
 
-	bool MatchTableOffset(Value value, Value& key, uint32_t& offset, uint32_t& stride) const {
+	// key & low, created once after key's definition so it dominates every table read.
+	Value MaskedKey(Value key, uint32_t low) {
+		for (const auto& [cached_key, cached_mask, value]: m_masked_keys)
+			if (cached_key == key && cached_mask == low) return value;
+		const auto* definition = key.TryInstruction();
+		if (definition == nullptr || definition->Parent() == nullptr) return {};
+		auto* block = definition->Parent();
+		auto where = std::ranges::find_if(block->Instructions(),
+		    [&](const Inst& inst) { return &inst == definition; });
+		if (where == block->Instructions().end()) return {};
+		++where;
+		const Value value(&*block->PrependNewInst(where, ValueOpcode::BitwiseAnd32, {key, Value(low)}));
+		m_masked_keys.emplace_back(key, low, value);
+		return value;
+	}

Good catch, fixed in 39dfea3: the masked key is now inserted after the block's whole Phi group, so a key defined by a Phi no longer splits it.

**@⁠NeySlim** on GitHub · 2026-10-06 21:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#discussion_r4200533902) On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 1148 (outdated): ```diff @@ -1062,14 +1131,48 @@ class Tracker { return axis; } - bool MatchTableOffset(Value value, Value& key, uint32_t& offset, uint32_t& stride) const { + // key & low, created once after key's definition so it dominates every table read. + Value MaskedKey(Value key, uint32_t low) { + for (const auto& [cached_key, cached_mask, value]: m_masked_keys) + if (cached_key == key && cached_mask == low) return value; + const auto* definition = key.TryInstruction(); + if (definition == nullptr || definition->Parent() == nullptr) return {}; + auto* block = definition->Parent(); + auto where = std::ranges::find_if(block->Instructions(), + [&](const Inst& inst) { return &inst == definition; }); + if (where == block->Instructions().end()) return {}; + ++where; + const Value value(&*block->PrependNewInst(where, ValueOpcode::BitwiseAnd32, {key, Value(low)})); + m_masked_keys.emplace_back(key, low, value); + return value; + } ``` Good catch, fixed in 39dfea3: the masked key is now inserted after the block's whole Phi group, so a key defined by a Phi no longer splits it.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-06 21:18 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp line 374 (outdated):

@@ -367,6 +367,22 @@ bool MaterializeIndirectDescriptor(const ResourcePlan&                         p
 			}
 			keys.resize(key_count);
 			std::iota(keys.begin(), keys.end(), 0u);
+		} else if (!indirect.selector_first.IsEmpty() && material_value.dword_count == 2u) {
+			// Selector words behind a scalar pointer: no buffer bounds to honour.
+			uint32_t first = 0, count = 0;
+			if (!clean.Evaluate(indirect.selector_first, first) ||
+			    !clean.Evaluate(indirect.key_count, count) || count > MaxIndirectDescriptorProbes)

Reordered in 39dfea3 to match the immediate-key path: the count is normalized to zero for signed nonpositive values first and the probe limit is checked afterwards. I kept the existing "normalize then limit" semantics rather than adding a signedness flag, so an unsigned count above 2^31 is also treated as empty, as it already is for immediate keys; that case has no practical shader shape.

**@⁠NeySlim** on GitHub · 2026-10-06 21:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#discussion_r4200534211) On `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` line 374 (outdated): ```diff @@ -367,6 +367,22 @@ bool MaterializeIndirectDescriptor(const ResourcePlan& p } keys.resize(key_count); std::iota(keys.begin(), keys.end(), 0u); + } else if (!indirect.selector_first.IsEmpty() && material_value.dword_count == 2u) { + // Selector words behind a scalar pointer: no buffer bounds to honour. + uint32_t first = 0, count = 0; + if (!clean.Evaluate(indirect.selector_first, first) || + !clean.Evaluate(indirect.key_count, count) || count > MaxIndirectDescriptorProbes) ``` Reordered in 39dfea3 to match the immediate-key path: the count is normalized to zero for signed nonpositive values first and the probe limit is checked afterwards. I kept the existing "normalize then limit" semantics rather than adding a signedness flag, so an unsigned count above 2^31 is also treated as empty, as it already is for immediate keys; that case has no practical shader shape.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-06 21:18 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 1589 (outdated):

@@ -1468,6 +1573,39 @@ class Tracker {
 		return true;
 	}
 
+	// key = S_LOAD_DWORD(ptr + index * stride + offset) with index a zero-based loop counter
+	// bounded by a runtime value: the host reads the first `bound` selector words.
+	bool MatchLoopSelectedKey(Value key, const Inst& image,
+	                          DescriptorSource::IndirectDescriptor& indirect,
+	                          DescriptorSource& material_source) {
+		if (m_shader_buffer_writes) return false;
+		const auto* read = key.Resolve().TryInstruction();
+		if (read == nullptr || read->GetOpcode() != ValueOpcode::LoadAddressU32) return false;
+		uint32_t memory_index = 0;
+		const auto* memory = ScalarReadMemory(*read, memory_index);
+		// The selector offset is added unsigned at materialization: no negative displacement.
+		if (memory == nullptr || memory->kind != ResourceKind::ScalarAddress ||
+		    memory->data_dwords != 1u || (memory->offset & 0x80000000u) != 0u ||
+		    (memory->offset & 3u) != 0u || !MemoryIndexBelongsTo(memory_index, *read)) return false;

Agreed. d645fdb rejected a negative SMEM displacement and 54ee0da also rejects a negative shader-side immediate and a sum above INT32_MAX, since the materializer adds both unsigned.

**@⁠NeySlim** on GitHub · 2026-10-06 21:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#discussion_r4200534521) On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 1589 (outdated): ```diff @@ -1468,6 +1573,39 @@ class Tracker { return true; } + // key = S_LOAD_DWORD(ptr + index * stride + offset) with index a zero-based loop counter + // bounded by a runtime value: the host reads the first `bound` selector words. + bool MatchLoopSelectedKey(Value key, const Inst& image, + DescriptorSource::IndirectDescriptor& indirect, + DescriptorSource& material_source) { + if (m_shader_buffer_writes) return false; + const auto* read = key.Resolve().TryInstruction(); + if (read == nullptr || read->GetOpcode() != ValueOpcode::LoadAddressU32) return false; + uint32_t memory_index = 0; + const auto* memory = ScalarReadMemory(*read, memory_index); + // The selector offset is added unsigned at materialization: no negative displacement. + if (memory == nullptr || memory->kind != ResourceKind::ScalarAddress || + memory->data_dwords != 1u || (memory->offset & 0x80000000u) != 0u || + (memory->offset & 3u) != 0u || !MemoryIndexBelongsTo(memory_index, *read)) return false; ``` Agreed. d645fdb rejected a negative SMEM displacement and 54ee0da also rejects a negative shader-side immediate and a sum above `INT32_MAX`, since the materializer adds both unsigned.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 21:18 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 1148 (outdated):

@@ -1062,14 +1131,48 @@ class Tracker {
 		return axis;
 	}
 
-	bool MatchTableOffset(Value value, Value& key, uint32_t& offset, uint32_t& stride) const {
+	// key & low, created once after key's definition so it dominates every table read.
+	Value MaskedKey(Value key, uint32_t low) {
+		for (const auto& [cached_key, cached_mask, value]: m_masked_keys)
+			if (cached_key == key && cached_mask == low) return value;
+		const auto* definition = key.TryInstruction();
+		if (definition == nullptr || definition->Parent() == nullptr) return {};
+		auto* block = definition->Parent();
+		auto where = std::ranges::find_if(block->Instructions(),
+		    [&](const Inst& inst) { return &inst == definition; });
+		if (where == block->Instructions().end()) return {};
+		++where;
+		const Value value(&*block->PrependNewInst(where, ValueOpcode::BitwiseAnd32, {key, Value(low)}));
+		m_masked_keys.emplace_back(key, low, value);
+		return value;
+	}

@NeySlim, thanks for the fix. MaskedKey now inserts BitwiseAnd32 after the complete Phi group, which addresses the ordering issue.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 21:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#discussion_r4200536747) On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 1148 (outdated): ```diff @@ -1062,14 +1131,48 @@ class Tracker { return axis; } - bool MatchTableOffset(Value value, Value& key, uint32_t& offset, uint32_t& stride) const { + // key & low, created once after key's definition so it dominates every table read. + Value MaskedKey(Value key, uint32_t low) { + for (const auto& [cached_key, cached_mask, value]: m_masked_keys) + if (cached_key == key && cached_mask == low) return value; + const auto* definition = key.TryInstruction(); + if (definition == nullptr || definition->Parent() == nullptr) return {}; + auto* block = definition->Parent(); + auto where = std::ranges::find_if(block->Instructions(), + [&](const Inst& inst) { return &inst == definition; }); + if (where == block->Instructions().end()) return {}; + ++where; + const Value value(&*block->PrependNewInst(where, ValueOpcode::BitwiseAnd32, {key, Value(low)})); + m_masked_keys.emplace_back(key, low, value); + return value; + } ``` `@NeySlim`, thanks for the fix. `MaskedKey` now inserts `BitwiseAnd32` after the complete Phi group, which addresses the ordering issue. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=%40coderabbitai%20spotted%20a%20subtle%20SPIR-V%20correctness%20bug%3A%20inserting%20a%20masked%20key%20between%20Phi%20nodes%20breaks%20emission.%20Inserting%20it%20after%20the%20full%20Phi%20group%20fixes%20the%20ordering.%20Try%20CodeRabbit%20for%20sharp%20reviews!%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1118%23discussion_r4199907421)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 21:18 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 1589 (outdated):

@@ -1468,6 +1573,39 @@ class Tracker {
 		return true;
 	}
 
+	// key = S_LOAD_DWORD(ptr + index * stride + offset) with index a zero-based loop counter
+	// bounded by a runtime value: the host reads the first `bound` selector words.
+	bool MatchLoopSelectedKey(Value key, const Inst& image,
+	                          DescriptorSource::IndirectDescriptor& indirect,
+	                          DescriptorSource& material_source) {
+		if (m_shader_buffer_writes) return false;
+		const auto* read = key.Resolve().TryInstruction();
+		if (read == nullptr || read->GetOpcode() != ValueOpcode::LoadAddressU32) return false;
+		uint32_t memory_index = 0;
+		const auto* memory = ScalarReadMemory(*read, memory_index);
+		// The selector offset is added unsigned at materialization: no negative displacement.
+		if (memory == nullptr || memory->kind != ResourceKind::ScalarAddress ||
+		    memory->data_dwords != 1u || (memory->offset & 0x80000000u) != 0u ||
+		    (memory->offset & 3u) != 0u || !MemoryIndexBelongsTo(memory_index, *read)) return false;

@NeySlim Thanks for the clarification and fix. MatchLoopSelectedKey now rejects negative SMEM displacements, negative matched shader-side displacements, and combined offsets above INT32_MAX. These checks address the reported case.


✏️ Learnings added
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1118
File: src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp:1588-1589
Timestamp: 2026-10-06T21:18:26.437Z
Learning: In src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp, Tracker::MatchLoopSelectedKey must account for unsigned selector-offset addition in MaterializeIndirectDescriptor in src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp. Negative SMEM and matched shader-side displacements must not be treated as large positive selector offsets.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 21:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#discussion_r4200537831) On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 1589 (outdated): ```diff @@ -1468,6 +1573,39 @@ class Tracker { return true; } + // key = S_LOAD_DWORD(ptr + index * stride + offset) with index a zero-based loop counter + // bounded by a runtime value: the host reads the first `bound` selector words. + bool MatchLoopSelectedKey(Value key, const Inst& image, + DescriptorSource::IndirectDescriptor& indirect, + DescriptorSource& material_source) { + if (m_shader_buffer_writes) return false; + const auto* read = key.Resolve().TryInstruction(); + if (read == nullptr || read->GetOpcode() != ValueOpcode::LoadAddressU32) return false; + uint32_t memory_index = 0; + const auto* memory = ScalarReadMemory(*read, memory_index); + // The selector offset is added unsigned at materialization: no negative displacement. + if (memory == nullptr || memory->kind != ResourceKind::ScalarAddress || + memory->data_dwords != 1u || (memory->offset & 0x80000000u) != 0u || + (memory->offset & 3u) != 0u || !MemoryIndexBelongsTo(memory_index, *read)) return false; ``` `@NeySlim` Thanks for the clarification and fix. `MatchLoopSelectedKey` now rejects negative SMEM displacements, negative matched shader-side displacements, and combined offsets above `INT32_MAX`. These checks address the reported case. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1118 File: src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp:1588-1589 Timestamp: 2026-10-06T21:18:26.437Z Learning: In src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp, Tracker::MatchLoopSelectedKey must account for unsigned selector-offset addition in MaterializeIndirectDescriptor in src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp. Negative SMEM and matched shader-side displacements must not be treated as large positive selector offsets. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Negative%20selector%20displacements%20can%20wrap%20into%20large%20positive%20offsets%20and%20pass%20validation.%20Reject%20negative%20shader-side%20immediates%20and%20sums%20above%20%60INT32_MAX%60%20before%20materialization.%20Try%20%40coderabbitai%20for%20actionable%20code%20reviews!%20%F0%9F%9A%80&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1118%23discussion_r4200189275)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 21:18 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp line 374 (outdated):

@@ -367,6 +367,22 @@ bool MaterializeIndirectDescriptor(const ResourcePlan&                         p
 			}
 			keys.resize(key_count);
 			std::iota(keys.begin(), keys.end(), 0u);
+		} else if (!indirect.selector_first.IsEmpty() && material_value.dword_count == 2u) {
+			// Selector words behind a scalar pointer: no buffer bounds to honour.
+			uint32_t first = 0, count = 0;
+			if (!clean.Evaluate(indirect.selector_first, first) ||
+			    !clean.Evaluate(indirect.key_count, count) || count > MaxIndirectDescriptorProbes)

@NeySlim, the supplied code now normalizes nonpositive signed counts before checking MaxIndirectDescriptorProbes. This addresses the ordering issue.

Thanks for clarifying the intended semantics. Keeping the immediate-key behavior is reasonable for the supported shader shapes; a signedness flag is not needed for this fix.


✏️ Learnings added
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1118
File: src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp:0-0
Timestamp: 2026-10-06T21:18:24.919Z
Learning: In src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp, MaterializeIndirectDescriptor intentionally uses the same normalize-then-limit count semantics for scalar-pointer selector keys and immediate keys. It interprets the U32 count as int32_t and converts nonpositive values to zero before checking MaxIndirectDescriptorProbes. Unsigned counts with the high bit set therefore also become empty. The maintainer considers those unsigned counts outside practical supported shader shapes and does not require a separate signedness flag.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 21:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#discussion_r4200537985) On `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` line 374 (outdated): ```diff @@ -367,6 +367,22 @@ bool MaterializeIndirectDescriptor(const ResourcePlan& p } keys.resize(key_count); std::iota(keys.begin(), keys.end(), 0u); + } else if (!indirect.selector_first.IsEmpty() && material_value.dword_count == 2u) { + // Selector words behind a scalar pointer: no buffer bounds to honour. + uint32_t first = 0, count = 0; + if (!clean.Evaluate(indirect.selector_first, first) || + !clean.Evaluate(indirect.key_count, count) || count > MaxIndirectDescriptorProbes) ``` `@NeySlim`, the supplied code now normalizes nonpositive signed counts before checking `MaxIndirectDescriptorProbes`. This addresses the ordering issue. Thanks for clarifying the intended semantics. Keeping the immediate-key behavior is reasonable for the supported shader shapes; a signedness flag is not needed for this fix. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1118 File: src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp:0-0 Timestamp: 2026-10-06T21:18:24.919Z Learning: In src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp, MaterializeIndirectDescriptor intentionally uses the same normalize-then-limit count semantics for scalar-pointer selector keys and immediate keys. It interprets the U32 count as int32_t and converts nonpositive values to zero before checking MaxIndirectDescriptorProbes. Unsigned counts with the high bit set therefore also become empty. The maintainer considers those unsigned counts outside practical supported shader shapes and does not require a separate signedness flag. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Normalize%20signed%20nonpositive%20loop%20bounds%20before%20enforcing%20probe%20limits%E2%80%94otherwise%20zero-iteration%20indirect%20image%20loops%20can%20fail%20materialization.%20Try%20%40coderabbitai%20for%20sharp%20code%20reviews%20%F0%9F%90%87%E2%9A%A1&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1118%23discussion_r4199907404)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠NeySlim on GitHub · 2026-10-07 14:44 UTC · original

Pushed d615e4e with two fixes found while testing this branch on God of War Ragnarök (PPSA08332):

  1. TestGuardedDirectImageTable failed on this branch: its ExecZero and VccZero variants were accepted because EdgeProvesNonzero no longer required an all-lanes edge. The requirement from main is back, and the test passes again.

  2. Two bit-scan loops still failed with GetImageResource dword 0 is not a valid runtime value, because their guard is built with s_cselect_b64 <mask>, exec, 0:

    • pixel shader 0x3352cea59e15e2f2: the loop exits on s_cbranch_vccnz with vcc = ((ff1 >= n) || (ff1 == -1)) && exec;
    • compute shader 0x25e7d7d6b79a016f: s_cmp_lg_u32 -1, ff1; s_cselect_b64 s8, exec, 0; s_mov_b64 exec, s8.

    The texel only reaches registers through SelectU32(lanes, component, old). ObservedLanes returns that common lane predicate, and the key is accepted when either:

    • an all-lanes guard edge proves ff1 != -1 once lanes is known true (lanes implies the EXEC term of the guard), or
    • lanes itself contains ff1 != -1 (the second shader).

    Lanes that never observe the texel do not matter: a key outside the mapping falls back to the root resource.

Tests (resource_tracking, resource_materialization): new TestGuardedDirectImageTable variants. LaneExit and LaneMask are accepted. LaneUnobserved (texel not masked), LaneUnrelated (predicate unrelated to EXEC) and LaneAny (any-lane edge) are rejected. Without ObservedLanes, LaneExit and LaneMask fail with the original error.

AI use: investigated, written and tested with Claude Code (AI agent) on my machine; I reviewed the diff and the results.

**@⁠NeySlim** on GitHub · 2026-10-07 14:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#issuecomment-6040423975) Pushed d615e4e with two fixes found while testing this branch on God of War Ragnarök (PPSA08332): 1. `TestGuardedDirectImageTable` failed on this branch: its `ExecZero` and `VccZero` variants were accepted because `EdgeProvesNonzero` no longer required an all-lanes edge. The requirement from main is back, and the test passes again. 2. Two bit-scan loops still failed with `GetImageResource dword 0 is not a valid runtime value`, because their guard is built with `s_cselect_b64 <mask>, exec, 0`: - pixel shader `0x3352cea59e15e2f2`: the loop exits on `s_cbranch_vccnz` with `vcc = ((ff1 >= n) || (ff1 == -1)) && exec`; - compute shader `0x25e7d7d6b79a016f`: `s_cmp_lg_u32 -1, ff1; s_cselect_b64 s8, exec, 0; s_mov_b64 exec, s8`. The texel only reaches registers through `SelectU32(lanes, component, old)`. `ObservedLanes` returns that common lane predicate, and the key is accepted when either: - an all-lanes guard edge proves `ff1 != -1` once `lanes` is known true (`lanes` implies the EXEC term of the guard), or - `lanes` itself contains `ff1 != -1` (the second shader). Lanes that never observe the texel do not matter: a key outside the mapping falls back to the root resource. Tests (`resource_tracking`, `resource_materialization`): new `TestGuardedDirectImageTable` variants. `LaneExit` and `LaneMask` are accepted. `LaneUnobserved` (texel not masked), `LaneUnrelated` (predicate unrelated to EXEC) and `LaneAny` (any-lane edge) are rejected. Without `ObservedLanes`, `LaneExit` and `LaneMask` fail with the original error. AI use: investigated, written and tested with Claude Code (AI agent) on my machine; I reviewed the diff and the results.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 19:53 UTC · original

Rebased on main (59183dbf), squashed into one commit (65660f8d) since every commit conflicted with the reworked planner. Main now forwards the loop increment through a synthetic continue block in BoundedLoop, so I dropped that part and kept main's version. The rest sits on main's structures: the bit-scan proof no longer needs block_info, the twin-handle reuse runs inside the new per-handle plan_handle loop (images and samplers), TryMakeFiniteDescriptor replaces TryMakeFiniteImage, and the wider-record bound sits next to main's MatchScalarMaterialKey branch. resource_tracking and resource_materialization pass; the lane-guarded TestGuardedDirectImageTable variants fail with main's tracking and pass here. Full GPU suite, one case per process: 602/612, same as main.

**@⁠NeySlim** on GitHub · 2026-10-09 19:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#issuecomment-6088195323) Rebased on main (59183dbf), squashed into one commit (65660f8d) since every commit conflicted with the reworked planner. Main now forwards the loop increment through a synthetic continue block in `BoundedLoop`, so I dropped that part and kept main's version. The rest sits on main's structures: the bit-scan proof no longer needs `block_info`, the twin-handle reuse runs inside the new per-handle `plan_handle` loop (images and samplers), `TryMakeFiniteDescriptor` replaces `TryMakeFiniteImage`, and the wider-record bound sits next to main's `MatchScalarMaterialKey` branch. `resource_tracking` and `resource_materialization` pass; the lane-guarded `TestGuardedDirectImageTable` variants fail with main's tracking and pass here. Full GPU suite, one case per process: 602/612, same as main.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 20:38 UTC · original

Pushed 5114cc1: a negative selector value no longer binds a null descriptor.

In God of War Ragnarök (PPSA08332) the only negative key comes from pixel shader 0xb466313c9f94f942, where -1 is a "no texture" sentinel that the shader tests before the descriptor read:

s_mul_i32 vcc_lo, s97, 48
s_load_dword s2, s[0:1], vcc_lo offset:0xac4     ; key = selectors[i]
s_cmp_ge_i32 s2, 0
s_cbranch_scc0 ...                               ; skip the texture when key < 0
s_lshl_b32 vcc_hi, s2, 5
s_add_i32 vcc_lo, vcc_hi, 0x5f2c
s_load_dwordx8 s[24:31], s[0:1], vcc_lo
image_sample_lz v[0:2], v[7:8], s[24:31], s[88:91] dmask:0x7 dim:SQ_RSRC_IMG_2D

Changes:

  • Tracking marks the pointer-backed selector selector_nonnegative when every path from the key's load to the image crosses a uniform edge that proves key >= 0 (signed compares with an immediate, through LogicalNot and conjunctions). Materialization then drops negative keys, since the image never runs with them.
  • Without that proof, a negative key is handled like any other: its record is read at the address the shader computes, (key * stride + offset) in 32 bits. An unreadable record fails specialization as before.
  • A source shared through InternSource or a twin handle keeps the flag only if every use is proven.

Tests: TestLoopSelectedSignedKey covers the guarded key (no candidate for -1) and four cases without a valid proof (no guard, unrelated value, inverted guard, a second unguarded sample of the same table), where -1 reads the record before the table. Both halves fail on the previous commit. resource_tracking and resource_materialization pass, and the GPU suite (one case per process) gives 602 of 612, the same as main. In the game, all 13 loop-selected tables compiled up to the setup screen get the proof, and the game still reaches gameplay with correct rendering.

AI use: investigated, written and tested with Claude Code (AI agent) on my machine.

**@⁠NeySlim** on GitHub · 2026-10-09 20:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#issuecomment-6088855316) Pushed 5114cc1: a negative selector value no longer binds a null descriptor. In God of War Ragnarök (PPSA08332) the only negative key comes from pixel shader `0xb466313c9f94f942`, where -1 is a "no texture" sentinel that the shader tests before the descriptor read: ``` s_mul_i32 vcc_lo, s97, 48 s_load_dword s2, s[0:1], vcc_lo offset:0xac4 ; key = selectors[i] s_cmp_ge_i32 s2, 0 s_cbranch_scc0 ... ; skip the texture when key < 0 s_lshl_b32 vcc_hi, s2, 5 s_add_i32 vcc_lo, vcc_hi, 0x5f2c s_load_dwordx8 s[24:31], s[0:1], vcc_lo image_sample_lz v[0:2], v[7:8], s[24:31], s[88:91] dmask:0x7 dim:SQ_RSRC_IMG_2D ``` Changes: - Tracking marks the pointer-backed selector `selector_nonnegative` when every path from the key's load to the image crosses a uniform edge that proves `key >= 0` (signed compares with an immediate, through `LogicalNot` and conjunctions). Materialization then drops negative keys, since the image never runs with them. - Without that proof, a negative key is handled like any other: its record is read at the address the shader computes, `(key * stride + offset)` in 32 bits. An unreadable record fails specialization as before. - A source shared through `InternSource` or a twin handle keeps the flag only if every use is proven. Tests: `TestLoopSelectedSignedKey` covers the guarded key (no candidate for -1) and four cases without a valid proof (no guard, unrelated value, inverted guard, a second unguarded sample of the same table), where -1 reads the record before the table. Both halves fail on the previous commit. `resource_tracking` and `resource_materialization` pass, and the GPU suite (one case per process) gives 602 of 612, the same as main. In the game, all 13 loop-selected tables compiled up to the setup screen get the proof, and the game still reaches gameplay with correct rendering. AI use: investigated, written and tested with Claude Code (AI agent) on my machine.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-11 18:18 UTC · original

Rebased on main after 4c87dbeb; the only conflict was a test fixture (ImageSampleRaw now takes the EXEC operand), no change to the planner. resource_tracking, resource_materialization, scalar_provenance and shader_cfg pass, the guard-proof tests still fail when their rules are removed, and the GPU suite one case per process gives 613 of 623, the same as main.

**@⁠NeySlim** on GitHub · 2026-10-11 18:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#issuecomment-6112161771) Rebased on main after 4c87dbeb; the only conflict was a test fixture (`ImageSampleRaw` now takes the EXEC operand), no change to the planner. `resource_tracking`, `resource_materialization`, `scalar_provenance` and `shader_cfg` pass, the guard-proof tests still fail when their rules are removed, and the GPU suite one case per process gives 613 of 623, the same as main.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-14 07:05 UTC · original

Rebased on main. Most of this landed in 1fa79d5c, 7e884f55, ed1195d1 and 9a3aca96; what is left is the bit scan bound carried by the image's EXEC, the signed loop count and the negative-key proof. Added a key >= -1 case to the test.

**@⁠NeySlim** on GitHub · 2026-10-14 07:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#issuecomment-6162878073) Rebased on main. Most of this landed in 1fa79d5c, 7e884f55, ed1195d1 and 9a3aca96; what is left is the bit scan bound carried by the image's EXEC, the signed loop count and the negative-key proof. Added a key >= -1 case to the test.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-14 07:16 UTC · original

Correction to my last comment: the parts that landed are a287a54f2, 25e1cc7ec, d70cbd418, ed1195d1, 9a3aca96, 7e884f55 and 1fa79d5c (body updated).

**@⁠NeySlim** on GitHub · 2026-10-14 07:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#issuecomment-6163034839) Correction to my last comment: the parts that landed are a287a54f2, 25e1cc7ec, d70cbd418, ed1195d1, 9a3aca96, 7e884f55 and 1fa79d5c (body updated).
Author
Owner

@⁠Ekt0re on GitHub · 2026-10-26 15:59 UTC · original

Hi, I was looking at this pull request, and I see it's very interesting. How's it going? Have you made any recent updates or achieved any new results?

**@⁠Ekt0re** on GitHub · 2026-10-26 15:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#issuecomment-6420666654) Hi, I was looking at this pull request, and I see it's very interesting. How's it going? Have you made any recent updates or achieved any new results?
Author
Owner

@⁠NeySlim on GitHub · 2026-10-26 16:06 UTC · original

No updates, I've stopped working on this. Most of it landed on main already; the branch stays open if anyone wants to pick up the rest.

**@⁠NeySlim** on GitHub · 2026-10-26 16:06 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1118#issuecomment-6420844202) No updates, I've stopped working on this. Most of it landed on main already; the branch stays open if anyone wants to pick up the rest.
This pull request has changes conflicting with the target branch.
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.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/1118/head:github-bot/gh-1118'
git switch 'github-bot/gh-1118'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1118'
git switch 'github-bot/gh-1118'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1118'
git switch 'github-bot/gh-1118'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1118'
git switch 'main'
git merge --squash 'github-bot/gh-1118'
git switch 'main'
git merge --ff-only 'github-bot/gh-1118'
git switch 'main'
git merge 'github-bot/gh-1118'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.