shader: fix indirect light tables instead of tolerating stale slots #1255

Open
github-bot wants to merge 1 commit from github-bot/gh-1255 into main AGit
Owner

@⁠NeySlim on GitHub · 2026-10-08 20:26 UTC · original
NeySlim:fix/bitscan-mask-keys → main · +579 −12 · 4 files · 1 commits · open

This replaces #1119, which was rightly closed as a hack: instead of binding null images or downgrading errors for "stale" descriptor-table slots, it fixes why those slots were read. The error was reproduced on God of War Ragnarök (PPSA08332, 05.005) with the #1119 tolerances removed.

Part of the original PR landed on main in the meantime (735a2292, 652154ae, 9bcf80bf), and main's dimension rules (b6da0683) now cover what the mixed-dimension commits did for this game, so they were dropped. What is left is the bit scan bound.

shader: bound bit scan image keys by mask bits and table count

Error: sampled image descriptor 17 uses unsupported format 2, then invalid data image range: address=0x10391a700000 (a 64-bit pointer read as a T#), from the clustered-lighting compute shaders (e.g. 4579381eaaeeead7, 2bbe19f271202135).

Cause: the light tables are walked with a bit scan (s_ff1_i32_b32 / s_bitset0_b32) and the planner probed all 32 keys. The shader only visits the set bits of its mask, the mask is a 12-bit field (s_bfe_u32 ..., 0xc0010), and the loop exits at key >= count, with count read from the table (s_cmp_ge_u32 directly or through a flag s_cselect/s_or/s_cmp_lg_u32 0). Records past count hold unrelated data.

Change: the plan keeps the scanned mask when it can be evaluated (ScannedMask), its width (MaskWidth, kept as the descriptor's key_limit), and a key < count bound proven on every edge that reaches the sample (ScanBound). Materialization enumerates the set bits within [0, min(count, width)), so the plan adds no instruction to the shader. The entry mask is used only when every back edge provably clears bits of it; that proof resolves a lane select to one arm only behind a uniform branch or an EXEC branch.

Tests: TestBitScanKeyRange and TestBitScanMaskProof in resource_tracking_tests. TestBitScanKeyRange fails on main without this commit.

Validation

Linux, Radeon 8060S, Mesa RADV 26.2.4, rebased on 42bb0da5.

  • resource_tracking, resource_materialization, scalar_provenance and shader_cfg pass. shader_recompiler_compute_tests one case per process: same 52 failures as main on this setup (out of 775).
  • God of War Ragnarök, traced runs from a new game through the sled section: 353 indirect image tables planned, each with a single dimension.

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

AI use

I used Claude Code (AI agent) to reproduce the errors without the tolerances, trace them to their causes in the shaders, write the changes and the tests, and run the tests and the game above on my machine. I reviewed the diff and the results before opening this PR.

**@⁠NeySlim** on GitHub · 2026-10-08 20:26 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255) `NeySlim:fix/bitscan-mask-keys` → `main` · +579 −12 · 4 files · 1 commits · open This replaces #1119, which was rightly closed as a hack: instead of binding null images or downgrading errors for "stale" descriptor-table slots, it fixes why those slots were read. The error was reproduced on God of War Ragnarök (PPSA08332, 05.005) with the #1119 tolerances removed. Part of the original PR landed on main in the meantime (735a2292, 652154ae, 9bcf80bf), and main's dimension rules (b6da0683) now cover what the mixed-dimension commits did for this game, so they were dropped. What is left is the bit scan bound. ## shader: bound bit scan image keys by mask bits and table count **Error:** `sampled image descriptor 17 uses unsupported format 2`, then `invalid data image range: address=0x10391a700000` (a 64-bit pointer read as a T#), from the clustered-lighting compute shaders (e.g. `4579381eaaeeead7`, `2bbe19f271202135`). **Cause:** the light tables are walked with a bit scan (`s_ff1_i32_b32` / `s_bitset0_b32`) and the planner probed all 32 keys. The shader only visits the set bits of its mask, the mask is a 12-bit field (`s_bfe_u32 ..., 0xc0010`), and the loop exits at `key >= count`, with `count` read from the table (`s_cmp_ge_u32` directly or through a flag `s_cselect`/`s_or`/`s_cmp_lg_u32 0`). Records past `count` hold unrelated data. **Change:** the plan keeps the scanned mask when it can be evaluated (`ScannedMask`), its width (`MaskWidth`, kept as the descriptor's `key_limit`), and a `key < count` bound proven on every edge that reaches the sample (`ScanBound`). Materialization enumerates the set bits within `[0, min(count, width))`, so the plan adds no instruction to the shader. The entry mask is used only when every back edge provably clears bits of it; that proof resolves a lane select to one arm only behind a uniform branch or an EXEC branch. **Tests:** `TestBitScanKeyRange` and `TestBitScanMaskProof` in `resource_tracking_tests`. `TestBitScanKeyRange` fails on main without this commit. ## Validation Linux, Radeon 8060S, Mesa RADV 26.2.4, rebased on 42bb0da5. - resource_tracking, resource_materialization, scalar_provenance and shader_cfg pass. `shader_recompiler_compute_tests` one case per process: same 52 failures as main on this setup (out of 775). - God of War Ragnarök, traced runs from a new game through the sled section: 353 indirect image tables planned, each with a single dimension. Not tested on Windows or macOS; the change is platform-independent recompiler code. ## AI use I used Claude Code (AI agent) to reproduce the errors without the tolerances, trace them to their causes in the shaders, write the changes and the tests, and run the tests and the game above on my machine. I reviewed the diff and the results before opening this PR.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:50:14 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 20:33 UTC · original · edited 2026-10-17 07:55 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: 06e6dc5d6e2aa53a1937c68a6e07a3b298a9aa72
  • Latest commit, not reviewed: 406ff33018

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: d2759c64-91df-4757-b624-d721dfe13baa
📥 Commits

Reviewing files that changed from the base of the PR and between f42dfe429c52c551e248d7a9ba9c1afe52aae0e3 and 06e6dc5d6e2aa53a1937c68a6e07a3b298a9aa72.

📒 Files selected for processing (6)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ShaderRecompilerComputeTests.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.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The image source path now uses a temporary upload buffer when the staging ring cannot map the requested range. Resource tracking derives bounds for bit-scan indirect image selectors and records image-use patterns. Materialization enumerates selected keys and checks candidate compatibility. The SPIR-V emitter limits coordinates to the instruction dimension. New tests cover oversized image uploads and indirect image tracking, materialization, and emission.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 06e6d

This change fixes indirect image light tables and adds a fallback upload path for oversized images, with test coverage for each fix. No outstanding issues were identified in the reviewed changes, and earlier review concerns have been addressed.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 31.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 35 functions across 6 files. (1 skipped: … 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.
Title check Passed The title clearly identifies the main change: fixing indirect light tables instead of tolerating stale descriptor slots.
Description check Passed The description directly explains the causes, fixes, tests, validation results, and scope of the indirect image table and oversized image changes.
Full details: Docstring Coverage

Explanation

Docstring coverage is 31.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 35 functions across 6 files. (1 skipped: 1 too large.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • 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-08 20:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#issuecomment-6068535182) · edited 2026-10-17 07:55 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/1255?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: 06e6dc5d6e2aa53a1937c68a6e07a3b298a9aa72 > - Latest commit, not reviewed: 406ff3301858f1c9890d9fd38eaca8c5c5658736 > > 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**: `d2759c64-91df-4757-b624-d721dfe13baa` </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between f42dfe429c52c551e248d7a9ba9c1afe52aae0e3 and 06e6dc5d6e2aa53a1937c68a6e07a3b298a9aa72. </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing (6)</strong></summary> <dl> <dd> * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </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. </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 The image source path now uses a temporary upload buffer when the staging ring cannot map the requested range. Resource tracking derives bounds for bit-scan indirect image selectors and records image-use patterns. Materialization enumerates selected keys and checks candidate compatibility. The SPIR-V emitter limits coordinates to the instruction dimension. New tests cover oversized image uploads and indirect image tracking, materialization, and emission. **Suggested reviewers:** `nmzik` </dd> </dl> </details> </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"06e6dc5d6e2aa53a1937c68a6e07a3b298a9aa72" --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>⚪ Minimal</strong> · up to <code>06e6d</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **⚪ Minimal** · up to `06e6d` --> <!-- final_review_risk_coverage:{"sourceCommitId":"06e6dc5d6e2aa53a1937c68a6e07a3b298a9aa72","coveredCommitId":"06e6dc5d6e2aa53a1937c68a6e07a3b298a9aa72","kind":"reviewed"} --> This change fixes indirect image light tables and adds a fallback upload path for oversized images, with test coverage for each fix. No outstanding issues were identified in the reviewed changes, and earlier review concerns have been addressed. <!-- 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-inconclusive-14-v2.svg" width="14" height="14" align="middle" alt="Inconclusive" title="Inconclusive"></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 inconclusive</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | Docstring coverage is 31.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 35 functions across 6 files. (1 skipped: … | 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. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly identifies the main change: fixing indirect light tables instead of tolerating stale descriptor slots. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the causes, fixes, tests, validation results, and scope of the indirect image table and oversized image changes. | </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 31.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 35 functions across 6 files. (1 skipped: 1 too large.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </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=1255)! 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-08 20:33 UTC · original · edited 2026-10-08 21:50 UTC
On src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp line 652 (outdated):

@@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna
 			return dimension == Decoder::ImageDimension::Dim2D ||
 			       dimension == Decoder::ImageDimension::Dim2DArray;
 		};
+		// A plain sample reads the selected record with the record's own type, as the T#
+		// drives the hardware: records of another dimension or numeric class stay candidates.
+		// Derivatives, offsets and gathers are laid out for one dimension only.
+		const auto& base_root    = program.info.images[root_index];
+		uint32_t    sample_flags = 0;
+		for (const auto& memory: program.memory_info) {
+			if (memory.kind == ResourceKind::Image && memory.resource == root_index) {
+				sample_flags |= memory.image_sample_flags;
+			}
+		}
+		const bool mixed_dimensions =
+		    base_root.resource_class == ImageResourceClass::Sampled && !base_root.written &&
+		    !base_root.atomic &&
+		    (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset |
+		                     Decoder::ImageSampleFlagGatherHorizontal)) == 0u;

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Exclude multisampled candidates from mixed_dimensions.

mixed_dimensions accepts a candidate of any dimension. DescriptorDimension maps kColor2DMsaa and kColor2DMsaaArray to Dim2DMsaa and Dim2DMsaaArray. The normalize callback nulls a dimension mismatch only for bounded tables. It does not null mismatches for bit-scan tables or for explicitly selected sources.

Consider a heap that contains an MSAA render-target descriptor in a plain-sample table. That candidate now passes the check at Lines 669-671. Before this change, the check rejected it. EmitSample in spirvEmitterImage.cpp then emits OpSampledImage and OpImageSample* on a multisampled image. SPIR-V does not allow either operation on an image with MS=1. The module is invalid and can fail pipeline creation or crash the driver.

Reject multisampled candidates when their coordinates differ from the exemplar's.

🐛 Proposed fix
 		const bool mixed_dimensions =
 		    base_root.resource_class == ImageResourceClass::Sampled && !base_root.written &&
 		    !base_root.atomic &&
 		    (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset |
 		                     Decoder::ImageSampleFlagGatherHorizontal)) == 0u;
