shader: support mixed indirect image candidates and bounded keys #852

Closed
github-bot wants to merge 12 commits from gh-pr/852/head into gh-pr/852/base
Owner

@⁠tototomate123 on GitHub · 2026-09-26 16:13 UTC · original
tototomate123:fix/hfw-indirect-image-candidates → main · +1980 −595 · 6 files · 12 commits · closed without merging

Depends on #811. This follow-up handles image descriptor candidates that differ between 2D and 3D textures and lets indirect mappings serve dimension queries and image reads. It builds on #811 s address backed indirect descriptor tracking. Until #811 merges, GitHubs diff against main also includes the commits from #811.

Changes

  • Accept 2D and 3D candidates when the image is used only for simple sampling without explicit derivatives, offsets, or comparison. Keep rejecting incompatible candidates for other uses.
  • Preserve the instruction's supplied coordinate layout when sampling or reading a candidate with a different dimension, so a mip level is not mistaken for a depth coordinate.
  • Share the indirect candidate selection path across sampling, dimension queries, and image reads. Dimension queries and reads use each selected candidate's actual image dimension.
  • Include descriptor details in incompatible-candidate errors and identify unsupported indirect image operations explicitly.
  • Recognize bounded address-backed material keys in the captured HFW shader. Enumerate the words the shader can read, apply its key transform, and reject specialization if shader writes can overlap those words.
  • Recognize scalar-buffer image keys selected by a signed-clamped loop index. Probe only reachable slots; keep wrapped-offset enumeration for selectors without a proven bound.
  • Add resource tracking, specialization, and SPIR-V regression coverage for mixed dimensions, queries, reads, and coordinate layout.

Manual result and remaining issue

With local build b2c394d, Horizon Forbidden West (PPSA01521) gets past the earlier shader tracking and materialization failures and consistently renders the loading screen after New Game. It remained on that screen for at least five minutes in more than two manual runs; no new shader or fatal error appeared. i3STzxuwPx0[Rudp_v1][Rudp_v1.1][Func] is called repeatedly but remains unresolved. The cause of the loading screen wait is not yet known.

Validation

  • Linux: cmake --build _Build/linux --target resource_tracking_tests resource_materialization_tests shader_recompiler_compute_tests kyty_emulator -j 4 passed after merging upstream main at ae39466.
  • Linux: ctest --test-dir _Build/linux --output-on-failure -R '^(resource_tracking|resource_materialization|shader_recompiler_compute)$' passed after that merge (3 tests).
  • The source commits passed the configured clang-format pre-commit hook.
  • The manual game run was on b2c394d; no game run has been performed after the upstream main merge.
  • Windows and macOS builds and tests have not been run locally. Confirm CI results before merging.

AI assistance was used to investigate the crashes, implement the shader changes, review the C++ changes, write regression tests, and run local checks. I manually tested the game and reviewed the resulting behavior, crash logs and parts of the code.

