Spider-Man: Miles Morales to gameplay: recompiler, PM4, cache and diagnostics fixes #780

Open
github-bot wants to merge 13 commits from github-bot/gh-780 into main AGit
Owner

@⁠itsmemac on GitHub · 2026-09-22 21:31 UTC · original
itsmemac:spiderman-running-22-09-2026 → main · +690 −174 · 35 files · 13 commits · open

Summary

Marvel's Spider-Man: Miles Morales (PPSA01417) boots, loads the world and is playable, and
Astro Bot (PPSA21564) runs with its non-RT patch (distributed separately, not part of this
PR). The work is split into topic commits that each build on their own, so they can be
reviewed and cherry-picked individually. Each commit message explains the problem it fixes
and how it was found.

Changes since the last version of this PR

Rebased on main at a0268f1d (912 commits since the previous base). Where main now does
the same job, its version is kept and our topic is dropped; where ours still adds something,
it was re-ported onto the new code.

Dropped, superseded by main:

  • shader: implement S_MEMREALTIME (77a8f307, b2f40c6c read the device clock divided to 100 MHz).
  • shader: cache declared shader hashes (the shader map hashes once at registration).
  • render: read GPU-owned descriptor words through the tracked mapping (TryReadBufferBacking
    downloads GPU-dirty bytes first).
  • render: skip clean tracker regions and redundant BDA synchronization (the BDA sync queue,
    f356fa37, and the early-out in ForEachModifiedRange cover it).
  • buffer cache: download ranges larger than the staging ring in windows (oversized downloads
    use a one-off buffer).
  • vulkan: place images in host memory when device memory is exhausted (6ff6e755 allocates
    with AUTO_PREFER_DEVICE within budget).
  • ampr: map commands, counters and asynchronous engines (implemented on main).
  • ajm: carry partial ATRAC9 superframes across decode jobs (main now reports partial input
    as unconsumed so the title resends it, and tests that contract; stashing the tail would
    decode a resend twice).

The commits the older description listed but that had already left the branch (GLC/SLC
coherence, EOP event 0x14, VrrStatus, agc tracing, the save_data_memory_tests build) are not
listed below either.

Re-ported onto the rewritten code:

  • Non-fatal translation: the pipeline cache now marks an untranslatable program
    skip_dispatch; tessellation pairs the analysis rejects are remembered next to
    m_tess_layouts. Resource tracking fails inside many nested planning helpers, so in
    non-fatal mode Tracker::Fail throws a private TrackingFailure that only
    TrackResources catches, instead of an early return at every call site.
  • Texture collector: the per-frame budget keeps main's heap-reference and eviction-counter
    handling.
  • Device loss: VK_EXT_device_fault and NV diagnostics config are wired into the new feature
    chain. The NV checkpoint markers are dropped: main removed the per-command debug info they
    were labelled with, and the fault's vendor dump is what names the hung shader.
  • Video out: reduced to the two 10-bit encodings main still lacks.
  • Smaller adjustments: the GPU rejection uses reject(), the presented-frame count sits next
    to main's, and image backing that cannot be read zero-fills through TryReadSparseBacking.

Commits

Shader recompiler

  • shader: skip programs the recompiler cannot translate instead of exiting
  • shader: snapshot pixel shader input semantics at registration

Command processor

  • gpu: skip PM4 type-0 packets

Renderer and caches

  • render: bind buffer descriptors in guest page 0 as null
  • buffer cache: age entries by presented frames and publish aged dirty buffers
  • buffer cache: zero-fill guest image backing that cannot be read
  • texture cache: budget eviction per frame and write back GPU-written tiled images
  • texture cache: stage image downloads larger than the download ring

Vulkan and video out

  • video out: add two 10-bit output format policies
  • vulkan: skip GPUs that cannot report surface capabilities

Libraries

  • dialog: keep progress bar dialogs open until the title closes them

Diagnostics

  • vulkan: report device loss with VK_EXT_device_fault
  • common: print a symbolized host stack on fatal errors

Testing

  • Windows 11, clang-cl, Release: the emulator and the test targets build.
  • ctest: 74 of 79 pass. None of the five failures involves this PR: vdecsw does not
    compile with the VS 2019 STL (std::aligned_alloc), psml is not built by kyty_tests,
    kernel_file_system does not link on Windows (SDL_main), and common's
    File.GetTimesReportsExactNanoseconds throws in this STL's last_write_time.
    ngs2_sampler passes once the ATRAC9 topic is dropped.
  • shader_recompiler_compute passes, including the buffer and texture cache GC tests and
    the tessellation interface tests this PR updates.
  • Not yet run on games on this tip.
  • Built only on Windows with an NVIDIA GPU; the Linux and macOS builds are left to CI.

Known limitations

  • Programs that use still-unimplemented instructions are skipped along with their draw or
    dispatch.
  • Spider-Man: water does not render yet.

AI assistance was used

🤖 Generated with Claude Code

**@⁠itsmemac** on GitHub · 2026-09-22 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780) `itsmemac:spiderman-running-22-09-2026` → `main` · +690 −174 · 35 files · 13 commits · open ## Summary Marvel's Spider-Man: Miles Morales (PPSA01417) boots, loads the world and is playable, and Astro Bot (PPSA21564) runs with its non-RT patch (distributed separately, not part of this PR). The work is split into topic commits that each build on their own, so they can be reviewed and cherry-picked individually. Each commit message explains the problem it fixes and how it was found. ## Changes since the last version of this PR Rebased on `main` at a0268f1d (912 commits since the previous base). Where `main` now does the same job, its version is kept and our topic is dropped; where ours still adds something, it was re-ported onto the new code. Dropped, superseded by `main`: - shader: implement S_MEMREALTIME (77a8f307, b2f40c6c read the device clock divided to 100 MHz). - shader: cache declared shader hashes (the shader map hashes once at registration). - render: read GPU-owned descriptor words through the tracked mapping (TryReadBufferBacking downloads GPU-dirty bytes first). - render: skip clean tracker regions and redundant BDA synchronization (the BDA sync queue, f356fa37, and the early-out in ForEachModifiedRange cover it). - buffer cache: download ranges larger than the staging ring in windows (oversized downloads use a one-off buffer). - vulkan: place images in host memory when device memory is exhausted (6ff6e755 allocates with AUTO_PREFER_DEVICE within budget). - ampr: map commands, counters and asynchronous engines (implemented on `main`). - ajm: carry partial ATRAC9 superframes across decode jobs (`main` now reports partial input as unconsumed so the title resends it, and tests that contract; stashing the tail would decode a resend twice). The commits the older description listed but that had already left the branch (GLC/SLC coherence, EOP event 0x14, VrrStatus, agc tracing, the save_data_memory_tests build) are not listed below either. Re-ported onto the rewritten code: - Non-fatal translation: the pipeline cache now marks an untranslatable program `skip_dispatch`; tessellation pairs the analysis rejects are remembered next to `m_tess_layouts`. Resource tracking fails inside many nested planning helpers, so in non-fatal mode `Tracker::Fail` throws a private `TrackingFailure` that only `TrackResources` catches, instead of an early return at every call site. - Texture collector: the per-frame budget keeps `main`'s heap-reference and eviction-counter handling. - Device loss: `VK_EXT_device_fault` and NV diagnostics config are wired into the new feature chain. The NV checkpoint markers are dropped: `main` removed the per-command debug info they were labelled with, and the fault's vendor dump is what names the hung shader. - Video out: reduced to the two 10-bit encodings `main` still lacks. - Smaller adjustments: the GPU rejection uses `reject()`, the presented-frame count sits next to `main`'s, and image backing that cannot be read zero-fills through `TryReadSparseBacking`. ## Commits Shader recompiler - shader: skip programs the recompiler cannot translate instead of exiting - shader: snapshot pixel shader input semantics at registration Command processor - gpu: skip PM4 type-0 packets Renderer and caches - render: bind buffer descriptors in guest page 0 as null - buffer cache: age entries by presented frames and publish aged dirty buffers - buffer cache: zero-fill guest image backing that cannot be read - texture cache: budget eviction per frame and write back GPU-written tiled images - texture cache: stage image downloads larger than the download ring Vulkan and video out - video out: add two 10-bit output format policies - vulkan: skip GPUs that cannot report surface capabilities Libraries - dialog: keep progress bar dialogs open until the title closes them Diagnostics - vulkan: report device loss with VK_EXT_device_fault - common: print a symbolized host stack on fatal errors ## Testing - Windows 11, clang-cl, Release: the emulator and the test targets build. - `ctest`: 74 of 79 pass. None of the five failures involves this PR: `vdecsw` does not compile with the VS 2019 STL (`std::aligned_alloc`), `psml` is not built by `kyty_tests`, `kernel_file_system` does not link on Windows (SDL_main), and `common`'s `File.GetTimesReportsExactNanoseconds` throws in this STL's `last_write_time`. `ngs2_sampler` passes once the ATRAC9 topic is dropped. - `shader_recompiler_compute` passes, including the buffer and texture cache GC tests and the tessellation interface tests this PR updates. - Not yet run on games on this tip. - Built only on Windows with an NVIDIA GPU; the Linux and macOS builds are left to CI. ## Known limitations - Programs that use still-unimplemented instructions are skipped along with their draw or dispatch. - Spider-Man: water does not render yet. AI assistance was used 🤖 Generated with [Claude Code](https://claude.com/claude-code)
A program the recompiler cannot translate now costs its draw or dispatch
instead of the session. Marvel's Spider-Man: Miles Morales and Astro Bot each
have a handful of compute programs using instructions that are not implemented
yet (MIMG 0xe6 BVH intersection, VOP2 0x12 with SDWA), and upstream exits on the
first of them.

- CompileOptions::non_fatal and TranslateResult::unsupported; a
  TranslationNonFatalScope carries the policy into the frontend.
- The give-up points in Dispatch, ShaderCFG and the tessellation analysis and
  lowering record the reason, log it and return instead of calling EXIT.
  AnalyzeTessellationPrograms and LowerTessellationMemory return success.
- Resource tracking fails in many nested planning helpers, so in non-fatal mode
  Tracker::Fail logs and throws a TrackingFailure that only TrackResources
  catches; TrackResources returns false and the program is discarded.
- The pipeline cache marks an untranslatable program skip_dispatch, so it is
  not translated again, and remembers LS/HS pairs the tessellation analysis
  rejects.
- A draw is skipped when any of its vertex stages or its active pixel program
  is missing; GetGraphicsPrograms leaves stage 0 unbound for the existing check.
  A dispatch whose program is missing is skipped as before.
- A resource-materialization failure (a descriptor source not mapped or filled
  yet) skips that use and is logged, at most sixteen times.
- resource_tracking_tests and scalar_provenance_tests link common for the
  logging.
Titles leave reserved dwords in their command buffers as zeros, which decode as
type-0 packets and were reported as an unknown opcode. They are now skipped by
their encoded length.
A buffer descriptor whose base lies in guest page 0 is a null or garbage
descriptor; it now binds as null, as address 0 already did. The garbage
collector skips a buffer registered at address 0 (it had died on a page-aligned
buffer there, since the memory tracker cannot hold address 0), and the tracker's
invalid-range exit names the range.
- Pressure is judged by the cache's own bytes. Device-wide usage also counts
  the images spilled to host memory, which on a 6 GB card kept the collector in
  its aggressive mode forever, recreating ~100 buffers a second.
- An aged dirty buffer is always downloaded and dropped. Retaining it left its
  GPU-written bytes owning the pages, and images sharing those pages went black.
- Entries age in presented frames, not collector runs: the collector runs once
  per guest submission, and a title can submit a hundred times a frame.
  GraphicContext counts presented frames; the LRU clock adds one step per 512
  collector runs so a stretch without presents still ages.
- The cache tests present frames to age their entries, and the dirty-GC test
  follows the new policy.
ObtainBufferForImage zero-fills an image's staging copy when its guest backing
cannot be read yet (not mapped or not filled), instead of exiting.
The texture collector could not keep a 4K title in a 6 GB card. Measured on
Spider-Man:

- Entries age in presented frames. Counted in collector runs, one per guest
  submission, an age of 8 evicted textures inside the frame that used them, to
  recreate them the next: 11 000 image creations a second at the title menu.
  An image used in the frame being recorded is never a candidate. Title menu:
  1 fps to 30 fps.
- Pressure is judged by the cache's own image bytes. Device-wide usage counts
  the images the cache spilled to host memory and never falls.
- Under pressure, eviction is budgeted per frame in bytes actually freed, in
  proportion to the excess (a quarter of it over the critical mark, an eighth
  over the pressure mark, at least 64 or 16 MiB, at most 1 024 images a
  frame). A budget per run churned; a small fixed count was spent on images the
  collector then skipped.
- Under pressure a GPU-written tiled image is written back, detiled, and
  evicted like any other, within 256 MiB of write-back a frame (an image that
  does not fit what is left waits for the next frame, unless it is the first).
  They were never
  evicted before: 3 500 of every 4 000 candidates, so the cache grew to 13.5 GB
  and the NVIDIA driver crashed in present. A streaming burst now returns to the
  threshold within nine frames.
- The collector test helper starts each scenario with an empty frame budget.
An image larger than the download ring gets a staging buffer of its own for
the transfer instead of exiting: the ring cannot map it, and an image's
regions cannot be cut into ring-sized pieces the way a buffer range can.
Adds the video-out pixel format encodings 0x8100000622000000 (A2B10G10R10)
and 0x8100000600000000 (A2R10G10B10), which titles register beside the ones
already listed. Upstream has since added the BT.2100 PQ and FP16 encodings
this change originally carried.
A candidate GPU whose driver fails the surface capabilities query for the
window (vkGetPhysicalDeviceSurfaceCapabilitiesKHR) is skipped during device
selection instead of ending the session. The integrated GPU of a hybrid laptop
does this intermittently (ErrorUnknown), and the discrete GPU was never
considered.
A progress bar dialog has no button: the title closes it when its work is
done. The save-data dialog (mode 5) and the message dialog (mode 2) reported
their progress bars as finished at once, so the title took them for dismissed
and opened them again every frame. Spider-Man's manual save did that ~470
times a frame. They now stay running until closed; every other mode is answered as
before.
A lost device used to end in a bare EXIT from vkQueueSubmit or the timeline
wait, with nothing saying which work hung.

- VK_EXT_device_fault is enabled when the device offers it. When a submit or
  MasterSemaphore::Wait returns VK_ERROR_DEVICE_LOST, the fault description,
  address records and vendor records are printed and logged, and the vendor
  binary (on NVIDIA a GPU crash dump that names the hung shader) is written to
  _device_fault.nv-gpudmp.
- VK_NV_device_diagnostics_config is enabled with shader debug info, resource
  tracking and shader error reporting where available, which the NVIDIA dump
  draws on.
- MasterSemaphore::Wait reports the failing result and ticks instead of a
  bare EXIT_NOT_IMPLEMENTED.
A fatal EXIT prints a symbolized host stack (dbghelp on Windows, serialized
with a mutex since dbghelp is not thread-safe) after the build and error
lines.
Pixel shader input semantics are copied into ShaderMappedData when the shader
is registered, and ShaderGetStaticInputInfoPS reads the copy instead of reading
through the guest pointer for every lookup.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:32:15 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original · edited 2026-11-05 16:54 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: be768a7d7a4beb301a85de3f8d44e0df7fab6646
  • Latest commit, not reviewed: 275c211e52

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.

Walkthrough

The pull request updates graphics diagnostics, dirty tracking, cache collection, rendering, and Vulkan setup. Shader translation gains non-fatal failure reporting and realtime-clock support. AMPR adds guest path decoding, asynchronous command submission, and execution of wait, counter, and mapping commands. Guest APIs change ATRAC9 input buffering, progress-bar dialog status, and legacy save discovery. Host fatal reports can include Windows stack details.

Suggested reviewers: nmzik

Change: Bug fix

Merge Risk: High · up to be768

The change is not ready to merge: affected games can hang or crash, and memory-mapping and graphics paths still have material correctness risks. Fix the high-impact failures before merging.

Security architecture risk: Moderate · up to be768

Memory-pressure cleanup can now write tiled images back to guest memory and allocate a staging buffer sized to an image. The first such writeback can exceed the per-frame budget. Existing image and memory checks remain in place; whether a guest can create an image large enough to cause material resource pressure is unresolved.

Retained concerns

  • Medium · security · inferred: Under memory pressure, the first safely downloadable tiled image is exempt from the 256 MiB writeback check. If an eligible guest-derived image can exceed that size, collection can allocate a correspondingly large dedicated staging buffer at a time of existing memory pressure. The reachable image-size bound and resulting availability impact remain unverified.
Security review details

Security Blast Radius

  • inferred — Guest GPU work can indirectly trigger host-renderer collection, so the plausible resource impact is the local emulator and its GPU process. No cross-process or tenant reachability was established.

Trust Boundaries and Controls

  • observed — The examined path retains guest-range validation and image-download eligibility checks; the changed staging-buffer selection does not itself permit an arbitrary guest address or cache image to be supplied to collection.

Resilience and Maintainability Implications

  • observed — A failed dedicated-buffer mapping or guest-backing read returns before writeback is scheduled; collection skips freeing an image when its required safe download fails.

Hardening Proposals

  • proposed — Establish the maximum eligible tiled-image size and document whether an oversized first writeback is an intentional progress exception. If the budget is meant to be a hard resource limit, handle oversized images without allocating beyond it during pressured collection.
Pre-merge checks: Passed 4

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 names a multi-area change (recompiler, PM4, cache and diagnostics fixes). The changeset covers shader recompiler, command processor, renderer and cache, Vulkan, video out, dialog, and diagno…
Description check Passed The description states the goal (Spider-Man: Miles Morales boots and is playable), lists the topic commits, and describes the shader recompiler, renderer, cache, Vulkan, video out, dialog, and diagnos…
Full details: Title check

Explanation

The title names a multi-area change (recompiler, PM4, cache and diagnostics fixes). The changeset covers shader recompiler, command processor, renderer and cache, Vulkan, video out, dialog, and diagnostics work. The title is partially related: it reflects real parts of the change but is broad and lists many areas instead of one primary change. It is not vague or off-topic, so it passes.

Full details: Description check

Explanation

The description states the goal (Spider-Man: Miles Morales boots and is playable), lists the topic commits, and describes the shader recompiler, renderer, cache, Vulkan, video out, dialog, and diagnostics work. These match the changeset, so the description is related and passes.

Tip

🎯 Customize your risk assessments

Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.

✅ Automatic approvals, with your rules

Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.

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

ℹ️ Recent review info

⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: c1846a4c-b666-4bf2-9a42-6a3f3489fda6

📥 Commits

Reviewing files that changed from the base of the PR and between 508adebfaec9dd1ccfcca7a1dff98f00429008fd and be768a7d7a4beb301a85de3f8d44e0df7fab6646.

📒 Files selected for processing (6)

  • CMakeLists.txt
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/presentation/window/swapchain.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.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-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#issuecomment-5784755002) · edited 2026-11-05 16:54 UTC <!-- coderabbit-ai-generated:v1 --> <!-- 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/780"><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: be768a7d7a4beb301a85de3f8d44e0df7fab6646 > - Latest commit, not reviewed: 275c211e52f0a7825a0bd1e41b1d7c953871735d > > 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_status_start --> No actionable comments were generated in the recent review. <!-- recent_review_status_end --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> <br> The pull request updates graphics diagnostics, dirty tracking, cache collection, rendering, and Vulkan setup. Shader translation gains non-fatal failure reporting and realtime-clock support. AMPR adds guest path decoding, asynchronous command submission, and execution of wait, counter, and mapping commands. Guest APIs change ATRAC9 input buffering, progress-bar dialog status, and legacy save discovery. Host fatal reports can include Windows stack details. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} --> <!-- change_assessment_commit:"be768a7d7a4beb301a85de3f8d44e0df7fab6646" --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-high-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> High</strong> · up to <code>be768</code></summary> <dl> <dd> <br> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** _🟠 High_ · up to `be768` --> <!-- final_review_risk_coverage:{"sourceCommitId":"be768a7d7a4beb301a85de3f8d44e0df7fab6646","coveredCommitId":"be768a7d7a4beb301a85de3f8d44e0df7fab6646","kind":"reviewed"} --> The change is not ready to merge: affected games can hang or crash, and memory-mapping and graphics paths still have material correctness risks. Fix the high-impact failures before merging. <!-- final_review_risk_end --> </dd> </dl> </details> <details> <summary><strong>Security architecture risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-normal-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Moderate</strong> · up to <code>be768</code></summary> <dl> <dd> <br> <!-- architecture_review_start --> <!-- architecture_review_label ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `be768` --> Memory-pressure cleanup can now write tiled images back to guest memory and allocate a staging buffer sized to an image. The first such writeback can exceed the per-frame budget. Existing image and memory checks remain in place; whether a guest can create an image large enough to cause material resource pressure is unresolved. **Retained concerns** - **Medium · security · inferred:** Under memory pressure, the first safely downloadable tiled image is exempt from the 256 MiB writeback check. If an eligible guest-derived image can exceed that size, collection can allocate a correspondingly large dedicated staging buffer at a time of existing memory pressure. The reachable image-size bound and resulting availability impact remain unverified. <details> <summary><strong>Security review details</strong></summary> <dl> <dd> <br> **Security Blast Radius** - _inferred_ — Guest GPU work can indirectly trigger host-renderer collection, so the plausible resource impact is the local emulator and its GPU process. No cross-process or tenant reachability was established. **Trust Boundaries and Controls** - _observed_ — The examined path retains guest-range validation and image-download eligibility checks; the changed staging-buffer selection does not itself permit an arbitrary guest address or cache image to be supplied to collection. **Resilience and Maintainability Implications** - _observed_ — A failed dedicated-buffer mapping or guest-backing read returns before writeback is scheduled; collection skips freeing an image when its required safe download fails. **Hardening Proposals** - _proposed_ — Establish the maximum eligible tiled-image size and document whether an oversized first writeback is an intentional progress exception. If the budget is meant to be a hard resource limit, handle oversized images without allocating beyond it during pressured collection. </dd> </dl> </details> <!-- architecture_review_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</strong></summary> <dl> <dd> <br> | 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 names a multi-area change (recompiler, PM4, cache and diagnostics fixes). The changeset covers shader recompiler, command processor, renderer and cache, Vulkan, video out, dialog, and diagno… | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description states the goal (Spider-Man: Miles Morales boots and is playable), lists the topic commits, and describes the shader recompiler, renderer, cache, Vulkan, video out, dialog, and diagnos… | <details> <summary><strong>Full details: Title check</strong></summary> <dl> <dd> <br> **Explanation** The title names a multi-area change (recompiler, PM4, cache and diagnostics fixes). The changeset covers shader recompiler, command processor, renderer and cache, Vulkan, video out, dialog, and diagnostics work. The title is partially related: it reflects real parts of the change but is broad and lists many areas instead of one primary change. It is not vague or off-topic, so it passes. </dd> </dl> </details> <details> <summary><strong>Full details: Description check</strong></summary> <dl> <dd> <br> **Explanation** The description states the goal (Spider-Man: Miles Morales boots and is playable), lists the topic commits, and describes the shader recompiler, renderer, cache, Vulkan, video out, dialog, and diagnostics work. These match the changeset, so the description is related and passes. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- announcements_start --> > [!TIP] > <details> > <summary><strong>🎯 Customize your risk assessments</strong></summary> > <dl> > <dd> > <br> > > Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using **Merge Risk Instructions** and **Security Risk Instructions** in your review settings. Security architecture risk assessments require the **Advanced plan or above**. > > </dd> > </dl> > </details> > > <details> > <summary><strong>✅ Automatic approvals, with your rules</strong></summary> > <dl> > <dd> > <br> > > Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable **Automatic approvals** in review settings, with overrides for teams or file paths. > > </dd> > </dl> > </details> <!-- announcements_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=780)! 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> <br> - [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> <!-- tips_end --> <!-- recent_review_start --> <h6> <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <br> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> <br> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `c1846a4c-b666-4bf2-9a42-6a3f3489fda6` </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 508adebfaec9dd1ccfcca7a1dff98f00429008fd and be768a7d7a4beb301a85de3f8d44e0df7fab6646. </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing (6)</strong></summary> <dl> <dd> <br> * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/presentation/window/swapchain.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.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; 7 remain after this review. </dd> </dl> </details> </h6> <!-- recent_review_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/graphics/host_gpu/renderer/cache/bufferCache.cpp line 116 (outdated):

@@ -109,6 +110,15 @@ void BufferCache::DeleteBuffer(BufferId id) {
 }
 
 bool BufferCache::DownloadBufferMemory(Buffer& buffer, uint64_t vaddr, uint64_t size) {
+	const auto capacity = m_download_buffer.Size();
+	bool       any      = false;
+	for (uint64_t offset = 0; offset < size; offset += capacity) {
+		any |= DownloadBufferWindow(buffer, vaddr + offset, std::min(capacity, size - offset));

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Limit each download window by packed staging size.

This loop limits the guest address span to the 32 MiB staging capacity. DownloadBufferWindow aligns each dirty segment to 64 bytes. If a large GPU-dirty buffer contains many short, separated segments, one window can require more than 32 MiB and fail at Map. Split windows using the accumulated aligned copy size, or use staging that can hold that size.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882763) On `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` line 116 (outdated): ```diff @@ -109,6 +110,15 @@ void BufferCache::DeleteBuffer(BufferId id) { } bool BufferCache::DownloadBufferMemory(Buffer& buffer, uint64_t vaddr, uint64_t size) { + const auto capacity = m_download_buffer.Size(); + bool any = false; + for (uint64_t offset = 0; offset < size; offset += capacity) { + any |= DownloadBufferWindow(buffer, vaddr + offset, std::min(capacity, size - offset)); ``` _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ **Limit each download window by packed staging size.** This loop limits the guest address span to the 32 MiB staging capacity. `DownloadBufferWindow` aligns *each* dirty segment to 64 bytes. If a large GPU-dirty buffer contains many short, separated segments, one window can require more than 32 MiB and fail at `Map`. Split windows using the accumulated aligned copy size, or use staging that can hold that size. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:b3d860d65f4161704ba0fd7b --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/graphics/host_gpu/renderer/cache/textureCache.cpp line 2041 (outdated):

@@ -1942,40 +1977,68 @@ void TextureCache::UnmapMemory(uint64_t address, uint64_t size) {
 	}
 }
 