+		const auto is_msaa = [](Decoder::ImageDimension dimension) {
+			return dimension == Decoder::ImageDimension::Dim2DMsaa ||
+			       dimension == Decoder::ImageDimension::Dim2DMsaaArray;
+		};

In the candidate check, add this condition:

 			if ((image.numeric_class != image_class.numeric_class && !mixed_classes) ||
+			    (!same_coordinates && (is_msaa(image.dimension) || is_msaa(image_class.dimension))) ||
 			    (!same_coordinates && !mixed_dimensions &&

✅ Addressed in commits 19a361f to cfe3000

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 20:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#discussion_r4223850968) · edited 2026-10-08 21:50 UTC On `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` line 652 (outdated): ```diff @@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna return dimension == Decoder::ImageDimension::Dim2D || dimension == Decoder::ImageDimension::Dim2DArray; }; + // A plain sample reads the selected record with the record's own type, as the T# + // drives the hardware: records of another dimension or numeric class stay candidates. + // Derivatives, offsets and gathers are laid out for one dimension only. + const auto& base_root = program.info.images[root_index]; + uint32_t sample_flags = 0; + for (const auto& memory: program.memory_info) { + if (memory.kind == ResourceKind::Image && memory.resource == root_index) { + sample_flags |= memory.image_sample_flags; + } + } + const bool mixed_dimensions = + base_root.resource_class == ImageResourceClass::Sampled && !base_root.written && + !base_root.atomic && + (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset | + Decoder::ImageSampleFlagGatherHorizontal)) == 0u; ``` **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** **Exclude multisampled candidates from `mixed_dimensions`.** `mixed_dimensions` accepts a candidate of any dimension. `DescriptorDimension` maps `kColor2DMsaa` and `kColor2DMsaaArray` to `Dim2DMsaa` and `Dim2DMsaaArray`. The normalize callback nulls a dimension mismatch only for bounded tables. It does not null mismatches for bit-scan tables or for explicitly selected `sources`. Consider a heap that contains an MSAA render-target descriptor in a plain-sample table. That candidate now passes the check at Lines 669-671. Before this change, the check rejected it. `EmitSample` in `spirvEmitterImage.cpp` then emits `OpSampledImage` and `OpImageSample*` on a multisampled image. SPIR-V does not allow either operation on an image with MS=1. The module is invalid and can fail pipeline creation or crash the driver. Reject multisampled candidates when their coordinates differ from the exemplar's. <details> <summary>🐛 Proposed fix</summary> ```diff const bool mixed_dimensions = base_root.resource_class == ImageResourceClass::Sampled && !base_root.written && !base_root.atomic && (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset | Decoder::ImageSampleFlagGatherHorizontal)) == 0u; + const auto is_msaa = [](Decoder::ImageDimension dimension) { + return dimension == Decoder::ImageDimension::Dim2DMsaa || + dimension == Decoder::ImageDimension::Dim2DMsaaArray; + }; ``` In the candidate check, add this condition: ```diff if ((image.numeric_class != image_class.numeric_class && !mixed_classes) || + (!same_coordinates && (is_msaa(image.dimension) || is_msaa(image_class.dimension))) || (!same_coordinates && !mixed_dimensions && ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:9cf62ab6ccfc33aaf1ca3378 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commits 19a361f to cfe3000
Author
Owner

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

@@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna
 			return dimension == Decoder::ImageDimension::Dim2D ||
 			       dimension == Decoder::ImageDimension::Dim2DArray;
 		};
+		// A plain sample reads the selected record with the record's own type, as the T#
+		// drives the hardware: records of another dimension or numeric class stay candidates.
+		// Derivatives, offsets and gathers are laid out for one dimension only.
+		const auto& base_root    = program.info.images[root_index];
+		uint32_t    sample_flags = 0;
+		for (const auto& memory: program.memory_info) {
+			if (memory.kind == ResourceKind::Image && memory.resource == root_index) {
+				sample_flags |= memory.image_sample_flags;
+			}
+		}
+		const bool mixed_dimensions =
+		    base_root.resource_class == ImageResourceClass::Sampled && !base_root.written &&
+		    !base_root.atomic &&
+		    (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset |
+		                     Decoder::ImageSampleFlagGatherHorizontal)) == 0u;
+		const bool mixed_classes = mixed_dimensions && !base_root.depth_compare;

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C4 'force_point_filtering|integer_border' --type=cpp
rg -nP -C6 '\bMakeSampledImage\s*\(' --type=cpp

Repository: KytyPS5/KytyPS5

Length of output: 23919


🏁 Script executed:

set -e
printf '%s\n' '--- ResourceMaterialization sampler planning and specialization ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '560,705p'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1235,1350p'
printf '%s\n' '--- indirect image emission ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp | sed -n '780,875p'
printf '%s\n' '--- relevant PR diff ---'
git diff aa3b2cd57f84e414a4af0ccbc42d7eb35a8af17b 720d10cc976f28cc0af5f0bfa1857406017edc22 -- src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp

Repository: KytyPS5/KytyPS5

Length of output: 24288


🏁 Script executed:

set -e
printf '%s\n' '--- indirect candidate emission ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp | sed -n '838,965p'
printf '%s\n' '--- ApplyResourceSpecialization memory and pair remap ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1340,1425p'
printf '%s\n' '--- sampler classification declarations and uses ---'
rg -n -F -- 'enum class SamplerClass' src
rg -n -F -- 'SamplerClass ClassifySampler' src
rg -n -F -- 'ClassifySampler(' src/graphics/shader/recompiler

Repository: KytyPS5/KytyPS5

Length of output: 12728


🏁 Script executed:

set -e
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '96,125p'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1418,1432p'

Repository: KytyPS5/KytyPS5

Length of output: 2165


Do not reuse the root sampler for mixed numeric classes.

EmitSample uses each candidate's image type but passes the same mem.sampler to every candidate. ApplyResourceSpecialization selects that sampler from the indirect root. Therefore, an integer candidate under a float root can use float border-color settings and linear filtering. The reverse case can also use integer-root settings, including point filtering for PointInteger.

Restrict mixed numeric classes to candidates with the same SamplerClass, or add per-class sampler variants for indirect candidates.

🐛 Suggested fix
-			if ((image.numeric_class != image_class.numeric_class && !mixed_classes) ||
+			if ((image.numeric_class != image_class.numeric_class &&
+			     (!mixed_classes ||
+			      ClassifySampler(image) != ClassifySampler(image_class))) ||

✅ Addressed in commits 19a361f to cfe3000

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 20:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#discussion_r4223850985) · edited 2026-10-08 21:51 UTC On `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` line 653 (outdated): ```diff @@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna return dimension == Decoder::ImageDimension::Dim2D || dimension == Decoder::ImageDimension::Dim2DArray; }; + // A plain sample reads the selected record with the record's own type, as the T# + // drives the hardware: records of another dimension or numeric class stay candidates. + // Derivatives, offsets and gathers are laid out for one dimension only. + const auto& base_root = program.info.images[root_index]; + uint32_t sample_flags = 0; + for (const auto& memory: program.memory_info) { + if (memory.kind == ResourceKind::Image && memory.resource == root_index) { + sample_flags |= memory.image_sample_flags; + } + } + const bool mixed_dimensions = + base_root.resource_class == ImageResourceClass::Sampled && !base_root.written && + !base_root.atomic && + (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset | + Decoder::ImageSampleFlagGatherHorizontal)) == 0u; + const bool mixed_classes = mixed_dimensions && !base_root.depth_compare; ``` **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C4 'force_point_filtering|integer_border' --type=cpp rg -nP -C6 '\bMakeSampledImage\s*\(' --type=cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 23919 --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- ResourceMaterialization sampler planning and specialization ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '560,705p' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1235,1350p' printf '%s\n' '--- indirect image emission ---' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp | sed -n '780,875p' printf '%s\n' '--- relevant PR diff ---' git diff aa3b2cd57f84e414a4af0ccbc42d7eb35a8af17b 720d10cc976f28cc0af5f0bfa1857406017edc22 -- src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 24288 --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- indirect candidate emission ---' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp | sed -n '838,965p' printf '%s\n' '--- ApplyResourceSpecialization memory and pair remap ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1340,1425p' printf '%s\n' '--- sampler classification declarations and uses ---' rg -n -F -- 'enum class SamplerClass' src rg -n -F -- 'SamplerClass ClassifySampler' src rg -n -F -- 'ClassifySampler(' src/graphics/shader/recompiler ``` Repository: KytyPS5/KytyPS5 Length of output: 12728 --- 🏁 Script executed: ```bash set -e nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '96,125p' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1418,1432p' ``` Repository: KytyPS5/KytyPS5 Length of output: 2165 --- </details> **Do not reuse the root sampler for mixed numeric classes.** `EmitSample` uses each candidate's image type but passes the same `mem.sampler` to every candidate. `ApplyResourceSpecialization` selects that sampler from the indirect root. Therefore, an integer candidate under a float root can use float border-color settings and linear filtering. The reverse case can also use integer-root settings, including point filtering for `PointInteger`. Restrict mixed numeric classes to candidates with the same `SamplerClass`, or add per-class sampler variants for indirect candidates. <details> <summary>🐛 Suggested fix</summary> ```diff - if ((image.numeric_class != image_class.numeric_class && !mixed_classes) || + if ((image.numeric_class != image_class.numeric_class && + (!mixed_classes || + ClassifySampler(image) != ClassifySampler(image_class))) || ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:027f210c076f8f4c6c9ce696 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commits 19a361f to cfe3000
Author
Owner

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/graphics/host_gpu/renderer/cache/bufferCache.cpp (1)

532-542: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Fallback buffer release is deferred correctly, but the fallback depends on Map returning null only for oversize.

The temporary upload buffer is flushed and its release is deferred through DeferOperation, which matches UploadCopies (Line 470). UploadCopies already uses the same pattern. The two paths are consistent.

One open question remains. m_staging_buffer.Map(size, 16) can return null for reasons other than "larger than the ring". One example is a transient full ring. The comment on Line 532 states only the oversize case. The fallback is still correct in both cases, but it allocates a full-size host buffer each time. Update the comment to say the fallback also applies when the ring cannot currently map the range.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0596e6f3-da84-46a8-ac07-c5fc7e90edf4
📥 Commits

Reviewing files that changed from the base of the PR and between 2f4b8a335d and 720d10cc976f28cc0af5f0bfa1857406017edc22.

📒 Files selected for processing (6)
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 20:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#pullrequestreview-5462523072) · **reviewed** **Actionable comments posted: 2** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>src/graphics/host_gpu/renderer/cache/bufferCache.cpp (1)</summary><blockquote> `532-542`: **📐 Maintainability & Code Quality** | **🔵 Trivial** | **💤 Low value** **Fallback buffer release is deferred correctly, but the fallback depends on `Map` returning null only for oversize.** The temporary upload buffer is flushed and its release is deferred through `DeferOperation`, which matches `UploadCopies` (Line 470). `UploadCopies` already uses the same pattern. The two paths are consistent. One open question remains. `m_staging_buffer.Map(size, 16)` can return null for reasons other than "larger than the ring". One example is a transient full ring. The comment on Line 532 states only the oversize case. The fallback is still correct in both cases, but it allocates a full-size host buffer each time. Update the comment to say the fallback also applies when the ring cannot currently map the range. <!-- cr-comment:v1:15c476e9ab28fd644b7b55c8 --> </blockquote></details> </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**: `0596e6f3-da84-46a8-ac07-c5fc7e90edf4` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 2f4b8a335d5e27a5153bdea670bd877a061e37b1 and 720d10cc976f28cc0af5f0bfa1857406017edc22. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=95dc75e3-7fa8-4c41-92a3-19aea9fb025f attempt=1114fcc6-a665-427c-b81f-fa80868eff3c batch=1/1 -->
Author
Owner

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

@@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna
 			return dimension == Decoder::ImageDimension::Dim2D ||
 			       dimension == Decoder::ImageDimension::Dim2DArray;
 		};
+		// A plain sample reads the selected record with the record's own type, as the T#
+		// drives the hardware: records of another dimension or numeric class stay candidates.
+		// Derivatives, offsets and gathers are laid out for one dimension only.
+		const auto& base_root    = program.info.images[root_index];
+		uint32_t    sample_flags = 0;
+		for (const auto& memory: program.memory_info) {
+			if (memory.kind == ResourceKind::Image && memory.resource == root_index) {
+				sample_flags |= memory.image_sample_flags;
+			}
+		}
+		const bool mixed_dimensions =
+		    base_root.resource_class == ImageResourceClass::Sampled && !base_root.written &&
+		    !base_root.atomic &&
+		    (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset |
+		                     Decoder::ImageSampleFlagGatherHorizontal)) == 0u;