**@⁠tototomate123** on GitHub · 2026-09-26 16:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/852) `tototomate123:fix/hfw-indirect-image-candidates` → `main` · +1980 −595 · 6 files · 12 commits · closed without merging **Depends on #811.** This follow-up handles image descriptor candidates that differ between 2D and 3D textures and lets indirect mappings serve dimension queries and image reads. It builds on #811 s address backed indirect descriptor tracking. Until #811 merges, GitHubs diff against `main` also includes the commits from #811. ### Changes - Accept 2D and 3D candidates when the image is used only for simple sampling without explicit derivatives, offsets, or comparison. Keep rejecting incompatible candidates for other uses. - Preserve the instruction's supplied coordinate layout when sampling or reading a candidate with a different dimension, so a mip level is not mistaken for a depth coordinate. - Share the indirect candidate selection path across sampling, dimension queries, and image reads. Dimension queries and reads use each selected candidate's actual image dimension. - Include descriptor details in incompatible-candidate errors and identify unsupported indirect image operations explicitly. - Recognize bounded address-backed material keys in the captured HFW shader. Enumerate the words the shader can read, apply its key transform, and reject specialization if shader writes can overlap those words. - Recognize scalar-buffer image keys selected by a signed-clamped loop index. Probe only reachable slots; keep wrapped-offset enumeration for selectors without a proven bound. - Add resource tracking, specialization, and SPIR-V regression coverage for mixed dimensions, queries, reads, and coordinate layout. ### Manual result and remaining issue With local build `b2c394d`, Horizon Forbidden West (PPSA01521) gets past the earlier shader tracking and materialization failures and consistently renders the loading screen after New Game. It remained on that screen for at least five minutes in more than two manual runs; no new shader or fatal error appeared. `i3STzxuwPx0[Rudp_v1][Rudp_v1.1][Func]` is called repeatedly but remains unresolved. The cause of the loading screen wait is not yet known. ### Validation - Linux: `cmake --build _Build/linux --target resource_tracking_tests resource_materialization_tests shader_recompiler_compute_tests kyty_emulator -j 4` passed after merging upstream `main` at `ae39466`. - Linux: `ctest --test-dir _Build/linux --output-on-failure -R '^(resource_tracking|resource_materialization|shader_recompiler_compute)$'` passed after that merge (3 tests). - The source commits passed the configured `clang-format` pre-commit hook. - The manual game run was on `b2c394d`; no game run has been performed after the upstream `main` merge. - Windows and macOS builds and tests have not been run locally. Confirm CI results before merging. _AI assistance was used to investigate the crashes, implement the shader changes, review the C++ changes, write regression tests, and run local checks. I manually tested the game and reviewed the resulting behavior, crash logs and parts of the code._
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:35:08 +00:00
github-bot closed this pull request 2026-11-26 09:35:08 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 16:25 UTC · original · edited 2026-09-30 13:46 UTC

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

Resource tracking now recognizes address-key, buffer-record, and loop-derived indirect-image selectors. Materialization enumerates selector keys, builds candidate mappings, and validates candidate compatibility. It supports simple 2D/3D candidate combinations when the image metadata permits them. The SPIR-V emitter uses candidate-specific operations for sampling, dimension queries, and reads, and limits coordinates to supplied address components. Tests cover selector tracking, materialization, and emitted image operations.

Suggested reviewers: nmzik, senaxx

Priority: ⬇️ Low

Change: Feature

Merge Risk: 🟡 Moderate · up to 32e6b

For some indirect texture selectors, shaders can sample the wrong texture. This happens when a bounded loop selector has a large member offset, or when bounded and unbounded uses share one source. Fix both before merging.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 32e6b

The new bounded image-selection rules can merge distinct selection bounds or inspect the wrong slots, potentially selecting the wrong image. Guest-memory checks and descriptor validation remain in place; no host-memory escape was demonstrated.

Retained concerns

  • Medium · architecture · inferred: The new selector_limit affects which material words and image candidates are enumerated, but InternSource does not compare it. Image sources sharing material/table descriptors and other metadata can therefore merge despite different loop caps. If the shorter bound is interned first, another operation can lack reachable candidates; the runtime switch silently selects candidate zero for an unmapped key. This breaks the specialization-to-binding identity contract.
  • Medium · architecture · inferred: Tracking reduces the material offset to its wraparound residue before recording a finite selector_limit. Bounded materialization then treats that residue as the original starting offset. MatchMaterialOffset accepts larger constant biases: with stride 16, bias 36, and cap 2, enumeration reads offsets 4 and 20 instead of the reachable offsets 36 and 52. Residue reduction preserves an unrestricted wrapped domain, not a finite loop domain, so valid runtime keys can be omitted and redirected to the default image candidate.
Security review details

Security Blast Radius

  • inferred — Guest shader code and descriptor data reach the shared graphics/compute shader pipeline and current guest-memory backing. The demonstrated outcome is candidate discovery and image-binding selection; cross-guest, host-memory, or broader privilege compromise has not been established.

Security Findings and Attack Paths

  • inferred — A crafted shader can exercise differing finite selector domains against shared descriptor sources or biased material offsets. Incomplete candidate discovery can then redirect a runtime image operation to candidate zero. This supports the resource-identity concerns above, but does not demonstrate access outside guest-authorized memory.