+uint64_t TextureCache::LruClock() const noexcept {
+	return m_graphics.presented_frames.load(std::memory_order_relaxed) + m_gc_tick / 512;
+}
+
 void TextureCache::RunGarbageCollector() {
 	std::scoped_lock lock {m_lock};
-	const uint64_t   tick = m_gc_tick++;
-	if (m_graphics.CanReportMemoryUsage()) {
-		m_total_used_memory = m_graphics.GetDeviceMemoryUsage();
-	}
+	m_gc_tick++;
+	const uint64_t clock = LruClock();
 	if (m_total_used_memory < m_trigger_gc_memory) {
 		return;
 	}
+	if (m_gc_budget_frame != clock) {
+		m_gc_budget_frame       = clock;
+		m_gc_freed_bytes_frame  = 0;
+		m_gc_freed_images_frame = 0;
+		m_gc_written_back_bytes_frame = 0;
+	}
 	const auto collect = [&](bool allow_aggressive) {
-		bool           pressured  = m_total_used_memory >= m_pressure_gc_memory;
-		bool           aggressive = allow_aggressive && m_total_used_memory >= m_critical_gc_memory;
-		const uint64_t age       = std::min<uint64_t>(aggressive ? 160 : pressured ? 80 : 16, tick);
-		size_t         deletions = aggressive ? 40 : pressured ? 20 : 10;
+		bool pressured  = m_total_used_memory >= m_pressure_gc_memory;
+		bool aggressive = allow_aggressive && m_total_used_memory >= m_critical_gc_memory;
+		const uint64_t age = std::min<uint64_t>(aggressive ? 1 : pressured ? 4 : 16, clock);
+		constexpr uint64_t MiB             = 1024 * 1024;
+		constexpr size_t   MaxFreesInFrame = 1024;
+		uint64_t           byte_budget     = 0;
+		size_t             deletions       = 10;
+		if (pressured || aggressive) {
+			const auto threshold = aggressive ? m_critical_gc_memory : m_pressure_gc_memory;
+			const auto excess    = m_total_used_memory - threshold;
+			byte_budget = aggressive ? std::max<uint64_t>(64 * MiB, excess / 4)
+			                         : std::max<uint64_t>(16 * MiB, excess / 8);
+			if (m_gc_freed_bytes_frame >= byte_budget ||
+			    m_gc_freed_images_frame >= MaxFreesInFrame) {
+				return;
+			}
+			deletions = MaxFreesInFrame - m_gc_freed_images_frame;
+		}
+		const size_t         visit_limit = pressured || aggressive ? deletions * 4 : deletions;
 		std::vector<ImageId> candidates;
-		candidates.reserve(deletions);
+		candidates.reserve(std::min<size_t>(visit_limit, 4096));
 		// Deleting depth recursively deletes its stencil association, so finish LRU traversal
 		// first.
-		m_lru_cache.ForEachItemBelow(tick - age, [&](ImageId id) {
+		m_lru_cache.ForEachItemBelow(clock - age, [&](ImageId id) {
 			candidates.push_back(id);
-			return candidates.size() == deletions;
+			return candidates.size() >= visit_limit || candidates.size() >= 4096;
 		});
 		for (const auto id: candidates) {
 			if (deletions == 0) {
 				break;
 			}
-			--deletions;
+			if (!(pressured || aggressive)) {
+				--deletions;
+			}
 			auto owner = m_slot_images.try_get(id);
 			if (owner == nullptr || !owner->registered || owner->depth_id) {
 				continue;
 			}
 			if (owner->IsGpuModified()) {
 				const bool safe = SafeToDownload(*owner);
-				if (safe && owner->info.IsTiled()) {
+				constexpr uint64_t WriteBackPerFrame = 256 * MiB;
+				if (safe && owner->info.IsTiled() &&
+				    (!(pressured || aggressive) ||
+				     m_gc_written_back_bytes_frame >= WriteBackPerFrame)) {

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Check the next tiled writeback against the frame budget.

The guard checks only m_gc_written_back_bytes_frame. If that value is below 256 MiB, a large tiled image proceeds even when its size takes the frame far beyond the limit. DownloadImageMemory can also allocate a dedicated download buffer for that image during memory pressure. Compare the remaining budget with owner->info.data.size before starting the writeback.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882773) On `src/graphics/host_gpu/renderer/cache/textureCache.cpp` line 2041 (outdated): ```diff @@ -1942,40 +1977,68 @@ void TextureCache::UnmapMemory(uint64_t address, uint64_t size) { } } +uint64_t TextureCache::LruClock() const noexcept { + return m_graphics.presented_frames.load(std::memory_order_relaxed) + m_gc_tick / 512; +} + void TextureCache::RunGarbageCollector() { std::scoped_lock lock {m_lock}; - const uint64_t tick = m_gc_tick++; - if (m_graphics.CanReportMemoryUsage()) { - m_total_used_memory = m_graphics.GetDeviceMemoryUsage(); - } + m_gc_tick++; + const uint64_t clock = LruClock(); if (m_total_used_memory < m_trigger_gc_memory) { return; } + if (m_gc_budget_frame != clock) { + m_gc_budget_frame = clock; + m_gc_freed_bytes_frame = 0; + m_gc_freed_images_frame = 0; + m_gc_written_back_bytes_frame = 0; + } const auto collect = [&](bool allow_aggressive) { - bool pressured = m_total_used_memory >= m_pressure_gc_memory; - bool aggressive = allow_aggressive && m_total_used_memory >= m_critical_gc_memory; - const uint64_t age = std::min<uint64_t>(aggressive ? 160 : pressured ? 80 : 16, tick); - size_t deletions = aggressive ? 40 : pressured ? 20 : 10; + bool pressured = m_total_used_memory >= m_pressure_gc_memory; + bool aggressive = allow_aggressive && m_total_used_memory >= m_critical_gc_memory; + const uint64_t age = std::min<uint64_t>(aggressive ? 1 : pressured ? 4 : 16, clock); + constexpr uint64_t MiB = 1024 * 1024; + constexpr size_t MaxFreesInFrame = 1024; + uint64_t byte_budget = 0; + size_t deletions = 10; + if (pressured || aggressive) { + const auto threshold = aggressive ? m_critical_gc_memory : m_pressure_gc_memory; + const auto excess = m_total_used_memory - threshold; + byte_budget = aggressive ? std::max<uint64_t>(64 * MiB, excess / 4) + : std::max<uint64_t>(16 * MiB, excess / 8); + if (m_gc_freed_bytes_frame >= byte_budget || + m_gc_freed_images_frame >= MaxFreesInFrame) { + return; + } + deletions = MaxFreesInFrame - m_gc_freed_images_frame; + } + const size_t visit_limit = pressured || aggressive ? deletions * 4 : deletions; std::vector<ImageId> candidates; - candidates.reserve(deletions); + candidates.reserve(std::min<size_t>(visit_limit, 4096)); // Deleting depth recursively deletes its stencil association, so finish LRU traversal // first. - m_lru_cache.ForEachItemBelow(tick - age, [&](ImageId id) { + m_lru_cache.ForEachItemBelow(clock - age, [&](ImageId id) { candidates.push_back(id); - return candidates.size() == deletions; + return candidates.size() >= visit_limit || candidates.size() >= 4096; }); for (const auto id: candidates) { if (deletions == 0) { break; } - --deletions; + if (!(pressured || aggressive)) { + --deletions; + } auto owner = m_slot_images.try_get(id); if (owner == nullptr || !owner->registered || owner->depth_id) { continue; } if (owner->IsGpuModified()) { const bool safe = SafeToDownload(*owner); - if (safe && owner->info.IsTiled()) { + constexpr uint64_t WriteBackPerFrame = 256 * MiB; + if (safe && owner->info.IsTiled() && + (!(pressured || aggressive) || + m_gc_written_back_bytes_frame >= WriteBackPerFrame)) { ``` _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ **Check the next tiled writeback against the frame budget.** The guard checks only `m_gc_written_back_bytes_frame`. If that value is below 256 MiB, a large tiled image proceeds even when its size takes the frame far beyond the limit. `DownloadImageMemory` can also allocate a dedicated download buffer for that image during memory pressure. Compare the remaining budget with `owner->info.data.size` before starting the writeback. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0786cbb26e403f9950d0ee4c --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp line 626 (outdated):

@@ -616,6 +620,10 @@ void DefineModule(EmitterState& state) {
 		state.builder.RequireCapability(spv::CapabilityInt64);
 		state.builder.RequireCapability(spv::CapabilityInt64Atomics);
 	}
+	if (state.requirements.shader_clock) {
+		state.builder.RequireCapability(spv::CapabilityShaderClockKHR);
+		state.builder.RequireExtension("SPV_KHR_shader_clock");
+	}

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Provide a fallback for devices without shaderDeviceClock.

A shader with S_MEMREALTIME now requires ShaderClockKHR and SPV_KHR_shader_clock. The PR objective states that this path has no fallback when shaderDeviceClock is unavailable. Such devices cannot run pipelines that contain this opcode.

Gate this lowering on the enabled device feature. Add an emulation path or reject the shader before pipeline creation with the existing non-fatal translation flow.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882782) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` line 626 (outdated): ```diff @@ -616,6 +620,10 @@ void DefineModule(EmitterState& state) { state.builder.RequireCapability(spv::CapabilityInt64); state.builder.RequireCapability(spv::CapabilityInt64Atomics); } + if (state.requirements.shader_clock) { + state.builder.RequireCapability(spv::CapabilityShaderClockKHR); + state.builder.RequireExtension("SPV_KHR_shader_clock"); + } ``` _🎯 Functional Correctness_ | _🟠 Major_ | _🏗️ Heavy lift_ **Provide a fallback for devices without `shaderDeviceClock`.** A shader with `S_MEMREALTIME` now requires `ShaderClockKHR` and `SPV_KHR_shader_clock`. The PR objective states that this path has no fallback when `shaderDeviceClock` is unavailable. Such devices cannot run pipelines that contain this opcode. Gate this lowering on the enabled device feature. Add an emulation path or reject the shader before pipeline creation with the existing non-fatal translation flow. <!-- fingerprinting:phantom:poseidon:tapir --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e64ef6f0c540032cb2639802 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 182 (outdated):

@@ -161,14 +169,28 @@ class Tracker {
 		std::array<const Inst*, 8> reads {};
 	};
 
-	[[noreturn]] void Fail(uint32_t pc, const std::string& reason) const {
+	void Fail(uint32_t pc, const std::string& reason) const {
 		const auto message =
 		    fmt::format("shader resource tracking: hash=0x{:016x} stage={} pc=0x{:08x} {}",
 		                m_program.shader_hash, StageName(m_program.stage), pc, reason);
+		if (Frontend::TranslationNonFatal()) {
+			if (!m_failed) {
+				LOGF("%s\n", message.c_str());
+			}
+			m_failed = true;
+			return;
+		}

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

A non-fatal Fail now returns into code that assumes it does not return.

Every call site of Fail was written for the old [[noreturn]] contract. In non-fatal mode, Fail returns. ShaderFailureNonFatal() always returns true, so this is the production path. The caller then continues on the state that Fail rejected:

  • GetHandle (Lines 553-558): if handle == nullptr, MakeSource(*handle, ...) dereferences null.
  • MakeSource (Lines 266-273): if NumArgs() != width, handle.Arg(i) reads past the argument list.
  • Collect (Lines 726-732): if flags.index is out of range, m_program.memory_info[flags.index] reads out of bounds. If NumArgs() == 0, later inst.Arg(0) calls are invalid.
  • ValidateAddressHandle (Lines 574-579): if handle is null, handle->NumArgs() dereferences null.
  • Run (Lines 97-102): planning continues after "resources already tracked" and "SRT plan is not ready".

Malformed shader IR can therefore crash the emulator. The unsupported-shader path should skip that shader instead.

Return immediately after each Fail whose following code depends on the rejected condition. For value-returning helpers, return a failure value.

Proposed fix (representative sites)
 		if (m_program.resource_tracking_complete) {
 			Fail(0, "resources already tracked");
+			return;
 		}
 		if (!m_program.srt_plan_complete) {
 			Fail(0, "SRT plan is not ready");
+			return;
 		}
 		if (handle.NumArgs() != width) {
 			Fail(pc, ...);
+			return;
 		}
 		if (handle == nullptr || handle->GetOpcode() != expected) {
 			Fail(pc, fmt::format("memory operation requires {}", ValueOpcodeName(expected)));
+			return false;
 		}
 		DescriptorSource descriptor;
 		MakeSource(*handle, width, sampler, sample_adjust, descriptor, pc);
+		if (m_failed) {
+			return false;
+		}
 		if (flags.index >= m_program.memory_info.size()) {
 			Fail(flags.pc, ...);
+			return;
 		}
 		if (inst.NumArgs() == 0) {
 			Fail(flags.pc, "memory operation has no resource handle");
+			return;
 		}
 		if (handle == nullptr || handle->GetOpcode() != ValueOpcode::GetAddressResource) {
 			Fail(pc, "address operation requires GetAddressResource");
+			return;
 		}

The image and sampler GetHandle calls in Collect ignore the return value. Add if (m_failed) return; after each of those calls.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882787) On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 182 (outdated): ```diff @@ -161,14 +169,28 @@ class Tracker { std::array<const Inst*, 8> reads {}; }; - [[noreturn]] void Fail(uint32_t pc, const std::string& reason) const { + void Fail(uint32_t pc, const std::string& reason) const { const auto message = fmt::format("shader resource tracking: hash=0x{:016x} stage={} pc=0x{:08x} {}", m_program.shader_hash, StageName(m_program.stage), pc, reason); + if (Frontend::TranslationNonFatal()) { + if (!m_failed) { + LOGF("%s\n", message.c_str()); + } + m_failed = true; + return; + } ``` _🩺 Stability & Availability_ | _🔴 Critical_ | _⚡ Quick win_ **A non-fatal `Fail` now returns into code that assumes it does not return.** Every call site of `Fail` was written for the old `[[noreturn]]` contract. In non-fatal mode, `Fail` returns. `ShaderFailureNonFatal()` always returns true, so this is the production path. The caller then continues on the state that `Fail` rejected: - `GetHandle` (Lines 553-558): if `handle == nullptr`, `MakeSource(*handle, ...)` dereferences null. - `MakeSource` (Lines 266-273): if `NumArgs() != width`, `handle.Arg(i)` reads past the argument list. - `Collect` (Lines 726-732): if `flags.index` is out of range, `m_program.memory_info[flags.index]` reads out of bounds. If `NumArgs() == 0`, later `inst.Arg(0)` calls are invalid. - `ValidateAddressHandle` (Lines 574-579): if `handle` is null, `handle->NumArgs()` dereferences null. - `Run` (Lines 97-102): planning continues after "resources already tracked" and "SRT plan is not ready". Malformed shader IR can therefore crash the emulator. The unsupported-shader path should skip that shader instead. Return immediately after each `Fail` whose following code depends on the rejected condition. For value-returning helpers, return a failure value. <details> <summary>Proposed fix (representative sites)</summary> ```diff if (m_program.resource_tracking_complete) { Fail(0, "resources already tracked"); + return; } if (!m_program.srt_plan_complete) { Fail(0, "SRT plan is not ready"); + return; } ``` ```diff if (handle.NumArgs() != width) { Fail(pc, ...); + return; } ``` ```diff if (handle == nullptr || handle->GetOpcode() != expected) { Fail(pc, fmt::format("memory operation requires {}", ValueOpcodeName(expected))); + return false; } DescriptorSource descriptor; MakeSource(*handle, width, sampler, sample_adjust, descriptor, pc); + if (m_failed) { + return false; + } ``` ```diff if (flags.index >= m_program.memory_info.size()) { Fail(flags.pc, ...); + return; } if (inst.NumArgs() == 0) { Fail(flags.pc, "memory operation has no resource handle"); + return; } ``` ```diff if (handle == nullptr || handle->GetOpcode() != ValueOpcode::GetAddressResource) { Fail(pc, "address operation requires GetAddressResource"); + return; } ``` The image and sampler `GetHandle` calls in `Collect` ignore the return value. Add `if (m_failed) return;` after each of those calls. </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:496a5c5a2530d61f2e006352 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp line 207 (outdated):

@@ -0,0 +1,806 @@
+// Compiles a ResourcePlan's reachable SRT expression graph into a flat, topologically-ordered
+// CompiledSrtProgram once per unique shader, so per-draw evaluation (SrtExecution) indexes a
+// flat array instead of SrtWalker.cpp's Evaluator re-walking the same Inst graph, node by node,
+// on every single draw.
+//
+// This file is a deliberately case-by-case port of Evaluator::EvaluateInst/EvaluateRawRead/
+// EvaluateExtract (SrtWalker.cpp) split into two halves per opcode: a Compile-time half (this
+// file's Compiler class) that resolves everything structural/static once -- operand slots,
+// MemoryFlags, SRT slot indices, component indices, the "is this SRT slot clean" flag -- and an
+// execute-time half (SrtExecution) that does only the genuinely runtime-dependent work
+// (user_data lookups, guest memory reads, and the arithmetic itself). Every case here should be
+// read side-by-side with its EvaluateInst counterpart; anything that doesn't map cleanly compiles
+// to AlwaysFails rather than guessing, matching EvaluateInst's own `default: break;`.
+//
+// Only opcodes SrtWalker.cpp's own Evaluator actually resolves are handled here (e.g. no
+// CompositeExtractU32x4/BitCount32/FindILsb32/FindUMsb32 -- this codebase's Evaluator has no
+// cases for them either, so they already compile to AlwaysFails via the default path, matching
+// the interpreter exactly). SelectU32/U1/F32 gets its own CompiledOpKind rather than folding into
+// the generic arithmetic dispatch: this codebase's Select resolves its predicate through the
+// clean pass (when one is available) and only evaluates the branch it actually selects, unlike a
+// plain eager ternary -- see CompiledOpKind::Select's case in SrtExecution::Evaluate below.
+//
+// Two facts from ExtractResourcePlan (ResourceMaterialization.cpp) shape this compiler:
+//   - Its Clone lambda already resolves every Phi to its invariant value or leaves it unreachable,
+//     so any Phi that still appears in a ResourcePlan's value_storage is provably non-invariant.
+//     No runtime Phi-resolution logic is needed here at all -- see CompiledOpKind::AlwaysFails.
+//   - CompositeConstructU32x2 and IAddCarry32 are never given their own EvaluateInst case -- they
+//     are only ever reached through CompositeExtractU32x2's special-casing, which reads directly
+//     through them without evaluating the construct/carry node as its own value. This compiler
+//     mirrors that with ExtractPassthrough/ExtractCarryHalf, so a construct or carry node reached
+//     any other way still compiles to AlwaysFails, exactly like today's `default: break;`.
+#include "graphics/shader/recompiler/ir/passes/SrtCompiler.h"
+
+#include "common/assert.h"
+#include "common/profiler.h"
+#include "graphics/shader/recompiler/ir/ShaderIR.h"
+
+#include <algorithm>
+#include <array>
+#include <bit>
+#include <cmath>
+#include <cstring>
+#include <deque>
+#include <unordered_map>
+
+namespace Libs::Graphics::ShaderRecompiler::IR {
+namespace {
+
+constexpr uint64_t AddressMask = 0x0000ffffffffffffull;
+
+// Sentinel stored in m_slot_for_inst while an Inst's operands are still being compiled, so a
+// genuine cycle (should be impossible post-Phi-elimination, but never trust that blindly) fails
+// closed as AlwaysFails instead of infinitely recursing.
+constexpr uint32_t kInProgressSlot = UINT32_MAX - 1;
+
+bool IsRawReadOpcode(const ResourcePlan& program, const Inst& inst) {
+	const auto op = inst.GetOpcode();
+	if (op != ValueOpcode::LoadAddressU32 && op != ValueOpcode::ReadConstBuffer) {
+		return false;
+	}
+	const auto index = inst.Flags<MemoryFlags>().index;
+	if (index >= program.memory_info.size()) {
+		return false;
+	}
+	const auto kind = program.memory_info[index].kind;
+	return (op == ValueOpcode::LoadAddressU32 && kind == ResourceKind::ScalarAddress) ||
+	       (op == ValueOpcode::ReadConstBuffer && kind == ResourceKind::ScalarBuffer);
+}
+
+class Compiler {
+public:
+	explicit Compiler(const ResourcePlan& program): m_program(program) {}
+
+	CompiledSrtProgram Run() {
+		CompiledSrtProgram result;
+		result.descriptor_source_slots.resize(m_program.descriptor_sources.size());
+		for (size_t i = 0; i < m_program.descriptor_sources.size(); i++) {
+			const auto& source = m_program.descriptor_sources[i];
+			for (uint32_t d = 0; d < source.dword_count; d++) {
+				result.descriptor_source_slots[i][d] = CompileValue(source.dwords[d]);
+			}
+		}
+		result.srt_read_slots.resize(m_program.srt_reads.size());
+		for (size_t i = 0; i < m_program.srt_reads.size(); i++) {
+			result.srt_read_slots[i] = CompileValue(m_program.srt_reads[i].value);
+		}
+		result.control_flow_condition_slots.resize(m_program.control_flow.size());
+		for (size_t i = 0; i < m_program.control_flow.size(); i++) {
+			const auto& condition = m_program.control_flow[i].condition;
+			result.control_flow_condition_slots[i] =
+			    condition.IsEmpty() ? kInvalidSlot : CompileValue(condition);
+		}
+		result.ops = std::move(m_ops);
+		return result;
+	}
+
+private:
+	static CompiledOp AlwaysFailsOp() {
+		CompiledOp op;
+		op.kind = CompiledOpKind::AlwaysFails;
+		return op;
+	}
+
+	// Post-order: every operand this node references is compiled (and therefore already has a
+	// lower slot index in m_ops) before this node's own CompiledOp is appended.
+	uint32_t CompileValue(Value value) {
+		value = value.Resolve();
+		if (value.IsImmediate()) {
+			return EmitConstant(value);
+		}
+		auto* inst = value.TryInstruction();
+		if (inst == nullptr) {
+			return EmitOp(AlwaysFailsOp());
+		}
+		if (const auto it = m_slot_for_inst.find(inst); it != m_slot_for_inst.end()) {
+			if (it->second == kInProgressSlot) {
+				return EmitOp(AlwaysFailsOp());
+			}
+			return it->second;
+		}
+		m_slot_for_inst.emplace(inst, kInProgressSlot);
+		auto       op          = CompileInst(*inst);
+		const auto slot        = EmitOp(std::move(op));
+		m_slot_for_inst[inst] = slot;
+		return slot;
+	}
+
+	uint32_t EmitOp(CompiledOp op) {
+		m_ops.push_back(std::move(op));
+		return static_cast<uint32_t>(m_ops.size() - 1);
+	}
+
+	uint32_t EmitConstant(Value value) {
+		CompiledOp op;
+		op.kind = CompiledOpKind::Constant;
+		switch (value.GetType()) {
+			case Type::U1: op.immediate = value.U1(); break;
+			case Type::U8: op.immediate = value.U8(); break;
+			case Type::U16: op.immediate = value.U16(); break;
+			case Type::U32: op.immediate = value.U32(); break;
+			case Type::U64: op.immediate = value.U64(); break;
+			case Type::F32: op.immediate = std::bit_cast<uint32_t>(value.F32Value()); break;
+			default: return EmitOp(AlwaysFailsOp());
+		}
+		return EmitOp(std::move(op));
+	}
+
+	// Mirrors Evaluator::EvaluateInst case-by-case -- see this file's header comment.
+	CompiledOp CompileInst(const Inst& inst) {
+		const auto opcode = inst.GetOpcode();
+		switch (opcode) {
+			case ValueOpcode::GetUserData: {
+				if (inst.NumArgs() != 1 || inst.Arg(0).GetType() != Type::ScalarReg) {
+					return AlwaysFailsOp();
+				}
+				const auto reg = RegIndex(inst.Arg(0).ScalarRegister());
+				if (reg < m_program.user_data_base) {
+					return AlwaysFailsOp();
+				}
+				CompiledOp op;
+				op.kind      = CompiledOpKind::GetUserData;
+				op.immediate = reg - m_program.user_data_base;
+				return op;
+			}
+			case ValueOpcode::GetShaderBase: {
+				CompiledOp op;
+				op.kind = CompiledOpKind::GetShaderBase;
+				return op;
+			}
+			case ValueOpcode::Phi:
+				// Provably non-invariant -- see this file's header comment.
+				return AlwaysFailsOp();
+			case ValueOpcode::ReadFirstLane: {
+				if (inst.NumArgs() != 2) {
+					return AlwaysFailsOp();
+				}
+				CompiledOp op;
+				op.kind         = CompiledOpKind::ReadFirstLane;
+				op.num_operands = 2;
+				op.operands[0]  = CompileValue(inst.Arg(0));
+				op.operands[1]  = CompileValue(inst.Arg(1));
+				return op;
+			}
+			case ValueOpcode::BitCastU32F32:
+			case ValueOpcode::BitCastF32U32:
+				return GenericUnary(inst, opcode);
+			case ValueOpcode::CompositeExtractU64:
+			case ValueOpcode::CompositeExtractU32x2:
+				return CompileExtract(inst, opcode);
+			case ValueOpcode::CompositeConstructU64:
+				return GenericBinary(inst, opcode);
+			case ValueOpcode::ReadConst: {
+				if (inst.NumArgs() != 2) {
+					return AlwaysFailsOp();
+				}
+				const auto slot = inst.Arg(1).Resolve();
+				if (!slot.IsImmediate() || slot.GetType() != Type::U32) {
+					return AlwaysFailsOp();
+				}
+				const auto slot_index = slot.U32();
+				if (slot_index >= m_program.srt_reads.size()) {
+					return AlwaysFailsOp();
+				}
+				CompiledOp op;
+				op.kind           = CompiledOpKind::ReadConst;
+				op.srt_slot_clean = slot_index < m_program.clean_flat_slots.size() &&
+				                    m_program.clean_flat_slots[slot_index] != 0u;

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C4 '\b(WalkSrt|EvaluateDescriptorSources?|EvaluateRuntimeSources)\s*\(' --type=cpp

Repository: KytyPS5/KytyPS5

Length of output: 31493


🏁 Script executed:

rg -n 'SrtExecution' --type=cpp | head -50

Repository: KytyPS5/KytyPS5

Length of output: 3125


🏁 Script executed:

sed -n '1140,1160p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp

Repository: KytyPS5/KytyPS5

Length of output: 930


🏁 Script executed:

sed -n '472,490p' src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp

Repository: KytyPS5/KytyPS5

Length of output: 1281


🏁 Script executed:

sed -n '200,220p' src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp

Repository: KytyPS5/KytyPS5

Length of output: 1000


🏁 Script executed:

sed -n '525,615p' src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4749


🏁 Script executed:

sed -n '1100,1170p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp

Repository: KytyPS5/KytyPS5

Length of output: 3153


🏁 Script executed:

sed -n '1316,1346p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp

Repository: KytyPS5/KytyPS5

Length of output: 1666


🏁 Script executed:

rg -n 'EvaluateRuntimeSourcesCompiled' --type=cpp -B 2 -A 2

Repository: KytyPS5/KytyPS5

Length of output: 2698


🏁 Script executed:

sed -n '1155,1195p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp

Repository: KytyPS5/KytyPS5

Length of output: 1616


🏁 Script executed:

sed -n '1195,1245p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp

Repository: KytyPS5/KytyPS5

Length of output: 2098


🏁 Script executed:

sed -n '1245,1280p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp

Repository: KytyPS5/KytyPS5

Length of output: 2128


The compiled evaluator bakes clean-slot decisions at compile time instead of checking the runtime clean_flat_slots span.

The compiled path stores op.srt_slot_clean from m_program.clean_flat_slots at compile time (SrtCompiler.cpp:205-207). At runtime, SrtExecution::Evaluate uses this baked value (SrtCompiler.cpp:576):

case CompiledOpKind::ReadConst:
    return Demand(clean || op.srt_slot_clean, op.operands[0], result);

The interpreter checks the runtime clean_flat_slots span instead. SrtWalker.cpp:1107-1109 shows:

const bool clean    = read.flat_offset < clean_flat_slots.size() &&
                      clean_flat_slots[read.flat_offset] != 0u;

When WalkSrt or EvaluateDescriptorSources passes an empty clean_flat_slots span (SrtWalker.cpp:1330, 1345), the compiled path reads through read_specialization_memory (if the slot was marked clean at compile time), while the interpreter reads through read_memory. If read_specialization_memory is null, the compiled path fails; in shadow-validation mode, the mismatch exits the program (SrtWalker.cpp:1269-1280).

Store the slot index and check the runtime span during execution, as proposed.

Suggested fix
 				CompiledOp op;
 				op.kind           = CompiledOpKind::ReadConst;
-				op.srt_slot_clean = slot_index < m_program.clean_flat_slots.size() &&
-				                    m_program.clean_flat_slots[slot_index] != 0u;
+				op.immediate      = slot_index; // resolved against the caller's clean_flat_slots

Pass clean_flat_slots into SrtExecution, then evaluate in Evaluate():

case CompiledOpKind::ReadConst: {
	const bool slot_clean = op.immediate < m_clean_flat_slots.size() &&
	                        m_clean_flat_slots[op.immediate] != 0u;
	return Demand(clean || slot_clean, op.operands[0], result);
}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882791) On `src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp` line 207 (outdated): ```diff @@ -0,0 +1,806 @@ +// Compiles a ResourcePlan's reachable SRT expression graph into a flat, topologically-ordered +// CompiledSrtProgram once per unique shader, so per-draw evaluation (SrtExecution) indexes a +// flat array instead of SrtWalker.cpp's Evaluator re-walking the same Inst graph, node by node, +// on every single draw. +// +// This file is a deliberately case-by-case port of Evaluator::EvaluateInst/EvaluateRawRead/ +// EvaluateExtract (SrtWalker.cpp) split into two halves per opcode: a Compile-time half (this +// file's Compiler class) that resolves everything structural/static once -- operand slots, +// MemoryFlags, SRT slot indices, component indices, the "is this SRT slot clean" flag -- and an +// execute-time half (SrtExecution) that does only the genuinely runtime-dependent work +// (user_data lookups, guest memory reads, and the arithmetic itself). Every case here should be +// read side-by-side with its EvaluateInst counterpart; anything that doesn't map cleanly compiles +// to AlwaysFails rather than guessing, matching EvaluateInst's own `default: break;`. +// +// Only opcodes SrtWalker.cpp's own Evaluator actually resolves are handled here (e.g. no +// CompositeExtractU32x4/BitCount32/FindILsb32/FindUMsb32 -- this codebase's Evaluator has no +// cases for them either, so they already compile to AlwaysFails via the default path, matching +// the interpreter exactly). SelectU32/U1/F32 gets its own CompiledOpKind rather than folding into +// the generic arithmetic dispatch: this codebase's Select resolves its predicate through the +// clean pass (when one is available) and only evaluates the branch it actually selects, unlike a +// plain eager ternary -- see CompiledOpKind::Select's case in SrtExecution::Evaluate below. +// +// Two facts from ExtractResourcePlan (ResourceMaterialization.cpp) shape this compiler: +// - Its Clone lambda already resolves every Phi to its invariant value or leaves it unreachable, +// so any Phi that still appears in a ResourcePlan's value_storage is provably non-invariant. +// No runtime Phi-resolution logic is needed here at all -- see CompiledOpKind::AlwaysFails. +// - CompositeConstructU32x2 and IAddCarry32 are never given their own EvaluateInst case -- they +// are only ever reached through CompositeExtractU32x2's special-casing, which reads directly +// through them without evaluating the construct/carry node as its own value. This compiler +// mirrors that with ExtractPassthrough/ExtractCarryHalf, so a construct or carry node reached +// any other way still compiles to AlwaysFails, exactly like today's `default: break;`. +#include "graphics/shader/recompiler/ir/passes/SrtCompiler.h" + +#include "common/assert.h" +#include "common/profiler.h" +#include "graphics/shader/recompiler/ir/ShaderIR.h" + +#include <algorithm> +#include <array> +#include <bit> +#include <cmath> +#include <cstring> +#include <deque> +#include <unordered_map> + +namespace Libs::Graphics::ShaderRecompiler::IR { +namespace { + +constexpr uint64_t AddressMask = 0x0000ffffffffffffull; + +// Sentinel stored in m_slot_for_inst while an Inst's operands are still being compiled, so a +// genuine cycle (should be impossible post-Phi-elimination, but never trust that blindly) fails +// closed as AlwaysFails instead of infinitely recursing. +constexpr uint32_t kInProgressSlot = UINT32_MAX - 1; + +bool IsRawReadOpcode(const ResourcePlan& program, const Inst& inst) { + const auto op = inst.GetOpcode(); + if (op != ValueOpcode::LoadAddressU32 && op != ValueOpcode::ReadConstBuffer) { + return false; + } + const auto index = inst.Flags<MemoryFlags>().index; + if (index >= program.memory_info.size()) { + return false; + } + const auto kind = program.memory_info[index].kind; + return (op == ValueOpcode::LoadAddressU32 && kind == ResourceKind::ScalarAddress) || + (op == ValueOpcode::ReadConstBuffer && kind == ResourceKind::ScalarBuffer); +} + +class Compiler { +public: + explicit Compiler(const ResourcePlan& program): m_program(program) {} + + CompiledSrtProgram Run() { + CompiledSrtProgram result; + result.descriptor_source_slots.resize(m_program.descriptor_sources.size()); + for (size_t i = 0; i < m_program.descriptor_sources.size(); i++) { + const auto& source = m_program.descriptor_sources[i]; + for (uint32_t d = 0; d < source.dword_count; d++) { + result.descriptor_source_slots[i][d] = CompileValue(source.dwords[d]); + } + } + result.srt_read_slots.resize(m_program.srt_reads.size()); + for (size_t i = 0; i < m_program.srt_reads.size(); i++) { + result.srt_read_slots[i] = CompileValue(m_program.srt_reads[i].value); + } + result.control_flow_condition_slots.resize(m_program.control_flow.size()); + for (size_t i = 0; i < m_program.control_flow.size(); i++) { + const auto& condition = m_program.control_flow[i].condition; + result.control_flow_condition_slots[i] = + condition.IsEmpty() ? kInvalidSlot : CompileValue(condition); + } + result.ops = std::move(m_ops); + return result; + } + +private: + static CompiledOp AlwaysFailsOp() { + CompiledOp op; + op.kind = CompiledOpKind::AlwaysFails; + return op; + } + + // Post-order: every operand this node references is compiled (and therefore already has a + // lower slot index in m_ops) before this node's own CompiledOp is appended. + uint32_t CompileValue(Value value) { + value = value.Resolve(); + if (value.IsImmediate()) { + return EmitConstant(value); + } + auto* inst = value.TryInstruction(); + if (inst == nullptr) { + return EmitOp(AlwaysFailsOp()); + } + if (const auto it = m_slot_for_inst.find(inst); it != m_slot_for_inst.end()) { + if (it->second == kInProgressSlot) { + return EmitOp(AlwaysFailsOp()); + } + return it->second; + } + m_slot_for_inst.emplace(inst, kInProgressSlot); + auto op = CompileInst(*inst); + const auto slot = EmitOp(std::move(op)); + m_slot_for_inst[inst] = slot; + return slot; + } + + uint32_t EmitOp(CompiledOp op) { + m_ops.push_back(std::move(op)); + return static_cast<uint32_t>(m_ops.size() - 1); + } + + uint32_t EmitConstant(Value value) { + CompiledOp op; + op.kind = CompiledOpKind::Constant; + switch (value.GetType()) { + case Type::U1: op.immediate = value.U1(); break; + case Type::U8: op.immediate = value.U8(); break; + case Type::U16: op.immediate = value.U16(); break; + case Type::U32: op.immediate = value.U32(); break; + case Type::U64: op.immediate = value.U64(); break; + case Type::F32: op.immediate = std::bit_cast<uint32_t>(value.F32Value()); break; + default: return EmitOp(AlwaysFailsOp()); + } + return EmitOp(std::move(op)); + } + + // Mirrors Evaluator::EvaluateInst case-by-case -- see this file's header comment. + CompiledOp CompileInst(const Inst& inst) { + const auto opcode = inst.GetOpcode(); + switch (opcode) { + case ValueOpcode::GetUserData: { + if (inst.NumArgs() != 1 || inst.Arg(0).GetType() != Type::ScalarReg) { + return AlwaysFailsOp(); + } + const auto reg = RegIndex(inst.Arg(0).ScalarRegister()); + if (reg < m_program.user_data_base) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::GetUserData; + op.immediate = reg - m_program.user_data_base; + return op; + } + case ValueOpcode::GetShaderBase: { + CompiledOp op; + op.kind = CompiledOpKind::GetShaderBase; + return op; + } + case ValueOpcode::Phi: + // Provably non-invariant -- see this file's header comment. + return AlwaysFailsOp(); + case ValueOpcode::ReadFirstLane: { + if (inst.NumArgs() != 2) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::ReadFirstLane; + op.num_operands = 2; + op.operands[0] = CompileValue(inst.Arg(0)); + op.operands[1] = CompileValue(inst.Arg(1)); + return op; + } + case ValueOpcode::BitCastU32F32: + case ValueOpcode::BitCastF32U32: + return GenericUnary(inst, opcode); + case ValueOpcode::CompositeExtractU64: + case ValueOpcode::CompositeExtractU32x2: + return CompileExtract(inst, opcode); + case ValueOpcode::CompositeConstructU64: + return GenericBinary(inst, opcode); + case ValueOpcode::ReadConst: { + if (inst.NumArgs() != 2) { + return AlwaysFailsOp(); + } + const auto slot = inst.Arg(1).Resolve(); + if (!slot.IsImmediate() || slot.GetType() != Type::U32) { + return AlwaysFailsOp(); + } + const auto slot_index = slot.U32(); + if (slot_index >= m_program.srt_reads.size()) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::ReadConst; + op.srt_slot_clean = slot_index < m_program.clean_flat_slots.size() && + m_program.clean_flat_slots[slot_index] != 0u; ``` _🎯 Functional Correctness_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C4 '\b(WalkSrt|EvaluateDescriptorSources?|EvaluateRuntimeSources)\s*\(' --type=cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 31493 --- 🏁 Script executed: ```bash rg -n 'SrtExecution' --type=cpp | head -50 ``` Repository: KytyPS5/KytyPS5 Length of output: 3125 --- 🏁 Script executed: ```bash sed -n '1140,1160p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 930 --- 🏁 Script executed: ```bash sed -n '472,490p' src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 1281 --- 🏁 Script executed: ```bash sed -n '200,220p' src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 1000 --- 🏁 Script executed: ```bash sed -n '525,615p' src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4749 --- 🏁 Script executed: ```bash sed -n '1100,1170p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 3153 --- 🏁 Script executed: ```bash sed -n '1316,1346p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 1666 --- 🏁 Script executed: ```bash rg -n 'EvaluateRuntimeSourcesCompiled' --type=cpp -B 2 -A 2 ``` Repository: KytyPS5/KytyPS5 Length of output: 2698 --- 🏁 Script executed: ```bash sed -n '1155,1195p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 1616 --- 🏁 Script executed: ```bash sed -n '1195,1245p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 2098 --- 🏁 Script executed: ```bash sed -n '1245,1280p' src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 2128 --- </details> **The compiled evaluator bakes clean-slot decisions at compile time instead of checking the runtime `clean_flat_slots` span.** The compiled path stores `op.srt_slot_clean` from `m_program.clean_flat_slots` at compile time (SrtCompiler.cpp:205-207). At runtime, `SrtExecution::Evaluate` uses this baked value (SrtCompiler.cpp:576): ```cpp case CompiledOpKind::ReadConst: return Demand(clean || op.srt_slot_clean, op.operands[0], result); ``` The interpreter checks the runtime `clean_flat_slots` span instead. SrtWalker.cpp:1107-1109 shows: ```cpp const bool clean = read.flat_offset < clean_flat_slots.size() && clean_flat_slots[read.flat_offset] != 0u; ``` When `WalkSrt` or `EvaluateDescriptorSources` passes an empty `clean_flat_slots` span (SrtWalker.cpp:1330, 1345), the compiled path reads through `read_specialization_memory` (if the slot was marked clean at compile time), while the interpreter reads through `read_memory`. If `read_specialization_memory` is null, the compiled path fails; in shadow-validation mode, the mismatch exits the program (SrtWalker.cpp:1269-1280). Store the slot index and check the runtime span during execution, as proposed. <details> <summary>Suggested fix</summary> ```diff CompiledOp op; op.kind = CompiledOpKind::ReadConst; - op.srt_slot_clean = slot_index < m_program.clean_flat_slots.size() && - m_program.clean_flat_slots[slot_index] != 0u; + op.immediate = slot_index; // resolved against the caller's clean_flat_slots ``` Pass `clean_flat_slots` into `SrtExecution`, then evaluate in `Evaluate()`: ```cpp case CompiledOpKind::ReadConst: { const bool slot_clean = op.immediate < m_clean_flat_slots.size() && m_clean_flat_slots[op.immediate] != 0u; return Demand(clean || slot_clean, op.operands[0], result); } ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d1302266ccbb574a62dca7a2 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp line 248 (outdated):

@@ -0,0 +1,806 @@
+// Compiles a ResourcePlan's reachable SRT expression graph into a flat, topologically-ordered
+// CompiledSrtProgram once per unique shader, so per-draw evaluation (SrtExecution) indexes a
+// flat array instead of SrtWalker.cpp's Evaluator re-walking the same Inst graph, node by node,
+// on every single draw.
+//
+// This file is a deliberately case-by-case port of Evaluator::EvaluateInst/EvaluateRawRead/
+// EvaluateExtract (SrtWalker.cpp) split into two halves per opcode: a Compile-time half (this
+// file's Compiler class) that resolves everything structural/static once -- operand slots,
+// MemoryFlags, SRT slot indices, component indices, the "is this SRT slot clean" flag -- and an
+// execute-time half (SrtExecution) that does only the genuinely runtime-dependent work
+// (user_data lookups, guest memory reads, and the arithmetic itself). Every case here should be
+// read side-by-side with its EvaluateInst counterpart; anything that doesn't map cleanly compiles
+// to AlwaysFails rather than guessing, matching EvaluateInst's own `default: break;`.
+//
+// Only opcodes SrtWalker.cpp's own Evaluator actually resolves are handled here (e.g. no
+// CompositeExtractU32x4/BitCount32/FindILsb32/FindUMsb32 -- this codebase's Evaluator has no
+// cases for them either, so they already compile to AlwaysFails via the default path, matching
+// the interpreter exactly). SelectU32/U1/F32 gets its own CompiledOpKind rather than folding into
+// the generic arithmetic dispatch: this codebase's Select resolves its predicate through the
+// clean pass (when one is available) and only evaluates the branch it actually selects, unlike a
+// plain eager ternary -- see CompiledOpKind::Select's case in SrtExecution::Evaluate below.
+//
+// Two facts from ExtractResourcePlan (ResourceMaterialization.cpp) shape this compiler:
+//   - Its Clone lambda already resolves every Phi to its invariant value or leaves it unreachable,
+//     so any Phi that still appears in a ResourcePlan's value_storage is provably non-invariant.
+//     No runtime Phi-resolution logic is needed here at all -- see CompiledOpKind::AlwaysFails.
+//   - CompositeConstructU32x2 and IAddCarry32 are never given their own EvaluateInst case -- they
+//     are only ever reached through CompositeExtractU32x2's special-casing, which reads directly
+//     through them without evaluating the construct/carry node as its own value. This compiler
+//     mirrors that with ExtractPassthrough/ExtractCarryHalf, so a construct or carry node reached
+//     any other way still compiles to AlwaysFails, exactly like today's `default: break;`.
+#include "graphics/shader/recompiler/ir/passes/SrtCompiler.h"
+
+#include "common/assert.h"
+#include "common/profiler.h"
+#include "graphics/shader/recompiler/ir/ShaderIR.h"
+
+#include <algorithm>
+#include <array>
+#include <bit>
+#include <cmath>
+#include <cstring>
+#include <deque>
+#include <unordered_map>
+
+namespace Libs::Graphics::ShaderRecompiler::IR {
+namespace {
+
+constexpr uint64_t AddressMask = 0x0000ffffffffffffull;
+
+// Sentinel stored in m_slot_for_inst while an Inst's operands are still being compiled, so a
+// genuine cycle (should be impossible post-Phi-elimination, but never trust that blindly) fails
+// closed as AlwaysFails instead of infinitely recursing.
+constexpr uint32_t kInProgressSlot = UINT32_MAX - 1;
+
+bool IsRawReadOpcode(const ResourcePlan& program, const Inst& inst) {
+	const auto op = inst.GetOpcode();
+	if (op != ValueOpcode::LoadAddressU32 && op != ValueOpcode::ReadConstBuffer) {
+		return false;
+	}
+	const auto index = inst.Flags<MemoryFlags>().index;
+	if (index >= program.memory_info.size()) {
+		return false;
+	}
+	const auto kind = program.memory_info[index].kind;
+	return (op == ValueOpcode::LoadAddressU32 && kind == ResourceKind::ScalarAddress) ||
+	       (op == ValueOpcode::ReadConstBuffer && kind == ResourceKind::ScalarBuffer);
+}
+
+class Compiler {
+public:
+	explicit Compiler(const ResourcePlan& program): m_program(program) {}
+
+	CompiledSrtProgram Run() {
+		CompiledSrtProgram result;
+		result.descriptor_source_slots.resize(m_program.descriptor_sources.size());
+		for (size_t i = 0; i < m_program.descriptor_sources.size(); i++) {
+			const auto& source = m_program.descriptor_sources[i];
+			for (uint32_t d = 0; d < source.dword_count; d++) {
+				result.descriptor_source_slots[i][d] = CompileValue(source.dwords[d]);
+			}
+		}
+		result.srt_read_slots.resize(m_program.srt_reads.size());
+		for (size_t i = 0; i < m_program.srt_reads.size(); i++) {
+			result.srt_read_slots[i] = CompileValue(m_program.srt_reads[i].value);
+		}
+		result.control_flow_condition_slots.resize(m_program.control_flow.size());
+		for (size_t i = 0; i < m_program.control_flow.size(); i++) {
+			const auto& condition = m_program.control_flow[i].condition;
+			result.control_flow_condition_slots[i] =
+			    condition.IsEmpty() ? kInvalidSlot : CompileValue(condition);
+		}
+		result.ops = std::move(m_ops);
+		return result;
+	}
+
+private:
+	static CompiledOp AlwaysFailsOp() {
+		CompiledOp op;
+		op.kind = CompiledOpKind::AlwaysFails;
+		return op;
+	}
+
+	// Post-order: every operand this node references is compiled (and therefore already has a
+	// lower slot index in m_ops) before this node's own CompiledOp is appended.
+	uint32_t CompileValue(Value value) {
+		value = value.Resolve();
+		if (value.IsImmediate()) {
+			return EmitConstant(value);
+		}
+		auto* inst = value.TryInstruction();
+		if (inst == nullptr) {
+			return EmitOp(AlwaysFailsOp());
+		}
+		if (const auto it = m_slot_for_inst.find(inst); it != m_slot_for_inst.end()) {
+			if (it->second == kInProgressSlot) {
+				return EmitOp(AlwaysFailsOp());
+			}
+			return it->second;
+		}
+		m_slot_for_inst.emplace(inst, kInProgressSlot);
+		auto       op          = CompileInst(*inst);
+		const auto slot        = EmitOp(std::move(op));
+		m_slot_for_inst[inst] = slot;
+		return slot;
+	}
+
+	uint32_t EmitOp(CompiledOp op) {
+		m_ops.push_back(std::move(op));
+		return static_cast<uint32_t>(m_ops.size() - 1);
+	}
+
+	uint32_t EmitConstant(Value value) {
+		CompiledOp op;
+		op.kind = CompiledOpKind::Constant;
+		switch (value.GetType()) {
+			case Type::U1: op.immediate = value.U1(); break;
+			case Type::U8: op.immediate = value.U8(); break;
+			case Type::U16: op.immediate = value.U16(); break;
+			case Type::U32: op.immediate = value.U32(); break;
+			case Type::U64: op.immediate = value.U64(); break;
+			case Type::F32: op.immediate = std::bit_cast<uint32_t>(value.F32Value()); break;
+			default: return EmitOp(AlwaysFailsOp());
+		}
+		return EmitOp(std::move(op));
+	}
+
+	// Mirrors Evaluator::EvaluateInst case-by-case -- see this file's header comment.
+	CompiledOp CompileInst(const Inst& inst) {
+		const auto opcode = inst.GetOpcode();
+		switch (opcode) {
+			case ValueOpcode::GetUserData: {
+				if (inst.NumArgs() != 1 || inst.Arg(0).GetType() != Type::ScalarReg) {
+					return AlwaysFailsOp();
+				}
+				const auto reg = RegIndex(inst.Arg(0).ScalarRegister());
+				if (reg < m_program.user_data_base) {
+					return AlwaysFailsOp();
+				}
+				CompiledOp op;
+				op.kind      = CompiledOpKind::GetUserData;
+				op.immediate = reg - m_program.user_data_base;
+				return op;
+			}
+			case ValueOpcode::GetShaderBase: {
+				CompiledOp op;
+				op.kind = CompiledOpKind::GetShaderBase;
+				return op;
+			}
+			case ValueOpcode::Phi:
+				// Provably non-invariant -- see this file's header comment.
+				return AlwaysFailsOp();
+			case ValueOpcode::ReadFirstLane: {
+				if (inst.NumArgs() != 2) {
+					return AlwaysFailsOp();
+				}
+				CompiledOp op;
+				op.kind         = CompiledOpKind::ReadFirstLane;
+				op.num_operands = 2;
+				op.operands[0]  = CompileValue(inst.Arg(0));
+				op.operands[1]  = CompileValue(inst.Arg(1));
+				return op;
+			}
+			case ValueOpcode::BitCastU32F32:
+			case ValueOpcode::BitCastF32U32:
+				return GenericUnary(inst, opcode);
+			case ValueOpcode::CompositeExtractU64:
+			case ValueOpcode::CompositeExtractU32x2:
+				return CompileExtract(inst, opcode);
+			case ValueOpcode::CompositeConstructU64:
+				return GenericBinary(inst, opcode);
+			case ValueOpcode::ReadConst: {
+				if (inst.NumArgs() != 2) {
+					return AlwaysFailsOp();
+				}
+				const auto slot = inst.Arg(1).Resolve();
+				if (!slot.IsImmediate() || slot.GetType() != Type::U32) {
+					return AlwaysFailsOp();
+				}
+				const auto slot_index = slot.U32();
+				if (slot_index >= m_program.srt_reads.size()) {
+					return AlwaysFailsOp();
+				}
+				CompiledOp op;
+				op.kind           = CompiledOpKind::ReadConst;
+				op.srt_slot_clean = slot_index < m_program.clean_flat_slots.size() &&
+				                    m_program.clean_flat_slots[slot_index] != 0u;
+				op.num_operands = 1;
+				// The SRT read's own value graph -- compiled once here (shared with anyone else
+				// referencing the same srt_reads[slot_index], since CompileValue dedupes by Inst*
+				// either way).
+				op.operands[0] = CompileValue(m_program.srt_reads[slot_index].value);
+				return op;
+			}
+			case ValueOpcode::LoadAddressU32:
+			case ValueOpcode::ReadConstBuffer:
+				if (IsRawReadOpcode(m_program, inst)) {
+					return CompileRawRead(inst, opcode);
+				}
+				return AlwaysFailsOp();
+			case ValueOpcode::IAdd32:
+			case ValueOpcode::IAdd64:
+			case ValueOpcode::ISub32:
+			case ValueOpcode::ISub64:
+			case ValueOpcode::IMul32:
+			case ValueOpcode::IMul64:
+			case ValueOpcode::UMin32:
+			case ValueOpcode::FPMul32:
+			case ValueOpcode::FPOrdLessThanEqual32:
+			case ValueOpcode::FPOrdGreaterThanEqual32:
+			case ValueOpcode::BitwiseAnd32:
+			case ValueOpcode::BitwiseAnd64:
+			case ValueOpcode::BitwiseOr32:
+			case ValueOpcode::BitwiseXor32:
+			case ValueOpcode::ShiftLeftLogical32:
+			case ValueOpcode::ShiftLeftLogical64:
+			case ValueOpcode::ShiftRightLogical32:
+			case ValueOpcode::ShiftRightLogical64:
+			case ValueOpcode::ShiftRightArithmetic32:
+			case ValueOpcode::ShiftRightArithmetic64:
+			case ValueOpcode::IEqual32:
+			case ValueOpcode::INotEqual32:
+			case ValueOpcode::ULessThan32:
+			case ValueOpcode::UGreaterThan32:
+			case ValueOpcode::LogicalAnd:
+			case ValueOpcode::LogicalOr:
+			case ValueOpcode::LogicalXor:
+				return GenericBinary(inst, opcode);

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add SGreaterThanEqual32 to the compile switch.

SrtExecution::Generic handles ValueOpcode::SGreaterThanEqual32, and Evaluator::EvaluateInst also supports it. CompileInst has no case for it, so it reaches default and becomes AlwaysFails.

A plan that uses this opcode always fails the compiled path. Every draw then runs both evaluators. When KYTY_SRT_SHADOW_VALIDATE is set, interpreted_ok != compiled_ok calls EXIT.

Proposed fix
 			case ValueOpcode::UGreaterThan32:
+			case ValueOpcode::SGreaterThanEqual32:
 			case ValueOpcode::LogicalAnd:
📝 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.

			case ValueOpcode::IEqual32:
			case ValueOpcode::INotEqual32:
			case ValueOpcode::ULessThan32:
			case ValueOpcode::UGreaterThan32:
			case ValueOpcode::SGreaterThanEqual32:
			case ValueOpcode::LogicalAnd:
			case ValueOpcode::LogicalOr:
			case ValueOpcode::LogicalXor:
				return GenericBinary(inst, opcode);
**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882801) On `src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp` line 248 (outdated): ```diff @@ -0,0 +1,806 @@ +// Compiles a ResourcePlan's reachable SRT expression graph into a flat, topologically-ordered +// CompiledSrtProgram once per unique shader, so per-draw evaluation (SrtExecution) indexes a +// flat array instead of SrtWalker.cpp's Evaluator re-walking the same Inst graph, node by node, +// on every single draw. +// +// This file is a deliberately case-by-case port of Evaluator::EvaluateInst/EvaluateRawRead/ +// EvaluateExtract (SrtWalker.cpp) split into two halves per opcode: a Compile-time half (this +// file's Compiler class) that resolves everything structural/static once -- operand slots, +// MemoryFlags, SRT slot indices, component indices, the "is this SRT slot clean" flag -- and an +// execute-time half (SrtExecution) that does only the genuinely runtime-dependent work +// (user_data lookups, guest memory reads, and the arithmetic itself). Every case here should be +// read side-by-side with its EvaluateInst counterpart; anything that doesn't map cleanly compiles +// to AlwaysFails rather than guessing, matching EvaluateInst's own `default: break;`. +// +// Only opcodes SrtWalker.cpp's own Evaluator actually resolves are handled here (e.g. no +// CompositeExtractU32x4/BitCount32/FindILsb32/FindUMsb32 -- this codebase's Evaluator has no +// cases for them either, so they already compile to AlwaysFails via the default path, matching +// the interpreter exactly). SelectU32/U1/F32 gets its own CompiledOpKind rather than folding into +// the generic arithmetic dispatch: this codebase's Select resolves its predicate through the +// clean pass (when one is available) and only evaluates the branch it actually selects, unlike a +// plain eager ternary -- see CompiledOpKind::Select's case in SrtExecution::Evaluate below. +// +// Two facts from ExtractResourcePlan (ResourceMaterialization.cpp) shape this compiler: +// - Its Clone lambda already resolves every Phi to its invariant value or leaves it unreachable, +// so any Phi that still appears in a ResourcePlan's value_storage is provably non-invariant. +// No runtime Phi-resolution logic is needed here at all -- see CompiledOpKind::AlwaysFails. +// - CompositeConstructU32x2 and IAddCarry32 are never given their own EvaluateInst case -- they +// are only ever reached through CompositeExtractU32x2's special-casing, which reads directly +// through them without evaluating the construct/carry node as its own value. This compiler +// mirrors that with ExtractPassthrough/ExtractCarryHalf, so a construct or carry node reached +// any other way still compiles to AlwaysFails, exactly like today's `default: break;`. +#include "graphics/shader/recompiler/ir/passes/SrtCompiler.h" + +#include "common/assert.h" +#include "common/profiler.h" +#include "graphics/shader/recompiler/ir/ShaderIR.h" + +#include <algorithm> +#include <array> +#include <bit> +#include <cmath> +#include <cstring> +#include <deque> +#include <unordered_map> + +namespace Libs::Graphics::ShaderRecompiler::IR { +namespace { + +constexpr uint64_t AddressMask = 0x0000ffffffffffffull; + +// Sentinel stored in m_slot_for_inst while an Inst's operands are still being compiled, so a +// genuine cycle (should be impossible post-Phi-elimination, but never trust that blindly) fails +// closed as AlwaysFails instead of infinitely recursing. +constexpr uint32_t kInProgressSlot = UINT32_MAX - 1; + +bool IsRawReadOpcode(const ResourcePlan& program, const Inst& inst) { + const auto op = inst.GetOpcode(); + if (op != ValueOpcode::LoadAddressU32 && op != ValueOpcode::ReadConstBuffer) { + return false; + } + const auto index = inst.Flags<MemoryFlags>().index; + if (index >= program.memory_info.size()) { + return false; + } + const auto kind = program.memory_info[index].kind; + return (op == ValueOpcode::LoadAddressU32 && kind == ResourceKind::ScalarAddress) || + (op == ValueOpcode::ReadConstBuffer && kind == ResourceKind::ScalarBuffer); +} + +class Compiler { +public: + explicit Compiler(const ResourcePlan& program): m_program(program) {} + + CompiledSrtProgram Run() { + CompiledSrtProgram result; + result.descriptor_source_slots.resize(m_program.descriptor_sources.size()); + for (size_t i = 0; i < m_program.descriptor_sources.size(); i++) { + const auto& source = m_program.descriptor_sources[i]; + for (uint32_t d = 0; d < source.dword_count; d++) { + result.descriptor_source_slots[i][d] = CompileValue(source.dwords[d]); + } + } + result.srt_read_slots.resize(m_program.srt_reads.size()); + for (size_t i = 0; i < m_program.srt_reads.size(); i++) { + result.srt_read_slots[i] = CompileValue(m_program.srt_reads[i].value); + } + result.control_flow_condition_slots.resize(m_program.control_flow.size()); + for (size_t i = 0; i < m_program.control_flow.size(); i++) { + const auto& condition = m_program.control_flow[i].condition; + result.control_flow_condition_slots[i] = + condition.IsEmpty() ? kInvalidSlot : CompileValue(condition); + } + result.ops = std::move(m_ops); + return result; + } + +private: + static CompiledOp AlwaysFailsOp() { + CompiledOp op; + op.kind = CompiledOpKind::AlwaysFails; + return op; + } + + // Post-order: every operand this node references is compiled (and therefore already has a + // lower slot index in m_ops) before this node's own CompiledOp is appended. + uint32_t CompileValue(Value value) { + value = value.Resolve(); + if (value.IsImmediate()) { + return EmitConstant(value); + } + auto* inst = value.TryInstruction(); + if (inst == nullptr) { + return EmitOp(AlwaysFailsOp()); + } + if (const auto it = m_slot_for_inst.find(inst); it != m_slot_for_inst.end()) { + if (it->second == kInProgressSlot) { + return EmitOp(AlwaysFailsOp()); + } + return it->second; + } + m_slot_for_inst.emplace(inst, kInProgressSlot); + auto op = CompileInst(*inst); + const auto slot = EmitOp(std::move(op)); + m_slot_for_inst[inst] = slot; + return slot; + } + + uint32_t EmitOp(CompiledOp op) { + m_ops.push_back(std::move(op)); + return static_cast<uint32_t>(m_ops.size() - 1); + } + + uint32_t EmitConstant(Value value) { + CompiledOp op; + op.kind = CompiledOpKind::Constant; + switch (value.GetType()) { + case Type::U1: op.immediate = value.U1(); break; + case Type::U8: op.immediate = value.U8(); break; + case Type::U16: op.immediate = value.U16(); break; + case Type::U32: op.immediate = value.U32(); break; + case Type::U64: op.immediate = value.U64(); break; + case Type::F32: op.immediate = std::bit_cast<uint32_t>(value.F32Value()); break; + default: return EmitOp(AlwaysFailsOp()); + } + return EmitOp(std::move(op)); + } + + // Mirrors Evaluator::EvaluateInst case-by-case -- see this file's header comment. + CompiledOp CompileInst(const Inst& inst) { + const auto opcode = inst.GetOpcode(); + switch (opcode) { + case ValueOpcode::GetUserData: { + if (inst.NumArgs() != 1 || inst.Arg(0).GetType() != Type::ScalarReg) { + return AlwaysFailsOp(); + } + const auto reg = RegIndex(inst.Arg(0).ScalarRegister()); + if (reg < m_program.user_data_base) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::GetUserData; + op.immediate = reg - m_program.user_data_base; + return op; + } + case ValueOpcode::GetShaderBase: { + CompiledOp op; + op.kind = CompiledOpKind::GetShaderBase; + return op; + } + case ValueOpcode::Phi: + // Provably non-invariant -- see this file's header comment. + return AlwaysFailsOp(); + case ValueOpcode::ReadFirstLane: { + if (inst.NumArgs() != 2) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::ReadFirstLane; + op.num_operands = 2; + op.operands[0] = CompileValue(inst.Arg(0)); + op.operands[1] = CompileValue(inst.Arg(1)); + return op; + } + case ValueOpcode::BitCastU32F32: + case ValueOpcode::BitCastF32U32: + return GenericUnary(inst, opcode); + case ValueOpcode::CompositeExtractU64: + case ValueOpcode::CompositeExtractU32x2: + return CompileExtract(inst, opcode); + case ValueOpcode::CompositeConstructU64: + return GenericBinary(inst, opcode); + case ValueOpcode::ReadConst: { + if (inst.NumArgs() != 2) { + return AlwaysFailsOp(); + } + const auto slot = inst.Arg(1).Resolve(); + if (!slot.IsImmediate() || slot.GetType() != Type::U32) { + return AlwaysFailsOp(); + } + const auto slot_index = slot.U32(); + if (slot_index >= m_program.srt_reads.size()) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::ReadConst; + op.srt_slot_clean = slot_index < m_program.clean_flat_slots.size() && + m_program.clean_flat_slots[slot_index] != 0u; + op.num_operands = 1; + // The SRT read's own value graph -- compiled once here (shared with anyone else + // referencing the same srt_reads[slot_index], since CompileValue dedupes by Inst* + // either way). + op.operands[0] = CompileValue(m_program.srt_reads[slot_index].value); + return op; + } + case ValueOpcode::LoadAddressU32: + case ValueOpcode::ReadConstBuffer: + if (IsRawReadOpcode(m_program, inst)) { + return CompileRawRead(inst, opcode); + } + return AlwaysFailsOp(); + case ValueOpcode::IAdd32: + case ValueOpcode::IAdd64: + case ValueOpcode::ISub32: + case ValueOpcode::ISub64: + case ValueOpcode::IMul32: + case ValueOpcode::IMul64: + case ValueOpcode::UMin32: + case ValueOpcode::FPMul32: + case ValueOpcode::FPOrdLessThanEqual32: + case ValueOpcode::FPOrdGreaterThanEqual32: + case ValueOpcode::BitwiseAnd32: + case ValueOpcode::BitwiseAnd64: + case ValueOpcode::BitwiseOr32: + case ValueOpcode::BitwiseXor32: + case ValueOpcode::ShiftLeftLogical32: + case ValueOpcode::ShiftLeftLogical64: + case ValueOpcode::ShiftRightLogical32: + case ValueOpcode::ShiftRightLogical64: + case ValueOpcode::ShiftRightArithmetic32: + case ValueOpcode::ShiftRightArithmetic64: + case ValueOpcode::IEqual32: + case ValueOpcode::INotEqual32: + case ValueOpcode::ULessThan32: + case ValueOpcode::UGreaterThan32: + case ValueOpcode::LogicalAnd: + case ValueOpcode::LogicalOr: + case ValueOpcode::LogicalXor: + return GenericBinary(inst, opcode); ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Add `SGreaterThanEqual32` to the compile switch.** `SrtExecution::Generic` handles `ValueOpcode::SGreaterThanEqual32`, and `Evaluator::EvaluateInst` also supports it. `CompileInst` has no case for it, so it reaches `default` and becomes `AlwaysFails`. A plan that uses this opcode always fails the compiled path. Every draw then runs both evaluators. When `KYTY_SRT_SHADOW_VALIDATE` is set, `interpreted_ok != compiled_ok` calls `EXIT`. <details> <summary>Proposed fix</summary> ```diff case ValueOpcode::UGreaterThan32: + case ValueOpcode::SGreaterThanEqual32: case ValueOpcode::LogicalAnd: ``` </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 case ValueOpcode::IEqual32: case ValueOpcode::INotEqual32: case ValueOpcode::ULessThan32: case ValueOpcode::UGreaterThan32: case ValueOpcode::SGreaterThanEqual32: case ValueOpcode::LogicalAnd: case ValueOpcode::LogicalOr: case ValueOpcode::LogicalXor: return GenericBinary(inst, opcode); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:bbbd9e5b2381d42c9626696b --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp line 563 (outdated):

@@ -0,0 +1,806 @@
+// Compiles a ResourcePlan's reachable SRT expression graph into a flat, topologically-ordered
+// CompiledSrtProgram once per unique shader, so per-draw evaluation (SrtExecution) indexes a
+// flat array instead of SrtWalker.cpp's Evaluator re-walking the same Inst graph, node by node,
+// on every single draw.
+//
+// This file is a deliberately case-by-case port of Evaluator::EvaluateInst/EvaluateRawRead/
+// EvaluateExtract (SrtWalker.cpp) split into two halves per opcode: a Compile-time half (this
+// file's Compiler class) that resolves everything structural/static once -- operand slots,
+// MemoryFlags, SRT slot indices, component indices, the "is this SRT slot clean" flag -- and an
+// execute-time half (SrtExecution) that does only the genuinely runtime-dependent work
+// (user_data lookups, guest memory reads, and the arithmetic itself). Every case here should be
+// read side-by-side with its EvaluateInst counterpart; anything that doesn't map cleanly compiles
+// to AlwaysFails rather than guessing, matching EvaluateInst's own `default: break;`.
+//
+// Only opcodes SrtWalker.cpp's own Evaluator actually resolves are handled here (e.g. no
+// CompositeExtractU32x4/BitCount32/FindILsb32/FindUMsb32 -- this codebase's Evaluator has no
+// cases for them either, so they already compile to AlwaysFails via the default path, matching
+// the interpreter exactly). SelectU32/U1/F32 gets its own CompiledOpKind rather than folding into
+// the generic arithmetic dispatch: this codebase's Select resolves its predicate through the
+// clean pass (when one is available) and only evaluates the branch it actually selects, unlike a
+// plain eager ternary -- see CompiledOpKind::Select's case in SrtExecution::Evaluate below.
+//
+// Two facts from ExtractResourcePlan (ResourceMaterialization.cpp) shape this compiler:
+//   - Its Clone lambda already resolves every Phi to its invariant value or leaves it unreachable,
+//     so any Phi that still appears in a ResourcePlan's value_storage is provably non-invariant.
+//     No runtime Phi-resolution logic is needed here at all -- see CompiledOpKind::AlwaysFails.
+//   - CompositeConstructU32x2 and IAddCarry32 are never given their own EvaluateInst case -- they
+//     are only ever reached through CompositeExtractU32x2's special-casing, which reads directly
+//     through them without evaluating the construct/carry node as its own value. This compiler
+//     mirrors that with ExtractPassthrough/ExtractCarryHalf, so a construct or carry node reached
+//     any other way still compiles to AlwaysFails, exactly like today's `default: break;`.
+#include "graphics/shader/recompiler/ir/passes/SrtCompiler.h"
+
+#include "common/assert.h"
+#include "common/profiler.h"
+#include "graphics/shader/recompiler/ir/ShaderIR.h"
+
+#include <algorithm>
+#include <array>
+#include <bit>
+#include <cmath>
+#include <cstring>
+#include <deque>
+#include <unordered_map>
+
+namespace Libs::Graphics::ShaderRecompiler::IR {
+namespace {
+
+constexpr uint64_t AddressMask = 0x0000ffffffffffffull;
+
+// Sentinel stored in m_slot_for_inst while an Inst's operands are still being compiled, so a
+// genuine cycle (should be impossible post-Phi-elimination, but never trust that blindly) fails
+// closed as AlwaysFails instead of infinitely recursing.
+constexpr uint32_t kInProgressSlot = UINT32_MAX - 1;
+
+bool IsRawReadOpcode(const ResourcePlan& program, const Inst& inst) {
+	const auto op = inst.GetOpcode();
+	if (op != ValueOpcode::LoadAddressU32 && op != ValueOpcode::ReadConstBuffer) {
+		return false;
+	}
+	const auto index = inst.Flags<MemoryFlags>().index;
+	if (index >= program.memory_info.size()) {
+		return false;
+	}
+	const auto kind = program.memory_info[index].kind;
+	return (op == ValueOpcode::LoadAddressU32 && kind == ResourceKind::ScalarAddress) ||
+	       (op == ValueOpcode::ReadConstBuffer && kind == ResourceKind::ScalarBuffer);
+}
+
+class Compiler {
+public:
+	explicit Compiler(const ResourcePlan& program): m_program(program) {}
+
+	CompiledSrtProgram Run() {
+		CompiledSrtProgram result;
+		result.descriptor_source_slots.resize(m_program.descriptor_sources.size());
+		for (size_t i = 0; i < m_program.descriptor_sources.size(); i++) {
+			const auto& source = m_program.descriptor_sources[i];
+			for (uint32_t d = 0; d < source.dword_count; d++) {
+				result.descriptor_source_slots[i][d] = CompileValue(source.dwords[d]);
+			}
+		}
+		result.srt_read_slots.resize(m_program.srt_reads.size());
+		for (size_t i = 0; i < m_program.srt_reads.size(); i++) {
+			result.srt_read_slots[i] = CompileValue(m_program.srt_reads[i].value);
+		}
+		result.control_flow_condition_slots.resize(m_program.control_flow.size());
+		for (size_t i = 0; i < m_program.control_flow.size(); i++) {
+			const auto& condition = m_program.control_flow[i].condition;
+			result.control_flow_condition_slots[i] =
+			    condition.IsEmpty() ? kInvalidSlot : CompileValue(condition);
+		}
+		result.ops = std::move(m_ops);
+		return result;
+	}
+
+private:
+	static CompiledOp AlwaysFailsOp() {
+		CompiledOp op;
+		op.kind = CompiledOpKind::AlwaysFails;
+		return op;
+	}
+
+	// Post-order: every operand this node references is compiled (and therefore already has a
+	// lower slot index in m_ops) before this node's own CompiledOp is appended.
+	uint32_t CompileValue(Value value) {
+		value = value.Resolve();
+		if (value.IsImmediate()) {
+			return EmitConstant(value);
+		}
+		auto* inst = value.TryInstruction();
+		if (inst == nullptr) {
+			return EmitOp(AlwaysFailsOp());
+		}
+		if (const auto it = m_slot_for_inst.find(inst); it != m_slot_for_inst.end()) {
+			if (it->second == kInProgressSlot) {
+				return EmitOp(AlwaysFailsOp());
+			}
+			return it->second;
+		}
+		m_slot_for_inst.emplace(inst, kInProgressSlot);
+		auto       op          = CompileInst(*inst);
+		const auto slot        = EmitOp(std::move(op));
+		m_slot_for_inst[inst] = slot;
+		return slot;
+	}
+
+	uint32_t EmitOp(CompiledOp op) {
+		m_ops.push_back(std::move(op));
+		return static_cast<uint32_t>(m_ops.size() - 1);
+	}
+
+	uint32_t EmitConstant(Value value) {
+		CompiledOp op;
+		op.kind = CompiledOpKind::Constant;
+		switch (value.GetType()) {
+			case Type::U1: op.immediate = value.U1(); break;
+			case Type::U8: op.immediate = value.U8(); break;
+			case Type::U16: op.immediate = value.U16(); break;
+			case Type::U32: op.immediate = value.U32(); break;
+			case Type::U64: op.immediate = value.U64(); break;
+			case Type::F32: op.immediate = std::bit_cast<uint32_t>(value.F32Value()); break;
+			default: return EmitOp(AlwaysFailsOp());
+		}
+		return EmitOp(std::move(op));
+	}
+
+	// Mirrors Evaluator::EvaluateInst case-by-case -- see this file's header comment.
+	CompiledOp CompileInst(const Inst& inst) {
+		const auto opcode = inst.GetOpcode();
+		switch (opcode) {
+			case ValueOpcode::GetUserData: {
+				if (inst.NumArgs() != 1 || inst.Arg(0).GetType() != Type::ScalarReg) {
+					return AlwaysFailsOp();
+				}
+				const auto reg = RegIndex(inst.Arg(0).ScalarRegister());
+				if (reg < m_program.user_data_base) {
+					return AlwaysFailsOp();
+				}
+				CompiledOp op;
+				op.kind      = CompiledOpKind::GetUserData;
+				op.immediate = reg - m_program.user_data_base;
+				return op;
+			}
+			case ValueOpcode::GetShaderBase: {
+				CompiledOp op;
+				op.kind = CompiledOpKind::GetShaderBase;
+				return op;
+			}
+			case ValueOpcode::Phi:
+				// Provably non-invariant -- see this file's header comment.
+				return AlwaysFailsOp();
+			case ValueOpcode::ReadFirstLane: {
+				if (inst.NumArgs() != 2) {
+					return AlwaysFailsOp();
+				}
+				CompiledOp op;
+				op.kind         = CompiledOpKind::ReadFirstLane;
+				op.num_operands = 2;
+				op.operands[0]  = CompileValue(inst.Arg(0));
+				op.operands[1]  = CompileValue(inst.Arg(1));
+				return op;
+			}
+			case ValueOpcode::BitCastU32F32:
+			case ValueOpcode::BitCastF32U32:
+				return GenericUnary(inst, opcode);
+			case ValueOpcode::CompositeExtractU64:
+			case ValueOpcode::CompositeExtractU32x2:
+				return CompileExtract(inst, opcode);
+			case ValueOpcode::CompositeConstructU64:
+				return GenericBinary(inst, opcode);
+			case ValueOpcode::ReadConst: {
+				if (inst.NumArgs() != 2) {
+					return AlwaysFailsOp();
+				}
+				const auto slot = inst.Arg(1).Resolve();
+				if (!slot.IsImmediate() || slot.GetType() != Type::U32) {
+					return AlwaysFailsOp();
+				}
+				const auto slot_index = slot.U32();
+				if (slot_index >= m_program.srt_reads.size()) {
+					return AlwaysFailsOp();
+				}
+				CompiledOp op;
+				op.kind           = CompiledOpKind::ReadConst;
+				op.srt_slot_clean = slot_index < m_program.clean_flat_slots.size() &&
+				                    m_program.clean_flat_slots[slot_index] != 0u;
+				op.num_operands = 1;
+				// The SRT read's own value graph -- compiled once here (shared with anyone else
+				// referencing the same srt_reads[slot_index], since CompileValue dedupes by Inst*
+				// either way).
+				op.operands[0] = CompileValue(m_program.srt_reads[slot_index].value);
+				return op;
+			}
+			case ValueOpcode::LoadAddressU32:
+			case ValueOpcode::ReadConstBuffer:
+				if (IsRawReadOpcode(m_program, inst)) {
+					return CompileRawRead(inst, opcode);
+				}
+				return AlwaysFailsOp();
+			case ValueOpcode::IAdd32:
+			case ValueOpcode::IAdd64:
+			case ValueOpcode::ISub32:
+			case ValueOpcode::ISub64:
+			case ValueOpcode::IMul32:
+			case ValueOpcode::IMul64:
+			case ValueOpcode::UMin32:
+			case ValueOpcode::FPMul32:
+			case ValueOpcode::FPOrdLessThanEqual32:
+			case ValueOpcode::FPOrdGreaterThanEqual32:
+			case ValueOpcode::BitwiseAnd32:
+			case ValueOpcode::BitwiseAnd64:
+			case ValueOpcode::BitwiseOr32:
+			case ValueOpcode::BitwiseXor32:
+			case ValueOpcode::ShiftLeftLogical32:
+			case ValueOpcode::ShiftLeftLogical64:
+			case ValueOpcode::ShiftRightLogical32:
+			case ValueOpcode::ShiftRightLogical64:
+			case ValueOpcode::ShiftRightArithmetic32:
+			case ValueOpcode::ShiftRightArithmetic64:
+			case ValueOpcode::IEqual32:
+			case ValueOpcode::INotEqual32:
+			case ValueOpcode::ULessThan32:
+			case ValueOpcode::UGreaterThan32:
+			case ValueOpcode::LogicalAnd:
+			case ValueOpcode::LogicalOr:
+			case ValueOpcode::LogicalXor:
+				return GenericBinary(inst, opcode);
+			case ValueOpcode::ConvertF32U32:
+			case ValueOpcode::ConvertU32F32:
+			case ValueOpcode::FPTrunc32:
+			case ValueOpcode::FPIsNan32:
+			case ValueOpcode::BitwiseNot32:
+			case ValueOpcode::LogicalNot:
+				return GenericUnary(inst, opcode);
+			case ValueOpcode::BitFieldUExtract:
+			case ValueOpcode::BitFieldSExtract:
+				return GenericTernary(inst, opcode);
+			case ValueOpcode::BitFieldInsert:
+				return GenericQuaternary(inst, opcode);
+			case ValueOpcode::SelectU32:
+			case ValueOpcode::SelectU1:
+			case ValueOpcode::SelectF32:
+				return CompileSelect(inst);
+			case ValueOpcode::UndefU1:
+			case ValueOpcode::UndefU8:
+			case ValueOpcode::UndefU16:
+			case ValueOpcode::UndefU32:
+			case ValueOpcode::UndefU64:
+			default:
+				return AlwaysFailsOp();
+		}
+	}
+
+	CompiledOp GenericUnary(const Inst& inst, ValueOpcode opcode) {
+		if (inst.NumArgs() < 1) {
+			return AlwaysFailsOp();
+		}
+		CompiledOp op;
+		op.kind         = CompiledOpKind::Generic;
+		op.opcode       = opcode;
+		op.num_operands = 1;
+		op.operands[0]  = CompileValue(inst.Arg(0));
+		return op;
+	}
+
+	CompiledOp GenericBinary(const Inst& inst, ValueOpcode opcode) {
+		if (inst.NumArgs() < 2) {
+			return AlwaysFailsOp();
+		}
+		CompiledOp op;
+		op.kind         = CompiledOpKind::Generic;
+		op.opcode       = opcode;
+		op.num_operands = 2;
+		op.operands[0]  = CompileValue(inst.Arg(0));
+		op.operands[1]  = CompileValue(inst.Arg(1));
+		return op;
+	}
+
+	CompiledOp GenericTernary(const Inst& inst, ValueOpcode opcode) {
+		if (inst.NumArgs() < 3) {
+			return AlwaysFailsOp();
+		}
+		CompiledOp op;
+		op.kind         = CompiledOpKind::Generic;
+		op.opcode       = opcode;
+		op.num_operands = 3;
+		op.operands[0]  = CompileValue(inst.Arg(0));
+		op.operands[1]  = CompileValue(inst.Arg(1));
+		op.operands[2]  = CompileValue(inst.Arg(2));
+		return op;
+	}
+
+	CompiledOp GenericQuaternary(const Inst& inst, ValueOpcode opcode) {
+		if (inst.NumArgs() < 4) {
+			return AlwaysFailsOp();
+		}
+		CompiledOp op;
+		op.kind         = CompiledOpKind::Generic;
+		op.opcode       = opcode;
+		op.num_operands = 4;
+		op.operands[0]  = CompileValue(inst.Arg(0));
+		op.operands[1]  = CompileValue(inst.Arg(1));
+		op.operands[2]  = CompileValue(inst.Arg(2));
+		op.operands[3]  = CompileValue(inst.Arg(3));
+		return op;
+	}
+
+	// Mirrors EvaluateInst's Select case: the predicate is resolved through the clean pass (see
+	// SrtExecution::Evaluate), and only the branch it selects is ever compiled to require a value
+	// -- but both branches still need their own slots compiled here so the flat array stays
+	// complete for anyone else referencing the same nodes.
+	CompiledOp CompileSelect(const Inst& inst) {
+		if (inst.NumArgs() != 3) {
+			return AlwaysFailsOp();
+		}
+		CompiledOp op;
+		op.kind         = CompiledOpKind::Select;
+		op.num_operands = 3;
+		op.operands[0]  = CompileValue(inst.Arg(0));
+		op.operands[1]  = CompileValue(inst.Arg(1));
+		op.operands[2]  = CompileValue(inst.Arg(2));
+		return op;
+	}
+
+	// Mirrors Evaluator::EvaluateExtract.
+	CompiledOp CompileExtract(const Inst& inst, ValueOpcode opcode) {
+		if (inst.NumArgs() != 2) {
+			return AlwaysFailsOp();
+		}
+		const auto index = inst.Arg(1).Resolve();
+		if (!index.IsImmediate() || index.GetType() != Type::U32) {
+			return AlwaysFailsOp();
+		}
+		const auto component = index.U32();
+		if (component >= 2u) {
+			return AlwaysFailsOp();
+		}
+		if (opcode == ValueOpcode::CompositeExtractU64) {
+			CompiledOp op;
+			op.kind         = CompiledOpKind::ExtractU64;
+			op.component    = component;
+			op.num_operands = 1;
+			op.operands[0]  = CompileValue(inst.Arg(0));
+			return op;
+		}
+		const auto* source = inst.Arg(0).ResolveInstruction();
+		if (source == nullptr) {
+			return AlwaysFailsOp();
+		}
+		const auto source_opcode = source->GetOpcode();
+		if (source_opcode == ValueOpcode::CompositeConstructU32x2) {
+			// EvaluateExtract never evaluates the construct node itself -- it reaches straight
+			// through to one of its arguments. Guard against a construct with too few args
+			// (source->Arg(component) would otherwise assert inside Inst::Arg).
+			if (component >= source->NumArgs()) {
+				return AlwaysFailsOp();
+			}
+			CompiledOp op;
+			op.kind         = CompiledOpKind::ExtractPassthrough;
+			op.num_operands = 1;
+			op.operands[0]  = CompileValue(source->Arg(component));
+			return op;
+		}
+		if (source_opcode == ValueOpcode::IAddCarry32) {
+			if (source->NumArgs() < 2) {
+				return AlwaysFailsOp();
+			}
+			CompiledOp op;
+			op.kind         = CompiledOpKind::ExtractCarryHalf;
+			op.component    = component;
+			op.num_operands = 2;
+			op.operands[0]  = CompileValue(source->Arg(0));
+			op.operands[1]  = CompileValue(source->Arg(1));
+			return op;
+		}
+		return AlwaysFailsOp();
+	}
+
+	// Mirrors Evaluator::EvaluateRawRead's *structural* validation -- everything here is static
+	// (memory_info, handle shape, immediate offset), so it's fully resolved once, at compile
+	// time. Only the address arithmetic and the actual guest read remain for execute time.
+	CompiledOp CompileRawRead(const Inst& inst, ValueOpcode opcode) {
+		const auto flags = inst.Flags<MemoryFlags>();
+		if (flags.index >= m_program.memory_info.size()) {
+			return AlwaysFailsOp();
+		}
+		const auto& mem = m_program.memory_info[flags.index];
+		if (inst.NumArgs() < 2) {
+			return AlwaysFailsOp();
+		}
+		const auto* handle = inst.Arg(0).ResolveInstruction();
+		if (handle == nullptr) {
+			return AlwaysFailsOp();
+		}
+		const bool is_const_buffer_read = opcode == ValueOpcode::ReadConstBuffer;
+		if (is_const_buffer_read && handle->NumArgs() != 4u) {
+			return AlwaysFailsOp();
+		}
+		if (handle->NumArgs() < 2) {
+			return AlwaysFailsOp();
+		}
+		CompiledOp op;
+		op.kind                 = CompiledOpKind::RawRead;
+		op.is_const_buffer_read = is_const_buffer_read;
+		op.immediate = static_cast<uint64_t>(static_cast<int64_t>(static_cast<int32_t>(mem.offset)));
+		op.num_operands = is_const_buffer_read ? 5 : 3;
+		op.operands[0]  = CompileValue(handle->Arg(0)); // low
+		op.operands[1]  = CompileValue(handle->Arg(1)); // high
+		op.operands[2]  = CompileValue(inst.Arg(1));    // offset
+		if (is_const_buffer_read) {
+			op.operands[3] = CompileValue(handle->Arg(2)); // records
+			op.operands[4] = CompileValue(handle->Arg(3)); // word3
+		}
+		return op;
+	}
+
+	const ResourcePlan&                       m_program;
+	std::vector<CompiledOp>                   m_ops;
+	std::unordered_map<const Inst*, uint32_t> m_slot_for_inst;
+};
+
+bool AddSignedAddress(uint64_t base, int64_t offset, uint64_t& result) {
+	if (base > AddressMask) {
+		return false;
+	}
+	if (offset < 0) {
+		const auto magnitude = uint64_t {0} - static_cast<uint64_t>(offset);
+		if (magnitude > base) {
+			return false;
+		}
+		result = base - magnitude;
+		return true;
+	}
+	const auto magnitude = static_cast<uint64_t>(offset);
+	if (magnitude > AddressMask - base) {
+		return false;
+	}
+	result = base + magnitude;
+	return true;
+}
+
+float    Float32(uint64_t bits) { return std::bit_cast<float>(static_cast<uint32_t>(bits)); }
+uint64_t Float32Bits(float value) { return std::bit_cast<uint32_t>(value); }
+
+} // namespace
+
+CompiledSrtProgram CompileSrtProgram(const ResourcePlan& program) {
+	return Compiler(program).Run();
+}
+
+SrtExecution::SrtExecution(const CompiledSrtProgram& compiled, const SrtRuntime& runtime,
+                           SrtExecutorScratch& clean_scratch, SrtExecutorScratch& raw_scratch)
+    : SrtExecution(compiled, runtime.read_specialization_memory, runtime.read_memory,
+                   runtime.userdata, runtime.user_data, runtime.shader_base, clean_scratch,
+                   raw_scratch, kInvalidSlot) {}
+
+SrtExecution::SrtExecution(const CompiledSrtProgram& compiled, SrtMemoryReader clean_read,
+                           SrtMemoryReader raw_read, void* userdata,
+                           std::span<const uint32_t> user_data, uint64_t shader_base,
+                           SrtExecutorScratch& clean, SrtExecutorScratch& raw,
+                           uint32_t active_mask_slot)
+    : m_compiled(compiled), m_clean_read(clean_read), m_raw_read(raw_read), m_userdata(userdata),
+      m_user_data(user_data), m_shader_base(shader_base), m_clean(clean), m_raw(raw),
+      m_active_mask_slot(active_mask_slot) {
+	Reset(m_clean);
+	Reset(m_raw);
+}
+
+bool SrtExecution::Demand(bool clean, uint32_t slot, uint64_t& value) {
+	auto& scratch = clean ? m_clean : m_raw;
+	if (slot >= m_compiled.ops.size()) {
+		return false;
+	}
+	switch (scratch.computed[slot]) {
+		case Computed: value = scratch.results[slot]; return true;
+		case Failed: return false;
+		case Visiting: return false;
+		default: break;
+	}
+	scratch.computed[slot] = Visiting;
+	uint64_t   out = 0;
+	const bool ok  = Evaluate(clean, slot, out);
+	scratch.results[slot]  = out;
+	scratch.computed[slot] = ok ? Computed : Failed;
+	value                  = out;
+	return ok;
+}
+
+void SrtExecution::Reset(SrtExecutorScratch& scratch) const {
+	const auto count = m_compiled.ops.size();
+	if (scratch.results.size() < count) {
+		scratch.results.resize(count);
+		scratch.computed.resize(count);
+	}
+	std::memset(scratch.computed.data(), Untried, count * sizeof(scratch.computed[0]));
+}
+
+bool SrtExecution::Operand(bool clean, const CompiledOp& op, uint32_t index,
+                           uint64_t& value) {
+	const auto slot = op.operands[index];
+	return slot != kInvalidSlot && Demand(clean, slot, value);
+}
+
+bool SrtExecution::Evaluate(bool clean, uint32_t i, uint64_t& result) {
+	const auto& op = m_compiled.ops[i];
+	switch (op.kind) {
+		case CompiledOpKind::AlwaysFails: return false;
+		case CompiledOpKind::Constant: result = op.immediate; return true;
+		case CompiledOpKind::GetUserData:
+			if (op.immediate >= m_user_data.size()) {
+				return false;
+			}
+			result = m_user_data[op.immediate];
+			return true;
+		case CompiledOpKind::GetShaderBase: result = m_shader_base; return true;
+		case CompiledOpKind::ReadFirstLane: {
+			// This nested pass must not reuse (or pollute) the outer pass's cache, since the
+			// active-mask shortcut below can make the same slot evaluate differently
+			// depending on which mask scope is active -- each nesting depth needs its own,
+			// independent storage (matching Evaluator's brand-new-instance-per-ReadFirstLane
+			// behaviour). A bare thread_local buffer isn't safe here: a ReadFirstLane whose
+			// own mask operand is itself gated by another ReadFirstLane recurses into this
+			// same case, and the inner call's reset would clobber the outer call's in-flight
+			// state. Instead, borrow slot g_nested_scratch_depth from a thread_local pool
+			// indexed by nesting depth -- each depth gets its own buffer, reused across calls
+			// instead of freshly heap-allocated every single time (ReadFirstLane is common
+			// enough in SRT graphs that a fresh pair of vector allocations per hit was
+			// measurable). std::deque, not std::vector: growing it while this frame still
+			// holds `nested_scratch` as a reference must not invalidate that reference, which
+			// vector's reallocation-on-growth would risk if a deeper nested call grows the
+			// pool while this frame is still using its own slot.
+			thread_local std::deque<std::pair<SrtExecutorScratch, SrtExecutorScratch>>
+			                      g_nested_scratch_pool;
+			thread_local uint32_t g_nested_scratch_depth = 0;
+			if (g_nested_scratch_pool.size() <= g_nested_scratch_depth) {
+				g_nested_scratch_pool.emplace_back();
+			}
+			auto& nested_scratch = g_nested_scratch_pool[g_nested_scratch_depth];
+			++g_nested_scratch_depth;
+			SrtExecution nested(m_compiled, m_clean_read, clean ? m_clean_read : m_raw_read,
+			                    m_userdata, m_user_data, m_shader_base, nested_scratch.first,
+			                    nested_scratch.second, op.operands[1]);

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

A nested ReadFirstLane under the clean pass can read memory without a check.

If clean is true, the nested execution uses m_clean_read as its raw reader. If read_specialization_memory is null, m_clean_read is null. RawRead(false, ...) then reaches std::memcpy at the guest-derived address.

The interpreter prevents this case. CleanRuntime sets an always-false reader, so the clean evaluator and its nested active evaluator fail the read.

A Select predicate always uses the clean pass. A ReadFirstLane inside that predicate therefore reaches this path. The result is a mismatch with the interpreter and a direct read that the comment "A missing clean reader must never fall through to the raw-memory path" forbids.

Proposed fix
+			constexpr SrtMemoryReader fail_read = +[](void*, uint64_t, uint32_t*) { return false; };
+			const auto nested_raw =
+			    clean ? (m_clean_read != nullptr ? m_clean_read : fail_read) : m_raw_read;
-			SrtExecution nested(m_compiled, m_clean_read, clean ? m_clean_read : m_raw_read,
+			SrtExecution nested(m_compiled, m_clean_read, nested_raw,
**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882838) On `src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp` line 563 (outdated): ```diff @@ -0,0 +1,806 @@ +// Compiles a ResourcePlan's reachable SRT expression graph into a flat, topologically-ordered +// CompiledSrtProgram once per unique shader, so per-draw evaluation (SrtExecution) indexes a +// flat array instead of SrtWalker.cpp's Evaluator re-walking the same Inst graph, node by node, +// on every single draw. +// +// This file is a deliberately case-by-case port of Evaluator::EvaluateInst/EvaluateRawRead/ +// EvaluateExtract (SrtWalker.cpp) split into two halves per opcode: a Compile-time half (this +// file's Compiler class) that resolves everything structural/static once -- operand slots, +// MemoryFlags, SRT slot indices, component indices, the "is this SRT slot clean" flag -- and an +// execute-time half (SrtExecution) that does only the genuinely runtime-dependent work +// (user_data lookups, guest memory reads, and the arithmetic itself). Every case here should be +// read side-by-side with its EvaluateInst counterpart; anything that doesn't map cleanly compiles +// to AlwaysFails rather than guessing, matching EvaluateInst's own `default: break;`. +// +// Only opcodes SrtWalker.cpp's own Evaluator actually resolves are handled here (e.g. no +// CompositeExtractU32x4/BitCount32/FindILsb32/FindUMsb32 -- this codebase's Evaluator has no +// cases for them either, so they already compile to AlwaysFails via the default path, matching +// the interpreter exactly). SelectU32/U1/F32 gets its own CompiledOpKind rather than folding into +// the generic arithmetic dispatch: this codebase's Select resolves its predicate through the +// clean pass (when one is available) and only evaluates the branch it actually selects, unlike a +// plain eager ternary -- see CompiledOpKind::Select's case in SrtExecution::Evaluate below. +// +// Two facts from ExtractResourcePlan (ResourceMaterialization.cpp) shape this compiler: +// - Its Clone lambda already resolves every Phi to its invariant value or leaves it unreachable, +// so any Phi that still appears in a ResourcePlan's value_storage is provably non-invariant. +// No runtime Phi-resolution logic is needed here at all -- see CompiledOpKind::AlwaysFails. +// - CompositeConstructU32x2 and IAddCarry32 are never given their own EvaluateInst case -- they +// are only ever reached through CompositeExtractU32x2's special-casing, which reads directly +// through them without evaluating the construct/carry node as its own value. This compiler +// mirrors that with ExtractPassthrough/ExtractCarryHalf, so a construct or carry node reached +// any other way still compiles to AlwaysFails, exactly like today's `default: break;`. +#include "graphics/shader/recompiler/ir/passes/SrtCompiler.h" + +#include "common/assert.h" +#include "common/profiler.h" +#include "graphics/shader/recompiler/ir/ShaderIR.h" + +#include <algorithm> +#include <array> +#include <bit> +#include <cmath> +#include <cstring> +#include <deque> +#include <unordered_map> + +namespace Libs::Graphics::ShaderRecompiler::IR { +namespace { + +constexpr uint64_t AddressMask = 0x0000ffffffffffffull; + +// Sentinel stored in m_slot_for_inst while an Inst's operands are still being compiled, so a +// genuine cycle (should be impossible post-Phi-elimination, but never trust that blindly) fails +// closed as AlwaysFails instead of infinitely recursing. +constexpr uint32_t kInProgressSlot = UINT32_MAX - 1; + +bool IsRawReadOpcode(const ResourcePlan& program, const Inst& inst) { + const auto op = inst.GetOpcode(); + if (op != ValueOpcode::LoadAddressU32 && op != ValueOpcode::ReadConstBuffer) { + return false; + } + const auto index = inst.Flags<MemoryFlags>().index; + if (index >= program.memory_info.size()) { + return false; + } + const auto kind = program.memory_info[index].kind; + return (op == ValueOpcode::LoadAddressU32 && kind == ResourceKind::ScalarAddress) || + (op == ValueOpcode::ReadConstBuffer && kind == ResourceKind::ScalarBuffer); +} + +class Compiler { +public: + explicit Compiler(const ResourcePlan& program): m_program(program) {} + + CompiledSrtProgram Run() { + CompiledSrtProgram result; + result.descriptor_source_slots.resize(m_program.descriptor_sources.size()); + for (size_t i = 0; i < m_program.descriptor_sources.size(); i++) { + const auto& source = m_program.descriptor_sources[i]; + for (uint32_t d = 0; d < source.dword_count; d++) { + result.descriptor_source_slots[i][d] = CompileValue(source.dwords[d]); + } + } + result.srt_read_slots.resize(m_program.srt_reads.size()); + for (size_t i = 0; i < m_program.srt_reads.size(); i++) { + result.srt_read_slots[i] = CompileValue(m_program.srt_reads[i].value); + } + result.control_flow_condition_slots.resize(m_program.control_flow.size()); + for (size_t i = 0; i < m_program.control_flow.size(); i++) { + const auto& condition = m_program.control_flow[i].condition; + result.control_flow_condition_slots[i] = + condition.IsEmpty() ? kInvalidSlot : CompileValue(condition); + } + result.ops = std::move(m_ops); + return result; + } + +private: + static CompiledOp AlwaysFailsOp() { + CompiledOp op; + op.kind = CompiledOpKind::AlwaysFails; + return op; + } + + // Post-order: every operand this node references is compiled (and therefore already has a + // lower slot index in m_ops) before this node's own CompiledOp is appended. + uint32_t CompileValue(Value value) { + value = value.Resolve(); + if (value.IsImmediate()) { + return EmitConstant(value); + } + auto* inst = value.TryInstruction(); + if (inst == nullptr) { + return EmitOp(AlwaysFailsOp()); + } + if (const auto it = m_slot_for_inst.find(inst); it != m_slot_for_inst.end()) { + if (it->second == kInProgressSlot) { + return EmitOp(AlwaysFailsOp()); + } + return it->second; + } + m_slot_for_inst.emplace(inst, kInProgressSlot); + auto op = CompileInst(*inst); + const auto slot = EmitOp(std::move(op)); + m_slot_for_inst[inst] = slot; + return slot; + } + + uint32_t EmitOp(CompiledOp op) { + m_ops.push_back(std::move(op)); + return static_cast<uint32_t>(m_ops.size() - 1); + } + + uint32_t EmitConstant(Value value) { + CompiledOp op; + op.kind = CompiledOpKind::Constant; + switch (value.GetType()) { + case Type::U1: op.immediate = value.U1(); break; + case Type::U8: op.immediate = value.U8(); break; + case Type::U16: op.immediate = value.U16(); break; + case Type::U32: op.immediate = value.U32(); break; + case Type::U64: op.immediate = value.U64(); break; + case Type::F32: op.immediate = std::bit_cast<uint32_t>(value.F32Value()); break; + default: return EmitOp(AlwaysFailsOp()); + } + return EmitOp(std::move(op)); + } + + // Mirrors Evaluator::EvaluateInst case-by-case -- see this file's header comment. + CompiledOp CompileInst(const Inst& inst) { + const auto opcode = inst.GetOpcode(); + switch (opcode) { + case ValueOpcode::GetUserData: { + if (inst.NumArgs() != 1 || inst.Arg(0).GetType() != Type::ScalarReg) { + return AlwaysFailsOp(); + } + const auto reg = RegIndex(inst.Arg(0).ScalarRegister()); + if (reg < m_program.user_data_base) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::GetUserData; + op.immediate = reg - m_program.user_data_base; + return op; + } + case ValueOpcode::GetShaderBase: { + CompiledOp op; + op.kind = CompiledOpKind::GetShaderBase; + return op; + } + case ValueOpcode::Phi: + // Provably non-invariant -- see this file's header comment. + return AlwaysFailsOp(); + case ValueOpcode::ReadFirstLane: { + if (inst.NumArgs() != 2) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::ReadFirstLane; + op.num_operands = 2; + op.operands[0] = CompileValue(inst.Arg(0)); + op.operands[1] = CompileValue(inst.Arg(1)); + return op; + } + case ValueOpcode::BitCastU32F32: + case ValueOpcode::BitCastF32U32: + return GenericUnary(inst, opcode); + case ValueOpcode::CompositeExtractU64: + case ValueOpcode::CompositeExtractU32x2: + return CompileExtract(inst, opcode); + case ValueOpcode::CompositeConstructU64: + return GenericBinary(inst, opcode); + case ValueOpcode::ReadConst: { + if (inst.NumArgs() != 2) { + return AlwaysFailsOp(); + } + const auto slot = inst.Arg(1).Resolve(); + if (!slot.IsImmediate() || slot.GetType() != Type::U32) { + return AlwaysFailsOp(); + } + const auto slot_index = slot.U32(); + if (slot_index >= m_program.srt_reads.size()) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::ReadConst; + op.srt_slot_clean = slot_index < m_program.clean_flat_slots.size() && + m_program.clean_flat_slots[slot_index] != 0u; + op.num_operands = 1; + // The SRT read's own value graph -- compiled once here (shared with anyone else + // referencing the same srt_reads[slot_index], since CompileValue dedupes by Inst* + // either way). + op.operands[0] = CompileValue(m_program.srt_reads[slot_index].value); + return op; + } + case ValueOpcode::LoadAddressU32: + case ValueOpcode::ReadConstBuffer: + if (IsRawReadOpcode(m_program, inst)) { + return CompileRawRead(inst, opcode); + } + return AlwaysFailsOp(); + case ValueOpcode::IAdd32: + case ValueOpcode::IAdd64: + case ValueOpcode::ISub32: + case ValueOpcode::ISub64: + case ValueOpcode::IMul32: + case ValueOpcode::IMul64: + case ValueOpcode::UMin32: + case ValueOpcode::FPMul32: + case ValueOpcode::FPOrdLessThanEqual32: + case ValueOpcode::FPOrdGreaterThanEqual32: + case ValueOpcode::BitwiseAnd32: + case ValueOpcode::BitwiseAnd64: + case ValueOpcode::BitwiseOr32: + case ValueOpcode::BitwiseXor32: + case ValueOpcode::ShiftLeftLogical32: + case ValueOpcode::ShiftLeftLogical64: + case ValueOpcode::ShiftRightLogical32: + case ValueOpcode::ShiftRightLogical64: + case ValueOpcode::ShiftRightArithmetic32: + case ValueOpcode::ShiftRightArithmetic64: + case ValueOpcode::IEqual32: + case ValueOpcode::INotEqual32: + case ValueOpcode::ULessThan32: + case ValueOpcode::UGreaterThan32: + case ValueOpcode::LogicalAnd: + case ValueOpcode::LogicalOr: + case ValueOpcode::LogicalXor: + return GenericBinary(inst, opcode); + case ValueOpcode::ConvertF32U32: + case ValueOpcode::ConvertU32F32: + case ValueOpcode::FPTrunc32: + case ValueOpcode::FPIsNan32: + case ValueOpcode::BitwiseNot32: + case ValueOpcode::LogicalNot: + return GenericUnary(inst, opcode); + case ValueOpcode::BitFieldUExtract: + case ValueOpcode::BitFieldSExtract: + return GenericTernary(inst, opcode); + case ValueOpcode::BitFieldInsert: + return GenericQuaternary(inst, opcode); + case ValueOpcode::SelectU32: + case ValueOpcode::SelectU1: + case ValueOpcode::SelectF32: + return CompileSelect(inst); + case ValueOpcode::UndefU1: + case ValueOpcode::UndefU8: + case ValueOpcode::UndefU16: + case ValueOpcode::UndefU32: + case ValueOpcode::UndefU64: + default: + return AlwaysFailsOp(); + } + } + + CompiledOp GenericUnary(const Inst& inst, ValueOpcode opcode) { + if (inst.NumArgs() < 1) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::Generic; + op.opcode = opcode; + op.num_operands = 1; + op.operands[0] = CompileValue(inst.Arg(0)); + return op; + } + + CompiledOp GenericBinary(const Inst& inst, ValueOpcode opcode) { + if (inst.NumArgs() < 2) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::Generic; + op.opcode = opcode; + op.num_operands = 2; + op.operands[0] = CompileValue(inst.Arg(0)); + op.operands[1] = CompileValue(inst.Arg(1)); + return op; + } + + CompiledOp GenericTernary(const Inst& inst, ValueOpcode opcode) { + if (inst.NumArgs() < 3) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::Generic; + op.opcode = opcode; + op.num_operands = 3; + op.operands[0] = CompileValue(inst.Arg(0)); + op.operands[1] = CompileValue(inst.Arg(1)); + op.operands[2] = CompileValue(inst.Arg(2)); + return op; + } + + CompiledOp GenericQuaternary(const Inst& inst, ValueOpcode opcode) { + if (inst.NumArgs() < 4) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::Generic; + op.opcode = opcode; + op.num_operands = 4; + op.operands[0] = CompileValue(inst.Arg(0)); + op.operands[1] = CompileValue(inst.Arg(1)); + op.operands[2] = CompileValue(inst.Arg(2)); + op.operands[3] = CompileValue(inst.Arg(3)); + return op; + } + + // Mirrors EvaluateInst's Select case: the predicate is resolved through the clean pass (see + // SrtExecution::Evaluate), and only the branch it selects is ever compiled to require a value + // -- but both branches still need their own slots compiled here so the flat array stays + // complete for anyone else referencing the same nodes. + CompiledOp CompileSelect(const Inst& inst) { + if (inst.NumArgs() != 3) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::Select; + op.num_operands = 3; + op.operands[0] = CompileValue(inst.Arg(0)); + op.operands[1] = CompileValue(inst.Arg(1)); + op.operands[2] = CompileValue(inst.Arg(2)); + return op; + } + + // Mirrors Evaluator::EvaluateExtract. + CompiledOp CompileExtract(const Inst& inst, ValueOpcode opcode) { + if (inst.NumArgs() != 2) { + return AlwaysFailsOp(); + } + const auto index = inst.Arg(1).Resolve(); + if (!index.IsImmediate() || index.GetType() != Type::U32) { + return AlwaysFailsOp(); + } + const auto component = index.U32(); + if (component >= 2u) { + return AlwaysFailsOp(); + } + if (opcode == ValueOpcode::CompositeExtractU64) { + CompiledOp op; + op.kind = CompiledOpKind::ExtractU64; + op.component = component; + op.num_operands = 1; + op.operands[0] = CompileValue(inst.Arg(0)); + return op; + } + const auto* source = inst.Arg(0).ResolveInstruction(); + if (source == nullptr) { + return AlwaysFailsOp(); + } + const auto source_opcode = source->GetOpcode(); + if (source_opcode == ValueOpcode::CompositeConstructU32x2) { + // EvaluateExtract never evaluates the construct node itself -- it reaches straight + // through to one of its arguments. Guard against a construct with too few args + // (source->Arg(component) would otherwise assert inside Inst::Arg). + if (component >= source->NumArgs()) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::ExtractPassthrough; + op.num_operands = 1; + op.operands[0] = CompileValue(source->Arg(component)); + return op; + } + if (source_opcode == ValueOpcode::IAddCarry32) { + if (source->NumArgs() < 2) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::ExtractCarryHalf; + op.component = component; + op.num_operands = 2; + op.operands[0] = CompileValue(source->Arg(0)); + op.operands[1] = CompileValue(source->Arg(1)); + return op; + } + return AlwaysFailsOp(); + } + + // Mirrors Evaluator::EvaluateRawRead's *structural* validation -- everything here is static + // (memory_info, handle shape, immediate offset), so it's fully resolved once, at compile + // time. Only the address arithmetic and the actual guest read remain for execute time. + CompiledOp CompileRawRead(const Inst& inst, ValueOpcode opcode) { + const auto flags = inst.Flags<MemoryFlags>(); + if (flags.index >= m_program.memory_info.size()) { + return AlwaysFailsOp(); + } + const auto& mem = m_program.memory_info[flags.index]; + if (inst.NumArgs() < 2) { + return AlwaysFailsOp(); + } + const auto* handle = inst.Arg(0).ResolveInstruction(); + if (handle == nullptr) { + return AlwaysFailsOp(); + } + const bool is_const_buffer_read = opcode == ValueOpcode::ReadConstBuffer; + if (is_const_buffer_read && handle->NumArgs() != 4u) { + return AlwaysFailsOp(); + } + if (handle->NumArgs() < 2) { + return AlwaysFailsOp(); + } + CompiledOp op; + op.kind = CompiledOpKind::RawRead; + op.is_const_buffer_read = is_const_buffer_read; + op.immediate = static_cast<uint64_t>(static_cast<int64_t>(static_cast<int32_t>(mem.offset))); + op.num_operands = is_const_buffer_read ? 5 : 3; + op.operands[0] = CompileValue(handle->Arg(0)); // low + op.operands[1] = CompileValue(handle->Arg(1)); // high + op.operands[2] = CompileValue(inst.Arg(1)); // offset + if (is_const_buffer_read) { + op.operands[3] = CompileValue(handle->Arg(2)); // records + op.operands[4] = CompileValue(handle->Arg(3)); // word3 + } + return op; + } + + const ResourcePlan& m_program; + std::vector<CompiledOp> m_ops; + std::unordered_map<const Inst*, uint32_t> m_slot_for_inst; +}; + +bool AddSignedAddress(uint64_t base, int64_t offset, uint64_t& result) { + if (base > AddressMask) { + return false; + } + if (offset < 0) { + const auto magnitude = uint64_t {0} - static_cast<uint64_t>(offset); + if (magnitude > base) { + return false; + } + result = base - magnitude; + return true; + } + const auto magnitude = static_cast<uint64_t>(offset); + if (magnitude > AddressMask - base) { + return false; + } + result = base + magnitude; + return true; +} + +float Float32(uint64_t bits) { return std::bit_cast<float>(static_cast<uint32_t>(bits)); } +uint64_t Float32Bits(float value) { return std::bit_cast<uint32_t>(value); } + +} // namespace + +CompiledSrtProgram CompileSrtProgram(const ResourcePlan& program) { + return Compiler(program).Run(); +} + +SrtExecution::SrtExecution(const CompiledSrtProgram& compiled, const SrtRuntime& runtime, + SrtExecutorScratch& clean_scratch, SrtExecutorScratch& raw_scratch) + : SrtExecution(compiled, runtime.read_specialization_memory, runtime.read_memory, + runtime.userdata, runtime.user_data, runtime.shader_base, clean_scratch, + raw_scratch, kInvalidSlot) {} + +SrtExecution::SrtExecution(const CompiledSrtProgram& compiled, SrtMemoryReader clean_read, + SrtMemoryReader raw_read, void* userdata, + std::span<const uint32_t> user_data, uint64_t shader_base, + SrtExecutorScratch& clean, SrtExecutorScratch& raw, + uint32_t active_mask_slot) + : m_compiled(compiled), m_clean_read(clean_read), m_raw_read(raw_read), m_userdata(userdata), + m_user_data(user_data), m_shader_base(shader_base), m_clean(clean), m_raw(raw), + m_active_mask_slot(active_mask_slot) { + Reset(m_clean); + Reset(m_raw); +} + +bool SrtExecution::Demand(bool clean, uint32_t slot, uint64_t& value) { + auto& scratch = clean ? m_clean : m_raw; + if (slot >= m_compiled.ops.size()) { + return false; + } + switch (scratch.computed[slot]) { + case Computed: value = scratch.results[slot]; return true; + case Failed: return false; + case Visiting: return false; + default: break; + } + scratch.computed[slot] = Visiting; + uint64_t out = 0; + const bool ok = Evaluate(clean, slot, out); + scratch.results[slot] = out; + scratch.computed[slot] = ok ? Computed : Failed; + value = out; + return ok; +} + +void SrtExecution::Reset(SrtExecutorScratch& scratch) const { + const auto count = m_compiled.ops.size(); + if (scratch.results.size() < count) { + scratch.results.resize(count); + scratch.computed.resize(count); + } + std::memset(scratch.computed.data(), Untried, count * sizeof(scratch.computed[0])); +} + +bool SrtExecution::Operand(bool clean, const CompiledOp& op, uint32_t index, + uint64_t& value) { + const auto slot = op.operands[index]; + return slot != kInvalidSlot && Demand(clean, slot, value); +} + +bool SrtExecution::Evaluate(bool clean, uint32_t i, uint64_t& result) { + const auto& op = m_compiled.ops[i]; + switch (op.kind) { + case CompiledOpKind::AlwaysFails: return false; + case CompiledOpKind::Constant: result = op.immediate; return true; + case CompiledOpKind::GetUserData: + if (op.immediate >= m_user_data.size()) { + return false; + } + result = m_user_data[op.immediate]; + return true; + case CompiledOpKind::GetShaderBase: result = m_shader_base; return true; + case CompiledOpKind::ReadFirstLane: { + // This nested pass must not reuse (or pollute) the outer pass's cache, since the + // active-mask shortcut below can make the same slot evaluate differently + // depending on which mask scope is active -- each nesting depth needs its own, + // independent storage (matching Evaluator's brand-new-instance-per-ReadFirstLane + // behaviour). A bare thread_local buffer isn't safe here: a ReadFirstLane whose + // own mask operand is itself gated by another ReadFirstLane recurses into this + // same case, and the inner call's reset would clobber the outer call's in-flight + // state. Instead, borrow slot g_nested_scratch_depth from a thread_local pool + // indexed by nesting depth -- each depth gets its own buffer, reused across calls + // instead of freshly heap-allocated every single time (ReadFirstLane is common + // enough in SRT graphs that a fresh pair of vector allocations per hit was + // measurable). std::deque, not std::vector: growing it while this frame still + // holds `nested_scratch` as a reference must not invalidate that reference, which + // vector's reallocation-on-growth would risk if a deeper nested call grows the + // pool while this frame is still using its own slot. + thread_local std::deque<std::pair<SrtExecutorScratch, SrtExecutorScratch>> + g_nested_scratch_pool; + thread_local uint32_t g_nested_scratch_depth = 0; + if (g_nested_scratch_pool.size() <= g_nested_scratch_depth) { + g_nested_scratch_pool.emplace_back(); + } + auto& nested_scratch = g_nested_scratch_pool[g_nested_scratch_depth]; + ++g_nested_scratch_depth; + SrtExecution nested(m_compiled, m_clean_read, clean ? m_clean_read : m_raw_read, + m_userdata, m_user_data, m_shader_base, nested_scratch.first, + nested_scratch.second, op.operands[1]); ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **A nested `ReadFirstLane` under the clean pass can read memory without a check.** If `clean` is true, the nested execution uses `m_clean_read` as its raw reader. If `read_specialization_memory` is null, `m_clean_read` is null. `RawRead(false, ...)` then reaches `std::memcpy` at the guest-derived address. The interpreter prevents this case. `CleanRuntime` sets an always-false reader, so the clean evaluator and its nested `active` evaluator fail the read. A `Select` predicate always uses the clean pass. A `ReadFirstLane` inside that predicate therefore reaches this path. The result is a mismatch with the interpreter and a direct read that the comment "A missing clean reader must never fall through to the raw-memory path" forbids. <details> <summary>Proposed fix</summary> ```diff + constexpr SrtMemoryReader fail_read = +[](void*, uint64_t, uint32_t*) { return false; }; + const auto nested_raw = + clean ? (m_clean_read != nullptr ? m_clean_read : fail_read) : m_raw_read; - SrtExecution nested(m_compiled, m_clean_read, clean ? m_clean_read : m_raw_read, + SrtExecution nested(m_compiled, m_clean_read, nested_raw, ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d409d223adc8ceef668a8ccf --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/libs/ajm/atrac9_decoder.h line 139 (outdated):

@@ -103,25 +104,49 @@ class AjmAt9Decoder final: public AjmDecoder {
 			return result;
 		}
 
+		const size_t pending_size = m_pending.size();
+		if (pending_size != 0) {
+			m_pending.insert(m_pending.end(), static_cast<const uint8_t*>(input),
+			                 static_cast<const uint8_t*>(input) + input_size);
+			input      = m_pending.data();
+			input_size = m_pending.size();
+		}
+		const auto  finish = [&](AjmDecodeResult& done, size_t consumed, bool stash_tail) {
+			if (stash_tail && consumed < input_size) {
+				std::vector<uint8_t> tail(static_cast<const uint8_t*>(input) + consumed,
+				                          static_cast<const uint8_t*>(input) + input_size);
+				m_pending = std::move(tail);
+				consumed  = input_size;
+			} else if (consumed < pending_size) {
+				std::vector<uint8_t> tail(static_cast<const uint8_t*>(input) + consumed,
+				                          static_cast<const uint8_t*>(input) + pending_size);
+				m_pending = std::move(tail);
+			} else {
+				m_pending.clear();
+			}
+			done.input_consumed = consumed > pending_size ? consumed - pending_size : 0;
+			return done;
+		};
+
 		const auto* input_bytes  = static_cast<const uint8_t*>(input);
 		auto*       output_bytes = static_cast<uint8_t*>(output);
 		size_t      input_offset = 0;
+		bool        stash_tail   = false;
 
 		if (m_parse_riff_header && input_size >= 12 &&
 		    AjmFourCcEquals(input_bytes, 'R', 'I', 'F', 'F')) {
 			if (!ParseRiffHeader(input_bytes, input_size, &input_offset, gapless, &result)) {
-				return result;
+				return finish(result, 0, false);

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Retain partial RIFF data.

When ParseRiffHeader returns AJM_RESULT_PARTIAL_INPUT, this calls finish(result, 0, false). With no existing pending data, finish clears m_pending and reports zero consumed bytes. A split RIFF header is discarded, so the next decode call cannot complete it. Set stash_tail for the partial-input result.

Proposed fix
-				return finish(result, 0, false);
+				return finish(result, 0, result.result == AJM_RESULT_PARTIAL_INPUT);
📝 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.

				return finish(result, 0, result.result == AJM_RESULT_PARTIAL_INPUT);
**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882849) On `src/libs/ajm/atrac9_decoder.h` line 139 (outdated): ```diff @@ -103,25 +104,49 @@ class AjmAt9Decoder final: public AjmDecoder { return result; } + const size_t pending_size = m_pending.size(); + if (pending_size != 0) { + m_pending.insert(m_pending.end(), static_cast<const uint8_t*>(input), + static_cast<const uint8_t*>(input) + input_size); + input = m_pending.data(); + input_size = m_pending.size(); + } + const auto finish = [&](AjmDecodeResult& done, size_t consumed, bool stash_tail) { + if (stash_tail && consumed < input_size) { + std::vector<uint8_t> tail(static_cast<const uint8_t*>(input) + consumed, + static_cast<const uint8_t*>(input) + input_size); + m_pending = std::move(tail); + consumed = input_size; + } else if (consumed < pending_size) { + std::vector<uint8_t> tail(static_cast<const uint8_t*>(input) + consumed, + static_cast<const uint8_t*>(input) + pending_size); + m_pending = std::move(tail); + } else { + m_pending.clear(); + } + done.input_consumed = consumed > pending_size ? consumed - pending_size : 0; + return done; + }; + const auto* input_bytes = static_cast<const uint8_t*>(input); auto* output_bytes = static_cast<uint8_t*>(output); size_t input_offset = 0; + bool stash_tail = false; if (m_parse_riff_header && input_size >= 12 && AjmFourCcEquals(input_bytes, 'R', 'I', 'F', 'F')) { if (!ParseRiffHeader(input_bytes, input_size, &input_offset, gapless, &result)) { - return result; + return finish(result, 0, false); ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Retain partial RIFF data.** When `ParseRiffHeader` returns `AJM_RESULT_PARTIAL_INPUT`, this calls `finish(result, 0, false)`. With no existing pending data, `finish` clears `m_pending` and reports zero consumed bytes. A split RIFF header is discarded, so the next decode call cannot complete it. Set `stash_tail` for the partial-input result. <details> <summary>Proposed fix</summary> ```diff - return finish(result, 0, false); + return finish(result, 0, result.result == AJM_RESULT_PARTIAL_INPUT); ``` </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 return finish(result, 0, result.result == AJM_RESULT_PARTIAL_INPUT); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:poseidon:tapir --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3a517d26303980f645f6d4cb --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/libs/libAmpr.cpp line 246 (outdated):

@@ -101,23 +142,109 @@ static uint32_t ComputeFileId(const char* guest_path) {
 	return hash & static_cast<uint32_t>(std::numeric_limits<int32_t>::max());
 }
 
-static int ReadGuestCString(uint64_t addr, char* out, size_t out_size) {
-	if (addr == 0) {
-		return LibKernel::KERNEL_ERROR_EFAULT;
+static bool CopyStringToOutput(const std::string& str, char* out, size_t out_size) {
+	if (str.empty() || str.size() + 1 > out_size) {
+		return false;
+	}
+
+	std::memcpy(out, str.c_str(), str.size() + 1);
+	return true;
+}
+
+static bool ReadGuestCString(uint64_t addr, char* out, size_t out_size) {
+	if (out == nullptr || out_size == 0 || addr == 0) {
+		return false;
 	}
 
-	const auto* src = reinterpret_cast<const char*>(addr);
-	for (size_t pos = 0; pos < out_size; pos++) {
+	const auto  max_len = static_cast<uint64_t>(out_size - 1);
+	const auto* src     = reinterpret_cast<const char*>(static_cast<uintptr_t>(addr));
+	for (uint64_t pos = 0; pos < max_len; pos++) {
 		if (addr > std::numeric_limits<uint64_t>::max() - pos) {
-			return LibKernel::KERNEL_ERROR_EFAULT;
+			out[pos] = '\0';
+			return false;
+		}
+
+		const auto ch = src[pos];
+		out[pos]      = ch;
+		if (ch == '\0') {
+			return pos != 0;
+		}
+	}
+
+	out[max_len] = '\0';
+	return false;
+}
+
+static bool ReadGuestWideCString(uint64_t addr, char* out, size_t out_size) {
+	if (out == nullptr || out_size == 0 || addr == 0) {
+		return false;
+	}
+
+	std::array<char16_t, 1024> tmp {};
+	const auto                 max_len = std::min<uint64_t>(tmp.size() - 1, out_size - 1);
+	const auto*                src = reinterpret_cast<const char*>(static_cast<uintptr_t>(addr));
+	for (uint64_t pos = 0; pos < max_len; pos++) {
+		if (pos > (std::numeric_limits<uint64_t>::max() - addr) / sizeof(char16_t)) {
+			return false;
 		}
-		out[pos] = src[pos];
-		if (out[pos] == '\0') {
-			return OK;
+
+		char16_t ch = 0;
+		std::memcpy(&ch, src + pos * sizeof(char16_t), sizeof(ch));
+		tmp[static_cast<size_t>(pos)] = ch;
+		if (ch == u'\0') {
+			return pos != 0 && CopyStringToOutput(Common::Utf16ToUtf8(tmp.data()), out, out_size);
 		}
 	}
 
-	return LibKernel::KERNEL_ERROR_ENAMETOOLONG;
+	return false;
+}
+
+static bool ReadGuestPathText(uint64_t addr, char* out, size_t out_size) {
+	std::array<char, 1024> narrow {};
+	if (ReadGuestCString(addr, narrow.data(), std::min(narrow.size(), out_size))) {
+		const auto narrow_len = std::strlen(narrow.data());
+		if (narrow_len > 1 || !ReadGuestWideCString(addr, out, out_size)) {
+			std::memcpy(out, narrow.data(), std::strlen(narrow.data()) + 1);
+		}
+		return true;
+	}
+
+	if (ReadGuestWideCString(addr, out, out_size)) {
+		return true;
+	}
+	return false;
+}
+
+static bool ReadPathPointer(uint64_t pointer_addr, char* out, size_t out_size) {
+	uint64_t path_addr = 0;
+	if (!ReadGuest(pointer_addr, &path_addr)) {
+		return false;
+	}
+	if (path_addr == 0) {
+		return false;
+	}
+	if (ReadGuestPathText(path_addr, out, out_size)) {
+		return true;
+	}
+	return false;
+}
+
+static bool ResolvePathFromList(uint64_t path_list, uint64_t index, char* out, size_t out_size) {
+	if (ReadPathPointer(path_list + index * sizeof(uint64_t), out, out_size)) {
+		return true;
+	}
+	if (index != 0) {
+		return false;
+	}
+	if (ReadGuestPathText(path_list, out, out_size)) {
+		return true;
+	}
+	for (uint64_t offset = 0; offset < 0x40; offset += sizeof(uint64_t)) {
+		if (ReadPathPointer(path_list + offset, out, out_size)) {
+			return true;
+		}
+	}

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

rg -n "ReadPathPointer|ReadGuestPathText|ReadGuestCString|IsValidGuestRange|IsGuestRangeCommitted" src/libs/libAmpr.cpp | head -100

Repository: KytyPS5/KytyPS5

Length of output: 2692


🏁 Script executed:

sed -n '77,250p' src/libs/libAmpr.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4956


🏁 Script executed:

sed -n '109,130p' src/libs/libAmpr.cpp

Repository: KytyPS5/KytyPS5

Length of output: 772


Inline paths may cause access violations before the fallback runs.

ResolvePathFromList reads list entries as pointers through ReadPathPointer. For an inline path stored directly in the list (not referenced through a pointer), the first 8 bytes are printable ASCII characters. When interpreted as a uint64_t pointer, these bytes form a non-canonical host address. ReadGuestPathText then calls ReadGuestCString, which dereferences this address without validating that it is canonical or committed. The access violation occurs before the inline-path fallback at line 239 executes.

IsValidGuestRange (line 77) checks only for zero and overflow. It does not validate canonical addresses or committed memory. ReadGuestCString (line 154) calls IsValidGuestRange but then dereferences the address unconditionally at line 168. The loop starting at line 241 has the same issue for each slot.

Validate that a candidate pointer address is canonical and committed before dereferencing it. On Windows, call IsGuestRangeCommitted before reading. Alternatively, attempt the inline-text interpretation first, before treating the bytes as a pointer.

Suggested fix

Check committed memory status in ReadPathPointer before dereferencing:

static bool ReadPathPointer(uint64_t pointer_addr, char* out, size_t out_size) {
	uint64_t path_addr = 0;
	if (!ReadGuest(pointer_addr, &path_addr)) {
		return false;
	}
	if (path_addr == 0) {
		return false;
	}
	if (!IsGuestRangeCommitted(path_addr, 1)) {
		return false;
	}
	if (ReadGuestPathText(path_addr, out, out_size)) {
		return true;
	}
	return false;
}

Alternatively, reorder ResolvePathFromList to attempt inline interpretation before pointer dereference:

static bool ResolvePathFromList(uint64_t path_list, uint64_t index, char* out, size_t out_size) {
	if (index == 0 && ReadGuestPathText(path_list, out, out_size)) {
		return true;
	}
	if (ReadPathPointer(path_list + index * sizeof(uint64_t), out, out_size)) {
		return true;
	}
	if (index != 0) {
		return false;
	}
	for (uint64_t offset = 0; offset < 0x40; offset += sizeof(uint64_t)) {
		if (ReadPathPointer(path_list + offset, out, out_size)) {
			return true;
		}
	}
	return false;
}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882857) On `src/libs/libAmpr.cpp` line 246 (outdated): ```diff @@ -101,23 +142,109 @@ static uint32_t ComputeFileId(const char* guest_path) { return hash & static_cast<uint32_t>(std::numeric_limits<int32_t>::max()); } -static int ReadGuestCString(uint64_t addr, char* out, size_t out_size) { - if (addr == 0) { - return LibKernel::KERNEL_ERROR_EFAULT; +static bool CopyStringToOutput(const std::string& str, char* out, size_t out_size) { + if (str.empty() || str.size() + 1 > out_size) { + return false; + } + + std::memcpy(out, str.c_str(), str.size() + 1); + return true; +} + +static bool ReadGuestCString(uint64_t addr, char* out, size_t out_size) { + if (out == nullptr || out_size == 0 || addr == 0) { + return false; } - const auto* src = reinterpret_cast<const char*>(addr); - for (size_t pos = 0; pos < out_size; pos++) { + const auto max_len = static_cast<uint64_t>(out_size - 1); + const auto* src = reinterpret_cast<const char*>(static_cast<uintptr_t>(addr)); + for (uint64_t pos = 0; pos < max_len; pos++) { if (addr > std::numeric_limits<uint64_t>::max() - pos) { - return LibKernel::KERNEL_ERROR_EFAULT; + out[pos] = '\0'; + return false; + } + + const auto ch = src[pos]; + out[pos] = ch; + if (ch == '\0') { + return pos != 0; + } + } + + out[max_len] = '\0'; + return false; +} + +static bool ReadGuestWideCString(uint64_t addr, char* out, size_t out_size) { + if (out == nullptr || out_size == 0 || addr == 0) { + return false; + } + + std::array<char16_t, 1024> tmp {}; + const auto max_len = std::min<uint64_t>(tmp.size() - 1, out_size - 1); + const auto* src = reinterpret_cast<const char*>(static_cast<uintptr_t>(addr)); + for (uint64_t pos = 0; pos < max_len; pos++) { + if (pos > (std::numeric_limits<uint64_t>::max() - addr) / sizeof(char16_t)) { + return false; } - out[pos] = src[pos]; - if (out[pos] == '\0') { - return OK; + + char16_t ch = 0; + std::memcpy(&ch, src + pos * sizeof(char16_t), sizeof(ch)); + tmp[static_cast<size_t>(pos)] = ch; + if (ch == u'\0') { + return pos != 0 && CopyStringToOutput(Common::Utf16ToUtf8(tmp.data()), out, out_size); } } - return LibKernel::KERNEL_ERROR_ENAMETOOLONG; + return false; +} + +static bool ReadGuestPathText(uint64_t addr, char* out, size_t out_size) { + std::array<char, 1024> narrow {}; + if (ReadGuestCString(addr, narrow.data(), std::min(narrow.size(), out_size))) { + const auto narrow_len = std::strlen(narrow.data()); + if (narrow_len > 1 || !ReadGuestWideCString(addr, out, out_size)) { + std::memcpy(out, narrow.data(), std::strlen(narrow.data()) + 1); + } + return true; + } + + if (ReadGuestWideCString(addr, out, out_size)) { + return true; + } + return false; +} + +static bool ReadPathPointer(uint64_t pointer_addr, char* out, size_t out_size) { + uint64_t path_addr = 0; + if (!ReadGuest(pointer_addr, &path_addr)) { + return false; + } + if (path_addr == 0) { + return false; + } + if (ReadGuestPathText(path_addr, out, out_size)) { + return true; + } + return false; +} + +static bool ResolvePathFromList(uint64_t path_list, uint64_t index, char* out, size_t out_size) { + if (ReadPathPointer(path_list + index * sizeof(uint64_t), out, out_size)) { + return true; + } + if (index != 0) { + return false; + } + if (ReadGuestPathText(path_list, out, out_size)) { + return true; + } + for (uint64_t offset = 0; offset < 0x40; offset += sizeof(uint64_t)) { + if (ReadPathPointer(path_list + offset, out, out_size)) { + return true; + } + } ``` _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash rg -n "ReadPathPointer|ReadGuestPathText|ReadGuestCString|IsValidGuestRange|IsGuestRangeCommitted" src/libs/libAmpr.cpp | head -100 ``` Repository: KytyPS5/KytyPS5 Length of output: 2692 --- 🏁 Script executed: ```bash sed -n '77,250p' src/libs/libAmpr.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4956 --- 🏁 Script executed: ```bash sed -n '109,130p' src/libs/libAmpr.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 772 --- </details> **Inline paths may cause access violations before the fallback runs.** `ResolvePathFromList` reads list entries as pointers through `ReadPathPointer`. For an inline path stored directly in the list (not referenced through a pointer), the first 8 bytes are printable ASCII characters. When interpreted as a `uint64_t` pointer, these bytes form a non-canonical host address. `ReadGuestPathText` then calls `ReadGuestCString`, which dereferences this address without validating that it is canonical or committed. The access violation occurs before the inline-path fallback at line 239 executes. `IsValidGuestRange` (line 77) checks only for zero and overflow. It does not validate canonical addresses or committed memory. `ReadGuestCString` (line 154) calls `IsValidGuestRange` but then dereferences the address unconditionally at line 168. The loop starting at line 241 has the same issue for each slot. Validate that a candidate pointer address is canonical and committed before dereferencing it. On Windows, call `IsGuestRangeCommitted` before reading. Alternatively, attempt the inline-text interpretation first, before treating the bytes as a pointer. <details> <summary>Suggested fix</summary> Check committed memory status in `ReadPathPointer` before dereferencing: ```cpp static bool ReadPathPointer(uint64_t pointer_addr, char* out, size_t out_size) { uint64_t path_addr = 0; if (!ReadGuest(pointer_addr, &path_addr)) { return false; } if (path_addr == 0) { return false; } if (!IsGuestRangeCommitted(path_addr, 1)) { return false; } if (ReadGuestPathText(path_addr, out, out_size)) { return true; } return false; } ``` Alternatively, reorder `ResolvePathFromList` to attempt inline interpretation before pointer dereference: ```cpp static bool ResolvePathFromList(uint64_t path_list, uint64_t index, char* out, size_t out_size) { if (index == 0 && ReadGuestPathText(path_list, out, out_size)) { return true; } if (ReadPathPointer(path_list + index * sizeof(uint64_t), out, out_size)) { return true; } if (index != 0) { return false; } for (uint64_t offset = 0; offset < 0x40; offset += sizeof(uint64_t)) { if (ReadPathPointer(path_list + offset, out, out_size)) { return true; } } return false; } ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a293f95d29f5cd90614bd1bf --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/libs/libAmpr.cpp line 738 (outdated):

@@ -549,38 +731,35 @@ static int KYTY_SYSV_ABI SubmitCommandBufferAndGetResult(void*     command_buffe
 	const auto id =
 	    AprShared::AllocateSubmissionId(command_buffer_addr, reinterpret_cast<uint64_t>(result));
 
-	int32_t  execution_result = OK;
-	uint32_t error_offset     = 0;
-	auto submit_result = LibAmpr::Ampr::ExecuteAprCommandBuffer(command_buffer_addr,
-	                                                            &execution_result, &error_offset);
+	const auto submit_result = LibAmpr::Ampr::EnqueueCommandBuffer(
+	    command_buffer_addr, false, static_cast<uint32_t>(priority), id,
+	    reinterpret_cast<uint64_t>(result));
 	if (submit_result != OK) {
+		AprShared::CompleteSubmission(id, nullptr);

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Enqueue-failure cleanup blocks forever in CompleteSubmission.

CompleteSubmission now waits until the record is erased or done is true. When EnqueueCommandBuffer fails, no worker runs and nothing sets done. The cleanup call therefore blocks the calling guest thread permanently instead of returning the error. EnqueueCommandBuffer returns EFAULT when TryGetCommandBufferState fails, so an invalid command-buffer header triggers this path.

Add a non-blocking helper that erases the record and call it at all four sites.

🐛 Proposed fix
// In namespace AprShared
static void DiscardSubmission(uint32_t submission_id) {
	std::scoped_lock lock(g_mutex);
	g_submissions.erase(submission_id);
	g_submissions_done.notify_all();
}
 	if (submit_result != OK) {
-		AprShared::CompleteSubmission(id, nullptr);
+		AprShared::DiscardSubmission(id);
 		return KernelSyscallResult(submit_result);
 	}

Also applies to: 776-776, 3166-3166, 3194-3194

**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882868) On `src/libs/libAmpr.cpp` line 738 (outdated): ```diff @@ -549,38 +731,35 @@ static int KYTY_SYSV_ABI SubmitCommandBufferAndGetResult(void* command_buffe const auto id = AprShared::AllocateSubmissionId(command_buffer_addr, reinterpret_cast<uint64_t>(result)); - int32_t execution_result = OK; - uint32_t error_offset = 0; - auto submit_result = LibAmpr::Ampr::ExecuteAprCommandBuffer(command_buffer_addr, - &execution_result, &error_offset); + const auto submit_result = LibAmpr::Ampr::EnqueueCommandBuffer( + command_buffer_addr, false, static_cast<uint32_t>(priority), id, + reinterpret_cast<uint64_t>(result)); if (submit_result != OK) { + AprShared::CompleteSubmission(id, nullptr); ``` _🩺 Stability & Availability_ | _🔴 Critical_ | _⚡ Quick win_ **Enqueue-failure cleanup blocks forever in `CompleteSubmission`.** `CompleteSubmission` now waits until the record is erased or `done` is true. When `EnqueueCommandBuffer` fails, no worker runs and nothing sets `done`. The cleanup call therefore blocks the calling guest thread permanently instead of returning the error. `EnqueueCommandBuffer` returns `EFAULT` when `TryGetCommandBufferState` fails, so an invalid command-buffer header triggers this path. Add a non-blocking helper that erases the record and call it at all four sites. <details> <summary>🐛 Proposed fix</summary> ```cpp // In namespace AprShared static void DiscardSubmission(uint32_t submission_id) { std::scoped_lock lock(g_mutex); g_submissions.erase(submission_id); g_submissions_done.notify_all(); } ``` ```diff if (submit_result != OK) { - AprShared::CompleteSubmission(id, nullptr); + AprShared::DiscardSubmission(id); return KernelSyscallResult(submit_result); } ``` </details> Also applies to: 776-776, 3166-3166, 3194-3194 <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0d55007f2826d07ffc17a6f5 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/libs/libAmpr.cpp line 1251 (outdated):

@@ -1019,6 +1248,7 @@ static bool WriteCommandBufferPointers(uint64_t command_buffer, uint64_t buffer,
 	state.read_file_commands.clear();
 	state.kernel_event_commands.clear();
 	state.write_address_commands.clear();
+	state.wait_address_commands.clear();

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Clear counter_commands on reset and include it in HasQueuedCommands.

WriteCommandBufferPointers clears every command queue except counter_commands. CommandBufferReset calls it with write_offset = 0. When new records advance write_offset, stale counter commands with a smaller record_offset pass the filter in ExecuteCommandBufferState again. The next submission then replays old counter writes and waits. HasQueuedCommands at Line 1007-1008 also omits counter_commands. As a result, ResolveCommandBufferStateLocked can pick an alias state over a buffer that holds only counter commands.

🐛 Proposed fix
 	state.wait_address_commands.clear();
 	state.amm_map_commands.clear();
+	state.counter_commands.clear();
 	       !state.write_address_commands.empty() || !state.wait_address_commands.empty() ||
-	       !state.amm_map_commands.empty();
+	       !state.amm_map_commands.empty() || !state.counter_commands.empty();
**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882880) On `src/libs/libAmpr.cpp` line 1251 (outdated): ```diff @@ -1019,6 +1248,7 @@ static bool WriteCommandBufferPointers(uint64_t command_buffer, uint64_t buffer, state.read_file_commands.clear(); state.kernel_event_commands.clear(); state.write_address_commands.clear(); + state.wait_address_commands.clear(); ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Clear `counter_commands` on reset and include it in `HasQueuedCommands`.** `WriteCommandBufferPointers` clears every command queue except `counter_commands`. `CommandBufferReset` calls it with `write_offset = 0`. When new records advance `write_offset`, stale counter commands with a smaller `record_offset` pass the filter in `ExecuteCommandBufferState` again. The next submission then replays old counter writes and waits. `HasQueuedCommands` at Line 1007-1008 also omits `counter_commands`. As a result, `ResolveCommandBufferStateLocked` can pick an alias state over a buffer that holds only counter commands. <details> <summary>🐛 Proposed fix</summary> ```diff state.wait_address_commands.clear(); state.amm_map_commands.clear(); + state.counter_commands.clear(); ``` ```diff !state.write_address_commands.empty() || !state.wait_address_commands.empty() || - !state.amm_map_commands.empty(); + !state.amm_map_commands.empty() || !state.counter_commands.empty(); ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8f5eb9a0a32e248bcae1b25d --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original
On src/libs/libAmpr.cpp line 1641 (outdated):

@@ -1250,18 +1621,34 @@ static bool AllocateAmmAutoDirectMemory(uint64_t size, int memory_type, uint64_t
 		return false;
 	}
 
-	*dmem_offset = static_cast<uint64_t>(allocated);
+	*dmem_offset             = static_cast<uint64_t>(allocated);
+	g_amm_auto_mappings[va] = {*dmem_offset, size, false};
 	return true;
 }
 
+static void ReleaseAmmAutoDirectMemory(uint64_t va, uint64_t size) {
+	std::scoped_lock lock(g_amm_auto_pool_mutex);
+	auto             it = g_amm_auto_mappings.lower_bound(va);
+	while (it != g_amm_auto_mappings.end() && it->first < va + size) {
+		const auto mapping = it->second;
+		if (mapping.from_pool) {
+			AmmAutoFreeLocked(mapping.dmem_offset, mapping.size);
+		} else {
+			(void)LibKernel::Memory::KernelReleaseDirectMemory(
+			    static_cast<int64_t>(mapping.dmem_offset), mapping.size);
+		}
+		it = g_amm_auto_mappings.erase(it);
+	}

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

A partial unmap returns still-mapped direct memory to the pool.

ReleaseAmmAutoDirectMemory releases the complete mapping.size for each mapping that starts inside [va, va + size). Consider an unmap of only the first page of a 64 KiB auto mapping. The code frees all 64 KiB to g_amm_auto_free while the remaining 48 KiB are still mapped. A later AllocateAmmAutoDirectMemory can then give that range to another VA, and two live VAs alias the same physical memory. Also, lower_bound(va) misses mappings that start before va and overlap the range, so those allocations leak.

Release only the overlapping portion: [max(va, start), min(va + size, start + mapping.size)). Keep or split the remaining head and tail entries.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4076882887) On `src/libs/libAmpr.cpp` line 1641 (outdated): ```diff @@ -1250,18 +1621,34 @@ static bool AllocateAmmAutoDirectMemory(uint64_t size, int memory_type, uint64_t return false; } - *dmem_offset = static_cast<uint64_t>(allocated); + *dmem_offset = static_cast<uint64_t>(allocated); + g_amm_auto_mappings[va] = {*dmem_offset, size, false}; return true; } +static void ReleaseAmmAutoDirectMemory(uint64_t va, uint64_t size) { + std::scoped_lock lock(g_amm_auto_pool_mutex); + auto it = g_amm_auto_mappings.lower_bound(va); + while (it != g_amm_auto_mappings.end() && it->first < va + size) { + const auto mapping = it->second; + if (mapping.from_pool) { + AmmAutoFreeLocked(mapping.dmem_offset, mapping.size); + } else { + (void)LibKernel::Memory::KernelReleaseDirectMemory( + static_cast<int64_t>(mapping.dmem_offset), mapping.size); + } + it = g_amm_auto_mappings.erase(it); + } ``` _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _🏗️ Heavy lift_ **A partial unmap returns still-mapped direct memory to the pool.** `ReleaseAmmAutoDirectMemory` releases the complete `mapping.size` for each mapping that starts inside `[va, va + size)`. Consider an unmap of only the first page of a 64 KiB auto mapping. The code frees all 64 KiB to `g_amm_auto_free` while the remaining 48 KiB are still mapped. A later `AllocateAmmAutoDirectMemory` can then give that range to another VA, and two live VAs alias the same physical memory. Also, `lower_bound(va)` misses mappings that start before `va` and overlap the range, so those allocations leak. Release only the overlapping portion: `[max(va, start), min(va + size, start + mapping.size))`. Keep or split the remaining head and tail entries. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:971b271adb81ed120032b6b9 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-22 21:50 UTC · original · reviewed

Actionable comments posted: 12

Caution

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

⚠️ Outside diff range comments (1)

🟠 Major · Honor coherence for ReadConstBuffer loads. · spirvEmitterMemory.cpp:1155-1157

src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp:1155-1157
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Honor coherence for ReadConstBuffer loads.

MemoryInfoFromDecoded now sets memory.coherent for glc or slc. A coherent S_BUFFER_LOAD_* reaches this ReadConstBuffer path, but this direct OpLoad has no MemoryAccessVolatileMask. Requirement analysis also sets coherent_buffers only for BufferAccess operations, so this path can omit the Coherent descriptor decoration. These loads can observe stale buffer data.

Set the coherent-buffer requirement for coherent scalar-buffer accesses. Emit a volatile load here when access.coherent is true.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 33abf9c6-e1be-48d2-9394-4e100a3343d1

📥 Commits

Reviewing files that changed from the base of the PR and between 8b095caefe and e2264dd01cca9f02b22a382f8fa71624f61ad4b5.

📒 Files selected for processing (71)
  • CMakeLists.txt
  • src/common/CMakeLists.txt
  • src/common/assert.cpp
  • src/common/assert.h
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/guest_gpu/command_processor/pm4Handlers.cpp
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/diagnosticCheckpoints.cpp
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/memoryTracker.cpp
  • src/graphics/host_gpu/memoryTracker.h
  • src/graphics/host_gpu/regionManager.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/faultManager.cpp
  • src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/graphics/host_gpu/renderer/commandScheduler.cpp
  • src/graphics/host_gpu/renderer/commandScheduler.h
  • src/graphics/host_gpu/renderer/context.cpp
  • src/graphics/host_gpu/renderer/image/image.h
  • src/graphics/host_gpu/renderer/image/imageInfo.h
  • src/graphics/host_gpu/renderer/masterSemaphore.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/renderer/renderContext.cpp
  • src/graphics/host_gpu/renderer/renderContext.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/host_gpu/vma.cpp
  • src/graphics/presentation/videoOut.cpp
  • src/graphics/presentation/window/swapchain.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.h
  • src/graphics/shader/recompiler/Tessellation.cpp
  • src/graphics/shader/recompiler/Tessellation.h
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp
  • src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h
  • src/graphics/shader/recompiler/frontend/translate/Dispatch.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translator.h
  • src/graphics/shader/recompiler/ir/Program.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.h
  • src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtCompiler.h
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shader.h
  • src/graphics/shader/shaderCompiler.h
  • src/graphics/shader/shaderVertexMetadata.cpp
  • src/libs/agc.cpp
  • src/libs/ajm.cpp
  • src/libs/ajm/atrac9_decoder.h
  • src/libs/dialog.cpp
  • src/libs/libAmpr.cpp
  • tests/ShaderRecompilerComputeTests.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-22 21:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#pullrequestreview-5284211845) · **reviewed** **Actionable comments posted: 12** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><em>🟠 Major</em> · Honor coherence for <code>ReadConstBuffer</code> loads. · <code>spirvEmitterMemory.cpp:1155-1157</code></summary><blockquote> > > `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp:1155-1157` > _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ > > **Honor coherence for `ReadConstBuffer` loads.** > > `MemoryInfoFromDecoded` now sets `memory.coherent` for `glc` or `slc`. A coherent `S_BUFFER_LOAD_*` reaches this `ReadConstBuffer` path, but this direct `OpLoad` has no `MemoryAccessVolatileMask`. Requirement analysis also sets `coherent_buffers` only for `BufferAccess` operations, so this path can omit the `Coherent` descriptor decoration. These loads can observe stale buffer data. > > Set the coherent-buffer requirement for coherent scalar-buffer accesses. Emit a volatile load here when `access.coherent` is true. > > <!-- cr-comment:v1:bb1483d02d122e21e6e6cc0c --> > > </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**: `33abf9c6-e1be-48d2-9394-4e100a3343d1` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 8b095caefecc2b0066b1b66425d24fd90f29a609 and e2264dd01cca9f02b22a382f8fa71624f61ad4b5. </details> <details> <summary>📒 Files selected for processing (71)</summary> * `CMakeLists.txt` * `src/common/CMakeLists.txt` * `src/common/assert.cpp` * `src/common/assert.h` * `src/graphics/guest_gpu/command_processor/commandProcessor.h` * `src/graphics/guest_gpu/command_processor/pm4Handlers.cpp` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/diagnosticCheckpoints.cpp` * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/memoryTracker.cpp` * `src/graphics/host_gpu/memoryTracker.h` * `src/graphics/host_gpu/regionManager.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `src/graphics/host_gpu/renderer/cache/faultManager.cpp` * `src/graphics/host_gpu/renderer/cache/streamBuffer.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` * `src/graphics/host_gpu/renderer/commandScheduler.cpp` * `src/graphics/host_gpu/renderer/commandScheduler.h` * `src/graphics/host_gpu/renderer/context.cpp` * `src/graphics/host_gpu/renderer/image/image.h` * `src/graphics/host_gpu/renderer/image/imageInfo.h` * `src/graphics/host_gpu/renderer/masterSemaphore.cpp` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/render.h` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/renderer/renderContext.cpp` * `src/graphics/host_gpu/renderer/renderContext.h` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/host_gpu/vma.cpp` * `src/graphics/presentation/videoOut.cpp` * `src/graphics/presentation/window/swapchain.cpp` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.h` * `src/graphics/shader/recompiler/Tessellation.cpp` * `src/graphics/shader/recompiler/Tessellation.h` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp` * `src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h` * `src/graphics/shader/recompiler/frontend/translate/Dispatch.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translator.h` * `src/graphics/shader/recompiler/ir/Program.cpp` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.h` * `src/graphics/shader/recompiler/ir/passes/SrtCompiler.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtCompiler.h` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shader.h` * `src/graphics/shader/shaderCompiler.h` * `src/graphics/shader/shaderVertexMetadata.cpp` * `src/libs/agc.cpp` * `src/libs/ajm.cpp` * `src/libs/ajm/atrac9_decoder.h` * `src/libs/dialog.cpp` * `src/libs/libAmpr.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** 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 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-23 20:34 UTC · original
On src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp line 395 (outdated):

@@ -347,13 +387,42 @@ struct PipelineCache::ProgramCache {
 		} else {
 			options.wave_size = input_info.wave_size;
 		}
+		options.non_fatal = ShaderFailureNonFatal();
 		auto translated = ShaderRecompiler::TranslateProgram(params.code, options);
+		if (translated.unsupported) {
+			unsupported.insert(lookup_key);
+			return ShaderProgram {};
+		}

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C6 '\bGetGraphicsPrograms\s*\(|\bGetComputeProgram\s*\(' --type=cpp
rg -nP -C4 '\bGetGraphicsPipeline\s*\(|\bGetComputePipeline\s*\(' --type=cpp -g '!**/pipelineCache.cpp'

Repository: KytyPS5/KytyPS5

Length of output: 16868


🏁 Script executed:

#!/bin/bash
sed -n '840,915p;1035,1115p' src/graphics/host_gpu/renderer/renderDraw.cpp
sed -n '639,735p;770,850p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
sed -n '100,130p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.h

Repository: KytyPS5/KytyPS5

Length of output: 17770


🏁 Script executed:

sed -n '840,915p;1035,1115p' src/graphics/host_gpu/renderer/renderDraw.cpp
sed -n '639,735p;770,850p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
sed -n '100,130p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.h

Repository: KytyPS5/KytyPS5

Length of output: 17770


🏁 Script executed:

sed -n '735,810p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
rg -n -C8 'vertex_shader_ids|CreatePipelineInternal' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 6179


🏁 Script executed:

rg -n -C10 'CreatePipelineInternal' --type=cpp src/graphics/host_gpu

Repository: KytyPS5/KytyPS5

Length of output: 12083


🏁 Script executed:

sed -n '209,310p;330,430p' src/graphics/host_gpu/renderer/pipeline/shaders.cpp
rg -n -C8 'tess_(control|eval)_shader_module|programs\.vertex\[[12]\]' src/graphics/host_gpu/renderer/pipeline/shaders.cpp

Repository: KytyPS5/KytyPS5

Length of output: 14247


Reject draws with incomplete tessellation programs.

PrepareDrawRenderState checks only state.programs.vertex[0] and the pixel program. If vertex[1] is valid but vertex[2] is empty, VertexStageCount() returns 3. CreatePipelineInternal then builds the tessellation stage with programs.vertex[2].module, which is null. Pipeline creation can fail, and the code exits when Vulkan returns an error.

 	state.ps_active = DrawHasActivePixelShader(buffer);
 	RefreshShaders(buffer, draw, state);
-	if (!state.programs.vertex[0] || (state.ps_active && !state.programs.pixel)) {
+	const bool tess_active =
+	    buffer.GetUserConfig().GetPrimType() == Prospero::PrimitiveType::kPatch;
+	if (!state.programs.vertex[0] ||
+	    (tess_active &amp;&amp; (!state.programs.vertex[1] || !state.programs.vertex[2])) ||
+	    (state.ps_active &amp;&amp; !state.programs.pixel)) {
 		return false;
 	}

The compute paths already reject an empty compute program before calling GetComputePipeline.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-23 20:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4087028582) On `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` line 395 (outdated): ```diff @@ -347,13 +387,42 @@ struct PipelineCache::ProgramCache { } else { options.wave_size = input_info.wave_size; } + options.non_fatal = ShaderFailureNonFatal(); auto translated = ShaderRecompiler::TranslateProgram(params.code, options); + if (translated.unsupported) { + unsupported.insert(lookup_key); + return ShaderProgram {}; + } ``` _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C6 '\bGetGraphicsPrograms\s*\(|\bGetComputeProgram\s*\(' --type=cpp rg -nP -C4 '\bGetGraphicsPipeline\s*\(|\bGetComputePipeline\s*\(' --type=cpp -g '!**/pipelineCache.cpp' ``` Repository: KytyPS5/KytyPS5 Length of output: 16868 --- 🏁 Script executed: ```bash #!/bin/bash sed -n '840,915p;1035,1115p' src/graphics/host_gpu/renderer/renderDraw.cpp sed -n '639,735p;770,850p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp sed -n '100,130p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.h ``` Repository: KytyPS5/KytyPS5 Length of output: 17770 --- 🏁 Script executed: ```bash sed -n '840,915p;1035,1115p' src/graphics/host_gpu/renderer/renderDraw.cpp sed -n '639,735p;770,850p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp sed -n '100,130p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.h ``` Repository: KytyPS5/KytyPS5 Length of output: 17770 --- 🏁 Script executed: ```bash sed -n '735,810p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp rg -n -C8 'vertex_shader_ids|CreatePipelineInternal' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 6179 --- 🏁 Script executed: ```bash rg -n -C10 'CreatePipelineInternal' --type=cpp src/graphics/host_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 12083 --- 🏁 Script executed: ```bash sed -n '209,310p;330,430p' src/graphics/host_gpu/renderer/pipeline/shaders.cpp rg -n -C8 'tess_(control|eval)_shader_module|programs\.vertex\[[12]\]' src/graphics/host_gpu/renderer/pipeline/shaders.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 14247 --- </details> **Reject draws with incomplete tessellation programs.** `PrepareDrawRenderState` checks only `state.programs.vertex[0]` and the pixel program. If `vertex[1]` is valid but `vertex[2]` is empty, `VertexStageCount()` returns 3. `CreatePipelineInternal` then builds the tessellation stage with `programs.vertex[2].module`, which is null. Pipeline creation can fail, and the code exits when Vulkan returns an error. ```diff state.ps_active = DrawHasActivePixelShader(buffer); RefreshShaders(buffer, draw, state); - if (!state.programs.vertex[0] || (state.ps_active && !state.programs.pixel)) { + const bool tess_active = + buffer.GetUserConfig().GetPrimType() == Prospero::PrimitiveType::kPatch; + if (!state.programs.vertex[0] || + (tess_active &amp;&amp; (!state.programs.vertex[1] || !state.programs.vertex[2])) || + (state.ps_active &amp;&amp; !state.programs.pixel)) { return false; } ``` The compute paths already reject an empty compute program before calling `GetComputePipeline`. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:710d2a04fc5b63c5121f3e19 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-23 20:34 UTC · original
On src/graphics/presentation/window/vulkanWindow.cpp line 698 (outdated):

@@ -669,6 +683,47 @@ static vk::Device VulkanCreateDevice(GraphicContext& graphics,
 		provoking_vertex.transformFeedbackPreservesProvokingVertex = VK_FALSE;
 		create_info.pNext = &provoking_vertex;
 	}
+	vk::DeviceDiagnosticsConfigCreateInfoNV diagnostics_config {};
+	if (HasExtension(device_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) {
+		vk::PhysicalDeviceDiagnosticsConfigFeaturesNV supported_diagnostics {};
+		vk::PhysicalDeviceFeatures2                   diagnostics_query {};
+		diagnostics_query.pNext = &supported_diagnostics;
+		physical_device.getFeatures2(&diagnostics_query);
+		if (supported_diagnostics.diagnosticsConfig) {
+			diagnostics_config.flags =
+			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderDebugInfo |
+			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableResourceTracking |
+			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderErrorReporting;
+			diagnostics_config.pNext = const_cast<void*>(create_info.pNext);
+			create_info.pNext        = &diagnostics_config;

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Enable diagnosticsConfig with the diagnostic flags.

When supported_diagnostics.diagnosticsConfig is true, this branch chains vk::DeviceDiagnosticsConfigCreateInfoNV but never enables vk::PhysicalDeviceDiagnosticsConfigFeaturesNV::diagnosticsConfig on the created device. The support query does not enable the feature. Chain the feature with diagnosticsConfig = VK_TRUE before requesting the flags; otherwise the requested diagnostic configuration cannot be relied on. (docs.vulkan.org)

**@⁠coderabbitai[bot]** on GitHub · 2026-09-23 20:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4087028591) On `src/graphics/presentation/window/vulkanWindow.cpp` line 698 (outdated): ```diff @@ -669,6 +683,47 @@ static vk::Device VulkanCreateDevice(GraphicContext& graphics, provoking_vertex.transformFeedbackPreservesProvokingVertex = VK_FALSE; create_info.pNext = &provoking_vertex; } + vk::DeviceDiagnosticsConfigCreateInfoNV diagnostics_config {}; + if (HasExtension(device_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) { + vk::PhysicalDeviceDiagnosticsConfigFeaturesNV supported_diagnostics {}; + vk::PhysicalDeviceFeatures2 diagnostics_query {}; + diagnostics_query.pNext = &supported_diagnostics; + physical_device.getFeatures2(&diagnostics_query); + if (supported_diagnostics.diagnosticsConfig) { + diagnostics_config.flags = + vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderDebugInfo | + vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableResourceTracking | + vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderErrorReporting; + diagnostics_config.pNext = const_cast<void*>(create_info.pNext); + create_info.pNext = &diagnostics_config; ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Enable `diagnosticsConfig` with the diagnostic flags.** When `supported_diagnostics.diagnosticsConfig` is true, this branch chains `vk::DeviceDiagnosticsConfigCreateInfoNV` but never enables `vk::PhysicalDeviceDiagnosticsConfigFeaturesNV::diagnosticsConfig` on the created device. The support query does not enable the feature. Chain the feature with `diagnosticsConfig = VK_TRUE` before requesting the flags; otherwise the requested diagnostic configuration cannot be relied on. ([docs.vulkan.org](https://docs.vulkan.org/refpages/latest/refpages/source/VkPhysicalDeviceDiagnosticsConfigFeaturesNV.html?utm_source=openai)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c16ed44977ed734a088f9329 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-23 20:34 UTC · original
On src/libs/ajm/atrac9_decoder.h line 110 (outdated):

@@ -103,25 +104,49 @@ class AjmAt9Decoder final: public AjmDecoder {
 			return result;
 		}
 
+		const size_t pending_size = m_pending.size();
+		if (pending_size != 0) {
+			m_pending.insert(m_pending.end(), static_cast<const uint8_t*>(input),
+			                 static_cast<const uint8_t*>(input) + input_size);

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Clear pending input on explicit reinitialization.

If a decode buffers an incomplete superframe, an explicit Initialize call leaves m_pending intact. The next Decode call prepends old-stream bytes to the new stream. This can corrupt playback or cause a codec error. Clear m_pending in AjmAt9Decoder::Initialize when it accepts a new configuration. Do not clear it in InitializeConfig: RIFF parsing also calls that function while reading buffered input. The AJM initialization paths in src/libs/ajm.cpp do not require a preceding Reset. (raw.githubusercontent.com)

**@⁠coderabbitai[bot]** on GitHub · 2026-09-23 20:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4087028597) On `src/libs/ajm/atrac9_decoder.h` line 110 (outdated): ```diff @@ -103,25 +104,49 @@ class AjmAt9Decoder final: public AjmDecoder { return result; } + const size_t pending_size = m_pending.size(); + if (pending_size != 0) { + m_pending.insert(m_pending.end(), static_cast<const uint8_t*>(input), + static_cast<const uint8_t*>(input) + input_size); ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Clear pending input on explicit reinitialization.** If a decode buffers an incomplete superframe, an explicit `Initialize` call leaves `m_pending` intact. The next `Decode` call prepends old-stream bytes to the new stream. This can corrupt playback or cause a codec error. Clear `m_pending` in `AjmAt9Decoder::Initialize` when it accepts a new configuration. Do not clear it in `InitializeConfig`: RIFF parsing also calls that function while reading buffered input. The AJM initialization paths in `src/libs/ajm.cpp` do not require a preceding `Reset`. ([raw.githubusercontent.com](https://raw.githubusercontent.com/itsmemac/KytyPS5/spiderman-running-22-09-2026/src/libs/ajm/atrac9_decoder.h)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:7e9fe65416bb41001c3c82d2 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-23 20:34 UTC · original · reviewed

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 1b996e99-ea42-4606-b696-fb19fd9a6c43

📥 Commits

Reviewing files that changed from the base of the PR and between e2264dd01cca9f02b22a382f8fa71624f61ad4b5 and 652517b99c143732db13cf988738a1c095fadd23.

📒 Files selected for processing (21)
  • CMakeLists.txt
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/masterSemaphore.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/presentation/videoOut.cpp
  • src/graphics/presentation/videoOut.h
  • src/graphics/presentation/window/swapchain.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shaderCompiler.h
  • src/libs/ajm/atrac9_decoder.h
  • src/libs/libAmpr.cpp
  • tests/ShaderRecompilerComputeTests.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-23 20:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#pullrequestreview-5296468711) · **reviewed** **Actionable comments posted: 3** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `1b996e99-ea42-4606-b696-fb19fd9a6c43` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between e2264dd01cca9f02b22a382f8fa71624f61ad4b5 and 652517b99c143732db13cf988738a1c095fadd23. </details> <details> <summary>📒 Files selected for processing (21)</summary> * `CMakeLists.txt` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/masterSemaphore.cpp` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/presentation/videoOut.cpp` * `src/graphics/presentation/videoOut.h` * `src/graphics/presentation/window/swapchain.cpp` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shaderCompiler.h` * `src/libs/ajm/atrac9_decoder.h` * `src/libs/libAmpr.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** 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 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 10:50 UTC · original
On src/graphics/presentation/videoOut.cpp line 1685 (outdated):

@@ -1680,18 +1682,10 @@ KYTY_SYSV_ABI int VideoOutGetOutputStatus(int handle, VideoOutOutputStatus* stat
 	return OK;
 }
 
-KYTY_SYSV_ABI int VideoOutGetVrrStatus(int handle, int32_t* status) {
+KYTY_SYSV_ABI int VideoOutGetVrrStatus() {

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- diff ---'
git diff --no-ext-diff --unified=30 db7745ef414b0e04afca7be9ead71434033f6051 998adaae5d306d26203c5e47a2a58e6b48c39d53 -- src/graphics/presentation/videoOut.cpp
printf '%s\n' '--- symbol occurrences ---'
rg -n -C 4 'VideoOutGetVrrStatus|GetVrrStatus' .
printf '%s\n' '--- changed-file declarations around target ---'
sed -n '1640,1715p' src/graphics/presentation/videoOut.cpp

Repository: KytyPS5/KytyPS5

Length of output: 8662


🏁 Script executed:

set -eu
printf '%s\n' '--- base declaration ---'
git show db7745ef414b0e04afca7be9ead71434033f6051:src/graphics/presentation/videoOut.h | sed -n '70,100p'
printf '%s\n' '--- current declaration and library context ---'
sed -n '70,100p' src/graphics/presentation/videoOut.h
sed -n '1,75p' src/libs/libVideoOut.cpp
printf '%s\n' '--- base/current VRR references in tracked files ---'
git grep -n -i -E 'vrr|VideoOutVrrStatus|kP2L8t3j-aM' db7745ef414b0e04afca7be9ead71434033f6051 -- ':!*.git' || true
printf '%s\n' '--- registration macro definitions/usages ---'
rg -n -C 5 'define[[:space:]]+LIB_FUNC|LIB_FUNC\\(' src | head -200

Repository: KytyPS5/KytyPS5

Length of output: 9548


Preserve the VRR-status output contract.

The registered symbol and VideoOutVrrStatus version are unchanged. A caller using the previous ABI can pass a handle and status pointer, but this function ignores both, returns OK, and leaves the status unchanged. Restore the previous parameters and validation.

Suggested fix
-KYTY_SYSV_ABI int VideoOutGetVrrStatus() {
+KYTY_SYSV_ABI int VideoOutGetVrrStatus(int handle, int32_t* status) {
 	PRINT_NAME();

 	// Kyty currently presents at a fixed refresh rate and does not negotiate VRR.
+	if (status == nullptr) {
+		return VIDEO_OUT_ERROR_INVALID_ADDRESS;
+	}
+	if (DriverState().Get(handle) == nullptr) {
+		return VIDEO_OUT_ERROR_INVALID_HANDLE;
+	}
+	*status = 0;
 	return OK;
 }
**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 10:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4092733804) On `src/graphics/presentation/videoOut.cpp` line 1685 (outdated): ```diff @@ -1680,18 +1682,10 @@ KYTY_SYSV_ABI int VideoOutGetOutputStatus(int handle, VideoOutOutputStatus* stat return OK; } -KYTY_SYSV_ABI int VideoOutGetVrrStatus(int handle, int32_t* status) { +KYTY_SYSV_ABI int VideoOutGetVrrStatus() { ``` _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -eu printf '%s\n' '--- diff ---' git diff --no-ext-diff --unified=30 db7745ef414b0e04afca7be9ead71434033f6051 998adaae5d306d26203c5e47a2a58e6b48c39d53 -- src/graphics/presentation/videoOut.cpp printf '%s\n' '--- symbol occurrences ---' rg -n -C 4 'VideoOutGetVrrStatus|GetVrrStatus' . printf '%s\n' '--- changed-file declarations around target ---' sed -n '1640,1715p' src/graphics/presentation/videoOut.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 8662 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- base declaration ---' git show db7745ef414b0e04afca7be9ead71434033f6051:src/graphics/presentation/videoOut.h | sed -n '70,100p' printf '%s\n' '--- current declaration and library context ---' sed -n '70,100p' src/graphics/presentation/videoOut.h sed -n '1,75p' src/libs/libVideoOut.cpp printf '%s\n' '--- base/current VRR references in tracked files ---' git grep -n -i -E 'vrr|VideoOutVrrStatus|kP2L8t3j-aM' db7745ef414b0e04afca7be9ead71434033f6051 -- ':!*.git' || true printf '%s\n' '--- registration macro definitions/usages ---' rg -n -C 5 'define[[:space:]]+LIB_FUNC|LIB_FUNC\\(' src | head -200 ``` Repository: KytyPS5/KytyPS5 Length of output: 9548 --- </details> **Preserve the VRR-status output contract.** The registered symbol and `VideoOutVrrStatus` version are unchanged. A caller using the previous ABI can pass a handle and status pointer, but this function ignores both, returns `OK`, and leaves the status unchanged. Restore the previous parameters and validation. <details> <summary>Suggested fix</summary> ```diff -KYTY_SYSV_ABI int VideoOutGetVrrStatus() { +KYTY_SYSV_ABI int VideoOutGetVrrStatus(int handle, int32_t* status) { PRINT_NAME(); // Kyty currently presents at a fixed refresh rate and does not negotiate VRR. + if (status == nullptr) { + return VIDEO_OUT_ERROR_INVALID_ADDRESS; + } + if (DriverState().Get(handle) == nullptr) { + return VIDEO_OUT_ERROR_INVALID_HANDLE; + } + *status = 0; return OK; } ``` </details> <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:cb2cec0380e72ce7b8cef3b9 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 10:50 UTC · original
On src/graphics/presentation/window/vulkanWindow.cpp line 703 (outdated):

@@ -669,6 +683,50 @@ static vk::Device VulkanCreateDevice(GraphicContext& graphics,
 		provoking_vertex.transformFeedbackPreservesProvokingVertex = VK_FALSE;
 		create_info.pNext = &provoking_vertex;
 	}
+	vk::DeviceDiagnosticsConfigCreateInfoNV       diagnostics_config {};
+	vk::PhysicalDeviceDiagnosticsConfigFeaturesNV diagnostics_features {};
+	if (HasExtension(device_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) {
+		vk::PhysicalDeviceDiagnosticsConfigFeaturesNV supported_diagnostics {};
+		vk::PhysicalDeviceFeatures2                   diagnostics_query {};
+		diagnostics_query.pNext = &supported_diagnostics;
+		physical_device.getFeatures2(&diagnostics_query);
+		if (supported_diagnostics.diagnosticsConfig) {
+			diagnostics_config.flags =
+			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderDebugInfo |
+			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableResourceTracking |
+			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderErrorReporting;
+			diagnostics_features.diagnosticsConfig = VK_TRUE;
+			diagnostics_features.pNext             = const_cast<void*>(create_info.pNext);
+			diagnostics_config.pNext               = &diagnostics_features;
+			create_info.pNext                      = &diagnostics_config;
+		}
+	}

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- PR diff ---'
git diff --unified=25 db7745ef414b0e04afca7be9ead71434033f6051 998adaae5d306d26203c5e47a2a58e6b48c39d53 -- src/graphics/presentation/window/vulkanWindow.cpp
printf '%s\n' '--- relevant source ranges ---'
sed -n '660,735p' src/graphics/presentation/window/vulkanWindow.cpp
sed -n '1065,1110p' src/graphics/presentation/window/vulkanWindow.cpp
printf '%s\n' '--- diagnostics/checkpoint bindings ---'
rg -n -C 8 'SetDebugInfo|setCheckpointNV|VK_NV_device_diagnostic_checkpoints|VK_NV_device_diagnostics_config|DeviceDiagnosticsConfigFlagBitsNV|GpuCrash|CrashDiagnostics' src

Repository: KytyPS5/KytyPS5

Length of output: 43057


Gate NV diagnostics configuration behind a runtime option.

The code enables all three NV diagnostics flags whenever the device exposes VK_NV_device_diagnostics_config. It also enables the checkpoint extension without a runtime gate. Normal rendering can therefore perform diagnostic work without a crash-diagnostics opt-in.

Enable these features and extensions only when a GPU crash-diagnostics option is enabled.

♻️ Suggested gating
-		if (HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME)) {
+		if (Config::GpuCrashDiagnosticsEnabled() &&
+		    HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME)) {
 			device_extensions.push_back(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME);
 			graphic_ctx.diagnostic_checkpoints_enabled = true;
 		}
...
-		if (HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) {
+		if (Config::GpuCrashDiagnosticsEnabled() &&
+		    HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) {
 			device_extensions.push_back(VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME);
 		}

Apply the same condition to the diagnostics feature branch. Config::GpuCrashDiagnosticsEnabled is a suggested name.

📝 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.

	vk::DeviceDiagnosticsConfigCreateInfoNV       diagnostics_config {};
	vk::PhysicalDeviceDiagnosticsConfigFeaturesNV diagnostics_features {};
	if (Config::GpuCrashDiagnosticsEnabled() &&
	    HasExtension(device_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) {
		vk::PhysicalDeviceDiagnosticsConfigFeaturesNV supported_diagnostics {};
		vk::PhysicalDeviceFeatures2                   diagnostics_query {};
		diagnostics_query.pNext = &supported_diagnostics;
		physical_device.getFeatures2(&diagnostics_query);
		if (supported_diagnostics.diagnosticsConfig) {
			diagnostics_config.flags =
			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderDebugInfo |
			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableResourceTracking |
			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderErrorReporting;
			diagnostics_features.diagnosticsConfig = VK_TRUE;
			diagnostics_features.pNext             = const_cast<void*>(create_info.pNext);
			diagnostics_config.pNext               = &diagnostics_features;
			create_info.pNext                      = &diagnostics_config;
		}
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 10:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4092733812) On `src/graphics/presentation/window/vulkanWindow.cpp` line 703 (outdated): ```diff @@ -669,6 +683,50 @@ static vk::Device VulkanCreateDevice(GraphicContext& graphics, provoking_vertex.transformFeedbackPreservesProvokingVertex = VK_FALSE; create_info.pNext = &provoking_vertex; } + vk::DeviceDiagnosticsConfigCreateInfoNV diagnostics_config {}; + vk::PhysicalDeviceDiagnosticsConfigFeaturesNV diagnostics_features {}; + if (HasExtension(device_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) { + vk::PhysicalDeviceDiagnosticsConfigFeaturesNV supported_diagnostics {}; + vk::PhysicalDeviceFeatures2 diagnostics_query {}; + diagnostics_query.pNext = &supported_diagnostics; + physical_device.getFeatures2(&diagnostics_query); + if (supported_diagnostics.diagnosticsConfig) { + diagnostics_config.flags = + vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderDebugInfo | + vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableResourceTracking | + vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderErrorReporting; + diagnostics_features.diagnosticsConfig = VK_TRUE; + diagnostics_features.pNext = const_cast<void*>(create_info.pNext); + diagnostics_config.pNext = &diagnostics_features; + create_info.pNext = &diagnostics_config; + } + } ``` _🚀 Performance & Scalability_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -eu printf '%s\n' '--- PR diff ---' git diff --unified=25 db7745ef414b0e04afca7be9ead71434033f6051 998adaae5d306d26203c5e47a2a58e6b48c39d53 -- src/graphics/presentation/window/vulkanWindow.cpp printf '%s\n' '--- relevant source ranges ---' sed -n '660,735p' src/graphics/presentation/window/vulkanWindow.cpp sed -n '1065,1110p' src/graphics/presentation/window/vulkanWindow.cpp printf '%s\n' '--- diagnostics/checkpoint bindings ---' rg -n -C 8 'SetDebugInfo|setCheckpointNV|VK_NV_device_diagnostic_checkpoints|VK_NV_device_diagnostics_config|DeviceDiagnosticsConfigFlagBitsNV|GpuCrash|CrashDiagnostics' src ``` Repository: KytyPS5/KytyPS5 Length of output: 43057 --- </details> **Gate NV diagnostics configuration behind a runtime option.** The code enables all three NV diagnostics flags whenever the device exposes `VK_NV_device_diagnostics_config`. It also enables the checkpoint extension without a runtime gate. Normal rendering can therefore perform diagnostic work without a crash-diagnostics opt-in. Enable these features and extensions only when a GPU crash-diagnostics option is enabled. <details> <summary>♻️ Suggested gating</summary> ```diff - if (HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME)) { + if (Config::GpuCrashDiagnosticsEnabled() && + HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME)) { device_extensions.push_back(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME); graphic_ctx.diagnostic_checkpoints_enabled = true; } ... - if (HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) { + if (Config::GpuCrashDiagnosticsEnabled() && + HasExtension(available_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) { device_extensions.push_back(VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME); } ``` Apply the same condition to the diagnostics feature branch. `Config::GpuCrashDiagnosticsEnabled` is a suggested name. </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 vk::DeviceDiagnosticsConfigCreateInfoNV diagnostics_config {}; vk::PhysicalDeviceDiagnosticsConfigFeaturesNV diagnostics_features {}; if (Config::GpuCrashDiagnosticsEnabled() && HasExtension(device_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) { vk::PhysicalDeviceDiagnosticsConfigFeaturesNV supported_diagnostics {}; vk::PhysicalDeviceFeatures2 diagnostics_query {}; diagnostics_query.pNext = &supported_diagnostics; physical_device.getFeatures2(&diagnostics_query); if (supported_diagnostics.diagnosticsConfig) { diagnostics_config.flags = vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderDebugInfo | vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableResourceTracking | vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderErrorReporting; diagnostics_features.diagnosticsConfig = VK_TRUE; diagnostics_features.pNext = const_cast<void*>(create_info.pNext); diagnostics_config.pNext = &diagnostics_features; create_info.pNext = &diagnostics_config; } } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:696945d43b5c5dd2350dddbf --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 10:50 UTC · original
On src/graphics/presentation/window/vulkanWindow.cpp line 729 (outdated):

@@ -669,6 +683,50 @@ static vk::Device VulkanCreateDevice(GraphicContext& graphics,
 		provoking_vertex.transformFeedbackPreservesProvokingVertex = VK_FALSE;
 		create_info.pNext = &provoking_vertex;
 	}
+	vk::DeviceDiagnosticsConfigCreateInfoNV       diagnostics_config {};
+	vk::PhysicalDeviceDiagnosticsConfigFeaturesNV diagnostics_features {};
+	if (HasExtension(device_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) {
+		vk::PhysicalDeviceDiagnosticsConfigFeaturesNV supported_diagnostics {};
+		vk::PhysicalDeviceFeatures2                   diagnostics_query {};
+		diagnostics_query.pNext = &supported_diagnostics;
+		physical_device.getFeatures2(&diagnostics_query);
+		if (supported_diagnostics.diagnosticsConfig) {
+			diagnostics_config.flags =
+			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderDebugInfo |
+			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableResourceTracking |
+			    vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderErrorReporting;
+			diagnostics_features.diagnosticsConfig = VK_TRUE;
+			diagnostics_features.pNext             = const_cast<void*>(create_info.pNext);
+			diagnostics_config.pNext               = &diagnostics_features;
+			create_info.pNext                      = &diagnostics_config;
+		}
+	}
+	vk::PhysicalDeviceShaderClockFeaturesKHR shader_clock {};
+	if (HasExtension(device_extensions, VK_KHR_SHADER_CLOCK_EXTENSION_NAME)) {
+		vk::PhysicalDeviceShaderClockFeaturesKHR supported_clock {};
+		vk::PhysicalDeviceFeatures2              clock_query {};
+		clock_query.pNext = &supported_clock;
+		physical_device.getFeatures2(&clock_query);
+		if (supported_clock.shaderDeviceClock) {
+			shader_clock.shaderDeviceClock       = VK_TRUE;
+			shader_clock.pNext                   = const_cast<void*>(create_info.pNext);
+			create_info.pNext                    = &shader_clock;
+			graphics.shader_device_clock_enabled = true;
+		}
+	}
+	vk::PhysicalDeviceFaultFeaturesEXT device_fault {};
+	if (HasExtension(device_extensions, VK_EXT_DEVICE_FAULT_EXTENSION_NAME)) {
+		vk::PhysicalDeviceFaultFeaturesEXT supported_fault {};
+		vk::PhysicalDeviceFeatures2        fault_query {};
+		fault_query.pNext = &supported_fault;
+		physical_device.getFeatures2(&fault_query);
+		if (supported_fault.deviceFault) {
+			device_fault.deviceFault      = VK_TRUE;
+			device_fault.pNext            = const_cast<void*>(create_info.pNext);
+			create_info.pNext             = &device_fault;
+			graphics.device_fault_enabled = true;
+		}
+	}

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Turn on deviceFaultVendorBinary so the vendor dump in DumpDeviceFault can run.

This branch turns on only deviceFault. DumpDeviceFault in src/graphics/host_gpu/diagnosticCheckpoints.cpp allocates counts.vendorBinarySize bytes and writes _device_fault.nv-gpudmp. Under VK_EXT_device_fault, the implementation returns vendorBinarySize == 0 when deviceFaultVendorBinary is not enabled. As a result, the vendor binary dump never runs.

If supported_fault.deviceFaultVendorBinary is true, set the same feature on device_fault.

🐛 Proposed fix
 		if (supported_fault.deviceFault) {
 			device_fault.deviceFault      = VK_TRUE;
+			device_fault.deviceFaultVendorBinary = supported_fault.deviceFaultVendorBinary;
 			device_fault.pNext            = const_cast<void*>(create_info.pNext);
📝 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.

	vk::PhysicalDeviceFaultFeaturesEXT device_fault {};
	if (HasExtension(device_extensions, VK_EXT_DEVICE_FAULT_EXTENSION_NAME)) {
		vk::PhysicalDeviceFaultFeaturesEXT supported_fault {};
		vk::PhysicalDeviceFeatures2        fault_query {};
		fault_query.pNext = &supported_fault;
		physical_device.getFeatures2(&fault_query);
		if (supported_fault.deviceFault) {
			device_fault.deviceFault      = VK_TRUE;
			device_fault.deviceFaultVendorBinary = supported_fault.deviceFaultVendorBinary;
			device_fault.pNext            = const_cast<void*>(create_info.pNext);
			create_info.pNext             = &device_fault;
			graphics.device_fault_enabled = true;
		}
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 10:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4092733831) On `src/graphics/presentation/window/vulkanWindow.cpp` line 729 (outdated): ```diff @@ -669,6 +683,50 @@ static vk::Device VulkanCreateDevice(GraphicContext& graphics, provoking_vertex.transformFeedbackPreservesProvokingVertex = VK_FALSE; create_info.pNext = &provoking_vertex; } + vk::DeviceDiagnosticsConfigCreateInfoNV diagnostics_config {}; + vk::PhysicalDeviceDiagnosticsConfigFeaturesNV diagnostics_features {}; + if (HasExtension(device_extensions, VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME)) { + vk::PhysicalDeviceDiagnosticsConfigFeaturesNV supported_diagnostics {}; + vk::PhysicalDeviceFeatures2 diagnostics_query {}; + diagnostics_query.pNext = &supported_diagnostics; + physical_device.getFeatures2(&diagnostics_query); + if (supported_diagnostics.diagnosticsConfig) { + diagnostics_config.flags = + vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderDebugInfo | + vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableResourceTracking | + vk::DeviceDiagnosticsConfigFlagBitsNV::eEnableShaderErrorReporting; + diagnostics_features.diagnosticsConfig = VK_TRUE; + diagnostics_features.pNext = const_cast<void*>(create_info.pNext); + diagnostics_config.pNext = &diagnostics_features; + create_info.pNext = &diagnostics_config; + } + } + vk::PhysicalDeviceShaderClockFeaturesKHR shader_clock {}; + if (HasExtension(device_extensions, VK_KHR_SHADER_CLOCK_EXTENSION_NAME)) { + vk::PhysicalDeviceShaderClockFeaturesKHR supported_clock {}; + vk::PhysicalDeviceFeatures2 clock_query {}; + clock_query.pNext = &supported_clock; + physical_device.getFeatures2(&clock_query); + if (supported_clock.shaderDeviceClock) { + shader_clock.shaderDeviceClock = VK_TRUE; + shader_clock.pNext = const_cast<void*>(create_info.pNext); + create_info.pNext = &shader_clock; + graphics.shader_device_clock_enabled = true; + } + } + vk::PhysicalDeviceFaultFeaturesEXT device_fault {}; + if (HasExtension(device_extensions, VK_EXT_DEVICE_FAULT_EXTENSION_NAME)) { + vk::PhysicalDeviceFaultFeaturesEXT supported_fault {}; + vk::PhysicalDeviceFeatures2 fault_query {}; + fault_query.pNext = &supported_fault; + physical_device.getFeatures2(&fault_query); + if (supported_fault.deviceFault) { + device_fault.deviceFault = VK_TRUE; + device_fault.pNext = const_cast<void*>(create_info.pNext); + create_info.pNext = &device_fault; + graphics.device_fault_enabled = true; + } + } ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Turn on `deviceFaultVendorBinary` so the vendor dump in `DumpDeviceFault` can run.** This branch turns on only `deviceFault`. `DumpDeviceFault` in `src/graphics/host_gpu/diagnosticCheckpoints.cpp` allocates `counts.vendorBinarySize` bytes and writes `_device_fault.nv-gpudmp`. Under `VK_EXT_device_fault`, the implementation returns `vendorBinarySize == 0` when `deviceFaultVendorBinary` is not enabled. As a result, the vendor binary dump never runs. If `supported_fault.deviceFaultVendorBinary` is true, set the same feature on `device_fault`. <details> <summary>🐛 Proposed fix</summary> ```diff if (supported_fault.deviceFault) { device_fault.deviceFault = VK_TRUE; + device_fault.deviceFaultVendorBinary = supported_fault.deviceFaultVendorBinary; device_fault.pNext = const_cast<void*>(create_info.pNext); ``` </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 vk::PhysicalDeviceFaultFeaturesEXT device_fault {}; if (HasExtension(device_extensions, VK_EXT_DEVICE_FAULT_EXTENSION_NAME)) { vk::PhysicalDeviceFaultFeaturesEXT supported_fault {}; vk::PhysicalDeviceFeatures2 fault_query {}; fault_query.pNext = &supported_fault; physical_device.getFeatures2(&fault_query); if (supported_fault.deviceFault) { device_fault.deviceFault = VK_TRUE; device_fault.deviceFaultVendorBinary = supported_fault.deviceFaultVendorBinary; device_fault.pNext = const_cast<void*>(create_info.pNext); create_info.pNext = &device_fault; graphics.device_fault_enabled = true; } } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:09d7c296744276e0d45eceef --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 10:50 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp line 1171 (outdated):

@@ -1153,8 +1162,14 @@ void EmitReadConstBuffer(ValueEmitContext& ctx, const IR::Inst& inst) {
 	const auto element   = EmitMemoryElementIndex(state, access, index);
 	const auto condition = EmitMemoryElementInBounds(state, access, element);
 	ctx.Define(inst, EmitValueOrZeroIfCondition(state, condition, [&]() {
-		           return EmitNative<spv::OpLoad, IR::Type::U32>(
-		               state, EmitMemoryElementPointer(state, access, element));
+		           const auto pointer = EmitMemoryElementPointer(state, access, element);
+		           if (!access.coherent) {
+			           return EmitNative<spv::OpLoad, IR::Type::U32>(state, pointer);
+		           }
+		           const auto value = state.builder.AllocateId();
+		           state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer,
+		                                     spv::MemoryAccessVolatileMask);

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Set the coherent-buffer requirement for scalar-buffer loads.

If a shader uses a GLC/SLC S_BUFFER_LOAD_* without a coherent vector-buffer access, this branch emits a volatile load, but AnalyzeProgramRequirements does not set coherent_buffers for ResourceKind::ScalarBuffer. DefineDescriptors therefore omits the buffer descriptor’s Coherent decoration. Volatile prevents the load from being eliminated or combined; it does not declare the buffer coherent. Include coherent scalar-buffer loads in requirement analysis so polling loads can observe writes from other invocations. (raw.githubusercontent.com)

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 10:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4092733845) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` line 1171 (outdated): ```diff @@ -1153,8 +1162,14 @@ void EmitReadConstBuffer(ValueEmitContext& ctx, const IR::Inst& inst) { const auto element = EmitMemoryElementIndex(state, access, index); const auto condition = EmitMemoryElementInBounds(state, access, element); ctx.Define(inst, EmitValueOrZeroIfCondition(state, condition, [&]() { - return EmitNative<spv::OpLoad, IR::Type::U32>( - state, EmitMemoryElementPointer(state, access, element)); + const auto pointer = EmitMemoryElementPointer(state, access, element); + if (!access.coherent) { + return EmitNative<spv::OpLoad, IR::Type::U32>(state, pointer); + } + const auto value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, + spv::MemoryAccessVolatileMask); ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Set the coherent-buffer requirement for scalar-buffer loads.** If a shader uses a GLC/SLC `S_BUFFER_LOAD_*` without a coherent vector-buffer access, this branch emits a volatile load, but `AnalyzeProgramRequirements` does not set `coherent_buffers` for `ResourceKind::ScalarBuffer`. `DefineDescriptors` therefore omits the buffer descriptor’s `Coherent` decoration. Volatile prevents the load from being eliminated or combined; it does not declare the buffer coherent. Include coherent scalar-buffer loads in requirement analysis so polling loads can observe writes from other invocations. ([raw.githubusercontent.com](https://raw.githubusercontent.com/itsmemac/KytyPS5/spiderman-running-22-09-2026/src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:2c155e14359c92426f751f88 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 10:50 UTC · original
On src/libs/libSaveData.cpp line 419 (outdated):

@@ -408,7 +413,10 @@ static int64_t newest_save_time(const std::filesystem::path& directory) {
 
 static int load_save_param(const std::filesystem::path& directory, SaveDataParam* param) {
 	*param = {};
-	const int status = read_save_param(save_param_path(directory), param);
+	int status = read_save_param(save_param_path(directory), param);
+	if (status == SAVE_DATA_ERROR_NOT_FOUND && is_legacy_save(directory)) {
+		status = OK;
+	}

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Initialize metadata when a legacy save is updated.

This fallback lets a guest read parameters from a mounted legacy save, but SaveDataSetParam cannot update them. Parameter types 1–4 return SAVE_DATA_ERROR_NOT_FOUND when they read the missing param.bin. A type-0 update fails because write_save_file cannot create its temporary file inside the missing sce_sys directory. Initialize the metadata on the first parameter write so a discovered legacy save remains writable.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 10:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4092733857) On `src/libs/libSaveData.cpp` line 419 (outdated): ```diff @@ -408,7 +413,10 @@ static int64_t newest_save_time(const std::filesystem::path& directory) { static int load_save_param(const std::filesystem::path& directory, SaveDataParam* param) { *param = {}; - const int status = read_save_param(save_param_path(directory), param); + int status = read_save_param(save_param_path(directory), param); + if (status == SAVE_DATA_ERROR_NOT_FOUND && is_legacy_save(directory)) { + status = OK; + } ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Initialize metadata when a legacy save is updated.** This fallback lets a guest read parameters from a mounted legacy save, but `SaveDataSetParam` cannot update them. Parameter types 1–4 return `SAVE_DATA_ERROR_NOT_FOUND` when they read the missing `param.bin`. A type-0 update fails because `write_save_file` cannot create its temporary file inside the missing `sce_sys` directory. Initialize the metadata on the first parameter write so a discovered legacy save remains writable. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:5f13e42ecbd906a197dcce5c --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 10:50 UTC · original
On src/libs/libSaveData.cpp line 609 (outdated):

@@ -597,7 +605,8 @@ int KYTY_SYSV_ABI SaveDataDirNameSearch(const SaveDataDirNameSearchCond* cond,
 		for (const auto& entry: Common::File::GetDirEntries(root)) {
 			if (!entry.is_file && entry.name != "." && entry.name != ".." &&
 			    !entry.name.starts_with("sce_") && valid_path_component(entry.name) &&
-			    Common::File::IsFileExisting(save_param_path(root / entry.name))) {
+			    (Common::File::IsFileExisting(save_param_path(root / entry.name)) ||
+			     is_legacy_save(root / entry.name))) {

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Return allocation information for legacy saves.

If a caller requests result->infos, this search now includes a legacy save, then calls read_save_blocks for that save at Line 649. A legacy save has no sce_sys/blocks.bin, so the entire search returns SAVE_DATA_ERROR_BROKEN. Supply a defined allocation value for legacy saves before including them in searches that request infos.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 10:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#discussion_r4092733865) On `src/libs/libSaveData.cpp` line 609 (outdated): ```diff @@ -597,7 +605,8 @@ int KYTY_SYSV_ABI SaveDataDirNameSearch(const SaveDataDirNameSearchCond* cond, for (const auto& entry: Common::File::GetDirEntries(root)) { if (!entry.is_file && entry.name != "." && entry.name != ".." && !entry.name.starts_with("sce_") && valid_path_component(entry.name) && - Common::File::IsFileExisting(save_param_path(root / entry.name))) { + (Common::File::IsFileExisting(save_param_path(root / entry.name)) || + is_legacy_save(root / entry.name))) { ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Return allocation information for legacy saves.** If a caller requests `result->infos`, this search now includes a legacy save, then calls `read_save_blocks` for that save at Line 649. A legacy save has no `sce_sys/blocks.bin`, so the entire search returns `SAVE_DATA_ERROR_BROKEN`. Supply a defined allocation value for legacy saves before including them in searches that request `infos`. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:82c5d25ce9df786b24ebd804 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 10:50 UTC · original · reviewed

Actionable comments posted: 6

Caution

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

⚠️ Outside diff range comments (1)

🟠 Major · Return after the successful backing read. · pipelineCache.cpp:122

src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp:122
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Return after the successful backing read.

TryReadBacking copies into values without checking the guest mapping's current CPU protection. ProtectGuestHostMemory can change that protection. The following memcpy reads the guest address directly and can fault. Return true after TryReadBacking.

🐛 Suggested fix
 	if (!Libs::LibKernel::Memory::TryReadBacking(address, values.data(), values.size_bytes())) {
 		return false;
 	}
-	std::memcpy(values.data(), reinterpret_cast<const void*>(address), values.size_bytes());
 	return true;

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: b0402b32-3da7-4fdb-9e35-a5953a57a25f

📥 Commits

Reviewing files that changed from the base of the PR and between 652517b99c143732db13cf988738a1c095fadd23 and 998adaae5d306d26203c5e47a2a58e6b48c39d53.

📒 Files selected for processing (16)
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/presentation/videoOut.cpp
  • src/graphics/presentation/window/swapchain.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/libs/ajm/atrac9_decoder.h
  • src/libs/libSaveData.cpp
  • tests/SaveDataMemoryTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 10:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#pullrequestreview-5303370726) · **reviewed** **Actionable comments posted: 6** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><em>🟠 Major</em> · Return after the successful backing read. · <code>pipelineCache.cpp:122</code></summary><blockquote> > > `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp:122` > _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ > > **Return after the successful backing read.** > > `TryReadBacking` copies into `values` without checking the guest mapping's current CPU protection. `ProtectGuestHostMemory` can change that protection. The following `memcpy` reads the guest address directly and can fault. Return `true` after `TryReadBacking`. > > <details> > <summary>🐛 Suggested fix</summary> > > ```diff > if (!Libs::LibKernel::Memory::TryReadBacking(address, values.data(), values.size_bytes())) { > return false; > } > - std::memcpy(values.data(), reinterpret_cast<const void*>(address), values.size_bytes()); > return true; > ``` > > </details> > > <!-- cr-comment:v1:96d480b7735e335b94350d19 --> > > </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**: `b0402b32-3da7-4fdb-9e35-a5953a57a25f` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 652517b99c143732db13cf988738a1c095fadd23 and 998adaae5d306d26203c5e47a2a58e6b48c39d53. </details> <details> <summary>📒 Files selected for processing (16)</summary> * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/presentation/videoOut.cpp` * `src/graphics/presentation/window/swapchain.cpp` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/libs/ajm/atrac9_decoder.h` * `src/libs/libSaveData.cpp` * `tests/SaveDataMemoryTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** 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 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 21:53 UTC · original · reviewed

🧹 Nitpick comments (1)
src/graphics/shader/shader.h (1)

303-303: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert a non-zero semantic value in ShaderVertexMetadataTests.

ShaderReadVertexMetadata copies semantic data from input_semantics_snapshot, but the fixture leaves that array zero-initialized and the test checks only the count. The test can therefore pass when snapshot copying is incorrect.

🧪 Suggested test fix
 	Fixture() {
+		semantic.semantic = 7;
 		offsets.fill(AGC_ILLEGAL_DIRECT_OFFSET);
 		offsets[static_cast<size_t>(AgcDirectResourceType::PtrVertexBufferTable)]     = 2;
 		offsets[static_cast<size_t>(AgcDirectResourceType::PtrVertexAttribDescTable)] = 4;
 		user_data.direct_resource_offset = offsets.data();
 		user_data.direct_resource_count  = static_cast<uint16_t>(offsets.size());
 		mapped.user_data                 = &user_data;
 		mapped.input_semantics           = &semantic;
 		mapped.num_input_semantics       = 1;
+		mapped.input_semantics_snapshot[0] = semantic;
 	}
 };
@@
 	Check(output.vertex_buffer_reg == 2 && output.vertex_attrib_reg == 4 &&
+	          output.input_semantics[0].semantic == semantic.semantic &&
 	          output.input_semantics_count == 1,

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: aea94322-7569-4d67-815d-32a3ed1e3946

📥 Commits

Reviewing files that changed from the base of the PR and between 998adaae5d306d26203c5e47a2a58e6b48c39d53 and 508adebfaec9dd1ccfcca7a1dff98f00429008fd.

📒 Files selected for processing (22)
  • CMakeLists.txt
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/image/imageInfo.h
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp
  • src/graphics/shader/recompiler/frontend/translate/Dispatch.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translator.h
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shader.h
  • 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 21:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#pullrequestreview-5327605606) · **reviewed** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>src/graphics/shader/shader.h (1)</summary><blockquote> `303-303`: _🎯 Functional Correctness_ | _🔵 Trivial_ | _⚡ Quick win_ **Assert a non-zero semantic value in `ShaderVertexMetadataTests`.** `ShaderReadVertexMetadata` copies semantic data from `input_semantics_snapshot`, but the fixture leaves that array zero-initialized and the test checks only the count. The test can therefore pass when snapshot copying is incorrect. <details> <summary>🧪 Suggested test fix</summary> ```diff Fixture() { + semantic.semantic = 7; offsets.fill(AGC_ILLEGAL_DIRECT_OFFSET); offsets[static_cast<size_t>(AgcDirectResourceType::PtrVertexBufferTable)] = 2; offsets[static_cast<size_t>(AgcDirectResourceType::PtrVertexAttribDescTable)] = 4; user_data.direct_resource_offset = offsets.data(); user_data.direct_resource_count = static_cast<uint16_t>(offsets.size()); mapped.user_data = &user_data; mapped.input_semantics = &semantic; mapped.num_input_semantics = 1; + mapped.input_semantics_snapshot[0] = semantic; } }; @@ Check(output.vertex_buffer_reg == 2 && output.vertex_attrib_reg == 4 && + output.input_semantics[0].semantic == semantic.semantic && output.input_semantics_count == 1, ``` </details> <!-- cr-comment:v1:cf910e22a126ebd7b6eadd19 --> </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**: `aea94322-7569-4d67-815d-32a3ed1e3946` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 998adaae5d306d26203c5e47a2a58e6b48c39d53 and 508adebfaec9dd1ccfcca7a1dff98f00429008fd. </details> <details> <summary>📒 Files selected for processing (22)</summary> * `CMakeLists.txt` * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/image/imageInfo.h` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp` * `src/graphics/shader/recompiler/frontend/translate/Dispatch.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translator.h` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shader.h` * `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 -->
Author
Owner

@⁠Nmzik on GitHub · 2026-09-29 18:19 UTC · original

@⁠itsmemac Thanks.
Current status: game is now in-game on main.
Only two things left: visual bug with Miles head and very low performance. I'll take a look later at other/perf commits. Readbacks are not needed. Dont close PR

**@⁠Nmzik** on GitHub · 2026-09-29 18:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#issuecomment-5896055198) @⁠itsmemac Thanks. Current status: game is now in-game on main. Only two things left: visual bug with Miles head and very low performance. I'll take a look later at other/perf commits. Readbacks are not needed. Dont close PR
Author
Owner

@⁠itsmemac on GitHub · 2026-09-29 18:28 UTC · original

@⁠itsmemac Thanks. Current status: game is now in-game on main. Only two things left: visual bug with Miles head and very low performance. I'll take a look later at other/perf commits. Readbacks are not needed. Dont close PR

Thank you for taking your time in reviewing this PR.

**@⁠itsmemac** on GitHub · 2026-09-29 18:28 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#issuecomment-5896196014) > @⁠itsmemac Thanks. Current status: game is now in-game on main. Only two things left: visual bug with Miles head and very low performance. I'll take a look later at other/perf commits. Readbacks are not needed. Dont close PR Thank you for taking your time in reviewing this PR.
Author
Owner

@⁠overlordxrz-source on GitHub · 2026-10-06 00:47 UTC · original

Data point on the red macOS CI leg (Sept 29 run failed in PageManagerTests: fixed low mach_vm_allocate failed): I built this PR's head (290da746) locally (x86_64 macOS no-Qt Release, Apple Silicon Mac) and page_manager_tests passes — all cases green, same as current main on this machine. Main's macOS CI is also green. That points at the CI runner environment (fixed low-address mach_vm_allocate is host-layout-sensitive) rather than this PR's VM changes — none of which touch page mapping paths anyway (this branch is recompiler/PM4/cache/AMPR/diagnostics). Suggest re-running the macOS job; happy to dig further if it fails the same way twice.

**@⁠overlordxrz-source** on GitHub · 2026-10-06 00:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/780#issuecomment-6006820704) Data point on the red macOS CI leg (Sept 29 run failed in `PageManagerTests: fixed low mach_vm_allocate failed`): I built this PR's head (`290da746`) locally (x86_64 macOS no-Qt Release, Apple Silicon Mac) and `page_manager_tests` passes — all cases green, same as current main on this machine. Main's macOS CI is also green. That points at the CI runner environment (fixed low-address `mach_vm_allocate` is host-layout-sensitive) rather than this PR's VM changes — none of which touch page mapping paths anyway (this branch is recompiler/PM4/cache/AMPR/diagnostics). Suggest re-running the macOS job; happy to dig further if it fails the same way twice.
This pull request has changes conflicting with the target branch.
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/graphics/host_gpu/renderer/image/imageInfo.h
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/Tessellation.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/780/head:github-bot/gh-780'
git switch 'github-bot/gh-780'

Merge

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