Agreed, fixed in 19a361f1. Once a plain sample accepted candidates of another dimension, a multisampled record in a bit scan table or in explicitly selected sources passed the check (only bounded tables drop a dimension mismatch), and EmitSample would have emitted OpSampledImage/OpImageSample* on an MS=1 image. Indirect tables are only sampled, so a multisampled candidate now refuses the table on every table shape, whatever its coordinates. This also covers a table whose records are all multisampled, which was accepted before this PR and produced the same invalid module. Tests: TestBoundedImageViewEligibility (an explicitly selected 2D MSAA record) and TestBitScanKeyRange (a scanned 2D MSAA record) in resource_tracking_tests; both fail without the change.

**@⁠NeySlim** on GitHub · 2026-10-08 21:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#discussion_r4224462942) On `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` line 652 (outdated): ```diff @@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna return dimension == Decoder::ImageDimension::Dim2D || dimension == Decoder::ImageDimension::Dim2DArray; }; + // A plain sample reads the selected record with the record's own type, as the T# + // drives the hardware: records of another dimension or numeric class stay candidates. + // Derivatives, offsets and gathers are laid out for one dimension only. + const auto& base_root = program.info.images[root_index]; + uint32_t sample_flags = 0; + for (const auto& memory: program.memory_info) { + if (memory.kind == ResourceKind::Image && memory.resource == root_index) { + sample_flags |= memory.image_sample_flags; + } + } + const bool mixed_dimensions = + base_root.resource_class == ImageResourceClass::Sampled && !base_root.written && + !base_root.atomic && + (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset | + Decoder::ImageSampleFlagGatherHorizontal)) == 0u; ``` Agreed, fixed in 19a361f1. Once a plain sample accepted candidates of another dimension, a multisampled record in a bit scan table or in explicitly selected sources passed the check (only bounded tables drop a dimension mismatch), and `EmitSample` would have emitted `OpSampledImage`/`OpImageSample*` on an MS=1 image. Indirect tables are only sampled, so a multisampled candidate now refuses the table on every table shape, whatever its coordinates. This also covers a table whose records are all multisampled, which was accepted before this PR and produced the same invalid module. Tests: `TestBoundedImageViewEligibility` (an explicitly selected 2D MSAA record) and `TestBitScanKeyRange` (a scanned 2D MSAA record) in `resource_tracking_tests`; both fail without the change.
Author
Owner

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

@@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna
 			return dimension == Decoder::ImageDimension::Dim2D ||
 			       dimension == Decoder::ImageDimension::Dim2DArray;
 		};
+		// A plain sample reads the selected record with the record's own type, as the T#
+		// drives the hardware: records of another dimension or numeric class stay candidates.
+		// Derivatives, offsets and gathers are laid out for one dimension only.
+		const auto& base_root    = program.info.images[root_index];
+		uint32_t    sample_flags = 0;
+		for (const auto& memory: program.memory_info) {
+			if (memory.kind == ResourceKind::Image && memory.resource == root_index) {
+				sample_flags |= memory.image_sample_flags;
+			}
+		}
+		const bool mixed_dimensions =
+		    base_root.resource_class == ImageResourceClass::Sampled && !base_root.written &&
+		    !base_root.atomic &&
+		    (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset |
+		                     Decoder::ImageSampleFlagGatherHorizontal)) == 0u;
+		const bool mixed_classes = mixed_dimensions && !base_root.depth_compare;

Agreed, fixed in bfe34a23 by restricting the table rather than adding per-class samplers. I first checked what the game needs: the only float/uint mix in its light tables was the record past the table count, a 64-bit pointer read as a 2D 8_UINT T#, which fb72234e no longer reads. A 10-minute run from a new game with a trace on candidates of another class found none; a second 10-minute run with this change reports no incompatible candidates. Candidates must already share their conversion format, so requiring the same SamplerClass amounts to requiring the same numeric class: the table now keeps one numeric class, the root's sampler variant fits every candidate, and the per-candidate result type and bitcast in EmitSample are gone. A record of another class gets the explicit incompatible candidates error. Test: TestBoundedImageViewEligibility now refuses an explicitly selected record of another numeric class and fails without the change; IndirectImageMixedCandidates is removed with the emitter path it covered. While checking the same rule I also excluded depth-compare samples from mixed dimensions in cfe30003, since there is no 3D comparison sample; TestBoundedImageViewEligibility covers it and fails without the change.

**@⁠NeySlim** on GitHub · 2026-10-08 21:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#discussion_r4224463164) On `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` line 653 (outdated): ```diff @@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna return dimension == Decoder::ImageDimension::Dim2D || dimension == Decoder::ImageDimension::Dim2DArray; }; + // A plain sample reads the selected record with the record's own type, as the T# + // drives the hardware: records of another dimension or numeric class stay candidates. + // Derivatives, offsets and gathers are laid out for one dimension only. + const auto& base_root = program.info.images[root_index]; + uint32_t sample_flags = 0; + for (const auto& memory: program.memory_info) { + if (memory.kind == ResourceKind::Image && memory.resource == root_index) { + sample_flags |= memory.image_sample_flags; + } + } + const bool mixed_dimensions = + base_root.resource_class == ImageResourceClass::Sampled && !base_root.written && + !base_root.atomic && + (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset | + Decoder::ImageSampleFlagGatherHorizontal)) == 0u; + const bool mixed_classes = mixed_dimensions && !base_root.depth_compare; ``` Agreed, fixed in bfe34a23 by restricting the table rather than adding per-class samplers. I first checked what the game needs: the only float/uint mix in its light tables was the record past the table count, a 64-bit pointer read as a 2D 8_UINT T#, which fb72234e no longer reads. A 10-minute run from a new game with a trace on candidates of another class found none; a second 10-minute run with this change reports no `incompatible candidates`. Candidates must already share their conversion format, so requiring the same `SamplerClass` amounts to requiring the same numeric class: the table now keeps one numeric class, the root's sampler variant fits every candidate, and the per-candidate result type and bitcast in `EmitSample` are gone. A record of another class gets the explicit `incompatible candidates` error. Test: `TestBoundedImageViewEligibility` now refuses an explicitly selected record of another numeric class and fails without the change; `IndirectImageMixedCandidates` is removed with the emitter path it covered. While checking the same rule I also excluded depth-compare samples from mixed dimensions in cfe30003, since there is no 3D comparison sample; `TestBoundedImageViewEligibility` covers it and fails without the change.
Author
Owner

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

@@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna
 			return dimension == Decoder::ImageDimension::Dim2D ||
 			       dimension == Decoder::ImageDimension::Dim2DArray;
 		};
+		// A plain sample reads the selected record with the record's own type, as the T#
+		// drives the hardware: records of another dimension or numeric class stay candidates.
+		// Derivatives, offsets and gathers are laid out for one dimension only.
+		const auto& base_root    = program.info.images[root_index];
+		uint32_t    sample_flags = 0;
+		for (const auto& memory: program.memory_info) {
+			if (memory.kind == ResourceKind::Image && memory.resource == root_index) {
+				sample_flags |= memory.image_sample_flags;
+			}
+		}
+		const bool mixed_dimensions =
+		    base_root.resource_class == ImageResourceClass::Sampled && !base_root.written &&
+		    !base_root.atomic &&
+		    (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset |
+		                     Decoder::ImageSampleFlagGatherHorizontal)) == 0u;

@NeySlim, thanks for the clarification and fix. The unconditional is_msaa(image.dimension) check in BuildResourceSpecialization covers both mixed-dimension tables and tables whose candidates are all multisampled. This is stronger than my proposed coordinate-dependent check.

The two reported regression tests cover explicitly selected and bit-scan candidates.