Trust Boundaries and Controls

  • observed — The production strict-read callback delegates to guest-memory backing and rejects GPU-dirty ranges. Address-key tracking requires guarded, aligned, bounded reads and consistent affine transforms. Protected address/record/mask selectors reject address or image writes and enable captured-read overlap checks when buffers are written.

Resilience and Maintainability Implications

  • observed — The scalar-buffer fallback is not classified as a protected image, so its selector reads do not independently activate write-overlap capture. The inspected main-base implementation also specialized scalar-buffer keys without that protection. This is a pre-existing limitation, not evidence of a newly introduced write-bypass vulnerability.
🚥 Pre-merge checks | ✅ 4 | ❓ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ❓ Inconclusive Docstring coverage is 4.49% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 89 functions across 5 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main changes: support for mixed indirect image candidates and bounded keys.
Description check ✅ Passed The description directly explains the implementation, tests, validation results, dependencies, and known limitations for the changeset.
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.
Full details: Docstring Coverage

Explanation

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


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-09-26 16:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/852#issuecomment-5847873472) · edited 2026-09-30 13:46 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/852?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> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough Resource tracking now recognizes address-key, buffer-record, and loop-derived indirect-image selectors. Materialization enumerates selector keys, builds candidate mappings, and validates candidate compatibility. It supports simple 2D/3D candidate combinations when the image metadata permits them. The SPIR-V emitter uses candidate-specific operations for sampling, dimension queries, and reads, and limits coordinates to supplied address components. Tests cover selector tracking, materialization, and emitted image operations. **Suggested reviewers:** `nmzik`, `senaxx` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"32e6b2a0c4d351b0ecfc2ea82c81c19f8adc3545" --> **Change:** Feature <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🟡 Moderate_ · up to `32e6b` <!-- final_review_risk_coverage:{"sourceCommitId":"32e6b2a0c4d351b0ecfc2ea82c81c19f8adc3545","coveredCommitId":"32e6b2a0c4d351b0ecfc2ea82c81c19f8adc3545","kind":"reviewed"} --> For some indirect texture selectors, shaders can sample the wrong texture. This happens when a bounded loop selector has a large member offset, or when bounded and unbounded uses share one source. Fix both before merging. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `32e6b` The new bounded image-selection rules can merge distinct selection bounds or inspect the wrong slots, potentially selecting the wrong image. Guest-memory checks and descriptor validation remain in place; no host-memory escape was demonstrated. **Retained concerns** - **Medium · architecture · inferred:** The new selector_limit affects which material words and image candidates are enumerated, but InternSource does not compare it. Image sources sharing material/table descriptors and other metadata can therefore merge despite different loop caps. If the shorter bound is interned first, another operation can lack reachable candidates; the runtime switch silently selects candidate zero for an unmapped key. This breaks the specialization-to-binding identity contract. - **Medium · architecture · inferred:** Tracking reduces the material offset to its wraparound residue before recording a finite selector_limit. Bounded materialization then treats that residue as the original starting offset. MatchMaterialOffset accepts larger constant biases: with stride 16, bias 36, and cap 2, enumeration reads offsets 4 and 20 instead of the reachable offsets 36 and 52. Residue reduction preserves an unrestricted wrapped domain, not a finite loop domain, so valid runtime keys can be omitted and redirected to the default image candidate. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — Guest shader code and descriptor data reach the shared graphics/compute shader pipeline and current guest-memory backing. The demonstrated outcome is candidate discovery and image-binding selection; cross-guest, host-memory, or broader privilege compromise has not been established. **Security Findings and Attack Paths** - _inferred_ — A crafted shader can exercise differing finite selector domains against shared descriptor sources or biased material offsets. Incomplete candidate discovery can then redirect a runtime image operation to candidate zero. This supports the resource-identity concerns above, but does not demonstrate access outside guest-authorized memory. **Trust Boundaries and Controls** - _observed_ — The production strict-read callback delegates to guest-memory backing and rejects GPU-dirty ranges. Address-key tracking requires guarded, aligned, bounded reads and consistent affine transforms. Protected address/record/mask selectors reject address or image writes and enable captured-read overlap checks when buffers are written. **Resilience and Maintainability Implications** - _observed_ — The scalar-buffer fallback is not classified as a protected image, so its selector reads do not independently activate write-overlap capture. The inspected main-base implementation also specialized scalar-buffer keys without that protection. This is a pre-existing limitation, not evidence of a newly introduced write-bypass vulnerability. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❓ 1</summary> ### ❌ Failed checks (1 inconclusive) | Check name | Status | Explanation | Resolution | | :----------------: | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ❓ Inconclusive | Docstring coverage is 4.49% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 89 functions across 5 files. (1 skipped: 1… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :-------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly summarizes the main changes: support for mixed indirect image candidates and bounded keys. | | Description check | ✅ Passed | The description directly explains the implementation, tests, validation results, dependencies, and known limitations for the changeset. | | 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. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 4.49% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 89 functions across 5 files. (1 skipped: 1 too large.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=852)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [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) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 16:25 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: 2c975fd3-aa87-4151-8757-a8c7839a5057

📥 Commits

Reviewing files that changed from the base of the PR and between 16b83a034c and ae39466e14.

📒 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 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 16:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/852#pullrequestreview-5326549576) · **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**: `2c975fd3-aa87-4151-8757-a8c7839a5057` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 16b83a034cdc7abed2482605c77921b10056d83c and ae39466e14e15e71fecdc66a63ca771a501928f7. </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 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -740,2 +815,3 @@
(!a.selector_mask.IsEmpty() &&
!EquivalentValue(m_program, a.selector_mask, b.selector_mask))) continue;
!EquivalentValue(m_program, a.selector_mask, b.selector_mask)))
continue;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 16:25 UTC · original

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Compare selector_limit when you intern indirect image sources.

InternSource now compares the new key metadata: record_key, address_key, address_key_count, key_scale and key_bias. It does not compare selector_limit. TryMakeIndirectImage sets selector_limit only when the selector's loop bound is SMin32(x, cap).

Consider two handles that read the same material and table with the same stride and offsets. If only one of them is in an SMin32-bounded loop, both handles intern to the same DescriptorSource. The metadata of the first handle wins. AddImage keys by source, so both handles also share one ImageResource and one key mapping.

If the bounded handle comes first, MaterializeIndirectImage probes only selector_limit records. Keys that only the unbounded handle can reach are then missing from the mapping. At runtime, EmitImageCandidateSwitch sends a missing key to candidate 0, which samples the wrong texture.

🐛 Proposed fix
 				    a.address_key_count != b.address_key_count || a.key_scale != b.key_scale ||
-				    a.key_bias != b.key_bias ||
+				    a.key_bias != b.key_bias || a.selector_limit != b.selector_limit ||
 				    !EquivalentValue(m_program, a.key_count, b.key_count) ||
📝 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.

				    a.selector_stride != b.selector_stride ||
				    a.selector_offset != b.selector_offset || a.table_offset != b.table_offset ||
				    a.record_key != b.record_key || a.address_key != b.address_key ||
				    a.address_key_count != b.address_key_count || a.key_scale != b.key_scale ||
				    a.key_bias != b.key_bias || a.selector_limit != b.selector_limit ||
				    !EquivalentValue(m_program, a.key_count, b.key_count) ||
				    a.selector_mask.IsEmpty() != b.selector_mask.IsEmpty() ||
				    (!a.selector_mask.IsEmpty() &&
				     !EquivalentValue(m_program, a.selector_mask, b.selector_mask)))
					continue;