✏️ Learnings added
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1255
File: src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp:653-658
Timestamp: 2026-10-08T21:50:39.131Z
Learning: In src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp, indirect image tables support sampling only. BuildResourceSpecialization must reject multisampled candidates regardless of coordinate compatibility, including tables whose candidates are all multisampled. Plain sampling through EmitSample would otherwise emit invalid OpSampledImage/OpImageSample* operations on an MS=1 image.

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-08 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#discussion_r4224496434) On `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` line 652 (outdated): ```diff @@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna return dimension == Decoder::ImageDimension::Dim2D || dimension == Decoder::ImageDimension::Dim2DArray; }; + // A plain sample reads the selected record with the record's own type, as the T# + // drives the hardware: records of another dimension or numeric class stay candidates. + // Derivatives, offsets and gathers are laid out for one dimension only. + const auto& base_root = program.info.images[root_index]; + uint32_t sample_flags = 0; + for (const auto& memory: program.memory_info) { + if (memory.kind == ResourceKind::Image && memory.resource == root_index) { + sample_flags |= memory.image_sample_flags; + } + } + const bool mixed_dimensions = + base_root.resource_class == ImageResourceClass::Sampled && !base_root.written && + !base_root.atomic && + (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset | + Decoder::ImageSampleFlagGatherHorizontal)) == 0u; ``` `@NeySlim`, thanks for the clarification and fix. The unconditional `is_msaa(image.dimension)` check in `BuildResourceSpecialization` covers both mixed-dimension tables and tables whose candidates are all multisampled. This is stronger than my proposed coordinate-dependent check. The two reported regression tests cover explicitly selected and bit-scan candidates. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1255 File: src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp:653-658 Timestamp: 2026-10-08T21:50:39.131Z Learning: In src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp, indirect image tables support sampling only. BuildResourceSpecialization must reject multisampled candidates regardless of coordinate compatibility, including tables whose candidates are all multisampled. Plain sampling through EmitSample would otherwise emit invalid OpSampledImage/OpImageSample* operations on an MS=1 image. ``` > 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=Prevent%20invalid%20SPIR-V%3A%20reject%20multisampled%20candidates%20from%20plain-sample%20tables%20across%20all%20table%20shapes%20to%20avoid%20pipeline%20failures.%20Try%20%40coderabbitai%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1255%23discussion_r4223850968)? 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-08 21:51 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp line 653 (outdated):

@@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna
 			return dimension == Decoder::ImageDimension::Dim2D ||
 			       dimension == Decoder::ImageDimension::Dim2DArray;
 		};
+		// A plain sample reads the selected record with the record's own type, as the T#
+		// drives the hardware: records of another dimension or numeric class stay candidates.
+		// Derivatives, offsets and gathers are laid out for one dimension only.
+		const auto& base_root    = program.info.images[root_index];
+		uint32_t    sample_flags = 0;
+		for (const auto& memory: program.memory_info) {
+			if (memory.kind == ResourceKind::Image && memory.resource == root_index) {
+				sample_flags |= memory.image_sample_flags;
+			}
+		}
+		const bool mixed_dimensions =
+		    base_root.resource_class == ImageResourceClass::Sampled && !base_root.written &&
+		    !base_root.atomic &&
+		    (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset |
+		                     Decoder::ImageSampleFlagGatherHorizontal)) == 0u;
+		const bool mixed_classes = mixed_dimensions && !base_root.depth_compare;

@NeySlim Thanks for the explanation and the fix. The supplied BuildResourceSpecialization code now rejects candidates with a different numeric class. With the existing conversion-format check, the root’s sampler variant fits every candidate. This addresses the sampler-reuse concern without per-class samplers.

The code also excludes comparison samples from the mixed-dimension relaxation. Your reported TestBoundedImageViewEligibility cases cover both restrictions. I have not run the tests.


✏️ Learnings added
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1255
File: src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp:0-0
Timestamp: 2026-10-08T21:51:19.136Z
Learning: In src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp, BuildResourceSpecialization requires indirect image candidates to share one numeric class and conversion format. This keeps the root sampler variant compatible with every candidate; mixed numeric classes must produce the explicit "incompatible candidates" error rather than rely on per-candidate result types or bitcasts. Depth-compare samples are excluded from the mixed-dimension relaxation because 3D comparison sampling is unsupported. TestBoundedImageViewEligibility covers both restrictions.

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.


🧠 Learnings used
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1255
File: src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp:653-658
Timestamp: 2026-10-08T21:50:41.794Z
Learning: In src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp, indirect image tables support sampling only. BuildResourceSpecialization must reject multisampled candidates regardless of coordinate compatibility, including tables whose candidates are all multisampled. Plain sampling through EmitSample would otherwise emit invalid OpSampledImage/OpImageSample* operations on an MS=1 image.

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-08 21:51 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#discussion_r4224501404) On `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` line 653 (outdated): ```diff @@ -622,6 +635,22 @@ static bool BuildResourceSpecialization(const ResourcePlan& program, ResourceSna return dimension == Decoder::ImageDimension::Dim2D || dimension == Decoder::ImageDimension::Dim2DArray; }; + // A plain sample reads the selected record with the record's own type, as the T# + // drives the hardware: records of another dimension or numeric class stay candidates. + // Derivatives, offsets and gathers are laid out for one dimension only. + const auto& base_root = program.info.images[root_index]; + uint32_t sample_flags = 0; + for (const auto& memory: program.memory_info) { + if (memory.kind == ResourceKind::Image && memory.resource == root_index) { + sample_flags |= memory.image_sample_flags; + } + } + const bool mixed_dimensions = + base_root.resource_class == ImageResourceClass::Sampled && !base_root.written && + !base_root.atomic && + (sample_flags & (Decoder::ImageSampleFlagDerivative | Decoder::ImageSampleFlagOffset | + Decoder::ImageSampleFlagGatherHorizontal)) == 0u; + const bool mixed_classes = mixed_dimensions && !base_root.depth_compare; ``` `@NeySlim` Thanks for the explanation and the fix. The supplied `BuildResourceSpecialization` code now rejects candidates with a different numeric class. With the existing conversion-format check, the root’s sampler variant fits every candidate. This addresses the sampler-reuse concern without per-class samplers. The code also excludes comparison samples from the mixed-dimension relaxation. Your reported `TestBoundedImageViewEligibility` cases cover both restrictions. I have not run the tests. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1255 File: src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp:0-0 Timestamp: 2026-10-08T21:51:19.136Z Learning: In src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp, BuildResourceSpecialization requires indirect image candidates to share one numeric class and conversion format. This keeps the root sampler variant compatible with every candidate; mixed numeric classes must produce the explicit "incompatible candidates" error rather than rely on per-candidate result types or bitcasts. Depth-compare samples are excluded from the mixed-dimension relaxation because 3D comparison sampling is unsupported. TestBoundedImageViewEligibility covers both restrictions. ``` > 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> --- <details> <summary>🧠 Learnings used</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1255 File: src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp:653-658 Timestamp: 2026-10-08T21:50:41.794Z Learning: In src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp, indirect image tables support sampling only. BuildResourceSpecialization must reject multisampled candidates regardless of coordinate compatibility, including tables whose candidates are all multisampled. Plain sampling through EmitSample would otherwise emit invalid OpSampledImage/OpImageSample* operations on an MS=1 image. ``` </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=Mixed-numeric%20image%20candidates%20can%20inherit%20the%20wrong%20sampler%E2%80%94breaking%20filtering%20and%20border%20colors.%20%40coderabbitai%20caught%20it%3A%20restrict%20candidates%20by%20SamplerClass.%20Try%20CodeRabbit%20for%20sharper%20reviews!%20%F0%9F%94%8D&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1255%23discussion_r4223850985)? 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-09 10:18 UTC · original

Follow-up to an independent review; each commit adds a test that fails without it:

  • c71004d5: a mixed-candidate sample read the candidate's coordinate count from the address, so with a 2D image_sample_l a 3D or array candidate took the LOD as its depth or slice. The emitter now reads only the coordinates the instruction supplies; the others are zero, as a plain sample already got them. (The game samples these tables with a 3D image_sample_lz.)
  • 926234ea: only image_sample selects each record's own view; loads, gathers and queries read through the root's view. Mixed dimensions are now accepted only when every use of the table is a sample (ImageResource::sample_only, merged at tracking time).
  • 7b3ef81e: a multisampled candidate refuses only a table that uses a sampler; image_load of a multisampled table works as before this PR.
  • 98eb445d: the proof that a bit scan loop only clears bits of its mask assumed any revisited node proven. It now assumes its claim only for the scanned phi and merges still being proven (counterexample t = mask | bit; t & (c ? t : mask) in the test).
  • 2954e640: a lane select resolved to its true arm behind any positive edge; after s_cbranch_vccnz EXEC is unchanged and lanes with VCC clear also run the arm. Only uniform and EXEC edges resolve a select now.
  • dd499f59: the scan width is kept as the descriptor's key_limit and applied at materialization, instead of a UMin32 inserted into the shader per handle; an immediate count now bounds the scan too.
**@⁠NeySlim** on GitHub · 2026-10-09 10:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#issuecomment-6078935369) Follow-up to an independent review; each commit adds a test that fails without it: - c71004d5: a mixed-candidate sample read the candidate's coordinate count from the address, so with a 2D `image_sample_l` a 3D or array candidate took the LOD as its depth or slice. The emitter now reads only the coordinates the instruction supplies; the others are zero, as a plain sample already got them. (The game samples these tables with a 3D `image_sample_lz`.) - 926234ea: only `image_sample` selects each record's own view; loads, gathers and queries read through the root's view. Mixed dimensions are now accepted only when every use of the table is a sample (`ImageResource::sample_only`, merged at tracking time). - 7b3ef81e: a multisampled candidate refuses only a table that uses a sampler; `image_load` of a multisampled table works as before this PR. - 98eb445d: the proof that a bit scan loop only clears bits of its mask assumed any revisited node proven. It now assumes its claim only for the scanned phi and merges still being proven (counterexample `t = mask | bit; t & (c ? t : mask)` in the test). - 2954e640: a lane select resolved to its true arm behind any positive edge; after `s_cbranch_vccnz` EXEC is unchanged and lanes with VCC clear also run the arm. Only uniform and EXEC edges resolve a select now. - dd499f59: the scan width is kept as the descriptor's `key_limit` and applied at materialization, instead of a `UMin32` inserted into the shader per handle; an immediate count now bounds the scan too.
Author
Owner

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

Rebased on main after the CFG rework; tests adapted to the new IR structures: the bit scan tests set terminators and branch conditions on the blocks themselves (Block::terminator, Block::condition) instead of Program::block_info, and the compute checks collect bindings with CollectShaderInfo instead of AllocateBindings. No change to the fixes. Each commit still builds, each new test still fails without its fix, and shader_recompiler_compute_tests one case per process gives the same results as main (598 of 608 pass, the other 10 fail on main too on this RADV setup).

**@⁠NeySlim** on GitHub · 2026-10-09 11:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#issuecomment-6079571415) Rebased on main after the CFG rework; tests adapted to the new IR structures: the bit scan tests set terminators and branch conditions on the blocks themselves (`Block::terminator`, `Block::condition`) instead of `Program::block_info`, and the compute checks collect bindings with `CollectShaderInfo` instead of `AllocateBindings`. No change to the fixes. Each commit still builds, each new test still fails without its fix, and `shader_recompiler_compute_tests` one case per process gives the same results as main (598 of 608 pass, the other 10 fail on main too on this RADV setup).
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 11:08 UTC · original · edited 2026-10-09 12:14 UTC
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 1377 (outdated):