**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 16:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/852#discussion_r4111975417) _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Compare `selector_limit` when you intern indirect image sources.** `InternSource` now compares the new key metadata: `record_key`, `address_key`, `address_key_count`, `key_scale` and `key_bias`. It does not compare `selector_limit`. `TryMakeIndirectImage` sets `selector_limit` only when the selector's loop bound is `SMin32(x, cap)`. Consider two handles that read the same material and table with the same stride and offsets. If only one of them is in an `SMin32`-bounded loop, both handles intern to the same `DescriptorSource`. The metadata of the first handle wins. `AddImage` keys by `source`, so both handles also share one `ImageResource` and one key mapping. If the bounded handle comes first, `MaterializeIndirectImage` probes only `selector_limit` records. Keys that only the unbounded handle can reach are then missing from the mapping. At runtime, `EmitImageCandidateSwitch` sends a missing key to candidate 0, which samples the wrong texture. <details> <summary>🐛 Proposed fix</summary> ```diff a.address_key_count != b.address_key_count || a.key_scale != b.key_scale || - a.key_bias != b.key_bias || + a.key_bias != b.key_bias || a.selector_limit != b.selector_limit || !EquivalentValue(m_program, a.key_count, b.key_count) || ``` </details> <!-- 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 a.selector_stride != b.selector_stride || a.selector_offset != b.selector_offset || a.table_offset != b.table_offset || a.record_key != b.record_key || a.address_key != b.address_key || a.address_key_count != b.address_key_count || a.key_scale != b.key_scale || a.key_bias != b.key_bias || a.selector_limit != b.selector_limit || !EquivalentValue(m_program, a.key_count, b.key_count) || a.selector_mask.IsEmpty() != b.selector_mask.IsEmpty() || (!a.selector_mask.IsEmpty() && !EquivalentValue(m_program, a.selector_mask, b.selector_mask))) continue; ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:19a6e791038d1f8759d467ef --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠tototomate123 on GitHub · 2026-09-26 18:43 UTC · original · edited 2026-09-26 21:17 UTC

HFW loading investigation update

The latest contributor-run build (ae39466-dirty) reaches VS 11 / PS 9 / CS 55 after a local AMM allocator fix. The previous loading stall was caused by an observable allocation failure rather than slow shader compilation.

The current stopping point is a separate audio assertion after unresolved eDFeTyi+G3Y (sceAjmDecMp3ParseFrame).

These are local follow-up changes and are not part of this PR. The shader changes described in the PR body remain the scope of #852.

Follow-up investigation

  1. Diagnostics: added tracing for loading, APR, GPU waits, RUDP, and AMM to identify where progress stopped.
  2. RUDP: tested the observed status poll with pass/zero/one outputs; none affected the stall.
  3. AMM: added reusable automatic backing, which fixes the observed allocation exhaustion and lets HFW progress to VS 11 / PS 9 / CS 55. See #854; #780 contains related work.
  4. MP3: implemented sceAjmDecMp3ParseFrame (eDFeTyi+G3Y) and the metadata the game's caller expects. This has not yet been tested in-game.
  5. Tests: added MP3 parser coverage and reran the relevant AMM regression tests.

Validation and limits

  • Linux kyty_emulator rebuilt successfully.
  • MP3 parser CTest and ASan/UBSan runs passed.
  • AMM regression tests passed.
  • git diff --check passed.
  • The CS55 run validates the AMM fix, but the new MP3 implementation has not yet been tested in-game.
  • Full loading/gameplay and Windows/macOS remain unverified.

The AJM NID/output layout was cross-checked against shadPS4's AJM implementation and MP3 parser, as well as the local guest call site.

AI assistance was used for the investigation, implementation, tests and this update. I performed the game runs and supplied the logs