@@ -1302,6 +1307,218 @@ class Tracker {
 		       first->NumArgs() == 1u && EquivalentValue(m_program, first->Arg(0), mask);
 	}
 
+	// The mask of a bit scan is the scanned value, or the entry value of a loop phi that only
+	// ever clears its bits. `width` receives the number of bits the mask can set; the mask
+	// itself is returned only when the host can evaluate it.
+	Value ScannedMask(Value value, uint32_t& width) const {
+		width = 32u;
+		value = value.Resolve();
+		// The scalar mask may reach s_ff1 through a lane read of a wave-emulated SGPR.
+		if (const auto* lane = value.TryInstruction();
+		    lane != nullptr && lane->GetOpcode() == ValueOpcode::ReadFirstLane &&
+		    lane->NumArgs() == 2u && !ValidateRuntimeValue(m_program, value))
+			value = lane->Arg(0).Resolve();
+		const auto* phi = value.TryInstruction();
+		if (phi != nullptr && phi->GetOpcode() == ValueOpcode::Phi && phi->NumArgs() == 2u &&
+		    phi->GetType() == Type::U32) {
+			for (uint32_t back = 0; back < 2u; ++back) {
+				std::vector<const Inst*> proving;
+				uint32_t                 budget = 256u;
+				if (!ClearsBitsOf(phi->Arg(back), value, *phi, back, proving, budget)) continue;
+				value = ArmValue(phi->Arg(back ^ 1u), *phi, back ^ 1u);
+				break;
+			}
+		}
+		width = MaskWidth(value);
+		return ValidateRuntimeValue(m_program, value, RuntimeValueType::Integer) ? value : Value {};
+	}
+
+	// Bits a mask can set: a bit field extract or an immediate AND bounds it statically.
+	static uint32_t MaskWidth(Value value) {
+		const auto* inst      = value.Resolve().TryInstruction();
+		uint32_t    immediate = 0;
+		if (inst == nullptr) return 32u;
+		if (inst->GetOpcode() == ValueOpcode::BitFieldUExtract && inst->NumArgs() == 3u &&
+		    ImmediateU32(inst->Arg(2), immediate))
+			return std::min(immediate, 32u);
+		if (inst->GetOpcode() == ValueOpcode::BitwiseAnd32 && inst->NumArgs() == 2u) {
+			for (uint32_t arg = 0; arg < 2u; ++arg) {
+				if (ImmediateU32(inst->Arg(arg), immediate)) return std::bit_width(immediate);
+			}
+			return std::min(MaskWidth(inst->Arg(0)), MaskWidth(inst->Arg(1)));
+		}
+		if (inst->GetOpcode() == ValueOpcode::ReadFirstLane && inst->NumArgs() == 2u)
+			return MaskWidth(inst->Arg(0));
+		return 32u;
+	}
+
+	// Active lanes reaching the incoming block of a phi arm satisfy every positive edge
+	// predicate that holds for all lanes or sets EXEC on their way from the loop header;
+	// selects on those predicates take their true arm.
+	bool HoldsOnArm(Value predicate, const Inst& phi, uint32_t arm) const {
+		const auto* incoming = phi.PhiBlock(arm);
+		if (incoming == phi.Parent()) return false;
+		return GuardedOnEntry(
+		    incoming, [&](const Block* block) { return block == phi.Parent(); },
+		    [&](const EdgePredicate& edge) {
+			    return edge.positive && (edge.lanes == LaneQuantifier::All || edge.exec) &&
+			           Implies(edge.condition, predicate);
+		    });
+	}
+
+	// The value a phi arm carries: sibling phis of the same header resolve to their own arm
+	// and lane selects whose predicate holds on the arm resolve to the selected value.
+	Value ArmValue(Value value, const Inst& phi, uint32_t arm, uint32_t depth = 0) const {
+		value            = value.Resolve();
+		const auto* inst = value.TryInstruction();
+		if (inst == nullptr || depth > 16u) return value;
+		if (inst->GetOpcode() == ValueOpcode::Phi && inst->Parent() == phi.Parent() &&
+		    inst->NumArgs() == phi.NumArgs() && inst->PhiBlock(arm) == phi.PhiBlock(arm))
+			return ArmValue(inst->Arg(arm), phi, arm, depth + 1u);

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- target block ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1280,1425p'
printf '%s\n' '--- ArmValue references ---'
rg -n -F -- 'ArmValue(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp src tests || true
printf '%s\n' '--- sibling phi and proof references ---'
rg -n -F -- 'TestBitScanMaskProof' . || true
rg -n -F -- 'ClearsBitsOf' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
printf '%s\n' '--- relevant diff ---'
git diff --unified=35 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 9417f07924b3c58c617c3fcf2063fb62091a2502 -- src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Repository: KytyPS5/KytyPS5

Length of output: 40783


🏁 Script executed:

nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1320,1405p'
rg -n -F -- 'TestBitScanMaskProof' .
rg -n -F -- 'ArmValue(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Repository: KytyPS5/KytyPS5

Length of output: 5502


🏁 Script executed:

set -eu
nl -ba tests/ResourceTrackingTests.cpp | sed -n '1020,1195p'
printf '%s\n' '--- tests around later registrations ---'
nl -ba tests/ResourceTrackingTests.cpp | sed -n '3965,4010p'
printf '%s\n' '--- test diff for this feature ---'
git diff --unified=25 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 9417f07924b3c58c617c3fcf2063fb62091a2502 -- tests/ResourceTrackingTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 42371


Remove sibling-phi substitution on loop back arms.

ScannedMask passes the update arm to ClearsBitsOf, and ClearsBitsOf calls ArmValue before checking the update. On a loop back arm, S is the current-iteration value in the loop body. Replacing it with S.Arg(back) reads the value for the next iteration. This can make ClearsBitsOf accept a mask update that can gain bits.

The same substitution can make a sibling-phi predicate select the wrong arm.

🐛 Suggested fix
--- "a/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp"
+++ "b/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp"
@@ -1372,9 +1372,8 @@
 		value            = value.Resolve();
 		const auto* inst = value.TryInstruction();
 		if (inst == nullptr || depth > 16u) return value;
-		if (inst->GetOpcode() == ValueOpcode::Phi && inst->Parent() == phi.Parent() &&
-		    inst->NumArgs() == phi.NumArgs() && inst->PhiBlock(arm) == phi.PhiBlock(arm))
-			return ArmValue(inst->Arg(arm), phi, arm, depth + 1u);
+		// Inside the loop body, a sibling header phi holds its current-iteration value,
+		// not the value of its back arm; only the entry arm may be substituted.
 		if (inst->GetOpcode() == ValueOpcode::SelectU32 && inst->NumArgs() == 3u) {
 			const auto predicate = ArmValue(inst->Arg(0), phi, arm, depth + 1u);
 			if (predicate.IsImmediate() && predicate.GetType() == Type::U1)

Add a TestBitScanMaskProof variant with a mask that swaps through a sibling phi. selector_mask must remain empty.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

		// Inside the loop body, a sibling header phi holds its current-iteration value,
		// not the value of its back arm; only the entry arm may be substituted.

✅ Addressed in commit f42dfe4

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 11:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#discussion_r4229449779) · edited 2026-10-09 12:14 UTC On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 1377 (outdated): ```diff @@ -1302,6 +1307,218 @@ class Tracker { first->NumArgs() == 1u && EquivalentValue(m_program, first->Arg(0), mask); } + // The mask of a bit scan is the scanned value, or the entry value of a loop phi that only + // ever clears its bits. `width` receives the number of bits the mask can set; the mask + // itself is returned only when the host can evaluate it. + Value ScannedMask(Value value, uint32_t& width) const { + width = 32u; + value = value.Resolve(); + // The scalar mask may reach s_ff1 through a lane read of a wave-emulated SGPR. + if (const auto* lane = value.TryInstruction(); + lane != nullptr && lane->GetOpcode() == ValueOpcode::ReadFirstLane && + lane->NumArgs() == 2u && !ValidateRuntimeValue(m_program, value)) + value = lane->Arg(0).Resolve(); + const auto* phi = value.TryInstruction(); + if (phi != nullptr && phi->GetOpcode() == ValueOpcode::Phi && phi->NumArgs() == 2u && + phi->GetType() == Type::U32) { + for (uint32_t back = 0; back < 2u; ++back) { + std::vector<const Inst*> proving; + uint32_t budget = 256u; + if (!ClearsBitsOf(phi->Arg(back), value, *phi, back, proving, budget)) continue; + value = ArmValue(phi->Arg(back ^ 1u), *phi, back ^ 1u); + break; + } + } + width = MaskWidth(value); + return ValidateRuntimeValue(m_program, value, RuntimeValueType::Integer) ? value : Value {}; + } + + // Bits a mask can set: a bit field extract or an immediate AND bounds it statically. + static uint32_t MaskWidth(Value value) { + const auto* inst = value.Resolve().TryInstruction(); + uint32_t immediate = 0; + if (inst == nullptr) return 32u; + if (inst->GetOpcode() == ValueOpcode::BitFieldUExtract && inst->NumArgs() == 3u && + ImmediateU32(inst->Arg(2), immediate)) + return std::min(immediate, 32u); + if (inst->GetOpcode() == ValueOpcode::BitwiseAnd32 && inst->NumArgs() == 2u) { + for (uint32_t arg = 0; arg < 2u; ++arg) { + if (ImmediateU32(inst->Arg(arg), immediate)) return std::bit_width(immediate); + } + return std::min(MaskWidth(inst->Arg(0)), MaskWidth(inst->Arg(1))); + } + if (inst->GetOpcode() == ValueOpcode::ReadFirstLane && inst->NumArgs() == 2u) + return MaskWidth(inst->Arg(0)); + return 32u; + } + + // Active lanes reaching the incoming block of a phi arm satisfy every positive edge + // predicate that holds for all lanes or sets EXEC on their way from the loop header; + // selects on those predicates take their true arm. + bool HoldsOnArm(Value predicate, const Inst& phi, uint32_t arm) const { + const auto* incoming = phi.PhiBlock(arm); + if (incoming == phi.Parent()) return false; + return GuardedOnEntry( + incoming, [&](const Block* block) { return block == phi.Parent(); }, + [&](const EdgePredicate& edge) { + return edge.positive && (edge.lanes == LaneQuantifier::All || edge.exec) && + Implies(edge.condition, predicate); + }); + } + + // The value a phi arm carries: sibling phis of the same header resolve to their own arm + // and lane selects whose predicate holds on the arm resolve to the selected value. + Value ArmValue(Value value, const Inst& phi, uint32_t arm, uint32_t depth = 0) const { + value = value.Resolve(); + const auto* inst = value.TryInstruction(); + if (inst == nullptr || depth > 16u) return value; + if (inst->GetOpcode() == ValueOpcode::Phi && inst->Parent() == phi.Parent() && + inst->NumArgs() == phi.NumArgs() && inst->PhiBlock(arm) == phi.PhiBlock(arm)) + return ArmValue(inst->Arg(arm), phi, arm, depth + 1u); ``` **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -eu printf '%s\n' '--- target block ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1280,1425p' printf '%s\n' '--- ArmValue references ---' rg -n -F -- 'ArmValue(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp src tests || true printf '%s\n' '--- sibling phi and proof references ---' rg -n -F -- 'TestBitScanMaskProof' . || true rg -n -F -- 'ClearsBitsOf' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp printf '%s\n' '--- relevant diff ---' git diff --unified=35 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 9417f07924b3c58c617c3fcf2063fb62091a2502 -- src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 40783 --- 🏁 Script executed: ```bash nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '1320,1405p' rg -n -F -- 'TestBitScanMaskProof' . rg -n -F -- 'ArmValue(' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 5502 --- 🏁 Script executed: ```bash set -eu nl -ba tests/ResourceTrackingTests.cpp | sed -n '1020,1195p' printf '%s\n' '--- tests around later registrations ---' nl -ba tests/ResourceTrackingTests.cpp | sed -n '3965,4010p' printf '%s\n' '--- test diff for this feature ---' git diff --unified=25 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 9417f07924b3c58c617c3fcf2063fb62091a2502 -- tests/ResourceTrackingTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 42371 --- </details> **Remove sibling-phi substitution on loop back arms.** `ScannedMask` passes the update arm to `ClearsBitsOf`, and `ClearsBitsOf` calls `ArmValue` before checking the update. On a loop back arm, `S` is the current-iteration value in the loop body. Replacing it with `S.Arg(back)` reads the value for the next iteration. This can make `ClearsBitsOf` accept a mask update that can gain bits. The same substitution can make a sibling-phi predicate select the wrong arm. <details> <summary>🐛 Suggested fix</summary> ```diff --- "a/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp" +++ "b/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp" @@ -1372,9 +1372,8 @@ value = value.Resolve(); const auto* inst = value.TryInstruction(); if (inst == nullptr || depth > 16u) return value; - if (inst->GetOpcode() == ValueOpcode::Phi && inst->Parent() == phi.Parent() && - inst->NumArgs() == phi.NumArgs() && inst->PhiBlock(arm) == phi.PhiBlock(arm)) - return ArmValue(inst->Arg(arm), phi, arm, depth + 1u); + // Inside the loop body, a sibling header phi holds its current-iteration value, + // not the value of its back arm; only the entry arm may be substituted. if (inst->GetOpcode() == ValueOpcode::SelectU32 && inst->NumArgs() == 3u) { const auto predicate = ArmValue(inst->Arg(0), phi, arm, depth + 1u); if (predicate.IsImmediate() && predicate.GetType() == Type::U1) ``` </details> Add a `TestBitScanMaskProof` variant with a mask that swaps through a sibling phi. `selector_mask` must remain empty. <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion // Inside the loop body, a sibling header phi holds its current-iteration value, // not the value of its back arm; only the entry arm may be substituted. ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6162c2741e96e7a6e779edb2 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit f42dfe4
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 11:08 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: e7cf2885-4bad-4343-839f-39866db5f5f1
📥 Commits

Reviewing files that changed from the base of the PR and between cfe3000305cfa6f630b3fc96cd0330660ae5e303 and 9417f07924b3c58c617c3fcf2063fb62091a2502.

📒 Files selected for processing (6)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ShaderRecompilerComputeTests.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-09 11:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#pullrequestreview-5469232848) · **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**: `e7cf2885-4bad-4343-839f-39866db5f5f1` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between cfe3000305cfa6f630b3fc96cd0330660ae5e303 and 9417f07924b3c58c617c3fcf2063fb62091a2502. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ShaderRecompilerComputeTests.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=b90244e5-da25-4fa9-89a4-c3403e58e50e attempt=0dd9294e-105a-4187-a5b6-68f7f974b195 batch=1/1 -->
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 12:14 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 1377 (outdated):

@@ -1302,6 +1307,218 @@ class Tracker {
 		       first->NumArgs() == 1u && EquivalentValue(m_program, first->Arg(0), mask);
 	}
 
+	// The mask of a bit scan is the scanned value, or the entry value of a loop phi that only
+	// ever clears its bits. `width` receives the number of bits the mask can set; the mask
+	// itself is returned only when the host can evaluate it.
+	Value ScannedMask(Value value, uint32_t& width) const {
+		width = 32u;
+		value = value.Resolve();
+		// The scalar mask may reach s_ff1 through a lane read of a wave-emulated SGPR.
+		if (const auto* lane = value.TryInstruction();
+		    lane != nullptr && lane->GetOpcode() == ValueOpcode::ReadFirstLane &&
+		    lane->NumArgs() == 2u && !ValidateRuntimeValue(m_program, value))
+			value = lane->Arg(0).Resolve();
+		const auto* phi = value.TryInstruction();
+		if (phi != nullptr && phi->GetOpcode() == ValueOpcode::Phi && phi->NumArgs() == 2u &&
+		    phi->GetType() == Type::U32) {
+			for (uint32_t back = 0; back < 2u; ++back) {
+				std::vector<const Inst*> proving;
+				uint32_t                 budget = 256u;
+				if (!ClearsBitsOf(phi->Arg(back), value, *phi, back, proving, budget)) continue;
+				value = ArmValue(phi->Arg(back ^ 1u), *phi, back ^ 1u);
+				break;
+			}
+		}
+		width = MaskWidth(value);
+		return ValidateRuntimeValue(m_program, value, RuntimeValueType::Integer) ? value : Value {};
+	}
+
+	// Bits a mask can set: a bit field extract or an immediate AND bounds it statically.
+	static uint32_t MaskWidth(Value value) {
+		const auto* inst      = value.Resolve().TryInstruction();
+		uint32_t    immediate = 0;
+		if (inst == nullptr) return 32u;
+		if (inst->GetOpcode() == ValueOpcode::BitFieldUExtract && inst->NumArgs() == 3u &&
+		    ImmediateU32(inst->Arg(2), immediate))
+			return std::min(immediate, 32u);
+		if (inst->GetOpcode() == ValueOpcode::BitwiseAnd32 && inst->NumArgs() == 2u) {
+			for (uint32_t arg = 0; arg < 2u; ++arg) {
+				if (ImmediateU32(inst->Arg(arg), immediate)) return std::bit_width(immediate);
+			}
+			return std::min(MaskWidth(inst->Arg(0)), MaskWidth(inst->Arg(1)));
+		}
+		if (inst->GetOpcode() == ValueOpcode::ReadFirstLane && inst->NumArgs() == 2u)
+			return MaskWidth(inst->Arg(0));
+		return 32u;
+	}
+
+	// Active lanes reaching the incoming block of a phi arm satisfy every positive edge
+	// predicate that holds for all lanes or sets EXEC on their way from the loop header;
+	// selects on those predicates take their true arm.
+	bool HoldsOnArm(Value predicate, const Inst& phi, uint32_t arm) const {
+		const auto* incoming = phi.PhiBlock(arm);
+		if (incoming == phi.Parent()) return false;
+		return GuardedOnEntry(
+		    incoming, [&](const Block* block) { return block == phi.Parent(); },
+		    [&](const EdgePredicate& edge) {
+			    return edge.positive && (edge.lanes == LaneQuantifier::All || edge.exec) &&
+			           Implies(edge.condition, predicate);
+		    });
+	}
+
+	// The value a phi arm carries: sibling phis of the same header resolve to their own arm
+	// and lane selects whose predicate holds on the arm resolve to the selected value.
+	Value ArmValue(Value value, const Inst& phi, uint32_t arm, uint32_t depth = 0) const {
+		value            = value.Resolve();
+		const auto* inst = value.TryInstruction();
+		if (inst == nullptr || depth > 16u) return value;
+		if (inst->GetOpcode() == ValueOpcode::Phi && inst->Parent() == phi.Parent() &&
+		    inst->NumArgs() == phi.NumArgs() && inst->PhiBlock(arm) == phi.PhiBlock(arm))
+			return ArmValue(inst->Arg(arm), phi, arm, depth + 1u);

Confirmed and fixed in f42dfe42. A mask whose back arm is a sibling header phi (the sibling starts from another word and takes the cleared mask on the back edge) was accepted and evaluated from its entry value. ArmValue no longer substitutes sibling phis at all: on the entry arm the case cannot occur, since values from before the loop cannot reference a header phi, so there was nothing to keep. TestBitScanMaskProof has a SwapsThroughSibling variant that fails without the fix.

The game does not rely on it: I translated all 560 compute and pixel shaders dumped from the game (wave32 and wave64) with both versions. No bit scan proof ever reached a sibling phi, and every proof (including the light-table shaders) gives the same result.

**@⁠NeySlim** on GitHub · 2026-10-09 12:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#discussion_r4229965501) On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 1377 (outdated): ```diff @@ -1302,6 +1307,218 @@ class Tracker { first->NumArgs() == 1u && EquivalentValue(m_program, first->Arg(0), mask); } + // The mask of a bit scan is the scanned value, or the entry value of a loop phi that only + // ever clears its bits. `width` receives the number of bits the mask can set; the mask + // itself is returned only when the host can evaluate it. + Value ScannedMask(Value value, uint32_t& width) const { + width = 32u; + value = value.Resolve(); + // The scalar mask may reach s_ff1 through a lane read of a wave-emulated SGPR. + if (const auto* lane = value.TryInstruction(); + lane != nullptr && lane->GetOpcode() == ValueOpcode::ReadFirstLane && + lane->NumArgs() == 2u && !ValidateRuntimeValue(m_program, value)) + value = lane->Arg(0).Resolve(); + const auto* phi = value.TryInstruction(); + if (phi != nullptr && phi->GetOpcode() == ValueOpcode::Phi && phi->NumArgs() == 2u && + phi->GetType() == Type::U32) { + for (uint32_t back = 0; back < 2u; ++back) { + std::vector<const Inst*> proving; + uint32_t budget = 256u; + if (!ClearsBitsOf(phi->Arg(back), value, *phi, back, proving, budget)) continue; + value = ArmValue(phi->Arg(back ^ 1u), *phi, back ^ 1u); + break; + } + } + width = MaskWidth(value); + return ValidateRuntimeValue(m_program, value, RuntimeValueType::Integer) ? value : Value {}; + } + + // Bits a mask can set: a bit field extract or an immediate AND bounds it statically. + static uint32_t MaskWidth(Value value) { + const auto* inst = value.Resolve().TryInstruction(); + uint32_t immediate = 0; + if (inst == nullptr) return 32u; + if (inst->GetOpcode() == ValueOpcode::BitFieldUExtract && inst->NumArgs() == 3u && + ImmediateU32(inst->Arg(2), immediate)) + return std::min(immediate, 32u); + if (inst->GetOpcode() == ValueOpcode::BitwiseAnd32 && inst->NumArgs() == 2u) { + for (uint32_t arg = 0; arg < 2u; ++arg) { + if (ImmediateU32(inst->Arg(arg), immediate)) return std::bit_width(immediate); + } + return std::min(MaskWidth(inst->Arg(0)), MaskWidth(inst->Arg(1))); + } + if (inst->GetOpcode() == ValueOpcode::ReadFirstLane && inst->NumArgs() == 2u) + return MaskWidth(inst->Arg(0)); + return 32u; + } + + // Active lanes reaching the incoming block of a phi arm satisfy every positive edge + // predicate that holds for all lanes or sets EXEC on their way from the loop header; + // selects on those predicates take their true arm. + bool HoldsOnArm(Value predicate, const Inst& phi, uint32_t arm) const { + const auto* incoming = phi.PhiBlock(arm); + if (incoming == phi.Parent()) return false; + return GuardedOnEntry( + incoming, [&](const Block* block) { return block == phi.Parent(); }, + [&](const EdgePredicate& edge) { + return edge.positive && (edge.lanes == LaneQuantifier::All || edge.exec) && + Implies(edge.condition, predicate); + }); + } + + // The value a phi arm carries: sibling phis of the same header resolve to their own arm + // and lane selects whose predicate holds on the arm resolve to the selected value. + Value ArmValue(Value value, const Inst& phi, uint32_t arm, uint32_t depth = 0) const { + value = value.Resolve(); + const auto* inst = value.TryInstruction(); + if (inst == nullptr || depth > 16u) return value; + if (inst->GetOpcode() == ValueOpcode::Phi && inst->Parent() == phi.Parent() && + inst->NumArgs() == phi.NumArgs() && inst->PhiBlock(arm) == phi.PhiBlock(arm)) + return ArmValue(inst->Arg(arm), phi, arm, depth + 1u); ``` Confirmed and fixed in f42dfe42. A mask whose back arm is a sibling header phi (the sibling starts from another word and takes the cleared mask on the back edge) was accepted and evaluated from its entry value. `ArmValue` no longer substitutes sibling phis at all: on the entry arm the case cannot occur, since values from before the loop cannot reference a header phi, so there was nothing to keep. `TestBitScanMaskProof` has a `SwapsThroughSibling` variant that fails without the fix. The game does not rely on it: I translated all 560 compute and pixel shaders dumped from the game (wave32 and wave64) with both versions. No bit scan proof ever reached a sibling phi, and every proof (including the light-table shaders) gives the same result.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 12:14 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 1377 (outdated):

@@ -1302,6 +1307,218 @@ class Tracker {
 		       first->NumArgs() == 1u && EquivalentValue(m_program, first->Arg(0), mask);
 	}
 
+	// The mask of a bit scan is the scanned value, or the entry value of a loop phi that only
+	// ever clears its bits. `width` receives the number of bits the mask can set; the mask
+	// itself is returned only when the host can evaluate it.
+	Value ScannedMask(Value value, uint32_t& width) const {
+		width = 32u;
+		value = value.Resolve();
+		// The scalar mask may reach s_ff1 through a lane read of a wave-emulated SGPR.
+		if (const auto* lane = value.TryInstruction();
+		    lane != nullptr && lane->GetOpcode() == ValueOpcode::ReadFirstLane &&
+		    lane->NumArgs() == 2u && !ValidateRuntimeValue(m_program, value))
+			value = lane->Arg(0).Resolve();
+		const auto* phi = value.TryInstruction();
+		if (phi != nullptr && phi->GetOpcode() == ValueOpcode::Phi && phi->NumArgs() == 2u &&
+		    phi->GetType() == Type::U32) {
+			for (uint32_t back = 0; back < 2u; ++back) {
+				std::vector<const Inst*> proving;
+				uint32_t                 budget = 256u;
+				if (!ClearsBitsOf(phi->Arg(back), value, *phi, back, proving, budget)) continue;
+				value = ArmValue(phi->Arg(back ^ 1u), *phi, back ^ 1u);
+				break;
+			}
+		}
+		width = MaskWidth(value);
+		return ValidateRuntimeValue(m_program, value, RuntimeValueType::Integer) ? value : Value {};
+	}
+
+	// Bits a mask can set: a bit field extract or an immediate AND bounds it statically.
+	static uint32_t MaskWidth(Value value) {
+		const auto* inst      = value.Resolve().TryInstruction();
+		uint32_t    immediate = 0;
+		if (inst == nullptr) return 32u;
+		if (inst->GetOpcode() == ValueOpcode::BitFieldUExtract && inst->NumArgs() == 3u &&
+		    ImmediateU32(inst->Arg(2), immediate))
+			return std::min(immediate, 32u);
+		if (inst->GetOpcode() == ValueOpcode::BitwiseAnd32 && inst->NumArgs() == 2u) {
+			for (uint32_t arg = 0; arg < 2u; ++arg) {
+				if (ImmediateU32(inst->Arg(arg), immediate)) return std::bit_width(immediate);
+			}
+			return std::min(MaskWidth(inst->Arg(0)), MaskWidth(inst->Arg(1)));
+		}
+		if (inst->GetOpcode() == ValueOpcode::ReadFirstLane && inst->NumArgs() == 2u)
+			return MaskWidth(inst->Arg(0));
+		return 32u;
+	}
+
+	// Active lanes reaching the incoming block of a phi arm satisfy every positive edge
+	// predicate that holds for all lanes or sets EXEC on their way from the loop header;
+	// selects on those predicates take their true arm.
+	bool HoldsOnArm(Value predicate, const Inst& phi, uint32_t arm) const {
+		const auto* incoming = phi.PhiBlock(arm);
+		if (incoming == phi.Parent()) return false;
+		return GuardedOnEntry(
+		    incoming, [&](const Block* block) { return block == phi.Parent(); },
+		    [&](const EdgePredicate& edge) {
+			    return edge.positive && (edge.lanes == LaneQuantifier::All || edge.exec) &&
+			           Implies(edge.condition, predicate);
+		    });
+	}
+
+	// The value a phi arm carries: sibling phis of the same header resolve to their own arm
+	// and lane selects whose predicate holds on the arm resolve to the selected value.
+	Value ArmValue(Value value, const Inst& phi, uint32_t arm, uint32_t depth = 0) const {
+		value            = value.Resolve();
+		const auto* inst = value.TryInstruction();
+		if (inst == nullptr || depth > 16u) return value;
+		if (inst->GetOpcode() == ValueOpcode::Phi && inst->Parent() == phi.Parent() &&
+		    inst->NumArgs() == phi.NumArgs() && inst->PhiBlock(arm) == phi.PhiBlock(arm))
+			return ArmValue(inst->Arg(arm), phi, arm, depth + 1u);

@NeySlim, thanks for the fix and clarification. The supplied ArmValue implementation no longer substitutes sibling header phis. Removing the substitution entirely is correct: pre-loop values cannot reference a header phi.

The reported SwapsThroughSibling regression test covers the invalid proof. Your comparison of all 560 dumped shaders also indicates that this fix does not change the game’s bit-scan proof results.


✏️ Learnings added
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1255
File: src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp:0-0
Timestamp: 2026-10-09T12:14:42.777Z
Learning: In the C++ shader resource tracker at src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp, Tracker::ArmValue must not substitute sibling header phis when proving bit-scan mask updates. A sibling header phi holds the current-iteration value in the loop body, while its back-arm operand describes the next iteration. No entry-arm substitution is needed because pre-loop values cannot reference a header phi.

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-09 12:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#discussion_r4229969085) On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 1377 (outdated): ```diff @@ -1302,6 +1307,218 @@ class Tracker { first->NumArgs() == 1u && EquivalentValue(m_program, first->Arg(0), mask); } + // The mask of a bit scan is the scanned value, or the entry value of a loop phi that only + // ever clears its bits. `width` receives the number of bits the mask can set; the mask + // itself is returned only when the host can evaluate it. + Value ScannedMask(Value value, uint32_t& width) const { + width = 32u; + value = value.Resolve(); + // The scalar mask may reach s_ff1 through a lane read of a wave-emulated SGPR. + if (const auto* lane = value.TryInstruction(); + lane != nullptr && lane->GetOpcode() == ValueOpcode::ReadFirstLane && + lane->NumArgs() == 2u && !ValidateRuntimeValue(m_program, value)) + value = lane->Arg(0).Resolve(); + const auto* phi = value.TryInstruction(); + if (phi != nullptr && phi->GetOpcode() == ValueOpcode::Phi && phi->NumArgs() == 2u && + phi->GetType() == Type::U32) { + for (uint32_t back = 0; back < 2u; ++back) { + std::vector<const Inst*> proving; + uint32_t budget = 256u; + if (!ClearsBitsOf(phi->Arg(back), value, *phi, back, proving, budget)) continue; + value = ArmValue(phi->Arg(back ^ 1u), *phi, back ^ 1u); + break; + } + } + width = MaskWidth(value); + return ValidateRuntimeValue(m_program, value, RuntimeValueType::Integer) ? value : Value {}; + } + + // Bits a mask can set: a bit field extract or an immediate AND bounds it statically. + static uint32_t MaskWidth(Value value) { + const auto* inst = value.Resolve().TryInstruction(); + uint32_t immediate = 0; + if (inst == nullptr) return 32u; + if (inst->GetOpcode() == ValueOpcode::BitFieldUExtract && inst->NumArgs() == 3u && + ImmediateU32(inst->Arg(2), immediate)) + return std::min(immediate, 32u); + if (inst->GetOpcode() == ValueOpcode::BitwiseAnd32 && inst->NumArgs() == 2u) { + for (uint32_t arg = 0; arg < 2u; ++arg) { + if (ImmediateU32(inst->Arg(arg), immediate)) return std::bit_width(immediate); + } + return std::min(MaskWidth(inst->Arg(0)), MaskWidth(inst->Arg(1))); + } + if (inst->GetOpcode() == ValueOpcode::ReadFirstLane && inst->NumArgs() == 2u) + return MaskWidth(inst->Arg(0)); + return 32u; + } + + // Active lanes reaching the incoming block of a phi arm satisfy every positive edge + // predicate that holds for all lanes or sets EXEC on their way from the loop header; + // selects on those predicates take their true arm. + bool HoldsOnArm(Value predicate, const Inst& phi, uint32_t arm) const { + const auto* incoming = phi.PhiBlock(arm); + if (incoming == phi.Parent()) return false; + return GuardedOnEntry( + incoming, [&](const Block* block) { return block == phi.Parent(); }, + [&](const EdgePredicate& edge) { + return edge.positive && (edge.lanes == LaneQuantifier::All || edge.exec) && + Implies(edge.condition, predicate); + }); + } + + // The value a phi arm carries: sibling phis of the same header resolve to their own arm + // and lane selects whose predicate holds on the arm resolve to the selected value. + Value ArmValue(Value value, const Inst& phi, uint32_t arm, uint32_t depth = 0) const { + value = value.Resolve(); + const auto* inst = value.TryInstruction(); + if (inst == nullptr || depth > 16u) return value; + if (inst->GetOpcode() == ValueOpcode::Phi && inst->Parent() == phi.Parent() && + inst->NumArgs() == phi.NumArgs() && inst->PhiBlock(arm) == phi.PhiBlock(arm)) + return ArmValue(inst->Arg(arm), phi, arm, depth + 1u); ``` `@NeySlim`, thanks for the fix and clarification. The supplied `ArmValue` implementation no longer substitutes sibling header phis. Removing the substitution entirely is correct: pre-loop values cannot reference a header phi. The reported `SwapsThroughSibling` regression test covers the invalid proof. Your comparison of all 560 dumped shaders also indicates that this fix does not change the game’s bit-scan proof results. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1255 File: src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp:0-0 Timestamp: 2026-10-09T12:14:42.777Z Learning: In the C++ shader resource tracker at src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp, Tracker::ArmValue must not substitute sibling header phis when proving bit-scan mask updates. A sibling header phi holds the current-iteration value in the loop body, while its back-arm operand describes the next iteration. No entry-arm substitution is needed because pre-loop values cannot reference a header phi. ``` > 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=%40coderabbitai%20caught%20a%20subtle%20loop-phi%20bug%3A%20sibling%20substitution%20could%20accept%20a%20mask%20that%20gains%20bits.%20Removing%20it%20and%20adding%20a%20regression%20test%20keeps%20%60selector_mask%60%20safe.%20Try%20%40coderabbitai%20for%20sharp%20code%20reviews!%20%F0%9F%90%9B%F0%9F%94%8D&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1255%23discussion_r4229449779)? 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-09 18:52 UTC · original

Rebased on main after 71c72617 (indirect texture dispatch shared with image loads). The sample changes now sit on EmitImageAccess. Since loads now fetch each candidate through its own view, the rules changed in one new commit (06e6dc5d):

  • The coordinate rule moved into CoordF32 and CoordU32: every candidate reads only the coordinates the instruction's dimension supplies, the others are zero. It now covers loads too: a 3D candidate of a 2D image_load_mip no longer takes the LOD as its depth, and on main a 2D array candidate of such a load read the LOD as its layer. Any other caller, such as the gathers and queries of #1320, gets the same rule.
  • A multisampled load takes its fragment index at the instruction's position, not at the candidate's (they differ when the record's dimension differs from the instruction's).
  • Mixed dimensions are accepted for tables read by plain image_sample and now also by image_load. A load candidate of another dimension must not be a cube (no fetch through a cube view) and must be multisampled exactly when the instruction is. Gathers and queries still require one dimension; with #1320 they dispatch per candidate, so they could be allowed later if a game needs it.
  • Multisampled candidates are still refused only for sampled tables.

Tests: TestIndirectImageTableOperations now accepts mixed loads and refuses a cube load candidate or a multisampled mismatch; new host test IndirectImageLoadCoordinates (2D load with a 3D candidate: depth 0, LOD kept; 2D MSAA array load with a 2D MSAA candidate: fragment index from the instruction). Each rule of the PR fails its test when removed (rechecked after the rebase). CPU suites pass; GPU suite one case per process: 603 of 613 pass, main 602 of 612, same 10 failures. Body updated.

**@⁠NeySlim** on GitHub · 2026-10-09 18:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#issuecomment-6087242578) Rebased on main after 71c72617 (indirect texture dispatch shared with image loads). The sample changes now sit on `EmitImageAccess`. Since loads now fetch each candidate through its own view, the rules changed in one new commit (06e6dc5d): - The coordinate rule moved into `CoordF32` and `CoordU32`: every candidate reads only the coordinates the instruction's dimension supplies, the others are zero. It now covers loads too: a 3D candidate of a 2D `image_load_mip` no longer takes the LOD as its depth, and on main a 2D array candidate of such a load read the LOD as its layer. Any other caller, such as the gathers and queries of #1320, gets the same rule. - A multisampled load takes its fragment index at the instruction's position, not at the candidate's (they differ when the record's dimension differs from the instruction's). - Mixed dimensions are accepted for tables read by plain `image_sample` and now also by `image_load`. A load candidate of another dimension must not be a cube (no fetch through a cube view) and must be multisampled exactly when the instruction is. Gathers and queries still require one dimension; with #1320 they dispatch per candidate, so they could be allowed later if a game needs it. - Multisampled candidates are still refused only for sampled tables. Tests: `TestIndirectImageTableOperations` now accepts mixed loads and refuses a cube load candidate or a multisampled mismatch; new host test `IndirectImageLoadCoordinates` (2D load with a 3D candidate: depth 0, LOD kept; 2D MSAA array load with a 2D MSAA candidate: fragment index from the instruction). Each rule of the PR fails its test when removed (rechecked after the rebase). CPU suites pass; GPU suite one case per process: 603 of 613 pass, main 602 of 612, same 10 failures. Body updated.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 21:54 UTC · original

Rebased on current main and pushed 2ec8eeb5. The one-numeric-class rule from 874ed0fe was wrong for this game: a scene samples a sample-only table at pc 0x2c1c that mixes a Uint 2D T# with Float cube and 2D array T#s, and the shader then stopped on incompatible candidates. The per-class sampler variants are needed after all. Sample-only tables may mix classes again: each candidate is sampled with its own image type, its result bitcast to the instruction's type, and the S# variant of its own class (the one a direct sample of that record gets), so the root's variant is no longer applied to other classes. Tables also read by image_load keep one class. New tests: TestMixedCandidateSamplers and the GPU part of IndirectImageMixedCandidates (each lane reads its record's texel bits and its own variant's border); both fail when the rule is removed.

**@⁠NeySlim** on GitHub · 2026-10-09 21:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#issuecomment-6089900486) Rebased on current main and pushed 2ec8eeb5. The one-numeric-class rule from 874ed0fe was wrong for this game: a scene samples a sample-only table at pc `0x2c1c` that mixes a Uint 2D T# with Float cube and 2D array T#s, and the shader then stopped on `incompatible candidates`. The per-class sampler variants are needed after all. Sample-only tables may mix classes again: each candidate is sampled with its own image type, its result bitcast to the instruction's type, and the S# variant of its own class (the one a direct sample of that record gets), so the root's variant is no longer applied to other classes. Tables also read by `image_load` keep one class. New tests: `TestMixedCandidateSamplers` and the GPU part of `IndirectImageMixedCandidates` (each lane reads its record's texel bits and its own variant's border); both fail when the rule is removed.
Author
Owner

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

Rebased on main after 4c87dbeb and 984cfceb. The conflicts were in the sample path: I kept main's per-candidate texel offsets and the new EXEC operand, and re-applied the per-class sampler variant and the per-candidate sample type on top. Nothing was dropped: this PR never changed gathers, and gathers and queries still require one dimension and one numeric class. The tests now pass the EXEC operand of ImageSampleRaw / ImageGatherRaw.

resource_tracking, resource_materialization, scalar_provenance and shader_cfg pass; removing the bit scan bounds, the mask proof rules, the coordinate rule, the multisample rules or the per-class sampler variant still makes the matching test fail. GPU suite one case per process: 614 of 624, the same 10 failures as main (613 of 623).

**@⁠NeySlim** on GitHub · 2026-10-11 18:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#issuecomment-6112161607) Rebased on main after 4c87dbeb and 984cfceb. The conflicts were in the sample path: I kept main's per-candidate texel offsets and the new EXEC operand, and re-applied the per-class sampler variant and the per-candidate sample type on top. Nothing was dropped: this PR never changed gathers, and gathers and queries still require one dimension and one numeric class. The tests now pass the EXEC operand of `ImageSampleRaw` / `ImageGatherRaw`. `resource_tracking`, `resource_materialization`, `scalar_provenance` and `shader_cfg` pass; removing the bit scan bounds, the mask proof rules, the coordinate rule, the multisample rules or the per-class sampler variant still makes the matching test fail. GPU suite one case per process: 614 of 624, the same 10 failures as main (613 of 623).
Author
Owner

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

Rebased on main. Part of this landed in 735a2292, 652154ae and 9bcf80bf; what is left is the bit scan key bound, the coordinate fix for candidates of another dimension and the mixed-dimension tables, now split into three commits.

**@⁠NeySlim** on GitHub · 2026-10-14 07:04 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#issuecomment-6162866417) Rebased on main. Part of this landed in 735a2292, 652154ae and 9bcf80bf; what is left is the bit scan key bound, the coordinate fix for candidates of another dimension and the mixed-dimension tables, now split into three commits.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-17 07:55 UTC · original

Rebased on main (42bb0da5). After b6da0683 the mixed-dimension commit conflicts with main's rule (1D/2D mixing only for unfiltered loads and stores, and a 1D access must not take a 2D record), so I checked whether God of War still needs it.

It doesn't. With the bit scan bounds in place, traced runs from a new game through the sled section planned 353 indirect image tables and every one had a single dimension: 250 all 3D under image_sample_lz, 103 all cube under image_sample_l. The cross-dimension record that motivated the rule was the record past the table count, which the bit scan commit no longer reads, and a cube/2D array mix is already covered by main's 2D/2D array rule.

So I dropped "sample and load mixed-dimension indirect image candidates" and "read only the instruction's coordinates" from this PR. What's left is the bit scan bound (mask bits and table count). Main's finite bit mask worklists don't cover it: TestBitScanKeyRange fails on main without this commit. resource_tracking, resource_materialization, scalar_provenance and shader_cfg pass; GPU suite one case per process: same 52 failures as main (out of 775).

**@⁠NeySlim** on GitHub · 2026-10-17 07:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1255#issuecomment-6231438609) Rebased on main (42bb0da5). After b6da0683 the mixed-dimension commit conflicts with main's rule (1D/2D mixing only for unfiltered loads and stores, and a 1D access must not take a 2D record), so I checked whether God of War still needs it. It doesn't. With the bit scan bounds in place, traced runs from a new game through the sled section planned 353 indirect image tables and every one had a single dimension: 250 all 3D under `image_sample_lz`, 103 all cube under `image_sample_l`. The cross-dimension record that motivated the rule was the record past the table count, which the bit scan commit no longer reads, and a cube/2D array mix is already covered by main's 2D/2D array rule. So I dropped "sample and load mixed-dimension indirect image candidates" and "read only the instruction's coordinates" from this PR. What's left is the bit scan bound (mask bits and table count). Main's finite bit mask worklists don't cover it: `TestBitScanKeyRange` fails on main without this commit. resource_tracking, resource_materialization, scalar_provenance and shader_cfg pass; GPU suite one case per process: same 52 failures as main (out of 775).
This pull request has changes conflicting with the target branch.
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • 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/1255/head:github-bot/gh-1255'
git switch 'github-bot/gh-1255'

Merge

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