**@⁠tototomate123** on GitHub · 2026-09-26 18:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/852#issuecomment-5848854526) · edited 2026-09-26 21:17 UTC ## HFW loading investigation update The latest contributor-run build (`ae39466-dirty`) reaches **VS 11 / PS 9 / CS 55** after a local AMM allocator fix. The previous loading stall was caused by an observable allocation failure rather than slow shader compilation. The current stopping point is a separate audio assertion after unresolved `eDFeTyi+G3Y` (`sceAjmDecMp3ParseFrame`). These are **local follow-up changes and are not part of this PR**. The shader changes described in the PR body remain the scope of #852. ### Follow-up investigation 1. **Diagnostics:** added tracing for loading, APR, GPU waits, RUDP, and AMM to identify where progress stopped. 2. **RUDP:** tested the observed status poll with pass/zero/one outputs; none affected the stall. 3. **AMM:** added reusable automatic backing, which fixes the observed allocation exhaustion and lets HFW progress to **VS 11 / PS 9 / CS 55**. See #854; #780 contains related work. 4. **MP3:** implemented `sceAjmDecMp3ParseFrame` (`eDFeTyi+G3Y`) and the metadata the game's caller expects. This has not yet been tested in-game. 5. **Tests:** added MP3 parser coverage and reran the relevant AMM regression tests. ### Validation and limits - Linux `kyty_emulator` rebuilt successfully. - MP3 parser CTest and ASan/UBSan runs passed. - AMM regression tests passed. - `git diff --check` passed. - The **CS55 run validates the AMM fix**, but the new MP3 implementation has **not yet been tested in-game**. - Full loading/gameplay and Windows/macOS remain unverified. The AJM NID/output layout was cross-checked against shadPS4's AJM implementation and MP3 parser, as well as the local guest call site. AI assistance was used for the investigation, implementation, tests and this update. I performed the game runs and supplied the logs
@ -1424,0 +1911,4 @@
(ImmediateU32(bound_inst->Arg(0), bound_cap) ||
ImmediateU32(bound_inst->Arg(1), bound_cap)) &&
bound_cap > 0u && bound_cap <= INT32_MAX) {
indirect.selector_limit = bound_cap;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 13:41 UTC · original

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Keep the unreduced member offset when you set selector_limit.

Lines 1903-1905 replace indirect.selector_offset with its residue modulo step = gcd(selector_stride, 2^32). That value is correct only for the unbounded branch in MaterializeIndirectImage. That branch enumerates the full residue class in steps of step.

The new selector_limit branch in ResourceMaterialization.cpp (lines 356-377) enumerates selector_offset + index * selector_stride instead. It steps by selector_stride, not by step. If the member offset is at least step, the enumerated offsets differ from the offsets the shader reads.

Example: stride = 224 gives step = 32. A member offset of 36 is reduced to 4. The shader reads 36 + i*224, but materialization probes 4 + i*224. With stride = 2 and member 3, the reduced offset is 0, so the probes miss every odd-aligned read. The key mapping then does not contain the keys that the shader loads. At runtime, the candidate switch sends each missing key to candidate 0, so the shader samples the wrong texture.

The overflow check in the bounded branch also uses the reduced offset. As a result, it does not prove that member + (cap-1)*stride stays below 2^32.

Fix: when you set selector_limit, store the original member offset plus the aligned immediate. ReadScalarTable aligns each probe with & ~3. Adding memory->offset & ~3 is a multiple of 4, so (member + i*stride + imm_al) & ~3 equals ((member + i*stride) & ~3) + imm_al. The materialization overflow check then correctly rules out U32 wraparound. The current tests do not catch this bug. The bounded fixture puts the member offset in memory.offset, and the split_offset cases have no loop bound. Add a bounded-loop fixture with an IAdd32 member offset that is at least step.

🐛 Proposed fix
+			const auto member_offset = indirect.selector_offset;
 			const auto step = std::gcd<uint64_t>(indirect.selector_stride, uint64_t {1} << 32u);
 			indirect.selector_offset =
 			    (static_cast<uint32_t>(indirect.selector_offset % step) & ~3u) +
 			    (memory->offset & ~3u);
 			const auto  loop_bound = BoundedLoopCount(selector, handle.Parent(), true);
 			const auto* bound_inst = loop_bound.Resolve().TryInstruction();
 			uint32_t    bound_cap  = 0;
 			if (bound_inst != nullptr && bound_inst->GetOpcode() == ValueOpcode::SMin32 &&
 			    bound_inst->NumArgs() == 2u &&
 			    (ImmediateU32(bound_inst->Arg(0), bound_cap) ||
 			     ImmediateU32(bound_inst->Arg(1), bound_cap)) &&
 			    bound_cap > 0u && bound_cap <= INT32_MAX) {
 				indirect.selector_limit = bound_cap;
+				// The bounded enumeration steps by the stride, so it needs the exact member offset.
+				indirect.selector_offset = member_offset + (memory->offset & ~3u);
 			}

The existing check static_cast<uint64_t>(indirect.selector_offset) + memory->offset > UINT32_MAX at line 1896 already prevents overflow in the new sum.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 13:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/852#discussion_r4145229896) _🎯 Functional Correctness_ | _🟠 Major_ | _🏗️ Heavy lift_ **Keep the unreduced member offset when you set `selector_limit`.** Lines 1903-1905 replace `indirect.selector_offset` with its residue modulo `step = gcd(selector_stride, 2^32)`. That value is correct only for the unbounded branch in `MaterializeIndirectImage`. That branch enumerates the full residue class in steps of `step`. The new `selector_limit` branch in `ResourceMaterialization.cpp` (lines 356-377) enumerates `selector_offset + index * selector_stride` instead. It steps by `selector_stride`, not by `step`. If the member offset is at least `step`, the enumerated offsets differ from the offsets the shader reads. Example: `stride = 224` gives `step = 32`. A member offset of `36` is reduced to `4`. The shader reads `36 + i*224`, but materialization probes `4 + i*224`. With `stride = 2` and member `3`, the reduced offset is `0`, so the probes miss every odd-aligned read. The key mapping then does not contain the keys that the shader loads. At runtime, the candidate switch sends each missing key to candidate 0, so the shader samples the wrong texture. The overflow check in the bounded branch also uses the reduced offset. As a result, it does not prove that `member + (cap-1)*stride` stays below `2^32`. Fix: when you set `selector_limit`, store the original member offset plus the aligned immediate. `ReadScalarTable` aligns each probe with `& ~3`. Adding `memory->offset & ~3` is a multiple of 4, so `(member + i*stride + imm_al) & ~3` equals `((member + i*stride) & ~3) + imm_al`. The materialization overflow check then correctly rules out U32 wraparound. The current tests do not catch this bug. The bounded fixture puts the member offset in `memory.offset`, and the `split_offset` cases have no loop bound. Add a bounded-loop fixture with an `IAdd32` member offset that is at least `step`. <details> <summary>🐛 Proposed fix</summary> ```diff + const auto member_offset = indirect.selector_offset; const auto step = std::gcd<uint64_t>(indirect.selector_stride, uint64_t {1} << 32u); indirect.selector_offset = (static_cast<uint32_t>(indirect.selector_offset % step) & ~3u) + (memory->offset & ~3u); const auto loop_bound = BoundedLoopCount(selector, handle.Parent(), true); const auto* bound_inst = loop_bound.Resolve().TryInstruction(); uint32_t bound_cap = 0; if (bound_inst != nullptr && bound_inst->GetOpcode() == ValueOpcode::SMin32 && bound_inst->NumArgs() == 2u && (ImmediateU32(bound_inst->Arg(0), bound_cap) || ImmediateU32(bound_inst->Arg(1), bound_cap)) && bound_cap > 0u && bound_cap <= INT32_MAX) { indirect.selector_limit = bound_cap; + // The bounded enumeration steps by the stride, so it needs the exact member offset. + indirect.selector_offset = member_offset + (memory->offset & ~3u); } ``` The existing check `static_cast<uint64_t>(indirect.selector_offset) + memory->offset > UINT32_MAX` at line 1896 already prevents overflow in the new sum. </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8e457455b1335336304ae183 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 13:41 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: 391db8b9-48e6-4878-a3e8-8202fe8ac4f6

📥 Commits

Reviewing files that changed from the base of the PR and between ae39466e14 and 32e6b2a0c4.

📒 Files selected for processing (5)
  • 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; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 13:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/852#pullrequestreview-5366995694) · **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**: `391db8b9-48e6-4878-a3e8-8202fe8ac4f6` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between ae39466e14e15e71fecdc66a63ca771a501928f7 and 32e6b2a0c4d351b0ecfc2ea82c81c19f8adc3545. </details> <details> <summary>📒 Files selected for processing (5)</summary> * `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; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.